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