/[path-sandbox]/trunk/src/sandbox.c
Gentoo

Contents of /trunk/src/sandbox.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 99 - (show annotations) (download) (as text)
Fri May 13 13:30:51 2005 UTC (9 years, 2 months ago) by azarah
Original Path: trunk/sandbox.c
File MIME type: text/x-csrc
File size: 18192 byte(s)
Modify get_sandbox_pids_file(), get_sandbox_log() and get_sandbox_debug_log()
to use TMPDIR if present in environment.

1 /*
2 ** Path sandbox for the gentoo linux portage package system, initially
3 ** based on the ROCK Linux Wrapper for getting a list of created files
4 **
5 ** to integrate with bash, bash should have been built like this
6 **
7 ** ./configure --prefix=<prefix> --host=<host> --without-gnu-malloc
8 **
9 ** it's very important that the --enable-static-link option is NOT specified
10 **
11 ** Copyright (C) 2001 Geert Bevin, Uwyn, http://www.uwyn.com
12 ** Distributed under the terms of the GNU General Public License, v2 or later
13 ** Author : Geert Bevin <gbevin@uwyn.com>
14 ** $Header$
15 */
16
17 /* #define _GNU_SOURCE */
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <limits.h>
25 #include <string.h>
26 #include <sys/file.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <sys/resource.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include "sandbox.h"
35
36 static char tmp_dir[SB_PATH_MAX];
37
38 static int cleaned_up = 0;
39 static int print_debug = 0;
40 static int stop_called = 0;
41
42 /* Read pids file, and load active pids into an array. Return number of pids in array */
43 int load_active_pids(int fd, int **pids)
44 {
45 char *data = NULL;
46 char *ptr = NULL, *ptr2 = NULL;
47 int my_pid;
48 int num_pids = 0;
49 long len;
50
51 pids[0] = NULL;
52
53 len = file_length(fd);
54
55 /* Allocate and zero datablock to read pids file */
56 data = (char *)malloc((len + 1) * sizeof(char));
57 memset(data, 0, len + 1);
58
59 /* Start at beginning of file */
60 lseek(fd, 0L, SEEK_SET);
61
62 /* read entire file into a buffer */
63 read(fd, data, len);
64
65 ptr = data;
66
67 /* Loop and read all pids */
68 while (1) {
69 /* Find new line */
70 ptr2 = strchr(ptr, '\n');
71 if (ptr2 == NULL)
72 break; /* No more PIDs */
73
74 /* Clear the \n. And ptr should have a null-terminated decimal string */
75 ptr2[0] = 0;
76
77 my_pid = atoi(ptr);
78
79 /* If the PID is still alive, add it to our array */
80 if ((0 != my_pid) && (0 == kill(my_pid, 0))) {
81 pids[0] = (int *)realloc(pids[0], (num_pids + 1) * sizeof(int));
82 pids[0][num_pids] = my_pid;
83 num_pids++;
84 }
85
86 /* Put ptr past the NULL we just wrote */
87 ptr = ptr2 + 1;
88 }
89
90 if (data)
91 free(data);
92 data = NULL;
93
94 return num_pids;
95 }
96
97 void cleanup()
98 {
99 int i = 0;
100 int success = 1;
101 int pids_file = -1, num_of_pids = 0;
102 int *pids_array = NULL;
103 char pid_string[SB_BUF_LEN];
104 char *sandbox_pids_file;
105
106 /* Generate sandbox pids-file path */
107 sandbox_pids_file = get_sandbox_pids_file(tmp_dir);
108
109 /* Remove this sandbox's bash pid from the global pids
110 * file if we have not already done so */
111 if (0 == cleaned_up) {
112 cleaned_up = 1;
113 success = 1;
114
115 if (print_debug)
116 printf("Cleaning up pids file.\n");
117
118 /* Stat the PIDs file, make sure it exists and is a regular file */
119 if (file_exist(sandbox_pids_file, 1) <= 0) {
120 fprintf(stderr, ">>> pids file is not a regular file\n");
121 success = 0;
122 /* We should really not fail if the pidsfile is missing here, but
123 * rather just exit cleanly, as there is still some cleanup to do */
124 return;
125 }
126
127 pids_file = file_open(sandbox_pids_file, "r+", 1, 0664, "portage");
128 if (-1 == pids_file) {
129 success = 0;
130 /* Nothing more to do here */
131 return;
132 }
133
134 /* Load "still active" pids into an array */
135 num_of_pids = load_active_pids(pids_file, &pids_array);
136 //printf("pids: %d\r\n", num_of_pids);
137
138
139 file_truncate(pids_file);
140
141 /* if pids are still running, write only the running pids back to the file */
142 if (num_of_pids > 1) {
143 for (i = 0; i < num_of_pids; i++) {
144 if (pids_array[i] != getpid()) {
145 sprintf(pid_string, "%d\n", pids_array[i]);
146
147 if (write(pids_file, pid_string, strlen(pid_string)) != strlen(pid_string)) {
148 perror(">>> pids file write");
149 success = 0;
150 break;
151 }
152 }
153 }
154
155 file_close(pids_file);
156 pids_file = -1;
157 } else {
158
159 file_close(pids_file);
160 pids_file = -1;
161
162 /* remove the pidsfile, as this was the last sandbox */
163 unlink(sandbox_pids_file);
164 }
165
166 if (pids_array != NULL)
167 free(pids_array);
168 pids_array = NULL;
169 }
170
171 free(sandbox_pids_file);
172 if (0 == success)
173 return;
174 }
175
176 int print_sandbox_log(char *sandbox_log)
177 {
178 int sandbox_log_file = -1;
179 char *beep_count_env = NULL;
180 int i, color, beep_count = 0;
181 long len = 0;
182 char *buffer = NULL;
183
184 sandbox_log_file = file_open(sandbox_log, "r", 1, 0664, "portage");
185 if (-1 == sandbox_log_file)
186 return 0;
187
188 len = file_length(sandbox_log_file);
189 buffer = (char *)malloc((len + 1) * sizeof(char));
190 memset(buffer, 0, len + 1);
191 read(sandbox_log_file, buffer, len);
192 file_close(sandbox_log_file);
193
194 color = ((getenv("NOCOLOR") != NULL) ? 0 : 1);
195
196 if (color)
197 printf("\e[31;01m");
198 printf("--------------------------- ACCESS VIOLATION SUMMARY ---------------------------");
199 if (color)
200 printf("\033[0m");
201 if (color)
202 printf("\e[31;01m");
203 printf("\nLOG FILE = \"%s\"", sandbox_log);
204 if (color)
205 printf("\033[0m");
206 printf("\n\n");
207 printf("%s", buffer);
208 if (buffer)
209 free(buffer);
210 buffer = NULL;
211 printf("\e[31;01m--------------------------------------------------------------------------------\033[0m\n");
212
213 beep_count_env = getenv(ENV_SANDBOX_BEEP);
214 if (beep_count_env)
215 beep_count = atoi(beep_count_env);
216 else
217 beep_count = DEFAULT_BEEP_COUNT;
218
219 for (i = 0; i < beep_count; i++) {
220 fputc('\a', stderr);
221 if (i < beep_count - 1)
222 sleep(1);
223 }
224 return 1;
225 }
226
227 void stop(int signum)
228 {
229 if (stop_called == 0) {
230 stop_called = 1;
231 printf("Caught signal %d in pid %d\r\n", signum, getpid());
232 cleanup();
233 } else {
234 fprintf(stderr, "Pid %d alreadly caught signal and is still cleaning up\n", getpid());
235 }
236 }
237
238 void get_sandbox_write_envvar(char *buf, char *home_dir, char *portage_tmp_dir, char *var_tmp_dir, char *tmp_dir)
239 {
240 /* bzero out entire buffer then append trailing 0 */
241 memset(buf, 0, SB_BUF_LEN);
242
243 /* these could go into make.globals later on */
244 snprintf(buf, SB_BUF_LEN,
245 "%s:%s/.gconfd/lock:%s/.bash_history:%s:%s:%s:%s",
246 "/dev/zero:/dev/fd/:/dev/null:/dev/pts/:"
247 "/dev/vc/:/dev/pty:/dev/tty:"
248 "/dev/shm/ngpt:/var/log/scrollkeeper.log:"
249 "/usr/tmp/conftest:/usr/lib/conftest:"
250 "/usr/lib32/conftest:/usr/lib64/conftest:"
251 "/usr/tmp/cf:/usr/lib/cf:/usr/lib32/cf:/usr/lib64/cf",
252 home_dir, home_dir,
253 (NULL != portage_tmp_dir) ? portage_tmp_dir : tmp_dir,
254 tmp_dir, var_tmp_dir, "/tmp/:/var/tmp/");
255 }
256
257 void get_sandbox_predict_envvar(char *buf, char *home_dir)
258 {
259 /* bzero out entire buffer then append trailing 0 */
260 memset(buf, 0, SB_BUF_LEN);
261
262 /* these should go into make.globals later on */
263 snprintf(buf, SB_BUF_LEN, "%s/.:"
264 "/usr/lib/python2.0/:"
265 "/usr/lib/python2.1/:"
266 "/usr/lib/python2.2/:"
267 "/usr/lib/python2.3/:"
268 "/usr/lib/python2.4/:"
269 "/usr/lib/python2.5/:"
270 "/usr/lib/python3.0/:",
271 home_dir);
272 }
273
274 int sandbox_setenv(char **env, char *name, char *val) {
275 char **tmp_env = env;
276 char *tmp_string = NULL;
277
278 while (NULL != *tmp_env)
279 tmp_env++;
280
281 /* strlen(name) + strlen(val) + '=' + '\0' */
282 /* FIXME: Should probably free this at some stage - more neatness than
283 * a real leak that will cause issues. */
284 tmp_string = calloc(strlen(name) + strlen(val) + 2, sizeof(char *));
285 if (NULL == tmp_string) {
286 perror(">>> out of memory (sandbox_setenv)");
287 exit(1);
288 }
289
290 snprintf(tmp_string, strlen(name) + strlen(val) + 2, "%s=%s",
291 name, val);
292 *tmp_env = tmp_string;
293
294 return 0;
295 }
296
297 /* We setup the environment child side only to prevent issues with
298 * setting LD_PRELOAD parent side */
299 char **sandbox_setup_environ(char *sandbox_dir, char *sandbox_lib, char *sandbox_rc, char *sandbox_log,
300 char *sandbox_debug_log, char *sandbox_write_envvar, char *sandbox_predict_envvar)
301 {
302 int env_size = 0;
303
304 char **new_environ;
305 char **env_ptr = environ;
306 char *ld_preload_envvar = NULL;
307
308 /* Unset these, as its easier than replacing when setting up our
309 * new environment below */
310 unsetenv(ENV_SANDBOX_DIR);
311 unsetenv(ENV_SANDBOX_LIB);
312 unsetenv(ENV_SANDBOX_BASHRC);
313 unsetenv(ENV_SANDBOX_LOG);
314 unsetenv(ENV_SANDBOX_DEBUG_LOG);
315
316 if (NULL != getenv("LD_PRELOAD")) {
317 /* FIXME: Should probably free this at some stage - more neatness
318 * than a real leak that will cause issues. */
319 ld_preload_envvar = malloc(strlen(getenv("LD_PRELOAD")) +
320 strlen(sandbox_lib) + 2);
321 if (NULL == ld_preload_envvar)
322 return NULL;
323 strncpy(ld_preload_envvar, sandbox_lib, strlen(sandbox_lib));
324 strncat(ld_preload_envvar, " ", 1);
325 strncat(ld_preload_envvar, getenv("LD_PRELOAD"),
326 strlen(getenv("LD_PRELOAD")));
327 } else {
328 /* FIXME: Should probably free this at some stage - more neatness
329 * than a real leak that will cause issues. */
330 ld_preload_envvar = strndup(sandbox_lib, strlen(sandbox_lib));
331 if (NULL == ld_preload_envvar)
332 return NULL;
333 }
334 unsetenv("LD_PRELOAD");
335
336 while (NULL != *env_ptr) {
337 env_size++;
338 env_ptr++;
339 }
340
341 /* FIXME: Should probably free this at some stage - more neatness than
342 * a real leak that will cause issues. */
343 new_environ = calloc((env_size + 15 + 1) * sizeof(char *), sizeof(char *));
344 if (NULL == new_environ)
345 return NULL;
346
347 /* First add our new variables to the beginning - this is due to some
348 * weirdness that I cannot remember */
349 sandbox_setenv(new_environ, ENV_SANDBOX_DIR, sandbox_dir);
350 sandbox_setenv(new_environ, ENV_SANDBOX_LIB, sandbox_lib);
351 sandbox_setenv(new_environ, ENV_SANDBOX_BASHRC, sandbox_rc);
352 sandbox_setenv(new_environ, ENV_SANDBOX_LOG, sandbox_log);
353 sandbox_setenv(new_environ, ENV_SANDBOX_DEBUG_LOG, sandbox_debug_log);
354 sandbox_setenv(new_environ, "LD_PRELOAD", ld_preload_envvar);
355
356 if (!getenv(ENV_SANDBOX_DENY))
357 sandbox_setenv(new_environ, ENV_SANDBOX_DENY, LD_PRELOAD_FILE);
358
359 if (!getenv(ENV_SANDBOX_READ))
360 sandbox_setenv(new_environ, ENV_SANDBOX_READ, "/");
361
362 if (!getenv(ENV_SANDBOX_WRITE))
363 sandbox_setenv(new_environ, ENV_SANDBOX_WRITE, sandbox_write_envvar);
364
365 if (!getenv(ENV_SANDBOX_PREDICT))
366 sandbox_setenv(new_environ, ENV_SANDBOX_PREDICT, sandbox_predict_envvar);
367
368 /* This one should NEVER be set in ebuilds, as it is the one
369 * private thing libsandbox.so use to test if the sandbox
370 * should be active for this pid, or not.
371 *
372 * azarah (3 Aug 2002)
373 */
374
375 sandbox_setenv(new_environ, "SANDBOX_ACTIVE", "armedandready");
376
377 env_size = 0;
378 while (NULL != new_environ[env_size])
379 env_size++;
380
381 /* Now add the rest */
382 env_ptr = environ;
383 while (NULL != *env_ptr) {
384 new_environ[env_size + (env_ptr - environ)] = *env_ptr;
385 env_ptr++;
386 }
387
388 return new_environ;
389 }
390
391 int spawn_shell(char *argv_bash[], char *env[])
392 {
393 int pid;
394 int status = 0;
395 int ret = 0;
396
397 pid = fork();
398
399 /* Child's process */
400 if (0 == pid) {
401 execve(argv_bash[0], argv_bash, env);
402 return 0;
403 } else if (pid < 0) {
404 return 0;
405 }
406 ret = waitpid(pid, &status, 0);
407 if ((-1 == ret) || (status > 0))
408 return 0;
409
410 return 1;
411 }
412
413 int main(int argc, char **argv)
414 {
415 int ret = 0, i = 0, success = 1;
416 int sandbox_log_presence = 0;
417 int pids_file = -1;
418 long len;
419
420 int *pids_array = NULL;
421 int num_of_pids = 0;
422
423 // char run_arg[255];
424 char **sandbox_environ;
425 char sandbox_log[SB_PATH_MAX];
426 char sandbox_debug_log[SB_PATH_MAX];
427 char sandbox_dir[SB_PATH_MAX];
428 char sandbox_lib[SB_PATH_MAX];
429 char sandbox_rc[SB_PATH_MAX];
430 char *sandbox_pids_file;
431 char portage_tmp_dir[SB_PATH_MAX];
432 char var_tmp_dir[SB_PATH_MAX];
433 char sandbox_write_envvar[SB_BUF_LEN];
434 char sandbox_predict_envvar[SB_BUF_LEN];
435 char pid_string[SB_BUF_LEN];
436 char **argv_bash = NULL;
437
438 char *run_str = "-c";
439 char *home_dir = NULL;
440 char *tmp_string = NULL;
441
442 /* Only print info if called with no arguments .... */
443 if (argc < 2)
444 print_debug = 1;
445
446 if (print_debug)
447 printf("========================== Gentoo linux path sandbox ===========================\n");
448
449 /* check if a sandbox is already running */
450 if (NULL != getenv(ENV_SANDBOX_ON)) {
451 fprintf(stderr, "Not launching a new sandbox instance\n");
452 fprintf(stderr, "Another one is already running in this process hierarchy.\n");
453 exit(1);
454 } else {
455
456 /* determine the location of all the sandbox support files */
457 if (print_debug)
458 printf("Detection of the support files.\n");
459
460 if (NULL == realpath(getenv(ENV_PORTAGE_TMPDIR) ? getenv(ENV_PORTAGE_TMPDIR)
461 : PORTAGE_TMPDIR,
462 portage_tmp_dir)) {
463 perror(">>> get portage_tmp_dir");
464 exit(1);
465 }
466 if (NULL == realpath(VAR_TMPDIR, var_tmp_dir)) {
467 perror(">>> get var_tmp_dir");
468 exit(1);
469 }
470 if (NULL == realpath(getenv(ENV_TMPDIR) ? getenv(ENV_TMPDIR)
471 : TMPDIR,
472 tmp_dir)) {
473 perror(">>> get tmp_dir");
474 exit(1);
475 }
476
477 /* Generate base sandbox path */
478 snprintf(sandbox_dir, SB_PATH_MAX, "%s/",
479 get_sandbox_path(argv[0]));
480
481 /* Generate sandbox lib path */
482 snprintf(sandbox_lib, SB_PATH_MAX, "%s",
483 get_sandbox_lib(sandbox_dir));
484
485 /* Generate sandbox pids-file path */
486 sandbox_pids_file = get_sandbox_pids_file(tmp_dir);
487
488 /* Generate sandbox bashrc path */
489 snprintf(sandbox_rc, SB_PATH_MAX, "%s",
490 get_sandbox_rc(sandbox_dir));
491
492 /* verify the existance of required files */
493 if (print_debug)
494 printf("Verification of the required files.\n");
495
496 #ifndef SB_HAVE_64BIT_ARCH
497 if (file_exist(sandbox_lib, 0) <= 0) {
498 fprintf(stderr, "Could not open the sandbox library at '%s'.\n", sandbox_lib);
499 return -1;
500 }
501 #endif
502 if (file_exist(sandbox_rc, 0) <= 0) {
503 fprintf(stderr, "Could not open the sandbox rc file at '%s'.\n", sandbox_rc);
504 return -1;
505 }
506
507 /* set up the required environment variables */
508 if (print_debug)
509 printf("Setting up the required environment variables.\n");
510
511 home_dir = getenv("HOME");
512 if (!home_dir) {
513 home_dir = "/tmp";
514 setenv("HOME", home_dir, 1);
515 }
516
517 /* Generate sandbox log full path */
518 snprintf(sandbox_log, SB_PATH_MAX, "%s",
519 get_sandbox_log(tmp_dir));
520
521 /* Generate sandbox debug log full path */
522 snprintf(sandbox_debug_log, SB_PATH_MAX, "%s",
523 get_sandbox_debug_log(tmp_dir));
524
525 /* This one should not be child only, as we check above to see
526 * if we are already running (check sandbox_setup_environ).
527 * This needs to be set before calling sandbox_setup_environ(),
528 * else its not set for the child */
529 setenv(ENV_SANDBOX_ON, "1", 0);
530
531 /* Setup the child environment stuff */
532 get_sandbox_write_envvar(sandbox_write_envvar, home_dir,
533 portage_tmp_dir, var_tmp_dir, tmp_dir);
534 get_sandbox_predict_envvar(sandbox_predict_envvar, home_dir);
535 sandbox_environ = sandbox_setup_environ(sandbox_dir, sandbox_lib,
536 sandbox_rc, sandbox_log, sandbox_debug_log,
537 sandbox_write_envvar, sandbox_predict_envvar);
538 if (NULL == sandbox_environ) {
539 perror(">>> out of memory (environ)");
540 exit(1);
541 }
542
543 /* if the portage temp dir was present, cd into it */
544 if (NULL != portage_tmp_dir)
545 chdir(portage_tmp_dir);
546
547 argv_bash = (char **)malloc(6 * sizeof(char *));
548 argv_bash[0] = strdup("/bin/bash");
549 argv_bash[1] = strdup("-rcfile");
550 argv_bash[2] = strdup(sandbox_rc);
551
552 if (argc < 2)
553 argv_bash[3] = NULL;
554 else
555 argv_bash[3] = strdup(run_str); /* "-c" */
556
557 argv_bash[4] = NULL; /* strdup(run_arg); */
558 argv_bash[5] = NULL;
559
560 if (argc >= 2) {
561 for (i = 1; i < argc; i++) {
562 if (NULL == argv_bash[4])
563 len = 0;
564 else
565 len = strlen(argv_bash[4]);
566
567 argv_bash[4] = (char *)realloc(argv_bash[4],
568 (len + strlen(argv[i]) + 2) * sizeof(char));
569
570 if (0 == len)
571 argv_bash[4][0] = 0;
572 if (1 != i)
573 strcat(argv_bash[4], " ");
574
575 strcat(argv_bash[4], argv[i]);
576 }
577 }
578
579 /* set up the required signal handlers */
580 signal(SIGHUP, &stop);
581 signal(SIGINT, &stop);
582 signal(SIGQUIT, &stop);
583 signal(SIGTERM, &stop);
584
585 /* Load our PID into PIDs file */
586 success = 1;
587 if (file_exist(sandbox_pids_file, 1) < 0) {
588 success = 0;
589 fprintf(stderr, ">>> %s is not a regular file\n", sandbox_pids_file);
590 } else {
591 pids_file = file_open(sandbox_pids_file, "r+", 1, 0664, "portage");
592 if (-1 == pids_file)
593 success = 0;
594 }
595 if (1 == success) {
596 /* Grab still active pids */
597 num_of_pids = load_active_pids(pids_file, &pids_array);
598
599 /* Zero out file */
600 file_truncate(pids_file);
601
602 /* Output active pids, and append our pid */
603 for (i = 0; i < num_of_pids + 1; i++) {
604 /* Time for our entry */
605 if (i == num_of_pids)
606 sprintf(pid_string, "%d\n", getpid());
607 else
608 sprintf(pid_string, "%d\n", pids_array[i]);
609
610 if (write(pids_file, pid_string, strlen(pid_string)) != strlen(pid_string)) {
611 perror(">>> pids file write");
612 success = 0;
613 break;
614 }
615 }
616 /* Clean pids_array */
617 if (pids_array)
618 free(pids_array);
619 pids_array = NULL;
620 num_of_pids = 0;
621
622 /* We're done with the pids file */
623 file_close(pids_file);
624 }
625
626 /* Something went wrong, bail out */
627 if (0 == success) {
628 perror(">>> pids file write");
629 exit(1);
630 }
631
632 /* STARTING PROTECTED ENVIRONMENT */
633 if (print_debug) {
634 printf("The protected environment has been started.\n");
635 printf("--------------------------------------------------------------------------------\n");
636 }
637
638 if (print_debug)
639 printf("Shell being started in forked process.\n");
640
641 /* Start Bash */
642 if (!spawn_shell(argv_bash, sandbox_environ)) {
643 if (print_debug)
644 fprintf(stderr, ">>> shell process failed to spawn\n");
645 success = 0;
646 }
647
648 /* Free bash stuff */
649 for (i = 0; i < 6; i++) {
650 if (argv_bash[i])
651 free(argv_bash[i]);
652 argv_bash[i] = NULL;
653 }
654 if (argv_bash)
655 free(argv_bash);
656 argv_bash = NULL;
657
658 if (print_debug)
659 printf("Cleaning up sandbox process\n");
660
661 cleanup();
662
663 if (print_debug) {
664 printf("========================== Gentoo linux path sandbox ===========================\n");
665 printf("The protected environment has been shut down.\n");
666 }
667
668 if (file_exist(sandbox_log, 0)) {
669 sandbox_log_presence = 1;
670 success = 1;
671 if (!print_sandbox_log(sandbox_log))
672 success = 0;
673
674 #if 0
675 if (!success)
676 exit(1);
677 #endif
678
679 } else if (print_debug) {
680 printf("--------------------------------------------------------------------------------\n");
681 }
682
683 free(sandbox_pids_file);
684
685 if ((sandbox_log_presence) || (!success))
686 return 1;
687 else
688 return 0;
689 }
690 }
691
692 // vim:noexpandtab noai:cindent ai

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

  ViewVC Help
Powered by ViewVC 1.1.20