-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathbt.h
1476 lines (1293 loc) · 42.2 KB
/
bt.h
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
#ifndef BT_H
#define BT_H
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <vector>
#include <unordered_set>
#include <stdarg.h>
#include <boost/crc.hpp>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
//#define USE_OPENSSL 1
#ifdef USE_OPENSSL
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/ec.h>
#include <openssl/pem.h>
#endif
#include "file_accessor.h"
typedef unsigned int UINT;
typedef char byte;
typedef char CHAR;
typedef char BYTE;
typedef unsigned char uchar;
typedef unsigned char ubyte;
typedef unsigned char UCHAR;
typedef unsigned char UBYTE;
typedef short int16;
typedef short SHORT;
typedef short INT16;
typedef unsigned short uint16;
typedef unsigned short ushort;
typedef unsigned short USHORT;
typedef unsigned short UINT16;
typedef unsigned short WORD;
typedef int int32;
typedef int INT;
typedef int INT32;
typedef int LONG;
typedef unsigned int uint;
typedef unsigned int uint32;
//typedef unsigned int ulong;
typedef unsigned int UINT;
typedef unsigned int UINT32;
typedef unsigned int ULONG;
typedef unsigned int DWORD;
typedef long long int64;
typedef long long quad;
typedef long long QUAD;
typedef long long INT64;
typedef long long __int64;
typedef unsigned long long uint64;
typedef unsigned long long uquad;
typedef unsigned long long UQUAD;
typedef unsigned long long UINT64;
typedef unsigned long long QWORD;
typedef unsigned long long __uint64;
typedef float FLOAT;
typedef double DOUBLE;
typedef float hfloat;
typedef float HFLOAT;
typedef unsigned long long OLETIME;
typedef long time_t;
const int CHECKSUM_BYTE = 0;
const int CHECKSUM_SHORT_LE = 1;
const int CHECKSUM_SHORT_BE = 2;
const int CHECKSUM_INT_LE = 3;
const int CHECKSUM_INT_BE = 4;
const int CHECKSUM_INT64_LE = 5;
const int CHECKSUM_INT64_BE = 6;
const int CHECKSUM_SUM8 = 7;
const int CHECKSUM_SUM16 = 8;
const int CHECKSUM_SUM32 = 9;
const int CHECKSUM_SUM64 = 10;
const int CHECKSUM_CRC16 = 11;
const int CHECKSUM_CRCCCITT = 12;
const int CHECKSUM_CRC32 = 13;
const int CHECKSUM_ADLER32 = 14;
const int CHECKSUM_MD2 = 15;
const int CHECKSUM_MD4 = 16;
const int CHECKSUM_MD5 = 17;
const int CHECKSUM_RIPEMD160 = 18;
const int CHECKSUM_SHA1 = 19;
const int CHECKSUM_SHA256 = 20;
const int CHECKSUM_SHA384 = 21;
const int CHECKSUM_SHA512 = 22;
const int CHECKSUM_TIGER = 23;
const int CHECKSUM_CRC8 = 24;
const int FINDMETHOD_NORMAL = 0;
const int FINDMETHOD_WILDCARDS = 1;
const int FINDMETHOD_REGEX = 2;
const int cBlack = 0x000000;
const int cRed = 0x0000ff;
const int cDkRed = 0x000080;
const int cLtRed = 0x8080ff;
const int cGreen = 0x00ff00;
const int cDkGreen = 0x008000;
const int cLtGreen = 0x80ff80;
const int cBlue = 0xff0000;
const int cDkBlue = 0x800000;
const int cLtBlue = 0xff8080;
const int cPurple = 0xff00ff;
const int cDkPurple = 0x800080;
const int cLtPurple = 0xffe0ff;
const int cAqua = 0xffff00;
const int cDkAqua = 0x808000;
const int cLtAqua = 0xffffe0;
const int cYellow = 0x00ffff;
const int cDkYellow = 0x008080;
const int cLtYellow = 0x80ffff;
const int cDkGray = 0x404040;
const int cGray = 0x808080;
const int cSilver = 0xc0c0c0;
const int cLtGray = 0xe0e0e0;
const int cWhite = 0xffffff;
const int cNone = 0xffffffff;
const int True = 1;
const int TRUE = 1;
const int False = 0;
const int FALSE = 0;
#define GENERATE_VAR(name, value) do { \
start_generation(#name); \
name ## _var = (value); \
name ## _exists = true; \
end_generation(); \
} while (0)
#define GENERATE(name, value) do { \
start_generation(#name); \
(value); \
end_generation(); \
} while (0)
#define GENERATE_EXISTS(name, value) \
name ## _exists = true
unsigned long long STR2INT(std::string s) {
assert(s.size() <= 8);
unsigned long long result = 0;
for (char& c : s) {
result = (result << 8) | c;
}
return result;
}
constexpr unsigned long long STR2INT(const char * s) {
#ifndef __clang__
assert(strlen(s) <= 8);
#endif
unsigned long long result = 0;
while (*s) {
result = (result << 8) | *s;
++s;
}
return result;
}
extern unsigned char *rand_buffer;
file_accessor file_acc;
extern bool is_big_endian;
extern bool is_padded_bitfield;
void generate_file();
bool aflsmart_output = false;
double get_validity() {
return (double)file_acc.parsed_file_size / (double)file_acc.final_file_size;
}
void start_generation(const char* name) {
if (!get_parse_tree)
return;
generator_stack.emplace_back(name, file_acc.rand_prev, file_acc.rand_pos);
file_acc.rand_prev = file_acc.rand_pos;
file_acc.rand_last = UINT_MAX;
}
void end_generation() {
if (!get_parse_tree)
return;
stack_cell& back = generator_stack.back();
stack_cell& prev = generator_stack[generator_stack.size() - 2];
file_acc.rand_prev = file_acc.rand_pos;
if (smart_mutation && back.rand_start == rand_start && (is_optional || strcmp(back.name, chunk_name) == 0)) {
unsigned size = MAX_RAND_SIZE - file_acc.rand_pos;
if (size > MAX_RAND_SIZE - (rand_end + 1))
size = MAX_RAND_SIZE - (rand_end + 1);
memmove(file_acc.rand_buffer + file_acc.rand_pos, file_acc.rand_buffer + (rand_end + 1), size);
if (smart_swapping) {
if (rand_start2 > rand_end)
rand_start2 += file_acc.rand_pos - (rand_end + 1);
rand_end2 += file_acc.rand_pos - (rand_end + 1);
}
rand_end = file_acc.rand_pos - 1;
}
if (smart_swapping && back.rand_start == rand_start2 && (is_optional || strcmp(back.name, chunk_name2) == 0)) {
unsigned size = MAX_RAND_SIZE - file_acc.rand_pos;
if (size > MAX_RAND_SIZE - (rand_end2 + 1))
size = MAX_RAND_SIZE - (rand_end2 + 1);
memmove(file_acc.rand_buffer + file_acc.rand_pos, file_acc.rand_buffer + (rand_end2 + 1), size);
rand_end2 = file_acc.rand_pos - 1;
}
if (smart_abstraction && back.rand_start == rand_start && (is_optional || strcmp(back.name, chunk_name) == 0)) {
if (following_rand_size > MAX_RAND_SIZE - file_acc.rand_pos)
following_rand_size = MAX_RAND_SIZE - file_acc.rand_pos;
memcpy(file_acc.rand_buffer + file_acc.rand_pos, following_rand_buffer, following_rand_size);
smart_abstraction = false;
}
if (back.min < prev.min)
prev.min = back.min;
if (back.max > prev.max)
prev.max = back.max;
if (back.min > back.max) {
back.min = file_acc.file_pos;
back.max = file_acc.file_pos - 1;
}
if (debug_print && back.min <= back.max) {
// printf("%u,%u, ", back.rand_start, file_acc.rand_pos - 1);
printf("%u,%u,", back.min, back.max);
bool first = true;
stack_cell* parent = NULL;
for (auto& cell : generator_stack) {
if (first) {
printf("%s", cell.name);
first = false;
} else {
printf("~%s", cell.name);
if (parent->counts[cell.name])
printf("_%u", parent->counts[cell.name]);
}
parent = &cell;
}
if (aflsmart_output) {
printf(",Enabled\n");
} else {
if (file_acc.rand_last != UINT_MAX)
printf(",Appendable");
if (back.rand_start != back.rand_start_real)
printf(",Optional\n");
else
printf("\n");
}
}
if (get_chunk && back.min == chunk_start && back.max == chunk_end) {
printf("TARGET CHUNK FOUND\n");
rand_start = back.rand_start;
rand_end = file_acc.rand_pos - 1;
is_optional = back.rand_start != back.rand_start_real;
chunk_name = back.name;
if (is_delete) {
is_following = true;
delete_start = back.min;
delete_end = back.max;
}
}
if (get_chunk && chunk_end == UINT_MAX && back.max == chunk_start - 1 && file_acc.rand_last != UINT_MAX) {
printf("APPENDABLE CHUNK FOUND\n");
rand_start = file_acc.rand_last;
chunk_name = back.name;
}
if (get_chunk && chunk_end == UINT_MAX && back.min == chunk_start && back.rand_start != back.rand_start_real) {
printf("OPTIONAL CHUNK FOUND\n");
rand_start = back.rand_start;
chunk_name = back.name;
}
if (get_all_chunks) {
if (back.rand_start != back.rand_start_real) {
optional_chunks.emplace_back(file_index, back.rand_start, file_acc.rand_pos - 1, variable_types[back.name].c_str(), back.name, back.min, back.max);
insertion_points[file_index].emplace_back(back.rand_start, variable_types[back.name].c_str(), back.name, back.min);
is_following = true;
chunk_name = back.name;
rand_start = back.rand_start;
rand_end = file_acc.rand_pos - 1;
delete_start = back.min;
delete_end = back.max;
} else if (file_acc.rand_pos > back.rand_start) {
int size = non_optional_index[file_index].size();
int i;
for (i = 0; i < size; ++i) {
if (strcmp(non_optional_index[file_index][i].type, variable_types[back.name].c_str()) == 0) {
++non_optional_index[file_index][i].size;
break;
}
}
if (i == size) {
non_optional_index[file_index].emplace_back(variable_types[back.name].c_str(), non_optional_chunks[variable_types[back.name]].size(), 1);
}
non_optional_chunks[variable_types[back.name]].emplace_back(file_index, back.rand_start, file_acc.rand_pos - 1, variable_types[back.name].c_str(), back.name, back.min, back.max);
}
if (file_acc.rand_last != UINT_MAX) {
insertion_points[file_index].emplace_back(file_acc.rand_last, variable_types[back.name].c_str(), back.name, back.max + 1);
}
}
file_acc.rand_last = UINT_MAX;
++prev.counts[back.name];
generator_stack.pop_back();
}
char* get_bin_name(char* arg) {
char* bin = strrchr(arg, '/');
if (bin)
return bin+1;
return arg;
}
void set_parser() {
file_acc.generate = false;
}
void set_generator() {
file_acc.generate = true;
}
bool setup_input(const char* filename) {
bool success = true;
debug_print = true;
int file_fd;
if (strcmp(filename, "-") == 0)
file_fd = STDIN_FILENO;
else
file_fd = open(filename, O_RDONLY);
if (file_fd == -1) {
perror(filename);
exit(1);
}
if (file_fd == STDIN_FILENO) {
// Read from stdin, up to MAX_RAND_SIZE
unsigned char *p = rand_buffer;
ssize_t size;
ssize_t chars_left = MAX_RAND_SIZE;
while (chars_left > 0 &&
(size = read(file_fd, p, chars_left)) > 0)
{
p += size;
chars_left -= size;
}
if (chars_left == 0)
{
perror("Standard input size exceeds MAX_RAND_SIZE");
exit(1);
}
ssize_t total = p - rand_buffer;
file_acc.seed(rand_buffer, MAX_RAND_SIZE, total);
}
if (file_acc.generate) {
ssize_t size = read(file_fd, rand_buffer, MAX_RAND_SIZE);
if (size < 0) {
perror("Failed to read seed file");
exit(1);
}
file_acc.seed(rand_buffer, size, 0);
} else {
get_parse_tree = true;
struct stat st;
if (fstat(file_fd, &st)) {
perror("Failed to stat input file");
exit(1);
}
ssize_t file_size = st.st_size;
if (file_size > MAX_FILE_SIZE) {
fprintf(stderr, "File size exceeds MAX_FILE_SIZE\n");
file_size = MAX_FILE_SIZE;
success = false;
}
ssize_t size = read(file_fd, file_acc.file_buffer, file_size);
if (size != file_size) {
perror("Failed to read input file");
exit(1);
}
file_acc.seed(rand_buffer, MAX_RAND_SIZE, file_size);
}
if (file_fd != STDIN_FILENO)
close(file_fd);
return success;
}
void save_output(const char* filename) {
int file_fd;
if (strcmp(filename, "-") == 0)
file_fd = STDOUT_FILENO;
else
file_fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
if (file_fd == -1) {
perror(filename);
exit(1);
}
if (file_acc.generate) {
ssize_t res = write(file_fd, file_acc.file_buffer, file_acc.file_size);
if (res != file_acc.file_size)
fprintf(stderr, "Failed to write file\n");
} else {
ssize_t res = write(file_fd, rand_buffer, file_acc.rand_pos);
if (res != file_acc.rand_pos)
fprintf(stderr, "Failed to write file\n");
}
if (file_fd != STDOUT_FILENO)
close(file_fd);
}
unsigned copy_rand(unsigned char *dest) {
memcpy(dest, file_acc.rand_buffer, file_acc.rand_pos);
return file_acc.rand_pos;
}
void delete_globals();
extern "C" size_t ff_generate(unsigned char* data, size_t size, unsigned char** new_data) {
file_acc.seed(data, size, 0);
try {
generate_file();
} catch (int status) {
delete_globals();
if (status) {
*new_data = NULL;
return 0;
}
} catch (...) {
delete_globals();
*new_data = NULL;
return 0;
}
*new_data = file_acc.file_buffer;
return file_acc.file_size;
}
extern "C" int ff_parse(unsigned char* data, size_t size, unsigned char** new_data, size_t* new_size) {
file_acc.generate = false;
if (size > MAX_FILE_SIZE) {
fprintf(stderr, "File size larger than MAX_FILE_SIZE\n");
size = MAX_FILE_SIZE;
}
if (data != file_acc.file_buffer) {
memcpy(file_acc.file_buffer, data, size);
}
memset(file_acc.file_buffer + size, 0, MAX_FILE_SIZE - size);
file_acc.seed(rand_buffer, MAX_RAND_SIZE, size);
bool success = true;
try {
generate_file();
} catch (int status) {
delete_globals();
if (status)
success = false;
} catch (...) {
delete_globals();
success = false;
}
*new_data = rand_buffer;
*new_size = file_acc.rand_pos;
file_acc.generate = true;
return success;
}
void exit_template(int status) {
if (debug_print || print_errors)
fprintf(stderr, "Template exited with code %d\n", status);
throw status;
}
void exit_template(std::string message) {
if (debug_print || print_errors)
fprintf(stderr, "Template exited with message: %s\n", message.c_str());
throw -1;
}
#ifdef USE_OPENSSL
RSA *rsa = NULL;
EC_KEY *eckey = NULL;
RSA *ca_rsa = NULL;
bool RSA_key_generate(std::string& modulus, std::string& public_exponent) {
int ret = 0, req = 0;
rsa = NULL;
BIGNUM *bne = NULL;
BIO *bp_public = NULL, *bp_private = NULL;
int bits = 2048;
unsigned long e = RSA_F4;
unsigned char *ptr;
if (file_acc.generate) {
// generate rsa key
bne = BN_new();
ret = BN_set_word(bne, e);
if(ret != 1){
goto free_all;
}
rsa = RSA_new();
ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
if(ret != 1){
goto free_all;
}
// save private key
bp_private = BIO_new_file("private_rsa.pem", "w+");
ret = PEM_write_bio_RSAPrivateKey(bp_private, rsa, NULL, NULL, 0, NULL, NULL);
if(ret != 1){
goto free_all;
}
if (debug_print)
printf("Wrote RSA key to file private_rsa.pem\n");
} else {
// read rsa key
bp_private = BIO_new_file("private_rsa.pem", "r");
if(!bp_private){
fprintf(stderr, "Failed to read RSA key from file private_rsa.pem\n");
abort();
}
rsa = PEM_read_bio_RSAPrivateKey(bp_private, NULL, NULL, NULL);
if(!rsa){
fprintf(stderr, "Failed to read RSA key from file private_rsa.pem\n");
abort();
}
if (debug_print)
printf("Read RSA key from file private_rsa.pem\n");
}
// save public key
bp_public = BIO_new_file("public_rsa.pem", "w+");
ret = PEM_write_bio_RSAPublicKey(bp_public, rsa);
if(ret != 1){
goto free_all;
}
// get modulus
req = BN_num_bytes(RSA_get0_n(rsa));
ptr = (unsigned char *) OPENSSL_malloc(req);
ret = BN_bn2bin(RSA_get0_n(rsa), ptr);
modulus = std::string((const char *)ptr, ret);
OPENSSL_free(ptr);
// get public exponent
req = BN_num_bytes(RSA_get0_e(rsa));
ptr = (unsigned char *) OPENSSL_malloc(req);
ret = BN_bn2bin(RSA_get0_e(rsa), ptr);
public_exponent = std::string((const char *)ptr, ret);
OPENSSL_free(ptr);
ret = 1;
// free
free_all:
BIO_free_all(bp_public);
BIO_free_all(bp_private);
BN_free(bne);
return (ret == 1);
}
bool EC_key_generate(std::string& public_point) {
int ret = 0;
eckey = NULL;
BIGNUM *bne = NULL;
BIO *bp_public = NULL, *bp_private = NULL;
EC_POINT *pub_key = NULL;
EC_GROUP *prime256v1_group = NULL;
unsigned char *ptr;
// 1. generate ec key
eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
ret = EC_KEY_generate_key(eckey);
if(ret != 1){
goto free_all;
}
// 2. save public key
bp_public = BIO_new_file("public_ec.pem", "w+");
ret = PEM_write_bio_EC_PUBKEY(bp_public, eckey);
if(ret != 1){
goto free_all;
}
// 3. save private key
bp_private = BIO_new_file("private_ec.pem", "w+");
ret = PEM_write_bio_ECPrivateKey(bp_private, eckey, NULL, NULL, 0, NULL, NULL);
if(ret != 1){
goto free_all;
}
// 4. get public point
pub_key = (EC_POINT *)EC_KEY_get0_public_key(eckey);
prime256v1_group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
ret = EC_POINT_point2buf(prime256v1_group, pub_key, POINT_CONVERSION_COMPRESSED, &ptr, nullptr);
EC_GROUP_free(prime256v1_group);
public_point = std::string((const char *)ptr, ret);
OPENSSL_free(ptr);
ret = 1;
// 5. free
free_all:
BIO_free_all(bp_public);
BIO_free_all(bp_private);
BN_free(bne);
return (ret == 1);
}
void read_ca_key() {
BIO *bp_private = NULL;
// read CA rsa key
bp_private = BIO_new_file("ca_rsa.pem", "r");
if(!bp_private){
fprintf(stderr, "Failed to read RSA key from file ca_rsa.pem\n");
abort();
}
ca_rsa = PEM_read_bio_RSAPrivateKey(bp_private, NULL, NULL, NULL);
if(!ca_rsa){
fprintf(stderr, "Failed to read RSA key from file ca_rsa.pem\n");
abort();
}
if (debug_print)
printf("Read CA RSA key from file ca_rsa.pem\n");
}
bool RSA_sign_SHA256(int64 start, int64 size, std::string& signature) {
read_ca_key();
int ret = 0;
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha;
SHA256_Init(&sha);
SHA256_Update(&sha, file_acc.file_buffer + start, size);
SHA256_Final(hash, &sha);
unsigned char* sigret = (unsigned char *) OPENSSL_malloc(RSA_size(ca_rsa));
unsigned int siglen = 0;
ret = RSA_sign(NID_sha256, hash, SHA256_DIGEST_LENGTH, sigret, &siglen, ca_rsa);
signature = std::string((const char *)sigret, siglen);
OPENSSL_free(sigret);
return (ret == 1);
}
bool ECDSA_sign_SHA256(int64 start, int64 size, std::string& signature) {
assert_cond(eckey, "No EC key available for signing");
int ret = 0;
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha;
SHA256_Init(&sha);
SHA256_Update(&sha, file_acc.file_buffer + start, size);
SHA256_Final(hash, &sha);
unsigned char* sigret = (unsigned char *) OPENSSL_malloc(ECDSA_size(eckey));
unsigned int siglen = 0;
ret = ECDSA_sign(0, hash, SHA256_DIGEST_LENGTH, sigret, &siglen, eckey);
signature = std::string((const char *)sigret, siglen);
OPENSSL_free(sigret);
return (ret == 1);
}
#endif
void Assert(int value, const char* msg = "") {
if (!value)
exit_template(msg);
}
int Abs(int value) {
return abs(value);
}
bool change_array_length = false;
void check_array_length(unsigned& size) {
if (change_array_length && size > MAX_FILE_SIZE/16 && file_acc.generate) {
unsigned new_size = file_acc.rand_int(16, file_acc.parse);
if (debug_print)
fprintf(stderr, "Array length too large: %d, replaced with %u\n", (signed)size, new_size);
size = new_size;
}
assert_cond(size <= MAX_FILE_SIZE - file_acc.file_pos, "Array length too large");
}
void ChangeArrayLength() {
change_array_length = true;
}
void EndChangeArrayLength() {
change_array_length = false;
}
bool global_indexing_of_arrays = false;
void GlobalIndexingOfArrays() {
global_indexing_of_arrays = true;
}
void BigEndian() { is_big_endian = true; }
void LittleEndian() { is_big_endian = false; }
int IsBigEndian() { return is_big_endian; }
void BitfieldLeftToRight() {
is_bitfield_left_to_right[is_big_endian] = true;
}
void BitfieldEnablePadding() {
if (is_padded_bitfield)
return;
file_acc.finish_bitfield();
is_padded_bitfield = true;
}
void BitfieldDisablePadding() {
if (!is_padded_bitfield)
return;
file_acc.finish_bitfield();
is_padded_bitfield = false;
}
void SetForeColor(int color) { }
void SetBackColor(int color) { }
void Exit(int errorcode) { exit_template(errorcode); }
void DisplayFormatBinary() { }
void DisplayFormatDecimal() { }
void DisplayFormatHex() { }
void DisplayFormatOctal() { }
int SetEvilBit(int allow) {
return file_acc.set_evil_bit(allow);
}
uint32 Checksum(int checksum_type, int64 start, int64 size) {
assert_cond(start >= 0 && size >= 0 && start + size <= file_acc.file_size, "checksum range invalid");
switch(checksum_type) {
case CHECKSUM_CRC8: {
boost::crc_optimal<8, 0x07, 0x00, 0, false, false> res;
res.process_bytes(file_acc.file_buffer + start, size);
return res.checksum();
}
case CHECKSUM_CRC16: {
boost::crc_16_type res;
res.process_bytes(file_acc.file_buffer + start, size);
return res.checksum();
}
case CHECKSUM_CRC32: {
boost::crc_32_type res;
res.process_bytes(file_acc.file_buffer + start, size);
return res.checksum();
}
default:
abort();
}
}
#ifdef USE_OPENSSL
int ChecksumAlgStr(int algorithm, std::string& result, int64 start = 0, int64 size = 0, std::string ignore = "", int64 crcPolynomial = -1, int64 crcInitValue = -1) {
// Other configurations not yet handled
assert(ignore == "" && crcPolynomial == -1 && crcInitValue == -1);
assert_cond(start >= 0 && size >= 0 && start + size <= file_acc.file_size, "checksum range invalid");
switch(algorithm) {
case CHECKSUM_MD5: {
unsigned char res[MD5_DIGEST_LENGTH];
MD5(file_acc.file_buffer + start, size, res);
result = std::string((const char*)res, MD5_DIGEST_LENGTH);
return MD5_DIGEST_LENGTH;
}
default:
abort();
}
}
#endif
void Warning(const std::string fmt, ...) {
if (!debug_print && !print_errors)
return;
fprintf(stderr, "Warning: ");
va_list args;
va_start(args,fmt);
vfprintf(stderr, fmt.c_str(), args);
va_end(args);
fprintf(stderr, "\n");
}
int Printf(const std::string fmt, ...) {
if (!debug_print)
return 0;
va_list args;
va_start(args,fmt);
int result = vprintf(fmt.c_str(), args);
va_end(args);
return result;
}
int StatusMessage(const std::string fmt, ...) {
if (!debug_print)
return 0;
va_list args;
va_start(args,fmt);
int result = vprintf(fmt.c_str(), args);
va_end(args);
return result;
}
int SPrintf(std::string& s, const char* fmt, ...) {
char res[4096];
va_list args;
va_start(args,fmt);
int result = vsnprintf(res, 4096, fmt, args);
va_end(args);
s = res;
return result;
}
std::string Str(const char* fmt, ...) {
char res[4096];
va_list args;
va_start(args,fmt);
vsnprintf(res, 4096, fmt, args);
va_end(args);
return res;
}
int Atoi(std::string s) {
return atoi(s.c_str());
}
int Strlen(std::string s) { return s.size(); }
int Strcmp(std::string s1, std::string s2) {
return strcmp(s1.c_str(), s2.c_str());
}
int Strncmp(std::string s1, std::string s2, int n) {
assert ((unsigned) n <= s1.length() && (unsigned) n <= s2.length());
return strncmp(s1.c_str(), s2.c_str(), n);
}
int Strstr(std::string s1, std::string s2) {
return s1.find(s2);
}
std::string SubStr(std::string s, int start, int count = -1) {
size_t len = s.length();
assert_cond((unsigned)start < len, "SubStr: invalid position");
if (count == -1)
return std::string(s.c_str() + start, len - start);
assert_cond((unsigned)count <= len - start, "SubStr: invalid count");
return std::string(s.c_str() + start, count);
}
int Memcmp(std::string s1, std::string s2, int n) {
assert ((unsigned) n <= s1.length() && (unsigned) n <= s2.length());
return memcmp(s1.c_str(), s2.c_str(), n);
}
void Memcpy(std::string& dest, std::string src, int n, int destOffset = 0, int srcOffset = 0) {
// Other configurations not yet handled
assert(destOffset == 0 && srcOffset == 0);
assert ((unsigned) n <= src.length());
dest = std::string(src.c_str(), n);
}
int IsParsing() {
return !file_acc.generate;
}
int FEof(double p = 0.125) { return file_acc.feof(p); }
int64 FTell() { return file_acc.file_pos; }
int64 FTellBits() { return file_acc.file_pos * 8 + file_acc.bitfield_bits; }
int FSeek(int64 pos, bool print = true) {
assert_cond(0 <= pos && pos <= MAX_FILE_SIZE, "FSeek/FSkip: invalid position");
if (print && debug_print && file_acc.file_pos != pos)
fprintf(stderr, "FSeek from %u to %lld\n", file_acc.file_pos, pos);
if (pos > file_acc.file_size) {
if (debug_print)
fprintf(stderr, "Padding file from %u to %lld\n", file_acc.file_size, pos);
file_acc.file_pos = file_acc.file_size;
file_acc.is_padding = true;
while (file_acc.file_pos < pos) {
file_acc.file_integer(1, 0, 0);
}
file_acc.is_padding = false;
} else {
file_acc.file_pos = pos;
}
return 0;
}
int FSkip(int64 offset) {
if (debug_print && offset != 0)
fprintf(stderr, "FSkip from %u to %lld\n", file_acc.file_pos, file_acc.file_pos + offset);
return FSeek(file_acc.file_pos + offset, false);
}
int64 FileSize() {
if (!file_acc.has_size) {
file_acc.lookahead = true;
if (!file_acc.generate)
file_acc.parse = [](unsigned char* file_buf) -> long long { return file_acc.final_file_size - file_acc.file_size; };
unsigned new_file_size = file_acc.file_size + file_acc.rand_int(MAX_FILE_SIZE + 1 - file_acc.file_size, file_acc.parse);
file_acc.lookahead = false;
if (debug_print)
fprintf(stderr, "FileSize %u\n", new_file_size);
int64 original_pos = FTell();
FSeek(new_file_size, false);
FSeek(original_pos, false);
file_acc.has_size = true;
}
return file_acc.file_size;
}
unsigned get_file_size() {
return file_acc.file_size;
}
class TFindResults {
public:
int count_var = 0;
std::vector<long> start_var;
std::vector<long> size_var;
int& count() { return count_var; }
std::vector<long>& start() { return start_var; }
std::vector<long>& size() { return size_var; }
};
template<typename T>
TFindResults FindAll(T data, int matchcase=true, int wholeword=false, int method=0, double tolerance=0.0, int dir=1, int64 start=0, int64 size=0, int wildcardMatchLength=24) {
// Arbitrary types T not yet handled
abort();
}
template<>
TFindResults FindAll(const char* data, int matchcase, int wholeword, int method, double tolerance, int dir, int64 start, int64 size, int wildcardMatchLength) {
// Other configurations not yet handled
assert(matchcase == true && wholeword == false && method == 0 && tolerance == 0.0 && dir == 1 && size == 0 && wildcardMatchLength == 24);
// This function is currently only implemented in parsing mode
assert(!file_acc.generate);
unsigned data_size = strlen(data);
TFindResults res;
while (true) {
unsigned char* p = (unsigned char*) memmem(file_acc.file_buffer + start, file_acc.final_file_size - start, data, data_size);
if (!p)
break;
++res.count_var;
res.start_var.push_back(p - file_acc.file_buffer);
res.size_var.push_back(data_size);
start = (p - file_acc.file_buffer) + 1;
}
return res;
}
template<typename T>
int64 FindFirst(T data, int matchcase=true, int wholeword=false, int method=0, double tolerance=0.0, int dir=1, int64 start=0, int64 size=0, int wildcardMatchLength=24) {
// Other configurations not yet handled
assert(matchcase == true && wholeword == false && method == 0 && tolerance == 0.0 && dir == 1 && size == 0 && wildcardMatchLength == 24);
T newdata = data;
swap_bytes(&newdata, sizeof(T));