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