Readd fixed ICMPv6 validity check
[project/odhcpd.git] / src / dhcpv6-ia.c
1 /**
2  * Copyright (C) 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 #include "odhcpd.h"
16 #include "dhcpv6.h"
17 #include "dhcpv4.h"
18 #include "md5.h"
19
20 #include <time.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <alloca.h>
24 #include <resolv.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <arpa/inet.h>
29 #include <sys/timerfd.h>
30
31
32 static void update(struct interface *iface);
33 static void reconf_timer(struct uloop_timeout *event);
34 static struct uloop_timeout reconf_event = {.cb = reconf_timer};
35 static int socket_fd = -1;
36 static uint32_t serial = 0;
37
38
39 int dhcpv6_ia_init(int dhcpv6_socket)
40 {
41         socket_fd = dhcpv6_socket;
42         uloop_timeout_set(&reconf_event, 2000);
43         return 0;
44 }
45
46
47 int setup_dhcpv6_ia_interface(struct interface *iface, bool enable)
48 {
49         if (!enable && iface->ia_assignments.next) {
50                 struct dhcpv6_assignment *c;
51                 while (!list_empty(&iface->ia_assignments)) {
52                         c = list_first_entry(&iface->ia_assignments, struct dhcpv6_assignment, head);
53                         list_del(&c->head);
54                         free(c->hostname);
55                         free(c->classes);
56                         free(c);
57                 }
58         }
59
60         if (iface->dhcpv6 == RELAYD_SERVER) {
61                 if (!iface->ia_assignments.next)
62                         INIT_LIST_HEAD(&iface->ia_assignments);
63
64                 if (list_empty(&iface->ia_assignments)) {
65                         struct dhcpv6_assignment *border = calloc(1, sizeof(*border));
66                         if (!border) {
67                                 syslog(LOG_ERR, "Calloc failed for border on interface %s", iface->ifname);
68                                 return -1;
69                         }
70                         
71                         border->length = 64;
72                         list_add(&border->head, &iface->ia_assignments);
73                 }
74
75                 update(iface);
76
77                 // Parse static entries
78                 struct lease *lease;
79                 list_for_each_entry(lease, &leases, head) {
80                         // Construct entry
81                         struct dhcpv6_assignment *a = calloc(1, sizeof(*a) + lease->duid_len);
82                         if (!a) {
83                                 syslog(LOG_ERR, "Calloc failed for static lease assignment on interface %s",
84                                         iface->ifname);
85                                 return -1;
86                         }
87
88                         a->clid_len = lease->duid_len;
89                         a->length = 128;
90                         a->assigned = lease->hostid;
91                         odhcpd_urandom(a->key, sizeof(a->key));
92                         memcpy(a->clid_data, lease->duid, a->clid_len);
93                         memcpy(a->mac, lease->mac.ether_addr_octet, sizeof(a->mac));
94
95                         // Assign to all interfaces
96                         struct dhcpv6_assignment *c;
97                         list_for_each_entry(c, &iface->ia_assignments, head) {
98                                 if (c->length != 128 || c->assigned > a->assigned) {
99                                         list_add_tail(&a->head, &c->head);
100                                 } else if (c->assigned == a->assigned) {
101                                         // Already an assignment with that number
102                                         break;
103                                 }
104                         }
105
106                         if (a->head.next) {
107                                 if (lease->hostname[0]) {
108                                         free(a->hostname);
109                                         a->hostname = strdup(lease->hostname);
110                                 }
111                         } else {
112                                 free(a->classes);
113                                 free(a->hostname);
114                                 free(a);
115                         }
116                 }
117         }
118         return 0;
119 }
120
121
122 static int send_reconf(struct interface *iface, struct dhcpv6_assignment *assign)
123 {
124         struct {
125                 struct dhcpv6_client_header hdr;
126                 uint16_t srvid_type;
127                 uint16_t srvid_len;
128                 uint16_t duid_type;
129                 uint16_t hardware_type;
130                 uint8_t mac[6];
131                 uint16_t msg_type;
132                 uint16_t msg_len;
133                 uint8_t msg_id;
134                 struct dhcpv6_auth_reconfigure auth;
135                 uint16_t clid_type;
136                 uint16_t clid_len;
137                 uint8_t clid_data[128];
138         } __attribute__((packed)) reconf_msg = {
139                 .hdr = {DHCPV6_MSG_RECONFIGURE, {0, 0, 0}},
140                 .srvid_type = htons(DHCPV6_OPT_SERVERID),
141                 .srvid_len = htons(10),
142                 .duid_type = htons(3),
143                 .hardware_type = htons(1),
144                 .msg_type = htons(DHCPV6_OPT_RECONF_MSG),
145                 .msg_len = htons(1),
146                 .msg_id = DHCPV6_MSG_RENEW,
147                 .auth = {htons(DHCPV6_OPT_AUTH),
148                                 htons(sizeof(reconf_msg.auth) - 4), 3, 1, 0,
149                                 {htonl(time(NULL)), htonl(++serial)}, 2, {0}},
150                 .clid_type = htons(DHCPV6_OPT_CLIENTID),
151                 .clid_len = htons(assign->clid_len),
152                 .clid_data = {0},
153         };
154
155         odhcpd_get_mac(iface, reconf_msg.mac);
156         memcpy(reconf_msg.clid_data, assign->clid_data, assign->clid_len);
157         struct iovec iov = {&reconf_msg, sizeof(reconf_msg) - 128 + assign->clid_len};
158
159         md5_ctx_t md5;
160         uint8_t secretbytes[16];
161         memcpy(secretbytes, assign->key, sizeof(secretbytes));
162
163         for (size_t i = 0; i < sizeof(secretbytes); ++i)
164                 secretbytes[i] ^= 0x36;
165
166         md5_begin(&md5);
167         md5_hash(secretbytes, sizeof(secretbytes), &md5);
168         md5_hash(iov.iov_base, iov.iov_len, &md5);
169         md5_end(reconf_msg.auth.key, &md5);
170
171         for (size_t i = 0; i < sizeof(secretbytes); ++i) {
172                 secretbytes[i] ^= 0x36;
173                 secretbytes[i] ^= 0x5c;
174         }
175
176         md5_begin(&md5);
177         md5_hash(secretbytes, sizeof(secretbytes), &md5);
178         md5_hash(reconf_msg.auth.key, 16, &md5);
179         md5_end(reconf_msg.auth.key, &md5);
180
181         return odhcpd_send(socket_fd, &assign->peer, &iov, 1, iface);
182 }
183
184
185 void dhcpv6_write_statefile(void)
186 {
187         if (config.dhcp_statefile) {
188                 time_t now = odhcpd_time(), wall_time = time(NULL);
189                 int fd = open(config.dhcp_statefile, O_CREAT | O_WRONLY | O_CLOEXEC, 0644);
190                 if (fd < 0)
191                         return;
192
193                 lockf(fd, F_LOCK, 0);
194                 ftruncate(fd, 0);
195
196                 FILE *fp = fdopen(fd, "w");
197                 if (!fp) {
198                         close(fd);
199                         return;
200                 }
201
202                 struct interface *iface;
203                 list_for_each_entry(iface, &interfaces, head) {
204                         if (iface->dhcpv6 != RELAYD_SERVER && iface->dhcpv4 != RELAYD_SERVER)
205                                 continue;
206
207                         if (iface->dhcpv6 == RELAYD_SERVER) {
208                                 struct dhcpv6_assignment *c;
209                                 list_for_each_entry(c, &iface->ia_assignments, head) {
210                                         if (c->clid_len == 0)
211                                                 continue;
212
213                                         char ipbuf[INET6_ADDRSTRLEN];
214                                         char leasebuf[512];
215                                         char duidbuf[264];
216                                         odhcpd_hexlify(duidbuf, c->clid_data, c->clid_len);
217
218                                         // iface DUID iaid hostname lifetime assigned length [addrs...]
219                                         int l = snprintf(leasebuf, sizeof(leasebuf), "# %s %s %x %s %u %x %u ",
220                                                         iface->ifname, duidbuf, ntohl(c->iaid),
221                                                         (c->hostname ? c->hostname : "-"),
222                                                         (unsigned)(c->valid_until > now ?
223                                                                         (c->valid_until - now + wall_time) : 0),
224                                                         c->assigned, (unsigned)c->length);
225
226                                         struct in6_addr addr;
227                                         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
228                                                 if (iface->ia_addr[i].prefix > 64)
229                                                         continue;
230
231                                                 addr = iface->ia_addr[i].addr;
232                                                 if (c->length == 128)
233                                                         addr.s6_addr32[3] = htonl(c->assigned);
234                                                 else
235                                                         addr.s6_addr32[1] |= htonl(c->assigned);
236                                                 inet_ntop(AF_INET6, &addr, ipbuf, sizeof(ipbuf) - 1);
237
238                                                 if (c->length == 128 && c->hostname && i == 0)
239                                                         fprintf(fp, "%s\t%s\n", ipbuf, c->hostname);
240
241                                                 l += snprintf(leasebuf + l, sizeof(leasebuf) - l, "%s/%hhu ", ipbuf, c->length);
242                                         }
243                                         leasebuf[l - 1] = '\n';
244                                         fwrite(leasebuf, 1, l, fp);
245                                 }
246                         }
247
248                         if (iface->dhcpv4 == RELAYD_SERVER) {
249                                 struct dhcpv4_assignment *c;
250                                 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
251                                         char ipbuf[INET6_ADDRSTRLEN];
252                                         char leasebuf[512];
253                                         char duidbuf[16];
254                                         odhcpd_hexlify(duidbuf, c->hwaddr, sizeof(c->hwaddr));
255
256                                         // iface DUID iaid hostname lifetime assigned length [addrs...]
257                                         int l = snprintf(leasebuf, sizeof(leasebuf), "# %s %s ipv4 %s %u %x 32 ",
258                                                         iface->ifname, duidbuf,
259                                                         (c->hostname ? c->hostname : "-"),
260                                                         (unsigned)(c->valid_until > now ?
261                                                                         (c->valid_until - now + wall_time) : 0),
262                                                         c->addr);
263
264                                         struct in_addr addr = {htonl(c->addr)};
265                                         inet_ntop(AF_INET, &addr, ipbuf, sizeof(ipbuf) - 1);
266
267                                         if (c->hostname[0])
268                                                 fprintf(fp, "%s\t%s\n", ipbuf, c->hostname);
269
270                                         l += snprintf(leasebuf + l, sizeof(leasebuf) - l, "%s/32 ", ipbuf);
271                                         leasebuf[l - 1] = '\n';
272                                         fwrite(leasebuf, 1, l, fp);
273                                 }
274                         }
275                 }
276
277                 fclose(fp);
278         }
279
280         if (config.dhcp_cb) {
281                 char *argv[2] = {config.dhcp_cb, NULL};
282                 if (!vfork()) {
283                         execv(argv[0], argv);
284                         _exit(128);
285                 }
286         }
287 }
288
289
290 static void apply_lease(struct interface *iface, struct dhcpv6_assignment *a, bool add)
291 {
292         if (a->length > 64)
293                 return;
294
295         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
296                 struct in6_addr prefix = iface->ia_addr[i].addr;
297                 prefix.s6_addr32[1] |= htonl(a->assigned);
298                 odhcpd_setup_route(&prefix, a->length, iface, &a->peer.sin6_addr, add);
299         }
300 }
301
302
303 static bool assign_pd(struct interface *iface, struct dhcpv6_assignment *assign)
304 {
305         struct dhcpv6_assignment *c;
306         if (iface->ia_addr_len < 1)
307                 return false;
308
309         // Try honoring the hint first
310         uint32_t current = 1, asize = (1 << (64 - assign->length)) - 1;
311         if (assign->assigned) {
312                 list_for_each_entry(c, &iface->ia_assignments, head) {
313                         if (c->length == 128)
314                                 continue;
315
316                         if (assign->assigned >= current && assign->assigned + asize < c->assigned) {
317                                 list_add_tail(&assign->head, &c->head);
318                                 apply_lease(iface, assign, true);
319                                 return true;
320                         }
321
322                         if (c->assigned != 0)
323                                 current = (c->assigned + (1 << (64 - c->length)));
324                 }
325         }
326
327         // Fallback to a variable assignment
328         current = 1;
329         list_for_each_entry(c, &iface->ia_assignments, head) {
330                 if (c->length == 128)
331                         continue;
332
333                 current = (current + asize) & (~asize);
334                 if (current + asize < c->assigned) {
335                         assign->assigned = current;
336                         list_add_tail(&assign->head, &c->head);
337                         apply_lease(iface, assign, true);
338                         return true;
339                 }
340
341                 if (c->assigned != 0)
342                         current = (c->assigned + (1 << (64 - c->length)));
343         }
344
345         return false;
346 }
347
348
349 static bool assign_na(struct interface *iface, struct dhcpv6_assignment *assign)
350 {
351         bool match = false;
352         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
353                 if (!iface->ia_addr[i].has_class) {
354                         match = true;
355                         continue;
356                 } else if (assign->classes_cnt) {
357                         for (size_t j = 0; j < assign->classes_cnt; ++j)
358                                 if (assign->classes[j] == iface->ia_addr[i].class)
359                                         match = true;
360                 } else if (assign->all_class) {
361                         match = true;
362                 }
363         }
364
365         if (!match)
366                 return false;
367
368         // Seed RNG with checksum of DUID
369         uint32_t seed = 0;
370         for (size_t i = 0; i < assign->clid_len; ++i)
371                 seed += assign->clid_data[i];
372         srand(seed);
373
374         // Try to assign up to 100x
375         for (size_t i = 0; i < 100; ++i) {
376                 uint32_t try;
377                 do try = ((uint32_t)rand()) % 0x0fff; while (try < 0x100);
378
379                 struct dhcpv6_assignment *c;
380                 list_for_each_entry(c, &iface->ia_assignments, head) {
381                         if (c->assigned > try || c->length != 128) {
382                                 assign->assigned = try;
383                                 list_add_tail(&assign->head, &c->head);
384                                 return true;
385                         } else if (c->assigned == try) {
386                                 break;
387                         }
388                 }
389         }
390
391         return false;
392 }
393
394
395 static int prefixcmp(const void *va, const void *vb)
396 {
397         const struct odhcpd_ipaddr *a = va, *b = vb;
398         uint32_t a_pref = ((a->addr.s6_addr[0] & 0xfe) != 0xfc) ? a->preferred : 1;
399         uint32_t b_pref = ((b->addr.s6_addr[0] & 0xfe) != 0xfc) ? b->preferred : 1;
400         return (a_pref < b_pref) ? 1 : (a_pref > b_pref) ? -1 : 0;
401 }
402
403
404 static void update(struct interface *iface)
405 {
406         struct odhcpd_ipaddr addr[8];
407         memset(addr, 0, sizeof(addr));
408         int len = odhcpd_get_interface_addresses(iface->ifindex, addr, 8);
409
410         if (len < 0)
411                 return;
412
413         qsort(addr, len, sizeof(*addr), prefixcmp);
414
415         time_t now = odhcpd_time();
416         int minprefix = -1;
417
418         for (int i = 0; i < len; ++i) {
419                 if (addr[i].prefix > minprefix)
420                         minprefix = addr[i].prefix;
421
422                 addr[i].addr.s6_addr32[2] = 0;
423                 addr[i].addr.s6_addr32[3] = 0;
424
425                 if (addr[i].preferred < UINT32_MAX - now)
426                         addr[i].preferred += now;
427
428                 if (addr[i].valid < UINT32_MAX - now)
429                         addr[i].valid += now;
430         }
431
432         struct dhcpv6_assignment *border = list_last_entry(&iface->ia_assignments, struct dhcpv6_assignment, head);
433         border->assigned = 1 << (64 - minprefix);
434
435         bool change = len != (int)iface->ia_addr_len;
436         for (int i = 0; !change && i < len; ++i)
437                 if (addr[i].addr.s6_addr32[0] != iface->ia_addr[i].addr.s6_addr32[0] ||
438                                 addr[i].addr.s6_addr32[1] != iface->ia_addr[i].addr.s6_addr32[1] ||
439                                 (addr[i].preferred > 0) != (iface->ia_addr[i].preferred > 0) ||
440                                 (addr[i].valid > (uint32_t)now + 7200) !=
441                                                 (iface->ia_addr[i].valid > (uint32_t)now + 7200))
442                         change = true;
443
444         if (change) {
445                 struct dhcpv6_assignment *c;
446                 list_for_each_entry(c, &iface->ia_assignments, head)
447                         if (c != border)
448                                 apply_lease(iface, c, false);
449         }
450
451         memcpy(iface->ia_addr, addr, len * sizeof(*addr));
452         iface->ia_addr_len = len;
453
454         if (change) { // Addresses / prefixes have changed
455                 struct list_head reassign = LIST_HEAD_INIT(reassign);
456                 struct dhcpv6_assignment *c, *d;
457                 list_for_each_entry_safe(c, d, &iface->ia_assignments, head) {
458                         if (c->clid_len == 0 || c->valid_until < now)
459                                 continue;
460
461                         if (c->length < 128 && c->assigned >= border->assigned && c != border)
462                                 list_move(&c->head, &reassign);
463                         else if (c != border)
464                                 apply_lease(iface, c, true);
465
466                         if (c->accept_reconf && c->reconf_cnt == 0) {
467                                 c->reconf_cnt = 1;
468                                 c->reconf_sent = now;
469                                 send_reconf(iface, c);
470
471                                 // Leave all other assignments of that client alone
472                                 struct dhcpv6_assignment *a;
473                                 list_for_each_entry(a, &iface->ia_assignments, head)
474                                         if (a != c && a->clid_len == c->clid_len &&
475                                                         !memcmp(a->clid_data, c->clid_data, a->clid_len))
476                                                 c->reconf_cnt = INT_MAX;
477                         }
478                 }
479
480                 while (!list_empty(&reassign)) {
481                         c = list_first_entry(&reassign, struct dhcpv6_assignment, head);
482                         list_del(&c->head);
483                         if (!assign_pd(iface, c)) {
484                                 c->assigned = 0;
485                                 list_add(&c->head, &iface->ia_assignments);
486                         }
487                 }
488
489                 dhcpv6_write_statefile();
490         }
491 }
492
493
494 static void reconf_timer(struct uloop_timeout *event)
495 {
496         time_t now = odhcpd_time();
497         struct interface *iface;
498         list_for_each_entry(iface, &interfaces, head) {
499                 if (iface->dhcpv6 != RELAYD_SERVER || iface->ia_assignments.next == NULL)
500                         continue;
501
502                 struct dhcpv6_assignment *a, *n;
503                 list_for_each_entry_safe(a, n, &iface->ia_assignments, head) {
504                         if (a->valid_until < now) {
505                                 if ((a->length < 128 && a->clid_len > 0) ||
506                                                 (a->length == 128 && a->clid_len == 0)) {
507                                         list_del(&a->head);
508                                         free(a->classes);
509                                         free(a->hostname);
510                                         free(a);
511                                 }
512                         } else if (a->reconf_cnt > 0 && a->reconf_cnt < 8 &&
513                                         now > a->reconf_sent + (1 << a->reconf_cnt)) {
514                                 ++a->reconf_cnt;
515                                 a->reconf_sent = now;
516                                 send_reconf(iface, a);
517                         }
518                 }
519
520                 if (iface->ia_reconf) {
521                         update(iface);
522                         iface->ia_reconf = false;
523                 }
524         }
525
526         uloop_timeout_set(event, 2000);
527 }
528
529
530 static size_t append_reply(uint8_t *buf, size_t buflen, uint16_t status,
531                 const struct dhcpv6_ia_hdr *ia, struct dhcpv6_assignment *a,
532                 struct interface *iface, bool request)
533 {
534         if (buflen < sizeof(*ia) + sizeof(struct dhcpv6_ia_prefix))
535                 return 0;
536
537         struct dhcpv6_ia_hdr out = {ia->type, 0, ia->iaid, 0, 0};
538         size_t datalen = sizeof(out);
539         time_t now = odhcpd_time();
540
541         if (status) {
542                 struct __attribute__((packed)) {
543                         uint16_t type;
544                         uint16_t len;
545                         uint16_t value;
546                 } stat = {htons(DHCPV6_OPT_STATUS), htons(sizeof(stat) - 4),
547                                 htons(status)};
548
549                 memcpy(buf + datalen, &stat, sizeof(stat));
550                 datalen += sizeof(stat);
551         } else {
552                 if (a) {
553                         uint32_t pref = 3600;
554                         uint32_t valid = 3600;
555                         bool have_non_ula = false;
556                         for (size_t i = 0; i < iface->ia_addr_len; ++i)
557                                 if ((iface->ia_addr[i].addr.s6_addr[0] & 0xfe) != 0xfc)
558                                         have_non_ula = true;
559
560                         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
561                                 bool match = true;
562                                 if (iface->ia_addr[i].has_class) {
563                                         match = false;
564                                         if (a->classes_cnt) {
565                                                 for (size_t j = 0; j < a->classes_cnt; ++j)
566                                                         if (a->classes[j] == iface->ia_addr[i].class)
567                                                                 match = true;
568                                         } else if (a->all_class) {
569                                                 match = true;
570                                         }
571                                 }
572
573                                 if (!match)
574                                         continue;
575
576                                 uint32_t prefix_pref = iface->ia_addr[i].preferred - now;
577                                 uint32_t prefix_valid = iface->ia_addr[i].valid - now;
578
579                                 if (iface->ia_addr[i].prefix > 64 ||
580                                                 iface->ia_addr[i].preferred <= (uint32_t)now)
581                                         continue;
582
583                                 // ULA-deprecation compatibility workaround
584                                 if ((iface->ia_addr[i].addr.s6_addr[0] & 0xfe) == 0xfc &&
585                                                 a->length == 128 && have_non_ula &&
586                                                 iface->deprecate_ula_if_public_avail)
587                                         continue;
588
589                                 if (prefix_pref > 86400)
590                                         prefix_pref = 86400;
591
592                                 if (prefix_valid > 86400)
593                                         prefix_valid = 86400;
594
595 #ifdef DHCPV6_OPT_PREFIX_CLASS
596                                 struct {
597                                         uint16_t code;
598                                         uint16_t length;
599                                         uint16_t class;
600                                 } pclass = {htons(DHCPV6_OPT_PREFIX_CLASS),
601                                         htons(2), htons(iface->ia_addr[i].class)};
602 #endif
603
604                                 if (a->length < 128) {
605                                         struct dhcpv6_ia_prefix p = {
606                                                 .type = htons(DHCPV6_OPT_IA_PREFIX),
607                                                 .len = htons(sizeof(p) - 4),
608                                                 .preferred = htonl(prefix_pref),
609                                                 .valid = htonl(prefix_valid),
610                                                 .prefix = a->length,
611                                                 .addr = iface->ia_addr[i].addr
612                                         };
613                                         p.addr.s6_addr32[1] |= htonl(a->assigned);
614                                         size_t entrlen = sizeof(p) - 4;
615
616 #ifdef DHCPV6_OPT_PREFIX_CLASS
617                                         if (iface->ia_addr[i].has_class) {
618                                                 entrlen += sizeof(pclass);
619                                                 p.len = htons(entrlen);
620                                         }
621 #endif
622
623                                         if (datalen + entrlen + 4 > buflen || a->assigned == 0)
624                                                 continue;
625
626                                         memcpy(buf + datalen, &p, sizeof(p));
627 #ifdef DHCPV6_OPT_PREFIX_CLASS
628                                         memcpy(buf + datalen + sizeof(p), &pclass, sizeof(pclass));
629 #endif
630                                         datalen += entrlen + 4;
631                                 } else {
632                                         struct dhcpv6_ia_addr n = {
633                                                 .type = htons(DHCPV6_OPT_IA_ADDR),
634                                                 .len = htons(sizeof(n) - 4),
635                                                 .addr = iface->ia_addr[i].addr,
636                                                 .preferred = htonl(prefix_pref),
637                                                 .valid = htonl(prefix_valid)
638                                         };
639                                         n.addr.s6_addr32[3] = htonl(a->assigned);
640                                         size_t entrlen = sizeof(n) - 4;
641
642 #ifdef DHCPV6_OPT_PREFIX_CLASS
643                                         if (iface->ia_addr[i].has_class) {
644                                                 entrlen += sizeof(pclass);
645                                                 n.len = htons(entrlen);
646                                         }
647 #endif
648
649                                         if (datalen + entrlen + 4 > buflen || a->assigned == 0)
650                                                 continue;
651
652                                         memcpy(buf + datalen, &n, sizeof(n));
653 #ifdef DHCPV6_OPT_PREFIX_CLASS
654                                         memcpy(buf + datalen + sizeof(n), &pclass, sizeof(pclass));
655 #endif
656                                         datalen += entrlen + 4;
657                                 }
658
659                                 // Calculate T1 / T2 based on non-deprecated addresses
660                                 if (prefix_pref > 0) {
661                                         if (prefix_pref < pref)
662                                                 pref = prefix_pref;
663
664                                         if (prefix_valid < valid)
665                                                 valid = prefix_valid;
666                                 }
667                         }
668
669                         a->valid_until = valid + now;
670                         out.t1 = htonl(pref * 5 / 10);
671                         out.t2 = htonl(pref * 8 / 10);
672
673                         if (!out.t1)
674                                 out.t1 = htonl(1);
675
676                         if (!out.t2)
677                                 out.t2 = htonl(1);
678                 }
679
680                 if (!request) {
681                         uint8_t *odata, *end = ((uint8_t*)ia) + htons(ia->len) + 4;
682                         uint16_t otype, olen;
683                         dhcpv6_for_each_option((uint8_t*)&ia[1], end, otype, olen, odata) {
684                                 struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&odata[-4];
685                                 struct dhcpv6_ia_addr *n = (struct dhcpv6_ia_addr*)&odata[-4];
686                                 if ((otype != DHCPV6_OPT_IA_PREFIX || olen < sizeof(*p) - 4) &&
687                                                 (otype != DHCPV6_OPT_IA_ADDR || olen < sizeof(*n) - 4))
688                                         continue;
689
690                                 bool found = false;
691                                 if (a) {
692                                         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
693                                                 if (iface->ia_addr[i].prefix > 64 ||
694                                                                 iface->ia_addr[i].preferred <= (uint32_t)now)
695                                                         continue;
696
697                                                 struct in6_addr addr = iface->ia_addr[i].addr;
698                                                 if (ia->type == htons(DHCPV6_OPT_IA_PD)) {
699                                                         addr.s6_addr32[1] |= htonl(a->assigned);
700
701                                                         if (IN6_ARE_ADDR_EQUAL(&p->addr, &addr) &&
702                                                                         p->prefix == a->length)
703                                                                 found = true;
704                                                 } else {
705                                                         addr.s6_addr32[3] = htonl(a->assigned);
706
707                                                         if (IN6_ARE_ADDR_EQUAL(&n->addr, &addr))
708                                                                 found = true;
709                                                 }
710                                         }
711                                 }
712
713                                 if (!found) {
714                                         if (otype == DHCPV6_OPT_IA_PREFIX) {
715                                                 struct dhcpv6_ia_prefix inv = {
716                                                         .type = htons(DHCPV6_OPT_IA_PREFIX),
717                                                         .len = htons(sizeof(inv) - 4),
718                                                         .preferred = 0,
719                                                         .valid = 0,
720                                                         .prefix = p->prefix,
721                                                         .addr = p->addr
722                                                 };
723
724                                                 if (datalen + sizeof(inv) > buflen)
725                                                         continue;
726
727                                                 memcpy(buf + datalen, &inv, sizeof(inv));
728                                                 datalen += sizeof(inv);
729                                         } else {
730                                                 struct dhcpv6_ia_addr inv = {
731                                                         .type = htons(DHCPV6_OPT_IA_ADDR),
732                                                         .len = htons(sizeof(inv) - 4),
733                                                         .addr = n->addr,
734                                                         .preferred = 0,
735                                                         .valid = 0
736                                                 };
737
738                                                 if (datalen + sizeof(inv) > buflen)
739                                                         continue;
740
741                                                 memcpy(buf + datalen, &inv, sizeof(inv));
742                                                 datalen += sizeof(inv);
743                                         }
744                                 }
745                         }
746                 }
747         }
748
749         out.len = htons(datalen - 4);
750         memcpy(buf, &out, sizeof(out));
751         return datalen;
752 }
753
754
755 size_t dhcpv6_handle_ia(uint8_t *buf, size_t buflen, struct interface *iface,
756                 const struct sockaddr_in6 *addr, const void *data, const uint8_t *end)
757 {
758         time_t now = odhcpd_time();
759         size_t response_len = 0;
760         const struct dhcpv6_client_header *hdr = data;
761         uint8_t *start = (uint8_t*)&hdr[1], *odata;
762         uint16_t otype, olen;
763
764         // Find and parse client-id and hostname
765         bool accept_reconf = false;
766         uint8_t *clid_data = NULL, clid_len = 0, mac[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
767         char hostname[256];
768         size_t hostname_len = 0;
769         bool class_oro = false;
770         dhcpv6_for_each_option(start, end, otype, olen, odata) {
771                 if (otype == DHCPV6_OPT_CLIENTID) {
772                         clid_data = odata;
773                         clid_len = olen;
774
775                         if (olen == 14 && odata[0] == 0 && odata[1] == 1)
776                                 memcpy(mac, &odata[8], sizeof(mac));
777                         else if (olen == 10 && odata[0] == 0 && odata[1] == 3)
778                                 memcpy(mac, &odata[4], sizeof(mac));
779                 } else if (otype == DHCPV6_OPT_FQDN && olen >= 2 && olen <= 255) {
780                         uint8_t fqdn_buf[256];
781                         memcpy(fqdn_buf, odata, olen);
782                         fqdn_buf[olen++] = 0;
783
784                         if (dn_expand(&fqdn_buf[1], &fqdn_buf[olen], &fqdn_buf[1], hostname, sizeof(hostname)) > 0)
785                                 hostname_len = strcspn(hostname, ".");
786                 } else if (otype == DHCPV6_OPT_ORO) {
787 #ifdef DHCPV6_OPT_PREFIX_CLASS
788                         for (size_t i = 0; i + 1 < olen; i += 2) {
789                                 if (odata[i] == (DHCPV6_OPT_PREFIX_CLASS >> 8) &&
790                                                 odata[i + 1] == (DHCPV6_OPT_PREFIX_CLASS & 0xff))
791                                         class_oro = true;
792                         }
793 #endif
794                 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
795                         accept_reconf = true;
796                 }
797         }
798
799         if (!clid_data || !clid_len || clid_len > 130)
800                 goto out;
801
802         update(iface);
803         bool update_state = false;
804
805         struct dhcpv6_assignment *first = NULL;
806         dhcpv6_for_each_option(start, end, otype, olen, odata) {
807                 bool is_pd = (otype == DHCPV6_OPT_IA_PD);
808                 bool is_na = (otype == DHCPV6_OPT_IA_NA);
809                 if (!is_pd && !is_na)
810                         continue;
811
812                 struct dhcpv6_ia_hdr *ia = (struct dhcpv6_ia_hdr*)&odata[-4];
813                 size_t ia_response_len = 0;
814                 uint8_t reqlen = (is_pd) ? 62 : 128;
815                 uint32_t reqhint = 0;
816
817                 const uint8_t classes_max = 32;
818                 uint8_t classes_cnt = 0;
819                 uint16_t classes[classes_max];
820
821                 // Parse request hint for IA-PD
822                 if (is_pd) {
823                         uint8_t *sdata;
824                         uint16_t stype, slen;
825                         dhcpv6_for_each_option(&ia[1], odata + olen, stype, slen, sdata) {
826                                 if (stype != DHCPV6_OPT_IA_PREFIX || slen < sizeof(struct dhcpv6_ia_prefix) - 4)
827                                         continue;
828
829                                 struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&sdata[-4];
830                                 if (p->prefix) {
831                                         reqlen = p->prefix;
832                                         reqhint = ntohl(p->addr.s6_addr32[1]);
833                                         if (reqlen > 32 && reqlen <= 64)
834                                                 reqhint &= (1U << (64 - reqlen)) - 1;
835                                 }
836
837 #ifdef DHCPV6_OPT_PREFIX_CLASS
838                                 uint8_t *xdata;
839                                 uint16_t xtype, xlen;
840                                 dhcpv6_for_each_option(&p[1], sdata + slen, xtype, xlen, xdata) {
841                                         if (xtype != DHCPV6_OPT_PREFIX_CLASS || xlen != 2)
842                                                 continue;
843
844                                         if (classes_cnt >= classes_max)
845                                                 continue;
846
847                                         classes[classes_cnt++] = (uint16_t)xdata[0] << 8 | (uint16_t)xdata[1];
848                                 }
849 #endif
850                         }
851
852                         if (reqlen > 64)
853                                 reqlen = 64;
854                 } else if (is_na) {
855                         uint8_t *sdata;
856                         uint16_t stype, slen;
857                         dhcpv6_for_each_option(&ia[1], odata + olen, stype, slen, sdata) {
858                                 if (stype != DHCPV6_OPT_IA_ADDR || slen < sizeof(struct dhcpv6_ia_addr) - 4)
859                                         continue;
860
861 #ifdef DHCPV6_OPT_PREFIX_CLASS
862                                 uint8_t *xdata;
863                                 uint16_t xtype, xlen;
864                                 struct dhcpv6_ia_addr *p = (struct dhcpv6_ia_addr*)&sdata[-4];
865                                 dhcpv6_for_each_option(&p[1], sdata + slen, xtype, xlen, xdata) {
866                                         if (xtype != DHCPV6_OPT_PREFIX_CLASS || xlen != 2)
867                                                 continue;
868
869                                         if (classes_cnt >= classes_max)
870                                                 continue;
871
872                                         classes[classes_cnt++] = (uint16_t)xdata[0] << 8 | (uint16_t)xdata[1];
873                                 }
874 #endif
875                         }
876                 }
877
878                 // Find assignment
879                 struct dhcpv6_assignment *c, *a = NULL;
880                 list_for_each_entry(c, &iface->ia_assignments, head) {
881                         if (((c->clid_len == clid_len && !memcmp(c->clid_data, clid_data, clid_len)) ||
882                                         (c->clid_len >= clid_len && !c->clid_data[0] && !c->clid_data[1]
883                                                 && !memcmp(c->mac, mac, sizeof(mac)))) &&
884                                         (c->iaid == ia->iaid || c->valid_until < now) &&
885                                         ((is_pd && c->length <= 64) || (is_na && c->length == 128))) {
886                                 a = c;
887
888                                 // Reset state
889                                 apply_lease(iface, a, false);
890                                 memcpy(a->clid_data, clid_data, clid_len);
891                                 a->clid_len = clid_len;
892                                 a->iaid = ia->iaid;
893                                 a->peer = *addr;
894                                 a->reconf_cnt = 0;
895                                 a->reconf_sent = 0;
896                                 a->all_class = class_oro;
897                                 a->classes_cnt = classes_cnt;
898                                 a->classes = realloc(a->classes, classes_cnt * sizeof(uint16_t));
899                                 if (a->classes)
900                                         memcpy(a->classes, classes, classes_cnt * sizeof(uint16_t));
901                                 break;
902                         }
903                 }
904
905                 // Generic message handling
906                 uint16_t status = DHCPV6_STATUS_OK;
907                 if (hdr->msg_type == DHCPV6_MSG_SOLICIT || hdr->msg_type == DHCPV6_MSG_REQUEST) {
908                         bool assigned = !!a;
909
910                         if (!a && !iface->no_dynamic_dhcp) { // Create new binding
911                                 a = calloc(1, sizeof(*a) + clid_len);
912                                 if (a) {
913                                         a->clid_len = clid_len;
914                                         a->iaid = ia->iaid;
915                                         a->length = reqlen;
916                                         a->peer = *addr;
917                                         a->assigned = reqhint;
918                                         a->all_class = class_oro;
919                                         a->classes_cnt = classes_cnt;
920                                         if (classes_cnt) {
921                                                 a->classes = malloc(classes_cnt * sizeof(uint16_t));
922                                                 if (a->classes)
923                                                         memcpy(a->classes, classes, classes_cnt * sizeof(uint16_t));
924                                         }
925
926                                         if (first)
927                                                 memcpy(a->key, first->key, sizeof(a->key));
928                                         else
929                                                 odhcpd_urandom(a->key, sizeof(a->key));
930                                         memcpy(a->clid_data, clid_data, clid_len);
931
932                                         if (is_pd)
933                                                 while (!(assigned = assign_pd(iface, a)) && ++a->length <= 64);
934                                         else
935                                                 assigned = assign_na(iface, a);
936                                 }
937                         }
938
939                         if (!assigned || iface->ia_addr_len == 0) { // Set error status
940                                 status = (is_pd) ? DHCPV6_STATUS_NOPREFIXAVAIL : DHCPV6_STATUS_NOADDRSAVAIL;
941                         } else if (assigned && !first) { //
942                                 size_t handshake_len = 4;
943                                 buf[0] = 0;
944                                 buf[1] = DHCPV6_OPT_RECONF_ACCEPT;
945                                 buf[2] = 0;
946                                 buf[3] = 0;
947
948                                 if (hdr->msg_type == DHCPV6_MSG_REQUEST) {
949                                         struct dhcpv6_auth_reconfigure auth = {
950                                                 htons(DHCPV6_OPT_AUTH),
951                                                 htons(sizeof(auth) - 4),
952                                                 3, 1, 0,
953                                                 {htonl(time(NULL)), htonl(++serial)},
954                                                 1,
955                                                 {0}
956                                         };
957                                         memcpy(auth.key, a->key, sizeof(a->key));
958                                         memcpy(buf + handshake_len, &auth, sizeof(auth));
959                                         handshake_len += sizeof(auth);
960                                 }
961
962                                 buf += handshake_len;
963                                 buflen -= handshake_len;
964                                 response_len += handshake_len;
965
966                                 first = a;
967                         }
968
969                         ia_response_len = append_reply(buf, buflen, status, ia, a, iface, true);
970
971                         // Was only a solicitation: mark binding for removal
972                         if (assigned && hdr->msg_type == DHCPV6_MSG_SOLICIT) {
973                                 a->valid_until = 0;
974                         } else if (assigned && hdr->msg_type == DHCPV6_MSG_REQUEST) {
975                                 if (hostname_len > 0) {
976                                         a->hostname = realloc(a->hostname, hostname_len + 1);
977                                         if (a->hostname) {
978                                                 memcpy(a->hostname, hostname, hostname_len);
979                                                 a->hostname[hostname_len] = 0;
980                                         }
981                                 }
982                                 a->accept_reconf = accept_reconf;
983                                 apply_lease(iface, a, true);
984                                 update_state = true;
985                         } else if (!assigned && a) { // Cleanup failed assignment
986                                 free(a->classes);
987                                 free(a->hostname);
988                                 free(a);
989                         }
990                 } else if (hdr->msg_type == DHCPV6_MSG_RENEW ||
991                                 hdr->msg_type == DHCPV6_MSG_RELEASE ||
992                                 hdr->msg_type == DHCPV6_MSG_REBIND ||
993                                 hdr->msg_type == DHCPV6_MSG_DECLINE) {
994                         if (!a && hdr->msg_type != DHCPV6_MSG_REBIND) {
995                                 status = DHCPV6_STATUS_NOBINDING;
996                                 ia_response_len = append_reply(buf, buflen, status, ia, a, iface, false);
997                         } else if (hdr->msg_type == DHCPV6_MSG_RENEW ||
998                                         hdr->msg_type == DHCPV6_MSG_REBIND) {
999                                 ia_response_len = append_reply(buf, buflen, status, ia, a, iface, false);
1000                                 if (a)
1001                                         apply_lease(iface, a, true);
1002                         } else if (hdr->msg_type == DHCPV6_MSG_RELEASE) {
1003                                 a->valid_until = 0;
1004                                 apply_lease(iface, a, false);
1005                                 update_state = true;
1006                         } else if (hdr->msg_type == DHCPV6_MSG_DECLINE && a->length == 128) {
1007                                 a->clid_len = 0;
1008                                 a->valid_until = now + 3600; // Block address for 1h
1009                                 update_state = true;
1010                         }
1011                 } else if (hdr->msg_type == DHCPV6_MSG_CONFIRM) {
1012                         // Always send NOTONLINK for CONFIRM so that clients restart connection
1013                         status = DHCPV6_STATUS_NOTONLINK;
1014                         ia_response_len = append_reply(buf, buflen, status, ia, a, iface, true);
1015                 }
1016
1017                 buf += ia_response_len;
1018                 buflen -= ia_response_len;
1019                 response_len += ia_response_len;
1020         }
1021
1022         if (hdr->msg_type == DHCPV6_MSG_RELEASE && response_len + 6 < buflen) {
1023                 buf[0] = 0;
1024                 buf[1] = DHCPV6_OPT_STATUS;
1025                 buf[2] = 0;
1026                 buf[3] = 2;
1027                 buf[4] = 0;
1028                 buf[5] = DHCPV6_STATUS_OK;
1029                 response_len += 6;
1030         }
1031
1032         if (update_state)
1033                 dhcpv6_write_statefile();
1034
1035 out:
1036         return response_len;
1037 }