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