-
Notifications
You must be signed in to change notification settings - Fork 663
/
bytecode.c
3625 lines (3398 loc) · 125 KB
/
bytecode.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
/*
* Load, and verify ClamAV bytecode.
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include <string.h>
#include <assert.h>
#include <fcntl.h>
#if HAVE_JSON
#include "json.h"
#endif
#include "dconf.h"
#include "clamav.h"
#include "others.h"
#include "pe.h"
#include "bytecode.h"
#include "bytecode_priv.h"
#include "bytecode_detect.h"
#include "readdb.h"
#include "scanners.h"
#include "bytecode_api.h"
#include "bytecode_api_impl.h"
#include "builtin_bytecodes.h"
#ifndef MAX_TRACKED_BC
#define MAX_TRACKED_BC 64
#endif
#define BC_EVENTS_PER_SIG 2
#define MAX_BC_SIGEVENT_ID MAX_TRACKED_BC *BC_EVENTS_PER_SIG
cli_events_t *g_sigevents = NULL;
unsigned int g_sigid;
/* dummy values */
static const uint32_t nomatch[64] = {
0xdeadbeef, 0xdeaddead, 0xbeefdead, 0xdeaddead, 0xdeadbeef, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
static const uint32_t nooffsets[64] = {
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE,
CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE, CLI_SIZE_NONE};
static const uint16_t nokind;
static const uint32_t nofilesize;
static const struct cli_pe_hook_data nopedata;
static void context_safe(struct cli_bc_ctx *ctx)
{
/* make sure these are never NULL */
if (!ctx->hooks.kind)
ctx->hooks.kind = &nokind;
if (!ctx->hooks.match_counts)
ctx->hooks.match_counts = nomatch;
if (!ctx->hooks.match_offsets)
ctx->hooks.match_offsets = nooffsets;
if (!ctx->hooks.filesize)
ctx->hooks.filesize = &nofilesize;
if (!ctx->hooks.pedata)
ctx->hooks.pedata = &nopedata;
}
/**
* @brief Reset bytecode state, so you can run another bytecode with same ctx.
*
* IMPORTANT: This function does not clear/reset all fields in the context!
*
* @param ctx
*/
static void bytecode_context_reset(struct cli_bc_ctx *ctx)
{
unsigned i;
free(ctx->opsizes);
ctx->opsizes = NULL;
free(ctx->values);
ctx->values = NULL;
free(ctx->operands);
ctx->operands = NULL;
if (-1 != ctx->outfd) {
close(ctx->outfd);
ctx->outfd = -1;
cli_ctx *cctx = ctx->ctx;
if (ctx->tempfile && (!cctx || !cctx->engine->keeptmp)) {
cli_unlink(ctx->tempfile);
}
free(ctx->tempfile);
ctx->tempfile = NULL;
}
if (ctx->jsnormdir) {
char fullname[1025];
cli_ctx *cctx = ctx->ctx;
int fd;
cl_error_t ret = CL_CLEAN;
if (!ctx->found) {
snprintf(fullname, 1024, "%s" PATHSEP "javascript", ctx->jsnormdir);
fd = open(fullname, O_RDONLY | O_BINARY);
if (fd >= 0) {
cctx->next_layer_is_normalized = true; // This flag ingested by cli_recursion_stack_push().
ret = cli_scan_desc(fd, cctx, CL_TYPE_HTML, false, NULL, AC_SCAN_VIR, NULL, NULL);
if (ret == CL_CLEAN) {
if (lseek(fd, 0, SEEK_SET) == -1)
cli_dbgmsg("cli_bytecode: call to lseek() has failed\n");
else {
cctx->next_layer_is_normalized = true; // This flag ingested by cli_recursion_stack_push().
ret = cli_scan_desc(fd, cctx, CL_TYPE_TEXT_ASCII, false, NULL, AC_SCAN_VIR, NULL, NULL);
}
}
close(fd);
}
}
if (!cctx || !cctx->engine->keeptmp) {
cli_rmdirs(ctx->jsnormdir);
}
free(ctx->jsnormdir);
if (ret != CL_SUCCESS) {
ctx->found = 1;
}
}
ctx->numParams = 0;
ctx->funcid = 0;
/* don't touch fmap, file_size, and hooks, sections, ctx, timeout, pdf* */
ctx->off = 0;
ctx->written = 0;
ctx->jsnormwritten = 0;
#if USE_MPOOL
if (ctx->mpool) {
mpool_destroy(ctx->mpool);
ctx->mpool = NULL;
}
#else
/*TODO: implement for no-mmap case too*/
#endif
for (i = 0; i < ctx->ninflates; i++)
cli_bcapi_inflate_done(ctx, i);
free(ctx->inflates);
ctx->inflates = NULL;
ctx->ninflates = 0;
for (i = 0; i < ctx->nlzmas; i++)
cli_bcapi_lzma_done(ctx, i);
free(ctx->lzmas);
ctx->lzmas = NULL;
ctx->nlzmas = 0;
#if HAVE_BZLIB_H
for (i = 0; i < ctx->nbzip2s; i++)
cli_bcapi_bzip2_done(ctx, i);
free(ctx->bzip2s);
ctx->bzip2s = NULL;
ctx->nbzip2s = 0;
#endif
for (i = 0; i < ctx->nbuffers; i++)
cli_bcapi_buffer_pipe_done(ctx, i);
free(ctx->buffers);
ctx->buffers = NULL;
ctx->nbuffers = 0;
for (i = 0; i < ctx->nhashsets; i++)
cli_bcapi_hashset_done(ctx, i);
free(ctx->hashsets);
ctx->hashsets = NULL;
ctx->nhashsets = 0;
for (i = 0; i < ctx->njsnorms; i++)
cli_bcapi_jsnorm_done(ctx, i);
free(ctx->jsnorms);
ctx->jsnorms = NULL;
ctx->njsnorms = 0;
ctx->jsnormdir = NULL;
for (i = 0; i < ctx->nmaps; i++)
cli_bcapi_map_done(ctx, i);
free(ctx->maps);
ctx->maps = NULL;
ctx->nmaps = 0;
/* Use input_switch() to free the extracted file fmap, if one exists */
cli_bcapi_input_switch(ctx, 0);
#if HAVE_JSON
free((json_object **)(ctx->jsonobjs));
ctx->jsonobjs = NULL;
ctx->njsonobjs = 0;
#endif
ctx->containertype = CL_TYPE_ANY;
}
static inline void bytecode_context_initialize(struct cli_bc_ctx *ctx) {
memset(ctx, 0, sizeof(*ctx));
ctx->bytecode_timeout = 60000;
// 0 (aka stdin) is not a valid fd for `outfd`.
// If encountered, we should initialize it to -1 instead.
ctx->outfd = -1;
}
struct cli_bc_ctx *cli_bytecode_context_alloc(void)
{
struct cli_bc_ctx *ctx = cli_malloc(sizeof(*ctx));
if (!ctx) {
cli_errmsg("Failed to allocate bytecode context\n");
return NULL;
}
bytecode_context_initialize(ctx);
bytecode_context_reset(ctx);
return ctx;
}
void cli_bytecode_context_destroy(struct cli_bc_ctx *ctx)
{
bytecode_context_reset(ctx);
free(ctx);
}
int cli_bytecode_context_getresult_file(struct cli_bc_ctx *ctx, char **tempfilename)
{
int fd;
*tempfilename = ctx->tempfile;
fd = ctx->outfd;
ctx->tempfile = NULL;
ctx->outfd = -1;
return fd;
}
static unsigned typesize(const struct cli_bc *bc, uint16_t type)
{
struct cli_bc_type *ty;
unsigned j;
type &= 0x7fff;
if (!type)
return 0;
if (type <= 8)
return 1;
if (type <= 16)
return 2;
if (type <= 32)
return 4;
if (type <= 64)
return 8;
ty = &bc->types[type - 65];
if (ty->size)
return ty->size;
switch (ty->kind) {
case 2:
case 3:
for (j = 0; j < ty->numElements; j++)
ty->size += typesize(bc, ty->containedTypes[j]);
break;
case 4:
ty->size = ty->numElements * typesize(bc, ty->containedTypes[0]);
break;
default:
break;
}
if (!ty->size && ty->kind != DFunctionType) {
cli_warnmsg("type %d size is 0\n", type - 65);
}
return ty->size;
}
static unsigned typealign(const struct cli_bc *bc, uint16_t type)
{
type &= 0x7fff;
if (type <= 64) {
unsigned size = typesize(bc, type);
return size ? size : 1;
}
return bc->types[type - 65].align;
}
cl_error_t cli_bytecode_context_setfuncid(struct cli_bc_ctx *ctx, const struct cli_bc *bc, unsigned funcid)
{
unsigned i, s = 0;
const struct cli_bc_func *func;
if (funcid >= bc->num_func) {
cli_errmsg("bytecode: function ID doesn't exist: %u\n", funcid);
return CL_EARG;
}
func = ctx->func = &bc->funcs[funcid];
ctx->bc = bc;
ctx->numParams = func->numArgs;
ctx->funcid = funcid;
if (func->numArgs) {
ctx->operands = cli_malloc(sizeof(*ctx->operands) * func->numArgs);
if (!ctx->operands) {
cli_errmsg("bytecode: error allocating memory for parameters\n");
return CL_EMEM;
}
ctx->opsizes = cli_malloc(sizeof(*ctx->opsizes) * func->numArgs);
if (!ctx->opsizes) {
cli_errmsg("bytecode: error allocating memory for opsizes\n");
return CL_EMEM;
}
for (i = 0; i < func->numArgs; i++) {
unsigned al = typealign(bc, func->types[i]);
s = (s + al - 1) & ~(al - 1);
ctx->operands[i] = s;
s += ctx->opsizes[i] = typesize(bc, func->types[i]);
}
}
s += 8; /* return value */
ctx->bytes = s;
ctx->values = cli_malloc(s);
if (!ctx->values) {
cli_errmsg("bytecode: error allocating memory for parameters\n");
return CL_EMEM;
}
return CL_SUCCESS;
}
static inline bool type_isint(uint16_t type)
{
return type > 0 && type <= 64;
}
cl_error_t cli_bytecode_context_setparam_int(struct cli_bc_ctx *ctx, unsigned i, uint64_t c)
{
if (i >= ctx->numParams) {
cli_errmsg("bytecode: param index out of bounds: %u\n", i);
return CL_EARG;
}
if (!type_isint(ctx->func->types[i])) {
cli_errmsg("bytecode: parameter type mismatch\n");
return CL_EARG;
}
switch (ctx->opsizes[i]) {
case 1:
ctx->values[ctx->operands[i]] = c;
break;
case 2:
*(uint16_t *)&ctx->values[ctx->operands[i]] = c;
break;
case 4:
*(uint32_t *)&ctx->values[ctx->operands[i]] = c;
break;
case 8:
*(uint64_t *)&ctx->values[ctx->operands[i]] = c;
break;
}
return CL_SUCCESS;
}
cl_error_t cli_bytecode_context_setparam_ptr(struct cli_bc_ctx *ctx, unsigned i, void *data, unsigned datalen)
{
UNUSEDPARAM(ctx);
UNUSEDPARAM(i);
UNUSEDPARAM(data);
UNUSEDPARAM(datalen);
cli_errmsg("Pointer parameters are not implemented yet!\n");
return CL_EARG;
}
static inline uint64_t readNumber(const unsigned char *p, unsigned *off, unsigned len, bool *ok)
{
uint64_t n = 0;
unsigned i, newoff, lim, p0 = p[*off], shift = 0;
lim = p0 - 0x60;
if (lim > 0x10) {
cli_errmsg("Invalid number type: %c\n", p0);
*ok = false;
return 0;
}
newoff = *off + lim + 1;
if (newoff > len) {
cli_errmsg("End of line encountered while reading number\n");
*ok = false;
return 0;
}
if (p0 == 0x60) {
*off = newoff;
return 0;
}
for (i = *off + 1; i < newoff; i++) {
uint64_t v = p[i];
if (UNLIKELY((v & 0xf0) != 0x60)) {
cli_errmsg("Invalid number part: %c\n", (char)v);
*ok = false;
return 0;
}
v &= 0xf;
v <<= shift;
n |= v;
shift += 4;
}
*off = newoff;
return n;
}
static inline funcid_t readFuncID(struct cli_bc *bc, unsigned char *p,
unsigned *off, unsigned len, bool *ok)
{
funcid_t id = readNumber(p, off, len, ok) - 1;
if (*ok && id >= bc->num_func) {
cli_errmsg("Called function out of range: %u >= %u\n", id, bc->num_func);
*ok = false;
return ~0;
}
return id;
}
static inline funcid_t readAPIFuncID(struct cli_bc *bc, unsigned char *p,
unsigned *off, unsigned len, bool *ok)
{
funcid_t id = readNumber(p, off, len, ok) - 1;
if (*ok && !cli_bitset_test(bc->uses_apis, id)) {
cli_errmsg("Called undeclared API function: %u\n", id);
*ok = false;
return ~0;
}
return id;
}
static inline unsigned readFixedNumber(const unsigned char *p, unsigned *off,
unsigned len, bool *ok, unsigned width)
{
unsigned i, n = 0, shift = 0;
unsigned newoff = *off + width;
if (newoff > len) {
cli_errmsg("Newline encountered while reading number\n");
*ok = false;
return 0;
}
for (i = *off; i < newoff; i++) {
unsigned v = p[i];
if (UNLIKELY((v & 0xf0) != 0x60)) {
cli_errmsg("Invalid number part: %c\n", v);
*ok = false;
return 0;
}
v &= 0xf;
v <<= shift;
n |= v;
shift += 4;
}
*off = newoff;
return n;
}
static inline operand_t readOperand(struct cli_bc_func *func, unsigned char *p,
unsigned *off, unsigned len, bool *ok)
{
uint64_t v;
if ((p[*off] & 0xf0) == 0x40 || p[*off] == 0x50) {
uint64_t *dest;
uint16_t ty;
p[*off] |= 0x20;
/* TODO: unique constants */
func->constants = cli_realloc2(func->constants, (func->numConstants + 1) * sizeof(*func->constants));
if (!func->constants) {
*ok = false;
return MAX_OP;
}
v = readNumber(p, off, len, ok);
dest = &func->constants[func->numConstants];
/* Write the constant to the correct place according to its type.
* This is needed on big-endian machines, because constants are always
* read as u64, but accessed as one of these types: u8, u16, u32, u64 */
*dest = 0;
ty = 8 * readFixedNumber(p, off, len, ok, 1);
if (!ty) {
/* This is a global variable */
return 0x80000000 | v;
}
if (ty <= 8)
*(uint8_t *)dest = v;
else if (ty <= 16)
*(uint16_t *)dest = v;
else if (ty <= 32)
*(uint32_t *)dest = v;
else
*dest = v;
return func->numValues + func->numConstants++;
}
v = readNumber(p, off, len, ok);
if (!*ok)
return MAX_OP;
if (v >= func->numValues) {
cli_errmsg("Operand index exceeds bounds: %u >= %u!\n", (unsigned)v, (unsigned)func->numValues);
*ok = false;
return MAX_OP;
}
return v;
}
static inline char *readData(const unsigned char *p, unsigned *off, unsigned len, bool *ok, unsigned *datalen)
{
unsigned char *dat, *q;
unsigned l, newoff, i;
if (p[*off] != '|') {
cli_errmsg("Data start marker missing: %c\n", p[*off]);
*ok = false;
return NULL;
}
(*off)++;
l = readNumber(p, off, len, ok);
if (!l || !ok) {
*datalen = l;
return NULL;
}
newoff = *off + 2 * l;
if (newoff > len) {
cli_errmsg("Line ended while reading data\n");
*ok = false;
return 0;
}
dat = cli_malloc(l);
if (!dat) {
cli_errmsg("Cannot allocate memory for data\n");
*ok = false;
return NULL;
}
q = dat;
for (i = *off; i < newoff; i += 2) {
const unsigned char v0 = p[i];
const unsigned char v1 = p[i + 1];
if (UNLIKELY((v0 & 0xf0) != 0x60 || (v1 & 0xf0) != 0x60)) {
cli_errmsg("Invalid data part: %c%c\n", v0, v1);
*ok = false;
free(dat);
return 0;
}
*q++ = (v0 & 0xf) | ((v1 & 0xf) << 4);
}
*off = newoff;
*datalen = l;
return (char *)dat;
}
static inline char *readString(const unsigned char *p, unsigned *off, unsigned len, bool *ok)
{
unsigned stringlen = 0;
char *str = readData(p, off, len, ok, &stringlen);
if (*ok && stringlen && str[stringlen - 1] != '\0') {
str[stringlen - 1] = '\0';
cli_errmsg("bytecode: string missing \\0 terminator: %s\n", str);
free(str);
*ok = false;
return NULL;
}
return str;
}
static cl_error_t parseHeader(struct cli_bc *bc, unsigned char *buffer, unsigned *linelength)
{
uint64_t magic1;
unsigned magic2;
bool ok = true;
unsigned offset, len, flevel;
char *pos;
if (strncmp((const char *)buffer, BC_HEADER, sizeof(BC_HEADER) - 1)) {
cli_errmsg("Missing file magic in bytecode");
return CL_EMALFDB;
}
offset = sizeof(BC_HEADER) - 1;
len = strlen((const char *)buffer);
bc->metadata.formatlevel = readNumber(buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Unable to parse (format) functionality level in bytecode header\n");
return CL_EMALFDB;
}
/* we support 2 bytecode formats */
if (bc->metadata.formatlevel != BC_FORMAT_096 &&
bc->metadata.formatlevel != BC_FORMAT_LEVEL) {
cli_dbgmsg("Skipping bytecode with (format) functionality level: %u (current %u)\n",
bc->metadata.formatlevel, BC_FORMAT_LEVEL);
return CL_BREAK;
}
/* Optimistic parsing, check for error only at the end.*/
bc->metadata.timestamp = readNumber(buffer, &offset, len, &ok);
bc->metadata.sigmaker = readString(buffer, &offset, len, &ok);
bc->metadata.targetExclude = readNumber(buffer, &offset, len, &ok);
bc->kind = readNumber(buffer, &offset, len, &ok);
bc->metadata.minfunc = readNumber(buffer, &offset, len, &ok);
bc->metadata.maxfunc = readNumber(buffer, &offset, len, &ok);
flevel = cl_retflevel();
/* in 0.96 these 2 fields are unused / zero, in post 0.96 these mean
* min/max flevel.
* So 0 for min/max means no min/max
* Note that post 0.96 bytecode/bytecode lsig needs format 7, because
* 0.96 doesn't check lsig functionality level.
*/
if ((bc->metadata.minfunc && bc->metadata.minfunc > flevel) ||
(bc->metadata.maxfunc && bc->metadata.maxfunc < flevel)) {
cli_dbgmsg("Skipping bytecode with (engine) functionality level %u-%u (current %u)\n",
bc->metadata.minfunc, bc->metadata.maxfunc, flevel);
return CL_BREAK;
}
bc->metadata.maxresource = readNumber(buffer, &offset, len, &ok);
bc->metadata.compiler = readString(buffer, &offset, len, &ok);
bc->num_types = readNumber(buffer, &offset, len, &ok);
bc->num_func = readNumber(buffer, &offset, len, &ok);
bc->state = bc_loaded;
bc->uses_apis = NULL;
bc->dbgnodes = NULL;
bc->dbgnode_cnt = 0;
if (!ok) {
cli_errmsg("Invalid bytecode header at %u\n", offset);
return CL_EMALFDB;
}
magic1 = readNumber(buffer, &offset, len, &ok);
magic2 = readFixedNumber(buffer, &offset, len, &ok, 2);
if (!ok || magic1 != 0x53e5493e9f3d1c30ull || magic2 != 42) {
unsigned long m0 = magic1 >> 32;
unsigned long m1 = magic1;
cli_errmsg("Magic numbers don't match: %lx%lx, %u\n", m0, m1, magic2);
return CL_EMALFDB;
}
if (buffer[offset] != ':') {
cli_errmsg("Expected : but found: %c\n", buffer[offset]);
return CL_EMALFDB;
}
offset++;
*linelength = strtol((const char *)buffer + offset, &pos, 10);
if (*pos != '\0') {
cli_errmsg("Invalid number: %s\n", buffer + offset);
return CL_EMALFDB;
}
bc->funcs = cli_calloc(bc->num_func, sizeof(*bc->funcs));
if (!bc->funcs) {
cli_errmsg("Out of memory allocating %u functions\n", bc->num_func);
return CL_EMEM;
}
bc->types = cli_calloc(bc->num_types, sizeof(*bc->types));
if (!bc->types) {
cli_errmsg("Out of memory allocating %u types\n", bc->num_types);
return CL_EMEM;
}
return CL_SUCCESS;
}
static cl_error_t parseLSig(struct cli_bc *bc, char *buffer)
{
// const char *prefix;
// char *vnames;
char *vend = strchr(buffer, ';');
if (vend) {
bc->lsig = cli_strdup(buffer);
*vend++ = '\0';
// prefix = buffer;
// vnames = strchr(vend, '{');
} else {
/* Not a logical signature, but we still have a virusname */
bc->hook_name = cli_strdup(buffer);
bc->lsig = NULL;
}
return CL_SUCCESS;
}
static uint16_t readTypeID(struct cli_bc *bc, unsigned char *buffer,
unsigned *offset, unsigned len, bool *ok)
{
uint64_t t = readNumber(buffer, offset, len, ok);
if (!ok)
return ~0;
if (t >= bc->num_types + bc->start_tid) {
cli_errmsg("Invalid type id: %llu\n", (unsigned long long)t);
*ok = false;
return ~0;
}
return t;
}
static void parseType(struct cli_bc *bc, struct cli_bc_type *ty,
unsigned char *buffer, unsigned *off, unsigned len,
bool *ok)
{
unsigned j;
ty->numElements = readNumber(buffer, off, len, ok);
if (!*ok) {
cli_errmsg("Error parsing type\n");
*ok = false;
return;
}
ty->containedTypes = cli_malloc(sizeof(*ty->containedTypes) * ty->numElements);
if (!ty->containedTypes) {
cli_errmsg("Out of memory allocating %u types\n", ty->numElements);
*ok = false;
return;
}
for (j = 0; j < ty->numElements; j++) {
ty->containedTypes[j] = readTypeID(bc, buffer, off, len, ok);
}
}
static uint16_t containedTy[] = {8, 16, 32, 64};
#define NUM_STATIC_TYPES 4
static void add_static_types(struct cli_bc *bc)
{
unsigned i;
for (i = 0; i < NUM_STATIC_TYPES; i++) {
bc->types[i].kind = DPointerType;
bc->types[i].numElements = 1;
bc->types[i].containedTypes = &containedTy[i];
bc->types[i].size = bc->types[i].align = 8;
}
}
static cl_error_t parseTypes(struct cli_bc *bc, unsigned char *buffer)
{
unsigned i, offset = 1, len = strlen((const char *)buffer);
bool ok = true;
if (buffer[0] != 'T') {
cli_errmsg("Invalid function types header: %c\n", buffer[0]);
return CL_EMALFDB;
}
bc->start_tid = readFixedNumber(buffer, &offset, len, &ok, 2);
if (bc->start_tid != BC_START_TID) {
cli_warnmsg("Type start id mismatch: %u != %u\n", bc->start_tid,
BC_START_TID);
return CL_BREAK;
}
add_static_types(bc);
for (i = (BC_START_TID - 65); i < bc->num_types - 1; i++) {
struct cli_bc_type *ty = &bc->types[i];
uint8_t t = readFixedNumber(buffer, &offset, len, &ok, 1);
if (!ok) {
cli_errmsg("Error reading type kind\n");
return CL_EMALFDB;
}
switch (t) {
case 1:
ty->kind = DFunctionType;
ty->size = ty->align = sizeof(void *);
parseType(bc, ty, buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Error parsing type %u\n", i);
return CL_EMALFDB;
}
if (!ty->numElements) {
cli_errmsg("Function with no return type? %u\n", i);
return CL_EMALFDB;
}
break;
case 2:
case 3:
ty->kind = (t == 2) ? DPackedStructType : DStructType;
ty->size = ty->align = 0; /* TODO:calculate size/align of structs */
ty->align = 8;
parseType(bc, ty, buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Error parsing type %u\n", i);
return CL_EMALFDB;
}
break;
case 4:
ty->kind = DArrayType;
/* number of elements of array, not subtypes! */
ty->numElements = readNumber(buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Error parsing type %u\n", i);
return CL_EMALFDB;
}
/* fall-through */
case 5:
if (t == 5) {
ty->kind = DPointerType;
ty->numElements = 1;
}
ty->containedTypes = cli_malloc(sizeof(*ty->containedTypes));
if (!ty->containedTypes) {
cli_errmsg("Out of memory allocating containedType\n");
return CL_EMALFDB;
}
ty->containedTypes[0] = readTypeID(bc, buffer, &offset, len, &ok);
if (!ok) {
cli_errmsg("Error parsing type %u\n", i);
return CL_EMALFDB;
}
if (t == 5) {
/* for interpreter, pointers 64-bit there */
ty->size = ty->align = 8;
} else {
ty->size = ty->numElements * typesize(bc, ty->containedTypes[0]);
ty->align = typealign(bc, ty->containedTypes[0]);
}
break;
default:
cli_errmsg("Invalid type kind: %u\n", t);
return CL_EMALFDB;
}
}
for (i = (BC_START_TID - 65); i < bc->num_types - 1; i++) {
struct cli_bc_type *ty = &bc->types[i];
if (ty->kind == DArrayType) {
ty->size = ty->numElements * typesize(bc, ty->containedTypes[0]);
ty->align = typealign(bc, ty->containedTypes[0]);
}
}
return CL_SUCCESS;
}
/* checks whether the type described by tid is the same as the one described by
* apitid. */
static bool types_equal(const struct cli_bc *bc, uint16_t *apity2ty, uint16_t tid, uint16_t apitid)
{
unsigned i;
const struct cli_bc_type *ty = &bc->types[tid - 65];
const struct cli_bc_type *apity = &cli_apicall_types[apitid];
/* If we've already verified type equality, return.
* Since we need to check equality of recursive types, we assume types are
* equal while checking equality of contained types, unless proven
* otherwise. */
if (apity2ty[apitid] == tid + 1) {
return true;
}
apity2ty[apitid] = tid + 1;
if (ty->kind != apity->kind) {
cli_dbgmsg("bytecode: type kind mismatch: %u != %u\n", ty->kind, apity->kind);
return false;
}
if (ty->numElements != apity->numElements) {
cli_dbgmsg("bytecode: type numElements mismatch: %u != %u\n", ty->numElements, apity->numElements);
return false;
}
for (i = 0; i < ty->numElements; i++) {
if (apity->containedTypes[i] < BC_START_TID) {
if (ty->containedTypes[i] != apity->containedTypes[i]) {
cli_dbgmsg("bytecode: contained type mismatch: %u != %u\n",
ty->containedTypes[i], apity->containedTypes[i]);
return false;
}
} else if (!types_equal(bc, apity2ty, ty->containedTypes[i], apity->containedTypes[i] - BC_START_TID))
return false;
if (ty->kind == DArrayType)
break; /* validated the contained type already */
}
return true;
}
static cl_error_t parseApis(struct cli_bc *bc, unsigned char *buffer)
{
unsigned i, offset = 1, len = strlen((const char *)buffer), maxapi, calls;
bool ok = true;
uint16_t *apity2ty; /*map of api type to current bytecode type ID */
if (buffer[0] != 'E') {
cli_errmsg("bytecode: Invalid api header: %c\n", buffer[0]);
return CL_EMALFDB;
}
maxapi = readNumber(buffer, &offset, len, &ok);
if (!ok)
return CL_EMALFDB;
if (maxapi > cli_apicall_maxapi) {
cli_dbgmsg("bytecode using API %u, but highest API known to libclamav is %u, skipping\n", maxapi, cli_apicall_maxapi);
return CL_BREAK;
}
calls = readNumber(buffer, &offset, len, &ok);
if (!ok)
return CL_EMALFDB;
if (calls > maxapi) {
cli_errmsg("bytecode: attempting to describe more APIs than max: %u > %u\n", calls, maxapi);
return CL_EMALFDB;
}
bc->uses_apis = cli_bitset_init();
if (!bc->uses_apis) {
cli_errmsg("Out of memory allocating apis bitset\n");
return CL_EMEM;
}
apity2ty = cli_calloc(cli_apicall_maxtypes, sizeof(*cli_apicall_types));
if (!apity2ty) {
cli_errmsg("Out of memory allocating apity2ty\n");
return CL_EMEM;
}
for (i = 0; i < calls; i++) {
unsigned id = readNumber(buffer, &offset, len, &ok);
uint16_t tid = readTypeID(bc, buffer, &offset, len, &ok);
char *name = readString(buffer, &offset, len, &ok);
/* validate APIcall prototype */
if (id > maxapi) {
cli_errmsg("bytecode: API id %u out of range, max %u\n", id, maxapi);
ok = false;
}
/* API ids start from 1 */
id--;
if (ok && name && strcmp(cli_apicalls[id].name, name)) {
cli_errmsg("bytecode: API %u name mismatch: %s expected %s\n", id, name, cli_apicalls[id].name);
ok = false;
}
if (ok && !types_equal(bc, apity2ty, tid, cli_apicalls[id].type)) {
cli_errmsg("bytecode: API %u prototype doesn't match\n", id);
ok = false;
}
/* don't need the name anymore */
free(name);
if (!ok) {
free(apity2ty); /* free temporary map */
return CL_EMALFDB;
}
/* APIcall is valid */
cli_bitset_set(bc->uses_apis, id);
}
free(apity2ty); /* free temporary map */
cli_dbgmsg("bytecode: Parsed %u APIcalls, maxapi %u\n", calls, maxapi);
return CL_SUCCESS;
}
static uint16_t type_components(struct cli_bc *bc, uint16_t id, bool *ok)
{
unsigned i, sum = 0;
const struct cli_bc_type *ty;
if (id <= 64)
return 1;
ty = &bc->types[id - 65];
/* TODO: protect against recursive types */
switch (ty->kind) {
case DFunctionType:
cli_errmsg("bytecode: function type not accepted for constant: %u\n", id);
/* don't accept functions as constant initializers */
*ok = false;
return 0;
case DPointerType:
return 2;
case DStructType:
case DPackedStructType:
for (i = 0; i < ty->numElements; i++) {
sum += type_components(bc, ty->containedTypes[i], ok);
}
return sum;
case DArrayType:
return type_components(bc, ty->containedTypes[0], ok) * ty->numElements;
default:
*ok = false;
return 0;
}
}