Merge from vendor branch WPA_SUPPLICANT:
[dragonfly.git] / sys / netproto / key / key.c
1 /*      $FreeBSD: src/sys/netkey/key.c,v 1.16.2.13 2002/07/24 18:17:40 ume Exp $        */
2 /*      $DragonFly: src/sys/netproto/key/key.c,v 1.16 2006/03/29 23:17:16 joerg Exp $   */
3 /*      $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
4
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * This code is referd to RFC 2367
36  */
37
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41
42 #include <sys/types.h>
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/mbuf.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
49 #include <sys/malloc.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/errno.h>
54 #include <sys/proc.h>
55 #include <sys/queue.h>
56 #include <sys/syslog.h>
57 #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) malloc((unsigned long)(n), M_SECA, M_INTWAIT | M_NULLOK))
313 #define KFREE(p)                                                             \
314         free((caddr_t)(p), M_SECA);
315 #else
316 #define KMALLOC(p, t, n) \
317 do { \
318         ((p) = (t)malloc((unsigned long)(n), M_SECA, M_INTWAIT | M_NULLOK)); \
319         printf("%s %d: %p <- KMALLOC(%s, %d)\n",                             \
320                 __FILE__, __LINE__, (p), #t, n);                             \
321 } while (0)
322
323 #define KFREE(p)                                                             \
324         do {                                                                 \
325                 printf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p));   \
326                 free((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                 printf("*** objects\n");
532                 kdebug_secpolicyindex(spidx));
533
534         LIST_FOREACH(sp, &sptree[dir], chain) {
535                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
536                         printf("*** 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                 printf("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                                 printf("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                         printf("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                 printf("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                 printf("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                         printf("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                 printf("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                                 printf("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 mismathed. 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 *ia;
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(ia, &in_ifaddrhead, ia_link) {
3729                         if (sin->sin_family == ia->ia_addr.sin_family &&
3730                             sin->sin_len == ia->ia_addr.sin_len &&
3731                             sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3732                         {
3733                                 return 1;
3734                         }
3735                 }
3736                 break;
3737 #endif
3738 #ifdef INET6
3739         case AF_INET6:
3740                 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3741 #endif
3742         }
3743
3744         return 0;
3745 }
3746
3747 #ifdef INET6
3748 /*
3749  * compare my own address for IPv6.
3750  * 1: ours
3751  * 0: other
3752  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3753  */
3754 #include <netinet6/in6_var.h>
3755
3756 static int
3757 key_ismyaddr6(struct sockaddr_in6 *sin6)
3758 {
3759         struct in6_ifaddr *ia;
3760         struct in6_multi *in6m;
3761
3762         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3763                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3764                     (struct sockaddr *)&ia->ia_addr, 0) == 0)
3765                         return 1;
3766
3767                 /*
3768                  * XXX Multicast
3769                  * XXX why do we care about multlicast here while we don't care
3770                  * about IPv4 multicast??
3771                  * XXX scope
3772                  */
3773                 in6m = NULL;
3774                 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3775                 if (in6m)
3776                         return 1;
3777         }
3778
3779         /* loopback, just for safety */
3780         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3781                 return 1;
3782
3783         return 0;
3784 }
3785 #endif /*INET6*/
3786
3787 /*
3788  * compare two secasindex structure.
3789  * flag can specify to compare 2 saidxes.
3790  * compare two secasindex structure without both mode and reqid.
3791  * don't compare port.
3792  * IN:  
3793  *      saidx0: source, it can be in SAD.
3794  *      saidx1: object.
3795  * OUT: 
3796  *      1 : equal
3797  *      0 : not equal
3798  */
3799 static int
3800 key_cmpsaidx(struct secasindex *saidx0, struct secasindex *saidx1,
3801              int flag)
3802 {
3803         /* sanity */
3804         if (saidx0 == NULL && saidx1 == NULL)
3805                 return 1;
3806
3807         if (saidx0 == NULL || saidx1 == NULL)
3808                 return 0;
3809
3810         if (saidx0->proto != saidx1->proto)
3811                 return 0;
3812
3813         if (flag == CMP_EXACTLY) {
3814                 if (saidx0->mode != saidx1->mode)
3815                         return 0;
3816                 if (saidx0->reqid != saidx1->reqid)
3817                         return 0;
3818                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.ss_len) != 0 ||
3819                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.ss_len) != 0)
3820                         return 0;
3821         } else {
3822
3823                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3824                 if (flag == CMP_MODE_REQID
3825                   ||flag == CMP_REQID) {
3826                         /*
3827                          * If reqid of SPD is non-zero, unique SA is required.
3828                          * The result must be of same reqid in this case.
3829                          */
3830                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3831                                 return 0;
3832                 }
3833
3834                 if (flag == CMP_MODE_REQID) {
3835                         if (saidx0->mode != IPSEC_MODE_ANY
3836                          && saidx0->mode != saidx1->mode)
3837                                 return 0;
3838                 }
3839
3840                 if (key_sockaddrcmp((struct sockaddr *)&saidx0->src,
3841                                 (struct sockaddr *)&saidx1->src, 0) != 0) {
3842                         return 0;
3843                 }
3844                 if (key_sockaddrcmp((struct sockaddr *)&saidx0->dst,
3845                                 (struct sockaddr *)&saidx1->dst, 0) != 0) {
3846                         return 0;
3847                 }
3848         }
3849
3850         return 1;
3851 }
3852
3853 /*
3854  * compare two secindex structure exactly.
3855  * IN:
3856  *      spidx0: source, it is often in SPD.
3857  *      spidx1: object, it is often from PFKEY message.
3858  * OUT:
3859  *      1 : equal
3860  *      0 : not equal
3861  */
3862 static int
3863 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
3864                      struct secpolicyindex *spidx1)
3865 {
3866         /* sanity */
3867         if (spidx0 == NULL && spidx1 == NULL)
3868                 return 1;
3869
3870         if (spidx0 == NULL || spidx1 == NULL)
3871                 return 0;
3872
3873         if (spidx0->prefs != spidx1->prefs
3874          || spidx0->prefd != spidx1->prefd
3875          || spidx0->ul_proto != spidx1->ul_proto)
3876                 return 0;
3877
3878         if (key_sockaddrcmp((struct sockaddr *)&spidx0->src,
3879             (struct sockaddr *)&spidx1->src, 1) != 0) {
3880                 return 0;
3881         }
3882         if (key_sockaddrcmp((struct sockaddr *)&spidx0->dst,
3883             (struct sockaddr *)&spidx1->dst, 1) != 0) {
3884                 return 0;
3885         }
3886
3887         return 1;
3888 }
3889
3890 /*
3891  * compare two secindex structure with mask.
3892  * IN:
3893  *      spidx0: source, it is often in SPD.
3894  *      spidx1: object, it is often from IP header.
3895  * OUT:
3896  *      1 : equal
3897  *      0 : not equal
3898  */
3899 static int
3900 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
3901                       struct secpolicyindex *spidx1)
3902 {
3903         /* sanity */
3904         if (spidx0 == NULL && spidx1 == NULL)
3905                 return 1;
3906
3907         if (spidx0 == NULL || spidx1 == NULL)
3908                 return 0;
3909
3910         if (spidx0->src.ss_family != spidx1->src.ss_family ||
3911             spidx0->dst.ss_family != spidx1->dst.ss_family ||
3912             spidx0->src.ss_len != spidx1->src.ss_len ||
3913             spidx0->dst.ss_len != spidx1->dst.ss_len)
3914                 return 0;
3915
3916         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3917         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3918          && spidx0->ul_proto != spidx1->ul_proto)
3919                 return 0;
3920
3921         switch (spidx0->src.ss_family) {
3922         case AF_INET:
3923                 if (satosin(&spidx0->src)->sin_port != IPSEC_PORT_ANY
3924                  && satosin(&spidx0->src)->sin_port !=
3925                     satosin(&spidx1->src)->sin_port)
3926                         return 0;
3927                 if (!key_bbcmp((caddr_t)&satosin(&spidx0->src)->sin_addr,
3928                     (caddr_t)&satosin(&spidx1->src)->sin_addr, spidx0->prefs))
3929                         return 0;
3930                 break;
3931         case AF_INET6:
3932                 if (satosin6(&spidx0->src)->sin6_port != IPSEC_PORT_ANY
3933                  && satosin6(&spidx0->src)->sin6_port !=
3934                     satosin6(&spidx1->src)->sin6_port)
3935                         return 0;
3936                 /*
3937                  * scope_id check. if sin6_scope_id is 0, we regard it
3938                  * as a wildcard scope, which matches any scope zone ID. 
3939                  */
3940                 if (satosin6(&spidx0->src)->sin6_scope_id &&
3941                     satosin6(&spidx1->src)->sin6_scope_id &&
3942                     satosin6(&spidx0->src)->sin6_scope_id !=
3943                     satosin6(&spidx1->src)->sin6_scope_id)
3944                         return 0;
3945                 if (!key_bbcmp((caddr_t)&satosin6(&spidx0->src)->sin6_addr,
3946                     (caddr_t)&satosin6(&spidx1->src)->sin6_addr, spidx0->prefs))
3947                         return 0;
3948                 break;
3949         default:
3950                 /* XXX */
3951                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.ss_len) != 0)
3952                         return 0;
3953                 break;
3954         }
3955
3956         switch (spidx0->dst.ss_family) {
3957         case AF_INET:
3958                 if (satosin(&spidx0->dst)->sin_port != IPSEC_PORT_ANY
3959                  && satosin(&spidx0->dst)->sin_port !=
3960                     satosin(&spidx1->dst)->sin_port)
3961                         return 0;
3962                 if (!key_bbcmp((caddr_t)&satosin(&spidx0->dst)->sin_addr,
3963                     (caddr_t)&satosin(&spidx1->dst)->sin_addr, spidx0->prefd))
3964                         return 0;
3965                 break;
3966         case AF_INET6:
3967                 if (satosin6(&spidx0->dst)->sin6_port != IPSEC_PORT_ANY
3968                  && satosin6(&spidx0->dst)->sin6_port !=
3969                     satosin6(&spidx1->dst)->sin6_port)
3970                         return 0;
3971                 /*
3972                  * scope_id check. if sin6_scope_id is 0, we regard it
3973                  * as a wildcard scope, which matches any scope zone ID. 
3974                  */
3975                 if (satosin6(&spidx0->src)->sin6_scope_id &&
3976                     satosin6(&spidx1->src)->sin6_scope_id &&
3977                     satosin6(&spidx0->dst)->sin6_scope_id !=
3978                     satosin6(&spidx1->dst)->sin6_scope_id)
3979                         return 0;
3980                 if (!key_bbcmp((caddr_t)&satosin6(&spidx0->dst)->sin6_addr,
3981                     (caddr_t)&satosin6(&spidx1->dst)->sin6_addr, spidx0->prefd))
3982                         return 0;
3983                 break;
3984         default:
3985                 /* XXX */
3986                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.ss_len) != 0)
3987                         return 0;
3988                 break;
3989         }
3990
3991         /* XXX Do we check other field ?  e.g. flowinfo */
3992
3993         return 1;
3994 }
3995
3996 /* returns 0 on match */
3997 static int
3998 key_sockaddrcmp(struct sockaddr *sa1, struct sockaddr *sa2, int port)
3999 {
4000         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4001                 return 1;
4002
4003         switch (sa1->sa_family) {
4004         case AF_INET:
4005                 if (sa1->sa_len != sizeof(struct sockaddr_in))
4006                         return 1;
4007                 if (satosin(sa1)->sin_addr.s_addr !=
4008                     satosin(sa2)->sin_addr.s_addr) {
4009                         return 1;
4010                 }
4011                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4012                         return 1;
4013                 break;
4014         case AF_INET6:
4015                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4016                         return 1;       /*EINVAL*/
4017                 if (satosin6(sa1)->sin6_scope_id !=
4018                     satosin6(sa2)->sin6_scope_id) {
4019                         return 1;
4020                 }
4021                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4022                     &satosin6(sa2)->sin6_addr)) {
4023                         return 1;
4024                 }
4025                 if (port &&
4026                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4027                         return 1;
4028                 }
4029         default:
4030                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4031                         return 1;
4032                 break;
4033         }
4034
4035         return 0;
4036 }
4037
4038 /*
4039  * compare two buffers with mask.
4040  * IN:
4041  *      addr1: source
4042  *      addr2: object
4043  *      bits:  Number of bits to compare
4044  * OUT:
4045  *      1 : equal
4046  *      0 : not equal
4047  */
4048 static int
4049 key_bbcmp(caddr_t p1, caddr_t p2, u_int bits)
4050 {
4051         u_int8_t mask;
4052
4053         /* XXX: This could be considerably faster if we compare a word
4054          * at a time, but it is complicated on LSB Endian machines */
4055
4056         /* Handle null pointers */
4057         if (p1 == NULL || p2 == NULL)
4058                 return (p1 == p2);
4059
4060         while (bits >= 8) {
4061                 if (*p1++ != *p2++)
4062                         return 0;
4063                 bits -= 8;
4064         }
4065
4066         if (bits > 0) {
4067                 mask = ~((1<<(8-bits))-1);
4068                 if ((*p1 & mask) != (*p2 & mask))
4069                         return 0;
4070         }
4071         return 1;       /* Match! */
4072 }
4073
4074 /*
4075  * time handler.
4076  * scanning SPD and SAD to check status for each entries,
4077  * and do to remove or to expire.
4078  * XXX: year 2038 problem may remain.
4079  */
4080 void
4081 key_timehandler(void *__dummy)
4082 {
4083         u_int dir;
4084         struct timeval tv;
4085
4086         microtime(&tv);
4087
4088         crit_enter();
4089
4090         /* SPD */
4091     {
4092         struct secpolicy *sp, *nextsp;
4093
4094         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4095                 for (sp = LIST_FIRST(&sptree[dir]);
4096                      sp != NULL;
4097                      sp = nextsp) {
4098
4099                         nextsp = LIST_NEXT(sp, chain);
4100
4101                         if (sp->state == IPSEC_SPSTATE_DEAD) {
4102                                 key_freesp(sp);
4103                                 continue;
4104                         }
4105
4106                         if (sp->lifetime == 0 && sp->validtime == 0)
4107                                 continue;
4108
4109                         /* the deletion will occur next time */
4110                         if ((sp->lifetime
4111                           && tv.tv_sec - sp->created > sp->lifetime)
4112                          || (sp->validtime
4113                           && tv.tv_sec - sp->lastused > sp->validtime)) {
4114                                 sp->state = IPSEC_SPSTATE_DEAD;
4115                                 key_spdexpire(sp);
4116                                 continue;
4117                         }
4118                 }
4119         }
4120     }
4121
4122         /* SAD */
4123     {
4124         struct secashead *sah, *nextsah;
4125         struct secasvar *sav, *nextsav;
4126
4127         for (sah = LIST_FIRST(&sahtree);
4128              sah != NULL;
4129              sah = nextsah) {
4130
4131                 nextsah = LIST_NEXT(sah, chain);
4132
4133                 /* if sah has been dead, then delete it and process next sah. */
4134                 if (sah->state == SADB_SASTATE_DEAD) {
4135                         key_delsah(sah);
4136                         continue;
4137                 }
4138
4139                 /* if LARVAL entry doesn't become MATURE, delete it. */
4140                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
4141                      sav != NULL;
4142                      sav = nextsav) {
4143
4144                         nextsav = LIST_NEXT(sav, chain);
4145
4146                         if (tv.tv_sec - sav->created > key_larval_lifetime) {
4147                                 key_freesav(sav);
4148                         }
4149                 }
4150
4151                 /*
4152                  * check MATURE entry to start to send expire message
4153                  * whether or not.
4154                  */
4155                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
4156                      sav != NULL;
4157                      sav = nextsav) {
4158
4159                         nextsav = LIST_NEXT(sav, chain);
4160
4161                         /* we don't need to check. */
4162                         if (sav->lft_s == NULL)
4163                                 continue;
4164
4165                         /* sanity check */
4166                         if (sav->lft_c == NULL) {
4167                                 ipseclog((LOG_DEBUG,"key_timehandler: "
4168                                         "There is no CURRENT time, why?\n"));
4169                                 continue;
4170                         }
4171
4172                         /* check SOFT lifetime */
4173                         if (sav->lft_s->sadb_lifetime_addtime != 0
4174                          && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4175                                 /*
4176                                  * check the SA if it has been used.
4177                                  * when it hasn't been used, delete it.
4178                                  * i don't think such SA will be used.
4179                                  */
4180                                 if (sav->lft_c->sadb_lifetime_usetime == 0) {
4181                                         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4182                                         key_freesav(sav);
4183                                         sav = NULL;
4184                                 } else {
4185                                         key_sa_chgstate(sav, SADB_SASTATE_DYING);
4186                                         /*
4187                                          * XXX If we keep to send expire
4188                                          * message in the status of
4189                                          * DYING. Do remove below code.
4190                                          */
4191                                         key_expire(sav);
4192                                 }
4193                         }
4194
4195                         /* check SOFT lifetime by bytes */
4196                         /*
4197                          * XXX I don't know the way to delete this SA
4198                          * when new SA is installed.  Caution when it's
4199                          * installed too big lifetime by time.
4200                          */
4201                         else if (sav->lft_s->sadb_lifetime_bytes != 0
4202                               && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4203
4204                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4205                                 /*
4206                                  * XXX If we keep to send expire
4207                                  * message in the status of
4208                                  * DYING. Do remove below code.
4209                                  */
4210                                 key_expire(sav);
4211                         }
4212                 }
4213
4214                 /* check DYING entry to change status to DEAD. */
4215                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
4216                      sav != NULL;
4217                      sav = nextsav) {
4218
4219                         nextsav = LIST_NEXT(sav, chain);
4220
4221                         /* we don't need to check. */
4222                         if (sav->lft_h == NULL)
4223                                 continue;
4224
4225                         /* sanity check */
4226                         if (sav->lft_c == NULL) {
4227                                 ipseclog((LOG_DEBUG, "key_timehandler: "
4228                                         "There is no CURRENT time, why?\n"));
4229                                 continue;
4230                         }
4231
4232                         if (sav->lft_h->sadb_lifetime_addtime != 0
4233                          && tv.tv_sec - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4234                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4235                                 key_freesav(sav);
4236                                 sav = NULL;
4237                         }
4238 #if 0   /* XXX Should we keep to send expire message until HARD lifetime ? */
4239                         else if (sav->lft_s != NULL
4240                               && sav->lft_s->sadb_lifetime_addtime != 0
4241                               && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4242                                 /*
4243                                  * XXX: should be checked to be
4244                                  * installed the valid SA.
4245                                  */
4246
4247                                 /*
4248                                  * If there is no SA then sending
4249                                  * expire message.
4250                                  */
4251                                 key_expire(sav);
4252                         }
4253 #endif
4254                         /* check HARD lifetime by bytes */
4255                         else if (sav->lft_h->sadb_lifetime_bytes != 0
4256                               && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4257                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4258                                 key_freesav(sav);
4259                                 sav = NULL;
4260                         }
4261                 }
4262
4263                 /* delete entry in DEAD */
4264                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
4265                      sav != NULL;
4266                      sav = nextsav) {
4267
4268                         nextsav = LIST_NEXT(sav, chain);
4269
4270                         /* sanity check */
4271                         if (sav->state != SADB_SASTATE_DEAD) {
4272                                 ipseclog((LOG_DEBUG, "key_timehandler: "
4273                                         "invalid sav->state "
4274                                         "(queue: %d SA: %d): "
4275                                         "kill it anyway\n",
4276                                         SADB_SASTATE_DEAD, sav->state));
4277                         }
4278
4279                         /*
4280                          * do not call key_freesav() here.
4281                          * sav should already be freed, and sav->refcnt
4282                          * shows other references to sav
4283                          * (such as from SPD).
4284                          */
4285                 }
4286         }
4287     }
4288
4289 #ifndef IPSEC_NONBLOCK_ACQUIRE
4290         /* ACQ tree */
4291     {
4292         struct secacq *acq, *nextacq;
4293
4294         for (acq = LIST_FIRST(&acqtree);
4295              acq != NULL;
4296              acq = nextacq) {
4297
4298                 nextacq = LIST_NEXT(acq, chain);
4299
4300                 if (tv.tv_sec - acq->created > key_blockacq_lifetime
4301                  && __LIST_CHAINED(acq)) {
4302                         LIST_REMOVE(acq, chain);
4303                         KFREE(acq);
4304                 }
4305         }
4306     }
4307 #endif
4308
4309         /* SP ACQ tree */
4310     {
4311         struct secspacq *acq, *nextacq;
4312
4313         for (acq = LIST_FIRST(&spacqtree);
4314              acq != NULL;
4315              acq = nextacq) {
4316
4317                 nextacq = LIST_NEXT(acq, chain);
4318
4319                 if (tv.tv_sec - acq->created > key_blockacq_lifetime
4320                  && __LIST_CHAINED(acq)) {
4321                         LIST_REMOVE(acq, chain);
4322                         KFREE(acq);
4323                 }
4324         }
4325     }
4326
4327         /* initialize random seed */
4328         if (key_tick_init_random++ > key_int_random) {
4329                 key_tick_init_random = 0;
4330                 key_srandom();
4331         }
4332
4333 #ifndef IPSEC_DEBUG2
4334         /* do exchange to tick time !! */
4335         callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
4336 #endif /* IPSEC_DEBUG2 */
4337
4338         crit_exit();
4339         return;
4340 }
4341
4342 /*
4343  * to initialize a seed for random()
4344  */
4345 static void
4346 key_srandom(void)
4347 {
4348         struct timeval tv;
4349
4350         microtime(&tv);
4351
4352         srandom(tv.tv_usec);
4353
4354         return;
4355 }
4356
4357 u_long
4358 key_random(void)
4359 {
4360         u_long value;
4361
4362         key_randomfill(&value, sizeof(value));
4363         return value;
4364 }
4365
4366 void
4367 key_randomfill(void *p, size_t l)
4368 {
4369         size_t n;
4370         u_long v;
4371         static int warn = 1;
4372
4373         n = 0;
4374         n = (size_t)read_random(p, (u_int)l);
4375         /* last resort */
4376         while (n < l) {
4377                 v = random();
4378                 bcopy(&v, (u_int8_t *)p + n,
4379                     l - n < sizeof(v) ? l - n : sizeof(v));
4380                 n += sizeof(v);
4381
4382                 if (warn) {
4383                         printf("WARNING: pseudo-random number generator "
4384                             "used for IPsec processing\n");
4385                         warn = 0;
4386                 }
4387         }
4388 }
4389
4390 /*
4391  * map SADB_SATYPE_* to IPPROTO_*.
4392  * if satype == SADB_SATYPE then satype is mapped to ~0.
4393  * OUT:
4394  *      0: invalid satype.
4395  */
4396 static u_int16_t
4397 key_satype2proto(u_int8_t satype)
4398 {
4399         switch (satype) {
4400         case SADB_SATYPE_UNSPEC:
4401                 return IPSEC_PROTO_ANY;
4402         case SADB_SATYPE_AH:
4403                 return IPPROTO_AH;
4404         case SADB_SATYPE_ESP:
4405                 return IPPROTO_ESP;
4406         case SADB_X_SATYPE_IPCOMP:
4407                 return IPPROTO_IPCOMP;
4408                 break;
4409         default:
4410                 return 0;
4411         }
4412         /* NOTREACHED */
4413 }
4414
4415 /*
4416  * map IPPROTO_* to SADB_SATYPE_*
4417  * OUT:
4418  *      0: invalid protocol type.
4419  */
4420 static u_int8_t
4421 key_proto2satype(u_int16_t proto)
4422 {
4423         switch (proto) {
4424         case IPPROTO_AH:
4425                 return SADB_SATYPE_AH;
4426         case IPPROTO_ESP:
4427                 return SADB_SATYPE_ESP;
4428         case IPPROTO_IPCOMP:
4429                 return SADB_X_SATYPE_IPCOMP;
4430                 break;
4431         default:
4432                 return 0;
4433         }
4434         /* NOTREACHED */
4435 }
4436
4437 /* %%% PF_KEY */
4438 /*
4439  * SADB_GETSPI processing is to receive
4440  *      <base, (SA2), src address, dst address, (SPI range)>
4441  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4442  * tree with the status of LARVAL, and send
4443  *      <base, SA(*), address(SD)>
4444  * to the IKMPd.
4445  *
4446  * IN:  mhp: pointer to the pointer to each header.
4447  * OUT: NULL if fail.
4448  *      other if success, return pointer to the message to send.
4449  */
4450 static int
4451 key_getspi(struct socket *so, struct mbuf *m,
4452            const struct sadb_msghdr *mhp)
4453 {
4454         struct sadb_address *src0, *dst0;
4455         struct secasindex saidx;
4456         struct secashead *newsah;
4457         struct secasvar *newsav;
4458         u_int8_t proto;
4459         u_int32_t spi;
4460         u_int8_t mode;
4461         u_int32_t reqid;
4462         int error;
4463
4464         /* sanity check */
4465         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4466                 panic("key_getspi: NULL pointer is passed.\n");
4467
4468         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4469             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4470                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4471                 return key_senderror(so, m, EINVAL);
4472         }
4473         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4474             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4475                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4476                 return key_senderror(so, m, EINVAL);
4477         }
4478         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4479                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4480                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4481         } else {
4482                 mode = IPSEC_MODE_ANY;
4483                 reqid = 0;
4484         }
4485
4486         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4487         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4488
4489         /* map satype to proto */
4490         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4491                 ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
4492                 return key_senderror(so, m, EINVAL);
4493         }
4494
4495         /* make sure if port number is zero. */
4496         switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4497         case AF_INET:
4498                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4499                     sizeof(struct sockaddr_in))
4500                         return key_senderror(so, m, EINVAL);
4501                 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4502                 break;
4503         case AF_INET6:
4504                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4505                     sizeof(struct sockaddr_in6))
4506                         return key_senderror(so, m, EINVAL);
4507                 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4508                 break;
4509         default:
4510                 ; /*???*/
4511         }
4512         switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4513         case AF_INET:
4514                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4515                     sizeof(struct sockaddr_in))
4516                         return key_senderror(so, m, EINVAL);
4517                 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4518                 break;
4519         case AF_INET6:
4520                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4521                     sizeof(struct sockaddr_in6))
4522                         return key_senderror(so, m, EINVAL);
4523                 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4524                 break;
4525         default:
4526                 ; /*???*/
4527         }
4528
4529         /* XXX boundary check against sa_len */
4530         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4531
4532         /* SPI allocation */
4533         spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4534                                &saidx);
4535         if (spi == 0)
4536                 return key_senderror(so, m, EINVAL);
4537
4538         /* get a SA index */
4539         if ((newsah = key_getsah(&saidx)) == NULL) {
4540                 /* create a new SA index */
4541                 if ((newsah = key_newsah(&saidx)) == NULL) {
4542                         ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
4543                         return key_senderror(so, m, ENOBUFS);
4544                 }
4545         }
4546
4547         /* get a new SA */
4548         /* XXX rewrite */
4549         newsav = key_newsav(m, mhp, newsah, &error);
4550         if (newsav == NULL) {
4551                 /* XXX don't free new SA index allocated in above. */
4552                 return key_senderror(so, m, error);
4553         }
4554
4555         /* set spi */
4556         newsav->spi = htonl(spi);
4557
4558 #ifndef IPSEC_NONBLOCK_ACQUIRE
4559         /* delete the entry in acqtree */
4560         if (mhp->msg->sadb_msg_seq != 0) {
4561                 struct secacq *acq;
4562                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4563                         /* reset counter in order to deletion by timehandler. */
4564                         struct timeval tv;
4565                         microtime(&tv);
4566                         acq->created = tv.tv_sec;
4567                         acq->count = 0;
4568                 }
4569         }
4570 #endif
4571
4572     {
4573         struct mbuf *n, *nn;
4574         struct sadb_sa *m_sa;
4575         struct sadb_msg *newmsg;
4576         int off, len;
4577
4578         /* create new sadb_msg to reply. */
4579         len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4580             PFKEY_ALIGN8(sizeof(struct sadb_sa));
4581         if (len > MCLBYTES)
4582                 return key_senderror(so, m, ENOBUFS);
4583
4584         MGETHDR(n, MB_DONTWAIT, MT_DATA);
4585         if (len > MHLEN) {
4586                 MCLGET(n, MB_DONTWAIT);
4587                 if ((n->m_flags & M_EXT) == 0) {
4588                         m_freem(n);
4589                         n = NULL;
4590                 }
4591         }
4592         if (!n)
4593                 return key_senderror(so, m, ENOBUFS);
4594
4595         n->m_len = len;
4596         n->m_next = NULL;
4597         off = 0;
4598
4599         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4600         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4601
4602         m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4603         m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4604         m_sa->sadb_sa_exttype = SADB_EXT_SA;
4605         m_sa->sadb_sa_spi = htonl(spi);
4606         off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4607
4608 #ifdef DIAGNOSTIC
4609         if (off != len)
4610                 panic("length inconsistency in key_getspi");
4611 #endif
4612
4613         n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4614             SADB_EXT_ADDRESS_DST);
4615         if (!n->m_next) {
4616                 m_freem(n);
4617                 return key_senderror(so, m, ENOBUFS);
4618         }
4619
4620         if (n->m_len < sizeof(struct sadb_msg)) {
4621                 n = m_pullup(n, sizeof(struct sadb_msg));
4622                 if (n == NULL)
4623                         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4624         }
4625
4626         n->m_pkthdr.len = 0;
4627         for (nn = n; nn; nn = nn->m_next)
4628                 n->m_pkthdr.len += nn->m_len;
4629
4630         newmsg = mtod(n, struct sadb_msg *);
4631         newmsg->sadb_msg_seq = newsav->seq;
4632         newmsg->sadb_msg_errno = 0;
4633         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4634
4635         m_freem(m);
4636         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4637     }
4638 }
4639
4640 /*
4641  * allocating new SPI
4642  * called by key_getspi().
4643  * OUT:
4644  *      0:      failure.
4645  *      others: success.
4646  */
4647 static u_int32_t
4648 key_do_getnewspi(struct sadb_spirange *spirange,
4649                  struct secasindex *saidx)
4650 {
4651         u_int32_t newspi;
4652         u_int32_t min, max;
4653         int count = key_spi_trycnt;
4654
4655         /* set spi range to allocate */
4656         if (spirange != NULL) {
4657                 min = spirange->sadb_spirange_min;
4658                 max = spirange->sadb_spirange_max;
4659         } else {
4660                 min = key_spi_minval;
4661                 max = key_spi_maxval;
4662         }
4663         /* IPCOMP needs 2-byte SPI */
4664         if (saidx->proto == IPPROTO_IPCOMP) {
4665                 u_int32_t t;
4666                 if (min >= 0x10000)
4667                         min = 0xffff;
4668                 if (max >= 0x10000)
4669                         max = 0xffff;
4670                 if (min > max) {
4671                         t = min; min = max; max = t;
4672                 }
4673         }
4674
4675         if (min == max) {
4676                 if (key_checkspidup(saidx, min) != NULL) {
4677                         ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
4678                         return 0;
4679                 }
4680
4681                 count--; /* taking one cost. */
4682                 newspi = min;
4683
4684         } else {
4685
4686                 /* init SPI */
4687                 newspi = 0;
4688
4689                 /* when requesting to allocate spi ranged */
4690                 while (count--) {
4691                         /* generate pseudo-random SPI value ranged. */
4692                         newspi = min + (key_random() % (max - min + 1));
4693
4694                         if (key_checkspidup(saidx, newspi) == NULL)
4695                                 break;
4696                 }
4697
4698                 if (count == 0 || newspi == 0) {
4699                         ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
4700                         return 0;
4701                 }
4702         }
4703
4704         /* statistics */
4705         keystat.getspi_count =
4706                 (keystat.getspi_count + key_spi_trycnt - count) / 2;
4707
4708         return newspi;
4709 }
4710
4711 /*
4712  * SADB_UPDATE processing
4713  * receive
4714  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4715  *       key(AE), (identity(SD),) (sensitivity)>
4716  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4717  * and send
4718  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4719  *       (identity(SD),) (sensitivity)>
4720  * to the ikmpd.
4721  *
4722  * m will always be freed.
4723  */
4724 static int
4725 key_update(struct socket *so, struct mbuf *m,
4726            const struct sadb_msghdr *mhp)
4727 {
4728         struct sadb_sa *sa0;
4729         struct sadb_address *src0, *dst0;
4730         struct secasindex saidx;
4731         struct secashead *sah;
4732         struct secasvar *sav;
4733         u_int16_t proto;
4734         u_int8_t mode;
4735         u_int32_t reqid;
4736         int error;
4737
4738         /* sanity check */
4739         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4740                 panic("key_update: NULL pointer is passed.\n");
4741
4742         /* map satype to proto */
4743         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4744                 ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
4745                 return key_senderror(so, m, EINVAL);
4746         }
4747
4748         if (mhp->ext[SADB_EXT_SA] == NULL ||
4749             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4750             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4751             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4752              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4753             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4754              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4755             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4756              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4757             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4758              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4759                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4760                 return key_senderror(so, m, EINVAL);
4761         }
4762         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4763             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4764             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4765                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
4766                 return key_senderror(so, m, EINVAL);
4767         }
4768         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4769                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4770                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4771         } else {
4772                 mode = IPSEC_MODE_ANY;
4773                 reqid = 0;
4774         }
4775         /* XXX boundary checking for other extensions */
4776
4777         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4778         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4779         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4780
4781         /* XXX boundary check against sa_len */
4782         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4783
4784         /* get a SA header */
4785         if ((sah = key_getsah(&saidx)) == NULL) {
4786                 ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
4787                 return key_senderror(so, m, ENOENT);
4788         }
4789
4790         /* set spidx if there */
4791         /* XXX rewrite */
4792         error = key_setident(sah, m, mhp);
4793         if (error)
4794                 return key_senderror(so, m, error);
4795
4796         /* find a SA with sequence number. */
4797 #ifdef IPSEC_DOSEQCHECK
4798         if (mhp->msg->sadb_msg_seq != 0
4799          && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4800                 ipseclog((LOG_DEBUG,
4801                     "key_update: no larval SA with sequence %u exists.\n",
4802                     mhp->msg->sadb_msg_seq));
4803                 return key_senderror(so, m, ENOENT);
4804         }
4805 #else
4806         if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
4807                 ipseclog((LOG_DEBUG,
4808                     "key_update: no such a SA found (spi:%u)\n",
4809                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4810                 return key_senderror(so, m, EINVAL);
4811         }
4812 #endif
4813
4814         /* validity check */
4815         if (sav->sah->saidx.proto != proto) {
4816                 ipseclog((LOG_DEBUG,
4817                     "key_update: protocol mismatched (DB=%u param=%u)\n",
4818                     sav->sah->saidx.proto, proto));
4819                 return key_senderror(so, m, EINVAL);
4820         }
4821 #ifdef IPSEC_DOSEQCHECK
4822         if (sav->spi != sa0->sadb_sa_spi) {
4823                 ipseclog((LOG_DEBUG,
4824                     "key_update: SPI mismatched (DB:%u param:%u)\n",
4825                     (u_int32_t)ntohl(sav->spi),
4826                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4827                 return key_senderror(so, m, EINVAL);
4828         }
4829 #endif
4830         if (sav->pid != mhp->msg->sadb_msg_pid) {
4831                 ipseclog((LOG_DEBUG,
4832                     "key_update: pid mismatched (DB:%u param:%u)\n",
4833                     sav->pid, mhp->msg->sadb_msg_pid));
4834                 return key_senderror(so, m, EINVAL);
4835         }
4836
4837         /* copy sav values */
4838         error = key_setsaval(sav, m, mhp);
4839         if (error) {
4840                 key_freesav(sav);
4841                 return key_senderror(so, m, error);
4842         }
4843
4844         /* check SA values to be mature. */
4845         if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4846                 key_freesav(sav);
4847                 return key_senderror(so, m, 0);
4848         }
4849
4850     {
4851         struct mbuf *n;
4852
4853         /* set msg buf from mhp */
4854         n = key_getmsgbuf_x1(m, mhp);
4855         if (n == NULL) {
4856                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
4857                 return key_senderror(so, m, ENOBUFS);
4858         }
4859
4860         m_freem(m);
4861         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4862     }
4863 }
4864
4865 /*
4866  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4867  * only called by key_update().
4868  * OUT:
4869  *      NULL    : not found
4870  *      others  : found, pointer to a SA.
4871  */
4872 #ifdef IPSEC_DOSEQCHECK
4873 static struct secasvar *
4874 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
4875 {
4876         struct secasvar *sav;
4877         u_int state;
4878
4879         state = SADB_SASTATE_LARVAL;
4880
4881         /* search SAD with sequence number ? */
4882         LIST_FOREACH(sav, &sah->savtree[state], chain) {
4883
4884                 KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
4885
4886                 if (sav->seq == seq) {
4887                         sav->refcnt++;
4888                         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4889                                 printf("DP key_getsavbyseq cause "
4890                                         "refcnt++:%d SA:%p\n",
4891                                         sav->refcnt, sav));
4892                         return sav;
4893                 }
4894         }
4895
4896         return NULL;
4897 }
4898 #endif
4899
4900 /*
4901  * SADB_ADD processing
4902  * add a entry to SA database, when received
4903  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4904  *       key(AE), (identity(SD),) (sensitivity)>
4905  * from the ikmpd,
4906  * and send
4907  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4908  *       (identity(SD),) (sensitivity)>
4909  * to the ikmpd.
4910  *
4911  * IGNORE identity and sensitivity messages.
4912  *
4913  * m will always be freed.
4914  */
4915 static int
4916 key_add(struct socket *so, struct mbuf *m,
4917         const struct sadb_msghdr *mhp)
4918 {
4919         struct sadb_sa *sa0;
4920         struct sadb_address *src0, *dst0;
4921         struct secasindex saidx;
4922         struct secashead *newsah;
4923         struct secasvar *newsav;
4924         u_int16_t proto;
4925         u_int8_t mode;
4926         u_int32_t reqid;
4927         int error;
4928
4929         /* sanity check */
4930         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4931                 panic("key_add: NULL pointer is passed.\n");
4932
4933         /* map satype to proto */
4934         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4935                 ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
4936                 return key_senderror(so, m, EINVAL);
4937         }
4938
4939         if (mhp->ext[SADB_EXT_SA] == NULL ||
4940             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4941             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4942             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4943              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4944             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4945              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4946             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4947              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4948             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4949              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4950                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4951                 return key_senderror(so, m, EINVAL);
4952         }
4953         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4954             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4955             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4956                 /* XXX need more */
4957                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
4958                 return key_senderror(so, m, EINVAL);
4959         }
4960         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4961                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4962                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4963         } else {
4964                 mode = IPSEC_MODE_ANY;
4965                 reqid = 0;
4966         }
4967
4968         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4969         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4970         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4971
4972         /* XXX boundary check against sa_len */
4973         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4974
4975         /* get a SA header */
4976         if ((newsah = key_getsah(&saidx)) == NULL) {
4977                 /* create a new SA header */
4978                 if ((newsah = key_newsah(&saidx)) == NULL) {
4979                         ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
4980                         return key_senderror(so, m, ENOBUFS);
4981                 }
4982         }
4983
4984         /* set spidx if there */
4985         /* XXX rewrite */
4986         error = key_setident(newsah, m, mhp);
4987         if (error) {
4988                 return key_senderror(so, m, error);
4989         }
4990
4991         /* create new SA entry. */
4992         /* We can create new SA only if SPI is differenct. */
4993         if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
4994                 ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
4995                 return key_senderror(so, m, EEXIST);
4996         }
4997         newsav = key_newsav(m, mhp, newsah, &error);
4998         if (newsav == NULL) {
4999                 return key_senderror(so, m, error);
5000         }
5001
5002         /* check SA values to be mature. */
5003         if ((error = key_mature(newsav)) != 0) {
5004                 key_freesav(newsav);
5005                 return key_senderror(so, m, error);
5006         }
5007
5008         /*
5009          * don't call key_freesav() here, as we would like to keep the SA
5010          * in the database on success.
5011          */
5012
5013     {
5014         struct mbuf *n;
5015
5016         /* set msg buf from mhp */
5017         n = key_getmsgbuf_x1(m, mhp);
5018         if (n == NULL) {
5019                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
5020                 return key_senderror(so, m, ENOBUFS);
5021         }
5022
5023         m_freem(m);
5024         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5025     }
5026 }
5027
5028 /* m is retained */
5029 static int
5030 key_setident(struct secashead *sah, struct mbuf *m,
5031              const struct sadb_msghdr *mhp)
5032 {
5033         const struct sadb_ident *idsrc, *iddst;
5034         int idsrclen, iddstlen;
5035
5036         /* sanity check */
5037         if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5038                 panic("key_setident: NULL pointer is passed.\n");
5039
5040         /* don't make buffer if not there */
5041         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5042             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5043                 sah->idents = NULL;
5044                 sah->identd = NULL;
5045                 return 0;
5046         }
5047         
5048         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5049             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5050                 ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
5051                 return EINVAL;
5052         }
5053
5054         idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5055         iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5056         idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5057         iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5058
5059         /* validity check */
5060         if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5061                 ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
5062                 return EINVAL;
5063         }
5064
5065         switch (idsrc->sadb_ident_type) {
5066         case SADB_IDENTTYPE_PREFIX:
5067         case SADB_IDENTTYPE_FQDN:
5068         case SADB_IDENTTYPE_USERFQDN:
5069         default:
5070                 /* XXX do nothing */
5071                 sah->idents = NULL;
5072                 sah->identd = NULL;
5073                 return 0;
5074         }
5075
5076         /* make structure */
5077         KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
5078         if (sah->idents == NULL) {
5079                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5080                 return ENOBUFS;
5081         }
5082         KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
5083         if (sah->identd == NULL) {
5084                 KFREE(sah->idents);
5085                 sah->idents = NULL;
5086                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5087                 return ENOBUFS;
5088         }
5089         bcopy(idsrc, sah->idents, idsrclen);
5090         bcopy(iddst, sah->identd, iddstlen);
5091
5092         return 0;
5093 }
5094
5095 /*
5096  * m will not be freed on return.
5097  * it is caller's responsibility to free the result. 
5098  */
5099 static struct mbuf *
5100 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5101 {
5102         struct mbuf *n;
5103
5104         /* sanity check */
5105         if (m == NULL || mhp == NULL || mhp->msg == NULL)
5106                 panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
5107
5108         /* create new sadb_msg to reply. */
5109         n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5110             SADB_EXT_SA, SADB_X_EXT_SA2,
5111             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5112             SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5113             SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5114         if (!n)
5115                 return NULL;
5116
5117         if (n->m_len < sizeof(struct sadb_msg)) {
5118                 n = m_pullup(n, sizeof(struct sadb_msg));
5119                 if (n == NULL)
5120                         return NULL;
5121         }
5122         mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5123         mtod(n, struct sadb_msg *)->sadb_msg_len =
5124             PFKEY_UNIT64(n->m_pkthdr.len);
5125
5126         return n;
5127 }
5128
5129 static int key_delete_all (struct socket *, struct mbuf *,
5130         const struct sadb_msghdr *, u_int16_t);
5131
5132 /*
5133  * SADB_DELETE processing
5134  * receive
5135  *   <base, SA(*), address(SD)>
5136  * from the ikmpd, and set SADB_SASTATE_DEAD,
5137  * and send,
5138  *   <base, SA(*), address(SD)>
5139  * to the ikmpd.
5140  *
5141  * m will always be freed.
5142  */
5143 static int
5144 key_delete(struct socket *so, struct mbuf *m,
5145            const struct sadb_msghdr *mhp)
5146 {
5147         struct sadb_sa *sa0;
5148         struct sadb_address *src0, *dst0;
5149         struct secasindex saidx;
5150         struct secashead *sah;
5151         struct secasvar *sav = NULL;
5152         u_int16_t proto;
5153
5154         /* sanity check */
5155         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5156                 panic("key_delete: NULL pointer is passed.\n");
5157
5158         /* map satype to proto */
5159         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5160                 ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
5161                 return key_senderror(so, m, EINVAL);
5162         }
5163
5164         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5165             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5166                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5167                 return key_senderror(so, m, EINVAL);
5168         }
5169
5170         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5171             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5172                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5173                 return key_senderror(so, m, EINVAL);
5174         }
5175
5176         if (mhp->ext[SADB_EXT_SA] == NULL) {
5177                 /*
5178                  * Caller wants us to delete all non-LARVAL SAs
5179                  * that match the src/dst.  This is used during
5180                  * IKE INITIAL-CONTACT.
5181                  */
5182                 ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
5183                 return key_delete_all(so, m, mhp, proto);
5184         } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5185                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5186                 return key_senderror(so, m, EINVAL);
5187         }
5188
5189         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5190         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5191         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5192
5193         /* XXX boundary check against sa_len */
5194         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5195
5196         /* get a SA header */
5197         LIST_FOREACH(sah, &sahtree, chain) {
5198                 if (sah->state == SADB_SASTATE_DEAD)
5199                         continue;
5200                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5201                         continue;
5202
5203                 /* get a SA with SPI. */
5204                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5205                 if (sav)
5206                         break;
5207         }
5208         if (sah == NULL) {
5209                 ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
5210                 return key_senderror(so, m, ENOENT);
5211         }
5212
5213         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5214         key_freesav(sav);
5215         sav = NULL;
5216
5217     {
5218         struct mbuf *n;
5219         struct sadb_msg *newmsg;
5220
5221         /* create new sadb_msg to reply. */
5222         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5223             SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5224         if (!n)
5225                 return key_senderror(so, m, ENOBUFS);
5226
5227         if (n->m_len < sizeof(struct sadb_msg)) {
5228                 n = m_pullup(n, sizeof(struct sadb_msg));
5229                 if (n == NULL)
5230                         return key_senderror(so, m, ENOBUFS);
5231         }
5232         newmsg = mtod(n, struct sadb_msg *);
5233         newmsg->sadb_msg_errno = 0;
5234         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5235
5236         m_freem(m);
5237         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5238     }
5239 }
5240
5241 /*
5242  * delete all SAs for src/dst.  Called from key_delete().
5243  */
5244 static int
5245 key_delete_all(struct socket *so, struct mbuf *m,
5246                const struct sadb_msghdr *mhp, u_int16_t proto)
5247 {
5248         struct sadb_address *src0, *dst0;
5249         struct secasindex saidx;
5250         struct secashead *sah;
5251         struct secasvar *sav, *nextsav;
5252         u_int stateidx, state;
5253
5254         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5255         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5256
5257         /* XXX boundary check against sa_len */
5258         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5259
5260         LIST_FOREACH(sah, &sahtree, chain) {
5261                 if (sah->state == SADB_SASTATE_DEAD)
5262                         continue;
5263                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5264                         continue;
5265
5266                 /* Delete all non-LARVAL SAs. */
5267                 for (stateidx = 0;
5268                      stateidx < _ARRAYLEN(saorder_state_alive);
5269                      stateidx++) {
5270                         state = saorder_state_alive[stateidx];
5271                         if (state == SADB_SASTATE_LARVAL)
5272                                 continue;
5273                         for (sav = LIST_FIRST(&sah->savtree[state]);
5274                              sav != NULL; sav = nextsav) {
5275                                 nextsav = LIST_NEXT(sav, chain);
5276                                 /* sanity check */
5277                                 if (sav->state != state) {
5278                                         ipseclog((LOG_DEBUG, "key_delete_all: "
5279                                                "invalid sav->state "
5280                                                "(queue: %d SA: %d)\n",
5281                                                state, sav->state));
5282                                         continue;
5283                                 }
5284                                 
5285                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5286                                 key_freesav(sav);
5287                         }
5288                 }
5289         }
5290     {
5291         struct mbuf *n;
5292         struct sadb_msg *newmsg;
5293
5294         /* create new sadb_msg to reply. */
5295         n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5296             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5297         if (!n)
5298                 return key_senderror(so, m, ENOBUFS);
5299
5300         if (n->m_len < sizeof(struct sadb_msg)) {
5301                 n = m_pullup(n, sizeof(struct sadb_msg));
5302                 if (n == NULL)
5303                         return key_senderror(so, m, ENOBUFS);
5304         }
5305         newmsg = mtod(n, struct sadb_msg *);
5306         newmsg->sadb_msg_errno = 0;
5307         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5308
5309         m_freem(m);
5310         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5311     }
5312 }
5313
5314 /*
5315  * SADB_GET processing
5316  * receive
5317  *   <base, SA(*), address(SD)>
5318  * from the ikmpd, and get a SP and a SA to respond,
5319  * and send,
5320  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5321  *       (identity(SD),) (sensitivity)>
5322  * to the ikmpd.
5323  *
5324  * m will always be freed.
5325  */
5326 static int
5327 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5328 {
5329         struct sadb_sa *sa0;
5330         struct sadb_address *src0, *dst0;
5331         struct secasindex saidx;
5332         struct secashead *sah;
5333         struct secasvar *sav = NULL;
5334         u_int16_t proto;
5335
5336         /* sanity check */
5337         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5338                 panic("key_get: NULL pointer is passed.\n");
5339
5340         /* map satype to proto */
5341         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5342                 ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
5343                 return key_senderror(so, m, EINVAL);
5344         }
5345
5346         if (mhp->ext[SADB_EXT_SA] == NULL ||
5347             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5348             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5349                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5350                 return key_senderror(so, m, EINVAL);
5351         }
5352         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5353             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5354             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5355                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5356                 return key_senderror(so, m, EINVAL);
5357         }
5358
5359         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5360         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5361         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5362
5363         /* XXX boundary check against sa_len */
5364         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5365
5366         /* get a SA header */
5367         LIST_FOREACH(sah, &sahtree, chain) {
5368                 if (sah->state == SADB_SASTATE_DEAD)
5369                         continue;
5370                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5371                         continue;
5372
5373                 /* get a SA with SPI. */
5374                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5375                 if (sav)
5376                         break;
5377         }
5378         if (sah == NULL) {
5379                 ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5380                 return key_senderror(so, m, ENOENT);
5381         }
5382
5383     {
5384         struct mbuf *n;
5385         u_int8_t satype;
5386
5387         /* map proto to satype */
5388         if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5389                 ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5390                 return key_senderror(so, m, EINVAL);
5391         }
5392
5393         /* create new sadb_msg to reply. */
5394         n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5395             mhp->msg->sadb_msg_pid);
5396         if (!n)
5397                 return key_senderror(so, m, ENOBUFS);
5398
5399         m_freem(m);
5400         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5401     }
5402 }
5403
5404 /* XXX make it sysctl-configurable? */
5405 static void
5406 key_getcomb_setlifetime(struct sadb_comb *comb)
5407 {
5408
5409         comb->sadb_comb_soft_allocations = 1;
5410         comb->sadb_comb_hard_allocations = 1;
5411         comb->sadb_comb_soft_bytes = 0;
5412         comb->sadb_comb_hard_bytes = 0;
5413         comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
5414         comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5415         comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
5416         comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5417 }
5418
5419 #ifdef IPSEC_ESP
5420 /*
5421  * XXX reorder combinations by preference
5422  * XXX no idea if the user wants ESP authentication or not
5423  */
5424 static struct mbuf *
5425 key_getcomb_esp(void)
5426 {
5427         struct sadb_comb *comb;
5428         const struct esp_algorithm *algo;
5429         struct mbuf *result = NULL, *m, *n;
5430         int encmin;
5431         int i, off, o;
5432         int totlen;
5433         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5434
5435         m = NULL;
5436         for (i = 1; i <= SADB_EALG_MAX; i++) {
5437                 algo = esp_algorithm_lookup(i);
5438                 if (!algo)
5439                         continue;
5440
5441                 if (algo->keymax < ipsec_esp_keymin)
5442                         continue;
5443                 if (algo->keymin < ipsec_esp_keymin)
5444                         encmin = ipsec_esp_keymin;
5445                 else
5446                         encmin = algo->keymin;
5447
5448                 if (ipsec_esp_auth)
5449                         m = key_getcomb_ah();
5450                 else {
5451 #ifdef DIAGNOSTIC
5452                         if (l > MLEN)
5453                                 panic("assumption failed in key_getcomb_esp");
5454 #endif
5455                         MGET(m, MB_DONTWAIT, MT_DATA);
5456                         if (m) {
5457                                 M_ALIGN(m, l);
5458                                 m->m_len = l;
5459                                 m->m_next = NULL;
5460                                 bzero(mtod(m, caddr_t), m->m_len);
5461                         }
5462                 }
5463                 if (!m)
5464                         goto fail;
5465
5466                 totlen = 0;
5467                 for (n = m; n; n = n->m_next)
5468                         totlen += n->m_len;
5469 #ifdef DIAGNOSTIC
5470                 if (totlen % l)
5471                         panic("assumption failed in key_getcomb_esp");
5472 #endif
5473
5474                 for (off = 0; off < totlen; off += l) {
5475                         n = m_pulldown(m, off, l, &o);
5476                         if (!n) {
5477                                 /* m is already freed */
5478                                 goto fail;
5479                         }
5480                         comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5481                         bzero(comb, sizeof(*comb));
5482                         key_getcomb_setlifetime(comb);
5483                         comb->sadb_comb_encrypt = i;
5484                         comb->sadb_comb_encrypt_minbits = encmin;
5485                         comb->sadb_comb_encrypt_maxbits = algo->keymax;
5486                 }
5487
5488                 if (!result)
5489                         result = m;
5490                 else
5491                         m_cat(result, m);
5492         }
5493
5494         return result;
5495
5496  fail:
5497         if (result)
5498                 m_freem(result);
5499         return NULL;
5500 }
5501 #endif
5502
5503 /*
5504  * XXX reorder combinations by preference
5505  */
5506 static struct mbuf *
5507 key_getcomb_ah(void)
5508 {
5509         struct sadb_comb *comb;
5510         const struct ah_algorithm *algo;
5511         struct mbuf *m;
5512         int min;
5513         int i;
5514         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5515
5516         m = NULL;
5517         for (i = 1; i <= SADB_AALG_MAX; i++) {
5518 #if 1
5519                 /* we prefer HMAC algorithms, not old algorithms */
5520                 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5521                         continue;
5522 #endif
5523                 algo = ah_algorithm_lookup(i);
5524                 if (!algo)
5525                         continue;
5526
5527                 if (algo->keymax < ipsec_ah_keymin)
5528                         continue;
5529                 if (algo->keymin < ipsec_ah_keymin)
5530                         min = ipsec_ah_keymin;
5531                 else
5532                         min = algo->keymin;
5533
5534                 if (!m) {
5535 #ifdef DIAGNOSTIC
5536                         if (l > MLEN)
5537                                 panic("assumption failed in key_getcomb_ah");
5538 #endif
5539                         MGET(m, MB_DONTWAIT, MT_DATA);
5540                         if (m) {
5541                                 M_ALIGN(m, l);
5542                                 m->m_len = l;
5543                                 m->m_next = NULL;
5544                         }
5545                 } else
5546                         M_PREPEND(m, l, MB_DONTWAIT);
5547                 if (!m)
5548                         return NULL;
5549
5550                 comb = mtod(m, struct sadb_comb *);
5551                 bzero(comb, sizeof(*comb));
5552                 key_getcomb_setlifetime(comb);
5553                 comb->sadb_comb_auth = i;
5554                 comb->sadb_comb_auth_minbits = min;
5555                 comb->sadb_comb_auth_maxbits = algo->keymax;
5556         }
5557
5558         return m;
5559 }
5560
5561 /*
5562  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
5563  * XXX reorder combinations by preference
5564  */
5565 static struct mbuf *
5566 key_getcomb_ipcomp(void)
5567 {
5568         struct sadb_comb *comb;
5569         const struct ipcomp_algorithm *algo;
5570         struct mbuf *m;
5571         int i;
5572         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5573
5574         m = NULL;
5575         for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5576                 algo = ipcomp_algorithm_lookup(i);
5577                 if (!algo)
5578                         continue;
5579
5580                 if (!m) {
5581 #ifdef DIAGNOSTIC
5582                         if (l > MLEN)
5583                                 panic("assumption failed in key_getcomb_ipcomp");
5584 #endif
5585                         MGET(m, MB_DONTWAIT, MT_DATA);
5586                         if (m) {
5587                                 M_ALIGN(m, l);
5588                                 m->m_len = l;
5589                                 m->m_next = NULL;
5590                         }
5591                 } else
5592                         M_PREPEND(m, l, MB_DONTWAIT);
5593                 if (!m)
5594                         return NULL;
5595
5596                 comb = mtod(m, struct sadb_comb *);
5597                 bzero(comb, sizeof(*comb));
5598                 key_getcomb_setlifetime(comb);
5599                 comb->sadb_comb_encrypt = i;
5600                 /* what should we set into sadb_comb_*_{min,max}bits? */
5601         }
5602
5603         return m;
5604 }
5605
5606 /*
5607  * XXX no way to pass mode (transport/tunnel) to userland
5608  * XXX replay checking?
5609  * XXX sysctl interface to ipsec_{ah,esp}_keymin
5610  */
5611 static struct mbuf *
5612 key_getprop(const struct secasindex *saidx)
5613 {
5614         struct sadb_prop *prop;
5615         struct mbuf *m, *n;
5616         const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5617         int totlen;
5618
5619         switch (saidx->proto)  {
5620 #ifdef IPSEC_ESP
5621         case IPPROTO_ESP:
5622                 m = key_getcomb_esp();
5623                 break;
5624 #endif
5625         case IPPROTO_AH:
5626                 m = key_getcomb_ah();
5627                 break;
5628         case IPPROTO_IPCOMP:
5629                 m = key_getcomb_ipcomp();
5630                 break;
5631         default:
5632                 return NULL;
5633         }
5634
5635         if (!m)
5636                 return NULL;
5637         M_PREPEND(m, l, MB_DONTWAIT);
5638         if (!m)
5639                 return NULL;
5640
5641         totlen = 0;
5642         for (n = m; n; n = n->m_next)
5643                 totlen += n->m_len;
5644
5645         prop = mtod(m, struct sadb_prop *);
5646         bzero(prop, sizeof(*prop));
5647         prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5648         prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5649         prop->sadb_prop_replay = 32;    /* XXX */
5650
5651         return m;
5652 }
5653
5654 /*
5655  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5656  * send
5657  *   <base, SA, address(SD), (address(P)), x_policy,
5658  *       (identity(SD),) (sensitivity,) proposal>
5659  * to KMD, and expect to receive
5660  *   <base> with SADB_ACQUIRE if error occured,
5661  * or
5662  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
5663  * from KMD by PF_KEY.
5664  *
5665  * XXX x_policy is outside of RFC2367 (KAME extension).
5666  * XXX sensitivity is not supported.
5667  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5668  * see comment for key_getcomb_ipcomp().
5669  *
5670  * OUT:
5671  *    0     : succeed
5672  *    others: error number
5673  */
5674 static int
5675 key_acquire(struct secasindex *saidx, struct secpolicy *sp)
5676 {
5677         struct mbuf *result = NULL, *m;
5678 #ifndef IPSEC_NONBLOCK_ACQUIRE
5679         struct secacq *newacq;
5680 #endif
5681         u_int8_t satype;
5682         int error = -1;
5683         u_int32_t seq;
5684
5685         /* sanity check */
5686         if (saidx == NULL)
5687                 panic("key_acquire: NULL pointer is passed.\n");
5688         if ((satype = key_proto2satype(saidx->proto)) == 0)
5689                 panic("key_acquire: invalid proto is passed.\n");
5690
5691 #ifndef IPSEC_NONBLOCK_ACQUIRE
5692         /*
5693          * We never do anything about acquirng SA.  There is anather
5694          * solution that kernel blocks to send SADB_ACQUIRE message until
5695          * getting something message from IKEd.  In later case, to be
5696          * managed with ACQUIRING list.
5697          */
5698         /* get a entry to check whether sending message or not. */
5699         if ((newacq = key_getacq(saidx)) != NULL) {
5700                 if (key_blockacq_count < newacq->count) {
5701                         /* reset counter and do send message. */
5702                         newacq->count = 0;
5703                 } else {
5704                         /* increment counter and do nothing. */
5705                         newacq->count++;
5706                         return 0;
5707                 }
5708         } else {
5709                 /* make new entry for blocking to send SADB_ACQUIRE. */
5710                 if ((newacq = key_newacq(saidx)) == NULL)
5711                         return ENOBUFS;
5712
5713                 /* add to acqtree */
5714                 LIST_INSERT_HEAD(&acqtree, newacq, chain);
5715         }
5716 #endif
5717
5718
5719 #ifndef IPSEC_NONBLOCK_ACQUIRE
5720         seq = newacq->seq;
5721 #else
5722         seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
5723 #endif
5724         m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5725         if (!m) {
5726                 error = ENOBUFS;
5727                 goto fail;
5728         }
5729         result = m;
5730
5731         /* set sadb_address for saidx's. */
5732         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5733             (struct sockaddr *)&saidx->src, FULLMASK, IPSEC_ULPROTO_ANY);
5734         if (!m) {
5735                 error = ENOBUFS;
5736                 goto fail;
5737         }
5738         m_cat(result, m);
5739
5740         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5741             (struct sockaddr *)&saidx->dst, FULLMASK, IPSEC_ULPROTO_ANY);
5742         if (!m) {
5743                 error = ENOBUFS;
5744                 goto fail;
5745         }
5746         m_cat(result, m);
5747
5748         /* XXX proxy address (optional) */
5749
5750         /* set sadb_x_policy */
5751         if (sp) {
5752                 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5753                 if (!m) {
5754                         error = ENOBUFS;
5755                         goto fail;
5756                 }
5757                 m_cat(result, m);
5758         }
5759
5760         /* XXX identity (optional) */
5761 #if 0
5762         if (idexttype && fqdn) {
5763                 /* create identity extension (FQDN) */
5764                 struct sadb_ident *id;
5765                 int fqdnlen;
5766
5767                 fqdnlen = strlen(fqdn) + 1;     /* +1 for terminating-NUL */
5768                 id = (struct sadb_ident *)p;
5769                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5770                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5771                 id->sadb_ident_exttype = idexttype;
5772                 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5773                 bcopy(fqdn, id + 1, fqdnlen);
5774                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5775         }
5776
5777         if (idexttype) {
5778                 /* create identity extension (USERFQDN) */
5779                 struct sadb_ident *id;
5780                 int userfqdnlen;
5781
5782                 if (userfqdn) {
5783                         /* +1 for terminating-NUL */
5784                         userfqdnlen = strlen(userfqdn) + 1;
5785                 } else
5786                         userfqdnlen = 0;
5787                 id = (struct sadb_ident *)p;
5788                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5789                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5790                 id->sadb_ident_exttype = idexttype;
5791                 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5792                 /* XXX is it correct? */
5793                 if (curproc && curproc->p_cred)
5794                         id->sadb_ident_id = curproc->p_cred->p_ruid;
5795                 if (userfqdn && userfqdnlen)
5796                         bcopy(userfqdn, id + 1, userfqdnlen);
5797                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5798         }
5799 #endif
5800
5801         /* XXX sensitivity (optional) */
5802
5803         /* create proposal/combination extension */
5804         m = key_getprop(saidx);
5805 #if 0
5806         /*
5807          * spec conformant: always attach proposal/combination extension,
5808          * the problem is that we have no way to attach it for ipcomp,
5809          * due to the way sadb_comb is declared in RFC2367.
5810          */
5811         if (!m) {
5812                 error = ENOBUFS;
5813                 goto fail;
5814         }
5815         m_cat(result, m);
5816 #else
5817         /*
5818          * outside of spec; make proposal/combination extension optional.
5819          */
5820         if (m)
5821                 m_cat(result, m);
5822 #endif
5823
5824         if ((result->m_flags & M_PKTHDR) == 0) {
5825                 error = EINVAL;
5826                 goto fail;
5827         }
5828
5829         if (result->m_len < sizeof(struct sadb_msg)) {
5830                 result = m_pullup(result, sizeof(struct sadb_msg));
5831                 if (result == NULL) {
5832                         error = ENOBUFS;
5833                         goto fail;
5834                 }
5835         }
5836
5837         result->m_pkthdr.len = 0;
5838         for (m = result; m; m = m->m_next)
5839                 result->m_pkthdr.len += m->m_len;
5840
5841         mtod(result, struct sadb_msg *)->sadb_msg_len =
5842             PFKEY_UNIT64(result->m_pkthdr.len);
5843
5844         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5845
5846  fail:
5847         if (result)
5848                 m_freem(result);
5849         return error;
5850 }
5851
5852 #ifndef IPSEC_NONBLOCK_ACQUIRE
5853 static struct secacq *
5854 key_newacq(struct secasindex *saidx)
5855 {
5856         struct secacq *newacq;
5857         struct timeval tv;
5858
5859         /* get new entry */
5860         KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
5861         if (newacq == NULL) {
5862                 ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
5863                 return NULL;
5864         }
5865         bzero(newacq, sizeof(*newacq));
5866
5867         /* copy secindex */
5868         bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5869         newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5870         microtime(&tv);
5871         newacq->created = tv.tv_sec;
5872         newacq->count = 0;
5873
5874         return newacq;
5875 }
5876
5877 static struct secacq *
5878 key_getacq(struct secasindex *saidx)
5879 {
5880         struct secacq *acq;
5881
5882         LIST_FOREACH(acq, &acqtree, chain) {
5883                 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5884                         return acq;
5885         }
5886
5887         return NULL;
5888 }
5889
5890 static struct secacq *
5891 key_getacqbyseq(u_int32_t seq)
5892 {
5893         struct secacq *acq;
5894
5895         LIST_FOREACH(acq, &acqtree, chain) {
5896                 if (acq->seq == seq)
5897                         return acq;
5898         }
5899
5900         return NULL;
5901 }
5902 #endif
5903
5904 static struct secspacq *
5905 key_newspacq(struct secpolicyindex *spidx)
5906 {
5907         struct secspacq *acq;
5908         struct timeval tv;
5909
5910         /* get new entry */
5911         KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
5912         if (acq == NULL) {
5913                 ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
5914                 return NULL;
5915         }
5916         bzero(acq, sizeof(*acq));
5917
5918         /* copy secindex */
5919         bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5920         microtime(&tv);
5921         acq->created = tv.tv_sec;
5922         acq->count = 0;
5923
5924         return acq;
5925 }
5926
5927 static struct secspacq *
5928 key_getspacq(struct secpolicyindex *spidx)
5929 {
5930         struct secspacq *acq;
5931
5932         LIST_FOREACH(acq, &spacqtree, chain) {
5933                 if (key_cmpspidx_exactly(spidx, &acq->spidx))
5934                         return acq;
5935         }
5936
5937         return NULL;
5938 }
5939
5940 /*
5941  * SADB_ACQUIRE processing,
5942  * in first situation, is receiving
5943  *   <base>
5944  * from the ikmpd, and clear sequence of its secasvar entry.
5945  *
5946  * In second situation, is receiving
5947  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5948  * from a user land process, and return
5949  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5950  * to the socket.
5951  *
5952  * m will always be freed.
5953  */
5954 static int
5955 key_acquire2(struct socket *so, struct mbuf *m,
5956              const struct sadb_msghdr *mhp)
5957 {
5958         struct sadb_address *src0, *dst0;
5959         struct secasindex saidx;
5960         struct secashead *sah;
5961         u_int16_t proto;
5962         int error;
5963
5964         /* sanity check */
5965         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5966                 panic("key_acquire2: NULL pointer is passed.\n");
5967
5968         /*
5969          * Error message from KMd.
5970          * We assume that if error was occured in IKEd, the length of PFKEY
5971          * message is equal to the size of sadb_msg structure.
5972          * We do not raise error even if error occured in this function.
5973          */
5974         if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5975 #ifndef IPSEC_NONBLOCK_ACQUIRE
5976                 struct secacq *acq;
5977                 struct timeval tv;
5978
5979                 /* check sequence number */
5980                 if (mhp->msg->sadb_msg_seq == 0) {
5981                         ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
5982                         m_freem(m);
5983                         return 0;
5984                 }
5985
5986                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5987                         /*
5988                          * the specified larval SA is already gone, or we got
5989                          * a bogus sequence number.  we can silently ignore it.
5990                          */
5991                         m_freem(m);
5992                         return 0;
5993                 }
5994
5995                 /* reset acq counter in order to deletion by timehander. */
5996                 microtime(&tv);
5997                 acq->created = tv.tv_sec;
5998                 acq->count = 0;
5999 #endif
6000                 m_freem(m);
6001                 return 0;
6002         }
6003
6004         /*
6005          * This message is from user land.
6006          */
6007
6008         /* map satype to proto */
6009         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6010                 ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
6011                 return key_senderror(so, m, EINVAL);
6012         }
6013
6014         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6015             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6016             mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6017                 /* error */
6018                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6019                 return key_senderror(so, m, EINVAL);
6020         }
6021         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6022             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6023             mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6024                 /* error */
6025                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6026                 return key_senderror(so, m, EINVAL);
6027         }
6028
6029         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6030         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6031
6032         /* XXX boundary check against sa_len */
6033         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6034
6035         /* get a SA index */
6036         LIST_FOREACH(sah, &sahtree, chain) {
6037                 if (sah->state == SADB_SASTATE_DEAD)
6038                         continue;
6039                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6040                         break;
6041         }
6042         if (sah != NULL) {
6043                 ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
6044                 return key_senderror(so, m, EEXIST);
6045         }
6046
6047         error = key_acquire(&saidx, NULL);
6048         if (error != 0) {
6049                 ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
6050                         "from key_acquire.\n", mhp->msg->sadb_msg_errno));
6051                 return key_senderror(so, m, error);
6052         }
6053
6054         return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6055 }
6056
6057 /*
6058  * SADB_REGISTER processing.
6059  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6060  * receive
6061  *   <base>
6062  * from the ikmpd, and register a socket to send PF_KEY messages,
6063  * and send
6064  *   <base, supported>
6065  * to KMD by PF_KEY.
6066  * If socket is detached, must free from regnode.
6067  *
6068  * m will always be freed.
6069  */
6070 static int
6071 key_register(struct socket *so, struct mbuf *m,
6072              const struct sadb_msghdr *mhp)
6073 {
6074         struct secreg *reg, *newreg = 0;
6075
6076         /* sanity check */
6077         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6078                 panic("key_register: NULL pointer is passed.\n");
6079
6080         /* check for invalid register message */
6081         if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6082                 return key_senderror(so, m, EINVAL);
6083
6084         /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6085         if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6086                 goto setmsg;
6087
6088         /* check whether existing or not */
6089         LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6090                 if (reg->so == so) {
6091                         ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
6092                         return key_senderror(so, m, EEXIST);
6093                 }
6094         }
6095
6096         /* create regnode */
6097         KMALLOC(newreg, struct secreg *, sizeof(*newreg));
6098         if (newreg == NULL) {
6099                 ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
6100                 return key_senderror(so, m, ENOBUFS);
6101         }
6102         bzero((caddr_t)newreg, sizeof(*newreg));
6103
6104         newreg->so = so;
6105         ((struct keycb *)sotorawcb(so))->kp_registered++;
6106
6107         /* add regnode to regtree. */
6108         LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6109
6110   setmsg:
6111     {
6112         struct mbuf *n;
6113         struct sadb_msg *newmsg;
6114         struct sadb_supported *sup;
6115         u_int len, alen, elen;
6116         int off;
6117         int i;
6118         struct sadb_alg *alg;
6119
6120         /* create new sadb_msg to reply. */
6121         alen = 0;
6122         for (i = 1; i <= SADB_AALG_MAX; i++) {
6123                 if (ah_algorithm_lookup(i))
6124                         alen += sizeof(struct sadb_alg);
6125         }
6126         if (alen)
6127                 alen += sizeof(struct sadb_supported);
6128         elen = 0;
6129 #ifdef IPSEC_ESP
6130         for (i = 1; i <= SADB_EALG_MAX; i++) {
6131                 if (esp_algorithm_lookup(i))
6132                         elen += sizeof(struct sadb_alg);
6133         }
6134         if (elen)
6135                 elen += sizeof(struct sadb_supported);
6136 #endif
6137
6138         len = sizeof(struct sadb_msg) + alen + elen;
6139
6140         if (len > MCLBYTES)
6141                 return key_senderror(so, m, ENOBUFS);
6142
6143         MGETHDR(n, MB_DONTWAIT, MT_DATA);
6144         if (len > MHLEN) {
6145                 MCLGET(n, MB_DONTWAIT);
6146                 if ((n->m_flags & M_EXT) == 0) {
6147                         m_freem(n);
6148                         n = NULL;
6149                 }
6150         }
6151         if (!n)
6152                 return key_senderror(so, m, ENOBUFS);
6153
6154         n->m_pkthdr.len = n->m_len = len;
6155         n->m_next = NULL;
6156         off = 0;
6157
6158         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6159         newmsg = mtod(n, struct sadb_msg *);
6160         newmsg->sadb_msg_errno = 0;
6161         newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6162         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6163
6164         /* for authentication algorithm */
6165         if (alen) {
6166                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6167                 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6168                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6169                 off += PFKEY_ALIGN8(sizeof(*sup));
6170
6171                 for (i = 1; i <= SADB_AALG_MAX; i++) {
6172                         const struct ah_algorithm *aalgo;
6173
6174                         aalgo = ah_algorithm_lookup(i);
6175                         if (!aalgo)
6176                                 continue;
6177                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6178                         alg->sadb_alg_id = i;
6179                         alg->sadb_alg_ivlen = 0;
6180                         alg->sadb_alg_minbits = aalgo->keymin;
6181                         alg->sadb_alg_maxbits = aalgo->keymax;
6182                         off += PFKEY_ALIGN8(sizeof(*alg));
6183                 }
6184         }
6185
6186 #ifdef IPSEC_ESP
6187         /* for encryption algorithm */
6188         if (elen) {
6189                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6190                 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6191                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6192                 off += PFKEY_ALIGN8(sizeof(*sup));
6193
6194                 for (i = 1; i <= SADB_EALG_MAX; i++) {
6195                         const struct esp_algorithm *ealgo;
6196
6197                         ealgo = esp_algorithm_lookup(i);
6198                         if (!ealgo)
6199                                 continue;
6200                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6201                         alg->sadb_alg_id = i;
6202                         if (ealgo && ealgo->ivlen) {
6203                                 /*
6204                                  * give NULL to get the value preferred by
6205                                  * algorithm XXX SADB_X_EXT_DERIV ?
6206                                  */
6207                                 alg->sadb_alg_ivlen =
6208                                     (*ealgo->ivlen)(ealgo, NULL);
6209                         } else
6210                                 alg->sadb_alg_ivlen = 0;
6211                         alg->sadb_alg_minbits = ealgo->keymin;
6212                         alg->sadb_alg_maxbits = ealgo->keymax;
6213                         off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6214                 }
6215         }
6216 #endif
6217
6218 #ifdef DIGAGNOSTIC
6219         if (off != len)
6220                 panic("length assumption failed in key_register");
6221 #endif
6222
6223         m_freem(m);
6224         return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6225     }
6226 }
6227
6228 /*
6229  * free secreg entry registered.
6230  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6231  */
6232 void
6233 key_freereg(struct socket *so)
6234 {
6235         struct secreg *reg;
6236         int i;
6237
6238         /* sanity check */
6239         if (so == NULL)
6240                 panic("key_freereg: NULL pointer is passed.\n");
6241
6242         /*
6243          * check whether existing or not.
6244          * check all type of SA, because there is a potential that
6245          * one socket is registered to multiple type of SA.
6246          */
6247         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6248                 LIST_FOREACH(reg, &regtree[i], chain) {
6249                         if (reg->so == so
6250                          && __LIST_CHAINED(reg)) {
6251                                 LIST_REMOVE(reg, chain);
6252                                 KFREE(reg);
6253                                 break;
6254                         }
6255                 }
6256         }
6257         
6258         return;
6259 }
6260
6261 /*
6262  * SADB_EXPIRE processing
6263  * send
6264  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6265  * to KMD by PF_KEY.
6266  * NOTE: We send only soft lifetime extension.
6267  *
6268  * OUT: 0       : succeed
6269  *      others  : error number
6270  */
6271 static int
6272 key_expire(struct secasvar *sav)
6273 {
6274         int satype;
6275         struct mbuf *result = NULL, *m;
6276         int len;
6277         int error = -1;
6278         struct sadb_lifetime *lt;
6279
6280         /* XXX: Why do we lock ? */
6281         crit_enter();
6282
6283         /* sanity check */
6284         if (sav == NULL)
6285                 panic("key_expire: NULL pointer is passed.\n");
6286         if (sav->sah == NULL)
6287                 panic("key_expire: Why was SA index in SA NULL.\n");
6288         if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
6289                 panic("key_expire: invalid proto is passed.\n");
6290
6291         /* set msg header */
6292         m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6293         if (!m) {
6294                 error = ENOBUFS;
6295                 goto fail;
6296         }
6297         result = m;
6298
6299         /* create SA extension */
6300         m = key_setsadbsa(sav);
6301         if (!m) {
6302                 error = ENOBUFS;
6303                 goto fail;
6304         }
6305         m_cat(result, m);
6306
6307         /* create SA extension */
6308         m = key_setsadbxsa2(sav->sah->saidx.mode,
6309                         sav->replay ? sav->replay->count : 0,
6310                         sav->sah->saidx.reqid);
6311         if (!m) {
6312                 error = ENOBUFS;
6313                 goto fail;
6314         }
6315         m_cat(result, m);
6316
6317         /* create lifetime extension (current and soft) */
6318         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6319         m = key_alloc_mbuf(len);
6320         if (!m || m->m_next) {  /*XXX*/
6321                 if (m)
6322                         m_freem(m);
6323                 error = ENOBUFS;
6324                 goto fail;
6325         }
6326         bzero(mtod(m, caddr_t), len);
6327         lt = mtod(m, struct sadb_lifetime *);
6328         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6329         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6330         lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6331         lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6332         lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6333         lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6334         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6335         bcopy(sav->lft_s, lt, sizeof(*lt));
6336         m_cat(result, m);
6337
6338         /* set sadb_address for source */
6339         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6340             (struct sockaddr *)&sav->sah->saidx.src,
6341             FULLMASK, IPSEC_ULPROTO_ANY);
6342         if (!m) {
6343                 error = ENOBUFS;
6344                 goto fail;
6345         }
6346         m_cat(result, m);
6347
6348         /* set sadb_address for destination */
6349         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6350             (struct sockaddr *)&sav->sah->saidx.dst,
6351             FULLMASK, IPSEC_ULPROTO_ANY);
6352         if (!m) {
6353                 error = ENOBUFS;
6354                 goto fail;
6355         }
6356         m_cat(result, m);
6357
6358         if ((result->m_flags & M_PKTHDR) == 0) {
6359                 error = EINVAL;
6360                 goto fail;
6361         }
6362
6363         if (result->m_len < sizeof(struct sadb_msg)) {
6364                 result = m_pullup(result, sizeof(struct sadb_msg));
6365                 if (result == NULL) {
6366                         error = ENOBUFS;
6367                         goto fail;
6368                 }
6369         }
6370
6371         result->m_pkthdr.len = 0;
6372         for (m = result; m; m = m->m_next)
6373                 result->m_pkthdr.len += m->m_len;
6374
6375         mtod(result, struct sadb_msg *)->sadb_msg_len =
6376             PFKEY_UNIT64(result->m_pkthdr.len);
6377
6378         crit_exit();
6379         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6380
6381  fail:
6382         if (result)
6383                 m_freem(result);
6384         crit_exit();
6385         return error;
6386 }
6387
6388 /*
6389  * SADB_FLUSH processing
6390  * receive
6391  *   <base>
6392  * from the ikmpd, and free all entries in secastree.
6393  * and send,
6394  *   <base>
6395  * to the ikmpd.
6396  * NOTE: to do is only marking SADB_SASTATE_DEAD.
6397  *
6398  * m will always be freed.
6399  */
6400 static int
6401 key_flush(struct socket *so, struct mbuf *m,
6402           const struct sadb_msghdr *mhp)
6403 {
6404         struct sadb_msg *newmsg;
6405         struct secashead *sah, *nextsah;
6406         struct secasvar *sav, *nextsav;
6407         u_int16_t proto;
6408         u_int8_t state;
6409         u_int stateidx;
6410
6411         /* sanity check */
6412         if (so == NULL || mhp == NULL || mhp->msg == NULL)
6413                 panic("key_flush: NULL pointer is passed.\n");
6414
6415         /* map satype to proto */
6416         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6417                 ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6418                 return key_senderror(so, m, EINVAL);
6419         }
6420
6421         /* no SATYPE specified, i.e. flushing all SA. */
6422         for (sah = LIST_FIRST(&sahtree);
6423              sah != NULL;
6424              sah = nextsah) {
6425                 nextsah = LIST_NEXT(sah, chain);
6426
6427                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6428                  && proto != sah->saidx.proto)
6429                         continue;
6430
6431                 for (stateidx = 0;
6432                      stateidx < _ARRAYLEN(saorder_state_alive);
6433                      stateidx++) {
6434                         state = saorder_state_any[stateidx];
6435                         for (sav = LIST_FIRST(&sah->savtree[state]);
6436                              sav != NULL;
6437                              sav = nextsav) {
6438
6439                                 nextsav = LIST_NEXT(sav, chain);
6440
6441                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6442                                 key_freesav(sav);
6443                         }
6444                 }
6445
6446                 sah->state = SADB_SASTATE_DEAD;
6447         }
6448
6449         if (m->m_len < sizeof(struct sadb_msg) ||
6450             sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6451                 ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
6452                 return key_senderror(so, m, ENOBUFS);
6453         }
6454
6455         if (m->m_next)
6456                 m_freem(m->m_next);
6457         m->m_next = NULL;
6458         m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6459         newmsg = mtod(m, struct sadb_msg *);
6460         newmsg->sadb_msg_errno = 0;
6461         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6462
6463         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6464 }
6465
6466 /*
6467  * SADB_DUMP processing
6468  * dump all entries including status of DEAD in SAD.
6469  * receive
6470  *   <base>
6471  * from the ikmpd, and dump all secasvar leaves
6472  * and send,
6473  *   <base> .....
6474  * to the ikmpd.
6475  *
6476  * m will always be freed.
6477  */
6478 static int
6479 key_dump(struct socket *so, struct mbuf *m,
6480          const struct sadb_msghdr *mhp)
6481 {
6482         struct secashead *sah;
6483         struct secasvar *sav;
6484         u_int16_t proto;
6485         u_int stateidx;
6486         u_int8_t satype;
6487         u_int8_t state;
6488         int cnt;
6489         struct sadb_msg *newmsg;
6490         struct mbuf *n;
6491
6492         /* sanity check */
6493         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6494                 panic("key_dump: NULL pointer is passed.\n");
6495
6496         /* map satype to proto */
6497         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6498                 ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
6499                 return key_senderror(so, m, EINVAL);
6500         }
6501
6502         /* count sav entries to be sent to the userland. */
6503         cnt = 0;
6504         LIST_FOREACH(sah, &sahtree, chain) {
6505                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6506                  && proto != sah->saidx.proto)
6507                         continue;
6508
6509                 for (stateidx = 0;
6510                      stateidx < _ARRAYLEN(saorder_state_any);
6511                      stateidx++) {
6512                         state = saorder_state_any[stateidx];
6513                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
6514                                 cnt++;
6515                         }
6516                 }
6517         }
6518
6519         if (cnt == 0)
6520                 return key_senderror(so, m, ENOENT);
6521
6522         /* send this to the userland, one at a time. */
6523         newmsg = NULL;
6524         LIST_FOREACH(sah, &sahtree, chain) {
6525                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6526                  && proto != sah->saidx.proto)
6527                         continue;
6528
6529                 /* map proto to satype */
6530                 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6531                         ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
6532                         return key_senderror(so, m, EINVAL);
6533                 }
6534
6535                 for (stateidx = 0;
6536                      stateidx < _ARRAYLEN(saorder_state_any);
6537                      stateidx++) {
6538                         state = saorder_state_any[stateidx];
6539                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
6540                                 n = key_setdumpsa(sav, SADB_DUMP, satype,
6541                                     --cnt, mhp->msg->sadb_msg_pid);
6542                                 if (!n)
6543                                         return key_senderror(so, m, ENOBUFS);
6544
6545                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6546                         }
6547                 }
6548         }
6549
6550         m_freem(m);
6551         return 0;
6552 }
6553
6554 /*
6555  * SADB_X_PROMISC processing
6556  *
6557  * m will always be freed.
6558  */
6559 static int
6560 key_promisc(struct socket *so, struct mbuf *m,
6561             const struct sadb_msghdr *mhp)
6562 {
6563         int olen;
6564
6565         /* sanity check */
6566         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6567                 panic("key_promisc: NULL pointer is passed.\n");
6568
6569         olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6570
6571         if (olen < sizeof(struct sadb_msg)) {
6572 #if 1
6573                 return key_senderror(so, m, EINVAL);
6574 #else
6575                 m_freem(m);
6576                 return 0;
6577 #endif
6578         } else if (olen == sizeof(struct sadb_msg)) {
6579                 /* enable/disable promisc mode */
6580                 struct keycb *kp;
6581
6582                 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6583                         return key_senderror(so, m, EINVAL);
6584                 mhp->msg->sadb_msg_errno = 0;
6585                 switch (mhp->msg->sadb_msg_satype) {
6586                 case 0:
6587                 case 1:
6588                         kp->kp_promisc = mhp->msg->sadb_msg_satype;
6589                         break;
6590                 default:
6591                         return key_senderror(so, m, EINVAL);
6592                 }
6593
6594                 /* send the original message back to everyone */
6595                 mhp->msg->sadb_msg_errno = 0;
6596                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6597         } else {
6598                 /* send packet as is */
6599
6600                 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6601
6602                 /* TODO: if sadb_msg_seq is specified, send to specific pid */
6603                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6604         }
6605 }
6606
6607 static int (*key_typesw[]) (struct socket *, struct mbuf *,
6608                 const struct sadb_msghdr *) = {
6609         NULL,           /* SADB_RESERVED */
6610         key_getspi,     /* SADB_GETSPI */
6611         key_update,     /* SADB_UPDATE */
6612         key_add,        /* SADB_ADD */
6613         key_delete,     /* SADB_DELETE */
6614         key_get,        /* SADB_GET */
6615         key_acquire2,   /* SADB_ACQUIRE */
6616         key_register,   /* SADB_REGISTER */
6617         NULL,           /* SADB_EXPIRE */
6618         key_flush,      /* SADB_FLUSH */
6619         key_dump,       /* SADB_DUMP */
6620         key_promisc,    /* SADB_X_PROMISC */
6621         NULL,           /* SADB_X_PCHANGE */
6622         key_spdadd,     /* SADB_X_SPDUPDATE */
6623         key_spdadd,     /* SADB_X_SPDADD */
6624         key_spddelete,  /* SADB_X_SPDDELETE */
6625         key_spdget,     /* SADB_X_SPDGET */
6626         NULL,           /* SADB_X_SPDACQUIRE */
6627         key_spddump,    /* SADB_X_SPDDUMP */
6628         key_spdflush,   /* SADB_X_SPDFLUSH */
6629         key_spdadd,     /* SADB_X_SPDSETIDX */
6630         NULL,           /* SADB_X_SPDEXPIRE */
6631         key_spddelete2, /* SADB_X_SPDDELETE2 */
6632 };
6633
6634 /*
6635  * parse sadb_msg buffer to process PFKEYv2,
6636  * and create a data to response if needed.
6637  * I think to be dealed with mbuf directly.
6638  * IN:
6639  *     msgp  : pointer to pointer to a received buffer pulluped.
6640  *             This is rewrited to response.
6641  *     so    : pointer to socket.
6642  * OUT:
6643  *    length for buffer to send to user process.
6644  */
6645 int
6646 key_parse(struct mbuf *m, struct socket *so)
6647 {
6648         struct sadb_msg *msg;
6649         struct sadb_msghdr mh;
6650         u_int orglen;
6651         int error;
6652         int target;
6653
6654         /* sanity check */
6655         if (m == NULL || so == NULL)
6656                 panic("key_parse: NULL pointer is passed.\n");
6657
6658 #if 0   /*kdebug_sadb assumes msg in linear buffer*/
6659         KEYDEBUG(KEYDEBUG_KEY_DUMP,
6660                 ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
6661                 kdebug_sadb(msg));
6662 #endif
6663
6664         if (m->m_len < sizeof(struct sadb_msg)) {
6665                 m = m_pullup(m, sizeof(struct sadb_msg));
6666                 if (!m)
6667                         return ENOBUFS;
6668         }
6669         msg = mtod(m, struct sadb_msg *);
6670         orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6671         target = KEY_SENDUP_ONE;
6672
6673         if ((m->m_flags & M_PKTHDR) == 0 ||
6674             m->m_pkthdr.len != m->m_pkthdr.len) {
6675                 ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
6676                 pfkeystat.out_invlen++;
6677                 error = EINVAL;
6678                 goto senderror;
6679         }
6680
6681         if (msg->sadb_msg_version != PF_KEY_V2) {
6682                 ipseclog((LOG_DEBUG,
6683                     "key_parse: PF_KEY version %u is mismatched.\n",
6684                     msg->sadb_msg_version));
6685                 pfkeystat.out_invver++;
6686                 error = EINVAL;
6687                 goto senderror;
6688         }
6689
6690         if (msg->sadb_msg_type > SADB_MAX) {
6691                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6692                     msg->sadb_msg_type));
6693                 pfkeystat.out_invmsgtype++;
6694                 error = EINVAL;
6695                 goto senderror;
6696         }
6697
6698         /* for old-fashioned code - should be nuked */
6699         if (m->m_pkthdr.len > MCLBYTES) {
6700                 m_freem(m);
6701                 return ENOBUFS;
6702         }
6703         if (m->m_next) {
6704                 struct mbuf *n;
6705
6706                 MGETHDR(n, MB_DONTWAIT, MT_DATA);
6707                 if (n && m->m_pkthdr.len > MHLEN) {
6708                         MCLGET(n, MB_DONTWAIT);
6709                         if ((n->m_flags & M_EXT) == 0) {
6710                                 m_free(n);
6711                                 n = NULL;
6712                         }
6713                 }
6714                 if (!n) {
6715                         m_freem(m);
6716                         return ENOBUFS;
6717                 }
6718                 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6719                 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6720                 n->m_next = NULL;
6721                 m_freem(m);
6722                 m = n;
6723         }
6724
6725         /* align the mbuf chain so that extensions are in contiguous region. */
6726         error = key_align(m, &mh);
6727         if (error)
6728                 return error;
6729
6730         if (m->m_next) {        /*XXX*/
6731                 m_freem(m);
6732                 return ENOBUFS;
6733         }
6734
6735         msg = mh.msg;
6736
6737         /* check SA type */
6738         switch (msg->sadb_msg_satype) {
6739         case SADB_SATYPE_UNSPEC:
6740                 switch (msg->sadb_msg_type) {
6741                 case SADB_GETSPI:
6742                 case SADB_UPDATE:
6743                 case SADB_ADD:
6744                 case SADB_DELETE:
6745                 case SADB_GET:
6746                 case SADB_ACQUIRE:
6747                 case SADB_EXPIRE:
6748                         ipseclog((LOG_DEBUG, "key_parse: must specify satype "
6749                             "when msg type=%u.\n", msg->sadb_msg_type));
6750                         pfkeystat.out_invsatype++;
6751                         error = EINVAL;
6752                         goto senderror;
6753                 }
6754                 break;
6755         case SADB_SATYPE_AH:
6756         case SADB_SATYPE_ESP:
6757         case SADB_X_SATYPE_IPCOMP:
6758                 switch (msg->sadb_msg_type) {
6759                 case SADB_X_SPDADD:
6760                 case SADB_X_SPDDELETE:
6761                 case SADB_X_SPDGET:
6762                 case SADB_X_SPDDUMP:
6763                 case SADB_X_SPDFLUSH:
6764                 case SADB_X_SPDSETIDX:
6765                 case SADB_X_SPDUPDATE:
6766                 case SADB_X_SPDDELETE2:
6767                         ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
6768                             msg->sadb_msg_type));
6769                         pfkeystat.out_invsatype++;
6770                         error = EINVAL;
6771                         goto senderror;
6772                 }
6773                 break;
6774         case SADB_SATYPE_RSVP:
6775         case SADB_SATYPE_OSPFV2:
6776         case SADB_SATYPE_RIPV2:
6777         case SADB_SATYPE_MIP:
6778                 ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
6779                     msg->sadb_msg_satype));
6780                 pfkeystat.out_invsatype++;
6781                 error = EOPNOTSUPP;
6782                 goto senderror;
6783         case 1: /* XXX: What does it do? */
6784                 if (msg->sadb_msg_type == SADB_X_PROMISC)
6785                         break;
6786                 /*FALLTHROUGH*/
6787         default:
6788                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
6789                     msg->sadb_msg_satype));
6790                 pfkeystat.out_invsatype++;
6791                 error = EINVAL;
6792                 goto senderror;
6793         }
6794
6795         /* check field of upper layer protocol and address family */
6796         if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6797          && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6798                 struct sadb_address *src0, *dst0;
6799                 u_int plen;
6800
6801                 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6802                 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6803
6804                 /* check upper layer protocol */
6805                 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6806                         ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
6807                         pfkeystat.out_invaddr++;
6808                         error = EINVAL;
6809                         goto senderror;
6810                 }
6811
6812                 /* check family */
6813                 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6814                     PFKEY_ADDR_SADDR(dst0)->sa_family) {
6815                         ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
6816                         pfkeystat.out_invaddr++;
6817                         error = EINVAL;
6818                         goto senderror;
6819                 }
6820                 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6821                     PFKEY_ADDR_SADDR(dst0)->sa_len) {
6822                         ipseclog((LOG_DEBUG,
6823                             "key_parse: address struct size mismatched.\n"));
6824                         pfkeystat.out_invaddr++;
6825                         error = EINVAL;
6826                         goto senderror;
6827                 }
6828
6829                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6830                 case AF_INET:
6831                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6832                             sizeof(struct sockaddr_in)) {
6833                                 pfkeystat.out_invaddr++;
6834                                 error = EINVAL;
6835                                 goto senderror;
6836                         }
6837                         break;
6838                 case AF_INET6:
6839                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6840                             sizeof(struct sockaddr_in6)) {
6841                                 pfkeystat.out_invaddr++;
6842                                 error = EINVAL;
6843                                 goto senderror;
6844                         }
6845                         break;
6846                 default:
6847                         ipseclog((LOG_DEBUG,
6848                             "key_parse: unsupported address family.\n"));
6849                         pfkeystat.out_invaddr++;
6850                         error = EAFNOSUPPORT;
6851                         goto senderror;
6852                 }
6853
6854                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6855                 case AF_INET:
6856                         plen = sizeof(struct in_addr) << 3;
6857                         break;
6858                 case AF_INET6:
6859                         plen = sizeof(struct in6_addr) << 3;
6860                         break;
6861                 default:
6862                         plen = 0;       /*fool gcc*/
6863                         break;
6864                 }
6865
6866                 /* check max prefix length */
6867                 if (src0->sadb_address_prefixlen > plen ||
6868                     dst0->sadb_address_prefixlen > plen) {
6869                         ipseclog((LOG_DEBUG,
6870                             "key_parse: illegal prefixlen.\n"));
6871                         pfkeystat.out_invaddr++;
6872                         error = EINVAL;
6873                         goto senderror;
6874                 }
6875
6876                 /*
6877                  * prefixlen == 0 is valid because there can be a case when
6878                  * all addresses are matched.
6879                  */
6880         }
6881
6882         if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6883             key_typesw[msg->sadb_msg_type] == NULL) {
6884                 pfkeystat.out_invmsgtype++;
6885                 error = EINVAL;
6886                 goto senderror;
6887         }
6888
6889         return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6890
6891 senderror:
6892         msg->sadb_msg_errno = error;
6893         return key_sendup_mbuf(so, m, target);
6894 }
6895
6896 static int
6897 key_senderror(struct socket *so, struct mbuf *m, int code)
6898 {
6899         struct sadb_msg *msg;
6900
6901         if (m->m_len < sizeof(struct sadb_msg))
6902                 panic("invalid mbuf passed to key_senderror");
6903
6904         msg = mtod(m, struct sadb_msg *);
6905         msg->sadb_msg_errno = code;
6906         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6907 }
6908
6909 /*
6910  * set the pointer to each header into message buffer.
6911  * m will be freed on error.
6912  * XXX larger-than-MCLBYTES extension?
6913  */
6914 static int
6915 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
6916 {
6917         struct mbuf *n;
6918         struct sadb_ext *ext;
6919         size_t off, end;
6920         int extlen;
6921         int toff;
6922
6923         /* sanity check */
6924         if (m == NULL || mhp == NULL)
6925                 panic("key_align: NULL pointer is passed.\n");
6926         if (m->m_len < sizeof(struct sadb_msg))
6927                 panic("invalid mbuf passed to key_align");
6928
6929         /* initialize */
6930         bzero(mhp, sizeof(*mhp));
6931
6932         mhp->msg = mtod(m, struct sadb_msg *);
6933         mhp->ext[0] = (struct sadb_ext *)mhp->msg;      /*XXX backward compat */
6934
6935         end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6936         extlen = end;   /*just in case extlen is not updated*/
6937         for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6938                 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6939                 if (!n) {
6940                         /* m is already freed */
6941                         return ENOBUFS;
6942                 }
6943                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6944
6945                 /* set pointer */
6946                 switch (ext->sadb_ext_type) {
6947                 case SADB_EXT_SA:
6948                 case SADB_EXT_ADDRESS_SRC:
6949                 case SADB_EXT_ADDRESS_DST:
6950                 case SADB_EXT_ADDRESS_PROXY:
6951                 case SADB_EXT_LIFETIME_CURRENT:
6952                 case SADB_EXT_LIFETIME_HARD:
6953                 case SADB_EXT_LIFETIME_SOFT:
6954                 case SADB_EXT_KEY_AUTH:
6955                 case SADB_EXT_KEY_ENCRYPT:
6956                 case SADB_EXT_IDENTITY_SRC:
6957                 case SADB_EXT_IDENTITY_DST:
6958                 case SADB_EXT_SENSITIVITY:
6959                 case SADB_EXT_PROPOSAL:
6960                 case SADB_EXT_SUPPORTED_AUTH:
6961                 case SADB_EXT_SUPPORTED_ENCRYPT:
6962                 case SADB_EXT_SPIRANGE:
6963                 case SADB_X_EXT_POLICY:
6964                 case SADB_X_EXT_SA2:
6965                         /* duplicate check */
6966                         /*
6967                          * XXX Are there duplication payloads of either
6968                          * KEY_AUTH or KEY_ENCRYPT ?
6969                          */
6970                         if (mhp->ext[ext->sadb_ext_type] != NULL) {
6971                                 ipseclog((LOG_DEBUG,
6972                                     "key_align: duplicate ext_type %u "
6973                                     "is passed.\n", ext->sadb_ext_type));
6974                                 m_freem(m);
6975                                 pfkeystat.out_dupext++;
6976                                 return EINVAL;
6977                         }
6978                         break;
6979                 default:
6980                         ipseclog((LOG_DEBUG,
6981                             "key_align: invalid ext_type %u is passed.\n",
6982                             ext->sadb_ext_type));
6983                         m_freem(m);
6984                         pfkeystat.out_invexttype++;
6985                         return EINVAL;
6986                 }
6987
6988                 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6989
6990                 if (key_validate_ext(ext, extlen)) {
6991                         m_freem(m);
6992                         pfkeystat.out_invlen++;
6993                         return EINVAL;
6994                 }
6995
6996                 n = m_pulldown(m, off, extlen, &toff);
6997                 if (!n) {
6998                         /* m is already freed */
6999                         return ENOBUFS;
7000                 }
7001                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7002
7003                 mhp->ext[ext->sadb_ext_type] = ext;
7004                 mhp->extoff[ext->sadb_ext_type] = off;
7005                 mhp->extlen[ext->sadb_ext_type] = extlen;
7006         }
7007
7008         if (off != end) {
7009                 m_freem(m);
7010                 pfkeystat.out_invlen++;
7011                 return EINVAL;
7012         }
7013
7014         return 0;
7015 }
7016
7017 static int
7018 key_validate_ext(const struct sadb_ext *ext, int len)
7019 {
7020         const struct sockaddr *sa;
7021         enum { NONE, ADDR } checktype = NONE;
7022         int baselen = 0;
7023         const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7024
7025         if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7026                 return EINVAL;
7027
7028         /* if it does not match minimum/maximum length, bail */
7029         if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7030             ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7031                 return EINVAL;
7032         if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7033                 return EINVAL;
7034         if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7035                 return EINVAL;
7036
7037         /* more checks based on sadb_ext_type XXX need more */
7038         switch (ext->sadb_ext_type) {
7039         case SADB_EXT_ADDRESS_SRC:
7040         case SADB_EXT_ADDRESS_DST:
7041         case SADB_EXT_ADDRESS_PROXY:
7042                 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7043                 checktype = ADDR;
7044                 break;
7045         case SADB_EXT_IDENTITY_SRC:
7046         case SADB_EXT_IDENTITY_DST:
7047                 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7048                     SADB_X_IDENTTYPE_ADDR) {
7049                         baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7050                         checktype = ADDR;
7051                 } else
7052                         checktype = NONE;
7053                 break;
7054         default:
7055                 checktype = NONE;
7056                 break;
7057         }
7058
7059         switch (checktype) {
7060         case NONE:
7061                 break;
7062         case ADDR:
7063                 sa = (const struct sockaddr *)((c_caddr_t)ext + baselen);
7064                 if (len < baselen + sal)
7065                         return EINVAL;
7066                 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7067                         return EINVAL;
7068                 break;
7069         }
7070
7071         return 0;
7072 }
7073
7074 void
7075 key_init(void)
7076 {
7077         int i;
7078
7079         bzero((caddr_t)&key_cb, sizeof(key_cb));
7080
7081         for (i = 0; i < IPSEC_DIR_MAX; i++) {
7082                 LIST_INIT(&sptree[i]);
7083         }
7084
7085         LIST_INIT(&sahtree);
7086
7087         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7088                 LIST_INIT(&regtree[i]);
7089         }
7090
7091 #ifndef IPSEC_NONBLOCK_ACQUIRE
7092         LIST_INIT(&acqtree);
7093 #endif
7094         LIST_INIT(&spacqtree);
7095
7096         /* system default */
7097 #ifdef INET
7098         ip4_def_policy.policy = IPSEC_POLICY_NONE;
7099         ip4_def_policy.refcnt++;        /*never reclaim this*/
7100 #endif
7101 #ifdef INET6
7102         ip6_def_policy.policy = IPSEC_POLICY_NONE;
7103         ip6_def_policy.refcnt++;        /*never reclaim this*/
7104 #endif
7105
7106 #ifndef IPSEC_DEBUG2
7107         callout_init(&key_timehandler_ch);
7108         callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
7109 #endif /*IPSEC_DEBUG2*/
7110
7111         /* initialize key statistics */
7112         keystat.getspi_count = 1;
7113
7114         printf("IPsec: Initialized Security Association Processing.\n");
7115
7116         return;
7117 }
7118
7119 /*
7120  * XXX: maybe This function is called after INBOUND IPsec processing.
7121  *
7122  * Special check for tunnel-mode packets.
7123  * We must make some checks for consistency between inner and outer IP header.
7124  *
7125  * xxx more checks to be provided
7126  */
7127 int
7128 key_checktunnelsanity(struct secasvar *sav, u_int family,
7129                       caddr_t src, caddr_t dst)
7130 {
7131         /* sanity check */
7132         if (sav->sah == NULL)
7133                 panic("sav->sah == NULL at key_checktunnelsanity");
7134
7135         /* XXX: check inner IP header */
7136
7137         return 1;
7138 }
7139
7140 #if 0
7141 #define hostnamelen     strlen(hostname)
7142
7143 /*
7144  * Get FQDN for the host.
7145  * If the administrator configured hostname (by hostname(1)) without
7146  * domain name, returns nothing.
7147  */
7148 static const char *
7149 key_getfqdn(void)
7150 {
7151         int i;
7152         int hasdot;
7153         static char fqdn[MAXHOSTNAMELEN + 1];
7154
7155         if (!hostnamelen)
7156                 return NULL;
7157
7158         /* check if it comes with domain name. */
7159         hasdot = 0;
7160         for (i = 0; i < hostnamelen; i++) {
7161                 if (hostname[i] == '.')
7162                         hasdot++;
7163         }
7164         if (!hasdot)
7165                 return NULL;
7166
7167         /* NOTE: hostname may not be NUL-terminated. */
7168         bzero(fqdn, sizeof(fqdn));
7169         bcopy(hostname, fqdn, hostnamelen);
7170         fqdn[hostnamelen] = '\0';
7171         return fqdn;
7172 }
7173
7174 /*
7175  * get username@FQDN for the host/user.
7176  */
7177 static const char *
7178 key_getuserfqdn(void)
7179 {
7180         const char *host;
7181         static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
7182         struct proc *p = curproc;
7183         char *q;
7184
7185         if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
7186                 return NULL;
7187         if (!(host = key_getfqdn()))
7188                 return NULL;
7189
7190         /* NOTE: s_login may not be-NUL terminated. */
7191         bzero(userfqdn, sizeof(userfqdn));
7192         bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
7193         userfqdn[MAXLOGNAME] = '\0';    /* safeguard */
7194         q = userfqdn + strlen(userfqdn);
7195         *q++ = '@';
7196         bcopy(host, q, strlen(host));
7197         q += strlen(host);
7198         *q++ = '\0';
7199
7200         return userfqdn;
7201 }
7202 #endif
7203
7204 /* record data transfer on SA, and update timestamps */
7205 void
7206 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
7207 {
7208         if (!sav)
7209                 panic("key_sa_recordxfer called with sav == NULL");
7210         if (!m)
7211                 panic("key_sa_recordxfer called with m == NULL");
7212         if (!sav->lft_c)
7213                 return;
7214
7215         /*
7216          * XXX Currently, there is a difference of bytes size
7217          * between inbound and outbound processing.
7218          */
7219         sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7220         /* to check bytes lifetime is done in key_timehandler(). */
7221
7222         /*
7223          * We use the number of packets as the unit of
7224          * sadb_lifetime_allocations.  We increment the variable
7225          * whenever {esp,ah}_{in,out}put is called.
7226          */
7227         sav->lft_c->sadb_lifetime_allocations++;
7228         /* XXX check for expires? */
7229
7230         /*
7231          * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7232          * in seconds.  HARD and SOFT lifetime are measured by the time
7233          * difference (again in seconds) from sadb_lifetime_usetime.
7234          *
7235          *      usetime
7236          *      v     expire   expire
7237          * -----+-----+--------+---> t
7238          *      <--------------> HARD
7239          *      <-----> SOFT
7240          */
7241     {
7242         struct timeval tv;
7243         microtime(&tv);
7244         sav->lft_c->sadb_lifetime_usetime = tv.tv_sec;
7245         /* XXX check for expires? */
7246     }
7247
7248         return;
7249 }
7250
7251 /* dumb version */
7252 void
7253 key_sa_routechange(struct sockaddr *dst)
7254 {
7255         struct secashead *sah;
7256         struct route *ro;
7257
7258         LIST_FOREACH(sah, &sahtree, chain) {
7259                 ro = &sah->sa_route;
7260                 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7261                  && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7262                         RTFREE(ro->ro_rt);
7263                         ro->ro_rt = (struct rtentry *)NULL;
7264                 }
7265         }
7266
7267         return;
7268 }
7269
7270 static void
7271 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7272 {
7273         if (sav == NULL)
7274                 panic("key_sa_chgstate called with sav == NULL");
7275
7276         if (sav->state == state)
7277                 return;
7278
7279         if (__LIST_CHAINED(sav))
7280                 LIST_REMOVE(sav, chain);
7281
7282         sav->state = state;
7283         LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7284 }
7285
7286 void
7287 key_sa_stir_iv(struct secasvar *sav)
7288 {
7289
7290         if (!sav->iv)
7291                 panic("key_sa_stir_iv called with sav == NULL");
7292         key_randomfill(sav->iv, sav->ivlen);
7293 }
7294
7295 /* XXX too much? */
7296 static struct mbuf *
7297 key_alloc_mbuf(int l)
7298 {
7299         struct mbuf *m = NULL, *n;
7300         int len, t;
7301
7302         len = l;
7303         while (len > 0) {
7304                 MGET(n, MB_DONTWAIT, MT_DATA);
7305                 if (n && len > MLEN)
7306                         MCLGET(n, MB_DONTWAIT);
7307                 if (!n) {
7308                         m_freem(m);
7309                         return NULL;
7310                 }
7311
7312                 n->m_next = NULL;
7313                 n->m_len = 0;
7314                 n->m_len = M_TRAILINGSPACE(n);
7315                 /* use the bottom of mbuf, hoping we can prepend afterwards */
7316                 if (n->m_len > len) {
7317                         t = (n->m_len - len) & ~(sizeof(long) - 1);
7318                         n->m_data += t;
7319                         n->m_len = len;
7320                 }
7321
7322                 len -= n->m_len;
7323
7324                 if (m)
7325                         m_cat(m, n);
7326                 else
7327                         m = n;
7328         }
7329
7330         return m;
7331 }