xref: /netbsd-src/sys/netipsec/ipsec.c (revision 4391d5e9d4f291db41e3b3ba26a01b5e51364aae)
1 /*	$NetBSD: ipsec.c,v 1.60 2013/06/08 13:50:22 rmind Exp $	*/
2 /*	$FreeBSD: /usr/local/www/cvsroot/FreeBSD/src/sys/netipsec/ipsec.c,v 1.2.2.2 2003/07/01 01:38:13 sam Exp $	*/
3 /*	$KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane 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: ipsec.c,v 1.60 2013/06/08 13:50:22 rmind Exp $");
36 
37 /*
38  * IPsec controller part.
39  */
40 
41 #include "opt_inet.h"
42 #ifdef __FreeBSD__
43 #include "opt_inet6.h"
44 #endif
45 #include "opt_ipsec.h"
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/domain.h>
52 #include <sys/protosw.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/errno.h>
56 #include <sys/time.h>
57 #include <sys/kernel.h>
58 #include <sys/syslog.h>
59 #include <sys/sysctl.h>
60 #include <sys/proc.h>
61 #include <sys/kauth.h>
62 
63 #include <net/if.h>
64 #include <net/route.h>
65 
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
69 #include <netinet/ip_var.h>
70 #include <netinet/in_var.h>
71 #include <netinet/udp.h>
72 #include <netinet/udp_var.h>
73 #include <netinet/tcp.h>
74 #include <netinet/udp.h>
75 #include <netinet/ip_icmp.h>
76 #include <netinet/ip_private.h>
77 
78 #include <netinet/ip6.h>
79 #ifdef INET6
80 #include <netinet6/ip6_var.h>
81 #endif
82 #include <netinet/in_pcb.h>
83 #ifdef INET6
84 #include <netinet6/in6_pcb.h>
85 #include <netinet/icmp6.h>
86 #endif
87 
88 #include <netipsec/ipsec.h>
89 #include <netipsec/ipsec_var.h>
90 #include <netipsec/ipsec_private.h>
91 #ifdef INET6
92 #include <netipsec/ipsec6.h>
93 #endif
94 #include <netipsec/ah_var.h>
95 #include <netipsec/esp_var.h>
96 #include <netipsec/ipcomp.h>		/*XXX*/
97 #include <netipsec/ipcomp_var.h>
98 
99 #include <netipsec/key.h>
100 #include <netipsec/keydb.h>
101 #include <netipsec/key_debug.h>
102 
103 #include <netipsec/xform.h>
104 
105 #include <netipsec/ipsec_osdep.h>
106 
107 #include <net/net_osdep.h>
108 
109 #ifdef IPSEC_DEBUG
110 int ipsec_debug = 1;
111 
112 /*
113  * When set to 1, IPsec will send packets with the same sequence number.
114  * This allows to verify if the other side has proper replay attacks detection.
115  */
116 int ipsec_replay = 0;
117 
118 /*
119  * When set 1, IPsec will send packets with corrupted HMAC.
120  * This allows to verify if the other side properly detects modified packets.
121  */
122 int ipsec_integrity = 0;
123 #else
124 int ipsec_debug = 0;
125 #endif
126 
127 percpu_t *ipsecstat_percpu;
128 int ip4_ah_offsetmask = 0;	/* maybe IP_DF? */
129 int ip4_ipsec_dfbit = 2;	/* DF bit on encap. 0: clear 1: set 2: copy */
130 int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
131 int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
132 int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
133 int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
134 struct secpolicy ip4_def_policy;
135 int ip4_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
136 int ip4_esp_randpad = -1;
137 
138 #ifdef __NetBSD__
139 u_int ipsec_spdgen = 1;		/* SPD generation # */
140 
141 static struct secpolicy *ipsec_checkpcbcache (struct mbuf *,
142 	struct inpcbpolicy *, int);
143 static int ipsec_fillpcbcache (struct inpcbpolicy *, struct mbuf *,
144 	struct secpolicy *, int);
145 static int ipsec_invalpcbcache (struct inpcbpolicy *, int);
146 #endif /* __NetBSD__ */
147 
148 /*
149  * Crypto support requirements:
150  *
151  *  1	require hardware support
152  * -1	require software support
153  *  0	take anything
154  */
155 int	crypto_support = 0;
156 
157 static struct secpolicy *ipsec_getpolicybysock(struct mbuf *, u_int,
158 	PCB_T *, int *);
159 
160 #ifdef __FreeBSD__
161 SYSCTL_DECL(_net_inet_ipsec);
162 
163 /* net.inet.ipsec */
164 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY,
165 	def_policy, CTLFLAG_RW,	&ip4_def_policy.policy,	0, "");
166 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
167 	CTLFLAG_RW, &ip4_esp_trans_deflev,	0, "");
168 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
169 	CTLFLAG_RW, &ip4_esp_net_deflev,	0, "");
170 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
171 	CTLFLAG_RW, &ip4_ah_trans_deflev,	0, "");
172 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
173 	CTLFLAG_RW, &ip4_ah_net_deflev,	0, "");
174 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS,
175 	ah_cleartos, CTLFLAG_RW,	&ip4_ah_cleartos,	0, "");
176 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK,
177 	ah_offsetmask, CTLFLAG_RW,	&ip4_ah_offsetmask,	0, "");
178 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT,
179 	dfbit, CTLFLAG_RW,	&ip4_ipsec_dfbit,	0, "");
180 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN,
181 	ecn, CTLFLAG_RW,	&ip4_ipsec_ecn,	0, "");
182 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG,
183 	debug, CTLFLAG_RW,	&ipsec_debug,	0, "");
184 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
185 	esp_randpad, CTLFLAG_RW,	&ip4_esp_randpad,	0, "");
186 SYSCTL_INT(_net_inet_ipsec, OID_AUTO,
187 	crypto_support,	CTLFLAG_RW,	&crypto_support,0, "");
188 SYSCTL_STRUCT(_net_inet_ipsec, OID_AUTO,
189 	ipsecstats,	CTLFLAG_RD,	&newipsecstat,	newipsecstat, "");
190 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay, CTLFLAG_RW, &ipsec_replay, 0,
191 	"Emulate replay attack");
192 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity, CTLFLAG_RW,
193 	&ipsec_integrity, 0, "Emulate man-in-the-middle attack");
194 #endif /* __FreeBSD__ */
195 
196 #ifdef INET6
197 int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
198 int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
199 int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
200 int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
201 struct secpolicy ip6_def_policy;
202 int ip6_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
203 int ip6_esp_randpad = -1;
204 
205 
206 #ifdef __FreeBSD__
207 SYSCTL_DECL(_net_inet6_ipsec6);
208 
209 /* net.inet6.ipsec6 */
210 #ifdef COMPAT_KAME
211 SYSCTL_OID(_net_inet6_ipsec6, IPSECCTL_STATS, stats, CTLFLAG_RD,
212 	0,0, compat_ipsecstats_sysctl, "S", "");
213 #endif /* COMPAT_KAME */
214 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY,
215 	def_policy, CTLFLAG_RW,	&ip4_def_policy.policy,	0, "");
216 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
217 	CTLFLAG_RW, &ip6_esp_trans_deflev,	0, "");
218 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
219 	CTLFLAG_RW, &ip6_esp_net_deflev,	0, "");
220 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
221 	CTLFLAG_RW, &ip6_ah_trans_deflev,	0, "");
222 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
223 	CTLFLAG_RW, &ip6_ah_net_deflev,	0, "");
224 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
225 	ecn, CTLFLAG_RW,	&ip6_ipsec_ecn,	0, "");
226 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG,
227 	debug, CTLFLAG_RW,	&ipsec_debug,	0, "");
228 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
229 	esp_randpad, CTLFLAG_RW,	&ip6_esp_randpad,	0, "");
230 #endif /* INET6 */
231 #endif /* __FreeBSD__ */
232 
233 static int ipsec4_setspidx_inpcb (struct mbuf *, struct inpcb *);
234 #ifdef INET6
235 static int ipsec6_setspidx_in6pcb (struct mbuf *, struct in6pcb *);
236 #endif
237 static int ipsec_setspidx (struct mbuf *, struct secpolicyindex *, int);
238 static void ipsec4_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
239 static int ipsec4_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
240 #ifdef INET6
241 static void ipsec6_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
242 static int ipsec6_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
243 #endif
244 static void ipsec_delpcbpolicy (struct inpcbpolicy *);
245 static struct secpolicy *ipsec_deepcopy_policy (const struct secpolicy *);
246 static int ipsec_set_policy (struct secpolicy **, int, const void *, size_t,
247     kauth_cred_t);
248 static int ipsec_get_policy (struct secpolicy *, struct mbuf **);
249 static void vshiftl (unsigned char *, int, int);
250 static size_t ipsec_hdrsiz (const struct secpolicy *);
251 
252 #ifdef __NetBSD__
253 /*
254  * Try to validate and use cached policy on a PCB.
255  */
256 static struct secpolicy *
257 ipsec_checkpcbcache(struct mbuf *m, struct inpcbpolicy *pcbsp, int dir)
258 {
259 	struct secpolicyindex spidx;
260 
261 	switch (dir) {
262 	case IPSEC_DIR_INBOUND:
263 	case IPSEC_DIR_OUTBOUND:
264 	case IPSEC_DIR_ANY:
265 		break;
266 	default:
267 		return NULL;
268 	}
269 #ifdef DIAGNOSTIC
270 	if (pcbsp == NULL) {
271 		printf("ipsec_checkpcbcache: NULL pcbsp\n");
272 		/* XXX panic? */
273 		return NULL;
274 	}
275 #endif
276 
277 #ifdef DIAGNOSTIC
278 	if (dir >= sizeof(pcbsp->sp_cache)/sizeof(pcbsp->sp_cache[0]))
279 		panic("dir too big in ipsec_checkpcbcache");
280 #endif
281 	/* SPD table change invalidate all the caches. */
282 	if (ipsec_spdgen != pcbsp->sp_cache[dir].cachegen) {
283 		ipsec_invalpcbcache(pcbsp, dir);
284 		return NULL;
285 	}
286 	if (!pcbsp->sp_cache[dir].cachesp)
287 		return NULL;
288 	if (pcbsp->sp_cache[dir].cachesp->state != IPSEC_SPSTATE_ALIVE) {
289 		ipsec_invalpcbcache(pcbsp, dir);
290 		return NULL;
291 	}
292 	if ((pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) == 0) {
293 		if (!pcbsp->sp_cache[dir].cachesp)
294 			return NULL;
295 		if (ipsec_setspidx(m, &spidx, 1) != 0)
296 			return NULL;
297 
298 		/*
299 		 * We have to make an exact match here since the cached rule
300 		 * might have lower priority than a rule that would otherwise
301 		 * have matched the packet.
302 		 */
303 
304 		if (memcmp(&pcbsp->sp_cache[dir].cacheidx, &spidx, sizeof(spidx)))
305 			return NULL;
306 
307 	} else {
308 		/*
309 		 * The pcb is connected, and the L4 code is sure that:
310 		 * - outgoing side uses inp_[lf]addr
311 		 * - incoming side looks up policy after inpcb lookup
312 		 * and address pair is know to be stable.  We do not need
313 		 * to generate spidx again, nor check the address match again.
314 		 *
315 		 * For IPv4/v6 SOCK_STREAM sockets, this assumptions holds
316 		 * and there are calls to ipsec_pcbconn() from in_pcbconnect().
317 		 */
318 	}
319 
320 	pcbsp->sp_cache[dir].cachesp->lastused = time_second;
321 	pcbsp->sp_cache[dir].cachesp->refcnt++;
322 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
323 		printf("DP ipsec_checkpcbcache cause refcnt++:%d SP:%p\n",
324 		pcbsp->sp_cache[dir].cachesp->refcnt,
325 		pcbsp->sp_cache[dir].cachesp));
326 	return pcbsp->sp_cache[dir].cachesp;
327 }
328 
329 static int
330 ipsec_fillpcbcache(struct inpcbpolicy *pcbsp, struct mbuf *m,
331 	struct secpolicy *sp, int dir)
332 {
333 
334 	switch (dir) {
335 	case IPSEC_DIR_INBOUND:
336 	case IPSEC_DIR_OUTBOUND:
337 		break;
338 	default:
339 		return EINVAL;
340 	}
341 #ifdef DIAGNOSTIC
342 	if (dir >= sizeof(pcbsp->sp_cache)/sizeof(pcbsp->sp_cache[0]))
343 		panic("dir too big in ipsec_fillpcbcache");
344 #endif
345 
346 	if (pcbsp->sp_cache[dir].cachesp)
347 		KEY_FREESP(&pcbsp->sp_cache[dir].cachesp);
348 	pcbsp->sp_cache[dir].cachesp = NULL;
349 	pcbsp->sp_cache[dir].cachehint = IPSEC_PCBHINT_MAYBE;
350 	if (ipsec_setspidx(m, &pcbsp->sp_cache[dir].cacheidx, 1) != 0) {
351 		return EINVAL;
352 	}
353 	pcbsp->sp_cache[dir].cachesp = sp;
354 	if (pcbsp->sp_cache[dir].cachesp) {
355 		pcbsp->sp_cache[dir].cachesp->refcnt++;
356 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
357 			printf("DP ipsec_fillpcbcache cause refcnt++:%d SP:%p\n",
358 			pcbsp->sp_cache[dir].cachesp->refcnt,
359 			pcbsp->sp_cache[dir].cachesp));
360 
361 		/*
362 		 * If the PCB is connected, we can remember a hint to
363 		 * possibly short-circuit IPsec processing in other places.
364 		 */
365 		if (pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) {
366 			switch (pcbsp->sp_cache[dir].cachesp->policy) {
367 			case IPSEC_POLICY_NONE:
368 			case IPSEC_POLICY_BYPASS:
369 				pcbsp->sp_cache[dir].cachehint =
370 					IPSEC_PCBHINT_NO;
371 				break;
372 			default:
373 				pcbsp->sp_cache[dir].cachehint =
374 					IPSEC_PCBHINT_YES;
375 			}
376 		}
377 	}
378 	pcbsp->sp_cache[dir].cachegen = ipsec_spdgen;
379 
380 	return 0;
381 }
382 
383 static int
384 ipsec_invalpcbcache(struct inpcbpolicy *pcbsp, int dir)
385 {
386 	int i;
387 
388 	for (i = IPSEC_DIR_INBOUND; i <= IPSEC_DIR_OUTBOUND; i++) {
389 		if (dir != IPSEC_DIR_ANY && i != dir)
390 			continue;
391 		if (pcbsp->sp_cache[i].cachesp)
392 			KEY_FREESP(&pcbsp->sp_cache[i].cachesp);
393 		pcbsp->sp_cache[i].cachesp = NULL;
394 		pcbsp->sp_cache[i].cachehint = IPSEC_PCBHINT_MAYBE;
395 		pcbsp->sp_cache[i].cachegen = 0;
396 		memset(&pcbsp->sp_cache[i].cacheidx, 0,
397 			  sizeof(pcbsp->sp_cache[i].cacheidx));
398 	}
399 	return 0;
400 }
401 
402 void
403 ipsec_pcbconn(struct inpcbpolicy *pcbsp)
404 {
405 
406 	pcbsp->sp_cacheflags |= IPSEC_PCBSP_CONNECTED;
407 	ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
408 }
409 
410 void
411 ipsec_pcbdisconn(struct inpcbpolicy *pcbsp)
412 {
413 
414 	pcbsp->sp_cacheflags &= ~IPSEC_PCBSP_CONNECTED;
415 	ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
416 }
417 
418 void
419 ipsec_invalpcbcacheall(void)
420 {
421 
422 	if (ipsec_spdgen == UINT_MAX)
423 		ipsec_spdgen = 1;
424 	else
425 		ipsec_spdgen++;
426 }
427 #endif /* __NetBSD__ */
428 
429 /*
430  * Return a held reference to the default SP.
431  */
432 static struct secpolicy *
433 key_allocsp_default(int af, const char *where, int tag)
434 {
435 	struct secpolicy *sp;
436 
437 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
438 		printf("DP key_allocsp_default from %s:%u\n", where, tag));
439 
440     switch(af) {
441         case AF_INET:
442 	        sp = &ip4_def_policy;
443             break;
444 #ifdef INET6
445         case AF_INET6:
446             sp = &ip6_def_policy;
447             break;
448 #endif
449         default:
450 	        KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
451 		    printf("key_allocsp_default : unexpected protocol family %u\n",
452                    af));
453             return NULL;
454     }
455 
456 	if (sp->policy != IPSEC_POLICY_DISCARD &&
457 		sp->policy != IPSEC_POLICY_NONE) {
458 		ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
459 			sp->policy, IPSEC_POLICY_NONE));
460 		sp->policy = IPSEC_POLICY_NONE;
461 	}
462 	sp->refcnt++;
463 
464 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
465 		printf("DP key_allocsp_default returns SP:%p (%u)\n",
466 			sp, sp->refcnt));
467 	return sp;
468 }
469 #define	KEY_ALLOCSP_DEFAULT(af) \
470 	key_allocsp_default((af),__FILE__, __LINE__)
471 
472 /*
473  * For OUTBOUND packet having a socket. Searching SPD for packet,
474  * and return a pointer to SP.
475  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
476  *		0	: bypass
477  *		EACCES	: discard packet.
478  *		ENOENT	: ipsec_acquire() in progress, maybe.
479  *		others	: error occurred.
480  *	others:	a pointer to SP
481  *
482  * NOTE: IPv6 mapped address concern is implemented here.
483  */
484 struct secpolicy *
485 ipsec_getpolicy(const struct tdb_ident *tdbi, u_int dir)
486 {
487 	struct secpolicy *sp;
488 
489 	IPSEC_ASSERT(tdbi != NULL, ("ipsec_getpolicy: null tdbi"));
490 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
491 		("ipsec_getpolicy: invalid direction %u", dir));
492 
493 	sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
494 	if (sp == NULL)			/*XXX????*/
495 		sp = KEY_ALLOCSP_DEFAULT(tdbi->dst.sa.sa_family);
496 	IPSEC_ASSERT(sp != NULL, ("ipsec_getpolicy: null SP"));
497 	return sp;
498 }
499 
500 /*
501  * For OUTBOUND packet having a socket. Searching SPD for packet,
502  * and return a pointer to SP.
503  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
504  *		0	: bypass
505  *		EACCES	: discard packet.
506  *		ENOENT	: ipsec_acquire() in progress, maybe.
507  *		others	: error occurred.
508  *	others:	a pointer to SP
509  *
510  * NOTE: IPv6 mapped address concern is implemented here.
511  */
512 static struct secpolicy *
513 ipsec_getpolicybysock(struct mbuf *m, u_int dir, PCB_T *inp, int *error)
514 {
515 	struct inpcbpolicy *pcbsp = NULL;
516 	struct secpolicy *currsp = NULL;	/* policy on socket */
517 	struct secpolicy *sp;
518 	int af;
519 
520 	IPSEC_ASSERT(m != NULL, ("ipsec_getpolicybysock: null mbuf"));
521 	IPSEC_ASSERT(inp != NULL, ("ipsec_getpolicybysock: null inpcb"));
522 	IPSEC_ASSERT(error != NULL, ("ipsec_getpolicybysock: null error"));
523 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
524 		("ipsec_getpolicybysock: invalid direction %u", dir));
525 
526 	IPSEC_ASSERT(PCB_SOCKET(inp) != NULL,
527 		("ipsec_getppolicybysock: null socket\n"));
528 
529 	/* XXX FIXME inpcb/in6pcb  vs socket*/
530 	af = PCB_FAMILY(inp);
531 	IPSEC_ASSERT(af == AF_INET || af == AF_INET6,
532 		("ipsec_getpolicybysock: unexpected protocol family %u", af));
533 
534 #ifdef __NetBSD__
535 	IPSEC_ASSERT(inp->inph_sp != NULL, ("null PCB policy cache"));
536 	/* If we have a cached entry, and if it is still valid, use it. */
537 	IPSEC_STATINC(IPSEC_STAT_SPDCACHELOOKUP);
538 	currsp = ipsec_checkpcbcache(m, /*inpcb_hdr*/inp->inph_sp, dir);
539 	if (currsp) {
540 		*error = 0;
541 		return currsp;
542 	}
543 	IPSEC_STATINC(IPSEC_STAT_SPDCACHEMISS);
544 #endif /* __NetBSD__ */
545 
546 	switch (af) {
547 	case AF_INET: {
548 		struct inpcb *in4p = PCB_TO_IN4PCB(inp);
549 		/* set spidx in pcb */
550 		*error = ipsec4_setspidx_inpcb(m, in4p);
551 		pcbsp = in4p->inp_sp;
552 		break;
553 		}
554 
555 #if defined(INET6)
556 	case AF_INET6: {
557 		struct in6pcb *in6p = PCB_TO_IN6PCB(inp);
558 		/* set spidx in pcb */
559 		*error = ipsec6_setspidx_in6pcb(m, in6p);
560 		pcbsp = in6p->in6p_sp;
561 		break;
562 		}
563 #endif
564 	default:
565 		*error = EPFNOSUPPORT;
566 		break;
567 	}
568 	if (*error)
569 		return NULL;
570 
571 	IPSEC_ASSERT(pcbsp != NULL, ("ipsec_getpolicybysock: null pcbsp"));
572 	switch (dir) {
573 	case IPSEC_DIR_INBOUND:
574 		currsp = pcbsp->sp_in;
575 		break;
576 	case IPSEC_DIR_OUTBOUND:
577 		currsp = pcbsp->sp_out;
578 		break;
579 	}
580 	IPSEC_ASSERT(currsp != NULL, ("ipsec_getpolicybysock: null currsp"));
581 
582 	if (pcbsp->priv) {			/* when privilieged socket */
583 		switch (currsp->policy) {
584 		case IPSEC_POLICY_BYPASS:
585 		case IPSEC_POLICY_IPSEC:
586 			currsp->refcnt++;
587 			sp = currsp;
588 			break;
589 
590 		case IPSEC_POLICY_ENTRUST:
591 			/* look for a policy in SPD */
592 			sp = KEY_ALLOCSP(&currsp->spidx, dir);
593 			if (sp == NULL)		/* no SP found */
594 				sp = KEY_ALLOCSP_DEFAULT(af);
595 			break;
596 
597 		default:
598 			ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
599 				  "Invalid policy for PCB %d\n", currsp->policy));
600 			*error = EINVAL;
601 			return NULL;
602 		}
603 	} else {				/* unpriv, SPD has policy */
604 		sp = KEY_ALLOCSP(&currsp->spidx, dir);
605 		if (sp == NULL) {		/* no SP found */
606 			switch (currsp->policy) {
607 			case IPSEC_POLICY_BYPASS:
608 				ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
609 					   "Illegal policy for non-priviliged defined %d\n",
610 					currsp->policy));
611 				*error = EINVAL;
612 				return NULL;
613 
614 			case IPSEC_POLICY_ENTRUST:
615 				sp = KEY_ALLOCSP_DEFAULT(af);
616 				break;
617 
618 			case IPSEC_POLICY_IPSEC:
619 				currsp->refcnt++;
620 				sp = currsp;
621 				break;
622 
623 			default:
624 				ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
625 				   "Invalid policy for PCB %d\n", currsp->policy));
626 				*error = EINVAL;
627 				return NULL;
628 			}
629 		}
630 	}
631 	IPSEC_ASSERT(sp != NULL,
632 		("ipsec_getpolicybysock: null SP (priv %u policy %u",
633 		 pcbsp->priv, currsp->policy));
634 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
635 		printf("DP ipsec_getpolicybysock (priv %u policy %u) allocates "
636 			   "SP:%p (refcnt %u)\n", pcbsp->priv, currsp->policy,
637 			   sp, sp->refcnt));
638 #ifdef __NetBSD__
639 	ipsec_fillpcbcache(pcbsp, m, sp, dir);
640 #endif /* __NetBSD__ */
641 	return sp;
642 }
643 
644 /*
645  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
646  * and return a pointer to SP.
647  * OUT:	positive: a pointer to the entry for security policy leaf matched.
648  *	NULL:	no apropreate SP found, the following value is set to error.
649  *		0	: bypass
650  *		EACCES	: discard packet.
651  *		ENOENT	: ipsec_acquire() in progress, maybe.
652  *		others	: error occurred.
653  */
654 struct secpolicy *
655 ipsec_getpolicybyaddr(struct mbuf *m, u_int dir, int flag, int *error)
656 {
657 	struct secpolicyindex spidx;
658 	struct secpolicy *sp;
659 
660 	IPSEC_ASSERT(m != NULL, ("ipsec_getpolicybyaddr: null mbuf"));
661 	IPSEC_ASSERT(error != NULL, ("ipsec_getpolicybyaddr: null error"));
662 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
663 		("ipsec4_getpolicybaddr: invalid direction %u", dir));
664 
665 	sp = NULL;
666 
667 	/* Make an index to look for a policy. */
668 	*error = ipsec_setspidx(m, &spidx, (flag & IP_FORWARDING) ? 0 : 1);
669 	if (*error != 0) {
670 		DPRINTF(("ipsec_getpolicybyaddr: setpidx failed,"
671 			" dir %u flag %u\n", dir, flag));
672 		memset(&spidx, 0, sizeof (spidx));
673 		return NULL;
674 	}
675 
676 	spidx.dir = dir;
677 
678 	if (key_havesp(dir)) {
679 		sp = KEY_ALLOCSP(&spidx, dir);
680 	}
681 
682 	if (sp == NULL)			/* no SP found, use system default */
683 		sp = KEY_ALLOCSP_DEFAULT(spidx.dst.sa.sa_family);
684 	IPSEC_ASSERT(sp != NULL, ("ipsec_getpolicybyaddr: null SP"));
685 	return sp;
686 }
687 
688 struct secpolicy *
689 ipsec4_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
690 		   struct inpcb *inp)
691 {
692 	struct secpolicy *sp;
693 
694 	*error = 0;
695 
696 
697 	/* XXX KAME IPv6 calls us with non-null inp but bogus inp_socket? */
698 	if (inp == NULL || inp->inp_socket == NULL) {
699 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
700 	} else
701 		sp = ipsec_getpolicybysock(m, dir, IN4PCB_TO_PCB(inp), error);
702 	if (sp == NULL) {
703 		IPSEC_ASSERT(*error != 0,
704 			("ipsec4_checkpolicy: getpolicy failed w/o error"));
705 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
706 		return NULL;
707 	}
708 	IPSEC_ASSERT(*error == 0,
709 		("ipsec4_checkpolicy: sp w/ error set to %u", *error));
710 	switch (sp->policy) {
711 	case IPSEC_POLICY_ENTRUST:
712 	default:
713 		printf("ipsec4_checkpolicy: invalid policy %u\n", sp->policy);
714 		/* fall thru... */
715 	case IPSEC_POLICY_DISCARD:
716 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
717 		*error = -EINVAL;	/* packet is discarded by caller */
718 		break;
719 	case IPSEC_POLICY_BYPASS:
720 	case IPSEC_POLICY_NONE:
721 		KEY_FREESP(&sp);
722 		sp = NULL;		/* NB: force NULL result */
723 		break;
724 	case IPSEC_POLICY_IPSEC:
725 		if (sp->req == NULL)	/* acquire an SA */
726 			*error = key_spdacquire(sp);
727 		break;
728 	}
729 	if (*error != 0) {
730 		KEY_FREESP(&sp);
731 		sp = NULL;
732 		DPRINTF(("%s: done, error %d\n", __func__, *error));
733 	}
734 	return sp;
735 }
736 
737 int
738 ipsec4_output(struct mbuf *m, struct socket *so, int flags,
739     struct secpolicy **sp_out, u_long *mtu, bool *natt_frag, bool *done)
740 {
741 	const struct ip *ip = mtod(m, const struct ip *);
742 	struct secpolicy *sp = NULL;
743 	struct inpcb *inp;
744 	int error, s;
745 
746 	inp = (so && so->so_proto->pr_domain->dom_family == AF_INET) ?
747 	    (struct inpcb *)so->so_pcb : NULL;
748 
749 	/*
750 	 * Check the security policy (SP) for the packet and, if required,
751 	 * do IPsec-related processing.  There are two cases here; the first
752 	 * time a packet is sent through it will be untagged and handled by
753 	 * ipsec4_checkpolicy().  If the packet is resubmitted to ip_output
754 	 * (e.g. after AH, ESP, etc. processing), there will be a tag to
755 	 * bypass the lookup and related policy checking.
756 	 */
757 	if (ipsec_outdone(m)) {
758 		return 0;
759 	}
760 	s = splsoftnet();
761 	if (inp && IPSEC_PCB_SKIP_IPSEC(inp->inp_sp, IPSEC_DIR_OUTBOUND)) {
762 		splx(s);
763 		return 0;
764 	}
765 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, inp);
766 
767 	/*
768 	 * There are four return cases:
769 	 *	sp != NULL			apply IPsec policy
770 	 *	sp == NULL, error == 0		no IPsec handling needed
771 	 *	sp == NULL, error == -EINVAL	discard packet w/o error
772 	 *	sp == NULL, error != 0		discard packet, report error
773 	 */
774 	if (sp == NULL) {
775 		splx(s);
776 		if (error) {
777 			/*
778 			 * Hack: -EINVAL is used to signal that a packet
779 			 * should be silently discarded.  This is typically
780 			 * because we asked key management for an SA and
781 			 * it was delayed (e.g. kicked up to IKE).
782 			 */
783 			if (error == -EINVAL)
784 				error = 0;
785 			m_freem(m);
786 			*done = true;
787 			return error;
788 		}
789 		/* No IPsec processing for this packet. */
790 		return 0;
791 	}
792 	*sp_out = sp;
793 
794 	/*
795 	 * NAT-T ESP fragmentation: do not do IPSec processing now,
796 	 * we will do it on each fragmented packet.
797 	 */
798 	if (sp->req->sav && (sp->req->sav->natt_type &
799 	    (UDP_ENCAP_ESPINUDP|UDP_ENCAP_ESPINUDP_NON_IKE))) {
800 		if (ntohs(ip->ip_len) > sp->req->sav->esp_frag) {
801 			*mtu = sp->req->sav->esp_frag;
802 			*natt_frag = true;
803 			splx(s);
804 			return 0;
805 		}
806 	}
807 
808 	/*
809 	 * Do delayed checksums now because we send before
810 	 * this is done in the normal processing path.
811 	 */
812 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
813 		in_delayed_cksum(m);
814 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
815 	}
816 
817 	/* Note: callee frees mbuf */
818 	error = ipsec4_process_packet(m, sp->req, flags, 0);
819 	/*
820 	 * Preserve KAME behaviour: ENOENT can be returned
821 	 * when an SA acquire is in progress.  Don't propagate
822 	 * this to user-level; it confuses applications.
823 	 *
824 	 * XXX this will go away when the SADB is redone.
825 	 */
826 	if (error == ENOENT)
827 		error = 0;
828 	splx(s);
829 	*done = true;
830 	return error;
831 }
832 
833 int
834 ipsec4_input(struct mbuf *m, int flags)
835 {
836 	struct m_tag *mtag;
837 	struct tdb_ident *tdbi;
838 	struct secpolicy *sp;
839 	int error, s;
840 
841 	/*
842 	 * Check if the packet has already had IPsec processing done.
843 	 * If so, then just pass it along.  This tag gets set during AH,
844 	 * ESP, etc. input handling, before the packet is returned to
845 	 * the IP input queue for delivery.
846 	 */
847 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
848 	s = splsoftnet();
849 	if (mtag != NULL) {
850 		tdbi = (struct tdb_ident *)(mtag + 1);
851 		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
852 	} else {
853 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
854 		    IP_FORWARDING, &error);
855 	}
856 	if (sp == NULL) {
857 		splx(s);
858 		return EINVAL;
859 	}
860 
861 	/*
862 	 * Check security policy against packet attributes.
863 	 */
864 	error = ipsec_in_reject(sp, m);
865 	KEY_FREESP(&sp);
866 	splx(s);
867 	if (error) {
868 		return error;
869 	}
870 
871 	if (flags == 0) {
872 		/* We are done. */
873 		return 0;
874 	}
875 
876 	/*
877 	 * Peek at the outbound SP for this packet to determine if
878 	 * it is a Fast Forward candidate.
879 	 */
880 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
881 	if (mtag != NULL) {
882 		m->m_flags &= ~M_CANFASTFWD;
883 		return 0;
884 	}
885 
886 	s = splsoftnet();
887 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, NULL);
888 	if (sp != NULL) {
889 		m->m_flags &= ~M_CANFASTFWD;
890 		KEY_FREESP(&sp);
891 	}
892 	splx(s);
893 	return 0;
894 }
895 
896 int
897 ipsec4_forward(struct mbuf *m, int *destmtu)
898 {
899 	/*
900 	 * If the packet is routed over IPsec tunnel, tell the
901 	 * originator the tunnel MTU.
902 	 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
903 	 * XXX quickhack!!!
904 	 */
905 	struct secpolicy *sp;
906 	size_t ipsechdr;
907 	int error;
908 
909 	sp = ipsec4_getpolicybyaddr(m,
910 	    IPSEC_DIR_OUTBOUND, IP_FORWARDING, &error);
911 	if (sp == NULL) {
912 		return EINVAL;
913 	}
914 
915 	/* Count IPsec header size. */
916 	ipsechdr = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, NULL);
917 
918 	/*
919 	 * Find the correct route for outer IPv4 header, compute tunnel MTU.
920 	 */
921 	if (sp->req && sp->req->sav && sp->req->sav->sah) {
922 		struct route *ro;
923 		struct rtentry *rt;
924 
925 		ro = &sp->req->sav->sah->sa_route;
926 		rt = rtcache_validate(ro);
927 		if (rt && rt->rt_ifp) {
928 			*destmtu = rt->rt_rmx.rmx_mtu ?
929 			    rt->rt_rmx.rmx_mtu : rt->rt_ifp->if_mtu;
930 			*destmtu -= ipsechdr;
931 		}
932 	}
933 	KEY_FREESP(&sp);
934 	return 0;
935 }
936 
937 #ifdef INET6
938 struct secpolicy *
939 ipsec6_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
940 	 	   struct in6pcb *in6p)
941 {
942 	struct secpolicy *sp;
943 
944 	*error = 0;
945 
946 
947 	/* XXX KAME IPv6 calls us with non-null inp but bogus inp_socket? */
948 	if (in6p == NULL || in6p->in6p_socket == NULL) {
949 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
950 	} else
951 		sp = ipsec_getpolicybysock(m, dir, IN6PCB_TO_PCB(in6p), error);
952 	if (sp == NULL) {
953 		IPSEC_ASSERT(*error != 0,
954 			("ipsec6_checkpolicy: getpolicy failed w/o error"));
955 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
956 		return NULL;
957 	}
958 	IPSEC_ASSERT(*error == 0,
959 		("ipsec6_checkpolicy: sp w/ error set to %u", *error));
960 	switch (sp->policy) {
961 	case IPSEC_POLICY_ENTRUST:
962 	default:
963 		printf("ipsec6_checkpolicy: invalid policy %u\n", sp->policy);
964 		/* fall thru... */
965 	case IPSEC_POLICY_DISCARD:
966 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
967 		*error = -EINVAL;   /* packet is discarded by caller */
968 		break;
969 	case IPSEC_POLICY_BYPASS:
970 	case IPSEC_POLICY_NONE:
971 		KEY_FREESP(&sp);
972 		sp = NULL;	  /* NB: force NULL result */
973 		break;
974 	case IPSEC_POLICY_IPSEC:
975 		if (sp->req == NULL)	/* acquire an SA */
976 			*error = key_spdacquire(sp);
977 		break;
978 	}
979 	if (*error != 0) {
980 		KEY_FREESP(&sp);
981 		sp = NULL;
982 		DPRINTF(("%s: done, error %d\n", __func__, *error));
983 	}
984 	return sp;
985 }
986 #endif /* INET6 */
987 
988 static int
989 ipsec4_setspidx_inpcb(struct mbuf *m, struct inpcb *pcb)
990 {
991 	int error;
992 
993 	IPSEC_ASSERT(pcb != NULL, ("ipsec4_setspidx_inpcb: null pcb"));
994 	IPSEC_ASSERT(pcb->inp_sp != NULL, ("ipsec4_setspidx_inpcb: null inp_sp"));
995 	IPSEC_ASSERT(pcb->inp_sp->sp_out != NULL && pcb->inp_sp->sp_in != NULL,
996 		("ipsec4_setspidx_inpcb: null sp_in || sp_out"));
997 
998 	error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
999 	if (error == 0) {
1000 		pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
1001 		pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
1002 		pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
1003 	} else {
1004 		memset(&pcb->inp_sp->sp_in->spidx, 0,
1005 			sizeof (pcb->inp_sp->sp_in->spidx));
1006 		memset(&pcb->inp_sp->sp_out->spidx, 0,
1007 			sizeof (pcb->inp_sp->sp_in->spidx));
1008 	}
1009 	return error;
1010 }
1011 
1012 #ifdef INET6
1013 static int
1014 ipsec6_setspidx_in6pcb(struct mbuf *m, struct in6pcb *pcb)
1015 {
1016 	struct secpolicyindex *spidx;
1017 	int error;
1018 
1019 	IPSEC_ASSERT(pcb != NULL, ("ipsec6_setspidx_in6pcb: null pcb"));
1020 	IPSEC_ASSERT(pcb->in6p_sp != NULL, ("ipsec6_setspidx_in6pcb: null inp_sp"));
1021 	IPSEC_ASSERT(pcb->in6p_sp->sp_out != NULL && pcb->in6p_sp->sp_in != NULL,
1022 		("ipsec6_setspidx_in6pcb: null sp_in || sp_out"));
1023 
1024 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
1025 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
1026 
1027 	spidx = &pcb->in6p_sp->sp_in->spidx;
1028 	error = ipsec_setspidx(m, spidx, 1);
1029 	if (error)
1030 		goto bad;
1031 	spidx->dir = IPSEC_DIR_INBOUND;
1032 
1033 	spidx = &pcb->in6p_sp->sp_out->spidx;
1034 	error = ipsec_setspidx(m, spidx, 1);
1035 	if (error)
1036 		goto bad;
1037 	spidx->dir = IPSEC_DIR_OUTBOUND;
1038 
1039 	return 0;
1040 
1041 bad:
1042 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
1043 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
1044 	return error;
1045 }
1046 #endif
1047 
1048 /*
1049  * configure security policy index (src/dst/proto/sport/dport)
1050  * by looking at the content of mbuf.
1051  * the caller is responsible for error recovery (like clearing up spidx).
1052  */
1053 static int
1054 ipsec_setspidx(struct mbuf *m, struct secpolicyindex *spidx, int needport)
1055 {
1056 	struct ip *ip = NULL;
1057 	struct ip ipbuf;
1058 	u_int v;
1059 	struct mbuf *n;
1060 	int len;
1061 	int error;
1062 
1063 	IPSEC_ASSERT(m != NULL, ("ipsec_setspidx: null mbuf"));
1064 
1065 	/*
1066 	 * validate m->m_pkthdr.len.  we see incorrect length if we
1067 	 * mistakenly call this function with inconsistent mbuf chain
1068 	 * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
1069 	 */
1070 	len = 0;
1071 	for (n = m; n; n = n->m_next)
1072 		len += n->m_len;
1073 	if (m->m_pkthdr.len != len) {
1074 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1075 			printf("ipsec_setspidx: "
1076 				   "total of m_len(%d) != pkthdr.len(%d), "
1077 				   "ignored.\n",
1078 				len, m->m_pkthdr.len));
1079 		return EINVAL;
1080 	}
1081 
1082 	if (m->m_pkthdr.len < sizeof(struct ip)) {
1083 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1084 			printf("ipsec_setspidx: "
1085 				"pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
1086 				m->m_pkthdr.len));
1087 		return EINVAL;
1088 	}
1089 
1090 	if (m->m_len >= sizeof(*ip))
1091 		ip = mtod(m, struct ip *);
1092 	else {
1093 		m_copydata(m, 0, sizeof(ipbuf), &ipbuf);
1094 		ip = &ipbuf;
1095 	}
1096 	v = ip->ip_v;
1097 	switch (v) {
1098 	case 4:
1099 		error = ipsec4_setspidx_ipaddr(m, spidx);
1100 		if (error)
1101 			return error;
1102 		ipsec4_get_ulp(m, spidx, needport);
1103 		return 0;
1104 #ifdef INET6
1105 	case 6:
1106 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
1107 			KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1108 				printf("ipsec_setspidx: "
1109 					"pkthdr.len(%d) < sizeof(struct ip6_hdr), "
1110 					"ignored.\n", m->m_pkthdr.len));
1111 			return EINVAL;
1112 		}
1113 		error = ipsec6_setspidx_ipaddr(m, spidx);
1114 		if (error)
1115 			return error;
1116 		ipsec6_get_ulp(m, spidx, needport);
1117 		return 0;
1118 #endif
1119 	default:
1120 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1121 			printf("ipsec_setspidx: "
1122 				"unknown IP version %u, ignored.\n", v));
1123 		return EINVAL;
1124 	}
1125 }
1126 
1127 static void
1128 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
1129 {
1130 	u_int8_t nxt;
1131 	int off;
1132 
1133 	/* sanity check */
1134 	IPSEC_ASSERT(m != NULL, ("ipsec4_get_ulp: null mbuf"));
1135 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
1136 		("ipsec4_get_ulp: packet too short"));
1137 
1138 	/* NB: ip_input() flips it into host endian XXX need more checking */
1139 	if (m->m_len >= sizeof(struct ip)) {
1140 		struct ip *ip = mtod(m, struct ip *);
1141 		if (ip->ip_off & IP_OFF_CONVERT(IP_MF | IP_OFFMASK))
1142 			goto done;
1143 		off = ip->ip_hl << 2;
1144 		nxt = ip->ip_p;
1145 	} else {
1146 		struct ip ih;
1147 
1148 		m_copydata(m, 0, sizeof (struct ip), &ih);
1149 		if (ih.ip_off & IP_OFF_CONVERT(IP_MF | IP_OFFMASK))
1150 			goto done;
1151 		off = ih.ip_hl << 2;
1152 		nxt = ih.ip_p;
1153 	}
1154 
1155 	while (off < m->m_pkthdr.len) {
1156 		struct ip6_ext ip6e;
1157 		struct tcphdr th;
1158 		struct udphdr uh;
1159 		struct icmp icmph;
1160 
1161 		switch (nxt) {
1162 		case IPPROTO_TCP:
1163 			spidx->ul_proto = nxt;
1164 			if (!needport)
1165 				goto done_proto;
1166 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
1167 				goto done;
1168 			m_copydata(m, off, sizeof (th), &th);
1169 			spidx->src.sin.sin_port = th.th_sport;
1170 			spidx->dst.sin.sin_port = th.th_dport;
1171 			return;
1172 		case IPPROTO_UDP:
1173 			spidx->ul_proto = nxt;
1174 			if (!needport)
1175 				goto done_proto;
1176 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
1177 				goto done;
1178 			m_copydata(m, off, sizeof (uh), &uh);
1179 			spidx->src.sin.sin_port = uh.uh_sport;
1180 			spidx->dst.sin.sin_port = uh.uh_dport;
1181 			return;
1182 		case IPPROTO_AH:
1183 			if (m->m_pkthdr.len > off + sizeof(ip6e))
1184 				goto done;
1185 			/* XXX sigh, this works but is totally bogus */
1186 			m_copydata(m, off, sizeof(ip6e), &ip6e);
1187 			off += (ip6e.ip6e_len + 2) << 2;
1188 			nxt = ip6e.ip6e_nxt;
1189 			break;
1190 		case IPPROTO_ICMP:
1191 			spidx->ul_proto = nxt;
1192 			if (off + sizeof(struct icmp) > m->m_pkthdr.len)
1193 				return;
1194 			m_copydata(m, off, sizeof(icmph), &icmph);
1195 			((struct sockaddr_in *)&spidx->src)->sin_port =
1196 			    htons((uint16_t)icmph.icmp_type);
1197 			((struct sockaddr_in *)&spidx->dst)->sin_port =
1198 			    htons((uint16_t)icmph.icmp_code);
1199 			return;
1200 		default:
1201 			/* XXX intermediate headers??? */
1202 			spidx->ul_proto = nxt;
1203 			goto done_proto;
1204 		}
1205 	}
1206 done:
1207 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
1208 done_proto:
1209 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
1210 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
1211 }
1212 
1213 /* assumes that m is sane */
1214 static int
1215 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
1216 {
1217 	static const struct sockaddr_in template = {
1218 		sizeof (struct sockaddr_in),
1219 		AF_INET,
1220 		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
1221 	};
1222 
1223 	spidx->src.sin = template;
1224 	spidx->dst.sin = template;
1225 
1226 	if (m->m_len < sizeof (struct ip)) {
1227 		m_copydata(m, offsetof(struct ip, ip_src),
1228 			   sizeof (struct  in_addr),
1229 			   &spidx->src.sin.sin_addr);
1230 		m_copydata(m, offsetof(struct ip, ip_dst),
1231 			   sizeof (struct  in_addr),
1232 			   &spidx->dst.sin.sin_addr);
1233 	} else {
1234 		struct ip *ip = mtod(m, struct ip *);
1235 		spidx->src.sin.sin_addr = ip->ip_src;
1236 		spidx->dst.sin.sin_addr = ip->ip_dst;
1237 	}
1238 
1239 	spidx->prefs = sizeof(struct in_addr) << 3;
1240 	spidx->prefd = sizeof(struct in_addr) << 3;
1241 
1242 	return 0;
1243 }
1244 
1245 #ifdef INET6
1246 static void
1247 ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *spidx,
1248 	       int needport)
1249 {
1250 	int off, nxt;
1251 	struct tcphdr th;
1252 	struct udphdr uh;
1253 	struct icmp6_hdr icmph;
1254 
1255 	/* sanity check */
1256 	if (m == NULL)
1257 		panic("ipsec6_get_ulp: NULL pointer was passed");
1258 
1259 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1260 		printf("ipsec6_get_ulp:\n"); kdebug_mbuf(m));
1261 
1262 	/* set default */
1263 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
1264 	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
1265 	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
1266 
1267 	nxt = -1;
1268 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
1269 	if (off < 0 || m->m_pkthdr.len < off)
1270 		return;
1271 
1272 	switch (nxt) {
1273 	case IPPROTO_TCP:
1274 		spidx->ul_proto = nxt;
1275 		if (!needport)
1276 			break;
1277 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
1278 			break;
1279 		m_copydata(m, off, sizeof(th), &th);
1280 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
1281 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
1282 		break;
1283 	case IPPROTO_UDP:
1284 		spidx->ul_proto = nxt;
1285 		if (!needport)
1286 			break;
1287 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
1288 			break;
1289 		m_copydata(m, off, sizeof(uh), &uh);
1290 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
1291 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
1292 		break;
1293 	case IPPROTO_ICMPV6:
1294 		spidx->ul_proto = nxt;
1295 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
1296 			break;
1297 		m_copydata(m, off, sizeof(icmph), &icmph);
1298 		((struct sockaddr_in6 *)&spidx->src)->sin6_port =
1299 		    htons((uint16_t)icmph.icmp6_type);
1300 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
1301 		    htons((uint16_t)icmph.icmp6_code);
1302 		break;
1303 	default:
1304 		/* XXX intermediate headers??? */
1305 		spidx->ul_proto = nxt;
1306 		break;
1307 	}
1308 }
1309 
1310 /* assumes that m is sane */
1311 static int
1312 ipsec6_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
1313 {
1314 	struct ip6_hdr *ip6 = NULL;
1315 	struct ip6_hdr ip6buf;
1316 	struct sockaddr_in6 *sin6;
1317 
1318 	if (m->m_len >= sizeof(*ip6))
1319 		ip6 = mtod(m, struct ip6_hdr *);
1320 	else {
1321 		m_copydata(m, 0, sizeof(ip6buf), &ip6buf);
1322 		ip6 = &ip6buf;
1323 	}
1324 
1325 	sin6 = (struct sockaddr_in6 *)&spidx->src;
1326 	memset(sin6, 0, sizeof(*sin6));
1327 	sin6->sin6_family = AF_INET6;
1328 	sin6->sin6_len = sizeof(struct sockaddr_in6);
1329 	memcpy(&sin6->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));
1330 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
1331 		sin6->sin6_addr.s6_addr16[1] = 0;
1332 		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
1333 	}
1334 	spidx->prefs = sizeof(struct in6_addr) << 3;
1335 
1336 	sin6 = (struct sockaddr_in6 *)&spidx->dst;
1337 	memset(sin6, 0, sizeof(*sin6));
1338 	sin6->sin6_family = AF_INET6;
1339 	sin6->sin6_len = sizeof(struct sockaddr_in6);
1340 	memcpy(&sin6->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
1341 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
1342 		sin6->sin6_addr.s6_addr16[1] = 0;
1343 		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
1344 	}
1345 	spidx->prefd = sizeof(struct in6_addr) << 3;
1346 
1347 	return 0;
1348 }
1349 #endif
1350 
1351 static void
1352 ipsec_delpcbpolicy(struct inpcbpolicy *p)
1353 {
1354 	free(p, M_SECA);
1355 }
1356 
1357 /* initialize policy in PCB */
1358 int
1359 ipsec_init_policy(struct socket *so, struct inpcbpolicy **policy)
1360 {
1361 	struct inpcbpolicy *new;
1362 
1363 	/* sanity check. */
1364 	if (so == NULL || policy == NULL)
1365 		panic("ipsec_init_policy: NULL pointer was passed");
1366 
1367 	new = malloc(sizeof(*new), M_SECA, M_NOWAIT|M_ZERO);
1368 	if (new == NULL) {
1369 		ipseclog((LOG_DEBUG, "ipsec_init_policy: No more memory.\n"));
1370 		return ENOBUFS;
1371 	}
1372 
1373 	if (IPSEC_PRIVILEGED_SO(so))
1374 		new->priv = 1;
1375 	else
1376 		new->priv = 0;
1377 
1378 	if ((new->sp_in = KEY_NEWSP()) == NULL) {
1379 		ipsec_delpcbpolicy(new);
1380 		return ENOBUFS;
1381 	}
1382 	new->sp_in->state = IPSEC_SPSTATE_ALIVE;
1383 	new->sp_in->policy = IPSEC_POLICY_ENTRUST;
1384 
1385 	if ((new->sp_out = KEY_NEWSP()) == NULL) {
1386 		KEY_FREESP(&new->sp_in);
1387 		ipsec_delpcbpolicy(new);
1388 		return ENOBUFS;
1389 	}
1390 	new->sp_out->state = IPSEC_SPSTATE_ALIVE;
1391 	new->sp_out->policy = IPSEC_POLICY_ENTRUST;
1392 
1393 	*policy = new;
1394 
1395 	return 0;
1396 }
1397 
1398 /* copy old ipsec policy into new */
1399 int
1400 ipsec_copy_policy(const struct inpcbpolicy *old, struct inpcbpolicy *new)
1401 {
1402 	struct secpolicy *sp;
1403 
1404 	sp = ipsec_deepcopy_policy(old->sp_in);
1405 	if (sp) {
1406 		KEY_FREESP(&new->sp_in);
1407 		new->sp_in = sp;
1408 	} else
1409 		return ENOBUFS;
1410 
1411 	sp = ipsec_deepcopy_policy(old->sp_out);
1412 	if (sp) {
1413 		KEY_FREESP(&new->sp_out);
1414 		new->sp_out = sp;
1415 	} else
1416 		return ENOBUFS;
1417 
1418 	new->priv = old->priv;
1419 
1420 	return 0;
1421 }
1422 
1423 /* deep-copy a policy in PCB */
1424 static struct secpolicy *
1425 ipsec_deepcopy_policy(const struct secpolicy *src)
1426 {
1427 	struct ipsecrequest *newchain = NULL;
1428 	const struct ipsecrequest *p;
1429 	struct ipsecrequest **q;
1430 	struct ipsecrequest *r;
1431 	struct secpolicy *dst;
1432 
1433 	if (src == NULL)
1434 		return NULL;
1435 	dst = KEY_NEWSP();
1436 	if (dst == NULL)
1437 		return NULL;
1438 
1439 	/*
1440 	 * deep-copy IPsec request chain.  This is required since struct
1441 	 * ipsecrequest is not reference counted.
1442 	 */
1443 	q = &newchain;
1444 	for (p = src->req; p; p = p->next) {
1445 		*q = malloc(sizeof(**q), M_SECA, M_NOWAIT|M_ZERO);
1446 		if (*q == NULL)
1447 			goto fail;
1448 		(*q)->next = NULL;
1449 
1450 		(*q)->saidx.proto = p->saidx.proto;
1451 		(*q)->saidx.mode = p->saidx.mode;
1452 		(*q)->level = p->level;
1453 		(*q)->saidx.reqid = p->saidx.reqid;
1454 
1455 		memcpy(&(*q)->saidx.src, &p->saidx.src, sizeof((*q)->saidx.src));
1456 		memcpy(&(*q)->saidx.dst, &p->saidx.dst, sizeof((*q)->saidx.dst));
1457 
1458 		(*q)->sav = NULL;
1459 		(*q)->sp = dst;
1460 
1461 		q = &((*q)->next);
1462 	}
1463 
1464 	dst->req = newchain;
1465 	dst->state = src->state;
1466 	dst->policy = src->policy;
1467 	/* do not touch the refcnt fields */
1468 
1469 	return dst;
1470 
1471 fail:
1472 	for (q = &newchain; *q; q = &r) {
1473 		r = (*q)->next;
1474 		free(*q, M_SECA);
1475 	}
1476 	return NULL;
1477 }
1478 
1479 /* set policy and ipsec request if present. */
1480 static int
1481 ipsec_set_policy(
1482 	struct secpolicy **policy,
1483 	int optname,
1484 	const void *request,
1485 	size_t len,
1486 	kauth_cred_t cred
1487 )
1488 {
1489 	const struct sadb_x_policy *xpl;
1490 	struct secpolicy *newsp = NULL;
1491 	int error;
1492 
1493 	/* sanity check. */
1494 	if (policy == NULL || *policy == NULL || request == NULL)
1495 		return EINVAL;
1496 	if (len < sizeof(*xpl))
1497 		return EINVAL;
1498 	xpl = (const struct sadb_x_policy *)request;
1499 
1500 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1501 		printf("ipsec_set_policy: passed policy\n");
1502 		kdebug_sadb_x_policy((const struct sadb_ext *)xpl));
1503 
1504 	/* check policy type */
1505 	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
1506 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
1507 	 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
1508 		return EINVAL;
1509 
1510 	/* check privileged socket */
1511 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1512 		error = kauth_authorize_network(cred, KAUTH_NETWORK_IPSEC,
1513 		    KAUTH_REQ_NETWORK_IPSEC_BYPASS, NULL, NULL, NULL);
1514 		if (error)
1515 			return (error);
1516 	}
1517 
1518 	/* allocation new SP entry */
1519 	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
1520 		return error;
1521 
1522 	newsp->state = IPSEC_SPSTATE_ALIVE;
1523 
1524 	/* clear old SP and set new SP */
1525 	KEY_FREESP(policy);
1526 	*policy = newsp;
1527 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1528 		printf("ipsec_set_policy: new policy\n");
1529 		kdebug_secpolicy(newsp));
1530 
1531 	return 0;
1532 }
1533 
1534 static int
1535 ipsec_get_policy(struct secpolicy *policy, struct mbuf **mp)
1536 {
1537 
1538 	/* sanity check. */
1539 	if (policy == NULL || mp == NULL)
1540 		return EINVAL;
1541 
1542 	*mp = key_sp2msg(policy);
1543 	if (!*mp) {
1544 		ipseclog((LOG_DEBUG, "ipsec_get_policy: No more memory.\n"));
1545 		return ENOBUFS;
1546 	}
1547 
1548 	(*mp)->m_type = MT_DATA;
1549 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1550 		printf("ipsec_get_policy:\n");
1551 		kdebug_mbuf(*mp));
1552 
1553 	return 0;
1554 }
1555 
1556 int
1557 ipsec4_set_policy(struct inpcb *inp, int optname, const void *request,
1558 		  size_t len, kauth_cred_t cred)
1559 {
1560 	const struct sadb_x_policy *xpl;
1561 	struct secpolicy **policy;
1562 
1563 	/* sanity check. */
1564 	if (inp == NULL || request == NULL)
1565 		return EINVAL;
1566 	if (len < sizeof(*xpl))
1567 		return EINVAL;
1568 	xpl = (const struct sadb_x_policy *)request;
1569 
1570 	IPSEC_ASSERT(inp->inp_sp != NULL,
1571 			 ("ipsec4_set_policy(): null inp->in_sp"));
1572 
1573 	/* select direction */
1574 	switch (xpl->sadb_x_policy_dir) {
1575 	case IPSEC_DIR_INBOUND:
1576 		policy = &inp->inp_sp->sp_in;
1577 		break;
1578 	case IPSEC_DIR_OUTBOUND:
1579 		policy = &inp->inp_sp->sp_out;
1580 		break;
1581 	default:
1582 		ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
1583 			xpl->sadb_x_policy_dir));
1584 		return EINVAL;
1585 	}
1586 
1587 	return ipsec_set_policy(policy, optname, request, len, cred);
1588 }
1589 
1590 int
1591 ipsec4_get_policy(struct inpcb *inp, const void *request, size_t len,
1592 		  struct mbuf **mp)
1593 {
1594 	const struct sadb_x_policy *xpl;
1595 	struct secpolicy *policy;
1596 
1597 	/* sanity check. */
1598 	if (inp == NULL || request == NULL || mp == NULL)
1599 		return EINVAL;
1600 	IPSEC_ASSERT(inp->inp_sp != NULL, ("ipsec4_get_policy: null inp_sp"));
1601 	if (len < sizeof(*xpl))
1602 		return EINVAL;
1603 	xpl = (const struct sadb_x_policy *)request;
1604 
1605 	/* select direction */
1606 	switch (xpl->sadb_x_policy_dir) {
1607 	case IPSEC_DIR_INBOUND:
1608 		policy = inp->inp_sp->sp_in;
1609 		break;
1610 	case IPSEC_DIR_OUTBOUND:
1611 		policy = inp->inp_sp->sp_out;
1612 		break;
1613 	default:
1614 		ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
1615 			xpl->sadb_x_policy_dir));
1616 		return EINVAL;
1617 	}
1618 
1619 	return ipsec_get_policy(policy, mp);
1620 }
1621 
1622 /* delete policy in PCB */
1623 int
1624 ipsec4_delete_pcbpolicy(struct inpcb *inp)
1625 {
1626 	IPSEC_ASSERT(inp != NULL, ("ipsec4_delete_pcbpolicy: null inp"));
1627 
1628 	if (inp->inp_sp == NULL)
1629 		return 0;
1630 
1631 	if (inp->inp_sp->sp_in != NULL)
1632 		KEY_FREESP(&inp->inp_sp->sp_in);
1633 
1634 	if (inp->inp_sp->sp_out != NULL)
1635 		KEY_FREESP(&inp->inp_sp->sp_out);
1636 
1637 #ifdef __NetBSD__
1638 	ipsec_invalpcbcache(inp->inp_sp, IPSEC_DIR_ANY);
1639 #endif
1640 
1641 	ipsec_delpcbpolicy(inp->inp_sp);
1642 	inp->inp_sp = NULL;
1643 
1644 	return 0;
1645 }
1646 
1647 #ifdef INET6
1648 int
1649 ipsec6_set_policy(struct in6pcb *in6p, int optname, const void *request,
1650 		  size_t len, kauth_cred_t cred)
1651 {
1652 	const struct sadb_x_policy *xpl;
1653 	struct secpolicy **policy;
1654 
1655 	/* sanity check. */
1656 	if (in6p == NULL || request == NULL)
1657 		return EINVAL;
1658 	if (len < sizeof(*xpl))
1659 		return EINVAL;
1660 	xpl = (const struct sadb_x_policy *)request;
1661 
1662 	/* select direction */
1663 	switch (xpl->sadb_x_policy_dir) {
1664 	case IPSEC_DIR_INBOUND:
1665 		policy = &in6p->in6p_sp->sp_in;
1666 		break;
1667 	case IPSEC_DIR_OUTBOUND:
1668 		policy = &in6p->in6p_sp->sp_out;
1669 		break;
1670 	default:
1671 		ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
1672 			xpl->sadb_x_policy_dir));
1673 		return EINVAL;
1674 	}
1675 
1676 	return ipsec_set_policy(policy, optname, request, len, cred);
1677 }
1678 
1679 int
1680 ipsec6_get_policy(struct in6pcb *in6p, const void *request, size_t len,
1681 		  struct mbuf **mp)
1682 {
1683 	const struct sadb_x_policy *xpl;
1684 	struct secpolicy *policy;
1685 
1686 	/* sanity check. */
1687 	if (in6p == NULL || request == NULL || mp == NULL)
1688 		return EINVAL;
1689 	IPSEC_ASSERT(in6p->in6p_sp != NULL, ("ipsec6_get_policy: null in6p_sp"));
1690 	if (len < sizeof(*xpl))
1691 		return EINVAL;
1692 	xpl = (const struct sadb_x_policy *)request;
1693 
1694 	/* select direction */
1695 	switch (xpl->sadb_x_policy_dir) {
1696 	case IPSEC_DIR_INBOUND:
1697 		policy = in6p->in6p_sp->sp_in;
1698 		break;
1699 	case IPSEC_DIR_OUTBOUND:
1700 		policy = in6p->in6p_sp->sp_out;
1701 		break;
1702 	default:
1703 		ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
1704 			xpl->sadb_x_policy_dir));
1705 		return EINVAL;
1706 	}
1707 
1708 	return ipsec_get_policy(policy, mp);
1709 }
1710 
1711 int
1712 ipsec6_delete_pcbpolicy(struct in6pcb *in6p)
1713 {
1714 	IPSEC_ASSERT(in6p != NULL, ("ipsec6_delete_pcbpolicy: null in6p"));
1715 
1716 	if (in6p->in6p_sp == NULL)
1717 		return 0;
1718 
1719 	if (in6p->in6p_sp->sp_in != NULL)
1720 		KEY_FREESP(&in6p->in6p_sp->sp_in);
1721 
1722 	if (in6p->in6p_sp->sp_out != NULL)
1723 		KEY_FREESP(&in6p->in6p_sp->sp_out);
1724 
1725 #ifdef __NetBSD
1726 	ipsec_invalpcbcache(in6p->in6p_sp, IPSEC_DIR_ANY);
1727 #endif
1728 
1729 	ipsec_delpcbpolicy(in6p->in6p_sp);
1730 	in6p->in6p_sp = NULL;
1731 
1732 	return 0;
1733 }
1734 #endif
1735 
1736 /*
1737  * return current level.
1738  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
1739  */
1740 u_int
1741 ipsec_get_reqlevel(const struct ipsecrequest *isr)
1742 {
1743 	u_int level = 0;
1744 	u_int esp_trans_deflev, esp_net_deflev;
1745 	u_int ah_trans_deflev, ah_net_deflev;
1746 
1747 	IPSEC_ASSERT(isr != NULL && isr->sp != NULL,
1748 		("ipsec_get_reqlevel: null argument"));
1749 	IPSEC_ASSERT(isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
1750 		("ipsec_get_reqlevel: af family mismatch, src %u, dst %u",
1751 		 isr->sp->spidx.src.sa.sa_family,
1752 		 isr->sp->spidx.dst.sa.sa_family));
1753 
1754 /* XXX note that we have ipseclog() expanded here - code sync issue */
1755 #define IPSEC_CHECK_DEFAULT(lev) \
1756 	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE		  \
1757 			&& (lev) != IPSEC_LEVEL_UNIQUE)				  \
1758 		? (ipsec_debug							  \
1759 			? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
1760 				(lev), IPSEC_LEVEL_REQUIRE)			  \
1761 			: 0),							  \
1762 			(lev) = IPSEC_LEVEL_REQUIRE,				  \
1763 			(lev)							  \
1764 		: (lev))
1765 
1766 	/* set default level */
1767 	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
1768 #ifdef INET
1769 	case AF_INET:
1770 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
1771 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
1772 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
1773 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
1774 		break;
1775 #endif
1776 #ifdef INET6
1777 	case AF_INET6:
1778 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
1779 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
1780 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
1781 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
1782 		break;
1783 #endif /* INET6 */
1784 	default:
1785 		panic("key_get_reqlevel: unknown af %u",
1786 			isr->sp->spidx.src.sa.sa_family);
1787 	}
1788 
1789 #undef IPSEC_CHECK_DEFAULT
1790 
1791 	/* set level */
1792 	switch (isr->level) {
1793 	case IPSEC_LEVEL_DEFAULT:
1794 		switch (isr->saidx.proto) {
1795 		case IPPROTO_ESP:
1796 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1797 				level = esp_net_deflev;
1798 			else
1799 				level = esp_trans_deflev;
1800 			break;
1801 		case IPPROTO_AH:
1802 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1803 				level = ah_net_deflev;
1804 			else
1805 				level = ah_trans_deflev;
1806 			break;
1807 		case IPPROTO_IPCOMP:
1808 			/*
1809 			 * we don't really care, as IPcomp document says that
1810 			 * we shouldn't compress small packets
1811 			 */
1812 			level = IPSEC_LEVEL_USE;
1813 			break;
1814 		default:
1815 			panic("ipsec_get_reqlevel: Illegal protocol defined %u",
1816 				isr->saidx.proto);
1817 		}
1818 		break;
1819 
1820 	case IPSEC_LEVEL_USE:
1821 	case IPSEC_LEVEL_REQUIRE:
1822 		level = isr->level;
1823 		break;
1824 	case IPSEC_LEVEL_UNIQUE:
1825 		level = IPSEC_LEVEL_REQUIRE;
1826 		break;
1827 
1828 	default:
1829 		panic("ipsec_get_reqlevel: Illegal IPsec level %u",
1830 			isr->level);
1831 	}
1832 
1833 	return level;
1834 }
1835 
1836 /*
1837  * Check security policy requirements against the actual
1838  * packet contents.  Return one if the packet should be
1839  * reject as "invalid"; otherwiser return zero to have the
1840  * packet treated as "valid".
1841  *
1842  * OUT:
1843  *	0: valid
1844  *	1: invalid
1845  */
1846 int
1847 ipsec_in_reject(const struct secpolicy *sp, const struct mbuf *m)
1848 {
1849 	struct ipsecrequest *isr;
1850 	int need_auth;
1851 
1852 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1853 		printf("ipsec_in_reject: using SP\n");
1854 		kdebug_secpolicy(sp));
1855 
1856 	/* check policy */
1857 	switch (sp->policy) {
1858 	case IPSEC_POLICY_DISCARD:
1859 		return 1;
1860 	case IPSEC_POLICY_BYPASS:
1861 	case IPSEC_POLICY_NONE:
1862 		return 0;
1863 	}
1864 
1865 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1866 		("ipsec_in_reject: invalid policy %u", sp->policy));
1867 
1868 	/* XXX should compare policy against ipsec header history */
1869 
1870 	need_auth = 0;
1871 	for (isr = sp->req; isr != NULL; isr = isr->next) {
1872 		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
1873 			continue;
1874 		switch (isr->saidx.proto) {
1875 		case IPPROTO_ESP:
1876 			if ((m->m_flags & M_DECRYPTED) == 0) {
1877 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1878 					printf("ipsec_in_reject: ESP m_flags:%x\n",
1879 						m->m_flags));
1880 				return 1;
1881 			}
1882 
1883 			if (!need_auth &&
1884 				isr->sav != NULL &&
1885 				isr->sav->tdb_authalgxform != NULL &&
1886 				(m->m_flags & M_AUTHIPDGM) == 0) {
1887 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1888 					printf("ipsec_in_reject: ESP/AH m_flags:%x\n",
1889 						m->m_flags));
1890 				return 1;
1891 			}
1892 			break;
1893 		case IPPROTO_AH:
1894 			need_auth = 1;
1895 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1896 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1897 					printf("ipsec_in_reject: AH m_flags:%x\n",
1898 						m->m_flags));
1899 				return 1;
1900 			}
1901 			break;
1902 		case IPPROTO_IPCOMP:
1903 			/*
1904 			 * we don't really care, as IPcomp document
1905 			 * says that we shouldn't compress small
1906 			 * packets, IPComp policy should always be
1907 			 * treated as being in "use" level.
1908 			 */
1909 			break;
1910 		}
1911 	}
1912 	return 0;		/* valid */
1913 }
1914 
1915 /*
1916  * Check AH/ESP integrity.
1917  * This function is called from tcp_input(), udp_input(),
1918  * and {ah,esp}4_input for tunnel mode
1919  */
1920 int
1921 ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
1922 {
1923 	struct secpolicy *sp;
1924 	int error;
1925 	int result;
1926 
1927 	IPSEC_ASSERT(m != NULL, ("ipsec4_in_reject_so: null mbuf"));
1928 
1929 	/* get SP for this packet.
1930 	 * When we are called from ip_forward(), we call
1931 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1932 	 */
1933 	if (inp == NULL)
1934 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1935 	else
1936 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
1937 					   IN4PCB_TO_PCB(inp), &error);
1938 
1939 	if (sp != NULL) {
1940 		result = ipsec_in_reject(sp, m);
1941 		if (result)
1942 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1943 		KEY_FREESP(&sp);
1944 	} else {
1945 		result = 0;	/* XXX should be panic ?
1946 				 * -> No, there may be error. */
1947 	}
1948 	return result;
1949 }
1950 
1951 
1952 #ifdef INET6
1953 /*
1954  * Check AH/ESP integrity.
1955  * This function is called from tcp6_input(), udp6_input(),
1956  * and {ah,esp}6_input for tunnel mode
1957  */
1958 int
1959 ipsec6_in_reject(struct mbuf *m, struct in6pcb *in6p)
1960 {
1961 	struct secpolicy *sp = NULL;
1962 	int error;
1963 	int result;
1964 
1965 	/* sanity check */
1966 	if (m == NULL)
1967 		return 0;	/* XXX should be panic ? */
1968 
1969 	/* get SP for this packet.
1970 	 * When we are called from ip_forward(), we call
1971 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1972 	 */
1973 	if (in6p == NULL)
1974 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1975 	else
1976 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
1977 			IN6PCB_TO_PCB(in6p),
1978 			&error);
1979 
1980 	if (sp != NULL) {
1981 		result = ipsec_in_reject(sp, m);
1982 		if (result)
1983 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1984 		KEY_FREESP(&sp);
1985 	} else {
1986 		result = 0;
1987 	}
1988 	return result;
1989 }
1990 #endif
1991 
1992 /*
1993  * compute the byte size to be occupied by IPsec header.
1994  * in case it is tunneled, it includes the size of outer IP header.
1995  * NOTE: SP passed is free in this function.
1996  */
1997 static size_t
1998 ipsec_hdrsiz(const struct secpolicy *sp)
1999 {
2000 	const struct ipsecrequest *isr;
2001 	size_t siz;
2002 
2003 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
2004 		printf("ipsec_hdrsiz: using SP\n");
2005 		kdebug_secpolicy(sp));
2006 
2007 	switch (sp->policy) {
2008 	case IPSEC_POLICY_DISCARD:
2009 	case IPSEC_POLICY_BYPASS:
2010 	case IPSEC_POLICY_NONE:
2011 		return 0;
2012 	}
2013 
2014 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2015 		("ipsec_hdrsiz: invalid policy %u", sp->policy));
2016 
2017 	siz = 0;
2018 	for (isr = sp->req; isr != NULL; isr = isr->next) {
2019 		size_t clen = 0;
2020 
2021 		switch (isr->saidx.proto) {
2022 		case IPPROTO_ESP:
2023 			clen = esp_hdrsiz(isr->sav);
2024 			break;
2025 		case IPPROTO_AH:
2026 			clen = ah_hdrsiz(isr->sav);
2027 			break;
2028 		case IPPROTO_IPCOMP:
2029 			clen = sizeof(struct ipcomp);
2030 			break;
2031 		}
2032 
2033 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
2034 			switch (isr->saidx.dst.sa.sa_family) {
2035 			case AF_INET:
2036 				clen += sizeof(struct ip);
2037 				break;
2038 #ifdef INET6
2039 			case AF_INET6:
2040 				clen += sizeof(struct ip6_hdr);
2041 				break;
2042 #endif
2043 			default:
2044 				ipseclog((LOG_ERR, "ipsec_hdrsiz: "
2045 					"unknown AF %d in IPsec tunnel SA\n",
2046 					((const struct sockaddr *)&isr->saidx.dst)->sa_family));
2047 				break;
2048 			}
2049 		}
2050 		siz += clen;
2051 	}
2052 
2053 	return siz;
2054 }
2055 
2056 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
2057 size_t
2058 ipsec4_hdrsiz(struct mbuf *m, u_int dir, struct inpcb *inp)
2059 {
2060 	struct secpolicy *sp;
2061 	int error;
2062 	size_t size;
2063 
2064 	IPSEC_ASSERT(m != NULL, ("ipsec4_hdrsiz: null mbuf"));
2065 	IPSEC_ASSERT(inp == NULL || inp->inp_socket != NULL,
2066 		("ipsec4_hdrsize: socket w/o inpcb"));
2067 
2068 	/* get SP for this packet.
2069 	 * When we are called from ip_forward(), we call
2070 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
2071 	 */
2072 	if (inp == NULL)
2073 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
2074 	else
2075 		sp = ipsec_getpolicybysock(m, dir,
2076 					   IN4PCB_TO_PCB(inp), &error);
2077 
2078 	if (sp != NULL) {
2079 		size = ipsec_hdrsiz(sp);
2080 		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
2081 			printf("ipsec4_hdrsiz: size:%lu.\n",
2082 				(unsigned long)size));
2083 
2084 		KEY_FREESP(&sp);
2085 	} else {
2086 		size = 0;	/* XXX should be panic ? */
2087 	}
2088 	return size;
2089 }
2090 
2091 #ifdef INET6
2092 /* This function is called from ipsec6_hdrsize_tcp(),
2093  * and maybe from ip6_forward.()
2094  */
2095 size_t
2096 ipsec6_hdrsiz(struct mbuf *m, u_int dir, struct in6pcb *in6p)
2097 {
2098 	struct secpolicy *sp;
2099 	int error;
2100 	size_t size;
2101 
2102 	IPSEC_ASSERT(m != NULL, ("ipsec6_hdrsiz: null mbuf"));
2103 	IPSEC_ASSERT(in6p == NULL || in6p->in6p_socket != NULL,
2104 		("ipsec6_hdrsize: socket w/o inpcb"));
2105 
2106 	/* get SP for this packet */
2107 	/* XXX Is it right to call with IP_FORWARDING. */
2108 	if (in6p == NULL)
2109 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
2110 	else
2111 		sp = ipsec_getpolicybysock(m, dir,
2112 			IN6PCB_TO_PCB(in6p),
2113 			&error);
2114 
2115 	if (sp == NULL)
2116 		return 0;
2117 	size = ipsec_hdrsiz(sp);
2118 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
2119 		printf("ipsec6_hdrsiz: size:%lu.\n", (unsigned long)size));
2120 	KEY_FREESP(&sp);
2121 
2122 	return size;
2123 }
2124 #endif /*INET6*/
2125 
2126 /*
2127  * Check the variable replay window.
2128  * ipsec_chkreplay() performs replay check before ICV verification.
2129  * ipsec_updatereplay() updates replay bitmap.  This must be called after
2130  * ICV verification (it also performs replay check, which is usually done
2131  * beforehand).
2132  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
2133  *
2134  * based on RFC 2401.
2135  */
2136 int
2137 ipsec_chkreplay(u_int32_t seq, const struct secasvar *sav)
2138 {
2139 	const struct secreplay *replay;
2140 	u_int32_t diff;
2141 	int fr;
2142 	u_int32_t wsizeb;	/* constant: bits of window size */
2143 	int frlast;		/* constant: last frame */
2144 
2145 	IPSEC_SPLASSERT_SOFTNET("ipsec_chkreplay");
2146 
2147 	IPSEC_ASSERT(sav != NULL, ("ipsec_chkreplay: Null SA"));
2148 	IPSEC_ASSERT(sav->replay != NULL, ("ipsec_chkreplay: Null replay state"));
2149 
2150 	replay = sav->replay;
2151 
2152 	if (replay->wsize == 0)
2153 		return 1;	/* no need to check replay. */
2154 
2155 	/* constant */
2156 	frlast = replay->wsize - 1;
2157 	wsizeb = replay->wsize << 3;
2158 
2159 	/* sequence number of 0 is invalid */
2160 	if (seq == 0)
2161 		return 0;
2162 
2163 	/* first time is always okay */
2164 	if (replay->count == 0)
2165 		return 1;
2166 
2167 	if (seq > replay->lastseq) {
2168 		/* larger sequences are okay */
2169 		return 1;
2170 	} else {
2171 		/* seq is equal or less than lastseq. */
2172 		diff = replay->lastseq - seq;
2173 
2174 		/* over range to check, i.e. too old or wrapped */
2175 		if (diff >= wsizeb)
2176 			return 0;
2177 
2178 		fr = frlast - diff / 8;
2179 
2180 		/* this packet already seen ? */
2181 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
2182 			return 0;
2183 
2184 		/* out of order but good */
2185 		return 1;
2186 	}
2187 }
2188 
2189 /*
2190  * check replay counter whether to update or not.
2191  * OUT:	0:	OK
2192  *	1:	NG
2193  */
2194 int
2195 ipsec_updatereplay(u_int32_t seq, const struct secasvar *sav)
2196 {
2197 	struct secreplay *replay;
2198 	u_int32_t diff;
2199 	int fr;
2200 	u_int32_t wsizeb;	/* constant: bits of window size */
2201 	int frlast;		/* constant: last frame */
2202 
2203 	IPSEC_SPLASSERT_SOFTNET("ipsec_updatereplay");
2204 
2205 	IPSEC_ASSERT(sav != NULL, ("ipsec_updatereplay: Null SA"));
2206 	IPSEC_ASSERT(sav->replay != NULL, ("ipsec_updatereplay: Null replay state"));
2207 
2208 	replay = sav->replay;
2209 
2210 	if (replay->wsize == 0)
2211 		goto ok;	/* no need to check replay. */
2212 
2213 	/* constant */
2214 	frlast = replay->wsize - 1;
2215 	wsizeb = replay->wsize << 3;
2216 
2217 	/* sequence number of 0 is invalid */
2218 	if (seq == 0)
2219 		return 1;
2220 
2221 	/* first time */
2222 	if (replay->count == 0) {
2223 		replay->lastseq = seq;
2224 		memset(replay->bitmap, 0, replay->wsize);
2225 		(replay->bitmap)[frlast] = 1;
2226 		goto ok;
2227 	}
2228 
2229 	if (seq > replay->lastseq) {
2230 		/* seq is larger than lastseq. */
2231 		diff = seq - replay->lastseq;
2232 
2233 		/* new larger sequence number */
2234 		if (diff < wsizeb) {
2235 			/* In window */
2236 			/* set bit for this packet */
2237 			vshiftl(replay->bitmap, diff, replay->wsize);
2238 			(replay->bitmap)[frlast] |= 1;
2239 		} else {
2240 			/* this packet has a "way larger" */
2241 			memset(replay->bitmap, 0, replay->wsize);
2242 			(replay->bitmap)[frlast] = 1;
2243 		}
2244 		replay->lastseq = seq;
2245 
2246 		/* larger is good */
2247 	} else {
2248 		/* seq is equal or less than lastseq. */
2249 		diff = replay->lastseq - seq;
2250 
2251 		/* over range to check, i.e. too old or wrapped */
2252 		if (diff >= wsizeb)
2253 			return 1;
2254 
2255 		fr = frlast - diff / 8;
2256 
2257 		/* this packet already seen ? */
2258 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
2259 			return 1;
2260 
2261 		/* mark as seen */
2262 		(replay->bitmap)[fr] |= (1 << (diff % 8));
2263 
2264 		/* out of order but good */
2265 	}
2266 
2267 ok:
2268 	if (replay->count == ~0) {
2269 
2270 		/* set overflow flag */
2271 		replay->overflow++;
2272 
2273 		/* don't increment, no more packets accepted */
2274 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
2275 			return 1;
2276 
2277 		ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
2278 			replay->overflow, ipsec_logsastr(sav)));
2279 	}
2280 
2281 	replay->count++;
2282 
2283 	return 0;
2284 }
2285 
2286 /*
2287  * shift variable length bunffer to left.
2288  * IN:	bitmap: pointer to the buffer
2289  * 	nbit:	the number of to shift.
2290  *	wsize:	buffer size (bytes).
2291  */
2292 static void
2293 vshiftl(unsigned char *bitmap, int nbit, int wsize)
2294 {
2295 	int s, j, i;
2296 	unsigned char over;
2297 
2298 	for (j = 0; j < nbit; j += 8) {
2299 		s = (nbit - j < 8) ? (nbit - j): 8;
2300 		bitmap[0] <<= s;
2301 		for (i = 1; i < wsize; i++) {
2302 			over = (bitmap[i] >> (8 - s));
2303 			bitmap[i] <<= s;
2304 			bitmap[i-1] |= over;
2305 		}
2306 	}
2307 
2308 	return;
2309 }
2310 
2311 /* Return a printable string for the IPv4 address. */
2312 static char *
2313 inet_ntoa4(struct in_addr ina)
2314 {
2315 	static char buf[4][4 * sizeof "123" + 4];
2316 	unsigned char *ucp = (unsigned char *) &ina;
2317 	static int i = 3;
2318 
2319 	i = (i + 1) % 4;
2320 	snprintf(buf[i], sizeof(buf[i]), "%d.%d.%d.%d",
2321 		ucp[0] & 0xff, ucp[1] & 0xff, ucp[2] & 0xff, ucp[3] & 0xff);
2322 	return (buf[i]);
2323 }
2324 
2325 /* Return a printable string for the address. */
2326 const char *
2327 ipsec_address(const union sockaddr_union *sa)
2328 {
2329 	switch (sa->sa.sa_family) {
2330 #if INET
2331 	case AF_INET:
2332 		return inet_ntoa4(sa->sin.sin_addr);
2333 #endif /* INET */
2334 
2335 #if INET6
2336 	case AF_INET6:
2337 		return ip6_sprintf(&sa->sin6.sin6_addr);
2338 #endif /* INET6 */
2339 
2340 	default:
2341 		return "(unknown address family)";
2342 	}
2343 }
2344 
2345 const char *
2346 ipsec_logsastr(const struct secasvar *sav)
2347 {
2348 	static char buf[256];
2349 	char *p;
2350 	const struct secasindex *saidx = &sav->sah->saidx;
2351 
2352 	IPSEC_ASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
2353 		("ipsec_logsastr: address family mismatch"));
2354 
2355 	p = buf;
2356 	snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
2357 	while (p && *p)
2358 		p++;
2359 	/* NB: only use ipsec_address on one address at a time */
2360 	snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
2361 		ipsec_address(&saidx->src));
2362 	while (p && *p)
2363 		p++;
2364 	snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
2365 		ipsec_address(&saidx->dst));
2366 
2367 	return buf;
2368 }
2369 
2370 void
2371 ipsec_dumpmbuf(struct mbuf *m)
2372 {
2373 	int totlen;
2374 	int i;
2375 	u_char *p;
2376 
2377 	totlen = 0;
2378 	printf("---\n");
2379 	while (m) {
2380 		p = mtod(m, u_char *);
2381 		for (i = 0; i < m->m_len; i++) {
2382 			printf("%02x ", p[i]);
2383 			totlen++;
2384 			if (totlen % 16 == 0)
2385 				printf("\n");
2386 		}
2387 		m = m->m_next;
2388 	}
2389 	if (totlen % 16 != 0)
2390 		printf("\n");
2391 	printf("---\n");
2392 }
2393 
2394 #ifdef INET6
2395 struct secpolicy *
2396 ipsec6_check_policy(struct mbuf *m, const struct socket *so,
2397 		    int flags, int *needipsecp, int *errorp)
2398 {
2399 	struct in6pcb *in6p = NULL;
2400 	struct secpolicy *sp = NULL;
2401 	int s;
2402 	int error = 0;
2403 	int needipsec = 0;
2404 
2405 	if (so != NULL && so->so_proto->pr_domain->dom_family == AF_INET6)
2406 		in6p = sotoin6pcb(so);
2407 
2408 	if (!ipsec_outdone(m)) {
2409 		s = splsoftnet();
2410 		if (in6p != NULL &&
2411 		    IPSEC_PCB_SKIP_IPSEC(in6p->in6p_sp, IPSEC_DIR_OUTBOUND)) {
2412 			splx(s);
2413 			goto skippolicycheck;
2414 		}
2415 		sp = ipsec6_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error,in6p);
2416 
2417 		/*
2418 		 * There are four return cases:
2419 		 *	sp != NULL			apply IPsec policy
2420 		 *	sp == NULL, error == 0		no IPsec handling needed
2421 		 *	sp == NULL, error == -EINVAL  discard packet w/o error
2422 		 *	sp == NULL, error != 0		discard packet, report error
2423 		 */
2424 
2425 		splx(s);
2426 		if (sp == NULL) {
2427 			/*
2428 			 * Caller must check the error return to see if it needs to discard
2429 			 * the packet.
2430 			 */
2431 			needipsec = 0;
2432 		} else {
2433 			needipsec = 1;
2434 		}
2435 	}
2436 skippolicycheck:;
2437 
2438 	*errorp = error;
2439 	*needipsecp = needipsec;
2440 	return sp;
2441 }
2442 #endif
2443 
2444 
2445 
2446 /* XXX this stuff doesn't belong here... */
2447 
2448 static	struct xformsw *xforms = NULL;
2449 
2450 /*
2451  * Register a transform; typically at system startup.
2452  */
2453 void
2454 xform_register(struct xformsw *xsp)
2455 {
2456 	xsp->xf_next = xforms;
2457 	xforms = xsp;
2458 }
2459 
2460 /*
2461  * Initialize transform support in an sav.
2462  */
2463 int
2464 xform_init(struct secasvar *sav, int xftype)
2465 {
2466 	struct xformsw *xsp;
2467 
2468 	if (sav->tdb_xform != NULL)	/* previously initialized */
2469 		return 0;
2470 	for (xsp = xforms; xsp; xsp = xsp->xf_next)
2471 		if (xsp->xf_type == xftype)
2472 			return (*xsp->xf_init)(sav, xsp);
2473 
2474 	DPRINTF(("xform_init: no match for xform type %d\n", xftype));
2475 	return EINVAL;
2476 }
2477 
2478 void
2479 nat_t_ports_get(struct mbuf *m, u_int16_t *dport, u_int16_t *sport) {
2480 	struct m_tag *tag;
2481 
2482 	if ((tag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS, NULL))) {
2483 		*sport = ((u_int16_t *)(tag + 1))[0];
2484 		*dport = ((u_int16_t *)(tag + 1))[1];
2485 	} else
2486 		*sport = *dport = 0;
2487 }
2488 
2489 #ifdef __NetBSD__
2490 /*
2491  * XXXJRT This should be done as a protosw init call.
2492  */
2493 void
2494 ipsec_attach(void)
2495 {
2496 
2497 	ipsecstat_percpu = percpu_alloc(sizeof(uint64_t) * IPSEC_NSTATS);
2498 
2499 	ah_attach();
2500 	esp_attach();
2501 	ipcomp_attach();
2502 	ipe4_attach();
2503 #ifdef TCP_SIGNATURE
2504 	tcpsignature_attach();
2505 #endif
2506 }
2507 #endif	/* __NetBSD__ */
2508