]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/netipsec/key.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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                         SPTREE_LOCK();
1886                         newsp->state = IPSEC_SPSTATE_DEAD;
1887                         SPTREE_UNLOCK();
1888                         KEY_FREESP(&newsp);
1889                 }
1890         } else {
1891                 if (newsp != NULL) {
1892                         KEY_FREESP(&newsp);
1893                         ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1894                                 __func__));
1895                         return key_senderror(so, m, EEXIST);
1896                 }
1897         }
1898
1899         /* allocation new SP entry */
1900         if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1901                 return key_senderror(so, m, error);
1902         }
1903
1904         if ((newsp->id = key_getnewspid()) == 0) {
1905                 _key_delsp(newsp);
1906                 return key_senderror(so, m, ENOBUFS);
1907         }
1908
1909         /* XXX boundary check against sa_len */
1910         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1911                         src0 + 1,
1912                         dst0 + 1,
1913                         src0->sadb_address_prefixlen,
1914                         dst0->sadb_address_prefixlen,
1915                         src0->sadb_address_proto,
1916                         &newsp->spidx);
1917
1918         /* sanity check on addr pair */
1919         if (((struct sockaddr *)(src0 + 1))->sa_family !=
1920                         ((struct sockaddr *)(dst0+ 1))->sa_family) {
1921                 _key_delsp(newsp);
1922                 return key_senderror(so, m, EINVAL);
1923         }
1924         if (((struct sockaddr *)(src0 + 1))->sa_len !=
1925                         ((struct sockaddr *)(dst0+ 1))->sa_len) {
1926                 _key_delsp(newsp);
1927                 return key_senderror(so, m, EINVAL);
1928         }
1929 #if 1
1930         if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1931                 struct sockaddr *sa;
1932                 sa = (struct sockaddr *)(src0 + 1);
1933                 if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
1934                         _key_delsp(newsp);
1935                         return key_senderror(so, m, EINVAL);
1936                 }
1937         }
1938         if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1939                 struct sockaddr *sa;
1940                 sa = (struct sockaddr *)(dst0 + 1);
1941                 if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1942                         _key_delsp(newsp);
1943                         return key_senderror(so, m, EINVAL);
1944                 }
1945         }
1946 #endif
1947
1948         newsp->created = time_second;
1949         newsp->lastused = newsp->created;
1950         newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1951         newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1952
1953         newsp->refcnt = 1;      /* do not reclaim until I say I do */
1954         newsp->state = IPSEC_SPSTATE_ALIVE;
1955         LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1956
1957         /* delete the entry in spacqtree */
1958         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1959                 struct secspacq *spacq = key_getspacq(&spidx);
1960                 if (spacq != NULL) {
1961                         /* reset counter in order to deletion by timehandler. */
1962                         spacq->created = time_second;
1963                         spacq->count = 0;
1964                         SPACQ_UNLOCK();
1965                 }
1966         }
1967
1968     {
1969         struct mbuf *n, *mpolicy;
1970         struct sadb_msg *newmsg;
1971         int off;
1972
1973         /*
1974          * Note: do not send SADB_X_EXT_NAT_T_* here:
1975          * we are sending traffic endpoints.
1976          */
1977
1978         /* create new sadb_msg to reply. */
1979         if (lft) {
1980                 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1981                     SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1982                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1983         } else {
1984                 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1985                     SADB_X_EXT_POLICY,
1986                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1987         }
1988         if (!n)
1989                 return key_senderror(so, m, ENOBUFS);
1990
1991         if (n->m_len < sizeof(*newmsg)) {
1992                 n = m_pullup(n, sizeof(*newmsg));
1993                 if (!n)
1994                         return key_senderror(so, m, ENOBUFS);
1995         }
1996         newmsg = mtod(n, struct sadb_msg *);
1997         newmsg->sadb_msg_errno = 0;
1998         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1999
2000         off = 0;
2001         mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2002             sizeof(*xpl), &off);
2003         if (mpolicy == NULL) {
2004                 /* n is already freed */
2005                 return key_senderror(so, m, ENOBUFS);
2006         }
2007         xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
2008         if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2009                 m_freem(n);
2010                 return key_senderror(so, m, EINVAL);
2011         }
2012         xpl->sadb_x_policy_id = newsp->id;
2013
2014         m_freem(m);
2015         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2016     }
2017 }
2018
2019 /*
2020  * get new policy id.
2021  * OUT:
2022  *      0:      failure.
2023  *      others: success.
2024  */
2025 static u_int32_t
2026 key_getnewspid()
2027 {
2028         u_int32_t newid = 0;
2029         int count = V_key_spi_trycnt;   /* XXX */
2030         struct secpolicy *sp;
2031
2032         /* when requesting to allocate spi ranged */
2033         while (count--) {
2034                 newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2035
2036                 if ((sp = key_getspbyid(newid)) == NULL)
2037                         break;
2038
2039                 KEY_FREESP(&sp);
2040         }
2041
2042         if (count == 0 || newid == 0) {
2043                 ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2044                         __func__));
2045                 return 0;
2046         }
2047
2048         return newid;
2049 }
2050
2051 /*
2052  * SADB_SPDDELETE processing
2053  * receive
2054  *   <base, address(SD), policy(*)>
2055  * from the user(?), and set SADB_SASTATE_DEAD,
2056  * and send,
2057  *   <base, address(SD), policy(*)>
2058  * to the ikmpd.
2059  * policy(*) including direction of policy.
2060  *
2061  * m will always be freed.
2062  */
2063 static int
2064 key_spddelete(so, m, mhp)
2065         struct socket *so;
2066         struct mbuf *m;
2067         const struct sadb_msghdr *mhp;
2068 {
2069         struct sadb_address *src0, *dst0;
2070         struct sadb_x_policy *xpl0;
2071         struct secpolicyindex spidx;
2072         struct secpolicy *sp;
2073
2074         IPSEC_ASSERT(so != NULL, ("null so"));
2075         IPSEC_ASSERT(m != NULL, ("null mbuf"));
2076         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2077         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2078
2079         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2080             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2081             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2082                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2083                         __func__));
2084                 return key_senderror(so, m, EINVAL);
2085         }
2086         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2087             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2088             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2089                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2090                         __func__));
2091                 return key_senderror(so, m, EINVAL);
2092         }
2093
2094         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2095         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2096         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2097
2098         /*
2099          * Note: do not parse SADB_X_EXT_NAT_T_* here:
2100          * we are processing traffic endpoints.
2101          */
2102
2103         /* make secindex */
2104         /* XXX boundary check against sa_len */
2105         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2106                         src0 + 1,
2107                         dst0 + 1,
2108                         src0->sadb_address_prefixlen,
2109                         dst0->sadb_address_prefixlen,
2110                         src0->sadb_address_proto,
2111                         &spidx);
2112
2113         /* checking the direciton. */
2114         switch (xpl0->sadb_x_policy_dir) {
2115         case IPSEC_DIR_INBOUND:
2116         case IPSEC_DIR_OUTBOUND:
2117                 break;
2118         default:
2119                 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2120                 return key_senderror(so, m, EINVAL);
2121         }
2122
2123         /* Is there SP in SPD ? */
2124         if ((sp = key_getsp(&spidx)) == NULL) {
2125                 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2126                 return key_senderror(so, m, EINVAL);
2127         }
2128
2129         /* save policy id to buffer to be returned. */
2130         xpl0->sadb_x_policy_id = sp->id;
2131
2132         SPTREE_LOCK();
2133         sp->state = IPSEC_SPSTATE_DEAD;
2134         SPTREE_UNLOCK();
2135         KEY_FREESP(&sp);
2136
2137     {
2138         struct mbuf *n;
2139         struct sadb_msg *newmsg;
2140
2141         /*
2142          * Note: do not send SADB_X_EXT_NAT_T_* here:
2143          * we are sending traffic endpoints.
2144          */
2145
2146         /* create new sadb_msg to reply. */
2147         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2148             SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2149         if (!n)
2150                 return key_senderror(so, m, ENOBUFS);
2151
2152         newmsg = mtod(n, struct sadb_msg *);
2153         newmsg->sadb_msg_errno = 0;
2154         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2155
2156         m_freem(m);
2157         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2158     }
2159 }
2160
2161 /*
2162  * SADB_SPDDELETE2 processing
2163  * receive
2164  *   <base, policy(*)>
2165  * from the user(?), and set SADB_SASTATE_DEAD,
2166  * and send,
2167  *   <base, policy(*)>
2168  * to the ikmpd.
2169  * policy(*) including direction of policy.
2170  *
2171  * m will always be freed.
2172  */
2173 static int
2174 key_spddelete2(so, m, mhp)
2175         struct socket *so;
2176         struct mbuf *m;
2177         const struct sadb_msghdr *mhp;
2178 {
2179         u_int32_t id;
2180         struct secpolicy *sp;
2181
2182         IPSEC_ASSERT(so != NULL, ("null socket"));
2183         IPSEC_ASSERT(m != NULL, ("null mbuf"));
2184         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2185         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2186
2187         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2188             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2189                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2190                 return key_senderror(so, m, EINVAL);
2191         }
2192
2193         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2194
2195         /* Is there SP in SPD ? */
2196         if ((sp = key_getspbyid(id)) == NULL) {
2197                 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2198                 return key_senderror(so, m, EINVAL);
2199         }
2200
2201         SPTREE_LOCK();
2202         sp->state = IPSEC_SPSTATE_DEAD;
2203         SPTREE_UNLOCK();
2204         KEY_FREESP(&sp);
2205
2206     {
2207         struct mbuf *n, *nn;
2208         struct sadb_msg *newmsg;
2209         int off, len;
2210
2211         /* create new sadb_msg to reply. */
2212         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2213
2214         MGETHDR(n, M_DONTWAIT, MT_DATA);
2215         if (n && len > MHLEN) {
2216                 MCLGET(n, M_DONTWAIT);
2217                 if ((n->m_flags & M_EXT) == 0) {
2218                         m_freem(n);
2219                         n = NULL;
2220                 }
2221         }
2222         if (!n)
2223                 return key_senderror(so, m, ENOBUFS);
2224
2225         n->m_len = len;
2226         n->m_next = NULL;
2227         off = 0;
2228
2229         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2230         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2231
2232         IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2233                 off, len));
2234
2235         n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2236             mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2237         if (!n->m_next) {
2238                 m_freem(n);
2239                 return key_senderror(so, m, ENOBUFS);
2240         }
2241
2242         n->m_pkthdr.len = 0;
2243         for (nn = n; nn; nn = nn->m_next)
2244                 n->m_pkthdr.len += nn->m_len;
2245
2246         newmsg = mtod(n, struct sadb_msg *);
2247         newmsg->sadb_msg_errno = 0;
2248         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2249
2250         m_freem(m);
2251         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2252     }
2253 }
2254
2255 /*
2256  * SADB_X_GET processing
2257  * receive
2258  *   <base, policy(*)>
2259  * from the user(?),
2260  * and send,
2261  *   <base, address(SD), policy>
2262  * to the ikmpd.
2263  * policy(*) including direction of policy.
2264  *
2265  * m will always be freed.
2266  */
2267 static int
2268 key_spdget(so, m, mhp)
2269         struct socket *so;
2270         struct mbuf *m;
2271         const struct sadb_msghdr *mhp;
2272 {
2273         u_int32_t id;
2274         struct secpolicy *sp;
2275         struct mbuf *n;
2276
2277         IPSEC_ASSERT(so != NULL, ("null socket"));
2278         IPSEC_ASSERT(m != NULL, ("null mbuf"));
2279         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2280         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2281
2282         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2283             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2284                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2285                         __func__));
2286                 return key_senderror(so, m, EINVAL);
2287         }
2288
2289         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2290
2291         /* Is there SP in SPD ? */
2292         if ((sp = key_getspbyid(id)) == NULL) {
2293                 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2294                 return key_senderror(so, m, ENOENT);
2295         }
2296
2297         n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2298         if (n != NULL) {
2299                 m_freem(m);
2300                 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2301         } else
2302                 return key_senderror(so, m, ENOBUFS);
2303 }
2304
2305 /*
2306  * SADB_X_SPDACQUIRE processing.
2307  * Acquire policy and SA(s) for a *OUTBOUND* packet.
2308  * send
2309  *   <base, policy(*)>
2310  * to KMD, and expect to receive
2311  *   <base> with SADB_X_SPDACQUIRE if error occured,
2312  * or
2313  *   <base, policy>
2314  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2315  * policy(*) is without policy requests.
2316  *
2317  *    0     : succeed
2318  *    others: error number
2319  */
2320 int
2321 key_spdacquire(sp)
2322         struct secpolicy *sp;
2323 {
2324         struct mbuf *result = NULL, *m;
2325         struct secspacq *newspacq;
2326
2327         IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2328         IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2329         IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2330                 ("policy not IPSEC %u", sp->policy));
2331
2332         /* Get an entry to check whether sent message or not. */
2333         newspacq = key_getspacq(&sp->spidx);
2334         if (newspacq != NULL) {
2335                 if (V_key_blockacq_count < newspacq->count) {
2336                         /* reset counter and do send message. */
2337                         newspacq->count = 0;
2338                 } else {
2339                         /* increment counter and do nothing. */
2340                         newspacq->count++;
2341                         return 0;
2342                 }
2343                 SPACQ_UNLOCK();
2344         } else {
2345                 /* make new entry for blocking to send SADB_ACQUIRE. */
2346                 newspacq = key_newspacq(&sp->spidx);
2347                 if (newspacq == NULL)
2348                         return ENOBUFS;
2349         }
2350
2351         /* create new sadb_msg to reply. */
2352         m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2353         if (!m)
2354                 return ENOBUFS;
2355
2356         result = m;
2357
2358         result->m_pkthdr.len = 0;
2359         for (m = result; m; m = m->m_next)
2360                 result->m_pkthdr.len += m->m_len;
2361
2362         mtod(result, struct sadb_msg *)->sadb_msg_len =
2363             PFKEY_UNIT64(result->m_pkthdr.len);
2364
2365         return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2366 }
2367
2368 /*
2369  * SADB_SPDFLUSH processing
2370  * receive
2371  *   <base>
2372  * from the user, and free all entries in secpctree.
2373  * and send,
2374  *   <base>
2375  * to the user.
2376  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2377  *
2378  * m will always be freed.
2379  */
2380 static int
2381 key_spdflush(so, m, mhp)
2382         struct socket *so;
2383         struct mbuf *m;
2384         const struct sadb_msghdr *mhp;
2385 {
2386         struct sadb_msg *newmsg;
2387         struct secpolicy *sp;
2388         u_int dir;
2389
2390         IPSEC_ASSERT(so != NULL, ("null socket"));
2391         IPSEC_ASSERT(m != NULL, ("null mbuf"));
2392         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2393         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2394
2395         if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2396                 return key_senderror(so, m, EINVAL);
2397
2398         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2399                 SPTREE_LOCK();
2400                 LIST_FOREACH(sp, &V_sptree[dir], chain)
2401                         sp->state = IPSEC_SPSTATE_DEAD;
2402                 SPTREE_UNLOCK();
2403         }
2404
2405         if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2406                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2407                 return key_senderror(so, m, ENOBUFS);
2408         }
2409
2410         if (m->m_next)
2411                 m_freem(m->m_next);
2412         m->m_next = NULL;
2413         m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2414         newmsg = mtod(m, struct sadb_msg *);
2415         newmsg->sadb_msg_errno = 0;
2416         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2417
2418         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2419 }
2420
2421 /*
2422  * SADB_SPDDUMP processing
2423  * receive
2424  *   <base>
2425  * from the user, and dump all SP leaves
2426  * and send,
2427  *   <base> .....
2428  * to the ikmpd.
2429  *
2430  * m will always be freed.
2431  */
2432 static int
2433 key_spddump(so, m, mhp)
2434         struct socket *so;
2435         struct mbuf *m;
2436         const struct sadb_msghdr *mhp;
2437 {
2438         struct secpolicy *sp;
2439         int cnt;
2440         u_int dir;
2441         struct mbuf *n;
2442
2443         IPSEC_ASSERT(so != NULL, ("null socket"));
2444         IPSEC_ASSERT(m != NULL, ("null mbuf"));
2445         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2446         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2447
2448         /* search SPD entry and get buffer size. */
2449         cnt = 0;
2450         SPTREE_LOCK();
2451         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2452                 LIST_FOREACH(sp, &V_sptree[dir], chain) {
2453                         cnt++;
2454                 }
2455         }
2456
2457         if (cnt == 0) {
2458                 SPTREE_UNLOCK();
2459                 return key_senderror(so, m, ENOENT);
2460         }
2461
2462         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2463                 LIST_FOREACH(sp, &V_sptree[dir], chain) {
2464                         --cnt;
2465                         n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2466                             mhp->msg->sadb_msg_pid);
2467
2468                         if (n)
2469                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2470                 }
2471         }
2472
2473         SPTREE_UNLOCK();
2474         m_freem(m);
2475         return 0;
2476 }
2477
2478 static struct mbuf *
2479 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2480 {
2481         struct mbuf *result = NULL, *m;
2482         struct seclifetime lt;
2483
2484         m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2485         if (!m)
2486                 goto fail;
2487         result = m;
2488
2489         /*
2490          * Note: do not send SADB_X_EXT_NAT_T_* here:
2491          * we are sending traffic endpoints.
2492          */
2493         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2494             &sp->spidx.src.sa, sp->spidx.prefs,
2495             sp->spidx.ul_proto);
2496         if (!m)
2497                 goto fail;
2498         m_cat(result, m);
2499
2500         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2501             &sp->spidx.dst.sa, sp->spidx.prefd,
2502             sp->spidx.ul_proto);
2503         if (!m)
2504                 goto fail;
2505         m_cat(result, m);
2506
2507         m = key_sp2msg(sp);
2508         if (!m)
2509                 goto fail;
2510         m_cat(result, m);
2511
2512         if(sp->lifetime){
2513                 lt.addtime=sp->created;
2514                 lt.usetime= sp->lastused;
2515                 m = key_setlifetime(&lt, SADB_EXT_LIFETIME_CURRENT);
2516                 if (!m)
2517                         goto fail;
2518                 m_cat(result, m);
2519                 
2520                 lt.addtime=sp->lifetime;
2521                 lt.usetime= sp->validtime;
2522                 m = key_setlifetime(&lt, SADB_EXT_LIFETIME_HARD);
2523                 if (!m)
2524                         goto fail;
2525                 m_cat(result, m);
2526         }
2527
2528         if ((result->m_flags & M_PKTHDR) == 0)
2529                 goto fail;
2530
2531         if (result->m_len < sizeof(struct sadb_msg)) {
2532                 result = m_pullup(result, sizeof(struct sadb_msg));
2533                 if (result == NULL)
2534                         goto fail;
2535         }
2536
2537         result->m_pkthdr.len = 0;
2538         for (m = result; m; m = m->m_next)
2539                 result->m_pkthdr.len += m->m_len;
2540
2541         mtod(result, struct sadb_msg *)->sadb_msg_len =
2542             PFKEY_UNIT64(result->m_pkthdr.len);
2543
2544         return result;
2545
2546 fail:
2547         m_freem(result);
2548         return NULL;
2549 }
2550
2551 /*
2552  * get PFKEY message length for security policy and request.
2553  */
2554 static u_int
2555 key_getspreqmsglen(sp)
2556         struct secpolicy *sp;
2557 {
2558         u_int tlen;
2559
2560         tlen = sizeof(struct sadb_x_policy);
2561
2562         /* if is the policy for ipsec ? */
2563         if (sp->policy != IPSEC_POLICY_IPSEC)
2564                 return tlen;
2565
2566         /* get length of ipsec requests */
2567     {
2568         struct ipsecrequest *isr;
2569         int len;
2570
2571         for (isr = sp->req; isr != NULL; isr = isr->next) {
2572                 len = sizeof(struct sadb_x_ipsecrequest)
2573                         + isr->saidx.src.sa.sa_len
2574                         + isr->saidx.dst.sa.sa_len;
2575
2576                 tlen += PFKEY_ALIGN8(len);
2577         }
2578     }
2579
2580         return tlen;
2581 }
2582
2583 /*
2584  * SADB_SPDEXPIRE processing
2585  * send
2586  *   <base, address(SD), lifetime(CH), policy>
2587  * to KMD by PF_KEY.
2588  *
2589  * OUT: 0       : succeed
2590  *      others  : error number
2591  */
2592 static int
2593 key_spdexpire(sp)
2594         struct secpolicy *sp;
2595 {
2596         struct mbuf *result = NULL, *m;
2597         int len;
2598         int error = -1;
2599         struct sadb_lifetime *lt;
2600
2601         /* XXX: Why do we lock ? */
2602
2603         IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2604
2605         /* set msg header */
2606         m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2607         if (!m) {
2608                 error = ENOBUFS;
2609                 goto fail;
2610         }
2611         result = m;
2612
2613         /* create lifetime extension (current and hard) */
2614         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2615         m = key_alloc_mbuf(len);
2616         if (!m || m->m_next) {  /*XXX*/
2617                 if (m)
2618                         m_freem(m);
2619                 error = ENOBUFS;
2620                 goto fail;
2621         }
2622         bzero(mtod(m, caddr_t), len);
2623         lt = mtod(m, struct sadb_lifetime *);
2624         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2625         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2626         lt->sadb_lifetime_allocations = 0;
2627         lt->sadb_lifetime_bytes = 0;
2628         lt->sadb_lifetime_addtime = sp->created;
2629         lt->sadb_lifetime_usetime = sp->lastused;
2630         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2631         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2632         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2633         lt->sadb_lifetime_allocations = 0;
2634         lt->sadb_lifetime_bytes = 0;
2635         lt->sadb_lifetime_addtime = sp->lifetime;
2636         lt->sadb_lifetime_usetime = sp->validtime;
2637         m_cat(result, m);
2638
2639         /*
2640          * Note: do not send SADB_X_EXT_NAT_T_* here:
2641          * we are sending traffic endpoints.
2642          */
2643
2644         /* set sadb_address for source */
2645         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2646             &sp->spidx.src.sa,
2647             sp->spidx.prefs, sp->spidx.ul_proto);
2648         if (!m) {
2649                 error = ENOBUFS;
2650                 goto fail;
2651         }
2652         m_cat(result, m);
2653
2654         /* set sadb_address for destination */
2655         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2656             &sp->spidx.dst.sa,
2657             sp->spidx.prefd, sp->spidx.ul_proto);
2658         if (!m) {
2659                 error = ENOBUFS;
2660                 goto fail;
2661         }
2662         m_cat(result, m);
2663
2664         /* set secpolicy */
2665         m = key_sp2msg(sp);
2666         if (!m) {
2667                 error = ENOBUFS;
2668                 goto fail;
2669         }
2670         m_cat(result, m);
2671
2672         if ((result->m_flags & M_PKTHDR) == 0) {
2673                 error = EINVAL;
2674                 goto fail;
2675         }
2676
2677         if (result->m_len < sizeof(struct sadb_msg)) {
2678                 result = m_pullup(result, sizeof(struct sadb_msg));
2679                 if (result == NULL) {
2680                         error = ENOBUFS;
2681                         goto fail;
2682                 }
2683         }
2684
2685         result->m_pkthdr.len = 0;
2686         for (m = result; m; m = m->m_next)
2687                 result->m_pkthdr.len += m->m_len;
2688
2689         mtod(result, struct sadb_msg *)->sadb_msg_len =
2690             PFKEY_UNIT64(result->m_pkthdr.len);
2691
2692         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2693
2694  fail:
2695         if (result)
2696                 m_freem(result);
2697         return error;
2698 }
2699
2700 /* %%% SAD management */
2701 /*
2702  * allocating a memory for new SA head, and copy from the values of mhp.
2703  * OUT: NULL    : failure due to the lack of memory.
2704  *      others  : pointer to new SA head.
2705  */
2706 static struct secashead *
2707 key_newsah(saidx)
2708         struct secasindex *saidx;
2709 {
2710         struct secashead *newsah;
2711
2712         IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2713
2714         newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2715         if (newsah != NULL) {
2716                 int i;
2717                 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2718                         LIST_INIT(&newsah->savtree[i]);
2719                 newsah->saidx = *saidx;
2720
2721                 /* add to saidxtree */
2722                 newsah->state = SADB_SASTATE_MATURE;
2723
2724                 SAHTREE_LOCK();
2725                 LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2726                 SAHTREE_UNLOCK();
2727         }
2728         return(newsah);
2729 }
2730
2731 /*
2732  * delete SA index and all SA registerd.
2733  */
2734 static void
2735 key_delsah(sah)
2736         struct secashead *sah;
2737 {
2738         struct secasvar *sav, *nextsav;
2739         u_int stateidx;
2740         int zombie = 0;
2741
2742         IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2743         SAHTREE_LOCK_ASSERT();
2744
2745         /* searching all SA registerd in the secindex. */
2746         for (stateidx = 0;
2747              stateidx < _ARRAYLEN(saorder_state_any);
2748              stateidx++) {
2749                 u_int state = saorder_state_any[stateidx];
2750                 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2751                         if (sav->refcnt == 0) {
2752                                 /* sanity check */
2753                                 KEY_CHKSASTATE(state, sav->state, __func__);
2754                                 /* 
2755                                  * do NOT call KEY_FREESAV here:
2756                                  * it will only delete the sav if refcnt == 1,
2757                                  * where we already know that refcnt == 0
2758                                  */
2759                                 key_delsav(sav);
2760                         } else {
2761                                 /* give up to delete this sa */
2762                                 zombie++;
2763                         }
2764                 }
2765         }
2766         if (!zombie) {          /* delete only if there are savs */
2767                 /* remove from tree of SA index */
2768                 if (__LIST_CHAINED(sah))
2769                         LIST_REMOVE(sah, chain);
2770                 if (sah->sa_route.ro_rt) {
2771                         RTFREE(sah->sa_route.ro_rt);
2772                         sah->sa_route.ro_rt = (struct rtentry *)NULL;
2773                 }
2774                 free(sah, M_IPSEC_SAH);
2775         }
2776 }
2777
2778 /*
2779  * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2780  * and copy the values of mhp into new buffer.
2781  * When SAD message type is GETSPI:
2782  *      to set sequence number from acq_seq++,
2783  *      to set zero to SPI.
2784  *      not to call key_setsava().
2785  * OUT: NULL    : fail
2786  *      others  : pointer to new secasvar.
2787  *
2788  * does not modify mbuf.  does not free mbuf on error.
2789  */
2790 static struct secasvar *
2791 key_newsav(m, mhp, sah, errp, where, tag)
2792         struct mbuf *m;
2793         const struct sadb_msghdr *mhp;
2794         struct secashead *sah;
2795         int *errp;
2796         const char* where;
2797         int tag;
2798 {
2799         struct secasvar *newsav;
2800         const struct sadb_sa *xsa;
2801
2802         IPSEC_ASSERT(m != NULL, ("null mbuf"));
2803         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2804         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2805         IPSEC_ASSERT(sah != NULL, ("null secashead"));
2806
2807         newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2808         if (newsav == NULL) {
2809                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2810                 *errp = ENOBUFS;
2811                 goto done;
2812         }
2813
2814         switch (mhp->msg->sadb_msg_type) {
2815         case SADB_GETSPI:
2816                 newsav->spi = 0;
2817
2818 #ifdef IPSEC_DOSEQCHECK
2819                 /* sync sequence number */
2820                 if (mhp->msg->sadb_msg_seq == 0)
2821                         newsav->seq =
2822                                 (V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2823                 else
2824 #endif
2825                         newsav->seq = mhp->msg->sadb_msg_seq;
2826                 break;
2827
2828         case SADB_ADD:
2829                 /* sanity check */
2830                 if (mhp->ext[SADB_EXT_SA] == NULL) {
2831                         free(newsav, M_IPSEC_SA);
2832                         newsav = NULL;
2833                         ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2834                                 __func__));
2835                         *errp = EINVAL;
2836                         goto done;
2837                 }
2838                 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2839                 newsav->spi = xsa->sadb_sa_spi;
2840                 newsav->seq = mhp->msg->sadb_msg_seq;
2841                 break;
2842         default:
2843                 free(newsav, M_IPSEC_SA);
2844                 newsav = NULL;
2845                 *errp = EINVAL;
2846                 goto done;
2847         }
2848
2849
2850         /* copy sav values */
2851         if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2852                 *errp = key_setsaval(newsav, m, mhp);
2853                 if (*errp) {
2854                         free(newsav, M_IPSEC_SA);
2855                         newsav = NULL;
2856                         goto done;
2857                 }
2858         }
2859
2860         SECASVAR_LOCK_INIT(newsav);
2861
2862         /* reset created */
2863         newsav->created = time_second;
2864         newsav->pid = mhp->msg->sadb_msg_pid;
2865
2866         /* add to satree */
2867         newsav->sah = sah;
2868         sa_initref(newsav);
2869         newsav->state = SADB_SASTATE_LARVAL;
2870
2871         /* XXX locking??? */
2872         LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2873                         secasvar, chain);
2874 done:
2875         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2876                 printf("DP %s from %s:%u return SP:%p\n", __func__,
2877                         where, tag, newsav));
2878
2879         return newsav;
2880 }
2881
2882 /*
2883  * free() SA variable entry.
2884  */
2885 static void
2886 key_cleansav(struct secasvar *sav)
2887 {
2888         /*
2889          * Cleanup xform state.  Note that zeroize'ing causes the
2890          * keys to be cleared; otherwise we must do it ourself.
2891          */
2892         if (sav->tdb_xform != NULL) {
2893                 sav->tdb_xform->xf_zeroize(sav);
2894                 sav->tdb_xform = NULL;
2895         } else {
2896                 KASSERT(sav->iv == NULL, ("iv but no xform"));
2897                 if (sav->key_auth != NULL)
2898                         bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2899                 if (sav->key_enc != NULL)
2900                         bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2901         }
2902         if (sav->key_auth != NULL) {
2903                 if (sav->key_auth->key_data != NULL)
2904                         free(sav->key_auth->key_data, M_IPSEC_MISC);
2905                 free(sav->key_auth, M_IPSEC_MISC);
2906                 sav->key_auth = NULL;
2907         }
2908         if (sav->key_enc != NULL) {
2909                 if (sav->key_enc->key_data != NULL)
2910                         free(sav->key_enc->key_data, M_IPSEC_MISC);
2911                 free(sav->key_enc, M_IPSEC_MISC);
2912                 sav->key_enc = NULL;
2913         }
2914         if (sav->sched) {
2915                 bzero(sav->sched, sav->schedlen);
2916                 free(sav->sched, M_IPSEC_MISC);
2917                 sav->sched = NULL;
2918         }
2919         if (sav->replay != NULL) {
2920                 free(sav->replay, M_IPSEC_MISC);
2921                 sav->replay = NULL;
2922         }
2923         if (sav->lft_c != NULL) {
2924                 free(sav->lft_c, M_IPSEC_MISC);
2925                 sav->lft_c = NULL;
2926         }
2927         if (sav->lft_h != NULL) {
2928                 free(sav->lft_h, M_IPSEC_MISC);
2929                 sav->lft_h = NULL;
2930         }
2931         if (sav->lft_s != NULL) {
2932                 free(sav->lft_s, M_IPSEC_MISC);
2933                 sav->lft_s = NULL;
2934         }
2935 }
2936
2937 /*
2938  * free() SA variable entry.
2939  */
2940 static void
2941 key_delsav(sav)
2942         struct secasvar *sav;
2943 {
2944         IPSEC_ASSERT(sav != NULL, ("null sav"));
2945         IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2946
2947         /* remove from SA header */
2948         if (__LIST_CHAINED(sav))
2949                 LIST_REMOVE(sav, chain);
2950         key_cleansav(sav);
2951         SECASVAR_LOCK_DESTROY(sav);
2952         free(sav, M_IPSEC_SA);
2953 }
2954
2955 /*
2956  * search SAD.
2957  * OUT:
2958  *      NULL    : not found
2959  *      others  : found, pointer to a SA.
2960  */
2961 static struct secashead *
2962 key_getsah(saidx)
2963         struct secasindex *saidx;
2964 {
2965         struct secashead *sah;
2966
2967         SAHTREE_LOCK();
2968         LIST_FOREACH(sah, &V_sahtree, chain) {
2969                 if (sah->state == SADB_SASTATE_DEAD)
2970                         continue;
2971                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2972                         break;
2973         }
2974         SAHTREE_UNLOCK();
2975
2976         return sah;
2977 }
2978
2979 /*
2980  * check not to be duplicated SPI.
2981  * NOTE: this function is too slow due to searching all SAD.
2982  * OUT:
2983  *      NULL    : not found
2984  *      others  : found, pointer to a SA.
2985  */
2986 static struct secasvar *
2987 key_checkspidup(saidx, spi)
2988         struct secasindex *saidx;
2989         u_int32_t spi;
2990 {
2991         struct secashead *sah;
2992         struct secasvar *sav;
2993
2994         /* check address family */
2995         if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2996                 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2997                         __func__));
2998                 return NULL;
2999         }
3000
3001         sav = NULL;
3002         /* check all SAD */
3003         SAHTREE_LOCK();
3004         LIST_FOREACH(sah, &V_sahtree, chain) {
3005                 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
3006                         continue;
3007                 sav = key_getsavbyspi(sah, spi);
3008                 if (sav != NULL)
3009                         break;
3010         }
3011         SAHTREE_UNLOCK();
3012
3013         return sav;
3014 }
3015
3016 /*
3017  * search SAD litmited alive SA, protocol, SPI.
3018  * OUT:
3019  *      NULL    : not found
3020  *      others  : found, pointer to a SA.
3021  */
3022 static struct secasvar *
3023 key_getsavbyspi(sah, spi)
3024         struct secashead *sah;
3025         u_int32_t spi;
3026 {
3027         struct secasvar *sav;
3028         u_int stateidx, state;
3029
3030         sav = NULL;
3031         SAHTREE_LOCK_ASSERT();
3032         /* search all status */
3033         for (stateidx = 0;
3034              stateidx < _ARRAYLEN(saorder_state_alive);
3035              stateidx++) {
3036
3037                 state = saorder_state_alive[stateidx];
3038                 LIST_FOREACH(sav, &sah->savtree[state], chain) {
3039
3040                         /* sanity check */
3041                         if (sav->state != state) {
3042                                 ipseclog((LOG_DEBUG, "%s: "
3043                                     "invalid sav->state (queue: %d SA: %d)\n",
3044                                     __func__, state, sav->state));
3045                                 continue;
3046                         }
3047
3048                         if (sav->spi == spi)
3049                                 return sav;
3050                 }
3051         }
3052
3053         return NULL;
3054 }
3055
3056 /*
3057  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3058  * You must update these if need.
3059  * OUT: 0:      success.
3060  *      !0:     failure.
3061  *
3062  * does not modify mbuf.  does not free mbuf on error.
3063  */
3064 static int
3065 key_setsaval(sav, m, mhp)
3066         struct secasvar *sav;
3067         struct mbuf *m;
3068         const struct sadb_msghdr *mhp;
3069 {
3070         int error = 0;
3071
3072         IPSEC_ASSERT(m != NULL, ("null mbuf"));
3073         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3074         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3075
3076         /* initialization */
3077         sav->replay = NULL;
3078         sav->key_auth = NULL;
3079         sav->key_enc = NULL;
3080         sav->sched = NULL;
3081         sav->schedlen = 0;
3082         sav->iv = NULL;
3083         sav->lft_c = NULL;
3084         sav->lft_h = NULL;
3085         sav->lft_s = NULL;
3086         sav->tdb_xform = NULL;          /* transform */
3087         sav->tdb_encalgxform = NULL;    /* encoding algorithm */
3088         sav->tdb_authalgxform = NULL;   /* authentication algorithm */
3089         sav->tdb_compalgxform = NULL;   /* compression algorithm */
3090         /*  Initialize even if NAT-T not compiled in: */
3091         sav->natt_type = 0;
3092         sav->natt_esp_frag_len = 0;
3093
3094         /* SA */
3095         if (mhp->ext[SADB_EXT_SA] != NULL) {
3096                 const struct sadb_sa *sa0;
3097
3098                 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3099                 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3100                         error = EINVAL;
3101                         goto fail;
3102                 }
3103
3104                 sav->alg_auth = sa0->sadb_sa_auth;
3105                 sav->alg_enc = sa0->sadb_sa_encrypt;
3106                 sav->flags = sa0->sadb_sa_flags;
3107
3108                 /* replay window */
3109                 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3110                         sav->replay = (struct secreplay *)
3111                                 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3112                         if (sav->replay == NULL) {
3113                                 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3114                                         __func__));
3115                                 error = ENOBUFS;
3116                                 goto fail;
3117                         }
3118                         if (sa0->sadb_sa_replay != 0)
3119                                 sav->replay->bitmap = (caddr_t)(sav->replay+1);
3120                         sav->replay->wsize = sa0->sadb_sa_replay;
3121                 }
3122         }
3123
3124         /* Authentication keys */
3125         if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3126                 const struct sadb_key *key0;
3127                 int len;
3128
3129                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3130                 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3131
3132                 error = 0;
3133                 if (len < sizeof(*key0)) {
3134                         error = EINVAL;
3135                         goto fail;
3136                 }
3137                 switch (mhp->msg->sadb_msg_satype) {
3138                 case SADB_SATYPE_AH:
3139                 case SADB_SATYPE_ESP:
3140                 case SADB_X_SATYPE_TCPSIGNATURE:
3141                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3142                             sav->alg_auth != SADB_X_AALG_NULL)
3143                                 error = EINVAL;
3144                         break;
3145                 case SADB_X_SATYPE_IPCOMP:
3146                 default:
3147                         error = EINVAL;
3148                         break;
3149                 }
3150                 if (error) {
3151                         ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3152                                 __func__));
3153                         goto fail;
3154                 }
3155
3156                 sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3157                                                                 M_IPSEC_MISC);
3158                 if (sav->key_auth == NULL ) {
3159                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3160                                   __func__));
3161                         error = ENOBUFS;
3162                         goto fail;
3163                 }
3164         }
3165
3166         /* Encryption key */
3167         if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3168                 const struct sadb_key *key0;
3169                 int len;
3170
3171                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3172                 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3173
3174                 error = 0;
3175                 if (len < sizeof(*key0)) {
3176                         error = EINVAL;
3177                         goto fail;
3178                 }
3179                 switch (mhp->msg->sadb_msg_satype) {
3180                 case SADB_SATYPE_ESP:
3181                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3182                             sav->alg_enc != SADB_EALG_NULL) {
3183                                 error = EINVAL;
3184                                 break;
3185                         }
3186                         sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3187                                                                        len,
3188                                                                        M_IPSEC_MISC);
3189                         if (sav->key_enc == NULL) {
3190                                 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3191                                         __func__));
3192                                 error = ENOBUFS;
3193                                 goto fail;
3194                         }
3195                         break;
3196                 case SADB_X_SATYPE_IPCOMP:
3197                         if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3198                                 error = EINVAL;
3199                         sav->key_enc = NULL;    /*just in case*/
3200                         break;
3201                 case SADB_SATYPE_AH:
3202                 case SADB_X_SATYPE_TCPSIGNATURE:
3203                 default:
3204                         error = EINVAL;
3205                         break;
3206                 }
3207                 if (error) {
3208                         ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3209                                 __func__));
3210                         goto fail;
3211                 }
3212         }
3213
3214         /* set iv */
3215         sav->ivlen = 0;
3216
3217         switch (mhp->msg->sadb_msg_satype) {
3218         case SADB_SATYPE_AH:
3219                 error = xform_init(sav, XF_AH);
3220                 break;
3221         case SADB_SATYPE_ESP:
3222                 error = xform_init(sav, XF_ESP);
3223                 break;
3224         case SADB_X_SATYPE_IPCOMP:
3225                 error = xform_init(sav, XF_IPCOMP);
3226                 break;
3227         case SADB_X_SATYPE_TCPSIGNATURE:
3228                 error = xform_init(sav, XF_TCPSIGNATURE);
3229                 break;
3230         }
3231         if (error) {
3232                 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3233                         __func__, mhp->msg->sadb_msg_satype));
3234                 goto fail;
3235         }
3236
3237         /* reset created */
3238         sav->created = time_second;
3239
3240         /* make lifetime for CURRENT */
3241         sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3242         if (sav->lft_c == NULL) {
3243                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3244                 error = ENOBUFS;
3245                 goto fail;
3246         }
3247
3248         sav->lft_c->allocations = 0;
3249         sav->lft_c->bytes = 0;
3250         sav->lft_c->addtime = time_second;
3251         sav->lft_c->usetime = 0;
3252
3253         /* lifetimes for HARD and SOFT */
3254     {
3255         const struct sadb_lifetime *lft0;
3256
3257         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3258         if (lft0 != NULL) {
3259                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3260                         error = EINVAL;
3261                         goto fail;
3262                 }
3263                 sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3264                 if (sav->lft_h == NULL) {
3265                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3266                         error = ENOBUFS;
3267                         goto fail;
3268                 }
3269                 /* to be initialize ? */
3270         }
3271
3272         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3273         if (lft0 != NULL) {
3274                 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3275                         error = EINVAL;
3276                         goto fail;
3277                 }
3278                 sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3279                 if (sav->lft_s == NULL) {
3280                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3281                         error = ENOBUFS;
3282                         goto fail;
3283                 }
3284                 /* to be initialize ? */
3285         }
3286     }
3287
3288         return 0;
3289
3290  fail:
3291         /* initialization */
3292         key_cleansav(sav);
3293
3294         return error;
3295 }
3296
3297 /*
3298  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3299  * OUT: 0:      valid
3300  *      other:  errno
3301  */
3302 static int
3303 key_mature(struct secasvar *sav)
3304 {
3305         int error;
3306
3307         /* check SPI value */
3308         switch (sav->sah->saidx.proto) {
3309         case IPPROTO_ESP:
3310         case IPPROTO_AH:
3311                 /*
3312                  * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3313                  * 1-255 reserved by IANA for future use,
3314                  * 0 for implementation specific, local use.
3315                  */
3316                 if (ntohl(sav->spi) <= 255) {
3317                         ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3318                             __func__, (u_int32_t)ntohl(sav->spi)));
3319                         return EINVAL;
3320                 }
3321                 break;
3322         }
3323
3324         /* check satype */
3325         switch (sav->sah->saidx.proto) {
3326         case IPPROTO_ESP:
3327                 /* check flags */
3328                 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3329                     (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3330                         ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3331                                 "given to old-esp.\n", __func__));
3332                         return EINVAL;
3333                 }
3334                 error = xform_init(sav, XF_ESP);
3335                 break;
3336         case IPPROTO_AH:
3337                 /* check flags */
3338                 if (sav->flags & SADB_X_EXT_DERIV) {
3339                         ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3340                                 "given to AH SA.\n", __func__));
3341                         return EINVAL;
3342                 }
3343                 if (sav->alg_enc != SADB_EALG_NONE) {
3344                         ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3345                                 "mismated.\n", __func__));
3346                         return(EINVAL);
3347                 }
3348                 error = xform_init(sav, XF_AH);
3349                 break;
3350         case IPPROTO_IPCOMP:
3351                 if (sav->alg_auth != SADB_AALG_NONE) {
3352                         ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3353                                 "mismated.\n", __func__));
3354                         return(EINVAL);
3355                 }
3356                 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3357                  && ntohl(sav->spi) >= 0x10000) {
3358                         ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3359                                 __func__));
3360                         return(EINVAL);
3361                 }
3362                 error = xform_init(sav, XF_IPCOMP);
3363                 break;
3364         case IPPROTO_TCP:
3365                 if (sav->alg_enc != SADB_EALG_NONE) {
3366                         ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3367                                 "mismated.\n", __func__));
3368                         return(EINVAL);
3369                 }
3370                 error = xform_init(sav, XF_TCPSIGNATURE);
3371                 break;
3372         default:
3373                 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3374                 error = EPROTONOSUPPORT;
3375                 break;
3376         }
3377         if (error == 0) {
3378                 SAHTREE_LOCK();
3379                 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3380                 SAHTREE_UNLOCK();
3381         }
3382         return (error);
3383 }
3384
3385 /*
3386  * subroutine for SADB_GET and SADB_DUMP.
3387  */
3388 static struct mbuf *
3389 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3390     u_int32_t seq, u_int32_t pid)
3391 {
3392         struct mbuf *result = NULL, *tres = NULL, *m;
3393         int i;
3394         int dumporder[] = {
3395                 SADB_EXT_SA, SADB_X_EXT_SA2,
3396                 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3397                 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3398                 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3399                 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3400                 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3401 #ifdef IPSEC_NAT_T
3402                 SADB_X_EXT_NAT_T_TYPE,
3403                 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3404                 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3405                 SADB_X_EXT_NAT_T_FRAG,
3406 #endif
3407         };
3408
3409         m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3410         if (m == NULL)
3411                 goto fail;
3412         result = m;
3413
3414         for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3415                 m = NULL;
3416                 switch (dumporder[i]) {
3417                 case SADB_EXT_SA:
3418                         m = key_setsadbsa(sav);
3419                         if (!m)
3420                                 goto fail;
3421                         break;
3422
3423                 case SADB_X_EXT_SA2:
3424                         m = key_setsadbxsa2(sav->sah->saidx.mode,
3425                                         sav->replay ? sav->replay->count : 0,
3426                                         sav->sah->saidx.reqid);
3427                         if (!m)
3428                                 goto fail;
3429                         break;
3430
3431                 case SADB_EXT_ADDRESS_SRC:
3432                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3433                             &sav->sah->saidx.src.sa,
3434                             FULLMASK, IPSEC_ULPROTO_ANY);
3435                         if (!m)
3436                                 goto fail;
3437                         break;
3438
3439                 case SADB_EXT_ADDRESS_DST:
3440                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3441                             &sav->sah->saidx.dst.sa,
3442                             FULLMASK, IPSEC_ULPROTO_ANY);
3443                         if (!m)
3444                                 goto fail;
3445                         break;
3446
3447                 case SADB_EXT_KEY_AUTH:
3448                         if (!sav->key_auth)
3449                                 continue;
3450                         m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3451                         if (!m)
3452                                 goto fail;
3453                         break;
3454
3455                 case SADB_EXT_KEY_ENCRYPT:
3456                         if (!sav->key_enc)
3457                                 continue;
3458                         m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3459                         if (!m)
3460                                 goto fail;
3461                         break;
3462
3463                 case SADB_EXT_LIFETIME_CURRENT:
3464                         if (!sav->lft_c)
3465                                 continue;
3466                         m = key_setlifetime(sav->lft_c, 
3467                                             SADB_EXT_LIFETIME_CURRENT);
3468                         if (!m)
3469                                 goto fail;
3470                         break;
3471
3472                 case SADB_EXT_LIFETIME_HARD:
3473                         if (!sav->lft_h)
3474                                 continue;
3475                         m = key_setlifetime(sav->lft_h, 
3476                                             SADB_EXT_LIFETIME_HARD);
3477                         if (!m)
3478                                 goto fail;
3479                         break;
3480
3481                 case SADB_EXT_LIFETIME_SOFT:
3482                         if (!sav->lft_s)
3483                                 continue;
3484                         m = key_setlifetime(sav->lft_s, 
3485                                             SADB_EXT_LIFETIME_SOFT);
3486
3487                         if (!m)
3488                                 goto fail;
3489                         break;
3490
3491 #ifdef IPSEC_NAT_T
3492                 case SADB_X_EXT_NAT_T_TYPE:
3493                         m = key_setsadbxtype(sav->natt_type);
3494                         if (!m)
3495                                 goto fail;
3496                         break;
3497                 
3498                 case SADB_X_EXT_NAT_T_DPORT:
3499                         m = key_setsadbxport(
3500                             KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3501                             SADB_X_EXT_NAT_T_DPORT);
3502                         if (!m)
3503                                 goto fail;
3504                         break;
3505
3506                 case SADB_X_EXT_NAT_T_SPORT:
3507                         m = key_setsadbxport(
3508                             KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3509                             SADB_X_EXT_NAT_T_SPORT);
3510                         if (!m)
3511                                 goto fail;
3512                         break;
3513
3514                 case SADB_X_EXT_NAT_T_OAI:
3515                 case SADB_X_EXT_NAT_T_OAR:
3516                 case SADB_X_EXT_NAT_T_FRAG:
3517                         /* We do not (yet) support those. */
3518                         continue;
3519 #endif
3520
3521                 case SADB_EXT_ADDRESS_PROXY:
3522                 case SADB_EXT_IDENTITY_SRC:
3523                 case SADB_EXT_IDENTITY_DST:
3524                         /* XXX: should we brought from SPD ? */
3525                 case SADB_EXT_SENSITIVITY:
3526                 default:
3527                         continue;
3528                 }
3529
3530                 if (!m)
3531                         goto fail;
3532                 if (tres)
3533                         m_cat(m, tres);
3534                 tres = m;
3535                   
3536         }
3537
3538         m_cat(result, tres);
3539         if (result->m_len < sizeof(struct sadb_msg)) {
3540                 result = m_pullup(result, sizeof(struct sadb_msg));
3541                 if (result == NULL)
3542                         goto fail;
3543         }
3544
3545         result->m_pkthdr.len = 0;
3546         for (m = result; m; m = m->m_next)
3547                 result->m_pkthdr.len += m->m_len;
3548
3549         mtod(result, struct sadb_msg *)->sadb_msg_len =
3550             PFKEY_UNIT64(result->m_pkthdr.len);
3551
3552         return result;
3553
3554 fail:
3555         m_freem(result);
3556         m_freem(tres);
3557         return NULL;
3558 }
3559
3560 /*
3561  * set data into sadb_msg.
3562  */
3563 static struct mbuf *
3564 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3565     pid_t pid, u_int16_t reserved)
3566 {
3567         struct mbuf *m;
3568         struct sadb_msg *p;
3569         int len;
3570
3571         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3572         if (len > MCLBYTES)
3573                 return NULL;
3574         MGETHDR(m, M_DONTWAIT, MT_DATA);
3575         if (m && len > MHLEN) {
3576                 MCLGET(m, M_DONTWAIT);
3577                 if ((m->m_flags & M_EXT) == 0) {
3578                         m_freem(m);
3579                         m = NULL;
3580                 }
3581         }
3582         if (!m)
3583                 return NULL;
3584         m->m_pkthdr.len = m->m_len = len;
3585         m->m_next = NULL;
3586
3587         p = mtod(m, struct sadb_msg *);
3588
3589         bzero(p, len);
3590         p->sadb_msg_version = PF_KEY_V2;
3591         p->sadb_msg_type = type;
3592         p->sadb_msg_errno = 0;
3593         p->sadb_msg_satype = satype;
3594         p->sadb_msg_len = PFKEY_UNIT64(tlen);
3595         p->sadb_msg_reserved = reserved;
3596         p->sadb_msg_seq = seq;
3597         p->sadb_msg_pid = (u_int32_t)pid;
3598
3599         return m;
3600 }
3601
3602 /*
3603  * copy secasvar data into sadb_address.
3604  */
3605 static struct mbuf *
3606 key_setsadbsa(sav)
3607         struct secasvar *sav;
3608 {
3609         struct mbuf *m;
3610         struct sadb_sa *p;
3611         int len;
3612
3613         len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3614         m = key_alloc_mbuf(len);
3615         if (!m || m->m_next) {  /*XXX*/
3616                 if (m)
3617                         m_freem(m);
3618                 return NULL;
3619         }
3620
3621         p = mtod(m, struct sadb_sa *);
3622
3623         bzero(p, len);
3624         p->sadb_sa_len = PFKEY_UNIT64(len);
3625         p->sadb_sa_exttype = SADB_EXT_SA;
3626         p->sadb_sa_spi = sav->spi;
3627         p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3628         p->sadb_sa_state = sav->state;
3629         p->sadb_sa_auth = sav->alg_auth;
3630         p->sadb_sa_encrypt = sav->alg_enc;
3631         p->sadb_sa_flags = sav->flags;
3632
3633         return m;
3634 }
3635
3636 /*
3637  * set data into sadb_address.
3638  */
3639 static struct mbuf *
3640 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3641 {
3642         struct mbuf *m;
3643         struct sadb_address *p;
3644         size_t len;
3645
3646         len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3647             PFKEY_ALIGN8(saddr->sa_len);
3648         m = key_alloc_mbuf(len);
3649         if (!m || m->m_next) {  /*XXX*/
3650                 if (m)
3651                         m_freem(m);
3652                 return NULL;
3653         }
3654
3655         p = mtod(m, struct sadb_address *);
3656
3657         bzero(p, len);
3658         p->sadb_address_len = PFKEY_UNIT64(len);
3659         p->sadb_address_exttype = exttype;
3660         p->sadb_address_proto = ul_proto;
3661         if (prefixlen == FULLMASK) {
3662                 switch (saddr->sa_family) {
3663                 case AF_INET:
3664                         prefixlen = sizeof(struct in_addr) << 3;
3665                         break;
3666                 case AF_INET6:
3667                         prefixlen = sizeof(struct in6_addr) << 3;
3668                         break;
3669                 default:
3670                         ; /*XXX*/
3671                 }
3672         }
3673         p->sadb_address_prefixlen = prefixlen;
3674         p->sadb_address_reserved = 0;
3675
3676         bcopy(saddr,
3677             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3678             saddr->sa_len);
3679
3680         return m;
3681 }
3682
3683 /*
3684  * set data into sadb_x_sa2.
3685  */
3686 static struct mbuf *
3687 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3688 {
3689         struct mbuf *m;
3690         struct sadb_x_sa2 *p;
3691         size_t len;
3692
3693         len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3694         m = key_alloc_mbuf(len);
3695         if (!m || m->m_next) {  /*XXX*/
3696                 if (m)
3697                         m_freem(m);
3698                 return NULL;
3699         }
3700
3701         p = mtod(m, struct sadb_x_sa2 *);
3702
3703         bzero(p, len);
3704         p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3705         p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3706         p->sadb_x_sa2_mode = mode;
3707         p->sadb_x_sa2_reserved1 = 0;
3708         p->sadb_x_sa2_reserved2 = 0;
3709         p->sadb_x_sa2_sequence = seq;
3710         p->sadb_x_sa2_reqid = reqid;
3711
3712         return m;
3713 }
3714
3715 #ifdef IPSEC_NAT_T
3716 /*
3717  * Set a type in sadb_x_nat_t_type.
3718  */
3719 static struct mbuf *
3720 key_setsadbxtype(u_int16_t type)
3721 {
3722         struct mbuf *m;
3723         size_t len;
3724         struct sadb_x_nat_t_type *p;
3725
3726         len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3727
3728         m = key_alloc_mbuf(len);
3729         if (!m || m->m_next) {  /*XXX*/
3730                 if (m)
3731                         m_freem(m);
3732                 return (NULL);
3733         }
3734
3735         p = mtod(m, struct sadb_x_nat_t_type *);
3736
3737         bzero(p, len);
3738         p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3739         p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3740         p->sadb_x_nat_t_type_type = type;
3741
3742         return (m);
3743 }
3744 /*
3745  * Set a port in sadb_x_nat_t_port.
3746  * In contrast to default RFC 2367 behaviour, port is in network byte order.
3747  */
3748 static struct mbuf *
3749 key_setsadbxport(u_int16_t port, u_int16_t type)
3750 {
3751         struct mbuf *m;
3752         size_t len;
3753         struct sadb_x_nat_t_port *p;
3754
3755         len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3756
3757         m = key_alloc_mbuf(len);
3758         if (!m || m->m_next) {  /*XXX*/
3759                 if (m)
3760                         m_freem(m);
3761                 return (NULL);
3762         }
3763
3764         p = mtod(m, struct sadb_x_nat_t_port *);
3765
3766         bzero(p, len);
3767         p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3768         p->sadb_x_nat_t_port_exttype = type;
3769         p->sadb_x_nat_t_port_port = port;
3770
3771         return (m);
3772 }
3773
3774 /* 
3775  * Get port from sockaddr. Port is in network byte order.
3776  */
3777 u_int16_t 
3778 key_portfromsaddr(struct sockaddr *sa)
3779 {
3780
3781         switch (sa->sa_family) {
3782 #ifdef INET
3783         case AF_INET:
3784                 return ((struct sockaddr_in *)sa)->sin_port;
3785 #endif
3786 #ifdef INET6
3787         case AF_INET6:
3788                 return ((struct sockaddr_in6 *)sa)->sin6_port;
3789 #endif
3790         }
3791         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3792                 printf("DP %s unexpected address family %d\n",
3793                         __func__, sa->sa_family));
3794         return (0);
3795 }
3796 #endif /* IPSEC_NAT_T */
3797
3798 /*
3799  * Set port in struct sockaddr. Port is in network byte order.
3800  */
3801 static void
3802 key_porttosaddr(struct sockaddr *sa, u_int16_t port)
3803 {
3804
3805         switch (sa->sa_family) {
3806 #ifdef INET
3807         case AF_INET:
3808                 ((struct sockaddr_in *)sa)->sin_port = port;
3809                 break;
3810 #endif
3811 #ifdef INET6
3812         case AF_INET6:
3813                 ((struct sockaddr_in6 *)sa)->sin6_port = port;
3814                 break;
3815 #endif
3816         default:
3817                 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3818                         __func__, sa->sa_family));
3819                 break;
3820         }
3821 }
3822
3823 /*
3824  * set data into sadb_x_policy
3825  */
3826 static struct mbuf *
3827 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3828 {
3829         struct mbuf *m;
3830         struct sadb_x_policy *p;
3831         size_t len;
3832
3833         len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3834         m = key_alloc_mbuf(len);
3835         if (!m || m->m_next) {  /*XXX*/
3836                 if (m)
3837                         m_freem(m);
3838                 return NULL;
3839         }
3840
3841         p = mtod(m, struct sadb_x_policy *);
3842
3843         bzero(p, len);
3844         p->sadb_x_policy_len = PFKEY_UNIT64(len);
3845         p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3846         p->sadb_x_policy_type = type;
3847         p->sadb_x_policy_dir = dir;
3848         p->sadb_x_policy_id = id;
3849
3850         return m;
3851 }
3852
3853 /* %%% utilities */
3854 /* Take a key message (sadb_key) from the socket and turn it into one
3855  * of the kernel's key structures (seckey).
3856  *
3857  * IN: pointer to the src
3858  * OUT: NULL no more memory
3859  */
3860 struct seckey *
3861 key_dup_keymsg(const struct sadb_key *src, u_int len,
3862                struct malloc_type *type)
3863 {
3864         struct seckey *dst;
3865         dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3866         if (dst != NULL) {
3867                 dst->bits = src->sadb_key_bits;
3868                 dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3869                 if (dst->key_data != NULL) {
3870                         bcopy((const char *)src + sizeof(struct sadb_key), 
3871                               dst->key_data, len);
3872                 } else {
3873                         ipseclog((LOG_DEBUG, "%s: No more memory.\n", 
3874                                   __func__));
3875                         free(dst, type);
3876                         dst = NULL;
3877                 }
3878         } else {
3879                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", 
3880                           __func__));
3881
3882         }
3883         return dst;
3884 }
3885
3886 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
3887  * turn it into one of the kernel's lifetime structures (seclifetime).
3888  *
3889  * IN: pointer to the destination, source and malloc type
3890  * OUT: NULL, no more memory
3891  */
3892
3893 static struct seclifetime *
3894 key_dup_lifemsg(const struct sadb_lifetime *src,
3895                  struct malloc_type *type)
3896 {
3897         struct seclifetime *dst = NULL;
3898
3899         dst = (struct seclifetime *)malloc(sizeof(struct seclifetime), 
3900                                            type, M_NOWAIT);
3901         if (dst == NULL) {
3902                 /* XXX counter */
3903                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3904         } else {
3905                 dst->allocations = src->sadb_lifetime_allocations;
3906                 dst->bytes = src->sadb_lifetime_bytes;
3907                 dst->addtime = src->sadb_lifetime_addtime;
3908                 dst->usetime = src->sadb_lifetime_usetime;
3909         }
3910         return dst;
3911 }
3912
3913 /* compare my own address
3914  * OUT: 1: true, i.e. my address.
3915  *      0: false
3916  */
3917 int
3918 key_ismyaddr(sa)
3919         struct sockaddr *sa;
3920 {
3921 #ifdef INET
3922         struct sockaddr_in *sin;
3923         struct in_ifaddr *ia;
3924 #endif
3925
3926         IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3927
3928         switch (sa->sa_family) {
3929 #ifdef INET
3930         case AF_INET:
3931                 sin = (struct sockaddr_in *)sa;
3932                 IN_IFADDR_RLOCK();
3933                 for (ia = V_in_ifaddrhead.tqh_first; ia;
3934                      ia = ia->ia_link.tqe_next)
3935                 {
3936                         if (sin->sin_family == ia->ia_addr.sin_family &&
3937                             sin->sin_len == ia->ia_addr.sin_len &&
3938                             sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3939                         {
3940                                 IN_IFADDR_RUNLOCK();
3941                                 return 1;
3942                         }
3943                 }
3944                 IN_IFADDR_RUNLOCK();
3945                 break;
3946 #endif
3947 #ifdef INET6
3948         case AF_INET6:
3949                 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3950 #endif
3951         }
3952
3953         return 0;
3954 }
3955
3956 #ifdef INET6
3957 /*
3958  * compare my own address for IPv6.
3959  * 1: ours
3960  * 0: other
3961  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3962  */
3963 #include <netinet6/in6_var.h>
3964
3965 static int
3966 key_ismyaddr6(sin6)
3967         struct sockaddr_in6 *sin6;
3968 {
3969         struct in6_ifaddr *ia;
3970 #if 0
3971         struct in6_multi *in6m;
3972 #endif
3973
3974         IN6_IFADDR_RLOCK();
3975         TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3976                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3977                     (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3978                         IN6_IFADDR_RUNLOCK();
3979                         return 1;
3980                 }
3981
3982 #if 0
3983                 /*
3984                  * XXX Multicast
3985                  * XXX why do we care about multlicast here while we don't care
3986                  * about IPv4 multicast??
3987                  * XXX scope
3988                  */
3989                 in6m = NULL;
3990                 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3991                 if (in6m) {
3992                         IN6_IFADDR_RUNLOCK();
3993                         return 1;
3994                 }
3995 #endif
3996         }
3997         IN6_IFADDR_RUNLOCK();
3998
3999         /* loopback, just for safety */
4000         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
4001                 return 1;
4002
4003         return 0;
4004 }
4005 #endif /*INET6*/
4006
4007 /*
4008  * compare two secasindex structure.
4009  * flag can specify to compare 2 saidxes.
4010  * compare two secasindex structure without both mode and reqid.
4011  * don't compare port.
4012  * IN:  
4013  *      saidx0: source, it can be in SAD.
4014  *      saidx1: object.
4015  * OUT: 
4016  *      1 : equal
4017  *      0 : not equal
4018  */
4019 static int
4020 key_cmpsaidx(
4021         const struct secasindex *saidx0,
4022         const struct secasindex *saidx1,
4023         int flag)
4024 {
4025         int chkport = 0;
4026
4027         /* sanity */
4028         if (saidx0 == NULL && saidx1 == NULL)
4029                 return 1;
4030
4031         if (saidx0 == NULL || saidx1 == NULL)
4032                 return 0;
4033
4034         if (saidx0->proto != saidx1->proto)
4035                 return 0;
4036
4037         if (flag == CMP_EXACTLY) {
4038                 if (saidx0->mode != saidx1->mode)
4039                         return 0;
4040                 if (saidx0->reqid != saidx1->reqid)
4041                         return 0;
4042                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4043                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4044                         return 0;
4045         } else {
4046
4047                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4048                 if (flag == CMP_MODE_REQID
4049                   ||flag == CMP_REQID) {
4050                         /*
4051                          * If reqid of SPD is non-zero, unique SA is required.
4052                          * The result must be of same reqid in this case.
4053                          */
4054                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4055                                 return 0;
4056                 }
4057
4058                 if (flag == CMP_MODE_REQID) {
4059                         if (saidx0->mode != IPSEC_MODE_ANY
4060                          && saidx0->mode != saidx1->mode)
4061                                 return 0;
4062                 }
4063
4064 #ifdef IPSEC_NAT_T
4065                 /*
4066                  * If NAT-T is enabled, check ports for tunnel mode.
4067                  * Do not check ports if they are set to zero in the SPD.
4068                  * Also do not do it for transport mode, as there is no
4069                  * port information available in the SP.
4070                  */
4071                 if (saidx1->mode == IPSEC_MODE_TUNNEL &&
4072                     saidx1->src.sa.sa_family == AF_INET &&
4073                     saidx1->dst.sa.sa_family == AF_INET &&
4074                     ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4075                     ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4076                         chkport = 1;
4077 #endif /* IPSEC_NAT_T */
4078
4079                 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4080                         return 0;
4081                 }
4082                 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4083                         return 0;
4084                 }
4085         }
4086
4087         return 1;
4088 }
4089
4090 /*
4091  * compare two secindex structure exactly.
4092  * IN:
4093  *      spidx0: source, it is often in SPD.
4094  *      spidx1: object, it is often from PFKEY message.
4095  * OUT:
4096  *      1 : equal
4097  *      0 : not equal
4098  */
4099 static int
4100 key_cmpspidx_exactly(
4101         struct secpolicyindex *spidx0,
4102         struct secpolicyindex *spidx1)
4103 {
4104         /* sanity */
4105         if (spidx0 == NULL && spidx1 == NULL)
4106                 return 1;
4107
4108         if (spidx0 == NULL || spidx1 == NULL)
4109                 return 0;
4110
4111         if (spidx0->prefs != spidx1->prefs
4112          || spidx0->prefd != spidx1->prefd
4113          || spidx0->ul_proto != spidx1->ul_proto)
4114                 return 0;
4115
4116         return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4117                key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4118 }
4119
4120 /*
4121  * compare two secindex structure with mask.
4122  * IN:
4123  *      spidx0: source, it is often in SPD.
4124  *      spidx1: object, it is often from IP header.
4125  * OUT:
4126  *      1 : equal
4127  *      0 : not equal
4128  */
4129 static int
4130 key_cmpspidx_withmask(
4131         struct secpolicyindex *spidx0,
4132         struct secpolicyindex *spidx1)
4133 {
4134         /* sanity */
4135         if (spidx0 == NULL && spidx1 == NULL)
4136                 return 1;
4137
4138         if (spidx0 == NULL || spidx1 == NULL)
4139                 return 0;
4140
4141         if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4142             spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4143             spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4144             spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4145                 return 0;
4146
4147         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4148         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4149          && spidx0->ul_proto != spidx1->ul_proto)
4150                 return 0;
4151
4152         switch (spidx0->src.sa.sa_family) {
4153         case AF_INET:
4154                 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4155                  && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4156                         return 0;
4157                 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4158                     &spidx1->src.sin.sin_addr, spidx0->prefs))
4159                         return 0;
4160                 break;
4161         case AF_INET6:
4162                 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4163                  && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4164                         return 0;
4165                 /*
4166                  * scope_id check. if sin6_scope_id is 0, we regard it
4167                  * as a wildcard scope, which matches any scope zone ID. 
4168                  */
4169                 if (spidx0->src.sin6.sin6_scope_id &&
4170                     spidx1->src.sin6.sin6_scope_id &&
4171                     spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4172                         return 0;
4173                 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4174                     &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4175                         return 0;
4176                 break;
4177         default:
4178                 /* XXX */
4179                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4180                         return 0;
4181                 break;
4182         }
4183
4184         switch (spidx0->dst.sa.sa_family) {
4185         case AF_INET:
4186                 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4187                  && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4188                         return 0;
4189                 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4190                     &spidx1->dst.sin.sin_addr, spidx0->prefd))
4191                         return 0;
4192                 break;
4193         case AF_INET6:
4194                 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4195                  && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4196                         return 0;
4197                 /*
4198                  * scope_id check. if sin6_scope_id is 0, we regard it
4199                  * as a wildcard scope, which matches any scope zone ID. 
4200                  */
4201                 if (spidx0->dst.sin6.sin6_scope_id &&
4202                     spidx1->dst.sin6.sin6_scope_id &&
4203                     spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4204                         return 0;
4205                 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4206                     &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4207                         return 0;
4208                 break;
4209         default:
4210                 /* XXX */
4211                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4212                         return 0;
4213                 break;
4214         }
4215
4216         /* XXX Do we check other field ?  e.g. flowinfo */
4217
4218         return 1;
4219 }
4220
4221 /* returns 0 on match */
4222 static int
4223 key_sockaddrcmp(
4224         const struct sockaddr *sa1,
4225         const struct sockaddr *sa2,
4226         int port)
4227 {
4228 #ifdef satosin
4229 #undef satosin
4230 #endif
4231 #define satosin(s) ((const struct sockaddr_in *)s)
4232 #ifdef satosin6
4233 #undef satosin6
4234 #endif
4235 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4236         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4237                 return 1;
4238
4239         switch (sa1->sa_family) {
4240         case AF_INET:
4241                 if (sa1->sa_len != sizeof(struct sockaddr_in))
4242                         return 1;
4243                 if (satosin(sa1)->sin_addr.s_addr !=
4244                     satosin(sa2)->sin_addr.s_addr) {
4245                         return 1;
4246                 }
4247                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4248                         return 1;
4249                 break;
4250         case AF_INET6:
4251                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4252                         return 1;       /*EINVAL*/
4253                 if (satosin6(sa1)->sin6_scope_id !=
4254                     satosin6(sa2)->sin6_scope_id) {
4255                         return 1;
4256                 }
4257                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4258                     &satosin6(sa2)->sin6_addr)) {
4259                         return 1;
4260                 }
4261                 if (port &&
4262                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4263                         return 1;
4264                 }
4265                 break;
4266         default:
4267                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4268                         return 1;
4269                 break;
4270         }
4271
4272         return 0;
4273 #undef satosin
4274 #undef satosin6
4275 }
4276
4277 /*
4278  * compare two buffers with mask.
4279  * IN:
4280  *      addr1: source
4281  *      addr2: object
4282  *      bits:  Number of bits to compare
4283  * OUT:
4284  *      1 : equal
4285  *      0 : not equal
4286  */
4287 static int
4288 key_bbcmp(const void *a1, const void *a2, u_int bits)
4289 {
4290         const unsigned char *p1 = a1;
4291         const unsigned char *p2 = a2;
4292
4293         /* XXX: This could be considerably faster if we compare a word
4294          * at a time, but it is complicated on LSB Endian machines */
4295
4296         /* Handle null pointers */
4297         if (p1 == NULL || p2 == NULL)
4298                 return (p1 == p2);
4299
4300         while (bits >= 8) {
4301                 if (*p1++ != *p2++)
4302                         return 0;
4303                 bits -= 8;
4304         }
4305
4306         if (bits > 0) {
4307                 u_int8_t mask = ~((1<<(8-bits))-1);
4308                 if ((*p1 & mask) != (*p2 & mask))
4309                         return 0;
4310         }
4311         return 1;       /* Match! */
4312 }
4313
4314 static void
4315 key_flush_spd(time_t now)
4316 {
4317         static u_int16_t sptree_scangen = 0;
4318         u_int16_t gen = sptree_scangen++;
4319         struct secpolicy *sp;
4320         u_int dir;
4321
4322         /* SPD */
4323         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4324 restart:
4325                 SPTREE_LOCK();
4326                 LIST_FOREACH(sp, &V_sptree[dir], chain) {
4327                         if (sp->scangen == gen)         /* previously handled */
4328                                 continue;
4329                         sp->scangen = gen;
4330                         if (sp->state == IPSEC_SPSTATE_DEAD &&
4331                             sp->refcnt == 1) {
4332                                 /*
4333                                  * Ensure that we only decrease refcnt once,
4334                                  * when we're the last consumer.
4335                                  * Directly call SP_DELREF/key_delsp instead
4336                                  * of KEY_FREESP to avoid unlocking/relocking
4337                                  * SPTREE_LOCK before key_delsp: may refcnt
4338                                  * be increased again during that time ?
4339                                  * NB: also clean entries created by
4340                                  * key_spdflush
4341                                  */
4342                                 SP_DELREF(sp);
4343                                 key_delsp(sp);
4344                                 SPTREE_UNLOCK();
4345                                 goto restart;
4346                         }
4347                         if (sp->lifetime == 0 && sp->validtime == 0)
4348                                 continue;
4349                         if ((sp->lifetime && now - sp->created > sp->lifetime)
4350                          || (sp->validtime && now - sp->lastused > sp->validtime)) {
4351                                 sp->state = IPSEC_SPSTATE_DEAD;
4352                                 SPTREE_UNLOCK();
4353                                 key_spdexpire(sp);
4354                                 goto restart;
4355                         }
4356                 }
4357                 SPTREE_UNLOCK();
4358         }
4359 }
4360
4361 static void
4362 key_flush_sad(time_t now)
4363 {
4364         struct secashead *sah, *nextsah;
4365         struct secasvar *sav, *nextsav;
4366
4367         /* SAD */
4368         SAHTREE_LOCK();
4369         LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4370                 /* if sah has been dead, then delete it and process next sah. */
4371                 if (sah->state == SADB_SASTATE_DEAD) {
4372                         key_delsah(sah);
4373                         continue;
4374                 }
4375
4376                 /* if LARVAL entry doesn't become MATURE, delete it. */
4377                 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4378                         /* Need to also check refcnt for a larval SA ??? */
4379                         if (now - sav->created > V_key_larval_lifetime)
4380                                 KEY_FREESAV(&sav);
4381                 }
4382
4383                 /*
4384                  * check MATURE entry to start to send expire message
4385                  * whether or not.
4386                  */
4387                 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4388                         /* we don't need to check. */
4389                         if (sav->lft_s == NULL)
4390                                 continue;
4391
4392                         /* sanity check */
4393                         if (sav->lft_c == NULL) {
4394                                 ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4395                                         "time, why?\n", __func__));
4396                                 continue;
4397                         }
4398
4399                         /* check SOFT lifetime */
4400                         if (sav->lft_s->addtime != 0 &&
4401                             now - sav->created > sav->lft_s->addtime) {
4402                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4403                                 /* 
4404                                  * Actually, only send expire message if
4405                                  * SA has been used, as it was done before,
4406                                  * but should we always send such message,
4407                                  * and let IKE daemon decide if it should be
4408                                  * renegotiated or not ?
4409                                  * XXX expire message will actually NOT be
4410                                  * sent if SA is only used after soft
4411                                  * lifetime has been reached, see below
4412                                  * (DYING state)
4413                                  */
4414                                 if (sav->lft_c->usetime != 0)
4415                                         key_expire(sav);
4416                         }
4417                         /* check SOFT lifetime by bytes */
4418                         /*
4419                          * XXX I don't know the way to delete this SA
4420                          * when new SA is installed.  Caution when it's
4421                          * installed too big lifetime by time.
4422                          */
4423                         else if (sav->lft_s->bytes != 0 &&
4424                             sav->lft_s->bytes < sav->lft_c->bytes) {
4425
4426                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4427                                 /*
4428                                  * XXX If we keep to send expire
4429                                  * message in the status of
4430                                  * DYING. Do remove below code.
4431                                  */
4432                                 key_expire(sav);
4433                         }
4434                 }
4435
4436                 /* check DYING entry to change status to DEAD. */
4437                 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4438                         /* we don't need to check. */
4439                         if (sav->lft_h == NULL)
4440                                 continue;
4441
4442                         /* sanity check */
4443                         if (sav->lft_c == NULL) {
4444                                 ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4445                                         "time, why?\n", __func__));
4446                                 continue;
4447                         }
4448
4449                         if (sav->lft_h->addtime != 0 &&
4450                             now - sav->created > sav->lft_h->addtime) {
4451                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4452                                 KEY_FREESAV(&sav);
4453                         }
4454 #if 0   /* XXX Should we keep to send expire message until HARD lifetime ? */
4455                         else if (sav->lft_s != NULL
4456                               && sav->lft_s->addtime != 0
4457                               && now - sav->created > sav->lft_s->addtime) {
4458                                 /*
4459                                  * XXX: should be checked to be
4460                                  * installed the valid SA.
4461                                  */
4462
4463                                 /*
4464                                  * If there is no SA then sending
4465                                  * expire message.
4466                                  */
4467                                 key_expire(sav);
4468                         }
4469 #endif
4470                         /* check HARD lifetime by bytes */
4471                         else if (sav->lft_h->bytes != 0 &&
4472                             sav->lft_h->bytes < sav->lft_c->bytes) {
4473                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4474                                 KEY_FREESAV(&sav);
4475                         }
4476                 }
4477
4478                 /* delete entry in DEAD */
4479                 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4480                         /* sanity check */
4481                         if (sav->state != SADB_SASTATE_DEAD) {
4482                                 ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4483                                         "(queue: %d SA: %d): kill it anyway\n",
4484                                         __func__,
4485                                         SADB_SASTATE_DEAD, sav->state));
4486                         }
4487                         /*
4488                          * do not call key_freesav() here.
4489                          * sav should already be freed, and sav->refcnt
4490                          * shows other references to sav
4491                          * (such as from SPD).
4492                          */
4493                 }
4494         }
4495         SAHTREE_UNLOCK();
4496 }
4497
4498 static void
4499 key_flush_acq(time_t now)
4500 {
4501         struct secacq *acq, *nextacq;
4502
4503         /* ACQ tree */
4504         ACQ_LOCK();
4505         for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4506                 nextacq = LIST_NEXT(acq, chain);
4507                 if (now - acq->created > V_key_blockacq_lifetime
4508                  && __LIST_CHAINED(acq)) {
4509                         LIST_REMOVE(acq, chain);
4510                         free(acq, M_IPSEC_SAQ);
4511                 }
4512         }
4513         ACQ_UNLOCK();
4514 }
4515
4516 static void
4517 key_flush_spacq(time_t now)
4518 {
4519         struct secspacq *acq, *nextacq;
4520
4521         /* SP ACQ tree */
4522         SPACQ_LOCK();
4523         for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4524                 nextacq = LIST_NEXT(acq, chain);
4525                 if (now - acq->created > V_key_blockacq_lifetime
4526                  && __LIST_CHAINED(acq)) {
4527                         LIST_REMOVE(acq, chain);
4528                         free(acq, M_IPSEC_SAQ);
4529                 }
4530         }
4531         SPACQ_UNLOCK();
4532 }
4533
4534 /*
4535  * time handler.
4536  * scanning SPD and SAD to check status for each entries,
4537  * and do to remove or to expire.
4538  * XXX: year 2038 problem may remain.
4539  */
4540 void
4541 key_timehandler(void)
4542 {
4543         VNET_ITERATOR_DECL(vnet_iter);
4544         time_t now = time_second;
4545
4546         VNET_LIST_RLOCK_NOSLEEP();
4547         VNET_FOREACH(vnet_iter) {
4548                 CURVNET_SET(vnet_iter);
4549                 key_flush_spd(now);
4550                 key_flush_sad(now);
4551                 key_flush_acq(now);
4552                 key_flush_spacq(now);
4553                 CURVNET_RESTORE();
4554         }
4555         VNET_LIST_RUNLOCK_NOSLEEP();
4556
4557 #ifndef IPSEC_DEBUG2
4558         /* do exchange to tick time !! */
4559         (void)timeout((void *)key_timehandler, (void *)0, hz);
4560 #endif /* IPSEC_DEBUG2 */
4561 }
4562
4563 u_long
4564 key_random()
4565 {
4566         u_long value;
4567
4568         key_randomfill(&value, sizeof(value));
4569         return value;
4570 }
4571
4572 void
4573 key_randomfill(p, l)
4574         void *p;
4575         size_t l;
4576 {
4577         size_t n;
4578         u_long v;
4579         static int warn = 1;
4580
4581         n = 0;
4582         n = (size_t)read_random(p, (u_int)l);
4583         /* last resort */
4584         while (n < l) {
4585                 v = random();
4586                 bcopy(&v, (u_int8_t *)p + n,
4587                     l - n < sizeof(v) ? l - n : sizeof(v));
4588                 n += sizeof(v);
4589
4590                 if (warn) {
4591                         printf("WARNING: pseudo-random number generator "
4592                             "used for IPsec processing\n");
4593                         warn = 0;
4594                 }
4595         }
4596 }
4597
4598 /*
4599  * map SADB_SATYPE_* to IPPROTO_*.
4600  * if satype == SADB_SATYPE then satype is mapped to ~0.
4601  * OUT:
4602  *      0: invalid satype.
4603  */
4604 static u_int16_t
4605 key_satype2proto(u_int8_t satype)
4606 {
4607         switch (satype) {
4608         case SADB_SATYPE_UNSPEC:
4609                 return IPSEC_PROTO_ANY;
4610         case SADB_SATYPE_AH:
4611                 return IPPROTO_AH;
4612         case SADB_SATYPE_ESP:
4613                 return IPPROTO_ESP;
4614         case SADB_X_SATYPE_IPCOMP:
4615                 return IPPROTO_IPCOMP;
4616         case SADB_X_SATYPE_TCPSIGNATURE:
4617                 return IPPROTO_TCP;
4618         default:
4619                 return 0;
4620         }
4621         /* NOTREACHED */
4622 }
4623
4624 /*
4625  * map IPPROTO_* to SADB_SATYPE_*
4626  * OUT:
4627  *      0: invalid protocol type.
4628  */
4629 static u_int8_t
4630 key_proto2satype(u_int16_t proto)
4631 {
4632         switch (proto) {
4633         case IPPROTO_AH:
4634                 return SADB_SATYPE_AH;
4635         case IPPROTO_ESP:
4636                 return SADB_SATYPE_ESP;
4637         case IPPROTO_IPCOMP:
4638                 return SADB_X_SATYPE_IPCOMP;
4639         case IPPROTO_TCP:
4640                 return SADB_X_SATYPE_TCPSIGNATURE;
4641         default:
4642                 return 0;
4643         }
4644         /* NOTREACHED */
4645 }
4646
4647 /* %%% PF_KEY */
4648 /*
4649  * SADB_GETSPI processing is to receive
4650  *      <base, (SA2), src address, dst address, (SPI range)>
4651  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4652  * tree with the status of LARVAL, and send
4653  *      <base, SA(*), address(SD)>
4654  * to the IKMPd.
4655  *
4656  * IN:  mhp: pointer to the pointer to each header.
4657  * OUT: NULL if fail.
4658  *      other if success, return pointer to the message to send.
4659  */
4660 static int
4661 key_getspi(so, m, mhp)
4662         struct socket *so;
4663         struct mbuf *m;
4664         const struct sadb_msghdr *mhp;
4665 {
4666         struct sadb_address *src0, *dst0;
4667         struct secasindex saidx;
4668         struct secashead *newsah;
4669         struct secasvar *newsav;
4670         u_int8_t proto;
4671         u_int32_t spi;
4672         u_int8_t mode;
4673         u_int32_t reqid;
4674         int error;
4675
4676         IPSEC_ASSERT(so != NULL, ("null socket"));
4677         IPSEC_ASSERT(m != NULL, ("null mbuf"));
4678         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4679         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4680
4681         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4682             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4683                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4684                         __func__));
4685                 return key_senderror(so, m, EINVAL);
4686         }
4687         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4688             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4689                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4690                         __func__));
4691                 return key_senderror(so, m, EINVAL);
4692         }
4693         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4694                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4695                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4696         } else {
4697                 mode = IPSEC_MODE_ANY;
4698                 reqid = 0;
4699         }
4700
4701         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4702         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4703
4704         /* map satype to proto */
4705         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4706                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4707                         __func__));
4708                 return key_senderror(so, m, EINVAL);
4709         }
4710
4711         /*
4712          * Make sure the port numbers are zero.
4713          * In case of NAT-T we will update them later if needed.
4714          */
4715         switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4716         case AF_INET:
4717                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4718                     sizeof(struct sockaddr_in))
4719                         return key_senderror(so, m, EINVAL);
4720                 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4721                 break;
4722         case AF_INET6:
4723                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4724                     sizeof(struct sockaddr_in6))
4725                         return key_senderror(so, m, EINVAL);
4726                 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4727                 break;
4728         default:
4729                 ; /*???*/
4730         }
4731         switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4732         case AF_INET:
4733                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4734                     sizeof(struct sockaddr_in))
4735                         return key_senderror(so, m, EINVAL);
4736                 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4737                 break;
4738         case AF_INET6:
4739                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4740                     sizeof(struct sockaddr_in6))
4741                         return key_senderror(so, m, EINVAL);
4742                 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4743                 break;
4744         default:
4745                 ; /*???*/
4746         }
4747
4748         /* XXX boundary check against sa_len */
4749         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4750
4751 #ifdef IPSEC_NAT_T
4752         /*
4753          * Handle NAT-T info if present.
4754          * We made sure the port numbers are zero above, so we do
4755          * not have to worry in case we do not update them.
4756          */
4757         if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4758                 ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4759         if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4760                 ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4761
4762         if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4763             mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4764             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4765                 struct sadb_x_nat_t_type *type;
4766                 struct sadb_x_nat_t_port *sport, *dport;
4767
4768                 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4769                     mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4770                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4771                         ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4772                             "passed.\n", __func__));
4773                         return key_senderror(so, m, EINVAL);
4774                 }
4775
4776                 sport = (struct sadb_x_nat_t_port *)
4777                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4778                 dport = (struct sadb_x_nat_t_port *)
4779                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4780
4781                 if (sport)
4782                         KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4783                 if (dport)
4784                         KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4785         }
4786 #endif
4787
4788         /* SPI allocation */
4789         spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4790                                &saidx);
4791         if (spi == 0)
4792                 return key_senderror(so, m, EINVAL);
4793
4794         /* get a SA index */
4795         if ((newsah = key_getsah(&saidx)) == NULL) {
4796                 /* create a new SA index */
4797                 if ((newsah = key_newsah(&saidx)) == NULL) {
4798                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4799                         return key_senderror(so, m, ENOBUFS);
4800                 }
4801         }
4802
4803         /* get a new SA */
4804         /* XXX rewrite */
4805         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4806         if (newsav == NULL) {
4807                 /* XXX don't free new SA index allocated in above. */
4808                 return key_senderror(so, m, error);
4809         }
4810
4811         /* set spi */
4812         newsav->spi = htonl(spi);
4813
4814         /* delete the entry in acqtree */
4815         if (mhp->msg->sadb_msg_seq != 0) {
4816                 struct secacq *acq;
4817                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4818                         /* reset counter in order to deletion by timehandler. */
4819                         acq->created = time_second;
4820                         acq->count = 0;
4821                 }
4822         }
4823
4824     {
4825         struct mbuf *n, *nn;
4826         struct sadb_sa *m_sa;
4827         struct sadb_msg *newmsg;
4828         int off, len;
4829
4830         /* create new sadb_msg to reply. */
4831         len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4832             PFKEY_ALIGN8(sizeof(struct sadb_sa));
4833
4834         MGETHDR(n, M_DONTWAIT, MT_DATA);
4835         if (len > MHLEN) {
4836                 MCLGET(n, M_DONTWAIT);
4837                 if ((n->m_flags & M_EXT) == 0) {
4838                         m_freem(n);
4839                         n = NULL;
4840                 }
4841         }
4842         if (!n)
4843                 return key_senderror(so, m, ENOBUFS);
4844
4845         n->m_len = len;
4846         n->m_next = NULL;
4847         off = 0;
4848
4849         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4850         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4851
4852         m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4853         m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4854         m_sa->sadb_sa_exttype = SADB_EXT_SA;
4855         m_sa->sadb_sa_spi = htonl(spi);
4856         off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4857
4858         IPSEC_ASSERT(off == len,
4859                 ("length inconsistency (off %u len %u)", off, len));
4860
4861         n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4862             SADB_EXT_ADDRESS_DST);
4863         if (!n->m_next) {
4864                 m_freem(n);
4865                 return key_senderror(so, m, ENOBUFS);
4866         }
4867
4868         if (n->m_len < sizeof(struct sadb_msg)) {
4869                 n = m_pullup(n, sizeof(struct sadb_msg));
4870                 if (n == NULL)
4871                         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4872         }
4873
4874         n->m_pkthdr.len = 0;
4875         for (nn = n; nn; nn = nn->m_next)
4876                 n->m_pkthdr.len += nn->m_len;
4877
4878         newmsg = mtod(n, struct sadb_msg *);
4879         newmsg->sadb_msg_seq = newsav->seq;
4880         newmsg->sadb_msg_errno = 0;
4881         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4882
4883         m_freem(m);
4884         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4885     }
4886 }
4887
4888 /*
4889  * allocating new SPI
4890  * called by key_getspi().
4891  * OUT:
4892  *      0:      failure.
4893  *      others: success.
4894  */
4895 static u_int32_t
4896 key_do_getnewspi(spirange, saidx)
4897         struct sadb_spirange *spirange;
4898         struct secasindex *saidx;
4899 {
4900         u_int32_t newspi;
4901         u_int32_t min, max;
4902         int count = V_key_spi_trycnt;
4903
4904         /* set spi range to allocate */
4905         if (spirange != NULL) {
4906                 min = spirange->sadb_spirange_min;
4907                 max = spirange->sadb_spirange_max;
4908         } else {
4909                 min = V_key_spi_minval;
4910                 max = V_key_spi_maxval;
4911         }
4912         /* IPCOMP needs 2-byte SPI */
4913         if (saidx->proto == IPPROTO_IPCOMP) {
4914                 u_int32_t t;
4915                 if (min >= 0x10000)
4916                         min = 0xffff;
4917                 if (max >= 0x10000)
4918                         max = 0xffff;
4919                 if (min > max) {
4920                         t = min; min = max; max = t;
4921                 }
4922         }
4923
4924         if (min == max) {
4925                 if (key_checkspidup(saidx, min) != NULL) {
4926                         ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4927                                 __func__, min));
4928                         return 0;
4929                 }
4930
4931                 count--; /* taking one cost. */
4932                 newspi = min;
4933
4934         } else {
4935
4936                 /* init SPI */
4937                 newspi = 0;
4938
4939                 /* when requesting to allocate spi ranged */
4940                 while (count--) {
4941                         /* generate pseudo-random SPI value ranged. */
4942                         newspi = min + (key_random() % (max - min + 1));
4943
4944                         if (key_checkspidup(saidx, newspi) == NULL)
4945                                 break;
4946                 }
4947
4948                 if (count == 0 || newspi == 0) {
4949                         ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4950                                 __func__));
4951                         return 0;
4952                 }
4953         }
4954
4955         /* statistics */
4956         keystat.getspi_count =
4957                 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4958
4959         return newspi;
4960 }
4961
4962 /*
4963  * SADB_UPDATE processing
4964  * receive
4965  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4966  *       key(AE), (identity(SD),) (sensitivity)>
4967  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4968  * and send
4969  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4970  *       (identity(SD),) (sensitivity)>
4971  * to the ikmpd.
4972  *
4973  * m will always be freed.
4974  */
4975 static int
4976 key_update(so, m, mhp)
4977         struct socket *so;
4978         struct mbuf *m;
4979         const struct sadb_msghdr *mhp;
4980 {
4981         struct sadb_sa *sa0;
4982         struct sadb_address *src0, *dst0;
4983 #ifdef IPSEC_NAT_T
4984         struct sadb_x_nat_t_type *type;
4985         struct sadb_x_nat_t_port *sport, *dport;
4986         struct sadb_address *iaddr, *raddr;
4987         struct sadb_x_nat_t_frag *frag;
4988 #endif
4989         struct secasindex saidx;
4990         struct secashead *sah;
4991         struct secasvar *sav;
4992         u_int16_t proto;
4993         u_int8_t mode;
4994         u_int32_t reqid;
4995         int error;
4996
4997         IPSEC_ASSERT(so != NULL, ("null socket"));
4998         IPSEC_ASSERT(m != NULL, ("null mbuf"));
4999         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5000         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5001
5002         /* map satype to proto */
5003         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5004                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5005                         __func__));
5006                 return key_senderror(so, m, EINVAL);
5007         }
5008
5009         if (mhp->ext[SADB_EXT_SA] == NULL ||
5010             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5011             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5012             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5013              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5014             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5015              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5016             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5017              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5018             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5019              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5020                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5021                         __func__));
5022                 return key_senderror(so, m, EINVAL);
5023         }
5024         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5025             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5026             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5027                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5028                         __func__));
5029                 return key_senderror(so, m, EINVAL);
5030         }
5031         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5032                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5033                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5034         } else {
5035                 mode = IPSEC_MODE_ANY;
5036                 reqid = 0;
5037         }
5038         /* XXX boundary checking for other extensions */
5039
5040         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5041         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5042         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5043
5044         /* XXX boundary check against sa_len */
5045         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5046
5047         /*
5048          * Make sure the port numbers are zero.
5049          * In case of NAT-T we will update them later if needed.
5050          */
5051         KEY_PORTTOSADDR(&saidx.src, 0);
5052         KEY_PORTTOSADDR(&saidx.dst, 0);
5053
5054 #ifdef IPSEC_NAT_T
5055         /*
5056          * Handle NAT-T info if present.
5057          */
5058         if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5059             mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5060             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5061
5062                 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5063                     mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5064                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5065                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5066                             __func__));
5067                         return key_senderror(so, m, EINVAL);
5068                 }
5069
5070                 type = (struct sadb_x_nat_t_type *)
5071                     mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5072                 sport = (struct sadb_x_nat_t_port *)
5073                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5074                 dport = (struct sadb_x_nat_t_port *)
5075                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5076         } else {
5077                 type = 0;
5078                 sport = dport = 0;
5079         }
5080         if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5081             mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5082                 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5083                     mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5084                         ipseclog((LOG_DEBUG, "%s: invalid message\n",
5085                             __func__));
5086                         return key_senderror(so, m, EINVAL);
5087                 }
5088                 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5089                 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5090                 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5091         } else {
5092                 iaddr = raddr = NULL;
5093         }
5094         if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5095                 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5096                         ipseclog((LOG_DEBUG, "%s: invalid message\n",
5097                             __func__));
5098                         return key_senderror(so, m, EINVAL);
5099                 }
5100                 frag = (struct sadb_x_nat_t_frag *)
5101                     mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5102         } else {
5103                 frag = 0;
5104         }
5105 #endif
5106
5107         /* get a SA header */
5108         if ((sah = key_getsah(&saidx)) == NULL) {
5109                 ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5110                 return key_senderror(so, m, ENOENT);
5111         }
5112
5113         /* set spidx if there */
5114         /* XXX rewrite */
5115         error = key_setident(sah, m, mhp);
5116         if (error)
5117                 return key_senderror(so, m, error);
5118
5119         /* find a SA with sequence number. */
5120 #ifdef IPSEC_DOSEQCHECK
5121         if (mhp->msg->sadb_msg_seq != 0
5122          && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5123                 ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5124                         "exists.\n", __func__, mhp->msg->sadb_msg_seq));
5125                 return key_senderror(so, m, ENOENT);
5126         }
5127 #else
5128         SAHTREE_LOCK();
5129         sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5130         SAHTREE_UNLOCK();
5131         if (sav == NULL) {
5132                 ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5133                         __func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5134                 return key_senderror(so, m, EINVAL);
5135         }
5136 #endif
5137
5138         /* validity check */
5139         if (sav->sah->saidx.proto != proto) {
5140                 ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5141                         "(DB=%u param=%u)\n", __func__,
5142                         sav->sah->saidx.proto, proto));
5143                 return key_senderror(so, m, EINVAL);
5144         }
5145 #ifdef IPSEC_DOSEQCHECK
5146         if (sav->spi != sa0->sadb_sa_spi) {
5147                 ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5148                     __func__,
5149                     (u_int32_t)ntohl(sav->spi),
5150                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5151                 return key_senderror(so, m, EINVAL);
5152         }
5153 #endif
5154         if (sav->pid != mhp->msg->sadb_msg_pid) {
5155                 ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5156                     __func__, sav->pid, mhp->msg->sadb_msg_pid));
5157                 return key_senderror(so, m, EINVAL);
5158         }
5159
5160         /* copy sav values */
5161         error = key_setsaval(sav, m, mhp);
5162         if (error) {
5163                 KEY_FREESAV(&sav);
5164                 return key_senderror(so, m, error);
5165         }
5166
5167 #ifdef IPSEC_NAT_T
5168         /*
5169          * Handle more NAT-T info if present,
5170          * now that we have a sav to fill.
5171          */
5172         if (type)
5173                 sav->natt_type = type->sadb_x_nat_t_type_type;
5174
5175         if (sport)
5176                 KEY_PORTTOSADDR(&sav->sah->saidx.src,
5177                     sport->sadb_x_nat_t_port_port);
5178         if (dport)
5179                 KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5180                     dport->sadb_x_nat_t_port_port);
5181
5182 #if 0
5183         /*
5184          * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5185          * We should actually check for a minimum MTU here, if we
5186          * want to support it in ip_output.
5187          */
5188         if (frag)
5189                 sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5190 #endif
5191 #endif
5192
5193         /* check SA values to be mature. */
5194         if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5195                 KEY_FREESAV(&sav);
5196                 return key_senderror(so, m, 0);
5197         }
5198
5199     {
5200         struct mbuf *n;
5201
5202         /* set msg buf from mhp */
5203         n = key_getmsgbuf_x1(m, mhp);
5204         if (n == NULL) {
5205                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5206                 return key_senderror(so, m, ENOBUFS);
5207         }
5208
5209         m_freem(m);
5210         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5211     }
5212 }
5213
5214 /*
5215  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5216  * only called by key_update().
5217  * OUT:
5218  *      NULL    : not found
5219  *      others  : found, pointer to a SA.
5220  */
5221 #ifdef IPSEC_DOSEQCHECK
5222 static struct secasvar *
5223 key_getsavbyseq(sah, seq)
5224         struct secashead *sah;
5225         u_int32_t seq;
5226 {
5227         struct secasvar *sav;
5228         u_int state;
5229
5230         state = SADB_SASTATE_LARVAL;
5231
5232         /* search SAD with sequence number ? */
5233         LIST_FOREACH(sav, &sah->savtree[state], chain) {
5234
5235                 KEY_CHKSASTATE(state, sav->state, __func__);
5236
5237                 if (sav->seq == seq) {
5238                         sa_addref(sav);
5239                         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5240                                 printf("DP %s cause refcnt++:%d SA:%p\n",
5241                                         __func__, sav->refcnt, sav));
5242                         return sav;
5243                 }
5244         }
5245
5246         return NULL;
5247 }
5248 #endif
5249
5250 /*
5251  * SADB_ADD processing
5252  * add an entry to SA database, when received
5253  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5254  *       key(AE), (identity(SD),) (sensitivity)>
5255  * from the ikmpd,
5256  * and send
5257  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5258  *       (identity(SD),) (sensitivity)>
5259  * to the ikmpd.
5260  *
5261  * IGNORE identity and sensitivity messages.
5262  *
5263  * m will always be freed.
5264  */
5265 static int
5266 key_add(so, m, mhp)
5267         struct socket *so;
5268         struct mbuf *m;
5269         const struct sadb_msghdr *mhp;
5270 {
5271         struct sadb_sa *sa0;
5272         struct sadb_address *src0, *dst0;
5273 #ifdef IPSEC_NAT_T
5274         struct sadb_x_nat_t_type *type;
5275         struct sadb_address *iaddr, *raddr;
5276         struct sadb_x_nat_t_frag *frag;
5277 #endif
5278         struct secasindex saidx;
5279         struct secashead *newsah;
5280         struct secasvar *newsav;
5281         u_int16_t proto;
5282         u_int8_t mode;
5283         u_int32_t reqid;
5284         int error;
5285
5286         IPSEC_ASSERT(so != NULL, ("null socket"));
5287         IPSEC_ASSERT(m != NULL, ("null mbuf"));
5288         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5289         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5290
5291         /* map satype to proto */
5292         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5293                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5294                         __func__));
5295                 return key_senderror(so, m, EINVAL);
5296         }
5297
5298         if (mhp->ext[SADB_EXT_SA] == NULL ||
5299             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5300             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5301             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5302              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5303             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5304              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5305             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5306              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5307             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5308              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5309                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5310                         __func__));
5311                 return key_senderror(so, m, EINVAL);
5312         }
5313         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5314             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5315             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5316                 /* XXX need more */
5317                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5318                         __func__));
5319                 return key_senderror(so, m, EINVAL);
5320         }
5321         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5322                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5323                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5324         } else {
5325                 mode = IPSEC_MODE_ANY;
5326                 reqid = 0;
5327         }
5328
5329         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5330         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5331         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5332
5333         /* XXX boundary check against sa_len */
5334         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5335
5336         /*
5337          * Make sure the port numbers are zero.
5338          * In case of NAT-T we will update them later if needed.
5339          */
5340         KEY_PORTTOSADDR(&saidx.src, 0);
5341         KEY_PORTTOSADDR(&saidx.dst, 0);
5342
5343 #ifdef IPSEC_NAT_T
5344         /*
5345          * Handle NAT-T info if present.
5346          */
5347         if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5348             mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5349             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5350                 struct sadb_x_nat_t_port *sport, *dport;
5351
5352                 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5353                     mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5354                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5355                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5356                             __func__));
5357                         return key_senderror(so, m, EINVAL);
5358                 }
5359
5360                 type = (struct sadb_x_nat_t_type *)
5361                     mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5362                 sport = (struct sadb_x_nat_t_port *)
5363                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5364                 dport = (struct sadb_x_nat_t_port *)
5365                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5366
5367                 if (sport)
5368                         KEY_PORTTOSADDR(&saidx.src,
5369                             sport->sadb_x_nat_t_port_port);
5370                 if (dport)
5371                         KEY_PORTTOSADDR(&saidx.dst,
5372                             dport->sadb_x_nat_t_port_port);
5373         } else {
5374                 type = 0;
5375         }
5376         if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5377             mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5378                 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5379                     mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5380                         ipseclog((LOG_DEBUG, "%s: invalid message\n",
5381                             __func__));
5382                         return key_senderror(so, m, EINVAL);
5383                 }
5384                 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5385                 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5386                 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5387         } else {
5388                 iaddr = raddr = NULL;
5389         }
5390         if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5391                 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5392                         ipseclog((LOG_DEBUG, "%s: invalid message\n",
5393                             __func__));
5394                         return key_senderror(so, m, EINVAL);
5395                 }
5396                 frag = (struct sadb_x_nat_t_frag *)
5397                     mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5398         } else {
5399                 frag = 0;
5400         }
5401 #endif
5402
5403         /* get a SA header */
5404         if ((newsah = key_getsah(&saidx)) == NULL) {
5405                 /* create a new SA header */
5406                 if ((newsah = key_newsah(&saidx)) == NULL) {
5407                         ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5408                         return key_senderror(so, m, ENOBUFS);
5409                 }
5410         }
5411
5412         /* set spidx if there */
5413         /* XXX rewrite */
5414         error = key_setident(newsah, m, mhp);
5415         if (error) {
5416                 return key_senderror(so, m, error);
5417         }
5418
5419         /* create new SA entry. */
5420         /* We can create new SA only if SPI is differenct. */
5421         SAHTREE_LOCK();
5422         newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5423         SAHTREE_UNLOCK();
5424         if (newsav != NULL) {
5425                 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5426                 return key_senderror(so, m, EEXIST);
5427         }
5428         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5429         if (newsav == NULL) {
5430                 return key_senderror(so, m, error);
5431         }
5432
5433 #ifdef IPSEC_NAT_T
5434         /*
5435          * Handle more NAT-T info if present,
5436          * now that we have a sav to fill.
5437          */
5438         if (type)
5439                 newsav->natt_type = type->sadb_x_nat_t_type_type;
5440
5441 #if 0
5442         /*
5443          * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5444          * We should actually check for a minimum MTU here, if we
5445          * want to support it in ip_output.
5446          */
5447         if (frag)
5448                 newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5449 #endif
5450 #endif
5451
5452         /* check SA values to be mature. */
5453         if ((error = key_mature(newsav)) != 0) {
5454                 KEY_FREESAV(&newsav);
5455                 return key_senderror(so, m, error);
5456         }
5457
5458         /*
5459          * don't call key_freesav() here, as we would like to keep the SA
5460          * in the database on success.
5461          */
5462
5463     {
5464         struct mbuf *n;
5465
5466         /* set msg buf from mhp */
5467         n = key_getmsgbuf_x1(m, mhp);
5468         if (n == NULL) {
5469                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5470                 return key_senderror(so, m, ENOBUFS);
5471         }
5472
5473         m_freem(m);
5474         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5475     }
5476 }
5477
5478 /* m is retained */
5479 static int
5480 key_setident(sah, m, mhp)
5481         struct secashead *sah;
5482         struct mbuf *m;
5483         const struct sadb_msghdr *mhp;
5484 {
5485         const struct sadb_ident *idsrc, *iddst;
5486         int idsrclen, iddstlen;
5487
5488         IPSEC_ASSERT(sah != NULL, ("null secashead"));
5489         IPSEC_ASSERT(m != NULL, ("null mbuf"));
5490         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5491         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5492
5493         /* don't make buffer if not there */
5494         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5495             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5496                 sah->idents = NULL;
5497                 sah->identd = NULL;
5498                 return 0;
5499         }
5500         
5501         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5502             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5503                 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5504                 return EINVAL;
5505         }
5506
5507         idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5508         iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5509         idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5510         iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5511
5512         /* validity check */
5513         if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5514                 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5515                 return EINVAL;
5516         }
5517
5518         switch (idsrc->sadb_ident_type) {
5519         case SADB_IDENTTYPE_PREFIX:
5520         case SADB_IDENTTYPE_FQDN:
5521         case SADB_IDENTTYPE_USERFQDN:
5522         default:
5523                 /* XXX do nothing */
5524                 sah->idents = NULL;
5525                 sah->identd = NULL;
5526                 return 0;
5527         }
5528
5529         /* make structure */
5530         sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5531         if (sah->idents == NULL) {
5532                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5533                 return ENOBUFS;
5534         }
5535         sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5536         if (sah->identd == NULL) {
5537                 free(sah->idents, M_IPSEC_MISC);
5538                 sah->idents = NULL;
5539                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5540                 return ENOBUFS;
5541         }
5542         sah->idents->type = idsrc->sadb_ident_type;
5543         sah->idents->id = idsrc->sadb_ident_id;
5544
5545         sah->identd->type = iddst->sadb_ident_type;
5546         sah->identd->id = iddst->sadb_ident_id;
5547
5548         return 0;
5549 }
5550
5551 /*
5552  * m will not be freed on return.
5553  * it is caller's responsibility to free the result. 
5554  */
5555 static struct mbuf *
5556 key_getmsgbuf_x1(m, mhp)
5557         struct mbuf *m;
5558         const struct sadb_msghdr *mhp;
5559 {
5560         struct mbuf *n;
5561
5562         IPSEC_ASSERT(m != NULL, ("null mbuf"));
5563         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5564         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5565
5566         /* create new sadb_msg to reply. */
5567         n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5568             SADB_EXT_SA, SADB_X_EXT_SA2,
5569             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5570             SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5571             SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5572         if (!n)
5573                 return NULL;
5574
5575         if (n->m_len < sizeof(struct sadb_msg)) {
5576                 n = m_pullup(n, sizeof(struct sadb_msg));
5577                 if (n == NULL)
5578                         return NULL;
5579         }
5580         mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5581         mtod(n, struct sadb_msg *)->sadb_msg_len =
5582             PFKEY_UNIT64(n->m_pkthdr.len);
5583
5584         return n;
5585 }
5586
5587 static int key_delete_all __P((struct socket *, struct mbuf *,
5588         const struct sadb_msghdr *, u_int16_t));
5589
5590 /*
5591  * SADB_DELETE processing
5592  * receive
5593  *   <base, SA(*), address(SD)>
5594  * from the ikmpd, and set SADB_SASTATE_DEAD,
5595  * and send,
5596  *   <base, SA(*), address(SD)>
5597  * to the ikmpd.
5598  *
5599  * m will always be freed.
5600  */
5601 static int
5602 key_delete(so, m, mhp)
5603         struct socket *so;
5604         struct mbuf *m;
5605         const struct sadb_msghdr *mhp;
5606 {
5607         struct sadb_sa *sa0;
5608         struct sadb_address *src0, *dst0;
5609         struct secasindex saidx;
5610         struct secashead *sah;
5611         struct secasvar *sav = NULL;
5612         u_int16_t proto;
5613
5614         IPSEC_ASSERT(so != NULL, ("null socket"));
5615         IPSEC_ASSERT(m != NULL, ("null mbuf"));
5616         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5617         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5618
5619         /* map satype to proto */
5620         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5621                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5622                         __func__));
5623                 return key_senderror(so, m, EINVAL);
5624         }
5625
5626         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5627             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5628                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5629                         __func__));
5630                 return key_senderror(so, m, EINVAL);
5631         }
5632
5633         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5634             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5635                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5636                         __func__));
5637                 return key_senderror(so, m, EINVAL);
5638         }
5639
5640         if (mhp->ext[SADB_EXT_SA] == NULL) {
5641                 /*
5642                  * Caller wants us to delete all non-LARVAL SAs
5643                  * that match the src/dst.  This is used during
5644                  * IKE INITIAL-CONTACT.
5645                  */
5646                 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5647                 return key_delete_all(so, m, mhp, proto);
5648         } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5649                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5650                         __func__));
5651                 return key_senderror(so, m, EINVAL);
5652         }
5653
5654         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5655         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5656         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5657
5658         /* XXX boundary check against sa_len */
5659         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5660
5661         /*
5662          * Make sure the port numbers are zero.
5663          * In case of NAT-T we will update them later if needed.
5664          */
5665         KEY_PORTTOSADDR(&saidx.src, 0);
5666         KEY_PORTTOSADDR(&saidx.dst, 0);
5667
5668 #ifdef IPSEC_NAT_T
5669         /*
5670          * Handle NAT-T info if present.
5671          */
5672         if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5673             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5674                 struct sadb_x_nat_t_port *sport, *dport;
5675
5676                 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5677                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5678                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5679                             __func__));
5680                         return key_senderror(so, m, EINVAL);
5681                 }
5682
5683                 sport = (struct sadb_x_nat_t_port *)
5684                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5685                 dport = (struct sadb_x_nat_t_port *)
5686                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5687
5688                 if (sport)
5689                         KEY_PORTTOSADDR(&saidx.src,
5690                             sport->sadb_x_nat_t_port_port);
5691                 if (dport)
5692                         KEY_PORTTOSADDR(&saidx.dst,
5693                             dport->sadb_x_nat_t_port_port);
5694         }
5695 #endif
5696
5697         /* get a SA header */
5698         SAHTREE_LOCK();
5699         LIST_FOREACH(sah, &V_sahtree, chain) {
5700                 if (sah->state == SADB_SASTATE_DEAD)
5701                         continue;
5702                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5703                         continue;
5704
5705                 /* get a SA with SPI. */
5706                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5707                 if (sav)
5708                         break;
5709         }
5710         if (sah == NULL) {
5711                 SAHTREE_UNLOCK();
5712                 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5713                 return key_senderror(so, m, ENOENT);
5714         }
5715
5716         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5717         SAHTREE_UNLOCK();
5718         KEY_FREESAV(&sav);
5719
5720     {
5721         struct mbuf *n;
5722         struct sadb_msg *newmsg;
5723
5724         /* create new sadb_msg to reply. */
5725         /* XXX-BZ NAT-T extensions? */
5726         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5727             SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5728         if (!n)
5729                 return key_senderror(so, m, ENOBUFS);
5730
5731         if (n->m_len < sizeof(struct sadb_msg)) {
5732                 n = m_pullup(n, sizeof(struct sadb_msg));
5733                 if (n == NULL)
5734                         return key_senderror(so, m, ENOBUFS);
5735         }
5736         newmsg = mtod(n, struct sadb_msg *);
5737         newmsg->sadb_msg_errno = 0;
5738         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5739
5740         m_freem(m);
5741         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5742     }
5743 }
5744
5745 /*
5746  * delete all SAs for src/dst.  Called from key_delete().
5747  */
5748 static int
5749 key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5750     u_int16_t proto)
5751 {
5752         struct sadb_address *src0, *dst0;
5753         struct secasindex saidx;
5754         struct secashead *sah;
5755         struct secasvar *sav, *nextsav;
5756         u_int stateidx, state;
5757
5758         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5759         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5760
5761         /* XXX boundary check against sa_len */
5762         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5763
5764         /*
5765          * Make sure the port numbers are zero.
5766          * In case of NAT-T we will update them later if needed.
5767          */
5768         KEY_PORTTOSADDR(&saidx.src, 0);
5769         KEY_PORTTOSADDR(&saidx.dst, 0);
5770
5771 #ifdef IPSEC_NAT_T
5772         /*
5773          * Handle NAT-T info if present.
5774          */
5775
5776         if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5777             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5778                 struct sadb_x_nat_t_port *sport, *dport;
5779
5780                 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5781                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5782                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5783                             __func__));
5784                         return key_senderror(so, m, EINVAL);
5785                 }
5786
5787                 sport = (struct sadb_x_nat_t_port *)
5788                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5789                 dport = (struct sadb_x_nat_t_port *)
5790                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5791
5792                 if (sport)
5793                         KEY_PORTTOSADDR(&saidx.src,
5794                             sport->sadb_x_nat_t_port_port);
5795                 if (dport)
5796                         KEY_PORTTOSADDR(&saidx.dst,
5797                             dport->sadb_x_nat_t_port_port);
5798         }
5799 #endif
5800
5801         SAHTREE_LOCK();
5802         LIST_FOREACH(sah, &V_sahtree, chain) {
5803                 if (sah->state == SADB_SASTATE_DEAD)
5804                         continue;
5805                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5806                         continue;
5807
5808                 /* Delete all non-LARVAL SAs. */
5809                 for (stateidx = 0;
5810                      stateidx < _ARRAYLEN(saorder_state_alive);
5811                      stateidx++) {
5812                         state = saorder_state_alive[stateidx];
5813                         if (state == SADB_SASTATE_LARVAL)
5814                                 continue;
5815                         for (sav = LIST_FIRST(&sah->savtree[state]);
5816                              sav != NULL; sav = nextsav) {
5817                                 nextsav = LIST_NEXT(sav, chain);
5818                                 /* sanity check */
5819                                 if (sav->state != state) {
5820                                         ipseclog((LOG_DEBUG, "%s: invalid "
5821                                                 "sav->state (queue %d SA %d)\n",
5822                                                 __func__, state, sav->state));
5823                                         continue;
5824                                 }
5825                                 
5826                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5827                                 KEY_FREESAV(&sav);
5828                         }
5829                 }
5830         }
5831         SAHTREE_UNLOCK();
5832     {
5833         struct mbuf *n;
5834         struct sadb_msg *newmsg;
5835
5836         /* create new sadb_msg to reply. */
5837         /* XXX-BZ NAT-T extensions? */
5838         n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5839             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5840         if (!n)
5841                 return key_senderror(so, m, ENOBUFS);
5842
5843         if (n->m_len < sizeof(struct sadb_msg)) {
5844                 n = m_pullup(n, sizeof(struct sadb_msg));
5845                 if (n == NULL)
5846                         return key_senderror(so, m, ENOBUFS);
5847         }
5848         newmsg = mtod(n, struct sadb_msg *);
5849         newmsg->sadb_msg_errno = 0;
5850         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5851
5852         m_freem(m);
5853         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5854     }
5855 }
5856
5857 /*
5858  * SADB_GET processing
5859  * receive
5860  *   <base, SA(*), address(SD)>
5861  * from the ikmpd, and get a SP and a SA to respond,
5862  * and send,
5863  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5864  *       (identity(SD),) (sensitivity)>
5865  * to the ikmpd.
5866  *
5867  * m will always be freed.
5868  */
5869 static int
5870 key_get(so, m, mhp)
5871         struct socket *so;
5872         struct mbuf *m;
5873         const struct sadb_msghdr *mhp;
5874 {
5875         struct sadb_sa *sa0;
5876         struct sadb_address *src0, *dst0;
5877         struct secasindex saidx;
5878         struct secashead *sah;
5879         struct secasvar *sav = NULL;
5880         u_int16_t proto;
5881
5882         IPSEC_ASSERT(so != NULL, ("null socket"));
5883         IPSEC_ASSERT(m != NULL, ("null mbuf"));
5884         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5885         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5886
5887         /* map satype to proto */
5888         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5889                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5890                         __func__));
5891                 return key_senderror(so, m, EINVAL);
5892         }
5893
5894         if (mhp->ext[SADB_EXT_SA] == NULL ||
5895             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5896             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5897                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5898                         __func__));
5899                 return key_senderror(so, m, EINVAL);
5900         }
5901         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5902             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5903             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5904                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5905                         __func__));
5906                 return key_senderror(so, m, EINVAL);
5907         }
5908
5909         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5910         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5911         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5912
5913         /* XXX boundary check against sa_len */
5914         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5915
5916         /*
5917          * Make sure the port numbers are zero.
5918          * In case of NAT-T we will update them later if needed.
5919          */
5920         KEY_PORTTOSADDR(&saidx.src, 0);
5921         KEY_PORTTOSADDR(&saidx.dst, 0);
5922
5923 #ifdef IPSEC_NAT_T
5924         /*
5925          * Handle NAT-T info if present.
5926          */
5927
5928         if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5929             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5930                 struct sadb_x_nat_t_port *sport, *dport;
5931
5932                 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5933                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5934                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5935                             __func__));
5936                         return key_senderror(so, m, EINVAL);
5937                 }
5938
5939                 sport = (struct sadb_x_nat_t_port *)
5940                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5941                 dport = (struct sadb_x_nat_t_port *)
5942                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5943
5944                 if (sport)
5945                         KEY_PORTTOSADDR(&saidx.src,
5946                             sport->sadb_x_nat_t_port_port);
5947                 if (dport)
5948                         KEY_PORTTOSADDR(&saidx.dst,
5949                             dport->sadb_x_nat_t_port_port);
5950         }
5951 #endif
5952
5953         /* get a SA header */
5954         SAHTREE_LOCK();
5955         LIST_FOREACH(sah, &V_sahtree, chain) {
5956                 if (sah->state == SADB_SASTATE_DEAD)
5957                         continue;
5958                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5959                         continue;
5960
5961                 /* get a SA with SPI. */
5962                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5963                 if (sav)
5964                         break;
5965         }
5966         SAHTREE_UNLOCK();
5967         if (sah == NULL) {
5968                 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5969                 return key_senderror(so, m, ENOENT);
5970         }
5971
5972     {
5973         struct mbuf *n;
5974         u_int8_t satype;
5975
5976         /* map proto to satype */
5977         if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5978                 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5979                         __func__));
5980                 return key_senderror(so, m, EINVAL);
5981         }
5982
5983         /* create new sadb_msg to reply. */
5984         n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5985             mhp->msg->sadb_msg_pid);
5986         if (!n)
5987                 return key_senderror(so, m, ENOBUFS);
5988
5989         m_freem(m);
5990         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5991     }
5992 }
5993
5994 /* XXX make it sysctl-configurable? */
5995 static void
5996 key_getcomb_setlifetime(comb)
5997         struct sadb_comb *comb;
5998 {
5999
6000         comb->sadb_comb_soft_allocations = 1;
6001         comb->sadb_comb_hard_allocations = 1;
6002         comb->sadb_comb_soft_bytes = 0;
6003         comb->sadb_comb_hard_bytes = 0;
6004         comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
6005         comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6006         comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
6007         comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6008 }
6009
6010 /*
6011  * XXX reorder combinations by preference
6012  * XXX no idea if the user wants ESP authentication or not
6013  */
6014 static struct mbuf *
6015 key_getcomb_esp()
6016 {
6017         struct sadb_comb *comb;
6018         struct enc_xform *algo;
6019         struct mbuf *result = NULL, *m, *n;
6020         int encmin;
6021         int i, off, o;
6022         int totlen;
6023         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6024
6025         m = NULL;
6026         for (i = 1; i <= SADB_EALG_MAX; i++) {
6027                 algo = esp_algorithm_lookup(i);
6028                 if (algo == NULL)
6029                         continue;
6030
6031                 /* discard algorithms with key size smaller than system min */
6032                 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6033                         continue;
6034                 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6035                         encmin = V_ipsec_esp_keymin;
6036                 else
6037                         encmin = _BITS(algo->minkey);
6038
6039                 if (V_ipsec_esp_auth)
6040                         m = key_getcomb_ah();
6041                 else {
6042                         IPSEC_ASSERT(l <= MLEN,
6043                                 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6044                         MGET(m, M_DONTWAIT, MT_DATA);
6045                         if (m) {
6046                                 M_ALIGN(m, l);
6047                                 m->m_len = l;
6048                                 m->m_next = NULL;
6049                                 bzero(mtod(m, caddr_t), m->m_len);
6050                         }
6051                 }
6052                 if (!m)
6053                         goto fail;
6054
6055                 totlen = 0;
6056                 for (n = m; n; n = n->m_next)
6057                         totlen += n->m_len;
6058                 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6059
6060                 for (off = 0; off < totlen; off += l) {
6061                         n = m_pulldown(m, off, l, &o);
6062                         if (!n) {
6063                                 /* m is already freed */
6064                                 goto fail;
6065                         }
6066                         comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6067                         bzero(comb, sizeof(*comb));
6068                         key_getcomb_setlifetime(comb);
6069                         comb->sadb_comb_encrypt = i;
6070                         comb->sadb_comb_encrypt_minbits = encmin;
6071                         comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6072                 }
6073
6074                 if (!result)
6075                         result = m;
6076                 else
6077                         m_cat(result, m);
6078         }
6079
6080         return result;
6081
6082  fail:
6083         if (result)
6084                 m_freem(result);
6085         return NULL;
6086 }
6087
6088 static void
6089 key_getsizes_ah(
6090         const struct auth_hash *ah,
6091         int alg,
6092         u_int16_t* min,
6093         u_int16_t* max)
6094 {
6095
6096         *min = *max = ah->keysize;
6097         if (ah->keysize == 0) {
6098                 /*
6099                  * Transform takes arbitrary key size but algorithm
6100                  * key size is restricted.  Enforce this here.
6101                  */
6102                 switch (alg) {
6103                 case SADB_X_AALG_MD5:   *min = *max = 16; break;
6104                 case SADB_X_AALG_SHA:   *min = *max = 20; break;
6105                 case SADB_X_AALG_NULL:  *min = 1; *max = 256; break;
6106                 default:
6107                         DPRINTF(("%s: unknown AH algorithm %u\n",
6108                                 __func__, alg));
6109                         break;
6110                 }
6111         }
6112 }
6113
6114 /*
6115  * XXX reorder combinations by preference
6116  */
6117 static struct mbuf *
6118 key_getcomb_ah()
6119 {
6120         struct sadb_comb *comb;
6121         struct auth_hash *algo;
6122         struct mbuf *m;
6123         u_int16_t minkeysize, maxkeysize;
6124         int i;
6125         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6126
6127         m = NULL;
6128         for (i = 1; i <= SADB_AALG_MAX; i++) {
6129 #if 1
6130                 /* we prefer HMAC algorithms, not old algorithms */
6131                 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
6132                         continue;
6133 #endif
6134                 algo = ah_algorithm_lookup(i);
6135                 if (!algo)
6136                         continue;
6137                 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6138                 /* discard algorithms with key size smaller than system min */
6139                 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6140                         continue;
6141
6142                 if (!m) {
6143                         IPSEC_ASSERT(l <= MLEN,
6144                                 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6145                         MGET(m, M_DONTWAIT, MT_DATA);
6146                         if (m) {
6147                                 M_ALIGN(m, l);
6148                                 m->m_len = l;
6149                                 m->m_next = NULL;
6150                         }
6151                 } else
6152                         M_PREPEND(m, l, M_DONTWAIT);
6153                 if (!m)
6154                         return NULL;
6155
6156                 comb = mtod(m, struct sadb_comb *);
6157                 bzero(comb, sizeof(*comb));
6158                 key_getcomb_setlifetime(comb);
6159                 comb->sadb_comb_auth = i;
6160                 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6161                 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6162         }
6163
6164         return m;
6165 }
6166
6167 /*
6168  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
6169  * XXX reorder combinations by preference
6170  */
6171 static struct mbuf *
6172 key_getcomb_ipcomp()
6173 {
6174         struct sadb_comb *comb;
6175         struct comp_algo *algo;
6176         struct mbuf *m;
6177         int i;
6178         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6179
6180         m = NULL;
6181         for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6182                 algo = ipcomp_algorithm_lookup(i);
6183                 if (!algo)
6184                         continue;
6185
6186                 if (!m) {
6187                         IPSEC_ASSERT(l <= MLEN,
6188                                 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6189                         MGET(m, M_DONTWAIT, MT_DATA);
6190                         if (m) {
6191                                 M_ALIGN(m, l);
6192                                 m->m_len = l;
6193                                 m->m_next = NULL;
6194                         }
6195                 } else
6196                         M_PREPEND(m, l, M_DONTWAIT);
6197                 if (!m)
6198                         return NULL;
6199
6200                 comb = mtod(m, struct sadb_comb *);
6201                 bzero(comb, sizeof(*comb));
6202                 key_getcomb_setlifetime(comb);
6203                 comb->sadb_comb_encrypt = i;
6204                 /* what should we set into sadb_comb_*_{min,max}bits? */
6205         }
6206
6207         return m;
6208 }
6209
6210 /*
6211  * XXX no way to pass mode (transport/tunnel) to userland
6212  * XXX replay checking?
6213  * XXX sysctl interface to ipsec_{ah,esp}_keymin
6214  */
6215 static struct mbuf *
6216 key_getprop(saidx)
6217         const struct secasindex *saidx;
6218 {
6219         struct sadb_prop *prop;
6220         struct mbuf *m, *n;
6221         const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6222         int totlen;
6223
6224         switch (saidx->proto)  {
6225         case IPPROTO_ESP:
6226                 m = key_getcomb_esp();
6227                 break;
6228         case IPPROTO_AH:
6229                 m = key_getcomb_ah();
6230                 break;
6231         case IPPROTO_IPCOMP:
6232                 m = key_getcomb_ipcomp();
6233                 break;
6234         default:
6235                 return NULL;
6236         }
6237
6238         if (!m)
6239                 return NULL;
6240         M_PREPEND(m, l, M_DONTWAIT);
6241         if (!m)
6242                 return NULL;
6243
6244         totlen = 0;
6245         for (n = m; n; n = n->m_next)
6246                 totlen += n->m_len;
6247
6248         prop = mtod(m, struct sadb_prop *);
6249         bzero(prop, sizeof(*prop));
6250         prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6251         prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6252         prop->sadb_prop_replay = 32;    /* XXX */
6253
6254         return m;
6255 }
6256
6257 /*
6258  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6259  * send
6260  *   <base, SA, address(SD), (address(P)), x_policy,
6261  *       (identity(SD),) (sensitivity,) proposal>
6262  * to KMD, and expect to receive
6263  *   <base> with SADB_ACQUIRE if error occured,
6264  * or
6265  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
6266  * from KMD by PF_KEY.
6267  *
6268  * XXX x_policy is outside of RFC2367 (KAME extension).
6269  * XXX sensitivity is not supported.
6270  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6271  * see comment for key_getcomb_ipcomp().
6272  *
6273  * OUT:
6274  *    0     : succeed
6275  *    others: error number
6276  */
6277 static int
6278 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6279 {
6280         struct mbuf *result = NULL, *m;
6281         struct secacq *newacq;
6282         u_int8_t satype;
6283         int error = -1;
6284         u_int32_t seq;
6285
6286         IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6287         satype = key_proto2satype(saidx->proto);
6288         IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6289
6290         /*
6291          * We never do anything about acquirng SA.  There is anather
6292          * solution that kernel blocks to send SADB_ACQUIRE message until
6293          * getting something message from IKEd.  In later case, to be
6294          * managed with ACQUIRING list.
6295          */
6296         /* Get an entry to check whether sending message or not. */
6297         if ((newacq = key_getacq(saidx)) != NULL) {
6298                 if (V_key_blockacq_count < newacq->count) {
6299                         /* reset counter and do send message. */
6300                         newacq->count = 0;
6301                 } else {
6302                         /* increment counter and do nothing. */
6303                         newacq->count++;
6304                         return 0;
6305                 }
6306         } else {
6307                 /* make new entry for blocking to send SADB_ACQUIRE. */
6308                 if ((newacq = key_newacq(saidx)) == NULL)
6309                         return ENOBUFS;
6310         }
6311
6312
6313         seq = newacq->seq;
6314         m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6315         if (!m) {
6316                 error = ENOBUFS;
6317                 goto fail;
6318         }
6319         result = m;
6320
6321         /*
6322          * No SADB_X_EXT_NAT_T_* here: we do not know
6323          * anything related to NAT-T at this time.
6324          */
6325
6326         /* set sadb_address for saidx's. */
6327         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6328             &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6329         if (!m) {
6330                 error = ENOBUFS;
6331                 goto fail;
6332         }
6333         m_cat(result, m);
6334
6335         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6336             &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6337         if (!m) {
6338                 error = ENOBUFS;
6339                 goto fail;
6340         }
6341         m_cat(result, m);
6342
6343         /* XXX proxy address (optional) */
6344
6345         /* set sadb_x_policy */
6346         if (sp) {
6347                 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6348                 if (!m) {
6349                         error = ENOBUFS;
6350                         goto fail;
6351                 }
6352                 m_cat(result, m);
6353         }
6354
6355         /* XXX identity (optional) */
6356 #if 0
6357         if (idexttype && fqdn) {
6358                 /* create identity extension (FQDN) */
6359                 struct sadb_ident *id;
6360                 int fqdnlen;
6361
6362                 fqdnlen = strlen(fqdn) + 1;     /* +1 for terminating-NUL */
6363                 id = (struct sadb_ident *)p;
6364                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6365                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6366                 id->sadb_ident_exttype = idexttype;
6367                 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6368                 bcopy(fqdn, id + 1, fqdnlen);
6369                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6370         }
6371
6372         if (idexttype) {
6373                 /* create identity extension (USERFQDN) */
6374                 struct sadb_ident *id;
6375                 int userfqdnlen;
6376
6377                 if (userfqdn) {
6378                         /* +1 for terminating-NUL */
6379                         userfqdnlen = strlen(userfqdn) + 1;
6380                 } else
6381                         userfqdnlen = 0;
6382                 id = (struct sadb_ident *)p;
6383                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6384                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6385                 id->sadb_ident_exttype = idexttype;
6386                 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6387                 /* XXX is it correct? */
6388                 if (curproc && curproc->p_cred)
6389                         id->sadb_ident_id = curproc->p_cred->p_ruid;
6390                 if (userfqdn && userfqdnlen)
6391                         bcopy(userfqdn, id + 1, userfqdnlen);
6392                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6393         }
6394 #endif
6395
6396         /* XXX sensitivity (optional) */
6397
6398         /* create proposal/combination extension */
6399         m = key_getprop(saidx);
6400 #if 0
6401         /*
6402          * spec conformant: always attach proposal/combination extension,
6403          * the problem is that we have no way to attach it for ipcomp,
6404          * due to the way sadb_comb is declared in RFC2367.
6405          */
6406         if (!m) {
6407                 error = ENOBUFS;
6408                 goto fail;
6409         }
6410         m_cat(result, m);
6411 #else
6412         /*
6413          * outside of spec; make proposal/combination extension optional.
6414          */
6415         if (m)
6416                 m_cat(result, m);
6417 #endif
6418
6419         if ((result->m_flags & M_PKTHDR) == 0) {
6420                 error = EINVAL;
6421                 goto fail;
6422         }
6423
6424         if (result->m_len < sizeof(struct sadb_msg)) {
6425                 result = m_pullup(result, sizeof(struct sadb_msg));
6426                 if (result == NULL) {
6427                         error = ENOBUFS;
6428                         goto fail;
6429                 }
6430         }
6431
6432         result->m_pkthdr.len = 0;
6433         for (m = result; m; m = m->m_next)
6434                 result->m_pkthdr.len += m->m_len;
6435
6436         mtod(result, struct sadb_msg *)->sadb_msg_len =
6437             PFKEY_UNIT64(result->m_pkthdr.len);
6438
6439         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6440
6441  fail:
6442         if (result)
6443                 m_freem(result);
6444         return error;
6445 }
6446
6447 static struct secacq *
6448 key_newacq(const struct secasindex *saidx)
6449 {
6450         struct secacq *newacq;
6451
6452         /* get new entry */
6453         newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6454         if (newacq == NULL) {
6455                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6456                 return NULL;
6457         }
6458
6459         /* copy secindex */
6460         bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6461         newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6462         newacq->created = time_second;
6463         newacq->count = 0;
6464
6465         /* add to acqtree */
6466         ACQ_LOCK();
6467         LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6468         ACQ_UNLOCK();
6469
6470         return newacq;
6471 }
6472
6473 static struct secacq *
6474 key_getacq(const struct secasindex *saidx)
6475 {
6476         struct secacq *acq;
6477
6478         ACQ_LOCK();
6479         LIST_FOREACH(acq, &V_acqtree, chain) {
6480                 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6481                         break;
6482         }
6483         ACQ_UNLOCK();
6484
6485         return acq;
6486 }
6487
6488 static struct secacq *
6489 key_getacqbyseq(seq)
6490         u_int32_t seq;
6491 {
6492         struct secacq *acq;
6493
6494         ACQ_LOCK();
6495         LIST_FOREACH(acq, &V_acqtree, chain) {
6496                 if (acq->seq == seq)
6497                         break;
6498         }
6499         ACQ_UNLOCK();
6500
6501         return acq;
6502 }
6503
6504 static struct secspacq *
6505 key_newspacq(spidx)
6506         struct secpolicyindex *spidx;
6507 {
6508         struct secspacq *acq;
6509
6510         /* get new entry */
6511         acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6512         if (acq == NULL) {
6513                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6514                 return NULL;
6515         }
6516
6517         /* copy secindex */
6518         bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6519         acq->created = time_second;
6520         acq->count = 0;
6521
6522         /* add to spacqtree */
6523         SPACQ_LOCK();
6524         LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6525         SPACQ_UNLOCK();
6526
6527         return acq;
6528 }
6529
6530 static struct secspacq *
6531 key_getspacq(spidx)
6532         struct secpolicyindex *spidx;
6533 {
6534         struct secspacq *acq;
6535
6536         SPACQ_LOCK();
6537         LIST_FOREACH(acq, &V_spacqtree, chain) {
6538                 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6539                         /* NB: return holding spacq_lock */
6540                         return acq;
6541                 }
6542         }
6543         SPACQ_UNLOCK();
6544
6545         return NULL;
6546 }
6547
6548 /*
6549  * SADB_ACQUIRE processing,
6550  * in first situation, is receiving
6551  *   <base>
6552  * from the ikmpd, and clear sequence of its secasvar entry.
6553  *
6554  * In second situation, is receiving
6555  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6556  * from a user land process, and return
6557  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6558  * to the socket.
6559  *
6560  * m will always be freed.
6561  */
6562 static int
6563 key_acquire2(so, m, mhp)
6564         struct socket *so;
6565         struct mbuf *m;
6566         const struct sadb_msghdr *mhp;
6567 {
6568         const struct sadb_address *src0, *dst0;
6569         struct secasindex saidx;
6570         struct secashead *sah;
6571         u_int16_t proto;
6572         int error;
6573
6574         IPSEC_ASSERT(so != NULL, ("null socket"));
6575         IPSEC_ASSERT(m != NULL, ("null mbuf"));
6576         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6577         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6578
6579         /*
6580          * Error message from KMd.
6581          * We assume that if error was occured in IKEd, the length of PFKEY
6582          * message is equal to the size of sadb_msg structure.
6583          * We do not raise error even if error occured in this function.
6584          */
6585         if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6586                 struct secacq *acq;
6587
6588                 /* check sequence number */
6589                 if (mhp->msg->sadb_msg_seq == 0) {
6590                         ipseclog((LOG_DEBUG, "%s: must specify sequence "
6591                                 "number.\n", __func__));
6592                         m_freem(m);
6593                         return 0;
6594                 }
6595
6596                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6597                         /*
6598                          * the specified larval SA is already gone, or we got
6599                          * a bogus sequence number.  we can silently ignore it.
6600                          */
6601                         m_freem(m);
6602                         return 0;
6603                 }
6604
6605                 /* reset acq counter in order to deletion by timehander. */
6606                 acq->created = time_second;
6607                 acq->count = 0;
6608                 m_freem(m);
6609                 return 0;
6610         }
6611
6612         /*
6613          * This message is from user land.
6614          */
6615
6616         /* map satype to proto */
6617         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6618                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6619                         __func__));
6620                 return key_senderror(so, m, EINVAL);
6621         }
6622
6623         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6624             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6625             mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6626                 /* error */
6627                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6628                         __func__));
6629                 return key_senderror(so, m, EINVAL);
6630         }
6631         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6632             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6633             mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6634                 /* error */
6635                 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",        
6636                         __func__));
6637                 return key_senderror(so, m, EINVAL);
6638         }
6639
6640         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6641         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6642
6643         /* XXX boundary check against sa_len */
6644         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6645
6646         /*
6647          * Make sure the port numbers are zero.
6648          * In case of NAT-T we will update them later if needed.
6649          */
6650         KEY_PORTTOSADDR(&saidx.src, 0);
6651         KEY_PORTTOSADDR(&saidx.dst, 0);
6652
6653 #ifndef IPSEC_NAT_T
6654         /*
6655          * Handle NAT-T info if present.
6656          */
6657
6658         if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6659             mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6660                 struct sadb_x_nat_t_port *sport, *dport;
6661
6662                 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6663                     mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6664                         ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6665                             __func__));
6666                         return key_senderror(so, m, EINVAL);
6667                 }
6668
6669                 sport = (struct sadb_x_nat_t_port *)
6670                     mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6671                 dport = (struct sadb_x_nat_t_port *)
6672                     mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6673
6674                 if (sport)
6675                         KEY_PORTTOSADDR(&saidx.src,
6676                             sport->sadb_x_nat_t_port_port);
6677                 if (dport)
6678                         KEY_PORTTOSADDR(&saidx.dst,
6679                             dport->sadb_x_nat_t_port_port);
6680         }
6681 #endif
6682
6683         /* get a SA index */
6684         SAHTREE_LOCK();
6685         LIST_FOREACH(sah, &V_sahtree, chain) {
6686                 if (sah->state == SADB_SASTATE_DEAD)
6687                         continue;
6688                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6689                         break;
6690         }
6691         SAHTREE_UNLOCK();
6692         if (sah != NULL) {
6693                 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6694                 return key_senderror(so, m, EEXIST);
6695         }
6696
6697         error = key_acquire(&saidx, NULL);
6698         if (error != 0) {
6699                 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6700                         __func__, mhp->msg->sadb_msg_errno));
6701                 return key_senderror(so, m, error);
6702         }
6703
6704         return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6705 }
6706
6707 /*
6708  * SADB_REGISTER processing.
6709  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6710  * receive
6711  *   <base>
6712  * from the ikmpd, and register a socket to send PF_KEY messages,
6713  * and send
6714  *   <base, supported>
6715  * to KMD by PF_KEY.
6716  * If socket is detached, must free from regnode.
6717  *
6718  * m will always be freed.
6719  */
6720 static int
6721 key_register(so, m, mhp)
6722         struct socket *so;
6723         struct mbuf *m;
6724         const struct sadb_msghdr *mhp;
6725 {
6726         struct secreg *reg, *newreg = 0;
6727
6728         IPSEC_ASSERT(so != NULL, ("null socket"));
6729         IPSEC_ASSERT(m != NULL, ("null mbuf"));
6730         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6731         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6732
6733         /* check for invalid register message */
6734         if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6735                 return key_senderror(so, m, EINVAL);
6736
6737         /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6738         if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6739                 goto setmsg;
6740
6741         /* check whether existing or not */
6742         REGTREE_LOCK();
6743         LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6744                 if (reg->so == so) {
6745                         REGTREE_UNLOCK();
6746                         ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6747                                 __func__));
6748                         return key_senderror(so, m, EEXIST);
6749                 }
6750         }
6751
6752         /* create regnode */
6753         newreg =  malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6754         if (newreg == NULL) {
6755                 REGTREE_UNLOCK();
6756                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6757                 return key_senderror(so, m, ENOBUFS);
6758         }
6759
6760         newreg->so = so;
6761         ((struct keycb *)sotorawcb(so))->kp_registered++;
6762
6763         /* add regnode to regtree. */
6764         LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6765         REGTREE_UNLOCK();
6766
6767   setmsg:
6768     {
6769         struct mbuf *n;
6770         struct sadb_msg *newmsg;
6771         struct sadb_supported *sup;
6772         u_int len, alen, elen;
6773         int off;
6774         int i;
6775         struct sadb_alg *alg;
6776
6777         /* create new sadb_msg to reply. */
6778         alen = 0;
6779         for (i = 1; i <= SADB_AALG_MAX; i++) {
6780                 if (ah_algorithm_lookup(i))
6781                         alen += sizeof(struct sadb_alg);
6782         }
6783         if (alen)
6784                 alen += sizeof(struct sadb_supported);
6785         elen = 0;
6786         for (i = 1; i <= SADB_EALG_MAX; i++) {
6787                 if (esp_algorithm_lookup(i))
6788                         elen += sizeof(struct sadb_alg);
6789         }
6790         if (elen)
6791                 elen += sizeof(struct sadb_supported);
6792
6793         len = sizeof(struct sadb_msg) + alen + elen;
6794
6795         if (len > MCLBYTES)
6796                 return key_senderror(so, m, ENOBUFS);
6797
6798         MGETHDR(n, M_DONTWAIT, MT_DATA);
6799         if (len > MHLEN) {
6800                 MCLGET(n, M_DONTWAIT);
6801                 if ((n->m_flags & M_EXT) == 0) {
6802                         m_freem(n);
6803                         n = NULL;
6804                 }
6805         }
6806         if (!n)
6807                 return key_senderror(so, m, ENOBUFS);
6808
6809         n->m_pkthdr.len = n->m_len = len;
6810         n->m_next = NULL;
6811         off = 0;
6812
6813         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6814         newmsg = mtod(n, struct sadb_msg *);
6815         newmsg->sadb_msg_errno = 0;
6816         newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6817         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6818
6819         /* for authentication algorithm */
6820         if (alen) {
6821                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6822                 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6823                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6824                 off += PFKEY_ALIGN8(sizeof(*sup));
6825
6826                 for (i = 1; i <= SADB_AALG_MAX; i++) {
6827                         struct auth_hash *aalgo;
6828                         u_int16_t minkeysize, maxkeysize;
6829
6830                         aalgo = ah_algorithm_lookup(i);
6831                         if (!aalgo)
6832                                 continue;
6833                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6834                         alg->sadb_alg_id = i;
6835                         alg->sadb_alg_ivlen = 0;
6836                         key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6837                         alg->sadb_alg_minbits = _BITS(minkeysize);
6838                         alg->sadb_alg_maxbits = _BITS(maxkeysize);
6839                         off += PFKEY_ALIGN8(sizeof(*alg));
6840                 }
6841         }
6842
6843         /* for encryption algorithm */
6844         if (elen) {
6845                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6846                 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6847                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6848                 off += PFKEY_ALIGN8(sizeof(*sup));
6849
6850                 for (i = 1; i <= SADB_EALG_MAX; i++) {
6851                         struct enc_xform *ealgo;
6852
6853                         ealgo = esp_algorithm_lookup(i);
6854                         if (!ealgo)
6855                                 continue;
6856                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6857                         alg->sadb_alg_id = i;
6858                         alg->sadb_alg_ivlen = ealgo->blocksize;
6859                         alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6860                         alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6861                         off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6862                 }
6863         }
6864
6865         IPSEC_ASSERT(off == len,
6866                 ("length assumption failed (off %u len %u)", off, len));
6867
6868         m_freem(m);
6869         return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6870     }
6871 }
6872
6873 /*
6874  * free secreg entry registered.
6875  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6876  */
6877 void
6878 key_freereg(struct socket *so)
6879 {
6880         struct secreg *reg;
6881         int i;
6882
6883         IPSEC_ASSERT(so != NULL, ("NULL so"));
6884
6885         /*
6886          * check whether existing or not.
6887          * check all type of SA, because there is a potential that
6888          * one socket is registered to multiple type of SA.
6889          */
6890         REGTREE_LOCK();
6891         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6892                 LIST_FOREACH(reg, &V_regtree[i], chain) {
6893                         if (reg->so == so && __LIST_CHAINED(reg)) {
6894                                 LIST_REMOVE(reg, chain);
6895                                 free(reg, M_IPSEC_SAR);
6896                                 break;
6897                         }
6898                 }
6899         }
6900         REGTREE_UNLOCK();
6901 }
6902
6903 /*
6904  * SADB_EXPIRE processing
6905  * send
6906  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6907  * to KMD by PF_KEY.
6908  * NOTE: We send only soft lifetime extension.
6909  *
6910  * OUT: 0       : succeed
6911  *      others  : error number
6912  */
6913 static int
6914 key_expire(struct secasvar *sav)
6915 {
6916         int s;
6917         int satype;
6918         struct mbuf *result = NULL, *m;
6919         int len;
6920         int error = -1;
6921         struct sadb_lifetime *lt;
6922
6923         /* XXX: Why do we lock ? */
6924         s = splnet();   /*called from softclock()*/
6925
6926         IPSEC_ASSERT (sav != NULL, ("null sav"));
6927         IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6928
6929         /* set msg header */
6930         satype = key_proto2satype(sav->sah->saidx.proto);
6931         IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6932         m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6933         if (!m) {
6934                 error = ENOBUFS;
6935                 goto fail;
6936         }
6937         result = m;
6938
6939         /* create SA extension */
6940         m = key_setsadbsa(sav);
6941         if (!m) {
6942                 error = ENOBUFS;
6943                 goto fail;
6944         }
6945         m_cat(result, m);
6946
6947         /* create SA extension */
6948         m = key_setsadbxsa2(sav->sah->saidx.mode,
6949                         sav->replay ? sav->replay->count : 0,
6950                         sav->sah->saidx.reqid);
6951         if (!m) {
6952                 error = ENOBUFS;
6953                 goto fail;
6954         }
6955         m_cat(result, m);
6956
6957         /* create lifetime extension (current and soft) */
6958         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6959         m = key_alloc_mbuf(len);
6960         if (!m || m->m_next) {  /*XXX*/
6961                 if (m)
6962                         m_freem(m);
6963                 error = ENOBUFS;
6964                 goto fail;
6965         }
6966         bzero(mtod(m, caddr_t), len);
6967         lt = mtod(m, struct sadb_lifetime *);
6968         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6969         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6970         lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6971         lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6972         lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6973         lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6974         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6975         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6976         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6977         lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6978         lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6979         lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6980         lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6981         m_cat(result, m);
6982
6983         /* set sadb_address for source */
6984         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6985             &sav->sah->saidx.src.sa,
6986             FULLMASK, IPSEC_ULPROTO_ANY);
6987         if (!m) {
6988                 error = ENOBUFS;
6989                 goto fail;
6990         }
6991         m_cat(result, m);
6992
6993         /* set sadb_address for destination */
6994         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6995             &sav->sah->saidx.dst.sa,
6996             FULLMASK, IPSEC_ULPROTO_ANY);
6997         if (!m) {
6998                 error = ENOBUFS;
6999                 goto fail;
7000         }
7001         m_cat(result, m);
7002
7003         /*
7004          * XXX-BZ Handle NAT-T extensions here.
7005          */
7006
7007         if ((result->m_flags & M_PKTHDR) == 0) {
7008                 error = EINVAL;
7009                 goto fail;
7010         }
7011
7012         if (result->m_len < sizeof(struct sadb_msg)) {
7013                 result = m_pullup(result, sizeof(struct sadb_msg));
7014                 if (result == NULL) {
7015                         error = ENOBUFS;
7016                         goto fail;
7017                 }
7018         }
7019
7020         result->m_pkthdr.len = 0;
7021         for (m = result; m; m = m->m_next)
7022                 result->m_pkthdr.len += m->m_len;
7023
7024         mtod(result, struct sadb_msg *)->sadb_msg_len =
7025             PFKEY_UNIT64(result->m_pkthdr.len);
7026
7027         splx(s);
7028         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7029
7030  fail:
7031         if (result)
7032                 m_freem(result);
7033         splx(s);
7034         return error;
7035 }
7036
7037 /*
7038  * SADB_FLUSH processing
7039  * receive
7040  *   <base>
7041  * from the ikmpd, and free all entries in secastree.
7042  * and send,
7043  *   <base>
7044  * to the ikmpd.
7045  * NOTE: to do is only marking SADB_SASTATE_DEAD.
7046  *
7047  * m will always be freed.
7048  */
7049 static int
7050 key_flush(so, m, mhp)
7051         struct socket *so;
7052         struct mbuf *m;
7053         const struct sadb_msghdr *mhp;
7054 {
7055         struct sadb_msg *newmsg;
7056         struct secashead *sah, *nextsah;
7057         struct secasvar *sav, *nextsav;
7058         u_int16_t proto;
7059         u_int8_t state;
7060         u_int stateidx;
7061
7062         IPSEC_ASSERT(so != NULL, ("null socket"));
7063         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7064         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7065
7066         /* map satype to proto */
7067         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7068                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7069                         __func__));
7070                 return key_senderror(so, m, EINVAL);
7071         }
7072
7073         /* no SATYPE specified, i.e. flushing all SA. */
7074         SAHTREE_LOCK();
7075         for (sah = LIST_FIRST(&V_sahtree);
7076              sah != NULL;
7077              sah = nextsah) {
7078                 nextsah = LIST_NEXT(sah, chain);
7079
7080                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7081                  && proto != sah->saidx.proto)
7082                         continue;
7083
7084                 for (stateidx = 0;
7085                      stateidx < _ARRAYLEN(saorder_state_alive);
7086                      stateidx++) {
7087                         state = saorder_state_any[stateidx];
7088                         for (sav = LIST_FIRST(&sah->savtree[state]);
7089                              sav != NULL;
7090                              sav = nextsav) {
7091
7092                                 nextsav = LIST_NEXT(sav, chain);
7093
7094                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7095                                 KEY_FREESAV(&sav);
7096                         }
7097                 }
7098
7099                 sah->state = SADB_SASTATE_DEAD;
7100         }
7101         SAHTREE_UNLOCK();
7102
7103         if (m->m_len < sizeof(struct sadb_msg) ||
7104             sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7105                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7106                 return key_senderror(so, m, ENOBUFS);
7107         }
7108
7109         if (m->m_next)
7110                 m_freem(m->m_next);
7111         m->m_next = NULL;
7112         m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7113         newmsg = mtod(m, struct sadb_msg *);
7114         newmsg->sadb_msg_errno = 0;
7115         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7116
7117         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7118 }
7119
7120 /*
7121  * SADB_DUMP processing
7122  * dump all entries including status of DEAD in SAD.
7123  * receive
7124  *   <base>
7125  * from the ikmpd, and dump all secasvar leaves
7126  * and send,
7127  *   <base> .....
7128  * to the ikmpd.
7129  *
7130  * m will always be freed.
7131  */
7132 static int
7133 key_dump(so, m, mhp)
7134         struct socket *so;
7135         struct mbuf *m;
7136         const struct sadb_msghdr *mhp;
7137 {
7138         struct secashead *sah;
7139         struct secasvar *sav;
7140         u_int16_t proto;
7141         u_int stateidx;
7142         u_int8_t satype;
7143         u_int8_t state;
7144         int cnt;
7145         struct sadb_msg *newmsg;
7146         struct mbuf *n;
7147
7148         IPSEC_ASSERT(so != NULL, ("null socket"));
7149         IPSEC_ASSERT(m != NULL, ("null mbuf"));
7150         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7151         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7152
7153         /* map satype to proto */
7154         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7155                 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7156                         __func__));
7157                 return key_senderror(so, m, EINVAL);
7158         }
7159
7160         /* count sav entries to be sent to the userland. */
7161         cnt = 0;
7162         SAHTREE_LOCK();
7163         LIST_FOREACH(sah, &V_sahtree, chain) {
7164                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7165                  && proto != sah->saidx.proto)
7166                         continue;
7167
7168                 for (stateidx = 0;
7169                      stateidx < _ARRAYLEN(saorder_state_any);
7170                      stateidx++) {
7171                         state = saorder_state_any[stateidx];
7172                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
7173                                 cnt++;
7174                         }
7175                 }
7176         }
7177
7178         if (cnt == 0) {
7179                 SAHTREE_UNLOCK();
7180                 return key_senderror(so, m, ENOENT);
7181         }
7182
7183         /* send this to the userland, one at a time. */
7184         newmsg = NULL;
7185         LIST_FOREACH(sah, &V_sahtree, chain) {
7186                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7187                  && proto != sah->saidx.proto)
7188                         continue;
7189
7190                 /* map proto to satype */
7191                 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7192                         SAHTREE_UNLOCK();
7193                         ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7194                                 "SAD.\n", __func__));
7195                         return key_senderror(so, m, EINVAL);
7196                 }
7197
7198                 for (stateidx = 0;
7199                      stateidx < _ARRAYLEN(saorder_state_any);
7200                      stateidx++) {
7201                         state = saorder_state_any[stateidx];
7202                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
7203                                 n = key_setdumpsa(sav, SADB_DUMP, satype,
7204                                     --cnt, mhp->msg->sadb_msg_pid);
7205                                 if (!n) {
7206                                         SAHTREE_UNLOCK();
7207                                         return key_senderror(so, m, ENOBUFS);
7208                                 }
7209                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7210                         }
7211                 }
7212         }
7213         SAHTREE_UNLOCK();
7214
7215         m_freem(m);
7216         return 0;
7217 }
7218
7219 /*
7220  * SADB_X_PROMISC processing
7221  *
7222  * m will always be freed.
7223  */
7224 static int
7225 key_promisc(so, m, mhp)
7226         struct socket *so;
7227         struct mbuf *m;
7228         const struct sadb_msghdr *mhp;
7229 {
7230         int olen;
7231
7232         IPSEC_ASSERT(so != NULL, ("null socket"));
7233         IPSEC_ASSERT(m != NULL, ("null mbuf"));
7234         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7235         IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7236
7237         olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7238
7239         if (olen < sizeof(struct sadb_msg)) {
7240 #if 1
7241                 return key_senderror(so, m, EINVAL);
7242 #else
7243                 m_freem(m);
7244                 return 0;
7245 #endif
7246         } else if (olen == sizeof(struct sadb_msg)) {
7247                 /* enable/disable promisc mode */
7248                 struct keycb *kp;
7249
7250                 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7251                         return key_senderror(so, m, EINVAL);
7252                 mhp->msg->sadb_msg_errno = 0;
7253                 switch (mhp->msg->sadb_msg_satype) {
7254                 case 0:
7255                 case 1:
7256                         kp->kp_promisc = mhp->msg->sadb_msg_satype;
7257                         break;
7258                 default:
7259                         return key_senderror(so, m, EINVAL);
7260                 }
7261
7262                 /* send the original message back to everyone */
7263                 mhp->msg->sadb_msg_errno = 0;
7264                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7265         } else {
7266                 /* send packet as is */
7267
7268                 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7269
7270                 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7271                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7272         }
7273 }
7274
7275 static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7276                 const struct sadb_msghdr *)) = {
7277         NULL,           /* SADB_RESERVED */
7278         key_getspi,     /* SADB_GETSPI */
7279         key_update,     /* SADB_UPDATE */
7280         key_add,        /* SADB_ADD */
7281         key_delete,     /* SADB_DELETE */
7282         key_get,        /* SADB_GET */
7283         key_acquire2,   /* SADB_ACQUIRE */
7284         key_register,   /* SADB_REGISTER */
7285         NULL,           /* SADB_EXPIRE */
7286         key_flush,      /* SADB_FLUSH */
7287         key_dump,       /* SADB_DUMP */
7288         key_promisc,    /* SADB_X_PROMISC */
7289         NULL,           /* SADB_X_PCHANGE */
7290         key_spdadd,     /* SADB_X_SPDUPDATE */
7291         key_spdadd,     /* SADB_X_SPDADD */
7292         key_spddelete,  /* SADB_X_SPDDELETE */
7293         key_spdget,     /* SADB_X_SPDGET */
7294         NULL,           /* SADB_X_SPDACQUIRE */
7295         key_spddump,    /* SADB_X_SPDDUMP */
7296         key_spdflush,   /* SADB_X_SPDFLUSH */
7297         key_spdadd,     /* SADB_X_SPDSETIDX */
7298         NULL,           /* SADB_X_SPDEXPIRE */
7299         key_spddelete2, /* SADB_X_SPDDELETE2 */
7300 };
7301
7302 /*
7303  * parse sadb_msg buffer to process PFKEYv2,
7304  * and create a data to response if needed.
7305  * I think to be dealed with mbuf directly.
7306  * IN:
7307  *     msgp  : pointer to pointer to a received buffer pulluped.
7308  *             This is rewrited to response.
7309  *     so    : pointer to socket.
7310  * OUT:
7311  *    length for buffer to send to user process.
7312  */
7313 int
7314 key_parse(m, so)
7315         struct mbuf *m;
7316         struct socket *so;
7317 {
7318         struct sadb_msg *msg;
7319         struct sadb_msghdr mh;
7320         u_int orglen;
7321         int error;
7322         int target;
7323
7324         IPSEC_ASSERT(so != NULL, ("null socket"));
7325         IPSEC_ASSERT(m != NULL, ("null mbuf"));
7326
7327 #if 0   /*kdebug_sadb assumes msg in linear buffer*/
7328         KEYDEBUG(KEYDEBUG_KEY_DUMP,
7329                 ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7330                 kdebug_sadb(msg));
7331 #endif
7332
7333         if (m->m_len < sizeof(struct sadb_msg)) {
7334                 m = m_pullup(m, sizeof(struct sadb_msg));
7335                 if (!m)
7336                         return ENOBUFS;
7337         }
7338         msg = mtod(m, struct sadb_msg *);
7339         orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7340         target = KEY_SENDUP_ONE;
7341
7342         if ((m->m_flags & M_PKTHDR) == 0 ||
7343             m->m_pkthdr.len != m->m_pkthdr.len) {
7344                 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7345                 V_pfkeystat.out_invlen++;
7346                 error = EINVAL;
7347                 goto senderror;
7348         }
7349
7350         if (msg->sadb_msg_version != PF_KEY_V2) {
7351                 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7352                     __func__, msg->sadb_msg_version));
7353                 V_pfkeystat.out_invver++;
7354                 error = EINVAL;
7355                 goto senderror;
7356         }
7357
7358         if (msg->sadb_msg_type > SADB_MAX) {
7359                 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7360                     __func__, msg->sadb_msg_type));
7361                 V_pfkeystat.out_invmsgtype++;
7362                 error = EINVAL;
7363                 goto senderror;
7364         }
7365
7366         /* for old-fashioned code - should be nuked */
7367         if (m->m_pkthdr.len > MCLBYTES) {
7368                 m_freem(m);
7369                 return ENOBUFS;
7370         }
7371         if (m->m_next) {
7372                 struct mbuf *n;
7373
7374                 MGETHDR(n, M_DONTWAIT, MT_DATA);
7375                 if (n && m->m_pkthdr.len > MHLEN) {
7376                         MCLGET(n, M_DONTWAIT);
7377                         if ((n->m_flags & M_EXT) == 0) {
7378                                 m_free(n);
7379                                 n = NULL;
7380                         }
7381                 }
7382                 if (!n) {
7383                         m_freem(m);
7384                         return ENOBUFS;
7385                 }
7386                 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7387                 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7388                 n->m_next = NULL;
7389                 m_freem(m);
7390                 m = n;
7391         }
7392
7393         /* align the mbuf chain so that extensions are in contiguous region. */
7394         error = key_align(m, &mh);
7395         if (error)
7396                 return error;
7397
7398         msg = mh.msg;
7399
7400         /* check SA type */
7401         switch (msg->sadb_msg_satype) {
7402         case SADB_SATYPE_UNSPEC:
7403                 switch (msg->sadb_msg_type) {
7404                 case SADB_GETSPI:
7405                 case SADB_UPDATE:
7406                 case SADB_ADD:
7407                 case SADB_DELETE:
7408                 case SADB_GET:
7409                 case SADB_ACQUIRE:
7410                 case SADB_EXPIRE:
7411                         ipseclog((LOG_DEBUG, "%s: must specify satype "
7412                             "when msg type=%u.\n", __func__,
7413                             msg->sadb_msg_type));
7414                         V_pfkeystat.out_invsatype++;
7415                         error = EINVAL;
7416                         goto senderror;
7417                 }
7418                 break;
7419         case SADB_SATYPE_AH:
7420         case SADB_SATYPE_ESP:
7421         case SADB_X_SATYPE_IPCOMP:
7422         case SADB_X_SATYPE_TCPSIGNATURE:
7423                 switch (msg->sadb_msg_type) {
7424                 case SADB_X_SPDADD:
7425                 case SADB_X_SPDDELETE:
7426                 case SADB_X_SPDGET:
7427                 case SADB_X_SPDDUMP:
7428                 case SADB_X_SPDFLUSH:
7429                 case SADB_X_SPDSETIDX:
7430                 case SADB_X_SPDUPDATE:
7431                 case SADB_X_SPDDELETE2:
7432                         ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7433                                 __func__, msg->sadb_msg_type));
7434                         V_pfkeystat.out_invsatype++;
7435                         error = EINVAL;
7436                         goto senderror;
7437                 }
7438                 break;
7439         case SADB_SATYPE_RSVP:
7440         case SADB_SATYPE_OSPFV2:
7441         case SADB_SATYPE_RIPV2:
7442         case SADB_SATYPE_MIP:
7443                 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7444                         __func__, msg->sadb_msg_satype));
7445                 V_pfkeystat.out_invsatype++;
7446                 error = EOPNOTSUPP;
7447                 goto senderror;
7448         case 1: /* XXX: What does it do? */
7449                 if (msg->sadb_msg_type == SADB_X_PROMISC)
7450                         break;
7451                 /*FALLTHROUGH*/
7452         default:
7453                 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7454                         __func__, msg->sadb_msg_satype));
7455                 V_pfkeystat.out_invsatype++;
7456                 error = EINVAL;
7457                 goto senderror;
7458         }
7459
7460         /* check field of upper layer protocol and address family */
7461         if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7462          && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7463                 struct sadb_address *src0, *dst0;
7464                 u_int plen;
7465
7466                 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7467                 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7468
7469                 /* check upper layer protocol */
7470                 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7471                         ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7472                                 "mismatched.\n", __func__));
7473                         V_pfkeystat.out_invaddr++;
7474                         error = EINVAL;
7475                         goto senderror;
7476                 }
7477
7478                 /* check family */
7479                 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7480                     PFKEY_ADDR_SADDR(dst0)->sa_family) {
7481                         ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7482                                 __func__));
7483                         V_pfkeystat.out_invaddr++;
7484                         error = EINVAL;
7485                         goto senderror;
7486                 }
7487                 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7488                     PFKEY_ADDR_SADDR(dst0)->sa_len) {
7489                         ipseclog((LOG_DEBUG, "%s: address struct size "
7490                                 "mismatched.\n", __func__));
7491                         V_pfkeystat.out_invaddr++;
7492                         error = EINVAL;
7493                         goto senderror;
7494                 }
7495
7496                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7497                 case AF_INET:
7498                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7499                             sizeof(struct sockaddr_in)) {
7500                                 V_pfkeystat.out_invaddr++;
7501                                 error = EINVAL;
7502                                 goto senderror;
7503                         }
7504                         break;
7505                 case AF_INET6:
7506                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7507                             sizeof(struct sockaddr_in6)) {
7508                                 V_pfkeystat.out_invaddr++;
7509                                 error = EINVAL;
7510                                 goto senderror;
7511                         }
7512                         break;
7513                 default:
7514                         ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7515                                 __func__));
7516                         V_pfkeystat.out_invaddr++;
7517                         error = EAFNOSUPPORT;
7518                         goto senderror;
7519                 }
7520
7521                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7522                 case AF_INET:
7523                         plen = sizeof(struct in_addr) << 3;
7524                         break;
7525                 case AF_INET6:
7526                         plen = sizeof(struct in6_addr) << 3;
7527                         break;
7528                 default:
7529                         plen = 0;       /*fool gcc*/
7530                         break;
7531                 }
7532
7533                 /* check max prefix length */
7534                 if (src0->sadb_address_prefixlen > plen ||
7535                     dst0->sadb_address_prefixlen > plen) {
7536                         ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7537                                 __func__));
7538                         V_pfkeystat.out_invaddr++;
7539                         error = EINVAL;
7540                         goto senderror;
7541                 }
7542
7543                 /*
7544                  * prefixlen == 0 is valid because there can be a case when
7545                  * all addresses are matched.
7546                  */
7547         }
7548
7549         if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7550             key_typesw[msg->sadb_msg_type] == NULL) {
7551                 V_pfkeystat.out_invmsgtype++;
7552                 error = EINVAL;
7553                 goto senderror;
7554         }
7555
7556         return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7557
7558 senderror:
7559         msg->sadb_msg_errno = error;
7560         return key_sendup_mbuf(so, m, target);
7561 }
7562
7563 static int
7564 key_senderror(so, m, code)
7565         struct socket *so;
7566         struct mbuf *m;
7567         int code;
7568 {
7569         struct sadb_msg *msg;
7570
7571         IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7572                 ("mbuf too small, len %u", m->m_len));
7573
7574         msg = mtod(m, struct sadb_msg *);
7575         msg->sadb_msg_errno = code;
7576         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7577 }
7578
7579 /*
7580  * set the pointer to each header into message buffer.
7581  * m will be freed on error.
7582  * XXX larger-than-MCLBYTES extension?
7583  */
7584 static int
7585 key_align(m, mhp)
7586         struct mbuf *m;
7587         struct sadb_msghdr *mhp;
7588 {
7589         struct mbuf *n;
7590         struct sadb_ext *ext;
7591         size_t off, end;
7592         int extlen;
7593         int toff;
7594
7595         IPSEC_ASSERT(m != NULL, ("null mbuf"));
7596         IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7597         IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7598                 ("mbuf too small, len %u", m->m_len));
7599
7600         /* initialize */
7601         bzero(mhp, sizeof(*mhp));
7602
7603         mhp->msg = mtod(m, struct sadb_msg *);
7604         mhp->ext[0] = (struct sadb_ext *)mhp->msg;      /*XXX backward compat */
7605
7606         end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7607         extlen = end;   /*just in case extlen is not updated*/
7608         for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7609                 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7610                 if (!n) {
7611                         /* m is already freed */
7612                         return ENOBUFS;
7613                 }
7614                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7615
7616                 /* set pointer */
7617                 switch (ext->sadb_ext_type) {
7618                 case SADB_EXT_SA:
7619                 case SADB_EXT_ADDRESS_SRC:
7620                 case SADB_EXT_ADDRESS_DST:
7621                 case SADB_EXT_ADDRESS_PROXY:
7622                 case SADB_EXT_LIFETIME_CURRENT:
7623                 case SADB_EXT_LIFETIME_HARD:
7624                 case SADB_EXT_LIFETIME_SOFT:
7625                 case SADB_EXT_KEY_AUTH:
7626                 case SADB_EXT_KEY_ENCRYPT:
7627                 case SADB_EXT_IDENTITY_SRC:
7628                 case SADB_EXT_IDENTITY_DST:
7629                 case SADB_EXT_SENSITIVITY:
7630                 case SADB_EXT_PROPOSAL:
7631                 case SADB_EXT_SUPPORTED_AUTH:
7632                 case SADB_EXT_SUPPORTED_ENCRYPT:
7633                 case SADB_EXT_SPIRANGE:
7634                 case SADB_X_EXT_POLICY:
7635                 case SADB_X_EXT_SA2:
7636 #ifdef IPSEC_NAT_T
7637                 case SADB_X_EXT_NAT_T_TYPE:
7638                 case SADB_X_EXT_NAT_T_SPORT:
7639                 case SADB_X_EXT_NAT_T_DPORT:
7640                 case SADB_X_EXT_NAT_T_OAI:
7641                 case SADB_X_EXT_NAT_T_OAR:
7642                 case SADB_X_EXT_NAT_T_FRAG:
7643 #endif
7644                         /* duplicate check */
7645                         /*
7646                          * XXX Are there duplication payloads of either
7647                          * KEY_AUTH or KEY_ENCRYPT ?
7648                          */
7649                         if (mhp->ext[ext->sadb_ext_type] != NULL) {
7650                                 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7651                                         "%u\n", __func__, ext->sadb_ext_type));
7652                                 m_freem(m);
7653                                 V_pfkeystat.out_dupext++;
7654                                 return EINVAL;
7655                         }
7656                         break;
7657                 default:
7658                         ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7659                                 __func__, ext->sadb_ext_type));
7660                         m_freem(m);
7661                         V_pfkeystat.out_invexttype++;
7662                         return EINVAL;
7663                 }
7664
7665                 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7666
7667                 if (key_validate_ext(ext, extlen)) {
7668                         m_freem(m);
7669                         V_pfkeystat.out_invlen++;
7670                         return EINVAL;
7671                 }
7672
7673                 n = m_pulldown(m, off, extlen, &toff);
7674                 if (!n) {
7675                         /* m is already freed */
7676                         return ENOBUFS;
7677                 }
7678                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7679
7680                 mhp->ext[ext->sadb_ext_type] = ext;
7681                 mhp->extoff[ext->sadb_ext_type] = off;
7682                 mhp->extlen[ext->sadb_ext_type] = extlen;
7683         }
7684
7685         if (off != end) {
7686                 m_freem(m);
7687                 V_pfkeystat.out_invlen++;
7688                 return EINVAL;
7689         }
7690
7691         return 0;
7692 }
7693
7694 static int
7695 key_validate_ext(ext, len)
7696         const struct sadb_ext *ext;
7697         int len;
7698 {
7699         const struct sockaddr *sa;
7700         enum { NONE, ADDR } checktype = NONE;
7701         int baselen = 0;
7702         const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7703
7704         if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7705                 return EINVAL;
7706
7707         /* if it does not match minimum/maximum length, bail */
7708         if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7709             ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7710                 return EINVAL;
7711         if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7712                 return EINVAL;
7713         if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7714                 return EINVAL;
7715
7716         /* more checks based on sadb_ext_type XXX need more */
7717         switch (ext->sadb_ext_type) {
7718         case SADB_EXT_ADDRESS_SRC:
7719         case SADB_EXT_ADDRESS_DST:
7720         case SADB_EXT_ADDRESS_PROXY:
7721                 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7722                 checktype = ADDR;
7723                 break;
7724         case SADB_EXT_IDENTITY_SRC:
7725         case SADB_EXT_IDENTITY_DST:
7726                 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7727                     SADB_X_IDENTTYPE_ADDR) {
7728                         baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7729                         checktype = ADDR;
7730                 } else
7731                         checktype = NONE;
7732                 break;
7733         default:
7734                 checktype = NONE;
7735                 break;
7736         }
7737
7738         switch (checktype) {
7739         case NONE:
7740                 break;
7741         case ADDR:
7742                 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7743                 if (len < baselen + sal)
7744                         return EINVAL;
7745                 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7746                         return EINVAL;
7747                 break;
7748         }
7749
7750         return 0;
7751 }
7752
7753 void
7754 key_init(void)
7755 {
7756         int i;
7757
7758         for (i = 0; i < IPSEC_DIR_MAX; i++)
7759                 LIST_INIT(&V_sptree[i]);
7760
7761         LIST_INIT(&V_sahtree);
7762
7763         for (i = 0; i <= SADB_SATYPE_MAX; i++)
7764                 LIST_INIT(&V_regtree[i]);
7765
7766         LIST_INIT(&V_acqtree);
7767         LIST_INIT(&V_spacqtree);
7768
7769         /* system default */
7770         V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7771         V_ip4_def_policy.refcnt++;      /*never reclaim this*/
7772
7773         if (!IS_DEFAULT_VNET(curvnet))
7774                 return;
7775
7776         SPTREE_LOCK_INIT();
7777         REGTREE_LOCK_INIT();
7778         SAHTREE_LOCK_INIT();
7779         ACQ_LOCK_INIT();
7780         SPACQ_LOCK_INIT();
7781
7782 #ifndef IPSEC_DEBUG2
7783         timeout((void *)key_timehandler, (void *)0, hz);
7784 #endif /*IPSEC_DEBUG2*/
7785
7786         /* initialize key statistics */
7787         keystat.getspi_count = 1;
7788
7789         printf("IPsec: Initialized Security Association Processing.\n");
7790 }
7791
7792 #ifdef VIMAGE
7793 void
7794 key_destroy(void)
7795 {
7796         struct secpolicy *sp, *nextsp;
7797         struct secacq *acq, *nextacq;
7798         struct secspacq *spacq, *nextspacq;
7799         struct secashead *sah, *nextsah;
7800         struct secreg *reg;
7801         int i;
7802
7803         SPTREE_LOCK();
7804         for (i = 0; i < IPSEC_DIR_MAX; i++) {
7805                 for (sp = LIST_FIRST(&V_sptree[i]); 
7806                     sp != NULL; sp = nextsp) {
7807                         nextsp = LIST_NEXT(sp, chain);
7808                         if (__LIST_CHAINED(sp)) {
7809                                 LIST_REMOVE(sp, chain);
7810                                 free(sp, M_IPSEC_SP);
7811                         }
7812                 }
7813         }
7814         SPTREE_UNLOCK();
7815
7816         SAHTREE_LOCK();
7817         for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7818                 nextsah = LIST_NEXT(sah, chain);
7819                 if (__LIST_CHAINED(sah)) {
7820                         LIST_REMOVE(sah, chain);
7821                         free(sah, M_IPSEC_SAH);
7822                 }
7823         }
7824         SAHTREE_UNLOCK();
7825
7826         REGTREE_LOCK();
7827         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7828                 LIST_FOREACH(reg, &V_regtree[i], chain) {
7829                         if (__LIST_CHAINED(reg)) {
7830                                 LIST_REMOVE(reg, chain);
7831                                 free(reg, M_IPSEC_SAR);
7832                                 break;
7833                         }
7834                 }
7835         }
7836         REGTREE_UNLOCK();
7837
7838         ACQ_LOCK();
7839         for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7840                 nextacq = LIST_NEXT(acq, chain);
7841                 if (__LIST_CHAINED(acq)) {
7842                         LIST_REMOVE(acq, chain);
7843                         free(acq, M_IPSEC_SAQ);
7844                 }
7845         }
7846         ACQ_UNLOCK();
7847
7848         SPACQ_LOCK();
7849         for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7850             spacq = nextspacq) {
7851                 nextspacq = LIST_NEXT(spacq, chain);
7852                 if (__LIST_CHAINED(spacq)) {
7853                         LIST_REMOVE(spacq, chain);
7854                         free(spacq, M_IPSEC_SAQ);
7855                 }
7856         }
7857         SPACQ_UNLOCK();
7858 }
7859 #endif
7860
7861 /*
7862  * XXX: maybe This function is called after INBOUND IPsec processing.
7863  *
7864  * Special check for tunnel-mode packets.
7865  * We must make some checks for consistency between inner and outer IP header.
7866  *
7867  * xxx more checks to be provided
7868  */
7869 int
7870 key_checktunnelsanity(sav, family, src, dst)
7871         struct secasvar *sav;
7872         u_int family;
7873         caddr_t src;
7874         caddr_t dst;
7875 {
7876         IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7877
7878         /* XXX: check inner IP header */
7879
7880         return 1;
7881 }
7882
7883 /* record data transfer on SA, and update timestamps */
7884 void
7885 key_sa_recordxfer(sav, m)
7886         struct secasvar *sav;
7887         struct mbuf *m;
7888 {
7889         IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7890         IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7891         if (!sav->lft_c)
7892                 return;
7893
7894         /*
7895          * XXX Currently, there is a difference of bytes size
7896          * between inbound and outbound processing.
7897          */
7898         sav->lft_c->bytes += m->m_pkthdr.len;
7899         /* to check bytes lifetime is done in key_timehandler(). */
7900
7901         /*
7902          * We use the number of packets as the unit of
7903          * allocations.  We increment the variable
7904          * whenever {esp,ah}_{in,out}put is called.
7905          */
7906         sav->lft_c->allocations++;
7907         /* XXX check for expires? */
7908
7909         /*
7910          * NOTE: We record CURRENT usetime by using wall clock,
7911          * in seconds.  HARD and SOFT lifetime are measured by the time
7912          * difference (again in seconds) from usetime.
7913          *
7914          *      usetime
7915          *      v     expire   expire
7916          * -----+-----+--------+---> t
7917          *      <--------------> HARD
7918          *      <-----> SOFT
7919          */
7920         sav->lft_c->usetime = time_second;
7921         /* XXX check for expires? */
7922
7923         return;
7924 }
7925
7926 /* dumb version */
7927 void
7928 key_sa_routechange(dst)
7929         struct sockaddr *dst;
7930 {
7931         struct secashead *sah;
7932         struct route *ro;
7933
7934         SAHTREE_LOCK();
7935         LIST_FOREACH(sah, &V_sahtree, chain) {
7936                 ro = &sah->sa_route;
7937                 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7938                  && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7939                         RTFREE(ro->ro_rt);
7940                         ro->ro_rt = (struct rtentry *)NULL;
7941                 }
7942         }
7943         SAHTREE_UNLOCK();
7944 }
7945
7946 static void
7947 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7948 {
7949         IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7950         SAHTREE_LOCK_ASSERT();
7951
7952         if (sav->state != state) {
7953                 if (__LIST_CHAINED(sav))
7954                         LIST_REMOVE(sav, chain);
7955                 sav->state = state;
7956                 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7957         }
7958 }
7959
7960 void
7961 key_sa_stir_iv(sav)
7962         struct secasvar *sav;
7963 {
7964
7965         IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7966         key_randomfill(sav->iv, sav->ivlen);
7967 }
7968
7969 /* XXX too much? */
7970 static struct mbuf *
7971 key_alloc_mbuf(l)
7972         int l;
7973 {
7974         struct mbuf *m = NULL, *n;
7975         int len, t;
7976
7977         len = l;
7978         while (len > 0) {
7979                 MGET(n, M_DONTWAIT, MT_DATA);
7980                 if (n && len > MLEN)
7981                         MCLGET(n, M_DONTWAIT);
7982                 if (!n) {
7983                         m_freem(m);
7984                         return NULL;
7985                 }
7986
7987                 n->m_next = NULL;
7988                 n->m_len = 0;
7989                 n->m_len = M_TRAILINGSPACE(n);
7990                 /* use the bottom of mbuf, hoping we can prepend afterwards */
7991                 if (n->m_len > len) {
7992                         t = (n->m_len - len) & ~(sizeof(long) - 1);
7993                         n->m_data += t;
7994                         n->m_len = len;
7995                 }
7996
7997                 len -= n->m_len;
7998
7999                 if (m)
8000                         m_cat(m, n);
8001                 else
8002                         m = n;
8003         }
8004
8005         return m;
8006 }
8007
8008 /*
8009  * Take one of the kernel's security keys and convert it into a PF_KEY
8010  * structure within an mbuf, suitable for sending up to a waiting
8011  * application in user land.
8012  * 
8013  * IN: 
8014  *    src: A pointer to a kernel security key.
8015  *    exttype: Which type of key this is. Refer to the PF_KEY data structures.
8016  * OUT:
8017  *    a valid mbuf or NULL indicating an error
8018  *
8019  */
8020
8021 static struct mbuf *
8022 key_setkey(struct seckey *src, u_int16_t exttype) 
8023 {
8024         struct mbuf *m;
8025         struct sadb_key *p;
8026         int len;
8027
8028         if (src == NULL)
8029                 return NULL;
8030
8031         len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8032         m = key_alloc_mbuf(len);
8033         if (m == NULL)
8034                 return NULL;
8035         p = mtod(m, struct sadb_key *);
8036         bzero(p, len);
8037         p->sadb_key_len = PFKEY_UNIT64(len);
8038         p->sadb_key_exttype = exttype;
8039         p->sadb_key_bits = src->bits;
8040         bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8041
8042         return m;
8043 }
8044
8045 /*
8046  * Take one of the kernel's lifetime data structures and convert it
8047  * into a PF_KEY structure within an mbuf, suitable for sending up to
8048  * a waiting application in user land.
8049  * 
8050  * IN: 
8051  *    src: A pointer to a kernel lifetime structure.
8052  *    exttype: Which type of lifetime this is. Refer to the PF_KEY 
8053  *             data structures for more information.
8054  * OUT:
8055  *    a valid mbuf or NULL indicating an error
8056  *
8057  */
8058
8059 static struct mbuf *
8060 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
8061 {
8062         struct mbuf *m = NULL;
8063         struct sadb_lifetime *p;
8064         int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8065
8066         if (src == NULL)
8067                 return NULL;
8068
8069         m = key_alloc_mbuf(len);
8070         if (m == NULL)
8071                 return m;
8072         p = mtod(m, struct sadb_lifetime *);
8073
8074         bzero(p, len);
8075         p->sadb_lifetime_len = PFKEY_UNIT64(len);
8076         p->sadb_lifetime_exttype = exttype;
8077         p->sadb_lifetime_allocations = src->allocations;
8078         p->sadb_lifetime_bytes = src->bytes;
8079         p->sadb_lifetime_addtime = src->addtime;
8080         p->sadb_lifetime_usetime = src->usetime;
8081         
8082         return m;
8083
8084 }