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