The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netipsec/key.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: bec8a311bc1087e12f7c6d8b6ca9e809


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.