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