1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2013 Allied Telesis Labs NZ
4  * Chris Packham, <judge.packham@gmail.com>
5  *
6  * Copyright (C) 2022 YADRO
7  * Viacheslav Mitrofanov <v.v.mitrofanov@yadro.com>
8  */
9 
10 /* Neighbour Discovery for IPv6 */
11 
12 #include <net.h>
13 #include <net6.h>
14 #include <ndisc.h>
15 #include <stdlib.h>
16 #include <linux/delay.h>
17 
18 /* IPv6 destination address of packet waiting for ND */
19 struct in6_addr net_nd_sol_packet_ip6 = ZERO_IPV6_ADDR;
20 /* IPv6 address we are expecting ND advert from */
21 static struct in6_addr net_nd_rep_packet_ip6 = ZERO_IPV6_ADDR;
22 /* MAC destination address of packet waiting for ND */
23 uchar *net_nd_packet_mac;
24 /* pointer to packet waiting to be transmitted after ND is resolved */
25 uchar *net_nd_tx_packet;
26 static uchar net_nd_packet_buf[PKTSIZE_ALIGN + PKTALIGN];
27 /* size of packet waiting to be transmitted */
28 int net_nd_tx_packet_size;
29 /* the timer for ND resolution */
30 ulong net_nd_timer_start;
31 /* the number of requests we have sent so far */
32 int net_nd_try;
33 struct in6_addr all_routers = ALL_ROUTERS_MULT_ADDR;
34 
35 #define MAX_RTR_SOLICITATIONS		3
36 /* The maximum time to delay sending the first router solicitation message. */
37 #define MAX_SOLICITATION_DELAY		1 // 1 second
38 /* The time to wait before sending the next router solicitation message. */
39 #define RTR_SOLICITATION_INTERVAL	4000 // 4 seconds
40 
41 #define IP6_NDISC_OPT_SPACE(len) (((len) + 2 + 7) & ~7)
42 
43 /**
44  * ndisc_insert_option() - Insert an option into a neighbor discovery packet
45  *
46  * @opt:	pointer to the option element of the neighbor discovery packet
47  * @type:	option type to insert
48  * @data:	option data to insert
49  * @len:	data length
50  * Return: the number of bytes inserted (which may be >= len)
51  */
ndisc_insert_option(__u8 * opt,int type,u8 * data,int len)52 static int ndisc_insert_option(__u8 *opt, int type, u8 *data, int len)
53 {
54 	int space = IP6_NDISC_OPT_SPACE(len);
55 
56 	opt[0] = type;
57 	opt[1] = space >> 3;
58 	memcpy(&opt[2], data, len);
59 	len += 2;
60 
61 	/* fill the remainder with 0 */
62 	if (space - len > 0)
63 		memset(&opt[len], '\0', space - len);
64 
65 	return space;
66 }
67 
68 /**
69  * ndisc_extract_enetaddr() - Extract the Ethernet address from a ND packet
70  *
71  * Note that the link layer address could be anything but the only networking
72  * media that u-boot supports is Ethernet so we assume we're extracting a 6
73  * byte Ethernet MAC address.
74  *
75  * @ndisc:	pointer to ND packet
76  * @enetaddr:	extracted MAC addr
77  */
ndisc_extract_enetaddr(struct nd_msg * ndisc,uchar enetaddr[6])78 static void ndisc_extract_enetaddr(struct nd_msg *ndisc, uchar enetaddr[6])
79 {
80 	memcpy(enetaddr, &ndisc->opt[2], 6);
81 }
82 
83 /**
84  * ndisc_has_option() - Check if the ND packet has the specified option set
85  *
86  * @ip6:	pointer to IPv6 header
87  * @type:	option type to check
88  * Return: 1 if ND has that option, 0 therwise
89  */
ndisc_has_option(struct ip6_hdr * ip6,__u8 type)90 static int ndisc_has_option(struct ip6_hdr *ip6, __u8 type)
91 {
92 	struct nd_msg *ndisc = (struct nd_msg *)(((uchar *)ip6) + IP6_HDR_SIZE);
93 
94 	if (ip6->payload_len <= sizeof(struct icmp6hdr))
95 		return 0;
96 
97 	return ndisc->opt[0] == type;
98 }
99 
ip6_send_ns(struct in6_addr * neigh_addr)100 static void ip6_send_ns(struct in6_addr *neigh_addr)
101 {
102 	struct in6_addr dst_adr;
103 	unsigned char enetaddr[6];
104 	struct nd_msg *msg;
105 	__u16 len;
106 	uchar *pkt;
107 	unsigned short csum;
108 	unsigned int pcsum;
109 
110 	debug("sending neighbor solicitation for %pI6c our address %pI6c\n",
111 	      neigh_addr, &net_link_local_ip6);
112 
113 	/* calculate src, dest IPv6 addr and dest Eth addr */
114 	ip6_make_snma(&dst_adr, neigh_addr);
115 	ip6_make_mult_ethdstaddr(enetaddr, &dst_adr);
116 	len = sizeof(struct icmp6hdr) + IN6ADDRSZ +
117 	    IP6_NDISC_OPT_SPACE(INETHADDRSZ);
118 
119 	pkt = (uchar *)net_tx_packet;
120 	pkt += net_set_ether(pkt, enetaddr, PROT_IP6);
121 	pkt += ip6_add_hdr(pkt, &net_link_local_ip6, &dst_adr, PROT_ICMPV6,
122 			   IPV6_NDISC_HOPLIMIT, len);
123 
124 	/* ICMPv6 - NS */
125 	msg = (struct nd_msg *)pkt;
126 	msg->icmph.icmp6_type = IPV6_NDISC_NEIGHBOUR_SOLICITATION;
127 	msg->icmph.icmp6_code = 0;
128 	memset(&msg->icmph.icmp6_cksum, 0, sizeof(__be16));
129 	memset(&msg->icmph.icmp6_unused, 0, sizeof(__be32));
130 
131 	/* Set the target address and llsaddr option */
132 	net_copy_ip6(&msg->target, neigh_addr);
133 	ndisc_insert_option(msg->opt, ND_OPT_SOURCE_LL_ADDR, net_ethaddr,
134 			    INETHADDRSZ);
135 
136 	/* checksum */
137 	pcsum = csum_partial((__u8 *)msg, len, 0);
138 	csum = csum_ipv6_magic(&net_link_local_ip6, &dst_adr,
139 			       len, PROT_ICMPV6, pcsum);
140 	msg->icmph.icmp6_cksum = csum;
141 	pkt += len;
142 
143 	/* send it! */
144 	net_send_packet(net_tx_packet, (pkt - net_tx_packet));
145 }
146 
147 /*
148  * ip6_send_rs() - Send IPv6 Router Solicitation Message.
149  *
150  * A router solicitation is sent to discover a router. RS message creation is
151  * based on RFC 4861 section 4.1. Router Solicitation Message Format.
152  */
ip6_send_rs(void)153 void ip6_send_rs(void)
154 {
155 	unsigned char enetaddr[6];
156 	struct rs_msg *msg;
157 	__u16 icmp_len;
158 	uchar *pkt;
159 	unsigned short csum;
160 	unsigned int pcsum;
161 	static unsigned int retry_count;
162 
163 	if (!ip6_is_unspecified_addr(&net_gateway6) &&
164 	    net_prefix_length != 0) {
165 		net_set_state(NETLOOP_SUCCESS);
166 		return;
167 	} else if (retry_count >= MAX_RTR_SOLICITATIONS) {
168 		net_set_state(NETLOOP_FAIL);
169 		net_set_timeout_handler(0, NULL);
170 		retry_count = 0;
171 		return;
172 	}
173 
174 	printf("ROUTER SOLICITATION %d\n", retry_count + 1);
175 
176 	ip6_make_mult_ethdstaddr(enetaddr, &all_routers);
177 	/*
178 	 * ICMP length is the size of ICMP header (8) + one option (8) = 16.
179 	 * The option is 2 bytes of type and length + 6 bytes for MAC.
180 	 */
181 	icmp_len = sizeof(struct icmp6hdr) + IP6_NDISC_OPT_SPACE(INETHADDRSZ);
182 
183 	pkt = (uchar *)net_tx_packet;
184 	pkt += net_set_ether(pkt, enetaddr, PROT_IP6);
185 	pkt += ip6_add_hdr(pkt, &net_link_local_ip6, &all_routers, PROT_ICMPV6,
186 			   IPV6_NDISC_HOPLIMIT, icmp_len);
187 
188 	/* ICMPv6 - RS */
189 	msg = (struct rs_msg *)pkt;
190 	msg->icmph.icmp6_type = IPV6_NDISC_ROUTER_SOLICITATION;
191 	msg->icmph.icmp6_code = 0;
192 	memset(&msg->icmph.icmp6_cksum, 0, sizeof(__be16));
193 	memset(&msg->icmph.icmp6_unused, 0, sizeof(__be32));
194 
195 	/* Set the llsaddr option */
196 	ndisc_insert_option(msg->opt, ND_OPT_SOURCE_LL_ADDR, net_ethaddr,
197 			    INETHADDRSZ);
198 
199 	/* checksum */
200 	pcsum = csum_partial((__u8 *)msg, icmp_len, 0);
201 	csum = csum_ipv6_magic(&net_link_local_ip6, &all_routers,
202 			       icmp_len, PROT_ICMPV6, pcsum);
203 	msg->icmph.icmp6_cksum = csum;
204 	pkt += icmp_len;
205 
206 	/* Wait up to 1 second if it is the first try to get the RA */
207 	if (retry_count == 0)
208 		udelay(((unsigned int)rand() % 1000000) * MAX_SOLICITATION_DELAY);
209 
210 	/* send it! */
211 	net_send_packet(net_tx_packet, (pkt - net_tx_packet));
212 
213 	retry_count++;
214 	net_set_timeout_handler(RTR_SOLICITATION_INTERVAL, ip6_send_rs);
215 }
216 
217 static void
ip6_send_na(uchar * eth_dst_addr,struct in6_addr * neigh_addr,struct in6_addr * target)218 ip6_send_na(uchar *eth_dst_addr, struct in6_addr *neigh_addr,
219 	    struct in6_addr *target)
220 {
221 	struct nd_msg *msg;
222 	__u16 len;
223 	uchar *pkt;
224 	unsigned short csum;
225 
226 	debug("sending neighbor advertisement for %pI6c to %pI6c (%pM)\n",
227 	      target, neigh_addr, eth_dst_addr);
228 
229 	len = sizeof(struct icmp6hdr) + IN6ADDRSZ +
230 	    IP6_NDISC_OPT_SPACE(INETHADDRSZ);
231 
232 	pkt = (uchar *)net_tx_packet;
233 	pkt += net_set_ether(pkt, eth_dst_addr, PROT_IP6);
234 	pkt += ip6_add_hdr(pkt, &net_link_local_ip6, neigh_addr,
235 			   PROT_ICMPV6, IPV6_NDISC_HOPLIMIT, len);
236 
237 	/* ICMPv6 - NA */
238 	msg = (struct nd_msg *)pkt;
239 	msg->icmph.icmp6_type = IPV6_NDISC_NEIGHBOUR_ADVERTISEMENT;
240 	msg->icmph.icmp6_code = 0;
241 	memset(&msg->icmph.icmp6_cksum, 0, sizeof(__be16));
242 	memset(&msg->icmph.icmp6_unused, 0, sizeof(__be32));
243 	msg->icmph.icmp6_dataun.u_nd_advt.solicited = 1;
244 	msg->icmph.icmp6_dataun.u_nd_advt.override = 1;
245 	/* Set the target address and lltargetaddr option */
246 	net_copy_ip6(&msg->target, target);
247 	ndisc_insert_option(msg->opt, ND_OPT_TARGET_LL_ADDR, net_ethaddr,
248 			    INETHADDRSZ);
249 
250 	/* checksum */
251 	csum = csum_ipv6_magic(&net_link_local_ip6,
252 			       neigh_addr, len, PROT_ICMPV6,
253 			       csum_partial((__u8 *)msg, len, 0));
254 	msg->icmph.icmp6_cksum = csum;
255 	pkt += len;
256 
257 	/* send it! */
258 	net_send_packet(net_tx_packet, (pkt - net_tx_packet));
259 }
260 
ndisc_request(void)261 void ndisc_request(void)
262 {
263 	if (!ip6_addr_in_subnet(&net_ip6, &net_nd_sol_packet_ip6,
264 				net_prefix_length)) {
265 		if (ip6_is_unspecified_addr(&net_gateway6)) {
266 			puts("## Warning: gatewayip6 is needed but not set\n");
267 			net_nd_rep_packet_ip6 = net_nd_sol_packet_ip6;
268 		} else {
269 			net_nd_rep_packet_ip6 = net_gateway6;
270 		}
271 	} else {
272 		net_nd_rep_packet_ip6 = net_nd_sol_packet_ip6;
273 	}
274 
275 	ip6_send_ns(&net_nd_rep_packet_ip6);
276 }
277 
ndisc_timeout_check(void)278 int ndisc_timeout_check(void)
279 {
280 	ulong t;
281 
282 	if (ip6_is_unspecified_addr(&net_nd_sol_packet_ip6))
283 		return 0;
284 
285 	t = get_timer(0);
286 
287 	/* check for NDISC timeout */
288 	if ((t - net_nd_timer_start) > NDISC_TIMEOUT) {
289 		net_nd_try++;
290 		if (net_nd_try >= NDISC_TIMEOUT_COUNT) {
291 			puts("\nNeighbour discovery retry count exceeded; "
292 			     "starting again\n");
293 			net_nd_try = 0;
294 			net_set_state(NETLOOP_FAIL);
295 		} else {
296 			net_nd_timer_start = t;
297 			ndisc_request();
298 		}
299 	}
300 	return 1;
301 }
302 
303 /*
304  * ndisc_init() - Make initial steps for ND state machine.
305  * Usually move variables into initial state.
306  */
ndisc_init(void)307 void ndisc_init(void)
308 {
309 	net_nd_packet_mac = NULL;
310 	net_nd_tx_packet = NULL;
311 	net_nd_sol_packet_ip6 = net_null_addr_ip6;
312 	net_nd_rep_packet_ip6 = net_null_addr_ip6;
313 	net_nd_tx_packet_size = 0;
314 	net_nd_tx_packet = &net_nd_packet_buf[0] + (PKTALIGN - 1);
315 	net_nd_tx_packet -= (ulong)net_nd_tx_packet % PKTALIGN;
316 }
317 
318 /*
319  * validate_ra() - Validate the router advertisement message.
320  *
321  * @ip6: Pointer to the router advertisement packet
322  *
323  * Check if the router advertisement message is valid. Conditions are
324  * according to RFC 4861 section 6.1.2. Validation of Router Advertisement
325  * Messages.
326  *
327  * Return: true if the message is valid and false if it is invalid.
328  */
validate_ra(struct ip6_hdr * ip6)329 bool validate_ra(struct ip6_hdr *ip6)
330 {
331 	struct icmp6hdr *icmp = (struct icmp6hdr *)(ip6 + 1);
332 
333 	/* ICMP length (derived from the IP length) should be 16 or more octets. */
334 	if (ip6->payload_len < 16)
335 		return false;
336 
337 	/* Source IP Address should be a valid link-local address. */
338 	if ((ntohs(ip6->saddr.s6_addr16[0]) & IPV6_LINK_LOCAL_MASK) !=
339 	    IPV6_LINK_LOCAL_PREFIX)
340 		return false;
341 
342 	/*
343 	 * The IP Hop Limit field should have a value of 255, i.e., the packet
344 	 * could not possibly have been forwarded by a router.
345 	 */
346 	if (ip6->hop_limit != 255)
347 		return false;
348 
349 	/* ICMP checksum has already been checked in net_ip6_handler. */
350 
351 	if (icmp->icmp6_code != 0)
352 		return false;
353 
354 	return true;
355 }
356 
357 /*
358  * process_ra() - Process the router advertisement packet.
359  *
360  * @ip6: Pointer to the router advertisement packet
361  * @len: Length of the router advertisement packet
362  *
363  * Process the received router advertisement message.
364  * Although RFC 4861 requires retaining at least two router addresses, we only
365  * keep one because of the U-Boot limitations and its goal of lightweight code.
366  *
367  * Return: 0 - RA is a default router and contains valid prefix information.
368  * Non-zero - RA options are invalid or do not indicate it is a default router
369  * or do not contain valid prefix information.
370  */
process_ra(struct ip6_hdr * ip6,int len)371 int process_ra(struct ip6_hdr *ip6, int len)
372 {
373 	/* Pointer to the ICMP section of the packet */
374 	struct icmp6hdr *icmp = (struct icmp6hdr *)(ip6 + 1);
375 	struct ra_msg *msg = (struct ra_msg *)icmp;
376 	int remaining_option_len = len - IP6_HDR_SIZE - sizeof(struct ra_msg);
377 	unsigned short int option_len;	/* Length of each option */
378 	/* Pointer to the ICMPv6 message options */
379 	unsigned char *option = NULL;
380 	/* 8-bit identifier of the type of ICMPv6 option */
381 	unsigned char type = 0;
382 	struct icmp6_ra_prefix_info *prefix = NULL;
383 
384 	if (len > ETH_MAX_MTU)
385 		return -EMSGSIZE;
386 	/* Ignore the packet if router lifetime is 0. */
387 	if (!icmp->icmp6_rt_lifetime)
388 		return -EOPNOTSUPP;
389 
390 	/* Processing the options */
391 	option = msg->opt;
392 	while (remaining_option_len > 0) {
393 		/* The 2nd byte of the option is its length. */
394 		option_len = option[1];
395 		/* All included options should have a positive length. */
396 		if (option_len == 0)
397 			return -EINVAL;
398 
399 		type = option[0];
400 		/* All option types except Prefix Information are ignored. */
401 		switch (type) {
402 		case ND_OPT_SOURCE_LL_ADDR:
403 		case ND_OPT_TARGET_LL_ADDR:
404 		case ND_OPT_REDIRECT_HDR:
405 		case ND_OPT_MTU:
406 			break;
407 		case ND_OPT_PREFIX_INFO:
408 			prefix = (struct icmp6_ra_prefix_info *)option;
409 			/* The link-local prefix 0xfe80::/10 is ignored. */
410 			if ((ntohs(prefix->prefix.s6_addr16[0]) &
411 			     IPV6_LINK_LOCAL_MASK) == IPV6_LINK_LOCAL_PREFIX)
412 				break;
413 			if (prefix->on_link && ntohl(prefix->valid_lifetime)) {
414 				net_prefix_length = prefix->prefix_len;
415 				net_gateway6 = ip6->saddr;
416 				return 0;
417 			}
418 			break;
419 		default:
420 			debug("Unknown IPv6 Neighbor Discovery Option 0x%x\n",
421 			      type);
422 		}
423 
424 		option_len <<= 3; /* Option length is a multiple of 8. */
425 		remaining_option_len -= option_len;
426 		option += option_len;
427 	}
428 
429 	return -EADDRNOTAVAIL;
430 }
431 
ndisc_receive(struct ethernet_hdr * et,struct ip6_hdr * ip6,int len)432 int ndisc_receive(struct ethernet_hdr *et, struct ip6_hdr *ip6, int len)
433 {
434 	struct icmp6hdr *icmp =
435 	    (struct icmp6hdr *)(((uchar *)ip6) + IP6_HDR_SIZE);
436 	struct nd_msg *ndisc = (struct nd_msg *)icmp;
437 	uchar neigh_eth_addr[6];
438 	int err = 0;	// The error code returned calling functions.
439 
440 	switch (icmp->icmp6_type) {
441 	case IPV6_NDISC_NEIGHBOUR_SOLICITATION:
442 		debug("received neighbor solicitation for %pI6c from %pI6c\n",
443 		      &ndisc->target, &ip6->saddr);
444 		if (ip6_is_our_addr(&ndisc->target) &&
445 		    ndisc_has_option(ip6, ND_OPT_SOURCE_LL_ADDR)) {
446 			ndisc_extract_enetaddr(ndisc, neigh_eth_addr);
447 			ip6_send_na(neigh_eth_addr, &ip6->saddr,
448 				    &ndisc->target);
449 		}
450 		break;
451 
452 	case IPV6_NDISC_NEIGHBOUR_ADVERTISEMENT:
453 		/* are we waiting for a reply ? */
454 		if (ip6_is_unspecified_addr(&net_nd_sol_packet_ip6))
455 			break;
456 
457 		if ((memcmp(&ndisc->target, &net_nd_rep_packet_ip6,
458 			    sizeof(struct in6_addr)) == 0) &&
459 		    ndisc_has_option(ip6, ND_OPT_TARGET_LL_ADDR)) {
460 			ndisc_extract_enetaddr(ndisc, neigh_eth_addr);
461 
462 			/* save address for later use */
463 			if (net_nd_packet_mac)
464 				memcpy(net_nd_packet_mac, neigh_eth_addr, 6);
465 
466 			/* modify header, and transmit it */
467 			memcpy(((struct ethernet_hdr *)net_nd_tx_packet)->et_dest,
468 			       neigh_eth_addr, 6);
469 
470 			net_send_packet(net_nd_tx_packet,
471 					net_nd_tx_packet_size);
472 
473 			/* no ND request pending now */
474 			net_nd_sol_packet_ip6 = net_null_addr_ip6;
475 			net_nd_tx_packet_size = 0;
476 			net_nd_packet_mac = NULL;
477 		}
478 		break;
479 	case IPV6_NDISC_ROUTER_SOLICITATION:
480 		break;
481 	case IPV6_NDISC_ROUTER_ADVERTISEMENT:
482 		debug("Received router advertisement for %pI6c from %pI6c\n",
483 		      &ip6->daddr, &ip6->saddr);
484 		/*
485 		 * If gateway and prefix are set, the RA packet is ignored. The
486 		 * reason is that the U-Boot code is supposed to be as compact
487 		 * as possible and does not need to take care of multiple
488 		 * routers. In addition to that, U-Boot does not want to handle
489 		 * scenarios like a router setting its lifetime to zero to
490 		 * indicate it is not routing anymore. U-Boot program has a
491 		 * short life when the system boots up and does not need such
492 		 * sophistication.
493 		 */
494 		if (!ip6_is_unspecified_addr(&net_gateway6) &&
495 		    net_prefix_length != 0) {
496 			break;
497 		}
498 		if (!validate_ra(ip6)) {
499 			debug("Invalid router advertisement message.\n");
500 			break;
501 		}
502 		err = process_ra(ip6, len);
503 		if (err)
504 			debug("Ignored router advertisement. Error: %d\n", err);
505 		else
506 			printf("Set gatewayip6: %pI6c, prefix_length: %d\n",
507 			       &net_gateway6, net_prefix_length);
508 		break;
509 	default:
510 		debug("Unexpected ICMPv6 type 0x%x\n", icmp->icmp6_type);
511 		return -1;
512 	}
513 
514 	return 0;
515 }
516