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