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