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