Fix possible buffer overflows in DNS handling
[project/odhcp6c.git] / src / odhcp6c.c
1 /**
2 * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License v2 as published by
6 * the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 */
14
15 #include <time.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <stddef.h>
21 #include <unistd.h>
22 #include <syslog.h>
23 #include <signal.h>
24 #include <string.h>
25 #include <stdbool.h>
26
27 #include <net/if.h>
28 #include <sys/wait.h>
29 #include <sys/syscall.h>
30
31 #include "odhcp6c.h"
32 #include "ra.h"
33
34
35 static void sighandler(int signal);
36 static int usage(void);
37
38
39 static uint8_t *state_data[_STATE_MAX] = {NULL};
40 static size_t state_len[_STATE_MAX] = {0};
41
42 static volatile int do_signal = 0;
43 static int urandom_fd = -1, allow_slaac_only = 0;
44 static bool bound = false, release = true;
45
46
47 int main(_unused int argc, char* const argv[])
48 {
49 // Allocate ressources
50 const char *pidfile = NULL;
51 const char *script = "/usr/sbin/odhcp6c-update";
52 ssize_t l;
53 uint8_t buf[134];
54 char *optpos;
55 uint16_t opttype;
56 enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY;
57
58 bool help = false, daemonize = false;
59 int logopt = LOG_PID;
60 int c, request_pd = 0;
61 while ((c = getopt(argc, argv, "S::N:P:c:r:s:khedp:")) != -1) {
62 switch (c) {
63 case 'S':
64 allow_slaac_only = (optarg) ? atoi(optarg) : -1;
65 break;
66
67 case 'N':
68 if (!strcmp(optarg, "force"))
69 ia_na_mode = IA_MODE_FORCE;
70 else if (!strcmp(optarg, "none"))
71 ia_na_mode = IA_MODE_NONE;
72 else if (!strcmp(optarg, "try"))
73 ia_na_mode = IA_MODE_TRY;
74 else
75 help = true;
76 break;
77
78 case 'P':
79 if (allow_slaac_only >= 0 && allow_slaac_only < 10)
80 allow_slaac_only = 10;
81
82 request_pd = strtoul(optarg, NULL, 10);
83 if (request_pd == 0)
84 request_pd = -1;
85 break;
86
87 case 'c':
88 l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg);
89 if (l > 0) {
90 buf[0] = 0;
91 buf[1] = DHCPV6_OPT_CLIENTID;
92 buf[2] = 0;
93 buf[3] = l;
94 odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4);
95 } else {
96 help = true;
97 }
98 break;
99
100 case 'r':
101 optpos = optarg;
102 while (optpos[0]) {
103 opttype = htons(strtoul(optarg, &optpos, 10));
104 if (optpos == optarg)
105 break;
106 else if (optpos[0])
107 optarg = &optpos[1];
108 odhcp6c_add_state(STATE_ORO, &opttype, 2);
109 }
110 break;
111
112 case 's':
113 script = optarg;
114 break;
115
116 case 'k':
117 release = false;
118 break;
119
120 case 'e':
121 logopt |= LOG_PERROR;
122 break;
123
124 case 'd':
125 daemonize = true;
126 break;
127
128 case 'p':
129 pidfile = optarg;
130 break;
131
132 default:
133 help = true;
134 break;
135 }
136 }
137
138 openlog("odhcp6c", logopt, LOG_DAEMON);
139 const char *ifname = argv[optind];
140
141 if (help || !ifname)
142 return usage();
143
144 signal(SIGIO, sighandler);
145 signal(SIGHUP, sighandler);
146 signal(SIGINT, sighandler);
147 signal(SIGCHLD, sighandler);
148 signal(SIGTERM, sighandler);
149 signal(SIGUSR1, sighandler);
150 signal(SIGUSR2, sighandler);
151
152 if ((urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY)) < 0 ||
153 init_dhcpv6(ifname, request_pd) || ra_init(ifname) ||
154 script_init(script, ifname)) {
155 syslog(LOG_ERR, "failed to initialize: %s", strerror(errno));
156 return 3;
157 }
158
159 if (daemonize) {
160 openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR
161 if (daemon(0, 0)) {
162 syslog(LOG_ERR, "Failed to daemonize: %s",
163 strerror(errno));
164 return 4;
165 }
166
167 char pidbuf[128];
168 if (!pidfile) {
169 snprintf(pidbuf, sizeof(pidbuf),
170 "/var/run/odhcp6c.%s.pid", ifname);
171 pidfile = pidbuf;
172 }
173
174 int fd = open(pidfile, O_WRONLY | O_CREAT);
175 if (fd >= 0) {
176 char buf[8];
177 int len = snprintf(buf, sizeof(buf), "%i\n", getpid());
178 write(fd, buf, len);
179 close(fd);
180 }
181 }
182
183 script_call("started");
184
185 while (do_signal != SIGTERM) { // Main logic
186 odhcp6c_clear_state(STATE_SERVER_ID);
187 odhcp6c_clear_state(STATE_SERVER_CAND);
188 odhcp6c_clear_state(STATE_IA_PD);
189 odhcp6c_clear_state(STATE_SNTP_IP);
190 odhcp6c_clear_state(STATE_SNTP_FQDN);
191 odhcp6c_clear_state(STATE_SIP_IP);
192 odhcp6c_clear_state(STATE_SIP_FQDN);
193 dhcpv6_set_ia_na_mode(ia_na_mode);
194 bound = false;
195
196 syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname);
197
198 do_signal = 0;
199 int res = dhcpv6_request(DHCPV6_MSG_SOLICIT);
200 odhcp6c_signal_process();
201
202 if (res < 0) {
203 continue; // Might happen if we got a signal
204 } else if (res == DHCPV6_STATELESS) { // Stateless mode
205 while (do_signal == 0 || do_signal == SIGUSR1) {
206 do_signal = 0;
207
208 res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
209 odhcp6c_signal_process();
210 if (do_signal == SIGUSR1)
211 continue;
212 else if (res < 0)
213 break;
214 else if (res > 0)
215 script_call("informed");
216
217 bound = true;
218 syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname);
219
220 if (dhcpv6_poll_reconfigure() > 0)
221 script_call("informed");
222 }
223
224 continue;
225 }
226
227 // Stateful mode
228 if (dhcpv6_request(DHCPV6_MSG_REQUEST) < 0)
229 continue;
230
231 odhcp6c_signal_process();
232 script_call("bound");
233 bound = true;
234 syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname);
235
236 while (do_signal == 0 || do_signal == SIGUSR1) {
237 // Renew Cycle
238 // Wait for T1 to expire or until we get a reconfigure
239 int res = dhcpv6_poll_reconfigure();
240 odhcp6c_signal_process();
241 if (res >= 0) {
242 if (res > 0)
243 script_call("updated");
244
245 continue;
246 }
247
248 // Handle signal, if necessary
249 if (do_signal == SIGUSR1)
250 do_signal = 0; // Acknowledged
251 else if (do_signal > 0)
252 break; // Other signal type
253
254 size_t ia_pd_len, ia_na_len, ia_pd_new, ia_na_new;
255 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
256 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
257
258 // If we have any IAs, send renew, otherwise request
259 int r;
260 if (ia_pd_len == 0 && ia_na_len == 0)
261 r = dhcpv6_request(DHCPV6_MSG_REQUEST);
262 else
263 r = dhcpv6_request(DHCPV6_MSG_RENEW);
264 odhcp6c_signal_process();
265 if (r > 0) // Publish updates
266 script_call("updated");
267 if (r >= 0)
268 continue; // Renew was successful
269
270 odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
271
272 // If we have IAs, try rebind otherwise restart
273 res = dhcpv6_request(DHCPV6_MSG_REBIND);
274 odhcp6c_signal_process();
275
276 odhcp6c_get_state(STATE_IA_PD, &ia_pd_new);
277 odhcp6c_get_state(STATE_IA_NA, &ia_na_new);
278 if (res < 0 || (ia_pd_new == 0 && ia_pd_len) ||
279 (ia_na_new == 0 && ia_na_len))
280 break; // We lost all our IAs, restart
281 else if (res > 0)
282 script_call("rebound");
283 }
284
285
286 size_t ia_pd_len, ia_na_len, server_id_len;
287 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
288 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
289 odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
290
291 // Add all prefixes to lost prefixes
292 bound = false;
293 script_call("unbound");
294
295 if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release)
296 dhcpv6_request(DHCPV6_MSG_RELEASE);
297
298 odhcp6c_clear_state(STATE_IA_NA);
299 odhcp6c_clear_state(STATE_IA_PD);
300 }
301
302 script_call("stopped");
303 return 0;
304 }
305
306
307 static int usage(void)
308 {
309 const char buf[] =
310 "Usage: odhcp6c [options] <interface>\n"
311 "\nFeature options:\n"
312 " -S <time> Wait at least <time> sec for a DHCP-server (0)\n"
313 " -N <mode> Mode for requesting addresses [try|force|none]\n"
314 " -P <length> Request IPv6-Prefix (0 = auto)\n"
315 " -c <clientid> Override client-ID (base-16 encoded)\n"
316 " -r <options> Options to be requested (comma-separated)\n"
317 " -s <script> Status update script (/usr/sbin/odhcp6c-update)\n"
318 " -k Don't send a RELEASE when stopping\n"
319 "\nInvocation options:\n"
320 " -p <pidfile> Set pidfile (/var/run/6relayd.pid)\n"
321 " -d Daemonize\n"
322 " -e Write logmessages to stderr\n"
323 //" -v Increase logging verbosity\n"
324 " -h Show this help\n\n";
325 write(STDERR_FILENO, buf, sizeof(buf));
326 return 1;
327 }
328
329
330 // Don't want to pull-in librt and libpthread just for a monotonic clock...
331 uint64_t odhcp6c_get_milli_time(void)
332 {
333 struct timespec t = {0, 0};
334 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
335 return t.tv_sec * 1000 + t.tv_nsec / 1000000;
336 }
337
338
339 static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
340 {
341 if (len == 0)
342 return state_data[state] + state_len[state];
343 else if (state_len[state] + len > 1024)
344 return NULL;
345
346 uint8_t *n = realloc(state_data[state], state_len[state] + len);
347 if (n || state_len[state] + len == 0) {
348 state_data[state] = n;
349 n += state_len[state];
350 state_len[state] += len;
351 }
352 return n;
353 }
354
355
356 bool odhcp6c_signal_process(void)
357 {
358 if (do_signal == SIGIO) {
359 do_signal = 0;
360 bool ra_updated = ra_process();
361
362 if (ra_rtnl_process() || (ra_updated && (bound || allow_slaac_only == 0)))
363 script_call("ra-updated"); // Immediate process urgent events
364 else if (ra_updated && !bound && allow_slaac_only > 0)
365 script_delay_call("ra-updated", allow_slaac_only);
366 }
367
368 return do_signal != 0;
369 }
370
371
372 void odhcp6c_clear_state(enum odhcp6c_state state)
373 {
374 state_len[state] = 0;
375 }
376
377
378 void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
379 {
380 uint8_t *n = odhcp6c_resize_state(state, len);
381 if (n)
382 memcpy(n, data, len);
383 }
384
385
386 size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
387 {
388 uint8_t *data = state_data[state];
389 ssize_t len_after = state_len[state] - (offset + len);
390 if (len_after < 0)
391 return state_len[state];
392
393 memmove(data + offset, data + offset + len, len_after);
394 return state_len[state] -= len;
395 }
396
397
398 void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
399 {
400 *len = state_len[state];
401 return state_data[state];
402 }
403
404
405 struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
406 {
407 size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + new->length / 8;
408 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
409 struct odhcp6c_entry *x = NULL;
410
411 for (struct odhcp6c_entry *c = start; !x && c < &start[len/sizeof(*c)]; ++c)
412 if (!memcmp(c, new, cmplen))
413 return c;
414
415 return NULL;
416 }
417
418
419 void odhcp6c_update_entry_safe(enum odhcp6c_state state, struct odhcp6c_entry *new, uint32_t safe)
420 {
421 size_t len;
422 struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
423 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
424
425 if (x && x->valid > new->valid && new->valid < safe)
426 new->valid = safe;
427
428 if (new->valid > 0) {
429 if (x) {
430 x->valid = new->valid;
431 x->preferred = new->preferred;
432 } else {
433 odhcp6c_add_state(state, new, sizeof(*new));
434 }
435 } else if (x) {
436 odhcp6c_remove_state(state, (x - start) * sizeof(*x), sizeof(*x));
437 }
438 }
439
440
441 void odhcp6c_update_entry(enum odhcp6c_state state, struct odhcp6c_entry *new)
442 {
443 odhcp6c_update_entry_safe(state, new, 0);
444 }
445
446
447 static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
448 {
449 size_t len;
450 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
451 for (struct odhcp6c_entry *c = start; c < &start[len / sizeof(*c)]; ++c) {
452 if (c->preferred < elapsed)
453 c->preferred = 0;
454 else if (c->preferred != UINT32_MAX)
455 c->preferred -= elapsed;
456
457 if (c->valid < elapsed)
458 c->valid = 0;
459 else if (c->valid != UINT32_MAX)
460 c->valid -= elapsed;
461
462 if (!c->valid)
463 odhcp6c_remove_state(state, (c - start) * sizeof(*c), sizeof(*c));
464 }
465 }
466
467
468 void odhcp6c_expire(void)
469 {
470 static time_t last_update = 0;
471 time_t now = odhcp6c_get_milli_time() / 1000;
472
473 uint32_t elapsed = now - last_update;
474 last_update = now;
475
476 odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
477 odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
478 odhcp6c_expire_list(STATE_RA_DNS, elapsed);
479 odhcp6c_expire_list(STATE_IA_NA, elapsed);
480 odhcp6c_expire_list(STATE_IA_PD, elapsed);
481 }
482
483
484 void odhcp6c_random(void *buf, size_t len)
485 {
486 read(urandom_fd, buf, len);
487 }
488
489
490 static void sighandler(int signal)
491 {
492 if (signal == SIGCHLD)
493 while (waitpid(-1, NULL, WNOHANG) > 0);
494 else if (signal == SIGUSR1)
495 do_signal = SIGUSR1;
496 else if (signal == SIGUSR2)
497 do_signal = SIGUSR2;
498 else if (signal == SIGIO)
499 do_signal = SIGIO;
500 else
501 do_signal = SIGTERM;
502 }