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