13c5f5e63f7094bb9ac2b14046cd4237134a0b07
[vboot.git] / futility / vb1_helper.c
1 /*
2  * Copyright 2014 The Chromium OS Authors. All rights reserved.
3  * Use of this source code is governed by a BSD-style license that can be
4  * found in the LICENSE file.
5  */
6
7 #include <errno.h>
8 #include <inttypes.h>           /* For PRIu64 */
9 #include <stdio.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <openssl/rsa.h>
13
14 #include "2sysincludes.h"
15 #include "2api.h"
16 #include "2common.h"
17 #include "2rsa.h"
18 #include "2sha.h"
19 #include "file_type.h"
20 #include "futility.h"
21 #include "host_common.h"
22 #include "kernel_blob.h"
23 #include "util_misc.h"
24 #include "vb1_helper.h"
25 #include "vb2_common.h"
26
27 const char *vb1_crypto_name(uint32_t algo)
28 {
29         return algo < kNumAlgorithms ? algo_strings[algo] : "(invalid)";
30 }
31
32 /****************************************************************************/
33 /* Here are globals containing all the bits & pieces I'm working on.
34  *
35  * kernel vblock    = keyblock + kernel preamble + padding to 64K (or whatever)
36  * kernel blob      = 32-bit kernel + config file + params + bootloader stub +
37  *                    vmlinuz_header
38  * kernel partition = kernel vblock + kernel blob
39  *
40  * The VbKernelPreambleHeader.preamble_size includes the padding.
41  */
42
43 /* The keyblock, preamble, and kernel blob are kept in separate places. */
44 static VbKeyBlockHeader *g_keyblock;
45 static VbKernelPreambleHeader *g_preamble;
46 static uint8_t *g_kernel_blob_data;
47 static uint64_t g_kernel_blob_size;
48
49 /* These refer to individual parts within the kernel blob. */
50 static uint8_t *g_kernel_data;
51 static uint64_t g_kernel_size;
52 static uint8_t *g_config_data;
53 static uint64_t g_config_size;
54 static uint8_t *g_param_data;
55 static uint64_t g_param_size;
56 static uint8_t *g_bootloader_data;
57 static uint64_t g_bootloader_size;
58 static uint8_t *g_vmlinuz_header_data;
59 static uint64_t g_vmlinuz_header_size;
60
61 static uint64_t g_ondisk_bootloader_addr;
62 static uint64_t g_ondisk_vmlinuz_header_addr;
63
64
65 /*
66  * Read the kernel command line from a file. Get rid of \n characters along
67  * the way and verify that the line fits into a 4K buffer.
68  *
69  * Return the buffer contaning the line on success (and set the line length
70  * using the passed in parameter), or NULL in case something goes wrong.
71  */
72 uint8_t *ReadConfigFile(const char *config_file, uint64_t *config_size)
73 {
74         uint8_t *config_buf;
75         int i;
76
77         config_buf = ReadFile(config_file, config_size);
78         if (!config_buf)
79                 return NULL;
80         Debug(" config file size=0x%" PRIx64 "\n", *config_size);
81         if (CROS_CONFIG_SIZE <= *config_size) { /* room for trailing '\0' */
82                 fprintf(stderr, "Config file %s is too large (>= %d bytes)\n",
83                         config_file, CROS_CONFIG_SIZE);
84                 return NULL;
85         }
86
87         /* Replace newlines with spaces */
88         for (i = 0; i < *config_size; i++)
89                 if ('\n' == config_buf[i])
90                         config_buf[i] = ' ';
91
92         return config_buf;
93 }
94
95 /****************************************************************************/
96
97 /* Return the smallest integral multiple of [alignment] that is equal
98  * to or greater than [val]. Used to determine the number of
99  * pages/sectors/blocks/whatever needed to contain [val]
100  * items/bytes/etc. */
101 static uint64_t roundup(uint64_t val, uint64_t alignment)
102 {
103         uint64_t rem = val % alignment;
104         if (rem)
105                 return val + (alignment - rem);
106         return val;
107 }
108
109 /* Match regexp /\b--\b/ to delimit the start of the kernel commandline. If we
110  * don't find one, we'll use the whole thing. */
111 static unsigned int find_cmdline_start(uint8_t *buf_ptr, unsigned int max_len)
112 {
113         char *input = (char *)buf_ptr;
114         int start = 0;
115         int i;
116         for (i = 0; i < max_len - 1 && input[i]; i++) {
117                 if ('-' == input[i] && '-' == input[i + 1]) {
118                         if ((i == 0 || ' ' == input[i - 1]) &&
119                             (i + 2 >= max_len || ' ' == input[i + 2])) {
120                                 /* found "--" with nothing before or after it */
121                                 start = i + 2;  /* hope for a trailing '\0' */
122                                 break;
123                         }
124                 }
125         }
126         while (' ' == input[start])     /* skip leading spaces */
127                 start++;
128
129         return start;
130 }
131
132 /* Offset of kernel command line string from the start of the kernel blob */
133 uint64_t kernel_cmd_line_offset(const struct vb2_kernel_preamble *preamble)
134 {
135         return preamble->bootloader_address - preamble->body_load_address -
136             CROS_CONFIG_SIZE - CROS_PARAMS_SIZE;
137 }
138
139 /* Returns the size of the 32-bit kernel, or negative on error. */
140 static int KernelSize(uint8_t *kernel_buf, uint64_t kernel_size,
141                       enum arch_t arch)
142 {
143         uint64_t kernel32_start = 0;
144         struct linux_kernel_params *lh;
145
146         /* Except for x86, the kernel is the kernel. */
147         if (arch != ARCH_X86)
148                 return kernel_size;
149
150         /* The first part of the x86 vmlinuz is a header, followed by
151          * a real-mode boot stub. We only want the 32-bit part. */
152         lh = (struct linux_kernel_params *)kernel_buf;
153         kernel32_start = (lh->setup_sects + 1) << 9;
154         if (kernel32_start >= kernel_size) {
155                 fprintf(stderr, "Malformed kernel\n");
156                 return -1;
157         }
158         return kernel_size - kernel32_start;
159 }
160
161 /* This extracts g_kernel_* and g_param_* from a standard vmlinuz file.
162  * It returns nonzero on error. */
163 static int PickApartVmlinuz(uint8_t *kernel_buf, uint64_t kernel_size,
164                             enum arch_t arch,
165                             uint64_t kernel_body_load_address)
166 {
167         uint64_t kernel32_start = 0;
168         uint64_t kernel32_size = kernel_size;
169         struct linux_kernel_params *lh, *params;
170
171         /* Except for x86, the kernel is the kernel. */
172         if (arch == ARCH_X86) {
173                 /* The first part of the x86 vmlinuz is a header, followed by
174                  * a real-mode boot stub. We only want the 32-bit part. */
175                 lh = (struct linux_kernel_params *)kernel_buf;
176                 kernel32_start = (lh->setup_sects + 1) << 9;
177                 if (kernel32_start >= kernel_size) {
178                         fprintf(stderr, "Malformed kernel\n");
179                         return -1;
180                 }
181                 kernel32_size = kernel_size - kernel32_start;
182
183                 Debug(" kernel16_start=0x%" PRIx64 "\n", 0);
184                 Debug(" kernel16_size=0x%" PRIx64 "\n", kernel32_start);
185
186                 /* Copy the original zeropage data from kernel_buf into
187                  * g_param_data, then tweak a few fields for our purposes */
188                 params = (struct linux_kernel_params *)(g_param_data);
189                 Memcpy(&(params->setup_sects), &(lh->setup_sects),
190                        offsetof(struct linux_kernel_params, e820_entries)
191                        - offsetof(struct linux_kernel_params, setup_sects));
192                 params->boot_flag = 0;
193                 params->ramdisk_image = 0;      /* we don't support initrd */
194                 params->ramdisk_size = 0;
195                 params->type_of_loader = 0xff;
196                 /* We need to point to the kernel commandline arg. On disk, it
197                  * will come right after the 32-bit part of the kernel. */
198                 params->cmd_line_ptr = kernel_body_load_address +
199                         roundup(kernel32_size, CROS_ALIGN) +
200                         find_cmdline_start(g_config_data, g_config_size);
201                 Debug(" cmdline_addr=0x%x\n", params->cmd_line_ptr);
202                 Debug(" version=0x%x\n", params->version);
203                 Debug(" kernel_alignment=0x%x\n", params->kernel_alignment);
204                 Debug(" relocatable_kernel=0x%x\n", params->relocatable_kernel);
205                 /* Add a fake e820 memory map with 2 entries. */
206                 params->n_e820_entry = 2;
207                 params->e820_entries[0].start_addr = 0x00000000;
208                 params->e820_entries[0].segment_size = 0x00001000;
209                 params->e820_entries[0].segment_type = E820_TYPE_RAM;
210                 params->e820_entries[1].start_addr = 0xfffff000;
211                 params->e820_entries[1].segment_size = 0x00001000;
212                 params->e820_entries[1].segment_type = E820_TYPE_RESERVED;
213         }
214
215         Debug(" kernel32_start=0x%" PRIx64 "\n", kernel32_start);
216         Debug(" kernel32_size=0x%" PRIx64 "\n", kernel32_size);
217
218         /* Keep just the 32-bit kernel. */
219         if (kernel32_size) {
220                 g_kernel_size = kernel32_size;
221                 Memcpy(g_kernel_data, kernel_buf + kernel32_start,
222                        g_kernel_size);
223         }
224
225         /* done */
226         return 0;
227 }
228
229 /* Split a kernel blob into separate g_kernel, g_param, g_config,
230  * g_bootloader, and g_vmlinuz_header parts. */
231 static void UnpackKernelBlob(uint8_t *kernel_blob_data)
232 {
233         uint64_t now;
234         uint64_t vmlinuz_header_size = 0;
235         uint64_t vmlinuz_header_address = 0;
236
237         /* We have to work backwards from the end, because the preamble
238            only describes the bootloader and vmlinuz stubs. */
239
240         /* Vmlinuz Header is at the end */
241         if (VbGetKernelVmlinuzHeader(g_preamble,
242                                      &vmlinuz_header_address,
243                                      &vmlinuz_header_size)
244             != VBOOT_SUCCESS) {
245                 fprintf(stderr, "Unable to retrieve Vmlinuz Header!");
246                 return;
247         }
248         if (vmlinuz_header_size) {
249                 now = vmlinuz_header_address - g_preamble->body_load_address;
250                 g_vmlinuz_header_size = vmlinuz_header_size;
251                 g_vmlinuz_header_data = kernel_blob_data + now;
252
253                 Debug("vmlinuz_header_size     = 0x%" PRIx64 "\n",
254                       g_vmlinuz_header_size);
255                 Debug("vmlinuz_header_ofs      = 0x%" PRIx64 "\n", now);
256         }
257
258         /* Where does the bootloader stub begin? */
259         now = g_preamble->bootloader_address - g_preamble->body_load_address;
260
261         /* Bootloader is at the end */
262         g_bootloader_size = g_preamble->bootloader_size;
263         g_bootloader_data = kernel_blob_data + now;
264         /* TODO: What to do if this is beyond the end of the blob? */
265
266         Debug("bootloader_size     = 0x%" PRIx64 "\n", g_bootloader_size);
267         Debug("bootloader_ofs      = 0x%" PRIx64 "\n", now);
268
269         /* Before that is the params */
270         now -= CROS_PARAMS_SIZE;
271         g_param_size = CROS_PARAMS_SIZE;
272         g_param_data = kernel_blob_data + now;
273         Debug("param_ofs           = 0x%" PRIx64 "\n", now);
274
275         /* Before that is the config */
276         now -= CROS_CONFIG_SIZE;
277         g_config_size = CROS_CONFIG_SIZE;
278         g_config_data = kernel_blob_data + now;
279         Debug("config_ofs          = 0x%" PRIx64 "\n", now);
280
281         /* The kernel starts at offset 0 and extends up to the config */
282         g_kernel_data = kernel_blob_data;
283         g_kernel_size = now;
284         Debug("kernel_size         = 0x%" PRIx64 "\n", g_kernel_size);
285 }
286
287
288 /* Replaces the config section of the specified kernel blob.
289  * Return nonzero on error. */
290 int UpdateKernelBlobConfig(uint8_t *kblob_data, uint64_t kblob_size,
291                            uint8_t *config_data, uint64_t config_size)
292 {
293         /* We should have already examined this blob. If not, we could do it
294          * again, but it's more likely due to an error. */
295         if (kblob_data != g_kernel_blob_data ||
296             kblob_size != g_kernel_blob_size) {
297                 fprintf(stderr, "Trying to update some other blob\n");
298                 return -1;
299         }
300
301         Memset(g_config_data, 0, g_config_size);
302         Memcpy(g_config_data, config_data, config_size);
303
304         return 0;
305 }
306
307 /* Split a kernel partition into separate vblock and blob parts. */
308 uint8_t *UnpackKPart(uint8_t *kpart_data, uint64_t kpart_size,
309                      uint64_t padding,
310                      VbKeyBlockHeader **keyblock_ptr,
311                      VbKernelPreambleHeader **preamble_ptr,
312                      uint64_t *blob_size_ptr)
313 {
314         VbKeyBlockHeader *keyblock;
315         VbKernelPreambleHeader *preamble;
316         uint64_t vmlinuz_header_size = 0;
317         uint64_t vmlinuz_header_address = 0;
318         uint64_t now = 0;
319         uint32_t flags = 0;
320
321         /* Sanity-check the keyblock */
322         keyblock = (VbKeyBlockHeader *)kpart_data;
323         Debug("Keyblock is 0x%" PRIx64 " bytes\n", keyblock->key_block_size);
324         now += keyblock->key_block_size;
325         if (now > kpart_size) {
326                 fprintf(stderr,
327                         "key_block_size advances past the end of the blob\n");
328                 return NULL;
329         }
330         if (now > padding) {
331                 fprintf(stderr,
332                         "key_block_size advances past %" PRIu64
333                         " byte padding\n",
334                         padding);
335                 return NULL;
336         }
337
338         /* LGTM */
339         g_keyblock = keyblock;
340
341         /* And the preamble */
342         preamble = (VbKernelPreambleHeader *)(kpart_data + now);
343         Debug("Preamble is 0x%" PRIx64 " bytes\n", preamble->preamble_size);
344         now += preamble->preamble_size;
345         if (now > kpart_size) {
346                 fprintf(stderr,
347                         "preamble_size advances past the end of the blob\n");
348                 return NULL;
349         }
350         if (now > padding) {
351                 fprintf(stderr, "preamble_size advances past %" PRIu64
352                         " byte padding\n", padding);
353                 return NULL;
354         }
355         /* LGTM */
356         Debug(" kernel_version = %d\n", preamble->kernel_version);
357         Debug(" bootloader_address = 0x%" PRIx64 "\n",
358               preamble->bootloader_address);
359         Debug(" bootloader_size = 0x%" PRIx64 "\n", preamble->bootloader_size);
360         Debug(" kern_blob_size = 0x%" PRIx64 "\n",
361               preamble->body_signature.data_size);
362
363         if (VbKernelHasFlags(preamble) == VBOOT_SUCCESS)
364                 flags = preamble->flags;
365         Debug(" flags = 0x%" PRIx32 "\n", flags);
366
367         g_preamble = preamble;
368         g_ondisk_bootloader_addr = g_preamble->bootloader_address;
369
370         if (VbGetKernelVmlinuzHeader(preamble,
371                                      &vmlinuz_header_address,
372                                      &vmlinuz_header_size)
373             != VBOOT_SUCCESS) {
374                 fprintf(stderr, "Unable to retrieve Vmlinuz Header!");
375                 return NULL;
376         }
377         if (vmlinuz_header_size) {
378                 Debug(" vmlinuz_header_address = 0x%" PRIx64 "\n",
379                       vmlinuz_header_address);
380                 Debug(" vmlinuz_header_size = 0x%" PRIx64 "\n",
381                       vmlinuz_header_size);
382                 g_ondisk_vmlinuz_header_addr = vmlinuz_header_address;
383         }
384
385         Debug("kernel blob is at offset 0x%" PRIx64 "\n", now);
386         g_kernel_blob_data = kpart_data + now;
387         g_kernel_blob_size = preamble->body_signature.data_size;
388
389         /* Sanity check */
390         if (g_kernel_blob_size < preamble->body_signature.data_size)
391                 fprintf(stderr,
392                         "Warning: kernel file only has 0x%" PRIx64 " bytes\n",
393                         g_kernel_blob_size);
394
395         /* Update the blob pointers */
396         UnpackKernelBlob(g_kernel_blob_data);
397
398         if (keyblock_ptr)
399                 *keyblock_ptr = keyblock;
400         if (preamble_ptr)
401                 *preamble_ptr = preamble;
402         if (blob_size_ptr)
403                 *blob_size_ptr = g_kernel_blob_size;
404
405         return g_kernel_blob_data;
406 }
407
408 uint8_t *SignKernelBlob(uint8_t *kernel_blob, uint64_t kernel_size,
409                         uint64_t padding,
410                         int version, uint64_t kernel_body_load_address,
411                         VbKeyBlockHeader *keyblock, VbPrivateKey *signpriv_key,
412                         uint32_t flags, uint64_t *vblock_size_ptr)
413 {
414         VbSignature *body_sig;
415         VbKernelPreambleHeader *preamble;
416         uint64_t min_size = padding > keyblock->key_block_size
417                 ? padding - keyblock->key_block_size : 0;
418         void *outbuf;
419         uint64_t outsize;
420
421         /* Sign the kernel data */
422         body_sig = CalculateSignature(kernel_blob, kernel_size, signpriv_key);
423         if (!body_sig) {
424                 fprintf(stderr, "Error calculating body signature\n");
425                 return NULL;
426         }
427
428         /* Create preamble */
429         preamble = CreateKernelPreamble(version,
430                                         kernel_body_load_address,
431                                         g_ondisk_bootloader_addr,
432                                         g_bootloader_size,
433                                         body_sig,
434                                         g_ondisk_vmlinuz_header_addr,
435                                         g_vmlinuz_header_size,
436                                         flags,
437                                         min_size,
438                                         signpriv_key);
439         if (!preamble) {
440                 fprintf(stderr, "Error creating preamble.\n");
441                 return 0;
442         }
443
444         outsize = keyblock->key_block_size + preamble->preamble_size;
445         outbuf = malloc(outsize);
446         Memset(outbuf, 0, outsize);
447         Memcpy(outbuf, keyblock, keyblock->key_block_size);
448         Memcpy(outbuf + keyblock->key_block_size,
449                preamble, preamble->preamble_size);
450
451         if (vblock_size_ptr)
452                 *vblock_size_ptr = outsize;
453         return outbuf;
454 }
455
456 /* Returns zero on success */
457 int WriteSomeParts(const char *outfile,
458                    void *part1_data, uint64_t part1_size,
459                    void *part2_data, uint64_t part2_size)
460 {
461         FILE *f;
462
463         /* Write the output file */
464         Debug("writing %s with 0x%" PRIx64 ", 0x%" PRIx64 "\n",
465               outfile, part1_size, part2_size);
466
467         f = fopen(outfile, "wb");
468         if (!f) {
469                 fprintf(stderr, "Can't open output file %s: %s\n",
470                         outfile, strerror(errno));
471                 return -1;
472         }
473
474         if (part1_data && part1_size) {
475                 if (1 != fwrite(part1_data, part1_size, 1, f)) {
476                         fprintf(stderr, "Can't write output file %s: %s\n",
477                                 outfile, strerror(errno));
478                         fclose(f);
479                         unlink(outfile);
480                         return -1;
481                 }
482         }
483
484         if (part2_data && part2_size) {
485                 if (1 != fwrite(part2_data, part2_size, 1, f)) {
486                         fprintf(stderr, "Can't write output file %s: %s\n",
487                                 outfile, strerror(errno));
488                         fclose(f);
489                         unlink(outfile);
490                         return -1;
491                 }
492         }
493
494         fclose(f);
495
496         /* Success */
497         return 0;
498 }
499
500 /* Returns 0 on success */
501 int VerifyKernelBlob(uint8_t *kernel_blob,
502                      uint64_t kernel_size,
503                      VbPublicKey *signpub_key,
504                      const char *keyblock_outfile,
505                      uint64_t min_version)
506 {
507         VbPublicKey *data_key;
508         RSAPublicKey *rsa;
509         int rv = -1;
510         uint64_t vmlinuz_header_size = 0;
511         uint64_t vmlinuz_header_address = 0;
512
513         if (0 != KeyBlockVerify(g_keyblock, g_keyblock->key_block_size,
514                                 signpub_key, (0 == signpub_key))) {
515                 fprintf(stderr, "Error verifying key block.\n");
516                 goto done;
517         }
518
519         printf("Key block:\n");
520         data_key = &g_keyblock->data_key;
521         printf("  Signature:           %s\n",
522                signpub_key ? "valid" : "ignored");
523         printf("  Size:                0x%" PRIx64 "\n",
524                g_keyblock->key_block_size);
525         printf("  Flags:               %" PRIu64 " ",
526                g_keyblock->key_block_flags);
527         if (g_keyblock->key_block_flags & KEY_BLOCK_FLAG_DEVELOPER_0)
528                 printf(" !DEV");
529         if (g_keyblock->key_block_flags & KEY_BLOCK_FLAG_DEVELOPER_1)
530                 printf(" DEV");
531         if (g_keyblock->key_block_flags & KEY_BLOCK_FLAG_RECOVERY_0)
532                 printf(" !REC");
533         if (g_keyblock->key_block_flags & KEY_BLOCK_FLAG_RECOVERY_1)
534                 printf(" REC");
535         printf("\n");
536         printf("  Data key algorithm:  %" PRIu64 " %s\n", data_key->algorithm,
537                (data_key->algorithm < kNumAlgorithms ?
538                 algo_strings[data_key->algorithm] : "(invalid)"));
539         printf("  Data key version:    %" PRIu64 "\n", data_key->key_version);
540         printf("  Data key sha1sum:    %s\n",
541                packed_key_sha1_string((struct vb2_packed_key *)data_key));
542
543         if (keyblock_outfile) {
544                 FILE *f = NULL;
545                 f = fopen(keyblock_outfile, "wb");
546                 if (!f)  {
547                         fprintf(stderr, "Can't open key block file %s: %s\n",
548                                 keyblock_outfile, strerror(errno));
549                         goto done;
550                 }
551                 if (1 != fwrite(g_keyblock, g_keyblock->key_block_size, 1, f)) {
552                         fprintf(stderr, "Can't write key block file %s: %s\n",
553                                 keyblock_outfile, strerror(errno));
554                         fclose(f);
555                         goto done;
556                 }
557                 fclose(f);
558         }
559
560         if (data_key->key_version < (min_version >> 16)) {
561                 fprintf(stderr, "Data key version %" PRIu64
562                         " is lower than minimum %" PRIu64 ".\n",
563                         data_key->key_version, (min_version >> 16));
564                 goto done;
565         }
566
567         rsa = PublicKeyToRSA(data_key);
568         if (!rsa) {
569                 fprintf(stderr, "Error parsing data key.\n");
570                 goto done;
571         }
572
573         /* Verify preamble */
574         if (0 != VerifyKernelPreamble(g_preamble,
575                                       g_preamble->preamble_size, rsa)) {
576                 fprintf(stderr, "Error verifying preamble.\n");
577                 goto done;
578         }
579
580         printf("Preamble:\n");
581         printf("  Size:                0x%" PRIx64 "\n",
582                g_preamble->preamble_size);
583         printf("  Header version:      %" PRIu32 ".%" PRIu32 "\n",
584                g_preamble->header_version_major,
585                g_preamble->header_version_minor);
586         printf("  Kernel version:      %" PRIu64 "\n",
587                g_preamble->kernel_version);
588         printf("  Body load address:   0x%" PRIx64 "\n",
589                g_preamble->body_load_address);
590         printf("  Body size:           0x%" PRIx64 "\n",
591                g_preamble->body_signature.data_size);
592         printf("  Bootloader address:  0x%" PRIx64 "\n",
593                g_preamble->bootloader_address);
594         printf("  Bootloader size:     0x%" PRIx64 "\n",
595                g_preamble->bootloader_size);
596
597         if (VbGetKernelVmlinuzHeader(g_preamble,
598                                      &vmlinuz_header_address,
599                                      &vmlinuz_header_size)
600             != VBOOT_SUCCESS) {
601                 fprintf(stderr, "Unable to retrieve Vmlinuz Header!");
602                 goto done;
603         }
604         if (vmlinuz_header_size) {
605                 printf("  Vmlinuz header address: 0x%" PRIx64 "\n",
606                        vmlinuz_header_address);
607                 printf("  Vmlinuz header size:    0x%" PRIx64 "\n",
608                        vmlinuz_header_size);
609         }
610
611         if (VbKernelHasFlags(g_preamble) == VBOOT_SUCCESS)
612                 printf("  Flags          :       0x%" PRIx32 "\n",
613                        g_preamble->flags);
614
615         if (g_preamble->kernel_version < (min_version & 0xFFFF)) {
616                 fprintf(stderr,
617                         "Kernel version %" PRIu64 " is lower than minimum %"
618                         PRIu64 ".\n", g_preamble->kernel_version,
619                         (min_version & 0xFFFF));
620                 goto done;
621         }
622
623         /* Verify body */
624         if (0 != VerifyData(kernel_blob, kernel_size,
625                             &g_preamble->body_signature, rsa)) {
626                 fprintf(stderr, "Error verifying kernel body.\n");
627                 goto done;
628         }
629         printf("Body verification succeeded.\n");
630
631         printf("Config:\n%s\n", kernel_blob + kernel_cmd_line_offset(
632                      (struct vb2_kernel_preamble *)g_preamble));
633
634         rv = 0;
635 done:
636         return rv;
637 }
638
639
640 uint8_t *CreateKernelBlob(uint8_t *vmlinuz_buf, uint64_t vmlinuz_size,
641                           enum arch_t arch, uint64_t kernel_body_load_address,
642                           uint8_t *config_data, uint64_t config_size,
643                           uint8_t *bootloader_data, uint64_t bootloader_size,
644                           uint64_t *blob_size_ptr)
645 {
646         uint64_t now = 0;
647         int tmp;
648
649         /* We have all the parts. How much room do we need? */
650         tmp = KernelSize(vmlinuz_buf, vmlinuz_size, arch);
651         if (tmp < 0)
652                 return NULL;
653         g_kernel_size = tmp;
654         g_config_size = CROS_CONFIG_SIZE;
655         g_param_size = CROS_PARAMS_SIZE;
656         g_bootloader_size = roundup(bootloader_size, CROS_ALIGN);
657         g_vmlinuz_header_size = vmlinuz_size-g_kernel_size;
658         g_kernel_blob_size =
659                 roundup(g_kernel_size, CROS_ALIGN) +
660                 g_config_size                      +
661                 g_param_size                       +
662                 g_bootloader_size                  +
663                 g_vmlinuz_header_size;
664         Debug("g_kernel_blob_size  0x%" PRIx64 "\n", g_kernel_blob_size);
665
666         /* Allocate space for the blob. */
667         g_kernel_blob_data = malloc(g_kernel_blob_size);
668         Memset(g_kernel_blob_data, 0, g_kernel_blob_size);
669
670         /* Assign the sub-pointers */
671         g_kernel_data = g_kernel_blob_data + now;
672         Debug("g_kernel_size       0x%" PRIx64 " ofs 0x%" PRIx64 "\n",
673               g_kernel_size, now);
674         now += roundup(g_kernel_size, CROS_ALIGN);
675
676         g_config_data = g_kernel_blob_data + now;
677         Debug("g_config_size       0x%" PRIx64 " ofs 0x%" PRIx64 "\n",
678               g_config_size, now);
679         now += g_config_size;
680
681         g_param_data = g_kernel_blob_data + now;
682         Debug("g_param_size        0x%" PRIx64 " ofs 0x%" PRIx64 "\n",
683               g_param_size, now);
684         now += g_param_size;
685
686         g_bootloader_data = g_kernel_blob_data + now;
687         Debug("g_bootloader_size   0x%" PRIx64 " ofs 0x%" PRIx64 "\n",
688               g_bootloader_size, now);
689         g_ondisk_bootloader_addr = kernel_body_load_address + now;
690         Debug("g_ondisk_bootloader_addr   0x%" PRIx64 "\n",
691               g_ondisk_bootloader_addr);
692         now += g_bootloader_size;
693
694         if (g_vmlinuz_header_size) {
695                 g_vmlinuz_header_data = g_kernel_blob_data + now;
696                 Debug("g_vmlinuz_header_size 0x%" PRIx64 " ofs 0x%" PRIx64 "\n",
697                       g_vmlinuz_header_size, now);
698                 g_ondisk_vmlinuz_header_addr = kernel_body_load_address + now;
699                 Debug("g_ondisk_vmlinuz_header_addr   0x%" PRIx64 "\n",
700                       g_ondisk_vmlinuz_header_addr);
701         }
702
703         Debug("end of kern_blob at kern_blob+0x%" PRIx64 "\n", now);
704
705         /* Copy the kernel and params bits into the correct places */
706         if (0 != PickApartVmlinuz(vmlinuz_buf, vmlinuz_size,
707                                   arch, kernel_body_load_address)) {
708                 fprintf(stderr, "Error picking apart kernel file.\n");
709                 free(g_kernel_blob_data);
710                 g_kernel_blob_data = NULL;
711                 g_kernel_blob_size = 0;
712                 return NULL;
713         }
714
715         /* Copy the other bits too */
716         Memcpy(g_config_data, config_data, config_size);
717         Memcpy(g_bootloader_data, bootloader_data, bootloader_size);
718         if (g_vmlinuz_header_size) {
719                 Memcpy(g_vmlinuz_header_data,
720                        vmlinuz_buf,
721                        g_vmlinuz_header_size);
722         }
723
724         if (blob_size_ptr)
725                 *blob_size_ptr = g_kernel_blob_size;
726         return g_kernel_blob_data;
727 }
728
729 enum futil_file_type ft_recognize_vblock1(uint8_t *buf, uint32_t len)
730 {
731         int rv;
732
733         uint8_t workbuf[VB2_WORKBUF_RECOMMENDED_SIZE];
734         struct vb2_workbuf wb;
735         vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));
736
737         /* Vboot 2.0 signature checks destroy the buffer, so make a copy */
738         uint8_t *buf2 = malloc(len);
739         memcpy(buf2, buf, len);
740
741         struct vb2_keyblock *keyblock = (struct vb2_keyblock *)buf;
742         if (VB2_SUCCESS != vb2_verify_keyblock_hash(keyblock, len, &wb)) {
743                 free(buf2);
744                 return FILE_TYPE_UNKNOWN;
745         }
746
747         /* Try unpacking the data key from the keyblock */
748         struct vb2_public_key data_key;
749         if (VB2_SUCCESS !=
750             vb2_unpack_key(&data_key, (const uint8_t *)&keyblock->data_key,
751                            keyblock->data_key.key_offset +
752                            keyblock->data_key.key_size)) {
753                 /* It looks like a bad keyblock, but still a keyblock */
754                 free(buf2);
755                 return FILE_TYPE_KEYBLOCK;
756         }
757
758         uint32_t more = keyblock->keyblock_size;
759
760         /* Followed by firmware preamble too? */
761         struct vb2_fw_preamble *pre2 = (struct vb2_fw_preamble *)(buf2 + more);
762         rv = vb2_verify_fw_preamble(pre2, len - more, &data_key, &wb);
763         free(buf2);
764         if (VB2_SUCCESS == rv)
765                 return FILE_TYPE_FW_PREAMBLE;
766
767         /* Or maybe kernel preamble? */
768         RSAPublicKey *rsa = PublicKeyToRSA((VbPublicKey *)&keyblock->data_key);
769         VbKernelPreambleHeader *kern_preamble =
770                 (VbKernelPreambleHeader *)(buf + more);
771         if (VBOOT_SUCCESS ==
772             VerifyKernelPreamble(kern_preamble, len - more, rsa))
773                 return FILE_TYPE_KERN_PREAMBLE;
774
775         /* No, just keyblock */
776         return FILE_TYPE_KEYBLOCK;
777 }
778
779 enum futil_file_type ft_recognize_vb1_key(uint8_t *buf, uint32_t len)
780 {
781         struct vb2_packed_key *pubkey = (struct vb2_packed_key *)buf;
782         VbPrivateKey key;
783         const unsigned char *start;
784
785         /* Maybe just a VbPublicKey? */
786         if (packed_key_looks_ok(pubkey, len))
787                 return FILE_TYPE_PUBKEY;
788
789         /* How about a VbPrivateKey? */
790         if (len < sizeof(key.algorithm))
791                 return FILE_TYPE_UNKNOWN;
792
793         key.algorithm = *(typeof(key.algorithm) *)buf;
794         start = buf + sizeof(key.algorithm);
795         key.rsa_private_key = d2i_RSAPrivateKey(NULL, &start,
796                                                 len - sizeof(key.algorithm));
797
798         if (key.rsa_private_key) {
799                 RSA_free(key.rsa_private_key);
800                 return FILE_TYPE_PRIVKEY;
801         }
802
803         return FILE_TYPE_UNKNOWN;
804 }