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 #include <fcntl.h>
43
44 using android::base::StringPrintf;
45 using android::binder::Status;
46 using android::idmap2::BinaryStreamVisitor;
47 using android::idmap2::FabricatedOverlayContainer;
48 using android::idmap2::Idmap;
49 using android::idmap2::IdmapConstraint;
50 using android::idmap2::IdmapConstraints;
51 using android::idmap2::IdmapHeader;
52 using android::idmap2::OverlayResourceContainer;
53 using android::idmap2::PrettyPrintVisitor;
54 using android::idmap2::TargetResourceContainer;
55 using android::idmap2::utils::kIdmapCacheDir;
56 using android::idmap2::utils::kIdmapFilePermissionMask;
57 using android::idmap2::utils::RandomStringForPath;
58 using android::idmap2::utils::UidHasWriteAccessToPath;
59
60 using PolicyBitmask = android::ResTable_overlayable_policy_header::PolicyBitmask;
61
62 namespace {
63
64 constexpr std::string_view kFrameworkPath = "/system/framework/framework-res.apk";
65
ok()66 Status ok() {
67 return Status::ok();
68 }
69
error(const std::string & msg)70 Status error(const std::string& msg) {
71 LOG(ERROR) << msg;
72 return Status::fromExceptionCode(Status::EX_NONE, msg.c_str());
73 }
74
ConvertAidlArgToPolicyBitmask(int32_t arg)75 PolicyBitmask ConvertAidlArgToPolicyBitmask(int32_t arg) {
76 return static_cast<PolicyBitmask>(arg);
77 }
78
ConvertAidlConstraintsToIdmapConstraints(const std::vector<android::os::OverlayConstraint> & constraints)79 std::unique_ptr<const IdmapConstraints> ConvertAidlConstraintsToIdmapConstraints(
80 const std::vector<android::os::OverlayConstraint>& constraints) {
81 auto idmapConstraints = std::make_unique<IdmapConstraints>();
82 for (const auto& constraint : constraints) {
83 IdmapConstraint idmapConstraint{};
84 idmapConstraint.constraint_type = constraint.type;
85 idmapConstraint.constraint_value = constraint.value;
86 idmapConstraints->constraints.insert(idmapConstraint);
87 }
88 return idmapConstraints;
89 }
90
91 } // namespace
92
93 namespace android::os {
94
95 template <typename T>
GetPointer(const OwningPtr<T> & ptr)96 const T* Idmap2Service::GetPointer(const OwningPtr<T>& ptr) {
97 return std::visit([](auto&& ptr) { return ptr.get(); }, ptr);
98 }
99
getIdmapPath(const std::string & overlay_path,int32_t user_id ATTRIBUTE_UNUSED,std::string * _aidl_return)100 Status Idmap2Service::getIdmapPath(const std::string& overlay_path,
101 int32_t user_id ATTRIBUTE_UNUSED, std::string* _aidl_return) {
102 assert(_aidl_return);
103 SYSTRACE << "Idmap2Service::getIdmapPath " << overlay_path;
104 *_aidl_return = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
105 return ok();
106 }
107
removeIdmap(const std::string & overlay_path,int32_t user_id ATTRIBUTE_UNUSED,bool * _aidl_return)108 Status Idmap2Service::removeIdmap(const std::string& overlay_path, int32_t user_id ATTRIBUTE_UNUSED,
109 bool* _aidl_return) {
110 assert(_aidl_return);
111 SYSTRACE << "Idmap2Service::removeIdmap " << overlay_path;
112 const uid_t uid = IPCThreadState::self()->getCallingUid();
113 const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
114 if (!UidHasWriteAccessToPath(uid, idmap_path)) {
115 *_aidl_return = false;
116 return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
117 idmap_path.c_str(), uid));
118 }
119 if (unlink(idmap_path.c_str()) != 0) {
120 *_aidl_return = false;
121 return error("failed to unlink " + idmap_path + ": " + strerror(errno));
122 }
123 *_aidl_return = true;
124 return ok();
125 }
126
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,const std::vector<os::OverlayConstraint> & constraints,bool * _aidl_return)127 Status Idmap2Service::verifyIdmap(const std::string& target_path, const std::string& overlay_path,
128 const std::string& overlay_name, int32_t fulfilled_policies,
129 bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
130 const std::vector<os::OverlayConstraint>& constraints,
131 bool* _aidl_return) {
132 SYSTRACE << "Idmap2Service::verifyIdmap " << overlay_path;
133 assert(_aidl_return);
134
135 const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
136 std::ifstream fin(idmap_path);
137 const std::unique_ptr<const IdmapHeader> header = IdmapHeader::FromBinaryStream(fin);
138 const std::unique_ptr<const IdmapConstraints> oldConstraints =
139 IdmapConstraints::FromBinaryStream(fin);
140 fin.close();
141 if (!header) {
142 *_aidl_return = false;
143 LOG(WARNING) << "failed to parse idmap header of '" << idmap_path << "'";
144 return ok();
145 }
146 if (!oldConstraints) {
147 *_aidl_return = false;
148 LOG(WARNING) << "failed to parse idmap constraints of '" << idmap_path << "'";
149 return ok();
150 }
151
152 const auto target = GetTargetContainer(target_path);
153 if (!target) {
154 *_aidl_return = false;
155 LOG(WARNING) << "failed to load target '" << target_path << "'";
156 return ok();
157 }
158
159 const auto overlay = OverlayResourceContainer::FromPath(overlay_path);
160 if (!overlay) {
161 *_aidl_return = false;
162 LOG(WARNING) << "failed to load overlay '" << overlay_path << "'";
163 return ok();
164 }
165
166 auto up_to_date =
167 header->IsUpToDate(*GetPointer(*target), **overlay, overlay_name,
168 ConvertAidlArgToPolicyBitmask(fulfilled_policies), enforce_overlayable);
169
170 std::unique_ptr<const IdmapConstraints> newConstraints =
171 ConvertAidlConstraintsToIdmapConstraints(constraints);
172
173 *_aidl_return = static_cast<bool>(up_to_date && (*oldConstraints == *newConstraints));
174 if (!up_to_date) {
175 LOG(WARNING) << "idmap '" << idmap_path
176 << "' not up to date : " << up_to_date.GetErrorMessage();
177 }
178 return ok();
179 }
180
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,const std::vector<os::OverlayConstraint> & constraints,std::optional<std::string> * _aidl_return)181 Status Idmap2Service::createIdmap(const std::string& target_path, const std::string& overlay_path,
182 const std::string& overlay_name, int32_t fulfilled_policies,
183 bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
184 const std::vector<os::OverlayConstraint>& constraints,
185 std::optional<std::string>* _aidl_return) {
186 assert(_aidl_return);
187 SYSTRACE << "Idmap2Service::createIdmap " << target_path << " " << overlay_path;
188 _aidl_return->reset();
189
190 const PolicyBitmask policy_bitmask = ConvertAidlArgToPolicyBitmask(fulfilled_policies);
191
192 const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
193 const uid_t uid = IPCThreadState::self()->getCallingUid();
194 if (!UidHasWriteAccessToPath(uid, idmap_path)) {
195 return error(base::StringPrintf("will not write to %s: calling uid %d lacks write accesss",
196 idmap_path.c_str(), uid));
197 }
198
199 // idmap files are mapped with mmap in libandroidfw. Deleting and recreating the idmap guarantees
200 // that existing memory maps will continue to be valid and unaffected. The file must be deleted
201 // before attempting to create the idmap, so that if idmap creation fails, the overlay will no
202 // longer be usable.
203 unlink(idmap_path.c_str());
204
205 const auto target = GetTargetContainer(target_path);
206 if (!target) {
207 return error("failed to load target '%s'" + target_path);
208 }
209
210 const auto overlay = OverlayResourceContainer::FromPath(overlay_path);
211 if (!overlay) {
212 return error("failed to load apk overlay '%s'" + overlay_path);
213 }
214
215 std::unique_ptr<const IdmapConstraints> idmapConstraints =
216 ConvertAidlConstraintsToIdmapConstraints(constraints);
217 const auto idmap = Idmap::FromContainers(*GetPointer(*target), **overlay, overlay_name,
218 policy_bitmask, enforce_overlayable,
219 std::move(idmapConstraints));
220 if (!idmap) {
221 return error(idmap.GetErrorMessage());
222 }
223
224 umask(kIdmapFilePermissionMask);
225 std::ofstream fout(idmap_path);
226 if (fout.fail()) {
227 return error("failed to open idmap path " + idmap_path);
228 }
229
230 BinaryStreamVisitor visitor(fout);
231 (*idmap)->accept(&visitor);
232 fout.close();
233 if (fout.fail()) {
234 unlink(idmap_path.c_str());
235 return error("failed to write to idmap path " + idmap_path);
236 }
237
238 *_aidl_return = idmap_path;
239 return ok();
240 }
241
GetTargetContainer(const std::string & target_path)242 idmap2::Result<Idmap2Service::TargetResourceContainerPtr> Idmap2Service::GetTargetContainer(
243 const std::string& target_path) {
244 const bool is_framework = target_path == kFrameworkPath;
245 bool use_cache;
246 struct stat st = {};
247 if (is_framework || !::stat(target_path.c_str(), &st)) {
248 use_cache = true;
249 } else {
250 LOG(WARNING) << "failed to stat target path '" << target_path << "' for the cache";
251 use_cache = false;
252 }
253
254 if (use_cache) {
255 std::lock_guard lock(container_cache_mutex_);
256 if (auto cache_it = container_cache_.find(target_path); cache_it != container_cache_.end()) {
257 const auto& item = cache_it->second;
258 if (is_framework ||
259 (item.dev == st.st_dev && item.inode == st.st_ino && item.size == st.st_size
260 && item.mtime.tv_sec == st.st_mtim.tv_sec && item.mtime.tv_nsec == st.st_mtim.tv_nsec)) {
261 return {item.apk};
262 }
263 container_cache_.erase(cache_it);
264 }
265 }
266
267 auto target = TargetResourceContainer::FromPath(target_path);
268 if (!target) {
269 return target.GetError();
270 }
271 if (!use_cache) {
272 return {std::move(*target)};
273 }
274
275 auto res = std::shared_ptr(std::move(*target));
276 std::lock_guard lock(container_cache_mutex_);
277 container_cache_.emplace(target_path, CachedContainer {
278 .dev = dev_t(st.st_dev),
279 .inode = ino_t(st.st_ino),
280 .size = st.st_size,
281 .mtime = st.st_mtim,
282 .apk = res
283 });
284 return {res};
285 }
286
createFabricatedOverlay(const os::FabricatedOverlayInternal & overlay,std::optional<os::FabricatedOverlayInfo> * _aidl_return)287 Status Idmap2Service::createFabricatedOverlay(
288 const os::FabricatedOverlayInternal& overlay,
289 std::optional<os::FabricatedOverlayInfo>* _aidl_return) {
290 idmap2::FabricatedOverlay::Builder builder(overlay.packageName, overlay.overlayName,
291 overlay.targetPackageName);
292 if (!overlay.targetOverlayable.empty()) {
293 builder.SetOverlayable(overlay.targetOverlayable);
294 }
295
296 for (const auto& res : overlay.entries) {
297 if (res.dataType == Res_value::TYPE_STRING) {
298 builder.SetResourceValue(res.resourceName, res.dataType, res.stringData.value(),
299 res.configuration.value_or(std::string()));
300 } else if (res.binaryData.has_value()) {
301 builder.SetResourceValue(res.resourceName, res.binaryData->get(),
302 res.binaryDataOffset, res.binaryDataSize,
303 res.configuration.value_or(std::string()),
304 res.isNinePatch);
305 } else {
306 builder.SetResourceValue(res.resourceName, res.dataType, res.data,
307 res.configuration.value_or(std::string()));
308 }
309 }
310
311 // Generate the file path of the fabricated overlay and ensure it does not collide with an
312 // existing path. Re-registering a fabricated overlay will always result in an updated path.
313 std::string path;
314 std::string file_name;
315 do {
316 constexpr size_t kSuffixLength = 4;
317 const std::string random_suffix = RandomStringForPath(kSuffixLength);
318 file_name = StringPrintf("%s-%s-%s.frro", overlay.packageName.c_str(),
319 overlay.overlayName.c_str(), random_suffix.c_str());
320 path = StringPrintf("%s/%s", kIdmapCacheDir.data(), file_name.c_str());
321
322 // Invoking std::filesystem::exists with a file name greater than 255 characters will cause this
323 // process to abort since the name exceeds the maximum file name size.
324 const size_t kMaxFileNameLength = 255;
325 if (file_name.size() > kMaxFileNameLength) {
326 return error(
327 base::StringPrintf("fabricated overlay file name '%s' longer than %zu characters",
328 file_name.c_str(), kMaxFileNameLength));
329 }
330 } while (std::filesystem::exists(path));
331 builder.setFrroPath(path);
332
333 const uid_t uid = IPCThreadState::self()->getCallingUid();
334 if (!UidHasWriteAccessToPath(uid, path)) {
335 return error(base::StringPrintf("will not write to %s: calling uid %d lacks write access",
336 path.c_str(), uid));
337 }
338
339 const auto frro = builder.Build();
340 if (!frro) {
341 return error(StringPrintf("failed to serialize '%s:%s': %s", overlay.packageName.c_str(),
342 overlay.overlayName.c_str(), frro.GetErrorMessage().c_str()));
343 }
344 // Persist the fabricated overlay.
345 umask(kIdmapFilePermissionMask);
346 std::ofstream fout(path);
347 if (fout.fail()) {
348 return error("failed to open frro path " + path);
349 }
350 auto result = frro->ToBinaryStream(fout);
351 if (!result) {
352 unlink(path.c_str());
353 return error("failed to write to frro path " + path + ": " + result.GetErrorMessage());
354 }
355 if (fout.fail()) {
356 unlink(path.c_str());
357 return error("failed to write to frro path " + path);
358 }
359
360 os::FabricatedOverlayInfo out_info;
361 out_info.packageName = overlay.packageName;
362 out_info.overlayName = overlay.overlayName;
363 out_info.targetPackageName = overlay.targetPackageName;
364 out_info.targetOverlayable = overlay.targetOverlayable;
365 out_info.path = path;
366 *_aidl_return = out_info;
367 return ok();
368 }
369
acquireFabricatedOverlayIterator(int32_t * _aidl_return)370 Status Idmap2Service::acquireFabricatedOverlayIterator(int32_t* _aidl_return) {
371 std::lock_guard l(frro_iter_mutex_);
372 if (frro_iter_.has_value()) {
373 LOG(WARNING) << "active ffro iterator was not previously released";
374 }
375 frro_iter_ = std::filesystem::directory_iterator(kIdmapCacheDir);
376 if (frro_iter_id_ == std::numeric_limits<int32_t>::max()) {
377 frro_iter_id_ = 0;
378 } else {
379 ++frro_iter_id_;
380 }
381 *_aidl_return = frro_iter_id_;
382 return ok();
383 }
384
releaseFabricatedOverlayIterator(int32_t iteratorId)385 Status Idmap2Service::releaseFabricatedOverlayIterator(int32_t iteratorId) {
386 std::lock_guard l(frro_iter_mutex_);
387 if (!frro_iter_.has_value()) {
388 LOG(WARNING) << "no active ffro iterator to release";
389 } else if (frro_iter_id_ != iteratorId) {
390 LOG(WARNING) << "incorrect iterator id in a call to release";
391 } else {
392 frro_iter_.reset();
393 }
394 return ok();
395 }
396
nextFabricatedOverlayInfos(int32_t iteratorId,std::vector<os::FabricatedOverlayInfo> * _aidl_return)397 Status Idmap2Service::nextFabricatedOverlayInfos(int32_t iteratorId,
398 std::vector<os::FabricatedOverlayInfo>* _aidl_return) {
399 std::lock_guard l(frro_iter_mutex_);
400
401 constexpr size_t kMaxEntryCount = 100;
402 if (!frro_iter_.has_value()) {
403 return error("no active frro iterator");
404 } else if (frro_iter_id_ != iteratorId) {
405 return error("incorrect iterator id in a call to next");
406 }
407
408 size_t count = 0;
409 auto& entry_iter = *frro_iter_;
410 auto entry_iter_end = end(*frro_iter_);
411 for (; entry_iter != entry_iter_end && count < kMaxEntryCount; ++entry_iter) {
412 auto& entry = *entry_iter;
413 if (!entry.is_regular_file() || !android::IsFabricatedOverlay(entry.path().native())) {
414 continue;
415 }
416
417 const auto overlay = FabricatedOverlayContainer::FromPath(entry.path().native());
418 if (!overlay) {
419 LOG(WARNING) << "Failed to open '" << entry.path() << "': " << overlay.GetErrorMessage();
420 continue;
421 }
422
423 auto info = (*overlay)->GetManifestInfo();
424 os::FabricatedOverlayInfo out_info;
425 out_info.packageName = std::move(info.package_name);
426 out_info.overlayName = std::move(info.name);
427 out_info.targetPackageName = std::move(info.target_package);
428 out_info.targetOverlayable = std::move(info.target_name);
429 out_info.path = entry.path();
430 _aidl_return->emplace_back(std::move(out_info));
431 count++;
432 }
433 return ok();
434 }
435
deleteFabricatedOverlay(const std::string & overlay_path,bool * _aidl_return)436 binder::Status Idmap2Service::deleteFabricatedOverlay(const std::string& overlay_path,
437 bool* _aidl_return) {
438 SYSTRACE << "Idmap2Service::deleteFabricatedOverlay " << overlay_path;
439 const uid_t uid = IPCThreadState::self()->getCallingUid();
440
441 if (!UidHasWriteAccessToPath(uid, overlay_path)) {
442 *_aidl_return = false;
443 return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
444 overlay_path.c_str(), uid));
445 }
446
447 const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
448 if (!UidHasWriteAccessToPath(uid, idmap_path)) {
449 *_aidl_return = false;
450 return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
451 idmap_path.c_str(), uid));
452 }
453
454 if (unlink(overlay_path.c_str()) != 0) {
455 *_aidl_return = false;
456 return error("failed to unlink " + overlay_path + ": " + strerror(errno));
457 }
458
459 if (unlink(idmap_path.c_str()) != 0) {
460 *_aidl_return = false;
461 return error("failed to unlink " + idmap_path + ": " + strerror(errno));
462 }
463
464 *_aidl_return = true;
465 return ok();
466 }
467
dumpIdmap(const std::string & overlay_path,std::string * _aidl_return)468 binder::Status Idmap2Service::dumpIdmap(const std::string& overlay_path,
469 std::string* _aidl_return) {
470 assert(_aidl_return);
471
472 const auto idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_path);
473 std::ifstream fin(idmap_path);
474 const auto idmap = Idmap::FromBinaryStream(fin);
475 fin.close();
476 if (!idmap) {
477 return error(idmap.GetErrorMessage());
478 }
479
480 std::stringstream stream;
481 PrettyPrintVisitor visitor(stream);
482 (*idmap)->accept(&visitor);
483 *_aidl_return = stream.str();
484
485 return ok();
486 }
487
488 } // namespace android::os
489