1 /** @file
2  * @brief IPv6 related functions
3  */
4 
5 /*
6  * Copyright (c) 2016 Intel Corporation
7  *
8  * SPDX-License-Identifier: Apache-2.0
9  */
10 
11 /* By default this prints too much data, set the value to 1 to see
12  * neighbor cache contents.
13  */
14 #define NET_DEBUG_NBR 0
15 
16 #include <zephyr/logging/log.h>
17 LOG_MODULE_REGISTER(net_ipv6, CONFIG_NET_IPV6_LOG_LEVEL);
18 
19 #include <errno.h>
20 #include <stdlib.h>
21 
22 #if defined(CONFIG_NET_IPV6_IID_STABLE)
23 #include <zephyr/random/random.h>
24 #include <mbedtls/md.h>
25 #endif /* CONFIG_NET_IPV6_IID_STABLE */
26 
27 #include <zephyr/net/net_core.h>
28 #include <zephyr/net/net_pkt.h>
29 #include <zephyr/net/net_stats.h>
30 #include <zephyr/net/net_context.h>
31 #include <zephyr/net/net_mgmt.h>
32 #include <zephyr/net/virtual.h>
33 #include <zephyr/net/ethernet.h>
34 #include "net_private.h"
35 #include "connection.h"
36 #include "icmpv6.h"
37 #include "udp_internal.h"
38 #include "tcp_internal.h"
39 #include "ipv6.h"
40 #include "nbr.h"
41 #include "6lo.h"
42 #include "route.h"
43 #include "net_stats.h"
44 
45 BUILD_ASSERT(sizeof(struct in6_addr) == NET_IPV6_ADDR_SIZE);
46 
47 /* Timeout value to be used when allocating net buffer during various
48  * neighbor discovery procedures.
49  */
50 #define ND_NET_BUF_TIMEOUT K_MSEC(100)
51 
52 /* Timeout for various buffer allocations in this file. */
53 #define NET_BUF_TIMEOUT K_MSEC(50)
54 
55 /* Maximum reachable time value specified in RFC 4861 section
56  * 6.2.1. Router Configuration Variables, AdvReachableTime
57  */
58 #define MAX_REACHABLE_TIME 3600000
59 
net_ipv6_create(struct net_pkt * pkt,const struct in6_addr * src,const struct in6_addr * dst)60 int net_ipv6_create(struct net_pkt *pkt,
61 		    const struct in6_addr *src,
62 		    const struct in6_addr *dst)
63 {
64 	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(ipv6_access, struct net_ipv6_hdr);
65 	struct net_ipv6_hdr *ipv6_hdr;
66 	uint8_t tc = 0;
67 
68 	ipv6_hdr = (struct net_ipv6_hdr *)net_pkt_get_data(pkt, &ipv6_access);
69 	if (!ipv6_hdr) {
70 		return -ENOBUFS;
71 	}
72 
73 	if (IS_ENABLED(CONFIG_NET_IP_DSCP_ECN)) {
74 		net_ipv6_set_dscp(&tc, net_pkt_ip_dscp(pkt));
75 		net_ipv6_set_ecn(&tc, net_pkt_ip_ecn(pkt));
76 	}
77 
78 	ipv6_hdr->vtc     = 0x60 | ((tc >> 4) & 0x0F);
79 	ipv6_hdr->tcflow  = (tc << 4) & 0xF0;
80 	ipv6_hdr->flow    = 0U;
81 	ipv6_hdr->len     = 0U;
82 	ipv6_hdr->nexthdr = 0U;
83 
84 	/* Set the hop limit by default from net_pkt as that could
85 	 * be set for example when sending NS. If the limit is 0,
86 	 * then take the value from socket.
87 	 */
88 	ipv6_hdr->hop_limit = net_pkt_ipv6_hop_limit(pkt);
89 	if (ipv6_hdr->hop_limit == 0U) {
90 		if (net_ipv6_is_addr_mcast(dst)) {
91 			if (net_pkt_context(pkt) != NULL) {
92 				ipv6_hdr->hop_limit =
93 					net_context_get_ipv6_mcast_hop_limit(net_pkt_context(pkt));
94 			} else {
95 				ipv6_hdr->hop_limit =
96 					net_if_ipv6_get_mcast_hop_limit(net_pkt_iface(pkt));
97 			}
98 		} else {
99 			if (net_pkt_context(pkt) != NULL) {
100 				ipv6_hdr->hop_limit =
101 					net_context_get_ipv6_hop_limit(net_pkt_context(pkt));
102 			} else {
103 				ipv6_hdr->hop_limit =
104 					net_if_ipv6_get_hop_limit(net_pkt_iface(pkt));
105 			}
106 		}
107 	}
108 
109 	net_ipv6_addr_copy_raw(ipv6_hdr->dst, (uint8_t *)dst);
110 	net_ipv6_addr_copy_raw(ipv6_hdr->src, (uint8_t *)src);
111 
112 	net_pkt_set_ip_hdr_len(pkt, sizeof(struct net_ipv6_hdr));
113 	net_pkt_set_ipv6_ext_len(pkt, 0);
114 
115 	return net_pkt_set_data(pkt, &ipv6_access);
116 }
117 
net_ipv6_finalize(struct net_pkt * pkt,uint8_t next_header_proto)118 int net_ipv6_finalize(struct net_pkt *pkt, uint8_t next_header_proto)
119 {
120 	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(ipv6_access, struct net_ipv6_hdr);
121 	struct net_ipv6_hdr *ipv6_hdr;
122 
123 	net_pkt_set_overwrite(pkt, true);
124 
125 	ipv6_hdr = (struct net_ipv6_hdr *)net_pkt_get_data(pkt, &ipv6_access);
126 	if (!ipv6_hdr) {
127 		return -ENOBUFS;
128 	}
129 
130 	ipv6_hdr->len = htons(net_pkt_get_len(pkt) -
131 			      sizeof(struct net_ipv6_hdr));
132 
133 	if (net_pkt_ipv6_next_hdr(pkt) != 255U) {
134 		ipv6_hdr->nexthdr = net_pkt_ipv6_next_hdr(pkt);
135 	} else {
136 		ipv6_hdr->nexthdr = next_header_proto;
137 	}
138 
139 	net_pkt_set_data(pkt, &ipv6_access);
140 
141 	if (net_pkt_ipv6_next_hdr(pkt) != 255U &&
142 	    net_pkt_skip(pkt, net_pkt_ipv6_ext_len(pkt))) {
143 		return -ENOBUFS;
144 	}
145 
146 	net_pkt_set_ll_proto_type(pkt, NET_ETH_PTYPE_IPV6);
147 
148 	if (IS_ENABLED(CONFIG_NET_UDP) &&
149 	    next_header_proto == IPPROTO_UDP) {
150 		return net_udp_finalize(pkt, false);
151 	} else if (IS_ENABLED(CONFIG_NET_TCP) &&
152 		   next_header_proto == IPPROTO_TCP) {
153 		return net_tcp_finalize(pkt, false);
154 	} else if (next_header_proto == IPPROTO_ICMPV6) {
155 		return net_icmpv6_finalize(pkt, false);
156 	}
157 
158 	return 0;
159 }
160 
ipv6_drop_on_unknown_option(struct net_pkt * pkt,struct net_ipv6_hdr * hdr,uint8_t opt_type,uint16_t opt_type_offset)161 static inline bool ipv6_drop_on_unknown_option(struct net_pkt *pkt,
162 					       struct net_ipv6_hdr *hdr,
163 					       uint8_t opt_type,
164 					       uint16_t opt_type_offset)
165 {
166 	/* RFC 2460 chapter 4.2 tells how to handle the unknown
167 	 * options by the two highest order bits of the option:
168 	 *
169 	 * 00: Skip over this option and continue processing the header.
170 	 * 01: Discard the packet.
171 	 * 10: Discard the packet and, regardless of whether or not the
172 	 *     packet's Destination Address was a multicast address,
173 	 *     send an ICMP Parameter Problem, Code 2, message to the packet's
174 	 *     Source Address, pointing to the unrecognized Option Type.
175 	 * 11: Discard the packet and, only if the packet's Destination
176 	 *     Address was not a multicast address, send an ICMP Parameter
177 	 *     Problem, Code 2, message to the packet's Source Address,
178 	 *     pointing to the unrecognized Option Type.
179 	 */
180 	NET_DBG("Unknown option %d (0x%02x) MSB %d - 0x%02x",
181 		opt_type, opt_type, opt_type >> 6, opt_type & 0xc0);
182 
183 	switch (opt_type & 0xc0) {
184 	case 0x00:
185 		return false;
186 	case 0x40:
187 		break;
188 	case 0xc0:
189 		if (net_ipv6_is_addr_mcast((struct in6_addr *)hdr->dst)) {
190 			break;
191 		}
192 
193 		__fallthrough;
194 	case 0x80:
195 		net_icmpv6_send_error(pkt, NET_ICMPV6_PARAM_PROBLEM,
196 				      NET_ICMPV6_PARAM_PROB_OPTION,
197 				      (uint32_t)opt_type_offset);
198 		break;
199 	}
200 
201 	return true;
202 }
203 
ipv6_handle_ext_hdr_options(struct net_pkt * pkt,struct net_ipv6_hdr * hdr,uint16_t pkt_len)204 static inline int ipv6_handle_ext_hdr_options(struct net_pkt *pkt,
205 					      struct net_ipv6_hdr *hdr,
206 					      uint16_t pkt_len)
207 {
208 	uint16_t exthdr_len = 0U;
209 	uint16_t length = 0U;
210 
211 	{
212 		uint8_t val = 0U;
213 
214 		if (net_pkt_read_u8(pkt, &val)) {
215 			return -ENOBUFS;
216 		}
217 		exthdr_len = val * 8U + 8;
218 	}
219 
220 	if (exthdr_len > pkt_len) {
221 		NET_DBG("Corrupted packet, extension header %d too long "
222 			"(max %d bytes)", exthdr_len, pkt_len);
223 		return -EINVAL;
224 	}
225 
226 	length += 2U;
227 
228 	while (length < exthdr_len) {
229 		uint16_t opt_type_offset;
230 		uint8_t opt_type, opt_len;
231 
232 		opt_type_offset = net_pkt_get_current_offset(pkt);
233 
234 		/* Each extension option has type and length - except
235 		 * Pad1 which has only a type without any length
236 		 */
237 		if (net_pkt_read_u8(pkt, &opt_type)) {
238 			return -ENOBUFS;
239 		}
240 
241 		if (opt_type != NET_IPV6_EXT_HDR_OPT_PAD1) {
242 			if (net_pkt_read_u8(pkt, &opt_len)) {
243 				return -ENOBUFS;
244 			}
245 		}
246 
247 		switch (opt_type) {
248 		case NET_IPV6_EXT_HDR_OPT_PAD1:
249 			NET_DBG("PAD1 option");
250 			length++;
251 			break;
252 		case NET_IPV6_EXT_HDR_OPT_PADN:
253 			NET_DBG("PADN option");
254 			length += opt_len + 2;
255 			net_pkt_skip(pkt, opt_len);
256 			break;
257 		default:
258 			/* Make sure that the option length is not too large.
259 			 * The former 1 + 1 is the length of extension type +
260 			 * length fields.
261 			 * The latter 1 + 1 is the length of the sub-option
262 			 * type and length fields.
263 			 */
264 			if (opt_len > (exthdr_len - (1 + 1 + 1 + 1))) {
265 				return -EINVAL;
266 			}
267 
268 			if (ipv6_drop_on_unknown_option(pkt, hdr,
269 							opt_type, opt_type_offset)) {
270 				return -ENOTSUP;
271 			}
272 
273 			if (net_pkt_skip(pkt, opt_len)) {
274 				return -ENOBUFS;
275 			}
276 
277 			length += opt_len + 2;
278 
279 			break;
280 		}
281 	}
282 
283 	return exthdr_len;
284 }
285 
286 #if defined(CONFIG_NET_ROUTE)
add_route(struct net_if * iface,struct in6_addr * addr,uint8_t prefix_len)287 static struct net_route_entry *add_route(struct net_if *iface,
288 					 struct in6_addr *addr,
289 					 uint8_t prefix_len)
290 {
291 	struct net_route_entry *route;
292 
293 	route = net_route_lookup(iface, addr);
294 	if (route) {
295 		return route;
296 	}
297 
298 	route = net_route_add(iface, addr, prefix_len, addr,
299 			      NET_IPV6_ND_INFINITE_LIFETIME,
300 			      NET_ROUTE_PREFERENCE_LOW);
301 
302 	NET_DBG("%s route to %s/%d iface %p", route ? "Add" : "Cannot add",
303 		net_sprint_ipv6_addr(addr), prefix_len, iface);
304 
305 	return route;
306 }
307 #endif /* CONFIG_NET_ROUTE */
308 
ipv6_no_route_info(struct net_pkt * pkt,struct in6_addr * src,struct in6_addr * dst)309 static void ipv6_no_route_info(struct net_pkt *pkt,
310 			       struct in6_addr *src,
311 			       struct in6_addr *dst)
312 {
313 	NET_DBG("Will not route pkt %p ll src %s to dst %s between interfaces",
314 		pkt, net_sprint_ipv6_addr(src),
315 		net_sprint_ipv6_addr(dst));
316 }
317 
318 #if defined(CONFIG_NET_ROUTE)
ipv6_route_packet(struct net_pkt * pkt,struct net_ipv6_hdr * hdr)319 static enum net_verdict ipv6_route_packet(struct net_pkt *pkt,
320 					  struct net_ipv6_hdr *hdr)
321 {
322 	struct net_route_entry *route;
323 	struct in6_addr *nexthop;
324 	bool found;
325 
326 	/* Check if the packet can be routed */
327 	if (IS_ENABLED(CONFIG_NET_ROUTING)) {
328 		found = net_route_get_info(NULL, (struct in6_addr *)hdr->dst,
329 					   &route, &nexthop);
330 	} else {
331 		found = net_route_get_info(net_pkt_iface(pkt),
332 					   (struct in6_addr *)hdr->dst,
333 					   &route, &nexthop);
334 	}
335 
336 	if (found) {
337 		int ret;
338 
339 		if (IS_ENABLED(CONFIG_NET_ROUTING) &&
340 		    (net_ipv6_is_ll_addr((struct in6_addr *)hdr->src) ||
341 		     net_ipv6_is_ll_addr((struct in6_addr *)hdr->dst))) {
342 			/* RFC 4291 ch 2.5.6 */
343 			ipv6_no_route_info(pkt, (struct in6_addr *)hdr->src,
344 					   (struct in6_addr *)hdr->dst);
345 			goto drop;
346 		}
347 
348 		/* Used when detecting if the original link
349 		 * layer address length is changed or not.
350 		 */
351 		net_pkt_set_orig_iface(pkt, net_pkt_iface(pkt));
352 
353 		if (route) {
354 			net_pkt_set_iface(pkt, route->iface);
355 		}
356 
357 		if (IS_ENABLED(CONFIG_NET_ROUTING) &&
358 		    net_pkt_orig_iface(pkt) != net_pkt_iface(pkt) &&
359 		    !net_if_flag_is_set(net_pkt_orig_iface(pkt), NET_IF_IPV6_NO_ND)) {
360 			/* If the route interface to destination is
361 			 * different than the original route, then add
362 			 * route to original source.
363 			 */
364 			NET_DBG("Route pkt %p from %p to %p",
365 				pkt, net_pkt_orig_iface(pkt),
366 				net_pkt_iface(pkt));
367 
368 			add_route(net_pkt_orig_iface(pkt),
369 				  (struct in6_addr *)hdr->src, 128);
370 		}
371 
372 		ret = net_route_packet(pkt, nexthop);
373 		if (ret < 0) {
374 			NET_DBG("Cannot re-route pkt %p via %s "
375 				"at iface %p (%d)",
376 				pkt, net_sprint_ipv6_addr(nexthop),
377 				net_pkt_iface(pkt), ret);
378 		} else {
379 			return NET_OK;
380 		}
381 	} else {
382 		struct net_if *iface = NULL;
383 		int ret;
384 
385 		if (net_if_ipv6_addr_onlink(&iface, (struct in6_addr *)hdr->dst)) {
386 			ret = net_route_packet_if(pkt, iface);
387 			if (ret < 0) {
388 				NET_DBG("Cannot re-route pkt %p "
389 					"at iface %p (%d)",
390 					pkt, net_pkt_iface(pkt), ret);
391 			} else {
392 				return NET_OK;
393 			}
394 		}
395 
396 		NET_DBG("No route to %s pkt %p dropped",
397 			net_sprint_ipv6_addr(&hdr->dst), pkt);
398 	}
399 
400 drop:
401 	return NET_DROP;
402 }
403 #else
ipv6_route_packet(struct net_pkt * pkt,struct net_ipv6_hdr * hdr)404 static inline enum net_verdict ipv6_route_packet(struct net_pkt *pkt,
405 						 struct net_ipv6_hdr *hdr)
406 {
407 	ARG_UNUSED(pkt);
408 	ARG_UNUSED(hdr);
409 
410 	NET_DBG("DROP: Packet %p not for me", pkt);
411 
412 	return NET_DROP;
413 }
414 
415 #endif /* CONFIG_NET_ROUTE */
416 
417 
ipv6_forward_mcast_packet(struct net_pkt * pkt,struct net_ipv6_hdr * hdr)418 static enum net_verdict ipv6_forward_mcast_packet(struct net_pkt *pkt,
419 						 struct net_ipv6_hdr *hdr)
420 {
421 #if defined(CONFIG_NET_ROUTE_MCAST)
422 	int routed;
423 
424 	/* Continue processing without forwarding if:
425 	 *   1. routing loop could be created
426 	 *   2. the destination is of interface local scope
427 	 *   3. is from link local source
428 	 *   4. hop limit is or would become zero
429 	 */
430 	if (net_ipv6_is_addr_mcast((struct in6_addr *)hdr->src) ||
431 	    net_ipv6_is_addr_mcast_iface((struct in6_addr *)hdr->dst) ||
432 	    net_ipv6_is_ll_addr((struct in6_addr *)hdr->src) || hdr->hop_limit <= 1) {
433 		return NET_CONTINUE;
434 	}
435 
436 	routed = net_route_mcast_forward_packet(pkt, hdr);
437 
438 	if (routed < 0) {
439 		return NET_DROP;
440 	}
441 #endif /*CONFIG_NET_ROUTE_MCAST*/
442 	return NET_CONTINUE;
443 }
444 
extension_to_bitmap(uint8_t header,uint8_t ext_bitmap)445 static uint8_t extension_to_bitmap(uint8_t header, uint8_t ext_bitmap)
446 {
447 	switch (header) {
448 	case NET_IPV6_NEXTHDR_HBHO:
449 		return NET_IPV6_EXT_HDR_BITMAP_HBHO;
450 	case NET_IPV6_NEXTHDR_DESTO:
451 		/* Destination header can appears twice */
452 		if (ext_bitmap & NET_IPV6_EXT_HDR_BITMAP_DESTO1) {
453 			return NET_IPV6_EXT_HDR_BITMAP_DESTO2;
454 		}
455 		return NET_IPV6_EXT_HDR_BITMAP_DESTO1;
456 	case NET_IPV6_NEXTHDR_ROUTING:
457 		return NET_IPV6_EXT_HDR_BITMAP_ROUTING;
458 	case NET_IPV6_NEXTHDR_FRAG:
459 		return NET_IPV6_EXT_HDR_BITMAP_FRAG;
460 	default:
461 		return 0;
462 	}
463 }
464 
is_src_non_tentative_itself(struct in6_addr * src)465 static inline bool is_src_non_tentative_itself(struct in6_addr *src)
466 {
467 	struct net_if_addr *ifaddr;
468 
469 	ifaddr = net_if_ipv6_addr_lookup(src, NULL);
470 	if (ifaddr != NULL && ifaddr->addr_state != NET_ADDR_TENTATIVE) {
471 		return true;
472 	}
473 
474 	return false;
475 }
476 
net_ipv6_input(struct net_pkt * pkt,bool is_loopback)477 enum net_verdict net_ipv6_input(struct net_pkt *pkt, bool is_loopback)
478 {
479 	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(ipv6_access, struct net_ipv6_hdr);
480 	NET_PKT_DATA_ACCESS_DEFINE(udp_access, struct net_udp_hdr);
481 	NET_PKT_DATA_ACCESS_DEFINE(tcp_access, struct net_tcp_hdr);
482 	struct net_if *pkt_iface = net_pkt_iface(pkt);
483 	enum net_verdict verdict = NET_DROP;
484 	int real_len = net_pkt_get_len(pkt);
485 	uint8_t ext_bitmap = 0U;
486 	uint16_t ext_len = 0U;
487 	uint8_t current_hdr, nexthdr, prev_hdr_offset;
488 	union net_proto_header proto_hdr;
489 	struct net_ipv6_hdr *hdr;
490 	struct net_if_mcast_addr *if_mcast_addr;
491 	union net_ip_header ip;
492 	int pkt_len;
493 
494 #if defined(CONFIG_NET_L2_IPIP)
495 	struct net_pkt_cursor hdr_start;
496 
497 	net_pkt_cursor_backup(pkt, &hdr_start);
498 #endif
499 
500 	net_stats_update_ipv6_recv(pkt_iface);
501 
502 	hdr = (struct net_ipv6_hdr *)net_pkt_get_data(pkt, &ipv6_access);
503 	if (!hdr) {
504 		NET_DBG("DROP: no buffer");
505 		goto drop;
506 	}
507 
508 	pkt_len = ntohs(hdr->len) + sizeof(struct net_ipv6_hdr);
509 	if (real_len < pkt_len) {
510 		NET_DBG("DROP: pkt len per hdr %d != pkt real len %d",
511 			pkt_len, real_len);
512 		goto drop;
513 	} else if (real_len > pkt_len) {
514 		net_pkt_update_length(pkt, pkt_len);
515 	}
516 
517 	NET_DBG("IPv6 packet len %d received from %s to %s", pkt_len,
518 		net_sprint_ipv6_addr(&hdr->src),
519 		net_sprint_ipv6_addr(&hdr->dst));
520 
521 	if (net_ipv6_is_addr_unspecified((struct in6_addr *)hdr->src)) {
522 		/* If this is a possible DAD message, let it pass. Extra checks
523 		 * are done in duplicate address detection code to verify that
524 		 * the packet is ok.
525 		 */
526 		if (!(IS_ENABLED(CONFIG_NET_IPV6_DAD) &&
527 		      net_ipv6_is_addr_solicited_node((struct in6_addr *)hdr->dst))) {
528 			NET_DBG("DROP: src addr is %s", "unspecified");
529 			goto drop;
530 		}
531 	}
532 
533 	if (net_ipv6_is_addr_mcast((struct in6_addr *)hdr->src) ||
534 	    net_ipv6_is_addr_mcast_scope((struct in6_addr *)hdr->dst, 0)) {
535 		NET_DBG("DROP: multicast packet");
536 		goto drop;
537 	}
538 
539 	if (!is_loopback) {
540 		if (net_ipv6_is_addr_loopback((struct in6_addr *)hdr->dst) ||
541 		    net_ipv6_is_addr_loopback((struct in6_addr *)hdr->src)) {
542 			NET_DBG("DROP: ::1 packet");
543 			goto drop;
544 		}
545 
546 		if (net_ipv6_is_addr_mcast_iface((struct in6_addr *)hdr->dst) ||
547 		    (net_ipv6_is_addr_mcast_group(
548 			    (struct in6_addr *)hdr->dst,
549 			    net_ipv6_unspecified_address()) &&
550 		     (net_ipv6_is_addr_mcast_site((struct in6_addr *)hdr->dst) ||
551 		      net_ipv6_is_addr_mcast_org((struct in6_addr *)hdr->dst)))) {
552 			NET_DBG("DROP: invalid scope multicast packet");
553 			goto drop;
554 		}
555 
556 		/* We need to pass the packet through in case our address is
557 		 * tentative, as receiving a packet with a tentative address as
558 		 * source means that duplicate address has been detected.
559 		 * This check is done later on if routing features are enabled.
560 		 */
561 		if (!IS_ENABLED(CONFIG_NET_ROUTING) && !IS_ENABLED(CONFIG_NET_ROUTE_MCAST) &&
562 		    is_src_non_tentative_itself((struct in6_addr *)hdr->src)) {
563 			NET_DBG("DROP: src addr is %s", "mine");
564 			goto drop;
565 		}
566 	}
567 
568 	/* Reconstruct TC field. */
569 
570 	if (IS_ENABLED(CONFIG_NET_IP_DSCP_ECN)) {
571 		uint8_t tc = ((hdr->vtc << 4) & 0xF0) | ((hdr->tcflow >> 4) & 0x0F);
572 
573 		net_pkt_set_ip_dscp(pkt, net_ipv6_get_dscp(tc));
574 		net_pkt_set_ip_ecn(pkt, net_ipv6_get_ecn(tc));
575 	}
576 
577 	/* Check extension headers */
578 	net_pkt_set_ipv6_next_hdr(pkt, hdr->nexthdr);
579 	net_pkt_set_ipv6_ext_len(pkt, 0);
580 	net_pkt_set_ip_hdr_len(pkt, sizeof(struct net_ipv6_hdr));
581 	net_pkt_set_ipv6_hop_limit(pkt, NET_IPV6_HDR(pkt)->hop_limit);
582 	net_pkt_set_family(pkt, PF_INET6);
583 
584 	if (!net_pkt_filter_ip_recv_ok(pkt)) {
585 		/* drop the packet */
586 		NET_DBG("DROP: pkt filter");
587 		return NET_DROP;
588 	}
589 
590 	if (IS_ENABLED(CONFIG_NET_ROUTE_MCAST) &&
591 		net_ipv6_is_addr_mcast((struct in6_addr *)hdr->dst) && !net_pkt_forwarding(pkt)) {
592 		/* If the packet is a multicast packet and multicast routing
593 		 * is activated, we give the packet to the routing engine.
594 		 *
595 		 * But we only drop the packet if an error occurs, otherwise
596 		 * it might be eminent to respond on the packet on application
597 		 * layer.
598 		 */
599 		if (ipv6_forward_mcast_packet(pkt, hdr) == NET_DROP) {
600 			NET_DBG("DROP: forward mcast");
601 			goto drop;
602 		}
603 	}
604 
605 	if (!net_ipv6_is_addr_mcast((struct in6_addr *)hdr->dst)) {
606 		if (!net_if_ipv6_addr_lookup_by_iface(pkt_iface, (struct in6_addr *)hdr->dst)) {
607 			if (ipv6_route_packet(pkt, hdr) == NET_OK) {
608 				return NET_OK;
609 			}
610 
611 			NET_DBG("DROP: no such address %s in iface %d",
612 				net_sprint_ipv6_addr((struct in6_addr *)hdr->dst),
613 				net_if_get_by_iface(pkt_iface));
614 			goto drop;
615 		}
616 
617 		/* If we receive a packet with ll source address fe80: and
618 		 * destination address is one of ours, and if the packet would
619 		 * cross interface boundary, then drop the packet.
620 		 * RFC 4291 ch 2.5.6
621 		 */
622 		if (IS_ENABLED(CONFIG_NET_ROUTING) &&
623 		    net_ipv6_is_ll_addr((struct in6_addr *)hdr->src) &&
624 		    !net_if_ipv6_addr_lookup_by_iface(
625 				pkt_iface, (struct in6_addr *)hdr->dst)) {
626 			ipv6_no_route_info(pkt, (struct in6_addr *)hdr->src,
627 					   (struct in6_addr *)hdr->dst);
628 			NET_DBG("DROP: cross interface boundary");
629 			goto drop;
630 		}
631 	}
632 
633 	if ((IS_ENABLED(CONFIG_NET_ROUTING) || IS_ENABLED(CONFIG_NET_ROUTE_MCAST)) &&
634 	    !is_loopback && is_src_non_tentative_itself((struct in6_addr *)hdr->src)) {
635 		NET_DBG("DROP: src addr is %s", "mine");
636 		goto drop;
637 	}
638 
639 	if (net_ipv6_is_addr_mcast((struct in6_addr *)hdr->dst) &&
640 	    !(net_ipv6_is_addr_mcast_iface((struct in6_addr *)hdr->dst) ||
641 	      net_ipv6_is_addr_mcast_link_all_nodes((struct in6_addr *)hdr->dst))) {
642 		/* If we receive a packet with a interface-local or
643 		 * link-local all-nodes multicast destination address we
644 		 * always have to pass it to the upper layer.
645 		 *
646 		 * For all other destination multicast addresses we have to
647 		 * check if one of the joined multicast groups on the
648 		 * originating interface of the packet matches. Otherwise the
649 		 * packet will be dropped.
650 		 * RFC4291 ch 2.7.1, ch 2.8
651 		 */
652 		if_mcast_addr = net_if_ipv6_maddr_lookup(
653 				    (struct in6_addr *)hdr->dst, &pkt_iface);
654 
655 		if (!if_mcast_addr ||
656 		    !net_if_ipv6_maddr_is_joined(if_mcast_addr)) {
657 			NET_DBG("DROP: packet for unjoined multicast address");
658 			goto drop;
659 		}
660 	}
661 
662 	net_pkt_acknowledge_data(pkt, &ipv6_access);
663 
664 	current_hdr = hdr->nexthdr;
665 	ext_bitmap = extension_to_bitmap(current_hdr, ext_bitmap);
666 	/* Offset of "nexthdr" in the IPv6 header */
667 	prev_hdr_offset = (uint8_t *)&hdr->nexthdr - (uint8_t *)hdr;
668 	net_pkt_set_ipv6_hdr_prev(pkt, prev_hdr_offset);
669 
670 	while (!net_ipv6_is_nexthdr_upper_layer(current_hdr)) {
671 		int exthdr_len;
672 		uint8_t ext_bit;
673 
674 		NET_DBG("IPv6 next header %d", current_hdr);
675 
676 		if (current_hdr == NET_IPV6_NEXTHDR_NONE) {
677 			/* There is nothing after this header (see RFC 2460,
678 			 * ch 4.7), so we can drop the packet now.
679 			 * This is not an error case so do not update drop
680 			 * statistics.
681 			 */
682 			NET_DBG("DROP: none nexthdr");
683 			return NET_DROP;
684 		}
685 
686 		/* Offset of "nexthdr" in the Extension Header */
687 		prev_hdr_offset = net_pkt_get_current_offset(pkt);
688 
689 		if (net_pkt_read_u8(pkt, &nexthdr)) {
690 			NET_DBG("DROP: pkt invalid read");
691 			goto drop;
692 		}
693 
694 		/* Detect duplicated Extension headers */
695 		ext_bit = extension_to_bitmap(nexthdr, ext_bitmap);
696 		if (ext_bit & ext_bitmap) {
697 			goto bad_hdr;
698 		}
699 		ext_bitmap |= ext_bit;
700 
701 		/* Make sure that nexthdr is valid, reject the Extension Header early otherwise.
702 		 * This is also important so that the "pointer" field in the ICMPv6 error
703 		 * message points to the "nexthdr" field.
704 		 */
705 		switch (nexthdr) {
706 		case NET_IPV6_NEXTHDR_HBHO:
707 			/* Hop-by-hop header can appear only once and must appear right after
708 			 * the IPv6 header. Consequently the "nexthdr" field of an Extension
709 			 * Header can never be an HBH option.
710 			 */
711 			goto bad_hdr;
712 
713 		case NET_IPV6_NEXTHDR_DESTO:
714 		case NET_IPV6_NEXTHDR_FRAG:
715 		case NET_IPV6_NEXTHDR_NONE:
716 			/* Valid values */
717 			break;
718 
719 		default:
720 			if (net_ipv6_is_nexthdr_upper_layer(nexthdr)) {
721 				break;
722 			}
723 			goto bad_hdr;
724 		}
725 
726 		/* Process the current Extension Header */
727 		switch (current_hdr) {
728 		case NET_IPV6_NEXTHDR_HBHO:
729 		case NET_IPV6_NEXTHDR_DESTO:
730 			/* Process options below */
731 			break;
732 
733 		case NET_IPV6_NEXTHDR_FRAG:
734 			if (IS_ENABLED(CONFIG_NET_IPV6_FRAGMENT)) {
735 				net_pkt_set_ipv6_fragment_start(
736 					pkt,
737 					net_pkt_get_current_offset(pkt) - 1);
738 				return net_ipv6_handle_fragment_hdr(pkt, hdr,
739 								    current_hdr);
740 			}
741 
742 			goto bad_hdr;
743 
744 		default:
745 			/* Unsupported */
746 			goto bad_hdr;
747 		}
748 
749 		exthdr_len = ipv6_handle_ext_hdr_options(pkt, hdr, pkt_len);
750 		if (exthdr_len < 0) {
751 			NET_DBG("DROP: extension hdr len (%d)", exthdr_len);
752 			goto drop;
753 		}
754 
755 		ext_len += exthdr_len;
756 		current_hdr = nexthdr;
757 		/* Save the offset to "nexthdr" in case we need to overwrite it
758 		 * when processing a fragment header
759 		 */
760 		net_pkt_set_ipv6_hdr_prev(pkt, prev_hdr_offset);
761 	}
762 
763 	net_pkt_set_ipv6_ext_len(pkt, ext_len);
764 
765 	switch (current_hdr) {
766 	case IPPROTO_ICMPV6:
767 		verdict = net_icmpv6_input(pkt, hdr);
768 		break;
769 	case IPPROTO_TCP:
770 		proto_hdr.tcp = net_tcp_input(pkt, &tcp_access);
771 		if (proto_hdr.tcp) {
772 			verdict = NET_OK;
773 		}
774 
775 		NET_DBG("%s verdict %s", "TCP", net_verdict2str(verdict));
776 		break;
777 	case IPPROTO_UDP:
778 		proto_hdr.udp = net_udp_input(pkt, &udp_access);
779 		if (proto_hdr.udp) {
780 			verdict = NET_OK;
781 		}
782 
783 		NET_DBG("%s verdict %s", "UDP", net_verdict2str(verdict));
784 		break;
785 
786 #if defined(CONFIG_NET_L2_IPIP)
787 	case IPPROTO_IPV6:
788 	case IPPROTO_IPIP: {
789 		struct sockaddr_in6 remote_addr = { 0 };
790 		struct net_if *tunnel_iface;
791 
792 		remote_addr.sin6_family = AF_INET6;
793 		net_ipv6_addr_copy_raw((uint8_t *)&remote_addr.sin6_addr, hdr->src);
794 
795 		net_pkt_set_remote_address(pkt, (struct sockaddr *)&remote_addr,
796 					   sizeof(struct sockaddr_in6));
797 
798 		/* Get rid of the old IP header */
799 		net_pkt_cursor_restore(pkt, &hdr_start);
800 		net_pkt_pull(pkt, net_pkt_ip_hdr_len(pkt) +
801 			     net_pkt_ipv6_ext_len(pkt));
802 
803 		tunnel_iface = net_ipip_get_virtual_interface(net_pkt_iface(pkt));
804 		if (tunnel_iface != NULL && net_if_l2(tunnel_iface)->recv != NULL) {
805 			return net_if_l2(tunnel_iface)->recv(net_pkt_iface(pkt), pkt);
806 		}
807 	}
808 #endif
809 	}
810 
811 	if (verdict == NET_DROP) {
812 		NET_DBG("DROP: because verdict");
813 		goto drop;
814 	} else if (current_hdr == IPPROTO_ICMPV6) {
815 		NET_DBG("%s verdict %s", "ICMPv6", net_verdict2str(verdict));
816 		return verdict;
817 	}
818 
819 	ip.ipv6 = hdr;
820 
821 	verdict = net_conn_input(pkt, &ip, current_hdr, &proto_hdr);
822 
823 	NET_DBG("%s verdict %s", "Connection", net_verdict2str(verdict));
824 
825 	if (verdict != NET_DROP) {
826 		return verdict;
827 	}
828 
829 drop:
830 	net_stats_update_ipv6_drop(pkt_iface);
831 	return NET_DROP;
832 
833 bad_hdr:
834 	/* Send error message about parameter problem (RFC 2460) */
835 	net_icmpv6_send_error(pkt, NET_ICMPV6_PARAM_PROBLEM,
836 			      NET_ICMPV6_PARAM_PROB_NEXTHEADER,
837 			      net_pkt_get_current_offset(pkt) - 1);
838 
839 	NET_DBG("DROP: Unknown/wrong nexthdr type");
840 	net_stats_update_ip_errors_protoerr(pkt_iface);
841 
842 	return NET_DROP;
843 }
844 
845 #if defined(CONFIG_NET_IPV6_IID_STABLE)
check_reserved(const uint8_t * buf,size_t len)846 static bool check_reserved(const uint8_t *buf, size_t len)
847 {
848 	/* Subnet-Router Anycast (RFC 4291) */
849 	if (memcmp(buf, (uint8_t *)&(struct in6_addr)IN6ADDR_ANY_INIT, len) == 0) {
850 		return true;
851 	}
852 
853 	/* Reserved Subnet Anycast Addresses (RFC 2526)
854 	 *    FDFF:FFFF:FFFF:FF80 - FDFF:FFFF:FFFF:FFFF
855 	 */
856 	if (buf[0] == 0xFD && buf[1] == 0xFF && buf[2] == 0xFF &&
857 	    buf[3] == 0xFF && buf[4] == 0xFF && buf[5] == 0xFF &&
858 	    buf[6] == 0xFF && buf[7] >= 0x80) {
859 		return true;
860 	}
861 
862 	return false;
863 }
864 #endif /* CONFIG_NET_IPV6_IID_STABLE */
865 
gen_stable_iid(uint8_t if_index,const struct in6_addr * prefix,uint8_t * network_id,size_t network_id_len,uint8_t dad_counter,uint8_t * stable_iid,size_t stable_iid_len)866 static int gen_stable_iid(uint8_t if_index,
867 			  const struct in6_addr *prefix,
868 			  uint8_t *network_id, size_t network_id_len,
869 			  uint8_t dad_counter,
870 			  uint8_t *stable_iid,
871 			  size_t stable_iid_len)
872 {
873 #if defined(CONFIG_NET_IPV6_IID_STABLE)
874 	const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
875 	mbedtls_md_context_t ctx;
876 	uint8_t digest[32];
877 	int ret;
878 	static bool once;
879 	static uint8_t secret_key[16]; /* Min 128 bits, RFC 7217 ch 5 */
880 	struct {
881 		struct in6_addr prefix;
882 		uint8_t if_index;
883 		uint8_t network_id[16];
884 		uint8_t dad_counter;
885 	} buf = {
886 		.dad_counter = dad_counter,
887 	};
888 
889 	if (prefix == NULL) {
890 		NET_ERR("IPv6 prefix must be set for generating a stable IID");
891 		return -EINVAL;
892 	}
893 
894 	memcpy(&buf.prefix, prefix, sizeof(struct in6_addr));
895 
896 	buf.if_index = if_index;
897 
898 	if (network_id != NULL && network_id_len > 0) {
899 		memcpy(buf.network_id, network_id,
900 		       MIN(network_id_len, sizeof(buf.network_id)));
901 	}
902 
903 	if (!once) {
904 		sys_rand_get(&secret_key, sizeof(secret_key));
905 		once = true;
906 	}
907 
908 	mbedtls_md_init(&ctx);
909 	ret = mbedtls_md_setup(&ctx, md_info, true);
910 	if (ret != 0) {
911 		NET_DBG("Cannot %s hmac (%d)", "setup", ret);
912 		goto err;
913 	}
914 
915 	ret = mbedtls_md_hmac_starts(&ctx, secret_key, sizeof(secret_key));
916 	if (ret != 0) {
917 		NET_DBG("Cannot %s hmac (%d)", "start", ret);
918 		goto err;
919 	}
920 
921 	ret = mbedtls_md_hmac_update(&ctx, (uint8_t *)&buf, sizeof(buf));
922 	if (ret != 0) {
923 		NET_DBG("Cannot %s hmac (%d)", "update", ret);
924 		goto err;
925 	}
926 
927 	ret = mbedtls_md_hmac_finish(&ctx, digest);
928 	if (ret != 0) {
929 		NET_DBG("Cannot %s hmac (%d)", "finish", ret);
930 		goto err;
931 	}
932 
933 	memcpy(stable_iid, digest, MIN(sizeof(digest), stable_iid_len));
934 
935 	/* Check reserved addresses, RFC 5453 ch 3 */
936 	if (unlikely(check_reserved(stable_iid, stable_iid_len))) {
937 		LOG_HEXDUMP_DBG(stable_iid, stable_iid_len,
938 				"Generated IID is reserved");
939 		ret = -EINVAL;
940 		goto err;
941 	}
942 
943 err:
944 	mbedtls_md_free(&ctx);
945 
946 	return ret;
947 #else
948 	return -ENOTSUP;
949 #endif
950 }
951 
net_ipv6_addr_generate_iid(struct net_if * iface,const struct in6_addr * prefix,uint8_t * network_id,size_t network_id_len,uint8_t dad_counter,struct in6_addr * addr,struct net_linkaddr * lladdr)952 int net_ipv6_addr_generate_iid(struct net_if *iface,
953 			       const struct in6_addr *prefix,
954 			       uint8_t *network_id,
955 			       size_t network_id_len,
956 			       uint8_t dad_counter,
957 			       struct in6_addr *addr,
958 			       struct net_linkaddr *lladdr)
959 {
960 	struct in6_addr tmp_addr;
961 	uint8_t if_index;
962 
963 	if_index = (iface == NULL) ? net_if_get_by_iface(net_if_get_default())
964 		: net_if_get_by_iface(iface);
965 
966 	if (IS_ENABLED(CONFIG_NET_IPV6_IID_STABLE)) {
967 		struct in6_addr tmp_prefix = { 0 };
968 		int ret;
969 
970 		if (prefix == NULL) {
971 			UNALIGNED_PUT(htonl(0xfe800000), &tmp_prefix.s6_addr32[0]);
972 		} else {
973 			UNALIGNED_PUT(UNALIGNED_GET(&prefix->s6_addr32[0]),
974 				      &tmp_prefix.s6_addr32[0]);
975 			UNALIGNED_PUT(UNALIGNED_GET(&prefix->s6_addr32[1]),
976 				      &tmp_prefix.s6_addr32[1]);
977 		}
978 
979 		ret = gen_stable_iid(if_index, &tmp_prefix, network_id, network_id_len,
980 				     dad_counter, (uint8_t *)&tmp_addr + 8,
981 				     sizeof(tmp_addr) / 2);
982 		if (ret < 0) {
983 			return ret;
984 		}
985 	}
986 
987 	if (prefix == NULL) {
988 		UNALIGNED_PUT(htonl(0xfe800000), &tmp_addr.s6_addr32[0]);
989 		UNALIGNED_PUT(0, &tmp_addr.s6_addr32[1]);
990 	} else {
991 		UNALIGNED_PUT(UNALIGNED_GET(&prefix->s6_addr32[0]), &tmp_addr.s6_addr32[0]);
992 		UNALIGNED_PUT(UNALIGNED_GET(&prefix->s6_addr32[1]), &tmp_addr.s6_addr32[1]);
993 	}
994 
995 	if (IS_ENABLED(CONFIG_NET_IPV6_IID_EUI_64)) {
996 		switch (lladdr->len) {
997 		case 2:
998 			/* The generated IPv6 shall not toggle the
999 			 * Universal/Local bit. RFC 6282 ch 3.2.2
1000 			 */
1001 			if (lladdr->type == NET_LINK_IEEE802154) {
1002 				UNALIGNED_PUT(0, &tmp_addr.s6_addr32[2]);
1003 				tmp_addr.s6_addr[11] = 0xff;
1004 				tmp_addr.s6_addr[12] = 0xfe;
1005 				tmp_addr.s6_addr[13] = 0U;
1006 				tmp_addr.s6_addr[14] = lladdr->addr[0];
1007 				tmp_addr.s6_addr[15] = lladdr->addr[1];
1008 			}
1009 
1010 			break;
1011 		case 6:
1012 			/* We do not toggle the Universal/Local bit
1013 			 * in Bluetooth. See RFC 7668 ch 3.2.2
1014 			 */
1015 			memcpy(&tmp_addr.s6_addr[8], lladdr->addr, 3);
1016 			tmp_addr.s6_addr[11] = 0xff;
1017 			tmp_addr.s6_addr[12] = 0xfe;
1018 			memcpy(&tmp_addr.s6_addr[13], lladdr->addr + 3, 3);
1019 
1020 			if (lladdr->type == NET_LINK_ETHERNET) {
1021 				tmp_addr.s6_addr[8] ^= 0x02;
1022 			}
1023 
1024 			break;
1025 		case 8:
1026 			memcpy(&tmp_addr.s6_addr[8], lladdr->addr, lladdr->len);
1027 			tmp_addr.s6_addr[8] ^= 0x02;
1028 			break;
1029 		}
1030 	}
1031 
1032 	NET_DBG("%s IID for iface %d %s",
1033 		IS_ENABLED(CONFIG_NET_IPV6_IID_STABLE) ? "Stable" : "EUI-64",
1034 		if_index, net_sprint_ipv6_addr(&tmp_addr));
1035 
1036 	memcpy(addr, &tmp_addr, sizeof(*addr));
1037 	return 0;
1038 }
1039 
net_ipv6_init(void)1040 void net_ipv6_init(void)
1041 {
1042 	net_ipv6_nbr_init();
1043 
1044 #if defined(CONFIG_NET_IPV6_MLD)
1045 	net_ipv6_mld_init();
1046 #endif
1047 }
1048