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 "optimize/Obfuscator.h"
18
19 #include <fstream>
20 #include <map>
21 #include <set>
22 #include <string>
23 #include <unordered_set>
24
25 #include "ResourceTable.h"
26 #include "ValueVisitor.h"
27 #include "androidfw/StringPiece.h"
28 #include "util/Util.h"
29
30 static const char base64_chars[] =
31 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
32 "abcdefghijklmnopqrstuvwxyz"
33 "0123456789-_";
34
35 namespace aapt {
36
Obfuscator(OptimizeOptions & optimizeOptions)37 Obfuscator::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) {
41 }
42
ShortenFileName(android::StringPiece file_path,int output_length)43 std::string ShortenFileName(android::StringPiece file_path, int output_length) {
44 std::size_t hash_num = std::hash<android::StringPiece>{}(file_path);
45 std::string result = "";
46 // 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
55 // Return the optimal hash length such that at most 10% of resources collide in
56 // their shortened path.
57 // Reference: http://matt.might.net/articles/counting-hash-collisions/
OptimalShortenedLength(int num_resources)58 int OptimalShortenedLength(int num_resources) {
59 if (num_resources > 4000) {
60 return 3;
61 } else {
62 return 2;
63 }
64 }
65
GetShortenedPath(android::StringPiece shortened_filename,android::StringPiece extension,int collision_count)66 std::string GetShortenedPath(android::StringPiece shortened_filename,
67 android::StringPiece extension, int collision_count) {
68 std::string shortened_path = std::string("res/") += shortened_filename;
69 if (collision_count > 0) {
70 shortened_path += std::to_string(collision_count);
71 }
72 shortened_path += extension;
73 return shortened_path;
74 }
75
76 // implement custom comparator of FileReference pointers so as to use the
77 // underlying filepath as key rather than the integer address. This is to ensure
78 // determinism of output for colliding files.
79 struct PathComparator {
operator ()aapt::PathComparator80 bool operator()(const FileReference* lhs, const FileReference* rhs) const {
81 return lhs->path->compare(*rhs->path);
82 }
83 };
84
HandleShortenFilePaths(ResourceTable * table,std::map<std::string,std::string> & shortened_path_map,const std::set<ResourceName> & path_shorten_exemptions)85 static bool HandleShortenFilePaths(ResourceTable* table,
86 std::map<std::string, std::string>& shortened_path_map,
87 const std::set<ResourceName>& path_shorten_exemptions) {
88 // used to detect collisions
89 std::unordered_set<std::string> shortened_paths;
90 std::set<FileReference*, PathComparator> file_refs;
91 for (auto& package : table->packages) {
92 for (auto& type : package->types) {
93 for (auto& entry : type->entries) {
94 ResourceName resource_name({}, type->named_type, entry->name);
95 if (path_shorten_exemptions.find(resource_name) != path_shorten_exemptions.end()) {
96 continue;
97 }
98 for (auto& config_value : entry->values) {
99 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
100 if (file_ref) {
101 file_refs.insert(file_ref);
102 }
103 }
104 }
105 }
106 }
107 int num_chars = OptimalShortenedLength(file_refs.size());
108 for (auto& file_ref : file_refs) {
109 android::StringPiece res_subdir, actual_filename, extension;
110 util::ExtractResFilePathParts(*file_ref->path, &res_subdir, &actual_filename, &extension);
111
112 // Android detects ColorStateLists via pathname, skip res/color*
113 if (util::StartsWith(res_subdir, "res/color")) continue;
114
115 std::string shortened_filename = ShortenFileName(*file_ref->path, num_chars);
116 int collision_count = 0;
117 std::string shortened_path = GetShortenedPath(shortened_filename, extension, collision_count);
118 while (shortened_paths.find(shortened_path) != shortened_paths.end()) {
119 collision_count++;
120 shortened_path = GetShortenedPath(shortened_filename, extension, collision_count);
121 }
122 shortened_paths.insert(shortened_path);
123 shortened_path_map.insert({*file_ref->path, shortened_path});
124 file_ref->path = table->string_pool.MakeRef(shortened_path, file_ref->path.GetContext());
125 }
126 return true;
127 }
128
ObfuscateResourceName(const bool collapse_key_stringpool,const std::set<ResourceName> & name_collapse_exemptions,const ResourceNamedType & type_name,const ResourceTableEntryView & entry,const android::base::function_ref<void (Result obfuscatedResult,const ResourceName &)> onObfuscate)129 void Obfuscator::ObfuscateResourceName(
130 const bool collapse_key_stringpool, const std::set<ResourceName>& name_collapse_exemptions,
131 const ResourceNamedType& type_name, const ResourceTableEntryView& entry,
132 const android::base::function_ref<void(Result obfuscatedResult, const ResourceName&)>
133 onObfuscate) {
134 ResourceName resource_name({}, type_name, entry.name);
135 if (!collapse_key_stringpool ||
136 name_collapse_exemptions.find(resource_name) != name_collapse_exemptions.end()) {
137 onObfuscate(Result::Keep_ExemptionList, resource_name);
138 } else {
139 // resource isn't exempt from collapse, add it as obfuscated value
140 if (entry.overlayable_item) {
141 // if the resource name of the specific entry is obfuscated and this
142 // entry is in the overlayable list, the overlay can't work on this
143 // overlayable at runtime because the name has been obfuscated in
144 // resources.arsc during flatten operation.
145 onObfuscate(Result::Keep_Overlayable, resource_name);
146 } else {
147 onObfuscate(Result::Obfuscated, resource_name);
148 }
149 }
150 }
151
HandleCollapseKeyStringPool(const ResourceTable * table,const bool collapse_key_string_pool,const std::set<ResourceName> & name_collapse_exemptions,std::unordered_map<uint32_t,std::string> & id_resource_map)152 static bool HandleCollapseKeyStringPool(
153 const ResourceTable* table, const bool collapse_key_string_pool,
154 const std::set<ResourceName>& name_collapse_exemptions,
155 std::unordered_map<uint32_t, std::string>& id_resource_map) {
156 if (!collapse_key_string_pool) {
157 return true;
158 }
159
160 int entryResId = 0;
161 auto onObfuscate = [&entryResId, &id_resource_map](const Obfuscator::Result obfuscatedResult,
162 const ResourceName& resource_name) {
163 if (obfuscatedResult == Obfuscator::Result::Obfuscated) {
164 id_resource_map.insert({entryResId, resource_name.entry});
165 }
166 };
167
168 for (auto& package : table->packages) {
169 for (auto& type : package->types) {
170 for (auto& entry : type->entries) {
171 if (!entry->id.has_value() || entry->name.empty()) {
172 continue;
173 }
174 entryResId = entry->id->id;
175 ResourceTableEntryView entry_view{
176 .name = entry->name,
177 .id = entry->id ? entry->id.value().entry_id() : (std::optional<uint16_t>)std::nullopt,
178 .visibility = entry->visibility,
179 .allow_new = entry->allow_new,
180 .overlayable_item = entry->overlayable_item,
181 .staged_id = entry->staged_id};
182
183 Obfuscator::ObfuscateResourceName(collapse_key_string_pool, name_collapse_exemptions,
184 type->named_type, entry_view, onObfuscate);
185 }
186 }
187 }
188
189 return true;
190 }
191
Consume(IAaptContext * context,ResourceTable * table)192 bool Obfuscator::Consume(IAaptContext* context, ResourceTable* table) {
193 HandleCollapseKeyStringPool(table, options_.collapse_key_stringpool,
194 options_.name_collapse_exemptions, options_.id_resource_map);
195 if (shorten_resource_paths_) {
196 return HandleShortenFilePaths(table, options_.shortened_path_map,
197 options_.path_shorten_exemptions);
198 }
199 return true;
200 }
201
WriteObfuscationMap(const std::string & file_path) const202 bool Obfuscator::WriteObfuscationMap(const std::string& file_path) const {
203 pb::ResourceMappings resourceMappings;
204 for (const auto& [id, name] : options_.id_resource_map) {
205 auto* collapsedNameMapping = resourceMappings.mutable_collapsed_names()->add_resource_names();
206 collapsedNameMapping->set_id(id);
207 collapsedNameMapping->set_name(name);
208 }
209
210 for (const auto& [original_path, shortened_path] : options_.shortened_path_map) {
211 auto* resource_path = resourceMappings.mutable_shortened_paths()->add_resource_paths();
212 resource_path->set_original_path(original_path);
213 resource_path->set_shortened_path(shortened_path);
214 }
215
216 { // RAII style, output the pb content to file and close fout in destructor
217 std::ofstream fout(file_path, std::ios::out | std::ios::trunc | std::ios::binary);
218 if (!fout.is_open()) {
219 return false;
220 }
221 return resourceMappings.SerializeToOstream(&fout);
222 }
223 }
224
225 /**
226 * Tell the optimizer whether it's needed to dump information for de-obfuscating.
227 *
228 * There are two conditions need to dump the information for de-obfuscating.
229 * * the option of shortening file paths is enabled.
230 * * the option of collapsing resource names is enabled.
231 * @return true if the information needed for de-obfuscating, otherwise false
232 */
IsEnabled() const233 bool Obfuscator::IsEnabled() const {
234 return shorten_resource_paths_ || collapse_key_stringpool_;
235 }
236
237 } // namespace aapt
238