-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstm32mp1sign.c
546 lines (504 loc) · 18.3 KB
/
stm32mp1sign.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
// SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause
/*
* Copyright (C) 2022, Christian Melki
*
* Functional contribution list:
* Conny Sjaunja 2023, ECDSA verification.
*
* Version history:
* 1.0: First release.
* 1.1: Some polishing.
* 1.2: Added verification.
* 1.3: Add simple pubkey hash file creation.
*/
#define _DEFAULT_SOURCE
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <errno.h>
#include <getopt.h>
#include <errno.h>
#include <endian.h>
#include <libgen.h>
#include <sys/mman.h>
#include <fcntl.h>
/* Usage of deprecated functions.
* Want this to build with older openssl.
* Don't require 3.0+ functions.
*/
#define OPENSSL_API_COMPAT 0x10101000L
#include <openssl/opensslv.h>
#include <openssl/ecdsa.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/obj_mac.h>
#include "config.h"
#define UNUSED __attribute__((unused))
#define HEADER_MAGIC "STM2"
/* The ec pubkeys for allowed curves are 65 bytes.
* 1 byte describing format and 2*32 byte,
* x concatenated y points in an ecsig struct.
*/
#define EC_POINT_UNCOMPRESSED_LEN 65
/* The CPU hashes header from offset 0x48,
* ie. from member header_version and all of the data.
*/
#define STM32_HASH_OFFSET offsetof(struct stm32_header, header_version)
/* The stm32 header is often defined to be 0x100 bytes.
* However, some implementations carry a padding of
* uint32_t x[83/4] (?!?).
* Other definitions do uint8_t x[83] (like this one).
* Also add packed, which seems to be missing in
* a lot of implementations in the wild.
*/
struct __attribute((packed)) stm32_header {
uint32_t magic_number;
uint8_t image_signature[64];
uint32_t image_checksum;
uint8_t header_version[4];
uint32_t image_length;
uint32_t image_entry_point;
uint32_t reserved1;
uint32_t load_address;
uint32_t reserved2;
uint32_t version_number;
uint32_t option_flags;
uint32_t ecdsa_algorithm;
uint8_t ecdsa_public_key[64];
uint8_t padding[83];
uint8_t binary_type;
};
static void
usage(char *argv[])
{
printf("%s usage:\n", argv[0]);
printf("---------------------\n");
printf("%s --image <file> --key <file> --sign [--password <string>]\n", argv[0]);
printf("%s --image <file> --key <file> --verify\n", argv[0]);
printf("%s --help\n", argv[0]);
printf("where:\n");
printf("--image ; Path to stm32image file.\n");
printf("--key ; Path to the key used.\n");
printf(" ; The only allowed EC curves are: prime256v1, brainpoolP256r1\n");
printf(" ; Contains private and public key when signing.\n");
printf(" ; Contains the public key when verifying.\n");
printf("--sign ; Sign the stm32image.\n");
printf("--verify ; Verify the stm32image.\n");
printf("--password ; Not mandatory. Contains private key password. Used when signing.\n");
printf(" ; If not used, program will ask interactively.\n");
printf("--pubhash ; Not mandatory. If used then the raw ec point hash of the public key\n");
printf(" ; will be overwritten to the current dir + pubkey.hash filename.\n");
printf("--version ; %s version.\n", argv[0]);
printf("--help ; This help.\n");
}
static unsigned char *
stm32image_load(int fd, off_t *len)
{
unsigned char *data;
if (fd < 0 || !len) {
fprintf(stderr, "Invalid input.\n");
goto err_out;
}
if ((*len = lseek(fd, 0, SEEK_END)) == (off_t)-1) {
fprintf(stderr, "Cannot seek to end.\n");
goto err_out;
}
if (*len <= (off_t)sizeof(struct stm32_header)) {
fprintf(stderr, "Image file too small for stm32 header.\n");
goto err_out;
}
if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
fprintf(stderr, "Cannot seek to start.\n");
goto err_out;
}
if ((data = mmap(NULL, *len, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_POPULATE, fd, 0)) == MAP_FAILED) {
fprintf(stderr, "mmap failed: %s\n", strerror(errno));
goto err_out;
}
/* Not overly rigorous checks.
* Assuming header was generated by something sane already.
*/
if (memcmp(data, HEADER_MAGIC, strlen(HEADER_MAGIC))) {
fprintf(stderr, "Invalid stm32 header magic.\n");
goto err_out;
}
return data;
err_out:
if (len) *len = 0;
return NULL;
}
static int
openssl_pw_cb(char *buf, int size, int rwflag UNUSED, void *u UNUSED)
{
int len;
char *passwd;
passwd = getpass("stm32mp1sign. Privkey password: ");
len = strlen(passwd);
if (len <= 0 || len > size) {
return 0;
}
memcpy(buf, passwd, len);
return len;
}
static EC_KEY *
openssl_load_key(const char *key_path, char *pw, bool privkey)
{
BIO *bio_key = NULL;
EVP_PKEY *key = NULL;
EC_KEY *eckey = NULL;
if (!key_path || !key_path[0]) {
fprintf(stderr, "Invalid input.\n");
goto err_out;
}
if (!(bio_key = BIO_new_file(key_path, "r"))) {
fprintf(stderr, "Unable to load key %s.\n", key_path);
goto err_out;
}
if (privkey) {
key = PEM_read_bio_PrivateKey(bio_key, NULL,
pw ? NULL : openssl_pw_cb,
pw ? pw : NULL);
} else {
key = PEM_read_bio_PUBKEY(bio_key, NULL,
NULL,
NULL);
}
if (!key) {
fprintf(stderr, "Unable to load key %s.\n",
key_path);
goto err_out;
}
if (!(eckey = EVP_PKEY_get1_EC_KEY(key))) {
fprintf(stderr, "Unable to get EC key.\n");
goto err_out;
}
if (key) EVP_PKEY_free(key);
if (bio_key) BIO_free(bio_key);
return eckey;
err_out:
if (key) EVP_PKEY_free(key);
if (bio_key) BIO_free(bio_key);
return NULL;
}
static uint8_t *
openssl_get_pubkey(EC_KEY *eckey, size_t *len, int *alg)
{
int nid = 0;
BN_CTX *ctx = NULL;
const EC_POINT *public_key = NULL;
const EC_GROUP *group = NULL;
uint8_t *buffer = NULL;
if (!eckey || !len | !alg) {
fprintf(stderr, "Invalid input.\n");
goto err_out;
}
if (!(public_key = EC_KEY_get0_public_key(eckey))) {
fprintf(stderr, "Unable to get EC pubkey.\n");
goto err_out;
}
if (!(group = EC_KEY_get0_group(eckey))) {
fprintf(stderr, "Unable to get EC group.\n");
goto err_out;
}
if (!EC_GROUP_get_asn1_flag(group)) {
fprintf(stderr, "Unable to get EC parameters.\n");
goto err_out;
}
/* Only allow these curves */
nid = EC_GROUP_get_curve_name(group);
if (nid == NID_X9_62_prime256v1) {
*alg = 1;
} else if (nid == NID_brainpoolP256r1) {
*alg = 2;
} else {
fprintf(stderr, "Invalid EC curve in use.\n");
goto err_out;
}
if (!(ctx = BN_CTX_new())) {
fprintf(stderr, "Unable to allocate bignum context.\n");
goto err_out;
}
/* Use point2oct twice.
* Get length, allocate storage, repeat to get contents.
*/
if (!(*len = EC_POINT_point2oct(group, public_key,
EC_KEY_get_conv_form(eckey), NULL,
0, ctx))) {
fprintf(stderr, "Unable to get EC pubkey length.\n");
goto err_out;
}
if (!(buffer = OPENSSL_malloc(*len))) {
fprintf(stderr, "Unable to allocate pubkey buffer.\n");
goto err_out;
}
if (!(*len = EC_POINT_point2oct(group, public_key,
EC_KEY_get_conv_form(eckey), buffer,
*len, ctx))) {
fprintf(stderr, "Unable to get EC pubkey length.\n");
goto err_out;
}
if (ctx) BN_CTX_free(ctx);
return buffer;
err_out:
if (ctx) BN_CTX_free(ctx);
if (len) *len = 0;
if (alg) *alg = 0;
return NULL;
}
static ECDSA_SIG *
openssl_do_ecdsa_sha256_sign(EC_KEY *eckey,
unsigned char *data, unsigned long datalen)
{
ECDSA_SIG *ecsig = NULL;
if (!eckey || !data || !datalen) {
fprintf(stderr, "Invalid input.\n");
goto err_out;
}
if (!(ecsig = ECDSA_do_sign(SHA256(data, datalen, NULL),
SHA256_DIGEST_LENGTH, eckey))) {
fprintf(stderr, "Unable to generate ECDSA signature.\n");
goto err_out;
}
return ecsig;
err_out:
return NULL;
}
static ECDSA_SIG *
openssl_do_ecdsa_sha256_verify(ECDSA_SIG *ecsig, EC_KEY *eckey,
unsigned char *data, unsigned long datalen)
{
if (!ecsig || !eckey || !data || !datalen) {
fprintf(stderr, "Invalid input.\n");
goto err_out;
}
if (!(ECDSA_do_verify(SHA256(data, datalen, NULL),
SHA256_DIGEST_LENGTH, ecsig, eckey))) {
fprintf(stderr, "Unable to verify ECDSA signature.\n");
goto err_out;
}
return ecsig;
err_out:
return NULL;
}
int
main(int argc, char *argv[])
{
struct stm32_header *h = NULL;
FILE *fp = NULL;
unsigned char *p;
char *key_path = NULL;
char *password = NULL;
EC_KEY *eckey = NULL;
ECDSA_SIG *ecsig = NULL;
unsigned char *data = NULL;
off_t datalen;
uint8_t *buf = NULL;
size_t len;
int alg, c, fd = -1;
bool sign = false, verify = false, pubhash = false;
static struct option options[] = {
{"image", required_argument, 0, 'i'},
{"key", required_argument, 0, 'k'},
{"sign", no_argument, 0, 's'},
{"verify", no_argument, 0, 'v'},
{"password", required_argument, 0, 'p'},
{"pubhash", no_argument, 0, 'x'},
{"version", no_argument, 0, 'V'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
/* Prevent pages from reaching swap.
* Contains sensitive data.
*/
if (mlockall(MCL_CURRENT | MCL_FUTURE)) {
fprintf(stderr,
"Warn: Failed protecting memory from being swapped.\n");
}
while (1) {
c = getopt_long(argc, argv, "i:svk:p:xhV", options, NULL);
if (c == -1)
break;
switch (c) {
case 'i':
fd = open(optarg, O_RDWR);
if (fd < 0) {
fprintf(stderr,
"Error: Cannot open %s: %s\n",
optarg, strerror(errno));
goto err_out;
}
break;
case 'k':
key_path = strdup(optarg);
break;
case 's':
sign = true;
break;
case 'v':
verify = true;
break;
case 'p':
password = strdup(optarg);
break;
case 'x':
pubhash = true;
break;
case 'V':
fprintf(stderr, "Version: %s\n", PACKAGE_VERSION);
goto err_out;
break;
case 'h':
usage(argv);
goto err_out;
break;
default:
fprintf(stderr, "%s: unknown option\n", argv[0]);
usage(argv);
goto err_out;
break;
}
}
if (sign == verify) {
fprintf(stderr, "%s: Op must be either sign or verify.\n",
argv[0]);
usage(argv);
goto err_out;
}
if (fd < 0) {
fprintf(stderr, "%s: Missing stm32 image file.\n",
argv[0]);
usage(argv);
goto err_out;
}
if (!key_path) {
fprintf(stderr, "%s: Missing key path or password.\n",
argv[0]);
usage(argv);
goto err_out;
}
/* Load and validate image magic. */
if (!(data = stm32image_load(fd, &datalen))) {
goto err_out;
}
/* Load key.
* Contains both priv and pubkey if signing.
* Contains only pubkey if verifying.
*/
if (!(eckey = openssl_load_key(key_path, password, sign))) {
goto err_out;
}
/* Slap the header over the data so we can modify it.
* Don't forget header endians.
*/
h = (struct stm32_header *)data;
/* sign and verify already checked to be mutually exclusive */
if (sign) {
/* Get raw pubkey from key. */
if (!(buf = openssl_get_pubkey(eckey, &len, &alg))) {
goto err_out;
}
if (buf[0] != POINT_CONVERSION_UNCOMPRESSED ||
len != EC_POINT_UNCOMPRESSED_LEN) {
fprintf(stderr, "EC pubkey invalid length.\n");
goto err_out;
}
/* Copy raw pubkey to header.
* First byte is the type declaration. Skip it.
* Raw bignum. Two points on curve. X concatenated with Y.
*/
memcpy(h->ecdsa_public_key, &buf[1], len - 1);
/* option:
* 0: signed.
* 1: not signed.
*/
h->option_flags = htole32(0);
/* Algorithm:
* 1: prime256v1
* 2: brainpoolP256r1
*/
h->ecdsa_algorithm = htole32(alg);
/* Do ECDSA signature with sha256
* from correct offset in header to end of data.
*/
if (!(ecsig =
openssl_do_ecdsa_sha256_sign(eckey,
&data[STM32_HASH_OFFSET],
datalen - STM32_HASH_OFFSET))) {
goto err_out;
}
/* Copy signature to header.
* Raw bignum. Two numbers. R concatenated with S.
*/
BN_bn2bin(ECDSA_SIG_get0_r(ecsig),
&((h->image_signature)[0]));
BN_bn2bin(ECDSA_SIG_get0_s(ecsig),
&((h->image_signature)[32]));
}
if (verify) {
if (!(ecsig = ECDSA_SIG_new())) {
fprintf(stderr, "Unable to allocate a ecsig structure.\n");
goto err_out;
}
/* Get signature from header
* Raw bignum. Two numbers. R concatenated with S.
*/
ECDSA_SIG_set0(ecsig,
BN_bin2bn(&((h->image_signature)[0]), 32, NULL),
BN_bin2bn(&((h->image_signature)[32]), 32, NULL));
/* Do ECDSA verification with sha256
* from correct offset in header to end of data.
*/
if (!(ecsig =
openssl_do_ecdsa_sha256_verify(ecsig, eckey,
&data[STM32_HASH_OFFSET],
datalen - STM32_HASH_OFFSET))) {
goto err_out;
}
}
/* Pubkeys are always available, regardless of operation */
if (pubhash) {
if (!(p = SHA256(h->ecdsa_public_key,
EC_POINT_UNCOMPRESSED_LEN - 1, NULL))) {
fprintf(stderr, "Unable to calculate sha256 of raw pubkey.\n");
goto err_out;
}
if (!(fp = fopen("./pubkey.hash", "w+"))) {
fprintf(stderr, "Unable to open pubkey hash file.\n");
goto err_out;
}
if (fwrite(p, 1, SHA256_DIGEST_LENGTH, fp) !=
SHA256_DIGEST_LENGTH) {
fprintf(stderr, "Unable to write pubkey hash.\n");
goto err_out;
}
}
if (ecsig) ECDSA_SIG_free(ecsig);
if (buf) OPENSSL_free(buf);
if (eckey) EC_KEY_free(eckey);
if (data) munmap(data, datalen);
if (password) {
memset(password, 0, strlen(password));
free(password);
}
if (key_path) free(key_path);
if (fp) fclose(fp);
munlockall();
exit(EXIT_SUCCESS);
err_out:
if (ecsig) ECDSA_SIG_free(ecsig);
if (buf) OPENSSL_free(buf);
if (eckey) EC_KEY_free(eckey);
if (data) munmap(data, datalen);
if (password) {
memset(password, 0, strlen(password));
free(password);
}
if (key_path) free(key_path);
if (fp) fclose(fp);
munlockall();
exit(EXIT_FAILURE);
}