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