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 "idmap2/Idmap.h"
18 
19 #include <algorithm>
20 #include <iostream>
21 #include <iterator>
22 #include <limits>
23 #include <map>
24 #include <memory>
25 #include <set>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 #include "android-base/macros.h"
31 #include "android-base/stringprintf.h"
32 #include "androidfw/AssetManager2.h"
33 #include "idmap2/ResourceMapping.h"
34 #include "idmap2/ResourceUtils.h"
35 #include "idmap2/Result.h"
36 #include "idmap2/SysTrace.h"
37 #include "idmap2/ZipFile.h"
38 #include "utils/String16.h"
39 #include "utils/String8.h"
40 
41 namespace android::idmap2 {
42 
43 namespace {
44 
Read8(std::istream & stream,uint8_t * out)45 bool WARN_UNUSED Read8(std::istream& stream, uint8_t* out) {
46   uint8_t value;
47   if (stream.read(reinterpret_cast<char*>(&value), sizeof(uint8_t))) {
48     *out = value;
49     return true;
50   }
51   return false;
52 }
53 
Read32(std::istream & stream,uint32_t * out)54 bool WARN_UNUSED Read32(std::istream& stream, uint32_t* out) {
55   uint32_t value;
56   if (stream.read(reinterpret_cast<char*>(&value), sizeof(uint32_t))) {
57     *out = dtohl(value);
58     return true;
59   }
60   return false;
61 }
62 
ReadBuffer(std::istream & stream,std::unique_ptr<uint8_t[]> * out,size_t length)63 bool WARN_UNUSED ReadBuffer(std::istream& stream, std::unique_ptr<uint8_t[]>* out, size_t length) {
64   auto buffer = std::unique_ptr<uint8_t[]>(new uint8_t[length]);
65   if (stream.read(reinterpret_cast<char*>(buffer.get()), length)) {
66     *out = std::move(buffer);
67     return true;
68   }
69   return false;
70 }
71 
72 // a string is encoded as a kIdmapStringLength char array; the array is always null-terminated
ReadString256(std::istream & stream,char out[kIdmapStringLength])73 bool WARN_UNUSED ReadString256(std::istream& stream, char out[kIdmapStringLength]) {
74   char buf[kIdmapStringLength];
75   memset(buf, 0, sizeof(buf));
76   if (!stream.read(buf, sizeof(buf))) {
77     return false;
78   }
79   if (buf[sizeof(buf) - 1] != '\0') {
80     return false;
81   }
82   memcpy(out, buf, sizeof(buf));
83   return true;
84 }
85 
ReadString(std::istream & stream)86 Result<std::string> ReadString(std::istream& stream) {
87   uint32_t size;
88   if (!Read32(stream, &size)) {
89     return Error("failed to read string size");
90   }
91   if (size == 0) {
92     return std::string("");
93   }
94   std::string buf(size, '\0');
95   if (!stream.read(buf.data(), size)) {
96     return Error("failed to read string of size %u", size);
97   }
98   // buf is guaranteed to be null terminated (with enough nulls to end on a word boundary)
99   buf.resize(strlen(buf.c_str()));
100   return buf;
101 }
102 
103 }  // namespace
104 
GetPackageCrc(const ZipFile & zip)105 Result<uint32_t> GetPackageCrc(const ZipFile& zip) {
106   const Result<uint32_t> a = zip.Crc("resources.arsc");
107   const Result<uint32_t> b = zip.Crc("AndroidManifest.xml");
108   return a && b
109              ? Result<uint32_t>(*a ^ *b)
110              : Error("failed to get CRC for \"%s\"", a ? "AndroidManifest.xml" : "resources.arsc");
111 }
112 
FromBinaryStream(std::istream & stream)113 std::unique_ptr<const IdmapHeader> IdmapHeader::FromBinaryStream(std::istream& stream) {
114   std::unique_ptr<IdmapHeader> idmap_header(new IdmapHeader());
115   uint8_t enforce_overlayable;
116   if (!Read32(stream, &idmap_header->magic_) || !Read32(stream, &idmap_header->version_) ||
117       !Read32(stream, &idmap_header->target_crc_) || !Read32(stream, &idmap_header->overlay_crc_) ||
118       !Read32(stream, &idmap_header->fulfilled_policies_) || !Read8(stream, &enforce_overlayable) ||
119       !ReadString256(stream, idmap_header->target_path_) ||
120       !ReadString256(stream, idmap_header->overlay_path_)) {
121     return nullptr;
122   }
123 
124   idmap_header->enforce_overlayable_ = static_cast<bool>(enforce_overlayable);
125 
126   auto debug_str = ReadString(stream);
127   if (!debug_str) {
128     return nullptr;
129   }
130   idmap_header->debug_info_ = std::move(*debug_str);
131 
132   return std::move(idmap_header);
133 }
134 
IsUpToDate(const char * target_path,const char * overlay_path,PolicyBitmask fulfilled_policies,bool enforce_overlayable) const135 Result<Unit> IdmapHeader::IsUpToDate(const char* target_path, const char* overlay_path,
136                                      PolicyBitmask fulfilled_policies,
137                                      bool enforce_overlayable) const {
138   const std::unique_ptr<const ZipFile> target_zip = ZipFile::Open(target_path);
139   if (!target_zip) {
140     return Error("failed to open target %s", target_path);
141   }
142 
143   const Result<uint32_t> target_crc = GetPackageCrc(*target_zip);
144   if (!target_crc) {
145     return Error("failed to get target crc");
146   }
147 
148   const std::unique_ptr<const ZipFile> overlay_zip = ZipFile::Open(overlay_path);
149   if (!overlay_zip) {
150     return Error("failed to overlay target %s", overlay_path);
151   }
152 
153   const Result<uint32_t> overlay_crc = GetPackageCrc(*overlay_zip);
154   if (!overlay_crc) {
155     return Error("failed to get overlay crc");
156   }
157 
158   return IsUpToDate(target_path, overlay_path, *target_crc, *overlay_crc, fulfilled_policies,
159                     enforce_overlayable);
160 }
161 
IsUpToDate(const char * target_path,const char * overlay_path,uint32_t target_crc,uint32_t overlay_crc,PolicyBitmask fulfilled_policies,bool enforce_overlayable) const162 Result<Unit> IdmapHeader::IsUpToDate(const char* target_path, const char* overlay_path,
163                                      uint32_t target_crc, uint32_t overlay_crc,
164                                      PolicyBitmask fulfilled_policies,
165                                      bool enforce_overlayable) const {
166   if (magic_ != kIdmapMagic) {
167     return Error("bad magic: actual 0x%08x, expected 0x%08x", magic_, kIdmapMagic);
168   }
169 
170   if (version_ != kIdmapCurrentVersion) {
171     return Error("bad version: actual 0x%08x, expected 0x%08x", version_, kIdmapCurrentVersion);
172   }
173 
174   if (target_crc_ != target_crc) {
175     return Error("bad target crc: idmap version 0x%08x, file system version 0x%08x", target_crc_,
176                  target_crc);
177   }
178 
179   if (overlay_crc_ != overlay_crc) {
180     return Error("bad overlay crc: idmap version 0x%08x, file system version 0x%08x", overlay_crc_,
181                  overlay_crc);
182   }
183 
184   if (fulfilled_policies_ != fulfilled_policies) {
185     return Error("bad fulfilled policies: idmap version 0x%08x, file system version 0x%08x",
186                  fulfilled_policies, fulfilled_policies_);
187   }
188 
189   if (enforce_overlayable != enforce_overlayable_) {
190     return Error("bad enforce overlayable: idmap version %s, file system version %s",
191                  enforce_overlayable ? "true" : "false", enforce_overlayable_ ? "true" : "false");
192   }
193 
194   if (strcmp(target_path, target_path_) != 0) {
195     return Error("bad target path: idmap version %s, file system version %s", target_path,
196                  target_path_);
197   }
198 
199   if (strcmp(overlay_path, overlay_path_) != 0) {
200     return Error("bad overlay path: idmap version %s, file system version %s", overlay_path,
201                  overlay_path_);
202   }
203 
204   return Unit{};
205 }
206 
FromBinaryStream(std::istream & stream)207 std::unique_ptr<const IdmapData::Header> IdmapData::Header::FromBinaryStream(std::istream& stream) {
208   std::unique_ptr<IdmapData::Header> idmap_data_header(new IdmapData::Header());
209 
210   if (!Read8(stream, &idmap_data_header->target_package_id_) ||
211       !Read8(stream, &idmap_data_header->overlay_package_id_) ||
212       !Read32(stream, &idmap_data_header->target_entry_count) ||
213       !Read32(stream, &idmap_data_header->overlay_entry_count) ||
214       !Read32(stream, &idmap_data_header->string_pool_index_offset) ||
215       !Read32(stream, &idmap_data_header->string_pool_len)) {
216     return nullptr;
217   }
218 
219   return std::move(idmap_data_header);
220 }
221 
FromBinaryStream(std::istream & stream)222 std::unique_ptr<const IdmapData> IdmapData::FromBinaryStream(std::istream& stream) {
223   std::unique_ptr<IdmapData> data(new IdmapData());
224   data->header_ = IdmapData::Header::FromBinaryStream(stream);
225   if (!data->header_) {
226     return nullptr;
227   }
228   // Read the mapping of target resource id to overlay resource value.
229   for (size_t i = 0; i < data->header_->GetTargetEntryCount(); i++) {
230     TargetEntry target_entry{};
231     if (!Read32(stream, &target_entry.target_id) || !Read8(stream, &target_entry.data_type) ||
232         !Read32(stream, &target_entry.data_value)) {
233       return nullptr;
234     }
235     data->target_entries_.emplace_back(target_entry);
236   }
237 
238   // Read the mapping of overlay resource id to target resource id.
239   for (size_t i = 0; i < data->header_->GetOverlayEntryCount(); i++) {
240     OverlayEntry overlay_entry{};
241     if (!Read32(stream, &overlay_entry.overlay_id) || !Read32(stream, &overlay_entry.target_id)) {
242       return nullptr;
243     }
244     data->overlay_entries_.emplace_back(overlay_entry);
245   }
246 
247   // Read raw string pool bytes.
248   if (!ReadBuffer(stream, &data->string_pool_, data->header_->string_pool_len)) {
249     return nullptr;
250   }
251 
252   return std::move(data);
253 }
254 
CanonicalIdmapPathFor(const std::string & absolute_dir,const std::string & absolute_apk_path)255 std::string Idmap::CanonicalIdmapPathFor(const std::string& absolute_dir,
256                                          const std::string& absolute_apk_path) {
257   assert(absolute_dir.size() > 0 && absolute_dir[0] == "/");
258   assert(absolute_apk_path.size() > 0 && absolute_apk_path[0] == "/");
259   std::string copy(++absolute_apk_path.cbegin(), absolute_apk_path.cend());
260   replace(copy.begin(), copy.end(), '/', '@');
261   return absolute_dir + "/" + copy + "@idmap";
262 }
263 
FromBinaryStream(std::istream & stream)264 Result<std::unique_ptr<const Idmap>> Idmap::FromBinaryStream(std::istream& stream) {
265   SYSTRACE << "Idmap::FromBinaryStream";
266   std::unique_ptr<Idmap> idmap(new Idmap());
267 
268   idmap->header_ = IdmapHeader::FromBinaryStream(stream);
269   if (!idmap->header_) {
270     return Error("failed to parse idmap header");
271   }
272 
273   // idmap version 0x01 does not specify the number of data blocks that follow
274   // the idmap header; assume exactly one data block
275   for (int i = 0; i < 1; i++) {
276     std::unique_ptr<const IdmapData> data = IdmapData::FromBinaryStream(stream);
277     if (!data) {
278       return Error("failed to parse data block %d", i);
279     }
280     idmap->data_.push_back(std::move(data));
281   }
282 
283   return {std::move(idmap)};
284 }
285 
FromResourceMapping(const ResourceMapping & resource_mapping)286 Result<std::unique_ptr<const IdmapData>> IdmapData::FromResourceMapping(
287     const ResourceMapping& resource_mapping) {
288   if (resource_mapping.GetTargetToOverlayMap().empty()) {
289     return Error("no resources were overlaid");
290   }
291 
292   std::unique_ptr<IdmapData> data(new IdmapData());
293   for (const auto& mappings : resource_mapping.GetTargetToOverlayMap()) {
294     data->target_entries_.emplace_back(IdmapData::TargetEntry{
295         mappings.first, mappings.second.data_type, mappings.second.data_value});
296   }
297 
298   for (const auto& mappings : resource_mapping.GetOverlayToTargetMap()) {
299     data->overlay_entries_.emplace_back(IdmapData::OverlayEntry{mappings.first, mappings.second});
300   }
301 
302   std::unique_ptr<IdmapData::Header> data_header(new IdmapData::Header());
303   data_header->target_package_id_ = resource_mapping.GetTargetPackageId();
304   data_header->overlay_package_id_ = resource_mapping.GetOverlayPackageId();
305   data_header->target_entry_count = static_cast<uint32_t>(data->target_entries_.size());
306   data_header->overlay_entry_count = static_cast<uint32_t>(data->overlay_entries_.size());
307   data_header->string_pool_index_offset = resource_mapping.GetStringPoolOffset();
308 
309   const auto string_pool_data = resource_mapping.GetStringPoolData();
310   data_header->string_pool_len = string_pool_data.second;
311   data->string_pool_ = std::unique_ptr<uint8_t[]>(new uint8_t[data_header->string_pool_len]);
312   memcpy(data->string_pool_.get(), string_pool_data.first, data_header->string_pool_len);
313 
314   data->header_ = std::move(data_header);
315   return {std::move(data)};
316 }
317 
FromApkAssets(const ApkAssets & target_apk_assets,const ApkAssets & overlay_apk_assets,const PolicyBitmask & fulfilled_policies,bool enforce_overlayable)318 Result<std::unique_ptr<const Idmap>> Idmap::FromApkAssets(const ApkAssets& target_apk_assets,
319                                                           const ApkAssets& overlay_apk_assets,
320                                                           const PolicyBitmask& fulfilled_policies,
321                                                           bool enforce_overlayable) {
322   SYSTRACE << "Idmap::FromApkAssets";
323   const std::string& target_apk_path = target_apk_assets.GetPath();
324   const std::string& overlay_apk_path = overlay_apk_assets.GetPath();
325 
326   const std::unique_ptr<const ZipFile> target_zip = ZipFile::Open(target_apk_path);
327   if (!target_zip) {
328     return Error("failed to open target as zip");
329   }
330 
331   const std::unique_ptr<const ZipFile> overlay_zip = ZipFile::Open(overlay_apk_path);
332   if (!overlay_zip) {
333     return Error("failed to open overlay as zip");
334   }
335 
336   std::unique_ptr<IdmapHeader> header(new IdmapHeader());
337   header->magic_ = kIdmapMagic;
338   header->version_ = kIdmapCurrentVersion;
339 
340   Result<uint32_t> crc = GetPackageCrc(*target_zip);
341   if (!crc) {
342     return Error(crc.GetError(), "failed to get zip CRC for target");
343   }
344   header->target_crc_ = *crc;
345 
346   crc = GetPackageCrc(*overlay_zip);
347   if (!crc) {
348     return Error(crc.GetError(), "failed to get zip CRC for overlay");
349   }
350   header->overlay_crc_ = *crc;
351 
352   header->fulfilled_policies_ = fulfilled_policies;
353   header->enforce_overlayable_ = enforce_overlayable;
354 
355   if (target_apk_path.size() > sizeof(header->target_path_)) {
356     return Error("target apk path \"%s\" longer than maximum size %zu", target_apk_path.c_str(),
357                  sizeof(header->target_path_));
358   }
359   memset(header->target_path_, 0, sizeof(header->target_path_));
360   memcpy(header->target_path_, target_apk_path.data(), target_apk_path.size());
361 
362   if (overlay_apk_path.size() > sizeof(header->overlay_path_)) {
363     return Error("overlay apk path \"%s\" longer than maximum size %zu", overlay_apk_path.c_str(),
364                  sizeof(header->target_path_));
365   }
366   memset(header->overlay_path_, 0, sizeof(header->overlay_path_));
367   memcpy(header->overlay_path_, overlay_apk_path.data(), overlay_apk_path.size());
368 
369   auto overlay_info = utils::ExtractOverlayManifestInfo(overlay_apk_path);
370   if (!overlay_info) {
371     return overlay_info.GetError();
372   }
373 
374   LogInfo log_info;
375   auto resource_mapping =
376       ResourceMapping::FromApkAssets(target_apk_assets, overlay_apk_assets, *overlay_info,
377                                      fulfilled_policies, enforce_overlayable, log_info);
378   if (!resource_mapping) {
379     return resource_mapping.GetError();
380   }
381 
382   auto idmap_data = IdmapData::FromResourceMapping(*resource_mapping);
383   if (!idmap_data) {
384     return idmap_data.GetError();
385   }
386 
387   std::unique_ptr<Idmap> idmap(new Idmap());
388   header->debug_info_ = log_info.GetString();
389   idmap->header_ = std::move(header);
390   idmap->data_.push_back(std::move(*idmap_data));
391 
392   return {std::move(idmap)};
393 }
394 
accept(Visitor * v) const395 void IdmapHeader::accept(Visitor* v) const {
396   assert(v != nullptr);
397   v->visit(*this);
398 }
399 
accept(Visitor * v) const400 void IdmapData::Header::accept(Visitor* v) const {
401   assert(v != nullptr);
402   v->visit(*this);
403 }
404 
accept(Visitor * v) const405 void IdmapData::accept(Visitor* v) const {
406   assert(v != nullptr);
407   header_->accept(v);
408   v->visit(*this);
409 }
410 
accept(Visitor * v) const411 void Idmap::accept(Visitor* v) const {
412   assert(v != nullptr);
413   header_->accept(v);
414   v->visit(*this);
415   auto end = data_.cend();
416   for (auto iter = data_.cbegin(); iter != end; ++iter) {
417     (*iter)->accept(v);
418   }
419 }
420 
421 }  // namespace android::idmap2
422