blob: cc21093084b5d0b7bb978c9a341e197cc9b9cfda [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
Yurii Zubrytskyia5775142022-11-02 17:49:49 -070043std::string 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);
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
Mohamed Heikal525714a2019-07-18 11:14:31 -040055// Return the optimal hash length such that at most 10% of resources collide in
56// their shortened path.
Mohamed Heikalc7694032018-11-07 16:49:02 -050057// Reference: http://matt.might.net/articles/counting-hash-collisions/
58int OptimalShortenedLength(int num_resources) {
Mohamed Heikal525714a2019-07-18 11:14:31 -040059 if (num_resources > 4000) {
60 return 3;
61 } else {
62 return 2;
Mohamed Heikalc7694032018-11-07 16:49:02 -050063 }
Mohamed Heikalc7694032018-11-07 16:49:02 -050064}
65
Yurii Zubrytskyia5775142022-11-02 17:49:49 -070066std::string GetShortenedPath(android::StringPiece shortened_filename,
67 android::StringPiece extension, int collision_count) {
68 std::string shortened_path = std::string("res/") += shortened_filename;
Mohamed Heikalc7694032018-11-07 16:49:02 -050069 if (collision_count > 0) {
70 shortened_path += std::to_string(collision_count);
71 }
72 shortened_path += extension;
73 return shortened_path;
74}
75
Mohamed Heikalb2bac122019-07-17 17:47:17 -040076// 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.
79struct PathComparator {
felkachang4bdd3ac2022-09-13 10:58:49 +080080 bool operator()(const FileReference* lhs, const FileReference* rhs) const {
81 return lhs->path->compare(*rhs->path);
82 }
Mohamed Heikalb2bac122019-07-17 17:47:17 -040083};
84
felkachang8ceb39c2022-09-13 10:58:49 +080085static bool HandleShortenFilePaths(ResourceTable* table,
86 std::map<std::string, std::string>& shortened_path_map) {
Mohamed Heikalc7694032018-11-07 16:49:02 -050087 // used to detect collisions
88 std::unordered_set<std::string> shortened_paths;
Mohamed Heikalb2bac122019-07-17 17:47:17 -040089 std::set<FileReference*, PathComparator> file_refs;
Mohamed Heikalc7694032018-11-07 16:49:02 -050090 for (auto& package : table->packages) {
91 for (auto& type : package->types) {
92 for (auto& entry : type->entries) {
93 for (auto& config_value : entry->values) {
94 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
95 if (file_ref) {
96 file_refs.insert(file_ref);
97 }
98 }
99 }
100 }
101 }
102 int num_chars = OptimalShortenedLength(file_refs.size());
103 for (auto& file_ref : file_refs) {
104 android::StringPiece res_subdir, actual_filename, extension;
105 util::ExtractResFilePathParts(*file_ref->path, &res_subdir, &actual_filename, &extension);
106
Mohamed Heikal61d528f2019-07-08 15:06:39 -0400107 // Android detects ColorStateLists via pathname, skip res/color*
felkachang4bdd3ac2022-09-13 10:58:49 +0800108 if (util::StartsWith(res_subdir, "res/color")) continue;
Mohamed Heikal7c757302019-04-25 17:39:43 -0400109
Mohamed Heikalc7694032018-11-07 16:49:02 -0500110 std::string shortened_filename = ShortenFileName(*file_ref->path, num_chars);
111 int collision_count = 0;
112 std::string shortened_path = GetShortenedPath(shortened_filename, extension, collision_count);
113 while (shortened_paths.find(shortened_path) != shortened_paths.end()) {
114 collision_count++;
115 shortened_path = GetShortenedPath(shortened_filename, extension, collision_count);
116 }
117 shortened_paths.insert(shortened_path);
felkachang8ceb39c2022-09-13 10:58:49 +0800118 shortened_path_map.insert({*file_ref->path, shortened_path});
Mohamed Heikalc7694032018-11-07 16:49:02 -0500119 file_ref->path = table->string_pool.MakeRef(shortened_path, file_ref->path.GetContext());
120 }
121 return true;
122}
123
felkachang8ceb39c2022-09-13 10:58:49 +0800124void Obfuscator::ObfuscateResourceName(
125 const bool collapse_key_stringpool, const std::set<ResourceName>& name_collapse_exemptions,
126 const ResourceNamedType& type_name, const ResourceTableEntryView& entry,
127 const android::base::function_ref<void(Result obfuscatedResult, const ResourceName&)>
128 onObfuscate) {
129 ResourceName resource_name({}, type_name, entry.name);
130 if (!collapse_key_stringpool ||
131 name_collapse_exemptions.find(resource_name) != name_collapse_exemptions.end()) {
132 onObfuscate(Result::Keep_ExemptionList, resource_name);
133 } else {
134 // resource isn't exempt from collapse, add it as obfuscated value
135 if (entry.overlayable_item) {
136 // if the resource name of the specific entry is obfuscated and this
137 // entry is in the overlayable list, the overlay can't work on this
138 // overlayable at runtime because the name has been obfuscated in
139 // resources.arsc during flatten operation.
140 onObfuscate(Result::Keep_Overlayable, resource_name);
141 } else {
142 onObfuscate(Result::Obfuscated, resource_name);
143 }
144 }
145}
146
147static bool HandleCollapseKeyStringPool(
148 const ResourceTable* table, const bool collapse_key_string_pool,
149 const std::set<ResourceName>& name_collapse_exemptions,
150 std::unordered_map<uint32_t, std::string>& id_resource_map) {
151 if (!collapse_key_string_pool) {
152 return true;
153 }
154
155 int entryResId = 0;
156 auto onObfuscate = [&entryResId, &id_resource_map](const Obfuscator::Result obfuscatedResult,
157 const ResourceName& resource_name) {
158 if (obfuscatedResult == Obfuscator::Result::Obfuscated) {
159 id_resource_map.insert({entryResId, resource_name.entry});
160 }
161 };
162
163 for (auto& package : table->packages) {
164 for (auto& type : package->types) {
165 for (auto& entry : type->entries) {
166 if (!entry->id.has_value() || entry->name.empty()) {
167 continue;
168 }
169 entryResId = entry->id->id;
170 ResourceTableEntryView entry_view{
171 .name = entry->name,
172 .id = entry->id ? entry->id.value().entry_id() : (std::optional<uint16_t>)std::nullopt,
173 .visibility = entry->visibility,
174 .allow_new = entry->allow_new,
175 .overlayable_item = entry->overlayable_item,
176 .staged_id = entry->staged_id};
177
178 Obfuscator::ObfuscateResourceName(collapse_key_string_pool, name_collapse_exemptions,
179 type->named_type, entry_view, onObfuscate);
180 }
181 }
182 }
183
184 return true;
185}
186
187bool Obfuscator::Consume(IAaptContext* context, ResourceTable* table) {
188 HandleCollapseKeyStringPool(table, options_.collapse_key_stringpool,
189 options_.name_collapse_exemptions, options_.id_resource_map);
190 if (shorten_resource_paths_) {
191 return HandleShortenFilePaths(table, options_.shortened_path_map);
192 }
193 return true;
194}
195
felkachang78a8d372022-09-14 15:17:29 +0800196bool Obfuscator::WriteObfuscationMap(const std::string& file_path) const {
197 pb::ResourceMappings resourceMappings;
198 for (const auto& [id, name] : options_.id_resource_map) {
199 auto* collapsedNameMapping = resourceMappings.mutable_collapsed_names()->add_resource_names();
200 collapsedNameMapping->set_id(id);
201 collapsedNameMapping->set_name(name);
202 }
203
204 for (const auto& [original_path, shortened_path] : options_.shortened_path_map) {
205 auto* resource_path = resourceMappings.mutable_shortened_paths()->add_resource_paths();
206 resource_path->set_original_path(original_path);
207 resource_path->set_shortened_path(shortened_path);
208 }
209
210 { // RAII style, output the pb content to file and close fout in destructor
211 std::ofstream fout(file_path, std::ios::out | std::ios::trunc | std::ios::binary);
212 if (!fout.is_open()) {
213 return false;
214 }
215 return resourceMappings.SerializeToOstream(&fout);
216 }
217}
218
felkachang8ceb39c2022-09-13 10:58:49 +0800219/**
220 * Tell the optimizer whether it's needed to dump information for de-obfuscating.
221 *
222 * There are two conditions need to dump the information for de-obfuscating.
223 * * the option of shortening file paths is enabled.
224 * * the option of collapsing resource names is enabled.
225 * @return true if the information needed for de-obfuscating, otherwise false
226 */
227bool Obfuscator::IsEnabled() const {
228 return shorten_resource_paths_ || collapse_key_stringpool_;
229}
230
Mohamed Heikalc7694032018-11-07 16:49:02 -0500231} // namespace aapt