summaryrefslogtreecommitdiff
blob: 8afbac71ee7dfc3eb198b7ff6fc55c373e224dcd (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
/*
 *  Path sandbox for the gentoo linux portage package system, initially
 *  based on the ROCK Linux Wrapper for getting a list of created files
 *
 *  to integrate with bash, bash should have been built like this
 *
 *  ./configure --prefix=<prefix> --host=<host> --without-gnu-malloc
 *
 *  it's very important that the --enable-static-link option is NOT specified
 *
 *  Copyright (C) 2001 Geert Bevin, Uwyn, http://www.uwyn.com
 *  Distributed under the terms of the GNU General Public License, v2 or later 
 *  Author : Geert Bevin <gbevin@uwyn.com>
 *
 *  Post Bevin leaving Gentoo ranks:
 *  --------------------------------
 *    Ripped out all the wrappers, and implemented those of InstallWatch.
 *    Losts of cleanups and bugfixes.  Implement a execve that forces $LIBSANDBOX
 *    in $LD_PRELOAD.  Reformat the whole thing to look  somewhat like the reworked
 *    sandbox.c from Brad House <brad@mainstreetsoftworks.com>.
 *
 *    Martin Schlemmer <azarah@gentoo.org> (18 Aug 2002)
 *
 *  Partly Copyright (C) 1998-9 Pancrazio `Ezio' de Mauro <p@demauro.net>,
 *  as some of the InstallWatch code was used.
 *
 *
 *  $Id: /var/cvsroot/gentoo-src/portage/src/sandbox-1.1/Attic/libsandbox.c,v 1.22.2.3 2004/12/01 22:14:09 carpaski Exp $
 *
 */

/* Uncomment below to enable wrapping of mknod().
 * This is broken currently. */
/* #define WRAP_MKNOD 1 */

/* Uncomment below to enable the use of strtok_r(). */
#define REENTRANT_STRTOK 1

/* Uncomment below to enable memory debugging. */
/* #define SB_MEM_DEBUG 1 */

#define open   xxx_open
#define open64 xxx_open64

/* Wrapping mknod, do not have any effect, and
 * wrapping __xmknod causes calls to it to segfault
 */
#ifdef WRAP_MKNOD
# define __xmknod xxx___xmknod
#endif

#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/param.h>
#include <unistd.h>
#include <utime.h>

#ifdef SB_MEM_DEBUG
# include <mcheck.h>
#endif

#ifdef WRAP_MKNOD
# undef __xmknod
#endif

#undef open
#undef open64

#include "localdecls.h"
#include "sandbox.h"

/* Macros to check if a function should be executed */
#define FUNCTION_SANDBOX_SAFE(func, path) \
        ((0 == is_sandbox_on()) || (1 == before_syscall(func, path)))

#define FUNCTION_SANDBOX_SAFE_INT(func, path, flags) \
        ((0 == is_sandbox_on()) || (1 == before_syscall_open_int(func, path, flags)))

#define FUNCTION_SANDBOX_SAFE_CHAR(func, path, mode) \
        ((0 == is_sandbox_on()) || (1 == before_syscall_open_char(func, path, mode)))

/* Macro to check if a wrapper is defined, if not
 * then try to resolve it again. */
#define check_dlsym(name) \
{ \
  int old_errno=errno; \
  if (!true_ ## name) true_ ## name=get_dlsym(#name); \
  errno=old_errno; \
}

/* Macro to check if we could canonicalize a path.  It returns an integer on
 * failure. */
#define canonicalize_int(path, resolved_path) \
{ \
  if (0 != canonicalize(path, resolved_path)) \
    return -1; \
}

/* Macro to check if we could canonicalize a path.  It returns a NULL pointer on
 * failure. */
#define canonicalize_ptr(path, resolved_path) \
{ \
  if (0 != canonicalize(path, resolved_path)) \
    return NULL; \
}

static char sandbox_lib[255];
//static char sandbox_pids_file[255];
static char *sandbox_pids_file;

typedef struct {
	int show_access_violation;
	char **deny_prefixes;
	int num_deny_prefixes;
	char **read_prefixes;
	int num_read_prefixes;
	char **write_prefixes;
	int num_write_prefixes;
	char **predict_prefixes;
	int num_predict_prefixes;
	char **write_denied_prefixes;
	int num_write_denied_prefixes;
} sbcontext_t;

/* glibc modified realpath() functions */
char *erealpath(const char *name, char *resolved);
/* glibc modified getcwd() functions */
char *egetcwd(char *, size_t);

static void init_wrappers(void);
static void *get_dlsym(const char *);
static int canonicalize(const char *, char *);
static int check_access(sbcontext_t *, const char *, const char *);
static int check_syscall(sbcontext_t *, const char *, const char *);
static int before_syscall(const char *, const char *);
static int before_syscall_open_int(const char *, const char *, int);
static int before_syscall_open_char(const char *, const char *, const char *);
static void clean_env_entries(char ***, int *);
static void init_context(sbcontext_t *);
static void init_env_entries(char ***, int *, char *, int);
static char *filter_path(const char *);
static int is_sandbox_on();
static int is_sandbox_pid();

/* Wrapped functions */

extern int chmod(const char *, mode_t);
static int (*true_chmod) (const char *, mode_t);
extern int chown(const char *, uid_t, gid_t);
static int (*true_chown) (const char *, uid_t, gid_t);
extern int creat(const char *, mode_t);
static int (*true_creat) (const char *, mode_t);
extern FILE *fopen(const char *, const char *);
static FILE *(*true_fopen) (const char *, const char *);
extern int lchown(const char *, uid_t, gid_t);
static int (*true_lchown) (const char *, uid_t, gid_t);
extern int link(const char *, const char *);
static int (*true_link) (const char *, const char *);
extern int mkdir(const char *, mode_t);
static int (*true_mkdir) (const char *, mode_t);
extern DIR *opendir(const char *);
static DIR *(*true_opendir) (const char *);
#ifdef WRAP_MKNOD
extern int __xmknod(const char *, mode_t, dev_t);
static int (*true___xmknod) (const char *, mode_t, dev_t);
#endif
extern int open(const char *, int, ...);
static int (*true_open) (const char *, int, ...);
extern int rename(const char *, const char *);
static int (*true_rename) (const char *, const char *);
extern int rmdir(const char *);
static int (*true_rmdir) (const char *);
extern int symlink(const char *, const char *);
static int (*true_symlink) (const char *, const char *);
extern int truncate(const char *, TRUNCATE_T);
static int (*true_truncate) (const char *, TRUNCATE_T);
extern int unlink(const char *);
static int (*true_unlink) (const char *);

#if (GLIBC_MINOR >= 1)

extern int creat64(const char *, __mode_t);
static int (*true_creat64) (const char *, __mode_t);
extern FILE *fopen64(const char *, const char *);
static FILE *(*true_fopen64) (const char *, const char *);
extern int open64(const char *, int, ...);
static int (*true_open64) (const char *, int, ...);
extern int truncate64(const char *, __off64_t);
static int (*true_truncate64) (const char *, __off64_t);

#endif

extern int execve(const char *filename, char *const argv[], char *const envp[]);
static int (*true_execve) (const char *, char *const[], char *const[]);

/*
 * Initialize the shabang
 */

static void
init_wrappers(void)
{
	void *libc_handle = NULL;

#ifdef BROKEN_RTLD_NEXT
//  printf ("RTLD_LAZY");
	libc_handle = dlopen(LIBC_VERSION, RTLD_LAZY);
#else
//  printf ("RTLD_NEXT");
	libc_handle = RTLD_NEXT;
#endif

	true_chmod = dlsym(libc_handle, "chmod");
	true_chown = dlsym(libc_handle, "chown");
	true_creat = dlsym(libc_handle, "creat");
	true_fopen = dlsym(libc_handle, "fopen");
	true_lchown = dlsym(libc_handle, "lchown");
	true_link = dlsym(libc_handle, "link");
	true_mkdir = dlsym(libc_handle, "mkdir");
	true_opendir = dlsym(libc_handle, "opendir");
#ifdef WRAP_MKNOD
	true___xmknod = dlsym(libc_handle, "__xmknod");
#endif
	true_open = dlsym(libc_handle, "open");
	true_rename = dlsym(libc_handle, "rename");
	true_rmdir = dlsym(libc_handle, "rmdir");
	true_symlink = dlsym(libc_handle, "symlink");
	true_truncate = dlsym(libc_handle, "truncate");
	true_unlink = dlsym(libc_handle, "unlink");

#if (GLIBC_MINOR >= 1)
	true_creat64 = dlsym(libc_handle, "creat64");
	true_fopen64 = dlsym(libc_handle, "fopen64");
	true_open64 = dlsym(libc_handle, "open64");
	true_truncate64 = dlsym(libc_handle, "truncate64");
#endif

	true_execve = dlsym(libc_handle, "execve");
}

void
_fini(void)
{
    free(sandbox_pids_file);
}

void
_init(void)
{
	int old_errno = errno;
	char *tmp_string = NULL;

#ifdef SB_MEM_DEBUG
	mtrace();
#endif

	init_wrappers();

	/* Get the path and name to this library */
	tmp_string = get_sandbox_lib("/");
	strncpy(sandbox_lib, tmp_string, sizeof(sandbox_lib)-1);
	if (tmp_string)
		free(tmp_string);
	tmp_string = NULL;

	/* Generate sandbox pids-file path */
	sandbox_pids_file = get_sandbox_pids_file();

	errno = old_errno;
}

static int
canonicalize(const char *path, char *resolved_path)
{
	int old_errno = errno;
	char *retval;

	*resolved_path = '\0';

	/* If path == NULL, return or we get a segfault */
	if (NULL == path) {
		errno = EINVAL;
		return -1;
	}

	/* Do not try to resolve an empty path */
	if ('\0' == path[0]) {
		errno = old_errno;
		return 0;
	}

	retval = erealpath(path, resolved_path);

	if ((!retval) && (path[0] != '/')) {
		/* The path could not be canonicalized, append it
		 * to the current working directory if it was not
		 * an absolute path
		 */
		if (errno == ENAMETOOLONG)
			return -1;

		egetcwd(resolved_path, SB_PATH_MAX - 2);
		strcat(resolved_path, "/");
		strncat(resolved_path, path, SB_PATH_MAX - 1);

		if (!erealpath(resolved_path, resolved_path)) {
			if (errno == ENAMETOOLONG) {
				/* The resolved path is too long for the buffer to hold */
				return -1;
			} else {
				/* Whatever it resolved, is not a valid path */
				errno = ENOENT;
				return -1;
			}
		}

	} else if ((!retval) && (path[0] == '/')) {
		/* Whatever it resolved, is not a valid path */
		errno = ENOENT;
		return -1;
	}

	errno = old_errno;
	return 0;
}

static void *
get_dlsym(const char *symname)
{
	void *libc_handle = NULL;
	void *symaddr = NULL;

#ifdef BROKEN_RTLD_NEXT
	libc_handle = dlopen(LIBC_VERSION, RTLD_LAZY);
	if (!libc_handle) {
		printf("libsandbox.so: Can't dlopen libc: %s\n", dlerror());
		abort();
	}
#else
	libc_handle = RTLD_NEXT;
#endif

	symaddr = dlsym(libc_handle, symname);
	if (!symaddr) {
		printf("libsandbox.so: Can't resolve %s: %s\n", symname, dlerror());
		abort();
	}

	return symaddr;
}

/*
 * Wrapper Functions
 */

int
chmod(const char *path, mode_t mode)
{
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(path, canonic);

	if FUNCTION_SANDBOX_SAFE
		("chmod", canonic) {
		check_dlsym(chmod);
		result = true_chmod(path, mode);
		}

	return result;
}

int
chown(const char *path, uid_t owner, gid_t group)
{
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(path, canonic);

	if FUNCTION_SANDBOX_SAFE
		("chown", canonic) {
		check_dlsym(chown);
		result = true_chown(path, owner, group);
		}

	return result;
}

int
creat(const char *pathname, mode_t mode)
{
/* Is it a system call? */
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE
		("creat", canonic) {
		check_dlsym(open);
		result = true_open(pathname, O_CREAT | O_WRONLY | O_TRUNC, mode);
		}

	return result;
}

FILE *
fopen(const char *pathname, const char *mode)
{
	FILE *result = NULL;
	char canonic[SB_PATH_MAX];

	canonicalize_ptr(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE_CHAR
		("fopen", canonic, mode) {
		check_dlsym(fopen);
		result = true_fopen(pathname, mode);
		}

	return result;
}

int
lchown(const char *path, uid_t owner, gid_t group)
{
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(path, canonic);

	if FUNCTION_SANDBOX_SAFE
		("lchown", canonic) {
		check_dlsym(lchown);
		result = true_lchown(path, owner, group);
		}

	return result;
}

int
link(const char *oldpath, const char *newpath)
{
	int result = -1;
	char old_canonic[SB_PATH_MAX], new_canonic[SB_PATH_MAX];

	canonicalize_int(oldpath, old_canonic);
	canonicalize_int(newpath, new_canonic);

	if FUNCTION_SANDBOX_SAFE
		("link", new_canonic) {
		check_dlsym(link);
		result = true_link(oldpath, newpath);
		}

	return result;
}

int
mkdir(const char *pathname, mode_t mode)
// returns 0 success, or -1 if an error occurred
{
	int result = -1, my_errno = errno;
	char canonic[SB_PATH_MAX];
	struct stat st;

	canonicalize_int(pathname, canonic);

	/* Check if the directory exist, return EEXIST rather than failing */
	if (0 == lstat(canonic, &st)) {
		errno = EEXIST;
		return -1; 
	}
	errno = my_errno;

	if FUNCTION_SANDBOX_SAFE
		("mkdir", canonic) {
		check_dlsym(mkdir);
		result = true_mkdir(pathname, mode);
		}

	return result;
}

DIR *
opendir(const char *name)
{
	DIR *result = NULL;
	char canonic[SB_PATH_MAX];

	canonicalize_ptr(name, canonic);

	if FUNCTION_SANDBOX_SAFE
		("opendir", canonic) {
		check_dlsym(opendir);
		result = true_opendir(name);
		}

	return result;
}

#ifdef WRAP_MKNOD

int
__xmknod(const char *pathname, mode_t mode, dev_t dev)
{
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE
		("__xmknod", canonic) {
		check_dlsym(__xmknod);
		result = true___xmknod(pathname, mode, dev);
		}

	return result;
}

#endif

int
open(const char *pathname, int flags, ...)
{
/* Eventually, there is a third parameter: it's mode_t mode */
	va_list ap;
	mode_t mode = 0;
	int result = -1;
	char canonic[SB_PATH_MAX];

	if (flags & O_CREAT) {
		va_start(ap, flags);
		mode = va_arg(ap, mode_t);
		va_end(ap);
	}

	canonicalize_int(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE_INT
		("open", canonic, flags) {
		/* We need to resolve open() realtime in some cases,
		 * else we get a segfault when running /bin/ps, etc
		 * in a sandbox */
		check_dlsym(open);
		result = true_open(pathname, flags, mode);
		}

	return result;
}

int
rename(const char *oldpath, const char *newpath)
{
	int result = -1;
	char old_canonic[SB_PATH_MAX], new_canonic[SB_PATH_MAX];

	canonicalize_int(oldpath, old_canonic);
	canonicalize_int(newpath, new_canonic);

	if (FUNCTION_SANDBOX_SAFE("rename", old_canonic) &&
			FUNCTION_SANDBOX_SAFE("rename", new_canonic)) {
		check_dlsym(rename);
		result = true_rename(oldpath, newpath);
	}

	return result;
}

int
rmdir(const char *pathname)
{
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE
		("rmdir", canonic) {
		check_dlsym(rmdir);
		result = true_rmdir(pathname);
		}

	return result;
}

int
symlink(const char *oldpath, const char *newpath)
{
	int result = -1;
	char old_canonic[SB_PATH_MAX], new_canonic[SB_PATH_MAX];

	canonicalize_int(oldpath, old_canonic);
	canonicalize_int(newpath, new_canonic);

	if FUNCTION_SANDBOX_SAFE
		("symlink", new_canonic) {
		check_dlsym(symlink);
		result = true_symlink(oldpath, newpath);
		}

	return result;
}

int
truncate(const char *path, TRUNCATE_T length)
{
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(path, canonic);

	if FUNCTION_SANDBOX_SAFE
		("truncate", canonic) {
		check_dlsym(truncate);
		result = true_truncate(path, length);
		}

	return result;
}

int
unlink(const char *pathname)
{
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE
		("unlink", canonic) {
		check_dlsym(unlink);
		result = true_unlink(pathname);
		}

	return result;
}

#if (GLIBC_MINOR >= 1)

int
creat64(const char *pathname, __mode_t mode)
{
/* Is it a system call? */
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE
		("creat64", canonic) {
		check_dlsym(open64);
		result = true_open64(pathname, O_CREAT | O_WRONLY | O_TRUNC, mode);
		}

	return result;
}

FILE *
fopen64(const char *pathname, const char *mode)
{
	FILE *result = NULL;
	char canonic[SB_PATH_MAX];

	canonicalize_ptr(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE_CHAR
		("fopen64", canonic, mode) {
		check_dlsym(fopen64);
		result = true_fopen(pathname, mode);
		}

	return result;
}

int
open64(const char *pathname, int flags, ...)
{
/* Eventually, there is a third parameter: it's mode_t mode */
	va_list ap;
	mode_t mode = 0;
	int result = -1;
	char canonic[SB_PATH_MAX];

	if (flags & O_CREAT) {
		va_start(ap, flags);
		mode = va_arg(ap, mode_t);
		va_end(ap);
	}

	canonicalize_int(pathname, canonic);

	if FUNCTION_SANDBOX_SAFE_INT
		("open64", canonic, flags) {
		check_dlsym(open64);
		result = true_open64(pathname, flags, mode);
		}

	return result;
}

int
truncate64(const char *path, __off64_t length)
{
	int result = -1;
	char canonic[SB_PATH_MAX];

	canonicalize_int(path, canonic);

	if FUNCTION_SANDBOX_SAFE
		("truncate64", canonic) {
		check_dlsym(truncate64);
		result = true_truncate64(path, length);
		}

	return result;
}

#endif													/* GLIBC_MINOR >= 1 */

/*
 * Exec Wrappers
 */

int
execve(const char *filename, char *const argv[], char *const envp[])
{
	int old_errno = errno;
	int result = -1;
	int count = 0;
	int env_len = 0;
	char canonic[SB_PATH_MAX];
	char **my_env = NULL;
	int kill_env = 1;
	/* We limit the size LD_PRELOAD can be here, but it should be enough */
	char tmp_str[4096];

	canonicalize_int(filename, canonic);

	if FUNCTION_SANDBOX_SAFE
		("execve", canonic) {
		while (envp[count] != NULL) {
			if (strstr(envp[count], "LD_PRELOAD=") == envp[count]) {
				if (NULL != strstr(envp[count], sandbox_lib)) {
					my_env = (char **) envp;
					kill_env = 0;
					break;
				} else {
					int i = 0;
					const int max_envp_len =
							strlen(envp[count]) + strlen(sandbox_lib) + 1;

					/* Fail safe ... */
					if (max_envp_len > 4096) {
						fprintf(stderr, "sandbox:  max_envp_len too big!\n");
						errno = ENOMEM;
						return result;
					}

					/* Calculate envp size */
					my_env = (char **) envp;
					do
						env_len += 1;
					while (*my_env++);

					my_env = (char **) malloc((env_len + 2) * sizeof (char *));
					if (NULL == my_env) {
						errno = ENOMEM;
						return result;
					}
					/* Copy envp to my_env */
					do
						my_env[i] = envp[i];
					while (envp[i++]);

					/* Set tmp_str to envp[count] */
					strncpy(tmp_str, envp[count], max_envp_len - 1);

					/* LD_PRELOAD already have variables other than sandbox_lib,
					 * thus we have to add sandbox_lib seperated via a whitespace. */
					if (0 != strncmp(envp[count], "LD_PRELOAD=", max_envp_len - 1)) {
						strncat(tmp_str, " ", max_envp_len - strlen(tmp_str));
						strncat(tmp_str, sandbox_lib, max_envp_len - strlen(tmp_str));
					} else {
						strncat(tmp_str, sandbox_lib, max_envp_len - strlen(tmp_str));
					}

					/* Valid string? */
					tmp_str[max_envp_len] = '\0';

					/* Ok, replace my_env[count] with our version that contains
					 * sandbox_lib ... */
					my_env[count] = tmp_str;

					break;
				}
			}
			count++;
		}

		errno = old_errno;
		check_dlsym(execve);
		result = true_execve(filename, argv, my_env);
		old_errno = errno;

		if (my_env && kill_env) {
			free(my_env);
			my_env = NULL;
		}
	}

	errno = old_errno;

	return result;
}

/*
 * Internal Functions
 */

#if (GLIBC_MINOR == 1)

/* This hack is needed for glibc 2.1.1 (and others?)
 * (not really needed, but good example) */
extern int fclose(FILE *);
static int (*true_fclose) (FILE *) = NULL;
int
fclose(FILE * file)
{
	int result = -1;

	check_dlsym(fclose);
	result = true_fclose(file);

	return result;
}

#endif													/* GLIBC_MINOR == 1 */

static void
init_context(sbcontext_t * context)
{
	context->show_access_violation = 1;
	context->deny_prefixes = NULL;
	context->num_deny_prefixes = 0;
	context->read_prefixes = NULL;
	context->num_read_prefixes = 0;
	context->write_prefixes = NULL;
	context->num_write_prefixes = 0;
	context->predict_prefixes = NULL;
	context->num_predict_prefixes = 0;
	context->write_denied_prefixes = NULL;
	context->num_write_denied_prefixes = 0;
}

static int
is_sandbox_pid()
{
	int old_errno = errno;
	int result = 0;
	FILE *pids_stream = NULL;
	int pids_file = -1;
	int current_pid = 0;
	int tmp_pid = 0;

	init_wrappers();

	pids_stream = true_fopen(sandbox_pids_file, "r");

	if (NULL == pids_stream) {
		perror(">>> pids file fopen");
	} else {
		pids_file = fileno(pids_stream);

		if (pids_file < 0) {
			perror(">>> pids file fileno");
		} else {
			current_pid = getpid();

			while (EOF != fscanf(pids_stream, "%d\n", &tmp_pid)) {
				if (tmp_pid == current_pid) {
					result = 1;
					break;
				}
			}
		}
		if (EOF == fclose(pids_stream)) {
			perror(">>> pids file fclose");
		}
		pids_stream = NULL;
		pids_file = -1;
	}

	errno = old_errno;

	return result;
}

static void
clean_env_entries(char ***prefixes_array, int *prefixes_num)
{
	int old_errno = errno;
	int i = 0;

	if (NULL != *prefixes_array) {
		for (i = 0; i < *prefixes_num; i++) {
			if (NULL != (*prefixes_array)[i]) {
				free((*prefixes_array)[i]);
				(*prefixes_array)[i] = NULL;
			}
		}
		if (*prefixes_array)
			free(*prefixes_array);
		*prefixes_array = NULL;
		*prefixes_num = 0;
	}

	errno = old_errno;
}

static void
init_env_entries(char ***prefixes_array, int *prefixes_num, char *env, int warn)
{
	int old_errno = errno;
	char *prefixes_env = getenv(env);

	if (NULL == prefixes_env) {
		fprintf(stderr,
						"Sandbox error : the %s environmental variable should be defined.\n",
						env);
	} else {
		char *buffer = NULL;
		int prefixes_env_length = strlen(prefixes_env);
		int i = 0;
		int num_delimiters = 0;
		char *token = NULL;
		char *prefix = NULL;

		for (i = 0; i < prefixes_env_length; i++) {
			if (':' == prefixes_env[i]) {
				num_delimiters++;
			}
		}

		if (num_delimiters > 0) {
			*prefixes_array =
					(char **) malloc((num_delimiters + 1) * sizeof (char *));
			buffer = strndupa(prefixes_env, prefixes_env_length);

#ifdef REENTRANT_STRTOK
			token = strtok_r(buffer, ":", &buffer);
#else
			token = strtok(buffer, ":");
#endif

			while ((NULL != token) && (strlen(token) > 0)) {
				prefix = strndup(token, strlen(token));
				(*prefixes_array)[(*prefixes_num)++] = filter_path(prefix);

#ifdef REENTRANT_STRTOK
				token = strtok_r(NULL, ":", &buffer);
#else
				token = strtok(NULL, ":");
#endif

				if (prefix)
					free(prefix);
				prefix = NULL;
			}
		} else if (prefixes_env_length > 0) {
			(*prefixes_array) = (char **) malloc(sizeof (char *));

			(*prefixes_array)[(*prefixes_num)++] = filter_path(prefixes_env);
		}
	}

	errno = old_errno;
}

static char *
filter_path(const char *path)
{
	int old_errno = errno;
	char *filtered_path = (char *) malloc(SB_PATH_MAX * sizeof (char));

	canonicalize_ptr(path, filtered_path);

	errno = old_errno;

	return filtered_path;
}

static int
check_access(sbcontext_t * sbcontext, const char *func, const char *path)
{
	int old_errno = errno;
	int result = -1;
	int i = 0;
	char *filtered_path = filter_path(path);

	if ('/' != filtered_path[0]) {
		errno = old_errno;

		if (filtered_path)
			free(filtered_path);
		filtered_path = NULL;

		return 0;
	}

	if ((0 == strncmp(filtered_path, "/etc/ld.so.preload", 18))
			&& (is_sandbox_pid())) {
		result = 1;
	}

	if (-1 == result) {
		if (NULL != sbcontext->deny_prefixes) {
			for (i = 0; i < sbcontext->num_deny_prefixes; i++) {
				if (NULL != sbcontext->deny_prefixes[i]) {
					if (0 == strncmp(filtered_path,
													 sbcontext->
													 deny_prefixes[i],
													 strlen(sbcontext->deny_prefixes[i]))) {
						result = 0;
						break;
					}
				}
			}
		}

		if (-1 == result) {
			if ((NULL != sbcontext->read_prefixes) &&
					((0 == strncmp(func, "open_rd", 7)) ||
					 (0 == strncmp(func, "popen", 5)) ||
					 (0 == strncmp(func, "opendir", 7)) ||
					 (0 == strncmp(func, "system", 6)) ||
					 (0 == strncmp(func, "execl", 5)) ||
					 (0 == strncmp(func, "execlp", 6)) ||
					 (0 == strncmp(func, "execle", 6)) ||
					 (0 == strncmp(func, "execv", 5)) ||
					 (0 == strncmp(func, "execvp", 6)) ||
					 (0 == strncmp(func, "execve", 6))
					)
					) {
				for (i = 0; i < sbcontext->num_read_prefixes; i++) {
					if (NULL != sbcontext->read_prefixes[i]) {
						if (0 == strncmp(filtered_path,
														 sbcontext->
														 read_prefixes[i],
														 strlen(sbcontext->read_prefixes[i]))) {
							result = 1;
							break;
						}
					}
				}
			} else if ((NULL != sbcontext->write_prefixes) &&
								 ((0 == strncmp(func, "open_wr", 7)) ||
									(0 == strncmp(func, "creat", 5)) ||
									(0 == strncmp(func, "creat64", 7)) ||
									(0 == strncmp(func, "mkdir", 5)) ||
									(0 == strncmp(func, "mknod", 5)) ||
									(0 == strncmp(func, "mkfifo", 6)) ||
									(0 == strncmp(func, "link", 4)) ||
									(0 == strncmp(func, "symlink", 7)) ||
									(0 == strncmp(func, "rename", 6)) ||
									(0 == strncmp(func, "utime", 5)) ||
									(0 == strncmp(func, "utimes", 6)) ||
									(0 == strncmp(func, "unlink", 6)) ||
									(0 == strncmp(func, "rmdir", 5)) ||
									(0 == strncmp(func, "chown", 5)) ||
									(0 == strncmp(func, "lchown", 6)) ||
									(0 == strncmp(func, "chmod", 5)) ||
									(0 == strncmp(func, "truncate", 8)) ||
									(0 == strncmp(func, "ftruncate", 9)) ||
									(0 == strncmp(func, "truncate64", 10)) ||
									(0 == strncmp(func, "ftruncate64", 11))
								 )
					) {
				struct stat tmp_stat;

				for (i = 0; i < sbcontext->num_write_denied_prefixes; i++) {
					if (NULL != sbcontext->write_denied_prefixes[i]) {
						if (0 ==
								strncmp(filtered_path,
												sbcontext->
												write_denied_prefixes
												[i], strlen(sbcontext->write_denied_prefixes[i]))) {
							result = 0;
							break;
						}
					}
				}

				if (-1 == result) {
					for (i = 0; i < sbcontext->num_write_prefixes; i++) {
						if (NULL != sbcontext->write_prefixes[i]) {
							if (0 ==
									strncmp
									(filtered_path,
									 sbcontext->write_prefixes[i],
									 strlen(sbcontext->write_prefixes[i]))) {
								result = 1;
								break;
							}
						}
					}

					if (-1 == result) {
						/* hack to prevent mkdir of existing dirs to show errors */
						if (0 == strncmp(func, "mkdir", 5)) {
							if (0 == stat(filtered_path, &tmp_stat)) {
								sbcontext->show_access_violation = 0;
								result = 0;
							}
						}

						if (-1 == result) {
							for (i = 0; i < sbcontext->num_predict_prefixes; i++) {
								if (NULL != sbcontext->predict_prefixes[i]) {
									if (0 ==
											strncmp
											(filtered_path,
											 sbcontext->
											 predict_prefixes[i],
											 strlen(sbcontext->predict_prefixes[i]))) {
										sbcontext->show_access_violation = 0;
										result = 0;
										break;
									}
								}
							}
						}
					}
				}
			}
		}
	}

	if (-1 == result) {
		result = 0;
	}

	if (filtered_path)
		free(filtered_path);
	filtered_path = NULL;

	errno = old_errno;

	return result;
}

static int
check_syscall(sbcontext_t * sbcontext, const char *func, const char *file)
{
	int old_errno = errno;
	int result = 1;
	struct stat log_stat;
	char *log_path = NULL;
	char *absolute_path = NULL;
	char *tmp_buffer = NULL;
	int log_file = 0;
	struct stat debug_log_stat;
	char *debug_log_env = NULL;
	char *debug_log_path = NULL;
	int debug_log_file = 0;
	char buffer[512];
	char *dpath = NULL;

	init_wrappers();

	if ('/' == file[0]) {
		absolute_path = (char *) malloc((strlen(file) + 1) * sizeof (char));
		sprintf(absolute_path, "%s", file);
	} else {
		tmp_buffer = (char *) malloc(SB_PATH_MAX * sizeof (char));
		egetcwd(tmp_buffer, SB_PATH_MAX - 1);
		absolute_path = (char *) malloc((strlen(tmp_buffer) + 1 + strlen(file) + 1) * sizeof (char));
		sprintf(absolute_path, "%s/%s", tmp_buffer, file);
		if (tmp_buffer)
			free(tmp_buffer);
		tmp_buffer = NULL;
	}

	log_path = getenv("SANDBOX_LOG");
	debug_log_env = getenv("SANDBOX_DEBUG");
	debug_log_path = getenv("SANDBOX_DEBUG_LOG");

	if (((NULL == log_path) ||
			 (0 != strncmp(absolute_path, log_path, strlen(log_path)))) &&
			((NULL == debug_log_env) ||
			 (NULL == debug_log_path) ||
			 (0 != strncmp(absolute_path, debug_log_path, strlen(debug_log_path))))
			&& (0 == check_access(sbcontext, func, absolute_path))
			) {
		if (1 == sbcontext->show_access_violation) {
			fprintf(stderr,
							"\e[31;01mACCESS DENIED\033[0m  %s:%*s%s\n",
							func, (int) (10 - strlen(func)), "", absolute_path);

			if (NULL != log_path) {
				sprintf(buffer, "%s:%*s%s\n", func, (int) (10 - strlen(func)), "",
								absolute_path);
				// log_path somehow gets corrupted.  figuring out why would be good.
				dpath = strdup(log_path);
				if ((0 == lstat(log_path, &log_stat))
						&& (0 == S_ISREG(log_stat.st_mode))
						) {
					fprintf(stderr,
						"\e[31;01mSECURITY BREACH\033[0m  %s already exists and is not a regular file.\n",
						dpath);
				} else if (0 == check_access(sbcontext, "open_wr", dpath)) {
					unsetenv("SANDBOX_LOG");
					fprintf(stderr,
						"\e[31;01mSECURITY BREACH\033[0m SANDBOX_LOG %s isn't allowed via SANDBOX_WRITE\n",
						dpath);
				} else {
					log_file = true_open(dpath,
						 O_APPEND | O_WRONLY
						 | O_CREAT,
						 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
					if (log_file >= 0) {
						write(log_file, buffer, strlen(buffer));
						close(log_file);
					}
				}
				free(dpath);
			}
		}

		result = 0;
	} else if (NULL != debug_log_env) {
		if (NULL != debug_log_path) {
			if (0 != strncmp(absolute_path, debug_log_path, strlen(debug_log_path))) {
				sprintf(buffer, "%s:%*s%s\n", func, (int) (10 - strlen(func)), "",
								absolute_path);
				//debug_log_path somehow gets corupted, same thing as log_path above.
				dpath = strdup(debug_log_path);
				if ((0 == lstat(debug_log_path, &debug_log_stat))
						&& (0 == S_ISREG(debug_log_stat.st_mode))
						) {
					fprintf(stderr,
						"\e[31;01mSECURITY BREACH\033[0m  %s already exists and is not a regular file.\n",
						debug_log_path);
				} else if (0 == check_access(sbcontext, "open_wr", dpath)) {
					unsetenv("SANDBOX_DEBUG");
					unsetenv("SANDBOX_DEBUG_LOG");
					fprintf(stderr,
						"\e[31;01mSECURITY BREACH\033[0m  SANDBOX_DEBUG_LOG %s isn't allowed by SANDBOX_WRITE.\n",
						dpath);
				} else {					
					debug_log_file =
						true_open(dpath,
							O_APPEND | O_WRONLY |
							O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
					if (debug_log_file >= 0) {
						write(debug_log_file, buffer, strlen(buffer));
						close(debug_log_file);
					}
				}
				free(dpath);
			}
		} else {
			fprintf(stderr,
				"\e[32;01mACCESS ALLOWED\033[0m %s:%*s%s\n",
				func, (int) (10 - strlen(func)), "", absolute_path);
		}
	}

	if (absolute_path)
		free(absolute_path);
	absolute_path = NULL;

	errno = old_errno;

	return result;
}

static int
is_sandbox_on()
{
	int old_errno = errno;

	/* $SANDBOX_ACTIVE is an env variable that should ONLY
	 * be used internal by sandbox.c and libsanbox.c.  External
	 * sources should NEVER set it, else the sandbox is enabled
	 * in some cases when run in parallel with another sandbox,
	 * but not even in the sandbox shell.
	 *
	 * Azarah (3 Aug 2002)
	 */
	if ((NULL != getenv("SANDBOX_ON")) &&
			(0 == strncmp(getenv("SANDBOX_ON"), "1", 1)) &&
			(NULL != getenv("SANDBOX_ACTIVE")) &&
			(0 == strncmp(getenv("SANDBOX_ACTIVE"), "armedandready", 13))
			) {
		errno = old_errno;

		return 1;
	} else {
		errno = old_errno;

		return 0;
	}
}

static int
before_syscall(const char *func, const char *file)
{
	int old_errno = errno;
	int result = 1;
	sbcontext_t sbcontext;

	if (!strlen(file)) {
		/* The file/directory does not exist */
		errno = ENOENT;
		return 0;
	}

	init_context(&sbcontext);

	init_env_entries(&(sbcontext.deny_prefixes),
									 &(sbcontext.num_deny_prefixes), "SANDBOX_DENY", 1);
	init_env_entries(&(sbcontext.read_prefixes),
									 &(sbcontext.num_read_prefixes), "SANDBOX_READ", 1);
	init_env_entries(&(sbcontext.write_prefixes),
									 &(sbcontext.num_write_prefixes), "SANDBOX_WRITE", 1);
	init_env_entries(&(sbcontext.predict_prefixes),
									 &(sbcontext.num_predict_prefixes), "SANDBOX_PREDICT", 1);

	result = check_syscall(&sbcontext, func, file);

	clean_env_entries(&(sbcontext.deny_prefixes), &(sbcontext.num_deny_prefixes));
	clean_env_entries(&(sbcontext.read_prefixes), &(sbcontext.num_read_prefixes));
	clean_env_entries(&(sbcontext.write_prefixes),
										&(sbcontext.num_write_prefixes));
	clean_env_entries(&(sbcontext.predict_prefixes),
										&(sbcontext.num_predict_prefixes));

	errno = old_errno;

	if (0 == result) {
		errno = EACCES;
	}

	return result;
}

static int
before_syscall_open_int(const char *func, const char *file, int flags)
{
	if ((flags & O_WRONLY) || (flags & O_RDWR)) {
		return before_syscall("open_wr", file);
	} else {
		return before_syscall("open_rd", file);
	}
}

static int
before_syscall_open_char(const char *func, const char *file, const char *mode)
{
	if (*mode == 'r' && ((strcmp(mode, "r") == 0) ||
			     /* The strspn accept args are known non-writable modifiers */
			     (strlen(++mode) == strspn(mode, "xbtmc")))) {
		return before_syscall("open_rd", file);
	} else {
		return before_syscall("open_wr", file);
	}
}

#include "getcwd.c"
#include "canonicalize.c"

// vim:expandtab noai:cindent ai