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