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