jail.c revision 112705
1/* 2 * ---------------------------------------------------------------------------- 3 * "THE BEER-WARE LICENSE" (Revision 42): 4 * <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you 5 * can do whatever you want with this stuff. If we meet some day, and you think 6 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp 7 * ---------------------------------------------------------------------------- 8 * 9 * $FreeBSD: head/usr.sbin/jail/jail.c 112705 2003-03-27 12:16:58Z maxim $ 10 * 11 */ 12 13#include <sys/param.h> 14#include <sys/jail.h> 15 16#include <netinet/in.h> 17#include <arpa/inet.h> 18 19#include <err.h> 20#include <grp.h> 21#include <login_cap.h> 22#include <pwd.h> 23#include <stdio.h> 24#include <stdlib.h> 25#include <string.h> 26#include <unistd.h> 27 28static void usage(void); 29 30int 31main(int argc, char **argv) 32{ 33 login_cap_t *lcap; 34 struct jail j; 35 struct passwd *pwd; 36 struct in_addr in; 37 int ch, groups[NGROUPS], i, ngroups; 38 char *username; 39 40 username = NULL; 41 42 while ((ch = getopt(argc, argv, "u:")) != -1) 43 switch (ch) { 44 case 'u': 45 username = optarg; 46 break; 47 default: 48 usage(); 49 break; 50 } 51 argc -= optind; 52 argv += optind; 53 if (argc < 4) 54 usage(); 55 56 if (username != NULL) { 57 pwd = getpwnam(username); 58 if (pwd == NULL) 59 err(1, "getpwnam %s", username); 60 lcap = login_getpwclass(pwd); 61 if (lcap == NULL) 62 err(1, "getpwclass failed", username); 63 ngroups = NGROUPS; 64 i = getgrouplist(username, pwd->pw_gid, groups, &ngroups); 65 if (i) 66 err(1, "getgrouplist %s", username); 67 } 68 i = chdir(argv[0]); 69 if (i) 70 err(1, "chdir %s", argv[0]); 71 memset(&j, 0, sizeof(j)); 72 j.version = 0; 73 j.path = argv[0]; 74 j.hostname = argv[1]; 75 i = inet_aton(argv[2], &in); 76 if (!i) 77 errx(1, "Couldn't make sense of ip-number\n"); 78 j.ip_number = ntohl(in.s_addr); 79 i = jail(&j); 80 if (i) 81 err(1, "Imprisonment failed"); 82 if (username != NULL) { 83 i = setgroups(ngroups, groups); 84 if (i) 85 err(1, "setgroups failed"); 86 i = setgid(pwd->pw_gid); 87 if (i) 88 err(1, "setgid failed"); 89 i = setusercontext(lcap, pwd, pwd->pw_uid, 90 LOGIN_SETALL & ~LOGIN_SETGROUP); 91 if (i) 92 err(1, "setusercontext failed"); 93 } 94 i = execv(argv[3], argv + 3); 95 if (i) 96 err(1, "execv(%s)", argv[3]); 97 exit (0); 98} 99 100static void 101usage(void) 102{ 103 104 errx(1, 105 "Usage: jail [-u username] path hostname ip-number command ..."); 106} 107