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