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