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