1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "idmap2d/Idmap2Service.h"
18
19 #include <sys/stat.h> // umask
20 #include <sys/types.h> // umask
21
22 #include <cerrno>
23 #include <cstring>
24 #include <filesystem>
25 #include <fstream>
26 #include <limits>
27 #include <memory>
28 #include <ostream>
29 #include <string>
30 #include <utility>
31 #include <vector>
32
33 #include "android-base/macros.h"
34 #include "android-base/stringprintf.h"
35 #include "binder/IPCThreadState.h"
36 #include "idmap2/BinaryStreamVisitor.h"
37 #include "idmap2/FileUtils.h"
38 #include "idmap2/Idmap.h"
39 #include "idmap2/PrettyPrintVisitor.h"
40 #include "idmap2/Result.h"
41 #include "idmap2/SysTrace.h"
42
43 using android::base::StringPrintf;
44 using android::binder::Status;
45 using android::idmap2::BinaryStreamVisitor;
46 using android::idmap2::FabricatedOverlayContainer;
47 using android::idmap2::Idmap;
48 using android::idmap2::IdmapHeader;
49 using android::idmap2::OverlayResourceContainer;
50 using android::idmap2::PrettyPrintVisitor;
51 using android::idmap2::TargetResourceContainer;
52 using android::idmap2::utils::kIdmapCacheDir;
53 using android::idmap2::utils::kIdmapFilePermissionMask;
54 using android::idmap2::utils::RandomStringForPath;
55 using android::idmap2::utils::UidHasWriteAccessToPath;
56
57 using PolicyBitmask = android::ResTable_overlayable_policy_header::PolicyBitmask;
58
59 namespace {
60
61 constexpr const char* kFrameworkPath = "/system/framework/framework-res.apk";
62
ok()63 Status ok() {
64 return Status::ok();
65 }
66
error(const std::string & msg)67 Status error(const std::string& msg) {
68 LOG(ERROR) << msg;
69 return Status::fromExceptionCode(Status::EX_NONE, msg.c_str());
70 }
71
ConvertAidlArgToPolicyBitmask(int32_t arg)72 PolicyBitmask ConvertAidlArgToPolicyBitmask(int32_t arg) {
73 return static_cast<PolicyBitmask>(arg);
74 }
75
76 } // namespace
77
78 namespace android::os {
79
getIdmapPath(const std::string & overlay_path,int32_t user_id ATTRIBUTE_UNUSED,std::string * _aidl_return)80 Status Idmap2Service::getIdmapPath(const std::string& overlay_path,
81 int32_t user_id ATTRIBUTE_UNUSED, std::string* _aidl_return) {
82 assert(_aidl_return);
83 SYSTRACE << "Idmap2Service::getIdmapPath " << overlay_path;
84 *_aidl_return = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
85 return ok();
86 }
87
removeIdmap(const std::string & overlay_path,int32_t user_id ATTRIBUTE_UNUSED,bool * _aidl_return)88 Status Idmap2Service::removeIdmap(const std::string& overlay_path, int32_t user_id ATTRIBUTE_UNUSED,
89 bool* _aidl_return) {
90 assert(_aidl_return);
91 SYSTRACE << "Idmap2Service::removeIdmap " << overlay_path;
92 const uid_t uid = IPCThreadState::self()->getCallingUid();
93 const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
94 if (!UidHasWriteAccessToPath(uid, idmap_path)) {
95 *_aidl_return = false;
96 return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
97 idmap_path.c_str(), uid));
98 }
99 if (unlink(idmap_path.c_str()) != 0) {
100 *_aidl_return = false;
101 return error("failed to unlink " + idmap_path + ": " + strerror(errno));
102 }
103 *_aidl_return = true;
104 return ok();
105 }
106
verifyIdmap(const std::string & target_path,const std::string & overlay_path,const std::string & overlay_name,int32_t fulfilled_policies,bool enforce_overlayable,int32_t user_id ATTRIBUTE_UNUSED,bool * _aidl_return)107 Status Idmap2Service::verifyIdmap(const std::string& target_path, const std::string& overlay_path,
108 const std::string& overlay_name, int32_t fulfilled_policies,
109 bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
110 bool* _aidl_return) {
111 SYSTRACE << "Idmap2Service::verifyIdmap " << overlay_path;
112 assert(_aidl_return);
113
114 const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
115 std::ifstream fin(idmap_path);
116 const std::unique_ptr<const IdmapHeader> header = IdmapHeader::FromBinaryStream(fin);
117 fin.close();
118 if (!header) {
119 *_aidl_return = false;
120 LOG(WARNING) << "failed to parse idmap header of '" << idmap_path << "'";
121 return ok();
122 }
123
124 const auto target = GetTargetContainer(target_path);
125 if (!target) {
126 *_aidl_return = false;
127 LOG(WARNING) << "failed to load target '" << target_path << "'";
128 return ok();
129 }
130
131 const auto overlay = OverlayResourceContainer::FromPath(overlay_path);
132 if (!overlay) {
133 *_aidl_return = false;
134 LOG(WARNING) << "failed to load overlay '" << overlay_path << "'";
135 return ok();
136 }
137
138 auto up_to_date =
139 header->IsUpToDate(*GetPointer(*target), **overlay, overlay_name,
140 ConvertAidlArgToPolicyBitmask(fulfilled_policies), enforce_overlayable);
141
142 *_aidl_return = static_cast<bool>(up_to_date);
143 if (!up_to_date) {
144 LOG(WARNING) << "idmap '" << idmap_path
145 << "' not up to date : " << up_to_date.GetErrorMessage();
146 }
147 return ok();
148 }
149
createIdmap(const std::string & target_path,const std::string & overlay_path,const std::string & overlay_name,int32_t fulfilled_policies,bool enforce_overlayable,int32_t user_id ATTRIBUTE_UNUSED,std::optional<std::string> * _aidl_return)150 Status Idmap2Service::createIdmap(const std::string& target_path, const std::string& overlay_path,
151 const std::string& overlay_name, int32_t fulfilled_policies,
152 bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
153 std::optional<std::string>* _aidl_return) {
154 assert(_aidl_return);
155 SYSTRACE << "Idmap2Service::createIdmap " << target_path << " " << overlay_path;
156 _aidl_return->reset();
157
158 const PolicyBitmask policy_bitmask = ConvertAidlArgToPolicyBitmask(fulfilled_policies);
159
160 const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
161 const uid_t uid = IPCThreadState::self()->getCallingUid();
162 if (!UidHasWriteAccessToPath(uid, idmap_path)) {
163 return error(base::StringPrintf("will not write to %s: calling uid %d lacks write accesss",
164 idmap_path.c_str(), uid));
165 }
166
167 // idmap files are mapped with mmap in libandroidfw. Deleting and recreating the idmap guarantees
168 // that existing memory maps will continue to be valid and unaffected. The file must be deleted
169 // before attempting to create the idmap, so that if idmap creation fails, the overlay will no
170 // longer be usable.
171 unlink(idmap_path.c_str());
172
173 const auto target = GetTargetContainer(target_path);
174 if (!target) {
175 return error("failed to load target '%s'" + target_path);
176 }
177
178 const auto overlay = OverlayResourceContainer::FromPath(overlay_path);
179 if (!overlay) {
180 return error("failed to load apk overlay '%s'" + overlay_path);
181 }
182
183 const auto idmap = Idmap::FromContainers(*GetPointer(*target), **overlay, overlay_name,
184 policy_bitmask, enforce_overlayable);
185 if (!idmap) {
186 return error(idmap.GetErrorMessage());
187 }
188
189 umask(kIdmapFilePermissionMask);
190 std::ofstream fout(idmap_path);
191 if (fout.fail()) {
192 return error("failed to open idmap path " + idmap_path);
193 }
194
195 BinaryStreamVisitor visitor(fout);
196 (*idmap)->accept(&visitor);
197 fout.close();
198 if (fout.fail()) {
199 unlink(idmap_path.c_str());
200 return error("failed to write to idmap path " + idmap_path);
201 }
202
203 *_aidl_return = idmap_path;
204 return ok();
205 }
206
GetTargetContainer(const std::string & target_path)207 idmap2::Result<Idmap2Service::TargetResourceContainerPtr> Idmap2Service::GetTargetContainer(
208 const std::string& target_path) {
209 if (target_path == kFrameworkPath) {
210 if (framework_apk_cache_ == nullptr) {
211 // Initialize the framework APK cache.
212 auto target = TargetResourceContainer::FromPath(target_path);
213 if (!target) {
214 return target.GetError();
215 }
216 framework_apk_cache_ = std::move(*target);
217 }
218 return {framework_apk_cache_.get()};
219 }
220
221 auto target = TargetResourceContainer::FromPath(target_path);
222 if (!target) {
223 return target.GetError();
224 }
225 return {std::move(*target)};
226 }
227
createFabricatedOverlay(const os::FabricatedOverlayInternal & overlay,std::optional<os::FabricatedOverlayInfo> * _aidl_return)228 Status Idmap2Service::createFabricatedOverlay(
229 const os::FabricatedOverlayInternal& overlay,
230 std::optional<os::FabricatedOverlayInfo>* _aidl_return) {
231 idmap2::FabricatedOverlay::Builder builder(overlay.packageName, overlay.overlayName,
232 overlay.targetPackageName);
233 if (!overlay.targetOverlayable.empty()) {
234 builder.SetOverlayable(overlay.targetOverlayable);
235 }
236
237 for (const auto& res : overlay.entries) {
238 builder.SetResourceValue(res.resourceName, res.dataType, res.data);
239 }
240
241 // Generate the file path of the fabricated overlay and ensure it does not collide with an
242 // existing path. Re-registering a fabricated overlay will always result in an updated path.
243 std::string path;
244 std::string file_name;
245 do {
246 constexpr size_t kSuffixLength = 4;
247 const std::string random_suffix = RandomStringForPath(kSuffixLength);
248 file_name = StringPrintf("%s-%s-%s.frro", overlay.packageName.c_str(),
249 overlay.overlayName.c_str(), random_suffix.c_str());
250 path = StringPrintf("%s/%s", kIdmapCacheDir, file_name.c_str());
251
252 // Invoking std::filesystem::exists with a file name greater than 255 characters will cause this
253 // process to abort since the name exceeds the maximum file name size.
254 const size_t kMaxFileNameLength = 255;
255 if (file_name.size() > kMaxFileNameLength) {
256 return error(
257 base::StringPrintf("fabricated overlay file name '%s' longer than %zu characters",
258 file_name.c_str(), kMaxFileNameLength));
259 }
260 } while (std::filesystem::exists(path));
261
262 const uid_t uid = IPCThreadState::self()->getCallingUid();
263 if (!UidHasWriteAccessToPath(uid, path)) {
264 return error(base::StringPrintf("will not write to %s: calling uid %d lacks write access",
265 path.c_str(), uid));
266 }
267
268 const auto frro = builder.Build();
269 if (!frro) {
270 return error(StringPrintf("failed to serialize '%s:%s': %s", overlay.packageName.c_str(),
271 overlay.overlayName.c_str(), frro.GetErrorMessage().c_str()));
272 }
273 // Persist the fabricated overlay.
274 umask(kIdmapFilePermissionMask);
275 std::ofstream fout(path);
276 if (fout.fail()) {
277 return error("failed to open frro path " + path);
278 }
279 auto result = frro->ToBinaryStream(fout);
280 if (!result) {
281 unlink(path.c_str());
282 return error("failed to write to frro path " + path + ": " + result.GetErrorMessage());
283 }
284 if (fout.fail()) {
285 unlink(path.c_str());
286 return error("failed to write to frro path " + path);
287 }
288
289 os::FabricatedOverlayInfo out_info;
290 out_info.packageName = overlay.packageName;
291 out_info.overlayName = overlay.overlayName;
292 out_info.targetPackageName = overlay.targetPackageName;
293 out_info.targetOverlayable = overlay.targetOverlayable;
294 out_info.path = path;
295 *_aidl_return = out_info;
296 return ok();
297 }
298
acquireFabricatedOverlayIterator(int32_t * _aidl_return)299 Status Idmap2Service::acquireFabricatedOverlayIterator(int32_t* _aidl_return) {
300 std::lock_guard l(frro_iter_mutex_);
301 if (frro_iter_.has_value()) {
302 LOG(WARNING) << "active ffro iterator was not previously released";
303 }
304 frro_iter_ = std::filesystem::directory_iterator(kIdmapCacheDir);
305 if (frro_iter_id_ == std::numeric_limits<int32_t>::max()) {
306 frro_iter_id_ = 0;
307 } else {
308 ++frro_iter_id_;
309 }
310 *_aidl_return = frro_iter_id_;
311 return ok();
312 }
313
releaseFabricatedOverlayIterator(int32_t iteratorId)314 Status Idmap2Service::releaseFabricatedOverlayIterator(int32_t iteratorId) {
315 std::lock_guard l(frro_iter_mutex_);
316 if (!frro_iter_.has_value()) {
317 LOG(WARNING) << "no active ffro iterator to release";
318 } else if (frro_iter_id_ != iteratorId) {
319 LOG(WARNING) << "incorrect iterator id in a call to release";
320 } else {
321 frro_iter_.reset();
322 }
323 return ok();
324 }
325
nextFabricatedOverlayInfos(int32_t iteratorId,std::vector<os::FabricatedOverlayInfo> * _aidl_return)326 Status Idmap2Service::nextFabricatedOverlayInfos(int32_t iteratorId,
327 std::vector<os::FabricatedOverlayInfo>* _aidl_return) {
328 std::lock_guard l(frro_iter_mutex_);
329
330 constexpr size_t kMaxEntryCount = 100;
331 if (!frro_iter_.has_value()) {
332 return error("no active frro iterator");
333 } else if (frro_iter_id_ != iteratorId) {
334 return error("incorrect iterator id in a call to next");
335 }
336
337 size_t count = 0;
338 auto& entry_iter = *frro_iter_;
339 auto entry_iter_end = end(*frro_iter_);
340 for (; entry_iter != entry_iter_end && count < kMaxEntryCount; ++entry_iter) {
341 auto& entry = *entry_iter;
342 if (!entry.is_regular_file() || !android::IsFabricatedOverlay(entry.path().native())) {
343 continue;
344 }
345
346 const auto overlay = FabricatedOverlayContainer::FromPath(entry.path().native());
347 if (!overlay) {
348 LOG(WARNING) << "Failed to open '" << entry.path() << "': " << overlay.GetErrorMessage();
349 continue;
350 }
351
352 auto info = (*overlay)->GetManifestInfo();
353 os::FabricatedOverlayInfo out_info;
354 out_info.packageName = std::move(info.package_name);
355 out_info.overlayName = std::move(info.name);
356 out_info.targetPackageName = std::move(info.target_package);
357 out_info.targetOverlayable = std::move(info.target_name);
358 out_info.path = entry.path();
359 _aidl_return->emplace_back(std::move(out_info));
360 count++;
361 }
362 return ok();
363 }
364
deleteFabricatedOverlay(const std::string & overlay_path,bool * _aidl_return)365 binder::Status Idmap2Service::deleteFabricatedOverlay(const std::string& overlay_path,
366 bool* _aidl_return) {
367 SYSTRACE << "Idmap2Service::deleteFabricatedOverlay " << overlay_path;
368 const uid_t uid = IPCThreadState::self()->getCallingUid();
369
370 if (!UidHasWriteAccessToPath(uid, overlay_path)) {
371 *_aidl_return = false;
372 return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
373 overlay_path.c_str(), uid));
374 }
375
376 const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
377 if (!UidHasWriteAccessToPath(uid, idmap_path)) {
378 *_aidl_return = false;
379 return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
380 idmap_path.c_str(), uid));
381 }
382
383 if (unlink(overlay_path.c_str()) != 0) {
384 *_aidl_return = false;
385 return error("failed to unlink " + overlay_path + ": " + strerror(errno));
386 }
387
388 if (unlink(idmap_path.c_str()) != 0) {
389 *_aidl_return = false;
390 return error("failed to unlink " + idmap_path + ": " + strerror(errno));
391 }
392
393 *_aidl_return = true;
394 return ok();
395 }
396
dumpIdmap(const std::string & overlay_path,std::string * _aidl_return)397 binder::Status Idmap2Service::dumpIdmap(const std::string& overlay_path,
398 std::string* _aidl_return) {
399 assert(_aidl_return);
400
401 const auto idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
402 std::ifstream fin(idmap_path);
403 const auto idmap = Idmap::FromBinaryStream(fin);
404 fin.close();
405 if (!idmap) {
406 return error(idmap.GetErrorMessage());
407 }
408
409 std::stringstream stream;
410 PrettyPrintVisitor visitor(stream);
411 (*idmap)->accept(&visitor);
412 *_aidl_return = stream.str();
413
414 return ok();
415 }
416
417 } // namespace android::os
418