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