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