xref: /dragonfly/contrib/dhcpcd/src/arp.c (revision 207ba670)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - ARP handler
4  * Copyright (c) 2006-2019 Roy Marples <roy@marples.name>
5  * All rights reserved
6 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/socket.h>
30 #include <sys/types.h>
31 
32 #include <arpa/inet.h>
33 
34 #include <net/if.h>
35 #include <netinet/in.h>
36 #include <netinet/if_ether.h>
37 
38 #include <errno.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <unistd.h>
43 
44 #define ELOOP_QUEUE 5
45 #include "config.h"
46 #include "arp.h"
47 #include "bpf.h"
48 #include "ipv4.h"
49 #include "common.h"
50 #include "dhcpcd.h"
51 #include "eloop.h"
52 #include "if.h"
53 #include "if-options.h"
54 #include "ipv4ll.h"
55 #include "logerr.h"
56 
57 #if defined(ARP)
58 #define ARP_LEN								      \
59 	(sizeof(struct arphdr) + (2 * sizeof(uint32_t)) + (2 * HWADDR_LEN))
60 
61 /* ARP debugging can be quite noisy. Enable this for more noise! */
62 //#define	ARP_DEBUG
63 
64 /* Assert the correct structure size for on wire */
65 __CTASSERT(sizeof(struct arphdr) == 8);
66 
67 static ssize_t
68 arp_request(const struct interface *ifp,
69     const struct in_addr *sip, const struct in_addr *tip)
70 {
71 	uint8_t arp_buffer[ARP_LEN];
72 	struct arphdr ar;
73 	size_t len;
74 	uint8_t *p;
75 	const struct iarp_state *state;
76 
77 	ar.ar_hrd = htons(ifp->family);
78 	ar.ar_pro = htons(ETHERTYPE_IP);
79 	ar.ar_hln = ifp->hwlen;
80 	ar.ar_pln = sizeof(tip->s_addr);
81 	ar.ar_op = htons(ARPOP_REQUEST);
82 
83 	p = arp_buffer;
84 	len = 0;
85 
86 #define CHECK(fun, b, l)						\
87 	do {								\
88 		if (len + (l) > sizeof(arp_buffer))			\
89 			goto eexit;					\
90 		fun(p, (b), (l));					\
91 		p += (l);						\
92 		len += (l);						\
93 	} while (/* CONSTCOND */ 0)
94 #define APPEND(b, l)	CHECK(memcpy, b, l)
95 #define ZERO(l)		CHECK(memset, 0, l)
96 
97 	APPEND(&ar, sizeof(ar));
98 	APPEND(ifp->hwaddr, ifp->hwlen);
99 	if (sip != NULL)
100 		APPEND(&sip->s_addr, sizeof(sip->s_addr));
101 	else
102 		ZERO(sizeof(tip->s_addr));
103 	ZERO(ifp->hwlen);
104 	APPEND(&tip->s_addr, sizeof(tip->s_addr));
105 
106 	state = ARP_CSTATE(ifp);
107 	return bpf_send(ifp, state->bpf_fd, ETHERTYPE_ARP, arp_buffer, len);
108 
109 eexit:
110 	errno = ENOBUFS;
111 	return -1;
112 }
113 
114 static void
115 arp_report_conflicted(const struct arp_state *astate,
116     const struct arp_msg *amsg)
117 {
118 	char buf[HWADDR_LEN * 3];
119 
120 	if (amsg == NULL) {
121 		logerrx("%s: DAD detected %s",
122 		    astate->iface->name, inet_ntoa(astate->addr));
123 		return;
124 	}
125 
126 	logerrx("%s: hardware address %s claims %s",
127 	    astate->iface->name,
128 	    hwaddr_ntoa(amsg->sha, astate->iface->hwlen, buf, sizeof(buf)),
129 	    inet_ntoa(astate->addr));
130 }
131 
132 static void
133 arp_found(struct arp_state *astate, const struct arp_msg *amsg)
134 {
135 	struct interface *ifp;
136 	struct ipv4_addr *ia;
137 #ifndef KERNEL_RFC5227
138 	struct timespec now, defend;
139 #endif
140 
141 	arp_report_conflicted(astate, amsg);
142 	ifp = astate->iface;
143 
144 	/* If we haven't added the address we're doing a probe. */
145 	ia = ipv4_iffindaddr(ifp, &astate->addr, NULL);
146 	if (ia == NULL) {
147 		if (astate->found_cb != NULL)
148 			astate->found_cb(astate, amsg);
149 		return;
150 	}
151 
152 #ifndef KERNEL_RFC5227
153 	/* RFC 3927 Section 2.5 says a defence should
154 	 * broadcast an ARP announcement.
155 	 * Because the kernel will also unicast a reply to the
156 	 * hardware address which requested the IP address
157 	 * the other IPv4LL client will receieve two ARP
158 	 * messages.
159 	 * If another conflict happens within DEFEND_INTERVAL
160 	 * then we must drop our address and negotiate a new one. */
161 	defend.tv_sec = astate->defend.tv_sec + DEFEND_INTERVAL;
162 	defend.tv_nsec = astate->defend.tv_nsec;
163 	clock_gettime(CLOCK_MONOTONIC, &now);
164 	if (timespeccmp(&defend, &now, >))
165 		logwarnx("%s: %d second defence failed for %s",
166 		    ifp->name, DEFEND_INTERVAL, inet_ntoa(astate->addr));
167 	else if (arp_request(ifp, &astate->addr, &astate->addr) == -1)
168 		logerr(__func__);
169 	else {
170 		logdebugx("%s: defended address %s",
171 		    ifp->name, inet_ntoa(astate->addr));
172 		astate->defend = now;
173 		return;
174 	}
175 #endif
176 
177 	if (astate->defend_failed_cb != NULL)
178 		astate->defend_failed_cb(astate);
179 }
180 
181 static bool
182 arp_validate(const struct interface *ifp, struct arphdr *arp)
183 {
184 
185 	/* Families must match */
186 	if (arp->ar_hrd != htons(ifp->family))
187 		return false;
188 
189 	/* Protocol must be IP. */
190 	if (arp->ar_pro != htons(ETHERTYPE_IP))
191 		return false;
192 
193 	/* lladdr length matches */
194 	if (arp->ar_hln != ifp->hwlen)
195 		return false;
196 
197 	/* Protocol length must match in_addr_t */
198 	if (arp->ar_pln != sizeof(in_addr_t))
199 		return false;
200 
201 	/* Only these types are recognised */
202 	if (arp->ar_op != htons(ARPOP_REPLY) &&
203 	    arp->ar_op != htons(ARPOP_REQUEST))
204 		return false;
205 
206 	return true;
207 }
208 
209 static void
210 arp_packet(struct interface *ifp, uint8_t *data, size_t len)
211 {
212 	const struct interface *ifn;
213 	struct arphdr ar;
214 	struct arp_msg arm;
215 	const struct iarp_state *state;
216 	struct arp_state *astate, *astaten;
217 	uint8_t *hw_s, *hw_t;
218 
219 	/* We must have a full ARP header */
220 	if (len < sizeof(ar))
221 		return;
222 	memcpy(&ar, data, sizeof(ar));
223 
224 	if (!arp_validate(ifp, &ar)) {
225 #ifdef BPF_DEBUG
226 		logerrx("%s: ARP BPF validation failure", ifp->name);
227 #endif
228 		return;
229 	}
230 
231 	/* Get pointers to the hardware addresses */
232 	hw_s = data + sizeof(ar);
233 	hw_t = hw_s + ar.ar_hln + ar.ar_pln;
234 	/* Ensure we got all the data */
235 	if ((size_t)((hw_t + ar.ar_hln + ar.ar_pln) - data) > len)
236 		return;
237 	/* Ignore messages from ourself */
238 	TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
239 		if (ar.ar_hln == ifn->hwlen &&
240 		    memcmp(hw_s, ifn->hwaddr, ifn->hwlen) == 0)
241 			break;
242 	}
243 	if (ifn) {
244 #ifdef ARP_DEBUG
245 		logdebugx("%s: ignoring ARP from self", ifp->name);
246 #endif
247 		return;
248 	}
249 	/* Copy out the HW and IP addresses */
250 	memcpy(&arm.sha, hw_s, ar.ar_hln);
251 	memcpy(&arm.sip.s_addr, hw_s + ar.ar_hln, ar.ar_pln);
252 	memcpy(&arm.tha, hw_t, ar.ar_hln);
253 	memcpy(&arm.tip.s_addr, hw_t + ar.ar_hln, ar.ar_pln);
254 
255 	/* Match the ARP probe to our states.
256 	 * Ignore Unicast Poll, RFC1122. */
257 	state = ARP_CSTATE(ifp);
258 	TAILQ_FOREACH_SAFE(astate, &state->arp_states, next, astaten) {
259 		if (IN_ARE_ADDR_EQUAL(&arm.sip, &astate->addr) ||
260 		    (IN_IS_ADDR_UNSPECIFIED(&arm.sip) &&
261 		    IN_ARE_ADDR_EQUAL(&arm.tip, &astate->addr) &&
262 		    state->bpf_flags & BPF_BCAST))
263 			arp_found(astate, &arm);
264 	}
265 }
266 
267 static void
268 arp_close(struct interface *ifp)
269 {
270 	struct iarp_state *state;
271 
272 	if ((state = ARP_STATE(ifp)) == NULL || state->bpf_fd == -1)
273 		return;
274 
275 	eloop_event_delete(ifp->ctx->eloop, state->bpf_fd);
276 	bpf_close(ifp, state->bpf_fd);
277 	state->bpf_fd = -1;
278 	state->bpf_flags |= BPF_EOF;
279 }
280 
281 static void
282 arp_tryfree(struct iarp_state *state)
283 {
284 	struct interface *ifp = state->ifp;
285 
286 	/* If there are no more ARP states, close the socket. */
287 	if (TAILQ_FIRST(&state->arp_states) == NULL) {
288 		arp_close(ifp);
289 		if (state->bpf_flags & BPF_READING)
290 			state->bpf_flags |= BPF_EOF;
291 		else {
292 			free(state);
293 			ifp->if_data[IF_DATA_ARP] = NULL;
294 		}
295 	} else {
296 		if (bpf_arp(ifp, state->bpf_fd) == -1)
297 			logerr(__func__);
298 	}
299 }
300 
301 static void
302 arp_read(void *arg)
303 {
304 	struct iarp_state *state = arg;
305 	struct interface *ifp = state->ifp;
306 	uint8_t buf[ARP_LEN];
307 	ssize_t bytes;
308 
309 	/* Some RAW mechanisms are generic file descriptors, not sockets.
310 	 * This means we have no kernel call to just get one packet,
311 	 * so we have to process the entire buffer. */
312 	state->bpf_flags &= ~BPF_EOF;
313 	state->bpf_flags |= BPF_READING;
314 	while (!(state->bpf_flags & BPF_EOF)) {
315 		bytes = bpf_read(ifp, state->bpf_fd, buf, sizeof(buf),
316 				 &state->bpf_flags);
317 		if (bytes == -1) {
318 			logerr("%s: %s", __func__, ifp->name);
319 			arp_close(ifp);
320 			break;
321 		}
322 		arp_packet(ifp, buf, (size_t)bytes);
323 		/* Check we still have a state after processing. */
324 		if ((state = ARP_STATE(ifp)) == NULL)
325 			break;
326 	}
327 	if (state != NULL) {
328 		state->bpf_flags &= ~BPF_READING;
329 		/* Try and free the state if nothing left to do. */
330 		arp_tryfree(state);
331 	}
332 }
333 
334 static int
335 arp_open(struct interface *ifp)
336 {
337 	struct iarp_state *state;
338 
339 	state = ARP_STATE(ifp);
340 	if (state->bpf_fd == -1) {
341 		state->bpf_fd = bpf_open(ifp, bpf_arp);
342 		if (state->bpf_fd == -1)
343 			return -1;
344 		eloop_event_add(ifp->ctx->eloop, state->bpf_fd, arp_read, state);
345 	}
346 	return state->bpf_fd;
347 }
348 
349 static void
350 arp_probed(void *arg)
351 {
352 	struct arp_state *astate = arg;
353 
354 	timespecclear(&astate->defend);
355 	astate->not_found_cb(astate);
356 }
357 
358 static void
359 arp_probe1(void *arg)
360 {
361 	struct arp_state *astate = arg;
362 	struct interface *ifp = astate->iface;
363 	struct timespec tv;
364 
365 	if (++astate->probes < PROBE_NUM) {
366 		tv.tv_sec = PROBE_MIN;
367 		tv.tv_nsec = (suseconds_t)arc4random_uniform(
368 		    (PROBE_MAX - PROBE_MIN) * NSEC_PER_SEC);
369 		timespecnorm(&tv);
370 		eloop_timeout_add_tv(ifp->ctx->eloop, &tv, arp_probe1, astate);
371 	} else {
372 		tv.tv_sec = ANNOUNCE_WAIT;
373 		tv.tv_nsec = 0;
374 		eloop_timeout_add_tv(ifp->ctx->eloop, &tv, arp_probed, astate);
375 	}
376 	logdebugx("%s: ARP probing %s (%d of %d), next in %0.1f seconds",
377 	    ifp->name, inet_ntoa(astate->addr),
378 	    astate->probes ? astate->probes : PROBE_NUM, PROBE_NUM,
379 	    timespec_to_double(&tv));
380 	if (arp_request(ifp, NULL, &astate->addr) == -1)
381 		logerr(__func__);
382 }
383 
384 void
385 arp_probe(struct arp_state *astate)
386 {
387 
388 	if (arp_open(astate->iface) == -1) {
389 		logerr(__func__);
390 		return;
391 	} else {
392 		const struct iarp_state *state = ARP_CSTATE(astate->iface);
393 
394 		if (bpf_arp(astate->iface, state->bpf_fd) == -1)
395 			logerr(__func__);
396 	}
397 	astate->probes = 0;
398 	logdebugx("%s: probing for %s",
399 	    astate->iface->name, inet_ntoa(astate->addr));
400 	arp_probe1(astate);
401 }
402 #endif	/* ARP */
403 
404 static struct arp_state *
405 arp_find(struct interface *ifp, const struct in_addr *addr)
406 {
407 	struct iarp_state *state;
408 	struct arp_state *astate;
409 
410 	if ((state = ARP_STATE(ifp)) == NULL)
411 		goto out;
412 	TAILQ_FOREACH(astate, &state->arp_states, next) {
413 		if (astate->addr.s_addr == addr->s_addr && astate->iface == ifp)
414 			return astate;
415 	}
416 out:
417 	errno = ESRCH;
418 	return NULL;
419 }
420 
421 static void
422 arp_announced(void *arg)
423 {
424 	struct arp_state *astate = arg;
425 
426 	if (astate->announced_cb) {
427 		astate->announced_cb(astate);
428 		return;
429 	}
430 
431 	/* Keep the ARP state open to handle ongoing ACD. */
432 }
433 
434 static void
435 arp_announce1(void *arg)
436 {
437 	struct arp_state *astate = arg;
438 	struct interface *ifp = astate->iface;
439 	struct ipv4_addr *ia;
440 
441 	if (++astate->claims < ANNOUNCE_NUM)
442 		logdebugx("%s: ARP announcing %s (%d of %d), "
443 		    "next in %d.0 seconds",
444 		    ifp->name, inet_ntoa(astate->addr),
445 		    astate->claims, ANNOUNCE_NUM, ANNOUNCE_WAIT);
446 	else
447 		logdebugx("%s: ARP announcing %s (%d of %d)",
448 		    ifp->name, inet_ntoa(astate->addr),
449 		    astate->claims, ANNOUNCE_NUM);
450 
451 	/* The kernel will send a Gratuitous ARP for newly added addresses.
452 	 * So we can avoid sending the same.
453 	 * Linux is special and doesn't send one. */
454 	ia = ipv4_iffindaddr(ifp, &astate->addr, NULL);
455 #ifndef __linux__
456 	if (astate->claims == 1 && ia != NULL && ia->flags & IPV4_AF_NEW)
457 		goto skip_request;
458 #endif
459 
460 	if (arp_request(ifp, &astate->addr, &astate->addr) == -1)
461 		logerr(__func__);
462 
463 #ifndef __linux__
464 skip_request:
465 #endif
466 	/* No longer a new address. */
467 	if (ia != NULL)
468 		ia->flags |= ~IPV4_AF_NEW;
469 
470 	eloop_timeout_add_sec(ifp->ctx->eloop, ANNOUNCE_WAIT,
471 	    astate->claims < ANNOUNCE_NUM ? arp_announce1 : arp_announced,
472 	    astate);
473 }
474 
475 void
476 arp_announce(struct arp_state *astate)
477 {
478 	struct iarp_state *state;
479 	struct interface *ifp;
480 	struct arp_state *a2;
481 	int r;
482 
483 	if (arp_open(astate->iface) == -1) {
484 		logerr(__func__);
485 		return;
486 	}
487 
488 	/* Cancel any other ARP announcements for this address. */
489 	TAILQ_FOREACH(ifp, astate->iface->ctx->ifaces, next) {
490 		state = ARP_STATE(ifp);
491 		if (state == NULL)
492 			continue;
493 		TAILQ_FOREACH(a2, &state->arp_states, next) {
494 			if (astate == a2 ||
495 			    a2->addr.s_addr != astate->addr.s_addr)
496 				continue;
497 			r = eloop_timeout_delete(a2->iface->ctx->eloop,
498 			    a2->claims < ANNOUNCE_NUM
499 			    ? arp_announce1 : arp_announced,
500 			    a2);
501 			if (r == -1)
502 				logerr(__func__);
503 			else if (r != 0)
504 				logdebugx("%s: ARP announcement "
505 				    "of %s cancelled",
506 				    a2->iface->name,
507 				    inet_ntoa(a2->addr));
508 		}
509 	}
510 
511 	astate->claims = 0;
512 	arp_announce1(astate);
513 }
514 
515 void
516 arp_ifannounceaddr(struct interface *ifp, const struct in_addr *ia)
517 {
518 	struct arp_state *astate;
519 
520 	if (ifp->flags & IFF_NOARP)
521 		return;
522 
523 	astate = arp_find(ifp, ia);
524 	if (astate == NULL) {
525 		astate = arp_new(ifp, ia);
526 		if (astate == NULL)
527 			return;
528 		astate->announced_cb = arp_free;
529 	}
530 	arp_announce(astate);
531 }
532 
533 void
534 arp_announceaddr(struct dhcpcd_ctx *ctx, const struct in_addr *ia)
535 {
536 	struct interface *ifp, *iff = NULL;
537 	struct ipv4_addr *iap;
538 
539 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
540 		if (!ifp->active || ifp->carrier <= LINK_DOWN)
541 			continue;
542 		iap = ipv4_iffindaddr(ifp, ia, NULL);
543 		if (iap == NULL)
544 			continue;
545 #ifdef IN_IFF_NOTUSEABLE
546 		if (!(iap->addr_flags & IN_IFF_NOTUSEABLE))
547 			continue;
548 #endif
549 		if (iff != NULL && iff->metric < ifp->metric)
550 			continue;
551 		iff = ifp;
552 	}
553 	if (iff == NULL)
554 		return;
555 
556 	arp_ifannounceaddr(iff, ia);
557 }
558 
559 struct arp_state *
560 arp_new(struct interface *ifp, const struct in_addr *addr)
561 {
562 	struct iarp_state *state;
563 	struct arp_state *astate;
564 
565 	if ((state = ARP_STATE(ifp)) == NULL) {
566 	        ifp->if_data[IF_DATA_ARP] = malloc(sizeof(*state));
567 		state = ARP_STATE(ifp);
568 		if (state == NULL) {
569 			logerr(__func__);
570 			return NULL;
571 		}
572 		state->ifp = ifp;
573 		state->bpf_fd = -1;
574 		state->bpf_flags = 0;
575 		TAILQ_INIT(&state->arp_states);
576 	} else {
577 		if (addr && (astate = arp_find(ifp, addr)))
578 			return astate;
579 	}
580 
581 	if ((astate = calloc(1, sizeof(*astate))) == NULL) {
582 		logerr(__func__);
583 		return NULL;
584 	}
585 	astate->iface = ifp;
586 	if (addr)
587 		astate->addr = *addr;
588 	state = ARP_STATE(ifp);
589 	TAILQ_INSERT_TAIL(&state->arp_states, astate, next);
590 
591 	if (bpf_arp(ifp, state->bpf_fd) == -1)
592 		logerr(__func__); /* try and continue */
593 
594 	return astate;
595 }
596 
597 void
598 arp_cancel(struct arp_state *astate)
599 {
600 
601 	eloop_timeout_delete(astate->iface->ctx->eloop, NULL, astate);
602 }
603 
604 void
605 arp_free(struct arp_state *astate)
606 {
607 	struct interface *ifp;
608 	struct iarp_state *state;
609 
610 	if (astate == NULL)
611 		return;
612 
613 	ifp = astate->iface;
614 	eloop_timeout_delete(ifp->ctx->eloop, NULL, astate);
615 	state =	ARP_STATE(ifp);
616 	TAILQ_REMOVE(&state->arp_states, astate, next);
617 	if (astate->free_cb)
618 		astate->free_cb(astate);
619 	free(astate);
620 	arp_tryfree(state);
621 }
622 
623 void
624 arp_freeaddr(struct interface *ifp, const struct in_addr *ia)
625 {
626 	struct arp_state *astate;
627 
628 	astate = arp_find(ifp, ia);
629 	arp_free(astate);
630 }
631 
632 void
633 arp_drop(struct interface *ifp)
634 {
635 	struct iarp_state *state;
636 	struct arp_state *astate;
637 
638 	while ((state = ARP_STATE(ifp)) != NULL &&
639 	    (astate = TAILQ_FIRST(&state->arp_states)) != NULL)
640 		arp_free(astate);
641 
642 	/* No need to close because the last free will close */
643 }
644