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