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