OSDN Git Service

Revert "system/extra: include more of what you use."
[android-x86/system-extras.git] / verity / verify_boot_signature.c
1 /*
2  * Copyright (C) 2014 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 #define _LARGEFILE64_SOURCE
18
19 #include <endian.h>
20 #include <stddef.h>
21 #include <stdint.h>
22 #include <string.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <errno.h>
28
29 #include <openssl/asn1.h>
30 #include <openssl/asn1t.h>
31 #include <openssl/err.h>
32 #include <openssl/evp.h>
33 #include <openssl/rsa.h>
34 #include <openssl/x509.h>
35
36 #include "bootimg.h"
37
38 #define FORMAT_VERSION 1
39 #define BUFFER_SIZE (1024 * 1024)
40
41 typedef struct {
42     ASN1_STRING *target;
43     ASN1_INTEGER *length;
44 } AuthAttrs;
45
46 ASN1_SEQUENCE(AuthAttrs) = {
47     ASN1_SIMPLE(AuthAttrs, target, ASN1_PRINTABLE),
48     ASN1_SIMPLE(AuthAttrs, length, ASN1_INTEGER)
49 } ASN1_SEQUENCE_END(AuthAttrs)
50
51 IMPLEMENT_ASN1_FUNCTIONS(AuthAttrs)
52
53 typedef struct {
54     ASN1_INTEGER *formatVersion;
55     X509 *certificate;
56     X509_ALGOR *algorithmIdentifier;
57     AuthAttrs *authenticatedAttributes;
58     ASN1_OCTET_STRING *signature;
59 } BootSignature;
60
61 ASN1_SEQUENCE(BootSignature) = {
62     ASN1_SIMPLE(BootSignature, formatVersion, ASN1_INTEGER),
63     ASN1_SIMPLE(BootSignature, certificate, X509),
64     ASN1_SIMPLE(BootSignature, algorithmIdentifier, X509_ALGOR),
65     ASN1_SIMPLE(BootSignature, authenticatedAttributes, AuthAttrs),
66     ASN1_SIMPLE(BootSignature, signature, ASN1_OCTET_STRING)
67 } ASN1_SEQUENCE_END(BootSignature)
68
69 IMPLEMENT_ASN1_FUNCTIONS(BootSignature)
70
71 static BIO *g_error = NULL;
72
73 #if defined(OPENSSL_IS_BORINGSSL)
74 /* In BoringSSL, ERR_print_errors has been moved to the BIO functions in order
75  * to avoid the incorrect dependency of ERR on BIO. */
76 static void ERR_print_errors(BIO *bio) {
77     BIO_print_errors(bio);
78 }
79 #endif
80
81 /**
82  * Rounds n up to the nearest multiple of page_size
83  * @param n The value to round
84  * @param page_size Page size
85  */
86 static uint64_t page_align(uint64_t n, uint64_t page_size)
87 {
88     return (((n + page_size - 1) / page_size) * page_size);
89 }
90
91 /**
92  * Calculates the offset to the beginning of the BootSignature block
93  * based on the boot image header. The signature will start after the
94  * the boot image contents.
95  * @param fd File descriptor to the boot image
96  * @param offset Receives the offset in bytes
97  */
98 static int get_signature_offset(int fd, off64_t *offset)
99 {
100     int i;
101     struct boot_img_hdr hdr;
102
103     if (!offset) {
104         return -1;
105     }
106
107     if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
108         return -1;
109     }
110
111     if (memcmp(BOOT_MAGIC, hdr.magic, BOOT_MAGIC_SIZE) != 0) {
112         printf("Invalid boot image: missing magic\n");
113         return -1;
114     }
115
116     if (!hdr.page_size) {
117         printf("Invalid boot image: page size must be non-zero\n");
118         return -1;
119     }
120
121     *offset = page_align(hdr.page_size
122                     + page_align(hdr.kernel_size,  hdr.page_size)
123                     + page_align(hdr.ramdisk_size, hdr.page_size)
124                     + page_align(hdr.second_size,  hdr.page_size),
125                 hdr.page_size);
126
127     return 0;
128 }
129
130 /**
131  * Reads and parses the ASN.1 BootSignature block from the given offset
132  * @param fd File descriptor to the boot image
133  * @param offset Offset from the beginning of file to the signature
134  * @param bs Pointer to receive the BootImage structure
135  */
136 static int read_signature(int fd, off64_t offset, BootSignature **bs)
137 {
138     BIO *in = NULL;
139
140     if (!bs) {
141         return -1;
142     }
143
144     if (lseek64(fd, offset, SEEK_SET) == -1) {
145         return -1;
146     }
147
148     if ((in = BIO_new_fd(fd, BIO_NOCLOSE)) == NULL) {
149         ERR_print_errors(g_error);
150         return -1;
151     }
152
153     if ((*bs = ASN1_item_d2i_bio(ASN1_ITEM_rptr(BootSignature), in, bs)) == NULL) {
154         ERR_print_errors(g_error);
155         BIO_free(in);
156         return -1;
157     }
158
159     BIO_free(in);
160     return 0;
161 }
162
163 /**
164  * Validates the format of the boot signature block, and checks that
165  * the length in authenticated attributes matches the actual length of
166  * the image.
167  * @param bs The boot signature block to validate
168  * @param length The actual length of the boot image without the signature
169  */
170 static int validate_signature_block(const BootSignature *bs, uint64_t length)
171 {
172     BIGNUM expected;
173     BIGNUM value;
174     int rc = -1;
175
176     if (!bs) {
177         return -1;
178     }
179
180     BN_init(&expected);
181     BN_init(&value);
182
183     /* Confirm that formatVersion matches our supported version */
184     if (!BN_set_word(&expected, FORMAT_VERSION)) {
185         ERR_print_errors(g_error);
186         goto vsb_done;
187     }
188
189     ASN1_INTEGER_to_BN(bs->formatVersion, &value);
190
191     if (BN_cmp(&expected, &value) != 0) {
192         printf("Unsupported signature version\n");
193         goto vsb_done;
194     }
195
196     BN_clear(&expected);
197     BN_clear(&value);
198
199     /* Confirm that the length of the image matches with the length in
200         the authenticated attributes */
201     length = htobe64(length);
202     BN_bin2bn((const unsigned char *) &length, sizeof(length), &expected);
203
204     ASN1_INTEGER_to_BN(bs->authenticatedAttributes->length, &value);
205
206     if (BN_cmp(&expected, &value) != 0) {
207         printf("Image length doesn't match signature attributes\n");
208         goto vsb_done;
209     }
210
211     rc = 0;
212
213 vsb_done:
214     BN_free(&expected);
215     BN_free(&value);
216
217     return rc;
218 }
219
220 /**
221  * Creates a SHA-256 hash from the boot image contents and the encoded
222  * authenticated attributes.
223  * @param fd File descriptor to the boot image
224  * @param length Length of the boot image without the signature block
225  * @param aa Pointer to AuthAttrs
226  * @param digest Pointer to a buffer where the hash is written
227  */
228 static int hash_image(int fd, uint64_t length, const AuthAttrs *aa,
229         unsigned char *digest)
230 {
231     EVP_MD_CTX *ctx = NULL;
232     int rc = -1;
233
234     ssize_t bytes = 0;
235     unsigned char *attrs = NULL;
236     unsigned char *buffer = NULL;
237     unsigned char *p = NULL;
238     uint64_t total = 0;
239
240     if (!aa || !digest) {
241         goto hi_done;
242     }
243
244     if ((buffer = malloc(BUFFER_SIZE)) == NULL) {
245         goto hi_done;
246     }
247
248     if (lseek64(fd, 0, SEEK_SET) != 0) {
249         goto hi_done;
250     }
251
252     if ((ctx = EVP_MD_CTX_create()) == NULL) {
253         ERR_print_errors(g_error);
254         goto hi_done;
255     }
256
257     EVP_DigestInit(ctx, EVP_sha256());
258
259     do {
260         bytes = BUFFER_SIZE;
261
262         if ((length - total) < BUFFER_SIZE) {
263             bytes = length - total;
264         }
265
266         if ((bytes = read(fd, buffer, bytes)) == -1) {
267             printf("%s\n", strerror(errno));
268             goto hi_done;
269         }
270
271         EVP_DigestUpdate(ctx, buffer, bytes);
272         total += bytes;
273     } while (total < length);
274
275     if ((bytes = i2d_AuthAttrs((AuthAttrs *) aa, NULL)) < 0) {
276         ERR_print_errors(g_error);
277         goto hi_done;
278     }
279
280     if ((attrs = OPENSSL_malloc(bytes)) == NULL) {
281         ERR_print_errors(g_error);
282         goto hi_done;
283     }
284
285     p = attrs;
286
287     if (i2d_AuthAttrs((AuthAttrs *) aa, &p) < 0) {
288         ERR_print_errors(g_error);
289         goto hi_done;
290     }
291
292     EVP_DigestUpdate(ctx, attrs, bytes);
293     EVP_DigestFinal(ctx, digest, NULL);
294
295     rc = 0;
296
297 hi_done:
298     if (buffer) {
299         free(buffer);
300     }
301
302     if (ctx) {
303         EVP_MD_CTX_destroy(ctx);
304     }
305
306     if (attrs) {
307         OPENSSL_free(attrs);
308     }
309
310     return rc;
311 }
312
313 /**
314  * Verifies the RSA signature
315  * @param fd File descriptor to the boot image
316  * @param length Length of the boot image without the signature block
317  * @param bs The boot signature block
318  */
319 static int verify_signature(int fd, uint64_t length, const BootSignature *bs)
320 {
321     int rc = -1;
322     EVP_PKEY *pkey = NULL;
323     RSA *rsa = NULL;
324     unsigned char digest[SHA256_DIGEST_LENGTH];
325
326     if (!bs) {
327         goto vs_done;
328     }
329
330     if (hash_image(fd, length, bs->authenticatedAttributes, digest) == -1) {
331         goto vs_done;
332     }
333
334     if ((pkey = X509_get_pubkey(bs->certificate)) == NULL) {
335         ERR_print_errors(g_error);
336         goto vs_done;
337     }
338
339     if ((rsa = EVP_PKEY_get1_RSA(pkey)) == NULL) {
340         ERR_print_errors(g_error);
341         goto vs_done;
342     }
343
344     if (!RSA_verify(NID_sha256, digest, SHA256_DIGEST_LENGTH,
345                 bs->signature->data, bs->signature->length, rsa)) {
346         ERR_print_errors(g_error);
347         goto vs_done;
348     }
349
350     rc = 0;
351
352 vs_done:
353     if (pkey) {
354         EVP_PKEY_free(pkey);
355     }
356
357     if (rsa) {
358         RSA_free(rsa);
359     }
360
361     return rc;
362 }
363
364 /**
365  * Given the file name of a signed boot image, verifies the signature
366  * @param image_file Name of the boot image file
367  */
368 static int verify(const char *image_file)
369 {
370     BootSignature *bs = NULL;
371     int fd = -1;
372     int rc = 1;
373     off64_t offset = 0;
374
375     if (!image_file) {
376         return rc;
377     }
378
379     if ((fd = open(image_file, O_RDONLY | O_LARGEFILE)) == -1) {
380         return rc;
381     }
382
383     if (get_signature_offset(fd, &offset) == -1) {
384         goto out;
385     }
386
387     if (read_signature(fd, offset, &bs) == -1) {
388         goto out;
389     }
390
391     if (validate_signature_block(bs, offset) == -1) {
392         goto out;
393     }
394
395     if (verify_signature(fd, offset, bs) == -1) {
396         goto out;
397     }
398
399     printf("Signature is VALID\n");
400     rc = 0;
401
402 out:
403     if (bs) {
404         BootSignature_free(bs);
405     }
406
407     if (fd != -1) {
408         close(fd);
409     }
410
411     return rc;
412 }
413
414 static void usage()
415 {
416     printf("Usage: verify_boot_signature <path-to-boot-image>\n");
417 }
418
419 int main(int argc, char *argv[])
420 {
421     if (argc != 2) {
422         usage();
423         return 1;
424     }
425
426     /* BIO descriptor for logging OpenSSL errors to stderr */
427     if ((g_error = BIO_new_fd(STDERR_FILENO, BIO_NOCLOSE)) == NULL) {
428         printf("Failed to allocate a BIO handle for error output\n");
429         return 1;
430     }
431
432     ERR_load_crypto_strings();
433
434     return verify(argv[1]);
435 }