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