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