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