forked from Foundation-Devices/passport-firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcosign.c
764 lines (680 loc) · 17.5 KB
/
cosign.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
// SPDX-FileCopyrightText: 2020 Foundation Devices, Inc. <[email protected]>
// SPDX-License-Identifier: GPL-3.0-or-later
//
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <libgen.h>
#include <time.h>
#include <openssl/bio.h>
#include <openssl/ec.h>
#include "fwheader.h"
#include "hash.h"
#include "firmware-keys.h"
#include "uECC.h"
// This is the maximum length of "-key" + "-user", "00", "01", "02", or "03"
// Also, + 1 for the folder "/"
#define KEY_NAME_MAX_LENGTH 15
static char *firmware;
static char *version;
static bool help;
static bool debug_log_level;
static bool extract_signature;
static uint8_t header[FW_HEADER_SIZE];
static char *key;
extern EC_KEY *PEM_read_bio_ECPrivateKey(BIO *bp, EC_KEY **key, void *cb, void *u);
static void usage(
char *name
)
{
printf("Usage:%s\n", name);
printf("\t-d: debug logging\n"
"\t-f <firmware file>: full path to firmware file to sign\n"
"\t-h: this message\n"
"\t-k <private key file>\n"
"\t-v <version>: firmware version\n"
);
exit(1);
}
static void process_args(
int argc,
char **argv
)
{
int c = 0;
while ((c = getopt(argc, argv, "dhf:v:k:x")) != -1)
{
switch (c)
{
case 'f':
firmware = optarg;
break;
case 'v':
version = optarg;
break;
case 'k':
key = optarg;
break;
case 'd':
debug_log_level = true;
break;
case 'h':
help = true;
break;
case 'x':
extract_signature = true;
break;
default:
usage(argv[0]);
break;
}
}
}
static size_t read_file(
char *path,
uint8_t **buffer
)
{
uint32_t ret = 0;
struct stat info;
FILE *fp;
fp = fopen(path, "r");
if (fp == NULL)
{
printf("failed to open %s\n", path);
return 0;
}
stat(path, &info);
*buffer = (uint8_t*)calloc(1, info.st_size + sizeof(ulong));
if (*buffer == NULL)
{
printf("insufficient memory\n");
goto out;
}
ret = fread(*buffer, 1, info.st_size, fp);
if (ret != info.st_size)
free(*buffer);
else
ret = info.st_size;
out:
fclose(fp);
return ret;
}
static uint8_t *read_private_key(
char *key
)
{
BIO *in;
EC_KEY *eckey;
const BIGNUM *pkey;
int len;
int keylen;
uint8_t *private_key = NULL;
in = BIO_new_file(key, "r");
if (in == NULL)
{
printf("key %s does not appear to be in PEM format\n", key);
return NULL;
}
eckey = PEM_read_bio_ECPrivateKey(in, NULL, NULL, NULL);
if (eckey == NULL)
{
printf("could not read key %s\n", key);
goto out;
}
pkey = EC_KEY_get0_private_key(eckey);
if (pkey == NULL)
{
printf("internal error: could not get binary from private key %s\n", key);
goto out;
}
len = BN_num_bytes(pkey);
if (len <= 0)
{
printf("could not get private key length: %d\n", len);
goto out;
}
private_key = (uint8_t *)calloc(1, len);
if (private_key == NULL)
{
printf("insufficient memory\n");
goto out;
}
keylen = BN_bn2bin(pkey, private_key);
if (keylen != len)
{
printf("could not convert private key %s\n", key);
goto out;
}
out:
BIO_free(in);
return private_key;
}
static uint8_t *read_public_key(
char *key
)
{
BIO *in;
BN_CTX *ctx;
EC_KEY *eckey;
const EC_GROUP *ecgroup;
const EC_POINT *ecpoint;
BIGNUM *pkeyx;
BIGNUM *pkeyy;
uint8_t *x;
uint8_t *y;
int rc;
int lenx;
int leny;
int keylen;
uint8_t *public_key = NULL;
in = BIO_new_file(key, "r");
if (in == NULL)
{
printf("key %s does not appear to be in PEM format\n", key);
return NULL;
}
eckey = PEM_read_bio_ECPrivateKey(in, NULL, NULL, NULL);
if (eckey == NULL)
{
printf("could not read key %s\n", key);
goto out;
}
ctx = BN_CTX_new();
if (ctx == NULL)
{
printf("could not get BN context\n");
goto out;
}
pkeyx = BN_new();
if (pkeyx == NULL)
{
printf("insufficient memory\n");
goto out;
}
pkeyy = BN_new();
if (pkeyy == NULL)
{
printf("insufficient memory\n");
goto out;
}
ecgroup = EC_KEY_get0_group(eckey);
if (ecgroup == NULL)
{
printf("failed to get EC GROUP\n");
goto out;
}
ecpoint = EC_KEY_get0_public_key(eckey);
if (ecpoint == NULL)
{
printf("failed to get public key from private key\n");
goto out;
}
rc = EC_POINT_get_affine_coordinates(ecgroup, ecpoint, pkeyx, pkeyy, ctx);
if (rc == 0)
{
printf("get affine failed\n");
goto out;
}
lenx = BN_num_bytes(pkeyx);
if (lenx <= 0)
{
printf("invalid public key length: %d\n", lenx);
goto out;
}
leny = BN_num_bytes(pkeyy);
if (leny <= 0)
{
printf("invalid public key length: %d\n", leny);
goto out;
}
x = (uint8_t *)calloc(1, lenx);
if (x == NULL)
{
printf("insufficient memory\n");
goto out;
}
y = (uint8_t *)calloc(1, leny);
if (y == NULL)
{
printf("insufficient memory\n");
goto out;
}
public_key = (uint8_t *)calloc(1, lenx + leny);
if (public_key == NULL)
{
printf("insufficient memory\n");
goto out;
}
keylen = BN_bn2bin(pkeyx, x);
if (keylen != lenx)
{
printf("could not convert public key %s\n", key);
goto out;
}
keylen = BN_bn2bin(pkeyy, y);
if (keylen != leny)
{
printf("could not convert public key %s\n", key);
goto out;
}
memcpy(public_key, x, lenx);
memcpy(&public_key[lenx], y, leny);
BN_CTX_free(ctx);
BN_free(pkeyx);
BN_free(pkeyy);
out:
BIO_free(in);
return public_key;
}
char *remove_ext(char* str) {
char *ret_str;
char *last_ext;
uint8_t len;
if (str == NULL) return NULL;
// How much to copy?
last_ext = strrchr (str, '.');
if (last_ext == NULL)
{
len = strlen(str);
}
else
{
len = last_ext - str;
}
ret_str = malloc(len + 1);
if (ret_str == NULL)
{
return NULL;
}
strncpy (ret_str, str, len);
ret_str[len] = '\0';
return ret_str;
}
char *remove_unsigned(char *str) {
int len;
char *ret_str;
char *needle = strstr(str, "-unsigned");
if (needle == NULL)
{
len = strlen(str);
}
else
{
len = needle - str;
}
ret_str = malloc(len + 1);
if (ret_str == NULL)
{
return NULL;
}
strncpy(ret_str, str, len);
ret_str[len] = '\0';
return ret_str;
}
bool is_valid_version(char *version) {
int num_matched;
int version_major;
int version_minor;
int version_rev;
char left_over;
num_matched = sscanf(version, "%u.%u.%u%c", &version_major, &version_minor, &version_rev, &left_over);
if (num_matched != 3)
{
return false;
}
// Version major is restricted to only 0-9 while others are 0-99
// Max version number string is 7 + null terminator
if (version_major > 9 || version_major < 0 ||
version_minor > 99 || version_minor < 0 ||
version_rev > 99 || version_rev < 0)
{
return false;
}
else
{
sprintf(version, "%d.%d.%d", version_major, version_minor, version_rev);
return true;
}
}
int find_public_key(
uint8_t *key
)
{
int keynum;
for (keynum = 0; keynum < FW_MAX_PUB_KEYS; ++keynum)
{
if (memcmp(approved_pubkeys[keynum], key, sizeof(approved_pubkeys[keynum])) == 0)
return keynum;
}
return -1;
}
static void sign_firmware(
char *fw,
char *key,
char *version
)
{
size_t ret = 0;
size_t fwlen;
uint8_t *fwbuf = NULL;
FILE *fp = NULL;
char *output = NULL;
char *path;
char *filename;
char *file;
char *final_file;
char *tmp;
passport_firmware_header_t *hdrptr;
uint8_t *fwptr;
uint8_t fw_hash[HASH_LEN];
uint8_t *working_signature;
int rc;
uint8_t working_key = 0;
uint8_t *private_key;
uint8_t *public_key;
if (fw == NULL)
{
printf("firmware not specified\n");
return;
}
if (key == NULL)
{
printf("private key not specified\n");
return;
}
private_key = read_private_key(key);
if (private_key == NULL)
{
printf("could not get private key\n");
return;
}
public_key = read_public_key(key);
if (public_key == NULL)
{
printf("could not get public key\n");
return;
}
rc = find_public_key(public_key);
if (rc < 0)
{
printf("key %s not a supported public key...assuming user key\n", key);
working_key = FW_USER_KEY;
}
else
working_key = rc;
tmp = strdup(fw);
filename = basename(tmp);
if (filename == NULL)
{
printf("basename() failed\n");
return;
}
path = dirname(tmp);
if (path == NULL)
{
printf("dirname() failed\n");
return;
}
file = remove_ext(filename);
if (file == NULL)
{
free(file);
printf("insufficient memory (ext)\n");
return;
}
final_file = remove_unsigned(file);
free(file);
if (final_file == NULL)
{
printf("insufficient memory (unsigned)\n");
return;
}
output = (char *)calloc(1, strlen(path) + strlen(final_file) + KEY_NAME_MAX_LENGTH);
if (output == NULL)
{
printf("insufficient memory (output)\n");
return;
}
if (debug_log_level)
printf("Reading %s...", fw);
fwlen = read_file(fw, &fwbuf);
if (fwlen == 0)
{
printf("file %s has no data\n", fw);
return;
}
if (debug_log_level)
printf("done\n");
/*
* Test for an existing header in the firwmare. If one exists that
* means that it has been signed at least once already.
*/
hdrptr = (passport_firmware_header_t *)fwbuf;
if (hdrptr->info.magic == FW_HEADER_MAGIC)
{
/* Looks like there is an existing header...let's validate it */
if (hdrptr->info.timestamp == 0)
{
printf("Existing header found but timestamp invalid\n");
goto out;
}
else if (strlen((char *)hdrptr->info.fwversion) == 0)
{
printf("Existing header found but FW version invalid\n");
goto out;
}
else if (hdrptr->info.fwlength != fwlen - FW_HEADER_SIZE)
{
printf("Existing header found but FW length invalid\n");
goto out;
}
else if (hdrptr->signature.pubkey1 == FW_USER_KEY)
{
printf("This firmware was already signed by a user private key.\n");
goto out;
}
else if (hdrptr->signature.pubkey1 == working_key)
{
printf("This firmware was already signed by key%02d (same key cannot sign twice).\n", working_key);
goto out;
}
else if (working_key == FW_USER_KEY)
{
printf("Cannot sign firmware with a user private key after signing with a Foundation private key.\n");
goto out;
}
hdrptr->signature.pubkey2 = working_key;
working_signature = hdrptr->signature.signature2;
fwptr = fwbuf + FW_HEADER_SIZE;
// Generate output filename
sprintf(output, "%s/passport-fw-%s.bin", path, hdrptr->info.fwversion);
}
else
{
/* No existing header...confirm that the user specified a version */
if (version == NULL)
{
printf("Version not specified\n");
goto out;
}
if (!is_valid_version(version)) {
printf("Incorrect version number. Correct format: <0-9>.<0-99>.<0-99> (e.g., 1.12.34)\n");
goto out;
}
// Generate output filename
if (working_key == FW_USER_KEY)
{
sprintf(output, "%s/%s-key-user.bin", path, final_file);
}
else
{
sprintf(output, "%s/%s-key%02d.bin", path, final_file, working_key);
}
hdrptr = (passport_firmware_header_t *)header;
/* Create a new header...this is the first signature. */
time_t now = time(NULL);
hdrptr->info.magic = FW_HEADER_MAGIC;
hdrptr->info.timestamp = now;
struct tm now_tm = *localtime(&now);
// Make a string version of the date too for easier display in the bootloader
// where we don't have fancy date/time functions.
strftime((char*)hdrptr->info.fwdate, sizeof(hdrptr->info.fwdate), "%b %d, %Y", &now_tm);
strcpy((char *)hdrptr->info.fwversion, version);
hdrptr->info.fwlength = fwlen;
hdrptr->signature.pubkey1 = working_key;
working_signature = hdrptr->signature.signature1;
fwptr = fwbuf;
}
free(final_file);
fp = fopen(output, "wb");
if (fp == NULL)
{
printf("failed to open %s\n", output);
goto out;
}
if (debug_log_level)
{
printf("FW header content:\n");
printf("\ttimestamp: %d\n", hdrptr->info.timestamp);
printf("\t fwdate: %s\n", hdrptr->info.fwdate);
printf("\tfwversion: %s\n", hdrptr->info.fwversion);
printf("\t fwlength: %d\n", hdrptr->info.fwlength);
}
hash_fw(&hdrptr->info, fwptr, hdrptr->info.fwlength, fw_hash, HASH_LEN);
if (debug_log_level)
{
printf("FW hash: ");
for (int i = 0; i < HASH_LEN; ++i)
printf("%02x", fw_hash[i]);
printf("\n");
}
/* Encrypt the hash here... */
rc = uECC_sign(private_key,
fw_hash, sizeof(fw_hash),
working_signature, uECC_secp256k1());
if (rc == 0)
{
printf("signature failed\n");
goto out;
}
if (working_key != FW_USER_KEY)
{
rc = uECC_verify(approved_pubkeys[working_key],
fw_hash, sizeof(fw_hash),
working_signature, uECC_secp256k1());
if (rc == 0)
{
printf("verify signature failed\n");
goto out;
}
}
if (debug_log_level)
{
printf("signature: ");
for (int i = 0; i < SIGNATURE_LEN; ++i)
printf("%02x", working_signature[i]);
printf("\n");
}
if (debug_log_level)
printf("Writing header to %s - ", output);
ret = fwrite(hdrptr, 1, FW_HEADER_SIZE, fp);
if (ret != FW_HEADER_SIZE)
{
unlink(output);
printf("\n%s write failed - check disk space\n", output);
goto out;
}
if (debug_log_level)
printf("done\n");
if (debug_log_level)
printf("Writing firmware to %s - ", output);
ret = fwrite(fwptr, 1, hdrptr->info.fwlength, fp);
if (ret != hdrptr->info.fwlength)
{
unlink(output);
printf("\n%s write failed - check disk space\n", output);
goto out;
}
if (debug_log_level)
printf("done\n");
printf("Wrote signed firmware to: %s\n", output);
out:
free(fwbuf);
free(output);
free(tmp);
if (fp != NULL)
fclose(fp);
}
static void dump_firmware_signature(
char *fw
)
{
size_t fwlen;
uint8_t *fwbuf = NULL;
passport_firmware_header_t *hdrptr;
uint8_t fw_hash[HASH_LEN];
if (fw == NULL)
{
printf("firmware not specified\n");
return;
}
if (debug_log_level)
printf("Reading %s...", fw);
fwlen = read_file(fw, &fwbuf);
if (fwlen == 0)
{
printf("file %s has no data\n", fw);
return;
}
if (debug_log_level)
printf("done\n");
hdrptr = (passport_firmware_header_t *)fwbuf;
if (hdrptr->info.magic == FW_HEADER_MAGIC)
{
printf("FW header content:\n");
printf("\ttimestamp: %d\n", hdrptr->info.timestamp);
printf("\t fwdate: %s\n", hdrptr->info.fwdate);
printf("\tfwversion: %s\n", hdrptr->info.fwversion);
printf("\t fwlength: %d\n", hdrptr->info.fwlength);
printf("\t key: %d\n", hdrptr->signature.pubkey1);
printf("\tsignature: ");
for (int i = 0; i < SIGNATURE_LEN; ++i)
printf("%02x", hdrptr->signature.signature1[i]);
printf("\n");
printf("\t key: %d\n", hdrptr->signature.pubkey2);
printf("\tsignature: ");
for (int i = 0; i < SIGNATURE_LEN; ++i)
printf("%02x", hdrptr->signature.signature2[i]);
printf("\n");
// Print hashes
hash_fw_user(fwbuf, fwlen, fw_hash, HASH_LEN, true);
printf("\nFW Build Hash: ");
for (int i = 0; i < HASH_LEN; ++i)
printf("%02x", fw_hash[i]);
printf("\n");
hash_fw_user(fwbuf, fwlen, fw_hash, HASH_LEN, false);
printf("FW Download Hash: ");
for (int i = 0; i < HASH_LEN; ++i)
printf("%02x", fw_hash[i]);
printf("\n");
}
else
printf("No firmware header found in file %s\n", fw);
}
int main(int argc, char *argv[])
{
process_args(argc, argv);
if (help)
usage(argv[0]);
if (extract_signature)
dump_firmware_signature(firmware);
else
sign_firmware(firmware, key, version);
exit(0);
}