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