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