Change (almost) all references to tqh_first and tqe_next and tqe_prev
[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.9 2004/08/02 13:22:33 joerg Exp $    */
3 /*      $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
4
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * This code is referd to RFC 2367
36  */
37
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41
42 #include <sys/types.h>
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/mbuf.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
49 #include <sys/malloc.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/errno.h>
54 #include <sys/proc.h>
55 #include <sys/queue.h>
56 #include <sys/syslog.h>
57
58 #include <net/if.h>
59 #include <net/route.h>
60 #include <net/raw_cb.h>
61
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/in_var.h>
66
67 #ifdef INET6
68 #include <netinet/ip6.h>
69 #include <netinet6/in6_var.h>
70 #include <netinet6/ip6_var.h>
71 #endif /* INET6 */
72
73 #ifdef INET
74 #include <netinet/in_pcb.h>
75 #endif
76 #ifdef INET6
77 #include <netinet6/in6_pcb.h>
78 #endif /* INET6 */
79
80 #include <net/pfkeyv2.h>
81 #include "keydb.h"
82 #include "key.h"
83 #include "keysock.h"
84 #include "key_debug.h"
85
86 #include <netinet6/ipsec.h>
87 #ifdef INET6
88 #include <netinet6/ipsec6.h>
89 #endif
90 #include <netinet6/ah.h>
91 #ifdef INET6
92 #include <netinet6/ah6.h>
93 #endif
94 #ifdef IPSEC_ESP
95 #include <netinet6/esp.h>
96 #ifdef INET6
97 #include <netinet6/esp6.h>
98 #endif
99 #endif
100 #include <netinet6/ipcomp.h>
101 #ifdef INET6
102 #include <netinet6/ipcomp6.h>
103 #endif
104
105 #include <machine/stdarg.h>
106
107 /* randomness */
108 #include <sys/random.h>
109
110 #include <net/net_osdep.h>
111
112 #ifndef satosin
113 #define satosin(s) ((struct sockaddr_in *)s)
114 #endif
115
116 #define FULLMASK        0xff
117
118 /*
119  * Note on SA reference counting:
120  * - SAs that are not in DEAD state will have (total external reference + 1)
121  *   following value in reference count field.  they cannot be freed and are
122  *   referenced from SA header.
123  * - SAs that are in DEAD state will have (total external reference)
124  *   in reference count field.  they are ready to be freed.  reference from
125  *   SA header will be removed in key_delsav(), when the reference count
126  *   field hits 0 (= no external reference other than from SA header.
127  */
128
129 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                 TAILQ_FOREACH(ia, &in_ifaddrhead, ia_link) {
3805                         if (sin->sin_family == ia->ia_addr.sin_family &&
3806                             sin->sin_len == ia->ia_addr.sin_len &&
3807                             sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3808                         {
3809                                 return 1;
3810                         }
3811                 }
3812                 break;
3813 #endif
3814 #ifdef INET6
3815         case AF_INET6:
3816                 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3817 #endif
3818         }
3819
3820         return 0;
3821 }
3822
3823 #ifdef INET6
3824 /*
3825  * compare my own address for IPv6.
3826  * 1: ours
3827  * 0: other
3828  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3829  */
3830 #include <netinet6/in6_var.h>
3831
3832 static int
3833 key_ismyaddr6(sin6)
3834         struct sockaddr_in6 *sin6;
3835 {
3836         struct in6_ifaddr *ia;
3837         struct in6_multi *in6m;
3838
3839         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3840                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3841                     (struct sockaddr *)&ia->ia_addr, 0) == 0)
3842                         return 1;
3843
3844                 /*
3845                  * XXX Multicast
3846                  * XXX why do we care about multlicast here while we don't care
3847                  * about IPv4 multicast??
3848                  * XXX scope
3849                  */
3850                 in6m = NULL;
3851                 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3852                 if (in6m)
3853                         return 1;
3854         }
3855
3856         /* loopback, just for safety */
3857         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3858                 return 1;
3859
3860         return 0;
3861 }
3862 #endif /*INET6*/
3863
3864 /*
3865  * compare two secasindex structure.
3866  * flag can specify to compare 2 saidxes.
3867  * compare two secasindex structure without both mode and reqid.
3868  * don't compare port.
3869  * IN:  
3870  *      saidx0: source, it can be in SAD.
3871  *      saidx1: object.
3872  * OUT: 
3873  *      1 : equal
3874  *      0 : not equal
3875  */
3876 static int
3877 key_cmpsaidx(saidx0, saidx1, flag)
3878         struct secasindex *saidx0, *saidx1;
3879         int flag;
3880 {
3881         /* sanity */
3882         if (saidx0 == NULL && saidx1 == NULL)
3883                 return 1;
3884
3885         if (saidx0 == NULL || saidx1 == NULL)
3886                 return 0;
3887
3888         if (saidx0->proto != saidx1->proto)
3889                 return 0;
3890
3891         if (flag == CMP_EXACTLY) {
3892                 if (saidx0->mode != saidx1->mode)
3893                         return 0;
3894                 if (saidx0->reqid != saidx1->reqid)
3895                         return 0;
3896                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.ss_len) != 0 ||
3897                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.ss_len) != 0)
3898                         return 0;
3899         } else {
3900
3901                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3902                 if (flag == CMP_MODE_REQID
3903                   ||flag == CMP_REQID) {
3904                         /*
3905                          * If reqid of SPD is non-zero, unique SA is required.
3906                          * The result must be of same reqid in this case.
3907                          */
3908                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3909                                 return 0;
3910                 }
3911
3912                 if (flag == CMP_MODE_REQID) {
3913                         if (saidx0->mode != IPSEC_MODE_ANY
3914                          && saidx0->mode != saidx1->mode)
3915                                 return 0;
3916                 }
3917
3918                 if (key_sockaddrcmp((struct sockaddr *)&saidx0->src,
3919                                 (struct sockaddr *)&saidx1->src, 0) != 0) {
3920                         return 0;
3921                 }
3922                 if (key_sockaddrcmp((struct sockaddr *)&saidx0->dst,
3923                                 (struct sockaddr *)&saidx1->dst, 0) != 0) {
3924                         return 0;
3925                 }
3926         }
3927
3928         return 1;
3929 }
3930
3931 /*
3932  * compare two secindex structure exactly.
3933  * IN:
3934  *      spidx0: source, it is often in SPD.
3935  *      spidx1: object, it is often from PFKEY message.
3936  * OUT:
3937  *      1 : equal
3938  *      0 : not equal
3939  */
3940 static int
3941 key_cmpspidx_exactly(spidx0, spidx1)
3942         struct secpolicyindex *spidx0, *spidx1;
3943 {
3944         /* sanity */
3945         if (spidx0 == NULL && spidx1 == NULL)
3946                 return 1;
3947
3948         if (spidx0 == NULL || spidx1 == NULL)
3949                 return 0;
3950
3951         if (spidx0->prefs != spidx1->prefs
3952          || spidx0->prefd != spidx1->prefd
3953          || spidx0->ul_proto != spidx1->ul_proto)
3954                 return 0;
3955
3956         if (key_sockaddrcmp((struct sockaddr *)&spidx0->src,
3957             (struct sockaddr *)&spidx1->src, 1) != 0) {
3958                 return 0;
3959         }
3960         if (key_sockaddrcmp((struct sockaddr *)&spidx0->dst,
3961             (struct sockaddr *)&spidx1->dst, 1) != 0) {
3962                 return 0;
3963         }
3964
3965         return 1;
3966 }
3967
3968 /*
3969  * compare two secindex structure with mask.
3970  * IN:
3971  *      spidx0: source, it is often in SPD.
3972  *      spidx1: object, it is often from IP header.
3973  * OUT:
3974  *      1 : equal
3975  *      0 : not equal
3976  */
3977 static int
3978 key_cmpspidx_withmask(spidx0, spidx1)
3979         struct secpolicyindex *spidx0, *spidx1;
3980 {
3981         /* sanity */
3982         if (spidx0 == NULL && spidx1 == NULL)
3983                 return 1;
3984
3985         if (spidx0 == NULL || spidx1 == NULL)
3986                 return 0;
3987
3988         if (spidx0->src.ss_family != spidx1->src.ss_family ||
3989             spidx0->dst.ss_family != spidx1->dst.ss_family ||
3990             spidx0->src.ss_len != spidx1->src.ss_len ||
3991             spidx0->dst.ss_len != spidx1->dst.ss_len)
3992                 return 0;
3993
3994         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3995         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3996          && spidx0->ul_proto != spidx1->ul_proto)
3997                 return 0;
3998
3999         switch (spidx0->src.ss_family) {
4000         case AF_INET:
4001                 if (satosin(&spidx0->src)->sin_port != IPSEC_PORT_ANY
4002                  && satosin(&spidx0->src)->sin_port !=
4003                     satosin(&spidx1->src)->sin_port)
4004                         return 0;
4005                 if (!key_bbcmp((caddr_t)&satosin(&spidx0->src)->sin_addr,
4006                     (caddr_t)&satosin(&spidx1->src)->sin_addr, spidx0->prefs))
4007                         return 0;
4008                 break;
4009         case AF_INET6:
4010                 if (satosin6(&spidx0->src)->sin6_port != IPSEC_PORT_ANY
4011                  && satosin6(&spidx0->src)->sin6_port !=
4012                     satosin6(&spidx1->src)->sin6_port)
4013                         return 0;
4014                 /*
4015                  * scope_id check. if sin6_scope_id is 0, we regard it
4016                  * as a wildcard scope, which matches any scope zone ID. 
4017                  */
4018                 if (satosin6(&spidx0->src)->sin6_scope_id &&
4019                     satosin6(&spidx1->src)->sin6_scope_id &&
4020                     satosin6(&spidx0->src)->sin6_scope_id !=
4021                     satosin6(&spidx1->src)->sin6_scope_id)
4022                         return 0;
4023                 if (!key_bbcmp((caddr_t)&satosin6(&spidx0->src)->sin6_addr,
4024                     (caddr_t)&satosin6(&spidx1->src)->sin6_addr, spidx0->prefs))
4025                         return 0;
4026                 break;
4027         default:
4028                 /* XXX */
4029                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.ss_len) != 0)
4030                         return 0;
4031                 break;
4032         }
4033
4034         switch (spidx0->dst.ss_family) {
4035         case AF_INET:
4036                 if (satosin(&spidx0->dst)->sin_port != IPSEC_PORT_ANY
4037                  && satosin(&spidx0->dst)->sin_port !=
4038                     satosin(&spidx1->dst)->sin_port)
4039                         return 0;
4040                 if (!key_bbcmp((caddr_t)&satosin(&spidx0->dst)->sin_addr,
4041                     (caddr_t)&satosin(&spidx1->dst)->sin_addr, spidx0->prefd))
4042                         return 0;
4043                 break;
4044         case AF_INET6:
4045                 if (satosin6(&spidx0->dst)->sin6_port != IPSEC_PORT_ANY
4046                  && satosin6(&spidx0->dst)->sin6_port !=
4047                     satosin6(&spidx1->dst)->sin6_port)
4048                         return 0;
4049                 /*
4050                  * scope_id check. if sin6_scope_id is 0, we regard it
4051                  * as a wildcard scope, which matches any scope zone ID. 
4052                  */
4053                 if (satosin6(&spidx0->src)->sin6_scope_id &&
4054                     satosin6(&spidx1->src)->sin6_scope_id &&
4055                     satosin6(&spidx0->dst)->sin6_scope_id !=
4056                     satosin6(&spidx1->dst)->sin6_scope_id)
4057                         return 0;
4058                 if (!key_bbcmp((caddr_t)&satosin6(&spidx0->dst)->sin6_addr,
4059                     (caddr_t)&satosin6(&spidx1->dst)->sin6_addr, spidx0->prefd))
4060                         return 0;
4061                 break;
4062         default:
4063                 /* XXX */
4064                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.ss_len) != 0)
4065                         return 0;
4066                 break;
4067         }
4068
4069         /* XXX Do we check other field ?  e.g. flowinfo */
4070
4071         return 1;
4072 }
4073
4074 /* returns 0 on match */
4075 static int
4076 key_sockaddrcmp(sa1, sa2, port)
4077         struct sockaddr *sa1;
4078         struct sockaddr *sa2;
4079         int port;
4080 {
4081         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4082                 return 1;
4083
4084         switch (sa1->sa_family) {
4085         case AF_INET:
4086                 if (sa1->sa_len != sizeof(struct sockaddr_in))
4087                         return 1;
4088                 if (satosin(sa1)->sin_addr.s_addr !=
4089                     satosin(sa2)->sin_addr.s_addr) {
4090                         return 1;
4091                 }
4092                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4093                         return 1;
4094                 break;
4095         case AF_INET6:
4096                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4097                         return 1;       /*EINVAL*/
4098                 if (satosin6(sa1)->sin6_scope_id !=
4099                     satosin6(sa2)->sin6_scope_id) {
4100                         return 1;
4101                 }
4102                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4103                     &satosin6(sa2)->sin6_addr)) {
4104                         return 1;
4105                 }
4106                 if (port &&
4107                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4108                         return 1;
4109                 }
4110         default:
4111                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4112                         return 1;
4113                 break;
4114         }
4115
4116         return 0;
4117 }
4118
4119 /*
4120  * compare two buffers with mask.
4121  * IN:
4122  *      addr1: source
4123  *      addr2: object
4124  *      bits:  Number of bits to compare
4125  * OUT:
4126  *      1 : equal
4127  *      0 : not equal
4128  */
4129 static int
4130 key_bbcmp(p1, p2, bits)
4131         caddr_t p1, p2;
4132         u_int bits;
4133 {
4134         u_int8_t mask;
4135
4136         /* XXX: This could be considerably faster if we compare a word
4137          * at a time, but it is complicated on LSB Endian machines */
4138
4139         /* Handle null pointers */
4140         if (p1 == NULL || p2 == NULL)
4141                 return (p1 == p2);
4142
4143         while (bits >= 8) {
4144                 if (*p1++ != *p2++)
4145                         return 0;
4146                 bits -= 8;
4147         }
4148
4149         if (bits > 0) {
4150                 mask = ~((1<<(8-bits))-1);
4151                 if ((*p1 & mask) != (*p2 & mask))
4152                         return 0;
4153         }
4154         return 1;       /* Match! */
4155 }
4156
4157 /*
4158  * time handler.
4159  * scanning SPD and SAD to check status for each entries,
4160  * and do to remove or to expire.
4161  * XXX: year 2038 problem may remain.
4162  */
4163 void
4164 key_timehandler(void)
4165 {
4166         u_int dir;
4167         int s;
4168         struct timeval tv;
4169
4170         microtime(&tv);
4171
4172         s = splnet();   /*called from softclock()*/
4173
4174         /* SPD */
4175     {
4176         struct secpolicy *sp, *nextsp;
4177
4178         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4179                 for (sp = LIST_FIRST(&sptree[dir]);
4180                      sp != NULL;
4181                      sp = nextsp) {
4182
4183                         nextsp = LIST_NEXT(sp, chain);
4184
4185                         if (sp->state == IPSEC_SPSTATE_DEAD) {
4186                                 key_freesp(sp);
4187                                 continue;
4188                         }
4189
4190                         if (sp->lifetime == 0 && sp->validtime == 0)
4191                                 continue;
4192
4193                         /* the deletion will occur next time */
4194                         if ((sp->lifetime
4195                           && tv.tv_sec - sp->created > sp->lifetime)
4196                          || (sp->validtime
4197                           && tv.tv_sec - sp->lastused > sp->validtime)) {
4198                                 sp->state = IPSEC_SPSTATE_DEAD;
4199                                 key_spdexpire(sp);
4200                                 continue;
4201                         }
4202                 }
4203         }
4204     }
4205
4206         /* SAD */
4207     {
4208         struct secashead *sah, *nextsah;
4209         struct secasvar *sav, *nextsav;
4210
4211         for (sah = LIST_FIRST(&sahtree);
4212              sah != NULL;
4213              sah = nextsah) {
4214
4215                 nextsah = LIST_NEXT(sah, chain);
4216
4217                 /* if sah has been dead, then delete it and process next sah. */
4218                 if (sah->state == SADB_SASTATE_DEAD) {
4219                         key_delsah(sah);
4220                         continue;
4221                 }
4222
4223                 /* if LARVAL entry doesn't become MATURE, delete it. */
4224                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
4225                      sav != NULL;
4226                      sav = nextsav) {
4227
4228                         nextsav = LIST_NEXT(sav, chain);
4229
4230                         if (tv.tv_sec - sav->created > key_larval_lifetime) {
4231                                 key_freesav(sav);
4232                         }
4233                 }
4234
4235                 /*
4236                  * check MATURE entry to start to send expire message
4237                  * whether or not.
4238                  */
4239                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
4240                      sav != NULL;
4241                      sav = nextsav) {
4242
4243                         nextsav = LIST_NEXT(sav, chain);
4244
4245                         /* we don't need to check. */
4246                         if (sav->lft_s == NULL)
4247                                 continue;
4248
4249                         /* sanity check */
4250                         if (sav->lft_c == NULL) {
4251                                 ipseclog((LOG_DEBUG,"key_timehandler: "
4252                                         "There is no CURRENT time, why?\n"));
4253                                 continue;
4254                         }
4255
4256                         /* check SOFT lifetime */
4257                         if (sav->lft_s->sadb_lifetime_addtime != 0
4258                          && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4259                                 /*
4260                                  * check the SA if it has been used.
4261                                  * when it hasn't been used, delete it.
4262                                  * i don't think such SA will be used.
4263                                  */
4264                                 if (sav->lft_c->sadb_lifetime_usetime == 0) {
4265                                         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4266                                         key_freesav(sav);
4267                                         sav = NULL;
4268                                 } else {
4269                                         key_sa_chgstate(sav, SADB_SASTATE_DYING);
4270                                         /*
4271                                          * XXX If we keep to send expire
4272                                          * message in the status of
4273                                          * DYING. Do remove below code.
4274                                          */
4275                                         key_expire(sav);
4276                                 }
4277                         }
4278
4279                         /* check SOFT lifetime by bytes */
4280                         /*
4281                          * XXX I don't know the way to delete this SA
4282                          * when new SA is installed.  Caution when it's
4283                          * installed too big lifetime by time.
4284                          */
4285                         else if (sav->lft_s->sadb_lifetime_bytes != 0
4286                               && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4287
4288                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4289                                 /*
4290                                  * XXX If we keep to send expire
4291                                  * message in the status of
4292                                  * DYING. Do remove below code.
4293                                  */
4294                                 key_expire(sav);
4295                         }
4296                 }
4297
4298                 /* check DYING entry to change status to DEAD. */
4299                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
4300                      sav != NULL;
4301                      sav = nextsav) {
4302
4303                         nextsav = LIST_NEXT(sav, chain);
4304
4305                         /* we don't need to check. */
4306                         if (sav->lft_h == NULL)
4307                                 continue;
4308
4309                         /* sanity check */
4310                         if (sav->lft_c == NULL) {
4311                                 ipseclog((LOG_DEBUG, "key_timehandler: "
4312                                         "There is no CURRENT time, why?\n"));
4313                                 continue;
4314                         }
4315
4316                         if (sav->lft_h->sadb_lifetime_addtime != 0
4317                          && tv.tv_sec - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4318                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4319                                 key_freesav(sav);
4320                                 sav = NULL;
4321                         }
4322 #if 0   /* XXX Should we keep to send expire message until HARD lifetime ? */
4323                         else if (sav->lft_s != NULL
4324                               && sav->lft_s->sadb_lifetime_addtime != 0
4325                               && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4326                                 /*
4327                                  * XXX: should be checked to be
4328                                  * installed the valid SA.
4329                                  */
4330
4331                                 /*
4332                                  * If there is no SA then sending
4333                                  * expire message.
4334                                  */
4335                                 key_expire(sav);
4336                         }
4337 #endif
4338                         /* check HARD lifetime by bytes */
4339                         else if (sav->lft_h->sadb_lifetime_bytes != 0
4340                               && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4341                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4342                                 key_freesav(sav);
4343                                 sav = NULL;
4344                         }
4345                 }
4346
4347                 /* delete entry in DEAD */
4348                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
4349                      sav != NULL;
4350                      sav = nextsav) {
4351
4352                         nextsav = LIST_NEXT(sav, chain);
4353
4354                         /* sanity check */
4355                         if (sav->state != SADB_SASTATE_DEAD) {
4356                                 ipseclog((LOG_DEBUG, "key_timehandler: "
4357                                         "invalid sav->state "
4358                                         "(queue: %d SA: %d): "
4359                                         "kill it anyway\n",
4360                                         SADB_SASTATE_DEAD, sav->state));
4361                         }
4362
4363                         /*
4364                          * do not call key_freesav() here.
4365                          * sav should already be freed, and sav->refcnt
4366                          * shows other references to sav
4367                          * (such as from SPD).
4368                          */
4369                 }
4370         }
4371     }
4372
4373 #ifndef IPSEC_NONBLOCK_ACQUIRE
4374         /* ACQ tree */
4375     {
4376         struct secacq *acq, *nextacq;
4377
4378         for (acq = LIST_FIRST(&acqtree);
4379              acq != NULL;
4380              acq = nextacq) {
4381
4382                 nextacq = LIST_NEXT(acq, chain);
4383
4384                 if (tv.tv_sec - acq->created > key_blockacq_lifetime
4385                  && __LIST_CHAINED(acq)) {
4386                         LIST_REMOVE(acq, chain);
4387                         KFREE(acq);
4388                 }
4389         }
4390     }
4391 #endif
4392
4393         /* SP ACQ tree */
4394     {
4395         struct secspacq *acq, *nextacq;
4396
4397         for (acq = LIST_FIRST(&spacqtree);
4398              acq != NULL;
4399              acq = nextacq) {
4400
4401                 nextacq = LIST_NEXT(acq, chain);
4402
4403                 if (tv.tv_sec - acq->created > key_blockacq_lifetime
4404                  && __LIST_CHAINED(acq)) {
4405                         LIST_REMOVE(acq, chain);
4406                         KFREE(acq);
4407                 }
4408         }
4409     }
4410
4411         /* initialize random seed */
4412         if (key_tick_init_random++ > key_int_random) {
4413                 key_tick_init_random = 0;
4414                 key_srandom();
4415         }
4416
4417 #ifndef IPSEC_DEBUG2
4418         /* do exchange to tick time !! */
4419         (void)timeout((void *)key_timehandler, (void *)0, hz);
4420 #endif /* IPSEC_DEBUG2 */
4421
4422         splx(s);
4423         return;
4424 }
4425
4426 /*
4427  * to initialize a seed for random()
4428  */
4429 static void
4430 key_srandom()
4431 {
4432         struct timeval tv;
4433
4434         microtime(&tv);
4435
4436         srandom(tv.tv_usec);
4437
4438         return;
4439 }
4440
4441 u_long
4442 key_random()
4443 {
4444         u_long value;
4445
4446         key_randomfill(&value, sizeof(value));
4447         return value;
4448 }
4449
4450 void
4451 key_randomfill(p, l)
4452         void *p;
4453         size_t l;
4454 {
4455         size_t n;
4456         u_long v;
4457         static int warn = 1;
4458
4459         n = 0;
4460         n = (size_t)read_random(p, (u_int)l);
4461         /* last resort */
4462         while (n < l) {
4463                 v = random();
4464                 bcopy(&v, (u_int8_t *)p + n,
4465                     l - n < sizeof(v) ? l - n : sizeof(v));
4466                 n += sizeof(v);
4467
4468                 if (warn) {
4469                         printf("WARNING: pseudo-random number generator "
4470                             "used for IPsec processing\n");
4471                         warn = 0;
4472                 }
4473         }
4474 }
4475
4476 /*
4477  * map SADB_SATYPE_* to IPPROTO_*.
4478  * if satype == SADB_SATYPE then satype is mapped to ~0.
4479  * OUT:
4480  *      0: invalid satype.
4481  */
4482 static u_int16_t
4483 key_satype2proto(satype)
4484         u_int8_t satype;
4485 {
4486         switch (satype) {
4487         case SADB_SATYPE_UNSPEC:
4488                 return IPSEC_PROTO_ANY;
4489         case SADB_SATYPE_AH:
4490                 return IPPROTO_AH;
4491         case SADB_SATYPE_ESP:
4492                 return IPPROTO_ESP;
4493         case SADB_X_SATYPE_IPCOMP:
4494                 return IPPROTO_IPCOMP;
4495                 break;
4496         default:
4497                 return 0;
4498         }
4499         /* NOTREACHED */
4500 }
4501
4502 /*
4503  * map IPPROTO_* to SADB_SATYPE_*
4504  * OUT:
4505  *      0: invalid protocol type.
4506  */
4507 static u_int8_t
4508 key_proto2satype(proto)
4509         u_int16_t proto;
4510 {
4511         switch (proto) {
4512         case IPPROTO_AH:
4513                 return SADB_SATYPE_AH;
4514         case IPPROTO_ESP:
4515                 return SADB_SATYPE_ESP;
4516         case IPPROTO_IPCOMP:
4517                 return SADB_X_SATYPE_IPCOMP;
4518                 break;
4519         default:
4520                 return 0;
4521         }
4522         /* NOTREACHED */
4523 }
4524
4525 /* %%% PF_KEY */
4526 /*
4527  * SADB_GETSPI processing is to receive
4528  *      <base, (SA2), src address, dst address, (SPI range)>
4529  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4530  * tree with the status of LARVAL, and send
4531  *      <base, SA(*), address(SD)>
4532  * to the IKMPd.
4533  *
4534  * IN:  mhp: pointer to the pointer to each header.
4535  * OUT: NULL if fail.
4536  *      other if success, return pointer to the message to send.
4537  */
4538 static int
4539 key_getspi(so, m, mhp)
4540         struct socket *so;
4541         struct mbuf *m;
4542         const struct sadb_msghdr *mhp;
4543 {
4544         struct sadb_address *src0, *dst0;
4545         struct secasindex saidx;
4546         struct secashead *newsah;
4547         struct secasvar *newsav;
4548         u_int8_t proto;
4549         u_int32_t spi;
4550         u_int8_t mode;
4551         u_int32_t reqid;
4552         int error;
4553
4554         /* sanity check */
4555         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4556                 panic("key_getspi: NULL pointer is passed.\n");
4557
4558         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4559             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4560                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4561                 return key_senderror(so, m, EINVAL);
4562         }
4563         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4564             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4565                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4566                 return key_senderror(so, m, EINVAL);
4567         }
4568         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4569                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4570                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4571         } else {
4572                 mode = IPSEC_MODE_ANY;
4573                 reqid = 0;
4574         }
4575
4576         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4577         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4578
4579         /* map satype to proto */
4580         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4581                 ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
4582                 return key_senderror(so, m, EINVAL);
4583         }
4584
4585         /* make sure if port number is zero. */
4586         switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4587         case AF_INET:
4588                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4589                     sizeof(struct sockaddr_in))
4590                         return key_senderror(so, m, EINVAL);
4591                 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4592                 break;
4593         case AF_INET6:
4594                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4595                     sizeof(struct sockaddr_in6))
4596                         return key_senderror(so, m, EINVAL);
4597                 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4598                 break;
4599         default:
4600                 ; /*???*/
4601         }
4602         switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4603         case AF_INET:
4604                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4605                     sizeof(struct sockaddr_in))
4606                         return key_senderror(so, m, EINVAL);
4607                 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4608                 break;
4609         case AF_INET6:
4610                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4611                     sizeof(struct sockaddr_in6))
4612                         return key_senderror(so, m, EINVAL);
4613                 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4614                 break;
4615         default:
4616                 ; /*???*/
4617         }
4618
4619         /* XXX boundary check against sa_len */
4620         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4621
4622         /* SPI allocation */
4623         spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4624                                &saidx);
4625         if (spi == 0)
4626                 return key_senderror(so, m, EINVAL);
4627
4628         /* get a SA index */
4629         if ((newsah = key_getsah(&saidx)) == NULL) {
4630                 /* create a new SA index */
4631                 if ((newsah = key_newsah(&saidx)) == NULL) {
4632                         ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
4633                         return key_senderror(so, m, ENOBUFS);
4634                 }
4635         }
4636
4637         /* get a new SA */
4638         /* XXX rewrite */
4639         newsav = key_newsav(m, mhp, newsah, &error);
4640         if (newsav == NULL) {
4641                 /* XXX don't free new SA index allocated in above. */
4642                 return key_senderror(so, m, error);
4643         }
4644
4645         /* set spi */
4646         newsav->spi = htonl(spi);
4647
4648 #ifndef IPSEC_NONBLOCK_ACQUIRE
4649         /* delete the entry in acqtree */
4650         if (mhp->msg->sadb_msg_seq != 0) {
4651                 struct secacq *acq;
4652                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4653                         /* reset counter in order to deletion by timehandler. */
4654                         struct timeval tv;
4655                         microtime(&tv);
4656                         acq->created = tv.tv_sec;
4657                         acq->count = 0;
4658                 }
4659         }
4660 #endif
4661
4662     {
4663         struct mbuf *n, *nn;
4664         struct sadb_sa *m_sa;
4665         struct sadb_msg *newmsg;
4666         int off, len;
4667
4668         /* create new sadb_msg to reply. */
4669         len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4670             PFKEY_ALIGN8(sizeof(struct sadb_sa));
4671         if (len > MCLBYTES)
4672                 return key_senderror(so, m, ENOBUFS);
4673
4674         MGETHDR(n, MB_DONTWAIT, MT_DATA);
4675         if (len > MHLEN) {
4676                 MCLGET(n, MB_DONTWAIT);
4677                 if ((n->m_flags & M_EXT) == 0) {
4678                         m_freem(n);
4679                         n = NULL;
4680                 }
4681         }
4682         if (!n)
4683                 return key_senderror(so, m, ENOBUFS);
4684
4685         n->m_len = len;
4686         n->m_next = NULL;
4687         off = 0;
4688
4689         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4690         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4691
4692         m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4693         m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4694         m_sa->sadb_sa_exttype = SADB_EXT_SA;
4695         m_sa->sadb_sa_spi = htonl(spi);
4696         off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4697
4698 #ifdef DIAGNOSTIC
4699         if (off != len)
4700                 panic("length inconsistency in key_getspi");
4701 #endif
4702
4703         n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4704             SADB_EXT_ADDRESS_DST);
4705         if (!n->m_next) {
4706                 m_freem(n);
4707                 return key_senderror(so, m, ENOBUFS);
4708         }
4709
4710         if (n->m_len < sizeof(struct sadb_msg)) {
4711                 n = m_pullup(n, sizeof(struct sadb_msg));
4712                 if (n == NULL)
4713                         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4714         }
4715
4716         n->m_pkthdr.len = 0;
4717         for (nn = n; nn; nn = nn->m_next)
4718                 n->m_pkthdr.len += nn->m_len;
4719
4720         newmsg = mtod(n, struct sadb_msg *);
4721         newmsg->sadb_msg_seq = newsav->seq;
4722         newmsg->sadb_msg_errno = 0;
4723         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4724
4725         m_freem(m);
4726         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4727     }
4728 }
4729
4730 /*
4731  * allocating new SPI
4732  * called by key_getspi().
4733  * OUT:
4734  *      0:      failure.
4735  *      others: success.
4736  */
4737 static u_int32_t
4738 key_do_getnewspi(spirange, saidx)
4739         struct sadb_spirange *spirange;
4740         struct secasindex *saidx;
4741 {
4742         u_int32_t newspi;
4743         u_int32_t min, max;
4744         int count = key_spi_trycnt;
4745
4746         /* set spi range to allocate */
4747         if (spirange != NULL) {
4748                 min = spirange->sadb_spirange_min;
4749                 max = spirange->sadb_spirange_max;
4750         } else {
4751                 min = key_spi_minval;
4752                 max = key_spi_maxval;
4753         }
4754         /* IPCOMP needs 2-byte SPI */
4755         if (saidx->proto == IPPROTO_IPCOMP) {
4756                 u_int32_t t;
4757                 if (min >= 0x10000)
4758                         min = 0xffff;
4759                 if (max >= 0x10000)
4760                         max = 0xffff;
4761                 if (min > max) {
4762                         t = min; min = max; max = t;
4763                 }
4764         }
4765
4766         if (min == max) {
4767                 if (key_checkspidup(saidx, min) != NULL) {
4768                         ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
4769                         return 0;
4770                 }
4771
4772                 count--; /* taking one cost. */
4773                 newspi = min;
4774
4775         } else {
4776
4777                 /* init SPI */
4778                 newspi = 0;
4779
4780                 /* when requesting to allocate spi ranged */
4781                 while (count--) {
4782                         /* generate pseudo-random SPI value ranged. */
4783                         newspi = min + (key_random() % (max - min + 1));
4784
4785                         if (key_checkspidup(saidx, newspi) == NULL)
4786                                 break;
4787                 }
4788
4789                 if (count == 0 || newspi == 0) {
4790                         ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
4791                         return 0;
4792                 }
4793         }
4794
4795         /* statistics */
4796         keystat.getspi_count =
4797                 (keystat.getspi_count + key_spi_trycnt - count) / 2;
4798
4799         return newspi;
4800 }
4801
4802 /*
4803  * SADB_UPDATE processing
4804  * receive
4805  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4806  *       key(AE), (identity(SD),) (sensitivity)>
4807  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4808  * and send
4809  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4810  *       (identity(SD),) (sensitivity)>
4811  * to the ikmpd.
4812  *
4813  * m will always be freed.
4814  */
4815 static int
4816 key_update(so, m, mhp)
4817         struct socket *so;
4818         struct mbuf *m;
4819         const struct sadb_msghdr *mhp;
4820 {
4821         struct sadb_sa *sa0;
4822         struct sadb_address *src0, *dst0;
4823         struct secasindex saidx;
4824         struct secashead *sah;
4825         struct secasvar *sav;
4826         u_int16_t proto;
4827         u_int8_t mode;
4828         u_int32_t reqid;
4829         int error;
4830
4831         /* sanity check */
4832         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4833                 panic("key_update: NULL pointer is passed.\n");
4834
4835         /* map satype to proto */
4836         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4837                 ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
4838                 return key_senderror(so, m, EINVAL);
4839         }
4840
4841         if (mhp->ext[SADB_EXT_SA] == NULL ||
4842             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4843             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4844             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4845              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4846             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4847              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4848             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4849              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4850             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4851              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4852                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4853                 return key_senderror(so, m, EINVAL);
4854         }
4855         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4856             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4857             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4858                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4859                 return key_senderror(so, m, EINVAL);
4860         }
4861         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4862                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4863                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4864         } else {
4865                 mode = IPSEC_MODE_ANY;
4866                 reqid = 0;
4867         }
4868         /* XXX boundary checking for other extensions */
4869
4870         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4871         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4872         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4873
4874         /* XXX boundary check against sa_len */
4875         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4876
4877         /* get a SA header */
4878         if ((sah = key_getsah(&saidx)) == NULL) {
4879                 ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
4880                 return key_senderror(so, m, ENOENT);
4881         }
4882
4883         /* set spidx if there */
4884         /* XXX rewrite */
4885         error = key_setident(sah, m, mhp);
4886         if (error)
4887                 return key_senderror(so, m, error);
4888
4889         /* find a SA with sequence number. */
4890 #ifdef IPSEC_DOSEQCHECK
4891         if (mhp->msg->sadb_msg_seq != 0
4892          && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4893                 ipseclog((LOG_DEBUG,
4894                     "key_update: no larval SA with sequence %u exists.\n",
4895                     mhp->msg->sadb_msg_seq));
4896                 return key_senderror(so, m, ENOENT);
4897         }
4898 #else
4899         if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
4900                 ipseclog((LOG_DEBUG,
4901                     "key_update: no such a SA found (spi:%u)\n",
4902                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4903                 return key_senderror(so, m, EINVAL);
4904         }
4905 #endif
4906
4907         /* validity check */
4908         if (sav->sah->saidx.proto != proto) {
4909                 ipseclog((LOG_DEBUG,
4910                     "key_update: protocol mismatched (DB=%u param=%u)\n",
4911                     sav->sah->saidx.proto, proto));
4912                 return key_senderror(so, m, EINVAL);
4913         }
4914 #ifdef IPSEC_DOSEQCHECK
4915         if (sav->spi != sa0->sadb_sa_spi) {
4916                 ipseclog((LOG_DEBUG,
4917                     "key_update: SPI mismatched (DB:%u param:%u)\n",
4918                     (u_int32_t)ntohl(sav->spi),
4919                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4920                 return key_senderror(so, m, EINVAL);
4921         }
4922 #endif
4923         if (sav->pid != mhp->msg->sadb_msg_pid) {
4924                 ipseclog((LOG_DEBUG,
4925                     "key_update: pid mismatched (DB:%u param:%u)\n",
4926                     sav->pid, mhp->msg->sadb_msg_pid));
4927                 return key_senderror(so, m, EINVAL);
4928         }
4929
4930         /* copy sav values */
4931         error = key_setsaval(sav, m, mhp);
4932         if (error) {
4933                 key_freesav(sav);
4934                 return key_senderror(so, m, error);
4935         }
4936
4937         /* check SA values to be mature. */
4938         if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4939                 key_freesav(sav);
4940                 return key_senderror(so, m, 0);
4941         }
4942
4943     {
4944         struct mbuf *n;
4945
4946         /* set msg buf from mhp */
4947         n = key_getmsgbuf_x1(m, mhp);
4948         if (n == NULL) {
4949                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4950                 return key_senderror(so, m, ENOBUFS);
4951         }
4952
4953         m_freem(m);
4954         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4955     }
4956 }
4957
4958 /*
4959  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4960  * only called by key_update().
4961  * OUT:
4962  *      NULL    : not found
4963  *      others  : found, pointer to a SA.
4964  */
4965 #ifdef IPSEC_DOSEQCHECK
4966 static struct secasvar *
4967 key_getsavbyseq(sah, seq)
4968         struct secashead *sah;
4969         u_int32_t seq;
4970 {
4971         struct secasvar *sav;
4972         u_int state;
4973
4974         state = SADB_SASTATE_LARVAL;
4975
4976         /* search SAD with sequence number ? */
4977         LIST_FOREACH(sav, &sah->savtree[state], chain) {
4978
4979                 KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
4980
4981                 if (sav->seq == seq) {
4982                         sav->refcnt++;
4983                         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4984                                 printf("DP key_getsavbyseq cause "
4985                                         "refcnt++:%d SA:%p\n",
4986                                         sav->refcnt, sav));
4987                         return sav;
4988                 }
4989         }
4990
4991         return NULL;
4992 }
4993 #endif
4994
4995 /*
4996  * SADB_ADD processing
4997  * add a entry to SA database, when received
4998  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4999  *       key(AE), (identity(SD),) (sensitivity)>
5000  * from the ikmpd,
5001  * and send
5002  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5003  *       (identity(SD),) (sensitivity)>
5004  * to the ikmpd.
5005  *
5006  * IGNORE identity and sensitivity messages.
5007  *
5008  * m will always be freed.
5009  */
5010 static int
5011 key_add(so, m, mhp)
5012         struct socket *so;
5013         struct mbuf *m;
5014         const struct sadb_msghdr *mhp;
5015 {
5016         struct sadb_sa *sa0;
5017         struct sadb_address *src0, *dst0;
5018         struct secasindex saidx;
5019         struct secashead *newsah;
5020         struct secasvar *newsav;
5021         u_int16_t proto;
5022         u_int8_t mode;
5023         u_int32_t reqid;
5024         int error;
5025
5026         /* sanity check */
5027         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5028                 panic("key_add: NULL pointer is passed.\n");
5029
5030         /* map satype to proto */
5031         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5032                 ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
5033                 return key_senderror(so, m, EINVAL);
5034         }
5035
5036         if (mhp->ext[SADB_EXT_SA] == NULL ||
5037             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5038             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5039             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5040              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5041             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5042              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5043             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5044              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5045             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5046              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5047                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
5048                 return key_senderror(so, m, EINVAL);
5049         }
5050         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5051             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5052             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5053                 /* XXX need more */
5054                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
5055                 return key_senderror(so, m, EINVAL);
5056         }
5057         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5058                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5059                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5060         } else {
5061                 mode = IPSEC_MODE_ANY;
5062                 reqid = 0;
5063         }
5064
5065         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5066         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5067         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5068
5069         /* XXX boundary check against sa_len */
5070         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5071
5072         /* get a SA header */
5073         if ((newsah = key_getsah(&saidx)) == NULL) {
5074                 /* create a new SA header */
5075                 if ((newsah = key_newsah(&saidx)) == NULL) {
5076                         ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
5077                         return key_senderror(so, m, ENOBUFS);
5078                 }
5079         }
5080
5081         /* set spidx if there */
5082         /* XXX rewrite */
5083         error = key_setident(newsah, m, mhp);
5084         if (error) {
5085                 return key_senderror(so, m, error);
5086         }
5087
5088         /* create new SA entry. */
5089         /* We can create new SA only if SPI is differenct. */
5090         if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
5091                 ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
5092                 return key_senderror(so, m, EEXIST);
5093         }
5094         newsav = key_newsav(m, mhp, newsah, &error);
5095         if (newsav == NULL) {
5096                 return key_senderror(so, m, error);
5097         }
5098
5099         /* check SA values to be mature. */
5100         if ((error = key_mature(newsav)) != 0) {
5101                 key_freesav(newsav);
5102                 return key_senderror(so, m, error);
5103         }
5104
5105         /*
5106          * don't call key_freesav() here, as we would like to keep the SA
5107          * in the database on success.
5108          */
5109
5110     {
5111         struct mbuf *n;
5112
5113         /* set msg buf from mhp */
5114         n = key_getmsgbuf_x1(m, mhp);
5115         if (n == NULL) {
5116                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
5117                 return key_senderror(so, m, ENOBUFS);
5118         }
5119
5120         m_freem(m);
5121         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5122     }
5123 }
5124
5125 /* m is retained */
5126 static int
5127 key_setident(sah, m, mhp)
5128         struct secashead *sah;
5129         struct mbuf *m;
5130         const struct sadb_msghdr *mhp;
5131 {
5132         const struct sadb_ident *idsrc, *iddst;
5133         int idsrclen, iddstlen;
5134
5135         /* sanity check */
5136         if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5137                 panic("key_setident: NULL pointer is passed.\n");
5138
5139         /* don't make buffer if not there */
5140         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5141             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5142                 sah->idents = NULL;
5143                 sah->identd = NULL;
5144                 return 0;
5145         }
5146         
5147         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5148             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5149                 ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
5150                 return EINVAL;
5151         }
5152
5153         idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5154         iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5155         idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5156         iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5157
5158         /* validity check */
5159         if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5160                 ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
5161                 return EINVAL;
5162         }
5163
5164         switch (idsrc->sadb_ident_type) {
5165         case SADB_IDENTTYPE_PREFIX:
5166         case SADB_IDENTTYPE_FQDN:
5167         case SADB_IDENTTYPE_USERFQDN:
5168         default:
5169                 /* XXX do nothing */
5170                 sah->idents = NULL;
5171                 sah->identd = NULL;
5172                 return 0;
5173         }
5174
5175         /* make structure */
5176         KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
5177         if (sah->idents == NULL) {
5178                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5179                 return ENOBUFS;
5180         }
5181         KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
5182         if (sah->identd == NULL) {
5183                 KFREE(sah->idents);
5184                 sah->idents = NULL;
5185                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5186                 return ENOBUFS;
5187         }
5188         bcopy(idsrc, sah->idents, idsrclen);
5189         bcopy(iddst, sah->identd, iddstlen);
5190
5191         return 0;
5192 }
5193
5194 /*
5195  * m will not be freed on return.
5196  * it is caller's responsibility to free the result. 
5197  */
5198 static struct mbuf *
5199 key_getmsgbuf_x1(m, mhp)
5200         struct mbuf *m;
5201         const struct sadb_msghdr *mhp;
5202 {
5203         struct mbuf *n;
5204
5205         /* sanity check */
5206         if (m == NULL || mhp == NULL || mhp->msg == NULL)
5207                 panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
5208
5209         /* create new sadb_msg to reply. */
5210         n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5211             SADB_EXT_SA, SADB_X_EXT_SA2,
5212             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5213             SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5214             SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5215         if (!n)
5216                 return NULL;
5217
5218         if (n->m_len < sizeof(struct sadb_msg)) {
5219                 n = m_pullup(n, sizeof(struct sadb_msg));
5220                 if (n == NULL)
5221                         return NULL;
5222         }
5223         mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5224         mtod(n, struct sadb_msg *)->sadb_msg_len =
5225             PFKEY_UNIT64(n->m_pkthdr.len);
5226
5227         return n;
5228 }
5229
5230 static int key_delete_all (struct socket *, struct mbuf *,
5231         const struct sadb_msghdr *, u_int16_t);
5232
5233 /*
5234  * SADB_DELETE processing
5235  * receive
5236  *   <base, SA(*), address(SD)>
5237  * from the ikmpd, and set SADB_SASTATE_DEAD,
5238  * and send,
5239  *   <base, SA(*), address(SD)>
5240  * to the ikmpd.
5241  *
5242  * m will always be freed.
5243  */
5244 static int
5245 key_delete(so, m, mhp)
5246         struct socket *so;
5247         struct mbuf *m;
5248         const struct sadb_msghdr *mhp;
5249 {
5250         struct sadb_sa *sa0;
5251         struct sadb_address *src0, *dst0;
5252         struct secasindex saidx;
5253         struct secashead *sah;
5254         struct secasvar *sav = NULL;
5255         u_int16_t proto;
5256
5257         /* sanity check */
5258         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5259                 panic("key_delete: NULL pointer is passed.\n");
5260
5261         /* map satype to proto */
5262         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5263                 ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
5264                 return key_senderror(so, m, EINVAL);
5265         }
5266
5267         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5268             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5269                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5270                 return key_senderror(so, m, EINVAL);
5271         }
5272
5273         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5274             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5275                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5276                 return key_senderror(so, m, EINVAL);
5277         }
5278
5279         if (mhp->ext[SADB_EXT_SA] == NULL) {
5280                 /*
5281                  * Caller wants us to delete all non-LARVAL SAs
5282                  * that match the src/dst.  This is used during
5283                  * IKE INITIAL-CONTACT.
5284                  */
5285                 ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
5286                 return key_delete_all(so, m, mhp, proto);
5287         } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5288                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5289                 return key_senderror(so, m, EINVAL);
5290         }
5291
5292         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5293         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5294         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5295
5296         /* XXX boundary check against sa_len */
5297         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5298
5299         /* get a SA header */
5300         LIST_FOREACH(sah, &sahtree, chain) {
5301                 if (sah->state == SADB_SASTATE_DEAD)
5302                         continue;
5303                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5304                         continue;
5305
5306                 /* get a SA with SPI. */
5307                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5308                 if (sav)
5309                         break;
5310         }
5311         if (sah == NULL) {
5312                 ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
5313                 return key_senderror(so, m, ENOENT);
5314         }
5315
5316         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5317         key_freesav(sav);
5318         sav = NULL;
5319
5320     {
5321         struct mbuf *n;
5322         struct sadb_msg *newmsg;
5323
5324         /* create new sadb_msg to reply. */
5325         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5326             SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5327         if (!n)
5328                 return key_senderror(so, m, ENOBUFS);
5329
5330         if (n->m_len < sizeof(struct sadb_msg)) {
5331                 n = m_pullup(n, sizeof(struct sadb_msg));
5332                 if (n == NULL)
5333                         return key_senderror(so, m, ENOBUFS);
5334         }
5335         newmsg = mtod(n, struct sadb_msg *);
5336         newmsg->sadb_msg_errno = 0;
5337         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5338
5339         m_freem(m);
5340         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5341     }
5342 }
5343
5344 /*
5345  * delete all SAs for src/dst.  Called from key_delete().
5346  */
5347 static int
5348 key_delete_all(so, m, mhp, proto)
5349         struct socket *so;
5350         struct mbuf *m;
5351         const struct sadb_msghdr *mhp;
5352         u_int16_t proto;
5353 {
5354         struct sadb_address *src0, *dst0;
5355         struct secasindex saidx;
5356         struct secashead *sah;
5357         struct secasvar *sav, *nextsav;
5358         u_int stateidx, state;
5359
5360         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5361         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5362
5363         /* XXX boundary check against sa_len */
5364         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5365
5366         LIST_FOREACH(sah, &sahtree, chain) {
5367                 if (sah->state == SADB_SASTATE_DEAD)
5368                         continue;
5369                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5370                         continue;
5371
5372                 /* Delete all non-LARVAL SAs. */
5373                 for (stateidx = 0;
5374                      stateidx < _ARRAYLEN(saorder_state_alive);
5375                      stateidx++) {
5376                         state = saorder_state_alive[stateidx];
5377                         if (state == SADB_SASTATE_LARVAL)
5378                                 continue;
5379                         for (sav = LIST_FIRST(&sah->savtree[state]);
5380                              sav != NULL; sav = nextsav) {
5381                                 nextsav = LIST_NEXT(sav, chain);
5382                                 /* sanity check */
5383                                 if (sav->state != state) {
5384                                         ipseclog((LOG_DEBUG, "key_delete_all: "
5385                                                "invalid sav->state "
5386                                                "(queue: %d SA: %d)\n",
5387                                                state, sav->state));
5388                                         continue;
5389                                 }
5390                                 
5391                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5392                                 key_freesav(sav);
5393                         }
5394                 }
5395         }
5396     {
5397         struct mbuf *n;
5398         struct sadb_msg *newmsg;
5399
5400         /* create new sadb_msg to reply. */
5401         n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5402             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5403         if (!n)
5404                 return key_senderror(so, m, ENOBUFS);
5405
5406         if (n->m_len < sizeof(struct sadb_msg)) {
5407                 n = m_pullup(n, sizeof(struct sadb_msg));
5408                 if (n == NULL)
5409                         return key_senderror(so, m, ENOBUFS);
5410         }
5411         newmsg = mtod(n, struct sadb_msg *);
5412         newmsg->sadb_msg_errno = 0;
5413         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5414
5415         m_freem(m);
5416         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5417     }
5418 }
5419
5420 /*
5421  * SADB_GET processing
5422  * receive
5423  *   <base, SA(*), address(SD)>
5424  * from the ikmpd, and get a SP and a SA to respond,
5425  * and send,
5426  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5427  *       (identity(SD),) (sensitivity)>
5428  * to the ikmpd.
5429  *
5430  * m will always be freed.
5431  */
5432 static int
5433 key_get(so, m, mhp)
5434         struct socket *so;
5435         struct mbuf *m;
5436         const struct sadb_msghdr *mhp;
5437 {
5438         struct sadb_sa *sa0;
5439         struct sadb_address *src0, *dst0;
5440         struct secasindex saidx;
5441         struct secashead *sah;
5442         struct secasvar *sav = NULL;
5443         u_int16_t proto;
5444
5445         /* sanity check */
5446         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5447                 panic("key_get: NULL pointer is passed.\n");
5448
5449         /* map satype to proto */
5450         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5451                 ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
5452                 return key_senderror(so, m, EINVAL);
5453         }
5454
5455         if (mhp->ext[SADB_EXT_SA] == NULL ||
5456             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5457             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5458                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5459                 return key_senderror(so, m, EINVAL);
5460         }
5461         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5462             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5463             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5464                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5465                 return key_senderror(so, m, EINVAL);
5466         }
5467
5468         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5469         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5470         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5471
5472         /* XXX boundary check against sa_len */
5473         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5474
5475         /* get a SA header */
5476         LIST_FOREACH(sah, &sahtree, chain) {
5477                 if (sah->state == SADB_SASTATE_DEAD)
5478                         continue;
5479                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5480                         continue;
5481
5482                 /* get a SA with SPI. */
5483                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5484                 if (sav)
5485                         break;
5486         }
5487         if (sah == NULL) {
5488                 ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5489                 return key_senderror(so, m, ENOENT);
5490         }
5491
5492     {
5493         struct mbuf *n;
5494         u_int8_t satype;
5495
5496         /* map proto to satype */
5497         if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5498                 ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5499                 return key_senderror(so, m, EINVAL);
5500         }
5501
5502         /* create new sadb_msg to reply. */
5503         n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5504             mhp->msg->sadb_msg_pid);
5505         if (!n)
5506                 return key_senderror(so, m, ENOBUFS);
5507
5508         m_freem(m);
5509         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5510     }
5511 }
5512
5513 /* XXX make it sysctl-configurable? */
5514 static void
5515 key_getcomb_setlifetime(comb)
5516         struct sadb_comb *comb;
5517 {
5518
5519         comb->sadb_comb_soft_allocations = 1;
5520         comb->sadb_comb_hard_allocations = 1;
5521         comb->sadb_comb_soft_bytes = 0;
5522         comb->sadb_comb_hard_bytes = 0;
5523         comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
5524         comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5525         comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
5526         comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5527 }
5528
5529 #ifdef IPSEC_ESP
5530 /*
5531  * XXX reorder combinations by preference
5532  * XXX no idea if the user wants ESP authentication or not
5533  */
5534 static struct mbuf *
5535 key_getcomb_esp()
5536 {
5537         struct sadb_comb *comb;
5538         const struct esp_algorithm *algo;
5539         struct mbuf *result = NULL, *m, *n;
5540         int encmin;
5541         int i, off, o;
5542         int totlen;
5543         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5544
5545         m = NULL;
5546         for (i = 1; i <= SADB_EALG_MAX; i++) {
5547                 algo = esp_algorithm_lookup(i);
5548                 if (!algo)
5549                         continue;
5550
5551                 if (algo->keymax < ipsec_esp_keymin)
5552                         continue;
5553                 if (algo->keymin < ipsec_esp_keymin)
5554                         encmin = ipsec_esp_keymin;
5555                 else
5556                         encmin = algo->keymin;
5557
5558                 if (ipsec_esp_auth)
5559                         m = key_getcomb_ah();
5560                 else {
5561 #ifdef DIAGNOSTIC
5562                         if (l > MLEN)
5563                                 panic("assumption failed in key_getcomb_esp");
5564 #endif
5565                         MGET(m, MB_DONTWAIT, MT_DATA);
5566                         if (m) {
5567                                 M_ALIGN(m, l);
5568                                 m->m_len = l;
5569                                 m->m_next = NULL;
5570                                 bzero(mtod(m, caddr_t), m->m_len);
5571                         }
5572                 }
5573                 if (!m)
5574                         goto fail;
5575
5576                 totlen = 0;
5577                 for (n = m; n; n = n->m_next)
5578                         totlen += n->m_len;
5579 #ifdef DIAGNOSTIC
5580                 if (totlen % l)
5581                         panic("assumption failed in key_getcomb_esp");
5582 #endif
5583
5584                 for (off = 0; off < totlen; off += l) {
5585                         n = m_pulldown(m, off, l, &o);
5586                         if (!n) {
5587                                 /* m is already freed */
5588                                 goto fail;
5589                         }
5590                         comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5591                         bzero(comb, sizeof(*comb));
5592                         key_getcomb_setlifetime(comb);
5593                         comb->sadb_comb_encrypt = i;
5594                         comb->sadb_comb_encrypt_minbits = encmin;
5595                         comb->sadb_comb_encrypt_maxbits = algo->keymax;
5596                 }
5597
5598                 if (!result)
5599                         result = m;
5600                 else
5601                         m_cat(result, m);
5602         }
5603
5604         return result;
5605
5606  fail:
5607         if (result)
5608                 m_freem(result);
5609         return NULL;
5610 }
5611 #endif
5612
5613 /*
5614  * XXX reorder combinations by preference
5615  */
5616 static struct mbuf *
5617 key_getcomb_ah()
5618 {
5619         struct sadb_comb *comb;
5620         const struct ah_algorithm *algo;
5621         struct mbuf *m;
5622         int min;
5623         int i;
5624         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5625
5626         m = NULL;
5627         for (i = 1; i <= SADB_AALG_MAX; i++) {
5628 #if 1
5629                 /* we prefer HMAC algorithms, not old algorithms */
5630                 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5631                         continue;
5632 #endif
5633                 algo = ah_algorithm_lookup(i);
5634                 if (!algo)
5635                         continue;
5636
5637                 if (algo->keymax < ipsec_ah_keymin)
5638                         continue;
5639                 if (algo->keymin < ipsec_ah_keymin)
5640                         min = ipsec_ah_keymin;
5641                 else
5642                         min = algo->keymin;
5643
5644                 if (!m) {
5645 #ifdef DIAGNOSTIC
5646                         if (l > MLEN)
5647                                 panic("assumption failed in key_getcomb_ah");
5648 #endif
5649                         MGET(m, MB_DONTWAIT, MT_DATA);
5650                         if (m) {
5651                                 M_ALIGN(m, l);
5652                                 m->m_len = l;
5653                                 m->m_next = NULL;
5654                         }
5655                 } else
5656                         M_PREPEND(m, l, MB_DONTWAIT);
5657                 if (!m)
5658                         return NULL;
5659
5660                 comb = mtod(m, struct sadb_comb *);
5661                 bzero(comb, sizeof(*comb));
5662                 key_getcomb_setlifetime(comb);
5663                 comb->sadb_comb_auth = i;
5664                 comb->sadb_comb_auth_minbits = min;
5665                 comb->sadb_comb_auth_maxbits = algo->keymax;
5666         }
5667
5668         return m;
5669 }
5670
5671 /*
5672  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5673  * XXX reorder combinations by preference
5674  */
5675 static struct mbuf *
5676 key_getcomb_ipcomp()
5677 {
5678         struct sadb_comb *comb;
5679         const struct ipcomp_algorithm *algo;
5680         struct mbuf *m;
5681         int i;
5682         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5683
5684         m = NULL;
5685         for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5686                 algo = ipcomp_algorithm_lookup(i);
5687                 if (!algo)
5688                         continue;
5689
5690                 if (!m) {
5691 #ifdef DIAGNOSTIC
5692                         if (l > MLEN)
5693                                 panic("assumption failed in key_getcomb_ipcomp");
5694 #endif
5695                         MGET(m, MB_DONTWAIT, MT_DATA);
5696                         if (m) {
5697                                 M_ALIGN(m, l);
5698                                 m->m_len = l;
5699                                 m->m_next = NULL;
5700                         }
5701                 } else
5702                         M_PREPEND(m, l, MB_DONTWAIT);
5703                 if (!m)
5704                         return NULL;
5705
5706                 comb = mtod(m, struct sadb_comb *);
5707                 bzero(comb, sizeof(*comb));
5708                 key_getcomb_setlifetime(comb);
5709                 comb->sadb_comb_encrypt = i;
5710                 /* what should we set into sadb_comb_*_{min,max}bits? */
5711         }
5712
5713         return m;
5714 }
5715
5716 /*
5717  * XXX no way to pass mode (transport/tunnel) to userland
5718  * XXX replay checking?
5719  * XXX sysctl interface to ipsec_{ah,esp}_keymin
5720  */
5721 static struct mbuf *
5722 key_getprop(saidx)
5723         const struct secasindex *saidx;
5724 {
5725         struct sadb_prop *prop;
5726         struct mbuf *m, *n;
5727         const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5728         int totlen;
5729
5730         switch (saidx->proto)  {
5731 #ifdef IPSEC_ESP
5732         case IPPROTO_ESP:
5733                 m = key_getcomb_esp();
5734                 break;
5735 #endif
5736         case IPPROTO_AH:
5737                 m = key_getcomb_ah();
5738                 break;
5739         case IPPROTO_IPCOMP:
5740                 m = key_getcomb_ipcomp();
5741                 break;
5742         default:
5743                 return NULL;
5744         }
5745
5746         if (!m)
5747                 return NULL;
5748         M_PREPEND(m, l, MB_DONTWAIT);
5749         if (!m)
5750                 return NULL;
5751
5752         totlen = 0;
5753         for (n = m; n; n = n->m_next)
5754                 totlen += n->m_len;
5755
5756         prop = mtod(m, struct sadb_prop *);
5757         bzero(prop, sizeof(*prop));
5758         prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5759         prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5760         prop->sadb_prop_replay = 32;    /* XXX */
5761
5762         return m;
5763 }
5764
5765 /*
5766  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5767  * send
5768  *   <base, SA, address(SD), (address(P)), x_policy,
5769  *       (identity(SD),) (sensitivity,) proposal>
5770  * to KMD, and expect to receive
5771  *   <base> with SADB_ACQUIRE if error occured,
5772  * or
5773  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5774  * from KMD by PF_KEY.
5775  *
5776  * XXX x_policy is outside of RFC2367 (KAME extension).
5777  * XXX sensitivity is not supported.
5778  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5779  * see comment for key_getcomb_ipcomp().
5780  *
5781  * OUT:
5782  *    0     : succeed
5783  *    others: error number
5784  */
5785 static int
5786 key_acquire(saidx, sp)
5787         struct secasindex *saidx;
5788         struct secpolicy *sp;
5789 {
5790         struct mbuf *result = NULL, *m;
5791 #ifndef IPSEC_NONBLOCK_ACQUIRE
5792         struct secacq *newacq;
5793 #endif
5794         u_int8_t satype;
5795         int error = -1;
5796         u_int32_t seq;
5797
5798         /* sanity check */
5799         if (saidx == NULL)
5800                 panic("key_acquire: NULL pointer is passed.\n");
5801         if ((satype = key_proto2satype(saidx->proto)) == 0)
5802                 panic("key_acquire: invalid proto is passed.\n");
5803
5804 #ifndef IPSEC_NONBLOCK_ACQUIRE
5805         /*
5806          * We never do anything about acquirng SA.  There is anather
5807          * solution that kernel blocks to send SADB_ACQUIRE message until
5808          * getting something message from IKEd.  In later case, to be
5809          * managed with ACQUIRING list.
5810          */
5811         /* get a entry to check whether sending message or not. */
5812         if ((newacq = key_getacq(saidx)) != NULL) {
5813                 if (key_blockacq_count < newacq->count) {
5814                         /* reset counter and do send message. */
5815                         newacq->count = 0;
5816                 } else {
5817                         /* increment counter and do nothing. */
5818                         newacq->count++;
5819                         return 0;
5820                 }
5821         } else {
5822                 /* make new entry for blocking to send SADB_ACQUIRE. */
5823                 if ((newacq = key_newacq(saidx)) == NULL)
5824                         return ENOBUFS;
5825
5826                 /* add to acqtree */
5827                 LIST_INSERT_HEAD(&acqtree, newacq, chain);
5828         }
5829 #endif
5830
5831
5832 #ifndef IPSEC_NONBLOCK_ACQUIRE
5833         seq = newacq->seq;
5834 #else
5835         seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
5836 #endif
5837         m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5838         if (!m) {
5839                 error = ENOBUFS;
5840                 goto fail;
5841         }
5842         result = m;
5843
5844         /* set sadb_address for saidx's. */
5845         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5846             (struct sockaddr *)&saidx->src, FULLMASK, IPSEC_ULPROTO_ANY);
5847         if (!m) {
5848                 error = ENOBUFS;
5849                 goto fail;
5850         }
5851         m_cat(result, m);
5852
5853         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5854             (struct sockaddr *)&saidx->dst, FULLMASK, IPSEC_ULPROTO_ANY);
5855         if (!m) {
5856                 error = ENOBUFS;
5857                 goto fail;
5858         }
5859         m_cat(result, m);
5860
5861         /* XXX proxy address (optional) */
5862
5863         /* set sadb_x_policy */
5864         if (sp) {
5865                 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5866                 if (!m) {
5867                         error = ENOBUFS;
5868                         goto fail;
5869                 }
5870                 m_cat(result, m);
5871         }
5872
5873         /* XXX identity (optional) */
5874 #if 0
5875         if (idexttype && fqdn) {
5876                 /* create identity extension (FQDN) */
5877                 struct sadb_ident *id;
5878                 int fqdnlen;
5879
5880                 fqdnlen = strlen(fqdn) + 1;     /* +1 for terminating-NUL */
5881                 id = (struct sadb_ident *)p;
5882                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5883                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5884                 id->sadb_ident_exttype = idexttype;
5885                 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5886                 bcopy(fqdn, id + 1, fqdnlen);
5887                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5888         }
5889
5890         if (idexttype) {
5891                 /* create identity extension (USERFQDN) */
5892                 struct sadb_ident *id;
5893                 int userfqdnlen;
5894
5895                 if (userfqdn) {
5896                         /* +1 for terminating-NUL */
5897                         userfqdnlen = strlen(userfqdn) + 1;
5898                 } else
5899                         userfqdnlen = 0;
5900                 id = (struct sadb_ident *)p;
5901                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5902                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5903                 id->sadb_ident_exttype = idexttype;
5904                 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5905                 /* XXX is it correct? */
5906                 if (curproc && curproc->p_cred)
5907                         id->sadb_ident_id = curproc->p_cred->p_ruid;
5908                 if (userfqdn && userfqdnlen)
5909                         bcopy(userfqdn, id + 1, userfqdnlen);
5910                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5911         }
5912 #endif
5913
5914         /* XXX sensitivity (optional) */
5915
5916         /* create proposal/combination extension */
5917         m = key_getprop(saidx);
5918 #if 0
5919         /*
5920          * spec conformant: always attach proposal/combination extension,
5921          * the problem is that we have no way to attach it for ipcomp,
5922          * due to the way sadb_comb is declared in RFC2367.
5923          */
5924         if (!m) {
5925                 error = ENOBUFS;
5926                 goto fail;
5927         }
5928         m_cat(result, m);
5929 #else
5930         /*
5931          * outside of spec; make proposal/combination extension optional.
5932          */
5933         if (m)
5934                 m_cat(result, m);
5935 #endif
5936
5937         if ((result->m_flags & M_PKTHDR) == 0) {
5938                 error = EINVAL;
5939                 goto fail;
5940         }
5941
5942         if (result->m_len < sizeof(struct sadb_msg)) {
5943                 result = m_pullup(result, sizeof(struct sadb_msg));
5944                 if (result == NULL) {
5945                         error = ENOBUFS;
5946                         goto fail;
5947                 }
5948         }
5949
5950         result->m_pkthdr.len = 0;
5951         for (m = result; m; m = m->m_next)
5952                 result->m_pkthdr.len += m->m_len;
5953
5954         mtod(result, struct sadb_msg *)->sadb_msg_len =
5955             PFKEY_UNIT64(result->m_pkthdr.len);
5956
5957         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5958
5959  fail:
5960         if (result)
5961                 m_freem(result);
5962         return error;
5963 }
5964
5965 #ifndef IPSEC_NONBLOCK_ACQUIRE
5966 static struct secacq *
5967 key_newacq(saidx)
5968         struct secasindex *saidx;
5969 {
5970         struct secacq *newacq;
5971         struct timeval tv;
5972
5973         /* get new entry */
5974         KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
5975         if (newacq == NULL) {
5976                 ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
5977                 return NULL;
5978         }
5979         bzero(newacq, sizeof(*newacq));
5980
5981         /* copy secindex */
5982         bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5983         newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5984         microtime(&tv);
5985         newacq->created = tv.tv_sec;
5986         newacq->count = 0;
5987
5988         return newacq;
5989 }
5990
5991 static struct secacq *
5992 key_getacq(saidx)
5993         struct secasindex *saidx;
5994 {
5995         struct secacq *acq;
5996
5997         LIST_FOREACH(acq, &acqtree, chain) {
5998                 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5999                         return acq;
6000         }
6001
6002         return NULL;
6003 }
6004
6005 static struct secacq *
6006 key_getacqbyseq(seq)
6007         u_int32_t seq;
6008 {
6009         struct secacq *acq;
6010
6011         LIST_FOREACH(acq, &acqtree, chain) {
6012                 if (acq->seq == seq)
6013                         return acq;
6014         }
6015
6016         return NULL;
6017 }
6018 #endif
6019
6020 static struct secspacq *
6021 key_newspacq(spidx)
6022         struct secpolicyindex *spidx;
6023 {
6024         struct secspacq *acq;
6025         struct timeval tv;
6026
6027         /* get new entry */
6028         KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
6029         if (acq == NULL) {
6030                 ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
6031                 return NULL;
6032         }
6033         bzero(acq, sizeof(*acq));
6034
6035         /* copy secindex */
6036         bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6037         microtime(&tv);
6038         acq->created = tv.tv_sec;
6039         acq->count = 0;
6040
6041         return acq;
6042 }
6043
6044 static struct secspacq *
6045 key_getspacq(spidx)
6046         struct secpolicyindex *spidx;
6047 {
6048         struct secspacq *acq;
6049
6050         LIST_FOREACH(acq, &spacqtree, chain) {
6051                 if (key_cmpspidx_exactly(spidx, &acq->spidx))
6052                         return acq;
6053         }
6054
6055         return NULL;
6056 }
6057
6058 /*
6059  * SADB_ACQUIRE processing,
6060  * in first situation, is receiving
6061  *   <base>
6062  * from the ikmpd, and clear sequence of its secasvar entry.
6063  *
6064  * In second situation, is receiving
6065  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6066  * from a user land process, and return
6067  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6068  * to the socket.
6069  *
6070  * m will always be freed.
6071  */
6072 static int
6073 key_acquire2(so, m, mhp)
6074         struct socket *so;
6075         struct mbuf *m;
6076         const struct sadb_msghdr *mhp;
6077 {
6078         struct sadb_address *src0, *dst0;
6079         struct secasindex saidx;
6080         struct secashead *sah;
6081         u_int16_t proto;
6082         int error;
6083
6084         /* sanity check */
6085         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6086                 panic("key_acquire2: NULL pointer is passed.\n");
6087
6088         /*
6089          * Error message from KMd.
6090          * We assume that if error was occured in IKEd, the length of PFKEY
6091          * message is equal to the size of sadb_msg structure.
6092          * We do not raise error even if error occured in this function.
6093          */
6094         if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6095 #ifndef IPSEC_NONBLOCK_ACQUIRE
6096                 struct secacq *acq;
6097                 struct timeval tv;
6098
6099                 /* check sequence number */
6100                 if (mhp->msg->sadb_msg_seq == 0) {
6101                         ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
6102                         m_freem(m);
6103                         return 0;
6104                 }
6105
6106                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6107                         /*
6108                          * the specified larval SA is already gone, or we got
6109                          * a bogus sequence number.  we can silently ignore it.
6110                          */
6111                         m_freem(m);
6112                         return 0;
6113                 }
6114
6115                 /* reset acq counter in order to deletion by timehander. */
6116                 microtime(&tv);
6117                 acq->created = tv.tv_sec;
6118                 acq->count = 0;
6119 #endif
6120                 m_freem(m);
6121                 return 0;
6122         }
6123
6124         /*
6125          * This message is from user land.
6126          */
6127
6128         /* map satype to proto */
6129         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6130                 ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
6131                 return key_senderror(so, m, EINVAL);
6132         }
6133
6134         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6135             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6136             mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6137                 /* error */
6138                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6139                 return key_senderror(so, m, EINVAL);
6140         }
6141         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6142             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6143             mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6144                 /* error */
6145                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6146                 return key_senderror(so, m, EINVAL);
6147         }
6148
6149         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6150         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6151
6152         /* XXX boundary check against sa_len */
6153         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6154
6155         /* get a SA index */
6156         LIST_FOREACH(sah, &sahtree, chain) {
6157                 if (sah->state == SADB_SASTATE_DEAD)
6158                         continue;
6159                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6160                         break;
6161         }
6162         if (sah != NULL) {
6163                 ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
6164                 return key_senderror(so, m, EEXIST);
6165         }
6166
6167         error = key_acquire(&saidx, NULL);
6168         if (error != 0) {
6169                 ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
6170                         "from key_acquire.\n", mhp->msg->sadb_msg_errno));
6171                 return key_senderror(so, m, error);
6172         }
6173
6174         return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6175 }
6176
6177 /*
6178  * SADB_REGISTER processing.
6179  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6180  * receive
6181  *   <base>
6182  * from the ikmpd, and register a socket to send PF_KEY messages,
6183  * and send
6184  *   <base, supported>
6185  * to KMD by PF_KEY.
6186  * If socket is detached, must free from regnode.
6187  *
6188  * m will always be freed.
6189  */
6190 static int
6191 key_register(so, m, mhp)
6192         struct socket *so;
6193         struct mbuf *m;
6194         const struct sadb_msghdr *mhp;
6195 {
6196         struct secreg *reg, *newreg = 0;
6197
6198         /* sanity check */
6199         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6200                 panic("key_register: NULL pointer is passed.\n");
6201
6202         /* check for invalid register message */
6203         if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6204                 return key_senderror(so, m, EINVAL);
6205
6206         /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6207         if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6208                 goto setmsg;
6209
6210         /* check whether existing or not */
6211         LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6212                 if (reg->so == so) {
6213                         ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
6214                         return key_senderror(so, m, EEXIST);
6215                 }
6216         }
6217
6218         /* create regnode */
6219         KMALLOC(newreg, struct secreg *, sizeof(*newreg));
6220         if (newreg == NULL) {
6221                 ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
6222                 return key_senderror(so, m, ENOBUFS);
6223         }
6224         bzero((caddr_t)newreg, sizeof(*newreg));
6225
6226         newreg->so = so;
6227         ((struct keycb *)sotorawcb(so))->kp_registered++;
6228
6229         /* add regnode to regtree. */
6230         LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6231
6232   setmsg:
6233     {
6234         struct mbuf *n;
6235         struct sadb_msg *newmsg;
6236         struct sadb_supported *sup;
6237         u_int len, alen, elen;
6238         int off;
6239         int i;
6240         struct sadb_alg *alg;
6241
6242         /* create new sadb_msg to reply. */
6243         alen = 0;
6244         for (i = 1; i <= SADB_AALG_MAX; i++) {
6245                 if (ah_algorithm_lookup(i))
6246                         alen += sizeof(struct sadb_alg);
6247         }
6248         if (alen)
6249                 alen += sizeof(struct sadb_supported);
6250         elen = 0;
6251 #ifdef IPSEC_ESP
6252         for (i = 1; i <= SADB_EALG_MAX; i++) {
6253                 if (esp_algorithm_lookup(i))
6254                         elen += sizeof(struct sadb_alg);
6255         }
6256         if (elen)
6257                 elen += sizeof(struct sadb_supported);
6258 #endif
6259
6260         len = sizeof(struct sadb_msg) + alen + elen;
6261
6262         if (len > MCLBYTES)
6263                 return key_senderror(so, m, ENOBUFS);
6264
6265         MGETHDR(n, MB_DONTWAIT, MT_DATA);
6266         if (len > MHLEN) {
6267                 MCLGET(n, MB_DONTWAIT);
6268                 if ((n->m_flags & M_EXT) == 0) {
6269                         m_freem(n);
6270                         n = NULL;
6271                 }
6272         }
6273         if (!n)
6274                 return key_senderror(so, m, ENOBUFS);
6275
6276         n->m_pkthdr.len = n->m_len = len;
6277         n->m_next = NULL;
6278         off = 0;
6279
6280         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6281         newmsg = mtod(n, struct sadb_msg *);
6282         newmsg->sadb_msg_errno = 0;
6283         newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6284         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6285
6286         /* for authentication algorithm */
6287         if (alen) {
6288                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6289                 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6290                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6291                 off += PFKEY_ALIGN8(sizeof(*sup));
6292
6293                 for (i = 1; i <= SADB_AALG_MAX; i++) {
6294                         const struct ah_algorithm *aalgo;
6295
6296                         aalgo = ah_algorithm_lookup(i);
6297                         if (!aalgo)
6298                                 continue;
6299                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6300                         alg->sadb_alg_id = i;
6301                         alg->sadb_alg_ivlen = 0;
6302                         alg->sadb_alg_minbits = aalgo->keymin;
6303                         alg->sadb_alg_maxbits = aalgo->keymax;
6304                         off += PFKEY_ALIGN8(sizeof(*alg));
6305                 }
6306         }
6307
6308 #ifdef IPSEC_ESP
6309         /* for encryption algorithm */
6310         if (elen) {
6311                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6312                 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6313                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6314                 off += PFKEY_ALIGN8(sizeof(*sup));
6315
6316                 for (i = 1; i <= SADB_EALG_MAX; i++) {
6317                         const struct esp_algorithm *ealgo;
6318
6319                         ealgo = esp_algorithm_lookup(i);
6320                         if (!ealgo)
6321                                 continue;
6322                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6323                         alg->sadb_alg_id = i;
6324                         if (ealgo && ealgo->ivlen) {
6325                                 /*
6326                                  * give NULL to get the value preferred by
6327                                  * algorithm XXX SADB_X_EXT_DERIV ?
6328                                  */
6329                                 alg->sadb_alg_ivlen =
6330                                     (*ealgo->ivlen)(ealgo, NULL);
6331                         } else
6332                                 alg->sadb_alg_ivlen = 0;
6333                         alg->sadb_alg_minbits = ealgo->keymin;
6334                         alg->sadb_alg_maxbits = ealgo->keymax;
6335                         off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6336                 }
6337         }
6338 #endif
6339
6340 #ifdef DIGAGNOSTIC
6341         if (off != len)
6342                 panic("length assumption failed in key_register");
6343 #endif
6344
6345         m_freem(m);
6346         return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6347     }
6348 }
6349
6350 /*
6351  * free secreg entry registered.
6352  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6353  */
6354 void
6355 key_freereg(so)
6356         struct socket *so;
6357 {
6358         struct secreg *reg;
6359         int i;
6360
6361         /* sanity check */
6362         if (so == NULL)
6363                 panic("key_freereg: NULL pointer is passed.\n");
6364
6365         /*
6366          * check whether existing or not.
6367          * check all type of SA, because there is a potential that
6368          * one socket is registered to multiple type of SA.
6369          */
6370         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6371                 LIST_FOREACH(reg, &regtree[i], chain) {
6372                         if (reg->so == so
6373                          && __LIST_CHAINED(reg)) {
6374                                 LIST_REMOVE(reg, chain);
6375                                 KFREE(reg);
6376                                 break;
6377                         }
6378                 }
6379         }
6380         
6381         return;
6382 }
6383
6384 /*
6385  * SADB_EXPIRE processing
6386  * send
6387  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6388  * to KMD by PF_KEY.
6389  * NOTE: We send only soft lifetime extension.
6390  *
6391  * OUT: 0       : succeed
6392  *      others  : error number
6393  */
6394 static int
6395 key_expire(sav)
6396         struct secasvar *sav;
6397 {
6398         int s;
6399         int satype;
6400         struct mbuf *result = NULL, *m;
6401         int len;
6402         int error = -1;
6403         struct sadb_lifetime *lt;
6404
6405         /* XXX: Why do we lock ? */
6406         s = splnet();   /*called from softclock()*/
6407
6408         /* sanity check */
6409         if (sav == NULL)
6410                 panic("key_expire: NULL pointer is passed.\n");
6411         if (sav->sah == NULL)
6412                 panic("key_expire: Why was SA index in SA NULL.\n");
6413         if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
6414                 panic("key_expire: invalid proto is passed.\n");
6415
6416         /* set msg header */
6417         m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6418         if (!m) {
6419                 error = ENOBUFS;
6420                 goto fail;
6421         }
6422         result = m;
6423
6424         /* create SA extension */
6425         m = key_setsadbsa(sav);
6426         if (!m) {
6427                 error = ENOBUFS;
6428                 goto fail;
6429         }
6430         m_cat(result, m);
6431
6432         /* create SA extension */
6433         m = key_setsadbxsa2(sav->sah->saidx.mode,
6434                         sav->replay ? sav->replay->count : 0,
6435                         sav->sah->saidx.reqid);
6436         if (!m) {
6437                 error = ENOBUFS;
6438                 goto fail;
6439         }
6440         m_cat(result, m);
6441
6442         /* create lifetime extension (current and soft) */
6443         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6444         m = key_alloc_mbuf(len);
6445         if (!m || m->m_next) {  /*XXX*/
6446                 if (m)
6447                         m_freem(m);
6448                 error = ENOBUFS;
6449                 goto fail;
6450         }
6451         bzero(mtod(m, caddr_t), len);
6452         lt = mtod(m, struct sadb_lifetime *);
6453         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6454         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6455         lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6456         lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6457         lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6458         lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6459         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6460         bcopy(sav->lft_s, lt, sizeof(*lt));
6461         m_cat(result, m);
6462
6463         /* set sadb_address for source */
6464         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6465             (struct sockaddr *)&sav->sah->saidx.src,
6466             FULLMASK, IPSEC_ULPROTO_ANY);
6467         if (!m) {
6468                 error = ENOBUFS;
6469                 goto fail;
6470         }
6471         m_cat(result, m);
6472
6473         /* set sadb_address for destination */
6474         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6475             (struct sockaddr *)&sav->sah->saidx.dst,
6476             FULLMASK, IPSEC_ULPROTO_ANY);
6477         if (!m) {
6478                 error = ENOBUFS;
6479                 goto fail;
6480         }
6481         m_cat(result, m);
6482
6483         if ((result->m_flags & M_PKTHDR) == 0) {
6484                 error = EINVAL;
6485                 goto fail;
6486         }
6487
6488         if (result->m_len < sizeof(struct sadb_msg)) {
6489                 result = m_pullup(result, sizeof(struct sadb_msg));
6490                 if (result == NULL) {
6491                         error = ENOBUFS;
6492                         goto fail;
6493                 }
6494         }
6495
6496         result->m_pkthdr.len = 0;
6497         for (m = result; m; m = m->m_next)
6498                 result->m_pkthdr.len += m->m_len;
6499
6500         mtod(result, struct sadb_msg *)->sadb_msg_len =
6501             PFKEY_UNIT64(result->m_pkthdr.len);
6502
6503         splx(s);
6504         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6505
6506  fail:
6507         if (result)
6508                 m_freem(result);
6509         splx(s);
6510         return error;
6511 }
6512
6513 /*
6514  * SADB_FLUSH processing
6515  * receive
6516  *   <base>
6517  * from the ikmpd, and free all entries in secastree.
6518  * and send,
6519  *   <base>
6520  * to the ikmpd.
6521  * NOTE: to do is only marking SADB_SASTATE_DEAD.
6522  *
6523  * m will always be freed.
6524  */
6525 static int
6526 key_flush(so, m, mhp)
6527         struct socket *so;
6528         struct mbuf *m;
6529         const struct sadb_msghdr *mhp;
6530 {
6531         struct sadb_msg *newmsg;
6532         struct secashead *sah, *nextsah;
6533         struct secasvar *sav, *nextsav;
6534         u_int16_t proto;
6535         u_int8_t state;
6536         u_int stateidx;
6537
6538         /* sanity check */
6539         if (so == NULL || mhp == NULL || mhp->msg == NULL)
6540                 panic("key_flush: NULL pointer is passed.\n");
6541
6542         /* map satype to proto */
6543         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6544                 ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6545                 return key_senderror(so, m, EINVAL);
6546         }
6547
6548         /* no SATYPE specified, i.e. flushing all SA. */
6549         for (sah = LIST_FIRST(&sahtree);
6550              sah != NULL;
6551              sah = nextsah) {
6552                 nextsah = LIST_NEXT(sah, chain);
6553
6554                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6555                  && proto != sah->saidx.proto)
6556                         continue;
6557
6558                 for (stateidx = 0;
6559                      stateidx < _ARRAYLEN(saorder_state_alive);
6560                      stateidx++) {
6561                         state = saorder_state_any[stateidx];
6562                         for (sav = LIST_FIRST(&sah->savtree[state]);
6563                              sav != NULL;
6564                              sav = nextsav) {
6565
6566                                 nextsav = LIST_NEXT(sav, chain);
6567
6568                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6569                                 key_freesav(sav);
6570                         }
6571                 }
6572
6573                 sah->state = SADB_SASTATE_DEAD;
6574         }
6575
6576         if (m->m_len < sizeof(struct sadb_msg) ||
6577             sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6578                 ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
6579                 return key_senderror(so, m, ENOBUFS);
6580         }
6581
6582         if (m->m_next)
6583                 m_freem(m->m_next);
6584         m->m_next = NULL;
6585         m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6586         newmsg = mtod(m, struct sadb_msg *);
6587         newmsg->sadb_msg_errno = 0;
6588         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6589
6590         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6591 }
6592
6593 /*
6594  * SADB_DUMP processing
6595  * dump all entries including status of DEAD in SAD.
6596  * receive
6597  *   <base>
6598  * from the ikmpd, and dump all secasvar leaves
6599  * and send,
6600  *   <base> .....
6601  * to the ikmpd.
6602  *
6603  * m will always be freed.
6604  */
6605 static int
6606 key_dump(so, m, mhp)
6607         struct socket *so;
6608         struct mbuf *m;
6609         const struct sadb_msghdr *mhp;
6610 {
6611         struct secashead *sah;
6612         struct secasvar *sav;
6613         u_int16_t proto;
6614         u_int stateidx;
6615         u_int8_t satype;
6616         u_int8_t state;
6617         int cnt;
6618         struct sadb_msg *newmsg;
6619         struct mbuf *n;
6620
6621         /* sanity check */
6622         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6623                 panic("key_dump: NULL pointer is passed.\n");
6624
6625         /* map satype to proto */
6626         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6627                 ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
6628                 return key_senderror(so, m, EINVAL);
6629         }
6630
6631         /* count sav entries to be sent to the userland. */
6632         cnt = 0;
6633         LIST_FOREACH(sah, &sahtree, chain) {
6634                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6635                  && proto != sah->saidx.proto)
6636                         continue;
6637
6638                 for (stateidx = 0;
6639                      stateidx < _ARRAYLEN(saorder_state_any);
6640                      stateidx++) {
6641                         state = saorder_state_any[stateidx];
6642                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
6643                                 cnt++;
6644                         }
6645                 }
6646         }
6647
6648         if (cnt == 0)
6649                 return key_senderror(so, m, ENOENT);
6650
6651         /* send this to the userland, one at a time. */
6652         newmsg = NULL;
6653         LIST_FOREACH(sah, &sahtree, chain) {
6654                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6655                  && proto != sah->saidx.proto)
6656                         continue;
6657
6658                 /* map proto to satype */
6659                 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6660                         ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
6661                         return key_senderror(so, m, EINVAL);
6662                 }
6663
6664                 for (stateidx = 0;
6665                      stateidx < _ARRAYLEN(saorder_state_any);
6666                      stateidx++) {
6667                         state = saorder_state_any[stateidx];
6668                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
6669                                 n = key_setdumpsa(sav, SADB_DUMP, satype,
6670                                     --cnt, mhp->msg->sadb_msg_pid);
6671                                 if (!n)
6672                                         return key_senderror(so, m, ENOBUFS);
6673
6674                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6675                         }
6676                 }
6677         }
6678
6679         m_freem(m);
6680         return 0;
6681 }
6682
6683 /*
6684  * SADB_X_PROMISC processing
6685  *
6686  * m will always be freed.
6687  */
6688 static int
6689 key_promisc(so, m, mhp)
6690         struct socket *so;
6691         struct mbuf *m;
6692         const struct sadb_msghdr *mhp;
6693 {
6694         int olen;
6695
6696         /* sanity check */
6697         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6698                 panic("key_promisc: NULL pointer is passed.\n");
6699
6700         olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6701
6702         if (olen < sizeof(struct sadb_msg)) {
6703 #if 1
6704                 return key_senderror(so, m, EINVAL);
6705 #else
6706                 m_freem(m);
6707                 return 0;
6708 #endif
6709         } else if (olen == sizeof(struct sadb_msg)) {
6710                 /* enable/disable promisc mode */
6711                 struct keycb *kp;
6712
6713                 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6714                         return key_senderror(so, m, EINVAL);
6715                 mhp->msg->sadb_msg_errno = 0;
6716                 switch (mhp->msg->sadb_msg_satype) {
6717                 case 0:
6718                 case 1:
6719                         kp->kp_promisc = mhp->msg->sadb_msg_satype;
6720                         break;
6721                 default:
6722                         return key_senderror(so, m, EINVAL);
6723                 }
6724
6725                 /* send the original message back to everyone */
6726                 mhp->msg->sadb_msg_errno = 0;
6727                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6728         } else {
6729                 /* send packet as is */
6730
6731                 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6732
6733                 /* TODO: if sadb_msg_seq is specified, send to specific pid */
6734                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6735         }
6736 }
6737
6738 static int (*key_typesw[]) (struct socket *, struct mbuf *,
6739                 const struct sadb_msghdr *) = {
6740         NULL,           /* SADB_RESERVED */
6741         key_getspi,     /* SADB_GETSPI */
6742         key_update,     /* SADB_UPDATE */
6743         key_add,        /* SADB_ADD */
6744         key_delete,     /* SADB_DELETE */
6745         key_get,        /* SADB_GET */
6746         key_acquire2,   /* SADB_ACQUIRE */
6747         key_register,   /* SADB_REGISTER */
6748         NULL,           /* SADB_EXPIRE */
6749         key_flush,      /* SADB_FLUSH */
6750         key_dump,       /* SADB_DUMP */
6751         key_promisc,    /* SADB_X_PROMISC */
6752         NULL,           /* SADB_X_PCHANGE */
6753         key_spdadd,     /* SADB_X_SPDUPDATE */
6754         key_spdadd,     /* SADB_X_SPDADD */
6755         key_spddelete,  /* SADB_X_SPDDELETE */
6756         key_spdget,     /* SADB_X_SPDGET */
6757         NULL,           /* SADB_X_SPDACQUIRE */
6758         key_spddump,    /* SADB_X_SPDDUMP */
6759         key_spdflush,   /* SADB_X_SPDFLUSH */
6760         key_spdadd,     /* SADB_X_SPDSETIDX */
6761         NULL,           /* SADB_X_SPDEXPIRE */
6762         key_spddelete2, /* SADB_X_SPDDELETE2 */
6763 };
6764
6765 /*
6766  * parse sadb_msg buffer to process PFKEYv2,
6767  * and create a data to response if needed.
6768  * I think to be dealed with mbuf directly.
6769  * IN:
6770  *     msgp  : pointer to pointer to a received buffer pulluped.
6771  *             This is rewrited to response.
6772  *     so    : pointer to socket.
6773  * OUT:
6774  *    length for buffer to send to user process.
6775  */
6776 int
6777 key_parse(m, so)
6778         struct mbuf *m;
6779         struct socket *so;
6780 {
6781         struct sadb_msg *msg;
6782         struct sadb_msghdr mh;
6783         u_int orglen;
6784         int error;
6785         int target;
6786
6787         /* sanity check */
6788         if (m == NULL || so == NULL)
6789                 panic("key_parse: NULL pointer is passed.\n");
6790
6791 #if 0   /*kdebug_sadb assumes msg in linear buffer*/
6792         KEYDEBUG(KEYDEBUG_KEY_DUMP,
6793                 ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
6794                 kdebug_sadb(msg));
6795 #endif
6796
6797         if (m->m_len < sizeof(struct sadb_msg)) {
6798                 m = m_pullup(m, sizeof(struct sadb_msg));
6799                 if (!m)
6800                         return ENOBUFS;
6801         }
6802         msg = mtod(m, struct sadb_msg *);
6803         orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6804         target = KEY_SENDUP_ONE;
6805
6806         if ((m->m_flags & M_PKTHDR) == 0 ||
6807             m->m_pkthdr.len != m->m_pkthdr.len) {
6808                 ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
6809                 pfkeystat.out_invlen++;
6810                 error = EINVAL;
6811                 goto senderror;
6812         }
6813
6814         if (msg->sadb_msg_version != PF_KEY_V2) {
6815                 ipseclog((LOG_DEBUG,
6816                     "key_parse: PF_KEY version %u is mismatched.\n",
6817                     msg->sadb_msg_version));
6818                 pfkeystat.out_invver++;
6819                 error = EINVAL;
6820                 goto senderror;
6821         }
6822
6823         if (msg->sadb_msg_type > SADB_MAX) {
6824                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6825                     msg->sadb_msg_type));
6826                 pfkeystat.out_invmsgtype++;
6827                 error = EINVAL;
6828                 goto senderror;
6829         }
6830
6831         /* for old-fashioned code - should be nuked */
6832         if (m->m_pkthdr.len > MCLBYTES) {
6833                 m_freem(m);
6834                 return ENOBUFS;
6835         }
6836         if (m->m_next) {
6837                 struct mbuf *n;
6838
6839                 MGETHDR(n, MB_DONTWAIT, MT_DATA);
6840                 if (n && m->m_pkthdr.len > MHLEN) {
6841                         MCLGET(n, MB_DONTWAIT);
6842                         if ((n->m_flags & M_EXT) == 0) {
6843                                 m_free(n);
6844                                 n = NULL;
6845                         }
6846                 }
6847                 if (!n) {
6848                         m_freem(m);
6849                         return ENOBUFS;
6850                 }
6851                 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6852                 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6853                 n->m_next = NULL;
6854                 m_freem(m);
6855                 m = n;
6856         }
6857
6858         /* align the mbuf chain so that extensions are in contiguous region. */
6859         error = key_align(m, &mh);
6860         if (error)
6861                 return error;
6862
6863         if (m->m_next) {        /*XXX*/
6864                 m_freem(m);
6865                 return ENOBUFS;
6866         }
6867
6868         msg = mh.msg;
6869
6870         /* check SA type */
6871         switch (msg->sadb_msg_satype) {
6872         case SADB_SATYPE_UNSPEC:
6873                 switch (msg->sadb_msg_type) {
6874                 case SADB_GETSPI:
6875                 case SADB_UPDATE:
6876                 case SADB_ADD:
6877                 case SADB_DELETE:
6878                 case SADB_GET:
6879                 case SADB_ACQUIRE:
6880                 case SADB_EXPIRE:
6881                         ipseclog((LOG_DEBUG, "key_parse: must specify satype "
6882                             "when msg type=%u.\n", msg->sadb_msg_type));
6883                         pfkeystat.out_invsatype++;
6884                         error = EINVAL;
6885                         goto senderror;
6886                 }
6887                 break;
6888         case SADB_SATYPE_AH:
6889         case SADB_SATYPE_ESP:
6890         case SADB_X_SATYPE_IPCOMP:
6891                 switch (msg->sadb_msg_type) {
6892                 case SADB_X_SPDADD:
6893                 case SADB_X_SPDDELETE:
6894                 case SADB_X_SPDGET:
6895                 case SADB_X_SPDDUMP:
6896                 case SADB_X_SPDFLUSH:
6897                 case SADB_X_SPDSETIDX:
6898                 case SADB_X_SPDUPDATE:
6899                 case SADB_X_SPDDELETE2:
6900                         ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
6901                             msg->sadb_msg_type));
6902                         pfkeystat.out_invsatype++;
6903                         error = EINVAL;
6904                         goto senderror;
6905                 }
6906                 break;
6907         case SADB_SATYPE_RSVP:
6908         case SADB_SATYPE_OSPFV2:
6909         case SADB_SATYPE_RIPV2:
6910         case SADB_SATYPE_MIP:
6911                 ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
6912                     msg->sadb_msg_satype));
6913                 pfkeystat.out_invsatype++;
6914                 error = EOPNOTSUPP;
6915                 goto senderror;
6916         case 1: /* XXX: What does it do? */
6917                 if (msg->sadb_msg_type == SADB_X_PROMISC)
6918                         break;
6919                 /*FALLTHROUGH*/
6920         default:
6921                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6922                     msg->sadb_msg_satype));
6923                 pfkeystat.out_invsatype++;
6924                 error = EINVAL;
6925                 goto senderror;
6926         }
6927
6928         /* check field of upper layer protocol and address family */
6929         if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6930          && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6931                 struct sadb_address *src0, *dst0;
6932                 u_int plen;
6933
6934                 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6935                 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6936
6937                 /* check upper layer protocol */
6938                 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6939                         ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
6940                         pfkeystat.out_invaddr++;
6941                         error = EINVAL;
6942                         goto senderror;
6943                 }
6944
6945                 /* check family */
6946                 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6947                     PFKEY_ADDR_SADDR(dst0)->sa_family) {
6948                         ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
6949                         pfkeystat.out_invaddr++;
6950                         error = EINVAL;
6951                         goto senderror;
6952                 }
6953                 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6954                     PFKEY_ADDR_SADDR(dst0)->sa_len) {
6955                         ipseclog((LOG_DEBUG,
6956                             "key_parse: address struct size mismatched.\n"));
6957                         pfkeystat.out_invaddr++;
6958                         error = EINVAL;
6959                         goto senderror;
6960                 }
6961
6962                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6963                 case AF_INET:
6964                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6965                             sizeof(struct sockaddr_in)) {
6966                                 pfkeystat.out_invaddr++;
6967                                 error = EINVAL;
6968                                 goto senderror;
6969                         }
6970                         break;
6971                 case AF_INET6:
6972                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6973                             sizeof(struct sockaddr_in6)) {
6974                                 pfkeystat.out_invaddr++;
6975                                 error = EINVAL;
6976                                 goto senderror;
6977                         }
6978                         break;
6979                 default:
6980                         ipseclog((LOG_DEBUG,
6981                             "key_parse: unsupported address family.\n"));
6982                         pfkeystat.out_invaddr++;
6983                         error = EAFNOSUPPORT;
6984                         goto senderror;
6985                 }
6986
6987                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6988                 case AF_INET:
6989                         plen = sizeof(struct in_addr) << 3;
6990                         break;
6991                 case AF_INET6:
6992                         plen = sizeof(struct in6_addr) << 3;
6993                         break;
6994                 default:
6995                         plen = 0;       /*fool gcc*/
6996                         break;
6997                 }
6998
6999                 /* check max prefix length */
7000                 if (src0->sadb_address_prefixlen > plen ||
7001                     dst0->sadb_address_prefixlen > plen) {
7002                         ipseclog((LOG_DEBUG,
7003                             "key_parse: illegal prefixlen.\n"));
7004                         pfkeystat.out_invaddr++;
7005                         error = EINVAL;
7006                         goto senderror;
7007                 }
7008
7009                 /*
7010                  * prefixlen == 0 is valid because there can be a case when
7011                  * all addresses are matched.
7012                  */
7013         }
7014
7015         if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7016             key_typesw[msg->sadb_msg_type] == NULL) {
7017                 pfkeystat.out_invmsgtype++;
7018                 error = EINVAL;
7019                 goto senderror;
7020         }
7021
7022         return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7023
7024 senderror:
7025         msg->sadb_msg_errno = error;
7026         return key_sendup_mbuf(so, m, target);
7027 }
7028
7029 static int
7030 key_senderror(so, m, code)
7031         struct socket *so;
7032         struct mbuf *m;
7033         int code;
7034 {
7035         struct sadb_msg *msg;
7036
7037         if (m->m_len < sizeof(struct sadb_msg))
7038                 panic("invalid mbuf passed to key_senderror");
7039
7040         msg = mtod(m, struct sadb_msg *);
7041         msg->sadb_msg_errno = code;
7042         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7043 }
7044
7045 /*
7046  * set the pointer to each header into message buffer.
7047  * m will be freed on error.
7048  * XXX larger-than-MCLBYTES extension?
7049  */
7050 static int
7051 key_align(m, mhp)
7052         struct mbuf *m;
7053         struct sadb_msghdr *mhp;
7054 {
7055         struct mbuf *n;
7056         struct sadb_ext *ext;
7057         size_t off, end;
7058         int extlen;
7059         int toff;
7060
7061         /* sanity check */
7062         if (m == NULL || mhp == NULL)
7063                 panic("key_align: NULL pointer is passed.\n");
7064         if (m->m_len < sizeof(struct sadb_msg))
7065                 panic("invalid mbuf passed to key_align");
7066
7067         /* initialize */
7068         bzero(mhp, sizeof(*mhp));
7069
7070         mhp->msg = mtod(m, struct sadb_msg *);
7071         mhp->ext[0] = (struct sadb_ext *)mhp->msg;      /*XXX backward compat */
7072
7073         end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7074         extlen = end;   /*just in case extlen is not updated*/
7075         for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7076                 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7077                 if (!n) {
7078                         /* m is already freed */
7079                         return ENOBUFS;
7080                 }
7081                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7082
7083                 /* set pointer */
7084                 switch (ext->sadb_ext_type) {
7085                 case SADB_EXT_SA:
7086                 case SADB_EXT_ADDRESS_SRC:
7087                 case SADB_EXT_ADDRESS_DST:
7088                 case SADB_EXT_ADDRESS_PROXY:
7089                 case SADB_EXT_LIFETIME_CURRENT:
7090                 case SADB_EXT_LIFETIME_HARD:
7091                 case SADB_EXT_LIFETIME_SOFT:
7092                 case SADB_EXT_KEY_AUTH:
7093                 case SADB_EXT_KEY_ENCRYPT:
7094                 case SADB_EXT_IDENTITY_SRC:
7095                 case SADB_EXT_IDENTITY_DST:
7096                 case SADB_EXT_SENSITIVITY:
7097                 case SADB_EXT_PROPOSAL:
7098                 case SADB_EXT_SUPPORTED_AUTH:
7099                 case SADB_EXT_SUPPORTED_ENCRYPT:
7100                 case SADB_EXT_SPIRANGE:
7101                 case SADB_X_EXT_POLICY:
7102                 case SADB_X_EXT_SA2:
7103                         /* duplicate check */
7104                         /*
7105                          * XXX Are there duplication payloads of either
7106                          * KEY_AUTH or KEY_ENCRYPT ?
7107                          */
7108                         if (mhp->ext[ext->sadb_ext_type] != NULL) {
7109                                 ipseclog((LOG_DEBUG,
7110                                     "key_align: duplicate ext_type %u "
7111                                     "is passed.\n", ext->sadb_ext_type));
7112                                 m_freem(m);
7113                                 pfkeystat.out_dupext++;
7114                                 return EINVAL;
7115                         }
7116                         break;
7117                 default:
7118                         ipseclog((LOG_DEBUG,
7119                             "key_align: invalid ext_type %u is passed.\n",
7120                             ext->sadb_ext_type));
7121                         m_freem(m);
7122                         pfkeystat.out_invexttype++;
7123                         return EINVAL;
7124                 }
7125
7126                 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7127
7128                 if (key_validate_ext(ext, extlen)) {
7129                         m_freem(m);
7130                         pfkeystat.out_invlen++;
7131                         return EINVAL;
7132                 }
7133
7134                 n = m_pulldown(m, off, extlen, &toff);
7135                 if (!n) {
7136                         /* m is already freed */
7137                         return ENOBUFS;
7138                 }
7139                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7140
7141                 mhp->ext[ext->sadb_ext_type] = ext;
7142                 mhp->extoff[ext->sadb_ext_type] = off;
7143                 mhp->extlen[ext->sadb_ext_type] = extlen;
7144         }
7145
7146         if (off != end) {
7147                 m_freem(m);
7148                 pfkeystat.out_invlen++;
7149                 return EINVAL;
7150         }
7151
7152         return 0;
7153 }
7154
7155 static int
7156 key_validate_ext(ext, len)
7157         const struct sadb_ext *ext;
7158         int len;
7159 {
7160         const struct sockaddr *sa;
7161         enum { NONE, ADDR } checktype = NONE;
7162         int baselen;
7163         const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7164
7165         if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7166                 return EINVAL;
7167
7168         /* if it does not match minimum/maximum length, bail */
7169         if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7170             ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7171                 return EINVAL;
7172         if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7173                 return EINVAL;
7174         if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7175                 return EINVAL;
7176
7177         /* more checks based on sadb_ext_type XXX need more */
7178         switch (ext->sadb_ext_type) {
7179         case SADB_EXT_ADDRESS_SRC:
7180         case SADB_EXT_ADDRESS_DST:
7181         case SADB_EXT_ADDRESS_PROXY:
7182                 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7183                 checktype = ADDR;
7184                 break;
7185         case SADB_EXT_IDENTITY_SRC:
7186         case SADB_EXT_IDENTITY_DST:
7187                 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7188                     SADB_X_IDENTTYPE_ADDR) {
7189                         baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7190                         checktype = ADDR;
7191                 } else
7192                         checktype = NONE;
7193                 break;
7194         default:
7195                 checktype = NONE;
7196                 break;
7197         }
7198
7199         switch (checktype) {
7200         case NONE:
7201                 break;
7202         case ADDR:
7203                 sa = (const struct sockaddr *)((c_caddr_t)ext + baselen);
7204                 if (len < baselen + sal)
7205                         return EINVAL;
7206                 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7207                         return EINVAL;
7208                 break;
7209         }
7210
7211         return 0;
7212 }
7213
7214 void
7215 key_init()
7216 {
7217         int i;
7218
7219         bzero((caddr_t)&key_cb, sizeof(key_cb));
7220
7221         for (i = 0; i < IPSEC_DIR_MAX; i++) {
7222                 LIST_INIT(&sptree[i]);
7223         }
7224
7225         LIST_INIT(&sahtree);
7226
7227         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7228                 LIST_INIT(&regtree[i]);
7229         }
7230
7231 #ifndef IPSEC_NONBLOCK_ACQUIRE
7232         LIST_INIT(&acqtree);
7233 #endif
7234         LIST_INIT(&spacqtree);
7235
7236         /* system default */
7237 #ifdef INET
7238         ip4_def_policy.policy = IPSEC_POLICY_NONE;
7239         ip4_def_policy.refcnt++;        /*never reclaim this*/
7240 #endif
7241 #ifdef INET6
7242         ip6_def_policy.policy = IPSEC_POLICY_NONE;
7243         ip6_def_policy.refcnt++;        /*never reclaim this*/
7244 #endif
7245
7246 #ifndef IPSEC_DEBUG2
7247         timeout((void *)key_timehandler, (void *)0, hz);
7248 #endif /*IPSEC_DEBUG2*/
7249
7250         /* initialize key statistics */
7251         keystat.getspi_count = 1;
7252
7253         printf("IPsec: Initialized Security Association Processing.\n");
7254
7255         return;
7256 }
7257
7258 /*
7259  * XXX: maybe This function is called after INBOUND IPsec processing.
7260  *
7261  * Special check for tunnel-mode packets.
7262  * We must make some checks for consistency between inner and outer IP header.
7263  *
7264  * xxx more checks to be provided
7265  */
7266 int
7267 key_checktunnelsanity(sav, family, src, dst)
7268         struct secasvar *sav;
7269         u_int family;
7270         caddr_t src;
7271         caddr_t dst;
7272 {
7273         /* sanity check */
7274         if (sav->sah == NULL)
7275                 panic("sav->sah == NULL at key_checktunnelsanity");
7276
7277         /* XXX: check inner IP header */
7278
7279         return 1;
7280 }
7281
7282 #if 0
7283 #define hostnamelen     strlen(hostname)
7284
7285 /*
7286  * Get FQDN for the host.
7287  * If the administrator configured hostname (by hostname(1)) without
7288  * domain name, returns nothing.
7289  */
7290 static const char *
7291 key_getfqdn()
7292 {
7293         int i;
7294         int hasdot;
7295         static char fqdn[MAXHOSTNAMELEN + 1];
7296
7297         if (!hostnamelen)
7298                 return NULL;
7299
7300         /* check if it comes with domain name. */
7301         hasdot = 0;
7302         for (i = 0; i < hostnamelen; i++) {
7303                 if (hostname[i] == '.')
7304                         hasdot++;
7305         }
7306         if (!hasdot)
7307                 return NULL;
7308
7309         /* NOTE: hostname may not be NUL-terminated. */
7310         bzero(fqdn, sizeof(fqdn));
7311         bcopy(hostname, fqdn, hostnamelen);
7312         fqdn[hostnamelen] = '\0';
7313         return fqdn;
7314 }
7315
7316 /*
7317  * get username@FQDN for the host/user.
7318  */
7319 static const char *
7320 key_getuserfqdn()
7321 {
7322         const char *host;
7323         static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
7324         struct proc *p = curproc;
7325         char *q;
7326
7327         if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
7328                 return NULL;
7329         if (!(host = key_getfqdn()))
7330                 return NULL;
7331
7332         /* NOTE: s_login may not be-NUL terminated. */
7333         bzero(userfqdn, sizeof(userfqdn));
7334         bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
7335         userfqdn[MAXLOGNAME] = '\0';    /* safeguard */
7336         q = userfqdn + strlen(userfqdn);
7337         *q++ = '@';
7338         bcopy(host, q, strlen(host));
7339         q += strlen(host);
7340         *q++ = '\0';
7341
7342         return userfqdn;
7343 }
7344 #endif
7345
7346 /* record data transfer on SA, and update timestamps */
7347 void
7348 key_sa_recordxfer(sav, m)
7349         struct secasvar *sav;
7350         struct mbuf *m;
7351 {
7352         if (!sav)
7353                 panic("key_sa_recordxfer called with sav == NULL");
7354         if (!m)
7355                 panic("key_sa_recordxfer called with m == NULL");
7356         if (!sav->lft_c)
7357                 return;
7358
7359         /*
7360          * XXX Currently, there is a difference of bytes size
7361          * between inbound and outbound processing.
7362          */
7363         sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7364         /* to check bytes lifetime is done in key_timehandler(). */
7365
7366         /*
7367          * We use the number of packets as the unit of
7368          * sadb_lifetime_allocations.  We increment the variable
7369          * whenever {esp,ah}_{in,out}put is called.
7370          */
7371         sav->lft_c->sadb_lifetime_allocations++;
7372         /* XXX check for expires? */
7373
7374         /*
7375          * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7376          * in seconds.  HARD and SOFT lifetime are measured by the time
7377          * difference (again in seconds) from sadb_lifetime_usetime.
7378          *
7379          *      usetime
7380          *      v     expire   expire
7381          * -----+-----+--------+---> t
7382          *      <--------------> HARD
7383          *      <-----> SOFT
7384          */
7385     {
7386         struct timeval tv;
7387         microtime(&tv);
7388         sav->lft_c->sadb_lifetime_usetime = tv.tv_sec;
7389         /* XXX check for expires? */
7390     }
7391
7392         return;
7393 }
7394
7395 /* dumb version */
7396 void
7397 key_sa_routechange(dst)
7398         struct sockaddr *dst;
7399 {
7400         struct secashead *sah;
7401         struct route *ro;
7402
7403         LIST_FOREACH(sah, &sahtree, chain) {
7404                 ro = &sah->sa_route;
7405                 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7406                  && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7407                         RTFREE(ro->ro_rt);
7408                         ro->ro_rt = (struct rtentry *)NULL;
7409                 }
7410         }
7411
7412         return;
7413 }
7414
7415 static void
7416 key_sa_chgstate(sav, state)
7417         struct secasvar *sav;
7418         u_int8_t state;
7419 {
7420         if (sav == NULL)
7421                 panic("key_sa_chgstate called with sav == NULL");
7422
7423         if (sav->state == state)
7424                 return;
7425
7426         if (__LIST_CHAINED(sav))
7427                 LIST_REMOVE(sav, chain);
7428
7429         sav->state = state;
7430         LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7431 }
7432
7433 void
7434 key_sa_stir_iv(sav)
7435         struct secasvar *sav;
7436 {
7437
7438         if (!sav->iv)
7439                 panic("key_sa_stir_iv called with sav == NULL");
7440         key_randomfill(sav->iv, sav->ivlen);
7441 }
7442
7443 /* XXX too much? */
7444 static struct mbuf *
7445 key_alloc_mbuf(l)
7446         int l;
7447 {
7448         struct mbuf *m = NULL, *n;
7449         int len, t;
7450
7451         len = l;
7452         while (len > 0) {
7453                 MGET(n, MB_DONTWAIT, MT_DATA);
7454                 if (n && len > MLEN)
7455                         MCLGET(n, MB_DONTWAIT);
7456                 if (!n) {
7457                         m_freem(m);
7458                         return NULL;
7459                 }
7460
7461                 n->m_next = NULL;
7462                 n->m_len = 0;
7463                 n->m_len = M_TRAILINGSPACE(n);
7464                 /* use the bottom of mbuf, hoping we can prepend afterwards */
7465                 if (n->m_len > len) {
7466                         t = (n->m_len - len) & ~(sizeof(long) - 1);
7467                         n->m_data += t;
7468                         n->m_len = len;
7469                 }
7470
7471                 len -= n->m_len;
7472
7473                 if (m)
7474                         m_cat(m, n);
7475                 else
7476                         m = n;
7477         }
7478
7479         return m;
7480 }