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