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