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 #include <unistd.h>
22 
23 #include <cerrno>
24 #include <cstring>
25 #include <fstream>
26 #include <memory>
27 #include <ostream>
28 #include <string>
29 
30 #include "android-base/macros.h"
31 #include "android-base/stringprintf.h"
32 #include "binder/IPCThreadState.h"
33 #include "idmap2/BinaryStreamVisitor.h"
34 #include "idmap2/FileUtils.h"
35 #include "idmap2/Idmap.h"
36 #include "idmap2/Result.h"
37 #include "idmap2/SysTrace.h"
38 #include "idmap2/ZipFile.h"
39 #include "utils/String8.h"
40 
41 using android::IPCThreadState;
42 using android::base::StringPrintf;
43 using android::binder::Status;
44 using android::idmap2::BinaryStreamVisitor;
45 using android::idmap2::GetPackageCrc;
46 using android::idmap2::Idmap;
47 using android::idmap2::IdmapHeader;
48 using android::idmap2::ZipFile;
49 using android::idmap2::utils::kIdmapCacheDir;
50 using android::idmap2::utils::kIdmapFilePermissionMask;
51 using android::idmap2::utils::UidHasWriteAccessToPath;
52 
53 using PolicyBitmask = android::ResTable_overlayable_policy_header::PolicyBitmask;
54 
55 namespace {
56 
57 constexpr const char* kFrameworkPath = "/system/framework/framework-res.apk";
58 
ok()59 Status ok() {
60   return Status::ok();
61 }
62 
error(const std::string & msg)63 Status error(const std::string& msg) {
64   LOG(ERROR) << msg;
65   return Status::fromExceptionCode(Status::EX_NONE, msg.c_str());
66 }
67 
ConvertAidlArgToPolicyBitmask(int32_t arg)68 PolicyBitmask ConvertAidlArgToPolicyBitmask(int32_t arg) {
69   return static_cast<PolicyBitmask>(arg);
70 }
71 
GetCrc(const std::string & apk_path,uint32_t * out_crc)72 Status GetCrc(const std::string& apk_path, uint32_t* out_crc) {
73   const auto zip = ZipFile::Open(apk_path);
74   if (!zip) {
75     return error(StringPrintf("failed to open apk %s", apk_path.c_str()));
76   }
77 
78   const auto crc = GetPackageCrc(*zip);
79   if (!crc) {
80     return error(crc.GetErrorMessage());
81   }
82 
83   *out_crc = *crc;
84   return ok();
85 }
86 
87 }  // namespace
88 
89 namespace android::os {
90 
getIdmapPath(const std::string & overlay_apk_path,int32_t user_id ATTRIBUTE_UNUSED,std::string * _aidl_return)91 Status Idmap2Service::getIdmapPath(const std::string& overlay_apk_path,
92                                    int32_t user_id ATTRIBUTE_UNUSED, std::string* _aidl_return) {
93   assert(_aidl_return);
94   SYSTRACE << "Idmap2Service::getIdmapPath " << overlay_apk_path;
95   *_aidl_return = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_apk_path);
96   return ok();
97 }
98 
removeIdmap(const std::string & overlay_apk_path,int32_t user_id ATTRIBUTE_UNUSED,bool * _aidl_return)99 Status Idmap2Service::removeIdmap(const std::string& overlay_apk_path,
100                                   int32_t user_id ATTRIBUTE_UNUSED, bool* _aidl_return) {
101   assert(_aidl_return);
102   SYSTRACE << "Idmap2Service::removeIdmap " << overlay_apk_path;
103   const uid_t uid = IPCThreadState::self()->getCallingUid();
104   const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_apk_path);
105   if (!UidHasWriteAccessToPath(uid, idmap_path)) {
106     *_aidl_return = false;
107     return error(base::StringPrintf("failed to unlink %s: calling uid %d lacks write access",
108                                     idmap_path.c_str(), uid));
109   }
110   if (unlink(idmap_path.c_str()) != 0) {
111     *_aidl_return = false;
112     return error("failed to unlink " + idmap_path + ": " + strerror(errno));
113   }
114   *_aidl_return = true;
115   return ok();
116 }
117 
verifyIdmap(const std::string & target_apk_path,const std::string & overlay_apk_path,int32_t fulfilled_policies,bool enforce_overlayable,int32_t user_id ATTRIBUTE_UNUSED,bool * _aidl_return)118 Status Idmap2Service::verifyIdmap(const std::string& target_apk_path,
119                                   const std::string& overlay_apk_path, int32_t fulfilled_policies,
120                                   bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
121                                   bool* _aidl_return) {
122   SYSTRACE << "Idmap2Service::verifyIdmap " << overlay_apk_path;
123   assert(_aidl_return);
124 
125   const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_apk_path);
126   std::ifstream fin(idmap_path);
127   const std::unique_ptr<const IdmapHeader> header = IdmapHeader::FromBinaryStream(fin);
128   fin.close();
129   if (!header) {
130     *_aidl_return = false;
131     return error("failed to parse idmap header");
132   }
133 
134   uint32_t target_crc;
135   if (target_apk_path == kFrameworkPath && android_crc_) {
136     target_crc = *android_crc_;
137   } else {
138     auto target_crc_status = GetCrc(target_apk_path, &target_crc);
139     if (!target_crc_status.isOk()) {
140       *_aidl_return = false;
141       return target_crc_status;
142     }
143 
144     // Loading the framework zip can take several milliseconds. Cache the crc of the framework
145     // resource APK to reduce repeated work during boot.
146     if (target_apk_path == kFrameworkPath) {
147       android_crc_ = target_crc;
148     }
149   }
150 
151   uint32_t overlay_crc;
152   auto overlay_crc_status = GetCrc(overlay_apk_path, &overlay_crc);
153   if (!overlay_crc_status.isOk()) {
154     *_aidl_return = false;
155     return overlay_crc_status;
156   }
157 
158   auto up_to_date =
159       header->IsUpToDate(target_apk_path.c_str(), overlay_apk_path.c_str(), target_crc, overlay_crc,
160                          ConvertAidlArgToPolicyBitmask(fulfilled_policies), enforce_overlayable);
161 
162   *_aidl_return = static_cast<bool>(up_to_date);
163   return *_aidl_return ? ok() : error(up_to_date.GetErrorMessage());
164 }
165 
createIdmap(const std::string & target_apk_path,const std::string & overlay_apk_path,int32_t fulfilled_policies,bool enforce_overlayable,int32_t user_id ATTRIBUTE_UNUSED,aidl::nullable<std::string> * _aidl_return)166 Status Idmap2Service::createIdmap(const std::string& target_apk_path,
167                                   const std::string& overlay_apk_path, int32_t fulfilled_policies,
168                                   bool enforce_overlayable, int32_t user_id ATTRIBUTE_UNUSED,
169                                   aidl::nullable<std::string>* _aidl_return) {
170   assert(_aidl_return);
171   SYSTRACE << "Idmap2Service::createIdmap " << target_apk_path << " " << overlay_apk_path;
172   _aidl_return->reset(nullptr);
173 
174   const PolicyBitmask policy_bitmask = ConvertAidlArgToPolicyBitmask(fulfilled_policies);
175 
176   const std::string idmap_path = Idmap::CanonicalIdmapPathFor(kIdmapCacheDir, overlay_apk_path);
177   const uid_t uid = IPCThreadState::self()->getCallingUid();
178   if (!UidHasWriteAccessToPath(uid, idmap_path)) {
179     return error(base::StringPrintf("will not write to %s: calling uid %d lacks write accesss",
180                                     idmap_path.c_str(), uid));
181   }
182 
183   const std::unique_ptr<const ApkAssets> target_apk = ApkAssets::Load(target_apk_path);
184   if (!target_apk) {
185     return error("failed to load apk " + target_apk_path);
186   }
187 
188   const std::unique_ptr<const ApkAssets> overlay_apk = ApkAssets::Load(overlay_apk_path);
189   if (!overlay_apk) {
190     return error("failed to load apk " + overlay_apk_path);
191   }
192 
193   const auto idmap =
194       Idmap::FromApkAssets(*target_apk, *overlay_apk, policy_bitmask, enforce_overlayable);
195   if (!idmap) {
196     return error(idmap.GetErrorMessage());
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.
201   unlink(idmap_path.c_str());
202 
203   umask(kIdmapFilePermissionMask);
204   std::ofstream fout(idmap_path);
205   if (fout.fail()) {
206     return error("failed to open idmap path " + idmap_path);
207   }
208 
209   BinaryStreamVisitor visitor(fout);
210   (*idmap)->accept(&visitor);
211   fout.close();
212   if (fout.fail()) {
213     unlink(idmap_path.c_str());
214     return error("failed to write to idmap path " + idmap_path);
215   }
216 
217   *_aidl_return = aidl::make_nullable<std::string>(idmap_path);
218   return ok();
219 }
220 
221 }  // namespace android::os
222