keysock.c revision 1.36
1/*	$NetBSD: keysock.c,v 1.36 2014/07/23 13:17:18 rtr Exp $	*/
2/*	$FreeBSD: src/sys/netipsec/keysock.c,v 1.3.2.1 2003/01/24 05:11:36 sam Exp $	*/
3/*	$KAME: keysock.c,v 1.25 2001/08/13 20:07:41 itojun Exp $	*/
4
5/*
6 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the project nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#include <sys/cdefs.h>
35__KERNEL_RCSID(0, "$NetBSD: keysock.c,v 1.36 2014/07/23 13:17:18 rtr Exp $");
36
37#include "opt_ipsec.h"
38
39/* This code has derived from sys/net/rtsock.c on FreeBSD2.2.5 */
40
41#include <sys/types.h>
42#include <sys/param.h>
43#include <sys/domain.h>
44#include <sys/errno.h>
45#include <sys/kernel.h>
46#include <sys/kmem.h>
47#include <sys/mbuf.h>
48#include <sys/protosw.h>
49#include <sys/signalvar.h>
50#include <sys/socket.h>
51#include <sys/socketvar.h>
52#include <sys/sysctl.h>
53#include <sys/systm.h>
54
55#include <net/raw_cb.h>
56#include <net/route.h>
57
58#include <net/pfkeyv2.h>
59#include <netipsec/key.h>
60#include <netipsec/keysock.h>
61#include <netipsec/key_debug.h>
62
63#include <netipsec/ipsec_osdep.h>
64#include <netipsec/ipsec_private.h>
65
66typedef int	pr_output_t (struct mbuf *, struct socket *);
67
68struct key_cb {
69	int key_count;
70	int any_count;
71};
72static struct key_cb key_cb;
73
74static struct sockaddr key_dst = {
75    .sa_len = 2,
76    .sa_family = PF_KEY,
77};
78static struct sockaddr key_src = {
79    .sa_len = 2,
80    .sa_family = PF_KEY,
81};
82
83
84static int key_sendup0(struct rawcb *, struct mbuf *, int, int);
85
86int key_registered_sb_max = (2048 * MHLEN); /* XXX arbitrary */
87
88/*
89 * key_output()
90 */
91int
92key_output(struct mbuf *m, ...)
93{
94	struct sadb_msg *msg;
95	int len, error = 0;
96	int s;
97	struct socket *so;
98	va_list ap;
99
100	va_start(ap, m);
101	so = va_arg(ap, struct socket *);
102	va_end(ap);
103
104	if (m == 0)
105		panic("key_output: NULL pointer was passed");
106
107	{
108		uint64_t *ps = PFKEY_STAT_GETREF();
109		ps[PFKEY_STAT_OUT_TOTAL]++;
110		ps[PFKEY_STAT_OUT_BYTES] += m->m_pkthdr.len;
111		PFKEY_STAT_PUTREF();
112	}
113
114	len = m->m_pkthdr.len;
115	if (len < sizeof(struct sadb_msg)) {
116		PFKEY_STATINC(PFKEY_STAT_OUT_TOOSHORT);
117		error = EINVAL;
118		goto end;
119	}
120
121	if (m->m_len < sizeof(struct sadb_msg)) {
122		if ((m = m_pullup(m, sizeof(struct sadb_msg))) == 0) {
123			PFKEY_STATINC(PFKEY_STAT_OUT_NOMEM);
124			error = ENOBUFS;
125			goto end;
126		}
127	}
128
129	if ((m->m_flags & M_PKTHDR) == 0)
130		panic("key_output: not M_PKTHDR ??");
131
132	KEYDEBUG(KEYDEBUG_KEY_DUMP, kdebug_mbuf(m));
133
134	msg = mtod(m, struct sadb_msg *);
135	PFKEY_STATINC(PFKEY_STAT_OUT_MSGTYPE + msg->sadb_msg_type);
136	if (len != PFKEY_UNUNIT64(msg->sadb_msg_len)) {
137		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
138		error = EINVAL;
139		goto end;
140	}
141
142	/*XXX giant lock*/
143	s = splsoftnet();
144	error = key_parse(m, so);
145	m = NULL;
146	splx(s);
147end:
148	if (m)
149		m_freem(m);
150	return error;
151}
152
153/*
154 * send message to the socket.
155 */
156static int
157key_sendup0(
158    struct rawcb *rp,
159    struct mbuf *m,
160    int promisc,
161    int sbprio
162)
163{
164	int error;
165	int ok;
166
167	if (promisc) {
168		struct sadb_msg *pmsg;
169
170		M_PREPEND(m, sizeof(struct sadb_msg), M_DONTWAIT);
171		if (m && m->m_len < sizeof(struct sadb_msg))
172			m = m_pullup(m, sizeof(struct sadb_msg));
173		if (!m) {
174			PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
175			return ENOBUFS;
176		}
177		m->m_pkthdr.len += sizeof(*pmsg);
178
179		pmsg = mtod(m, struct sadb_msg *);
180		memset(pmsg, 0, sizeof(*pmsg));
181		pmsg->sadb_msg_version = PF_KEY_V2;
182		pmsg->sadb_msg_type = SADB_X_PROMISC;
183		pmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
184		/* pid and seq? */
185
186		PFKEY_STATINC(PFKEY_STAT_IN_MSGTYPE + pmsg->sadb_msg_type);
187	}
188
189	if (sbprio == 0)
190		ok = sbappendaddr(&rp->rcb_socket->so_rcv,
191			       (struct sockaddr *)&key_src, m, NULL);
192	else
193		ok = sbappendaddrchain(&rp->rcb_socket->so_rcv,
194			       (struct sockaddr *)&key_src, m, sbprio);
195
196	  if (!ok) {
197		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
198		m_freem(m);
199		error = ENOBUFS;
200	} else
201		error = 0;
202	sorwakeup(rp->rcb_socket);
203	return error;
204}
205
206/* XXX this interface should be obsoleted. */
207int
208key_sendup(struct socket *so, struct sadb_msg *msg, u_int len,
209	   int target)	/*target of the resulting message*/
210{
211	struct mbuf *m, *n, *mprev;
212	int tlen;
213
214	/* sanity check */
215	if (so == 0 || msg == 0)
216		panic("key_sendup: NULL pointer was passed");
217
218	KEYDEBUG(KEYDEBUG_KEY_DUMP,
219		printf("key_sendup: \n");
220		kdebug_sadb(msg));
221
222	/*
223	 * we increment statistics here, just in case we have ENOBUFS
224	 * in this function.
225	 */
226	{
227		uint64_t *ps = PFKEY_STAT_GETREF();
228		ps[PFKEY_STAT_IN_TOTAL]++;
229		ps[PFKEY_STAT_IN_BYTES] += len;
230		ps[PFKEY_STAT_IN_MSGTYPE + msg->sadb_msg_type]++;
231		PFKEY_STAT_PUTREF();
232	}
233
234	/*
235	 * Get mbuf chain whenever possible (not clusters),
236	 * to save socket buffer.  We'll be generating many SADB_ACQUIRE
237	 * messages to listening key sockets.  If we simply allocate clusters,
238	 * sbappendaddr() will raise ENOBUFS due to too little sbspace().
239	 * sbspace() computes # of actual data bytes AND mbuf region.
240	 *
241	 * TODO: SADB_ACQUIRE filters should be implemented.
242	 */
243	tlen = len;
244	m = mprev = NULL;
245	while (tlen > 0) {
246		int mlen;
247		if (tlen == len) {
248			MGETHDR(n, M_DONTWAIT, MT_DATA);
249			mlen = MHLEN;
250		} else {
251			MGET(n, M_DONTWAIT, MT_DATA);
252			mlen = MLEN;
253		}
254		if (!n) {
255			PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
256			return ENOBUFS;
257		}
258		n->m_len = mlen;
259		if (tlen >= MCLBYTES) {	/*XXX better threshold? */
260			MCLGET(n, M_DONTWAIT);
261			if ((n->m_flags & M_EXT) == 0) {
262				m_free(n);
263				m_freem(m);
264				PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
265				return ENOBUFS;
266			}
267			n->m_len = MCLBYTES;
268		}
269
270		if (tlen < n->m_len)
271			n->m_len = tlen;
272		n->m_next = NULL;
273		if (m == NULL)
274			m = mprev = n;
275		else {
276			mprev->m_next = n;
277			mprev = n;
278		}
279		tlen -= n->m_len;
280		n = NULL;
281	}
282	m->m_pkthdr.len = len;
283	m->m_pkthdr.rcvif = NULL;
284	m_copyback(m, 0, len, msg);
285
286	/* avoid duplicated statistics */
287	{
288		uint64_t *ps = PFKEY_STAT_GETREF();
289		ps[PFKEY_STAT_IN_TOTAL]--;
290		ps[PFKEY_STAT_IN_BYTES] -= len;
291		ps[PFKEY_STAT_IN_MSGTYPE + msg->sadb_msg_type]--;
292		PFKEY_STAT_PUTREF();
293	}
294
295	return key_sendup_mbuf(so, m, target);
296}
297
298/* so can be NULL if target != KEY_SENDUP_ONE */
299int
300key_sendup_mbuf(struct socket *so, struct mbuf *m,
301		int target/*, sbprio */)
302{
303	struct mbuf *n;
304	struct keycb *kp;
305	int sendup;
306	struct rawcb *rp;
307	int error = 0;
308	int sbprio = 0; /* XXX should be a parameter */
309
310	if (m == NULL)
311		panic("key_sendup_mbuf: NULL pointer was passed");
312	if (so == NULL && target == KEY_SENDUP_ONE)
313		panic("key_sendup_mbuf: NULL pointer was passed");
314
315	/*
316	 * RFC 2367 says ACQUIRE and other kernel-generated messages
317	 * are special. We treat all KEY_SENDUP_REGISTERED messages
318	 * as special, delivering them to all registered sockets
319	 * even if the socket is at or above its so->so_rcv.sb_max limits.
320	 * The only constraint is that the  so_rcv data fall below
321	 * key_registered_sb_max.
322	 * Doing that check here avoids reworking every key_sendup_mbuf()
323	 * in the short term. . The rework will be done after a technical
324	 * conensus that this approach is appropriate.
325 	 */
326	if (target == KEY_SENDUP_REGISTERED) {
327		sbprio = SB_PRIO_BESTEFFORT;
328	}
329
330	{
331		uint64_t *ps = PFKEY_STAT_GETREF();
332		ps[PFKEY_STAT_IN_TOTAL]++;
333		ps[PFKEY_STAT_IN_BYTES] += m->m_pkthdr.len;
334		PFKEY_STAT_PUTREF();
335	}
336	if (m->m_len < sizeof(struct sadb_msg)) {
337#if 1
338		m = m_pullup(m, sizeof(struct sadb_msg));
339		if (m == NULL) {
340			PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
341			return ENOBUFS;
342		}
343#else
344		/* don't bother pulling it up just for stats */
345#endif
346	}
347	if (m->m_len >= sizeof(struct sadb_msg)) {
348		struct sadb_msg *msg;
349		msg = mtod(m, struct sadb_msg *);
350		PFKEY_STATINC(PFKEY_STAT_IN_MSGTYPE + msg->sadb_msg_type);
351	}
352
353	LIST_FOREACH(rp, &rawcb_list, rcb_list)
354	{
355		struct socket * kso = rp->rcb_socket;
356		if (rp->rcb_proto.sp_family != PF_KEY)
357			continue;
358		if (rp->rcb_proto.sp_protocol
359		 && rp->rcb_proto.sp_protocol != PF_KEY_V2) {
360			continue;
361		}
362
363		kp = (struct keycb *)rp;
364
365		/*
366		 * If you are in promiscuous mode, and when you get broadcasted
367		 * reply, you'll get two PF_KEY messages.
368		 * (based on pf_key@inner.net message on 14 Oct 1998)
369		 */
370		if (((struct keycb *)rp)->kp_promisc) {
371			if ((n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
372				(void)key_sendup0(rp, n, 1, 0);
373				n = NULL;
374			}
375		}
376
377		/* the exact target will be processed later */
378		if (so && sotorawcb(so) == rp)
379			continue;
380
381		sendup = 0;
382		switch (target) {
383		case KEY_SENDUP_ONE:
384			/* the statement has no effect */
385			if (so && sotorawcb(so) == rp)
386				sendup++;
387			break;
388		case KEY_SENDUP_ALL:
389			sendup++;
390			break;
391		case KEY_SENDUP_REGISTERED:
392			if (kp->kp_registered) {
393				if (kso->so_rcv.sb_cc <= key_registered_sb_max)
394					sendup++;
395			  	else
396			  		printf("keysock: "
397					       "registered sendup dropped, "
398					       "sb_cc %ld max %d\n",
399					       kso->so_rcv.sb_cc,
400					       key_registered_sb_max);
401			}
402			break;
403		}
404		PFKEY_STATINC(PFKEY_STAT_IN_MSGTARGET + target);
405
406		if (!sendup)
407			continue;
408
409		if ((n = m_copy(m, 0, (int)M_COPYALL)) == NULL) {
410			m_freem(m);
411			PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
412			return ENOBUFS;
413		}
414
415		if ((error = key_sendup0(rp, n, 0, 0)) != 0) {
416			m_freem(m);
417			return error;
418		}
419
420		n = NULL;
421	}
422
423	/* The 'later' time for processing the exact target has arrived */
424	if (so) {
425		error = key_sendup0(sotorawcb(so), m, 0, sbprio);
426		m = NULL;
427	} else {
428		error = 0;
429		m_freem(m);
430	}
431	return error;
432}
433
434static int
435key_attach(struct socket *so, int proto)
436{
437	struct keycb *kp;
438	int s, error;
439
440	KASSERT(sotorawcb(so) == NULL);
441	kp = kmem_zalloc(sizeof(*kp), KM_SLEEP);
442	kp->kp_raw.rcb_len = sizeof(*kp);
443	so->so_pcb = kp;
444
445	s = splsoftnet();
446	error = raw_attach(so, proto);
447	if (error) {
448		PFKEY_STATINC(PFKEY_STAT_SOCKERR);
449		kmem_free(kp, sizeof(*kp));
450		so->so_pcb = NULL;
451		goto out;
452	}
453
454	kp->kp_promisc = kp->kp_registered = 0;
455
456	if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) /* XXX: AF_KEY */
457		key_cb.key_count++;
458	key_cb.any_count++;
459	kp->kp_raw.rcb_laddr = &key_src;
460	kp->kp_raw.rcb_faddr = &key_dst;
461	soisconnected(so);
462	so->so_options |= SO_USELOOPBACK;
463out:
464	KASSERT(solocked(so));
465	splx(s);
466	return error;
467}
468
469static void
470key_detach(struct socket *so)
471{
472	struct keycb *kp = (struct keycb *)sotorawcb(so);
473	int s;
474
475	KASSERT(solocked(so));
476	KASSERT(kp != NULL);
477
478	s = splsoftnet();
479	if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) /* XXX: AF_KEY */
480		key_cb.key_count--;
481	key_cb.any_count--;
482	key_freereg(so);
483	raw_detach(so);
484	splx(s);
485}
486
487static int
488key_accept(struct socket *so, struct mbuf *nam)
489{
490	KASSERT(solocked(so));
491
492	panic("key_accept");
493	/* NOT REACHED */
494	return EOPNOTSUPP;
495}
496
497static int
498key_ioctl(struct socket *so, u_long cmd, void *nam, struct ifnet *ifp)
499{
500	return EOPNOTSUPP;
501}
502
503static int
504key_stat(struct socket *so, struct stat *ub)
505{
506	KASSERT(solocked(so));
507
508	return 0;
509}
510
511static int
512key_peeraddr(struct socket *so, struct mbuf *nam)
513{
514	struct rawcb *rp = sotorawcb(so);
515
516	KASSERT(solocked(so));
517	KASSERT(rp != NULL);
518	KASSERT(nam != NULL);
519
520	if (rp->rcb_faddr == NULL)
521		return ENOTCONN;
522
523	raw_setpeeraddr(rp, nam);
524	return 0;
525}
526
527static int
528key_sockaddr(struct socket *so, struct mbuf *nam)
529{
530	struct rawcb *rp = sotorawcb(so);
531
532	KASSERT(solocked(so));
533	KASSERT(rp != NULL);
534	KASSERT(nam != NULL);
535
536	if (rp->rcb_faddr == NULL)
537		return ENOTCONN;
538
539	raw_setsockaddr(rp, nam);
540	return 0;
541}
542
543static int
544key_recvoob(struct socket *so, struct mbuf *m, int flags)
545{
546	KASSERT(solocked(so));
547
548	return EOPNOTSUPP;
549}
550
551static int
552key_sendoob(struct socket *so, struct mbuf *m, struct mbuf *control)
553{
554	KASSERT(solocked(so));
555
556	m_freem(m);
557	m_freem(control);
558
559	return EOPNOTSUPP;
560}
561
562/*
563 * key_usrreq()
564 * derived from net/rtsock.c:route_usrreq()
565 */
566static int
567key_usrreq(struct socket *so, int req,struct mbuf *m, struct mbuf *nam,
568    struct mbuf *control, struct lwp *l)
569{
570	int s, error = 0;
571
572	KASSERT(req != PRU_ATTACH);
573	KASSERT(req != PRU_DETACH);
574	KASSERT(req != PRU_ACCEPT);
575	KASSERT(req != PRU_CONTROL);
576	KASSERT(req != PRU_SENSE);
577	KASSERT(req != PRU_PEERADDR);
578	KASSERT(req != PRU_SOCKADDR);
579	KASSERT(req != PRU_RCVOOB);
580	KASSERT(req != PRU_SENDOOB);
581
582	s = splsoftnet();
583	error = raw_usrreq(so, req, m, nam, control, l);
584	m = control = NULL;	/* reclaimed in raw_usrreq */
585	splx(s);
586
587	return error;
588}
589
590/*
591 * Definitions of protocols supported in the KEY domain.
592 */
593
594DOMAIN_DEFINE(keydomain);
595
596PR_WRAP_USRREQS(key)
597#define	key_attach	key_attach_wrapper
598#define	key_detach	key_detach_wrapper
599#define	key_accept	key_accept_wrapper
600#define	key_ioctl	key_ioctl_wrapper
601#define	key_stat	key_stat_wrapper
602#define	key_peeraddr	key_peeraddr_wrapper
603#define	key_sockaddr	key_sockaddr_wrapper
604#define	key_recvoob	key_recvoob_wrapper
605#define	key_sendoob	key_sendoob_wrapper
606#define	key_usrreq	key_usrreq_wrapper
607
608const struct pr_usrreqs key_usrreqs = {
609	.pr_attach	= key_attach,
610	.pr_detach	= key_detach,
611	.pr_accept	= key_accept,
612	.pr_ioctl	= key_ioctl,
613	.pr_stat	= key_stat,
614	.pr_peeraddr	= key_peeraddr,
615	.pr_sockaddr	= key_sockaddr,
616	.pr_recvoob	= key_recvoob,
617	.pr_sendoob	= key_sendoob,
618	.pr_generic	= key_usrreq,
619};
620
621const struct protosw keysw[] = {
622    {
623	.pr_type = SOCK_RAW,
624	.pr_domain = &keydomain,
625	.pr_protocol = PF_KEY_V2,
626	.pr_flags = PR_ATOMIC|PR_ADDR,
627	.pr_output = key_output,
628	.pr_ctlinput = raw_ctlinput,
629	.pr_usrreqs = &key_usrreqs,
630	.pr_init = raw_init,
631    }
632};
633
634struct domain keydomain = {
635    .dom_family = PF_KEY,
636    .dom_name = "key",
637    .dom_init = key_init,
638    .dom_protosw = keysw,
639    .dom_protoswNPROTOSW = &keysw[__arraycount(keysw)],
640};
641