xref: /netbsd-src/sys/netipsec/keysock.c (revision 2c6fc41c810f5088457889d00eba558e8bc74d9e)
1 /*	$NetBSD: keysock.c,v 1.26 2014/05/21 20:46:29 rmind 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.26 2014/05/21 20:46:29 rmind 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 
66 typedef int	pr_output_t (struct mbuf *, struct socket *);
67 
68 struct key_cb {
69 	int key_count;
70 	int any_count;
71 };
72 static struct key_cb key_cb;
73 
74 static struct sockaddr key_dst = {
75     .sa_len = 2,
76     .sa_family = PF_KEY,
77 };
78 static struct sockaddr key_src = {
79     .sa_len = 2,
80     .sa_family = PF_KEY,
81 };
82 
83 
84 static int key_sendup0(struct rawcb *, struct mbuf *, int, int);
85 
86 int key_registered_sb_max = (2048 * MHLEN); /* XXX arbitrary */
87 
88 /*
89  * key_output()
90  */
91 int
92 key_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);
147 end:
148 	if (m)
149 		m_freem(m);
150 	return error;
151 }
152 
153 /*
154  * send message to the socket.
155  */
156 static int
157 key_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. */
207 int
208 key_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 		if (tlen == len) {
247 			MGETHDR(n, M_DONTWAIT, MT_DATA);
248 			n->m_len = MHLEN;
249 		} else {
250 			MGET(n, M_DONTWAIT, MT_DATA);
251 			n->m_len = MLEN;
252 		}
253 		if (!n) {
254 			PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
255 			return ENOBUFS;
256 		}
257 		if (tlen >= MCLBYTES) {	/*XXX better threshold? */
258 			MCLGET(n, M_DONTWAIT);
259 			if ((n->m_flags & M_EXT) == 0) {
260 				m_free(n);
261 				m_freem(m);
262 				PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
263 				return ENOBUFS;
264 			}
265 			n->m_len = MCLBYTES;
266 		}
267 
268 		if (tlen < n->m_len)
269 			n->m_len = tlen;
270 		n->m_next = NULL;
271 		if (m == NULL)
272 			m = mprev = n;
273 		else {
274 			mprev->m_next = n;
275 			mprev = n;
276 		}
277 		tlen -= n->m_len;
278 		n = NULL;
279 	}
280 	m->m_pkthdr.len = len;
281 	m->m_pkthdr.rcvif = NULL;
282 	m_copyback(m, 0, len, msg);
283 
284 	/* avoid duplicated statistics */
285 	{
286 		uint64_t *ps = PFKEY_STAT_GETREF();
287 		ps[PFKEY_STAT_IN_TOTAL]--;
288 		ps[PFKEY_STAT_IN_BYTES] -= len;
289 		ps[PFKEY_STAT_IN_MSGTYPE + msg->sadb_msg_type]--;
290 		PFKEY_STAT_PUTREF();
291 	}
292 
293 	return key_sendup_mbuf(so, m, target);
294 }
295 
296 /* so can be NULL if target != KEY_SENDUP_ONE */
297 int
298 key_sendup_mbuf(struct socket *so, struct mbuf *m,
299 		int target/*, sbprio */)
300 {
301 	struct mbuf *n;
302 	struct keycb *kp;
303 	int sendup;
304 	struct rawcb *rp;
305 	int error = 0;
306 	int sbprio = 0; /* XXX should be a parameter */
307 
308 	if (m == NULL)
309 		panic("key_sendup_mbuf: NULL pointer was passed");
310 	if (so == NULL && target == KEY_SENDUP_ONE)
311 		panic("key_sendup_mbuf: NULL pointer was passed");
312 
313 	/*
314 	 * RFC 2367 says ACQUIRE and other kernel-generated messages
315 	 * are special. We treat all KEY_SENDUP_REGISTERED messages
316 	 * as special, delivering them to all registered sockets
317 	 * even if the socket is at or above its so->so_rcv.sb_max limits.
318 	 * The only constraint is that the  so_rcv data fall below
319 	 * key_registered_sb_max.
320 	 * Doing that check here avoids reworking every key_sendup_mbuf()
321 	 * in the short term. . The rework will be done after a technical
322 	 * conensus that this approach is appropriate.
323  	 */
324 	if (target == KEY_SENDUP_REGISTERED) {
325 		sbprio = SB_PRIO_BESTEFFORT;
326 	}
327 
328 	{
329 		uint64_t *ps = PFKEY_STAT_GETREF();
330 		ps[PFKEY_STAT_IN_TOTAL]++;
331 		ps[PFKEY_STAT_IN_BYTES] += m->m_pkthdr.len;
332 		PFKEY_STAT_PUTREF();
333 	}
334 	if (m->m_len < sizeof(struct sadb_msg)) {
335 #if 1
336 		m = m_pullup(m, sizeof(struct sadb_msg));
337 		if (m == NULL) {
338 			PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
339 			return ENOBUFS;
340 		}
341 #else
342 		/* don't bother pulling it up just for stats */
343 #endif
344 	}
345 	if (m->m_len >= sizeof(struct sadb_msg)) {
346 		struct sadb_msg *msg;
347 		msg = mtod(m, struct sadb_msg *);
348 		PFKEY_STATINC(PFKEY_STAT_IN_MSGTYPE + msg->sadb_msg_type);
349 	}
350 
351 	LIST_FOREACH(rp, &rawcb_list, rcb_list)
352 	{
353 		struct socket * kso = rp->rcb_socket;
354 		if (rp->rcb_proto.sp_family != PF_KEY)
355 			continue;
356 		if (rp->rcb_proto.sp_protocol
357 		 && rp->rcb_proto.sp_protocol != PF_KEY_V2) {
358 			continue;
359 		}
360 
361 		kp = (struct keycb *)rp;
362 
363 		/*
364 		 * If you are in promiscuous mode, and when you get broadcasted
365 		 * reply, you'll get two PF_KEY messages.
366 		 * (based on pf_key@inner.net message on 14 Oct 1998)
367 		 */
368 		if (((struct keycb *)rp)->kp_promisc) {
369 			if ((n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
370 				(void)key_sendup0(rp, n, 1, 0);
371 				n = NULL;
372 			}
373 		}
374 
375 		/* the exact target will be processed later */
376 		if (so && sotorawcb(so) == rp)
377 			continue;
378 
379 		sendup = 0;
380 		switch (target) {
381 		case KEY_SENDUP_ONE:
382 			/* the statement has no effect */
383 			if (so && sotorawcb(so) == rp)
384 				sendup++;
385 			break;
386 		case KEY_SENDUP_ALL:
387 			sendup++;
388 			break;
389 		case KEY_SENDUP_REGISTERED:
390 			if (kp->kp_registered) {
391 				if (kso->so_rcv.sb_cc <= key_registered_sb_max)
392 					sendup++;
393 			  	else
394 			  		printf("keysock: "
395 					       "registered sendup dropped, "
396 					       "sb_cc %ld max %d\n",
397 					       kso->so_rcv.sb_cc,
398 					       key_registered_sb_max);
399 			}
400 			break;
401 		}
402 		PFKEY_STATINC(PFKEY_STAT_IN_MSGTARGET + target);
403 
404 		if (!sendup)
405 			continue;
406 
407 		if ((n = m_copy(m, 0, (int)M_COPYALL)) == NULL) {
408 			m_freem(m);
409 			PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
410 			return ENOBUFS;
411 		}
412 
413 		if ((error = key_sendup0(rp, n, 0, 0)) != 0) {
414 			m_freem(m);
415 			return error;
416 		}
417 
418 		n = NULL;
419 	}
420 
421 	/* The 'later' time for processing the exact target has arrived */
422 	if (so) {
423 		error = key_sendup0(sotorawcb(so), m, 0, sbprio);
424 		m = NULL;
425 	} else {
426 		error = 0;
427 		m_freem(m);
428 	}
429 	return error;
430 }
431 
432 static int
433 key_attach(struct socket *so, int proto)
434 {
435 	struct keycb *kp;
436 	int s, error;
437 
438 	KASSERT(sotorawcb(so) == NULL);
439 	kp = kmem_zalloc(sizeof(*kp), KM_SLEEP);
440 	kp->kp_raw.rcb_len = sizeof(*kp);
441 	so->so_pcb = kp;
442 
443 	s = splsoftnet();
444 	error = raw_attach(so, proto);
445 	if (error) {
446 		PFKEY_STATINC(PFKEY_STAT_SOCKERR);
447 		kmem_free(kp, sizeof(*kp));
448 		so->so_pcb = NULL;
449 		goto out;
450 	}
451 
452 	kp->kp_promisc = kp->kp_registered = 0;
453 
454 	if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) /* XXX: AF_KEY */
455 		key_cb.key_count++;
456 	key_cb.any_count++;
457 	kp->kp_raw.rcb_laddr = &key_src;
458 	kp->kp_raw.rcb_faddr = &key_dst;
459 	soisconnected(so);
460 	so->so_options |= SO_USELOOPBACK;
461 out:
462 	KASSERT(solocked(so));
463 	splx(s);
464 	return error;
465 }
466 
467 static void
468 key_detach(struct socket *so)
469 {
470 	struct keycb *kp = (struct keycb *)sotorawcb(so);
471 	int s;
472 
473 	KASSERT(solocked(so));
474 	KASSERT(kp != NULL);
475 
476 	s = splsoftnet();
477 	if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) /* XXX: AF_KEY */
478 		key_cb.key_count--;
479 	key_cb.any_count--;
480 	key_freereg(so);
481 	raw_detach(so);
482 	splx(s);
483 }
484 
485 /*
486  * key_usrreq()
487  * derived from net/rtsock.c:route_usrreq()
488  */
489 static int
490 key_usrreq(struct socket *so, int req,struct mbuf *m, struct mbuf *nam,
491     struct mbuf *control, struct lwp *l)
492 {
493 	int s, error = 0;
494 
495 	KASSERT(req != PRU_ATTACH);
496 	KASSERT(req != PRU_DETACH);
497 
498 	s = splsoftnet();
499 	error = raw_usrreq(so, req, m, nam, control, l);
500 	m = control = NULL;	/* reclaimed in raw_usrreq */
501 	splx(s);
502 
503 	return error;
504 }
505 
506 /*
507  * Definitions of protocols supported in the KEY domain.
508  */
509 
510 DOMAIN_DEFINE(keydomain);
511 
512 PR_WRAP_USRREQS(key)
513 #define	key_attach	key_attach_wrapper
514 #define	key_detach	key_detach_wrapper
515 #define	key_usrreq	key_usrreq_wrapper
516 
517 const struct pr_usrreqs key_usrreqs = {
518 	.pr_attach	= key_attach,
519 	.pr_detach	= key_detach,
520 	.pr_generic	= key_usrreq,
521 };
522 
523 const struct protosw keysw[] = {
524     {
525 	.pr_type = SOCK_RAW,
526 	.pr_domain = &keydomain,
527 	.pr_protocol = PF_KEY_V2,
528 	.pr_flags = PR_ATOMIC|PR_ADDR,
529 	.pr_output = key_output,
530 	.pr_ctlinput = raw_ctlinput,
531 	.pr_usrreqs = &key_usrreqs,
532 	.pr_init = raw_init,
533     }
534 };
535 
536 struct domain keydomain = {
537     .dom_family = PF_KEY,
538     .dom_name = "key",
539     .dom_init = key_init,
540     .dom_protosw = keysw,
541     .dom_protoswNPROTOSW = &keysw[__arraycount(keysw)],
542 };
543