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