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-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

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