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


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

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

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

    1 /*      $FreeBSD$       */
    2 /*      $KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $ */
    3 
    4 /*-
    5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following conditions
   10  * are met:
   11  * 1. Redistributions of source code must retain the above copyright
   12  *    notice, this list of conditions and the following disclaimer.
   13  * 2. Redistributions in binary form must reproduce the above copyright
   14  *    notice, this list of conditions and the following disclaimer in the
   15  *    documentation and/or other materials provided with the distribution.
   16  * 3. Neither the name of the project nor the names of its contributors
   17  *    may be used to endorse or promote products derived from this software
   18  *    without specific prior written permission.
   19  *
   20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
   21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
   24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   30  * SUCH DAMAGE.
   31  */
   32 
   33 /*
   34  * IPsec controller part.
   35  */
   36 
   37 #include "opt_inet.h"
   38 #include "opt_inet6.h"
   39 #include "opt_ipsec.h"
   40 
   41 #include <sys/param.h>
   42 #include <sys/systm.h>
   43 #include <sys/malloc.h>
   44 #include <sys/mbuf.h>
   45 #include <sys/domain.h>
   46 #include <sys/protosw.h>
   47 #include <sys/socket.h>
   48 #include <sys/socketvar.h>
   49 #include <sys/errno.h>
   50 #include <sys/time.h>
   51 #include <sys/kernel.h>
   52 #include <sys/syslog.h>
   53 #include <sys/sysctl.h>
   54 #include <sys/proc.h>
   55 
   56 #include <net/if.h>
   57 #include <net/route.h>
   58 
   59 #include <netinet/in.h>
   60 #include <netinet/in_systm.h>
   61 #include <netinet/ip.h>
   62 #include <netinet/ip_var.h>
   63 #include <netinet/in_var.h>
   64 #include <netinet/udp.h>
   65 #include <netinet/udp_var.h>
   66 #include <netinet/tcp.h>
   67 #include <netinet/udp.h>
   68 
   69 #include <netinet/ip6.h>
   70 #ifdef INET6
   71 #include <netinet6/ip6_var.h>
   72 #endif
   73 #include <netinet/in_pcb.h>
   74 #ifdef INET6
   75 #include <netinet/icmp6.h>
   76 #endif
   77 
   78 #include <netipsec/ipsec.h>
   79 #ifdef INET6
   80 #include <netipsec/ipsec6.h>
   81 #endif
   82 #include <netipsec/ah_var.h>
   83 #include <netipsec/esp_var.h>
   84 #include <netipsec/ipcomp.h>            /*XXX*/
   85 #include <netipsec/ipcomp_var.h>
   86 
   87 #include <netipsec/key.h>
   88 #include <netipsec/keydb.h>
   89 #include <netipsec/key_debug.h>
   90 
   91 #include <netipsec/xform.h>
   92 
   93 #include <machine/in_cksum.h>
   94 
   95 #ifdef IPSEC_DEBUG
   96 int ipsec_debug = 1;
   97 #else
   98 int ipsec_debug = 0;
   99 #endif
  100 
  101 /* NB: name changed so netstat doesn't use it */
  102 struct newipsecstat newipsecstat;
  103 int ip4_ah_offsetmask = 0;      /* maybe IP_DF? */
  104 int ip4_ipsec_dfbit = 0;        /* DF bit on encap. 0: clear 1: set 2: copy */
  105 int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
  106 int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
  107 int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
  108 int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
  109 struct secpolicy ip4_def_policy;
  110 int ip4_ipsec_ecn = 0;          /* ECN ignore(-1)/forbidden(0)/allowed(1) */
  111 int ip4_esp_randpad = -1;
  112 /*
  113  * Crypto support requirements:
  114  *
  115  *  1   require hardware support
  116  * -1   require software support
  117  *  0   take anything
  118  */
  119 int     crypto_support = 0;
  120 
  121 SYSCTL_DECL(_net_inet_ipsec);
  122 
  123 /* net.inet.ipsec */
  124 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY,
  125         def_policy, CTLFLAG_RW, &ip4_def_policy.policy, 0, "");
  126 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
  127         CTLFLAG_RW, &ip4_esp_trans_deflev,      0, "");
  128 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
  129         CTLFLAG_RW, &ip4_esp_net_deflev,        0, "");
  130 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
  131         CTLFLAG_RW, &ip4_ah_trans_deflev,       0, "");
  132 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
  133         CTLFLAG_RW, &ip4_ah_net_deflev, 0, "");
  134 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS,
  135         ah_cleartos, CTLFLAG_RW,        &ah_cleartos,   0, "");
  136 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK,
  137         ah_offsetmask, CTLFLAG_RW,      &ip4_ah_offsetmask,     0, "");
  138 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT,
  139         dfbit, CTLFLAG_RW,      &ip4_ipsec_dfbit,       0, "");
  140 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN,
  141         ecn, CTLFLAG_RW,        &ip4_ipsec_ecn, 0, "");
  142 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG,
  143         debug, CTLFLAG_RW,      &ipsec_debug,   0, "");
  144 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
  145         esp_randpad, CTLFLAG_RW,        &ip4_esp_randpad,       0, "");
  146 SYSCTL_INT(_net_inet_ipsec, OID_AUTO,
  147         crypto_support, CTLFLAG_RW,     &crypto_support,0, "");
  148 SYSCTL_STRUCT(_net_inet_ipsec, OID_AUTO,
  149         ipsecstats,     CTLFLAG_RD,     &newipsecstat,  newipsecstat, "");
  150 
  151 #ifdef INET6
  152 int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
  153 int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
  154 int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
  155 int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
  156 int ip6_ipsec_ecn = 0;          /* ECN ignore(-1)/forbidden(0)/allowed(1) */
  157 int ip6_esp_randpad = -1;
  158 
  159 SYSCTL_DECL(_net_inet6_ipsec6);
  160 
  161 /* net.inet6.ipsec6 */
  162 #ifdef COMPAT_KAME
  163 SYSCTL_OID(_net_inet6_ipsec6, IPSECCTL_STATS, stats, CTLFLAG_RD,
  164         0,0, compat_ipsecstats_sysctl, "S", "");
  165 #endif /* COMPAT_KAME */
  166 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY,
  167         def_policy, CTLFLAG_RW, &ip4_def_policy.policy, 0, "");
  168 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
  169         CTLFLAG_RW, &ip6_esp_trans_deflev,      0, "");
  170 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
  171         CTLFLAG_RW, &ip6_esp_net_deflev,        0, "");
  172 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
  173         CTLFLAG_RW, &ip6_ah_trans_deflev,       0, "");
  174 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
  175         CTLFLAG_RW, &ip6_ah_net_deflev, 0, "");
  176 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
  177         ecn, CTLFLAG_RW,        &ip6_ipsec_ecn, 0, "");
  178 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG,
  179         debug, CTLFLAG_RW,      &ipsec_debug,   0, "");
  180 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
  181         esp_randpad, CTLFLAG_RW,        &ip6_esp_randpad,       0, "");
  182 #endif /* INET6 */
  183 
  184 static int ipsec4_setspidx_inpcb __P((struct mbuf *, struct inpcb *pcb));
  185 #ifdef INET6
  186 static int ipsec6_setspidx_in6pcb __P((struct mbuf *, struct in6pcb *pcb));
  187 #endif
  188 static int ipsec_setspidx __P((struct mbuf *, struct secpolicyindex *, int));
  189 static void ipsec4_get_ulp __P((struct mbuf *m, struct secpolicyindex *, int));
  190 static int ipsec4_setspidx_ipaddr __P((struct mbuf *, struct secpolicyindex *));
  191 #ifdef INET6
  192 static void ipsec6_get_ulp __P((struct mbuf *m, struct secpolicyindex *, int));
  193 static int ipsec6_setspidx_ipaddr __P((struct mbuf *, struct secpolicyindex *));
  194 #endif
  195 static void ipsec_delpcbpolicy __P((struct inpcbpolicy *));
  196 static struct secpolicy *ipsec_deepcopy_policy __P((struct secpolicy *src));
  197 static int ipsec_set_policy __P((struct secpolicy **pcb_sp,
  198         int optname, caddr_t request, size_t len, int priv));
  199 static int ipsec_get_policy __P((struct secpolicy *pcb_sp, struct mbuf **mp));
  200 static void vshiftl __P((unsigned char *, int, int));
  201 static size_t ipsec_hdrsiz __P((struct secpolicy *));
  202 
  203 MALLOC_DEFINE(M_IPSEC_INPCB, "inpcbpolicy", "inpcb-resident ipsec policy");
  204 
  205 /*
  206  * Return a held reference to the default SP.
  207  */
  208 static struct secpolicy *
  209 key_allocsp_default(const char* where, int tag)
  210 {
  211         struct secpolicy *sp;
  212 
  213         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  214                 printf("DP key_allocsp_default from %s:%u\n", where, tag));
  215 
  216         sp = &ip4_def_policy;
  217         if (sp->policy != IPSEC_POLICY_DISCARD &&
  218             sp->policy != IPSEC_POLICY_NONE) {
  219                 ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
  220                     sp->policy, IPSEC_POLICY_NONE));
  221                 sp->policy = IPSEC_POLICY_NONE;
  222         }
  223         key_addref(sp);
  224 
  225         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  226                 printf("DP key_allocsp_default returns SP:%p (%u)\n",
  227                         sp, sp->refcnt));
  228         return sp;
  229 }
  230 #define KEY_ALLOCSP_DEFAULT() \
  231         key_allocsp_default(__FILE__, __LINE__)
  232 
  233 /*
  234  * For OUTBOUND packet having a socket. Searching SPD for packet,
  235  * and return a pointer to SP.
  236  * OUT: NULL:   no apropreate SP found, the following value is set to error.
  237  *              0       : bypass
  238  *              EACCES  : discard packet.
  239  *              ENOENT  : ipsec_acquire() in progress, maybe.
  240  *              others  : error occured.
  241  *      others: a pointer to SP
  242  *
  243  * NOTE: IPv6 mapped adddress concern is implemented here.
  244  */
  245 struct secpolicy *
  246 ipsec_getpolicy(struct tdb_ident *tdbi, u_int dir)
  247 {
  248         struct secpolicy *sp;
  249 
  250         IPSEC_ASSERT(tdbi != NULL, ("null tdbi"));
  251         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  252                 ("invalid direction %u", dir));
  253 
  254         sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
  255         if (sp == NULL)                 /*XXX????*/
  256                 sp = KEY_ALLOCSP_DEFAULT();
  257         IPSEC_ASSERT(sp != NULL, ("null SP"));
  258         return sp;
  259 }
  260 
  261 /*
  262  * For OUTBOUND packet having a socket. Searching SPD for packet,
  263  * and return a pointer to SP.
  264  * OUT: NULL:   no apropreate SP found, the following value is set to error.
  265  *              0       : bypass
  266  *              EACCES  : discard packet.
  267  *              ENOENT  : ipsec_acquire() in progress, maybe.
  268  *              others  : error occured.
  269  *      others: a pointer to SP
  270  *
  271  * NOTE: IPv6 mapped adddress concern is implemented here.
  272  */
  273 struct secpolicy *
  274 ipsec_getpolicybysock(m, dir, inp, error)
  275         struct mbuf *m;
  276         u_int dir;
  277         struct inpcb *inp;
  278         int *error;
  279 {
  280         struct inpcbpolicy *pcbsp = NULL;
  281         struct secpolicy *currsp = NULL;        /* policy on socket */
  282         struct secpolicy *sp;
  283 
  284         IPSEC_ASSERT(m != NULL, ("null mbuf"));
  285         IPSEC_ASSERT(inp != NULL, ("null inpcb"));
  286         IPSEC_ASSERT(error != NULL, ("null error"));
  287         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  288                 ("invalid direction %u", dir));
  289 
  290         /* set spidx in pcb */
  291         if (inp->inp_vflag & INP_IPV6PROTO) {
  292 #ifdef INET6
  293                 *error = ipsec6_setspidx_in6pcb(m, inp);
  294                 pcbsp = inp->in6p_sp;
  295 #else
  296                 *error = EINVAL;                /* should not happen */
  297 #endif
  298         } else {
  299                 *error = ipsec4_setspidx_inpcb(m, inp);
  300                 pcbsp = inp->inp_sp;
  301         }
  302         if (*error)
  303                 return NULL;
  304 
  305         IPSEC_ASSERT(pcbsp != NULL, ("null pcbsp"));
  306         switch (dir) {
  307         case IPSEC_DIR_INBOUND:
  308                 currsp = pcbsp->sp_in;
  309                 break;
  310         case IPSEC_DIR_OUTBOUND:
  311                 currsp = pcbsp->sp_out;
  312                 break;
  313         }
  314         IPSEC_ASSERT(currsp != NULL, ("null currsp"));
  315 
  316         if (pcbsp->priv) {                      /* when privilieged socket */
  317                 switch (currsp->policy) {
  318                 case IPSEC_POLICY_BYPASS:
  319                 case IPSEC_POLICY_IPSEC:
  320                         key_addref(currsp);
  321                         sp = currsp;
  322                         break;
  323 
  324                 case IPSEC_POLICY_ENTRUST:
  325                         /* look for a policy in SPD */
  326                         sp = KEY_ALLOCSP(&currsp->spidx, dir);
  327                         if (sp == NULL)         /* no SP found */
  328                                 sp = KEY_ALLOCSP_DEFAULT();
  329                         break;
  330 
  331                 default:
  332                         ipseclog((LOG_ERR, "%s: Invalid policy for PCB %d\n",
  333                                 __func__, currsp->policy));
  334                         *error = EINVAL;
  335                         return NULL;
  336                 }
  337         } else {                                /* unpriv, SPD has policy */
  338                 sp = KEY_ALLOCSP(&currsp->spidx, dir);
  339                 if (sp == NULL) {               /* no SP found */
  340                         switch (currsp->policy) {
  341                         case IPSEC_POLICY_BYPASS:
  342                                 ipseclog((LOG_ERR, "%s: Illegal policy for "
  343                                         "non-priviliged defined %d\n",
  344                                         __func__, currsp->policy));
  345                                 *error = EINVAL;
  346                                 return NULL;
  347 
  348                         case IPSEC_POLICY_ENTRUST:
  349                                 sp = KEY_ALLOCSP_DEFAULT();
  350                                 break;
  351 
  352                         case IPSEC_POLICY_IPSEC:
  353                                 key_addref(currsp);
  354                                 sp = currsp;
  355                                 break;
  356 
  357                         default:
  358                                 ipseclog((LOG_ERR, "%s: Invalid policy for "
  359                                         "PCB %d\n", __func__, currsp->policy));
  360                                 *error = EINVAL;
  361                                 return NULL;
  362                         }
  363                 }
  364         }
  365         IPSEC_ASSERT(sp != NULL,
  366                 ("null SP (priv %u policy %u", pcbsp->priv, currsp->policy));
  367         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  368                 printf("DP %s (priv %u policy %u) allocate SP:%p (refcnt %u)\n",
  369                         __func__, pcbsp->priv, currsp->policy, sp, sp->refcnt));
  370         return sp;
  371 }
  372 
  373 /*
  374  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
  375  * and return a pointer to SP.
  376  * OUT: positive: a pointer to the entry for security policy leaf matched.
  377  *      NULL:   no apropreate SP found, the following value is set to error.
  378  *              0       : bypass
  379  *              EACCES  : discard packet.
  380  *              ENOENT  : ipsec_acquire() in progress, maybe.
  381  *              others  : error occured.
  382  */
  383 struct secpolicy *
  384 ipsec_getpolicybyaddr(m, dir, flag, error)
  385         struct mbuf *m;
  386         u_int dir;
  387         int flag;
  388         int *error;
  389 {
  390         struct secpolicyindex spidx;
  391         struct secpolicy *sp;
  392 
  393         IPSEC_ASSERT(m != NULL, ("null mbuf"));
  394         IPSEC_ASSERT(error != NULL, ("null error"));
  395         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  396                 ("invalid direction %u", dir));
  397 
  398         sp = NULL;
  399         if (key_havesp(dir)) {
  400                 /* Make an index to look for a policy. */
  401                 *error = ipsec_setspidx(m, &spidx,
  402                                         (flag & IP_FORWARDING) ? 0 : 1);
  403                 if (*error != 0) {
  404                         DPRINTF(("%s: setpidx failed, dir %u flag %u\n",
  405                                 __func__, dir, flag));
  406                         return NULL;
  407                 }
  408                 spidx.dir = dir;
  409 
  410                 sp = KEY_ALLOCSP(&spidx, dir);
  411         }
  412         if (sp == NULL)                 /* no SP found, use system default */
  413                 sp = KEY_ALLOCSP_DEFAULT();
  414         IPSEC_ASSERT(sp != NULL, ("null SP"));
  415         return sp;
  416 }
  417 
  418 struct secpolicy *
  419 ipsec4_checkpolicy(m, dir, flag, error, inp)
  420         struct mbuf *m;
  421         u_int dir, flag;
  422         int *error;
  423         struct inpcb *inp;
  424 {
  425         struct secpolicy *sp;
  426 
  427         *error = 0;
  428         if (inp == NULL)
  429                 sp = ipsec_getpolicybyaddr(m, dir, flag, error);
  430         else
  431                 sp = ipsec_getpolicybysock(m, dir, inp, error);
  432         if (sp == NULL) {
  433                 IPSEC_ASSERT(*error != 0, ("getpolicy failed w/o error"));
  434                 newipsecstat.ips_out_inval++;
  435                 return NULL;
  436         }
  437         IPSEC_ASSERT(*error == 0, ("sp w/ error set to %u", *error));
  438         switch (sp->policy) {
  439         case IPSEC_POLICY_ENTRUST:
  440         default:
  441                 printf("%s: invalid policy %u\n", __func__, sp->policy);
  442                 /* fall thru... */
  443         case IPSEC_POLICY_DISCARD:
  444                 newipsecstat.ips_out_polvio++;
  445                 *error = -EINVAL;       /* packet is discarded by caller */
  446                 break;
  447         case IPSEC_POLICY_BYPASS:
  448         case IPSEC_POLICY_NONE:
  449                 KEY_FREESP(&sp);
  450                 sp = NULL;              /* NB: force NULL result */
  451                 break;
  452         case IPSEC_POLICY_IPSEC:
  453                 if (sp->req == NULL)    /* acquire an SA */
  454                         *error = key_spdacquire(sp);
  455                 break;
  456         }
  457         if (*error != 0) {
  458                 KEY_FREESP(&sp);
  459                 sp = NULL;
  460         }
  461         return sp;
  462 }
  463 
  464 static int
  465 ipsec4_setspidx_inpcb(m, pcb)
  466         struct mbuf *m;
  467         struct inpcb *pcb;
  468 {
  469         int error;
  470 
  471         IPSEC_ASSERT(pcb != NULL, ("null pcb"));
  472         IPSEC_ASSERT(pcb->inp_sp != NULL, ("null inp_sp"));
  473         IPSEC_ASSERT(pcb->inp_sp->sp_out != NULL && pcb->inp_sp->sp_in != NULL,
  474                 ("null sp_in || sp_out"));
  475 
  476         error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
  477         if (error == 0) {
  478                 pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
  479                 pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
  480                 pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
  481         } else {
  482                 bzero(&pcb->inp_sp->sp_in->spidx,
  483                         sizeof (pcb->inp_sp->sp_in->spidx));
  484                 bzero(&pcb->inp_sp->sp_out->spidx,
  485                         sizeof (pcb->inp_sp->sp_in->spidx));
  486         }
  487         return error;
  488 }
  489 
  490 #ifdef INET6
  491 static int
  492 ipsec6_setspidx_in6pcb(m, pcb)
  493         struct mbuf *m;
  494         struct in6pcb *pcb;
  495 {
  496         struct secpolicyindex *spidx;
  497         int error;
  498 
  499         IPSEC_ASSERT(pcb != NULL, ("null pcb"));
  500         IPSEC_ASSERT(pcb->in6p_sp != NULL, ("null inp_sp"));
  501         IPSEC_ASSERT(pcb->in6p_sp->sp_out != NULL && pcb->in6p_sp->sp_in != NULL,
  502                 ("null sp_in || sp_out"));
  503 
  504         bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
  505         bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
  506 
  507         spidx = &pcb->in6p_sp->sp_in->spidx;
  508         error = ipsec_setspidx(m, spidx, 1);
  509         if (error)
  510                 goto bad;
  511         spidx->dir = IPSEC_DIR_INBOUND;
  512 
  513         spidx = &pcb->in6p_sp->sp_out->spidx;
  514         error = ipsec_setspidx(m, spidx, 1);
  515         if (error)
  516                 goto bad;
  517         spidx->dir = IPSEC_DIR_OUTBOUND;
  518 
  519         return 0;
  520 
  521 bad:
  522         bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
  523         bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
  524         return error;
  525 }
  526 #endif
  527 
  528 /*
  529  * configure security policy index (src/dst/proto/sport/dport)
  530  * by looking at the content of mbuf.
  531  * the caller is responsible for error recovery (like clearing up spidx).
  532  */
  533 static int
  534 ipsec_setspidx(m, spidx, needport)
  535         struct mbuf *m;
  536         struct secpolicyindex *spidx;
  537         int needport;
  538 {
  539         struct ip *ip = NULL;
  540         struct ip ipbuf;
  541         u_int v;
  542         struct mbuf *n;
  543         int len;
  544         int error;
  545 
  546         IPSEC_ASSERT(m != NULL, ("null mbuf"));
  547 
  548         /*
  549          * validate m->m_pkthdr.len.  we see incorrect length if we
  550          * mistakenly call this function with inconsistent mbuf chain
  551          * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
  552          */
  553         len = 0;
  554         for (n = m; n; n = n->m_next)
  555                 len += n->m_len;
  556         if (m->m_pkthdr.len != len) {
  557                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  558                         printf("%s: pkthdr len(%d) mismatch (%d), ignored.\n",
  559                                 __func__, len, m->m_pkthdr.len));
  560                 return EINVAL;
  561         }
  562 
  563         if (m->m_pkthdr.len < sizeof(struct ip)) {
  564                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  565                         printf("%s: pkthdr len(%d) too small (v4), ignored.\n",
  566                             __func__, m->m_pkthdr.len));
  567                 return EINVAL;
  568         }
  569 
  570         if (m->m_len >= sizeof(*ip))
  571                 ip = mtod(m, struct ip *);
  572         else {
  573                 m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
  574                 ip = &ipbuf;
  575         }
  576 #ifdef _IP_VHL
  577         v = _IP_VHL_V(ip->ip_vhl);
  578 #else
  579         v = ip->ip_v;
  580 #endif
  581         switch (v) {
  582         case 4:
  583                 error = ipsec4_setspidx_ipaddr(m, spidx);
  584                 if (error)
  585                         return error;
  586                 ipsec4_get_ulp(m, spidx, needport);
  587                 return 0;
  588 #ifdef INET6
  589         case 6:
  590                 if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
  591                         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  592                                 printf("%s: pkthdr len(%d) too small (v6), "
  593                                 "ignored\n", __func__, m->m_pkthdr.len));
  594                         return EINVAL;
  595                 }
  596                 error = ipsec6_setspidx_ipaddr(m, spidx);
  597                 if (error)
  598                         return error;
  599                 ipsec6_get_ulp(m, spidx, needport);
  600                 return 0;
  601 #endif
  602         default:
  603                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  604                         printf("%s: " "unknown IP version %u, ignored.\n",
  605                                 __func__, v));
  606                 return EINVAL;
  607         }
  608 }
  609 
  610 static void
  611 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
  612 {
  613         u_int8_t nxt;
  614         int off;
  615 
  616         /* sanity check */
  617         IPSEC_ASSERT(m != NULL, ("null mbuf"));
  618         IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),("packet too short"));
  619 
  620         /* NB: ip_input() flips it into host endian XXX need more checking */
  621         if (m->m_len < sizeof (struct ip)) {
  622                 struct ip *ip = mtod(m, struct ip *);
  623                 if (ip->ip_off & (IP_MF | IP_OFFMASK))
  624                         goto done;
  625 #ifdef _IP_VHL
  626                 off = _IP_VHL_HL(ip->ip_vhl) << 2;
  627 #else
  628                 off = ip->ip_hl << 2;
  629 #endif
  630                 nxt = ip->ip_p;
  631         } else {
  632                 struct ip ih;
  633 
  634                 m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
  635                 if (ih.ip_off & (IP_MF | IP_OFFMASK))
  636                         goto done;
  637 #ifdef _IP_VHL
  638                 off = _IP_VHL_HL(ih.ip_vhl) << 2;
  639 #else
  640                 off = ih.ip_hl << 2;
  641 #endif
  642                 nxt = ih.ip_p;
  643         }
  644 
  645         while (off < m->m_pkthdr.len) {
  646                 struct ip6_ext ip6e;
  647                 struct tcphdr th;
  648                 struct udphdr uh;
  649 
  650                 switch (nxt) {
  651                 case IPPROTO_TCP:
  652                         spidx->ul_proto = nxt;
  653                         if (!needport)
  654                                 goto done_proto;
  655                         if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
  656                                 goto done;
  657                         m_copydata(m, off, sizeof (th), (caddr_t) &th);
  658                         spidx->src.sin.sin_port = th.th_sport;
  659                         spidx->dst.sin.sin_port = th.th_dport;
  660                         return;
  661                 case IPPROTO_UDP:
  662                         spidx->ul_proto = nxt;
  663                         if (!needport)
  664                                 goto done_proto;
  665                         if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
  666                                 goto done;
  667                         m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
  668                         spidx->src.sin.sin_port = uh.uh_sport;
  669                         spidx->dst.sin.sin_port = uh.uh_dport;
  670                         return;
  671                 case IPPROTO_AH:
  672                         if (off + sizeof(ip6e) > m->m_pkthdr.len)
  673                                 goto done;
  674                         /* XXX sigh, this works but is totally bogus */
  675                         m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
  676                         off += (ip6e.ip6e_len + 2) << 2;
  677                         nxt = ip6e.ip6e_nxt;
  678                         break;
  679                 case IPPROTO_ICMP:
  680                 default:
  681                         /* XXX intermediate headers??? */
  682                         spidx->ul_proto = nxt;
  683                         goto done_proto;
  684                 }
  685         }
  686 done:
  687         spidx->ul_proto = IPSEC_ULPROTO_ANY;
  688 done_proto:
  689         spidx->src.sin.sin_port = IPSEC_PORT_ANY;
  690         spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
  691 }
  692 
  693 /* assumes that m is sane */
  694 static int
  695 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
  696 {
  697         static const struct sockaddr_in template = {
  698                 sizeof (struct sockaddr_in),
  699                 AF_INET,
  700                 0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
  701         };
  702 
  703         spidx->src.sin = template;
  704         spidx->dst.sin = template;
  705 
  706         if (m->m_len < sizeof (struct ip)) {
  707                 m_copydata(m, offsetof(struct ip, ip_src),
  708                            sizeof (struct  in_addr),
  709                            (caddr_t) &spidx->src.sin.sin_addr);
  710                 m_copydata(m, offsetof(struct ip, ip_dst),
  711                            sizeof (struct  in_addr),
  712                            (caddr_t) &spidx->dst.sin.sin_addr);
  713         } else {
  714                 struct ip *ip = mtod(m, struct ip *);
  715                 spidx->src.sin.sin_addr = ip->ip_src;
  716                 spidx->dst.sin.sin_addr = ip->ip_dst;
  717         }
  718 
  719         spidx->prefs = sizeof(struct in_addr) << 3;
  720         spidx->prefd = sizeof(struct in_addr) << 3;
  721 
  722         return 0;
  723 }
  724 
  725 #ifdef INET6
  726 static void
  727 ipsec6_get_ulp(m, spidx, needport)
  728         struct mbuf *m;
  729         struct secpolicyindex *spidx;
  730         int needport;
  731 {
  732         int off, nxt;
  733         struct tcphdr th;
  734         struct udphdr uh;
  735         struct icmp6_hdr ih;
  736 
  737         /* sanity check */
  738         if (m == NULL)
  739                 panic("%s: NULL pointer was passed.\n", __func__);
  740 
  741         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  742                 printf("%s:\n", __func__); kdebug_mbuf(m));
  743 
  744         /* set default */
  745         spidx->ul_proto = IPSEC_ULPROTO_ANY;
  746         ((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
  747         ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
  748 
  749         nxt = -1;
  750         off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
  751         if (off < 0 || m->m_pkthdr.len < off)
  752                 return;
  753 
  754         switch (nxt) {
  755         case IPPROTO_TCP:
  756                 spidx->ul_proto = nxt;
  757                 if (!needport)
  758                         break;
  759                 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
  760                         break;
  761                 m_copydata(m, off, sizeof(th), (caddr_t)&th);
  762                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
  763                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
  764                 break;
  765         case IPPROTO_UDP:
  766                 spidx->ul_proto = nxt;
  767                 if (!needport)
  768                         break;
  769                 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
  770                         break;
  771                 m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
  772                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
  773                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
  774                 break;
  775         case IPPROTO_ICMPV6:
  776                 spidx->ul_proto = nxt;
  777                 if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
  778                         break;
  779                 m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
  780                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port =
  781                     htons((uint16_t)ih.icmp6_type);
  782                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
  783                     htons((uint16_t)ih.icmp6_code);
  784                 break;
  785         default:
  786                 /* XXX intermediate headers??? */
  787                 spidx->ul_proto = nxt;
  788                 break;
  789         }
  790 }
  791 
  792 /* assumes that m is sane */
  793 static int
  794 ipsec6_setspidx_ipaddr(m, spidx)
  795         struct mbuf *m;
  796         struct secpolicyindex *spidx;
  797 {
  798         struct ip6_hdr *ip6 = NULL;
  799         struct ip6_hdr ip6buf;
  800         struct sockaddr_in6 *sin6;
  801 
  802         if (m->m_len >= sizeof(*ip6))
  803                 ip6 = mtod(m, struct ip6_hdr *);
  804         else {
  805                 m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf);
  806                 ip6 = &ip6buf;
  807         }
  808 
  809         sin6 = (struct sockaddr_in6 *)&spidx->src;
  810         bzero(sin6, sizeof(*sin6));
  811         sin6->sin6_family = AF_INET6;
  812         sin6->sin6_len = sizeof(struct sockaddr_in6);
  813         bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src));
  814         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
  815                 sin6->sin6_addr.s6_addr16[1] = 0;
  816                 sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
  817         }
  818         spidx->prefs = sizeof(struct in6_addr) << 3;
  819 
  820         sin6 = (struct sockaddr_in6 *)&spidx->dst;
  821         bzero(sin6, sizeof(*sin6));
  822         sin6->sin6_family = AF_INET6;
  823         sin6->sin6_len = sizeof(struct sockaddr_in6);
  824         bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst));
  825         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
  826                 sin6->sin6_addr.s6_addr16[1] = 0;
  827                 sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
  828         }
  829         spidx->prefd = sizeof(struct in6_addr) << 3;
  830 
  831         return 0;
  832 }
  833 #endif
  834 
  835 static void
  836 ipsec_delpcbpolicy(p)
  837         struct inpcbpolicy *p;
  838 {
  839         free(p, M_IPSEC_INPCB);
  840 }
  841 
  842 /* initialize policy in PCB */
  843 int
  844 ipsec_init_policy(so, pcb_sp)
  845         struct socket *so;
  846         struct inpcbpolicy **pcb_sp;
  847 {
  848         struct inpcbpolicy *new;
  849 
  850         /* sanity check. */
  851         if (so == NULL || pcb_sp == NULL)
  852                 panic("%s: NULL pointer was passed.\n", __func__);
  853 
  854         new = (struct inpcbpolicy *) malloc(sizeof(struct inpcbpolicy),
  855                                             M_IPSEC_INPCB, M_NOWAIT|M_ZERO);
  856         if (new == NULL) {
  857                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
  858                 return ENOBUFS;
  859         }
  860 
  861         new->priv = IPSEC_IS_PRIVILEGED_SO(so);
  862 
  863         if ((new->sp_in = KEY_NEWSP()) == NULL) {
  864                 ipsec_delpcbpolicy(new);
  865                 return ENOBUFS;
  866         }
  867         new->sp_in->state = IPSEC_SPSTATE_ALIVE;
  868         new->sp_in->policy = IPSEC_POLICY_ENTRUST;
  869 
  870         if ((new->sp_out = KEY_NEWSP()) == NULL) {
  871                 KEY_FREESP(&new->sp_in);
  872                 ipsec_delpcbpolicy(new);
  873                 return ENOBUFS;
  874         }
  875         new->sp_out->state = IPSEC_SPSTATE_ALIVE;
  876         new->sp_out->policy = IPSEC_POLICY_ENTRUST;
  877 
  878         *pcb_sp = new;
  879 
  880         return 0;
  881 }
  882 
  883 /* copy old ipsec policy into new */
  884 int
  885 ipsec_copy_policy(old, new)
  886         struct inpcbpolicy *old, *new;
  887 {
  888         struct secpolicy *sp;
  889 
  890         sp = ipsec_deepcopy_policy(old->sp_in);
  891         if (sp) {
  892                 KEY_FREESP(&new->sp_in);
  893                 new->sp_in = sp;
  894         } else
  895                 return ENOBUFS;
  896 
  897         sp = ipsec_deepcopy_policy(old->sp_out);
  898         if (sp) {
  899                 KEY_FREESP(&new->sp_out);
  900                 new->sp_out = sp;
  901         } else
  902                 return ENOBUFS;
  903 
  904         new->priv = old->priv;
  905 
  906         return 0;
  907 }
  908 
  909 struct ipsecrequest *
  910 ipsec_newisr(void)
  911 {
  912         struct ipsecrequest *p;
  913 
  914         p = malloc(sizeof(struct ipsecrequest), M_IPSEC_SR, M_NOWAIT|M_ZERO);
  915         if (p != NULL)
  916                 IPSECREQUEST_LOCK_INIT(p);
  917         return p;
  918 }
  919 
  920 void
  921 ipsec_delisr(struct ipsecrequest *p)
  922 {
  923         IPSECREQUEST_LOCK_DESTROY(p);
  924         free(p, M_IPSEC_SR);
  925 }
  926 
  927 /* deep-copy a policy in PCB */
  928 static struct secpolicy *
  929 ipsec_deepcopy_policy(src)
  930         struct secpolicy *src;
  931 {
  932         struct ipsecrequest *newchain = NULL;
  933         struct ipsecrequest *p;
  934         struct ipsecrequest **q;
  935         struct ipsecrequest *r;
  936         struct secpolicy *dst;
  937 
  938         if (src == NULL)
  939                 return NULL;
  940         dst = KEY_NEWSP();
  941         if (dst == NULL)
  942                 return NULL;
  943 
  944         /*
  945          * deep-copy IPsec request chain.  This is required since struct
  946          * ipsecrequest is not reference counted.
  947          */
  948         q = &newchain;
  949         for (p = src->req; p; p = p->next) {
  950                 *q = ipsec_newisr();
  951                 if (*q == NULL)
  952                         goto fail;
  953                 (*q)->saidx.proto = p->saidx.proto;
  954                 (*q)->saidx.mode = p->saidx.mode;
  955                 (*q)->level = p->level;
  956                 (*q)->saidx.reqid = p->saidx.reqid;
  957 
  958                 bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src));
  959                 bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst));
  960 
  961                 (*q)->sp = dst;
  962 
  963                 q = &((*q)->next);
  964         }
  965 
  966         dst->req = newchain;
  967         dst->state = src->state;
  968         dst->policy = src->policy;
  969         /* do not touch the refcnt fields */
  970 
  971         return dst;
  972 
  973 fail:
  974         for (p = newchain; p; p = r) {
  975                 r = p->next;
  976                 ipsec_delisr(p);
  977                 p = NULL;
  978         }
  979         return NULL;
  980 }
  981 
  982 /* set policy and ipsec request if present. */
  983 static int
  984 ipsec_set_policy(pcb_sp, optname, request, len, priv)
  985         struct secpolicy **pcb_sp;
  986         int optname;
  987         caddr_t request;
  988         size_t len;
  989         int priv;
  990 {
  991         struct sadb_x_policy *xpl;
  992         struct secpolicy *newsp = NULL;
  993         int error;
  994 
  995         /* sanity check. */
  996         if (pcb_sp == NULL || *pcb_sp == NULL || request == NULL)
  997                 return EINVAL;
  998         if (len < sizeof(*xpl))
  999                 return EINVAL;
 1000         xpl = (struct sadb_x_policy *)request;
 1001 
 1002         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1003                 printf("%s: passed policy\n", __func__);
 1004                 kdebug_sadb_x_policy((struct sadb_ext *)xpl));
 1005 
 1006         /* check policy type */
 1007         /* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
 1008         if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
 1009          || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
 1010                 return EINVAL;
 1011 
 1012         /* check privileged socket */
 1013         if (priv == 0 && xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS)
 1014                 return EACCES;
 1015 
 1016         /* allocation new SP entry */
 1017         if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
 1018                 return error;
 1019 
 1020         newsp->state = IPSEC_SPSTATE_ALIVE;
 1021 
 1022         /* clear old SP and set new SP */
 1023         KEY_FREESP(pcb_sp);
 1024         *pcb_sp = newsp;
 1025         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1026                 printf("%s: new policy\n", __func__);
 1027                 kdebug_secpolicy(newsp));
 1028 
 1029         return 0;
 1030 }
 1031 
 1032 static int
 1033 ipsec_get_policy(pcb_sp, mp)
 1034         struct secpolicy *pcb_sp;
 1035         struct mbuf **mp;
 1036 {
 1037 
 1038         /* sanity check. */
 1039         if (pcb_sp == NULL || mp == NULL)
 1040                 return EINVAL;
 1041 
 1042         *mp = key_sp2msg(pcb_sp);
 1043         if (!*mp) {
 1044                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
 1045                 return ENOBUFS;
 1046         }
 1047 
 1048         (*mp)->m_type = MT_DATA;
 1049         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1050                 printf("%s:\n", __func__); kdebug_mbuf(*mp));
 1051 
 1052         return 0;
 1053 }
 1054 
 1055 int
 1056 ipsec4_set_policy(inp, optname, request, len, priv)
 1057         struct inpcb *inp;
 1058         int optname;
 1059         caddr_t request;
 1060         size_t len;
 1061         int priv;
 1062 {
 1063         struct sadb_x_policy *xpl;
 1064         struct secpolicy **pcb_sp;
 1065 
 1066         /* sanity check. */
 1067         if (inp == NULL || request == NULL)
 1068                 return EINVAL;
 1069         if (len < sizeof(*xpl))
 1070                 return EINVAL;
 1071         xpl = (struct sadb_x_policy *)request;
 1072 
 1073         /* select direction */
 1074         switch (xpl->sadb_x_policy_dir) {
 1075         case IPSEC_DIR_INBOUND:
 1076                 pcb_sp = &inp->inp_sp->sp_in;
 1077                 break;
 1078         case IPSEC_DIR_OUTBOUND:
 1079                 pcb_sp = &inp->inp_sp->sp_out;
 1080                 break;
 1081         default:
 1082                 ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
 1083                         xpl->sadb_x_policy_dir));
 1084                 return EINVAL;
 1085         }
 1086 
 1087         return ipsec_set_policy(pcb_sp, optname, request, len, priv);
 1088 }
 1089 
 1090 int
 1091 ipsec4_get_policy(inp, request, len, mp)
 1092         struct inpcb *inp;
 1093         caddr_t request;
 1094         size_t len;
 1095         struct mbuf **mp;
 1096 {
 1097         struct sadb_x_policy *xpl;
 1098         struct secpolicy *pcb_sp;
 1099 
 1100         /* sanity check. */
 1101         if (inp == NULL || request == NULL || mp == NULL)
 1102                 return EINVAL;
 1103         IPSEC_ASSERT(inp->inp_sp != NULL, ("null inp_sp"));
 1104         if (len < sizeof(*xpl))
 1105                 return EINVAL;
 1106         xpl = (struct sadb_x_policy *)request;
 1107 
 1108         /* select direction */
 1109         switch (xpl->sadb_x_policy_dir) {
 1110         case IPSEC_DIR_INBOUND:
 1111                 pcb_sp = inp->inp_sp->sp_in;
 1112                 break;
 1113         case IPSEC_DIR_OUTBOUND:
 1114                 pcb_sp = inp->inp_sp->sp_out;
 1115                 break;
 1116         default:
 1117                 ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
 1118                         xpl->sadb_x_policy_dir));
 1119                 return EINVAL;
 1120         }
 1121 
 1122         return ipsec_get_policy(pcb_sp, mp);
 1123 }
 1124 
 1125 /* delete policy in PCB */
 1126 int
 1127 ipsec4_delete_pcbpolicy(inp)
 1128         struct inpcb *inp;
 1129 {
 1130         IPSEC_ASSERT(inp != NULL, ("null inp"));
 1131 
 1132         if (inp->inp_sp == NULL)
 1133                 return 0;
 1134 
 1135         if (inp->inp_sp->sp_in != NULL)
 1136                 KEY_FREESP(&inp->inp_sp->sp_in);
 1137 
 1138         if (inp->inp_sp->sp_out != NULL)
 1139                 KEY_FREESP(&inp->inp_sp->sp_out);
 1140 
 1141         ipsec_delpcbpolicy(inp->inp_sp);
 1142         inp->inp_sp = NULL;
 1143 
 1144         return 0;
 1145 }
 1146 
 1147 #ifdef INET6
 1148 int
 1149 ipsec6_set_policy(in6p, optname, request, len, priv)
 1150         struct in6pcb *in6p;
 1151         int optname;
 1152         caddr_t request;
 1153         size_t len;
 1154         int priv;
 1155 {
 1156         struct sadb_x_policy *xpl;
 1157         struct secpolicy **pcb_sp;
 1158 
 1159         /* sanity check. */
 1160         if (in6p == NULL || request == NULL)
 1161                 return EINVAL;
 1162         if (len < sizeof(*xpl))
 1163                 return EINVAL;
 1164         xpl = (struct sadb_x_policy *)request;
 1165 
 1166         /* select direction */
 1167         switch (xpl->sadb_x_policy_dir) {
 1168         case IPSEC_DIR_INBOUND:
 1169                 pcb_sp = &in6p->in6p_sp->sp_in;
 1170                 break;
 1171         case IPSEC_DIR_OUTBOUND:
 1172                 pcb_sp = &in6p->in6p_sp->sp_out;
 1173                 break;
 1174         default:
 1175                 ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
 1176                         xpl->sadb_x_policy_dir));
 1177                 return EINVAL;
 1178         }
 1179 
 1180         return ipsec_set_policy(pcb_sp, optname, request, len, priv);
 1181 }
 1182 
 1183 int
 1184 ipsec6_get_policy(in6p, request, len, mp)
 1185         struct in6pcb *in6p;
 1186         caddr_t request;
 1187         size_t len;
 1188         struct mbuf **mp;
 1189 {
 1190         struct sadb_x_policy *xpl;
 1191         struct secpolicy *pcb_sp;
 1192 
 1193         /* sanity check. */
 1194         if (in6p == NULL || request == NULL || mp == NULL)
 1195                 return EINVAL;
 1196         IPSEC_ASSERT(in6p->in6p_sp != NULL, ("null in6p_sp"));
 1197         if (len < sizeof(*xpl))
 1198                 return EINVAL;
 1199         xpl = (struct sadb_x_policy *)request;
 1200 
 1201         /* select direction */
 1202         switch (xpl->sadb_x_policy_dir) {
 1203         case IPSEC_DIR_INBOUND:
 1204                 pcb_sp = in6p->in6p_sp->sp_in;
 1205                 break;
 1206         case IPSEC_DIR_OUTBOUND:
 1207                 pcb_sp = in6p->in6p_sp->sp_out;
 1208                 break;
 1209         default:
 1210                 ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
 1211                         xpl->sadb_x_policy_dir));
 1212                 return EINVAL;
 1213         }
 1214 
 1215         return ipsec_get_policy(pcb_sp, mp);
 1216 }
 1217 
 1218 int
 1219 ipsec6_delete_pcbpolicy(in6p)
 1220         struct in6pcb *in6p;
 1221 {
 1222         IPSEC_ASSERT(in6p != NULL, ("null in6p"));
 1223 
 1224         if (in6p->in6p_sp == NULL)
 1225                 return 0;
 1226 
 1227         if (in6p->in6p_sp->sp_in != NULL)
 1228                 KEY_FREESP(&in6p->in6p_sp->sp_in);
 1229 
 1230         if (in6p->in6p_sp->sp_out != NULL)
 1231                 KEY_FREESP(&in6p->in6p_sp->sp_out);
 1232 
 1233         ipsec_delpcbpolicy(in6p->in6p_sp);
 1234         in6p->in6p_sp = NULL;
 1235 
 1236         return 0;
 1237 }
 1238 #endif
 1239 
 1240 /*
 1241  * return current level.
 1242  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
 1243  */
 1244 u_int
 1245 ipsec_get_reqlevel(isr)
 1246         struct ipsecrequest *isr;
 1247 {
 1248         u_int level = 0;
 1249         u_int esp_trans_deflev, esp_net_deflev;
 1250         u_int ah_trans_deflev, ah_net_deflev;
 1251 
 1252         IPSEC_ASSERT(isr != NULL && isr->sp != NULL, ("null argument"));
 1253         IPSEC_ASSERT(isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
 1254                 ("af family mismatch, src %u, dst %u",
 1255                  isr->sp->spidx.src.sa.sa_family,
 1256                  isr->sp->spidx.dst.sa.sa_family));
 1257 
 1258 /* XXX note that we have ipseclog() expanded here - code sync issue */
 1259 #define IPSEC_CHECK_DEFAULT(lev) \
 1260         (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE            \
 1261                         && (lev) != IPSEC_LEVEL_UNIQUE)                       \
 1262                 ? (ipsec_debug                                                \
 1263                         ? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
 1264                                 (lev), IPSEC_LEVEL_REQUIRE)                   \
 1265                         : 0),                                                 \
 1266                         (lev) = IPSEC_LEVEL_REQUIRE,                          \
 1267                         (lev)                                                 \
 1268                 : (lev))
 1269 
 1270         /* set default level */
 1271         switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
 1272 #ifdef INET
 1273         case AF_INET:
 1274                 esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
 1275                 esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
 1276                 ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
 1277                 ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
 1278                 break;
 1279 #endif
 1280 #ifdef INET6
 1281         case AF_INET6:
 1282                 esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
 1283                 esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
 1284                 ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
 1285                 ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
 1286                 break;
 1287 #endif /* INET6 */
 1288         default:
 1289                 panic("%s: unknown af %u",
 1290                         __func__, isr->sp->spidx.src.sa.sa_family);
 1291         }
 1292 
 1293 #undef IPSEC_CHECK_DEFAULT
 1294 
 1295         /* set level */
 1296         switch (isr->level) {
 1297         case IPSEC_LEVEL_DEFAULT:
 1298                 switch (isr->saidx.proto) {
 1299                 case IPPROTO_ESP:
 1300                         if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
 1301                                 level = esp_net_deflev;
 1302                         else
 1303                                 level = esp_trans_deflev;
 1304                         break;
 1305                 case IPPROTO_AH:
 1306                         if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
 1307                                 level = ah_net_deflev;
 1308                         else
 1309                                 level = ah_trans_deflev;
 1310                         break;
 1311                 case IPPROTO_IPCOMP:
 1312                         /*
 1313                          * we don't really care, as IPcomp document says that
 1314                          * we shouldn't compress small packets
 1315                          */
 1316                         level = IPSEC_LEVEL_USE;
 1317                         break;
 1318                 default:
 1319                         panic("%s: Illegal protocol defined %u\n", __func__,
 1320                                 isr->saidx.proto);
 1321                 }
 1322                 break;
 1323 
 1324         case IPSEC_LEVEL_USE:
 1325         case IPSEC_LEVEL_REQUIRE:
 1326                 level = isr->level;
 1327                 break;
 1328         case IPSEC_LEVEL_UNIQUE:
 1329                 level = IPSEC_LEVEL_REQUIRE;
 1330                 break;
 1331 
 1332         default:
 1333                 panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
 1334         }
 1335 
 1336         return level;
 1337 }
 1338 
 1339 /*
 1340  * Check security policy requirements against the actual
 1341  * packet contents.  Return one if the packet should be
 1342  * reject as "invalid"; otherwiser return zero to have the
 1343  * packet treated as "valid".
 1344  *
 1345  * OUT:
 1346  *      0: valid
 1347  *      1: invalid
 1348  */
 1349 int
 1350 ipsec_in_reject(struct secpolicy *sp, struct mbuf *m)
 1351 {
 1352         struct ipsecrequest *isr;
 1353         int need_auth;
 1354 
 1355         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 1356                 printf("%s: using SP\n", __func__); kdebug_secpolicy(sp));
 1357 
 1358         /* check policy */
 1359         switch (sp->policy) {
 1360         case IPSEC_POLICY_DISCARD:
 1361                 return 1;
 1362         case IPSEC_POLICY_BYPASS:
 1363         case IPSEC_POLICY_NONE:
 1364                 return 0;
 1365         }
 1366 
 1367         IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
 1368                 ("invalid policy %u", sp->policy));
 1369 
 1370         /* XXX should compare policy against ipsec header history */
 1371 
 1372         need_auth = 0;
 1373         for (isr = sp->req; isr != NULL; isr = isr->next) {
 1374                 if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
 1375                         continue;
 1376                 switch (isr->saidx.proto) {
 1377                 case IPPROTO_ESP:
 1378                         if ((m->m_flags & M_DECRYPTED) == 0) {
 1379                                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1380                                     printf("%s: ESP m_flags:%x\n", __func__,
 1381                                             m->m_flags));
 1382                                 return 1;
 1383                         }
 1384 
 1385                         if (!need_auth &&
 1386                             isr->sav != NULL &&
 1387                             isr->sav->tdb_authalgxform != NULL &&
 1388                             (m->m_flags & M_AUTHIPDGM) == 0) {
 1389                                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1390                                     printf("%s: ESP/AH m_flags:%x\n", __func__,
 1391                                             m->m_flags));
 1392                                 return 1;
 1393                         }
 1394                         break;
 1395                 case IPPROTO_AH:
 1396                         need_auth = 1;
 1397                         if ((m->m_flags & M_AUTHIPHDR) == 0) {
 1398                                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1399                                     printf("%s: AH m_flags:%x\n", __func__,
 1400                                             m->m_flags));
 1401                                 return 1;
 1402                         }
 1403                         break;
 1404                 case IPPROTO_IPCOMP:
 1405                         /*
 1406                          * we don't really care, as IPcomp document
 1407                          * says that we shouldn't compress small
 1408                          * packets, IPComp policy should always be
 1409                          * treated as being in "use" level.
 1410                          */
 1411                         break;
 1412                 }
 1413         }
 1414         return 0;               /* valid */
 1415 }
 1416 
 1417 /*
 1418  * Check AH/ESP integrity.
 1419  * This function is called from tcp_input(), udp_input(),
 1420  * and {ah,esp}4_input for tunnel mode
 1421  */
 1422 int
 1423 ipsec4_in_reject(m, inp)
 1424         struct mbuf *m;
 1425         struct inpcb *inp;
 1426 {
 1427         struct secpolicy *sp;
 1428         int error;
 1429         int result;
 1430 
 1431         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 1432 
 1433         /* get SP for this packet.
 1434          * When we are called from ip_forward(), we call
 1435          * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
 1436          */
 1437         if (inp == NULL)
 1438                 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
 1439         else
 1440                 sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
 1441 
 1442         if (sp != NULL) {
 1443                 result = ipsec_in_reject(sp, m);
 1444                 if (result)
 1445                         newipsecstat.ips_in_polvio++;
 1446                 KEY_FREESP(&sp);
 1447         } else {
 1448                 result = 0;     /* XXX should be panic ?
 1449                                  * -> No, there may be error. */
 1450         }
 1451         return result;
 1452 }
 1453 
 1454 #ifdef INET6
 1455 /*
 1456  * Check AH/ESP integrity.
 1457  * This function is called from tcp6_input(), udp6_input(),
 1458  * and {ah,esp}6_input for tunnel mode
 1459  */
 1460 int
 1461 ipsec6_in_reject(m, inp)
 1462         struct mbuf *m;
 1463         struct inpcb *inp;
 1464 {
 1465         struct secpolicy *sp = NULL;
 1466         int error;
 1467         int result;
 1468 
 1469         /* sanity check */
 1470         if (m == NULL)
 1471                 return 0;       /* XXX should be panic ? */
 1472 
 1473         /* get SP for this packet.
 1474          * When we are called from ip_forward(), we call
 1475          * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
 1476          */
 1477         if (inp == NULL)
 1478                 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
 1479         else
 1480                 sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
 1481 
 1482         if (sp != NULL) {
 1483                 result = ipsec_in_reject(sp, m);
 1484                 if (result)
 1485                         newipsecstat.ips_in_polvio++;
 1486                 KEY_FREESP(&sp);
 1487         } else {
 1488                 result = 0;
 1489         }
 1490         return result;
 1491 }
 1492 #endif
 1493 
 1494 /*
 1495  * compute the byte size to be occupied by IPsec header.
 1496  * in case it is tunneled, it includes the size of outer IP header.
 1497  * NOTE: SP passed is free in this function.
 1498  */
 1499 static size_t
 1500 ipsec_hdrsiz(struct secpolicy *sp)
 1501 {
 1502         struct ipsecrequest *isr;
 1503         size_t siz;
 1504 
 1505         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 1506                 printf("%s: using SP\n", __func__); kdebug_secpolicy(sp));
 1507 
 1508         switch (sp->policy) {
 1509         case IPSEC_POLICY_DISCARD:
 1510         case IPSEC_POLICY_BYPASS:
 1511         case IPSEC_POLICY_NONE:
 1512                 return 0;
 1513         }
 1514 
 1515         IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
 1516                 ("invalid policy %u", sp->policy));
 1517 
 1518         siz = 0;
 1519         for (isr = sp->req; isr != NULL; isr = isr->next) {
 1520                 size_t clen = 0;
 1521 
 1522                 switch (isr->saidx.proto) {
 1523                 case IPPROTO_ESP:
 1524                         clen = esp_hdrsiz(isr->sav);
 1525                         break;
 1526                 case IPPROTO_AH:
 1527                         clen = ah_hdrsiz(isr->sav);
 1528                         break;
 1529                 case IPPROTO_IPCOMP:
 1530                         clen = sizeof(struct ipcomp);
 1531                         break;
 1532                 }
 1533 
 1534                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
 1535                         switch (isr->saidx.dst.sa.sa_family) {
 1536                         case AF_INET:
 1537                                 clen += sizeof(struct ip);
 1538                                 break;
 1539 #ifdef INET6
 1540                         case AF_INET6:
 1541                                 clen += sizeof(struct ip6_hdr);
 1542                                 break;
 1543 #endif
 1544                         default:
 1545                                 ipseclog((LOG_ERR, "%s: unknown AF %d in "
 1546                                     "IPsec tunnel SA\n", __func__,
 1547                                     ((struct sockaddr *)&isr->saidx.dst)->sa_family));
 1548                                 break;
 1549                         }
 1550                 }
 1551                 siz += clen;
 1552         }
 1553 
 1554         return siz;
 1555 }
 1556 
 1557 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
 1558 size_t
 1559 ipsec4_hdrsiz(m, dir, inp)
 1560         struct mbuf *m;
 1561         u_int dir;
 1562         struct inpcb *inp;
 1563 {
 1564         struct secpolicy *sp;
 1565         int error;
 1566         size_t size;
 1567 
 1568         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 1569 
 1570         /* get SP for this packet.
 1571          * When we are called from ip_forward(), we call
 1572          * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
 1573          */
 1574         if (inp == NULL)
 1575                 sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
 1576         else
 1577                 sp = ipsec_getpolicybysock(m, dir, inp, &error);
 1578 
 1579         if (sp != NULL) {
 1580                 size = ipsec_hdrsiz(sp);
 1581                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 1582                         printf("%s: size:%lu.\n", __func__,
 1583                                 (unsigned long)size));
 1584 
 1585                 KEY_FREESP(&sp);
 1586         } else {
 1587                 size = 0;       /* XXX should be panic ? */
 1588         }
 1589         return size;
 1590 }
 1591 
 1592 #ifdef INET6
 1593 /* This function is called from ipsec6_hdrsize_tcp(),
 1594  * and maybe from ip6_forward.()
 1595  */
 1596 size_t
 1597 ipsec6_hdrsiz(m, dir, in6p)
 1598         struct mbuf *m;
 1599         u_int dir;
 1600         struct in6pcb *in6p;
 1601 {
 1602         struct secpolicy *sp;
 1603         int error;
 1604         size_t size;
 1605 
 1606         IPSEC_ASSERT(m != NULL, ("null mbuf"));
 1607         IPSEC_ASSERT(in6p == NULL || in6p->in6p_socket != NULL,
 1608                 ("socket w/o inpcb"));
 1609 
 1610         /* get SP for this packet */
 1611         /* XXX Is it right to call with IP_FORWARDING. */
 1612         if (in6p == NULL)
 1613                 sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
 1614         else
 1615                 sp = ipsec_getpolicybysock(m, dir, in6p, &error);
 1616 
 1617         if (sp == NULL)
 1618                 return 0;
 1619         size = ipsec_hdrsiz(sp);
 1620         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 1621                 printf("%s: size:%lu.\n", __func__, (unsigned long)size));
 1622         KEY_FREESP(&sp);
 1623 
 1624         return size;
 1625 }
 1626 #endif /*INET6*/
 1627 
 1628 /*
 1629  * Check the variable replay window.
 1630  * ipsec_chkreplay() performs replay check before ICV verification.
 1631  * ipsec_updatereplay() updates replay bitmap.  This must be called after
 1632  * ICV verification (it also performs replay check, which is usually done
 1633  * beforehand).
 1634  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
 1635  *
 1636  * based on RFC 2401.
 1637  */
 1638 int
 1639 ipsec_chkreplay(seq, sav)
 1640         u_int32_t seq;
 1641         struct secasvar *sav;
 1642 {
 1643         const struct secreplay *replay;
 1644         u_int32_t diff;
 1645         int fr;
 1646         u_int32_t wsizeb;       /* constant: bits of window size */
 1647         int frlast;             /* constant: last frame */
 1648 
 1649         IPSEC_SPLASSERT_SOFTNET(__func__);
 1650 
 1651         IPSEC_ASSERT(sav != NULL, ("Null SA"));
 1652         IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
 1653 
 1654         replay = sav->replay;
 1655 
 1656         if (replay->wsize == 0)
 1657                 return 1;       /* no need to check replay. */
 1658 
 1659         /* constant */
 1660         frlast = replay->wsize - 1;
 1661         wsizeb = replay->wsize << 3;
 1662 
 1663         /* sequence number of 0 is invalid */
 1664         if (seq == 0)
 1665                 return 0;
 1666 
 1667         /* first time is always okay */
 1668         if (replay->count == 0)
 1669                 return 1;
 1670 
 1671         if (seq > replay->lastseq) {
 1672                 /* larger sequences are okay */
 1673                 return 1;
 1674         } else {
 1675                 /* seq is equal or less than lastseq. */
 1676                 diff = replay->lastseq - seq;
 1677 
 1678                 /* over range to check, i.e. too old or wrapped */
 1679                 if (diff >= wsizeb)
 1680                         return 0;
 1681 
 1682                 fr = frlast - diff / 8;
 1683 
 1684                 /* this packet already seen ? */
 1685                 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
 1686                         return 0;
 1687 
 1688                 /* out of order but good */
 1689                 return 1;
 1690         }
 1691 }
 1692 
 1693 /*
 1694  * check replay counter whether to update or not.
 1695  * OUT: 0:      OK
 1696  *      1:      NG
 1697  */
 1698 int
 1699 ipsec_updatereplay(seq, sav)
 1700         u_int32_t seq;
 1701         struct secasvar *sav;
 1702 {
 1703         struct secreplay *replay;
 1704         u_int32_t diff;
 1705         int fr;
 1706         u_int32_t wsizeb;       /* constant: bits of window size */
 1707         int frlast;             /* constant: last frame */
 1708 
 1709         IPSEC_SPLASSERT_SOFTNET(__func__);
 1710 
 1711         IPSEC_ASSERT(sav != NULL, ("Null SA"));
 1712         IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
 1713 
 1714         replay = sav->replay;
 1715 
 1716         if (replay->wsize == 0)
 1717                 goto ok;        /* no need to check replay. */
 1718 
 1719         /* constant */
 1720         frlast = replay->wsize - 1;
 1721         wsizeb = replay->wsize << 3;
 1722 
 1723         /* sequence number of 0 is invalid */
 1724         if (seq == 0)
 1725                 return 1;
 1726 
 1727         /* first time */
 1728         if (replay->count == 0) {
 1729                 replay->lastseq = seq;
 1730                 bzero(replay->bitmap, replay->wsize);
 1731                 (replay->bitmap)[frlast] = 1;
 1732                 goto ok;
 1733         }
 1734 
 1735         if (seq > replay->lastseq) {
 1736                 /* seq is larger than lastseq. */
 1737                 diff = seq - replay->lastseq;
 1738 
 1739                 /* new larger sequence number */
 1740                 if (diff < wsizeb) {
 1741                         /* In window */
 1742                         /* set bit for this packet */
 1743                         vshiftl(replay->bitmap, diff, replay->wsize);
 1744                         (replay->bitmap)[frlast] |= 1;
 1745                 } else {
 1746                         /* this packet has a "way larger" */
 1747                         bzero(replay->bitmap, replay->wsize);
 1748                         (replay->bitmap)[frlast] = 1;
 1749                 }
 1750                 replay->lastseq = seq;
 1751 
 1752                 /* larger is good */
 1753         } else {
 1754                 /* seq is equal or less than lastseq. */
 1755                 diff = replay->lastseq - seq;
 1756 
 1757                 /* over range to check, i.e. too old or wrapped */
 1758                 if (diff >= wsizeb)
 1759                         return 1;
 1760 
 1761                 fr = frlast - diff / 8;
 1762 
 1763                 /* this packet already seen ? */
 1764                 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
 1765                         return 1;
 1766 
 1767                 /* mark as seen */
 1768                 (replay->bitmap)[fr] |= (1 << (diff % 8));
 1769 
 1770                 /* out of order but good */
 1771         }
 1772 
 1773 ok:
 1774         if (replay->count == ~0) {
 1775 
 1776                 /* set overflow flag */
 1777                 replay->overflow++;
 1778 
 1779                 /* don't increment, no more packets accepted */
 1780                 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
 1781                         return 1;
 1782 
 1783                 ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
 1784                     __func__, replay->overflow, ipsec_logsastr(sav)));
 1785         }
 1786 
 1787         replay->count++;
 1788 
 1789         return 0;
 1790 }
 1791 
 1792 /*
 1793  * shift variable length buffer to left.
 1794  * IN:  bitmap: pointer to the buffer
 1795  *      nbit:   the number of to shift.
 1796  *      wsize:  buffer size (bytes).
 1797  */
 1798 static void
 1799 vshiftl(bitmap, nbit, wsize)
 1800         unsigned char *bitmap;
 1801         int nbit, wsize;
 1802 {
 1803         int s, j, i;
 1804         unsigned char over;
 1805 
 1806         for (j = 0; j < nbit; j += 8) {
 1807                 s = (nbit - j < 8) ? (nbit - j): 8;
 1808                 bitmap[0] <<= s;
 1809                 for (i = 1; i < wsize; i++) {
 1810                         over = (bitmap[i] >> (8 - s));
 1811                         bitmap[i] <<= s;
 1812                         bitmap[i-1] |= over;
 1813                 }
 1814         }
 1815 
 1816         return;
 1817 }
 1818 
 1819 /* Return a printable string for the IPv4 address. */
 1820 static char *
 1821 inet_ntoa4(struct in_addr ina)
 1822 {
 1823         static char buf[4][4 * sizeof "123" + 4];
 1824         unsigned char *ucp = (unsigned char *) &ina;
 1825         static int i = 3;
 1826 
 1827         i = (i + 1) % 4;
 1828         sprintf(buf[i], "%d.%d.%d.%d", ucp[0] & 0xff, ucp[1] & 0xff,
 1829             ucp[2] & 0xff, ucp[3] & 0xff);
 1830         return (buf[i]);
 1831 }
 1832 
 1833 /* Return a printable string for the address. */
 1834 char *
 1835 ipsec_address(union sockaddr_union* sa)
 1836 {
 1837         switch (sa->sa.sa_family) {
 1838 #ifdef INET
 1839         case AF_INET:
 1840                 return inet_ntoa4(sa->sin.sin_addr);
 1841 #endif /* INET */
 1842 
 1843 #ifdef INET6
 1844         case AF_INET6:
 1845                 return ip6_sprintf(&sa->sin6.sin6_addr);
 1846 #endif /* INET6 */
 1847 
 1848         default:
 1849                 return "(unknown address family)";
 1850         }
 1851 }
 1852 
 1853 const char *
 1854 ipsec_logsastr(sav)
 1855         struct secasvar *sav;
 1856 {
 1857         static char buf[256];
 1858         char *p;
 1859         struct secasindex *saidx = &sav->sah->saidx;
 1860 
 1861         IPSEC_ASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
 1862                 ("address family mismatch"));
 1863 
 1864         p = buf;
 1865         snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
 1866         while (p && *p)
 1867                 p++;
 1868         /* NB: only use ipsec_address on one address at a time */
 1869         snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
 1870                 ipsec_address(&saidx->src));
 1871         while (p && *p)
 1872                 p++;
 1873         snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
 1874                 ipsec_address(&saidx->dst));
 1875 
 1876         return buf;
 1877 }
 1878 
 1879 void
 1880 ipsec_dumpmbuf(m)
 1881         struct mbuf *m;
 1882 {
 1883         int totlen;
 1884         int i;
 1885         u_char *p;
 1886 
 1887         totlen = 0;
 1888         printf("---\n");
 1889         while (m) {
 1890                 p = mtod(m, u_char *);
 1891                 for (i = 0; i < m->m_len; i++) {
 1892                         printf("%02x ", p[i]);
 1893                         totlen++;
 1894                         if (totlen % 16 == 0)
 1895                                 printf("\n");
 1896                 }
 1897                 m = m->m_next;
 1898         }
 1899         if (totlen % 16 != 0)
 1900                 printf("\n");
 1901         printf("---\n");
 1902 }
 1903 
 1904 static void
 1905 ipsec_attach(void)
 1906 {
 1907         SECPOLICY_LOCK_INIT(&ip4_def_policy);
 1908         ip4_def_policy.refcnt = 1;                      /* NB: disallow free */
 1909 }
 1910 SYSINIT(ipsec, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST, ipsec_attach, NULL)
 1911 
 1912 
 1913 /* XXX this stuff doesn't belong here... */
 1914 
 1915 static  struct xformsw* xforms = NULL;
 1916 
 1917 /*
 1918  * Register a transform; typically at system startup.
 1919  */
 1920 void
 1921 xform_register(struct xformsw* xsp)
 1922 {
 1923         xsp->xf_next = xforms;
 1924         xforms = xsp;
 1925 }
 1926 
 1927 /*
 1928  * Initialize transform support in an sav.
 1929  */
 1930 int
 1931 xform_init(struct secasvar *sav, int xftype)
 1932 {
 1933         struct xformsw *xsp;
 1934 
 1935         if (sav->tdb_xform != NULL)     /* previously initialized */
 1936                 return 0;
 1937         for (xsp = xforms; xsp; xsp = xsp->xf_next)
 1938                 if (xsp->xf_type == xftype)
 1939                         return (*xsp->xf_init)(sav, xsp);
 1940         return EINVAL;
 1941 }

Cache object: 4b760b447f25f751a01efb3b6eb7124f


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


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