xref: /xnu-8792.61.2/bsd/netinet/ip_icmp.c (revision 42e220869062b56f8d7d0726fd4c88954f87902c)
1 /*
2  * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (c) 1982, 1986, 1988, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. All advertising materials mentioning features or use of this software
41  *    must display the following acknowledgement:
42  *	This product includes software developed by the University of
43  *	California, Berkeley and its contributors.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)ip_icmp.c	8.2 (Berkeley) 1/4/94
61  */
62 /*
63  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
64  * support for mandatory and extensible security protections.  This notice
65  * is included in support of clause 2.2 (b) of the Apple Public License,
66  * Version 2.0.
67  */
68 
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/mbuf.h>
72 #include <sys/mcache.h>
73 #include <sys/protosw.h>
74 #include <sys/socket.h>
75 #include <sys/time.h>
76 #include <sys/kernel.h>
77 #include <sys/sysctl.h>
78 
79 #include <machine/endian.h>
80 
81 #include <net/if.h>
82 #include <net/route.h>
83 #include <net/content_filter.h>
84 
85 #define _IP_VHL
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/in_var.h>
89 #include <netinet/ip.h>
90 #include <netinet/ip_icmp.h>
91 #include <netinet/ip_var.h>
92 #include <netinet/icmp_var.h>
93 #include <netinet/tcp.h>
94 #include <netinet/tcp_fsm.h>
95 #include <netinet/tcp_seq.h>
96 #include <netinet/tcp_timer.h>
97 #include <netinet/tcp_var.h>
98 #include <netinet/tcpip.h>
99 
100 #if IPSEC
101 #include <netinet6/ipsec.h>
102 #include <netkey/key.h>
103 #endif
104 
105 #if NECP
106 #include <net/necp.h>
107 #endif /* NECP */
108 
109 
110 /*
111  * ICMP routines: error generation, receive packet processing, and
112  * routines to turnaround packets back to the originator, and
113  * host table maintenance routines.
114  */
115 
116 struct  icmpstat icmpstat;
117 SYSCTL_STRUCT(_net_inet_icmp, ICMPCTL_STATS, stats,
118     CTLFLAG_RD | CTLFLAG_LOCKED,
119     &icmpstat, icmpstat, "");
120 
121 static int      icmpmaskrepl = 0;
122 SYSCTL_INT(_net_inet_icmp, ICMPCTL_MASKREPL, maskrepl,
123     CTLFLAG_RW | CTLFLAG_LOCKED,
124     &icmpmaskrepl, 0, "");
125 
126 static int      icmptimestamp = 0;
127 SYSCTL_INT(_net_inet_icmp, ICMPCTL_TIMESTAMP, timestamp,
128     CTLFLAG_RW | CTLFLAG_LOCKED,
129     &icmptimestamp, 0, "");
130 
131 static int      drop_redirect = 1;
132 SYSCTL_INT(_net_inet_icmp, OID_AUTO, drop_redirect,
133     CTLFLAG_RW | CTLFLAG_LOCKED,
134     &drop_redirect, 0, "");
135 
136 static int      log_redirect = 0;
137 SYSCTL_INT(_net_inet_icmp, OID_AUTO, log_redirect,
138     CTLFLAG_RW | CTLFLAG_LOCKED,
139     &log_redirect, 0, "");
140 
141 const static int icmp_datalen = 8;
142 /*
143  * ICMP broadcast echo sysctl
144  */
145 static int      icmpbmcastecho = 1;
146 SYSCTL_INT(_net_inet_icmp, OID_AUTO, bmcastecho, CTLFLAG_RW | CTLFLAG_LOCKED,
147     &icmpbmcastecho, 0, "");
148 
149 #if (DEBUG | DEVELOPMENT)
150 static int      icmpprintfs = 0;
151 SYSCTL_INT(_net_inet_icmp, OID_AUTO, verbose, CTLFLAG_RW | CTLFLAG_LOCKED,
152     &icmpprintfs, 0, "");
153 #endif
154 
155 static void     icmp_reflect(struct mbuf *);
156 static void     icmp_send(struct mbuf *, struct mbuf *);
157 
158 /*
159  * Generate packet gencount for ICMP for a given error type
160  * and code.
161  * We do it this way to ensure we only dedup the packets that belong
162  * to the same type, which is usually what port scanning and other such
163  * attack vectors depend on.
164  */
165 static uint32_t
icmp_error_packet_gencount(int type,int code)166 icmp_error_packet_gencount(int type, int code)
167 {
168 	return (PF_INET << 24) | (type << 16) | (code << 8);
169 }
170 
171 static int      suppress_icmp_port_unreach = 0;
172 SYSCTL_INT(_net_inet_icmp, OID_AUTO, suppress_icmp_port_unreach,
173     CTLFLAG_RW | CTLFLAG_LOCKED,
174     &suppress_icmp_port_unreach, 0,
175     "Suppress ICMP destination unreachable type with code port unreachable");
176 
177 /*
178  * Generate an error packet of type error
179  * in response to bad packet ip.
180  */
181 void
icmp_error(struct mbuf * n,int type,int code,u_int32_t dest,u_int32_t nextmtu)182 icmp_error(
183 	struct mbuf *n,
184 	int type,
185 	int code,
186 	u_int32_t dest,
187 	u_int32_t nextmtu)
188 {
189 	struct ip *oip = NULL;
190 	struct ip *nip = NULL;
191 	struct icmp *icp = NULL;
192 	struct mbuf *m = NULL;
193 	u_int32_t oiphlen = 0;
194 	u_int32_t icmplen = 0;
195 	u_int32_t icmpelen = 0;
196 	u_int32_t nlen = 0;
197 
198 	VERIFY((u_int)type <= ICMP_MAXTYPE);
199 	VERIFY(code <= UINT8_MAX);
200 
201 	/* Expect 32-bit aligned data pointer on strict-align platforms */
202 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(n);
203 
204 	if (type != ICMP_REDIRECT) {
205 		icmpstat.icps_error++;
206 	}
207 
208 	if (suppress_icmp_port_unreach &&
209 	    type == ICMP_UNREACH && code == ICMP_UNREACH_PORT) {
210 		goto freeit;
211 	}
212 	/*
213 	 * Don't send error:
214 	 *   if not the first fragment of message
215 	 *   if original packet was a multicast or broadcast packet
216 	 *   if the old packet protocol was ICMP
217 	 *   error message, only known informational types.
218 	 */
219 	if (n->m_flags & (M_BCAST | M_MCAST)) {
220 		goto freeit;
221 	}
222 
223 	/*
224 	 * Drop if IP header plus ICMP_MINLEN bytes are not contiguous
225 	 * in first mbuf.
226 	 */
227 	if (n->m_len < sizeof(struct ip) + ICMP_MINLEN) {
228 		goto freeit;
229 	}
230 
231 	oip = mtod(n, struct ip *);
232 	oiphlen = IP_VHL_HL(oip->ip_vhl) << 2;
233 	if (n->m_len < oiphlen + ICMP_MINLEN) {
234 		goto freeit;
235 	}
236 
237 #if (DEBUG | DEVELOPMENT)
238 	if (icmpprintfs > 1) {
239 		printf("icmp_error(0x%llx, %x, %d)\n",
240 		    (uint64_t)VM_KERNEL_ADDRPERM(oip), type, code);
241 	}
242 #endif
243 
244 	if (oip->ip_off & ~(IP_MF | IP_DF)) {
245 		goto freeit;
246 	}
247 
248 	if (oip->ip_p == IPPROTO_ICMP && type != ICMP_REDIRECT &&
249 	    n->m_len >= oiphlen + ICMP_MINLEN &&
250 	    !ICMP_INFOTYPE(((struct icmp *)(void *)((caddr_t)oip + oiphlen))->
251 	    icmp_type)) {
252 		icmpstat.icps_oldicmp++;
253 		goto freeit;
254 	}
255 
256 	/*
257 	 * Calculate the length to quote from original packet and prevent
258 	 * the ICMP mbuf from overflowing.
259 	 * Unfortunatly this is non-trivial since ip_forward()
260 	 * sends us truncated packets.
261 	 */
262 	nlen = m_length(n);
263 	if (oip->ip_p == IPPROTO_TCP) {
264 		struct tcphdr *th = NULL;
265 		u_int16_t tcphlen = 0;
266 
267 		/*
268 		 * If the packet got truncated and TCP header
269 		 * is not contained in the packet, send out
270 		 * standard reply with only IP header as payload
271 		 */
272 		if (oiphlen + sizeof(struct tcphdr) > n->m_len &&
273 		    n->m_next == NULL) {
274 			goto stdreply;
275 		}
276 
277 		/*
278 		 * Otherwise, pull up to get IP and TCP headers
279 		 * together
280 		 */
281 		if (n->m_len < (oiphlen + sizeof(struct tcphdr)) &&
282 		    (n = m_pullup(n, (oiphlen + sizeof(struct tcphdr)))) == NULL) {
283 			goto freeit;
284 		}
285 
286 		/*
287 		 * Reinit pointers derived from mbuf data pointer
288 		 * as things might have moved around with m_pullup
289 		 */
290 		oip = mtod(n, struct ip *);
291 		th = (struct tcphdr *)(void *)((caddr_t)oip + oiphlen);
292 
293 		if (th != ((struct tcphdr *)P2ROUNDDOWN(th,
294 		    sizeof(u_int32_t))) ||
295 		    ((th->th_off << 2) > UINT16_MAX)) {
296 			goto freeit;
297 		}
298 		tcphlen = (uint16_t)(th->th_off << 2);
299 
300 		/* Sanity checks */
301 		if (tcphlen < sizeof(struct tcphdr)) {
302 			goto freeit;
303 		}
304 		if (oip->ip_len < (oiphlen + tcphlen)) {
305 			goto freeit;
306 		}
307 		if ((oiphlen + tcphlen) > n->m_len && n->m_next == NULL) {
308 			goto stdreply;
309 		}
310 		if (n->m_len < (oiphlen + tcphlen) &&
311 		    (n = m_pullup(n, (oiphlen + tcphlen))) == NULL) {
312 			goto freeit;
313 		}
314 
315 		/*
316 		 * Reinit pointers derived from mbuf data pointer
317 		 * as things might have moved around with m_pullup
318 		 */
319 		oip = mtod(n, struct ip *);
320 		th = (struct tcphdr *)(void *)((caddr_t)oip + oiphlen);
321 
322 		icmpelen = max(tcphlen, min(icmp_datalen,
323 		    (oip->ip_len - oiphlen)));
324 	} else {
325 stdreply:       icmpelen = max(ICMP_MINLEN, min(icmp_datalen,
326 		    (oip->ip_len - oiphlen)));
327 	}
328 
329 	icmplen = min(oiphlen + icmpelen, nlen);
330 	if (icmplen < sizeof(struct ip)) {
331 		goto freeit;
332 	}
333 
334 	/*
335 	 * First, formulate icmp message
336 	 * Allocate enough space for the IP header, ICMP header
337 	 * and the payload (part of the original message to be sent back).
338 	 */
339 	if (MHLEN > (sizeof(struct ip) + ICMP_MINLEN + icmplen)) {
340 		m = m_gethdr(M_DONTWAIT, MT_HEADER);    /* MAC-OK */
341 	} else {
342 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
343 	}
344 
345 	if (m == NULL) {
346 		goto freeit;
347 	}
348 
349 	/*
350 	 * Further refine the payload length to the space
351 	 * remaining in mbuf after including the IP header and ICMP
352 	 * header.
353 	 */
354 	icmplen = min(icmplen, (u_int)M_TRAILINGSPACE(m) -
355 	    (u_int)(sizeof(struct ip) - ICMP_MINLEN));
356 	m_align(m, ICMP_MINLEN + icmplen);
357 	m->m_len = ICMP_MINLEN + icmplen; /* for ICMP header and data */
358 
359 	icp = mtod(m, struct icmp *);
360 	icmpstat.icps_outhist[type]++;
361 	icp->icmp_type = (u_char)type;
362 	if (type == ICMP_REDIRECT) {
363 		icp->icmp_gwaddr.s_addr = dest;
364 	} else {
365 		icp->icmp_void = 0;
366 		/*
367 		 * The following assignments assume an overlay with the
368 		 * zeroed icmp_void field.
369 		 */
370 		if (type == ICMP_PARAMPROB) {
371 			icp->icmp_pptr = (u_char)code;
372 			code = 0;
373 		} else if (type == ICMP_UNREACH &&
374 		    code == ICMP_UNREACH_NEEDFRAG && nextmtu != 0) {
375 			icp->icmp_nextmtu = htons((uint16_t)nextmtu);
376 		}
377 	}
378 
379 	icp->icmp_code = (u_char)code;
380 
381 	/*
382 	 * Copy icmplen worth of content from original
383 	 * mbuf (n) to the new packet after ICMP header.
384 	 */
385 	m_copydata(n, 0, icmplen, (caddr_t)&icp->icmp_ip);
386 	nip = &icp->icmp_ip;
387 
388 	/*
389 	 * Convert fields to network representation.
390 	 */
391 #if BYTE_ORDER != BIG_ENDIAN
392 	HTONS(nip->ip_len);
393 	HTONS(nip->ip_off);
394 #endif
395 	/*
396 	 * Set up ICMP message mbuf and copy old IP header (without options
397 	 * in front of ICMP message.
398 	 */
399 	m->m_data -= sizeof(struct ip);
400 	m->m_len += sizeof(struct ip);
401 	m->m_pkthdr.len = m->m_len;
402 	m->m_pkthdr.rcvif = n->m_pkthdr.rcvif;
403 	/*
404 	 * To avoid some flavors of port scanning and other attacks,
405 	 * use packet suppression without using any other sort of
406 	 * rate limiting with static bounds.
407 	 * XXX Not setting PKTF_FLOW_ID here because we were concerned
408 	 * about it triggering regression elsewhere outside of network stack
409 	 * where there might be an assumption around flow ID being non-zero.
410 	 * It should be noted though that previously if PKTF_FLOW_ID was not
411 	 * set, PF would have generated flow hash irrespective of ICMPv4/v6
412 	 * type. That doesn't happen now and PF only computes hash for ICMP
413 	 * types that need state creation (which is not true of error types).
414 	 * It would have been a problem because we really want all the ICMP
415 	 * error type packets to share the same flow ID for global suppression.
416 	 */
417 	m->m_pkthdr.comp_gencnt = icmp_error_packet_gencount(type, code);
418 
419 	nip = mtod(m, struct ip *);
420 	bcopy((caddr_t)oip, (caddr_t)nip, sizeof(struct ip));
421 	nip->ip_len = (uint16_t)m->m_len;
422 	nip->ip_vhl = IP_VHL_BORING;
423 	nip->ip_p = IPPROTO_ICMP;
424 	nip->ip_tos = 0;
425 	nip->ip_off = 0;
426 	icmp_reflect(m);
427 freeit:
428 	m_freem(n);
429 }
430 
431 /*
432  * Process a received ICMP message.
433  */
434 void
icmp_input(struct mbuf * m,int hlen)435 icmp_input(struct mbuf *m, int hlen)
436 {
437 	struct sockaddr_in icmpsrc, icmpdst, icmpgw;
438 	struct icmp *icp;
439 	struct ip *ip = mtod(m, struct ip *);
440 	int icmplen;
441 	int i;
442 	struct in_ifaddr *ia;
443 	void (*ctlfunc)(int, struct sockaddr *, void *, struct ifnet *);
444 	int code;
445 	boolean_t should_log_redirect = false;
446 
447 	/* Expect 32-bit aligned data pointer on strict-align platforms */
448 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
449 
450 	icmplen = ip->ip_len;
451 
452 	/*
453 	 * Locate icmp structure in mbuf, and check
454 	 * that not corrupted and of at least minimum length.
455 	 */
456 #if (DEBUG | DEVELOPMENT)
457 	if (icmpprintfs > 2) {
458 		char src_str[MAX_IPv4_STR_LEN];
459 		char dst_str[MAX_IPv4_STR_LEN];
460 
461 		inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
462 		inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
463 		printf("%s: from %s to %s, len %d\n",
464 		    __func__, src_str, dst_str, icmplen);
465 	}
466 #endif
467 	if (icmplen < ICMP_MINLEN) {
468 		icmpstat.icps_tooshort++;
469 		goto freeit;
470 	}
471 	i = hlen + min(icmplen, ICMP_ADVLENMIN);
472 	if (m->m_len < i && (m = m_pullup(m, i)) == NULL) {
473 		icmpstat.icps_tooshort++;
474 		return;
475 	}
476 	/* Re-seat the pointers, since `m_pullup' might have moved `m'. `icp' is re-seated below. */
477 	ip = mtod(m, struct ip *);
478 
479 	m->m_len -= hlen;
480 	m->m_data += hlen;
481 	icp = mtod(m, struct icmp *);
482 	if (in_cksum(m, icmplen) != 0) {
483 		icmpstat.icps_checksum++;
484 		goto freeit;
485 	}
486 	m->m_len += hlen;
487 	m->m_data -= hlen;
488 
489 #if (DEBUG | DEVELOPMENT)
490 	if (icmpprintfs > 2) {
491 		printf("icmp_input, type %d code %d\n", icp->icmp_type,
492 		    icp->icmp_code);
493 	}
494 #endif
495 
496 	/*
497 	 * Message type specific processing.
498 	 */
499 	if (icp->icmp_type > ICMP_MAXTYPE) {
500 		goto raw;
501 	}
502 
503 	/* Initialize */
504 	bzero(&icmpsrc, sizeof(icmpsrc));
505 	icmpsrc.sin_len = sizeof(struct sockaddr_in);
506 	icmpsrc.sin_family = AF_INET;
507 	bzero(&icmpdst, sizeof(icmpdst));
508 	icmpdst.sin_len = sizeof(struct sockaddr_in);
509 	icmpdst.sin_family = AF_INET;
510 	bzero(&icmpgw, sizeof(icmpgw));
511 	icmpgw.sin_len = sizeof(struct sockaddr_in);
512 	icmpgw.sin_family = AF_INET;
513 
514 	icmpstat.icps_inhist[icp->icmp_type]++;
515 	code = icp->icmp_code;
516 	switch (icp->icmp_type) {
517 	case ICMP_UNREACH:
518 		switch (code) {
519 		case ICMP_UNREACH_NET:
520 		case ICMP_UNREACH_HOST:
521 		case ICMP_UNREACH_SRCFAIL:
522 		case ICMP_UNREACH_NET_UNKNOWN:
523 		case ICMP_UNREACH_HOST_UNKNOWN:
524 		case ICMP_UNREACH_ISOLATED:
525 		case ICMP_UNREACH_TOSNET:
526 		case ICMP_UNREACH_TOSHOST:
527 		case ICMP_UNREACH_HOST_PRECEDENCE:
528 		case ICMP_UNREACH_PRECEDENCE_CUTOFF:
529 			code = PRC_UNREACH_NET;
530 			break;
531 
532 		case ICMP_UNREACH_NEEDFRAG:
533 			code = PRC_MSGSIZE;
534 			break;
535 
536 		/*
537 		 * RFC 1122, Sections 3.2.2.1 and 4.2.3.9.
538 		 * Treat subcodes 2,3 as immediate RST
539 		 */
540 		case ICMP_UNREACH_PROTOCOL:
541 		case ICMP_UNREACH_PORT:
542 			code = PRC_UNREACH_PORT;
543 			break;
544 
545 		case ICMP_UNREACH_NET_PROHIB:
546 		case ICMP_UNREACH_HOST_PROHIB:
547 		case ICMP_UNREACH_FILTER_PROHIB:
548 			code = PRC_UNREACH_ADMIN_PROHIB;
549 			break;
550 
551 		default:
552 			goto badcode;
553 		}
554 		goto deliver;
555 
556 	case ICMP_TIMXCEED:
557 		if (code > 1) {
558 			goto badcode;
559 		}
560 		code += PRC_TIMXCEED_INTRANS;
561 		goto deliver;
562 
563 	case ICMP_PARAMPROB:
564 		if (code > 1) {
565 			goto badcode;
566 		}
567 		code = PRC_PARAMPROB;
568 		goto deliver;
569 
570 	case ICMP_SOURCEQUENCH:
571 		if (code) {
572 			goto badcode;
573 		}
574 		code = PRC_QUENCH;
575 deliver:
576 		/*
577 		 * Problem with datagram; advise higher level routines.
578 		 */
579 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp)
580 		    || IP_VHL_HL(icp->icmp_ip.ip_vhl) <
581 		    (sizeof(struct ip) >> 2) ||
582 		    (m = m_pullup(m, hlen + ICMP_ADVLEN(icp))) == NULL) {
583 			icmpstat.icps_badlen++;
584 			goto freeit;
585 		}
586 
587 		/* Re-seat the pointers, since `m_pullup' might have moved `m'*/
588 		ip = mtod(m, struct ip *);
589 		icp = (struct icmp *)(void *)(mtod(m, uint8_t *) + hlen);
590 
591 #if BYTE_ORDER != BIG_ENDIAN
592 		NTOHS(icp->icmp_ip.ip_len);
593 #endif
594 
595 		/* Discard ICMP's in response to multicast packets */
596 		if (IN_MULTICAST(ntohl(icp->icmp_ip.ip_dst.s_addr))) {
597 			goto badcode;
598 		}
599 #if (DEBUG | DEVELOPMENT)
600 		if (icmpprintfs > 2) {
601 			printf("deliver to protocol %d\n",
602 			    icp->icmp_ip.ip_p);
603 		}
604 #endif
605 		icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
606 
607 		/*
608 		 * if the packet contains [IPv4 AH TCP], we can't make a
609 		 * notification to TCP layer.
610 		 */
611 		ctlfunc = ip_protox[icp->icmp_ip.ip_p]->pr_ctlinput;
612 
613 		if (ctlfunc) {
614 			struct ipctlparam ctl_param = {
615 				.ipc_m = m,
616 				.ipc_icmp = icp,
617 				.ipc_icmp_ip = &icp->icmp_ip,
618 				.ipc_off = hlen + offsetof(struct icmp, icmp_ip) + (IP_VHL_HL(icp->icmp_ip.ip_vhl) << 2)
619 			};
620 			LCK_MTX_ASSERT(inet_domain_mutex, LCK_MTX_ASSERT_OWNED);
621 
622 			lck_mtx_unlock(inet_domain_mutex);
623 
624 			(*ctlfunc)(code, (struct sockaddr *)&icmpsrc,
625 			    (void *)&ctl_param, m->m_pkthdr.rcvif);
626 
627 			lck_mtx_lock(inet_domain_mutex);
628 		}
629 		break;
630 
631 badcode:
632 		icmpstat.icps_badcode++;
633 		break;
634 
635 	case ICMP_ECHO:
636 		if ((m->m_flags & (M_MCAST | M_BCAST))) {
637 			if (icmpbmcastecho == 0) {
638 				icmpstat.icps_bmcastecho++;
639 				break;
640 			}
641 		}
642 
643 		/*
644 		 * rdar://18644769
645 		 * Do not reply when the destination is link local multicast or broadcast
646 		 * and the source is not from a directly connected subnet
647 		 */
648 		if ((IN_LOCAL_GROUP(ntohl(ip->ip_dst.s_addr)) ||
649 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) &&
650 		    in_localaddr(ip->ip_src) == 0) {
651 			icmpstat.icps_bmcastecho++;
652 #if (DEBUG | DEVELOPMENT)
653 			if (icmpprintfs > 0) {
654 				char src_str[MAX_IPv4_STR_LEN];
655 				char dst_str[MAX_IPv4_STR_LEN];
656 
657 				inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
658 				inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
659 				printf("%s: non local (B|M)CAST %s to %s, len %d\n",
660 				    __func__, src_str, dst_str, icmplen);
661 			}
662 #endif
663 			break;
664 		}
665 
666 		icp->icmp_type = ICMP_ECHOREPLY;
667 		goto reflect;
668 
669 	case ICMP_TSTAMP:
670 		if (icmptimestamp == 0) {
671 			break;
672 		}
673 
674 		if (!icmpbmcastecho
675 		    && (m->m_flags & (M_MCAST | M_BCAST)) != 0) {
676 			icmpstat.icps_bmcasttstamp++;
677 			break;
678 		}
679 		if (icmplen < ICMP_TSLEN) {
680 			icmpstat.icps_badlen++;
681 			break;
682 		}
683 		icp->icmp_type = ICMP_TSTAMPREPLY;
684 		icp->icmp_rtime = iptime();
685 		icp->icmp_ttime = icp->icmp_rtime;      /* bogus, do later! */
686 		goto reflect;
687 
688 	case ICMP_MASKREQ:
689 		if (icmpmaskrepl == 0) {
690 			break;
691 		}
692 		/*
693 		 * We are not able to respond with all ones broadcast
694 		 * unless we receive it over a point-to-point interface.
695 		 */
696 		if (icmplen < ICMP_MASKLEN) {
697 			break;
698 		}
699 		switch (ip->ip_dst.s_addr) {
700 		case INADDR_BROADCAST:
701 		case INADDR_ANY:
702 			icmpdst.sin_addr = ip->ip_src;
703 			break;
704 
705 		default:
706 			icmpdst.sin_addr = ip->ip_dst;
707 		}
708 		ia = (struct in_ifaddr *)ifaof_ifpforaddr(
709 			(struct sockaddr *)&icmpdst, m->m_pkthdr.rcvif);
710 		if (ia == 0) {
711 			break;
712 		}
713 		IFA_LOCK(&ia->ia_ifa);
714 		if (ia->ia_ifp == 0) {
715 			IFA_UNLOCK(&ia->ia_ifa);
716 			IFA_REMREF(&ia->ia_ifa);
717 			ia = NULL;
718 			break;
719 		}
720 		icp->icmp_type = ICMP_MASKREPLY;
721 		icp->icmp_mask = ia->ia_sockmask.sin_addr.s_addr;
722 		if (ip->ip_src.s_addr == 0) {
723 			if (ia->ia_ifp->if_flags & IFF_BROADCAST) {
724 				ip->ip_src = satosin(&ia->ia_broadaddr)->sin_addr;
725 			} else if (ia->ia_ifp->if_flags & IFF_POINTOPOINT) {
726 				ip->ip_src = satosin(&ia->ia_dstaddr)->sin_addr;
727 			}
728 		}
729 		IFA_UNLOCK(&ia->ia_ifa);
730 		IFA_REMREF(&ia->ia_ifa);
731 reflect:
732 		ip->ip_len += hlen;     /* since ip_input deducts this */
733 		icmpstat.icps_reflect++;
734 		icmpstat.icps_outhist[icp->icmp_type]++;
735 		icmp_reflect(m);
736 		return;
737 
738 	case ICMP_REDIRECT:
739 		if (drop_redirect) {
740 			break;
741 		}
742 		if (code > 3) {
743 			goto badcode;
744 		}
745 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
746 		    IP_VHL_HL(icp->icmp_ip.ip_vhl) < (sizeof(struct ip) >> 2)) {
747 			icmpstat.icps_badlen++;
748 			break;
749 		}
750 
751 #if (DEBUG | DEVELOPMENT)
752 		should_log_redirect = log_redirect || (icmpprintfs > 0);
753 #else
754 		should_log_redirect = log_redirect;
755 #endif
756 		/*
757 		 * Short circuit routing redirects to force
758 		 * immediate change in the kernel's routing
759 		 * tables.  The message is also handed to anyone
760 		 * listening on a raw socket (e.g. the routing
761 		 * daemon for use in updating its tables).
762 		 */
763 		icmpgw.sin_addr = ip->ip_src;
764 		icmpdst.sin_addr = icp->icmp_gwaddr;
765 
766 		if (should_log_redirect) {
767 			char src_str[MAX_IPv4_STR_LEN];
768 			char dst_str[MAX_IPv4_STR_LEN];
769 			char gw_str[MAX_IPv4_STR_LEN];
770 
771 			inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
772 			inet_ntop(AF_INET, &icp->icmp_ip.ip_dst, dst_str, sizeof(dst_str));
773 			inet_ntop(AF_INET, &icp->icmp_gwaddr, gw_str, sizeof(gw_str));
774 			printf("%s: redirect dst %s to %s from %s\n", __func__,
775 			    dst_str, gw_str, src_str);
776 		}
777 		icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
778 		rtredirect(m->m_pkthdr.rcvif, (struct sockaddr *)&icmpsrc,
779 		    (struct sockaddr *)&icmpdst, NULL, RTF_GATEWAY | RTF_HOST,
780 		    (struct sockaddr *)&icmpgw, NULL);
781 		pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&icmpsrc);
782 #if IPSEC
783 		key_sa_routechange((struct sockaddr *)&icmpsrc);
784 #endif
785 		break;
786 
787 	/*
788 	 * No kernel processing for the following;
789 	 * just fall through to send to raw listener.
790 	 */
791 	case ICMP_ECHOREPLY:
792 	case ICMP_ROUTERADVERT:
793 	case ICMP_ROUTERSOLICIT:
794 	case ICMP_TSTAMPREPLY:
795 	case ICMP_IREQREPLY:
796 	case ICMP_MASKREPLY:
797 	default:
798 		break;
799 	}
800 
801 raw:
802 	rip_input(m, hlen);
803 	return;
804 
805 freeit:
806 	m_freem(m);
807 }
808 
809 /*
810  * Reflect the ip packet back to the source
811  */
812 static void
icmp_reflect(struct mbuf * m)813 icmp_reflect(struct mbuf *m)
814 {
815 	struct ip *ip = mtod(m, struct ip *);
816 	struct sockaddr_in icmpdst;
817 	struct in_ifaddr *ia;
818 	struct in_addr t;
819 	struct mbuf *opts = NULL;
820 	int optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
821 
822 	if (!in_canforward(ip->ip_src) &&
823 	    ((ntohl(ip->ip_src.s_addr) & IN_CLASSA_NET) !=
824 	    (IN_LOOPBACKNET << IN_CLASSA_NSHIFT))) {
825 		m_freem(m);     /* Bad return address */
826 		goto done;      /* Ip_output() will check for broadcast */
827 	}
828 	t = ip->ip_dst;
829 	ip->ip_dst = ip->ip_src;
830 	/*
831 	 * If the incoming packet was addressed directly to us,
832 	 * use dst as the src for the reply.  Otherwise (broadcast
833 	 * or anonymous), use the address which corresponds
834 	 * to the incoming interface.
835 	 */
836 	lck_rw_lock_shared(&in_ifaddr_rwlock);
837 	TAILQ_FOREACH(ia, INADDR_HASH(t.s_addr), ia_hash) {
838 		IFA_LOCK(&ia->ia_ifa);
839 		if (t.s_addr == IA_SIN(ia)->sin_addr.s_addr) {
840 			IFA_ADDREF_LOCKED(&ia->ia_ifa);
841 			IFA_UNLOCK(&ia->ia_ifa);
842 			goto match;
843 		}
844 		IFA_UNLOCK(&ia->ia_ifa);
845 	}
846 	/*
847 	 * Slow path; check for broadcast addresses.  Find a source
848 	 * IP address to use when replying to the broadcast request;
849 	 * let IP handle the source interface selection work.
850 	 */
851 	for (ia = in_ifaddrhead.tqh_first; ia; ia = ia->ia_link.tqe_next) {
852 		IFA_LOCK(&ia->ia_ifa);
853 		if (ia->ia_ifp && (ia->ia_ifp->if_flags & IFF_BROADCAST) &&
854 		    t.s_addr == satosin(&ia->ia_broadaddr)->sin_addr.s_addr) {
855 			IFA_ADDREF_LOCKED(&ia->ia_ifa);
856 			IFA_UNLOCK(&ia->ia_ifa);
857 			break;
858 		}
859 		IFA_UNLOCK(&ia->ia_ifa);
860 	}
861 match:
862 	lck_rw_done(&in_ifaddr_rwlock);
863 
864 	/* Initialize */
865 	bzero(&icmpdst, sizeof(icmpdst));
866 	icmpdst.sin_len = sizeof(struct sockaddr_in);
867 	icmpdst.sin_family = AF_INET;
868 	icmpdst.sin_addr = t;
869 	if ((ia == (struct in_ifaddr *)0) && m->m_pkthdr.rcvif) {
870 		ia = (struct in_ifaddr *)ifaof_ifpforaddr(
871 			(struct sockaddr *)&icmpdst, m->m_pkthdr.rcvif);
872 	}
873 	/*
874 	 * The following happens if the packet was not addressed to us,
875 	 * and was received on an interface with no IP address.
876 	 */
877 	if (ia == (struct in_ifaddr *)0) {
878 		lck_rw_lock_shared(&in_ifaddr_rwlock);
879 		ia = in_ifaddrhead.tqh_first;
880 		if (ia == (struct in_ifaddr *)0) {/* no address yet, bail out */
881 			lck_rw_done(&in_ifaddr_rwlock);
882 			m_freem(m);
883 			goto done;
884 		}
885 		IFA_ADDREF(&ia->ia_ifa);
886 		lck_rw_done(&in_ifaddr_rwlock);
887 	}
888 	IFA_LOCK_SPIN(&ia->ia_ifa);
889 	t = IA_SIN(ia)->sin_addr;
890 	IFA_UNLOCK(&ia->ia_ifa);
891 	ip->ip_src = t;
892 	ip->ip_ttl = (u_char)ip_defttl;
893 	IFA_REMREF(&ia->ia_ifa);
894 	ia = NULL;
895 
896 	if (optlen > 0) {
897 		u_char *cp;
898 		int opt, cnt;
899 		u_int len;
900 
901 		/*
902 		 * Retrieve any source routing from the incoming packet;
903 		 * add on any record-route or timestamp options.
904 		 */
905 		cp = (u_char *) (ip + 1);
906 		if ((opts = ip_srcroute()) == 0 &&
907 		    (opts = m_gethdr(M_DONTWAIT, MT_HEADER))) { /* MAC-OK */
908 			opts->m_len = sizeof(struct in_addr);
909 			mtod(opts, struct in_addr *)->s_addr = 0;
910 		}
911 		if (opts) {
912 #if (DEBUG | DEVELOPMENT)
913 			if (icmpprintfs > 1) {
914 				printf("icmp_reflect optlen %d rt %d => ",
915 				    optlen, opts->m_len);
916 			}
917 #endif
918 			for (cnt = optlen; cnt > 0; cnt -= len, cp += len) {
919 				opt = cp[IPOPT_OPTVAL];
920 				if (opt == IPOPT_EOL) {
921 					break;
922 				}
923 				if (opt == IPOPT_NOP) {
924 					len = 1;
925 				} else {
926 					if (cnt < IPOPT_OLEN + sizeof(*cp)) {
927 						break;
928 					}
929 					len = cp[IPOPT_OLEN];
930 					if (len < IPOPT_OLEN + sizeof(*cp) ||
931 					    len > cnt) {
932 						break;
933 					}
934 				}
935 				/*
936 				 * Should check for overflow, but it "can't happen"
937 				 */
938 				if (opt == IPOPT_RR || opt == IPOPT_TS ||
939 				    opt == IPOPT_SECURITY) {
940 					bcopy((caddr_t)cp,
941 					    mtod(opts, caddr_t) + opts->m_len, len);
942 					opts->m_len += len;
943 				}
944 			}
945 			/* Terminate & pad, if necessary */
946 			cnt = opts->m_len % 4;
947 			if (cnt) {
948 				for (; cnt < 4; cnt++) {
949 					*(mtod(opts, caddr_t) + opts->m_len) =
950 					    IPOPT_EOL;
951 					opts->m_len++;
952 				}
953 			}
954 #if (DEBUG | DEVELOPMENT)
955 			if (icmpprintfs > 1) {
956 				printf("%d\n", opts->m_len);
957 			}
958 #endif
959 		}
960 		/*
961 		 * Now strip out original options by copying rest of first
962 		 * mbuf's data back, and adjust the IP length.
963 		 */
964 		ip->ip_len -= optlen;
965 		ip->ip_vhl = IP_VHL_BORING;
966 		m->m_len -= optlen;
967 		if (m->m_flags & M_PKTHDR) {
968 			m->m_pkthdr.len -= optlen;
969 		}
970 		optlen += sizeof(struct ip);
971 		bcopy((caddr_t)ip + optlen, (caddr_t)(ip + 1),
972 		    (unsigned)(m->m_len - sizeof(struct ip)));
973 	}
974 	m->m_flags &= ~(M_BCAST | M_MCAST);
975 	icmp_send(m, opts);
976 done:
977 	if (opts) {
978 		(void)m_free(opts);
979 	}
980 }
981 
982 /*
983  * Send an icmp packet back to the ip level,
984  * after supplying a checksum.
985  */
986 static void
icmp_send(struct mbuf * m,struct mbuf * opts)987 icmp_send(struct mbuf *m, struct mbuf *opts)
988 {
989 	struct ip *ip = mtod(m, struct ip *);
990 	int hlen;
991 	struct icmp *icp;
992 	struct route ro;
993 	struct ip_out_args ipoa;
994 
995 	bzero(&ipoa, sizeof(ipoa));
996 	ipoa.ipoa_boundif = IFSCOPE_NONE;
997 	ipoa.ipoa_flags = IPOAF_SELECT_SRCIF | IPOAF_BOUND_SRCADDR;
998 	ipoa.ipoa_sotc = SO_TC_UNSPEC;
999 	ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
1000 
1001 	if (!(m->m_pkthdr.pkt_flags & PKTF_LOOP) && m->m_pkthdr.rcvif != NULL) {
1002 		ipoa.ipoa_boundif = m->m_pkthdr.rcvif->if_index;
1003 		ipoa.ipoa_flags |= IPOAF_BOUND_IF;
1004 	}
1005 
1006 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1007 	m->m_data += hlen;
1008 	m->m_len -= hlen;
1009 	icp = mtod(m, struct icmp *);
1010 	icp->icmp_cksum = 0;
1011 	icp->icmp_cksum = in_cksum(m, ip->ip_len - hlen);
1012 	m->m_data -= hlen;
1013 	m->m_len += hlen;
1014 	m->m_pkthdr.rcvif = NULL;
1015 	m->m_pkthdr.csum_data = 0;
1016 	m->m_pkthdr.csum_flags = 0;
1017 #if (DEBUG | DEVELOPMENT)
1018 	if (icmpprintfs > 2) {
1019 		char src_str[MAX_IPv4_STR_LEN];
1020 		char dst_str[MAX_IPv4_STR_LEN];
1021 
1022 		inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
1023 		inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
1024 		printf("%s: dst %s src %s\n", __func__, dst_str, src_str);
1025 	}
1026 #endif
1027 	bzero(&ro, sizeof ro);
1028 	(void) ip_output(m, opts, &ro, IP_OUTARGS, NULL, &ipoa);
1029 	ROUTE_RELEASE(&ro);
1030 }
1031 
1032 u_int32_t
iptime(void)1033 iptime(void)
1034 {
1035 	struct timeval atv;
1036 	u_int32_t t;
1037 
1038 	getmicrotime(&atv);
1039 	t = (atv.tv_sec % (24 * 60 * 60)) * 1000 + atv.tv_usec / 1000;
1040 	return htonl(t);
1041 }
1042 
1043 #if 1
1044 /*
1045  * Return the next larger or smaller MTU plateau (table from RFC 1191)
1046  * given current value MTU.  If DIR is less than zero, a larger plateau
1047  * is returned; otherwise, a smaller value is returned.
1048  */
1049 int
ip_next_mtu(int mtu,int dir)1050 ip_next_mtu(int mtu, int dir)
1051 {
1052 	static int mtutab[] = {
1053 		65535, 32000, 17914, 8166, 4352, 2002, 1492, 1006, 508, 296,
1054 		68, 0
1055 	};
1056 	int i;
1057 
1058 	for (i = 0; i < (sizeof mtutab) / (sizeof mtutab[0]); i++) {
1059 		if (mtu >= mtutab[i]) {
1060 			break;
1061 		}
1062 	}
1063 
1064 	if (dir < 0) {
1065 		if (i == 0) {
1066 			return 0;
1067 		} else {
1068 			return mtutab[i - 1];
1069 		}
1070 	} else {
1071 		if (mtutab[i] == 0) {
1072 			return 0;
1073 		} else if (mtu > mtutab[i]) {
1074 			return mtutab[i];
1075 		} else {
1076 			return mtutab[i + 1];
1077 		}
1078 	}
1079 }
1080 #endif
1081 
1082 #if __APPLE__
1083 
1084 /*
1085  * Non-privileged ICMP socket operations
1086  * - send ICMP echo request
1087  * - all ICMP
1088  * - limited socket options
1089  */
1090 
1091 #include <netinet/ip_icmp.h>
1092 #include <netinet/in_pcb.h>
1093 
1094 extern u_int32_t rip_sendspace;
1095 extern u_int32_t rip_recvspace;
1096 extern struct inpcbinfo ripcbinfo;
1097 
1098 int rip_abort(struct socket *);
1099 int rip_bind(struct socket *, struct sockaddr *, struct proc *);
1100 int rip_connect(struct socket *, struct sockaddr *, struct proc *);
1101 int rip_detach(struct socket *);
1102 int rip_disconnect(struct socket *);
1103 int rip_shutdown(struct socket *);
1104 
1105 __private_extern__ int icmp_dgram_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam, struct mbuf *control, struct proc *p);
1106 __private_extern__ int icmp_dgram_attach(struct socket *so, int proto, struct proc *p);
1107 __private_extern__ int icmp_dgram_ctloutput(struct socket *so, struct sockopt *sopt);
1108 
1109 __private_extern__ struct pr_usrreqs icmp_dgram_usrreqs = {
1110 	.pru_abort =            rip_abort,
1111 	.pru_attach =           icmp_dgram_attach,
1112 	.pru_bind =             rip_bind,
1113 	.pru_connect =          rip_connect,
1114 	.pru_control =          in_control,
1115 	.pru_detach =           rip_detach,
1116 	.pru_disconnect =       rip_disconnect,
1117 	.pru_peeraddr =         in_getpeeraddr,
1118 	.pru_send =             icmp_dgram_send,
1119 	.pru_shutdown =         rip_shutdown,
1120 	.pru_sockaddr =         in_getsockaddr,
1121 	.pru_sosend =           sosend,
1122 	.pru_soreceive =        soreceive,
1123 };
1124 
1125 /* Like rip_attach but without root privilege enforcement */
1126 __private_extern__ int
icmp_dgram_attach(struct socket * so,__unused int proto,struct proc * p)1127 icmp_dgram_attach(struct socket *so, __unused int proto, struct proc *p)
1128 {
1129 	struct inpcb *inp;
1130 	int error;
1131 
1132 	inp = sotoinpcb(so);
1133 	if (inp) {
1134 		panic("icmp_dgram_attach");
1135 	}
1136 
1137 	error = soreserve(so, rip_sendspace, rip_recvspace);
1138 	if (error) {
1139 		return error;
1140 	}
1141 	error = in_pcballoc(so, &ripcbinfo, p);
1142 	if (error) {
1143 		return error;
1144 	}
1145 	inp = (struct inpcb *)so->so_pcb;
1146 	inp->inp_vflag |= INP_IPV4;
1147 	inp->inp_ip_p = IPPROTO_ICMP;
1148 	inp->inp_ip_ttl = (u_char)ip_defttl;
1149 	return 0;
1150 }
1151 
1152 /*
1153  * Raw IP socket option processing.
1154  */
1155 __private_extern__ int
icmp_dgram_ctloutput(struct socket * so,struct sockopt * sopt)1156 icmp_dgram_ctloutput(struct socket *so, struct sockopt *sopt)
1157 {
1158 	int     error;
1159 
1160 	if (sopt->sopt_level != IPPROTO_IP) {
1161 		return EINVAL;
1162 	}
1163 
1164 	switch (sopt->sopt_name) {
1165 	case IP_OPTIONS:
1166 	case IP_HDRINCL:
1167 	case IP_TOS:
1168 	case IP_TTL:
1169 	case IP_RECVOPTS:
1170 	case IP_RECVRETOPTS:
1171 	case IP_RECVDSTADDR:
1172 	case IP_RETOPTS:
1173 	case IP_MULTICAST_IF:
1174 	case IP_MULTICAST_IFINDEX:
1175 	case IP_MULTICAST_TTL:
1176 	case IP_MULTICAST_LOOP:
1177 	case IP_ADD_MEMBERSHIP:
1178 	case IP_DROP_MEMBERSHIP:
1179 	case IP_MULTICAST_VIF:
1180 	case IP_PORTRANGE:
1181 	case IP_RECVIF:
1182 	case IP_IPSEC_POLICY:
1183 	case IP_STRIPHDR:
1184 	case IP_RECVTTL:
1185 	case IP_BOUND_IF:
1186 	case IP_DONTFRAG:
1187 	case IP_NO_IFT_CELLULAR:
1188 		error = rip_ctloutput(so, sopt);
1189 		break;
1190 
1191 	default:
1192 		error = EINVAL;
1193 		break;
1194 	}
1195 
1196 	return error;
1197 }
1198 
1199 __private_extern__ int
icmp_dgram_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * nam,struct mbuf * control,struct proc * p)1200 icmp_dgram_send(struct socket *so, int flags, struct mbuf *m,
1201     struct sockaddr *nam, struct mbuf *control, struct proc *p)
1202 {
1203 	struct ip *ip;
1204 	struct inpcb *inp = sotoinpcb(so);
1205 	int hlen;
1206 	struct icmp *icp;
1207 	struct in_ifaddr *ia = NULL;
1208 	int icmplen;
1209 	int error = EINVAL;
1210 	int inp_flags = inp ? inp->inp_flags : 0;
1211 
1212 	if (inp == NULL
1213 #if NECP
1214 	    || (necp_socket_should_use_flow_divert(inp))
1215 #endif /* NECP */
1216 	    ) {
1217 		if (inp != NULL) {
1218 			error = EPROTOTYPE;
1219 		}
1220 		goto bad;
1221 	}
1222 
1223 #if CONTENT_FILTER
1224 	/*
1225 	 * If socket is subject to Content Filter, get inp_flags from saved state
1226 	 */
1227 	if (CFIL_DGRAM_FILTERED(so) && nam == NULL) {
1228 		cfil_dgram_peek_socket_state(m, &inp_flags);
1229 	}
1230 #endif
1231 
1232 	if ((inp_flags & INP_HDRINCL) != 0) {
1233 		/* Expect 32-bit aligned data ptr on strict-align platforms */
1234 		MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
1235 		/*
1236 		 * This is not raw IP, we liberal only for fields TOS,
1237 		 * id and TTL.
1238 		 */
1239 		ip = mtod(m, struct ip *);
1240 
1241 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1242 		/* Some sanity checks */
1243 		if (m->m_pkthdr.len < hlen + ICMP_MINLEN) {
1244 			goto bad;
1245 		}
1246 		/* Only IPv4 */
1247 		if (IP_VHL_V(ip->ip_vhl) != 4) {
1248 			goto bad;
1249 		}
1250 		if (hlen < 20 || hlen > 40 || ip->ip_len != m->m_pkthdr.len) {
1251 			goto bad;
1252 		}
1253 		/* Bogus fragments can tie up peer resources */
1254 		if ((ip->ip_off & ~IP_DF) != 0) {
1255 			goto bad;
1256 		}
1257 		/* Allow only ICMP even for user provided IP header */
1258 		if (ip->ip_p != IPPROTO_ICMP) {
1259 			goto bad;
1260 		}
1261 		/*
1262 		 * To prevent spoofing, specified source address must
1263 		 * be one of ours.
1264 		 */
1265 		if (ip->ip_src.s_addr != INADDR_ANY) {
1266 			socket_unlock(so, 0);
1267 			lck_rw_lock_shared(&in_ifaddr_rwlock);
1268 			if (TAILQ_EMPTY(&in_ifaddrhead)) {
1269 				lck_rw_done(&in_ifaddr_rwlock);
1270 				socket_lock(so, 0);
1271 				goto bad;
1272 			}
1273 			TAILQ_FOREACH(ia, INADDR_HASH(ip->ip_src.s_addr),
1274 			    ia_hash) {
1275 				IFA_LOCK(&ia->ia_ifa);
1276 				if (IA_SIN(ia)->sin_addr.s_addr ==
1277 				    ip->ip_src.s_addr) {
1278 					IFA_UNLOCK(&ia->ia_ifa);
1279 					lck_rw_done(&in_ifaddr_rwlock);
1280 					socket_lock(so, 0);
1281 					goto ours;
1282 				}
1283 				IFA_UNLOCK(&ia->ia_ifa);
1284 			}
1285 			lck_rw_done(&in_ifaddr_rwlock);
1286 			socket_lock(so, 0);
1287 			goto bad;
1288 		}
1289 ours:
1290 		/* Do not trust we got a valid checksum */
1291 		ip->ip_sum = 0;
1292 
1293 		icp = (struct icmp *)(void *)(((char *)m->m_data) + hlen);
1294 		icmplen = m->m_pkthdr.len - hlen;
1295 	} else {
1296 		if ((icmplen = m->m_pkthdr.len) < ICMP_MINLEN) {
1297 			goto bad;
1298 		}
1299 		icp = mtod(m, struct icmp *);
1300 	}
1301 	/*
1302 	 * Allow only to send request types with code 0
1303 	 */
1304 	if (icp->icmp_code != 0) {
1305 		goto bad;
1306 	}
1307 	switch (icp->icmp_type) {
1308 	case ICMP_ECHO:
1309 		break;
1310 	case ICMP_TSTAMP:
1311 		if (icmplen != 20) {
1312 			goto bad;
1313 		}
1314 		break;
1315 	case ICMP_MASKREQ:
1316 		if (icmplen != 12) {
1317 			goto bad;
1318 		}
1319 		break;
1320 	default:
1321 		goto bad;
1322 	}
1323 	return rip_send(so, flags, m, nam, control, p);
1324 bad:
1325 	VERIFY(error != 0);
1326 
1327 	if (m != NULL) {
1328 		m_freem(m);
1329 	}
1330 	if (control != NULL) {
1331 		m_freem(control);
1332 	}
1333 
1334 	return error;
1335 }
1336 
1337 #endif /* __APPLE__ */
1338