ifnet: Properly protect if_multiaddrs using ifnet serializers
[dragonfly.git] / sys / netproto / ipsec / key.c
1 /*      $FreeBSD: src/sys/netipsec/key.c,v 1.3.2.1 2003/01/24 05:11:35 sam Exp $        */
2 /*      $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
3
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 /*
34  * This code is referd to RFC 2367
35  */
36
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/mbuf.h>
46 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/malloc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/errno.h>
53 #include <sys/proc.h>
54 #include <sys/queue.h>
55 #include <sys/syslog.h>
56
57 #include <net/if.h>
58 #include <net/route.h>
59 #include <net/raw_cb.h>
60
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/in_var.h>
65
66 #ifdef INET6
67 #include <netinet/ip6.h>
68 #include <netinet6/in6_var.h>
69 #include <netinet6/ip6_var.h>
70 #endif /* INET6 */
71
72 #ifdef INET
73 #include <netinet/in_pcb.h>
74 #endif
75 #ifdef INET6
76 #include <netinet6/in6_pcb.h>
77 #endif /* INET6 */
78
79 #include <net/pfkeyv2.h>
80 #include <netproto/ipsec/keydb.h>
81 #include <netproto/ipsec/key.h>
82 #include <netproto/ipsec/keysock.h>
83 #include <netproto/ipsec/key_debug.h>
84
85 #include <netproto/ipsec/ipsec.h>
86 #ifdef INET6
87 #include <netproto/ipsec/ipsec6.h>
88 #endif
89
90 #include <netproto/ipsec/xform.h>
91
92 #include <machine/stdarg.h>
93
94 /* randomness */
95 #include <sys/random.h>
96
97 #include <net/net_osdep.h>
98
99 #define FULLMASK        0xff
100 #define _BITS(bytes)    ((bytes) << 3)
101
102 /*
103  * Note on SA reference counting:
104  * - SAs that are not in DEAD state will have (total external reference + 1)
105  *   following value in reference count field.  they cannot be freed and are
106  *   referenced from SA header.
107  * - SAs that are in DEAD state will have (total external reference)
108  *   in reference count field.  they are ready to be freed.  reference from
109  *   SA header will be removed in key_delsav(), when the reference count
110  *   field hits 0 (= no external reference other than from SA header.
111  */
112
113 #ifndef IPSEC_DEBUG2
114 static struct callout key_timehandler_ch;
115 #endif
116 u_int32_t key_debug_level = 0;
117 static u_int key_spi_trycnt = 1000;
118 static u_int32_t key_spi_minval = 0x100;
119 static u_int32_t key_spi_maxval = 0x0fffffff;   /* XXX */
120 static u_int32_t policy_id = 0;
121 static u_int key_int_random = 60;       /*interval to initialize randseed,1(m)*/
122 static u_int key_larval_lifetime = 30;  /* interval to expire acquiring, 30(s)*/
123 static int key_blockacq_count = 10;     /* counter for blocking SADB_ACQUIRE.*/
124 static int key_blockacq_lifetime = 20;  /* lifetime for blocking SADB_ACQUIRE.*/
125 static int key_prefered_oldsa = 1;      /* prefered old sa rather than new sa.*/
126
127 static u_int32_t acq_seq = 0;
128 static int key_tick_init_random = 0;
129
130 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];     /* SPD */
131 static LIST_HEAD(_sahtree, secashead) sahtree;                  /* SAD */
132 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
133                                                         /* registed list */
134 #ifndef IPSEC_NONBLOCK_ACQUIRE
135 static LIST_HEAD(_acqtree, secacq) acqtree;             /* acquiring list */
136 #endif
137 static LIST_HEAD(_spacqtree, secspacq) spacqtree;       /* SP acquiring list */
138
139 /* search order for SAs */
140 static u_int saorder_state_valid[] = {
141         SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
142         /*
143          * This order is important because we must select the oldest SA
144          * for outbound processing.  For inbound, This is not important.
145          */
146 };
147 static u_int saorder_state_alive[] = {
148         /* except DEAD */
149         SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
150 };
151 static u_int saorder_state_any[] = {
152         SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
153         SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
154 };
155
156 static const int minsize[] = {
157         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
158         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
159         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
160         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
161         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
162         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_SRC */
163         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_DST */
164         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_PROXY */
165         sizeof(struct sadb_key),        /* SADB_EXT_KEY_AUTH */
166         sizeof(struct sadb_key),        /* SADB_EXT_KEY_ENCRYPT */
167         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_SRC */
168         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_DST */
169         sizeof(struct sadb_sens),       /* SADB_EXT_SENSITIVITY */
170         sizeof(struct sadb_prop),       /* SADB_EXT_PROPOSAL */
171         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_AUTH */
172         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_ENCRYPT */
173         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
174         0,                              /* SADB_X_EXT_KMPRIVATE */
175         sizeof(struct sadb_x_policy),   /* SADB_X_EXT_POLICY */
176         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
177 };
178 static const int maxsize[] = {
179         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
180         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
181         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
182         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
183         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
184         0,                              /* SADB_EXT_ADDRESS_SRC */
185         0,                              /* SADB_EXT_ADDRESS_DST */
186         0,                              /* SADB_EXT_ADDRESS_PROXY */
187         0,                              /* SADB_EXT_KEY_AUTH */
188         0,                              /* SADB_EXT_KEY_ENCRYPT */
189         0,                              /* SADB_EXT_IDENTITY_SRC */
190         0,                              /* SADB_EXT_IDENTITY_DST */
191         0,                              /* SADB_EXT_SENSITIVITY */
192         0,                              /* SADB_EXT_PROPOSAL */
193         0,                              /* SADB_EXT_SUPPORTED_AUTH */
194         0,                              /* SADB_EXT_SUPPORTED_ENCRYPT */
195         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
196         0,                              /* SADB_X_EXT_KMPRIVATE */
197         0,                              /* SADB_X_EXT_POLICY */
198         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
199 };
200
201 static int ipsec_esp_keymin = 256;
202 static int ipsec_esp_auth = 0;
203 static int ipsec_ah_keymin = 128;
204
205 #ifdef SYSCTL_DECL
206 SYSCTL_DECL(_net_key);
207 #endif
208
209 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,        debug,  CTLFLAG_RW, \
210         &key_debug_level,       0,      "");
211
212 /* max count of trial for the decision of spi value */
213 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,            spi_trycnt,     CTLFLAG_RW, \
214         &key_spi_trycnt,        0,      "");
215
216 /* minimum spi value to allocate automatically. */
217 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,      spi_minval,     CTLFLAG_RW, \
218         &key_spi_minval,        0,      "");
219
220 /* maximun spi value to allocate automatically. */
221 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,      spi_maxval,     CTLFLAG_RW, \
222         &key_spi_maxval,        0,      "");
223
224 /* interval to initialize randseed */
225 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,     CTLFLAG_RW, \
226         &key_int_random,        0,      "");
227
228 /* lifetime for larval SA */
229 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,    larval_lifetime, CTLFLAG_RW, \
230         &key_larval_lifetime,   0,      "");
231
232 /* counter for blocking to send SADB_ACQUIRE to IKEd */
233 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,     blockacq_count, CTLFLAG_RW, \
234         &key_blockacq_count,    0,      "");
235
236 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
237 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,  blockacq_lifetime, CTLFLAG_RW, \
238         &key_blockacq_lifetime, 0,      "");
239
240 /* ESP auth */
241 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,   esp_auth, CTLFLAG_RW, \
242         &ipsec_esp_auth,        0,      "");
243
244 /* minimum ESP key length */
245 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW, \
246         &ipsec_esp_keymin,      0,      "");
247
248 /* minimum AH key length */
249 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,  ah_keymin, CTLFLAG_RW, \
250         &ipsec_ah_keymin,       0,      "");
251
252 /* perfered old SA rather than new SA */
253 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,     prefered_oldsa, CTLFLAG_RW,\
254         &key_prefered_oldsa,    0,      "");
255
256 #define __LIST_CHAINED(elm) \
257         (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
258 #define LIST_INSERT_TAIL(head, elm, type, field) \
259 do {\
260         struct type *curelm = LIST_FIRST(head); \
261         if (curelm == NULL) {\
262                 LIST_INSERT_HEAD(head, elm, field); \
263         } else { \
264                 while (LIST_NEXT(curelm, field)) \
265                         curelm = LIST_NEXT(curelm, field);\
266                 LIST_INSERT_AFTER(curelm, elm, field);\
267         }\
268 } while (0)
269
270 #define KEY_CHKSASTATE(head, sav, name) \
271 do { \
272         if ((head) != (sav)) {                                          \
273                 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
274                         (name), (head), (sav)));                        \
275                 continue;                                               \
276         }                                                               \
277 } while (0)
278
279 #define KEY_CHKSPDIR(head, sp, name) \
280 do { \
281         if ((head) != (sp)) {                                           \
282                 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
283                         "anyway continue.\n",                           \
284                         (name), (head), (sp)));                         \
285         }                                                               \
286 } while (0)
287
288 MALLOC_DEFINE(M_SECA, "key mgmt", "security associations, key management");
289
290 #if 1
291 #define KMALLOC(p, t, n)                                                     \
292         ((p) = (t) kmalloc((unsigned long)(n), M_SECA, M_INTWAIT | M_NULLOK))
293 #define KFREE(p)                                                             \
294         kfree((caddr_t)(p), M_SECA)
295 #else
296 #define KMALLOC(p, t, n) \
297 do { \
298         ((p) = (t)kmalloc((unsigned long)(n), M_SECA, M_INTWAIT | M_NULLOK)); \
299         kprintf("%s %d: %p <- KMALLOC(%s, %d)\n",                             \
300                 __FILE__, __LINE__, (p), #t, n);                             \
301 } while (0)
302
303 #define KFREE(p)                                                             \
304         do {                                                                 \
305                 kprintf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p));   \
306                 kfree((caddr_t)(p), M_SECA);                                  \
307         } while (0)
308 #endif
309
310 /*
311  * set parameters into secpolicyindex buffer.
312  * Must allocate secpolicyindex buffer passed to this function.
313  */
314 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
315 do { \
316         bzero((idx), sizeof(struct secpolicyindex));                         \
317         (idx)->dir = (_dir);                                                 \
318         (idx)->prefs = (ps);                                                 \
319         (idx)->prefd = (pd);                                                 \
320         (idx)->ul_proto = (ulp);                                             \
321         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
322         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
323 } while (0)
324
325 /*
326  * set parameters into secasindex buffer.
327  * Must allocate secasindex buffer before calling this function.
328  */
329 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
330 do { \
331         bzero((idx), sizeof(struct secasindex));                             \
332         (idx)->proto = (p);                                                  \
333         (idx)->mode = (m);                                                   \
334         (idx)->reqid = (r);                                                  \
335         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
336         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
337 } while (0)
338
339 /* key statistics */
340 struct _keystat {
341         u_long getspi_count; /* the avarage of count to try to get new SPI */
342 } keystat;
343
344 struct sadb_msghdr {
345         struct sadb_msg *msg;
346         struct sadb_ext *ext[SADB_EXT_MAX + 1];
347         int extoff[SADB_EXT_MAX + 1];
348         int extlen[SADB_EXT_MAX + 1];
349 };
350
351 static struct secasvar *key_allocsa_policy (const struct secasindex *);
352 static void key_freesp_so (struct secpolicy **);
353 static struct secasvar *key_do_allocsa_policy (struct secashead *, u_int);
354 static void key_delsp (struct secpolicy *);
355 static struct secpolicy *key_getsp (struct secpolicyindex *);
356 static struct secpolicy *key_getspbyid (u_int32_t);
357 static u_int32_t key_newreqid (void);
358 static struct mbuf *key_gather_mbuf (struct mbuf *,
359         const struct sadb_msghdr *, int, int, ...);
360 static int key_spdadd (struct socket *, struct mbuf *,
361         const struct sadb_msghdr *);
362 static u_int32_t key_getnewspid (void);
363 static int key_spddelete (struct socket *, struct mbuf *,
364         const struct sadb_msghdr *);
365 static int key_spddelete2 (struct socket *, struct mbuf *,
366         const struct sadb_msghdr *);
367 static int key_spdget (struct socket *, struct mbuf *,
368         const struct sadb_msghdr *);
369 static int key_spdflush (struct socket *, struct mbuf *,
370         const struct sadb_msghdr *);
371 static int key_spddump (struct socket *, struct mbuf *,
372         const struct sadb_msghdr *);
373 static struct mbuf *key_setdumpsp (struct secpolicy *,
374         u_int8_t, u_int32_t, u_int32_t);
375 static u_int key_getspreqmsglen (struct secpolicy *);
376 static int key_spdexpire (struct secpolicy *);
377 static struct secashead *key_newsah (struct secasindex *);
378 static void key_delsah (struct secashead *);
379 static struct secasvar *key_newsav (struct mbuf *,
380         const struct sadb_msghdr *, struct secashead *, int *,
381         const char*, int);
382 #define KEY_NEWSAV(m, sadb, sah, e)                             \
383         key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
384 static void key_delsav (struct secasvar *);
385 static struct secashead *key_getsah (struct secasindex *);
386 static struct secasvar *key_checkspidup (struct secasindex *, u_int32_t);
387 static struct secasvar *key_getsavbyspi (struct secashead *, u_int32_t);
388 static int key_setsaval (struct secasvar *, struct mbuf *,
389         const struct sadb_msghdr *);
390 static int key_mature (struct secasvar *);
391 static struct mbuf *key_setdumpsa (struct secasvar *, u_int8_t,
392         u_int8_t, u_int32_t, u_int32_t);
393 static struct mbuf *key_setsadbmsg (u_int8_t, u_int16_t, u_int8_t,
394         u_int32_t, pid_t, u_int16_t);
395 static struct mbuf *key_setsadbsa (struct secasvar *);
396 static struct mbuf *key_setsadbaddr (u_int16_t,
397         const struct sockaddr *, u_int8_t, u_int16_t);
398 #if 0
399 static struct mbuf *key_setsadbident (u_int16_t, u_int16_t, caddr_t,
400         int, u_int64_t);
401 #endif
402 static struct mbuf *key_setsadbxsa2 (u_int8_t, u_int32_t, u_int32_t);
403 static struct mbuf *key_setsadbxpolicy (u_int16_t, u_int8_t,
404         u_int32_t);
405 static void *key_newbuf (const void *, u_int);
406 #ifdef INET6
407 static int key_ismyaddr6 (struct sockaddr_in6 *);
408 #endif
409
410 /* flags for key_cmpsaidx() */
411 #define CMP_HEAD        1       /* protocol, addresses. */
412 #define CMP_MODE_REQID  2       /* additionally HEAD, reqid, mode. */
413 #define CMP_REQID       3       /* additionally HEAD, reaid. */
414 #define CMP_EXACTLY     4       /* all elements. */
415 static int key_cmpsaidx
416         (const struct secasindex *, const struct secasindex *, int);
417
418 static int key_cmpspidx_exactly
419         (struct secpolicyindex *, struct secpolicyindex *);
420 static int key_cmpspidx_withmask
421         (struct secpolicyindex *, struct secpolicyindex *);
422 static int key_sockaddrcmp (const struct sockaddr *, const struct sockaddr *, int);
423 static int key_bbcmp (const void *, const void *, u_int);
424 static void key_srandom (void);
425 static u_int16_t key_satype2proto (u_int8_t);
426 static u_int8_t key_proto2satype (u_int16_t);
427
428 static int key_getspi (struct socket *, struct mbuf *,
429         const struct sadb_msghdr *);
430 static u_int32_t key_do_getnewspi (struct sadb_spirange *,
431                                         struct secasindex *);
432 static int key_update (struct socket *, struct mbuf *,
433         const struct sadb_msghdr *);
434 #ifdef IPSEC_DOSEQCHECK
435 static struct secasvar *key_getsavbyseq (struct secashead *, u_int32_t);
436 #endif
437 static int key_add (struct socket *, struct mbuf *,
438         const struct sadb_msghdr *);
439 static int key_setident (struct secashead *, struct mbuf *,
440         const struct sadb_msghdr *);
441 static struct mbuf *key_getmsgbuf_x1 (struct mbuf *,
442         const struct sadb_msghdr *);
443 static int key_delete (struct socket *, struct mbuf *,
444         const struct sadb_msghdr *);
445 static int key_get (struct socket *, struct mbuf *,
446         const struct sadb_msghdr *);
447
448 static void key_getcomb_setlifetime (struct sadb_comb *);
449 static struct mbuf *key_getcomb_esp (void);
450 static struct mbuf *key_getcomb_ah (void);
451 static struct mbuf *key_getcomb_ipcomp (void);
452 static struct mbuf *key_getprop (const struct secasindex *);
453
454 static int key_acquire (const struct secasindex *, struct secpolicy *);
455 #ifndef IPSEC_NONBLOCK_ACQUIRE
456 static struct secacq *key_newacq (const struct secasindex *);
457 static struct secacq *key_getacq (const struct secasindex *);
458 static struct secacq *key_getacqbyseq (u_int32_t);
459 #endif
460 static struct secspacq *key_newspacq (struct secpolicyindex *);
461 static struct secspacq *key_getspacq (struct secpolicyindex *);
462 static int key_acquire2 (struct socket *, struct mbuf *,
463         const struct sadb_msghdr *);
464 static int key_register (struct socket *, struct mbuf *,
465         const struct sadb_msghdr *);
466 static int key_expire (struct secasvar *);
467 static int key_flush (struct socket *, struct mbuf *,
468         const struct sadb_msghdr *);
469 static int key_dump (struct socket *, struct mbuf *,
470         const struct sadb_msghdr *);
471 static int key_promisc (struct socket *, struct mbuf *,
472         const struct sadb_msghdr *);
473 static int key_senderror (struct socket *, struct mbuf *, int);
474 static int key_validate_ext (const struct sadb_ext *, int);
475 static int key_align (struct mbuf *, struct sadb_msghdr *);
476 #if 0
477 static const char *key_getfqdn (void);
478 static const char *key_getuserfqdn (void);
479 #endif
480 static void key_sa_chgstate (struct secasvar *, u_int8_t);
481 static struct mbuf *key_alloc_mbuf (int);
482
483 #define SA_ADDREF(p) do {                                               \
484         (p)->refcnt++;                                                  \
485         KASSERT((p)->refcnt != 0,                                       \
486                 ("SA refcnt overflow at %s:%u", __FILE__, __LINE__));   \
487 } while (0)
488 #define SA_DELREF(p) do {                                               \
489         KASSERT((p)->refcnt > 0,                                        \
490                 ("SA refcnt underflow at %s:%u", __FILE__, __LINE__));  \
491         (p)->refcnt--;                                                  \
492 } while (0)
493
494 #define SP_ADDREF(p) do {                                               \
495         (p)->refcnt++;                                                  \
496         KASSERT((p)->refcnt != 0,                                       \
497                 ("SP refcnt overflow at %s:%u", __FILE__, __LINE__));   \
498 } while (0)
499 #define SP_DELREF(p) do {                                               \
500         KASSERT((p)->refcnt > 0,                                        \
501                 ("SP refcnt underflow at %s:%u", __FILE__, __LINE__));  \
502         (p)->refcnt--;                                                  \
503 } while (0)
504
505 /*
506  * Return 0 when there are known to be no SP's for the specified
507  * direction.  Otherwise return 1.  This is used by IPsec code
508  * to optimize performance.
509  */
510 int
511 key_havesp(u_int dir)
512 {
513         return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
514                 LIST_FIRST(&sptree[dir]) != NULL : 1);
515 }
516
517 /* %%% IPsec policy management */
518 /*
519  * allocating a SP for OUTBOUND or INBOUND packet.
520  * Must call key_freesp() later.
521  * OUT: NULL:   not found
522  *      others: found and return the pointer.
523  */
524 struct secpolicy *
525 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
526 {
527         struct secpolicy *sp;
528         
529
530         KASSERT(spidx != NULL, ("key_allocsp: null spidx"));
531         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
532                 ("key_allocsp: invalid direction %u", dir));
533
534         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
535                 kprintf("DP key_allocsp from %s:%u\n", where, tag));
536
537         /* get a SP entry */
538         crit_enter();
539         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
540                  kprintf("*** objects\n"); kdebug_secpolicyindex(spidx));
541
542         LIST_FOREACH(sp, &sptree[dir], chain) {
543                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
544                          kprintf("*** in SPD\n");
545                          kdebug_secpolicyindex(&sp->spidx));
546
547                 if (sp->state == IPSEC_SPSTATE_DEAD)
548                         continue;
549                 if (key_cmpspidx_withmask(&sp->spidx, spidx))
550                         goto found;
551         }
552         sp = NULL;
553 found:
554         if (sp) {
555                 /* sanity check */
556                 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
557
558                 /* found a SPD entry */
559                 sp->lastused = time_second;
560                 SP_ADDREF(sp);
561         }
562         crit_exit();
563
564         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
565                 kprintf("DP key_allocsp return SP:%p (ID=%u) refcnt %u\n",
566                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
567         return sp;
568 }
569
570 /*
571  * allocating a SP for OUTBOUND or INBOUND packet.
572  * Must call key_freesp() later.
573  * OUT: NULL:   not found
574  *      others: found and return the pointer.
575  */
576 struct secpolicy *
577 key_allocsp2(u_int32_t spi,
578              union sockaddr_union *dst,
579              u_int8_t proto,
580              u_int dir,
581              const char* where, int tag)
582 {
583         struct secpolicy *sp;
584         
585
586         KASSERT(dst != NULL, ("key_allocsp2: null dst"));
587         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
588                 ("key_allocsp2: invalid direction %u", dir));
589
590         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
591                 kprintf("DP key_allocsp2 from %s:%u\n", where, tag));
592
593         /* get a SP entry */
594         crit_enter();
595         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
596                 kprintf("*** objects\n");
597                 kprintf("spi %u proto %u dir %u\n", spi, proto, dir);
598                 kdebug_sockaddr(&dst->sa));
599
600         LIST_FOREACH(sp, &sptree[dir], chain) {
601                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
602                         kprintf("*** in SPD\n");
603                         kdebug_secpolicyindex(&sp->spidx));
604
605                 if (sp->state == IPSEC_SPSTATE_DEAD)
606                         continue;
607                 /* compare simple values, then dst address */
608                 if (sp->spidx.ul_proto != proto)
609                         continue;
610                 /* NB: spi's must exist and match */
611                 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
612                         continue;
613                 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
614                         goto found;
615         }
616         sp = NULL;
617 found:
618         if (sp) {
619                 /* sanity check */
620                 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp2");
621
622                 /* found a SPD entry */
623                 sp->lastused = time_second;
624                 SP_ADDREF(sp);
625         }
626         crit_exit();
627
628         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
629                 kprintf("DP key_allocsp2 return SP:%p (ID=%u) refcnt %u\n",
630                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
631         return sp;
632 }
633
634 /*
635  * return a policy that matches this particular inbound packet.
636  * XXX slow
637  */
638 struct secpolicy *
639 key_gettunnel(const struct sockaddr *osrc,
640               const struct sockaddr *odst,
641               const struct sockaddr *isrc,
642               const struct sockaddr *idst,
643               const char* where, int tag)
644 {
645         struct secpolicy *sp;
646         const int dir = IPSEC_DIR_INBOUND;
647         
648         struct ipsecrequest *r1, *r2, *p;
649         struct secpolicyindex spidx;
650
651         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
652                 kprintf("DP key_gettunnel from %s:%u\n", where, tag));
653
654         if (isrc->sa_family != idst->sa_family) {
655                 ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
656                         isrc->sa_family, idst->sa_family));
657                 sp = NULL;
658                 goto done;
659         }
660
661         crit_enter();
662         LIST_FOREACH(sp, &sptree[dir], chain) {
663                 if (sp->state == IPSEC_SPSTATE_DEAD)
664                         continue;
665
666                 r1 = r2 = NULL;
667                 for (p = sp->req; p; p = p->next) {
668                         if (p->saidx.mode != IPSEC_MODE_TUNNEL)
669                                 continue;
670
671                         r1 = r2;
672                         r2 = p;
673
674                         if (!r1) {
675                                 /* here we look at address matches only */
676                                 spidx = sp->spidx;
677                                 if (isrc->sa_len > sizeof(spidx.src) ||
678                                     idst->sa_len > sizeof(spidx.dst))
679                                         continue;
680                                 bcopy(isrc, &spidx.src, isrc->sa_len);
681                                 bcopy(idst, &spidx.dst, idst->sa_len);
682                                 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
683                                         continue;
684                         } else {
685                                 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
686                                     key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
687                                         continue;
688                         }
689
690                         if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
691                             key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
692                                 continue;
693
694                         goto found;
695                 }
696         }
697         sp = NULL;
698 found:
699         if (sp) {
700                 sp->lastused = time_second;
701                 SP_ADDREF(sp);
702         }
703         crit_exit();
704 done:
705         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
706                 kprintf("DP key_gettunnel return SP:%p (ID=%u) refcnt %u\n",
707                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
708         return sp;
709 }
710
711 /*
712  * allocating an SA entry for an *OUTBOUND* packet.
713  * checking each request entries in SP, and acquire an SA if need.
714  * OUT: 0: there are valid requests.
715  *      ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
716  */
717 int
718 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
719 {
720         u_int level;
721         int error;
722
723         KASSERT(isr != NULL, ("key_checkrequest: null isr"));
724         KASSERT(saidx != NULL, ("key_checkrequest: null saidx"));
725         KASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
726                 saidx->mode == IPSEC_MODE_TUNNEL,
727                 ("key_checkrequest: unexpected policy %u", saidx->mode));
728
729         /* get current level */
730         level = ipsec_get_reqlevel(isr);
731
732         /*
733          * XXX guard against protocol callbacks from the crypto
734          * thread as they reference ipsecrequest.sav which we
735          * temporarily null out below.  Need to rethink how we
736          * handle bundled SA's in the callback thread.
737          */
738 #if 0
739         /*
740          * We do allocate new SA only if the state of SA in the holder is
741          * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
742          */
743         if (isr->sav != NULL) {
744                 if (isr->sav->sah == NULL)
745                         panic("key_checkrequest: sah is null.");
746                 if (isr->sav == (struct secasvar *)LIST_FIRST(
747                             &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
748                         KEY_FREESAV(&isr->sav);
749                         isr->sav = NULL;
750                 }
751         }
752 #else
753         /*
754          * we free any SA stashed in the IPsec request because a different
755          * SA may be involved each time this request is checked, either
756          * because new SAs are being configured, or this request is
757          * associated with an unconnected datagram socket, or this request
758          * is associated with a system default policy.
759          *
760          * The operation may have negative impact to performance.  We may
761          * want to check cached SA carefully, rather than picking new SA
762          * every time.
763          */
764         if (isr->sav != NULL) {
765                 KEY_FREESAV(&isr->sav);
766                 isr->sav = NULL;
767         }
768 #endif
769
770         /*
771          * new SA allocation if no SA found.
772          * key_allocsa_policy should allocate the oldest SA available.
773          * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
774          */
775         if (isr->sav == NULL)
776                 isr->sav = key_allocsa_policy(saidx);
777
778         /* When there is SA. */
779         if (isr->sav != NULL) {
780                 if (isr->sav->state != SADB_SASTATE_MATURE &&
781                     isr->sav->state != SADB_SASTATE_DYING)
782                         return EINVAL;
783                 return 0;
784         }
785
786         /* there is no SA */
787         error = key_acquire(saidx, isr->sp);
788         if (error != 0) {
789                 /* XXX What should I do ? */
790                 ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
791                         "from key_acquire.\n", error));
792                 return error;
793         }
794
795         if (level != IPSEC_LEVEL_REQUIRE) {
796                 /* XXX sigh, the interface to this routine is botched */
797                 KASSERT(isr->sav == NULL, ("key_checkrequest: unexpected SA"));
798                 return 0;
799         } else {
800                 return ENOENT;
801         }
802 }
803
804 /*
805  * allocating a SA for policy entry from SAD.
806  * NOTE: searching SAD of aliving state.
807  * OUT: NULL:   not found.
808  *      others: found and return the pointer.
809  */
810 static struct secasvar *
811 key_allocsa_policy(const struct secasindex *saidx)
812 {
813         struct secashead *sah;
814         struct secasvar *sav;
815         u_int stateidx, state;
816
817         LIST_FOREACH(sah, &sahtree, chain) {
818                 if (sah->state == SADB_SASTATE_DEAD)
819                         continue;
820                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
821                         goto found;
822         }
823
824         return NULL;
825
826     found:
827
828         /* search valid state */
829         for (stateidx = 0;
830              stateidx < NELEM(saorder_state_valid);
831              stateidx++) {
832
833                 state = saorder_state_valid[stateidx];
834
835                 sav = key_do_allocsa_policy(sah, state);
836                 if (sav != NULL)
837                         return sav;
838         }
839
840         return NULL;
841 }
842
843 /*
844  * searching SAD with direction, protocol, mode and state.
845  * called by key_allocsa_policy().
846  * OUT:
847  *      NULL    : not found
848  *      others  : found, pointer to a SA.
849  */
850 static struct secasvar *
851 key_do_allocsa_policy(struct secashead *sah, u_int state)
852 {
853         struct secasvar *sav, *nextsav, *candidate = NULL, *d;
854
855         LIST_FOREACH_MUTABLE(sav, &sah->savtree[state], chain, nextsav) {
856                 /* sanity check */
857                 KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
858
859                 /* initialize */
860                 if (candidate == NULL) {
861                         candidate = sav;
862                         continue;
863                 }
864
865                 /* Which SA is the better ? */
866
867                 /* sanity check 2 */
868                 if (candidate->lft_c == NULL || sav->lft_c == NULL)
869                         panic("key_do_allocsa_policy: "
870                                 "lifetime_current is NULL.\n");
871
872                 /* What the best method is to compare ? */
873                 if (key_prefered_oldsa) {
874                         if (candidate->lft_c->sadb_lifetime_addtime >
875                                         sav->lft_c->sadb_lifetime_addtime) {
876                                 candidate = sav;
877                         }
878                         continue;
879                 }
880
881                 /* prefered new sa rather than old sa */
882                 if (candidate->lft_c->sadb_lifetime_addtime <
883                                 sav->lft_c->sadb_lifetime_addtime) {
884                         d = candidate;
885                         candidate = sav;
886                 } else
887                         d = sav;
888
889                 /*
890                  * prepared to delete the SA when there is more
891                  * suitable candidate and the lifetime of the SA is not
892                  * permanent.
893                  */
894                 if (d->lft_c->sadb_lifetime_addtime != 0) {
895                         struct mbuf *m, *result;
896                         u_int8_t satype;
897
898                         key_sa_chgstate(d, SADB_SASTATE_DEAD);
899
900                         KASSERT(d->refcnt > 0,
901                                 ("key_do_allocsa_policy: bogus ref count"));
902
903                         satype = key_proto2satype(d->sah->saidx.proto);
904                         if (satype == 0)
905                                 goto msgfail;
906
907                         m = key_setsadbmsg(SADB_DELETE, 0, satype, 0, 0,
908                                            d->refcnt - 1);
909                         if (!m)
910                                 goto msgfail;
911                         result = m;
912
913                         /* set sadb_address for saidx's. */
914                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
915                                 &d->sah->saidx.src.sa,
916                                 d->sah->saidx.src.sa.sa_len << 3,
917                                 IPSEC_ULPROTO_ANY);
918                         if (!m)
919                                 goto msgfail;
920                         m_cat(result, m);
921
922                         /* set sadb_address for saidx's. */
923                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
924                                 &d->sah->saidx.dst.sa,
925                                 d->sah->saidx.dst.sa.sa_len << 3,
926                                 IPSEC_ULPROTO_ANY);
927                         if (!m)
928                                 goto msgfail;
929                         m_cat(result, m);
930
931                         /* create SA extension */
932                         m = key_setsadbsa(d);
933                         if (!m)
934                                 goto msgfail;
935                         m_cat(result, m);
936
937                         if (result->m_len < sizeof(struct sadb_msg)) {
938                                 result = m_pullup(result,
939                                                 sizeof(struct sadb_msg));
940                                 if (result == NULL)
941                                         goto msgfail;
942                         }
943
944                         result->m_pkthdr.len = m_lengthm(result, NULL);
945                         mtod(result, struct sadb_msg *)->sadb_msg_len =
946                                 PFKEY_UNIT64(result->m_pkthdr.len);
947
948                         if (key_sendup_mbuf(NULL, result,
949                                         KEY_SENDUP_REGISTERED))
950                                 goto msgfail;
951                  msgfail:
952                         KEY_FREESAV(&d);
953                 }
954         }
955
956         if (candidate) {
957                 SA_ADDREF(candidate);
958                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
959                          kprintf("DP allocsa_policy cause refcnt++:%d SA:%p\n",
960                                 candidate->refcnt, candidate));
961         }
962         return candidate;
963 }
964
965 /*
966  * allocating a usable SA entry for a *INBOUND* packet.
967  * Must call key_freesav() later.
968  * OUT: positive:       pointer to a usable sav (i.e. MATURE or DYING state).
969  *      NULL:           not found, or error occured.
970  *
971  * In the comparison, no source address is used--for RFC2401 conformance.
972  * To quote, from section 4.1:
973  *      A security association is uniquely identified by a triple consisting
974  *      of a Security Parameter Index (SPI), an IP Destination Address, and a
975  *      security protocol (AH or ESP) identifier.
976  * Note that, however, we do need to keep source address in IPsec SA.
977  * IKE specification and PF_KEY specification do assume that we
978  * keep source address in IPsec SA.  We see a tricky situation here.
979  */
980 struct secasvar *
981 key_allocsa(
982         union sockaddr_union *dst,
983         u_int proto,
984         u_int32_t spi,
985         const char* where, int tag)
986 {
987         struct secashead *sah;
988         struct secasvar *sav;
989         u_int stateidx, state;
990         
991
992         KASSERT(dst != NULL, ("key_allocsa: null dst address"));
993
994         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
995                 kprintf("DP key_allocsa from %s:%u\n", where, tag));
996
997         /*
998          * searching SAD.
999          * XXX: to be checked internal IP header somewhere.  Also when
1000          * IPsec tunnel packet is received.  But ESP tunnel mode is
1001          * encrypted so we can't check internal IP header.
1002          */
1003         crit_enter();
1004         LIST_FOREACH(sah, &sahtree, chain) {
1005                 /* search valid state */
1006                 for (stateidx = 0;
1007                      stateidx < NELEM(saorder_state_valid);
1008                      stateidx++) {
1009                         state = saorder_state_valid[stateidx];
1010                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
1011                                 /* sanity check */
1012                                 KEY_CHKSASTATE(sav->state, state, "key_allocsav");
1013                                 /* do not return entries w/ unusable state */
1014                                 if (sav->state != SADB_SASTATE_MATURE &&
1015                                     sav->state != SADB_SASTATE_DYING)
1016                                         continue;
1017                                 if (proto != sav->sah->saidx.proto)
1018                                         continue;
1019                                 if (spi != sav->spi)
1020                                         continue;
1021 #if 0   /* don't check src */
1022                                 /* check src address */
1023                                 if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1024                                         continue;
1025 #endif
1026                                 /* check dst address */
1027                                 if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1028                                         continue;
1029                                 SA_ADDREF(sav);
1030                                 goto done;
1031                         }
1032                 }
1033         }
1034         sav = NULL;
1035 done:
1036         crit_exit();
1037
1038         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1039                 kprintf("DP key_allocsa return SA:%p; refcnt %u\n",
1040                         sav, sav ? sav->refcnt : 0));
1041         return sav;
1042 }
1043
1044 /*
1045  * Must be called after calling key_allocsp().
1046  * For both the packet without socket and key_freeso().
1047  */
1048 void
1049 _key_freesp(struct secpolicy **spp, const char* where, int tag)
1050 {
1051         struct secpolicy *sp = *spp;
1052
1053         KASSERT(sp != NULL, ("key_freesp: null sp"));
1054
1055         SP_DELREF(sp);
1056
1057         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1058                 kprintf("DP key_freesp SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1059                         sp, sp->id, where, tag, sp->refcnt));
1060
1061         if (sp->refcnt == 0) {
1062                 *spp = NULL;
1063                 key_delsp(sp);
1064         }
1065 }
1066
1067 /*
1068  * Must be called after calling key_allocsp().
1069  * For the packet with socket.
1070  */
1071 void
1072 key_freeso(struct socket *so)
1073 {
1074         /* sanity check */
1075         KASSERT(so != NULL, ("key_freeso: null so"));
1076
1077         switch (so->so_proto->pr_domain->dom_family) {
1078 #ifdef INET
1079         case PF_INET:
1080             {
1081                 struct inpcb *pcb = so->so_pcb;
1082
1083                 /* Does it have a PCB ? */
1084                 if (pcb == NULL)
1085                         return;
1086                 key_freesp_so(&pcb->inp_sp->sp_in);
1087                 key_freesp_so(&pcb->inp_sp->sp_out);
1088             }
1089                 break;
1090 #endif
1091 #ifdef INET6
1092         case PF_INET6:
1093             {
1094 #ifdef HAVE_NRL_INPCB
1095                 struct inpcb *pcb  = so->so_pcb;
1096
1097                 /* Does it have a PCB ? */
1098                 if (pcb == NULL)
1099                         return;
1100                 key_freesp_so(&pcb->inp_sp->sp_in);
1101                 key_freesp_so(&pcb->inp_sp->sp_out);
1102 #else
1103                 struct in6pcb *pcb  = so->so_pcb;
1104
1105                 /* Does it have a PCB ? */
1106                 if (pcb == NULL)
1107                         return;
1108                 key_freesp_so(&pcb->in6p_sp->sp_in);
1109                 key_freesp_so(&pcb->in6p_sp->sp_out);
1110 #endif
1111             }
1112                 break;
1113 #endif /* INET6 */
1114         default:
1115                 ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
1116                     so->so_proto->pr_domain->dom_family));
1117                 return;
1118         }
1119 }
1120
1121 static void
1122 key_freesp_so(struct secpolicy **sp)
1123 {
1124         KASSERT(sp != NULL && *sp != NULL, ("key_freesp_so: null sp"));
1125
1126         if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1127             (*sp)->policy == IPSEC_POLICY_BYPASS)
1128                 return;
1129
1130         KASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1131                 ("key_freesp_so: invalid policy %u", (*sp)->policy));
1132         KEY_FREESP(sp);
1133 }
1134
1135 /*
1136  * Must be called after calling key_allocsa().
1137  * This function is called by key_freesp() to free some SA allocated
1138  * for a policy.
1139  */
1140 void
1141 key_freesav(struct secasvar **psav, const char* where, int tag)
1142 {
1143         struct secasvar *sav = *psav;
1144
1145         KASSERT(sav != NULL, ("key_freesav: null sav"));
1146
1147         SA_DELREF(sav);
1148
1149         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1150                 kprintf("DP key_freesav SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1151                         sav, ntohl(sav->spi), where, tag, sav->refcnt));
1152
1153         if (sav->refcnt == 0) {
1154                 *psav = NULL;
1155                 key_delsav(sav);
1156         }
1157 }
1158
1159 /* %%% SPD management */
1160 /*
1161  * free security policy entry.
1162  */
1163 static void
1164 key_delsp(struct secpolicy *sp)
1165 {
1166         
1167
1168         KASSERT(sp != NULL, ("key_delsp: null sp"));
1169
1170         sp->state = IPSEC_SPSTATE_DEAD;
1171
1172         KASSERT(sp->refcnt == 0,
1173                 ("key_delsp: SP with references deleted (refcnt %u)",
1174                 sp->refcnt));
1175
1176         crit_enter();
1177         /* remove from SP index */
1178         if (__LIST_CHAINED(sp))
1179                 LIST_REMOVE(sp, chain);
1180
1181     {
1182         struct ipsecrequest *isr = sp->req, *nextisr;
1183
1184         while (isr != NULL) {
1185                 if (isr->sav != NULL) {
1186                         KEY_FREESAV(&isr->sav);
1187                         isr->sav = NULL;
1188                 }
1189
1190                 nextisr = isr->next;
1191                 KFREE(isr);
1192                 isr = nextisr;
1193         }
1194     }
1195
1196         KFREE(sp);
1197
1198         crit_exit();
1199 }
1200
1201 /*
1202  * search SPD
1203  * OUT: NULL    : not found
1204  *      others  : found, pointer to a SP.
1205  */
1206 static struct secpolicy *
1207 key_getsp(struct secpolicyindex *spidx)
1208 {
1209         struct secpolicy *sp;
1210
1211         KASSERT(spidx != NULL, ("key_getsp: null spidx"));
1212
1213         LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
1214                 if (sp->state == IPSEC_SPSTATE_DEAD)
1215                         continue;
1216                 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1217                         SP_ADDREF(sp);
1218                         return sp;
1219                 }
1220         }
1221
1222         return NULL;
1223 }
1224
1225 /*
1226  * get SP by index.
1227  * OUT: NULL    : not found
1228  *      others  : found, pointer to a SP.
1229  */
1230 static struct secpolicy *
1231 key_getspbyid(u_int32_t id)
1232 {
1233         struct secpolicy *sp;
1234
1235         LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
1236                 if (sp->state == IPSEC_SPSTATE_DEAD)
1237                         continue;
1238                 if (sp->id == id) {
1239                         SP_ADDREF(sp);
1240                         return sp;
1241                 }
1242         }
1243
1244         LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
1245                 if (sp->state == IPSEC_SPSTATE_DEAD)
1246                         continue;
1247                 if (sp->id == id) {
1248                         SP_ADDREF(sp);
1249                         return sp;
1250                 }
1251         }
1252
1253         return NULL;
1254 }
1255
1256 struct secpolicy *
1257 key_newsp(const char* where, int tag)
1258 {
1259         struct secpolicy *newsp = NULL;
1260
1261         newsp = kmalloc(sizeof(struct secpolicy), M_SECA,
1262                         M_INTWAIT | M_ZERO | M_NULLOK);
1263         if (newsp) {
1264                 newsp->refcnt = 1;
1265                 newsp->req = NULL;
1266         }
1267
1268         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1269                 kprintf("DP key_newsp from %s:%u return SP:%p\n",
1270                         where, tag, newsp));
1271         return newsp;
1272 }
1273
1274 /*
1275  * create secpolicy structure from sadb_x_policy structure.
1276  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1277  * so must be set properly later.
1278  */
1279 struct secpolicy *
1280 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1281 {
1282         struct secpolicy *newsp;
1283
1284         /* sanity check */
1285         if (xpl0 == NULL)
1286                 panic("key_msg2sp: NULL pointer was passed.");
1287         if (len < sizeof(*xpl0))
1288                 panic("key_msg2sp: invalid length.");
1289         if (len != PFKEY_EXTLEN(xpl0)) {
1290                 ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
1291                 *error = EINVAL;
1292                 return NULL;
1293         }
1294
1295         if ((newsp = KEY_NEWSP()) == NULL) {
1296                 *error = ENOBUFS;
1297                 return NULL;
1298         }
1299
1300         newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1301         newsp->policy = xpl0->sadb_x_policy_type;
1302
1303         /* check policy */
1304         switch (xpl0->sadb_x_policy_type) {
1305         case IPSEC_POLICY_DISCARD:
1306         case IPSEC_POLICY_NONE:
1307         case IPSEC_POLICY_ENTRUST:
1308         case IPSEC_POLICY_BYPASS:
1309                 newsp->req = NULL;
1310                 break;
1311
1312         case IPSEC_POLICY_IPSEC:
1313             {
1314                 int tlen;
1315                 struct sadb_x_ipsecrequest *xisr;
1316                 struct ipsecrequest **p_isr = &newsp->req;
1317
1318                 /* validity check */
1319                 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1320                         ipseclog((LOG_DEBUG,
1321                             "key_msg2sp: Invalid msg length.\n"));
1322                         KEY_FREESP(&newsp);
1323                         *error = EINVAL;
1324                         return NULL;
1325                 }
1326
1327                 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1328                 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1329
1330                 while (tlen > 0) {
1331                         /* length check */
1332                         if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1333                                 ipseclog((LOG_DEBUG, "key_msg2sp: "
1334                                         "invalid ipsecrequest length.\n"));
1335                                 KEY_FREESP(&newsp);
1336                                 *error = EINVAL;
1337                                 return NULL;
1338                         }
1339
1340                         /* allocate request buffer */
1341                         KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
1342                         if ((*p_isr) == NULL) {
1343                                 ipseclog((LOG_DEBUG,
1344                                     "key_msg2sp: No more memory.\n"));
1345                                 KEY_FREESP(&newsp);
1346                                 *error = ENOBUFS;
1347                                 return NULL;
1348                         }
1349                         bzero(*p_isr, sizeof(**p_isr));
1350
1351                         /* set values */
1352                         (*p_isr)->next = NULL;
1353
1354                         switch (xisr->sadb_x_ipsecrequest_proto) {
1355                         case IPPROTO_ESP:
1356                         case IPPROTO_AH:
1357                         case IPPROTO_IPCOMP:
1358                                 break;
1359                         default:
1360                                 ipseclog((LOG_DEBUG,
1361                                     "key_msg2sp: invalid proto type=%u\n",
1362                                     xisr->sadb_x_ipsecrequest_proto));
1363                                 KEY_FREESP(&newsp);
1364                                 *error = EPROTONOSUPPORT;
1365                                 return NULL;
1366                         }
1367                         (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1368
1369                         switch (xisr->sadb_x_ipsecrequest_mode) {
1370                         case IPSEC_MODE_TRANSPORT:
1371                         case IPSEC_MODE_TUNNEL:
1372                                 break;
1373                         case IPSEC_MODE_ANY:
1374                         default:
1375                                 ipseclog((LOG_DEBUG,
1376                                     "key_msg2sp: invalid mode=%u\n",
1377                                     xisr->sadb_x_ipsecrequest_mode));
1378                                 KEY_FREESP(&newsp);
1379                                 *error = EINVAL;
1380                                 return NULL;
1381                         }
1382                         (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1383
1384                         switch (xisr->sadb_x_ipsecrequest_level) {
1385                         case IPSEC_LEVEL_DEFAULT:
1386                         case IPSEC_LEVEL_USE:
1387                         case IPSEC_LEVEL_REQUIRE:
1388                                 break;
1389                         case IPSEC_LEVEL_UNIQUE:
1390                                 /* validity check */
1391                                 /*
1392                                  * If range violation of reqid, kernel will
1393                                  * update it, don't refuse it.
1394                                  */
1395                                 if (xisr->sadb_x_ipsecrequest_reqid
1396                                                 > IPSEC_MANUAL_REQID_MAX) {
1397                                         ipseclog((LOG_DEBUG,
1398                                             "key_msg2sp: reqid=%d range "
1399                                             "violation, updated by kernel.\n",
1400                                             xisr->sadb_x_ipsecrequest_reqid));
1401                                         xisr->sadb_x_ipsecrequest_reqid = 0;
1402                                 }
1403
1404                                 /* allocate new reqid id if reqid is zero. */
1405                                 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1406                                         u_int32_t reqid;
1407                                         if ((reqid = key_newreqid()) == 0) {
1408                                                 KEY_FREESP(&newsp);
1409                                                 *error = ENOBUFS;
1410                                                 return NULL;
1411                                         }
1412                                         (*p_isr)->saidx.reqid = reqid;
1413                                         xisr->sadb_x_ipsecrequest_reqid = reqid;
1414                                 } else {
1415                                 /* set it for manual keying. */
1416                                         (*p_isr)->saidx.reqid =
1417                                                 xisr->sadb_x_ipsecrequest_reqid;
1418                                 }
1419                                 break;
1420
1421                         default:
1422                                 ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
1423                                         xisr->sadb_x_ipsecrequest_level));
1424                                 KEY_FREESP(&newsp);
1425                                 *error = EINVAL;
1426                                 return NULL;
1427                         }
1428                         (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1429
1430                         /* set IP addresses if there */
1431                         if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1432                                 struct sockaddr *paddr;
1433
1434                                 paddr = (struct sockaddr *)(xisr + 1);
1435
1436                                 /* validity check */
1437                                 if (paddr->sa_len
1438                                     > sizeof((*p_isr)->saidx.src)) {
1439                                         ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1440                                                 "address length.\n"));
1441                                         KEY_FREESP(&newsp);
1442                                         *error = EINVAL;
1443                                         return NULL;
1444                                 }
1445                                 bcopy(paddr, &(*p_isr)->saidx.src,
1446                                         paddr->sa_len);
1447
1448                                 paddr = (struct sockaddr *)((caddr_t)paddr
1449                                                         + paddr->sa_len);
1450
1451                                 /* validity check */
1452                                 if (paddr->sa_len
1453                                     > sizeof((*p_isr)->saidx.dst)) {
1454                                         ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1455                                                 "address length.\n"));
1456                                         KEY_FREESP(&newsp);
1457                                         *error = EINVAL;
1458                                         return NULL;
1459                                 }
1460                                 bcopy(paddr, &(*p_isr)->saidx.dst,
1461                                         paddr->sa_len);
1462                         }
1463
1464                         (*p_isr)->sav = NULL;
1465                         (*p_isr)->sp = newsp;
1466
1467                         /* initialization for the next. */
1468                         p_isr = &(*p_isr)->next;
1469                         tlen -= xisr->sadb_x_ipsecrequest_len;
1470
1471                         /* validity check */
1472                         if (tlen < 0) {
1473                                 ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
1474                                 KEY_FREESP(&newsp);
1475                                 *error = EINVAL;
1476                                 return NULL;
1477                         }
1478
1479                         xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1480                                          + xisr->sadb_x_ipsecrequest_len);
1481                 }
1482             }
1483                 break;
1484         default:
1485                 ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
1486                 KEY_FREESP(&newsp);
1487                 *error = EINVAL;
1488                 return NULL;
1489         }
1490
1491         *error = 0;
1492         return newsp;
1493 }
1494
1495 static u_int32_t
1496 key_newreqid(void)
1497 {
1498         static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1499
1500         auto_reqid = (auto_reqid == ~0
1501                         ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1502
1503         /* XXX should be unique check */
1504
1505         return auto_reqid;
1506 }
1507
1508 /*
1509  * copy secpolicy struct to sadb_x_policy structure indicated.
1510  */
1511 struct mbuf *
1512 key_sp2msg(struct secpolicy *sp)
1513 {
1514         struct sadb_x_policy *xpl;
1515         int tlen;
1516         caddr_t p;
1517         struct mbuf *m;
1518
1519         /* sanity check. */
1520         if (sp == NULL)
1521                 panic("key_sp2msg: NULL pointer was passed.");
1522
1523         tlen = key_getspreqmsglen(sp);
1524
1525         m = key_alloc_mbuf(tlen);
1526         if (!m || m->m_next) {  /*XXX*/
1527                 if (m)
1528                         m_freem(m);
1529                 return NULL;
1530         }
1531
1532         m->m_len = tlen;
1533         m->m_next = NULL;
1534         xpl = mtod(m, struct sadb_x_policy *);
1535         bzero(xpl, tlen);
1536
1537         xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1538         xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1539         xpl->sadb_x_policy_type = sp->policy;
1540         xpl->sadb_x_policy_dir = sp->spidx.dir;
1541         xpl->sadb_x_policy_id = sp->id;
1542         p = (caddr_t)xpl + sizeof(*xpl);
1543
1544         /* if is the policy for ipsec ? */
1545         if (sp->policy == IPSEC_POLICY_IPSEC) {
1546                 struct sadb_x_ipsecrequest *xisr;
1547                 struct ipsecrequest *isr;
1548
1549                 for (isr = sp->req; isr != NULL; isr = isr->next) {
1550
1551                         xisr = (struct sadb_x_ipsecrequest *)p;
1552
1553                         xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1554                         xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1555                         xisr->sadb_x_ipsecrequest_level = isr->level;
1556                         xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1557
1558                         p += sizeof(*xisr);
1559                         bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1560                         p += isr->saidx.src.sa.sa_len;
1561                         bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1562                         p += isr->saidx.src.sa.sa_len;
1563
1564                         xisr->sadb_x_ipsecrequest_len =
1565                                 PFKEY_ALIGN8(sizeof(*xisr)
1566                                         + isr->saidx.src.sa.sa_len
1567                                         + isr->saidx.dst.sa.sa_len);
1568                 }
1569         }
1570
1571         return m;
1572 }
1573
1574 /* m will not be freed nor modified */
1575 static struct mbuf *
1576 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1577         int ndeep, int nitem, ...)
1578 {
1579         __va_list ap;
1580         int idx;
1581         int i;
1582         struct mbuf *result = NULL, *n;
1583         int len;
1584
1585         if (m == NULL || mhp == NULL)
1586                 panic("null pointer passed to key_gather");
1587
1588         __va_start(ap, nitem);
1589         for (i = 0; i < nitem; i++) {
1590                 idx = __va_arg(ap, int);
1591                 if (idx < 0 || idx > SADB_EXT_MAX)
1592                         goto fail;
1593                 /* don't attempt to pull empty extension */
1594                 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1595                         continue;
1596                 if (idx != SADB_EXT_RESERVED  &&
1597                     (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1598                         continue;
1599
1600                 if (idx == SADB_EXT_RESERVED) {
1601                         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1602 #ifdef DIAGNOSTIC
1603                         if (len > MHLEN)
1604                                 panic("assumption failed");
1605 #endif
1606                         MGETHDR(n, MB_DONTWAIT, MT_DATA);
1607                         if (!n)
1608                                 goto fail;
1609                         n->m_len = len;
1610                         n->m_next = NULL;
1611                         m_copydata(m, 0, sizeof(struct sadb_msg),
1612                             mtod(n, caddr_t));
1613                 } else if (i < ndeep) {
1614                         len = mhp->extlen[idx];
1615                         n = key_alloc_mbuf(len);
1616                         if (!n || n->m_next) {  /*XXX*/
1617                                 if (n)
1618                                         m_freem(n);
1619                                 goto fail;
1620                         }
1621                         m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1622                             mtod(n, caddr_t));
1623                 } else {
1624                         n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1625                             MB_DONTWAIT);
1626                 }
1627                 if (n == NULL)
1628                         goto fail;
1629
1630                 if (result)
1631                         m_cat(result, n);
1632                 else
1633                         result = n;
1634         }
1635         __va_end(ap);
1636
1637         if (result->m_flags & M_PKTHDR)
1638                 result->m_pkthdr.len = m_lengthm(result, NULL);
1639
1640         return result;
1641
1642 fail:
1643         m_freem(result);
1644         return NULL;
1645 }
1646
1647 /*
1648  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1649  * add an entry to SP database, when received
1650  *   <base, address(SD), (lifetime(H),) policy>
1651  * from the user(?).
1652  * Adding to SP database,
1653  * and send
1654  *   <base, address(SD), (lifetime(H),) policy>
1655  * to the socket which was send.
1656  *
1657  * SPDADD set a unique policy entry.
1658  * SPDSETIDX like SPDADD without a part of policy requests.
1659  * SPDUPDATE replace a unique policy entry.
1660  *
1661  * m will always be freed.
1662  */
1663 static int
1664 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1665 {
1666         struct sadb_address *src0, *dst0;
1667         struct sadb_x_policy *xpl0, *xpl;
1668         struct sadb_lifetime *lft = NULL;
1669         struct secpolicyindex spidx;
1670         struct secpolicy *newsp;
1671         struct sockaddr *saddr, *daddr;
1672         int error;
1673
1674         /* sanity check */
1675         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
1676                 panic("key_spdadd: NULL pointer is passed.");
1677
1678         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1679             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1680             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1681                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1682                 return key_senderror(so, m, EINVAL);
1683         }
1684         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1685             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1686             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1687                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1688                 return key_senderror(so, m, EINVAL);
1689         }
1690         if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1691                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1692                         < sizeof(struct sadb_lifetime)) {
1693                         ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1694                         return key_senderror(so, m, EINVAL);
1695                 }
1696                 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1697         }
1698
1699         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1700         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1701         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1702
1703         /* make secindex */
1704         /* XXX boundary check against sa_len */
1705         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1706                         src0 + 1,
1707                         dst0 + 1,
1708                         src0->sadb_address_prefixlen,
1709                         dst0->sadb_address_prefixlen,
1710                         src0->sadb_address_proto,
1711                         &spidx);
1712
1713         /* checking the direciton. */
1714         switch (xpl0->sadb_x_policy_dir) {
1715         case IPSEC_DIR_INBOUND:
1716         case IPSEC_DIR_OUTBOUND:
1717                 break;
1718         default:
1719                 ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
1720                 mhp->msg->sadb_msg_errno = EINVAL;
1721                 return 0;
1722         }
1723
1724         /* check policy */
1725         /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1726         if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1727          || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1728                 ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
1729                 return key_senderror(so, m, EINVAL);
1730         }
1731
1732         /* policy requests are mandatory when action is ipsec. */
1733         if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1734          && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1735          && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1736                 ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
1737                 return key_senderror(so, m, EINVAL);
1738         }
1739
1740         /*
1741          * checking there is SP already or not.
1742          * SPDUPDATE doesn't depend on whether there is a SP or not.
1743          * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1744          * then error.
1745          */
1746         newsp = key_getsp(&spidx);
1747         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1748                 if (newsp) {
1749                         newsp->state = IPSEC_SPSTATE_DEAD;
1750                         KEY_FREESP(&newsp);
1751                 }
1752         } else {
1753                 if (newsp != NULL) {
1754                         KEY_FREESP(&newsp);
1755                         ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
1756                         return key_senderror(so, m, EEXIST);
1757                 }
1758         }
1759
1760         /* allocation new SP entry */
1761         if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1762                 return key_senderror(so, m, error);
1763         }
1764
1765         if ((newsp->id = key_getnewspid()) == 0) {
1766                 KFREE(newsp);
1767                 return key_senderror(so, m, ENOBUFS);
1768         }
1769
1770         /* XXX boundary check against sa_len */
1771         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1772                         src0 + 1,
1773                         dst0 + 1,
1774                         src0->sadb_address_prefixlen,
1775                         dst0->sadb_address_prefixlen,
1776                         src0->sadb_address_proto,
1777                         &newsp->spidx);
1778
1779         /* sanity check on addr pair */
1780         saddr = (struct sockaddr *)(src0 + 1);
1781         daddr = (struct sockaddr *)(dst0 + 1);
1782         if (saddr->sa_family != daddr->sa_family) {
1783                 KFREE(newsp);
1784                 return key_senderror(so, m, EINVAL);
1785         }
1786         if (saddr->sa_len != daddr->sa_len) {
1787                 KFREE(newsp);
1788                 return key_senderror(so, m, EINVAL);
1789         }
1790 #if 1
1791         if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1792                 if (saddr->sa_family != newsp->req->saidx.src.sa.sa_family) {
1793                         KFREE(newsp);
1794                         return key_senderror(so, m, EINVAL);
1795                 }
1796         }
1797         if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1798                 if (daddr->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1799                         KFREE(newsp);
1800                         return key_senderror(so, m, EINVAL);
1801                 }
1802         }
1803 #endif
1804
1805         newsp->created = time_second;
1806         newsp->lastused = newsp->created;
1807         newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1808         newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1809
1810         newsp->refcnt = 1;      /* do not reclaim until I say I do */
1811         newsp->state = IPSEC_SPSTATE_ALIVE;
1812         LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1813
1814         /* delete the entry in spacqtree */
1815         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1816                 struct secspacq *spacq;
1817                 if ((spacq = key_getspacq(&spidx)) != NULL) {
1818                         /* reset counter in order to deletion by timehandler. */
1819                         spacq->created = time_second;
1820                         spacq->count = 0;
1821                 }
1822         }
1823
1824     {
1825         struct mbuf *n, *mpolicy;
1826         struct sadb_msg *newmsg;
1827         int off;
1828
1829         /* create new sadb_msg to reply. */
1830         if (lft) {
1831                 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1832                     SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1833                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1834         } else {
1835                 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1836                     SADB_X_EXT_POLICY,
1837                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1838         }
1839         if (!n)
1840                 return key_senderror(so, m, ENOBUFS);
1841
1842         if (n->m_len < sizeof(*newmsg)) {
1843                 n = m_pullup(n, sizeof(*newmsg));
1844                 if (!n)
1845                         return key_senderror(so, m, ENOBUFS);
1846         }
1847         newmsg = mtod(n, struct sadb_msg *);
1848         newmsg->sadb_msg_errno = 0;
1849         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1850
1851         off = 0;
1852         mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1853             sizeof(*xpl), &off);
1854         if (mpolicy == NULL) {
1855                 /* n is already freed */
1856                 return key_senderror(so, m, ENOBUFS);
1857         }
1858         xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1859         if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1860                 m_freem(n);
1861                 return key_senderror(so, m, EINVAL);
1862         }
1863         xpl->sadb_x_policy_id = newsp->id;
1864
1865         m_freem(m);
1866         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1867     }
1868 }
1869
1870 /*
1871  * get new policy id.
1872  * OUT:
1873  *      0:      failure.
1874  *      others: success.
1875  */
1876 static u_int32_t
1877 key_getnewspid(void)
1878 {
1879         u_int32_t newid = 0;
1880         int count = key_spi_trycnt;     /* XXX */
1881         struct secpolicy *sp;
1882
1883         /* when requesting to allocate spi ranged */
1884         while (count--) {
1885                 newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
1886
1887                 if ((sp = key_getspbyid(newid)) == NULL)
1888                         break;
1889
1890                 KEY_FREESP(&sp);
1891         }
1892
1893         if (count == 0 || newid == 0) {
1894                 ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
1895                 return 0;
1896         }
1897
1898         return newid;
1899 }
1900
1901 /*
1902  * SADB_SPDDELETE processing
1903  * receive
1904  *   <base, address(SD), policy(*)>
1905  * from the user(?), and set SADB_SASTATE_DEAD,
1906  * and send,
1907  *   <base, address(SD), policy(*)>
1908  * to the ikmpd.
1909  * policy(*) including direction of policy.
1910  *
1911  * m will always be freed.
1912  */
1913 static int
1914 key_spddelete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1915 {
1916         struct sadb_address *src0, *dst0;
1917         struct sadb_x_policy *xpl0;
1918         struct secpolicyindex spidx;
1919         struct secpolicy *sp;
1920
1921         /* sanity check */
1922         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
1923                 panic("key_spddelete: NULL pointer is passed.");
1924
1925         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1926             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1927             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1928                 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
1929                 return key_senderror(so, m, EINVAL);
1930         }
1931         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1932             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1933             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1934                 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
1935                 return key_senderror(so, m, EINVAL);
1936         }
1937
1938         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1939         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1940         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1941
1942         /* make secindex */
1943         /* XXX boundary check against sa_len */
1944         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1945                         src0 + 1,
1946                         dst0 + 1,
1947                         src0->sadb_address_prefixlen,
1948                         dst0->sadb_address_prefixlen,
1949                         src0->sadb_address_proto,
1950                         &spidx);
1951
1952         /* checking the direciton. */
1953         switch (xpl0->sadb_x_policy_dir) {
1954         case IPSEC_DIR_INBOUND:
1955         case IPSEC_DIR_OUTBOUND:
1956                 break;
1957         default:
1958                 ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
1959                 return key_senderror(so, m, EINVAL);
1960         }
1961
1962         /* Is there SP in SPD ? */
1963         if ((sp = key_getsp(&spidx)) == NULL) {
1964                 ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
1965                 return key_senderror(so, m, EINVAL);
1966         }
1967
1968         /* save policy id to buffer to be returned. */
1969         xpl0->sadb_x_policy_id = sp->id;
1970
1971         sp->state = IPSEC_SPSTATE_DEAD;
1972         KEY_FREESP(&sp);
1973
1974     {
1975         struct mbuf *n;
1976         struct sadb_msg *newmsg;
1977
1978         /* create new sadb_msg to reply. */
1979         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
1980             SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1981         if (!n)
1982                 return key_senderror(so, m, ENOBUFS);
1983
1984         newmsg = mtod(n, struct sadb_msg *);
1985         newmsg->sadb_msg_errno = 0;
1986         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1987
1988         m_freem(m);
1989         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1990     }
1991 }
1992
1993 /*
1994  * SADB_SPDDELETE2 processing
1995  * receive
1996  *   <base, policy(*)>
1997  * from the user(?), and set SADB_SASTATE_DEAD,
1998  * and send,
1999  *   <base, policy(*)>
2000  * to the ikmpd.
2001  * policy(*) including direction of policy.
2002  *
2003  * m will always be freed.
2004  */
2005 static int
2006 key_spddelete2(struct socket *so, struct mbuf *m,
2007                const struct sadb_msghdr *mhp)
2008 {
2009         u_int32_t id;
2010         struct secpolicy *sp;
2011
2012         /* sanity check */
2013         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2014                 panic("key_spddelete2: NULL pointer is passed.");
2015
2016         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2017             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2018                 ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
2019                 key_senderror(so, m, EINVAL);
2020                 return 0;
2021         }
2022
2023         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2024
2025         /* Is there SP in SPD ? */
2026         if ((sp = key_getspbyid(id)) == NULL) {
2027                 ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
2028                 key_senderror(so, m, EINVAL);
2029         }
2030
2031         sp->state = IPSEC_SPSTATE_DEAD;
2032         KEY_FREESP(&sp);
2033
2034     {
2035         struct mbuf *n;
2036         struct sadb_msg *newmsg;
2037         int off, len;
2038
2039         /* create new sadb_msg to reply. */
2040         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2041
2042         if (len > MCLBYTES)
2043                 return key_senderror(so, m, ENOBUFS);
2044         n = m_getb(len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
2045         if (!n)
2046                 return key_senderror(so, m, ENOBUFS);
2047         n->m_len = len;
2048
2049         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t));
2050         off = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2051
2052 #ifdef DIAGNOSTIC
2053         if (off != len)
2054                 panic("length inconsistency in key_spddelete2");
2055 #endif
2056
2057         n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2058             mhp->extlen[SADB_X_EXT_POLICY], MB_DONTWAIT);
2059         if (!n->m_next) {
2060                 m_freem(n);
2061                 return key_senderror(so, m, ENOBUFS);
2062         }
2063         n->m_pkthdr.len = m_lengthm(n, NULL);
2064
2065         newmsg = mtod(n, struct sadb_msg *);
2066         newmsg->sadb_msg_errno = 0;
2067         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2068
2069         m_freem(m);
2070         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2071     }
2072 }
2073
2074 /*
2075  * SADB_X_GET processing
2076  * receive
2077  *   <base, policy(*)>
2078  * from the user(?),
2079  * and send,
2080  *   <base, address(SD), policy>
2081  * to the ikmpd.
2082  * policy(*) including direction of policy.
2083  *
2084  * m will always be freed.
2085  */
2086 static int
2087 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2088 {
2089         u_int32_t id;
2090         struct secpolicy *sp;
2091         struct mbuf *n;
2092
2093         /* sanity check */
2094         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2095                 panic("key_spdget: NULL pointer is passed.");
2096
2097         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2098             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2099                 ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
2100                 return key_senderror(so, m, EINVAL);
2101         }
2102
2103         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2104
2105         /* Is there SP in SPD ? */
2106         if ((sp = key_getspbyid(id)) == NULL) {
2107                 ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
2108                 return key_senderror(so, m, ENOENT);
2109         }
2110
2111         n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2112         if (n != NULL) {
2113                 m_freem(m);
2114                 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2115         } else
2116                 return key_senderror(so, m, ENOBUFS);
2117 }
2118
2119 /*
2120  * SADB_X_SPDACQUIRE processing.
2121  * Acquire policy and SA(s) for a *OUTBOUND* packet.
2122  * send
2123  *   <base, policy(*)>
2124  * to KMD, and expect to receive
2125  *   <base> with SADB_X_SPDACQUIRE if error occured,
2126  * or
2127  *   <base, policy>
2128  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2129  * policy(*) is without policy requests.
2130  *
2131  *    0     : succeed
2132  *    others: error number
2133  */
2134 int
2135 key_spdacquire(struct secpolicy *sp)
2136 {
2137         struct mbuf *result = NULL, *m;
2138         struct secspacq *newspacq;
2139         int error;
2140
2141         /* sanity check */
2142         if (sp == NULL)
2143                 panic("key_spdacquire: NULL pointer is passed.");
2144         if (sp->req != NULL)
2145                 panic("key_spdacquire: called but there is request.");
2146         if (sp->policy != IPSEC_POLICY_IPSEC)
2147                 panic("key_spdacquire: policy mismatched. IPsec is expected.");
2148
2149         /* Get an entry to check whether sent message or not. */
2150         if ((newspacq = key_getspacq(&sp->spidx)) != NULL) {
2151                 if (key_blockacq_count < newspacq->count) {
2152                         /* reset counter and do send message. */
2153                         newspacq->count = 0;
2154                 } else {
2155                         /* increment counter and do nothing. */
2156                         newspacq->count++;
2157                         return 0;
2158                 }
2159         } else {
2160                 /* make new entry for blocking to send SADB_ACQUIRE. */
2161                 if ((newspacq = key_newspacq(&sp->spidx)) == NULL)
2162                         return ENOBUFS;
2163
2164                 /* add to acqtree */
2165                 LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
2166         }
2167
2168         /* create new sadb_msg to reply. */
2169         m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2170         if (!m) {
2171                 error = ENOBUFS;
2172                 goto fail;
2173         }
2174         result = m;
2175         result->m_pkthdr.len = m_lengthm(result, NULL);
2176         mtod(result, struct sadb_msg *)->sadb_msg_len =
2177             PFKEY_UNIT64(result->m_pkthdr.len);
2178
2179         return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2180
2181 fail:
2182         if (result)
2183                 m_freem(result);
2184         return error;
2185 }
2186
2187 /*
2188  * SADB_SPDFLUSH processing
2189  * receive
2190  *   <base>
2191  * from the user, and free all entries in secpctree.
2192  * and send,
2193  *   <base>
2194  * to the user.
2195  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2196  *
2197  * m will always be freed.
2198  */
2199 static int
2200 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2201 {
2202         struct sadb_msg *newmsg;
2203         struct secpolicy *sp;
2204         u_int dir;
2205
2206         /* sanity check */
2207         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2208                 panic("key_spdflush: NULL pointer is passed.");
2209
2210         if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2211                 return key_senderror(so, m, EINVAL);
2212
2213         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2214                 LIST_FOREACH(sp, &sptree[dir], chain) {
2215                         sp->state = IPSEC_SPSTATE_DEAD;
2216                 }
2217         }
2218
2219         if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2220                 ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
2221                 return key_senderror(so, m, ENOBUFS);
2222         }
2223
2224         if (m->m_next)
2225                 m_freem(m->m_next);
2226         m->m_next = NULL;
2227         m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2228         newmsg = mtod(m, struct sadb_msg *);
2229         newmsg->sadb_msg_errno = 0;
2230         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2231
2232         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2233 }
2234
2235 /*
2236  * SADB_SPDDUMP processing
2237  * receive
2238  *   <base>
2239  * from the user, and dump all SP leaves
2240  * and send,
2241  *   <base> .....
2242  * to the ikmpd.
2243  *
2244  * m will always be freed.
2245  */
2246 static int
2247 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2248 {
2249         struct secpolicy *sp;
2250         int cnt;
2251         u_int dir;
2252         struct mbuf *n;
2253
2254         /* sanity check */
2255         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2256                 panic("key_spddump: NULL pointer is passed.");
2257
2258         /* search SPD entry and get buffer size. */
2259         cnt = 0;
2260         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2261                 LIST_FOREACH(sp, &sptree[dir], chain) {
2262                         cnt++;
2263                 }
2264         }
2265
2266         if (cnt == 0)
2267                 return key_senderror(so, m, ENOENT);
2268
2269         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2270                 LIST_FOREACH(sp, &sptree[dir], chain) {
2271                         --cnt;
2272                         n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2273                             mhp->msg->sadb_msg_pid);
2274
2275                         if (n)
2276                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2277                 }
2278         }
2279
2280         m_freem(m);
2281         return 0;
2282 }
2283
2284 static struct mbuf *
2285 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2286               u_int32_t pid)
2287 {
2288         struct mbuf *result = NULL, *m;
2289
2290         m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2291         if (!m)
2292                 goto fail;
2293         result = m;
2294
2295         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2296             &sp->spidx.src.sa, sp->spidx.prefs,
2297             sp->spidx.ul_proto);
2298         if (!m)
2299                 goto fail;
2300         m_cat(result, m);
2301
2302         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2303             &sp->spidx.dst.sa, sp->spidx.prefd,
2304             sp->spidx.ul_proto);
2305         if (!m)
2306                 goto fail;
2307         m_cat(result, m);
2308
2309         m = key_sp2msg(sp);
2310         if (!m)
2311                 goto fail;
2312         m_cat(result, m);
2313
2314         if ((result->m_flags & M_PKTHDR) == 0)
2315                 goto fail;
2316
2317         if (result->m_len < sizeof(struct sadb_msg)) {
2318                 result = m_pullup(result, sizeof(struct sadb_msg));
2319                 if (result == NULL)
2320                         goto fail;
2321         }
2322         result->m_pkthdr.len = m_lengthm(result, NULL);
2323         mtod(result, struct sadb_msg *)->sadb_msg_len =
2324             PFKEY_UNIT64(result->m_pkthdr.len);
2325
2326         return result;
2327
2328 fail:
2329         m_freem(result);
2330         return NULL;
2331 }
2332
2333 /*
2334  * get PFKEY message length for security policy and request.
2335  */
2336 static u_int
2337 key_getspreqmsglen(struct secpolicy *sp)
2338 {
2339         struct ipsecrequest *isr;
2340         u_int tlen, len;
2341
2342         tlen = sizeof(struct sadb_x_policy);
2343
2344         /* if is the policy for ipsec ? */
2345         if (sp->policy != IPSEC_POLICY_IPSEC)
2346                 return tlen;
2347
2348         /* get length of ipsec requests */
2349         for (isr = sp->req; isr != NULL; isr = isr->next) {
2350                 len = sizeof(struct sadb_x_ipsecrequest) +
2351                       isr->saidx.src.sa.sa_len + isr->saidx.dst.sa.sa_len;
2352
2353                 tlen += PFKEY_ALIGN8(len);
2354         }
2355
2356         return tlen;
2357 }
2358
2359 /*
2360  * SADB_SPDEXPIRE processing
2361  * send
2362  *   <base, address(SD), lifetime(CH), policy>
2363  * to KMD by PF_KEY.
2364  *
2365  * OUT: 0       : succeed
2366  *      others  : error number
2367  */
2368 static int
2369 key_spdexpire(struct secpolicy *sp)
2370 {
2371         
2372         struct mbuf *result = NULL, *m;
2373         int len;
2374         int error = -1;
2375         struct sadb_lifetime *lt;
2376
2377         /* XXX: Why do we lock ? */
2378         crit_enter();
2379
2380         /* sanity check */
2381         if (sp == NULL)
2382                 panic("key_spdexpire: NULL pointer is passed.");
2383
2384         /* set msg header */
2385         m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2386         if (!m) {
2387                 error = ENOBUFS;
2388                 goto fail;
2389         }
2390         result = m;
2391
2392         /* create lifetime extension (current and hard) */
2393         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2394         m = key_alloc_mbuf(len);
2395         if (!m || m->m_next) {  /*XXX*/
2396                 if (m)
2397                         m_freem(m);
2398                 error = ENOBUFS;
2399                 goto fail;
2400         }
2401         bzero(mtod(m, caddr_t), len);
2402         lt = mtod(m, struct sadb_lifetime *);
2403         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2404         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2405         lt->sadb_lifetime_allocations = 0;
2406         lt->sadb_lifetime_bytes = 0;
2407         lt->sadb_lifetime_addtime = sp->created;
2408         lt->sadb_lifetime_usetime = sp->lastused;
2409         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2410         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2411         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2412         lt->sadb_lifetime_allocations = 0;
2413         lt->sadb_lifetime_bytes = 0;
2414         lt->sadb_lifetime_addtime = sp->lifetime;
2415         lt->sadb_lifetime_usetime = sp->validtime;
2416         m_cat(result, m);
2417
2418         /* set sadb_address for source */
2419         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2420             &sp->spidx.src.sa,
2421             sp->spidx.prefs, sp->spidx.ul_proto);
2422         if (!m) {
2423                 error = ENOBUFS;
2424                 goto fail;
2425         }
2426         m_cat(result, m);
2427
2428         /* set sadb_address for destination */
2429         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2430             &sp->spidx.dst.sa,
2431             sp->spidx.prefd, sp->spidx.ul_proto);
2432         if (!m) {
2433                 error = ENOBUFS;
2434                 goto fail;
2435         }
2436         m_cat(result, m);
2437
2438         /* set secpolicy */
2439         m = key_sp2msg(sp);
2440         if (!m) {
2441                 error = ENOBUFS;
2442                 goto fail;
2443         }
2444         m_cat(result, m);
2445
2446         if ((result->m_flags & M_PKTHDR) == 0) {
2447                 error = EINVAL;
2448                 goto fail;
2449         }
2450
2451         if (result->m_len < sizeof(struct sadb_msg)) {
2452                 result = m_pullup(result, sizeof(struct sadb_msg));
2453                 if (result == NULL) {
2454                         error = ENOBUFS;
2455                         goto fail;
2456                 }
2457         }
2458         result->m_pkthdr.len = m_lengthm(result, NULL);
2459         mtod(result, struct sadb_msg *)->sadb_msg_len =
2460             PFKEY_UNIT64(result->m_pkthdr.len);
2461
2462         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2463
2464  fail:
2465         if (result)
2466                 m_freem(result);
2467         crit_exit();
2468         return error;
2469 }
2470
2471 /* %%% SAD management */
2472 /*
2473  * allocating a memory for new SA head, and copy from the values of mhp.
2474  * OUT: NULL    : failure due to the lack of memory.
2475  *      others  : pointer to new SA head.
2476  */
2477 static struct secashead *
2478 key_newsah(struct secasindex *saidx)
2479 {
2480         struct secashead *newsah;
2481
2482         KASSERT(saidx != NULL, ("key_newsaidx: null saidx"));
2483
2484         newsah = kmalloc(sizeof(struct secashead), M_SECA, 
2485                         M_INTWAIT | M_ZERO | M_NULLOK);
2486         if (newsah != NULL) {
2487                 int i;
2488                 for (i = 0; i < NELEM(newsah->savtree); i++)
2489                         LIST_INIT(&newsah->savtree[i]);
2490                 newsah->saidx = *saidx;
2491
2492                 /* add to saidxtree */
2493                 newsah->state = SADB_SASTATE_MATURE;
2494                 LIST_INSERT_HEAD(&sahtree, newsah, chain);
2495         }
2496         return(newsah);
2497 }
2498
2499 /*
2500  * Delete SA index and all registered SAs.
2501  */
2502 static void
2503 key_delsah(struct secashead *sah)
2504 {
2505         struct secasvar *sav, *nextsav;
2506         u_int stateidx;
2507         int nzombies = 0;
2508
2509         /* sanity check */
2510         if (sah == NULL)
2511                 panic("key_delsah: NULL pointer is passed.");
2512
2513         crit_enter();
2514
2515         /* searching all SA registerd in the secindex. */
2516         for (stateidx = 0; stateidx < NELEM(saorder_state_any);
2517              stateidx++) {
2518                 u_int state = saorder_state_any[stateidx];
2519
2520                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[state], chain, nextsav)
2521                         if (sav->refcnt == 0) {
2522                                 /* sanity check */
2523                                 KEY_CHKSASTATE(state, sav->state, __func__);
2524                                 KEY_FREESAV(&sav);
2525                         } else {
2526                                 /* give up to delete this SA */
2527                                 nzombies++;
2528                         }
2529         }
2530
2531         /* Delete sah it has are no savs. */
2532         if (nzombies == 0) {
2533                 /* remove from tree of SA index */
2534                 if (__LIST_CHAINED(sah))
2535                         LIST_REMOVE(sah, chain);
2536                 if (sah->sa_route.ro_rt) {
2537                         RTFREE(sah->sa_route.ro_rt);
2538                         sah->sa_route.ro_rt = NULL;
2539                 }
2540                 KFREE(sah);
2541         }
2542
2543         crit_exit();
2544         return;
2545 }
2546
2547 /*
2548  * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
2549  * and copy the values of mhp into new buffer.
2550  * When SAD message type is GETSPI:
2551  *      to set sequence number from acq_seq++,
2552  *      to set zero to SPI.
2553  *      not to call key_setsava().
2554  * OUT: NULL    : fail
2555  *      others  : pointer to new secasvar.
2556  *
2557  * does not modify mbuf.  does not free mbuf on error.
2558  */
2559 static struct secasvar *
2560 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp, struct secashead *sah,
2561            int *errp, const char *where, int tag)
2562 {
2563         struct secasvar *newsav;
2564         const struct sadb_sa *xsa;
2565
2566         /* sanity check */
2567         if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
2568                 panic("key_newsa: NULL pointer is passed.");
2569
2570         KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
2571         if (newsav == NULL) {
2572                 ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
2573                 *errp = ENOBUFS;
2574                 goto done;
2575         }
2576         bzero((caddr_t)newsav, sizeof(struct secasvar));
2577
2578         switch (mhp->msg->sadb_msg_type) {
2579         case SADB_GETSPI:
2580                 newsav->spi = 0;
2581
2582 #ifdef IPSEC_DOSEQCHECK
2583                 /* sync sequence number */
2584                 if (mhp->msg->sadb_msg_seq == 0)
2585                         newsav->seq =
2586                                 (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
2587                 else
2588 #endif
2589                         newsav->seq = mhp->msg->sadb_msg_seq;
2590                 break;
2591
2592         case SADB_ADD:
2593                 /* sanity check */
2594                 if (mhp->ext[SADB_EXT_SA] == NULL) {
2595                         KFREE(newsav), newsav = NULL;
2596                         ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
2597                         *errp = EINVAL;
2598                         goto done;
2599                 }
2600                 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2601                 newsav->spi = xsa->sadb_sa_spi;
2602                 newsav->seq = mhp->msg->sadb_msg_seq;
2603                 break;
2604         default:
2605                 KFREE(newsav), newsav = NULL;
2606                 *errp = EINVAL;
2607                 goto done;
2608         }
2609
2610         /* copy sav values */
2611         if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2612                 *errp = key_setsaval(newsav, m, mhp);
2613                 if (*errp) {
2614                         KFREE(newsav), newsav = NULL;
2615                         goto done;
2616                 }
2617         }
2618
2619         /* reset created */
2620         newsav->created = time_second;
2621         newsav->pid = mhp->msg->sadb_msg_pid;
2622
2623         /* add to satree */
2624         newsav->sah = sah;
2625         newsav->refcnt = 1;
2626         newsav->state = SADB_SASTATE_LARVAL;
2627         LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2628                         secasvar, chain);
2629 done:
2630         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2631                 kprintf("DP key_newsav from %s:%u return SP:%p\n",
2632                         where, tag, newsav));
2633
2634         return newsav;
2635 }
2636
2637 /*
2638  * free() SA variable entry.
2639  */
2640 static void
2641 key_delsav(struct secasvar *sav)
2642 {
2643         KASSERT(sav != NULL, ("key_delsav: null sav"));
2644         KASSERT(sav->refcnt == 0,
2645                 ("key_delsav: reference count %u > 0", sav->refcnt));
2646
2647         /* remove from SA header */
2648         if (__LIST_CHAINED(sav))
2649                 LIST_REMOVE(sav, chain);
2650
2651         /*
2652          * Cleanup xform state.  Note that zeroize'ing causes the
2653          * keys to be cleared; otherwise we must do it ourself.
2654          */
2655         if (sav->tdb_xform != NULL) {
2656                 sav->tdb_xform->xf_zeroize(sav);
2657                 sav->tdb_xform = NULL;
2658         } else {
2659                 if (sav->key_auth != NULL)
2660                         bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2661                 if (sav->key_enc != NULL)
2662                         bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
2663         }
2664         if (sav->key_auth != NULL) {
2665                 KFREE(sav->key_auth);
2666                 sav->key_auth = NULL;
2667         }
2668         if (sav->key_enc != NULL) {
2669                 KFREE(sav->key_enc);
2670                 sav->key_enc = NULL;
2671         }
2672         if (sav->sched) {
2673                 bzero(sav->sched, sav->schedlen);
2674                 KFREE(sav->sched);
2675                 sav->sched = NULL;
2676         }
2677         if (sav->replay != NULL) {
2678                 KFREE(sav->replay);
2679                 sav->replay = NULL;
2680         }
2681         if (sav->lft_c != NULL) {
2682                 KFREE(sav->lft_c);
2683                 sav->lft_c = NULL;
2684         }
2685         if (sav->lft_h != NULL) {
2686                 KFREE(sav->lft_h);
2687                 sav->lft_h = NULL;
2688         }
2689         if (sav->lft_s != NULL) {
2690                 KFREE(sav->lft_s);
2691                 sav->lft_s = NULL;
2692         }
2693         if (sav->iv != NULL) {
2694                 KFREE(sav->iv);
2695                 sav->iv = NULL;
2696         }
2697
2698         KFREE(sav);
2699
2700         return;
2701 }
2702
2703 /*
2704  * search SAD.
2705  * OUT:
2706  *      NULL    : not found
2707  *      others  : found, pointer to a SA.
2708  */
2709 static struct secashead *
2710 key_getsah(struct secasindex *saidx)
2711 {
2712         struct secashead *sah;
2713
2714         LIST_FOREACH(sah, &sahtree, chain) {
2715                 if (sah->state == SADB_SASTATE_DEAD)
2716                         continue;
2717                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2718                         return sah;
2719         }
2720
2721         return NULL;
2722 }
2723
2724 /*
2725  * check not to be duplicated SPI.
2726  * NOTE: this function is too slow due to searching all SAD.
2727  * OUT:
2728  *      NULL    : not found
2729  *      others  : found, pointer to a SA.
2730  */
2731 static struct secasvar *
2732 key_checkspidup(struct secasindex *saidx, u_int32_t spi)
2733 {
2734         struct secashead *sah;
2735         struct secasvar *sav;
2736
2737         /* check address family */
2738         if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2739                 ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
2740                 return NULL;
2741         }
2742
2743         /* check all SAD */
2744         LIST_FOREACH(sah, &sahtree, chain) {
2745                 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2746                         continue;
2747                 sav = key_getsavbyspi(sah, spi);
2748                 if (sav != NULL)
2749                         return sav;
2750         }
2751
2752         return NULL;
2753 }
2754
2755 /*
2756  * search SAD litmited alive SA, protocol, SPI.
2757  * OUT:
2758  *      NULL    : not found
2759  *      others  : found, pointer to a SA.
2760  */
2761 static struct secasvar *
2762 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
2763 {
2764         struct secasvar *sav;
2765         u_int stateidx;
2766
2767         /* search all status */
2768         for (stateidx = 0; stateidx < NELEM(saorder_state_alive);
2769              stateidx++) {
2770                 u_int state = saorder_state_alive[stateidx];
2771
2772                 LIST_FOREACH(sav, &sah->savtree[state], chain) {
2773                         /* sanity check */
2774                         if (sav->state != state) {
2775                                 ipseclog((LOG_DEBUG, "key_getsavbyspi: "
2776                                     "invalid sav->state (queue: %d SA: %d)\n",
2777                                     state, sav->state));
2778                                 continue;
2779                         }
2780
2781                         if (sav->spi == spi)
2782                                 return sav;
2783                 }
2784         }
2785
2786         return NULL;
2787 }
2788
2789 /*
2790  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2791  * You must update these if need.
2792  * OUT: 0:      success.
2793  *      !0:     failure.
2794  *
2795  * does not modify mbuf.  does not free mbuf on error.
2796  */
2797 static int
2798 key_setsaval(struct secasvar *sav, struct mbuf *m,
2799              const struct sadb_msghdr *mhp)
2800 {
2801         int error = 0;
2802
2803         /* sanity check */
2804         if (m == NULL || mhp == NULL || mhp->msg == NULL)
2805                 panic("key_setsaval: NULL pointer is passed.");
2806
2807         /* initialization */
2808         sav->replay = NULL;
2809         sav->key_auth = NULL;
2810         sav->key_enc = NULL;
2811         sav->sched = NULL;
2812         sav->schedlen = 0;
2813         sav->iv = NULL;
2814         sav->lft_c = NULL;
2815         sav->lft_h = NULL;
2816         sav->lft_s = NULL;
2817         sav->tdb_xform = NULL;          /* transform */
2818         sav->tdb_encalgxform = NULL;    /* encoding algorithm */
2819         sav->tdb_authalgxform = NULL;   /* authentication algorithm */
2820         sav->tdb_compalgxform = NULL;   /* compression algorithm */
2821
2822         /* SA */
2823         if (mhp->ext[SADB_EXT_SA] != NULL) {
2824                 const struct sadb_sa *sa0;
2825
2826                 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2827                 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
2828                         error = EINVAL;
2829                         goto fail;
2830                 }
2831
2832                 sav->alg_auth = sa0->sadb_sa_auth;
2833                 sav->alg_enc = sa0->sadb_sa_encrypt;
2834                 sav->flags = sa0->sadb_sa_flags;
2835
2836                 /* replay window */
2837                 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
2838                         sav->replay = 
2839                             kmalloc(sizeof(struct secreplay)+sa0->sadb_sa_replay,
2840                                     M_SECA, M_INTWAIT | M_ZERO | M_NULLOK);
2841                         if (sav->replay == NULL) {
2842                                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2843                                 error = ENOBUFS;
2844                                 goto fail;
2845                         }
2846                         if (sa0->sadb_sa_replay != 0)
2847                                 sav->replay->bitmap = (caddr_t)(sav->replay+1);
2848                         sav->replay->wsize = sa0->sadb_sa_replay;
2849                 }
2850         }
2851
2852         /* Authentication keys */
2853         if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
2854                 const struct sadb_key *key0;
2855                 int len;
2856
2857                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
2858                 len = mhp->extlen[SADB_EXT_KEY_AUTH];
2859
2860                 error = 0;
2861                 if (len < sizeof(*key0)) {
2862                         error = EINVAL;
2863                         goto fail;
2864                 }
2865                 switch (mhp->msg->sadb_msg_satype) {
2866                 case SADB_SATYPE_AH:
2867                 case SADB_SATYPE_ESP:
2868                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
2869                             sav->alg_auth != SADB_X_AALG_NULL)
2870                                 error = EINVAL;
2871                         break;
2872                 case SADB_X_SATYPE_IPCOMP:
2873                 default:
2874                         error = EINVAL;
2875                         break;
2876                 }
2877                 if (error) {
2878                         ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
2879                         goto fail;
2880                 }
2881
2882                 sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
2883                 if (sav->key_auth == NULL) {
2884                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2885                         error = ENOBUFS;
2886                         goto fail;
2887                 }
2888         }
2889
2890         /* Encryption key */
2891         if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
2892                 const struct sadb_key *key0;
2893                 int len;
2894
2895                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
2896                 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
2897
2898                 error = 0;
2899                 if (len < sizeof(*key0)) {
2900                         error = EINVAL;
2901                         goto fail;
2902                 }
2903                 switch (mhp->msg->sadb_msg_satype) {
2904                 case SADB_SATYPE_ESP:
2905                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
2906                             sav->alg_enc != SADB_EALG_NULL) {
2907                                 error = EINVAL;
2908                                 break;
2909                         }
2910                         sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
2911                         if (sav->key_enc == NULL) {
2912                                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2913                                 error = ENOBUFS;
2914                                 goto fail;
2915                         }
2916                         break;
2917                 case SADB_X_SATYPE_IPCOMP:
2918                         if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
2919                                 error = EINVAL;
2920                         sav->key_enc = NULL;    /*just in case*/
2921                         break;
2922                 case SADB_SATYPE_AH:
2923                 default:
2924                         error = EINVAL;
2925                         break;
2926                 }
2927                 if (error) {
2928                         ipseclog((LOG_DEBUG, "key_setsatval: invalid key_enc value.\n"));
2929                         goto fail;
2930                 }
2931         }
2932
2933         /* set iv */
2934         sav->ivlen = 0;
2935
2936         switch (mhp->msg->sadb_msg_satype) {
2937         case SADB_SATYPE_AH:
2938                 error = xform_init(sav, XF_AH);
2939                 break;
2940         case SADB_SATYPE_ESP:
2941                 error = xform_init(sav, XF_ESP);
2942                 break;
2943         case SADB_X_SATYPE_IPCOMP:
2944                 error = xform_init(sav, XF_IPCOMP);
2945                 break;
2946         }
2947         if (error) {
2948                 ipseclog((LOG_DEBUG,
2949                         "key_setsaval: unable to initialize SA type %u.\n",
2950                         mhp->msg->sadb_msg_satype));
2951                 goto fail;
2952         }
2953
2954         /* reset created */
2955         sav->created = time_second;
2956
2957         /* make lifetime for CURRENT */
2958         KMALLOC(sav->lft_c, struct sadb_lifetime *,
2959             sizeof(struct sadb_lifetime));
2960         if (sav->lft_c == NULL) {
2961                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2962                 error = ENOBUFS;
2963                 goto fail;
2964         }
2965
2966         sav->lft_c->sadb_lifetime_len =
2967             PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2968         sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2969         sav->lft_c->sadb_lifetime_allocations = 0;
2970         sav->lft_c->sadb_lifetime_bytes = 0;
2971         sav->lft_c->sadb_lifetime_addtime = time_second;
2972         sav->lft_c->sadb_lifetime_usetime = 0;
2973
2974         /* lifetimes for HARD and SOFT */
2975     {
2976         const struct sadb_lifetime *lft0;
2977
2978         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
2979         if (lft0 != NULL) {
2980                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
2981                         error = EINVAL;
2982                         goto fail;
2983                 }
2984                 sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
2985                     sizeof(*lft0));
2986                 if (sav->lft_h == NULL) {
2987                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
2988                         error = ENOBUFS;
2989                         goto fail;
2990                 }
2991                 /* to be initialize ? */
2992         }
2993
2994         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
2995         if (lft0 != NULL) {
2996                 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
2997                         error = EINVAL;
2998                         goto fail;
2999                 }
3000                 sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
3001                     sizeof(*lft0));
3002                 if (sav->lft_s == NULL) {
3003                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3004                         error = ENOBUFS;
3005                         goto fail;
3006                 }
3007                 /* to be initialize ? */
3008         }
3009     }
3010
3011         return 0;
3012
3013  fail:
3014         /* initialization */
3015         if (sav->replay != NULL) {
3016                 KFREE(sav->replay);
3017                 sav->replay = NULL;
3018         }
3019         if (sav->key_auth != NULL) {
3020                 KFREE(sav->key_auth);
3021                 sav->key_auth = NULL;
3022         }
3023         if (sav->key_enc != NULL) {
3024                 KFREE(sav->key_enc);
3025                 sav->key_enc = NULL;
3026         }
3027         if (sav->sched) {
3028                 KFREE(sav->sched);
3029                 sav->sched = NULL;
3030         }
3031         if (sav->iv != NULL) {
3032                 KFREE(sav->iv);
3033                 sav->iv = NULL;
3034         }
3035         if (sav->lft_c != NULL) {
3036                 KFREE(sav->lft_c);
3037                 sav->lft_c = NULL;
3038         }
3039         if (sav->lft_h != NULL) {
3040                 KFREE(sav->lft_h);
3041                 sav->lft_h = NULL;
3042         }
3043         if (sav->lft_s != NULL) {
3044                 KFREE(sav->lft_s);
3045                 sav->lft_s = NULL;
3046         }
3047
3048         return error;
3049 }
3050
3051 /*
3052  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3053  * OUT: 0:      valid
3054  *      other:  errno
3055  */
3056 static int
3057 key_mature(struct secasvar *sav)
3058 {
3059         int error;
3060
3061         /* check SPI value */
3062         switch (sav->sah->saidx.proto) {
3063         case IPPROTO_ESP:
3064         case IPPROTO_AH:
3065                 if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
3066                         ipseclog((LOG_DEBUG,
3067                             "key_mature: illegal range of SPI %u.\n",
3068                             (u_int32_t)ntohl(sav->spi)));
3069                         return EINVAL;
3070                 }
3071                 break;
3072         }
3073
3074         /* check satype */
3075         switch (sav->sah->saidx.proto) {
3076         case IPPROTO_ESP:
3077                 /* check flags */
3078                 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3079                     (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3080                         ipseclog((LOG_DEBUG, "key_mature: "
3081                             "invalid flag (derived) given to old-esp.\n"));
3082                         return EINVAL;
3083                 }
3084                 error = xform_init(sav, XF_ESP);
3085                 break;
3086         case IPPROTO_AH:
3087                 /* check flags */
3088                 if (sav->flags & SADB_X_EXT_DERIV) {
3089                         ipseclog((LOG_DEBUG, "key_mature: "
3090                             "invalid flag (derived) given to AH SA.\n"));
3091                         return EINVAL;
3092                 }
3093                 if (sav->alg_enc != SADB_EALG_NONE) {
3094                         ipseclog((LOG_DEBUG, "key_mature: "
3095                             "protocol and algorithm mismated.\n"));
3096                         return(EINVAL);
3097                 }
3098                 error = xform_init(sav, XF_AH);
3099                 break;
3100         case IPPROTO_IPCOMP:
3101                 if (sav->alg_auth != SADB_AALG_NONE) {
3102                         ipseclog((LOG_DEBUG, "key_mature: "
3103                                 "protocol and algorithm mismated.\n"));
3104                         return(EINVAL);
3105                 }
3106                 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3107                  && ntohl(sav->spi) >= 0x10000) {
3108                         ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
3109                         return(EINVAL);
3110                 }
3111                 error = xform_init(sav, XF_IPCOMP);
3112                 break;
3113         default:
3114                 ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
3115                 error = EPROTONOSUPPORT;
3116                 break;
3117         }
3118         if (error == 0)
3119                 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3120         return (error);
3121 }
3122
3123 /*
3124  * subroutine for SADB_GET and SADB_DUMP.
3125  */
3126 static struct mbuf *
3127 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3128               u_int32_t seq, u_int32_t pid)
3129 {
3130         struct mbuf *result = NULL, *tres = NULL, *m;
3131         int l = 0;
3132         int i;
3133         void *p;
3134         int dumporder[] = {
3135                 SADB_EXT_SA, SADB_X_EXT_SA2,
3136                 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3137                 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3138                 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3139                 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3140                 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3141         };
3142
3143         m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3144         if (m == NULL)
3145                 goto fail;
3146         result = m;
3147
3148         for (i = NELEM(dumporder) - 1; i >= 0; i--) {
3149                 m = NULL;
3150                 p = NULL;
3151                 switch (dumporder[i]) {
3152                 case SADB_EXT_SA:
3153                         m = key_setsadbsa(sav);
3154                         if (!m)
3155                                 goto fail;
3156                         break;
3157
3158                 case SADB_X_EXT_SA2:
3159                         m = key_setsadbxsa2(sav->sah->saidx.mode,
3160                                         sav->replay ? sav->replay->count : 0,
3161                                         sav->sah->saidx.reqid);
3162                         if (!m)
3163                                 goto fail;
3164                         break;
3165
3166                 case SADB_EXT_ADDRESS_SRC:
3167                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3168                             &sav->sah->saidx.src.sa,
3169                             FULLMASK, IPSEC_ULPROTO_ANY);
3170                         if (!m)
3171                                 goto fail;
3172                         break;
3173
3174                 case SADB_EXT_ADDRESS_DST:
3175                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3176                             &sav->sah->saidx.dst.sa,
3177                             FULLMASK, IPSEC_ULPROTO_ANY);
3178                         if (!m)
3179                                 goto fail;
3180                         break;
3181
3182                 case SADB_EXT_KEY_AUTH:
3183                         if (!sav->key_auth)
3184                                 continue;
3185                         l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3186                         p = sav->key_auth;
3187                         break;
3188
3189                 case SADB_EXT_KEY_ENCRYPT:
3190                         if (!sav->key_enc)
3191                                 continue;
3192                         l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3193                         p = sav->key_enc;
3194                         break;
3195
3196                 case SADB_EXT_LIFETIME_CURRENT:
3197                         if (!sav->lft_c)
3198                                 continue;
3199                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3200                         p = sav->lft_c;
3201                         break;
3202
3203                 case SADB_EXT_LIFETIME_HARD:
3204                         if (!sav->lft_h)
3205                                 continue;
3206                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3207                         p = sav->lft_h;
3208                         break;
3209
3210                 case SADB_EXT_LIFETIME_SOFT:
3211                         if (!sav->lft_s)
3212                                 continue;
3213                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3214                         p = sav->lft_s;
3215                         break;
3216
3217                 case SADB_EXT_ADDRESS_PROXY:
3218                 case SADB_EXT_IDENTITY_SRC:
3219                 case SADB_EXT_IDENTITY_DST:
3220                         /* XXX: should we brought from SPD ? */
3221                 case SADB_EXT_SENSITIVITY:
3222                 default:
3223                         continue;
3224                 }
3225
3226                 if ((!m && !p) || (m && p))
3227                         goto fail;
3228                 if (p && tres) {
3229                         M_PREPEND(tres, l, MB_DONTWAIT);
3230                         if (!tres)
3231                                 goto fail;
3232                         bcopy(p, mtod(tres, caddr_t), l);
3233                         continue;
3234                 }
3235                 if (p) {
3236                         m = key_alloc_mbuf(l);
3237                         if (!m)
3238                                 goto fail;
3239                         m_copyback(m, 0, l, p);
3240                 }
3241
3242                 if (tres)
3243                         m_cat(m, tres);
3244                 tres = m;
3245         }
3246
3247         m_cat(result, tres);
3248
3249         if (result->m_len < sizeof(struct sadb_msg)) {
3250                 result = m_pullup(result, sizeof(struct sadb_msg));
3251                 if (result == NULL)
3252                         goto fail;
3253         }
3254         result->m_pkthdr.len = m_lengthm(result, NULL);
3255         mtod(result, struct sadb_msg *)->sadb_msg_len =
3256             PFKEY_UNIT64(result->m_pkthdr.len);
3257
3258         return result;
3259
3260 fail:
3261         m_freem(result);
3262         m_freem(tres);
3263         return NULL;
3264 }
3265
3266 /*
3267  * set data into sadb_msg.
3268  */
3269 static struct mbuf *
3270 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3271                pid_t pid, u_int16_t reserved)
3272 {
3273         struct mbuf *m;
3274         struct sadb_msg *p;
3275         int len;
3276
3277         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3278         if (len > MCLBYTES)
3279                 return NULL;
3280         m = m_getb(len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
3281         if (!m)
3282                 return NULL;
3283         m->m_pkthdr.len = m->m_len = len;
3284
3285         p = mtod(m, struct sadb_msg *);
3286
3287         bzero(p, len);
3288         p->sadb_msg_version = PF_KEY_V2;
3289         p->sadb_msg_type = type;
3290         p->sadb_msg_errno = 0;
3291         p->sadb_msg_satype = satype;
3292         p->sadb_msg_len = PFKEY_UNIT64(tlen);
3293         p->sadb_msg_reserved = reserved;
3294         p->sadb_msg_seq = seq;
3295         p->sadb_msg_pid = (u_int32_t)pid;
3296
3297         return m;
3298 }
3299
3300 /*
3301  * copy secasvar data into sadb_address.
3302  */
3303 static struct mbuf *
3304 key_setsadbsa(struct secasvar *sav)
3305 {
3306         struct mbuf *m;
3307         struct sadb_sa *p;
3308         int len;
3309
3310         len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3311         m = key_alloc_mbuf(len);
3312         if (!m || m->m_next) {  /*XXX*/
3313                 if (m)
3314                         m_freem(m);
3315                 return NULL;
3316         }
3317
3318         p = mtod(m, struct sadb_sa *);
3319
3320         bzero(p, len);
3321         p->sadb_sa_len = PFKEY_UNIT64(len);
3322         p->sadb_sa_exttype = SADB_EXT_SA;
3323         p->sadb_sa_spi = sav->spi;
3324         p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3325         p->sadb_sa_state = sav->state;
3326         p->sadb_sa_auth = sav->alg_auth;
3327         p->sadb_sa_encrypt = sav->alg_enc;
3328         p->sadb_sa_flags = sav->flags;
3329
3330         return m;
3331 }
3332
3333 /*
3334  * set data into sadb_address.
3335  */
3336 static struct mbuf *
3337 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen,
3338                 u_int16_t ul_proto)
3339 {
3340         struct mbuf *m;
3341         struct sadb_address *p;
3342         size_t len;
3343
3344         len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3345             PFKEY_ALIGN8(saddr->sa_len);
3346         m = key_alloc_mbuf(len);
3347         if (!m || m->m_next) {  /*XXX*/
3348                 if (m)
3349                         m_freem(m);
3350                 return NULL;
3351         }
3352
3353         p = mtod(m, struct sadb_address *);
3354
3355         bzero(p, len);
3356         p->sadb_address_len = PFKEY_UNIT64(len);
3357         p->sadb_address_exttype = exttype;
3358         p->sadb_address_proto = ul_proto;
3359         if (prefixlen == FULLMASK) {
3360                 switch (saddr->sa_family) {
3361                 case AF_INET:
3362                         prefixlen = sizeof(struct in_addr) << 3;
3363                         break;
3364                 case AF_INET6:
3365                         prefixlen = sizeof(struct in6_addr) << 3;
3366                         break;
3367                 default:
3368                         ; /*XXX*/
3369                 }
3370         }
3371         p->sadb_address_prefixlen = prefixlen;
3372         p->sadb_address_reserved = 0;
3373
3374         bcopy(saddr,
3375             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3376             saddr->sa_len);
3377
3378         return m;
3379 }
3380
3381 #if 0
3382 /*
3383  * set data into sadb_ident.
3384  */
3385 static struct mbuf *
3386 key_setsadbident(u_int16_t exttype, u_int16_t idtype, caddr_t string,
3387                  int stringlen, u_int64_t id)
3388 {
3389         struct mbuf *m;
3390         struct sadb_ident *p;
3391         size_t len;
3392
3393         len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
3394         m = key_alloc_mbuf(len);
3395         if (!m || m->m_next) {  /*XXX*/
3396                 if (m)
3397                         m_freem(m);
3398                 return NULL;
3399         }
3400
3401         p = mtod(m, struct sadb_ident *);
3402
3403         bzero(p, len);
3404         p->sadb_ident_len = PFKEY_UNIT64(len);
3405         p->sadb_ident_exttype = exttype;
3406         p->sadb_ident_type = idtype;
3407         p->sadb_ident_reserved = 0;
3408         p->sadb_ident_id = id;
3409
3410         bcopy(string,
3411             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
3412             stringlen);
3413
3414         return m;
3415 }
3416 #endif
3417
3418 /*
3419  * set data into sadb_x_sa2.
3420  */
3421 static struct mbuf *
3422 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3423 {
3424         struct mbuf *m;
3425         struct sadb_x_sa2 *p;
3426         size_t len;
3427
3428         len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3429         m = key_alloc_mbuf(len);
3430         if (!m || m->m_next) {  /*XXX*/
3431                 if (m)
3432                         m_freem(m);
3433                 return NULL;
3434         }
3435
3436         p = mtod(m, struct sadb_x_sa2 *);
3437
3438         bzero(p, len);
3439         p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3440         p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3441         p->sadb_x_sa2_mode = mode;
3442         p->sadb_x_sa2_reserved1 = 0;
3443         p->sadb_x_sa2_reserved2 = 0;
3444         p->sadb_x_sa2_sequence = seq;
3445         p->sadb_x_sa2_reqid = reqid;
3446
3447         return m;
3448 }
3449
3450 /*
3451  * set data into sadb_x_policy
3452  */
3453 static struct mbuf *
3454 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3455 {
3456         struct mbuf *m;
3457         struct sadb_x_policy *p;
3458         size_t len;
3459
3460         len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3461         m = key_alloc_mbuf(len);
3462         if (!m || m->m_next) {  /*XXX*/
3463                 if (m)
3464                         m_freem(m);
3465                 return NULL;
3466         }
3467
3468         p = mtod(m, struct sadb_x_policy *);
3469
3470         bzero(p, len);
3471         p->sadb_x_policy_len = PFKEY_UNIT64(len);
3472         p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3473         p->sadb_x_policy_type = type;
3474         p->sadb_x_policy_dir = dir;
3475         p->sadb_x_policy_id = id;
3476
3477         return m;
3478 }
3479
3480 /* %%% utilities */
3481 /*
3482  * copy a buffer into the new buffer allocated.
3483  */
3484 static void *
3485 key_newbuf(const void *src, u_int len)
3486 {
3487         caddr_t new;
3488
3489         KMALLOC(new, caddr_t, len);
3490         if (new == NULL) {
3491                 ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
3492                 return NULL;
3493         }
3494         bcopy(src, new, len);
3495
3496         return new;
3497 }
3498
3499 /* compare my own address
3500  * OUT: 1: true, i.e. my address.
3501  *      0: false
3502  */
3503 int
3504 key_ismyaddr(struct sockaddr *sa)
3505 {
3506 #ifdef INET
3507         struct sockaddr_in *sin;
3508         struct in_ifaddr_container *iac;
3509 #endif
3510
3511         /* sanity check */
3512         if (sa == NULL)
3513                 panic("key_ismyaddr: NULL pointer is passed.");
3514
3515         switch (sa->sa_family) {
3516 #ifdef INET
3517         case AF_INET:
3518                 sin = (struct sockaddr_in *)sa;
3519                 TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
3520                         struct in_ifaddr *ia = iac->ia;
3521
3522                         if (sin->sin_family == ia->ia_addr.sin_family &&
3523                             sin->sin_len == ia->ia_addr.sin_len &&
3524                             sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3525                         {
3526                                 return 1;
3527                         }
3528                 }
3529                 break;
3530 #endif
3531 #ifdef INET6
3532         case AF_INET6:
3533                 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3534 #endif
3535         }
3536
3537         return 0;
3538 }
3539
3540 #ifdef INET6
3541 /*
3542  * compare my own address for IPv6.
3543  * 1: ours
3544  * 0: other
3545  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3546  */
3547 static int
3548 key_ismyaddr6(struct sockaddr_in6 *sin6)
3549 {
3550         struct in6_ifaddr *ia;
3551         struct in6_multi *in6m;
3552
3553         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3554                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3555                     (struct sockaddr *)&ia->ia_addr, 0) == 0)
3556                         return 1;
3557
3558                 /*
3559                  * XXX Multicast
3560                  * XXX why do we care about multlicast here while we don't care
3561                  * about IPv4 multicast??
3562                  * XXX scope
3563                  */
3564                 in6m = IN6_LOOKUP_MULTI(&sin6->sin6_addr, ia->ia_ifp);
3565                 if (in6m)
3566                         return 1;
3567         }
3568
3569         /* loopback, just for safety */
3570         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3571                 return 1;
3572
3573         return 0;
3574 }
3575 #endif /*INET6*/
3576
3577 /*
3578  * compare two secasindex structure.
3579  * flag can specify to compare 2 saidxes.
3580  * compare two secasindex structure without both mode and reqid.
3581  * don't compare port.
3582  * IN:  
3583  *      saidx0: source, it can be in SAD.
3584  *      saidx1: object.
3585  * OUT: 
3586  *      1 : equal
3587  *      0 : not equal
3588  */
3589 static int
3590 key_cmpsaidx(
3591         const struct secasindex *saidx0,
3592         const struct secasindex *saidx1,
3593         int flag)
3594 {
3595         /* sanity */
3596         if (saidx0 == NULL && saidx1 == NULL)
3597                 return 1;
3598
3599         if (saidx0 == NULL || saidx1 == NULL)
3600                 return 0;
3601
3602         if (saidx0->proto != saidx1->proto)
3603                 return 0;
3604
3605         if (flag == CMP_EXACTLY) {
3606                 if (saidx0->mode != saidx1->mode)
3607                         return 0;
3608                 if (saidx0->reqid != saidx1->reqid)
3609                         return 0;
3610                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3611                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3612                         return 0;
3613         } else {
3614
3615                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3616                 if (flag == CMP_MODE_REQID
3617                   ||flag == CMP_REQID) {
3618                         /*
3619                          * If reqid of SPD is non-zero, unique SA is required.
3620                          * The result must be of same reqid in this case.
3621                          */
3622                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3623                                 return 0;
3624                 }
3625
3626                 if (flag == CMP_MODE_REQID) {
3627                         if (saidx0->mode != IPSEC_MODE_ANY
3628                          && saidx0->mode != saidx1->mode)
3629                                 return 0;
3630                 }
3631
3632                 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3633                         return 0;
3634                 }
3635                 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3636                         return 0;
3637                 }
3638         }
3639
3640         return 1;
3641 }
3642
3643 /*
3644  * compare two secindex structure exactly.
3645  * IN:
3646  *      spidx0: source, it is often in SPD.
3647  *      spidx1: object, it is often from PFKEY message.
3648  * OUT:
3649  *      1 : equal
3650  *      0 : not equal
3651  */
3652 static int
3653 key_cmpspidx_exactly(
3654         struct secpolicyindex *spidx0,
3655         struct secpolicyindex *spidx1)
3656 {
3657         /* sanity */
3658         if (spidx0 == NULL && spidx1 == NULL)
3659                 return 1;
3660
3661         if (spidx0 == NULL || spidx1 == NULL)
3662                 return 0;
3663
3664         if (spidx0->prefs != spidx1->prefs
3665          || spidx0->prefd != spidx1->prefd
3666          || spidx0->ul_proto != spidx1->ul_proto)
3667                 return 0;
3668
3669         return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3670                key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3671 }
3672
3673 /*
3674  * compare two secindex structure with mask.
3675  * IN:
3676  *      spidx0: source, it is often in SPD.
3677  *      spidx1: object, it is often from IP header.
3678  * OUT:
3679  *      1 : equal
3680  *      0 : not equal
3681  */
3682 static int
3683 key_cmpspidx_withmask(
3684         struct secpolicyindex *spidx0,
3685         struct secpolicyindex *spidx1)
3686 {
3687         /* sanity */
3688         if (spidx0 == NULL && spidx1 == NULL)
3689                 return 1;
3690
3691         if (spidx0 == NULL || spidx1 == NULL)
3692                 return 0;
3693
3694         if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3695             spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3696             spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3697             spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3698                 return 0;
3699
3700         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3701         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3702          && spidx0->ul_proto != spidx1->ul_proto)
3703                 return 0;
3704
3705         switch (spidx0->src.sa.sa_family) {
3706         case AF_INET:
3707                 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3708                  && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3709                         return 0;
3710                 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3711                     &spidx1->src.sin.sin_addr, spidx0->prefs))
3712                         return 0;
3713                 break;
3714         case AF_INET6:
3715                 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3716                  && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3717                         return 0;
3718                 /*
3719                  * scope_id check. if sin6_scope_id is 0, we regard it
3720                  * as a wildcard scope, which matches any scope zone ID. 
3721                  */
3722                 if (spidx0->src.sin6.sin6_scope_id &&
3723                     spidx1->src.sin6.sin6_scope_id &&
3724                     spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3725                         return 0;
3726                 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3727                     &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3728                         return 0;
3729                 break;
3730         default:
3731                 /* XXX */
3732                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3733                         return 0;
3734                 break;
3735         }
3736
3737         switch (spidx0->dst.sa.sa_family) {
3738         case AF_INET:
3739                 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3740                  && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3741                         return 0;
3742                 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3743                     &spidx1->dst.sin.sin_addr, spidx0->prefd))
3744                         return 0;
3745                 break;
3746         case AF_INET6:
3747                 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3748                  && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3749                         return 0;
3750                 /*
3751                  * scope_id check. if sin6_scope_id is 0, we regard it
3752                  * as a wildcard scope, which matches any scope zone ID. 
3753                  */
3754                 if (spidx0->dst.sin6.sin6_scope_id &&
3755                     spidx1->dst.sin6.sin6_scope_id &&
3756                     spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3757                         return 0;
3758                 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3759                     &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3760                         return 0;
3761                 break;
3762         default:
3763                 /* XXX */
3764                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3765                         return 0;
3766                 break;
3767         }
3768
3769         /* XXX Do we check other field ?  e.g. flowinfo */
3770
3771         return 1;
3772 }
3773
3774 /* returns 0 on match */
3775 static int
3776 key_sockaddrcmp(
3777         const struct sockaddr *sa1,
3778         const struct sockaddr *sa2,
3779         int port)
3780 {
3781 #ifdef satosin
3782 #undef satosin
3783 #endif
3784 #define satosin(s) ((const struct sockaddr_in *)s)
3785 #ifdef satosin6
3786 #undef satosin6
3787 #endif
3788 #define satosin6(s) ((const struct sockaddr_in6 *)s)
3789         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
3790                 return 1;
3791
3792         switch (sa1->sa_family) {
3793         case AF_INET:
3794                 if (sa1->sa_len != sizeof(struct sockaddr_in))
3795                         return 1;
3796                 if (satosin(sa1)->sin_addr.s_addr !=
3797                     satosin(sa2)->sin_addr.s_addr) {
3798                         return 1;
3799                 }
3800                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
3801                         return 1;
3802                 break;
3803         case AF_INET6:
3804                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
3805                         return 1;       /*EINVAL*/
3806                 if (satosin6(sa1)->sin6_scope_id !=
3807                     satosin6(sa2)->sin6_scope_id) {
3808                         return 1;
3809                 }
3810                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
3811                     &satosin6(sa2)->sin6_addr)) {
3812                         return 1;
3813                 }
3814                 if (port &&
3815                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
3816                         return 1;
3817                 }
3818         default:
3819                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
3820                         return 1;
3821                 break;
3822         }
3823
3824         return 0;
3825 #undef satosin
3826 #undef satosin6
3827 }
3828
3829 /*
3830  * compare two buffers with mask.
3831  * IN:
3832  *      addr1: source
3833  *      addr2: object
3834  *      bits:  Number of bits to compare
3835  * OUT:
3836  *      1 : equal
3837  *      0 : not equal
3838  */
3839 static int
3840 key_bbcmp(const void *a1, const void *a2, u_int bits)
3841 {
3842         const unsigned char *p1 = a1;
3843         const unsigned char *p2 = a2;
3844
3845         /* XXX: This could be considerably faster if we compare a word
3846          * at a time, but it is complicated on LSB Endian machines */
3847
3848         /* Handle null pointers */
3849         if (p1 == NULL || p2 == NULL)
3850                 return (p1 == p2);
3851
3852         while (bits >= 8) {
3853                 if (*p1++ != *p2++)
3854                         return 0;
3855                 bits -= 8;
3856         }
3857
3858         if (bits > 0) {
3859                 u_int8_t mask = ~((1<<(8-bits))-1);
3860                 if ((*p1 & mask) != (*p2 & mask))
3861                         return 0;
3862         }
3863         return 1;       /* Match! */
3864 }
3865
3866 /*
3867  * time handler.
3868  * scanning SPD and SAD to check status for each entries,
3869  * and do to remove or to expire.
3870  * XXX: year 2038 problem may remain.
3871  */
3872 void
3873 key_timehandler(void *unused)
3874 {
3875         u_int dir;
3876         time_t now = time_second;
3877         struct secspacq *spacq, *nextspacq;
3878
3879         crit_enter();
3880
3881         /* SPD */
3882     {
3883         struct secpolicy *sp, *nextsp;
3884
3885         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
3886                 LIST_FOREACH_MUTABLE(sp, &sptree[dir], chain, nextsp) {
3887                         if (sp->state == IPSEC_SPSTATE_DEAD) {
3888                                 KEY_FREESP(&sp);
3889                                 continue;
3890                         }
3891
3892                         if (sp->lifetime == 0 && sp->validtime == 0)
3893                                 continue;
3894
3895                         /* the deletion will occur next time */
3896                         if ((sp->lifetime && now - sp->created > sp->lifetime)
3897                          || (sp->validtime && now - sp->lastused > sp->validtime)) {
3898                                 sp->state = IPSEC_SPSTATE_DEAD;
3899                                 key_spdexpire(sp);
3900                                 continue;
3901                         }
3902                 }
3903         }
3904     }
3905
3906         /* SAD */
3907     {
3908         struct secashead *sah, *nextsah;
3909         struct secasvar *sav, *nextsav;
3910
3911         LIST_FOREACH_MUTABLE(sah, &sahtree, chain, nextsah) {
3912                 /* if sah has been dead, then delete it and process next sah. */
3913                 if (sah->state == SADB_SASTATE_DEAD) {
3914                         key_delsah(sah);
3915                         continue;
3916                 }
3917
3918                 /* if LARVAL entry doesn't become MATURE, delete it. */
3919                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_LARVAL],
3920                                      chain, nextsav) {
3921                         if (now - sav->created > key_larval_lifetime) {
3922                                 KEY_FREESAV(&sav);
3923                         }
3924                 }
3925
3926                 /*
3927                  * check MATURE entry to start to send expire message
3928                  * whether or not.
3929                  */
3930                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_MATURE],
3931                                      chain, nextsav) {
3932                         /* we don't need to check. */
3933                         if (sav->lft_s == NULL)
3934                                 continue;
3935
3936                         /* sanity check */
3937                         if (sav->lft_c == NULL) {
3938                                 ipseclog((LOG_DEBUG,"key_timehandler: "
3939                                         "There is no CURRENT time, why?\n"));
3940                                 continue;
3941                         }
3942
3943                         /* check SOFT lifetime */
3944                         if (sav->lft_s->sadb_lifetime_addtime != 0
3945                          && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
3946                                 /*
3947                                  * check SA to be used whether or not.
3948                                  * when SA hasn't been used, delete it.
3949                                  */
3950                                 if (sav->lft_c->sadb_lifetime_usetime == 0) {
3951                                         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
3952                                         KEY_FREESAV(&sav);
3953                                 } else {
3954                                         key_sa_chgstate(sav, SADB_SASTATE_DYING);
3955                                         /*
3956                                          * XXX If we keep to send expire
3957                                          * message in the status of
3958                                          * DYING. Do remove below code.
3959                                          */
3960                                         key_expire(sav);
3961                                 }
3962                         }
3963                         /* check SOFT lifetime by bytes */
3964                         /*
3965                          * XXX I don't know the way to delete this SA
3966                          * when new SA is installed.  Caution when it's
3967                          * installed too big lifetime by time.
3968                          */
3969                         else if (sav->lft_s->sadb_lifetime_bytes != 0
3970                               && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
3971
3972                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
3973                                 /*
3974                                  * XXX If we keep to send expire
3975                                  * message in the status of
3976                                  * DYING. Do remove below code.
3977                                  */
3978                                 key_expire(sav);
3979                         }
3980                 }
3981
3982                 /* check DYING entry to change status to DEAD. */
3983                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_DYING],
3984                                      chain, nextsav) {
3985                         /* we don't need to check. */
3986                         if (sav->lft_h == NULL)
3987                                 continue;
3988
3989                         /* sanity check */
3990                         if (sav->lft_c == NULL) {
3991                                 ipseclog((LOG_DEBUG, "key_timehandler: "
3992                                         "There is no CURRENT time, why?\n"));
3993                                 continue;
3994                         }
3995
3996                         if (sav->lft_h->sadb_lifetime_addtime != 0
3997                          && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
3998                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
3999                                 KEY_FREESAV(&sav);
4000                         }
4001 #if 0   /* XXX Should we keep to send expire message until HARD lifetime ? */
4002                         else if (sav->lft_s != NULL
4003                               && sav->lft_s->sadb_lifetime_addtime != 0
4004                               && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4005                                 /*
4006                                  * XXX: should be checked to be
4007                                  * installed the valid SA.
4008                                  */
4009
4010                                 /*
4011                                  * If there is no SA then sending
4012                                  * expire message.
4013                                  */
4014                                 key_expire(sav);
4015                         }
4016 #endif
4017                         /* check HARD lifetime by bytes */
4018                         else if (sav->lft_h->sadb_lifetime_bytes != 0
4019                               && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4020                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4021                                 KEY_FREESAV(&sav);
4022                         }
4023                 }
4024
4025                 /* delete entry in DEAD */
4026                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_DEAD],
4027                                      chain, nextsav) {
4028                         /* sanity check */
4029                         if (sav->state != SADB_SASTATE_DEAD) {
4030                                 ipseclog((LOG_DEBUG, "key_timehandler: "
4031                                         "invalid sav->state "
4032                                         "(queue: %d SA: %d): "
4033                                         "kill it anyway\n",
4034                                         SADB_SASTATE_DEAD, sav->state));
4035                         }
4036
4037                         /*
4038                          * do not call key_freesav() here.
4039                          * sav should already be freed, and sav->refcnt
4040                          * shows other references to sav
4041                          * (such as from SPD).
4042                          */
4043                 }
4044         }
4045     }
4046
4047 #ifndef IPSEC_NONBLOCK_ACQUIRE
4048         /* ACQ tree */
4049     {
4050         struct secacq *acq, *nextacq;
4051
4052         LIST_FOREACH_MUTABLE(acq, &acqtree, chain, nextacq) {
4053                 if (now - acq->created > key_blockacq_lifetime &&
4054                     __LIST_CHAINED(acq)) {
4055                         LIST_REMOVE(acq, chain);
4056                         KFREE(acq);
4057                 }
4058         }
4059     }
4060 #endif
4061
4062         /* SP ACQ tree */
4063         LIST_FOREACH_MUTABLE(spacq, &spacqtree, chain, nextspacq) {
4064                 if (now - spacq->created > key_blockacq_lifetime &&
4065                     __LIST_CHAINED(spacq)) {
4066                         LIST_REMOVE(spacq, chain);
4067                         KFREE(spacq);
4068                 }
4069         }
4070
4071         /* initialize random seed */
4072         if (key_tick_init_random++ > key_int_random) {
4073                 key_tick_init_random = 0;
4074                 key_srandom();
4075         }
4076
4077 #ifndef IPSEC_DEBUG2
4078         /* do exchange to tick time !! */
4079         callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
4080 #endif
4081
4082         crit_exit();
4083         return;
4084 }
4085
4086 /*
4087  * to initialize a seed for random()
4088  */
4089 static void
4090 key_srandom(void)
4091 {
4092         skrandom(time_second);
4093 }
4094
4095 u_long
4096 key_random(void)
4097 {
4098         u_long value;
4099
4100         key_randomfill(&value, sizeof(value));
4101         return value;
4102 }
4103
4104 void
4105 key_randomfill(void *p, size_t l)
4106 {
4107         size_t n;
4108         u_long v;
4109         static int warn = 1;
4110
4111         n = (size_t)read_random(p, (u_int)l);
4112         /* last resort */
4113         while (n < l) {
4114                 v = krandom();
4115                 bcopy(&v, (u_int8_t *)p + n,
4116                     l - n < sizeof(v) ? l - n : sizeof(v));
4117                 n += sizeof(v);
4118
4119                 if (warn) {
4120                         kprintf("WARNING: pseudo-random number generator "
4121                             "used for IPsec processing\n");
4122                         warn = 0;
4123                 }
4124         }
4125 }
4126
4127 /*
4128  * map SADB_SATYPE_* to IPPROTO_*.
4129  * if satype == SADB_SATYPE then satype is mapped to ~0.
4130  * OUT:
4131  *      0: invalid satype.
4132  */
4133 static u_int16_t
4134 key_satype2proto(u_int8_t satype)
4135 {
4136         switch (satype) {
4137         case SADB_SATYPE_UNSPEC:
4138                 return IPSEC_PROTO_ANY;
4139         case SADB_SATYPE_AH:
4140                 return IPPROTO_AH;
4141         case SADB_SATYPE_ESP:
4142                 return IPPROTO_ESP;
4143         case SADB_X_SATYPE_IPCOMP:
4144                 return IPPROTO_IPCOMP;
4145         default:
4146                 return 0;
4147         }
4148         /* NOTREACHED */
4149 }
4150
4151 /*
4152  * map IPPROTO_* to SADB_SATYPE_*
4153  * OUT:
4154  *      0: invalid protocol type.
4155  */
4156 static u_int8_t
4157 key_proto2satype(u_int16_t proto)
4158 {
4159         switch (proto) {
4160         case IPPROTO_AH:
4161                 return SADB_SATYPE_AH;
4162         case IPPROTO_ESP:
4163                 return SADB_SATYPE_ESP;
4164         case IPPROTO_IPCOMP:
4165                 return SADB_X_SATYPE_IPCOMP;
4166         default:
4167                 return 0;
4168         }
4169         /* NOTREACHED */
4170 }
4171
4172 /* %%% PF_KEY */
4173 /*
4174  * SADB_GETSPI processing is to receive
4175  *      <base, (SA2), src address, dst address, (SPI range)>
4176  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4177  * tree with the status of LARVAL, and send
4178  *      <base, SA(*), address(SD)>
4179  * to the IKMPd.
4180  *
4181  * IN:  mhp: pointer to the pointer to each header.
4182  * OUT: NULL if fail.
4183  *      other if success, return pointer to the message to send.
4184  */
4185 static int
4186 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4187 {
4188         struct sadb_address *src0, *dst0;
4189         struct secasindex saidx;
4190         struct secashead *newsah;
4191         struct secasvar *newsav;
4192         struct sockaddr *saddr, *daddr;
4193         u_int8_t proto;
4194         u_int32_t spi;
4195         u_int8_t mode;
4196         u_int32_t reqid;
4197         int error;
4198
4199         /* sanity check */
4200         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4201                 panic("key_getspi: NULL pointer is passed.");
4202
4203         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4204             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4205                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4206                 return key_senderror(so, m, EINVAL);
4207         }
4208         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4209             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4210                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4211                 return key_senderror(so, m, EINVAL);
4212         }
4213         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4214                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4215                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4216         } else {
4217                 mode = IPSEC_MODE_ANY;
4218                 reqid = 0;
4219         }
4220
4221         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4222         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4223
4224         /* map satype to proto */
4225         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4226                 ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
4227                 return key_senderror(so, m, EINVAL);
4228         }
4229
4230         /* make sure if port number is zero. */
4231         saddr = (struct sockaddr *)(src0 + 1);
4232         daddr = (struct sockaddr *)(dst0 + 1);
4233         switch (saddr->sa_family) {
4234         case AF_INET:
4235                 if (saddr->sa_len != sizeof(struct sockaddr_in))
4236                         return key_senderror(so, m, EINVAL);
4237                 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4238                 break;
4239         case AF_INET6:
4240                 if (saddr->sa_len != sizeof(struct sockaddr_in6))
4241                         return key_senderror(so, m, EINVAL);
4242                 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4243                 break;
4244         default:
4245                 ; /*???*/
4246         }
4247         switch (daddr->sa_family) {
4248         case AF_INET:
4249                 if (daddr->sa_len != sizeof(struct sockaddr_in))
4250                         return key_senderror(so, m, EINVAL);
4251                 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4252                 break;
4253         case AF_INET6:
4254                 if (daddr->sa_len != sizeof(struct sockaddr_in6))
4255                         return key_senderror(so, m, EINVAL);
4256                 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4257                 break;
4258         default:
4259                 ; /*???*/
4260         }
4261
4262         /* XXX boundary check against sa_len */
4263         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4264
4265         /* SPI allocation */
4266         spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4267                                &saidx);
4268         if (spi == 0)
4269                 return key_senderror(so, m, EINVAL);
4270
4271         /* get a SA index */
4272         if ((newsah = key_getsah(&saidx)) == NULL) {
4273                 /* create a new SA index */
4274                 if ((newsah = key_newsah(&saidx)) == NULL) {
4275                         ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
4276                         return key_senderror(so, m, ENOBUFS);
4277                 }
4278         }
4279
4280         /* get a new SA */
4281         /* XXX rewrite */
4282         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4283         if (newsav == NULL) {
4284                 /* XXX don't free new SA index allocated in above. */
4285                 return key_senderror(so, m, error);
4286         }
4287
4288         /* set spi */
4289         newsav->spi = htonl(spi);
4290
4291 #ifndef IPSEC_NONBLOCK_ACQUIRE
4292         /* delete the entry in acqtree */
4293         if (mhp->msg->sadb_msg_seq != 0) {
4294                 struct secacq *acq;
4295                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4296                         /* reset counter in order to deletion by timehandler. */
4297                         acq->created = time_second;
4298                         acq->count = 0;
4299                 }
4300         }
4301 #endif
4302
4303     {
4304         struct mbuf *n;
4305         struct sadb_sa *m_sa;
4306         struct sadb_msg *newmsg;
4307         int off, len;
4308
4309         /* create new sadb_msg to reply. */
4310         len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4311             PFKEY_ALIGN8(sizeof(struct sadb_sa));
4312         if (len > MCLBYTES)
4313                 return key_senderror(so, m, ENOBUFS);
4314         n = m_getb(len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
4315         if (!n)
4316                 return key_senderror(so, m, ENOBUFS);
4317         n->m_len = len;
4318
4319         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t));
4320         off = PFKEY_ALIGN8(sizeof(struct sadb_msg));
4321
4322         m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4323         m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4324         m_sa->sadb_sa_exttype = SADB_EXT_SA;
4325         m_sa->sadb_sa_spi = htonl(spi);
4326         off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4327
4328 #ifdef DIAGNOSTIC
4329         if (off != len)
4330                 panic("length inconsistency in key_getspi");
4331 #endif
4332
4333         n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4334             SADB_EXT_ADDRESS_DST);
4335         if (!n->m_next) {
4336                 m_freem(n);
4337                 return key_senderror(so, m, ENOBUFS);
4338         }
4339
4340         if (n->m_len < sizeof(struct sadb_msg)) {
4341                 n = m_pullup(n, sizeof(struct sadb_msg));
4342                 if (n == NULL)
4343                         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4344         }
4345         n->m_pkthdr.len = m_lengthm(n, NULL);
4346
4347         newmsg = mtod(n, struct sadb_msg *);
4348         newmsg->sadb_msg_seq = newsav->seq;
4349         newmsg->sadb_msg_errno = 0;
4350         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4351
4352         m_freem(m);
4353         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4354     }
4355 }
4356
4357 /*
4358  * allocating new SPI
4359  * called by key_getspi().
4360  * OUT:
4361  *      0:      failure.
4362  *      others: success.
4363  */
4364 static u_int32_t
4365 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
4366 {
4367         u_int32_t newspi;
4368         u_int32_t min, max;
4369         int count = key_spi_trycnt;
4370
4371         /* set spi range to allocate */
4372         if (spirange != NULL) {
4373                 min = spirange->sadb_spirange_min;
4374                 max = spirange->sadb_spirange_max;
4375         } else {
4376                 min = key_spi_minval;
4377                 max = key_spi_maxval;
4378         }
4379         /* IPCOMP needs 2-byte SPI */
4380         if (saidx->proto == IPPROTO_IPCOMP) {
4381                 u_int32_t t;
4382                 if (min >= 0x10000)
4383                         min = 0xffff;
4384                 if (max >= 0x10000)
4385                         max = 0xffff;
4386                 if (min > max) {
4387                         t = min; min = max; max = t;
4388                 }
4389         }
4390
4391         if (min == max) {
4392                 if (key_checkspidup(saidx, min) != NULL) {
4393                         ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
4394                         return 0;
4395                 }
4396
4397                 count--; /* taking one cost. */
4398                 newspi = min;
4399
4400         } else {
4401
4402                 /* init SPI */
4403                 newspi = 0;
4404
4405                 /* when requesting to allocate spi ranged */
4406                 while (count--) {
4407                         /* generate pseudo-random SPI value ranged. */
4408                         newspi = min + (key_random() % (max - min + 1));
4409
4410                         if (key_checkspidup(saidx, newspi) == NULL)
4411                                 break;
4412                 }
4413
4414                 if (count == 0 || newspi == 0) {
4415                         ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
4416                         return 0;
4417                 }
4418         }
4419
4420         /* statistics */
4421         keystat.getspi_count =
4422                 (keystat.getspi_count + key_spi_trycnt - count) / 2;
4423
4424         return newspi;
4425 }
4426
4427 /*
4428  * SADB_UPDATE processing
4429  * receive
4430  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4431  *       key(AE), (identity(SD),) (sensitivity)>
4432  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4433  * and send
4434  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4435  *       (identity(SD),) (sensitivity)>
4436  * to the ikmpd.
4437  *
4438  * m will always be freed.
4439  */
4440 static int
4441 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4442 {
4443         struct sadb_sa *sa0;
4444         struct sadb_address *src0, *dst0;
4445         struct secasindex saidx;
4446         struct secashead *sah;
4447         struct secasvar *sav;
4448         u_int16_t proto;
4449         u_int8_t mode;
4450         u_int32_t reqid;
4451         int error;
4452
4453         /* sanity check */
4454         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4455                 panic("key_update: NULL pointer is passed.");
4456
4457         /* map satype to proto */
4458         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4459                 ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
4460                 return key_senderror(so, m, EINVAL);
4461         }
4462
4463         if (mhp->ext[SADB_EXT_SA] == NULL ||
4464             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4465             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4466             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4467              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4468             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4469              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4470             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4471              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4472             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4473              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4474                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4475                 return key_senderror(so, m, EINVAL);
4476         }
4477         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4478             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4479             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4480                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4481                 return key_senderror(so, m, EINVAL);
4482         }
4483         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4484                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4485                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4486         } else {
4487                 mode = IPSEC_MODE_ANY;
4488                 reqid = 0;
4489         }
4490         /* XXX boundary checking for other extensions */
4491
4492         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4493         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4494         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4495
4496         /* XXX boundary check against sa_len */
4497         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4498
4499         /* get a SA header */
4500         if ((sah = key_getsah(&saidx)) == NULL) {
4501                 ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
4502                 return key_senderror(so, m, ENOENT);
4503         }
4504
4505         /* set spidx if there */
4506         /* XXX rewrite */
4507         error = key_setident(sah, m, mhp);
4508         if (error)
4509                 return key_senderror(so, m, error);
4510
4511         /* find a SA with sequence number. */
4512 #ifdef IPSEC_DOSEQCHECK
4513         if (mhp->msg->sadb_msg_seq != 0
4514          && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4515                 ipseclog((LOG_DEBUG,
4516                     "key_update: no larval SA with sequence %u exists.\n",
4517                     mhp->msg->sadb_msg_seq));
4518                 return key_senderror(so, m, ENOENT);
4519         }
4520 #else
4521         if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
4522                 ipseclog((LOG_DEBUG,
4523                     "key_update: no such a SA found (spi:%u)\n",
4524                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4525                 return key_senderror(so, m, EINVAL);
4526         }
4527 #endif
4528
4529         /* validity check */
4530         if (sav->sah->saidx.proto != proto) {
4531                 ipseclog((LOG_DEBUG,
4532                     "key_update: protocol mismatched (DB=%u param=%u)\n",
4533                     sav->sah->saidx.proto, proto));
4534                 return key_senderror(so, m, EINVAL);
4535         }
4536 #ifdef IPSEC_DOSEQCHECK
4537         if (sav->spi != sa0->sadb_sa_spi) {
4538                 ipseclog((LOG_DEBUG,
4539                     "key_update: SPI mismatched (DB:%u param:%u)\n",
4540                     (u_int32_t)ntohl(sav->spi),
4541                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4542                 return key_senderror(so, m, EINVAL);
4543         }
4544 #endif
4545         if (sav->pid != mhp->msg->sadb_msg_pid) {
4546                 ipseclog((LOG_DEBUG,
4547                     "key_update: pid mismatched (DB:%u param:%u)\n",
4548                     sav->pid, mhp->msg->sadb_msg_pid));
4549                 return key_senderror(so, m, EINVAL);
4550         }
4551
4552         /* copy sav values */
4553         error = key_setsaval(sav, m, mhp);
4554         if (error) {
4555                 KEY_FREESAV(&sav);
4556                 return key_senderror(so, m, error);
4557         }
4558
4559         /* check SA values to be mature. */
4560         if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4561                 KEY_FREESAV(&sav);
4562                 return key_senderror(so, m, 0);
4563         }
4564
4565     {
4566         struct mbuf *n;
4567
4568         /* set msg buf from mhp */
4569         n = key_getmsgbuf_x1(m, mhp);
4570         if (n == NULL) {
4571                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4572                 return key_senderror(so, m, ENOBUFS);
4573         }
4574
4575         m_freem(m);
4576         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4577     }
4578 }
4579
4580 /*
4581  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4582  * only called by key_update().
4583  * OUT:
4584  *      NULL    : not found
4585  *      others  : found, pointer to a SA.
4586  */
4587 #ifdef IPSEC_DOSEQCHECK
4588 static struct secasvar *
4589 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
4590 {
4591         struct secasvar *sav;
4592         u_int state;
4593
4594         state = SADB_SASTATE_LARVAL;
4595
4596         /* search SAD with sequence number ? */
4597         LIST_FOREACH(sav, &sah->savtree[state], chain) {
4598
4599                 KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
4600
4601                 if (sav->seq == seq) {
4602                         SA_ADDREF(sav);
4603                         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4604                                 kprintf("DP key_getsavbyseq cause "
4605                                         "refcnt++:%d SA:%p\n",
4606                                         sav->refcnt, sav));
4607                         return sav;
4608                 }
4609         }
4610
4611         return NULL;
4612 }
4613 #endif
4614
4615 /*
4616  * SADB_ADD processing
4617  * add an entry to SA database, when received
4618  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4619  *       key(AE), (identity(SD),) (sensitivity)>
4620  * from the ikmpd,
4621  * and send
4622  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4623  *       (identity(SD),) (sensitivity)>
4624  * to the ikmpd.
4625  *
4626  * IGNORE identity and sensitivity messages.
4627  *
4628  * m will always be freed.
4629  */
4630 static int
4631 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4632 {
4633         struct sadb_sa *sa0;
4634         struct sadb_address *src0, *dst0;
4635         struct secasindex saidx;
4636         struct secashead *newsah;
4637         struct secasvar *newsav;
4638         u_int16_t proto;
4639         u_int8_t mode;
4640         u_int32_t reqid;
4641         int error;
4642
4643         /* sanity check */
4644         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4645                 panic("key_add: NULL pointer is passed.");
4646
4647         /* map satype to proto */
4648         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4649                 ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
4650                 return key_senderror(so, m, EINVAL);
4651         }
4652
4653         if (mhp->ext[SADB_EXT_SA] == NULL ||
4654             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4655             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4656             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4657              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4658             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4659              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4660             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4661              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4662             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4663              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4664                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4665                 return key_senderror(so, m, EINVAL);
4666         }
4667         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4668             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4669             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4670                 /* XXX need more */
4671                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4672                 return key_senderror(so, m, EINVAL);
4673         }
4674         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4675                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4676                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4677         } else {
4678                 mode = IPSEC_MODE_ANY;
4679                 reqid = 0;
4680         }
4681
4682         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4683         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4684         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4685
4686         /* XXX boundary check against sa_len */
4687         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4688
4689         /* get a SA header */
4690         if ((newsah = key_getsah(&saidx)) == NULL) {
4691                 /* create a new SA header */
4692                 if ((newsah = key_newsah(&saidx)) == NULL) {
4693                         ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
4694                         return key_senderror(so, m, ENOBUFS);
4695                 }
4696         }
4697
4698         /* set spidx if there */
4699         /* XXX rewrite */
4700         error = key_setident(newsah, m, mhp);
4701         if (error) {
4702                 return key_senderror(so, m, error);
4703         }
4704
4705         /* create new SA entry. */
4706         /* We can create new SA only if SPI is differenct. */
4707         if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
4708                 ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
4709                 return key_senderror(so, m, EEXIST);
4710         }
4711         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4712         if (newsav == NULL) {
4713                 return key_senderror(so, m, error);
4714         }
4715
4716         /* check SA values to be mature. */
4717         if ((error = key_mature(newsav)) != 0) {
4718                 KEY_FREESAV(&newsav);
4719                 return key_senderror(so, m, error);
4720         }
4721
4722         /*
4723          * don't call key_freesav() here, as we would like to keep the SA
4724          * in the database on success.
4725          */
4726
4727     {
4728         struct mbuf *n;
4729
4730         /* set msg buf from mhp */
4731         n = key_getmsgbuf_x1(m, mhp);
4732         if (n == NULL) {
4733                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4734                 return key_senderror(so, m, ENOBUFS);
4735         }
4736
4737         m_freem(m);
4738         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4739     }
4740 }
4741
4742 /* m is retained */
4743 static int
4744 key_setident(struct secashead *sah, struct mbuf *m,
4745              const struct sadb_msghdr *mhp)
4746 {
4747         const struct sadb_ident *idsrc, *iddst;
4748         int idsrclen, iddstlen;
4749
4750         /* sanity check */
4751         if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4752                 panic("key_setident: NULL pointer is passed.");
4753
4754         /* don't make buffer if not there */
4755         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
4756             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4757                 sah->idents = NULL;
4758                 sah->identd = NULL;
4759                 return 0;
4760         }
4761         
4762         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
4763             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4764                 ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
4765                 return EINVAL;
4766         }
4767
4768         idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
4769         iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
4770         idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
4771         iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
4772
4773         /* validity check */
4774         if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
4775                 ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
4776                 return EINVAL;
4777         }
4778
4779         switch (idsrc->sadb_ident_type) {
4780         case SADB_IDENTTYPE_PREFIX:
4781         case SADB_IDENTTYPE_FQDN:
4782         case SADB_IDENTTYPE_USERFQDN:
4783         default:
4784                 /* XXX do nothing */
4785                 sah->idents = NULL;
4786                 sah->identd = NULL;
4787                 return 0;
4788         }
4789
4790         /* make structure */
4791         KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
4792         if (sah->idents == NULL) {
4793                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
4794                 return ENOBUFS;
4795         }
4796         KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
4797         if (sah->identd == NULL) {
4798                 KFREE(sah->idents);
4799                 sah->idents = NULL;
4800                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
4801                 return ENOBUFS;
4802         }
4803         bcopy(idsrc, sah->idents, idsrclen);
4804         bcopy(iddst, sah->identd, iddstlen);
4805
4806         return 0;
4807 }
4808
4809 /*
4810  * m will not be freed on return.
4811  * it is caller's responsibility to free the result. 
4812  */
4813 static struct mbuf *
4814 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
4815 {
4816         struct mbuf *n;
4817
4818         /* sanity check */
4819         if (m == NULL || mhp == NULL || mhp->msg == NULL)
4820                 panic("key_getmsgbuf_x1: NULL pointer is passed.");
4821
4822         /* create new sadb_msg to reply. */
4823         n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
4824             SADB_EXT_SA, SADB_X_EXT_SA2,
4825             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
4826             SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
4827             SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
4828         if (!n)
4829                 return NULL;
4830
4831         if (n->m_len < sizeof(struct sadb_msg)) {
4832                 n = m_pullup(n, sizeof(struct sadb_msg));
4833                 if (n == NULL)
4834                         return NULL;
4835         }
4836         mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
4837         mtod(n, struct sadb_msg *)->sadb_msg_len =
4838             PFKEY_UNIT64(n->m_pkthdr.len);
4839
4840         return n;
4841 }
4842
4843 static int key_delete_all (struct socket *, struct mbuf *,
4844         const struct sadb_msghdr *, u_int16_t);
4845
4846 /*
4847  * SADB_DELETE processing
4848  * receive
4849  *   <base, SA(*), address(SD)>
4850  * from the ikmpd, and set SADB_SASTATE_DEAD,
4851  * and send,
4852  *   <base, SA(*), address(SD)>
4853  * to the ikmpd.
4854  *
4855  * m will always be freed.
4856  */
4857 static int
4858 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4859 {
4860         struct sadb_sa *sa0;
4861         struct sadb_address *src0, *dst0;
4862         struct secasindex saidx;
4863         struct secashead *sah;
4864         struct secasvar *sav = NULL;
4865         u_int16_t proto;
4866
4867         /* sanity check */
4868         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4869                 panic("key_delete: NULL pointer is passed.");
4870
4871         /* map satype to proto */
4872         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4873                 ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
4874                 return key_senderror(so, m, EINVAL);
4875         }
4876
4877         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4878             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4879                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
4880                 return key_senderror(so, m, EINVAL);
4881         }
4882
4883         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4884             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4885                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
4886                 return key_senderror(so, m, EINVAL);
4887         }
4888
4889         if (mhp->ext[SADB_EXT_SA] == NULL) {
4890                 /*
4891                  * Caller wants us to delete all non-LARVAL SAs
4892                  * that match the src/dst.  This is used during
4893                  * IKE INITIAL-CONTACT.
4894                  */
4895                 ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
4896                 return key_delete_all(so, m, mhp, proto);
4897         } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
4898                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
4899                 return key_senderror(so, m, EINVAL);
4900         }
4901
4902         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4903         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4904         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4905
4906         /* XXX boundary check against sa_len */
4907         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
4908
4909         /* get a SA header */
4910         LIST_FOREACH(sah, &sahtree, chain) {
4911                 if (sah->state == SADB_SASTATE_DEAD)
4912                         continue;
4913                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
4914                         continue;
4915
4916                 /* get a SA with SPI. */
4917                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4918                 if (sav)
4919                         break;
4920         }
4921         if (sah == NULL) {
4922                 ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
4923                 return key_senderror(so, m, ENOENT);
4924         }
4925
4926         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4927         KEY_FREESAV(&sav);
4928
4929     {
4930         struct mbuf *n;
4931         struct sadb_msg *newmsg;
4932
4933         /* create new sadb_msg to reply. */
4934         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
4935             SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
4936         if (!n)
4937                 return key_senderror(so, m, ENOBUFS);
4938
4939         if (n->m_len < sizeof(struct sadb_msg)) {
4940                 n = m_pullup(n, sizeof(struct sadb_msg));
4941                 if (n == NULL)
4942                         return key_senderror(so, m, ENOBUFS);
4943         }
4944         newmsg = mtod(n, struct sadb_msg *);
4945         newmsg->sadb_msg_errno = 0;
4946         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4947
4948         m_freem(m);
4949         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4950     }
4951 }
4952
4953 /*
4954  * delete all SAs for src/dst.  Called from key_delete().
4955  */
4956 static int
4957 key_delete_all(struct socket *so, struct mbuf *m,
4958                const struct sadb_msghdr *mhp, u_int16_t proto)
4959 {
4960         struct sadb_address *src0, *dst0;
4961         struct secasindex saidx;
4962         struct secashead *sah;
4963         struct secasvar *sav, *nextsav;
4964         u_int stateidx, state;
4965         struct mbuf *n;
4966         struct sadb_msg *newmsg;
4967
4968         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4969         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4970
4971         /* XXX boundary check against sa_len */
4972         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
4973
4974         LIST_FOREACH(sah, &sahtree, chain) {
4975                 if (sah->state == SADB_SASTATE_DEAD)
4976                         continue;
4977                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
4978                         continue;
4979
4980                 /* Delete all non-LARVAL SAs. */
4981                 for (stateidx = 0; stateidx < NELEM(saorder_state_alive);
4982                      stateidx++) {
4983                         state = saorder_state_alive[stateidx];
4984                         if (state == SADB_SASTATE_LARVAL)
4985                                 continue;
4986                         LIST_FOREACH_MUTABLE(sav, &sah->savtree[state], chain,
4987                                              nextsav) {
4988                                 /* sanity check */
4989                                 if (sav->state != state) {
4990                                         ipseclog((LOG_DEBUG, "key_delete_all: "
4991                                                "invalid sav->state "
4992                                                "(queue: %d SA: %d)\n",
4993                                                state, sav->state));
4994                                         continue;
4995                                 }
4996                                 
4997                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4998                                 KEY_FREESAV(&sav);
4999                         }
5000                 }
5001         }
5002
5003         /* create new sadb_msg to reply. */
5004         n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5005             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5006         if (!n)
5007                 return key_senderror(so, m, ENOBUFS);
5008
5009         if (n->m_len < sizeof(struct sadb_msg)) {
5010                 n = m_pullup(n, sizeof(struct sadb_msg));
5011                 if (n == NULL)
5012                         return key_senderror(so, m, ENOBUFS);
5013         }
5014         newmsg = mtod(n, struct sadb_msg *);
5015         newmsg->sadb_msg_errno = 0;
5016         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5017
5018         m_freem(m);
5019         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5020 }
5021
5022 /*
5023  * SADB_GET processing
5024  * receive
5025  *   <base, SA(*), address(SD)>
5026  * from the ikmpd, and get a SP and a SA to respond,
5027  * and send,
5028  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5029  *       (identity(SD),) (sensitivity)>
5030  * to the ikmpd.
5031  *
5032  * m will always be freed.
5033  */
5034 static int
5035 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5036 {
5037         struct sadb_sa *sa0;
5038         struct sadb_address *src0, *dst0;
5039         struct secasindex saidx;
5040         struct secashead *sah;
5041         struct secasvar *sav = NULL;
5042         u_int16_t proto;
5043
5044         /* sanity check */
5045         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5046                 panic("key_get: NULL pointer is passed.");
5047
5048         /* map satype to proto */
5049         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5050                 ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
5051                 return key_senderror(so, m, EINVAL);
5052         }
5053
5054         if (mhp->ext[SADB_EXT_SA] == NULL ||
5055             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5056             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5057                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5058                 return key_senderror(so, m, EINVAL);
5059         }
5060         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5061             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5062             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5063                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5064                 return key_senderror(so, m, EINVAL);
5065         }
5066
5067         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5068         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5069         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5070
5071         /* XXX boundary check against sa_len */
5072         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5073
5074         /* get a SA header */
5075         LIST_FOREACH(sah, &sahtree, chain) {
5076                 if (sah->state == SADB_SASTATE_DEAD)
5077                         continue;
5078                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5079                         continue;
5080
5081                 /* get a SA with SPI. */
5082                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5083                 if (sav)
5084                         break;
5085         }
5086         if (sah == NULL) {
5087                 ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5088                 return key_senderror(so, m, ENOENT);
5089         }
5090
5091     {
5092         struct mbuf *n;
5093         u_int8_t satype;
5094
5095         /* map proto to satype */
5096         if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5097                 ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5098                 return key_senderror(so, m, EINVAL);
5099         }
5100
5101         /* create new sadb_msg to reply. */
5102         n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5103             mhp->msg->sadb_msg_pid);
5104         if (!n)
5105                 return key_senderror(so, m, ENOBUFS);
5106
5107         m_freem(m);
5108         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5109     }
5110 }
5111
5112 /* XXX make it sysctl-configurable? */
5113 static void
5114 key_getcomb_setlifetime(struct sadb_comb *comb)
5115 {
5116
5117         comb->sadb_comb_soft_allocations = 1;
5118         comb->sadb_comb_hard_allocations = 1;
5119         comb->sadb_comb_soft_bytes = 0;
5120         comb->sadb_comb_hard_bytes = 0;
5121         comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
5122         comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5123         comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
5124         comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5125 }
5126
5127 /*
5128  * XXX reorder combinations by preference
5129  * XXX no idea if the user wants ESP authentication or not
5130  */
5131 static struct mbuf *
5132 key_getcomb_esp(void)
5133 {
5134         struct sadb_comb *comb;
5135         struct enc_xform *algo;
5136         struct mbuf *result = NULL, *m, *n;
5137         int encmin;
5138         int i, off, o;
5139         int totlen;
5140         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5141
5142         m = NULL;
5143         for (i = 1; i <= SADB_EALG_MAX; i++) {
5144                 algo = esp_algorithm_lookup(i);
5145                 if (algo == NULL)
5146                         continue;
5147
5148                 /* discard algorithms with key size smaller than system min */
5149                 if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5150                         continue;
5151                 if (_BITS(algo->minkey) < ipsec_esp_keymin)
5152                         encmin = ipsec_esp_keymin;
5153                 else
5154                         encmin = _BITS(algo->minkey);
5155
5156                 if (ipsec_esp_auth)
5157                         m = key_getcomb_ah();
5158                 else {
5159                         KASSERT(l <= MLEN,
5160                                 ("key_getcomb_esp: l=%u > MLEN=%lu",
5161                                 l, (u_long) MLEN));
5162                         MGET(m, MB_DONTWAIT, MT_DATA);
5163                         if (m) {
5164                                 M_ALIGN(m, l);
5165                                 m->m_len = l;
5166                                 m->m_next = NULL;
5167                                 bzero(mtod(m, caddr_t), m->m_len);
5168                         }
5169                 }
5170                 if (!m)
5171                         goto fail;
5172
5173                 totlen = m_lengthm(m, NULL);
5174                 KASSERT((totlen % l) == 0,
5175                         ("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
5176
5177                 for (off = 0; off < totlen; off += l) {
5178                         n = m_pulldown(m, off, l, &o);
5179                         if (!n) {
5180                                 /* m is already freed */
5181                                 goto fail;
5182                         }
5183                         comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5184                         bzero(comb, sizeof(*comb));
5185                         key_getcomb_setlifetime(comb);
5186                         comb->sadb_comb_encrypt = i;
5187                         comb->sadb_comb_encrypt_minbits = encmin;
5188                         comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5189                 }
5190
5191                 if (!result)
5192                         result = m;
5193                 else
5194                         m_cat(result, m);
5195         }
5196
5197         return result;
5198
5199  fail:
5200         if (result)
5201                 m_freem(result);
5202         return NULL;
5203 }
5204
5205 static void
5206 key_getsizes_ah(
5207         const struct auth_hash *ah,
5208         int alg,
5209         u_int16_t* min,
5210         u_int16_t* max)
5211 {
5212         *min = *max = ah->keysize;
5213         if (ah->keysize == 0) {
5214                 /*
5215                  * Transform takes arbitrary key size but algorithm
5216                  * key size is restricted.  Enforce this here.
5217                  */
5218                 switch (alg) {
5219                 case SADB_X_AALG_MD5:   *min = *max = 16; break;
5220                 case SADB_X_AALG_SHA:   *min = *max = 20; break;
5221                 case SADB_X_AALG_NULL:  *min = 1; *max = 256; break;
5222                 default:
5223                         DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
5224                                 alg));
5225                         break;
5226                 }
5227         }
5228 }
5229
5230 /*
5231  * XXX reorder combinations by preference
5232  */
5233 static struct mbuf *
5234 key_getcomb_ah(void)
5235 {
5236         struct sadb_comb *comb;
5237         struct auth_hash *algo;
5238         struct mbuf *m;
5239         u_int16_t minkeysize, maxkeysize;
5240         int i;
5241         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5242
5243         m = NULL;
5244         for (i = 1; i <= SADB_AALG_MAX; i++) {
5245 #if 1
5246                 /* we prefer HMAC algorithms, not old algorithms */
5247                 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5248                         continue;
5249 #endif
5250                 algo = ah_algorithm_lookup(i);
5251                 if (!algo)
5252                         continue;
5253                 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5254                 /* discard algorithms with key size smaller than system min */
5255                 if (_BITS(minkeysize) < ipsec_ah_keymin)
5256                         continue;
5257
5258                 if (!m) {
5259                         KASSERT(l <= MLEN,
5260                                 ("key_getcomb_ah: l=%u > MLEN=%lu",
5261                                 l, (u_long) MLEN));
5262                         MGET(m, MB_DONTWAIT, MT_DATA);
5263                         if (m) {
5264                                 M_ALIGN(m, l);
5265                                 m->m_len = l;
5266                                 m->m_next = NULL;
5267                         }
5268                 } else
5269                         M_PREPEND(m, l, MB_DONTWAIT);
5270                 if (!m)
5271                         return NULL;
5272
5273                 comb = mtod(m, struct sadb_comb *);
5274                 bzero(comb, sizeof(*comb));
5275                 key_getcomb_setlifetime(comb);
5276                 comb->sadb_comb_auth = i;
5277                 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5278                 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5279         }
5280
5281         return m;
5282 }
5283
5284 /*
5285  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5286  * XXX reorder combinations by preference
5287  */
5288 static struct mbuf *
5289 key_getcomb_ipcomp(void)
5290 {
5291         struct sadb_comb *comb;
5292         struct comp_algo *algo;
5293         struct mbuf *m;
5294         int i;
5295         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5296
5297         m = NULL;
5298         for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5299                 algo = ipcomp_algorithm_lookup(i);
5300                 if (!algo)
5301                         continue;
5302
5303                 if (!m) {
5304                         KASSERT(l <= MLEN,
5305                                 ("key_getcomb_ipcomp: l=%u > MLEN=%lu",
5306                                 l, (u_long) MLEN));
5307                         MGET(m, MB_DONTWAIT, MT_DATA);
5308                         if (m) {
5309                                 M_ALIGN(m, l);
5310                                 m->m_len = l;
5311                                 m->m_next = NULL;
5312                         }
5313                 } else
5314                         M_PREPEND(m, l, MB_DONTWAIT);
5315                 if (!m)
5316                         return NULL;
5317
5318                 comb = mtod(m, struct sadb_comb *);
5319                 bzero(comb, sizeof(*comb));
5320                 key_getcomb_setlifetime(comb);
5321                 comb->sadb_comb_encrypt = i;
5322                 /* what should we set into sadb_comb_*_{min,max}bits? */
5323         }
5324
5325         return m;
5326 }
5327
5328 /*
5329  * XXX no way to pass mode (transport/tunnel) to userland
5330  * XXX replay checking?
5331  * XXX sysctl interface to ipsec_{ah,esp}_keymin
5332  */
5333 static struct mbuf *
5334 key_getprop(const struct secasindex *saidx)
5335 {
5336         struct sadb_prop *prop;
5337         struct mbuf *m;
5338         const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5339
5340         switch (saidx->proto)  {
5341         case IPPROTO_ESP:
5342                 m = key_getcomb_esp();
5343                 break;
5344         case IPPROTO_AH:
5345                 m = key_getcomb_ah();
5346                 break;
5347         case IPPROTO_IPCOMP:
5348                 m = key_getcomb_ipcomp();
5349                 break;
5350         default:
5351                 return NULL;
5352         }
5353
5354         if (!m)
5355                 return NULL;
5356         M_PREPEND(m, l, MB_DONTWAIT);
5357         if (!m)
5358                 return NULL;
5359
5360         prop = mtod(m, struct sadb_prop *);
5361         bzero(prop, sizeof(*prop));
5362         prop->sadb_prop_len = PFKEY_UNIT64(m_lengthm(m, NULL));
5363         prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5364         prop->sadb_prop_replay = 32;    /* XXX */
5365
5366         return m;
5367 }
5368
5369 /*
5370  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5371  * send
5372  *   <base, SA, address(SD), (address(P)), x_policy,
5373  *       (identity(SD),) (sensitivity,) proposal>
5374  * to KMD, and expect to receive
5375  *   <base> with SADB_ACQUIRE if error occured,
5376  * or
5377  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5378  * from KMD by PF_KEY.
5379  *
5380  * XXX x_policy is outside of RFC2367 (KAME extension).
5381  * XXX sensitivity is not supported.
5382  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5383  * see comment for key_getcomb_ipcomp().
5384  *
5385  * OUT:
5386  *    0     : succeed
5387  *    others: error number
5388  */
5389 static int
5390 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5391 {
5392         struct mbuf *result = NULL, *m;
5393 #ifndef IPSEC_NONBLOCK_ACQUIRE
5394         struct secacq *newacq;
5395 #endif
5396         u_int8_t satype;
5397         int error = -1;
5398         u_int32_t seq;
5399
5400         /* sanity check */
5401         KASSERT(saidx != NULL, ("key_acquire: null saidx"));
5402         satype = key_proto2satype(saidx->proto);
5403         KASSERT(satype != 0,
5404                 ("key_acquire: null satype, protocol %u", saidx->proto));
5405
5406 #ifndef IPSEC_NONBLOCK_ACQUIRE
5407         /*
5408          * We never do anything about acquirng SA.  There is anather
5409          * solution that kernel blocks to send SADB_ACQUIRE message until
5410          * getting something message from IKEd.  In later case, to be
5411          * managed with ACQUIRING list.
5412          */
5413         /* Get an entry to check whether sending message or not. */
5414         if ((newacq = key_getacq(saidx)) != NULL) {
5415                 if (key_blockacq_count < newacq->count) {
5416                         /* reset counter and do send message. */
5417                         newacq->count = 0;
5418                 } else {
5419                         /* increment counter and do nothing. */
5420                         newacq->count++;
5421                         return 0;
5422                 }
5423         } else {
5424                 /* make new entry for blocking to send SADB_ACQUIRE. */
5425                 if ((newacq = key_newacq(saidx)) == NULL)
5426                         return ENOBUFS;
5427
5428                 /* add to acqtree */
5429                 LIST_INSERT_HEAD(&acqtree, newacq, chain);
5430         }
5431 #endif
5432
5433
5434 #ifndef IPSEC_NONBLOCK_ACQUIRE
5435         seq = newacq->seq;
5436 #else
5437         seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
5438 #endif
5439         m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5440         if (!m) {
5441                 error = ENOBUFS;
5442                 goto fail;
5443         }
5444         result = m;
5445
5446         /* set sadb_address for saidx's. */
5447         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5448             &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5449         if (!m) {
5450                 error = ENOBUFS;
5451                 goto fail;
5452         }
5453         m_cat(result, m);
5454
5455         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5456             &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5457         if (!m) {
5458                 error = ENOBUFS;
5459                 goto fail;
5460         }
5461         m_cat(result, m);
5462
5463         /* XXX proxy address (optional) */
5464
5465         /* set sadb_x_policy */
5466         if (sp) {
5467                 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5468                 if (!m) {
5469                         error = ENOBUFS;
5470                         goto fail;
5471                 }
5472                 m_cat(result, m);
5473         }
5474
5475         /* XXX identity (optional) */
5476 #if 0
5477         if (idexttype && fqdn) {
5478                 /* create identity extension (FQDN) */
5479                 struct sadb_ident *id;
5480                 int fqdnlen;
5481
5482                 fqdnlen = strlen(fqdn) + 1;     /* +1 for terminating-NUL */
5483                 id = (struct sadb_ident *)p;
5484                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5485                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5486                 id->sadb_ident_exttype = idexttype;
5487                 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5488                 bcopy(fqdn, id + 1, fqdnlen);
5489                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5490         }
5491
5492         if (idexttype) {
5493                 /* create identity extension (USERFQDN) */
5494                 struct sadb_ident *id;
5495                 int userfqdnlen;
5496
5497                 if (userfqdn) {
5498                         /* +1 for terminating-NUL */
5499                         userfqdnlen = strlen(userfqdn) + 1;
5500                 } else
5501                         userfqdnlen = 0;
5502                 id = (struct sadb_ident *)p;
5503                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5504                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5505                 id->sadb_ident_exttype = idexttype;
5506                 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5507                 /* XXX is it correct? */
5508                 if (curproc && curproc->p_cred)
5509                         id->sadb_ident_id = curproc->p_cred->p_ruid;
5510                 if (userfqdn && userfqdnlen)
5511                         bcopy(userfqdn, id + 1, userfqdnlen);
5512                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5513         }
5514 #endif
5515
5516         /* XXX sensitivity (optional) */
5517
5518         /* create proposal/combination extension */
5519         m = key_getprop(saidx);
5520 #if 0
5521         /*
5522          * spec conformant: always attach proposal/combination extension,
5523          * the problem is that we have no way to attach it for ipcomp,
5524          * due to the way sadb_comb is declared in RFC2367.
5525          */
5526         if (!m) {
5527                 error = ENOBUFS;
5528                 goto fail;
5529         }
5530         m_cat(result, m);
5531 #else
5532         /*
5533          * outside of spec; make proposal/combination extension optional.
5534          */
5535         if (m)
5536                 m_cat(result, m);
5537 #endif
5538
5539         if ((result->m_flags & M_PKTHDR) == 0) {
5540                 error = EINVAL;
5541                 goto fail;
5542         }
5543
5544         if (result->m_len < sizeof(struct sadb_msg)) {
5545                 result = m_pullup(result, sizeof(struct sadb_msg));
5546                 if (result == NULL) {
5547                         error = ENOBUFS;
5548                         goto fail;
5549                 }
5550         }
5551         result->m_pkthdr.len = m_lengthm(result, NULL);
5552         mtod(result, struct sadb_msg *)->sadb_msg_len =
5553             PFKEY_UNIT64(result->m_pkthdr.len);
5554
5555         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5556
5557  fail:
5558         if (result)
5559                 m_freem(result);
5560         return error;
5561 }
5562
5563 #ifndef IPSEC_NONBLOCK_ACQUIRE
5564 static struct secacq *
5565 key_newacq(const struct secasindex *saidx)
5566 {
5567         struct secacq *newacq;
5568
5569         /* get new entry */
5570         KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
5571         if (newacq == NULL) {
5572                 ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
5573                 return NULL;
5574         }
5575         bzero(newacq, sizeof(*newacq));
5576
5577         /* copy secindex */
5578         bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5579         newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5580         newacq->created = time_second;
5581         newacq->count = 0;
5582
5583         return newacq;
5584 }
5585
5586 static struct secacq *
5587 key_getacq(const struct secasindex *saidx)
5588 {
5589         struct secacq *acq;
5590
5591         LIST_FOREACH(acq, &acqtree, chain) {
5592                 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5593                         return acq;
5594         }
5595
5596         return NULL;
5597 }
5598
5599 static struct secacq *
5600 key_getacqbyseq(u_int32_t seq)
5601 {
5602         struct secacq *acq;
5603
5604         LIST_FOREACH(acq, &acqtree, chain) {
5605                 if (acq->seq == seq)
5606                         return acq;
5607         }
5608
5609         return NULL;
5610 }
5611 #endif
5612
5613 static struct secspacq *
5614 key_newspacq(struct secpolicyindex *spidx)
5615 {
5616         struct secspacq *acq;
5617
5618         /* get new entry */
5619         KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
5620         if (acq == NULL) {
5621                 ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
5622                 return NULL;
5623         }
5624         bzero(acq, sizeof(*acq));
5625
5626         /* copy secindex */
5627         bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5628         acq->created = time_second;
5629         acq->count = 0;
5630
5631         return acq;
5632 }
5633
5634 static struct secspacq *
5635 key_getspacq(struct secpolicyindex *spidx)
5636 {
5637         struct secspacq *acq;
5638
5639         LIST_FOREACH(acq, &spacqtree, chain) {
5640                 if (key_cmpspidx_exactly(spidx, &acq->spidx))
5641                         return acq;
5642         }
5643
5644         return NULL;
5645 }
5646
5647 /*
5648  * SADB_ACQUIRE processing,
5649  * in first situation, is receiving
5650  *   <base>
5651  * from the ikmpd, and clear sequence of its secasvar entry.
5652  *
5653  * In second situation, is receiving
5654  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5655  * from a user land process, and return
5656  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5657  * to the socket.
5658  *
5659  * m will always be freed.
5660  */
5661 static int
5662 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5663 {
5664         const struct sadb_address *src0, *dst0;
5665         struct secasindex saidx;
5666         struct secashead *sah;
5667         u_int16_t proto;
5668         int error;
5669
5670         /* sanity check */
5671         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5672                 panic("key_acquire2: NULL pointer is passed.");
5673
5674         /*
5675          * Error message from KMd.
5676          * We assume that if error was occured in IKEd, the length of PFKEY
5677          * message is equal to the size of sadb_msg structure.
5678          * We do not raise error even if error occured in this function.
5679          */
5680         if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5681 #ifndef IPSEC_NONBLOCK_ACQUIRE
5682                 struct secacq *acq;
5683
5684                 /* check sequence number */
5685                 if (mhp->msg->sadb_msg_seq == 0) {
5686                         ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
5687                         m_freem(m);
5688                         return 0;
5689                 }
5690
5691                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5692                         /*
5693                          * the specified larval SA is already gone, or we got
5694                          * a bogus sequence number.  we can silently ignore it.
5695                          */
5696                         m_freem(m);
5697                         return 0;
5698                 }
5699
5700                 /* reset acq counter in order to deletion by timehander. */
5701                 acq->created = time_second;
5702                 acq->count = 0;
5703 #endif
5704                 m_freem(m);
5705                 return 0;
5706         }
5707
5708         /*
5709          * This message is from user land.
5710          */
5711
5712         /* map satype to proto */
5713         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5714                 ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
5715                 return key_senderror(so, m, EINVAL);
5716         }
5717
5718         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5719             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5720             mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
5721                 /* error */
5722                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
5723                 return key_senderror(so, m, EINVAL);
5724         }
5725         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5726             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
5727             mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
5728                 /* error */
5729                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
5730                 return key_senderror(so, m, EINVAL);
5731         }
5732
5733         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5734         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5735
5736         /* XXX boundary check against sa_len */
5737         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5738
5739         /* get a SA index */
5740         LIST_FOREACH(sah, &sahtree, chain) {
5741                 if (sah->state == SADB_SASTATE_DEAD)
5742                         continue;
5743                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
5744                         break;
5745         }
5746         if (sah != NULL) {
5747                 ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
5748                 return key_senderror(so, m, EEXIST);
5749         }
5750
5751         error = key_acquire(&saidx, NULL);
5752         if (error != 0) {
5753                 ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
5754                         "from key_acquire.\n", mhp->msg->sadb_msg_errno));
5755                 return key_senderror(so, m, error);
5756         }
5757
5758         return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
5759 }
5760
5761 /*
5762  * SADB_REGISTER processing.
5763  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
5764  * receive
5765  *   <base>
5766  * from the ikmpd, and register a socket to send PF_KEY messages,
5767  * and send
5768  *   <base, supported>
5769  * to KMD by PF_KEY.
5770  * If socket is detached, must free from regnode.
5771  *
5772  * m will always be freed.
5773  */
5774 static int
5775 key_register(struct socket *so, struct mbuf *m,
5776              const struct sadb_msghdr *mhp)
5777 {
5778         struct secreg *reg, *newreg = NULL;
5779
5780         /* sanity check */
5781         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5782                 panic("key_register: NULL pointer is passed.");
5783
5784         /* check for invalid register message */
5785         if (mhp->msg->sadb_msg_satype >= NELEM(regtree))
5786                 return key_senderror(so, m, EINVAL);
5787
5788         /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
5789         if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
5790                 goto setmsg;
5791
5792         /* check whether existing or not */
5793         LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
5794                 if (reg->so == so) {
5795                         ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
5796                         return key_senderror(so, m, EEXIST);
5797                 }
5798         }
5799
5800         /* create regnode */
5801         KMALLOC(newreg, struct secreg *, sizeof(*newreg));
5802         if (newreg == NULL) {
5803                 ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
5804                 return key_senderror(so, m, ENOBUFS);
5805         }
5806         bzero((caddr_t)newreg, sizeof(*newreg));
5807
5808         newreg->so = so;
5809         ((struct keycb *)sotorawcb(so))->kp_registered++;
5810
5811         /* add regnode to regtree. */
5812         LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
5813
5814   setmsg:
5815     {
5816         struct mbuf *n;
5817         struct sadb_msg *newmsg;
5818         struct sadb_supported *sup;
5819         u_int len, alen, elen;
5820         int off;
5821         int i;
5822         struct sadb_alg *alg;
5823
5824         /* create new sadb_msg to reply. */
5825         alen = 0;
5826         for (i = 1; i <= SADB_AALG_MAX; i++) {
5827                 if (ah_algorithm_lookup(i))
5828                         alen += sizeof(struct sadb_alg);
5829         }
5830         if (alen)
5831                 alen += sizeof(struct sadb_supported);
5832         elen = 0;
5833         for (i = 1; i <= SADB_EALG_MAX; i++) {
5834                 if (esp_algorithm_lookup(i))
5835                         elen += sizeof(struct sadb_alg);
5836         }
5837         if (elen)
5838                 elen += sizeof(struct sadb_supported);
5839
5840         len = sizeof(struct sadb_msg) + alen + elen;
5841
5842         if (len > MCLBYTES)
5843                 return key_senderror(so, m, ENOBUFS);
5844         n = m_getb(len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
5845         if (!n)
5846                 return key_senderror(so, m, ENOBUFS);
5847         n->m_pkthdr.len = n->m_len = len;
5848
5849         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t));
5850         newmsg = mtod(n, struct sadb_msg *);
5851         newmsg->sadb_msg_errno = 0;
5852         newmsg->sadb_msg_len = PFKEY_UNIT64(len);
5853         off = PFKEY_ALIGN8(sizeof(struct sadb_msg));
5854
5855         /* for authentication algorithm */
5856         if (alen) {
5857                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
5858                 sup->sadb_supported_len = PFKEY_UNIT64(alen);
5859                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
5860                 off += PFKEY_ALIGN8(sizeof(*sup));
5861
5862                 for (i = 1; i <= SADB_AALG_MAX; i++) {
5863                         struct auth_hash *aalgo;
5864                         u_int16_t minkeysize, maxkeysize;
5865
5866                         aalgo = ah_algorithm_lookup(i);
5867                         if (!aalgo)
5868                                 continue;
5869                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
5870                         alg->sadb_alg_id = i;
5871                         alg->sadb_alg_ivlen = 0;
5872                         key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
5873                         alg->sadb_alg_minbits = _BITS(minkeysize);
5874                         alg->sadb_alg_maxbits = _BITS(maxkeysize);
5875                         off += PFKEY_ALIGN8(sizeof(*alg));
5876                 }
5877         }
5878
5879         /* for encryption algorithm */
5880         if (elen) {
5881                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
5882                 sup->sadb_supported_len = PFKEY_UNIT64(elen);
5883                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
5884                 off += PFKEY_ALIGN8(sizeof(*sup));
5885
5886                 for (i = 1; i <= SADB_EALG_MAX; i++) {
5887                         struct enc_xform *ealgo;
5888
5889                         ealgo = esp_algorithm_lookup(i);
5890                         if (!ealgo)
5891                                 continue;
5892                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
5893                         alg->sadb_alg_id = i;
5894                         alg->sadb_alg_ivlen = ealgo->blocksize;
5895                         alg->sadb_alg_minbits = _BITS(ealgo->minkey);
5896                         alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
5897                         off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
5898                 }
5899         }
5900
5901 #ifdef DIGAGNOSTIC
5902         if (off != len)
5903                 panic("length assumption failed in key_register");
5904 #endif
5905
5906         m_freem(m);
5907         return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
5908     }
5909 }
5910
5911 /*
5912  * free secreg entry registered.
5913  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
5914  */
5915 void
5916 key_freereg(struct socket *so)
5917 {
5918         struct secreg *reg;
5919         int i;
5920
5921         /* sanity check */
5922         if (so == NULL)
5923                 panic("key_freereg: NULL pointer is passed.");
5924
5925         /*
5926          * check whether existing or not.
5927          * check all type of SA, because there is a potential that
5928          * one socket is registered to multiple type of SA.
5929          */
5930         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
5931                 LIST_FOREACH(reg, &regtree[i], chain) {
5932                         if (reg->so == so
5933                          && __LIST_CHAINED(reg)) {
5934                                 LIST_REMOVE(reg, chain);
5935                                 KFREE(reg);
5936                                 break;
5937                         }
5938                 }
5939         }
5940         
5941         return;
5942 }
5943
5944 /*
5945  * SADB_EXPIRE processing
5946  * send
5947  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
5948  * to KMD by PF_KEY.
5949  * NOTE: We send only soft lifetime extension.
5950  *
5951  * OUT: 0       : succeed
5952  *      others  : error number
5953  */
5954 static int
5955 key_expire(struct secasvar *sav)
5956 {
5957         
5958         int satype;
5959         struct mbuf *result = NULL, *m;
5960         int len;
5961         int error = -1;
5962         struct sadb_lifetime *lt;
5963
5964         /* XXX: Why do we lock ? */
5965         crit_enter();
5966
5967         /* sanity check */
5968         if (sav == NULL)
5969                 panic("key_expire: NULL pointer is passed.");
5970         if (sav->sah == NULL)
5971                 panic("key_expire: Why was SA index in SA NULL.");
5972         if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
5973                 panic("key_expire: invalid proto is passed.");
5974
5975         /* set msg header */
5976         m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
5977         if (!m) {
5978                 error = ENOBUFS;
5979                 goto fail;
5980         }
5981         result = m;
5982
5983         /* create SA extension */
5984         m = key_setsadbsa(sav);
5985         if (!m) {
5986                 error = ENOBUFS;
5987                 goto fail;
5988         }
5989         m_cat(result, m);
5990
5991         /* create SA extension */
5992         m = key_setsadbxsa2(sav->sah->saidx.mode,
5993                         sav->replay ? sav->replay->count : 0,
5994                         sav->sah->saidx.reqid);
5995         if (!m) {
5996                 error = ENOBUFS;
5997                 goto fail;
5998         }
5999         m_cat(result, m);
6000
6001         /* create lifetime extension (current and soft) */
6002         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6003         m = key_alloc_mbuf(len);
6004         if (!m || m->m_next) {  /*XXX*/
6005                 if (m)
6006                         m_freem(m);
6007                 error = ENOBUFS;
6008                 goto fail;
6009         }
6010         bzero(mtod(m, caddr_t), len);
6011         lt = mtod(m, struct sadb_lifetime *);
6012         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6013         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6014         lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6015         lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6016         lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6017         lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6018         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6019         bcopy(sav->lft_s, lt, sizeof(*lt));
6020         m_cat(result, m);
6021
6022         /* set sadb_address for source */
6023         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6024             &sav->sah->saidx.src.sa,
6025             FULLMASK, IPSEC_ULPROTO_ANY);
6026         if (!m) {
6027                 error = ENOBUFS;
6028                 goto fail;
6029         }
6030         m_cat(result, m);
6031
6032         /* set sadb_address for destination */
6033         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6034             &sav->sah->saidx.dst.sa,
6035             FULLMASK, IPSEC_ULPROTO_ANY);
6036         if (!m) {
6037                 error = ENOBUFS;
6038                 goto fail;
6039         }
6040         m_cat(result, m);
6041
6042         if ((result->m_flags & M_PKTHDR) == 0) {
6043                 error = EINVAL;
6044                 goto fail;
6045         }
6046
6047         if (result->m_len < sizeof(struct sadb_msg)) {
6048                 result = m_pullup(result, sizeof(struct sadb_msg));
6049                 if (result == NULL) {
6050                         error = ENOBUFS;
6051                         goto fail;
6052                 }
6053         }
6054         result->m_pkthdr.len = m_lengthm(result, NULL);
6055         mtod(result, struct sadb_msg *)->sadb_msg_len =
6056             PFKEY_UNIT64(result->m_pkthdr.len);
6057
6058         crit_exit();
6059         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6060
6061  fail:
6062         if (result)
6063                 m_freem(result);
6064         crit_exit();
6065         return error;
6066 }
6067
6068 /*
6069  * SADB_FLUSH processing
6070  * receive
6071  *   <base>
6072  * from the ikmpd, and free all entries in secastree.
6073  * and send,
6074  *   <base>
6075  * to the ikmpd.
6076  * NOTE: to do is only marking SADB_SASTATE_DEAD.
6077  *
6078  * m will always be freed.
6079  */
6080 static int
6081 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6082 {
6083         struct sadb_msg *newmsg;
6084         struct secashead *sah;
6085         u_int16_t proto;
6086         u_int stateidx;
6087
6088         /* sanity check */
6089         if (so == NULL || mhp == NULL || mhp->msg == NULL)
6090                 panic("key_flush: NULL pointer is passed.");
6091
6092         /* map satype to proto */
6093         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6094                 ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6095                 return key_senderror(so, m, EINVAL);
6096         }
6097
6098         /* no SATYPE specified, i.e. flushing all SA. */
6099         LIST_FOREACH(sah, &sahtree, chain) {
6100                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
6101                     proto != sah->saidx.proto)
6102                         continue;
6103
6104                 for (stateidx = 0; stateidx < NELEM(saorder_state_alive);
6105                      stateidx++) {
6106                         struct secasvar *sav, *nextsav;
6107                         u_int8_t state = saorder_state_any[stateidx];
6108
6109                         LIST_FOREACH_MUTABLE(sav, &sah->savtree[state], chain,
6110                                              nextsav) {
6111                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6112                                 KEY_FREESAV(&sav);
6113                         }
6114                 }
6115
6116                 sah->state = SADB_SASTATE_DEAD;
6117         }
6118
6119         if (m->m_len < sizeof(struct sadb_msg) ||
6120             sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6121                 ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
6122                 return key_senderror(so, m, ENOBUFS);
6123         }
6124
6125         if (m->m_next)
6126                 m_freem(m->m_next);
6127         m->m_next = NULL;
6128         m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6129         newmsg = mtod(m, struct sadb_msg *);
6130         newmsg->sadb_msg_errno = 0;
6131         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6132
6133         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6134 }
6135
6136 /*
6137  * SADB_DUMP processing
6138  * dump all entries including status of DEAD in SAD.
6139  * receive
6140  *   <base>
6141  * from the ikmpd, and dump all secasvar leaves
6142  * and send,
6143  *   <base> .....
6144  * to the ikmpd.
6145  *
6146  * m will always be freed.
6147  */
6148 static int
6149 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6150 {
6151         struct secashead *sah;
6152         struct secasvar *sav;
6153         u_int16_t proto;
6154         u_int stateidx;
6155         u_int8_t satype;
6156         u_int8_t state;
6157         int cnt;
6158         struct mbuf *n;
6159
6160         /* sanity check */
6161         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6162                 panic("key_dump: NULL pointer is passed.");
6163
6164         /* map satype to proto */
6165         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6166                 ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
6167                 return key_senderror(so, m, EINVAL);
6168         }
6169
6170         /* count sav entries to be sent to the userland. */
6171         cnt = 0;
6172         LIST_FOREACH(sah, &sahtree, chain) {
6173                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
6174                     proto != sah->saidx.proto)
6175                         continue;
6176
6177                 for (stateidx = 0; stateidx < NELEM(saorder_state_any);
6178                      stateidx++) {
6179                         state = saorder_state_any[stateidx];
6180                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
6181                                 cnt++;
6182                         }
6183                 }
6184         }
6185
6186         if (cnt == 0)
6187                 return key_senderror(so, m, ENOENT);
6188
6189         /* send this to the userland, one at a time. */
6190         LIST_FOREACH(sah, &sahtree, chain) {
6191                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6192                  && proto != sah->saidx.proto)
6193                         continue;
6194
6195                 /* map proto to satype */
6196                 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6197                         ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
6198                         return key_senderror(so, m, EINVAL);
6199                 }
6200
6201                 for (stateidx = 0; stateidx < NELEM(saorder_state_any);
6202                      stateidx++) {
6203                         state = saorder_state_any[stateidx];
6204                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
6205                                 n = key_setdumpsa(sav, SADB_DUMP, satype,
6206                                     --cnt, mhp->msg->sadb_msg_pid);
6207                                 if (!n)
6208                                         return key_senderror(so, m, ENOBUFS);
6209
6210                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6211                         }
6212                 }
6213         }
6214
6215         m_freem(m);
6216         return 0;
6217 }
6218
6219 /*
6220  * SADB_X_PROMISC processing
6221  *
6222  * m will always be freed.
6223  */
6224 static int
6225 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6226 {
6227         int olen;
6228
6229         /* sanity check */
6230         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6231                 panic("key_promisc: NULL pointer is passed.");
6232
6233         olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6234
6235         if (olen < sizeof(struct sadb_msg)) {
6236 #if 1
6237                 return key_senderror(so, m, EINVAL);
6238 #else
6239                 m_freem(m);
6240                 return 0;
6241 #endif
6242         } else if (olen == sizeof(struct sadb_msg)) {
6243                 /* enable/disable promisc mode */
6244                 struct keycb *kp;
6245
6246                 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6247                         return key_senderror(so, m, EINVAL);
6248                 mhp->msg->sadb_msg_errno = 0;
6249                 switch (mhp->msg->sadb_msg_satype) {
6250                 case 0:
6251                 case 1:
6252                         kp->kp_promisc = mhp->msg->sadb_msg_satype;
6253                         break;
6254                 default:
6255                         return key_senderror(so, m, EINVAL);
6256                 }
6257
6258                 /* send the original message back to everyone */
6259                 mhp->msg->sadb_msg_errno = 0;
6260                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6261         } else {
6262                 /* send packet as is */
6263
6264                 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6265
6266                 /* TODO: if sadb_msg_seq is specified, send to specific pid */
6267                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6268         }
6269 }
6270
6271 static int (*key_typesw[]) (struct socket *, struct mbuf *,
6272                 const struct sadb_msghdr *) = {
6273         NULL,           /* SADB_RESERVED */
6274         key_getspi,     /* SADB_GETSPI */
6275         key_update,     /* SADB_UPDATE */
6276         key_add,        /* SADB_ADD */
6277         key_delete,     /* SADB_DELETE */
6278         key_get,        /* SADB_GET */
6279         key_acquire2,   /* SADB_ACQUIRE */
6280         key_register,   /* SADB_REGISTER */
6281         NULL,           /* SADB_EXPIRE */
6282         key_flush,      /* SADB_FLUSH */
6283         key_dump,       /* SADB_DUMP */
6284         key_promisc,    /* SADB_X_PROMISC */
6285         NULL,           /* SADB_X_PCHANGE */
6286         key_spdadd,     /* SADB_X_SPDUPDATE */
6287         key_spdadd,     /* SADB_X_SPDADD */
6288         key_spddelete,  /* SADB_X_SPDDELETE */
6289         key_spdget,     /* SADB_X_SPDGET */
6290         NULL,           /* SADB_X_SPDACQUIRE */
6291         key_spddump,    /* SADB_X_SPDDUMP */
6292         key_spdflush,   /* SADB_X_SPDFLUSH */
6293         key_spdadd,     /* SADB_X_SPDSETIDX */
6294         NULL,           /* SADB_X_SPDEXPIRE */
6295         key_spddelete2, /* SADB_X_SPDDELETE2 */
6296 };
6297
6298 /*
6299  * parse sadb_msg buffer to process PFKEYv2,
6300  * and create a data to response if needed.
6301  * I think to be dealed with mbuf directly.
6302  * IN:
6303  *     msgp  : pointer to pointer to a received buffer pulluped.
6304  *             This is rewrited to response.
6305  *     so    : pointer to socket.
6306  * OUT:
6307  *    length for buffer to send to user process.
6308  */
6309 int
6310 key_parse(struct mbuf *m, struct socket *so)
6311 {
6312         struct sadb_msg *msg;
6313         struct sadb_msghdr mh;
6314         u_int orglen;
6315         int error;
6316         int target;
6317
6318         /* sanity check */
6319         if (m == NULL || so == NULL)
6320                 panic("key_parse: NULL pointer is passed.");
6321
6322 #if 0   /*kdebug_sadb assumes msg in linear buffer*/
6323         KEYDEBUG(KEYDEBUG_KEY_DUMP,
6324                 ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
6325                 kdebug_sadb(msg));
6326 #endif
6327
6328         if (m->m_len < sizeof(struct sadb_msg)) {
6329                 m = m_pullup(m, sizeof(struct sadb_msg));
6330                 if (!m)
6331                         return ENOBUFS;
6332         }
6333         msg = mtod(m, struct sadb_msg *);
6334         orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6335         target = KEY_SENDUP_ONE;
6336
6337         if ((m->m_flags & M_PKTHDR) == 0 ||
6338             m->m_pkthdr.len != m->m_pkthdr.len) {
6339                 ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
6340                 pfkeystat.out_invlen++;
6341                 error = EINVAL;
6342                 goto senderror;
6343         }
6344
6345         if (msg->sadb_msg_version != PF_KEY_V2) {
6346                 ipseclog((LOG_DEBUG,
6347                     "key_parse: PF_KEY version %u is mismatched.\n",
6348                     msg->sadb_msg_version));
6349                 pfkeystat.out_invver++;
6350                 error = EINVAL;
6351                 goto senderror;
6352         }
6353
6354         if (msg->sadb_msg_type > SADB_MAX) {
6355                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6356                     msg->sadb_msg_type));
6357                 pfkeystat.out_invmsgtype++;
6358                 error = EINVAL;
6359                 goto senderror;
6360         }
6361
6362         /* for old-fashioned code - should be nuked */
6363         if (m->m_pkthdr.len > MCLBYTES) {
6364                 m_freem(m);
6365                 return ENOBUFS;
6366         }
6367         if (m->m_next) {
6368                 struct mbuf *n;
6369
6370                 n = m_getb(m->m_pkthdr.len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
6371                 if (!n) {
6372                         m_freem(m);
6373                         return ENOBUFS;
6374                 }
6375                 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6376                 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6377                 m_freem(m);
6378                 m = n;
6379         }
6380
6381         /* align the mbuf chain so that extensions are in contiguous region. */
6382         error = key_align(m, &mh);
6383         if (error)
6384                 return error;
6385
6386         msg = mh.msg;
6387
6388         /* check SA type */
6389         switch (msg->sadb_msg_satype) {
6390         case SADB_SATYPE_UNSPEC:
6391                 switch (msg->sadb_msg_type) {
6392                 case SADB_GETSPI:
6393                 case SADB_UPDATE:
6394                 case SADB_ADD:
6395                 case SADB_DELETE:
6396                 case SADB_GET:
6397                 case SADB_ACQUIRE:
6398                 case SADB_EXPIRE:
6399                         ipseclog((LOG_DEBUG, "key_parse: must specify satype "
6400                             "when msg type=%u.\n", msg->sadb_msg_type));
6401                         pfkeystat.out_invsatype++;
6402                         error = EINVAL;
6403                         goto senderror;
6404                 }
6405                 break;
6406         case SADB_SATYPE_AH:
6407         case SADB_SATYPE_ESP:
6408         case SADB_X_SATYPE_IPCOMP:
6409                 switch (msg->sadb_msg_type) {
6410                 case SADB_X_SPDADD:
6411                 case SADB_X_SPDDELETE:
6412                 case SADB_X_SPDGET:
6413                 case SADB_X_SPDDUMP:
6414                 case SADB_X_SPDFLUSH:
6415                 case SADB_X_SPDSETIDX:
6416                 case SADB_X_SPDUPDATE:
6417                 case SADB_X_SPDDELETE2:
6418                         ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
6419                             msg->sadb_msg_type));
6420                         pfkeystat.out_invsatype++;
6421                         error = EINVAL;
6422                         goto senderror;
6423                 }
6424                 break;
6425         case SADB_SATYPE_RSVP:
6426         case SADB_SATYPE_OSPFV2:
6427         case SADB_SATYPE_RIPV2:
6428         case SADB_SATYPE_MIP:
6429                 ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
6430                     msg->sadb_msg_satype));
6431                 pfkeystat.out_invsatype++;
6432                 error = EOPNOTSUPP;
6433                 goto senderror;
6434         case 1: /* XXX: What does it do? */
6435                 if (msg->sadb_msg_type == SADB_X_PROMISC)
6436                         break;
6437                 /*FALLTHROUGH*/
6438         default:
6439                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6440                     msg->sadb_msg_satype));
6441                 pfkeystat.out_invsatype++;
6442                 error = EINVAL;
6443                 goto senderror;
6444         }
6445
6446         /* check field of upper layer protocol and address family */
6447         if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6448          && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6449                 struct sadb_address *src0, *dst0;
6450                 u_int plen;
6451
6452                 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6453                 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6454
6455                 /* check upper layer protocol */
6456                 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6457                         ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
6458                         pfkeystat.out_invaddr++;
6459                         error = EINVAL;
6460                         goto senderror;
6461                 }
6462
6463                 /* check family */
6464                 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6465                     PFKEY_ADDR_SADDR(dst0)->sa_family) {
6466                         ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
6467                         pfkeystat.out_invaddr++;
6468                         error = EINVAL;
6469                         goto senderror;
6470                 }
6471                 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6472                     PFKEY_ADDR_SADDR(dst0)->sa_len) {
6473                         ipseclog((LOG_DEBUG,
6474                             "key_parse: address struct size mismatched.\n"));
6475                         pfkeystat.out_invaddr++;
6476                         error = EINVAL;
6477                         goto senderror;
6478                 }
6479
6480                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6481                 case AF_INET:
6482                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6483                             sizeof(struct sockaddr_in)) {
6484                                 pfkeystat.out_invaddr++;
6485                                 error = EINVAL;
6486                                 goto senderror;
6487                         }
6488                         break;
6489                 case AF_INET6:
6490                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6491                             sizeof(struct sockaddr_in6)) {
6492                                 pfkeystat.out_invaddr++;
6493                                 error = EINVAL;
6494                                 goto senderror;
6495                         }
6496                         break;
6497                 default:
6498                         ipseclog((LOG_DEBUG,
6499                             "key_parse: unsupported address family.\n"));
6500                         pfkeystat.out_invaddr++;
6501                         error = EAFNOSUPPORT;
6502                         goto senderror;
6503                 }
6504
6505                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6506                 case AF_INET:
6507                         plen = sizeof(struct in_addr) << 3;
6508                         break;
6509                 case AF_INET6:
6510                         plen = sizeof(struct in6_addr) << 3;
6511                         break;
6512                 default:
6513                         plen = 0;       /*fool gcc*/
6514                         break;
6515                 }
6516
6517                 /* check max prefix length */
6518                 if (src0->sadb_address_prefixlen > plen ||
6519                     dst0->sadb_address_prefixlen > plen) {
6520                         ipseclog((LOG_DEBUG,
6521                             "key_parse: illegal prefixlen.\n"));
6522                         pfkeystat.out_invaddr++;
6523                         error = EINVAL;
6524                         goto senderror;
6525                 }
6526
6527                 /*
6528                  * prefixlen == 0 is valid because there can be a case when
6529                  * all addresses are matched.
6530                  */
6531         }
6532
6533         if (msg->sadb_msg_type >= NELEM(key_typesw) ||
6534             key_typesw[msg->sadb_msg_type] == NULL) {
6535                 pfkeystat.out_invmsgtype++;
6536                 error = EINVAL;
6537                 goto senderror;
6538         }
6539
6540         return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6541
6542 senderror:
6543         msg->sadb_msg_errno = error;
6544         return key_sendup_mbuf(so, m, target);
6545 }
6546
6547 static int
6548 key_senderror(struct socket *so, struct mbuf *m, int code)
6549 {
6550         struct sadb_msg *msg;
6551
6552         if (m->m_len < sizeof(struct sadb_msg))
6553                 panic("invalid mbuf passed to key_senderror");
6554
6555         msg = mtod(m, struct sadb_msg *);
6556         msg->sadb_msg_errno = code;
6557         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6558 }
6559
6560 /*
6561  * set the pointer to each header into message buffer.
6562  * m will be freed on error.
6563  * XXX larger-than-MCLBYTES extension?
6564  */
6565 static int
6566 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
6567 {
6568         struct mbuf *n;
6569         struct sadb_ext *ext;
6570         size_t off, end;
6571         int extlen;
6572         int toff;
6573
6574         /* sanity check */
6575         if (m == NULL || mhp == NULL)
6576                 panic("key_align: NULL pointer is passed.");
6577         if (m->m_len < sizeof(struct sadb_msg))
6578                 panic("invalid mbuf passed to key_align");
6579
6580         /* initialize */
6581         bzero(mhp, sizeof(*mhp));
6582
6583         mhp->msg = mtod(m, struct sadb_msg *);
6584         mhp->ext[0] = (struct sadb_ext *)mhp->msg;      /*XXX backward compat */
6585
6586         end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6587         extlen = end;   /*just in case extlen is not updated*/
6588         for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6589                 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6590                 if (!n) {
6591                         /* m is already freed */
6592                         return ENOBUFS;
6593                 }
6594                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6595
6596                 /* set pointer */
6597                 switch (ext->sadb_ext_type) {
6598                 case SADB_EXT_SA:
6599                 case SADB_EXT_ADDRESS_SRC:
6600                 case SADB_EXT_ADDRESS_DST:
6601                 case SADB_EXT_ADDRESS_PROXY:
6602                 case SADB_EXT_LIFETIME_CURRENT:
6603                 case SADB_EXT_LIFETIME_HARD:
6604                 case SADB_EXT_LIFETIME_SOFT:
6605                 case SADB_EXT_KEY_AUTH:
6606                 case SADB_EXT_KEY_ENCRYPT:
6607                 case SADB_EXT_IDENTITY_SRC:
6608                 case SADB_EXT_IDENTITY_DST:
6609                 case SADB_EXT_SENSITIVITY:
6610                 case SADB_EXT_PROPOSAL:
6611                 case SADB_EXT_SUPPORTED_AUTH:
6612                 case SADB_EXT_SUPPORTED_ENCRYPT:
6613                 case SADB_EXT_SPIRANGE:
6614                 case SADB_X_EXT_POLICY:
6615                 case SADB_X_EXT_SA2:
6616                         /* duplicate check */
6617                         /*
6618                          * XXX Are there duplication payloads of either
6619                          * KEY_AUTH or KEY_ENCRYPT ?
6620                          */
6621                         if (mhp->ext[ext->sadb_ext_type] != NULL) {
6622                                 ipseclog((LOG_DEBUG,
6623                                     "key_align: duplicate ext_type %u "
6624                                     "is passed.\n", ext->sadb_ext_type));
6625                                 m_freem(m);
6626                                 pfkeystat.out_dupext++;
6627                                 return EINVAL;
6628                         }
6629                         break;
6630                 default:
6631                         ipseclog((LOG_DEBUG,
6632                             "key_align: invalid ext_type %u is passed.\n",
6633                             ext->sadb_ext_type));
6634                         m_freem(m);
6635                         pfkeystat.out_invexttype++;
6636                         return EINVAL;
6637                 }
6638
6639                 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6640
6641                 if (key_validate_ext(ext, extlen)) {
6642                         m_freem(m);
6643                         pfkeystat.out_invlen++;
6644                         return EINVAL;
6645                 }
6646
6647                 n = m_pulldown(m, off, extlen, &toff);
6648                 if (!n) {
6649                         /* m is already freed */
6650                         return ENOBUFS;
6651                 }
6652                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6653
6654                 mhp->ext[ext->sadb_ext_type] = ext;
6655                 mhp->extoff[ext->sadb_ext_type] = off;
6656                 mhp->extlen[ext->sadb_ext_type] = extlen;
6657         }
6658
6659         if (off != end) {
6660                 m_freem(m);
6661                 pfkeystat.out_invlen++;
6662                 return EINVAL;
6663         }
6664
6665         return 0;
6666 }
6667
6668 static int
6669 key_validate_ext(const struct sadb_ext *ext, int len)
6670 {
6671         const struct sockaddr *sa;
6672         enum { NONE, ADDR } checktype = NONE;
6673         int baselen = 0;
6674         const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
6675
6676         if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
6677                 return EINVAL;
6678
6679         /* if it does not match minimum/maximum length, bail */
6680         if (ext->sadb_ext_type >= NELEM(minsize) ||
6681             ext->sadb_ext_type >= NELEM(maxsize))
6682                 return EINVAL;
6683         if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
6684                 return EINVAL;
6685         if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
6686                 return EINVAL;
6687
6688         /* more checks based on sadb_ext_type XXX need more */
6689         switch (ext->sadb_ext_type) {
6690         case SADB_EXT_ADDRESS_SRC:
6691         case SADB_EXT_ADDRESS_DST:
6692         case SADB_EXT_ADDRESS_PROXY:
6693                 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
6694                 checktype = ADDR;
6695                 break;
6696         case SADB_EXT_IDENTITY_SRC:
6697         case SADB_EXT_IDENTITY_DST:
6698                 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
6699                     SADB_X_IDENTTYPE_ADDR) {
6700                         baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
6701                         checktype = ADDR;
6702                 } else
6703                         checktype = NONE;
6704                 break;
6705         default:
6706                 checktype = NONE;
6707                 break;
6708         }
6709
6710         switch (checktype) {
6711         case NONE:
6712                 break;
6713         case ADDR:
6714                 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
6715                 if (len < baselen + sal)
6716                         return EINVAL;
6717                 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
6718                         return EINVAL;
6719                 break;
6720         }
6721
6722         return 0;
6723 }
6724
6725 void
6726 key_init(void)
6727 {
6728         int i;
6729
6730         for (i = 0; i < IPSEC_DIR_MAX; i++) {
6731                 LIST_INIT(&sptree[i]);
6732         }
6733
6734         LIST_INIT(&sahtree);
6735
6736         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6737                 LIST_INIT(&regtree[i]);
6738         }
6739
6740 #ifndef IPSEC_NONBLOCK_ACQUIRE
6741         LIST_INIT(&acqtree);
6742 #endif
6743         LIST_INIT(&spacqtree);
6744
6745         /* system default */
6746         ip4_def_policy.policy = IPSEC_POLICY_NONE;
6747         ip4_def_policy.refcnt++;        /*never reclaim this*/
6748
6749 #ifndef IPSEC_DEBUG2
6750         callout_init(&key_timehandler_ch);
6751         callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
6752 #endif /*IPSEC_DEBUG2*/
6753
6754         /* initialize key statistics */
6755         keystat.getspi_count = 1;
6756
6757         kprintf("IPsec: Initialized Security Association Processing.\n");
6758
6759         return;
6760 }
6761
6762 /*
6763  * XXX: maybe This function is called after INBOUND IPsec processing.
6764  *
6765  * Special check for tunnel-mode packets.
6766  * We must make some checks for consistency between inner and outer IP header.
6767  *
6768  * xxx more checks to be provided
6769  */
6770 int
6771 key_checktunnelsanity(struct secasvar *sav, u_int family, caddr_t src,
6772                       caddr_t dst)
6773 {
6774         /* sanity check */
6775         if (sav->sah == NULL)
6776                 panic("sav->sah == NULL at key_checktunnelsanity");
6777
6778         /* XXX: check inner IP header */
6779
6780         return 1;
6781 }
6782
6783 #if 0
6784 #define hostnamelen     strlen(hostname)
6785
6786 /*
6787  * Get FQDN for the host.
6788  * If the administrator configured hostname (by hostname(1)) without
6789  * domain name, returns nothing.
6790  */
6791 static const char *
6792 key_getfqdn(void)
6793 {
6794         int i;
6795         int hasdot;
6796         static char fqdn[MAXHOSTNAMELEN + 1];
6797
6798         if (!hostnamelen)
6799                 return NULL;
6800
6801         /* check if it comes with domain name. */
6802         hasdot = 0;
6803         for (i = 0; i < hostnamelen; i++) {
6804                 if (hostname[i] == '.')
6805                         hasdot++;
6806         }
6807         if (!hasdot)
6808                 return NULL;
6809
6810         /* NOTE: hostname may not be NUL-terminated. */
6811         bzero(fqdn, sizeof(fqdn));
6812         bcopy(hostname, fqdn, hostnamelen);
6813         fqdn[hostnamelen] = '\0';
6814         return fqdn;
6815 }
6816
6817 /*
6818  * get username@FQDN for the host/user.
6819  */
6820 static const char *
6821 key_getuserfqdn(void)
6822 {
6823         const char *host;
6824         static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
6825         struct proc *p = curproc;
6826         char *q;
6827
6828         if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
6829                 return NULL;
6830         if (!(host = key_getfqdn()))
6831                 return NULL;
6832
6833         /* NOTE: s_login may not be-NUL terminated. */
6834         bzero(userfqdn, sizeof(userfqdn));
6835         bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
6836         userfqdn[MAXLOGNAME] = '\0';    /* safeguard */
6837         q = userfqdn + strlen(userfqdn);
6838         *q++ = '@';
6839         bcopy(host, q, strlen(host));
6840         q += strlen(host);
6841         *q++ = '\0';
6842
6843         return userfqdn;
6844 }
6845 #endif
6846
6847 /* record data transfer on SA, and update timestamps */
6848 void
6849 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
6850 {
6851         KASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
6852         KASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
6853         if (!sav->lft_c)
6854                 return;
6855
6856         /*
6857          * XXX Currently, there is a difference of bytes size
6858          * between inbound and outbound processing.
6859          */
6860         sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
6861         /* to check bytes lifetime is done in key_timehandler(). */
6862
6863         /*
6864          * We use the number of packets as the unit of
6865          * sadb_lifetime_allocations.  We increment the variable
6866          * whenever {esp,ah}_{in,out}put is called.
6867          */
6868         sav->lft_c->sadb_lifetime_allocations++;
6869         /* XXX check for expires? */
6870
6871         /*
6872          * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
6873          * in seconds.  HARD and SOFT lifetime are measured by the time
6874          * difference (again in seconds) from sadb_lifetime_usetime.
6875          *
6876          *      usetime
6877          *      v     expire   expire
6878          * -----+-----+--------+---> t
6879          *      <--------------> HARD
6880          *      <-----> SOFT
6881          */
6882         sav->lft_c->sadb_lifetime_usetime = time_second;
6883         /* XXX check for expires? */
6884
6885         return;
6886 }
6887
6888 /* dumb version */
6889 void
6890 key_sa_routechange(struct sockaddr *dst)
6891 {
6892         struct secashead *sah;
6893         struct route *ro;
6894
6895         LIST_FOREACH(sah, &sahtree, chain) {
6896                 ro = &sah->sa_route;
6897                 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
6898                  && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
6899                         RTFREE(ro->ro_rt);
6900                         ro->ro_rt = NULL;
6901                 }
6902         }
6903
6904         return;
6905 }
6906
6907 static void
6908 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
6909 {
6910         if (sav == NULL)
6911                 panic("key_sa_chgstate called with sav == NULL");
6912
6913         if (sav->state == state)
6914                 return;
6915
6916         if (__LIST_CHAINED(sav))
6917                 LIST_REMOVE(sav, chain);
6918
6919         sav->state = state;
6920         LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
6921 }
6922
6923 void
6924 key_sa_stir_iv(struct secasvar *sav)
6925 {
6926
6927         if (!sav->iv)
6928                 panic("key_sa_stir_iv called with sav == NULL");
6929         key_randomfill(sav->iv, sav->ivlen);
6930 }
6931
6932 /* XXX too much? */
6933 static struct mbuf *
6934 key_alloc_mbuf(int l)
6935 {
6936         struct mbuf *m = NULL, *n;
6937         int len, t;
6938
6939         len = l;
6940         while (len > 0) {
6941                 n = m_getb(len, MB_DONTWAIT, MT_DATA, 0);
6942                 if (!n) {
6943                         m_freem(m);
6944                         return NULL;
6945                 }
6946                 n->m_len = 0;
6947                 n->m_len = M_TRAILINGSPACE(n);
6948                 /* use the bottom of mbuf, hoping we can prepend afterwards */
6949                 if (n->m_len > len) {
6950                         t = (n->m_len - len) & ~(sizeof(long) - 1);
6951                         n->m_data += t;
6952                         n->m_len = len;
6953                 }
6954
6955                 len -= n->m_len;
6956
6957                 if (m)
6958                         m_cat(m, n);
6959                 else
6960                         m = n;
6961         }
6962
6963         return m;
6964 }