-
Notifications
You must be signed in to change notification settings - Fork 0
/
osxiec.c
3420 lines (2905 loc) · 119 KB
/
osxiec.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 <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <sandbox.h>
#include <mach/mach.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <spawn.h>
#include <curl/curl.h>
#include <readline/readline.h>
#include "plugin_manager/plugin_manager.h"
#include <pwd.h>
#include <regex.h>
#include <stdbool.h>
#include "osxiec_script/osxiec_script.h"
#include <libgen.h>
#include "/opt/homebrew/Cellar/json-c/0.17/include/json-c/json.h"
#include <termios.h>
#include <mach-o/dyld.h>
#define OSXIEC_ARCHITECTURE "arm64"
#define MAX_COMMAND_LEN 1024
#define MAX_PATH_LEN 256
#define MAX_FILE_SIZE 1024*1024*1024 // 1 GB
#define MAX_FILES 2147483648
#define PORT 3000
#define MAX_CLIENTS 15
#define DEBUG_NONE 0
#define DEBUG_STEP 1
#define DEBUG_BREAK 2
#define CHUNK_SIZE 8192 // 8 KB chunks
#define SHARED_FOLDER_PATH "/Volumes/SharedContainer"
#define CPU_USAGE_THRESHOLD 80.0 // 80% CPU usage
#define MEMORY_USAGE_THRESHOLD 80.0 // 80% of soft limit
#define MAX_CPU_PRIORITY 39 // Maximum nice value
#define MIN_CPU_PRIORITY -20 // Minimum nice value
#define MAX_MEMORY_LIMIT 2147483648 // 2 GB max memory limit
#define MAX_HISTORY_LEN 100
#define MAX_LINE_LEN 1024
#define VERSION "v0.72"
int port = PORT;
typedef struct {
char name[MAX_PATH_LEN];
size_t size;
char *data;
} File;
typedef struct {
char source[MAX_PATH_LEN];
char target[MAX_PATH_LEN];
} Mount;
typedef struct {
char name[MAX_PATH_LEN];
long memory_soft_limit;
long memory_hard_limit;
int cpu_priority;
char network_mode[20];
uid_t container_uid;
gid_t container_gid;
char network_name[MAX_PATH_LEN];
int vlan_id;
char start_config[MAX_PATH_LEN];
} ContainerConfig;
typedef struct {
char name[MAX_PATH_LEN];
int vlan_id;
int num_containers;
char container_names[MAX_CLIENTS][MAX_PATH_LEN];
char container_ips[MAX_CLIENTS][16];
} ContainerNetwork;
int debug_mode = DEBUG_NONE;
char *breakpoint = NULL;
typedef struct {
char current_directory[MAX_PATH_LEN];
char last_executed_command[MAX_COMMAND_LEN];
int num_processes;
long memory_usage;
char network_status[50];
char **environment_variables;
int num_env_vars;
} ContainerState;
ContainerState container_state = {0};
typedef struct {
char commands[MAX_HISTORY_LEN][MAX_COMMAND_LEN];
int count;
int current;
} CommandHistory;
CommandHistory history = { .count = 0, .current = 0 };
int read_files(const char *dir_path, File *files, uid_t uid, gid_t gid) {
DIR *dir;
struct dirent *entry;
char file_path[MAX_PATH_LEN];
int num_files = 0;
struct stat st;
dir = opendir(dir_path);
if (dir == NULL) {
perror("Error opening directory");
return -1;
}
while ((entry = readdir(dir)) != NULL) {
snprintf(file_path, sizeof(file_path), "%s/%s", dir_path, entry->d_name);
if (stat(file_path, &st) == 0) {
if (S_ISDIR(st.st_mode)) {
// Skip "." and ".."
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// Recursively read subdirectories
int sub_num_files = read_files(file_path, &files[num_files], uid, gid);
if (sub_num_files < 0) {
closedir(dir);
return -1;
}
num_files += sub_num_files;
} else if (S_ISREG(st.st_mode)) {
if (st.st_size > MAX_FILE_SIZE) {
fprintf(stderr, "File %s is too large (max %d bytes)\n", entry->d_name, MAX_FILE_SIZE);
continue;
}
strncpy(files[num_files].name, file_path, MAX_PATH_LEN - 1);
files[num_files].name[MAX_PATH_LEN - 1] = '\0';
files[num_files].size = st.st_size;
files[num_files].data = malloc(st.st_size);
if (files[num_files].data == NULL) {
perror("Error allocating memory for file data");
closedir(dir);
return -1;
}
FILE *file = fopen(file_path, "rb");
if (file == NULL) {
perror("Error opening file");
free(files[num_files].data);
closedir(dir);
return -1;
}
if (fread(files[num_files].data, 1, st.st_size, file) != st.st_size) {
perror("Error reading file");
fclose(file);
free(files[num_files].data);
closedir(dir);
return -1;
}
fclose(file);
// Set appropriate permissions
if (chmod(file_path, 0755) != 0) {
perror("Error setting file permissions");
free(files[num_files].data);
closedir(dir);
return -1;
}
// Change ownership of the file
if (chown(file_path, uid, gid) != 0) {
perror("Error changing file ownership");
free(files[num_files].data);
closedir(dir);
return -1;
}
num_files++;
}
}
}
closedir(dir);
return num_files;
}
extern char **environ;
void update_container_state() {
// Update current directory
getcwd(container_state.current_directory, MAX_PATH_LEN);
// Update number of processes
container_state.num_processes = 1;
// Update memory usage
FILE* file = fopen("/proc/self/status", "r");
if (file) {
char line[128];
while (fgets(line, sizeof(line), file)) {
if (strncmp(line, "VmRSS:", 6) == 0) {
sscanf(line + 6, "%ld", &container_state.memory_usage);
break;
}
}
fclose(file);
}
strcpy(container_state.network_status, "Connected");
// Update environment variables
for (int i = 0; environ[i] != NULL; i++) {
if (i >= container_state.num_env_vars) {
container_state.environment_variables = realloc(container_state.environment_variables, (i + 1) * sizeof(char*));
container_state.environment_variables[i] = strdup(environ[i]);
container_state.num_env_vars++;
} else if (strcmp(container_state.environment_variables[i], environ[i]) != 0) {
free(container_state.environment_variables[i]);
container_state.environment_variables[i] = strdup(environ[i]);
}
}
}
void print_container_state() {
update_container_state();
printf("Container State:\n");
printf(" Current Directory: %s\n", container_state.current_directory);
printf(" Last Executed Command: %s\n", container_state.last_executed_command);
printf(" Number of Processes: %d\n", container_state.num_processes);
printf(" Network Status: %s\n", container_state.network_status);
printf(" Environment Variables:\n");
for (int i = 0; i < container_state.num_env_vars; i++) {
printf(" %s\n", container_state.environment_variables[i]);
}
}
void handle_debug_command(char *command) {
if (strcmp(command, "continue") == 0 || strcmp(command, "c") == 0) {
debug_mode = DEBUG_NONE;
} else if (strcmp(command, "step") == 0 || strcmp(command, "s") == 0) {
debug_mode = DEBUG_STEP;
} else if (strncmp(command, "break ", 6) == 0) {
if (breakpoint) free(breakpoint);
breakpoint = strdup(command + 6);
debug_mode = DEBUG_BREAK;
} else if (strcmp(command, "print") == 0 || strcmp(command, "p") == 0) {
print_container_state();
} else if (strncmp(command, "print ", 6) == 0 || strncmp(command, "p ", 2) == 0) {
char *var_name = command + (command[1] == ' ' ? 2 : 6);
char *var_value = getenv(var_name);
if (var_value) {
printf("%s = %s\n", var_name, var_value);
} else {
printf("Variable %s not found\n", var_name);
}
} else if (strcmp(command, "help") == 0 || strcmp(command, "h") == 0) {
printf("Debug commands:\n");
printf(" continue (c) - Continue execution\n");
printf(" step (s) - Step to next command\n");
printf(" break <command> - Set breakpoint at command\n");
printf(" print (p) - Print container state\n");
printf(" print <var> (p <var>) - Print value of environment variable\n");
printf(" help (h) - Show this help message\n");
} else {
printf("Unknown debug command. Type 'help' for a list of commands.\n");
}
}
int is_subpath(const char *path, const char *base) {
char resolved_path[PATH_MAX];
char resolved_base[PATH_MAX];
if (realpath(path, resolved_path) == NULL || realpath(base, resolved_base) == NULL) {
return 0;
}
return strncmp(resolved_path, resolved_base, strlen(resolved_base)) == 0;
}
void execute_command(const char *command, const char *container_root) {
if (command == NULL || strlen(command) == 0) {
fprintf(stderr, "Error: Empty command\n");
return;
}
if (debug_mode == DEBUG_STEP || (debug_mode == DEBUG_BREAK && breakpoint && strstr(command, breakpoint))) {
printf("Debugger: Paused at command: %s\n", command);
char *debug_cmd;
while ((debug_cmd = readline("debug> ")) != NULL) {
handle_debug_command(debug_cmd);
free(debug_cmd);
if (debug_mode == DEBUG_NONE) break;
}
}
printf("Executing: %s\n", command);
strncpy(container_state.last_executed_command, command, MAX_COMMAND_LEN - 1);
container_state.last_executed_command[MAX_COMMAND_LEN - 1] = '\0';
// Update current directory if it's a cd command
if (strncmp(command, "cd ", 3) == 0) {
const char *new_dir = command + 3;
const char shared_folder_path[] = "/Volumes/SharedContainer";
char current_path[PATH_MAX];
if (getcwd(current_path, sizeof(current_path)) == NULL) {
perror("Failed to get current directory");
return;
}
if (is_subpath(new_dir, container_root) ||
is_subpath(new_dir, shared_folder_path) ||
(is_subpath(current_path, shared_folder_path) && strcmp(new_dir, container_root) == 0)) {
if (chdir(new_dir) == 0) {
getcwd(container_state.current_directory, MAX_PATH_LEN);
printf("Changed directory to: %s\n", container_state.current_directory);
} else {
perror("Failed to change directory");
}
} else {
fprintf(stderr, "Error: Cannot change directory outside of the container or shared folder.\n");
}
return;
}
char *args[MAX_COMMAND_LEN / 2 + 1];
char *command_copy = strdup(command);
if (command_copy == NULL) {
perror("Failed to allocate memory for command");
return;
}
char *token = strtok(command_copy, " ");
int i = 0;
while (token != NULL && i < MAX_COMMAND_LEN / 2) {
args[i++] = token;
token = strtok(NULL, " ");
}
args[i] = NULL;
pid_t pid;
int status;
posix_spawn_file_actions_t actions;
posix_spawnattr_t attr;
if (posix_spawn_file_actions_init(&actions) != 0) {
perror("posix_spawn_file_actions_init failed");
free(command_copy);
return;
}
if (posix_spawnattr_init(&attr) != 0) {
perror("posix_spawnattr_init failed");
posix_spawn_file_actions_destroy(&actions);
free(command_copy);
return;
}
int ret = posix_spawnp(&pid, args[0], &actions, &attr, args, environ);
if (ret == 0) {
if (waitpid(pid, &status, 0) != -1) {
if (WIFEXITED(status)) {
printf("Child process exited with status %d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("Child process terminated by signal %d\n", WTERMSIG(status));
}
} else {
perror("Error waiting for child process");
}
} else {
fprintf(stderr, "posix_spawnp failed: %s\n", strerror(ret));
}
posix_spawn_file_actions_destroy(&actions);
posix_spawnattr_destroy(&attr);
free(command_copy);
}
void execute_start_config(const char *config_file, const char *container_root) {
FILE *file = fopen(config_file, "r");
if (file == NULL) {
perror("Error opening start configuration file");
return;
}
char line[MAX_COMMAND_LEN];
while (fgets(line, sizeof(line), file)) {
// Remove newline character if present
line[strcspn(line, "\n")] = 0;
// Skip empty lines and comments
if (line[0] == '\0' || line[0] == '#') {
continue;
}
printf("Executing start command: %s\n", line);
execute_command(line, container_root);
}
fclose(file);
}
int is_base64(const char *str) {
regex_t regex;
int reti = regcomp(®ex, "^[A-Za-z0-9+/]+={0,2}$", REG_EXTENDED);
if (reti) {
return 0;
}
reti = regexec(®ex, str, 0, NULL, 0);
regfree(®ex);
return (reti == 0);
}
void security_scan(const char *bin_file) {
// Note this is a work in progress, so it make not always provide correct results
FILE *file = fopen(bin_file, "rb");
if (file == NULL) {
perror("Error opening binary file for security scan");
return;
}
ContainerConfig config;
if (fread(&config, sizeof(ContainerConfig), 1, file) != 1) {
perror("Error reading container config during security scan");
fclose(file);
return;
}
printf("Performing security scan on %s\n", bin_file);
// Check container configuration
if (config.container_uid == 0 || config.container_gid == 0) {
printf("HIGH RISK: Container is running as root. This is a significant security risk.\n");
}
if (strcmp(config.network_mode, "host") == 0) {
printf("HIGH RISK: Container is using host network mode. This can be a significant security risk.\n");
printf("The host network error will not be revelenant if you use the vlan network.\n");
}
// Check resource limits
if (config.memory_hard_limit == 0) {
printf("MEDIUM RISK: No hard memory limit set. This could lead to resource exhaustion.\n");
}
if (config.cpu_priority == 0) {
printf("LOW RISK: No CPU priority set. This could lead to resource contention.\n");
}
int num_files;
fread(&num_files, sizeof(int), 1, file);
regex_t regex;
regcomp(®ex, "^[a-zA-Z0-9._-]+$", REG_EXTENDED);
for (int i = 0; i < num_files; i++) {
char file_name[MAX_PATH_LEN];
size_t file_size;
fread(file_name, sizeof(char), MAX_PATH_LEN, file);
fread(&file_size, sizeof(size_t), 1, file);
// Check for potentially dangerous file names
if (strstr(file_name, "..") != NULL) {
printf("HIGH RISK: File '%s' contains potentially dangerous '..' in its path.\n", file_name);
}
if (regexec(®ex, file_name, 0, NULL, 0) != 0) {
printf("MEDIUM RISK: File '%s' has a potentially unsafe name.\n", file_name);
}
// Check for overly permissive file permissions
if (strstr(file_name, ".sh") != NULL || strstr(file_name, ".py") || strstr(file_name, ".lua") != NULL) {
printf("LOW RISK: Script file detected: '%s'. Ensure it has appropriate permissions.\n", file_name);
}
// Check for sensitive files
if (strstr(file_name, "id_rsa") != NULL || strstr(file_name, ".pem") != NULL) {
printf("HIGH RISK: Potential private key file detected: '%s'. Ensure it's properly secured.\n", file_name);
}
if (strstr(file_name, "password") != NULL || strstr(file_name, "secret") != NULL) {
printf("HIGH RISK: Potential sensitive file detected: '%s'. Ensure it's properly secured.\n", file_name);
}
// Scan file contents
char *buffer = malloc(file_size + 1);
if (buffer == NULL) {
perror("Failed to allocate memory for file content");
continue;
}
fread(buffer, 1, file_size, file);
buffer[file_size] = '\0';
// Check for insecure environment variables
if (strstr(buffer, "ENV_VAR_WITH_SENSITIVE_INFO") != NULL) {
printf("MEDIUM RISK: Insecure environment variable detected in file '%s'.\n", file_name);
}
// Check for insecure capabilities
if (strstr(buffer, "CAP_SYS_ADMIN") != NULL) {
printf("HIGH RISK: Insecure capability detected in file '%s'.\n", file_name);
}
// Check for insecure file permissions
if (strstr(buffer, "chmod 777") != NULL) {
printf("HIGH RISK: Insecure file permissions detected in file '%s'.\n", file_name);
}
// Check for hardcoded credentials
regex_t pwd_regex;
if (regcomp(&pwd_regex, "(password|api_key|secret)\\s*=\\s*['\"][^'\"]+['\"]", REG_EXTENDED | REG_ICASE) == 0) {
if (regexec(&pwd_regex, buffer, 0, NULL, 0) == 0) {
printf("HIGH RISK: Potential hardcoded credentials detected in file '%s'.\n", file_name);
}
regfree(&pwd_regex);
}
// Check for potential SQL injection vulnerabilities
if (strstr(buffer, "SELECT") != NULL && strstr(buffer, "WHERE") != NULL && strstr(buffer, "+") != NULL) {
printf("HIGH RISK: Potential SQL injection vulnerability detected in file '%s'.\n", file_name);
}
// Check for base64 encoded strings (potential hidden data)
char *token = strtok(buffer, " \t\n");
while (token != NULL) {
if (strlen(token) > 20 && is_base64(token)) {
printf("LOW RISK: Potential base64 encoded data detected in file '%s'. Verify if it contains sensitive information.\n", file_name);
break;
}
token = strtok(NULL, " \t\n");
}
free(buffer);
}
regfree(®ex);
printf("Security scan completed.\n");
fclose(file);
}
void read_config_file(const char *filename, ContainerConfig *config) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening config file");
exit(EXIT_FAILURE);
}
char line[MAX_LINE_LEN];
while (fgets(line, sizeof(line), file)) {
char key[64], value[MAX_LINE_LEN];
if (sscanf(line, "%63[^=]=%[^\n]", key, value) == 2) {
if (strcmp(key, "name") == 0) {
strncpy(config->name, value, sizeof(config->name) - 1);
} else if (strcmp(key, "memory_soft_limit") == 0) {
config->memory_soft_limit = strtoul(value, NULL, 10);
} else if (strcmp(key, "memory_hard_limit") == 0) {
config->memory_hard_limit = strtoul(value, NULL, 10);
} else if (strcmp(key, "cpu_priority") == 0) {
config->cpu_priority = atoi(value);
} else if (strcmp(key, "network_mode") == 0) {
strncpy(config->network_mode, value, sizeof(config->network_mode) - 1);
} else if (strcmp(key, "container_uid") == 0) {
config->container_uid = atoi(value);
} else if (strcmp(key, "container_gid") == 0) {
config->container_gid = atoi(value);
}
}
}
fclose(file);
}
void containerize_directory(const char *dir_path, const char *output_file, const char *start_config_file, const char *container_config_file) {
FILE *bin_file = fopen(output_file, "wb");
if (bin_file == NULL) {
perror("Error opening output file");
exit(EXIT_FAILURE);
}
File *files = malloc(sizeof(File) * MAX_FILES);
if (files == NULL) {
perror("Error allocating memory for files");
fclose(bin_file);
exit(EXIT_FAILURE);
}
int num_files;
// Initialize default config
ContainerConfig config = {
.name = "default_container",
.memory_soft_limit = 384 * 1024 * 1024,
.memory_hard_limit = 512 * 1024 * 1024,
.cpu_priority = 20,
.network_mode = "bridge",
.container_uid = 1000,
.container_gid = 1000,
.start_config = ""
};
if (container_config_file) {
read_config_file(container_config_file, &config);
}
if (start_config_file) {
strncpy(config.start_config, start_config_file, MAX_PATH_LEN - 1);
config.start_config[MAX_PATH_LEN - 1] = '\0';
} else {
config.start_config[0] = '\0';
}
num_files = read_files(dir_path, files, config.container_uid, config.container_gid);
if (num_files < 0) {
free(files);
fclose(bin_file);
exit(EXIT_FAILURE);
}
fwrite(&config, sizeof(ContainerConfig), 1, bin_file);
fwrite(&num_files, sizeof(int), 1, bin_file);
// Display the progress bar
int progress_bar_width = 50;
printf("Containerizing [");
fflush(stdout);
for (int i = 0; i < num_files; i++) {
fwrite(files[i].name, sizeof(char), MAX_PATH_LEN, bin_file);
fwrite(&files[i].size, sizeof(size_t), 1, bin_file);
fwrite(files[i].data, 1, files[i].size, bin_file);
free(files[i].data);
// Update the progress bar
int progress = (i + 1) * progress_bar_width / num_files;
for (int j = 0; j < progress; j++) {
printf("#");
fflush(stdout);
}
for (int j = progress; j < progress_bar_width; j++) {
printf(" ");
fflush(stdout);
}
printf("] %d%%\r", (i + 1) * 100 / num_files);
fflush(stdout);
}
printf("\n");
free(files);
fclose(bin_file);
security_scan(output_file);
}
void containerize_directory_with_bin_file(const char *dir_path, const char *input_bin_file, const char *output_file, const char *start_config_file, const char *container_config_file) {
FILE *bin_file = fopen(output_file, "wb");
if (bin_file == NULL) {
perror("Error opening output file");
exit(EXIT_FAILURE);
}
File *files = malloc(sizeof(File) * MAX_FILES);
if (files == NULL) {
perror("Error allocating memory for files");
fclose(bin_file);
exit(EXIT_FAILURE);
}
int num_files = 0;
// Initialize default config
ContainerConfig config = {
.name = "default_container",
.memory_soft_limit = 384 * 1024 * 1024,
.memory_hard_limit = 512 * 1024 * 1024,
.cpu_priority = 20,
.network_mode = "bridge",
.container_uid = 1000,
.container_gid = 1000,
.start_config = ""
};
// Load config from file if provided
if (container_config_file) {
read_config_file(container_config_file, &config);
}
if (start_config_file) {
strncpy(config.start_config, start_config_file, MAX_PATH_LEN - 1);
config.start_config[MAX_PATH_LEN - 1] = '\0';
}
// Read files from directory
int dir_files = read_files(dir_path, files, config.container_uid, config.container_gid);
if (dir_files < 0) {
free(files);
fclose(bin_file);
exit(EXIT_FAILURE);
}
num_files += dir_files;
// Read files from input bin file
if (input_bin_file) {
FILE *input_bin = fopen(input_bin_file, "rb");
if (input_bin == NULL) {
perror("Error opening input bin file");
free(files);
fclose(bin_file);
exit(EXIT_FAILURE);
}
ContainerConfig input_config;
fread(&input_config, sizeof(ContainerConfig), 1, input_bin);
int input_num_files;
fread(&input_num_files, sizeof(int), 1, input_bin);
for (int i = 0; i < input_num_files; i++) {
File *file = &files[num_files + i];
fread(file->name, sizeof(char), MAX_PATH_LEN, input_bin);
fread(&file->size, sizeof(size_t), 1, input_bin);
file->data = malloc(file->size);
if (file->data == NULL) {
perror("Error allocating memory for file data");
fclose(input_bin);
free(files);
fclose(bin_file);
exit(EXIT_FAILURE);
}
fread(file->data, 1, file->size, input_bin);
}
num_files += input_num_files;
fclose(input_bin);
}
fwrite(&config, sizeof(ContainerConfig), 1, bin_file);
fwrite(&num_files, sizeof(int), 1, bin_file);
// Display the progress bar
int progress_bar_width = 50;
printf("Containerizing [");
fflush(stdout);
for (int i = 0; i < num_files; i++) {
fwrite(files[i].name, sizeof(char), MAX_PATH_LEN, bin_file);
fwrite(&files[i].size, sizeof(size_t), 1, bin_file);
fwrite(files[i].data, 1, files[i].size, bin_file);
free(files[i].data);
// Update the progress bar
int progress = (i + 1) * progress_bar_width / num_files;
for (int j = 0; j < progress; j++) {
printf("#");
fflush(stdout);
}
for (int j = progress; j < progress_bar_width; j++) {
printf(" ");
fflush(stdout);
}
printf("] %d%%\r", (i + 1) * 100 / num_files);
fflush(stdout);
}
printf("\n");
free(files);
fclose(bin_file);
security_scan(output_file);
}
void *monitor_memory_usage(void *arg) {
ContainerConfig *config = (ContainerConfig *)arg;
mach_port_t task = mach_task_self();
while (1) {
task_vm_info_data_t vm_info;
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
if (task_info(task, TASK_VM_INFO, (task_info_t)&vm_info, &count) == KERN_SUCCESS) {
vm_size_t used_memory = vm_info.internal + vm_info.compressed;
if (used_memory > config->memory_hard_limit) {
fprintf(stderr, "Memory usage exceeded hard limit. Terminating process.\n");
exit(1);
} else if (used_memory > config->memory_soft_limit) {
fprintf(stderr, "Warning: Memory usage exceeded soft limit. Clearing cache memory.\n");
system("purge");
}
}
sleep(1);
}
}
void apply_resource_limits(const ContainerConfig *config) {
// Note it applies basic limits, as it doesn't fully use the kernel
// The reason why is that it would cause many permission issues, pottentially allow the containers to acces parts of the kernel they shouldn't be able to access
setpriority(PRIO_PROCESS, 0, config->cpu_priority);
// Start memory monitoring thread
pthread_t memory_thread;
if (pthread_create(&memory_thread, NULL, monitor_memory_usage, (void *)config) != 0) {
perror("Failed to create memory monitoring thread");
} else {
printf("Memory monitoring started with soft limit %ld bytes and hard limit %ld bytes\n",
config->memory_soft_limit, config->memory_hard_limit);
}
}
ContainerNetwork load_container_network(const char *name) {
ContainerNetwork network = {0};
char filename[MAX_PATH_LEN];
snprintf(filename, sizeof(filename), "/tmp/network_%s.conf", name);
FILE *file = fopen(filename, "r");
if (file == NULL) {
fprintf(stderr, "Failed to load network configuration for %s\n", name);
return network;
}
char line[256];
while (fgets(line, sizeof(line), file)) {
if (sscanf(line, "name=%s", network.name) == 1) {
continue;
}
if (sscanf(line, "vlan_id=%d", &network.vlan_id) == 1) {
continue;
}
if (sscanf(line, "container_name=%s", network.container_names[network.num_containers]) == 1) {
network.num_containers++;
continue;
}
if (sscanf(line, "container_ip=%s", network.container_ips[network.num_containers - 1]) == 1) {
continue;
}
}
fclose(file);
return network;
}
void create_and_save_container_network(const char *name, int vlan_id) {
ContainerNetwork network;
strncpy(network.name, name, MAX_PATH_LEN - 1);
network.vlan_id = vlan_id;
network.num_containers = 0;
// Save the network configuration to a file
char filename[MAX_PATH_LEN];
snprintf(filename, sizeof(filename), "/tmp/network_%s.conf", name);
FILE *file = fopen(filename, "w");
if (file == NULL) {
perror("Failed to save network configuration");
return;
}
fprintf(file, "name=%s\n", network.name);
fprintf(file, "vlan_id=%d\n", network.vlan_id);
fclose(file);
printf("Created and saved network %s with VLAN ID %d\n", network.name, network.vlan_id);
}
void remove_container_network(const char *name) {
char filename[MAX_PATH_LEN];
snprintf(filename, sizeof(filename), "/tmp/network_%s.conf", name);
if (remove(filename) == 0) {
printf("Removed network %s\n", name);
} else {
perror("Failed to remove network");
}
}
void add_container_to_network(ContainerNetwork *network, const char *container_name) {
if (network->num_containers < MAX_CLIENTS) {
strncpy(network->container_names[network->num_containers], container_name, MAX_PATH_LEN - 1);
// Dynamically assign IP address based on the number of containers
char container_ip[16];
snprintf(container_ip, sizeof(container_ip), "192.168.%d.%d", network->vlan_id, network->num_containers + 2);
strncpy(network->container_ips[network->num_containers], container_ip, 15);
network->num_containers++;
// Save the updated network configuration to a file
char filename[MAX_PATH_LEN];
snprintf(filename, sizeof(filename), "/tmp/network_%s.conf", network->name);
FILE *file = fopen(filename, "a");
if (file == NULL) {
perror("Failed to save network configuration");
return;
}
fprintf(file, "container_name=%s\n", container_name);
fprintf(file, "container_ip=%s\n", container_ip);
fclose(file);
}
}
char *get_ip_address() {
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1) {
perror("socket");
return NULL;
}
struct sockaddr_in loopback;
memset(&loopback, 0, sizeof(loopback));
loopback.sin_family = AF_INET;
// Ping Google's DNS server
loopback.sin_addr.s_addr = inet_addr("8.8.8.8");
loopback.sin_port = htons(53);
if (connect(sock, (struct sockaddr *)&loopback, sizeof(loopback)) == -1) {
perror("connect");
close(sock);
return NULL;
}
struct sockaddr_in addr;
socklen_t addr_len = sizeof(addr);
if (getsockname(sock, (struct sockaddr *)&addr, &addr_len) == -1) {
perror("getsockname");
close(sock);
return NULL;
}
close(sock);
char *ip = strdup(inet_ntoa(addr.sin_addr));
return ip;
}
void setup_pf_rules(ContainerNetwork *network) {
char *ip_address = get_ip_address();
if (ip_address == NULL) {
fprintf(stderr, "Failed to get IP address\n");
return;
}
// Assign IP address to the VLAN interface
char ip_cmd[256];
snprintf(ip_cmd, sizeof(ip_cmd), "ifconfig vlan%d create vlan %d vlandev en0 && ifconfig vlan%d inet %s/24 up",
network->vlan_id, network->vlan_id, network->vlan_id, ip_address);
system(ip_cmd);
// Create a new file for VLAN rules
char vlan_rules_file[64];
snprintf(vlan_rules_file, sizeof(vlan_rules_file), "/etc/pf.vlan%d.conf", network->vlan_id);
FILE *vlan_pf_conf = fopen(vlan_rules_file, "w");
if (vlan_pf_conf == NULL) {
perror("Failed to create VLAN rules file");
free(ip_address);
return;
}
// Write the VLAN rules to the new file
fprintf(vlan_pf_conf,
"# VLAN %d rules\n"
"nat on en0 from %s/24 to any -> (en0)\n"
"pass on vlan%d all\n"
"pass in on vlan%d all\n"
"pass out on vlan%d all\n",
network->vlan_id,
ip_address,
network->vlan_id,
network->vlan_id,
network->vlan_id
);
fclose(vlan_pf_conf);
// Add include statement to main pf.conf if not already present
char include_cmd[256];
snprintf(include_cmd, sizeof(include_cmd),
"grep -q 'include \"%s\"' /etc/pf.conf || echo 'include \"%s\"' >> /etc/pf.conf",
vlan_rules_file, vlan_rules_file);
system(include_cmd);
// Reload only the VLAN rules
char reload_cmd[256];
snprintf(reload_cmd, sizeof(reload_cmd), "pfctl -f %s", vlan_rules_file);
system(reload_cmd);