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

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