xref: /freebsd-13-stable/sys/netipsec/key.c (revision 1219a3f40db386aaa10edfea27d9cc73fdea3935)
1 /*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * This code is referd to RFC 2367
36  */
37 
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41 
42 #include <sys/types.h>
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/fnv_hash.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/mbuf.h>
50 #include <sys/domain.h>
51 #include <sys/protosw.h>
52 #include <sys/malloc.h>
53 #include <sys/rmlock.h>
54 #include <sys/socket.h>
55 #include <sys/socketvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/errno.h>
58 #include <sys/proc.h>
59 #include <sys/queue.h>
60 #include <sys/refcount.h>
61 #include <sys/syslog.h>
62 
63 #include <vm/uma.h>
64 
65 #include <net/if.h>
66 #include <net/if_var.h>
67 #include <net/vnet.h>
68 #include <net/raw_cb.h>
69 
70 #include <netinet/in.h>
71 #include <netinet/in_systm.h>
72 #include <netinet/ip.h>
73 #include <netinet/in_var.h>
74 #include <netinet/udp.h>
75 
76 #ifdef INET6
77 #include <netinet/ip6.h>
78 #include <netinet6/in6_var.h>
79 #include <netinet6/ip6_var.h>
80 #endif /* INET6 */
81 
82 #include <net/pfkeyv2.h>
83 #include <netipsec/keydb.h>
84 #include <netipsec/key.h>
85 #include <netipsec/keysock.h>
86 #include <netipsec/key_debug.h>
87 
88 #include <netipsec/ipsec.h>
89 #ifdef INET6
90 #include <netipsec/ipsec6.h>
91 #endif
92 
93 #include <netipsec/xform.h>
94 #include <machine/in_cksum.h>
95 #include <machine/stdarg.h>
96 
97 /* randomness */
98 #include <sys/random.h>
99 
100 #define FULLMASK	0xff
101 #define	_BITS(bytes)	((bytes) << 3)
102 
103 #define	UINT32_80PCT	0xcccccccc
104 /*
105  * Note on SA reference counting:
106  * - SAs that are not in DEAD state will have (total external reference + 1)
107  *   following value in reference count field.  they cannot be freed and are
108  *   referenced from SA header.
109  * - SAs that are in DEAD state will have (total external reference)
110  *   in reference count field.  they are ready to be freed.  reference from
111  *   SA header will be removed in key_delsav(), when the reference count
112  *   field hits 0 (= no external reference other than from SA header.
113  */
114 
115 VNET_DEFINE(u_int32_t, key_debug_level) = 0;
116 VNET_DEFINE_STATIC(u_int, key_spi_trycnt) = 1000;
117 VNET_DEFINE_STATIC(u_int32_t, key_spi_minval) = 0x100;
118 VNET_DEFINE_STATIC(u_int32_t, key_spi_maxval) = 0x0fffffff;	/* XXX */
119 VNET_DEFINE_STATIC(u_int32_t, policy_id) = 0;
120 /*interval to initialize randseed,1(m)*/
121 VNET_DEFINE_STATIC(u_int, key_int_random) = 60;
122 /* interval to expire acquiring, 30(s)*/
123 VNET_DEFINE_STATIC(u_int, key_larval_lifetime) = 30;
124 /* counter for blocking SADB_ACQUIRE.*/
125 VNET_DEFINE_STATIC(int, key_blockacq_count) = 10;
126 /* lifetime for blocking SADB_ACQUIRE.*/
127 VNET_DEFINE_STATIC(int, key_blockacq_lifetime) = 20;
128 /* preferred old sa rather than new sa.*/
129 VNET_DEFINE_STATIC(int, key_preferred_oldsa) = 1;
130 #define	V_key_spi_trycnt	VNET(key_spi_trycnt)
131 #define	V_key_spi_minval	VNET(key_spi_minval)
132 #define	V_key_spi_maxval	VNET(key_spi_maxval)
133 #define	V_policy_id		VNET(policy_id)
134 #define	V_key_int_random	VNET(key_int_random)
135 #define	V_key_larval_lifetime	VNET(key_larval_lifetime)
136 #define	V_key_blockacq_count	VNET(key_blockacq_count)
137 #define	V_key_blockacq_lifetime	VNET(key_blockacq_lifetime)
138 #define	V_key_preferred_oldsa	VNET(key_preferred_oldsa)
139 
140 VNET_DEFINE_STATIC(u_int32_t, acq_seq) = 0;
141 #define	V_acq_seq		VNET(acq_seq)
142 
143 VNET_DEFINE_STATIC(uint32_t, sp_genid) = 0;
144 #define	V_sp_genid		VNET(sp_genid)
145 
146 /* SPD */
147 TAILQ_HEAD(secpolicy_queue, secpolicy);
148 LIST_HEAD(secpolicy_list, secpolicy);
149 VNET_DEFINE_STATIC(struct secpolicy_queue, sptree[IPSEC_DIR_MAX]);
150 VNET_DEFINE_STATIC(struct secpolicy_queue, sptree_ifnet[IPSEC_DIR_MAX]);
151 static struct rmlock sptree_lock;
152 #define	V_sptree		VNET(sptree)
153 #define	V_sptree_ifnet		VNET(sptree_ifnet)
154 #define	SPTREE_LOCK_INIT()      rm_init(&sptree_lock, "sptree")
155 #define	SPTREE_LOCK_DESTROY()   rm_destroy(&sptree_lock)
156 #define	SPTREE_RLOCK_TRACKER    struct rm_priotracker sptree_tracker
157 #define	SPTREE_RLOCK()          rm_rlock(&sptree_lock, &sptree_tracker)
158 #define	SPTREE_RUNLOCK()        rm_runlock(&sptree_lock, &sptree_tracker)
159 #define	SPTREE_RLOCK_ASSERT()   rm_assert(&sptree_lock, RA_RLOCKED)
160 #define	SPTREE_WLOCK()          rm_wlock(&sptree_lock)
161 #define	SPTREE_WUNLOCK()        rm_wunlock(&sptree_lock)
162 #define	SPTREE_WLOCK_ASSERT()   rm_assert(&sptree_lock, RA_WLOCKED)
163 #define	SPTREE_UNLOCK_ASSERT()  rm_assert(&sptree_lock, RA_UNLOCKED)
164 
165 /* Hash table for lookup SP using unique id */
166 VNET_DEFINE_STATIC(struct secpolicy_list *, sphashtbl);
167 VNET_DEFINE_STATIC(u_long, sphash_mask);
168 #define	V_sphashtbl		VNET(sphashtbl)
169 #define	V_sphash_mask		VNET(sphash_mask)
170 
171 #define	SPHASH_NHASH_LOG2	7
172 #define	SPHASH_NHASH		(1 << SPHASH_NHASH_LOG2)
173 #define	SPHASH_HASHVAL(id)	(key_u32hash(id) & V_sphash_mask)
174 #define	SPHASH_HASH(id)		&V_sphashtbl[SPHASH_HASHVAL(id)]
175 
176 /* SPD cache */
177 struct spdcache_entry {
178    struct secpolicyindex spidx;	/* secpolicyindex */
179    struct secpolicy *sp;	/* cached policy to be used */
180 
181    LIST_ENTRY(spdcache_entry) chain;
182 };
183 LIST_HEAD(spdcache_entry_list, spdcache_entry);
184 
185 #define	SPDCACHE_MAX_ENTRIES_PER_HASH	8
186 
187 VNET_DEFINE_STATIC(u_int, key_spdcache_maxentries) = 0;
188 #define	V_key_spdcache_maxentries	VNET(key_spdcache_maxentries)
189 VNET_DEFINE_STATIC(u_int, key_spdcache_threshold) = 32;
190 #define	V_key_spdcache_threshold	VNET(key_spdcache_threshold)
191 VNET_DEFINE_STATIC(unsigned long, spd_size) = 0;
192 #define	V_spd_size		VNET(spd_size)
193 
194 #define SPDCACHE_ENABLED()	(V_key_spdcache_maxentries != 0)
195 #define SPDCACHE_ACTIVE() \
196 	(SPDCACHE_ENABLED() && V_spd_size >= V_key_spdcache_threshold)
197 
198 VNET_DEFINE_STATIC(struct spdcache_entry_list *, spdcachehashtbl);
199 VNET_DEFINE_STATIC(u_long, spdcachehash_mask);
200 #define	V_spdcachehashtbl	VNET(spdcachehashtbl)
201 #define	V_spdcachehash_mask	VNET(spdcachehash_mask)
202 
203 #define	SPDCACHE_HASHVAL(idx) \
204 	(key_addrprotohash(&(idx)->src, &(idx)->dst, &(idx)->ul_proto) &  \
205 	    V_spdcachehash_mask)
206 
207 /* Each cache line is protected by a mutex */
208 VNET_DEFINE_STATIC(struct mtx *, spdcache_lock);
209 #define	V_spdcache_lock		VNET(spdcache_lock)
210 
211 #define	SPDCACHE_LOCK_INIT(a) \
212 	mtx_init(&V_spdcache_lock[a], "spdcache", \
213 	    "fast ipsec SPD cache", MTX_DEF|MTX_DUPOK)
214 #define	SPDCACHE_LOCK_DESTROY(a)	mtx_destroy(&V_spdcache_lock[a])
215 #define	SPDCACHE_LOCK(a)		mtx_lock(&V_spdcache_lock[a]);
216 #define	SPDCACHE_UNLOCK(a)		mtx_unlock(&V_spdcache_lock[a]);
217 
218 /* SAD */
219 TAILQ_HEAD(secashead_queue, secashead);
220 LIST_HEAD(secashead_list, secashead);
221 VNET_DEFINE_STATIC(struct secashead_queue, sahtree);
222 static struct rmlock sahtree_lock;
223 #define	V_sahtree		VNET(sahtree)
224 #define	SAHTREE_LOCK_INIT()	rm_init(&sahtree_lock, "sahtree")
225 #define	SAHTREE_LOCK_DESTROY()	rm_destroy(&sahtree_lock)
226 #define	SAHTREE_RLOCK_TRACKER	struct rm_priotracker sahtree_tracker
227 #define	SAHTREE_RLOCK()		rm_rlock(&sahtree_lock, &sahtree_tracker)
228 #define	SAHTREE_RUNLOCK()	rm_runlock(&sahtree_lock, &sahtree_tracker)
229 #define	SAHTREE_RLOCK_ASSERT()	rm_assert(&sahtree_lock, RA_RLOCKED)
230 #define	SAHTREE_WLOCK()		rm_wlock(&sahtree_lock)
231 #define	SAHTREE_WUNLOCK()	rm_wunlock(&sahtree_lock)
232 #define	SAHTREE_WLOCK_ASSERT()	rm_assert(&sahtree_lock, RA_WLOCKED)
233 #define	SAHTREE_UNLOCK_ASSERT()	rm_assert(&sahtree_lock, RA_UNLOCKED)
234 
235 /* Hash table for lookup in SAD using SA addresses */
236 VNET_DEFINE_STATIC(struct secashead_list *, sahaddrhashtbl);
237 VNET_DEFINE_STATIC(u_long, sahaddrhash_mask);
238 #define	V_sahaddrhashtbl	VNET(sahaddrhashtbl)
239 #define	V_sahaddrhash_mask	VNET(sahaddrhash_mask)
240 
241 #define	SAHHASH_NHASH_LOG2	7
242 #define	SAHHASH_NHASH		(1 << SAHHASH_NHASH_LOG2)
243 #define	SAHADDRHASH_HASHVAL(idx)	\
244 	(key_addrprotohash(&(idx)->src, &(idx)->dst, &(idx)->proto) & \
245 	    V_sahaddrhash_mask)
246 #define	SAHADDRHASH_HASH(saidx)		\
247     &V_sahaddrhashtbl[SAHADDRHASH_HASHVAL(saidx)]
248 
249 /* Hash table for lookup in SAD using SPI */
250 LIST_HEAD(secasvar_list, secasvar);
251 VNET_DEFINE_STATIC(struct secasvar_list *, savhashtbl);
252 VNET_DEFINE_STATIC(u_long, savhash_mask);
253 #define	V_savhashtbl		VNET(savhashtbl)
254 #define	V_savhash_mask		VNET(savhash_mask)
255 #define	SAVHASH_NHASH_LOG2	7
256 #define	SAVHASH_NHASH		(1 << SAVHASH_NHASH_LOG2)
257 #define	SAVHASH_HASHVAL(spi)	(key_u32hash(spi) & V_savhash_mask)
258 #define	SAVHASH_HASH(spi)	&V_savhashtbl[SAVHASH_HASHVAL(spi)]
259 
260 static uint32_t
key_addrprotohash(const union sockaddr_union * src,const union sockaddr_union * dst,const uint8_t * proto)261 key_addrprotohash(const union sockaddr_union *src,
262     const union sockaddr_union *dst, const uint8_t *proto)
263 {
264 	uint32_t hval;
265 
266 	hval = fnv_32_buf(proto, sizeof(*proto),
267 	    FNV1_32_INIT);
268 	switch (dst->sa.sa_family) {
269 #ifdef INET
270 	case AF_INET:
271 		hval = fnv_32_buf(&src->sin.sin_addr,
272 		    sizeof(in_addr_t), hval);
273 		hval = fnv_32_buf(&dst->sin.sin_addr,
274 		    sizeof(in_addr_t), hval);
275 		break;
276 #endif
277 #ifdef INET6
278 	case AF_INET6:
279 		hval = fnv_32_buf(&src->sin6.sin6_addr,
280 		    sizeof(struct in6_addr), hval);
281 		hval = fnv_32_buf(&dst->sin6.sin6_addr,
282 		    sizeof(struct in6_addr), hval);
283 		break;
284 #endif
285 	default:
286 		hval = 0;
287 		ipseclog((LOG_DEBUG, "%s: unknown address family %d\n",
288 		    __func__, dst->sa.sa_family));
289 	}
290 	return (hval);
291 }
292 
293 static uint32_t
key_u32hash(uint32_t val)294 key_u32hash(uint32_t val)
295 {
296 
297 	return (fnv_32_buf(&val, sizeof(val), FNV1_32_INIT));
298 }
299 
300 							/* registed list */
301 VNET_DEFINE_STATIC(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
302 #define	V_regtree		VNET(regtree)
303 static struct mtx regtree_lock;
304 #define	REGTREE_LOCK_INIT() \
305 	mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
306 #define	REGTREE_LOCK_DESTROY()	mtx_destroy(&regtree_lock)
307 #define	REGTREE_LOCK()		mtx_lock(&regtree_lock)
308 #define	REGTREE_UNLOCK()	mtx_unlock(&regtree_lock)
309 #define	REGTREE_LOCK_ASSERT()	mtx_assert(&regtree_lock, MA_OWNED)
310 
311 /* Acquiring list */
312 LIST_HEAD(secacq_list, secacq);
313 VNET_DEFINE_STATIC(struct secacq_list, acqtree);
314 #define	V_acqtree		VNET(acqtree)
315 static struct mtx acq_lock;
316 #define	ACQ_LOCK_INIT() \
317     mtx_init(&acq_lock, "acqtree", "ipsec SA acquiring list", MTX_DEF)
318 #define	ACQ_LOCK_DESTROY()	mtx_destroy(&acq_lock)
319 #define	ACQ_LOCK()		mtx_lock(&acq_lock)
320 #define	ACQ_UNLOCK()		mtx_unlock(&acq_lock)
321 #define	ACQ_LOCK_ASSERT()	mtx_assert(&acq_lock, MA_OWNED)
322 
323 /* Hash table for lookup in ACQ list using SA addresses */
324 VNET_DEFINE_STATIC(struct secacq_list *, acqaddrhashtbl);
325 VNET_DEFINE_STATIC(u_long, acqaddrhash_mask);
326 #define	V_acqaddrhashtbl	VNET(acqaddrhashtbl)
327 #define	V_acqaddrhash_mask	VNET(acqaddrhash_mask)
328 
329 /* Hash table for lookup in ACQ list using SEQ number */
330 VNET_DEFINE_STATIC(struct secacq_list *, acqseqhashtbl);
331 VNET_DEFINE_STATIC(u_long, acqseqhash_mask);
332 #define	V_acqseqhashtbl		VNET(acqseqhashtbl)
333 #define	V_acqseqhash_mask	VNET(acqseqhash_mask)
334 
335 #define	ACQHASH_NHASH_LOG2	7
336 #define	ACQHASH_NHASH		(1 << ACQHASH_NHASH_LOG2)
337 #define	ACQADDRHASH_HASHVAL(idx)	\
338 	(key_addrprotohash(&(idx)->src, &(idx)->dst, &(idx)->proto) & \
339 	    V_acqaddrhash_mask)
340 #define	ACQSEQHASH_HASHVAL(seq)		\
341     (key_u32hash(seq) & V_acqseqhash_mask)
342 #define	ACQADDRHASH_HASH(saidx)	\
343     &V_acqaddrhashtbl[ACQADDRHASH_HASHVAL(saidx)]
344 #define	ACQSEQHASH_HASH(seq)	\
345     &V_acqseqhashtbl[ACQSEQHASH_HASHVAL(seq)]
346 							/* SP acquiring list */
347 VNET_DEFINE_STATIC(LIST_HEAD(_spacqtree, secspacq), spacqtree);
348 #define	V_spacqtree		VNET(spacqtree)
349 static struct mtx spacq_lock;
350 #define	SPACQ_LOCK_INIT() \
351 	mtx_init(&spacq_lock, "spacqtree", \
352 		"fast ipsec security policy acquire list", MTX_DEF)
353 #define	SPACQ_LOCK_DESTROY()	mtx_destroy(&spacq_lock)
354 #define	SPACQ_LOCK()		mtx_lock(&spacq_lock)
355 #define	SPACQ_UNLOCK()		mtx_unlock(&spacq_lock)
356 #define	SPACQ_LOCK_ASSERT()	mtx_assert(&spacq_lock, MA_OWNED)
357 
358 static const int minsize[] = {
359 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
360 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
361 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
362 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
363 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
364 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
365 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
366 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
367 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
368 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
369 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
370 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
371 	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
372 	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
373 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
374 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
375 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
376 	0,				/* SADB_X_EXT_KMPRIVATE */
377 	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
378 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
379 	sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
380 	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
381 	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
382 	sizeof(struct sadb_address),	/* SADB_X_EXT_NAT_T_OAI */
383 	sizeof(struct sadb_address),	/* SADB_X_EXT_NAT_T_OAR */
384 	sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
385 	sizeof(struct sadb_x_sa_replay), /* SADB_X_EXT_SA_REPLAY */
386 	sizeof(struct sadb_address),	/* SADB_X_EXT_NEW_ADDRESS_SRC */
387 	sizeof(struct sadb_address),	/* SADB_X_EXT_NEW_ADDRESS_DST */
388 };
389 _Static_assert(sizeof(minsize)/sizeof(int) == SADB_EXT_MAX + 1, "minsize size mismatch");
390 
391 static const int maxsize[] = {
392 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
393 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
394 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
395 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
396 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
397 	0,				/* SADB_EXT_ADDRESS_SRC */
398 	0,				/* SADB_EXT_ADDRESS_DST */
399 	0,				/* SADB_EXT_ADDRESS_PROXY */
400 	0,				/* SADB_EXT_KEY_AUTH */
401 	0,				/* SADB_EXT_KEY_ENCRYPT */
402 	0,				/* SADB_EXT_IDENTITY_SRC */
403 	0,				/* SADB_EXT_IDENTITY_DST */
404 	0,				/* SADB_EXT_SENSITIVITY */
405 	0,				/* SADB_EXT_PROPOSAL */
406 	0,				/* SADB_EXT_SUPPORTED_AUTH */
407 	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
408 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
409 	0,				/* SADB_X_EXT_KMPRIVATE */
410 	0,				/* SADB_X_EXT_POLICY */
411 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
412 	sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
413 	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
414 	sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
415 	0,				/* SADB_X_EXT_NAT_T_OAI */
416 	0,				/* SADB_X_EXT_NAT_T_OAR */
417 	sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
418 	sizeof(struct sadb_x_sa_replay), /* SADB_X_EXT_SA_REPLAY */
419 	0,				/* SADB_X_EXT_NEW_ADDRESS_SRC */
420 	0,				/* SADB_X_EXT_NEW_ADDRESS_DST */
421 };
422 _Static_assert(sizeof(maxsize)/sizeof(int) == SADB_EXT_MAX + 1, "minsize size mismatch");
423 
424 /*
425  * Internal values for SA flags:
426  * SADB_X_EXT_F_CLONED means that SA was cloned by key_updateaddresses,
427  *	thus we will not free the most of SA content in key_delsav().
428  */
429 #define	SADB_X_EXT_F_CLONED	0x80000000
430 
431 #define	SADB_CHECKLEN(_mhp, _ext)			\
432     ((_mhp)->extlen[(_ext)] < minsize[(_ext)] || (maxsize[(_ext)] != 0 && \
433 	((_mhp)->extlen[(_ext)] > maxsize[(_ext)])))
434 #define	SADB_CHECKHDR(_mhp, _ext)	((_mhp)->ext[(_ext)] == NULL)
435 
436 VNET_DEFINE_STATIC(int, ipsec_esp_keymin) = 256;
437 VNET_DEFINE_STATIC(int, ipsec_esp_auth) = 0;
438 VNET_DEFINE_STATIC(int, ipsec_ah_keymin) = 128;
439 
440 #define	V_ipsec_esp_keymin	VNET(ipsec_esp_keymin)
441 #define	V_ipsec_esp_auth	VNET(ipsec_esp_auth)
442 #define	V_ipsec_ah_keymin	VNET(ipsec_ah_keymin)
443 
444 #ifdef IPSEC_DEBUG
445 VNET_DEFINE(int, ipsec_debug) = 1;
446 #else
447 VNET_DEFINE(int, ipsec_debug) = 0;
448 #endif
449 
450 #ifdef INET
451 SYSCTL_DECL(_net_inet_ipsec);
452 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG, debug,
453     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
454     "Enable IPsec debugging output when set.");
455 #endif
456 #ifdef INET6
457 SYSCTL_DECL(_net_inet6_ipsec6);
458 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG, debug,
459     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
460     "Enable IPsec debugging output when set.");
461 #endif
462 
463 SYSCTL_DECL(_net_key);
464 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,
465 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_debug_level), 0, "");
466 
467 /* max count of trial for the decision of spi value */
468 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
469 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_trycnt), 0, "");
470 
471 /* minimum spi value to allocate automatically. */
472 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval,
473 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_minval), 0, "");
474 
475 /* maximun spi value to allocate automatically. */
476 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval,
477 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_maxval), 0, "");
478 
479 /* interval to initialize randseed */
480 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,
481 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_int_random), 0, "");
482 
483 /* lifetime for larval SA */
484 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime,
485 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_larval_lifetime), 0, "");
486 
487 /* counter for blocking to send SADB_ACQUIRE to IKEd */
488 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count,
489 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_count), 0, "");
490 
491 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
492 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime,
493 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
494 
495 /* ESP auth */
496 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth,
497 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth), 0, "");
498 
499 /* minimum ESP key length */
500 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin,
501 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin), 0, "");
502 
503 /* minimum AH key length */
504 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin,
505 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin), 0, "");
506 
507 /* perfered old SA rather than new SA */
508 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, preferred_oldsa,
509 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa), 0, "");
510 
511 static SYSCTL_NODE(_net_key, OID_AUTO, spdcache,
512     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
513     "SPD cache");
514 
515 SYSCTL_UINT(_net_key_spdcache, OID_AUTO, maxentries,
516 	CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(key_spdcache_maxentries), 0,
517 	"Maximum number of entries in the SPD cache"
518 	" (power of 2, 0 to disable)");
519 
520 SYSCTL_UINT(_net_key_spdcache, OID_AUTO, threshold,
521 	CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(key_spdcache_threshold), 0,
522 	"Number of SPs that make the SPD cache active");
523 
524 #define __LIST_CHAINED(elm) \
525 	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
526 
527 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
528 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
529 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
530 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
531 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
532 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
533 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
534 MALLOC_DEFINE(M_IPSEC_SPDCACHE, "ipsec-spdcache", "ipsec SPD cache");
535 
536 VNET_DEFINE_STATIC(uma_zone_t, key_lft_zone);
537 #define	V_key_lft_zone		VNET(key_lft_zone)
538 
539 /*
540  * set parameters into secpolicyindex buffer.
541  * Must allocate secpolicyindex buffer passed to this function.
542  */
543 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
544 do { \
545 	bzero((idx), sizeof(struct secpolicyindex));                         \
546 	(idx)->dir = (_dir);                                                 \
547 	(idx)->prefs = (ps);                                                 \
548 	(idx)->prefd = (pd);                                                 \
549 	(idx)->ul_proto = (ulp);                                             \
550 	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
551 	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
552 } while (0)
553 
554 /*
555  * set parameters into secasindex buffer.
556  * Must allocate secasindex buffer before calling this function.
557  */
558 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
559 do { \
560 	bzero((idx), sizeof(struct secasindex));                             \
561 	(idx)->proto = (p);                                                  \
562 	(idx)->mode = (m);                                                   \
563 	(idx)->reqid = (r);                                                  \
564 	bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
565 	bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
566 	key_porttosaddr(&(idx)->src.sa, 0);				     \
567 	key_porttosaddr(&(idx)->dst.sa, 0);				     \
568 } while (0)
569 
570 /* key statistics */
571 struct _keystat {
572 	u_long getspi_count; /* the avarage of count to try to get new SPI */
573 } keystat;
574 
575 struct sadb_msghdr {
576 	struct sadb_msg *msg;
577 	struct sadb_ext *ext[SADB_EXT_MAX + 1];
578 	int extoff[SADB_EXT_MAX + 1];
579 	int extlen[SADB_EXT_MAX + 1];
580 };
581 
582 static const struct supported_ealgs {
583 	int sadb_alg;
584 	const struct enc_xform *xform;
585 } supported_ealgs[] = {
586 	{ SADB_X_EALG_AES,		&enc_xform_rijndael128 },
587 	{ SADB_EALG_NULL,		&enc_xform_null },
588 	{ SADB_X_EALG_AESCTR,		&enc_xform_aes_icm },
589 	{ SADB_X_EALG_AESGCM16,		&enc_xform_aes_nist_gcm },
590 	{ SADB_X_EALG_AESGMAC,		&enc_xform_aes_nist_gmac },
591 };
592 
593 static const struct supported_aalgs {
594 	int sadb_alg;
595 	const struct auth_hash *xform;
596 } supported_aalgs[] = {
597 	{ SADB_X_AALG_NULL,		&auth_hash_null },
598 	{ SADB_AALG_SHA1HMAC,		&auth_hash_hmac_sha1 },
599 	{ SADB_X_AALG_SHA2_256,		&auth_hash_hmac_sha2_256 },
600 	{ SADB_X_AALG_SHA2_384,		&auth_hash_hmac_sha2_384 },
601 	{ SADB_X_AALG_SHA2_512,		&auth_hash_hmac_sha2_512 },
602 	{ SADB_X_AALG_AES128GMAC,	&auth_hash_nist_gmac_aes_128 },
603 	{ SADB_X_AALG_AES192GMAC,	&auth_hash_nist_gmac_aes_192 },
604 	{ SADB_X_AALG_AES256GMAC,	&auth_hash_nist_gmac_aes_256 },
605 };
606 
607 static const struct supported_calgs {
608 	int sadb_alg;
609 	const struct comp_algo *xform;
610 } supported_calgs[] = {
611 	{ SADB_X_CALG_DEFLATE,		&comp_algo_deflate },
612 };
613 
614 #ifndef IPSEC_DEBUG2
615 static struct callout key_timer;
616 #endif
617 
618 static void key_unlink(struct secpolicy *);
619 static struct secpolicy *key_do_allocsp(struct secpolicyindex *spidx, u_int dir);
620 static struct secpolicy *key_getsp(struct secpolicyindex *);
621 static struct secpolicy *key_getspbyid(u_int32_t);
622 static struct mbuf *key_gather_mbuf(struct mbuf *,
623 	const struct sadb_msghdr *, int, int, ...);
624 static int key_spdadd(struct socket *, struct mbuf *,
625 	const struct sadb_msghdr *);
626 static uint32_t key_getnewspid(void);
627 static int key_spddelete(struct socket *, struct mbuf *,
628 	const struct sadb_msghdr *);
629 static int key_spddelete2(struct socket *, struct mbuf *,
630 	const struct sadb_msghdr *);
631 static int key_spdget(struct socket *, struct mbuf *,
632 	const struct sadb_msghdr *);
633 static int key_spdflush(struct socket *, struct mbuf *,
634 	const struct sadb_msghdr *);
635 static int key_spddump(struct socket *, struct mbuf *,
636 	const struct sadb_msghdr *);
637 static struct mbuf *key_setdumpsp(struct secpolicy *,
638 	u_int8_t, u_int32_t, u_int32_t);
639 static struct mbuf *key_sp2mbuf(struct secpolicy *);
640 static size_t key_getspreqmsglen(struct secpolicy *);
641 static int key_spdexpire(struct secpolicy *);
642 static struct secashead *key_newsah(struct secasindex *);
643 static void key_freesah(struct secashead **);
644 static void key_delsah(struct secashead *);
645 static struct secasvar *key_newsav(const struct sadb_msghdr *,
646     struct secasindex *, uint32_t, int *);
647 static void key_delsav(struct secasvar *);
648 static void key_unlinksav(struct secasvar *);
649 static struct secashead *key_getsah(struct secasindex *);
650 static int key_checkspidup(uint32_t);
651 static struct secasvar *key_getsavbyspi(uint32_t);
652 static int key_setnatt(struct secasvar *, const struct sadb_msghdr *);
653 static int key_setsaval(struct secasvar *, const struct sadb_msghdr *);
654 static int key_updatelifetimes(struct secasvar *, const struct sadb_msghdr *);
655 static int key_updateaddresses(struct socket *, struct mbuf *,
656     const struct sadb_msghdr *, struct secasvar *, struct secasindex *);
657 
658 static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t,
659 	u_int8_t, u_int32_t, u_int32_t);
660 static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t,
661 	u_int32_t, pid_t, u_int16_t);
662 static struct mbuf *key_setsadbsa(struct secasvar *);
663 static struct mbuf *key_setsadbaddr(u_int16_t,
664 	const struct sockaddr *, u_int8_t, u_int16_t);
665 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
666 static struct mbuf *key_setsadbxtype(u_int16_t);
667 static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t);
668 static struct mbuf *key_setsadbxsareplay(u_int32_t);
669 static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t,
670 	u_int32_t, u_int32_t);
671 static struct seckey *key_dup_keymsg(const struct sadb_key *,
672     struct malloc_type *);
673 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
674     struct malloc_type *);
675 
676 /* flags for key_cmpsaidx() */
677 #define CMP_HEAD	1	/* protocol, addresses. */
678 #define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
679 #define CMP_REQID	3	/* additionally HEAD, reaid. */
680 #define CMP_EXACTLY	4	/* all elements. */
681 static int key_cmpsaidx(const struct secasindex *,
682     const struct secasindex *, int);
683 static int key_cmpspidx_exactly(struct secpolicyindex *,
684     struct secpolicyindex *);
685 static int key_cmpspidx_withmask(struct secpolicyindex *,
686     struct secpolicyindex *);
687 static int key_bbcmp(const void *, const void *, u_int);
688 static uint8_t key_satype2proto(uint8_t);
689 static uint8_t key_proto2satype(uint8_t);
690 
691 static int key_getspi(struct socket *, struct mbuf *,
692 	const struct sadb_msghdr *);
693 static uint32_t key_do_getnewspi(struct sadb_spirange *, struct secasindex *);
694 static int key_update(struct socket *, struct mbuf *,
695 	const struct sadb_msghdr *);
696 static int key_add(struct socket *, struct mbuf *,
697 	const struct sadb_msghdr *);
698 static int key_setident(struct secashead *, const struct sadb_msghdr *);
699 static struct mbuf *key_getmsgbuf_x1(struct mbuf *,
700 	const struct sadb_msghdr *);
701 static int key_delete(struct socket *, struct mbuf *,
702 	const struct sadb_msghdr *);
703 static int key_delete_all(struct socket *, struct mbuf *,
704 	const struct sadb_msghdr *, struct secasindex *);
705 static int key_get(struct socket *, struct mbuf *,
706 	const struct sadb_msghdr *);
707 
708 static void key_getcomb_setlifetime(struct sadb_comb *);
709 static struct mbuf *key_getcomb_ealg(void);
710 static struct mbuf *key_getcomb_ah(void);
711 static struct mbuf *key_getcomb_ipcomp(void);
712 static struct mbuf *key_getprop(const struct secasindex *);
713 
714 static int key_acquire(const struct secasindex *, struct secpolicy *);
715 static uint32_t key_newacq(const struct secasindex *, int *);
716 static uint32_t key_getacq(const struct secasindex *, int *);
717 static int key_acqdone(const struct secasindex *, uint32_t);
718 static int key_acqreset(uint32_t);
719 static struct secspacq *key_newspacq(struct secpolicyindex *);
720 static struct secspacq *key_getspacq(struct secpolicyindex *);
721 static int key_acquire2(struct socket *, struct mbuf *,
722 	const struct sadb_msghdr *);
723 static int key_register(struct socket *, struct mbuf *,
724 	const struct sadb_msghdr *);
725 static int key_expire(struct secasvar *, int);
726 static int key_flush(struct socket *, struct mbuf *,
727 	const struct sadb_msghdr *);
728 static int key_dump(struct socket *, struct mbuf *,
729 	const struct sadb_msghdr *);
730 static int key_promisc(struct socket *, struct mbuf *,
731 	const struct sadb_msghdr *);
732 static int key_senderror(struct socket *, struct mbuf *, int);
733 static int key_validate_ext(const struct sadb_ext *, int);
734 static int key_align(struct mbuf *, struct sadb_msghdr *);
735 static struct mbuf *key_setlifetime(struct seclifetime *, uint16_t);
736 static struct mbuf *key_setkey(struct seckey *, uint16_t);
737 
738 static void spdcache_init(void);
739 static void spdcache_clear(void);
740 static struct spdcache_entry *spdcache_entry_alloc(
741 	const struct secpolicyindex *spidx,
742 	struct secpolicy *policy);
743 static void spdcache_entry_free(struct spdcache_entry *entry);
744 #ifdef VIMAGE
745 static void spdcache_destroy(void);
746 #endif
747 
748 #define	DBG_IPSEC_INITREF(t, p)	do {				\
749 	refcount_init(&(p)->refcnt, 1);				\
750 	KEYDBG(KEY_STAMP,					\
751 	    printf("%s: Initialize refcnt %s(%p) = %u\n",	\
752 	    __func__, #t, (p), (p)->refcnt));			\
753 } while (0)
754 #define	DBG_IPSEC_ADDREF(t, p)	do {				\
755 	refcount_acquire(&(p)->refcnt);				\
756 	KEYDBG(KEY_STAMP,					\
757 	    printf("%s: Acquire refcnt %s(%p) -> %u\n",		\
758 	    __func__, #t, (p), (p)->refcnt));			\
759 } while (0)
760 #define	DBG_IPSEC_DELREF(t, p)	do {				\
761 	KEYDBG(KEY_STAMP,					\
762 	    printf("%s: Release refcnt %s(%p) -> %u\n",		\
763 	    __func__, #t, (p), (p)->refcnt - 1));		\
764 	refcount_release(&(p)->refcnt);				\
765 } while (0)
766 
767 #define	IPSEC_INITREF(t, p)	refcount_init(&(p)->refcnt, 1)
768 #define	IPSEC_ADDREF(t, p)	refcount_acquire(&(p)->refcnt)
769 #define	IPSEC_DELREF(t, p)	refcount_release(&(p)->refcnt)
770 
771 #define	SP_INITREF(p)	IPSEC_INITREF(SP, p)
772 #define	SP_ADDREF(p)	IPSEC_ADDREF(SP, p)
773 #define	SP_DELREF(p)	IPSEC_DELREF(SP, p)
774 
775 #define	SAH_INITREF(p)	IPSEC_INITREF(SAH, p)
776 #define	SAH_ADDREF(p)	IPSEC_ADDREF(SAH, p)
777 #define	SAH_DELREF(p)	IPSEC_DELREF(SAH, p)
778 
779 #define	SAV_INITREF(p)	IPSEC_INITREF(SAV, p)
780 #define	SAV_ADDREF(p)	IPSEC_ADDREF(SAV, p)
781 #define	SAV_DELREF(p)	IPSEC_DELREF(SAV, p)
782 
783 /*
784  * Update the refcnt while holding the SPTREE lock.
785  */
786 void
key_addref(struct secpolicy * sp)787 key_addref(struct secpolicy *sp)
788 {
789 
790 	SP_ADDREF(sp);
791 }
792 
793 /*
794  * Return 0 when there are known to be no SP's for the specified
795  * direction.  Otherwise return 1.  This is used by IPsec code
796  * to optimize performance.
797  */
798 int
key_havesp(u_int dir)799 key_havesp(u_int dir)
800 {
801 
802 	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
803 		TAILQ_FIRST(&V_sptree[dir]) != NULL : 1);
804 }
805 
806 /*
807  * Allocate a single mbuf with a buffer of the desired length.  The buffer is
808  * pre-zeroed to help ensure that uninitialized pad bytes are not leaked.
809  */
810 static struct mbuf *
key_mget(u_int len)811 key_mget(u_int len)
812 {
813 	struct mbuf *m;
814 
815 	KASSERT(len <= MCLBYTES,
816 	    ("%s: invalid buffer length %u", __func__, len));
817 
818 	m = m_get2(len, M_NOWAIT, MT_DATA, M_PKTHDR);
819 	if (m == NULL)
820 		return (NULL);
821 	memset(mtod(m, void *), 0, len);
822 	return (m);
823 }
824 
825 /* %%% IPsec policy management */
826 /*
827  * Return current SPDB generation.
828  */
829 uint32_t
key_getspgen(void)830 key_getspgen(void)
831 {
832 
833 	return (V_sp_genid);
834 }
835 
836 void
key_bumpspgen(void)837 key_bumpspgen(void)
838 {
839 
840 	V_sp_genid++;
841 }
842 
843 static int
key_checksockaddrs(struct sockaddr * src,struct sockaddr * dst)844 key_checksockaddrs(struct sockaddr *src, struct sockaddr *dst)
845 {
846 
847 	/* family match */
848 	if (src->sa_family != dst->sa_family)
849 		return (EINVAL);
850 	/* sa_len match */
851 	if (src->sa_len != dst->sa_len)
852 		return (EINVAL);
853 	switch (src->sa_family) {
854 #ifdef INET
855 	case AF_INET:
856 		if (src->sa_len != sizeof(struct sockaddr_in))
857 			return (EINVAL);
858 		break;
859 #endif
860 #ifdef INET6
861 	case AF_INET6:
862 		if (src->sa_len != sizeof(struct sockaddr_in6))
863 			return (EINVAL);
864 		break;
865 #endif
866 	default:
867 		return (EAFNOSUPPORT);
868 	}
869 	return (0);
870 }
871 
872 struct secpolicy *
key_do_allocsp(struct secpolicyindex * spidx,u_int dir)873 key_do_allocsp(struct secpolicyindex *spidx, u_int dir)
874 {
875 	SPTREE_RLOCK_TRACKER;
876 	struct secpolicy *sp;
877 
878 	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
879 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
880 		("invalid direction %u", dir));
881 
882 	SPTREE_RLOCK();
883 	TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
884 		if (key_cmpspidx_withmask(&sp->spidx, spidx)) {
885 			SP_ADDREF(sp);
886 			break;
887 		}
888 	}
889 	SPTREE_RUNLOCK();
890 	return (sp);
891 }
892 
893 /*
894  * allocating a SP for OUTBOUND or INBOUND packet.
895  * Must call key_freesp() later.
896  * OUT:	NULL:	not found
897  *	others:	found and return the pointer.
898  */
899 struct secpolicy *
key_allocsp(struct secpolicyindex * spidx,u_int dir)900 key_allocsp(struct secpolicyindex *spidx, u_int dir)
901 {
902 	struct spdcache_entry *entry, *lastentry, *tmpentry;
903 	struct secpolicy *sp;
904 	uint32_t hashv;
905 	int nb_entries;
906 
907 	if (!SPDCACHE_ACTIVE()) {
908 		sp = key_do_allocsp(spidx, dir);
909 		goto out;
910 	}
911 
912 	hashv = SPDCACHE_HASHVAL(spidx);
913 	SPDCACHE_LOCK(hashv);
914 	nb_entries = 0;
915 	LIST_FOREACH_SAFE(entry, &V_spdcachehashtbl[hashv], chain, tmpentry) {
916 		/* Removed outdated entries */
917 		if (entry->sp != NULL &&
918 		    entry->sp->state == IPSEC_SPSTATE_DEAD) {
919 			LIST_REMOVE(entry, chain);
920 			spdcache_entry_free(entry);
921 			continue;
922 		}
923 
924 		nb_entries++;
925 		if (!key_cmpspidx_exactly(&entry->spidx, spidx)) {
926 			lastentry = entry;
927 			continue;
928 		}
929 
930 		sp = entry->sp;
931 		if (entry->sp != NULL)
932 			SP_ADDREF(sp);
933 
934 		/* IPSECSTAT_INC(ips_spdcache_hits); */
935 
936 		SPDCACHE_UNLOCK(hashv);
937 		goto out;
938 	}
939 
940 	/* IPSECSTAT_INC(ips_spdcache_misses); */
941 
942 	sp = key_do_allocsp(spidx, dir);
943 	entry = spdcache_entry_alloc(spidx, sp);
944 	if (entry != NULL) {
945 		if (nb_entries >= SPDCACHE_MAX_ENTRIES_PER_HASH) {
946 			LIST_REMOVE(lastentry, chain);
947 			spdcache_entry_free(lastentry);
948 		}
949 
950 		LIST_INSERT_HEAD(&V_spdcachehashtbl[hashv], entry, chain);
951 	}
952 
953 	SPDCACHE_UNLOCK(hashv);
954 
955 out:
956 	if (sp != NULL) {	/* found a SPD entry */
957 		sp->lastused = time_second;
958 		KEYDBG(IPSEC_STAMP,
959 		    printf("%s: return SP(%p)\n", __func__, sp));
960 		KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
961 	} else {
962 		KEYDBG(IPSEC_DATA,
963 		    printf("%s: lookup failed for ", __func__);
964 		    kdebug_secpolicyindex(spidx, NULL));
965 	}
966 	return (sp);
967 }
968 
969 /*
970  * Allocating an SA entry for an *INBOUND* or *OUTBOUND* TCP packet, signed
971  * or should be signed by MD5 signature.
972  * We don't use key_allocsa() for such lookups, because we don't know SPI.
973  * Unlike ESP and AH protocols, SPI isn't transmitted in the TCP header with
974  * signed packet. We use SADB only as storage for password.
975  * OUT:	positive:	corresponding SA for given saidx found.
976  *	NULL:		SA not found
977  */
978 struct secasvar *
key_allocsa_tcpmd5(struct secasindex * saidx)979 key_allocsa_tcpmd5(struct secasindex *saidx)
980 {
981 	SAHTREE_RLOCK_TRACKER;
982 	struct secashead *sah;
983 	struct secasvar *sav;
984 
985 	IPSEC_ASSERT(saidx->proto == IPPROTO_TCP,
986 	    ("unexpected security protocol %u", saidx->proto));
987 	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TCPMD5,
988 	    ("unexpected mode %u", saidx->mode));
989 
990 	SAHTREE_RLOCK();
991 	LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
992 		KEYDBG(IPSEC_DUMP,
993 		    printf("%s: checking SAH\n", __func__);
994 		    kdebug_secash(sah, "  "));
995 		if (sah->saidx.proto != IPPROTO_TCP)
996 			continue;
997 		if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
998 		    !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
999 			break;
1000 	}
1001 	if (sah != NULL) {
1002 		if (V_key_preferred_oldsa)
1003 			sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1004 		else
1005 			sav = TAILQ_FIRST(&sah->savtree_alive);
1006 		if (sav != NULL)
1007 			SAV_ADDREF(sav);
1008 	} else
1009 		sav = NULL;
1010 	SAHTREE_RUNLOCK();
1011 
1012 	if (sav != NULL) {
1013 		KEYDBG(IPSEC_STAMP,
1014 		    printf("%s: return SA(%p)\n", __func__, sav));
1015 		KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1016 	} else {
1017 		KEYDBG(IPSEC_STAMP,
1018 		    printf("%s: SA not found\n", __func__));
1019 		KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1020 	}
1021 	return (sav);
1022 }
1023 
1024 /*
1025  * Allocating an SA entry for an *OUTBOUND* packet.
1026  * OUT:	positive:	corresponding SA for given saidx found.
1027  *	NULL:		SA not found, but will be acquired, check *error
1028  *			for acquiring status.
1029  */
1030 struct secasvar *
key_allocsa_policy(struct secpolicy * sp,const struct secasindex * saidx,int * error)1031 key_allocsa_policy(struct secpolicy *sp, const struct secasindex *saidx,
1032     int *error)
1033 {
1034 	SAHTREE_RLOCK_TRACKER;
1035 	struct secashead *sah;
1036 	struct secasvar *sav;
1037 
1038 	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
1039 	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
1040 		saidx->mode == IPSEC_MODE_TUNNEL,
1041 		("unexpected policy %u", saidx->mode));
1042 
1043 	/*
1044 	 * We check new SA in the IPsec request because a different
1045 	 * SA may be involved each time this request is checked, either
1046 	 * because new SAs are being configured, or this request is
1047 	 * associated with an unconnected datagram socket, or this request
1048 	 * is associated with a system default policy.
1049 	 */
1050 	SAHTREE_RLOCK();
1051 	LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
1052 		KEYDBG(IPSEC_DUMP,
1053 		    printf("%s: checking SAH\n", __func__);
1054 		    kdebug_secash(sah, "  "));
1055 		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
1056 			break;
1057 	}
1058 	if (sah != NULL) {
1059 		/*
1060 		 * Allocate the oldest SA available according to
1061 		 * draft-jenkins-ipsec-rekeying-03.
1062 		 */
1063 		if (V_key_preferred_oldsa)
1064 			sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1065 		else
1066 			sav = TAILQ_FIRST(&sah->savtree_alive);
1067 		if (sav != NULL)
1068 			SAV_ADDREF(sav);
1069 	} else
1070 		sav = NULL;
1071 	SAHTREE_RUNLOCK();
1072 
1073 	if (sav != NULL) {
1074 		*error = 0;
1075 		KEYDBG(IPSEC_STAMP,
1076 		    printf("%s: chosen SA(%p) for SP(%p)\n", __func__,
1077 			sav, sp));
1078 		KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1079 		return (sav); /* return referenced SA */
1080 	}
1081 
1082 	/* there is no SA */
1083 	*error = key_acquire(saidx, sp);
1084 	if ((*error) != 0)
1085 		ipseclog((LOG_DEBUG,
1086 		    "%s: error %d returned from key_acquire()\n",
1087 			__func__, *error));
1088 	KEYDBG(IPSEC_STAMP,
1089 	    printf("%s: acquire SA for SP(%p), error %d\n",
1090 		__func__, sp, *error));
1091 	KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1092 	return (NULL);
1093 }
1094 
1095 /*
1096  * allocating a usable SA entry for a *INBOUND* packet.
1097  * Must call key_freesav() later.
1098  * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
1099  *	NULL:		not found, or error occurred.
1100  *
1101  * According to RFC 2401 SA is uniquely identified by a triple SPI,
1102  * destination address, and security protocol. But according to RFC 4301,
1103  * SPI by itself suffices to specify an SA.
1104  *
1105  * Note that, however, we do need to keep source address in IPsec SA.
1106  * IKE specification and PF_KEY specification do assume that we
1107  * keep source address in IPsec SA.  We see a tricky situation here.
1108  */
1109 struct secasvar *
key_allocsa(union sockaddr_union * dst,uint8_t proto,uint32_t spi)1110 key_allocsa(union sockaddr_union *dst, uint8_t proto, uint32_t spi)
1111 {
1112 	SAHTREE_RLOCK_TRACKER;
1113 	struct secasvar *sav;
1114 
1115 	IPSEC_ASSERT(proto == IPPROTO_ESP || proto == IPPROTO_AH ||
1116 	    proto == IPPROTO_IPCOMP, ("unexpected security protocol %u",
1117 	    proto));
1118 
1119 	SAHTREE_RLOCK();
1120 	LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
1121 		if (sav->spi == spi)
1122 			break;
1123 	}
1124 	/*
1125 	 * We use single SPI namespace for all protocols, so it is
1126 	 * impossible to have SPI duplicates in the SAVHASH.
1127 	 */
1128 	if (sav != NULL) {
1129 		if (sav->state != SADB_SASTATE_LARVAL &&
1130 		    sav->sah->saidx.proto == proto &&
1131 		    key_sockaddrcmp(&dst->sa,
1132 			&sav->sah->saidx.dst.sa, 0) == 0)
1133 			SAV_ADDREF(sav);
1134 		else
1135 			sav = NULL;
1136 	}
1137 	SAHTREE_RUNLOCK();
1138 
1139 	if (sav == NULL) {
1140 		KEYDBG(IPSEC_STAMP,
1141 		    char buf[IPSEC_ADDRSTRLEN];
1142 		    printf("%s: SA not found for spi %u proto %u dst %s\n",
1143 			__func__, ntohl(spi), proto, ipsec_address(dst, buf,
1144 			sizeof(buf))));
1145 	} else {
1146 		KEYDBG(IPSEC_STAMP,
1147 		    printf("%s: return SA(%p)\n", __func__, sav));
1148 		KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1149 	}
1150 	return (sav);
1151 }
1152 
1153 struct secasvar *
key_allocsa_tunnel(union sockaddr_union * src,union sockaddr_union * dst,uint8_t proto)1154 key_allocsa_tunnel(union sockaddr_union *src, union sockaddr_union *dst,
1155     uint8_t proto)
1156 {
1157 	SAHTREE_RLOCK_TRACKER;
1158 	struct secasindex saidx;
1159 	struct secashead *sah;
1160 	struct secasvar *sav;
1161 
1162 	IPSEC_ASSERT(src != NULL, ("null src address"));
1163 	IPSEC_ASSERT(dst != NULL, ("null dst address"));
1164 
1165 	KEY_SETSECASIDX(proto, IPSEC_MODE_TUNNEL, 0, &src->sa,
1166 	    &dst->sa, &saidx);
1167 
1168 	sav = NULL;
1169 	SAHTREE_RLOCK();
1170 	LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
1171 		if (IPSEC_MODE_TUNNEL != sah->saidx.mode)
1172 			continue;
1173 		if (proto != sah->saidx.proto)
1174 			continue;
1175 		if (key_sockaddrcmp(&src->sa, &sah->saidx.src.sa, 0) != 0)
1176 			continue;
1177 		if (key_sockaddrcmp(&dst->sa, &sah->saidx.dst.sa, 0) != 0)
1178 			continue;
1179 		/* XXXAE: is key_preferred_oldsa reasonably?*/
1180 		if (V_key_preferred_oldsa)
1181 			sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1182 		else
1183 			sav = TAILQ_FIRST(&sah->savtree_alive);
1184 		if (sav != NULL) {
1185 			SAV_ADDREF(sav);
1186 			break;
1187 		}
1188 	}
1189 	SAHTREE_RUNLOCK();
1190 	KEYDBG(IPSEC_STAMP,
1191 	    printf("%s: return SA(%p)\n", __func__, sav));
1192 	if (sav != NULL)
1193 		KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1194 	return (sav);
1195 }
1196 
1197 /*
1198  * Must be called after calling key_allocsp().
1199  */
1200 void
key_freesp(struct secpolicy ** spp)1201 key_freesp(struct secpolicy **spp)
1202 {
1203 	struct secpolicy *sp = *spp;
1204 
1205 	IPSEC_ASSERT(sp != NULL, ("null sp"));
1206 	if (SP_DELREF(sp) == 0)
1207 		return;
1208 
1209 	KEYDBG(IPSEC_STAMP,
1210 	    printf("%s: last reference to SP(%p)\n", __func__, sp));
1211 	KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1212 
1213 	*spp = NULL;
1214 	while (sp->tcount > 0)
1215 		ipsec_delisr(sp->req[--sp->tcount]);
1216 	free(sp, M_IPSEC_SP);
1217 }
1218 
1219 static void
key_unlink(struct secpolicy * sp)1220 key_unlink(struct secpolicy *sp)
1221 {
1222 
1223 	IPSEC_ASSERT(sp->spidx.dir == IPSEC_DIR_INBOUND ||
1224 	    sp->spidx.dir == IPSEC_DIR_OUTBOUND,
1225 	    ("invalid direction %u", sp->spidx.dir));
1226 	SPTREE_UNLOCK_ASSERT();
1227 
1228 	KEYDBG(KEY_STAMP,
1229 	    printf("%s: SP(%p)\n", __func__, sp));
1230 	SPTREE_WLOCK();
1231 	if (sp->state != IPSEC_SPSTATE_ALIVE) {
1232 		/* SP is already unlinked */
1233 		SPTREE_WUNLOCK();
1234 		return;
1235 	}
1236 	sp->state = IPSEC_SPSTATE_DEAD;
1237 	TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
1238 	V_spd_size--;
1239 	LIST_REMOVE(sp, idhash);
1240 	V_sp_genid++;
1241 	SPTREE_WUNLOCK();
1242 	if (SPDCACHE_ENABLED())
1243 		spdcache_clear();
1244 	key_freesp(&sp);
1245 }
1246 
1247 /*
1248  * insert a secpolicy into the SP database. Lower priorities first
1249  */
1250 static void
key_insertsp(struct secpolicy * newsp)1251 key_insertsp(struct secpolicy *newsp)
1252 {
1253 	struct secpolicy *sp;
1254 
1255 	SPTREE_WLOCK_ASSERT();
1256 	TAILQ_FOREACH(sp, &V_sptree[newsp->spidx.dir], chain) {
1257 		if (newsp->priority < sp->priority) {
1258 			TAILQ_INSERT_BEFORE(sp, newsp, chain);
1259 			goto done;
1260 		}
1261 	}
1262 	TAILQ_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, chain);
1263 done:
1264 	LIST_INSERT_HEAD(SPHASH_HASH(newsp->id), newsp, idhash);
1265 	newsp->state = IPSEC_SPSTATE_ALIVE;
1266 	V_spd_size++;
1267 	V_sp_genid++;
1268 }
1269 
1270 /*
1271  * Insert a bunch of VTI secpolicies into the SPDB.
1272  * We keep VTI policies in the separate list due to following reasons:
1273  * 1) they should be immutable to user's or some deamon's attempts to
1274  *    delete. The only way delete such policies - destroy or unconfigure
1275  *    corresponding virtual inteface.
1276  * 2) such policies have traffic selector that matches all traffic per
1277  *    address family.
1278  * Since all VTI policies have the same priority, we don't care about
1279  * policies order.
1280  */
1281 int
key_register_ifnet(struct secpolicy ** spp,u_int count)1282 key_register_ifnet(struct secpolicy **spp, u_int count)
1283 {
1284 	struct mbuf *m;
1285 	u_int i;
1286 
1287 	SPTREE_WLOCK();
1288 	/*
1289 	 * First of try to acquire id for each SP.
1290 	 */
1291 	for (i = 0; i < count; i++) {
1292 		IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1293 		    spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1294 		    ("invalid direction %u", spp[i]->spidx.dir));
1295 
1296 		if ((spp[i]->id = key_getnewspid()) == 0) {
1297 			SPTREE_WUNLOCK();
1298 			return (EAGAIN);
1299 		}
1300 	}
1301 	for (i = 0; i < count; i++) {
1302 		TAILQ_INSERT_TAIL(&V_sptree_ifnet[spp[i]->spidx.dir],
1303 		    spp[i], chain);
1304 		/*
1305 		 * NOTE: despite the fact that we keep VTI SP in the
1306 		 * separate list, SPHASH contains policies from both
1307 		 * sources. Thus SADB_X_SPDGET will correctly return
1308 		 * SP by id, because it uses SPHASH for lookups.
1309 		 */
1310 		LIST_INSERT_HEAD(SPHASH_HASH(spp[i]->id), spp[i], idhash);
1311 		spp[i]->state = IPSEC_SPSTATE_IFNET;
1312 	}
1313 	SPTREE_WUNLOCK();
1314 	/*
1315 	 * Notify user processes about new SP.
1316 	 */
1317 	for (i = 0; i < count; i++) {
1318 		m = key_setdumpsp(spp[i], SADB_X_SPDADD, 0, 0);
1319 		if (m != NULL)
1320 			key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1321 	}
1322 	return (0);
1323 }
1324 
1325 void
key_unregister_ifnet(struct secpolicy ** spp,u_int count)1326 key_unregister_ifnet(struct secpolicy **spp, u_int count)
1327 {
1328 	struct mbuf *m;
1329 	u_int i;
1330 
1331 	SPTREE_WLOCK();
1332 	for (i = 0; i < count; i++) {
1333 		IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1334 		    spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1335 		    ("invalid direction %u", spp[i]->spidx.dir));
1336 
1337 		if (spp[i]->state != IPSEC_SPSTATE_IFNET)
1338 			continue;
1339 		spp[i]->state = IPSEC_SPSTATE_DEAD;
1340 		TAILQ_REMOVE(&V_sptree_ifnet[spp[i]->spidx.dir],
1341 		    spp[i], chain);
1342 		V_spd_size--;
1343 		LIST_REMOVE(spp[i], idhash);
1344 	}
1345 	SPTREE_WUNLOCK();
1346 	if (SPDCACHE_ENABLED())
1347 		spdcache_clear();
1348 
1349 	for (i = 0; i < count; i++) {
1350 		m = key_setdumpsp(spp[i], SADB_X_SPDDELETE, 0, 0);
1351 		if (m != NULL)
1352 			key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1353 	}
1354 }
1355 
1356 /*
1357  * Must be called after calling key_allocsa().
1358  * This function is called by key_freesp() to free some SA allocated
1359  * for a policy.
1360  */
1361 void
key_freesav(struct secasvar ** psav)1362 key_freesav(struct secasvar **psav)
1363 {
1364 	struct secasvar *sav = *psav;
1365 
1366 	IPSEC_ASSERT(sav != NULL, ("null sav"));
1367 	if (SAV_DELREF(sav) == 0)
1368 		return;
1369 
1370 	KEYDBG(IPSEC_STAMP,
1371 	    printf("%s: last reference to SA(%p)\n", __func__, sav));
1372 
1373 	*psav = NULL;
1374 	key_delsav(sav);
1375 }
1376 
1377 /*
1378  * Unlink SA from SAH and SPI hash under SAHTREE_WLOCK.
1379  * Expect that SA has extra reference due to lookup.
1380  * Release this references, also release SAH reference after unlink.
1381  */
1382 static void
key_unlinksav(struct secasvar * sav)1383 key_unlinksav(struct secasvar *sav)
1384 {
1385 	struct secashead *sah;
1386 
1387 	KEYDBG(KEY_STAMP,
1388 	    printf("%s: SA(%p)\n", __func__, sav));
1389 
1390 	SAHTREE_UNLOCK_ASSERT();
1391 	SAHTREE_WLOCK();
1392 	if (sav->state == SADB_SASTATE_DEAD) {
1393 		/* SA is already unlinked */
1394 		SAHTREE_WUNLOCK();
1395 		return;
1396 	}
1397 	/* Unlink from SAH */
1398 	if (sav->state == SADB_SASTATE_LARVAL)
1399 		TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
1400 	else
1401 		TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
1402 	/* Unlink from SPI hash */
1403 	LIST_REMOVE(sav, spihash);
1404 	sav->state = SADB_SASTATE_DEAD;
1405 	sah = sav->sah;
1406 	SAHTREE_WUNLOCK();
1407 	key_freesav(&sav);
1408 	/* Since we are unlinked, release reference to SAH */
1409 	key_freesah(&sah);
1410 }
1411 
1412 /* %%% SPD management */
1413 /*
1414  * search SPD
1415  * OUT:	NULL	: not found
1416  *	others	: found, pointer to a SP.
1417  */
1418 static struct secpolicy *
key_getsp(struct secpolicyindex * spidx)1419 key_getsp(struct secpolicyindex *spidx)
1420 {
1421 	SPTREE_RLOCK_TRACKER;
1422 	struct secpolicy *sp;
1423 
1424 	IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1425 
1426 	SPTREE_RLOCK();
1427 	TAILQ_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1428 		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1429 			SP_ADDREF(sp);
1430 			break;
1431 		}
1432 	}
1433 	SPTREE_RUNLOCK();
1434 
1435 	return sp;
1436 }
1437 
1438 /*
1439  * get SP by index.
1440  * OUT:	NULL	: not found
1441  *	others	: found, pointer to referenced SP.
1442  */
1443 static struct secpolicy *
key_getspbyid(uint32_t id)1444 key_getspbyid(uint32_t id)
1445 {
1446 	SPTREE_RLOCK_TRACKER;
1447 	struct secpolicy *sp;
1448 
1449 	SPTREE_RLOCK();
1450 	LIST_FOREACH(sp, SPHASH_HASH(id), idhash) {
1451 		if (sp->id == id) {
1452 			SP_ADDREF(sp);
1453 			break;
1454 		}
1455 	}
1456 	SPTREE_RUNLOCK();
1457 	return (sp);
1458 }
1459 
1460 struct secpolicy *
key_newsp(void)1461 key_newsp(void)
1462 {
1463 	struct secpolicy *sp;
1464 
1465 	sp = malloc(sizeof(*sp), M_IPSEC_SP, M_NOWAIT | M_ZERO);
1466 	if (sp != NULL)
1467 		SP_INITREF(sp);
1468 	return (sp);
1469 }
1470 
1471 struct ipsecrequest *
ipsec_newisr(void)1472 ipsec_newisr(void)
1473 {
1474 
1475 	return (malloc(sizeof(struct ipsecrequest), M_IPSEC_SR,
1476 	    M_NOWAIT | M_ZERO));
1477 }
1478 
1479 void
ipsec_delisr(struct ipsecrequest * p)1480 ipsec_delisr(struct ipsecrequest *p)
1481 {
1482 
1483 	free(p, M_IPSEC_SR);
1484 }
1485 
1486 /*
1487  * create secpolicy structure from sadb_x_policy structure.
1488  * NOTE: `state', `secpolicyindex' and 'id' in secpolicy structure
1489  * are not set, so must be set properly later.
1490  */
1491 struct secpolicy *
key_msg2sp(struct sadb_x_policy * xpl0,size_t len,int * error)1492 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1493 {
1494 	struct secpolicy *newsp;
1495 
1496 	IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1497 	IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1498 
1499 	if (len != PFKEY_EXTLEN(xpl0)) {
1500 		ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1501 		*error = EINVAL;
1502 		return NULL;
1503 	}
1504 
1505 	if ((newsp = key_newsp()) == NULL) {
1506 		*error = ENOBUFS;
1507 		return NULL;
1508 	}
1509 
1510 	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1511 	newsp->policy = xpl0->sadb_x_policy_type;
1512 	newsp->priority = xpl0->sadb_x_policy_priority;
1513 	newsp->tcount = 0;
1514 
1515 	/* check policy */
1516 	switch (xpl0->sadb_x_policy_type) {
1517 	case IPSEC_POLICY_DISCARD:
1518 	case IPSEC_POLICY_NONE:
1519 	case IPSEC_POLICY_ENTRUST:
1520 	case IPSEC_POLICY_BYPASS:
1521 		break;
1522 
1523 	case IPSEC_POLICY_IPSEC:
1524 	    {
1525 		struct sadb_x_ipsecrequest *xisr;
1526 		struct ipsecrequest *isr;
1527 		int tlen;
1528 
1529 		/* validity check */
1530 		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1531 			ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1532 				__func__));
1533 			key_freesp(&newsp);
1534 			*error = EINVAL;
1535 			return NULL;
1536 		}
1537 
1538 		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1539 		xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1540 
1541 		while (tlen > 0) {
1542 			/* length check */
1543 			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr) ||
1544 			    xisr->sadb_x_ipsecrequest_len > tlen) {
1545 				ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1546 					"length.\n", __func__));
1547 				key_freesp(&newsp);
1548 				*error = EINVAL;
1549 				return NULL;
1550 			}
1551 
1552 			if (newsp->tcount >= IPSEC_MAXREQ) {
1553 				ipseclog((LOG_DEBUG,
1554 				    "%s: too many ipsecrequests.\n",
1555 				    __func__));
1556 				key_freesp(&newsp);
1557 				*error = EINVAL;
1558 				return (NULL);
1559 			}
1560 
1561 			/* allocate request buffer */
1562 			/* NB: data structure is zero'd */
1563 			isr = ipsec_newisr();
1564 			if (isr == NULL) {
1565 				ipseclog((LOG_DEBUG,
1566 				    "%s: No more memory.\n", __func__));
1567 				key_freesp(&newsp);
1568 				*error = ENOBUFS;
1569 				return NULL;
1570 			}
1571 
1572 			newsp->req[newsp->tcount++] = isr;
1573 
1574 			/* set values */
1575 			switch (xisr->sadb_x_ipsecrequest_proto) {
1576 			case IPPROTO_ESP:
1577 			case IPPROTO_AH:
1578 			case IPPROTO_IPCOMP:
1579 				break;
1580 			default:
1581 				ipseclog((LOG_DEBUG,
1582 				    "%s: invalid proto type=%u\n", __func__,
1583 				    xisr->sadb_x_ipsecrequest_proto));
1584 				key_freesp(&newsp);
1585 				*error = EPROTONOSUPPORT;
1586 				return NULL;
1587 			}
1588 			isr->saidx.proto =
1589 			    (uint8_t)xisr->sadb_x_ipsecrequest_proto;
1590 
1591 			switch (xisr->sadb_x_ipsecrequest_mode) {
1592 			case IPSEC_MODE_TRANSPORT:
1593 			case IPSEC_MODE_TUNNEL:
1594 				break;
1595 			case IPSEC_MODE_ANY:
1596 			default:
1597 				ipseclog((LOG_DEBUG,
1598 				    "%s: invalid mode=%u\n", __func__,
1599 				    xisr->sadb_x_ipsecrequest_mode));
1600 				key_freesp(&newsp);
1601 				*error = EINVAL;
1602 				return NULL;
1603 			}
1604 			isr->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1605 
1606 			switch (xisr->sadb_x_ipsecrequest_level) {
1607 			case IPSEC_LEVEL_DEFAULT:
1608 			case IPSEC_LEVEL_USE:
1609 			case IPSEC_LEVEL_REQUIRE:
1610 				break;
1611 			case IPSEC_LEVEL_UNIQUE:
1612 				/* validity check */
1613 				/*
1614 				 * If range violation of reqid, kernel will
1615 				 * update it, don't refuse it.
1616 				 */
1617 				if (xisr->sadb_x_ipsecrequest_reqid
1618 						> IPSEC_MANUAL_REQID_MAX) {
1619 					ipseclog((LOG_DEBUG,
1620 					    "%s: reqid=%d range "
1621 					    "violation, updated by kernel.\n",
1622 					    __func__,
1623 					    xisr->sadb_x_ipsecrequest_reqid));
1624 					xisr->sadb_x_ipsecrequest_reqid = 0;
1625 				}
1626 
1627 				/* allocate new reqid id if reqid is zero. */
1628 				if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1629 					u_int32_t reqid;
1630 					if ((reqid = key_newreqid()) == 0) {
1631 						key_freesp(&newsp);
1632 						*error = ENOBUFS;
1633 						return NULL;
1634 					}
1635 					isr->saidx.reqid = reqid;
1636 					xisr->sadb_x_ipsecrequest_reqid = reqid;
1637 				} else {
1638 				/* set it for manual keying. */
1639 					isr->saidx.reqid =
1640 					    xisr->sadb_x_ipsecrequest_reqid;
1641 				}
1642 				break;
1643 
1644 			default:
1645 				ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1646 					__func__,
1647 					xisr->sadb_x_ipsecrequest_level));
1648 				key_freesp(&newsp);
1649 				*error = EINVAL;
1650 				return NULL;
1651 			}
1652 			isr->level = xisr->sadb_x_ipsecrequest_level;
1653 
1654 			/* set IP addresses if there */
1655 			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1656 				struct sockaddr *paddr;
1657 
1658 				len = tlen - sizeof(*xisr);
1659 				paddr = (struct sockaddr *)(xisr + 1);
1660 				/* validity check */
1661 				if (len < sizeof(struct sockaddr) ||
1662 				    len < 2 * paddr->sa_len ||
1663 				    paddr->sa_len > sizeof(isr->saidx.src)) {
1664 					ipseclog((LOG_DEBUG, "%s: invalid "
1665 						"request address length.\n",
1666 						__func__));
1667 					key_freesp(&newsp);
1668 					*error = EINVAL;
1669 					return NULL;
1670 				}
1671 				/*
1672 				 * Request length should be enough to keep
1673 				 * source and destination addresses.
1674 				 */
1675 				if (xisr->sadb_x_ipsecrequest_len <
1676 				    sizeof(*xisr) + 2 * paddr->sa_len) {
1677 					ipseclog((LOG_DEBUG, "%s: invalid "
1678 					    "ipsecrequest length.\n",
1679 					    __func__));
1680 					key_freesp(&newsp);
1681 					*error = EINVAL;
1682 					return (NULL);
1683 				}
1684 				bcopy(paddr, &isr->saidx.src, paddr->sa_len);
1685 				paddr = (struct sockaddr *)((caddr_t)paddr +
1686 				    paddr->sa_len);
1687 
1688 				/* validity check */
1689 				if (paddr->sa_len !=
1690 				    isr->saidx.src.sa.sa_len) {
1691 					ipseclog((LOG_DEBUG, "%s: invalid "
1692 						"request address length.\n",
1693 						__func__));
1694 					key_freesp(&newsp);
1695 					*error = EINVAL;
1696 					return NULL;
1697 				}
1698 				/* AF family should match */
1699 				if (paddr->sa_family !=
1700 				    isr->saidx.src.sa.sa_family) {
1701 					ipseclog((LOG_DEBUG, "%s: address "
1702 					    "family doesn't match.\n",
1703 						__func__));
1704 					key_freesp(&newsp);
1705 					*error = EINVAL;
1706 					return (NULL);
1707 				}
1708 				bcopy(paddr, &isr->saidx.dst, paddr->sa_len);
1709 			} else {
1710 				/*
1711 				 * Addresses for TUNNEL mode requests are
1712 				 * mandatory.
1713 				 */
1714 				if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1715 					ipseclog((LOG_DEBUG, "%s: missing "
1716 					    "request addresses.\n", __func__));
1717 					key_freesp(&newsp);
1718 					*error = EINVAL;
1719 					return (NULL);
1720 				}
1721 			}
1722 			tlen -= xisr->sadb_x_ipsecrequest_len;
1723 
1724 			/* validity check */
1725 			if (tlen < 0) {
1726 				ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1727 					__func__));
1728 				key_freesp(&newsp);
1729 				*error = EINVAL;
1730 				return NULL;
1731 			}
1732 
1733 			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1734 			                 + xisr->sadb_x_ipsecrequest_len);
1735 		}
1736 		/* XXXAE: LARVAL SP */
1737 		if (newsp->tcount < 1) {
1738 			ipseclog((LOG_DEBUG, "%s: valid IPSEC transforms "
1739 			    "not found.\n", __func__));
1740 			key_freesp(&newsp);
1741 			*error = EINVAL;
1742 			return (NULL);
1743 		}
1744 	    }
1745 		break;
1746 	default:
1747 		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1748 		key_freesp(&newsp);
1749 		*error = EINVAL;
1750 		return NULL;
1751 	}
1752 
1753 	*error = 0;
1754 	return (newsp);
1755 }
1756 
1757 uint32_t
key_newreqid(void)1758 key_newreqid(void)
1759 {
1760 	static uint32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1761 
1762 	if (auto_reqid == ~0)
1763 		auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1764 	else
1765 		auto_reqid++;
1766 
1767 	/* XXX should be unique check */
1768 	return (auto_reqid);
1769 }
1770 
1771 /*
1772  * copy secpolicy struct to sadb_x_policy structure indicated.
1773  */
1774 static struct mbuf *
key_sp2mbuf(struct secpolicy * sp)1775 key_sp2mbuf(struct secpolicy *sp)
1776 {
1777 	struct mbuf *m;
1778 	size_t tlen;
1779 
1780 	tlen = key_getspreqmsglen(sp);
1781 	m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1782 	if (m == NULL)
1783 		return (NULL);
1784 	m_align(m, tlen);
1785 	m->m_len = tlen;
1786 	if (key_sp2msg(sp, m->m_data, &tlen) != 0) {
1787 		m_freem(m);
1788 		return (NULL);
1789 	}
1790 	return (m);
1791 }
1792 
1793 int
key_sp2msg(struct secpolicy * sp,void * request,size_t * len)1794 key_sp2msg(struct secpolicy *sp, void *request, size_t *len)
1795 {
1796 	struct sadb_x_ipsecrequest *xisr;
1797 	struct sadb_x_policy *xpl;
1798 	struct ipsecrequest *isr;
1799 	size_t xlen, ilen;
1800 	caddr_t p;
1801 	int error, i;
1802 
1803 	IPSEC_ASSERT(sp != NULL, ("null policy"));
1804 
1805 	xlen = sizeof(*xpl);
1806 	if (*len < xlen)
1807 		return (EINVAL);
1808 
1809 	error = 0;
1810 	bzero(request, *len);
1811 	xpl = (struct sadb_x_policy *)request;
1812 	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1813 	xpl->sadb_x_policy_type = sp->policy;
1814 	xpl->sadb_x_policy_dir = sp->spidx.dir;
1815 	xpl->sadb_x_policy_id = sp->id;
1816 	xpl->sadb_x_policy_priority = sp->priority;
1817 	switch (sp->state) {
1818 	case IPSEC_SPSTATE_IFNET:
1819 		xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_IFNET;
1820 		break;
1821 	case IPSEC_SPSTATE_PCB:
1822 		xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_PCB;
1823 		break;
1824 	default:
1825 		xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_GLOBAL;
1826 	}
1827 
1828 	/* if is the policy for ipsec ? */
1829 	if (sp->policy == IPSEC_POLICY_IPSEC) {
1830 		p = (caddr_t)xpl + sizeof(*xpl);
1831 		for (i = 0; i < sp->tcount; i++) {
1832 			isr = sp->req[i];
1833 			ilen = PFKEY_ALIGN8(sizeof(*xisr) +
1834 			    isr->saidx.src.sa.sa_len +
1835 			    isr->saidx.dst.sa.sa_len);
1836 			xlen += ilen;
1837 			if (xlen > *len) {
1838 				error = ENOBUFS;
1839 				/* Calculate needed size */
1840 				continue;
1841 			}
1842 			xisr = (struct sadb_x_ipsecrequest *)p;
1843 			xisr->sadb_x_ipsecrequest_len = ilen;
1844 			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1845 			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1846 			xisr->sadb_x_ipsecrequest_level = isr->level;
1847 			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1848 
1849 			p += sizeof(*xisr);
1850 			bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1851 			p += isr->saidx.src.sa.sa_len;
1852 			bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1853 			p += isr->saidx.dst.sa.sa_len;
1854 		}
1855 	}
1856 	xpl->sadb_x_policy_len = PFKEY_UNIT64(xlen);
1857 	if (error == 0)
1858 		*len = xlen;
1859 	else
1860 		*len = sizeof(*xpl);
1861 	return (error);
1862 }
1863 
1864 /* m will not be freed nor modified */
1865 static struct mbuf *
key_gather_mbuf(struct mbuf * m,const struct sadb_msghdr * mhp,int ndeep,int nitem,...)1866 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1867     int ndeep, int nitem, ...)
1868 {
1869 	va_list ap;
1870 	int idx;
1871 	int i;
1872 	struct mbuf *result = NULL, *n;
1873 	int len;
1874 
1875 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1876 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1877 
1878 	va_start(ap, nitem);
1879 	for (i = 0; i < nitem; i++) {
1880 		idx = va_arg(ap, int);
1881 		if (idx < 0 || idx > SADB_EXT_MAX)
1882 			goto fail;
1883 		/* don't attempt to pull empty extension */
1884 		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1885 			continue;
1886 		if (idx != SADB_EXT_RESERVED  &&
1887 		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1888 			continue;
1889 
1890 		if (idx == SADB_EXT_RESERVED) {
1891 			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1892 
1893 			IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1894 
1895 			MGETHDR(n, M_NOWAIT, MT_DATA);
1896 			if (!n)
1897 				goto fail;
1898 			n->m_len = len;
1899 			n->m_next = NULL;
1900 			m_copydata(m, 0, sizeof(struct sadb_msg),
1901 			    mtod(n, caddr_t));
1902 		} else if (i < ndeep) {
1903 			len = mhp->extlen[idx];
1904 			n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1905 			if (n == NULL)
1906 				goto fail;
1907 			m_align(n, len);
1908 			n->m_len = len;
1909 			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1910 			    mtod(n, caddr_t));
1911 		} else {
1912 			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1913 			    M_NOWAIT);
1914 		}
1915 		if (n == NULL)
1916 			goto fail;
1917 
1918 		if (result)
1919 			m_cat(result, n);
1920 		else
1921 			result = n;
1922 	}
1923 	va_end(ap);
1924 
1925 	if ((result->m_flags & M_PKTHDR) != 0) {
1926 		result->m_pkthdr.len = 0;
1927 		for (n = result; n; n = n->m_next)
1928 			result->m_pkthdr.len += n->m_len;
1929 	}
1930 
1931 	return result;
1932 
1933 fail:
1934 	m_freem(result);
1935 	va_end(ap);
1936 	return NULL;
1937 }
1938 
1939 /*
1940  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1941  * add an entry to SP database, when received
1942  *   <base, address(SD), (lifetime(H),) policy>
1943  * from the user(?).
1944  * Adding to SP database,
1945  * and send
1946  *   <base, address(SD), (lifetime(H),) policy>
1947  * to the socket which was send.
1948  *
1949  * SPDADD set a unique policy entry.
1950  * SPDSETIDX like SPDADD without a part of policy requests.
1951  * SPDUPDATE replace a unique policy entry.
1952  *
1953  * XXXAE: serialize this in PF_KEY to avoid races.
1954  * m will always be freed.
1955  */
1956 static int
key_spdadd(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)1957 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1958 {
1959 	struct secpolicyindex spidx;
1960 	struct sadb_address *src0, *dst0;
1961 	struct sadb_x_policy *xpl0, *xpl;
1962 	struct sadb_lifetime *lft = NULL;
1963 	struct secpolicy *newsp;
1964 	int error;
1965 
1966 	IPSEC_ASSERT(so != NULL, ("null socket"));
1967 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1968 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1969 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1970 
1971 	if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
1972 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
1973 	    SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
1974 		ipseclog((LOG_DEBUG,
1975 		    "%s: invalid message: missing required header.\n",
1976 		    __func__));
1977 		return key_senderror(so, m, EINVAL);
1978 	}
1979 	if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
1980 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
1981 	    SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
1982 		ipseclog((LOG_DEBUG,
1983 		    "%s: invalid message: wrong header size.\n", __func__));
1984 		return key_senderror(so, m, EINVAL);
1985 	}
1986 	if (!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD)) {
1987 		if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD)) {
1988 			ipseclog((LOG_DEBUG,
1989 			    "%s: invalid message: wrong header size.\n",
1990 			    __func__));
1991 			return key_senderror(so, m, EINVAL);
1992 		}
1993 		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1994 	}
1995 
1996 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1997 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1998 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1999 
2000 	/* check the direciton */
2001 	switch (xpl0->sadb_x_policy_dir) {
2002 	case IPSEC_DIR_INBOUND:
2003 	case IPSEC_DIR_OUTBOUND:
2004 		break;
2005 	default:
2006 		ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
2007 		return key_senderror(so, m, EINVAL);
2008 	}
2009 	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
2010 	if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2011 	    xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2012 	    xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2013 		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2014 		return key_senderror(so, m, EINVAL);
2015 	}
2016 
2017 	/* policy requests are mandatory when action is ipsec. */
2018 	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2019 	    mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
2020 		ipseclog((LOG_DEBUG,
2021 		    "%s: policy requests required.\n", __func__));
2022 		return key_senderror(so, m, EINVAL);
2023 	}
2024 
2025 	error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
2026 	    (struct sockaddr *)(dst0 + 1));
2027 	if (error != 0 ||
2028 	    src0->sadb_address_proto != dst0->sadb_address_proto) {
2029 		ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2030 		return key_senderror(so, m, error);
2031 	}
2032 	/* make secindex */
2033 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2034 	                src0 + 1,
2035 	                dst0 + 1,
2036 	                src0->sadb_address_prefixlen,
2037 	                dst0->sadb_address_prefixlen,
2038 	                src0->sadb_address_proto,
2039 	                &spidx);
2040 	/* Checking there is SP already or not. */
2041 	newsp = key_getsp(&spidx);
2042 	if (newsp != NULL) {
2043 		if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
2044 			KEYDBG(KEY_STAMP,
2045 			    printf("%s: unlink SP(%p) for SPDUPDATE\n",
2046 				__func__, newsp));
2047 			KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2048 			key_unlink(newsp);
2049 			key_freesp(&newsp);
2050 		} else {
2051 			key_freesp(&newsp);
2052 			ipseclog((LOG_DEBUG,
2053 			    "%s: a SP entry exists already.\n", __func__));
2054 			return (key_senderror(so, m, EEXIST));
2055 		}
2056 	}
2057 
2058 	/* allocate new SP entry */
2059 	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
2060 		return key_senderror(so, m, error);
2061 	}
2062 
2063 	newsp->lastused = newsp->created = time_second;
2064 	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
2065 	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
2066 	bcopy(&spidx, &newsp->spidx, sizeof(spidx));
2067 
2068 	/* XXXAE: there is race between key_getsp() and key_insertsp() */
2069 	SPTREE_WLOCK();
2070 	if ((newsp->id = key_getnewspid()) == 0) {
2071 		SPTREE_WUNLOCK();
2072 		key_freesp(&newsp);
2073 		return key_senderror(so, m, ENOBUFS);
2074 	}
2075 	key_insertsp(newsp);
2076 	SPTREE_WUNLOCK();
2077 	if (SPDCACHE_ENABLED())
2078 		spdcache_clear();
2079 
2080 	KEYDBG(KEY_STAMP,
2081 	    printf("%s: SP(%p)\n", __func__, newsp));
2082 	KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2083 
2084     {
2085 	struct mbuf *n, *mpolicy;
2086 	struct sadb_msg *newmsg;
2087 	int off;
2088 
2089 	/* create new sadb_msg to reply. */
2090 	if (lft) {
2091 		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
2092 		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
2093 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2094 	} else {
2095 		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
2096 		    SADB_X_EXT_POLICY,
2097 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2098 	}
2099 	if (!n)
2100 		return key_senderror(so, m, ENOBUFS);
2101 
2102 	if (n->m_len < sizeof(*newmsg)) {
2103 		n = m_pullup(n, sizeof(*newmsg));
2104 		if (!n)
2105 			return key_senderror(so, m, ENOBUFS);
2106 	}
2107 	newmsg = mtod(n, struct sadb_msg *);
2108 	newmsg->sadb_msg_errno = 0;
2109 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2110 
2111 	off = 0;
2112 	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2113 	    sizeof(*xpl), &off);
2114 	if (mpolicy == NULL) {
2115 		/* n is already freed */
2116 		return key_senderror(so, m, ENOBUFS);
2117 	}
2118 	xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
2119 	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2120 		m_freem(n);
2121 		return key_senderror(so, m, EINVAL);
2122 	}
2123 	xpl->sadb_x_policy_id = newsp->id;
2124 
2125 	m_freem(m);
2126 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2127     }
2128 }
2129 
2130 /*
2131  * get new policy id.
2132  * OUT:
2133  *	0:	failure.
2134  *	others: success.
2135  */
2136 static uint32_t
key_getnewspid(void)2137 key_getnewspid(void)
2138 {
2139 	struct secpolicy *sp;
2140 	uint32_t newid = 0;
2141 	int count = V_key_spi_trycnt;	/* XXX */
2142 
2143 	SPTREE_WLOCK_ASSERT();
2144 	while (count--) {
2145 		if (V_policy_id == ~0) /* overflowed */
2146 			newid = V_policy_id = 1;
2147 		else
2148 			newid = ++V_policy_id;
2149 		LIST_FOREACH(sp, SPHASH_HASH(newid), idhash) {
2150 			if (sp->id == newid)
2151 				break;
2152 		}
2153 		if (sp == NULL)
2154 			break;
2155 	}
2156 	if (count == 0 || newid == 0) {
2157 		ipseclog((LOG_DEBUG, "%s: failed to allocate policy id.\n",
2158 		    __func__));
2159 		return (0);
2160 	}
2161 	return (newid);
2162 }
2163 
2164 /*
2165  * SADB_SPDDELETE processing
2166  * receive
2167  *   <base, address(SD), policy(*)>
2168  * from the user(?), and set SADB_SASTATE_DEAD,
2169  * and send,
2170  *   <base, address(SD), policy(*)>
2171  * to the ikmpd.
2172  * policy(*) including direction of policy.
2173  *
2174  * m will always be freed.
2175  */
2176 static int
key_spddelete(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)2177 key_spddelete(struct socket *so, struct mbuf *m,
2178     const struct sadb_msghdr *mhp)
2179 {
2180 	struct secpolicyindex spidx;
2181 	struct sadb_address *src0, *dst0;
2182 	struct sadb_x_policy *xpl0;
2183 	struct secpolicy *sp;
2184 
2185 	IPSEC_ASSERT(so != NULL, ("null so"));
2186 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2187 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2188 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2189 
2190 	if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
2191 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
2192 	    SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
2193 		ipseclog((LOG_DEBUG,
2194 		    "%s: invalid message: missing required header.\n",
2195 		    __func__));
2196 		return key_senderror(so, m, EINVAL);
2197 	}
2198 	if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
2199 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
2200 	    SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2201 		ipseclog((LOG_DEBUG,
2202 		    "%s: invalid message: wrong header size.\n", __func__));
2203 		return key_senderror(so, m, EINVAL);
2204 	}
2205 
2206 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2207 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2208 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2209 
2210 	/* check the direciton */
2211 	switch (xpl0->sadb_x_policy_dir) {
2212 	case IPSEC_DIR_INBOUND:
2213 	case IPSEC_DIR_OUTBOUND:
2214 		break;
2215 	default:
2216 		ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
2217 		return key_senderror(so, m, EINVAL);
2218 	}
2219 	/* Only DISCARD, NONE and IPSEC are allowed */
2220 	if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2221 	    xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2222 	    xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2223 		ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2224 		return key_senderror(so, m, EINVAL);
2225 	}
2226 	if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
2227 	    (struct sockaddr *)(dst0 + 1)) != 0 ||
2228 	    src0->sadb_address_proto != dst0->sadb_address_proto) {
2229 		ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2230 		return key_senderror(so, m, EINVAL);
2231 	}
2232 	/* make secindex */
2233 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2234 	                src0 + 1,
2235 	                dst0 + 1,
2236 	                src0->sadb_address_prefixlen,
2237 	                dst0->sadb_address_prefixlen,
2238 	                src0->sadb_address_proto,
2239 	                &spidx);
2240 
2241 	/* Is there SP in SPD ? */
2242 	if ((sp = key_getsp(&spidx)) == NULL) {
2243 		ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2244 		return key_senderror(so, m, EINVAL);
2245 	}
2246 
2247 	/* save policy id to buffer to be returned. */
2248 	xpl0->sadb_x_policy_id = sp->id;
2249 
2250 	KEYDBG(KEY_STAMP,
2251 	    printf("%s: SP(%p)\n", __func__, sp));
2252 	KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2253 	key_unlink(sp);
2254 	key_freesp(&sp);
2255 
2256     {
2257 	struct mbuf *n;
2258 	struct sadb_msg *newmsg;
2259 
2260 	/* create new sadb_msg to reply. */
2261 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2262 	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2263 	if (!n)
2264 		return key_senderror(so, m, ENOBUFS);
2265 
2266 	newmsg = mtod(n, struct sadb_msg *);
2267 	newmsg->sadb_msg_errno = 0;
2268 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2269 
2270 	m_freem(m);
2271 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2272     }
2273 }
2274 
2275 /*
2276  * SADB_SPDDELETE2 processing
2277  * receive
2278  *   <base, policy(*)>
2279  * from the user(?), and set SADB_SASTATE_DEAD,
2280  * and send,
2281  *   <base, policy(*)>
2282  * to the ikmpd.
2283  * policy(*) including direction of policy.
2284  *
2285  * m will always be freed.
2286  */
2287 static int
key_spddelete2(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)2288 key_spddelete2(struct socket *so, struct mbuf *m,
2289     const struct sadb_msghdr *mhp)
2290 {
2291 	struct secpolicy *sp;
2292 	uint32_t id;
2293 
2294 	IPSEC_ASSERT(so != NULL, ("null socket"));
2295 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2296 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2297 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2298 
2299 	if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2300 	    SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2301 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2302 		    __func__));
2303 		return key_senderror(so, m, EINVAL);
2304 	}
2305 
2306 	id = ((struct sadb_x_policy *)
2307 	    mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2308 
2309 	/* Is there SP in SPD ? */
2310 	if ((sp = key_getspbyid(id)) == NULL) {
2311 		ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2312 		    __func__, id));
2313 		return key_senderror(so, m, EINVAL);
2314 	}
2315 
2316 	KEYDBG(KEY_STAMP,
2317 	    printf("%s: SP(%p)\n", __func__, sp));
2318 	KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2319 	key_unlink(sp);
2320 	if (sp->state != IPSEC_SPSTATE_DEAD) {
2321 		ipseclog((LOG_DEBUG, "%s: failed to delete SP with id %u.\n",
2322 		    __func__, id));
2323 		key_freesp(&sp);
2324 		return (key_senderror(so, m, EACCES));
2325 	}
2326 	key_freesp(&sp);
2327 
2328     {
2329 	struct mbuf *n, *nn;
2330 	struct sadb_msg *newmsg;
2331 	int off, len;
2332 
2333 	/* create new sadb_msg to reply. */
2334 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2335 
2336 	n = key_mget(len);
2337 	if (n == NULL)
2338 		return key_senderror(so, m, ENOBUFS);
2339 
2340 	n->m_len = len;
2341 	n->m_next = NULL;
2342 	off = 0;
2343 
2344 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2345 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2346 
2347 	IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2348 		off, len));
2349 
2350 	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2351 	    mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2352 	if (!n->m_next) {
2353 		m_freem(n);
2354 		return key_senderror(so, m, ENOBUFS);
2355 	}
2356 
2357 	n->m_pkthdr.len = 0;
2358 	for (nn = n; nn; nn = nn->m_next)
2359 		n->m_pkthdr.len += nn->m_len;
2360 
2361 	newmsg = mtod(n, struct sadb_msg *);
2362 	newmsg->sadb_msg_errno = 0;
2363 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2364 
2365 	m_freem(m);
2366 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2367     }
2368 }
2369 
2370 /*
2371  * SADB_X_SPDGET processing
2372  * receive
2373  *   <base, policy(*)>
2374  * from the user(?),
2375  * and send,
2376  *   <base, address(SD), policy>
2377  * to the ikmpd.
2378  * policy(*) including direction of policy.
2379  *
2380  * m will always be freed.
2381  */
2382 static int
key_spdget(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)2383 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2384 {
2385 	struct secpolicy *sp;
2386 	struct mbuf *n;
2387 	uint32_t id;
2388 
2389 	IPSEC_ASSERT(so != NULL, ("null socket"));
2390 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2391 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2392 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2393 
2394 	if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2395 	    SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2396 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2397 		    __func__));
2398 		return key_senderror(so, m, EINVAL);
2399 	}
2400 
2401 	id = ((struct sadb_x_policy *)
2402 	    mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2403 
2404 	/* Is there SP in SPD ? */
2405 	if ((sp = key_getspbyid(id)) == NULL) {
2406 		ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2407 		    __func__, id));
2408 		return key_senderror(so, m, ENOENT);
2409 	}
2410 
2411 	n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
2412 	    mhp->msg->sadb_msg_pid);
2413 	key_freesp(&sp);
2414 	if (n != NULL) {
2415 		m_freem(m);
2416 		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2417 	} else
2418 		return key_senderror(so, m, ENOBUFS);
2419 }
2420 
2421 /*
2422  * SADB_X_SPDACQUIRE processing.
2423  * Acquire policy and SA(s) for a *OUTBOUND* packet.
2424  * send
2425  *   <base, policy(*)>
2426  * to KMD, and expect to receive
2427  *   <base> with SADB_X_SPDACQUIRE if error occurred,
2428  * or
2429  *   <base, policy>
2430  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2431  * policy(*) is without policy requests.
2432  *
2433  *    0     : succeed
2434  *    others: error number
2435  */
2436 int
key_spdacquire(struct secpolicy * sp)2437 key_spdacquire(struct secpolicy *sp)
2438 {
2439 	struct mbuf *result = NULL, *m;
2440 	struct secspacq *newspacq;
2441 
2442 	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2443 	IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2444 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2445 		("policy not IPSEC %u", sp->policy));
2446 
2447 	/* Get an entry to check whether sent message or not. */
2448 	newspacq = key_getspacq(&sp->spidx);
2449 	if (newspacq != NULL) {
2450 		if (V_key_blockacq_count < newspacq->count) {
2451 			/* reset counter and do send message. */
2452 			newspacq->count = 0;
2453 		} else {
2454 			/* increment counter and do nothing. */
2455 			newspacq->count++;
2456 			SPACQ_UNLOCK();
2457 			return (0);
2458 		}
2459 		SPACQ_UNLOCK();
2460 	} else {
2461 		/* make new entry for blocking to send SADB_ACQUIRE. */
2462 		newspacq = key_newspacq(&sp->spidx);
2463 		if (newspacq == NULL)
2464 			return ENOBUFS;
2465 	}
2466 
2467 	/* create new sadb_msg to reply. */
2468 	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2469 	if (!m)
2470 		return ENOBUFS;
2471 
2472 	result = m;
2473 
2474 	result->m_pkthdr.len = 0;
2475 	for (m = result; m; m = m->m_next)
2476 		result->m_pkthdr.len += m->m_len;
2477 
2478 	mtod(result, struct sadb_msg *)->sadb_msg_len =
2479 	    PFKEY_UNIT64(result->m_pkthdr.len);
2480 
2481 	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2482 }
2483 
2484 /*
2485  * SADB_SPDFLUSH processing
2486  * receive
2487  *   <base>
2488  * from the user, and free all entries in secpctree.
2489  * and send,
2490  *   <base>
2491  * to the user.
2492  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2493  *
2494  * m will always be freed.
2495  */
2496 static int
key_spdflush(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)2497 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2498 {
2499 	struct secpolicy_queue drainq;
2500 	struct sadb_msg *newmsg;
2501 	struct secpolicy *sp, *nextsp;
2502 	u_int dir;
2503 
2504 	IPSEC_ASSERT(so != NULL, ("null socket"));
2505 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2506 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2507 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2508 
2509 	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2510 		return key_senderror(so, m, EINVAL);
2511 
2512 	TAILQ_INIT(&drainq);
2513 	SPTREE_WLOCK();
2514 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2515 		TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2516 	}
2517 	/*
2518 	 * We need to set state to DEAD for each policy to be sure,
2519 	 * that another thread won't try to unlink it.
2520 	 * Also remove SP from sphash.
2521 	 */
2522 	TAILQ_FOREACH(sp, &drainq, chain) {
2523 		sp->state = IPSEC_SPSTATE_DEAD;
2524 		LIST_REMOVE(sp, idhash);
2525 	}
2526 	V_sp_genid++;
2527 	V_spd_size = 0;
2528 	SPTREE_WUNLOCK();
2529 	if (SPDCACHE_ENABLED())
2530 		spdcache_clear();
2531 	sp = TAILQ_FIRST(&drainq);
2532 	while (sp != NULL) {
2533 		nextsp = TAILQ_NEXT(sp, chain);
2534 		key_freesp(&sp);
2535 		sp = nextsp;
2536 	}
2537 
2538 	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2539 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2540 		return key_senderror(so, m, ENOBUFS);
2541 	}
2542 
2543 	if (m->m_next)
2544 		m_freem(m->m_next);
2545 	m->m_next = NULL;
2546 	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2547 	newmsg = mtod(m, struct sadb_msg *);
2548 	newmsg->sadb_msg_errno = 0;
2549 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2550 
2551 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2552 }
2553 
2554 static uint8_t
key_satype2scopemask(uint8_t satype)2555 key_satype2scopemask(uint8_t satype)
2556 {
2557 
2558 	if (satype == IPSEC_POLICYSCOPE_ANY)
2559 		return (0xff);
2560 	return (satype);
2561 }
2562 /*
2563  * SADB_SPDDUMP processing
2564  * receive
2565  *   <base>
2566  * from the user, and dump all SP leaves and send,
2567  *   <base> .....
2568  * to the ikmpd.
2569  *
2570  * NOTE:
2571  *   sadb_msg_satype is considered as mask of policy scopes.
2572  *   m will always be freed.
2573  */
2574 static int
key_spddump(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)2575 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2576 {
2577 	SPTREE_RLOCK_TRACKER;
2578 	struct secpolicy *sp;
2579 	struct mbuf *n;
2580 	int cnt;
2581 	u_int dir, scope;
2582 
2583 	IPSEC_ASSERT(so != NULL, ("null socket"));
2584 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
2585 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2586 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2587 
2588 	/* search SPD entry and get buffer size. */
2589 	cnt = 0;
2590 	scope = key_satype2scopemask(mhp->msg->sadb_msg_satype);
2591 	SPTREE_RLOCK();
2592 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2593 		if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2594 			TAILQ_FOREACH(sp, &V_sptree[dir], chain)
2595 				cnt++;
2596 		}
2597 		if (scope & IPSEC_POLICYSCOPE_IFNET) {
2598 			TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain)
2599 				cnt++;
2600 		}
2601 	}
2602 
2603 	if (cnt == 0) {
2604 		SPTREE_RUNLOCK();
2605 		return key_senderror(so, m, ENOENT);
2606 	}
2607 
2608 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2609 		if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2610 			TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2611 				--cnt;
2612 				n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2613 				    mhp->msg->sadb_msg_pid);
2614 
2615 				if (n != NULL)
2616 					key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2617 			}
2618 		}
2619 		if (scope & IPSEC_POLICYSCOPE_IFNET) {
2620 			TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain) {
2621 				--cnt;
2622 				n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2623 				    mhp->msg->sadb_msg_pid);
2624 
2625 				if (n != NULL)
2626 					key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2627 			}
2628 		}
2629 	}
2630 
2631 	SPTREE_RUNLOCK();
2632 	m_freem(m);
2633 	return (0);
2634 }
2635 
2636 static struct mbuf *
key_setdumpsp(struct secpolicy * sp,u_int8_t type,u_int32_t seq,u_int32_t pid)2637 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2638     u_int32_t pid)
2639 {
2640 	struct mbuf *result = NULL, *m;
2641 	struct seclifetime lt;
2642 
2643 	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2644 	if (!m)
2645 		goto fail;
2646 	result = m;
2647 
2648 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2649 	    &sp->spidx.src.sa, sp->spidx.prefs,
2650 	    sp->spidx.ul_proto);
2651 	if (!m)
2652 		goto fail;
2653 	m_cat(result, m);
2654 
2655 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2656 	    &sp->spidx.dst.sa, sp->spidx.prefd,
2657 	    sp->spidx.ul_proto);
2658 	if (!m)
2659 		goto fail;
2660 	m_cat(result, m);
2661 
2662 	m = key_sp2mbuf(sp);
2663 	if (!m)
2664 		goto fail;
2665 	m_cat(result, m);
2666 
2667 	if(sp->lifetime){
2668 		lt.addtime=sp->created;
2669 		lt.usetime= sp->lastused;
2670 		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2671 		if (!m)
2672 			goto fail;
2673 		m_cat(result, m);
2674 
2675 		lt.addtime=sp->lifetime;
2676 		lt.usetime= sp->validtime;
2677 		m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2678 		if (!m)
2679 			goto fail;
2680 		m_cat(result, m);
2681 	}
2682 
2683 	if ((result->m_flags & M_PKTHDR) == 0)
2684 		goto fail;
2685 
2686 	if (result->m_len < sizeof(struct sadb_msg)) {
2687 		result = m_pullup(result, sizeof(struct sadb_msg));
2688 		if (result == NULL)
2689 			goto fail;
2690 	}
2691 
2692 	result->m_pkthdr.len = 0;
2693 	for (m = result; m; m = m->m_next)
2694 		result->m_pkthdr.len += m->m_len;
2695 
2696 	mtod(result, struct sadb_msg *)->sadb_msg_len =
2697 	    PFKEY_UNIT64(result->m_pkthdr.len);
2698 
2699 	return result;
2700 
2701 fail:
2702 	m_freem(result);
2703 	return NULL;
2704 }
2705 /*
2706  * get PFKEY message length for security policy and request.
2707  */
2708 static size_t
key_getspreqmsglen(struct secpolicy * sp)2709 key_getspreqmsglen(struct secpolicy *sp)
2710 {
2711 	size_t tlen, len;
2712 	int i;
2713 
2714 	tlen = sizeof(struct sadb_x_policy);
2715 	/* if is the policy for ipsec ? */
2716 	if (sp->policy != IPSEC_POLICY_IPSEC)
2717 		return (tlen);
2718 
2719 	/* get length of ipsec requests */
2720 	for (i = 0; i < sp->tcount; i++) {
2721 		len = sizeof(struct sadb_x_ipsecrequest)
2722 			+ sp->req[i]->saidx.src.sa.sa_len
2723 			+ sp->req[i]->saidx.dst.sa.sa_len;
2724 
2725 		tlen += PFKEY_ALIGN8(len);
2726 	}
2727 	return (tlen);
2728 }
2729 
2730 /*
2731  * SADB_SPDEXPIRE processing
2732  * send
2733  *   <base, address(SD), lifetime(CH), policy>
2734  * to KMD by PF_KEY.
2735  *
2736  * OUT:	0	: succeed
2737  *	others	: error number
2738  */
2739 static int
key_spdexpire(struct secpolicy * sp)2740 key_spdexpire(struct secpolicy *sp)
2741 {
2742 	struct sadb_lifetime *lt;
2743 	struct mbuf *result = NULL, *m;
2744 	int len, error = -1;
2745 
2746 	IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2747 
2748 	KEYDBG(KEY_STAMP,
2749 	    printf("%s: SP(%p)\n", __func__, sp));
2750 	KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2751 
2752 	/* set msg header */
2753 	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2754 	if (!m) {
2755 		error = ENOBUFS;
2756 		goto fail;
2757 	}
2758 	result = m;
2759 
2760 	/* create lifetime extension (current and hard) */
2761 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2762 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2763 	if (m == NULL) {
2764 		error = ENOBUFS;
2765 		goto fail;
2766 	}
2767 	m_align(m, len);
2768 	m->m_len = len;
2769 	bzero(mtod(m, caddr_t), len);
2770 	lt = mtod(m, struct sadb_lifetime *);
2771 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2772 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2773 	lt->sadb_lifetime_allocations = 0;
2774 	lt->sadb_lifetime_bytes = 0;
2775 	lt->sadb_lifetime_addtime = sp->created;
2776 	lt->sadb_lifetime_usetime = sp->lastused;
2777 	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2778 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2779 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2780 	lt->sadb_lifetime_allocations = 0;
2781 	lt->sadb_lifetime_bytes = 0;
2782 	lt->sadb_lifetime_addtime = sp->lifetime;
2783 	lt->sadb_lifetime_usetime = sp->validtime;
2784 	m_cat(result, m);
2785 
2786 	/* set sadb_address for source */
2787 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2788 	    &sp->spidx.src.sa,
2789 	    sp->spidx.prefs, sp->spidx.ul_proto);
2790 	if (!m) {
2791 		error = ENOBUFS;
2792 		goto fail;
2793 	}
2794 	m_cat(result, m);
2795 
2796 	/* set sadb_address for destination */
2797 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2798 	    &sp->spidx.dst.sa,
2799 	    sp->spidx.prefd, sp->spidx.ul_proto);
2800 	if (!m) {
2801 		error = ENOBUFS;
2802 		goto fail;
2803 	}
2804 	m_cat(result, m);
2805 
2806 	/* set secpolicy */
2807 	m = key_sp2mbuf(sp);
2808 	if (!m) {
2809 		error = ENOBUFS;
2810 		goto fail;
2811 	}
2812 	m_cat(result, m);
2813 
2814 	if ((result->m_flags & M_PKTHDR) == 0) {
2815 		error = EINVAL;
2816 		goto fail;
2817 	}
2818 
2819 	if (result->m_len < sizeof(struct sadb_msg)) {
2820 		result = m_pullup(result, sizeof(struct sadb_msg));
2821 		if (result == NULL) {
2822 			error = ENOBUFS;
2823 			goto fail;
2824 		}
2825 	}
2826 
2827 	result->m_pkthdr.len = 0;
2828 	for (m = result; m; m = m->m_next)
2829 		result->m_pkthdr.len += m->m_len;
2830 
2831 	mtod(result, struct sadb_msg *)->sadb_msg_len =
2832 	    PFKEY_UNIT64(result->m_pkthdr.len);
2833 
2834 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2835 
2836  fail:
2837 	if (result)
2838 		m_freem(result);
2839 	return error;
2840 }
2841 
2842 /* %%% SAD management */
2843 /*
2844  * allocating and initialize new SA head.
2845  * OUT:	NULL	: failure due to the lack of memory.
2846  *	others	: pointer to new SA head.
2847  */
2848 static struct secashead *
key_newsah(struct secasindex * saidx)2849 key_newsah(struct secasindex *saidx)
2850 {
2851 	struct secashead *sah;
2852 
2853 	sah = malloc(sizeof(struct secashead), M_IPSEC_SAH,
2854 	    M_NOWAIT | M_ZERO);
2855 	if (sah == NULL) {
2856 		PFKEYSTAT_INC(in_nomem);
2857 		return (NULL);
2858 	}
2859 	TAILQ_INIT(&sah->savtree_larval);
2860 	TAILQ_INIT(&sah->savtree_alive);
2861 	sah->saidx = *saidx;
2862 	sah->state = SADB_SASTATE_DEAD;
2863 	SAH_INITREF(sah);
2864 
2865 	KEYDBG(KEY_STAMP,
2866 	    printf("%s: SAH(%p)\n", __func__, sah));
2867 	KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2868 	return (sah);
2869 }
2870 
2871 static void
key_freesah(struct secashead ** psah)2872 key_freesah(struct secashead **psah)
2873 {
2874 	struct secashead *sah = *psah;
2875 
2876 	if (SAH_DELREF(sah) == 0)
2877 		return;
2878 
2879 	KEYDBG(KEY_STAMP,
2880 	    printf("%s: last reference to SAH(%p)\n", __func__, sah));
2881 	KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2882 
2883 	*psah = NULL;
2884 	key_delsah(sah);
2885 }
2886 
2887 static void
key_delsah(struct secashead * sah)2888 key_delsah(struct secashead *sah)
2889 {
2890 	IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2891 	IPSEC_ASSERT(sah->state == SADB_SASTATE_DEAD,
2892 	    ("Attempt to free non DEAD SAH %p", sah));
2893 	IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_larval),
2894 	    ("Attempt to free SAH %p with LARVAL SA", sah));
2895 	IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_alive),
2896 	    ("Attempt to free SAH %p with ALIVE SA", sah));
2897 
2898 	free(sah, M_IPSEC_SAH);
2899 }
2900 
2901 /*
2902  * allocating a new SA for key_add() and key_getspi() call,
2903  * and copy the values of mhp into new buffer.
2904  * When SAD message type is SADB_GETSPI set SA state to LARVAL.
2905  * For SADB_ADD create and initialize SA with MATURE state.
2906  * OUT:	NULL	: fail
2907  *	others	: pointer to new secasvar.
2908  */
2909 static struct secasvar *
key_newsav(const struct sadb_msghdr * mhp,struct secasindex * saidx,uint32_t spi,int * errp)2910 key_newsav(const struct sadb_msghdr *mhp, struct secasindex *saidx,
2911     uint32_t spi, int *errp)
2912 {
2913 	struct secashead *sah;
2914 	struct secasvar *sav;
2915 	int isnew;
2916 
2917 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2918 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2919 	IPSEC_ASSERT(mhp->msg->sadb_msg_type == SADB_GETSPI ||
2920 	    mhp->msg->sadb_msg_type == SADB_ADD, ("wrong message type"));
2921 
2922 	sav = NULL;
2923 	sah = NULL;
2924 	/* check SPI value */
2925 	switch (saidx->proto) {
2926 	case IPPROTO_ESP:
2927 	case IPPROTO_AH:
2928 		/*
2929 		 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
2930 		 * 1-255 reserved by IANA for future use,
2931 		 * 0 for implementation specific, local use.
2932 		 */
2933 		if (ntohl(spi) <= 255) {
2934 			ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
2935 			    __func__, ntohl(spi)));
2936 			*errp = EINVAL;
2937 			goto done;
2938 		}
2939 		break;
2940 	}
2941 
2942 	sav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT | M_ZERO);
2943 	if (sav == NULL) {
2944 		*errp = ENOBUFS;
2945 		goto done;
2946 	}
2947 	sav->lock = malloc(sizeof(struct rmlock), M_IPSEC_MISC,
2948 	    M_NOWAIT | M_ZERO);
2949 	if (sav->lock == NULL) {
2950 		*errp = ENOBUFS;
2951 		goto done;
2952 	}
2953 	rm_init(sav->lock, "ipsec association");
2954 	sav->lft_c = uma_zalloc_pcpu(V_key_lft_zone, M_NOWAIT);
2955 	if (sav->lft_c == NULL) {
2956 		*errp = ENOBUFS;
2957 		goto done;
2958 	}
2959 	counter_u64_zero(sav->lft_c_allocations);
2960 	counter_u64_zero(sav->lft_c_bytes);
2961 
2962 	sav->spi = spi;
2963 	sav->seq = mhp->msg->sadb_msg_seq;
2964 	sav->state = SADB_SASTATE_LARVAL;
2965 	sav->pid = (pid_t)mhp->msg->sadb_msg_pid;
2966 	SAV_INITREF(sav);
2967 again:
2968 	sah = key_getsah(saidx);
2969 	if (sah == NULL) {
2970 		/* create a new SA index */
2971 		sah = key_newsah(saidx);
2972 		if (sah == NULL) {
2973 			ipseclog((LOG_DEBUG,
2974 			    "%s: No more memory.\n", __func__));
2975 			*errp = ENOBUFS;
2976 			goto done;
2977 		}
2978 		isnew = 1;
2979 	} else
2980 		isnew = 0;
2981 
2982 	sav->sah = sah;
2983 	if (mhp->msg->sadb_msg_type == SADB_GETSPI) {
2984 		sav->created = time_second;
2985 	} else if (sav->state == SADB_SASTATE_LARVAL) {
2986 		/*
2987 		 * Do not call key_setsaval() second time in case
2988 		 * of `goto again`. We will have MATURE state.
2989 		 */
2990 		*errp = key_setsaval(sav, mhp);
2991 		if (*errp != 0)
2992 			goto done;
2993 		sav->state = SADB_SASTATE_MATURE;
2994 	}
2995 
2996 	SAHTREE_WLOCK();
2997 	/*
2998 	 * Check that existing SAH wasn't unlinked.
2999 	 * Since we didn't hold the SAHTREE lock, it is possible,
3000 	 * that callout handler or key_flush() or key_delete() could
3001 	 * unlink this SAH.
3002 	 */
3003 	if (isnew == 0 && sah->state == SADB_SASTATE_DEAD) {
3004 		SAHTREE_WUNLOCK();
3005 		key_freesah(&sah);	/* reference from key_getsah() */
3006 		goto again;
3007 	}
3008 	if (isnew != 0) {
3009 		/*
3010 		 * Add new SAH into SADB.
3011 		 *
3012 		 * XXXAE: we can serialize key_add and key_getspi calls, so
3013 		 * several threads will not fight in the race.
3014 		 * Otherwise we should check under SAHTREE lock, that this
3015 		 * SAH would not added twice.
3016 		 */
3017 		TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
3018 		/* Add new SAH into hash by addresses */
3019 		LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
3020 		/* Now we are linked in the chain */
3021 		sah->state = SADB_SASTATE_MATURE;
3022 		/*
3023 		 * SAV references this new SAH.
3024 		 * In case of existing SAH we reuse reference
3025 		 * from key_getsah().
3026 		 */
3027 		SAH_ADDREF(sah);
3028 	}
3029 	/* Link SAV with SAH */
3030 	if (sav->state == SADB_SASTATE_MATURE)
3031 		TAILQ_INSERT_HEAD(&sah->savtree_alive, sav, chain);
3032 	else
3033 		TAILQ_INSERT_HEAD(&sah->savtree_larval, sav, chain);
3034 	/* Add SAV into SPI hash */
3035 	LIST_INSERT_HEAD(SAVHASH_HASH(sav->spi), sav, spihash);
3036 	SAHTREE_WUNLOCK();
3037 	*errp = 0;	/* success */
3038 done:
3039 	if (*errp != 0) {
3040 		if (sav != NULL) {
3041 			if (sav->lock != NULL) {
3042 				rm_destroy(sav->lock);
3043 				free(sav->lock, M_IPSEC_MISC);
3044 			}
3045 			if (sav->lft_c != NULL)
3046 				uma_zfree_pcpu(V_key_lft_zone, sav->lft_c);
3047 			free(sav, M_IPSEC_SA), sav = NULL;
3048 		}
3049 		if (sah != NULL)
3050 			key_freesah(&sah);
3051 		if (*errp == ENOBUFS) {
3052 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3053 			    __func__));
3054 			PFKEYSTAT_INC(in_nomem);
3055 		}
3056 	}
3057 	return (sav);
3058 }
3059 
3060 /*
3061  * free() SA variable entry.
3062  */
3063 static void
key_cleansav(struct secasvar * sav)3064 key_cleansav(struct secasvar *sav)
3065 {
3066 
3067 	if (sav->natt != NULL) {
3068 		free(sav->natt, M_IPSEC_MISC);
3069 		sav->natt = NULL;
3070 	}
3071 	if (sav->flags & SADB_X_EXT_F_CLONED)
3072 		return;
3073 	if (sav->tdb_xform != NULL) {
3074 		sav->tdb_xform->xf_cleanup(sav);
3075 		sav->tdb_xform = NULL;
3076 	}
3077 	if (sav->key_auth != NULL) {
3078 		zfree(sav->key_auth->key_data, M_IPSEC_MISC);
3079 		free(sav->key_auth, M_IPSEC_MISC);
3080 		sav->key_auth = NULL;
3081 	}
3082 	if (sav->key_enc != NULL) {
3083 		zfree(sav->key_enc->key_data, M_IPSEC_MISC);
3084 		free(sav->key_enc, M_IPSEC_MISC);
3085 		sav->key_enc = NULL;
3086 	}
3087 	if (sav->replay != NULL) {
3088 		mtx_destroy(&sav->replay->lock);
3089 		if (sav->replay->bitmap != NULL)
3090 			free(sav->replay->bitmap, M_IPSEC_MISC);
3091 		free(sav->replay, M_IPSEC_MISC);
3092 		sav->replay = NULL;
3093 	}
3094 	if (sav->lft_h != NULL) {
3095 		free(sav->lft_h, M_IPSEC_MISC);
3096 		sav->lft_h = NULL;
3097 	}
3098 	if (sav->lft_s != NULL) {
3099 		free(sav->lft_s, M_IPSEC_MISC);
3100 		sav->lft_s = NULL;
3101 	}
3102 }
3103 
3104 /*
3105  * free() SA variable entry.
3106  */
3107 static void
key_delsav(struct secasvar * sav)3108 key_delsav(struct secasvar *sav)
3109 {
3110 	IPSEC_ASSERT(sav != NULL, ("null sav"));
3111 	IPSEC_ASSERT(sav->state == SADB_SASTATE_DEAD,
3112 	    ("attempt to free non DEAD SA %p", sav));
3113 	IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0",
3114 	    sav->refcnt));
3115 
3116 	/*
3117 	 * SA must be unlinked from the chain and hashtbl.
3118 	 * If SA was cloned, we leave all fields untouched,
3119 	 * except NAT-T config.
3120 	 */
3121 	key_cleansav(sav);
3122 	if ((sav->flags & SADB_X_EXT_F_CLONED) == 0) {
3123 		rm_destroy(sav->lock);
3124 		free(sav->lock, M_IPSEC_MISC);
3125 		uma_zfree_pcpu(V_key_lft_zone, sav->lft_c);
3126 	}
3127 	free(sav, M_IPSEC_SA);
3128 }
3129 
3130 /*
3131  * search SAH.
3132  * OUT:
3133  *	NULL	: not found
3134  *	others	: found, referenced pointer to a SAH.
3135  */
3136 static struct secashead *
key_getsah(struct secasindex * saidx)3137 key_getsah(struct secasindex *saidx)
3138 {
3139 	SAHTREE_RLOCK_TRACKER;
3140 	struct secashead *sah;
3141 
3142 	SAHTREE_RLOCK();
3143 	LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
3144 	    if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID) != 0) {
3145 		    SAH_ADDREF(sah);
3146 		    break;
3147 	    }
3148 	}
3149 	SAHTREE_RUNLOCK();
3150 	return (sah);
3151 }
3152 
3153 /*
3154  * Check not to be duplicated SPI.
3155  * OUT:
3156  *	0	: not found
3157  *	1	: found SA with given SPI.
3158  */
3159 static int
key_checkspidup(uint32_t spi)3160 key_checkspidup(uint32_t spi)
3161 {
3162 	SAHTREE_RLOCK_TRACKER;
3163 	struct secasvar *sav;
3164 
3165 	/* Assume SPI is in network byte order */
3166 	SAHTREE_RLOCK();
3167 	LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3168 		if (sav->spi == spi)
3169 			break;
3170 	}
3171 	SAHTREE_RUNLOCK();
3172 	return (sav != NULL);
3173 }
3174 
3175 /*
3176  * Search SA by SPI.
3177  * OUT:
3178  *	NULL	: not found
3179  *	others	: found, referenced pointer to a SA.
3180  */
3181 static struct secasvar *
key_getsavbyspi(uint32_t spi)3182 key_getsavbyspi(uint32_t spi)
3183 {
3184 	SAHTREE_RLOCK_TRACKER;
3185 	struct secasvar *sav;
3186 
3187 	/* Assume SPI is in network byte order */
3188 	SAHTREE_RLOCK();
3189 	LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3190 		if (sav->spi != spi)
3191 			continue;
3192 		SAV_ADDREF(sav);
3193 		break;
3194 	}
3195 	SAHTREE_RUNLOCK();
3196 	return (sav);
3197 }
3198 
3199 static int
key_updatelifetimes(struct secasvar * sav,const struct sadb_msghdr * mhp)3200 key_updatelifetimes(struct secasvar *sav, const struct sadb_msghdr *mhp)
3201 {
3202 	struct seclifetime *lft_h, *lft_s, *tmp;
3203 
3204 	/* Lifetime extension is optional, check that it is present. */
3205 	if (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3206 	    SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) {
3207 		/*
3208 		 * In case of SADB_UPDATE we may need to change
3209 		 * existing lifetimes.
3210 		 */
3211 		if (sav->state == SADB_SASTATE_MATURE) {
3212 			lft_h = lft_s = NULL;
3213 			goto reset;
3214 		}
3215 		return (0);
3216 	}
3217 	/* Both HARD and SOFT extensions must present */
3218 	if ((SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3219 	    !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
3220 	    (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
3221 	    !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
3222 		ipseclog((LOG_DEBUG,
3223 		    "%s: invalid message: missing required header.\n",
3224 		    __func__));
3225 		return (EINVAL);
3226 	}
3227 	if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD) ||
3228 	    SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_SOFT)) {
3229 		ipseclog((LOG_DEBUG,
3230 		    "%s: invalid message: wrong header size.\n", __func__));
3231 		return (EINVAL);
3232 	}
3233 	lft_h = key_dup_lifemsg((const struct sadb_lifetime *)
3234 	    mhp->ext[SADB_EXT_LIFETIME_HARD], M_IPSEC_MISC);
3235 	if (lft_h == NULL) {
3236 		PFKEYSTAT_INC(in_nomem);
3237 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3238 		return (ENOBUFS);
3239 	}
3240 	lft_s = key_dup_lifemsg((const struct sadb_lifetime *)
3241 	    mhp->ext[SADB_EXT_LIFETIME_SOFT], M_IPSEC_MISC);
3242 	if (lft_s == NULL) {
3243 		PFKEYSTAT_INC(in_nomem);
3244 		free(lft_h, M_IPSEC_MISC);
3245 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3246 		return (ENOBUFS);
3247 	}
3248 reset:
3249 	if (sav->state != SADB_SASTATE_LARVAL) {
3250 		/*
3251 		 * key_update() holds reference to this SA,
3252 		 * so it won't be deleted in meanwhile.
3253 		 */
3254 		SECASVAR_WLOCK(sav);
3255 		tmp = sav->lft_h;
3256 		sav->lft_h = lft_h;
3257 		lft_h = tmp;
3258 
3259 		tmp = sav->lft_s;
3260 		sav->lft_s = lft_s;
3261 		lft_s = tmp;
3262 		SECASVAR_WUNLOCK(sav);
3263 		if (lft_h != NULL)
3264 			free(lft_h, M_IPSEC_MISC);
3265 		if (lft_s != NULL)
3266 			free(lft_s, M_IPSEC_MISC);
3267 		return (0);
3268 	}
3269 	/* We can update lifetime without holding a lock */
3270 	IPSEC_ASSERT(sav->lft_h == NULL, ("lft_h is already initialized\n"));
3271 	IPSEC_ASSERT(sav->lft_s == NULL, ("lft_s is already initialized\n"));
3272 	sav->lft_h = lft_h;
3273 	sav->lft_s = lft_s;
3274 	return (0);
3275 }
3276 
3277 /*
3278  * copy SA values from PF_KEY message except *SPI, SEQ, PID and TYPE*.
3279  * You must update these if need. Expects only LARVAL SAs.
3280  * OUT:	0:	success.
3281  *	!0:	failure.
3282  */
3283 static int
key_setsaval(struct secasvar * sav,const struct sadb_msghdr * mhp)3284 key_setsaval(struct secasvar *sav, const struct sadb_msghdr *mhp)
3285 {
3286 	const struct sadb_sa *sa0;
3287 	const struct sadb_key *key0;
3288 	uint32_t replay;
3289 	size_t len;
3290 	int error;
3291 
3292 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3293 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3294 	IPSEC_ASSERT(sav->state == SADB_SASTATE_LARVAL,
3295 	    ("Attempt to update non LARVAL SA"));
3296 
3297 	/* XXX rewrite */
3298 	error = key_setident(sav->sah, mhp);
3299 	if (error != 0)
3300 		goto fail;
3301 
3302 	/* SA */
3303 	if (!SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
3304 		if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
3305 			error = EINVAL;
3306 			goto fail;
3307 		}
3308 		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3309 		sav->alg_auth = sa0->sadb_sa_auth;
3310 		sav->alg_enc = sa0->sadb_sa_encrypt;
3311 		sav->flags = sa0->sadb_sa_flags;
3312 		if ((sav->flags & SADB_KEY_FLAGS_MAX) != sav->flags) {
3313 			ipseclog((LOG_DEBUG,
3314 			    "%s: invalid sa_flags 0x%08x.\n", __func__,
3315 			    sav->flags));
3316 			error = EINVAL;
3317 			goto fail;
3318 		}
3319 
3320 		/* Optional replay window */
3321 		replay = 0;
3322 		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0)
3323 			replay = sa0->sadb_sa_replay;
3324 		if (!SADB_CHECKHDR(mhp, SADB_X_EXT_SA_REPLAY)) {
3325 			if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA_REPLAY)) {
3326 				error = EINVAL;
3327 				goto fail;
3328 			}
3329 			replay = ((const struct sadb_x_sa_replay *)
3330 			    mhp->ext[SADB_X_EXT_SA_REPLAY])->sadb_x_sa_replay_replay;
3331 
3332 			if (replay > UINT32_MAX - 32) {
3333 				ipseclog((LOG_DEBUG,
3334 				    "%s: replay window too big.\n", __func__));
3335 				error = EINVAL;
3336 				goto fail;
3337 			}
3338 
3339 			replay = (replay + 7) >> 3;
3340 		}
3341 
3342 		sav->replay = malloc(sizeof(struct secreplay), M_IPSEC_MISC,
3343 		    M_NOWAIT | M_ZERO);
3344 		if (sav->replay == NULL) {
3345 			PFKEYSTAT_INC(in_nomem);
3346 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3347 			    __func__));
3348 			error = ENOBUFS;
3349 			goto fail;
3350 		}
3351 		mtx_init(&sav->replay->lock, "ipsec replay", NULL, MTX_DEF);
3352 
3353 		if (replay != 0) {
3354 			/* number of 32b blocks to be allocated */
3355 			uint32_t bitmap_size;
3356 
3357 			/* RFC 6479:
3358 			 * - the allocated replay window size must be
3359 			 *   a power of two.
3360 			 * - use an extra 32b block as a redundant window.
3361 			 */
3362 			bitmap_size = 1;
3363 			while (replay + 4 > bitmap_size)
3364 				bitmap_size <<= 1;
3365 			bitmap_size = bitmap_size / 4;
3366 
3367 			sav->replay->bitmap = malloc(
3368 			    bitmap_size * sizeof(uint32_t), M_IPSEC_MISC,
3369 			    M_NOWAIT | M_ZERO);
3370 			if (sav->replay->bitmap == NULL) {
3371 				PFKEYSTAT_INC(in_nomem);
3372 				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3373 					__func__));
3374 				error = ENOBUFS;
3375 				goto fail;
3376 			}
3377 			sav->replay->bitmap_size = bitmap_size;
3378 			sav->replay->wsize = replay;
3379 		}
3380 	}
3381 
3382 	/* Authentication keys */
3383 	if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
3384 		if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH)) {
3385 			error = EINVAL;
3386 			goto fail;
3387 		}
3388 		error = 0;
3389 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3390 		len = mhp->extlen[SADB_EXT_KEY_AUTH];
3391 		switch (mhp->msg->sadb_msg_satype) {
3392 		case SADB_SATYPE_AH:
3393 		case SADB_SATYPE_ESP:
3394 		case SADB_X_SATYPE_TCPSIGNATURE:
3395 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3396 			    sav->alg_auth != SADB_X_AALG_NULL)
3397 				error = EINVAL;
3398 			if (key0->sadb_key_bits == 0 || (sizeof(struct sadb_key) +
3399 			    (key0->sadb_key_bits >> 3)) > len)
3400 				error = EINVAL;
3401 			break;
3402 		case SADB_X_SATYPE_IPCOMP:
3403 		default:
3404 			error = EINVAL;
3405 			break;
3406 		}
3407 		if (error) {
3408 			ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3409 				__func__));
3410 			goto fail;
3411 		}
3412 
3413 		sav->key_auth = key_dup_keymsg(key0, M_IPSEC_MISC);
3414 		if (sav->key_auth == NULL ) {
3415 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3416 				  __func__));
3417 			PFKEYSTAT_INC(in_nomem);
3418 			error = ENOBUFS;
3419 			goto fail;
3420 		}
3421 	}
3422 
3423 	/* Encryption key */
3424 	if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) {
3425 		if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT)) {
3426 			error = EINVAL;
3427 			goto fail;
3428 		}
3429 		error = 0;
3430 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3431 		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3432 		switch (mhp->msg->sadb_msg_satype) {
3433 		case SADB_SATYPE_ESP:
3434 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3435 			    sav->alg_enc != SADB_EALG_NULL) {
3436 				error = EINVAL;
3437 				break;
3438 			}
3439 			if (key0->sadb_key_bits == 0 || (sizeof(struct sadb_key) +
3440 			    (key0->sadb_key_bits >> 3)) > len) {
3441 				error = EINVAL;
3442 				break;
3443 			}
3444 			sav->key_enc = key_dup_keymsg(key0, M_IPSEC_MISC);
3445 			if (sav->key_enc == NULL) {
3446 				ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3447 					__func__));
3448 				PFKEYSTAT_INC(in_nomem);
3449 				error = ENOBUFS;
3450 				goto fail;
3451 			}
3452 			break;
3453 		case SADB_X_SATYPE_IPCOMP:
3454 			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3455 				error = EINVAL;
3456 			sav->key_enc = NULL;	/*just in case*/
3457 			break;
3458 		case SADB_SATYPE_AH:
3459 		case SADB_X_SATYPE_TCPSIGNATURE:
3460 		default:
3461 			error = EINVAL;
3462 			break;
3463 		}
3464 		if (error) {
3465 			ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3466 				__func__));
3467 			goto fail;
3468 		}
3469 	}
3470 
3471 	/* set iv */
3472 	sav->ivlen = 0;
3473 	switch (mhp->msg->sadb_msg_satype) {
3474 	case SADB_SATYPE_AH:
3475 		if (sav->flags & SADB_X_EXT_DERIV) {
3476 			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3477 			    "given to AH SA.\n", __func__));
3478 			error = EINVAL;
3479 			goto fail;
3480 		}
3481 		if (sav->alg_enc != SADB_EALG_NONE) {
3482 			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3483 			    "mismated.\n", __func__));
3484 			error = EINVAL;
3485 			goto fail;
3486 		}
3487 		error = xform_init(sav, XF_AH);
3488 		break;
3489 	case SADB_SATYPE_ESP:
3490 		if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) ==
3491 		    (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) {
3492 			ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3493 			    "given to old-esp.\n", __func__));
3494 			error = EINVAL;
3495 			goto fail;
3496 		}
3497 		error = xform_init(sav, XF_ESP);
3498 		break;
3499 	case SADB_X_SATYPE_IPCOMP:
3500 		if (sav->alg_auth != SADB_AALG_NONE) {
3501 			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3502 			    "mismated.\n", __func__));
3503 			error = EINVAL;
3504 			goto fail;
3505 		}
3506 		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0 &&
3507 		    ntohl(sav->spi) >= 0x10000) {
3508 			ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3509 			    __func__));
3510 			error = EINVAL;
3511 			goto fail;
3512 		}
3513 		error = xform_init(sav, XF_IPCOMP);
3514 		break;
3515 	case SADB_X_SATYPE_TCPSIGNATURE:
3516 		if (sav->alg_enc != SADB_EALG_NONE) {
3517 			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3518 			    "mismated.\n", __func__));
3519 			error = EINVAL;
3520 			goto fail;
3521 		}
3522 		error = xform_init(sav, XF_TCPSIGNATURE);
3523 		break;
3524 	default:
3525 		ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3526 		error = EPROTONOSUPPORT;
3527 		goto fail;
3528 	}
3529 	if (error) {
3530 		ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3531 		    __func__, mhp->msg->sadb_msg_satype));
3532 		goto fail;
3533 	}
3534 
3535 	/* Handle NAT-T headers */
3536 	error = key_setnatt(sav, mhp);
3537 	if (error != 0)
3538 		goto fail;
3539 
3540 	/* Initialize lifetime for CURRENT */
3541 	sav->firstused = 0;
3542 	sav->created = time_second;
3543 
3544 	/* lifetimes for HARD and SOFT */
3545 	error = key_updatelifetimes(sav, mhp);
3546 	if (error == 0)
3547 		return (0);
3548 fail:
3549 	key_cleansav(sav);
3550 	return (error);
3551 }
3552 
3553 /*
3554  * subroutine for SADB_GET and SADB_DUMP.
3555  */
3556 static struct mbuf *
key_setdumpsa(struct secasvar * sav,uint8_t type,uint8_t satype,uint32_t seq,uint32_t pid)3557 key_setdumpsa(struct secasvar *sav, uint8_t type, uint8_t satype,
3558     uint32_t seq, uint32_t pid)
3559 {
3560 	struct seclifetime lft_c;
3561 	struct mbuf *result = NULL, *tres = NULL, *m;
3562 	int i, dumporder[] = {
3563 		SADB_EXT_SA, SADB_X_EXT_SA2, SADB_X_EXT_SA_REPLAY,
3564 		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3565 		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3566 		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY,
3567 		SADB_EXT_KEY_AUTH, SADB_EXT_KEY_ENCRYPT,
3568 		SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
3569 		SADB_EXT_SENSITIVITY,
3570 		SADB_X_EXT_NAT_T_TYPE,
3571 		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3572 		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3573 		SADB_X_EXT_NAT_T_FRAG,
3574 	};
3575 	uint32_t replay_count;
3576 
3577 	SECASVAR_RLOCK_TRACKER;
3578 
3579 	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3580 	if (m == NULL)
3581 		goto fail;
3582 	result = m;
3583 
3584 	for (i = nitems(dumporder) - 1; i >= 0; i--) {
3585 		m = NULL;
3586 		switch (dumporder[i]) {
3587 		case SADB_EXT_SA:
3588 			m = key_setsadbsa(sav);
3589 			if (!m)
3590 				goto fail;
3591 			break;
3592 
3593 		case SADB_X_EXT_SA2: {
3594 			SECASVAR_RLOCK(sav);
3595 			replay_count = sav->replay ? sav->replay->count : 0;
3596 			SECASVAR_RUNLOCK(sav);
3597 			m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
3598 					sav->sah->saidx.reqid);
3599 			if (!m)
3600 				goto fail;
3601 			break;
3602 		}
3603 		case SADB_X_EXT_SA_REPLAY:
3604 			if (sav->replay == NULL ||
3605 			    sav->replay->wsize <= UINT8_MAX)
3606 				continue;
3607 
3608 			m = key_setsadbxsareplay(sav->replay->wsize);
3609 			if (!m)
3610 				goto fail;
3611 			break;
3612 
3613 		case SADB_EXT_ADDRESS_SRC:
3614 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3615 			    &sav->sah->saidx.src.sa,
3616 			    FULLMASK, IPSEC_ULPROTO_ANY);
3617 			if (!m)
3618 				goto fail;
3619 			break;
3620 
3621 		case SADB_EXT_ADDRESS_DST:
3622 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3623 			    &sav->sah->saidx.dst.sa,
3624 			    FULLMASK, IPSEC_ULPROTO_ANY);
3625 			if (!m)
3626 				goto fail;
3627 			break;
3628 
3629 		case SADB_EXT_KEY_AUTH:
3630 			if (!sav->key_auth)
3631 				continue;
3632 			m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3633 			if (!m)
3634 				goto fail;
3635 			break;
3636 
3637 		case SADB_EXT_KEY_ENCRYPT:
3638 			if (!sav->key_enc)
3639 				continue;
3640 			m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3641 			if (!m)
3642 				goto fail;
3643 			break;
3644 
3645 		case SADB_EXT_LIFETIME_CURRENT:
3646 			lft_c.addtime = sav->created;
3647 			lft_c.allocations = (uint32_t)counter_u64_fetch(
3648 			    sav->lft_c_allocations);
3649 			lft_c.bytes = counter_u64_fetch(sav->lft_c_bytes);
3650 			lft_c.usetime = sav->firstused;
3651 			m = key_setlifetime(&lft_c, SADB_EXT_LIFETIME_CURRENT);
3652 			if (!m)
3653 				goto fail;
3654 			break;
3655 
3656 		case SADB_EXT_LIFETIME_HARD:
3657 			if (!sav->lft_h)
3658 				continue;
3659 			m = key_setlifetime(sav->lft_h,
3660 					    SADB_EXT_LIFETIME_HARD);
3661 			if (!m)
3662 				goto fail;
3663 			break;
3664 
3665 		case SADB_EXT_LIFETIME_SOFT:
3666 			if (!sav->lft_s)
3667 				continue;
3668 			m = key_setlifetime(sav->lft_s,
3669 					    SADB_EXT_LIFETIME_SOFT);
3670 
3671 			if (!m)
3672 				goto fail;
3673 			break;
3674 
3675 		case SADB_X_EXT_NAT_T_TYPE:
3676 			if (sav->natt == NULL)
3677 				continue;
3678 			m = key_setsadbxtype(UDP_ENCAP_ESPINUDP);
3679 			if (!m)
3680 				goto fail;
3681 			break;
3682 
3683 		case SADB_X_EXT_NAT_T_DPORT:
3684 			if (sav->natt == NULL)
3685 				continue;
3686 			m = key_setsadbxport(sav->natt->dport,
3687 			    SADB_X_EXT_NAT_T_DPORT);
3688 			if (!m)
3689 				goto fail;
3690 			break;
3691 
3692 		case SADB_X_EXT_NAT_T_SPORT:
3693 			if (sav->natt == NULL)
3694 				continue;
3695 			m = key_setsadbxport(sav->natt->sport,
3696 			    SADB_X_EXT_NAT_T_SPORT);
3697 			if (!m)
3698 				goto fail;
3699 			break;
3700 
3701 		case SADB_X_EXT_NAT_T_OAI:
3702 			if (sav->natt == NULL ||
3703 			    (sav->natt->flags & IPSEC_NATT_F_OAI) == 0)
3704 				continue;
3705 			m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAI,
3706 			    &sav->natt->oai.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3707 			if (!m)
3708 				goto fail;
3709 			break;
3710 		case SADB_X_EXT_NAT_T_OAR:
3711 			if (sav->natt == NULL ||
3712 			    (sav->natt->flags & IPSEC_NATT_F_OAR) == 0)
3713 				continue;
3714 			m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAR,
3715 			    &sav->natt->oar.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3716 			if (!m)
3717 				goto fail;
3718 			break;
3719 		case SADB_X_EXT_NAT_T_FRAG:
3720 			/* We do not (yet) support those. */
3721 			continue;
3722 
3723 		case SADB_EXT_ADDRESS_PROXY:
3724 		case SADB_EXT_IDENTITY_SRC:
3725 		case SADB_EXT_IDENTITY_DST:
3726 			/* XXX: should we brought from SPD ? */
3727 		case SADB_EXT_SENSITIVITY:
3728 		default:
3729 			continue;
3730 		}
3731 
3732 		if (!m)
3733 			goto fail;
3734 		if (tres)
3735 			m_cat(m, tres);
3736 		tres = m;
3737 	}
3738 
3739 	m_cat(result, tres);
3740 	tres = NULL;
3741 	if (result->m_len < sizeof(struct sadb_msg)) {
3742 		result = m_pullup(result, sizeof(struct sadb_msg));
3743 		if (result == NULL)
3744 			goto fail;
3745 	}
3746 
3747 	result->m_pkthdr.len = 0;
3748 	for (m = result; m; m = m->m_next)
3749 		result->m_pkthdr.len += m->m_len;
3750 
3751 	mtod(result, struct sadb_msg *)->sadb_msg_len =
3752 	    PFKEY_UNIT64(result->m_pkthdr.len);
3753 
3754 	return result;
3755 
3756 fail:
3757 	m_freem(result);
3758 	m_freem(tres);
3759 	return NULL;
3760 }
3761 
3762 /*
3763  * set data into sadb_msg.
3764  */
3765 static struct mbuf *
key_setsadbmsg(u_int8_t type,u_int16_t tlen,u_int8_t satype,u_int32_t seq,pid_t pid,u_int16_t reserved)3766 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3767     pid_t pid, u_int16_t reserved)
3768 {
3769 	struct mbuf *m;
3770 	struct sadb_msg *p;
3771 	int len;
3772 
3773 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3774 	if (len > MCLBYTES)
3775 		return NULL;
3776 	m = key_mget(len);
3777 	if (m == NULL)
3778 		return NULL;
3779 	m->m_pkthdr.len = m->m_len = len;
3780 	m->m_next = NULL;
3781 
3782 	p = mtod(m, struct sadb_msg *);
3783 
3784 	bzero(p, len);
3785 	p->sadb_msg_version = PF_KEY_V2;
3786 	p->sadb_msg_type = type;
3787 	p->sadb_msg_errno = 0;
3788 	p->sadb_msg_satype = satype;
3789 	p->sadb_msg_len = PFKEY_UNIT64(tlen);
3790 	p->sadb_msg_reserved = reserved;
3791 	p->sadb_msg_seq = seq;
3792 	p->sadb_msg_pid = (u_int32_t)pid;
3793 
3794 	return m;
3795 }
3796 
3797 /*
3798  * copy secasvar data into sadb_address.
3799  */
3800 static struct mbuf *
key_setsadbsa(struct secasvar * sav)3801 key_setsadbsa(struct secasvar *sav)
3802 {
3803 	struct mbuf *m;
3804 	struct sadb_sa *p;
3805 	int len;
3806 
3807 	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3808 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3809 	if (m == NULL)
3810 		return (NULL);
3811 	m_align(m, len);
3812 	m->m_len = len;
3813 	p = mtod(m, struct sadb_sa *);
3814 	bzero(p, len);
3815 	p->sadb_sa_len = PFKEY_UNIT64(len);
3816 	p->sadb_sa_exttype = SADB_EXT_SA;
3817 	p->sadb_sa_spi = sav->spi;
3818 	p->sadb_sa_replay = sav->replay ?
3819 	    (sav->replay->wsize > UINT8_MAX ? UINT8_MAX :
3820 		sav->replay->wsize): 0;
3821 	p->sadb_sa_state = sav->state;
3822 	p->sadb_sa_auth = sav->alg_auth;
3823 	p->sadb_sa_encrypt = sav->alg_enc;
3824 	p->sadb_sa_flags = sav->flags & SADB_KEY_FLAGS_MAX;
3825 	return (m);
3826 }
3827 
3828 /*
3829  * set data into sadb_address.
3830  */
3831 static struct mbuf *
key_setsadbaddr(u_int16_t exttype,const struct sockaddr * saddr,u_int8_t prefixlen,u_int16_t ul_proto)3832 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3833     u_int8_t prefixlen, u_int16_t ul_proto)
3834 {
3835 	struct mbuf *m;
3836 	struct sadb_address *p;
3837 	size_t len;
3838 
3839 	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3840 	    PFKEY_ALIGN8(saddr->sa_len);
3841 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3842 	if (m == NULL)
3843 		return (NULL);
3844 	m_align(m, len);
3845 	m->m_len = len;
3846 	p = mtod(m, struct sadb_address *);
3847 
3848 	bzero(p, len);
3849 	p->sadb_address_len = PFKEY_UNIT64(len);
3850 	p->sadb_address_exttype = exttype;
3851 	p->sadb_address_proto = ul_proto;
3852 	if (prefixlen == FULLMASK) {
3853 		switch (saddr->sa_family) {
3854 		case AF_INET:
3855 			prefixlen = sizeof(struct in_addr) << 3;
3856 			break;
3857 		case AF_INET6:
3858 			prefixlen = sizeof(struct in6_addr) << 3;
3859 			break;
3860 		default:
3861 			; /*XXX*/
3862 		}
3863 	}
3864 	p->sadb_address_prefixlen = prefixlen;
3865 	p->sadb_address_reserved = 0;
3866 
3867 	bcopy(saddr,
3868 	    mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3869 	    saddr->sa_len);
3870 
3871 	return m;
3872 }
3873 
3874 /*
3875  * set data into sadb_x_sa2.
3876  */
3877 static struct mbuf *
key_setsadbxsa2(u_int8_t mode,u_int32_t seq,u_int32_t reqid)3878 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3879 {
3880 	struct mbuf *m;
3881 	struct sadb_x_sa2 *p;
3882 	size_t len;
3883 
3884 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3885 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3886 	if (m == NULL)
3887 		return (NULL);
3888 	m_align(m, len);
3889 	m->m_len = len;
3890 	p = mtod(m, struct sadb_x_sa2 *);
3891 
3892 	bzero(p, len);
3893 	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3894 	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3895 	p->sadb_x_sa2_mode = mode;
3896 	p->sadb_x_sa2_reserved1 = 0;
3897 	p->sadb_x_sa2_reserved2 = 0;
3898 	p->sadb_x_sa2_sequence = seq;
3899 	p->sadb_x_sa2_reqid = reqid;
3900 
3901 	return m;
3902 }
3903 
3904 /*
3905  * Set data into sadb_x_sa_replay.
3906  */
3907 static struct mbuf *
key_setsadbxsareplay(u_int32_t replay)3908 key_setsadbxsareplay(u_int32_t replay)
3909 {
3910 	struct mbuf *m;
3911 	struct sadb_x_sa_replay *p;
3912 	size_t len;
3913 
3914 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa_replay));
3915 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3916 	if (m == NULL)
3917 		return (NULL);
3918 	m_align(m, len);
3919 	m->m_len = len;
3920 	p = mtod(m, struct sadb_x_sa_replay *);
3921 
3922 	bzero(p, len);
3923 	p->sadb_x_sa_replay_len = PFKEY_UNIT64(len);
3924 	p->sadb_x_sa_replay_exttype = SADB_X_EXT_SA_REPLAY;
3925 	p->sadb_x_sa_replay_replay = (replay << 3);
3926 
3927 	return m;
3928 }
3929 
3930 /*
3931  * Set a type in sadb_x_nat_t_type.
3932  */
3933 static struct mbuf *
key_setsadbxtype(u_int16_t type)3934 key_setsadbxtype(u_int16_t type)
3935 {
3936 	struct mbuf *m;
3937 	size_t len;
3938 	struct sadb_x_nat_t_type *p;
3939 
3940 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3941 
3942 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3943 	if (m == NULL)
3944 		return (NULL);
3945 	m_align(m, len);
3946 	m->m_len = len;
3947 	p = mtod(m, struct sadb_x_nat_t_type *);
3948 
3949 	bzero(p, len);
3950 	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3951 	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3952 	p->sadb_x_nat_t_type_type = type;
3953 
3954 	return (m);
3955 }
3956 /*
3957  * Set a port in sadb_x_nat_t_port.
3958  * In contrast to default RFC 2367 behaviour, port is in network byte order.
3959  */
3960 static struct mbuf *
key_setsadbxport(u_int16_t port,u_int16_t type)3961 key_setsadbxport(u_int16_t port, u_int16_t type)
3962 {
3963 	struct mbuf *m;
3964 	size_t len;
3965 	struct sadb_x_nat_t_port *p;
3966 
3967 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3968 
3969 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3970 	if (m == NULL)
3971 		return (NULL);
3972 	m_align(m, len);
3973 	m->m_len = len;
3974 	p = mtod(m, struct sadb_x_nat_t_port *);
3975 
3976 	bzero(p, len);
3977 	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3978 	p->sadb_x_nat_t_port_exttype = type;
3979 	p->sadb_x_nat_t_port_port = port;
3980 
3981 	return (m);
3982 }
3983 
3984 /*
3985  * Get port from sockaddr. Port is in network byte order.
3986  */
3987 uint16_t
key_portfromsaddr(struct sockaddr * sa)3988 key_portfromsaddr(struct sockaddr *sa)
3989 {
3990 
3991 	switch (sa->sa_family) {
3992 #ifdef INET
3993 	case AF_INET:
3994 		return ((struct sockaddr_in *)sa)->sin_port;
3995 #endif
3996 #ifdef INET6
3997 	case AF_INET6:
3998 		return ((struct sockaddr_in6 *)sa)->sin6_port;
3999 #endif
4000 	}
4001 	return (0);
4002 }
4003 
4004 /*
4005  * Set port in struct sockaddr. Port is in network byte order.
4006  */
4007 void
key_porttosaddr(struct sockaddr * sa,uint16_t port)4008 key_porttosaddr(struct sockaddr *sa, uint16_t port)
4009 {
4010 
4011 	switch (sa->sa_family) {
4012 #ifdef INET
4013 	case AF_INET:
4014 		((struct sockaddr_in *)sa)->sin_port = port;
4015 		break;
4016 #endif
4017 #ifdef INET6
4018 	case AF_INET6:
4019 		((struct sockaddr_in6 *)sa)->sin6_port = port;
4020 		break;
4021 #endif
4022 	default:
4023 		ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
4024 			__func__, sa->sa_family));
4025 		break;
4026 	}
4027 }
4028 
4029 /*
4030  * set data into sadb_x_policy
4031  */
4032 static struct mbuf *
key_setsadbxpolicy(u_int16_t type,u_int8_t dir,u_int32_t id,u_int32_t priority)4033 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id, u_int32_t priority)
4034 {
4035 	struct mbuf *m;
4036 	struct sadb_x_policy *p;
4037 	size_t len;
4038 
4039 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
4040 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
4041 	if (m == NULL)
4042 		return (NULL);
4043 	m_align(m, len);
4044 	m->m_len = len;
4045 	p = mtod(m, struct sadb_x_policy *);
4046 
4047 	bzero(p, len);
4048 	p->sadb_x_policy_len = PFKEY_UNIT64(len);
4049 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
4050 	p->sadb_x_policy_type = type;
4051 	p->sadb_x_policy_dir = dir;
4052 	p->sadb_x_policy_id = id;
4053 	p->sadb_x_policy_priority = priority;
4054 
4055 	return m;
4056 }
4057 
4058 /* %%% utilities */
4059 /* Take a key message (sadb_key) from the socket and turn it into one
4060  * of the kernel's key structures (seckey).
4061  *
4062  * IN: pointer to the src
4063  * OUT: NULL no more memory
4064  */
4065 struct seckey *
key_dup_keymsg(const struct sadb_key * src,struct malloc_type * type)4066 key_dup_keymsg(const struct sadb_key *src, struct malloc_type *type)
4067 {
4068 	struct seckey *dst;
4069 	size_t len;
4070 
4071 	dst = malloc(sizeof(*dst), type, M_NOWAIT);
4072 	if (dst != NULL) {
4073 		len = src->sadb_key_bits >> 3;
4074 		dst->bits = src->sadb_key_bits;
4075 		dst->key_data = malloc(len, type, M_NOWAIT);
4076 		if (dst->key_data != NULL) {
4077 			bcopy((const char *)(src + 1), dst->key_data, len);
4078 		} else {
4079 			ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4080 			    __func__));
4081 			free(dst, type);
4082 			dst = NULL;
4083 		}
4084 	} else {
4085 		ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4086 		    __func__));
4087 	}
4088 	return (dst);
4089 }
4090 
4091 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
4092  * turn it into one of the kernel's lifetime structures (seclifetime).
4093  *
4094  * IN: pointer to the destination, source and malloc type
4095  * OUT: NULL, no more memory
4096  */
4097 
4098 static struct seclifetime *
key_dup_lifemsg(const struct sadb_lifetime * src,struct malloc_type * type)4099 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
4100 {
4101 	struct seclifetime *dst;
4102 
4103 	dst = malloc(sizeof(*dst), type, M_NOWAIT);
4104 	if (dst == NULL) {
4105 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4106 		return (NULL);
4107 	}
4108 	dst->allocations = src->sadb_lifetime_allocations;
4109 	dst->bytes = src->sadb_lifetime_bytes;
4110 	dst->addtime = src->sadb_lifetime_addtime;
4111 	dst->usetime = src->sadb_lifetime_usetime;
4112 	return (dst);
4113 }
4114 
4115 /*
4116  * compare two secasindex structure.
4117  * flag can specify to compare 2 saidxes.
4118  * compare two secasindex structure without both mode and reqid.
4119  * don't compare port.
4120  * IN:
4121  *      saidx0: source, it can be in SAD.
4122  *      saidx1: object.
4123  * OUT:
4124  *      1 : equal
4125  *      0 : not equal
4126  */
4127 static int
key_cmpsaidx(const struct secasindex * saidx0,const struct secasindex * saidx1,int flag)4128 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
4129     int flag)
4130 {
4131 
4132 	/* sanity */
4133 	if (saidx0 == NULL && saidx1 == NULL)
4134 		return 1;
4135 
4136 	if (saidx0 == NULL || saidx1 == NULL)
4137 		return 0;
4138 
4139 	if (saidx0->proto != saidx1->proto)
4140 		return 0;
4141 
4142 	if (flag == CMP_EXACTLY) {
4143 		if (saidx0->mode != saidx1->mode)
4144 			return 0;
4145 		if (saidx0->reqid != saidx1->reqid)
4146 			return 0;
4147 		if (bcmp(&saidx0->src, &saidx1->src,
4148 		    saidx0->src.sa.sa_len) != 0 ||
4149 		    bcmp(&saidx0->dst, &saidx1->dst,
4150 		    saidx0->dst.sa.sa_len) != 0)
4151 			return 0;
4152 	} else {
4153 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4154 		if (flag == CMP_MODE_REQID || flag == CMP_REQID) {
4155 			/*
4156 			 * If reqid of SPD is non-zero, unique SA is required.
4157 			 * The result must be of same reqid in this case.
4158 			 */
4159 			if (saidx1->reqid != 0 &&
4160 			    saidx0->reqid != saidx1->reqid)
4161 				return 0;
4162 		}
4163 
4164 		if (flag == CMP_MODE_REQID) {
4165 			if (saidx0->mode != IPSEC_MODE_ANY
4166 			 && saidx0->mode != saidx1->mode)
4167 				return 0;
4168 		}
4169 
4170 		if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0)
4171 			return 0;
4172 		if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0)
4173 			return 0;
4174 	}
4175 
4176 	return 1;
4177 }
4178 
4179 /*
4180  * compare two secindex structure exactly.
4181  * IN:
4182  *	spidx0: source, it is often in SPD.
4183  *	spidx1: object, it is often from PFKEY message.
4184  * OUT:
4185  *	1 : equal
4186  *	0 : not equal
4187  */
4188 static int
key_cmpspidx_exactly(struct secpolicyindex * spidx0,struct secpolicyindex * spidx1)4189 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
4190     struct secpolicyindex *spidx1)
4191 {
4192 	/* sanity */
4193 	if (spidx0 == NULL && spidx1 == NULL)
4194 		return 1;
4195 
4196 	if (spidx0 == NULL || spidx1 == NULL)
4197 		return 0;
4198 
4199 	if (spidx0->prefs != spidx1->prefs
4200 	 || spidx0->prefd != spidx1->prefd
4201 	 || spidx0->ul_proto != spidx1->ul_proto
4202 	 || spidx0->dir != spidx1->dir)
4203 		return 0;
4204 
4205 	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4206 	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4207 }
4208 
4209 /*
4210  * compare two secindex structure with mask.
4211  * IN:
4212  *	spidx0: source, it is often in SPD.
4213  *	spidx1: object, it is often from IP header.
4214  * OUT:
4215  *	1 : equal
4216  *	0 : not equal
4217  */
4218 static int
key_cmpspidx_withmask(struct secpolicyindex * spidx0,struct secpolicyindex * spidx1)4219 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
4220     struct secpolicyindex *spidx1)
4221 {
4222 	/* sanity */
4223 	if (spidx0 == NULL && spidx1 == NULL)
4224 		return 1;
4225 
4226 	if (spidx0 == NULL || spidx1 == NULL)
4227 		return 0;
4228 
4229 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4230 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4231 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4232 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4233 		return 0;
4234 
4235 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4236 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4237 	 && spidx0->ul_proto != spidx1->ul_proto)
4238 		return 0;
4239 
4240 	switch (spidx0->src.sa.sa_family) {
4241 	case AF_INET:
4242 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4243 		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4244 			return 0;
4245 		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4246 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
4247 			return 0;
4248 		break;
4249 	case AF_INET6:
4250 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4251 		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4252 			return 0;
4253 		/*
4254 		 * scope_id check. if sin6_scope_id is 0, we regard it
4255 		 * as a wildcard scope, which matches any scope zone ID.
4256 		 */
4257 		if (spidx0->src.sin6.sin6_scope_id &&
4258 		    spidx1->src.sin6.sin6_scope_id &&
4259 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4260 			return 0;
4261 		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4262 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4263 			return 0;
4264 		break;
4265 	default:
4266 		/* XXX */
4267 		if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4268 			return 0;
4269 		break;
4270 	}
4271 
4272 	switch (spidx0->dst.sa.sa_family) {
4273 	case AF_INET:
4274 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4275 		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4276 			return 0;
4277 		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4278 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
4279 			return 0;
4280 		break;
4281 	case AF_INET6:
4282 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4283 		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4284 			return 0;
4285 		/*
4286 		 * scope_id check. if sin6_scope_id is 0, we regard it
4287 		 * as a wildcard scope, which matches any scope zone ID.
4288 		 */
4289 		if (spidx0->dst.sin6.sin6_scope_id &&
4290 		    spidx1->dst.sin6.sin6_scope_id &&
4291 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4292 			return 0;
4293 		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4294 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4295 			return 0;
4296 		break;
4297 	default:
4298 		/* XXX */
4299 		if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4300 			return 0;
4301 		break;
4302 	}
4303 
4304 	/* XXX Do we check other field ?  e.g. flowinfo */
4305 
4306 	return 1;
4307 }
4308 
4309 #ifdef satosin
4310 #undef satosin
4311 #endif
4312 #define satosin(s) ((const struct sockaddr_in *)s)
4313 #ifdef satosin6
4314 #undef satosin6
4315 #endif
4316 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4317 /* returns 0 on match */
4318 int
key_sockaddrcmp(const struct sockaddr * sa1,const struct sockaddr * sa2,int port)4319 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4320     int port)
4321 {
4322 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4323 		return 1;
4324 
4325 	switch (sa1->sa_family) {
4326 #ifdef INET
4327 	case AF_INET:
4328 		if (sa1->sa_len != sizeof(struct sockaddr_in))
4329 			return 1;
4330 		if (satosin(sa1)->sin_addr.s_addr !=
4331 		    satosin(sa2)->sin_addr.s_addr) {
4332 			return 1;
4333 		}
4334 		if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4335 			return 1;
4336 		break;
4337 #endif
4338 #ifdef INET6
4339 	case AF_INET6:
4340 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
4341 			return 1;	/*EINVAL*/
4342 		if (satosin6(sa1)->sin6_scope_id !=
4343 		    satosin6(sa2)->sin6_scope_id) {
4344 			return 1;
4345 		}
4346 		if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4347 		    &satosin6(sa2)->sin6_addr)) {
4348 			return 1;
4349 		}
4350 		if (port &&
4351 		    satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4352 			return 1;
4353 		}
4354 		break;
4355 #endif
4356 	default:
4357 		if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4358 			return 1;
4359 		break;
4360 	}
4361 
4362 	return 0;
4363 }
4364 
4365 /* returns 0 on match */
4366 int
key_sockaddrcmp_withmask(const struct sockaddr * sa1,const struct sockaddr * sa2,size_t mask)4367 key_sockaddrcmp_withmask(const struct sockaddr *sa1,
4368     const struct sockaddr *sa2, size_t mask)
4369 {
4370 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4371 		return (1);
4372 
4373 	switch (sa1->sa_family) {
4374 #ifdef INET
4375 	case AF_INET:
4376 		return (!key_bbcmp(&satosin(sa1)->sin_addr,
4377 		    &satosin(sa2)->sin_addr, mask));
4378 #endif
4379 #ifdef INET6
4380 	case AF_INET6:
4381 		if (satosin6(sa1)->sin6_scope_id !=
4382 		    satosin6(sa2)->sin6_scope_id)
4383 			return (1);
4384 		return (!key_bbcmp(&satosin6(sa1)->sin6_addr,
4385 		    &satosin6(sa2)->sin6_addr, mask));
4386 #endif
4387 	}
4388 	return (1);
4389 }
4390 #undef satosin
4391 #undef satosin6
4392 
4393 /*
4394  * compare two buffers with mask.
4395  * IN:
4396  *	addr1: source
4397  *	addr2: object
4398  *	bits:  Number of bits to compare
4399  * OUT:
4400  *	1 : equal
4401  *	0 : not equal
4402  */
4403 static int
key_bbcmp(const void * a1,const void * a2,u_int bits)4404 key_bbcmp(const void *a1, const void *a2, u_int bits)
4405 {
4406 	const unsigned char *p1 = a1;
4407 	const unsigned char *p2 = a2;
4408 
4409 	/* XXX: This could be considerably faster if we compare a word
4410 	 * at a time, but it is complicated on LSB Endian machines */
4411 
4412 	/* Handle null pointers */
4413 	if (p1 == NULL || p2 == NULL)
4414 		return (p1 == p2);
4415 
4416 	while (bits >= 8) {
4417 		if (*p1++ != *p2++)
4418 			return 0;
4419 		bits -= 8;
4420 	}
4421 
4422 	if (bits > 0) {
4423 		u_int8_t mask = ~((1<<(8-bits))-1);
4424 		if ((*p1 & mask) != (*p2 & mask))
4425 			return 0;
4426 	}
4427 	return 1;	/* Match! */
4428 }
4429 
4430 static void
key_flush_spd(time_t now)4431 key_flush_spd(time_t now)
4432 {
4433 	SPTREE_RLOCK_TRACKER;
4434 	struct secpolicy_list drainq;
4435 	struct secpolicy *sp, *nextsp;
4436 	u_int dir;
4437 
4438 	LIST_INIT(&drainq);
4439 	SPTREE_RLOCK();
4440 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4441 		TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4442 			if (sp->lifetime == 0 && sp->validtime == 0)
4443 				continue;
4444 			if ((sp->lifetime &&
4445 			    now - sp->created > sp->lifetime) ||
4446 			    (sp->validtime &&
4447 			    now - sp->lastused > sp->validtime)) {
4448 				/* Hold extra reference to send SPDEXPIRE */
4449 				SP_ADDREF(sp);
4450 				LIST_INSERT_HEAD(&drainq, sp, drainq);
4451 			}
4452 		}
4453 	}
4454 	SPTREE_RUNLOCK();
4455 	if (LIST_EMPTY(&drainq))
4456 		return;
4457 
4458 	SPTREE_WLOCK();
4459 	sp = LIST_FIRST(&drainq);
4460 	while (sp != NULL) {
4461 		nextsp = LIST_NEXT(sp, drainq);
4462 		/* Check that SP is still linked */
4463 		if (sp->state != IPSEC_SPSTATE_ALIVE) {
4464 			LIST_REMOVE(sp, drainq);
4465 			key_freesp(&sp); /* release extra reference */
4466 			sp = nextsp;
4467 			continue;
4468 		}
4469 		TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
4470 		V_spd_size--;
4471 		LIST_REMOVE(sp, idhash);
4472 		sp->state = IPSEC_SPSTATE_DEAD;
4473 		sp = nextsp;
4474 	}
4475 	V_sp_genid++;
4476 	SPTREE_WUNLOCK();
4477 	if (SPDCACHE_ENABLED())
4478 		spdcache_clear();
4479 
4480 	sp = LIST_FIRST(&drainq);
4481 	while (sp != NULL) {
4482 		nextsp = LIST_NEXT(sp, drainq);
4483 		key_spdexpire(sp);
4484 		key_freesp(&sp); /* release extra reference */
4485 		key_freesp(&sp); /* release last reference */
4486 		sp = nextsp;
4487 	}
4488 }
4489 
4490 static void
key_flush_sad(time_t now)4491 key_flush_sad(time_t now)
4492 {
4493 	SAHTREE_RLOCK_TRACKER;
4494 	struct secashead_list emptyq;
4495 	struct secasvar_list drainq, hexpireq, sexpireq, freeq;
4496 	struct secashead *sah, *nextsah;
4497 	struct secasvar *sav, *nextsav;
4498 
4499 	SECASVAR_RLOCK_TRACKER;
4500 
4501 	LIST_INIT(&drainq);
4502 	LIST_INIT(&hexpireq);
4503 	LIST_INIT(&sexpireq);
4504 	LIST_INIT(&emptyq);
4505 
4506 	SAHTREE_RLOCK();
4507 	TAILQ_FOREACH(sah, &V_sahtree, chain) {
4508 		/* Check for empty SAH */
4509 		if (TAILQ_EMPTY(&sah->savtree_larval) &&
4510 		    TAILQ_EMPTY(&sah->savtree_alive)) {
4511 			SAH_ADDREF(sah);
4512 			LIST_INSERT_HEAD(&emptyq, sah, drainq);
4513 			continue;
4514 		}
4515 		/* Add all stale LARVAL SAs into drainq */
4516 		TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
4517 			if (now - sav->created < V_key_larval_lifetime)
4518 				continue;
4519 			SAV_ADDREF(sav);
4520 			LIST_INSERT_HEAD(&drainq, sav, drainq);
4521 		}
4522 		TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
4523 			/* lifetimes aren't specified */
4524 			if (sav->lft_h == NULL)
4525 				continue;
4526 			SECASVAR_RLOCK(sav);
4527 			/*
4528 			 * Check again with lock held, because it may
4529 			 * be updated by SADB_UPDATE.
4530 			 */
4531 			if (sav->lft_h == NULL) {
4532 				SECASVAR_RUNLOCK(sav);
4533 				continue;
4534 			}
4535 			/*
4536 			 * RFC 2367:
4537 			 * HARD lifetimes MUST take precedence over SOFT
4538 			 * lifetimes, meaning if the HARD and SOFT lifetimes
4539 			 * are the same, the HARD lifetime will appear on the
4540 			 * EXPIRE message.
4541 			 */
4542 			/* check HARD lifetime */
4543 			if ((sav->lft_h->addtime != 0 &&
4544 			    now - sav->created > sav->lft_h->addtime) ||
4545 			    (sav->lft_h->usetime != 0 && sav->firstused &&
4546 			    now - sav->firstused > sav->lft_h->usetime) ||
4547 			    (sav->lft_h->bytes != 0 && counter_u64_fetch(
4548 			        sav->lft_c_bytes) > sav->lft_h->bytes)) {
4549 				SECASVAR_RUNLOCK(sav);
4550 				SAV_ADDREF(sav);
4551 				LIST_INSERT_HEAD(&hexpireq, sav, drainq);
4552 				continue;
4553 			}
4554 			/* check SOFT lifetime (only for MATURE SAs) */
4555 			if (sav->state == SADB_SASTATE_MATURE && (
4556 			    (sav->lft_s->addtime != 0 &&
4557 			    now - sav->created > sav->lft_s->addtime) ||
4558 			    (sav->lft_s->usetime != 0 && sav->firstused &&
4559 			    now - sav->firstused > sav->lft_s->usetime) ||
4560 			    (sav->lft_s->bytes != 0 && counter_u64_fetch(
4561 				sav->lft_c_bytes) > sav->lft_s->bytes) ||
4562 			    (!(sav->flags & SADB_X_SAFLAGS_ESN) &&
4563 			    (sav->replay != NULL) && (
4564 			    (sav->replay->count > UINT32_80PCT) ||
4565 			    (sav->replay->last > UINT32_80PCT))))) {
4566 				SECASVAR_RUNLOCK(sav);
4567 				SAV_ADDREF(sav);
4568 				LIST_INSERT_HEAD(&sexpireq, sav, drainq);
4569 				continue;
4570 			}
4571 			SECASVAR_RUNLOCK(sav);
4572 		}
4573 	}
4574 	SAHTREE_RUNLOCK();
4575 
4576 	if (LIST_EMPTY(&emptyq) && LIST_EMPTY(&drainq) &&
4577 	    LIST_EMPTY(&hexpireq) && LIST_EMPTY(&sexpireq))
4578 		return;
4579 
4580 	LIST_INIT(&freeq);
4581 	SAHTREE_WLOCK();
4582 	/* Unlink stale LARVAL SAs */
4583 	sav = LIST_FIRST(&drainq);
4584 	while (sav != NULL) {
4585 		nextsav = LIST_NEXT(sav, drainq);
4586 		/* Check that SA is still LARVAL */
4587 		if (sav->state != SADB_SASTATE_LARVAL) {
4588 			LIST_REMOVE(sav, drainq);
4589 			LIST_INSERT_HEAD(&freeq, sav, drainq);
4590 			sav = nextsav;
4591 			continue;
4592 		}
4593 		TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
4594 		LIST_REMOVE(sav, spihash);
4595 		sav->state = SADB_SASTATE_DEAD;
4596 		sav = nextsav;
4597 	}
4598 	/* Unlink all SAs with expired HARD lifetime */
4599 	sav = LIST_FIRST(&hexpireq);
4600 	while (sav != NULL) {
4601 		nextsav = LIST_NEXT(sav, drainq);
4602 		/* Check that SA is not unlinked */
4603 		if (sav->state == SADB_SASTATE_DEAD) {
4604 			LIST_REMOVE(sav, drainq);
4605 			LIST_INSERT_HEAD(&freeq, sav, drainq);
4606 			sav = nextsav;
4607 			continue;
4608 		}
4609 		TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
4610 		LIST_REMOVE(sav, spihash);
4611 		sav->state = SADB_SASTATE_DEAD;
4612 		sav = nextsav;
4613 	}
4614 	/* Mark all SAs with expired SOFT lifetime as DYING */
4615 	sav = LIST_FIRST(&sexpireq);
4616 	while (sav != NULL) {
4617 		nextsav = LIST_NEXT(sav, drainq);
4618 		/* Check that SA is not unlinked */
4619 		if (sav->state == SADB_SASTATE_DEAD) {
4620 			LIST_REMOVE(sav, drainq);
4621 			LIST_INSERT_HEAD(&freeq, sav, drainq);
4622 			sav = nextsav;
4623 			continue;
4624 		}
4625 		/*
4626 		 * NOTE: this doesn't change SA order in the chain.
4627 		 */
4628 		sav->state = SADB_SASTATE_DYING;
4629 		sav = nextsav;
4630 	}
4631 	/* Unlink empty SAHs */
4632 	sah = LIST_FIRST(&emptyq);
4633 	while (sah != NULL) {
4634 		nextsah = LIST_NEXT(sah, drainq);
4635 		/* Check that SAH is still empty and not unlinked */
4636 		if (sah->state == SADB_SASTATE_DEAD ||
4637 		    !TAILQ_EMPTY(&sah->savtree_larval) ||
4638 		    !TAILQ_EMPTY(&sah->savtree_alive)) {
4639 			LIST_REMOVE(sah, drainq);
4640 			key_freesah(&sah); /* release extra reference */
4641 			sah = nextsah;
4642 			continue;
4643 		}
4644 		TAILQ_REMOVE(&V_sahtree, sah, chain);
4645 		LIST_REMOVE(sah, addrhash);
4646 		sah->state = SADB_SASTATE_DEAD;
4647 		sah = nextsah;
4648 	}
4649 	SAHTREE_WUNLOCK();
4650 
4651 	/* Send SPDEXPIRE messages */
4652 	sav = LIST_FIRST(&hexpireq);
4653 	while (sav != NULL) {
4654 		nextsav = LIST_NEXT(sav, drainq);
4655 		key_expire(sav, 1);
4656 		key_freesah(&sav->sah); /* release reference from SAV */
4657 		key_freesav(&sav); /* release extra reference */
4658 		key_freesav(&sav); /* release last reference */
4659 		sav = nextsav;
4660 	}
4661 	sav = LIST_FIRST(&sexpireq);
4662 	while (sav != NULL) {
4663 		nextsav = LIST_NEXT(sav, drainq);
4664 		key_expire(sav, 0);
4665 		key_freesav(&sav); /* release extra reference */
4666 		sav = nextsav;
4667 	}
4668 	/* Free stale LARVAL SAs */
4669 	sav = LIST_FIRST(&drainq);
4670 	while (sav != NULL) {
4671 		nextsav = LIST_NEXT(sav, drainq);
4672 		key_freesah(&sav->sah); /* release reference from SAV */
4673 		key_freesav(&sav); /* release extra reference */
4674 		key_freesav(&sav); /* release last reference */
4675 		sav = nextsav;
4676 	}
4677 	/* Free SAs that were unlinked/changed by someone else */
4678 	sav = LIST_FIRST(&freeq);
4679 	while (sav != NULL) {
4680 		nextsav = LIST_NEXT(sav, drainq);
4681 		key_freesav(&sav); /* release extra reference */
4682 		sav = nextsav;
4683 	}
4684 	/* Free empty SAH */
4685 	sah = LIST_FIRST(&emptyq);
4686 	while (sah != NULL) {
4687 		nextsah = LIST_NEXT(sah, drainq);
4688 		key_freesah(&sah); /* release extra reference */
4689 		key_freesah(&sah); /* release last reference */
4690 		sah = nextsah;
4691 	}
4692 }
4693 
4694 static void
key_flush_acq(time_t now)4695 key_flush_acq(time_t now)
4696 {
4697 	struct secacq *acq, *nextacq;
4698 
4699 	/* ACQ tree */
4700 	ACQ_LOCK();
4701 	acq = LIST_FIRST(&V_acqtree);
4702 	while (acq != NULL) {
4703 		nextacq = LIST_NEXT(acq, chain);
4704 		if (now - acq->created > V_key_blockacq_lifetime) {
4705 			LIST_REMOVE(acq, chain);
4706 			LIST_REMOVE(acq, addrhash);
4707 			LIST_REMOVE(acq, seqhash);
4708 			free(acq, M_IPSEC_SAQ);
4709 		}
4710 		acq = nextacq;
4711 	}
4712 	ACQ_UNLOCK();
4713 }
4714 
4715 static void
key_flush_spacq(time_t now)4716 key_flush_spacq(time_t now)
4717 {
4718 	struct secspacq *acq, *nextacq;
4719 
4720 	/* SP ACQ tree */
4721 	SPACQ_LOCK();
4722 	for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4723 		nextacq = LIST_NEXT(acq, chain);
4724 		if (now - acq->created > V_key_blockacq_lifetime
4725 		 && __LIST_CHAINED(acq)) {
4726 			LIST_REMOVE(acq, chain);
4727 			free(acq, M_IPSEC_SAQ);
4728 		}
4729 	}
4730 	SPACQ_UNLOCK();
4731 }
4732 
4733 /*
4734  * time handler.
4735  * scanning SPD and SAD to check status for each entries,
4736  * and do to remove or to expire.
4737  * XXX: year 2038 problem may remain.
4738  */
4739 static void
key_timehandler(void * arg)4740 key_timehandler(void *arg)
4741 {
4742 	VNET_ITERATOR_DECL(vnet_iter);
4743 	time_t now = time_second;
4744 
4745 	VNET_LIST_RLOCK_NOSLEEP();
4746 	VNET_FOREACH(vnet_iter) {
4747 		CURVNET_SET(vnet_iter);
4748 		key_flush_spd(now);
4749 		key_flush_sad(now);
4750 		key_flush_acq(now);
4751 		key_flush_spacq(now);
4752 		CURVNET_RESTORE();
4753 	}
4754 	VNET_LIST_RUNLOCK_NOSLEEP();
4755 
4756 #ifndef IPSEC_DEBUG2
4757 	/* do exchange to tick time !! */
4758 	callout_schedule(&key_timer, hz);
4759 #endif /* IPSEC_DEBUG2 */
4760 }
4761 
4762 u_long
key_random(void)4763 key_random(void)
4764 {
4765 	u_long value;
4766 
4767 	arc4random_buf(&value, sizeof(value));
4768 	return value;
4769 }
4770 
4771 /*
4772  * map SADB_SATYPE_* to IPPROTO_*.
4773  * if satype == SADB_SATYPE then satype is mapped to ~0.
4774  * OUT:
4775  *	0: invalid satype.
4776  */
4777 static uint8_t
key_satype2proto(uint8_t satype)4778 key_satype2proto(uint8_t satype)
4779 {
4780 	switch (satype) {
4781 	case SADB_SATYPE_UNSPEC:
4782 		return IPSEC_PROTO_ANY;
4783 	case SADB_SATYPE_AH:
4784 		return IPPROTO_AH;
4785 	case SADB_SATYPE_ESP:
4786 		return IPPROTO_ESP;
4787 	case SADB_X_SATYPE_IPCOMP:
4788 		return IPPROTO_IPCOMP;
4789 	case SADB_X_SATYPE_TCPSIGNATURE:
4790 		return IPPROTO_TCP;
4791 	default:
4792 		return 0;
4793 	}
4794 	/* NOTREACHED */
4795 }
4796 
4797 /*
4798  * map IPPROTO_* to SADB_SATYPE_*
4799  * OUT:
4800  *	0: invalid protocol type.
4801  */
4802 static uint8_t
key_proto2satype(uint8_t proto)4803 key_proto2satype(uint8_t proto)
4804 {
4805 	switch (proto) {
4806 	case IPPROTO_AH:
4807 		return SADB_SATYPE_AH;
4808 	case IPPROTO_ESP:
4809 		return SADB_SATYPE_ESP;
4810 	case IPPROTO_IPCOMP:
4811 		return SADB_X_SATYPE_IPCOMP;
4812 	case IPPROTO_TCP:
4813 		return SADB_X_SATYPE_TCPSIGNATURE;
4814 	default:
4815 		return 0;
4816 	}
4817 	/* NOTREACHED */
4818 }
4819 
4820 /* %%% PF_KEY */
4821 /*
4822  * SADB_GETSPI processing is to receive
4823  *	<base, (SA2), src address, dst address, (SPI range)>
4824  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4825  * tree with the status of LARVAL, and send
4826  *	<base, SA(*), address(SD)>
4827  * to the IKMPd.
4828  *
4829  * IN:	mhp: pointer to the pointer to each header.
4830  * OUT:	NULL if fail.
4831  *	other if success, return pointer to the message to send.
4832  */
4833 static int
key_getspi(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)4834 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4835 {
4836 	struct secasindex saidx;
4837 	struct sadb_address *src0, *dst0;
4838 	struct secasvar *sav;
4839 	uint32_t reqid, spi;
4840 	int error;
4841 	uint8_t mode, proto;
4842 
4843 	IPSEC_ASSERT(so != NULL, ("null socket"));
4844 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
4845 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4846 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4847 
4848 	if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
4849 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)
4850 #ifdef PFKEY_STRICT_CHECKS
4851 	    || SADB_CHECKHDR(mhp, SADB_EXT_SPIRANGE)
4852 #endif
4853 	    ) {
4854 		ipseclog((LOG_DEBUG,
4855 		    "%s: invalid message: missing required header.\n",
4856 		    __func__));
4857 		error = EINVAL;
4858 		goto fail;
4859 	}
4860 	if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
4861 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)
4862 #ifdef PFKEY_STRICT_CHECKS
4863 	    || SADB_CHECKLEN(mhp, SADB_EXT_SPIRANGE)
4864 #endif
4865 	    ) {
4866 		ipseclog((LOG_DEBUG,
4867 		    "%s: invalid message: wrong header size.\n", __func__));
4868 		error = EINVAL;
4869 		goto fail;
4870 	}
4871 	if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
4872 		mode = IPSEC_MODE_ANY;
4873 		reqid = 0;
4874 	} else {
4875 		if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
4876 			ipseclog((LOG_DEBUG,
4877 			    "%s: invalid message: wrong header size.\n",
4878 			    __func__));
4879 			error = EINVAL;
4880 			goto fail;
4881 		}
4882 		mode = ((struct sadb_x_sa2 *)
4883 		    mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4884 		reqid = ((struct sadb_x_sa2 *)
4885 		    mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4886 	}
4887 
4888 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4889 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4890 
4891 	/* map satype to proto */
4892 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4893 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4894 			__func__));
4895 		error = EINVAL;
4896 		goto fail;
4897 	}
4898 	error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
4899 	    (struct sockaddr *)(dst0 + 1));
4900 	if (error != 0) {
4901 		ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
4902 		error = EINVAL;
4903 		goto fail;
4904 	}
4905 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4906 
4907 	/* SPI allocation */
4908 	spi = key_do_getnewspi(
4909 	    (struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE], &saidx);
4910 	if (spi == 0) {
4911 		/*
4912 		 * Requested SPI or SPI range is not available or
4913 		 * already used.
4914 		 */
4915 		error = EEXIST;
4916 		goto fail;
4917 	}
4918 	sav = key_newsav(mhp, &saidx, spi, &error);
4919 	if (sav == NULL)
4920 		goto fail;
4921 
4922 	if (sav->seq != 0) {
4923 		/*
4924 		 * RFC2367:
4925 		 * If the SADB_GETSPI message is in response to a
4926 		 * kernel-generated SADB_ACQUIRE, the sadb_msg_seq
4927 		 * MUST be the same as the SADB_ACQUIRE message.
4928 		 *
4929 		 * XXXAE: However it doesn't definethe behaviour how to
4930 		 * check this and what to do if it doesn't match.
4931 		 * Also what we should do if it matches?
4932 		 *
4933 		 * We can compare saidx used in SADB_ACQUIRE with saidx
4934 		 * used in SADB_GETSPI, but this probably can break
4935 		 * existing software. For now just warn if it doesn't match.
4936 		 *
4937 		 * XXXAE: anyway it looks useless.
4938 		 */
4939 		key_acqdone(&saidx, sav->seq);
4940 	}
4941 	KEYDBG(KEY_STAMP,
4942 	    printf("%s: SA(%p)\n", __func__, sav));
4943 	KEYDBG(KEY_DATA, kdebug_secasv(sav));
4944 
4945     {
4946 	struct mbuf *n, *nn;
4947 	struct sadb_sa *m_sa;
4948 	struct sadb_msg *newmsg;
4949 	int off, len;
4950 
4951 	/* create new sadb_msg to reply. */
4952 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4953 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
4954 
4955 	n = key_mget(len);
4956 	if (n == NULL) {
4957 		error = ENOBUFS;
4958 		goto fail;
4959 	}
4960 
4961 	n->m_len = len;
4962 	n->m_next = NULL;
4963 	off = 0;
4964 
4965 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4966 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4967 
4968 	m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4969 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4970 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
4971 	m_sa->sadb_sa_spi = spi; /* SPI is already in network byte order */
4972 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4973 
4974 	IPSEC_ASSERT(off == len,
4975 		("length inconsistency (off %u len %u)", off, len));
4976 
4977 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4978 	    SADB_EXT_ADDRESS_DST);
4979 	if (!n->m_next) {
4980 		m_freem(n);
4981 		error = ENOBUFS;
4982 		goto fail;
4983 	}
4984 
4985 	if (n->m_len < sizeof(struct sadb_msg)) {
4986 		n = m_pullup(n, sizeof(struct sadb_msg));
4987 		if (n == NULL)
4988 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4989 	}
4990 
4991 	n->m_pkthdr.len = 0;
4992 	for (nn = n; nn; nn = nn->m_next)
4993 		n->m_pkthdr.len += nn->m_len;
4994 
4995 	newmsg = mtod(n, struct sadb_msg *);
4996 	newmsg->sadb_msg_seq = sav->seq;
4997 	newmsg->sadb_msg_errno = 0;
4998 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4999 
5000 	m_freem(m);
5001 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5002     }
5003 
5004 fail:
5005 	return (key_senderror(so, m, error));
5006 }
5007 
5008 /*
5009  * allocating new SPI
5010  * called by key_getspi().
5011  * OUT:
5012  *	0:	failure.
5013  *	others: success, SPI in network byte order.
5014  */
5015 static uint32_t
key_do_getnewspi(struct sadb_spirange * spirange,struct secasindex * saidx)5016 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
5017 {
5018 	uint32_t min, max, newspi, t;
5019 	int count = V_key_spi_trycnt;
5020 
5021 	/* set spi range to allocate */
5022 	if (spirange != NULL) {
5023 		min = spirange->sadb_spirange_min;
5024 		max = spirange->sadb_spirange_max;
5025 	} else {
5026 		min = V_key_spi_minval;
5027 		max = V_key_spi_maxval;
5028 	}
5029 	/* IPCOMP needs 2-byte SPI */
5030 	if (saidx->proto == IPPROTO_IPCOMP) {
5031 		if (min >= 0x10000)
5032 			min = 0xffff;
5033 		if (max >= 0x10000)
5034 			max = 0xffff;
5035 		if (min > max) {
5036 			t = min; min = max; max = t;
5037 		}
5038 	}
5039 
5040 	if (min == max) {
5041 		if (key_checkspidup(htonl(min))) {
5042 			ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
5043 			    __func__, min));
5044 			return 0;
5045 		}
5046 
5047 		count--; /* taking one cost. */
5048 		newspi = min;
5049 	} else {
5050 		/* init SPI */
5051 		newspi = 0;
5052 
5053 		/* when requesting to allocate spi ranged */
5054 		while (count--) {
5055 			/* generate pseudo-random SPI value ranged. */
5056 			newspi = min + (key_random() % (max - min + 1));
5057 			if (!key_checkspidup(htonl(newspi)))
5058 				break;
5059 		}
5060 
5061 		if (count == 0 || newspi == 0) {
5062 			ipseclog((LOG_DEBUG,
5063 			    "%s: failed to allocate SPI.\n", __func__));
5064 			return 0;
5065 		}
5066 	}
5067 
5068 	/* statistics */
5069 	keystat.getspi_count =
5070 	    (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
5071 
5072 	return (htonl(newspi));
5073 }
5074 
5075 /*
5076  * Find TCP-MD5 SA with corresponding secasindex.
5077  * If not found, return NULL and fill SPI with usable value if needed.
5078  */
5079 static struct secasvar *
key_getsav_tcpmd5(struct secasindex * saidx,uint32_t * spi)5080 key_getsav_tcpmd5(struct secasindex *saidx, uint32_t *spi)
5081 {
5082 	SAHTREE_RLOCK_TRACKER;
5083 	struct secashead *sah;
5084 	struct secasvar *sav;
5085 
5086 	IPSEC_ASSERT(saidx->proto == IPPROTO_TCP, ("wrong proto"));
5087 	SAHTREE_RLOCK();
5088 	LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
5089 		if (sah->saidx.proto != IPPROTO_TCP)
5090 			continue;
5091 		if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
5092 		    !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
5093 			break;
5094 	}
5095 	if (sah != NULL) {
5096 		if (V_key_preferred_oldsa)
5097 			sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
5098 		else
5099 			sav = TAILQ_FIRST(&sah->savtree_alive);
5100 		if (sav != NULL) {
5101 			SAV_ADDREF(sav);
5102 			SAHTREE_RUNLOCK();
5103 			return (sav);
5104 		}
5105 	}
5106 	if (spi == NULL) {
5107 		/* No SPI required */
5108 		SAHTREE_RUNLOCK();
5109 		return (NULL);
5110 	}
5111 	/* Check that SPI is unique */
5112 	LIST_FOREACH(sav, SAVHASH_HASH(*spi), spihash) {
5113 		if (sav->spi == *spi)
5114 			break;
5115 	}
5116 	if (sav == NULL) {
5117 		SAHTREE_RUNLOCK();
5118 		/* SPI is already unique */
5119 		return (NULL);
5120 	}
5121 	SAHTREE_RUNLOCK();
5122 	/* XXX: not optimal */
5123 	*spi = key_do_getnewspi(NULL, saidx);
5124 	return (NULL);
5125 }
5126 
5127 static int
key_updateaddresses(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp,struct secasvar * sav,struct secasindex * saidx)5128 key_updateaddresses(struct socket *so, struct mbuf *m,
5129     const struct sadb_msghdr *mhp, struct secasvar *sav,
5130     struct secasindex *saidx)
5131 {
5132 	struct sockaddr *newaddr;
5133 	struct secashead *sah;
5134 	struct secasvar *newsav, *tmp;
5135 	struct mbuf *n;
5136 	int error, isnew;
5137 
5138 	/* Check that we need to change SAH */
5139 	if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC)) {
5140 		newaddr = (struct sockaddr *)(
5141 		    ((struct sadb_address *)
5142 		    mhp->ext[SADB_X_EXT_NEW_ADDRESS_SRC]) + 1);
5143 		bcopy(newaddr, &saidx->src, newaddr->sa_len);
5144 		key_porttosaddr(&saidx->src.sa, 0);
5145 	}
5146 	if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5147 		newaddr = (struct sockaddr *)(
5148 		    ((struct sadb_address *)
5149 		    mhp->ext[SADB_X_EXT_NEW_ADDRESS_DST]) + 1);
5150 		bcopy(newaddr, &saidx->dst, newaddr->sa_len);
5151 		key_porttosaddr(&saidx->dst.sa, 0);
5152 	}
5153 	if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5154 	    !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5155 		error = key_checksockaddrs(&saidx->src.sa, &saidx->dst.sa);
5156 		if (error != 0) {
5157 			ipseclog((LOG_DEBUG, "%s: invalid new sockaddr.\n",
5158 			    __func__));
5159 			return (error);
5160 		}
5161 
5162 		sah = key_getsah(saidx);
5163 		if (sah == NULL) {
5164 			/* create a new SA index */
5165 			sah = key_newsah(saidx);
5166 			if (sah == NULL) {
5167 				ipseclog((LOG_DEBUG,
5168 				    "%s: No more memory.\n", __func__));
5169 				return (ENOBUFS);
5170 			}
5171 			isnew = 2; /* SAH is new */
5172 		} else
5173 			isnew = 1; /* existing SAH is referenced */
5174 	} else {
5175 		/*
5176 		 * src and dst addresses are still the same.
5177 		 * Do we want to change NAT-T config?
5178 		 */
5179 		if (sav->sah->saidx.proto != IPPROTO_ESP ||
5180 		    SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5181 		    SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5182 		    SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5183 			ipseclog((LOG_DEBUG,
5184 			    "%s: invalid message: missing required header.\n",
5185 			    __func__));
5186 			return (EINVAL);
5187 		}
5188 		/* We hold reference to SA, thus SAH will be referenced too. */
5189 		sah = sav->sah;
5190 		isnew = 0;
5191 	}
5192 
5193 	newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA,
5194 	    M_NOWAIT | M_ZERO);
5195 	if (newsav == NULL) {
5196 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5197 		error = ENOBUFS;
5198 		goto fail;
5199 	}
5200 
5201 	/* Clone SA's content into newsav */
5202 	SAV_INITREF(newsav);
5203 	bcopy(sav, newsav, offsetof(struct secasvar, chain));
5204 	/*
5205 	 * We create new NAT-T config if it is needed.
5206 	 * Old NAT-T config will be freed by key_cleansav() when
5207 	 * last reference to SA will be released.
5208 	 */
5209 	newsav->natt = NULL;
5210 	newsav->sah = sah;
5211 	newsav->state = SADB_SASTATE_MATURE;
5212 	error = key_setnatt(newsav, mhp);
5213 	if (error != 0)
5214 		goto fail;
5215 
5216 	SAHTREE_WLOCK();
5217 	/* Check that SA is still alive */
5218 	if (sav->state == SADB_SASTATE_DEAD) {
5219 		/* SA was unlinked */
5220 		SAHTREE_WUNLOCK();
5221 		error = ESRCH;
5222 		goto fail;
5223 	}
5224 
5225 	/* Unlink SA from SAH and SPI hash */
5226 	IPSEC_ASSERT((sav->flags & SADB_X_EXT_F_CLONED) == 0,
5227 	    ("SA is already cloned"));
5228 	IPSEC_ASSERT(sav->state == SADB_SASTATE_MATURE ||
5229 	    sav->state == SADB_SASTATE_DYING,
5230 	    ("Wrong SA state %u\n", sav->state));
5231 	TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
5232 	LIST_REMOVE(sav, spihash);
5233 	sav->state = SADB_SASTATE_DEAD;
5234 
5235 	/*
5236 	 * Link new SA with SAH. Keep SAs ordered by
5237 	 * create time (newer are first).
5238 	 */
5239 	TAILQ_FOREACH(tmp, &sah->savtree_alive, chain) {
5240 		if (newsav->created > tmp->created) {
5241 			TAILQ_INSERT_BEFORE(tmp, newsav, chain);
5242 			break;
5243 		}
5244 	}
5245 	if (tmp == NULL)
5246 		TAILQ_INSERT_TAIL(&sah->savtree_alive, newsav, chain);
5247 
5248 	/* Add new SA into SPI hash. */
5249 	LIST_INSERT_HEAD(SAVHASH_HASH(newsav->spi), newsav, spihash);
5250 
5251 	/* Add new SAH into SADB. */
5252 	if (isnew == 2) {
5253 		TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
5254 		LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
5255 		sah->state = SADB_SASTATE_MATURE;
5256 		SAH_ADDREF(sah); /* newsav references new SAH */
5257 	}
5258 	/*
5259 	 * isnew == 1 -> @sah was referenced by key_getsah().
5260 	 * isnew == 0 -> we use the same @sah, that was used by @sav,
5261 	 *	and we use its reference for @newsav.
5262 	 */
5263 	SECASVAR_WLOCK(sav);
5264 	/* XXX: replace cntr with pointer? */
5265 	newsav->cntr = sav->cntr;
5266 	sav->flags |= SADB_X_EXT_F_CLONED;
5267 	SECASVAR_WUNLOCK(sav);
5268 
5269 	SAHTREE_WUNLOCK();
5270 
5271 	KEYDBG(KEY_STAMP,
5272 	    printf("%s: SA(%p) cloned into SA(%p)\n",
5273 	    __func__, sav, newsav));
5274 	KEYDBG(KEY_DATA, kdebug_secasv(newsav));
5275 
5276 	key_freesav(&sav); /* release last reference */
5277 
5278 	/* set msg buf from mhp */
5279 	n = key_getmsgbuf_x1(m, mhp);
5280 	if (n == NULL) {
5281 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5282 		return (ENOBUFS);
5283 	}
5284 	m_freem(m);
5285 	key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5286 	return (0);
5287 fail:
5288 	if (isnew != 0)
5289 		key_freesah(&sah);
5290 	if (newsav != NULL) {
5291 		if (newsav->natt != NULL)
5292 			free(newsav->natt, M_IPSEC_MISC);
5293 		free(newsav, M_IPSEC_SA);
5294 	}
5295 	return (error);
5296 }
5297 
5298 /*
5299  * SADB_UPDATE processing
5300  * receive
5301  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5302  *       key(AE), (identity(SD),) (sensitivity)>
5303  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5304  * and send
5305  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5306  *       (identity(SD),) (sensitivity)>
5307  * to the ikmpd.
5308  *
5309  * m will always be freed.
5310  */
5311 static int
key_update(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)5312 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5313 {
5314 	struct secasindex saidx;
5315 	struct sadb_address *src0, *dst0;
5316 	struct sadb_sa *sa0;
5317 	struct secasvar *sav;
5318 	uint32_t reqid;
5319 	int error;
5320 	uint8_t mode, proto;
5321 
5322 	IPSEC_ASSERT(so != NULL, ("null socket"));
5323 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5324 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5325 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5326 
5327 	/* map satype to proto */
5328 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5329 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5330 		    __func__));
5331 		return key_senderror(so, m, EINVAL);
5332 	}
5333 
5334 	if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5335 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5336 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5337 	    (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5338 		!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5339 	    (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5340 		!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5341 		ipseclog((LOG_DEBUG,
5342 		    "%s: invalid message: missing required header.\n",
5343 		    __func__));
5344 		return key_senderror(so, m, EINVAL);
5345 	}
5346 	if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5347 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5348 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5349 		ipseclog((LOG_DEBUG,
5350 		    "%s: invalid message: wrong header size.\n", __func__));
5351 		return key_senderror(so, m, EINVAL);
5352 	}
5353 	if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5354 		mode = IPSEC_MODE_ANY;
5355 		reqid = 0;
5356 	} else {
5357 		if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5358 			ipseclog((LOG_DEBUG,
5359 			    "%s: invalid message: wrong header size.\n",
5360 			    __func__));
5361 			return key_senderror(so, m, EINVAL);
5362 		}
5363 		mode = ((struct sadb_x_sa2 *)
5364 		    mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5365 		reqid = ((struct sadb_x_sa2 *)
5366 		    mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5367 	}
5368 
5369 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5370 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5371 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5372 
5373 	/*
5374 	 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5375 	 * SADB_UPDATE message.
5376 	 */
5377 	if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5378 		ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5379 #ifdef PFKEY_STRICT_CHECKS
5380 		return key_senderror(so, m, EINVAL);
5381 #endif
5382 	}
5383 	error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5384 	    (struct sockaddr *)(dst0 + 1));
5385 	if (error != 0) {
5386 		ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5387 		return key_senderror(so, m, error);
5388 	}
5389 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5390 	sav = key_getsavbyspi(sa0->sadb_sa_spi);
5391 	if (sav == NULL) {
5392 		ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u\n",
5393 		    __func__, ntohl(sa0->sadb_sa_spi)));
5394 		return key_senderror(so, m, EINVAL);
5395 	}
5396 	/*
5397 	 * Check that SADB_UPDATE issued by the same process that did
5398 	 * SADB_GETSPI or SADB_ADD.
5399 	 */
5400 	if (sav->pid != mhp->msg->sadb_msg_pid) {
5401 		ipseclog((LOG_DEBUG,
5402 		    "%s: pid mismatched (SPI %u, pid %u vs. %u)\n", __func__,
5403 		    ntohl(sav->spi), sav->pid, mhp->msg->sadb_msg_pid));
5404 		key_freesav(&sav);
5405 		return key_senderror(so, m, EINVAL);
5406 	}
5407 	/* saidx should match with SA. */
5408 	if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_MODE_REQID) == 0) {
5409 		ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u\n",
5410 		    __func__, ntohl(sav->spi)));
5411 		key_freesav(&sav);
5412 		return key_senderror(so, m, ESRCH);
5413 	}
5414 
5415 	if (sav->state == SADB_SASTATE_LARVAL) {
5416 		if ((mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5417 		    SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) ||
5418 		    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5419 		    SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH))) {
5420 			ipseclog((LOG_DEBUG,
5421 			    "%s: invalid message: missing required header.\n",
5422 			    __func__));
5423 			key_freesav(&sav);
5424 			return key_senderror(so, m, EINVAL);
5425 		}
5426 		/*
5427 		 * We can set any values except src, dst and SPI.
5428 		 */
5429 		error = key_setsaval(sav, mhp);
5430 		if (error != 0) {
5431 			key_freesav(&sav);
5432 			return (key_senderror(so, m, error));
5433 		}
5434 		/* Change SA state to MATURE */
5435 		SAHTREE_WLOCK();
5436 		if (sav->state != SADB_SASTATE_LARVAL) {
5437 			/* SA was deleted or another thread made it MATURE. */
5438 			SAHTREE_WUNLOCK();
5439 			key_freesav(&sav);
5440 			return (key_senderror(so, m, ESRCH));
5441 		}
5442 		/*
5443 		 * NOTE: we keep SAs in savtree_alive ordered by created
5444 		 * time. When SA's state changed from LARVAL to MATURE,
5445 		 * we update its created time in key_setsaval() and move
5446 		 * it into head of savtree_alive.
5447 		 */
5448 		TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
5449 		TAILQ_INSERT_HEAD(&sav->sah->savtree_alive, sav, chain);
5450 		sav->state = SADB_SASTATE_MATURE;
5451 		SAHTREE_WUNLOCK();
5452 	} else {
5453 		/*
5454 		 * For DYING and MATURE SA we can change only state
5455 		 * and lifetimes. Report EINVAL if something else attempted
5456 		 * to change.
5457 		 */
5458 		if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5459 		    !SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
5460 			key_freesav(&sav);
5461 			return (key_senderror(so, m, EINVAL));
5462 		}
5463 		error = key_updatelifetimes(sav, mhp);
5464 		if (error != 0) {
5465 			key_freesav(&sav);
5466 			return (key_senderror(so, m, error));
5467 		}
5468 		/*
5469 		 * This is FreeBSD extension to RFC2367.
5470 		 * IKEd can specify SADB_X_EXT_NEW_ADDRESS_SRC and/or
5471 		 * SADB_X_EXT_NEW_ADDRESS_DST when it wants to change
5472 		 * SA addresses (for example to implement MOBIKE protocol
5473 		 * as described in RFC4555). Also we allow to change
5474 		 * NAT-T config.
5475 		 */
5476 		if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5477 		    !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST) ||
5478 		    !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5479 		    sav->natt != NULL) {
5480 			error = key_updateaddresses(so, m, mhp, sav, &saidx);
5481 			key_freesav(&sav);
5482 			if (error != 0)
5483 				return (key_senderror(so, m, error));
5484 			return (0);
5485 		}
5486 		/* Check that SA is still alive */
5487 		SAHTREE_WLOCK();
5488 		if (sav->state == SADB_SASTATE_DEAD) {
5489 			/* SA was unlinked */
5490 			SAHTREE_WUNLOCK();
5491 			key_freesav(&sav);
5492 			return (key_senderror(so, m, ESRCH));
5493 		}
5494 		/*
5495 		 * NOTE: there is possible state moving from DYING to MATURE,
5496 		 * but this doesn't change created time, so we won't reorder
5497 		 * this SA.
5498 		 */
5499 		sav->state = SADB_SASTATE_MATURE;
5500 		SAHTREE_WUNLOCK();
5501 	}
5502 	KEYDBG(KEY_STAMP,
5503 	    printf("%s: SA(%p)\n", __func__, sav));
5504 	KEYDBG(KEY_DATA, kdebug_secasv(sav));
5505 	key_freesav(&sav);
5506 
5507     {
5508 	struct mbuf *n;
5509 
5510 	/* set msg buf from mhp */
5511 	n = key_getmsgbuf_x1(m, mhp);
5512 	if (n == NULL) {
5513 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5514 		return key_senderror(so, m, ENOBUFS);
5515 	}
5516 
5517 	m_freem(m);
5518 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5519     }
5520 }
5521 
5522 /*
5523  * SADB_ADD processing
5524  * add an entry to SA database, when received
5525  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5526  *       key(AE), (identity(SD),) (sensitivity)>
5527  * from the ikmpd,
5528  * and send
5529  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5530  *       (identity(SD),) (sensitivity)>
5531  * to the ikmpd.
5532  *
5533  * IGNORE identity and sensitivity messages.
5534  *
5535  * m will always be freed.
5536  */
5537 static int
key_add(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)5538 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5539 {
5540 	struct secasindex saidx;
5541 	struct sadb_address *src0, *dst0;
5542 	struct sadb_sa *sa0;
5543 	struct secasvar *sav;
5544 	uint32_t reqid, spi;
5545 	uint8_t mode, proto;
5546 	int error;
5547 
5548 	IPSEC_ASSERT(so != NULL, ("null socket"));
5549 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5550 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5551 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5552 
5553 	/* map satype to proto */
5554 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5555 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5556 		    __func__));
5557 		return key_senderror(so, m, EINVAL);
5558 	}
5559 
5560 	if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5561 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5562 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5563 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP && (
5564 		SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5565 		SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT))) ||
5566 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH && (
5567 		SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH) ||
5568 		SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH))) ||
5569 	    (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5570 		!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5571 	    (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5572 		!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5573 		ipseclog((LOG_DEBUG,
5574 		    "%s: invalid message: missing required header.\n",
5575 		    __func__));
5576 		return key_senderror(so, m, EINVAL);
5577 	}
5578 	if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5579 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5580 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5581 		ipseclog((LOG_DEBUG,
5582 		    "%s: invalid message: wrong header size.\n", __func__));
5583 		return key_senderror(so, m, EINVAL);
5584 	}
5585 	if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5586 		mode = IPSEC_MODE_ANY;
5587 		reqid = 0;
5588 	} else {
5589 		if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5590 			ipseclog((LOG_DEBUG,
5591 			    "%s: invalid message: wrong header size.\n",
5592 			    __func__));
5593 			return key_senderror(so, m, EINVAL);
5594 		}
5595 		mode = ((struct sadb_x_sa2 *)
5596 		    mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5597 		reqid = ((struct sadb_x_sa2 *)
5598 		    mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5599 	}
5600 
5601 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5602 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5603 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5604 
5605 	/*
5606 	 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5607 	 * SADB_ADD message.
5608 	 */
5609 	if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5610 		ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5611 #ifdef PFKEY_STRICT_CHECKS
5612 		return key_senderror(so, m, EINVAL);
5613 #endif
5614 	}
5615 	error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5616 	    (struct sockaddr *)(dst0 + 1));
5617 	if (error != 0) {
5618 		ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5619 		return key_senderror(so, m, error);
5620 	}
5621 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5622 	spi = sa0->sadb_sa_spi;
5623 	/*
5624 	 * For TCP-MD5 SAs we don't use SPI. Check the uniqueness using
5625 	 * secasindex.
5626 	 * XXXAE: IPComp seems also doesn't use SPI.
5627 	 */
5628 	if (proto == IPPROTO_TCP) {
5629 		sav = key_getsav_tcpmd5(&saidx, &spi);
5630 		if (sav == NULL && spi == 0) {
5631 			/* Failed to allocate SPI */
5632 			ipseclog((LOG_DEBUG, "%s: SA already exists.\n",
5633 			    __func__));
5634 			return key_senderror(so, m, EEXIST);
5635 		}
5636 		/* XXX: SPI that we report back can have another value */
5637 	} else {
5638 		/* We can create new SA only if SPI is different. */
5639 		sav = key_getsavbyspi(spi);
5640 	}
5641 	if (sav != NULL) {
5642 		key_freesav(&sav);
5643 		ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5644 		return key_senderror(so, m, EEXIST);
5645 	}
5646 
5647 	sav = key_newsav(mhp, &saidx, spi, &error);
5648 	if (sav == NULL)
5649 		return key_senderror(so, m, error);
5650 	KEYDBG(KEY_STAMP,
5651 	    printf("%s: return SA(%p)\n", __func__, sav));
5652 	KEYDBG(KEY_DATA, kdebug_secasv(sav));
5653 	/*
5654 	 * If SADB_ADD was in response to SADB_ACQUIRE, we need to schedule
5655 	 * ACQ for deletion.
5656 	 */
5657 	if (sav->seq != 0)
5658 		key_acqdone(&saidx, sav->seq);
5659 
5660     {
5661 	/*
5662 	 * Don't call key_freesav() on error here, as we would like to
5663 	 * keep the SA in the database.
5664 	 */
5665 	struct mbuf *n;
5666 
5667 	/* set msg buf from mhp */
5668 	n = key_getmsgbuf_x1(m, mhp);
5669 	if (n == NULL) {
5670 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5671 		return key_senderror(so, m, ENOBUFS);
5672 	}
5673 
5674 	m_freem(m);
5675 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5676     }
5677 }
5678 
5679 /*
5680  * NAT-T support.
5681  * IKEd may request the use ESP in UDP encapsulation when it detects the
5682  * presence of NAT. It uses NAT-T extension headers for such SAs to specify
5683  * parameters needed for encapsulation and decapsulation. These PF_KEY
5684  * extension headers are not standardized, so this comment addresses our
5685  * implementation.
5686  * SADB_X_EXT_NAT_T_TYPE specifies type of encapsulation, we support only
5687  * UDP_ENCAP_ESPINUDP as described in RFC3948.
5688  * SADB_X_EXT_NAT_T_SPORT/DPORT specifies source and destination ports for
5689  * UDP header. We use these ports in UDP encapsulation procedure, also we
5690  * can check them in UDP decapsulation procedure.
5691  * SADB_X_EXT_NAT_T_OA[IR] specifies original address of initiator or
5692  * responder. These addresses can be used for transport mode to adjust
5693  * checksum after decapsulation and decryption. Since original IP addresses
5694  * used by peer usually different (we detected presence of NAT), TCP/UDP
5695  * pseudo header checksum and IP header checksum was calculated using original
5696  * addresses. After decapsulation and decryption we need to adjust checksum
5697  * to have correct datagram.
5698  *
5699  * We expect presence of NAT-T extension headers only in SADB_ADD and
5700  * SADB_UPDATE messages. We report NAT-T extension headers in replies
5701  * to SADB_ADD, SADB_UPDATE, SADB_GET, and SADB_DUMP messages.
5702  */
5703 static int
key_setnatt(struct secasvar * sav,const struct sadb_msghdr * mhp)5704 key_setnatt(struct secasvar *sav, const struct sadb_msghdr *mhp)
5705 {
5706 	struct sadb_x_nat_t_port *port;
5707 	struct sadb_x_nat_t_type *type;
5708 	struct sadb_address *oai, *oar;
5709 	struct sockaddr *sa;
5710 	uint32_t addr;
5711 	uint16_t cksum;
5712 
5713 	IPSEC_ASSERT(sav->natt == NULL, ("natt is already initialized"));
5714 	/*
5715 	 * Ignore NAT-T headers if sproto isn't ESP.
5716 	 */
5717 	if (sav->sah->saidx.proto != IPPROTO_ESP)
5718 		return (0);
5719 
5720 	if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) &&
5721 	    !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) &&
5722 	    !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5723 		if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5724 		    SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5725 		    SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5726 			ipseclog((LOG_DEBUG,
5727 			    "%s: invalid message: wrong header size.\n",
5728 			    __func__));
5729 			return (EINVAL);
5730 		}
5731 	} else
5732 		return (0);
5733 
5734 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5735 	if (type->sadb_x_nat_t_type_type != UDP_ENCAP_ESPINUDP) {
5736 		ipseclog((LOG_DEBUG, "%s: unsupported NAT-T type %u.\n",
5737 		    __func__, type->sadb_x_nat_t_type_type));
5738 		return (EINVAL);
5739 	}
5740 	/*
5741 	 * Allocate storage for NAT-T config.
5742 	 * On error it will be released by key_cleansav().
5743 	 */
5744 	sav->natt = malloc(sizeof(struct secnatt), M_IPSEC_MISC,
5745 	    M_NOWAIT | M_ZERO);
5746 	if (sav->natt == NULL) {
5747 		PFKEYSTAT_INC(in_nomem);
5748 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5749 		return (ENOBUFS);
5750 	}
5751 	port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5752 	if (port->sadb_x_nat_t_port_port == 0) {
5753 		ipseclog((LOG_DEBUG, "%s: invalid NAT-T sport specified.\n",
5754 		    __func__));
5755 		return (EINVAL);
5756 	}
5757 	sav->natt->sport = port->sadb_x_nat_t_port_port;
5758 	port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5759 	if (port->sadb_x_nat_t_port_port == 0) {
5760 		ipseclog((LOG_DEBUG, "%s: invalid NAT-T dport specified.\n",
5761 		    __func__));
5762 		return (EINVAL);
5763 	}
5764 	sav->natt->dport = port->sadb_x_nat_t_port_port;
5765 
5766 	/*
5767 	 * SADB_X_EXT_NAT_T_OAI and SADB_X_EXT_NAT_T_OAR are optional
5768 	 * and needed only for transport mode IPsec.
5769 	 * Usually NAT translates only one address, but it is possible,
5770 	 * that both addresses could be translated.
5771 	 * NOTE: Value of SADB_X_EXT_NAT_T_OAI is equal to SADB_X_EXT_NAT_T_OA.
5772 	 */
5773 	if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAI)) {
5774 		if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAI)) {
5775 			ipseclog((LOG_DEBUG,
5776 			    "%s: invalid message: wrong header size.\n",
5777 			    __func__));
5778 			return (EINVAL);
5779 		}
5780 		oai = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5781 	} else
5782 		oai = NULL;
5783 	if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAR)) {
5784 		if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAR)) {
5785 			ipseclog((LOG_DEBUG,
5786 			    "%s: invalid message: wrong header size.\n",
5787 			    __func__));
5788 			return (EINVAL);
5789 		}
5790 		oar = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5791 	} else
5792 		oar = NULL;
5793 
5794 	/* Initialize addresses only for transport mode */
5795 	if (sav->sah->saidx.mode != IPSEC_MODE_TUNNEL) {
5796 		cksum = 0;
5797 		if (oai != NULL) {
5798 			/* Currently we support only AF_INET */
5799 			sa = (struct sockaddr *)(oai + 1);
5800 			if (sa->sa_family != AF_INET ||
5801 			    sa->sa_len != sizeof(struct sockaddr_in)) {
5802 				ipseclog((LOG_DEBUG,
5803 				    "%s: wrong NAT-OAi header.\n",
5804 				    __func__));
5805 				return (EINVAL);
5806 			}
5807 			/* Ignore address if it the same */
5808 			if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5809 			    sav->sah->saidx.src.sin.sin_addr.s_addr) {
5810 				bcopy(sa, &sav->natt->oai.sa, sa->sa_len);
5811 				sav->natt->flags |= IPSEC_NATT_F_OAI;
5812 				/* Calculate checksum delta */
5813 				addr = sav->sah->saidx.src.sin.sin_addr.s_addr;
5814 				cksum = in_addword(cksum, ~addr >> 16);
5815 				cksum = in_addword(cksum, ~addr & 0xffff);
5816 				addr = sav->natt->oai.sin.sin_addr.s_addr;
5817 				cksum = in_addword(cksum, addr >> 16);
5818 				cksum = in_addword(cksum, addr & 0xffff);
5819 			}
5820 		}
5821 		if (oar != NULL) {
5822 			/* Currently we support only AF_INET */
5823 			sa = (struct sockaddr *)(oar + 1);
5824 			if (sa->sa_family != AF_INET ||
5825 			    sa->sa_len != sizeof(struct sockaddr_in)) {
5826 				ipseclog((LOG_DEBUG,
5827 				    "%s: wrong NAT-OAr header.\n",
5828 				    __func__));
5829 				return (EINVAL);
5830 			}
5831 			/* Ignore address if it the same */
5832 			if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5833 			    sav->sah->saidx.dst.sin.sin_addr.s_addr) {
5834 				bcopy(sa, &sav->natt->oar.sa, sa->sa_len);
5835 				sav->natt->flags |= IPSEC_NATT_F_OAR;
5836 				/* Calculate checksum delta */
5837 				addr = sav->sah->saidx.dst.sin.sin_addr.s_addr;
5838 				cksum = in_addword(cksum, ~addr >> 16);
5839 				cksum = in_addword(cksum, ~addr & 0xffff);
5840 				addr = sav->natt->oar.sin.sin_addr.s_addr;
5841 				cksum = in_addword(cksum, addr >> 16);
5842 				cksum = in_addword(cksum, addr & 0xffff);
5843 			}
5844 		}
5845 		sav->natt->cksum = cksum;
5846 	}
5847 	return (0);
5848 }
5849 
5850 static int
key_setident(struct secashead * sah,const struct sadb_msghdr * mhp)5851 key_setident(struct secashead *sah, const struct sadb_msghdr *mhp)
5852 {
5853 	const struct sadb_ident *idsrc, *iddst;
5854 
5855 	IPSEC_ASSERT(sah != NULL, ("null secashead"));
5856 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5857 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5858 
5859 	/* don't make buffer if not there */
5860 	if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) &&
5861 	    SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5862 		sah->idents = NULL;
5863 		sah->identd = NULL;
5864 		return (0);
5865 	}
5866 
5867 	if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) ||
5868 	    SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5869 		ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5870 		return (EINVAL);
5871 	}
5872 
5873 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5874 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5875 
5876 	/* validity check */
5877 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5878 		ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5879 		return EINVAL;
5880 	}
5881 
5882 	switch (idsrc->sadb_ident_type) {
5883 	case SADB_IDENTTYPE_PREFIX:
5884 	case SADB_IDENTTYPE_FQDN:
5885 	case SADB_IDENTTYPE_USERFQDN:
5886 	default:
5887 		/* XXX do nothing */
5888 		sah->idents = NULL;
5889 		sah->identd = NULL;
5890 	 	return 0;
5891 	}
5892 
5893 	/* make structure */
5894 	sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5895 	if (sah->idents == NULL) {
5896 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5897 		return ENOBUFS;
5898 	}
5899 	sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5900 	if (sah->identd == NULL) {
5901 		free(sah->idents, M_IPSEC_MISC);
5902 		sah->idents = NULL;
5903 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5904 		return ENOBUFS;
5905 	}
5906 	sah->idents->type = idsrc->sadb_ident_type;
5907 	sah->idents->id = idsrc->sadb_ident_id;
5908 
5909 	sah->identd->type = iddst->sadb_ident_type;
5910 	sah->identd->id = iddst->sadb_ident_id;
5911 
5912 	return 0;
5913 }
5914 
5915 /*
5916  * m will not be freed on return.
5917  * it is caller's responsibility to free the result.
5918  *
5919  * Called from SADB_ADD and SADB_UPDATE. Reply will contain headers
5920  * from the request in defined order.
5921  */
5922 static struct mbuf *
key_getmsgbuf_x1(struct mbuf * m,const struct sadb_msghdr * mhp)5923 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5924 {
5925 	struct mbuf *n;
5926 
5927 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5928 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5929 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5930 
5931 	/* create new sadb_msg to reply. */
5932 	n = key_gather_mbuf(m, mhp, 1, 16, SADB_EXT_RESERVED,
5933 	    SADB_EXT_SA, SADB_X_EXT_SA2,
5934 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5935 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5936 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
5937 	    SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
5938 	    SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
5939 	    SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NEW_ADDRESS_SRC,
5940 	    SADB_X_EXT_NEW_ADDRESS_DST);
5941 	if (!n)
5942 		return NULL;
5943 
5944 	if (n->m_len < sizeof(struct sadb_msg)) {
5945 		n = m_pullup(n, sizeof(struct sadb_msg));
5946 		if (n == NULL)
5947 			return NULL;
5948 	}
5949 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5950 	mtod(n, struct sadb_msg *)->sadb_msg_len =
5951 	    PFKEY_UNIT64(n->m_pkthdr.len);
5952 
5953 	return n;
5954 }
5955 
5956 /*
5957  * SADB_DELETE processing
5958  * receive
5959  *   <base, SA(*), address(SD)>
5960  * from the ikmpd, and set SADB_SASTATE_DEAD,
5961  * and send,
5962  *   <base, SA(*), address(SD)>
5963  * to the ikmpd.
5964  *
5965  * m will always be freed.
5966  */
5967 static int
key_delete(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)5968 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5969 {
5970 	struct secasindex saidx;
5971 	struct sadb_address *src0, *dst0;
5972 	struct secasvar *sav;
5973 	struct sadb_sa *sa0;
5974 	uint8_t proto;
5975 
5976 	IPSEC_ASSERT(so != NULL, ("null socket"));
5977 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
5978 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5979 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5980 
5981 	/* map satype to proto */
5982 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5983 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5984 		    __func__));
5985 		return key_senderror(so, m, EINVAL);
5986 	}
5987 
5988 	if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5989 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5990 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5991 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5992 		ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5993 		    __func__));
5994 		return key_senderror(so, m, EINVAL);
5995 	}
5996 
5997 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5998 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5999 
6000 	if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6001 	    (struct sockaddr *)(dst0 + 1)) != 0) {
6002 		ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6003 		return (key_senderror(so, m, EINVAL));
6004 	}
6005 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6006 	if (SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
6007 		/*
6008 		 * Caller wants us to delete all non-LARVAL SAs
6009 		 * that match the src/dst.  This is used during
6010 		 * IKE INITIAL-CONTACT.
6011 		 * XXXAE: this looks like some extension to RFC2367.
6012 		 */
6013 		ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
6014 		return (key_delete_all(so, m, mhp, &saidx));
6015 	}
6016 	if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
6017 		ipseclog((LOG_DEBUG,
6018 		    "%s: invalid message: wrong header size.\n", __func__));
6019 		return (key_senderror(so, m, EINVAL));
6020 	}
6021 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6022 	if (proto == IPPROTO_TCP)
6023 		sav = key_getsav_tcpmd5(&saidx, NULL);
6024 	else
6025 		sav = key_getsavbyspi(sa0->sadb_sa_spi);
6026 	if (sav == NULL) {
6027 		ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u.\n",
6028 		    __func__, ntohl(sa0->sadb_sa_spi)));
6029 		return (key_senderror(so, m, ESRCH));
6030 	}
6031 	if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6032 		ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6033 		    __func__, ntohl(sav->spi)));
6034 		key_freesav(&sav);
6035 		return (key_senderror(so, m, ESRCH));
6036 	}
6037 	KEYDBG(KEY_STAMP,
6038 	    printf("%s: SA(%p)\n", __func__, sav));
6039 	KEYDBG(KEY_DATA, kdebug_secasv(sav));
6040 	key_unlinksav(sav);
6041 	key_freesav(&sav);
6042 
6043     {
6044 	struct mbuf *n;
6045 	struct sadb_msg *newmsg;
6046 
6047 	/* create new sadb_msg to reply. */
6048 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
6049 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6050 	if (!n)
6051 		return key_senderror(so, m, ENOBUFS);
6052 
6053 	if (n->m_len < sizeof(struct sadb_msg)) {
6054 		n = m_pullup(n, sizeof(struct sadb_msg));
6055 		if (n == NULL)
6056 			return key_senderror(so, m, ENOBUFS);
6057 	}
6058 	newmsg = mtod(n, struct sadb_msg *);
6059 	newmsg->sadb_msg_errno = 0;
6060 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6061 
6062 	m_freem(m);
6063 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6064     }
6065 }
6066 
6067 /*
6068  * delete all SAs for src/dst.  Called from key_delete().
6069  */
6070 static int
key_delete_all(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp,struct secasindex * saidx)6071 key_delete_all(struct socket *so, struct mbuf *m,
6072     const struct sadb_msghdr *mhp, struct secasindex *saidx)
6073 {
6074 	struct secasvar_queue drainq;
6075 	struct secashead *sah;
6076 	struct secasvar *sav, *nextsav;
6077 
6078 	TAILQ_INIT(&drainq);
6079 	SAHTREE_WLOCK();
6080 	LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
6081 		if (key_cmpsaidx(&sah->saidx, saidx, CMP_HEAD) == 0)
6082 			continue;
6083 		/* Move all ALIVE SAs into drainq */
6084 		TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6085 	}
6086 	/* Unlink all queued SAs from SPI hash */
6087 	TAILQ_FOREACH(sav, &drainq, chain) {
6088 		sav->state = SADB_SASTATE_DEAD;
6089 		LIST_REMOVE(sav, spihash);
6090 	}
6091 	SAHTREE_WUNLOCK();
6092 	/* Now we can release reference for all SAs in drainq */
6093 	sav = TAILQ_FIRST(&drainq);
6094 	while (sav != NULL) {
6095 		KEYDBG(KEY_STAMP,
6096 		    printf("%s: SA(%p)\n", __func__, sav));
6097 		KEYDBG(KEY_DATA, kdebug_secasv(sav));
6098 		nextsav = TAILQ_NEXT(sav, chain);
6099 		key_freesah(&sav->sah); /* release reference from SAV */
6100 		key_freesav(&sav); /* release last reference */
6101 		sav = nextsav;
6102 	}
6103 
6104     {
6105 	struct mbuf *n;
6106 	struct sadb_msg *newmsg;
6107 
6108 	/* create new sadb_msg to reply. */
6109 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
6110 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6111 	if (!n)
6112 		return key_senderror(so, m, ENOBUFS);
6113 
6114 	if (n->m_len < sizeof(struct sadb_msg)) {
6115 		n = m_pullup(n, sizeof(struct sadb_msg));
6116 		if (n == NULL)
6117 			return key_senderror(so, m, ENOBUFS);
6118 	}
6119 	newmsg = mtod(n, struct sadb_msg *);
6120 	newmsg->sadb_msg_errno = 0;
6121 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6122 
6123 	m_freem(m);
6124 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6125     }
6126 }
6127 
6128 /*
6129  * Delete all alive SAs for corresponding xform.
6130  * Larval SAs have not initialized tdb_xform, so it is safe to leave them
6131  * here when xform disappears.
6132  */
6133 void
key_delete_xform(const struct xformsw * xsp)6134 key_delete_xform(const struct xformsw *xsp)
6135 {
6136 	struct secasvar_queue drainq;
6137 	struct secashead *sah;
6138 	struct secasvar *sav, *nextsav;
6139 
6140 	TAILQ_INIT(&drainq);
6141 	SAHTREE_WLOCK();
6142 	TAILQ_FOREACH(sah, &V_sahtree, chain) {
6143 		sav = TAILQ_FIRST(&sah->savtree_alive);
6144 		if (sav == NULL)
6145 			continue;
6146 		if (sav->tdb_xform != xsp)
6147 			continue;
6148 		/*
6149 		 * It is supposed that all SAs in the chain are related to
6150 		 * one xform.
6151 		 */
6152 		TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6153 	}
6154 	/* Unlink all queued SAs from SPI hash */
6155 	TAILQ_FOREACH(sav, &drainq, chain) {
6156 		sav->state = SADB_SASTATE_DEAD;
6157 		LIST_REMOVE(sav, spihash);
6158 	}
6159 	SAHTREE_WUNLOCK();
6160 
6161 	/* Now we can release reference for all SAs in drainq */
6162 	sav = TAILQ_FIRST(&drainq);
6163 	while (sav != NULL) {
6164 		KEYDBG(KEY_STAMP,
6165 		    printf("%s: SA(%p)\n", __func__, sav));
6166 		KEYDBG(KEY_DATA, kdebug_secasv(sav));
6167 		nextsav = TAILQ_NEXT(sav, chain);
6168 		key_freesah(&sav->sah); /* release reference from SAV */
6169 		key_freesav(&sav); /* release last reference */
6170 		sav = nextsav;
6171 	}
6172 }
6173 
6174 /*
6175  * SADB_GET processing
6176  * receive
6177  *   <base, SA(*), address(SD)>
6178  * from the ikmpd, and get a SP and a SA to respond,
6179  * and send,
6180  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
6181  *       (identity(SD),) (sensitivity)>
6182  * to the ikmpd.
6183  *
6184  * m will always be freed.
6185  */
6186 static int
key_get(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)6187 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6188 {
6189 	struct secasindex saidx;
6190 	struct sadb_address *src0, *dst0;
6191 	struct sadb_sa *sa0;
6192 	struct secasvar *sav;
6193 	uint8_t proto;
6194 
6195 	IPSEC_ASSERT(so != NULL, ("null socket"));
6196 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6197 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6198 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6199 
6200 	/* map satype to proto */
6201 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6202 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6203 			__func__));
6204 		return key_senderror(so, m, EINVAL);
6205 	}
6206 
6207 	if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
6208 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6209 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)) {
6210 		ipseclog((LOG_DEBUG,
6211 		    "%s: invalid message: missing required header.\n",
6212 		    __func__));
6213 		return key_senderror(so, m, EINVAL);
6214 	}
6215 	if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
6216 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6217 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
6218 		ipseclog((LOG_DEBUG,
6219 		    "%s: invalid message: wrong header size.\n", __func__));
6220 		return key_senderror(so, m, EINVAL);
6221 	}
6222 
6223 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6224 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6225 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6226 
6227 	if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6228 	    (struct sockaddr *)(dst0 + 1)) != 0) {
6229 		ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6230 		return key_senderror(so, m, EINVAL);
6231 	}
6232 	KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6233 
6234 	if (proto == IPPROTO_TCP)
6235 		sav = key_getsav_tcpmd5(&saidx, NULL);
6236 	else
6237 		sav = key_getsavbyspi(sa0->sadb_sa_spi);
6238 	if (sav == NULL) {
6239 		ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
6240 		return key_senderror(so, m, ESRCH);
6241 	}
6242 	if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6243 		ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6244 		    __func__, ntohl(sa0->sadb_sa_spi)));
6245 		key_freesav(&sav);
6246 		return (key_senderror(so, m, ESRCH));
6247 	}
6248 
6249     {
6250 	struct mbuf *n;
6251 	uint8_t satype;
6252 
6253 	/* map proto to satype */
6254 	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0) {
6255 		ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
6256 		    __func__));
6257 		key_freesav(&sav);
6258 		return key_senderror(so, m, EINVAL);
6259 	}
6260 
6261 	/* create new sadb_msg to reply. */
6262 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
6263 	    mhp->msg->sadb_msg_pid);
6264 
6265 	key_freesav(&sav);
6266 	if (!n)
6267 		return key_senderror(so, m, ENOBUFS);
6268 
6269 	m_freem(m);
6270 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6271     }
6272 }
6273 
6274 /* XXX make it sysctl-configurable? */
6275 static void
key_getcomb_setlifetime(struct sadb_comb * comb)6276 key_getcomb_setlifetime(struct sadb_comb *comb)
6277 {
6278 
6279 	comb->sadb_comb_soft_allocations = 1;
6280 	comb->sadb_comb_hard_allocations = 1;
6281 	comb->sadb_comb_soft_bytes = 0;
6282 	comb->sadb_comb_hard_bytes = 0;
6283 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
6284 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6285 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
6286 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6287 }
6288 
6289 /*
6290  * XXX reorder combinations by preference
6291  * XXX no idea if the user wants ESP authentication or not
6292  */
6293 static struct mbuf *
key_getcomb_ealg(void)6294 key_getcomb_ealg(void)
6295 {
6296 	struct sadb_comb *comb;
6297 	const struct enc_xform *algo;
6298 	struct mbuf *result = NULL, *m, *n;
6299 	int encmin;
6300 	int i, off, o;
6301 	int totlen;
6302 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6303 
6304 	m = NULL;
6305 	for (i = 1; i <= SADB_EALG_MAX; i++) {
6306 		algo = enc_algorithm_lookup(i);
6307 		if (algo == NULL)
6308 			continue;
6309 
6310 		/* discard algorithms with key size smaller than system min */
6311 		if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6312 			continue;
6313 		if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6314 			encmin = V_ipsec_esp_keymin;
6315 		else
6316 			encmin = _BITS(algo->minkey);
6317 
6318 		if (V_ipsec_esp_auth)
6319 			m = key_getcomb_ah();
6320 		else {
6321 			IPSEC_ASSERT(l <= MLEN,
6322 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6323 			MGET(m, M_NOWAIT, MT_DATA);
6324 			if (m) {
6325 				M_ALIGN(m, l);
6326 				m->m_len = l;
6327 				m->m_next = NULL;
6328 				bzero(mtod(m, caddr_t), m->m_len);
6329 			}
6330 		}
6331 		if (!m)
6332 			goto fail;
6333 
6334 		totlen = 0;
6335 		for (n = m; n; n = n->m_next)
6336 			totlen += n->m_len;
6337 		IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6338 
6339 		for (off = 0; off < totlen; off += l) {
6340 			n = m_pulldown(m, off, l, &o);
6341 			if (!n) {
6342 				/* m is already freed */
6343 				goto fail;
6344 			}
6345 			comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6346 			bzero(comb, sizeof(*comb));
6347 			key_getcomb_setlifetime(comb);
6348 			comb->sadb_comb_encrypt = i;
6349 			comb->sadb_comb_encrypt_minbits = encmin;
6350 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6351 		}
6352 
6353 		if (!result)
6354 			result = m;
6355 		else
6356 			m_cat(result, m);
6357 	}
6358 
6359 	return result;
6360 
6361  fail:
6362 	if (result)
6363 		m_freem(result);
6364 	return NULL;
6365 }
6366 
6367 static void
key_getsizes_ah(const struct auth_hash * ah,int alg,u_int16_t * min,u_int16_t * max)6368 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
6369     u_int16_t* max)
6370 {
6371 
6372 	*min = *max = ah->hashsize;
6373 	if (ah->keysize == 0) {
6374 		/*
6375 		 * Transform takes arbitrary key size but algorithm
6376 		 * key size is restricted.  Enforce this here.
6377 		 */
6378 		switch (alg) {
6379 		case SADB_X_AALG_NULL:	*min = 1; *max = 256; break;
6380 		case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
6381 		case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
6382 		case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
6383 		default:
6384 			DPRINTF(("%s: unknown AH algorithm %u\n",
6385 				__func__, alg));
6386 			break;
6387 		}
6388 	}
6389 }
6390 
6391 /*
6392  * XXX reorder combinations by preference
6393  */
6394 static struct mbuf *
key_getcomb_ah(void)6395 key_getcomb_ah(void)
6396 {
6397 	const struct auth_hash *algo;
6398 	struct sadb_comb *comb;
6399 	struct mbuf *m;
6400 	u_int16_t minkeysize, maxkeysize;
6401 	int i;
6402 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6403 
6404 	m = NULL;
6405 	for (i = 1; i <= SADB_AALG_MAX; i++) {
6406 #if 1
6407 		/* we prefer HMAC algorithms, not old algorithms */
6408 		if (i != SADB_AALG_SHA1HMAC &&
6409 		    i != SADB_X_AALG_SHA2_256 &&
6410 		    i != SADB_X_AALG_SHA2_384 &&
6411 		    i != SADB_X_AALG_SHA2_512)
6412 			continue;
6413 #endif
6414 		algo = auth_algorithm_lookup(i);
6415 		if (!algo)
6416 			continue;
6417 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6418 		/* discard algorithms with key size smaller than system min */
6419 		if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6420 			continue;
6421 
6422 		if (!m) {
6423 			IPSEC_ASSERT(l <= MLEN,
6424 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6425 			MGET(m, M_NOWAIT, MT_DATA);
6426 			if (m) {
6427 				M_ALIGN(m, l);
6428 				m->m_len = l;
6429 				m->m_next = NULL;
6430 			}
6431 		} else
6432 			M_PREPEND(m, l, M_NOWAIT);
6433 		if (!m)
6434 			return NULL;
6435 
6436 		comb = mtod(m, struct sadb_comb *);
6437 		bzero(comb, sizeof(*comb));
6438 		key_getcomb_setlifetime(comb);
6439 		comb->sadb_comb_auth = i;
6440 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6441 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6442 	}
6443 
6444 	return m;
6445 }
6446 
6447 /*
6448  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6449  * XXX reorder combinations by preference
6450  */
6451 static struct mbuf *
key_getcomb_ipcomp(void)6452 key_getcomb_ipcomp(void)
6453 {
6454 	const struct comp_algo *algo;
6455 	struct sadb_comb *comb;
6456 	struct mbuf *m;
6457 	int i;
6458 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6459 
6460 	m = NULL;
6461 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6462 		algo = comp_algorithm_lookup(i);
6463 		if (!algo)
6464 			continue;
6465 
6466 		if (!m) {
6467 			IPSEC_ASSERT(l <= MLEN,
6468 				("l=%u > MLEN=%lu", l, (u_long) MLEN));
6469 			MGET(m, M_NOWAIT, MT_DATA);
6470 			if (m) {
6471 				M_ALIGN(m, l);
6472 				m->m_len = l;
6473 				m->m_next = NULL;
6474 			}
6475 		} else
6476 			M_PREPEND(m, l, M_NOWAIT);
6477 		if (!m)
6478 			return NULL;
6479 
6480 		comb = mtod(m, struct sadb_comb *);
6481 		bzero(comb, sizeof(*comb));
6482 		key_getcomb_setlifetime(comb);
6483 		comb->sadb_comb_encrypt = i;
6484 		/* what should we set into sadb_comb_*_{min,max}bits? */
6485 	}
6486 
6487 	return m;
6488 }
6489 
6490 /*
6491  * XXX no way to pass mode (transport/tunnel) to userland
6492  * XXX replay checking?
6493  * XXX sysctl interface to ipsec_{ah,esp}_keymin
6494  */
6495 static struct mbuf *
key_getprop(const struct secasindex * saidx)6496 key_getprop(const struct secasindex *saidx)
6497 {
6498 	struct sadb_prop *prop;
6499 	struct mbuf *m, *n;
6500 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6501 	int totlen;
6502 
6503 	switch (saidx->proto)  {
6504 	case IPPROTO_ESP:
6505 		m = key_getcomb_ealg();
6506 		break;
6507 	case IPPROTO_AH:
6508 		m = key_getcomb_ah();
6509 		break;
6510 	case IPPROTO_IPCOMP:
6511 		m = key_getcomb_ipcomp();
6512 		break;
6513 	default:
6514 		return NULL;
6515 	}
6516 
6517 	if (!m)
6518 		return NULL;
6519 	M_PREPEND(m, l, M_NOWAIT);
6520 	if (!m)
6521 		return NULL;
6522 
6523 	totlen = 0;
6524 	for (n = m; n; n = n->m_next)
6525 		totlen += n->m_len;
6526 
6527 	prop = mtod(m, struct sadb_prop *);
6528 	bzero(prop, sizeof(*prop));
6529 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6530 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6531 	prop->sadb_prop_replay = 32;	/* XXX */
6532 
6533 	return m;
6534 }
6535 
6536 /*
6537  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6538  * send
6539  *   <base, SA, address(SD), (address(P)), x_policy,
6540  *       (identity(SD),) (sensitivity,) proposal>
6541  * to KMD, and expect to receive
6542  *   <base> with SADB_ACQUIRE if error occurred,
6543  * or
6544  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6545  * from KMD by PF_KEY.
6546  *
6547  * XXX x_policy is outside of RFC2367 (KAME extension).
6548  * XXX sensitivity is not supported.
6549  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6550  * see comment for key_getcomb_ipcomp().
6551  *
6552  * OUT:
6553  *    0     : succeed
6554  *    others: error number
6555  */
6556 static int
key_acquire(const struct secasindex * saidx,struct secpolicy * sp)6557 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6558 {
6559 	union sockaddr_union addr;
6560 	struct mbuf *result, *m;
6561 	uint32_t seq;
6562 	int error;
6563 	uint16_t ul_proto;
6564 	uint8_t mask, satype;
6565 
6566 	IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6567 	satype = key_proto2satype(saidx->proto);
6568 	IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6569 
6570 	error = -1;
6571 	result = NULL;
6572 	ul_proto = IPSEC_ULPROTO_ANY;
6573 
6574 	/* Get seq number to check whether sending message or not. */
6575 	seq = key_getacq(saidx, &error);
6576 	if (seq == 0)
6577 		return (error);
6578 
6579 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6580 	if (!m) {
6581 		error = ENOBUFS;
6582 		goto fail;
6583 	}
6584 	result = m;
6585 
6586 	/*
6587 	 * set sadb_address for saidx's.
6588 	 *
6589 	 * Note that if sp is supplied, then we're being called from
6590 	 * key_allocsa_policy() and should supply port and protocol
6591 	 * information.
6592 	 * XXXAE: why only TCP and UDP? ICMP and SCTP looks applicable too.
6593 	 * XXXAE: probably we can handle this in the ipsec[46]_allocsa().
6594 	 * XXXAE: it looks like we should save this info in the ACQ entry.
6595 	 */
6596 	if (sp != NULL && (sp->spidx.ul_proto == IPPROTO_TCP ||
6597 	    sp->spidx.ul_proto == IPPROTO_UDP))
6598 		ul_proto = sp->spidx.ul_proto;
6599 
6600 	addr = saidx->src;
6601 	mask = FULLMASK;
6602 	if (ul_proto != IPSEC_ULPROTO_ANY) {
6603 		switch (sp->spidx.src.sa.sa_family) {
6604 		case AF_INET:
6605 			if (sp->spidx.src.sin.sin_port != IPSEC_PORT_ANY) {
6606 				addr.sin.sin_port = sp->spidx.src.sin.sin_port;
6607 				mask = sp->spidx.prefs;
6608 			}
6609 			break;
6610 		case AF_INET6:
6611 			if (sp->spidx.src.sin6.sin6_port != IPSEC_PORT_ANY) {
6612 				addr.sin6.sin6_port =
6613 				    sp->spidx.src.sin6.sin6_port;
6614 				mask = sp->spidx.prefs;
6615 			}
6616 			break;
6617 		default:
6618 			break;
6619 		}
6620 	}
6621 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &addr.sa, mask, ul_proto);
6622 	if (!m) {
6623 		error = ENOBUFS;
6624 		goto fail;
6625 	}
6626 	m_cat(result, m);
6627 
6628 	addr = saidx->dst;
6629 	mask = FULLMASK;
6630 	if (ul_proto != IPSEC_ULPROTO_ANY) {
6631 		switch (sp->spidx.dst.sa.sa_family) {
6632 		case AF_INET:
6633 			if (sp->spidx.dst.sin.sin_port != IPSEC_PORT_ANY) {
6634 				addr.sin.sin_port = sp->spidx.dst.sin.sin_port;
6635 				mask = sp->spidx.prefd;
6636 			}
6637 			break;
6638 		case AF_INET6:
6639 			if (sp->spidx.dst.sin6.sin6_port != IPSEC_PORT_ANY) {
6640 				addr.sin6.sin6_port =
6641 				    sp->spidx.dst.sin6.sin6_port;
6642 				mask = sp->spidx.prefd;
6643 			}
6644 			break;
6645 		default:
6646 			break;
6647 		}
6648 	}
6649 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &addr.sa, mask, ul_proto);
6650 	if (!m) {
6651 		error = ENOBUFS;
6652 		goto fail;
6653 	}
6654 	m_cat(result, m);
6655 
6656 	/* XXX proxy address (optional) */
6657 
6658 	/*
6659 	 * Set sadb_x_policy. This is KAME extension to RFC2367.
6660 	 */
6661 	if (sp != NULL) {
6662 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id,
6663 		    sp->priority);
6664 		if (!m) {
6665 			error = ENOBUFS;
6666 			goto fail;
6667 		}
6668 		m_cat(result, m);
6669 	}
6670 
6671 	/*
6672 	 * Set sadb_x_sa2 extension if saidx->reqid is not zero.
6673 	 * This is FreeBSD extension to RFC2367.
6674 	 */
6675 	if (saidx->reqid != 0) {
6676 		m = key_setsadbxsa2(saidx->mode, 0, saidx->reqid);
6677 		if (m == NULL) {
6678 			error = ENOBUFS;
6679 			goto fail;
6680 		}
6681 		m_cat(result, m);
6682 	}
6683 	/* XXX identity (optional) */
6684 #if 0
6685 	if (idexttype && fqdn) {
6686 		/* create identity extension (FQDN) */
6687 		struct sadb_ident *id;
6688 		int fqdnlen;
6689 
6690 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
6691 		id = (struct sadb_ident *)p;
6692 		bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6693 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6694 		id->sadb_ident_exttype = idexttype;
6695 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6696 		bcopy(fqdn, id + 1, fqdnlen);
6697 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6698 	}
6699 
6700 	if (idexttype) {
6701 		/* create identity extension (USERFQDN) */
6702 		struct sadb_ident *id;
6703 		int userfqdnlen;
6704 
6705 		if (userfqdn) {
6706 			/* +1 for terminating-NUL */
6707 			userfqdnlen = strlen(userfqdn) + 1;
6708 		} else
6709 			userfqdnlen = 0;
6710 		id = (struct sadb_ident *)p;
6711 		bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6712 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6713 		id->sadb_ident_exttype = idexttype;
6714 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6715 		/* XXX is it correct? */
6716 		if (curproc && curproc->p_cred)
6717 			id->sadb_ident_id = curproc->p_cred->p_ruid;
6718 		if (userfqdn && userfqdnlen)
6719 			bcopy(userfqdn, id + 1, userfqdnlen);
6720 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6721 	}
6722 #endif
6723 
6724 	/* XXX sensitivity (optional) */
6725 
6726 	/* create proposal/combination extension */
6727 	m = key_getprop(saidx);
6728 #if 0
6729 	/*
6730 	 * spec conformant: always attach proposal/combination extension,
6731 	 * the problem is that we have no way to attach it for ipcomp,
6732 	 * due to the way sadb_comb is declared in RFC2367.
6733 	 */
6734 	if (!m) {
6735 		error = ENOBUFS;
6736 		goto fail;
6737 	}
6738 	m_cat(result, m);
6739 #else
6740 	/*
6741 	 * outside of spec; make proposal/combination extension optional.
6742 	 */
6743 	if (m)
6744 		m_cat(result, m);
6745 #endif
6746 
6747 	if ((result->m_flags & M_PKTHDR) == 0) {
6748 		error = EINVAL;
6749 		goto fail;
6750 	}
6751 
6752 	if (result->m_len < sizeof(struct sadb_msg)) {
6753 		result = m_pullup(result, sizeof(struct sadb_msg));
6754 		if (result == NULL) {
6755 			error = ENOBUFS;
6756 			goto fail;
6757 		}
6758 	}
6759 
6760 	result->m_pkthdr.len = 0;
6761 	for (m = result; m; m = m->m_next)
6762 		result->m_pkthdr.len += m->m_len;
6763 
6764 	mtod(result, struct sadb_msg *)->sadb_msg_len =
6765 	    PFKEY_UNIT64(result->m_pkthdr.len);
6766 
6767 	KEYDBG(KEY_STAMP,
6768 	    printf("%s: SP(%p)\n", __func__, sp));
6769 	KEYDBG(KEY_DATA, kdebug_secasindex(saidx, NULL));
6770 
6771 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6772 
6773  fail:
6774 	if (result)
6775 		m_freem(result);
6776 	return error;
6777 }
6778 
6779 static uint32_t
key_newacq(const struct secasindex * saidx,int * perror)6780 key_newacq(const struct secasindex *saidx, int *perror)
6781 {
6782 	struct secacq *acq;
6783 	uint32_t seq;
6784 
6785 	acq = malloc(sizeof(*acq), M_IPSEC_SAQ, M_NOWAIT | M_ZERO);
6786 	if (acq == NULL) {
6787 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6788 		*perror = ENOBUFS;
6789 		return (0);
6790 	}
6791 
6792 	/* copy secindex */
6793 	bcopy(saidx, &acq->saidx, sizeof(acq->saidx));
6794 	acq->created = time_second;
6795 	acq->count = 0;
6796 
6797 	/* add to acqtree */
6798 	ACQ_LOCK();
6799 	seq = acq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6800 	LIST_INSERT_HEAD(&V_acqtree, acq, chain);
6801 	LIST_INSERT_HEAD(ACQADDRHASH_HASH(saidx), acq, addrhash);
6802 	LIST_INSERT_HEAD(ACQSEQHASH_HASH(seq), acq, seqhash);
6803 	ACQ_UNLOCK();
6804 	*perror = 0;
6805 	return (seq);
6806 }
6807 
6808 static uint32_t
key_getacq(const struct secasindex * saidx,int * perror)6809 key_getacq(const struct secasindex *saidx, int *perror)
6810 {
6811 	struct secacq *acq;
6812 	uint32_t seq;
6813 
6814 	ACQ_LOCK();
6815 	LIST_FOREACH(acq, ACQADDRHASH_HASH(saidx), addrhash) {
6816 		if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY)) {
6817 			if (acq->count > V_key_blockacq_count) {
6818 				/*
6819 				 * Reset counter and send message.
6820 				 * Also reset created time to keep ACQ for
6821 				 * this saidx.
6822 				 */
6823 				acq->created = time_second;
6824 				acq->count = 0;
6825 				seq = acq->seq;
6826 			} else {
6827 				/*
6828 				 * Increment counter and do nothing.
6829 				 * We send SADB_ACQUIRE message only
6830 				 * for each V_key_blockacq_count packet.
6831 				 */
6832 				acq->count++;
6833 				seq = 0;
6834 			}
6835 			break;
6836 		}
6837 	}
6838 	ACQ_UNLOCK();
6839 	if (acq != NULL) {
6840 		*perror = 0;
6841 		return (seq);
6842 	}
6843 	/* allocate new  entry */
6844 	return (key_newacq(saidx, perror));
6845 }
6846 
6847 static int
key_acqreset(uint32_t seq)6848 key_acqreset(uint32_t seq)
6849 {
6850 	struct secacq *acq;
6851 
6852 	ACQ_LOCK();
6853 	LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6854 		if (acq->seq == seq) {
6855 			acq->count = 0;
6856 			acq->created = time_second;
6857 			break;
6858 		}
6859 	}
6860 	ACQ_UNLOCK();
6861 	if (acq == NULL)
6862 		return (ESRCH);
6863 	return (0);
6864 }
6865 /*
6866  * Mark ACQ entry as stale to remove it in key_flush_acq().
6867  * Called after successful SADB_GETSPI message.
6868  */
6869 static int
key_acqdone(const struct secasindex * saidx,uint32_t seq)6870 key_acqdone(const struct secasindex *saidx, uint32_t seq)
6871 {
6872 	struct secacq *acq;
6873 
6874 	ACQ_LOCK();
6875 	LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6876 		if (acq->seq == seq)
6877 			break;
6878 	}
6879 	if (acq != NULL) {
6880 		if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY) == 0) {
6881 			ipseclog((LOG_DEBUG,
6882 			    "%s: Mismatched saidx for ACQ %u\n", __func__, seq));
6883 			acq = NULL;
6884 		} else {
6885 			acq->created = 0;
6886 		}
6887 	} else {
6888 		ipseclog((LOG_DEBUG,
6889 		    "%s: ACQ %u is not found.\n", __func__, seq));
6890 	}
6891 	ACQ_UNLOCK();
6892 	if (acq == NULL)
6893 		return (ESRCH);
6894 	return (0);
6895 }
6896 
6897 static struct secspacq *
key_newspacq(struct secpolicyindex * spidx)6898 key_newspacq(struct secpolicyindex *spidx)
6899 {
6900 	struct secspacq *acq;
6901 
6902 	/* get new entry */
6903 	acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6904 	if (acq == NULL) {
6905 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6906 		return NULL;
6907 	}
6908 
6909 	/* copy secindex */
6910 	bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6911 	acq->created = time_second;
6912 	acq->count = 0;
6913 
6914 	/* add to spacqtree */
6915 	SPACQ_LOCK();
6916 	LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6917 	SPACQ_UNLOCK();
6918 
6919 	return acq;
6920 }
6921 
6922 static struct secspacq *
key_getspacq(struct secpolicyindex * spidx)6923 key_getspacq(struct secpolicyindex *spidx)
6924 {
6925 	struct secspacq *acq;
6926 
6927 	SPACQ_LOCK();
6928 	LIST_FOREACH(acq, &V_spacqtree, chain) {
6929 		if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6930 			/* NB: return holding spacq_lock */
6931 			return acq;
6932 		}
6933 	}
6934 	SPACQ_UNLOCK();
6935 
6936 	return NULL;
6937 }
6938 
6939 /*
6940  * SADB_ACQUIRE processing,
6941  * in first situation, is receiving
6942  *   <base>
6943  * from the ikmpd, and clear sequence of its secasvar entry.
6944  *
6945  * In second situation, is receiving
6946  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6947  * from a user land process, and return
6948  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6949  * to the socket.
6950  *
6951  * m will always be freed.
6952  */
6953 static int
key_acquire2(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)6954 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6955 {
6956 	SAHTREE_RLOCK_TRACKER;
6957 	struct sadb_address *src0, *dst0;
6958 	struct secasindex saidx;
6959 	struct secashead *sah;
6960 	uint32_t reqid;
6961 	int error;
6962 	uint8_t mode, proto;
6963 
6964 	IPSEC_ASSERT(so != NULL, ("null socket"));
6965 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
6966 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6967 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6968 
6969 	/*
6970 	 * Error message from KMd.
6971 	 * We assume that if error was occurred in IKEd, the length of PFKEY
6972 	 * message is equal to the size of sadb_msg structure.
6973 	 * We do not raise error even if error occurred in this function.
6974 	 */
6975 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6976 		/* check sequence number */
6977 		if (mhp->msg->sadb_msg_seq == 0 ||
6978 		    mhp->msg->sadb_msg_errno == 0) {
6979 			ipseclog((LOG_DEBUG, "%s: must specify sequence "
6980 				"number and errno.\n", __func__));
6981 		} else {
6982 			/*
6983 			 * IKEd reported that error occurred.
6984 			 * XXXAE: what it expects from the kernel?
6985 			 * Probably we should send SADB_ACQUIRE again?
6986 			 * If so, reset ACQ's state.
6987 			 * XXXAE: it looks useless.
6988 			 */
6989 			key_acqreset(mhp->msg->sadb_msg_seq);
6990 		}
6991 		m_freem(m);
6992 		return (0);
6993 	}
6994 
6995 	/*
6996 	 * This message is from user land.
6997 	 */
6998 
6999 	/* map satype to proto */
7000 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7001 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7002 		    __func__));
7003 		return key_senderror(so, m, EINVAL);
7004 	}
7005 
7006 	if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
7007 	    SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
7008 	    SADB_CHECKHDR(mhp, SADB_EXT_PROPOSAL)) {
7009 		ipseclog((LOG_DEBUG,
7010 		    "%s: invalid message: missing required header.\n",
7011 		    __func__));
7012 		return key_senderror(so, m, EINVAL);
7013 	}
7014 	if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
7015 	    SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
7016 	    SADB_CHECKLEN(mhp, SADB_EXT_PROPOSAL)) {
7017 		ipseclog((LOG_DEBUG,
7018 		    "%s: invalid message: wrong header size.\n", __func__));
7019 		return key_senderror(so, m, EINVAL);
7020 	}
7021 
7022 	if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
7023 		mode = IPSEC_MODE_ANY;
7024 		reqid = 0;
7025 	} else {
7026 		if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
7027 			ipseclog((LOG_DEBUG,
7028 			    "%s: invalid message: wrong header size.\n",
7029 			    __func__));
7030 			return key_senderror(so, m, EINVAL);
7031 		}
7032 		mode = ((struct sadb_x_sa2 *)
7033 		    mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
7034 		reqid = ((struct sadb_x_sa2 *)
7035 		    mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
7036 	}
7037 
7038 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
7039 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
7040 
7041 	error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
7042 	    (struct sockaddr *)(dst0 + 1));
7043 	if (error != 0) {
7044 		ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
7045 		return key_senderror(so, m, EINVAL);
7046 	}
7047 	KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
7048 
7049 	/* get a SA index */
7050 	SAHTREE_RLOCK();
7051 	LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
7052 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
7053 			break;
7054 	}
7055 	SAHTREE_RUNLOCK();
7056 	if (sah != NULL) {
7057 		ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
7058 		return key_senderror(so, m, EEXIST);
7059 	}
7060 
7061 	error = key_acquire(&saidx, NULL);
7062 	if (error != 0) {
7063 		ipseclog((LOG_DEBUG,
7064 		    "%s: error %d returned from key_acquire()\n",
7065 			__func__, error));
7066 		return key_senderror(so, m, error);
7067 	}
7068 	m_freem(m);
7069 	return (0);
7070 }
7071 
7072 /*
7073  * SADB_REGISTER processing.
7074  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
7075  * receive
7076  *   <base>
7077  * from the ikmpd, and register a socket to send PF_KEY messages,
7078  * and send
7079  *   <base, supported>
7080  * to KMD by PF_KEY.
7081  * If socket is detached, must free from regnode.
7082  *
7083  * m will always be freed.
7084  */
7085 static int
key_register(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)7086 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7087 {
7088 	struct secreg *reg, *newreg = NULL;
7089 
7090 	IPSEC_ASSERT(so != NULL, ("null socket"));
7091 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7092 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7093 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7094 
7095 	/* check for invalid register message */
7096 	if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
7097 		return key_senderror(so, m, EINVAL);
7098 
7099 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
7100 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
7101 		goto setmsg;
7102 
7103 	/* check whether existing or not */
7104 	REGTREE_LOCK();
7105 	LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
7106 		if (reg->so == so) {
7107 			REGTREE_UNLOCK();
7108 			ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
7109 				__func__));
7110 			return key_senderror(so, m, EEXIST);
7111 		}
7112 	}
7113 
7114 	/* create regnode */
7115 	newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
7116 	if (newreg == NULL) {
7117 		REGTREE_UNLOCK();
7118 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7119 		return key_senderror(so, m, ENOBUFS);
7120 	}
7121 
7122 	newreg->so = so;
7123 	((struct keycb *)sotorawcb(so))->kp_registered++;
7124 
7125 	/* add regnode to regtree. */
7126 	LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
7127 	REGTREE_UNLOCK();
7128 
7129   setmsg:
7130     {
7131 	struct mbuf *n;
7132 	struct sadb_msg *newmsg;
7133 	struct sadb_supported *sup;
7134 	u_int len, alen, elen;
7135 	int off;
7136 	int i;
7137 	struct sadb_alg *alg;
7138 
7139 	/* create new sadb_msg to reply. */
7140 	alen = 0;
7141 	for (i = 1; i <= SADB_AALG_MAX; i++) {
7142 		if (auth_algorithm_lookup(i))
7143 			alen += sizeof(struct sadb_alg);
7144 	}
7145 	if (alen)
7146 		alen += sizeof(struct sadb_supported);
7147 	elen = 0;
7148 	for (i = 1; i <= SADB_EALG_MAX; i++) {
7149 		if (enc_algorithm_lookup(i))
7150 			elen += sizeof(struct sadb_alg);
7151 	}
7152 	if (elen)
7153 		elen += sizeof(struct sadb_supported);
7154 
7155 	len = sizeof(struct sadb_msg) + alen + elen;
7156 
7157 	if (len > MCLBYTES)
7158 		return key_senderror(so, m, ENOBUFS);
7159 
7160 	n = key_mget(len);
7161 	if (n == NULL)
7162 		return key_senderror(so, m, ENOBUFS);
7163 
7164 	n->m_pkthdr.len = n->m_len = len;
7165 	n->m_next = NULL;
7166 	off = 0;
7167 
7168 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
7169 	newmsg = mtod(n, struct sadb_msg *);
7170 	newmsg->sadb_msg_errno = 0;
7171 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
7172 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
7173 
7174 	/* for authentication algorithm */
7175 	if (alen) {
7176 		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7177 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
7178 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
7179 		off += PFKEY_ALIGN8(sizeof(*sup));
7180 
7181 		for (i = 1; i <= SADB_AALG_MAX; i++) {
7182 			const struct auth_hash *aalgo;
7183 			u_int16_t minkeysize, maxkeysize;
7184 
7185 			aalgo = auth_algorithm_lookup(i);
7186 			if (!aalgo)
7187 				continue;
7188 			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7189 			alg->sadb_alg_id = i;
7190 			alg->sadb_alg_ivlen = 0;
7191 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
7192 			alg->sadb_alg_minbits = _BITS(minkeysize);
7193 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
7194 			off += PFKEY_ALIGN8(sizeof(*alg));
7195 		}
7196 	}
7197 
7198 	/* for encryption algorithm */
7199 	if (elen) {
7200 		sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7201 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
7202 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
7203 		off += PFKEY_ALIGN8(sizeof(*sup));
7204 
7205 		for (i = 1; i <= SADB_EALG_MAX; i++) {
7206 			const struct enc_xform *ealgo;
7207 
7208 			ealgo = enc_algorithm_lookup(i);
7209 			if (!ealgo)
7210 				continue;
7211 			alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7212 			alg->sadb_alg_id = i;
7213 			alg->sadb_alg_ivlen = ealgo->ivsize;
7214 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
7215 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
7216 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
7217 		}
7218 	}
7219 
7220 	IPSEC_ASSERT(off == len,
7221 		("length assumption failed (off %u len %u)", off, len));
7222 
7223 	m_freem(m);
7224 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
7225     }
7226 }
7227 
7228 /*
7229  * free secreg entry registered.
7230  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
7231  */
7232 void
key_freereg(struct socket * so)7233 key_freereg(struct socket *so)
7234 {
7235 	struct secreg *reg;
7236 	int i;
7237 
7238 	IPSEC_ASSERT(so != NULL, ("NULL so"));
7239 
7240 	/*
7241 	 * check whether existing or not.
7242 	 * check all type of SA, because there is a potential that
7243 	 * one socket is registered to multiple type of SA.
7244 	 */
7245 	REGTREE_LOCK();
7246 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7247 		LIST_FOREACH(reg, &V_regtree[i], chain) {
7248 			if (reg->so == so && __LIST_CHAINED(reg)) {
7249 				LIST_REMOVE(reg, chain);
7250 				free(reg, M_IPSEC_SAR);
7251 				break;
7252 			}
7253 		}
7254 	}
7255 	REGTREE_UNLOCK();
7256 }
7257 
7258 /*
7259  * SADB_EXPIRE processing
7260  * send
7261  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
7262  * to KMD by PF_KEY.
7263  * NOTE: We send only soft lifetime extension.
7264  *
7265  * OUT:	0	: succeed
7266  *	others	: error number
7267  */
7268 static int
key_expire(struct secasvar * sav,int hard)7269 key_expire(struct secasvar *sav, int hard)
7270 {
7271 	struct mbuf *result = NULL, *m;
7272 	struct sadb_lifetime *lt;
7273 	uint32_t replay_count;
7274 	int error, len;
7275 	uint8_t satype;
7276 
7277 	SECASVAR_RLOCK_TRACKER;
7278 
7279 	IPSEC_ASSERT (sav != NULL, ("null sav"));
7280 	IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
7281 
7282 	KEYDBG(KEY_STAMP,
7283 	    printf("%s: SA(%p) expired %s lifetime\n", __func__,
7284 		sav, hard ? "hard": "soft"));
7285 	KEYDBG(KEY_DATA, kdebug_secasv(sav));
7286 	/* set msg header */
7287 	satype = key_proto2satype(sav->sah->saidx.proto);
7288 	IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
7289 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
7290 	if (!m) {
7291 		error = ENOBUFS;
7292 		goto fail;
7293 	}
7294 	result = m;
7295 
7296 	/* create SA extension */
7297 	m = key_setsadbsa(sav);
7298 	if (!m) {
7299 		error = ENOBUFS;
7300 		goto fail;
7301 	}
7302 	m_cat(result, m);
7303 
7304 	/* create SA extension */
7305 	SECASVAR_RLOCK(sav);
7306 	replay_count = sav->replay ? sav->replay->count : 0;
7307 	SECASVAR_RUNLOCK(sav);
7308 
7309 	m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
7310 			sav->sah->saidx.reqid);
7311 	if (!m) {
7312 		error = ENOBUFS;
7313 		goto fail;
7314 	}
7315 	m_cat(result, m);
7316 
7317 	if (sav->replay && sav->replay->wsize > UINT8_MAX) {
7318 		m = key_setsadbxsareplay(sav->replay->wsize);
7319 		if (!m) {
7320 			error = ENOBUFS;
7321 			goto fail;
7322 		}
7323 		m_cat(result, m);
7324 	}
7325 
7326 	/* create lifetime extension (current and soft) */
7327 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
7328 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7329 	if (m == NULL) {
7330 		error = ENOBUFS;
7331 		goto fail;
7332 	}
7333 	m_align(m, len);
7334 	m->m_len = len;
7335 	bzero(mtod(m, caddr_t), len);
7336 	lt = mtod(m, struct sadb_lifetime *);
7337 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7338 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
7339 	lt->sadb_lifetime_allocations =
7340 	    (uint32_t)counter_u64_fetch(sav->lft_c_allocations);
7341 	lt->sadb_lifetime_bytes =
7342 	    counter_u64_fetch(sav->lft_c_bytes);
7343 	lt->sadb_lifetime_addtime = sav->created;
7344 	lt->sadb_lifetime_usetime = sav->firstused;
7345 	lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
7346 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7347 	if (hard) {
7348 		lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
7349 		lt->sadb_lifetime_allocations = sav->lft_h->allocations;
7350 		lt->sadb_lifetime_bytes = sav->lft_h->bytes;
7351 		lt->sadb_lifetime_addtime = sav->lft_h->addtime;
7352 		lt->sadb_lifetime_usetime = sav->lft_h->usetime;
7353 	} else {
7354 		lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
7355 		lt->sadb_lifetime_allocations = sav->lft_s->allocations;
7356 		lt->sadb_lifetime_bytes = sav->lft_s->bytes;
7357 		lt->sadb_lifetime_addtime = sav->lft_s->addtime;
7358 		lt->sadb_lifetime_usetime = sav->lft_s->usetime;
7359 	}
7360 	m_cat(result, m);
7361 
7362 	/* set sadb_address for source */
7363 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7364 	    &sav->sah->saidx.src.sa,
7365 	    FULLMASK, IPSEC_ULPROTO_ANY);
7366 	if (!m) {
7367 		error = ENOBUFS;
7368 		goto fail;
7369 	}
7370 	m_cat(result, m);
7371 
7372 	/* set sadb_address for destination */
7373 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7374 	    &sav->sah->saidx.dst.sa,
7375 	    FULLMASK, IPSEC_ULPROTO_ANY);
7376 	if (!m) {
7377 		error = ENOBUFS;
7378 		goto fail;
7379 	}
7380 	m_cat(result, m);
7381 
7382 	/*
7383 	 * XXX-BZ Handle NAT-T extensions here.
7384 	 * XXXAE: it doesn't seem quite useful. IKEs should not depend on
7385 	 * this information, we report only significant SA fields.
7386 	 */
7387 
7388 	if ((result->m_flags & M_PKTHDR) == 0) {
7389 		error = EINVAL;
7390 		goto fail;
7391 	}
7392 
7393 	if (result->m_len < sizeof(struct sadb_msg)) {
7394 		result = m_pullup(result, sizeof(struct sadb_msg));
7395 		if (result == NULL) {
7396 			error = ENOBUFS;
7397 			goto fail;
7398 		}
7399 	}
7400 
7401 	result->m_pkthdr.len = 0;
7402 	for (m = result; m; m = m->m_next)
7403 		result->m_pkthdr.len += m->m_len;
7404 
7405 	mtod(result, struct sadb_msg *)->sadb_msg_len =
7406 	    PFKEY_UNIT64(result->m_pkthdr.len);
7407 
7408 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7409 
7410  fail:
7411 	if (result)
7412 		m_freem(result);
7413 	return error;
7414 }
7415 
7416 static void
key_freesah_flushed(struct secashead_queue * flushq)7417 key_freesah_flushed(struct secashead_queue *flushq)
7418 {
7419 	struct secashead *sah, *nextsah;
7420 	struct secasvar *sav, *nextsav;
7421 
7422 	sah = TAILQ_FIRST(flushq);
7423 	while (sah != NULL) {
7424 		sav = TAILQ_FIRST(&sah->savtree_larval);
7425 		while (sav != NULL) {
7426 			nextsav = TAILQ_NEXT(sav, chain);
7427 			TAILQ_REMOVE(&sah->savtree_larval, sav, chain);
7428 			key_freesav(&sav); /* release last reference */
7429 			key_freesah(&sah); /* release reference from SAV */
7430 			sav = nextsav;
7431 		}
7432 		sav = TAILQ_FIRST(&sah->savtree_alive);
7433 		while (sav != NULL) {
7434 			nextsav = TAILQ_NEXT(sav, chain);
7435 			TAILQ_REMOVE(&sah->savtree_alive, sav, chain);
7436 			key_freesav(&sav); /* release last reference */
7437 			key_freesah(&sah); /* release reference from SAV */
7438 			sav = nextsav;
7439 		}
7440 		nextsah = TAILQ_NEXT(sah, chain);
7441 		key_freesah(&sah);	/* release last reference */
7442 		sah = nextsah;
7443 	}
7444 }
7445 
7446 /*
7447  * SADB_FLUSH processing
7448  * receive
7449  *   <base>
7450  * from the ikmpd, and free all entries in secastree.
7451  * and send,
7452  *   <base>
7453  * to the ikmpd.
7454  * NOTE: to do is only marking SADB_SASTATE_DEAD.
7455  *
7456  * m will always be freed.
7457  */
7458 static int
key_flush(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)7459 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7460 {
7461 	struct secashead_queue flushq;
7462 	struct sadb_msg *newmsg;
7463 	struct secashead *sah, *nextsah;
7464 	struct secasvar *sav;
7465 	uint8_t proto;
7466 	int i;
7467 
7468 	IPSEC_ASSERT(so != NULL, ("null socket"));
7469 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7470 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7471 
7472 	/* map satype to proto */
7473 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7474 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7475 			__func__));
7476 		return key_senderror(so, m, EINVAL);
7477 	}
7478 	KEYDBG(KEY_STAMP,
7479 	    printf("%s: proto %u\n", __func__, proto));
7480 
7481 	TAILQ_INIT(&flushq);
7482 	if (proto == IPSEC_PROTO_ANY) {
7483 		/* no SATYPE specified, i.e. flushing all SA. */
7484 		SAHTREE_WLOCK();
7485 		/* Move all SAHs into flushq */
7486 		TAILQ_CONCAT(&flushq, &V_sahtree, chain);
7487 		/* Flush all buckets in SPI hash */
7488 		for (i = 0; i < V_savhash_mask + 1; i++)
7489 			LIST_INIT(&V_savhashtbl[i]);
7490 		/* Flush all buckets in SAHADDRHASH */
7491 		for (i = 0; i < V_sahaddrhash_mask + 1; i++)
7492 			LIST_INIT(&V_sahaddrhashtbl[i]);
7493 		/* Mark all SAHs as unlinked */
7494 		TAILQ_FOREACH(sah, &flushq, chain) {
7495 			sah->state = SADB_SASTATE_DEAD;
7496 			/*
7497 			 * Callout handler makes its job using
7498 			 * RLOCK and drain queues. In case, when this
7499 			 * function will be called just before it
7500 			 * acquires WLOCK, we need to mark SAs as
7501 			 * unlinked to prevent second unlink.
7502 			 */
7503 			TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7504 				sav->state = SADB_SASTATE_DEAD;
7505 			}
7506 			TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7507 				sav->state = SADB_SASTATE_DEAD;
7508 			}
7509 		}
7510 		SAHTREE_WUNLOCK();
7511 	} else {
7512 		SAHTREE_WLOCK();
7513 		sah = TAILQ_FIRST(&V_sahtree);
7514 		while (sah != NULL) {
7515 			IPSEC_ASSERT(sah->state != SADB_SASTATE_DEAD,
7516 			    ("DEAD SAH %p in SADB_FLUSH", sah));
7517 			nextsah = TAILQ_NEXT(sah, chain);
7518 			if (sah->saidx.proto != proto) {
7519 				sah = nextsah;
7520 				continue;
7521 			}
7522 			sah->state = SADB_SASTATE_DEAD;
7523 			TAILQ_REMOVE(&V_sahtree, sah, chain);
7524 			LIST_REMOVE(sah, addrhash);
7525 			/* Unlink all SAs from SPI hash */
7526 			TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7527 				LIST_REMOVE(sav, spihash);
7528 				sav->state = SADB_SASTATE_DEAD;
7529 			}
7530 			TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7531 				LIST_REMOVE(sav, spihash);
7532 				sav->state = SADB_SASTATE_DEAD;
7533 			}
7534 			/* Add SAH into flushq */
7535 			TAILQ_INSERT_HEAD(&flushq, sah, chain);
7536 			sah = nextsah;
7537 		}
7538 		SAHTREE_WUNLOCK();
7539 	}
7540 
7541 	key_freesah_flushed(&flushq);
7542 	/* Free all queued SAs and SAHs */
7543 	if (m->m_len < sizeof(struct sadb_msg) ||
7544 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7545 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7546 		return key_senderror(so, m, ENOBUFS);
7547 	}
7548 
7549 	if (m->m_next)
7550 		m_freem(m->m_next);
7551 	m->m_next = NULL;
7552 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7553 	newmsg = mtod(m, struct sadb_msg *);
7554 	newmsg->sadb_msg_errno = 0;
7555 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7556 
7557 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7558 }
7559 
7560 /*
7561  * SADB_DUMP processing
7562  * dump all entries including status of DEAD in SAD.
7563  * receive
7564  *   <base>
7565  * from the ikmpd, and dump all secasvar leaves
7566  * and send,
7567  *   <base> .....
7568  * to the ikmpd.
7569  *
7570  * m will always be freed.
7571  */
7572 static int
key_dump(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)7573 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7574 {
7575 	SAHTREE_RLOCK_TRACKER;
7576 	struct secashead *sah;
7577 	struct secasvar *sav;
7578 	struct mbuf *n;
7579 	uint32_t cnt;
7580 	uint8_t proto, satype;
7581 
7582 	IPSEC_ASSERT(so != NULL, ("null socket"));
7583 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7584 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7585 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7586 
7587 	/* map satype to proto */
7588 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7589 		ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7590 		    __func__));
7591 		return key_senderror(so, m, EINVAL);
7592 	}
7593 
7594 	/* count sav entries to be sent to the userland. */
7595 	cnt = 0;
7596 	SAHTREE_RLOCK();
7597 	TAILQ_FOREACH(sah, &V_sahtree, chain) {
7598 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7599 		    proto != sah->saidx.proto)
7600 			continue;
7601 
7602 		TAILQ_FOREACH(sav, &sah->savtree_larval, chain)
7603 			cnt++;
7604 		TAILQ_FOREACH(sav, &sah->savtree_alive, chain)
7605 			cnt++;
7606 	}
7607 
7608 	if (cnt == 0) {
7609 		SAHTREE_RUNLOCK();
7610 		return key_senderror(so, m, ENOENT);
7611 	}
7612 
7613 	/* send this to the userland, one at a time. */
7614 	TAILQ_FOREACH(sah, &V_sahtree, chain) {
7615 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7616 		    proto != sah->saidx.proto)
7617 			continue;
7618 
7619 		/* map proto to satype */
7620 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7621 			SAHTREE_RUNLOCK();
7622 			ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7623 			    "SAD.\n", __func__));
7624 			return key_senderror(so, m, EINVAL);
7625 		}
7626 		TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7627 			n = key_setdumpsa(sav, SADB_DUMP, satype,
7628 			    --cnt, mhp->msg->sadb_msg_pid);
7629 			if (n == NULL) {
7630 				SAHTREE_RUNLOCK();
7631 				return key_senderror(so, m, ENOBUFS);
7632 			}
7633 			key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7634 		}
7635 		TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7636 			n = key_setdumpsa(sav, SADB_DUMP, satype,
7637 			    --cnt, mhp->msg->sadb_msg_pid);
7638 			if (n == NULL) {
7639 				SAHTREE_RUNLOCK();
7640 				return key_senderror(so, m, ENOBUFS);
7641 			}
7642 			key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7643 		}
7644 	}
7645 	SAHTREE_RUNLOCK();
7646 	m_freem(m);
7647 	return (0);
7648 }
7649 /*
7650  * SADB_X_PROMISC processing
7651  *
7652  * m will always be freed.
7653  */
7654 static int
key_promisc(struct socket * so,struct mbuf * m,const struct sadb_msghdr * mhp)7655 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7656 {
7657 	int olen;
7658 
7659 	IPSEC_ASSERT(so != NULL, ("null socket"));
7660 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7661 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7662 	IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7663 
7664 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7665 
7666 	if (olen < sizeof(struct sadb_msg)) {
7667 #if 1
7668 		return key_senderror(so, m, EINVAL);
7669 #else
7670 		m_freem(m);
7671 		return 0;
7672 #endif
7673 	} else if (olen == sizeof(struct sadb_msg)) {
7674 		/* enable/disable promisc mode */
7675 		struct keycb *kp;
7676 
7677 		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7678 			return key_senderror(so, m, EINVAL);
7679 		mhp->msg->sadb_msg_errno = 0;
7680 		switch (mhp->msg->sadb_msg_satype) {
7681 		case 0:
7682 		case 1:
7683 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
7684 			break;
7685 		default:
7686 			return key_senderror(so, m, EINVAL);
7687 		}
7688 
7689 		/* send the original message back to everyone */
7690 		mhp->msg->sadb_msg_errno = 0;
7691 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7692 	} else {
7693 		/* send packet as is */
7694 
7695 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7696 
7697 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
7698 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7699 	}
7700 }
7701 
7702 static int (*key_typesw[])(struct socket *, struct mbuf *,
7703 		const struct sadb_msghdr *) = {
7704 	NULL,		/* SADB_RESERVED */
7705 	key_getspi,	/* SADB_GETSPI */
7706 	key_update,	/* SADB_UPDATE */
7707 	key_add,	/* SADB_ADD */
7708 	key_delete,	/* SADB_DELETE */
7709 	key_get,	/* SADB_GET */
7710 	key_acquire2,	/* SADB_ACQUIRE */
7711 	key_register,	/* SADB_REGISTER */
7712 	NULL,		/* SADB_EXPIRE */
7713 	key_flush,	/* SADB_FLUSH */
7714 	key_dump,	/* SADB_DUMP */
7715 	key_promisc,	/* SADB_X_PROMISC */
7716 	NULL,		/* SADB_X_PCHANGE */
7717 	key_spdadd,	/* SADB_X_SPDUPDATE */
7718 	key_spdadd,	/* SADB_X_SPDADD */
7719 	key_spddelete,	/* SADB_X_SPDDELETE */
7720 	key_spdget,	/* SADB_X_SPDGET */
7721 	NULL,		/* SADB_X_SPDACQUIRE */
7722 	key_spddump,	/* SADB_X_SPDDUMP */
7723 	key_spdflush,	/* SADB_X_SPDFLUSH */
7724 	key_spdadd,	/* SADB_X_SPDSETIDX */
7725 	NULL,		/* SADB_X_SPDEXPIRE */
7726 	key_spddelete2,	/* SADB_X_SPDDELETE2 */
7727 };
7728 
7729 /*
7730  * parse sadb_msg buffer to process PFKEYv2,
7731  * and create a data to response if needed.
7732  * I think to be dealed with mbuf directly.
7733  * IN:
7734  *     msgp  : pointer to pointer to a received buffer pulluped.
7735  *             This is rewrited to response.
7736  *     so    : pointer to socket.
7737  * OUT:
7738  *    length for buffer to send to user process.
7739  */
7740 int
key_parse(struct mbuf * m,struct socket * so)7741 key_parse(struct mbuf *m, struct socket *so)
7742 {
7743 	struct sadb_msg *msg;
7744 	struct sadb_msghdr mh;
7745 	u_int orglen;
7746 	int error;
7747 	int target;
7748 
7749 	IPSEC_ASSERT(so != NULL, ("null socket"));
7750 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
7751 
7752 	if (m->m_len < sizeof(struct sadb_msg)) {
7753 		m = m_pullup(m, sizeof(struct sadb_msg));
7754 		if (!m)
7755 			return ENOBUFS;
7756 	}
7757 	msg = mtod(m, struct sadb_msg *);
7758 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7759 	target = KEY_SENDUP_ONE;
7760 
7761 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len != orglen) {
7762 		ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7763 		PFKEYSTAT_INC(out_invlen);
7764 		error = EINVAL;
7765 		goto senderror;
7766 	}
7767 
7768 	if (msg->sadb_msg_version != PF_KEY_V2) {
7769 		ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7770 		    __func__, msg->sadb_msg_version));
7771 		PFKEYSTAT_INC(out_invver);
7772 		error = EINVAL;
7773 		goto senderror;
7774 	}
7775 
7776 	if (msg->sadb_msg_type > SADB_MAX) {
7777 		ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7778 		    __func__, msg->sadb_msg_type));
7779 		PFKEYSTAT_INC(out_invmsgtype);
7780 		error = EINVAL;
7781 		goto senderror;
7782 	}
7783 
7784 	/* for old-fashioned code - should be nuked */
7785 	if (m->m_pkthdr.len > MCLBYTES) {
7786 		m_freem(m);
7787 		return ENOBUFS;
7788 	}
7789 	if (m->m_next) {
7790 		struct mbuf *n;
7791 
7792 		n = key_mget(m->m_pkthdr.len);
7793 		if (n == NULL) {
7794 			m_freem(m);
7795 			return ENOBUFS;
7796 		}
7797 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7798 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7799 		n->m_next = NULL;
7800 		m_freem(m);
7801 		m = n;
7802 	}
7803 
7804 	/* align the mbuf chain so that extensions are in contiguous region. */
7805 	error = key_align(m, &mh);
7806 	if (error)
7807 		return error;
7808 
7809 	msg = mh.msg;
7810 
7811 	/* We use satype as scope mask for spddump */
7812 	if (msg->sadb_msg_type == SADB_X_SPDDUMP) {
7813 		switch (msg->sadb_msg_satype) {
7814 		case IPSEC_POLICYSCOPE_ANY:
7815 		case IPSEC_POLICYSCOPE_GLOBAL:
7816 		case IPSEC_POLICYSCOPE_IFNET:
7817 		case IPSEC_POLICYSCOPE_PCB:
7818 			break;
7819 		default:
7820 			ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7821 			    __func__, msg->sadb_msg_type));
7822 			PFKEYSTAT_INC(out_invsatype);
7823 			error = EINVAL;
7824 			goto senderror;
7825 		}
7826 	} else {
7827 		switch (msg->sadb_msg_satype) { /* check SA type */
7828 		case SADB_SATYPE_UNSPEC:
7829 			switch (msg->sadb_msg_type) {
7830 			case SADB_GETSPI:
7831 			case SADB_UPDATE:
7832 			case SADB_ADD:
7833 			case SADB_DELETE:
7834 			case SADB_GET:
7835 			case SADB_ACQUIRE:
7836 			case SADB_EXPIRE:
7837 				ipseclog((LOG_DEBUG, "%s: must specify satype "
7838 				    "when msg type=%u.\n", __func__,
7839 				    msg->sadb_msg_type));
7840 				PFKEYSTAT_INC(out_invsatype);
7841 				error = EINVAL;
7842 				goto senderror;
7843 			}
7844 			break;
7845 		case SADB_SATYPE_AH:
7846 		case SADB_SATYPE_ESP:
7847 		case SADB_X_SATYPE_IPCOMP:
7848 		case SADB_X_SATYPE_TCPSIGNATURE:
7849 			switch (msg->sadb_msg_type) {
7850 			case SADB_X_SPDADD:
7851 			case SADB_X_SPDDELETE:
7852 			case SADB_X_SPDGET:
7853 			case SADB_X_SPDFLUSH:
7854 			case SADB_X_SPDSETIDX:
7855 			case SADB_X_SPDUPDATE:
7856 			case SADB_X_SPDDELETE2:
7857 				ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7858 				    __func__, msg->sadb_msg_type));
7859 				PFKEYSTAT_INC(out_invsatype);
7860 				error = EINVAL;
7861 				goto senderror;
7862 			}
7863 			break;
7864 		case SADB_SATYPE_RSVP:
7865 		case SADB_SATYPE_OSPFV2:
7866 		case SADB_SATYPE_RIPV2:
7867 		case SADB_SATYPE_MIP:
7868 			ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7869 			    __func__, msg->sadb_msg_satype));
7870 			PFKEYSTAT_INC(out_invsatype);
7871 			error = EOPNOTSUPP;
7872 			goto senderror;
7873 		case 1:	/* XXX: What does it do? */
7874 			if (msg->sadb_msg_type == SADB_X_PROMISC)
7875 				break;
7876 			/*FALLTHROUGH*/
7877 		default:
7878 			ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7879 			    __func__, msg->sadb_msg_satype));
7880 			PFKEYSTAT_INC(out_invsatype);
7881 			error = EINVAL;
7882 			goto senderror;
7883 		}
7884 	}
7885 
7886 	/* check field of upper layer protocol and address family */
7887 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7888 	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7889 		struct sadb_address *src0, *dst0;
7890 		u_int plen;
7891 
7892 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7893 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7894 
7895 		/* check upper layer protocol */
7896 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7897 			ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7898 				"mismatched.\n", __func__));
7899 			PFKEYSTAT_INC(out_invaddr);
7900 			error = EINVAL;
7901 			goto senderror;
7902 		}
7903 
7904 		/* check family */
7905 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7906 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
7907 			ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7908 				__func__));
7909 			PFKEYSTAT_INC(out_invaddr);
7910 			error = EINVAL;
7911 			goto senderror;
7912 		}
7913 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7914 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
7915 			ipseclog((LOG_DEBUG, "%s: address struct size "
7916 				"mismatched.\n", __func__));
7917 			PFKEYSTAT_INC(out_invaddr);
7918 			error = EINVAL;
7919 			goto senderror;
7920 		}
7921 
7922 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7923 		case AF_INET:
7924 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7925 			    sizeof(struct sockaddr_in)) {
7926 				PFKEYSTAT_INC(out_invaddr);
7927 				error = EINVAL;
7928 				goto senderror;
7929 			}
7930 			break;
7931 		case AF_INET6:
7932 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7933 			    sizeof(struct sockaddr_in6)) {
7934 				PFKEYSTAT_INC(out_invaddr);
7935 				error = EINVAL;
7936 				goto senderror;
7937 			}
7938 			break;
7939 		default:
7940 			ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7941 				__func__));
7942 			PFKEYSTAT_INC(out_invaddr);
7943 			error = EAFNOSUPPORT;
7944 			goto senderror;
7945 		}
7946 
7947 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7948 		case AF_INET:
7949 			plen = sizeof(struct in_addr) << 3;
7950 			break;
7951 		case AF_INET6:
7952 			plen = sizeof(struct in6_addr) << 3;
7953 			break;
7954 		default:
7955 			plen = 0;	/*fool gcc*/
7956 			break;
7957 		}
7958 
7959 		/* check max prefix length */
7960 		if (src0->sadb_address_prefixlen > plen ||
7961 		    dst0->sadb_address_prefixlen > plen) {
7962 			ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7963 				__func__));
7964 			PFKEYSTAT_INC(out_invaddr);
7965 			error = EINVAL;
7966 			goto senderror;
7967 		}
7968 
7969 		/*
7970 		 * prefixlen == 0 is valid because there can be a case when
7971 		 * all addresses are matched.
7972 		 */
7973 	}
7974 
7975 	if (msg->sadb_msg_type >= nitems(key_typesw) ||
7976 	    key_typesw[msg->sadb_msg_type] == NULL) {
7977 		PFKEYSTAT_INC(out_invmsgtype);
7978 		error = EINVAL;
7979 		goto senderror;
7980 	}
7981 
7982 	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7983 
7984 senderror:
7985 	msg->sadb_msg_errno = error;
7986 	return key_sendup_mbuf(so, m, target);
7987 }
7988 
7989 static int
key_senderror(struct socket * so,struct mbuf * m,int code)7990 key_senderror(struct socket *so, struct mbuf *m, int code)
7991 {
7992 	struct sadb_msg *msg;
7993 
7994 	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7995 		("mbuf too small, len %u", m->m_len));
7996 
7997 	msg = mtod(m, struct sadb_msg *);
7998 	msg->sadb_msg_errno = code;
7999 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
8000 }
8001 
8002 /*
8003  * set the pointer to each header into message buffer.
8004  * m will be freed on error.
8005  * XXX larger-than-MCLBYTES extension?
8006  */
8007 static int
key_align(struct mbuf * m,struct sadb_msghdr * mhp)8008 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
8009 {
8010 	struct mbuf *n;
8011 	struct sadb_ext *ext;
8012 	size_t off, end;
8013 	int extlen;
8014 	int toff;
8015 
8016 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
8017 	IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
8018 	IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
8019 		("mbuf too small, len %u", m->m_len));
8020 
8021 	/* initialize */
8022 	bzero(mhp, sizeof(*mhp));
8023 
8024 	mhp->msg = mtod(m, struct sadb_msg *);
8025 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
8026 
8027 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
8028 	extlen = end;	/*just in case extlen is not updated*/
8029 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
8030 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
8031 		if (!n) {
8032 			/* m is already freed */
8033 			return ENOBUFS;
8034 		}
8035 		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8036 
8037 		/* set pointer */
8038 		switch (ext->sadb_ext_type) {
8039 		case SADB_EXT_SA:
8040 		case SADB_EXT_ADDRESS_SRC:
8041 		case SADB_EXT_ADDRESS_DST:
8042 		case SADB_EXT_ADDRESS_PROXY:
8043 		case SADB_EXT_LIFETIME_CURRENT:
8044 		case SADB_EXT_LIFETIME_HARD:
8045 		case SADB_EXT_LIFETIME_SOFT:
8046 		case SADB_EXT_KEY_AUTH:
8047 		case SADB_EXT_KEY_ENCRYPT:
8048 		case SADB_EXT_IDENTITY_SRC:
8049 		case SADB_EXT_IDENTITY_DST:
8050 		case SADB_EXT_SENSITIVITY:
8051 		case SADB_EXT_PROPOSAL:
8052 		case SADB_EXT_SUPPORTED_AUTH:
8053 		case SADB_EXT_SUPPORTED_ENCRYPT:
8054 		case SADB_EXT_SPIRANGE:
8055 		case SADB_X_EXT_POLICY:
8056 		case SADB_X_EXT_SA2:
8057 		case SADB_X_EXT_NAT_T_TYPE:
8058 		case SADB_X_EXT_NAT_T_SPORT:
8059 		case SADB_X_EXT_NAT_T_DPORT:
8060 		case SADB_X_EXT_NAT_T_OAI:
8061 		case SADB_X_EXT_NAT_T_OAR:
8062 		case SADB_X_EXT_NAT_T_FRAG:
8063 		case SADB_X_EXT_SA_REPLAY:
8064 		case SADB_X_EXT_NEW_ADDRESS_SRC:
8065 		case SADB_X_EXT_NEW_ADDRESS_DST:
8066 			/* duplicate check */
8067 			/*
8068 			 * XXX Are there duplication payloads of either
8069 			 * KEY_AUTH or KEY_ENCRYPT ?
8070 			 */
8071 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
8072 				ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
8073 					"%u\n", __func__, ext->sadb_ext_type));
8074 				m_freem(m);
8075 				PFKEYSTAT_INC(out_dupext);
8076 				return EINVAL;
8077 			}
8078 			break;
8079 		default:
8080 			ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
8081 				__func__, ext->sadb_ext_type));
8082 			m_freem(m);
8083 			PFKEYSTAT_INC(out_invexttype);
8084 			return EINVAL;
8085 		}
8086 
8087 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
8088 
8089 		if (key_validate_ext(ext, extlen)) {
8090 			m_freem(m);
8091 			PFKEYSTAT_INC(out_invlen);
8092 			return EINVAL;
8093 		}
8094 
8095 		n = m_pulldown(m, off, extlen, &toff);
8096 		if (!n) {
8097 			/* m is already freed */
8098 			return ENOBUFS;
8099 		}
8100 		ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8101 
8102 		mhp->ext[ext->sadb_ext_type] = ext;
8103 		mhp->extoff[ext->sadb_ext_type] = off;
8104 		mhp->extlen[ext->sadb_ext_type] = extlen;
8105 	}
8106 
8107 	if (off != end) {
8108 		m_freem(m);
8109 		PFKEYSTAT_INC(out_invlen);
8110 		return EINVAL;
8111 	}
8112 
8113 	return 0;
8114 }
8115 
8116 static int
key_validate_ext(const struct sadb_ext * ext,int len)8117 key_validate_ext(const struct sadb_ext *ext, int len)
8118 {
8119 	const struct sockaddr *sa;
8120 	enum { NONE, ADDR } checktype = NONE;
8121 	int baselen = 0;
8122 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
8123 
8124 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
8125 		return EINVAL;
8126 
8127 	/* if it does not match minimum/maximum length, bail */
8128 	if (ext->sadb_ext_type >= nitems(minsize) ||
8129 	    ext->sadb_ext_type >= nitems(maxsize))
8130 		return EINVAL;
8131 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
8132 		return EINVAL;
8133 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
8134 		return EINVAL;
8135 
8136 	/* more checks based on sadb_ext_type XXX need more */
8137 	switch (ext->sadb_ext_type) {
8138 	case SADB_EXT_ADDRESS_SRC:
8139 	case SADB_EXT_ADDRESS_DST:
8140 	case SADB_EXT_ADDRESS_PROXY:
8141 	case SADB_X_EXT_NAT_T_OAI:
8142 	case SADB_X_EXT_NAT_T_OAR:
8143 	case SADB_X_EXT_NEW_ADDRESS_SRC:
8144 	case SADB_X_EXT_NEW_ADDRESS_DST:
8145 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
8146 		checktype = ADDR;
8147 		break;
8148 	case SADB_EXT_IDENTITY_SRC:
8149 	case SADB_EXT_IDENTITY_DST:
8150 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
8151 		    SADB_X_IDENTTYPE_ADDR) {
8152 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
8153 			checktype = ADDR;
8154 		} else
8155 			checktype = NONE;
8156 		break;
8157 	default:
8158 		checktype = NONE;
8159 		break;
8160 	}
8161 
8162 	switch (checktype) {
8163 	case NONE:
8164 		break;
8165 	case ADDR:
8166 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
8167 		if (len < baselen + sal)
8168 			return EINVAL;
8169 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
8170 			return EINVAL;
8171 		break;
8172 	}
8173 
8174 	return 0;
8175 }
8176 
8177 void
spdcache_init(void)8178 spdcache_init(void)
8179 {
8180 	int i;
8181 
8182 	TUNABLE_INT_FETCH("net.key.spdcache.maxentries",
8183 	    &V_key_spdcache_maxentries);
8184 	TUNABLE_INT_FETCH("net.key.spdcache.threshold",
8185 	    &V_key_spdcache_threshold);
8186 
8187 	if (V_key_spdcache_maxentries) {
8188 		V_key_spdcache_maxentries = MAX(V_key_spdcache_maxentries,
8189 		    SPDCACHE_MAX_ENTRIES_PER_HASH);
8190 		V_spdcachehashtbl = hashinit(V_key_spdcache_maxentries /
8191 		    SPDCACHE_MAX_ENTRIES_PER_HASH,
8192 		    M_IPSEC_SPDCACHE, &V_spdcachehash_mask);
8193 		V_key_spdcache_maxentries = (V_spdcachehash_mask + 1)
8194 		    * SPDCACHE_MAX_ENTRIES_PER_HASH;
8195 
8196 		V_spdcache_lock = malloc(sizeof(struct mtx) *
8197 		    (V_spdcachehash_mask + 1),
8198 		    M_IPSEC_SPDCACHE, M_WAITOK|M_ZERO);
8199 
8200 		for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8201 			SPDCACHE_LOCK_INIT(i);
8202 	}
8203 }
8204 
8205 struct spdcache_entry *
spdcache_entry_alloc(const struct secpolicyindex * spidx,struct secpolicy * sp)8206 spdcache_entry_alloc(const struct secpolicyindex *spidx, struct secpolicy *sp)
8207 {
8208 	struct spdcache_entry *entry;
8209 
8210 	entry = malloc(sizeof(struct spdcache_entry),
8211 		    M_IPSEC_SPDCACHE, M_NOWAIT|M_ZERO);
8212 	if (entry == NULL)
8213 		return NULL;
8214 
8215 	if (sp != NULL)
8216 		SP_ADDREF(sp);
8217 
8218 	entry->spidx = *spidx;
8219 	entry->sp = sp;
8220 
8221 	return (entry);
8222 }
8223 
8224 void
spdcache_entry_free(struct spdcache_entry * entry)8225 spdcache_entry_free(struct spdcache_entry *entry)
8226 {
8227 
8228 	if (entry->sp != NULL)
8229 		key_freesp(&entry->sp);
8230 	free(entry, M_IPSEC_SPDCACHE);
8231 }
8232 
8233 void
spdcache_clear(void)8234 spdcache_clear(void)
8235 {
8236 	struct spdcache_entry *entry;
8237 	int i;
8238 
8239 	for (i = 0; i < V_spdcachehash_mask + 1; ++i) {
8240 		SPDCACHE_LOCK(i);
8241 		while (!LIST_EMPTY(&V_spdcachehashtbl[i])) {
8242 			entry = LIST_FIRST(&V_spdcachehashtbl[i]);
8243 			LIST_REMOVE(entry, chain);
8244 			spdcache_entry_free(entry);
8245 		}
8246 		SPDCACHE_UNLOCK(i);
8247 	}
8248 }
8249 
8250 #ifdef VIMAGE
8251 void
spdcache_destroy(void)8252 spdcache_destroy(void)
8253 {
8254 	int i;
8255 
8256 	if (SPDCACHE_ENABLED()) {
8257 		spdcache_clear();
8258 		hashdestroy(V_spdcachehashtbl, M_IPSEC_SPDCACHE, V_spdcachehash_mask);
8259 
8260 		for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8261 			SPDCACHE_LOCK_DESTROY(i);
8262 
8263 		free(V_spdcache_lock, M_IPSEC_SPDCACHE);
8264 	}
8265 }
8266 #endif
8267 void
key_init(void)8268 key_init(void)
8269 {
8270 	int i;
8271 
8272 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
8273 		TAILQ_INIT(&V_sptree[i]);
8274 		TAILQ_INIT(&V_sptree_ifnet[i]);
8275 	}
8276 
8277 	V_key_lft_zone = uma_zcreate("IPsec SA lft_c",
8278 	    sizeof(uint64_t) * 2, NULL, NULL, NULL, NULL,
8279 	    UMA_ALIGN_PTR, UMA_ZONE_PCPU);
8280 
8281 	TAILQ_INIT(&V_sahtree);
8282 	V_sphashtbl = hashinit(SPHASH_NHASH, M_IPSEC_SP, &V_sphash_mask);
8283 	V_savhashtbl = hashinit(SAVHASH_NHASH, M_IPSEC_SA, &V_savhash_mask);
8284 	V_sahaddrhashtbl = hashinit(SAHHASH_NHASH, M_IPSEC_SAH,
8285 	    &V_sahaddrhash_mask);
8286 	V_acqaddrhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8287 	    &V_acqaddrhash_mask);
8288 	V_acqseqhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8289 	    &V_acqseqhash_mask);
8290 
8291 	spdcache_init();
8292 
8293 	for (i = 0; i <= SADB_SATYPE_MAX; i++)
8294 		LIST_INIT(&V_regtree[i]);
8295 
8296 	LIST_INIT(&V_acqtree);
8297 	LIST_INIT(&V_spacqtree);
8298 
8299 	if (!IS_DEFAULT_VNET(curvnet))
8300 		return;
8301 
8302 	SPTREE_LOCK_INIT();
8303 	REGTREE_LOCK_INIT();
8304 	SAHTREE_LOCK_INIT();
8305 	ACQ_LOCK_INIT();
8306 	SPACQ_LOCK_INIT();
8307 
8308 #ifndef IPSEC_DEBUG2
8309 	callout_init(&key_timer, 1);
8310 	callout_reset(&key_timer, hz, key_timehandler, NULL);
8311 #endif /*IPSEC_DEBUG2*/
8312 
8313 	/* initialize key statistics */
8314 	keystat.getspi_count = 1;
8315 
8316 	if (bootverbose)
8317 		printf("IPsec: Initialized Security Association Processing.\n");
8318 }
8319 
8320 #ifdef VIMAGE
8321 void
key_destroy(void)8322 key_destroy(void)
8323 {
8324 	struct secashead_queue sahdrainq;
8325 	struct secpolicy_queue drainq;
8326 	struct secpolicy *sp, *nextsp;
8327 	struct secacq *acq, *nextacq;
8328 	struct secspacq *spacq, *nextspacq;
8329 	struct secashead *sah;
8330 	struct secasvar *sav;
8331 	struct secreg *reg;
8332 	int i;
8333 
8334 	/*
8335 	 * XXX: can we just call free() for each object without
8336 	 * walking through safe way with releasing references?
8337 	 */
8338 	TAILQ_INIT(&drainq);
8339 	SPTREE_WLOCK();
8340 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
8341 		TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
8342 		TAILQ_CONCAT(&drainq, &V_sptree_ifnet[i], chain);
8343 	}
8344 	for (i = 0; i < V_sphash_mask + 1; i++)
8345 		LIST_INIT(&V_sphashtbl[i]);
8346 	SPTREE_WUNLOCK();
8347 	spdcache_destroy();
8348 
8349 	sp = TAILQ_FIRST(&drainq);
8350 	while (sp != NULL) {
8351 		nextsp = TAILQ_NEXT(sp, chain);
8352 		key_freesp(&sp);
8353 		sp = nextsp;
8354 	}
8355 
8356 	TAILQ_INIT(&sahdrainq);
8357 	SAHTREE_WLOCK();
8358 	TAILQ_CONCAT(&sahdrainq, &V_sahtree, chain);
8359 	for (i = 0; i < V_savhash_mask + 1; i++)
8360 		LIST_INIT(&V_savhashtbl[i]);
8361 	for (i = 0; i < V_sahaddrhash_mask + 1; i++)
8362 		LIST_INIT(&V_sahaddrhashtbl[i]);
8363 	TAILQ_FOREACH(sah, &sahdrainq, chain) {
8364 		sah->state = SADB_SASTATE_DEAD;
8365 		TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
8366 			sav->state = SADB_SASTATE_DEAD;
8367 		}
8368 		TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
8369 			sav->state = SADB_SASTATE_DEAD;
8370 		}
8371 	}
8372 	SAHTREE_WUNLOCK();
8373 
8374 	key_freesah_flushed(&sahdrainq);
8375 	hashdestroy(V_sphashtbl, M_IPSEC_SP, V_sphash_mask);
8376 	hashdestroy(V_savhashtbl, M_IPSEC_SA, V_savhash_mask);
8377 	hashdestroy(V_sahaddrhashtbl, M_IPSEC_SAH, V_sahaddrhash_mask);
8378 
8379 	REGTREE_LOCK();
8380 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
8381 		LIST_FOREACH(reg, &V_regtree[i], chain) {
8382 			if (__LIST_CHAINED(reg)) {
8383 				LIST_REMOVE(reg, chain);
8384 				free(reg, M_IPSEC_SAR);
8385 				break;
8386 			}
8387 		}
8388 	}
8389 	REGTREE_UNLOCK();
8390 
8391 	ACQ_LOCK();
8392 	acq = LIST_FIRST(&V_acqtree);
8393 	while (acq != NULL) {
8394 		nextacq = LIST_NEXT(acq, chain);
8395 		LIST_REMOVE(acq, chain);
8396 		free(acq, M_IPSEC_SAQ);
8397 		acq = nextacq;
8398 	}
8399 	for (i = 0; i < V_acqaddrhash_mask + 1; i++)
8400 		LIST_INIT(&V_acqaddrhashtbl[i]);
8401 	for (i = 0; i < V_acqseqhash_mask + 1; i++)
8402 		LIST_INIT(&V_acqseqhashtbl[i]);
8403 	ACQ_UNLOCK();
8404 
8405 	SPACQ_LOCK();
8406 	for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
8407 	    spacq = nextspacq) {
8408 		nextspacq = LIST_NEXT(spacq, chain);
8409 		if (__LIST_CHAINED(spacq)) {
8410 			LIST_REMOVE(spacq, chain);
8411 			free(spacq, M_IPSEC_SAQ);
8412 		}
8413 	}
8414 	SPACQ_UNLOCK();
8415 	hashdestroy(V_acqaddrhashtbl, M_IPSEC_SAQ, V_acqaddrhash_mask);
8416 	hashdestroy(V_acqseqhashtbl, M_IPSEC_SAQ, V_acqseqhash_mask);
8417 	uma_zdestroy(V_key_lft_zone);
8418 
8419 	if (!IS_DEFAULT_VNET(curvnet))
8420 		return;
8421 #ifndef IPSEC_DEBUG2
8422 	callout_drain(&key_timer);
8423 #endif
8424 	SPTREE_LOCK_DESTROY();
8425 	REGTREE_LOCK_DESTROY();
8426 	SAHTREE_LOCK_DESTROY();
8427 	ACQ_LOCK_DESTROY();
8428 	SPACQ_LOCK_DESTROY();
8429 }
8430 #endif
8431 
8432 /* record data transfer on SA, and update timestamps */
8433 void
key_sa_recordxfer(struct secasvar * sav,struct mbuf * m)8434 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
8435 {
8436 	IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
8437 	IPSEC_ASSERT(m != NULL, ("Null mbuf"));
8438 
8439 	/*
8440 	 * XXX Currently, there is a difference of bytes size
8441 	 * between inbound and outbound processing.
8442 	 */
8443 	counter_u64_add(sav->lft_c_bytes, m->m_pkthdr.len);
8444 
8445 	/*
8446 	 * We use the number of packets as the unit of
8447 	 * allocations.  We increment the variable
8448 	 * whenever {esp,ah}_{in,out}put is called.
8449 	 */
8450 	counter_u64_add(sav->lft_c_allocations, 1);
8451 
8452 	/*
8453 	 * NOTE: We record CURRENT usetime by using wall clock,
8454 	 * in seconds.  HARD and SOFT lifetime are measured by the time
8455 	 * difference (again in seconds) from usetime.
8456 	 *
8457 	 *	usetime
8458 	 *	v     expire   expire
8459 	 * -----+-----+--------+---> t
8460 	 *	<--------------> HARD
8461 	 *	<-----> SOFT
8462 	 */
8463 	if (sav->firstused == 0)
8464 		sav->firstused = time_second;
8465 }
8466 
8467 /*
8468  * Take one of the kernel's security keys and convert it into a PF_KEY
8469  * structure within an mbuf, suitable for sending up to a waiting
8470  * application in user land.
8471  *
8472  * IN:
8473  *    src: A pointer to a kernel security key.
8474  *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
8475  * OUT:
8476  *    a valid mbuf or NULL indicating an error
8477  *
8478  */
8479 
8480 static struct mbuf *
key_setkey(struct seckey * src,uint16_t exttype)8481 key_setkey(struct seckey *src, uint16_t exttype)
8482 {
8483 	struct mbuf *m;
8484 	struct sadb_key *p;
8485 	int len;
8486 
8487 	if (src == NULL)
8488 		return NULL;
8489 
8490 	len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8491 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8492 	if (m == NULL)
8493 		return NULL;
8494 	m_align(m, len);
8495 	m->m_len = len;
8496 	p = mtod(m, struct sadb_key *);
8497 	bzero(p, len);
8498 	p->sadb_key_len = PFKEY_UNIT64(len);
8499 	p->sadb_key_exttype = exttype;
8500 	p->sadb_key_bits = src->bits;
8501 	bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8502 
8503 	return m;
8504 }
8505 
8506 /*
8507  * Take one of the kernel's lifetime data structures and convert it
8508  * into a PF_KEY structure within an mbuf, suitable for sending up to
8509  * a waiting application in user land.
8510  *
8511  * IN:
8512  *    src: A pointer to a kernel lifetime structure.
8513  *    exttype: Which type of lifetime this is. Refer to the PF_KEY
8514  *             data structures for more information.
8515  * OUT:
8516  *    a valid mbuf or NULL indicating an error
8517  *
8518  */
8519 
8520 static struct mbuf *
key_setlifetime(struct seclifetime * src,uint16_t exttype)8521 key_setlifetime(struct seclifetime *src, uint16_t exttype)
8522 {
8523 	struct mbuf *m = NULL;
8524 	struct sadb_lifetime *p;
8525 	int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8526 
8527 	if (src == NULL)
8528 		return NULL;
8529 
8530 	m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8531 	if (m == NULL)
8532 		return m;
8533 	m_align(m, len);
8534 	m->m_len = len;
8535 	p = mtod(m, struct sadb_lifetime *);
8536 
8537 	bzero(p, len);
8538 	p->sadb_lifetime_len = PFKEY_UNIT64(len);
8539 	p->sadb_lifetime_exttype = exttype;
8540 	p->sadb_lifetime_allocations = src->allocations;
8541 	p->sadb_lifetime_bytes = src->bytes;
8542 	p->sadb_lifetime_addtime = src->addtime;
8543 	p->sadb_lifetime_usetime = src->usetime;
8544 
8545 	return m;
8546 
8547 }
8548 
8549 const struct enc_xform *
enc_algorithm_lookup(int alg)8550 enc_algorithm_lookup(int alg)
8551 {
8552 	int i;
8553 
8554 	for (i = 0; i < nitems(supported_ealgs); i++)
8555 		if (alg == supported_ealgs[i].sadb_alg)
8556 			return (supported_ealgs[i].xform);
8557 	return (NULL);
8558 }
8559 
8560 const struct auth_hash *
auth_algorithm_lookup(int alg)8561 auth_algorithm_lookup(int alg)
8562 {
8563 	int i;
8564 
8565 	for (i = 0; i < nitems(supported_aalgs); i++)
8566 		if (alg == supported_aalgs[i].sadb_alg)
8567 			return (supported_aalgs[i].xform);
8568 	return (NULL);
8569 }
8570 
8571 const struct comp_algo *
comp_algorithm_lookup(int alg)8572 comp_algorithm_lookup(int alg)
8573 {
8574 	int i;
8575 
8576 	for (i = 0; i < nitems(supported_calgs); i++)
8577 		if (alg == supported_calgs[i].sadb_alg)
8578 			return (supported_calgs[i].xform);
8579 	return (NULL);
8580 }
8581