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