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


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

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

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

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

Cache object: 8e20ecb72ef6fb9917d73529b061b56a


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