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