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-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: 1aa433199807e720fccf9201b2a3d449


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