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