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