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