kernel: Add a number of missing crit_exit, lwkt_reltoken, rel_mplock, etc.
[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 /*      $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
3
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 /*
34  * This code is referd to RFC 2367
35  */
36
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/mbuf.h>
46 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/malloc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/errno.h>
53 #include <sys/proc.h>
54 #include <sys/queue.h>
55 #include <sys/syslog.h>
56
57 #include <net/if.h>
58 #include <net/route.h>
59 #include <net/raw_cb.h>
60
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/in_var.h>
65
66 #ifdef INET6
67 #include <netinet/ip6.h>
68 #include <netinet6/in6_var.h>
69 #include <netinet6/ip6_var.h>
70 #endif /* INET6 */
71
72 #ifdef INET
73 #include <netinet/in_pcb.h>
74 #endif
75 #ifdef INET6
76 #include <netinet6/in6_pcb.h>
77 #endif /* INET6 */
78
79 #include <net/pfkeyv2.h>
80 #include <netproto/ipsec/keydb.h>
81 #include <netproto/ipsec/key.h>
82 #include <netproto/ipsec/keysock.h>
83 #include <netproto/ipsec/key_debug.h>
84
85 #include <netproto/ipsec/ipsec.h>
86 #ifdef INET6
87 #include <netproto/ipsec/ipsec6.h>
88 #endif
89
90 #include <netproto/ipsec/xform.h>
91
92 #include <machine/stdarg.h>
93
94 /* randomness */
95 #include <sys/random.h>
96
97 #include <net/net_osdep.h>
98
99 #define FULLMASK        0xff
100 #define _BITS(bytes)    ((bytes) << 3)
101
102 /*
103  * Note on SA reference counting:
104  * - SAs that are not in DEAD state will have (total external reference + 1)
105  *   following value in reference count field.  they cannot be freed and are
106  *   referenced from SA header.
107  * - SAs that are in DEAD state will have (total external reference)
108  *   in reference count field.  they are ready to be freed.  reference from
109  *   SA header will be removed in key_delsav(), when the reference count
110  *   field hits 0 (= no external reference other than from SA header.
111  */
112
113 #ifndef IPSEC_DEBUG2
114 static struct callout key_timehandler_ch;
115 #endif
116 u_int32_t key_debug_level = 0;
117 static u_int key_spi_trycnt = 1000;
118 static u_int32_t key_spi_minval = 0x100;
119 static u_int32_t key_spi_maxval = 0x0fffffff;   /* XXX */
120 static u_int32_t policy_id = 0;
121 static u_int key_int_random = 60;       /*interval to initialize randseed,1(m)*/
122 static u_int key_larval_lifetime = 30;  /* interval to expire acquiring, 30(s)*/
123 static int key_blockacq_count = 10;     /* counter for blocking SADB_ACQUIRE.*/
124 static int key_blockacq_lifetime = 20;  /* lifetime for blocking SADB_ACQUIRE.*/
125 static int key_prefered_oldsa = 1;      /* prefered old sa rather than new sa.*/
126
127 static u_int32_t acq_seq = 0;
128 static int key_tick_init_random = 0;
129
130 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];     /* SPD */
131 static LIST_HEAD(_sahtree, secashead) sahtree;                  /* SAD */
132 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
133                                                         /* registed list */
134 #ifndef IPSEC_NONBLOCK_ACQUIRE
135 static LIST_HEAD(_acqtree, secacq) acqtree;             /* acquiring list */
136 #endif
137 static LIST_HEAD(_spacqtree, secspacq) spacqtree;       /* SP acquiring list */
138
139 /* search order for SAs */
140 static u_int saorder_state_valid[] = {
141         SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
142         /*
143          * This order is important because we must select the oldest SA
144          * for outbound processing.  For inbound, This is not important.
145          */
146 };
147 static u_int saorder_state_alive[] = {
148         /* except DEAD */
149         SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
150 };
151 static u_int saorder_state_any[] = {
152         SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
153         SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
154 };
155
156 static const int minsize[] = {
157         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
158         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
159         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
160         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
161         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
162         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_SRC */
163         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_DST */
164         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_PROXY */
165         sizeof(struct sadb_key),        /* SADB_EXT_KEY_AUTH */
166         sizeof(struct sadb_key),        /* SADB_EXT_KEY_ENCRYPT */
167         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_SRC */
168         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_DST */
169         sizeof(struct sadb_sens),       /* SADB_EXT_SENSITIVITY */
170         sizeof(struct sadb_prop),       /* SADB_EXT_PROPOSAL */
171         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_AUTH */
172         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_ENCRYPT */
173         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
174         0,                              /* SADB_X_EXT_KMPRIVATE */
175         sizeof(struct sadb_x_policy),   /* SADB_X_EXT_POLICY */
176         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
177 };
178 static const int maxsize[] = {
179         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
180         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
181         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
182         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
183         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
184         0,                              /* SADB_EXT_ADDRESS_SRC */
185         0,                              /* SADB_EXT_ADDRESS_DST */
186         0,                              /* SADB_EXT_ADDRESS_PROXY */
187         0,                              /* SADB_EXT_KEY_AUTH */
188         0,                              /* SADB_EXT_KEY_ENCRYPT */
189         0,                              /* SADB_EXT_IDENTITY_SRC */
190         0,                              /* SADB_EXT_IDENTITY_DST */
191         0,                              /* SADB_EXT_SENSITIVITY */
192         0,                              /* SADB_EXT_PROPOSAL */
193         0,                              /* SADB_EXT_SUPPORTED_AUTH */
194         0,                              /* SADB_EXT_SUPPORTED_ENCRYPT */
195         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
196         0,                              /* SADB_X_EXT_KMPRIVATE */
197         0,                              /* SADB_X_EXT_POLICY */
198         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
199 };
200
201 static int ipsec_esp_keymin = 256;
202 static int ipsec_esp_auth = 0;
203 static int ipsec_ah_keymin = 128;
204
205 #ifdef SYSCTL_DECL
206 SYSCTL_DECL(_net_key);
207 #endif
208
209 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,        debug,  CTLFLAG_RW, \
210         &key_debug_level,       0,      "");
211
212 /* max count of trial for the decision of spi value */
213 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,            spi_trycnt,     CTLFLAG_RW, \
214         &key_spi_trycnt,        0,      "");
215
216 /* minimum spi value to allocate automatically. */
217 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,      spi_minval,     CTLFLAG_RW, \
218         &key_spi_minval,        0,      "");
219
220 /* maximun spi value to allocate automatically. */
221 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,      spi_maxval,     CTLFLAG_RW, \
222         &key_spi_maxval,        0,      "");
223
224 /* interval to initialize randseed */
225 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,     CTLFLAG_RW, \
226         &key_int_random,        0,      "");
227
228 /* lifetime for larval SA */
229 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,    larval_lifetime, CTLFLAG_RW, \
230         &key_larval_lifetime,   0,      "");
231
232 /* counter for blocking to send SADB_ACQUIRE to IKEd */
233 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,     blockacq_count, CTLFLAG_RW, \
234         &key_blockacq_count,    0,      "");
235
236 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
237 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,  blockacq_lifetime, CTLFLAG_RW, \
238         &key_blockacq_lifetime, 0,      "");
239
240 /* ESP auth */
241 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,   esp_auth, CTLFLAG_RW, \
242         &ipsec_esp_auth,        0,      "");
243
244 /* minimum ESP key length */
245 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW, \
246         &ipsec_esp_keymin,      0,      "");
247
248 /* minimum AH key length */
249 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,  ah_keymin, CTLFLAG_RW, \
250         &ipsec_ah_keymin,       0,      "");
251
252 /* perfered old SA rather than new SA */
253 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,     prefered_oldsa, CTLFLAG_RW,\
254         &key_prefered_oldsa,    0,      "");
255
256 #define __LIST_CHAINED(elm) \
257         (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
258 #define LIST_INSERT_TAIL(head, elm, type, field) \
259 do {\
260         struct type *curelm = LIST_FIRST(head); \
261         if (curelm == NULL) {\
262                 LIST_INSERT_HEAD(head, elm, field); \
263         } else { \
264                 while (LIST_NEXT(curelm, field)) \
265                         curelm = LIST_NEXT(curelm, field);\
266                 LIST_INSERT_AFTER(curelm, elm, field);\
267         }\
268 } while (0)
269
270 #define KEY_CHKSASTATE(head, sav, name) \
271 do { \
272         if ((head) != (sav)) {                                          \
273                 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
274                         (name), (head), (sav)));                        \
275                 continue;                                               \
276         }                                                               \
277 } while (0)
278
279 #define KEY_CHKSPDIR(head, sp, name) \
280 do { \
281         if ((head) != (sp)) {                                           \
282                 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
283                         "anyway continue.\n",                           \
284                         (name), (head), (sp)));                         \
285         }                                                               \
286 } while (0)
287
288 MALLOC_DEFINE(M_SECA, "key mgmt", "security associations, key management");
289
290 #if 1
291 #define KMALLOC(p, t, n)                                                     \
292         ((p) = (t) kmalloc((unsigned long)(n), M_SECA, M_INTWAIT | M_NULLOK))
293 #define KFREE(p)                                                             \
294         kfree((caddr_t)(p), M_SECA)
295 #else
296 #define KMALLOC(p, t, n) \
297 do { \
298         ((p) = (t)kmalloc((unsigned long)(n), M_SECA, M_INTWAIT | M_NULLOK)); \
299         kprintf("%s %d: %p <- KMALLOC(%s, %d)\n",                             \
300                 __FILE__, __LINE__, (p), #t, n);                             \
301 } while (0)
302
303 #define KFREE(p)                                                             \
304         do {                                                                 \
305                 kprintf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p));   \
306                 kfree((caddr_t)(p), M_SECA);                                  \
307         } while (0)
308 #endif
309
310 /*
311  * set parameters into secpolicyindex buffer.
312  * Must allocate secpolicyindex buffer passed to this function.
313  */
314 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
315 do { \
316         bzero((idx), sizeof(struct secpolicyindex));                         \
317         (idx)->dir = (_dir);                                                 \
318         (idx)->prefs = (ps);                                                 \
319         (idx)->prefd = (pd);                                                 \
320         (idx)->ul_proto = (ulp);                                             \
321         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
322         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
323 } while (0)
324
325 /*
326  * set parameters into secasindex buffer.
327  * Must allocate secasindex buffer before calling this function.
328  */
329 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
330 do { \
331         bzero((idx), sizeof(struct secasindex));                             \
332         (idx)->proto = (p);                                                  \
333         (idx)->mode = (m);                                                   \
334         (idx)->reqid = (r);                                                  \
335         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
336         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
337 } while (0)
338
339 /* key statistics */
340 struct _keystat {
341         u_long getspi_count; /* the avarage of count to try to get new SPI */
342 } keystat;
343
344 struct sadb_msghdr {
345         struct sadb_msg *msg;
346         struct sadb_ext *ext[SADB_EXT_MAX + 1];
347         int extoff[SADB_EXT_MAX + 1];
348         int extlen[SADB_EXT_MAX + 1];
349 };
350
351 static struct secasvar *key_allocsa_policy (const struct secasindex *);
352 static void key_freesp_so (struct secpolicy **);
353 static struct secasvar *key_do_allocsa_policy (struct secashead *, u_int);
354 static void key_delsp (struct secpolicy *);
355 static struct secpolicy *key_getsp (struct secpolicyindex *);
356 static struct secpolicy *key_getspbyid (u_int32_t);
357 static u_int32_t key_newreqid (void);
358 static struct mbuf *key_gather_mbuf (struct mbuf *,
359         const struct sadb_msghdr *, int, int, ...);
360 static int key_spdadd (struct socket *, struct mbuf *,
361         const struct sadb_msghdr *);
362 static u_int32_t key_getnewspid (void);
363 static int key_spddelete (struct socket *, struct mbuf *,
364         const struct sadb_msghdr *);
365 static int key_spddelete2 (struct socket *, struct mbuf *,
366         const struct sadb_msghdr *);
367 static int key_spdget (struct socket *, struct mbuf *,
368         const struct sadb_msghdr *);
369 static int key_spdflush (struct socket *, struct mbuf *,
370         const struct sadb_msghdr *);
371 static int key_spddump (struct socket *, struct mbuf *,
372         const struct sadb_msghdr *);
373 static struct mbuf *key_setdumpsp (struct secpolicy *,
374         u_int8_t, u_int32_t, u_int32_t);
375 static u_int key_getspreqmsglen (struct secpolicy *);
376 static int key_spdexpire (struct secpolicy *);
377 static struct secashead *key_newsah (struct secasindex *);
378 static void key_delsah (struct secashead *);
379 static struct secasvar *key_newsav (struct mbuf *,
380         const struct sadb_msghdr *, struct secashead *, int *,
381         const char*, int);
382 #define KEY_NEWSAV(m, sadb, sah, e)                             \
383         key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
384 static void key_delsav (struct secasvar *);
385 static struct secashead *key_getsah (struct secasindex *);
386 static struct secasvar *key_checkspidup (struct secasindex *, u_int32_t);
387 static struct secasvar *key_getsavbyspi (struct secashead *, u_int32_t);
388 static int key_setsaval (struct secasvar *, struct mbuf *,
389         const struct sadb_msghdr *);
390 static int key_mature (struct secasvar *);
391 static struct mbuf *key_setdumpsa (struct secasvar *, u_int8_t,
392         u_int8_t, u_int32_t, u_int32_t);
393 static struct mbuf *key_setsadbmsg (u_int8_t, u_int16_t, u_int8_t,
394         u_int32_t, pid_t, u_int16_t);
395 static struct mbuf *key_setsadbsa (struct secasvar *);
396 static struct mbuf *key_setsadbaddr (u_int16_t,
397         const struct sockaddr *, u_int8_t, u_int16_t);
398 #if 0
399 static struct mbuf *key_setsadbident (u_int16_t, u_int16_t, caddr_t,
400         int, u_int64_t);
401 #endif
402 static struct mbuf *key_setsadbxsa2 (u_int8_t, u_int32_t, u_int32_t);
403 static struct mbuf *key_setsadbxpolicy (u_int16_t, u_int8_t,
404         u_int32_t);
405 static void *key_newbuf (const void *, u_int);
406 #ifdef INET6
407 static int key_ismyaddr6 (struct sockaddr_in6 *);
408 #endif
409
410 /* flags for key_cmpsaidx() */
411 #define CMP_HEAD        1       /* protocol, addresses. */
412 #define CMP_MODE_REQID  2       /* additionally HEAD, reqid, mode. */
413 #define CMP_REQID       3       /* additionally HEAD, reaid. */
414 #define CMP_EXACTLY     4       /* all elements. */
415 static int key_cmpsaidx
416         (const struct secasindex *, const struct secasindex *, int);
417
418 static int key_cmpspidx_exactly
419         (struct secpolicyindex *, struct secpolicyindex *);
420 static int key_cmpspidx_withmask
421         (struct secpolicyindex *, struct secpolicyindex *);
422 static int key_sockaddrcmp (const struct sockaddr *, const struct sockaddr *, int);
423 static int key_bbcmp (const void *, const void *, u_int);
424 static void key_srandom (void);
425 static u_int16_t key_satype2proto (u_int8_t);
426 static u_int8_t key_proto2satype (u_int16_t);
427
428 static int key_getspi (struct socket *, struct mbuf *,
429         const struct sadb_msghdr *);
430 static u_int32_t key_do_getnewspi (struct sadb_spirange *,
431                                         struct secasindex *);
432 static int key_update (struct socket *, struct mbuf *,
433         const struct sadb_msghdr *);
434 #ifdef IPSEC_DOSEQCHECK
435 static struct secasvar *key_getsavbyseq (struct secashead *, u_int32_t);
436 #endif
437 static int key_add (struct socket *, struct mbuf *,
438         const struct sadb_msghdr *);
439 static int key_setident (struct secashead *, struct mbuf *,
440         const struct sadb_msghdr *);
441 static struct mbuf *key_getmsgbuf_x1 (struct mbuf *,
442         const struct sadb_msghdr *);
443 static int key_delete (struct socket *, struct mbuf *,
444         const struct sadb_msghdr *);
445 static int key_get (struct socket *, struct mbuf *,
446         const struct sadb_msghdr *);
447
448 static void key_getcomb_setlifetime (struct sadb_comb *);
449 static struct mbuf *key_getcomb_esp (void);
450 static struct mbuf *key_getcomb_ah (void);
451 static struct mbuf *key_getcomb_ipcomp (void);
452 static struct mbuf *key_getprop (const struct secasindex *);
453
454 static int key_acquire (const struct secasindex *, struct secpolicy *);
455 #ifndef IPSEC_NONBLOCK_ACQUIRE
456 static struct secacq *key_newacq (const struct secasindex *);
457 static struct secacq *key_getacq (const struct secasindex *);
458 static struct secacq *key_getacqbyseq (u_int32_t);
459 #endif
460 static struct secspacq *key_newspacq (struct secpolicyindex *);
461 static struct secspacq *key_getspacq (struct secpolicyindex *);
462 static int key_acquire2 (struct socket *, struct mbuf *,
463         const struct sadb_msghdr *);
464 static int key_register (struct socket *, struct mbuf *,
465         const struct sadb_msghdr *);
466 static int key_expire (struct secasvar *);
467 static int key_flush (struct socket *, struct mbuf *,
468         const struct sadb_msghdr *);
469 static int key_dump (struct socket *, struct mbuf *,
470         const struct sadb_msghdr *);
471 static int key_promisc (struct socket *, struct mbuf *,
472         const struct sadb_msghdr *);
473 static int key_senderror (struct socket *, struct mbuf *, int);
474 static int key_validate_ext (const struct sadb_ext *, int);
475 static int key_align (struct mbuf *, struct sadb_msghdr *);
476 #if 0
477 static const char *key_getfqdn (void);
478 static const char *key_getuserfqdn (void);
479 #endif
480 static void key_sa_chgstate (struct secasvar *, u_int8_t);
481 static struct mbuf *key_alloc_mbuf (int);
482
483 #define SA_ADDREF(p) do {                                               \
484         (p)->refcnt++;                                                  \
485         KASSERT((p)->refcnt != 0,                                       \
486                 ("SA refcnt overflow at %s:%u", __FILE__, __LINE__));   \
487 } while (0)
488 #define SA_DELREF(p) do {                                               \
489         KASSERT((p)->refcnt > 0,                                        \
490                 ("SA refcnt underflow at %s:%u", __FILE__, __LINE__));  \
491         (p)->refcnt--;                                                  \
492 } while (0)
493
494 #define SP_ADDREF(p) do {                                               \
495         (p)->refcnt++;                                                  \
496         KASSERT((p)->refcnt != 0,                                       \
497                 ("SP refcnt overflow at %s:%u", __FILE__, __LINE__));   \
498 } while (0)
499 #define SP_DELREF(p) do {                                               \
500         KASSERT((p)->refcnt > 0,                                        \
501                 ("SP refcnt underflow at %s:%u", __FILE__, __LINE__));  \
502         (p)->refcnt--;                                                  \
503 } while (0)
504
505 /*
506  * Return 0 when there are known to be no SP's for the specified
507  * direction.  Otherwise return 1.  This is used by IPsec code
508  * to optimize performance.
509  */
510 int
511 key_havesp(u_int dir)
512 {
513         return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
514                 LIST_FIRST(&sptree[dir]) != NULL : 1);
515 }
516
517 /* %%% IPsec policy management */
518 /*
519  * allocating a SP for OUTBOUND or INBOUND packet.
520  * Must call key_freesp() later.
521  * OUT: NULL:   not found
522  *      others: found and return the pointer.
523  */
524 struct secpolicy *
525 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
526 {
527         struct secpolicy *sp;
528         
529
530         KASSERT(spidx != NULL, ("key_allocsp: null spidx"));
531         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
532                 ("key_allocsp: invalid direction %u", dir));
533
534         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
535                 kprintf("DP key_allocsp from %s:%u\n", where, tag));
536
537         /* get a SP entry */
538         crit_enter();
539         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
540                  kprintf("*** objects\n"); kdebug_secpolicyindex(spidx));
541
542         LIST_FOREACH(sp, &sptree[dir], chain) {
543                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
544                          kprintf("*** in SPD\n");
545                          kdebug_secpolicyindex(&sp->spidx));
546
547                 if (sp->state == IPSEC_SPSTATE_DEAD)
548                         continue;
549                 if (key_cmpspidx_withmask(&sp->spidx, spidx))
550                         goto found;
551         }
552         sp = NULL;
553 found:
554         if (sp) {
555                 /* sanity check */
556                 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
557
558                 /* found a SPD entry */
559                 sp->lastused = time_second;
560                 SP_ADDREF(sp);
561         }
562         crit_exit();
563
564         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
565                 kprintf("DP key_allocsp return SP:%p (ID=%u) refcnt %u\n",
566                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
567         return sp;
568 }
569
570 /*
571  * allocating a SP for OUTBOUND or INBOUND packet.
572  * Must call key_freesp() later.
573  * OUT: NULL:   not found
574  *      others: found and return the pointer.
575  */
576 struct secpolicy *
577 key_allocsp2(u_int32_t spi,
578              union sockaddr_union *dst,
579              u_int8_t proto,
580              u_int dir,
581              const char* where, int tag)
582 {
583         struct secpolicy *sp;
584         
585
586         KASSERT(dst != NULL, ("key_allocsp2: null dst"));
587         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
588                 ("key_allocsp2: invalid direction %u", dir));
589
590         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
591                 kprintf("DP key_allocsp2 from %s:%u\n", where, tag));
592
593         /* get a SP entry */
594         crit_enter();
595         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
596                 kprintf("*** objects\n");
597                 kprintf("spi %u proto %u dir %u\n", spi, proto, dir);
598                 kdebug_sockaddr(&dst->sa));
599
600         LIST_FOREACH(sp, &sptree[dir], chain) {
601                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
602                         kprintf("*** in SPD\n");
603                         kdebug_secpolicyindex(&sp->spidx));
604
605                 if (sp->state == IPSEC_SPSTATE_DEAD)
606                         continue;
607                 /* compare simple values, then dst address */
608                 if (sp->spidx.ul_proto != proto)
609                         continue;
610                 /* NB: spi's must exist and match */
611                 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
612                         continue;
613                 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
614                         goto found;
615         }
616         sp = NULL;
617 found:
618         if (sp) {
619                 /* sanity check */
620                 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp2");
621
622                 /* found a SPD entry */
623                 sp->lastused = time_second;
624                 SP_ADDREF(sp);
625         }
626         crit_exit();
627
628         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
629                 kprintf("DP key_allocsp2 return SP:%p (ID=%u) refcnt %u\n",
630                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
631         return sp;
632 }
633
634 /*
635  * return a policy that matches this particular inbound packet.
636  * XXX slow
637  */
638 struct secpolicy *
639 key_gettunnel(const struct sockaddr *osrc,
640               const struct sockaddr *odst,
641               const struct sockaddr *isrc,
642               const struct sockaddr *idst,
643               const char* where, int tag)
644 {
645         struct secpolicy *sp;
646         const int dir = IPSEC_DIR_INBOUND;
647         
648         struct ipsecrequest *r1, *r2, *p;
649         struct secpolicyindex spidx;
650
651         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
652                 kprintf("DP key_gettunnel from %s:%u\n", where, tag));
653
654         if (isrc->sa_family != idst->sa_family) {
655                 ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
656                         isrc->sa_family, idst->sa_family));
657                 sp = NULL;
658                 goto done;
659         }
660
661         crit_enter();
662         LIST_FOREACH(sp, &sptree[dir], chain) {
663                 if (sp->state == IPSEC_SPSTATE_DEAD)
664                         continue;
665
666                 r1 = r2 = NULL;
667                 for (p = sp->req; p; p = p->next) {
668                         if (p->saidx.mode != IPSEC_MODE_TUNNEL)
669                                 continue;
670
671                         r1 = r2;
672                         r2 = p;
673
674                         if (!r1) {
675                                 /* here we look at address matches only */
676                                 spidx = sp->spidx;
677                                 if (isrc->sa_len > sizeof(spidx.src) ||
678                                     idst->sa_len > sizeof(spidx.dst))
679                                         continue;
680                                 bcopy(isrc, &spidx.src, isrc->sa_len);
681                                 bcopy(idst, &spidx.dst, idst->sa_len);
682                                 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
683                                         continue;
684                         } else {
685                                 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
686                                     key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
687                                         continue;
688                         }
689
690                         if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
691                             key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
692                                 continue;
693
694                         goto found;
695                 }
696         }
697         sp = NULL;
698 found:
699         if (sp) {
700                 sp->lastused = time_second;
701                 SP_ADDREF(sp);
702         }
703         crit_exit();
704 done:
705         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
706                 kprintf("DP key_gettunnel return SP:%p (ID=%u) refcnt %u\n",
707                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
708         return sp;
709 }
710
711 /*
712  * allocating an SA entry for an *OUTBOUND* packet.
713  * checking each request entries in SP, and acquire an SA if need.
714  * OUT: 0: there are valid requests.
715  *      ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
716  */
717 int
718 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
719 {
720         u_int level;
721         int error;
722
723         KASSERT(isr != NULL, ("key_checkrequest: null isr"));
724         KASSERT(saidx != NULL, ("key_checkrequest: null saidx"));
725         KASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
726                 saidx->mode == IPSEC_MODE_TUNNEL,
727                 ("key_checkrequest: unexpected policy %u", saidx->mode));
728
729         /* get current level */
730         level = ipsec_get_reqlevel(isr);
731
732         /*
733          * XXX guard against protocol callbacks from the crypto
734          * thread as they reference ipsecrequest.sav which we
735          * temporarily null out below.  Need to rethink how we
736          * handle bundled SA's in the callback thread.
737          */
738 #if 0
739         /*
740          * We do allocate new SA only if the state of SA in the holder is
741          * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
742          */
743         if (isr->sav != NULL) {
744                 if (isr->sav->sah == NULL)
745                         panic("key_checkrequest: sah is null.");
746                 if (isr->sav == (struct secasvar *)LIST_FIRST(
747                             &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
748                         KEY_FREESAV(&isr->sav);
749                         isr->sav = NULL;
750                 }
751         }
752 #else
753         /*
754          * we free any SA stashed in the IPsec request because a different
755          * SA may be involved each time this request is checked, either
756          * because new SAs are being configured, or this request is
757          * associated with an unconnected datagram socket, or this request
758          * is associated with a system default policy.
759          *
760          * The operation may have negative impact to performance.  We may
761          * want to check cached SA carefully, rather than picking new SA
762          * every time.
763          */
764         if (isr->sav != NULL) {
765                 KEY_FREESAV(&isr->sav);
766                 isr->sav = NULL;
767         }
768 #endif
769
770         /*
771          * new SA allocation if no SA found.
772          * key_allocsa_policy should allocate the oldest SA available.
773          * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
774          */
775         if (isr->sav == NULL)
776                 isr->sav = key_allocsa_policy(saidx);
777
778         /* When there is SA. */
779         if (isr->sav != NULL) {
780                 if (isr->sav->state != SADB_SASTATE_MATURE &&
781                     isr->sav->state != SADB_SASTATE_DYING)
782                         return EINVAL;
783                 return 0;
784         }
785
786         /* there is no SA */
787         error = key_acquire(saidx, isr->sp);
788         if (error != 0) {
789                 /* XXX What should I do ? */
790                 ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
791                         "from key_acquire.\n", error));
792                 return error;
793         }
794
795         if (level != IPSEC_LEVEL_REQUIRE) {
796                 /* XXX sigh, the interface to this routine is botched */
797                 KASSERT(isr->sav == NULL, ("key_checkrequest: unexpected SA"));
798                 return 0;
799         } else {
800                 return ENOENT;
801         }
802 }
803
804 /*
805  * allocating a SA for policy entry from SAD.
806  * NOTE: searching SAD of aliving state.
807  * OUT: NULL:   not found.
808  *      others: found and return the pointer.
809  */
810 static struct secasvar *
811 key_allocsa_policy(const struct secasindex *saidx)
812 {
813         struct secashead *sah;
814         struct secasvar *sav;
815         u_int stateidx, state;
816
817         LIST_FOREACH(sah, &sahtree, chain) {
818                 if (sah->state == SADB_SASTATE_DEAD)
819                         continue;
820                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
821                         goto found;
822         }
823
824         return NULL;
825
826     found:
827
828         /* search valid state */
829         for (stateidx = 0;
830              stateidx < NELEM(saorder_state_valid);
831              stateidx++) {
832
833                 state = saorder_state_valid[stateidx];
834
835                 sav = key_do_allocsa_policy(sah, state);
836                 if (sav != NULL)
837                         return sav;
838         }
839
840         return NULL;
841 }
842
843 /*
844  * searching SAD with direction, protocol, mode and state.
845  * called by key_allocsa_policy().
846  * OUT:
847  *      NULL    : not found
848  *      others  : found, pointer to a SA.
849  */
850 static struct secasvar *
851 key_do_allocsa_policy(struct secashead *sah, u_int state)
852 {
853         struct secasvar *sav, *nextsav, *candidate = NULL, *d;
854
855         LIST_FOREACH_MUTABLE(sav, &sah->savtree[state], chain, nextsav) {
856                 /* sanity check */
857                 KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
858
859                 /* initialize */
860                 if (candidate == NULL) {
861                         candidate = sav;
862                         continue;
863                 }
864
865                 /* Which SA is the better ? */
866
867                 /* sanity check 2 */
868                 if (candidate->lft_c == NULL || sav->lft_c == NULL)
869                         panic("key_do_allocsa_policy: "
870                                 "lifetime_current is NULL.\n");
871
872                 /* What the best method is to compare ? */
873                 if (key_prefered_oldsa) {
874                         if (candidate->lft_c->sadb_lifetime_addtime >
875                                         sav->lft_c->sadb_lifetime_addtime) {
876                                 candidate = sav;
877                         }
878                         continue;
879                 }
880
881                 /* prefered new sa rather than old sa */
882                 if (candidate->lft_c->sadb_lifetime_addtime <
883                                 sav->lft_c->sadb_lifetime_addtime) {
884                         d = candidate;
885                         candidate = sav;
886                 } else
887                         d = sav;
888
889                 /*
890                  * prepared to delete the SA when there is more
891                  * suitable candidate and the lifetime of the SA is not
892                  * permanent.
893                  */
894                 if (d->lft_c->sadb_lifetime_addtime != 0) {
895                         struct mbuf *m, *result;
896                         u_int8_t satype;
897
898                         key_sa_chgstate(d, SADB_SASTATE_DEAD);
899
900                         KASSERT(d->refcnt > 0,
901                                 ("key_do_allocsa_policy: bogus ref count"));
902
903                         satype = key_proto2satype(d->sah->saidx.proto);
904                         if (satype == 0)
905                                 goto msgfail;
906
907                         m = key_setsadbmsg(SADB_DELETE, 0, satype, 0, 0,
908                                            d->refcnt - 1);
909                         if (!m)
910                                 goto msgfail;
911                         result = m;
912
913                         /* set sadb_address for saidx's. */
914                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
915                                 &d->sah->saidx.src.sa,
916                                 d->sah->saidx.src.sa.sa_len << 3,
917                                 IPSEC_ULPROTO_ANY);
918                         if (!m)
919                                 goto msgfail;
920                         m_cat(result, m);
921
922                         /* set sadb_address for saidx's. */
923                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
924                                 &d->sah->saidx.dst.sa,
925                                 d->sah->saidx.dst.sa.sa_len << 3,
926                                 IPSEC_ULPROTO_ANY);
927                         if (!m)
928                                 goto msgfail;
929                         m_cat(result, m);
930
931                         /* create SA extension */
932                         m = key_setsadbsa(d);
933                         if (!m)
934                                 goto msgfail;
935                         m_cat(result, m);
936
937                         if (result->m_len < sizeof(struct sadb_msg)) {
938                                 result = m_pullup(result,
939                                                 sizeof(struct sadb_msg));
940                                 if (result == NULL)
941                                         goto msgfail;
942                         }
943
944                         result->m_pkthdr.len = m_lengthm(result, NULL);
945                         mtod(result, struct sadb_msg *)->sadb_msg_len =
946                                 PFKEY_UNIT64(result->m_pkthdr.len);
947
948                         if (key_sendup_mbuf(NULL, result,
949                                         KEY_SENDUP_REGISTERED))
950                                 goto msgfail;
951                  msgfail:
952                         KEY_FREESAV(&d);
953                 }
954         }
955
956         if (candidate) {
957                 SA_ADDREF(candidate);
958                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
959                          kprintf("DP allocsa_policy cause refcnt++:%d SA:%p\n",
960                                 candidate->refcnt, candidate));
961         }
962         return candidate;
963 }
964
965 /*
966  * allocating a usable SA entry for a *INBOUND* packet.
967  * Must call key_freesav() later.
968  * OUT: positive:       pointer to a usable sav (i.e. MATURE or DYING state).
969  *      NULL:           not found, or error occured.
970  *
971  * In the comparison, no source address is used--for RFC2401 conformance.
972  * To quote, from section 4.1:
973  *      A security association is uniquely identified by a triple consisting
974  *      of a Security Parameter Index (SPI), an IP Destination Address, and a
975  *      security protocol (AH or ESP) identifier.
976  * Note that, however, we do need to keep source address in IPsec SA.
977  * IKE specification and PF_KEY specification do assume that we
978  * keep source address in IPsec SA.  We see a tricky situation here.
979  */
980 struct secasvar *
981 key_allocsa(
982         union sockaddr_union *dst,
983         u_int proto,
984         u_int32_t spi,
985         const char* where, int tag)
986 {
987         struct secashead *sah;
988         struct secasvar *sav;
989         u_int stateidx, state;
990         
991
992         KASSERT(dst != NULL, ("key_allocsa: null dst address"));
993
994         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
995                 kprintf("DP key_allocsa from %s:%u\n", where, tag));
996
997         /*
998          * searching SAD.
999          * XXX: to be checked internal IP header somewhere.  Also when
1000          * IPsec tunnel packet is received.  But ESP tunnel mode is
1001          * encrypted so we can't check internal IP header.
1002          */
1003         crit_enter();
1004         LIST_FOREACH(sah, &sahtree, chain) {
1005                 /* search valid state */
1006                 for (stateidx = 0;
1007                      stateidx < NELEM(saorder_state_valid);
1008                      stateidx++) {
1009                         state = saorder_state_valid[stateidx];
1010                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
1011                                 /* sanity check */
1012                                 KEY_CHKSASTATE(sav->state, state, "key_allocsav");
1013                                 /* do not return entries w/ unusable state */
1014                                 if (sav->state != SADB_SASTATE_MATURE &&
1015                                     sav->state != SADB_SASTATE_DYING)
1016                                         continue;
1017                                 if (proto != sav->sah->saidx.proto)
1018                                         continue;
1019                                 if (spi != sav->spi)
1020                                         continue;
1021 #if 0   /* don't check src */
1022                                 /* check src address */
1023                                 if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1024                                         continue;
1025 #endif
1026                                 /* check dst address */
1027                                 if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1028                                         continue;
1029                                 SA_ADDREF(sav);
1030                                 goto done;
1031                         }
1032                 }
1033         }
1034         sav = NULL;
1035 done:
1036         crit_exit();
1037
1038         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1039                 kprintf("DP key_allocsa return SA:%p; refcnt %u\n",
1040                         sav, sav ? sav->refcnt : 0));
1041         return sav;
1042 }
1043
1044 /*
1045  * Must be called after calling key_allocsp().
1046  * For both the packet without socket and key_freeso().
1047  */
1048 void
1049 _key_freesp(struct secpolicy **spp, const char* where, int tag)
1050 {
1051         struct secpolicy *sp = *spp;
1052
1053         KASSERT(sp != NULL, ("key_freesp: null sp"));
1054
1055         SP_DELREF(sp);
1056
1057         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1058                 kprintf("DP key_freesp SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1059                         sp, sp->id, where, tag, sp->refcnt));
1060
1061         if (sp->refcnt == 0) {
1062                 *spp = NULL;
1063                 key_delsp(sp);
1064         }
1065 }
1066
1067 /*
1068  * Must be called after calling key_allocsp().
1069  * For the packet with socket.
1070  */
1071 void
1072 key_freeso(struct socket *so)
1073 {
1074         /* sanity check */
1075         KASSERT(so != NULL, ("key_freeso: null so"));
1076
1077         switch (so->so_proto->pr_domain->dom_family) {
1078 #ifdef INET
1079         case PF_INET:
1080             {
1081                 struct inpcb *pcb = so->so_pcb;
1082
1083                 /* Does it have a PCB ? */
1084                 if (pcb == NULL)
1085                         return;
1086                 key_freesp_so(&pcb->inp_sp->sp_in);
1087                 key_freesp_so(&pcb->inp_sp->sp_out);
1088             }
1089                 break;
1090 #endif
1091 #ifdef INET6
1092         case PF_INET6:
1093             {
1094 #ifdef HAVE_NRL_INPCB
1095                 struct inpcb *pcb  = so->so_pcb;
1096
1097                 /* Does it have a PCB ? */
1098                 if (pcb == NULL)
1099                         return;
1100                 key_freesp_so(&pcb->inp_sp->sp_in);
1101                 key_freesp_so(&pcb->inp_sp->sp_out);
1102 #else
1103                 struct in6pcb *pcb  = so->so_pcb;
1104
1105                 /* Does it have a PCB ? */
1106                 if (pcb == NULL)
1107                         return;
1108                 key_freesp_so(&pcb->in6p_sp->sp_in);
1109                 key_freesp_so(&pcb->in6p_sp->sp_out);
1110 #endif
1111             }
1112                 break;
1113 #endif /* INET6 */
1114         default:
1115                 ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
1116                     so->so_proto->pr_domain->dom_family));
1117                 return;
1118         }
1119 }
1120
1121 static void
1122 key_freesp_so(struct secpolicy **sp)
1123 {
1124         KASSERT(sp != NULL && *sp != NULL, ("key_freesp_so: null sp"));
1125
1126         if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1127             (*sp)->policy == IPSEC_POLICY_BYPASS)
1128                 return;
1129
1130         KASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1131                 ("key_freesp_so: invalid policy %u", (*sp)->policy));
1132         KEY_FREESP(sp);
1133 }
1134
1135 /*
1136  * Must be called after calling key_allocsa().
1137  * This function is called by key_freesp() to free some SA allocated
1138  * for a policy.
1139  */
1140 void
1141 key_freesav(struct secasvar **psav, const char* where, int tag)
1142 {
1143         struct secasvar *sav = *psav;
1144
1145         KASSERT(sav != NULL, ("key_freesav: null sav"));
1146
1147         SA_DELREF(sav);
1148
1149         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1150                 kprintf("DP key_freesav SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1151                         sav, ntohl(sav->spi), where, tag, sav->refcnt));
1152
1153         if (sav->refcnt == 0) {
1154                 *psav = NULL;
1155                 key_delsav(sav);
1156         }
1157 }
1158
1159 /* %%% SPD management */
1160 /*
1161  * free security policy entry.
1162  */
1163 static void
1164 key_delsp(struct secpolicy *sp)
1165 {
1166         
1167
1168         KASSERT(sp != NULL, ("key_delsp: null sp"));
1169
1170         sp->state = IPSEC_SPSTATE_DEAD;
1171
1172         KASSERT(sp->refcnt == 0,
1173                 ("key_delsp: SP with references deleted (refcnt %u)",
1174                 sp->refcnt));
1175
1176         crit_enter();
1177         /* remove from SP index */
1178         if (__LIST_CHAINED(sp))
1179                 LIST_REMOVE(sp, chain);
1180
1181     {
1182         struct ipsecrequest *isr = sp->req, *nextisr;
1183
1184         while (isr != NULL) {
1185                 if (isr->sav != NULL) {
1186                         KEY_FREESAV(&isr->sav);
1187                         isr->sav = NULL;
1188                 }
1189
1190                 nextisr = isr->next;
1191                 KFREE(isr);
1192                 isr = nextisr;
1193         }
1194     }
1195
1196         KFREE(sp);
1197
1198         crit_exit();
1199 }
1200
1201 /*
1202  * search SPD
1203  * OUT: NULL    : not found
1204  *      others  : found, pointer to a SP.
1205  */
1206 static struct secpolicy *
1207 key_getsp(struct secpolicyindex *spidx)
1208 {
1209         struct secpolicy *sp;
1210
1211         KASSERT(spidx != NULL, ("key_getsp: null spidx"));
1212
1213         LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
1214                 if (sp->state == IPSEC_SPSTATE_DEAD)
1215                         continue;
1216                 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1217                         SP_ADDREF(sp);
1218                         return sp;
1219                 }
1220         }
1221
1222         return NULL;
1223 }
1224
1225 /*
1226  * get SP by index.
1227  * OUT: NULL    : not found
1228  *      others  : found, pointer to a SP.
1229  */
1230 static struct secpolicy *
1231 key_getspbyid(u_int32_t id)
1232 {
1233         struct secpolicy *sp;
1234
1235         LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
1236                 if (sp->state == IPSEC_SPSTATE_DEAD)
1237                         continue;
1238                 if (sp->id == id) {
1239                         SP_ADDREF(sp);
1240                         return sp;
1241                 }
1242         }
1243
1244         LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
1245                 if (sp->state == IPSEC_SPSTATE_DEAD)
1246                         continue;
1247                 if (sp->id == id) {
1248                         SP_ADDREF(sp);
1249                         return sp;
1250                 }
1251         }
1252
1253         return NULL;
1254 }
1255
1256 struct secpolicy *
1257 key_newsp(const char* where, int tag)
1258 {
1259         struct secpolicy *newsp = NULL;
1260
1261         newsp = kmalloc(sizeof(struct secpolicy), M_SECA,
1262                         M_INTWAIT | M_ZERO | M_NULLOK);
1263         if (newsp) {
1264                 newsp->refcnt = 1;
1265                 newsp->req = NULL;
1266         }
1267
1268         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1269                 kprintf("DP key_newsp from %s:%u return SP:%p\n",
1270                         where, tag, newsp));
1271         return newsp;
1272 }
1273
1274 /*
1275  * create secpolicy structure from sadb_x_policy structure.
1276  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1277  * so must be set properly later.
1278  */
1279 struct secpolicy *
1280 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1281 {
1282         struct secpolicy *newsp;
1283
1284         /* sanity check */
1285         if (xpl0 == NULL)
1286                 panic("key_msg2sp: NULL pointer was passed.");
1287         if (len < sizeof(*xpl0))
1288                 panic("key_msg2sp: invalid length.");
1289         if (len != PFKEY_EXTLEN(xpl0)) {
1290                 ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
1291                 *error = EINVAL;
1292                 return NULL;
1293         }
1294
1295         if ((newsp = KEY_NEWSP()) == NULL) {
1296                 *error = ENOBUFS;
1297                 return NULL;
1298         }
1299
1300         newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1301         newsp->policy = xpl0->sadb_x_policy_type;
1302
1303         /* check policy */
1304         switch (xpl0->sadb_x_policy_type) {
1305         case IPSEC_POLICY_DISCARD:
1306         case IPSEC_POLICY_NONE:
1307         case IPSEC_POLICY_ENTRUST:
1308         case IPSEC_POLICY_BYPASS:
1309                 newsp->req = NULL;
1310                 break;
1311
1312         case IPSEC_POLICY_IPSEC:
1313             {
1314                 int tlen;
1315                 struct sadb_x_ipsecrequest *xisr;
1316                 struct ipsecrequest **p_isr = &newsp->req;
1317
1318                 /* validity check */
1319                 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1320                         ipseclog((LOG_DEBUG,
1321                             "key_msg2sp: Invalid msg length.\n"));
1322                         KEY_FREESP(&newsp);
1323                         *error = EINVAL;
1324                         return NULL;
1325                 }
1326
1327                 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1328                 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1329
1330                 while (tlen > 0) {
1331                         /* length check */
1332                         if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1333                                 ipseclog((LOG_DEBUG, "key_msg2sp: "
1334                                         "invalid ipsecrequest length.\n"));
1335                                 KEY_FREESP(&newsp);
1336                                 *error = EINVAL;
1337                                 return NULL;
1338                         }
1339
1340                         /* allocate request buffer */
1341                         KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
1342                         if ((*p_isr) == NULL) {
1343                                 ipseclog((LOG_DEBUG,
1344                                     "key_msg2sp: No more memory.\n"));
1345                                 KEY_FREESP(&newsp);
1346                                 *error = ENOBUFS;
1347                                 return NULL;
1348                         }
1349                         bzero(*p_isr, sizeof(**p_isr));
1350
1351                         /* set values */
1352                         (*p_isr)->next = NULL;
1353
1354                         switch (xisr->sadb_x_ipsecrequest_proto) {
1355                         case IPPROTO_ESP:
1356                         case IPPROTO_AH:
1357                         case IPPROTO_IPCOMP:
1358                                 break;
1359                         default:
1360                                 ipseclog((LOG_DEBUG,
1361                                     "key_msg2sp: invalid proto type=%u\n",
1362                                     xisr->sadb_x_ipsecrequest_proto));
1363                                 KEY_FREESP(&newsp);
1364                                 *error = EPROTONOSUPPORT;
1365                                 return NULL;
1366                         }
1367                         (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1368
1369                         switch (xisr->sadb_x_ipsecrequest_mode) {
1370                         case IPSEC_MODE_TRANSPORT:
1371                         case IPSEC_MODE_TUNNEL:
1372                                 break;
1373                         case IPSEC_MODE_ANY:
1374                         default:
1375                                 ipseclog((LOG_DEBUG,
1376                                     "key_msg2sp: invalid mode=%u\n",
1377                                     xisr->sadb_x_ipsecrequest_mode));
1378                                 KEY_FREESP(&newsp);
1379                                 *error = EINVAL;
1380                                 return NULL;
1381                         }
1382                         (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1383
1384                         switch (xisr->sadb_x_ipsecrequest_level) {
1385                         case IPSEC_LEVEL_DEFAULT:
1386                         case IPSEC_LEVEL_USE:
1387                         case IPSEC_LEVEL_REQUIRE:
1388                                 break;
1389                         case IPSEC_LEVEL_UNIQUE:
1390                                 /* validity check */
1391                                 /*
1392                                  * If range violation of reqid, kernel will
1393                                  * update it, don't refuse it.
1394                                  */
1395                                 if (xisr->sadb_x_ipsecrequest_reqid
1396                                                 > IPSEC_MANUAL_REQID_MAX) {
1397                                         ipseclog((LOG_DEBUG,
1398                                             "key_msg2sp: reqid=%d range "
1399                                             "violation, updated by kernel.\n",
1400                                             xisr->sadb_x_ipsecrequest_reqid));
1401                                         xisr->sadb_x_ipsecrequest_reqid = 0;
1402                                 }
1403
1404                                 /* allocate new reqid id if reqid is zero. */
1405                                 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1406                                         u_int32_t reqid;
1407                                         if ((reqid = key_newreqid()) == 0) {
1408                                                 KEY_FREESP(&newsp);
1409                                                 *error = ENOBUFS;
1410                                                 return NULL;
1411                                         }
1412                                         (*p_isr)->saidx.reqid = reqid;
1413                                         xisr->sadb_x_ipsecrequest_reqid = reqid;
1414                                 } else {
1415                                 /* set it for manual keying. */
1416                                         (*p_isr)->saidx.reqid =
1417                                                 xisr->sadb_x_ipsecrequest_reqid;
1418                                 }
1419                                 break;
1420
1421                         default:
1422                                 ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
1423                                         xisr->sadb_x_ipsecrequest_level));
1424                                 KEY_FREESP(&newsp);
1425                                 *error = EINVAL;
1426                                 return NULL;
1427                         }
1428                         (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1429
1430                         /* set IP addresses if there */
1431                         if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1432                                 struct sockaddr *paddr;
1433
1434                                 paddr = (struct sockaddr *)(xisr + 1);
1435
1436                                 /* validity check */
1437                                 if (paddr->sa_len
1438                                     > sizeof((*p_isr)->saidx.src)) {
1439                                         ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1440                                                 "address length.\n"));
1441                                         KEY_FREESP(&newsp);
1442                                         *error = EINVAL;
1443                                         return NULL;
1444                                 }
1445                                 bcopy(paddr, &(*p_isr)->saidx.src,
1446                                         paddr->sa_len);
1447
1448                                 paddr = (struct sockaddr *)((caddr_t)paddr
1449                                                         + paddr->sa_len);
1450
1451                                 /* validity check */
1452                                 if (paddr->sa_len
1453                                     > sizeof((*p_isr)->saidx.dst)) {
1454                                         ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1455                                                 "address length.\n"));
1456                                         KEY_FREESP(&newsp);
1457                                         *error = EINVAL;
1458                                         return NULL;
1459                                 }
1460                                 bcopy(paddr, &(*p_isr)->saidx.dst,
1461                                         paddr->sa_len);
1462                         }
1463
1464                         (*p_isr)->sav = NULL;
1465                         (*p_isr)->sp = newsp;
1466
1467                         /* initialization for the next. */
1468                         p_isr = &(*p_isr)->next;
1469                         tlen -= xisr->sadb_x_ipsecrequest_len;
1470
1471                         /* validity check */
1472                         if (tlen < 0) {
1473                                 ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
1474                                 KEY_FREESP(&newsp);
1475                                 *error = EINVAL;
1476                                 return NULL;
1477                         }
1478
1479                         xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1480                                          + xisr->sadb_x_ipsecrequest_len);
1481                 }
1482             }
1483                 break;
1484         default:
1485                 ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
1486                 KEY_FREESP(&newsp);
1487                 *error = EINVAL;
1488                 return NULL;
1489         }
1490
1491         *error = 0;
1492         return newsp;
1493 }
1494
1495 static u_int32_t
1496 key_newreqid(void)
1497 {
1498         static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1499
1500         auto_reqid = (auto_reqid == ~0
1501                         ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1502
1503         /* XXX should be unique check */
1504
1505         return auto_reqid;
1506 }
1507
1508 /*
1509  * copy secpolicy struct to sadb_x_policy structure indicated.
1510  */
1511 struct mbuf *
1512 key_sp2msg(struct secpolicy *sp)
1513 {
1514         struct sadb_x_policy *xpl;
1515         int tlen;
1516         caddr_t p;
1517         struct mbuf *m;
1518
1519         /* sanity check. */
1520         if (sp == NULL)
1521                 panic("key_sp2msg: NULL pointer was passed.");
1522
1523         tlen = key_getspreqmsglen(sp);
1524
1525         m = key_alloc_mbuf(tlen);
1526         if (!m || m->m_next) {  /*XXX*/
1527                 if (m)
1528                         m_freem(m);
1529                 return NULL;
1530         }
1531
1532         m->m_len = tlen;
1533         m->m_next = NULL;
1534         xpl = mtod(m, struct sadb_x_policy *);
1535         bzero(xpl, tlen);
1536
1537         xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1538         xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1539         xpl->sadb_x_policy_type = sp->policy;
1540         xpl->sadb_x_policy_dir = sp->spidx.dir;
1541         xpl->sadb_x_policy_id = sp->id;
1542         p = (caddr_t)xpl + sizeof(*xpl);
1543
1544         /* if is the policy for ipsec ? */
1545         if (sp->policy == IPSEC_POLICY_IPSEC) {
1546                 struct sadb_x_ipsecrequest *xisr;
1547                 struct ipsecrequest *isr;
1548
1549                 for (isr = sp->req; isr != NULL; isr = isr->next) {
1550
1551                         xisr = (struct sadb_x_ipsecrequest *)p;
1552
1553                         xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1554                         xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1555                         xisr->sadb_x_ipsecrequest_level = isr->level;
1556                         xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1557
1558                         p += sizeof(*xisr);
1559                         bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1560                         p += isr->saidx.src.sa.sa_len;
1561                         bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1562                         p += isr->saidx.src.sa.sa_len;
1563
1564                         xisr->sadb_x_ipsecrequest_len =
1565                                 PFKEY_ALIGN8(sizeof(*xisr)
1566                                         + isr->saidx.src.sa.sa_len
1567                                         + isr->saidx.dst.sa.sa_len);
1568                 }
1569         }
1570
1571         return m;
1572 }
1573
1574 /* m will not be freed nor modified */
1575 static struct mbuf *
1576 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1577         int ndeep, int nitem, ...)
1578 {
1579         __va_list ap;
1580         int idx;
1581         int i;
1582         struct mbuf *result = NULL, *n;
1583         int len;
1584
1585         if (m == NULL || mhp == NULL)
1586                 panic("null pointer passed to key_gather");
1587
1588         __va_start(ap, nitem);
1589         for (i = 0; i < nitem; i++) {
1590                 idx = __va_arg(ap, int);
1591                 if (idx < 0 || idx > SADB_EXT_MAX)
1592                         goto fail;
1593                 /* don't attempt to pull empty extension */
1594                 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1595                         continue;
1596                 if (idx != SADB_EXT_RESERVED  &&
1597                     (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1598                         continue;
1599
1600                 if (idx == SADB_EXT_RESERVED) {
1601                         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1602 #ifdef DIAGNOSTIC
1603                         if (len > MHLEN)
1604                                 panic("assumption failed");
1605 #endif
1606                         MGETHDR(n, MB_DONTWAIT, MT_DATA);
1607                         if (!n)
1608                                 goto fail;
1609                         n->m_len = len;
1610                         n->m_next = NULL;
1611                         m_copydata(m, 0, sizeof(struct sadb_msg),
1612                             mtod(n, caddr_t));
1613                 } else if (i < ndeep) {
1614                         len = mhp->extlen[idx];
1615                         n = key_alloc_mbuf(len);
1616                         if (!n || n->m_next) {  /*XXX*/
1617                                 if (n)
1618                                         m_freem(n);
1619                                 goto fail;
1620                         }
1621                         m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1622                             mtod(n, caddr_t));
1623                 } else {
1624                         n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1625                             MB_DONTWAIT);
1626                 }
1627                 if (n == NULL)
1628                         goto fail;
1629
1630                 if (result)
1631                         m_cat(result, n);
1632                 else
1633                         result = n;
1634         }
1635         __va_end(ap);
1636
1637         if (result->m_flags & M_PKTHDR)
1638                 result->m_pkthdr.len = m_lengthm(result, NULL);
1639
1640         return result;
1641
1642 fail:
1643         m_freem(result);
1644         return NULL;
1645 }
1646
1647 /*
1648  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1649  * add an entry to SP database, when received
1650  *   <base, address(SD), (lifetime(H),) policy>
1651  * from the user(?).
1652  * Adding to SP database,
1653  * and send
1654  *   <base, address(SD), (lifetime(H),) policy>
1655  * to the socket which was send.
1656  *
1657  * SPDADD set a unique policy entry.
1658  * SPDSETIDX like SPDADD without a part of policy requests.
1659  * SPDUPDATE replace a unique policy entry.
1660  *
1661  * m will always be freed.
1662  */
1663 static int
1664 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1665 {
1666         struct sadb_address *src0, *dst0;
1667         struct sadb_x_policy *xpl0, *xpl;
1668         struct sadb_lifetime *lft = NULL;
1669         struct secpolicyindex spidx;
1670         struct secpolicy *newsp;
1671         struct sockaddr *saddr, *daddr;
1672         int error;
1673
1674         /* sanity check */
1675         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
1676                 panic("key_spdadd: NULL pointer is passed.");
1677
1678         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1679             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1680             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1681                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1682                 return key_senderror(so, m, EINVAL);
1683         }
1684         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1685             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1686             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1687                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1688                 return key_senderror(so, m, EINVAL);
1689         }
1690         if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1691                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1692                         < sizeof(struct sadb_lifetime)) {
1693                         ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1694                         return key_senderror(so, m, EINVAL);
1695                 }
1696                 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1697         }
1698
1699         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1700         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1701         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1702
1703         /* make secindex */
1704         /* XXX boundary check against sa_len */
1705         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1706                         src0 + 1,
1707                         dst0 + 1,
1708                         src0->sadb_address_prefixlen,
1709                         dst0->sadb_address_prefixlen,
1710                         src0->sadb_address_proto,
1711                         &spidx);
1712
1713         /* checking the direciton. */
1714         switch (xpl0->sadb_x_policy_dir) {
1715         case IPSEC_DIR_INBOUND:
1716         case IPSEC_DIR_OUTBOUND:
1717                 break;
1718         default:
1719                 ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
1720                 mhp->msg->sadb_msg_errno = EINVAL;
1721                 return 0;
1722         }
1723
1724         /* check policy */
1725         /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1726         if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1727          || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1728                 ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
1729                 return key_senderror(so, m, EINVAL);
1730         }
1731
1732         /* policy requests are mandatory when action is ipsec. */
1733         if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1734          && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1735          && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1736                 ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
1737                 return key_senderror(so, m, EINVAL);
1738         }
1739
1740         /*
1741          * checking there is SP already or not.
1742          * SPDUPDATE doesn't depend on whether there is a SP or not.
1743          * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1744          * then error.
1745          */
1746         newsp = key_getsp(&spidx);
1747         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1748                 if (newsp) {
1749                         newsp->state = IPSEC_SPSTATE_DEAD;
1750                         KEY_FREESP(&newsp);
1751                 }
1752         } else {
1753                 if (newsp != NULL) {
1754                         KEY_FREESP(&newsp);
1755                         ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
1756                         return key_senderror(so, m, EEXIST);
1757                 }
1758         }
1759
1760         /* allocation new SP entry */
1761         if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1762                 return key_senderror(so, m, error);
1763         }
1764
1765         if ((newsp->id = key_getnewspid()) == 0) {
1766                 KFREE(newsp);
1767                 return key_senderror(so, m, ENOBUFS);
1768         }
1769
1770         /* XXX boundary check against sa_len */
1771         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1772                         src0 + 1,
1773                         dst0 + 1,
1774                         src0->sadb_address_prefixlen,
1775                         dst0->sadb_address_prefixlen,
1776                         src0->sadb_address_proto,
1777                         &newsp->spidx);
1778
1779         /* sanity check on addr pair */
1780         saddr = (struct sockaddr *)(src0 + 1);
1781         daddr = (struct sockaddr *)(dst0 + 1);
1782         if (saddr->sa_family != daddr->sa_family) {
1783                 KFREE(newsp);
1784                 return key_senderror(so, m, EINVAL);
1785         }
1786         if (saddr->sa_len != daddr->sa_len) {
1787                 KFREE(newsp);
1788                 return key_senderror(so, m, EINVAL);
1789         }
1790 #if 1
1791         if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1792                 if (saddr->sa_family != newsp->req->saidx.src.sa.sa_family) {
1793                         KFREE(newsp);
1794                         return key_senderror(so, m, EINVAL);
1795                 }
1796         }
1797         if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1798                 if (daddr->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1799                         KFREE(newsp);
1800                         return key_senderror(so, m, EINVAL);
1801                 }
1802         }
1803 #endif
1804
1805         newsp->created = time_second;
1806         newsp->lastused = newsp->created;
1807         newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1808         newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1809
1810         newsp->refcnt = 1;      /* do not reclaim until I say I do */
1811         newsp->state = IPSEC_SPSTATE_ALIVE;
1812         LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1813
1814         /* delete the entry in spacqtree */
1815         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1816                 struct secspacq *spacq;
1817                 if ((spacq = key_getspacq(&spidx)) != NULL) {
1818                         /* reset counter in order to deletion by timehandler. */
1819                         spacq->created = time_second;
1820                         spacq->count = 0;
1821                 }
1822         }
1823
1824     {
1825         struct mbuf *n, *mpolicy;
1826         struct sadb_msg *newmsg;
1827         int off;
1828
1829         /* create new sadb_msg to reply. */
1830         if (lft) {
1831                 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1832                     SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1833                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1834         } else {
1835                 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1836                     SADB_X_EXT_POLICY,
1837                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1838         }
1839         if (!n)
1840                 return key_senderror(so, m, ENOBUFS);
1841
1842         if (n->m_len < sizeof(*newmsg)) {
1843                 n = m_pullup(n, sizeof(*newmsg));
1844                 if (!n)
1845                         return key_senderror(so, m, ENOBUFS);
1846         }
1847         newmsg = mtod(n, struct sadb_msg *);
1848         newmsg->sadb_msg_errno = 0;
1849         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1850
1851         off = 0;
1852         mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1853             sizeof(*xpl), &off);
1854         if (mpolicy == NULL) {
1855                 /* n is already freed */
1856                 return key_senderror(so, m, ENOBUFS);
1857         }
1858         xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1859         if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1860                 m_freem(n);
1861                 return key_senderror(so, m, EINVAL);
1862         }
1863         xpl->sadb_x_policy_id = newsp->id;
1864
1865         m_freem(m);
1866         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1867     }
1868 }
1869
1870 /*
1871  * get new policy id.
1872  * OUT:
1873  *      0:      failure.
1874  *      others: success.
1875  */
1876 static u_int32_t
1877 key_getnewspid(void)
1878 {
1879         u_int32_t newid = 0;
1880         int count = key_spi_trycnt;     /* XXX */
1881         struct secpolicy *sp;
1882
1883         /* when requesting to allocate spi ranged */
1884         while (count--) {
1885                 newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
1886
1887                 if ((sp = key_getspbyid(newid)) == NULL)
1888                         break;
1889
1890                 KEY_FREESP(&sp);
1891         }
1892
1893         if (count == 0 || newid == 0) {
1894                 ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
1895                 return 0;
1896         }
1897
1898         return newid;
1899 }
1900
1901 /*
1902  * SADB_SPDDELETE processing
1903  * receive
1904  *   <base, address(SD), policy(*)>
1905  * from the user(?), and set SADB_SASTATE_DEAD,
1906  * and send,
1907  *   <base, address(SD), policy(*)>
1908  * to the ikmpd.
1909  * policy(*) including direction of policy.
1910  *
1911  * m will always be freed.
1912  */
1913 static int
1914 key_spddelete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1915 {
1916         struct sadb_address *src0, *dst0;
1917         struct sadb_x_policy *xpl0;
1918         struct secpolicyindex spidx;
1919         struct secpolicy *sp;
1920
1921         /* sanity check */
1922         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
1923                 panic("key_spddelete: NULL pointer is passed.");
1924
1925         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1926             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1927             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1928                 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
1929                 return key_senderror(so, m, EINVAL);
1930         }
1931         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1932             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1933             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1934                 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
1935                 return key_senderror(so, m, EINVAL);
1936         }
1937
1938         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1939         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1940         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1941
1942         /* make secindex */
1943         /* XXX boundary check against sa_len */
1944         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1945                         src0 + 1,
1946                         dst0 + 1,
1947                         src0->sadb_address_prefixlen,
1948                         dst0->sadb_address_prefixlen,
1949                         src0->sadb_address_proto,
1950                         &spidx);
1951
1952         /* checking the direciton. */
1953         switch (xpl0->sadb_x_policy_dir) {
1954         case IPSEC_DIR_INBOUND:
1955         case IPSEC_DIR_OUTBOUND:
1956                 break;
1957         default:
1958                 ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
1959                 return key_senderror(so, m, EINVAL);
1960         }
1961
1962         /* Is there SP in SPD ? */
1963         if ((sp = key_getsp(&spidx)) == NULL) {
1964                 ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
1965                 return key_senderror(so, m, EINVAL);
1966         }
1967
1968         /* save policy id to buffer to be returned. */
1969         xpl0->sadb_x_policy_id = sp->id;
1970
1971         sp->state = IPSEC_SPSTATE_DEAD;
1972         KEY_FREESP(&sp);
1973
1974     {
1975         struct mbuf *n;
1976         struct sadb_msg *newmsg;
1977
1978         /* create new sadb_msg to reply. */
1979         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
1980             SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1981         if (!n)
1982                 return key_senderror(so, m, ENOBUFS);
1983
1984         newmsg = mtod(n, struct sadb_msg *);
1985         newmsg->sadb_msg_errno = 0;
1986         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1987
1988         m_freem(m);
1989         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1990     }
1991 }
1992
1993 /*
1994  * SADB_SPDDELETE2 processing
1995  * receive
1996  *   <base, policy(*)>
1997  * from the user(?), and set SADB_SASTATE_DEAD,
1998  * and send,
1999  *   <base, policy(*)>
2000  * to the ikmpd.
2001  * policy(*) including direction of policy.
2002  *
2003  * m will always be freed.
2004  */
2005 static int
2006 key_spddelete2(struct socket *so, struct mbuf *m,
2007                const struct sadb_msghdr *mhp)
2008 {
2009         u_int32_t id;
2010         struct secpolicy *sp;
2011
2012         /* sanity check */
2013         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2014                 panic("key_spddelete2: NULL pointer is passed.");
2015
2016         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2017             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2018                 ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
2019                 key_senderror(so, m, EINVAL);
2020                 return 0;
2021         }
2022
2023         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2024
2025         /* Is there SP in SPD ? */
2026         if ((sp = key_getspbyid(id)) == NULL) {
2027                 ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
2028                 key_senderror(so, m, EINVAL);
2029         }
2030
2031         sp->state = IPSEC_SPSTATE_DEAD;
2032         KEY_FREESP(&sp);
2033
2034     {
2035         struct mbuf *n;
2036         struct sadb_msg *newmsg;
2037         int off, len;
2038
2039         /* create new sadb_msg to reply. */
2040         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2041
2042         if (len > MCLBYTES)
2043                 return key_senderror(so, m, ENOBUFS);
2044         n = m_getb(len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
2045         if (!n)
2046                 return key_senderror(so, m, ENOBUFS);
2047         n->m_len = len;
2048
2049         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t));
2050         off = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2051
2052 #ifdef DIAGNOSTIC
2053         if (off != len)
2054                 panic("length inconsistency in key_spddelete2");
2055 #endif
2056
2057         n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2058             mhp->extlen[SADB_X_EXT_POLICY], MB_DONTWAIT);
2059         if (!n->m_next) {
2060                 m_freem(n);
2061                 return key_senderror(so, m, ENOBUFS);
2062         }
2063         n->m_pkthdr.len = m_lengthm(n, NULL);
2064
2065         newmsg = mtod(n, struct sadb_msg *);
2066         newmsg->sadb_msg_errno = 0;
2067         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2068
2069         m_freem(m);
2070         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2071     }
2072 }
2073
2074 /*
2075  * SADB_X_GET processing
2076  * receive
2077  *   <base, policy(*)>
2078  * from the user(?),
2079  * and send,
2080  *   <base, address(SD), policy>
2081  * to the ikmpd.
2082  * policy(*) including direction of policy.
2083  *
2084  * m will always be freed.
2085  */
2086 static int
2087 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2088 {
2089         u_int32_t id;
2090         struct secpolicy *sp;
2091         struct mbuf *n;
2092
2093         /* sanity check */
2094         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2095                 panic("key_spdget: NULL pointer is passed.");
2096
2097         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2098             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2099                 ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
2100                 return key_senderror(so, m, EINVAL);
2101         }
2102
2103         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2104
2105         /* Is there SP in SPD ? */
2106         if ((sp = key_getspbyid(id)) == NULL) {
2107                 ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
2108                 return key_senderror(so, m, ENOENT);
2109         }
2110
2111         n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2112         if (n != NULL) {
2113                 m_freem(m);
2114                 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2115         } else
2116                 return key_senderror(so, m, ENOBUFS);
2117 }
2118
2119 /*
2120  * SADB_X_SPDACQUIRE processing.
2121  * Acquire policy and SA(s) for a *OUTBOUND* packet.
2122  * send
2123  *   <base, policy(*)>
2124  * to KMD, and expect to receive
2125  *   <base> with SADB_X_SPDACQUIRE if error occured,
2126  * or
2127  *   <base, policy>
2128  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2129  * policy(*) is without policy requests.
2130  *
2131  *    0     : succeed
2132  *    others: error number
2133  */
2134 int
2135 key_spdacquire(struct secpolicy *sp)
2136 {
2137         struct mbuf *result = NULL, *m;
2138         struct secspacq *newspacq;
2139         int error;
2140
2141         /* sanity check */
2142         if (sp == NULL)
2143                 panic("key_spdacquire: NULL pointer is passed.");
2144         if (sp->req != NULL)
2145                 panic("key_spdacquire: called but there is request.");
2146         if (sp->policy != IPSEC_POLICY_IPSEC)
2147                 panic("key_spdacquire: policy mismatched. IPsec is expected.");
2148
2149         /* Get an entry to check whether sent message or not. */
2150         if ((newspacq = key_getspacq(&sp->spidx)) != NULL) {
2151                 if (key_blockacq_count < newspacq->count) {
2152                         /* reset counter and do send message. */
2153                         newspacq->count = 0;
2154                 } else {
2155                         /* increment counter and do nothing. */
2156                         newspacq->count++;
2157                         return 0;
2158                 }
2159         } else {
2160                 /* make new entry for blocking to send SADB_ACQUIRE. */
2161                 if ((newspacq = key_newspacq(&sp->spidx)) == NULL)
2162                         return ENOBUFS;
2163
2164                 /* add to acqtree */
2165                 LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
2166         }
2167
2168         /* create new sadb_msg to reply. */
2169         m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2170         if (!m) {
2171                 error = ENOBUFS;
2172                 goto fail;
2173         }
2174         result = m;
2175         result->m_pkthdr.len = m_lengthm(result, NULL);
2176         mtod(result, struct sadb_msg *)->sadb_msg_len =
2177             PFKEY_UNIT64(result->m_pkthdr.len);
2178
2179         return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2180
2181 fail:
2182         if (result)
2183                 m_freem(result);
2184         return error;
2185 }
2186
2187 /*
2188  * SADB_SPDFLUSH processing
2189  * receive
2190  *   <base>
2191  * from the user, and free all entries in secpctree.
2192  * and send,
2193  *   <base>
2194  * to the user.
2195  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2196  *
2197  * m will always be freed.
2198  */
2199 static int
2200 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2201 {
2202         struct sadb_msg *newmsg;
2203         struct secpolicy *sp;
2204         u_int dir;
2205
2206         /* sanity check */
2207         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2208                 panic("key_spdflush: NULL pointer is passed.");
2209
2210         if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2211                 return key_senderror(so, m, EINVAL);
2212
2213         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2214                 LIST_FOREACH(sp, &sptree[dir], chain) {
2215                         sp->state = IPSEC_SPSTATE_DEAD;
2216                 }
2217         }
2218
2219         if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2220                 ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
2221                 return key_senderror(so, m, ENOBUFS);
2222         }
2223
2224         if (m->m_next)
2225                 m_freem(m->m_next);
2226         m->m_next = NULL;
2227         m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2228         newmsg = mtod(m, struct sadb_msg *);
2229         newmsg->sadb_msg_errno = 0;
2230         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2231
2232         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2233 }
2234
2235 /*
2236  * SADB_SPDDUMP processing
2237  * receive
2238  *   <base>
2239  * from the user, and dump all SP leaves
2240  * and send,
2241  *   <base> .....
2242  * to the ikmpd.
2243  *
2244  * m will always be freed.
2245  */
2246 static int
2247 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2248 {
2249         struct secpolicy *sp;
2250         int cnt;
2251         u_int dir;
2252         struct mbuf *n;
2253
2254         /* sanity check */
2255         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2256                 panic("key_spddump: NULL pointer is passed.");
2257
2258         /* search SPD entry and get buffer size. */
2259         cnt = 0;
2260         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2261                 LIST_FOREACH(sp, &sptree[dir], chain) {
2262                         cnt++;
2263                 }
2264         }
2265
2266         if (cnt == 0)
2267                 return key_senderror(so, m, ENOENT);
2268
2269         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2270                 LIST_FOREACH(sp, &sptree[dir], chain) {
2271                         --cnt;
2272                         n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2273                             mhp->msg->sadb_msg_pid);
2274
2275                         if (n)
2276                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2277                 }
2278         }
2279
2280         m_freem(m);
2281         return 0;
2282 }
2283
2284 static struct mbuf *
2285 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2286               u_int32_t pid)
2287 {
2288         struct mbuf *result = NULL, *m;
2289
2290         m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2291         if (!m)
2292                 goto fail;
2293         result = m;
2294
2295         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2296             &sp->spidx.src.sa, sp->spidx.prefs,
2297             sp->spidx.ul_proto);
2298         if (!m)
2299                 goto fail;
2300         m_cat(result, m);
2301
2302         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2303             &sp->spidx.dst.sa, sp->spidx.prefd,
2304             sp->spidx.ul_proto);
2305         if (!m)
2306                 goto fail;
2307         m_cat(result, m);
2308
2309         m = key_sp2msg(sp);
2310         if (!m)
2311                 goto fail;
2312         m_cat(result, m);
2313
2314         if ((result->m_flags & M_PKTHDR) == 0)
2315                 goto fail;
2316
2317         if (result->m_len < sizeof(struct sadb_msg)) {
2318                 result = m_pullup(result, sizeof(struct sadb_msg));
2319                 if (result == NULL)
2320                         goto fail;
2321         }
2322         result->m_pkthdr.len = m_lengthm(result, NULL);
2323         mtod(result, struct sadb_msg *)->sadb_msg_len =
2324             PFKEY_UNIT64(result->m_pkthdr.len);
2325
2326         return result;
2327
2328 fail:
2329         m_freem(result);
2330         return NULL;
2331 }
2332
2333 /*
2334  * get PFKEY message length for security policy and request.
2335  */
2336 static u_int
2337 key_getspreqmsglen(struct secpolicy *sp)
2338 {
2339         struct ipsecrequest *isr;
2340         u_int tlen, len;
2341
2342         tlen = sizeof(struct sadb_x_policy);
2343
2344         /* if is the policy for ipsec ? */
2345         if (sp->policy != IPSEC_POLICY_IPSEC)
2346                 return tlen;
2347
2348         /* get length of ipsec requests */
2349         for (isr = sp->req; isr != NULL; isr = isr->next) {
2350                 len = sizeof(struct sadb_x_ipsecrequest) +
2351                       isr->saidx.src.sa.sa_len + isr->saidx.dst.sa.sa_len;
2352
2353                 tlen += PFKEY_ALIGN8(len);
2354         }
2355
2356         return tlen;
2357 }
2358
2359 /*
2360  * SADB_SPDEXPIRE processing
2361  * send
2362  *   <base, address(SD), lifetime(CH), policy>
2363  * to KMD by PF_KEY.
2364  *
2365  * OUT: 0       : succeed
2366  *      others  : error number
2367  */
2368 static int
2369 key_spdexpire(struct secpolicy *sp)
2370 {
2371         
2372         struct mbuf *result = NULL, *m;
2373         int len;
2374         int error = -1;
2375         struct sadb_lifetime *lt;
2376
2377         /* XXX: Why do we lock ? */
2378         crit_enter();
2379
2380         /* sanity check */
2381         if (sp == NULL)
2382                 panic("key_spdexpire: NULL pointer is passed.");
2383
2384         /* set msg header */
2385         m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2386         if (!m) {
2387                 error = ENOBUFS;
2388                 goto fail;
2389         }
2390         result = m;
2391
2392         /* create lifetime extension (current and hard) */
2393         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2394         m = key_alloc_mbuf(len);
2395         if (!m || m->m_next) {  /*XXX*/
2396                 if (m)
2397                         m_freem(m);
2398                 error = ENOBUFS;
2399                 goto fail;
2400         }
2401         bzero(mtod(m, caddr_t), len);
2402         lt = mtod(m, struct sadb_lifetime *);
2403         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2404         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2405         lt->sadb_lifetime_allocations = 0;
2406         lt->sadb_lifetime_bytes = 0;
2407         lt->sadb_lifetime_addtime = sp->created;
2408         lt->sadb_lifetime_usetime = sp->lastused;
2409         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2410         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2411         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2412         lt->sadb_lifetime_allocations = 0;
2413         lt->sadb_lifetime_bytes = 0;
2414         lt->sadb_lifetime_addtime = sp->lifetime;
2415         lt->sadb_lifetime_usetime = sp->validtime;
2416         m_cat(result, m);
2417
2418         /* set sadb_address for source */
2419         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2420             &sp->spidx.src.sa,
2421             sp->spidx.prefs, sp->spidx.ul_proto);
2422         if (!m) {
2423                 error = ENOBUFS;
2424                 goto fail;
2425         }
2426         m_cat(result, m);
2427
2428         /* set sadb_address for destination */
2429         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2430             &sp->spidx.dst.sa,
2431             sp->spidx.prefd, sp->spidx.ul_proto);
2432         if (!m) {
2433                 error = ENOBUFS;
2434                 goto fail;
2435         }
2436         m_cat(result, m);
2437
2438         /* set secpolicy */
2439         m = key_sp2msg(sp);
2440         if (!m) {
2441                 error = ENOBUFS;
2442                 goto fail;
2443         }
2444         m_cat(result, m);
2445
2446         if ((result->m_flags & M_PKTHDR) == 0) {
2447                 error = EINVAL;
2448                 goto fail;
2449         }
2450
2451         if (result->m_len < sizeof(struct sadb_msg)) {
2452                 result = m_pullup(result, sizeof(struct sadb_msg));
2453                 if (result == NULL) {
2454                         error = ENOBUFS;
2455                         goto fail;
2456                 }
2457         }
2458         result->m_pkthdr.len = m_lengthm(result, NULL);
2459         mtod(result, struct sadb_msg *)->sadb_msg_len =
2460             PFKEY_UNIT64(result->m_pkthdr.len);
2461
2462         error = key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2463         crit_exit();
2464         return error;
2465
2466  fail:
2467         if (result)
2468                 m_freem(result);
2469         crit_exit();
2470         return error;
2471 }
2472
2473 /* %%% SAD management */
2474 /*
2475  * allocating a memory for new SA head, and copy from the values of mhp.
2476  * OUT: NULL    : failure due to the lack of memory.
2477  *      others  : pointer to new SA head.
2478  */
2479 static struct secashead *
2480 key_newsah(struct secasindex *saidx)
2481 {
2482         struct secashead *newsah;
2483
2484         KASSERT(saidx != NULL, ("key_newsaidx: null saidx"));
2485
2486         newsah = kmalloc(sizeof(struct secashead), M_SECA, 
2487                         M_INTWAIT | M_ZERO | M_NULLOK);
2488         if (newsah != NULL) {
2489                 int i;
2490                 for (i = 0; i < NELEM(newsah->savtree); i++)
2491                         LIST_INIT(&newsah->savtree[i]);
2492                 newsah->saidx = *saidx;
2493
2494                 /* add to saidxtree */
2495                 newsah->state = SADB_SASTATE_MATURE;
2496                 LIST_INSERT_HEAD(&sahtree, newsah, chain);
2497         }
2498         return(newsah);
2499 }
2500
2501 /*
2502  * Delete SA index and all registered SAs.
2503  */
2504 static void
2505 key_delsah(struct secashead *sah)
2506 {
2507         struct secasvar *sav, *nextsav;
2508         u_int stateidx;
2509         int nzombies = 0;
2510
2511         /* sanity check */
2512         if (sah == NULL)
2513                 panic("key_delsah: NULL pointer is passed.");
2514
2515         crit_enter();
2516
2517         /* searching all SA registerd in the secindex. */
2518         for (stateidx = 0; stateidx < NELEM(saorder_state_any);
2519              stateidx++) {
2520                 u_int state = saorder_state_any[stateidx];
2521
2522                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[state], chain, nextsav)
2523                         if (sav->refcnt == 0) {
2524                                 /* sanity check */
2525                                 KEY_CHKSASTATE(state, sav->state, __func__);
2526                                 KEY_FREESAV(&sav);
2527                         } else {
2528                                 /* give up to delete this SA */
2529                                 nzombies++;
2530                         }
2531         }
2532
2533         /* Delete sah it has are no savs. */
2534         if (nzombies == 0) {
2535                 /* remove from tree of SA index */
2536                 if (__LIST_CHAINED(sah))
2537                         LIST_REMOVE(sah, chain);
2538                 if (sah->sa_route.ro_rt) {
2539                         RTFREE(sah->sa_route.ro_rt);
2540                         sah->sa_route.ro_rt = NULL;
2541                 }
2542                 KFREE(sah);
2543         }
2544
2545         crit_exit();
2546         return;
2547 }
2548
2549 /*
2550  * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2551  * and copy the values of mhp into new buffer.
2552  * When SAD message type is GETSPI:
2553  *      to set sequence number from acq_seq++,
2554  *      to set zero to SPI.
2555  *      not to call key_setsava().
2556  * OUT: NULL    : fail
2557  *      others  : pointer to new secasvar.
2558  *
2559  * does not modify mbuf.  does not free mbuf on error.
2560  */
2561 static struct secasvar *
2562 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp, struct secashead *sah,
2563            int *errp, const char *where, int tag)
2564 {
2565         struct secasvar *newsav;
2566         const struct sadb_sa *xsa;
2567
2568         /* sanity check */
2569         if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
2570                 panic("key_newsa: NULL pointer is passed.");
2571
2572         KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
2573         if (newsav == NULL) {
2574                 ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
2575                 *errp = ENOBUFS;
2576                 goto done;
2577         }
2578         bzero((caddr_t)newsav, sizeof(struct secasvar));
2579
2580         switch (mhp->msg->sadb_msg_type) {
2581         case SADB_GETSPI:
2582                 newsav->spi = 0;
2583
2584 #ifdef IPSEC_DOSEQCHECK
2585                 /* sync sequence number */
2586                 if (mhp->msg->sadb_msg_seq == 0)
2587                         newsav->seq =
2588                                 (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
2589                 else
2590 #endif
2591                         newsav->seq = mhp->msg->sadb_msg_seq;
2592                 break;
2593
2594         case SADB_ADD:
2595                 /* sanity check */
2596                 if (mhp->ext[SADB_EXT_SA] == NULL) {
2597                         KFREE(newsav), newsav = NULL;
2598                         ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
2599                         *errp = EINVAL;
2600                         goto done;
2601                 }
2602                 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2603                 newsav->spi = xsa->sadb_sa_spi;
2604                 newsav->seq = mhp->msg->sadb_msg_seq;
2605                 break;
2606         default:
2607                 KFREE(newsav), newsav = NULL;
2608                 *errp = EINVAL;
2609                 goto done;
2610         }
2611
2612         /* copy sav values */
2613         if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2614                 *errp = key_setsaval(newsav, m, mhp);
2615                 if (*errp) {
2616                         KFREE(newsav), newsav = NULL;
2617                         goto done;
2618                 }
2619         }
2620
2621         /* reset created */
2622         newsav->created = time_second;
2623         newsav->pid = mhp->msg->sadb_msg_pid;
2624
2625         /* add to satree */
2626         newsav->sah = sah;
2627         newsav->refcnt = 1;
2628         newsav->state = SADB_SASTATE_LARVAL;
2629         LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2630                         secasvar, chain);
2631 done:
2632         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2633                 kprintf("DP key_newsav from %s:%u return SP:%p\n",
2634                         where, tag, newsav));
2635
2636         return newsav;
2637 }
2638
2639 /*
2640  * free() SA variable entry.
2641  */
2642 static void
2643 key_delsav(struct secasvar *sav)
2644 {
2645         KASSERT(sav != NULL, ("key_delsav: null sav"));
2646         KASSERT(sav->refcnt == 0,
2647                 ("key_delsav: reference count %u > 0", sav->refcnt));
2648
2649         /* remove from SA header */
2650         if (__LIST_CHAINED(sav))
2651                 LIST_REMOVE(sav, chain);
2652
2653         /*
2654          * Cleanup xform state.  Note that zeroize'ing causes the
2655          * keys to be cleared; otherwise we must do it ourself.
2656          */
2657         if (sav->tdb_xform != NULL) {
2658                 sav->tdb_xform->xf_zeroize(sav);
2659                 sav->tdb_xform = NULL;
2660         } else {
2661                 if (sav->key_auth != NULL)
2662                         bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2663                 if (sav->key_enc != NULL)
2664                         bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
2665         }
2666         if (sav->key_auth != NULL) {
2667                 KFREE(sav->key_auth);
2668                 sav->key_auth = NULL;
2669         }
2670         if (sav->key_enc != NULL) {
2671                 KFREE(sav->key_enc);
2672                 sav->key_enc = NULL;
2673         }
2674         if (sav->sched) {
2675                 bzero(sav->sched, sav->schedlen);
2676                 KFREE(sav->sched);
2677                 sav->sched = NULL;
2678         }
2679         if (sav->replay != NULL) {
2680                 KFREE(sav->replay);
2681                 sav->replay = NULL;
2682         }
2683         if (sav->lft_c != NULL) {
2684                 KFREE(sav->lft_c);
2685                 sav->lft_c = NULL;
2686         }
2687         if (sav->lft_h != NULL) {
2688                 KFREE(sav->lft_h);
2689                 sav->lft_h = NULL;
2690         }
2691         if (sav->lft_s != NULL) {
2692                 KFREE(sav->lft_s);
2693                 sav->lft_s = NULL;
2694         }
2695         if (sav->iv != NULL) {
2696                 KFREE(sav->iv);
2697                 sav->iv = NULL;
2698         }
2699
2700         KFREE(sav);
2701
2702         return;
2703 }
2704
2705 /*
2706  * search SAD.
2707  * OUT:
2708  *      NULL    : not found
2709  *      others  : found, pointer to a SA.
2710  */
2711 static struct secashead *
2712 key_getsah(struct secasindex *saidx)
2713 {
2714         struct secashead *sah;
2715
2716         LIST_FOREACH(sah, &sahtree, chain) {
2717                 if (sah->state == SADB_SASTATE_DEAD)
2718                         continue;
2719                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2720                         return sah;
2721         }
2722
2723         return NULL;
2724 }
2725
2726 /*
2727  * check not to be duplicated SPI.
2728  * NOTE: this function is too slow due to searching all SAD.
2729  * OUT:
2730  *      NULL    : not found
2731  *      others  : found, pointer to a SA.
2732  */
2733 static struct secasvar *
2734 key_checkspidup(struct secasindex *saidx, u_int32_t spi)
2735 {
2736         struct secashead *sah;
2737         struct secasvar *sav;
2738
2739         /* check address family */
2740         if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2741                 ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
2742                 return NULL;
2743         }
2744
2745         /* check all SAD */
2746         LIST_FOREACH(sah, &sahtree, chain) {
2747                 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2748                         continue;
2749                 sav = key_getsavbyspi(sah, spi);
2750                 if (sav != NULL)
2751                         return sav;
2752         }
2753
2754         return NULL;
2755 }
2756
2757 /*
2758  * search SAD litmited alive SA, protocol, SPI.
2759  * OUT:
2760  *      NULL    : not found
2761  *      others  : found, pointer to a SA.
2762  */
2763 static struct secasvar *
2764 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
2765 {
2766         struct secasvar *sav;
2767         u_int stateidx;
2768
2769         /* search all status */
2770         for (stateidx = 0; stateidx < NELEM(saorder_state_alive);
2771              stateidx++) {
2772                 u_int state = saorder_state_alive[stateidx];
2773
2774                 LIST_FOREACH(sav, &sah->savtree[state], chain) {
2775                         /* sanity check */
2776                         if (sav->state != state) {
2777                                 ipseclog((LOG_DEBUG, "key_getsavbyspi: "
2778                                     "invalid sav->state (queue: %d SA: %d)\n",
2779                                     state, sav->state));
2780                                 continue;
2781                         }
2782
2783                         if (sav->spi == spi)
2784                                 return sav;
2785                 }
2786         }
2787
2788         return NULL;
2789 }
2790
2791 /*
2792  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2793  * You must update these if need.
2794  * OUT: 0:      success.
2795  *      !0:     failure.
2796  *
2797  * does not modify mbuf.  does not free mbuf on error.
2798  */
2799 static int
2800 key_setsaval(struct secasvar *sav, struct mbuf *m,
2801              const struct sadb_msghdr *mhp)
2802 {
2803         int error = 0;
2804
2805         /* sanity check */
2806         if (m == NULL || mhp == NULL || mhp->msg == NULL)
2807                 panic("key_setsaval: NULL pointer is passed.");
2808
2809         /* initialization */
2810         sav->replay = NULL;
2811         sav->key_auth = NULL;
2812         sav->key_enc = NULL;
2813         sav->sched = NULL;
2814         sav->schedlen = 0;
2815         sav->iv = NULL;
2816         sav->lft_c = NULL;
2817         sav->lft_h = NULL;
2818         sav->lft_s = NULL;
2819         sav->tdb_xform = NULL;          /* transform */
2820         sav->tdb_encalgxform = NULL;    /* encoding algorithm */
2821         sav->tdb_authalgxform = NULL;   /* authentication algorithm */
2822         sav->tdb_compalgxform = NULL;   /* compression algorithm */
2823
2824         /* SA */
2825         if (mhp->ext[SADB_EXT_SA] != NULL) {
2826                 const struct sadb_sa *sa0;
2827
2828                 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2829                 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
2830                         error = EINVAL;
2831                         goto fail;
2832                 }
2833
2834                 sav->alg_auth = sa0->sadb_sa_auth;
2835                 sav->alg_enc = sa0->sadb_sa_encrypt;
2836                 sav->flags = sa0->sadb_sa_flags;
2837
2838                 /* replay window */
2839                 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
2840                         sav->replay = 
2841                             kmalloc(sizeof(struct secreplay)+sa0->sadb_sa_replay,
2842                                     M_SECA, M_INTWAIT | M_ZERO | M_NULLOK);
2843                         if (sav->replay == NULL) {
2844                                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2845                                 error = ENOBUFS;
2846                                 goto fail;
2847                         }
2848                         if (sa0->sadb_sa_replay != 0)
2849                                 sav->replay->bitmap = (caddr_t)(sav->replay+1);
2850                         sav->replay->wsize = sa0->sadb_sa_replay;
2851                 }
2852         }
2853
2854         /* Authentication keys */
2855         if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
2856                 const struct sadb_key *key0;
2857                 int len;
2858
2859                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
2860                 len = mhp->extlen[SADB_EXT_KEY_AUTH];
2861
2862                 error = 0;
2863                 if (len < sizeof(*key0)) {
2864                         error = EINVAL;
2865                         goto fail;
2866                 }
2867                 switch (mhp->msg->sadb_msg_satype) {
2868                 case SADB_SATYPE_AH:
2869                 case SADB_SATYPE_ESP:
2870                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
2871                             sav->alg_auth != SADB_X_AALG_NULL)
2872                                 error = EINVAL;
2873                         break;
2874                 case SADB_X_SATYPE_IPCOMP:
2875                 default:
2876                         error = EINVAL;
2877                         break;
2878                 }
2879                 if (error) {
2880                         ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
2881                         goto fail;
2882                 }
2883
2884                 sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
2885                 if (sav->key_auth == NULL) {
2886                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2887                         error = ENOBUFS;
2888                         goto fail;
2889                 }
2890         }
2891
2892         /* Encryption key */
2893         if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
2894                 const struct sadb_key *key0;
2895                 int len;
2896
2897                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
2898                 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
2899
2900                 error = 0;
2901                 if (len < sizeof(*key0)) {
2902                         error = EINVAL;
2903                         goto fail;
2904                 }
2905                 switch (mhp->msg->sadb_msg_satype) {
2906                 case SADB_SATYPE_ESP:
2907                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
2908                             sav->alg_enc != SADB_EALG_NULL) {
2909                                 error = EINVAL;
2910                                 break;
2911                         }
2912                         sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
2913                         if (sav->key_enc == NULL) {
2914                                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2915                                 error = ENOBUFS;
2916                                 goto fail;
2917                         }
2918                         break;
2919                 case SADB_X_SATYPE_IPCOMP:
2920                         if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
2921                                 error = EINVAL;
2922                         sav->key_enc = NULL;    /*just in case*/
2923                         break;
2924                 case SADB_SATYPE_AH:
2925                 default:
2926                         error = EINVAL;
2927                         break;
2928                 }
2929                 if (error) {
2930                         ipseclog((LOG_DEBUG, "key_setsatval: invalid key_enc value.\n"));
2931                         goto fail;
2932                 }
2933         }
2934
2935         /* set iv */
2936         sav->ivlen = 0;
2937
2938         switch (mhp->msg->sadb_msg_satype) {
2939         case SADB_SATYPE_AH:
2940                 error = xform_init(sav, XF_AH);
2941                 break;
2942         case SADB_SATYPE_ESP:
2943                 error = xform_init(sav, XF_ESP);
2944                 break;
2945         case SADB_X_SATYPE_IPCOMP:
2946                 error = xform_init(sav, XF_IPCOMP);
2947                 break;
2948         }
2949         if (error) {
2950                 ipseclog((LOG_DEBUG,
2951                         "key_setsaval: unable to initialize SA type %u.\n",
2952                         mhp->msg->sadb_msg_satype));
2953                 goto fail;
2954         }
2955
2956         /* reset created */
2957         sav->created = time_second;
2958
2959         /* make lifetime for CURRENT */
2960         KMALLOC(sav->lft_c, struct sadb_lifetime *,
2961             sizeof(struct sadb_lifetime));
2962         if (sav->lft_c == NULL) {
2963                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2964                 error = ENOBUFS;
2965                 goto fail;
2966         }
2967
2968         sav->lft_c->sadb_lifetime_len =
2969             PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2970         sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2971         sav->lft_c->sadb_lifetime_allocations = 0;
2972         sav->lft_c->sadb_lifetime_bytes = 0;
2973         sav->lft_c->sadb_lifetime_addtime = time_second;
2974         sav->lft_c->sadb_lifetime_usetime = 0;
2975
2976         /* lifetimes for HARD and SOFT */
2977     {
2978         const struct sadb_lifetime *lft0;
2979
2980         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
2981         if (lft0 != NULL) {
2982                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
2983                         error = EINVAL;
2984                         goto fail;
2985                 }
2986                 sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
2987                     sizeof(*lft0));
2988                 if (sav->lft_h == NULL) {
2989                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2990                         error = ENOBUFS;
2991                         goto fail;
2992                 }
2993                 /* to be initialize ? */
2994         }
2995
2996         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
2997         if (lft0 != NULL) {
2998                 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
2999                         error = EINVAL;
3000                         goto fail;
3001                 }
3002                 sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
3003                     sizeof(*lft0));
3004                 if (sav->lft_s == NULL) {
3005                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3006                         error = ENOBUFS;
3007                         goto fail;
3008                 }
3009                 /* to be initialize ? */
3010         }
3011     }
3012
3013         return 0;
3014
3015  fail:
3016         /* initialization */
3017         if (sav->replay != NULL) {
3018                 KFREE(sav->replay);
3019                 sav->replay = NULL;
3020         }
3021         if (sav->key_auth != NULL) {
3022                 KFREE(sav->key_auth);
3023                 sav->key_auth = NULL;
3024         }
3025         if (sav->key_enc != NULL) {
3026                 KFREE(sav->key_enc);
3027                 sav->key_enc = NULL;
3028         }
3029         if (sav->sched) {
3030                 KFREE(sav->sched);
3031                 sav->sched = NULL;
3032         }
3033         if (sav->iv != NULL) {
3034                 KFREE(sav->iv);
3035                 sav->iv = NULL;
3036         }
3037         if (sav->lft_c != NULL) {
3038                 KFREE(sav->lft_c);
3039                 sav->lft_c = NULL;
3040         }
3041         if (sav->lft_h != NULL) {
3042                 KFREE(sav->lft_h);
3043                 sav->lft_h = NULL;
3044         }
3045         if (sav->lft_s != NULL) {
3046                 KFREE(sav->lft_s);
3047                 sav->lft_s = NULL;
3048         }
3049
3050         return error;
3051 }
3052
3053 /*
3054  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3055  * OUT: 0:      valid
3056  *      other:  errno
3057  */
3058 static int
3059 key_mature(struct secasvar *sav)
3060 {
3061         int error;
3062
3063         /* check SPI value */
3064         switch (sav->sah->saidx.proto) {
3065         case IPPROTO_ESP:
3066         case IPPROTO_AH:
3067                 if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
3068                         ipseclog((LOG_DEBUG,
3069                             "key_mature: illegal range of SPI %u.\n",
3070                             (u_int32_t)ntohl(sav->spi)));
3071                         return EINVAL;
3072                 }
3073                 break;
3074         }
3075
3076         /* check satype */
3077         switch (sav->sah->saidx.proto) {
3078         case IPPROTO_ESP:
3079                 /* check flags */
3080                 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3081                     (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3082                         ipseclog((LOG_DEBUG, "key_mature: "
3083                             "invalid flag (derived) given to old-esp.\n"));
3084                         return EINVAL;
3085                 }
3086                 error = xform_init(sav, XF_ESP);
3087                 break;
3088         case IPPROTO_AH:
3089                 /* check flags */
3090                 if (sav->flags & SADB_X_EXT_DERIV) {
3091                         ipseclog((LOG_DEBUG, "key_mature: "
3092                             "invalid flag (derived) given to AH SA.\n"));
3093                         return EINVAL;
3094                 }
3095                 if (sav->alg_enc != SADB_EALG_NONE) {
3096                         ipseclog((LOG_DEBUG, "key_mature: "
3097                             "protocol and algorithm mismated.\n"));
3098                         return(EINVAL);
3099                 }
3100                 error = xform_init(sav, XF_AH);
3101                 break;
3102         case IPPROTO_IPCOMP:
3103                 if (sav->alg_auth != SADB_AALG_NONE) {
3104                         ipseclog((LOG_DEBUG, "key_mature: "
3105                                 "protocol and algorithm mismated.\n"));
3106                         return(EINVAL);
3107                 }
3108                 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3109                  && ntohl(sav->spi) >= 0x10000) {
3110                         ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
3111                         return(EINVAL);
3112                 }
3113                 error = xform_init(sav, XF_IPCOMP);
3114                 break;
3115         default:
3116                 ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
3117                 error = EPROTONOSUPPORT;
3118                 break;
3119         }
3120         if (error == 0)
3121                 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3122         return (error);
3123 }
3124
3125 /*
3126  * subroutine for SADB_GET and SADB_DUMP.
3127  */
3128 static struct mbuf *
3129 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3130               u_int32_t seq, u_int32_t pid)
3131 {
3132         struct mbuf *result = NULL, *tres = NULL, *m;
3133         int l = 0;
3134         int i;
3135         void *p;
3136         int dumporder[] = {
3137                 SADB_EXT_SA, SADB_X_EXT_SA2,
3138                 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3139                 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3140                 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3141                 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3142                 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3143         };
3144
3145         m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3146         if (m == NULL)
3147                 goto fail;
3148         result = m;
3149
3150         for (i = NELEM(dumporder) - 1; i >= 0; i--) {
3151                 m = NULL;
3152                 p = NULL;
3153                 switch (dumporder[i]) {
3154                 case SADB_EXT_SA:
3155                         m = key_setsadbsa(sav);
3156                         if (!m)
3157                                 goto fail;
3158                         break;
3159
3160                 case SADB_X_EXT_SA2:
3161                         m = key_setsadbxsa2(sav->sah->saidx.mode,
3162                                         sav->replay ? sav->replay->count : 0,
3163                                         sav->sah->saidx.reqid);
3164                         if (!m)
3165                                 goto fail;
3166                         break;
3167
3168                 case SADB_EXT_ADDRESS_SRC:
3169                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3170                             &sav->sah->saidx.src.sa,
3171                             FULLMASK, IPSEC_ULPROTO_ANY);
3172                         if (!m)
3173                                 goto fail;
3174                         break;
3175
3176                 case SADB_EXT_ADDRESS_DST:
3177                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3178                             &sav->sah->saidx.dst.sa,
3179                             FULLMASK, IPSEC_ULPROTO_ANY);
3180                         if (!m)
3181                                 goto fail;
3182                         break;
3183
3184                 case SADB_EXT_KEY_AUTH:
3185                         if (!sav->key_auth)
3186                                 continue;
3187                         l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3188                         p = sav->key_auth;
3189                         break;
3190
3191                 case SADB_EXT_KEY_ENCRYPT:
3192                         if (!sav->key_enc)
3193                                 continue;
3194                         l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3195                         p = sav->key_enc;
3196                         break;
3197
3198                 case SADB_EXT_LIFETIME_CURRENT:
3199                         if (!sav->lft_c)
3200                                 continue;
3201                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3202                         p = sav->lft_c;
3203                         break;
3204
3205                 case SADB_EXT_LIFETIME_HARD:
3206                         if (!sav->lft_h)
3207                                 continue;
3208                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3209                         p = sav->lft_h;
3210                         break;
3211
3212                 case SADB_EXT_LIFETIME_SOFT:
3213                         if (!sav->lft_s)
3214                                 continue;
3215                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3216                         p = sav->lft_s;
3217                         break;
3218
3219                 case SADB_EXT_ADDRESS_PROXY:
3220                 case SADB_EXT_IDENTITY_SRC:
3221                 case SADB_EXT_IDENTITY_DST:
3222                         /* XXX: should we brought from SPD ? */
3223                 case SADB_EXT_SENSITIVITY:
3224                 default:
3225                         continue;
3226                 }
3227
3228                 if ((!m && !p) || (m && p))
3229                         goto fail;
3230                 if (p && tres) {
3231                         M_PREPEND(tres, l, MB_DONTWAIT);
3232                         if (!tres)
3233                                 goto fail;
3234                         bcopy(p, mtod(tres, caddr_t), l);
3235                         continue;
3236                 }
3237                 if (p) {
3238                         m = key_alloc_mbuf(l);
3239                         if (!m)
3240                                 goto fail;
3241                         m_copyback(m, 0, l, p);
3242                 }
3243
3244                 if (tres)
3245                         m_cat(m, tres);
3246                 tres = m;
3247         }
3248
3249         m_cat(result, tres);
3250
3251         if (result->m_len < sizeof(struct sadb_msg)) {
3252                 result = m_pullup(result, sizeof(struct sadb_msg));
3253                 if (result == NULL)
3254                         goto fail;
3255         }
3256         result->m_pkthdr.len = m_lengthm(result, NULL);
3257         mtod(result, struct sadb_msg *)->sadb_msg_len =
3258             PFKEY_UNIT64(result->m_pkthdr.len);
3259
3260         return result;
3261
3262 fail:
3263         m_freem(result);
3264         m_freem(tres);
3265         return NULL;
3266 }
3267
3268 /*
3269  * set data into sadb_msg.
3270  */
3271 static struct mbuf *
3272 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3273                pid_t pid, u_int16_t reserved)
3274 {
3275         struct mbuf *m;
3276         struct sadb_msg *p;
3277         int len;
3278
3279         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3280         if (len > MCLBYTES)
3281                 return NULL;
3282         m = m_getb(len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
3283         if (!m)
3284                 return NULL;
3285         m->m_pkthdr.len = m->m_len = len;
3286
3287         p = mtod(m, struct sadb_msg *);
3288
3289         bzero(p, len);
3290         p->sadb_msg_version = PF_KEY_V2;
3291         p->sadb_msg_type = type;
3292         p->sadb_msg_errno = 0;
3293         p->sadb_msg_satype = satype;
3294         p->sadb_msg_len = PFKEY_UNIT64(tlen);
3295         p->sadb_msg_reserved = reserved;
3296         p->sadb_msg_seq = seq;
3297         p->sadb_msg_pid = (u_int32_t)pid;
3298
3299         return m;
3300 }
3301
3302 /*
3303  * copy secasvar data into sadb_address.
3304  */
3305 static struct mbuf *
3306 key_setsadbsa(struct secasvar *sav)
3307 {
3308         struct mbuf *m;
3309         struct sadb_sa *p;
3310         int len;
3311
3312         len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3313         m = key_alloc_mbuf(len);
3314         if (!m || m->m_next) {  /*XXX*/
3315                 if (m)
3316                         m_freem(m);
3317                 return NULL;
3318         }
3319
3320         p = mtod(m, struct sadb_sa *);
3321
3322         bzero(p, len);
3323         p->sadb_sa_len = PFKEY_UNIT64(len);
3324         p->sadb_sa_exttype = SADB_EXT_SA;
3325         p->sadb_sa_spi = sav->spi;
3326         p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3327         p->sadb_sa_state = sav->state;
3328         p->sadb_sa_auth = sav->alg_auth;
3329         p->sadb_sa_encrypt = sav->alg_enc;
3330         p->sadb_sa_flags = sav->flags;
3331
3332         return m;
3333 }
3334
3335 /*
3336  * set data into sadb_address.
3337  */
3338 static struct mbuf *
3339 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen,
3340                 u_int16_t ul_proto)
3341 {
3342         struct mbuf *m;
3343         struct sadb_address *p;
3344         size_t len;
3345
3346         len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3347             PFKEY_ALIGN8(saddr->sa_len);
3348         m = key_alloc_mbuf(len);
3349         if (!m || m->m_next) {  /*XXX*/
3350                 if (m)
3351                         m_freem(m);
3352                 return NULL;
3353         }
3354
3355         p = mtod(m, struct sadb_address *);
3356
3357         bzero(p, len);
3358         p->sadb_address_len = PFKEY_UNIT64(len);
3359         p->sadb_address_exttype = exttype;
3360         p->sadb_address_proto = ul_proto;
3361         if (prefixlen == FULLMASK) {
3362                 switch (saddr->sa_family) {
3363                 case AF_INET:
3364                         prefixlen = sizeof(struct in_addr) << 3;
3365                         break;
3366                 case AF_INET6:
3367                         prefixlen = sizeof(struct in6_addr) << 3;
3368                         break;
3369                 default:
3370                         ; /*XXX*/
3371                 }
3372         }
3373         p->sadb_address_prefixlen = prefixlen;
3374         p->sadb_address_reserved = 0;
3375
3376         bcopy(saddr,
3377             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3378             saddr->sa_len);
3379
3380         return m;
3381 }
3382
3383 #if 0
3384 /*
3385  * set data into sadb_ident.
3386  */
3387 static struct mbuf *
3388 key_setsadbident(u_int16_t exttype, u_int16_t idtype, caddr_t string,
3389                  int stringlen, u_int64_t id)
3390 {
3391         struct mbuf *m;
3392         struct sadb_ident *p;
3393         size_t len;
3394
3395         len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
3396         m = key_alloc_mbuf(len);
3397         if (!m || m->m_next) {  /*XXX*/
3398                 if (m)
3399                         m_freem(m);
3400                 return NULL;
3401         }
3402
3403         p = mtod(m, struct sadb_ident *);
3404
3405         bzero(p, len);
3406         p->sadb_ident_len = PFKEY_UNIT64(len);
3407         p->sadb_ident_exttype = exttype;
3408         p->sadb_ident_type = idtype;
3409         p->sadb_ident_reserved = 0;
3410         p->sadb_ident_id = id;
3411
3412         bcopy(string,
3413             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
3414             stringlen);
3415
3416         return m;
3417 }
3418 #endif
3419
3420 /*
3421  * set data into sadb_x_sa2.
3422  */
3423 static struct mbuf *
3424 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3425 {
3426         struct mbuf *m;
3427         struct sadb_x_sa2 *p;
3428         size_t len;
3429
3430         len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3431         m = key_alloc_mbuf(len);
3432         if (!m || m->m_next) {  /*XXX*/
3433                 if (m)
3434                         m_freem(m);
3435                 return NULL;
3436         }
3437
3438         p = mtod(m, struct sadb_x_sa2 *);
3439
3440         bzero(p, len);
3441         p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3442         p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3443         p->sadb_x_sa2_mode = mode;
3444         p->sadb_x_sa2_reserved1 = 0;
3445         p->sadb_x_sa2_reserved2 = 0;
3446         p->sadb_x_sa2_sequence = seq;
3447         p->sadb_x_sa2_reqid = reqid;
3448
3449         return m;
3450 }
3451
3452 /*
3453  * set data into sadb_x_policy
3454  */
3455 static struct mbuf *
3456 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3457 {
3458         struct mbuf *m;
3459         struct sadb_x_policy *p;
3460         size_t len;
3461
3462         len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3463         m = key_alloc_mbuf(len);
3464         if (!m || m->m_next) {  /*XXX*/
3465                 if (m)
3466                         m_freem(m);
3467                 return NULL;
3468         }
3469
3470         p = mtod(m, struct sadb_x_policy *);
3471
3472         bzero(p, len);
3473         p->sadb_x_policy_len = PFKEY_UNIT64(len);
3474         p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3475         p->sadb_x_policy_type = type;
3476         p->sadb_x_policy_dir = dir;
3477         p->sadb_x_policy_id = id;
3478
3479         return m;
3480 }
3481
3482 /* %%% utilities */
3483 /*
3484  * copy a buffer into the new buffer allocated.
3485  */
3486 static void *
3487 key_newbuf(const void *src, u_int len)
3488 {
3489         caddr_t new;
3490
3491         KMALLOC(new, caddr_t, len);
3492         if (new == NULL) {
3493                 ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
3494                 return NULL;
3495         }
3496         bcopy(src, new, len);
3497
3498         return new;
3499 }
3500
3501 /* compare my own address
3502  * OUT: 1: true, i.e. my address.
3503  *      0: false
3504  */
3505 int
3506 key_ismyaddr(struct sockaddr *sa)
3507 {
3508 #ifdef INET
3509         struct sockaddr_in *sin;
3510         struct in_ifaddr_container *iac;
3511 #endif
3512
3513         /* sanity check */
3514         if (sa == NULL)
3515                 panic("key_ismyaddr: NULL pointer is passed.");
3516
3517         switch (sa->sa_family) {
3518 #ifdef INET
3519         case AF_INET:
3520                 sin = (struct sockaddr_in *)sa;
3521                 TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
3522                         struct in_ifaddr *ia = iac->ia;
3523
3524                         if (sin->sin_family == ia->ia_addr.sin_family &&
3525                             sin->sin_len == ia->ia_addr.sin_len &&
3526                             sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3527                         {
3528                                 return 1;
3529                         }
3530                 }
3531                 break;
3532 #endif
3533 #ifdef INET6
3534         case AF_INET6:
3535                 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3536 #endif
3537         }
3538
3539         return 0;
3540 }
3541
3542 #ifdef INET6
3543 /*
3544  * compare my own address for IPv6.
3545  * 1: ours
3546  * 0: other
3547  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3548  */
3549 static int
3550 key_ismyaddr6(struct sockaddr_in6 *sin6)
3551 {
3552         struct in6_ifaddr *ia;
3553         struct in6_multi *in6m;
3554
3555         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3556                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3557                     (struct sockaddr *)&ia->ia_addr, 0) == 0)
3558                         return 1;
3559
3560                 /*
3561                  * XXX Multicast
3562                  * XXX why do we care about multlicast here while we don't care
3563                  * about IPv4 multicast??
3564                  * XXX scope
3565                  */
3566                 in6m = IN6_LOOKUP_MULTI(&sin6->sin6_addr, ia->ia_ifp);
3567                 if (in6m)
3568                         return 1;
3569         }
3570
3571         /* loopback, just for safety */
3572         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3573                 return 1;
3574
3575         return 0;
3576 }
3577 #endif /*INET6*/
3578
3579 /*
3580  * compare two secasindex structure.
3581  * flag can specify to compare 2 saidxes.
3582  * compare two secasindex structure without both mode and reqid.
3583  * don't compare port.
3584  * IN:  
3585  *      saidx0: source, it can be in SAD.
3586  *      saidx1: object.
3587  * OUT: 
3588  *      1 : equal
3589  *      0 : not equal
3590  */
3591 static int
3592 key_cmpsaidx(
3593         const struct secasindex *saidx0,
3594         const struct secasindex *saidx1,
3595         int flag)
3596 {
3597         /* sanity */
3598         if (saidx0 == NULL && saidx1 == NULL)
3599                 return 1;
3600
3601         if (saidx0 == NULL || saidx1 == NULL)
3602                 return 0;
3603
3604         if (saidx0->proto != saidx1->proto)
3605                 return 0;
3606
3607         if (flag == CMP_EXACTLY) {
3608                 if (saidx0->mode != saidx1->mode)
3609                         return 0;
3610                 if (saidx0->reqid != saidx1->reqid)
3611                         return 0;
3612                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3613                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3614                         return 0;
3615         } else {
3616
3617                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3618                 if (flag == CMP_MODE_REQID
3619                   ||flag == CMP_REQID) {
3620                         /*
3621                          * If reqid of SPD is non-zero, unique SA is required.
3622                          * The result must be of same reqid in this case.
3623                          */
3624                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3625                                 return 0;
3626                 }
3627
3628                 if (flag == CMP_MODE_REQID) {
3629                         if (saidx0->mode != IPSEC_MODE_ANY
3630                          && saidx0->mode != saidx1->mode)
3631                                 return 0;
3632                 }
3633
3634                 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3635                         return 0;
3636                 }
3637                 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3638                         return 0;
3639                 }
3640         }
3641
3642         return 1;
3643 }
3644
3645 /*
3646  * compare two secindex structure exactly.
3647  * IN:
3648  *      spidx0: source, it is often in SPD.
3649  *      spidx1: object, it is often from PFKEY message.
3650  * OUT:
3651  *      1 : equal
3652  *      0 : not equal
3653  */
3654 static int
3655 key_cmpspidx_exactly(
3656         struct secpolicyindex *spidx0,
3657         struct secpolicyindex *spidx1)
3658 {
3659         /* sanity */
3660         if (spidx0 == NULL && spidx1 == NULL)
3661                 return 1;
3662
3663         if (spidx0 == NULL || spidx1 == NULL)
3664                 return 0;
3665
3666         if (spidx0->prefs != spidx1->prefs
3667          || spidx0->prefd != spidx1->prefd
3668          || spidx0->ul_proto != spidx1->ul_proto)
3669                 return 0;
3670
3671         return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3672                key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3673 }
3674
3675 /*
3676  * compare two secindex structure with mask.
3677  * IN:
3678  *      spidx0: source, it is often in SPD.
3679  *      spidx1: object, it is often from IP header.
3680  * OUT:
3681  *      1 : equal
3682  *      0 : not equal
3683  */
3684 static int
3685 key_cmpspidx_withmask(
3686         struct secpolicyindex *spidx0,
3687         struct secpolicyindex *spidx1)
3688 {
3689         /* sanity */
3690         if (spidx0 == NULL && spidx1 == NULL)
3691                 return 1;
3692
3693         if (spidx0 == NULL || spidx1 == NULL)
3694                 return 0;
3695
3696         if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3697             spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3698             spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3699             spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3700                 return 0;
3701
3702         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3703         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3704          && spidx0->ul_proto != spidx1->ul_proto)
3705                 return 0;
3706
3707         switch (spidx0->src.sa.sa_family) {
3708         case AF_INET:
3709                 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3710                  && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3711                         return 0;
3712                 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3713                     &spidx1->src.sin.sin_addr, spidx0->prefs))
3714                         return 0;
3715                 break;
3716         case AF_INET6:
3717                 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3718                  && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3719                         return 0;
3720                 /*
3721                  * scope_id check. if sin6_scope_id is 0, we regard it
3722                  * as a wildcard scope, which matches any scope zone ID. 
3723                  */
3724                 if (spidx0->src.sin6.sin6_scope_id &&
3725                     spidx1->src.sin6.sin6_scope_id &&
3726                     spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3727                         return 0;
3728                 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3729                     &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3730                         return 0;
3731                 break;
3732         default:
3733                 /* XXX */
3734                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3735                         return 0;
3736                 break;
3737         }
3738
3739         switch (spidx0->dst.sa.sa_family) {
3740         case AF_INET:
3741                 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3742                  && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3743                         return 0;
3744                 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3745                     &spidx1->dst.sin.sin_addr, spidx0->prefd))
3746                         return 0;
3747                 break;
3748         case AF_INET6:
3749                 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3750                  && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3751                         return 0;
3752                 /*
3753                  * scope_id check. if sin6_scope_id is 0, we regard it
3754                  * as a wildcard scope, which matches any scope zone ID. 
3755                  */
3756                 if (spidx0->dst.sin6.sin6_scope_id &&
3757                     spidx1->dst.sin6.sin6_scope_id &&
3758                     spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3759                         return 0;
3760                 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3761                     &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3762                         return 0;
3763                 break;
3764         default:
3765                 /* XXX */
3766                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3767                         return 0;
3768                 break;
3769         }
3770
3771         /* XXX Do we check other field ?  e.g. flowinfo */
3772
3773         return 1;
3774 }
3775
3776 /* returns 0 on match */
3777 static int
3778 key_sockaddrcmp(
3779         const struct sockaddr *sa1,
3780         const struct sockaddr *sa2,
3781         int port)
3782 {
3783 #ifdef satosin
3784 #undef satosin
3785 #endif
3786 #define satosin(s) ((const struct sockaddr_in *)s)
3787 #ifdef satosin6
3788 #undef satosin6
3789 #endif
3790 #define satosin6(s) ((const struct sockaddr_in6 *)s)
3791         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
3792                 return 1;
3793
3794         switch (sa1->sa_family) {
3795         case AF_INET:
3796                 if (sa1->sa_len != sizeof(struct sockaddr_in))
3797                         return 1;
3798                 if (satosin(sa1)->sin_addr.s_addr !=
3799                     satosin(sa2)->sin_addr.s_addr) {
3800                         return 1;
3801                 }
3802                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
3803                         return 1;
3804                 break;
3805         case AF_INET6:
3806                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
3807                         return 1;       /*EINVAL*/
3808                 if (satosin6(sa1)->sin6_scope_id !=
3809                     satosin6(sa2)->sin6_scope_id) {
3810                         return 1;
3811                 }
3812                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
3813                     &satosin6(sa2)->sin6_addr)) {
3814                         return 1;
3815                 }
3816                 if (port &&
3817                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
3818                         return 1;
3819                 }
3820         default:
3821                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
3822                         return 1;
3823                 break;
3824         }
3825
3826         return 0;
3827 #undef satosin
3828 #undef satosin6
3829 }
3830
3831 /*
3832  * compare two buffers with mask.
3833  * IN:
3834  *      addr1: source
3835  *      addr2: object
3836  *      bits:  Number of bits to compare
3837  * OUT:
3838  *      1 : equal
3839  *      0 : not equal
3840  */
3841 static int
3842 key_bbcmp(const void *a1, const void *a2, u_int bits)
3843 {
3844         const unsigned char *p1 = a1;
3845         const unsigned char *p2 = a2;
3846
3847         /* XXX: This could be considerably faster if we compare a word
3848          * at a time, but it is complicated on LSB Endian machines */
3849
3850         /* Handle null pointers */
3851         if (p1 == NULL || p2 == NULL)
3852                 return (p1 == p2);
3853
3854         while (bits >= 8) {
3855                 if (*p1++ != *p2++)
3856                         return 0;
3857                 bits -= 8;
3858         }
3859
3860         if (bits > 0) {
3861                 u_int8_t mask = ~((1<<(8-bits))-1);
3862                 if ((*p1 & mask) != (*p2 & mask))
3863                         return 0;
3864         }
3865         return 1;       /* Match! */
3866 }
3867
3868 /*
3869  * time handler.
3870  * scanning SPD and SAD to check status for each entries,
3871  * and do to remove or to expire.
3872  * XXX: year 2038 problem may remain.
3873  */
3874 void
3875 key_timehandler(void *unused)
3876 {
3877         u_int dir;
3878         time_t now = time_second;
3879         struct secspacq *spacq, *nextspacq;
3880
3881         crit_enter();
3882
3883         /* SPD */
3884     {
3885         struct secpolicy *sp, *nextsp;
3886
3887         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
3888                 LIST_FOREACH_MUTABLE(sp, &sptree[dir], chain, nextsp) {
3889                         if (sp->state == IPSEC_SPSTATE_DEAD) {
3890                                 KEY_FREESP(&sp);
3891                                 continue;
3892                         }
3893
3894                         if (sp->lifetime == 0 && sp->validtime == 0)
3895                                 continue;
3896
3897                         /* the deletion will occur next time */
3898                         if ((sp->lifetime && now - sp->created > sp->lifetime)
3899                          || (sp->validtime && now - sp->lastused > sp->validtime)) {
3900                                 sp->state = IPSEC_SPSTATE_DEAD;
3901                                 key_spdexpire(sp);
3902                                 continue;
3903                         }
3904                 }
3905         }
3906     }
3907
3908         /* SAD */
3909     {
3910         struct secashead *sah, *nextsah;
3911         struct secasvar *sav, *nextsav;
3912
3913         LIST_FOREACH_MUTABLE(sah, &sahtree, chain, nextsah) {
3914                 /* if sah has been dead, then delete it and process next sah. */
3915                 if (sah->state == SADB_SASTATE_DEAD) {
3916                         key_delsah(sah);
3917                         continue;
3918                 }
3919
3920                 /* if LARVAL entry doesn't become MATURE, delete it. */
3921                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_LARVAL],
3922                                      chain, nextsav) {
3923                         if (now - sav->created > key_larval_lifetime) {
3924                                 KEY_FREESAV(&sav);
3925                         }
3926                 }
3927
3928                 /*
3929                  * check MATURE entry to start to send expire message
3930                  * whether or not.
3931                  */
3932                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_MATURE],
3933                                      chain, nextsav) {
3934                         /* we don't need to check. */
3935                         if (sav->lft_s == NULL)
3936                                 continue;
3937
3938                         /* sanity check */
3939                         if (sav->lft_c == NULL) {
3940                                 ipseclog((LOG_DEBUG,"key_timehandler: "
3941                                         "There is no CURRENT time, why?\n"));
3942                                 continue;
3943                         }
3944
3945                         /* check SOFT lifetime */
3946                         if (sav->lft_s->sadb_lifetime_addtime != 0
3947                          && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
3948                                 /*
3949                                  * check SA to be used whether or not.
3950                                  * when SA hasn't been used, delete it.
3951                                  */
3952                                 if (sav->lft_c->sadb_lifetime_usetime == 0) {
3953                                         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
3954                                         KEY_FREESAV(&sav);
3955                                 } else {
3956                                         key_sa_chgstate(sav, SADB_SASTATE_DYING);
3957                                         /*
3958                                          * XXX If we keep to send expire
3959                                          * message in the status of
3960                                          * DYING. Do remove below code.
3961                                          */
3962                                         key_expire(sav);
3963                                 }
3964                         }
3965                         /* check SOFT lifetime by bytes */
3966                         /*
3967                          * XXX I don't know the way to delete this SA
3968                          * when new SA is installed.  Caution when it's
3969                          * installed too big lifetime by time.
3970                          */
3971                         else if (sav->lft_s->sadb_lifetime_bytes != 0
3972                               && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
3973
3974                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
3975                                 /*
3976                                  * XXX If we keep to send expire
3977                                  * message in the status of
3978                                  * DYING. Do remove below code.
3979                                  */
3980                                 key_expire(sav);
3981                         }
3982                 }