forked from toniebox-reverse-engineering/teddycloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp32.c
1053 lines (881 loc) · 28.1 KB
/
esp32.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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define TRACE_LEVEL TRACE_LEVEL_INFO
#include <stdint.h>
#include "hash/sha256.h"
#include "fs_ext.h"
#include "path.h"
#include "debug.h"
#include "esp32.h"
#include "ff.h"
#include "diskio.h"
#include "server_helpers.h"
#include "cert.h"
#include "pem_import.h"
#define ESP_PARTITION_TYPE_APP 0
#define ESP_PARTITION_TYPE_DATA 1
#pragma pack(push, 1)
/*
********** ESP32 partition structures **********
*/
struct ESP32_part_entry
{
uint16_t magic;
uint8_t partType;
uint8_t partSubType;
uint32_t fileOffset;
uint32_t length;
uint8_t label[16];
uint32_t reserved;
};
/*
********** ESP32 firmware structures **********
*/
struct ESP32_segment
{
uint32_t loadAddress;
uint32_t length;
// uint8_t data[length];
};
struct ESP32_EFH
{
uint8_t wp_pin;
uint8_t spi_drive[3];
uint16_t chip_id;
uint8_t min_chip_rev_old;
uint16_t min_chip_revision;
uint16_t max_chip_revision;
uint8_t reserved[4];
uint8_t has_hash;
};
struct ESP32_header
{
uint8_t magic;
uint8_t segments;
uint8_t flashMode;
uint8_t flashInfo;
uint32_t entry;
struct ESP32_EFH extended;
// ESP32_segment segment_data[segments];
};
struct ESP32_footer
{
uint8_t chk;
uint8_t sha[32];
};
/*
********** ESP32 asset wear levelling structures **********
*/
#define WL_CFG_SECTORS_COUNT 1
#define WL_DUMMY_SECTORS_COUNT 1
#define WL_CONFIG_HEADER_SIZE 48
#define WL_STATE_RECORD_SIZE 16
#define WL_STATE_HEADER_SIZE 64
#define WL_STATE_COPY_COUNT 2
#define WL_SECTOR_SIZE 0x1000
struct WL_STATE_T_DATA
{
uint32_t pos;
uint32_t max_pos;
uint32_t move_count;
uint32_t access_count;
uint32_t max_count;
uint32_t block_size;
uint32_t version;
uint32_t device_id;
uint8_t reserved[28];
};
struct WL_CONFIG_T_DATA
{
uint32_t start_addr;
uint32_t full_mem_size;
uint32_t page_size;
uint32_t sector_size;
uint32_t updaterate;
uint32_t wr_size;
uint32_t version;
uint32_t temp_buff_size;
};
struct wl_state
{
struct WL_STATE_T_DATA wl_state;
size_t fs_offset;
size_t wl_sectors_size;
size_t partition_size;
size_t fat_sectors;
size_t total_sectors;
size_t total_records;
size_t wl_state_size;
size_t wl_state_sectors_cnt;
FsFile *file;
};
#pragma pack(pop)
struct wl_state esp32_wl_state;
size_t esp32_wl_translate(const struct wl_state *state, size_t sector)
{
sector = (sector + state->wl_state.move_count) % state->fat_sectors;
if (sector >= state->total_records)
{
sector += 1;
}
return sector;
}
DWORD get_fattime()
{
// Retrieve current time
time_t time = getCurrentUnixTime();
DateTime date;
convertUnixTimeToDate(time, &date);
return (
(uint32_t)(date.year - 1980) << 25 |
(uint32_t)(date.month) << 21 |
(uint32_t)(date.day) << 16 |
(uint32_t)(date.hours) << 11 |
(uint32_t)(date.minutes) << 5 |
(uint32_t)(date.seconds) >> 1);
}
DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void *buff)
{
return RES_OK;
}
DSTATUS disk_status(BYTE pdrv)
{
return RES_OK;
}
DSTATUS disk_initialize(BYTE pdrv)
{
return RES_OK;
}
DRESULT disk_write(BYTE pdrv, const BYTE *buffer, LBA_t sector, UINT count)
{
struct wl_state *state = (struct wl_state *)&esp32_wl_state;
for (int sec = 0; sec < count; sec++)
{
size_t trans_sec = esp32_wl_translate(state, sector + sec);
fsSeekFile(state->file, state->fs_offset + trans_sec * WL_SECTOR_SIZE, FS_SEEK_SET);
error_t error = fsWriteFile(state->file, (void *)&buffer[sec * WL_SECTOR_SIZE], WL_SECTOR_SIZE);
if (error != NO_ERROR)
{
TRACE_ERROR("Failed to write sector\r\n");
return RES_ERROR;
}
}
return RES_OK;
}
DRESULT disk_read(BYTE pdrv, BYTE *buffer, LBA_t sector, UINT count)
{
struct wl_state *state = (struct wl_state *)&esp32_wl_state;
for (int sec = 0; sec < count; sec++)
{
size_t read;
size_t trans_sec = esp32_wl_translate(state, sector + sec);
fsSeekFile(state->file, state->fs_offset + trans_sec * WL_SECTOR_SIZE, FS_SEEK_SET);
error_t error = fsReadFile(state->file, (void *)&buffer[sec * WL_SECTOR_SIZE], WL_SECTOR_SIZE, &read);
if (error != NO_ERROR || read != WL_SECTOR_SIZE)
{
TRACE_ERROR("Failed to read sector\r\n");
return RES_ERROR;
}
}
return RES_OK;
}
error_t esp32_wl_init(struct wl_state *state, FsFile *file, size_t offset, size_t length)
{
state->fs_offset = offset;
state->file = file;
state->partition_size = length;
state->total_sectors = state->partition_size / WL_SECTOR_SIZE;
state->wl_state_size = WL_STATE_HEADER_SIZE + WL_STATE_RECORD_SIZE * state->total_sectors;
state->wl_state_sectors_cnt = (state->wl_state_size + WL_SECTOR_SIZE - 1) / WL_SECTOR_SIZE;
state->wl_sectors_size = (state->wl_state_sectors_cnt * WL_SECTOR_SIZE * WL_STATE_COPY_COUNT) + WL_SECTOR_SIZE;
state->fat_sectors = state->total_sectors - 1 - (WL_STATE_COPY_COUNT * state->wl_state_sectors_cnt);
fsSeekFile(file, offset + state->partition_size - state->wl_sectors_size, FS_SEEK_SET);
size_t read;
error_t error = fsReadFile(file, &state->wl_state, sizeof(state->wl_state), &read);
if (error != NO_ERROR || read != sizeof(state->wl_state))
{
TRACE_ERROR("Failed to read wl_state\r\n");
return ERROR_FAILURE;
}
uint8_t state_record_empty[WL_STATE_RECORD_SIZE];
memset(state_record_empty, 0xFF, WL_STATE_RECORD_SIZE);
for (int pos = 0; pos < state->wl_state_size; pos++)
{
uint8_t state_record[WL_STATE_RECORD_SIZE];
error = fsReadFile(file, state_record, sizeof(state_record), &read);
if (read != sizeof(state_record))
{
TRACE_ERROR("Failed to read state_record\r\n");
return ERROR_FAILURE;
}
if (!memcmp(state_record_empty, state_record, WL_STATE_RECORD_SIZE))
{
break;
}
state->total_records++;
}
return NO_ERROR;
}
error_t esp32_fixup_fatfs(FsFile *file, size_t offset, size_t length, bool modify)
{
if (esp32_wl_init(&esp32_wl_state, file, offset, length) != NO_ERROR)
{
TRACE_ERROR("Failed to init wear leveling\r\n");
return ERROR_FAILURE;
}
FATFS fs;
FRESULT ret = f_mount(&fs, "0:", 1);
if (ret == FR_OK)
{
DIR dirInfo;
FRESULT res = f_opendir(&dirInfo, "\\CERT\\");
if (res == FR_OK)
{
TRACE_INFO("Index of CERT\r\n");
do
{
FILINFO fileInfo;
if (f_readdir(&dirInfo, &fileInfo) != FR_OK)
{
break;
}
if (!fileInfo.fname[0])
{
break;
}
TRACE_INFO(" %-12s %-10u %04d-%02d-%02d %02d:%02d:%02d\r\n", fileInfo.fname, fileInfo.fsize,
((fileInfo.fdate >> 9) & 0x7F) + 1980,
(fileInfo.fdate >> 5) & 0x0F,
(fileInfo.fdate) & 0x1F,
(fileInfo.ftime >> 11) & 0x1F,
(fileInfo.ftime >> 5) & 0x3F,
(fileInfo.ftime & 0x1F) * 2);
} while (1);
f_closedir(&dirInfo);
}
f_unmount("0:");
}
return NO_ERROR;
}
error_t esp32_fat_extract_folder(FsFile *file, size_t offset, size_t length, const char *path, const char *out_path)
{
if (esp32_wl_init(&esp32_wl_state, file, offset, length) != NO_ERROR)
{
TRACE_ERROR("Failed to init wear leveling\r\n");
return ERROR_FAILURE;
}
FATFS fs;
FRESULT ret = f_mount(&fs, "0:", 1);
if (ret != FR_OK)
{
TRACE_ERROR("Failed to mount image\r\n");
return ERROR_FAILURE;
}
DIR dirInfo;
FRESULT res = f_opendir(&dirInfo, path);
if (res == FR_OK)
{
do
{
FILINFO fileInfo;
if (f_readdir(&dirInfo, &fileInfo) != FR_OK)
{
break;
}
if (!fileInfo.fname[0])
{
break;
}
char fatFileName[FS_MAX_PATH_LEN];
osStrcpy(fatFileName, path);
osStrcat(fatFileName, "\\");
osStrcat(fatFileName, fileInfo.fname);
char outFileName[FS_MAX_PATH_LEN];
osStrcpy(outFileName, out_path);
pathAddSlash(outFileName, FS_MAX_PATH_LEN);
pathCombine(outFileName, fileInfo.fname, FS_MAX_PATH_LEN);
pathCanonicalize(outFileName);
TRACE_INFO("Write '%s to '%s' (%d bytes)\r\n", fatFileName, outFileName, fileInfo.fsize);
FsFile *outFile = fsOpenFile(outFileName, FS_FILE_MODE_WRITE);
if (!outFile)
{
TRACE_ERROR("Failed to open output file\r\n");
return ERROR_FAILURE;
}
FIL fp;
if (f_open(&fp, fatFileName, FA_READ) != FR_OK)
{
TRACE_ERROR("Failed to open FAT file\r\n");
return ERROR_FAILURE;
}
uint8_t buffer[512];
for (int pos = 0; pos < fileInfo.fsize; pos += sizeof(buffer))
{
uint32_t read;
if (f_read(&fp, buffer, sizeof(buffer), &read) != FR_OK)
{
TRACE_ERROR("Failed to read from FAT file\r\n");
return ERROR_FAILURE;
}
if (fsWriteFile(outFile, buffer, read) != NO_ERROR)
{
TRACE_ERROR("Failed to write output file\r\n");
return ERROR_FAILURE;
}
}
f_close(&fp);
fsCloseFile(outFile);
} while (1);
f_closedir(&dirInfo);
}
f_unmount("0:");
return NO_ERROR;
}
error_t esp32_fat_inject_folder(FsFile *file, size_t offset, size_t length, const char *path, const char *in_path)
{
if (esp32_wl_init(&esp32_wl_state, file, offset, length) != NO_ERROR)
{
TRACE_ERROR("Failed to init wear leveling\r\n");
return ERROR_FAILURE;
}
FATFS fs;
FRESULT ret = f_mount(&fs, "0:", 1);
if (ret != FR_OK)
{
TRACE_ERROR("Failed to mount image\r\n");
return ERROR_FAILURE;
}
FsDir *dir = fsOpenDir(in_path);
if (!dir)
{
TRACE_ERROR("Failed to open source directory\r\n");
return ERROR_FAILURE;
}
do
{
FsDirEntry dirEntry;
if (fsReadDir(dir, &dirEntry) != NO_ERROR)
{
break;
}
if (dirEntry.attributes & FS_FILE_ATTR_DIRECTORY)
{
continue;
}
char fatFileName[FS_MAX_PATH_LEN];
osStrcpy(fatFileName, path);
osStrcat(fatFileName, "\\");
osStrcat(fatFileName, dirEntry.name);
char inFileName[FS_MAX_PATH_LEN];
osStrcpy(inFileName, in_path);
pathAddSlash(inFileName, FS_MAX_PATH_LEN);
pathCombine(inFileName, dirEntry.name, FS_MAX_PATH_LEN);
pathCanonicalize(inFileName);
TRACE_INFO("Write '%s to '%s'\r\n", inFileName, fatFileName);
FsFile *inFile = fsOpenFile(inFileName, FS_FILE_MODE_READ);
if (!inFile)
{
TRACE_ERROR("Failed to open output file\r\n");
return ERROR_FAILURE;
}
// f_unlink(fatFileName);
FIL fp;
if (f_open(&fp, fatFileName, FA_WRITE | FA_CREATE_ALWAYS) != FR_OK)
{
TRACE_ERROR("Failed to open FAT file\r\n");
return ERROR_FAILURE;
}
uint8_t buffer[512];
uint32_t written_total = 0;
for (int pos = 0; pos < dirEntry.size; pos += sizeof(buffer))
{
size_t read;
if (fsReadFile(inFile, buffer, sizeof(buffer), &read) != NO_ERROR)
{
TRACE_ERROR("Failed to read from input file\r\n");
return ERROR_FAILURE;
}
TRACE_INFO(" Read %" PRIuSIZE " byte\r\n", read);
uint32_t written;
if (f_write(&fp, buffer, read, &written) != FR_OK || read != written)
{
TRACE_ERROR("Failed to write to FAT file\r\n");
return ERROR_FAILURE;
}
written_total += written;
}
TRACE_INFO(" Wrote %d byte\r\n", written_total);
f_sync(&fp);
f_close(&fp);
fsCloseFile(inFile);
} while (1);
fsCloseDir(dir);
f_unmount("0:");
return NO_ERROR;
}
error_t esp32_fixup_partitions(FsFile *file, size_t offset, bool modify)
{
size_t offset_current = offset;
struct ESP32_part_entry entry;
int num = 0;
error_t error;
while (true)
{
fsSeekFile(file, offset_current, FS_SEEK_SET);
size_t read;
error = fsReadFile(file, &entry, sizeof(entry), &read);
if (read != sizeof(entry))
{
TRACE_ERROR("Failed to read entry\r\n");
return ERROR_FAILURE;
}
if (entry.magic == 0x50AA)
{
TRACE_INFO("#%d Type: %d, SubType: %02X, Offset: 0x%06X, Length: 0x%06X, Label: '%s'\r\n", num, entry.partType, entry.partSubType, entry.fileOffset, entry.length, entry.label);
if (entry.partType == ESP_PARTITION_TYPE_APP)
{
esp32_fixup_image(file, entry.fileOffset, entry.length, modify);
}
if (entry.partType == ESP_PARTITION_TYPE_DATA && entry.partSubType == 0x81)
{
esp32_fixup_fatfs(file, entry.fileOffset, entry.length, modify);
}
}
else
{
break;
}
offset_current += sizeof(entry);
num++;
}
return error;
}
error_t esp32_get_partition(FsFile *file, size_t offset, const char *label, size_t *part_start, size_t *part_size)
{
size_t offset_current = offset;
struct ESP32_part_entry entry;
int num = 0;
error_t error;
TRACE_INFO("Search for partition '%s'\r\n", label);
while (true)
{
fsSeekFile(file, offset_current, FS_SEEK_SET);
size_t read;
error = fsReadFile(file, &entry, sizeof(entry), &read);
if (error != NO_ERROR || read != sizeof(entry))
{
TRACE_ERROR("Failed to read entry\r\n");
return ERROR_FAILURE;
}
if (entry.magic == 0x50AA)
{
if (!osStrcmp((const char *)entry.label, label))
{
TRACE_INFO("Found partition '%s' at 0x%06" PRIx32 "\r\n", label, entry.fileOffset);
*part_start = entry.fileOffset;
*part_size = entry.length;
return NO_ERROR;
}
}
else
{
break;
}
offset_current += sizeof(entry);
num++;
}
TRACE_ERROR("Partition '%s' not found\r\n", label);
return ERROR_FAILURE;
}
void esp32_chk_update(uint8_t *chk, void *buffer, size_t length)
{
for (size_t pos = 0; pos < length; pos++)
{
*chk ^= ((uint8_t *)buffer)[pos];
}
}
error_t esp32_fixup_image(FsFile *file, size_t offset, size_t length, bool modify)
{
size_t offset_current = offset;
struct ESP32_header header;
fsSeekFile(file, offset_current, FS_SEEK_SET);
uint8_t chk_calc = 0xEF;
Sha256Context ctx;
sha256Init(&ctx);
size_t read;
error_t error = fsReadFile(file, &header, sizeof(header), &read);
if (read != sizeof(header))
{
TRACE_ERROR("Failed to read header\r\n");
return ERROR_FAILURE;
}
sha256Update(&ctx, &header, sizeof(header));
offset_current += sizeof(header);
if (header.magic != 0xE9)
{
TRACE_INFO("No image found\r\n");
return ERROR_FAILURE;
}
for (int seg = 0; seg < header.segments; seg++)
{
struct ESP32_segment segment;
fsSeekFile(file, offset_current, FS_SEEK_SET);
error = fsReadFile(file, &segment, sizeof(segment), &read);
if (read != sizeof(segment))
{
TRACE_ERROR("Failed to read segment\r\n");
return ERROR_FAILURE;
}
TRACE_INFO("#%d Address: 0x%08X, Len: 0x%06X, Offset: 0x%06X\r\n", seg, segment.loadAddress, segment.length, (uint32_t)offset_current);
sha256Update(&ctx, &segment, sizeof(segment));
offset_current += sizeof(segment);
for (size_t pos = 0; pos < segment.length;)
{
uint8_t buffer[512];
size_t maxLen = sizeof(buffer);
if (maxLen > segment.length - pos)
{
maxLen = segment.length - pos;
}
fsSeekFile(file, offset_current, FS_SEEK_SET);
error = fsReadFile(file, buffer, maxLen, &read);
if (read != maxLen)
{
TRACE_ERROR("Failed to read data\r\n");
return ERROR_FAILURE;
}
sha256Update(&ctx, buffer, maxLen);
esp32_chk_update(&chk_calc, buffer, maxLen);
offset_current += maxLen;
pos += maxLen;
}
}
TRACE_INFO(" Offset: 0x%06X\r\n", (uint32_t)offset_current);
while ((offset_current & 0x0F) != 0x0F)
{
uint8_t null = 0;
sha256Update(&ctx, &null, sizeof(null));
offset_current++;
}
fsSeekFile(file, offset_current, FS_SEEK_SET);
uint8_t chk;
error = fsReadFile(file, &chk, sizeof(chk), &read);
if (read != sizeof(chk))
{
TRACE_ERROR("Failed to read chk\r\n");
return ERROR_FAILURE;
}
TRACE_INFO("CHK: 0x%02X\r\n", chk);
TRACE_INFO("CHK: 0x%02X (calculated)\r\n", chk_calc);
if (modify && chk != chk_calc)
{
TRACE_INFO("Fix checksum\r\n");
fsSeekFile(file, offset_current, FS_SEEK_SET);
error = fsWriteFile(file, &chk_calc, sizeof(chk_calc));
if (error != NO_ERROR)
{
TRACE_ERROR("Failed to write chk\r\n");
return ERROR_FAILURE;
}
}
offset_current += 1;
sha256Update(&ctx, &chk_calc, sizeof(chk_calc));
uint8_t sha256_calc[32];
sha256Final(&ctx, sha256_calc);
if (header.extended.has_hash)
{
uint8_t sha256[32];
error = fsReadFile(file, &sha256, sizeof(sha256), &read);
if (read != sizeof(sha256))
{
TRACE_ERROR("Failed to read sha256\r\n");
return ERROR_FAILURE;
}
char buf[sizeof(sha256) * 2 + 1];
for (int pos = 0; pos < sizeof(sha256); pos++)
{
osSprintf(&buf[pos * 2], "%02X", sha256[pos]);
}
TRACE_INFO("SHA1: %s\r\n", buf);
for (int pos = 0; pos < sizeof(sha256_calc); pos++)
{
osSprintf(&buf[pos * 2], "%02X", sha256_calc[pos]);
}
TRACE_INFO("SHA1: %s (calculated)\r\n", buf);
if (modify && osMemcmp(sha256_calc, sha256, sizeof(sha256_calc)))
{
TRACE_INFO("Fix SHA1\r\n");
fsSeekFile(file, offset_current, FS_SEEK_SET);
error = fsWriteFile(file, &sha256_calc, sizeof(sha256_calc));
if (error != NO_ERROR)
{
TRACE_ERROR("Failed to write SHA1\r\n");
return ERROR_FAILURE;
}
}
}
return error;
}
error_t esp32_fixup(const char *path, bool modify)
{
uint32_t length;
error_t error = fsGetFileSize(path, &length);
if (error || length < 0x9000)
{
TRACE_ERROR("File does not exist or is too small '%s'\r\n", path);
return ERROR_NOT_FOUND;
}
FsFile *file = fsOpenFileEx(path, "rb+");
esp32_fixup_image(file, 0, length, modify);
esp32_fixup_partitions(file, 0x9000, modify);
return NO_ERROR;
}
error_t esp32_fat_extract(const char *firmware, const char *fat_path, const char *out_path)
{
uint32_t length;
error_t error = fsGetFileSize(firmware, &length);
if (error || length < 0x9000)
{
TRACE_ERROR("File does not exist or is too small '%s'\r\n", firmware);
return ERROR_NOT_FOUND;
}
FsFile *file = fsOpenFileEx(firmware, "rb+");
size_t part_offset;
size_t part_size;
error = esp32_get_partition(file, 0x9000, "assets", &part_offset, &part_size);
if (error != NO_ERROR)
{
TRACE_ERROR("Asset partition not found\r\n");
return ERROR_NOT_FOUND;
}
esp32_fat_extract_folder(file, part_offset, part_size, "CERT", out_path);
fsCloseFile(file);
return NO_ERROR;
}
error_t esp32_fat_inject(const char *firmware, const char *fat_path, const char *in_path)
{
uint32_t length;
error_t error = fsGetFileSize(firmware, &length);
if (error || length < 0x9000)
{
TRACE_ERROR("File does not exist or is too small '%s'\r\n", firmware);
return ERROR_NOT_FOUND;
}
FsFile *file = fsOpenFileEx(firmware, "rb+");
size_t part_offset;
size_t part_size;
error = esp32_get_partition(file, 0x9000, "assets", &part_offset, &part_size);
if (error != NO_ERROR)
{
TRACE_ERROR("Asset partition not found\r\n");
return ERROR_NOT_FOUND;
}
esp32_fat_inject_folder(file, part_offset, part_size, fat_path, in_path);
fsCloseFile(file);
return NO_ERROR;
}
/**
* @brief Replaces all occurrences of a pattern string with a replacement string in a given buffer.
*
* This function searches the buffer for the C-string 'pattern' and replaces all its occurrences with the
* C-string 'replace'. It doesn't check if the sizes of the two strings differ and overwrites the original
* string beyond its end if needed. It makes sure not to read or write beyond the buffer end.
*
* @param buffer The buffer in which to replace occurrences of 'pattern'.
* @param buffer_len The length of the buffer.
* @param pattern The pattern string to search for.
* @param replace The replacement string.
* @return The number of replacements made.
*/
uint32_t mem_replace(uint8_t *buffer, size_t buffer_len, const char *pattern, const char *replace)
{
int replaced = 0;
size_t pattern_len = strlen(pattern) + 1;
size_t replace_len = strlen(replace) + 1;
if (pattern_len == 0 || buffer_len == 0)
{
return 0;
}
for (size_t i = 0; i <= buffer_len - pattern_len; ++i)
{
if (memcmp(&buffer[i], pattern, pattern_len) == 0)
{
// Make sure we don't write beyond buffer end
size_t end_index = i + replace_len;
if (end_index > buffer_len)
{
break;
}
memcpy(&buffer[i], replace, replace_len);
i += (pattern_len - 1); // Skip ahead
replaced++;
}
}
return replaced;
}
error_t esp32_inject_cert(const char *rootPath, const char *patchedPath, const char *mac)
{
error_t ret = NO_ERROR;
char *cert_path = custom_asprintf("%s/cert_%s/", rootPath, mac);
TRACE_INFO("Generating certs for MAC %s into '%s'\r\n", mac, cert_path);
do
{
if (!fsDirExists(cert_path))
{
if (fsCreateDir(cert_path) != NO_ERROR)
{
TRACE_ERROR("Failed to create '%s'\r\n", cert_path);
ret = ERROR_NOT_FOUND;
break;
}
}
if (cert_generate_mac(mac, cert_path) != NO_ERROR)
{
TRACE_ERROR("Failed to generate certificate\r\n");
ret = ERROR_NOT_FOUND;
break;
}
TRACE_INFO("Injecting certs into '%s'\r\n", patchedPath);
if (esp32_fat_inject(patchedPath, "CERT", cert_path) != NO_ERROR)
{
TRACE_ERROR("Failed to patch image\r\n");
ret = ERROR_NOT_FOUND;
break;
}
} while (0);
free(cert_path);
return ret;
}
error_t esp32_inject_ca(const char *rootPath, const char *patchedPath, const char *mac)
{
error_t ret = NO_ERROR;
char *cert_path = custom_asprintf("%s/cert_%s/", rootPath, mac);
char *ca_file = custom_asprintf("%s/ca.der", cert_path);
TRACE_INFO("Writing CA into '%s'\r\n", ca_file);
do
{
if (!fsDirExists(cert_path))
{
if (fsCreateDir(cert_path) != NO_ERROR)
{
TRACE_ERROR("Failed to create '%s'\r\n", cert_path);
ret = ERROR_NOT_FOUND;
break;
}
}
const char *server_ca = settings_get_string("internal.server.ca");
size_t server_ca_der_size = 0;
TRACE_INFO("Convert CA certificate...\r\n");
if (pemImportCertificate(server_ca, strlen(server_ca), NULL, &server_ca_der_size, NULL) != NO_ERROR)
{
TRACE_ERROR("pemImportCertificate failed\r\n");
return ERROR_FAILURE;
}
uint8_t *server_ca_der = osAllocMem(server_ca_der_size);
if (pemImportCertificate(server_ca, strlen(server_ca), server_ca_der, &server_ca_der_size, NULL) != NO_ERROR)
{
TRACE_ERROR("pemImportCertificate failed\r\n");
return ERROR_FAILURE;
}
if (fsFileExists(ca_file))
{
if (fsDeleteFile(ca_file) != NO_ERROR)
{
TRACE_ERROR("Failed to delete pre-existing '%s'\r\n", cert_path);
ret = ERROR_NOT_FOUND;
break;
}
}
FsFile *ca = fsOpenFile(ca_file, FS_FILE_MODE_WRITE);
if (!ca)
{
TRACE_ERROR("Failed to create CA file\r\n");
ret = ERROR_NOT_FOUND;
break;
}
if (fsWriteFile(ca, server_ca_der, server_ca_der_size) != NO_ERROR)
{
TRACE_ERROR("Failed to write CA file\r\n");
ret = ERROR_NOT_FOUND;
break;
}
fsCloseFile(ca);
TRACE_INFO("Injecting CA into '%s'\r\n", patchedPath);
if (esp32_fat_inject(patchedPath, "CERT", cert_path) != NO_ERROR)
{
TRACE_ERROR("Failed to patch image\r\n");
ret = ERROR_NOT_FOUND;
break;
}
if (fsDeleteFile(ca_file) != NO_ERROR)
{
TRACE_ERROR("Failed to delete during clean-up '%s'\r\n", cert_path);
ret = ERROR_NOT_FOUND;
break;
}
if (fsRemoveDir(cert_path) != NO_ERROR)
{
TRACE_ERROR("Failed to delete directory during clean-up '%s'\r\n", cert_path);
ret = ERROR_NOT_FOUND;
break;
}
} while (0);
free(cert_path);
free(ca_file);
return ret;
}
error_t esp32_patch_host(const char *patchedPath, const char *hostname)
{
error_t ret = NO_ERROR;
TRACE_INFO("Patching hostnames in '%s'\r\n", patchedPath);
do
{
uint32_t bin_size = 0;
size_t total = 0;
if (fsGetFileSize(patchedPath, &bin_size))
{
TRACE_ERROR("File does not exist '%s'\r\n", patchedPath);
return ERROR_NOT_FOUND;