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