xref: /dragonfly/contrib/dhcpcd/src/arp.c (revision a705726d)
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 
210 static void
211 arp_packet(struct interface *ifp, uint8_t *data, size_t len)
212 {
213 	const struct interface *ifn;
214 	struct arphdr ar;
215 	struct arp_msg arm;
216 	const struct iarp_state *state;
217 	struct arp_state *astate, *astaten;
218 	uint8_t *hw_s, *hw_t;
219 
220 	/* We must have a full ARP header */
221 	if (len < sizeof(ar))
222 		return;
223 	memcpy(&ar, data, sizeof(ar));
224 
225 	if (!arp_validate(ifp, &ar)) {
226 #ifdef BPF_DEBUG
227 		logerrx("%s: ARP BPF validation failure", ifp->name);
228 #endif
229 		return;
230 	}
231 
232 	/* Get pointers to the hardware addresses */
233 	hw_s = data + sizeof(ar);
234 	hw_t = hw_s + ar.ar_hln + ar.ar_pln;
235 	/* Ensure we got all the data */
236 	if ((size_t)((hw_t + ar.ar_hln + ar.ar_pln) - data) > len)
237 		return;
238 	/* Ignore messages from ourself */
239 	TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
240 		if (ar.ar_hln == ifn->hwlen &&
241 		    memcmp(hw_s, ifn->hwaddr, ifn->hwlen) == 0)
242 			break;
243 	}
244 	if (ifn) {
245 #ifdef ARP_DEBUG
246 		logdebugx("%s: ignoring ARP from self", ifp->name);
247 #endif
248 		return;
249 	}
250 	/* Copy out the HW and IP addresses */
251 	memcpy(&arm.sha, hw_s, ar.ar_hln);
252 	memcpy(&arm.sip.s_addr, hw_s + ar.ar_hln, ar.ar_pln);
253 	memcpy(&arm.tha, hw_t, ar.ar_hln);
254 	memcpy(&arm.tip.s_addr, hw_t + ar.ar_hln, ar.ar_pln);
255 
256 	/* Match the ARP probe to our states.
257 	 * Ignore Unicast Poll, RFC1122. */
258 	state = ARP_CSTATE(ifp);
259 	TAILQ_FOREACH_SAFE(astate, &state->arp_states, next, astaten) {
260 		if (IN_ARE_ADDR_EQUAL(&arm.sip, &astate->addr) ||
261 		    (IN_IS_ADDR_UNSPECIFIED(&arm.sip) &&
262 		    IN_ARE_ADDR_EQUAL(&arm.tip, &astate->addr) &&
263 		    state->bpf_flags & BPF_BCAST))
264 			arp_found(astate, &arm);
265 	}
266 }
267 
268 static void
269 arp_close(struct interface *ifp)
270 {
271 	struct iarp_state *state;
272 
273 	if ((state = ARP_STATE(ifp)) == NULL || state->bpf_fd == -1)
274 		return;
275 
276 	eloop_event_delete(ifp->ctx->eloop, state->bpf_fd);
277 	bpf_close(ifp, state->bpf_fd);
278 	state->bpf_fd = -1;
279 	state->bpf_flags |= BPF_EOF;
280 }
281 
282 static void
283 arp_tryfree(struct interface *ifp)
284 {
285 	struct iarp_state *state = ARP_STATE(ifp);
286 
287 	/* If there are no more ARP states, close the socket. */
288 	if (TAILQ_FIRST(&state->arp_states) == NULL) {
289 		arp_close(ifp);
290 		if (state->bpf_flags & BPF_READING)
291 			state->bpf_flags |= BPF_EOF;
292 		else {
293 			free(state);
294 			ifp->if_data[IF_DATA_ARP] = NULL;
295 		}
296 	} else {
297 		if (bpf_arp(ifp, state->bpf_fd) == -1)
298 			logerr(__func__);
299 	}
300 }
301 
302 static void
303 arp_read(void *arg)
304 {
305 	struct interface *ifp = arg;
306 	struct iarp_state *state;
307 	uint8_t buf[ARP_LEN];
308 	ssize_t bytes;
309 
310 	/* Some RAW mechanisms are generic file descriptors, not sockets.
311 	 * This means we have no kernel call to just get one packet,
312 	 * so we have to process the entire buffer. */
313 	state = ARP_STATE(ifp);
314 	state->bpf_flags &= ~BPF_EOF;
315 	state->bpf_flags |= BPF_READING;
316 	while (!(state->bpf_flags & BPF_EOF)) {
317 		bytes = bpf_read(ifp, state->bpf_fd, buf, sizeof(buf),
318 				 &state->bpf_flags);
319 		if (bytes == -1) {
320 			logerr("%s: %s", __func__, ifp->name);
321 			arp_close(ifp);
322 			break;
323 		}
324 		arp_packet(ifp, buf, (size_t)bytes);
325 		/* Check we still have a state after processing. */
326 		if ((state = ARP_STATE(ifp)) == NULL)
327 			break;
328 	}
329 	if (state != NULL) {
330 		state->bpf_flags &= ~BPF_READING;
331 		/* Try and free the state if nothing left to do. */
332 		arp_tryfree(ifp);
333 	}
334 }
335 
336 static int
337 arp_open(struct interface *ifp)
338 {
339 	struct iarp_state *state;
340 
341 	state = ARP_STATE(ifp);
342 	if (state->bpf_fd == -1) {
343 		state->bpf_fd = bpf_open(ifp, bpf_arp);
344 		if (state->bpf_fd == -1)
345 			return -1;
346 		eloop_event_add(ifp->ctx->eloop, state->bpf_fd, arp_read, ifp);
347 	}
348 	return state->bpf_fd;
349 }
350 
351 static void
352 arp_probed(void *arg)
353 {
354 	struct arp_state *astate = arg;
355 
356 	timespecclear(&astate->defend);
357 	astate->not_found_cb(astate);
358 }
359 
360 static void
361 arp_probe1(void *arg)
362 {
363 	struct arp_state *astate = arg;
364 	struct interface *ifp = astate->iface;
365 	struct timespec tv;
366 
367 	if (++astate->probes < PROBE_NUM) {
368 		tv.tv_sec = PROBE_MIN;
369 		tv.tv_nsec = (suseconds_t)arc4random_uniform(
370 		    (PROBE_MAX - PROBE_MIN) * NSEC_PER_SEC);
371 		timespecnorm(&tv);
372 		eloop_timeout_add_tv(ifp->ctx->eloop, &tv, arp_probe1, astate);
373 	} else {
374 		tv.tv_sec = ANNOUNCE_WAIT;
375 		tv.tv_nsec = 0;
376 		eloop_timeout_add_tv(ifp->ctx->eloop, &tv, arp_probed, astate);
377 	}
378 	logdebugx("%s: ARP probing %s (%d of %d), next in %0.1f seconds",
379 	    ifp->name, inet_ntoa(astate->addr),
380 	    astate->probes ? astate->probes : PROBE_NUM, PROBE_NUM,
381 	    timespec_to_double(&tv));
382 	if (arp_request(ifp, NULL, &astate->addr) == -1)
383 		logerr(__func__);
384 }
385 
386 void
387 arp_probe(struct arp_state *astate)
388 {
389 
390 	if (arp_open(astate->iface) == -1) {
391 		logerr(__func__);
392 		return;
393 	} else {
394 		const struct iarp_state *state = ARP_CSTATE(astate->iface);
395 
396 		if (bpf_arp(astate->iface, state->bpf_fd) == -1)
397 			logerr(__func__);
398 	}
399 	astate->probes = 0;
400 	logdebugx("%s: probing for %s",
401 	    astate->iface->name, inet_ntoa(astate->addr));
402 	arp_probe1(astate);
403 }
404 #endif	/* ARP */
405 
406 static struct arp_state *
407 arp_find(struct interface *ifp, const struct in_addr *addr)
408 {
409 	struct iarp_state *state;
410 	struct arp_state *astate;
411 
412 	if ((state = ARP_STATE(ifp)) == NULL)
413 		goto out;
414 	TAILQ_FOREACH(astate, &state->arp_states, next) {
415 		if (astate->addr.s_addr == addr->s_addr && astate->iface == ifp)
416 			return astate;
417 	}
418 out:
419 	errno = ESRCH;
420 	return NULL;
421 }
422 
423 static void
424 arp_announced(void *arg)
425 {
426 	struct arp_state *astate = arg;
427 
428 	if (astate->announced_cb) {
429 		astate->announced_cb(astate);
430 		return;
431 	}
432 
433 	/* Keep the ARP state open to handle ongoing ACD. */
434 }
435 
436 static void
437 arp_announce1(void *arg)
438 {
439 	struct arp_state *astate = arg;
440 	struct interface *ifp = astate->iface;
441 	struct ipv4_addr *ia;
442 
443 	if (++astate->claims < ANNOUNCE_NUM)
444 		logdebugx("%s: ARP announcing %s (%d of %d), "
445 		    "next in %d.0 seconds",
446 		    ifp->name, inet_ntoa(astate->addr),
447 		    astate->claims, ANNOUNCE_NUM, ANNOUNCE_WAIT);
448 	else
449 		logdebugx("%s: ARP announcing %s (%d of %d)",
450 		    ifp->name, inet_ntoa(astate->addr),
451 		    astate->claims, ANNOUNCE_NUM);
452 
453 	/* The kernel will send a Gratuitous ARP for newly added addresses.
454 	 * So we can avoid sending the same.
455 	 * Linux is special and doesn't send one. */
456 	ia = ipv4_iffindaddr(ifp, &astate->addr, NULL);
457 #ifndef __linux__
458 	if (astate->claims == 1 && ia != NULL && ia->flags & IPV4_AF_NEW)
459 		goto skip_request;
460 #endif
461 
462 	if (arp_request(ifp, &astate->addr, &astate->addr) == -1)
463 		logerr(__func__);
464 
465 #ifndef __linux__
466 skip_request:
467 #endif
468 	/* No longer a new address. */
469 	if (ia != NULL)
470 		ia->flags |= ~IPV4_AF_NEW;
471 
472 	eloop_timeout_add_sec(ifp->ctx->eloop, ANNOUNCE_WAIT,
473 	    astate->claims < ANNOUNCE_NUM ? arp_announce1 : arp_announced,
474 	    astate);
475 }
476 
477 void
478 arp_announce(struct arp_state *astate)
479 {
480 	struct iarp_state *state;
481 	struct interface *ifp;
482 	struct arp_state *a2;
483 	int r;
484 
485 	if (arp_open(astate->iface) == -1) {
486 		logerr(__func__);
487 		return;
488 	}
489 
490 	/* Cancel any other ARP announcements for this address. */
491 	TAILQ_FOREACH(ifp, astate->iface->ctx->ifaces, next) {
492 		state = ARP_STATE(ifp);
493 		if (state == NULL)
494 			continue;
495 		TAILQ_FOREACH(a2, &state->arp_states, next) {
496 			if (astate == a2 ||
497 			    a2->addr.s_addr != astate->addr.s_addr)
498 				continue;
499 			r = eloop_timeout_delete(a2->iface->ctx->eloop,
500 			    a2->claims < ANNOUNCE_NUM
501 			    ? arp_announce1 : arp_announced,
502 			    a2);
503 			if (r == -1)
504 				logerr(__func__);
505 			else if (r != 0)
506 				logdebugx("%s: ARP announcement "
507 				    "of %s cancelled",
508 				    a2->iface->name,
509 				    inet_ntoa(a2->addr));
510 		}
511 	}
512 
513 	astate->claims = 0;
514 	arp_announce1(astate);
515 }
516 
517 void
518 arp_ifannounceaddr(struct interface *ifp, const struct in_addr *ia)
519 {
520 	struct arp_state *astate;
521 
522 	if (ifp->flags & IFF_NOARP)
523 		return;
524 
525 	astate = arp_find(ifp, ia);
526 	if (astate == NULL) {
527 		astate = arp_new(ifp, ia);
528 		if (astate == NULL)
529 			return;
530 		astate->announced_cb = arp_free;
531 	}
532 	arp_announce(astate);
533 }
534 
535 void
536 arp_announceaddr(struct dhcpcd_ctx *ctx, const struct in_addr *ia)
537 {
538 	struct interface *ifp, *iff = NULL;
539 	struct ipv4_addr *iap;
540 
541 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
542 		if (!ifp->active || ifp->carrier <= LINK_DOWN)
543 			continue;
544 		iap = ipv4_iffindaddr(ifp, ia, NULL);
545 		if (iap == NULL)
546 			continue;
547 #ifdef IN_IFF_NOTUSEABLE
548 		if (!(iap->addr_flags & IN_IFF_NOTUSEABLE))
549 			continue;
550 #endif
551 		if (iff != NULL && iff->metric < ifp->metric)
552 			continue;
553 		iff = ifp;
554 	}
555 	if (iff == NULL)
556 		return;
557 
558 	arp_ifannounceaddr(iff, ia);
559 }
560 
561 struct arp_state *
562 arp_new(struct interface *ifp, const struct in_addr *addr)
563 {
564 	struct iarp_state *state;
565 	struct arp_state *astate;
566 
567 	if ((state = ARP_STATE(ifp)) == NULL) {
568 	        ifp->if_data[IF_DATA_ARP] = malloc(sizeof(*state));
569 		state = ARP_STATE(ifp);
570 		if (state == NULL) {
571 			logerr(__func__);
572 			return NULL;
573 		}
574 		state->bpf_fd = -1;
575 		state->bpf_flags = 0;
576 		TAILQ_INIT(&state->arp_states);
577 	} else {
578 		if (addr && (astate = arp_find(ifp, addr)))
579 			return astate;
580 	}
581 
582 	if ((astate = calloc(1, sizeof(*astate))) == NULL) {
583 		logerr(__func__);
584 		return NULL;
585 	}
586 	astate->iface = ifp;
587 	if (addr)
588 		astate->addr = *addr;
589 	state = ARP_STATE(ifp);
590 	TAILQ_INSERT_TAIL(&state->arp_states, astate, next);
591 
592 	if (bpf_arp(ifp, state->bpf_fd) == -1)
593 		logerr(__func__); /* try and continue */
594 
595 	return astate;
596 }
597 
598 void
599 arp_cancel(struct arp_state *astate)
600 {
601 
602 	eloop_timeout_delete(astate->iface->ctx->eloop, NULL, astate);
603 }
604 
605 void
606 arp_free(struct arp_state *astate)
607 {
608 	struct interface *ifp;
609 	struct iarp_state *state;
610 
611 	if (astate == NULL)
612 		return;
613 
614 	ifp = astate->iface;
615 	eloop_timeout_delete(ifp->ctx->eloop, NULL, astate);
616 	state =	ARP_STATE(ifp);
617 	TAILQ_REMOVE(&state->arp_states, astate, next);
618 	if (astate->free_cb)
619 		astate->free_cb(astate);
620 	free(astate);
621 	arp_tryfree(ifp);
622 }
623 
624 void
625 arp_freeaddr(struct interface *ifp, const struct in_addr *ia)
626 {
627 	struct arp_state *astate;
628 
629 	astate = arp_find(ifp, ia);
630 	arp_free(astate);
631 }
632 
633 void
634 arp_drop(struct interface *ifp)
635 {
636 	struct iarp_state *state;
637 	struct arp_state *astate;
638 
639 	while ((state = ARP_STATE(ifp)) != NULL &&
640 	    (astate = TAILQ_FIRST(&state->arp_states)) != NULL)
641 		arp_free(astate);
642 
643 	/* No need to close because the last free will close */
644 }
645