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