jail.c revision 113277
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 113277 2003-04-09 03:04:12Z mike $
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, 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	if (username != NULL) {
86		if (setgroups(ngroups, groups) != 0)
87			err(1, "setgroups");
88		if (setgid(pwd->pw_gid) != 0)
89			err(1, "setgid");
90		if (setusercontext(lcap, pwd, pwd->pw_uid,
91		    LOGIN_SETALL & ~LOGIN_SETGROUP) != 0)
92			err(1, "setusercontext");
93		login_close(lcap);
94	}
95	if (execv(argv[3], argv + 3) != 0)
96		err(1, "execv: %s", argv[3]);
97	exit(0);
98}
99
100static void
101usage(void)
102{
103
104	(void)fprintf(stderr,
105	"usage: jail [-i] [-u username] path hostname ip-number command ...\n");
106	exit(1);
107}
108