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