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  -  FREEBSD10  -  FREEBSD9  -  FREEBSD92  -  FREEBSD91  -  FREEBSD90  -  FREEBSD8  -  FREEBSD82  -  FREEBSD81  -  FREEBSD80  -  FREEBSD7  -  FREEBSD74  -  FREEBSD73  -  FREEBSD72  -  FREEBSD71  -  FREEBSD70  -  FREEBSD6  -  FREEBSD64  -  FREEBSD63  -  FREEBSD62  -  FREEBSD61  -  FREEBSD60  -  FREEBSD5  -  FREEBSD55  -  FREEBSD54  -  FREEBSD53  -  FREEBSD52  -  FREEBSD51  -  FREEBSD50  -  FREEBSD4  -  FREEBSD3  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

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

Cache object: 8d35262cbbd36b2ad3524b84ca2423e2


[ 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.