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