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

Cache object: 3210a3878b5fa942318ef1eace07034e


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