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