Merge branch 'vendor/LIBEDIT'
[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 #include <netinet6/in6_var.h>
3548
3549 static int
3550 key_ismyaddr6(struct sockaddr_in6 *sin6)
3551 {
3552         struct in6_ifaddr *ia;
3553         struct in6_multi *in6m;
3554
3555         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3556                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3557                     (struct sockaddr *)&ia->ia_addr, 0) == 0)
3558                         return 1;
3559
3560                 /*
3561                  * XXX Multicast
3562                  * XXX why do we care about multlicast here while we don't care
3563                  * about IPv4 multicast??
3564                  * XXX scope
3565                  */
3566                 in6m = NULL;
3567                 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3568                 if (in6m)
3569                         return 1;
3570         }
3571
3572         /* loopback, just for safety */
3573         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3574                 return 1;
3575
3576         return 0;
3577 }
3578 #endif /*INET6*/
3579
3580 /*
3581  * compare two secasindex structure.
3582  * flag can specify to compare 2 saidxes.
3583  * compare two secasindex structure without both mode and reqid.
3584  * don't compare port.
3585  * IN:  
3586  *      saidx0: source, it can be in SAD.
3587  *      saidx1: object.
3588  * OUT: 
3589  *      1 : equal
3590  *      0 : not equal
3591  */
3592 static int
3593 key_cmpsaidx(
3594         const struct secasindex *saidx0,
3595         const struct secasindex *saidx1,
3596         int flag)
3597 {
3598         /* sanity */
3599         if (saidx0 == NULL && saidx1 == NULL)
3600                 return 1;
3601
3602         if (saidx0 == NULL || saidx1 == NULL)
3603                 return 0;
3604
3605         if (saidx0->proto != saidx1->proto)
3606                 return 0;
3607
3608         if (flag == CMP_EXACTLY) {
3609                 if (saidx0->mode != saidx1->mode)
3610                         return 0;
3611                 if (saidx0->reqid != saidx1->reqid)
3612                         return 0;
3613                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3614                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3615                         return 0;
3616         } else {
3617
3618                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3619                 if (flag == CMP_MODE_REQID
3620                   ||flag == CMP_REQID) {
3621                         /*
3622                          * If reqid of SPD is non-zero, unique SA is required.
3623                          * The result must be of same reqid in this case.
3624                          */
3625                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3626                                 return 0;
3627                 }
3628
3629                 if (flag == CMP_MODE_REQID) {
3630                         if (saidx0->mode != IPSEC_MODE_ANY
3631                          && saidx0->mode != saidx1->mode)
3632                                 return 0;
3633                 }
3634
3635                 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3636                         return 0;
3637                 }
3638                 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3639                         return 0;
3640                 }
3641         }
3642
3643         return 1;
3644 }
3645
3646 /*
3647  * compare two secindex structure exactly.
3648  * IN:
3649  *      spidx0: source, it is often in SPD.
3650  *      spidx1: object, it is often from PFKEY message.
3651  * OUT:
3652  *      1 : equal
3653  *      0 : not equal
3654  */
3655 static int
3656 key_cmpspidx_exactly(
3657         struct secpolicyindex *spidx0,
3658         struct secpolicyindex *spidx1)
3659 {
3660         /* sanity */
3661         if (spidx0 == NULL && spidx1 == NULL)
3662                 return 1;
3663
3664         if (spidx0 == NULL || spidx1 == NULL)
3665                 return 0;
3666
3667         if (spidx0->prefs != spidx1->prefs
3668          || spidx0->prefd != spidx1->prefd
3669          || spidx0->ul_proto != spidx1->ul_proto)
3670                 return 0;
3671
3672         return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3673                key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3674 }
3675
3676 /*
3677  * compare two secindex structure with mask.
3678  * IN:
3679  *      spidx0: source, it is often in SPD.
3680  *      spidx1: object, it is often from IP header.
3681  * OUT:
3682  *      1 : equal
3683  *      0 : not equal
3684  */
3685 static int
3686 key_cmpspidx_withmask(
3687         struct secpolicyindex *spidx0,
3688         struct secpolicyindex *spidx1)
3689 {
3690         /* sanity */
3691         if (spidx0 == NULL && spidx1 == NULL)
3692                 return 1;
3693
3694         if (spidx0 == NULL || spidx1 == NULL)
3695                 return 0;
3696
3697         if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3698             spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3699             spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3700             spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3701                 return 0;
3702
3703         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3704         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3705          && spidx0->ul_proto != spidx1->ul_proto)
3706                 return 0;
3707
3708         switch (spidx0->src.sa.sa_family) {
3709         case AF_INET:
3710                 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3711                  && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3712                         return 0;
3713                 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3714                     &spidx1->src.sin.sin_addr, spidx0->prefs))
3715                         return 0;
3716                 break;
3717         case AF_INET6:
3718                 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3719                  && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3720                         return 0;
3721                 /*
3722                  * scope_id check. if sin6_scope_id is 0, we regard it
3723                  * as a wildcard scope, which matches any scope zone ID. 
3724                  */
3725                 if (spidx0->src.sin6.sin6_scope_id &&
3726                     spidx1->src.sin6.sin6_scope_id &&
3727                     spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3728                         return 0;
3729                 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3730                     &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3731                         return 0;
3732                 break;
3733         default:
3734                 /* XXX */
3735                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3736                         return 0;
3737                 break;
3738         }
3739
3740         switch (spidx0->dst.sa.sa_family) {
3741         case AF_INET:
3742                 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3743                  && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3744                         return 0;
3745                 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3746                     &spidx1->dst.sin.sin_addr, spidx0->prefd))
3747                         return 0;
3748                 break;
3749         case AF_INET6:
3750                 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3751                  && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3752                         return 0;
3753                 /*
3754                  * scope_id check. if sin6_scope_id is 0, we regard it
3755                  * as a wildcard scope, which matches any scope zone ID. 
3756                  */
3757                 if (spidx0->dst.sin6.sin6_scope_id &&
3758                     spidx1->dst.sin6.sin6_scope_id &&
3759                     spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3760                         return 0;
3761                 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3762                     &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3763                         return 0;
3764                 break;
3765         default:
3766                 /* XXX */
3767                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3768                         return 0;
3769                 break;
3770         }
3771
3772         /* XXX Do we check other field ?  e.g. flowinfo */
3773
3774         return 1;
3775 }
3776
3777 /* returns 0 on match */
3778 static int
3779 key_sockaddrcmp(
3780         const struct sockaddr *sa1,
3781         const struct sockaddr *sa2,
3782         int port)
3783 {
3784 #ifdef satosin
3785 #undef satosin
3786 #endif
3787 #define satosin(s) ((const struct sockaddr_in *)s)
3788 #ifdef satosin6
3789 #undef satosin6
3790 #endif
3791 #define satosin6(s) ((const struct sockaddr_in6 *)s)
3792         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
3793                 return 1;
3794
3795         switch (sa1->sa_family) {
3796         case AF_INET:
3797                 if (sa1->sa_len != sizeof(struct sockaddr_in))
3798                         return 1;
3799                 if (satosin(sa1)->sin_addr.s_addr !=
3800                     satosin(sa2)->sin_addr.s_addr) {
3801                         return 1;
3802                 }
3803                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
3804                         return 1;
3805                 break;
3806         case AF_INET6:
3807                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
3808                         return 1;       /*EINVAL*/
3809                 if (satosin6(sa1)->sin6_scope_id !=
3810                     satosin6(sa2)->sin6_scope_id) {
3811                         return 1;
3812                 }
3813                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
3814                     &satosin6(sa2)->sin6_addr)) {
3815                         return 1;
3816                 }
3817                 if (port &&
3818                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
3819                         return 1;
3820                 }
3821         default:
3822                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
3823                         return 1;
3824                 break;
3825         }
3826
3827         return 0;
3828 #undef satosin
3829 #undef satosin6
3830 }
3831
3832 /*
3833  * compare two buffers with mask.
3834  * IN:
3835  *      addr1: source
3836  *      addr2: object
3837  *      bits:  Number of bits to compare
3838  * OUT:
3839  *      1 : equal
3840  *      0 : not equal
3841  */
3842 static int
3843 key_bbcmp(const void *a1, const void *a2, u_int bits)
3844 {
3845         const unsigned char *p1 = a1;
3846         const unsigned char *p2 = a2;
3847
3848         /* XXX: This could be considerably faster if we compare a word
3849          * at a time, but it is complicated on LSB Endian machines */
3850
3851         /* Handle null pointers */
3852         if (p1 == NULL || p2 == NULL)
3853                 return (p1 == p2);
3854
3855         while (bits >= 8) {
3856                 if (*p1++ != *p2++)
3857                         return 0;
3858                 bits -= 8;
3859         }
3860
3861         if (bits > 0) {
3862                 u_int8_t mask = ~((1<<(8-bits))-1);
3863                 if ((*p1 & mask) != (*p2 & mask))
3864                         return 0;
3865         }
3866         return 1;       /* Match! */
3867 }
3868
3869 /*
3870  * time handler.
3871  * scanning SPD and SAD to check status for each entries,
3872  * and do to remove or to expire.
3873  * XXX: year 2038 problem may remain.
3874  */
3875 void
3876 key_timehandler(void *unused)
3877 {
3878         u_int dir;
3879         time_t now = time_second;
3880         struct secspacq *spacq, *nextspacq;
3881
3882         crit_enter();
3883
3884         /* SPD */
3885     {
3886         struct secpolicy *sp, *nextsp;
3887
3888         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
3889                 LIST_FOREACH_MUTABLE(sp, &sptree[dir], chain, nextsp) {
3890                         if (sp->state == IPSEC_SPSTATE_DEAD) {
3891                                 KEY_FREESP(&sp);
3892                                 continue;
3893                         }
3894
3895                         if (sp->lifetime == 0 && sp->validtime == 0)
3896                                 continue;
3897
3898                         /* the deletion will occur next time */
3899                         if ((sp->lifetime && now - sp->created > sp->lifetime)
3900                          || (sp->validtime && now - sp->lastused > sp->validtime)) {
3901                                 sp->state = IPSEC_SPSTATE_DEAD;
3902                                 key_spdexpire(sp);
3903                                 continue;
3904                         }
3905                 }
3906         }
3907     }
3908
3909         /* SAD */
3910     {
3911         struct secashead *sah, *nextsah;
3912         struct secasvar *sav, *nextsav;
3913
3914         LIST_FOREACH_MUTABLE(sah, &sahtree, chain, nextsah) {
3915                 /* if sah has been dead, then delete it and process next sah. */
3916                 if (sah->state == SADB_SASTATE_DEAD) {
3917                         key_delsah(sah);
3918                         continue;
3919                 }
3920
3921                 /* if LARVAL entry doesn't become MATURE, delete it. */
3922                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_LARVAL],
3923                                      chain, nextsav) {
3924                         if (now - sav->created > key_larval_lifetime) {
3925                                 KEY_FREESAV(&sav);
3926                         }
3927                 }
3928
3929                 /*
3930                  * check MATURE entry to start to send expire message
3931                  * whether or not.
3932                  */
3933                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_MATURE],
3934                                      chain, nextsav) {
3935                         /* we don't need to check. */
3936                         if (sav->lft_s == NULL)
3937                                 continue;
3938
3939                         /* sanity check */
3940                         if (sav->lft_c == NULL) {
3941                                 ipseclog((LOG_DEBUG,"key_timehandler: "
3942                                         "There is no CURRENT time, why?\n"));
3943                                 continue;
3944                         }
3945
3946                         /* check SOFT lifetime */
3947                         if (sav->lft_s->sadb_lifetime_addtime != 0
3948                          && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
3949                                 /*
3950                                  * check SA to be used whether or not.
3951                                  * when SA hasn't been used, delete it.
3952                                  */
3953                                 if (sav->lft_c->sadb_lifetime_usetime == 0) {
3954                                         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
3955                                         KEY_FREESAV(&sav);
3956                                 } else {
3957                                         key_sa_chgstate(sav, SADB_SASTATE_DYING);
3958                                         /*
3959                                          * XXX If we keep to send expire
3960                                          * message in the status of
3961                                          * DYING. Do remove below code.
3962                                          */
3963                                         key_expire(sav);
3964                                 }
3965                         }
3966                         /* check SOFT lifetime by bytes */
3967                         /*
3968                          * XXX I don't know the way to delete this SA
3969                          * when new SA is installed.  Caution when it's
3970                          * installed too big lifetime by time.
3971                          */
3972                         else if (sav->lft_s->sadb_lifetime_bytes != 0
3973                               && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
3974
3975                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
3976                                 /*
3977                                  * XXX If we keep to send expire
3978                                  * message in the status of
3979                                  * DYING. Do remove below code.
3980                                  */
3981                                 key_expire(sav);
3982                         }
3983                 }
3984
3985                 /* check DYING entry to change status to DEAD. */
3986                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_DYING],
3987                                      chain, nextsav) {
3988                         /* we don't need to check. */
3989                         if (sav->lft_h == NULL)
3990                                 continue;
3991
3992                         /* sanity check */
3993                         if (sav->lft_c == NULL) {
3994                                 ipseclog((LOG_DEBUG, "key_timehandler: "
3995                                         "There is no CURRENT time, why?\n"));
3996                                 continue;
3997                         }
3998
3999                         if (sav->lft_h->sadb_lifetime_addtime != 0
4000                          && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4001                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4002                                 KEY_FREESAV(&sav);
4003                         }
4004 #if 0   /* XXX Should we keep to send expire message until HARD lifetime ? */
4005                         else if (sav->lft_s != NULL
4006                               && sav->lft_s->sadb_lifetime_addtime != 0
4007                               && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4008                                 /*
4009                                  * XXX: should be checked to be
4010                                  * installed the valid SA.
4011                                  */
4012
4013                                 /*
4014                                  * If there is no SA then sending
4015                                  * expire message.
4016                                  */
4017                                 key_expire(sav);
4018                         }
4019 #endif
4020                         /* check HARD lifetime by bytes */
4021                         else if (sav->lft_h->sadb_lifetime_bytes != 0
4022                               && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4023                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4024                                 KEY_FREESAV(&sav);
4025                         }
4026                 }
4027
4028                 /* delete entry in DEAD */
4029                 LIST_FOREACH_MUTABLE(sav, &sah->savtree[SADB_SASTATE_DEAD],
4030                                      chain, nextsav) {
4031                         /* sanity check */
4032                         if (sav->state != SADB_SASTATE_DEAD) {
4033                                 ipseclog((LOG_DEBUG, "key_timehandler: "
4034                                         "invalid sav->state "
4035                                         "(queue: %d SA: %d): "
4036                                         "kill it anyway\n",
4037                                         SADB_SASTATE_DEAD, sav->state));
4038                         }
4039
4040                         /*
4041                          * do not call key_freesav() here.
4042                          * sav should already be freed, and sav->refcnt
4043                          * shows other references to sav
4044                          * (such as from SPD).
4045                          */
4046                 }
4047         }
4048     }
4049
4050 #ifndef IPSEC_NONBLOCK_ACQUIRE
4051         /* ACQ tree */
4052     {
4053         struct secacq *acq, *nextacq;
4054
4055         LIST_FOREACH_MUTABLE(acq, &acqtree, chain, nextacq) {
4056                 if (now - acq->created > key_blockacq_lifetime &&
4057                     __LIST_CHAINED(acq)) {
4058                         LIST_REMOVE(acq, chain);
4059                         KFREE(acq);
4060                 }
4061         }
4062     }
4063 #endif
4064
4065         /* SP ACQ tree */
4066         LIST_FOREACH_MUTABLE(spacq, &spacqtree, chain, nextspacq) {
4067                 if (now - spacq->created > key_blockacq_lifetime &&
4068                     __LIST_CHAINED(spacq)) {
4069                         LIST_REMOVE(spacq, chain);
4070                         KFREE(spacq);
4071                 }
4072         }
4073
4074         /* initialize random seed */
4075         if (key_tick_init_random++ > key_int_random) {
4076                 key_tick_init_random = 0;
4077                 key_srandom();
4078         }
4079
4080 #ifndef IPSEC_DEBUG2
4081         /* do exchange to tick time !! */
4082         callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
4083 #endif
4084
4085         crit_exit();
4086         return;
4087 }
4088
4089 /*
4090  * to initialize a seed for random()
4091  */
4092 static void
4093 key_srandom(void)
4094 {
4095         skrandom(time_second);
4096 }
4097
4098 u_long
4099 key_random(void)
4100 {
4101         u_long value;
4102
4103         key_randomfill(&value, sizeof(value));
4104         return value;
4105 }
4106
4107 void
4108 key_randomfill(void *p, size_t l)
4109 {
4110         size_t n;
4111         u_long v;
4112         static int warn = 1;
4113
4114         n = (size_t)read_random(p, (u_int)l);
4115         /* last resort */
4116         while (n < l) {
4117                 v = krandom();
4118                 bcopy(&v, (u_int8_t *)p + n,
4119                     l - n < sizeof(v) ? l - n : sizeof(v));
4120                 n += sizeof(v);
4121
4122                 if (warn) {
4123                         kprintf("WARNING: pseudo-random number generator "
4124                             "used for IPsec processing\n");
4125                         warn = 0;
4126                 }
4127         }
4128 }
4129
4130 /*
4131  * map SADB_SATYPE_* to IPPROTO_*.
4132  * if satype == SADB_SATYPE then satype is mapped to ~0.
4133  * OUT:
4134  *      0: invalid satype.
4135  */
4136 static u_int16_t
4137 key_satype2proto(u_int8_t satype)
4138 {
4139         switch (satype) {
4140         case SADB_SATYPE_UNSPEC:
4141                 return IPSEC_PROTO_ANY;
4142         case SADB_SATYPE_AH:
4143                 return IPPROTO_AH;
4144         case SADB_SATYPE_ESP:
4145                 return IPPROTO_ESP;
4146         case SADB_X_SATYPE_IPCOMP:
4147                 return IPPROTO_IPCOMP;
4148         default:
4149                 return 0;
4150         }
4151         /* NOTREACHED */
4152 }
4153
4154 /*
4155  * map IPPROTO_* to SADB_SATYPE_*
4156  * OUT:
4157  *      0: invalid protocol type.
4158  */
4159 static u_int8_t
4160 key_proto2satype(u_int16_t proto)
4161 {
4162         switch (proto) {
4163         case IPPROTO_AH:
4164                 return SADB_SATYPE_AH;
4165         case IPPROTO_ESP:
4166                 return SADB_SATYPE_ESP;
4167         case IPPROTO_IPCOMP:
4168                 return SADB_X_SATYPE_IPCOMP;
4169         default:
4170                 return 0;
4171         }
4172         /* NOTREACHED */
4173 }
4174
4175 /* %%% PF_KEY */
4176 /*
4177  * SADB_GETSPI processing is to receive
4178  *      <base, (SA2), src address, dst address, (SPI range)>
4179  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4180  * tree with the status of LARVAL, and send
4181  *      <base, SA(*), address(SD)>
4182  * to the IKMPd.
4183  *
4184  * IN:  mhp: pointer to the pointer to each header.
4185  * OUT: NULL if fail.
4186  *      other if success, return pointer to the message to send.
4187  */
4188 static int
4189 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4190 {
4191         struct sadb_address *src0, *dst0;
4192         struct secasindex saidx;
4193         struct secashead *newsah;
4194         struct secasvar *newsav;
4195         struct sockaddr *saddr, *daddr;
4196         u_int8_t proto;
4197         u_int32_t spi;
4198         u_int8_t mode;
4199         u_int32_t reqid;
4200         int error;
4201
4202         /* sanity check */
4203         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4204                 panic("key_getspi: NULL pointer is passed.");
4205
4206         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4207             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4208                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4209                 return key_senderror(so, m, EINVAL);
4210         }
4211         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4212             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4213                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4214                 return key_senderror(so, m, EINVAL);
4215         }
4216         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4217                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4218                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4219         } else {
4220                 mode = IPSEC_MODE_ANY;
4221                 reqid = 0;
4222         }
4223
4224         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4225         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4226
4227         /* map satype to proto */
4228         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4229                 ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
4230                 return key_senderror(so, m, EINVAL);
4231         }
4232
4233         /* make sure if port number is zero. */
4234         saddr = (struct sockaddr *)(src0 + 1);
4235         daddr = (struct sockaddr *)(dst0 + 1);
4236         switch (saddr->sa_family) {
4237         case AF_INET:
4238                 if (saddr->sa_len != sizeof(struct sockaddr_in))
4239                         return key_senderror(so, m, EINVAL);
4240                 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4241                 break;
4242         case AF_INET6:
4243                 if (saddr->sa_len != sizeof(struct sockaddr_in6))
4244                         return key_senderror(so, m, EINVAL);
4245                 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4246                 break;
4247         default:
4248                 ; /*???*/
4249         }
4250         switch (daddr->sa_family) {
4251         case AF_INET:
4252                 if (daddr->sa_len != sizeof(struct sockaddr_in))
4253                         return key_senderror(so, m, EINVAL);
4254                 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4255                 break;
4256         case AF_INET6:
4257                 if (daddr->sa_len != sizeof(struct sockaddr_in6))
4258                         return key_senderror(so, m, EINVAL);
4259                 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4260                 break;
4261         default:
4262                 ; /*???*/
4263         }
4264
4265         /* XXX boundary check against sa_len */
4266         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4267
4268         /* SPI allocation */
4269         spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4270                                &saidx);
4271         if (spi == 0)
4272                 return key_senderror(so, m, EINVAL);
4273
4274         /* get a SA index */
4275         if ((newsah = key_getsah(&saidx)) == NULL) {
4276                 /* create a new SA index */
4277                 if ((newsah = key_newsah(&saidx)) == NULL) {
4278                         ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
4279                         return key_senderror(so, m, ENOBUFS);
4280                 }
4281         }
4282
4283         /* get a new SA */
4284         /* XXX rewrite */
4285         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4286         if (newsav == NULL) {
4287                 /* XXX don't free new SA index allocated in above. */
4288                 return key_senderror(so, m, error);
4289         }
4290
4291         /* set spi */
4292         newsav->spi = htonl(spi);
4293
4294 #ifndef IPSEC_NONBLOCK_ACQUIRE
4295         /* delete the entry in acqtree */
4296         if (mhp->msg->sadb_msg_seq != 0) {
4297                 struct secacq *acq;
4298                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4299                         /* reset counter in order to deletion by timehandler. */
4300                         acq->created = time_second;
4301                         acq->count = 0;
4302                 }
4303         }
4304 #endif
4305
4306     {
4307         struct mbuf *n;
4308         struct sadb_sa *m_sa;
4309         struct sadb_msg *newmsg;
4310         int off, len;
4311
4312         /* create new sadb_msg to reply. */
4313         len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4314             PFKEY_ALIGN8(sizeof(struct sadb_sa));
4315         if (len > MCLBYTES)
4316                 return key_senderror(so, m, ENOBUFS);
4317         n = m_getb(len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
4318         if (!n)
4319                 return key_senderror(so, m, ENOBUFS);
4320         n->m_len = len;
4321
4322         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t));
4323         off = PFKEY_ALIGN8(sizeof(struct sadb_msg));
4324
4325         m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4326         m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4327         m_sa->sadb_sa_exttype = SADB_EXT_SA;
4328         m_sa->sadb_sa_spi = htonl(spi);
4329         off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4330
4331 #ifdef DIAGNOSTIC
4332         if (off != len)
4333                 panic("length inconsistency in key_getspi");
4334 #endif
4335
4336         n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4337             SADB_EXT_ADDRESS_DST);
4338         if (!n->m_next) {
4339                 m_freem(n);
4340                 return key_senderror(so, m, ENOBUFS);
4341         }
4342
4343         if (n->m_len < sizeof(struct sadb_msg)) {
4344                 n = m_pullup(n, sizeof(struct sadb_msg));
4345                 if (n == NULL)
4346                         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4347         }
4348         n->m_pkthdr.len = m_lengthm(n, NULL);
4349
4350         newmsg = mtod(n, struct sadb_msg *);
4351         newmsg->sadb_msg_seq = newsav->seq;
4352         newmsg->sadb_msg_errno = 0;
4353         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4354
4355         m_freem(m);
4356         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4357     }
4358 }
4359
4360 /*
4361  * allocating new SPI
4362  * called by key_getspi().
4363  * OUT:
4364  *      0:      failure.
4365  *      others: success.
4366  */
4367 static u_int32_t
4368 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
4369 {
4370         u_int32_t newspi;
4371         u_int32_t min, max;
4372         int count = key_spi_trycnt;
4373
4374         /* set spi range to allocate */
4375         if (spirange != NULL) {
4376                 min = spirange->sadb_spirange_min;
4377                 max = spirange->sadb_spirange_max;
4378         } else {
4379                 min = key_spi_minval;
4380                 max = key_spi_maxval;
4381         }
4382         /* IPCOMP needs 2-byte SPI */
4383         if (saidx->proto == IPPROTO_IPCOMP) {
4384                 u_int32_t t;
4385                 if (min >= 0x10000)
4386                         min = 0xffff;
4387                 if (max >= 0x10000)
4388                         max = 0xffff;
4389                 if (min > max) {
4390                         t = min; min = max; max = t;
4391                 }
4392         }
4393
4394         if (min == max) {
4395                 if (key_checkspidup(saidx, min) != NULL) {
4396                         ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
4397                         return 0;
4398                 }
4399
4400                 count--; /* taking one cost. */
4401                 newspi = min;
4402
4403         } else {
4404
4405                 /* init SPI */
4406                 newspi = 0;
4407
4408                 /* when requesting to allocate spi ranged */
4409                 while (count--) {
4410                         /* generate pseudo-random SPI value ranged. */
4411                         newspi = min + (key_random() % (max - min + 1));
4412
4413                         if (key_checkspidup(saidx, newspi) == NULL)
4414                                 break;
4415                 }
4416
4417                 if (count == 0 || newspi == 0) {
4418                         ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
4419                         return 0;
4420                 }
4421         }
4422
4423         /* statistics */
4424         keystat.getspi_count =
4425                 (keystat.getspi_count + key_spi_trycnt - count) / 2;
4426
4427         return newspi;
4428 }
4429
4430 /*
4431  * SADB_UPDATE processing
4432  * receive
4433  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4434  *       key(AE), (identity(SD),) (sensitivity)>
4435  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4436  * and send
4437  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4438  *       (identity(SD),) (sensitivity)>
4439  * to the ikmpd.
4440  *
4441  * m will always be freed.
4442  */
4443 static int
4444 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4445 {
4446         struct sadb_sa *sa0;
4447         struct sadb_address *src0, *dst0;
4448         struct secasindex saidx;
4449         struct secashead *sah;
4450         struct secasvar *sav;
4451         u_int16_t proto;
4452         u_int8_t mode;
4453         u_int32_t reqid;
4454         int error;
4455
4456         /* sanity check */
4457         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4458                 panic("key_update: NULL pointer is passed.");
4459
4460         /* map satype to proto */
4461         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4462                 ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
4463                 return key_senderror(so, m, EINVAL);
4464         }
4465
4466         if (mhp->ext[SADB_EXT_SA] == NULL ||
4467             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4468             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4469             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4470              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4471             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4472              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4473             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4474              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4475             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4476              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4477                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4478                 return key_senderror(so, m, EINVAL);
4479         }
4480         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4481             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4482             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4483                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4484                 return key_senderror(so, m, EINVAL);
4485         }
4486         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4487                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4488                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4489         } else {
4490                 mode = IPSEC_MODE_ANY;
4491                 reqid = 0;
4492         }
4493         /* XXX boundary checking for other extensions */
4494
4495         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4496         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4497         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4498
4499         /* XXX boundary check against sa_len */
4500         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4501
4502         /* get a SA header */
4503         if ((sah = key_getsah(&saidx)) == NULL) {
4504                 ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
4505                 return key_senderror(so, m, ENOENT);
4506         }
4507
4508         /* set spidx if there */
4509         /* XXX rewrite */
4510         error = key_setident(sah, m, mhp);
4511         if (error)
4512                 return key_senderror(so, m, error);
4513
4514         /* find a SA with sequence number. */
4515 #ifdef IPSEC_DOSEQCHECK
4516         if (mhp->msg->sadb_msg_seq != 0
4517          && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4518                 ipseclog((LOG_DEBUG,
4519                     "key_update: no larval SA with sequence %u exists.\n",
4520                     mhp->msg->sadb_msg_seq));
4521                 return key_senderror(so, m, ENOENT);
4522         }
4523 #else
4524         if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
4525                 ipseclog((LOG_DEBUG,
4526                     "key_update: no such a SA found (spi:%u)\n",
4527                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4528                 return key_senderror(so, m, EINVAL);
4529         }
4530 #endif
4531
4532         /* validity check */
4533         if (sav->sah->saidx.proto != proto) {
4534                 ipseclog((LOG_DEBUG,
4535                     "key_update: protocol mismatched (DB=%u param=%u)\n",
4536                     sav->sah->saidx.proto, proto));
4537                 return key_senderror(so, m, EINVAL);
4538         }
4539 #ifdef IPSEC_DOSEQCHECK
4540         if (sav->spi != sa0->sadb_sa_spi) {
4541                 ipseclog((LOG_DEBUG,
4542                     "key_update: SPI mismatched (DB:%u param:%u)\n",
4543                     (u_int32_t)ntohl(sav->spi),
4544                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4545                 return key_senderror(so, m, EINVAL);
4546         }
4547 #endif
4548         if (sav->pid != mhp->msg->sadb_msg_pid) {
4549                 ipseclog((LOG_DEBUG,
4550                     "key_update: pid mismatched (DB:%u param:%u)\n",
4551                     sav->pid, mhp->msg->sadb_msg_pid));
4552                 return key_senderror(so, m, EINVAL);
4553         }
4554
4555         /* copy sav values */
4556         error = key_setsaval(sav, m, mhp);
4557         if (error) {
4558                 KEY_FREESAV(&sav);
4559                 return key_senderror(so, m, error);
4560         }
4561
4562         /* check SA values to be mature. */
4563         if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4564                 KEY_FREESAV(&sav);
4565                 return key_senderror(so, m, 0);
4566         }
4567
4568     {
4569         struct mbuf *n;
4570
4571         /* set msg buf from mhp */
4572         n = key_getmsgbuf_x1(m, mhp);
4573         if (n == NULL) {
4574                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4575                 return key_senderror(so, m, ENOBUFS);
4576         }
4577
4578         m_freem(m);
4579         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4580     }
4581 }
4582
4583 /*
4584  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4585  * only called by key_update().
4586  * OUT:
4587  *      NULL    : not found
4588  *      others  : found, pointer to a SA.
4589  */
4590 #ifdef IPSEC_DOSEQCHECK
4591 static struct secasvar *
4592 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
4593 {
4594         struct secasvar *sav;
4595         u_int state;
4596
4597         state = SADB_SASTATE_LARVAL;
4598
4599         /* search SAD with sequence number ? */
4600         LIST_FOREACH(sav, &sah->savtree[state], chain) {
4601
4602                 KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
4603
4604                 if (sav->seq == seq) {
4605                         SA_ADDREF(sav);
4606                         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4607                                 kprintf("DP key_getsavbyseq cause "
4608                                         "refcnt++:%d SA:%p\n",
4609                                         sav->refcnt, sav));
4610                         return sav;
4611                 }
4612         }
4613
4614         return NULL;
4615 }
4616 #endif
4617
4618 /*
4619  * SADB_ADD processing
4620  * add an entry to SA database, when received
4621  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4622  *       key(AE), (identity(SD),) (sensitivity)>
4623  * from the ikmpd,
4624  * and send
4625  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4626  *       (identity(SD),) (sensitivity)>
4627  * to the ikmpd.
4628  *
4629  * IGNORE identity and sensitivity messages.
4630  *
4631  * m will always be freed.
4632  */
4633 static int
4634 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4635 {
4636         struct sadb_sa *sa0;
4637         struct sadb_address *src0, *dst0;
4638         struct secasindex saidx;
4639         struct secashead *newsah;
4640         struct secasvar *newsav;
4641         u_int16_t proto;
4642         u_int8_t mode;
4643         u_int32_t reqid;
4644         int error;
4645
4646         /* sanity check */
4647         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4648                 panic("key_add: NULL pointer is passed.");
4649
4650         /* map satype to proto */
4651         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4652                 ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
4653                 return key_senderror(so, m, EINVAL);
4654         }
4655
4656         if (mhp->ext[SADB_EXT_SA] == NULL ||
4657             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4658             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4659             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4660              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4661             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4662              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4663             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4664              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4665             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4666              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4667                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4668                 return key_senderror(so, m, EINVAL);
4669         }
4670         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4671             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4672             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4673                 /* XXX need more */
4674                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4675                 return key_senderror(so, m, EINVAL);
4676         }
4677         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4678                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4679                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4680         } else {
4681                 mode = IPSEC_MODE_ANY;
4682                 reqid = 0;
4683         }
4684
4685         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4686         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4687         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4688
4689         /* XXX boundary check against sa_len */
4690         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4691
4692         /* get a SA header */
4693         if ((newsah = key_getsah(&saidx)) == NULL) {
4694                 /* create a new SA header */
4695                 if ((newsah = key_newsah(&saidx)) == NULL) {
4696                         ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
4697                         return key_senderror(so, m, ENOBUFS);
4698                 }
4699         }
4700
4701         /* set spidx if there */
4702         /* XXX rewrite */
4703         error = key_setident(newsah, m, mhp);
4704         if (error) {
4705                 return key_senderror(so, m, error);
4706         }
4707
4708         /* create new SA entry. */
4709         /* We can create new SA only if SPI is differenct. */
4710         if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
4711                 ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
4712                 return key_senderror(so, m, EEXIST);
4713         }
4714         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4715         if (newsav == NULL) {
4716                 return key_senderror(so, m, error);
4717         }
4718
4719         /* check SA values to be mature. */
4720         if ((error = key_mature(newsav)) != 0) {
4721                 KEY_FREESAV(&newsav);
4722                 return key_senderror(so, m, error);
4723         }
4724
4725         /*
4726          * don't call key_freesav() here, as we would like to keep the SA
4727          * in the database on success.
4728          */
4729
4730     {
4731         struct mbuf *n;
4732
4733         /* set msg buf from mhp */
4734         n = key_getmsgbuf_x1(m, mhp);
4735         if (n == NULL) {
4736                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4737                 return key_senderror(so, m, ENOBUFS);
4738         }
4739
4740         m_freem(m);
4741         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4742     }
4743 }
4744
4745 /* m is retained */
4746 static int
4747 key_setident(struct secashead *sah, struct mbuf *m,
4748              const struct sadb_msghdr *mhp)
4749 {
4750         const struct sadb_ident *idsrc, *iddst;
4751         int idsrclen, iddstlen;
4752
4753         /* sanity check */
4754         if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4755                 panic("key_setident: NULL pointer is passed.");
4756
4757         /* don't make buffer if not there */
4758         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
4759             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4760                 sah->idents = NULL;
4761                 sah->identd = NULL;
4762                 return 0;
4763         }
4764         
4765         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
4766             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4767                 ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
4768                 return EINVAL;
4769         }
4770
4771         idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
4772         iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
4773         idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
4774         iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
4775
4776         /* validity check */
4777         if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
4778                 ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
4779                 return EINVAL;
4780         }
4781
4782         switch (idsrc->sadb_ident_type) {
4783         case SADB_IDENTTYPE_PREFIX:
4784         case SADB_IDENTTYPE_FQDN:
4785         case SADB_IDENTTYPE_USERFQDN:
4786         default:
4787                 /* XXX do nothing */
4788                 sah->idents = NULL;
4789                 sah->identd = NULL;
4790                 return 0;
4791         }
4792
4793         /* make structure */
4794         KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
4795         if (sah->idents == NULL) {
4796                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
4797                 return ENOBUFS;
4798         }
4799         KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
4800         if (sah->identd == NULL) {
4801                 KFREE(sah->idents);
4802                 sah->idents = NULL;
4803                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
4804                 return ENOBUFS;
4805         }
4806         bcopy(idsrc, sah->idents, idsrclen);
4807         bcopy(iddst, sah->identd, iddstlen);
4808
4809         return 0;
4810 }
4811
4812 /*
4813  * m will not be freed on return.
4814  * it is caller's responsibility to free the result. 
4815  */
4816 static struct mbuf *
4817 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
4818 {
4819         struct mbuf *n;
4820
4821         /* sanity check */
4822         if (m == NULL || mhp == NULL || mhp->msg == NULL)
4823                 panic("key_getmsgbuf_x1: NULL pointer is passed.");
4824
4825         /* create new sadb_msg to reply. */
4826         n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
4827             SADB_EXT_SA, SADB_X_EXT_SA2,
4828             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
4829             SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
4830             SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
4831         if (!n)
4832                 return NULL;
4833
4834         if (n->m_len < sizeof(struct sadb_msg)) {
4835                 n = m_pullup(n, sizeof(struct sadb_msg));
4836                 if (n == NULL)
4837                         return NULL;
4838         }
4839         mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
4840         mtod(n, struct sadb_msg *)->sadb_msg_len =
4841             PFKEY_UNIT64(n->m_pkthdr.len);
4842
4843         return n;
4844 }
4845
4846 static int key_delete_all (struct socket *, struct mbuf *,
4847         const struct sadb_msghdr *, u_int16_t);
4848
4849 /*
4850  * SADB_DELETE processing
4851  * receive
4852  *   <base, SA(*), address(SD)>
4853  * from the ikmpd, and set SADB_SASTATE_DEAD,
4854  * and send,
4855  *   <base, SA(*), address(SD)>
4856  * to the ikmpd.
4857  *
4858  * m will always be freed.
4859  */
4860 static int
4861 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4862 {
4863         struct sadb_sa *sa0;
4864         struct sadb_address *src0, *dst0;
4865         struct secasindex saidx;
4866         struct secashead *sah;
4867         struct secasvar *sav = NULL;
4868         u_int16_t proto;
4869
4870         /* sanity check */
4871         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4872                 panic("key_delete: NULL pointer is passed.");
4873
4874         /* map satype to proto */
4875         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4876                 ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
4877                 return key_senderror(so, m, EINVAL);
4878         }
4879
4880         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4881             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4882                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
4883                 return key_senderror(so, m, EINVAL);
4884         }
4885
4886         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4887             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4888                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
4889                 return key_senderror(so, m, EINVAL);
4890         }
4891
4892         if (mhp->ext[SADB_EXT_SA] == NULL) {
4893                 /*
4894                  * Caller wants us to delete all non-LARVAL SAs
4895                  * that match the src/dst.  This is used during
4896                  * IKE INITIAL-CONTACT.
4897                  */
4898                 ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
4899                 return key_delete_all(so, m, mhp, proto);
4900         } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
4901                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
4902                 return key_senderror(so, m, EINVAL);
4903         }
4904
4905         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4906         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4907         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4908
4909         /* XXX boundary check against sa_len */
4910         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
4911
4912         /* get a SA header */
4913         LIST_FOREACH(sah, &sahtree, chain) {
4914                 if (sah->state == SADB_SASTATE_DEAD)
4915                         continue;
4916                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
4917                         continue;
4918
4919                 /* get a SA with SPI. */
4920                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4921                 if (sav)
4922                         break;
4923         }
4924         if (sah == NULL) {
4925                 ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
4926                 return key_senderror(so, m, ENOENT);
4927         }
4928
4929         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4930         KEY_FREESAV(&sav);
4931
4932     {
4933         struct mbuf *n;
4934         struct sadb_msg *newmsg;
4935
4936         /* create new sadb_msg to reply. */
4937         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
4938             SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
4939         if (!n)
4940                 return key_senderror(so, m, ENOBUFS);
4941
4942         if (n->m_len < sizeof(struct sadb_msg)) {
4943                 n = m_pullup(n, sizeof(struct sadb_msg));
4944                 if (n == NULL)
4945                         return key_senderror(so, m, ENOBUFS);
4946         }
4947         newmsg = mtod(n, struct sadb_msg *);
4948         newmsg->sadb_msg_errno = 0;
4949         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4950
4951         m_freem(m);
4952         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4953     }
4954 }
4955
4956 /*
4957  * delete all SAs for src/dst.  Called from key_delete().
4958  */
4959 static int
4960 key_delete_all(struct socket *so, struct mbuf *m,
4961                const struct sadb_msghdr *mhp, u_int16_t proto)
4962 {
4963         struct sadb_address *src0, *dst0;
4964         struct secasindex saidx;
4965         struct secashead *sah;
4966         struct secasvar *sav, *nextsav;
4967         u_int stateidx, state;
4968         struct mbuf *n;
4969         struct sadb_msg *newmsg;
4970
4971         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4972         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4973
4974         /* XXX boundary check against sa_len */
4975         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
4976
4977         LIST_FOREACH(sah, &sahtree, chain) {
4978                 if (sah->state == SADB_SASTATE_DEAD)
4979                         continue;
4980                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
4981                         continue;
4982
4983                 /* Delete all non-LARVAL SAs. */
4984                 for (stateidx = 0; stateidx < NELEM(saorder_state_alive);
4985                      stateidx++) {
4986                         state = saorder_state_alive[stateidx];
4987                         if (state == SADB_SASTATE_LARVAL)
4988                                 continue;
4989                         LIST_FOREACH_MUTABLE(sav, &sah->savtree[state], chain,
4990                                              nextsav) {
4991                                 /* sanity check */
4992                                 if (sav->state != state) {
4993                                         ipseclog((LOG_DEBUG, "key_delete_all: "
4994                                                "invalid sav->state "
4995                                                "(queue: %d SA: %d)\n",
4996                                                state, sav->state));
4997                                         continue;
4998                                 }
4999                                 
5000                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5001                                 KEY_FREESAV(&sav);
5002                         }
5003                 }
5004         }
5005
5006         /* create new sadb_msg to reply. */
5007         n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5008             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5009         if (!n)
5010                 return key_senderror(so, m, ENOBUFS);
5011
5012         if (n->m_len < sizeof(struct sadb_msg)) {
5013                 n = m_pullup(n, sizeof(struct sadb_msg));
5014                 if (n == NULL)
5015                         return key_senderror(so, m, ENOBUFS);
5016         }
5017         newmsg = mtod(n, struct sadb_msg *);
5018         newmsg->sadb_msg_errno = 0;
5019         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5020
5021         m_freem(m);
5022         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5023 }
5024
5025 /*
5026  * SADB_GET processing
5027  * receive
5028  *   <base, SA(*), address(SD)>
5029  * from the ikmpd, and get a SP and a SA to respond,
5030  * and send,
5031  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5032  *       (identity(SD),) (sensitivity)>
5033  * to the ikmpd.
5034  *
5035  * m will always be freed.
5036  */
5037 static int
5038 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5039 {
5040         struct sadb_sa *sa0;
5041         struct sadb_address *src0, *dst0;
5042         struct secasindex saidx;
5043         struct secashead *sah;
5044         struct secasvar *sav = NULL;
5045         u_int16_t proto;
5046
5047         /* sanity check */
5048         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5049                 panic("key_get: NULL pointer is passed.");
5050
5051         /* map satype to proto */
5052         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5053                 ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
5054                 return key_senderror(so, m, EINVAL);
5055         }
5056
5057         if (mhp->ext[SADB_EXT_SA] == NULL ||
5058             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5059             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5060                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5061                 return key_senderror(so, m, EINVAL);
5062         }
5063         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5064             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5065             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5066                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5067                 return key_senderror(so, m, EINVAL);
5068         }
5069
5070         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5071         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5072         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5073
5074         /* XXX boundary check against sa_len */
5075         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5076
5077         /* get a SA header */
5078         LIST_FOREACH(sah, &sahtree, chain) {
5079                 if (sah->state == SADB_SASTATE_DEAD)
5080                         continue;
5081                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5082                         continue;
5083
5084                 /* get a SA with SPI. */
5085                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5086                 if (sav)
5087                         break;
5088         }
5089         if (sah == NULL) {
5090                 ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5091                 return key_senderror(so, m, ENOENT);
5092         }
5093
5094     {
5095         struct mbuf *n;
5096         u_int8_t satype;
5097
5098         /* map proto to satype */
5099         if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5100                 ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5101                 return key_senderror(so, m, EINVAL);
5102         }
5103
5104         /* create new sadb_msg to reply. */
5105         n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5106             mhp->msg->sadb_msg_pid);
5107         if (!n)
5108                 return key_senderror(so, m, ENOBUFS);
5109
5110         m_freem(m);
5111         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5112     }
5113 }
5114
5115 /* XXX make it sysctl-configurable? */
5116 static void
5117 key_getcomb_setlifetime(struct sadb_comb *comb)
5118 {
5119
5120         comb->sadb_comb_soft_allocations = 1;
5121         comb->sadb_comb_hard_allocations = 1;
5122         comb->sadb_comb_soft_bytes = 0;
5123         comb->sadb_comb_hard_bytes = 0;
5124         comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
5125         comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5126         comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
5127         comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5128 }
5129
5130 /*
5131  * XXX reorder combinations by preference
5132  * XXX no idea if the user wants ESP authentication or not
5133  */
5134 static struct mbuf *
5135 key_getcomb_esp(void)
5136 {
5137         struct sadb_comb *comb;
5138         struct enc_xform *algo;
5139         struct mbuf *result = NULL, *m, *n;
5140         int encmin;
5141         int i, off, o;
5142         int totlen;
5143         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5144
5145         m = NULL;
5146         for (i = 1; i <= SADB_EALG_MAX; i++) {
5147                 algo = esp_algorithm_lookup(i);
5148                 if (algo == NULL)
5149                         continue;
5150
5151                 /* discard algorithms with key size smaller than system min */
5152                 if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5153                         continue;
5154                 if (_BITS(algo->minkey) < ipsec_esp_keymin)
5155                         encmin = ipsec_esp_keymin;
5156                 else
5157                         encmin = _BITS(algo->minkey);
5158
5159                 if (ipsec_esp_auth)
5160                         m = key_getcomb_ah();
5161                 else {
5162                         KASSERT(l <= MLEN,
5163                                 ("key_getcomb_esp: l=%u > MLEN=%lu",
5164                                 l, (u_long) MLEN));
5165                         MGET(m, MB_DONTWAIT, MT_DATA);
5166                         if (m) {
5167                                 M_ALIGN(m, l);
5168                                 m->m_len = l;
5169                                 m->m_next = NULL;
5170                                 bzero(mtod(m, caddr_t), m->m_len);
5171                         }
5172                 }
5173                 if (!m)
5174                         goto fail;
5175
5176                 totlen = m_lengthm(m, NULL);
5177                 KASSERT((totlen % l) == 0,
5178                         ("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
5179
5180                 for (off = 0; off < totlen; off += l) {
5181                         n = m_pulldown(m, off, l, &o);
5182                         if (!n) {
5183                                 /* m is already freed */
5184                                 goto fail;
5185                         }
5186                         comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5187                         bzero(comb, sizeof(*comb));
5188                         key_getcomb_setlifetime(comb);
5189                         comb->sadb_comb_encrypt = i;
5190                         comb->sadb_comb_encrypt_minbits = encmin;
5191                         comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5192                 }
5193
5194                 if (!result)
5195                         result = m;
5196                 else
5197                         m_cat(result, m);
5198         }
5199
5200         return result;
5201
5202  fail:
5203         if (result)
5204                 m_freem(result);
5205         return NULL;
5206 }
5207
5208 static void
5209 key_getsizes_ah(
5210         const struct auth_hash *ah,
5211         int alg,
5212         u_int16_t* min,
5213         u_int16_t* max)
5214 {
5215         *min = *max = ah->keysize;
5216         if (ah->keysize == 0) {
5217                 /*
5218                  * Transform takes arbitrary key size but algorithm
5219                  * key size is restricted.  Enforce this here.
5220                  */
5221                 switch (alg) {
5222                 case SADB_X_AALG_MD5:   *min = *max = 16; break;
5223                 case SADB_X_AALG_SHA:   *min = *max = 20; break;
5224                 case SADB_X_AALG_NULL:  *min = 1; *max = 256; break;
5225                 default:
5226                         DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
5227                                 alg));
5228                         break;
5229                 }
5230         }
5231 }
5232
5233 /*
5234  * XXX reorder combinations by preference
5235  */
5236 static struct mbuf *
5237 key_getcomb_ah(void)
5238 {
5239         struct sadb_comb *comb;
5240         struct auth_hash *algo;
5241         struct mbuf *m;
5242         u_int16_t minkeysize, maxkeysize;
5243         int i;
5244         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5245
5246         m = NULL;
5247         for (i = 1; i <= SADB_AALG_MAX; i++) {
5248 #if 1
5249                 /* we prefer HMAC algorithms, not old algorithms */
5250                 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5251                         continue;
5252 #endif
5253                 algo = ah_algorithm_lookup(i);
5254                 if (!algo)
5255                         continue;
5256                 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5257                 /* discard algorithms with key size smaller than system min */
5258                 if (_BITS(minkeysize) < ipsec_ah_keymin)
5259                         continue;
5260
5261                 if (!m) {
5262                         KASSERT(l <= MLEN,
5263                                 ("key_getcomb_ah: l=%u > MLEN=%lu",
5264                                 l, (u_long) MLEN));
5265                         MGET(m, MB_DONTWAIT, MT_DATA);
5266                         if (m) {
5267                                 M_ALIGN(m, l);
5268                                 m->m_len = l;
5269                                 m->m_next = NULL;
5270                         }
5271                 } else
5272                         M_PREPEND(m, l, MB_DONTWAIT);
5273                 if (!m)
5274                         return NULL;
5275
5276                 comb = mtod(m, struct sadb_comb *);
5277                 bzero(comb, sizeof(*comb));
5278                 key_getcomb_setlifetime(comb);
5279                 comb->sadb_comb_auth = i;
5280                 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5281                 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5282         }
5283
5284         return m;
5285 }
5286
5287 /*
5288  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5289  * XXX reorder combinations by preference
5290  */
5291 static struct mbuf *
5292 key_getcomb_ipcomp(void)
5293 {
5294         struct sadb_comb *comb;
5295         struct comp_algo *algo;
5296         struct mbuf *m;
5297         int i;
5298         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5299
5300         m = NULL;
5301         for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5302                 algo = ipcomp_algorithm_lookup(i);
5303                 if (!algo)
5304                         continue;
5305
5306                 if (!m) {
5307                         KASSERT(l <= MLEN,
5308                                 ("key_getcomb_ipcomp: l=%u > MLEN=%lu",
5309                                 l, (u_long) MLEN));
5310                         MGET(m, MB_DONTWAIT, MT_DATA);
5311                         if (m) {
5312                                 M_ALIGN(m, l);
5313                                 m->m_len = l;
5314                                 m->m_next = NULL;
5315                         }
5316                 } else
5317                         M_PREPEND(m, l, MB_DONTWAIT);
5318                 if (!m)
5319                         return NULL;
5320
5321                 comb = mtod(m, struct sadb_comb *);
5322                 bzero(comb, sizeof(*comb));
5323                 key_getcomb_setlifetime(comb);
5324                 comb->sadb_comb_encrypt = i;
5325                 /* what should we set into sadb_comb_*_{min,max}bits? */
5326         }
5327
5328         return m;
5329 }
5330
5331 /*
5332  * XXX no way to pass mode (transport/tunnel) to userland
5333  * XXX replay checking?
5334  * XXX sysctl interface to ipsec_{ah,esp}_keymin
5335  */
5336 static struct mbuf *
5337 key_getprop(const struct secasindex *saidx)
5338 {
5339         struct sadb_prop *prop;
5340         struct mbuf *m;
5341         const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5342
5343         switch (saidx->proto)  {
5344         case IPPROTO_ESP:
5345                 m = key_getcomb_esp();
5346                 break;
5347         case IPPROTO_AH:
5348                 m = key_getcomb_ah();
5349                 break;
5350         case IPPROTO_IPCOMP:
5351                 m = key_getcomb_ipcomp();
5352                 break;
5353         default:
5354                 return NULL;
5355         }
5356
5357         if (!m)
5358                 return NULL;
5359         M_PREPEND(m, l, MB_DONTWAIT);
5360         if (!m)
5361                 return NULL;
5362
5363         prop = mtod(m, struct sadb_prop *);
5364         bzero(prop, sizeof(*prop));
5365         prop->sadb_prop_len = PFKEY_UNIT64(m_lengthm(m, NULL));
5366         prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5367         prop->sadb_prop_replay = 32;    /* XXX */
5368
5369         return m;
5370 }
5371
5372 /*
5373  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5374  * send
5375  *   <base, SA, address(SD), (address(P)), x_policy,
5376  *       (identity(SD),) (sensitivity,) proposal>
5377  * to KMD, and expect to receive
5378  *   <base> with SADB_ACQUIRE if error occured,
5379  * or
5380  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5381  * from KMD by PF_KEY.
5382  *
5383  * XXX x_policy is outside of RFC2367 (KAME extension).
5384  * XXX sensitivity is not supported.
5385  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5386  * see comment for key_getcomb_ipcomp().
5387  *
5388  * OUT:
5389  *    0     : succeed
5390  *    others: error number
5391  */
5392 static int
5393 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5394 {
5395         struct mbuf *result = NULL, *m;
5396 #ifndef IPSEC_NONBLOCK_ACQUIRE
5397         struct secacq *newacq;
5398 #endif
5399         u_int8_t satype;
5400         int error = -1;
5401         u_int32_t seq;
5402
5403         /* sanity check */
5404         KASSERT(saidx != NULL, ("key_acquire: null saidx"));
5405         satype = key_proto2satype(saidx->proto);
5406         KASSERT(satype != 0,
5407                 ("key_acquire: null satype, protocol %u", saidx->proto));
5408
5409 #ifndef IPSEC_NONBLOCK_ACQUIRE
5410         /*
5411          * We never do anything about acquirng SA.  There is anather
5412          * solution that kernel blocks to send SADB_ACQUIRE message until
5413          * getting something message from IKEd.  In later case, to be
5414          * managed with ACQUIRING list.
5415          */
5416         /* Get an entry to check whether sending message or not. */
5417         if ((newacq = key_getacq(saidx)) != NULL) {
5418                 if (key_blockacq_count < newacq->count) {
5419                         /* reset counter and do send message. */
5420                         newacq->count = 0;
5421                 } else {
5422                         /* increment counter and do nothing. */
5423                         newacq->count++;
5424                         return 0;
5425                 }
5426         } else {
5427                 /* make new entry for blocking to send SADB_ACQUIRE. */
5428                 if ((newacq = key_newacq(saidx)) == NULL)
5429                         return ENOBUFS;
5430
5431                 /* add to acqtree */
5432                 LIST_INSERT_HEAD(&acqtree, newacq, chain);
5433         }
5434 #endif
5435
5436
5437 #ifndef IPSEC_NONBLOCK_ACQUIRE
5438         seq = newacq->seq;
5439 #else
5440         seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
5441 #endif
5442         m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5443         if (!m) {
5444                 error = ENOBUFS;
5445                 goto fail;
5446         }
5447         result = m;
5448
5449         /* set sadb_address for saidx's. */
5450         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5451             &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5452         if (!m) {
5453                 error = ENOBUFS;
5454                 goto fail;
5455         }
5456         m_cat(result, m);
5457
5458         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5459             &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5460         if (!m) {
5461                 error = ENOBUFS;
5462                 goto fail;
5463         }
5464         m_cat(result, m);
5465
5466         /* XXX proxy address (optional) */
5467
5468         /* set sadb_x_policy */
5469         if (sp) {
5470                 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5471                 if (!m) {
5472                         error = ENOBUFS;
5473                         goto fail;
5474                 }
5475                 m_cat(result, m);
5476         }
5477
5478         /* XXX identity (optional) */
5479 #if 0
5480         if (idexttype && fqdn) {
5481                 /* create identity extension (FQDN) */
5482                 struct sadb_ident *id;
5483                 int fqdnlen;
5484
5485                 fqdnlen = strlen(fqdn) + 1;     /* +1 for terminating-NUL */
5486                 id = (struct sadb_ident *)p;
5487                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5488                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5489                 id->sadb_ident_exttype = idexttype;
5490                 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5491                 bcopy(fqdn, id + 1, fqdnlen);
5492                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5493         }
5494
5495         if (idexttype) {
5496                 /* create identity extension (USERFQDN) */
5497                 struct sadb_ident *id;
5498                 int userfqdnlen;
5499
5500                 if (userfqdn) {
5501                         /* +1 for terminating-NUL */
5502                         userfqdnlen = strlen(userfqdn) + 1;
5503                 } else
5504                         userfqdnlen = 0;
5505                 id = (struct sadb_ident *)p;
5506                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5507                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5508                 id->sadb_ident_exttype = idexttype;
5509                 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5510                 /* XXX is it correct? */
5511                 if (curproc && curproc->p_cred)
5512                         id->sadb_ident_id = curproc->p_cred->p_ruid;
5513                 if (userfqdn && userfqdnlen)
5514                         bcopy(userfqdn, id + 1, userfqdnlen);
5515                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5516         }
5517 #endif
5518
5519         /* XXX sensitivity (optional) */
5520
5521         /* create proposal/combination extension */
5522         m = key_getprop(saidx);
5523 #if 0
5524         /*
5525          * spec conformant: always attach proposal/combination extension,
5526          * the problem is that we have no way to attach it for ipcomp,
5527          * due to the way sadb_comb is declared in RFC2367.
5528          */
5529         if (!m) {
5530                 error = ENOBUFS;
5531                 goto fail;
5532         }
5533         m_cat(result, m);
5534 #else
5535         /*
5536          * outside of spec; make proposal/combination extension optional.
5537          */
5538         if (m)
5539                 m_cat(result, m);
5540 #endif
5541
5542         if ((result->m_flags & M_PKTHDR) == 0) {
5543                 error = EINVAL;
5544                 goto fail;
5545         }
5546
5547         if (result->m_len < sizeof(struct sadb_msg)) {
5548                 result = m_pullup(result, sizeof(struct sadb_msg));
5549                 if (result == NULL) {
5550                         error = ENOBUFS;
5551                         goto fail;
5552                 }
5553         }
5554         result->m_pkthdr.len = m_lengthm(result, NULL);
5555         mtod(result, struct sadb_msg *)->sadb_msg_len =
5556             PFKEY_UNIT64(result->m_pkthdr.len);
5557
5558         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5559
5560  fail:
5561         if (result)
5562                 m_freem(result);
5563         return error;
5564 }
5565
5566 #ifndef IPSEC_NONBLOCK_ACQUIRE
5567 static struct secacq *
5568 key_newacq(const struct secasindex *saidx)
5569 {
5570         struct secacq *newacq;
5571
5572         /* get new entry */
5573         KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
5574         if (newacq == NULL) {
5575                 ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
5576                 return NULL;
5577         }
5578         bzero(newacq, sizeof(*newacq));
5579
5580         /* copy secindex */
5581         bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5582         newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5583         newacq->created = time_second;
5584         newacq->count = 0;
5585
5586         return newacq;
5587 }
5588
5589 static struct secacq *
5590 key_getacq(const struct secasindex *saidx)
5591 {
5592         struct secacq *acq;
5593
5594         LIST_FOREACH(acq, &acqtree, chain) {
5595                 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5596                         return acq;
5597         }
5598
5599         return NULL;
5600 }
5601
5602 static struct secacq *
5603 key_getacqbyseq(u_int32_t seq)
5604 {
5605         struct secacq *acq;
5606
5607         LIST_FOREACH(acq, &acqtree, chain) {
5608                 if (acq->seq == seq)
5609                         return acq;
5610         }
5611
5612         return NULL;
5613 }
5614 #endif
5615
5616 static struct secspacq *
5617 key_newspacq(struct secpolicyindex *spidx)
5618 {
5619         struct secspacq *acq;
5620
5621         /* get new entry */
5622         KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
5623         if (acq == NULL) {
5624                 ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
5625                 return NULL;
5626         }
5627         bzero(acq, sizeof(*acq));
5628
5629         /* copy secindex */
5630         bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5631         acq->created = time_second;
5632         acq->count = 0;
5633
5634         return acq;
5635 }
5636
5637 static struct secspacq *
5638 key_getspacq(struct secpolicyindex *spidx)
5639 {
5640         struct secspacq *acq;
5641
5642         LIST_FOREACH(acq, &spacqtree, chain) {
5643                 if (key_cmpspidx_exactly(spidx, &acq->spidx))
5644                         return acq;
5645         }
5646
5647         return NULL;
5648 }
5649
5650 /*
5651  * SADB_ACQUIRE processing,
5652  * in first situation, is receiving
5653  *   <base>
5654  * from the ikmpd, and clear sequence of its secasvar entry.
5655  *
5656  * In second situation, is receiving
5657  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5658  * from a user land process, and return
5659  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5660  * to the socket.
5661  *
5662  * m will always be freed.
5663  */
5664 static int
5665 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5666 {
5667         const struct sadb_address *src0, *dst0;
5668         struct secasindex saidx;
5669         struct secashead *sah;
5670         u_int16_t proto;
5671         int error;
5672
5673         /* sanity check */
5674         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5675                 panic("key_acquire2: NULL pointer is passed.");
5676
5677         /*
5678          * Error message from KMd.
5679          * We assume that if error was occured in IKEd, the length of PFKEY
5680          * message is equal to the size of sadb_msg structure.
5681          * We do not raise error even if error occured in this function.
5682          */
5683         if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5684 #ifndef IPSEC_NONBLOCK_ACQUIRE
5685                 struct secacq *acq;
5686
5687                 /* check sequence number */
5688                 if (mhp->msg->sadb_msg_seq == 0) {
5689                         ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
5690                         m_freem(m);
5691                         return 0;
5692                 }
5693
5694                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5695                         /*
5696                          * the specified larval SA is already gone, or we got
5697                          * a bogus sequence number.  we can silently ignore it.
5698                          */
5699                         m_freem(m);
5700                         return 0;
5701                 }
5702
5703                 /* reset acq counter in order to deletion by timehander. */
5704                 acq->created = time_second;
5705                 acq->count = 0;
5706 #endif
5707                 m_freem(m);
5708                 return 0;
5709         }
5710
5711         /*
5712          * This message is from user land.
5713          */
5714
5715         /* map satype to proto */
5716         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5717                 ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
5718                 return key_senderror(so, m, EINVAL);
5719         }
5720
5721         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5722             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5723             mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
5724                 /* error */
5725                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
5726                 return key_senderror(so, m, EINVAL);
5727         }
5728         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5729             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
5730             mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
5731                 /* error */
5732                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
5733                 return key_senderror(so, m, EINVAL);
5734         }
5735
5736         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5737         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5738
5739         /* XXX boundary check against sa_len */
5740         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5741
5742         /* get a SA index */
5743         LIST_FOREACH(sah, &sahtree, chain) {
5744                 if (sah->state == SADB_SASTATE_DEAD)
5745                         continue;
5746                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
5747                         break;
5748         }
5749         if (sah != NULL) {
5750                 ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
5751                 return key_senderror(so, m, EEXIST);
5752         }
5753
5754         error = key_acquire(&saidx, NULL);
5755         if (error != 0) {
5756                 ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
5757                         "from key_acquire.\n", mhp->msg->sadb_msg_errno));
5758                 return key_senderror(so, m, error);
5759         }
5760
5761         return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
5762 }
5763
5764 /*
5765  * SADB_REGISTER processing.
5766  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
5767  * receive
5768  *   <base>
5769  * from the ikmpd, and register a socket to send PF_KEY messages,
5770  * and send
5771  *   <base, supported>
5772  * to KMD by PF_KEY.
5773  * If socket is detached, must free from regnode.
5774  *
5775  * m will always be freed.
5776  */
5777 static int
5778 key_register(struct socket *so, struct mbuf *m,
5779              const struct sadb_msghdr *mhp)
5780 {
5781         struct secreg *reg, *newreg = NULL;
5782
5783         /* sanity check */
5784         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5785                 panic("key_register: NULL pointer is passed.");
5786
5787         /* check for invalid register message */
5788         if (mhp->msg->sadb_msg_satype >= NELEM(regtree))
5789                 return key_senderror(so, m, EINVAL);
5790
5791         /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
5792         if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
5793                 goto setmsg;
5794
5795         /* check whether existing or not */
5796         LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
5797                 if (reg->so == so) {
5798                         ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
5799                         return key_senderror(so, m, EEXIST);
5800                 }
5801         }
5802
5803         /* create regnode */
5804         KMALLOC(newreg, struct secreg *, sizeof(*newreg));
5805         if (newreg == NULL) {
5806                 ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
5807                 return key_senderror(so, m, ENOBUFS);
5808         }
5809         bzero((caddr_t)newreg, sizeof(*newreg));
5810
5811         newreg->so = so;
5812         ((struct keycb *)sotorawcb(so))->kp_registered++;
5813
5814         /* add regnode to regtree. */
5815         LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
5816
5817   setmsg:
5818     {
5819         struct mbuf *n;
5820         struct sadb_msg *newmsg;
5821         struct sadb_supported *sup;
5822         u_int len, alen, elen;
5823         int off;
5824         int i;
5825         struct sadb_alg *alg;
5826
5827         /* create new sadb_msg to reply. */
5828         alen = 0;
5829         for (i = 1; i <= SADB_AALG_MAX; i++) {
5830                 if (ah_algorithm_lookup(i))
5831                         alen += sizeof(struct sadb_alg);
5832         }
5833         if (alen)
5834                 alen += sizeof(struct sadb_supported);
5835         elen = 0;
5836         for (i = 1; i <= SADB_EALG_MAX; i++) {
5837                 if (esp_algorithm_lookup(i))
5838                         elen += sizeof(struct sadb_alg);
5839         }
5840         if (elen)
5841                 elen += sizeof(struct sadb_supported);
5842
5843         len = sizeof(struct sadb_msg) + alen + elen;
5844
5845         if (len > MCLBYTES)
5846                 return key_senderror(so, m, ENOBUFS);
5847         n = m_getb(len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
5848         if (!n)
5849                 return key_senderror(so, m, ENOBUFS);
5850         n->m_pkthdr.len = n->m_len = len;
5851
5852         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t));
5853         newmsg = mtod(n, struct sadb_msg *);
5854         newmsg->sadb_msg_errno = 0;
5855         newmsg->sadb_msg_len = PFKEY_UNIT64(len);
5856         off = PFKEY_ALIGN8(sizeof(struct sadb_msg));
5857
5858         /* for authentication algorithm */
5859         if (alen) {
5860                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
5861                 sup->sadb_supported_len = PFKEY_UNIT64(alen);
5862                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
5863                 off += PFKEY_ALIGN8(sizeof(*sup));
5864
5865                 for (i = 1; i <= SADB_AALG_MAX; i++) {
5866                         struct auth_hash *aalgo;
5867                         u_int16_t minkeysize, maxkeysize;
5868
5869                         aalgo = ah_algorithm_lookup(i);
5870                         if (!aalgo)
5871                                 continue;
5872                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
5873                         alg->sadb_alg_id = i;
5874                         alg->sadb_alg_ivlen = 0;
5875                         key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
5876                         alg->sadb_alg_minbits = _BITS(minkeysize);
5877                         alg->sadb_alg_maxbits = _BITS(maxkeysize);
5878                         off += PFKEY_ALIGN8(sizeof(*alg));
5879                 }
5880         }
5881
5882         /* for encryption algorithm */
5883         if (elen) {
5884                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
5885                 sup->sadb_supported_len = PFKEY_UNIT64(elen);
5886                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
5887                 off += PFKEY_ALIGN8(sizeof(*sup));
5888
5889                 for (i = 1; i <= SADB_EALG_MAX; i++) {
5890                         struct enc_xform *ealgo;
5891
5892                         ealgo = esp_algorithm_lookup(i);
5893                         if (!ealgo)
5894                                 continue;
5895                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
5896                         alg->sadb_alg_id = i;
5897                         alg->sadb_alg_ivlen = ealgo->blocksize;
5898                         alg->sadb_alg_minbits = _BITS(ealgo->minkey);
5899                         alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
5900                         off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
5901                 }
5902         }
5903
5904 #ifdef DIGAGNOSTIC
5905         if (off != len)
5906                 panic("length assumption failed in key_register");
5907 #endif
5908
5909         m_freem(m);
5910         return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
5911     }
5912 }
5913
5914 /*
5915  * free secreg entry registered.
5916  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
5917  */
5918 void
5919 key_freereg(struct socket *so)
5920 {
5921         struct secreg *reg;
5922         int i;
5923
5924         /* sanity check */
5925         if (so == NULL)
5926                 panic("key_freereg: NULL pointer is passed.");
5927
5928         /*
5929          * check whether existing or not.
5930          * check all type of SA, because there is a potential that
5931          * one socket is registered to multiple type of SA.
5932          */
5933         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
5934                 LIST_FOREACH(reg, &regtree[i], chain) {
5935                         if (reg->so == so
5936                          && __LIST_CHAINED(reg)) {
5937                                 LIST_REMOVE(reg, chain);
5938                                 KFREE(reg);
5939                                 break;
5940                         }
5941                 }
5942         }
5943         
5944         return;
5945 }
5946
5947 /*
5948  * SADB_EXPIRE processing
5949  * send
5950  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
5951  * to KMD by PF_KEY.
5952  * NOTE: We send only soft lifetime extension.
5953  *
5954  * OUT: 0       : succeed
5955  *      others  : error number
5956  */
5957 static int
5958 key_expire(struct secasvar *sav)
5959 {
5960         
5961         int satype;
5962         struct mbuf *result = NULL, *m;
5963         int len;
5964         int error = -1;
5965         struct sadb_lifetime *lt;
5966
5967         /* XXX: Why do we lock ? */
5968         crit_enter();
5969
5970         /* sanity check */
5971         if (sav == NULL)
5972                 panic("key_expire: NULL pointer is passed.");
5973         if (sav->sah == NULL)
5974                 panic("key_expire: Why was SA index in SA NULL.");
5975         if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
5976                 panic("key_expire: invalid proto is passed.");
5977
5978         /* set msg header */
5979         m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
5980         if (!m) {
5981                 error = ENOBUFS;
5982                 goto fail;
5983         }
5984         result = m;
5985
5986         /* create SA extension */
5987         m = key_setsadbsa(sav);
5988         if (!m) {
5989                 error = ENOBUFS;
5990                 goto fail;
5991         }
5992         m_cat(result, m);
5993
5994         /* create SA extension */
5995         m = key_setsadbxsa2(sav->sah->saidx.mode,
5996                         sav->replay ? sav->replay->count : 0,
5997                         sav->sah->saidx.reqid);
5998         if (!m) {
5999                 error = ENOBUFS;
6000                 goto fail;
6001         }
6002         m_cat(result, m);
6003
6004         /* create lifetime extension (current and soft) */
6005         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6006         m = key_alloc_mbuf(len);
6007         if (!m || m->m_next) {  /*XXX*/
6008                 if (m)
6009                         m_freem(m);
6010                 error = ENOBUFS;
6011                 goto fail;
6012         }
6013         bzero(mtod(m, caddr_t), len);
6014         lt = mtod(m, struct sadb_lifetime *);
6015         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6016         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6017         lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6018         lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6019         lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6020         lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6021         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6022         bcopy(sav->lft_s, lt, sizeof(*lt));
6023         m_cat(result, m);
6024
6025         /* set sadb_address for source */
6026         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6027             &sav->sah->saidx.src.sa,
6028             FULLMASK, IPSEC_ULPROTO_ANY);
6029         if (!m) {
6030                 error = ENOBUFS;
6031                 goto fail;
6032         }
6033         m_cat(result, m);
6034
6035         /* set sadb_address for destination */
6036         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6037             &sav->sah->saidx.dst.sa,
6038             FULLMASK, IPSEC_ULPROTO_ANY);
6039         if (!m) {
6040                 error = ENOBUFS;
6041                 goto fail;
6042         }
6043         m_cat(result, m);
6044
6045         if ((result->m_flags & M_PKTHDR) == 0) {
6046                 error = EINVAL;
6047                 goto fail;
6048         }
6049
6050         if (result->m_len < sizeof(struct sadb_msg)) {
6051                 result = m_pullup(result, sizeof(struct sadb_msg));
6052                 if (result == NULL) {
6053                         error = ENOBUFS;
6054                         goto fail;
6055                 }
6056         }
6057         result->m_pkthdr.len = m_lengthm(result, NULL);
6058         mtod(result, struct sadb_msg *)->sadb_msg_len =
6059             PFKEY_UNIT64(result->m_pkthdr.len);
6060
6061         crit_exit();
6062         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6063
6064  fail:
6065         if (result)
6066                 m_freem(result);
6067         crit_exit();
6068         return error;
6069 }
6070
6071 /*
6072  * SADB_FLUSH processing
6073  * receive
6074  *   <base>
6075  * from the ikmpd, and free all entries in secastree.
6076  * and send,
6077  *   <base>
6078  * to the ikmpd.
6079  * NOTE: to do is only marking SADB_SASTATE_DEAD.
6080  *
6081  * m will always be freed.
6082  */
6083 static int
6084 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6085 {
6086         struct sadb_msg *newmsg;
6087         struct secashead *sah;
6088         u_int16_t proto;
6089         u_int stateidx;
6090
6091         /* sanity check */
6092         if (so == NULL || mhp == NULL || mhp->msg == NULL)
6093                 panic("key_flush: NULL pointer is passed.");
6094
6095         /* map satype to proto */
6096         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6097                 ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6098                 return key_senderror(so, m, EINVAL);
6099         }
6100
6101         /* no SATYPE specified, i.e. flushing all SA. */
6102         LIST_FOREACH(sah, &sahtree, chain) {
6103                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
6104                     proto != sah->saidx.proto)
6105                         continue;
6106
6107                 for (stateidx = 0; stateidx < NELEM(saorder_state_alive);
6108                      stateidx++) {
6109                         struct secasvar *sav, *nextsav;
6110                         u_int8_t state = saorder_state_any[stateidx];
6111
6112                         LIST_FOREACH_MUTABLE(sav, &sah->savtree[state], chain,
6113                                              nextsav) {
6114                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6115                                 KEY_FREESAV(&sav);
6116                         }
6117                 }
6118
6119                 sah->state = SADB_SASTATE_DEAD;
6120         }
6121
6122         if (m->m_len < sizeof(struct sadb_msg) ||
6123             sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6124                 ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
6125                 return key_senderror(so, m, ENOBUFS);
6126         }
6127
6128         if (m->m_next)
6129                 m_freem(m->m_next);
6130         m->m_next = NULL;
6131         m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6132         newmsg = mtod(m, struct sadb_msg *);
6133         newmsg->sadb_msg_errno = 0;
6134         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6135
6136         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6137 }
6138
6139 /*
6140  * SADB_DUMP processing
6141  * dump all entries including status of DEAD in SAD.
6142  * receive
6143  *   <base>
6144  * from the ikmpd, and dump all secasvar leaves
6145  * and send,
6146  *   <base> .....
6147  * to the ikmpd.
6148  *
6149  * m will always be freed.
6150  */
6151 static int
6152 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6153 {
6154         struct secashead *sah;
6155         struct secasvar *sav;
6156         u_int16_t proto;
6157         u_int stateidx;
6158         u_int8_t satype;
6159         u_int8_t state;
6160         int cnt;
6161         struct mbuf *n;
6162
6163         /* sanity check */
6164         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6165                 panic("key_dump: NULL pointer is passed.");
6166
6167         /* map satype to proto */
6168         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6169                 ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
6170                 return key_senderror(so, m, EINVAL);
6171         }
6172
6173         /* count sav entries to be sent to the userland. */
6174         cnt = 0;
6175         LIST_FOREACH(sah, &sahtree, chain) {
6176                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
6177                     proto != sah->saidx.proto)
6178                         continue;
6179
6180                 for (stateidx = 0; stateidx < NELEM(saorder_state_any);
6181                      stateidx++) {
6182                         state = saorder_state_any[stateidx];
6183                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
6184                                 cnt++;
6185                         }
6186                 }
6187         }
6188
6189         if (cnt == 0)
6190                 return key_senderror(so, m, ENOENT);
6191
6192         /* send this to the userland, one at a time. */
6193         LIST_FOREACH(sah, &sahtree, chain) {
6194                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6195                  && proto != sah->saidx.proto)
6196                         continue;
6197
6198                 /* map proto to satype */
6199                 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6200                         ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
6201                         return key_senderror(so, m, EINVAL);
6202                 }
6203
6204                 for (stateidx = 0; stateidx < NELEM(saorder_state_any);
6205                      stateidx++) {
6206                         state = saorder_state_any[stateidx];
6207                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
6208                                 n = key_setdumpsa(sav, SADB_DUMP, satype,
6209                                     --cnt, mhp->msg->sadb_msg_pid);
6210                                 if (!n)
6211                                         return key_senderror(so, m, ENOBUFS);
6212
6213                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6214                         }
6215                 }
6216         }
6217
6218         m_freem(m);
6219         return 0;
6220 }
6221
6222 /*
6223  * SADB_X_PROMISC processing
6224  *
6225  * m will always be freed.
6226  */
6227 static int
6228 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6229 {
6230         int olen;
6231
6232         /* sanity check */
6233         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6234                 panic("key_promisc: NULL pointer is passed.");
6235
6236         olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6237
6238         if (olen < sizeof(struct sadb_msg)) {
6239 #if 1
6240                 return key_senderror(so, m, EINVAL);
6241 #else
6242                 m_freem(m);
6243                 return 0;
6244 #endif
6245         } else if (olen == sizeof(struct sadb_msg)) {
6246                 /* enable/disable promisc mode */
6247                 struct keycb *kp;
6248
6249                 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6250                         return key_senderror(so, m, EINVAL);
6251                 mhp->msg->sadb_msg_errno = 0;
6252                 switch (mhp->msg->sadb_msg_satype) {
6253                 case 0:
6254                 case 1:
6255                         kp->kp_promisc = mhp->msg->sadb_msg_satype;
6256                         break;
6257                 default:
6258                         return key_senderror(so, m, EINVAL);
6259                 }
6260
6261                 /* send the original message back to everyone */
6262                 mhp->msg->sadb_msg_errno = 0;
6263                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6264         } else {
6265                 /* send packet as is */
6266
6267                 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6268
6269                 /* TODO: if sadb_msg_seq is specified, send to specific pid */
6270                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6271         }
6272 }
6273
6274 static int (*key_typesw[]) (struct socket *, struct mbuf *,
6275                 const struct sadb_msghdr *) = {
6276         NULL,           /* SADB_RESERVED */
6277         key_getspi,     /* SADB_GETSPI */
6278         key_update,     /* SADB_UPDATE */
6279         key_add,        /* SADB_ADD */
6280         key_delete,     /* SADB_DELETE */
6281         key_get,        /* SADB_GET */
6282         key_acquire2,   /* SADB_ACQUIRE */
6283         key_register,   /* SADB_REGISTER */
6284         NULL,           /* SADB_EXPIRE */
6285         key_flush,      /* SADB_FLUSH */
6286         key_dump,       /* SADB_DUMP */
6287         key_promisc,    /* SADB_X_PROMISC */
6288         NULL,           /* SADB_X_PCHANGE */
6289         key_spdadd,     /* SADB_X_SPDUPDATE */
6290         key_spdadd,     /* SADB_X_SPDADD */
6291         key_spddelete,  /* SADB_X_SPDDELETE */
6292         key_spdget,     /* SADB_X_SPDGET */
6293         NULL,           /* SADB_X_SPDACQUIRE */
6294         key_spddump,    /* SADB_X_SPDDUMP */
6295         key_spdflush,   /* SADB_X_SPDFLUSH */
6296         key_spdadd,     /* SADB_X_SPDSETIDX */
6297         NULL,           /* SADB_X_SPDEXPIRE */
6298         key_spddelete2, /* SADB_X_SPDDELETE2 */
6299 };
6300
6301 /*
6302  * parse sadb_msg buffer to process PFKEYv2,
6303  * and create a data to response if needed.
6304  * I think to be dealed with mbuf directly.
6305  * IN:
6306  *     msgp  : pointer to pointer to a received buffer pulluped.
6307  *             This is rewrited to response.
6308  *     so    : pointer to socket.
6309  * OUT:
6310  *    length for buffer to send to user process.
6311  */
6312 int
6313 key_parse(struct mbuf *m, struct socket *so)
6314 {
6315         struct sadb_msg *msg;
6316         struct sadb_msghdr mh;
6317         u_int orglen;
6318         int error;
6319         int target;
6320
6321         /* sanity check */
6322         if (m == NULL || so == NULL)
6323                 panic("key_parse: NULL pointer is passed.");
6324
6325 #if 0   /*kdebug_sadb assumes msg in linear buffer*/
6326         KEYDEBUG(KEYDEBUG_KEY_DUMP,
6327                 ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
6328                 kdebug_sadb(msg));
6329 #endif
6330
6331         if (m->m_len < sizeof(struct sadb_msg)) {
6332                 m = m_pullup(m, sizeof(struct sadb_msg));
6333                 if (!m)
6334                         return ENOBUFS;
6335         }
6336         msg = mtod(m, struct sadb_msg *);
6337         orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6338         target = KEY_SENDUP_ONE;
6339
6340         if ((m->m_flags & M_PKTHDR) == 0 ||
6341             m->m_pkthdr.len != m->m_pkthdr.len) {
6342                 ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
6343                 pfkeystat.out_invlen++;
6344                 error = EINVAL;
6345                 goto senderror;
6346         }
6347
6348         if (msg->sadb_msg_version != PF_KEY_V2) {
6349                 ipseclog((LOG_DEBUG,
6350                     "key_parse: PF_KEY version %u is mismatched.\n",
6351                     msg->sadb_msg_version));
6352                 pfkeystat.out_invver++;
6353                 error = EINVAL;
6354                 goto senderror;
6355         }
6356
6357         if (msg->sadb_msg_type > SADB_MAX) {
6358                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6359                     msg->sadb_msg_type));
6360                 pfkeystat.out_invmsgtype++;
6361                 error = EINVAL;
6362                 goto senderror;
6363         }
6364
6365         /* for old-fashioned code - should be nuked */
6366         if (m->m_pkthdr.len > MCLBYTES) {
6367                 m_freem(m);
6368                 return ENOBUFS;
6369         }
6370         if (m->m_next) {
6371                 struct mbuf *n;
6372
6373                 n = m_getb(m->m_pkthdr.len, MB_DONTWAIT, MT_DATA, M_PKTHDR);
6374                 if (!n) {
6375                         m_freem(m);
6376                         return ENOBUFS;
6377                 }
6378                 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6379                 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6380                 m_freem(m);
6381                 m = n;
6382         }
6383
6384         /* align the mbuf chain so that extensions are in contiguous region. */
6385         error = key_align(m, &mh);
6386         if (error)
6387                 return error;
6388
6389         msg = mh.msg;
6390
6391         /* check SA type */
6392         switch (msg->sadb_msg_satype) {
6393         case SADB_SATYPE_UNSPEC:
6394                 switch (msg->sadb_msg_type) {
6395                 case SADB_GETSPI:
6396                 case SADB_UPDATE:
6397                 case SADB_ADD:
6398                 case SADB_DELETE:
6399                 case SADB_GET:
6400                 case SADB_ACQUIRE:
6401                 case SADB_EXPIRE:
6402                         ipseclog((LOG_DEBUG, "key_parse: must specify satype "
6403                             "when msg type=%u.\n", msg->sadb_msg_type));
6404                         pfkeystat.out_invsatype++;
6405                         error = EINVAL;
6406                         goto senderror;
6407                 }
6408                 break;
6409         case SADB_SATYPE_AH:
6410         case SADB_SATYPE_ESP:
6411         case SADB_X_SATYPE_IPCOMP:
6412                 switch (msg->sadb_msg_type) {
6413                 case SADB_X_SPDADD:
6414                 case SADB_X_SPDDELETE:
6415                 case SADB_X_SPDGET:
6416                 case SADB_X_SPDDUMP:
6417                 case SADB_X_SPDFLUSH:
6418                 case SADB_X_SPDSETIDX:
6419                 case SADB_X_SPDUPDATE:
6420                 case SADB_X_SPDDELETE2:
6421                         ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
6422                             msg->sadb_msg_type));
6423                         pfkeystat.out_invsatype++;
6424                         error = EINVAL;
6425                         goto senderror;
6426                 }
6427                 break;
6428         case SADB_SATYPE_RSVP:
6429         case SADB_SATYPE_OSPFV2:
6430         case SADB_SATYPE_RIPV2:
6431         case SADB_SATYPE_MIP:
6432                 ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
6433                     msg->sadb_msg_satype));
6434                 pfkeystat.out_invsatype++;
6435                 error = EOPNOTSUPP;
6436                 goto senderror;
6437         case 1: /* XXX: What does it do? */
6438                 if (msg->sadb_msg_type == SADB_X_PROMISC)
6439                         break;
6440                 /*FALLTHROUGH*/
6441         default:
6442                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6443                     msg->sadb_msg_satype));
6444                 pfkeystat.out_invsatype++;
6445                 error = EINVAL;
6446                 goto senderror;
6447         }
6448
6449         /* check field of upper layer protocol and address family */
6450         if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6451          && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6452                 struct sadb_address *src0, *dst0;
6453                 u_int plen;
6454
6455                 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6456                 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6457
6458                 /* check upper layer protocol */
6459                 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6460                         ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
6461                         pfkeystat.out_invaddr++;
6462                         error = EINVAL;
6463                         goto senderror;
6464                 }
6465
6466                 /* check family */
6467                 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6468                     PFKEY_ADDR_SADDR(dst0)->sa_family) {
6469                         ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
6470                         pfkeystat.out_invaddr++;
6471                         error = EINVAL;
6472                         goto senderror;
6473                 }
6474                 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6475                     PFKEY_ADDR_SADDR(dst0)->sa_len) {
6476                         ipseclog((LOG_DEBUG,
6477                             "key_parse: address struct size mismatched.\n"));
6478                         pfkeystat.out_invaddr++;
6479                         error = EINVAL;
6480                         goto senderror;
6481                 }
6482
6483                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6484                 case AF_INET:
6485                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6486                             sizeof(struct sockaddr_in)) {
6487                                 pfkeystat.out_invaddr++;
6488                                 error = EINVAL;
6489                                 goto senderror;
6490                         }
6491                         break;
6492                 case AF_INET6:
6493                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6494                             sizeof(struct sockaddr_in6)) {
6495                                 pfkeystat.out_invaddr++;
6496                                 error = EINVAL;
6497                                 goto senderror;
6498                         }
6499                         break;
6500                 default:
6501                         ipseclog((LOG_DEBUG,
6502                             "key_parse: unsupported address family.\n"));
6503                         pfkeystat.out_invaddr++;
6504                         error = EAFNOSUPPORT;
6505                         goto senderror;
6506                 }
6507
6508                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6509                 case AF_INET:
6510                         plen = sizeof(struct in_addr) << 3;
6511                         break;
6512                 case AF_INET6:
6513                         plen = sizeof(struct in6_addr) << 3;
6514                         break;
6515                 default:
6516                         plen = 0;       /*fool gcc*/
6517                         break;
6518                 }
6519
6520                 /* check max prefix length */
6521                 if (src0->sadb_address_prefixlen > plen ||
6522                     dst0->sadb_address_prefixlen > plen) {
6523                         ipseclog((LOG_DEBUG,
6524                             "key_parse: illegal prefixlen.\n"));
6525                         pfkeystat.out_invaddr++;
6526                         error = EINVAL;
6527                         goto senderror;
6528                 }
6529
6530                 /*
6531                  * prefixlen == 0 is valid because there can be a case when
6532                  * all addresses are matched.
6533                  */
6534         }
6535
6536         if (msg->sadb_msg_type >= NELEM(key_typesw) ||
6537             key_typesw[msg->sadb_msg_type] == NULL) {
6538                 pfkeystat.out_invmsgtype++;
6539                 error = EINVAL;
6540                 goto senderror;
6541         }
6542
6543         return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6544
6545 senderror:
6546         msg->sadb_msg_errno = error;
6547         return key_sendup_mbuf(so, m, target);
6548 }
6549
6550 static int
6551 key_senderror(struct socket *so, struct mbuf *m, int code)
6552 {
6553         struct sadb_msg *msg;
6554
6555         if (m->m_len < sizeof(struct sadb_msg))
6556                 panic("invalid mbuf passed to key_senderror");
6557
6558         msg = mtod(m, struct sadb_msg *);
6559         msg->sadb_msg_errno = code;
6560         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6561 }
6562
6563 /*
6564  * set the pointer to each header into message buffer.
6565  * m will be freed on error.
6566  * XXX larger-than-MCLBYTES extension?
6567  */
6568 static int
6569 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
6570 {
6571         struct mbuf *n;
6572         struct sadb_ext *ext;
6573         size_t off, end;
6574         int extlen;
6575         int toff;
6576
6577         /* sanity check */
6578         if (m == NULL || mhp == NULL)
6579                 panic("key_align: NULL pointer is passed.");
6580         if (m->m_len < sizeof(struct sadb_msg))
6581                 panic("invalid mbuf passed to key_align");
6582
6583         /* initialize */
6584         bzero(mhp, sizeof(*mhp));
6585
6586         mhp->msg = mtod(m, struct sadb_msg *);
6587         mhp->ext[0] = (struct sadb_ext *)mhp->msg;      /*XXX backward compat */
6588
6589         end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6590         extlen = end;   /*just in case extlen is not updated*/
6591         for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6592                 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6593                 if (!n) {
6594                         /* m is already freed */
6595                         return ENOBUFS;
6596                 }
6597                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6598
6599                 /* set pointer */
6600                 switch (ext->sadb_ext_type) {
6601                 case SADB_EXT_SA:
6602                 case SADB_EXT_ADDRESS_SRC:
6603                 case SADB_EXT_ADDRESS_DST:
6604                 case SADB_EXT_ADDRESS_PROXY:
6605                 case SADB_EXT_LIFETIME_CURRENT:
6606                 case SADB_EXT_LIFETIME_HARD:
6607                 case SADB_EXT_LIFETIME_SOFT:
6608                 case SADB_EXT_KEY_AUTH:
6609                 case SADB_EXT_KEY_ENCRYPT:
6610                 case SADB_EXT_IDENTITY_SRC:
6611                 case SADB_EXT_IDENTITY_DST:
6612                 case SADB_EXT_SENSITIVITY:
6613                 case SADB_EXT_PROPOSAL:
6614                 case SADB_EXT_SUPPORTED_AUTH:
6615                 case SADB_EXT_SUPPORTED_ENCRYPT:
6616                 case SADB_EXT_SPIRANGE:
6617                 case SADB_X_EXT_POLICY:
6618                 case SADB_X_EXT_SA2:
6619                         /* duplicate check */
6620                         /*
6621                          * XXX Are there duplication payloads of either
6622                          * KEY_AUTH or KEY_ENCRYPT ?
6623                          */
6624                         if (mhp->ext[ext->sadb_ext_type] != NULL) {
6625                                 ipseclog((LOG_DEBUG,
6626                                     "key_align: duplicate ext_type %u "
6627                                     "is passed.\n", ext->sadb_ext_type));
6628                                 m_freem(m);
6629                                 pfkeystat.out_dupext++;
6630                                 return EINVAL;
6631                         }
6632                         break;
6633                 default:
6634                         ipseclog((LOG_DEBUG,
6635                             "key_align: invalid ext_type %u is passed.\n",
6636                             ext->sadb_ext_type));
6637                         m_freem(m);
6638                         pfkeystat.out_invexttype++;
6639                         return EINVAL;
6640                 }
6641
6642                 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6643
6644                 if (key_validate_ext(ext, extlen)) {
6645                         m_freem(m);
6646                         pfkeystat.out_invlen++;
6647                         return EINVAL;
6648                 }
6649
6650                 n = m_pulldown(m, off, extlen, &toff);
6651                 if (!n) {
6652                         /* m is already freed */
6653                         return ENOBUFS;
6654                 }
6655                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6656
6657                 mhp->ext[ext->sadb_ext_type] = ext;
6658                 mhp->extoff[ext->sadb_ext_type] = off;
6659                 mhp->extlen[ext->sadb_ext_type] = extlen;
6660         }
6661
6662         if (off != end) {
6663                 m_freem(m);
6664                 pfkeystat.out_invlen++;
6665                 return EINVAL;
6666         }
6667
6668         return 0;
6669 }
6670
6671 static int
6672 key_validate_ext(const struct sadb_ext *ext, int len)
6673 {
6674         const struct sockaddr *sa;
6675         enum { NONE, ADDR } checktype = NONE;
6676         int baselen = 0;
6677         const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
6678
6679         if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
6680                 return EINVAL;
6681
6682         /* if it does not match minimum/maximum length, bail */
6683         if (ext->sadb_ext_type >= NELEM(minsize) ||
6684             ext->sadb_ext_type >= NELEM(maxsize))
6685                 return EINVAL;
6686         if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
6687                 return EINVAL;
6688         if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
6689                 return EINVAL;
6690
6691         /* more checks based on sadb_ext_type XXX need more */
6692         switch (ext->sadb_ext_type) {
6693         case SADB_EXT_ADDRESS_SRC:
6694         case SADB_EXT_ADDRESS_DST:
6695         case SADB_EXT_ADDRESS_PROXY:
6696                 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
6697                 checktype = ADDR;
6698                 break;
6699         case SADB_EXT_IDENTITY_SRC:
6700         case SADB_EXT_IDENTITY_DST:
6701                 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
6702                     SADB_X_IDENTTYPE_ADDR) {
6703                         baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
6704                         checktype = ADDR;
6705                 } else
6706                         checktype = NONE;
6707                 break;
6708         default:
6709                 checktype = NONE;
6710                 break;
6711         }
6712
6713         switch (checktype) {
6714         case NONE:
6715                 break;
6716         case ADDR:
6717                 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
6718                 if (len < baselen + sal)
6719                         return EINVAL;
6720                 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
6721                         return EINVAL;
6722                 break;
6723         }
6724
6725         return 0;
6726 }
6727
6728 void
6729 key_init(void)
6730 {
6731         int i;
6732
6733         for (i = 0; i < IPSEC_DIR_MAX; i++) {
6734                 LIST_INIT(&sptree[i]);
6735         }
6736
6737         LIST_INIT(&sahtree);
6738
6739         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6740                 LIST_INIT(&regtree[i]);
6741         }
6742
6743 #ifndef IPSEC_NONBLOCK_ACQUIRE
6744         LIST_INIT(&acqtree);
6745 #endif
6746         LIST_INIT(&spacqtree);
6747
6748         /* system default */
6749         ip4_def_policy.policy = IPSEC_POLICY_NONE;
6750         ip4_def_policy.refcnt++;        /*never reclaim this*/
6751
6752 #ifndef IPSEC_DEBUG2
6753         callout_init(&key_timehandler_ch);
6754         callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
6755 #endif /*IPSEC_DEBUG2*/
6756
6757         /* initialize key statistics */
6758         keystat.getspi_count = 1;
6759
6760         kprintf("IPsec: Initialized Security Association Processing.\n");
6761
6762         return;
6763 }
6764
6765 /*
6766  * XXX: maybe This function is called after INBOUND IPsec processing.
6767  *
6768  * Special check for tunnel-mode packets.
6769  * We must make some checks for consistency between inner and outer IP header.
6770  *
6771  * xxx more checks to be provided
6772  */
6773 int
6774 key_checktunnelsanity(struct secasvar *sav, u_int family, caddr_t src,
6775                       caddr_t dst)
6776 {
6777         /* sanity check */
6778         if (sav->sah == NULL)
6779                 panic("sav->sah == NULL at key_checktunnelsanity");
6780
6781         /* XXX: check inner IP header */
6782
6783         return 1;
6784 }
6785
6786 #if 0
6787 #define hostnamelen     strlen(hostname)
6788
6789 /*
6790  * Get FQDN for the host.
6791  * If the administrator configured hostname (by hostname(1)) without
6792  * domain name, returns nothing.
6793  */
6794 static const char *
6795 key_getfqdn(void)
6796 {
6797         int i;
6798         int hasdot;
6799         static char fqdn[MAXHOSTNAMELEN + 1];
6800
6801         if (!hostnamelen)
6802                 return NULL;
6803
6804         /* check if it comes with domain name. */
6805         hasdot = 0;
6806         for (i = 0; i < hostnamelen; i++) {
6807                 if (hostname[i] == '.')
6808                         hasdot++;
6809         }
6810         if (!hasdot)
6811                 return NULL;
6812
6813         /* NOTE: hostname may not be NUL-terminated. */
6814         bzero(fqdn, sizeof(fqdn));
6815         bcopy(hostname, fqdn, hostnamelen);
6816         fqdn[hostnamelen] = '\0';
6817         return fqdn;
6818 }
6819
6820 /*
6821  * get username@FQDN for the host/user.
6822  */
6823 static const char *
6824 key_getuserfqdn(void)
6825 {
6826         const char *host;
6827         static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
6828         struct proc *p = curproc;
6829         char *q;
6830
6831         if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
6832                 return NULL;
6833         if (!(host = key_getfqdn()))
6834                 return NULL;
6835
6836         /* NOTE: s_login may not be-NUL terminated. */
6837         bzero(userfqdn, sizeof(userfqdn));
6838         bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
6839         userfqdn[MAXLOGNAME] = '\0';    /* safeguard */
6840         q = userfqdn + strlen(userfqdn);
6841         *q++ = '@';
6842         bcopy(host, q, strlen(host));
6843         q += strlen(host);
6844         *q++ = '\0';
6845
6846         return userfqdn;
6847 }
6848 #endif
6849
6850 /* record data transfer on SA, and update timestamps */
6851 void
6852 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
6853 {
6854         KASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
6855         KASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
6856         if (!sav->lft_c)
6857                 return;
6858
6859         /*
6860          * XXX Currently, there is a difference of bytes size
6861          * between inbound and outbound processing.
6862          */
6863         sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
6864         /* to check bytes lifetime is done in key_timehandler(). */
6865
6866         /*
6867          * We use the number of packets as the unit of
6868          * sadb_lifetime_allocations.  We increment the variable
6869          * whenever {esp,ah}_{in,out}put is called.
6870          */
6871         sav->lft_c->sadb_lifetime_allocations++;
6872         /* XXX check for expires? */
6873
6874         /*
6875          * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
6876          * in seconds.  HARD and SOFT lifetime are measured by the time
6877          * difference (again in seconds) from sadb_lifetime_usetime.
6878          *
6879          *      usetime
6880          *      v     expire   expire
6881          * -----+-----+--------+---> t
6882          *      <--------------> HARD
6883          *      <-----> SOFT
6884          */
6885         sav->lft_c->sadb_lifetime_usetime = time_second;
6886         /* XXX check for expires? */
6887
6888         return;
6889 }
6890
6891 /* dumb version */
6892 void
6893 key_sa_routechange(struct sockaddr *dst)
6894 {
6895         struct secashead *sah;
6896         struct route *ro;
6897
6898         LIST_FOREACH(sah, &sahtree, chain) {
6899                 ro = &sah->sa_route;
6900                 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
6901                  && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
6902                         RTFREE(ro->ro_rt);
6903                         ro->ro_rt = NULL;
6904                 }
6905         }
6906
6907         return;
6908 }
6909
6910 static void
6911 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
6912 {
6913         if (sav == NULL)
6914                 panic("key_sa_chgstate called with sav == NULL");
6915
6916         if (sav->state == state)
6917                 return;
6918
6919         if (__LIST_CHAINED(sav))
6920                 LIST_REMOVE(sav, chain);
6921
6922         sav->state = state;
6923         LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
6924 }
6925
6926 void
6927 key_sa_stir_iv(struct secasvar *sav)
6928 {
6929
6930         if (!sav->iv)
6931                 panic("key_sa_stir_iv called with sav == NULL");
6932         key_randomfill(sav->iv, sav->ivlen);
6933 }
6934
6935 /* XXX too much? */
6936 static struct mbuf *
6937 key_alloc_mbuf(int l)
6938 {
6939         struct mbuf *m = NULL, *n;
6940         int len, t;
6941
6942         len = l;
6943         while (len > 0) {
6944                 n = m_getb(len, MB_DONTWAIT, MT_DATA, 0);
6945                 if (!n) {
6946                         m_freem(m);
6947                         return NULL;
6948                 }
6949                 n->m_len = 0;
6950                 n->m_len = M_TRAILINGSPACE(n);
6951                 /* use the bottom of mbuf, hoping we can prepend afterwards */
6952                 if (n->m_len > len) {
6953                         t = (n->m_len - len) & ~(sizeof(long) - 1);
6954                         n->m_data += t;
6955                         n->m_len = len;
6956                 }
6957
6958                 len -= n->m_len;
6959
6960                 if (m)
6961                         m_cat(m, n);
6962                 else
6963                         m = n;
6964         }
6965
6966         return m;
6967 }