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/netkey/key.c

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

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

Cache object: d968891c8b4a7a1b86b33b1001607131


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


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