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