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