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