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

Contents of /trunk/src/sandbox.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 89 - (show annotations) (download) (as text)
Wed May 11 23:23:07 2005 UTC (9 years, 4 months ago) by azarah
Original Path: trunk/sandbox.c
File MIME type: text/x-csrc
File size: 17890 byte(s)
Rewrite environment stuff to only be set when execve'ing the child process
to try and avoid issues like bug #91541 that causes sandbox to crash if
we set LD_PRELOAD sandbox side already.

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