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