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