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