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/netinet6/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/5.1/sys/netinet6/ipsec.c 114205 2003-04-29 08:43:56Z suz $     */
    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/ip_ecn.h>
   67 #ifdef INET6
   68 #include <netinet6/ip6_ecn.h>
   69 #endif
   70 #include <netinet/tcp.h>
   71 #include <netinet/udp.h>
   72 
   73 #include <netinet/ip6.h>
   74 #ifdef INET6
   75 #include <netinet6/ip6_var.h>
   76 #endif
   77 #include <netinet/in_pcb.h>
   78 #ifdef INET6
   79 #include <netinet/icmp6.h>
   80 #endif
   81 
   82 #include <netinet6/ipsec.h>
   83 #ifdef INET6
   84 #include <netinet6/ipsec6.h>
   85 #endif
   86 #include <netinet6/ah.h>
   87 #ifdef INET6
   88 #include <netinet6/ah6.h>
   89 #endif
   90 #ifdef IPSEC_ESP
   91 #include <netinet6/esp.h>
   92 #ifdef INET6
   93 #include <netinet6/esp6.h>
   94 #endif
   95 #endif
   96 #include <netinet6/ipcomp.h>
   97 #ifdef INET6
   98 #include <netinet6/ipcomp6.h>
   99 #endif
  100 #include <netkey/key.h>
  101 #include <netkey/keydb.h>
  102 #include <netkey/key_debug.h>
  103 
  104 #include <machine/in_cksum.h>
  105 
  106 #include <net/net_osdep.h>
  107 
  108 #ifdef IPSEC_DEBUG
  109 int ipsec_debug = 1;
  110 #else
  111 int ipsec_debug = 0;
  112 #endif
  113 
  114 struct ipsecstat ipsecstat;
  115 int ip4_ah_cleartos = 1;
  116 int ip4_ah_offsetmask = 0;      /* maybe IP_DF? */
  117 int ip4_ipsec_dfbit = 0;        /* DF bit on encap. 0: clear 1: set 2: copy */
  118 int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
  119 int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
  120 int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
  121 int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
  122 struct secpolicy ip4_def_policy;
  123 int ip4_ipsec_ecn = 0;          /* ECN ignore(-1)/forbidden(0)/allowed(1) */
  124 int ip4_esp_randpad = -1;
  125 
  126 #ifdef SYSCTL_DECL
  127 SYSCTL_DECL(_net_inet_ipsec);
  128 #ifdef INET6
  129 SYSCTL_DECL(_net_inet6_ipsec6);
  130 #endif
  131 #endif
  132 
  133 /* net.inet.ipsec */
  134 SYSCTL_STRUCT(_net_inet_ipsec, IPSECCTL_STATS,
  135         stats, CTLFLAG_RD,      &ipsecstat,     ipsecstat, "");
  136 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY,
  137         def_policy, CTLFLAG_RW, &ip4_def_policy.policy, 0, "");
  138 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
  139         CTLFLAG_RW, &ip4_esp_trans_deflev,      0, "");
  140 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
  141         CTLFLAG_RW, &ip4_esp_net_deflev,        0, "");
  142 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
  143         CTLFLAG_RW, &ip4_ah_trans_deflev,       0, "");
  144 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
  145         CTLFLAG_RW, &ip4_ah_net_deflev, 0, "");
  146 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS,
  147         ah_cleartos, CTLFLAG_RW,        &ip4_ah_cleartos,       0, "");
  148 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK,
  149         ah_offsetmask, CTLFLAG_RW,      &ip4_ah_offsetmask,     0, "");
  150 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT,
  151         dfbit, CTLFLAG_RW,      &ip4_ipsec_dfbit,       0, "");
  152 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN,
  153         ecn, CTLFLAG_RW,        &ip4_ipsec_ecn, 0, "");
  154 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG,
  155         debug, CTLFLAG_RW,      &ipsec_debug,   0, "");
  156 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
  157         esp_randpad, CTLFLAG_RW,        &ip4_esp_randpad,       0, "");
  158 
  159 #ifdef INET6
  160 struct ipsecstat ipsec6stat;
  161 int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
  162 int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
  163 int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
  164 int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
  165 struct secpolicy ip6_def_policy;
  166 int ip6_ipsec_ecn = 0;          /* ECN ignore(-1)/forbidden(0)/allowed(1) */
  167 int ip6_esp_randpad = -1;
  168 
  169 /* net.inet6.ipsec6 */
  170 SYSCTL_STRUCT(_net_inet6_ipsec6, IPSECCTL_STATS,
  171         stats, CTLFLAG_RD, &ipsec6stat, ipsecstat, "");
  172 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY,
  173         def_policy, CTLFLAG_RW, &ip6_def_policy.policy, 0, "");
  174 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
  175         CTLFLAG_RW, &ip6_esp_trans_deflev,      0, "");
  176 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
  177         CTLFLAG_RW, &ip6_esp_net_deflev,        0, "");
  178 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
  179         CTLFLAG_RW, &ip6_ah_trans_deflev,       0, "");
  180 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
  181         CTLFLAG_RW, &ip6_ah_net_deflev, 0, "");
  182 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
  183         ecn, CTLFLAG_RW,        &ip6_ipsec_ecn, 0, "");
  184 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG,
  185         debug, CTLFLAG_RW,      &ipsec_debug,   0, "");
  186 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
  187         esp_randpad, CTLFLAG_RW,        &ip6_esp_randpad,       0, "");
  188 #endif /* INET6 */
  189 
  190 static int ipsec_setspidx_mbuf
  191         __P((struct secpolicyindex *, u_int, u_int, struct mbuf *, int));
  192 static int ipsec4_setspidx_inpcb __P((struct mbuf *, struct inpcb *pcb));
  193 #ifdef INET6
  194 static int ipsec6_setspidx_in6pcb __P((struct mbuf *, struct in6pcb *pcb));
  195 #endif
  196 static int ipsec_setspidx __P((struct mbuf *, struct secpolicyindex *, int));
  197 static void ipsec4_get_ulp __P((struct mbuf *m, struct secpolicyindex *, int));
  198 static int ipsec4_setspidx_ipaddr __P((struct mbuf *, struct secpolicyindex *));
  199 #ifdef INET6
  200 static void ipsec6_get_ulp __P((struct mbuf *m, struct secpolicyindex *, int));
  201 static int ipsec6_setspidx_ipaddr __P((struct mbuf *, struct secpolicyindex *));
  202 #endif
  203 static struct inpcbpolicy *ipsec_newpcbpolicy __P((void));
  204 static void ipsec_delpcbpolicy __P((struct inpcbpolicy *));
  205 static struct secpolicy *ipsec_deepcopy_policy __P((struct secpolicy *src));
  206 static int ipsec_set_policy __P((struct secpolicy **pcb_sp,
  207         int optname, caddr_t request, size_t len, int priv));
  208 static int ipsec_get_policy __P((struct secpolicy *pcb_sp, struct mbuf **mp));
  209 static void vshiftl __P((unsigned char *, int, int));
  210 static int ipsec_in_reject __P((struct secpolicy *, struct mbuf *));
  211 static size_t ipsec_hdrsiz __P((struct secpolicy *));
  212 #ifdef INET
  213 static struct mbuf *ipsec4_splithdr __P((struct mbuf *));
  214 #endif
  215 #ifdef INET6
  216 static struct mbuf *ipsec6_splithdr __P((struct mbuf *));
  217 #endif
  218 #ifdef INET
  219 static int ipsec4_encapsulate __P((struct mbuf *, struct secasvar *));
  220 #endif
  221 #ifdef INET6
  222 static int ipsec6_encapsulate __P((struct mbuf *, struct secasvar *));
  223 #endif
  224 
  225 /*
  226  * For OUTBOUND packet having a socket. Searching SPD for packet,
  227  * and return a pointer to SP.
  228  * OUT: NULL:   no apropreate SP found, the following value is set to error.
  229  *              0       : bypass
  230  *              EACCES  : discard packet.
  231  *              ENOENT  : ipsec_acquire() in progress, maybe.
  232  *              others  : error occured.
  233  *      others: a pointer to SP
  234  *
  235  * NOTE: IPv6 mapped adddress concern is implemented here.
  236  */
  237 struct secpolicy *
  238 ipsec4_getpolicybypcb(m, dir, inp, error)
  239         struct mbuf *m;
  240         u_int dir;
  241         struct inpcb *inp;
  242         int *error;
  243 {
  244         struct inpcbpolicy *pcbsp = NULL;
  245         struct secpolicy *currsp = NULL;        /* policy on socket */
  246         struct secpolicy *kernsp = NULL;        /* policy on kernel */
  247 
  248         /* sanity check */
  249         if (m == NULL || inp == NULL || error == NULL)
  250                 panic("ipsec4_getpolicybysock: NULL pointer was passed.");
  251 
  252         /* set spidx in pcb */
  253 #ifdef INET6
  254         if (inp->inp_vflag & INP_IPV6PROTO)
  255                 *error = ipsec6_setspidx_in6pcb(m, inp);
  256         else
  257 #endif
  258                 *error = ipsec4_setspidx_inpcb(m, inp);
  259         if (*error)
  260                 return NULL;
  261         pcbsp = inp->inp_sp;
  262 
  263         /* sanity check */
  264         if (pcbsp == NULL)
  265                 panic("ipsec4_getpolicybysock: pcbsp is NULL.");
  266 
  267         switch (dir) {
  268         case IPSEC_DIR_INBOUND:
  269                 currsp = pcbsp->sp_in;
  270                 break;
  271         case IPSEC_DIR_OUTBOUND:
  272                 currsp = pcbsp->sp_out;
  273                 break;
  274         default:
  275                 panic("ipsec4_getpolicybysock: illegal direction.");
  276         }
  277 
  278         /* sanity check */
  279         if (currsp == NULL)
  280                 panic("ipsec4_getpolicybysock: currsp is NULL.");
  281 
  282         /* when privilieged socket */
  283         if (pcbsp->priv) {
  284                 switch (currsp->policy) {
  285                 case IPSEC_POLICY_BYPASS:
  286                         currsp->refcnt++;
  287                         *error = 0;
  288                         return currsp;
  289 
  290                 case IPSEC_POLICY_ENTRUST:
  291                         /* look for a policy in SPD */
  292                         kernsp = key_allocsp(&currsp->spidx, dir);
  293 
  294                         /* SP found */
  295                         if (kernsp != NULL) {
  296                                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  297                                         printf("DP ipsec4_getpolicybysock called "
  298                                                "to allocate SP:%p\n", kernsp));
  299                                 *error = 0;
  300                                 return kernsp;
  301                         }
  302 
  303                         /* no SP found */
  304                         if (ip4_def_policy.policy != IPSEC_POLICY_DISCARD
  305                          && ip4_def_policy.policy != IPSEC_POLICY_NONE) {
  306                                 ipseclog((LOG_INFO,
  307                                     "fixed system default policy: %d->%d\n",
  308                                     ip4_def_policy.policy, IPSEC_POLICY_NONE));
  309                                 ip4_def_policy.policy = IPSEC_POLICY_NONE;
  310                         }
  311                         ip4_def_policy.refcnt++;
  312                         *error = 0;
  313                         return &ip4_def_policy;
  314                         
  315                 case IPSEC_POLICY_IPSEC:
  316                         currsp->refcnt++;
  317                         *error = 0;
  318                         return currsp;
  319 
  320                 default:
  321                         ipseclog((LOG_ERR, "ipsec4_getpolicybysock: "
  322                               "Invalid policy for PCB %d\n", currsp->policy));
  323                         *error = EINVAL;
  324                         return NULL;
  325                 }
  326                 /* NOTREACHED */
  327         }
  328 
  329         /* when non-privilieged socket */
  330         /* look for a policy in SPD */
  331         kernsp = key_allocsp(&currsp->spidx, dir);
  332 
  333         /* SP found */
  334         if (kernsp != NULL) {
  335                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  336                         printf("DP ipsec4_getpolicybysock called "
  337                                "to allocate SP:%p\n", kernsp));
  338                 *error = 0;
  339                 return kernsp;
  340         }
  341 
  342         /* no SP found */
  343         switch (currsp->policy) {
  344         case IPSEC_POLICY_BYPASS:
  345                 ipseclog((LOG_ERR, "ipsec4_getpolicybysock: "
  346                        "Illegal policy for non-priviliged defined %d\n",
  347                         currsp->policy));
  348                 *error = EINVAL;
  349                 return NULL;
  350 
  351         case IPSEC_POLICY_ENTRUST:
  352                 if (ip4_def_policy.policy != IPSEC_POLICY_DISCARD
  353                  && ip4_def_policy.policy != IPSEC_POLICY_NONE) {
  354                         ipseclog((LOG_INFO,
  355                             "fixed system default policy: %d->%d\n",
  356                             ip4_def_policy.policy, IPSEC_POLICY_NONE));
  357                         ip4_def_policy.policy = IPSEC_POLICY_NONE;
  358                 }
  359                 ip4_def_policy.refcnt++;
  360                 *error = 0;
  361                 return &ip4_def_policy;
  362 
  363         case IPSEC_POLICY_IPSEC:
  364                 currsp->refcnt++;
  365                 *error = 0;
  366                 return currsp;
  367 
  368         default:
  369                 ipseclog((LOG_ERR, "ipsec4_getpolicybysock: "
  370                    "Invalid policy for PCB %d\n", currsp->policy));
  371                 *error = EINVAL;
  372                 return NULL;
  373         }
  374         /* NOTREACHED */
  375 }
  376 
  377 struct secpolicy *
  378 ipsec4_getpolicybysock(m, dir, so, error)
  379         struct mbuf *m;
  380         u_int dir;
  381         struct socket *so;
  382         int *error;
  383 {
  384 
  385         if (so == NULL)
  386                 panic("ipsec4_getpolicybysock: NULL pointer was passed.");
  387         return (ipsec4_getpolicybypcb(m, dir, sotoinpcb(so), error));
  388 }
  389 
  390 /*
  391  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
  392  * and return a pointer to SP.
  393  * OUT: positive: a pointer to the entry for security policy leaf matched.
  394  *      NULL:   no apropreate SP found, the following value is set to error.
  395  *              0       : bypass
  396  *              EACCES  : discard packet.
  397  *              ENOENT  : ipsec_acquire() in progress, maybe.
  398  *              others  : error occured.
  399  */
  400 struct secpolicy *
  401 ipsec4_getpolicybyaddr(m, dir, flag, error)
  402         struct mbuf *m;
  403         u_int dir;
  404         int flag;
  405         int *error;
  406 {
  407         struct secpolicy *sp = NULL;
  408 
  409         /* sanity check */
  410         if (m == NULL || error == NULL)
  411                 panic("ipsec4_getpolicybyaddr: NULL pointer was passed.");
  412 
  413     {
  414         struct secpolicyindex spidx;
  415 
  416         bzero(&spidx, sizeof(spidx));
  417 
  418         /* Make an index to look for a policy. */
  419         *error = ipsec_setspidx_mbuf(&spidx, dir, AF_INET, m,
  420             (flag & IP_FORWARDING) ? 0 : 1);
  421 
  422         if (*error != 0)
  423                 return NULL;
  424 
  425         sp = key_allocsp(&spidx, dir);
  426     }
  427 
  428         /* SP found */
  429         if (sp != NULL) {
  430                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  431                         printf("DP ipsec4_getpolicybyaddr called "
  432                                "to allocate SP:%p\n", sp));
  433                 *error = 0;
  434                 return sp;
  435         }
  436 
  437         /* no SP found */
  438         if (ip4_def_policy.policy != IPSEC_POLICY_DISCARD
  439          && ip4_def_policy.policy != IPSEC_POLICY_NONE) {
  440                 ipseclog((LOG_INFO, "fixed system default policy:%d->%d\n",
  441                         ip4_def_policy.policy,
  442                         IPSEC_POLICY_NONE));
  443                 ip4_def_policy.policy = IPSEC_POLICY_NONE;
  444         }
  445         ip4_def_policy.refcnt++;
  446         *error = 0;
  447         return &ip4_def_policy;
  448 }
  449 
  450 #ifdef INET6
  451 /*
  452  * For OUTBOUND packet having a socket. Searching SPD for packet,
  453  * and return a pointer to SP.
  454  * OUT: NULL:   no apropreate SP found, the following value is set to error.
  455  *              0       : bypass
  456  *              EACCES  : discard packet.
  457  *              ENOENT  : ipsec_acquire() in progress, maybe.
  458  *              others  : error occured.
  459  *      others: a pointer to SP
  460  */
  461 struct secpolicy *
  462 ipsec6_getpolicybypcb(m, dir, inp, error)
  463         struct mbuf *m;
  464         u_int dir;
  465         struct inpcb *inp;
  466         int *error;
  467 {
  468         struct inpcbpolicy *pcbsp = NULL;
  469         struct secpolicy *currsp = NULL;        /* policy on socket */
  470         struct secpolicy *kernsp = NULL;        /* policy on kernel */
  471 
  472         /* sanity check */
  473         if (m == NULL || inp == NULL || error == NULL)
  474                 panic("ipsec6_getpolicybysock: NULL pointer was passed.");
  475 
  476 #ifdef DIAGNOSTIC
  477         if ((inp->inp_vflag & INP_IPV6PROTO) == 0)
  478                 panic("ipsec6_getpolicybysock: socket domain != inet6");
  479 #endif
  480 
  481         /* set spidx in pcb */
  482         ipsec6_setspidx_in6pcb(m, inp);
  483         pcbsp = inp->in6p_sp;
  484 
  485         /* sanity check */
  486         if (pcbsp == NULL)
  487                 panic("ipsec6_getpolicybysock: pcbsp is NULL.");
  488 
  489         switch (dir) {
  490         case IPSEC_DIR_INBOUND:
  491                 currsp = pcbsp->sp_in;
  492                 break;
  493         case IPSEC_DIR_OUTBOUND:
  494                 currsp = pcbsp->sp_out;
  495                 break;
  496         default:
  497                 panic("ipsec6_getpolicybysock: illegal direction.");
  498         }
  499 
  500         /* sanity check */
  501         if (currsp == NULL)
  502                 panic("ipsec6_getpolicybysock: currsp is NULL.");
  503 
  504         /* when privilieged socket */
  505         if (pcbsp->priv) {
  506                 switch (currsp->policy) {
  507                 case IPSEC_POLICY_BYPASS:
  508                         currsp->refcnt++;
  509                         *error = 0;
  510                         return currsp;
  511 
  512                 case IPSEC_POLICY_ENTRUST:
  513                         /* look for a policy in SPD */
  514                         kernsp = key_allocsp(&currsp->spidx, dir);
  515 
  516                         /* SP found */
  517                         if (kernsp != NULL) {
  518                                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  519                                         printf("DP ipsec6_getpolicybysock called "
  520                                                "to allocate SP:%p\n", kernsp));
  521                                 *error = 0;
  522                                 return kernsp;
  523                         }
  524 
  525                         /* no SP found */
  526                         if (ip6_def_policy.policy != IPSEC_POLICY_DISCARD
  527                          && ip6_def_policy.policy != IPSEC_POLICY_NONE) {
  528                                 ipseclog((LOG_INFO,
  529                                     "fixed system default policy: %d->%d\n",
  530                                     ip6_def_policy.policy, IPSEC_POLICY_NONE));
  531                                 ip6_def_policy.policy = IPSEC_POLICY_NONE;
  532                         }
  533                         ip6_def_policy.refcnt++;
  534                         *error = 0;
  535                         return &ip6_def_policy;
  536                         
  537                 case IPSEC_POLICY_IPSEC:
  538                         currsp->refcnt++;
  539                         *error = 0;
  540                         return currsp;
  541 
  542                 default:
  543                         ipseclog((LOG_ERR, "ipsec6_getpolicybysock: "
  544                             "Invalid policy for PCB %d\n", currsp->policy));
  545                         *error = EINVAL;
  546                         return NULL;
  547                 }
  548                 /* NOTREACHED */
  549         }
  550 
  551         /* when non-privilieged socket */
  552         /* look for a policy in SPD */
  553         kernsp = key_allocsp(&currsp->spidx, dir);
  554 
  555         /* SP found */
  556         if (kernsp != NULL) {
  557                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  558                         printf("DP ipsec6_getpolicybysock called "
  559                                "to allocate SP:%p\n", kernsp));
  560                 *error = 0;
  561                 return kernsp;
  562         }
  563 
  564         /* no SP found */
  565         switch (currsp->policy) {
  566         case IPSEC_POLICY_BYPASS:
  567                 ipseclog((LOG_ERR, "ipsec6_getpolicybysock: "
  568                     "Illegal policy for non-priviliged defined %d\n",
  569                     currsp->policy));
  570                 *error = EINVAL;
  571                 return NULL;
  572 
  573         case IPSEC_POLICY_ENTRUST:
  574                 if (ip6_def_policy.policy != IPSEC_POLICY_DISCARD
  575                  && ip6_def_policy.policy != IPSEC_POLICY_NONE) {
  576                         ipseclog((LOG_INFO,
  577                             "fixed system default policy: %d->%d\n",
  578                             ip6_def_policy.policy, IPSEC_POLICY_NONE));
  579                         ip6_def_policy.policy = IPSEC_POLICY_NONE;
  580                 }
  581                 ip6_def_policy.refcnt++;
  582                 *error = 0;
  583                 return &ip6_def_policy;
  584 
  585         case IPSEC_POLICY_IPSEC:
  586                 currsp->refcnt++;
  587                 *error = 0;
  588                 return currsp;
  589 
  590         default:
  591                 ipseclog((LOG_ERR,
  592                     "ipsec6_policybysock: Invalid policy for PCB %d\n",
  593                     currsp->policy));
  594                 *error = EINVAL;
  595                 return NULL;
  596         }
  597         /* NOTREACHED */
  598 }
  599 
  600 struct secpolicy *
  601 ipsec6_getpolicybysock(m, dir, so, error)
  602         struct mbuf *m;
  603         u_int dir;
  604         struct socket *so;
  605         int *error;
  606 {
  607 
  608         if (so == NULL)
  609                 panic("ipsec6_getpolicybysock: NULL pointer was passed.");
  610         return (ipsec6_getpolicybypcb(m, dir, sotoin6pcb(so), error));
  611 }
  612 
  613 /*
  614  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
  615  * and return a pointer to SP.
  616  * `flag' means that packet is to be forwarded whether or not.
  617  *      flag = 1: forwad
  618  * OUT: positive: a pointer to the entry for security policy leaf matched.
  619  *      NULL:   no apropreate SP found, the following value is set to error.
  620  *              0       : bypass
  621  *              EACCES  : discard packet.
  622  *              ENOENT  : ipsec_acquire() in progress, maybe.
  623  *              others  : error occured.
  624  */
  625 #ifndef IP_FORWARDING
  626 #define IP_FORWARDING 1
  627 #endif
  628 
  629 struct secpolicy *
  630 ipsec6_getpolicybyaddr(m, dir, flag, error)
  631         struct mbuf *m;
  632         u_int dir;
  633         int flag;
  634         int *error;
  635 {
  636         struct secpolicy *sp = NULL;
  637 
  638         /* sanity check */
  639         if (m == NULL || error == NULL)
  640                 panic("ipsec6_getpolicybyaddr: NULL pointer was passed.");
  641 
  642     {
  643         struct secpolicyindex spidx;
  644 
  645         bzero(&spidx, sizeof(spidx));
  646 
  647         /* Make an index to look for a policy. */
  648         *error = ipsec_setspidx_mbuf(&spidx, dir, AF_INET6, m,
  649             (flag & IP_FORWARDING) ? 0 : 1);
  650 
  651         if (*error != 0)
  652                 return NULL;
  653 
  654         sp = key_allocsp(&spidx, dir);
  655     }
  656 
  657         /* SP found */
  658         if (sp != NULL) {
  659                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  660                         printf("DP ipsec6_getpolicybyaddr called "
  661                                "to allocate SP:%p\n", sp));
  662                 *error = 0;
  663                 return sp;
  664         }
  665 
  666         /* no SP found */
  667         if (ip6_def_policy.policy != IPSEC_POLICY_DISCARD
  668          && ip6_def_policy.policy != IPSEC_POLICY_NONE) {
  669                 ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
  670                     ip6_def_policy.policy, IPSEC_POLICY_NONE));
  671                 ip6_def_policy.policy = IPSEC_POLICY_NONE;
  672         }
  673         ip6_def_policy.refcnt++;
  674         *error = 0;
  675         return &ip6_def_policy;
  676 }
  677 #endif /* INET6 */
  678 
  679 /*
  680  * set IP address into spidx from mbuf.
  681  * When Forwarding packet and ICMP echo reply, this function is used.
  682  *
  683  * IN:  get the followings from mbuf.
  684  *      protocol family, src, dst, next protocol
  685  * OUT:
  686  *      0:      success.
  687  *      other:  failure, and set errno.
  688  */
  689 int
  690 ipsec_setspidx_mbuf(spidx, dir, family, m, needport)
  691         struct secpolicyindex *spidx;
  692         u_int dir, family;
  693         struct mbuf *m;
  694         int needport;
  695 {
  696         int error;
  697 
  698         /* sanity check */
  699         if (spidx == NULL || m == NULL)
  700                 panic("ipsec_setspidx_mbuf: NULL pointer was passed.");
  701 
  702         bzero(spidx, sizeof(*spidx));
  703 
  704         error = ipsec_setspidx(m, spidx, needport);
  705         if (error)
  706                 goto bad;
  707         spidx->dir = dir;
  708 
  709         return 0;
  710 
  711     bad:
  712         /* XXX initialize */
  713         bzero(spidx, sizeof(*spidx));
  714         return EINVAL;
  715 }
  716 
  717 static int
  718 ipsec4_setspidx_inpcb(m, pcb)
  719         struct mbuf *m;
  720         struct inpcb *pcb;
  721 {
  722         struct secpolicyindex *spidx;
  723         int error;
  724 
  725         /* sanity check */
  726         if (pcb == NULL)
  727                 panic("ipsec4_setspidx_inpcb: no PCB found.");
  728         if (pcb->inp_sp == NULL)
  729                 panic("ipsec4_setspidx_inpcb: no inp_sp found.");
  730         if (pcb->inp_sp->sp_out == NULL || pcb->inp_sp->sp_in == NULL)
  731                 panic("ipsec4_setspidx_inpcb: no sp_in/out found.");
  732 
  733         bzero(&pcb->inp_sp->sp_in->spidx, sizeof(*spidx));
  734         bzero(&pcb->inp_sp->sp_out->spidx, sizeof(*spidx));
  735 
  736         spidx = &pcb->inp_sp->sp_in->spidx;
  737         error = ipsec_setspidx(m, spidx, 1);
  738         if (error)
  739                 goto bad;
  740         spidx->dir = IPSEC_DIR_INBOUND;
  741 
  742         spidx = &pcb->inp_sp->sp_out->spidx;
  743         error = ipsec_setspidx(m, spidx, 1);
  744         if (error)
  745                 goto bad;
  746         spidx->dir = IPSEC_DIR_OUTBOUND;
  747 
  748         return 0;
  749 
  750 bad:
  751         bzero(&pcb->inp_sp->sp_in->spidx, sizeof(*spidx));
  752         bzero(&pcb->inp_sp->sp_out->spidx, sizeof(*spidx));
  753         return error;
  754 }
  755 
  756 #ifdef INET6
  757 static int
  758 ipsec6_setspidx_in6pcb(m, pcb)
  759         struct mbuf *m;
  760         struct in6pcb *pcb;
  761 {
  762         struct secpolicyindex *spidx;
  763         int error;
  764 
  765         /* sanity check */
  766         if (pcb == NULL)
  767                 panic("ipsec6_setspidx_in6pcb: no PCB found.");
  768         if (pcb->in6p_sp == NULL)
  769                 panic("ipsec6_setspidx_in6pcb: no in6p_sp found.");
  770         if (pcb->in6p_sp->sp_out == NULL || pcb->in6p_sp->sp_in == NULL)
  771                 panic("ipsec6_setspidx_in6pcb: no sp_in/out found.");
  772 
  773         bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
  774         bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
  775 
  776         spidx = &pcb->in6p_sp->sp_in->spidx;
  777         error = ipsec_setspidx(m, spidx, 1);
  778         if (error)
  779                 goto bad;
  780         spidx->dir = IPSEC_DIR_INBOUND;
  781 
  782         spidx = &pcb->in6p_sp->sp_out->spidx;
  783         error = ipsec_setspidx(m, spidx, 1);
  784         if (error)
  785                 goto bad;
  786         spidx->dir = IPSEC_DIR_OUTBOUND;
  787 
  788         return 0;
  789 
  790 bad:
  791         bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
  792         bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
  793         return error;
  794 }
  795 #endif
  796 
  797 /*
  798  * configure security policy index (src/dst/proto/sport/dport)
  799  * by looking at the content of mbuf.
  800  * the caller is responsible for error recovery (like clearing up spidx).
  801  */
  802 static int
  803 ipsec_setspidx(m, spidx, needport)
  804         struct mbuf *m;
  805         struct secpolicyindex *spidx;
  806         int needport;
  807 {
  808         struct ip *ip = NULL;
  809         struct ip ipbuf;
  810         u_int v;
  811         struct mbuf *n;
  812         int len;
  813         int error;
  814 
  815         if (m == NULL)
  816                 panic("ipsec_setspidx: m == 0 passed.");
  817 
  818         /*
  819          * validate m->m_pkthdr.len.  we see incorrect length if we
  820          * mistakenly call this function with inconsistent mbuf chain
  821          * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
  822          */
  823         len = 0;
  824         for (n = m; n; n = n->m_next)
  825                 len += n->m_len;
  826         if (m->m_pkthdr.len != len) {
  827                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  828                         printf("ipsec_setspidx: "
  829                                "total of m_len(%d) != pkthdr.len(%d), "
  830                                "ignored.\n",
  831                                 len, m->m_pkthdr.len));
  832                 return EINVAL;
  833         }
  834 
  835         if (m->m_pkthdr.len < sizeof(struct ip)) {
  836                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  837                         printf("ipsec_setspidx: "
  838                             "pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
  839                             m->m_pkthdr.len));
  840                 return EINVAL;
  841         }
  842 
  843         if (m->m_len >= sizeof(*ip))
  844                 ip = mtod(m, struct ip *);
  845         else {
  846                 m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
  847                 ip = &ipbuf;
  848         }
  849 #ifdef _IP_VHL
  850         v = _IP_VHL_V(ip->ip_vhl);
  851 #else
  852         v = ip->ip_v;
  853 #endif
  854         switch (v) {
  855         case 4:
  856                 error = ipsec4_setspidx_ipaddr(m, spidx);
  857                 if (error)
  858                         return error;
  859                 ipsec4_get_ulp(m, spidx, needport);
  860                 return 0;
  861 #ifdef INET6
  862         case 6:
  863                 if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
  864                         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  865                                 printf("ipsec_setspidx: "
  866                                     "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
  867                                     "ignored.\n", m->m_pkthdr.len));
  868                         return EINVAL;
  869                 }
  870                 error = ipsec6_setspidx_ipaddr(m, spidx);
  871                 if (error)
  872                         return error;
  873                 ipsec6_get_ulp(m, spidx, needport);
  874                 return 0;
  875 #endif
  876         default:
  877                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
  878                         printf("ipsec_setspidx: "
  879                             "unknown IP version %u, ignored.\n", v));
  880                 return EINVAL;
  881         }
  882 }
  883 
  884 static void
  885 ipsec4_get_ulp(m, spidx, needport)
  886         struct mbuf *m;
  887         struct secpolicyindex *spidx;
  888         int needport;
  889 {
  890         struct ip ip;
  891         struct ip6_ext ip6e;
  892         u_int8_t nxt;
  893         int off;
  894         struct tcphdr th;
  895         struct udphdr uh;
  896 
  897         /* sanity check */
  898         if (m == NULL)
  899                 panic("ipsec4_get_ulp: NULL pointer was passed.");
  900         if (m->m_pkthdr.len < sizeof(ip))
  901                 panic("ipsec4_get_ulp: too short");
  902 
  903         /* set default */
  904         spidx->ul_proto = IPSEC_ULPROTO_ANY;
  905         ((struct sockaddr_in *)&spidx->src)->sin_port = IPSEC_PORT_ANY;
  906         ((struct sockaddr_in *)&spidx->dst)->sin_port = IPSEC_PORT_ANY;
  907 
  908         m_copydata(m, 0, sizeof(ip), (caddr_t)&ip);
  909         /* ip_input() flips it into host endian XXX need more checking */
  910         if (ip.ip_off & (IP_MF | IP_OFFMASK))
  911                 return;
  912 
  913         nxt = ip.ip_p;
  914 #ifdef _IP_VHL
  915         off = _IP_VHL_HL(ip->ip_vhl) << 2;
  916 #else
  917         off = ip.ip_hl << 2;
  918 #endif
  919         while (off < m->m_pkthdr.len) {
  920                 switch (nxt) {
  921                 case IPPROTO_TCP:
  922                         spidx->ul_proto = nxt;
  923                         if (!needport)
  924                                 return;
  925                         if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
  926                                 return;
  927                         m_copydata(m, off, sizeof(th), (caddr_t)&th);
  928                         ((struct sockaddr_in *)&spidx->src)->sin_port =
  929                             th.th_sport;
  930                         ((struct sockaddr_in *)&spidx->dst)->sin_port =
  931                             th.th_dport;
  932                         return;
  933                 case IPPROTO_UDP:
  934                         spidx->ul_proto = nxt;
  935                         if (!needport)
  936                                 return;
  937                         if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
  938                                 return;
  939                         m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
  940                         ((struct sockaddr_in *)&spidx->src)->sin_port =
  941                             uh.uh_sport;
  942                         ((struct sockaddr_in *)&spidx->dst)->sin_port =
  943                             uh.uh_dport;
  944                         return;
  945                 case IPPROTO_AH:
  946                         if (m->m_pkthdr.len > off + sizeof(ip6e))
  947                                 return;
  948                         m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
  949                         off += (ip6e.ip6e_len + 2) << 2;
  950                         nxt = ip6e.ip6e_nxt;
  951                         break;
  952                 case IPPROTO_ICMP:
  953                 default:
  954                         /* XXX intermediate headers??? */
  955                         spidx->ul_proto = nxt;
  956                         return;
  957                 }
  958         }
  959 }
  960 
  961 /* assumes that m is sane */
  962 static int
  963 ipsec4_setspidx_ipaddr(m, spidx)
  964         struct mbuf *m;
  965         struct secpolicyindex *spidx;
  966 {
  967         struct ip *ip = NULL;
  968         struct ip ipbuf;
  969         struct sockaddr_in *sin;
  970 
  971         if (m->m_len >= sizeof(*ip))
  972                 ip = mtod(m, struct ip *);
  973         else {
  974                 m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
  975                 ip = &ipbuf;
  976         }
  977 
  978         sin = (struct sockaddr_in *)&spidx->src;
  979         bzero(sin, sizeof(*sin));
  980         sin->sin_family = AF_INET;
  981         sin->sin_len = sizeof(struct sockaddr_in);
  982         bcopy(&ip->ip_src, &sin->sin_addr, sizeof(ip->ip_src));
  983         spidx->prefs = sizeof(struct in_addr) << 3;
  984 
  985         sin = (struct sockaddr_in *)&spidx->dst;
  986         bzero(sin, sizeof(*sin));
  987         sin->sin_family = AF_INET;
  988         sin->sin_len = sizeof(struct sockaddr_in);
  989         bcopy(&ip->ip_dst, &sin->sin_addr, sizeof(ip->ip_dst));
  990         spidx->prefd = sizeof(struct in_addr) << 3;
  991         return 0;
  992 }
  993 
  994 #ifdef INET6
  995 static void
  996 ipsec6_get_ulp(m, spidx, needport)
  997         struct mbuf *m;
  998         struct secpolicyindex *spidx;
  999         int needport;
 1000 {
 1001         int off, nxt;
 1002         struct tcphdr th;
 1003         struct udphdr uh;
 1004 
 1005         /* sanity check */
 1006         if (m == NULL)
 1007                 panic("ipsec6_get_ulp: NULL pointer was passed.");
 1008 
 1009         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1010                 printf("ipsec6_get_ulp:\n"); kdebug_mbuf(m));
 1011 
 1012         /* set default */
 1013         spidx->ul_proto = IPSEC_ULPROTO_ANY;
 1014         ((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
 1015         ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
 1016 
 1017         nxt = -1;
 1018         off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
 1019         if (off < 0 || m->m_pkthdr.len < off)
 1020                 return;
 1021 
 1022         switch (nxt) {
 1023         case IPPROTO_TCP:
 1024                 spidx->ul_proto = nxt;
 1025                 if (!needport)
 1026                         break;
 1027                 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
 1028                         break;
 1029                 m_copydata(m, off, sizeof(th), (caddr_t)&th);
 1030                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
 1031                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
 1032                 break;
 1033         case IPPROTO_UDP:
 1034                 spidx->ul_proto = nxt;
 1035                 if (!needport)
 1036                         break;
 1037                 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
 1038                         break;
 1039                 m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
 1040                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
 1041                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
 1042                 break;
 1043         case IPPROTO_ICMPV6:
 1044         default:
 1045                 /* XXX intermediate headers??? */
 1046                 spidx->ul_proto = nxt;
 1047                 break;
 1048         }
 1049 }
 1050 
 1051 /* assumes that m is sane */
 1052 static int
 1053 ipsec6_setspidx_ipaddr(m, spidx)
 1054         struct mbuf *m;
 1055         struct secpolicyindex *spidx;
 1056 {
 1057         struct ip6_hdr *ip6 = NULL;
 1058         struct ip6_hdr ip6buf;
 1059         struct sockaddr_in6 *sin6;
 1060 
 1061         if (m->m_len >= sizeof(*ip6))
 1062                 ip6 = mtod(m, struct ip6_hdr *);
 1063         else {
 1064                 m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf);
 1065                 ip6 = &ip6buf;
 1066         }
 1067 
 1068         sin6 = (struct sockaddr_in6 *)&spidx->src;
 1069         bzero(sin6, sizeof(*sin6));
 1070         sin6->sin6_family = AF_INET6;
 1071         sin6->sin6_len = sizeof(struct sockaddr_in6);
 1072         bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src));
 1073         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
 1074                 sin6->sin6_addr.s6_addr16[1] = 0;
 1075                 sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
 1076         }
 1077         spidx->prefs = sizeof(struct in6_addr) << 3;
 1078 
 1079         sin6 = (struct sockaddr_in6 *)&spidx->dst;
 1080         bzero(sin6, sizeof(*sin6));
 1081         sin6->sin6_family = AF_INET6;
 1082         sin6->sin6_len = sizeof(struct sockaddr_in6);
 1083         bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst));
 1084         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
 1085                 sin6->sin6_addr.s6_addr16[1] = 0;
 1086                 sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
 1087         }
 1088         spidx->prefd = sizeof(struct in6_addr) << 3;
 1089 
 1090         return 0;
 1091 }
 1092 #endif
 1093 
 1094 static struct inpcbpolicy *
 1095 ipsec_newpcbpolicy()
 1096 {
 1097         struct inpcbpolicy *p;
 1098 
 1099         p = (struct inpcbpolicy *)malloc(sizeof(*p), M_SECA, M_NOWAIT);
 1100         return p;
 1101 }
 1102 
 1103 static void
 1104 ipsec_delpcbpolicy(p)
 1105         struct inpcbpolicy *p;
 1106 {
 1107         free(p, M_SECA);
 1108 }
 1109 
 1110 /* initialize policy in PCB */
 1111 int
 1112 ipsec_init_policy(so, pcb_sp)
 1113         struct socket *so;
 1114         struct inpcbpolicy **pcb_sp;
 1115 {
 1116         struct inpcbpolicy *new;
 1117 
 1118         /* sanity check. */
 1119         if (so == NULL || pcb_sp == NULL)
 1120                 panic("ipsec_init_policy: NULL pointer was passed.");
 1121 
 1122         new = ipsec_newpcbpolicy();
 1123         if (new == NULL) {
 1124                 ipseclog((LOG_DEBUG, "ipsec_init_policy: No more memory.\n"));
 1125                 return ENOBUFS;
 1126         }
 1127         bzero(new, sizeof(*new));
 1128 
 1129         if (so->so_cred != 0 && so->so_cred->cr_uid == 0)
 1130                 new->priv = 1;
 1131         else
 1132                 new->priv = 0;
 1133 
 1134         if ((new->sp_in = key_newsp()) == NULL) {
 1135                 ipsec_delpcbpolicy(new);
 1136                 return ENOBUFS;
 1137         }
 1138         new->sp_in->state = IPSEC_SPSTATE_ALIVE;
 1139         new->sp_in->policy = IPSEC_POLICY_ENTRUST;
 1140 
 1141         if ((new->sp_out = key_newsp()) == NULL) {
 1142                 key_freesp(new->sp_in);
 1143                 ipsec_delpcbpolicy(new);
 1144                 return ENOBUFS;
 1145         }
 1146         new->sp_out->state = IPSEC_SPSTATE_ALIVE;
 1147         new->sp_out->policy = IPSEC_POLICY_ENTRUST;
 1148 
 1149         *pcb_sp = new;
 1150 
 1151         return 0;
 1152 }
 1153 
 1154 /* copy old ipsec policy into new */
 1155 int
 1156 ipsec_copy_policy(old, new)
 1157         struct inpcbpolicy *old, *new;
 1158 {
 1159         struct secpolicy *sp;
 1160 
 1161         sp = ipsec_deepcopy_policy(old->sp_in);
 1162         if (sp) {
 1163                 key_freesp(new->sp_in);
 1164                 new->sp_in = sp;
 1165         } else
 1166                 return ENOBUFS;
 1167 
 1168         sp = ipsec_deepcopy_policy(old->sp_out);
 1169         if (sp) {
 1170                 key_freesp(new->sp_out);
 1171                 new->sp_out = sp;
 1172         } else
 1173                 return ENOBUFS;
 1174 
 1175         new->priv = old->priv;
 1176 
 1177         return 0;
 1178 }
 1179 
 1180 /* deep-copy a policy in PCB */
 1181 static struct secpolicy *
 1182 ipsec_deepcopy_policy(src)
 1183         struct secpolicy *src;
 1184 {
 1185         struct ipsecrequest *newchain = NULL;
 1186         struct ipsecrequest *p;
 1187         struct ipsecrequest **q;
 1188         struct ipsecrequest *r;
 1189         struct secpolicy *dst;
 1190 
 1191         dst = key_newsp();
 1192         if (src == NULL || dst == NULL)
 1193                 return NULL;
 1194 
 1195         /*
 1196          * deep-copy IPsec request chain.  This is required since struct
 1197          * ipsecrequest is not reference counted.
 1198          */
 1199         q = &newchain;
 1200         for (p = src->req; p; p = p->next) {
 1201                 *q = (struct ipsecrequest *)malloc(sizeof(struct ipsecrequest),
 1202                         M_SECA, M_NOWAIT);
 1203                 if (*q == NULL)
 1204                         goto fail;
 1205                 bzero(*q, sizeof(**q));
 1206                 (*q)->next = NULL;
 1207 
 1208                 (*q)->saidx.proto = p->saidx.proto;
 1209                 (*q)->saidx.mode = p->saidx.mode;
 1210                 (*q)->level = p->level;
 1211                 (*q)->saidx.reqid = p->saidx.reqid;
 1212 
 1213                 bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src));
 1214                 bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst));
 1215 
 1216                 (*q)->sav = NULL;
 1217                 (*q)->sp = dst;
 1218 
 1219                 q = &((*q)->next);
 1220         }
 1221 
 1222         dst->req = newchain;
 1223         dst->state = src->state;
 1224         dst->policy = src->policy;
 1225         /* do not touch the refcnt fields */
 1226 
 1227         return dst;
 1228 
 1229 fail:
 1230         for (p = newchain; p; p = r) {
 1231                 r = p->next;
 1232                 free(p, M_SECA);
 1233                 p = NULL;
 1234         }
 1235         return NULL;
 1236 }
 1237 
 1238 /* set policy and ipsec request if present. */
 1239 static int
 1240 ipsec_set_policy(pcb_sp, optname, request, len, priv)
 1241         struct secpolicy **pcb_sp;
 1242         int optname;
 1243         caddr_t request;
 1244         size_t len;
 1245         int priv;
 1246 {
 1247         struct sadb_x_policy *xpl;
 1248         struct secpolicy *newsp = NULL;
 1249         int error;
 1250 
 1251         /* sanity check. */
 1252         if (pcb_sp == NULL || *pcb_sp == NULL || request == NULL)
 1253                 return EINVAL;
 1254         if (len < sizeof(*xpl))
 1255                 return EINVAL;
 1256         xpl = (struct sadb_x_policy *)request;
 1257 
 1258         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1259                 printf("ipsec_set_policy: passed policy\n");
 1260                 kdebug_sadb_x_policy((struct sadb_ext *)xpl));
 1261 
 1262         /* check policy type */
 1263         /* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
 1264         if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
 1265          || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
 1266                 return EINVAL;
 1267 
 1268         /* check privileged socket */
 1269         if (priv == 0 && xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS)
 1270                 return EACCES;
 1271 
 1272         /* allocation new SP entry */
 1273         if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
 1274                 return error;
 1275 
 1276         newsp->state = IPSEC_SPSTATE_ALIVE;
 1277 
 1278         /* clear old SP and set new SP */
 1279         key_freesp(*pcb_sp);
 1280         *pcb_sp = newsp;
 1281         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1282                 printf("ipsec_set_policy: new policy\n");
 1283                 kdebug_secpolicy(newsp));
 1284 
 1285         return 0;
 1286 }
 1287 
 1288 static int
 1289 ipsec_get_policy(pcb_sp, mp)
 1290         struct secpolicy *pcb_sp;
 1291         struct mbuf **mp;
 1292 {
 1293 
 1294         /* sanity check. */
 1295         if (pcb_sp == NULL || mp == NULL)
 1296                 return EINVAL;
 1297 
 1298         *mp = key_sp2msg(pcb_sp);
 1299         if (!*mp) {
 1300                 ipseclog((LOG_DEBUG, "ipsec_get_policy: No more memory.\n"));
 1301                 return ENOBUFS;
 1302         }
 1303 
 1304         (*mp)->m_type = MT_DATA;
 1305         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1306                 printf("ipsec_get_policy:\n");
 1307                 kdebug_mbuf(*mp));
 1308 
 1309         return 0;
 1310 }
 1311 
 1312 int
 1313 ipsec4_set_policy(inp, optname, request, len, priv)
 1314         struct inpcb *inp;
 1315         int optname;
 1316         caddr_t request;
 1317         size_t len;
 1318         int priv;
 1319 {
 1320         struct sadb_x_policy *xpl;
 1321         struct secpolicy **pcb_sp;
 1322 
 1323         /* sanity check. */
 1324         if (inp == NULL || request == NULL)
 1325                 return EINVAL;
 1326         if (len < sizeof(*xpl))
 1327                 return EINVAL;
 1328         xpl = (struct sadb_x_policy *)request;
 1329 
 1330         /* select direction */
 1331         switch (xpl->sadb_x_policy_dir) {
 1332         case IPSEC_DIR_INBOUND:
 1333                 pcb_sp = &inp->inp_sp->sp_in;
 1334                 break;
 1335         case IPSEC_DIR_OUTBOUND:
 1336                 pcb_sp = &inp->inp_sp->sp_out;
 1337                 break;
 1338         default:
 1339                 ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
 1340                         xpl->sadb_x_policy_dir));
 1341                 return EINVAL;
 1342         }
 1343 
 1344         return ipsec_set_policy(pcb_sp, optname, request, len, priv);
 1345 }
 1346 
 1347 int
 1348 ipsec4_get_policy(inp, request, len, mp)
 1349         struct inpcb *inp;
 1350         caddr_t request;
 1351         size_t len;
 1352         struct mbuf **mp;
 1353 {
 1354         struct sadb_x_policy *xpl;
 1355         struct secpolicy *pcb_sp;
 1356 
 1357         /* sanity check. */
 1358         if (inp == NULL || request == NULL || mp == NULL)
 1359                 return EINVAL;
 1360         if (inp->inp_sp == NULL)
 1361                 panic("policy in PCB is NULL");
 1362         if (len < sizeof(*xpl))
 1363                 return EINVAL;
 1364         xpl = (struct sadb_x_policy *)request;
 1365 
 1366         /* select direction */
 1367         switch (xpl->sadb_x_policy_dir) {
 1368         case IPSEC_DIR_INBOUND:
 1369                 pcb_sp = inp->inp_sp->sp_in;
 1370                 break;
 1371         case IPSEC_DIR_OUTBOUND:
 1372                 pcb_sp = inp->inp_sp->sp_out;
 1373                 break;
 1374         default:
 1375                 ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
 1376                         xpl->sadb_x_policy_dir));
 1377                 return EINVAL;
 1378         }
 1379 
 1380         return ipsec_get_policy(pcb_sp, mp);
 1381 }
 1382 
 1383 /* delete policy in PCB */
 1384 int
 1385 ipsec4_delete_pcbpolicy(inp)
 1386         struct inpcb *inp;
 1387 {
 1388         /* sanity check. */
 1389         if (inp == NULL)
 1390                 panic("ipsec4_delete_pcbpolicy: NULL pointer was passed.");
 1391 
 1392         if (inp->inp_sp == NULL)
 1393                 return 0;
 1394 
 1395         if (inp->inp_sp->sp_in != NULL) {
 1396                 key_freesp(inp->inp_sp->sp_in);
 1397                 inp->inp_sp->sp_in = NULL;
 1398         }
 1399 
 1400         if (inp->inp_sp->sp_out != NULL) {
 1401                 key_freesp(inp->inp_sp->sp_out);
 1402                 inp->inp_sp->sp_out = NULL;
 1403         }
 1404 
 1405         ipsec_delpcbpolicy(inp->inp_sp);
 1406         inp->inp_sp = NULL;
 1407 
 1408         return 0;
 1409 }
 1410 
 1411 #ifdef INET6
 1412 int
 1413 ipsec6_set_policy(in6p, optname, request, len, priv)
 1414         struct in6pcb *in6p;
 1415         int optname;
 1416         caddr_t request;
 1417         size_t len;
 1418         int priv;
 1419 {
 1420         struct sadb_x_policy *xpl;
 1421         struct secpolicy **pcb_sp;
 1422 
 1423         /* sanity check. */
 1424         if (in6p == NULL || request == NULL)
 1425                 return EINVAL;
 1426         if (len < sizeof(*xpl))
 1427                 return EINVAL;
 1428         xpl = (struct sadb_x_policy *)request;
 1429 
 1430         /* select direction */
 1431         switch (xpl->sadb_x_policy_dir) {
 1432         case IPSEC_DIR_INBOUND:
 1433                 pcb_sp = &in6p->in6p_sp->sp_in;
 1434                 break;
 1435         case IPSEC_DIR_OUTBOUND:
 1436                 pcb_sp = &in6p->in6p_sp->sp_out;
 1437                 break;
 1438         default:
 1439                 ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
 1440                         xpl->sadb_x_policy_dir));
 1441                 return EINVAL;
 1442         }
 1443 
 1444         return ipsec_set_policy(pcb_sp, optname, request, len, priv);
 1445 }
 1446 
 1447 int
 1448 ipsec6_get_policy(in6p, request, len, mp)
 1449         struct in6pcb *in6p;
 1450         caddr_t request;
 1451         size_t len;
 1452         struct mbuf **mp;
 1453 {
 1454         struct sadb_x_policy *xpl;
 1455         struct secpolicy *pcb_sp;
 1456 
 1457         /* sanity check. */
 1458         if (in6p == NULL || request == NULL || mp == NULL)
 1459                 return EINVAL;
 1460         if (in6p->in6p_sp == NULL)
 1461                 panic("policy in PCB is NULL");
 1462         if (len < sizeof(*xpl))
 1463                 return EINVAL;
 1464         xpl = (struct sadb_x_policy *)request;
 1465 
 1466         /* select direction */
 1467         switch (xpl->sadb_x_policy_dir) {
 1468         case IPSEC_DIR_INBOUND:
 1469                 pcb_sp = in6p->in6p_sp->sp_in;
 1470                 break;
 1471         case IPSEC_DIR_OUTBOUND:
 1472                 pcb_sp = in6p->in6p_sp->sp_out;
 1473                 break;
 1474         default:
 1475                 ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
 1476                         xpl->sadb_x_policy_dir));
 1477                 return EINVAL;
 1478         }
 1479 
 1480         return ipsec_get_policy(pcb_sp, mp);
 1481 }
 1482 
 1483 int
 1484 ipsec6_delete_pcbpolicy(in6p)
 1485         struct in6pcb *in6p;
 1486 {
 1487         /* sanity check. */
 1488         if (in6p == NULL)
 1489                 panic("ipsec6_delete_pcbpolicy: NULL pointer was passed.");
 1490 
 1491         if (in6p->in6p_sp == NULL)
 1492                 return 0;
 1493 
 1494         if (in6p->in6p_sp->sp_in != NULL) {
 1495                 key_freesp(in6p->in6p_sp->sp_in);
 1496                 in6p->in6p_sp->sp_in = NULL;
 1497         }
 1498 
 1499         if (in6p->in6p_sp->sp_out != NULL) {
 1500                 key_freesp(in6p->in6p_sp->sp_out);
 1501                 in6p->in6p_sp->sp_out = NULL;
 1502         }
 1503 
 1504         ipsec_delpcbpolicy(in6p->in6p_sp);
 1505         in6p->in6p_sp = NULL;
 1506 
 1507         return 0;
 1508 }
 1509 #endif
 1510 
 1511 /*
 1512  * return current level.
 1513  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
 1514  */
 1515 u_int
 1516 ipsec_get_reqlevel(isr)
 1517         struct ipsecrequest *isr;
 1518 {
 1519         u_int level = 0;
 1520         u_int esp_trans_deflev, esp_net_deflev, ah_trans_deflev, ah_net_deflev;
 1521 
 1522         /* sanity check */
 1523         if (isr == NULL || isr->sp == NULL)
 1524                 panic("ipsec_get_reqlevel: NULL pointer is passed.");
 1525         if (((struct sockaddr *)&isr->sp->spidx.src)->sa_family
 1526                         != ((struct sockaddr *)&isr->sp->spidx.dst)->sa_family)
 1527                 panic("ipsec_get_reqlevel: family mismatched.");
 1528 
 1529 /* XXX note that we have ipseclog() expanded here - code sync issue */
 1530 #define IPSEC_CHECK_DEFAULT(lev) \
 1531         (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE            \
 1532                         && (lev) != IPSEC_LEVEL_UNIQUE)                       \
 1533                 ? (ipsec_debug                                                \
 1534                         ? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
 1535                                 (lev), IPSEC_LEVEL_REQUIRE)                   \
 1536                         : 0),                                                 \
 1537                         (lev) = IPSEC_LEVEL_REQUIRE,                          \
 1538                         (lev)                                                 \
 1539                 : (lev))
 1540 
 1541         /* set default level */
 1542         switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
 1543 #ifdef INET
 1544         case AF_INET:
 1545                 esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
 1546                 esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
 1547                 ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
 1548                 ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
 1549                 break;
 1550 #endif
 1551 #ifdef INET6
 1552         case AF_INET6:
 1553                 esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
 1554                 esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
 1555                 ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
 1556                 ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
 1557                 break;
 1558 #endif /* INET6 */
 1559         default:
 1560                 panic("key_get_reqlevel: Unknown family. %d",
 1561                         ((struct sockaddr *)&isr->sp->spidx.src)->sa_family);
 1562         }
 1563 
 1564 #undef IPSEC_CHECK_DEFAULT
 1565 
 1566         /* set level */
 1567         switch (isr->level) {
 1568         case IPSEC_LEVEL_DEFAULT:
 1569                 switch (isr->saidx.proto) {
 1570                 case IPPROTO_ESP:
 1571                         if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
 1572                                 level = esp_net_deflev;
 1573                         else
 1574                                 level = esp_trans_deflev;
 1575                         break;
 1576                 case IPPROTO_AH:
 1577                         if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
 1578                                 level = ah_net_deflev;
 1579                         else
 1580                                 level = ah_trans_deflev;
 1581                 case IPPROTO_IPCOMP:
 1582                         /*
 1583                          * we don't really care, as IPcomp document says that
 1584                          * we shouldn't compress small packets
 1585                          */
 1586                         level = IPSEC_LEVEL_USE;
 1587                         break;
 1588                 default:
 1589                         panic("ipsec_get_reqlevel: "
 1590                                 "Illegal protocol defined %u",
 1591                                 isr->saidx.proto);
 1592                 }
 1593                 break;
 1594 
 1595         case IPSEC_LEVEL_USE:
 1596         case IPSEC_LEVEL_REQUIRE:
 1597                 level = isr->level;
 1598                 break;
 1599         case IPSEC_LEVEL_UNIQUE:
 1600                 level = IPSEC_LEVEL_REQUIRE;
 1601                 break;
 1602 
 1603         default:
 1604                 panic("ipsec_get_reqlevel: Illegal IPsec level %u",
 1605                         isr->level);
 1606         }
 1607 
 1608         return level;
 1609 }
 1610 
 1611 /*
 1612  * Check AH/ESP integrity.
 1613  * OUT:
 1614  *      0: valid
 1615  *      1: invalid
 1616  */
 1617 static int
 1618 ipsec_in_reject(sp, m)
 1619         struct secpolicy *sp;
 1620         struct mbuf *m;
 1621 {
 1622         struct ipsecrequest *isr;
 1623         u_int level;
 1624         int need_auth, need_conf, need_icv;
 1625 
 1626         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 1627                 printf("ipsec_in_reject: using SP\n");
 1628                 kdebug_secpolicy(sp));
 1629 
 1630         /* check policy */
 1631         switch (sp->policy) {
 1632         case IPSEC_POLICY_DISCARD:
 1633                 return 1;
 1634         case IPSEC_POLICY_BYPASS:
 1635         case IPSEC_POLICY_NONE:
 1636                 return 0;
 1637         
 1638         case IPSEC_POLICY_IPSEC:
 1639                 break;
 1640 
 1641         case IPSEC_POLICY_ENTRUST:
 1642         default:
 1643                 panic("ipsec_hdrsiz: Invalid policy found. %d", sp->policy);
 1644         }
 1645 
 1646         need_auth = 0;
 1647         need_conf = 0;
 1648         need_icv = 0;
 1649 
 1650         /* XXX should compare policy against ipsec header history */
 1651 
 1652         for (isr = sp->req; isr != NULL; isr = isr->next) {
 1653 
 1654                 /* get current level */
 1655                 level = ipsec_get_reqlevel(isr);
 1656 
 1657                 switch (isr->saidx.proto) {
 1658                 case IPPROTO_ESP:
 1659                         if (level == IPSEC_LEVEL_REQUIRE) {
 1660                                 need_conf++;
 1661 
 1662                                 if (isr->sav != NULL
 1663                                  && isr->sav->flags == SADB_X_EXT_NONE
 1664                                  && isr->sav->alg_auth != SADB_AALG_NONE)
 1665                                         need_icv++;
 1666                         }
 1667                         break;
 1668                 case IPPROTO_AH:
 1669                         if (level == IPSEC_LEVEL_REQUIRE) {
 1670                                 need_auth++;
 1671                                 need_icv++;
 1672                         }
 1673                         break;
 1674                 case IPPROTO_IPCOMP:
 1675                         /*
 1676                          * we don't really care, as IPcomp document says that
 1677                          * we shouldn't compress small packets, IPComp policy
 1678                          * should always be treated as being in "use" level.
 1679                          */
 1680                         break;
 1681                 }
 1682         }
 1683 
 1684         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
 1685                 printf("ipsec_in_reject: auth:%d conf:%d icv:%d m_flags:%x\n",
 1686                         need_auth, need_conf, need_icv, m->m_flags));
 1687 
 1688         if ((need_conf && !(m->m_flags & M_DECRYPTED))
 1689          || (!need_auth && need_icv && !(m->m_flags & M_AUTHIPDGM))
 1690          || (need_auth && !(m->m_flags & M_AUTHIPHDR)))
 1691                 return 1;
 1692 
 1693         return 0;
 1694 }
 1695 
 1696 /*
 1697  * Check AH/ESP integrity.
 1698  * This function is called from tcp_input(), udp_input(),
 1699  * and {ah,esp}4_input for tunnel mode
 1700  */
 1701 int
 1702 ipsec4_in_reject(m, inp)
 1703         struct mbuf *m;
 1704         struct inpcb *inp;
 1705 {
 1706         struct secpolicy *sp = NULL;
 1707         int error;
 1708         int result;
 1709 
 1710         /* sanity check */
 1711         if (m == NULL)
 1712                 return 0;       /* XXX should be panic ? */
 1713 
 1714         /* get SP for this packet.
 1715          * When we are called from ip_forward(), we call
 1716          * ipsec4_getpolicybyaddr() with IP_FORWARDING flag.
 1717          */
 1718         if (inp == NULL)
 1719                 sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
 1720         else
 1721                 sp = ipsec4_getpolicybypcb(m, IPSEC_DIR_INBOUND, inp, &error);
 1722 
 1723         if (sp == NULL)
 1724                 return 0;       /* XXX should be panic ?
 1725                                  * -> No, there may be error. */
 1726 
 1727         result = ipsec_in_reject(sp, m);
 1728         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1729                 printf("DP ipsec4_in_reject_so call free SP:%p\n", sp));
 1730         key_freesp(sp);
 1731 
 1732         return result;
 1733 }
 1734 
 1735 int
 1736 ipsec4_in_reject_so(m, so)
 1737         struct mbuf *m;
 1738         struct socket *so;
 1739 {
 1740         if (so == NULL)
 1741                 return ipsec4_in_reject(m, NULL);
 1742         return ipsec4_in_reject(m, sotoinpcb(so));
 1743 }
 1744 
 1745 
 1746 #ifdef INET6
 1747 /*
 1748  * Check AH/ESP integrity.
 1749  * This function is called from tcp6_input(), udp6_input(),
 1750  * and {ah,esp}6_input for tunnel mode
 1751  */
 1752 int
 1753 ipsec6_in_reject(m, in6p)
 1754         struct mbuf *m;
 1755         struct in6pcb *in6p;
 1756 {
 1757         struct secpolicy *sp = NULL;
 1758         int error;
 1759         int result;
 1760 
 1761         /* sanity check */
 1762         if (m == NULL)
 1763                 return 0;       /* XXX should be panic ? */
 1764 
 1765         /* get SP for this packet.
 1766          * When we are called from ip_forward(), we call
 1767          * ipsec6_getpolicybyaddr() with IP_FORWARDING flag.
 1768          */
 1769         if (in6p == NULL)
 1770                 sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
 1771         else
 1772                 sp = ipsec6_getpolicybypcb(m, IPSEC_DIR_INBOUND, in6p, &error);
 1773 
 1774         if (sp == NULL)
 1775                 return 0;       /* XXX should be panic ? */
 1776 
 1777         result = ipsec_in_reject(sp, m);
 1778         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1779                 printf("DP ipsec6_in_reject call free SP:%p\n", sp));
 1780         key_freesp(sp);
 1781 
 1782         return result;
 1783 }
 1784 
 1785 int
 1786 ipsec6_in_reject_so(m, so)
 1787         struct mbuf *m;
 1788         struct socket *so;
 1789 {
 1790         if (so == NULL)
 1791                 return ipsec6_in_reject(m, NULL);
 1792         return ipsec6_in_reject(m, sotoin6pcb(so));
 1793 }
 1794 #endif
 1795 
 1796 /*
 1797  * compute the byte size to be occupied by IPsec header.
 1798  * in case it is tunneled, it includes the size of outer IP header.
 1799  * NOTE: SP passed is free in this function.
 1800  */
 1801 static size_t
 1802 ipsec_hdrsiz(sp)
 1803         struct secpolicy *sp;
 1804 {
 1805         struct ipsecrequest *isr;
 1806         size_t siz, clen;
 1807 
 1808         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 1809                 printf("ipsec_hdrsiz: using SP\n");
 1810                 kdebug_secpolicy(sp));
 1811 
 1812         /* check policy */
 1813         switch (sp->policy) {
 1814         case IPSEC_POLICY_DISCARD:
 1815         case IPSEC_POLICY_BYPASS:
 1816         case IPSEC_POLICY_NONE:
 1817                 return 0;
 1818         
 1819         case IPSEC_POLICY_IPSEC:
 1820                 break;
 1821 
 1822         case IPSEC_POLICY_ENTRUST:
 1823         default:
 1824                 panic("ipsec_hdrsiz: Invalid policy found. %d", sp->policy);
 1825         }
 1826 
 1827         siz = 0;
 1828 
 1829         for (isr = sp->req; isr != NULL; isr = isr->next) {
 1830 
 1831                 clen = 0;
 1832 
 1833                 switch (isr->saidx.proto) {
 1834                 case IPPROTO_ESP:
 1835 #ifdef IPSEC_ESP
 1836                         clen = esp_hdrsiz(isr);
 1837 #else
 1838                         clen = 0;       /* XXX */
 1839 #endif
 1840                         break;
 1841                 case IPPROTO_AH:
 1842                         clen = ah_hdrsiz(isr);
 1843                         break;
 1844                 case IPPROTO_IPCOMP:
 1845                         clen = sizeof(struct ipcomp);
 1846                         break;
 1847                 }
 1848 
 1849                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
 1850                         switch (((struct sockaddr *)&isr->saidx.dst)->sa_family) {
 1851                         case AF_INET:
 1852                                 clen += sizeof(struct ip);
 1853                                 break;
 1854 #ifdef INET6
 1855                         case AF_INET6:
 1856                                 clen += sizeof(struct ip6_hdr);
 1857                                 break;
 1858 #endif
 1859                         default:
 1860                                 ipseclog((LOG_ERR, "ipsec_hdrsiz: "
 1861                                     "unknown AF %d in IPsec tunnel SA\n",
 1862                                     ((struct sockaddr *)&isr->saidx.dst)->sa_family));
 1863                                 break;
 1864                         }
 1865                 }
 1866                 siz += clen;
 1867         }
 1868 
 1869         return siz;
 1870 }
 1871 
 1872 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
 1873 size_t
 1874 ipsec4_hdrsiz(m, dir, inp)
 1875         struct mbuf *m;
 1876         u_int dir;
 1877         struct inpcb *inp;
 1878 {
 1879         struct secpolicy *sp = NULL;
 1880         int error;
 1881         size_t size;
 1882 
 1883         /* sanity check */
 1884         if (m == NULL)
 1885                 return 0;       /* XXX should be panic ? */
 1886 #if 0
 1887         /* this is possible in TIME_WAIT state */
 1888         if (inp != NULL && inp->inp_socket == NULL)
 1889                 panic("ipsec4_hdrsize: why is socket NULL but there is PCB.");
 1890 #endif
 1891 
 1892         /* get SP for this packet.
 1893          * When we are called from ip_forward(), we call
 1894          * ipsec4_getpolicybyaddr() with IP_FORWARDING flag.
 1895          */
 1896         if (inp == NULL)
 1897                 sp = ipsec4_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
 1898         else
 1899                 sp = ipsec4_getpolicybypcb(m, dir, inp, &error);
 1900 
 1901         if (sp == NULL)
 1902                 return 0;       /* XXX should be panic ? */
 1903 
 1904         size = ipsec_hdrsiz(sp);
 1905         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1906                 printf("DP ipsec4_hdrsiz call free SP:%p\n", sp));
 1907         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 1908                 printf("ipsec4_hdrsiz: size:%lu.\n", (unsigned long)size));
 1909         key_freesp(sp);
 1910 
 1911         return size;
 1912 }
 1913 
 1914 #ifdef INET6
 1915 /* This function is called from ipsec6_hdrsize_tcp(),
 1916  * and maybe from ip6_forward.()
 1917  */
 1918 size_t
 1919 ipsec6_hdrsiz(m, dir, in6p)
 1920         struct mbuf *m;
 1921         u_int dir;
 1922         struct in6pcb *in6p;
 1923 {
 1924         struct secpolicy *sp = NULL;
 1925         int error;
 1926         size_t size;
 1927 
 1928         /* sanity check */
 1929         if (m == NULL)
 1930                 return 0;       /* XXX shoud be panic ? */
 1931 #if 0
 1932         /* this is possible in TIME_WAIT state */
 1933         if (in6p != NULL && in6p->in6p_socket == NULL)
 1934                 panic("ipsec6_hdrsize: why is socket NULL but there is PCB.");
 1935 #endif
 1936 
 1937         /* get SP for this packet */
 1938         /* XXX Is it right to call with IP_FORWARDING. */
 1939         if (in6p == NULL)
 1940                 sp = ipsec6_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
 1941         else
 1942                 sp = ipsec6_getpolicybypcb(m, dir, in6p, &error);
 1943 
 1944         if (sp == NULL)
 1945                 return 0;
 1946         size = ipsec_hdrsiz(sp);
 1947         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1948                 printf("DP ipsec6_hdrsiz call free SP:%p\n", sp));
 1949         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 1950                 printf("ipsec6_hdrsiz: size:%lu.\n", (unsigned long)size));
 1951         key_freesp(sp);
 1952 
 1953         return size;
 1954 }
 1955 #endif /* INET6 */
 1956 
 1957 #ifdef INET
 1958 /*
 1959  * encapsulate for ipsec tunnel.
 1960  * ip->ip_src must be fixed later on.
 1961  */
 1962 static int
 1963 ipsec4_encapsulate(m, sav)
 1964         struct mbuf *m;
 1965         struct secasvar *sav;
 1966 {
 1967         struct ip *oip;
 1968         struct ip *ip;
 1969         size_t hlen;
 1970         size_t plen;
 1971 
 1972         /* can't tunnel between different AFs */
 1973         if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family
 1974                 != ((struct sockaddr *)&sav->sah->saidx.dst)->sa_family
 1975          || ((struct sockaddr *)&sav->sah->saidx.src)->sa_family != AF_INET) {
 1976                 m_freem(m);
 1977                 return EINVAL;
 1978         }
 1979 #if 0
 1980         /* XXX if the dst is myself, perform nothing. */
 1981         if (key_ismyaddr((struct sockaddr *)&sav->sah->saidx.dst)) {
 1982                 m_freem(m);
 1983                 return EINVAL;
 1984         }
 1985 #endif
 1986 
 1987         if (m->m_len < sizeof(*ip))
 1988                 panic("ipsec4_encapsulate: assumption failed (first mbuf length)");
 1989 
 1990         ip = mtod(m, struct ip *);
 1991 #ifdef _IP_VHL
 1992         hlen = _IP_VHL_HL(ip->ip_vhl) << 2;
 1993 #else
 1994         hlen = ip->ip_hl << 2;
 1995 #endif
 1996 
 1997         if (m->m_len != hlen)
 1998                 panic("ipsec4_encapsulate: assumption failed (first mbuf length)");
 1999 
 2000         /* generate header checksum */
 2001         ip->ip_sum = 0;
 2002 #ifdef _IP_VHL
 2003         if (ip->ip_vhl == IP_VHL_BORING)
 2004                 ip->ip_sum = in_cksum_hdr(ip);
 2005         else
 2006                 ip->ip_sum = in_cksum(m, hlen);
 2007 #else
 2008         ip->ip_sum = in_cksum(m, hlen);
 2009 #endif
 2010 
 2011         plen = m->m_pkthdr.len;
 2012 
 2013         /*
 2014          * grow the mbuf to accomodate the new IPv4 header.
 2015          * NOTE: IPv4 options will never be copied.
 2016          */
 2017         if (M_LEADINGSPACE(m->m_next) < hlen) {
 2018                 struct mbuf *n;
 2019                 MGET(n, M_DONTWAIT, MT_DATA);
 2020                 if (!n) {
 2021                         m_freem(m);
 2022                         return ENOBUFS;
 2023                 }
 2024                 n->m_len = hlen;
 2025                 n->m_next = m->m_next;
 2026                 m->m_next = n;
 2027                 m->m_pkthdr.len += hlen;
 2028                 oip = mtod(n, struct ip *);
 2029         } else {
 2030                 m->m_next->m_len += hlen;
 2031                 m->m_next->m_data -= hlen;
 2032                 m->m_pkthdr.len += hlen;
 2033                 oip = mtod(m->m_next, struct ip *);
 2034         }
 2035         ip = mtod(m, struct ip *);
 2036         ovbcopy((caddr_t)ip, (caddr_t)oip, hlen);
 2037         m->m_len = sizeof(struct ip);
 2038         m->m_pkthdr.len -= (hlen - sizeof(struct ip));
 2039 
 2040         /* construct new IPv4 header. see RFC 2401 5.1.2.1 */
 2041         /* ECN consideration. */
 2042         ip_ecn_ingress(ip4_ipsec_ecn, &ip->ip_tos, &oip->ip_tos);
 2043 #ifdef _IP_VHL
 2044         ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
 2045 #else
 2046         ip->ip_hl = sizeof(struct ip) >> 2;
 2047 #endif
 2048         ip->ip_off &= htons(~IP_OFFMASK);
 2049         ip->ip_off &= htons(~IP_MF);
 2050         switch (ip4_ipsec_dfbit) {
 2051         case 0: /* clear DF bit */
 2052                 ip->ip_off &= htons(~IP_DF);
 2053                 break;
 2054         case 1: /* set DF bit */
 2055                 ip->ip_off |= htons(IP_DF);
 2056                 break;
 2057         default:        /* copy DF bit */
 2058                 break;
 2059         }
 2060         ip->ip_p = IPPROTO_IPIP;
 2061         if (plen + sizeof(struct ip) < IP_MAXPACKET)
 2062                 ip->ip_len = htons(plen + sizeof(struct ip));
 2063         else {
 2064                 ipseclog((LOG_ERR, "IPv4 ipsec: size exceeds limit: "
 2065                         "leave ip_len as is (invalid packet)\n"));
 2066         }
 2067 #ifdef RANDOM_IP_ID
 2068         ip->ip_id = ip_randomid();
 2069 #else
 2070         ip->ip_id = htons(ip_id++);
 2071 #endif
 2072         bcopy(&((struct sockaddr_in *)&sav->sah->saidx.src)->sin_addr,
 2073                 &ip->ip_src, sizeof(ip->ip_src));
 2074         bcopy(&((struct sockaddr_in *)&sav->sah->saidx.dst)->sin_addr,
 2075                 &ip->ip_dst, sizeof(ip->ip_dst));
 2076         ip->ip_ttl = IPDEFTTL;
 2077 
 2078         /* XXX Should ip_src be updated later ? */
 2079 
 2080         return 0;
 2081 }
 2082 #endif /* INET */
 2083 
 2084 #ifdef INET6
 2085 static int
 2086 ipsec6_encapsulate(m, sav)
 2087         struct mbuf *m;
 2088         struct secasvar *sav;
 2089 {
 2090         struct ip6_hdr *oip6;
 2091         struct ip6_hdr *ip6;
 2092         size_t plen;
 2093 
 2094         /* can't tunnel between different AFs */
 2095         if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family
 2096                 != ((struct sockaddr *)&sav->sah->saidx.dst)->sa_family
 2097          || ((struct sockaddr *)&sav->sah->saidx.src)->sa_family != AF_INET6) {
 2098                 m_freem(m);
 2099                 return EINVAL;
 2100         }
 2101 #if 0
 2102         /* XXX if the dst is myself, perform nothing. */
 2103         if (key_ismyaddr((struct sockaddr *)&sav->sah->saidx.dst)) {
 2104                 m_freem(m);
 2105                 return EINVAL;
 2106         }
 2107 #endif
 2108 
 2109         plen = m->m_pkthdr.len;
 2110 
 2111         /*
 2112          * grow the mbuf to accomodate the new IPv6 header.
 2113          */
 2114         if (m->m_len != sizeof(struct ip6_hdr))
 2115                 panic("ipsec6_encapsulate: assumption failed (first mbuf length)");
 2116         if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
 2117                 struct mbuf *n;
 2118                 MGET(n, M_DONTWAIT, MT_DATA);
 2119                 if (!n) {
 2120                         m_freem(m);
 2121                         return ENOBUFS;
 2122                 }
 2123                 n->m_len = sizeof(struct ip6_hdr);
 2124                 n->m_next = m->m_next;
 2125                 m->m_next = n;
 2126                 m->m_pkthdr.len += sizeof(struct ip6_hdr);
 2127                 oip6 = mtod(n, struct ip6_hdr *);
 2128         } else {
 2129                 m->m_next->m_len += sizeof(struct ip6_hdr);
 2130                 m->m_next->m_data -= sizeof(struct ip6_hdr);
 2131                 m->m_pkthdr.len += sizeof(struct ip6_hdr);
 2132                 oip6 = mtod(m->m_next, struct ip6_hdr *);
 2133         }
 2134         ip6 = mtod(m, struct ip6_hdr *);
 2135         ovbcopy((caddr_t)ip6, (caddr_t)oip6, sizeof(struct ip6_hdr));
 2136 
 2137         /* Fake link-local scope-class addresses */
 2138         if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_src))
 2139                 oip6->ip6_src.s6_addr16[1] = 0;
 2140         if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_dst))
 2141                 oip6->ip6_dst.s6_addr16[1] = 0;
 2142 
 2143         /* construct new IPv6 header. see RFC 2401 5.1.2.2 */
 2144         /* ECN consideration. */
 2145         ip6_ecn_ingress(ip6_ipsec_ecn, &ip6->ip6_flow, &oip6->ip6_flow);
 2146         if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr))
 2147                 ip6->ip6_plen = htons(plen);
 2148         else {
 2149                 /* ip6->ip6_plen will be updated in ip6_output() */
 2150         }
 2151         ip6->ip6_nxt = IPPROTO_IPV6;
 2152         bcopy(&((struct sockaddr_in6 *)&sav->sah->saidx.src)->sin6_addr,
 2153                 &ip6->ip6_src, sizeof(ip6->ip6_src));
 2154         bcopy(&((struct sockaddr_in6 *)&sav->sah->saidx.dst)->sin6_addr,
 2155                 &ip6->ip6_dst, sizeof(ip6->ip6_dst));
 2156         ip6->ip6_hlim = IPV6_DEFHLIM;
 2157 
 2158         /* XXX Should ip6_src be updated later ? */
 2159 
 2160         return 0;
 2161 }
 2162 #endif /* INET6 */
 2163 
 2164 /*
 2165  * Check the variable replay window.
 2166  * ipsec_chkreplay() performs replay check before ICV verification.
 2167  * ipsec_updatereplay() updates replay bitmap.  This must be called after
 2168  * ICV verification (it also performs replay check, which is usually done
 2169  * beforehand).
 2170  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
 2171  *
 2172  * based on RFC 2401.
 2173  */
 2174 int
 2175 ipsec_chkreplay(seq, sav)
 2176         u_int32_t seq;
 2177         struct secasvar *sav;
 2178 {
 2179         const struct secreplay *replay;
 2180         u_int32_t diff;
 2181         int fr;
 2182         u_int32_t wsizeb;       /* constant: bits of window size */
 2183         int frlast;             /* constant: last frame */
 2184 
 2185         /* sanity check */
 2186         if (sav == NULL)
 2187                 panic("ipsec_chkreplay: NULL pointer was passed.");
 2188 
 2189         replay = sav->replay;
 2190 
 2191         if (replay->wsize == 0)
 2192                 return 1;       /* no need to check replay. */
 2193 
 2194         /* constant */
 2195         frlast = replay->wsize - 1;
 2196         wsizeb = replay->wsize << 3;
 2197 
 2198         /* sequence number of 0 is invalid */
 2199         if (seq == 0)
 2200                 return 0;
 2201 
 2202         /* first time is always okay */
 2203         if (replay->count == 0)
 2204                 return 1;
 2205 
 2206         if (seq > replay->lastseq) {
 2207                 /* larger sequences are okay */
 2208                 return 1;
 2209         } else {
 2210                 /* seq is equal or less than lastseq. */
 2211                 diff = replay->lastseq - seq;
 2212 
 2213                 /* over range to check, i.e. too old or wrapped */
 2214                 if (diff >= wsizeb)
 2215                         return 0;
 2216 
 2217                 fr = frlast - diff / 8;
 2218 
 2219                 /* this packet already seen ? */
 2220                 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
 2221                         return 0;
 2222 
 2223                 /* out of order but good */
 2224                 return 1;
 2225         }
 2226 }
 2227 
 2228 /*
 2229  * check replay counter whether to update or not.
 2230  * OUT: 0:      OK
 2231  *      1:      NG
 2232  */
 2233 int
 2234 ipsec_updatereplay(seq, sav)
 2235         u_int32_t seq;
 2236         struct secasvar *sav;
 2237 {
 2238         struct secreplay *replay;
 2239         u_int32_t diff;
 2240         int fr;
 2241         u_int32_t wsizeb;       /* constant: bits of window size */
 2242         int frlast;             /* constant: last frame */
 2243 
 2244         /* sanity check */
 2245         if (sav == NULL)
 2246                 panic("ipsec_chkreplay: NULL pointer was passed.");
 2247 
 2248         replay = sav->replay;
 2249 
 2250         if (replay->wsize == 0)
 2251                 goto ok;        /* no need to check replay. */
 2252 
 2253         /* constant */
 2254         frlast = replay->wsize - 1;
 2255         wsizeb = replay->wsize << 3;
 2256 
 2257         /* sequence number of 0 is invalid */
 2258         if (seq == 0)
 2259                 return 1;
 2260 
 2261         /* first time */
 2262         if (replay->count == 0) {
 2263                 replay->lastseq = seq;
 2264                 bzero(replay->bitmap, replay->wsize);
 2265                 (replay->bitmap)[frlast] = 1;
 2266                 goto ok;
 2267         }
 2268 
 2269         if (seq > replay->lastseq) {
 2270                 /* seq is larger than lastseq. */
 2271                 diff = seq - replay->lastseq;
 2272 
 2273                 /* new larger sequence number */
 2274                 if (diff < wsizeb) {
 2275                         /* In window */
 2276                         /* set bit for this packet */
 2277                         vshiftl(replay->bitmap, diff, replay->wsize);
 2278                         (replay->bitmap)[frlast] |= 1;
 2279                 } else {
 2280                         /* this packet has a "way larger" */
 2281                         bzero(replay->bitmap, replay->wsize);
 2282                         (replay->bitmap)[frlast] = 1;
 2283                 }
 2284                 replay->lastseq = seq;
 2285 
 2286                 /* larger is good */
 2287         } else {
 2288                 /* seq is equal or less than lastseq. */
 2289                 diff = replay->lastseq - seq;
 2290 
 2291                 /* over range to check, i.e. too old or wrapped */
 2292                 if (diff >= wsizeb)
 2293                         return 1;
 2294 
 2295                 fr = frlast - diff / 8;
 2296 
 2297                 /* this packet already seen ? */
 2298                 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
 2299                         return 1;
 2300 
 2301                 /* mark as seen */
 2302                 (replay->bitmap)[fr] |= (1 << (diff % 8));
 2303 
 2304                 /* out of order but good */
 2305         }
 2306 
 2307 ok:
 2308         if (replay->count == ~0) {
 2309 
 2310                 /* set overflow flag */
 2311                 replay->overflow++;
 2312 
 2313                 /* don't increment, no more packets accepted */
 2314                 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
 2315                         return 1;
 2316 
 2317                 ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
 2318                     replay->overflow, ipsec_logsastr(sav)));
 2319         }
 2320 
 2321         replay->count++;
 2322 
 2323         return 0;
 2324 }
 2325 
 2326 /*
 2327  * shift variable length buffer to left.
 2328  * IN:  bitmap: pointer to the buffer
 2329  *      nbit:   the number of to shift.
 2330  *      wsize:  buffer size (bytes).
 2331  */
 2332 static void
 2333 vshiftl(bitmap, nbit, wsize)
 2334         unsigned char *bitmap;
 2335         int nbit, wsize;
 2336 {
 2337         int s, j, i;
 2338         unsigned char over;
 2339 
 2340         for (j = 0; j < nbit; j += 8) {
 2341                 s = (nbit - j < 8) ? (nbit - j): 8;
 2342                 bitmap[0] <<= s;
 2343                 for (i = 1; i < wsize; i++) {
 2344                         over = (bitmap[i] >> (8 - s));
 2345                         bitmap[i] <<= s;
 2346                         bitmap[i-1] |= over;
 2347                 }
 2348         }
 2349 
 2350         return;
 2351 }
 2352 
 2353 const char *
 2354 ipsec4_logpacketstr(ip, spi)
 2355         struct ip *ip;
 2356         u_int32_t spi;
 2357 {
 2358         static char buf[256];
 2359         char *p;
 2360         u_int8_t *s, *d;
 2361 
 2362         s = (u_int8_t *)(&ip->ip_src);
 2363         d = (u_int8_t *)(&ip->ip_dst);
 2364 
 2365         p = buf;
 2366         snprintf(buf, sizeof(buf), "packet(SPI=%u ", (u_int32_t)ntohl(spi));
 2367         while (p && *p)
 2368                 p++;
 2369         snprintf(p, sizeof(buf) - (p - buf), "src=%u.%u.%u.%u",
 2370                 s[0], s[1], s[2], s[3]);
 2371         while (p && *p)
 2372                 p++;
 2373         snprintf(p, sizeof(buf) - (p - buf), " dst=%u.%u.%u.%u",
 2374                 d[0], d[1], d[2], d[3]);
 2375         while (p && *p)
 2376                 p++;
 2377         snprintf(p, sizeof(buf) - (p - buf), ")");
 2378 
 2379         return buf;
 2380 }
 2381 
 2382 #ifdef INET6
 2383 const char *
 2384 ipsec6_logpacketstr(ip6, spi)
 2385         struct ip6_hdr *ip6;
 2386         u_int32_t spi;
 2387 {
 2388         static char buf[256];
 2389         char *p;
 2390 
 2391         p = buf;
 2392         snprintf(buf, sizeof(buf), "packet(SPI=%u ", (u_int32_t)ntohl(spi));
 2393         while (p && *p)
 2394                 p++;
 2395         snprintf(p, sizeof(buf) - (p - buf), "src=%s",
 2396                 ip6_sprintf(&ip6->ip6_src));
 2397         while (p && *p)
 2398                 p++;
 2399         snprintf(p, sizeof(buf) - (p - buf), " dst=%s",
 2400                 ip6_sprintf(&ip6->ip6_dst));
 2401         while (p && *p)
 2402                 p++;
 2403         snprintf(p, sizeof(buf) - (p - buf), ")");
 2404 
 2405         return buf;
 2406 }
 2407 #endif /* INET6 */
 2408 
 2409 const char *
 2410 ipsec_logsastr(sav)
 2411         struct secasvar *sav;
 2412 {
 2413         static char buf[256];
 2414         char *p;
 2415         struct secasindex *saidx = &sav->sah->saidx;
 2416 
 2417         /* validity check */
 2418         if (((struct sockaddr *)&sav->sah->saidx.src)->sa_family
 2419                         != ((struct sockaddr *)&sav->sah->saidx.dst)->sa_family)
 2420                 panic("ipsec_logsastr: family mismatched.");
 2421 
 2422         p = buf;
 2423         snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
 2424         while (p && *p)
 2425                 p++;
 2426         if (((struct sockaddr *)&saidx->src)->sa_family == AF_INET) {
 2427                 u_int8_t *s, *d;
 2428                 s = (u_int8_t *)&((struct sockaddr_in *)&saidx->src)->sin_addr;
 2429                 d = (u_int8_t *)&((struct sockaddr_in *)&saidx->dst)->sin_addr;
 2430                 snprintf(p, sizeof(buf) - (p - buf),
 2431                         "src=%d.%d.%d.%d dst=%d.%d.%d.%d",
 2432                         s[0], s[1], s[2], s[3], d[0], d[1], d[2], d[3]);
 2433         }
 2434 #ifdef INET6
 2435         else if (((struct sockaddr *)&saidx->src)->sa_family == AF_INET6) {
 2436                 snprintf(p, sizeof(buf) - (p - buf),
 2437                         "src=%s",
 2438                         ip6_sprintf(&((struct sockaddr_in6 *)&saidx->src)->sin6_addr));
 2439                 while (p && *p)
 2440                         p++;
 2441                 snprintf(p, sizeof(buf) - (p - buf),
 2442                         " dst=%s",
 2443                         ip6_sprintf(&((struct sockaddr_in6 *)&saidx->dst)->sin6_addr));
 2444         }
 2445 #endif
 2446         while (p && *p)
 2447                 p++;
 2448         snprintf(p, sizeof(buf) - (p - buf), ")");
 2449 
 2450         return buf;
 2451 }
 2452 
 2453 void
 2454 ipsec_dumpmbuf(m)
 2455         struct mbuf *m;
 2456 {
 2457         int totlen;
 2458         int i;
 2459         u_char *p;
 2460 
 2461         totlen = 0;
 2462         printf("---\n");
 2463         while (m) {
 2464                 p = mtod(m, u_char *);
 2465                 for (i = 0; i < m->m_len; i++) {
 2466                         printf("%02x ", p[i]);
 2467                         totlen++;
 2468                         if (totlen % 16 == 0)
 2469                                 printf("\n");
 2470                 }
 2471                 m = m->m_next;
 2472         }
 2473         if (totlen % 16 != 0)
 2474                 printf("\n");
 2475         printf("---\n");
 2476 }
 2477 
 2478 #ifdef INET
 2479 /*
 2480  * IPsec output logic for IPv4.
 2481  */
 2482 int
 2483 ipsec4_output(state, sp, flags)
 2484         struct ipsec_output_state *state;
 2485         struct secpolicy *sp;
 2486         int flags;
 2487 {
 2488         struct ip *ip = NULL;
 2489         struct ipsecrequest *isr = NULL;
 2490         struct secasindex saidx;
 2491         int s;
 2492         int error;
 2493         struct sockaddr_in *dst4;
 2494         struct sockaddr_in *sin;
 2495 
 2496         if (!state)
 2497                 panic("state == NULL in ipsec4_output");
 2498         if (!state->m)
 2499                 panic("state->m == NULL in ipsec4_output");
 2500         if (!state->ro)
 2501                 panic("state->ro == NULL in ipsec4_output");
 2502         if (!state->dst)
 2503                 panic("state->dst == NULL in ipsec4_output");
 2504 
 2505         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 2506                 printf("ipsec4_output: applyed SP\n");
 2507                 kdebug_secpolicy(sp));
 2508 
 2509         for (isr = sp->req; isr != NULL; isr = isr->next) {
 2510 
 2511 #if 0   /* give up to check restriction of transport mode */
 2512         /* XXX but should be checked somewhere */
 2513                 /*
 2514                  * some of the IPsec operation must be performed only in
 2515                  * originating case.
 2516                  */
 2517                 if (isr->saidx.mode == IPSEC_MODE_TRANSPORT
 2518                  && (flags & IP_FORWARDING))
 2519                         continue;
 2520 #endif
 2521 
 2522                 /* make SA index for search proper SA */
 2523                 ip = mtod(state->m, struct ip *);
 2524                 bcopy(&isr->saidx, &saidx, sizeof(saidx));
 2525                 saidx.mode = isr->saidx.mode;
 2526                 saidx.reqid = isr->saidx.reqid;
 2527                 sin = (struct sockaddr_in *)&saidx.src;
 2528                 if (sin->sin_len == 0) {
 2529                         sin->sin_len = sizeof(*sin);
 2530                         sin->sin_family = AF_INET;
 2531                         sin->sin_port = IPSEC_PORT_ANY;
 2532                         bcopy(&ip->ip_src, &sin->sin_addr,
 2533                             sizeof(sin->sin_addr));
 2534                 }
 2535                 sin = (struct sockaddr_in *)&saidx.dst;
 2536                 if (sin->sin_len == 0) {
 2537                         sin->sin_len = sizeof(*sin);
 2538                         sin->sin_family = AF_INET;
 2539                         sin->sin_port = IPSEC_PORT_ANY;
 2540                         bcopy(&ip->ip_dst, &sin->sin_addr,
 2541                             sizeof(sin->sin_addr));
 2542                 }
 2543 
 2544                 if ((error = key_checkrequest(isr, &saidx)) != 0) {
 2545                         /*
 2546                          * IPsec processing is required, but no SA found.
 2547                          * I assume that key_acquire() had been called
 2548                          * to get/establish the SA. Here I discard
 2549                          * this packet because it is responsibility for
 2550                          * upper layer to retransmit the packet.
 2551                          */
 2552                         ipsecstat.out_nosa++;
 2553                         goto bad;
 2554                 }
 2555 
 2556                 /* validity check */
 2557                 if (isr->sav == NULL) {
 2558                         switch (ipsec_get_reqlevel(isr)) {
 2559                         case IPSEC_LEVEL_USE:
 2560                                 continue;
 2561                         case IPSEC_LEVEL_REQUIRE:
 2562                                 /* must be not reached here. */
 2563                                 panic("ipsec4_output: no SA found, but required.");
 2564                         }
 2565                 }
 2566 
 2567                 /*
 2568                  * If there is no valid SA, we give up to process any
 2569                  * more.  In such a case, the SA's status is changed
 2570                  * from DYING to DEAD after allocating.  If a packet
 2571                  * send to the receiver by dead SA, the receiver can
 2572                  * not decode a packet because SA has been dead.
 2573                  */
 2574                 if (isr->sav->state != SADB_SASTATE_MATURE
 2575                  && isr->sav->state != SADB_SASTATE_DYING) {
 2576                         ipsecstat.out_nosa++;
 2577                         error = EINVAL;
 2578                         goto bad;
 2579                 }
 2580 
 2581                 /*
 2582                  * There may be the case that SA status will be changed when
 2583                  * we are refering to one. So calling splsoftnet().
 2584                  */
 2585                 s = splnet();
 2586 
 2587                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
 2588                         /*
 2589                          * build IPsec tunnel.
 2590                          */
 2591                         /* XXX should be processed with other familiy */
 2592                         if (((struct sockaddr *)&isr->sav->sah->saidx.src)->sa_family != AF_INET) {
 2593                                 ipseclog((LOG_ERR, "ipsec4_output: "
 2594                                     "family mismatched between inner and outer spi=%u\n",
 2595                                     (u_int32_t)ntohl(isr->sav->spi)));
 2596                                 splx(s);
 2597                                 error = EAFNOSUPPORT;
 2598                                 goto bad;
 2599                         }
 2600 
 2601                         state->m = ipsec4_splithdr(state->m);
 2602                         if (!state->m) {
 2603                                 splx(s);
 2604                                 error = ENOMEM;
 2605                                 goto bad;
 2606                         }
 2607                         error = ipsec4_encapsulate(state->m, isr->sav);
 2608                         splx(s);
 2609                         if (error) {
 2610                                 state->m = NULL;
 2611                                 goto bad;
 2612                         }
 2613                         ip = mtod(state->m, struct ip *);
 2614 
 2615                         state->ro = &isr->sav->sah->sa_route;
 2616                         state->dst = (struct sockaddr *)&state->ro->ro_dst;
 2617                         dst4 = (struct sockaddr_in *)state->dst;
 2618                         if (state->ro->ro_rt
 2619                          && ((state->ro->ro_rt->rt_flags & RTF_UP) == 0
 2620                           || dst4->sin_addr.s_addr != ip->ip_dst.s_addr)) {
 2621                                 RTFREE(state->ro->ro_rt);
 2622                                 state->ro->ro_rt = NULL;
 2623                         }
 2624                         if (state->ro->ro_rt == 0) {
 2625                                 dst4->sin_family = AF_INET;
 2626                                 dst4->sin_len = sizeof(*dst4);
 2627                                 dst4->sin_addr = ip->ip_dst;
 2628                                 rtalloc(state->ro);
 2629                         }
 2630                         if (state->ro->ro_rt == 0) {
 2631                                 ipstat.ips_noroute++;
 2632                                 error = EHOSTUNREACH;
 2633                                 goto bad;
 2634                         }
 2635 
 2636                         /* adjust state->dst if tunnel endpoint is offlink */
 2637                         if (state->ro->ro_rt->rt_flags & RTF_GATEWAY) {
 2638                                 state->dst = (struct sockaddr *)state->ro->ro_rt->rt_gateway;
 2639                                 dst4 = (struct sockaddr_in *)state->dst;
 2640                         }
 2641                 } else
 2642                         splx(s);
 2643 
 2644                 state->m = ipsec4_splithdr(state->m);
 2645                 if (!state->m) {
 2646                         error = ENOMEM;
 2647                         goto bad;
 2648                 }
 2649                 switch (isr->saidx.proto) {
 2650                 case IPPROTO_ESP:
 2651 #ifdef IPSEC_ESP
 2652                         if ((error = esp4_output(state->m, isr)) != 0) {
 2653                                 state->m = NULL;
 2654                                 goto bad;
 2655                         }
 2656                         break;
 2657 #else
 2658                         m_freem(state->m);
 2659                         state->m = NULL;
 2660                         error = EINVAL;
 2661                         goto bad;
 2662 #endif
 2663                 case IPPROTO_AH:
 2664                         if ((error = ah4_output(state->m, isr)) != 0) {
 2665                                 state->m = NULL;
 2666                                 goto bad;
 2667                         }
 2668                         break;
 2669                 case IPPROTO_IPCOMP:
 2670                         if ((error = ipcomp4_output(state->m, isr)) != 0) {
 2671                                 state->m = NULL;
 2672                                 goto bad;
 2673                         }
 2674                         break;
 2675                 default:
 2676                         ipseclog((LOG_ERR,
 2677                             "ipsec4_output: unknown ipsec protocol %d\n",
 2678                             isr->saidx.proto));
 2679                         m_freem(state->m);
 2680                         state->m = NULL;
 2681                         error = EINVAL;
 2682                         goto bad;
 2683                 }
 2684 
 2685                 if (state->m == 0) {
 2686                         error = ENOMEM;
 2687                         goto bad;
 2688                 }
 2689                 ip = mtod(state->m, struct ip *);
 2690         }
 2691 
 2692         return 0;
 2693 
 2694 bad:
 2695         m_freem(state->m);
 2696         state->m = NULL;
 2697         return error;
 2698 }
 2699 #endif
 2700 
 2701 #ifdef INET6
 2702 /*
 2703  * IPsec output logic for IPv6, transport mode.
 2704  */
 2705 int
 2706 ipsec6_output_trans(state, nexthdrp, mprev, sp, flags, tun)
 2707         struct ipsec_output_state *state;
 2708         u_char *nexthdrp;
 2709         struct mbuf *mprev;
 2710         struct secpolicy *sp;
 2711         int flags;
 2712         int *tun;
 2713 {
 2714         struct ip6_hdr *ip6;
 2715         struct ipsecrequest *isr = NULL;
 2716         struct secasindex saidx;
 2717         int error = 0;
 2718         int plen;
 2719         struct sockaddr_in6 *sin6;
 2720 
 2721         if (!state)
 2722                 panic("state == NULL in ipsec6_output_trans");
 2723         if (!state->m)
 2724                 panic("state->m == NULL in ipsec6_output_trans");
 2725         if (!nexthdrp)
 2726                 panic("nexthdrp == NULL in ipsec6_output_trans");
 2727         if (!mprev)
 2728                 panic("mprev == NULL in ipsec6_output_trans");
 2729         if (!sp)
 2730                 panic("sp == NULL in ipsec6_output_trans");
 2731         if (!tun)
 2732                 panic("tun == NULL in ipsec6_output_trans");
 2733 
 2734         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 2735                 printf("ipsec6_output_trans: applyed SP\n");
 2736                 kdebug_secpolicy(sp));
 2737 
 2738         *tun = 0;
 2739         for (isr = sp->req; isr; isr = isr->next) {
 2740                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
 2741                         /* the rest will be handled by ipsec6_output_tunnel() */
 2742                         break;
 2743                 }
 2744 
 2745                 /* make SA index for search proper SA */
 2746                 ip6 = mtod(state->m, struct ip6_hdr *);
 2747                 bcopy(&isr->saidx, &saidx, sizeof(saidx));
 2748                 saidx.mode = isr->saidx.mode;
 2749                 saidx.reqid = isr->saidx.reqid;
 2750                 sin6 = (struct sockaddr_in6 *)&saidx.src;
 2751                 if (sin6->sin6_len == 0) {
 2752                         sin6->sin6_len = sizeof(*sin6);
 2753                         sin6->sin6_family = AF_INET6;
 2754                         sin6->sin6_port = IPSEC_PORT_ANY;
 2755                         bcopy(&ip6->ip6_src, &sin6->sin6_addr,
 2756                             sizeof(ip6->ip6_src));
 2757                         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
 2758                                 /* fix scope id for comparing SPD */
 2759                                 sin6->sin6_addr.s6_addr16[1] = 0;
 2760                                 sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
 2761                         }
 2762                 }
 2763                 sin6 = (struct sockaddr_in6 *)&saidx.dst;
 2764                 if (sin6->sin6_len == 0) {
 2765                         sin6->sin6_len = sizeof(*sin6);
 2766                         sin6->sin6_family = AF_INET6;
 2767                         sin6->sin6_port = IPSEC_PORT_ANY;
 2768                         bcopy(&ip6->ip6_dst, &sin6->sin6_addr,
 2769                             sizeof(ip6->ip6_dst));
 2770                         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
 2771                                 /* fix scope id for comparing SPD */
 2772                                 sin6->sin6_addr.s6_addr16[1] = 0;
 2773                                 sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
 2774                         }
 2775                 }
 2776 
 2777                 if (key_checkrequest(isr, &saidx) == ENOENT) {
 2778                         /*
 2779                          * IPsec processing is required, but no SA found.
 2780                          * I assume that key_acquire() had been called
 2781                          * to get/establish the SA. Here I discard
 2782                          * this packet because it is responsibility for
 2783                          * upper layer to retransmit the packet.
 2784                          */
 2785                         ipsec6stat.out_nosa++;
 2786                         error = ENOENT;
 2787 
 2788                         /*
 2789                          * Notify the fact that the packet is discarded
 2790                          * to ourselves. I believe this is better than
 2791                          * just silently discarding. (jinmei@kame.net)
 2792                          * XXX: should we restrict the error to TCP packets?
 2793                          * XXX: should we directly notify sockets via
 2794                          *      pfctlinputs?
 2795                          */
 2796                         icmp6_error(state->m, ICMP6_DST_UNREACH,
 2797                                     ICMP6_DST_UNREACH_ADMIN, 0);
 2798                         state->m = NULL; /* icmp6_error freed the mbuf */
 2799                         goto bad;
 2800                 }
 2801 
 2802                 /* validity check */
 2803                 if (isr->sav == NULL) {
 2804                         switch (ipsec_get_reqlevel(isr)) {
 2805                         case IPSEC_LEVEL_USE:
 2806                                 continue;
 2807                         case IPSEC_LEVEL_REQUIRE:
 2808                                 /* must be not reached here. */
 2809                                 panic("ipsec6_output_trans: no SA found, but required.");
 2810                         }
 2811                 }
 2812 
 2813                 /*
 2814                  * If there is no valid SA, we give up to process.
 2815                  * see same place at ipsec4_output().
 2816                  */
 2817                 if (isr->sav->state != SADB_SASTATE_MATURE
 2818                  && isr->sav->state != SADB_SASTATE_DYING) {
 2819                         ipsec6stat.out_nosa++;
 2820                         error = EINVAL;
 2821                         goto bad;
 2822                 }
 2823 
 2824                 switch (isr->saidx.proto) {
 2825                 case IPPROTO_ESP:
 2826 #ifdef IPSEC_ESP
 2827                         error = esp6_output(state->m, nexthdrp, mprev->m_next, isr);
 2828 #else
 2829                         m_freem(state->m);
 2830                         error = EINVAL;
 2831 #endif
 2832                         break;
 2833                 case IPPROTO_AH:
 2834                         error = ah6_output(state->m, nexthdrp, mprev->m_next, isr);
 2835                         break;
 2836                 case IPPROTO_IPCOMP:
 2837                         error = ipcomp6_output(state->m, nexthdrp, mprev->m_next, isr);
 2838                         break;
 2839                 default:
 2840                         ipseclog((LOG_ERR, "ipsec6_output_trans: "
 2841                             "unknown ipsec protocol %d\n", isr->saidx.proto));
 2842                         m_freem(state->m);
 2843                         ipsec6stat.out_inval++;
 2844                         error = EINVAL;
 2845                         break;
 2846                 }
 2847                 if (error) {
 2848                         state->m = NULL;
 2849                         goto bad;
 2850                 }
 2851                 plen = state->m->m_pkthdr.len - sizeof(struct ip6_hdr);
 2852                 if (plen > IPV6_MAXPACKET) {
 2853                         ipseclog((LOG_ERR, "ipsec6_output_trans: "
 2854                             "IPsec with IPv6 jumbogram is not supported\n"));
 2855                         ipsec6stat.out_inval++;
 2856                         error = EINVAL; /* XXX */
 2857                         goto bad;
 2858                 }
 2859                 ip6 = mtod(state->m, struct ip6_hdr *);
 2860                 ip6->ip6_plen = htons(plen);
 2861         }
 2862 
 2863         /* if we have more to go, we need a tunnel mode processing */
 2864         if (isr != NULL)
 2865                 *tun = 1;
 2866 
 2867         return 0;
 2868 
 2869 bad:
 2870         m_freem(state->m);
 2871         state->m = NULL;
 2872         return error;
 2873 }
 2874 
 2875 /*
 2876  * IPsec output logic for IPv6, tunnel mode.
 2877  */
 2878 int
 2879 ipsec6_output_tunnel(state, sp, flags)
 2880         struct ipsec_output_state *state;
 2881         struct secpolicy *sp;
 2882         int flags;
 2883 {
 2884         struct ip6_hdr *ip6;
 2885         struct ipsecrequest *isr = NULL;
 2886         struct secasindex saidx;
 2887         int error = 0;
 2888         int plen;
 2889         struct sockaddr_in6* dst6;
 2890         int s;
 2891 
 2892         if (!state)
 2893                 panic("state == NULL in ipsec6_output_tunnel");
 2894         if (!state->m)
 2895                 panic("state->m == NULL in ipsec6_output_tunnel");
 2896         if (!sp)
 2897                 panic("sp == NULL in ipsec6_output_tunnel");
 2898 
 2899         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
 2900                 printf("ipsec6_output_tunnel: applyed SP\n");
 2901                 kdebug_secpolicy(sp));
 2902 
 2903         /*
 2904          * transport mode ipsec (before the 1st tunnel mode) is already
 2905          * processed by ipsec6_output_trans().
 2906          */
 2907         for (isr = sp->req; isr; isr = isr->next) {
 2908                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
 2909                         break;
 2910         }
 2911 
 2912         for (/* already initialized */; isr; isr = isr->next) {
 2913                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
 2914                         /* When tunnel mode, SA peers must be specified. */
 2915                         bcopy(&isr->saidx, &saidx, sizeof(saidx));
 2916                 } else {
 2917                         /* make SA index to look for a proper SA */
 2918                         struct sockaddr_in6 *sin6;
 2919 
 2920                         bzero(&saidx, sizeof(saidx));
 2921                         saidx.proto = isr->saidx.proto;
 2922                         saidx.mode = isr->saidx.mode;
 2923                         saidx.reqid = isr->saidx.reqid;
 2924 
 2925                         ip6 = mtod(state->m, struct ip6_hdr *);
 2926                         sin6 = (struct sockaddr_in6 *)&saidx.src;
 2927                         if (sin6->sin6_len == 0) {
 2928                                 sin6->sin6_len = sizeof(*sin6);
 2929                                 sin6->sin6_family = AF_INET6;
 2930                                 sin6->sin6_port = IPSEC_PORT_ANY;
 2931                                 bcopy(&ip6->ip6_src, &sin6->sin6_addr,
 2932                                     sizeof(ip6->ip6_src));
 2933                                 if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
 2934                                         /* fix scope id for comparing SPD */
 2935                                         sin6->sin6_addr.s6_addr16[1] = 0;
 2936                                         sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
 2937                                 }
 2938                         }
 2939                         sin6 = (struct sockaddr_in6 *)&saidx.dst;
 2940                         if (sin6->sin6_len == 0) {
 2941                                 sin6->sin6_len = sizeof(*sin6);
 2942                                 sin6->sin6_family = AF_INET6;
 2943                                 sin6->sin6_port = IPSEC_PORT_ANY;
 2944                                 bcopy(&ip6->ip6_dst, &sin6->sin6_addr,
 2945                                     sizeof(ip6->ip6_dst));
 2946                                 if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
 2947                                         /* fix scope id for comparing SPD */
 2948                                         sin6->sin6_addr.s6_addr16[1] = 0;
 2949                                         sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
 2950                                 }
 2951                         }
 2952                 }
 2953 
 2954                 if (key_checkrequest(isr, &saidx) == ENOENT) {
 2955                         /*
 2956                          * IPsec processing is required, but no SA found.
 2957                          * I assume that key_acquire() had been called
 2958                          * to get/establish the SA. Here I discard
 2959                          * this packet because it is responsibility for
 2960                          * upper layer to retransmit the packet.
 2961                          */
 2962                         ipsec6stat.out_nosa++;
 2963                         error = ENOENT;
 2964                         goto bad;
 2965                 }
 2966 
 2967                 /* validity check */
 2968                 if (isr->sav == NULL) {
 2969                         switch (ipsec_get_reqlevel(isr)) {
 2970                         case IPSEC_LEVEL_USE:
 2971                                 continue;
 2972                         case IPSEC_LEVEL_REQUIRE:
 2973                                 /* must be not reached here. */
 2974                                 panic("ipsec6_output_tunnel: no SA found, but required.");
 2975                         }
 2976                 }
 2977 
 2978                 /*
 2979                  * If there is no valid SA, we give up to process.
 2980                  * see same place at ipsec4_output().
 2981                  */
 2982                 if (isr->sav->state != SADB_SASTATE_MATURE
 2983                  && isr->sav->state != SADB_SASTATE_DYING) {
 2984                         ipsec6stat.out_nosa++;
 2985                         error = EINVAL;
 2986                         goto bad;
 2987                 }
 2988 
 2989                 /*
 2990                  * There may be the case that SA status will be changed when
 2991                  * we are refering to one. So calling splsoftnet().
 2992                  */
 2993                 s = splnet();
 2994 
 2995                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
 2996                         /*
 2997                          * build IPsec tunnel.
 2998                          */
 2999                         /* XXX should be processed with other familiy */
 3000                         if (((struct sockaddr *)&isr->sav->sah->saidx.src)->sa_family != AF_INET6) {
 3001                                 ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
 3002                                     "family mismatched between inner and outer, spi=%u\n",
 3003                                     (u_int32_t)ntohl(isr->sav->spi)));
 3004                                 splx(s);
 3005                                 ipsec6stat.out_inval++;
 3006                                 error = EAFNOSUPPORT;
 3007                                 goto bad;
 3008                         }
 3009 
 3010                         state->m = ipsec6_splithdr(state->m);
 3011                         if (!state->m) {
 3012                                 splx(s);
 3013                                 ipsec6stat.out_nomem++;
 3014                                 error = ENOMEM;
 3015                                 goto bad;
 3016                         }
 3017                         error = ipsec6_encapsulate(state->m, isr->sav);
 3018                         splx(s);
 3019                         if (error) {
 3020                                 state->m = 0;
 3021                                 goto bad;
 3022                         }
 3023                         ip6 = mtod(state->m, struct ip6_hdr *);
 3024 
 3025                         state->ro = &isr->sav->sah->sa_route;
 3026                         state->dst = (struct sockaddr *)&state->ro->ro_dst;
 3027                         dst6 = (struct sockaddr_in6 *)state->dst;
 3028                         if (state->ro->ro_rt
 3029                          && ((state->ro->ro_rt->rt_flags & RTF_UP) == 0
 3030                           || !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst))) {
 3031                                 RTFREE(state->ro->ro_rt);
 3032                                 state->ro->ro_rt = NULL;
 3033                         }
 3034                         if (state->ro->ro_rt == 0) {
 3035                                 bzero(dst6, sizeof(*dst6));
 3036                                 dst6->sin6_family = AF_INET6;
 3037                                 dst6->sin6_len = sizeof(*dst6);
 3038                                 dst6->sin6_addr = ip6->ip6_dst;
 3039                                 rtalloc(state->ro);
 3040                         }
 3041                         if (state->ro->ro_rt == 0) {
 3042                                 ip6stat.ip6s_noroute++;
 3043                                 ipsec6stat.out_noroute++;
 3044                                 error = EHOSTUNREACH;
 3045                                 goto bad;
 3046                         }
 3047 
 3048                         /* adjust state->dst if tunnel endpoint is offlink */
 3049                         if (state->ro->ro_rt->rt_flags & RTF_GATEWAY) {
 3050                                 state->dst = (struct sockaddr *)state->ro->ro_rt->rt_gateway;
 3051                                 dst6 = (struct sockaddr_in6 *)state->dst;
 3052                         }
 3053                 } else
 3054                         splx(s);
 3055 
 3056                 state->m = ipsec6_splithdr(state->m);
 3057                 if (!state->m) {
 3058                         ipsec6stat.out_nomem++;
 3059                         error = ENOMEM;
 3060                         goto bad;
 3061                 }
 3062                 ip6 = mtod(state->m, struct ip6_hdr *);
 3063                 switch (isr->saidx.proto) {
 3064                 case IPPROTO_ESP:
 3065 #ifdef IPSEC_ESP
 3066                         error = esp6_output(state->m, &ip6->ip6_nxt, state->m->m_next, isr);
 3067 #else
 3068                         m_freem(state->m);
 3069                         error = EINVAL;
 3070 #endif
 3071                         break;
 3072                 case IPPROTO_AH:
 3073                         error = ah6_output(state->m, &ip6->ip6_nxt, state->m->m_next, isr);
 3074                         break;
 3075                 case IPPROTO_IPCOMP:
 3076                         /* XXX code should be here */
 3077                         /* FALLTHROUGH */
 3078                 default:
 3079                         ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
 3080                             "unknown ipsec protocol %d\n", isr->saidx.proto));
 3081                         m_freem(state->m);
 3082                         ipsec6stat.out_inval++;
 3083                         error = EINVAL;
 3084                         break;
 3085                 }
 3086                 if (error) {
 3087                         state->m = NULL;
 3088                         goto bad;
 3089                 }
 3090                 plen = state->m->m_pkthdr.len - sizeof(struct ip6_hdr);
 3091                 if (plen > IPV6_MAXPACKET) {
 3092                         ipseclog((LOG_ERR, "ipsec6_output_tunnel: "
 3093                             "IPsec with IPv6 jumbogram is not supported\n"));
 3094                         ipsec6stat.out_inval++;
 3095                         error = EINVAL; /* XXX */
 3096                         goto bad;
 3097                 }
 3098                 ip6 = mtod(state->m, struct ip6_hdr *);
 3099                 ip6->ip6_plen = htons(plen);
 3100         }
 3101 
 3102         return 0;
 3103 
 3104 bad:
 3105         m_freem(state->m);
 3106         state->m = NULL;
 3107         return error;
 3108 }
 3109 #endif /* INET6 */
 3110 
 3111 #ifdef INET
 3112 /*
 3113  * Chop IP header and option off from the payload.
 3114  */
 3115 static struct mbuf *
 3116 ipsec4_splithdr(m)
 3117         struct mbuf *m;
 3118 {
 3119         struct mbuf *mh;
 3120         struct ip *ip;
 3121         int hlen;
 3122 
 3123         if (m->m_len < sizeof(struct ip))
 3124                 panic("ipsec4_splithdr: first mbuf too short");
 3125         ip = mtod(m, struct ip *);
 3126 #ifdef _IP_VHL
 3127         hlen = _IP_VHL_HL(ip->ip_vhl) << 2;
 3128 #else
 3129         hlen = ip->ip_hl << 2;
 3130 #endif
 3131         if (m->m_len > hlen) {
 3132                 MGETHDR(mh, M_DONTWAIT, MT_HEADER);
 3133                 if (!mh) {
 3134                         m_freem(m);
 3135                         return NULL;
 3136                 }
 3137                 M_MOVE_PKTHDR(mh, m);
 3138                 MH_ALIGN(mh, hlen);
 3139                 m->m_len -= hlen;
 3140                 m->m_data += hlen;
 3141                 mh->m_next = m;
 3142                 m = mh;
 3143                 m->m_len = hlen;
 3144                 bcopy((caddr_t)ip, mtod(m, caddr_t), hlen);
 3145         } else if (m->m_len < hlen) {
 3146                 m = m_pullup(m, hlen);
 3147                 if (!m)
 3148                         return NULL;
 3149         }
 3150         return m;
 3151 }
 3152 #endif
 3153 
 3154 #ifdef INET6
 3155 static struct mbuf *
 3156 ipsec6_splithdr(m)
 3157         struct mbuf *m;
 3158 {
 3159         struct mbuf *mh;
 3160         struct ip6_hdr *ip6;
 3161         int hlen;
 3162 
 3163         if (m->m_len < sizeof(struct ip6_hdr))
 3164                 panic("ipsec6_splithdr: first mbuf too short");
 3165         ip6 = mtod(m, struct ip6_hdr *);
 3166         hlen = sizeof(struct ip6_hdr);
 3167         if (m->m_len > hlen) {
 3168                 MGETHDR(mh, M_DONTWAIT, MT_HEADER);
 3169                 if (!mh) {
 3170                         m_freem(m);
 3171                         return NULL;
 3172                 }
 3173                 M_MOVE_PKTHDR(mh, m);
 3174                 MH_ALIGN(mh, hlen);
 3175                 m->m_len -= hlen;
 3176                 m->m_data += hlen;
 3177                 mh->m_next = m;
 3178                 m = mh;
 3179                 m->m_len = hlen;
 3180                 bcopy((caddr_t)ip6, mtod(m, caddr_t), hlen);
 3181         } else if (m->m_len < hlen) {
 3182                 m = m_pullup(m, hlen);
 3183                 if (!m)
 3184                         return NULL;
 3185         }
 3186         return m;
 3187 }
 3188 #endif
 3189 
 3190 /* validate inbound IPsec tunnel packet. */
 3191 int
 3192 ipsec4_tunnel_validate(m, off, nxt0, sav)
 3193         struct mbuf *m;         /* no pullup permitted, m->m_len >= ip */
 3194         int off;
 3195         u_int nxt0;
 3196         struct secasvar *sav;
 3197 {
 3198         u_int8_t nxt = nxt0 & 0xff;
 3199         struct sockaddr_in *sin;
 3200         struct sockaddr_in osrc, odst, isrc, idst;
 3201         int hlen;
 3202         struct secpolicy *sp;
 3203         struct ip *oip;
 3204 
 3205 #ifdef DIAGNOSTIC
 3206         if (m->m_len < sizeof(struct ip))
 3207                 panic("too short mbuf on ipsec4_tunnel_validate");
 3208 #endif
 3209         if (nxt != IPPROTO_IPV4)
 3210                 return 0;
 3211         if (m->m_pkthdr.len < off + sizeof(struct ip))
 3212                 return 0;
 3213         /* do not decapsulate if the SA is for transport mode only */
 3214         if (sav->sah->saidx.mode == IPSEC_MODE_TRANSPORT)
 3215                 return 0;
 3216 
 3217         oip = mtod(m, struct ip *);
 3218 #ifdef _IP_VHL
 3219         hlen = _IP_VHL_HL(oip->ip_vhl) << 2;
 3220 #else
 3221         hlen = oip->ip_hl << 2;
 3222 #endif
 3223         if (hlen != sizeof(struct ip))
 3224                 return 0;
 3225 
 3226         /* AF_INET6 should be supported, but at this moment we don't. */
 3227         sin = (struct sockaddr_in *)&sav->sah->saidx.dst;
 3228         if (sin->sin_family != AF_INET)
 3229                 return 0;
 3230         if (bcmp(&oip->ip_dst, &sin->sin_addr, sizeof(oip->ip_dst)) != 0)
 3231                 return 0;
 3232 
 3233         /* XXX slow */
 3234         bzero(&osrc, sizeof(osrc));
 3235         bzero(&odst, sizeof(odst));
 3236         bzero(&isrc, sizeof(isrc));
 3237         bzero(&idst, sizeof(idst));
 3238         osrc.sin_family = odst.sin_family = isrc.sin_family = idst.sin_family = 
 3239             AF_INET;
 3240         osrc.sin_len = odst.sin_len = isrc.sin_len = idst.sin_len = 
 3241             sizeof(struct sockaddr_in);
 3242         osrc.sin_addr = oip->ip_src;
 3243         odst.sin_addr = oip->ip_dst;
 3244         m_copydata(m, off + offsetof(struct ip, ip_src), sizeof(isrc.sin_addr),
 3245             (caddr_t)&isrc.sin_addr);
 3246         m_copydata(m, off + offsetof(struct ip, ip_dst), sizeof(idst.sin_addr),
 3247             (caddr_t)&idst.sin_addr);
 3248 
 3249         /*
 3250          * RFC2401 5.2.1 (b): (assume that we are using tunnel mode)
 3251          * - if the inner destination is multicast address, there can be
 3252          *   multiple permissible inner source address.  implementation
 3253          *   may want to skip verification of inner source address against
 3254          *   SPD selector.
 3255          * - if the inner protocol is ICMP, the packet may be an error report
 3256          *   from routers on the other side of the VPN cloud (R in the
 3257          *   following diagram).  in this case, we cannot verify inner source
 3258          *   address against SPD selector.
 3259          *      me -- gw === gw -- R -- you
 3260          *
 3261          * we consider the first bullet to be users responsibility on SPD entry
 3262          * configuration (if you need to encrypt multicast traffic, set
 3263          * the source range of SPD selector to 0.0.0.0/0, or have explicit
 3264          * address ranges for possible senders).
 3265          * the second bullet is not taken care of (yet).
 3266          *
 3267          * therefore, we do not do anything special about inner source.
 3268          */
 3269 
 3270         sp = key_gettunnel((struct sockaddr *)&osrc, (struct sockaddr *)&odst,
 3271             (struct sockaddr *)&isrc, (struct sockaddr *)&idst);
 3272         if (!sp)
 3273                 return 0;
 3274         key_freesp(sp);
 3275 
 3276         return 1;
 3277 }
 3278 
 3279 #ifdef INET6
 3280 /* validate inbound IPsec tunnel packet. */
 3281 int
 3282 ipsec6_tunnel_validate(m, off, nxt0, sav)
 3283         struct mbuf *m;         /* no pullup permitted, m->m_len >= ip */
 3284         int off;
 3285         u_int nxt0;
 3286         struct secasvar *sav;
 3287 {
 3288         u_int8_t nxt = nxt0 & 0xff;
 3289         struct sockaddr_in6 *sin6;
 3290         struct sockaddr_in6 osrc, odst, isrc, idst;
 3291         struct secpolicy *sp;
 3292         struct ip6_hdr *oip6;
 3293 
 3294 #ifdef DIAGNOSTIC
 3295         if (m->m_len < sizeof(struct ip6_hdr))
 3296                 panic("too short mbuf on ipsec6_tunnel_validate");
 3297 #endif
 3298         if (nxt != IPPROTO_IPV6)
 3299                 return 0;
 3300         if (m->m_pkthdr.len < off + sizeof(struct ip6_hdr))
 3301                 return 0;
 3302         /* do not decapsulate if the SA is for transport mode only */
 3303         if (sav->sah->saidx.mode == IPSEC_MODE_TRANSPORT)
 3304                 return 0;
 3305 
 3306         oip6 = mtod(m, struct ip6_hdr *);
 3307         /* AF_INET should be supported, but at this moment we don't. */
 3308         sin6 = (struct sockaddr_in6 *)&sav->sah->saidx.dst;
 3309         if (sin6->sin6_family != AF_INET6)
 3310                 return 0;
 3311         if (!IN6_ARE_ADDR_EQUAL(&oip6->ip6_dst, &sin6->sin6_addr))
 3312                 return 0;
 3313 
 3314         /* XXX slow */
 3315         bzero(&osrc, sizeof(osrc));
 3316         bzero(&odst, sizeof(odst));
 3317         bzero(&isrc, sizeof(isrc));
 3318         bzero(&idst, sizeof(idst));
 3319         osrc.sin6_family = odst.sin6_family = isrc.sin6_family =
 3320             idst.sin6_family = AF_INET6;
 3321         osrc.sin6_len = odst.sin6_len = isrc.sin6_len = idst.sin6_len = 
 3322             sizeof(struct sockaddr_in6);
 3323         osrc.sin6_addr = oip6->ip6_src;
 3324         odst.sin6_addr = oip6->ip6_dst;
 3325         m_copydata(m, off + offsetof(struct ip6_hdr, ip6_src),
 3326             sizeof(isrc.sin6_addr), (caddr_t)&isrc.sin6_addr);
 3327         m_copydata(m, off + offsetof(struct ip6_hdr, ip6_dst),
 3328             sizeof(idst.sin6_addr), (caddr_t)&idst.sin6_addr);
 3329 
 3330         /*
 3331          * regarding to inner source address validation, see a long comment
 3332          * in ipsec4_tunnel_validate.
 3333          */
 3334 
 3335         sp = key_gettunnel((struct sockaddr *)&osrc, (struct sockaddr *)&odst,
 3336             (struct sockaddr *)&isrc, (struct sockaddr *)&idst);
 3337         /*
 3338          * when there is no suitable inbound policy for the packet of the ipsec
 3339          * tunnel mode, the kernel never decapsulate the tunneled packet
 3340          * as the ipsec tunnel mode even when the system wide policy is "none".
 3341          * then the kernel leaves the generic tunnel module to process this
 3342          * packet.  if there is no rule of the generic tunnel, the packet
 3343          * is rejected and the statistics will be counted up.
 3344          */
 3345         if (!sp)
 3346                 return 0;
 3347         key_freesp(sp);
 3348 
 3349         return 1;
 3350 }
 3351 #endif
 3352 
 3353 /*
 3354  * Make a mbuf chain for encryption.
 3355  * If the original mbuf chain contains a mbuf with a cluster,
 3356  * allocate a new cluster and copy the data to the new cluster.
 3357  * XXX: this hack is inefficient, but is necessary to handle cases
 3358  * of TCP retransmission...
 3359  */
 3360 struct mbuf *
 3361 ipsec_copypkt(m)
 3362         struct mbuf *m;
 3363 {
 3364         struct mbuf *n, **mpp, *mnew;
 3365 
 3366         for (n = m, mpp = &m; n; n = n->m_next) {
 3367                 if (n->m_flags & M_EXT) {
 3368                         /*
 3369                          * Make a copy only if there are more than one
 3370                          * references to the cluster.
 3371                          * XXX: is this approach effective?
 3372                          */
 3373                         if (n->m_ext.ext_type != EXT_CLUSTER || MEXT_IS_REF(n)) 
 3374                         {
 3375                                 int remain, copied;
 3376                                 struct mbuf *mm;
 3377 
 3378                                 if (n->m_flags & M_PKTHDR) {
 3379                                         MGETHDR(mnew, M_DONTWAIT, MT_HEADER);
 3380                                         if (mnew == NULL)
 3381                                                 goto fail;
 3382                                         if (!m_dup_pkthdr(mnew, n, M_DONTWAIT)) {
 3383                                                 m_free(mnew);
 3384                                                 goto fail;
 3385                                         }
 3386                                 }
 3387                                 else {
 3388                                         MGET(mnew, M_DONTWAIT, MT_DATA);
 3389                                         if (mnew == NULL)
 3390                                                 goto fail;
 3391                                 }
 3392                                 mnew->m_len = 0;
 3393                                 mm = mnew;
 3394 
 3395                                 /*
 3396                                  * Copy data. If we don't have enough space to
 3397                                  * store the whole data, allocate a cluster
 3398                                  * or additional mbufs.
 3399                                  * XXX: we don't use m_copyback(), since the
 3400                                  * function does not use clusters and thus is
 3401                                  * inefficient.
 3402                                  */
 3403                                 remain = n->m_len;
 3404                                 copied = 0;
 3405                                 while (1) {
 3406                                         int len;
 3407                                         struct mbuf *mn;
 3408 
 3409                                         if (remain <= (mm->m_flags & M_PKTHDR ? MHLEN : MLEN))
 3410                                                 len = remain;
 3411                                         else { /* allocate a cluster */
 3412                                                 MCLGET(mm, M_DONTWAIT);
 3413                                                 if (!(mm->m_flags & M_EXT)) {
 3414                                                         m_free(mm);
 3415                                                         goto fail;
 3416                                                 }
 3417                                                 len = remain < MCLBYTES ?
 3418                                                         remain : MCLBYTES;
 3419                                         }
 3420 
 3421                                         bcopy(n->m_data + copied, mm->m_data,
 3422                                               len);
 3423 
 3424                                         copied += len;
 3425                                         remain -= len;
 3426                                         mm->m_len = len;
 3427 
 3428                                         if (remain <= 0) /* completed? */
 3429                                                 break;
 3430 
 3431                                         /* need another mbuf */
 3432                                         MGETHDR(mn, M_DONTWAIT, MT_HEADER);
 3433                                         if (mn == NULL)
 3434                                                 goto fail;
 3435                                         mn->m_pkthdr.rcvif = NULL;
 3436                                         mm->m_next = mn;
 3437                                         mm = mn;
 3438                                 }
 3439 
 3440                                 /* adjust chain */
 3441                                 mm->m_next = m_free(n);
 3442                                 n = mm;
 3443                                 *mpp = mnew;
 3444                                 mpp = &n->m_next;
 3445 
 3446                                 continue;
 3447                         }
 3448                 }
 3449                 *mpp = n;
 3450                 mpp = &n->m_next;
 3451         }
 3452 
 3453         return(m);
 3454   fail:
 3455         m_freem(m);
 3456         return(NULL);
 3457 }
 3458 
 3459 void
 3460 ipsec_delaux(m)
 3461         struct mbuf *m;
 3462 {
 3463         struct m_tag *tag;
 3464 
 3465         while ((tag = m_tag_find(m, PACKET_TAG_IPSEC_HISTORY, NULL)) != NULL)
 3466                 m_tag_delete(m, tag);
 3467 }
 3468 
 3469 int
 3470 ipsec_addhist(m, proto, spi)
 3471         struct mbuf *m;
 3472         int proto;
 3473         u_int32_t spi;
 3474 {
 3475         struct m_tag *tag;
 3476         struct ipsec_history *p;
 3477 
 3478         tag = m_tag_get(PACKET_TAG_IPSEC_HISTORY,
 3479                         sizeof (struct ipsec_history), M_NOWAIT);
 3480         if (tag == NULL)
 3481                 return ENOBUFS;
 3482         p = (struct ipsec_history *)(tag+1);
 3483         bzero(p, sizeof(*p));
 3484         p->ih_proto = proto;
 3485         p->ih_spi = spi;
 3486         m_tag_prepend(m, tag);
 3487         return 0;
 3488 }
 3489 
 3490 struct ipsec_history *
 3491 ipsec_gethist(m, lenp)
 3492         struct mbuf *m;
 3493         int *lenp;
 3494 {
 3495         struct m_tag *tag;
 3496 
 3497         tag = m_tag_find(m, PACKET_TAG_IPSEC_HISTORY, NULL);
 3498         if (tag == NULL)
 3499                 return NULL;
 3500         /* XXX NB: noone uses this so fake it */
 3501         if (lenp)
 3502                 *lenp = sizeof (struct ipsec_history);
 3503         return ((struct ipsec_history *)(tag+1));
 3504 }

Cache object: 242b1101919a36339948384edcc2bd5c


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