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
|
/* Copyright 2015 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// global C++ includes
#include <string>
// global C includes
#include <assert.h>
#include <fcntl.h>
#include <gelf.h>
#include <libelf.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
// local includes
#include <common/publickey.h>
#include <common/image.h>
#include <common/signed_header.h>
using namespace std;
extern bool FLAGS_verbose;
#define VERBOSE(...) do{if(FLAGS_verbose)fprintf(stderr, __VA_ARGS__);}while(0)
#define WARN(...) do{fprintf(stderr, __VA_ARGS__);}while(0)
#define FATAL(...) do{fprintf(stderr, __VA_ARGS__);abort();}while(0)
static const int FLASH_START = 0x40000;
static const int FLASH_END = FLASH_START + 512 * 1024;
Image::Image()
: success_(true), low_(FLASH_END - FLASH_START), high_(0),
base_(0), ro_base_(FLASH_END), rx_base_(FLASH_END),
ro_max_(0), rx_max_(0) {
memset(mem_, 0xff, sizeof(mem_)); // default memory content
}
void Image::randomize() {
int fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0) {
read(fd, mem_, sizeof(mem_));
close(fd);
}
}
bool Image::fromElf(const string& filename) {
Elf* elf = NULL;
Elf_Scn* scn = NULL;
GElf_Shdr shdr;
GElf_Phdr phdr;
char* base_ptr = NULL;
struct stat elf_stats;
bool result = false;
int fd;
if ((fd = open(filename.c_str(), O_RDONLY)) < 0) {
WARN("failed to open '%s'\n", filename.c_str());
goto fail;
}
if ((fstat(fd, &elf_stats)) < 0) {
WARN("cannot stat '%s'\n", filename.c_str());
goto fail;
}
// printf("Elf filesize: %lu\n", elf_stats.st_size);
if ((base_ptr = (char*) malloc(elf_stats.st_size)) == NULL) {
WARN("cannot malloc %lu\n", elf_stats.st_size);
goto fail;
}
if (read(fd, base_ptr, elf_stats.st_size) < elf_stats.st_size) {
WARN("cannot read from '%s'\n", filename.c_str());
goto fail;
}
// Sniff content for sanity
if (*(uint32_t*) base_ptr != 0x464c457f) {
// WARN("'%s' is not elf file\n", filename);
goto fail;
}
if (elf_version(EV_CURRENT) == EV_NONE) {
WARN("Warning: elf library is out of date!\n");
}
elf = elf_begin(fd, ELF_C_READ, NULL);
// Infer minimal rx segment from section headers.
while ((scn = elf_nextscn(elf, scn)) != 0) {
gelf_getshdr(scn, &shdr);
VERBOSE("type %08x; flags %08lx ", shdr.sh_type, shdr.sh_flags);
VERBOSE("%08lx(@%08lx)[%08lx] align %lu ",
shdr.sh_addr, shdr.sh_offset, shdr.sh_size, shdr.sh_addralign);
// Ignore sections that are not alloc
if (!(shdr.sh_flags & SHF_ALLOC)) {
VERBOSE("non aloc, ignored\n");
continue;
}
// Ignore sections that are not exec
if (!(shdr.sh_flags & SHF_EXECINSTR)) {
VERBOSE("non exec, ignored\n");
continue;
}
// Ignore sections outside our flash range
if (shdr.sh_addr < FLASH_START ||
shdr.sh_addr + shdr.sh_size >= FLASH_END) {
VERBOSE("out of bounds, ignored\n");
continue;
}
VERBOSE("\n");
// Track rx boundaries
if (shdr.sh_addr < rx_base_) {
rx_base_ = shdr.sh_addr;
}
if (shdr.sh_addr + shdr.sh_size> rx_max_) {
rx_max_ = shdr.sh_addr + shdr.sh_size;
}
}
// Load image per program headers and track total ro segment
for (int index = 0; gelf_getphdr(elf, index, &phdr); ++index) {
VERBOSE("phdr %08lx(@%08lx) [%08lx/%08lx]",
phdr.p_vaddr, phdr.p_paddr, phdr.p_filesz, phdr.p_memsz);
if (phdr.p_filesz != phdr.p_memsz) {
VERBOSE(" (size mismatch, not loading)\n");
continue;
}
// Ignore sections outside our flash range
if (phdr.p_paddr < FLASH_START ||
phdr.p_paddr + phdr.p_memsz >= FLASH_END) {
VERBOSE(" (out of bounds, not loading)\n");
continue;
}
VERBOSE("\n");
// Track ro boundaries
if (phdr.p_paddr < ro_base_) {
ro_base_ = phdr.p_paddr;
}
if (phdr.p_paddr + phdr.p_memsz > ro_max_) {
ro_max_ = phdr.p_paddr + phdr.p_memsz;
}
// Copy data into image
for (size_t n = 0; n < phdr.p_filesz; ++n) {
store(phdr.p_paddr + n - FLASH_START,
base_ptr[phdr.p_offset + n]);
}
}
low_ &= ~2047;
base_ = low_;
if (rx_base_ < base_ + FLASH_START + sizeof(SignedHeader)) {
// Fix-up 1K header that is part of rx in EC builds
rx_base_ = base_ + FLASH_START + sizeof(SignedHeader);
}
high_ = ((high_ + 2047) / 2048) * 2048; // Round image to multiple of 2K.
VERBOSE("Rounded image size %lu\n", size());
VERBOSE("ro_base %08lx..%08lx\n", ro_base_, ro_max_);
VERBOSE("rx_base %08lx..%08lx\n", rx_base_, rx_max_);
result = true;
fail:
if (elf) elf_end(elf);
if (base_ptr) free(base_ptr);
if (fd >= 0) close(fd);
return result;
}
bool Image::fromIntelHex(const string& filename, bool withSignature) {
bool isRam = false;
int seg = 0;
FILE* fp = fopen(filename.c_str(), "rt");
if (fp != NULL) {
char line[BUFSIZ];
while (fgets(line, sizeof(line), fp)) {
if (strchr(line, '\r')) *strchr(line, '\r') = 0;
if (strchr(line, '\n')) *strchr(line, '\n') = 0;
if (line[0] != ':') continue; // assume comment line
if (strlen(line) < 9) {
WARN("short record %s", line);
success_ = false;
continue;
}
if (line[7] != '0') {
WARN("unknown record type %s", line);
success_ = false;
} else switch (line[8]) {
case '1': { // 01 eof
} break;
case '2': { // 02 segment
if (!strncmp(line, ":02000002", 9)) {
char* p = line + 9;
int s = parseWord(&p);
if (s != 0x1000) {
if (s >= FLASH_START/16 && s <= FLASH_END/16) {
seg = s - FLASH_START/16;
//WARN("at segment %04x\n", seg);
} else {
WARN("data should fit in range %x-%x: %s\n",
FLASH_START, FLASH_END, line);
success_ = false;
}
}
}
isRam = !strcmp(line, ":020000021000EC");
} break;
case '0': { // 00 data
char* p = line + 1;
int len = parseByte(&p);
int adr = parseWord(&p);
parseByte(&p);
while (len--) {
if (isRam) {
int v = parseByte(&p);
if (v != 0) {
WARN("WARNING: non-zero RAM byte %02x at %04x\n",
v, adr);
}
++adr;
} else {
store((seg * 16) + adr++, parseByte(&p));
}
}
} break;
case '3': { // 03 entry point
} break;
default: {
WARN("unknown record type %s", line);
success_ = false;
} break;
}
}
fclose(fp);
} else {
WARN("failed to open file '%s'\n", filename.c_str());
success_ = false;
}
if (success_) {
static_assert(sizeof(SignedHeader) == 1024,
"SignedHeader should be 1024 bytes");
if (withSignature) {
// signed images start on 2K boundary.
if ((low_ & 2047) != 0) {
WARN("signed images should start on 2K boundary, not %08x\n", low_);
}
base_ = low_;
} else {
// unsigned images start on odd 1K boundary.
if ((low_ & 2047) != 1024) {
WARN("unsigned images should start odd 1K boundary, not %08x\n", low_);
}
base_ = low_ - sizeof(SignedHeader);
}
}
if (success_) {
VERBOSE("low %08x, high %08x\n",
FLASH_START + low_, FLASH_START + high_);
// Round image to multiple of 2K.
high_ = ((high_ + 2047) / 2048) * 2048;
ro_base_ = FLASH_START + base_;
rx_base_ = FLASH_START + base_;
ro_max_ = FLASH_START + base_ + size();
rx_max_ = FLASH_START + base_ + size();
VERBOSE("base %08lx, size %08lx\n", ro_base_, size());
}
return success_;
}
Image::~Image() {}
void Image::toIntelHex(FILE *fout) const {
for (int i = base_; i < high_; i += 16) {
// spit out segment record at start of segment.
if (!((i - base_)&0xffff)) {
int s = FLASH_START/16 + (base_>>4) + ((i - base_)>>4);
fprintf(fout, ":02000002%04X%02X\n", s,
(~((2 + 2 + (s>>8)) & 255) + 1) & 255);
}
// spit out data records, 16 bytes each.
fprintf(fout, ":10%04X00", (i - base_)&0xffff);
int crc = 16 + (((i - base_)>>8)&255) + ((i - base_)&255);
for (int n = 0; n < 16; ++n) {
fprintf(fout, "%02X", mem_[i+n]);
crc += mem_[i+n];
}
fprintf(fout, "%02X", (~(crc & 255) + 1) & 255);
fprintf(fout, "\n");
}
}
void Image::generate(const std::string& filename, bool hex_output) const {
FILE* fout = fopen(filename.c_str(), "w");
if (!fout) return;
if (hex_output)
toIntelHex(fout);
else // TODO: we don't expect write to fail, can be made more robust.
fwrite(mem_ + base_, 1, high_ - base_, fout);
fclose(fout);
}
int Image::nibble(char n) {
switch (n) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return n - '0';
case 'a': case 'A': return 10;
case 'b': case 'B': return 11;
case 'c': case 'C': return 12;
case 'd': case 'D': return 13;
case 'e': case 'E': return 14;
case 'f': case 'F': return 15;
default:
WARN("bad hex digit '%c'\n", n);
success_ = false;
return 0;
}
}
int Image::parseByte(char** p) {
int result = nibble(**p);
result *= 16;
(*p)++;
result |= nibble(**p);
(*p)++;
return result;
}
int Image::parseWord(char** p) {
int result = parseByte(p);
result *= 256;
result |= parseByte(p);
return result;
}
void Image::store(int adr, int v) {
if (adr < 0 || (size_t)(adr) >= sizeof(mem_)) {
WARN("illegal adr %04x\n", adr);
success_ = false;
return;
}
mem_[adr] = v;
if (adr > high_) high_ = adr;
if (adr < low_) low_ = adr;
}
bool Image::sign(PublicKey& key,
const SignedHeader* input_hdr,
const uint32_t fuses[FUSE_MAX],
const uint32_t info[INFO_MAX],
const string& hashesFilename) {
BIGNUM* sig = NULL;
SignedHeader* hdr = (SignedHeader*)(&mem_[base_]);
SHA256_CTX sha256;
int result;
// List of hashes we actually sign.
struct {
uint8_t img_hash[SHA256_DIGEST_LENGTH];
uint8_t fuses_hash[SHA256_DIGEST_LENGTH];
uint8_t info_hash[SHA256_DIGEST_LENGTH];
} hashes;
memcpy(hdr, input_hdr, sizeof(SignedHeader));
hdr->image_size = this->size();
// Fill in key traits
hdr->keyid = key.n0inv();
key.modToArray(hdr->key, key.rwords());
// Hash fuses
SHA256_Init(&sha256);
SHA256_Update(&sha256, fuses, FUSE_MAX * sizeof(uint32_t));
SHA256_Final(hashes.fuses_hash, &sha256);
hdr->fuses_chk_ =
(hashes.fuses_hash[0] << 0)
| (hashes.fuses_hash[1] << 8)
| (hashes.fuses_hash[2] << 16)
| (hashes.fuses_hash[3] << 24);
// Hash info
SHA256_Init(&sha256);
SHA256_Update(&sha256, info, INFO_MAX * sizeof(uint32_t));
SHA256_Final(hashes.info_hash, &sha256);
hdr->info_chk_ =
(hashes.info_hash[0] << 0)
| (hashes.info_hash[1] << 8)
| (hashes.info_hash[2] << 16)
| (hashes.info_hash[3] << 24);
// Hash img
int size = this->size() - offsetof(SignedHeader, tag);
SHA256_Init(&sha256);
SHA256_Update(&sha256, &hdr->tag, size);
SHA256_Final(hashes.img_hash, &sha256);
hdr->img_chk_ =
(hashes.img_hash[0] << 0)
| (hashes.img_hash[1] << 8)
| (hashes.img_hash[2] << 16)
| (hashes.img_hash[3] << 24);
// Dump out values for comparing against boot_rom
VERBOSE("Himg =");
for (size_t i = 0; i < sizeof(hashes.img_hash); ++i) {
VERBOSE("%02x", hashes.img_hash[i]);
}
VERBOSE("\n");
VERBOSE("Hfss =");
for (size_t i = 0; i < sizeof(hashes.fuses_hash); ++i) {
VERBOSE("%02x", hashes.fuses_hash[i]);
}
VERBOSE("\n");
VERBOSE("Hinf =");
for (size_t i = 0; i < sizeof(hashes.info_hash); ++i) {
VERBOSE("%02x", hashes.info_hash[i]);
}
VERBOSE("\n");
if (!hashesFilename.empty()) {
// Write hashes to file for subsequent extraneous (re)signing.
int fd = open(hashesFilename.c_str(), O_CREAT|O_TRUNC|O_RDWR, 0600);
if (fd >= 0) {
write(fd, &hashes, sizeof(hashes));
close(fd);
}
}
sig = BN_bin2bn((uint8_t*)(hdr->signature), sizeof(hdr->signature), NULL);
result = key.sign(&hashes, sizeof(hashes), &sig);
if (result != 1) {
WARN("key.sign: %d\n", result);
} else {
key.toArray(hdr->signature, key.rwords(), sig);
}
if (sig) BN_free(sig);
return result == 1;
}
|