source: rtems-libbsd/freebsd/sys/netipsec/key.c @ 66659ff

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 66659ff was 66659ff, checked in by Sebastian Huber <sebastian.huber@…>, on 11/06/13 at 15:20:21

Update to FreeBSD 9.2

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