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