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_raw(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,const uint8_t * src,const uint8_t * dst)309 static void ipv6_no_route_info(struct net_pkt *pkt,
310 			       const uint8_t *src,
311 			       const uint8_t *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 	struct in6_addr src_ip, dst_ip;
325 	bool found;
326 
327 	net_ipv6_addr_copy_raw(src_ip.s6_addr, hdr->src);
328 	net_ipv6_addr_copy_raw(dst_ip.s6_addr, hdr->dst);
329 
330 	/* Check if the packet can be routed */
331 	if (IS_ENABLED(CONFIG_NET_ROUTING)) {
332 		found = net_route_get_info(NULL, &dst_ip, &route, &nexthop);
333 	} else {
334 		found = net_route_get_info(net_pkt_iface(pkt), &dst_ip,
335 					   &route, &nexthop);
336 	}
337 
338 	if (found) {
339 		int ret;
340 
341 		if (IS_ENABLED(CONFIG_NET_ROUTING) &&
342 		    (net_ipv6_is_ll_addr(&src_ip) ||
343 		     net_ipv6_is_ll_addr(&dst_ip))) {
344 			/* RFC 4291 ch 2.5.6 */
345 			ipv6_no_route_info(pkt, hdr->src, hdr->dst);
346 
347 			goto drop;
348 		}
349 
350 		/* Used when detecting if the original link
351 		 * layer address length is changed or not.
352 		 */
353 		net_pkt_set_orig_iface(pkt, net_pkt_iface(pkt));
354 
355 		if (route) {
356 			net_pkt_set_iface(pkt, route->iface);
357 		}
358 
359 		if (IS_ENABLED(CONFIG_NET_ROUTING) &&
360 		    net_pkt_orig_iface(pkt) != net_pkt_iface(pkt) &&
361 		    !net_if_flag_is_set(net_pkt_orig_iface(pkt), NET_IF_IPV6_NO_ND)) {
362 			/* If the route interface to destination is
363 			 * different than the original route, then add
364 			 * route to original source.
365 			 */
366 			NET_DBG("Route pkt %p from %p to %p",
367 				pkt, net_pkt_orig_iface(pkt),
368 				net_pkt_iface(pkt));
369 
370 			add_route(net_pkt_orig_iface(pkt), &src_ip, 128);
371 		}
372 
373 		ret = net_route_packet(pkt, nexthop);
374 		if (ret < 0) {
375 			NET_DBG("Cannot re-route pkt %p via %s "
376 				"at iface %p (%d)",
377 				pkt, net_sprint_ipv6_addr(nexthop),
378 				net_pkt_iface(pkt), ret);
379 		} else {
380 			return NET_OK;
381 		}
382 	} else {
383 		struct net_if *iface = NULL;
384 		int ret;
385 
386 		if (net_if_ipv6_addr_onlink(&iface, &dst_ip)) {
387 			ret = net_route_packet_if(pkt, iface);
388 			if (ret < 0) {
389 				NET_DBG("Cannot re-route pkt %p "
390 					"at iface %p (%d)",
391 					pkt, net_pkt_iface(pkt), ret);
392 			} else {
393 				return NET_OK;
394 			}
395 		}
396 
397 		NET_DBG("No route to %s pkt %p dropped",
398 			net_sprint_ipv6_addr(&dst_ip), pkt);
399 	}
400 
401 drop:
402 	return NET_DROP;
403 }
404 #else
ipv6_route_packet(struct net_pkt * pkt,struct net_ipv6_hdr * hdr)405 static inline enum net_verdict ipv6_route_packet(struct net_pkt *pkt,
406 						 struct net_ipv6_hdr *hdr)
407 {
408 	ARG_UNUSED(pkt);
409 	ARG_UNUSED(hdr);
410 
411 	NET_DBG("DROP: Packet %p not for me", pkt);
412 
413 	return NET_DROP;
414 }
415 
416 #endif /* CONFIG_NET_ROUTE */
417 
418 
ipv6_forward_mcast_packet(struct net_pkt * pkt,struct net_ipv6_hdr * hdr)419 static enum net_verdict ipv6_forward_mcast_packet(struct net_pkt *pkt,
420 						 struct net_ipv6_hdr *hdr)
421 {
422 #if defined(CONFIG_NET_ROUTE_MCAST)
423 	int routed;
424 
425 	/* Continue processing without forwarding if:
426 	 *   1. routing loop could be created
427 	 *   2. the destination is of interface local scope
428 	 *   3. is from link local source
429 	 *   4. hop limit is or would become zero
430 	 */
431 	if (net_ipv6_is_addr_mcast_raw(hdr->src) ||
432 	    net_ipv6_is_addr_mcast_iface_raw(hdr->dst) ||
433 	    net_ipv6_is_ll_addr_raw(hdr->src) || hdr->hop_limit <= 1) {
434 		return NET_CONTINUE;
435 	}
436 
437 	routed = net_route_mcast_forward_packet(pkt, hdr);
438 
439 	if (routed < 0) {
440 		return NET_DROP;
441 	}
442 #endif /*CONFIG_NET_ROUTE_MCAST*/
443 	return NET_CONTINUE;
444 }
445 
extension_to_bitmap(uint8_t header,uint8_t ext_bitmap)446 static uint8_t extension_to_bitmap(uint8_t header, uint8_t ext_bitmap)
447 {
448 	switch (header) {
449 	case NET_IPV6_NEXTHDR_HBHO:
450 		return NET_IPV6_EXT_HDR_BITMAP_HBHO;
451 	case NET_IPV6_NEXTHDR_DESTO:
452 		/* Destination header can appears twice */
453 		if (ext_bitmap & NET_IPV6_EXT_HDR_BITMAP_DESTO1) {
454 			return NET_IPV6_EXT_HDR_BITMAP_DESTO2;
455 		}
456 		return NET_IPV6_EXT_HDR_BITMAP_DESTO1;
457 	case NET_IPV6_NEXTHDR_ROUTING:
458 		return NET_IPV6_EXT_HDR_BITMAP_ROUTING;
459 	case NET_IPV6_NEXTHDR_FRAG:
460 		return NET_IPV6_EXT_HDR_BITMAP_FRAG;
461 	default:
462 		return 0;
463 	}
464 }
465 
is_src_non_tentative_itself(const uint8_t * src)466 static inline bool is_src_non_tentative_itself(const uint8_t *src)
467 {
468 	struct net_if_addr *ifaddr;
469 
470 	ifaddr = net_if_ipv6_addr_lookup_raw(src, NULL);
471 	if (ifaddr != NULL && ifaddr->addr_state != NET_ADDR_TENTATIVE) {
472 		return true;
473 	}
474 
475 	return false;
476 }
477 
net_ipv6_input(struct net_pkt * pkt,bool is_loopback)478 enum net_verdict net_ipv6_input(struct net_pkt *pkt, bool is_loopback)
479 {
480 	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(ipv6_access, struct net_ipv6_hdr);
481 	NET_PKT_DATA_ACCESS_DEFINE(udp_access, struct net_udp_hdr);
482 	NET_PKT_DATA_ACCESS_DEFINE(tcp_access, struct net_tcp_hdr);
483 	struct net_if *pkt_iface = net_pkt_iface(pkt);
484 	enum net_verdict verdict = NET_DROP;
485 	int real_len = net_pkt_get_len(pkt);
486 	uint8_t ext_bitmap = 0U;
487 	uint16_t ext_len = 0U;
488 	uint8_t current_hdr, nexthdr, prev_hdr_offset;
489 	union net_proto_header proto_hdr;
490 	struct net_ipv6_hdr *hdr;
491 	struct net_if_mcast_addr *if_mcast_addr;
492 	union net_ip_header ip;
493 	int pkt_len;
494 
495 #if defined(CONFIG_NET_L2_IPIP)
496 	struct net_pkt_cursor hdr_start;
497 
498 	net_pkt_cursor_backup(pkt, &hdr_start);
499 #endif
500 
501 	net_stats_update_ipv6_recv(pkt_iface);
502 
503 	hdr = (struct net_ipv6_hdr *)net_pkt_get_data(pkt, &ipv6_access);
504 	if (!hdr) {
505 		NET_DBG("DROP: no buffer");
506 		goto drop;
507 	}
508 
509 	pkt_len = ntohs(hdr->len) + sizeof(struct net_ipv6_hdr);
510 	if (real_len < pkt_len) {
511 		NET_DBG("DROP: pkt len per hdr %d != pkt real len %d",
512 			pkt_len, real_len);
513 		goto drop;
514 	} else if (real_len > pkt_len) {
515 		net_pkt_update_length(pkt, pkt_len);
516 	}
517 
518 	NET_DBG("IPv6 packet len %d received from %s to %s", pkt_len,
519 		net_sprint_ipv6_addr(&hdr->src),
520 		net_sprint_ipv6_addr(&hdr->dst));
521 
522 	if (net_ipv6_is_addr_unspecified_raw(hdr->src)) {
523 		/* If this is a possible DAD message, let it pass. Extra checks
524 		 * are done in duplicate address detection code to verify that
525 		 * the packet is ok.
526 		 */
527 		if (!(IS_ENABLED(CONFIG_NET_IPV6_DAD) &&
528 		      net_ipv6_is_addr_solicited_node_raw(hdr->dst))) {
529 			NET_DBG("DROP: src addr is %s", "unspecified");
530 			goto drop;
531 		}
532 	}
533 
534 	if (net_ipv6_is_addr_mcast_raw(hdr->src) ||
535 	    net_ipv6_is_addr_mcast_scope_raw(hdr->dst, 0)) {
536 		NET_DBG("DROP: multicast packet");
537 		goto drop;
538 	}
539 
540 	if (!is_loopback) {
541 		if (net_ipv6_is_addr_loopback_raw(hdr->dst) ||
542 		    net_ipv6_is_addr_loopback_raw(hdr->src)) {
543 			NET_DBG("DROP: ::1 packet");
544 			goto drop;
545 		}
546 
547 		if (net_ipv6_is_addr_mcast_iface_raw(hdr->dst) ||
548 		    (net_ipv6_is_addr_mcast_group_raw(
549 			    hdr->dst,
550 			    (const uint8_t *)net_ipv6_unspecified_address()) &&
551 		     (net_ipv6_is_addr_mcast_site_raw(hdr->dst) ||
552 		      net_ipv6_is_addr_mcast_org_raw(hdr->dst)))) {
553 			NET_DBG("DROP: invalid scope multicast packet");
554 			goto drop;
555 		}
556 
557 		/* We need to pass the packet through in case our address is
558 		 * tentative, as receiving a packet with a tentative address as
559 		 * source means that duplicate address has been detected.
560 		 * This check is done later on if routing features are enabled.
561 		 */
562 		if (!IS_ENABLED(CONFIG_NET_ROUTING) && !IS_ENABLED(CONFIG_NET_ROUTE_MCAST) &&
563 		    is_src_non_tentative_itself(hdr->src)) {
564 			NET_DBG("DROP: src addr is %s", "mine");
565 			goto drop;
566 		}
567 	}
568 
569 	/* Reconstruct TC field. */
570 
571 	if (IS_ENABLED(CONFIG_NET_IP_DSCP_ECN)) {
572 		uint8_t tc = ((hdr->vtc << 4) & 0xF0) | ((hdr->tcflow >> 4) & 0x0F);
573 
574 		net_pkt_set_ip_dscp(pkt, net_ipv6_get_dscp(tc));
575 		net_pkt_set_ip_ecn(pkt, net_ipv6_get_ecn(tc));
576 	}
577 
578 	/* Check extension headers */
579 	net_pkt_set_ipv6_next_hdr(pkt, hdr->nexthdr);
580 	net_pkt_set_ipv6_ext_len(pkt, 0);
581 	net_pkt_set_ip_hdr_len(pkt, sizeof(struct net_ipv6_hdr));
582 	net_pkt_set_ipv6_hop_limit(pkt, NET_IPV6_HDR(pkt)->hop_limit);
583 	net_pkt_set_family(pkt, PF_INET6);
584 
585 	if (!net_pkt_filter_ip_recv_ok(pkt)) {
586 		/* drop the packet */
587 		NET_DBG("DROP: pkt filter");
588 		net_stats_update_filter_rx_ipv6_drop(net_pkt_iface(pkt));
589 		return NET_DROP;
590 	}
591 
592 	if (IS_ENABLED(CONFIG_NET_ROUTE_MCAST) &&
593 		net_ipv6_is_addr_mcast_raw(hdr->dst) && !net_pkt_forwarding(pkt)) {
594 		/* If the packet is a multicast packet and multicast routing
595 		 * is activated, we give the packet to the routing engine.
596 		 *
597 		 * But we only drop the packet if an error occurs, otherwise
598 		 * it might be eminent to respond on the packet on application
599 		 * layer.
600 		 */
601 		if (ipv6_forward_mcast_packet(pkt, hdr) == NET_DROP) {
602 			NET_DBG("DROP: forward mcast");
603 			goto drop;
604 		}
605 	}
606 
607 	if (!net_ipv6_is_addr_mcast_raw(hdr->dst)) {
608 		if (!net_if_ipv6_addr_lookup_by_iface_raw(pkt_iface, hdr->dst)) {
609 			if (ipv6_route_packet(pkt, hdr) == NET_OK) {
610 				return NET_OK;
611 			}
612 
613 			NET_DBG("DROP: no such address %s in iface %d",
614 				net_sprint_ipv6_addr(hdr->dst),
615 				net_if_get_by_iface(pkt_iface));
616 			goto drop;
617 		}
618 
619 		/* If we receive a packet with ll source address fe80: and
620 		 * destination address is one of ours, and if the packet would
621 		 * cross interface boundary, then drop the packet.
622 		 * RFC 4291 ch 2.5.6
623 		 */
624 		if (IS_ENABLED(CONFIG_NET_ROUTING) &&
625 		    net_ipv6_is_ll_addr_raw(hdr->src) &&
626 		    !net_if_ipv6_addr_lookup_by_iface_raw(pkt_iface, hdr->dst)) {
627 			ipv6_no_route_info(pkt, hdr->src, 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(hdr->src)) {
635 		NET_DBG("DROP: src addr is %s", "mine");
636 		goto drop;
637 	}
638 
639 	if (net_ipv6_is_addr_mcast_raw(hdr->dst) &&
640 	    !(net_ipv6_is_addr_mcast_iface_raw(hdr->dst) ||
641 	      net_ipv6_is_addr_mcast_link_all_nodes_raw(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_raw(hdr->dst, &pkt_iface);
653 		if (!if_mcast_addr ||
654 		    !net_if_ipv6_maddr_is_joined(if_mcast_addr)) {
655 			NET_DBG("DROP: packet for unjoined multicast address");
656 			goto drop;
657 		}
658 	}
659 
660 	net_pkt_acknowledge_data(pkt, &ipv6_access);
661 
662 	current_hdr = hdr->nexthdr;
663 	ext_bitmap = extension_to_bitmap(current_hdr, ext_bitmap);
664 	/* Offset of "nexthdr" in the IPv6 header */
665 	prev_hdr_offset = (uint8_t *)&hdr->nexthdr - (uint8_t *)hdr;
666 	net_pkt_set_ipv6_hdr_prev(pkt, prev_hdr_offset);
667 
668 	while (!net_ipv6_is_nexthdr_upper_layer(current_hdr)) {
669 		int exthdr_len;
670 		uint8_t ext_bit;
671 
672 		NET_DBG("IPv6 next header %d", current_hdr);
673 
674 		if (current_hdr == NET_IPV6_NEXTHDR_NONE) {
675 			/* There is nothing after this header (see RFC 2460,
676 			 * ch 4.7), so we can drop the packet now.
677 			 * This is not an error case so do not update drop
678 			 * statistics.
679 			 */
680 			NET_DBG("DROP: none nexthdr");
681 			return NET_DROP;
682 		}
683 
684 		/* Offset of "nexthdr" in the Extension Header */
685 		prev_hdr_offset = net_pkt_get_current_offset(pkt);
686 
687 		if (net_pkt_read_u8(pkt, &nexthdr)) {
688 			NET_DBG("DROP: pkt invalid read");
689 			goto drop;
690 		}
691 
692 		/* Detect duplicated Extension headers */
693 		ext_bit = extension_to_bitmap(nexthdr, ext_bitmap);
694 		if (ext_bit & ext_bitmap) {
695 			goto bad_hdr;
696 		}
697 		ext_bitmap |= ext_bit;
698 
699 		/* Make sure that nexthdr is valid, reject the Extension Header early otherwise.
700 		 * This is also important so that the "pointer" field in the ICMPv6 error
701 		 * message points to the "nexthdr" field.
702 		 */
703 		switch (nexthdr) {
704 		case NET_IPV6_NEXTHDR_HBHO:
705 			/* Hop-by-hop header can appear only once and must appear right after
706 			 * the IPv6 header. Consequently the "nexthdr" field of an Extension
707 			 * Header can never be an HBH option.
708 			 */
709 			goto bad_hdr;
710 
711 		case NET_IPV6_NEXTHDR_DESTO:
712 		case NET_IPV6_NEXTHDR_FRAG:
713 		case NET_IPV6_NEXTHDR_NONE:
714 			/* Valid values */
715 			break;
716 
717 		default:
718 			if (net_ipv6_is_nexthdr_upper_layer(nexthdr)) {
719 				break;
720 			}
721 			goto bad_hdr;
722 		}
723 
724 		/* Process the current Extension Header */
725 		switch (current_hdr) {
726 		case NET_IPV6_NEXTHDR_HBHO:
727 		case NET_IPV6_NEXTHDR_DESTO:
728 			/* Process options below */
729 			break;
730 
731 		case NET_IPV6_NEXTHDR_FRAG:
732 			if (IS_ENABLED(CONFIG_NET_IPV6_FRAGMENT)) {
733 				net_pkt_set_ipv6_fragment_start(
734 					pkt,
735 					net_pkt_get_current_offset(pkt) - 1);
736 				return net_ipv6_handle_fragment_hdr(pkt, hdr,
737 								    current_hdr);
738 			}
739 
740 			goto bad_hdr;
741 
742 		default:
743 			/* Unsupported */
744 			goto bad_hdr;
745 		}
746 
747 		exthdr_len = ipv6_handle_ext_hdr_options(pkt, hdr, pkt_len);
748 		if (exthdr_len < 0) {
749 			NET_DBG("DROP: extension hdr len (%d)", exthdr_len);
750 			goto drop;
751 		}
752 
753 		ext_len += exthdr_len;
754 		current_hdr = nexthdr;
755 		/* Save the offset to "nexthdr" in case we need to overwrite it
756 		 * when processing a fragment header
757 		 */
758 		net_pkt_set_ipv6_hdr_prev(pkt, prev_hdr_offset);
759 	}
760 
761 	net_pkt_set_ipv6_ext_len(pkt, ext_len);
762 
763 	ip.ipv6 = hdr;
764 
765 	if (IS_ENABLED(CONFIG_NET_SOCKETS_INET_RAW)) {
766 		if (net_conn_raw_ip_input(pkt, &ip, current_hdr) == NET_DROP) {
767 			goto drop;
768 		}
769 	}
770 
771 	switch (current_hdr) {
772 	case IPPROTO_ICMPV6:
773 		verdict = net_icmpv6_input(pkt, hdr);
774 		break;
775 	case IPPROTO_TCP:
776 		proto_hdr.tcp = net_tcp_input(pkt, &tcp_access);
777 		if (proto_hdr.tcp) {
778 			verdict = NET_OK;
779 		}
780 
781 		NET_DBG("%s verdict %s", "TCP", net_verdict2str(verdict));
782 		break;
783 	case IPPROTO_UDP:
784 		proto_hdr.udp = net_udp_input(pkt, &udp_access);
785 		if (proto_hdr.udp) {
786 			verdict = NET_OK;
787 		}
788 
789 		NET_DBG("%s verdict %s", "UDP", net_verdict2str(verdict));
790 		break;
791 
792 #if defined(CONFIG_NET_L2_IPIP)
793 	case IPPROTO_IPV6:
794 	case IPPROTO_IPIP: {
795 		struct sockaddr_in6 remote_addr = { 0 };
796 		struct net_if *tunnel_iface;
797 
798 		remote_addr.sin6_family = AF_INET6;
799 		net_ipv6_addr_copy_raw((uint8_t *)&remote_addr.sin6_addr, hdr->src);
800 
801 		net_pkt_set_remote_address(pkt, (struct sockaddr *)&remote_addr,
802 					   sizeof(struct sockaddr_in6));
803 
804 		/* Get rid of the old IP header */
805 		net_pkt_cursor_restore(pkt, &hdr_start);
806 		net_pkt_pull(pkt, net_pkt_ip_hdr_len(pkt) +
807 			     net_pkt_ipv6_ext_len(pkt));
808 
809 		tunnel_iface = net_ipip_get_virtual_interface(net_pkt_iface(pkt));
810 		if (tunnel_iface != NULL && net_if_l2(tunnel_iface)->recv != NULL) {
811 			return net_if_l2(tunnel_iface)->recv(net_pkt_iface(pkt), pkt);
812 		}
813 	}
814 #endif
815 	}
816 
817 	if (verdict == NET_DROP) {
818 		NET_DBG("DROP: because verdict");
819 		goto drop;
820 	} else if (current_hdr == IPPROTO_ICMPV6) {
821 		NET_DBG("%s verdict %s", "ICMPv6", net_verdict2str(verdict));
822 		return verdict;
823 	}
824 
825 	verdict = net_conn_input(pkt, &ip, current_hdr, &proto_hdr);
826 
827 	NET_DBG("%s verdict %s", "Connection", net_verdict2str(verdict));
828 
829 	if (verdict != NET_DROP) {
830 		return verdict;
831 	}
832 
833 drop:
834 	net_stats_update_ipv6_drop(pkt_iface);
835 	return NET_DROP;
836 
837 bad_hdr:
838 	/* Send error message about parameter problem (RFC 2460) */
839 	net_icmpv6_send_error(pkt, NET_ICMPV6_PARAM_PROBLEM,
840 			      NET_ICMPV6_PARAM_PROB_NEXTHEADER,
841 			      net_pkt_get_current_offset(pkt) - 1);
842 
843 	NET_DBG("DROP: Unknown/wrong nexthdr type");
844 	net_stats_update_ip_errors_protoerr(pkt_iface);
845 
846 	return NET_DROP;
847 }
848 
849 #if defined(CONFIG_NET_IPV6_IID_STABLE)
check_reserved(const uint8_t * buf,size_t len)850 static bool check_reserved(const uint8_t *buf, size_t len)
851 {
852 	/* Subnet-Router Anycast (RFC 4291) */
853 	if (memcmp(buf, (uint8_t *)&(struct in6_addr)IN6ADDR_ANY_INIT, len) == 0) {
854 		return true;
855 	}
856 
857 	/* Reserved Subnet Anycast Addresses (RFC 2526)
858 	 *    FDFF:FFFF:FFFF:FF80 - FDFF:FFFF:FFFF:FFFF
859 	 */
860 	if (buf[0] == 0xFD && buf[1] == 0xFF && buf[2] == 0xFF &&
861 	    buf[3] == 0xFF && buf[4] == 0xFF && buf[5] == 0xFF &&
862 	    buf[6] == 0xFF && buf[7] >= 0x80) {
863 		return true;
864 	}
865 
866 	return false;
867 }
868 #endif /* CONFIG_NET_IPV6_IID_STABLE */
869 
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)870 static int gen_stable_iid(uint8_t if_index,
871 			  const struct in6_addr *prefix,
872 			  uint8_t *network_id, size_t network_id_len,
873 			  uint8_t dad_counter,
874 			  uint8_t *stable_iid,
875 			  size_t stable_iid_len)
876 {
877 #if defined(CONFIG_NET_IPV6_IID_STABLE)
878 	const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
879 	mbedtls_md_context_t ctx;
880 	uint8_t digest[32];
881 	int ret;
882 	static bool once;
883 	static uint8_t secret_key[16]; /* Min 128 bits, RFC 7217 ch 5 */
884 	struct {
885 		struct in6_addr prefix;
886 		uint8_t if_index;
887 		uint8_t network_id[16];
888 		uint8_t dad_counter;
889 	} buf = {
890 		.dad_counter = dad_counter,
891 	};
892 
893 	if (prefix == NULL) {
894 		NET_ERR("IPv6 prefix must be set for generating a stable IID");
895 		return -EINVAL;
896 	}
897 
898 	memcpy(&buf.prefix, prefix, sizeof(struct in6_addr));
899 
900 	buf.if_index = if_index;
901 
902 	if (network_id != NULL && network_id_len > 0) {
903 		memcpy(buf.network_id, network_id,
904 		       MIN(network_id_len, sizeof(buf.network_id)));
905 	}
906 
907 	if (!once) {
908 		sys_rand_get(&secret_key, sizeof(secret_key));
909 		once = true;
910 	}
911 
912 	mbedtls_md_init(&ctx);
913 	ret = mbedtls_md_setup(&ctx, md_info, true);
914 	if (ret != 0) {
915 		NET_DBG("Cannot %s hmac (%d)", "setup", ret);
916 		goto err;
917 	}
918 
919 	ret = mbedtls_md_hmac_starts(&ctx, secret_key, sizeof(secret_key));
920 	if (ret != 0) {
921 		NET_DBG("Cannot %s hmac (%d)", "start", ret);
922 		goto err;
923 	}
924 
925 	ret = mbedtls_md_hmac_update(&ctx, (uint8_t *)&buf, sizeof(buf));
926 	if (ret != 0) {
927 		NET_DBG("Cannot %s hmac (%d)", "update", ret);
928 		goto err;
929 	}
930 
931 	ret = mbedtls_md_hmac_finish(&ctx, digest);
932 	if (ret != 0) {
933 		NET_DBG("Cannot %s hmac (%d)", "finish", ret);
934 		goto err;
935 	}
936 
937 	memcpy(stable_iid, digest, MIN(sizeof(digest), stable_iid_len));
938 
939 	/* Check reserved addresses, RFC 5453 ch 3 */
940 	if (unlikely(check_reserved(stable_iid, stable_iid_len))) {
941 		LOG_HEXDUMP_DBG(stable_iid, stable_iid_len,
942 				"Generated IID is reserved");
943 		ret = -EINVAL;
944 		goto err;
945 	}
946 
947 err:
948 	mbedtls_md_free(&ctx);
949 
950 	return ret;
951 #else
952 	return -ENOTSUP;
953 #endif
954 }
955 
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)956 int net_ipv6_addr_generate_iid(struct net_if *iface,
957 			       const struct in6_addr *prefix,
958 			       uint8_t *network_id,
959 			       size_t network_id_len,
960 			       uint8_t dad_counter,
961 			       struct in6_addr *addr,
962 			       struct net_linkaddr *lladdr)
963 {
964 	struct in6_addr tmp_addr;
965 	uint8_t if_index;
966 
967 	if_index = (iface == NULL) ? net_if_get_by_iface(net_if_get_default())
968 		: net_if_get_by_iface(iface);
969 
970 	if (IS_ENABLED(CONFIG_NET_IPV6_IID_STABLE)) {
971 		struct in6_addr tmp_prefix = { 0 };
972 		int ret;
973 
974 		if (prefix == NULL) {
975 			UNALIGNED_PUT(htonl(0xfe800000), &tmp_prefix.s6_addr32[0]);
976 		} else {
977 			UNALIGNED_PUT(UNALIGNED_GET(&prefix->s6_addr32[0]),
978 				      &tmp_prefix.s6_addr32[0]);
979 			UNALIGNED_PUT(UNALIGNED_GET(&prefix->s6_addr32[1]),
980 				      &tmp_prefix.s6_addr32[1]);
981 		}
982 
983 		ret = gen_stable_iid(if_index, &tmp_prefix, network_id, network_id_len,
984 				     dad_counter, (uint8_t *)&tmp_addr + 8,
985 				     sizeof(tmp_addr) / 2);
986 		if (ret < 0) {
987 			return ret;
988 		}
989 	}
990 
991 	if (prefix == NULL) {
992 		UNALIGNED_PUT(htonl(0xfe800000), &tmp_addr.s6_addr32[0]);
993 		UNALIGNED_PUT(0, &tmp_addr.s6_addr32[1]);
994 	} else {
995 		UNALIGNED_PUT(UNALIGNED_GET(&prefix->s6_addr32[0]), &tmp_addr.s6_addr32[0]);
996 		UNALIGNED_PUT(UNALIGNED_GET(&prefix->s6_addr32[1]), &tmp_addr.s6_addr32[1]);
997 	}
998 
999 	if (IS_ENABLED(CONFIG_NET_IPV6_IID_EUI_64)) {
1000 		switch (lladdr->len) {
1001 		case 2:
1002 			/* The generated IPv6 shall not toggle the
1003 			 * Universal/Local bit. RFC 6282 ch 3.2.2
1004 			 */
1005 			if (lladdr->type == NET_LINK_IEEE802154) {
1006 				UNALIGNED_PUT(0, &tmp_addr.s6_addr32[2]);
1007 				tmp_addr.s6_addr[11] = 0xff;
1008 				tmp_addr.s6_addr[12] = 0xfe;
1009 				tmp_addr.s6_addr[13] = 0U;
1010 				tmp_addr.s6_addr[14] = lladdr->addr[0];
1011 				tmp_addr.s6_addr[15] = lladdr->addr[1];
1012 			}
1013 
1014 			break;
1015 		case 6:
1016 			/* We do not toggle the Universal/Local bit
1017 			 * in Bluetooth. See RFC 7668 ch 3.2.2
1018 			 */
1019 			memcpy(&tmp_addr.s6_addr[8], lladdr->addr, 3);
1020 			tmp_addr.s6_addr[11] = 0xff;
1021 			tmp_addr.s6_addr[12] = 0xfe;
1022 			memcpy(&tmp_addr.s6_addr[13], lladdr->addr + 3, 3);
1023 
1024 			if (lladdr->type == NET_LINK_ETHERNET) {
1025 				tmp_addr.s6_addr[8] ^= 0x02;
1026 			}
1027 
1028 			break;
1029 		case 8:
1030 			if (sizeof(lladdr->addr) < 8) {
1031 				NET_ERR("Invalid link layer address length %zu, expecting 8",
1032 					sizeof(lladdr->addr));
1033 				return -EINVAL;
1034 			}
1035 
1036 			memcpy(&tmp_addr.s6_addr[8], lladdr->addr, lladdr->len);
1037 			tmp_addr.s6_addr[8] ^= 0x02;
1038 			break;
1039 		}
1040 	}
1041 
1042 	NET_DBG("%s IID for iface %d %s",
1043 		IS_ENABLED(CONFIG_NET_IPV6_IID_STABLE) ? "Stable" : "EUI-64",
1044 		if_index, net_sprint_ipv6_addr(&tmp_addr));
1045 
1046 	memcpy(addr, &tmp_addr, sizeof(*addr));
1047 	return 0;
1048 }
1049 
net_ipv6_init(void)1050 void net_ipv6_init(void)
1051 {
1052 	net_ipv6_nbr_init();
1053 
1054 #if defined(CONFIG_NET_IPV6_MLD)
1055 	net_ipv6_mld_init();
1056 #endif
1057 }
1058