blob: 903cdf852566bc72e674823356e1ad75a415c29e [file] [log] [blame]
Mohamed Heikalc7694032018-11-07 16:49:02 -05001/*
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
felkachang4bdd3ac2022-09-13 10:58:49 +080017#include "optimize/Obfuscator.h"
Mohamed Heikalc7694032018-11-07 16:49:02 -050018
felkachang78a8d372022-09-14 15:17:29 +080019#include <fstream>
felkachang8ceb39c2022-09-13 10:58:49 +080020#include <map>
Mohamed Heikalb2bac122019-07-17 17:47:17 -040021#include <set>
felkachang4bdd3ac2022-09-13 10:58:49 +080022#include <string>
Mohamed Heikalc7694032018-11-07 16:49:02 -050023#include <unordered_set>
24
Mohamed Heikalc7694032018-11-07 16:49:02 -050025#include "ResourceTable.h"
26#include "ValueVisitor.h"
felkachang4bdd3ac2022-09-13 10:58:49 +080027#include "androidfw/StringPiece.h"
Mohamed Heikal61d528f2019-07-08 15:06:39 -040028#include "util/Util.h"
Mohamed Heikalc7694032018-11-07 16:49:02 -050029
felkachang4bdd3ac2022-09-13 10:58:49 +080030static const char base64_chars[] =
31 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
32 "abcdefghijklmnopqrstuvwxyz"
33 "0123456789-_";
Mohamed Heikalc7694032018-11-07 16:49:02 -050034
35namespace aapt {
36
felkachang8ceb39c2022-09-13 10:58:49 +080037Obfuscator::Obfuscator(OptimizeOptions& optimizeOptions)
38 : options_(optimizeOptions.table_flattener_options),
39 shorten_resource_paths_(optimizeOptions.shorten_resource_paths),
40 collapse_key_stringpool_(optimizeOptions.table_flattener_options.collapse_key_stringpool) {
Mohamed Heikalc7694032018-11-07 16:49:02 -050041}
42
Mark Punzalan19e1d2052023-07-11 20:37:45 +000043std::string Obfuscator::ShortenFileName(android::StringPiece file_path, int output_length) {
Mohamed Heikalc7694032018-11-07 16:49:02 -050044 std::size_t hash_num = std::hash<android::StringPiece>{}(file_path);
Mark Punzalan19e1d2052023-07-11 20:37:45 +000045 std::string result;
Mohamed Heikalc7694032018-11-07 16:49:02 -050046 // Convert to (modified) base64 so that it is a proper file path.
47 for (int i = 0; i < output_length; i++) {
48 uint8_t sextet = hash_num & 0x3f;
49 hash_num >>= 6;
50 result += base64_chars[sextet];
51 }
52 return result;
53}
54
Mark Punzalan19e1d2052023-07-11 20:37:45 +000055static std::string RenameDisallowedFileNames(const std::string& file_name) {
56 // We are renaming shortened file names to make sure they not a reserved file name in Windows.
57 // See: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file. We are renaming
58 // "COM" and "LPT" too because we are appending a number in case of hash collisions; "COM1",
59 // "COM2", etc. are reserved names.
60 static const char* const reserved_windows_names[] = {"CON", "PRN", "AUX", "NUL", "COM", "LPT"};
61 if (file_name.length() == 3) {
62 // Need to convert the file name to uppercase as Windows is case insensitive. E.g., "NuL",
63 // "nul", and "NUl" are also reserved.
64 std::string result_upper_cased(3, 0);
65 std::transform(file_name.begin(), file_name.end(), result_upper_cased.begin(),
66 [](unsigned char c) { return std::toupper(c); });
67 for (auto reserved_windows_name : reserved_windows_names) {
68 if (result_upper_cased == reserved_windows_name) {
69 // Simple solution to make it a non-reserved name is to add an underscore
70 return "_" + file_name;
71 }
72 }
73 }
74
75 return file_name;
76}
77
Mohamed Heikal525714a2019-07-18 11:14:31 -040078// Return the optimal hash length such that at most 10% of resources collide in
79// their shortened path.
Mohamed Heikalc7694032018-11-07 16:49:02 -050080// Reference: http://matt.might.net/articles/counting-hash-collisions/
Mark Punzalan19e1d2052023-07-11 20:37:45 +000081static int OptimalShortenedLength(int num_resources) {
Mohamed Heikal525714a2019-07-18 11:14:31 -040082 if (num_resources > 4000) {
83 return 3;
84 } else {
85 return 2;
Mohamed Heikalc7694032018-11-07 16:49:02 -050086 }
Mohamed Heikalc7694032018-11-07 16:49:02 -050087}
88
Mark Punzalan19e1d2052023-07-11 20:37:45 +000089static std::string GetShortenedPath(android::StringPiece shortened_filename,
90 android::StringPiece extension, int collision_count) {
Yurii Zubrytskyia5775142022-11-02 17:49:49 -070091 std::string shortened_path = std::string("res/") += shortened_filename;
Mohamed Heikalc7694032018-11-07 16:49:02 -050092 if (collision_count > 0) {
93 shortened_path += std::to_string(collision_count);
94 }
95 shortened_path += extension;
96 return shortened_path;
97}
98
Mohamed Heikalb2bac122019-07-17 17:47:17 -040099// implement custom comparator of FileReference pointers so as to use the
100// underlying filepath as key rather than the integer address. This is to ensure
101// determinism of output for colliding files.
102struct PathComparator {
felkachang4bdd3ac2022-09-13 10:58:49 +0800103 bool operator()(const FileReference* lhs, const FileReference* rhs) const {
104 return lhs->path->compare(*rhs->path);
105 }
Mohamed Heikalb2bac122019-07-17 17:47:17 -0400106};
107
Mark Punzalan19e1d2052023-07-11 20:37:45 +0000108bool Obfuscator::HandleShortenFilePaths(ResourceTable* table,
109 std::map<std::string, std::string>& shortened_path_map,
110 const std::set<ResourceName>& path_shorten_exemptions) {
Mohamed Heikalc7694032018-11-07 16:49:02 -0500111 // used to detect collisions
112 std::unordered_set<std::string> shortened_paths;
Mohamed Heikalb2bac122019-07-17 17:47:17 -0400113 std::set<FileReference*, PathComparator> file_refs;
Mohamed Heikalc7694032018-11-07 16:49:02 -0500114 for (auto& package : table->packages) {
115 for (auto& type : package->types) {
116 for (auto& entry : type->entries) {
branliuf1ed5232022-12-16 19:02:29 +0800117 ResourceName resource_name({}, type->named_type, entry->name);
118 if (path_shorten_exemptions.find(resource_name) != path_shorten_exemptions.end()) {
119 continue;
120 }
Mohamed Heikalc7694032018-11-07 16:49:02 -0500121 for (auto& config_value : entry->values) {
122 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
123 if (file_ref) {
124 file_refs.insert(file_ref);
125 }
126 }
127 }
128 }
129 }
130 int num_chars = OptimalShortenedLength(file_refs.size());
131 for (auto& file_ref : file_refs) {
132 android::StringPiece res_subdir, actual_filename, extension;
133 util::ExtractResFilePathParts(*file_ref->path, &res_subdir, &actual_filename, &extension);
134
Mohamed Heikal61d528f2019-07-08 15:06:39 -0400135 // Android detects ColorStateLists via pathname, skip res/color*
felkachang4bdd3ac2022-09-13 10:58:49 +0800136 if (util::StartsWith(res_subdir, "res/color")) continue;
Mohamed Heikal7c757302019-04-25 17:39:43 -0400137
Mark Punzalan19e1d2052023-07-11 20:37:45 +0000138 std::string shortened_filename =
139 RenameDisallowedFileNames(ShortenFileName(*file_ref->path, num_chars));
Mohamed Heikalc7694032018-11-07 16:49:02 -0500140 int collision_count = 0;
141 std::string shortened_path = GetShortenedPath(shortened_filename, extension, collision_count);
142 while (shortened_paths.find(shortened_path) != shortened_paths.end()) {
143 collision_count++;
144 shortened_path = GetShortenedPath(shortened_filename, extension, collision_count);
145 }
146 shortened_paths.insert(shortened_path);
felkachang8ceb39c2022-09-13 10:58:49 +0800147 shortened_path_map.insert({*file_ref->path, shortened_path});
Mohamed Heikalc7694032018-11-07 16:49:02 -0500148 file_ref->path = table->string_pool.MakeRef(shortened_path, file_ref->path.GetContext());
149 }
150 return true;
151}
152
felkachang8ceb39c2022-09-13 10:58:49 +0800153void Obfuscator::ObfuscateResourceName(
154 const bool collapse_key_stringpool, const std::set<ResourceName>& name_collapse_exemptions,
155 const ResourceNamedType& type_name, const ResourceTableEntryView& entry,
156 const android::base::function_ref<void(Result obfuscatedResult, const ResourceName&)>
157 onObfuscate) {
158 ResourceName resource_name({}, type_name, entry.name);
159 if (!collapse_key_stringpool ||
160 name_collapse_exemptions.find(resource_name) != name_collapse_exemptions.end()) {
161 onObfuscate(Result::Keep_ExemptionList, resource_name);
162 } else {
163 // resource isn't exempt from collapse, add it as obfuscated value
164 if (entry.overlayable_item) {
165 // if the resource name of the specific entry is obfuscated and this
166 // entry is in the overlayable list, the overlay can't work on this
167 // overlayable at runtime because the name has been obfuscated in
168 // resources.arsc during flatten operation.
169 onObfuscate(Result::Keep_Overlayable, resource_name);
170 } else {
171 onObfuscate(Result::Obfuscated, resource_name);
172 }
173 }
174}
175
176static bool HandleCollapseKeyStringPool(
177 const ResourceTable* table, const bool collapse_key_string_pool,
178 const std::set<ResourceName>& name_collapse_exemptions,
179 std::unordered_map<uint32_t, std::string>& id_resource_map) {
180 if (!collapse_key_string_pool) {
181 return true;
182 }
183
184 int entryResId = 0;
185 auto onObfuscate = [&entryResId, &id_resource_map](const Obfuscator::Result obfuscatedResult,
186 const ResourceName& resource_name) {
187 if (obfuscatedResult == Obfuscator::Result::Obfuscated) {
188 id_resource_map.insert({entryResId, resource_name.entry});
189 }
190 };
191
192 for (auto& package : table->packages) {
193 for (auto& type : package->types) {
194 for (auto& entry : type->entries) {
195 if (!entry->id.has_value() || entry->name.empty()) {
196 continue;
197 }
198 entryResId = entry->id->id;
199 ResourceTableEntryView entry_view{
200 .name = entry->name,
201 .id = entry->id ? entry->id.value().entry_id() : (std::optional<uint16_t>)std::nullopt,
202 .visibility = entry->visibility,
203 .allow_new = entry->allow_new,
204 .overlayable_item = entry->overlayable_item,
205 .staged_id = entry->staged_id};
206
207 Obfuscator::ObfuscateResourceName(collapse_key_string_pool, name_collapse_exemptions,
208 type->named_type, entry_view, onObfuscate);
209 }
210 }
211 }
212
213 return true;
214}
215
216bool Obfuscator::Consume(IAaptContext* context, ResourceTable* table) {
217 HandleCollapseKeyStringPool(table, options_.collapse_key_stringpool,
218 options_.name_collapse_exemptions, options_.id_resource_map);
219 if (shorten_resource_paths_) {
branliuf1ed5232022-12-16 19:02:29 +0800220 return HandleShortenFilePaths(table, options_.shortened_path_map,
221 options_.path_shorten_exemptions);
felkachang8ceb39c2022-09-13 10:58:49 +0800222 }
223 return true;
224}
225
felkachang78a8d372022-09-14 15:17:29 +0800226bool Obfuscator::WriteObfuscationMap(const std::string& file_path) const {
227 pb::ResourceMappings resourceMappings;
228 for (const auto& [id, name] : options_.id_resource_map) {
229 auto* collapsedNameMapping = resourceMappings.mutable_collapsed_names()->add_resource_names();
230 collapsedNameMapping->set_id(id);
231 collapsedNameMapping->set_name(name);
232 }
233
234 for (const auto& [original_path, shortened_path] : options_.shortened_path_map) {
235 auto* resource_path = resourceMappings.mutable_shortened_paths()->add_resource_paths();
236 resource_path->set_original_path(original_path);
237 resource_path->set_shortened_path(shortened_path);
238 }
239
240 { // RAII style, output the pb content to file and close fout in destructor
241 std::ofstream fout(file_path, std::ios::out | std::ios::trunc | std::ios::binary);
242 if (!fout.is_open()) {
243 return false;
244 }
245 return resourceMappings.SerializeToOstream(&fout);
246 }
247}
248
felkachang8ceb39c2022-09-13 10:58:49 +0800249/**
250 * Tell the optimizer whether it's needed to dump information for de-obfuscating.
251 *
252 * There are two conditions need to dump the information for de-obfuscating.
253 * * the option of shortening file paths is enabled.
254 * * the option of collapsing resource names is enabled.
255 * @return true if the information needed for de-obfuscating, otherwise false
256 */
257bool Obfuscator::IsEnabled() const {
258 return shorten_resource_paths_ || collapse_key_stringpool_;
259}
260
Mohamed Heikalc7694032018-11-07 16:49:02 -0500261} // namespace aapt