"Fossies" - the Fresh Open Source Software Archive

Member "vpnc-0.5.3/vpnc.c" (19 Nov 2008, 111796 Bytes) of package /linux/privat/old/vpnc-0.5.3.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "vpnc.c" see the Fossies "Dox" file reference documentation.

    1 /* IPSec VPN client compatible with Cisco equipment.
    2    Copyright (C) 2002      Geoffrey Keating
    3    Copyright (C) 2003-2005 Maurice Massar
    4    Copyright (C) 2004      Tomas Mraz
    5    Copyright (C) 2004      Martin von Gagern
    6 
    7    This program is free software; you can redistribute it and/or modify
    8    it under the terms of the GNU General Public License as published by
    9    the Free Software Foundation; either version 2 of the License, or
   10    (at your option) any later version.
   11    
   12    This program is distributed in the hope that it will be useful,
   13    but WITHOUT ANY WARRANTY; without even the implied warranty of
   14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   15    GNU General Public License for more details.
   16    
   17    You should have received a copy of the GNU General Public License
   18    along with this program; if not, write to the Free Software
   19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   20 
   21    $Id: vpnc.c 371 2008-11-19 20:55:28Z Joerg Mayer $
   22 */
   23 
   24 #define _GNU_SOURCE
   25 #include <assert.h>
   26 #include <unistd.h>
   27 #include <sys/fcntl.h>
   28 #include <stdio.h>
   29 #include <errno.h>
   30 #include <string.h>
   31 #include <time.h>
   32 #include <stdlib.h>
   33 #include <sys/socket.h>
   34 #include <netinet/in.h>
   35 #include <netdb.h>
   36 #include <arpa/inet.h>
   37 #include <poll.h>
   38 #include <sys/ioctl.h>
   39 #include <sys/utsname.h>
   40 
   41 #include <gcrypt.h>
   42 
   43 #ifdef OPENSSL_GPL_VIOLATION
   44 /* OpenSSL */
   45 #include <openssl/x509.h>
   46 #include <openssl/err.h>
   47 #endif /* OPENSSL_GPL_VIOLATION */
   48 
   49 #include "sysdep.h"
   50 #include "config.h"
   51 #include "isakmp-pkt.h"
   52 #include "math_group.h"
   53 #include "dh.h"
   54 #include "vpnc.h"
   55 #include "tunip.h"
   56 #include "supp.h"
   57 
   58 #if defined(__CYGWIN__)
   59     GCRY_THREAD_OPTION_PTHREAD_IMPL;
   60 #endif
   61 
   62 #define ISAKMP_PORT (500)
   63 #define ISAKMP_PORT_NATT (4500)
   64 
   65 const unsigned char VID_XAUTH[] = { /* "draft-ietf-ipsra-isakmp-xauth-06.txt"/8 */
   66     0x09, 0x00, 0x26, 0x89, 0xDF, 0xD6, 0xB7, 0x12
   67 };
   68 const unsigned char VID_DPD[] = { /* Dead Peer Detection, RFC 3706 */
   69     0xAF, 0xCA, 0xD7, 0x13, 0x68, 0xA1, 0xF1, 0xC9,
   70     0x6B, 0x86, 0x96, 0xFC, 0x77, 0x57, 0x01, 0x00
   71 };
   72 const unsigned char VID_UNITY[] = { /* "CISCO-UNITY"/14 + major + minor */
   73     0x12, 0xF5, 0xF2, 0x8C, 0x45, 0x71, 0x68, 0xA9,
   74     0x70, 0x2D, 0x9F, 0xE2, 0x74, 0xCC, 0x01, 0x00
   75 };
   76 const unsigned char VID_UNKNOWN[] = {
   77     0x12, 0x6E, 0x1F, 0x57, 0x72, 0x91, 0x15, 0x3B,
   78     0x20, 0x48, 0x5F, 0x7F, 0x15, 0x5B, 0x4B, 0xC8
   79 };
   80 const unsigned char VID_NATT_00[] = { /* "draft-ietf-ipsec-nat-t-ike-00" */
   81     0x44, 0x85, 0x15, 0x2d, 0x18, 0xb6, 0xbb, 0xcd,
   82     0x0b, 0xe8, 0xa8, 0x46, 0x95, 0x79, 0xdd, 0xcc
   83 };
   84 const unsigned char VID_NATT_01[] = { /* "draft-ietf-ipsec-nat-t-ike-01" */
   85     0x16, 0xf6, 0xca, 0x16, 0xe4, 0xa4, 0x06, 0x6d,
   86     0x83, 0x82, 0x1a, 0x0f, 0x0a, 0xea, 0xa8, 0x62
   87 };
   88 const unsigned char VID_NATT_02[] = { /* "draft-ietf-ipsec-nat-t-ike-02" */
   89     0xcd, 0x60, 0x46, 0x43, 0x35, 0xdf, 0x21, 0xf8,
   90     0x7c, 0xfd, 0xb2, 0xfc, 0x68, 0xb6, 0xa4, 0x48
   91 };
   92 const unsigned char VID_NATT_02N[] = { /* "draft-ietf-ipsec-nat-t-ike-02\n" */
   93     0x90, 0xCB, 0x80, 0x91, 0x3E, 0xBB, 0x69, 0x6E,
   94     0x08, 0x63, 0x81, 0xB5, 0xEC, 0x42, 0x7B, 0x1F
   95 };
   96 const unsigned char VID_NATT_RFC[] = { /* "RFC 3947" */
   97     0x4A, 0x13, 0x1C, 0x81, 0x07, 0x03, 0x58, 0x45,
   98     0x5C, 0x57, 0x28, 0xF2, 0x0E, 0x95, 0x45, 0x2F
   99 };
  100 const unsigned char VID_DWR[] = { /* DWR: Delete with reason */
  101     0x2D, 0x79, 0x22, 0xC6, 0xB3, 0x01, 0xD9, 0xB0,
  102     0xE1, 0x34, 0x27, 0x39, 0xE9, 0xCF, 0xBB, 0xD5
  103 };
  104 /* Cisco Unknown1:
  105  *const unsigned char VID_CISCO_UNKNOWN_1[] = {
  106  *  1f07f70eaa6514d3b0fa96542a500407
  107  *};
  108  */
  109 
  110 const unsigned char VID_CISCO_FRAG[] = { /* "FRAGMENTATION" */
  111     0x40, 0x48, 0xB7, 0xD5, 0x6E, 0xBC, 0xE8, 0x85,
  112     0x25, 0xE7, 0xDE, 0x7F, 0x00, 0xD6, 0xC2, 0xD3,
  113     0x80, 0x00, 0x00, 0x00
  114 };
  115 const unsigned char VID_NETSCREEN_15[] = { /* netscreen 15 */
  116     0x16, 0x6f, 0x93, 0x2d, 0x55, 0xeb, 0x64, 0xd8,
  117     0xe4, 0xdf, 0x4f, 0xd3, 0x7e, 0x23, 0x13, 0xf0,
  118     0xd0, 0xfd, 0x84, 0x51, 0x00, 0x00, 0x00, 0x00,
  119     0x00, 0x00, 0x00, 0x00
  120 };
  121 const unsigned char VID_HEARTBEAT_NOTIFY[] = { /* Heartbeat Notify */
  122     0x48, 0x65, 0x61, 0x72, 0x74, 0x42, 0x65, 0x61,
  123     0x74, 0x5f, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79,
  124     0x38, 0x6b, 0x01, 0x00
  125 };
  126 const unsigned char VID_NORTEL_CONT[] = { /* BNES: Bay Networks Enterprise Switch + version/id of some kind */
  127     0x42, 0x4e, 0x45, 0x53, 0x00, 0x00, 0x00, 0x0a
  128 };
  129 
  130 const unsigned char FW_UNKNOWN_TYPEINFO[] = {
  131     0x80, 0x01, 0x00, 0x01, 0x80, 0x02, 0x00, 0x01,
  132     0x80, 0x03, 0x00, 0x02
  133 };
  134 
  135 struct vid_element {
  136     const unsigned char* valueptr;
  137     const uint16_t length;
  138     const char* descr;
  139 };
  140 
  141 const struct vid_element vid_list[] = {
  142     { VID_XAUTH,        sizeof(VID_XAUTH),  "Xauth" },  
  143     { VID_DPD,      sizeof(VID_DPD),    "DPD" },    
  144     { VID_UNITY,        sizeof(VID_UNITY),  "Cisco Unity" },    
  145     { VID_NATT_00,      sizeof(VID_NATT_00),    "Nat-T 00" },   
  146     { VID_NATT_01,      sizeof(VID_NATT_01),    "Nat-T 01" },   
  147     { VID_NATT_02,      sizeof(VID_NATT_02),    "Nat-T 02" },   
  148     { VID_NATT_02N,     sizeof(VID_NATT_02N),   "Nat-T 02N" },  
  149     { VID_NATT_RFC,     sizeof(VID_NATT_RFC),   "Nat-T RFC" },  
  150     { VID_DWR,      sizeof(VID_DWR),    "Delete With Reason" }, 
  151     { VID_CISCO_FRAG,   sizeof(VID_CISCO_FRAG), "Cisco Fragmentation" },
  152     { VID_NETSCREEN_15, sizeof(VID_NETSCREEN_15),   "Netscreen 15" },
  153     { VID_NORTEL_CONT,  sizeof(VID_NORTEL_CONT),    "Nortel Contivity" },
  154     { VID_HEARTBEAT_NOTIFY, sizeof(VID_HEARTBEAT_NOTIFY),   "Heartbeat Notify" },
  155 
  156     { NULL, 0, NULL }
  157 };
  158 
  159 /* What are DWR-Code and DWR-Text ? */
  160 
  161 static uint8_t r_packet[8192];
  162 static ssize_t r_length;
  163 
  164 void print_vid(const unsigned char *vid, uint16_t len) {
  165     
  166     int vid_index = 0;
  167 
  168     if (opt_debug < 2)
  169         return;
  170 
  171     while (vid_list[vid_index].length) {
  172         if (len == vid_list[vid_index].length &&
  173             memcmp(vid_list[vid_index].valueptr, vid, len) == 0) {
  174             printf("   (%s)\n", vid_list[vid_index].descr);
  175             return;
  176         }
  177         vid_index++;
  178     }
  179     printf("   (unknown)\n");
  180 }
  181 
  182 static __inline__ int min(int a, int b)
  183 {
  184     return (a < b) ? a : b;
  185 }
  186 
  187 static void addenv(const void *name, const char *value)
  188 {
  189     char *strbuf = NULL, *oldval;
  190 
  191     oldval = getenv(name);
  192     if (oldval != NULL) {
  193         strbuf = xallocc(strlen(oldval) + 1 + strlen(value) + 1);
  194         strcat(strbuf, oldval);
  195         strcat(strbuf, " ");
  196         strcat(strbuf, value);
  197     }
  198 
  199     setenv(name, strbuf ? strbuf : value, 1);
  200 
  201     free(strbuf);
  202 }
  203 
  204 static void addenv_ipv4(const void *name, uint8_t * data)
  205 {
  206     addenv(name, inet_ntoa(*((struct in_addr *)data)));
  207 }
  208 
  209 static int make_socket(struct sa_block *s, uint16_t src_port, uint16_t dst_port)
  210 {
  211     int sock;
  212     struct sockaddr_in name;
  213     socklen_t len = sizeof(name);
  214 
  215     /* create the socket */
  216     sock = socket(PF_INET, SOCK_DGRAM, 0);
  217     if (sock < 0)
  218         error(1, errno, "making socket");
  219 
  220 #ifdef FD_CLOEXEC
  221     /* do not pass socket to vpnc-script, etc. */
  222     fcntl(sock, F_SETFD, FD_CLOEXEC);
  223 #endif
  224 
  225     /* give the socket a name */
  226     name.sin_family = AF_INET;
  227     name.sin_addr = s->opt_src_ip;
  228     name.sin_port = htons(src_port);
  229     if (bind(sock, (struct sockaddr *)&name, sizeof(name)) < 0)
  230         error(1, errno, "Error binding to source port. Try '--local-port 0'\nFailed to bind to %s:%d", inet_ntoa(s->opt_src_ip), src_port);
  231 
  232     /* connect the socket */
  233     name.sin_family = AF_INET;
  234     name.sin_addr = s->dst;
  235     name.sin_port = htons(dst_port);
  236     if (connect(sock, (struct sockaddr *)&name, sizeof(name)) < 0)
  237         error(1, errno, "connecting to port %d", ntohs(dst_port));
  238 
  239     /* who am I */
  240     if (getsockname(sock, (struct sockaddr *)&name, &len) < 0)
  241         error(1, errno, "reading local address from socket %d", sock);
  242     s->src = name.sin_addr;
  243     
  244     return sock;
  245 }
  246 
  247 static void cleanup(struct sa_block *s) {
  248     if (s->ike_fd != 0) {
  249         close(s->ike_fd);
  250         s->ike_fd = 0;
  251     }
  252     if (s->esp_fd != 0) {
  253         close(s->esp_fd);
  254         s->esp_fd = 0;
  255     }
  256     if (s->ike.resend_hash) {
  257         free(s->ike.resend_hash);
  258         s->ike.resend_hash = NULL;
  259     }
  260     if (s->ike.skeyid_d) {
  261         free(s->ike.skeyid_d);
  262         s->ike.skeyid_d = NULL;
  263     }
  264     if (s->ike.skeyid_a) {
  265         free(s->ike.skeyid_a);
  266         s->ike.skeyid_a = NULL;
  267     }
  268     if (s->ike.initial_iv) {
  269         free(s->ike.initial_iv);
  270         s->ike.initial_iv = NULL;
  271     }
  272     if (s->ike.current_iv) {
  273         free(s->ike.current_iv);
  274         s->ike.current_iv = NULL;
  275     }
  276     if (s->ike.key) {
  277         free(s->ike.key);
  278         s->ike.key = NULL;
  279     }
  280     if (s->ipsec.rx.key) {
  281         free(s->ipsec.rx.key);
  282         s->ipsec.rx.key = NULL;
  283     }
  284     if (s->ipsec.tx.key) {
  285         free(s->ipsec.tx.key);
  286         s->ipsec.tx.key = NULL;
  287     }
  288     if (s->ipsec.rx.cry_ctx) {
  289         gcry_cipher_close(s->ipsec.rx.cry_ctx);
  290         s->ipsec.rx.cry_ctx = NULL;
  291     }
  292     if (s->ipsec.tx.cry_ctx) {
  293         gcry_cipher_close(s->ipsec.tx.cry_ctx);
  294         s->ipsec.tx.cry_ctx = NULL;
  295     }
  296 }
  297 
  298 static void init_sockaddr(struct in_addr *dst, const char *hostname)
  299 {
  300     struct hostent *hostinfo;
  301 
  302     if (inet_aton(hostname, dst) == 0) {
  303         hostinfo = gethostbyname(hostname);
  304         if (hostinfo == NULL)
  305             error(1, 0, "unknown host `%s'\n", hostname);
  306         *dst = *(struct in_addr *)hostinfo->h_addr;
  307     }
  308 }
  309 
  310 static void init_netaddr(struct in_addr *net, const char *string)
  311 {
  312     char *p;
  313 
  314     if ((p = strchr(string, '/')) != NULL) {
  315         char *host = xallocc(p - string + 1);
  316         memcpy(host, string, p - string + 1);
  317         host[p - string] = '\0';
  318         init_sockaddr((struct in_addr *)net, host);
  319         free(host);
  320         if (strchr(p + 1, '.') != NULL)
  321             init_sockaddr(net + 1, p + 1);
  322         else {
  323             int bits = atoi(p + 1);
  324             unsigned long mask = (1 << bits) - 1;
  325             memcpy((char *)(net + 1), (char *)&mask, 4);
  326         }
  327     } else {
  328         memset((char *)net, 0, 8);
  329     }
  330 }
  331 
  332 static void setup_tunnel(struct sa_block *s)
  333 {
  334     setenv("reason", "pre-init", 1);
  335     system(config[CONFIG_SCRIPT]);
  336     
  337     if (config[CONFIG_IF_NAME])
  338         memcpy(s->tun_name, config[CONFIG_IF_NAME], strlen(config[CONFIG_IF_NAME]));
  339 
  340     s->tun_fd = tun_open(s->tun_name, opt_if_mode);
  341     DEBUG(2, printf("using interface %s\n", s->tun_name));
  342     setenv("TUNDEV", s->tun_name, 1);
  343 
  344     if (s->tun_fd == -1)
  345         error(1, errno, "can't initialise tunnel interface");
  346 #ifdef FD_CLOEXEC
  347     /* do not pass socket to vpnc-script, etc. */
  348     fcntl(s->tun_fd, F_SETFD, FD_CLOEXEC);
  349 #endif
  350     
  351     if (opt_if_mode == IF_MODE_TAP) {
  352         if (tun_get_hwaddr(s->tun_fd, s->tun_name, s->tun_hwaddr) < 0) {
  353             error(1, errno, "can't get tunnel HW address");
  354         }
  355         hex_dump("interface HW addr", s->tun_hwaddr, ETH_ALEN, NULL);
  356     }
  357 }
  358 
  359 static void config_tunnel(struct sa_block *s)
  360 {
  361     setenv("VPNGATEWAY", inet_ntoa(s->dst), 1);
  362     setenv("reason", "connect", 1);
  363     system(config[CONFIG_SCRIPT]);
  364 }
  365 
  366 static void close_tunnel(struct sa_block *s)
  367 {
  368     setenv("reason", "disconnect", 1);
  369     system(config[CONFIG_SCRIPT]);
  370     tun_close(s->tun_fd, s->tun_name);
  371 }
  372 
  373 static int recv_ignore_dup(struct sa_block *s, void *recvbuf, size_t recvbufsize)
  374 {
  375     uint8_t *resend_check_hash;
  376     int recvsize, hash_len;
  377 
  378     recvsize = recv(s->ike_fd, recvbuf, recvbufsize, 0);
  379     if (recvsize < 0)
  380         error(1, errno, "receiving packet");
  381     if ((unsigned int)recvsize > recvbufsize)
  382         error(1, errno, "received packet too large for buffer");
  383 
  384     /* skip (not only) NAT-T draft-0 keepalives */
  385     if ( /* (s->ipsec.natt_active_mode == NATT_ACTIVE_DRAFT_OLD) && */
  386         (recvsize == 1) && (*((u_char *)(recvbuf)) == 0xff))
  387     {
  388         if ((s->ipsec.natt_active_mode != NATT_ACTIVE_DRAFT_OLD))
  389         {
  390             DEBUG(2, printf("Received UDP NAT-Keepalive bug nat active mode incorrect: %d\n", s->ipsec.natt_active_mode));
  391         }
  392         return -1;
  393     }
  394     
  395     hash_len = gcry_md_get_algo_dlen(GCRY_MD_SHA1);
  396     resend_check_hash = malloc(hash_len);
  397     gcry_md_hash_buffer(GCRY_MD_SHA1, resend_check_hash, recvbuf, recvsize);
  398     if (s->ike.resend_hash && memcmp(s->ike.resend_hash, resend_check_hash, hash_len) == 0) {
  399         free(resend_check_hash);
  400         return -1;
  401     }
  402     if (!s->ike.resend_hash) {
  403         s->ike.resend_hash = resend_check_hash;
  404     } else {
  405         memcpy(s->ike.resend_hash, resend_check_hash, hash_len);
  406         free(resend_check_hash);
  407     }
  408     
  409     return recvsize;
  410 }
  411 
  412 /* Send TOSEND of size SENDSIZE to the socket.  Then wait for a new packet,
  413    resending TOSEND on timeout, and ignoring duplicate packets; the
  414    new packet is put in RECVBUF of size RECVBUFSIZE and the actual size
  415    of the new packet is returned.  */
  416 
  417 static ssize_t sendrecv(struct sa_block *s, void *recvbuf, size_t recvbufsize, void *tosend, size_t sendsize, int sendonly)
  418 {
  419     struct pollfd pfd;
  420     int tries = 0;
  421     int recvsize = -1;
  422     time_t start = time(NULL);
  423     time_t end = 0;
  424     void *realtosend;
  425 
  426     pfd.fd = s->ike_fd;
  427     pfd.events = POLLIN;
  428     tries = 0;
  429 
  430     if ((s->ipsec.natt_active_mode == NATT_ACTIVE_RFC) && (tosend != NULL)) {
  431         DEBUG(2, printf("NAT-T mode, adding non-esp marker\n"));
  432         realtosend = xallocc(sendsize+4);
  433         memmove((char*)realtosend+4, tosend, sendsize);
  434         sendsize += 4;
  435     } else {
  436         realtosend = tosend;
  437     }
  438 
  439     for (;;) {
  440         int pollresult;
  441 
  442         if (realtosend != NULL)
  443             if (write(s->ike_fd, realtosend, sendsize) != (int)sendsize)
  444                 error(1, errno, "can't send packet");
  445         if (sendonly)
  446             break;
  447         
  448         do {
  449             pollresult = poll(&pfd, 1, s->ike.timeout << tries);
  450         } while (pollresult == -1 && errno == EINTR);
  451         
  452         if (pollresult == -1)
  453             error(1, errno, "can't poll socket");
  454         if (pollresult != 0) {
  455             recvsize = recv_ignore_dup(s, recvbuf, recvbufsize);
  456             end = time(NULL);
  457             if (recvsize != -1)
  458                 break;
  459             continue;
  460         }
  461         
  462         if (tries > 2)
  463             error(1, 0, "no response from target");
  464         tries++;
  465     }
  466 
  467     if (realtosend != tosend)
  468         free(realtosend);
  469 
  470     if (sendonly)
  471         return 0;
  472 
  473     if ((s->ipsec.natt_active_mode == NATT_ACTIVE_RFC)&&(recvsize > 4)) {
  474         recvsize -= 4; /* 4 bytes non-esp marker */
  475         memmove(recvbuf, (char *)recvbuf+4, recvsize);
  476     }
  477 
  478     DEBUGTOP(3, printf("\n receiving: <========================\n"));
  479 
  480     /* Wait at least 2s for a response or 4 times the time it took
  481      * last time.  */
  482     if (start >= end)
  483         s->ike.timeout = 2000;
  484     else
  485         s->ike.timeout = 4000 * (end - start);
  486 
  487     return recvsize;
  488 }
  489 
  490 static int isakmp_crypt(struct sa_block *s, uint8_t * block, size_t blocklen, int enc)
  491 {
  492     unsigned char *new_iv, *iv = NULL;
  493     int info_ex;
  494     gcry_cipher_hd_t cry_ctx;
  495 
  496     if (blocklen < ISAKMP_PAYLOAD_O || ((blocklen - ISAKMP_PAYLOAD_O) % s->ike.ivlen != 0))
  497         abort();
  498 
  499     if (!enc && (memcmp(block + ISAKMP_I_COOKIE_O, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH) != 0
  500         || memcmp(block + ISAKMP_R_COOKIE_O, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH) != 0)) {
  501         DEBUG(2, printf("got paket with wrong cookies\n"));
  502         return ISAKMP_N_INVALID_COOKIE;
  503     }
  504     
  505     info_ex = block[ISAKMP_EXCHANGE_TYPE_O] == ISAKMP_EXCHANGE_INFORMATIONAL;
  506     
  507     if (memcmp(block + ISAKMP_MESSAGE_ID_O, s->ike.current_iv_msgid, 4) != 0) {
  508         gcry_md_hd_t md_ctx;
  509 
  510         gcry_md_open(&md_ctx, s->ike.md_algo, 0);
  511         gcry_md_write(md_ctx, s->ike.initial_iv, s->ike.ivlen);
  512         gcry_md_write(md_ctx, block + ISAKMP_MESSAGE_ID_O, 4);
  513         gcry_md_final(md_ctx);
  514         if (info_ex) {
  515             iv = xallocc(s->ike.ivlen);
  516             memcpy(iv, gcry_md_read(md_ctx, 0), s->ike.ivlen);
  517         } else {
  518             memcpy(s->ike.current_iv, gcry_md_read(md_ctx, 0), s->ike.ivlen);
  519             memcpy(s->ike.current_iv_msgid, block + ISAKMP_MESSAGE_ID_O, 4);
  520         }
  521         gcry_md_close(md_ctx);
  522     } else if (info_ex) {
  523         abort();
  524     }
  525     
  526     if (!info_ex) {
  527         iv = s->ike.current_iv;
  528     }
  529 
  530     new_iv = xallocc(s->ike.ivlen);
  531     gcry_cipher_open(&cry_ctx, s->ike.cry_algo, GCRY_CIPHER_MODE_CBC, 0);
  532     gcry_cipher_setkey(cry_ctx, s->ike.key, s->ike.keylen);
  533     gcry_cipher_setiv(cry_ctx, iv, s->ike.ivlen);
  534     if (!enc) {
  535         memcpy(new_iv, block + blocklen - s->ike.ivlen, s->ike.ivlen);
  536         gcry_cipher_decrypt(cry_ctx, block + ISAKMP_PAYLOAD_O, blocklen - ISAKMP_PAYLOAD_O,
  537             NULL, 0);
  538         if (!info_ex)
  539             memcpy(s->ike.current_iv, new_iv, s->ike.ivlen);
  540     } else {
  541         gcry_cipher_encrypt(cry_ctx, block + ISAKMP_PAYLOAD_O, blocklen - ISAKMP_PAYLOAD_O,
  542             NULL, 0);
  543         if (!info_ex)
  544             memcpy(s->ike.current_iv, block + blocklen - s->ike.ivlen, s->ike.ivlen);
  545     }
  546     gcry_cipher_close(cry_ctx);
  547     
  548     free(new_iv);
  549     if (info_ex)
  550         free(iv);
  551     
  552     return 0;
  553 }
  554 
  555 static uint16_t unpack_verify_phase2(struct sa_block *s, uint8_t * r_packet,
  556     size_t r_length, struct isakmp_packet **r_p, const uint8_t * nonce, size_t nonce_size)
  557 {
  558     struct isakmp_packet *r;
  559     int reject = 0;
  560     
  561     *r_p = NULL;
  562 
  563     /* Some users report "payload ... not padded..." errors. It seems that they
  564      * are harmless, so ignore and fix the symptom
  565      */
  566     if (r_length < ISAKMP_PAYLOAD_O ||
  567         ((r_length - ISAKMP_PAYLOAD_O) % s->ike.ivlen != 0)) {
  568         DEBUG(2, printf("payload too short or not padded: len=%lld, min=%d (ivlen=%lld)\n",
  569             (long long)r_length, ISAKMP_PAYLOAD_O, (long long)s->ike.ivlen));
  570         hex_dump("Payload", r_packet, r_length, NULL);
  571         if (r_length < ISAKMP_PAYLOAD_O ) {
  572             return ISAKMP_N_UNEQUAL_PAYLOAD_LENGTHS;
  573         }
  574         r_length -= (r_length - ISAKMP_PAYLOAD_O) % s->ike.ivlen;
  575     }
  576 
  577     reject = isakmp_crypt(s, r_packet, r_length, 0);
  578     if (reject != 0)
  579         return reject;
  580 
  581     s->ike.life.rx += r_length;
  582     
  583     {
  584         r = parse_isakmp_packet(r_packet, r_length, &reject);
  585         if (reject != 0) {
  586             if (r) free_isakmp_packet(r);
  587             return reject;
  588         }
  589     }
  590 
  591     /* Verify the basic stuff.  */
  592     if (r->flags != ISAKMP_FLAG_E) {
  593         free_isakmp_packet(r);
  594         return ISAKMP_N_INVALID_FLAGS;
  595     }
  596 
  597     {
  598         size_t sz, spos;
  599         gcry_md_hd_t hm;
  600         unsigned char *expected_hash;
  601         struct isakmp_payload *h = r->payload;
  602 
  603         if (h == NULL || h->type != ISAKMP_PAYLOAD_HASH || h->u.hash.length != s->ike.md_len) {
  604             free_isakmp_packet(r);
  605             return ISAKMP_N_INVALID_HASH_INFORMATION;
  606         }
  607 
  608         spos = (ISAKMP_PAYLOAD_O + (r_packet[ISAKMP_PAYLOAD_O + 2] << 8)
  609             + r_packet[ISAKMP_PAYLOAD_O + 3]);
  610 
  611         /* Compute the real length based on the payload lengths.  */
  612         for (sz = spos; r_packet[sz] != 0; sz += r_packet[sz + 2] << 8 | r_packet[sz + 3]) ;
  613         sz += r_packet[sz + 2] << 8 | r_packet[sz + 3];
  614 
  615         gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
  616         gcry_md_setkey(hm, s->ike.skeyid_a, s->ike.md_len);
  617         gcry_md_write(hm, r_packet + ISAKMP_MESSAGE_ID_O, 4);
  618         if (nonce)
  619             gcry_md_write(hm, nonce, nonce_size);
  620         gcry_md_write(hm, r_packet + spos, sz - spos);
  621         gcry_md_final(hm);
  622         expected_hash = gcry_md_read(hm, 0);
  623 
  624         DEBUG(3,printf("hashlen: %lu\n", (unsigned long)s->ike.md_len));
  625         DEBUG(3,printf("u.hash.length: %d\n", h->u.hash.length));
  626         hex_dump("expected_hash", expected_hash, s->ike.md_len, NULL);
  627         hex_dump("h->u.hash.data", h->u.hash.data, s->ike.md_len, NULL);
  628 
  629         reject = 0;
  630         if (memcmp(h->u.hash.data, expected_hash, s->ike.md_len) != 0)
  631             reject = ISAKMP_N_AUTHENTICATION_FAILED;
  632         gcry_md_close(hm);
  633 #if 0
  634         if (reject != 0) {
  635             free_isakmp_packet(r);
  636             return reject;
  637         }
  638 #endif
  639     }
  640     *r_p = r;
  641     return 0;
  642 }
  643 
  644 static void
  645 phase2_authpacket(struct sa_block *s, struct isakmp_payload *pl,
  646     uint8_t exchange_type, uint32_t msgid,
  647     uint8_t ** p_flat, size_t * p_size,
  648     uint8_t * nonce_i, int ni_len, uint8_t * nonce_r, int nr_len)
  649 {
  650     struct isakmp_packet *p;
  651     uint8_t *pl_flat;
  652     size_t pl_size;
  653     gcry_md_hd_t hm;
  654     uint8_t msgid_sent[4];
  655 
  656     /* Build up the packet.  */
  657     p = new_isakmp_packet();
  658     memcpy(p->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
  659     memcpy(p->r_cookie, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
  660     p->flags = ISAKMP_FLAG_E;
  661     p->isakmp_version = ISAKMP_VERSION;
  662     p->exchange_type = exchange_type;
  663     p->message_id = msgid;
  664     p->payload = new_isakmp_payload(ISAKMP_PAYLOAD_HASH);
  665     p->payload->next = pl;
  666     p->payload->u.hash.length = s->ike.md_len;
  667     p->payload->u.hash.data = xallocc(s->ike.md_len);
  668 
  669     /* Set the MAC.  */
  670     gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
  671     gcry_md_setkey(hm, s->ike.skeyid_a, s->ike.md_len);
  672 
  673     if (pl == NULL) {
  674         DEBUG(3, printf("authing NULL package!\n"));
  675         gcry_md_write(hm, "" /* \0 */ , 1);
  676     }
  677 
  678     msgid_sent[0] = msgid >> 24;
  679     msgid_sent[1] = msgid >> 16;
  680     msgid_sent[2] = msgid >> 8;
  681     msgid_sent[3] = msgid;
  682     gcry_md_write(hm, msgid_sent, sizeof(msgid_sent));
  683 
  684     if (nonce_i != NULL)
  685         gcry_md_write(hm, nonce_i, ni_len);
  686 
  687     if (nonce_r != NULL)
  688         gcry_md_write(hm, nonce_r, nr_len);
  689 
  690     if (pl != NULL) {
  691         flatten_isakmp_payloads(pl, &pl_flat, &pl_size);
  692         gcry_md_write(hm, pl_flat, pl_size);
  693         memset(pl_flat, 0, pl_size);
  694         free(pl_flat);
  695     }
  696 
  697     gcry_md_final(hm);
  698     memcpy(p->payload->u.hash.data, gcry_md_read(hm, 0), s->ike.md_len);
  699     gcry_md_close(hm);
  700 
  701     flatten_isakmp_packet(p, p_flat, p_size, s->ike.ivlen);
  702     free_isakmp_packet(p);
  703 }
  704 
  705 static void sendrecv_phase2(struct sa_block *s, struct isakmp_payload *pl,
  706     uint8_t exchange_type, uint32_t msgid, int sendonly,
  707     uint8_t ** save_p_flat, size_t * save_p_size,
  708     uint8_t * nonce_i, int ni_len, uint8_t * nonce_r, int nr_len)
  709 {
  710     uint8_t *p_flat;
  711     size_t p_size;
  712     ssize_t recvlen;
  713 
  714     if ((save_p_flat == NULL) || (*save_p_flat == NULL)) {
  715         phase2_authpacket(s, pl, exchange_type, msgid, &p_flat, &p_size,
  716             nonce_i, ni_len, nonce_r, nr_len);
  717         isakmp_crypt(s, p_flat, p_size, 1);
  718     } else {
  719         p_flat = *save_p_flat;
  720         p_size = *save_p_size;
  721     }
  722 
  723     s->ike.life.tx += p_size;
  724 
  725     recvlen = sendrecv(s, r_packet, sizeof(r_packet), p_flat, p_size, sendonly);
  726     if (sendonly == 0)
  727         r_length = recvlen;
  728     
  729     if (save_p_flat == NULL) {
  730         free(p_flat);
  731     } else {
  732         *save_p_flat = p_flat;
  733         *save_p_size = p_size;
  734     }
  735 }
  736 
  737 static void send_phase2_late(struct sa_block *s, struct isakmp_payload *pl,
  738     uint8_t exchange_type, uint32_t msgid)
  739 {
  740     struct isakmp_packet *p;
  741     uint8_t *p_flat;
  742     size_t p_size;
  743     ssize_t recvlen;
  744 
  745     /* Build up the packet.  */
  746     p = new_isakmp_packet();
  747     memcpy(p->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
  748     memcpy(p->r_cookie, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
  749     p->flags = ISAKMP_FLAG_E;
  750     p->isakmp_version = ISAKMP_VERSION;
  751     p->exchange_type = exchange_type;
  752     p->message_id = msgid;
  753     p->payload = pl;
  754 
  755     flatten_isakmp_packet(p, &p_flat, &p_size, s->ike.ivlen);
  756     free_isakmp_packet(p);
  757     isakmp_crypt(s, p_flat, p_size, 1);
  758 
  759     s->ike.life.tx += p_size;
  760 
  761     recvlen = sendrecv(s, NULL, 0, p_flat, p_size, 1);
  762     free(p_flat);
  763 }
  764 
  765 void keepalive_ike(struct sa_block *s)
  766 {
  767     uint32_t msgid;
  768 
  769     gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
  770     send_phase2_late(s, NULL, ISAKMP_EXCHANGE_INFORMATIONAL, msgid);
  771 }
  772 
  773 static void send_dpd(struct sa_block *s, int isack, uint32_t seqno)
  774 {
  775     struct isakmp_payload *pl;
  776     uint32_t msgid;
  777     
  778     pl = new_isakmp_payload(ISAKMP_PAYLOAD_N);
  779     pl->u.n.doi = ISAKMP_DOI_IPSEC;
  780     pl->u.n.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
  781     pl->u.n.type = isack ? ISAKMP_N_R_U_THERE_ACK : ISAKMP_N_R_U_THERE;
  782     pl->u.n.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
  783     pl->u.n.spi = xallocc(2 * ISAKMP_COOKIE_LENGTH);
  784     memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 0, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
  785     memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 1, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
  786     pl->u.n.data_length = 4;
  787     pl->u.n.data = xallocc(4);
  788     memcpy(pl->u.n.data, &seqno, 4);
  789     gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
  790     /* 2007-09-06 JKU/ZID: Sonicwall drops non hashed r_u_there-requests */
  791     sendrecv_phase2(s, pl, ISAKMP_EXCHANGE_INFORMATIONAL, msgid,
  792         1 , NULL, NULL, NULL, 0, NULL, 0);
  793 }
  794 
  795 void dpd_ike(struct sa_block *s)
  796 {
  797     if (!s->ike.do_dpd)
  798         return;
  799     
  800     if (s->ike.dpd_seqno == s->ike.dpd_seqno_ack) {
  801         /* Increase the sequence number, reset the attempts to 6, record
  802         ** the current time and send a dpd request
  803         */
  804         s->ike.dpd_attempts = 6;
  805         s->ike.dpd_sent = time(NULL);
  806         ++s->ike.dpd_seqno;
  807         send_dpd(s, 0, s->ike.dpd_seqno);
  808     } else {
  809         /* Our last dpd request has not yet been acked.  If it's been
  810         ** less than 5 seconds since we sent it do nothing.  Otherwise
  811         ** decrement dpd_attempts.  If dpd_attempts is 0 dpd fails and we
  812         ** terminate otherwise we send it again with the same sequence
  813         ** number and record current time.
  814         */
  815         time_t now = time(NULL);
  816         if (now < s->ike.dpd_sent + 5)
  817             return;
  818         if (--s->ike.dpd_attempts == 0) {
  819             DEBUG(2, printf("dead peer detected, terminating\n"));
  820             do_kill = -2;
  821             return;
  822         }
  823         s->ike.dpd_sent = now;
  824         send_dpd(s, 0, s->ike.dpd_seqno);
  825     }
  826 }
  827 
  828 static void phase2_fatal(struct sa_block *s, const char *msg, int id)
  829 {
  830     struct isakmp_payload *pl;
  831     uint32_t msgid;
  832 
  833     DEBUG(1, printf("\n\n---!!!!!!!!! entering phase2_fatal !!!!!!!!!---\n\n\n"));
  834     gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
  835     pl = new_isakmp_payload(ISAKMP_PAYLOAD_N);
  836     pl->u.n.doi = ISAKMP_DOI_IPSEC;
  837     pl->u.n.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
  838     pl->u.n.type = id;
  839     sendrecv_phase2(s, pl, ISAKMP_EXCHANGE_INFORMATIONAL, msgid, 1, 0, 0, 0, 0, 0, 0);
  840 
  841     gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
  842     pl = new_isakmp_payload(ISAKMP_PAYLOAD_D);
  843     pl->u.d.doi = ISAKMP_DOI_IPSEC;
  844     pl->u.d.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
  845     pl->u.d.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
  846     pl->u.d.num_spi = 1;
  847     pl->u.d.spi = xallocc(1 * sizeof(uint8_t *));
  848     pl->u.d.spi[0] = xallocc(2 * ISAKMP_COOKIE_LENGTH);
  849     memcpy(pl->u.d.spi[0] + ISAKMP_COOKIE_LENGTH * 0, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
  850     memcpy(pl->u.d.spi[0] + ISAKMP_COOKIE_LENGTH * 1, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
  851     sendrecv_phase2(s, pl, ISAKMP_EXCHANGE_INFORMATIONAL, msgid, 1, 0, 0, 0, 0, 0, 0);
  852 
  853     error(1, 0, msg, val_to_string(id, isakmp_notify_enum_array), id);
  854 }
  855 
  856 static uint8_t *gen_keymat(struct sa_block *s,
  857     uint8_t protocol, uint32_t spi,
  858     const uint8_t * dh_shared, size_t dh_size,
  859     const uint8_t * ni_data, size_t ni_size, const uint8_t * nr_data, size_t nr_size)
  860 {
  861     gcry_md_hd_t hm;
  862     uint8_t *block;
  863     int i;
  864     int blksz;
  865     int cnt;
  866 
  867     blksz = s->ipsec.md_len + s->ipsec.key_len;
  868     cnt = (blksz + s->ike.md_len - 1) / s->ike.md_len;
  869     block = xallocc(cnt * s->ike.md_len);
  870     DEBUG(3, printf("generating %d bytes keymat (cnt=%d)\n", blksz, cnt));
  871     if (cnt < 1)
  872         abort();
  873 
  874     for (i = 0; i < cnt; i++) {
  875         gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
  876         gcry_md_setkey(hm, s->ike.skeyid_d, s->ike.md_len);
  877         if (i != 0)
  878             gcry_md_write(hm, block + (i - 1) * s->ike.md_len, s->ike.md_len);
  879         if (dh_shared != NULL)
  880             gcry_md_write(hm, dh_shared, dh_size);
  881         gcry_md_write(hm, &protocol, 1);
  882         gcry_md_write(hm, (uint8_t *) & spi, sizeof(spi));
  883         gcry_md_write(hm, ni_data, ni_size);
  884         gcry_md_write(hm, nr_data, nr_size);
  885         gcry_md_final(hm);
  886         memcpy(block + i * s->ike.md_len, gcry_md_read(hm, 0), s->ike.md_len);
  887         gcry_md_close(hm);
  888     }
  889     return block;
  890 }
  891 
  892 static int mask_to_masklen(struct in_addr mask)
  893 { 
  894     int len;
  895     uint32_t addr;
  896     
  897     addr = ntohl(mask.s_addr);
  898     for (len = 0; addr; addr <<= 1, len++)
  899         ;
  900     return len;
  901 }
  902 
  903 static int do_config_to_env(struct sa_block *s, struct isakmp_attribute *a)
  904 {
  905     int i;
  906     int reject = 0;
  907     int seen_address = 0;
  908     char *strbuf, *strbuf2;
  909     
  910     unsetenv("CISCO_BANNER");
  911     unsetenv("CISCO_DEF_DOMAIN");
  912     unsetenv("CISCO_SPLIT_INC");
  913     unsetenv("INTERNAL_IP4_NBNS");
  914     unsetenv("INTERNAL_IP4_DNS");
  915     unsetenv("INTERNAL_IP4_NETMASK");
  916     unsetenv("INTERNAL_IP4_ADDRESS");
  917 
  918     for (; a && reject == 0; a = a->next)
  919         switch (a->type) {
  920         case ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_ADDRESS:
  921             if (a->af != isakmp_attr_lots || a->u.lots.length != 4)
  922                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
  923             else {
  924                 addenv_ipv4("INTERNAL_IP4_ADDRESS", a->u.lots.data);
  925                 memcpy(s->our_address, a->u.lots.data, 4);
  926             }
  927             seen_address = 1;
  928             break;
  929 
  930         case ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_NETMASK:
  931             if (a->af == isakmp_attr_lots && a->u.lots.length == 0) {
  932                 DEBUG(2, printf("ignoring zero length netmask\n"));
  933                 continue;
  934             }
  935             if (a->af != isakmp_attr_lots || a->u.lots.length != 4)
  936                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
  937             else {
  938                 uint32_t netaddr = ((struct in_addr *)(s->our_address))->s_addr & ((struct in_addr *)(a->u.lots.data))->s_addr;
  939                 addenv_ipv4("INTERNAL_IP4_NETMASK", a->u.lots.data);
  940                 asprintf(&strbuf, "%d", mask_to_masklen(*((struct in_addr *)a->u.lots.data)));
  941                 setenv("INTERNAL_IP4_NETMASKLEN", strbuf, 1);
  942                 free(strbuf);
  943                 addenv_ipv4("INTERNAL_IP4_NETADDR",  (uint8_t *)&netaddr);
  944             }
  945             break;
  946 
  947         case ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_DNS:
  948             if (a->af != isakmp_attr_lots || a->u.lots.length != 4)
  949                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
  950             else
  951                 addenv_ipv4("INTERNAL_IP4_DNS", a->u.lots.data);
  952             break;
  953 
  954         case ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_NBNS:
  955             if (a->af != isakmp_attr_lots || a->u.lots.length != 4)
  956                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
  957             else
  958                 addenv_ipv4("INTERNAL_IP4_NBNS", a->u.lots.data);
  959             break;
  960 
  961         case ISAKMP_MODECFG_ATTRIB_CISCO_DEF_DOMAIN:
  962             if (a->af != isakmp_attr_lots) {
  963                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
  964                 break;
  965             }
  966             strbuf = xallocc(a->u.lots.length + 1);
  967             memcpy(strbuf, a->u.lots.data, a->u.lots.length);
  968             addenv("CISCO_DEF_DOMAIN", strbuf);
  969             free(strbuf);
  970             break;
  971 
  972         case ISAKMP_MODECFG_ATTRIB_CISCO_BANNER:
  973             if (a->af != isakmp_attr_lots) {
  974                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
  975                 break;
  976             }
  977             strbuf = xallocc(a->u.lots.length + 1);
  978             memcpy(strbuf, a->u.lots.data, a->u.lots.length);
  979             addenv("CISCO_BANNER", strbuf);
  980             free(strbuf);
  981             DEBUG(1, printf("Banner: "));
  982             DEBUG(1, fwrite(a->u.lots.data, a->u.lots.length, 1, stdout));
  983             DEBUG(1, printf("\n"));
  984             break;
  985 
  986         case ISAKMP_MODECFG_ATTRIB_APPLICATION_VERSION:
  987             DEBUG(2, printf("Remote Application Version: "));
  988             DEBUG(2, fwrite(a->u.lots.data, a->u.lots.length, 1, stdout));
  989             DEBUG(2, printf("\n"));
  990             break;
  991 
  992         case ISAKMP_MODECFG_ATTRIB_CISCO_DO_PFS:
  993             if (a->af != isakmp_attr_16)
  994                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
  995             else {
  996                 s->ipsec.do_pfs = a->u.attr_16;
  997                 DEBUG(2, printf("got pfs setting: %d\n", s->ipsec.do_pfs));
  998             }
  999             break;
 1000 
 1001         case ISAKMP_MODECFG_ATTRIB_CISCO_UDP_ENCAP_PORT:
 1002             if (a->af != isakmp_attr_16)
 1003                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
 1004             else {
 1005                 s->ipsec.peer_udpencap_port = a->u.attr_16;
 1006                 DEBUG(2, printf("got peer udp encapsulation port: %hu\n", s->ipsec.peer_udpencap_port));
 1007             }
 1008             break;
 1009 
 1010         case ISAKMP_MODECFG_ATTRIB_CISCO_SPLIT_INC:
 1011             if (a->af != isakmp_attr_acl) {
 1012                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
 1013                 break;
 1014             }
 1015             
 1016             DEBUG(2, printf("got %d acls for split include\n", a->u.acl.count));
 1017             asprintf(&strbuf, "%d", a->u.acl.count);
 1018             setenv("CISCO_SPLIT_INC", strbuf, 1);
 1019             free(strbuf);
 1020             
 1021             for (i = 0; i < a->u.acl.count; i++) {
 1022                 DEBUG(2, printf("acl %d: ", i));
 1023                 /* NOTE: inet_ntoa returns one static buffer */
 1024                 
 1025                 asprintf(&strbuf, "CISCO_SPLIT_INC_%d_ADDR", i);
 1026                 asprintf(&strbuf2, "%s", inet_ntoa(a->u.acl.acl_ent[i].addr));
 1027                 DEBUG(2, printf("addr: %s/", strbuf2));
 1028                 setenv(strbuf, strbuf2, 1);
 1029                 free(strbuf); free(strbuf2);
 1030                 
 1031                 asprintf(&strbuf, "CISCO_SPLIT_INC_%d_MASK", i);
 1032                 asprintf(&strbuf2, "%s", inet_ntoa(a->u.acl.acl_ent[i].mask));
 1033                 DEBUG(2, printf("%s ", strbuf2));
 1034                 setenv(strbuf, strbuf2, 1);
 1035                 free(strbuf); free(strbuf2);
 1036                 
 1037                 /* this is just here because ip route does not accept netmasks */
 1038                 asprintf(&strbuf, "CISCO_SPLIT_INC_%d_MASKLEN", i);
 1039                 asprintf(&strbuf2, "%d", mask_to_masklen(a->u.acl.acl_ent[i].mask));
 1040                 DEBUG(2, printf("(%s), ", strbuf2));
 1041                 setenv(strbuf, strbuf2, 1);
 1042                 free(strbuf); free(strbuf2);
 1043                 
 1044                 asprintf(&strbuf, "CISCO_SPLIT_INC_%d_PROTOCOL", i);
 1045                 asprintf(&strbuf2, "%hu", a->u.acl.acl_ent[i].protocol);
 1046                 DEBUG(2, printf("protocol: %s, ", strbuf2));
 1047                 setenv(strbuf, strbuf2, 1);
 1048                 free(strbuf); free(strbuf2);
 1049                 
 1050                 asprintf(&strbuf, "CISCO_SPLIT_INC_%d_SPORT", i);
 1051                 asprintf(&strbuf2, "%hu", a->u.acl.acl_ent[i].sport);
 1052                 DEBUG(2, printf("sport: %s, ", strbuf2));
 1053                 setenv(strbuf, strbuf2, 1);
 1054                 free(strbuf); free(strbuf2);
 1055                 
 1056                 asprintf(&strbuf, "CISCO_SPLIT_INC_%d_DPORT", i);
 1057                 asprintf(&strbuf2, "%hu", a->u.acl.acl_ent[i].dport);
 1058                 DEBUG(2, printf("dport: %s\n", strbuf2));
 1059                 setenv(strbuf, strbuf2, 1);
 1060                 free(strbuf); free(strbuf2);
 1061             }
 1062             break;
 1063             
 1064         case ISAKMP_MODECFG_ATTRIB_CISCO_SAVE_PW:
 1065             DEBUG(2, printf("got save password setting: %d\n", a->u.attr_16));
 1066             break;
 1067             
 1068         default:
 1069             DEBUG(2, printf("unknown attribute %d / 0x%X\n", a->type, a->type));
 1070             break;
 1071         }
 1072 
 1073     if (reject == 0 && !seen_address)
 1074         reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
 1075     
 1076     return reject;
 1077 }
 1078 
 1079 /* * */
 1080 
 1081 static struct isakmp_attribute *make_transform_ike(int dh_group, int crypt, int hash, int keylen, int auth)
 1082 {
 1083     struct isakmp_attribute *a = NULL;
 1084 
 1085     a = new_isakmp_attribute(IKE_ATTRIB_LIFE_DURATION, a);
 1086     a->af = isakmp_attr_lots;
 1087     a->u.lots.length = 4;
 1088     a->u.lots.data = xallocc(a->u.lots.length);
 1089     *((uint32_t *) a->u.lots.data) = htonl(2147483);
 1090     a = new_isakmp_attribute_16(IKE_ATTRIB_LIFE_TYPE, IKE_LIFE_TYPE_SECONDS, a);
 1091     a = new_isakmp_attribute_16(IKE_ATTRIB_AUTH_METHOD, auth, a);
 1092     a = new_isakmp_attribute_16(IKE_ATTRIB_GROUP_DESC, dh_group, a);
 1093     a = new_isakmp_attribute_16(IKE_ATTRIB_HASH, hash, a);
 1094     a = new_isakmp_attribute_16(IKE_ATTRIB_ENC, crypt, a);
 1095     if (keylen != 0)
 1096         a = new_isakmp_attribute_16(IKE_ATTRIB_KEY_LENGTH, keylen, a);
 1097     return a;
 1098 }
 1099 
 1100 static struct isakmp_payload *make_our_sa_ike(void)
 1101 {
 1102     struct isakmp_payload *r = new_isakmp_payload(ISAKMP_PAYLOAD_SA);
 1103     struct isakmp_payload *t = NULL, *tn;
 1104     struct isakmp_attribute *a;
 1105     int dh_grp = get_dh_group_ike()->ike_sa_id;
 1106     unsigned int auth, crypt, hash, keylen;
 1107     int i;
 1108 
 1109     r->u.sa.doi = ISAKMP_DOI_IPSEC;
 1110     r->u.sa.situation = ISAKMP_IPSEC_SIT_IDENTITY_ONLY;
 1111     r->u.sa.proposals = new_isakmp_payload(ISAKMP_PAYLOAD_P);
 1112     r->u.sa.proposals->u.p.prot_id = ISAKMP_IPSEC_PROTO_ISAKMP;
 1113     for (auth = 0; supp_auth[auth].name != NULL; auth++) {
 1114         if (opt_auth_mode == AUTH_MODE_CERT) {
 1115             if ((supp_auth[auth].ike_sa_id != IKE_AUTH_RSA_SIG) &&
 1116                 (supp_auth[auth].ike_sa_id != IKE_AUTH_DSS))
 1117                 continue;
 1118         } else if (opt_auth_mode == AUTH_MODE_HYBRID) {
 1119             if ((supp_auth[auth].ike_sa_id != IKE_AUTH_HybridInitRSA) &&
 1120                 (supp_auth[auth].ike_sa_id != IKE_AUTH_HybridInitDSS)) 
 1121                 continue;
 1122         } else {
 1123             if (supp_auth[auth].ike_sa_id == IKE_AUTH_HybridInitRSA ||
 1124                 supp_auth[auth].ike_sa_id == IKE_AUTH_HybridInitDSS ||
 1125                 supp_auth[auth].ike_sa_id == IKE_AUTH_RSA_SIG ||
 1126                 supp_auth[auth].ike_sa_id == IKE_AUTH_DSS)
 1127                 continue;
 1128         }
 1129         for (crypt = 0; supp_crypt[crypt].name != NULL; crypt++) {
 1130             keylen = supp_crypt[crypt].keylen;
 1131             for (hash = 0; supp_hash[hash].name != NULL; hash++) {
 1132                 tn = t;
 1133                 t = new_isakmp_payload(ISAKMP_PAYLOAD_T);
 1134                 t->u.t.id = ISAKMP_IPSEC_KEY_IKE;
 1135                 a = make_transform_ike(dh_grp, supp_crypt[crypt].ike_sa_id,
 1136                     supp_hash[hash].ike_sa_id, keylen, supp_auth[auth].ike_sa_id);
 1137                 t->u.t.attributes = a;
 1138                 t->next = tn;
 1139             }
 1140         }
 1141     }
 1142     for (i = 0, tn = t; tn; tn = tn->next)
 1143         tn->u.t.number = i++;
 1144     r->u.sa.proposals->u.p.transforms = t;
 1145     return r;
 1146 }
 1147 
 1148 static void lifetime_ike_process(struct sa_block *s, struct isakmp_attribute *a)
 1149 {
 1150     uint32_t value;
 1151     
 1152     assert(a != NULL);
 1153     assert(a->type == IKE_ATTRIB_LIFE_TYPE);
 1154     assert(a->af == isakmp_attr_16);
 1155     assert(a->u.attr_16 == IKE_LIFE_TYPE_SECONDS || a->u.attr_16 == IKE_LIFE_TYPE_K);
 1156     assert(a->next != NULL);
 1157     assert(a->next->type == IKE_ATTRIB_LIFE_DURATION);
 1158     
 1159     if (a->next->af == isakmp_attr_16)
 1160         value = a->next->u.attr_16;
 1161     else if (a->next->af == isakmp_attr_lots && a->next->u.lots.length == 4)
 1162         value = ntohl(*((uint32_t *) a->next->u.lots.data));
 1163     else
 1164         assert(0);
 1165     
 1166     DEBUG(2, printf("got ike lifetime attributes: %d %s\n", value,
 1167         (a->u.attr_16 == IKE_LIFE_TYPE_SECONDS) ? "seconds" : "kilobyte"));
 1168     
 1169     if (a->u.attr_16 == IKE_LIFE_TYPE_SECONDS)
 1170         s->ike.life.seconds = value;
 1171     else
 1172         s->ike.life.kbytes = value;
 1173 }
 1174 
 1175 static void lifetime_ipsec_process(struct sa_block *s, struct isakmp_attribute *a)
 1176 {
 1177     uint32_t value;
 1178     
 1179     assert(a != NULL);
 1180     assert(a->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE);
 1181     assert(a->af == isakmp_attr_16);
 1182     assert(a->u.attr_16 == IPSEC_LIFE_SECONDS || a->u.attr_16 == IPSEC_LIFE_K);
 1183     assert(a->next != NULL);
 1184     assert(a->next->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION);
 1185     
 1186     if (a->next->af == isakmp_attr_16)
 1187         value = a->next->u.attr_16;
 1188     else if (a->next->af == isakmp_attr_lots && a->next->u.lots.length == 4)
 1189         value = ntohl(*((uint32_t *) a->next->u.lots.data));
 1190     else
 1191         assert(0);
 1192     
 1193     DEBUG(2, printf("got ipsec lifetime attributes: %d %s\n", value,
 1194         (a->u.attr_16 == IPSEC_LIFE_SECONDS) ? "seconds" : "kilobyte"));
 1195     
 1196     if (a->u.attr_16 == IPSEC_LIFE_SECONDS)
 1197         s->ipsec.life.seconds = value;
 1198     else
 1199         s->ipsec.life.kbytes = value;
 1200     
 1201     /* FIXME: for notice-payloads: write a seperate function to handle them */
 1202     /* bug: this may process lifetime-attributes of SAs twice but to no consequence */
 1203     if (a->next->next != NULL && a->next->next->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE)
 1204         lifetime_ipsec_process(s, a->next->next);
 1205 }
 1206 
 1207 static void do_phase1_am(const char *key_id, const char *shared_key, struct sa_block *s)
 1208 {
 1209     unsigned char i_nonce[20];
 1210     struct group *dh_grp;
 1211     unsigned char *dh_public;
 1212     unsigned char *returned_hash;
 1213     unsigned char *psk_hash;
 1214 
 1215     struct isakmp_packet *p1;
 1216     struct isakmp_packet *r;
 1217     int seen_natt_vid = 0, seen_natd = 0, seen_natd_them = 0, seen_natd_us = 0, natd_type = 0;
 1218     unsigned char *natd_us = NULL, *natd_them = NULL;
 1219     int natt_draft = -1;
 1220     unsigned char *dh_shared_secret;
 1221     
 1222     DEBUGTOP(2, printf("S4.1 create_nonce\n"));
 1223     gcry_create_nonce(s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1224     s->ike.life.start = time(NULL);
 1225     s->ipsec.do_pfs = -1;
 1226     if (s->ike.i_cookie[0] == 0)
 1227         s->ike.i_cookie[0] = 1;
 1228     hex_dump("i_cookie", s->ike.i_cookie, ISAKMP_COOKIE_LENGTH, NULL);
 1229     gcry_create_nonce(i_nonce, sizeof(i_nonce));
 1230     hex_dump("i_nonce", i_nonce, sizeof(i_nonce), NULL);
 1231     DEBUGTOP(2, printf("S4.2 dh setup\n"));
 1232     /* Set up the Diffie-Hellman stuff.  */
 1233     {
 1234         dh_grp = group_get(get_dh_group_ike()->my_id);
 1235         dh_public = xallocc(dh_getlen(dh_grp));
 1236         dh_create_exchange(dh_grp, dh_public);
 1237         hex_dump("dh_public", dh_public, dh_getlen(dh_grp), NULL);
 1238     }
 1239 
 1240     DEBUGTOP(2, printf("S4.3 AM packet_1\n"));
 1241     /* Create the first packet.  */
 1242     {
 1243         struct isakmp_payload *l;
 1244         uint8_t *pkt;
 1245         size_t pkt_len;
 1246 
 1247         p1 = new_isakmp_packet();
 1248         memcpy(p1->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1249         p1->isakmp_version = ISAKMP_VERSION;
 1250         p1->exchange_type = ISAKMP_EXCHANGE_AGGRESSIVE;
 1251         p1->payload = l = make_our_sa_ike();
 1252         l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_KE, dh_public, dh_getlen(dh_grp));
 1253         l->next->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_NONCE,
 1254             i_nonce, sizeof(i_nonce));
 1255         l = l->next->next;
 1256         l->next = new_isakmp_payload(ISAKMP_PAYLOAD_ID);
 1257         l = l->next;
 1258         if (opt_vendor == VENDOR_CISCO)
 1259             l->u.id.type = ISAKMP_IPSEC_ID_KEY_ID;
 1260         else
 1261             l->u.id.type = ISAKMP_IPSEC_ID_USER_FQDN;
 1262         l->u.id.protocol = IPPROTO_UDP;
 1263         l->u.id.port = ISAKMP_PORT; /* this must be 500, see rfc2407, 4.6.2 */
 1264         l->u.id.length = strlen(key_id);
 1265         l->u.id.data = xallocc(l->u.id.length);
 1266         memcpy(l->u.id.data, key_id, strlen(key_id));
 1267         l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 1268             VID_XAUTH, sizeof(VID_XAUTH));
 1269         l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 1270             VID_UNITY, sizeof(VID_UNITY));
 1271         if ((opt_natt_mode == NATT_NORMAL) || (opt_natt_mode == NATT_FORCE)) {
 1272             l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 1273                 VID_NATT_RFC, sizeof(VID_NATT_RFC));
 1274             l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 1275                 VID_NATT_02N, sizeof(VID_NATT_02N));
 1276             l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 1277                 VID_NATT_02, sizeof(VID_NATT_02));
 1278             l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 1279                 VID_NATT_01, sizeof(VID_NATT_01));
 1280             l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 1281                 VID_NATT_00, sizeof(VID_NATT_00));
 1282         }
 1283         s->ike.dpd_idle = atoi(config[CONFIG_DPD_IDLE]);
 1284         if (s->ike.dpd_idle != 0) {
 1285             if (s->ike.dpd_idle < 10)
 1286                 s->ike.dpd_idle = 10;
 1287             if (s->ike.dpd_idle > 86400)
 1288                 s->ike.dpd_idle = 86400;
 1289             l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 1290                 VID_DPD, sizeof(VID_DPD));
 1291         }
 1292         flatten_isakmp_packet(p1, &pkt, &pkt_len, 0);
 1293 
 1294         /* Now, send that packet and receive a new one.  */
 1295         r_length = sendrecv(s, r_packet, sizeof(r_packet), pkt, pkt_len, 0);
 1296         free(pkt);
 1297     }
 1298     DEBUGTOP(2, printf("S4.4 AM_packet2\n"));
 1299     /* Decode the recieved packet.  */
 1300     {
 1301         int reject;
 1302         struct isakmp_payload *rp;
 1303         struct isakmp_payload *nonce = NULL;
 1304         struct isakmp_payload *ke = NULL;
 1305         struct isakmp_payload *hash = NULL;
 1306         struct isakmp_payload *last_cert = NULL;
 1307         struct isakmp_payload *sig = NULL;
 1308         struct isakmp_payload *idp = NULL;
 1309         int seen_sa = 0, seen_xauth_vid = 0;
 1310         unsigned char *psk_skeyid;
 1311         unsigned char *skeyid;
 1312         gcry_md_hd_t skeyid_ctx;
 1313 
 1314 #ifdef OPENSSL_GPL_VIOLATION
 1315         X509 *current_cert;
 1316         /* structure to store the certificate chain */
 1317         STACK_OF(X509) *cert_stack = sk_X509_new_null();
 1318 #endif /* OPENSSL_GPL_VIOLATION */
 1319 
 1320         reject = 0;
 1321         r = parse_isakmp_packet(r_packet, r_length, &reject);
 1322 
 1323         /* Verify the correctness of the recieved packet.  */
 1324         if (reject == 0 && memcmp(r->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH) != 0)
 1325             reject = ISAKMP_N_INVALID_COOKIE;
 1326         if (reject == 0)
 1327             memcpy(s->ike.r_cookie, r->r_cookie, ISAKMP_COOKIE_LENGTH);
 1328         if (reject == 0 && r->exchange_type != ISAKMP_EXCHANGE_AGGRESSIVE)
 1329             reject = ISAKMP_N_INVALID_EXCHANGE_TYPE;
 1330         if (reject == 0 && r->flags != 0)
 1331             reject = ISAKMP_N_INVALID_FLAGS;
 1332         if (reject == 0 && r->message_id != 0)
 1333             reject = ISAKMP_N_INVALID_MESSAGE_ID;
 1334         if (reject != 0)
 1335             error(1, 0, "response was invalid [1]: %s(%d)", val_to_string(reject, isakmp_notify_enum_array), reject);
 1336         for (rp = r->payload; rp && reject == 0; rp = rp->next)
 1337             switch (rp->type) {
 1338             case ISAKMP_PAYLOAD_SA:
 1339                 if (reject == 0 && rp->u.sa.doi != ISAKMP_DOI_IPSEC)
 1340                     reject = ISAKMP_N_DOI_NOT_SUPPORTED;
 1341                 if (reject == 0 &&
 1342                     rp->u.sa.situation != ISAKMP_IPSEC_SIT_IDENTITY_ONLY)
 1343                     reject = ISAKMP_N_SITUATION_NOT_SUPPORTED;
 1344                 if (reject == 0 &&
 1345                     (rp->u.sa.proposals == NULL
 1346                         || rp->u.sa.proposals->next != NULL))
 1347                     reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1348                 if (reject == 0 &&
 1349                     rp->u.sa.proposals->u.p.prot_id !=
 1350                     ISAKMP_IPSEC_PROTO_ISAKMP)
 1351                     reject = ISAKMP_N_INVALID_PROTOCOL_ID;
 1352                 if (reject == 0 && rp->u.sa.proposals->u.p.spi_size != 0)
 1353                     reject = ISAKMP_N_INVALID_SPI;
 1354                 if (reject == 0 &&
 1355                     (rp->u.sa.proposals->u.p.transforms == NULL
 1356                         || rp->u.sa.proposals->u.p.transforms->next !=
 1357                         NULL))
 1358                     reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1359                 if (reject == 0 &&
 1360                     (rp->u.sa.proposals->u.p.transforms->u.t.id
 1361                         != ISAKMP_IPSEC_KEY_IKE))
 1362                     reject = ISAKMP_N_INVALID_TRANSFORM_ID;
 1363                 if (reject == 0) {
 1364                     struct isakmp_attribute *a
 1365                         =
 1366                         rp->u.sa.proposals->u.p.transforms->u.t.attributes;
 1367                     int seen_enc = 0, seen_hash = 0, seen_auth = 0;
 1368                     int seen_group = 0, seen_keylen = 0;
 1369                     for (; a && reject == 0; a = a->next)
 1370                         switch (a->type) {
 1371                         case IKE_ATTRIB_GROUP_DESC:
 1372                             if (a->af == isakmp_attr_16 &&
 1373                                 a->u.attr_16 ==
 1374                                 get_dh_group_ike()->ike_sa_id)
 1375                                 seen_group = 1;
 1376                             else
 1377                                 reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1378                             break;
 1379                         case IKE_ATTRIB_AUTH_METHOD:
 1380                             if (a->af == isakmp_attr_16)
 1381                                 seen_auth = a->u.attr_16;
 1382                             else
 1383                                 reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1384                             break;
 1385                         case IKE_ATTRIB_HASH:
 1386                             if (a->af == isakmp_attr_16)
 1387                                 seen_hash = a->u.attr_16;
 1388                             else
 1389                                 reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1390                             break;
 1391                         case IKE_ATTRIB_ENC:
 1392                             if (a->af == isakmp_attr_16)
 1393                                 seen_enc = a->u.attr_16;
 1394                             else
 1395                                 reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1396                             break;
 1397                         case IKE_ATTRIB_KEY_LENGTH:
 1398                             if (a->af == isakmp_attr_16)
 1399                                 seen_keylen = a->u.attr_16;
 1400                             else
 1401                                 reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1402                             break;
 1403                         case IKE_ATTRIB_LIFE_TYPE:
 1404                             /* lifetime duration MUST follow lifetype attribute */
 1405                             if (a->next->type == IKE_ATTRIB_LIFE_DURATION) {
 1406                                 lifetime_ike_process(s, a);
 1407                             } else
 1408                                 reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1409                             break;
 1410                         case IKE_ATTRIB_LIFE_DURATION:
 1411                             /* already processed above in IKE_ATTRIB_LIFE_TYPE: */
 1412                             break;
 1413                         default:
 1414                             DEBUG(1, printf
 1415                                 ("unknown attribute %d, arborting..\n",
 1416                                     a->type));
 1417                             reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
 1418                             break;
 1419                         }
 1420                     if (!seen_group || !seen_auth || !seen_hash || !seen_enc)
 1421                         reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 1422 
 1423                     if (get_algo(SUPP_ALGO_AUTH, SUPP_ALGO_IKE_SA, seen_auth,
 1424                             NULL, 0) == NULL)
 1425                         reject = ISAKMP_N_NO_PROPOSAL_CHOSEN;
 1426                     if (get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IKE_SA, seen_hash,
 1427                             NULL, 0) == NULL)
 1428                         reject = ISAKMP_N_NO_PROPOSAL_CHOSEN;
 1429                     if (get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IKE_SA, seen_enc,
 1430                             NULL, seen_keylen) == NULL)
 1431                         reject = ISAKMP_N_NO_PROPOSAL_CHOSEN;
 1432 
 1433                     if (reject == 0) {
 1434                         seen_sa = 1;
 1435                         s->ike.auth_algo = seen_auth;
 1436                         s->ike.cry_algo =
 1437                             get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IKE_SA,
 1438                             seen_enc, NULL, seen_keylen)->my_id;
 1439                         s->ike.md_algo =
 1440                             get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IKE_SA,
 1441                             seen_hash, NULL, 0)->my_id;
 1442                         s->ike.md_len = gcry_md_get_algo_dlen(s->ike.md_algo);
 1443                         DEBUG(1, printf("IKE SA selected %s-%s-%s\n",
 1444                                 get_algo(SUPP_ALGO_AUTH,
 1445                                     SUPP_ALGO_IKE_SA, seen_auth,
 1446                                     NULL, 0)->name,
 1447                                 get_algo(SUPP_ALGO_CRYPT,
 1448                                     SUPP_ALGO_IKE_SA, seen_enc,
 1449                                     NULL, seen_keylen)->name,
 1450                                 get_algo(SUPP_ALGO_HASH,
 1451                                     SUPP_ALGO_IKE_SA, seen_hash,
 1452                                     NULL, 0)->name));
 1453                         if (s->ike.cry_algo == GCRY_CIPHER_DES && !opt_1des) {
 1454                             error(1, 0, "peer selected (single) DES as \"encryption\" method.\n"
 1455                                 "This algorithm is considered too weak today\n"
 1456                                 "If your vpn concentrator admin still insists on using DES\n"
 1457                                 "use the \"--enable-1des\" option.\n");
 1458                         }
 1459                     }
 1460                 }
 1461                 break;
 1462 
 1463             case ISAKMP_PAYLOAD_ID:
 1464                 idp = rp;
 1465                 break;
 1466             case ISAKMP_PAYLOAD_KE:
 1467                 ke = rp;
 1468                 break;
 1469             case ISAKMP_PAYLOAD_NONCE:
 1470                 nonce = rp;
 1471                 break;
 1472             case ISAKMP_PAYLOAD_HASH:
 1473                 hash = rp;
 1474                 break;
 1475             case ISAKMP_PAYLOAD_CERT:
 1476                 last_cert = rp;
 1477                 if (last_cert->u.cert.encoding == ISAKMP_CERT_X509_SIG) {
 1478 #ifdef OPENSSL_GPL_VIOLATION
 1479                     /* convert the certificate to an openssl-X509 structure and push it onto the chain stack */
 1480                     current_cert = d2i_X509(NULL, (const unsigned char **)&last_cert->u.cert.data, last_cert->u.cert.length);
 1481                     sk_X509_push(cert_stack, current_cert);
 1482                     last_cert->u.cert.data -= last_cert->u.cert.length; /* 'rewind' the pointer */
 1483 #endif /* OPENSSL_GPL_VIOLATION */
 1484                 }
 1485                 break;
 1486             case ISAKMP_PAYLOAD_SIG:
 1487                 sig = rp;
 1488                 break;
 1489             case ISAKMP_PAYLOAD_VID:
 1490                 if (rp->u.vid.length == sizeof(VID_XAUTH)
 1491                     && memcmp(rp->u.vid.data, VID_XAUTH,
 1492                         sizeof(VID_XAUTH)) == 0) {
 1493                     seen_xauth_vid = 1;
 1494                 } else if (rp->u.vid.length == sizeof(VID_NATT_RFC)
 1495                     && memcmp(rp->u.vid.data, VID_NATT_RFC,
 1496                         sizeof(VID_NATT_RFC)) == 0) {
 1497                     seen_natt_vid = 1;
 1498                     if (natt_draft < 1) natt_draft = 2;
 1499                     DEBUG(2, printf("peer is NAT-T capable (RFC 3947)\n"));
 1500                 } else if (rp->u.vid.length == sizeof(VID_NATT_02N)
 1501                     && memcmp(rp->u.vid.data, VID_NATT_02N,
 1502                         sizeof(VID_NATT_02N)) == 0) {
 1503                     seen_natt_vid = 1;
 1504                     if (natt_draft < 1) natt_draft = 2;
 1505                     DEBUG(2, printf("peer is NAT-T capable (draft-02)\\n\n")); /* sic! */
 1506                 } else if (rp->u.vid.length == sizeof(VID_NATT_02)
 1507                     && memcmp(rp->u.vid.data, VID_NATT_02,
 1508                         sizeof(VID_NATT_02)) == 0) {
 1509                     seen_natt_vid = 1;
 1510                     if (natt_draft < 1) natt_draft = 2;
 1511                     DEBUG(2, printf("peer is NAT-T capable (draft-02)\n"));
 1512                 } else if (rp->u.vid.length == sizeof(VID_NATT_01)
 1513                     && memcmp(rp->u.vid.data, VID_NATT_01,
 1514                         sizeof(VID_NATT_01)) == 0) {
 1515                     seen_natt_vid = 1;
 1516                     if (natt_draft < 1) natt_draft = 1;
 1517                     DEBUG(2, printf("peer is NAT-T capable (draft-01)\n"));
 1518                 } else if (rp->u.vid.length == sizeof(VID_NATT_00)
 1519                     && memcmp(rp->u.vid.data, VID_NATT_00,
 1520                         sizeof(VID_NATT_00)) == 0) {
 1521                     seen_natt_vid = 1;
 1522                     if (natt_draft < 0) natt_draft = 0;
 1523                     DEBUG(2, printf("peer is NAT-T capable (draft-00)\n"));
 1524                 } else if (rp->u.vid.length == sizeof(VID_DPD)
 1525                     && memcmp(rp->u.vid.data, VID_DPD,
 1526                         sizeof(VID_DPD)) == 0) {
 1527                     if (s->ike.dpd_idle != 0) {
 1528                         gcry_create_nonce(&s->ike.dpd_seqno, sizeof(s->ike.dpd_seqno));
 1529                         s->ike.dpd_seqno &= 0x7FFFFFFF;
 1530                         s->ike.dpd_seqno_ack = s->ike.dpd_seqno;
 1531                         s->ike.do_dpd = 1;
 1532                         DEBUG(2, printf("peer is DPD capable (RFC3706)\n"));
 1533                     } else {
 1534                         DEBUG(2, printf("ignoring that peer is DPD capable (RFC3706)\n"));
 1535                     }
 1536                 } else if (rp->u.vid.length == sizeof(VID_NETSCREEN_15)
 1537                     && memcmp(rp->u.vid.data, VID_NETSCREEN_15,
 1538                         sizeof(VID_NETSCREEN_15)) == 0) {
 1539                     DEBUG(2, printf("peer is using ScreenOS 5.3, 5.4 or 6.0\n"));
 1540                 } else if (rp->u.vid.length == sizeof(VID_HEARTBEAT_NOTIFY)
 1541                     && memcmp(rp->u.vid.data, VID_HEARTBEAT_NOTIFY,
 1542                         sizeof(VID_HEARTBEAT_NOTIFY)) == 0) {
 1543                     DEBUG(2, printf("peer sent Heartbeat Notify payload\n"));
 1544                 } else {
 1545                     hex_dump("unknown ISAKMP_PAYLOAD_VID",
 1546                         rp->u.vid.data, rp->u.vid.length, NULL);
 1547                 }
 1548                 break;
 1549             case ISAKMP_PAYLOAD_NAT_D_OLD:
 1550             case ISAKMP_PAYLOAD_NAT_D:
 1551                 natd_type = rp->type;
 1552                 DEBUG(2, printf("peer is using type %d%s for NAT-Discovery payloads\n",
 1553                     natd_type, val_to_string(natd_type, isakmp_payload_enum_array)));
 1554                 if (!seen_sa /*|| !seen_natt_vid*/) {
 1555                     reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
 1556                 } else if (opt_natt_mode == NATT_NONE) {
 1557                     ;
 1558                 } else if (rp->u.natd.length != s->ike.md_len) {
 1559                     reject = ISAKMP_N_PAYLOAD_MALFORMED;
 1560                 } else if (seen_natd == 0) {
 1561                     gcry_md_hd_t hm;
 1562                     uint16_t n_dst_port = htons(s->ike.dst_port);
 1563                     
 1564                     natd_us = xallocc(s->ike.md_len);
 1565                     natd_them = xallocc(s->ike.md_len);
 1566                     memcpy(natd_us, rp->u.natd.data, s->ike.md_len);
 1567                     gcry_md_open(&hm, s->ike.md_algo, 0);
 1568                     gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1569                     gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 1570                     gcry_md_write(hm, &s->dst, sizeof(struct in_addr));
 1571                     gcry_md_write(hm, &n_dst_port, sizeof(uint16_t));
 1572                     gcry_md_final(hm);
 1573                     memcpy(natd_them, gcry_md_read(hm, 0), s->ike.md_len);
 1574                     gcry_md_close(hm);
 1575                     seen_natd = 1;
 1576                 } else {
 1577                     if (memcmp(natd_them, rp->u.natd.data, s->ike.md_len) == 0)
 1578                         seen_natd_them = 1;
 1579                 }
 1580                 break;
 1581             default:
 1582                 DEBUG(1, printf("rejecting invalid payload type %d\n", rp->type));
 1583                 reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
 1584                 break;
 1585             }
 1586 
 1587         if (reject == 0) {
 1588             gcry_cipher_algo_info(s->ike.cry_algo, GCRYCTL_GET_BLKLEN, NULL, &(s->ike.ivlen));
 1589             gcry_cipher_algo_info(s->ike.cry_algo, GCRYCTL_GET_KEYLEN, NULL, &(s->ike.keylen));
 1590         }
 1591 
 1592         if (reject == 0 && (ke == NULL || ke->u.ke.length != dh_getlen(dh_grp)))
 1593             reject = ISAKMP_N_INVALID_KEY_INFORMATION;
 1594         if (reject == 0 && nonce == NULL)
 1595             reject = ISAKMP_N_INVALID_HASH_INFORMATION;
 1596         if (reject != 0)
 1597             error(1, 0, "response was invalid [2]: %s(%d)", val_to_string(reject, isakmp_notify_enum_array), reject);
 1598         if (reject == 0 && idp == NULL)
 1599             reject = ISAKMP_N_INVALID_ID_INFORMATION;
 1600   
 1601         /* Decide if signature or hash is expected (sig only if vpnc is initiator of hybrid-auth */
 1602         if (reject == 0 && opt_auth_mode == AUTH_MODE_PSK && (hash == NULL || hash->u.hash.length != s->ike.md_len))
 1603             reject = ISAKMP_N_INVALID_HASH_INFORMATION;
 1604         if (reject == 0 && sig == NULL &&
 1605             (opt_auth_mode == AUTH_MODE_CERT ||
 1606              opt_auth_mode == AUTH_MODE_HYBRID))
 1607             reject = ISAKMP_N_INVALID_SIGNATURE;
 1608         if (reject != 0)
 1609             error(1, 0, "response was invalid [3]: %s(%d)", val_to_string(reject, isakmp_notify_enum_array), reject);
 1610 
 1611         /* Determine the shared secret.  */
 1612         dh_shared_secret = xallocc(dh_getlen(dh_grp));
 1613         dh_create_shared(dh_grp, dh_shared_secret, ke->u.ke.data);
 1614         hex_dump("dh_shared_secret", dh_shared_secret, dh_getlen(dh_grp), NULL);
 1615         /* Generate SKEYID.  */
 1616         {
 1617             gcry_md_open(&skeyid_ctx, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1618             gcry_md_setkey(skeyid_ctx, shared_key, strlen(shared_key));
 1619             gcry_md_write(skeyid_ctx, i_nonce, sizeof(i_nonce));
 1620             gcry_md_write(skeyid_ctx, nonce->u.nonce.data, nonce->u.nonce.length);
 1621             gcry_md_final(skeyid_ctx);
 1622             psk_skeyid = xallocc(s->ike.md_len);
 1623             memcpy(psk_skeyid, gcry_md_read(skeyid_ctx, 0), s->ike.md_len);
 1624             if (opt_debug < 99)
 1625                 DEBUG(3, printf("(not dumping psk hash)\n"));
 1626             else
 1627                 hex_dump("psk_skeyid", psk_skeyid, s->ike.md_len, NULL);
 1628             free(psk_skeyid);
 1629             gcry_md_close(skeyid_ctx);
 1630             DEBUG(99, printf("shared-key: %s\n",shared_key));
 1631             
 1632             /* SKEYID - psk only */
 1633             if (s->ike.auth_algo == IKE_AUTH_PRESHARED ||
 1634                 s->ike.auth_algo == IKE_AUTH_XAUTHInitPreShared ||
 1635                 s->ike.auth_algo == IKE_AUTH_XAUTHRespPreShared) {
 1636                 gcry_md_open(&skeyid_ctx, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1637                 gcry_md_setkey(skeyid_ctx, shared_key, strlen(shared_key));
 1638                 gcry_md_write(skeyid_ctx, i_nonce, sizeof(i_nonce));
 1639                 gcry_md_write(skeyid_ctx, nonce->u.nonce.data, nonce->u.nonce.length);
 1640                 gcry_md_final(skeyid_ctx);
 1641             } else if (s->ike.auth_algo == IKE_AUTH_DSS ||
 1642                 s->ike.auth_algo == IKE_AUTH_RSA_SIG ||
 1643                 s->ike.auth_algo == IKE_AUTH_ECDSA_SIG ||
 1644                 s->ike.auth_algo == IKE_AUTH_HybridInitRSA ||
 1645                 s->ike.auth_algo == IKE_AUTH_HybridRespRSA || 
 1646                 s->ike.auth_algo == IKE_AUTH_HybridInitDSS ||
 1647                 s->ike.auth_algo == IKE_AUTH_HybridRespDSS ||
 1648                 s->ike.auth_algo == IKE_AUTH_XAUTHInitDSS ||
 1649                 s->ike.auth_algo == IKE_AUTH_XAUTHRespDSS ||
 1650                 s->ike.auth_algo == IKE_AUTH_XAUTHInitRSA ||
 1651                 s->ike.auth_algo == IKE_AUTH_XAUTHRespRSA) {
 1652                 unsigned char *key;
 1653                 int key_len;
 1654                 key_len = sizeof(i_nonce) + nonce->u.nonce.length;
 1655                 key = xallocc(key_len);
 1656                 memcpy(key, i_nonce, sizeof(i_nonce));
 1657                 memcpy(key + sizeof(i_nonce), nonce->u.nonce.data, nonce->u.nonce.length);
 1658                 gcry_md_open(&skeyid_ctx, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1659                 gcry_md_setkey(skeyid_ctx, key, key_len);
 1660                 gcry_md_write(skeyid_ctx, dh_shared_secret, dh_getlen(dh_grp));
 1661                 gcry_md_final(skeyid_ctx);
 1662             } else
 1663                 error(1, 0, "SKEYID could not be computed: %s", "the selected authentication method is not supported");
 1664             skeyid = gcry_md_read(skeyid_ctx, 0);
 1665             hex_dump("skeyid", skeyid, s->ike.md_len, NULL);
 1666         }
 1667 
 1668         /* Verify the hash.  */
 1669         {
 1670             gcry_md_hd_t hm;
 1671             unsigned char *expected_hash;
 1672             uint8_t *sa_f, *idi_f, *idp_f;
 1673             size_t sa_size, idi_size, idp_size;
 1674             struct isakmp_payload *sa, *idi;
 1675 
 1676             sa = p1->payload;
 1677             for (idi = sa; idi->type != ISAKMP_PAYLOAD_ID; idi = idi->next) ;
 1678             flatten_isakmp_payload(sa, &sa_f, &sa_size);
 1679             flatten_isakmp_payload(idi, &idi_f, &idi_size);
 1680             flatten_isakmp_payload(idp, &idp_f, &idp_size);
 1681 
 1682             gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1683             gcry_md_setkey(hm, skeyid, s->ike.md_len);
 1684             gcry_md_write(hm, ke->u.ke.data, ke->u.ke.length);
 1685             gcry_md_write(hm, dh_public, dh_getlen(dh_grp));
 1686             gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 1687             gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1688             gcry_md_write(hm, sa_f + 4, sa_size - 4);
 1689             gcry_md_write(hm, idp_f + 4, idp_size - 4);
 1690             gcry_md_final(hm);
 1691             expected_hash = gcry_md_read(hm, 0);
 1692             hex_dump("expected hash", expected_hash, s->ike.md_len, NULL);
 1693 
 1694             if (opt_auth_mode == AUTH_MODE_PSK) {
 1695                 if (memcmp(expected_hash, hash->u.hash.data, s->ike.md_len) != 0)
 1696                     error(2, 0, "hash comparison failed: %s(%d)\ncheck group password!",
 1697                         val_to_string(ISAKMP_N_AUTHENTICATION_FAILED, isakmp_notify_enum_array),
 1698                         ISAKMP_N_AUTHENTICATION_FAILED);
 1699                 hex_dump("received hash", hash->u.hash.data, hash->u.hash.length, NULL);
 1700             } else if (opt_auth_mode == AUTH_MODE_CERT ||
 1701                 opt_auth_mode == AUTH_MODE_HYBRID) {
 1702 #ifdef OPENSSL_GPL_VIOLATION
 1703                 
 1704                 /* BEGIN - check the signature using OpenSSL */
 1705             
 1706                 X509        *x509;
 1707                 EVP_PKEY    *pkey;
 1708                 RSA         *rsa;
 1709                 X509_STORE  *store;
 1710                 /* X509_LOOKUP  *lookup; */
 1711                 X509_STORE_CTX  *verify_ctx;
 1712                 unsigned char   *rec_hash;
 1713                 int     decr_size;
 1714     
 1715                 hex_dump("received signature", sig->u.sig.data, sig->u.sig.length, NULL);
 1716                 OpenSSL_add_all_ciphers();
 1717                 OpenSSL_add_all_digests();
 1718                 OpenSSL_add_all_algorithms();
 1719     
 1720                 ERR_load_crypto_strings();
 1721     
 1722                 hex_dump("last cert", last_cert->u.cert.data, last_cert->u.cert.length, NULL);
 1723                 x509 = d2i_X509(NULL, (const unsigned char **)&last_cert->u.cert.data, last_cert->u.cert.length);
 1724                 if (x509 == NULL) {
 1725                     ERR_print_errors_fp (stderr);
 1726                     error(1, 0, "x509 error\n");
 1727                 }
 1728                 DEBUG(3, printf("Subject name hash: %08lx\n",X509_subject_name_hash(x509)));
 1729     
 1730                 /* BEGIN - verify certificate chain */
 1731                 /* create the cert store */
 1732                 if (!(store = X509_STORE_new())) {
 1733                     error(1, 0, "Error creating X509_STORE object\n");
 1734                 }
 1735                 /* load the CA certificates */
 1736                 if (X509_STORE_load_locations (store, config[CONFIG_CA_FILE], config[CONFIG_CA_DIR]) != 1) {
 1737                     error(1, 0, "Error loading the CA file or directory\n");
 1738                 }
 1739                 if (X509_STORE_set_default_paths (store) != 1) {
 1740                     error(1, 0, "Error loading the system-wide CA certificates\n");
 1741                 }
 1742 
 1743 #if 0
 1744                 /* check CRLs */
 1745                 /* add the corresponding CRL for each CA in the chain to the lookup */
 1746 #define CRL_FILE "root-ca-crl.crl.pem"
 1747 
 1748                 if (!(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()))) {
 1749                     error(1, 0, "Error creating X509 lookup object.\n");
 1750                 }
 1751                 if (X509_load_crl_file(lookup, CRL_FILE, X509_FILETYPE_PEM) != 1) {
 1752                     ERR_print_errors_fp(stderr);
 1753                     error(1, 0, "Error reading CRL file\n");
 1754                 }
 1755                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
 1756 #endif /* 0 */
 1757                 /* create a verification context and initialize it */
 1758                 if (!(verify_ctx = X509_STORE_CTX_new ())) {
 1759                     error(1, 0, "Error creating X509_STORE_CTX object\n");
 1760                 }
 1761                 /* X509_STORE_CTX_init did not return an error condition
 1762                 in prior versions */
 1763                 if (X509_STORE_CTX_init (verify_ctx, store, x509, cert_stack) != 1)
 1764                     printf("Error intializing verification context\n");
 1765     
 1766                 /* verify the certificate */
 1767                 if (X509_verify_cert(verify_ctx) != 1) {
 1768                     ERR_print_errors_fp(stderr);
 1769                     error(2, 0, "Error verifying the certificate-chain\n");
 1770                 } else
 1771                     DEBUG(3, printf("Certificate-chain verified correctly!\n"));
 1772     
 1773                 /* END   - verify certificate chain */
 1774     
 1775     
 1776                 /* BEGIN - Signature Verification */
 1777                 pkey = X509_get_pubkey(x509);
 1778                 if (pkey == NULL) {
 1779                     ERR_print_errors_fp (stderr);
 1780                     exit (1);
 1781                 }
 1782     
 1783                 rsa = EVP_PKEY_get1_RSA(pkey);
 1784                 if (rsa == NULL) {
 1785                     ERR_print_errors_fp (stderr);
 1786                     exit (1);
 1787                 }
 1788                 rec_hash = xallocc(s->ike.md_len);
 1789                 decr_size = RSA_public_decrypt(sig->u.sig.length, sig->u.sig.data, rec_hash, rsa, RSA_PKCS1_PADDING);
 1790     
 1791                 if (decr_size != (int) s->ike.md_len) {
 1792                     printf("Decrypted-Size: %d\n",decr_size);
 1793                     hex_dump("    decr_hash", rec_hash, decr_size, NULL);
 1794                     hex_dump("expected hash", expected_hash, s->ike.md_len, NULL);
 1795                 
 1796                     error(2, 0, "The hash-value, which was decrypted from the received signature, and the expected hash-value differ in size.\n");
 1797                 } else {
 1798                     if (memcmp(rec_hash, expected_hash, decr_size) != 0) {
 1799                         printf("Decrypted-Size: %d\n",decr_size);
 1800                         hex_dump("    decr_hash", rec_hash, decr_size, NULL);
 1801                         hex_dump("expected hash", expected_hash, s->ike.md_len, NULL);
 1802     
 1803                         error(2, 0, "The hash-value, which was decrypted from the received signature, and the expected hash-value differ.\n");
 1804                     } else {
 1805                         DEBUG(3, printf("Signature MATCH!!\n"));
 1806                     }
 1807                 }
 1808                 /* END - Signature Verification */
 1809     
 1810                 EVP_PKEY_free(pkey);
 1811                 free(rec_hash);
 1812     
 1813                 /* END   - check the signature using OpenSSL */
 1814 #endif /* OPENSSL_GPL_VIOLATION */
 1815             }
 1816 
 1817             gcry_md_close(hm);
 1818 
 1819             gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1820             gcry_md_setkey(hm, skeyid, s->ike.md_len);
 1821             gcry_md_write(hm, dh_public, dh_getlen(dh_grp));
 1822             gcry_md_write(hm, ke->u.ke.data, ke->u.ke.length);
 1823             gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1824             gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 1825             gcry_md_write(hm, sa_f + 4, sa_size - 4);
 1826             gcry_md_write(hm, idi_f + 4, idi_size - 4);
 1827             gcry_md_final(hm);
 1828             returned_hash = xallocc(s->ike.md_len);
 1829             memcpy(returned_hash, gcry_md_read(hm, 0), s->ike.md_len);
 1830             gcry_md_close(hm);
 1831             hex_dump("returned_hash", returned_hash, s->ike.md_len, NULL);
 1832 
 1833             /* PRESHARED_KEY_HASH */
 1834             gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1835             gcry_md_setkey(hm, skeyid, s->ike.md_len);
 1836             gcry_md_write(hm, shared_key, strlen(shared_key));
 1837             gcry_md_final(hm);
 1838             psk_hash = xallocc(s->ike.md_len);
 1839             memcpy(psk_hash, gcry_md_read(hm, 0), s->ike.md_len);
 1840             gcry_md_close(hm);
 1841             hex_dump("psk_hash", psk_hash, s->ike.md_len, NULL);
 1842             /* End PRESHARED_KEY_HASH */
 1843 
 1844             free(sa_f);
 1845             free(idi_f);
 1846             free(idp_f);
 1847         }
 1848 
 1849         /* Determine all the SKEYID_x keys.  */
 1850         {
 1851             gcry_md_hd_t hm;
 1852             int i;
 1853             static const unsigned char c012[3] = { 0, 1, 2 };
 1854             unsigned char *skeyid_e;
 1855             unsigned char *dh_shared_secret;
 1856 
 1857             /* Determine the shared secret.  */
 1858             dh_shared_secret = xallocc(dh_getlen(dh_grp));
 1859             dh_create_shared(dh_grp, dh_shared_secret, ke->u.ke.data);
 1860             hex_dump("dh_shared_secret", dh_shared_secret, dh_getlen(dh_grp), NULL);
 1861 
 1862             gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1863             gcry_md_setkey(hm, skeyid, s->ike.md_len);
 1864             gcry_md_write(hm, dh_shared_secret, dh_getlen(dh_grp));
 1865             gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1866             gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 1867             gcry_md_write(hm, c012 + 0, 1);
 1868             gcry_md_final(hm);
 1869             if (s->ike.skeyid_d) free(s->ike.skeyid_d);
 1870             s->ike.skeyid_d = xallocc(s->ike.md_len);
 1871             memcpy(s->ike.skeyid_d, gcry_md_read(hm, 0), s->ike.md_len);
 1872             gcry_md_close(hm);
 1873             hex_dump("skeyid_d", s->ike.skeyid_d, s->ike.md_len, NULL);
 1874 
 1875             gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1876             gcry_md_setkey(hm, skeyid, s->ike.md_len);
 1877             gcry_md_write(hm, s->ike.skeyid_d, s->ike.md_len);
 1878             gcry_md_write(hm, dh_shared_secret, dh_getlen(dh_grp));
 1879             gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1880             gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 1881             gcry_md_write(hm, c012 + 1, 1);
 1882             gcry_md_final(hm);
 1883             if (s->ike.skeyid_a) free(s->ike.skeyid_a);
 1884             s->ike.skeyid_a = xallocc(s->ike.md_len);
 1885             memcpy(s->ike.skeyid_a, gcry_md_read(hm, 0), s->ike.md_len);
 1886             gcry_md_close(hm);
 1887             hex_dump("skeyid_a", s->ike.skeyid_a, s->ike.md_len, NULL);
 1888 
 1889             gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1890             gcry_md_setkey(hm, skeyid, s->ike.md_len);
 1891             gcry_md_write(hm, s->ike.skeyid_a, s->ike.md_len);
 1892             gcry_md_write(hm, dh_shared_secret, dh_getlen(dh_grp));
 1893             gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1894             gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 1895             gcry_md_write(hm, c012 + 2, 1);
 1896             gcry_md_final(hm);
 1897             skeyid_e = xallocc(s->ike.md_len);
 1898             memcpy(skeyid_e, gcry_md_read(hm, 0), s->ike.md_len);
 1899             gcry_md_close(hm);
 1900             hex_dump("skeyid_e", skeyid_e, s->ike.md_len, NULL);
 1901 
 1902             memset(dh_shared_secret, 0, sizeof(dh_shared_secret));
 1903             free(dh_shared_secret);
 1904 
 1905             /* Determine the IKE encryption key.  */
 1906             if (s->ike.key) free(s->ike.key);
 1907             s->ike.key = xallocc(s->ike.keylen);
 1908 
 1909             if (s->ike.keylen > s->ike.md_len) {
 1910                 for (i = 0; i * s->ike.md_len < s->ike.keylen; i++) {
 1911                     gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
 1912                     gcry_md_setkey(hm, skeyid_e, s->ike.md_len);
 1913                     if (i == 0)
 1914                         gcry_md_write(hm, "" /* &'\0' */ , 1);
 1915                     else
 1916                         gcry_md_write(hm, s->ike.key + (i - 1) * s->ike.md_len,
 1917                             s->ike.md_len);
 1918                     gcry_md_final(hm);
 1919                     memcpy(s->ike.key + i * s->ike.md_len, gcry_md_read(hm, 0),
 1920                         min(s->ike.md_len, s->ike.keylen - i * s->ike.md_len));
 1921                     gcry_md_close(hm);
 1922                 }
 1923             } else { /* keylen <= md_len */
 1924                 memcpy(s->ike.key, skeyid_e, s->ike.keylen);
 1925             }
 1926             hex_dump("enc-key", s->ike.key, s->ike.keylen, NULL);
 1927 
 1928             memset(skeyid_e, 0, s->ike.md_len);
 1929             free(skeyid_e);
 1930         }
 1931 
 1932         /* Determine the initial IV.  */
 1933         {
 1934             gcry_md_hd_t hm;
 1935 
 1936             assert(s->ike.ivlen <= s->ike.md_len);
 1937             gcry_md_open(&hm, s->ike.md_algo, 0);
 1938             gcry_md_write(hm, dh_public, dh_getlen(dh_grp));
 1939             gcry_md_write(hm, ke->u.ke.data, ke->u.ke.length);
 1940             gcry_md_final(hm);
 1941             if (s->ike.current_iv) free(s->ike.current_iv);
 1942             s->ike.current_iv = xallocc(s->ike.ivlen);
 1943             memcpy(s->ike.current_iv, gcry_md_read(hm, 0), s->ike.ivlen);
 1944             gcry_md_close(hm);
 1945             hex_dump("current_iv", s->ike.current_iv, s->ike.ivlen, NULL);
 1946             memset(s->ike.current_iv_msgid, 0, 4);
 1947         }
 1948 
 1949         gcry_md_close(skeyid_ctx);
 1950     }
 1951 
 1952     DEBUGTOP(2, printf("S4.5 AM_packet3\n"));
 1953     /* Send final phase 1 packet.  */
 1954     {
 1955         struct isakmp_packet *p2;
 1956         uint8_t *p2kt;
 1957         size_t p2kt_len;
 1958         struct isakmp_payload *pl;
 1959 #if 0 /* cert support */
 1960 #ifdef OPENSSL_GPL_VIOLATION
 1961         struct isakmp_payload *last_cert = NULL;
 1962         struct isakmp_payload *sig = NULL;
 1963 
 1964 
 1965         X509 *current_cert;
 1966         /* structure to store the certificate chain */
 1967         STACK_OF(X509) *cert_stack = sk_X509_new_null();
 1968 #endif /* OPENSSL_GPL_VIOLATION */
 1969 #endif /* 0 */
 1970 
 1971         p2 = new_isakmp_packet();
 1972         memcpy(p2->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1973         memcpy(p2->r_cookie, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 1974         p2->flags = ISAKMP_FLAG_E;
 1975         p2->isakmp_version = ISAKMP_VERSION;
 1976         p2->exchange_type = ISAKMP_EXCHANGE_AGGRESSIVE;
 1977     /* XXX CERT Add id(?), cert and sig here in case of cert auth */
 1978         p2->payload = new_isakmp_data_payload(ISAKMP_PAYLOAD_HASH,
 1979             returned_hash, s->ike.md_len);
 1980         p2->payload->next = pl = new_isakmp_payload(ISAKMP_PAYLOAD_N);
 1981         pl->u.n.doi = ISAKMP_DOI_IPSEC;
 1982         pl->u.n.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
 1983         pl->u.n.type = ISAKMP_N_IPSEC_INITIAL_CONTACT;
 1984         pl->u.n.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
 1985         pl->u.n.spi = xallocc(2 * ISAKMP_COOKIE_LENGTH);
 1986         memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 0, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 1987         memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 1, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 1988 
 1989         /* send PSK-hash if hybrid authentication is negotiated */
 1990         if (s->ike.auth_algo == IKE_AUTH_HybridInitRSA ||
 1991             s->ike.auth_algo == IKE_AUTH_HybridInitDSS) {
 1992             /* Notify - PRESHARED_KEY_HASH */
 1993             pl = pl->next = new_isakmp_payload(ISAKMP_PAYLOAD_N);
 1994             pl->u.n.doi = ISAKMP_DOI_IPSEC;
 1995             pl->u.n.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
 1996             /* Notify Message - Type: PRESHARED_KEY_HASH */
 1997             pl->u.n.type =  ISAKMP_N_CISCO_PRESHARED_KEY_HASH;
 1998             pl->u.n.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
 1999             pl->u.n.spi = xallocc(2 * ISAKMP_COOKIE_LENGTH);
 2000             memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 0,
 2001                 s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 2002             memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 1,
 2003                 s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 2004             pl->u.n.data_length = s->ike.md_len;
 2005             pl->u.n.data = xallocc(pl->u.n.data_length);
 2006             memcpy(pl->u.n.data, psk_hash, pl->u.n.data_length);
 2007             /* End Notify - PRESHARED_KEY_HASH */
 2008         }
 2009         pl = pl->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 2010             VID_UNKNOWN, sizeof(VID_UNKNOWN));
 2011         pl = pl->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
 2012             VID_UNITY, sizeof(VID_UNITY));
 2013 
 2014         /* include NAT traversal discovery payloads */
 2015         if (seen_natt_vid) {
 2016             assert(natd_type != 0);
 2017             pl = pl->next = new_isakmp_data_payload(natd_type,
 2018                 natd_them, s->ike.md_len);
 2019             /* this could be repeated fo any known outbound interfaces */
 2020             {
 2021                 gcry_md_hd_t hm;
 2022                 uint16_t n_src_port = htons(s->ike.src_port);
 2023                 
 2024                 gcry_md_open(&hm, s->ike.md_algo, 0);
 2025                 gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
 2026                 gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
 2027                 gcry_md_write(hm, &s->src, sizeof(struct in_addr));
 2028                 gcry_md_write(hm, &n_src_port, sizeof(uint16_t));
 2029                 gcry_md_final(hm);
 2030                 pl = pl->next = new_isakmp_data_payload(natd_type,
 2031                     gcry_md_read(hm, 0), s->ike.md_len);
 2032                 if (opt_natt_mode == NATT_FORCE) /* force detection of "this end behind NAT" */
 2033                     pl->u.ke.data[0] ^= 1; /* by flipping a bit in the nat-detection-hash */
 2034                 if (seen_natd && memcmp(natd_us, pl->u.ke.data, s->ike.md_len) == 0)
 2035                     seen_natd_us = 1;
 2036                 gcry_md_close(hm);
 2037             }
 2038             if (seen_natd) {
 2039                 free(natd_us);
 2040                 free(natd_them);
 2041             }
 2042             /* if there is a NAT, change to port 4500 and select UDP encap */
 2043             if (!seen_natd_us || !seen_natd_them) {
 2044                 DEBUG(1, printf("NAT status: this end behind NAT? %s -- remote end behind NAT? %s\n",
 2045                     seen_natd_us ? "no" : "YES", seen_natd_them ? "no" : "YES"));
 2046                 switch (natd_type) {
 2047                     case ISAKMP_PAYLOAD_NAT_D:
 2048                         s->ipsec.encap_mode = IPSEC_ENCAP_UDP_TUNNEL;
 2049                         break;
 2050                     case ISAKMP_PAYLOAD_NAT_D_OLD:
 2051                         s->ipsec.encap_mode = IPSEC_ENCAP_UDP_TUNNEL_OLD;
 2052                         break;
 2053                     default:
 2054                         abort();
 2055                 }
 2056                 if (natt_draft >= 2) {
 2057                     s->ipsec.natt_active_mode = NATT_ACTIVE_RFC;
 2058                     close(s->ike_fd);
 2059                     if (s->ike.src_port == ISAKMP_PORT)
 2060                         s->ike.src_port = ISAKMP_PORT_NATT;
 2061                     s->ike_fd = make_socket(s, s->ike.src_port, s->ike.dst_port = ISAKMP_PORT_NATT);
 2062                 } else {
 2063                     s->ipsec.natt_active_mode = NATT_ACTIVE_DRAFT_OLD;
 2064                 }
 2065             } else {
 2066                 DEBUG(1, printf("NAT status: NAT-T VID seen, no NAT device detected\n"));
 2067             }
 2068         } else {
 2069             DEBUG(1, printf("NAT status: no NAT-T VID seen\n"));
 2070         }
 2071 
 2072         
 2073         flatten_isakmp_packet(p2, &p2kt, &p2kt_len, s->ike.ivlen);
 2074         free_isakmp_packet(p2);
 2075         isakmp_crypt(s, p2kt, p2kt_len, 1);
 2076 
 2077         if (s->ike.initial_iv) free(s->ike.initial_iv);
 2078         s->ike.initial_iv = xallocc(s->ike.ivlen);
 2079         memcpy(s->ike.initial_iv, s->ike.current_iv, s->ike.ivlen);
 2080         hex_dump("initial_iv", s->ike.initial_iv, s->ike.ivlen, NULL);
 2081 
 2082         /* Now, send that packet and receive a new one.  */
 2083         r_length = sendrecv(s, r_packet, sizeof(r_packet), p2kt, p2kt_len, 0);
 2084         free(p2kt);
 2085     }
 2086     DEBUGTOP(2, printf("S4.6 cleanup\n"));
 2087 
 2088     free_isakmp_packet(p1);
 2089     /* This seems to cause a duplicate free of some data:
 2090      * *** glibc detected *** vpnc-connect: free(): invalid pointer: 0x09d63ba5
 2091      * See also: http://bugs.gentoo.org/show_bug.cgi?id=229003
 2092      */
 2093 #if 0
 2094     free_isakmp_packet(r);
 2095 #endif
 2096     free(returned_hash);
 2097     free(dh_public);
 2098     free(dh_shared_secret);
 2099     free(psk_hash);
 2100     group_free(dh_grp);
 2101 }
 2102 
 2103 static int do_phase2_notice_check(struct sa_block *s, struct isakmp_packet **r_p)
 2104 {
 2105     int reject = 0;
 2106     struct isakmp_packet *r;
 2107     
 2108     while (1) {
 2109         reject = unpack_verify_phase2(s, r_packet, r_length, r_p, NULL, 0);
 2110         if (reject == ISAKMP_N_INVALID_COOKIE) {
 2111             r_length = sendrecv(s, r_packet, sizeof(r_packet), NULL, 0, 0);
 2112             continue;
 2113         }
 2114         if (*r_p == NULL) {
 2115             assert(reject != 0);
 2116             return reject;
 2117         }
 2118         r = *r_p;
 2119         
 2120         /* check for notices */
 2121         if (r->exchange_type == ISAKMP_EXCHANGE_INFORMATIONAL &&
 2122             r->payload->next != NULL) {
 2123             if (r->payload->next->type == ISAKMP_PAYLOAD_N) {
 2124                 if (r->payload->next->u.n.type == ISAKMP_N_CISCO_LOAD_BALANCE) {
 2125                     /* load balancing notice ==> restart with new gw */
 2126                     if (r->payload->next->u.n.data_length != 4)
 2127                         error(1, 0, "malformed loadbalance target");
 2128                     s->dst = *(struct in_addr *)r->payload->next->u.n.data;
 2129                     s->ike.dst_port = ISAKMP_PORT;
 2130                     s->ipsec.encap_mode = IPSEC_ENCAP_TUNNEL;
 2131                     s->ipsec.natt_active_mode = NATT_ACTIVE_NONE;
 2132                     if (s->ike.src_port == ISAKMP_PORT_NATT)
 2133                         s->ike.src_port = ISAKMP_PORT;
 2134                     close(s->ike_fd);
 2135                     s->ike_fd = make_socket(s, s->ike.src_port, s->ike.dst_port);
 2136                     DEBUG(2, printf("got cisco loadbalancing notice, diverting to %s\n",
 2137                             inet_ntoa(s->dst)));
 2138                     return -1;
 2139                 } else if (r->payload->next->u.n.type == ISAKMP_N_IPSEC_RESPONDER_LIFETIME) {
 2140                     if (r->payload->next->u.n.protocol == ISAKMP_IPSEC_PROTO_ISAKMP)
 2141                         lifetime_ike_process(s, r->payload->next->u.n.attributes);
 2142                     else if (r->payload->next->u.n.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP)
 2143                         lifetime_ipsec_process(s, r->payload->next->u.n.attributes);
 2144                     else
 2145                         DEBUG(2, printf("got unknown lifetime notice, ignoring..\n"));
 2146                     r_length = sendrecv(s, r_packet, sizeof(r_packet), NULL, 0, 0);
 2147                     continue;
 2148                 } else if (r->payload->next->u.n.type == ISAKMP_N_IPSEC_INITIAL_CONTACT) {
 2149                     /* why in hell do we get this?? */
 2150                     DEBUG(2, printf("got initial contact notice, ignoring..\n"));
 2151                     r_length = sendrecv(s, r_packet, sizeof(r_packet), NULL, 0, 0);
 2152                     continue;
 2153                 } else {
 2154                     /* whatever */
 2155                     printf("received notice of type %s(%d), giving up\n",
 2156                         val_to_string(r->payload->next->u.n.type, isakmp_notify_enum_array),
 2157                         r->payload->next->u.n.type);
 2158                     return reject;
 2159                 }
 2160             }
 2161             if (r->payload->next->type == ISAKMP_PAYLOAD_D) {
 2162                 /* delete notice ==> ignore */
 2163                 DEBUG(2, printf("got delete for old connection, ignoring..\n"));
 2164                 r_length = sendrecv(s, r_packet, sizeof(r_packet), NULL, 0, 0);
 2165                 continue;
 2166             }
 2167         }
 2168         
 2169         break;
 2170     }
 2171     return reject;
 2172 }
 2173 
 2174 static int do_phase2_xauth(struct sa_block *s)
 2175 {
 2176     struct isakmp_packet *r = NULL;
 2177     int loopcount;
 2178     int reject;
 2179     int passwd_used = 0;
 2180 
 2181     DEBUGTOP(2, printf("S5.1 xauth_start\n"));
 2182     /* This can go around for a while.  */
 2183     for (loopcount = 0;; loopcount++) {
 2184         struct isakmp_payload *rp;
 2185         struct isakmp_attribute *a, *ap, *reply_attr;
 2186         char ntop_buf[32];
 2187         int seen_answer = 0;
 2188 
 2189         DEBUGTOP(2, printf("S5.2 notice_check\n"));
 2190         
 2191         /* recv and check for notices */
 2192         if (r) free_isakmp_packet(r);
 2193         r = NULL;
 2194         reject = do_phase2_notice_check(s, &r);
 2195         if (reject == -1) {
 2196             if (r) free_isakmp_packet(r);
 2197             return 1;
 2198         }
 2199         
 2200         DEBUGTOP(2, printf("S5.3 type-is-xauth check\n"));
 2201         /* Check the transaction type is OK.  */
 2202         if (reject == 0 && r->exchange_type != ISAKMP_EXCHANGE_MODECFG_TRANSACTION)
 2203             reject = ISAKMP_N_INVALID_EXCHANGE_TYPE;
 2204 
 2205         /* After the hash, expect an attribute block.  */
 2206         if (reject == 0
 2207             && (r->payload->next == NULL
 2208                 || r->payload->next->next != NULL
 2209                 || r->payload->next->type != ISAKMP_PAYLOAD_MODECFG_ATTR))
 2210             reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
 2211 
 2212         if (reject == 0 && r->payload->next->u.modecfg.type == ISAKMP_MODECFG_CFG_SET)
 2213             break;
 2214         if (reject == 0 && r->payload->next->u.modecfg.type != ISAKMP_MODECFG_CFG_REQUEST)
 2215             reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
 2216 
 2217         if (reject != 0)
 2218             phase2_fatal(s, "expected xauth packet; rejected: %s(%d)", reject);
 2219 
 2220         DEBUGTOP(2, printf("S5.4 xauth type check\n"));
 2221         a = r->payload->next->u.modecfg.attributes;
 2222         /* First, print any messages, and verify that we understand the
 2223          * conversation. This looks for any place were input is
 2224          * required - in these cases, we need to print the prompt
 2225          * regardless of whether the user requested interactive mode
 2226          * or not. */
 2227         for (ap = a; ap && seen_answer == 0; ap = ap->next)
 2228             if (ap->type == ISAKMP_XAUTH_06_ATTRIB_ANSWER
 2229                 || ap->type == ISAKMP_XAUTH_06_ATTRIB_NEXT_PIN
 2230                 /* || ap->type == ISAKMP_XAUTH_06_ATTRIB_PASSCODE */)
 2231                 seen_answer = 1;
 2232 
 2233         for (ap = a; ap && reject == 0; ap = ap->next)
 2234             switch (ap->type) {
 2235             case ISAKMP_XAUTH_06_ATTRIB_TYPE:
 2236                 if (ap->af != isakmp_attr_16 || ap->u.attr_16 != 0)
 2237                     reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
 2238                 break;
 2239             case ISAKMP_XAUTH_06_ATTRIB_USER_NAME:
 2240             case ISAKMP_XAUTH_06_ATTRIB_USER_PASSWORD:
 2241             case ISAKMP_XAUTH_06_ATTRIB_PASSCODE:
 2242             case ISAKMP_XAUTH_06_ATTRIB_DOMAIN:
 2243             case ISAKMP_XAUTH_06_ATTRIB_ANSWER:
 2244             case ISAKMP_XAUTH_06_ATTRIB_NEXT_PIN:
 2245             case ISAKMP_XAUTH_ATTRIB_CISCOEXT_VENDOR:
 2246                 break;
 2247             case ISAKMP_XAUTH_06_ATTRIB_MESSAGE:
 2248                 if (opt_debug || seen_answer || config[CONFIG_XAUTH_INTERACTIVE]) {
 2249                     if (ap->af == isakmp_attr_16)
 2250                         printf("%c%c\n", ap->u.attr_16 >> 8, ap->u.attr_16);
 2251                     else
 2252                         printf("%.*s%s", ap->u.lots.length, ap->u.lots.data,
 2253                             ((ap->u.lots.data
 2254                                     && ap->u.lots.data[ap->u.
 2255                                         lots.length - 1] !=
 2256                                     '\n')
 2257                                 ? "\n" : ""));
 2258                 }
 2259                 break;
 2260             default:
 2261                 reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
 2262             }
 2263         if (reject != 0)
 2264             phase2_fatal(s, "xauth packet unsupported: %s(%d)", reject);
 2265 
 2266         DEBUGTOP(2, printf("S5.5 do xauth authentication\n"));
 2267         inet_ntop(AF_INET, &s->dst, ntop_buf, sizeof(ntop_buf));
 2268 
 2269         /* Collect data from the user.  */
 2270         reply_attr = NULL;
 2271         for (ap = a; ap && reject == 0; ap = ap->next)
 2272             switch (ap->type) {
 2273             case ISAKMP_XAUTH_06_ATTRIB_DOMAIN:
 2274                 {
 2275                     struct isakmp_attribute *na;
 2276                     na = new_isakmp_attribute(ap->type, reply_attr);
 2277                     reply_attr = na;
 2278                     if (!config[CONFIG_DOMAIN])
 2279                         error(1, 0,
 2280                             "server requested domain, but none set (use \"Domain ...\" in config or --domain");
 2281                     na->u.lots.length = strlen(config[CONFIG_DOMAIN]);
 2282                     na->u.lots.data = xallocc(na->u.lots.length);
 2283                     memcpy(na->u.lots.data, config[CONFIG_DOMAIN],
 2284                         na->u.lots.length);
 2285                     break;
 2286                 }
 2287             case ISAKMP_XAUTH_06_ATTRIB_USER_NAME:
 2288                 {
 2289                     struct isakmp_attribute *na;
 2290                     na = new_isakmp_attribute(ap->type, reply_attr);
 2291                     reply_attr = na;
 2292                     na->u.lots.length = strlen(config[CONFIG_XAUTH_USERNAME]);
 2293                     na->u.lots.data = xallocc(na->u.lots.length);
 2294                     memcpy(na->u.lots.data, config[CONFIG_XAUTH_USERNAME],
 2295                         na->u.lots.length);
 2296                     break;
 2297                 }
 2298             case ISAKMP_XAUTH_06_ATTRIB_ANSWER:
 2299             case ISAKMP_XAUTH_06_ATTRIB_USER_PASSWORD:
 2300             case ISAKMP_XAUTH_06_ATTRIB_PASSCODE:
 2301             case ISAKMP_XAUTH_06_ATTRIB_NEXT_PIN:
 2302                 if (passwd_used && config[CONFIG_NON_INTERACTIVE]) {
 2303                     reject = ISAKMP_N_AUTHENTICATION_FAILED;
 2304                     phase2_fatal(s, "noninteractive can't reuse password", reject);
 2305                     error(2, 0, "authentication unsuccessful");
 2306                 } else if (seen_answer || passwd_used || config[CONFIG_XAUTH_INTERACTIVE]) {
 2307                     char *pass, *prompt = NULL;
 2308                     struct isakmp_attribute *na;
 2309 
 2310                     asprintf(&prompt, "%s for VPN %s@%s: ",
 2311                         (ap->type == ISAKMP_XAUTH_06_ATTRIB_ANSWER) ?
 2312                         "Answer" :
 2313                         (ap->type == ISAKMP_XAUTH_06_ATTRIB_USER_PASSWORD) ?
 2314                         "Password" : "Passcode",
 2315                         config[CONFIG_XAUTH_USERNAME], ntop_buf);
 2316                     pass = getpass(prompt);
 2317                     free(prompt);
 2318 
 2319                     na = new_isakmp_attribute(ap->type, reply_attr);
 2320                     reply_attr = na;
 2321                     na->u.lots.length = strlen(pass);
 2322                     na->u.lots.data = xallocc(na->u.lots.length);
 2323                     memcpy(na->u.lots.data, pass, na->u.lots.length);
 2324                     memset(pass, 0, na->u.lots.length);
 2325                 } else {
 2326                     struct isakmp_attribute *na;
 2327                     na = new_isakmp_attribute(ap->type, reply_attr);
 2328                     reply_attr = na;
 2329                     na->u.lots.length = strlen(config[CONFIG_XAUTH_PASSWORD]);
 2330                     na->u.lots.data = xallocc(na->u.lots.length);
 2331                     memcpy(na->u.lots.data, config[CONFIG_XAUTH_PASSWORD],
 2332                         na->u.lots.length);
 2333                     passwd_used = 1; /* Provide canned password at most once */
 2334                 }
 2335                 break;
 2336             default:
 2337                 ;
 2338             }
 2339 
 2340         /* Send the response.  */
 2341         rp = new_isakmp_payload(ISAKMP_PAYLOAD_MODECFG_ATTR);
 2342         rp->u.modecfg.type = ISAKMP_MODECFG_CFG_REPLY;
 2343         rp->u.modecfg.id = r->payload->next->u.modecfg.id;
 2344         rp->u.modecfg.attributes = reply_attr;
 2345         sendrecv_phase2(s, rp, ISAKMP_EXCHANGE_MODECFG_TRANSACTION,
 2346             r->message_id, 0, 0, 0, 0, 0, 0, 0);
 2347 
 2348     }
 2349     
 2350     if ((opt_vendor == VENDOR_NETSCREEN) &&
 2351         (r->payload->next->u.modecfg.type == ISAKMP_MODECFG_CFG_SET)) {
 2352         struct isakmp_attribute *a = r->payload->next->u.modecfg.attributes;
 2353         
 2354         DEBUGTOP(2, printf("S5.5.1 do netscreen modecfg extra\n"));
 2355         
 2356         do_config_to_env(s, a);
 2357         
 2358         for (; a; a = a->next)
 2359             if(a->af == isakmp_attr_lots)
 2360                 a->u.lots.length = 0;
 2361 
 2362         r->payload->next->u.modecfg.type = ISAKMP_MODECFG_CFG_ACK;
 2363         sendrecv_phase2(s, r->payload->next,
 2364             ISAKMP_EXCHANGE_MODECFG_TRANSACTION,
 2365             r->message_id, 0, 0, 0, 0, 0, 0, 0);
 2366         
 2367         reject = do_phase2_notice_check(s, &r);
 2368         if (reject == -1) {
 2369             free_isakmp_packet(r);
 2370             return 1;
 2371         }
 2372     }
 2373     
 2374     DEBUGTOP(2, printf("S5.6 process xauth response\n"));
 2375     {
 2376         /* The final SET should have just one attribute.  */
 2377         struct isakmp_attribute *a = r->payload->next->u.modecfg.attributes;
 2378         uint16_t set_result = 1;
 2379 
 2380         if (a == NULL
 2381             || a->type != ISAKMP_XAUTH_06_ATTRIB_STATUS
 2382             || a->af != isakmp_attr_16 || a->next != NULL) {
 2383             reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
 2384             phase2_fatal(s, "xauth SET response rejected: %s(%d)", reject);
 2385         } else {
 2386             set_result = a->u.attr_16;
 2387         }
 2388 
 2389         /* ACK the SET.  */
 2390         r->payload->next->u.modecfg.type = ISAKMP_MODECFG_CFG_ACK;
 2391         sendrecv_phase2(s, r->payload->next, ISAKMP_EXCHANGE_MODECFG_TRANSACTION,
 2392             r->message_id, 1, 0, 0, 0, 0, 0, 0);
 2393         r->payload->next = NULL;
 2394         free_isakmp_packet(r);
 2395 
 2396         if (set_result == 0)
 2397             error(2, 0, "authentication unsuccessful");
 2398     }
 2399     DEBUGTOP(2, printf("S5.7 xauth done\n"));
 2400     return 0;
 2401 }
 2402 
 2403 static int do_phase2_config(struct sa_block *s)
 2404 {
 2405     struct isakmp_payload *rp;
 2406     struct isakmp_attribute *a;
 2407     struct isakmp_packet *r;
 2408     struct utsname uts;
 2409     uint32_t msgid;
 2410     int reject;
 2411     
 2412     uname(&uts);
 2413 
 2414     gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
 2415     if (msgid == 0)
 2416         msgid = 1;
 2417 
 2418     rp = new_isakmp_payload(ISAKMP_PAYLOAD_MODECFG_ATTR);
 2419     rp->u.modecfg.type = ISAKMP_MODECFG_CFG_REQUEST;
 2420     rp->u.modecfg.id = 20;
 2421     a = NULL;
 2422 
 2423     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_APPLICATION_VERSION, a);
 2424     a->u.lots.length = strlen(config[CONFIG_VERSION]);
 2425     a->u.lots.data = xallocc(a->u.lots.length);
 2426     memcpy(a->u.lots.data, config[CONFIG_VERSION], a->u.lots.length);
 2427 
 2428     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_DDNS_HOSTNAME, a);
 2429     a->u.lots.length = strlen(uts.nodename);
 2430     a->u.lots.data = xallocc(a->u.lots.length);
 2431     memcpy(a->u.lots.data, uts.nodename, a->u.lots.length);
 2432 
 2433     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_SPLIT_INC, a);
 2434     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_SAVE_PW, a);
 2435     
 2436     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_BANNER, a);
 2437     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_DO_PFS, a);
 2438     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_FW_TYPE, a);
 2439     a->u.lots.length = sizeof(FW_UNKNOWN_TYPEINFO);
 2440     a->u.lots.data = xallocc(a->u.lots.length);
 2441     memcpy(a->u.lots.data, FW_UNKNOWN_TYPEINFO, a->u.lots.length);
 2442     if (opt_natt_mode == NATT_CISCO_UDP)
 2443         a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_UDP_ENCAP_PORT, a);
 2444     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_DEF_DOMAIN, a);
 2445     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_NBNS, a);
 2446     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_DNS, a);
 2447     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_NETMASK, a);
 2448     a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_ADDRESS, a);
 2449 
 2450     rp->u.modecfg.attributes = a;
 2451     DEBUGTOP(2, printf("S6.1 phase2_config send modecfg\n"));
 2452     sendrecv_phase2(s, rp, ISAKMP_EXCHANGE_MODECFG_TRANSACTION, msgid, 0, 0, 0, 0, 0, 0, 0);
 2453 
 2454     DEBUGTOP(2, printf("S6.2 phase2_config receive modecfg\n"));
 2455     /* recv and check for notices */
 2456     reject = do_phase2_notice_check(s, &r);
 2457     if (reject == -1) {
 2458         if (r) free_isakmp_packet(r);
 2459         return 1;
 2460     }
 2461         
 2462     /* Check the transaction type & message ID are OK.  */
 2463     if (reject == 0 && r->message_id != msgid)
 2464         reject = ISAKMP_N_INVALID_MESSAGE_ID;
 2465     if (reject == 0 && r->exchange_type != ISAKMP_EXCHANGE_MODECFG_TRANSACTION)
 2466         reject = ISAKMP_N_INVALID_EXCHANGE_TYPE;
 2467 
 2468     /* After the hash, expect an attribute block.  */
 2469     if (reject == 0
 2470         && (r->payload->next == NULL
 2471             || r->payload->next->next != NULL
 2472             || r->payload->next->type != ISAKMP_PAYLOAD_MODECFG_ATTR
 2473 #if 0
 2474             || r->payload->next->u.modecfg.id != 20
 2475 #endif
 2476             || r->payload->next->u.modecfg.type != ISAKMP_MODECFG_CFG_REPLY))
 2477         reject = ISAKMP_N_PAYLOAD_MALFORMED;
 2478 
 2479     if (reject != 0)
 2480         phase2_fatal(s, "configuration response rejected: %s(%d)", reject);
 2481 
 2482     if (reject == 0)
 2483         reject = do_config_to_env(s, r->payload->next->u.modecfg.attributes);
 2484     
 2485     if (reject != 0)
 2486         phase2_fatal(s, "configuration response rejected: %s(%d)", reject);
 2487 
 2488     DEBUG(1, printf("got address %s\n", getenv("INTERNAL_IP4_ADDRESS")));
 2489     free_isakmp_packet(r);
 2490     return 0;
 2491 }
 2492 
 2493 static struct isakmp_attribute *make_transform_ipsec(struct sa_block *s, int dh_group, int hash, int keylen)
 2494 {
 2495     struct isakmp_attribute *a = NULL;
 2496 
 2497     a = new_isakmp_attribute(ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION, a);
 2498     a->af = isakmp_attr_lots;
 2499     a->u.lots.length = 4;
 2500     a->u.lots.data = xallocc(a->u.lots.length);
 2501     *((uint32_t *) a->u.lots.data) = htonl(2147483);
 2502     a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE, IPSEC_LIFE_SECONDS, a);
 2503 
 2504     if (dh_group)
 2505         a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_GROUP_DESC, dh_group, a);
 2506     a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_AUTH_ALG, hash, a);
 2507     a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_ENCAP_MODE, s->ipsec.encap_mode, a);
 2508     if (keylen != 0)
 2509         a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_KEY_LENGTH, keylen, a);
 2510 
 2511     return a;
 2512 }
 2513 
 2514 static struct isakmp_payload *make_our_sa_ipsec(struct sa_block *s)
 2515 {
 2516     struct isakmp_payload *r = new_isakmp_payload(ISAKMP_PAYLOAD_SA);
 2517     struct isakmp_payload *p = NULL, *pn;
 2518     struct isakmp_attribute *a;
 2519     int dh_grp = get_dh_group_ipsec(s->ipsec.do_pfs)->ipsec_sa_id;
 2520     unsigned int crypt, hash, keylen;
 2521     int i;
 2522 
 2523     r = new_isakmp_payload(ISAKMP_PAYLOAD_SA);
 2524     r->u.sa.doi = ISAKMP_DOI_IPSEC;
 2525     r->u.sa.situation = ISAKMP_IPSEC_SIT_IDENTITY_ONLY;
 2526     r->u.sa.proposals = new_isakmp_payload(ISAKMP_PAYLOAD_P);
 2527     r->u.sa.proposals->u.p.spi_size = 4;
 2528     r->u.sa.proposals->u.p.spi = xallocc(4);
 2529     /* The sadb_sa_spi field is already in network order.  */
 2530     memcpy(r->u.sa.proposals->u.p.spi, &s->ipsec.rx.spi, 4);
 2531     r->u.sa.proposals->u.p.prot_id = ISAKMP_IPSEC_PROTO_IPSEC_ESP;
 2532     for (crypt = 0; supp_crypt[crypt].name != NULL; crypt++) {
 2533         keylen = supp_crypt[crypt].keylen;
 2534         for (hash = 0; supp_hash[hash].name != NULL; hash++) {
 2535             pn = p;
 2536             p = new_isakmp_payload(ISAKMP_PAYLOAD_P);
 2537             p->u.p.spi_size = 4;
 2538             p->u.p.spi = xallocc(4);
 2539             /* The sadb_sa_spi field is already in network order.  */
 2540             memcpy(p->u.p.spi, &s->ipsec.rx.spi, 4);
 2541             p->u.p.prot_id = ISAKMP_IPSEC_PROTO_IPSEC_ESP;
 2542             p->u.p.transforms = new_isakmp_payload(ISAKMP_PAYLOAD_T);
 2543             p->u.p.transforms->u.t.id = supp_crypt[crypt].ipsec_sa_id;
 2544             a = make_transform_ipsec(s, dh_grp, supp_hash[hash].ipsec_sa_id, keylen);
 2545             p->u.p.transforms->u.t.attributes = a;
 2546             p->next = pn;
 2547         }
 2548     }
 2549     for (i = 0, pn = p; pn; pn = pn->next)
 2550         pn->u.p.number = i++;
 2551     r->u.sa.proposals = p;
 2552     return r;
 2553 }
 2554 
 2555 static void do_phase2_qm(struct sa_block *s)
 2556 {
 2557     struct isakmp_payload *rp, *us, *ke = NULL, *them, *nonce_r = NULL;
 2558     struct isakmp_packet *r;
 2559     struct group *dh_grp = NULL;
 2560     uint32_t msgid;
 2561     int reject;
 2562     uint8_t *p_flat = NULL, *realiv = NULL, realiv_msgid[4];
 2563     size_t p_size = 0;
 2564     uint8_t nonce_i[20], *dh_public = NULL;
 2565     int i;
 2566 
 2567     DEBUGTOP(2, printf("S7.1 QM_packet1\n"));
 2568     /* Set up the Diffie-Hellman stuff.  */
 2569     if (get_dh_group_ipsec(s->ipsec.do_pfs)->my_id) {
 2570         dh_grp = group_get(get_dh_group_ipsec(s->ipsec.do_pfs)->my_id);
 2571         DEBUG(3, printf("len = %d\n", dh_getlen(dh_grp)));
 2572         dh_public = xallocc(dh_getlen(dh_grp));
 2573         dh_create_exchange(dh_grp, dh_public);
 2574         hex_dump("dh_public", dh_public, dh_getlen(dh_grp), NULL);
 2575     }
 2576 
 2577     gcry_create_nonce((uint8_t *) & s->ipsec.rx.spi, sizeof(s->ipsec.rx.spi));
 2578     rp = make_our_sa_ipsec(s); /* FIXME: LEAK: allocated memory never freed */
 2579     gcry_create_nonce((uint8_t *) nonce_i, sizeof(nonce_i));
 2580     rp->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_NONCE, nonce_i, sizeof(nonce_i));
 2581 
 2582     us = new_isakmp_payload(ISAKMP_PAYLOAD_ID);
 2583     us->u.id.type = ISAKMP_IPSEC_ID_IPV4_ADDR;
 2584     us->u.id.length = 4;
 2585     us->u.id.data = xallocc(4);
 2586     memcpy(us->u.id.data, s->our_address, sizeof(struct in_addr));
 2587     them = new_isakmp_payload(ISAKMP_PAYLOAD_ID);
 2588     them->u.id.type = ISAKMP_IPSEC_ID_IPV4_ADDR_SUBNET;
 2589     them->u.id.length = 8;
 2590     them->u.id.data = xallocc(8);
 2591     init_netaddr((struct in_addr *)them->u.id.data,
 2592              config[CONFIG_IPSEC_TARGET_NETWORK]);
 2593     us->next = them;
 2594     s->ipsec.life.start = time(NULL);
 2595 
 2596     if (!dh_grp) {
 2597         rp->next->next = us;
 2598     } else {
 2599         rp->next->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_KE,
 2600             dh_public, dh_getlen(dh_grp));
 2601         rp->next->next->next = us;
 2602     }
 2603 
 2604     gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
 2605     if (msgid == 0)
 2606         msgid = 1;
 2607 
 2608     for (i = 0; i < 4; i++) {
 2609         DEBUGTOP(2, printf("S7.2 QM_packet2 send_receive\n"));
 2610         sendrecv_phase2(s, rp, ISAKMP_EXCHANGE_IKE_QUICK,
 2611             msgid, 0, &p_flat, &p_size, 0, 0, 0, 0);
 2612 
 2613         if (realiv == NULL) {
 2614             realiv = xallocc(s->ike.ivlen);
 2615             memcpy(realiv, s->ike.current_iv, s->ike.ivlen);
 2616             memcpy(realiv_msgid, s->ike.current_iv_msgid, 4);
 2617         }
 2618 
 2619         DEBUGTOP(2, printf("S7.3 QM_packet2 validate type\n"));
 2620         reject = unpack_verify_phase2(s, r_packet, r_length, &r, nonce_i, sizeof(nonce_i)); /* FIXME: LEAK */
 2621 
 2622         if (((reject == 0) || (reject == ISAKMP_N_AUTHENTICATION_FAILED))
 2623             && r->exchange_type == ISAKMP_EXCHANGE_INFORMATIONAL) {
 2624             DEBUGTOP(2, printf("S7.4 process and skip lifetime notice\n"));
 2625             /* handle notify responder-lifetime */
 2626             /* (broken hash => ignore AUTHENTICATION_FAILED) */
 2627             if (reject == 0 && r->payload->next->type != ISAKMP_PAYLOAD_N)
 2628                 reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
 2629 
 2630             if (reject == 0
 2631                 && r->payload->next->u.n.type == ISAKMP_N_IPSEC_RESPONDER_LIFETIME) {
 2632                 if (r->payload->next->u.n.protocol == ISAKMP_IPSEC_PROTO_ISAKMP)
 2633                     lifetime_ike_process(s, r->payload->next->u.n.attributes);
 2634                 else if (r->payload->next->u.n.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP)
 2635                     lifetime_ipsec_process(s, r->payload->next->u.n.attributes);
 2636                 else
 2637                     DEBUG(2, printf("got unknown lifetime notice, ignoring..\n"));
 2638                 memcpy(s->ike.current_iv, realiv, s->ike.ivlen);
 2639                 memcpy(s->ike.current_iv_msgid, realiv_msgid, 4);
 2640                 continue;
 2641             }
 2642         }
 2643 
 2644         /* Check the transaction type & message ID are OK.  */
 2645         if (reject == 0 && r->message_id != msgid)
 2646             reject = ISAKMP_N_INVALID_MESSAGE_ID;
 2647 
 2648         if (reject == 0 && r->exchange_type != ISAKMP_EXCHANGE_IKE_QUICK)
 2649             reject = ISAKMP_N_INVALID_EXCHANGE_TYPE;
 2650 
 2651         /* The SA payload must be second.  */
 2652         if (reject == 0 && r->payload->next->type != ISAKMP_PAYLOAD_SA)
 2653             reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
 2654 
 2655         free(p_flat);
 2656         free(realiv);
 2657 
 2658         break;
 2659     }
 2660 
 2661     DEBUGTOP(2, printf("S7.5 QM_packet2 check reject offer\n"));
 2662     if (reject != 0)
 2663         phase2_fatal(s, "quick mode response rejected: %s(%d)\n"
 2664             "this means the concentrator did not like what we had to offer.\n"
 2665             "Possible reasons are:\n"
 2666             "  * concentrator configured to require a firewall\n"
 2667             "     this locks out even Cisco clients on any platform expect windows\n"
 2668             "     which is an obvious security improvment. There is no workaround (yet).\n"
 2669             "  * concentrator configured to require IP compression\n"
 2670             "     this is not yet supported by vpnc.\n"
 2671             "     Note: the Cisco Concentrator Documentation recommends against using\n"
 2672             "     compression, expect on low-bandwith (read: ISDN) links, because it\n"
 2673             "     uses much CPU-resources on the concentrator\n",
 2674             reject);
 2675 
 2676     DEBUGTOP(2, printf("S7.6 QM_packet2 check and process proposal\n"));
 2677     for (rp = r->payload->next; rp && reject == 0; rp = rp->next)
 2678         switch (rp->type) {
 2679         case ISAKMP_PAYLOAD_SA:
 2680             if (reject == 0 && rp->u.sa.doi != ISAKMP_DOI_IPSEC)
 2681                 reject = ISAKMP_N_DOI_NOT_SUPPORTED;
 2682             if (reject == 0 && rp->u.sa.situation != ISAKMP_IPSEC_SIT_IDENTITY_ONLY)
 2683                 reject = ISAKMP_N_SITUATION_NOT_SUPPORTED;
 2684             if (reject == 0 &&
 2685                 (rp->u.sa.proposals == NULL || rp->u.sa.proposals->next != NULL))
 2686                 reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2687             if (reject == 0 &&
 2688                 rp->u.sa.proposals->u.p.prot_id != ISAKMP_IPSEC_PROTO_IPSEC_ESP)
 2689                 reject = ISAKMP_N_INVALID_PROTOCOL_ID;
 2690             if (reject == 0 && rp->u.sa.proposals->u.p.spi_size != 4)
 2691                 reject = ISAKMP_N_INVALID_SPI;
 2692             if (reject == 0 &&
 2693                 (rp->u.sa.proposals->u.p.transforms == NULL
 2694                     || rp->u.sa.proposals->u.p.transforms->next != NULL))
 2695                 reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2696             if (reject == 0) {
 2697                 struct isakmp_attribute *a
 2698                     = rp->u.sa.proposals->u.p.transforms->u.t.attributes;
 2699                 int seen_enc = rp->u.sa.proposals->u.p.transforms->u.t.id;
 2700                 int seen_auth = 0, seen_encap = 0, seen_group = 0, seen_keylen = 0;
 2701 
 2702                 memcpy(&s->ipsec.tx.spi, rp->u.sa.proposals->u.p.spi, 4);
 2703 
 2704                 for (; a && reject == 0; a = a->next)
 2705                     switch (a->type) {
 2706                     case ISAKMP_IPSEC_ATTRIB_AUTH_ALG:
 2707                         if (a->af == isakmp_attr_16)
 2708                             seen_auth = a->u.attr_16;
 2709                         else
 2710                             reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2711                         break;
 2712                     case ISAKMP_IPSEC_ATTRIB_ENCAP_MODE:
 2713                         if (a->af == isakmp_attr_16 &&
 2714                             a->u.attr_16 == s->ipsec.encap_mode)
 2715                             seen_encap = 1;
 2716                         else
 2717                             reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2718                         break;
 2719                     case ISAKMP_IPSEC_ATTRIB_GROUP_DESC:
 2720                         if (dh_grp &&
 2721                             a->af == isakmp_attr_16 &&
 2722                             a->u.attr_16 ==
 2723                             get_dh_group_ipsec(s->ipsec.do_pfs)->ipsec_sa_id)
 2724                             seen_group = 1;
 2725                         else
 2726                             reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2727                         break;
 2728                     case ISAKMP_IPSEC_ATTRIB_KEY_LENGTH:
 2729                         if (a->af == isakmp_attr_16)
 2730                             seen_keylen = a->u.attr_16;
 2731                         else
 2732                             reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2733                         break;
 2734                     case ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE:
 2735                         /* lifetime duration MUST follow lifetype attribute */
 2736                         if (a->next->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION) {
 2737                             lifetime_ipsec_process(s, a);
 2738                         } else
 2739                             reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2740                         break;
 2741                     case ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION:
 2742                         /* already processed above in ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE: */
 2743                         break;
 2744                     default:
 2745                         reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
 2746                         break;
 2747                     }
 2748                 if (reject == 0 && (!seen_auth || !seen_encap ||
 2749                         (dh_grp && !seen_group)))
 2750                     reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2751 
 2752                 if (reject == 0
 2753                     && get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA, seen_auth,
 2754                         NULL, 0) == NULL)
 2755                     reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2756                 if (reject == 0
 2757                     && get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IPSEC_SA, seen_enc,
 2758                         NULL, seen_keylen) == NULL)
 2759                     reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2760 
 2761                 if (reject == 0) {
 2762                     s->ipsec.cry_algo =
 2763                         get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IPSEC_SA,
 2764                         seen_enc, NULL, seen_keylen)->my_id;
 2765                     s->ipsec.md_algo =
 2766                         get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA,
 2767                         seen_auth, NULL, 0)->my_id;
 2768                     if (s->ipsec.cry_algo) {
 2769                         gcry_cipher_algo_info(s->ipsec.cry_algo, GCRYCTL_GET_KEYLEN, NULL, &(s->ipsec.key_len));
 2770                         gcry_cipher_algo_info(s->ipsec.cry_algo, GCRYCTL_GET_BLKLEN, NULL, &(s->ipsec.blk_len));
 2771                         s->ipsec.iv_len = s->ipsec.blk_len;
 2772                     } else {
 2773                         s->ipsec.key_len = 0;
 2774                         s->ipsec.iv_len = 0;
 2775                         s->ipsec.blk_len = 8; /* seems to be this without encryption... */
 2776                     }
 2777                     s->ipsec.md_len = gcry_md_get_algo_dlen(s->ipsec.md_algo);
 2778                     DEBUG(1, printf("IPSEC SA selected %s-%s\n",
 2779                             get_algo(SUPP_ALGO_CRYPT,
 2780                                 SUPP_ALGO_IPSEC_SA, seen_enc, NULL,
 2781                                 seen_keylen)->name,
 2782                             get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA,
 2783                                 seen_auth, NULL, 0)->name));
 2784                     if (s->ipsec.cry_algo == GCRY_CIPHER_DES && !opt_1des) {
 2785                         error(1, 0, "peer selected (single) DES as \"encrytion\" method.\n"
 2786                             "This algorithm is considered to weak today\n"
 2787                             "If your vpn concentrator admin still insists on using DES\n"
 2788                             "use the \"--enable-1des\" option.\n");
 2789                     } else if (s->ipsec.cry_algo == GCRY_CIPHER_NONE && !opt_no_encryption) {
 2790                         error(1, 0, "peer selected NULL as \"encrytion\" method.\n"
 2791                             "This is _no_ encryption at all.\n"
 2792                             "Your traffic is still protected against modification with %s\n"
 2793                             "If your vpn concentrator admin still insists on not using encryption\n"
 2794                             "use the \"--enable-no-encryption\" option.\n",
 2795                             get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA, seen_auth, NULL, 0)->name);
 2796                     }
 2797                 }
 2798             }
 2799             break;
 2800 
 2801         case ISAKMP_PAYLOAD_N:
 2802             if (reject == 0 && rp->u.n.type == ISAKMP_N_IPSEC_RESPONDER_LIFETIME) {
 2803                 if (rp->u.n.protocol == ISAKMP_IPSEC_PROTO_ISAKMP)
 2804                     lifetime_ike_process(s, rp->u.n.attributes);
 2805                 else if (rp->u.n.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP)
 2806                     lifetime_ipsec_process(s, rp->u.n.attributes);
 2807                 else
 2808                     DEBUG(2, printf("got unknown lifetime notice, ignoring..\n"));
 2809             }
 2810             break;
 2811         case ISAKMP_PAYLOAD_ID:
 2812             /* FIXME: Parse payload ID and add route-env in case of ipv4_prefix */
 2813             break;
 2814         case ISAKMP_PAYLOAD_KE:
 2815             ke = rp;
 2816             break;
 2817         case ISAKMP_PAYLOAD_NONCE:
 2818             nonce_r = rp;
 2819             break;
 2820 
 2821         default:
 2822             reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
 2823             break;
 2824         }
 2825 
 2826     if (reject == 0 && nonce_r == NULL)
 2827         reject = ISAKMP_N_INVALID_HASH_INFORMATION;
 2828     if (reject == 0 && dh_grp && (ke == NULL || ke->u.ke.length != dh_getlen(dh_grp)))
 2829         reject = ISAKMP_N_INVALID_KEY_INFORMATION;
 2830     if (reject != 0)
 2831         phase2_fatal(s, "quick mode response rejected [2]: %s(%d)", reject);
 2832 
 2833     /* send final packet */
 2834     sendrecv_phase2(s, NULL, ISAKMP_EXCHANGE_IKE_QUICK,
 2835         msgid, 1, 0, 0, nonce_i, sizeof(nonce_i),
 2836         nonce_r->u.nonce.data, nonce_r->u.nonce.length);
 2837 
 2838     DEBUGTOP(2, printf("S7.7 QM_packet3 sent\n"));
 2839 
 2840     DEBUGTOP(2, printf("S7.8 setup ipsec tunnel\n"));
 2841     {
 2842         unsigned char *dh_shared_secret = NULL;
 2843 
 2844         if (dh_grp) {
 2845             /* Determine the shared secret.  */
 2846             dh_shared_secret = xallocc(dh_getlen(dh_grp));
 2847             dh_create_shared(dh_grp, dh_shared_secret, ke->u.ke.data);
 2848             hex_dump("dh_shared_secret", dh_shared_secret, dh_getlen(dh_grp), NULL);
 2849         }
 2850         
 2851         s->ipsec.rx.key = gen_keymat(s, ISAKMP_IPSEC_PROTO_IPSEC_ESP, s->ipsec.rx.spi,
 2852             dh_shared_secret, dh_grp ? dh_getlen(dh_grp) : 0,
 2853             nonce_i, sizeof(nonce_i), nonce_r->u.nonce.data, nonce_r->u.nonce.length);
 2854         
 2855         s->ipsec.tx.key = gen_keymat(s, ISAKMP_IPSEC_PROTO_IPSEC_ESP, s->ipsec.tx.spi,
 2856             dh_shared_secret, dh_grp ? dh_getlen(dh_grp) : 0,
 2857             nonce_i, sizeof(nonce_i), nonce_r->u.nonce.data, nonce_r->u.nonce.length);
 2858         
 2859         if (dh_grp)
 2860             group_free(dh_grp);
 2861         free(dh_shared_secret);
 2862         free_isakmp_packet(r);
 2863         
 2864         if ((opt_natt_mode == NATT_CISCO_UDP) && s->ipsec.peer_udpencap_port) {
 2865             s->esp_fd = make_socket(s, opt_udpencapport, s->ipsec.peer_udpencap_port);
 2866             s->ipsec.encap_mode = IPSEC_ENCAP_UDP_TUNNEL;
 2867             s->ipsec.natt_active_mode = NATT_ACTIVE_CISCO_UDP;
 2868         } else if (s->ipsec.encap_mode != IPSEC_ENCAP_TUNNEL) {
 2869             s->esp_fd = s->ike_fd;
 2870         } else {
 2871 #ifdef IP_HDRINCL
 2872             int hincl = 1;
 2873 #endif
 2874         
 2875             s->esp_fd = socket(PF_INET, SOCK_RAW, IPPROTO_ESP);
 2876             if (s->esp_fd == -1) {
 2877                 close_tunnel(s);
 2878                 error(1, errno, "Couldn't open socket of ESP. Maybe something registered ESP already.\nPlease try '--natt-mode force-natt' or disable whatever is using ESP.\nsocket(PF_INET, SOCK_RAW, IPPROTO_ESP)");
 2879             }
 2880 #ifdef IP_HDRINCL
 2881             if (setsockopt(s->esp_fd, IPPROTO_IP, IP_HDRINCL, &hincl, sizeof(hincl)) == -1) {
 2882                 close_tunnel(s);
 2883                 error(1, errno, "setsockopt(esp_fd, IPPROTO_IP, IP_HDRINCL, 1)");
 2884             }
 2885 #endif
 2886         }
 2887         
 2888         s->ipsec.rx.seq_id = s->ipsec.tx.seq_id = 1;
 2889     }
 2890     free(dh_public);
 2891 }
 2892 
 2893 static void send_delete_ipsec(struct sa_block *s)
 2894 {
 2895     /* 2007-08-31 JKU/ZID: Sonicwall doesn't like the chained
 2896      * request but wants them split. Cisco does fine with it. */
 2897     DEBUGTOP(2, printf("S7.10 send ipsec termination message\n"));
 2898     {
 2899         struct isakmp_payload *d_ipsec;
 2900         uint8_t del_msgid;
 2901 
 2902         gcry_create_nonce((uint8_t *) & del_msgid, sizeof(del_msgid));
 2903         d_ipsec = new_isakmp_payload(ISAKMP_PAYLOAD_D);
 2904         d_ipsec->u.d.doi = ISAKMP_DOI_IPSEC;
 2905         d_ipsec->u.d.protocol = ISAKMP_IPSEC_PROTO_IPSEC_ESP;
 2906         d_ipsec->u.d.spi_length = 4;
 2907         d_ipsec->u.d.num_spi = 2;
 2908         d_ipsec->u.d.spi = xallocc(2 * sizeof(uint8_t *));
 2909         d_ipsec->u.d.spi[0] = xallocc(d_ipsec->u.d.spi_length);
 2910         memcpy(d_ipsec->u.d.spi[0], &s->ipsec.rx.spi, 4);
 2911         d_ipsec->u.d.spi[1] = xallocc(d_ipsec->u.d.spi_length);
 2912         memcpy(d_ipsec->u.d.spi[1], &s->ipsec.tx.spi, 4);
 2913         sendrecv_phase2(s, d_ipsec, ISAKMP_EXCHANGE_INFORMATIONAL,
 2914             del_msgid, 1, NULL, NULL,
 2915             NULL, 0, NULL, 0);
 2916     }
 2917 }
 2918 
 2919 static void send_delete_isakmp(struct sa_block *s)
 2920 {
 2921     DEBUGTOP(2, printf("S7.11 send isakmp termination message\n"));
 2922     {
 2923         struct isakmp_payload *d_isakmp;
 2924         uint8_t del_msgid;
 2925 
 2926         gcry_create_nonce((uint8_t *) & del_msgid, sizeof(del_msgid));
 2927         d_isakmp = new_isakmp_payload(ISAKMP_PAYLOAD_D);
 2928         d_isakmp->u.d.doi = ISAKMP_DOI_IPSEC;
 2929         d_isakmp->u.d.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
 2930         d_isakmp->u.d.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
 2931         d_isakmp->u.d.num_spi = 1;
 2932         d_isakmp->u.d.spi = xallocc(1 * sizeof(uint8_t *));
 2933         d_isakmp->u.d.spi[0] = xallocc(2 * ISAKMP_COOKIE_LENGTH);
 2934         memcpy(d_isakmp->u.d.spi[0] + ISAKMP_COOKIE_LENGTH * 0, s->ike.i_cookie,
 2935             ISAKMP_COOKIE_LENGTH);
 2936         memcpy(d_isakmp->u.d.spi[0] + ISAKMP_COOKIE_LENGTH * 1, s->ike.r_cookie,
 2937             ISAKMP_COOKIE_LENGTH);
 2938         sendrecv_phase2(s, d_isakmp, ISAKMP_EXCHANGE_INFORMATIONAL,
 2939             del_msgid, 1, NULL, NULL,
 2940             NULL, 0, NULL, 0);
 2941     }
 2942 }
 2943 
 2944 static int do_rekey(struct sa_block *s, struct isakmp_packet *r)
 2945 {
 2946     struct isakmp_payload *rp, *ke = NULL, *nonce_i = NULL;
 2947     struct isakmp_attribute *a;
 2948     int seen_enc;
 2949     int seen_auth = 0, seen_encap = 0, seen_group = 0, seen_keylen = 0;
 2950     int nonce_i_copy_len;
 2951     struct group *dh_grp = NULL;
 2952     uint8_t nonce_r[20], *dh_public = NULL, *nonce_i_copy = NULL;
 2953     unsigned char *dh_shared_secret = NULL;
 2954     
 2955     if (get_dh_group_ipsec(s->ipsec.do_pfs)->my_id) {
 2956         dh_grp = group_get(get_dh_group_ipsec(s->ipsec.do_pfs)->my_id);
 2957         DEBUG(3, printf("len = %d\n", dh_getlen(dh_grp)));
 2958         dh_public = xallocc(dh_getlen(dh_grp));
 2959         dh_create_exchange(dh_grp, dh_public);
 2960         hex_dump("dh_public", dh_public, dh_getlen(dh_grp), NULL);
 2961     }
 2962     
 2963     rp = r->payload->next;
 2964     /* rp->type == ISAKMP_PAYLOAD_SA, verified by caller */
 2965     
 2966     if (rp->u.sa.doi != ISAKMP_DOI_IPSEC)
 2967         return ISAKMP_N_DOI_NOT_SUPPORTED;
 2968     if (rp->u.sa.situation != ISAKMP_IPSEC_SIT_IDENTITY_ONLY)
 2969         return ISAKMP_N_SITUATION_NOT_SUPPORTED;
 2970     if (rp->u.sa.proposals == NULL)
 2971         return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2972     if (rp->u.sa.proposals->u.p.prot_id != ISAKMP_IPSEC_PROTO_IPSEC_ESP)
 2973         return ISAKMP_N_INVALID_PROTOCOL_ID;
 2974     if (rp->u.sa.proposals->u.p.spi_size != 4)
 2975         return ISAKMP_N_INVALID_SPI;
 2976     if (rp->u.sa.proposals->u.p.transforms == NULL || rp->u.sa.proposals->u.p.transforms->next != NULL)
 2977         return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2978     
 2979     seen_enc = rp->u.sa.proposals->u.p.transforms->u.t.id;
 2980     
 2981     memcpy(&s->ipsec.tx.spi, rp->u.sa.proposals->u.p.spi, 4);
 2982     
 2983     for (a = rp->u.sa.proposals->u.p.transforms->u.t.attributes; a; a = a->next)
 2984         switch (a->type) {
 2985         case ISAKMP_IPSEC_ATTRIB_AUTH_ALG:
 2986             if (a->af == isakmp_attr_16)
 2987                 seen_auth = a->u.attr_16;
 2988             else
 2989                 return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 2990             break;
 2991         case ISAKMP_IPSEC_ATTRIB_ENCAP_MODE:
 2992             if (a->af == isakmp_attr_16 &&
 2993                 a->u.attr_16 == (
 2994                     (s->ipsec.natt_active_mode != NATT_ACTIVE_CISCO_UDP) ?
 2995                     s->ipsec.encap_mode :
 2996                     IPSEC_ENCAP_TUNNEL /* cisco-udp claims to use encap tunnel... */
 2997                 ))
 2998                 seen_encap = 1;
 2999             else
 3000                 return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3001             break;
 3002         case ISAKMP_IPSEC_ATTRIB_GROUP_DESC:
 3003             if (dh_grp && a->af == isakmp_attr_16 &&
 3004                 a->u.attr_16 == get_dh_group_ipsec(s->ipsec.do_pfs)->ipsec_sa_id)
 3005                 seen_group = 1;
 3006             else
 3007                 return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3008             break;
 3009         case ISAKMP_IPSEC_ATTRIB_KEY_LENGTH:
 3010             if (a->af == isakmp_attr_16)
 3011                 seen_keylen = a->u.attr_16;
 3012             else
 3013                 return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3014             break;
 3015         case ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE:
 3016             /* lifetime duration MUST follow lifetype attribute */
 3017             if (a->next->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION) {
 3018                 lifetime_ipsec_process(s, a);
 3019             } else
 3020                 return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3021             break;
 3022         case ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION:
 3023             /* already processed above in ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE: */
 3024             break;
 3025         default:
 3026             return ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
 3027             break;
 3028         }
 3029     if (!seen_auth || !seen_encap || (dh_grp && !seen_group))
 3030         return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3031     
 3032     /* FIXME: Current code has a limitation that will cause problems if
 3033      * different algorithms are negotiated during re-keying
 3034      */
 3035     if ((get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA, seen_auth, NULL, 0) == NULL) || 
 3036         (get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IPSEC_SA, seen_enc, NULL, seen_keylen) == NULL)) {
 3037         printf("\nFIXME: vpnc doesn't support change of algorightms during rekeying\n");
 3038         return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3039     }
 3040     
 3041     /* we don't want to change ciphers during rekeying */
 3042     if (s->ipsec.cry_algo != get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IPSEC_SA, seen_enc,  NULL, seen_keylen)->my_id)
 3043         return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3044     if (s->ipsec.md_algo  != get_algo(SUPP_ALGO_HASH,  SUPP_ALGO_IPSEC_SA, seen_auth, NULL, 0)->my_id)
 3045         return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3046     
 3047     for (rp = rp->next; rp; rp = rp->next)
 3048         switch (rp->type) {
 3049         case ISAKMP_PAYLOAD_ID:
 3050             /* FIXME: Parse payload ID and add route-env in case of ipv4_prefix */
 3051             break;
 3052         case ISAKMP_PAYLOAD_KE:
 3053             ke = rp;
 3054             break;
 3055         case ISAKMP_PAYLOAD_NONCE:
 3056             nonce_i = rp;
 3057             break;
 3058         default:
 3059             return ISAKMP_N_INVALID_PAYLOAD_TYPE;
 3060             break;
 3061         }
 3062     
 3063     if ((dh_grp && ke == NULL) || nonce_i == NULL)
 3064         return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
 3065     
 3066     DEBUG(3, printf("everything fine so far...\n"));
 3067     gcry_create_nonce((uint8_t *) nonce_r, sizeof(nonce_r));
 3068     gcry_create_nonce((uint8_t *) & s->ipsec.rx.spi, sizeof(s->ipsec.rx.spi));
 3069     
 3070     if (dh_grp) {
 3071         /* Determine the shared secret.  */
 3072         dh_shared_secret = xallocc(dh_getlen(dh_grp));
 3073         dh_create_shared(dh_grp, dh_shared_secret, ke->u.ke.data);
 3074         hex_dump("dh_shared_secret", dh_shared_secret, dh_getlen(dh_grp), NULL);
 3075     }
 3076     
 3077     free(s->ipsec.rx.key);
 3078     free(s->ipsec.tx.key);
 3079         
 3080     s->ipsec.rx.key = gen_keymat(s, ISAKMP_IPSEC_PROTO_IPSEC_ESP, s->ipsec.rx.spi,
 3081         dh_shared_secret, dh_grp ? dh_getlen(dh_grp) : 0,
 3082         nonce_i->u.nonce.data, nonce_i->u.nonce.length, nonce_r, sizeof(nonce_r));
 3083     
 3084     s->ipsec.tx.key = gen_keymat(s, ISAKMP_IPSEC_PROTO_IPSEC_ESP, s->ipsec.tx.spi,
 3085         dh_shared_secret, dh_grp ? dh_getlen(dh_grp) : 0,
 3086         nonce_i->u.nonce.data, nonce_i->u.nonce.length, nonce_r, sizeof(nonce_r));
 3087     
 3088     s->ipsec.rx.key_cry = s->ipsec.rx.key;
 3089     s->ipsec.rx.key_md  = s->ipsec.rx.key + s->ipsec.key_len;
 3090     s->ipsec.tx.key_cry = s->ipsec.tx.key;
 3091     s->ipsec.tx.key_md  = s->ipsec.tx.key + s->ipsec.key_len;
 3092     
 3093     nonce_i_copy_len = nonce_i->u.nonce.length;
 3094     nonce_i_copy = xallocc(nonce_i_copy_len);
 3095     memcpy(nonce_i_copy, nonce_i->u.nonce.data, nonce_i_copy_len);
 3096     
 3097     s->ipsec.rx.seq_id = s->ipsec.tx.seq_id = 1;
 3098     s->ipsec.life.start = time(NULL);
 3099     s->ipsec.life.tx = 0;
 3100     s->ipsec.life.rx = 0;
 3101     
 3102     if (s->ipsec.cry_algo) {
 3103         gcry_cipher_setkey(s->ipsec.rx.cry_ctx, s->ipsec.rx.key_cry, s->ipsec.key_len);
 3104         gcry_cipher_setkey(s->ipsec.tx.cry_ctx, s->ipsec.tx.key_cry, s->ipsec.key_len);
 3105     }
 3106     
 3107     /* use request as template and just exchange some values */
 3108     /* this overwrites data in nonce_i, ke! */
 3109     rp = r->payload->next;
 3110     /* SA, change the SPI */
 3111     memcpy(rp->u.sa.proposals->u.p.spi, &s->ipsec.rx.spi, 4);
 3112     
 3113     for (rp = rp->next; rp; rp = rp->next)
 3114         switch (rp->type) {
 3115         case ISAKMP_PAYLOAD_ID:
 3116             break;
 3117         case ISAKMP_PAYLOAD_KE:
 3118             memcpy(rp->u.ke.data, dh_public, dh_getlen(dh_grp));
 3119             break;
 3120         case ISAKMP_PAYLOAD_NONCE:
 3121             memcpy(rp->u.nonce.data, nonce_r, sizeof(nonce_r));
 3122             break;
 3123         default:
 3124             assert(0);
 3125             break;
 3126         }
 3127     
 3128     sendrecv_phase2(s, r->payload->next, ISAKMP_EXCHANGE_IKE_QUICK,
 3129         r->message_id, 0, 0, 0, nonce_i_copy, nonce_i_copy_len, 0,0);
 3130     unpack_verify_phase2(s, r_packet, r_length, &r, NULL, 0);
 3131     free(nonce_i_copy);
 3132     /* don't care about answer ... */
 3133     
 3134     return 0;
 3135 }
 3136 
 3137 void process_late_ike(struct sa_block *s, uint8_t *r_packet, ssize_t r_length)
 3138 {
 3139     int reject;
 3140     struct isakmp_packet *r;
 3141     struct isakmp_payload *rp;
 3142     
 3143     DEBUG(2,printf("got late ike paket: %zd bytes\n", r_length));
 3144     /* we should ignore resent pakets here.
 3145      * unpack_verify_phase2 will fail to decode them probably */
 3146     reject = unpack_verify_phase2(s, r_packet, r_length, &r, NULL, 0);
 3147     
 3148     /* just ignore broken stuff for now */
 3149     if (reject != 0) {
 3150         if (r) free_isakmp_packet(r);
 3151         return;
 3152     }
 3153     
 3154     /* everything must be encrypted by now */
 3155     if (r->payload == NULL || r->payload->type != ISAKMP_PAYLOAD_HASH) {
 3156         free_isakmp_packet(r);
 3157         return;
 3158     }
 3159     
 3160     /* empty packet? well, nothing to see here */
 3161     if (r->payload->next == NULL) {
 3162         free_isakmp_packet(r);
 3163         return;
 3164     }
 3165     
 3166     /* do we get an SA proposal for rekeying? */
 3167     if (r->exchange_type == ISAKMP_EXCHANGE_IKE_QUICK &&
 3168         r->payload->next->type == ISAKMP_PAYLOAD_SA) {
 3169         reject = do_rekey(s, r);
 3170         DEBUG(3, printf("do_rekey returned: %d\n", reject));
 3171         /* FIXME: LEAK but will create segfault for double free */
 3172         /* free_isakmp_packet(r); */
 3173         return;
 3174     }
 3175 
 3176     if (r->exchange_type == ISAKMP_EXCHANGE_INFORMATIONAL) {
 3177         /* Search for notify payloads */
 3178         for (rp = r->payload->next; rp; rp = rp->next) {
 3179             if (rp->type != ISAKMP_PAYLOAD_N)
 3180                 continue;
 3181             /* did we get a DPD request or ACK? */
 3182             if (rp->u.n.protocol != ISAKMP_IPSEC_PROTO_ISAKMP) {
 3183                 DEBUG(2, printf("got non isakmp-notify, ignoring...\n"));
 3184                 continue;
 3185             }
 3186             if (rp->u.n.type == ISAKMP_N_R_U_THERE) {
 3187                 uint32_t seq;
 3188                 if (rp->u.n.data_length != 4) {
 3189                     DEBUG(2, printf("ignoring bad data length R-U-THERE request\n"));
 3190                     continue;
 3191                 }
 3192                 memcpy(&seq, rp->u.n.data, 4);
 3193                 send_dpd(s, 1, seq);
 3194                 DEBUG(2, printf("got r-u-there request sent ack\n"));
 3195                 continue;
 3196             } else if (rp->u.n.type == ISAKMP_N_R_U_THERE_ACK) {
 3197                 uint32_t seqack;
 3198                 if (rp->u.n.data_length != 4) {
 3199                     DEBUG(2, printf("ignoring bad data length R-U-THERE-ACK\n"));
 3200                     continue;
 3201                 }
 3202                 memcpy(&seqack, rp->u.n.data, 4);
 3203                 if (seqack == s->ike.dpd_seqno) {
 3204                     s->ike.dpd_seqno_ack = seqack;
 3205                 } else {
 3206                     DEBUG(2, printf("ignoring r-u-there ack %u (expecting %u)\n", seqack, s->ike.dpd_seqno));
 3207                     continue;
 3208                 }
 3209                 DEBUG(2, printf("got r-u-there ack\n"));
 3210             }
 3211         }
 3212     }
 3213     
 3214     /* check if our isakmp sa gets deleted */
 3215     for (rp = r->payload->next; rp; rp = rp->next) {
 3216         /* search for delete payloads */
 3217         if (rp->type != ISAKMP_PAYLOAD_D)
 3218             continue;
 3219         if (rp->u.d.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP) {
 3220             /* RFC2408, 5.15:
 3221              * Process the Delete payload and take appropriate action, according
 3222              * to local security policy.  As described above, one appropriate
 3223              * action SHOULD include cleaning up the local SA database.
 3224              */
 3225             /* FIXME: any cleanup needed??? */
 3226 
 3227             free_isakmp_packet(r);
 3228             do_phase2_qm(s);
 3229             return;
 3230         }
 3231         /* skip ipsec-esp delete */
 3232         if (rp->u.d.protocol != ISAKMP_IPSEC_PROTO_ISAKMP) {
 3233             DEBUG(2, printf("got non isakmp-delete, ignoring...\n"));
 3234             continue;
 3235         };
 3236         
 3237         /*
 3238          * RFC 2408, 3.15 Delete Payload
 3239          * it is not stated that the SPI field of a delete
 3240          * payload can be ignored, because it is given in
 3241          * the headers, but I assume so. In other cases
 3242          * RFC 2408 (notifications) states this.
 3243          */
 3244         do_kill = -1;
 3245         DEBUG(2, printf("got isakmp-delete, terminating...\n"));
 3246         free_isakmp_packet(r);
 3247         return;
 3248     }
 3249     
 3250     free_isakmp_packet(r);
 3251     return;
 3252 }
 3253 
 3254 int main(int argc, char **argv)
 3255 {
 3256     int do_load_balance;
 3257     const uint8_t hex_test[] = { 0, 1, 2, 3 };
 3258     struct sa_block oursa[1];
 3259     struct sa_block *s = oursa;
 3260 
 3261     test_pack_unpack();
 3262 #if defined(__CYGWIN__)
 3263     gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
 3264 #endif
 3265     gcry_check_version("1.1.90");
 3266     gcry_control(GCRYCTL_INIT_SECMEM, 16384, 0);
 3267     group_init();
 3268     
 3269     memset(s, 0, sizeof(*s));
 3270     s->ipsec.encap_mode = IPSEC_ENCAP_TUNNEL;
 3271     s->ike.timeout = 1000; /* 1 second */
 3272 
 3273     do_config(argc, argv);
 3274     
 3275     DEBUG(1, printf("\nvpnc version " VERSION "\n"));
 3276     hex_dump("hex_test", hex_test, sizeof(hex_test), NULL);
 3277 
 3278     DEBUGTOP(2, printf("S1 init_sockaddr\n"));
 3279     init_sockaddr(&s->dst, config[CONFIG_IPSEC_GATEWAY]);
 3280     init_sockaddr(&s->opt_src_ip, config[CONFIG_LOCAL_ADDR]);
 3281     DEBUGTOP(2, printf("S2 make_socket\n"));
 3282     s->ike.src_port = atoi(config[CONFIG_LOCAL_PORT]);
 3283     s->ike.dst_port = ISAKMP_PORT;
 3284     s->ike_fd = make_socket(s, s->ike.src_port, s->ike.dst_port);
 3285     DEBUGTOP(2, printf("S3 setup_tunnel\n"));
 3286     setup_tunnel(s);
 3287 
 3288     do_load_balance = 0;
 3289     do {
 3290         DEBUGTOP(2, printf("S4 do_phase1_am\n"));
 3291         do_phase1_am(config[CONFIG_IPSEC_ID], config[CONFIG_IPSEC_SECRET], s);
 3292         DEBUGTOP(2, printf("S5 do_phase2_xauth\n"));
 3293         /* FIXME: Create and use a generic function in supp.[hc] */
 3294         if (s->ike.auth_algo >= IKE_AUTH_HybridInitRSA)
 3295             do_load_balance = do_phase2_xauth(s);
 3296         DEBUGTOP(2, printf("S6 do_phase2_config\n"));
 3297         if ((opt_vendor == VENDOR_CISCO) && (do_load_balance == 0))
 3298             do_load_balance = do_phase2_config(s);
 3299     } while (do_load_balance);
 3300     DEBUGTOP(2, printf("S7 setup_link (phase 2 + main_loop)\n"));
 3301     DEBUGTOP(2, printf("S7.0 run interface setup script\n"));
 3302     config_tunnel(s);
 3303     do_phase2_qm(s);
 3304     DEBUGTOP(2, printf("S7.9 main loop (receive and transmit ipsec packets)\n"));
 3305     vpnc_doit(s);
 3306 
 3307     /* Tear down phase 2 and 1 tunnels */
 3308     send_delete_ipsec(s);
 3309     send_delete_isakmp(s);
 3310 
 3311     /* Cleanup routing */
 3312     DEBUGTOP(2, printf("S8 close_tunnel\n"));
 3313     close_tunnel(s);
 3314 
 3315     /* Free resources */
 3316     DEBUGTOP(2, printf("S9 cleanup\n"));
 3317     cleanup(s);
 3318 
 3319     return 0;
 3320 }