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