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