1 /*
2 * Copyright (C) 2007 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 <ctype.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <limits.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
23 #include <unistd.h>
24
25 #include "common.h"
26 #include "install.h"
27 #include "mincrypt/rsa.h"
28 #include "minui/minui.h"
29 #include "minzip/SysUtil.h"
30 #include "minzip/Zip.h"
31 #include "mtdutils/mounts.h"
32 #include "mtdutils/mtdutils.h"
33 #include "roots.h"
34 #include "verifier.h"
35 #include "ui.h"
36
37 extern RecoveryUI* ui;
38
39 #define ASSUMED_UPDATE_BINARY_NAME "META-INF/com/google/android/update-binary"
40 #define PUBLIC_KEYS_FILE "/res/keys"
41
42 // Default allocation of progress bar segments to operations
43 static const int VERIFICATION_PROGRESS_TIME = 60;
44 static const float VERIFICATION_PROGRESS_FRACTION = 0.25;
45 static const float DEFAULT_FILES_PROGRESS_FRACTION = 0.4;
46 static const float DEFAULT_IMAGE_PROGRESS_FRACTION = 0.1;
47
48 // If the package contains an update binary, extract it and run it.
49 static int
try_update_binary(const char * path,ZipArchive * zip,int * wipe_cache)50 try_update_binary(const char *path, ZipArchive *zip, int* wipe_cache) {
51 const ZipEntry* binary_entry =
52 mzFindZipEntry(zip, ASSUMED_UPDATE_BINARY_NAME);
53 if (binary_entry == NULL) {
54 mzCloseZipArchive(zip);
55 return INSTALL_CORRUPT;
56 }
57
58 const char* binary = "/tmp/update_binary";
59 unlink(binary);
60 int fd = creat(binary, 0755);
61 if (fd < 0) {
62 mzCloseZipArchive(zip);
63 LOGE("Can't make %s\n", binary);
64 return INSTALL_ERROR;
65 }
66 bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
67 close(fd);
68 mzCloseZipArchive(zip);
69
70 if (!ok) {
71 LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
72 return INSTALL_ERROR;
73 }
74
75 int pipefd[2];
76 pipe(pipefd);
77
78 // When executing the update binary contained in the package, the
79 // arguments passed are:
80 //
81 // - the version number for this interface
82 //
83 // - an fd to which the program can write in order to update the
84 // progress bar. The program can write single-line commands:
85 //
86 // progress <frac> <secs>
87 // fill up the next <frac> part of of the progress bar
88 // over <secs> seconds. If <secs> is zero, use
89 // set_progress commands to manually control the
90 // progress of this segment of the bar
91 //
92 // set_progress <frac>
93 // <frac> should be between 0.0 and 1.0; sets the
94 // progress bar within the segment defined by the most
95 // recent progress command.
96 //
97 // firmware <"hboot"|"radio"> <filename>
98 // arrange to install the contents of <filename> in the
99 // given partition on reboot.
100 //
101 // (API v2: <filename> may start with "PACKAGE:" to
102 // indicate taking a file from the OTA package.)
103 //
104 // (API v3: this command no longer exists.)
105 //
106 // ui_print <string>
107 // display <string> on the screen.
108 //
109 // - the name of the package zip file.
110 //
111
112 const char** args = (const char**)malloc(sizeof(char*) * 5);
113 args[0] = binary;
114 args[1] = EXPAND(RECOVERY_API_VERSION); // defined in Android.mk
115 char* temp = (char*)malloc(10);
116 sprintf(temp, "%d", pipefd[1]);
117 args[2] = temp;
118 args[3] = (char*)path;
119 args[4] = NULL;
120
121 pid_t pid = fork();
122 if (pid == 0) {
123 close(pipefd[0]);
124 execv(binary, (char* const*)args);
125 fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
126 _exit(-1);
127 }
128 close(pipefd[1]);
129
130 *wipe_cache = 0;
131
132 char buffer[1024];
133 FILE* from_child = fdopen(pipefd[0], "r");
134 while (fgets(buffer, sizeof(buffer), from_child) != NULL) {
135 char* command = strtok(buffer, " \n");
136 if (command == NULL) {
137 continue;
138 } else if (strcmp(command, "progress") == 0) {
139 char* fraction_s = strtok(NULL, " \n");
140 char* seconds_s = strtok(NULL, " \n");
141
142 float fraction = strtof(fraction_s, NULL);
143 int seconds = strtol(seconds_s, NULL, 10);
144
145 ui->ShowProgress(fraction * (1-VERIFICATION_PROGRESS_FRACTION), seconds);
146 } else if (strcmp(command, "set_progress") == 0) {
147 char* fraction_s = strtok(NULL, " \n");
148 float fraction = strtof(fraction_s, NULL);
149 ui->SetProgress(fraction);
150 } else if (strcmp(command, "ui_print") == 0) {
151 char* str = strtok(NULL, "\n");
152 if (str) {
153 ui->Print("%s", str);
154 } else {
155 ui->Print("\n");
156 }
157 } else if (strcmp(command, "wipe_cache") == 0) {
158 *wipe_cache = 1;
159 } else if (strcmp(command, "clear_display") == 0) {
160 ui->SetBackground(RecoveryUI::NONE);
161 } else {
162 LOGE("unknown command [%s]\n", command);
163 }
164 }
165 fclose(from_child);
166
167 int status;
168 waitpid(pid, &status, 0);
169 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
170 LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
171 return INSTALL_ERROR;
172 }
173
174 return INSTALL_SUCCESS;
175 }
176
177 // Reads a file containing one or more public keys as produced by
178 // DumpPublicKey: this is an RSAPublicKey struct as it would appear
179 // as a C source literal, eg:
180 //
181 // "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
182 //
183 // For key versions newer than the original 2048-bit e=3 keys
184 // supported by Android, the string is preceded by a version
185 // identifier, eg:
186 //
187 // "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
188 //
189 // (Note that the braces and commas in this example are actual
190 // characters the parser expects to find in the file; the ellipses
191 // indicate more numbers omitted from this example.)
192 //
193 // The file may contain multiple keys in this format, separated by
194 // commas. The last key must not be followed by a comma.
195 //
196 // Returns NULL if the file failed to parse, or if it contain zero keys.
197 static RSAPublicKey*
load_keys(const char * filename,int * numKeys)198 load_keys(const char* filename, int* numKeys) {
199 RSAPublicKey* out = NULL;
200 *numKeys = 0;
201
202 FILE* f = fopen(filename, "r");
203 if (f == NULL) {
204 LOGE("opening %s: %s\n", filename, strerror(errno));
205 goto exit;
206 }
207
208 {
209 int i;
210 bool done = false;
211 while (!done) {
212 ++*numKeys;
213 out = (RSAPublicKey*)realloc(out, *numKeys * sizeof(RSAPublicKey));
214 RSAPublicKey* key = out + (*numKeys - 1);
215
216 char start_char;
217 if (fscanf(f, " %c", &start_char) != 1) goto exit;
218 if (start_char == '{') {
219 // a version 1 key has no version specifier.
220 key->exponent = 3;
221 } else if (start_char == 'v') {
222 int version;
223 if (fscanf(f, "%d {", &version) != 1) goto exit;
224 if (version == 2) {
225 key->exponent = 65537;
226 } else {
227 goto exit;
228 }
229 }
230
231 if (fscanf(f, " %i , 0x%x , { %u",
232 &(key->len), &(key->n0inv), &(key->n[0])) != 3) {
233 goto exit;
234 }
235 if (key->len != RSANUMWORDS) {
236 LOGE("key length (%d) does not match expected size\n", key->len);
237 goto exit;
238 }
239 for (i = 1; i < key->len; ++i) {
240 if (fscanf(f, " , %u", &(key->n[i])) != 1) goto exit;
241 }
242 if (fscanf(f, " } , { %u", &(key->rr[0])) != 1) goto exit;
243 for (i = 1; i < key->len; ++i) {
244 if (fscanf(f, " , %u", &(key->rr[i])) != 1) goto exit;
245 }
246 fscanf(f, " } } ");
247
248 // if the line ends in a comma, this file has more keys.
249 switch (fgetc(f)) {
250 case ',':
251 // more keys to come.
252 break;
253
254 case EOF:
255 done = true;
256 break;
257
258 default:
259 LOGE("unexpected character between keys\n");
260 goto exit;
261 }
262
263 LOGI("read key e=%d\n", key->exponent);
264 }
265 }
266
267 fclose(f);
268 return out;
269
270 exit:
271 if (f) fclose(f);
272 free(out);
273 *numKeys = 0;
274 return NULL;
275 }
276
277 static int
really_install_package(const char * path,int * wipe_cache)278 really_install_package(const char *path, int* wipe_cache)
279 {
280 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
281 ui->Print("Finding update package...\n");
282 ui->SetProgressType(RecoveryUI::INDETERMINATE);
283 LOGI("Update location: %s\n", path);
284
285 if (ensure_path_mounted(path) != 0) {
286 LOGE("Can't mount %s\n", path);
287 return INSTALL_CORRUPT;
288 }
289
290 ui->Print("Opening update package...\n");
291
292 int numKeys;
293 RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
294 if (loadedKeys == NULL) {
295 LOGE("Failed to load keys\n");
296 return INSTALL_CORRUPT;
297 }
298 LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);
299
300 // Give verification half the progress bar...
301 ui->Print("Verifying update package...\n");
302 ui->SetProgressType(RecoveryUI::DETERMINATE);
303 ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
304
305 int err;
306 err = verify_file(path, loadedKeys, numKeys);
307 free(loadedKeys);
308 LOGI("verify_file returned %d\n", err);
309 if (err != VERIFY_SUCCESS) {
310 LOGE("signature verification failed\n");
311 return INSTALL_CORRUPT;
312 }
313
314 /* Try to open the package.
315 */
316 ZipArchive zip;
317 err = mzOpenZipArchive(path, &zip);
318 if (err != 0) {
319 LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
320 return INSTALL_CORRUPT;
321 }
322
323 /* Verify and install the contents of the package.
324 */
325 ui->Print("Installing update...\n");
326 return try_update_binary(path, &zip, wipe_cache);
327 }
328
329 int
install_package(const char * path,int * wipe_cache,const char * install_file)330 install_package(const char* path, int* wipe_cache, const char* install_file)
331 {
332 FILE* install_log = fopen_path(install_file, "w");
333 if (install_log) {
334 fputs(path, install_log);
335 fputc('\n', install_log);
336 } else {
337 LOGE("failed to open last_install: %s\n", strerror(errno));
338 }
339 int result = really_install_package(path, wipe_cache);
340 if (install_log) {
341 fputc(result == INSTALL_SUCCESS ? '1' : '0', install_log);
342 fputc('\n', install_log);
343 fclose(install_log);
344 }
345 return result;
346 }
347