-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.c
1373 lines (1126 loc) · 44.4 KB
/
database.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
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/stat.h> // for stat
#include "database.h"
#include "submission.h"
#include "util.h"
#include "pthread.h"
#include <sys/types.h>
#include <pwd.h> // both for getuid and getpwuid
#include <netinet/icmp6.h> // for struct icmp6_hdr
#define DB_WARN printf("Database warning: sqlite3 support is disabled. #define USE_SQLITE3 in database.h!\n");
//#define VERBOSE_PTHREADS
#ifdef USE_SQLITE3
sqlite3* sqlite_db;
// how to create the tables in the Database.
// MAKE SURE TO ORDER THEM ALPHABETICALLY
char* tables[] = {"CREATE TABLE connection (af_inet_type NUMERIC, destination TEXT, end_time NUMERIC, id INTEGER PRIMARY KEY, protocol NUMERIC, protocol_id NUMERIC, source TEXT, start_time NUMERIC)",
"CREATE TABLE icmp (code NUMERIC, id INTEGER PRIMARY KEY, type NUMERIC)",
"CREATE TABLE payload (id INTEGER PRIMARY KEY, payload BLOB, report_url TEXT, filename TEXT, state NUMERIC)",
"CREATE TABLE tcp_udp (dport NUMERIC, id INTEGER PRIMARY KEY, payload_id NUMERIC, sport NUMERIC)"};
int ntables = 4;
#endif
int database_usedb;
int database_shellcode_detection;
pthread_t assessment_thread, conversion_thread, submission_thread;
pthread_mutex_t mutex;
// initializes the datbase and will report if an error should occur.
// also initializes the queues.
void database_init(char* filename) {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return;
sqlite3_open(filename, &sqlite_db);
if(!sqlite_db) {
printf("Database error: The database %s didn't open.\n", filename);
exit(EXIT_FAILURE);
}
TAILQ_INIT(&shellcode_assessment_queue);
TAILQ_INIT(&shellcode_submission_queue);
TAILQ_INIT(&shellcode_build_queue);
database_fix_permissions();
#else
DB_WARN
#endif
}
void database_fix_permissions() {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return;
if(database_shellcode_detection == 0)
return;
struct passwd* pw = getpwuid(getuid());
struct stat st;
int error = 0;
int retval = stat(database_shellcodedir, &st);
if(retval != 0) {
perror("Database error: Couldn't access the shellcode directory");
fprintf(stderr, "You configured %s as your shellcode directory. Please make sure it is accessible (honeyd was being run as user %s, uid: %d)\n", database_shellcodedir, pw->pw_name, pw->pw_uid );
error = 1;
}
char* msfencode_logdir;
asprintf(&msfencode_logdir, "%s/metasploit_logs", database_shellcodedir);
if(asprintf == NULL) {
printf("shellcode error while asprintf-ing msfencode_logdir");
exit(EXIT_FAILURE);
}
retval = stat(msfencode_logdir, &st);
if(retval != 0) {
perror("Database error: Couldn't access msfencode's logging directory");
fprintf(stderr, "You configured %s as the directory for msfencode to write it's logfiles to. Please make sure it is accessible (honeyd was being run as user %s, uid: %d)\n", msfencode_logdir, pw->pw_name, pw->pw_uid);
error = 1;
}
// set environment variable for msfencode
setenv("MSF_CFGROOT_CONFIG", msfencode_logdir, 1);
free(msfencode_logdir);
if(error > 0)
exit(EXIT_FAILURE);
#else
DB_WARN
#endif
}
void database_start_threads() {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
int retval = pthread_create(&assessment_thread, NULL, database_stupidly_trigger_assessment, NULL);
if(retval != 0) {
perror("Error creating assessment thread");
exit(EXIT_FAILURE);
}
retval = pthread_create(&conversion_thread, NULL, database_stupidly_trigger_conversion, NULL);
if(retval != 0) {
perror("Error creating conversion thread");
exit(EXIT_FAILURE);
}
retval = pthread_create(&submission_thread, NULL, database_stupidly_trigger_submission, NULL);
if(retval != 0) {
perror("Error creating submission thread");
exit(EXIT_FAILURE);
}
pthread_mutex_unlock(&mutex);
#else
DB_WARN
#endif
}
// performs a database query and will report if an error should occur.
// requires an open database connection.
void database_query(char* sql, int (*callback)(void*, int, char**, char**)) {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return;
char *errorMsg = NULL;
int retval = sqlite3_exec(sqlite_db, sql, callback, 0, &errorMsg);
if(retval != SQLITE_OK) {
printf("Database error: %s, retval: %d\n", errorMsg, retval);
sqlite3_free(sqlite_db);
free(errorMsg);
exit(EXIT_FAILURE);
}
#else
DB_WARN
#endif
}
// closes the database.
void database_close() {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return;
pthread_cancel(assessment_thread);
pthread_cancel(conversion_thread);
pthread_cancel(submission_thread);
printf("database info: waiting for threads to terminate...\n");
/*
*pthread_join(assessment_thread, NULL);
*pthread_join(conversion_thread, NULL);
*pthread_join(submission_thread, NULL);
*/
int retval = sqlite3_close(sqlite_db);
if(retval != SQLITE_OK) {
printf("Database error: closing the database didn't work. (%d)\nTODO: Fix this!\n", retval);
sqlite3_free(sqlite_db);
}
printf("Database info: Database successfully closed.\n");
#else
DB_WARN
#endif
}
// writes transport layer information (source port and destination port) into the database.
// requires an open database connection
// returns the ID of the row that was inserted.
int log_transport_layer(struct tuple* conhdr, int payload_id) {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return -1;
printf("Im logging the transport layer!\n");
sqlite3_stmt* statement;
int retval = sqlite3_prepare_v2(sqlite_db, "INSERT INTO tcp_udp (sport, dport, payload_id) VALUES (?, ?, ?);", -1, &statement, NULL);
if(retval != SQLITE_OK) {
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
printf("Error in sqlite3_prepare_v2 at line %d: %d\n", __LINE__, retval);
}
sqlite3_bind_int(statement, 1, conhdr->sport);
sqlite3_bind_int(statement, 2, conhdr->dport);
sqlite3_bind_int(statement, 3, payload_id);
int step_type = sqlite3_step(statement);
if(step_type != SQLITE_DONE) {
printf("Didn't really step through the INSERT statement - strange!: %d\n", step_type);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
sqlite3_finalize(statement);
return sqlite3_last_insert_rowid(sqlite_db);
#else
DB_WARN
return -1;
#endif
}
// writes icmpv4 information into the database.
// this breaks the convention of logging one layer only as it will also create an IPv6 entry
void log_icmp4(struct ip_hdr * ip, struct icmp_hdr * icmp) {
if(database_usedb == 0)
return;
if(ip == NULL) {
printf("Database warning: tried to log an icmp packet but couldn't read ipv6 header\n");
return;
}
if(icmp == NULL) {
printf("Database warning: tried to log an icmp packet but couldn't read icmpv6 header\n");
return;
}
char* sql = "INSERT INTO icmp (type, code) VALUES (?, ?)";
sqlite3_stmt* statement;
int retval = sqlite3_prepare_v2(sqlite_db, sql, strlen(sql) + 1, &statement, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_prepare_v2: %d\n", retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
retval = sqlite3_bind_int(statement, 1, icmp->icmp_type);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_int: %d\n", retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
retval = sqlite3_bind_int(statement, 2, icmp->icmp_code);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_int: %d\n", retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
while(1) {
retval = sqlite3_step(statement);
if(retval == SQLITE_DONE)
break;
else
printf("Database info: still stepping while INSERTING the icmp6 type\n");
}
sqlite3_finalize(statement);
int icmp_id = sqlite3_last_insert_rowid(sqlite_db);
sqlite3_stmt* stmt_ipv4;
// we use constant values 4 for the af_inet_type and 1 for the protocol number for icmp
// trying to use the preprocessor macro DB_PROTO_ICMP doesn't work here.. so we use
// hard coded numbers to limit the number of calls to sqlite3_bind_int.
char* ipv4_sql = "INSERT INTO connection (source, destination, af_inet_type, start_time, end_time, protocol, protocol_id) \
VALUES (?, ?, 4, ?, ?, 1, ?);";
retval = sqlite3_prepare_v2(sqlite_db, ipv4_sql, strlen(ipv4_sql) + 1, &stmt_ipv4, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite_prepare_v2: %d\n", retval);
sqlite3_finalize(stmt_ipv4);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
char* src = calloc(32, sizeof(char));
if(src == NULL) {
printf("Error: Couldn't alloc enough memory for buffer src in line %d\n", __LINE__);
exit(EXIT_FAILURE);
}
inet_ntop(AF_INET, &(ip->ip_src), src, 32 * sizeof(char));
retval = sqlite3_bind_text(stmt_ipv4, 1, src, -1, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv4);
sqlite3_free(sqlite_db);
free(src);
exit(EXIT_FAILURE);
}
char* dst = calloc(32, sizeof(char));
if(dst == NULL) {
printf("Error: Couldn't alloc enough memory for buffer dst in line %d\n", __LINE__);
exit(EXIT_FAILURE);
}
inet_ntop(AF_INET, &(ip->ip_dst), dst, 32 * sizeof(char));
retval = sqlite3_bind_text(stmt_ipv4, 2, dst, -1, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv4);
sqlite3_free(sqlite_db);
free(dst);
exit(EXIT_FAILURE);
}
time_t now = time(NULL);
retval = sqlite3_bind_int(stmt_ipv4, 3, (int) now);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv4);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
retval = sqlite3_bind_int(stmt_ipv4, 4, (int) now);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv4);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
retval = sqlite3_bind_int(stmt_ipv4, 5, icmp_id);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv4);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
while(1) {
retval = sqlite3_step(stmt_ipv4);
if(retval == SQLITE_DONE)
break;
else
printf("Datbase info: still stepping while INSERTING\n");
}
free(src);
free(dst);
sqlite3_finalize(stmt_ipv4);
}
// writes icmpv6 information into the database.
// this breaks the convention of logging one layer only as it will also create an IPv6 entry
void log_icmp6(struct ip6_hdr * ip6, struct icmp6_hdr * icmp6) {
if(database_usedb == 0)
return;
if(ip6 == NULL) {
printf("Database warning: tried to log an icmp packet but couldn't read ipv6 header\n");
return;
}
if(icmp6 == NULL) {
printf("Database warning: tried to log an icmp packet but couldn't read icmpv6 header\n");
return;
}
char* sql = "INSERT INTO icmp (type, code) VALUES (?, ?)";
sqlite3_stmt* statement;
int retval = sqlite3_prepare_v2(sqlite_db, sql, strlen(sql) + 1, &statement, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_prepare_v2: %d\n", retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
int type= icmp6->icmp6_type;
retval = sqlite3_bind_int(statement, 1, type);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_int: %d\n", retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
retval = sqlite3_bind_int(statement, 2, (int) icmp6->icmp6_code);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_int: %d\n", retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
while(1) {
retval = sqlite3_step(statement);
if(retval == SQLITE_DONE)
break;
else
printf("Database info: still stepping while INSERTING the icmp6 type\n");
}
sqlite3_finalize(statement);
int icmp_id = sqlite3_last_insert_rowid(sqlite_db);
sqlite3_stmt* stmt_ipv6;
// we use constant values 6 for the af_inet_type and 58 for the protocol number for icmpv6
// trying to use the preprocessor macro DB_PROTO_ICMP6 doesn't work here.. so we use
// hard coded numbers to limit the number of calls to sqlite3_bind_int.
char* ipv6_sql = "INSERT INTO connection (source, destination, af_inet_type, start_time, end_time, protocol, protocol_id) \
VALUES (?, ?, 6, ?, ?, 58, ?);";
retval = sqlite3_prepare_v2(sqlite_db, ipv6_sql, strlen(ipv6_sql) + 1, &stmt_ipv6, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite_prepare_v2: %d\n", retval);
sqlite3_finalize(stmt_ipv6);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
char* src = calloc(128, sizeof(char));
if(src == NULL) {
printf("Couldn't alloc enough memory for src buffer in line %d\n", __LINE__);
exit(EXIT_FAILURE);
}
inet_ntop(AF_INET6, &(ip6->ip6_src), src, 128 * sizeof(char));
retval = sqlite3_bind_text(stmt_ipv6, 1, src, -1, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv6);
sqlite3_free(sqlite_db);
free(src);
exit(EXIT_FAILURE);
}
char* dst = calloc(128, sizeof(char));
if(dst == NULL) {
printf("Couldn't alloc enough memory for dst buffer in line %d\n", __LINE__);
exit(EXIT_FAILURE);
}
inet_ntop(AF_INET6, &(ip6->ip6_dst), dst, 128 * sizeof(char));
retval = sqlite3_bind_text(stmt_ipv6, 2, dst, -1, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv6);
sqlite3_free(sqlite_db);
free(dst);
exit(EXIT_FAILURE);
}
time_t now = time(NULL);
retval = sqlite3_bind_int(stmt_ipv6, 3, (int) now);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv6);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
retval = sqlite3_bind_int(stmt_ipv6, 4, (int) now);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv6);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
retval = sqlite3_bind_int(stmt_ipv6, 5, icmp_id);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(stmt_ipv6);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
while(1) {
retval = sqlite3_step(stmt_ipv6);
if(retval == SQLITE_DONE)
break;
else
printf("Datbase info: still stepping while INSERTING\n");
}
free(src);
free(dst);
sqlite3_finalize(stmt_ipv6);
}
// writes network layer information into the database.
// includes addresses, timespan, network type, type of upper layer protocol and the id of the row
// requires an open database connection.
// returns the id of the row inserted.
int log_network_layer(struct tcp_con* tcp, struct udp_con* udp, int protocol_id) {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return -1;
printf("Im logging the network layer!\n");
// check that there's only one valid parameter
if( (tcp == NULL && udp == NULL) || (tcp != NULL && udp != NULL) ) {
printf("Database warning: one of the tcp or udp paramters must be valid, one must be NULL.\n");
return -1;
}
char* src;
char* dst;
char* sql = NULL;
int ipversion = -1;
if(tcp == NULL) {
honeyd_contoa_v2(&(udp->conhdr), &src, &dst);
if(udp->addr_family == AF_INET)
ipversion = 4;
if(udp->addr_family == AF_INET6)
ipversion = 6;
asprintf(&sql, "INSERT INTO connection \
(source, destination, af_inet_type, start_time, end_time, protocol, protocol_id) \
VALUES (\"%s\", \"%s\", %d, %d, %d, %d, %d)",
src, dst, ipversion, udp->start_time, udp->end_time, DB_PROTO_UDP, protocol_id);
} else {
honeyd_contoa_v2(&(tcp->conhdr), &src, &dst);
if(tcp->addr_family == AF_INET)
ipversion = 4;
if(tcp->addr_family == AF_INET6)
ipversion = 6;
asprintf(&sql, "INSERT INTO connection \
(source, destination, af_inet_type, start_time, end_time, protocol, protocol_id) \
VALUES (\"%s\", \"%s\", %d, %d, %d, %d, %d)",
src, dst, ipversion, tcp->start_time, tcp->end_time, DB_PROTO_TCP, protocol_id);
}
database_query(sql, NULL);
free(src);
free(dst);
free(sql);
return sqlite3_last_insert_rowid(sqlite_db);
#else
DB_WARN
return -1;
#endif
}
// writes the contents of the shellcode buffer
// (more accurately <size> bytes from <buffer> to the datbase
// returns -1 on error and the id of the newly created entry on success.
int log_payload(char* buffer, int size) {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return -1;
printf("Im logging the payload!\n");
sqlite3_stmt* statement;
char* query;
asprintf(&query, "INSERT INTO payload (payload, state) VALUES (?, %d);", DB_PAYLOAD_STATE_ASSESSABLE);
printf("there's a query here: %s\n", query);
int retval = sqlite3_prepare_v2(sqlite_db, query, strlen(query) + 1, &statement, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite_prepare_v2: %d\n", retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
retval = sqlite3_bind_blob(statement, 1, buffer, size, NULL);
if(retval != SQLITE_OK) {
printf("Database error: There was an error with sqlite3_bind_blob: %d\n", retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
while (1) {
int retval = sqlite3_step(statement);
if(retval == SQLITE_DONE)
break;
else
printf("Database info: still stepping while INSERTing the payload\n");
}
sqlite3_finalize(statement);
return sqlite3_last_insert_rowid(sqlite_db);
#else
DB_WARN
#endif
}
// performs the CREATE TABLE statements neccessary to correctly setup the database.
void database_create_tables() {
#ifdef USE_SQLITE3
if (database_usedb == 0)
return;
// build a string that creates tables by using the statements defined in tables[]
char* sql;
asprintf(&sql, "BEGIN TRANSACTION; %s; %s; %s; %s; COMMIT TRANSACTION;", tables[0], tables[1], tables[2], tables[3]);
//database_query(db, sql, NULL);
int i;
for (i = 0; i < ntables; i++) {
asprintf(&sql, "%s;", tables[i]);
database_query(sql, NULL);
free(sql);
}
#else
DB_WARN
#endif
}
// thank you http://stackoverflow.com/questions/1601151/how-do-i-check-in-sqlite-whether-a-table-exists
// checks if the database is correct by:
// - comparing the number of tables in the database with number of tables we defined.
// - the string needed to create the tables with those reported by the db
// returns 0 if everything is correct, -1 else.
int database_check_tables() {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return -1;
// query the number of tables present in the db
char *query_num_tables = "SELECT COUNT(*) FROM sqlite_master WHERE type='table';";
sqlite3_stmt* statement;
int retval = sqlite3_prepare_v2(sqlite_db, query_num_tables, strlen(query_num_tables) + 1, &statement, NULL);
if(statement == NULL) {
printf("statement is null\n");
}
if(retval != SQLITE_OK) {
printf("Database error: There was an error with the sqlite3_prepare (retval=%d)\n", retval );
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
// step through the result set -- only one row should be returned so there's no loop here
if(sqlite3_step(statement) != SQLITE_ROW) {
printf("Database error: Couldn't retrieve data with sqlite3_step\n");
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
// retrieve the value
int ntables_in_db = sqlite3_column_int(statement, 0);
if(ntables_in_db != ntables) {
printf("Database warning: There's something wrong with the database (%s).\nIt should have %d tables, but there are %d.\n", database_filename, ntables, ntables_in_db);
sqlite3_finalize(statement);
return -1;
}
// query the create-table statements that were needed to create the db.
sqlite3_finalize(statement);
char* query_create_table_statements = "SELECT sql FROM sqlite_master WHERE type='table' ORDER BY name ASC;";
retval = sqlite3_prepare_v2(sqlite_db, query_create_table_statements, strlen(query_create_table_statements) + 1, &statement, NULL);
if(retval != SQLITE_OK || statement == NULL) {
printf("Database error: There was an error with the sqlite3_prepare.\n");
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
// loop through the result set.
int table_id=0;
while(1) {
int step_type = sqlite3_step(statement);
if(step_type == SQLITE_ROW) {
// check if the table definitions and the structure in the db match.
if(strncmp(sqlite3_column_text(statement,0), tables[table_id], strlen(tables[table_id])) != 0) {
printf("Database warning: There's something wrong with the database (%s):\nTable #%d does not match the correct format.\nI've expected: %s\nBut found: %s\n", database_filename, table_id, tables[table_id], sqlite3_column_text(statement, 0));
return -1;
}
table_id++;
} else if (step_type == SQLITE_DONE) {
break;
} else {
printf("Database error: Couldn't step through the results.\n");
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
}
printf("Database info: The tables in the database are correct.\n");
sqlite3_finalize(statement);
return 0;
#else
DB_WARN
#endif
}
// deletes the database file specified by filename.
// asks the user, they have to choose [y/n]
// will remove the file from the harddisk.
int database_delete_database(char* filename) {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return -1;
char choice = 'U';
while(1) {
if(isalnum(choice))
printf("Database warning: Re-create database file? Note: This will delete EVERYTHING from the database file %s [Y/N]: ", filename);
choice = fgetc(stdin);
if(choice == 'Y' || choice == 'N' || choice == 'y' || choice == 'n')
break;
}
if(choice == 'Y' || choice == 'y') {
database_close();
int retval = remove(filename);
if(retval != 0) {
perror("Database error: Couldn't delete the database file");
return -1;
}
return 0;
} else {
printf("Database info: Nothing was deleted.\n");
return -1;
}
#else
DB_WARN
#endif
}
// sets the database filename - callback function for the config-file parser.
void database_set_dbfile(char* file) {
if (file != NULL) {
database_filename = file;
database_usedb = 1;
}
}
// sets the directory for where to put the shellcodes
void database_set_shellcodedir(char* path) {
if(path == NULL) {
printf("error parsing shellcodedir path.\n");
exit(EXIT_FAILURE);
}
// remove trailing slash
if(path[strlen(path) - 1] == '/')
path[strlen(path) - 1] = '\0';
database_shellcodedir = path;
database_shellcode_detection = 1;
}
// opens the database, retrieves all ASSESSABLE payloads and
// checks them one by one.
// Will mark them as being INTERESTING or BORING.
void database_assess_payloads() {
#ifdef USE_SQLITE3
if(database_usedb == 0)
return;
// query the DB for all ASSESSABLE payloads
char *sql;
asprintf(&sql, "SELECT id, payload FROM payload WHERE state = %d;", DB_PAYLOAD_STATE_ASSESSABLE);
// BEGIN CRITICAL SECTION - copy entries from the database into memory
pthread_mutex_lock(&mutex);
#ifdef VERBOSE_PTHREADS
printf("Database info [ASSESS]: Fetching assessable payloads. Aquired database lock.\n");
int assessable_counter = 0;
#endif
sqlite3_stmt* statement;
int retval = sqlite3_prepare_v2(sqlite_db, sql, strlen(sql) + 1, &statement, NULL);
if(retval != SQLITE_OK) {
printf("Error in sqlite3_prepare_v2 at line %d: %d\n", __LINE__, retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
// loop through the results
while(1) {
int step_type = sqlite3_step(statement);
if(step_type == SQLITE_ROW) {
// move the info from the database into memory.
// allocate sapce
struct shellcode* entry;
entry = calloc(1, sizeof(struct shellcode));
if(entry == NULL) {
printf("Error mallocing memory for temp shellcode buffer thing.\n");
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
// get data from database
int length = sqlite3_column_bytes(statement, 1);
int id = sqlite3_column_int(statement, 0);
char* result = sqlite3_column_blob(statement, 1);
entry->buf = calloc(length, sizeof(char));
if( (entry->buf) == NULL) {
printf("Couldn't malloc memory for the shellcode buffer\n");
exit(EXIT_FAILURE);
}
if( (memcpy(entry->buf, result, length)) == NULL) {
printf("Error memcpy-ing\n");
exit(EXIT_FAILURE);
}
entry->database_id = id;
entry->size = length;
entry->state = DB_PAYLOAD_STATE_ASSESSABLE;
// insert them into the temp queue
TAILQ_INSERT_TAIL(&shellcode_assessment_queue, entry, entries);
#ifdef VERBOSE_PTHREADS
assessable_counter++;
#endif
} else if(step_type == SQLITE_DONE) {
break;
} else {
// some error
printf("Some error stepping through the result set: %d\n", step_type);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
}
#ifdef VERBOSE_PTHREADS
printf("Database info [ASSESS]: Found %d assessable payloads. Releasing database lock\n", assessable_counter);
int current_counter = 0;
#endif
sqlite3_finalize(statement);
pthread_mutex_unlock(&mutex);
// END CRITICIAL SECTION - now that everything lives in memory, do some work on it
// loop over all items in the queue
struct shellcode* tmp;
TAILQ_FOREACH(tmp, &shellcode_assessment_queue, entries) {
// wrapper for libemu's getpc_check, set the state accordingly
if(shellcode_test(tmp->buf, tmp->size) >= 0) {
tmp->state = DB_PAYLOAD_STATE_INTERESTING;
} else {
tmp->state = DB_PAYLOAD_STATE_BORING;
}
#ifdef VERBOSE_PTHREADS
current_counter++;
printf("Database info [ASSESS]: Progress assessing payloads: %d of %d\n", current_counter, assessable_counter);
#endif
}
// BEGIN CRITICAL SECTION - the work is done, we write information back to the database
pthread_mutex_lock(&mutex);
#ifdef VERBOSE_PTHREADS
printf("Database info [ASSESS]: Done assessing %d payloads, now updating the database. Aquired database lock\n", assessable_counter);
current_counter = 0;
#endif
// prepare the update statement - this will update the state of all the items in the queue
char* update_sql = "UPDATE payload SET state=? WHERE id=?;";
sqlite3_stmt* update_statement;
retval = sqlite3_prepare_v2(sqlite_db, update_sql, strlen(update_sql) +1, &update_statement, NULL);
if(retval != SQLITE_OK) {
printf("Error preparing at line %d: %d\n", __LINE__, retval);
sqlite3_finalize(update_statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
TAILQ_FOREACH(tmp, &shellcode_assessment_queue, entries) {
// fill the missing numbers in the sql query
sqlite3_bind_int(update_statement, 1, tmp->state);
sqlite3_bind_int(update_statement, 2, tmp->database_id);
int step_type;
step_type = sqlite3_step(update_statement);
if( step_type != SQLITE_DONE) {
printf("Error: stepping through the UPDATE statement wasn't SQLITE_DONE but was %d\n", step_type);
}
sqlite3_reset(update_statement);
#ifdef VERBOSE_PTHREADS
current_counter++;
printf("Database info [ASSESS]: Progress updateing assessed payloads: %d of %d\n", current_counter, assessable_counter);
#endif
}
#ifdef VERBOSE_PTHREADS
printf("Database info [ASSESS]: Done updating %d assessed payloads. Releasing database lock\n", assessable_counter);
#endif
sqlite3_finalize(update_statement);
pthread_mutex_unlock(&mutex);
// CRITICAL SECTION DONE -- everything is back in the database, remove the in-memory entries
// remove all the entries from the queue
struct shellcode* entry;
while (entry = TAILQ_FIRST(&shellcode_assessment_queue)) {
TAILQ_REMOVE(&shellcode_assessment_queue, entry, entries);
free(entry->buf);
free(entry);
}
#else
DB_WARN
#endif
}
// Fetch payloads marked as INTERESTING from the database and
// convert them with shellcode_convert, one by one.
void database_build_executables() {
#ifdef USE_SQLITE3
if(database_usedb == 0 || database_shellcode_detection == 0)
return;
// BEGIN CRITICAL SECTION -- get interesting entries from the database to memory
pthread_mutex_lock(&mutex);
#ifdef VERBOSE_PTHREADS
printf("Database info [BUILD]: Fetching payloads to build executables for. Aquired database lock\n");
int build_exec_counter = 0;
#endif
// query the DB for all INTERESTING payloads
char *sql;
asprintf(&sql, "SELECT id, payload FROM payload WHERE state = %d;", DB_PAYLOAD_STATE_INTERESTING);
sqlite3_stmt* statement;
int retval = sqlite3_prepare_v2(sqlite_db, sql, strlen(sql) + 1, &statement, NULL);
if(retval != SQLITE_OK) {
printf("Error in sqlite3_prepare_v2 at line %d: %d\n", __LINE__, retval);
sqlite3_finalize(statement);
sqlite3_free(sqlite_db);
exit(EXIT_FAILURE);
}
// loop through the results
while(1) {
int step_type = sqlite3_step(statement);
if(step_type == SQLITE_ROW) {