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