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