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