Disable debugging by default
[project/odhcpd.git] / src / dhcpv4.c
1 /**
2  * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License v2 as published by
6  * the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  *
14  */
15
16 #include <time.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20 #include <stddef.h>
21 #include <stdlib.h>
22 #include <resolv.h>
23 #include <net/if.h>
24 #include <net/if_arp.h>
25 #include <netinet/ip.h>
26 #include <sys/ioctl.h>
27 #include <sys/timerfd.h>
28 #include <arpa/inet.h>
29
30 #include "odhcpd.h"
31 #include "dhcpv4.h"
32 #include "dhcpv6.h"
33
34
35 static void handle_dhcpv4(void *addr, void *data, size_t len,
36                 struct interface *iface);
37 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
38                 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
39                 const char *hostname);
40
41 // Magic option for hnet internal (4B enterprise ID, 1B data-len, 1B subopt-code, 1B subopt-len)
42 static uint8_t hnet_internal_data[7] = {0x00, 0x00, 0x76, 0xfe, 2, 1, 0};
43
44 // Create socket and register events
45 int init_dhcpv4(void)
46 {
47         return 0;
48 }
49
50
51 int setup_dhcpv4_interface(struct interface *iface, bool enable)
52 {
53         if (iface->dhcpv4_event.uloop.fd > 0) {
54                 uloop_fd_delete(&iface->dhcpv4_event.uloop);
55                 close(iface->dhcpv4_event.uloop.fd);
56                 iface->dhcpv4_event.uloop.fd = -1;
57         }
58
59         if (iface->dhcpv4 && enable) {
60                 if (!iface->dhcpv4_assignments.next)
61                         INIT_LIST_HEAD(&iface->dhcpv4_assignments);
62
63                 int sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
64                 if (sock < 0) {
65                         syslog(LOG_ERR, "Failed to create DHCPv4 server socket: %s",
66                                         strerror(errno));
67                         return -1;
68                 }
69
70                 // Basic IPv6 configuration
71                 int val = 1;
72                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
73                 setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val));
74                 setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &val, sizeof(val));
75
76                 val = IPTOS_PREC_INTERNETCONTROL;
77                 setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val));
78
79                 val = IP_PMTUDISC_DONT;
80                 setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
81
82                 setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE,
83                                 iface->ifname, strlen(iface->ifname));
84
85                 struct sockaddr_in bind_addr = {AF_INET, htons(DHCPV4_SERVER_PORT),
86                                         {INADDR_ANY}, {0}};
87
88                 if (bind(sock, (struct sockaddr*)&bind_addr, sizeof(bind_addr))) {
89                         syslog(LOG_ERR, "Failed to open DHCPv4 server socket: %s",
90                                         strerror(errno));
91                         return -1;
92                 }
93
94
95                 if (ntohl(iface->dhcpv4_start.s_addr) > ntohl(iface->dhcpv4_end.s_addr)) {
96                         syslog(LOG_ERR, "Invalid DHCP range");
97                         return -1;
98                 }
99
100                 // Create a range if not specified
101                 struct ifreq ifreq;
102                 strncpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
103
104                 struct sockaddr_in *saddr = (struct sockaddr_in*)&ifreq.ifr_addr;
105                 struct sockaddr_in *smask = (struct sockaddr_in*)&ifreq.ifr_netmask;
106                 if (!(iface->dhcpv4_start.s_addr & htonl(0xffff0000)) &&
107                                 !(iface->dhcpv4_end.s_addr & htonl(0xffff0000)) &&
108                                 !ioctl(sock, SIOCGIFADDR, &ifreq)) {
109                         struct in_addr addr = saddr->sin_addr;
110
111                         ioctl(sock, SIOCGIFNETMASK, &ifreq);
112                         struct in_addr mask = smask->sin_addr;
113
114                         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
115                         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
116
117                         if (start && end && start < end &&
118                                         start > ntohl(addr.s_addr & ~mask.s_addr) &&
119                                         (start & ntohl(mask.s_addr)) == start &&
120                                         (end & ntohl(mask.s_addr)) == end) {
121                                 iface->dhcpv4_start.s_addr = htonl(start) |
122                                                 (addr.s_addr & mask.s_addr);
123                                 iface->dhcpv4_end.s_addr = htonl(end) |
124                                                 (addr.s_addr & mask.s_addr);
125                         } else if (ntohl(mask.s_addr) <= 0xffffffc0) {
126                                 start = addr.s_addr & mask.s_addr;
127                                 end = addr.s_addr & mask.s_addr;
128
129                                 if (ntohl(mask.s_addr) <= 0xffffff00) {
130                                         iface->dhcpv4_start.s_addr = start | htonl(100);
131                                         iface->dhcpv4_end.s_addr = end | htonl(250);
132                                 } else {
133                                         iface->dhcpv4_start.s_addr = start | htonl(10);
134                                         iface->dhcpv4_end.s_addr = end | htonl(59);
135                                 }
136                         }
137
138
139                 }
140
141                 // Parse static entries
142                 struct lease *lease;
143                 list_for_each_entry(lease, &leases, head) {
144                         // Construct entry
145                         size_t hostlen = strlen(lease->hostname) + 1;
146                         struct dhcpv4_assignment *a = calloc(1, sizeof(*a) + hostlen);
147                         if (!a) {
148                                 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
149                                         iface->ifname);
150                                 return -1;
151                         }
152                         a->addr = ntohl(lease->ipaddr.s_addr);
153                         memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
154                         memcpy(a->hostname, lease->hostname, hostlen);
155
156                         // Assign to all interfaces
157                         struct dhcpv4_assignment *c;
158                         list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
159                                 if (c->addr > a->addr) {
160                                         list_add_tail(&a->head, &c->head);
161                                 } else if (c->addr == a->addr) {
162                                         // Already an assignment with that number
163                                         break;
164                                 }
165                         }
166
167                         if (!a->head.next)
168                                 free(a);
169                 }
170
171                 // Clean invalid assignments
172                 struct dhcpv4_assignment *a, *n;
173                 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
174                         if ((htonl(a->addr) & smask->sin_addr.s_addr) !=
175                                         (saddr->sin_addr.s_addr & smask->sin_addr.s_addr)) {
176                                 list_del(&a->head);
177                                 free(a);
178                         }
179                 }
180
181
182                 if (iface->dhcpv4_leasetime < 60)
183                         iface->dhcpv4_leasetime = 43200;
184
185                 iface->dhcpv4_event.uloop.fd = sock;
186                 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
187                 odhcpd_register(&iface->dhcpv4_event);
188         } else if (iface->dhcpv4_assignments.next) {
189                 while (!list_empty(&iface->dhcpv4_assignments)) {
190                         struct dhcpv4_assignment *a = list_first_entry(&iface->dhcpv4_assignments,
191                                         struct dhcpv4_assignment, head);
192                         list_del(&a->head);
193                         free(a->hostname);
194                         free(a);
195                 }
196
197         }
198         return 0;
199 }
200
201
202 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
203                 uint8_t type, uint8_t len, const void *data)
204 {
205         uint8_t *c = *cookie;
206         if (*cookie + 2 + len > (uint8_t*)&msg[1])
207                 return;
208
209         *c++ = type;
210         *c++ = len;
211         memcpy(c, data, len);
212
213         *cookie = c + len;
214 }
215
216
217 // Simple DHCPv6-server for information requests
218 static void handle_dhcpv4(void *addr, void *data, size_t len,
219                 struct interface *iface)
220 {
221         if (!iface->dhcpv4)
222                 return;
223
224         struct dhcpv4_message *req = data;
225         if (len < offsetof(struct dhcpv4_message, options) + 4 ||
226                         req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
227                 return;
228
229         int sock = iface->dhcpv4_event.uloop.fd;
230         struct sockaddr_in ifaddr;
231         struct sockaddr_in ifnetmask;
232
233         syslog(LOG_NOTICE, "Got DHCPv4 request");
234
235         struct ifreq ifreq;
236         memcpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
237         if (ioctl(sock, SIOCGIFADDR, &ifreq)) {
238                 syslog(LOG_WARNING, "DHCPv4 failed to detect address: %s", strerror(errno));
239                 return;
240         }
241
242         memcpy(&ifaddr, &ifreq.ifr_addr, sizeof(ifaddr));
243         if (ioctl(sock, SIOCGIFNETMASK, &ifreq))
244                 return;
245
246         memcpy(&ifnetmask, &ifreq.ifr_netmask, sizeof(ifnetmask));
247         uint32_t network = ifaddr.sin_addr.s_addr & ifnetmask.sin_addr.s_addr;
248
249         if ((iface->dhcpv4_start.s_addr & ifnetmask.sin_addr.s_addr) != network ||
250                         (iface->dhcpv4_end.s_addr & ifnetmask.sin_addr.s_addr) != network) {
251                 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
252                 return;
253         }
254
255         struct ifreq ifr = {.ifr_name = ""};
256         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
257
258         struct dhcpv4_message reply = {
259                 .op = DHCPV4_BOOTREPLY,
260                 .htype = 1,
261                 .hlen = 6,
262                 .hops = 0,
263                 .xid = req->xid,
264                 .secs = 0,
265                 .flags = req->flags,
266                 .ciaddr = {INADDR_ANY},
267                 .giaddr = req->giaddr,
268                 .siaddr = ifaddr.sin_addr,
269         };
270         memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
271
272         reply.options[0] = 0x63;
273         reply.options[1] = 0x82;
274         reply.options[2] = 0x53;
275         reply.options[3] = 0x63;
276
277         uint8_t *cookie = &reply.options[4];
278         uint8_t reqmsg = DHCPV4_MSG_REQUEST;
279         uint8_t msg = DHCPV4_MSG_ACK;
280
281         struct in_addr reqaddr = {INADDR_ANY};
282         char hostname[256];
283         hostname[0] = 0;
284
285         uint8_t *start = &req->options[4];
286         uint8_t *end = ((uint8_t*)data) + len;
287         struct dhcpv4_option *opt;
288         dhcpv4_for_each_option(start, end, opt) {
289                 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1) {
290                         reqmsg = opt->data[0];
291                 } else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
292                         memcpy(hostname, opt->data, opt->len);
293                         hostname[opt->len] = 0;
294                 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4) {
295                         memcpy(&reqaddr, opt->data, 4);
296                 } else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
297                         if (memcmp(opt->data, &ifaddr.sin_addr, 4))
298                                 return;
299                 } else if (opt->type == DHCPV4_OPT_VENDOR_SPECIFIC_INFORMATION &&
300                                 opt->len == sizeof(hnet_internal_data)) {
301                         if (!memcmp(opt->data, hnet_internal_data, sizeof(hnet_internal_data)))
302                                 return; // Ignoring hnet internal routers
303                 }
304         }
305
306         if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
307                         reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
308                         reqmsg != DHCPV4_MSG_RELEASE)
309                 return;
310
311         struct dhcpv4_assignment *lease = NULL;
312         if (reqmsg != DHCPV4_MSG_INFORM)
313                 lease = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr, hostname);
314
315         if (!lease) {
316                 if (reqmsg == DHCPV4_MSG_REQUEST)
317                         msg = DHCPV4_MSG_NAK;
318                 else if (reqmsg == DHCPV4_MSG_DISCOVER)
319                         return;
320         } else if (reqmsg == DHCPV4_MSG_DISCOVER) {
321                 msg = DHCPV4_MSG_OFFER;
322         }
323
324         if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
325                 return;
326
327         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
328         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, &ifaddr.sin_addr);
329
330         if (lease) {
331                 reply.yiaddr.s_addr = htonl(lease->addr);
332
333                 uint32_t val = htonl(iface->dhcpv4_leasetime);
334                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
335
336                 val = htonl(500 * iface->dhcpv4_leasetime / 1000);
337                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
338
339                 val = htonl(875 * iface->dhcpv4_leasetime / 1000);
340                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
341
342                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &ifnetmask.sin_addr);
343
344                 if (lease->hostname[0])
345                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
346                                         strlen(lease->hostname), lease->hostname);
347
348                 if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
349                         struct sockaddr_in *ina = (struct sockaddr_in*)&ifr.ifr_broadaddr;
350                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &ina->sin_addr);
351                 }
352         }
353
354         if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
355                 uint16_t mtu = htons(ifr.ifr_mtu);
356                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
357         }
358
359         if (iface->search) {
360                 char b[256];
361                 if (dn_expand(iface->search, iface->search + iface->search_len,
362                                 iface->search, b, sizeof(b)) > 0)
363                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DOMAIN, strlen(b), b);
364         } else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
365                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DOMAIN,
366                                 strlen(_res.dnsrch[0]), _res.dnsrch[0]);
367         }
368
369         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &ifaddr.sin_addr);
370
371
372
373         if (iface->dhcpv4_dns_cnt == 0)
374                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &ifaddr.sin_addr);
375         else
376                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
377                                 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
378
379
380         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
381
382         struct sockaddr_in dest = *((struct sockaddr_in*)addr);
383         if (req->giaddr.s_addr) {
384                 dest.sin_addr = req->giaddr;
385                 dest.sin_port = htons(DHCPV4_SERVER_PORT);
386         } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
387                 dest.sin_addr = req->ciaddr;
388                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
389         } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
390                         req->hlen != reply.hlen) {
391                 dest.sin_addr.s_addr = INADDR_BROADCAST;
392                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
393         } else {
394                 dest.sin_addr = reply.yiaddr;
395                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
396
397                 struct arpreq arp = {.arp_flags = ATF_COM};
398                 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
399                 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
400                 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
401                 ioctl(sock, SIOCSARP, &arp);
402         }
403
404         sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
405                         (struct sockaddr*)&dest, sizeof(dest));
406 }
407
408
409 static bool dhcpv4_assign(struct interface *iface,
410                 struct dhcpv4_assignment *assign, uint32_t raddr)
411 {
412         const unsigned tries = 10;
413         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
414         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
415         uint32_t count = end - start + 1;
416
417         // Seed RNG with checksum of DUID
418         uint32_t seed = 0;
419         for (size_t i = 0; i < sizeof(assign->hwaddr); ++i)
420                 seed += assign->hwaddr[i];
421         srand(seed);
422
423         // Try to assign up to 100x
424         for (unsigned i = 0; i < tries; ++i) {
425                 uint32_t try = (((uint32_t)rand()) % count) + start;
426                 if (i == 0 && raddr >= start && raddr <= end)
427                         try = raddr;
428                 else if (i == tries - 1)
429                         try = start;
430
431                 if (list_empty(&iface->dhcpv4_assignments)) {
432                         assign->addr = try;
433                         list_add(&assign->head, &iface->dhcpv4_assignments);
434                         return true;
435                 }
436
437                 struct dhcpv4_assignment *c;
438                 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
439                         if (c->addr > try) {
440                                 assign->addr = try;
441                                 list_add_tail(&assign->head, &c->head);
442                                 return true;
443                         } else if (c->addr == try) {
444                                 if (i < tries - 1)
445                                         break;
446                                 else
447                                         ++try;
448                         }
449                 }
450         }
451
452         return false;
453 }
454
455
456 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
457                 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
458                 const char *hostname)
459 {
460         struct dhcpv4_assignment *lease = NULL;
461         uint32_t raddr = ntohl(reqaddr.s_addr);
462         time_t now = odhcpd_time();
463
464         struct dhcpv4_assignment *c, *n, *a = NULL;
465         list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
466                 if (c->addr == raddr && !memcmp(c->hwaddr, mac, 6)) {
467                         a = c;
468                         break;
469                 } else if (c->valid_until < now) {
470                         list_del(&c->head);
471                         free(c);
472                 }
473         }
474
475         bool update_state = false;
476         if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
477                 bool assigned = !!a;
478                 size_t hostlen = strlen(hostname) + 1;
479
480                 if (!a && !iface->no_dynamic_dhcp) { // Create new binding
481                         a = calloc(1, sizeof(*a) + hostlen);
482                         if (!a) {
483                                 syslog(LOG_ERR, "Failed to calloc binding on interface %s", iface->ifname);
484                                 return NULL;
485                         }
486                         memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
487                         memcpy(a->hostname, hostname, hostlen);
488
489                         assigned = dhcpv4_assign(iface, a, raddr);
490                 }
491
492                 if (assigned && !a->hostname[0] && hostname) {
493                         a = realloc(a, sizeof(*a) + hostlen);
494                         if (!a) {
495                                 syslog(LOG_ERR, "Failed to realloc binding on interface %s", iface->ifname);
496                                 return NULL;
497                         }
498                         memcpy(a->hostname, hostname, hostlen);
499
500                         // Fixup list
501                         a->head.next->prev = &a->head;
502                         a->head.prev->next = &a->head;
503                 }
504
505                 // Was only a solicitation: mark binding for removal
506                 if (assigned && a->valid_until < now) {
507                         a->valid_until = (msg == DHCPV4_MSG_DISCOVER) ? 0 :
508                                         (now + iface->dhcpv4_leasetime);
509                 } else if (!assigned && a) { // Cleanup failed assignment
510                         free(a);
511                         a = NULL;
512                 }
513
514                 if (assigned && a)
515                         lease = a;
516         } else if (msg == DHCPV4_MSG_RELEASE) {
517                 if (a) {
518                         a->valid_until = 0;
519                         update_state = true;
520                 }
521         } else if (msg == DHCPV4_MSG_DECLINE) {
522                 memset(a->hwaddr, 0, sizeof(a->hwaddr));
523                 a->valid_until = now + 3600; // Block address for 1h
524                 update_state = true;
525         }
526
527         if (update_state)
528                 dhcpv6_write_statefile();
529
530         return lease;
531 }
532