1 /*	$NetBSD: ipsec.c,v 1.66 2015/04/01 02:49:44 ozaki-r Exp $	*/
2 /*	$FreeBSD: /usr/local/www/cvsroot/FreeBSD/src/sys/netipsec/ipsec.c,v 1.2.2.2 2003/07/01 01:38:13 sam Exp $	*/
3 /*	$KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $	*/
4 
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *	notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *	notice, this list of conditions and the following disclaimer in the
16  *	documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *	may be used to endorse or promote products derived from this software
19  *	without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: ipsec.c,v 1.66 2015/04/01 02:49:44 ozaki-r Exp $");
36 
37 /*
38  * IPsec controller part.
39  */
40 
41 #include "opt_inet.h"
42 #ifdef __FreeBSD__
43 #include "opt_inet6.h"
44 #endif
45 #include "opt_ipsec.h"
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/domain.h>
52 #include <sys/protosw.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/errno.h>
56 #include <sys/time.h>
57 #include <sys/kernel.h>
58 #include <sys/syslog.h>
59 #include <sys/sysctl.h>
60 #include <sys/proc.h>
61 #include <sys/kauth.h>
62 
63 #include <net/if.h>
64 #include <net/route.h>
65 
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
69 #include <netinet/ip_var.h>
70 #include <netinet/in_var.h>
71 #include <netinet/udp.h>
72 #include <netinet/udp_var.h>
73 #include <netinet/tcp.h>
74 #include <netinet/udp.h>
75 #include <netinet/ip_icmp.h>
76 #include <netinet/ip_private.h>
77 
78 #include <netinet/ip6.h>
79 #ifdef INET6
80 #include <netinet6/ip6_var.h>
81 #endif
82 #include <netinet/in_pcb.h>
83 #ifdef INET6
84 #include <netinet6/in6_pcb.h>
85 #include <netinet/icmp6.h>
86 #endif
87 
88 #include <netipsec/ipsec.h>
89 #include <netipsec/ipsec_var.h>
90 #include <netipsec/ipsec_private.h>
91 #ifdef INET6
92 #include <netipsec/ipsec6.h>
93 #endif
94 #include <netipsec/ah_var.h>
95 #include <netipsec/esp_var.h>
96 #include <netipsec/ipcomp.h>		/*XXX*/
97 #include <netipsec/ipcomp_var.h>
98 
99 #include <netipsec/key.h>
100 #include <netipsec/keydb.h>
101 #include <netipsec/key_debug.h>
102 
103 #include <netipsec/xform.h>
104 
105 #include <netipsec/ipsec_osdep.h>
106 
107 #include <net/net_osdep.h>
108 
109 int ipsec_used = 0;
110 int ipsec_enabled = 1;
111 
112 #ifdef IPSEC_DEBUG
113 int ipsec_debug = 1;
114 
115 /*
116  * When set to 1, IPsec will send packets with the same sequence number.
117  * This allows to verify if the other side has proper replay attacks detection.
118  */
119 int ipsec_replay = 0;
120 
121 /*
122  * When set 1, IPsec will send packets with corrupted HMAC.
123  * This allows to verify if the other side properly detects modified packets.
124  */
125 int ipsec_integrity = 0;
126 #else
127 int ipsec_debug = 0;
128 #endif
129 
130 percpu_t *ipsecstat_percpu;
131 int ip4_ah_offsetmask = 0;	/* maybe IP_DF? */
132 int ip4_ipsec_dfbit = 2;	/* DF bit on encap. 0: clear 1: set 2: copy */
133 int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
134 int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
135 int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
136 int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
137 struct secpolicy ip4_def_policy;
138 int ip4_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
139 int ip4_esp_randpad = -1;
140 
141 #ifdef __NetBSD__
142 u_int ipsec_spdgen = 1;		/* SPD generation # */
143 
144 static struct secpolicy *ipsec_checkpcbcache (struct mbuf *,
145 	struct inpcbpolicy *, int);
146 static int ipsec_fillpcbcache (struct inpcbpolicy *, struct mbuf *,
147 	struct secpolicy *, int);
148 static int ipsec_invalpcbcache (struct inpcbpolicy *, int);
149 #endif /* __NetBSD__ */
150 
151 /*
152  * Crypto support requirements:
153  *
154  *  1	require hardware support
155  * -1	require software support
156  *  0	take anything
157  */
158 int	crypto_support = 0;
159 
160 static struct secpolicy *ipsec_getpolicybysock(struct mbuf *, u_int,
161 	PCB_T *, int *);
162 
163 #ifdef __FreeBSD__
164 SYSCTL_DECL(_net_inet_ipsec);
165 
166 /* net.inet.ipsec */
167 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY,
168 	def_policy, CTLFLAG_RW,	&ip4_def_policy.policy,	0, "");
169 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
170 	CTLFLAG_RW, &ip4_esp_trans_deflev,	0, "");
171 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
172 	CTLFLAG_RW, &ip4_esp_net_deflev,	0, "");
173 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
174 	CTLFLAG_RW, &ip4_ah_trans_deflev,	0, "");
175 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
176 	CTLFLAG_RW, &ip4_ah_net_deflev,	0, "");
177 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS,
178 	ah_cleartos, CTLFLAG_RW,	&ip4_ah_cleartos,	0, "");
179 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK,
180 	ah_offsetmask, CTLFLAG_RW,	&ip4_ah_offsetmask,	0, "");
181 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT,
182 	dfbit, CTLFLAG_RW,	&ip4_ipsec_dfbit,	0, "");
183 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN,
184 	ecn, CTLFLAG_RW,	&ip4_ipsec_ecn,	0, "");
185 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG,
186 	debug, CTLFLAG_RW,	&ipsec_debug,	0, "");
187 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
188 	esp_randpad, CTLFLAG_RW,	&ip4_esp_randpad,	0, "");
189 SYSCTL_INT(_net_inet_ipsec, OID_AUTO,
190 	crypto_support,	CTLFLAG_RW,	&crypto_support,0, "");
191 SYSCTL_STRUCT(_net_inet_ipsec, OID_AUTO,
192 	ipsecstats,	CTLFLAG_RD,	&newipsecstat,	newipsecstat, "");
193 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay, CTLFLAG_RW, &ipsec_replay, 0,
194 	"Emulate replay attack");
195 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity, CTLFLAG_RW,
196 	&ipsec_integrity, 0, "Emulate man-in-the-middle attack");
197 #endif /* __FreeBSD__ */
198 
199 #ifdef INET6
200 int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
201 int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
202 int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
203 int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
204 struct secpolicy ip6_def_policy;
205 int ip6_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
206 int ip6_esp_randpad = -1;
207 
208 
209 #ifdef __FreeBSD__
210 SYSCTL_DECL(_net_inet6_ipsec6);
211 
212 /* net.inet6.ipsec6 */
213 #ifdef COMPAT_KAME
214 SYSCTL_OID(_net_inet6_ipsec6, IPSECCTL_STATS, stats, CTLFLAG_RD,
215 	0,0, compat_ipsecstats_sysctl, "S", "");
216 #endif /* COMPAT_KAME */
217 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY,
218 	def_policy, CTLFLAG_RW,	&ip4_def_policy.policy,	0, "");
219 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
220 	CTLFLAG_RW, &ip6_esp_trans_deflev,	0, "");
221 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
222 	CTLFLAG_RW, &ip6_esp_net_deflev,	0, "");
223 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
224 	CTLFLAG_RW, &ip6_ah_trans_deflev,	0, "");
225 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
226 	CTLFLAG_RW, &ip6_ah_net_deflev,	0, "");
227 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
228 	ecn, CTLFLAG_RW,	&ip6_ipsec_ecn,	0, "");
229 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG,
230 	debug, CTLFLAG_RW,	&ipsec_debug,	0, "");
231 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
232 	esp_randpad, CTLFLAG_RW,	&ip6_esp_randpad,	0, "");
233 #endif /* __FreeBSD__ */
234 #endif /* INET6 */
235 
236 static int ipsec4_setspidx_inpcb (struct mbuf *, struct inpcb *);
237 #ifdef INET6
238 static int ipsec6_setspidx_in6pcb (struct mbuf *, struct in6pcb *);
239 #endif
240 static int ipsec_setspidx (struct mbuf *, struct secpolicyindex *, int);
241 static void ipsec4_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
242 static int ipsec4_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
243 #ifdef INET6
244 static void ipsec6_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
245 static int ipsec6_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
246 #endif
247 static void ipsec_delpcbpolicy (struct inpcbpolicy *);
248 static struct secpolicy *ipsec_deepcopy_policy (const struct secpolicy *);
249 static int ipsec_set_policy (struct secpolicy **, int, const void *, size_t,
250     kauth_cred_t);
251 static int ipsec_get_policy (struct secpolicy *, struct mbuf **);
252 static void vshiftl (unsigned char *, int, int);
253 static size_t ipsec_hdrsiz (const struct secpolicy *);
254 
255 #ifdef __NetBSD__
256 /*
257  * Try to validate and use cached policy on a PCB.
258  */
259 static struct secpolicy *
ipsec_checkpcbcache(struct mbuf * m,struct inpcbpolicy * pcbsp,int dir)260 ipsec_checkpcbcache(struct mbuf *m, struct inpcbpolicy *pcbsp, int dir)
261 {
262 	struct secpolicyindex spidx;
263 
264 	switch (dir) {
265 	case IPSEC_DIR_INBOUND:
266 	case IPSEC_DIR_OUTBOUND:
267 	case IPSEC_DIR_ANY:
268 		break;
269 	default:
270 		return NULL;
271 	}
272 #ifdef DIAGNOSTIC
273 	if (pcbsp == NULL) {
274 		printf("%s: NULL pcbsp\n", __func__);
275 		/* XXX panic? */
276 		return NULL;
277 	}
278 #endif
279 
280 #ifdef DIAGNOSTIC
281 	if (dir >= sizeof(pcbsp->sp_cache)/sizeof(pcbsp->sp_cache[0]))
282 		panic("dir too big in ipsec_checkpcbcache");
283 #endif
284 	/* SPD table change invalidate all the caches. */
285 	if (ipsec_spdgen != pcbsp->sp_cache[dir].cachegen) {
286 		ipsec_invalpcbcache(pcbsp, dir);
287 		return NULL;
288 	}
289 	if (!pcbsp->sp_cache[dir].cachesp)
290 		return NULL;
291 	if (pcbsp->sp_cache[dir].cachesp->state != IPSEC_SPSTATE_ALIVE) {
292 		ipsec_invalpcbcache(pcbsp, dir);
293 		return NULL;
294 	}
295 	if ((pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) == 0) {
296 		if (!pcbsp->sp_cache[dir].cachesp)
297 			return NULL;
298 		if (ipsec_setspidx(m, &spidx, 1) != 0)
299 			return NULL;
300 
301 		/*
302 		 * We have to make an exact match here since the cached rule
303 		 * might have lower priority than a rule that would otherwise
304 		 * have matched the packet.
305 		 */
306 
307 		if (memcmp(&pcbsp->sp_cache[dir].cacheidx, &spidx, sizeof(spidx)))
308 			return NULL;
309 
310 	} else {
311 		/*
312 		 * The pcb is connected, and the L4 code is sure that:
313 		 * - outgoing side uses inp_[lf]addr
314 		 * - incoming side looks up policy after inpcb lookup
315 		 * and address pair is know to be stable.  We do not need
316 		 * to generate spidx again, nor check the address match again.
317 		 *
318 		 * For IPv4/v6 SOCK_STREAM sockets, this assumptions holds
319 		 * and there are calls to ipsec_pcbconn() from in_pcbconnect().
320 		 */
321 	}
322 
323 	pcbsp->sp_cache[dir].cachesp->lastused = time_second;
324 	pcbsp->sp_cache[dir].cachesp->refcnt++;
325 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
326 	    printf("DP %s cause refcnt++:%d SP:%p\n", __func__,
327 	    pcbsp->sp_cache[dir].cachesp->refcnt,
328 	    pcbsp->sp_cache[dir].cachesp));
329 	return pcbsp->sp_cache[dir].cachesp;
330 }
331 
332 static int
ipsec_fillpcbcache(struct inpcbpolicy * pcbsp,struct mbuf * m,struct secpolicy * sp,int dir)333 ipsec_fillpcbcache(struct inpcbpolicy *pcbsp, struct mbuf *m,
334 	struct secpolicy *sp, int dir)
335 {
336 
337 	switch (dir) {
338 	case IPSEC_DIR_INBOUND:
339 	case IPSEC_DIR_OUTBOUND:
340 		break;
341 	default:
342 		return EINVAL;
343 	}
344 #ifdef DIAGNOSTIC
345 	if (dir >= sizeof(pcbsp->sp_cache)/sizeof(pcbsp->sp_cache[0]))
346 		panic("dir too big in ipsec_fillpcbcache");
347 #endif
348 
349 	if (pcbsp->sp_cache[dir].cachesp)
350 		KEY_FREESP(&pcbsp->sp_cache[dir].cachesp);
351 	pcbsp->sp_cache[dir].cachesp = NULL;
352 	pcbsp->sp_cache[dir].cachehint = IPSEC_PCBHINT_MAYBE;
353 	if (ipsec_setspidx(m, &pcbsp->sp_cache[dir].cacheidx, 1) != 0) {
354 		return EINVAL;
355 	}
356 	pcbsp->sp_cache[dir].cachesp = sp;
357 	if (pcbsp->sp_cache[dir].cachesp) {
358 		pcbsp->sp_cache[dir].cachesp->refcnt++;
359 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
360 		    printf("DP %s cause refcnt++:%d SP:%p\n", __func__,
361 		    pcbsp->sp_cache[dir].cachesp->refcnt,
362 		    pcbsp->sp_cache[dir].cachesp));
363 
364 		/*
365 		 * If the PCB is connected, we can remember a hint to
366 		 * possibly short-circuit IPsec processing in other places.
367 		 */
368 		if (pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) {
369 			switch (pcbsp->sp_cache[dir].cachesp->policy) {
370 			case IPSEC_POLICY_NONE:
371 			case IPSEC_POLICY_BYPASS:
372 				pcbsp->sp_cache[dir].cachehint =
373 					IPSEC_PCBHINT_NO;
374 				break;
375 			default:
376 				pcbsp->sp_cache[dir].cachehint =
377 					IPSEC_PCBHINT_YES;
378 			}
379 		}
380 	}
381 	pcbsp->sp_cache[dir].cachegen = ipsec_spdgen;
382 
383 	return 0;
384 }
385 
386 static int
ipsec_invalpcbcache(struct inpcbpolicy * pcbsp,int dir)387 ipsec_invalpcbcache(struct inpcbpolicy *pcbsp, int dir)
388 {
389 	int i;
390 
391 	for (i = IPSEC_DIR_INBOUND; i <= IPSEC_DIR_OUTBOUND; i++) {
392 		if (dir != IPSEC_DIR_ANY && i != dir)
393 			continue;
394 		if (pcbsp->sp_cache[i].cachesp)
395 			KEY_FREESP(&pcbsp->sp_cache[i].cachesp);
396 		pcbsp->sp_cache[i].cachesp = NULL;
397 		pcbsp->sp_cache[i].cachehint = IPSEC_PCBHINT_MAYBE;
398 		pcbsp->sp_cache[i].cachegen = 0;
399 		memset(&pcbsp->sp_cache[i].cacheidx, 0,
400 			  sizeof(pcbsp->sp_cache[i].cacheidx));
401 	}
402 	return 0;
403 }
404 
405 void
ipsec_pcbconn(struct inpcbpolicy * pcbsp)406 ipsec_pcbconn(struct inpcbpolicy *pcbsp)
407 {
408 
409 	pcbsp->sp_cacheflags |= IPSEC_PCBSP_CONNECTED;
410 	ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
411 }
412 
413 void
ipsec_pcbdisconn(struct inpcbpolicy * pcbsp)414 ipsec_pcbdisconn(struct inpcbpolicy *pcbsp)
415 {
416 
417 	pcbsp->sp_cacheflags &= ~IPSEC_PCBSP_CONNECTED;
418 	ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
419 }
420 
421 void
ipsec_invalpcbcacheall(void)422 ipsec_invalpcbcacheall(void)
423 {
424 
425 	if (ipsec_spdgen == UINT_MAX)
426 		ipsec_spdgen = 1;
427 	else
428 		ipsec_spdgen++;
429 }
430 #endif /* __NetBSD__ */
431 
432 /*
433  * Return a held reference to the default SP.
434  */
435 static struct secpolicy *
key_allocsp_default(int af,const char * where,int tag)436 key_allocsp_default(int af, const char *where, int tag)
437 {
438 	struct secpolicy *sp;
439 
440 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
441 	    printf("DP %s from %s:%u\n", __func__, where, tag));
442 
443     switch(af) {
444         case AF_INET:
445 	        sp = &ip4_def_policy;
446             break;
447 #ifdef INET6
448         case AF_INET6:
449             sp = &ip6_def_policy;
450             break;
451 #endif
452         default:
453 	        KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
454 		    printf("%s: unexpected protocol family %u\n", __func__,
455                     af));
456             return NULL;
457     }
458 
459 	if (sp->policy != IPSEC_POLICY_DISCARD &&
460 		sp->policy != IPSEC_POLICY_NONE) {
461 		ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
462 		    sp->policy, IPSEC_POLICY_NONE));
463 		sp->policy = IPSEC_POLICY_NONE;
464 	}
465 	sp->refcnt++;
466 
467 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP, printf("DP %s returns SP:%p (%u)\n",
468 	    __func__, sp, sp->refcnt));
469 	return sp;
470 }
471 #define	KEY_ALLOCSP_DEFAULT(af) \
472 	key_allocsp_default((af),__FILE__, __LINE__)
473 
474 /*
475  * For OUTBOUND packet having a socket. Searching SPD for packet,
476  * and return a pointer to SP.
477  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
478  *		0	: bypass
479  *		EACCES	: discard packet.
480  *		ENOENT	: ipsec_acquire() in progress, maybe.
481  *		others	: error occurred.
482  *	others:	a pointer to SP
483  *
484  * NOTE: IPv6 mapped address concern is implemented here.
485  */
486 struct secpolicy *
ipsec_getpolicy(const struct tdb_ident * tdbi,u_int dir)487 ipsec_getpolicy(const struct tdb_ident *tdbi, u_int dir)
488 {
489 	struct secpolicy *sp;
490 
491 	IPSEC_ASSERT(tdbi != NULL, ("%s: null tdbi", __func__));
492 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
493 	    ("%s: invalid direction %u", __func__, dir));
494 
495 	sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
496 	if (sp == NULL)			/*XXX????*/
497 		sp = KEY_ALLOCSP_DEFAULT(tdbi->dst.sa.sa_family);
498 	IPSEC_ASSERT(sp != NULL, ("%s: null SP", __func__));
499 	return sp;
500 }
501 
502 /*
503  * For OUTBOUND packet having a socket. Searching SPD for packet,
504  * and return a pointer to SP.
505  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
506  *		0	: bypass
507  *		EACCES	: discard packet.
508  *		ENOENT	: ipsec_acquire() in progress, maybe.
509  *		others	: error occurred.
510  *	others:	a pointer to SP
511  *
512  * NOTE: IPv6 mapped address concern is implemented here.
513  */
514 static struct secpolicy *
ipsec_getpolicybysock(struct mbuf * m,u_int dir,PCB_T * inp,int * error)515 ipsec_getpolicybysock(struct mbuf *m, u_int dir, PCB_T *inp, int *error)
516 {
517 	struct inpcbpolicy *pcbsp = NULL;
518 	struct secpolicy *currsp = NULL;	/* policy on socket */
519 	struct secpolicy *sp;
520 	int af;
521 
522 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
523 	IPSEC_ASSERT(inp != NULL, ("%s: null inpcb", __func__));
524 	IPSEC_ASSERT(error != NULL, ("%s: null error", __func__));
525 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
526 	    ("%s: invalid direction %u", __func__, dir));
527 
528 	IPSEC_ASSERT(PCB_SOCKET(inp) != NULL, ("%s: null socket", __func__));
529 
530 	/* XXX FIXME inpcb/in6pcb  vs socket*/
531 	af = PCB_FAMILY(inp);
532 	IPSEC_ASSERT(af == AF_INET || af == AF_INET6,
533 	    ("%s: unexpected protocol family %u", __func__, af));
534 
535 #ifdef __NetBSD__
536 	IPSEC_ASSERT(inp->inph_sp != NULL, ("null PCB policy cache"));
537 	/* If we have a cached entry, and if it is still valid, use it. */
538 	IPSEC_STATINC(IPSEC_STAT_SPDCACHELOOKUP);
539 	currsp = ipsec_checkpcbcache(m, /*inpcb_hdr*/inp->inph_sp, dir);
540 	if (currsp) {
541 		*error = 0;
542 		return currsp;
543 	}
544 	IPSEC_STATINC(IPSEC_STAT_SPDCACHEMISS);
545 #endif /* __NetBSD__ */
546 
547 	switch (af) {
548 	case AF_INET: {
549 		struct inpcb *in4p = PCB_TO_IN4PCB(inp);
550 		/* set spidx in pcb */
551 		*error = ipsec4_setspidx_inpcb(m, in4p);
552 		pcbsp = in4p->inp_sp;
553 		break;
554 		}
555 
556 #if defined(INET6)
557 	case AF_INET6: {
558 		struct in6pcb *in6p = PCB_TO_IN6PCB(inp);
559 		/* set spidx in pcb */
560 		*error = ipsec6_setspidx_in6pcb(m, in6p);
561 		pcbsp = in6p->in6p_sp;
562 		break;
563 		}
564 #endif
565 	default:
566 		*error = EPFNOSUPPORT;
567 		break;
568 	}
569 	if (*error)
570 		return NULL;
571 
572 	IPSEC_ASSERT(pcbsp != NULL, ("%s: null pcbsp", __func__));
573 	switch (dir) {
574 	case IPSEC_DIR_INBOUND:
575 		currsp = pcbsp->sp_in;
576 		break;
577 	case IPSEC_DIR_OUTBOUND:
578 		currsp = pcbsp->sp_out;
579 		break;
580 	}
581 	IPSEC_ASSERT(currsp != NULL, ("%s: null currsp", __func__));
582 
583 	if (pcbsp->priv) {			/* when privilieged socket */
584 		switch (currsp->policy) {
585 		case IPSEC_POLICY_BYPASS:
586 		case IPSEC_POLICY_IPSEC:
587 			currsp->refcnt++;
588 			sp = currsp;
589 			break;
590 
591 		case IPSEC_POLICY_ENTRUST:
592 			/* look for a policy in SPD */
593 			sp = KEY_ALLOCSP(&currsp->spidx, dir);
594 			if (sp == NULL)		/* no SP found */
595 				sp = KEY_ALLOCSP_DEFAULT(af);
596 			break;
597 
598 		default:
599 			ipseclog((LOG_ERR, "%s: Invalid policy for PCB %d\n",
600 			    __func__, currsp->policy));
601 			*error = EINVAL;
602 			return NULL;
603 		}
604 	} else {				/* unpriv, SPD has policy */
605 		sp = KEY_ALLOCSP(&currsp->spidx, dir);
606 		if (sp == NULL) {		/* no SP found */
607 			switch (currsp->policy) {
608 			case IPSEC_POLICY_BYPASS:
609 				ipseclog((LOG_ERR, "%s: Illegal policy for "
610 				    "non-priviliged defined %d\n", __func__,
611 				    currsp->policy));
612 				*error = EINVAL;
613 				return NULL;
614 
615 			case IPSEC_POLICY_ENTRUST:
616 				sp = KEY_ALLOCSP_DEFAULT(af);
617 				break;
618 
619 			case IPSEC_POLICY_IPSEC:
620 				currsp->refcnt++;
621 				sp = currsp;
622 				break;
623 
624 			default:
625 				ipseclog((LOG_ERR, "%s: Invalid policy for "
626 				    "PCB %d\n", __func__, currsp->policy));
627 				*error = EINVAL;
628 				return NULL;
629 			}
630 		}
631 	}
632 	IPSEC_ASSERT(sp != NULL,
633 	    ("%s: null SP (priv %u policy %u", __func__, pcbsp->priv,
634 	    currsp->policy));
635 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
636 	    printf("DP %s (priv %u policy %u) allocates SP:%p (refcnt %u)\n",
637 	    __func__, pcbsp->priv, currsp->policy, sp, sp->refcnt));
638 #ifdef __NetBSD__
639 	ipsec_fillpcbcache(pcbsp, m, sp, dir);
640 #endif /* __NetBSD__ */
641 	return sp;
642 }
643 
644 /*
645  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
646  * and return a pointer to SP.
647  * OUT:	positive: a pointer to the entry for security policy leaf matched.
648  *	NULL:	no apropreate SP found, the following value is set to error.
649  *		0	: bypass
650  *		EACCES	: discard packet.
651  *		ENOENT	: ipsec_acquire() in progress, maybe.
652  *		others	: error occurred.
653  */
654 struct secpolicy *
ipsec_getpolicybyaddr(struct mbuf * m,u_int dir,int flag,int * error)655 ipsec_getpolicybyaddr(struct mbuf *m, u_int dir, int flag, int *error)
656 {
657 	struct secpolicyindex spidx;
658 	struct secpolicy *sp;
659 
660 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
661 	IPSEC_ASSERT(error != NULL, ("%s: null error", __func__));
662 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
663 	    ("%s: invalid direction %u", __func__, dir));
664 
665 	sp = NULL;
666 
667 	/* Make an index to look for a policy. */
668 	*error = ipsec_setspidx(m, &spidx, (flag & IP_FORWARDING) ? 0 : 1);
669 	if (*error != 0) {
670 		DPRINTF(("%s: setpidx failed, dir %u flag %u\n", __func__,
671 		    dir, flag));
672 		memset(&spidx, 0, sizeof (spidx));
673 		return NULL;
674 	}
675 
676 	spidx.dir = dir;
677 
678 	if (key_havesp(dir)) {
679 		sp = KEY_ALLOCSP(&spidx, dir);
680 	}
681 
682 	if (sp == NULL)			/* no SP found, use system default */
683 		sp = KEY_ALLOCSP_DEFAULT(spidx.dst.sa.sa_family);
684 	IPSEC_ASSERT(sp != NULL, ("%s: null SP", __func__));
685 	return sp;
686 }
687 
688 struct secpolicy *
ipsec4_checkpolicy(struct mbuf * m,u_int dir,u_int flag,int * error,struct inpcb * inp)689 ipsec4_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
690 		   struct inpcb *inp)
691 {
692 	struct secpolicy *sp;
693 
694 	*error = 0;
695 
696 
697 	/* XXX KAME IPv6 calls us with non-null inp but bogus inp_socket? */
698 	if (inp == NULL || inp->inp_socket == NULL) {
699 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
700 	} else
701 		sp = ipsec_getpolicybysock(m, dir, IN4PCB_TO_PCB(inp), error);
702 	if (sp == NULL) {
703 		IPSEC_ASSERT(*error != 0,
704 		    ("%s: getpolicy failed w/o error", __func__));
705 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
706 		return NULL;
707 	}
708 	IPSEC_ASSERT(*error == 0, ("%s: sp w/ error set to %u", __func__,
709 	    *error));
710 	switch (sp->policy) {
711 	case IPSEC_POLICY_ENTRUST:
712 	default:
713 		printf("%s: invalid policy %u\n", __func__, sp->policy);
714 		/* fall thru... */
715 	case IPSEC_POLICY_DISCARD:
716 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
717 		*error = -EINVAL;	/* packet is discarded by caller */
718 		break;
719 	case IPSEC_POLICY_BYPASS:
720 	case IPSEC_POLICY_NONE:
721 		KEY_FREESP(&sp);
722 		sp = NULL;		/* NB: force NULL result */
723 		break;
724 	case IPSEC_POLICY_IPSEC:
725 		if (sp->req == NULL)	/* acquire an SA */
726 			*error = key_spdacquire(sp);
727 		break;
728 	}
729 	if (*error != 0) {
730 		KEY_FREESP(&sp);
731 		sp = NULL;
732 		DPRINTF(("%s: done, error %d\n", __func__, *error));
733 	}
734 	return sp;
735 }
736 
737 int
ipsec4_output(struct mbuf * m,struct socket * so,int flags,struct secpolicy ** sp_out,u_long * mtu,bool * natt_frag,bool * done)738 ipsec4_output(struct mbuf *m, struct socket *so, int flags,
739     struct secpolicy **sp_out, u_long *mtu, bool *natt_frag, bool *done)
740 {
741 	const struct ip *ip = mtod(m, const struct ip *);
742 	struct secpolicy *sp = NULL;
743 	struct inpcb *inp;
744 	int error, s;
745 
746 	inp = (so && so->so_proto->pr_domain->dom_family == AF_INET) ?
747 	    (struct inpcb *)so->so_pcb : NULL;
748 
749 	/*
750 	 * Check the security policy (SP) for the packet and, if required,
751 	 * do IPsec-related processing.  There are two cases here; the first
752 	 * time a packet is sent through it will be untagged and handled by
753 	 * ipsec4_checkpolicy().  If the packet is resubmitted to ip_output
754 	 * (e.g. after AH, ESP, etc. processing), there will be a tag to
755 	 * bypass the lookup and related policy checking.
756 	 */
757 	if (ipsec_outdone(m)) {
758 		return 0;
759 	}
760 	s = splsoftnet();
761 	if (inp && IPSEC_PCB_SKIP_IPSEC(inp->inp_sp, IPSEC_DIR_OUTBOUND)) {
762 		splx(s);
763 		return 0;
764 	}
765 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, inp);
766 
767 	/*
768 	 * There are four return cases:
769 	 *	sp != NULL			apply IPsec policy
770 	 *	sp == NULL, error == 0		no IPsec handling needed
771 	 *	sp == NULL, error == -EINVAL	discard packet w/o error
772 	 *	sp == NULL, error != 0		discard packet, report error
773 	 */
774 	if (sp == NULL) {
775 		splx(s);
776 		if (error) {
777 			/*
778 			 * Hack: -EINVAL is used to signal that a packet
779 			 * should be silently discarded.  This is typically
780 			 * because we asked key management for an SA and
781 			 * it was delayed (e.g. kicked up to IKE).
782 			 */
783 			if (error == -EINVAL)
784 				error = 0;
785 			m_freem(m);
786 			*done = true;
787 			return error;
788 		}
789 		/* No IPsec processing for this packet. */
790 		return 0;
791 	}
792 	*sp_out = sp;
793 
794 	/*
795 	 * NAT-T ESP fragmentation: do not do IPSec processing now,
796 	 * we will do it on each fragmented packet.
797 	 */
798 	if (sp->req->sav && (sp->req->sav->natt_type &
799 	    (UDP_ENCAP_ESPINUDP|UDP_ENCAP_ESPINUDP_NON_IKE))) {
800 		if (ntohs(ip->ip_len) > sp->req->sav->esp_frag) {
801 			*mtu = sp->req->sav->esp_frag;
802 			*natt_frag = true;
803 			splx(s);
804 			return 0;
805 		}
806 	}
807 
808 	/*
809 	 * Do delayed checksums now because we send before
810 	 * this is done in the normal processing path.
811 	 */
812 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
813 		in_delayed_cksum(m);
814 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
815 	}
816 
817 	/* Note: callee frees mbuf */
818 	error = ipsec4_process_packet(m, sp->req, flags, 0);
819 	/*
820 	 * Preserve KAME behaviour: ENOENT can be returned
821 	 * when an SA acquire is in progress.  Don't propagate
822 	 * this to user-level; it confuses applications.
823 	 *
824 	 * XXX this will go away when the SADB is redone.
825 	 */
826 	if (error == ENOENT)
827 		error = 0;
828 	splx(s);
829 	*done = true;
830 	return error;
831 }
832 
833 int
ipsec4_input(struct mbuf * m,int flags)834 ipsec4_input(struct mbuf *m, int flags)
835 {
836 	struct m_tag *mtag;
837 	struct tdb_ident *tdbi;
838 	struct secpolicy *sp;
839 	int error, s;
840 
841 	/*
842 	 * Check if the packet has already had IPsec processing done.
843 	 * If so, then just pass it along.  This tag gets set during AH,
844 	 * ESP, etc. input handling, before the packet is returned to
845 	 * the IP input queue for delivery.
846 	 */
847 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
848 	s = splsoftnet();
849 	if (mtag != NULL) {
850 		tdbi = (struct tdb_ident *)(mtag + 1);
851 		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
852 	} else {
853 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
854 		    IP_FORWARDING, &error);
855 	}
856 	if (sp == NULL) {
857 		splx(s);
858 		return EINVAL;
859 	}
860 
861 	/*
862 	 * Check security policy against packet attributes.
863 	 */
864 	error = ipsec_in_reject(sp, m);
865 	KEY_FREESP(&sp);
866 	splx(s);
867 	if (error) {
868 		return error;
869 	}
870 
871 	if (flags == 0) {
872 		/* We are done. */
873 		return 0;
874 	}
875 
876 	/*
877 	 * Peek at the outbound SP for this packet to determine if
878 	 * it is a Fast Forward candidate.
879 	 */
880 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
881 	if (mtag != NULL) {
882 		m->m_flags &= ~M_CANFASTFWD;
883 		return 0;
884 	}
885 
886 	s = splsoftnet();
887 	sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, NULL);
888 	if (sp != NULL) {
889 		m->m_flags &= ~M_CANFASTFWD;
890 		KEY_FREESP(&sp);
891 	}
892 	splx(s);
893 	return 0;
894 }
895 
896 int
ipsec4_forward(struct mbuf * m,int * destmtu)897 ipsec4_forward(struct mbuf *m, int *destmtu)
898 {
899 	/*
900 	 * If the packet is routed over IPsec tunnel, tell the
901 	 * originator the tunnel MTU.
902 	 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
903 	 * XXX quickhack!!!
904 	 */
905 	struct secpolicy *sp;
906 	size_t ipsechdr;
907 	int error;
908 
909 	sp = ipsec4_getpolicybyaddr(m,
910 	    IPSEC_DIR_OUTBOUND, IP_FORWARDING, &error);
911 	if (sp == NULL) {
912 		return EINVAL;
913 	}
914 
915 	/* Count IPsec header size. */
916 	ipsechdr = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, NULL);
917 
918 	/*
919 	 * Find the correct route for outer IPv4 header, compute tunnel MTU.
920 	 */
921 	if (sp->req && sp->req->sav && sp->req->sav->sah) {
922 		struct route *ro;
923 		struct rtentry *rt;
924 
925 		ro = &sp->req->sav->sah->sa_route;
926 		rt = rtcache_validate(ro);
927 		if (rt && rt->rt_ifp) {
928 			*destmtu = rt->rt_rmx.rmx_mtu ?
929 			    rt->rt_rmx.rmx_mtu : rt->rt_ifp->if_mtu;
930 			*destmtu -= ipsechdr;
931 		}
932 	}
933 	KEY_FREESP(&sp);
934 	return 0;
935 }
936 
937 #ifdef INET6
938 struct secpolicy *
ipsec6_checkpolicy(struct mbuf * m,u_int dir,u_int flag,int * error,struct in6pcb * in6p)939 ipsec6_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
940 	 	   struct in6pcb *in6p)
941 {
942 	struct secpolicy *sp;
943 
944 	*error = 0;
945 
946 
947 	/* XXX KAME IPv6 calls us with non-null inp but bogus inp_socket? */
948 	if (in6p == NULL || in6p->in6p_socket == NULL) {
949 		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
950 	} else
951 		sp = ipsec_getpolicybysock(m, dir, IN6PCB_TO_PCB(in6p), error);
952 	if (sp == NULL) {
953 		IPSEC_ASSERT(*error != 0, ("%s: getpolicy failed w/o error",
954 		    __func__));
955 		IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
956 		return NULL;
957 	}
958 	IPSEC_ASSERT(*error == 0, ("%s: sp w/ error set to %u", __func__,
959 	    *error));
960 	switch (sp->policy) {
961 	case IPSEC_POLICY_ENTRUST:
962 	default:
963 		printf("%s: invalid policy %u\n", __func__, sp->policy);
964 		/* fall thru... */
965 	case IPSEC_POLICY_DISCARD:
966 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
967 		*error = -EINVAL;   /* packet is discarded by caller */
968 		break;
969 	case IPSEC_POLICY_BYPASS:
970 	case IPSEC_POLICY_NONE:
971 		KEY_FREESP(&sp);
972 		sp = NULL;	  /* NB: force NULL result */
973 		break;
974 	case IPSEC_POLICY_IPSEC:
975 		if (sp->req == NULL)	/* acquire an SA */
976 			*error = key_spdacquire(sp);
977 		break;
978 	}
979 	if (*error != 0) {
980 		KEY_FREESP(&sp);
981 		sp = NULL;
982 		DPRINTF(("%s: done, error %d\n", __func__, *error));
983 	}
984 	return sp;
985 }
986 #endif /* INET6 */
987 
988 static int
ipsec4_setspidx_inpcb(struct mbuf * m,struct inpcb * pcb)989 ipsec4_setspidx_inpcb(struct mbuf *m, struct inpcb *pcb)
990 {
991 	int error;
992 
993 	IPSEC_ASSERT(pcb != NULL, ("%s: null pcb", __func__));
994 	IPSEC_ASSERT(pcb->inp_sp != NULL, ("%s: null inp_sp", __func__));
995 	IPSEC_ASSERT(pcb->inp_sp->sp_out != NULL && pcb->inp_sp->sp_in != NULL,
996 	    ("%s: null sp_in || sp_out", __func__));
997 
998 	error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
999 	if (error == 0) {
1000 		pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
1001 		pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
1002 		pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
1003 	} else {
1004 		memset(&pcb->inp_sp->sp_in->spidx, 0,
1005 			sizeof (pcb->inp_sp->sp_in->spidx));
1006 		memset(&pcb->inp_sp->sp_out->spidx, 0,
1007 			sizeof (pcb->inp_sp->sp_in->spidx));
1008 	}
1009 	return error;
1010 }
1011 
1012 #ifdef INET6
1013 static int
ipsec6_setspidx_in6pcb(struct mbuf * m,struct in6pcb * pcb)1014 ipsec6_setspidx_in6pcb(struct mbuf *m, struct in6pcb *pcb)
1015 {
1016 	struct secpolicyindex *spidx;
1017 	int error;
1018 
1019 	IPSEC_ASSERT(pcb != NULL, ("%s: null pcb", __func__));
1020 	IPSEC_ASSERT(pcb->in6p_sp != NULL, ("%s: null inp_sp", __func__));
1021 	IPSEC_ASSERT(pcb->in6p_sp->sp_out != NULL &&
1022 	    pcb->in6p_sp->sp_in != NULL, ("%s: null sp_in || sp_out",
1023 	    __func__));
1024 
1025 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
1026 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
1027 
1028 	spidx = &pcb->in6p_sp->sp_in->spidx;
1029 	error = ipsec_setspidx(m, spidx, 1);
1030 	if (error)
1031 		goto bad;
1032 	spidx->dir = IPSEC_DIR_INBOUND;
1033 
1034 	spidx = &pcb->in6p_sp->sp_out->spidx;
1035 	error = ipsec_setspidx(m, spidx, 1);
1036 	if (error)
1037 		goto bad;
1038 	spidx->dir = IPSEC_DIR_OUTBOUND;
1039 
1040 	return 0;
1041 
1042 bad:
1043 	memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
1044 	memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
1045 	return error;
1046 }
1047 #endif
1048 
1049 /*
1050  * configure security policy index (src/dst/proto/sport/dport)
1051  * by looking at the content of mbuf.
1052  * the caller is responsible for error recovery (like clearing up spidx).
1053  */
1054 static int
ipsec_setspidx(struct mbuf * m,struct secpolicyindex * spidx,int needport)1055 ipsec_setspidx(struct mbuf *m, struct secpolicyindex *spidx, int needport)
1056 {
1057 	struct ip *ip = NULL;
1058 	struct ip ipbuf;
1059 	u_int v;
1060 	struct mbuf *n;
1061 	int len;
1062 	int error;
1063 
1064 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
1065 
1066 	/*
1067 	 * validate m->m_pkthdr.len.  we see incorrect length if we
1068 	 * mistakenly call this function with inconsistent mbuf chain
1069 	 * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
1070 	 */
1071 	len = 0;
1072 	for (n = m; n; n = n->m_next)
1073 		len += n->m_len;
1074 	if (m->m_pkthdr.len != len) {
1075 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: total of m_len(%d) "
1076 		    "!= pkthdr.len(%d), ignored.\n", __func__, len,
1077 		    m->m_pkthdr.len));
1078 		return EINVAL;
1079 	}
1080 
1081 	if (m->m_pkthdr.len < sizeof(struct ip)) {
1082 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: pkthdr.len(%d) < "
1083 		    "sizeof(struct ip), ignored.\n", __func__,
1084 		    m->m_pkthdr.len));
1085 		return EINVAL;
1086 	}
1087 
1088 	if (m->m_len >= sizeof(*ip))
1089 		ip = mtod(m, struct ip *);
1090 	else {
1091 		m_copydata(m, 0, sizeof(ipbuf), &ipbuf);
1092 		ip = &ipbuf;
1093 	}
1094 	v = ip->ip_v;
1095 	switch (v) {
1096 	case 4:
1097 		error = ipsec4_setspidx_ipaddr(m, spidx);
1098 		if (error)
1099 			return error;
1100 		ipsec4_get_ulp(m, spidx, needport);
1101 		return 0;
1102 #ifdef INET6
1103 	case 6:
1104 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
1105 			KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: "
1106 			    "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
1107 			    "ignored.\n", __func__, m->m_pkthdr.len));
1108 			return EINVAL;
1109 		}
1110 		error = ipsec6_setspidx_ipaddr(m, spidx);
1111 		if (error)
1112 			return error;
1113 		ipsec6_get_ulp(m, spidx, needport);
1114 		return 0;
1115 #endif
1116 	default:
1117 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: unknown IP version "
1118 		    "%u, ignored.\n", __func__, v));
1119 		return EINVAL;
1120 	}
1121 }
1122 
1123 static void
ipsec4_get_ulp(struct mbuf * m,struct secpolicyindex * spidx,int needport)1124 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
1125 {
1126 	u_int8_t nxt;
1127 	int off;
1128 
1129 	/* sanity check */
1130 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
1131 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
1132 	    ("%s: packet too short", __func__));
1133 
1134 	/* NB: ip_input() flips it into host endian XXX need more checking */
1135 	if (m->m_len >= sizeof(struct ip)) {
1136 		struct ip *ip = mtod(m, struct ip *);
1137 		if (ip->ip_off & IP_OFF_CONVERT(IP_MF | IP_OFFMASK))
1138 			goto done;
1139 		off = ip->ip_hl << 2;
1140 		nxt = ip->ip_p;
1141 	} else {
1142 		struct ip ih;
1143 
1144 		m_copydata(m, 0, sizeof (struct ip), &ih);
1145 		if (ih.ip_off & IP_OFF_CONVERT(IP_MF | IP_OFFMASK))
1146 			goto done;
1147 		off = ih.ip_hl << 2;
1148 		nxt = ih.ip_p;
1149 	}
1150 
1151 	while (off < m->m_pkthdr.len) {
1152 		struct ip6_ext ip6e;
1153 		struct tcphdr th;
1154 		struct udphdr uh;
1155 		struct icmp icmph;
1156 
1157 		switch (nxt) {
1158 		case IPPROTO_TCP:
1159 			spidx->ul_proto = nxt;
1160 			if (!needport)
1161 				goto done_proto;
1162 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
1163 				goto done;
1164 			m_copydata(m, off, sizeof (th), &th);
1165 			spidx->src.sin.sin_port = th.th_sport;
1166 			spidx->dst.sin.sin_port = th.th_dport;
1167 			return;
1168 		case IPPROTO_UDP:
1169 			spidx->ul_proto = nxt;
1170 			if (!needport)
1171 				goto done_proto;
1172 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
1173 				goto done;
1174 			m_copydata(m, off, sizeof (uh), &uh);
1175 			spidx->src.sin.sin_port = uh.uh_sport;
1176 			spidx->dst.sin.sin_port = uh.uh_dport;
1177 			return;
1178 		case IPPROTO_AH:
1179 			if (m->m_pkthdr.len > off + sizeof(ip6e))
1180 				goto done;
1181 			/* XXX sigh, this works but is totally bogus */
1182 			m_copydata(m, off, sizeof(ip6e), &ip6e);
1183 			off += (ip6e.ip6e_len + 2) << 2;
1184 			nxt = ip6e.ip6e_nxt;
1185 			break;
1186 		case IPPROTO_ICMP:
1187 			spidx->ul_proto = nxt;
1188 			if (off + sizeof(struct icmp) > m->m_pkthdr.len)
1189 				return;
1190 			m_copydata(m, off, sizeof(icmph), &icmph);
1191 			((struct sockaddr_in *)&spidx->src)->sin_port =
1192 			    htons((uint16_t)icmph.icmp_type);
1193 			((struct sockaddr_in *)&spidx->dst)->sin_port =
1194 			    htons((uint16_t)icmph.icmp_code);
1195 			return;
1196 		default:
1197 			/* XXX intermediate headers??? */
1198 			spidx->ul_proto = nxt;
1199 			goto done_proto;
1200 		}
1201 	}
1202 done:
1203 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
1204 done_proto:
1205 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
1206 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
1207 }
1208 
1209 /* assumes that m is sane */
1210 static int
ipsec4_setspidx_ipaddr(struct mbuf * m,struct secpolicyindex * spidx)1211 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
1212 {
1213 	static const struct sockaddr_in template = {
1214 		sizeof (struct sockaddr_in),
1215 		AF_INET,
1216 		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
1217 	};
1218 
1219 	spidx->src.sin = template;
1220 	spidx->dst.sin = template;
1221 
1222 	if (m->m_len < sizeof (struct ip)) {
1223 		m_copydata(m, offsetof(struct ip, ip_src),
1224 			   sizeof (struct  in_addr),
1225 			   &spidx->src.sin.sin_addr);
1226 		m_copydata(m, offsetof(struct ip, ip_dst),
1227 			   sizeof (struct  in_addr),
1228 			   &spidx->dst.sin.sin_addr);
1229 	} else {
1230 		struct ip *ip = mtod(m, struct ip *);
1231 		spidx->src.sin.sin_addr = ip->ip_src;
1232 		spidx->dst.sin.sin_addr = ip->ip_dst;
1233 	}
1234 
1235 	spidx->prefs = sizeof(struct in_addr) << 3;
1236 	spidx->prefd = sizeof(struct in_addr) << 3;
1237 
1238 	return 0;
1239 }
1240 
1241 #ifdef INET6
1242 static void
ipsec6_get_ulp(struct mbuf * m,struct secpolicyindex * spidx,int needport)1243 ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *spidx,
1244 	       int needport)
1245 {
1246 	int off, nxt;
1247 	struct tcphdr th;
1248 	struct udphdr uh;
1249 	struct icmp6_hdr icmph;
1250 
1251 	/* sanity check */
1252 	if (m == NULL)
1253 		panic("%s: NULL pointer was passed", __func__);
1254 
1255 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s:\n", __func__);
1256 	    kdebug_mbuf(m));
1257 
1258 	/* set default */
1259 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
1260 	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
1261 	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
1262 
1263 	nxt = -1;
1264 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
1265 	if (off < 0 || m->m_pkthdr.len < off)
1266 		return;
1267 
1268 	switch (nxt) {
1269 	case IPPROTO_TCP:
1270 		spidx->ul_proto = nxt;
1271 		if (!needport)
1272 			break;
1273 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
1274 			break;
1275 		m_copydata(m, off, sizeof(th), &th);
1276 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
1277 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
1278 		break;
1279 	case IPPROTO_UDP:
1280 		spidx->ul_proto = nxt;
1281 		if (!needport)
1282 			break;
1283 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
1284 			break;
1285 		m_copydata(m, off, sizeof(uh), &uh);
1286 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
1287 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
1288 		break;
1289 	case IPPROTO_ICMPV6:
1290 		spidx->ul_proto = nxt;
1291 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
1292 			break;
1293 		m_copydata(m, off, sizeof(icmph), &icmph);
1294 		((struct sockaddr_in6 *)&spidx->src)->sin6_port =
1295 		    htons((uint16_t)icmph.icmp6_type);
1296 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
1297 		    htons((uint16_t)icmph.icmp6_code);
1298 		break;
1299 	default:
1300 		/* XXX intermediate headers??? */
1301 		spidx->ul_proto = nxt;
1302 		break;
1303 	}
1304 }
1305 
1306 /* assumes that m is sane */
1307 static int
ipsec6_setspidx_ipaddr(struct mbuf * m,struct secpolicyindex * spidx)1308 ipsec6_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
1309 {
1310 	struct ip6_hdr *ip6 = NULL;
1311 	struct ip6_hdr ip6buf;
1312 	struct sockaddr_in6 *sin6;
1313 
1314 	if (m->m_len >= sizeof(*ip6))
1315 		ip6 = mtod(m, struct ip6_hdr *);
1316 	else {
1317 		m_copydata(m, 0, sizeof(ip6buf), &ip6buf);
1318 		ip6 = &ip6buf;
1319 	}
1320 
1321 	sin6 = (struct sockaddr_in6 *)&spidx->src;
1322 	memset(sin6, 0, sizeof(*sin6));
1323 	sin6->sin6_family = AF_INET6;
1324 	sin6->sin6_len = sizeof(struct sockaddr_in6);
1325 	memcpy(&sin6->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));
1326 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
1327 		sin6->sin6_addr.s6_addr16[1] = 0;
1328 		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
1329 	}
1330 	spidx->prefs = sizeof(struct in6_addr) << 3;
1331 
1332 	sin6 = (struct sockaddr_in6 *)&spidx->dst;
1333 	memset(sin6, 0, sizeof(*sin6));
1334 	sin6->sin6_family = AF_INET6;
1335 	sin6->sin6_len = sizeof(struct sockaddr_in6);
1336 	memcpy(&sin6->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
1337 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
1338 		sin6->sin6_addr.s6_addr16[1] = 0;
1339 		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
1340 	}
1341 	spidx->prefd = sizeof(struct in6_addr) << 3;
1342 
1343 	return 0;
1344 }
1345 #endif
1346 
1347 static void
ipsec_delpcbpolicy(struct inpcbpolicy * p)1348 ipsec_delpcbpolicy(struct inpcbpolicy *p)
1349 {
1350 	free(p, M_SECA);
1351 }
1352 
1353 /* initialize policy in PCB */
1354 int
ipsec_init_policy(struct socket * so,struct inpcbpolicy ** policy)1355 ipsec_init_policy(struct socket *so, struct inpcbpolicy **policy)
1356 {
1357 	struct inpcbpolicy *new;
1358 
1359 	/* sanity check. */
1360 	if (so == NULL || policy == NULL)
1361 		panic("%s: NULL pointer was passed", __func__);
1362 
1363 	new = malloc(sizeof(*new), M_SECA, M_NOWAIT|M_ZERO);
1364 	if (new == NULL) {
1365 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
1366 		return ENOBUFS;
1367 	}
1368 
1369 	if (IPSEC_PRIVILEGED_SO(so))
1370 		new->priv = 1;
1371 	else
1372 		new->priv = 0;
1373 
1374 	if ((new->sp_in = KEY_NEWSP()) == NULL) {
1375 		ipsec_delpcbpolicy(new);
1376 		return ENOBUFS;
1377 	}
1378 	new->sp_in->state = IPSEC_SPSTATE_ALIVE;
1379 	new->sp_in->policy = IPSEC_POLICY_ENTRUST;
1380 
1381 	if ((new->sp_out = KEY_NEWSP()) == NULL) {
1382 		KEY_FREESP(&new->sp_in);
1383 		ipsec_delpcbpolicy(new);
1384 		return ENOBUFS;
1385 	}
1386 	new->sp_out->state = IPSEC_SPSTATE_ALIVE;
1387 	new->sp_out->policy = IPSEC_POLICY_ENTRUST;
1388 
1389 	*policy = new;
1390 
1391 	return 0;
1392 }
1393 
1394 /* copy old ipsec policy into new */
1395 int
ipsec_copy_policy(const struct inpcbpolicy * old,struct inpcbpolicy * new)1396 ipsec_copy_policy(const struct inpcbpolicy *old, struct inpcbpolicy *new)
1397 {
1398 	struct secpolicy *sp;
1399 
1400 	sp = ipsec_deepcopy_policy(old->sp_in);
1401 	if (sp) {
1402 		KEY_FREESP(&new->sp_in);
1403 		new->sp_in = sp;
1404 	} else
1405 		return ENOBUFS;
1406 
1407 	sp = ipsec_deepcopy_policy(old->sp_out);
1408 	if (sp) {
1409 		KEY_FREESP(&new->sp_out);
1410 		new->sp_out = sp;
1411 	} else
1412 		return ENOBUFS;
1413 
1414 	new->priv = old->priv;
1415 
1416 	return 0;
1417 }
1418 
1419 /* deep-copy a policy in PCB */
1420 static struct secpolicy *
ipsec_deepcopy_policy(const struct secpolicy * src)1421 ipsec_deepcopy_policy(const struct secpolicy *src)
1422 {
1423 	struct ipsecrequest *newchain = NULL;
1424 	const struct ipsecrequest *p;
1425 	struct ipsecrequest **q;
1426 	struct ipsecrequest *r;
1427 	struct secpolicy *dst;
1428 
1429 	if (src == NULL)
1430 		return NULL;
1431 	dst = KEY_NEWSP();
1432 	if (dst == NULL)
1433 		return NULL;
1434 
1435 	/*
1436 	 * deep-copy IPsec request chain.  This is required since struct
1437 	 * ipsecrequest is not reference counted.
1438 	 */
1439 	q = &newchain;
1440 	for (p = src->req; p; p = p->next) {
1441 		*q = malloc(sizeof(**q), M_SECA, M_NOWAIT|M_ZERO);
1442 		if (*q == NULL)
1443 			goto fail;
1444 		(*q)->next = NULL;
1445 
1446 		(*q)->saidx.proto = p->saidx.proto;
1447 		(*q)->saidx.mode = p->saidx.mode;
1448 		(*q)->level = p->level;
1449 		(*q)->saidx.reqid = p->saidx.reqid;
1450 
1451 		memcpy(&(*q)->saidx.src, &p->saidx.src, sizeof((*q)->saidx.src));
1452 		memcpy(&(*q)->saidx.dst, &p->saidx.dst, sizeof((*q)->saidx.dst));
1453 
1454 		(*q)->sav = NULL;
1455 		(*q)->sp = dst;
1456 
1457 		q = &((*q)->next);
1458 	}
1459 
1460 	dst->req = newchain;
1461 	dst->state = src->state;
1462 	dst->policy = src->policy;
1463 	/* do not touch the refcnt fields */
1464 
1465 	return dst;
1466 
1467 fail:
1468 	for (q = &newchain; *q; q = &r) {
1469 		r = (*q)->next;
1470 		free(*q, M_SECA);
1471 	}
1472 	return NULL;
1473 }
1474 
1475 /* set policy and ipsec request if present. */
1476 static int
ipsec_set_policy(struct secpolicy ** policy,int optname,const void * request,size_t len,kauth_cred_t cred)1477 ipsec_set_policy(
1478 	struct secpolicy **policy,
1479 	int optname,
1480 	const void *request,
1481 	size_t len,
1482 	kauth_cred_t cred
1483 )
1484 {
1485 	const struct sadb_x_policy *xpl;
1486 	struct secpolicy *newsp = NULL;
1487 	int error;
1488 
1489 	/* sanity check. */
1490 	if (policy == NULL || *policy == NULL || request == NULL)
1491 		return EINVAL;
1492 	if (len < sizeof(*xpl))
1493 		return EINVAL;
1494 	xpl = (const struct sadb_x_policy *)request;
1495 
1496 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: passed policy\n", __func__);
1497 	    kdebug_sadb_x_policy((const struct sadb_ext *)xpl));
1498 
1499 	/* check policy type */
1500 	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
1501 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
1502 	 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
1503 		return EINVAL;
1504 
1505 	/* check privileged socket */
1506 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1507 		error = kauth_authorize_network(cred, KAUTH_NETWORK_IPSEC,
1508 		    KAUTH_REQ_NETWORK_IPSEC_BYPASS, NULL, NULL, NULL);
1509 		if (error)
1510 			return (error);
1511 	}
1512 
1513 	/* allocation new SP entry */
1514 	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
1515 		return error;
1516 
1517 	newsp->state = IPSEC_SPSTATE_ALIVE;
1518 
1519 	/* clear old SP and set new SP */
1520 	KEY_FREESP(policy);
1521 	*policy = newsp;
1522 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s: new policy\n", __func__);
1523 	    kdebug_secpolicy(newsp));
1524 
1525 	return 0;
1526 }
1527 
1528 static int
ipsec_get_policy(struct secpolicy * policy,struct mbuf ** mp)1529 ipsec_get_policy(struct secpolicy *policy, struct mbuf **mp)
1530 {
1531 
1532 	/* sanity check. */
1533 	if (policy == NULL || mp == NULL)
1534 		return EINVAL;
1535 
1536 	*mp = key_sp2msg(policy);
1537 	if (!*mp) {
1538 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
1539 		return ENOBUFS;
1540 	}
1541 
1542 	(*mp)->m_type = MT_DATA;
1543 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP, printf("%s:\n", __func__);
1544 	    kdebug_mbuf(*mp));
1545 
1546 	return 0;
1547 }
1548 
1549 int
ipsec4_set_policy(struct inpcb * inp,int optname,const void * request,size_t len,kauth_cred_t cred)1550 ipsec4_set_policy(struct inpcb *inp, int optname, const void *request,
1551 		  size_t len, kauth_cred_t cred)
1552 {
1553 	const struct sadb_x_policy *xpl;
1554 	struct secpolicy **policy;
1555 
1556 	/* sanity check. */
1557 	if (inp == NULL || request == NULL)
1558 		return EINVAL;
1559 	if (len < sizeof(*xpl))
1560 		return EINVAL;
1561 	xpl = (const struct sadb_x_policy *)request;
1562 
1563 	IPSEC_ASSERT(inp->inp_sp != NULL, ("%s: null inp->in_sp", __func__));
1564 
1565 	/* select direction */
1566 	switch (xpl->sadb_x_policy_dir) {
1567 	case IPSEC_DIR_INBOUND:
1568 		policy = &inp->inp_sp->sp_in;
1569 		break;
1570 	case IPSEC_DIR_OUTBOUND:
1571 		policy = &inp->inp_sp->sp_out;
1572 		break;
1573 	default:
1574 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1575 		    xpl->sadb_x_policy_dir));
1576 		return EINVAL;
1577 	}
1578 
1579 	return ipsec_set_policy(policy, optname, request, len, cred);
1580 }
1581 
1582 int
ipsec4_get_policy(struct inpcb * inp,const void * request,size_t len,struct mbuf ** mp)1583 ipsec4_get_policy(struct inpcb *inp, const void *request, size_t len,
1584 		  struct mbuf **mp)
1585 {
1586 	const struct sadb_x_policy *xpl;
1587 	struct secpolicy *policy;
1588 
1589 	/* sanity check. */
1590 	if (inp == NULL || request == NULL || mp == NULL)
1591 		return EINVAL;
1592 	IPSEC_ASSERT(inp->inp_sp != NULL, ("%s: null inp_sp", __func__));
1593 	if (len < sizeof(*xpl))
1594 		return EINVAL;
1595 	xpl = (const struct sadb_x_policy *)request;
1596 
1597 	/* select direction */
1598 	switch (xpl->sadb_x_policy_dir) {
1599 	case IPSEC_DIR_INBOUND:
1600 		policy = inp->inp_sp->sp_in;
1601 		break;
1602 	case IPSEC_DIR_OUTBOUND:
1603 		policy = inp->inp_sp->sp_out;
1604 		break;
1605 	default:
1606 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1607 		    xpl->sadb_x_policy_dir));
1608 		return EINVAL;
1609 	}
1610 
1611 	return ipsec_get_policy(policy, mp);
1612 }
1613 
1614 /* delete policy in PCB */
1615 int
ipsec4_delete_pcbpolicy(struct inpcb * inp)1616 ipsec4_delete_pcbpolicy(struct inpcb *inp)
1617 {
1618 	IPSEC_ASSERT(inp != NULL, ("%s: null inp", __func__));
1619 
1620 	if (inp->inp_sp == NULL)
1621 		return 0;
1622 
1623 	if (inp->inp_sp->sp_in != NULL)
1624 		KEY_FREESP(&inp->inp_sp->sp_in);
1625 
1626 	if (inp->inp_sp->sp_out != NULL)
1627 		KEY_FREESP(&inp->inp_sp->sp_out);
1628 
1629 #ifdef __NetBSD__
1630 	ipsec_invalpcbcache(inp->inp_sp, IPSEC_DIR_ANY);
1631 #endif
1632 
1633 	ipsec_delpcbpolicy(inp->inp_sp);
1634 	inp->inp_sp = NULL;
1635 
1636 	return 0;
1637 }
1638 
1639 #ifdef INET6
1640 int
ipsec6_set_policy(struct in6pcb * in6p,int optname,const void * request,size_t len,kauth_cred_t cred)1641 ipsec6_set_policy(struct in6pcb *in6p, int optname, const void *request,
1642 		  size_t len, kauth_cred_t cred)
1643 {
1644 	const struct sadb_x_policy *xpl;
1645 	struct secpolicy **policy;
1646 
1647 	/* sanity check. */
1648 	if (in6p == NULL || request == NULL)
1649 		return EINVAL;
1650 	if (len < sizeof(*xpl))
1651 		return EINVAL;
1652 	xpl = (const struct sadb_x_policy *)request;
1653 
1654 	/* select direction */
1655 	switch (xpl->sadb_x_policy_dir) {
1656 	case IPSEC_DIR_INBOUND:
1657 		policy = &in6p->in6p_sp->sp_in;
1658 		break;
1659 	case IPSEC_DIR_OUTBOUND:
1660 		policy = &in6p->in6p_sp->sp_out;
1661 		break;
1662 	default:
1663 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1664 		    xpl->sadb_x_policy_dir));
1665 		return EINVAL;
1666 	}
1667 
1668 	return ipsec_set_policy(policy, optname, request, len, cred);
1669 }
1670 
1671 int
ipsec6_get_policy(struct in6pcb * in6p,const void * request,size_t len,struct mbuf ** mp)1672 ipsec6_get_policy(struct in6pcb *in6p, const void *request, size_t len,
1673 		  struct mbuf **mp)
1674 {
1675 	const struct sadb_x_policy *xpl;
1676 	struct secpolicy *policy;
1677 
1678 	/* sanity check. */
1679 	if (in6p == NULL || request == NULL || mp == NULL)
1680 		return EINVAL;
1681 	IPSEC_ASSERT(in6p->in6p_sp != NULL, ("%s: null in6p_sp", __func__));
1682 	if (len < sizeof(*xpl))
1683 		return EINVAL;
1684 	xpl = (const struct sadb_x_policy *)request;
1685 
1686 	/* select direction */
1687 	switch (xpl->sadb_x_policy_dir) {
1688 	case IPSEC_DIR_INBOUND:
1689 		policy = in6p->in6p_sp->sp_in;
1690 		break;
1691 	case IPSEC_DIR_OUTBOUND:
1692 		policy = in6p->in6p_sp->sp_out;
1693 		break;
1694 	default:
1695 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1696 		    xpl->sadb_x_policy_dir));
1697 		return EINVAL;
1698 	}
1699 
1700 	return ipsec_get_policy(policy, mp);
1701 }
1702 
1703 int
ipsec6_delete_pcbpolicy(struct in6pcb * in6p)1704 ipsec6_delete_pcbpolicy(struct in6pcb *in6p)
1705 {
1706 	IPSEC_ASSERT(in6p != NULL, ("%s: null in6p", __func__));
1707 
1708 	if (in6p->in6p_sp == NULL)
1709 		return 0;
1710 
1711 	if (in6p->in6p_sp->sp_in != NULL)
1712 		KEY_FREESP(&in6p->in6p_sp->sp_in);
1713 
1714 	if (in6p->in6p_sp->sp_out != NULL)
1715 		KEY_FREESP(&in6p->in6p_sp->sp_out);
1716 
1717 #ifdef __NetBSD
1718 	ipsec_invalpcbcache(in6p->in6p_sp, IPSEC_DIR_ANY);
1719 #endif
1720 
1721 	ipsec_delpcbpolicy(in6p->in6p_sp);
1722 	in6p->in6p_sp = NULL;
1723 
1724 	return 0;
1725 }
1726 #endif
1727 
1728 /*
1729  * return current level.
1730  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
1731  */
1732 u_int
ipsec_get_reqlevel(const struct ipsecrequest * isr)1733 ipsec_get_reqlevel(const struct ipsecrequest *isr)
1734 {
1735 	u_int level = 0;
1736 	u_int esp_trans_deflev, esp_net_deflev;
1737 	u_int ah_trans_deflev, ah_net_deflev;
1738 
1739 	IPSEC_ASSERT(isr != NULL && isr->sp != NULL, ("%s: null argument",
1740 	    __func__));
1741 	IPSEC_ASSERT(isr->sp->spidx.src.sa.sa_family ==
1742 	    isr->sp->spidx.dst.sa.sa_family,
1743 	    ("%s: af family mismatch, src %u, dst %u", __func__,
1744 	    isr->sp->spidx.src.sa.sa_family, isr->sp->spidx.dst.sa.sa_family));
1745 
1746 /* XXX note that we have ipseclog() expanded here - code sync issue */
1747 #define IPSEC_CHECK_DEFAULT(lev) 					\
1748     (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE		\
1749     && (lev) != IPSEC_LEVEL_UNIQUE) ?					\
1750 	(ipsec_debug ? log(LOG_INFO, "fixed system default level " #lev \
1751 	":%d->%d\n", (lev), IPSEC_LEVEL_REQUIRE) : (void)0),		\
1752 	(lev) = IPSEC_LEVEL_REQUIRE, (lev)				\
1753     : (lev))
1754 
1755 	/* set default level */
1756 	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
1757 #ifdef INET
1758 	case AF_INET:
1759 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
1760 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
1761 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
1762 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
1763 		break;
1764 #endif
1765 #ifdef INET6
1766 	case AF_INET6:
1767 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
1768 		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
1769 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
1770 		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
1771 		break;
1772 #endif /* INET6 */
1773 	default:
1774 		panic("%s: unknown af %u", __func__,
1775 		    isr->sp->spidx.src.sa.sa_family);
1776 	}
1777 
1778 #undef IPSEC_CHECK_DEFAULT
1779 
1780 	/* set level */
1781 	switch (isr->level) {
1782 	case IPSEC_LEVEL_DEFAULT:
1783 		switch (isr->saidx.proto) {
1784 		case IPPROTO_ESP:
1785 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1786 				level = esp_net_deflev;
1787 			else
1788 				level = esp_trans_deflev;
1789 			break;
1790 		case IPPROTO_AH:
1791 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1792 				level = ah_net_deflev;
1793 			else
1794 				level = ah_trans_deflev;
1795 			break;
1796 		case IPPROTO_IPCOMP:
1797 			/*
1798 			 * we don't really care, as IPcomp document says that
1799 			 * we shouldn't compress small packets
1800 			 */
1801 			level = IPSEC_LEVEL_USE;
1802 			break;
1803 		default:
1804 			panic("%s: Illegal protocol defined %u", __func__,
1805 			    isr->saidx.proto);
1806 		}
1807 		break;
1808 
1809 	case IPSEC_LEVEL_USE:
1810 	case IPSEC_LEVEL_REQUIRE:
1811 		level = isr->level;
1812 		break;
1813 	case IPSEC_LEVEL_UNIQUE:
1814 		level = IPSEC_LEVEL_REQUIRE;
1815 		break;
1816 
1817 	default:
1818 		panic("%s: Illegal IPsec level %u", __func__, isr->level);
1819 	}
1820 
1821 	return level;
1822 }
1823 
1824 /*
1825  * Check security policy requirements against the actual
1826  * packet contents.  Return one if the packet should be
1827  * reject as "invalid"; otherwiser return zero to have the
1828  * packet treated as "valid".
1829  *
1830  * OUT:
1831  *	0: valid
1832  *	1: invalid
1833  */
1834 int
ipsec_in_reject(const struct secpolicy * sp,const struct mbuf * m)1835 ipsec_in_reject(const struct secpolicy *sp, const struct mbuf *m)
1836 {
1837 	struct ipsecrequest *isr;
1838 	int need_auth;
1839 
1840 	KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: using SP\n", __func__);
1841 	    kdebug_secpolicy(sp));
1842 
1843 	/* check policy */
1844 	switch (sp->policy) {
1845 	case IPSEC_POLICY_DISCARD:
1846 		return 1;
1847 	case IPSEC_POLICY_BYPASS:
1848 	case IPSEC_POLICY_NONE:
1849 		return 0;
1850 	}
1851 
1852 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1853 	    ("%s: invalid policy %u", __func__, sp->policy));
1854 
1855 	/* XXX should compare policy against ipsec header history */
1856 
1857 	need_auth = 0;
1858 	for (isr = sp->req; isr != NULL; isr = isr->next) {
1859 		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
1860 			continue;
1861 		switch (isr->saidx.proto) {
1862 		case IPPROTO_ESP:
1863 			if ((m->m_flags & M_DECRYPTED) == 0) {
1864 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1865 				    printf("%s: ESP m_flags:%x\n", __func__,
1866 				    m->m_flags));
1867 				return 1;
1868 			}
1869 
1870 			if (!need_auth &&
1871 				isr->sav != NULL &&
1872 				isr->sav->tdb_authalgxform != NULL &&
1873 				(m->m_flags & M_AUTHIPDGM) == 0) {
1874 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1875 				    printf("%s: ESP/AH m_flags:%x\n", __func__,
1876 				    m->m_flags));
1877 				return 1;
1878 			}
1879 			break;
1880 		case IPPROTO_AH:
1881 			need_auth = 1;
1882 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1883 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1884 				    printf("%s: AH m_flags:%x\n", __func__,
1885 				    m->m_flags));
1886 				return 1;
1887 			}
1888 			break;
1889 		case IPPROTO_IPCOMP:
1890 			/*
1891 			 * we don't really care, as IPcomp document
1892 			 * says that we shouldn't compress small
1893 			 * packets, IPComp policy should always be
1894 			 * treated as being in "use" level.
1895 			 */
1896 			break;
1897 		}
1898 	}
1899 	return 0;		/* valid */
1900 }
1901 
1902 /*
1903  * Check AH/ESP integrity.
1904  * This function is called from tcp_input(), udp_input(),
1905  * and {ah,esp}4_input for tunnel mode
1906  */
1907 int
ipsec4_in_reject(struct mbuf * m,struct inpcb * inp)1908 ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
1909 {
1910 	struct secpolicy *sp;
1911 	int error;
1912 	int result;
1913 
1914 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
1915 
1916 	/* get SP for this packet.
1917 	 * When we are called from ip_forward(), we call
1918 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1919 	 */
1920 	if (inp == NULL)
1921 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1922 	else
1923 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
1924 					   IN4PCB_TO_PCB(inp), &error);
1925 
1926 	if (sp != NULL) {
1927 		result = ipsec_in_reject(sp, m);
1928 		if (result)
1929 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1930 		KEY_FREESP(&sp);
1931 	} else {
1932 		result = 0;	/* XXX should be panic ?
1933 				 * -> No, there may be error. */
1934 	}
1935 	return result;
1936 }
1937 
1938 
1939 #ifdef INET6
1940 /*
1941  * Check AH/ESP integrity.
1942  * This function is called from tcp6_input(), udp6_input(),
1943  * and {ah,esp}6_input for tunnel mode
1944  */
1945 int
ipsec6_in_reject(struct mbuf * m,struct in6pcb * in6p)1946 ipsec6_in_reject(struct mbuf *m, struct in6pcb *in6p)
1947 {
1948 	struct secpolicy *sp = NULL;
1949 	int error;
1950 	int result;
1951 
1952 	/* sanity check */
1953 	if (m == NULL)
1954 		return 0;	/* XXX should be panic ? */
1955 
1956 	/* get SP for this packet.
1957 	 * When we are called from ip_forward(), we call
1958 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1959 	 */
1960 	if (in6p == NULL)
1961 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1962 	else
1963 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
1964 			IN6PCB_TO_PCB(in6p),
1965 			&error);
1966 
1967 	if (sp != NULL) {
1968 		result = ipsec_in_reject(sp, m);
1969 		if (result)
1970 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1971 		KEY_FREESP(&sp);
1972 	} else {
1973 		result = 0;
1974 	}
1975 	return result;
1976 }
1977 #endif
1978 
1979 /*
1980  * compute the byte size to be occupied by IPsec header.
1981  * in case it is tunneled, it includes the size of outer IP header.
1982  * NOTE: SP passed is free in this function.
1983  */
1984 static size_t
ipsec_hdrsiz(const struct secpolicy * sp)1985 ipsec_hdrsiz(const struct secpolicy *sp)
1986 {
1987 	const struct ipsecrequest *isr;
1988 	size_t siz;
1989 
1990 	KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: using SP\n", __func__);
1991 	    kdebug_secpolicy(sp));
1992 
1993 	switch (sp->policy) {
1994 	case IPSEC_POLICY_DISCARD:
1995 	case IPSEC_POLICY_BYPASS:
1996 	case IPSEC_POLICY_NONE:
1997 		return 0;
1998 	}
1999 
2000 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2001 	    ("%s: invalid policy %u", __func__, sp->policy));
2002 
2003 	siz = 0;
2004 	for (isr = sp->req; isr != NULL; isr = isr->next) {
2005 		size_t clen = 0;
2006 
2007 		switch (isr->saidx.proto) {
2008 		case IPPROTO_ESP:
2009 			clen = esp_hdrsiz(isr->sav);
2010 			break;
2011 		case IPPROTO_AH:
2012 			clen = ah_hdrsiz(isr->sav);
2013 			break;
2014 		case IPPROTO_IPCOMP:
2015 			clen = sizeof(struct ipcomp);
2016 			break;
2017 		}
2018 
2019 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
2020 			switch (isr->saidx.dst.sa.sa_family) {
2021 			case AF_INET:
2022 				clen += sizeof(struct ip);
2023 				break;
2024 #ifdef INET6
2025 			case AF_INET6:
2026 				clen += sizeof(struct ip6_hdr);
2027 				break;
2028 #endif
2029 			default:
2030 				ipseclog((LOG_ERR, "%s: unknown AF %d in "
2031 				    "IPsec tunnel SA\n", __func__,
2032 				    ((const struct sockaddr *)&isr->saidx.dst)
2033 				    ->sa_family));
2034 				break;
2035 			}
2036 		}
2037 		siz += clen;
2038 	}
2039 
2040 	return siz;
2041 }
2042 
2043 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
2044 size_t
ipsec4_hdrsiz(struct mbuf * m,u_int dir,struct inpcb * inp)2045 ipsec4_hdrsiz(struct mbuf *m, u_int dir, struct inpcb *inp)
2046 {
2047 	struct secpolicy *sp;
2048 	int error;
2049 	size_t size;
2050 
2051 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
2052 	IPSEC_ASSERT(inp == NULL || inp->inp_socket != NULL,
2053 	    ("%s: socket w/o inpcb", __func__));
2054 
2055 	/* get SP for this packet.
2056 	 * When we are called from ip_forward(), we call
2057 	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
2058 	 */
2059 	if (inp == NULL)
2060 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
2061 	else
2062 		sp = ipsec_getpolicybysock(m, dir,
2063 					   IN4PCB_TO_PCB(inp), &error);
2064 
2065 	if (sp != NULL) {
2066 		size = ipsec_hdrsiz(sp);
2067 		KEYDEBUG(KEYDEBUG_IPSEC_DATA, printf("%s: size:%lu.\n",
2068 		    __func__, (unsigned long)size));
2069 
2070 		KEY_FREESP(&sp);
2071 	} else {
2072 		size = 0;	/* XXX should be panic ? */
2073 	}
2074 	return size;
2075 }
2076 
2077 #ifdef INET6
2078 /* This function is called from ipsec6_hdrsize_tcp(),
2079  * and maybe from ip6_forward.()
2080  */
2081 size_t
ipsec6_hdrsiz(struct mbuf * m,u_int dir,struct in6pcb * in6p)2082 ipsec6_hdrsiz(struct mbuf *m, u_int dir, struct in6pcb *in6p)
2083 {
2084 	struct secpolicy *sp;
2085 	int error;
2086 	size_t size;
2087 
2088 	IPSEC_ASSERT(m != NULL, ("%s: null mbuf", __func__));
2089 	IPSEC_ASSERT(in6p == NULL || in6p->in6p_socket != NULL,
2090 	    ("%s: socket w/o inpcb", __func__));
2091 
2092 	/* get SP for this packet */
2093 	/* XXX Is it right to call with IP_FORWARDING. */
2094 	if (in6p == NULL)
2095 		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
2096 	else
2097 		sp = ipsec_getpolicybysock(m, dir,
2098 			IN6PCB_TO_PCB(in6p),
2099 			&error);
2100 
2101 	if (sp == NULL)
2102 		return 0;
2103 	size = ipsec_hdrsiz(sp);
2104 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
2105 	    printf("%s: size:%zu.\n", __func__, size));
2106 	KEY_FREESP(&sp);
2107 
2108 	return size;
2109 }
2110 #endif /*INET6*/
2111 
2112 /*
2113  * Check the variable replay window.
2114  * ipsec_chkreplay() performs replay check before ICV verification.
2115  * ipsec_updatereplay() updates replay bitmap.  This must be called after
2116  * ICV verification (it also performs replay check, which is usually done
2117  * beforehand).
2118  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
2119  *
2120  * based on RFC 2401.
2121  */
2122 int
ipsec_chkreplay(u_int32_t seq,const struct secasvar * sav)2123 ipsec_chkreplay(u_int32_t seq, const struct secasvar *sav)
2124 {
2125 	const struct secreplay *replay;
2126 	u_int32_t diff;
2127 	int fr;
2128 	u_int32_t wsizeb;	/* constant: bits of window size */
2129 	int frlast;		/* constant: last frame */
2130 
2131 	IPSEC_SPLASSERT_SOFTNET(__func__);
2132 
2133 	IPSEC_ASSERT(sav != NULL, ("%s: Null SA", __func__));
2134 	IPSEC_ASSERT(sav->replay != NULL, ("%s: Null replay state", __func__));
2135 
2136 	replay = sav->replay;
2137 
2138 	if (replay->wsize == 0)
2139 		return 1;	/* no need to check replay. */
2140 
2141 	/* constant */
2142 	frlast = replay->wsize - 1;
2143 	wsizeb = replay->wsize << 3;
2144 
2145 	/* sequence number of 0 is invalid */
2146 	if (seq == 0)
2147 		return 0;
2148 
2149 	/* first time is always okay */
2150 	if (replay->count == 0)
2151 		return 1;
2152 
2153 	if (seq > replay->lastseq) {
2154 		/* larger sequences are okay */
2155 		return 1;
2156 	} else {
2157 		/* seq is equal or less than lastseq. */
2158 		diff = replay->lastseq - seq;
2159 
2160 		/* over range to check, i.e. too old or wrapped */
2161 		if (diff >= wsizeb)
2162 			return 0;
2163 
2164 		fr = frlast - diff / 8;
2165 
2166 		/* this packet already seen ? */
2167 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
2168 			return 0;
2169 
2170 		/* out of order but good */
2171 		return 1;
2172 	}
2173 }
2174 
2175 /*
2176  * check replay counter whether to update or not.
2177  * OUT:	0:	OK
2178  *	1:	NG
2179  */
2180 int
ipsec_updatereplay(u_int32_t seq,const struct secasvar * sav)2181 ipsec_updatereplay(u_int32_t seq, const struct secasvar *sav)
2182 {
2183 	struct secreplay *replay;
2184 	u_int32_t diff;
2185 	int fr;
2186 	u_int32_t wsizeb;	/* constant: bits of window size */
2187 	int frlast;		/* constant: last frame */
2188 
2189 	IPSEC_SPLASSERT_SOFTNET(__func__);
2190 
2191 	IPSEC_ASSERT(sav != NULL, ("%s: Null SA", __func__));
2192 	IPSEC_ASSERT(sav->replay != NULL, ("%s: Null replay state", __func__));
2193 
2194 	replay = sav->replay;
2195 
2196 	if (replay->wsize == 0)
2197 		goto ok;	/* no need to check replay. */
2198 
2199 	/* constant */
2200 	frlast = replay->wsize - 1;
2201 	wsizeb = replay->wsize << 3;
2202 
2203 	/* sequence number of 0 is invalid */
2204 	if (seq == 0)
2205 		return 1;
2206 
2207 	/* first time */
2208 	if (replay->count == 0) {
2209 		replay->lastseq = seq;
2210 		memset(replay->bitmap, 0, replay->wsize);
2211 		(replay->bitmap)[frlast] = 1;
2212 		goto ok;
2213 	}
2214 
2215 	if (seq > replay->lastseq) {
2216 		/* seq is larger than lastseq. */
2217 		diff = seq - replay->lastseq;
2218 
2219 		/* new larger sequence number */
2220 		if (diff < wsizeb) {
2221 			/* In window */
2222 			/* set bit for this packet */
2223 			vshiftl(replay->bitmap, diff, replay->wsize);
2224 			(replay->bitmap)[frlast] |= 1;
2225 		} else {
2226 			/* this packet has a "way larger" */
2227 			memset(replay->bitmap, 0, replay->wsize);
2228 			(replay->bitmap)[frlast] = 1;
2229 		}
2230 		replay->lastseq = seq;
2231 
2232 		/* larger is good */
2233 	} else {
2234 		/* seq is equal or less than lastseq. */
2235 		diff = replay->lastseq - seq;
2236 
2237 		/* over range to check, i.e. too old or wrapped */
2238 		if (diff >= wsizeb)
2239 			return 1;
2240 
2241 		fr = frlast - diff / 8;
2242 
2243 		/* this packet already seen ? */
2244 		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
2245 			return 1;
2246 
2247 		/* mark as seen */
2248 		(replay->bitmap)[fr] |= (1 << (diff % 8));
2249 
2250 		/* out of order but good */
2251 	}
2252 
2253 ok:
2254 	if (replay->count == ~0) {
2255 
2256 		/* set overflow flag */
2257 		replay->overflow++;
2258 
2259 		/* don't increment, no more packets accepted */
2260 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
2261 			return 1;
2262 
2263 		ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
2264 		    replay->overflow, ipsec_logsastr(sav)));
2265 	}
2266 
2267 	replay->count++;
2268 
2269 	return 0;
2270 }
2271 
2272 /*
2273  * shift variable length bunffer to left.
2274  * IN:	bitmap: pointer to the buffer
2275  * 	nbit:	the number of to shift.
2276  *	wsize:	buffer size (bytes).
2277  */
2278 static void
vshiftl(unsigned char * bitmap,int nbit,int wsize)2279 vshiftl(unsigned char *bitmap, int nbit, int wsize)
2280 {
2281 	int s, j, i;
2282 	unsigned char over;
2283 
2284 	for (j = 0; j < nbit; j += 8) {
2285 		s = (nbit - j < 8) ? (nbit - j): 8;
2286 		bitmap[0] <<= s;
2287 		for (i = 1; i < wsize; i++) {
2288 			over = (bitmap[i] >> (8 - s));
2289 			bitmap[i] <<= s;
2290 			bitmap[i-1] |= over;
2291 		}
2292 	}
2293 
2294 	return;
2295 }
2296 
2297 /* Return a printable string for the IPv4 address. */
2298 static char *
inet_ntoa4(struct in_addr ina)2299 inet_ntoa4(struct in_addr ina)
2300 {
2301 	static char buf[4][4 * sizeof "123" + 4];
2302 	unsigned char *ucp = (unsigned char *) &ina;
2303 	static int i = 3;
2304 
2305 	i = (i + 1) % 4;
2306 	snprintf(buf[i], sizeof(buf[i]), "%d.%d.%d.%d",
2307 		ucp[0] & 0xff, ucp[1] & 0xff, ucp[2] & 0xff, ucp[3] & 0xff);
2308 	return (buf[i]);
2309 }
2310 
2311 /* Return a printable string for the address. */
2312 const char *
ipsec_address(const union sockaddr_union * sa)2313 ipsec_address(const union sockaddr_union *sa)
2314 {
2315 	switch (sa->sa.sa_family) {
2316 #if INET
2317 	case AF_INET:
2318 		return inet_ntoa4(sa->sin.sin_addr);
2319 #endif /* INET */
2320 
2321 #if INET6
2322 	case AF_INET6:
2323 		return ip6_sprintf(&sa->sin6.sin6_addr);
2324 #endif /* INET6 */
2325 
2326 	default:
2327 		return "(unknown address family)";
2328 	}
2329 }
2330 
2331 const char *
ipsec_logsastr(const struct secasvar * sav)2332 ipsec_logsastr(const struct secasvar *sav)
2333 {
2334 	static char buf[256];
2335 	char *p;
2336 	const struct secasindex *saidx = &sav->sah->saidx;
2337 
2338 	IPSEC_ASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
2339 	    ("%s: address family mismatch", __func__));
2340 
2341 	p = buf;
2342 	snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
2343 	while (p && *p)
2344 		p++;
2345 	/* NB: only use ipsec_address on one address at a time */
2346 	snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
2347 		ipsec_address(&saidx->src));
2348 	while (p && *p)
2349 		p++;
2350 	snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
2351 		ipsec_address(&saidx->dst));
2352 
2353 	return buf;
2354 }
2355 
2356 void
ipsec_dumpmbuf(struct mbuf * m)2357 ipsec_dumpmbuf(struct mbuf *m)
2358 {
2359 	int totlen;
2360 	int i;
2361 	u_char *p;
2362 
2363 	totlen = 0;
2364 	printf("---\n");
2365 	while (m) {
2366 		p = mtod(m, u_char *);
2367 		for (i = 0; i < m->m_len; i++) {
2368 			printf("%02x ", p[i]);
2369 			totlen++;
2370 			if (totlen % 16 == 0)
2371 				printf("\n");
2372 		}
2373 		m = m->m_next;
2374 	}
2375 	if (totlen % 16 != 0)
2376 		printf("\n");
2377 	printf("---\n");
2378 }
2379 
2380 #ifdef INET6
2381 struct secpolicy *
ipsec6_check_policy(struct mbuf * m,const struct socket * so,int flags,int * needipsecp,int * errorp)2382 ipsec6_check_policy(struct mbuf *m, const struct socket *so,
2383 		    int flags, int *needipsecp, int *errorp)
2384 {
2385 	struct in6pcb *in6p = NULL;
2386 	struct secpolicy *sp = NULL;
2387 	int s;
2388 	int error = 0;
2389 	int needipsec = 0;
2390 
2391 	if (so != NULL && so->so_proto->pr_domain->dom_family == AF_INET6)
2392 		in6p = sotoin6pcb(so);
2393 
2394 	if (!ipsec_outdone(m)) {
2395 		s = splsoftnet();
2396 		if (in6p != NULL &&
2397 		    IPSEC_PCB_SKIP_IPSEC(in6p->in6p_sp, IPSEC_DIR_OUTBOUND)) {
2398 			splx(s);
2399 			goto skippolicycheck;
2400 		}
2401 		sp = ipsec6_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error,in6p);
2402 
2403 		/*
2404 		 * There are four return cases:
2405 		 *	sp != NULL			apply IPsec policy
2406 		 *	sp == NULL, error == 0		no IPsec handling needed
2407 		 *	sp == NULL, error == -EINVAL  discard packet w/o error
2408 		 *	sp == NULL, error != 0		discard packet, report error
2409 		 */
2410 
2411 		splx(s);
2412 		if (sp == NULL) {
2413 			/*
2414 			 * Caller must check the error return to see if it needs to discard
2415 			 * the packet.
2416 			 */
2417 			needipsec = 0;
2418 		} else {
2419 			needipsec = 1;
2420 		}
2421 	}
2422 skippolicycheck:;
2423 
2424 	*errorp = error;
2425 	*needipsecp = needipsec;
2426 	return sp;
2427 }
2428 
2429 int
ipsec6_input(struct mbuf * m)2430 ipsec6_input(struct mbuf *m)
2431 {
2432 	struct m_tag *mtag;
2433 	struct tdb_ident *tdbi;
2434 	struct secpolicy *sp;
2435 	int s, error;
2436 
2437 	/*
2438 	 * Check if the packet has already had IPsec
2439 	 * processing done. If so, then just pass it
2440 	 * along. This tag gets set during AH, ESP,
2441 	 * etc. input handling, before the packet is
2442 	 * returned to the ip input queue for delivery.
2443 	 */
2444 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE,
2445 	    NULL);
2446 	s = splsoftnet();
2447 	if (mtag != NULL) {
2448 		tdbi = (struct tdb_ident *)(mtag + 1);
2449 		sp = ipsec_getpolicy(tdbi,
2450 		    IPSEC_DIR_INBOUND);
2451 	} else {
2452 		sp = ipsec_getpolicybyaddr(m,
2453 		    IPSEC_DIR_INBOUND, IP_FORWARDING,
2454 		    &error);
2455 	}
2456 	if (sp != NULL) {
2457 		/*
2458 		 * Check security policy against packet
2459 		 * attributes.
2460 		 */
2461 		error = ipsec_in_reject(sp, m);
2462 		KEY_FREESP(&sp);
2463 	} else {
2464 		/* XXX error stat??? */
2465 		error = EINVAL;
2466 		DPRINTF(("ip6_input: no SP, packet"
2467 		    " discarded\n"));/*XXX*/
2468 	}
2469 	splx(s);
2470 
2471 	return error;
2472 }
2473 #endif /* INET6 */
2474 
2475 
2476 
2477 /* XXX this stuff doesn't belong here... */
2478 
2479 static	struct xformsw *xforms = NULL;
2480 
2481 /*
2482  * Register a transform; typically at system startup.
2483  */
2484 void
xform_register(struct xformsw * xsp)2485 xform_register(struct xformsw *xsp)
2486 {
2487 	xsp->xf_next = xforms;
2488 	xforms = xsp;
2489 }
2490 
2491 /*
2492  * Initialize transform support in an sav.
2493  */
2494 int
xform_init(struct secasvar * sav,int xftype)2495 xform_init(struct secasvar *sav, int xftype)
2496 {
2497 	struct xformsw *xsp;
2498 
2499 	if (sav->tdb_xform != NULL)	/* previously initialized */
2500 		return 0;
2501 	for (xsp = xforms; xsp; xsp = xsp->xf_next)
2502 		if (xsp->xf_type == xftype)
2503 			return (*xsp->xf_init)(sav, xsp);
2504 
2505 	DPRINTF(("%s: no match for xform type %d\n", __func__, xftype));
2506 	return EINVAL;
2507 }
2508 
2509 void
nat_t_ports_get(struct mbuf * m,u_int16_t * dport,u_int16_t * sport)2510 nat_t_ports_get(struct mbuf *m, u_int16_t *dport, u_int16_t *sport) {
2511 	struct m_tag *tag;
2512 
2513 	if ((tag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS, NULL))) {
2514 		*sport = ((u_int16_t *)(tag + 1))[0];
2515 		*dport = ((u_int16_t *)(tag + 1))[1];
2516 	} else
2517 		*sport = *dport = 0;
2518 }
2519 
2520 #ifdef __NetBSD__
2521 /*
2522  * XXXJRT This should be done as a protosw init call.
2523  */
2524 void
ipsec_attach(void)2525 ipsec_attach(void)
2526 {
2527 
2528 	ipsecstat_percpu = percpu_alloc(sizeof(uint64_t) * IPSEC_NSTATS);
2529 
2530 	ah_attach();
2531 	esp_attach();
2532 	ipcomp_attach();
2533 	ipe4_attach();
2534 #ifdef TCP_SIGNATURE
2535 	tcpsignature_attach();
2536 #endif
2537 }
2538 #endif	/* __NetBSD__ */
2539