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