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