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