xref: /netbsd-src/sys/netipsec/ipsec.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: ipsec.c,v 1.48 2010/07/21 20:41:31 jakllsch 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.48 2010/07/21 20:41:31 jakllsch 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 	ipsec_delpcbpolicy(inp->inp_sp);
1441 	inp->inp_sp = NULL;
1442 
1443 	return 0;
1444 }
1445 
1446 #ifdef INET6
1447 int
1448 ipsec6_set_policy(struct in6pcb *in6p, int optname, void *request,
1449 		  size_t len, kauth_cred_t cred)
1450 {
1451 	struct sadb_x_policy *xpl;
1452 	struct secpolicy **pcb_sp;
1453 
1454 	/* sanity check. */
1455 	if (in6p == NULL || request == NULL)
1456 		return EINVAL;
1457 	if (len < sizeof(*xpl))
1458 		return EINVAL;
1459 	xpl = (struct sadb_x_policy *)request;
1460 
1461 	/* select direction */
1462 	switch (xpl->sadb_x_policy_dir) {
1463 	case IPSEC_DIR_INBOUND:
1464 		pcb_sp = &in6p->in6p_sp->sp_in;
1465 		break;
1466 	case IPSEC_DIR_OUTBOUND:
1467 		pcb_sp = &in6p->in6p_sp->sp_out;
1468 		break;
1469 	default:
1470 		ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
1471 			xpl->sadb_x_policy_dir));
1472 		return EINVAL;
1473 	}
1474 
1475 	return ipsec_set_policy(pcb_sp, optname, request, len, cred);
1476 }
1477 
1478 int
1479 ipsec6_get_policy(struct in6pcb *in6p, void *request, size_t len,
1480 		  struct mbuf **mp)
1481 {
1482 	struct sadb_x_policy *xpl;
1483 	struct secpolicy *pcb_sp;
1484 
1485 	/* sanity check. */
1486 	if (in6p == NULL || request == NULL || mp == NULL)
1487 		return EINVAL;
1488 	IPSEC_ASSERT(in6p->in6p_sp != NULL, ("ipsec6_get_policy: null in6p_sp"));
1489 	if (len < sizeof(*xpl))
1490 		return EINVAL;
1491 	xpl = (struct sadb_x_policy *)request;
1492 
1493 	/* select direction */
1494 	switch (xpl->sadb_x_policy_dir) {
1495 	case IPSEC_DIR_INBOUND:
1496 		pcb_sp = in6p->in6p_sp->sp_in;
1497 		break;
1498 	case IPSEC_DIR_OUTBOUND:
1499 		pcb_sp = in6p->in6p_sp->sp_out;
1500 		break;
1501 	default:
1502 		ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
1503 			xpl->sadb_x_policy_dir));
1504 		return EINVAL;
1505 	}
1506 
1507 	return ipsec_get_policy(pcb_sp, mp);
1508 }
1509 
1510 int
1511 ipsec6_delete_pcbpolicy(struct in6pcb *in6p)
1512 {
1513 	IPSEC_ASSERT(in6p != NULL, ("ipsec6_delete_pcbpolicy: null in6p"));
1514 
1515 	if (in6p->in6p_sp == NULL)
1516 		return 0;
1517 
1518 	if (in6p->in6p_sp->sp_in != NULL)
1519 		KEY_FREESP(&in6p->in6p_sp->sp_in);
1520 
1521 	if (in6p->in6p_sp->sp_out != NULL)
1522 		KEY_FREESP(&in6p->in6p_sp->sp_out);
1523 
1524 	ipsec_delpcbpolicy(in6p->in6p_sp);
1525 	in6p->in6p_sp = NULL;
1526 
1527 	return 0;
1528 }
1529 #endif
1530 
1531 /*
1532  * return current level.
1533  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
1534  */
1535 u_int
1536 ipsec_get_reqlevel(struct ipsecrequest *isr)
1537 {
1538 	u_int level = 0;
1539 	u_int esp_trans_deflev, esp_net_deflev;
1540 	u_int ah_trans_deflev, ah_net_deflev;
1541 
1542 	IPSEC_ASSERT(isr != NULL && isr->sp != NULL,
1543 		("ipsec_get_reqlevel: null argument"));
1544 	IPSEC_ASSERT(isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
1545 		("ipsec_get_reqlevel: af family mismatch, src %u, dst %u",
1546 		 isr->sp->spidx.src.sa.sa_family,
1547 		 isr->sp->spidx.dst.sa.sa_family));
1548 
1549 /* XXX note that we have ipseclog() expanded here - code sync issue */
1550 #define IPSEC_CHECK_DEFAULT(lev) \
1551 	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE		  \
1552 			&& (lev) != IPSEC_LEVEL_UNIQUE)				  \
1553 		? (ipsec_debug							  \
1554 			? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
1555 				(lev), IPSEC_LEVEL_REQUIRE)			  \
1556 			: 0),							  \
1557 			(lev) = IPSEC_LEVEL_REQUIRE,				  \
1558 			(lev)							  \
1559 		: (lev))
1560 
1561 	/* set default level */
1562 	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
1563 #ifdef INET
1564 	case AF_INET:
1565 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
1566 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
1567 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
1568 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
1569 		break;
1570 #endif
1571 #ifdef INET6
1572 	case AF_INET6:
1573 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
1574 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
1575 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
1576 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
1577 		break;
1578 #endif /* INET6 */
1579 	default:
1580 		panic("key_get_reqlevel: unknown af %u",
1581 			isr->sp->spidx.src.sa.sa_family);
1582 	}
1583 
1584 #undef IPSEC_CHECK_DEFAULT
1585 
1586 	/* set level */
1587 	switch (isr->level) {
1588 	case IPSEC_LEVEL_DEFAULT:
1589 		switch (isr->saidx.proto) {
1590 		case IPPROTO_ESP:
1591 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1592 				level = esp_net_deflev;
1593 			else
1594 				level = esp_trans_deflev;
1595 			break;
1596 		case IPPROTO_AH:
1597 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1598 				level = ah_net_deflev;
1599 			else
1600 				level = ah_trans_deflev;
1601 			break;
1602 		case IPPROTO_IPCOMP:
1603 			/*
1604 			 * we don't really care, as IPcomp document says that
1605 			 * we shouldn't compress small packets
1606 			 */
1607 			level = IPSEC_LEVEL_USE;
1608 			break;
1609 		default:
1610 			panic("ipsec_get_reqlevel: Illegal protocol defined %u",
1611 				isr->saidx.proto);
1612 		}
1613 		break;
1614 
1615 	case IPSEC_LEVEL_USE:
1616 	case IPSEC_LEVEL_REQUIRE:
1617 		level = isr->level;
1618 		break;
1619 	case IPSEC_LEVEL_UNIQUE:
1620 		level = IPSEC_LEVEL_REQUIRE;
1621 		break;
1622 
1623 	default:
1624 		panic("ipsec_get_reqlevel: Illegal IPsec level %u",
1625 			isr->level);
1626 	}
1627 
1628 	return level;
1629 }
1630 
1631 /*
1632  * Check security policy requirements against the actual
1633  * packet contents.  Return one if the packet should be
1634  * reject as "invalid"; otherwiser return zero to have the
1635  * packet treated as "valid".
1636  *
1637  * OUT:
1638  *	0: valid
1639  *	1: invalid
1640  */
1641 int
1642 ipsec_in_reject(struct secpolicy *sp, struct mbuf *m)
1643 {
1644 	struct ipsecrequest *isr;
1645 	int need_auth;
1646 
1647 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1648 		printf("ipsec_in_reject: using SP\n");
1649 		kdebug_secpolicy(sp));
1650 
1651 	/* check policy */
1652 	switch (sp->policy) {
1653 	case IPSEC_POLICY_DISCARD:
1654 		return 1;
1655 	case IPSEC_POLICY_BYPASS:
1656 	case IPSEC_POLICY_NONE:
1657 		return 0;
1658 	}
1659 
1660 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1661 		("ipsec_in_reject: invalid policy %u", sp->policy));
1662 
1663 	/* XXX should compare policy against ipsec header history */
1664 
1665 	need_auth = 0;
1666 	for (isr = sp->req; isr != NULL; isr = isr->next) {
1667 		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
1668 			continue;
1669 		switch (isr->saidx.proto) {
1670 		case IPPROTO_ESP:
1671 			if ((m->m_flags & M_DECRYPTED) == 0) {
1672 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1673 					printf("ipsec_in_reject: ESP m_flags:%x\n",
1674 						m->m_flags));
1675 				return 1;
1676 			}
1677 
1678 			if (!need_auth &&
1679 				isr->sav != NULL &&
1680 				isr->sav->tdb_authalgxform != NULL &&
1681 				(m->m_flags & M_AUTHIPDGM) == 0) {
1682 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1683 					printf("ipsec_in_reject: ESP/AH m_flags:%x\n",
1684 						m->m_flags));
1685 				return 1;
1686 			}
1687 			break;
1688 		case IPPROTO_AH:
1689 			need_auth = 1;
1690 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1691 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1692 					printf("ipsec_in_reject: AH m_flags:%x\n",
1693 						m->m_flags));
1694 				return 1;
1695 			}
1696 			break;
1697 		case IPPROTO_IPCOMP:
1698 			/*
1699 			 * we don't really care, as IPcomp document
1700 			 * says that we shouldn't compress small
1701 			 * packets, IPComp policy should always be
1702 			 * treated as being in "use" level.
1703 			 */
1704 			break;
1705 		}
1706 	}
1707 	return 0;		/* valid */
1708 }
1709 
1710 /*
1711  * Check AH/ESP integrity.
1712  * This function is called from tcp_input(), udp_input(),
1713  * and {ah,esp}4_input for tunnel mode
1714  */
1715 int
1716 ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
1717 {
1718 	struct secpolicy *sp;
1719 	int error;
1720 	int result;
1721 
1722 	IPSEC_ASSERT(m != NULL, ("ipsec4_in_reject_so: null mbuf"));
1723 
1724 	/* get SP for this packet.
1725 	 * When we are called from ip_forward(), we call
1726 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1727 	 */
1728 	if (inp == NULL)
1729 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1730 	else
1731 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
1732 					   IN4PCB_TO_PCB(inp), &error);
1733 
1734 	if (sp != NULL) {
1735 		result = ipsec_in_reject(sp, m);
1736 		if (result)
1737 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1738 		KEY_FREESP(&sp);
1739 	} else {
1740 		result = 0;	/* XXX should be panic ?
1741 				 * -> No, there may be error. */
1742 	}
1743 	return result;
1744 }
1745 
1746 
1747 #ifdef INET6
1748 /*
1749  * Check AH/ESP integrity.
1750  * This function is called from tcp6_input(), udp6_input(),
1751  * and {ah,esp}6_input for tunnel mode
1752  */
1753 int
1754 ipsec6_in_reject(struct mbuf *m, struct in6pcb *in6p)
1755 {
1756 	struct secpolicy *sp = NULL;
1757 	int error;
1758 	int result;
1759 
1760 	/* sanity check */
1761 	if (m == NULL)
1762 		return 0;	/* XXX should be panic ? */
1763 
1764 	/* get SP for this packet.
1765 	 * When we are called from ip_forward(), we call
1766 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1767 	 */
1768 	if (in6p == NULL)
1769 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1770 	else
1771 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
1772 			IN6PCB_TO_PCB(in6p),
1773 			&error);
1774 
1775 	if (sp != NULL) {
1776 		result = ipsec_in_reject(sp, m);
1777 		if (result)
1778 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1779 		KEY_FREESP(&sp);
1780 	} else {
1781 		result = 0;
1782 	}
1783 	return result;
1784 }
1785 #endif
1786 
1787 /*
1788  * compute the byte size to be occupied by IPsec header.
1789  * in case it is tunneled, it includes the size of outer IP header.
1790  * NOTE: SP passed is free in this function.
1791  */
1792 static size_t
1793 ipsec_hdrsiz(struct secpolicy *sp)
1794 {
1795 	struct ipsecrequest *isr;
1796 	size_t siz;
1797 
1798 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1799 		printf("ipsec_hdrsiz: using SP\n");
1800 		kdebug_secpolicy(sp));
1801 
1802 	switch (sp->policy) {
1803 	case IPSEC_POLICY_DISCARD:
1804 	case IPSEC_POLICY_BYPASS:
1805 	case IPSEC_POLICY_NONE:
1806 		return 0;
1807 	}
1808 
1809 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1810 		("ipsec_hdrsiz: invalid policy %u", sp->policy));
1811 
1812 	siz = 0;
1813 	for (isr = sp->req; isr != NULL; isr = isr->next) {
1814 		size_t clen = 0;
1815 
1816 		switch (isr->saidx.proto) {
1817 		case IPPROTO_ESP:
1818 			clen = esp_hdrsiz(isr->sav);
1819 			break;
1820 		case IPPROTO_AH:
1821 			clen = ah_hdrsiz(isr->sav);
1822 			break;
1823 		case IPPROTO_IPCOMP:
1824 			clen = sizeof(struct ipcomp);
1825 			break;
1826 		}
1827 
1828 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1829 			switch (isr->saidx.dst.sa.sa_family) {
1830 			case AF_INET:
1831 				clen += sizeof(struct ip);
1832 				break;
1833 #ifdef INET6
1834 			case AF_INET6:
1835 				clen += sizeof(struct ip6_hdr);
1836 				break;
1837 #endif
1838 			default:
1839 				ipseclog((LOG_ERR, "ipsec_hdrsiz: "
1840 					"unknown AF %d in IPsec tunnel SA\n",
1841 					((struct sockaddr *)&isr->saidx.dst)->sa_family));
1842 				break;
1843 			}
1844 		}
1845 		siz += clen;
1846 	}
1847 
1848 	return siz;
1849 }
1850 
1851 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
1852 size_t
1853 ipsec4_hdrsiz(struct mbuf *m, u_int dir, struct inpcb *inp)
1854 {
1855 	struct secpolicy *sp;
1856 	int error;
1857 	size_t size;
1858 
1859 	IPSEC_ASSERT(m != NULL, ("ipsec4_hdrsiz: null mbuf"));
1860 	IPSEC_ASSERT(inp == NULL || inp->inp_socket != NULL,
1861 		("ipsec4_hdrsize: socket w/o inpcb"));
1862 
1863 	/* get SP for this packet.
1864 	 * When we are called from ip_forward(), we call
1865 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1866 	 */
1867 	if (inp == NULL)
1868 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
1869 	else
1870 		sp = ipsec_getpolicybysock(m, dir,
1871 					   IN4PCB_TO_PCB(inp), &error);
1872 
1873 	if (sp != NULL) {
1874 		size = ipsec_hdrsiz(sp);
1875 		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1876 			printf("ipsec4_hdrsiz: size:%lu.\n",
1877 				(unsigned long)size));
1878 
1879 		KEY_FREESP(&sp);
1880 	} else {
1881 		size = 0;	/* XXX should be panic ? */
1882 	}
1883 	return size;
1884 }
1885 
1886 #ifdef INET6
1887 /* This function is called from ipsec6_hdrsize_tcp(),
1888  * and maybe from ip6_forward.()
1889  */
1890 size_t
1891 ipsec6_hdrsiz(struct mbuf *m, u_int dir, struct in6pcb *in6p)
1892 {
1893 	struct secpolicy *sp;
1894 	int error;
1895 	size_t size;
1896 
1897 	IPSEC_ASSERT(m != NULL, ("ipsec6_hdrsiz: null mbuf"));
1898 	IPSEC_ASSERT(in6p == NULL || in6p->in6p_socket != NULL,
1899 		("ipsec6_hdrsize: socket w/o inpcb"));
1900 
1901 	/* get SP for this packet */
1902 	/* XXX Is it right to call with IP_FORWARDING. */
1903 	if (in6p == NULL)
1904 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
1905 	else
1906 		sp = ipsec_getpolicybysock(m, dir,
1907 			IN6PCB_TO_PCB(in6p),
1908 			&error);
1909 
1910 	if (sp == NULL)
1911 		return 0;
1912 	size = ipsec_hdrsiz(sp);
1913 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1914 		printf("ipsec6_hdrsiz: size:%lu.\n", (unsigned long)size));
1915 	KEY_FREESP(&sp);
1916 
1917 	return size;
1918 }
1919 #endif /*INET6*/
1920 
1921 /*
1922  * Check the variable replay window.
1923  * ipsec_chkreplay() performs replay check before ICV verification.
1924  * ipsec_updatereplay() updates replay bitmap.  This must be called after
1925  * ICV verification (it also performs replay check, which is usually done
1926  * beforehand).
1927  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1928  *
1929  * based on RFC 2401.
1930  */
1931 int
1932 ipsec_chkreplay(u_int32_t seq, struct secasvar *sav)
1933 {
1934 	const struct secreplay *replay;
1935 	u_int32_t diff;
1936 	int fr;
1937 	u_int32_t wsizeb;	/* constant: bits of window size */
1938 	int frlast;		/* constant: last frame */
1939 
1940 	IPSEC_SPLASSERT_SOFTNET("ipsec_chkreplay");
1941 
1942 	IPSEC_ASSERT(sav != NULL, ("ipsec_chkreplay: Null SA"));
1943 	IPSEC_ASSERT(sav->replay != NULL, ("ipsec_chkreplay: Null replay state"));
1944 
1945 	replay = sav->replay;
1946 
1947 	if (replay->wsize == 0)
1948 		return 1;	/* no need to check replay. */
1949 
1950 	/* constant */
1951 	frlast = replay->wsize - 1;
1952 	wsizeb = replay->wsize << 3;
1953 
1954 	/* sequence number of 0 is invalid */
1955 	if (seq == 0)
1956 		return 0;
1957 
1958 	/* first time is always okay */
1959 	if (replay->count == 0)
1960 		return 1;
1961 
1962 	if (seq > replay->lastseq) {
1963 		/* larger sequences are okay */
1964 		return 1;
1965 	} else {
1966 		/* seq is equal or less than lastseq. */
1967 		diff = replay->lastseq - seq;
1968 
1969 		/* over range to check, i.e. too old or wrapped */
1970 		if (diff >= wsizeb)
1971 			return 0;
1972 
1973 		fr = frlast - diff / 8;
1974 
1975 		/* this packet already seen ? */
1976 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1977 			return 0;
1978 
1979 		/* out of order but good */
1980 		return 1;
1981 	}
1982 }
1983 
1984 /*
1985  * check replay counter whether to update or not.
1986  * OUT:	0:	OK
1987  *	1:	NG
1988  */
1989 int
1990 ipsec_updatereplay(u_int32_t seq, struct secasvar *sav)
1991 {
1992 	struct secreplay *replay;
1993 	u_int32_t diff;
1994 	int fr;
1995 	u_int32_t wsizeb;	/* constant: bits of window size */
1996 	int frlast;		/* constant: last frame */
1997 
1998 	IPSEC_SPLASSERT_SOFTNET("ipsec_updatereplay");
1999 
2000 	IPSEC_ASSERT(sav != NULL, ("ipsec_updatereplay: Null SA"));
2001 	IPSEC_ASSERT(sav->replay != NULL, ("ipsec_updatereplay: Null replay state"));
2002 
2003 	replay = sav->replay;
2004 
2005 	if (replay->wsize == 0)
2006 		goto ok;	/* no need to check replay. */
2007 
2008 	/* constant */
2009 	frlast = replay->wsize - 1;
2010 	wsizeb = replay->wsize << 3;
2011 
2012 	/* sequence number of 0 is invalid */
2013 	if (seq == 0)
2014 		return 1;
2015 
2016 	/* first time */
2017 	if (replay->count == 0) {
2018 		replay->lastseq = seq;
2019 		memset(replay->bitmap, 0, replay->wsize);
2020 		(replay->bitmap)[frlast] = 1;
2021 		goto ok;
2022 	}
2023 
2024 	if (seq > replay->lastseq) {
2025 		/* seq is larger than lastseq. */
2026 		diff = seq - replay->lastseq;
2027 
2028 		/* new larger sequence number */
2029 		if (diff < wsizeb) {
2030 			/* In window */
2031 			/* set bit for this packet */
2032 			vshiftl(replay->bitmap, diff, replay->wsize);
2033 			(replay->bitmap)[frlast] |= 1;
2034 		} else {
2035 			/* this packet has a "way larger" */
2036 			memset(replay->bitmap, 0, replay->wsize);
2037 			(replay->bitmap)[frlast] = 1;
2038 		}
2039 		replay->lastseq = seq;
2040 
2041 		/* larger is good */
2042 	} else {
2043 		/* seq is equal or less than lastseq. */
2044 		diff = replay->lastseq - seq;
2045 
2046 		/* over range to check, i.e. too old or wrapped */
2047 		if (diff >= wsizeb)
2048 			return 1;
2049 
2050 		fr = frlast - diff / 8;
2051 
2052 		/* this packet already seen ? */
2053 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
2054 			return 1;
2055 
2056 		/* mark as seen */
2057 		(replay->bitmap)[fr] |= (1 << (diff % 8));
2058 
2059 		/* out of order but good */
2060 	}
2061 
2062 ok:
2063 	if (replay->count == ~0) {
2064 
2065 		/* set overflow flag */
2066 		replay->overflow++;
2067 
2068 		/* don't increment, no more packets accepted */
2069 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
2070 			return 1;
2071 
2072 		ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
2073 			replay->overflow, ipsec_logsastr(sav)));
2074 	}
2075 
2076 	replay->count++;
2077 
2078 	return 0;
2079 }
2080 
2081 /*
2082  * shift variable length bunffer to left.
2083  * IN:	bitmap: pointer to the buffer
2084  * 	nbit:	the number of to shift.
2085  *	wsize:	buffer size (bytes).
2086  */
2087 static void
2088 vshiftl(unsigned char *bitmap, int nbit, int wsize)
2089 {
2090 	int s, j, i;
2091 	unsigned char over;
2092 
2093 	for (j = 0; j < nbit; j += 8) {
2094 		s = (nbit - j < 8) ? (nbit - j): 8;
2095 		bitmap[0] <<= s;
2096 		for (i = 1; i < wsize; i++) {
2097 			over = (bitmap[i] >> (8 - s));
2098 			bitmap[i] <<= s;
2099 			bitmap[i-1] |= over;
2100 		}
2101 	}
2102 
2103 	return;
2104 }
2105 
2106 /* Return a printable string for the IPv4 address. */
2107 static char *
2108 inet_ntoa4(struct in_addr ina)
2109 {
2110 	static char buf[4][4 * sizeof "123" + 4];
2111 	unsigned char *ucp = (unsigned char *) &ina;
2112 	static int i = 3;
2113 
2114 	i = (i + 1) % 4;
2115 	snprintf(buf[i], sizeof(buf[i]), "%d.%d.%d.%d",
2116 		ucp[0] & 0xff, ucp[1] & 0xff, ucp[2] & 0xff, ucp[3] & 0xff);
2117 	return (buf[i]);
2118 }
2119 
2120 /* Return a printable string for the address. */
2121 const char *
2122 ipsec_address(union sockaddr_union* sa)
2123 {
2124 	switch (sa->sa.sa_family) {
2125 #if INET
2126 	case AF_INET:
2127 		return inet_ntoa4(sa->sin.sin_addr);
2128 #endif /* INET */
2129 
2130 #if INET6
2131 	case AF_INET6:
2132 		return ip6_sprintf(&sa->sin6.sin6_addr);
2133 #endif /* INET6 */
2134 
2135 	default:
2136 		return "(unknown address family)";
2137 	}
2138 }
2139 
2140 const char *
2141 ipsec_logsastr(struct secasvar *sav)
2142 {
2143 	static char buf[256];
2144 	char *p;
2145 	struct secasindex *saidx = &sav->sah->saidx;
2146 
2147 	IPSEC_ASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
2148 		("ipsec_logsastr: address family mismatch"));
2149 
2150 	p = buf;
2151 	snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
2152 	while (p && *p)
2153 		p++;
2154 	/* NB: only use ipsec_address on one address at a time */
2155 	snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
2156 		ipsec_address(&saidx->src));
2157 	while (p && *p)
2158 		p++;
2159 	snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
2160 		ipsec_address(&saidx->dst));
2161 
2162 	return buf;
2163 }
2164 
2165 void
2166 ipsec_dumpmbuf(struct mbuf *m)
2167 {
2168 	int totlen;
2169 	int i;
2170 	u_char *p;
2171 
2172 	totlen = 0;
2173 	printf("---\n");
2174 	while (m) {
2175 		p = mtod(m, u_char *);
2176 		for (i = 0; i < m->m_len; i++) {
2177 			printf("%02x ", p[i]);
2178 			totlen++;
2179 			if (totlen % 16 == 0)
2180 				printf("\n");
2181 		}
2182 		m = m->m_next;
2183 	}
2184 	if (totlen % 16 != 0)
2185 		printf("\n");
2186 	printf("---\n");
2187 }
2188 
2189 #ifdef INET6
2190 struct secpolicy *
2191 ipsec6_check_policy(struct mbuf * m, const struct socket * so,
2192 		    int flags, int * needipsecp, int * errorp)
2193 {
2194 	struct in6pcb *in6p = NULL;
2195 	struct secpolicy *sp = NULL;
2196 	int s;
2197 	int error = 0;
2198 	int needipsec = 0;
2199 
2200 	if (so != NULL && so->so_proto->pr_domain->dom_family == AF_INET6)
2201 		in6p = sotoin6pcb(so);
2202 
2203 	if (!ipsec_outdone(m)) {
2204 		s = splsoftnet();
2205 		if (in6p != NULL &&
2206 		    IPSEC_PCB_SKIP_IPSEC(in6p->in6p_sp, IPSEC_DIR_OUTBOUND)) {
2207 			splx(s);
2208 			goto skippolicycheck;
2209 		}
2210 		sp = ipsec6_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error,in6p);
2211 
2212 		/*
2213 		 * There are four return cases:
2214 		 *	sp != NULL			apply IPsec policy
2215 		 *	sp == NULL, error == 0		no IPsec handling needed
2216 		 *	sp == NULL, error == -EINVAL  discard packet w/o error
2217 		 *	sp == NULL, error != 0		discard packet, report error
2218 		 */
2219 
2220 		splx(s);
2221 		if (sp == NULL) {
2222 			/*
2223 			 * Caller must check the error return to see if it needs to discard
2224 			 * the packet.
2225 			 */
2226 			needipsec = 0;
2227 		} else {
2228 			needipsec = 1;
2229 		}
2230 	}
2231 skippolicycheck:;
2232 
2233 	*errorp = error;
2234 	*needipsecp = needipsec;
2235 	return sp;
2236 }
2237 #endif
2238 
2239 
2240 
2241 /* XXX this stuff doesn't belong here... */
2242 
2243 static	struct xformsw* xforms = NULL;
2244 
2245 /*
2246  * Register a transform; typically at system startup.
2247  */
2248 void
2249 xform_register(struct xformsw* xsp)
2250 {
2251 	xsp->xf_next = xforms;
2252 	xforms = xsp;
2253 }
2254 
2255 /*
2256  * Initialize transform support in an sav.
2257  */
2258 int
2259 xform_init(struct secasvar *sav, int xftype)
2260 {
2261 	struct xformsw *xsp;
2262 
2263 	if (sav->tdb_xform != NULL)	/* previously initialized */
2264 		return 0;
2265 	for (xsp = xforms; xsp; xsp = xsp->xf_next)
2266 		if (xsp->xf_type == xftype)
2267 			return (*xsp->xf_init)(sav, xsp);
2268 
2269 	DPRINTF(("xform_init: no match for xform type %d\n", xftype));
2270 	return EINVAL;
2271 }
2272 
2273 #ifdef __NetBSD__
2274 /*
2275  * XXXJRT This should be done as a protosw init call.
2276  */
2277 void
2278 ipsec_attach(void)
2279 {
2280 
2281 	ipsecstat_percpu = percpu_alloc(sizeof(uint64_t) * IPSEC_NSTATS);
2282 
2283 	ah_attach();
2284 	esp_attach();
2285 	ipcomp_attach();
2286 	ipe4_attach();
2287 #ifdef TCP_SIGNATURE
2288 	tcpsignature_attach();
2289 #endif
2290 }
2291 #endif	/* __NetBSD__ */
2292