-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoSu.c
1485 lines (1344 loc) · 50.7 KB
/
oSu.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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <errno.h>
#include <linux/securebits.h>
#include <getopt.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>
#include <termios.h>
#include <pty.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <security/pam_appl.h>
#include <security/pam_misc.h>
#include <fcntl.h>
#include <limits.h>
#include <ctype.h>
#include <signal.h>
// Color Definitions
#define GREEN "\033[1;32m"
#define RED "\033[1;31m"
#define YELLOW "\033[1;33m"
#define BLUE "\033[1;34m"
#define MAGENTA "\033[1;35m"
#define CYAN "\033[1;36m"
#define RESET "\033[0m"
#define VERSION "1.1"
#define AUTHOR "Oddbyte (https://oddbyte.dev)"
const char *default_config = "\
# oSu configuration file.\n\
\n\
PATH-SECURE = { /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin } # PATH is automatically set to this upon running.\n\
\n\
# You can use UIDs and GIDs:\n\
user-[0] allow-caps all NOPASSWD\n\
group-[0] allow-caps all NOPASSWD\n\
# You can also use user / group names:\n\
# group-[wheel] allow-caps all\n\
# You can set specific capabilities to allow:\n\
# user-[oddbyte] allow-caps cap_dac_override,cap_chown\n\
# You can also deny certain ones:\n\
# group-[oddbyte] allow-caps all deny-caps cap_sys_admin,cap_bpf\n\
# The override specification should go like this, from most important (overrides lowers) to least important:\n\
\n\
# User Deny\n\
# Primary group deny\n\
# User Allow\n\
# Primary group allow\n\
# Supplemental group deny\n\
# Supplemental group allow\n\
\n\
# Example:\n\
# User oddbyte with group oddbyte and supplemental groups users and wheel runs osu\n\
# The config has user-[oddbyte] allow-caps cap_dac_override,cap_chown and group-[oddbyte] allow-caps all deny-caps cap_sys_admin,cap_bpf and group-[wheel] allow-caps all\n\
# This translates into: allow everything except cap_sys_admin,cap_bpf (group wheel allows all, but the primary group (oddbyte) is denying cap_sys_admin,cap_bpf)\n\
";
uid_t original_uid;
gid_t original_gid;
gid_t *user_supp_gids = NULL;
int num_user_supp_gids = 0;
void get_user_groups(uid_t uid, gid_t **groups, int *num_groups);
int has_option(char opt, int argc, char *argv[]);
typedef struct cap_rule {
int is_user_rule;
char *name;
uid_t uid;
gid_t gid;
int nopasswd;
int allow_all_caps;
int deny_all_caps;
cap_value_t allow_caps[64];
int num_allow_caps;
cap_value_t deny_caps[64];
int num_deny_caps;
struct cap_rule *next;
} cap_rule_t;
typedef struct {
char *path_secure;
cap_rule_t *rules;
} config_t;
// Function Declarations
void debug_capabilities(const char *message);
void set_all_caps();
void print_usage(int color_enabled);
int authenticate_user(const char *username);
void create_default_config(const char *config_path);
void enforce_config_permissions(const char *config_path);
void parse_config(const char *config_path, config_t *config);
void free_config(config_t *config);
void verify_binary_location(int color_enabled);
void set_secure_path(const char *path_secure, int color_enabled, int debug_mode);
void apply_capabilities(config_t *config, uid_t uid, gid_t gid, gid_t *supp_gids, int num_supp_gids);
void get_user_groups(uid_t uid, gid_t **groups, int *num_groups);
void display_user_capabilities(config_t *config, uid_t uid, gid_t gid, gid_t *supp_gids, int num_supp_gids);
char *trim_spaces(const char *str);
void set_cap_dac_read_search() {
cap_t caps = cap_get_proc();
if (!caps) {
perror(RED "cap_get_proc failed" RESET);
exit(EXIT_FAILURE);
}
cap_value_t cap_dac_read_search = CAP_DAC_READ_SEARCH;
if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap_dac_read_search, CAP_SET) == -1) {
perror(RED "Failed to set CAP_DAC_READ_SEARCH" RESET);
cap_free(caps);
exit(EXIT_FAILURE);
}
if (cap_set_proc(caps) == -1) {
perror(RED "Failed to apply capabilities to process" RESET);
cap_free(caps);
exit(EXIT_FAILURE);
}
cap_free(caps);
}
void clear_cap_dac_read_search() {
cap_t caps = cap_get_proc();
if (!caps) {
perror(RED "cap_get_proc failed" RESET);
exit(EXIT_FAILURE);
}
cap_value_t cap_dac_read_search = CAP_DAC_READ_SEARCH;
if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap_dac_read_search, CAP_CLEAR) == -1) {
perror(RED "Failed to clear CAP_DAC_READ_SEARCH" RESET);
cap_free(caps);
exit(EXIT_FAILURE);
}
if (cap_set_proc(caps) == -1) {
perror(RED "Failed to apply capabilities to process" RESET);
cap_free(caps);
exit(EXIT_FAILURE);
}
cap_free(caps);
}
int is_numeric(const char *str) {
while (*str) {
if (!isdigit((unsigned char)*str)) {
return 0;
}
str++;
}
return 1;
}
void add_supp_group(gid_t **supp_gids, int *num_supp_gids, int *supp_gids_capacity, gid_t new_gid) {
for (int i = 0; i < *num_supp_gids; i++) {
if ((*supp_gids)[i] == new_gid) {
return; // Already present, do not add again
}
}
// Initialize capacity if necessary
if (*supp_gids_capacity == 0) {
*supp_gids_capacity = 10; // Initial capacity
*supp_gids = malloc(*supp_gids_capacity * sizeof(gid_t));
if (!*supp_gids) {
perror(RED "Failed to allocate memory for supplemental groups" RESET);
exit(EXIT_FAILURE);
}
}
// Resize the array if needed
if (*num_supp_gids >= *supp_gids_capacity) {
*supp_gids_capacity *= 2;
gid_t *temp = realloc(*supp_gids, *supp_gids_capacity * sizeof(gid_t));
if (!temp) {
perror(RED "Failed to reallocate memory for supplemental groups" RESET);
free(*supp_gids);
exit(EXIT_FAILURE);
}
*supp_gids = temp;
}
// Add the new GID
(*supp_gids)[(*num_supp_gids)++] = new_gid;
}
void drop_all_caps() {
cap_t empty_caps = cap_init();
if (empty_caps == NULL) {
perror(RED "Failed to initialize empty capabilities" RESET);
exit(EXIT_FAILURE);
}
if (prctl(PR_SET_SECUREBITS, SECBIT_NO_CAP_AMBIENT_RAISE) == -1) {
perror(RED "Failed to disable ambient capability raising" RESET);
exit(EXIT_FAILURE);
}
for (int i = 0; i <= CAP_LAST_CAP; i++) {
if (prctl(PR_CAPBSET_DROP, i) == -1) {
perror(RED "Failed to drop capability from bounding set" RESET);
exit(EXIT_FAILURE);
}
}
if (cap_set_proc(empty_caps) == -1) {
perror(RED "Failed to drop all capabilities" RESET);
cap_free(empty_caps);
exit(EXIT_FAILURE);
}
cap_free(empty_caps);
}
void apply_secure_mode() {
drop_all_caps();
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1) {
perror(RED "Failed to set no-new-privs" RESET);
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[]) {
int color_enabled = 1; // Flag to enable/disable colors
// Check if output is a terminal
if (!isatty(STDOUT_FILENO)) {
color_enabled = 0;
}
verify_binary_location(color_enabled);
int preserve_path = 0;
char *whitelist_env = NULL;
char *user = NULL;
char *group = NULL;
char *supp_groups = NULL;
int login_shell = 0;
char *command = NULL;
int use_current_terminal = 1; // Use current terminal by default
int session_command = 0;
char *set_caps = NULL;
int show_capabilities = 0;
int debug_mode = 0;
static struct option long_options[] = {
{"preserve-path", no_argument, 0, 2},
{"whitelist-environment", required_argument, 0, 'w'},
{"user", required_argument, 0, 'u'},
{"group", required_argument, 0, 'g'},
{"supp-group", required_argument, 0, 'G'},
{"login", no_argument, 0, 'l'},
{"set-caps", required_argument, 0, 3},
{"command", required_argument, 0, 'c'},
{"session-command", required_argument, 0, 1},
{"pty", no_argument, 0, 'P'},
{"help", no_argument, 0, 'h'},
{"what-can-i-do", no_argument, 0, 4},
{"version", no_argument, 0, 'V'},
{"debug", no_argument, 0, 5},
{"no-color", no_argument, 0, 6},
{"drop", no_argument, 0, 7},
{0, 0, 0, 0}
};
int secure_mode = 0;
int opt;
int option_index = 0;
while ((opt = getopt_long(argc, argv, "mpw:u:g:G:lc:PhV", long_options, &option_index)) != -1) {
switch (opt) {
case 2:
preserve_path = 1;
break;
case 'w':
whitelist_env = optarg;
break;
case 'u':
user = optarg;
break;
case 'g':
group = optarg;
break;
case 'G':
supp_groups = optarg;
break;
case 'l':
login_shell = 1;
break;
case 3:
set_caps = optarg;
break;
case 'c':
command = optarg;
break;
case 'P':
use_current_terminal = 0; // Use a new pty if --pty is specified
break;
case 'h':
print_usage(color_enabled);
exit(EXIT_SUCCESS);
case 'V':
if (color_enabled) {
printf(GREEN "osu version %s\n" RESET, VERSION);
printf(MAGENTA "oSu author: %s\n" RESET, AUTHOR);
} else {
printf("osu version %s\n", VERSION);
printf("oSu author: %s\n", AUTHOR);
}
exit(EXIT_SUCCESS);
case 1:
command = optarg;
session_command = 1;
break;
case 4:
show_capabilities = 1;
break;
case 5:
debug_mode = 1;
break;
case 6:
color_enabled = 0;
break;
case 7:
secure_mode = 1;
break;
default:
print_usage(color_enabled);
exit(EXIT_FAILURE);
}
}
original_uid = getuid();
original_gid = getgid();
if (debug_mode) {
if (color_enabled) {
printf(CYAN "Original UID: %d\n" RESET, original_uid);
printf(CYAN "Original GID: %d\n" RESET, original_gid);
} else {
printf("Original UID: %d\n", original_uid);
printf("Original GID: %d\n", original_gid);
}
}
struct passwd *pw = getpwuid(original_uid);
if (!pw) {
fprintf(stderr, RED "Failed to get user info\n" RESET);
exit(EXIT_FAILURE);
}
const char *username = pw->pw_name;
gid_t *supp_gids = NULL;
int num_supp_gids = 0;
int supp_gids_capacity = 0;
get_user_groups(original_uid, &user_supp_gids, &num_user_supp_gids);
if (debug_mode) {
if (color_enabled) {
printf(YELLOW "=== uname -a ===\n" RESET);
} else {
printf("=== uname -a ===\n");
}
system("uname -a");
if (color_enabled) {
printf(YELLOW "================\n" RESET);
printf(CYAN "Caller's ID: \n" RESET);
printf(CYAN "UID: %d, GID: %d\n" RESET, original_uid, original_gid);
} else {
printf("================\n");
printf("Caller's ID: \n");
printf("UID: %d, GID: %d\n", original_uid, original_gid);
}
}
const char *config_path = "/etc/osu.conf";
struct stat st;
if (stat(config_path, &st) != 0) {
create_default_config(config_path);
}
enforce_config_permissions(config_path);
config_t config;
memset(&config, 0, sizeof(config_t));
parse_config(config_path, &config);
if (!preserve_path) {
if (config.path_secure) {
set_secure_path(config.path_secure, color_enabled, debug_mode);
} else {
fprintf(stderr, RED "PATH-SECURE not specified in config file\n" RESET);
exit(EXIT_FAILURE);
}
}
int requires_auth = 1;
cap_rule_t *rule = config.rules;
while (rule) {
if (rule->is_user_rule && rule->uid == original_uid && rule->nopasswd) {
requires_auth = 0;
break;
}
rule = rule->next;
}
if (requires_auth) {
if (authenticate_user(username) != 0) {
fprintf(stderr, RED "Authentication failed\n" RESET);
exit(EXIT_FAILURE);
}
}
if (show_capabilities) {
apply_capabilities(&config, original_uid, original_gid, user_supp_gids, num_user_supp_gids);
display_user_capabilities(&config, original_uid, original_gid, user_supp_gids, num_user_supp_gids);
free_config(&config);
free(user_supp_gids);
exit(EXIT_SUCCESS);
}
if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP) == -1) {
perror(RED "Failed to set securebits" RESET);
exit(EXIT_FAILURE);
}
if (setgid(0) == -1 || setuid(0) == -1) {
perror(RED "Failed to set UID/GID to root" RESET);
exit(EXIT_FAILURE);
}
set_all_caps();
if (debug_mode) {
debug_capabilities("After setting all capabilities");
}
if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP) == -1) {
perror(RED "Failed to set securebits before dropping root" RESET);
exit(EXIT_FAILURE);
}
// Validate that the caller is allowed to switch to the target user/group
uid_t target_uid = original_uid;
gid_t target_gid = original_gid;
if (user) {
struct passwd *pw_target = getpwnam(user);
if (!pw_target) {
fprintf(stderr, RED "User '%s' not found\n" RESET, user);
exit(EXIT_FAILURE);
}
target_uid = pw_target->pw_uid;
// Check if the caller has permission to switch to the target user
if (original_uid != 0 && original_uid != target_uid) {
fprintf(stderr, RED "You do not have permission to switch to user '%s'\n" RESET, user);
exit(EXIT_FAILURE);
}
setenv("HOME", pw_target->pw_dir, 1);
setenv("LOGNAME", user, 1);
}
if (group) {
struct group *gr = getgrnam(group);
if (!gr) {
fprintf(stderr, RED "Group '%s' not found\n" RESET, group);
exit(EXIT_FAILURE);
}
target_gid = gr->gr_gid;
// Check if the caller has permission to switch to the target group
if (original_uid != 0 && original_gid != target_gid) {
fprintf(stderr, RED "You do not have permission to switch to group '%s'\n" RESET, group);
exit(EXIT_FAILURE);
}
}
if (supp_groups) {
char *supp_groups_copy = strdup(supp_groups);
if (!supp_groups_copy) {
perror(RED "Failed to duplicate supplemental groups string" RESET);
exit(EXIT_FAILURE);
}
char *token = strtok(supp_groups_copy, ",");
while (token) {
struct group *gr = getgrnam(token);
if (!gr) {
fprintf(stderr, RED "Supplemental group '%s' not found\n" RESET, token);
free(supp_groups_copy);
free(supp_gids);
exit(EXIT_FAILURE);
}
// Check if the caller has permission to add supplemental groups
if (original_uid != 0) {
int found = 0;
for (int i = 0; i < num_user_supp_gids; i++) {
if (user_supp_gids[i] == gr->gr_gid) {
found = 1;
break;
}
}
if (!found) {
fprintf(stderr, RED "You do not have permission to add supplemental group '%s'\n" RESET, token);
free(supp_groups_copy);
free(supp_gids);
exit(EXIT_FAILURE);
}
}
// Add the group dynamically
add_supp_group(&supp_gids, &num_supp_gids, &supp_gids_capacity, gr->gr_gid);
token = strtok(NULL, ",");
}
free(supp_groups_copy);
} else {
// Preserve original supplemental groups
for (int i = 0; i < num_user_supp_gids; i++) {
add_supp_group(&supp_gids, &num_supp_gids, &supp_gids_capacity, user_supp_gids[i]);
}
}
// Check if the caller has CAP_SETUID and CAP_SETGID
cap_t current_caps = cap_get_proc();
if (!current_caps) {
perror(RED "Failed to get current capabilities" RESET);
exit(EXIT_FAILURE);
}
cap_flag_value_t cap_setuid_value;
if (cap_get_flag(current_caps, CAP_SETUID, CAP_EFFECTIVE, &cap_setuid_value) == -1) {
perror(RED "Failed to get CAP_SETUID flag" RESET);
cap_free(current_caps);
exit(EXIT_FAILURE);
}
cap_flag_value_t cap_setgid_value;
if (cap_get_flag(current_caps, CAP_SETGID, CAP_EFFECTIVE, &cap_setgid_value) == -1) {
perror(RED "Failed to get CAP_SETGID flag" RESET);
cap_free(current_caps);
exit(EXIT_FAILURE);
}
if(debug_mode) {
if (color_enabled) {
printf(YELLOW "Attempting to change UID to %d, and GID to %d\n" RESET, target_uid, target_gid);
printf(YELLOW "With %d supplemental groups\n" RESET, num_supp_gids);
} else {
printf("Attempting to change UID to %d, and GID to %d\n", target_uid, target_gid);
printf("With %d supplemental groups\n", num_supp_gids);
}
}
if (target_uid != original_uid && cap_setuid_value != CAP_SET) {
fprintf(stderr, RED "You are not allowed to change user (CAP_SETUID denied).\n" RESET);
cap_free(current_caps);
exit(EXIT_FAILURE);
}
if ((target_gid != original_gid || num_supp_gids != num_user_supp_gids) && cap_setgid_value != CAP_SET) {
fprintf(stderr, RED "You are not allowed to change group (CAP_SETGID denied).\n" RESET);
cap_free(current_caps);
exit(EXIT_FAILURE);
}
cap_free(current_caps);
if (debug_mode) {
debug_capabilities("Right before setgroups for supplemental groups");
}
// Apply supplemental groups
if (setgroups(num_supp_gids, supp_gids) == -1) {
perror(RED "Failed to set supplemental groups" RESET);
free(supp_gids);
exit(EXIT_FAILURE);
}
// Apply GID
if (setgid(target_gid) == -1) {
perror(RED "Failed to set GID" RESET);
exit(EXIT_FAILURE);
}
// Apply UID
if (setuid(target_uid) == -1) {
perror(RED "Failed to set UID" RESET);
exit(EXIT_FAILURE);
}
if (debug_mode) {
debug_capabilities("After setting UID and GID");
}
if (secure_mode) {
apply_secure_mode();
}
// Only set PATH to the secure path
if (!preserve_path) {
if (config.path_secure) {
set_secure_path(config.path_secure, color_enabled, debug_mode);
} else {
fprintf(stderr, RED "PATH-SECURE not specified in config file\n" RESET);
exit(EXIT_FAILURE);
}
}
// Apply capabilities based on the caller's UID and GIDs
if (!secure_mode) apply_capabilities(&config, original_uid, original_gid, user_supp_gids, num_user_supp_gids);
if (debug_mode) {
debug_capabilities("After applying capabilities based on configuration");
}
// Reset signal handlers
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
signal(SIGTTOU, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
// Set the shell process as the leader of a new process group
if (setpgid(0, 0) == -1) {
perror(RED "Failed to set process group" RESET);
exit(EXIT_FAILURE);
}
// Take control of the terminal
if (tcsetpgrp(STDIN_FILENO, getpid()) == -1) {
perror(RED "Failed to set controlling terminal" RESET);
exit(EXIT_FAILURE);
}
char *shell = "/usr/bin/bash";
char *shell_args[6];
int arg_index = 0;
if (login_shell) {
shell_args[arg_index++] = "--login";
}
shell_args[arg_index++] = "-i"; // Start an interactive shell
if (set_caps) {
cap_value_t user_caps[64];
int num_user_caps = 0;
char *caps_copy = strdup(set_caps);
if (!caps_copy) {
perror(RED "Failed to duplicate set_caps string" RESET);
exit(EXIT_FAILURE);
}
char *token = strtok(caps_copy, ",");
while (token && num_user_caps < 64) {
cap_value_t cap;
if (cap_from_name(token, &cap) == 0) {
user_caps[num_user_caps++] = cap;
} else {
fprintf(stderr, RED "Invalid capability: %s\n" RESET, token);
exit(EXIT_FAILURE);
}
token = strtok(NULL, ",");
}
free(caps_copy);
cap_t allowed_caps = cap_get_proc();
if (!allowed_caps) {
perror(RED "Failed to get allowed capabilities" RESET);
exit(EXIT_FAILURE);
}
cap_t desired_caps = cap_init();
if (!desired_caps) {
perror(RED "Failed to initialize desired capabilities" RESET);
cap_free(allowed_caps);
exit(EXIT_FAILURE);
}
for (int i = 0; i < num_user_caps; i++) {
cap_set_flag(desired_caps, CAP_EFFECTIVE, 1, &user_caps[i], CAP_SET);
cap_set_flag(desired_caps, CAP_PERMITTED, 1, &user_caps[i], CAP_SET);
cap_set_flag(desired_caps, CAP_INHERITABLE, 1, &user_caps[i], CAP_SET);
}
if (cap_set_proc(desired_caps) == -1) {
perror(RED "Failed to set desired capabilities" RESET);
cap_free(allowed_caps);
cap_free(desired_caps);
exit(EXIT_FAILURE);
}
cap_free(allowed_caps);
cap_free(desired_caps);
for (int i = 0; i < num_user_caps; i++) {
if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, user_caps[i], 0, 0) == -1) {
perror(RED "Failed to raise capability in ambient set" RESET);
exit(EXIT_FAILURE);
}
}
}
if (command) {
if(debug_mode) {
if (color_enabled) {
printf(YELLOW "command = %s\n" RESET, command);
} else {
printf("command = %s\n", command);
}
}
shell_args[arg_index++] = "-c";
shell_args[arg_index++] = command;
}
shell_args[arg_index] = NULL;
if (use_current_terminal) {
if (debug_mode) {
char cmd[4096] = {0}; // Initialize buffer with zeros
size_t cmd_len = 0;
for (int i = 0; shell_args[i] != NULL; i++) {
size_t arg_len = strlen(shell_args[i]);
if (cmd_len + arg_len + 1 >= sizeof(cmd)) { // +1 for space or null terminator
fprintf(stderr, RED "Command too long to debug print.\n" RESET);
break;
}
strcat(cmd, shell_args[i]);
cmd_len += arg_len;
if (shell_args[i + 1] != NULL) { // Add space if not the last argument
strcat(cmd, " ");
cmd_len += 1;
}
}
if (color_enabled) {
printf(CYAN "Executing: %s %s\n" RESET, shell, cmd);
} else {
printf("Executing: %s %s\n", shell, cmd);
}
}
// Directly exec the shell without forking
execv(shell, shell_args);
perror(RED "Failed to execute shell" RESET);
exit(EXIT_FAILURE);
} else {
if (debug_mode) {
char cmd[4096] = {0}; // Initialize buffer with zeros
size_t cmd_len = 0;
for (int i = 0; shell_args[i] != NULL; i++) {
size_t arg_len = strlen(shell_args[i]);
if (cmd_len + arg_len + 1 >= sizeof(cmd)) { // +1 for space or null terminator
fprintf(stderr, RED "Command too long to debug print.\n" RESET);
break;
}
strcat(cmd, shell_args[i]);
cmd_len += arg_len;
if (shell_args[i + 1] != NULL) { // Add space if not the last argument
strcat(cmd, " ");
cmd_len += 1;
}
}
if (color_enabled) {
printf(CYAN "Executing: %s\n" RESET, shell, cmd);
} else {
printf("Executing: %s\n", shell, cmd);
}
}
// Create a new pseudo-terminal
int master_fd;
pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);
if (pid == -1) {
perror(RED "Failed to forkpty" RESET);
exit(EXIT_FAILURE);
} else if (pid == 0) {
if (session_command) {
execv(shell, shell_args);
} else {
setsid();
execv(shell, shell_args);
}
perror(RED "Failed to execute shell" RESET);
exit(EXIT_FAILURE);
} else {
if (debug_mode) {
char cmd[4096] = {0}; // Initialize buffer with zeros
size_t cmd_len = 0;
for (int i = 0; shell_args[i] != NULL; i++) {
size_t arg_len = strlen(shell_args[i]);
if (cmd_len + arg_len + 1 >= sizeof(cmd)) { // +1 for space or null terminator
fprintf(stderr, RED "Command too long to debug print.\n" RESET);
break;
}
strcat(cmd, shell_args[i]);
cmd_len += arg_len;
if (shell_args[i + 1] != NULL) { // Add space if not the last argument
strcat(cmd, " ");
cmd_len += 1;
}
}
if (color_enabled) {
printf(CYAN "Executing: %s\n" RESET, shell, cmd);
} else {
printf("Executing: %s\n", shell, cmd);
}
}
fd_set fds;
char buf[256];
ssize_t nread;
while (1) {
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
FD_SET(master_fd, &fds);
int maxfd = (STDIN_FILENO > master_fd) ? STDIN_FILENO : master_fd;
int ret = select(maxfd + 1, &fds, NULL, NULL, NULL);
if (ret == -1) {
perror(RED "select failed" RESET);
break;
}
if (FD_ISSET(STDIN_FILENO, &fds)) {
nread = read(STDIN_FILENO, buf, sizeof(buf));
if (nread <= 0)
break;
write(master_fd, buf, nread);
}
if (FD_ISSET(master_fd, &fds)) {
nread = read(master_fd, buf, sizeof(buf));
if (nread <= 0)
break;
write(STDOUT_FILENO, buf, nread);
}
}
int status;
waitpid(pid, &status, 0);
}
}
free_config(&config);
free(user_supp_gids);
free(supp_gids);
return EXIT_SUCCESS;
}
void print_usage(int color_enabled) {
if (color_enabled) {
printf(MAGENTA "Usage:\n" RESET);
printf(" osu [options]\n\n");
printf(MAGENTA "Options:\n" RESET);
printf(GREEN " --preserve-path" RESET " don't reset path to PATH-SECURE\n");
printf(GREEN " -w, --whitelist-environment <list>" RESET " don't reset specified variables (If Path is included in this, it is ignored. Use --preserve-path instead.)\n");
printf("\n");
printf(GREEN " -u, --user <user>" RESET " specify the user\n");
printf(GREEN " -g, --group <group>" RESET " specify the primary group\n");
printf(GREEN " -G, --supp-group <group>" RESET " specify a supplemental group\n");
printf("\n");
printf(GREEN " -l, --login" RESET " make the shell a login shell\n");
printf(GREEN " --set-caps <list>" RESET " only set the specified capabilities (only if you have access to them. Run osu --what-can-i-do to see all capabilities you are allowed to use.)\n");
printf(GREEN " -c, --command <command>" RESET " pass a command to the shell with -c\n");
printf(" please make sure to enclose any commands that require spaces in double quotes (\"\")\n");
printf(" also, please escape any double quotes in the command like so: (\\\")\n");
printf(GREEN " --session-command <command>" RESET " pass a command to the shell with -c and do not create a new session\n");
printf(GREEN " -P, --pty" RESET " create a new pseudo-terminal\n");
printf("\n");
printf(GREEN " --debug" RESET " display debug messages all steps of the way\n");
printf(GREEN " --drop" RESET " drop all privs and capabilities, and set no-new-privs\n");
printf(GREEN " -h, --help" RESET " display this help\n");
printf(GREEN " --what-can-i-do" RESET " display what capabilities you can \n");
printf(GREEN " -V, --version" RESET " display version\n");
printf("\n");
printf(MAGENTA "Examples:\n" RESET);
printf(" osu\n");
printf(" osu -c sh\n");
printf(" osu --drop\n");
printf(" osu -u root -g 0 -G users,106 -c \"echo \\\"hello\\\"\"\n");
printf("\n");
printf("osu version %s\n", VERSION);
printf("oSu author: %s\n", AUTHOR);
} else {
printf("Usage:\n");
printf(" osu [options]\n\n");
printf("Options:\n");
printf(" --preserve-path don't reset path to PATH-SECURE\n");
printf(" -w, --whitelist-environment <list> don't reset specified variables (If Path is included in this, it is ignored. Use --preserve-path instead.)\n");
printf("\n");
printf(" -u, --user <user> specify the user\n");
printf(" -g, --group <group> specify the primary group\n");
printf(" -G, --supp-group <group> specify a supplemental group\n");
printf("\n");
printf(" -l, --login make the shell a login shell\n");
printf(" --set-caps <list> only set the specified capabilities (only if you have access to them. Run osu --what-can-i-do to see all capabilities you are allowed to use.)\n");
printf(" -c, --command <command> pass a command to the shell with -c\n");
printf(" please make sure to enclose any commands that require spaces in double quotes (\"\")\n");
printf(" also, please escape any double quotes in the command like so: (\\\")\n");
printf(" --session-command <command> pass a command to the shell with -c and do not create a new session\n");
printf(" -P, --pty create a new pseudo-terminal\n");
printf("\n");
printf(" --debug display debug messages all steps of the way\n");
printf(" --drop drop all privs and capabilities, and set no-new-privs\n");
printf(" -h, --help display this help\n");
printf(" --what-can-i-do display what capabilities you can \n");
printf(" -V, --version display version\n");
printf("\n");
printf("Examples:\n");
printf(" osu\n");
printf(" osu -c sh\n");
printf(" osu -u root -g 0 -G users,106 -c \"echo \\\"hello\\\"\"\n");
printf("\n");
printf("osu version %s\n", VERSION);
printf("oSu author: %s\n", AUTHOR);
}
}
void debug_capabilities(const char *message) {
printf(YELLOW "\n=== %s ===\n" RESET, message);
system("/usr/sbin/capsh --print");
}
void verify_binary_location(int color_enabled) {
char path[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", path, sizeof(path) - 1);
if (len == -1) {
perror(RED "Failed to get executable path" RESET);
exit(EXIT_FAILURE);
}
path[len] = '\0';
if (strcmp(path, "/usr/local/bin/osu") != 0) {
if (color_enabled) {
fprintf(stderr, RED "This binary must be located at /usr/local/bin/osu\n" RESET);
} else {
fprintf(stderr, "This binary must be located at /usr/local/bin/osu\n");
}
exit(EXIT_FAILURE);
}
}
void create_default_config(const char *config_path) {
FILE *file = fopen(config_path, "w");
if (!file) {
perror(RED "Failed to create default config file" RESET);
exit(EXIT_FAILURE);
}
fprintf(file, "%s", default_config);
fclose(file);
printf(GREEN "Default configuration file created at %s\n" RESET, config_path);
}
void enforce_config_permissions(const char *config_path) {
struct stat st;
if (stat(config_path, &st) != 0) {
perror(RED "Failed to stat config file" RESET);
exit(EXIT_FAILURE);
}
if (st.st_uid != 0 || st.st_gid != 0) {
if (chown(config_path, 0, 0) != 0) {
perror(RED "Failed to change ownership of config file" RESET);
exit(EXIT_FAILURE);
}
if (chown(config_path, 0, 0) == 0) {
if (st.st_uid != 0 || st.st_gid != 0) {
printf(GREEN "Ownership of config file set to root.\n" RESET);
}
}
}
if ((st.st_mode & 0777) != 0400) {
if (chmod(config_path, 0400) != 0) {
perror(RED "Failed to change permissions of config file" RESET);
exit(EXIT_FAILURE);
}
printf(GREEN "Permissions of config file set to 0400.\n" RESET);
}
}
void set_secure_path(const char *path_secure, int color_enabled, int debug_mode) {
if (setenv("PATH", path_secure, 1) != 0) {
perror(RED "Failed to set secure PATH" RESET);
exit(EXIT_FAILURE);
}
if (debug_mode) {
if (color_enabled) {
printf(GREEN "Secure PATH set to: %s\n" RESET, path_secure);
} else {
printf("Secure PATH set to: %s\n", path_secure);
}
}
}
char *trim_spaces(const char *str) {
while (isspace((unsigned char)*str)) str++;
if (*str == 0)
return strdup("");
const char *end = str + strlen(str) - 1;
while (end > str && isspace((unsigned char)*end)) {
end--;
}
size_t len = end - str + 1;