xref: /openbsd-src/usr.sbin/dhcpd/dhcpd.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /*	$OpenBSD: dhcpd.c,v 1.57 2019/08/06 11:07:37 krw Exp $ */
2 
3 /*
4  * Copyright (c) 2004 Henning Brauer <henning@cvs.openbsd.org>
5  * Copyright (c) 1995, 1996, 1997, 1998, 1999
6  * The Internet Software Consortium.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of The Internet Software Consortium nor the names
18  *    of its contributors may be used to endorse or promote products derived
19  *    from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
22  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25  * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
26  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * This software has been written for the Internet Software Consortium
36  * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
37  * Enterprises.  To learn more about the Internet Software Consortium,
38  * see ``http://www.vix.com/isc''.  To learn more about Vixie
39  * Enterprises, see ``http://www.vix.com''.
40  */
41 
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 
45 #include <net/if.h>
46 
47 #include <arpa/inet.h>
48 
49 #include <err.h>
50 #include <netdb.h>
51 #include <pwd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <syslog.h>
56 #include <time.h>
57 #include <unistd.h>
58 
59 #include "dhcp.h"
60 #include "tree.h"
61 #include "dhcpd.h"
62 #include "log.h"
63 #include "sync.h"
64 
65 
66 __dead void usage(void);
67 
68 time_t cur_time, last_scan;
69 struct group root_group;
70 
71 u_int16_t server_port;
72 u_int16_t client_port;
73 
74 struct passwd *pw;
75 int log_priority;
76 int pfpipe[2];
77 int gotpipe = 0;
78 int syncrecv;
79 int syncsend;
80 pid_t pfproc_pid = -1;
81 char *path_dhcpd_conf = _PATH_DHCPD_CONF;
82 char *path_dhcpd_db = _PATH_DHCPD_DB;
83 char *abandoned_tab = NULL;
84 char *changedmac_tab = NULL;
85 char *leased_tab = NULL;
86 
87 int
88 main(int argc, char *argv[])
89 {
90 	int ch, cftest = 0, daemonize = 1, rdomain = -1, udpsockmode = 0;
91 	char *sync_iface = NULL;
92 	char *sync_baddr = NULL;
93 	u_short sync_port = 0;
94 	struct servent *ent;
95 	struct in_addr udpaddr;
96 
97 	log_init(1, LOG_DAEMON);	/* log to stderr until daemonized */
98 	log_setverbose(1);
99 
100 	opterr = 0;
101 	while ((ch = getopt(argc, argv, "A:C:L:c:dfl:nu::Y:y:")) != -1)
102 		switch (ch) {
103 		case 'Y':
104 			syncsend = 1;
105 			break;
106 		case 'y':
107 			syncrecv = 1;
108 			break;
109 		}
110 	if (syncsend || syncrecv) {
111 		if ((ent = getservbyname("dhcpd-sync", "udp")) == NULL)
112 			errx(1, "Can't find service \"dhcpd-sync\" in "
113 			    "/etc/services");
114 		sync_port = ntohs(ent->s_port);
115 	}
116 
117 	udpaddr.s_addr = htonl(INADDR_BROADCAST);
118 
119 	optreset = optind = opterr = 1;
120 	while ((ch = getopt(argc, argv, "A:C:L:c:dfl:nu::Y:y:")) != -1)
121 		switch (ch) {
122 		case 'A':
123 			abandoned_tab = optarg;
124 			break;
125 		case 'C':
126 			changedmac_tab = optarg;
127 			break;
128 		case 'L':
129 			leased_tab = optarg;
130 			break;
131 		case 'c':
132 			path_dhcpd_conf = optarg;
133 			break;
134 		case 'd':
135 			daemonize = 0;
136 			break;
137 		case 'f':
138 			daemonize = 0;
139 			break;
140 		case 'l':
141 			path_dhcpd_db = optarg;
142 			break;
143 		case 'n':
144 			daemonize = 0;
145 			cftest = 1;
146 			break;
147 		case 'u':
148 			udpsockmode = 1;
149 			if (optarg != NULL) {
150 				if (inet_aton(optarg, &udpaddr) != 1)
151 					errx(1, "Cannot parse binding IP "
152 					    "address: %s", optarg);
153 			}
154 			break;
155 		case 'Y':
156 			if (sync_addhost(optarg, sync_port) != 0)
157 				sync_iface = optarg;
158 			syncsend = 1;
159 			break;
160 		case 'y':
161 			sync_baddr = optarg;
162 			syncrecv = 1;
163 			break;
164 		default:
165 			usage();
166 		}
167 
168 	argc -= optind;
169 	argv += optind;
170 
171 	while (argc > 0) {
172 		struct interface_info *tmp = calloc(1, sizeof(*tmp));
173 		if (!tmp)
174 			fatalx("calloc");
175 		strlcpy(tmp->name, argv[0], sizeof(tmp->name));
176 		tmp->next = interfaces;
177 		interfaces = tmp;
178 		argc--;
179 		argv++;
180 	}
181 
182 	/* Default DHCP/BOOTP ports. */
183 	server_port = htons(SERVER_PORT);
184 	client_port = htons(CLIENT_PORT);
185 
186 	tzset();
187 
188 	time(&cur_time);
189 	if (!readconf())
190 		fatalx("Configuration file errors encountered");
191 
192 	if (cftest)
193 		exit(0);
194 
195 	db_startup();
196 	if (!udpsockmode || argc > 0)
197 		discover_interfaces(&rdomain);
198 
199 	if (rdomain != -1)
200 		if (setrtable(rdomain) == -1)
201 			fatal("setrtable");
202 
203 	if (syncsend || syncrecv) {
204 		syncfd = sync_init(sync_iface, sync_baddr, sync_port);
205 		if (syncfd == -1)
206 			err(1, "sync init");
207 	}
208 
209 	if (daemonize)
210 		daemon(0, 0);
211 
212 	log_init(0, LOG_DAEMON);	/* stop logging to stderr */
213 	log_setverbose(0);
214 
215 	if ((pw = getpwnam("_dhcp")) == NULL)
216 		fatalx("user \"_dhcp\" not found");
217 
218 	/* don't go near /dev/pf unless we actually intend to use it */
219 	if ((abandoned_tab != NULL) ||
220 	    (changedmac_tab != NULL) ||
221 	    (leased_tab != NULL)){
222 		if (pipe(pfpipe) == -1)
223 			fatal("pipe");
224 		switch (pfproc_pid = fork()){
225 		case -1:
226 			fatal("fork");
227 			/* NOTREACHED */
228 			exit(1);
229 		case 0:
230 			/* child process. start up table engine */
231 			close(pfpipe[1]);
232 			pftable_handler();
233 			/* NOTREACHED */
234 			exit(1);
235 		default:
236 			close(pfpipe[0]);
237 			gotpipe = 1;
238 			break;
239 		}
240 	}
241 
242 	if (udpsockmode)
243 		udpsock_startup(udpaddr);
244 
245 	icmp_startup(1, lease_pinged);
246 
247 	if (chroot(pw->pw_dir) == -1)
248 		fatal("chroot %s", pw->pw_dir);
249 	if (chdir("/") == -1)
250 		fatal("chdir(\"/\")");
251 	if (setgroups(1, &pw->pw_gid) ||
252 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
253 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
254 		fatal("can't drop privileges");
255 
256 	if (udpsockmode) {
257 		if (pledge("stdio inet route sendfd", NULL) == -1)
258 			err(1, "pledge");
259 	} else {
260 		if (pledge("stdio inet sendfd", NULL) == -1)
261 			err(1, "pledge");
262 	}
263 
264 	add_timeout(cur_time + 5, periodic_scan, NULL);
265 	dispatch();
266 
267 	/* not reached */
268 	exit(0);
269 }
270 
271 __dead void
272 usage(void)
273 {
274 	extern char *__progname;
275 
276 	fprintf(stderr, "usage: %s [-dfn] [-A abandoned_ip_table]",
277 	    __progname);
278 	fprintf(stderr, " [-C changed_ip_table]\n");
279 	fprintf(stderr, "\t[-c config-file] [-L leased_ip_table]");
280 	fprintf(stderr, " [-l lease-file] [-u[bind_address]]\n");
281 	fprintf(stderr, "\t[-Y synctarget] [-y synclisten] [if0 [... ifN]]\n");
282 	exit(1);
283 }
284 
285 void
286 lease_pinged(struct iaddr from, u_int8_t *packet, int length)
287 {
288 	struct lease *lp;
289 
290 	/*
291 	 * Don't try to look up a pinged lease if we aren't trying to
292 	 * ping one - otherwise somebody could easily make us churn by
293 	 * just forging repeated ICMP EchoReply packets for us to look
294 	 * up.
295 	 */
296 	if (!outstanding_pings)
297 		return;
298 
299 	lp = find_lease_by_ip_addr(from);
300 
301 	if (!lp) {
302 		log_info("unexpected ICMP Echo Reply from %s", piaddr(from));
303 		return;
304 	}
305 
306 	if (!lp->state && !lp->releasing) {
307 		log_warnx("ICMP Echo Reply for %s arrived late or is "
308 		    "spurious.", piaddr(from));
309 		return;
310 	}
311 
312 	/* At this point it looks like we pinged a lease and got a
313 	 * response, which shouldn't have happened.
314 	 * if it did it's either one of two two cases:
315 	 * 1 - we pinged this lease before offering it and
316 	 *     something answered, so we abandon it.
317 	 * 2 - we pinged this lease before releasing it
318 	 *     and something answered, so we don't release it.
319 	 */
320 	if (lp->releasing) {
321 		log_warnx("IP address %s answers a ping after sending a "
322 		    "release", piaddr(lp->ip_addr));
323 		log_warnx("Possible release spoof - Not releasing address %s",
324 		    piaddr(lp->ip_addr));
325 		lp->releasing = 0;
326 	} else {
327 		free_lease_state(lp->state, "lease_pinged");
328 		lp->state = NULL;
329 		abandon_lease(lp, "pinged before offer");
330 	}
331 	cancel_timeout(lease_ping_timeout, lp);
332 	--outstanding_pings;
333 }
334 
335 void
336 lease_ping_timeout(void *vlp)
337 {
338 	struct lease	*lp = vlp;
339 
340 	--outstanding_pings;
341 	if (lp->releasing) {
342 		lp->releasing = 0;
343 		release_lease(lp);
344 	} else
345 		dhcp_reply(lp);
346 }
347 
348 /* from memory.c - needed to be able to walk the lease table */
349 extern struct subnet *subnets;
350 
351 #define MINIMUM(a,b) (((a)<(b))?(a):(b))
352 
353 void
354 periodic_scan(void *p)
355 {
356 	time_t x, y;
357 	struct subnet		*n;
358 	struct group		*g;
359 	struct shared_network	*s;
360 	struct lease		*l;
361 
362 	/* find the shortest lease this server gives out */
363 	x = MINIMUM(root_group.default_lease_time, root_group.max_lease_time);
364 	for (n = subnets; n; n = n->next_subnet)
365 		for (g = n->group; g; g = g->next)
366 			x = MINIMUM(x, g->default_lease_time);
367 
368 	/* use half of the shortest lease as the scan interval */
369 	y = x / 2;
370 	if (y < 1)
371 		y = 1;
372 
373 	/* walk across all leases to find the exired ones */
374 	for (n = subnets; n; n = n->next_subnet)
375 		for (g = n->group; g; g = g->next)
376 			for (s = g->shared_network; s; s = s->next)
377 				for (l = s->leases; l && l->ends; l = l->next)
378 					if (cur_time >= l->ends)
379 						if (l->ends > last_scan)
380 							pfmsg('R', l);
381 
382 	last_scan = cur_time;
383 	add_timeout(cur_time + y, periodic_scan, NULL);
384 }
385