xref: /openbsd-src/sys/netinet/ip_spd.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /* $OpenBSD: ip_spd.c,v 1.71 2014/04/14 09:06:42 mpi Exp $ */
2 /*
3  * The author of this code is Angelos D. Keromytis (angelos@cis.upenn.edu)
4  *
5  * Copyright (c) 2000-2001 Angelos D. Keromytis.
6  *
7  * Permission to use, copy, and modify this software with or without fee
8  * is hereby granted, provided that this entire notice is included in
9  * all copies of any software which is or includes a copy or
10  * modification of this software.
11  * You may use this code under the GNU public license if you so wish. Please
12  * contribute changes back to the authors under this freer than GPL license
13  * so that we may further the use of strong encryption without limitations to
14  * all.
15  *
16  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
17  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
18  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
19  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
20  * PURPOSE.
21  */
22 
23 #include <sys/param.h>
24 #include <sys/systm.h>
25 #include <sys/mbuf.h>
26 #include <sys/socket.h>
27 #include <sys/kernel.h>
28 #include <sys/socketvar.h>
29 #include <sys/protosw.h>
30 #include <sys/pool.h>
31 #include <sys/timeout.h>
32 
33 #include <net/if.h>
34 #include <net/route.h>
35 #include <net/netisr.h>
36 
37 #ifdef INET
38 #include <netinet/in.h>
39 #include <netinet/in_systm.h>
40 #include <netinet/ip.h>
41 #include <netinet/ip_var.h>
42 #include <netinet/in_pcb.h>
43 #endif /* INET */
44 
45 #ifdef INET6
46 #ifndef INET
47 #include <netinet/in.h>
48 #endif
49 #endif /* INET6 */
50 
51 #include <netinet/ip_ipsp.h>
52 #include <net/pfkeyv2.h>
53 
54 int	ipsp_acquire_sa(struct ipsec_policy *, union sockaddr_union *,
55 	    union sockaddr_union *, struct sockaddr_encap *, struct mbuf *);
56 void	ipsec_update_policy(struct inpcb *, struct ipsec_policy *, int, int);
57 struct	ipsec_acquire *ipsp_pending_acquire(struct ipsec_policy *,
58 	    union sockaddr_union *);
59 void	ipsp_delete_acquire(void *);
60 
61 #ifdef ENCDEBUG
62 #define	DPRINTF(x)	if (encdebug) printf x
63 #else
64 #define	DPRINTF(x)
65 #endif
66 
67 struct pool ipsec_policy_pool;
68 struct pool ipsec_acquire_pool;
69 int ipsec_policy_pool_initialized = 0;
70 int ipsec_acquire_pool_initialized = 0;
71 
72 /*
73  * Lookup at the SPD based on the headers contained on the mbuf. The second
74  * argument indicates what protocol family the header at the beginning of
75  * the mbuf is. hlen is the offset of the transport protocol header
76  * in the mbuf.
77  *
78  * Return combinations (of return value and in *error):
79  * - NULL/0 -> no IPsec required on packet
80  * - NULL/-EINVAL -> silently drop the packet
81  * - NULL/errno -> drop packet and return error
82  * or a pointer to a TDB (and 0 in *error).
83  *
84  * In the case of incoming flows, only the first three combinations are
85  * returned.
86  */
87 struct tdb *
88 ipsp_spd_lookup(struct mbuf *m, int af, int hlen, int *error, int direction,
89     struct tdb *tdbp, struct inpcb *inp, u_int32_t ipsecflowinfo)
90 {
91 	struct route_enc re0, *re = &re0;
92 	union sockaddr_union sdst, ssrc;
93 	struct sockaddr_encap *ddst;
94 	struct ipsec_policy *ipo;
95 	struct ipsec_ref *dstid = NULL, *srcid = NULL;
96 	struct tdb *tdbin = NULL;
97 	int signore = 0, dignore = 0;
98 	u_int rdomain = rtable_l2(m->m_pkthdr.ph_rtableid);
99 
100 	/*
101 	 * If there are no flows in place, there's no point
102 	 * continuing with the SPD lookup.
103 	 */
104 	if (!ipsec_in_use && inp == NULL) {
105 		*error = 0;
106 		return NULL;
107 	}
108 
109 	/*
110 	 * If an input packet is destined to a BYPASS socket, just accept it.
111 	 */
112 	if ((inp != NULL) && (direction == IPSP_DIRECTION_IN) &&
113 	    (inp->inp_seclevel[SL_ESP_TRANS] == IPSEC_LEVEL_BYPASS) &&
114 	    (inp->inp_seclevel[SL_ESP_NETWORK] == IPSEC_LEVEL_BYPASS) &&
115 	    (inp->inp_seclevel[SL_AUTH] == IPSEC_LEVEL_BYPASS)) {
116 		*error = 0;
117 		return NULL;
118 	}
119 
120 	memset(re, 0, sizeof(struct route_enc));
121 	memset(&sdst, 0, sizeof(union sockaddr_union));
122 	memset(&ssrc, 0, sizeof(union sockaddr_union));
123 	ddst = (struct sockaddr_encap *) &re->re_dst;
124 	ddst->sen_family = PF_KEY;
125 	ddst->sen_len = SENT_LEN;
126 
127 	switch (af) {
128 #ifdef INET
129 	case AF_INET:
130 		if (hlen < sizeof (struct ip) || m->m_pkthdr.len < hlen) {
131 			*error = EINVAL;
132 			return NULL;
133 		}
134 		ddst->sen_direction = direction;
135 		ddst->sen_type = SENT_IP4;
136 
137 		m_copydata(m, offsetof(struct ip, ip_src),
138 		    sizeof(struct in_addr), (caddr_t) &(ddst->sen_ip_src));
139 		m_copydata(m, offsetof(struct ip, ip_dst),
140 		    sizeof(struct in_addr), (caddr_t) &(ddst->sen_ip_dst));
141 		m_copydata(m, offsetof(struct ip, ip_p), sizeof(u_int8_t),
142 		    (caddr_t) &(ddst->sen_proto));
143 
144 		sdst.sin.sin_family = ssrc.sin.sin_family = AF_INET;
145 		sdst.sin.sin_len = ssrc.sin.sin_len =
146 		    sizeof(struct sockaddr_in);
147 		ssrc.sin.sin_addr = ddst->sen_ip_src;
148 		sdst.sin.sin_addr = ddst->sen_ip_dst;
149 
150 		/*
151 		 * If TCP/UDP, extract the port numbers to use in the lookup.
152 		 */
153 		switch (ddst->sen_proto) {
154 		case IPPROTO_UDP:
155 		case IPPROTO_TCP:
156 			/* Make sure there's enough data in the packet. */
157 			if (m->m_pkthdr.len < hlen + 2 * sizeof(u_int16_t)) {
158 				*error = EINVAL;
159 				return NULL;
160 			}
161 
162 			/*
163 			 * Luckily, the offset of the src/dst ports in
164 			 * both the UDP and TCP headers is the same (first
165 			 * two 16-bit values in the respective headers),
166 			 * so we can just copy them.
167 			 */
168 			m_copydata(m, hlen, sizeof(u_int16_t),
169 			    (caddr_t) &(ddst->sen_sport));
170 			m_copydata(m, hlen + sizeof(u_int16_t), sizeof(u_int16_t),
171 			    (caddr_t) &(ddst->sen_dport));
172 			break;
173 
174 		default:
175 			ddst->sen_sport = 0;
176 			ddst->sen_dport = 0;
177 		}
178 
179 		break;
180 #endif /* INET */
181 
182 #ifdef INET6
183 	case AF_INET6:
184 		if (hlen < sizeof (struct ip6_hdr) || m->m_pkthdr.len < hlen) {
185 			*error = EINVAL;
186 			return NULL;
187 		}
188 		ddst->sen_type = SENT_IP6;
189 		ddst->sen_ip6_direction = direction;
190 
191 		m_copydata(m, offsetof(struct ip6_hdr, ip6_src),
192 		    sizeof(struct in6_addr),
193 		    (caddr_t) &(ddst->sen_ip6_src));
194 		m_copydata(m, offsetof(struct ip6_hdr, ip6_dst),
195 		    sizeof(struct in6_addr),
196 		    (caddr_t) &(ddst->sen_ip6_dst));
197 		m_copydata(m, offsetof(struct ip6_hdr, ip6_nxt),
198 		    sizeof(u_int8_t),
199 		    (caddr_t) &(ddst->sen_ip6_proto));
200 
201 		sdst.sin6.sin6_family = ssrc.sin6.sin6_family = AF_INET6;
202 		sdst.sin6.sin6_len = ssrc.sin6.sin6_len =
203 		    sizeof(struct sockaddr_in6);
204 		in6_recoverscope(&ssrc.sin6, &ddst->sen_ip6_src, NULL);
205 		in6_recoverscope(&sdst.sin6, &ddst->sen_ip6_dst, NULL);
206 
207 		/*
208 		 * If TCP/UDP, extract the port numbers to use in the lookup.
209 		 */
210 		switch (ddst->sen_ip6_proto) {
211 		case IPPROTO_UDP:
212 		case IPPROTO_TCP:
213 			/* Make sure there's enough data in the packet. */
214 			if (m->m_pkthdr.len < hlen + 2 * sizeof(u_int16_t)) {
215 				*error = EINVAL;
216 				return NULL;
217 			}
218 
219 			/*
220 			 * Luckily, the offset of the src/dst ports in
221 			 * both the UDP and TCP headers is the same
222 			 * (first two 16-bit values in the respective
223 			 * headers), so we can just copy them.
224 			 */
225 			m_copydata(m, hlen, sizeof(u_int16_t),
226 			    (caddr_t) &(ddst->sen_ip6_sport));
227 			m_copydata(m, hlen + sizeof(u_int16_t), sizeof(u_int16_t),
228 			    (caddr_t) &(ddst->sen_ip6_dport));
229 			break;
230 
231 		default:
232 			ddst->sen_ip6_sport = 0;
233 			ddst->sen_ip6_dport = 0;
234 		}
235 
236 		break;
237 #endif /* INET6 */
238 
239 	default:
240 		*error = EAFNOSUPPORT;
241 		return NULL;
242 	}
243 
244 	/* Set the rdomain that was obtained from the mbuf */
245 	re->re_tableid = rdomain;
246 
247 	/* Actual SPD lookup. */
248 	rtalloc((struct route *) re);
249 	if (re->re_rt == NULL) {
250 		/*
251 		 * Return whatever the socket requirements are, there are no
252 		 * system-wide policies.
253 		 */
254 		*error = 0;
255 		return ipsp_spd_inp(m, af, hlen, error, direction,
256 		    tdbp, inp, NULL);
257 	}
258 
259 	/* Sanity check. */
260 	if ((re->re_rt->rt_gateway == NULL) ||
261 	    (((struct sockaddr_encap *) re->re_rt->rt_gateway)->sen_type !=
262 		SENT_IPSP)) {
263 		RTFREE(re->re_rt);
264 		*error = EHOSTUNREACH;
265 		DPRINTF(("ip_spd_lookup: no gateway in SPD entry!"));
266 		return NULL;
267 	}
268 
269 	ipo = ((struct sockaddr_encap *) (re->re_rt->rt_gateway))->sen_ipsp;
270 	RTFREE(re->re_rt);
271 	if (ipo == NULL) {
272 		*error = EHOSTUNREACH;
273 		DPRINTF(("ip_spd_lookup: no policy attached to SPD entry!"));
274 		return NULL;
275 	}
276 
277 	switch (ipo->ipo_type) {
278 	case IPSP_PERMIT:
279 		*error = 0;
280 		return ipsp_spd_inp(m, af, hlen, error, direction, tdbp,
281 		    inp, ipo);
282 
283 	case IPSP_DENY:
284 		*error = EHOSTUNREACH;
285 		return NULL;
286 
287 	case IPSP_IPSEC_USE:
288 	case IPSP_IPSEC_ACQUIRE:
289 	case IPSP_IPSEC_REQUIRE:
290 	case IPSP_IPSEC_DONTACQ:
291 		/* Nothing more needed here. */
292 		break;
293 
294 	default:
295 		*error = EINVAL;
296 		return NULL;
297 	}
298 
299 	/* Check for non-specific destination in the policy. */
300 	switch (ipo->ipo_dst.sa.sa_family) {
301 #ifdef INET
302 	case AF_INET:
303 		if ((ipo->ipo_dst.sin.sin_addr.s_addr == INADDR_ANY) ||
304 		    (ipo->ipo_dst.sin.sin_addr.s_addr == INADDR_BROADCAST))
305 			dignore = 1;
306 		break;
307 #endif /* INET */
308 
309 #ifdef INET6
310 	case AF_INET6:
311 		if ((IN6_IS_ADDR_UNSPECIFIED(&ipo->ipo_dst.sin6.sin6_addr)) ||
312 		    (memcmp(&ipo->ipo_dst.sin6.sin6_addr, &in6mask128,
313 		    sizeof(in6mask128)) == 0))
314 			dignore = 1;
315 		break;
316 #endif /* INET6 */
317 	}
318 
319 	/* Likewise for source. */
320 	switch (ipo->ipo_src.sa.sa_family) {
321 #ifdef INET
322 	case AF_INET:
323 		if (ipo->ipo_src.sin.sin_addr.s_addr == INADDR_ANY)
324 			signore = 1;
325 		break;
326 #endif /* INET */
327 
328 #ifdef INET6
329 	case AF_INET6:
330 		if (IN6_IS_ADDR_UNSPECIFIED(&ipo->ipo_src.sin6.sin6_addr))
331 			signore = 1;
332 		break;
333 #endif /* INET6 */
334 	}
335 
336 	/* Do we have a cached entry ? If so, check if it's still valid. */
337 	if ((ipo->ipo_tdb) && (ipo->ipo_tdb->tdb_flags & TDBF_INVALID)) {
338 		TAILQ_REMOVE(&ipo->ipo_tdb->tdb_policy_head, ipo,
339 		    ipo_tdb_next);
340 		ipo->ipo_tdb = NULL;
341 	}
342 
343 	/* Outgoing packet policy check. */
344 	if (direction == IPSP_DIRECTION_OUT) {
345 		/*
346 		 * Fetch the incoming TDB based on the SPI passed
347 		 * in ipsecflow and use it's dstid when looking
348 		 * up the outgoing TDB.
349 		 */
350 		if (ipsecflowinfo &&
351 		   (tdbin = gettdb(rdomain, ipsecflowinfo, &ssrc,
352 		    ipo->ipo_sproto)) != NULL) {
353 			srcid = tdbin->tdb_dstid;
354 			dstid = tdbin->tdb_srcid;
355 		}
356 		/*
357 		 * If the packet is destined for the policy-specified
358 		 * gateway/endhost, and the socket has the BYPASS
359 		 * option set, skip IPsec processing.
360 		 */
361 		if ((inp != NULL) &&
362 		    (inp->inp_seclevel[SL_ESP_TRANS] == IPSEC_LEVEL_BYPASS) &&
363 		    (inp->inp_seclevel[SL_ESP_NETWORK] ==
364 			IPSEC_LEVEL_BYPASS) &&
365 		    (inp->inp_seclevel[SL_AUTH] == IPSEC_LEVEL_BYPASS)) {
366 			/* Direct match. */
367 			if (dignore ||
368 			    !memcmp(&sdst, &ipo->ipo_dst, sdst.sa.sa_len)) {
369 				*error = 0;
370 				return NULL;
371 			}
372 		}
373 
374 		/* Check that the cached TDB (if present), is appropriate. */
375 		if (ipo->ipo_tdb) {
376 			if ((ipo->ipo_last_searched <= ipsec_last_added) ||
377 			    (ipo->ipo_sproto != ipo->ipo_tdb->tdb_sproto) ||
378 			    memcmp(dignore ? &sdst : &ipo->ipo_dst,
379 			    &ipo->ipo_tdb->tdb_dst,
380 			    ipo->ipo_tdb->tdb_dst.sa.sa_len))
381 				goto nomatchout;
382 
383 			if (!ipsp_aux_match(ipo->ipo_tdb,
384 			    srcid ? srcid : ipo->ipo_srcid,
385 			    dstid ? dstid : ipo->ipo_dstid,
386 			    ipo->ipo_local_cred, NULL,
387 			    &ipo->ipo_addr, &ipo->ipo_mask))
388 				goto nomatchout;
389 
390 			/* Cached entry is good. */
391 			*error = 0;
392 			return ipsp_spd_inp(m, af, hlen, error, direction,
393 			    tdbp, inp, ipo);
394 
395   nomatchout:
396 			/* Cached TDB was not good. */
397 			TAILQ_REMOVE(&ipo->ipo_tdb->tdb_policy_head, ipo,
398 			    ipo_tdb_next);
399 			ipo->ipo_tdb = NULL;
400 			ipo->ipo_last_searched = 0;
401 		}
402 
403 		/*
404 		 * If no SA has been added since the last time we did a
405 		 * lookup, there's no point searching for one. However, if the
406 		 * destination gateway is left unspecified (or is all-1's),
407 		 * always lookup since this is a generic-match rule
408 		 * (otherwise, we can have situations where SAs to some
409 		 * destinations exist but are not used, possibly leading to an
410 		 * explosion in the number of acquired SAs).
411 		 */
412 		if (ipo->ipo_last_searched <= ipsec_last_added)	{
413 			/* "Touch" the entry. */
414 			if (dignore == 0)
415 				ipo->ipo_last_searched = time_second;
416 
417 			/* Find an appropriate SA from the existing ones. */
418 			ipo->ipo_tdb =
419 			    gettdbbyaddr(rdomain,
420 				dignore ? &sdst : &ipo->ipo_dst,
421 				ipo->ipo_sproto,
422 				srcid ? srcid : ipo->ipo_srcid,
423 				dstid ? dstid : ipo->ipo_dstid,
424 				ipo->ipo_local_cred, m, af,
425 				&ipo->ipo_addr, &ipo->ipo_mask);
426 			if (ipo->ipo_tdb) {
427 				TAILQ_INSERT_TAIL(&ipo->ipo_tdb->tdb_policy_head,
428 				    ipo, ipo_tdb_next);
429 				*error = 0;
430 				return ipsp_spd_inp(m, af, hlen, error,
431 				    direction, tdbp, inp, ipo);
432 			}
433 		}
434 
435 		/* So, we don't have an SA -- just a policy. */
436 		switch (ipo->ipo_type) {
437 		case IPSP_IPSEC_REQUIRE:
438 			/* Acquire SA through key management. */
439 			if (ipsp_acquire_sa(ipo,
440 			    dignore ? &sdst : &ipo->ipo_dst,
441 			    signore ? NULL : &ipo->ipo_src, ddst, m) != 0) {
442 				*error = EACCES;
443 				return NULL;
444 			}
445 
446 			/* FALLTHROUGH */
447 		case IPSP_IPSEC_DONTACQ:
448 			*error = -EINVAL; /* Silently drop packet. */
449 			return NULL;
450 
451 		case IPSP_IPSEC_ACQUIRE:
452 			/* Acquire SA through key management. */
453 			ipsp_acquire_sa(ipo, dignore ? &sdst : &ipo->ipo_dst,
454 			    signore ? NULL : &ipo->ipo_src, ddst, NULL);
455 
456 			/* FALLTHROUGH */
457 		case IPSP_IPSEC_USE:
458 			*error = 0;
459 			return ipsp_spd_inp(m, af, hlen, error, direction,
460 			    tdbp, inp, ipo);
461 		}
462 	} else { /* IPSP_DIRECTION_IN */
463 		if (tdbp != NULL) {
464 			/* Direct match in the cache. */
465 			if (ipo->ipo_tdb == tdbp) {
466 				*error = 0;
467 				return ipsp_spd_inp(m, af, hlen, error,
468 				    direction, tdbp, inp, ipo);
469 			}
470 
471 			if (memcmp(dignore ? &ssrc : &ipo->ipo_dst,
472 			    &tdbp->tdb_src, tdbp->tdb_src.sa.sa_len) ||
473 			    (ipo->ipo_sproto != tdbp->tdb_sproto))
474 				goto nomatchin;
475 
476 			/* Match source ID. */
477 			if (ipo->ipo_srcid) {
478 				if (tdbp->tdb_dstid == NULL ||
479 				    !ipsp_ref_match(ipo->ipo_srcid,
480 					tdbp->tdb_dstid))
481 					goto nomatchin;
482 			}
483 
484 			/* Match destination ID. */
485 			if (ipo->ipo_dstid) {
486 				if (tdbp->tdb_srcid == NULL ||
487 				    !ipsp_ref_match(ipo->ipo_dstid,
488 					tdbp->tdb_srcid))
489 					goto nomatchin;
490 			}
491 
492 			/* Add it to the cache. */
493 			if (ipo->ipo_tdb)
494 				TAILQ_REMOVE(&ipo->ipo_tdb->tdb_policy_head,
495 				    ipo, ipo_tdb_next);
496 			ipo->ipo_tdb = tdbp;
497 			TAILQ_INSERT_TAIL(&tdbp->tdb_policy_head, ipo,
498 			    ipo_tdb_next);
499 			*error = 0;
500 			return ipsp_spd_inp(m, af, hlen, error, direction,
501 			    tdbp, inp, ipo);
502 
503   nomatchin: /* Nothing needed here, falling through */
504 	;
505 		}
506 
507 		/* Check whether cached entry applies. */
508 		if (ipo->ipo_tdb) {
509 			/*
510 			 * We only need to check that the correct
511 			 * security protocol and security gateway are
512 			 * set; credentials/IDs will be the same,
513 			 * since the cached entry is linked on this
514 			 * policy.
515 			 */
516 			if (ipo->ipo_sproto == ipo->ipo_tdb->tdb_sproto &&
517 			    !memcmp(&ipo->ipo_tdb->tdb_src,
518 			    dignore ? &ssrc : &ipo->ipo_dst,
519 			    ipo->ipo_tdb->tdb_src.sa.sa_len))
520 				goto skipinputsearch;
521 
522 			/* Not applicable, unlink. */
523 			TAILQ_REMOVE(&ipo->ipo_tdb->tdb_policy_head, ipo,
524 			    ipo_tdb_next);
525 			ipo->ipo_last_searched = 0;
526 			ipo->ipo_tdb = NULL;
527 		}
528 
529 		/* Find whether there exists an appropriate SA. */
530 		if (ipo->ipo_last_searched <= ipsec_last_added)	{
531 			if (dignore == 0)
532 				ipo->ipo_last_searched = time_second;
533 
534 			ipo->ipo_tdb =
535 			    gettdbbysrc(rdomain,
536 				dignore ? &ssrc : &ipo->ipo_dst,
537 				ipo->ipo_sproto, ipo->ipo_srcid,
538 				ipo->ipo_dstid, m, af, &ipo->ipo_addr,
539 				&ipo->ipo_mask);
540 			if (ipo->ipo_tdb)
541 				TAILQ_INSERT_TAIL(&ipo->ipo_tdb->tdb_policy_head,
542 				    ipo, ipo_tdb_next);
543 		}
544   skipinputsearch:
545 
546 		switch (ipo->ipo_type) {
547 		case IPSP_IPSEC_REQUIRE:
548 			/* If appropriate SA exists, don't acquire another. */
549 			if (ipo->ipo_tdb) {
550 				*error = -EINVAL;
551 				return NULL;
552 			}
553 
554 			/* Acquire SA through key management. */
555 			if ((*error = ipsp_acquire_sa(ipo,
556 			    dignore ? &ssrc : &ipo->ipo_dst,
557 			    signore ? NULL : &ipo->ipo_src, ddst, m)) != 0)
558 				return NULL;
559 
560 			/* FALLTHROUGH */
561 		case IPSP_IPSEC_DONTACQ:
562 			/* Drop packet. */
563 			*error = -EINVAL;
564 			return NULL;
565 
566 		case IPSP_IPSEC_ACQUIRE:
567 			/* If appropriate SA exists, don't acquire another. */
568 			if (ipo->ipo_tdb) {
569 				*error = 0;
570 				return ipsp_spd_inp(m, af, hlen, error,
571 				    direction, tdbp, inp, ipo);
572 			}
573 
574 			/* Acquire SA through key management. */
575 			ipsp_acquire_sa(ipo, dignore ? &ssrc : &ipo->ipo_dst,
576 			    signore ? NULL : &ipo->ipo_src, ddst, NULL);
577 
578 			/* FALLTHROUGH */
579 		case IPSP_IPSEC_USE:
580 			*error = 0;
581 			return ipsp_spd_inp(m, af, hlen, error, direction,
582 			    tdbp, inp, ipo);
583 		}
584 	}
585 
586 	/* Shouldn't ever get this far. */
587 	*error = EINVAL;
588 	return NULL;
589 }
590 
591 /*
592  * Delete a policy from the SPD.
593  */
594 int
595 ipsec_delete_policy(struct ipsec_policy *ipo)
596 {
597 	struct rt_addrinfo info;
598 	struct ipsec_acquire *ipa;
599 	int err = 0;
600 
601 	if (--ipo->ipo_ref_count > 0)
602 		return 0;
603 
604 	/* Delete from SPD. */
605 	if (!(ipo->ipo_flags & IPSP_POLICY_SOCKET)) {
606 		memset(&info, 0, sizeof(info));
607 		info.rti_info[RTAX_DST] = (struct sockaddr *)&ipo->ipo_addr;
608 		info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&ipo->ipo_mask;
609 
610 		/* XXX other tables? */
611 		err = rtrequest1(RTM_DELETE, &info, RTP_DEFAULT, NULL,
612 		    ipo->ipo_rdomain);
613 	}
614 	if (ipo->ipo_tdb != NULL)
615 		TAILQ_REMOVE(&ipo->ipo_tdb->tdb_policy_head, ipo,
616 		    ipo_tdb_next);
617 
618 	while ((ipa = TAILQ_FIRST(&ipo->ipo_acquires)) != NULL)
619 		ipsp_delete_acquire(ipa);
620 
621 	TAILQ_REMOVE(&ipsec_policy_head, ipo, ipo_list);
622 
623 	if (ipo->ipo_srcid)
624 		ipsp_reffree(ipo->ipo_srcid);
625 	if (ipo->ipo_dstid)
626 		ipsp_reffree(ipo->ipo_dstid);
627 	if (ipo->ipo_local_cred)
628 		ipsp_reffree(ipo->ipo_local_cred);
629 	if (ipo->ipo_local_auth)
630 		ipsp_reffree(ipo->ipo_local_auth);
631 
632 	if (!(ipo->ipo_flags & IPSP_POLICY_SOCKET))
633 		ipsec_in_use--;
634 
635 	pool_put(&ipsec_policy_pool, ipo);
636 
637 	return err;
638 }
639 
640 /*
641  * Add a policy to the SPD.
642  */
643 struct ipsec_policy *
644 ipsec_add_policy(struct inpcb *inp, int af, int direction)
645 {
646 	struct ipsec_policy *ipon;
647 
648 	if (ipsec_policy_pool_initialized == 0) {
649 		ipsec_policy_pool_initialized = 1;
650 		pool_init(&ipsec_policy_pool, sizeof(struct ipsec_policy),
651 		    0, 0, 0, "ipsec policy", NULL);
652 	}
653 
654 	ipon = pool_get(&ipsec_policy_pool, PR_NOWAIT|PR_ZERO);
655 	if (ipon == NULL)
656 		return NULL;
657 
658 	ipon->ipo_ref_count = 1;
659 	ipon->ipo_flags |= IPSP_POLICY_SOCKET;
660 
661 	ipon->ipo_type = IPSP_IPSEC_REQUIRE; /* XXX */
662 
663 	/* XXX
664 	 * We should actually be creating a linked list of
665 	 * policies (for tunnel/transport and ESP/AH), as needed.
666 	 */
667 	ipon->ipo_sproto = IPPROTO_ESP;
668 	ipon->ipo_rdomain = rtable_l2(inp->inp_rtableid);
669 
670 	TAILQ_INIT(&ipon->ipo_acquires);
671 	TAILQ_INSERT_HEAD(&ipsec_policy_head, ipon, ipo_list);
672 
673 	ipsec_update_policy(inp, ipon, af, direction);
674 
675 	return ipon;
676 }
677 
678 /*
679  * Update a PCB-attached policy.
680  */
681 void
682 ipsec_update_policy(struct inpcb *inp, struct ipsec_policy *ipon, int af,
683     int direction)
684 {
685 	ipon->ipo_addr.sen_len = ipon->ipo_mask.sen_len = SENT_LEN;
686 	ipon->ipo_addr.sen_family = ipon->ipo_mask.sen_family = PF_KEY;
687 	ipon->ipo_src.sa.sa_family = ipon->ipo_dst.sa.sa_family = af;
688 
689 	switch (af) {
690 	case AF_INET:
691 #ifdef INET
692 		ipon->ipo_addr.sen_type = ipon->ipo_mask.sen_type = SENT_IP4;
693 		ipon->ipo_addr.sen_ip_src = inp->inp_laddr;
694 		ipon->ipo_addr.sen_ip_dst = inp->inp_faddr;
695 		ipon->ipo_addr.sen_sport = inp->inp_lport;
696 		ipon->ipo_addr.sen_dport = inp->inp_fport;
697 		ipon->ipo_addr.sen_proto =
698 		    inp->inp_socket->so_proto->pr_protocol;
699 		ipon->ipo_addr.sen_direction = direction;
700 
701 		ipon->ipo_mask.sen_ip_src.s_addr = 0xffffffff;
702 		ipon->ipo_mask.sen_ip_dst.s_addr = 0xffffffff;
703 		ipon->ipo_mask.sen_sport = ipon->ipo_mask.sen_dport = 0xffff;
704 		ipon->ipo_mask.sen_proto = 0xff;
705 		ipon->ipo_mask.sen_direction = direction;
706 
707 		ipon->ipo_src.sa.sa_len = sizeof(struct sockaddr_in);
708 		ipon->ipo_dst.sa.sa_len = sizeof(struct sockaddr_in);
709 		ipon->ipo_src.sin.sin_addr = inp->inp_laddr;
710 		ipon->ipo_dst.sin.sin_addr = inp->inp_faddr;
711 #endif /* INET */
712 		break;
713 
714 	case AF_INET6:
715 #ifdef INET6
716 		ipon->ipo_addr.sen_type = ipon->ipo_mask.sen_type = SENT_IP6;
717 		ipon->ipo_addr.sen_ip6_src = inp->inp_laddr6;
718 		ipon->ipo_addr.sen_ip6_dst = inp->inp_faddr6;
719 		ipon->ipo_addr.sen_ip6_sport = inp->inp_lport;
720 		ipon->ipo_addr.sen_ip6_dport = inp->inp_fport;
721 		ipon->ipo_addr.sen_ip6_proto =
722 		    inp->inp_socket->so_proto->pr_protocol;
723 		ipon->ipo_addr.sen_ip6_direction = direction;
724 
725 		ipon->ipo_mask.sen_ip6_src = in6mask128;
726 		ipon->ipo_mask.sen_ip6_dst = in6mask128;
727 		ipon->ipo_mask.sen_ip6_sport = 0xffff;
728 		ipon->ipo_mask.sen_ip6_dport = 0xffff;
729 		ipon->ipo_mask.sen_ip6_proto = 0xff;
730 		ipon->ipo_mask.sen_ip6_direction = direction;
731 
732 		ipon->ipo_src.sa.sa_len = sizeof(struct sockaddr_in6);
733 		ipon->ipo_dst.sa.sa_len = sizeof(struct sockaddr_in6);
734 		ipon->ipo_src.sin6.sin6_addr = inp->inp_laddr6;
735 		ipon->ipo_dst.sin6.sin6_addr = inp->inp_faddr6;
736 #endif /* INET6 */
737 		break;
738 	}
739 }
740 
741 /*
742  * Delete a pending IPsec acquire record.
743  */
744 void
745 ipsp_delete_acquire(void *v)
746 {
747 	struct ipsec_acquire *ipa = v;
748 
749 	timeout_del(&ipa->ipa_timeout);
750 	TAILQ_REMOVE(&ipsec_acquire_head, ipa, ipa_next);
751 	if (ipa->ipa_policy != NULL)
752 		TAILQ_REMOVE(&ipa->ipa_policy->ipo_acquires, ipa,
753 		    ipa_ipo_next);
754 	pool_put(&ipsec_acquire_pool, ipa);
755 }
756 
757 /*
758  * Find out if there's an ACQUIRE pending.
759  * XXX Need a better structure.
760  */
761 struct ipsec_acquire *
762 ipsp_pending_acquire(struct ipsec_policy *ipo, union sockaddr_union *gw)
763 {
764 	struct ipsec_acquire *ipa;
765 
766 	TAILQ_FOREACH (ipa, &ipo->ipo_acquires, ipa_ipo_next) {
767 		if (!memcmp(gw, &ipa->ipa_addr, gw->sa.sa_len))
768 			return ipa;
769 	}
770 
771 	return NULL;
772 }
773 
774 /*
775  * Signal key management that we need an SA.
776  * XXX For outgoing policies, we could try to hold on to the mbuf.
777  */
778 int
779 ipsp_acquire_sa(struct ipsec_policy *ipo, union sockaddr_union *gw,
780     union sockaddr_union *laddr, struct sockaddr_encap *ddst, struct mbuf *m)
781 {
782 	struct ipsec_acquire *ipa;
783 
784 	/*
785 	 * If this is a socket policy, it has to have authentication
786 	 * information accompanying it --- can't tell key mgmt. to
787 	 * "find" it for us. This avoids abusing key mgmt. to authenticate
788 	 * on an application's behalf, even if the application doesn't
789 	 * have/know (and shouldn't) the appropriate authentication
790 	 * material (passphrase, private key, etc.)
791 	 */
792 	if (ipo->ipo_flags & IPSP_POLICY_SOCKET &&
793 	    ipo->ipo_local_auth == NULL)
794 		return EINVAL;
795 
796 	/* Check whether request has been made already. */
797 	if ((ipa = ipsp_pending_acquire(ipo, gw)) != NULL)
798 		return 0;
799 
800 	/* Add request in cache and proceed. */
801 	if (ipsec_acquire_pool_initialized == 0) {
802 		ipsec_acquire_pool_initialized = 1;
803 		pool_init(&ipsec_acquire_pool, sizeof(struct ipsec_acquire),
804 		    0, 0, 0, "ipsec acquire", NULL);
805 	}
806 
807 	ipa = pool_get(&ipsec_acquire_pool, PR_NOWAIT|PR_ZERO);
808 	if (ipa == NULL)
809 		return ENOMEM;
810 
811 	bcopy(gw, &ipa->ipa_addr, sizeof(union sockaddr_union));
812 
813 	timeout_set(&ipa->ipa_timeout, ipsp_delete_acquire, ipa);
814 
815 	ipa->ipa_info.sen_len = ipa->ipa_mask.sen_len = SENT_LEN;
816 	ipa->ipa_info.sen_family = ipa->ipa_mask.sen_family = PF_KEY;
817 
818 	/* Just copy the right information. */
819 	switch (ipo->ipo_addr.sen_type) {
820 #ifdef INET
821 	case SENT_IP4:
822 		ipa->ipa_info.sen_type = ipa->ipa_mask.sen_type = SENT_IP4;
823 		ipa->ipa_info.sen_direction = ipo->ipo_addr.sen_direction;
824 		ipa->ipa_mask.sen_direction = ipo->ipo_mask.sen_direction;
825 
826 		if (ipsp_is_unspecified(ipo->ipo_dst)) {
827 			ipa->ipa_info.sen_ip_src = ddst->sen_ip_src;
828 			ipa->ipa_mask.sen_ip_src.s_addr = INADDR_BROADCAST;
829 		} else {
830 			ipa->ipa_info.sen_ip_src = ipo->ipo_addr.sen_ip_src;
831 			ipa->ipa_mask.sen_ip_src = ipo->ipo_mask.sen_ip_src;
832 		}
833 
834 		if (ipsp_is_unspecified(ipo->ipo_dst)) {
835 			ipa->ipa_info.sen_ip_dst = ddst->sen_ip_dst;
836 			ipa->ipa_mask.sen_ip_dst.s_addr = INADDR_BROADCAST;
837 		} else {
838 			ipa->ipa_info.sen_ip_dst = ipo->ipo_addr.sen_ip_dst;
839 			ipa->ipa_mask.sen_ip_dst = ipo->ipo_mask.sen_ip_dst;
840 		}
841 
842 		ipa->ipa_info.sen_proto = ipo->ipo_addr.sen_proto;
843 		ipa->ipa_mask.sen_proto = ipo->ipo_mask.sen_proto;
844 
845 		if (ipo->ipo_addr.sen_proto) {
846 			ipa->ipa_info.sen_sport = ipo->ipo_addr.sen_sport;
847 			ipa->ipa_mask.sen_sport = ipo->ipo_mask.sen_sport;
848 
849 			ipa->ipa_info.sen_dport = ipo->ipo_addr.sen_dport;
850 			ipa->ipa_mask.sen_dport = ipo->ipo_mask.sen_dport;
851 		}
852 		break;
853 #endif /* INET */
854 
855 #ifdef INET6
856 	case SENT_IP6:
857 		ipa->ipa_info.sen_type = ipa->ipa_mask.sen_type = SENT_IP6;
858 		ipa->ipa_info.sen_ip6_direction =
859 		    ipo->ipo_addr.sen_ip6_direction;
860 		ipa->ipa_mask.sen_ip6_direction =
861 		    ipo->ipo_mask.sen_ip6_direction;
862 
863 		if (ipsp_is_unspecified(ipo->ipo_dst)) {
864 			ipa->ipa_info.sen_ip6_src = ddst->sen_ip6_src;
865 			ipa->ipa_mask.sen_ip6_src = in6mask128;
866 		} else {
867 			ipa->ipa_info.sen_ip6_src = ipo->ipo_addr.sen_ip6_src;
868 			ipa->ipa_mask.sen_ip6_src = ipo->ipo_mask.sen_ip6_src;
869 		}
870 
871 		if (ipsp_is_unspecified(ipo->ipo_dst)) {
872 			ipa->ipa_info.sen_ip6_dst = ddst->sen_ip6_dst;
873 			ipa->ipa_mask.sen_ip6_dst = in6mask128;
874 		} else {
875 			ipa->ipa_info.sen_ip6_dst = ipo->ipo_addr.sen_ip6_dst;
876 			ipa->ipa_mask.sen_ip6_dst = ipo->ipo_mask.sen_ip6_dst;
877 		}
878 
879 		ipa->ipa_info.sen_ip6_proto = ipo->ipo_addr.sen_ip6_proto;
880 		ipa->ipa_mask.sen_ip6_proto = ipo->ipo_mask.sen_ip6_proto;
881 
882 		if (ipo->ipo_mask.sen_ip6_proto) {
883 			ipa->ipa_info.sen_ip6_sport =
884 			    ipo->ipo_addr.sen_ip6_sport;
885 			ipa->ipa_mask.sen_ip6_sport =
886 			    ipo->ipo_mask.sen_ip6_sport;
887 			ipa->ipa_info.sen_ip6_dport =
888 			    ipo->ipo_addr.sen_ip6_dport;
889 			ipa->ipa_mask.sen_ip6_dport =
890 			    ipo->ipo_mask.sen_ip6_dport;
891 		}
892 		break;
893 #endif /* INET6 */
894 
895 	default:
896 		pool_put(&ipsec_acquire_pool, ipa);
897 		return 0;
898 	}
899 
900 	timeout_add_sec(&ipa->ipa_timeout, ipsec_expire_acquire);
901 
902 	TAILQ_INSERT_TAIL(&ipsec_acquire_head, ipa, ipa_next);
903 	TAILQ_INSERT_TAIL(&ipo->ipo_acquires, ipa, ipa_ipo_next);
904 	ipa->ipa_policy = ipo;
905 
906 	/* PF_KEYv2 notification message. */
907 	return pfkeyv2_acquire(ipo, gw, laddr, &ipa->ipa_seq, ddst);
908 }
909 
910 /*
911  * Deal with PCB security requirements.
912  */
913 struct tdb *
914 ipsp_spd_inp(struct mbuf *m, int af, int hlen, int *error, int direction,
915     struct tdb *tdbp, struct inpcb *inp, struct ipsec_policy *ipo)
916 {
917 	struct ipsec_policy sipon;
918 	struct tdb_ident *tdbi;
919 	struct m_tag *mtag;
920 	struct tdb *tdb = NULL;
921 
922 	/* Sanity check. */
923 	if (inp == NULL)
924 		goto justreturn;
925 
926 	/* Verify that we need to check for socket policy. */
927 	if ((inp->inp_seclevel[SL_ESP_TRANS] == IPSEC_LEVEL_BYPASS ||
928 	    inp->inp_seclevel[SL_ESP_TRANS] == IPSEC_LEVEL_NONE) &&
929 	    (inp->inp_seclevel[SL_ESP_NETWORK] == IPSEC_LEVEL_BYPASS ||
930 	    inp->inp_seclevel[SL_ESP_NETWORK] == IPSEC_LEVEL_NONE) &&
931 	    (inp->inp_seclevel[SL_AUTH] == IPSEC_LEVEL_BYPASS ||
932 	    inp->inp_seclevel[SL_AUTH] == IPSEC_LEVEL_NONE))
933 		goto justreturn;
934 
935 	switch (direction) {
936 	case IPSP_DIRECTION_IN:
937 		/*
938 		 * Some further checking: if the socket has specified
939 		 * that it will accept unencrypted traffic, don't
940 		 * bother checking any further -- just accept the packet.
941 		 */
942 		if ((inp->inp_seclevel[SL_ESP_TRANS] == IPSEC_LEVEL_AVAIL ||
943 		    inp->inp_seclevel[SL_ESP_TRANS] == IPSEC_LEVEL_USE) &&
944 		    (inp->inp_seclevel[SL_ESP_NETWORK] == IPSEC_LEVEL_AVAIL ||
945 		    inp->inp_seclevel[SL_ESP_NETWORK] == IPSEC_LEVEL_USE) &&
946 		    (inp->inp_seclevel[SL_AUTH] == IPSEC_LEVEL_AVAIL ||
947 		    inp->inp_seclevel[SL_AUTH] == IPSEC_LEVEL_USE))
948 			goto justreturn;
949 
950 		/* Initialize socket policy if unset. */
951 		if (inp->inp_ipo == NULL) {
952 			inp->inp_ipo = ipsec_add_policy(inp, af,
953 			    IPSP_DIRECTION_OUT);
954 			if (inp->inp_ipo == NULL) {
955 				*error = ENOBUFS;
956 				return NULL;
957 			}
958 		}
959 
960 		/*
961 		 * So we *must* have protected traffic. Let's see what
962 		 * we have received then.
963 		 */
964 		if (inp->inp_tdb_in != NULL) {
965 			if (inp->inp_tdb_in == tdbp)
966 				goto justreturn; /* We received packet under a
967 						  * previously-accepted TDB. */
968 
969 			/*
970 			 * We should be receiving protected traffic, and
971 			 * have an SA in place, but packet was received
972 			 * unprotected. Simply discard.
973 			 */
974 			if (tdbp == NULL) {
975 				*error = -EINVAL;
976 				return NULL;
977 			}
978 
979 			/* Update, since we may need all the relevant info. */
980 			ipsec_update_policy(inp, inp->inp_ipo, af,
981 			    IPSP_DIRECTION_OUT);
982 
983 			/*
984 			 * Check that the TDB the packet was received under
985 			 * is acceptable under the socket policy. If so,
986 			 * accept the packet; otherwise, discard.
987 			 */
988 			if (tdbp->tdb_sproto == inp->inp_ipo->ipo_sproto &&
989 			    !memcmp(&tdbp->tdb_src, &inp->inp_ipo->ipo_dst,
990 			    SA_LEN(&tdbp->tdb_src.sa)) &&
991 			    ipsp_aux_match(tdbp, inp->inp_ipo->ipo_srcid,
992 			    inp->inp_ipo->ipo_dstid, NULL, NULL,
993 			    &inp->inp_ipo->ipo_addr, &inp->inp_ipo->ipo_mask))
994 				goto justreturn;
995 			else {
996 				*error = -EINVAL;
997 				return NULL;
998 			}
999 		} else {
1000 			/* Update, since we may need all the relevant info. */
1001 			ipsec_update_policy(inp, inp->inp_ipo, af,
1002 			    IPSP_DIRECTION_OUT);
1003 
1004 			/*
1005 			 * If the packet was received under an SA, see if
1006 			 * it's acceptable under socket policy. If it is,
1007 			 * accept the packet.
1008 			 */
1009 			if (tdbp != NULL &&
1010 			    tdbp->tdb_sproto == inp->inp_ipo->ipo_sproto &&
1011 			    !memcmp(&tdbp->tdb_src, &inp->inp_ipo->ipo_dst,
1012 			    SA_LEN(&tdbp->tdb_src.sa)) &&
1013 			    ipsp_aux_match(tdbp, inp->inp_ipo->ipo_srcid,
1014 			    inp->inp_ipo->ipo_dstid, NULL, NULL,
1015 			    &inp->inp_ipo->ipo_addr, &inp->inp_ipo->ipo_mask))
1016 				goto justreturn;
1017 
1018 			/*
1019 			 * If the packet was not received under an SA, or
1020 			 * if the SA it was received under is not acceptable,
1021 			 * see if we already have an acceptable SA
1022 			 * established. If we do, discard packet.
1023 			 */
1024 			if (inp->inp_ipo->ipo_last_searched <=
1025 			    ipsec_last_added) {
1026 				inp->inp_ipo->ipo_last_searched = time_second;
1027 
1028 				/* Do we have an SA already established ? */
1029 				if (gettdbbysrc(rtable_l2(inp->inp_rtableid),
1030 				    &inp->inp_ipo->ipo_dst,
1031 				    inp->inp_ipo->ipo_sproto,
1032 				    inp->inp_ipo->ipo_srcid,
1033 				    inp->inp_ipo->ipo_dstid, m, af,
1034 				    &inp->inp_ipo->ipo_addr,
1035 				    &inp->inp_ipo->ipo_mask) != NULL) {
1036 					*error = -EINVAL;
1037 					return NULL;
1038 				}
1039 				/* Fall through */
1040 			}
1041 
1042 			/*
1043 			 * If we don't have an appropriate SA, acquire one
1044 			 * and discard the packet.
1045 			 */
1046 			ipsp_acquire_sa(inp->inp_ipo, &inp->inp_ipo->ipo_dst,
1047 			    &inp->inp_ipo->ipo_src, &inp->inp_ipo->ipo_addr, m);
1048 			*error = -EINVAL;
1049 			return NULL;
1050 		}
1051 
1052 		break;
1053 
1054 	case IPSP_DIRECTION_OUT:
1055 		/* Do we have a cached entry ? */
1056 		if (inp->inp_tdb_out != NULL) {
1057 			/*
1058 			 * If we also have to apply a different TDB as
1059 			 * a result of a system-wide policy, add a tag
1060 			 * to the packet.
1061 			 */
1062 			if (ipo != NULL && m != NULL &&
1063 			    ipo->ipo_tdb != NULL &&
1064 			    ipo->ipo_tdb != inp->inp_tdb_out) {
1065 				tdb = inp->inp_tdb_out;
1066 				goto tagandreturn;
1067 			} else
1068 				return inp->inp_tdb_out;
1069 		}
1070 
1071 		/*
1072 		 * We need to either find an SA with the appropriate
1073 		 * characteristics and link it to the PCB, or acquire
1074 		 * one.
1075 		 */
1076 		/* XXX Only support one policy/protocol for now. */
1077 		if (inp->inp_ipo != NULL) {
1078 			if (inp->inp_ipo->ipo_last_searched <=
1079 			    ipsec_last_added) {
1080 				inp->inp_ipo->ipo_last_searched = time_second;
1081 
1082 				/* Update, just in case. */
1083 				ipsec_update_policy(inp, inp->inp_ipo, af,
1084 				    IPSP_DIRECTION_OUT);
1085 
1086 				tdb = gettdbbyaddr(rtable_l2(inp->inp_rtableid),
1087 				    &inp->inp_ipo->ipo_dst,
1088 				    inp->inp_ipo->ipo_sproto,
1089 				    inp->inp_ipo->ipo_srcid,
1090 				    inp->inp_ipo->ipo_dstid,
1091 				    inp->inp_ipo->ipo_local_cred, m, af,
1092 				    &inp->inp_ipo->ipo_addr,
1093 				    &inp->inp_ipo->ipo_mask);
1094 			}
1095 		} else {
1096 			/*
1097 			 * Construct a pseudo-policy, with just the necessary
1098 			 * fields.
1099 			 */
1100 			ipsec_update_policy(inp, &sipon, af,
1101 			    IPSP_DIRECTION_OUT);
1102 
1103 			tdb = gettdbbyaddr(rtable_l2(inp->inp_rtableid),
1104 			    &sipon.ipo_dst, IPPROTO_ESP, NULL,
1105 			    NULL, NULL, m, af, &sipon.ipo_addr,
1106 			    &sipon.ipo_mask);
1107 		}
1108 
1109 		/* If we found an appropriate SA... */
1110 		if (tdb != NULL) {
1111 			tdb_add_inp(tdb, inp, 0); /* Latch onto PCB. */
1112 
1113 			if (ipo != NULL && ipo->ipo_tdb != NULL &&
1114 			    ipo->ipo_tdb != inp->inp_tdb_out && m != NULL)
1115 				goto tagandreturn;
1116 			else
1117 				return tdb;
1118 		} else {
1119 			/* Do we need to acquire one ? */
1120 			switch (inp->inp_seclevel[SL_ESP_TRANS]) {
1121 			case IPSEC_LEVEL_BYPASS:
1122 			case IPSEC_LEVEL_AVAIL:
1123 				/* No need to do anything. */
1124 				goto justreturn;
1125 			case IPSEC_LEVEL_USE:
1126 			case IPSEC_LEVEL_REQUIRE:
1127 			case IPSEC_LEVEL_UNIQUE:
1128 				/* Initialize socket policy if unset. */
1129 				if (inp->inp_ipo == NULL) {
1130 					inp->inp_ipo = ipsec_add_policy(inp, af, IPSP_DIRECTION_OUT);
1131 					if (inp->inp_ipo == NULL) {
1132 						*error = ENOBUFS;
1133 						return NULL;
1134 					}
1135 				}
1136 
1137 				/* Acquire a new SA. */
1138 				if ((*error = ipsp_acquire_sa(inp->inp_ipo,
1139 				    &inp->inp_ipo->ipo_dst,
1140 				    &inp->inp_ipo->ipo_src,
1141 				    &inp->inp_ipo->ipo_addr, m)) == 0)
1142 					*error = -EINVAL;
1143 
1144 				return NULL;
1145 			default:
1146 				DPRINTF(("ipsp_spd_inp: unknown sock security"
1147 				    " level %d",
1148 				    inp->inp_seclevel[SL_ESP_TRANS]));
1149 				*error = -EINVAL;
1150 				return NULL;
1151 			}
1152 		}
1153 		break;
1154 
1155 	default:  /* Should never happen. */
1156 		*error = -EINVAL;
1157 		return NULL;
1158 	}
1159 
1160  tagandreturn:
1161 	if (tdb == NULL)
1162 		goto justreturn;
1163 
1164 	mtag = m_tag_get(PACKET_TAG_IPSEC_PENDING_TDB,
1165 	    sizeof (struct tdb_ident), M_NOWAIT);
1166 	if (mtag == NULL) {
1167 		*error = ENOMEM;
1168 		return NULL;
1169 	}
1170 
1171 	tdbi = (struct tdb_ident *)(mtag + 1);
1172 	tdbi->spi = ipo->ipo_tdb->tdb_spi;
1173 	tdbi->proto = ipo->ipo_tdb->tdb_sproto;
1174 	tdbi->rdomain = rtable_l2(inp->inp_rtableid);
1175 	bcopy(&ipo->ipo_tdb->tdb_dst, &tdbi->dst,
1176 	    ipo->ipo_tdb->tdb_dst.sa.sa_len);
1177 	m_tag_prepend(m, mtag);
1178 	return tdb;
1179 
1180  justreturn:
1181 	if (ipo != NULL)
1182 		return ipo->ipo_tdb;
1183 	else
1184 		return NULL;
1185 }
1186 
1187 /*
1188  * Find a pending ACQUIRE record based on its sequence number.
1189  * XXX Need to use a better data structure.
1190  */
1191 struct ipsec_acquire *
1192 ipsec_get_acquire(u_int32_t seq)
1193 {
1194 	struct ipsec_acquire *ipa;
1195 
1196 	TAILQ_FOREACH (ipa, &ipsec_acquire_head, ipa_next)
1197 		if (ipa->ipa_seq == seq)
1198 			return ipa;
1199 
1200 	return NULL;
1201 }
1202