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