xref: /xnu-8019.80.24/bsd/netkey/keysock.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea)
1 /*
2  * Copyright (c) 2019 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 /*	$KAME: keysock.c,v 1.13 2000/03/25 07:24:13 sumikawa Exp $	*/
30 
31 /*
32  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
33  * All rights reserved.
34  *
35  * Redistribution and use in source and binary forms, with or without
36  * modification, are permitted provided that the following conditions
37  * are met:
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. Neither the name of the project nor the names of its contributors
44  *    may be used to endorse or promote products derived from this software
45  *    without specific prior written permission.
46  *
47  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
48  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
51  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57  * SUCH DAMAGE.
58  */
59 
60 /* This code has derived from sys/net/rtsock.c on FreeBSD2.2.5 */
61 
62 #include <sys/types.h>
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/sysctl.h>
67 #include <sys/mbuf.h>
68 #include <sys/mcache.h>
69 #include <sys/malloc.h>
70 #include <sys/socket.h>
71 #include <sys/socketvar.h>
72 #include <sys/domain.h>
73 #include <sys/protosw.h>
74 #include <sys/errno.h>
75 
76 #include <kern/locks.h>
77 
78 #include <net/raw_cb.h>
79 #include <net/route.h>
80 
81 #include <net/pfkeyv2.h>
82 #include <netkey/keydb.h>
83 #include <netkey/key.h>
84 #include <netkey/keysock.h>
85 #include <netkey/key_debug.h>
86 
87 extern lck_mtx_t raw_mtx;
88 extern void key_init(struct protosw *, struct domain *);
89 
90 struct sockaddr key_dst = { .sa_len = 2, .sa_family = PF_KEY, .sa_data = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } };
91 struct sockaddr key_src = { .sa_len = 2, .sa_family = PF_KEY, .sa_data = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, } };
92 
93 static void key_dinit(struct domain *);
94 static int key_sendup0(struct rawcb *, struct mbuf *, int);
95 
96 struct pfkeystat pfkeystat;
97 
98 static struct domain *keydomain = NULL;
99 
100 static LCK_GRP_DECLARE(pfkey_stat_mutex_grp, "pfkey_stat");
101 LCK_MTX_DECLARE(pfkey_stat_mutex, &pfkey_stat_mutex_grp);
102 
103 /*
104  * key_output()
105  */
106 int
107 #ifdef __APPLE__
108 /* No variable argument support? */
key_output(struct mbuf * m,struct socket * so)109 key_output(struct mbuf *m, struct socket *so)
110 #else
111 #if __STDC__
112 key_output(struct mbuf *m, ...)
113 #else
114 key_output(m, va_alist)
115 struct mbuf *m;
116 va_dcl
117 #endif
118 #endif
119 {
120 	struct sadb_msg *msg;
121 	int len, error = 0;
122 #ifndef __APPLE__
123 	struct socket *so;
124 	va_list ap;
125 
126 	va_start(ap, m);
127 	so = va_arg(ap, struct socket *);
128 	va_end(ap);
129 #endif
130 
131 	if (m == 0) {
132 		panic("key_output: NULL pointer was passed.");
133 	}
134 
135 	socket_unlock(so, 0);
136 	lck_mtx_lock(&pfkey_stat_mutex);
137 	pfkeystat.out_total++;
138 	pfkeystat.out_bytes += m->m_pkthdr.len;
139 	lck_mtx_unlock(&pfkey_stat_mutex);
140 
141 	len = m->m_pkthdr.len;
142 	if (len < sizeof(struct sadb_msg)) {
143 #if IPSEC_DEBUG
144 		printf("key_output: Invalid message length.\n");
145 #endif
146 		PFKEY_STAT_INCREMENT(pfkeystat.out_tooshort);
147 		error = EINVAL;
148 		goto end;
149 	}
150 
151 	if (m->m_len < sizeof(struct sadb_msg)) {
152 		if ((m = m_pullup(m, sizeof(struct sadb_msg))) == 0) {
153 #if IPSEC_DEBUG
154 			printf("key_output: can't pullup mbuf\n");
155 #endif
156 			PFKEY_STAT_INCREMENT(pfkeystat.out_nomem);
157 			error = ENOBUFS;
158 			goto end;
159 		}
160 	}
161 
162 	if ((m->m_flags & M_PKTHDR) == 0) {
163 		panic("key_output: not M_PKTHDR ??");
164 	}
165 
166 #if IPSEC_DEBUG
167 	KEYDEBUG(KEYDEBUG_KEY_DUMP, kdebug_mbuf(m));
168 #endif /* defined(IPSEC_DEBUG) */
169 
170 	msg = mtod(m, struct sadb_msg *);
171 	PFKEY_STAT_INCREMENT(pfkeystat.out_msgtype[msg->sadb_msg_type]);
172 	if (len != PFKEY_UNUNIT64(msg->sadb_msg_len)) {
173 #if IPSEC_DEBUG
174 		printf("key_output: Invalid message length.\n");
175 #endif
176 		PFKEY_STAT_INCREMENT(pfkeystat.out_invlen);
177 		error = EINVAL;
178 		goto end;
179 	}
180 
181 	error = key_parse(m, so);
182 	m = NULL;
183 
184 end:
185 	if (m) {
186 		m_freem(m);
187 	}
188 	socket_lock(so, 0);
189 	return error;
190 }
191 
192 /*
193  * send message to the socket.
194  */
195 static int
key_sendup0(struct rawcb * rp,struct mbuf * m,int promisc)196 key_sendup0(struct rawcb *rp, struct mbuf *m, int promisc)
197 {
198 	int error;
199 
200 	if (promisc) {
201 		struct sadb_msg *pmsg;
202 
203 		M_PREPEND(m, sizeof(struct sadb_msg), M_NOWAIT, 1);
204 		if (m && m->m_len < sizeof(struct sadb_msg)) {
205 			m = m_pullup(m, sizeof(struct sadb_msg));
206 		}
207 		if (!m) {
208 #if IPSEC_DEBUG
209 			printf("key_sendup0: cannot pullup\n");
210 #endif
211 			PFKEY_STAT_INCREMENT(pfkeystat.in_nomem);
212 			m_freem(m);
213 			return ENOBUFS;
214 		}
215 		m->m_pkthdr.len += sizeof(*pmsg);
216 		VERIFY(PFKEY_UNIT64(m->m_pkthdr.len) <= UINT16_MAX);
217 
218 		pmsg = mtod(m, struct sadb_msg *);
219 		bzero(pmsg, sizeof(*pmsg));
220 		pmsg->sadb_msg_version = PF_KEY_V2;
221 		pmsg->sadb_msg_type = SADB_X_PROMISC;
222 		pmsg->sadb_msg_len = (u_int16_t)PFKEY_UNIT64(m->m_pkthdr.len);
223 		/* pid and seq? */
224 
225 		PFKEY_STAT_INCREMENT(pfkeystat.in_msgtype[pmsg->sadb_msg_type]);
226 	}
227 
228 	if (!sbappendaddr(&rp->rcb_socket->so_rcv, (struct sockaddr *)&key_src,
229 	    m, NULL, &error)) {
230 #if IPSEC_DEBUG
231 		printf("key_sendup0: sbappendaddr failed\n");
232 #endif
233 		PFKEY_STAT_INCREMENT(pfkeystat.in_nomem);
234 	} else {
235 		sorwakeup(rp->rcb_socket);
236 	}
237 	return error;
238 }
239 
240 
241 /* so can be NULL if target != KEY_SENDUP_ONE */
242 int
key_sendup_mbuf(struct socket * so,struct mbuf * m,int target)243 key_sendup_mbuf(struct socket *so, struct mbuf *m, int target)
244 {
245 	struct mbuf *n;
246 	struct keycb *kp;
247 	int sendup;
248 	struct rawcb *rp;
249 	int error = 0;
250 
251 	if (m == NULL) {
252 		panic("key_sendup_mbuf: NULL pointer was passed.");
253 	}
254 	if (so == NULL && target == KEY_SENDUP_ONE) {
255 		panic("key_sendup_mbuf: NULL pointer was passed.");
256 	}
257 
258 	lck_mtx_lock(&pfkey_stat_mutex);
259 	pfkeystat.in_total++;
260 	pfkeystat.in_bytes += m->m_pkthdr.len;
261 	lck_mtx_unlock(&pfkey_stat_mutex);
262 	if (m->m_len < sizeof(struct sadb_msg)) {
263 #if 1
264 		m = m_pullup(m, sizeof(struct sadb_msg));
265 		if (m == NULL) {
266 			PFKEY_STAT_INCREMENT(pfkeystat.in_nomem);
267 			return ENOBUFS;
268 		}
269 #else
270 		/* don't bother pulling it up just for stats */
271 #endif
272 	}
273 	if (m->m_len >= sizeof(struct sadb_msg)) {
274 		struct sadb_msg *msg;
275 		msg = mtod(m, struct sadb_msg *);
276 		PFKEY_STAT_INCREMENT(pfkeystat.in_msgtype[msg->sadb_msg_type]);
277 	}
278 
279 	lck_mtx_lock(&raw_mtx);
280 	LIST_FOREACH(rp, &rawcb_list, list)
281 	{
282 		if (rp->rcb_proto.sp_family != PF_KEY) {
283 			continue;
284 		}
285 		if (rp->rcb_proto.sp_protocol
286 		    && rp->rcb_proto.sp_protocol != PF_KEY_V2) {
287 			continue;
288 		}
289 
290 		kp = (struct keycb *)rp;
291 
292 		socket_lock(rp->rcb_socket, 1);
293 		/*
294 		 * If you are in promiscuous mode, and when you get broadcasted
295 		 * reply, you'll get two PF_KEY messages.
296 		 * (based on [email protected] message on 14 Oct 1998)
297 		 */
298 		if (((struct keycb *)rp)->kp_promisc) {
299 			if ((n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
300 				(void)key_sendup0(rp, n, 1);
301 				n = NULL;
302 			}
303 		}
304 
305 		/* the exact target will be processed later */
306 		if (so && sotorawcb(so) == rp) {
307 			socket_unlock(rp->rcb_socket, 1);
308 			continue;
309 		}
310 
311 		sendup = 0;
312 		switch (target) {
313 		case KEY_SENDUP_ONE:
314 			/* the statement has no effect */
315 			break;
316 		case KEY_SENDUP_ALL:
317 			sendup++;
318 			break;
319 		case KEY_SENDUP_REGISTERED:
320 			if (kp->kp_registered) {
321 				sendup++;
322 			}
323 			break;
324 		}
325 		PFKEY_STAT_INCREMENT(pfkeystat.in_msgtarget[target]);
326 
327 		if (!sendup) {
328 			socket_unlock(rp->rcb_socket, 1);
329 			continue;
330 		} else {
331 			sendup = 0;  // clear for next iteration
332 		}
333 		if ((n = m_copy(m, 0, (int)M_COPYALL)) == NULL) {
334 #if IPSEC_DEBUG
335 			printf("key_sendup: m_copy fail\n");
336 #endif
337 			m_freem(m);
338 			PFKEY_STAT_INCREMENT(pfkeystat.in_nomem);
339 			socket_unlock(rp->rcb_socket, 1);
340 			lck_mtx_unlock(&raw_mtx);
341 			return ENOBUFS;
342 		}
343 
344 		/*
345 		 * ignore error even if queue is full.  PF_KEY does not
346 		 * guarantee the delivery of the message.
347 		 * this is important when target == KEY_SENDUP_ALL.
348 		 */
349 		key_sendup0(rp, n, 0);
350 		socket_unlock(rp->rcb_socket, 1);
351 		n = NULL;
352 	}
353 
354 	lck_mtx_unlock(&raw_mtx);
355 	if (so) {
356 		socket_lock(so, 1);
357 		error = key_sendup0(sotorawcb(so), m, 0);
358 		socket_unlock(so, 1);
359 		m = NULL;
360 	} else {
361 		error = 0;
362 		m_freem(m);
363 	}
364 	return error;
365 }
366 
367 /*
368  * key_abort()
369  * derived from net/rtsock.c:rts_abort()
370  */
371 static int
key_abort(struct socket * so)372 key_abort(struct socket *so)
373 {
374 	int error;
375 	error = raw_usrreqs.pru_abort(so);
376 	return error;
377 }
378 
379 /*
380  * key_attach()
381  * derived from net/rtsock.c:rts_attach()
382  */
383 static int
key_attach(struct socket * so,int proto,struct proc * p)384 key_attach(struct socket *so, int proto, struct proc *p)
385 {
386 	struct keycb *kp;
387 	int error;
388 
389 	if (sotorawcb(so) != 0) {
390 		return EISCONN; /* XXX panic? */
391 	}
392 	kp = (struct keycb *)_MALLOC(sizeof(*kp), M_PCB,
393 	    M_WAITOK | M_ZERO); /* XXX */
394 	if (kp == 0) {
395 		return ENOBUFS;
396 	}
397 
398 	so->so_pcb = (caddr_t)kp;
399 	kp->kp_promisc = kp->kp_registered = 0;
400 	kp->kp_raw.rcb_laddr = &key_src;
401 	kp->kp_raw.rcb_faddr = &key_dst;
402 
403 	error = raw_usrreqs.pru_attach(so, proto, p);
404 	kp = (struct keycb *)sotorawcb(so);
405 	if (error) {
406 		_FREE(kp, M_PCB);
407 		so->so_pcb = (caddr_t) 0;
408 		so->so_flags |= SOF_PCBCLEARING;
409 		printf("key_usrreq: key_usrreq results %d\n", error);
410 		return error;
411 	}
412 
413 	/* so is already locked when calling key_attach */
414 	if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) { /* XXX: AF_KEY */
415 		key_cb.key_count++;
416 	}
417 	key_cb.any_count++;
418 	soisconnected(so);
419 	so->so_options |= SO_USELOOPBACK;
420 
421 	return 0;
422 }
423 
424 /*
425  * key_bind()
426  * derived from net/rtsock.c:rts_bind()
427  */
428 static int
key_bind(struct socket * so,struct sockaddr * nam,struct proc * p)429 key_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
430 {
431 	int error;
432 	error = raw_usrreqs.pru_bind(so, nam, p); /* xxx just EINVAL */
433 	return error;
434 }
435 
436 /*
437  * key_connect()
438  * derived from net/rtsock.c:rts_connect()
439  */
440 static int
key_connect(struct socket * so,struct sockaddr * nam,struct proc * p)441 key_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
442 {
443 	int error;
444 	error = raw_usrreqs.pru_connect(so, nam, p); /* XXX just EINVAL */
445 	return error;
446 }
447 
448 /*
449  * key_detach()
450  * derived from net/rtsock.c:rts_detach()
451  */
452 static int
key_detach(struct socket * so)453 key_detach(struct socket *so)
454 {
455 	struct keycb *kp = (struct keycb *)sotorawcb(so);
456 	int error;
457 
458 	if (kp != 0) {
459 		if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) { /* XXX: AF_KEY */
460 			key_cb.key_count--;
461 		}
462 		key_cb.any_count--;
463 		socket_unlock(so, 0);
464 		key_freereg(so);
465 		socket_lock(so, 0);
466 	}
467 	error = raw_usrreqs.pru_detach(so);
468 	return error;
469 }
470 
471 /*
472  * key_disconnect()
473  * derived from net/rtsock.c:key_disconnect()
474  */
475 static int
key_disconnect(struct socket * so)476 key_disconnect(struct socket *so)
477 {
478 	int error;
479 	error = raw_usrreqs.pru_disconnect(so);
480 	return error;
481 }
482 
483 /*
484  * key_peeraddr()
485  * derived from net/rtsock.c:rts_peeraddr()
486  */
487 static int
key_peeraddr(struct socket * so,struct sockaddr ** nam)488 key_peeraddr(struct socket *so, struct sockaddr **nam)
489 {
490 	int error;
491 	error = raw_usrreqs.pru_peeraddr(so, nam);
492 	return error;
493 }
494 
495 /*
496  * key_send()
497  * derived from net/rtsock.c:rts_send()
498  */
499 static int
key_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * nam,struct mbuf * control,struct proc * p)500 key_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
501     struct mbuf *control, struct proc *p)
502 {
503 	int error;
504 	error = raw_usrreqs.pru_send(so, flags, m, nam, control, p);
505 	return error;
506 }
507 
508 /*
509  * key_shutdown()
510  * derived from net/rtsock.c:rts_shutdown()
511  */
512 static int
key_shutdown(struct socket * so)513 key_shutdown(struct socket *so)
514 {
515 	int error;
516 	error = raw_usrreqs.pru_shutdown(so);
517 	return error;
518 }
519 
520 /*
521  * key_sockaddr()
522  * derived from net/rtsock.c:rts_sockaddr()
523  */
524 static int
key_sockaddr(struct socket * so,struct sockaddr ** nam)525 key_sockaddr(struct socket *so, struct sockaddr **nam)
526 {
527 	int error;
528 	error = raw_usrreqs.pru_sockaddr(so, nam);
529 	return error;
530 }
531 
532 static struct pr_usrreqs key_usrreqs = {
533 	.pru_abort =            key_abort,
534 	.pru_attach =           key_attach,
535 	.pru_bind =             key_bind,
536 	.pru_connect =          key_connect,
537 	.pru_detach =           key_detach,
538 	.pru_disconnect =       key_disconnect,
539 	.pru_peeraddr =         key_peeraddr,
540 	.pru_send =             key_send,
541 	.pru_shutdown =         key_shutdown,
542 	.pru_sockaddr =         key_sockaddr,
543 	.pru_sosend =           sosend,
544 	.pru_soreceive =        soreceive,
545 };
546 
547 /* sysctl */
548 SYSCTL_NODE(_net, PF_KEY, key, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "Key Family");
549 
550 /*
551  * Definitions of protocols supported in the KEY domain.
552  */
553 
554 extern struct domain keydomain_s;
555 
556 static struct protosw keysw[] = {
557 	{
558 		.pr_type =              SOCK_RAW,
559 		.pr_protocol =          PF_KEY_V2,
560 		.pr_flags =             PR_ATOMIC | PR_ADDR,
561 		.pr_output =            key_output,
562 		.pr_ctlinput =          raw_ctlinput,
563 		.pr_init =              key_init,
564 		.pr_usrreqs =           &key_usrreqs,
565 	}
566 };
567 
568 static int key_proto_count = (sizeof(keysw) / sizeof(struct protosw));
569 
570 struct domain keydomain_s = {
571 	.dom_family =           PF_KEY,
572 	.dom_name =             "key",
573 	.dom_init =             key_dinit,
574 	.dom_maxrtkey =         sizeof(struct key_cb),
575 };
576 
577 static void
key_dinit(struct domain * dp)578 key_dinit(struct domain *dp)
579 {
580 	struct protosw *pr;
581 	int i;
582 
583 	VERIFY(!(dp->dom_flags & DOM_INITIALIZED));
584 	VERIFY(keydomain == NULL);
585 
586 	keydomain = dp;
587 
588 	for (i = 0, pr = &keysw[0]; i < key_proto_count; i++, pr++) {
589 		net_add_proto(pr, dp, 1);
590 	}
591 }
592