dhcpv4: fix lease ordering by ip address
[project/odhcpd.git] / src / dhcpv4.c
1 /**
2 * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
3 * Copyright (C) 2016 Hans Dedecker <dedeckeh@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License v2 as published by
7 * the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 *
15 */
16
17 #include <time.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 #include <stddef.h>
22 #include <stdlib.h>
23 #include <resolv.h>
24 #include <limits.h>
25 #include <net/if.h>
26 #include <net/if_arp.h>
27 #include <netinet/ip.h>
28 #include <sys/ioctl.h>
29 #include <sys/timerfd.h>
30 #include <arpa/inet.h>
31
32 #include <libubox/md5.h>
33
34 #include "odhcpd.h"
35 #include "dhcpv4.h"
36 #include "dhcpv6.h"
37
38 #define PACKET_SIZE(start, end) (((uint8_t *)end - (uint8_t *)start) < DHCPV4_MIN_PACKET_SIZE ? \
39 DHCPV4_MIN_PACKET_SIZE : (uint8_t *)end - (uint8_t *)start)
40
41 static void dhcpv4_netevent_cb(unsigned long event, struct netevent_handler_info *info);
42 static int setup_dhcpv4_addresses(struct interface *iface);
43 static bool addr_is_fr_ip(struct interface *iface, struct in_addr *addr);
44 static void valid_until_cb(struct uloop_timeout *event);
45 static void handle_addrlist_change(struct interface *iface);
46 static void dhcpv4_fr_start(struct dhcp_assignment *a);
47 static void dhcpv4_fr_rand_delay(struct dhcp_assignment *a);
48 static void dhcpv4_fr_stop(struct dhcp_assignment *a);
49 static void handle_dhcpv4(void *addr, void *data, size_t len,
50 struct interface *iface, void *dest_addr);
51 static struct dhcp_assignment* dhcpv4_lease(struct interface *iface,
52 enum dhcpv4_msg msg, const uint8_t *mac, const uint32_t reqaddr,
53 uint32_t *leasetime, const char *hostname, const size_t hostname_len,
54 const bool accept_fr_nonce, bool *incl_fr_opt, uint32_t *fr_serverid,
55 const char *reqopts, const size_t reqopts_len);
56
57 static struct netevent_handler dhcpv4_netevent_handler = { .cb = dhcpv4_netevent_cb, };
58 static struct uloop_timeout valid_until_timeout = {.cb = valid_until_cb};
59 static uint32_t serial = 0;
60
61 struct odhcpd_ref_ip {
62 struct list_head head;
63 int ref_cnt;
64 struct odhcpd_ipaddr addr;
65 };
66
67 /* Create socket and register events */
68 int dhcpv4_init(void)
69 {
70 uloop_timeout_set(&valid_until_timeout, 1000);
71 netlink_add_netevent_handler(&dhcpv4_netevent_handler);
72
73 return 0;
74 }
75
76 int dhcpv4_setup_interface(struct interface *iface, bool enable)
77 {
78 int ret = 0;
79
80 if (iface->dhcpv4_event.uloop.fd >= 0) {
81 uloop_fd_delete(&iface->dhcpv4_event.uloop);
82 close(iface->dhcpv4_event.uloop.fd);
83 iface->dhcpv4_event.uloop.fd = -1;
84 }
85
86 if (iface->dhcpv4 && enable) {
87 struct sockaddr_in bind_addr = {AF_INET, htons(DHCPV4_SERVER_PORT),
88 {INADDR_ANY}, {0}};
89 int val = 1;
90
91 iface->dhcpv4_event.uloop.fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
92 if (iface->dhcpv4_event.uloop.fd < 0) {
93 syslog(LOG_ERR, "socket(AF_INET): %m");
94 ret = -1;
95 goto out;
96 }
97
98 /* Basic IPv4 configuration */
99 if (setsockopt(iface->dhcpv4_event.uloop.fd, SOL_SOCKET, SO_REUSEADDR,
100 &val, sizeof(val)) < 0) {
101 syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
102 ret = -1;
103 goto out;
104 }
105
106 if (setsockopt(iface->dhcpv4_event.uloop.fd, SOL_SOCKET, SO_BROADCAST,
107 &val, sizeof(val)) < 0) {
108 syslog(LOG_ERR, "setsockopt(SO_BROADCAST): %m");
109 ret = -1;
110 goto out;
111 }
112
113 if (setsockopt(iface->dhcpv4_event.uloop.fd, IPPROTO_IP, IP_PKTINFO,
114 &val, sizeof(val)) < 0) {
115 syslog(LOG_ERR, "setsockopt(IP_PKTINFO): %m");
116 ret = -1;
117 goto out;
118 }
119
120 val = IPTOS_PREC_INTERNETCONTROL;
121 if (setsockopt(iface->dhcpv4_event.uloop.fd, IPPROTO_IP, IP_TOS,
122 &val, sizeof(val)) < 0) {
123 syslog(LOG_ERR, "setsockopt(IP_TOS): %m");
124 ret = -1;
125 goto out;
126 }
127
128 val = IP_PMTUDISC_DONT;
129 if (setsockopt(iface->dhcpv4_event.uloop.fd, IPPROTO_IP, IP_MTU_DISCOVER,
130 &val, sizeof(val)) < 0) {
131 syslog(LOG_ERR, "setsockopt(IP_MTU_DISCOVER): %m");
132 ret = -1;
133 goto out;
134 }
135
136 if (setsockopt(iface->dhcpv4_event.uloop.fd, SOL_SOCKET, SO_BINDTODEVICE,
137 iface->ifname, strlen(iface->ifname)) < 0) {
138 syslog(LOG_ERR, "setsockopt(SO_BINDTODEVICE): %m");
139 ret = -1;
140 goto out;
141 }
142
143 if (bind(iface->dhcpv4_event.uloop.fd, (struct sockaddr*)&bind_addr,
144 sizeof(bind_addr)) < 0) {
145 syslog(LOG_ERR, "bind(): %m");
146 ret = -1;
147 goto out;
148 }
149
150 if (setup_dhcpv4_addresses(iface) < 0) {
151 ret = -1;
152 goto out;
153 }
154
155 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
156 odhcpd_register(&iface->dhcpv4_event);
157 } else {
158 while (!list_empty(&iface->dhcpv4_assignments))
159 free_assignment(list_first_entry(&iface->dhcpv4_assignments,
160 struct dhcp_assignment, head));
161 }
162
163 out:
164 if (ret < 0 && iface->dhcpv4_event.uloop.fd >= 0) {
165 close(iface->dhcpv4_event.uloop.fd);
166 iface->dhcpv4_event.uloop.fd = -1;
167 }
168
169 return ret;
170 }
171
172
173 static void dhcpv4_netevent_cb(unsigned long event, struct netevent_handler_info *info)
174 {
175 struct interface *iface = info->iface;
176
177 if (!iface || iface->dhcpv4 == MODE_DISABLED)
178 return;
179
180 switch (event) {
181 case NETEV_IFINDEX_CHANGE:
182 dhcpv4_setup_interface(iface, true);
183 break;
184 case NETEV_ADDRLIST_CHANGE:
185 handle_addrlist_change(iface);
186 break;
187 default:
188 break;
189 }
190 }
191
192 static struct dhcp_assignment *find_assignment_by_hwaddr(struct interface *iface, const uint8_t *hwaddr)
193 {
194 struct dhcp_assignment *a;
195
196 list_for_each_entry(a, &iface->dhcpv4_assignments, head)
197 if (!memcmp(a->hwaddr, hwaddr, 6))
198 return a;
199
200 return NULL;
201 }
202
203 static int setup_dhcpv4_addresses(struct interface *iface)
204 {
205 iface->dhcpv4_start_ip.s_addr = INADDR_ANY;
206 iface->dhcpv4_end_ip.s_addr = INADDR_ANY;
207 iface->dhcpv4_local.s_addr = INADDR_ANY;
208 iface->dhcpv4_bcast.s_addr = INADDR_ANY;
209 iface->dhcpv4_mask.s_addr = INADDR_ANY;
210
211 /* Sanity checks */
212 if (iface->dhcpv4_start.s_addr & htonl(0xffff0000) ||
213 iface->dhcpv4_end.s_addr & htonl(0xffff0000) ||
214 ntohl(iface->dhcpv4_start.s_addr) > ntohl(iface->dhcpv4_end.s_addr)) {
215 syslog(LOG_ERR, "Invalid DHCP range for %s", iface->name);
216 return -1;
217 }
218
219 if (!iface->addr4_len) {
220 syslog(LOG_ERR, "No network(s) available on %s", iface->name);
221 return -1;
222 }
223
224 uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
225 uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
226
227 for (size_t i = 0; i < iface->addr4_len && start && end; i++) {
228 struct in_addr *addr = &iface->addr4[i].addr.in;
229 struct in_addr mask;
230
231 if (addr_is_fr_ip(iface, addr))
232 continue;
233
234 odhcpd_bitlen2netmask(false, iface->addr4[i].prefix, &mask);
235 if ((start & ntohl(~mask.s_addr)) == start &&
236 (end & ntohl(~mask.s_addr)) == end &&
237 end < ntohl(~mask.s_addr)) { /* Exclude broadcast address */
238 iface->dhcpv4_start_ip.s_addr = htonl(start) |
239 (addr->s_addr & mask.s_addr);
240 iface->dhcpv4_end_ip.s_addr = htonl(end) |
241 (addr->s_addr & mask.s_addr);
242 iface->dhcpv4_local = *addr;
243 iface->dhcpv4_bcast = iface->addr4[i].broadcast;
244 iface->dhcpv4_mask = mask;
245 return 0;
246 }
247 }
248
249 /* Don't allocate IP range for subnets bigger than 28 */
250 if (iface->addr4[0].prefix > 28) {
251 syslog(LOG_ERR, "Auto allocation of DHCP range fails on %s", iface->name);
252 return -1;
253 }
254
255 iface->dhcpv4_local = iface->addr4[0].addr.in;
256 iface->dhcpv4_bcast = iface->addr4[0].broadcast;
257 odhcpd_bitlen2netmask(false, iface->addr4[0].prefix, &iface->dhcpv4_mask);
258 end = start = iface->dhcpv4_local.s_addr & iface->dhcpv4_mask.s_addr;
259
260 /* Auto allocate ranges */
261 if (ntohl(iface->dhcpv4_mask.s_addr) <= 0xffffff00) { /* /24, 150 of 256, [100..249] */
262 iface->dhcpv4_start_ip.s_addr = start | htonl(100);
263 iface->dhcpv4_end_ip.s_addr = end | htonl(100 + 150 - 1);
264 } else if (ntohl(iface->dhcpv4_mask.s_addr) <= 0xffffff80) { /* /25, 100 of 128, [20..119] */
265 iface->dhcpv4_start_ip.s_addr = start | htonl(20);
266 iface->dhcpv4_end_ip.s_addr = end | htonl(20 + 100 - 1);
267 } else if (ntohl(iface->dhcpv4_mask.s_addr) <= 0xffffffc0) { /* /26, 50 of 64, [10..59] */
268 iface->dhcpv4_start_ip.s_addr = start | htonl(10);
269 iface->dhcpv4_end_ip.s_addr = end | htonl(10 + 50 - 1);
270 } else if (ntohl(iface->dhcpv4_mask.s_addr) <= 0xffffffe0) { /* /27, 20 of 32, [10..29] */
271 iface->dhcpv4_start_ip.s_addr = start | htonl(10);
272 iface->dhcpv4_end_ip.s_addr = end | htonl(10 + 20 - 1);
273 } else { /* /28, 10 of 16, [3..12] */
274 iface->dhcpv4_start_ip.s_addr = start | htonl(3);
275 iface->dhcpv4_end_ip.s_addr = end | htonl(3 + 10 - 1);
276 }
277
278 return 0;
279 }
280
281 static void inc_ref_cnt_ip(struct odhcpd_ref_ip **ptr, struct odhcpd_ref_ip *ip)
282 {
283 *ptr = ip;
284 ip->ref_cnt++;
285 }
286
287 static void decr_ref_cnt_ip(struct odhcpd_ref_ip **ptr, struct interface *iface)
288 {
289 struct odhcpd_ref_ip *ip = *ptr;
290
291 if (--ip->ref_cnt == 0) {
292 netlink_setup_addr(&ip->addr, iface->ifindex, false, false);
293
294 list_del(&ip->head);
295 free(ip);
296 }
297
298 *ptr = NULL;
299 }
300
301 static bool addr_is_fr_ip(struct interface *iface, struct in_addr *addr)
302 {
303 struct odhcpd_ref_ip *p;
304
305 list_for_each_entry(p, &iface->dhcpv4_fr_ips, head) {
306 if (addr->s_addr == p->addr.addr.in.s_addr)
307 return true;
308 }
309
310 return false;
311 }
312
313 static bool leases_require_fr(struct interface *iface, struct odhcpd_ipaddr *addr,
314 uint32_t mask)
315 {
316 struct dhcp_assignment *a = NULL;
317 struct odhcpd_ref_ip *fr_ip = NULL;
318
319 list_for_each_entry(a, &iface->dhcpv4_assignments, head) {
320 if ((a->accept_fr_nonce || iface->dhcpv4_forcereconf) &&
321 !a->fr_ip &&
322 ((a->addr & mask) == (addr->addr.in.s_addr & mask))) {
323 if (!fr_ip) {
324 fr_ip = calloc(1, sizeof(*fr_ip));
325 if (!fr_ip)
326 break;
327
328 list_add(&fr_ip->head, &iface->dhcpv4_fr_ips);
329 fr_ip->addr = *addr;
330 }
331 inc_ref_cnt_ip(&a->fr_ip, fr_ip);
332 }
333 }
334
335 return fr_ip ? true : false;
336 }
337
338 static void valid_until_cb(struct uloop_timeout *event)
339 {
340 struct interface *iface;
341 time_t now = odhcpd_time();
342
343 avl_for_each_element(&interfaces, iface, avl) {
344 struct dhcp_assignment *a, *n;
345
346 if (iface->dhcpv4 != MODE_SERVER)
347 continue;
348
349 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
350 if (!INFINITE_VALID(a->valid_until) && a->valid_until < now)
351 free_assignment(a);
352 }
353 }
354 uloop_timeout_set(event, 1000);
355 }
356
357 static void handle_addrlist_change(struct interface *iface)
358 {
359 struct odhcpd_ipaddr ip;
360 struct odhcpd_ref_ip *a;
361 struct dhcp_assignment *c;
362 uint32_t mask = iface->dhcpv4_mask.s_addr;
363
364 memset(&ip, 0, sizeof(ip));
365 ip.addr.in = iface->dhcpv4_local;
366 ip.prefix = odhcpd_netmask2bitlen(false, &iface->dhcpv4_mask);
367 ip.broadcast = iface->dhcpv4_bcast;
368
369 setup_dhcpv4_addresses(iface);
370
371 if ((ip.addr.in.s_addr & mask) ==
372 (iface->dhcpv4_local.s_addr & iface->dhcpv4_mask.s_addr))
373 return;
374
375 if (ip.addr.in.s_addr && !leases_require_fr(iface, &ip, mask))
376 return;
377
378 if (iface->dhcpv4_local.s_addr == INADDR_ANY || list_empty(&iface->dhcpv4_fr_ips))
379 return;
380
381 a = list_first_entry(&iface->dhcpv4_fr_ips, struct odhcpd_ref_ip, head);
382
383 if (netlink_setup_addr(&a->addr, iface->ifindex, false, true)) {
384 syslog(LOG_ERR, "Failed to add ip address on %s", iface->name);
385 return;
386 }
387
388 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
389 if ((c->flags & OAF_BOUND) && c->fr_ip && !c->fr_cnt) {
390 if (c->accept_fr_nonce || iface->dhcpv4_forcereconf)
391 dhcpv4_fr_rand_delay(c);
392 else
393 dhcpv4_fr_stop(c);
394 }
395 }
396 }
397
398 static char *dhcpv4_msg_to_string(uint8_t reqmsg)
399 {
400 switch (reqmsg) {
401 case (DHCPV4_MSG_DISCOVER):
402 return "DHCPV4_MSG_DISCOVER";
403 case (DHCPV4_MSG_OFFER):
404 return "DHCPV4_MSG_OFFER";
405 case (DHCPV4_MSG_REQUEST):
406 return "DHCPV4_MSG_REQUEST";
407 case (DHCPV4_MSG_DECLINE):
408 return "DHCPV4_MSG_DECLINE";
409 case (DHCPV4_MSG_ACK):
410 return "DHCPV4_MSG_ACK";
411 case (DHCPV4_MSG_NAK):
412 return "DHCPV4_MSG_NAK";
413 case (DHCPV4_MSG_RELEASE):
414 return "DHCPV4_MSG_RELEASE";
415 case (DHCPV4_MSG_INFORM):
416 return "DHCPV4_MSG_INFORM";
417 case (DHCPV4_MSG_FORCERENEW):
418 return "DHCPV4_MSG_FORCERENEW";
419 default:
420 return "UNKNOWN";
421 }
422 }
423
424 static void dhcpv4_free_assignment(struct dhcp_assignment *a)
425 {
426 if (a->fr_ip)
427 dhcpv4_fr_stop(a);
428 }
429
430 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
431 uint8_t type, uint8_t len, const void *data)
432 {
433 uint8_t *c = *cookie;
434 uint8_t *end = (uint8_t *)msg + sizeof(*msg);
435 bool tag_only = type == DHCPV4_OPT_PAD || type == DHCPV4_OPT_END;
436 int total_len = tag_only ? 1 : 2 + len;
437
438 if (*cookie + total_len > end)
439 return;
440
441 *cookie += total_len;
442 *c++ = type;
443
444 if (tag_only)
445 return;
446
447 *c++ = len;
448 memcpy(c, data, len);
449 }
450
451 static void dhcpv4_fr_send(struct dhcp_assignment *a)
452 {
453 struct dhcpv4_message fr_msg = {
454 .op = DHCPV4_BOOTREPLY,
455 .htype = 1,
456 .hlen = 6,
457 .hops = 0,
458 .secs = 0,
459 .flags = 0,
460 .ciaddr = {INADDR_ANY},
461 .yiaddr = {INADDR_ANY},
462 .siaddr = {INADDR_ANY},
463 .giaddr = {INADDR_ANY},
464 .chaddr = {0},
465 .sname = {0},
466 .file = {0},
467 };
468 struct dhcpv4_auth_forcerenew *auth_o, auth = {
469 .protocol = 3,
470 .algorithm = 1,
471 .rdm = 0,
472 .replay = {htonl(time(NULL)), htonl(++serial)},
473 .type = 2,
474 .key = {0},
475 };
476 struct interface *iface = a->iface;
477
478 odhcpd_urandom(&fr_msg.xid, sizeof(fr_msg.xid));
479 memcpy(fr_msg.chaddr, a->hwaddr, fr_msg.hlen);
480
481 fr_msg.options[0] = 0x63;
482 fr_msg.options[1] = 0x82;
483 fr_msg.options[2] = 0x53;
484 fr_msg.options[3] = 0x63;
485
486 uint8_t *cookie = &fr_msg.options[4];
487 uint8_t msg = DHCPV4_MSG_FORCERENEW;
488
489 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
490 if (a->accept_fr_nonce) {
491 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_AUTHENTICATION, sizeof(auth), &auth);
492 auth_o = (struct dhcpv4_auth_forcerenew *)(cookie - sizeof(auth));
493 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_END, 0, NULL);
494
495 md5_ctx_t md5;
496 uint8_t secretbytes[64];
497 memset(secretbytes, 0, sizeof(secretbytes));
498 memcpy(secretbytes, a->key, sizeof(a->key));
499
500 for (size_t i = 0; i < sizeof(secretbytes); ++i)
501 secretbytes[i] ^= 0x36;
502
503 md5_begin(&md5);
504 md5_hash(secretbytes, sizeof(secretbytes), &md5);
505 md5_hash(&fr_msg, sizeof(fr_msg), &md5);
506 md5_end(auth_o->key, &md5);
507
508 for (size_t i = 0; i < sizeof(secretbytes); ++i) {
509 secretbytes[i] ^= 0x36;
510 secretbytes[i] ^= 0x5c;
511 }
512
513 md5_begin(&md5);
514 md5_hash(secretbytes, sizeof(secretbytes), &md5);
515 md5_hash(auth_o->key, sizeof(auth_o->key), &md5);
516 md5_end(auth_o->key, &md5);
517 } else {
518 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_SERVERID, 4,
519 &a->fr_ip->addr.addr.in.s_addr);
520 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_END, 0, NULL);
521 }
522
523 struct sockaddr_in dest;
524 memset(&dest, 0, sizeof(dest));
525 dest.sin_family = AF_INET;
526 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
527 dest.sin_addr.s_addr = a->addr;
528
529 if (sendto(iface->dhcpv4_event.uloop.fd, &fr_msg, PACKET_SIZE(&fr_msg, cookie),
530 MSG_DONTWAIT, (struct sockaddr*)&dest, sizeof(dest)) < 0)
531 syslog(LOG_ERR, "Failed to send %s to %s - %s: %m", dhcpv4_msg_to_string(msg),
532 odhcpd_print_mac(a->hwaddr, sizeof(a->hwaddr)), inet_ntoa(dest.sin_addr));
533 else
534 syslog(LOG_NOTICE, "Sent %s to %s - %s", dhcpv4_msg_to_string(msg),
535 odhcpd_print_mac(a->hwaddr, sizeof(a->hwaddr)), inet_ntoa(dest.sin_addr));
536 }
537
538 static void dhcpv4_fr_timer(struct uloop_timeout *event)
539 {
540 struct dhcp_assignment *a = container_of(event, struct dhcp_assignment, fr_timer);
541
542 if (a->fr_cnt > 0 && a->fr_cnt < 8) {
543 dhcpv4_fr_send(a);
544 uloop_timeout_set(&a->fr_timer, 1000 << a->fr_cnt);
545 a->fr_cnt++;
546 } else
547 dhcpv4_fr_stop(a);
548 }
549
550 static void dhcpv4_fr_start(struct dhcp_assignment *a)
551 {
552 uloop_timeout_set(&a->fr_timer, 1000 << a->fr_cnt);
553 a->fr_timer.cb = dhcpv4_fr_timer;
554 a->fr_cnt++;
555
556 dhcpv4_fr_send(a);
557 }
558
559 static void dhcpv4_fr_delay_timer(struct uloop_timeout *event)
560 {
561 struct dhcp_assignment *a = container_of(event, struct dhcp_assignment, fr_timer);
562 struct interface *iface = a->iface;
563
564 (iface->dhcpv4_event.uloop.fd == -1 ? dhcpv4_fr_rand_delay(a) : dhcpv4_fr_start(a));
565 }
566
567 static void dhcpv4_fr_rand_delay(struct dhcp_assignment *a)
568 {
569 #define MIN_DELAY 500
570 #define MAX_FUZZ 500
571 int msecs;
572
573 odhcpd_urandom(&msecs, sizeof(msecs));
574
575 msecs = labs(msecs)%MAX_FUZZ + MIN_DELAY;
576
577 uloop_timeout_set(&a->fr_timer, msecs);
578 a->fr_timer.cb = dhcpv4_fr_delay_timer;
579 }
580
581 static void dhcpv4_fr_stop(struct dhcp_assignment *a)
582 {
583 uloop_timeout_cancel(&a->fr_timer);
584 decr_ref_cnt_ip(&a->fr_ip, a->iface);
585 a->fr_cnt = 0;
586 a->fr_timer.cb = NULL;
587 }
588
589 /* Handler for DHCPv4 messages */
590 static void handle_dhcpv4(void *addr, void *data, size_t len,
591 struct interface *iface, _unused void *dest_addr)
592 {
593 struct dhcpv4_message *req = data;
594
595 if (!iface->dhcpv4)
596 return;
597
598 if (len < offsetof(struct dhcpv4_message, options) + 4 ||
599 req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
600 return;
601
602 syslog(LOG_NOTICE, "Got DHCPv4 request on %s", iface->name);
603
604 if (!iface->dhcpv4_start_ip.s_addr && !iface->dhcpv4_end_ip.s_addr) {
605 syslog(LOG_ERR, "No DHCP range available on %s", iface->name);
606 return;
607 }
608
609 int sock = iface->dhcpv4_event.uloop.fd;
610
611 struct dhcpv4_message reply = {
612 .op = DHCPV4_BOOTREPLY,
613 .htype = req->htype,
614 .hlen = req->hlen,
615 .hops = 0,
616 .xid = req->xid,
617 .secs = 0,
618 .flags = req->flags,
619 .ciaddr = {INADDR_ANY},
620 .giaddr = req->giaddr,
621 .siaddr = iface->dhcpv4_local,
622 };
623 memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
624
625 reply.options[0] = 0x63;
626 reply.options[1] = 0x82;
627 reply.options[2] = 0x53;
628 reply.options[3] = 0x63;
629
630 uint8_t *cookie = &reply.options[4];
631 uint8_t reqmsg = DHCPV4_MSG_REQUEST;
632 uint8_t msg = DHCPV4_MSG_ACK;
633
634 uint32_t reqaddr = INADDR_ANY;
635 uint32_t leasetime = 0;
636 size_t hostname_len = 0;
637 size_t reqopts_len = 0;
638 char hostname[256];
639 char reqopts[256];
640 bool accept_fr_nonce = false;
641 bool incl_fr_opt = false;
642
643 uint8_t *start = &req->options[4];
644 uint8_t *end = ((uint8_t*)data) + len;
645 struct dhcpv4_option *opt;
646 dhcpv4_for_each_option(start, end, opt) {
647 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1)
648 reqmsg = opt->data[0];
649 else if (opt->type == DHCPV4_OPT_REQOPTS && opt->len > 0) {
650 reqopts_len = opt->len;
651 memcpy(reqopts, opt->data, reqopts_len);
652 reqopts[reqopts_len] = 0;
653 } else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
654 hostname_len = opt->len;
655 memcpy(hostname, opt->data, hostname_len);
656 hostname[hostname_len] = 0;
657 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4)
658 memcpy(&reqaddr, opt->data, 4);
659 else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
660 if (memcmp(opt->data, &iface->dhcpv4_local, 4))
661 return;
662 } else if (iface->filter_class && opt->type == DHCPV4_OPT_USER_CLASS) {
663 uint8_t *c = opt->data, *cend = &opt->data[opt->len];
664 for (; c < cend && &c[*c] < cend; c = &c[1 + *c]) {
665 size_t elen = strlen(iface->filter_class);
666 if (*c == elen && !memcmp(&c[1], iface->filter_class, elen))
667 return; // Ignore from homenet
668 }
669 } else if (opt->type == DHCPV4_OPT_LEASETIME && opt->len == 4)
670 memcpy(&leasetime, opt->data, 4);
671 else if (opt->type == DHCPV4_OPT_FORCERENEW_NONCE_CAPABLE && opt->len > 0) {
672 for (uint8_t i = 0; i < opt->len; i++) {
673 if (opt->data[i] == 1) {
674 accept_fr_nonce = true;
675 break;
676 }
677 }
678
679 }
680 }
681
682 if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
683 reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
684 reqmsg != DHCPV4_MSG_RELEASE)
685 return;
686
687 struct dhcp_assignment *a = NULL;
688 uint32_t serverid = iface->dhcpv4_local.s_addr;
689 uint32_t fr_serverid = INADDR_ANY;
690
691 if (reqmsg != DHCPV4_MSG_INFORM)
692 a = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr,
693 &leasetime, hostname, hostname_len,
694 accept_fr_nonce, &incl_fr_opt, &fr_serverid,
695 reqopts, reqopts_len);
696
697 if (!a) {
698 if (reqmsg == DHCPV4_MSG_REQUEST)
699 msg = DHCPV4_MSG_NAK;
700 else if (reqmsg == DHCPV4_MSG_DISCOVER)
701 return;
702 } else if (reqmsg == DHCPV4_MSG_DISCOVER)
703 msg = DHCPV4_MSG_OFFER;
704 else if (reqmsg == DHCPV4_MSG_REQUEST &&
705 ((reqaddr && reqaddr != a->addr) ||
706 (req->ciaddr.s_addr && req->ciaddr.s_addr != a->addr))) {
707 msg = DHCPV4_MSG_NAK;
708 /*
709 * DHCP client requested an IP which we can't offer to him. Probably the
710 * client changed the network or the network has been changed. The reply
711 * type is set to DHCPV4_MSG_NAK, because the client should not use that IP.
712 *
713 * For modern devices we build an answer that includes a valid IP, like
714 * a DHCPV4_MSG_ACK. The client will use that IP and doesn't need to
715 * perform additional DHCP round trips.
716 *
717 */
718
719 /*
720 *
721 * Buggy clients do serverid checking in nack messages; therefore set the
722 * serverid in nack messages triggered by a previous force renew equal to
723 * the server id in use at that time by the server
724 *
725 */
726 if (fr_serverid)
727 serverid = fr_serverid;
728
729 if (req->ciaddr.s_addr &&
730 ((iface->dhcpv4_start_ip.s_addr & iface->dhcpv4_mask.s_addr) !=
731 (req->ciaddr.s_addr & iface->dhcpv4_mask.s_addr)))
732 req->ciaddr.s_addr = INADDR_ANY;
733 }
734
735 syslog(LOG_NOTICE, "Received %s from %s on %s", dhcpv4_msg_to_string(reqmsg),
736 odhcpd_print_mac(req->chaddr, req->hlen), iface->name);
737
738 #ifdef WITH_UBUS
739 if (reqmsg == DHCPV4_MSG_RELEASE)
740 ubus_bcast_dhcp_event("dhcp.release", req->chaddr, req->hlen,
741 &req->ciaddr, hostname, iface->ifname);
742 #endif
743 if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
744 return;
745
746 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
747 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, &serverid);
748
749 if (a) {
750 uint32_t val;
751
752 reply.yiaddr.s_addr = a->addr;
753
754 val = htonl(leasetime);
755 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
756
757 if (leasetime != UINT32_MAX) {
758 val = htonl(500 * leasetime / 1000);
759 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
760
761 val = htonl(875 * leasetime / 1000);
762 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
763 }
764
765 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4,
766 &iface->dhcpv4_mask.s_addr);
767
768 if (a->hostname)
769 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
770 strlen(a->hostname), a->hostname);
771
772 if (iface->dhcpv4_bcast.s_addr != INADDR_ANY)
773 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &iface->dhcpv4_bcast);
774
775 if (incl_fr_opt) {
776 if (reqmsg == DHCPV4_MSG_REQUEST) {
777 struct dhcpv4_auth_forcerenew auth = {
778 .protocol = 3,
779 .algorithm = 1,
780 .rdm = 0,
781 .replay = {htonl(time(NULL)), htonl(++serial)},
782 .type = 1,
783 .key = {0},
784 };
785
786 memcpy(auth.key, a->key, sizeof(auth.key));
787 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_AUTHENTICATION, sizeof(auth), &auth);
788 } else {
789 uint8_t one = 1;
790 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_FORCERENEW_NONCE_CAPABLE,
791 sizeof(one), &one);
792 }
793 }
794 }
795
796 struct ifreq ifr;
797
798 memset(&ifr, 0, sizeof(ifr));
799 strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name) - 1);
800
801 if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
802 uint16_t mtu = htons(ifr.ifr_mtu);
803 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
804 }
805
806 if (iface->search && iface->search_len <= 255)
807 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
808 iface->search_len, iface->search);
809 else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
810 uint8_t search_buf[256];
811 int len = dn_comp(_res.dnsrch[0], search_buf,
812 sizeof(search_buf), NULL, NULL);
813 if (len > 0)
814 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
815 len, search_buf);
816 }
817
818 if (iface->dhcpv4_router_cnt == 0)
819 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &iface->dhcpv4_local);
820 else
821 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER,
822 4 * iface->dhcpv4_router_cnt, iface->dhcpv4_router);
823
824
825 if (iface->dhcpv4_dns_cnt == 0)
826 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &iface->dhcpv4_local);
827 else
828 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
829 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
830
831
832 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
833
834 struct sockaddr_in dest = *((struct sockaddr_in*)addr);
835 if (req->giaddr.s_addr) {
836 /*
837 * relay agent is configured, send reply to the agent
838 */
839 dest.sin_addr = req->giaddr;
840 dest.sin_port = htons(DHCPV4_SERVER_PORT);
841 } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
842 /*
843 * client has existing configuration (ciaddr is set) AND this address is
844 * not the address it used for the dhcp message
845 */
846 dest.sin_addr = req->ciaddr;
847 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
848 } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
849 req->hlen != reply.hlen || !reply.yiaddr.s_addr) {
850 /*
851 * client requests a broadcast reply OR we can't offer an IP
852 */
853 dest.sin_addr.s_addr = INADDR_BROADCAST;
854 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
855 } else if (!req->ciaddr.s_addr && msg == DHCPV4_MSG_NAK) {
856 /*
857 * client has no previous configuration -> no IP, so we need to reply
858 * with a broadcast packet
859 */
860 dest.sin_addr.s_addr = INADDR_BROADCAST;
861 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
862 } else {
863 struct arpreq arp = {.arp_flags = ATF_COM};
864
865 /*
866 * send reply to the newly (in this proccess) allocated IP
867 */
868 dest.sin_addr = reply.yiaddr;
869 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
870
871 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
872 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
873 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
874
875 if (ioctl(sock, SIOCSARP, &arp) < 0)
876 syslog(LOG_ERR, "ioctl(SIOCSARP): %m");
877 }
878
879 if (sendto(sock, &reply, PACKET_SIZE(&reply, cookie), MSG_DONTWAIT,
880 (struct sockaddr*)&dest, sizeof(dest)) < 0)
881 syslog(LOG_ERR, "Failed to send %s to %s - %s: %m",
882 dhcpv4_msg_to_string(msg),
883 dest.sin_addr.s_addr == INADDR_BROADCAST ?
884 "ff:ff:ff:ff:ff:ff": odhcpd_print_mac(req->chaddr, req->hlen),
885 inet_ntoa(dest.sin_addr));
886 else
887 syslog(LOG_NOTICE, "Sent %s to %s - %s",
888 dhcpv4_msg_to_string(msg),
889 dest.sin_addr.s_addr == INADDR_BROADCAST ?
890 "ff:ff:ff:ff:ff:ff": odhcpd_print_mac(req->chaddr, req->hlen),
891 inet_ntoa(dest.sin_addr));
892
893
894 #ifdef WITH_UBUS
895 if (msg == DHCPV4_MSG_ACK)
896 ubus_bcast_dhcp_event("dhcp.ack", req->chaddr, req->hlen, &reply.yiaddr,
897 hostname, iface->ifname);
898 #endif
899 }
900
901 static bool dhcpv4_insert_assignment(struct list_head *list, struct dhcp_assignment *a,
902 uint32_t addr)
903 {
904 uint32_t h_addr = ntohl(addr);
905 struct dhcp_assignment *c;
906
907 list_for_each_entry(c, list, head) {
908 uint32_t c_addr = ntohl(c->addr);
909
910 if (c_addr == h_addr)
911 return false;
912
913 if (c_addr > h_addr)
914 break;
915 }
916
917 /* Insert new node before c (might match list head) */
918 a->addr = addr;
919 list_add_tail(&a->head, &c->head);
920
921 return true;
922 }
923
924 static char* ip4toa(uint32_t addr)
925 {
926 static char buf[16];
927
928 snprintf(buf, sizeof(buf), "%u.%u.%u.%u",
929 ((uint8_t *)&addr)[0], ((uint8_t *)&addr)[1],
930 ((uint8_t *)&addr)[2], ((uint8_t *)&addr)[3]);
931
932 return buf;
933 }
934
935 static bool dhcpv4_assign(struct interface *iface, struct dhcp_assignment *a,
936 uint32_t raddr)
937 {
938 uint32_t start = ntohl(iface->dhcpv4_start_ip.s_addr);
939 uint32_t end = ntohl(iface->dhcpv4_end_ip.s_addr);
940 uint32_t count = end - start + 1;
941 uint32_t seed = 0;
942 bool assigned;
943
944 /* Preconfigured IP address by static lease */
945 if (a->addr) {
946 assigned = dhcpv4_insert_assignment(&iface->dhcpv4_assignments,
947 a, a->addr);
948
949 if (assigned)
950 syslog(LOG_INFO, "Assigning static IP: %s", ip4toa(a->addr));
951
952 return assigned;
953 }
954
955 /* try to assign the IP the client asked for */
956 if (start <= ntohl(raddr) && ntohl(raddr) <= end &&
957 !config_find_lease_by_ipaddr(raddr)) {
958 assigned = dhcpv4_insert_assignment(&iface->dhcpv4_assignments,
959 a, raddr);
960
961 if (assigned) {
962 syslog(LOG_INFO, "Assigning the IP the client asked for: %s",
963 ip4toa(a->addr));
964
965 return true;
966 }
967 }
968
969 /* Seed RNG with checksum of hwaddress */
970 for (size_t i = 0; i < sizeof(a->hwaddr); ++i) {
971 /* Knuth's multiplicative method */
972 uint8_t o = a->hwaddr[i];
973 seed += (o*2654435761) % UINT32_MAX;
974 }
975
976 srand(seed);
977
978 for (uint32_t i = 0, try = (((uint32_t)rand()) % count) + start; i < count;
979 ++i, try = (((try - start) + 1) % count) + start) {
980 uint32_t n_try = htonl(try);
981
982 if (config_find_lease_by_ipaddr(n_try))
983 continue;
984
985 assigned = dhcpv4_insert_assignment(&iface->dhcpv4_assignments,
986 a, n_try);
987
988 if (assigned) {
989 syslog(LOG_INFO, "Assigning mapped IP: %s (try %u of %u)",
990 ip4toa(a->addr), i + 1, count);
991
992 return true;
993 }
994 }
995
996 syslog(LOG_WARNING, "Can't assign any IP address -> address space is full");
997 return false;
998 }
999
1000
1001 static struct dhcp_assignment*
1002 dhcpv4_lease(struct interface *iface, enum dhcpv4_msg msg, const uint8_t *mac,
1003 const uint32_t reqaddr, uint32_t *leasetime, const char *hostname,
1004 const size_t hostname_len, const bool accept_fr_nonce, bool *incl_fr_opt,
1005 uint32_t *fr_serverid, const char* reqopts, const size_t reqopts_len)
1006 {
1007 struct dhcp_assignment *a = find_assignment_by_hwaddr(iface, mac);
1008 struct lease *l = config_find_lease_by_mac(mac);
1009 time_t now = odhcpd_time();
1010
1011 if (l && a && a->lease != l) {
1012 free_assignment(a);
1013 a = NULL;
1014 }
1015
1016 if (a && (a->flags & OAF_BOUND) && a->fr_ip) {
1017 *fr_serverid = a->fr_ip->addr.addr.in.s_addr;
1018 dhcpv4_fr_stop(a);
1019 }
1020
1021 if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
1022 bool assigned = !!a;
1023
1024 if (!a) {
1025 if (!iface->no_dynamic_dhcp || l) {
1026 /* Create new binding */
1027 a = calloc(1, sizeof(*a));
1028 if (!a) {
1029 syslog(LOG_ERR, "Failed to calloc binding on interface %s",
1030 iface->ifname);
1031 return NULL;
1032 }
1033 memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
1034 /* Set valid time to 0 for static lease indicating */
1035 /* infinite lifetime otherwise current time */
1036 a->valid_until = l ? 0 : now;
1037 a->dhcp_free_cb = dhcpv4_free_assignment;
1038 a->iface = iface;
1039 a->flags = OAF_DHCPV4;
1040 a->addr = l ? l->ipaddr : INADDR_ANY;
1041
1042 assigned = dhcpv4_assign(iface, a, reqaddr);
1043
1044 if (l) {
1045 a->flags |= OAF_STATIC;
1046
1047 if (l->hostname)
1048 a->hostname = strdup(l->hostname);
1049
1050 if (l->leasetime)
1051 a->leasetime = l->leasetime;
1052
1053 list_add(&a->lease_list, &l->assignments);
1054 a->lease = l;
1055 }
1056 }
1057 } else if (((a->addr & iface->dhcpv4_mask.s_addr) !=
1058 (iface->dhcpv4_start_ip.s_addr & iface->dhcpv4_mask.s_addr)) &&
1059 !(a->flags & OAF_STATIC)) {
1060 list_del(&a->head);
1061 a->addr = INADDR_ANY;
1062
1063 assigned = dhcpv4_assign(iface, a, reqaddr);
1064 }
1065
1066 if (assigned) {
1067 uint32_t my_leasetime;
1068
1069 if (a->leasetime)
1070 my_leasetime = a->leasetime;
1071 else
1072 my_leasetime = iface->dhcpv4_leasetime;
1073
1074 if ((*leasetime == 0) || (my_leasetime < *leasetime))
1075 *leasetime = my_leasetime;
1076
1077 if (msg == DHCPV4_MSG_DISCOVER) {
1078 a->flags &= ~OAF_BOUND;
1079
1080 *incl_fr_opt = accept_fr_nonce;
1081 if (!(a->flags & OAF_STATIC))
1082 a->valid_until = now;
1083 } else {
1084 if ((!(a->flags & OAF_STATIC) || !a->hostname) && hostname_len > 0) {
1085 a->hostname = realloc(a->hostname, hostname_len + 1);
1086 if (a->hostname) {
1087 memcpy(a->hostname, hostname, hostname_len);
1088 a->hostname[hostname_len] = 0;
1089
1090 if (odhcpd_valid_hostname(a->hostname))
1091 a->flags &= ~OAF_BROKEN_HOSTNAME;
1092 else
1093 a->flags |= OAF_BROKEN_HOSTNAME;
1094 }
1095 }
1096
1097 if (reqopts_len > 0) {
1098 a->reqopts = realloc(a->reqopts, reqopts_len + 1);
1099 if (a->reqopts) {
1100 memcpy(a->reqopts, reqopts, reqopts_len);
1101 a->reqopts[reqopts_len] = 0;
1102 }
1103 }
1104
1105 if (!(a->flags & OAF_BOUND)) {
1106 a->accept_fr_nonce = accept_fr_nonce;
1107 *incl_fr_opt = accept_fr_nonce;
1108 odhcpd_urandom(a->key, sizeof(a->key));
1109 a->flags |= OAF_BOUND;
1110 } else
1111 *incl_fr_opt = false;
1112
1113 if (!(a->flags & OAF_STATIC))
1114 a->valid_until = ((*leasetime == UINT32_MAX) ? 0 : (time_t)(now + *leasetime));
1115 }
1116 } else if (!assigned && a) {
1117 /* Cleanup failed assignment */
1118 free_assignment(a);
1119 a = NULL;
1120 }
1121
1122 } else if (msg == DHCPV4_MSG_RELEASE && a) {
1123 a->flags &= ~OAF_BOUND;
1124
1125 if (!(a->flags & OAF_STATIC))
1126 a->valid_until = now - 1;
1127
1128 } else if (msg == DHCPV4_MSG_DECLINE && a) {
1129 a->flags &= ~OAF_BOUND;
1130
1131 if (!(a->flags & OAF_STATIC)) {
1132 memset(a->hwaddr, 0, sizeof(a->hwaddr));
1133 a->valid_until = now + 3600; /* Block address for 1h */
1134 }
1135 }
1136
1137 dhcpv6_ia_write_statefile();
1138
1139 return a;
1140 }