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