xref: /freebsd/usr.sbin/jail/jail.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 
10 #include <sys/cdefs.h>
11 __FBSDID("$FreeBSD$");
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 
28 static void	usage(void);
29 
30 int
31 main(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, iflag, ngroups;
38 	char *username;
39 
40 	iflag = 0;
41 	username = NULL;
42 
43 	while ((ch = getopt(argc, argv, "iu:")) != -1) {
44 		switch (ch) {
45 		case 'i':
46 			iflag = 1;
47 			break;
48 		case 'u':
49 			username = optarg;
50 			break;
51 		default:
52 			usage();
53 		}
54 	}
55 	argc -= optind;
56 	argv += optind;
57 	if (argc < 4)
58 		usage();
59 
60 	if (username != NULL) {
61 		pwd = getpwnam(username);
62 		if (pwd == NULL)
63 			err(1, "getpwnam: %s", username);
64 		lcap = login_getpwclass(pwd);
65 		if (lcap == NULL)
66 			err(1, "getpwclass: %s", username);
67 		ngroups = NGROUPS;
68 		if (getgrouplist(username, pwd->pw_gid, groups, &ngroups) != 0)
69 			err(1, "getgrouplist: %s", username);
70 	}
71 	if (chdir(argv[0]) != 0)
72 		err(1, "chdir: %s", argv[0]);
73 	memset(&j, 0, sizeof(j));
74 	j.version = 0;
75 	j.path = argv[0];
76 	j.hostname = argv[1];
77 	if (inet_aton(argv[2], &in) == 0)
78 		errx(1, "Could not make sense of ip-number: %s", argv[2]);
79 	j.ip_number = ntohl(in.s_addr);
80 	i = jail(&j);
81 	if (i == -1)
82 		err(1, "jail");
83 	if (iflag) {
84 		printf("%d\n", i);
85 		fflush(stdout);
86 	}
87 	if (username != NULL) {
88 		if (setgroups(ngroups, groups) != 0)
89 			err(1, "setgroups");
90 		if (setgid(pwd->pw_gid) != 0)
91 			err(1, "setgid");
92 		if (setusercontext(lcap, pwd, pwd->pw_uid,
93 		    LOGIN_SETALL & ~LOGIN_SETGROUP) != 0)
94 			err(1, "setusercontext");
95 		login_close(lcap);
96 	}
97 	if (execv(argv[3], argv + 3) != 0)
98 		err(1, "execv: %s", argv[3]);
99 	exit(0);
100 }
101 
102 static void
103 usage(void)
104 {
105 
106 	(void)fprintf(stderr,
107 	"usage: jail [-i] [-u username] path hostname ip-number command ...\n");
108 	exit(1);
109 }
110