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