1 /* $Id: ikev1.c,v 1.34 2008/07/07 09:36:08 fukumoto Exp $ */
   2 
   3 /*
   4  * Copyright (C) 2004 WIDE Project.
   5  * All rights reserved.
   6  * 
   7  * Redistribution and use in source and binary forms, with or without
   8  * modification, are permitted provided that the following conditions
   9  * are met:
  10  * 1. Redistributions of source code must retain the above copyright
  11  *    notice, this list of conditions and the following disclaimer.
  12  * 2. Redistributions in binary form must reproduce the above copyright
  13  *    notice, this list of conditions and the following disclaimer in the
  14  *    documentation and/or other materials provided with the distribution.
  15  * 3. Neither the name of the project nor the names of its contributors
  16  *    may be used to endorse or promote products derived from this software
  17  *    without specific prior written permission.
  18  * 
  19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
  20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
  23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  29  * SUCH DAMAGE.
  30  */
  31 
  32 #include <config.h>
  33 
  34 #include <assert.h>
  35 #include <string.h>
  36 #include <sys/types.h>
  37 #if TIME_WITH_SYS_TIME
  38 #  include <sys/time.h>
  39 #  include <time.h>
  40 #else
  41 #  if HAVE_SYS_TIME_H
  42 #    include <sys/time.h>
  43 #  else
  44 #    include <time.h>
  45 #  endif
  46 #endif
  47 #include <sys/socket.h>
  48 #include <sys/errno.h>
  49 
  50 #include <netinet/in.h>
  51 #include <netdb.h>
  52 
  53 #ifdef HAVE_NETINET6_IPSEC_H
  54 # include <netinet6/ipsec.h>
  55 #else
  56 # ifdef HAVE_NETIPSEC_IPSEC_H
  57 #  include <netipsec/ipsec.h>
  58 # else
  59 #  include <linux/ipsec.h>
  60 # endif
  61 #endif
  62 
  63 #include "racoon.h"
  64 
  65 #include "isakmp.h"
  66 #include "ikev2.h"
  67 #include "keyed_hash.h"
  68 #include "isakmp_impl.h"
  69 #include "ikev1_impl.h"
  70 #include "ipsec_doi.h"
  71 #include "isakmp_ident.h"
  72 /* #include "isakmp_agg.h" */
  73 /* #include "isakmp_base.h" */
  74 #include "isakmp_quick.h"
  75 #include "isakmp_inf.h"
  76 #include "vendorid.h"
  77 #include "pfkey.h"
  78 #ifdef ENABLE_NATT
  79 #  include "ikev1_natt.h"
  80 #endif
  81 
  82 #include "var.h"
  83 
  84 #include "algorithm.h"
  85 #include "dhgroup.h"
  86 #include "oakley.h"             /* for prototypes */
  87 #include "crypto_impl.h"
  88 #include "ike_conf.h"
  89 #include "script.h"
  90 #include "handler.h"
  91 #include "remoteconf.h"
  92 #include "strnames.h"
  93 #include "sockmisc.h"
  94 
  95 #include "debug.h"
  96 
  97 static int nostate1 (struct ph1handle *, rc_vchar_t *);
  98 static int nostate2 (struct ph2handle *, rc_vchar_t *);
  99 
 100 extern caddr_t val2str(const char *, size_t);
 101 
 102 static int ph1_main (struct ph1handle *, rc_vchar_t *);
 103 static int quick_main (struct ph2handle *, rc_vchar_t *);
 104 static int isakmp_ph1begin_r (rc_vchar_t *,
 105                                   struct sockaddr *, struct sockaddr *,
 106                                   uint8_t);
 107 static void isakmp_ph2begin_i (struct ph1handle *, struct ph2handle *);
 108 static int isakmp_ph2begin_r (struct ph1handle *, rc_vchar_t *);
 109 static void isakmp_fail_initiate_ph2(struct ph2handle *);
 110 
 111 static void isakmp_ph1expire_stub(void *);
 112 
 113 static struct isakmpsa * create_isakmpsa(int, int, 
 114                                          struct rc_alglist *,
 115                                          struct rc_alglist *,
 116                                          struct rc_alglist *,
 117                                          struct rc_alglist *,
 118                                          struct rcf_remote *,
 119                                          rc_vchar_t *);
 120 
 121 int getsockmyaddr(struct sockaddr *addr);
 122 
 123 typedef int (*PH1EXCHG) (struct ph1handle *, rc_vchar_t *);
 124 
 125 PH1EXCHG ph1exchange[][2][PHASE1ST_MAX] = {
 126         /* error */
 127         {{NULL}, {NULL},},
 128         /* Identity Protection exchange */
 129         {
 130          {nostate1, ident_i1send, nostate1, ident_i2recv, ident_i2send,
 131           ident_i3recv, ident_i3send, ident_i4recv, ident_i4send, nostate1,},
 132          {nostate1, ident_r1recv, ident_r1send, ident_r2recv, ident_r2send,
 133           ident_r3recv, ident_r3send, nostate1, nostate1, nostate1,},
 134          },
 135         /* Aggressive exchange */
 136         {
 137 #if 0
 138          {nostate1, agg_i1send, nostate1, agg_i2recv, agg_i2send, nostate1,
 139           nostate1, nostate1, nostate1, nostate1,},
 140          {nostate1, agg_r1recv, agg_r1send, agg_r2recv, agg_r2send, nostate1,
 141           nostate1, nostate1, nostate1, nostate1,},
 142 #else
 143          {nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, 
 144           nostate1, nostate1, nostate1, nostate1, },
 145          {nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, 
 146           nostate1, nostate1, nostate1, nostate1, },
 147 #endif
 148          },
 149         /* Base exchange */
 150         {
 151 #if 0
 152          {nostate1, base_i1send, nostate1, base_i2recv, base_i2send,
 153           base_i3recv, base_i3send, nostate1, nostate1, nostate1,},
 154          {nostate1, base_r1recv, base_r1send, base_r2recv, base_r2send,
 155           nostate1, nostate1, nostate1, nostate1, nostate1,},
 156 #else
 157          {nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, 
 158           nostate1, nostate1, nostate1, nostate1, },
 159          {nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, 
 160           nostate1, nostate1, nostate1, nostate1, },
 161 #endif
 162          },
 163 };
 164 
 165 typedef int (*PH2EXCHG) (struct ph2handle *, rc_vchar_t *);
 166 
 167 PH2EXCHG ph2exchange[][2][PHASE2ST_MAX] = {
 168         /* error */
 169         {{NULL}, {NULL},},
 170         /* Quick mode for IKE */
 171         {
 172          {nostate2, nostate2, quick_i1prep, nostate2, quick_i1send,
 173           quick_i2recv, quick_i2send, quick_i3recv, nostate2, nostate2,},
 174          {nostate2, quick_r1recv, quick_r1prep, nostate2, quick_r2send,
 175           quick_r3recv, quick_r3prep, quick_r3send, nostate2, nostate2,},
 176          },
 177 };
 178 
 179 static int etypesw1 (int);
 180 static int etypesw2 (int);
 181 
 182 #if 0
 183 struct dh_def ikev1_dhdef = {
 184         {algtype_dhg_modp768, OAKLEY_ATTR_GRP_DESC_MODP768, &dh_mopd768},
 185         {algtype_dhg_modp1024, OAKLEY_ATTR_GRP_DESC_MODP1024, &dh_modp1024},
 186         /* { algtype_dhg_ec2n155, OAKLEY_ATTR_GRP_DESC_EC2N155, .... }, */
 187         /* { algtype_dhg_ec2n185, OAKLEY_ATTR_GRP_DESC_EC2N185, .... }, */
 188         {algtype_dhg_modp1536, OAKLEY_ATTR_GRP_DESC_MODP1536, &dh_modp1536},
 189         /* ec2n_163_a */
 190         /* ec2n_163_b */
 191         /* ec2n_283_a */
 192         /* ec2n_283_b */
 193         /* ec2n_409_a */
 194         /* ec2n_409_b */
 195         /* ec2n_571_a */
 196         /* ec2n_571_b */
 197         {algtype_dhg_modp2048, OAKLEY_ATTR_GRP_DESC_MODP2048, &dh_modp2048},
 198         {algtype_dhg_modp3072, OAKLEY_ATTR_GRP_DESC_MODP3072, &dh_modp3072},
 199         {algtype_dhg_modp4096, OAKLEY_ATTR_GRP_DESC_MODP4096, &dh_modp4096},
 200         {algtype_dhg_modp6144, OAKLEY_ATTR_GRP_DESC_MODP6144, &dh_modp6144},
 201         {algtype_dhg_modp8192, OAKLEY_ATTR_GRP_DESC_MODP8192, &dh_modp8192},
 202         {0}
 203 };
 204 #endif
 205 
 206 /*
 207  * main processing to handle isakmp payload
 208  */
 209 int
 210 ikev1_main(rc_vchar_t *msg, struct sockaddr *remote, struct sockaddr *local)
 211 {
 212         struct isakmp *isakmp = (struct isakmp *)msg->v;
 213         isakmp_index_t *index = (isakmp_index_t *)isakmp;
 214         uint32_t msgid = isakmp->msgid;
 215         struct ph1handle *iph1;
 216         static isakmp_cookie_t r_ck0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
 217 
 218         ++isakmpstat.v1input;
 219 
 220 #ifdef HAVE_PRINT_ISAKMP_C
 221         isakmp_printpacket(msg, remote, local, 0);
 222 #endif
 223 
 224         /* XXX: check sender whether to be allowed or not to accept */
 225 
 226         /* XXX: I don't know how to check isakmp half connection attack. */
 227 
 228         /* simply reply if the packet was processed. */
 229         if (check_recvdpkt((struct sockaddr *)remote,
 230                            (struct sockaddr *)local, msg)) {
 231                 plog(PLOG_INFO, PLOGLOC, 0,
 232                      "the packet is retransmitted by %s.\n",
 233                      rcs_sa2str((struct sockaddr *)remote));
 234                 /* ++isakmpstat.duplicate; */
 235                 return 0;
 236         }
 237 
 238         /* (RFC2408) 
 239          * Implementations SHOULD never accept packets with a minor
 240          * version number larger than its own, given the major version
 241          * numbers are identical.
 242          */
 243         if (ISAKMP_GETMINORV(isakmp->v) > ISAKMP_MINOR_VERSION) {
 244                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 245                      "unsupported isakmp version %d.%03d.\n",
 246                      ISAKMP_GETMAJORV(isakmp->v), ISAKMP_GETMINORV(isakmp->v));
 247                 /* XXX should send notification */
 248                 ++isakmpstat.unsupported_version;
 249                 return -1;
 250         }
 251 
 252         /* the initiator's cookie must not be zero */
 253         if (memcmp(&isakmp->i_ck, r_ck0, sizeof(isakmp_cookie_t)) == 0) {
 254                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 255                      "malformed cookie received.\n");
 256                 ++isakmpstat.invalid_ike_spi;
 257                 return -1;
 258         }
 259 
 260         /* check the Flags field. */
 261         /* XXX How is the exclusive check, E and A ? */
 262         if (isakmp->flags & ~(ISAKMP_FLAG_E | ISAKMP_FLAG_C | ISAKMP_FLAG_A)) {
 263                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 264                      "invalid flag 0x%02x.\n", isakmp->flags);
 265                 ++isakmpstat.invalid_flag;
 266                 return -1;
 267         }
 268 
 269         /* ignore commit bit. */
 270         if (ISSET(isakmp->flags, ISAKMP_FLAG_C)) {
 271                 if (isakmp->msgid == 0) {
 272                         isakmp_info_send_nx(isakmp, remote, local,
 273                                             ISAKMP_NTYPE_INVALID_FLAGS, NULL);
 274                         plog(PLOG_PROTOERR, PLOGLOC, 0,
 275                              "Commit bit on phase1 forbidden.\n");
 276                         ++isakmpstat.invalid_flag;
 277                         return -1;
 278                 }
 279         }
 280 
 281         iph1 = getph1byindex(index);
 282         if (iph1 != NULL) {
 283                 /* validity check */
 284                 if (memcmp(&isakmp->r_ck, r_ck0, sizeof(isakmp_cookie_t)) == 0
 285                     && iph1->side == INITIATOR) {
 286                         plog(PLOG_DEBUG, PLOGLOC, 0,
 287                              "malformed cookie received or "
 288                              "the initiator's cookies collide.\n");
 289                         ++isakmpstat.invalid_ike_spi;
 290                         return -1;
 291                 }
 292 
 293 #ifdef ENABLE_NATT
 294                 /* Floating ports for NAT-T */
 295                 if (NATT_AVAILABLE(iph1) &&
 296                     !(iph1->natt_flags & NAT_PORTS_CHANGED) &&
 297                     ((rcs_cmpsa(iph1->remote, remote) != 0) ||
 298                     (rcs_cmpsa(iph1->local, local) != 0))) {
 299                         /* prevent memory leak */
 300                         racoon_free(iph1->remote);
 301                         racoon_free(iph1->local);
 302 
 303                         /* copy-in new addresses */
 304                         iph1->remote = rcs_sadup(remote);
 305                         iph1->local = rcs_sadup(local);
 306 
 307                         /*
 308                          * set the flag to prevent further port floating.
 309                          * (FIXME: should we allow it? E.g. when the NAT gw 
 310                          * is rebooted?)
 311                          */
 312                         iph1->natt_flags |= NAT_PORTS_CHANGED | NAT_ADD_NON_ESP_MARKER;
 313                 }
 314 #endif
 315 
 316                 /* must be same addresses in one stream of a phase at least. */
 317                 if (rcs_cmpsa(iph1->remote, remote) != 0) {
 318                         char *saddr_db, *saddr_act;
 319 
 320                         saddr_db = strdup(rcs_sa2str(iph1->remote));
 321                         saddr_act = strdup(rcs_sa2str(remote));
 322 
 323                         plog(PLOG_PROTOWARN, PLOGLOC, 0,
 324                              "remote address mismatched. db=%s, act=%s\n",
 325                              saddr_db, saddr_act);
 326 
 327                         racoon_free(saddr_db);
 328                         racoon_free(saddr_act);
 329                 }
 330                 /*
 331                  * don't check of exchange type here because other type will be
 332                  * with same index, for example, informational exchange.
 333                  */
 334 
 335                 /* XXX more acceptable check */
 336         }
 337 
 338         switch (isakmp->etype) {
 339         case ISAKMP_ETYPE_IDENT:        /* == oakley main mode */
 340         case ISAKMP_ETYPE_AGG:
 341         case ISAKMP_ETYPE_BASE:
 342                 /* phase 1 validity check */
 343                 if (isakmp->msgid != 0) {
 344                         plog(PLOG_PROTOERR, PLOGLOC, 0,
 345                              "message id should be zero in phase1.\n");
 346                         ++isakmpstat.invalid_message_id;
 347                         return -1;
 348                 }
 349 
 350                 /* search for isakmp status record of phase 1 */
 351                 if (iph1 == NULL) {
 352                         /*
 353                          * the packet must be the 1st message from a initiator
 354                          * or the 2nd message from the responder.
 355                          */
 356 
 357                         /* search for phase1 handle by index without r_ck */
 358                         iph1 = getph1byindex0(index);
 359                         if (iph1 == NULL) {
 360                                 /*it must be the 1st message from a initiator. */
 361                                 if (memcmp(&isakmp->r_ck, r_ck0,
 362                                            sizeof(isakmp_cookie_t)) != 0) {
 363 
 364                                         plog(PLOG_DEBUG, PLOGLOC, 0,
 365                                              "malformed cookie received "
 366                                              "or the spi expired.\n");
 367                                         ++isakmpstat.unknown_cookie;
 368                                         return -1;
 369                                 }
 370 
 371                                 /* it must be responder's 1st exchange. */
 372                                 if (isakmp_ph1begin_r(msg, remote, local,
 373                                                       isakmp->etype) < 0)
 374                                         return -1;
 375                                 break;
 376 
 377                          /*NOTREACHED*/}
 378 
 379                         /* it must be the 2nd message from the responder. */
 380                         if (iph1->side != INITIATOR) {
 381                                 plog(PLOG_DEBUG, PLOGLOC, 0,
 382                                      "malformed cookie received. "
 383                                      "it has to be as the initiator.  %s\n",
 384                                      isakmp_pindex(&iph1->index, 0));
 385                                 ++isakmpstat.invalid_message_id;
 386                                 return -1;
 387                         }
 388                 }
 389 
 390                 /*
 391                  * Don't delete phase 1 handler when the exchange type
 392                  * in handler is not equal to packet's one because of no
 393                  * authencication completed.
 394                  */
 395                 if (iph1->etype != isakmp->etype) {
 396                         plog(PLOG_PROTOERR, PLOGLOC, 0,
 397                              "exchange type is mismatched: "
 398                              "db=%s packet=%s, ignore it.\n",
 399                              s_isakmp_etype(iph1->etype),
 400                              s_isakmp_etype(isakmp->etype));
 401                         ++isakmpstat.unexpected_packet;
 402                         return -1;
 403                 }
 404 
 405                 /* call main process of phase 1 */
 406                 if (ph1_main(iph1, msg) < 0) {
 407                         plog(PLOG_PROTOERR, PLOGLOC, 0,
 408                              "phase1 negotiation failed.\n");
 409                         remph1(iph1);
 410                         delph1(iph1);
 411                         return -1;
 412                 }
 413                 break;
 414 
 415 #if 0
 416         case ISAKMP_ETYPE_AUTH:
 417                 plog(PLOG_INFO, PLOGLOC, 0,
 418                      "unsupported exchange %d received.\n", isakmp->etype);
 419                 ++isakmpstat.unsupported_exchange_type;
 420                 break;
 421 #endif
 422 
 423         case ISAKMP_ETYPE_INFO:
 424         case ISAKMP_ETYPE_ACKINFO:
 425                 /*
 426                  * iph1 must be present for Information message.
 427                  * if iph1 is null then trying to get the phase1 status
 428                  * as the packet from responder againt initiator's 1st
 429                  * exchange in phase 1.
 430                  * NOTE: We think such informational exchange should be ignored.
 431                  */
 432                 if (iph1 == NULL) {
 433                         iph1 = getph1byindex0(index);
 434                         if (iph1 == NULL) {
 435                                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 436                                      "unknown Informational "
 437                                      "exchange received.\n");
 438                                 /* ++isakmpstat.infoexch_unknown_peer; */
 439                                 return -1;
 440                         }
 441                         if (rcs_cmpsa(iph1->remote, remote) != 0) {
 442                                 plog(PLOG_PROTOWARN, PLOGLOC, 0,
 443                                      "remote address mismatched. "
 444                                      "db=%s\n", rcs_sa2str(iph1->remote));
 445                                 /* ++isakmpstat.infoexch_unknown_remote_addr; */
 446                         }
 447                 }
 448 
 449                 if (isakmp_info_recv(iph1, msg) < 0)
 450                         return -1;
 451                 break;
 452 
 453         case ISAKMP_ETYPE_QUICK:
 454                 {
 455                         struct ph2handle *iph2;
 456 
 457                         if (iph1 == NULL) {
 458                                 isakmp_info_send_nx(isakmp, remote, local,
 459                                                     ISAKMP_NTYPE_INVALID_COOKIE,
 460                                                     NULL);
 461                                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 462                                      "can't start the quick mode, "
 463                                      "there is no ISAKMP-SA, %s\n",
 464                                      isakmp_pindex((isakmp_index_t *)&isakmp->
 465                                                    i_ck, isakmp->msgid));
 466                                 ++isakmpstat.invalid_ike_spi;
 467                                 return -1;
 468                         }
 469 
 470                         /* check status of phase 1 whether negotiated or not. */
 471                         if (iph1->status != PHASE1ST_ESTABLISHED) {
 472                                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 473                                      "can't start the quick mode, "
 474                                      "there is no valid ISAKMP-SA, %s\n",
 475                                      isakmp_pindex(&iph1->index, iph1->msgid));
 476                                 ++isakmpstat.premature;
 477                                 return -1;
 478                         }
 479 
 480                         /* search isakmp phase 2 stauts record. */
 481                         iph2 = getph2bymsgid(iph1, msgid);
 482                         if (iph2 == NULL) {
 483                                 /* it must be new negotiation as responder */
 484                                 if (isakmp_ph2begin_r(iph1, msg) < 0)
 485                                         return -1;
 486                                 return 0;
 487                          /*NOTREACHED*/}
 488 
 489                         /* commit bit. */
 490                         /* XXX
 491                          * we keep to set commit bit during negotiation.
 492                          * When SA is configured, bit will be reset.
 493                          * XXX
 494                          * don't initiate commit bit.  should be fixed in the future.
 495                          */
 496                         if (ISSET(isakmp->flags, ISAKMP_FLAG_C))
 497                                 iph2->flags |= ISAKMP_FLAG_C;
 498 
 499                         /* call main process of quick mode */
 500                         if (quick_main(iph2, msg) < 0) {
 501                                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 502                                      "phase2 negotiation failed.\n");
 503                                 unbindph12(iph2);
 504                                 remph2(iph2);
 505                                 delph2(iph2);
 506                                 return -1;
 507                         }
 508                 }
 509                 break;
 510 
 511         case ISAKMP_ETYPE_NEWGRP:
 512                 if (iph1 == NULL) {
 513                         plog(PLOG_PROTOERR, PLOGLOC, 0,
 514                              "Unknown new group mode exchange, "
 515                              "there is no ISAKMP-SA.\n");
 516                         ++isakmpstat.unknown_cookie;
 517                         return -1;
 518                 }
 519 #ifdef notyet
 520                 isakmp_newgroup_r(iph1, msg);
 521                 break;
 522 #else
 523                 /*FALLTHROUGH*/
 524 #endif
 525         case ISAKMP_ETYPE_NONE:
 526         default:
 527                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 528                      "Invalid exchange type %d from %s.\n",
 529                      isakmp->etype, rcs_sa2str(remote));
 530                 /* ++isakmpstat.unsupported_exchange_type; */
 531                 return -1;
 532         }
 533 
 534         return 0;
 535 }
 536 
 537 
 538 /* 
 539  * process ACQUIRE for IKEv1
 540  */
 541 void
 542 ikev1_initiate(struct isakmp_acquire_request *req, 
 543                struct rcf_policy *policy,
 544                struct rcf_selector *selector,
 545                struct rcf_remote *rm_info)
 546 {
 547         struct ph2handle *iph2;
 548         struct sockaddr *peer = 0;
 549         extern struct sadb_response_method ikev1_sadb_callback;
 550         extern struct ph2handle *getph2byselector();
 551         extern int set_proposal_from_policy();
 552 
 553         TRACE((PLOGLOC, "processing acquire for IKEv1\n"));
 554         if (ikev1_passive(rm_info) == RCT_BOOL_ON) {
 555                 isakmp_log(0, req->src, req->dst, 0, PLOG_INFO, PLOGLOC,  /* ??? */
 556                            "remote %s passive mode specified for IKEv1, dropping acquire request\n",
 557                            (rm_info->rm_index ?
 558                             rc_vmem2str(rm_info->rm_index) : "(default)"));
 559                 goto fail;
 560         }
 561 
 562         if (rm_info->ikev1->peers_ipaddr) {
 563                 if (rm_info->ikev1->peers_ipaddr->type != RCT_ADDR_INET) {
 564                         isakmp_log(0, req->src, req->dst, 0,
 565                                    PLOG_INTERR, PLOGLOC,
 566                                    "unsupported peers_ipaddr format in policy %.*s\n",
 567                                    (int)policy->pl_index->l,
 568                                    policy->pl_index->v);
 569                         goto fail;
 570                 }
 571                 peer = rcs_sadup(rm_info->ikev1->peers_ipaddr->a.ipaddr);
 572         } else {
 573                 peer = rcs_sadup(req->dst);
 574                 switch (SOCKADDR_FAMILY(peer)) {
 575                 case AF_INET:
 576                         ((struct sockaddr_in *)peer)->sin_port =
 577                                 htons(isakmp_port);
 578                         break;
 579 #ifdef INET6
 580                 case AF_INET6:
 581                         ((struct sockaddr_in6 *)peer)->sin6_port =
 582                                 htons(isakmp_port);
 583                         break;
 584 #endif
 585                 default:
 586                         isakmp_log(0, req->src, req->dst, 0,
 587                                    PLOG_INTERR, PLOGLOC,
 588                                    "unsupported address family (%d) for peer address\n",
 589                                    SOCKADDR_FAMILY(peer));
 590                         goto fail;
 591                 }
 592         }
 593 
 594         iph2 = getph2byselector(req->src, req->dst, selector);
 595         if (iph2) {
 596                 if (iph2->status < PHASE2ST_ESTABLISHED) {
 597                         isakmp_log(0, req->src, req->dst, 0, PLOG_DEBUG, PLOGLOC,
 598                                    "ignoring acquire request since there's ph2 already\n");
 599                         goto fail;
 600                 }
 601                 if (iph2->status == PHASE2ST_EXPIRED)
 602                         iph2 = 0;
 603         }
 604 
 605         iph2 = newph2();
 606         if (!iph2) {
 607                 plog(PLOG_INTERR, PLOGLOC, 0,
 608                      "failed to allocate phase 2 entry\n");
 609                 goto fail;
 610         }
 611         iph2->side = INITIATOR;
 612         iph2->selector = selector;
 613         selector = 0;
 614         iph2->satype = RCT_SATYPE_ESP; /* ??? */
 615         iph2->status = PHASE2ST_STATUS2;
 616 
 617         iph2->dst = rcs_sadup(req->dst);
 618         if (req->src2)
 619                 iph2->src = rcs_sadup(req->src2);
 620         else
 621                 iph2->src = rcs_sadup(req->src);
 622         if (!iph2->dst || !iph2->src) {
 623                 delph2(iph2);
 624                 goto fail_nomem;
 625         }
 626         iph2->seq = req->request_msg_seq;
 627 
 628         sadb_request_initialize(&iph2->sadb_request,
 629                                 req->callback_method,
 630                                 &ikev1_sadb_callback,
 631                                 req->request_msg_seq,
 632                                 iph2);
 633 
 634         if (set_proposal_from_policy(iph2, rm_info, policy)) {
 635                 plog(PLOG_INTERR, PLOGLOC, 0,
 636                      "failed to create saprop\n");
 637                 delph2(iph2);
 638                 goto fail;
 639         }
 640 
 641         TRACE((PLOGLOC, "new acquire ph2 %p\n", iph2));
 642 
 643         insph2(iph2);
 644 
 645         ikev1_post_acquire(rm_info, iph2);
 646 
 647  done:
 648         if (selector)
 649                 rcf_free_selector(selector);
 650         if (peer)
 651                 racoon_free(peer);
 652         return;
 653 
 654  fail_nomem:
 655         isakmp_log(0, req->src, req->dst, 0,
 656                    PLOG_INTERR, PLOGLOC, "failed allocating memory\n");
 657  fail:
 658         goto done;
 659 }
 660 
 661 
 662 /*
 663  * main function of phase 1.
 664  */
 665 static int
 666 ph1_main(iph1, msg)
 667         struct ph1handle *iph1;
 668         rc_vchar_t *msg;
 669 {
 670         int error;
 671 #ifdef ENABLE_STATS
 672         struct timeval start, end;
 673 #endif
 674 
 675         /* ignore a packet */
 676         if (iph1->status == PHASE1ST_ESTABLISHED) {
 677                 /* ++isakmpstat.ignore; */
 678                 return 0;
 679         }
 680 #ifdef ENABLE_STATS
 681         gettimeofday(&start, NULL);
 682 #endif
 683         /* receive */
 684         if (ph1exchange[etypesw1(iph1->etype)]
 685             [iph1->side]
 686             [iph1->status] == NULL) {
 687                 plog(PLOG_INTERR, PLOGLOC, 0,
 688                      "why isn't the function defined.\n");
 689                 /* ++isakmpstat.ignore; */
 690                 return -1;
 691         }
 692         error = (ph1exchange[etypesw1(iph1->etype)]
 693                  [iph1->side]
 694                  [iph1->status]) (iph1, msg);
 695         if (error != 0) {
 696 #if 0
 697                 /* XXX
 698                  * When an invalid packet is received on phase1, it should
 699                  * be selected to process this packet.  That is to respond
 700                  * with a notify and delete phase 1 handler, OR not to respond
 701                  * and keep phase 1 handler.
 702                  */
 703                 plog(PLOG_INTERR, PLOGLOC, 0,
 704                      "failed to pre-process packet.\n");
 705                 return -1;
 706 #else
 707                 /* ignore the error and keep phase 1 handler */
 708                 return 0;
 709 #endif
 710         }
 711 
 712         /* free resend buffer */
 713         if (iph1->sendbuf == NULL) {
 714                 plog(PLOG_INTERR, PLOGLOC, 0, "no buffer found as sendbuf\n");
 715                 return -1;
 716         }
 717         VPTRINIT(iph1->sendbuf);
 718 
 719         /* turn off schedule */
 720         if (iph1->scr)
 721                 SCHED_KILL(iph1->scr);
 722 
 723         /* send */
 724         plog(PLOG_DEBUG, PLOGLOC, 0, "===\n");
 725         if ((ph1exchange[etypesw1(iph1->etype)]
 726              [iph1->side]
 727              [iph1->status]) (iph1, msg) != 0) {
 728                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 729                      "failed to process packet.\n");
 730                 return -1;
 731         }
 732 #ifdef ENABLE_STATS
 733         gettimeofday(&end, NULL);
 734         syslog(LOG_NOTICE, "%s(%s): %8.6f",
 735                "phase1", s_isakmp_state(iph1->etype, iph1->side, iph1->status),
 736                timedelta(&start, &end));
 737 #endif
 738         if (iph1->status == PHASE1ST_ESTABLISHED) {
 739                 /* ++isakmpstat.ph1established; */
 740 #ifdef ENABLE_STATS
 741                 gettimeofday(&iph1->end, NULL);
 742                 syslog(LOG_NOTICE, "%s(%s): %8.6f",
 743                        "phase1", s_isakmp_etype(iph1->etype),
 744                        timedelta(&iph1->start, &iph1->end));
 745 #endif
 746 
 747                 /* save created date. */
 748                 (void)time(&iph1->created);
 749 
 750                 /* add to the schedule to expire, and seve back pointer. */
 751                 iph1->sce = sched_new(iph1->approval->lifetime,
 752                                       isakmp_ph1expire_stub, iph1);
 753 
 754                 /* INITIAL-CONTACT processing */
 755                 /* don't anything if local test mode. */
 756                 if (/*!opt_local */ 1
 757                     && iph1->rmconf->ikev1
 758                     && iph1->rmconf->ikev1->initial_contact
 759                     && !getcontacted(iph1->remote)) {
 760                         /*++isakmpstat.initial_contact; */
 761                         /* insert a node into contacted list. */
 762                         if (inscontacted(iph1->remote) == -1) {
 763                                 plog(PLOG_INTERR, PLOGLOC, 0,
 764                                      "failed to add contacted list.\n");
 765                                 /* ignore */
 766                         } else {
 767                                 /* send INITIAL-CONTACT */
 768                                 isakmp_info_send_n1(iph1,
 769                                                     ISAKMP_NTYPE_INITIAL_CONTACT,
 770                                                     NULL);
 771                         }
 772                 }
 773 
 774                 log_ph1established(iph1);
 775                 ikev1_script_hook(iph1, SCRIPT_PHASE1_UP);
 776                 plog(PLOG_DEBUG, PLOGLOC, NULL, "===\n");
 777         }
 778 
 779         return 0;
 780 }
 781 
 782 /*
 783  * main function of quick mode.
 784  */
 785 static int
 786 quick_main(struct ph2handle *iph2, rc_vchar_t *msg)
 787 {
 788         struct isakmp *isakmp = (struct isakmp *)msg->v;
 789         int error;
 790 #ifdef ENABLE_STATS
 791         struct timeval start, end;
 792 #endif
 793 
 794         /* ignore a packet */
 795         if (iph2->status == PHASE2ST_ESTABLISHED
 796             || iph2->status == PHASE2ST_GETSPISENT)
 797                 return 0;
 798 
 799 #ifdef ENABLE_STATS
 800         gettimeofday(&start, NULL);
 801 #endif
 802 
 803         /* receive */
 804         if (ph2exchange[etypesw2(isakmp->etype)]
 805             [iph2->side]
 806             [iph2->status] == NULL) {
 807                 plog(PLOG_INTERR, PLOGLOC, 0,
 808                      "why isn't the function defined.\n");
 809                 return -1;
 810         }
 811         error = (ph2exchange[etypesw2(isakmp->etype)]
 812                  [iph2->side]
 813                  [iph2->status]) (iph2, msg);
 814         if (error != 0) {
 815                 plog(PLOG_INTERR, PLOGLOC, 0,
 816                      "failed to pre-process packet.\n");
 817                 if (error == ISAKMP_INTERNAL_ERROR)
 818                         return 0;
 819                 isakmp_info_send_n1(iph2->ph1, error, NULL);
 820                 return -1;
 821         }
 822 
 823         /* when using commit bit, status will be reached here. */
 824         if (iph2->status == PHASE2ST_ADDSA)
 825                 return 0;
 826 
 827         /* free resend buffer */
 828         if (iph2->sendbuf == NULL) {
 829                 plog(PLOG_INTERR, PLOGLOC, NULL, "no buffer found as sendbuf\n");
 830                 return -1;
 831         }
 832         VPTRINIT(iph2->sendbuf);
 833 
 834         /* turn off schedule */
 835         if (iph2->scr)
 836                 SCHED_KILL(iph2->scr);
 837 
 838         /* send */
 839         plog(PLOG_DEBUG, PLOGLOC, NULL, "===\n");
 840         if ((ph2exchange[etypesw2(isakmp->etype)]
 841              [iph2->side]
 842              [iph2->status]) (iph2, msg) != 0) {
 843                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 844                      "failed to process packet.\n");
 845                 return -1;
 846         }
 847 #ifdef ENABLE_STATS
 848         gettimeofday(&end, NULL);
 849         syslog(LOG_NOTICE, "%s(%s): %8.6f",
 850                "phase2",
 851                s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
 852                timedelta(&start, &end));
 853 #endif
 854 
 855         return 0;
 856 }
 857 
 858 /* new negotiation of phase 1 for initiator */
 859 int
 860 isakmp_ph1begin_i(struct rcf_remote *rmconf, 
 861                   struct sockaddr *remote, struct sockaddr *local)
 862 {
 863         struct ph1handle *iph1;
 864 #ifdef ENABLE_STATS
 865         struct timeval start, end;
 866 #endif
 867 
 868         /* get new entry to isakmp status table. */
 869         iph1 = newph1();
 870         if (iph1 == NULL)
 871                 return -1;
 872 
 873         iph1->status = PHASE1ST_START;
 874         iph1->rmconf = rmconf;
 875         iph1->side = INITIATOR;
 876         iph1->version = ISAKMP_VERSION_NUMBER;
 877         iph1->msgid = 0;
 878         iph1->flags = 0;
 879         iph1->ph2cnt = 0;
 880 #ifdef HAVE_GSSAPI
 881         iph1->gssapi_state = NULL;
 882 #endif
 883         iph1->approval = NULL;
 884         iph1->proposal = ikev1_conf_to_isakmpsa(rmconf);
 885 
 886         /* XXX copy remote address */
 887         if (copy_ph1addresses(iph1, rmconf, remote, local) < 0)
 888                 return -1;
 889 
 890         (void)insph1(iph1);
 891 
 892         /* start phase 1 exchange */
 893         iph1->etype = ikev1_conf_exmode_to_isakmp(rmconf);
 894 
 895         plog(PLOG_DEBUG, PLOGLOC, NULL, "===\n");
 896         {
 897                 char *a;
 898 
 899                 a = strdup(rcs_sa2str(iph1->local));
 900                 plog(PLOG_INFO, PLOGLOC, NULL,
 901                      "initiate new phase 1 negotiation: %s<=>%s\n",
 902                      a, rcs_sa2str(iph1->remote));
 903                 racoon_free(a);
 904         }
 905         plog(PLOG_INFO, PLOGLOC, NULL,
 906              "begin %s mode.\n", s_isakmp_etype(iph1->etype));
 907 
 908 #ifdef ENABLE_STATS
 909         gettimeofday(&iph1->start, NULL);
 910         gettimeofday(&start, NULL);
 911 #endif
 912         /* start exchange */
 913         if ((ph1exchange[etypesw1(iph1->etype)]
 914              [iph1->side]
 915              [iph1->status]) (iph1, NULL) != 0) {
 916                 /* failed to start phase 1 negotiation */
 917                 remph1(iph1);
 918                 delph1(iph1);
 919 
 920                 return -1;
 921         }
 922 #ifdef ENABLE_STATS
 923         gettimeofday(&end, NULL);
 924         syslog(LOG_NOTICE, "%s(%s): %8.6f",
 925                "phase1",
 926                s_isakmp_state(iph1->etype, iph1->side, iph1->status),
 927                timedelta(&start, &end));
 928 #endif
 929 
 930         return 0;
 931 }
 932 
 933 /* new negotiation of phase 1 for responder */
 934 static int
 935 isakmp_ph1begin_r(rc_vchar_t *msg, struct sockaddr *remote,
 936                   struct sockaddr *local, uint8_t etype)
 937 {
 938         struct isakmp *isakmp = (struct isakmp *)msg->v;
 939         struct rcf_remote *rmconf;
 940         struct ph1handle *iph1;
 941         /* struct etypes *etypeok; */
 942 #ifdef ENABLE_STATS
 943         struct timeval start, end;
 944 #endif
 945 
 946         /* look for my configuration */
 947         rmconf = getrmconf(remote);
 948         if (rmconf == NULL) {
 949                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 950                      "couldn't find " "configuration.\n");
 951                 return -1;
 952         }
 953         if (rmconf->ikev1 == NULL) {
 954                 plog(PLOG_PROTOERR, PLOGLOC, 0, 
 955                      "received IKEv1 request but no IKEv1 configuration for peer %s\n",
 956                      rc_vmem2str(rmconf->rm_index));
 957                 return -1;
 958         }
 959 
 960         /* check to be acceptable exchange type */
 961         if (etype != ikev1_conf_exmode_to_isakmp(rmconf)) {
 962                 plog(PLOG_PROTOERR, PLOGLOC, 0,
 963                      "not acceptable %s mode\n", s_isakmp_etype(etype));
 964                 return -1;
 965         }
 966 
 967         /* get new entry to isakmp status table. */
 968         iph1 = newph1();
 969         if (iph1 == NULL)
 970                 return -1;
 971 
 972         memcpy(&iph1->index.i_ck, &isakmp->i_ck, sizeof(iph1->index.i_ck));
 973         iph1->status = PHASE1ST_START;
 974         iph1->rmconf = rmconf;
 975         iph1->flags = 0;
 976         iph1->side = RESPONDER;
 977         iph1->etype = etype;
 978         iph1->version = isakmp->v;
 979         iph1->msgid = 0;
 980 #ifdef HAVE_GSSAPI
 981         iph1->gssapi_state = NULL;
 982 #endif
 983         iph1->approval = NULL;
 984         iph1->proposal = ikev1_conf_to_isakmpsa(rmconf);
 985 
 986         /* copy remote address */
 987         if (copy_ph1addresses(iph1, rmconf, remote, local) < 0)
 988                 return -1;
 989 
 990         (void)insph1(iph1);
 991 
 992         plog(PLOG_DEBUG, PLOGLOC, NULL, "===\n");
 993         {
 994                 char *a;
 995 
 996                 a = strdup(rcs_sa2str(iph1->local));
 997                 plog(PLOG_INFO, PLOGLOC, NULL,
 998                      "respond new phase 1 negotiation: %s<=>%s\n",
 999                      a, rcs_sa2str(iph1->remote));
1000                 racoon_free(a);
1001         }
1002         plog(PLOG_INFO, PLOGLOC, NULL,
1003              "begin %s mode.\n", s_isakmp_etype(etype));
1004 
1005 #ifdef ENABLE_STATS
1006         gettimeofday(&iph1->start, NULL);
1007         gettimeofday(&start, NULL);
1008 #endif
1009         /* start exchange */
1010         if ((ph1exchange[etypesw1(iph1->etype)]
1011              [iph1->side]
1012              [iph1->status]) (iph1, msg) < 0
1013             || (ph1exchange[etypesw1(iph1->etype)]
1014                 [iph1->side]
1015                 [iph1->status]) (iph1, msg) < 0) {
1016                 plog(PLOG_PROTOERR, PLOGLOC, 0,
1017                      "failed to process packet.\n");
1018                 remph1(iph1);
1019                 delph1(iph1);
1020                 return -1;
1021         }
1022 #ifdef ENABLE_STATS
1023         gettimeofday(&end, NULL);
1024         syslog(LOG_NOTICE, "%s(%s): %8.6f",
1025                "phase1",
1026                s_isakmp_state(iph1->etype, iph1->side, iph1->status),
1027                timedelta(&start, &end));
1028 #endif
1029 
1030         return 0;
1031 }
1032 
1033 
1034 
1035 /*
1036  * make strings containing i_cookie + r_cookie + msgid
1037  */
1038 const char *
1039 isakmp_pindex(const isakmp_index_t *index, const uint32_t msgid)
1040 {
1041         static char buf[64];
1042         const unsigned char *p;
1043         int i, j;
1044 
1045         memset(buf, 0, sizeof(buf));
1046 
1047         /* copy index */
1048         p = (const unsigned char *)index;
1049         for (j = 0, i = 0; (size_t)i < sizeof(isakmp_index_t); i++) {
1050                 snprintf((char *)&buf[j], sizeof(buf) - j, "%02x", p[i]);
1051                 j += 2;
1052                 switch (i) {
1053                 case 7:
1054                         buf[j++] = ':';
1055                 }
1056         }
1057 
1058         if (msgid == 0)
1059                 return buf;
1060 
1061         /* copy msgid */
1062         snprintf((char *)&buf[j], sizeof(buf) - j, ":%08x", ntohl(msgid));
1063 
1064         return buf;
1065 }
1066 
1067 /*
1068  * receive GETSPI from kernel.
1069  */
1070 int
1071 isakmp_post_getspi(struct ph2handle *iph2)
1072 {
1073 #ifdef ENABLE_STATS
1074         struct timeval start, end;
1075 #endif
1076 
1077         /* don't process it because there is no suitable phase1-sa. */
1078         if (iph2->ph1->status == PHASE1ST_EXPIRED) {
1079                 plog(PLOG_INTERR, PLOGLOC, 0,
1080                         "the negotiation is stopped, "
1081                         "because there is no suitable ISAKMP-SA.\n");
1082                 return -1;
1083         }
1084 
1085 #ifdef ENABLE_STATS
1086         gettimeofday(&start, NULL);
1087 #endif
1088         if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1089                         [iph2->side]
1090                         [iph2->status])(iph2, NULL) != 0)
1091                 return -1;
1092 #ifdef ENABLE_STATS
1093         gettimeofday(&end, NULL);
1094         syslog(LOG_NOTICE, "%s(%s): %8.6f",
1095                 "phase2",
1096                 s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
1097                 timedelta(&start, &end));
1098 #endif
1099 
1100         return 0;
1101 }
1102 
1103 /* new negotiation of phase 2 for initiator */
1104 static void
1105 isakmp_ph2begin_i(struct ph1handle *iph1, struct ph2handle *iph2)
1106 {
1107         /* found ISAKMP-SA. */
1108         plog(PLOG_DEBUG, PLOGLOC, NULL, "===\n");
1109         plog(PLOG_DEBUG, PLOGLOC, NULL, "begin QUICK mode.\n");
1110         {
1111                 char *a;
1112                 a = strdup(rcs_sa2str(iph2->src));
1113                 plog(PLOG_INFO, PLOGLOC, NULL,
1114                      "initiate new phase 2 negotiation: %s<=>%s\n",
1115                      a, rcs_sa2str(iph2->dst));
1116                 racoon_free(a);
1117         }
1118 
1119 #ifdef ENABLE_STATS
1120         gettimeofday(&iph2->start, NULL);
1121 #endif
1122         /* found isakmp-sa */
1123         bindph12(iph1, iph2);
1124         iph2->status = PHASE2ST_STATUS2;
1125 
1126         if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1127              [iph2->side]
1128              [iph2->status]) (iph2, NULL) < 0) {
1129                 /* release ipsecsa handler due to internal error. */
1130                 plog(PLOG_INTERR, PLOGLOC, 0,
1131                      "failed to initiate phase 2 negotiation for %s\n",
1132                      rcs_sa2str_wop(iph2->dst));
1133                 isakmp_fail_initiate_ph2(iph2);
1134                 return;
1135         }
1136         return;
1137 }
1138 
1139 /* new negotiation of phase 2 for responder */
1140 static int
1141 isakmp_ph2begin_r(struct ph1handle *iph1, rc_vchar_t *msg)
1142 {
1143         struct isakmp *isakmp = (struct isakmp *)msg->v;
1144         struct ph2handle *iph2 = 0;
1145         int error;
1146 #ifdef ENABLE_STATS
1147         struct timeval start, end;
1148 #endif
1149         extern struct sadb_response_method ikev1_sadb_callback;
1150 
1151         iph2 = newph2();
1152         if (iph2 == NULL) {
1153                 plog(PLOG_INTERR, PLOGLOC, NULL,
1154                      "failed to allocate phase2 entry.\n");
1155                 return -1;
1156         }
1157 
1158         iph2->ph1 = iph1;
1159         iph2->side = RESPONDER;
1160         iph2->status = PHASE2ST_START;
1161         iph2->flags = isakmp->flags;
1162         iph2->msgid = isakmp->msgid;
1163         iph2->seq = sadb_new_seq(); /* pk_getseq(); */
1164         iph2->ivm = oakley_newiv2(iph1, iph2->msgid);
1165         if (iph2->ivm == NULL) {
1166                 delph2(iph2);
1167                 return -1;
1168         }
1169 
1170         iph2->dst = rcs_sadup(iph1->remote);      /* XXX should be considered */
1171         if (iph2->dst == NULL) {
1172                 delph2(iph2);
1173                 return -1;
1174         }
1175 
1176         iph2->src = rcs_sadup(iph1->local);       /* XXX should be considered */
1177         if (iph2->src == NULL) {
1178                 delph2(iph2);
1179                 return -1;
1180         }
1181 
1182         iph2->selector = 0;
1183 
1184         sadb_request_initialize(&iph2->sadb_request,
1185                                 debug_pfkey ? &sadb_debug_method : &sadb_responder_request_method,
1186                                 &ikev1_sadb_callback,
1187                                 iph2->seq,
1188                                 iph2);
1189 
1190         /* add new entry to isakmp status table */
1191         insph2(iph2);
1192         bindph12(iph1, iph2);
1193 
1194         plog(PLOG_DEBUG, PLOGLOC, NULL, "===\n");
1195         {
1196                 char *a;
1197 
1198                 a = strdup(rcs_sa2str(iph2->src));
1199                 plog(PLOG_INFO, PLOGLOC, NULL,
1200                      "respond new phase 2 negotiation: %s<=>%s\n",
1201                      a, rcs_sa2str(iph2->dst));
1202                 racoon_free(a);
1203         }
1204 
1205 #ifdef ENABLE_STATS
1206         gettimeofday(&start, NULL);
1207 #endif
1208 
1209         error = (ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1210                  [iph2->side]
1211                  [iph2->status]) (iph2, msg);
1212         if (error != 0) {
1213                 plog(PLOG_INTERR, PLOGLOC, 0,
1214                      "failed to pre-process packet.\n");
1215                 if (error != ISAKMP_INTERNAL_ERROR)
1216                         isakmp_info_send_n1(iph2->ph1, error, NULL);
1217                 /*
1218                  * release handler because it's wrong that ph2handle is kept
1219                  * after failed to check message for responder's.
1220                  */
1221                 unbindph12(iph2);
1222                 remph2(iph2);
1223                 delph2(iph2);
1224                 return -1;
1225         }
1226 
1227         /* send */
1228         plog(PLOG_DEBUG, PLOGLOC, NULL, "===\n");
1229         if ((ph2exchange[etypesw2(isakmp->etype)]
1230              [iph2->side]
1231              [iph2->status]) (iph2, msg) < 0) {
1232                 plog(PLOG_PROTOERR, PLOGLOC, 0,
1233                      "failed to process packet.\n");
1234                 /* don't release handler */
1235                 return -1;
1236         }
1237 #ifdef ENABLE_STATS
1238         gettimeofday(&end, NULL);
1239         syslog(LOG_NOTICE, "%s(%s): %8.6f",
1240                "phase2",
1241                s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
1242                timedelta(&start, &end));
1243 #endif
1244 
1245         return 0;
1246 }
1247 
1248 /* called from scheduler */
1249 static void
1250 isakmp_ph1resend_stub(void *p)
1251 {
1252         (void)isakmp_ph1resend((struct ph1handle *)p);
1253 }
1254 
1255 int
1256 isakmp_ph1resend(struct ph1handle *iph1)
1257 {
1258         if (iph1->retry_counter < 0) {
1259                 plog(PLOG_PROTOERR, PLOGLOC, NULL,
1260                      "phase1 negotiation failed due to time up (index %s).\n",
1261                      isakmp_pindex(&iph1->index, iph1->msgid));
1262 
1263                 remph1(iph1);
1264                 delph1(iph1);
1265                 return -1;
1266         }
1267 
1268         if (isakmp_send(iph1, iph1->sendbuf) < 0)
1269                 return -1;
1270 
1271         plog(PLOG_DEBUG, PLOGLOC, NULL,
1272              "resend phase1 packet %s\n",
1273              isakmp_pindex(&iph1->index, iph1->msgid));
1274 
1275         iph1->retry_counter--;
1276 
1277         iph1->scr = sched_new(ikev1_interval_to_send(iph1->rmconf),
1278                               isakmp_ph1resend_stub, iph1);
1279 
1280         return 0;
1281 }
1282 
1283 /* called from scheduler */
1284 static void
1285 isakmp_ph2resend_stub(void *p)
1286 {
1287 
1288         (void)isakmp_ph2resend((struct ph2handle *)p);
1289 }
1290 
1291 int
1292 isakmp_ph2resend(struct ph2handle *iph2)
1293 {
1294         if (iph2->retry_counter < 0) {
1295                 plog(PLOG_PROTOERR, PLOGLOC, NULL,
1296                      "phase2 negotiation failed due to time up. %s\n",
1297                      isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1298                 unbindph12(iph2);
1299                 remph2(iph2);
1300                 delph2(iph2);
1301                 return -1;
1302         }
1303 
1304         if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0)
1305                 return -1;
1306 
1307         plog(PLOG_DEBUG, PLOGLOC, NULL,
1308              "resend phase2 packet %s\n",
1309              isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1310 
1311         iph2->retry_counter--;
1312 
1313         iph2->scr = sched_new(ikev1_interval_to_send(iph2->ph1->rmconf),
1314                               isakmp_ph2resend_stub, iph2);
1315 
1316         return 0;
1317 }
1318 
1319 /* called from scheduler */
1320 static void
1321 isakmp_ph1expire_stub(void *p)
1322 {
1323 
1324         isakmp_ph1expire((struct ph1handle *)p);
1325 }
1326 
1327 void
1328 isakmp_ph1expire(struct ph1handle *iph1)
1329 {
1330         char *src, *dst;
1331 
1332         src = strdup(rcs_sa2str(iph1->local));
1333         dst = strdup(rcs_sa2str(iph1->remote));
1334         plog(PLOG_INFO, PLOGLOC, NULL,
1335              "ISAKMP-SA expired %s-%s spi:%s\n",
1336              src, dst, isakmp_pindex(&iph1->index, 0));
1337         racoon_free(src);
1338         racoon_free(dst);
1339 
1340         SCHED_KILL(iph1->sce);
1341 
1342         iph1->status = PHASE1ST_EXPIRED;
1343 
1344         /*
1345          * the phase1 deletion is postponed until there is no phase2.
1346          */
1347         if (LIST_FIRST(&iph1->ph2tree) != NULL) {
1348                 iph1->sce = sched_new(1, isakmp_ph1expire_stub, iph1);
1349                 return;
1350         }
1351 
1352         iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
1353 }
1354 
1355 /* called from scheduler */
1356 void
1357 isakmp_ph1delete_stub(void *p)
1358 {
1359 
1360         isakmp_ph1delete((struct ph1handle *)p);
1361 }
1362 
1363 void
1364 isakmp_ph1delete(struct ph1handle *iph1)
1365 {
1366         char *src, *dst;
1367 
1368         SCHED_KILL(iph1->sce);
1369 
1370         if (LIST_FIRST(&iph1->ph2tree) != NULL) {
1371                 iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
1372                 return;
1373         }
1374 
1375         /* don't re-negosiation when the phase 1 SA expires. */
1376 
1377         src = strdup(rcs_sa2str(iph1->local));
1378         dst = strdup(rcs_sa2str(iph1->remote));
1379         plog(PLOG_INFO, PLOGLOC, NULL,
1380              "ISAKMP-SA deleted %s-%s spi:%s\n",
1381              src, dst, isakmp_pindex(&iph1->index, 0));
1382         racoon_free(src);
1383         racoon_free(dst);
1384 
1385         remph1(iph1);
1386         delph1(iph1);
1387 
1388         return;
1389 }
1390 
1391 void
1392 isakmp_ph2expire(struct ph2handle *iph2)
1393 {
1394         char *src, *dst;
1395 
1396         SCHED_KILL(iph2->sce);
1397 
1398         src = strdup(rcs_sa2str_wop(iph2->src));
1399         dst = strdup(rcs_sa2str_wop(iph2->dst));
1400         plog(PLOG_INFO, PLOGLOC, NULL, "phase2 sa expired %s-%s\n", src, dst);
1401         racoon_free(src);
1402         racoon_free(dst);
1403 
1404         iph2->status = PHASE2ST_EXPIRED;
1405 
1406         iph2->sce = sched_new(1, isakmp_ph2delete_stub, iph2);
1407 
1408         return;
1409 }
1410 
1411 /* called from scheduler */
1412 void
1413 isakmp_ph2delete_stub(void *p)
1414 {
1415 
1416         isakmp_ph2delete((struct ph2handle *)p);
1417 }
1418 
1419 void
1420 isakmp_ph2delete(struct ph2handle *iph2)
1421 {
1422         char *src, *dst;
1423 
1424         SCHED_KILL(iph2->sce);
1425 
1426         src = strdup(rcs_sa2str_wop(iph2->src));
1427         dst = strdup(rcs_sa2str_wop(iph2->dst));
1428         plog(PLOG_INFO, PLOGLOC, NULL, "phase2 sa deleted %s-%s\n", src, dst);
1429         racoon_free(src);
1430         racoon_free(dst);
1431 
1432         unbindph12(iph2);
1433         remph2(iph2);
1434         delph2(iph2);
1435 
1436         return;
1437 }
1438 
1439 void
1440 ikev1_post_acquire(struct rcf_remote *rm_info, struct ph2handle *iph2)
1441 {
1442         struct ph1handle *iph1;
1443 
1444 #ifdef ENABLE_NATT
1445         if (!extract_port(iph2->src) && !extract_port(iph2->dst)) {
1446                 if ((iph1 = getph1byaddrwop(iph2->src, iph2->dst)) != NULL) {
1447                         set_port(iph2->src, extract_port(iph1->local));
1448                         set_port(iph2->dst, extract_port(iph1->remote));
1449                 }
1450         } else {
1451                 iph1 = getph1byaddr(iph2->src, iph2->dst);
1452         }
1453 #else
1454         iph1 = getph1byaddr(iph2->src, iph2->dst);
1455 #endif
1456 
1457 #define IKEV1_DEFAULT_RETRY_CHECKPH1 30
1458 
1459         if (!iph1) {
1460                 struct sched *sc;
1461 
1462                 if (isakmp_ph1begin_i(rm_info, iph2->dst, iph2->src) < 0) {
1463                         plog(PLOG_INTERR, PLOGLOC, 0,
1464                              "failed to initiate phase 1 negotiation for %s\n",
1465                              rcs_sa2str_wop(iph2->dst));
1466                         isakmp_fail_initiate_ph2(iph2);
1467                         goto fail;
1468                 }
1469                 iph2->retry_checkph1 = IKEV1_DEFAULT_RETRY_CHECKPH1;
1470                 sc = sched_new(1, isakmp_chkph1there_stub, iph2);
1471                 plog(PLOG_INFO, PLOGLOC, 0,
1472                      "IPsec-SA request for %s queued "
1473                      "since no phase1 found\n",
1474                      rcs_sa2str_wop(iph2->dst));
1475 
1476         } else if (iph1->status != PHASE1ST_ESTABLISHED) {
1477                 iph2->retry_checkph1 = IKEV1_DEFAULT_RETRY_CHECKPH1;
1478                 sched_new(1, isakmp_chkph1there_stub, iph2);
1479                 plog(PLOG_INFO, PLOGLOC, 0,
1480                      "request for establishing IPsec-SA was queued "
1481                      "since phase1 is not mature\n");
1482         } else {
1483                 /* iph1->status == PHASE1ST_ESTABLISHED */
1484                 TRACE((PLOGLOC, "begin QUICK mode\n"));
1485                 isakmp_ph2begin_i(iph1, iph2);
1486         }
1487  fail:
1488         return;
1489 }
1490 
1491 /* called by scheduler */
1492 void
1493 isakmp_chkph1there_stub(void *p)
1494 {
1495         isakmp_chkph1there((struct ph2handle *)p);
1496 }
1497 
1498 static void
1499 isakmp_fail_initiate_ph2(struct ph2handle *iph2)
1500 {
1501         /* send acquire to kernel as error */
1502         pk_sendeacquire(iph2);
1503 
1504         /* then remove ph2 */
1505         unbindph12(iph2);
1506         remph2(iph2);
1507         delph2(iph2);
1508 }
1509 
1510 void
1511 isakmp_chkph1there(struct ph2handle *iph2)
1512 {
1513         struct ph1handle *iph1;
1514 
1515         iph2->retry_checkph1--;
1516         if (iph2->retry_checkph1 < 0) {
1517                 plog(PLOG_INTERR, PLOGLOC, 0,
1518                         "phase2 negotiation failed "
1519                         "due to time up waiting for phase1. %s\n",
1520                         sadbsecas2str(iph2->dst, iph2->src,
1521                                 iph2->satype, 0, 0));
1522                 plog(PLOG_INFO, PLOGLOC, 0,
1523                      "delete phase 2 handler.\n");
1524                 isakmp_fail_initiate_ph2(iph2);
1525                 return;
1526         }
1527 
1528         /* 
1529          * Search isakmp status table by address and port 
1530          * If NAT-T is in use, consider null ports as a 
1531          * wildcard and use IKE ports instead.
1532          */
1533 #ifdef ENABLE_NATT
1534         if (!extract_port(iph2->src) && !extract_port(iph2->dst)) {
1535                 if ((iph1 = getph1byaddrwop(iph2->src, iph2->dst)) != NULL) {
1536                         set_port(iph2->src, extract_port(iph1->local));
1537                         set_port(iph2->dst, extract_port(iph1->remote));
1538                 }
1539         } else {
1540                 iph1 = getph1byaddr(iph2->src, iph2->dst);
1541         }
1542 #else
1543         iph1 = getph1byaddr(iph2->src, iph2->dst);
1544 #endif
1545 
1546         /* XXX Even if ph1 as responder is there, should we not start
1547          * phase 2 negotiation ? */
1548         if (iph1 != NULL
1549          && iph1->status == PHASE1ST_ESTABLISHED) {
1550                 /* found isakmp-sa */
1551                 /* begin quick mode */
1552                 isakmp_ph2begin_i(iph1, iph2);
1553                 return;
1554         }
1555 
1556         /* no isakmp-sa found */
1557         sched_new(1, isakmp_chkph1there_stub, iph2);
1558 
1559         return;
1560 }
1561 
1562 /*
1563  * Payload attribute handling
1564  */
1565 /* copy variable data into ALLOCATED buffer. */
1566 caddr_t
1567 isakmp_set_attr_v(caddr_t buf, int type, caddr_t val, int len)
1568 {
1569         struct isakmp_data *data;
1570 
1571         data = (struct isakmp_data *)buf;
1572         put_uint16(&data->type, type | ISAKMP_GEN_TLV);
1573         put_uint16(&data->lorv, len);
1574         memcpy(data + 1, val, len);
1575 
1576         return buf + sizeof(*data) + len;
1577 }
1578 
1579 /* copy fixed length data into ALLOCATED buffer. */
1580 caddr_t
1581 isakmp_set_attr_l(caddr_t buf, int type, uint32_t val)
1582 {
1583         struct isakmp_data *data;
1584 
1585         data = (struct isakmp_data *)buf;
1586         put_uint16(&data->type, type | ISAKMP_GEN_TV);
1587         put_uint16(&data->lorv, val);
1588 
1589         return buf + sizeof(*data);
1590 }
1591 
1592 /* add a variable data attribute to the buffer by reallocating it. */
1593 rc_vchar_t *
1594 isakmp_add_attr_v(rc_vchar_t *buf0, int type, caddr_t val, int len)
1595 {
1596         rc_vchar_t *buf = NULL;
1597         struct isakmp_data *data;
1598         int tlen;
1599         int oldlen = 0;
1600 
1601         tlen = sizeof(*data) + len;
1602 
1603         if (buf0) {
1604                 oldlen = buf0->l;
1605                 buf = rc_vrealloc(buf0, oldlen + tlen);
1606         } else
1607                 buf = rc_vmalloc(tlen);
1608         if (!buf) {
1609                 plog(PLOG_INTERR, PLOGLOC, NULL,
1610                      "failed to get a attribute buffer.\n");
1611                 return NULL;
1612         }
1613 
1614         data = (struct isakmp_data *)(buf->v + oldlen);
1615         put_uint16(&data->type, type | ISAKMP_GEN_TLV);
1616         put_uint16(&data->lorv, len);
1617         memcpy(data + 1, val, len);
1618 
1619         return buf;
1620 }
1621 
1622 /* add a fixed data attribute to the buffer by reallocating it. */
1623 rc_vchar_t *
1624 isakmp_add_attr_l(rc_vchar_t *buf0, int type, uint32_t val)
1625 {
1626         rc_vchar_t *buf = NULL;
1627         struct isakmp_data *data;
1628         int tlen;
1629         int oldlen = 0;
1630 
1631         tlen = sizeof(*data);
1632 
1633         if (buf0) {
1634                 oldlen = buf0->l;
1635                 buf = rc_vrealloc(buf0, oldlen + tlen);
1636         } else
1637                 buf = rc_vmalloc(tlen);
1638         if (!buf) {
1639                 plog(PLOG_INTERR, PLOGLOC, NULL,
1640                      "failed to get a attribute buffer.\n");
1641                 return NULL;
1642         }
1643 
1644         data = (struct isakmp_data *)(buf->v + oldlen);
1645         put_uint16(&data->type, type | ISAKMP_GEN_TV);
1646         put_uint16(&data->lorv, val);
1647 
1648         return buf;
1649 }
1650 
1651 /*
1652  * set values into allocated buffer of isakmp header for phase 1
1653  */
1654 static caddr_t
1655 set_isakmp_header(rc_vchar_t *vbuf, struct ph1handle *iph1, 
1656                  int nptype, uint8_t etype, uint8_t flags, uint32_t msgid)
1657 {
1658         struct isakmp *isakmp;
1659 
1660         if (vbuf->l < sizeof(*isakmp))
1661                 return NULL;
1662 
1663         isakmp = (struct isakmp *)vbuf->v;
1664 
1665         memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(isakmp_cookie_t));
1666         memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(isakmp_cookie_t));
1667         isakmp->np = nptype;
1668         isakmp->v = iph1->version;
1669         isakmp->etype = etype;
1670         isakmp->flags = flags;
1671         isakmp->msgid = msgid;
1672         put_uint32(&isakmp->len, vbuf->l);
1673 
1674         return vbuf->v + sizeof(*isakmp);
1675 }
1676 
1677 /*
1678  * set values into allocated buffer of isakmp header for phase 1
1679  */
1680 caddr_t
1681 set_isakmp_header1(rc_vchar_t *vbuf, struct ph1handle *iph1, int nptype)
1682 {
1683         return set_isakmp_header (vbuf, iph1, nptype, iph1->etype, iph1->flags, iph1->msgid);
1684 }
1685 
1686 /*
1687  * set values into allocated buffer of isakmp header for phase 2
1688  */
1689 caddr_t
1690 set_isakmp_header2(rc_vchar_t *vbuf, struct ph2handle *iph2, int nptype)
1691 {
1692         return set_isakmp_header (vbuf, iph2->ph1, nptype, ISAKMP_ETYPE_QUICK, iph2->flags, iph2->msgid);
1693 }
1694 
1695 #if 0
1696 /*
1697  * set values into allocated buffer of isakmp header for phase 1
1698  */
1699 caddr_t
1700 set_isakmp_header1(vbuf, iph1, nptype)
1701         rc_vchar_t *vbuf;
1702         struct ph1handle *iph1;
1703 {
1704         struct isakmp *isakmp;
1705         struct isakmp_construct res;
1706 
1707         res.buff = NULL;
1708         res.np = NULL;
1709 
1710         if (vbuf->l < sizeof(*isakmp))
1711                 return res;
1712 
1713         isakmp = (struct isakmp *)vbuf->v;
1714         memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(isakmp_cookie_t));
1715         memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(isakmp_cookie_t));
1716         isakmp->np = nptype;
1717         isakmp->v = iph1->version;
1718         isakmp->etype = iph1->etype;
1719         isakmp->flags = iph1->flags;
1720         isakmp->msgid = iph1->msgid;
1721         put_uint32(&isakmp->len, vbuf->l);
1722 
1723         res.np = &(isakmp->np);
1724         res.buff = vbuf->v + sizeof(*isakmp);
1725 
1726         return res;
1727 }
1728 
1729 /*
1730  * set values into allocated buffer of isakmp header for phase 2
1731  */
1732 caddr_t
1733 set_isakmp_header2(vbuf, iph2, nptype)
1734         rc_vchar_t *vbuf;
1735         struct ph2handle *iph2;
1736         int nptype;
1737 {
1738         struct isakmp *isakmp;
1739 
1740         if (vbuf->l < sizeof(*isakmp))
1741                 return NULL;
1742 
1743         isakmp = (struct isakmp *)vbuf->v;
1744         memcpy(&isakmp->i_ck, &iph2->ph1->index.i_ck, sizeof(isakmp_cookie_t));
1745         memcpy(&isakmp->r_ck, &iph2->ph1->index.r_ck, sizeof(isakmp_cookie_t));
1746         isakmp->np = nptype;
1747         isakmp->v = iph2->ph1->version;
1748         isakmp->etype = ISAKMP_ETYPE_QUICK;
1749         isakmp->flags = iph2->flags;
1750         memcpy(&isakmp->msgid, &iph2->msgid, sizeof(isakmp->msgid));
1751         put_uint32(&isakmp->len, vbuf->l);
1752 
1753         return vbuf->v + sizeof(*isakmp);
1754 }
1755 #endif
1756 
1757 /*
1758  * set values into allocated buffer of isakmp payload.
1759  */
1760 struct isakmp_construct
1761 set_isakmp_payload_c(struct isakmp_construct constr, rc_vchar_t *src, int nptype)
1762 {
1763         struct isakmp_gen *gen;
1764         caddr_t p = constr.buff;
1765 
1766         plog(PLOG_DEBUG, PLOGLOC, NULL, "add payload of len %lu, next type %d\n",
1767              (unsigned long)src->l, nptype);
1768 
1769         *constr.np = nptype;
1770         gen = (struct isakmp_gen *)p;
1771         gen->np = ISAKMP_NPTYPE_NONE;
1772         put_uint16(&gen->len, sizeof(*gen) + src->l);
1773         p += sizeof(*gen);
1774         memcpy(p, src->v, src->l);
1775         p += src->l;
1776 
1777         constr.np = &(gen->np);
1778         constr.buff = p;
1779 
1780         return constr;
1781 }
1782 
1783 /*
1784  * set values into allocated buffer of isakmp payload.
1785  */
1786 caddr_t
1787 set_isakmp_payload(caddr_t buf, rc_vchar_t *src, int nptype)
1788 {
1789         struct isakmp_gen *gen;
1790         caddr_t p = buf;
1791 
1792         plog(PLOG_DEBUG, PLOGLOC, NULL, "add payload of len %lu, next type %d\n",
1793              (unsigned long)src->l, nptype);
1794 
1795         gen = (struct isakmp_gen *)p;
1796         gen->np = nptype;
1797         put_uint16(&gen->len, sizeof(*gen) + src->l);
1798         p += sizeof(*gen);
1799         memcpy(p, src->v, src->l);
1800         p += src->l;
1801 
1802         return p;
1803 }
1804 
1805 /*
1806  * conversion routine for use with dispatch tables
1807  */
1808 static int
1809 etypesw1(int etype)
1810 {
1811         switch (etype) {
1812         case ISAKMP_ETYPE_IDENT:
1813                 return 1;
1814         case ISAKMP_ETYPE_AGG:
1815                 return 2;
1816         case ISAKMP_ETYPE_BASE:
1817                 return 3;
1818         default:
1819                 return 0;
1820         }
1821  /*NOTREACHED*/}
1822 
1823 static int
1824 etypesw2(int etype)
1825 {
1826         switch (etype) {
1827         case ISAKMP_ETYPE_QUICK:
1828                 return 1;
1829         default:
1830                 return 0;
1831         }
1832  /*NOTREACHED*/}
1833 
1834 int
1835 copy_ph1addresses(struct ph1handle *iph1, struct rcf_remote *rmconf, 
1836                   struct sockaddr *remote, struct sockaddr *local) 
1837 {
1838         uint16_t *port = NULL;
1839 
1840         /* address portion must be grabbed from real remote address "remote" */
1841         iph1->remote = rcs_sadup(remote);
1842         if (iph1->remote == NULL) {
1843                 delph1(iph1);
1844                 return -1;
1845         }
1846 
1847         /*
1848          * if remote has no port # (in case of initiator - from ACQUIRE msg)
1849          * - if remote.conf specifies port #, use that
1850          * - if remote.conf does not, use 500
1851          * if remote has port # (in case of responder - from recvfrom(2))
1852          * respect content of "remote".
1853          */
1854         switch (iph1->remote->sa_family) {
1855         case AF_INET:
1856                 port = &((struct sockaddr_in *)iph1->remote)->sin_port;
1857                 if (*port)
1858                         break;
1859                 *port = ((struct sockaddr_in *)rmconf->ikev1->peers_ipaddr->a.ipaddr)->sin_port;
1860                 if (*port)
1861                         break;
1862                 *port = htons(isakmp_port);
1863                 break;
1864 #ifdef INET6
1865         case AF_INET6:
1866                 port = &((struct sockaddr_in6 *)iph1->remote)->sin6_port;
1867                 if (*port)
1868                         break;
1869                 *port = ((struct sockaddr_in6 *)rmconf->ikev1->peers_ipaddr->a.ipaddr)->sin6_port;
1870                 if (*port)
1871                         break;
1872                 *port = htons(isakmp_port);
1873                 break;
1874 #endif
1875         default:
1876                 plog(PLOG_PROTOERR, PLOGLOC, NULL,
1877                      "invalid family: %d\n", iph1->remote->sa_family);
1878                 delph1(iph1);
1879                 return -1;
1880         }
1881 
1882         iph1->local = getlocaladdr(iph1->remote, local, isakmp_port);
1883         if (iph1->local == NULL) {
1884                 delph1(iph1);
1885                 return -1;
1886         }
1887 
1888         switch (iph1->local->sa_family) {
1889         case AF_INET:
1890                 port = &((struct sockaddr_in *)iph1->local)->sin_port;
1891                 break;
1892 #ifdef INET6
1893         case AF_INET6:
1894                 port = &((struct sockaddr_in6 *)iph1->local)->sin6_port;
1895                 break;
1896 #endif
1897         default:
1898                 plog(PLOG_PROTOERR, PLOGLOC, NULL,
1899                      "invalid family: %d\n", iph1->remote->sa_family);
1900                 delph1(iph1);
1901                 return -1;
1902         }
1903         if (*port == 0)
1904                 *port = htons(isakmp_port);
1905 
1906         return 0;
1907 }
1908 
1909 static int
1910 nostate1(struct ph1handle *iph1, rc_vchar_t *msg)
1911 {
1912         plog(PLOG_PROTOERR, PLOGLOC, 0, "wrong state %u.\n",
1913              iph1->status);
1914         return -1;
1915 }
1916 
1917 static int
1918 nostate2(struct ph2handle *iph2, rc_vchar_t *msg)
1919 {
1920         plog(PLOG_PROTOERR, PLOGLOC, 0, "wrong state %u.\n",
1921              iph2->status);
1922         return -1;
1923 }
1924 
1925 void
1926 log_ph1established(const struct ph1handle *iph1)
1927 {
1928         char *src, *dst;
1929 
1930         src = strdup(rcs_sa2str(iph1->local));
1931         dst = strdup(rcs_sa2str(iph1->remote));
1932         plog(PLOG_INFO, PLOGLOC, NULL,
1933              "ISAKMP-SA established %s-%s spi:%s\n",
1934              src, dst, isakmp_pindex(&iph1->index, 0));
1935         racoon_free(src);
1936         racoon_free(dst);
1937 
1938         return;
1939 }
1940 
1941 /*
1942  * calculate cookie and set.
1943  */
1944 int
1945 isakmp_newcookie(caddr_t place, struct sockaddr *remote, struct sockaddr *local)
1946 {
1947         rc_vchar_t *buf = NULL, *buf2 = NULL;
1948         char *p;
1949         int blen;
1950         int alen;
1951         caddr_t sa1, sa2;
1952         time_t t;
1953         int error = -1;
1954         uint16_t port;
1955         const int secret_size = 16;
1956 
1957         if (remote->sa_family != local->sa_family) {
1958                 plog(PLOG_PROTOERR, PLOGLOC, NULL,
1959                      "address family mismatch, remote:%d local:%d\n",
1960                      remote->sa_family, local->sa_family);
1961                 goto end;
1962         }
1963         switch (remote->sa_family) {
1964         case AF_INET:
1965                 alen = sizeof(struct in_addr);
1966                 sa1 = (caddr_t)&((struct sockaddr_in *)remote)->sin_addr;
1967                 sa2 = (caddr_t)&((struct sockaddr_in *)local)->sin_addr;
1968                 break;
1969 #ifdef INET6
1970         case AF_INET6:
1971                 alen = sizeof(struct in6_addr);
1972                 sa1 = (caddr_t)&((struct sockaddr_in6 *)remote)->sin6_addr;
1973                 sa2 = (caddr_t)&((struct sockaddr_in6 *)local)->sin6_addr;
1974                 break;
1975 #endif
1976         default:
1977                 plog(PLOG_PROTOERR, PLOGLOC, NULL,
1978                      "invalid family: %d\n", remote->sa_family);
1979                 goto end;
1980         }
1981         blen = (alen + sizeof(uint16_t)) * 2
1982                 + sizeof(time_t) + secret_size;
1983         buf = rc_vmalloc(blen);
1984         if (buf == NULL) {
1985                 plog(PLOG_INTERR, PLOGLOC, NULL, "failed to get a cookie.\n");
1986                 goto end;
1987         }
1988         p = buf->v;
1989 
1990         /* copy my address */
1991         memcpy(p, sa1, alen);
1992         p += alen;
1993         port = ((struct sockaddr_in *)remote)->sin_port;
1994         memcpy(p, &port, sizeof(uint16_t));
1995         p += sizeof(uint16_t);
1996 
1997         /* copy target address */
1998         memcpy(p, sa2, alen);
1999         p += alen;
2000         port = ((struct sockaddr_in *)local)->sin_port;
2001         memcpy(p, &port, sizeof(uint16_t));
2002         p += sizeof(uint16_t);
2003 
2004         /* copy time */
2005         t = time(0);
2006         memcpy(p, (caddr_t)&t, sizeof(t));
2007         p += sizeof(t);
2008 
2009         /* copy random value */
2010         buf2 = eay_set_random(secret_size);
2011         if (buf2 == NULL)
2012                 goto end;
2013         memcpy(p, buf2->v, secret_size);
2014         p += secret_size;
2015         rc_vfree(buf2);
2016 
2017         buf2 = eay_sha1_one(buf);
2018         memcpy(place, buf2->v, sizeof(isakmp_cookie_t));
2019 
2020         sa1 = val2str(place, sizeof(isakmp_cookie_t));
2021         plog(PLOG_DEBUG, PLOGLOC, NULL, "new cookie:\n%s\n", sa1);
2022         racoon_free(sa1);
2023 
2024         error = 0;
2025       end:
2026         if (buf != NULL)
2027                 rc_vfree(buf);
2028         if (buf2 != NULL)
2029                 rc_vfree(buf2);
2030         return error;
2031 }
2032 
2033 /*
2034  * save partner's(payload) data into phhandle.
2035  */
2036 int
2037 isakmp_p2ph(rc_vchar_t **buf, struct isakmp_gen *gen)
2038 {
2039         /* XXX to be checked in each functions for logging. */
2040         if (*buf) {
2041                 plog(PLOG_PROTOWARN, PLOGLOC, NULL,
2042                      "ignore this payload, same payload type exist.\n");
2043                 return -1;
2044         }
2045 
2046         *buf = rc_vmalloc(get_uint16(&gen->len) - sizeof(*gen));
2047         if (*buf == NULL) {
2048                 plog(PLOG_INTERR, PLOGLOC, NULL, "failed to get buffer.\n");
2049                 return -1;
2050         }
2051         memcpy((*buf)->v, gen + 1, (*buf)->l);
2052 
2053         return 0;
2054 }
2055 
2056 #if 0
2057 static int
2058 check_spi_size(proto_id, size)
2059         int proto_id, size;
2060 {
2061         switch (proto_id) {
2062         case IPSECDOI_PROTO_ISAKMP:
2063                 if (size != 0) {
2064                         /* WARNING */
2065                         plog(PLOG_DEBUG, PLOGLOC, NULL,
2066                              "SPI size isn't zero, but IKE proposal.\n");
2067                 }
2068                 return 0;
2069 
2070         case IPSECDOI_PROTO_IPSEC_AH:
2071         case IPSECDOI_PROTO_IPSEC_ESP:
2072                 if (size != 4) {
2073                         plog(PLOG_PROTOERR, PLOGLOC, NULL,
2074                              "invalid SPI size=%d for IPSEC proposal.\n", size);
2075                         return -1;
2076                 }
2077                 return 0;
2078 
2079         case IPSECDOI_PROTO_IPCOMP:
2080                 if (size != 2 && size != 4) {
2081                         plog(PLOG_INTERR, PLOGLOC, NULL,
2082                              "invalid SPI size=%d for IPCOMP proposal.\n",
2083                              size);
2084                         return -1;
2085                 }
2086                 return 0;
2087 
2088         default:
2089                 /* ??? */
2090                 return -1;
2091         }
2092         /* NOT REACHED */
2093 }
2094 #endif
2095 
2096 
2097 /*
2098  * parse ISAKMP payloads, without ISAKMP base header.
2099  */
2100 rc_vchar_t *
2101 isakmp_parsewoh(int np0, struct isakmp_gen *gen, int len)
2102 {
2103         unsigned char np = np0 & 0xff;
2104         int tlen, plen;
2105         rc_vchar_t *result;
2106         struct isakmp_parse_t *p, *ep;
2107 
2108         plog(PLOG_DEBUG, PLOGLOC, NULL, "begin.\n");
2109 
2110         /*
2111          * 5 is a magic number, but any value larger than 2 should be fine
2112          * as we do rc_vrealloc() in the following loop.
2113          */
2114         result = rc_vmalloc(sizeof(struct isakmp_parse_t) * 5);
2115         if (result == NULL) {
2116                 plog(PLOG_INTERR, PLOGLOC, 0,
2117                         "failed to get buffer.\n");
2118                 return NULL;
2119         }
2120         p = (struct isakmp_parse_t *)result->v;
2121         ep = (struct isakmp_parse_t *)(result->v + result->l - sizeof(*ep));
2122 
2123         tlen = len;
2124 
2125         /* parse through general headers */
2126         while (0 < tlen && np != ISAKMP_NPTYPE_NONE) {
2127                 if (tlen <= sizeof(struct isakmp_gen)) {
2128                         /* don't send information, see isakmp_ident_r1() */
2129                         plog(PLOG_PROTOERR, PLOGLOC, 0,
2130                                 "invalid length of payload\n");
2131                         rc_vfree(result);
2132                         return NULL;
2133                 }
2134 
2135                 plog(PLOG_DEBUG, PLOGLOC, NULL,
2136                         "seen nptype=%u(%s)\n", np, s_isakmp_nptype(np));
2137 
2138                 p->type = np;
2139                 p->len = get_uint16(&gen->len);
2140                 if (p->len < sizeof(struct isakmp_gen) || p->len > tlen) {
2141                         plog(PLOG_DEBUG, PLOGLOC, NULL,
2142                                 "invalid length of payload\n");
2143                         rc_vfree(result);
2144                         return NULL;
2145                 }
2146                 p->ptr = gen;
2147                 p++;
2148                 if (ep <= p) {
2149                         int off;
2150 
2151                         off = p - (struct isakmp_parse_t *)result->v;
2152                         result = rc_vrealloc(result, result->l * 2);
2153                         if (result == NULL) {
2154                                 plog(PLOG_DEBUG, PLOGLOC, NULL,
2155                                         "failed to realloc buffer.\n");
2156                                 rc_vfree(result);
2157                                 return NULL;
2158                         }
2159                         ep = (struct isakmp_parse_t *)
2160                                 (result->v + result->l - sizeof(*ep));
2161                         p = (struct isakmp_parse_t *)result->v;
2162                         p += off;
2163                 }
2164 
2165                 np = gen->np;
2166                 plen = get_uint16(&gen->len);
2167                 gen = (struct isakmp_gen *)((caddr_t)gen + plen);
2168                 tlen -= plen;
2169         }
2170         p->type = ISAKMP_NPTYPE_NONE;
2171         p->len = 0;
2172         p->ptr = NULL;
2173 
2174         plog(PLOG_DEBUG, PLOGLOC, NULL, "succeed.\n");
2175 
2176         return result;
2177 }
2178 
2179 
2180 /*
2181  * parse ISAKMP payloads, including ISAKMP base header.
2182  */
2183 rc_vchar_t *
2184 isakmp_parse(rc_vchar_t *buf)
2185 {
2186         struct isakmp *isakmp = (struct isakmp *)buf->v;
2187         struct isakmp_gen *gen;
2188         int tlen;
2189         rc_vchar_t *result;
2190         unsigned char np;
2191 
2192         np = isakmp->np;
2193         gen = (struct isakmp_gen *)(buf->v + sizeof(*isakmp));
2194         tlen = buf->l - sizeof(struct isakmp);
2195         result = isakmp_parsewoh(np, gen, tlen);
2196 
2197         return result;
2198 }
2199 
2200 
2201 int
2202 isakmp_send(struct ph1handle *iph1, rc_vchar_t *sbuf)
2203 {
2204         int len = 0;
2205         int s;
2206         rc_vchar_t *vbuf = NULL;
2207 
2208 #ifdef ENABLE_NATT
2209         size_t extralen = NON_ESP_MARKER_USE(iph1) ? NON_ESP_MARKER_LEN : 0;
2210 
2211 #ifdef ENABLE_FRAG
2212         /* 
2213          * Do not add the non ESP marker for a packet that will
2214          * be fragmented. The non ESP marker should appear in 
2215          * all fragment's packets, but not in the fragmented packet
2216          */
2217         if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN) 
2218                 extralen = 0;
2219 #endif
2220         if (extralen)
2221                 plog (PLOG_DEBUG, PLOGLOC, NULL, "Adding NON-ESP marker\n");
2222 
2223         /* If NAT-T port floating is in use, 4 zero bytes (non-ESP marker) 
2224            must added just before the packet itself. For this we must 
2225            allocate a new buffer and release it at the end. */
2226         if (extralen) {
2227                 if ((vbuf = rc_vmalloc (sbuf->l + extralen)) == NULL) {
2228                         plog(PLOG_INTERR, PLOGLOC, NULL,
2229                              "vbuf allocation failed\n");
2230                         return -1;
2231                 }
2232                 *(uint32_t *)vbuf->v = 0;
2233                 memcpy (vbuf->v + extralen, sbuf->v, sbuf->l);
2234                 sbuf = vbuf;
2235         }
2236 #endif
2237 
2238         /* select the socket to be sent */
2239         s = getsockmyaddr(iph1->local);
2240         if (s == -1){
2241                 if ( vbuf != NULL )
2242                         rc_vfree(vbuf);
2243                 return -1;
2244         }
2245 
2246         plog(PLOG_DEBUG, PLOGLOC, NULL, "%zu bytes from %s to %s\n",
2247              sbuf->l, rcs_sa2str(iph1->local), rcs_sa2str(iph1->remote));
2248 
2249 #ifdef ENABLE_FRAG
2250         if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN) {
2251                 if (isakmp_sendfrags(iph1, sbuf) == -1) {
2252                         plog(PLOG_INTERR, PLOGLOC, NULL, 
2253                             "isakmp_sendfrags failed\n");
2254                         if ( vbuf != NULL )
2255                                 rc_vfree(vbuf);
2256                         return -1;
2257                 }
2258         } else 
2259 #endif
2260         {
2261                 len = sendfromto(s, sbuf->v, sbuf->l,
2262                                  iph1->local, iph1->remote, ikev1_times_per_send(iph1->rmconf));
2263 
2264                 if (len == -1) {
2265                         plog(PLOG_INTERR, PLOGLOC, NULL, "sendfromto failed\n");
2266                         if ( vbuf != NULL )
2267                                 rc_vfree(vbuf);
2268                         return -1;
2269                 }
2270         }
2271         
2272         if ( vbuf != NULL )
2273                 rc_vfree(vbuf);
2274         
2275         return 0;
2276 }
2277 
2278 void
2279 ikev1_set_rmconf(struct ph1handle *iph1, struct rcf_remote *conf)
2280 {
2281         if (iph1->rmconf)
2282                 rcf_free_remote(iph1->rmconf);
2283 
2284         iph1->rmconf = conf;
2285 }
2286 
2287 int
2288 ikev1_verify_cert(struct rcf_remote *conf)
2289 {
2290         return ikev1_verify_pubkey(conf) != RCT_BOOL_OFF;
2291 }
2292 
2293 
2294 int 
2295 ikev1_getcert_method(struct rcf_remote *conf)
2296 {
2297         return ISAKMP_GETCERT_LOCALFILE;
2298 }
2299 
2300 int
2301 ikev1_certtype(struct rcf_remote *conf)
2302 {
2303         return ISAKMP_CERT_X509SIGN;
2304         /* ISAKMP_CERT_PLAINRSA; */
2305 }
2306 
2307 /*remoteconf.c*/
2308 struct rcf_remote *
2309 getrmconf(struct sockaddr *remote)
2310 {
2311         struct rcf_remote *conf;
2312 
2313         conf = ikev1_conf_find(remote);
2314         if (!conf) {
2315                 /* if no config with src addr, use default */
2316                 extern struct rcf_default *rcf_default_head;
2317                 extern struct rcf_remote *rcf_deepcopy_remote(struct rcf_remote *);
2318                 if (rcf_default_head && rcf_default_head->remote) {
2319                         plog(PLOG_DEBUG, PLOGLOC, 0,
2320                              "anonymous configuration selected for %s.\n",
2321                              rcs_sa2str(remote));
2322                         conf = rcf_deepcopy_remote(rcf_default_head->remote);
2323                 }
2324         }
2325         return conf;
2326 }
2327 
2328 
2329 /*isakmp.c*/
2330 uint32_t 
2331 isakmp_newmsgid2(struct ph1handle *iph1)
2332 {
2333         uint32_t msgid2;
2334 
2335         do {
2336                 msgid2 = eay_random_uint32();
2337         } while (getph2bymsgid(iph1, msgid2));
2338 
2339         return msgid2;
2340 }
2341 
2342 
2343 /**/
2344 int
2345 ikev1_doitype(struct rcf_remote *conf)
2346 {
2347         return IPSEC_DOI;       /* ??? */
2348 }
2349 
2350 /**/
2351 int
2352 ikev1_sittype(struct rcf_remote *conf)
2353 {
2354         return IPSECDOI_SIT_IDENTITY_ONLY;
2355 }
2356 
2357 
2358 /*??*/
2359 size_t
2360 sysdep_sa_len(struct sockaddr *a)
2361 {
2362         return SA_LEN(a);
2363 }
2364 
2365 
2366 int
2367 ikev1_weak_phase1_check(struct rcf_remote *conf)
2368 {
2369         return 0;
2370 }
2371 
2372 
2373 /*remoteconf.c*/
2374 /*%%%*/
2375 struct isakmpsa *
2376 newisakmpsa(void)
2377 {
2378         struct isakmpsa *new;
2379 
2380         new = racoon_calloc(1, sizeof(*new));
2381         if (new == NULL)
2382                 return NULL;
2383 
2384         /*
2385          * Just for sanity, make sure this is initialized.  This is
2386          * filled in for real when the ISAKMP proposal is configured.
2387          */
2388         new->vendorid = VENDORID_UNKNOWN;
2389 
2390         new->next = NULL;
2391         new->rmconf = NULL;
2392 #ifdef HAVE_GSSAPI
2393         new->gssid = NULL;
2394 #endif
2395 
2396         return new;
2397 }
2398 
2399 struct isakmpsa *
2400 dupisakmpsa(struct isakmpsa *sa)
2401 {
2402         struct isakmpsa *res = NULL;
2403 
2404         if (sa == NULL)
2405                 return NULL;
2406 
2407         res = newisakmpsa();
2408         if(res == NULL)
2409                 return NULL;
2410 
2411         *res = *sa;
2412 #ifdef HAVE_GSSAPI
2413         /* 
2414          * XXX gssid
2415          */
2416 #endif
2417         res->next=NULL;
2418 
2419         if (sa->dhgrp != NULL)
2420                 oakley_setdhgroup(sa->dh_group, &(res->dhgrp));
2421 
2422         return res;
2423 
2424 }
2425 
2426 /*
2427  * insert into tail of list.
2428  */
2429 struct isakmpsa *
2430 insisakmpsa(struct isakmpsa *new, struct isakmpsa *list)
2431 {
2432         struct isakmpsa *p;
2433 
2434         if (list == NULL) {
2435                 return new;
2436         } else {
2437                 for (p = list; p->next != NULL; p = p->next)
2438                         ;
2439                 p->next = new;
2440                 return list;
2441         }
2442 }
2443 
2444 void
2445 delisakmpsa(struct isakmpsa *sa)
2446 {
2447         if (sa->dhgrp)
2448                 oakley_dhgrp_free(sa->dhgrp);
2449         if (sa->next)
2450                 delisakmpsa(sa->next);
2451 #ifdef HAVE_GSSAPI
2452         if (sa->gssid)
2453                 rc_vfree(sa->gssid);
2454 #endif
2455         racoon_free(sa);
2456 }
2457 
2458 
2459 struct isakmpsa *
2460 ikev1_conf_to_isakmpsa(struct rcf_remote *rmconf)
2461 {
2462         const int       prop_no = 1;
2463         int     trns_no = 1;
2464         struct rc_alglist       *auth, *dh, *enc, *hash;
2465         struct isakmpsa *sa;
2466         struct isakmpsa *result = 0;
2467 
2468         for (auth = ikev1_kmp_auth_method(rmconf); auth; auth = auth->next) {
2469                 for (dh = ikev1_kmp_dh_group(rmconf); dh; dh = dh->next) {
2470                         for (enc = ikev1_kmp_enc_alg(rmconf); enc; enc = enc->next) {
2471                                 for (hash = ikev1_kmp_hash_alg(rmconf); hash; hash = hash->next) {
2472                                         sa = create_isakmpsa(prop_no,
2473                                                              trns_no, 
2474                                                              auth,
2475                                                              dh,
2476                                                              enc,
2477                                                              hash,
2478                                                              rmconf,
2479                                                              ikev1_my_gssapi_id(rmconf));
2480                                         ++trns_no;
2481                                         if (! sa) {
2482                                                 plog(PLOG_INTERR, PLOGLOC, 0,
2483                                                      "failed to create isakmp proposal\n");
2484                                                 return NULL;
2485                                         }
2486                                         result = insisakmpsa(sa, result);
2487                                 }
2488                         }
2489                 }
2490         }
2491 
2492         return result;
2493 }
2494 
2495 
2496 static int
2497 enc_keylen(rc_type algtype, int keylen)
2498 {
2499         switch (algtype) {
2500         case RCT_ALG_AES128_CBC:
2501                 return 128;
2502         case RCT_ALG_AES192_CBC:
2503                 return 192;
2504         case RCT_ALG_AES256_CBC:
2505                 return 256;
2506         default:
2507                 return keylen;
2508         }                       
2509 }
2510 
2511 
2512 static struct isakmpsa *
2513 create_isakmpsa(int prop_no, int trns_no, 
2514                 struct rc_alglist *auth, 
2515                 struct rc_alglist *dh, 
2516                 struct rc_alglist *enc, 
2517                 struct rc_alglist *hash, 
2518                 struct rcf_remote *rmconf, rc_vchar_t *gssid)
2519 {
2520         struct isakmpsa *new;
2521 
2522         new = newisakmpsa();
2523         if (new == NULL) {
2524                 plog(PLOG_INTERR, PLOGLOC, 0,
2525                      "failed allocating memory for isakmp proposal\n");
2526                 return 0;
2527         }
2528         new->prop_no = prop_no;
2529         new->trns_no = trns_no;
2530         new->lifetime = ikev1_kmp_sa_lifetime_time(rmconf);
2531         new->lifebyte = ikev1_kmp_sa_lifetime_byte(rmconf);
2532         new->lifebyte = (new->lifebyte + 1023) >> 10;
2533         new->enctype = alg_oakley_encdef_doi(enc->algtype);
2534         new->encklen = enc_keylen(enc->algtype, enc->keylen);
2535         new->authmethod = alg_oakley_authdef_doi(auth->algtype);
2536         new->hashtype = alg_oakley_hashdef_doi(hash->algtype);
2537         new->dh_group = alg_oakley_dhdef_doi(dh->algtype);
2538         new->vendorid = VENDORID_UNKNOWN; /*vendorid;*/
2539         new->rmconf = rmconf;
2540 #ifdef HAVE_GSSAPI
2541         if (new->authmethod == OAKLEY_ATTR_AUTH_METHOD_GSSAPI_KRB) {
2542                 if (gssid != NULL) {
2543                         new->gssid = rc_vmalloc(strlen(gssid));
2544                         memcpy(new->gssid->v, gssid, new->gssid->l);
2545                         racoon_free(gssid);
2546                 } else {
2547                         /*
2548                          * Allocate the default ID so that it gets put
2549                          * into a GSS ID attribute during the Phase 1
2550                          * exchange.
2551                          */
2552                         new->gssid = gssapi_get_default_gss_id();
2553                 }
2554         }
2555 #endif
2556 
2557         return new;
2558 }
2559 
2560 /*policy.c */
2561 void
2562 delsp_bothdir(struct policyindex *p)
2563 {
2564         plog(PLOG_INTERR, PLOGLOC, 0, "unimplemented\n");
2565 }
2566 
2567 
2568 int
2569 getsockmyaddr(struct sockaddr *addr)
2570 {
2571         extern int isakmp_find_socket();
2572 
2573         return isakmp_find_socket(addr);
2574 }
2575 
2576 
2577 int
2578 ikev1_cacerttype(struct rcf_remote *conf)
2579 {
2580         return ISAKMP_CERT_X509SIGN;
2581 }
2582 
2583 
2584 static int
2585 check_ph2_id_type(int type)
2586 {
2587         switch (type) {
2588         case IPSECDOI_ID_IPV4_ADDR:
2589         case IPSECDOI_ID_IPV4_ADDR_SUBNET:
2590         case IPSECDOI_ID_IPV6_ADDR:
2591         case IPSECDOI_ID_IPV6_ADDR_SUBNET:
2592                 return TRUE;
2593                 break;
2594         case IPSECDOI_ID_IPV4_ADDR_RANGE:
2595         case IPSECDOI_ID_IPV6_ADDR_RANGE:
2596         default:
2597                 return FALSE;
2598         }
2599 }
2600 
2601 
2602 static int
2603 id_is_matching(struct rc_addrlist *addr, int upper_layer_protocol, 
2604                rc_vchar_t *id)
2605 {
2606         int error;
2607         uint8_t plen;
2608         uint16_t ulproto;
2609         struct ipsecdoi_id_b *idb;
2610         struct sockaddr_storage ss;
2611 
2612         idb = (struct ipsecdoi_id_b *)id->v;
2613         switch (idb->type) {
2614         case IPSECDOI_ID_IPV4_ADDR:
2615         case IPSECDOI_ID_IPV4_ADDR_SUBNET:
2616         case IPSECDOI_ID_IPV6_ADDR:
2617         case IPSECDOI_ID_IPV6_ADDR_SUBNET:
2618                 if (addr->type != RCT_ADDR_INET) 
2619                         return FALSE;
2620 
2621                 /* get a source address of inbound SA */
2622                 error = ipsecdoi_id2sockaddr(id,
2623                                              (struct sockaddr *)&ss,
2624                                              &plen,
2625                                              &ulproto);
2626                 if (error)
2627                         return FALSE;
2628 
2629 #ifdef INET6
2630                 /* scope? */
2631 #endif
2632                 break;
2633 
2634         default:
2635                 return FALSE;
2636         }
2637 
2638         if (rcs_cmpsa(addr->a.ipaddr, (struct sockaddr *)&ss) != 0)
2639                 return FALSE;
2640 
2641         if (upper_layer_protocol == RC_PROTO_ANY)
2642                 upper_layer_protocol = IPSEC_ULPROTO_ANY;
2643 
2644         if (upper_layer_protocol != ulproto)
2645                 return FALSE;
2646 
2647         return TRUE;
2648 }
2649 
2650 
2651 static void
2652 free_selectorlist(struct rcf_selector *s)
2653 {
2654         struct rcf_selector *s_next;
2655 
2656         for (; s; s = s_next) {
2657                 s_next = s->next;
2658                 rcf_free_selector(s);
2659         }
2660 }
2661 
2662 
2663 struct rcf_selector *
2664 ike_conf_find_ikev1sel_by_id(rc_vchar_t *id_local, rc_vchar_t *id_remote)
2665 {
2666         int upper_layer_protocol;
2667         int err;
2668         struct ipsecdoi_id_b    *id_l;
2669         struct ipsecdoi_id_b    *id_r;
2670         struct rcf_selector *s;
2671         struct rcf_selector *s_next;
2672         struct rc_addrlist *srclist;
2673         struct rc_addrlist *dstlist;
2674 
2675         id_l = (struct ipsecdoi_id_b *)id_local->v;
2676         id_r = (struct ipsecdoi_id_b *)id_remote->v;
2677 
2678         if (!check_ph2_id_type(id_l->type)) {
2679                 isakmp_log(0, 0, 0, 0,
2680                            PLOG_PROTOERR, PLOGLOC, 
2681                            "received ID for localside (type %s) is not supported ID type\n",
2682                            s_ipsecdoi_ident(id_l->type));
2683                 return 0;
2684         }
2685         if (!check_ph2_id_type(id_r->type)) {
2686                 isakmp_log(0, 0, 0, 0,
2687                            PLOG_PROTOERR, PLOGLOC, 
2688                            "received ID for remoteside (type %s) is not supported ID type\n",
2689                            s_ipsecdoi_ident(id_r->type));
2690                 return 0;
2691         }
2692 
2693         if (rcf_get_selectorlist(&s)) {
2694                 TRACE((PLOGLOC, "rcf_get_selectorlist() failed\n"));
2695                 return 0;
2696         }
2697 
2698         for (; s; s_next = s->next, rcf_free_selector(s), s = s_next) {
2699                 if (s->direction != RCT_DIR_OUTBOUND)
2700                         continue;
2701                 srclist = dstlist = 0;
2702                 err = rcs_extend_addrlist(s->src, &srclist);
2703                 if (err != 0) {
2704                         isakmp_log(0, 0, 0, 0,
2705                                    PLOG_INTWARN, PLOGLOC,
2706                                    "expanding src address of selector %s: %s\n",
2707                                    rc_vmem2str(s->sl_index), gai_strerror(err));
2708                         goto next_selector;
2709                 }
2710                 err = rcs_extend_addrlist(s->dst, &dstlist);
2711                 if (err != 0) {
2712                         isakmp_log(0, 0, 0, 0,
2713                                    PLOG_INTWARN, PLOGLOC,
2714                                    "expanding dst address of selector %s: %s\n",
2715                                    rc_vmem2str(s->sl_index), gai_strerror(err));
2716                         goto next_selector;
2717                 }
2718 #if 0                           /* it looks like spmd uses only the first address of expanded addresses */
2719                 for (src = srclist; src; src = src->next) {
2720                         if (ts_payload_is_matching(ts_r,
2721                                                    upper_layer_protocol,
2722                                                    src->a.ipaddr,
2723                                                    src->prefixlen)) {
2724                                 for (dst = dstlist; dst; dst = dst->next) {
2725                                         if (ts_payload_is_matching(ts_i,
2726                                                                    upper_layer_protocol,
2727                                                                    dst->a.ipaddr,
2728                                                                    dst->prefixlen)) {
2729                                                 goto found;
2730                                         }
2731                                 }
2732                         }
2733                 }
2734 
2735                 continue;
2736 
2737               found:
2738                 ...;
2739 #endif
2740 
2741                 upper_layer_protocol = s->upper_layer_protocol;
2742                 if (id_is_matching(srclist, upper_layer_protocol, id_local)
2743                     && id_is_matching(dstlist, upper_layer_protocol, id_remote)) {
2744                         rcs_free_addrlist(srclist);
2745                         rcs_free_addrlist(dstlist);
2746                         free_selectorlist(s->next);
2747                         return s;
2748                 }
2749 
2750         next_selector:
2751                 if (srclist)
2752                         rcs_free_addrlist(srclist);
2753                 if (dstlist)
2754                         rcs_free_addrlist(dstlist);
2755         }
2756 
2757         return 0;
2758 }
2759 
2760 
2761 struct payload_list *
2762 isakmp_plist_append (struct payload_list *plist, rc_vchar_t *payload, int payload_type)
2763 {
2764         if (! plist) {
2765                 plist = racoon_malloc (sizeof (struct payload_list));
2766                 plist->prev = NULL;
2767         }
2768         else {
2769                 plist->next = racoon_malloc (sizeof (struct payload_list));
2770                 plist->next->prev = plist;
2771                 plist = plist->next;
2772         }
2773 
2774         plist->next = NULL;
2775         plist->payload = payload;
2776         plist->payload_type = payload_type;
2777 
2778         return plist;
2779 }
2780 
2781 rc_vchar_t * 
2782 isakmp_plist_set_all (struct payload_list **plist, struct ph1handle *iph1)
2783 {
2784         struct payload_list *ptr, *first;
2785         size_t tlen = sizeof (struct isakmp), n = 0;
2786         rc_vchar_t *buf;
2787         char *p;
2788 
2789         if (plist == NULL) {
2790                 plog(PLOG_INTERR, PLOGLOC, NULL, 
2791                     "in isakmp_plist_set_all: plist == NULL\n");
2792                 return NULL;
2793         }
2794 
2795         /* Seek to the first item.  */
2796         ptr = *plist;
2797         while (ptr->prev)
2798                 ptr = ptr->prev;
2799         first = ptr;
2800         
2801         /* Compute the whole length.  */
2802         while (ptr) {
2803                 tlen += ptr->payload->l + sizeof (struct isakmp_gen);
2804                 ptr = ptr->next;
2805         }
2806 
2807         buf = rc_vmalloc(tlen);
2808         if (buf == NULL) {
2809                 plog(PLOG_INTERR, PLOGLOC, NULL,
2810                         "failed to get buffer to send.\n");
2811                 goto end;
2812         }
2813 
2814         ptr = first;
2815 
2816         p = set_isakmp_header1(buf, iph1, ptr->payload_type);
2817         if (p == NULL)
2818                 goto end;
2819 
2820         while (ptr)
2821         {
2822                 p = set_isakmp_payload (p, ptr->payload, ptr->next ? ptr->next->payload_type : ISAKMP_NPTYPE_NONE);
2823                 first = ptr;
2824                 ptr = ptr->next;
2825                 racoon_free (first);
2826                 /* ptr->prev = NULL; first = NULL; ... omitted.  */
2827                 n++;
2828         }
2829 
2830         *plist = NULL;
2831 
2832         return buf;
2833 end:
2834         return NULL;
2835 }
2836 
2837 
2838 const char *
2839 ipsec_strerror(void)
2840 {
2841         return "";
2842 }
2843 
2844 void
2845 delete_spd(struct ph2handle *ph2)
2846 {
2847         plog(PLOG_INTWARN, PLOGLOC, 0, "unimplemented\n");
2848 }