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