1 /*
2 * Copyright (C) 2019 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 "apex_shim.h"
18
19 #include <android-base/file.h>
20 #include <android-base/logging.h>
21 #include <android-base/stringprintf.h>
22 #include <android-base/strings.h>
23 #include <openssl/sha.h>
24 #include <filesystem>
25 #include <fstream>
26 #include <sstream>
27 #include <unordered_set>
28
29 #include "apex_constants.h"
30 #include "apex_file.h"
31 #include "string_log.h"
32
33 using android::base::ErrnoError;
34 using android::base::Error;
35 using android::base::Result;
36 using ::apex::proto::ApexManifest;
37
38 namespace android {
39 namespace apex {
40 namespace shim {
41
42 namespace fs = std::filesystem;
43
44 namespace {
45
46 static constexpr const char* kApexCtsShimPackage = "com.android.apex.cts.shim";
47 static constexpr const char* kHashFilePath = "etc/hash.txt";
48 static constexpr const int kBufSize = 1024;
49 static constexpr const fs::perms kForbiddenFilePermissions =
50 fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec;
51 static constexpr const char* kExpectedCtsShimFiles[] = {
52 "apex_manifest.json",
53 "apex_manifest.pb",
54 "etc/hash.txt",
55 "app/CtsShim/CtsShim.apk",
56 "app/CtsShim@1/CtsShim.apk",
57 "app/CtsShim@2/CtsShim.apk",
58 "app/CtsShim@3/CtsShim.apk",
59 "app/CtsShimTargetPSdk/CtsShimTargetPSdk.apk",
60 "app/CtsShimTargetPSdk@1/CtsShimTargetPSdk.apk",
61 "app/CtsShimTargetPSdk@2/CtsShimTargetPSdk.apk",
62 "app/CtsShimTargetPSdk@3/CtsShimTargetPSdk.apk",
63 "priv-app/CtsShimPriv/CtsShimPriv.apk",
64 "priv-app/CtsShimPriv@1/CtsShimPriv.apk",
65 "priv-app/CtsShimPriv@2/CtsShimPriv.apk",
66 "priv-app/CtsShimPriv@3/CtsShimPriv.apk",
67 };
68
CalculateSha512(const std::string & path)69 Result<std::string> CalculateSha512(const std::string& path) {
70 LOG(DEBUG) << "Calculating SHA512 of " << path;
71 SHA512_CTX ctx;
72 SHA512_Init(&ctx);
73 std::ifstream apex(path, std::ios::binary);
74 if (apex.bad()) {
75 return Error() << "Failed to open " << path;
76 }
77 char buf[kBufSize];
78 while (!apex.eof()) {
79 apex.read(buf, kBufSize);
80 if (apex.bad()) {
81 return Error() << "Failed to read " << path;
82 }
83 int bytes_read = apex.gcount();
84 SHA512_Update(&ctx, buf, bytes_read);
85 }
86 uint8_t hash[SHA512_DIGEST_LENGTH];
87 SHA512_Final(hash, &ctx);
88 std::stringstream ss;
89 ss << std::hex;
90 for (int i = 0; i < SHA512_DIGEST_LENGTH; i++) {
91 ss << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
92 }
93 return ss.str();
94 }
95
GetAllowedHashes(const std::string & path)96 Result<std::vector<std::string>> GetAllowedHashes(const std::string& path) {
97 using android::base::ReadFileToString;
98 using android::base::StringPrintf;
99 const std::string& file_path =
100 StringPrintf("%s/%s", path.c_str(), kHashFilePath);
101 LOG(DEBUG) << "Reading SHA512 from " << file_path;
102 std::string hash;
103 if (!ReadFileToString(file_path, &hash, false /* follows symlinks */)) {
104 return ErrnoError() << "Failed to read " << file_path;
105 }
106 std::vector<std::string> allowed_hashes = android::base::Split(hash, "\n");
107 auto system_shim_hash = CalculateSha512(
108 StringPrintf("%s/%s", kApexPackageSystemDir, shim::kSystemShimApexName));
109 if (!system_shim_hash.ok()) {
110 return system_shim_hash.error();
111 }
112 allowed_hashes.push_back(std::move(*system_shim_hash));
113 return allowed_hashes;
114 }
115 } // namespace
116
IsShimApex(const ApexFile & apex_file)117 bool IsShimApex(const ApexFile& apex_file) {
118 return apex_file.GetManifest().name() == kApexCtsShimPackage;
119 }
120
ValidateShimApex(const std::string & mount_point,const ApexFile & apex_file)121 Result<void> ValidateShimApex(const std::string& mount_point,
122 const ApexFile& apex_file) {
123 LOG(DEBUG) << "Validating shim apex " << mount_point;
124 const ApexManifest& manifest = apex_file.GetManifest();
125 if (!manifest.preinstallhook().empty() ||
126 !manifest.postinstallhook().empty()) {
127 return Errorf("Shim apex is not allowed to have pre or post install hooks");
128 }
129 std::error_code ec;
130 std::unordered_set<std::string> expected_files;
131 for (auto file : kExpectedCtsShimFiles) {
132 expected_files.insert(file);
133 }
134
135 auto iter = fs::recursive_directory_iterator(mount_point, ec);
136 // Unfortunately fs::recursive_directory_iterator::operator++ can throw an
137 // exception, which means that it's impossible to use range-based for loop
138 // here.
139 while (iter != fs::end(iter)) {
140 auto path = iter->path();
141 // Resolve the mount point to ensure any trailing slash is removed.
142 auto resolved_mount_point = fs::path(mount_point).string();
143 auto local_path = path.string().substr(resolved_mount_point.length() + 1);
144 fs::file_status status = iter->status(ec);
145
146 if (fs::is_symlink(status)) {
147 return Error()
148 << "Shim apex is not allowed to contain symbolic links, found "
149 << path;
150 } else if (fs::is_regular_file(status)) {
151 if ((status.permissions() & kForbiddenFilePermissions) !=
152 fs::perms::none) {
153 return Error() << path << " has illegal permissions";
154 }
155 auto ex = expected_files.find(local_path);
156 if (ex != expected_files.end()) {
157 expected_files.erase(local_path);
158 } else {
159 return Error() << path << " is an unexpected file inside the shim apex";
160 }
161 } else if (!fs::is_directory(status)) {
162 // If this is not a symlink, a file or a directory, fail.
163 return Error() << "Unexpected file entry in shim apex: " << iter->path();
164 }
165 iter = iter.increment(ec);
166 if (ec) {
167 return Error() << "Failed to scan " << mount_point << " : "
168 << ec.message();
169 }
170 }
171
172 return {};
173 }
174
ValidateUpdate(const std::string & system_apex_path,const std::string & new_apex_path)175 Result<void> ValidateUpdate(const std::string& system_apex_path,
176 const std::string& new_apex_path) {
177 LOG(DEBUG) << "Validating update of shim apex to " << new_apex_path
178 << " using system shim apex " << system_apex_path;
179 auto allowed = GetAllowedHashes(system_apex_path);
180 if (!allowed.ok()) {
181 return allowed.error();
182 }
183 auto actual = CalculateSha512(new_apex_path);
184 if (!actual.ok()) {
185 return actual.error();
186 }
187 auto it = std::find(allowed->begin(), allowed->end(), *actual);
188 if (it == allowed->end()) {
189 return Error() << new_apex_path << " has unexpected SHA512 hash "
190 << *actual;
191 }
192 return {};
193 }
194
195 } // namespace shim
196 } // namespace apex
197 } // namespace android
198