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