1 /*        $NetBSD: isakmp.c,v 1.81 2025/03/08 16:39:08 christos Exp $ */
2 
3 /* Id: isakmp.c,v 1.74 2006/05/07 21:32:59 manubsd Exp */
4 
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include "config.h"
35 
36 #include <sys/types.h>
37 #include <sys/param.h>
38 #include <sys/socket.h>
39 #include <sys/queue.h>
40 
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 
44 #include PATH_IPSEC_H
45 
46 #include <stdlib.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <errno.h>
50 #if TIME_WITH_SYS_TIME
51 # include <sys/time.h>
52 # include <time.h>
53 #else
54 # if HAVE_SYS_TIME_H
55 #  include <sys/time.h>
56 # else
57 #  include <time.h>
58 # endif
59 #endif
60 #include <netdb.h>
61 #ifdef HAVE_UNISTD_H
62 #include <unistd.h>
63 #endif
64 #include <ctype.h>
65 #ifdef ENABLE_HYBRID
66 #include <resolv.h>
67 #endif
68 
69 #include "var.h"
70 #include "misc.h"
71 #include "vmbuf.h"
72 #include "plog.h"
73 #include "sockmisc.h"
74 #include "schedule.h"
75 #include "session.h"
76 #include "debug.h"
77 
78 #include "remoteconf.h"
79 #include "localconf.h"
80 #include "grabmyaddr.h"
81 #include "admin.h"
82 #include "privsep.h"
83 #include "isakmp_var.h"
84 #include "isakmp.h"
85 #include "oakley.h"
86 #include "evt.h"
87 #include "handler.h"
88 #include "ipsec_doi.h"
89 #include "pfkey.h"
90 #include "crypto_openssl.h"
91 #include "policy.h"
92 #include "algorithm.h"
93 #include "proposal.h"
94 #include "sainfo.h"
95 #include "isakmp_ident.h"
96 #include "isakmp_agg.h"
97 #include "isakmp_base.h"
98 #include "isakmp_quick.h"
99 #include "isakmp_inf.h"
100 #include "isakmp_newg.h"
101 #ifdef ENABLE_HYBRID
102 #include "vendorid.h"
103 #include "isakmp_xauth.h"
104 #include "isakmp_unity.h"
105 #include "isakmp_cfg.h"
106 #endif
107 #ifdef ENABLE_FRAG
108 #include "isakmp_frag.h"
109 #endif
110 #include "strnames.h"
111 #include "str2val.h"
112 
113 #include <fcntl.h>
114 
115 #ifdef ENABLE_NATT
116 # include "nattraversal.h"
117 #endif
118 # ifdef __linux__
119 #  include <linux/udp.h>
120 #  include <linux/ip.h>
121 #  ifndef SOL_UDP
122 #   define SOL_UDP 17
123 #  endif
124 # endif /* __linux__ */
125 # if defined(__NetBSD__) || defined(__FreeBSD__) ||         \
126   (defined(__APPLE__) && defined(__MACH__))
127 #  include <netinet/in.h>
128 #  include <netinet/udp.h>
129 #  include <netinet/in_systm.h>
130 #  include <netinet/ip.h>
131 #  define SOL_UDP IPPROTO_UDP
132 # endif /* __NetBSD__ / __FreeBSD__ */
133 
134 static int nostate1(struct ph1handle *, vchar_t *);
135 static int nostate2(struct ph2handle *, vchar_t *);
136 
137 static int (*ph1exchange[][2][PHASE1ST_MAX])(struct ph1handle *, vchar_t *) = {
138  /* error */
139  { { 0 }, { 0 }, },
140  /* Identity Protection exchange */
141  {
142   { nostate1, ident_i1send, nostate1, ident_i2recv, ident_i2send,
143     ident_i3recv, ident_i3send, ident_i4recv, ident_i4send, nostate1, nostate1,},
144   { nostate1, ident_r1recv, ident_r1send, ident_r2recv, ident_r2send,
145     ident_r3recv, ident_r3send, nostate1, nostate1, nostate1, nostate1, },
146  },
147  /* Aggressive exchange */
148  {
149   { nostate1, agg_i1send, nostate1, agg_i2recv, agg_i2send,
150     nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, },
151   { nostate1, agg_r1recv, agg_r1send, agg_r2recv, agg_r2send,
152     nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, },
153  },
154  /* Base exchange */
155  {
156   { nostate1, base_i1send, nostate1, base_i2recv, base_i2send,
157     base_i3recv, base_i3send, nostate1, nostate1, nostate1, nostate1, },
158   { nostate1, base_r1recv, base_r1send, base_r2recv, base_r2send,
159     nostate1, nostate1, nostate1, nostate1, nostate1, nostate1, },
160  },
161 };
162 
163 static int (*ph2exchange[][2][PHASE2ST_MAX])(struct ph2handle *, vchar_t *) = {
164  /* error */
165  { { 0 }, { 0 }, },
166  /* Quick mode for IKE */
167  {
168   { nostate2, nostate2, quick_i1prep, nostate2, quick_i1send,
169     quick_i2recv, quick_i2send, quick_i3recv, nostate2, nostate2, },
170   { nostate2, quick_r1recv, quick_r1prep, nostate2, quick_r2send,
171     quick_r3recv, quick_r3prep, quick_r3send, nostate2, nostate2, }
172  },
173 };
174 
175 static u_char r_ck0[] = { 0,0,0,0,0,0,0,0 }; /* used to verify the r_ck. */
176 
177 static int isakmp_main(vchar_t *, struct sockaddr *, struct sockaddr *);
178 static int ph1_main(struct ph1handle *, vchar_t *);
179 static int quick_main(struct ph2handle *, vchar_t *);
180 static int isakmp_ph1begin_r(vchar_t *, struct sockaddr *, struct sockaddr *,
181     uint8_t);
182 static int isakmp_ph2begin_i(struct ph1handle *, struct ph2handle *);
183 static int isakmp_ph2begin_r(struct ph1handle *, vchar_t *);
184 static int etypesw1(int);
185 static int etypesw2(int);
186 static int isakmp_ph1resend(struct ph1handle *);
187 static int isakmp_ph2resend(struct ph2handle *);
188 
189 #ifdef ENABLE_FRAG
190 static int frag_handler(struct ph1handle *,
191     vchar_t *, struct sockaddr *, struct sockaddr *);
192 #endif
193 
194 /*
195  * isakmp packet handler
196  */
197 /*ARGSUSED*/
198 static int
isakmp_handler(void * ctx __unused,int so_isakmp)199 isakmp_handler(void *ctx __unused, int so_isakmp)
200 {
201           struct isakmp isakmp;
202           union {
203                     char                buf[sizeof (isakmp) + 4];
204                     uint32_t  non_esp[2];
205                     struct              {
206                                              struct udphdr udp;
207 #ifdef __linux
208                                              struct iphdr ip;
209 #else
210                                              struct ip ip;
211 #endif
212                                              char buf[sizeof(isakmp) + 4];
213                                         } lbuf;
214           } x;
215           struct sockaddr_storage remote;
216           struct sockaddr_storage local;
217           unsigned int remote_len = sizeof(remote);
218           unsigned int local_len = sizeof(local);
219           ssize_t len = 0;
220           int extralen = 0;
221           vchar_t *buf = NULL, *tmpbuf = NULL;
222           int error = -1, res;
223 
224           /* read message by MSG_PEEK */
225           while ((len = recvfromto(so_isakmp, x.buf, sizeof(x),
226                         MSG_PEEK, (struct sockaddr *)&remote, &remote_len,
227                         (struct sockaddr *)&local, &local_len)) < 0) {
228                     if (errno == EINTR)
229                               continue;
230                     plog(LLV_ERROR, LOCATION, NULL,
231                               "failed to receive isakmp packet: %s\n",
232                               strerror (errno));
233                     goto end;
234           }
235 
236           /* keep-alive packet - ignore */
237           if (len == 1 && (x.buf[0]&0xff) == 0xff) {
238                     /* Pull the keep-alive packet */
239                     if ((len = recvfrom(so_isakmp, (char *)x.buf, 1,
240                         0, (struct sockaddr *)&remote, &remote_len)) != 1) {
241                               plog(LLV_ERROR, LOCATION, NULL,
242                                   "failed to receive keep alive packet: %s\n",
243                                   strerror (errno));
244                     }
245                     goto end;
246           }
247 
248           /* Lucent IKE in UDP encapsulation */
249           {
250 #ifdef __linux__
251                     if (ntohs(x.lbuf.udp.dest) == 501) {
252                               extralen += sizeof(x.lbuf.udp) + x.lbuf.ip.ihl;
253                     }
254 #else
255                     if (ntohs(x.lbuf.udp.uh_dport) == 501) {
256                               extralen += sizeof(x.lbuf.udp) + x.lbuf.ip.ip_hl;
257                     }
258 #endif
259           }
260 
261 #ifdef ENABLE_NATT
262           /* we don't know about portchange yet,
263              look for non-esp marker instead */
264           if (x.non_esp[0] == 0 && x.non_esp[1] != 0)
265                     extralen = NON_ESP_MARKER_LEN;
266 #endif
267 
268           /* now we know if there is an extra non-esp
269              marker at the beginning or not */
270           memcpy ((char *)&isakmp, x.buf + extralen, sizeof (isakmp));
271 
272           /* check isakmp header length, as well as sanity of header length */
273           if (len < sizeof(isakmp) || ntohl(isakmp.len) < sizeof(isakmp)) {
274                     plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
275                         "packet shorter than isakmp header size (%zu, %u, %zu)\n",
276                         len, ntohl(isakmp.len), sizeof(isakmp));
277                     /* dummy receive */
278                     if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
279                                   0, (struct sockaddr *)&remote, &remote_len)) < 0) {
280                               plog(LLV_ERROR, LOCATION, NULL,
281                                         "failed to receive isakmp packet: %s\n",
282                                         strerror (errno));
283                     }
284                     goto end;
285           }
286 
287           /* reject it if the size is tooooo big. */
288           if (ntohl(isakmp.len) > 0xffff) {
289                     plog(LLV_ERROR, LOCATION, NULL,
290                               "the length in the isakmp header is too big.\n");
291                     if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
292                                   0, (struct sockaddr *)&remote, &remote_len)) < 0) {
293                               plog(LLV_ERROR, LOCATION, NULL,
294                                         "failed to receive isakmp packet: %s\n",
295                                         strerror (errno));
296                     }
297                     goto end;
298           }
299 
300           /* read real message */
301           if ((tmpbuf = vmalloc(ntohl(isakmp.len) + extralen)) == NULL) {
302                     plog(LLV_ERROR, LOCATION, NULL,
303                               "failed to allocate reading buffer (%u Bytes)\n",
304                               ntohl(isakmp.len) + extralen);
305                     /* dummy receive */
306                     if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
307                                   0, (struct sockaddr *)&remote, &remote_len)) < 0) {
308                               plog(LLV_ERROR, LOCATION, NULL,
309                                         "failed to receive isakmp packet: %s\n",
310                                         strerror (errno));
311                     }
312                     goto end;
313           }
314 
315           while ((len = recvfromto(so_isakmp, (char *)tmpbuf->v, tmpbuf->l,
316                               0, (struct sockaddr *)&remote, &remote_len,
317                               (struct sockaddr *)&local, &local_len)) < 0) {
318                     if (errno == EINTR)
319                               continue;
320                     plog(LLV_ERROR, LOCATION, NULL,
321                               "failed to receive isakmp packet: %s\n",
322                               strerror (errno));
323                     goto end;
324           }
325 
326           if ((buf = vmalloc(len - extralen)) == NULL) {
327                     plog(LLV_ERROR, LOCATION, NULL,
328                               "failed to allocate reading buffer (%zu Bytes)\n",
329                               (len - extralen));
330                     goto end;
331           }
332 
333           memcpy (buf->v, tmpbuf->v + extralen, buf->l);
334 
335           len -= extralen;
336 
337           if (len != buf->l) {
338                     plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
339                               "received invalid length (%zd != %zu), why ?\n",
340                               len, buf->l);
341                     goto end;
342           }
343 
344           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
345           plog(LLV_DEBUG, LOCATION, NULL,
346                     "%zd bytes message received %s\n",
347                     len, saddr2str_fromto("from %s to %s",
348                               (struct sockaddr *)&remote,
349                               (struct sockaddr *)&local));
350           plogdump(LLV_DEBUG, buf->v, buf->l);
351 
352           /* avoid packets with malicious port/address */
353           if (extract_port((struct sockaddr *)&remote) == 0) {
354                     plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
355                               "src port == 0 (valid as UDP but not with IKE)\n");
356                     goto end;
357           }
358 
359           /* XXX: check sender whether to be allowed or not to accept */
360 
361           /* XXX: I don't know how to check isakmp half connection attack. */
362 
363           /* simply reply if the packet was processed. */
364           res=check_recvdpkt((struct sockaddr *)&remote,(struct sockaddr *)&local, buf);
365           if (res) {
366                     plog(LLV_NOTIFY, LOCATION, NULL,
367                               "the packet is retransmitted by %s (%d).\n",
368                                saddr2str((struct sockaddr *)&remote), res);
369                     error = 0;
370                     goto end;
371           }
372 
373           /* isakmp main routine */
374           if (isakmp_main(buf, (struct sockaddr *)&remote,
375                               (struct sockaddr *)&local) != 0) goto end;
376 
377           error = 0;
378 
379 end:
380           if (tmpbuf != NULL)
381                     vfree(tmpbuf);
382           if (buf != NULL)
383                     vfree(buf);
384           return error;
385 }
386 
387 /*
388  * main processing to handle isakmp payload
389  */
390 static int
isakmp_main(vchar_t * msg,struct sockaddr * remote,struct sockaddr * local)391 isakmp_main(vchar_t *msg, struct sockaddr *remote, struct sockaddr *local)
392 {
393           struct isakmp *isakmp = (struct isakmp *)msg->v;
394           isakmp_index *index1 = (isakmp_index *)isakmp;
395           uint32_t msgid = isakmp->msgid;
396           struct ph1handle *iph1;
397 
398 #ifdef HAVE_PRINT_ISAKMP_C
399           isakmp_printpacket(msg, remote, local, 0);
400 #endif
401 
402           /* the initiator's cookie must not be zero */
403           if (memcmp(&isakmp->i_ck, r_ck0, sizeof(cookie_t)) == 0) {
404                     plog(LLV_ERROR, LOCATION, remote,
405                               "malformed cookie received.\n");
406                     return -1;
407           }
408 
409           /* Check the Major and Minor Version fields. */
410           /*
411            * XXX Is is right to check version here ?
412            * I think it may no be here because the version depends
413            * on exchange status.
414            */
415           if (isakmp->v < ISAKMP_VERSION_NUMBER) {
416                     if (ISAKMP_GETMAJORV(isakmp->v) < ISAKMP_MAJOR_VERSION) {
417                               plog(LLV_ERROR, LOCATION, remote,
418                                         "invalid major version %d.\n",
419                                         ISAKMP_GETMAJORV(isakmp->v));
420                               return -1;
421                     }
422 #if ISAKMP_MINOR_VERSION > 0
423                     if (ISAKMP_GETMINORV(isakmp->v) < ISAKMP_MINOR_VERSION) {
424                               plog(LLV_ERROR, LOCATION, remote,
425                                         "invalid minor version %d.\n",
426                                         ISAKMP_GETMINORV(isakmp->v));
427                               return -1;
428                     }
429 #endif
430           }
431 
432           /* check the Flags field. */
433           /* XXX How is the exclusive check, E and A ? */
434           if (isakmp->flags & ~(ISAKMP_FLAG_E | ISAKMP_FLAG_C | ISAKMP_FLAG_A)) {
435                     plog(LLV_ERROR, LOCATION, remote,
436                               "invalid flag 0x%02x.\n", isakmp->flags);
437                     return -1;
438           }
439 
440           /* ignore commit bit. */
441           if (ISSET(isakmp->flags, ISAKMP_FLAG_C)) {
442                     if (isakmp->msgid == 0) {
443                               isakmp_info_send_nx(isakmp, remote, local,
444                                         ISAKMP_NTYPE_INVALID_FLAGS, NULL);
445                               plog(LLV_ERROR, LOCATION, remote,
446                                         "Commit bit on phase1 forbidden.\n");
447                               return -1;
448                     }
449           }
450 
451           iph1 = getph1byindex(index1);
452           if (iph1 != NULL) {
453                     /* validity check */
454                     if (memcmp(&isakmp->r_ck, r_ck0, sizeof(cookie_t)) == 0 &&
455                         iph1->side == INITIATOR) {
456                               plog(LLV_DEBUG, LOCATION, remote,
457                                         "malformed cookie received or "
458                                         "the initiator's cookies collide.\n");
459                               return -1;
460                     }
461 
462 #ifdef ENABLE_NATT
463                     /* Floating ports for NAT-T */
464                     if (NATT_AVAILABLE(iph1) &&
465                         ! (iph1->natt_flags & NAT_PORTS_CHANGED) &&
466                         ((cmpsaddr(iph1->remote, remote) != CMPSADDR_MATCH) ||
467                          (cmpsaddr(iph1->local, local) != CMPSADDR_MATCH)))
468                     {
469                               /* prevent memory leak */
470                               racoon_free(iph1->remote);
471                               racoon_free(iph1->local);
472                               iph1->remote = NULL;
473                               iph1->local = NULL;
474 
475                               /* copy-in new addresses */
476                               iph1->remote = dupsaddr(remote);
477                               if (iph1->remote == NULL) {
478                                         plog(LLV_ERROR, LOCATION, iph1->remote,
479                                            "phase1 failed: dupsaddr failed.\n");
480                                         remph1(iph1);
481                                         delph1(iph1);
482                                         return -1;
483                               }
484                               iph1->local = dupsaddr(local);
485                               if (iph1->local == NULL) {
486                                         plog(LLV_ERROR, LOCATION, iph1->remote,
487                                            "phase1 failed: dupsaddr failed.\n");
488                                         remph1(iph1);
489                                         delph1(iph1);
490                                         return -1;
491                               }
492 
493                               /* set the flag to prevent further port floating
494                                  (FIXME: should we allow it? E.g. when the NAT gw
495                                   is rebooted?) */
496                               iph1->natt_flags |= NAT_PORTS_CHANGED | NAT_ADD_NON_ESP_MARKER;
497 
498                               /* print some neat info */
499                               plog (LLV_INFO, LOCATION, NULL,
500                                     "NAT-T: ports changed to: %s\n",
501                                     saddr2str_fromto ("%s<->%s", iph1->remote, iph1->local));
502 
503                               natt_keepalive_add_ph1 (iph1);
504                     }
505 #endif
506 
507                     /* must be same addresses in one stream of a phase at least. */
508                     if (cmpsaddr(iph1->remote, remote) != CMPSADDR_MATCH) {
509                               char *saddr_db, *saddr_act;
510 
511                               saddr_db = racoon_strdup(saddr2str(iph1->remote));
512                               saddr_act = racoon_strdup(saddr2str(remote));
513                               STRDUP_FATAL(saddr_db);
514                               STRDUP_FATAL(saddr_act);
515 
516                               plog(LLV_WARNING, LOCATION, remote,
517                                         "remote address mismatched. db=%s, act=%s\n",
518                                         saddr_db, saddr_act);
519 
520                               racoon_free(saddr_db);
521                               racoon_free(saddr_act);
522                     }
523 
524                     /*
525                      * don't check of exchange type here because other type will be
526                      * with same index, for example, informational exchange.
527                      */
528 
529                     /* XXX more acceptable check */
530           }
531 
532           switch (isakmp->etype) {
533           case ISAKMP_ETYPE_IDENT:
534           case ISAKMP_ETYPE_AGG:
535           case ISAKMP_ETYPE_BASE:
536                     /* phase 1 validity check */
537                     if (isakmp->msgid != 0) {
538                               plog(LLV_ERROR, LOCATION, remote,
539                                         "message id should be zero in phase1.\n");
540                               return -1;
541                     }
542 
543                     /* search for isakmp status record of phase 1 */
544                     if (iph1 == NULL) {
545                               /*
546                                * the packet must be the 1st message from a initiator
547                                * or the 2nd message from the responder.
548                                */
549 
550                               /* search for phase1 handle by index without r_ck */
551                               iph1 = getph1byindex0(index1);
552                               if (iph1 == NULL) {
553                                         /*it must be the 1st message from a initiator.*/
554                                         if (memcmp(&isakmp->r_ck, r_ck0,
555                                                   sizeof(cookie_t)) != 0) {
556 
557                                                   plog(LLV_DEBUG, LOCATION, remote,
558                                                             "malformed cookie received "
559                                                             "or the spi expired.\n");
560                                                   return -1;
561                                         }
562 
563                                         /* it must be responder's 1st exchange. */
564                                         if (isakmp_ph1begin_r(msg, remote, local,
565                                                   isakmp->etype) < 0)
566                                                   return -1;
567                                         break;
568 
569                                         /*NOTREACHED*/
570                               }
571 
572                               /* it must be the 2nd message from the responder. */
573                               if (iph1->side != INITIATOR) {
574                                         plog(LLV_DEBUG, LOCATION, remote,
575                                                   "malformed cookie received. "
576                                                   "it has to be as the initiator.  %s\n",
577                                                   isakmp_pindex(&iph1->index, 0));
578                                         return -1;
579                               }
580                     }
581 
582                     /*
583                      * Don't delete phase 1 handler when the exchange type
584                      * in handler is not equal to packet's one because of no
585                      * authencication completed.
586                      */
587                     if (iph1->etype != isakmp->etype) {
588                               plog(LLV_ERROR, LOCATION, iph1->remote,
589                                         "exchange type is mismatched: "
590                                         "db=%s packet=%s, ignore it.\n",
591                                         s_isakmp_etype(iph1->etype),
592                                         s_isakmp_etype(isakmp->etype));
593                               return -1;
594                     }
595 
596 #ifdef ENABLE_FRAG
597                     if (isakmp->np == ISAKMP_NPTYPE_FRAG)
598                               return frag_handler(iph1, msg, remote, local);
599 #endif
600 
601                     /* call main process of phase 1 */
602                     if (ph1_main(iph1, msg) < 0) {
603                               plog(LLV_ERROR, LOCATION, iph1->remote,
604                                         "phase1 negotiation failed.\n");
605                               remph1(iph1);
606                               delph1(iph1);
607                               return -1;
608                     }
609                     break;
610 
611           case ISAKMP_ETYPE_AUTH:
612                     plog(LLV_INFO, LOCATION, remote,
613                               "unsupported exchange %d received.\n",
614                               isakmp->etype);
615                     break;
616 
617           case ISAKMP_ETYPE_INFO:
618           case ISAKMP_ETYPE_ACKINFO:
619                     /*
620                      * iph1 must be present for Information message.
621                      * if iph1 is null then trying to get the phase1 status
622                      * as the packet from responder again initiator's 1st
623                      * exchange in phase 1.
624                      * NOTE: We think such informational exchange should be ignored.
625                      */
626                     if (iph1 == NULL) {
627                               iph1 = getph1byindex0(index1);
628                               if (iph1 == NULL) {
629                                         plog(LLV_ERROR, LOCATION, remote,
630                                                   "unknown Informational "
631                                                   "exchange received.\n");
632                                         return -1;
633                               }
634                               if (cmpsaddr(iph1->remote, remote) != CMPSADDR_MATCH) {
635                                         plog(LLV_WARNING, LOCATION, remote,
636                                                   "remote address mismatched. "
637                                                   "db=%s\n",
638                                                   saddr2str(iph1->remote));
639                               }
640                     }
641 
642 #ifdef ENABLE_FRAG
643                     if (isakmp->np == ISAKMP_NPTYPE_FRAG)
644                               return frag_handler(iph1, msg, remote, local);
645 #endif
646 
647                     if (isakmp_info_recv(iph1, msg) < 0)
648                               return -1;
649                     break;
650 
651           case ISAKMP_ETYPE_QUICK:
652           {
653                     struct ph2handle *iph2;
654 
655                     if (iph1 == NULL) {
656                               isakmp_info_send_nx(isakmp, remote, local,
657                                         ISAKMP_NTYPE_INVALID_COOKIE, NULL);
658                               plog(LLV_ERROR, LOCATION, remote,
659                                         "can't start the quick mode, "
660                                         "there is no ISAKMP-SA, %s\n",
661                                         isakmp_pindex((isakmp_index *)&isakmp->i_ck,
662                                                   isakmp->msgid));
663                               return -1;
664                     }
665 #ifdef ENABLE_HYBRID
666                     /* Reinit the IVM if it's still there */
667                     if (iph1->mode_cfg && iph1->mode_cfg->ivm) {
668                               oakley_delivm(iph1->mode_cfg->ivm);
669                               iph1->mode_cfg->ivm = NULL;
670                     }
671 #endif
672 #ifdef ENABLE_FRAG
673                     if (isakmp->np == ISAKMP_NPTYPE_FRAG)
674                               return frag_handler(iph1, msg, remote, local);
675 #endif
676 
677                     /* check status of phase 1 whether negotiated or not. */
678                     if (iph1->status != PHASE1ST_ESTABLISHED &&
679                         iph1->status != PHASE1ST_DYING) {
680                               plog(LLV_ERROR, LOCATION, remote,
681                                         "can't start the quick mode, "
682                                         "there is no valid ISAKMP-SA, %s\n",
683                                         isakmp_pindex(&iph1->index, iph1->msgid));
684                               return -1;
685                     }
686 
687                     /* search isakmp phase 2 status record. */
688                     iph2 = getph2bymsgid(iph1, msgid);
689                     if (iph2 == NULL) {
690                               /* it must be new negotiation as responder */
691                               if (isakmp_ph2begin_r(iph1, msg) < 0)
692                                         return -1;
693                               return 0;
694                               /*NOTREACHED*/
695                     }
696 
697                     /* commit bit. */
698                     /* XXX
699                      * we keep to set commit bit during negotiation.
700                      * When SA is configured, bit will be reset.
701                      * XXX
702                      * don't initiate commit bit.  should be fixed in the future.
703                      */
704                     if (ISSET(isakmp->flags, ISAKMP_FLAG_C))
705                               iph2->flags |= ISAKMP_FLAG_C;
706 
707                     /* call main process of quick mode */
708                     if (quick_main(iph2, msg) < 0) {
709                               plog(LLV_ERROR, LOCATION, iph1->remote,
710                                         "phase2 negotiation failed.\n");
711                               remph2(iph2);
712                               delph2(iph2);
713                               return -1;
714                     }
715           }
716                     break;
717 
718           case ISAKMP_ETYPE_NEWGRP:
719                     if (iph1 == NULL) {
720                               plog(LLV_ERROR, LOCATION, remote,
721                                         "Unknown new group mode exchange, "
722                                         "there is no ISAKMP-SA.\n");
723                               return -1;
724                     }
725 
726 #ifdef ENABLE_FRAG
727                     if (isakmp->np == ISAKMP_NPTYPE_FRAG)
728                               return frag_handler(iph1, msg, remote, local);
729 #endif
730 
731                     isakmp_newgroup_r(iph1, msg);
732                     break;
733 
734 #ifdef ENABLE_HYBRID
735           case ISAKMP_ETYPE_CFG:
736                     if (iph1 == NULL) {
737                               plog(LLV_ERROR, LOCATION, NULL,
738                                    "mode config %d from %s, "
739                                    "but we have no ISAKMP-SA.\n",
740                                    isakmp->etype, saddr2str(remote));
741                               return -1;
742                     }
743 
744 #ifdef ENABLE_FRAG
745                     if (isakmp->np == ISAKMP_NPTYPE_FRAG)
746                               return frag_handler(iph1, msg, remote, local);
747 #endif
748 
749                     isakmp_cfg_r(iph1, msg);
750                     break;
751 #endif
752 
753           case ISAKMP_ETYPE_NONE:
754           default:
755                     plog(LLV_ERROR, LOCATION, NULL,
756                               "Invalid exchange type %d from %s.\n",
757                               isakmp->etype, saddr2str(remote));
758                     return -1;
759           }
760 
761           return 0;
762 }
763 
764 /*
765  * main function of phase 1.
766  */
767 static int
ph1_main(struct ph1handle * iph1,vchar_t * msg)768 ph1_main(struct ph1handle *iph1, vchar_t *msg)
769 {
770           int error;
771 #ifdef ENABLE_STATS
772           struct timeval start, end;
773 #endif
774 
775           /* ignore a packet */
776           if (iph1->status >= PHASE1ST_ESTABLISHED)
777                     return 0;
778 
779 #ifdef ENABLE_STATS
780           gettimeofday(&start, NULL);
781 #endif
782           /* receive */
783           if (ph1exchange[etypesw1(iph1->etype)]
784                            [iph1->side]
785                            [iph1->status] == NULL) {
786                     plog(LLV_ERROR, LOCATION, iph1->remote,
787                               "why isn't the function defined.\n");
788                     return -1;
789           }
790           error = (ph1exchange[etypesw1(iph1->etype)]
791                                   [iph1->side]
792                                   [iph1->status])(iph1, msg);
793           if (error != 0) {
794 
795                     /* XXX
796                      * When an invalid packet is received on phase1, it should
797                      * be selected to process this packet.  That is to respond
798                      * with a notify and delete phase 1 handler, OR not to respond
799                      * and keep phase 1 handler. However, in PHASE1ST_START when
800                      * acting as RESPONDER we must not keep phase 1 handler or else
801                      * it will stay forever.
802                      */
803 
804                     if (iph1->side == RESPONDER && iph1->status == PHASE1ST_START) {
805                               plog(LLV_ERROR, LOCATION, iph1->remote,
806                                         "failed to pre-process ph1 packet (side: %d, status %d).\n",
807                                         iph1->side, iph1->status);
808                               return -1;
809                     } else {
810                               /* ignore the error and keep phase 1 handler */
811                               return 0;
812                     }
813           }
814 
815 #ifndef ENABLE_FRAG
816           /* free resend buffer */
817           if (iph1->sendbuf == NULL) {
818                     plog(LLV_ERROR, LOCATION, NULL,
819                               "no buffer found as sendbuf\n");
820                     return -1;
821           }
822 #endif
823 
824           VPTRINIT(iph1->sendbuf);
825 
826           /* turn off schedule */
827           sched_cancel(&iph1->scr);
828 
829           /* send */
830           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
831           if ((ph1exchange[etypesw1(iph1->etype)]
832                               [iph1->side]
833                               [iph1->status])(iph1, msg) != 0) {
834                     plog(LLV_ERROR, LOCATION, iph1->remote,
835                               "failed to process ph1 packet (side: %d, status: %d).\n",
836                               iph1->side, iph1->status);
837                     return -1;
838           }
839 
840 #ifdef ENABLE_STATS
841           gettimeofday(&end, NULL);
842           syslog(LOG_NOTICE, "%s(%s): %8.6f",
843                     "phase1", s_isakmp_state(iph1->etype, iph1->side, iph1->status),
844                     timedelta(&start, &end));
845 #endif
846           if (iph1->status == PHASE1ST_ESTABLISHED) {
847 
848 #ifdef ENABLE_STATS
849                     gettimeofday(&iph1->end, NULL);
850                     syslog(LOG_NOTICE, "%s(%s): %8.6f",
851                               "phase1", s_isakmp_etype(iph1->etype),
852                               timedelta(&iph1->start, &iph1->end));
853 #endif
854 
855                     /* save created date. */
856                     (void)time(&iph1->created);
857 
858                     /* migrate ph2s from dying ph1s */
859                     migrate_dying_ph12(iph1);
860 
861                     /* add to the schedule to expire, and seve back pointer. */
862                     if (ph1_rekey_enabled(iph1)) {
863                               sched_schedule(&iph1->sce,
864                                                iph1->approval->lifetime *
865                                                PFKEY_SOFT_LIFETIME_RATE / 100,
866                                                isakmp_ph1dying_stub);
867                     } else {
868                               sched_schedule(&iph1->sce, iph1->approval->lifetime,
869                                                isakmp_ph1expire_stub);
870                     }
871 
872 #ifdef ENABLE_HYBRID
873                     if (iph1->mode_cfg->flags & ISAKMP_CFG_VENDORID_XAUTH) {
874                               switch (iph1->approval->authmethod) {
875                               case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
876                               case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
877                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
878                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
879                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
880                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
881                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
882                                         xauth_sendreq(iph1);
883                                         /* XXX Don't process INITIAL_CONTACT */
884                                         iph1->rmconf->ini_contact = 0;
885                                         break;
886                               case OAKLEY_ATTR_AUTH_METHOD_RSASIG:
887                                         if (iph1->rmconf->mode_cfg)
888                                                   error = isakmp_cfg_getconfig(iph1);
889                                         break;
890                               default:
891                                         break;
892                               }
893                     }
894 #endif
895 #ifdef ENABLE_DPD
896                     /* Schedule the r_u_there.... */
897                     if(iph1->dpd_support && iph1->rmconf->dpd_interval)
898                               isakmp_sched_r_u(iph1, 0);
899 #endif
900 
901                     /* INITIAL-CONTACT processing */
902                     /* don't anything if local test mode. */
903                     if (!f_local
904                      && iph1->rmconf->ini_contact && !getcontacted(iph1->remote)) {
905                               /* send INITIAL-CONTACT */
906                               isakmp_info_send_n1(iph1,
907                                                   ISAKMP_NTYPE_INITIAL_CONTACT, NULL);
908                               /* insert a node into contacted list. */
909                               if (inscontacted(iph1->remote) == -1) {
910                                         plog(LLV_ERROR, LOCATION, iph1->remote,
911                                                   "failed to add contacted list.\n");
912                                         /* ignore */
913                               }
914                     }
915                     if (iph1->initial_contact_received)
916                               isakmp_info_recv_initialcontact(iph1, NULL);
917 
918                     log_ph1established(iph1);
919                     plog(LLV_DEBUG, LOCATION, NULL, "===\n");
920 
921                     /*
922                      * SA up shell script hook: do it now,except if
923                      * ISAKMP mode config was requested. In the later
924                      * case it is done when we receive the configuration.
925                      */
926                     if ((iph1->status == PHASE1ST_ESTABLISHED) &&
927                         !iph1->rmconf->mode_cfg) {
928                               switch (iph1->approval->authmethod) {
929 #ifdef ENABLE_HYBRID
930                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
931                               case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
932                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
933                               /* Unimplemeted... */
934                               case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
935                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
936                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
937                               case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
938                                         break;
939 #endif
940                               default:
941                                         script_hook(iph1, SCRIPT_PHASE1_UP);
942                                         break;
943                               }
944                     }
945                     if ((iph1->rmconf->mode_cfg) &&
946                         !(iph1->mode_cfg->flags & ISAKMP_CFG_VENDORID_XAUTH)) {
947                               error = isakmp_cfg_getconfig(iph1);
948                     }
949           }
950 
951           return 0;
952 }
953 
954 /*
955  * main function of quick mode.
956  */
957 static int
quick_main(struct ph2handle * iph2,vchar_t * msg)958 quick_main(struct ph2handle *iph2, vchar_t *msg)
959 {
960           struct isakmp *isakmp = (struct isakmp *)msg->v;
961           int error;
962 #ifdef ENABLE_STATS
963           struct timeval start, end;
964 #endif
965 
966           /* ignore a packet */
967           if (iph2->status == PHASE2ST_ESTABLISHED
968            || iph2->status == PHASE2ST_GETSPISENT)
969                     return 0;
970 
971 #ifdef ENABLE_STATS
972           gettimeofday(&start, NULL);
973 #endif
974 
975           /* receive */
976           if (ph2exchange[etypesw2(isakmp->etype)]
977                            [iph2->side]
978                            [iph2->status] == NULL) {
979                     plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
980                               "why isn't the function defined.\n");
981                     return -1;
982           }
983           error = (ph2exchange[etypesw2(isakmp->etype)]
984                                   [iph2->side]
985                                   [iph2->status])(iph2, msg);
986           if (error != 0) {
987                     plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
988                               "failed to pre-process ph2 packet (side: %d, status %d).\n",
989                               iph2->side, iph2->status);
990                     if (error == ISAKMP_INTERNAL_ERROR)
991                               return 0;
992                     isakmp_info_send_n1(iph2->ph1, error, NULL);
993                     return -1;
994           }
995 
996           /* when using commit bit, status will be reached here. */
997           if (iph2->status == PHASE2ST_ADDSA)
998                     return 0;
999 
1000           /* free resend buffer */
1001           if (iph2->sendbuf == NULL) {
1002                     plog(LLV_ERROR, LOCATION, NULL,
1003                               "no buffer found as sendbuf\n");
1004                     return -1;
1005           }
1006           VPTRINIT(iph2->sendbuf);
1007 
1008           /* turn off schedule */
1009           sched_cancel(&iph2->scr);
1010 
1011           /* send */
1012           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1013           if ((ph2exchange[etypesw2(isakmp->etype)]
1014                               [iph2->side]
1015                               [iph2->status])(iph2, msg) != 0) {
1016                     plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
1017                               "failed to process ph2 packet (side: %d, status: %d).\n",
1018                               iph2->side, iph2->status);
1019                     return -1;
1020           }
1021 
1022 #ifdef ENABLE_STATS
1023           gettimeofday(&end, NULL);
1024           syslog(LOG_NOTICE, "%s(%s): %8.6f",
1025                     "phase2",
1026                     s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
1027                     timedelta(&start, &end));
1028 #endif
1029 
1030           return 0;
1031 }
1032 
1033 /* new negotiation of phase 1 for initiator */
1034 struct ph1handle *
isakmp_ph1begin_i(struct remoteconf * rmconf,struct sockaddr * remote,struct sockaddr * local)1035 isakmp_ph1begin_i(struct remoteconf *rmconf,
1036     struct sockaddr *remote, struct sockaddr *local)
1037 {
1038           struct ph1handle *iph1;
1039 #ifdef ENABLE_STATS
1040           struct timeval start, end;
1041 #endif
1042 
1043           /* get new entry to isakmp status table. */
1044           iph1 = newph1();
1045           if (iph1 == NULL)
1046                     return NULL;
1047 
1048           iph1->status = PHASE1ST_START;
1049           iph1->rmconf = rmconf;
1050           iph1->side = INITIATOR;
1051           iph1->version = ISAKMP_VERSION_NUMBER;
1052           iph1->msgid = 0;
1053           iph1->flags = 0;
1054           iph1->ph2cnt = 0;
1055 #ifdef HAVE_GSSAPI
1056           iph1->gssapi_state = NULL;
1057 #endif
1058 #ifdef ENABLE_HYBRID
1059           if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL) {
1060                     delph1(iph1);
1061                     return NULL;
1062           }
1063 #endif
1064 #ifdef ENABLE_FRAG
1065 
1066           if(rmconf->ike_frag == ISAKMP_FRAG_FORCE)
1067                     iph1->frag = 1;
1068           else
1069                     iph1->frag = 0;
1070           iph1->frag_last_index = 0;
1071           iph1->frag_chain = NULL;
1072 #endif
1073           iph1->approval = NULL;
1074 
1075           /* XXX copy remote address */
1076           if (copy_ph1addresses(iph1, rmconf, remote, local) < 0) {
1077                     delph1(iph1);
1078                     return NULL;
1079           }
1080 
1081           (void)insph1(iph1);
1082 
1083           /* start phase 1 exchange */
1084           iph1->etype = rmconf->etypes->type;
1085 
1086           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1087     {
1088           char *a;
1089 
1090           a = racoon_strdup(saddr2str(iph1->local));
1091           STRDUP_FATAL(a);
1092 
1093           plog(LLV_INFO, LOCATION, NULL,
1094                     "initiate new phase 1 negotiation: %s<=>%s\n",
1095                     a, saddr2str(iph1->remote));
1096           racoon_free(a);
1097     }
1098           plog(LLV_INFO, LOCATION, NULL,
1099                     "begin %s mode.\n",
1100                     s_isakmp_etype(iph1->etype));
1101 
1102 #ifdef ENABLE_STATS
1103           gettimeofday(&iph1->start, NULL);
1104           gettimeofday(&start, NULL);
1105 #endif
1106           /* start exchange */
1107           if ((ph1exchange[etypesw1(iph1->etype)]
1108                               [iph1->side]
1109                               [iph1->status])(iph1, NULL) != 0) {
1110                     /* failed to start phase 1 negotiation */
1111                     remph1(iph1);
1112                     delph1(iph1);
1113 
1114                     return NULL;
1115           }
1116 
1117 #ifdef ENABLE_STATS
1118           gettimeofday(&end, NULL);
1119           syslog(LOG_NOTICE, "%s(%s): %8.6f",
1120                     "phase1",
1121                     s_isakmp_state(iph1->etype, iph1->side, iph1->status),
1122                     timedelta(&start, &end));
1123 #endif
1124 
1125           return iph1;
1126 }
1127 
1128 /* new negotiation of phase 1 for responder */
1129 static int
isakmp_ph1begin_r(vchar_t * msg,struct sockaddr * remote,struct sockaddr * local,uint8_t etype)1130 isakmp_ph1begin_r(vchar_t *msg, struct sockaddr *remote, struct sockaddr *local,
1131     uint8_t etype)
1132 {
1133           struct isakmp *isakmp = (struct isakmp *)msg->v;
1134           struct ph1handle *iph1;
1135           struct rmconfselector rmsel;
1136 #ifdef ENABLE_STATS
1137           struct timeval start, end;
1138 #endif
1139 
1140           /* check if this etype is allowed */
1141           memset(&rmsel, 0, sizeof(rmsel));
1142           rmsel.remote = remote;
1143           if (enumrmconf(&rmsel, check_etypeok, (void *) (intptr_t) etype) == 0) {
1144                     plog(LLV_ERROR, LOCATION, remote,
1145                          "exchange %s not allowed in any applicable rmconf.\n",
1146                          s_isakmp_etype(etype));
1147                     return -1;
1148           }
1149 
1150           /* get new entry to isakmp status table. */
1151           iph1 = newph1();
1152           if (iph1 == NULL)
1153                     return -1;
1154 
1155           memcpy(&iph1->index.i_ck, &isakmp->i_ck, sizeof(iph1->index.i_ck));
1156           iph1->status = PHASE1ST_START;
1157           iph1->flags = 0;
1158           iph1->side = RESPONDER;
1159           iph1->etype = etype;
1160           iph1->version = isakmp->v;
1161           iph1->msgid = 0;
1162 #ifdef HAVE_GSSAPI
1163           iph1->gssapi_state = NULL;
1164 #endif
1165 #ifdef ENABLE_HYBRID
1166           if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL) {
1167                     delph1(iph1);
1168                     return -1;
1169           }
1170 #endif
1171 #ifdef ENABLE_FRAG
1172           iph1->frag = 0;
1173           iph1->frag_last_index = 0;
1174           iph1->frag_chain = NULL;
1175 #endif
1176           iph1->approval = NULL;
1177 
1178 #ifdef ENABLE_NATT
1179           /* RFC3947 says that we MUST accept new phases1 on NAT-T floated port.
1180            * We have to setup this flag now to correctly generate the first reply.
1181            * Don't know if a better check could be done for that ?
1182            */
1183           if(extract_port(local) == lcconf->port_isakmp_natt)
1184                     iph1->natt_flags |= (NAT_PORTS_CHANGED);
1185 #endif
1186 
1187           /* copy remote address; remote and local always contain
1188            * port numbers so rmconf is not needed */
1189           if (copy_ph1addresses(iph1, NULL, remote, local) < 0) {
1190                     delph1(iph1);
1191                     return -1;
1192           }
1193           (void)insph1(iph1);
1194 
1195           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1196     {
1197           char *a;
1198 
1199           a = racoon_strdup(saddr2str(iph1->local));
1200           STRDUP_FATAL(a);
1201 
1202           plog(LLV_INFO, LOCATION, NULL,
1203                     "respond new phase 1 negotiation: %s<=>%s\n",
1204                     a, saddr2str(iph1->remote));
1205           racoon_free(a);
1206     }
1207           plog(LLV_INFO, LOCATION, NULL,
1208                     "begin %s mode.\n", s_isakmp_etype(etype));
1209 
1210 #ifdef ENABLE_STATS
1211           gettimeofday(&iph1->start, NULL);
1212           gettimeofday(&start, NULL);
1213 #endif
1214 
1215 #ifndef ENABLE_FRAG
1216 
1217           /* start exchange */
1218           if ((ph1exchange[etypesw1(iph1->etype)]
1219                           [iph1->side]
1220                           [iph1->status])(iph1, msg) < 0
1221            || (ph1exchange[etypesw1(iph1->etype)]
1222                               [iph1->side]
1223                               [iph1->status])(iph1, msg) < 0) {
1224                     plog(LLV_ERROR, LOCATION, remote,
1225                               "failed to process ph1 packet (side: %d, status: %d).\n",
1226                               iph1->side, iph1->status);
1227                     remph1(iph1);
1228                     delph1(iph1);
1229                     return -1;
1230           }
1231 
1232 #ifdef ENABLE_STATS
1233           gettimeofday(&end, NULL);
1234           syslog(LOG_NOTICE, "%s(%s): %8.6f",
1235                     "phase1",
1236                     s_isakmp_state(iph1->etype, iph1->side, iph1->status),
1237                     timedelta(&start, &end));
1238 #endif
1239 
1240           return 0;
1241 
1242 #else /* ENABLE_FRAG */
1243 
1244           /* now that we have a phase1 handle, feed back into our
1245            * main receive function to catch fragmented packets
1246            */
1247 
1248           return isakmp_main(msg, remote, local);
1249 
1250 #endif /* ENABLE_FRAG */
1251 
1252 }
1253 
1254 /* new negotiation of phase 2 for initiator */
1255 static int
isakmp_ph2begin_i(struct ph1handle * iph1,struct ph2handle * iph2)1256 isakmp_ph2begin_i(struct ph1handle *iph1, struct ph2handle *iph2)
1257 {
1258 #ifdef ENABLE_HYBRID
1259           if (xauth_check(iph1) != 0) {
1260                     plog(LLV_ERROR, LOCATION, NULL,
1261                         "Attempt to start phase 2 whereas Xauth failed\n");
1262                     return -1;
1263           }
1264 #endif
1265 
1266           /* fixup ph2 ports for this ph1 */
1267           if (extract_port(iph2->src) == 0)
1268                     set_port(iph2->src, extract_port(iph1->local));
1269           if (extract_port(iph2->dst) == 0)
1270                     set_port(iph2->dst, extract_port(iph1->remote));
1271 
1272           /* found ISAKMP-SA. */
1273           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1274           plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
1275     {
1276           char *a;
1277           a = racoon_strdup(saddr2str(iph2->src));
1278           STRDUP_FATAL(a);
1279 
1280           plog(LLV_INFO, LOCATION, NULL,
1281                     "initiate new phase 2 negotiation: %s<=>%s\n",
1282                     a, saddr2str(iph2->dst));
1283           racoon_free(a);
1284     }
1285 
1286 #ifdef ENABLE_STATS
1287           gettimeofday(&iph2->start, NULL);
1288 #endif
1289           if (iph2->status != PHASE2ST_EXPIRED) /* Phase 1 is already bound (ongoing rekeying) */
1290                     bindph12(iph1, iph2);
1291           iph2->status = PHASE2ST_STATUS2;
1292 
1293           if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1294                                [iph2->side]
1295                                [iph2->status])(iph2, NULL) < 0) {
1296                     /* release ipsecsa handler due to internal error. */
1297                     remph2(iph2);
1298                     return -1;
1299           }
1300           return 0;
1301 }
1302 
1303 /* new negotiation of phase 2 for responder */
1304 static int
isakmp_ph2begin_r(struct ph1handle * iph1,vchar_t * msg)1305 isakmp_ph2begin_r(struct ph1handle *iph1, vchar_t *msg)
1306 {
1307           struct isakmp *isakmp = (struct isakmp *)msg->v;
1308           struct ph2handle *iph2 = 0;
1309           int error;
1310 #ifdef ENABLE_STATS
1311           struct timeval start, end;
1312 #endif
1313 #ifdef ENABLE_HYBRID
1314           if (xauth_check(iph1) != 0) {
1315                     plog(LLV_ERROR, LOCATION, NULL,
1316                         "Attempt to start phase 2 whereas Xauth failed\n");
1317                     return -1;
1318           }
1319 #endif
1320 
1321           iph2 = newph2();
1322           if (iph2 == NULL) {
1323                     plog(LLV_ERROR, LOCATION, NULL,
1324                               "failed to allocate phase2 entry.\n");
1325                     return -1;
1326           }
1327 
1328           iph2->side = RESPONDER;
1329           iph2->status = PHASE2ST_START;
1330           iph2->flags = isakmp->flags;
1331           iph2->msgid = isakmp->msgid;
1332           iph2->seq = pk_getseq();
1333           iph2->ivm = oakley_newiv2(iph1, iph2->msgid);
1334           if (iph2->ivm == NULL) {
1335                     delph2(iph2);
1336                     return -1;
1337           }
1338           iph2->dst = dupsaddr(iph1->remote);     /* XXX should be considered */
1339           if (iph2->dst == NULL) {
1340                     delph2(iph2);
1341                     return -1;
1342           }
1343           iph2->src = dupsaddr(iph1->local);      /* XXX should be considered */
1344           if (iph2->src == NULL) {
1345                     delph2(iph2);
1346                     return -1;
1347           }
1348 
1349           /* add new entry to isakmp status table */
1350           insph2(iph2);
1351           bindph12(iph1, iph2);
1352 
1353           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1354     {
1355           char *a;
1356 
1357           a = racoon_strdup(saddr2str(iph2->src));
1358           STRDUP_FATAL(a);
1359 
1360           plog(LLV_INFO, LOCATION, NULL,
1361                     "respond new phase 2 negotiation: %s<=>%s\n",
1362                     a, saddr2str(iph2->dst));
1363           racoon_free(a);
1364     }
1365 
1366 #ifdef ENABLE_STATS
1367           gettimeofday(&start, NULL);
1368 #endif
1369 
1370           error = (ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1371                              [iph2->side]
1372                              [iph2->status])(iph2, msg);
1373           if (error != 0) {
1374                     plog(LLV_ERROR, LOCATION, iph1->remote,
1375                               "failed to pre-process ph2 packet (side: %d, status: %d).\n",
1376                               iph2->side, iph2->status);
1377                     if (error != ISAKMP_INTERNAL_ERROR)
1378                               isakmp_info_send_n1(iph2->ph1, error, NULL);
1379                     /*
1380                      * release handler because it's wrong that ph2handle is kept
1381                      * after failed to check message for responder's.
1382                      */
1383                     remph2(iph2);
1384                     delph2(iph2);
1385                     return -1;
1386           }
1387 
1388           /* send */
1389           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1390           if ((ph2exchange[etypesw2(isakmp->etype)]
1391                               [iph2->side]
1392                               [iph2->status])(iph2, msg) < 0) {
1393                     plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
1394                               "failed to process ph2 packet (side: %d, status: %d).\n",
1395                               iph2->side, iph2->status);
1396                     /* don't release handler */
1397                     return -1;
1398           }
1399 #ifdef ENABLE_STATS
1400           gettimeofday(&end, NULL);
1401           syslog(LOG_NOTICE, "%s(%s): %8.6f",
1402                     "phase2",
1403                     s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
1404                     timedelta(&start, &end));
1405 #endif
1406 
1407           return 0;
1408 }
1409 
1410 /*
1411  * parse ISAKMP payloads, without ISAKMP base header.
1412  */
1413 vchar_t *
isakmp_parsewoh(int np0,struct isakmp_gen * gen,int len)1414 isakmp_parsewoh(int np0, struct isakmp_gen *gen, int len)
1415 {
1416           u_char np = np0 & 0xff;
1417           int tlen, plen;
1418           vchar_t *result;
1419           struct isakmp_parse_t *p, *ep;
1420 
1421           plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
1422 
1423           /*
1424            * 5 is a magic number, but any value larger than 2 should be fine
1425            * as we do vrealloc() in the following loop.
1426            */
1427           result = vmalloc(sizeof(struct isakmp_parse_t) * 5);
1428           if (result == NULL) {
1429                     plog(LLV_ERROR, LOCATION, NULL,
1430                               "failed to get buffer.\n");
1431                     return NULL;
1432           }
1433           p = (struct isakmp_parse_t *)result->v;
1434           ep = (struct isakmp_parse_t *)(result->v + result->l - sizeof(*ep));
1435 
1436           tlen = len;
1437 
1438           /* parse through general headers */
1439           while (0 < tlen && np != ISAKMP_NPTYPE_NONE) {
1440                     if (tlen <= sizeof(struct isakmp_gen)) {
1441                               /* don't send information, see isakmp_ident_r1() */
1442                               plog(LLV_ERROR, LOCATION, NULL,
1443                                         "invalid length of payload\n");
1444                               vfree(result);
1445                               return NULL;
1446                     }
1447 
1448                     plog(LLV_DEBUG, LOCATION, NULL,
1449                               "seen nptype=%u(%s)\n", np, s_isakmp_nptype(np));
1450 
1451                     p->type = np;
1452                     p->len = ntohs(gen->len);
1453                     if (p->len < sizeof(struct isakmp_gen) || p->len > tlen) {
1454                               plog(LLV_DEBUG, LOCATION, NULL,
1455                                         "invalid length of payload\n");
1456                               vfree(result);
1457                               return NULL;
1458                     }
1459                     p->ptr = gen;
1460                     p++;
1461                     if (ep <= p) {
1462                               off_t off;
1463 
1464                               off = p - (struct isakmp_parse_t *)result->v;
1465                               result = vrealloc(result, result->l * 2);
1466                               if (result == NULL) {
1467                                         plog(LLV_DEBUG, LOCATION, NULL,
1468                                                   "failed to realloc buffer.\n");
1469                                         vfree(result);
1470                                         return NULL;
1471                               }
1472                               ep = (struct isakmp_parse_t *)
1473                                         (result->v + result->l - sizeof(*ep));
1474                               p = (struct isakmp_parse_t *)result->v;
1475                               p += off;
1476                     }
1477 
1478                     np = gen->np;
1479                     plen = ntohs(gen->len);
1480                     gen = (struct isakmp_gen *)((caddr_t)gen + plen);
1481                     tlen -= plen;
1482           }
1483           p->type = ISAKMP_NPTYPE_NONE;
1484           p->len = 0;
1485           p->ptr = NULL;
1486 
1487           plog(LLV_DEBUG, LOCATION, NULL, "succeed.\n");
1488 
1489           return result;
1490 }
1491 
1492 /*
1493  * parse ISAKMP payloads, including ISAKMP base header.
1494  */
1495 vchar_t *
isakmp_parse(vchar_t * buf)1496 isakmp_parse(vchar_t *buf)
1497 {
1498           struct isakmp *isakmp = (struct isakmp *)buf->v;
1499           struct isakmp_gen *gen;
1500           size_t tlen;
1501           vchar_t *result;
1502           u_char np;
1503 
1504           np = isakmp->np;
1505           gen = (struct isakmp_gen *)(buf->v + sizeof(*isakmp));
1506           tlen = buf->l - sizeof(struct isakmp);
1507           result = isakmp_parsewoh(np, gen, tlen);
1508 
1509           return result;
1510 }
1511 
1512 /* %%% */
1513 int
isakmp_init()1514 isakmp_init()
1515 {
1516           /* initialize a isakmp status table */
1517           initph1tree();
1518           initph2tree();
1519           initctdtree();
1520           init_recvdpkt();
1521 
1522           return 0;
1523 }
1524 
1525 /*
1526  * make strings containing i_cookie + r_cookie + msgid
1527  */
1528 const char *
isakmp_pindex(const isakmp_index * index1,const uint32_t msgid)1529 isakmp_pindex(const isakmp_index *index1, const uint32_t msgid)
1530 {
1531           static char buf[64];
1532           const u_char *p;
1533           int i, j;
1534 
1535           memset(buf, 0, sizeof(buf));
1536 
1537           /* copy index */
1538           p = (const u_char *)index1;
1539           for (j = 0, i = 0; i < sizeof(isakmp_index); i++) {
1540                     snprintf((char *)&buf[j], sizeof(buf) - j, "%02x", p[i]);
1541                     j += 2;
1542                     switch (i) {
1543                     case 7:
1544                               buf[j++] = ':';
1545                     }
1546           }
1547 
1548           if (msgid == 0)
1549                     return buf;
1550 
1551           /* copy msgid */
1552           snprintf((char *)&buf[j], sizeof(buf) - j, ":%08x", ntohs(msgid));
1553 
1554           return buf;
1555 }
1556 
1557 /* open ISAKMP sockets. */
1558 int
isakmp_open(struct sockaddr * addr,int udp_encap)1559 isakmp_open(struct sockaddr *addr, int udp_encap)
1560 {
1561           const int yes = 1;
1562           int fd;
1563           struct sockaddr_in *sin = (struct sockaddr_in *) addr;
1564 #ifdef INET6
1565           struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) addr;
1566           int pktinfo;
1567 #endif
1568 #ifdef ENABLE_NATT
1569           int option = -1;
1570 #endif
1571 
1572           /* warn if wildcard address - should we forbid this? */
1573           switch (addr->sa_family) {
1574           case AF_INET:
1575                     if (sin->sin_addr.s_addr == 0)
1576                               plog(LLV_WARNING, LOCATION, NULL,
1577                                    "listening to wildcard address,"
1578                                    "broadcast IKE packet may kill you\n");
1579                     break;
1580 #ifdef INET6
1581           case AF_INET6:
1582                     if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
1583                               plog(LLV_DEBUG, LOCATION, NULL,
1584                                    "ignoring multicast address %s\n",
1585                                    saddr2str(addr));
1586                               return -1;
1587                     }
1588 
1589                     if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
1590                               plog(LLV_WARNING, LOCATION, NULL,
1591                                    "listening to wildcard address, "
1592                                    "broadcast IKE packet may kill you\n");
1593                     break;
1594 #endif
1595           default:
1596                     plog(LLV_ERROR, LOCATION, NULL,
1597                          "unsupported address family %d\n",
1598                          addr->sa_family);
1599                     return -1;
1600           }
1601 
1602           if ((fd = privsep_socket(addr->sa_family, SOCK_DGRAM, 0)) < 0) {
1603                     plog(LLV_ERROR, LOCATION, NULL,
1604                          "socket(%s)\n", strerror(errno));
1605                     return -1;
1606           }
1607           close_on_exec(fd);
1608           if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1)
1609                     plog(LLV_WARNING, LOCATION, NULL,
1610                          "failed to put socket in non-blocking mode\n");
1611 
1612           /* receive my interface address on inbound packets. */
1613           switch (addr->sa_family) {
1614           case AF_INET:
1615                     if (setsockopt(fd, IPPROTO_IP,
1616 #ifdef __linux__
1617                                      IP_PKTINFO,
1618 #else
1619                                      IP_RECVDSTADDR,
1620 #endif
1621                                      (const void *) &yes, sizeof(yes)) < 0) {
1622                               plog(LLV_ERROR, LOCATION, NULL,
1623                                    "setsockopt IP_RECVDSTADDR (%s)\n",
1624                                    strerror(errno));
1625                               goto err;
1626                     }
1627 
1628 #ifdef ENABLE_NATT
1629                     if (udp_encap)
1630                               option = UDP_ENCAP_ESPINUDP;
1631 #if defined(ENABLE_NATT_00) || defined(ENABLE_NATT_01)
1632                     else
1633                               option = UDP_ENCAP_ESPINUDP_NON_IKE;
1634 #endif
1635                     if (option == -1)
1636                               break;
1637 
1638                     if (setsockopt(fd, SOL_UDP,
1639                                      UDP_ENCAP, &option,
1640                                      sizeof(option)) < 0) {
1641                               plog(LLV_WARNING, LOCATION, NULL,
1642                                    "setsockopt(%s): UDP_ENCAP %s\n",
1643                                    option == UDP_ENCAP_ESPINUDP ? "UDP_ENCAP_ESPINUDP" : "UDP_ENCAP_ESPINUDP_NON_IKE",
1644                                    strerror(errno));
1645                     } else {
1646                               plog(LLV_INFO, LOCATION, NULL,
1647                                    "%s used for NAT-T\n",
1648                                    saddr2str(addr));
1649                     }
1650 #endif
1651                     break;
1652 
1653 #ifdef INET6
1654           case AF_INET6:
1655 #if defined(INET6_ADVAPI)
1656 #ifdef IPV6_RECVPKTINFO
1657                     pktinfo = IPV6_RECVPKTINFO;
1658 #else  /* old adv. API */
1659                     pktinfo = IPV6_PKTINFO;
1660 #endif /* IPV6_RECVPKTINFO */
1661 #else
1662                     pktinfo = IPV6_RECVDSTADDR;
1663 #endif
1664                     if (setsockopt(fd, IPPROTO_IPV6, pktinfo,
1665                                      &yes, sizeof(yes)) < 0) {
1666                               plog(LLV_ERROR, LOCATION, NULL,
1667                                    "setsockopt IPV6_RECVDSTADDR (%d):%s\n",
1668                                    pktinfo, strerror(errno));
1669                               goto err;
1670                     }
1671 
1672 #ifdef IPV6_USE_MIN_MTU
1673                     if (setsockopt(fd, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
1674                                      &yes, sizeof(yes)) < 0) {
1675                               plog(LLV_ERROR, LOCATION, NULL,
1676                                    "setsockopt IPV6_USE_MIN_MTU (%s)\n",
1677                                    strerror(errno));
1678                               goto err;
1679                     }
1680 #endif
1681                     break;
1682 #endif
1683           }
1684 
1685           if (setsockopt(fd, SOL_SOCKET,
1686 #ifdef __linux__
1687                            SO_REUSEADDR,
1688 #else
1689                            SO_REUSEPORT,
1690 #endif
1691                            &yes, sizeof(yes)) < 0) {
1692                     plog(LLV_ERROR, LOCATION, NULL,
1693                          "failed to set REUSE flag on %s (%s).\n",
1694                          saddr2str(addr), strerror(errno));
1695                     goto err;
1696           }
1697 
1698           if (setsockopt_bypass(fd, addr->sa_family) < 0)
1699                     goto err;
1700 
1701           if (privsep_bind(fd, addr, sysdep_sa_len(addr)) < 0) {
1702                     plog(LLV_ERROR, LOCATION, addr,
1703                          "failed to bind to address %s (%s).\n",
1704                          saddr2str(addr), strerror(errno));
1705                     goto err;
1706           }
1707 
1708           plog(LLV_INFO, LOCATION, NULL,
1709                "%s used as isakmp port (fd=%d)\n",
1710                saddr2str(addr), fd);
1711 
1712           monitor_fd(fd, isakmp_handler, NULL, 1);
1713           return fd;
1714 
1715 err:
1716           close(fd);
1717           return -1;
1718 }
1719 
1720 void
isakmp_close(int fd)1721 isakmp_close(int fd)
1722 {
1723           unmonitor_fd(fd);
1724           close(fd);
1725 }
1726 
1727 int
isakmp_send(struct ph1handle * iph1,vchar_t * sbuf)1728 isakmp_send(struct ph1handle *iph1, vchar_t *sbuf)
1729 {
1730           int len = 0;
1731           int s;
1732           vchar_t *vbuf = NULL, swap;
1733 
1734 #ifdef ENABLE_NATT
1735           size_t extralen = NON_ESP_MARKER_USE(iph1) ? NON_ESP_MARKER_LEN : 0;
1736 
1737           /* Check if NON_ESP_MARKER_LEN is already there (happens when resending packets)
1738            */
1739           if(extralen == NON_ESP_MARKER_LEN &&
1740              *(uint32_t *)sbuf->v == 0)
1741                     extralen = 0;
1742 
1743 #ifdef ENABLE_FRAG
1744           /*
1745            * Do not add the non ESP marker for a packet that will
1746            * be fragmented. The non ESP marker should appear in
1747            * all fragment's packets, but not in the fragmented packet
1748            */
1749           if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN)
1750                     extralen = 0;
1751 #endif
1752           if (extralen)
1753                     plog (LLV_DEBUG, LOCATION, NULL, "Adding NON-ESP marker\n");
1754 
1755           /* If NAT-T port floating is in use, 4 zero bytes (non-ESP marker)
1756              must added just before the packet itself. For this we must
1757              allocate a new buffer and release it at the end. */
1758           if (extralen) {
1759                     if ((vbuf = vmalloc (sbuf->l + extralen)) == NULL) {
1760                               plog(LLV_ERROR, LOCATION, NULL,
1761                                   "vbuf allocation failed\n");
1762                               return -1;
1763                     }
1764                     *(uint32_t *)vbuf->v = 0;
1765                     memcpy (vbuf->v + extralen, sbuf->v, sbuf->l);
1766                     /* ensures that the modified buffer will be sent back to the caller, so
1767                      * add_recvdpkt() will add the correct buffer
1768                      */
1769                     swap = *sbuf;
1770                     *sbuf = *vbuf;
1771                     *vbuf = swap;
1772                     vfree(vbuf);
1773           }
1774 #endif
1775 
1776           /* select the socket to be sent */
1777           s = myaddr_getfd(iph1->local);
1778           if (s == -1)
1779                     return -1;
1780 
1781           plog (LLV_DEBUG, LOCATION, NULL, "%zu bytes %s\n", sbuf->l,
1782                 saddr2str_fromto("from %s to %s", iph1->local, iph1->remote));
1783 
1784 #ifdef ENABLE_FRAG
1785           if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN) {
1786                     if (isakmp_sendfrags(iph1, sbuf) == -1) {
1787                               plog(LLV_ERROR, LOCATION, NULL,
1788                                   "isakmp_sendfrags failed\n");
1789                               return -1;
1790                     }
1791           } else
1792 #endif
1793           {
1794                     len = sendfromto(s, sbuf->v, sbuf->l,
1795                         iph1->local, iph1->remote, lcconf->count_persend);
1796 
1797                     if (len == -1) {
1798                               plog(LLV_ERROR, LOCATION, NULL, "sendfromto failed\n");
1799                               return -1;
1800                     }
1801           }
1802 
1803           return 0;
1804 }
1805 
1806 /* called from scheduler */
1807 static void
isakmp_ph1resend_stub(struct sched * p)1808 isakmp_ph1resend_stub(struct sched *p)
1809 {
1810           struct ph1handle *iph1 = container_of(p, struct ph1handle, scr);
1811 
1812           if (isakmp_ph1resend(iph1) < 0) {
1813                     remph1(iph1);
1814                     delph1(iph1);
1815           }
1816 }
1817 
1818 static int
isakmp_ph1resend(struct ph1handle * iph1)1819 isakmp_ph1resend(struct ph1handle *iph1)
1820 {
1821           /* Note: NEVER do the rem/del here, it will be done by the caller or by the _stub function
1822            */
1823           if (iph1->retry_counter <= 0) {
1824                     plog(LLV_ERROR, LOCATION, NULL,
1825                               "phase1 negotiation failed due to time up. %s\n",
1826                               isakmp_pindex(&iph1->index, iph1->msgid));
1827                     /* XXX is the peer really "dead" here ??? */
1828                     script_hook(iph1, SCRIPT_PHASE1_DEAD);
1829                     evt_phase1(iph1, EVT_PHASE1_NO_RESPONSE, NULL);
1830 
1831                     return -1;
1832           }
1833 
1834           if (isakmp_send(iph1, iph1->sendbuf) < 0){
1835                     plog(LLV_ERROR, LOCATION, NULL,
1836                                "phase1 negotiation failed due to send error. %s\n",
1837                                isakmp_pindex(&iph1->index, iph1->msgid));
1838                     evt_phase1(iph1, EVT_PHASE1_NO_RESPONSE, NULL);
1839                     return -1;
1840           }
1841 
1842           plog(LLV_DEBUG, LOCATION, NULL,
1843                     "resend phase1 packet %s\n",
1844                     isakmp_pindex(&iph1->index, iph1->msgid));
1845 
1846           iph1->retry_counter--;
1847 
1848           sched_schedule(&iph1->scr, lcconf->retry_interval,
1849                            isakmp_ph1resend_stub);
1850 
1851           return 0;
1852 }
1853 
1854 int
isakmp_ph1send(struct ph1handle * iph1)1855 isakmp_ph1send(struct ph1handle *iph1)
1856 {
1857           iph1->retry_counter = lcconf->retry_counter;
1858           return isakmp_ph1resend(iph1);
1859 }
1860 
1861 /* called from scheduler */
1862 static void
isakmp_ph2resend_stub(struct sched * p)1863 isakmp_ph2resend_stub(struct sched *p)
1864 {
1865           struct ph2handle *iph2 = container_of(p, struct ph2handle, scr);
1866 
1867           if (isakmp_ph2resend(iph2) < 0) {
1868                     remph2(iph2);
1869                     delph2(iph2);
1870           }
1871 }
1872 
1873 static int
isakmp_ph2resend(struct ph2handle * iph2)1874 isakmp_ph2resend(struct ph2handle *iph2)
1875 {
1876           /* Note: NEVER do the unbind/rem/del here, it will be done by the caller or by the _stub function
1877            */
1878           if (iph2->ph1->status >= PHASE1ST_EXPIRED) {
1879                     plog(LLV_ERROR, LOCATION, NULL,
1880                               "phase2 negotiation failed due to phase1 expired. %s\n",
1881                                         isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1882                     return -1;
1883           }
1884 
1885           if (iph2->retry_counter <= 0) {
1886                     plog(LLV_ERROR, LOCATION, NULL,
1887                               "phase2 negotiation failed due to time up. %s\n",
1888                                         isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1889                     evt_phase2(iph2, EVT_PHASE2_NO_RESPONSE, NULL);
1890                     unbindph12(iph2);
1891                     return -1;
1892           }
1893 
1894           if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0){
1895                     plog(LLV_ERROR, LOCATION, NULL,
1896                               "phase2 negotiation failed due to send error. %s\n",
1897                                         isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1898                     evt_phase2(iph2, EVT_PHASE2_NO_RESPONSE, NULL);
1899                     return -1;
1900           }
1901 
1902           plog(LLV_DEBUG, LOCATION, NULL,
1903                     "resend phase2 packet %s\n",
1904                     isakmp_pindex(&iph2->ph1->index, iph2->msgid));
1905 
1906           iph2->retry_counter--;
1907 
1908           sched_schedule(&iph2->scr, lcconf->retry_interval,
1909                            isakmp_ph2resend_stub);
1910 
1911           return 0;
1912 }
1913 
1914 int
isakmp_ph2send(struct ph2handle * iph2)1915 isakmp_ph2send(struct ph2handle *iph2)
1916 {
1917           iph2->retry_counter = lcconf->retry_counter;
1918           return isakmp_ph2resend(iph2);
1919 }
1920 
1921 /* called from scheduler */
1922 void
isakmp_ph1dying_stub(struct sched * p)1923 isakmp_ph1dying_stub(struct sched *p)
1924 {
1925 
1926           isakmp_ph1dying(container_of(p, struct ph1handle, sce));
1927 }
1928 
1929 void
isakmp_ph1dying(struct ph1handle * iph1)1930 isakmp_ph1dying(struct ph1handle *iph1)
1931 {
1932           struct ph1handle *new_iph1;
1933           struct ph2handle *p;
1934 
1935           if (iph1->status >= PHASE1ST_DYING)
1936                     return;
1937 
1938           /* Going away in after a while... */
1939           iph1->status = PHASE1ST_DYING;
1940 
1941           /* Any fresh phase1s? */
1942           new_iph1 = getph1(iph1, iph1->local, iph1->remote, 1);
1943           if (new_iph1 == NULL) {
1944                     LIST_FOREACH(p, &iph1->ph2tree, ph1bind) {
1945                               if (p->status != PHASE2ST_ESTABLISHED)
1946                                         continue;
1947 
1948                               plog(LLV_INFO, LOCATION, NULL,
1949                                    "renegotiating phase1 to %s due to "
1950                                    "active phase2\n",
1951                                    saddrwop2str(iph1->remote));
1952 
1953                               if (iph1->side == INITIATOR)
1954                                         isakmp_ph1begin_i(iph1->rmconf, iph1->remote,
1955                                                               iph1->local);
1956 
1957                               break;
1958                     }
1959           } else {
1960                     migrate_ph12(iph1, new_iph1);
1961           }
1962 
1963           /* Schedule for expiration */
1964           sched_schedule(&iph1->sce, iph1->approval->lifetime *
1965                            (100 - PFKEY_SOFT_LIFETIME_RATE) / 100,
1966                            isakmp_ph1expire_stub);
1967 }
1968 
1969 /* called from scheduler */
1970 void
isakmp_ph1expire_stub(struct sched * p)1971 isakmp_ph1expire_stub(struct sched *p)
1972 {
1973           isakmp_ph1expire(container_of(p, struct ph1handle, sce));
1974 }
1975 
1976 void
isakmp_ph1expire(struct ph1handle * iph1)1977 isakmp_ph1expire(struct ph1handle *iph1)
1978 {
1979           char *src, *dst;
1980 
1981           if (iph1->status < PHASE1ST_EXPIRED) {
1982                     src = racoon_strdup(saddr2str(iph1->local));
1983                     dst = racoon_strdup(saddr2str(iph1->remote));
1984                     STRDUP_FATAL(src);
1985                     STRDUP_FATAL(dst);
1986 
1987                     plog(LLV_INFO, LOCATION, NULL,
1988                                "ISAKMP-SA expired %s-%s spi:%s\n",
1989                                src, dst,
1990                                isakmp_pindex(&iph1->index, 0));
1991                     racoon_free(src);
1992                     racoon_free(dst);
1993                     iph1->status = PHASE1ST_EXPIRED;
1994           }
1995 
1996           isakmp_ph1delete(iph1);
1997 }
1998 
1999 /* called from scheduler */
2000 void
isakmp_ph1delete_stub(struct sched * p)2001 isakmp_ph1delete_stub(struct sched *p)
2002 {
2003 
2004           isakmp_ph1delete(container_of(p, struct ph1handle, sce));
2005 }
2006 
2007 void
isakmp_ph1delete(struct ph1handle * iph1)2008 isakmp_ph1delete(struct ph1handle *iph1)
2009 {
2010           struct ph2handle *p, *next;
2011           struct ph1handle *new_iph1;
2012           char *src, *dst;
2013 
2014           /* Migrate established phase2s. Any fresh phase1s? */
2015           new_iph1 = getph1(iph1, iph1->local, iph1->remote, 1);
2016           if (new_iph1 != NULL)
2017                     migrate_ph12(iph1, new_iph1);
2018 
2019           /* Discard any left phase2s */
2020           for (p = LIST_FIRST(&iph1->ph2tree); p; p = next) {
2021                     next = LIST_NEXT(p, ph1bind);
2022                     if (p->status == PHASE2ST_ESTABLISHED)
2023                               isakmp_info_send_d2(p);
2024                     /* remove all ph2 handles,
2025                      * as ph1handle will be expired soon
2026                      */
2027                     delete_spd(p, 1);
2028                     remph2(p);
2029                     delph2(p);
2030           }
2031 
2032           src = racoon_strdup(saddr2str(iph1->local));
2033           dst = racoon_strdup(saddr2str(iph1->remote));
2034           STRDUP_FATAL(src);
2035           STRDUP_FATAL(dst);
2036 
2037           plog(LLV_INFO, LOCATION, NULL,
2038                     "ISAKMP-SA deleted %s-%s spi:%s\n",
2039                     src, dst, isakmp_pindex(&iph1->index, 0));
2040 
2041           evt_phase1(iph1, EVT_PHASE1_DOWN, NULL);
2042           if (new_iph1 == NULL && ph1_rekey_enabled(iph1))
2043                     script_hook(iph1, SCRIPT_PHASE1_DEAD);
2044 
2045           racoon_free(src);
2046           racoon_free(dst);
2047 
2048           remph1(iph1);
2049           delph1(iph1);
2050 }
2051 
2052 /* called from scheduler.
2053  * this function will call only isakmp_ph2delete().
2054  * phase 2 handler remain forever if kernel doesn't cry a expire of phase 2 SA
2055  * by something cause.  That's why this function is called after phase 2 SA
2056  * expires in the userland.
2057  */
2058 void
isakmp_ph2expire_stub(struct sched * p)2059 isakmp_ph2expire_stub(struct sched *p)
2060 {
2061 
2062           isakmp_ph2expire(container_of(p, struct ph2handle, sce));
2063 }
2064 
2065 void
isakmp_ph2expire(struct ph2handle * iph2)2066 isakmp_ph2expire(struct ph2handle *iph2)
2067 {
2068           char *src, *dst;
2069 
2070           src = racoon_strdup(saddrwop2str(iph2->src));
2071           dst = racoon_strdup(saddrwop2str(iph2->dst));
2072           STRDUP_FATAL(src);
2073           STRDUP_FATAL(dst);
2074 
2075           plog(LLV_INFO, LOCATION, NULL,
2076                     "phase2 sa expired %s-%s\n", src, dst);
2077           racoon_free(src);
2078           racoon_free(dst);
2079 
2080           iph2->status = PHASE2ST_EXPIRED;
2081           sched_schedule(&iph2->sce, 1, isakmp_ph2delete_stub);
2082 }
2083 
2084 /* called from scheduler */
2085 void
isakmp_ph2delete_stub(struct sched * p)2086 isakmp_ph2delete_stub(struct sched *p)
2087 {
2088 
2089           isakmp_ph2delete(container_of(p, struct ph2handle, sce));
2090 }
2091 
2092 void
isakmp_ph2delete(struct ph2handle * iph2)2093 isakmp_ph2delete(struct ph2handle *iph2)
2094 {
2095           char *src, *dst;
2096 
2097           src = racoon_strdup(saddrwop2str(iph2->src));
2098           dst = racoon_strdup(saddrwop2str(iph2->dst));
2099           STRDUP_FATAL(src);
2100           STRDUP_FATAL(dst);
2101 
2102           plog(LLV_INFO, LOCATION, NULL,
2103                     "phase2 sa deleted %s-%s\n", src, dst);
2104           racoon_free(src);
2105           racoon_free(dst);
2106 
2107           remph2(iph2);
2108           delph2(iph2);
2109 
2110           return;
2111 }
2112 
2113 /* %%%
2114  * Interface between PF_KEYv2 and ISAKMP
2115  */
2116 /*
2117  * receive ACQUIRE from kernel, and begin either phase1 or phase2.
2118  * if phase1 has been finished, begin phase2.
2119  */
2120 int
isakmp_post_acquire(struct ph2handle * iph2,struct ph1handle * iph1hint,int nopassive)2121 isakmp_post_acquire(struct ph2handle *iph2, struct ph1handle *iph1hint,
2122     int nopassive)
2123 {
2124           struct remoteconf *rmconf;
2125           struct ph1handle *iph1 = NULL;
2126 
2127           plog(LLV_DEBUG, LOCATION, NULL, "in post_acquire\n");
2128 
2129           /* Search appropriate configuration with masking port. Note that
2130            * we always use iph2->dst, and not iph2->sa_dst.
2131            *
2132            * XXX One possible need for using iph2->sa_dst if not NULL would
2133            * be for selecting a remote configuration based on a stable
2134            * address of a mobile node (not a CoA provided by MIGRATE/KMADDRESS
2135            * as iph2->dst hint). This scenario would require additional changes,
2136            * so no need to bother yet. --arno */
2137 
2138           if (iph1hint == NULL || iph1hint->rmconf == NULL) {
2139                     rmconf = getrmconf(iph2->dst, nopassive ? GETRMCONF_F_NO_PASSIVE : 0);
2140                     if (rmconf == NULL) {
2141                               plog(LLV_ERROR, LOCATION, NULL,
2142                                         "no configuration found for %s.\n",
2143                                         saddrwop2str(iph2->dst));
2144                               return -1;
2145                     }
2146           } else {
2147                     rmconf = iph1hint->rmconf;
2148           }
2149 
2150           /* if passive mode, ignore the acquire message */
2151           if (nopassive && rmconf->passive) {
2152                     plog(LLV_DEBUG, LOCATION, NULL,
2153                               "because of passive mode, "
2154                               "ignore the acquire message for %s.\n",
2155                               saddrwop2str(iph2->dst));
2156                     return -1;
2157           }
2158 
2159           /*
2160            * XXX Searching by IP addresses + ports might fail on
2161            * some cases, we should use the ISAKMP identity to search
2162            * matching ISAKMP.
2163            */
2164           iph1 = getph1(iph1hint, iph2->src, iph2->dst, 0);
2165 
2166           /* no ISAKMP-SA found. */
2167           if (iph1 == NULL) {
2168                     iph2->retry_checkph1 = lcconf->retry_checkph1;
2169                     sched_schedule(&iph2->sce, 1, isakmp_chkph1there_stub);
2170                     plog(LLV_INFO, LOCATION, NULL,
2171                               "IPsec-SA request for %s queued "
2172                               "due to no phase1 found.\n",
2173                               saddrwop2str(iph2->dst));
2174 
2175                     /* start phase 1 negotiation as a initiator. */
2176                     if (isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src) == NULL) {
2177                               sched_cancel(&iph2->sce);
2178                               return -1;
2179                     }
2180 
2181                     return 0;
2182                     /*NOTREACHED*/
2183           }
2184 
2185           /* found ISAKMP-SA, but on negotiation. */
2186           if (iph1->status < PHASE1ST_ESTABLISHED) {
2187                     iph2->retry_checkph1 = lcconf->retry_checkph1;
2188                     sched_schedule(&iph2->sce, 1, isakmp_chkph1there_stub);
2189                     plog(LLV_INFO, LOCATION, iph2->dst,
2190                               "request for establishing IPsec-SA was queued "
2191                               "due to no phase1 found.\n");
2192                     return 0;
2193                     /*NOTREACHED*/
2194           }
2195 
2196           /* found established ISAKMP-SA */
2197           /* i.e. iph1->status == PHASE1ST_ESTABLISHED */
2198 
2199           /* found ISAKMP-SA. */
2200           plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
2201 
2202           /* begin quick mode */
2203           if (isakmp_ph2begin_i(iph1, iph2))
2204                     return -1;
2205 
2206           return 0;
2207 }
2208 
2209 int
isakmp_get_sainfo(struct ph2handle * iph2,struct secpolicy * sp_out,struct secpolicy * sp_in)2210 isakmp_get_sainfo(struct ph2handle *iph2, struct secpolicy *sp_out,
2211     struct secpolicy *sp_in)
2212 {
2213           struct remoteconf *conf;
2214           uint32_t remoteid = 0;
2215 
2216           plog(LLV_DEBUG, LOCATION, NULL,
2217                     "new acquire %s\n", spidx2str(&sp_out->spidx));
2218 
2219           /* get sainfo */
2220           {
2221                     vchar_t *idsrc, *iddst;
2222 
2223                     idsrc = ipsecdoi_sockaddr2id((struct sockaddr *)&sp_out->spidx.src,
2224                               sp_out->spidx.prefs, sp_out->spidx.ul_proto);
2225                     if (idsrc == NULL) {
2226                               plog(LLV_ERROR, LOCATION, NULL,
2227                                         "failed to get ID for %s\n",
2228                                         spidx2str(&sp_out->spidx));
2229                               return -1;
2230                     }
2231                     iddst = ipsecdoi_sockaddr2id((struct sockaddr *)&sp_out->spidx.dst,
2232                               sp_out->spidx.prefd, sp_out->spidx.ul_proto);
2233                     if (iddst == NULL) {
2234                               plog(LLV_ERROR, LOCATION, NULL,
2235                                         "failed to get ID for %s\n",
2236                                         spidx2str(&sp_out->spidx));
2237                               vfree(idsrc);
2238                               return -1;
2239                     }
2240 
2241                     conf = getrmconf(iph2->dst, 0);
2242                     if (conf != NULL)
2243                               remoteid = conf->ph1id;
2244                     else
2245                               plog(LLV_DEBUG, LOCATION, NULL, "Warning: no valid rmconf !\n");
2246 
2247                     iph2->sainfo = getsainfo(idsrc, iddst, NULL, NULL, remoteid);
2248                     vfree(idsrc);
2249                     vfree(iddst);
2250                     if (iph2->sainfo == NULL) {
2251                               plog(LLV_ERROR, LOCATION, NULL,
2252                                         "failed to get sainfo.\n");
2253                               return -1;
2254                               /* XXX should use the algorithm list from register message */
2255                     }
2256 
2257                     plog(LLV_DEBUG, LOCATION, NULL,
2258                               "selected sainfo: %s\n", sainfo2str(iph2->sainfo));
2259           }
2260 
2261           if (set_proposal_from_policy(iph2, sp_out, sp_in) < 0) {
2262                     plog(LLV_ERROR, LOCATION, NULL,
2263                               "failed to create saprop.\n");
2264                     return -1;
2265           }
2266 
2267           return 0;
2268 }
2269 
2270 
2271 /*
2272  * receive GETSPI from kernel.
2273  */
2274 int
isakmp_post_getspi(struct ph2handle * iph2)2275 isakmp_post_getspi(struct ph2handle *iph2)
2276 {
2277 #ifdef ENABLE_STATS
2278           struct timeval start, end;
2279 #endif
2280 
2281           /* don't process it because there is no suitable phase1-sa. */
2282           if (iph2->ph1->status >= PHASE1ST_EXPIRED) {
2283                     plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
2284                               "the negotiation is stopped, "
2285                               "because there is no suitable ISAKMP-SA.\n");
2286                     return -1;
2287           }
2288 
2289 #ifdef ENABLE_STATS
2290           gettimeofday(&start, NULL);
2291 #endif
2292           if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
2293                           [iph2->side]
2294                           [iph2->status])(iph2, NULL) != 0)
2295                     return -1;
2296 #ifdef ENABLE_STATS
2297           gettimeofday(&end, NULL);
2298           syslog(LOG_NOTICE, "%s(%s): %8.6f",
2299                     "phase2",
2300                     s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
2301                     timedelta(&start, &end));
2302 #endif
2303 
2304           return 0;
2305 }
2306 
2307 /* called by scheduler */
2308 void
isakmp_chkph1there_stub(struct sched * p)2309 isakmp_chkph1there_stub(struct sched *p)
2310 {
2311           isakmp_chkph1there(container_of(p, struct ph2handle, sce));
2312 }
2313 
2314 void
isakmp_chkph1there(struct ph2handle * iph2)2315 isakmp_chkph1there(struct ph2handle *iph2)
2316 {
2317           struct ph1handle *iph1;
2318 
2319           iph2->retry_checkph1--;
2320           if (iph2->retry_checkph1 < 0) {
2321                     plog(LLV_ERROR, LOCATION, iph2->dst,
2322                               "phase2 negotiation failed "
2323                               "due to time up waiting for phase1. %s\n",
2324                               sadbsecas2str(iph2->src, iph2->dst,
2325                                         iph2->satype, 0, 0));
2326                     plog(LLV_INFO, LOCATION, NULL,
2327                               "delete phase 2 handler.\n");
2328 
2329                     /* send acquire to kernel as error */
2330                     pk_sendeacquire(iph2);
2331 
2332                     remph2(iph2);
2333                     delph2(iph2);
2334 
2335                     return;
2336           }
2337 
2338           /* Search isakmp status table by address and port */
2339           iph1 = getph1byaddr(iph2->src, iph2->dst, 0);
2340 
2341           /* XXX Even if ph1 as responder is there, should we not start
2342            * phase 2 negotiation ? */
2343           if (iph1 != NULL
2344            && iph1->status == PHASE1ST_ESTABLISHED) {
2345                     /* found isakmp-sa */
2346 
2347                     plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: got a ph1 handler, setting ports.\n");
2348                     plog(LLV_DEBUG2, LOCATION, NULL, "iph1->local: %s\n", saddr2str(iph1->local));
2349                     plog(LLV_DEBUG2, LOCATION, NULL, "iph1->remote: %s\n", saddr2str(iph1->remote));
2350                     plog(LLV_DEBUG2, LOCATION, NULL, "before:\n");
2351                     plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
2352                     plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
2353                     set_port(iph2->src, extract_port(iph1->local));
2354                     set_port(iph2->dst, extract_port(iph1->remote));
2355                     plog(LLV_DEBUG2, LOCATION, NULL, "After:\n");
2356                     plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
2357                     plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
2358 
2359                     /* begin quick mode */
2360                     (void)isakmp_ph2begin_i(iph1, iph2);
2361                     return;
2362           }
2363 
2364           plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: no established ph1 handler found\n");
2365 
2366           /* no isakmp-sa found */
2367           sched_schedule(&iph2->sce, 1, isakmp_chkph1there_stub);
2368 
2369           return;
2370 }
2371 
2372 /* copy variable data into ALLOCATED buffer. */
2373 caddr_t
isakmp_set_attr_v(caddr_t buf,int type,caddr_t val,int len)2374 isakmp_set_attr_v(caddr_t buf, int type, caddr_t val, int len)
2375 {
2376           struct isakmp_data *data;
2377 
2378           data = (struct isakmp_data *)buf;
2379           data->type = htons((uint16_t)type | ISAKMP_GEN_TLV);
2380           data->lorv = htons((uint16_t)len);
2381           memcpy(data + 1, val, len);
2382 
2383           return buf + sizeof(*data) + len;
2384 }
2385 
2386 /* copy fixed length data into ALLOCATED buffer. */
2387 caddr_t
isakmp_set_attr_l(caddr_t buf,int type,uint32_t val)2388 isakmp_set_attr_l(caddr_t buf, int type, uint32_t val)
2389 {
2390           struct isakmp_data *data;
2391 
2392           data = (struct isakmp_data *)buf;
2393           data->type = htons((uint16_t)type | ISAKMP_GEN_TV);
2394           data->lorv = htons((uint16_t)val);
2395 
2396           return buf + sizeof(*data);
2397 }
2398 
2399 /* add a variable data attribute to the buffer by reallocating it. */
2400 vchar_t *
isakmp_add_attr_v(vchar_t * buf0,int type,caddr_t val,int len)2401 isakmp_add_attr_v(vchar_t *buf0, int type, caddr_t val, int len)
2402 {
2403           vchar_t *buf = NULL;
2404           struct isakmp_data *data;
2405           size_t tlen;
2406           size_t oldlen = 0;
2407 
2408           tlen = sizeof(*data) + len;
2409 
2410           if (buf0) {
2411                     oldlen = buf0->l;
2412                     buf = vrealloc(buf0, oldlen + tlen);
2413           } else
2414                     buf = vmalloc(tlen);
2415           if (!buf) {
2416                     plog(LLV_ERROR, LOCATION, NULL,
2417                               "failed to get a attribute buffer.\n");
2418                     return NULL;
2419           }
2420 
2421           data = (struct isakmp_data *)(buf->v + oldlen);
2422           data->type = htons((uint16_t)type | ISAKMP_GEN_TLV);
2423           data->lorv = htons((uint16_t)len);
2424           memcpy(data + 1, val, len);
2425 
2426           return buf;
2427 }
2428 
2429 /* add a fixed data attribute to the buffer by reallocating it. */
2430 vchar_t *
isakmp_add_attr_l(vchar_t * buf0,int type,uint32_t val)2431 isakmp_add_attr_l(vchar_t *buf0, int type, uint32_t val)
2432 {
2433           vchar_t *buf = NULL;
2434           struct isakmp_data *data;
2435           size_t tlen;
2436           size_t oldlen = 0;
2437 
2438           tlen = sizeof(*data);
2439 
2440           if (buf0) {
2441                     oldlen = buf0->l;
2442                     buf = vrealloc(buf0, oldlen + tlen);
2443           } else
2444                     buf = vmalloc(tlen);
2445           if (!buf) {
2446                     plog(LLV_ERROR, LOCATION, NULL,
2447                               "failed to get a attribute buffer.\n");
2448                     return NULL;
2449           }
2450 
2451           data = (struct isakmp_data *)(buf->v + oldlen);
2452           data->type = htons((uint16_t)type | ISAKMP_GEN_TV);
2453           data->lorv = htons((uint16_t)val);
2454 
2455           return buf;
2456 }
2457 
2458 /*
2459  * calculate cookie and set.
2460  */
2461 int
isakmp_newcookie(caddr_t place,struct sockaddr * remote,struct sockaddr * local)2462 isakmp_newcookie(caddr_t place, struct sockaddr *remote, struct sockaddr *local)
2463 {
2464           vchar_t *buf = NULL, *buf2 = NULL;
2465           char *p;
2466           size_t blen;
2467           size_t alen;
2468           caddr_t sa1, sa2;
2469           time_t t;
2470           int error = -1;
2471           u_short port;
2472 
2473 
2474           if (remote->sa_family != local->sa_family) {
2475                     plog(LLV_ERROR, LOCATION, NULL,
2476                               "address family mismatch, remote:%d local:%d\n",
2477                               remote->sa_family, local->sa_family);
2478                     goto end;
2479           }
2480           switch (remote->sa_family) {
2481           case AF_INET:
2482                     alen = sizeof(struct in_addr);
2483                     sa1 = (caddr_t)&((struct sockaddr_in *)remote)->sin_addr;
2484                     sa2 = (caddr_t)&((struct sockaddr_in *)local)->sin_addr;
2485                     break;
2486 #ifdef INET6
2487           case AF_INET6:
2488                     alen = sizeof(struct in6_addr);
2489                     sa1 = (caddr_t)&((struct sockaddr_in6 *)remote)->sin6_addr;
2490                     sa2 = (caddr_t)&((struct sockaddr_in6 *)local)->sin6_addr;
2491                     break;
2492 #endif
2493           default:
2494                     plog(LLV_ERROR, LOCATION, NULL,
2495                               "invalid family: %d\n", remote->sa_family);
2496                     goto end;
2497           }
2498           blen = (alen + sizeof(u_short)) * 2
2499                     + sizeof(time_t) + lcconf->secret_size;
2500           buf = vmalloc(blen);
2501           if (buf == NULL) {
2502                     plog(LLV_ERROR, LOCATION, NULL,
2503                               "failed to get a cookie.\n");
2504                     goto end;
2505           }
2506           p = buf->v;
2507 
2508           /* copy my address */
2509           memcpy(p, sa1, alen);
2510           p += alen;
2511           port = ((struct sockaddr_in *)remote)->sin_port;
2512           memcpy(p, &port, sizeof(u_short));
2513           p += sizeof(u_short);
2514 
2515           /* copy target address */
2516           memcpy(p, sa2, alen);
2517           p += alen;
2518           port = ((struct sockaddr_in *)local)->sin_port;
2519           memcpy(p, &port, sizeof(u_short));
2520           p += sizeof(u_short);
2521 
2522           /* copy time */
2523           t = time(0);
2524           memcpy(p, (caddr_t)&t, sizeof(t));
2525           p += sizeof(t);
2526 
2527           /* copy random value */
2528           buf2 = eay_set_random(lcconf->secret_size);
2529           if (buf2 == NULL)
2530                     goto end;
2531           memcpy(p, buf2->v, lcconf->secret_size);
2532           p += lcconf->secret_size;
2533           vfree(buf2);
2534 
2535           buf2 = eay_sha1_one(buf);
2536           memcpy(place, buf2->v, sizeof(cookie_t));
2537 
2538           sa1 = val2str(place, sizeof (cookie_t));
2539           plog(LLV_DEBUG, LOCATION, NULL, "new cookie:\n%s\n", sa1);
2540           racoon_free(sa1);
2541 
2542           error = 0;
2543 end:
2544           if (buf != NULL)
2545                     vfree(buf);
2546           if (buf2 != NULL)
2547                     vfree(buf2);
2548           return error;
2549 }
2550 
2551 /*
2552  * save partner's(payload) data into phhandle.
2553  */
2554 int
isakmp_p2ph(vchar_t ** buf,struct isakmp_gen * gen)2555 isakmp_p2ph( vchar_t **buf, struct isakmp_gen *gen)
2556 {
2557           /* XXX to be checked in each functions for logging. */
2558           if (*buf) {
2559                     plog(LLV_WARNING, LOCATION, NULL,
2560                               "ignore this payload, same payload type exist.\n");
2561                     return -1;
2562           }
2563 
2564           *buf = vmalloc(ntohs(gen->len) - sizeof(*gen));
2565           if (*buf == NULL) {
2566                     plog(LLV_ERROR, LOCATION, NULL,
2567                               "failed to get buffer.\n");
2568                     return -1;
2569           }
2570           memcpy((*buf)->v, gen + 1, (*buf)->l);
2571 
2572           return 0;
2573 }
2574 
2575 uint32_t
isakmp_newmsgid2(struct ph1handle * iph1)2576 isakmp_newmsgid2(struct ph1handle *iph1)
2577 {
2578           uint32_t msgid2;
2579 
2580           do {
2581                     msgid2 = eay_random();
2582           } while (getph2bymsgid(iph1, msgid2));
2583 
2584           return msgid2;
2585 }
2586 
2587 /*
2588  * set values into allocated buffer of isakmp header for phase 1
2589  */
2590 static caddr_t
set_isakmp_header(vchar_t * vbuf,struct ph1handle * iph1,int nptype,uint8_t etype,uint8_t flags,uint32_t msgid)2591 set_isakmp_header(vchar_t *vbuf, struct ph1handle *iph1, int nptype,
2592     uint8_t etype, uint8_t flags, uint32_t msgid)
2593 {
2594           struct isakmp *isakmp;
2595 
2596           if (vbuf->l < sizeof(*isakmp))
2597                     return NULL;
2598 
2599           isakmp = (struct isakmp *)vbuf->v;
2600 
2601           memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(cookie_t));
2602           memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(cookie_t));
2603           isakmp->np = nptype;
2604           isakmp->v = iph1->version;
2605           isakmp->etype = etype;
2606           isakmp->flags = flags;
2607           isakmp->msgid = msgid;
2608           isakmp->len = htonl(vbuf->l);
2609 
2610           return vbuf->v + sizeof(*isakmp);
2611 }
2612 
2613 /*
2614  * set values into allocated buffer of isakmp header for phase 1
2615  */
2616 caddr_t
set_isakmp_header1(vchar_t * vbuf,struct ph1handle * iph1,int nptype)2617 set_isakmp_header1(vchar_t *vbuf, struct ph1handle *iph1, int nptype)
2618 {
2619           return set_isakmp_header (vbuf, iph1, nptype, iph1->etype, iph1->flags, iph1->msgid);
2620 }
2621 
2622 /*
2623  * set values into allocated buffer of isakmp header for phase 2
2624  */
2625 caddr_t
set_isakmp_header2(vchar_t * vbuf,struct ph2handle * iph2,int nptype)2626 set_isakmp_header2(vchar_t *vbuf, struct ph2handle *iph2, int nptype)
2627 {
2628           return set_isakmp_header (vbuf, iph2->ph1, nptype, ISAKMP_ETYPE_QUICK, iph2->flags, iph2->msgid);
2629 }
2630 
2631 /*
2632  * set values into allocated buffer of isakmp payload.
2633  */
2634 caddr_t
set_isakmp_payload(caddr_t buf,vchar_t * src,int nptype)2635 set_isakmp_payload(caddr_t buf, vchar_t *src, int nptype)
2636 {
2637           struct isakmp_gen *gen;
2638           caddr_t p = buf;
2639 
2640           plog(LLV_DEBUG, LOCATION, NULL, "add payload of len %zu, next type %d\n",
2641               src->l, nptype);
2642 
2643           gen = (struct isakmp_gen *)p;
2644           gen->np = nptype;
2645           gen->len = htons(sizeof(*gen) + src->l);
2646           p += sizeof(*gen);
2647           memcpy(p, src->v, src->l);
2648           p += src->l;
2649 
2650           return p;
2651 }
2652 
2653 static int
etypesw1(int etype)2654 etypesw1(int etype)
2655 {
2656           switch (etype) {
2657           case ISAKMP_ETYPE_IDENT:
2658                     return 1;
2659           case ISAKMP_ETYPE_AGG:
2660                     return 2;
2661           case ISAKMP_ETYPE_BASE:
2662                     return 3;
2663           default:
2664                     return 0;
2665           }
2666           /*NOTREACHED*/
2667 }
2668 
2669 static int
etypesw2(int etype)2670 etypesw2(int etype)
2671 {
2672           switch (etype) {
2673           case ISAKMP_ETYPE_QUICK:
2674                     return 1;
2675           default:
2676                     return 0;
2677           }
2678           /*NOTREACHED*/
2679 }
2680 
2681 #ifdef HAVE_PRINT_ISAKMP_C
2682 /* for print-isakmp.c */
2683 char *snapend;
2684 extern void isakmp_print(const u_char *, u_int, const u_char *);
2685 
2686 char *getname(const u_char *);
2687 #ifdef INET6
2688 char *getname6(const u_char *);
2689 #endif
2690 int safeputchar(int);
2691 
2692 /*
2693  * Return a name for the IP address pointed to by ap.  This address
2694  * is assumed to be in network byte order.
2695  */
2696 char *
getname(ap)2697 getname(ap)
2698           const u_char *ap;
2699 {
2700           struct sockaddr_in addr;
2701           static char ntop_buf[NI_MAXHOST];
2702 
2703           memset(&addr, 0, sizeof(addr));
2704 #ifndef __linux__
2705           addr.sin_len = sizeof(struct sockaddr_in);
2706 #endif
2707           addr.sin_family = AF_INET;
2708           memcpy(&addr.sin_addr, ap, sizeof(addr.sin_addr));
2709           if (getnameinfo((struct sockaddr *)&addr, sizeof(addr),
2710                               ntop_buf, sizeof(ntop_buf), NULL, 0,
2711                               NI_NUMERICHOST | niflags))
2712                     strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2713 
2714           return ntop_buf;
2715 }
2716 
2717 #ifdef INET6
2718 /*
2719  * Return a name for the IP6 address pointed to by ap.  This address
2720  * is assumed to be in network byte order.
2721  */
2722 char *
getname6(ap)2723 getname6(ap)
2724           const u_char *ap;
2725 {
2726           struct sockaddr_in6 addr;
2727           static char ntop_buf[NI_MAXHOST];
2728 
2729           memset(&addr, 0, sizeof(addr));
2730           addr.sin6_len = sizeof(struct sockaddr_in6);
2731           addr.sin6_family = AF_INET6;
2732           memcpy(&addr.sin6_addr, ap, sizeof(addr.sin6_addr));
2733           if (getnameinfo((struct sockaddr *)&addr, addr.sin6_len,
2734                               ntop_buf, sizeof(ntop_buf), NULL, 0,
2735                               NI_NUMERICHOST | niflags))
2736                     strlcpy(ntop_buf, "?", sizeof(ntop_buf));
2737 
2738           return ntop_buf;
2739 }
2740 #endif /* INET6 */
2741 
2742 int
safeputchar(c)2743 safeputchar(c)
2744           int c;
2745 {
2746           unsigned char ch;
2747 
2748           ch = (unsigned char)(c & 0xff);
2749           if (c < 0x80 && isprint(c))
2750                     return printf("%c", c & 0xff);
2751           else
2752                     return printf("\\%03o", c & 0xff);
2753 }
2754 
2755 void
isakmp_printpacket(msg,from,my,decoded)2756 isakmp_printpacket(msg, from, my, decoded)
2757           vchar_t *msg;
2758           struct sockaddr *from;
2759           struct sockaddr *my;
2760           int decoded;
2761 {
2762 #ifdef YIPS_DEBUG
2763           struct timeval tv;
2764           int s;
2765           char hostbuf[NI_MAXHOST];
2766           char portbuf[NI_MAXSERV];
2767           struct isakmp *isakmp;
2768           vchar_t *buf;
2769 #endif
2770 
2771           if (loglevel < LLV_DEBUG)
2772                     return;
2773 
2774 #ifdef YIPS_DEBUG
2775           plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
2776 
2777           gettimeofday(&tv, NULL);
2778           s = tv.tv_sec % 3600;
2779           printf("%02d:%02d.%06u ", s / 60, s % 60, (uint32_t)tv.tv_usec);
2780 
2781           if (from) {
2782                     if (getnameinfo(from, sysdep_sa_len(from), hostbuf, sizeof(hostbuf),
2783                                         portbuf, sizeof(portbuf),
2784                                         NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
2785                               strlcpy(hostbuf, "?", sizeof(hostbuf));
2786                               strlcpy(portbuf, "?", sizeof(portbuf));
2787                     }
2788                     printf("%s:%s", hostbuf, portbuf);
2789           } else
2790                     printf("?");
2791           printf(" -> ");
2792           if (my) {
2793                     if (getnameinfo(my, sysdep_sa_len(my), hostbuf, sizeof(hostbuf),
2794                                         portbuf, sizeof(portbuf),
2795                                         NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
2796                               strlcpy(hostbuf, "?", sizeof(hostbuf));
2797                               strlcpy(portbuf, "?", sizeof(portbuf));
2798                     }
2799                     printf("%s:%s", hostbuf, portbuf);
2800           } else
2801                     printf("?");
2802           printf(": ");
2803 
2804           buf = vdup(msg);
2805           if (!buf) {
2806                     printf("(malloc fail)\n");
2807                     return;
2808           }
2809           if (decoded) {
2810                     isakmp = (struct isakmp *)buf->v;
2811                     if (isakmp->flags & ISAKMP_FLAG_E) {
2812 #if 0
2813                               int pad;
2814                               pad = *(u_char *)(buf->v + buf->l - 1);
2815                               if (buf->l < pad && 2 < vflag)
2816                                         printf("(wrong padding)");
2817 #endif
2818                               isakmp->flags &= ~ISAKMP_FLAG_E;
2819                     }
2820           }
2821 
2822           snapend = buf->v + buf->l;
2823           isakmp_print(buf->v, buf->l, NULL);
2824           vfree(buf);
2825           printf("\n");
2826           fflush(stdout);
2827 
2828           return;
2829 #endif
2830 }
2831 #endif /*HAVE_PRINT_ISAKMP_C*/
2832 
2833 int
copy_ph1addresses(struct ph1handle * iph1,struct remoteconf * rmconf,struct sockaddr * remote,struct sockaddr * local)2834 copy_ph1addresses(struct ph1handle *iph1, struct remoteconf *rmconf,
2835     struct sockaddr *remote, struct sockaddr *local)
2836 {
2837           uint16_t port = 0;
2838 
2839           /* address portion must be grabbed from real remote address "remote" */
2840           iph1->remote = dupsaddr(remote);
2841           if (iph1->remote == NULL)
2842                     return -1;
2843 
2844           /*
2845            * if remote has no port # (in case of initiator - from ACQUIRE msg)
2846            * - if remote.conf specifies port #, use that
2847            * - if remote.conf does not, use lcconf->port_isakmp
2848            * if remote has port # (in case of responder - from recvfrom(2))
2849            * respect content of "remote".
2850            */
2851           if (extract_port(iph1->remote) == 0) {
2852                     port = 0;
2853                     if (rmconf != NULL)
2854                               port = extract_port(rmconf->remote);
2855                     if (port == 0)
2856                               port = lcconf->port_isakmp;
2857                     set_port(iph1->remote, port);
2858           }
2859 
2860           if (local == NULL)
2861                     iph1->local = getlocaladdr(iph1->remote);
2862           else
2863                     iph1->local = dupsaddr(local);
2864           if (iph1->local == NULL)
2865                     return -1;
2866 
2867           if (extract_port(iph1->local) == 0) {
2868                     port = myaddr_getsport(iph1->local);
2869                     if (port == 0)
2870                               port = PORT_ISAKMP;
2871                     set_port(iph1->local, port);
2872           }
2873 
2874 #ifdef ENABLE_NATT
2875           if (extract_port(iph1->local) == lcconf->port_isakmp_natt) {
2876                     plog(LLV_DEBUG, LOCATION, NULL, "Marking ports as changed\n");
2877                     iph1->natt_flags |= NAT_ADD_NON_ESP_MARKER;
2878           }
2879 #endif
2880 
2881           return 0;
2882 }
2883 
2884 /*ARGSUSED*/
2885 static int
nostate1(struct ph1handle * iph1,vchar_t * msg __unused)2886 nostate1(struct ph1handle *iph1, vchar_t *msg __unused)
2887 {
2888           plog(LLV_ERROR, LOCATION, iph1->remote, "wrong state %u.\n",
2889                               iph1->status);
2890           return -1;
2891 }
2892 
2893 /*ARGSUSED*/
2894 static int
nostate2(struct ph2handle * iph2,vchar_t * msg __unused)2895 nostate2(struct ph2handle *iph2, vchar_t *msg __unused)
2896 {
2897           plog(LLV_ERROR, LOCATION, iph2->ph1->remote, "wrong state %u.\n",
2898                     iph2->status);
2899           return -1;
2900 }
2901 
2902 void
log_ph1established(const struct ph1handle * iph1)2903 log_ph1established(const struct ph1handle *iph1)
2904 {
2905           char *src, *dst;
2906 
2907           src = racoon_strdup(saddr2str(iph1->local));
2908           dst = racoon_strdup(saddr2str(iph1->remote));
2909           STRDUP_FATAL(src);
2910           STRDUP_FATAL(dst);
2911 
2912           plog(LLV_INFO, LOCATION, NULL,
2913                     "ISAKMP-SA established %s-%s spi:%s\n",
2914                     src, dst,
2915                     isakmp_pindex(&iph1->index, 0));
2916 
2917           evt_phase1(iph1, EVT_PHASE1_UP, NULL);
2918           if(!iph1->rmconf->mode_cfg)
2919                     evt_phase1(iph1, EVT_PHASE1_MODE_CFG, NULL);
2920 
2921           racoon_free(src);
2922           racoon_free(dst);
2923 
2924           return;
2925 }
2926 
2927 struct payload_list *
isakmp_plist_append_full(struct payload_list * plist,vchar_t * payload,uint8_t payload_type,uint8_t free_payload)2928 isakmp_plist_append_full (struct payload_list *plist, vchar_t *payload,
2929                                 uint8_t payload_type, uint8_t free_payload)
2930 {
2931           if (! plist) {
2932                     plist = racoon_malloc (sizeof (struct payload_list));
2933                     plist->prev = NULL;
2934           }
2935           else {
2936                     plist->next = racoon_malloc (sizeof (struct payload_list));
2937                     plist->next->prev = plist;
2938                     plist = plist->next;
2939           }
2940 
2941           plist->next = NULL;
2942           plist->payload = payload;
2943           plist->payload_type = payload_type;
2944           plist->free_payload = free_payload;
2945 
2946           return plist;
2947 }
2948 
2949 vchar_t *
isakmp_plist_set_all(struct payload_list ** plist,struct ph1handle * iph1)2950 isakmp_plist_set_all (struct payload_list **plist, struct ph1handle *iph1)
2951 {
2952           struct payload_list *ptr = *plist, *first;
2953           size_t tlen = sizeof (struct isakmp), n = 0;
2954           vchar_t *buf = NULL;
2955           char *p;
2956 
2957           /* Seek to the first item.  */
2958           while (ptr->prev) ptr = ptr->prev;
2959           first = ptr;
2960 
2961           /* Compute the whole length.  */
2962           while (ptr) {
2963                     tlen += ptr->payload->l + sizeof (struct isakmp_gen);
2964                     ptr = ptr->next;
2965           }
2966 
2967           buf = vmalloc(tlen);
2968           if (buf == NULL) {
2969                     plog(LLV_ERROR, LOCATION, NULL,
2970                               "failed to get buffer to send.\n");
2971                     goto end;
2972           }
2973 
2974           ptr = first;
2975 
2976           p = set_isakmp_header1(buf, iph1, ptr->payload_type);
2977           if (p == NULL)
2978                     goto end;
2979 
2980           while (ptr)
2981           {
2982                     p = set_isakmp_payload (p, ptr->payload, ptr->next ? ptr->next->payload_type : ISAKMP_NPTYPE_NONE);
2983                     first = ptr;
2984                     ptr = ptr->next;
2985                     if (first->free_payload)
2986                               vfree(first->payload);
2987                     racoon_free (first);
2988                     /* ptr->prev = NULL; first = NULL; ... omitted.  */
2989                     n++;
2990           }
2991 
2992           *plist = NULL;
2993 
2994           return buf;
2995 end:
2996           if (buf != NULL)
2997                     vfree(buf);
2998           return NULL;
2999 }
3000 
3001 #ifdef ENABLE_FRAG
3002 int
frag_handler(struct ph1handle * iph1,vchar_t * msg,struct sockaddr * remote,struct sockaddr * local)3003 frag_handler(struct ph1handle *iph1, vchar_t *msg, struct sockaddr *remote,
3004     struct sockaddr *local)
3005 {
3006           vchar_t *newmsg;
3007 
3008           if (isakmp_frag_extract(iph1, msg) == 1) {
3009                     if ((newmsg = isakmp_frag_reassembly(iph1)) == NULL) {
3010                               plog(LLV_ERROR, LOCATION, remote,
3011                                   "Packet reassembly failed\n");
3012                               return -1;
3013                     }
3014                     return isakmp_main(newmsg, remote, local);
3015           }
3016 
3017           return 0;
3018 }
3019 #endif
3020 
3021 void
script_hook(struct ph1handle * iph1,int script)3022 script_hook(struct ph1handle *iph1, int script)
3023 {
3024 #define IP_MAX 40
3025 #define PORT_MAX 6
3026           char addrstr[IP_MAX];
3027           char portstr[PORT_MAX];
3028           char **envp = NULL;
3029           int envc = 1;
3030           char **c;
3031 
3032           if (iph1 == NULL ||
3033                     iph1->rmconf == NULL ||
3034                     iph1->rmconf->script[script] == NULL)
3035                     return;
3036 
3037 #ifdef ENABLE_HYBRID
3038           (void)isakmp_cfg_setenv(iph1, &envp, &envc);
3039 #endif
3040 
3041           /* local address */
3042           GETNAMEINFO(iph1->local, addrstr, portstr);
3043 
3044           if (script_env_append(&envp, &envc, "LOCAL_ADDR", addrstr) != 0) {
3045                     plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_ADDR\n");
3046                     goto out;
3047           }
3048 
3049           if (script_env_append(&envp, &envc, "LOCAL_PORT", portstr) != 0) {
3050                     plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_PORT\n");
3051                     goto out;
3052           }
3053 
3054           /* Peer address */
3055           if (iph1->remote != NULL) {
3056                     GETNAMEINFO(iph1->remote, addrstr, portstr);
3057 
3058                     if (script_env_append(&envp, &envc,
3059                         "REMOTE_ADDR", addrstr) != 0) {
3060                               plog(LLV_ERROR, LOCATION, NULL,
3061                                   "Cannot set REMOTE_ADDR\n");
3062                               goto out;
3063                     }
3064 
3065                     if (script_env_append(&envp, &envc,
3066                         "REMOTE_PORT", portstr) != 0) {
3067                               plog(LLV_ERROR, LOCATION, NULL,
3068                                   "Cannot set REMOTEL_PORT\n");
3069                               goto out;
3070                     }
3071           }
3072 
3073           /* Peer identity. */
3074           if (iph1->id_p != NULL) {
3075                     if (script_env_append(&envp, &envc, "REMOTE_ID",
3076                                               ipsecdoi_id2str(iph1->id_p)) != 0) {
3077                               plog(LLV_ERROR, LOCATION, NULL,
3078                                    "Cannot set REMOTE_ID\n");
3079                               goto out;
3080                     }
3081           }
3082 
3083           if (privsep_script_exec(iph1->rmconf->script[script]->v,
3084               script, envp) != 0)
3085                     plog(LLV_ERROR, LOCATION, NULL,
3086                         "Script %s execution failed\n", script_names[script]);
3087 
3088 out:
3089           for (c = envp; *c; c++)
3090                     racoon_free(*c);
3091 
3092           racoon_free(envp);
3093 
3094           return;
3095 }
3096 
3097 int
script_env_append(char *** envp,int * envc,const char * name,char * value)3098 script_env_append(char ***envp, int *envc, const char *name, char *value)
3099 {
3100           char *envitem;
3101           char **newenvp;
3102           int newenvc;
3103 
3104           envitem = racoon_malloc(strlen(name) + 1 + strlen(value) + 1);
3105           if (envitem == NULL) {
3106                     plog(LLV_ERROR, LOCATION, NULL,
3107                         "Cannot allocate memory: %s\n", strerror(errno));
3108                     return -1;
3109           }
3110           sprintf(envitem, "%s=%s", name, value);
3111 
3112           newenvc = (*envc) + 1;
3113           newenvp = racoon_realloc(*envp, newenvc * sizeof(char *));
3114           if (newenvp == NULL) {
3115                     plog(LLV_ERROR, LOCATION, NULL,
3116                         "Cannot allocate memory: %s\n", strerror(errno));
3117                     racoon_free(envitem);
3118                     return -1;
3119           }
3120 
3121           newenvp[newenvc - 2] = envitem;
3122           newenvp[newenvc - 1] = NULL;
3123 
3124           *envp = newenvp;
3125           *envc = newenvc;
3126           return 0;
3127 }
3128 
3129 int
script_exec(char * script,int name,char * const envp[])3130 script_exec(char *script, int name, char *const envp[])
3131 {
3132           char *argv[] = { NULL, NULL, NULL };
3133 
3134           argv[0] = script;
3135           argv[1] = __UNCONST(script_names[name]);
3136           argv[2] = NULL;
3137 
3138           switch (fork()) {
3139           case 0:
3140                     execve(argv[0], argv, envp);
3141                     plog(LLV_ERROR, LOCATION, NULL,
3142                         "execve(\"%s\") failed: %s\n",
3143                         argv[0], strerror(errno));
3144                     _exit(1);
3145           case -1:
3146                     plog(LLV_ERROR, LOCATION, NULL,
3147                         "Cannot fork: %s\n", strerror(errno));
3148                     return -1;
3149           default:
3150                     break;
3151           }
3152           return 0;
3153 
3154 }
3155 
3156 void
purge_remote(struct ph1handle * iph1)3157 purge_remote(struct ph1handle *iph1)
3158 {
3159           vchar_t *buf = NULL;
3160           struct sadb_msg *msg, *next, *end;
3161           struct sadb_sa *sa;
3162           struct sockaddr *src, *dst;
3163           caddr_t mhp[SADB_EXT_MAX + 1];
3164           u_int proto_id;
3165           struct ph2handle *iph2;
3166           struct ph1handle *new_iph1;
3167 
3168           plog(LLV_INFO, LOCATION, NULL,
3169                      "purging ISAKMP-SA spi=%s.\n",
3170                      isakmp_pindex(&(iph1->index), iph1->msgid));
3171 
3172           /* Mark as expired. */
3173           iph1->status = PHASE1ST_EXPIRED;
3174 
3175           /* Check if we have another, still valid, phase1 SA. */
3176           new_iph1 = getph1(iph1, iph1->local, iph1->remote, GETPH1_F_ESTABLISHED);
3177 
3178           /*
3179            * Delete all orphaned or binded to the deleting ph1handle phase2 SAs.
3180            * Keep all others phase2 SAs.
3181            */
3182           buf = pfkey_dump_sadb(SADB_SATYPE_UNSPEC);
3183           if (buf == NULL) {
3184                     plog(LLV_DEBUG, LOCATION, NULL,
3185                               "pfkey_dump_sadb returned nothing.\n");
3186                     return;
3187           }
3188 
3189           msg = (struct sadb_msg *)buf->v;
3190           end = (struct sadb_msg *)(buf->v + buf->l);
3191 
3192           while (msg < end) {
3193                     if ((msg->sadb_msg_len << 3) < sizeof(*msg))
3194                               break;
3195                     next = (struct sadb_msg *)((caddr_t)msg + (msg->sadb_msg_len << 3));
3196                     if (msg->sadb_msg_type != SADB_DUMP) {
3197                               msg = next;
3198                               continue;
3199                     }
3200 
3201                     if (pfkey_align(msg, mhp) || pfkey_check(mhp)) {
3202                               plog(LLV_ERROR, LOCATION, NULL,
3203                                         "pfkey_check (%s)\n", ipsec_strerror());
3204                               msg = next;
3205                               continue;
3206                     }
3207 
3208                     sa = (struct sadb_sa *)(mhp[SADB_EXT_SA]);
3209                     if (!sa ||
3210                         !mhp[SADB_EXT_ADDRESS_SRC] ||
3211                         !mhp[SADB_EXT_ADDRESS_DST]) {
3212                               msg = next;
3213                               continue;
3214                     }
3215                     pk_fixup_sa_addresses(mhp);
3216                     src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
3217                     dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
3218 
3219                     if (sa->sadb_sa_state != SADB_SASTATE_LARVAL &&
3220                         sa->sadb_sa_state != SADB_SASTATE_MATURE &&
3221                         sa->sadb_sa_state != SADB_SASTATE_DYING) {
3222                               msg = next;
3223                               continue;
3224                     }
3225 
3226                     /*
3227                      * check in/outbound SAs.
3228                      * Select only SAs where src == local and dst == remote (outgoing)
3229                      * or src == remote and dst == local (incoming).
3230                      */
3231                     if ((cmpsaddr(iph1->local, src) != CMPSADDR_MATCH ||
3232                          cmpsaddr(iph1->remote, dst) != CMPSADDR_MATCH) &&
3233                         (cmpsaddr(iph1->local, dst) != CMPSADDR_MATCH ||
3234                          cmpsaddr(iph1->remote, src) != CMPSADDR_MATCH)) {
3235                               msg = next;
3236                               continue;
3237                     }
3238 
3239                     proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
3240                     iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
3241 
3242                     /* Check if there is another valid ISAKMP-SA */
3243                     if (new_iph1 != NULL) {
3244 
3245                               if (iph2 == NULL) {
3246                                         /* No handler... still send a pfkey_delete message, but log this !*/
3247                                         plog(LLV_INFO, LOCATION, NULL,
3248                                                   "Unknown IPsec-SA spi=%u, hmmmm?\n",
3249                                                   ntohl(sa->sadb_sa_spi));
3250                               }else{
3251 
3252                                         /*
3253                                          * If we have a new ph1, do not purge IPsec-SAs binded
3254                                          *  to a different ISAKMP-SA
3255                                          */
3256                                         if (iph2->ph1 != NULL && iph2->ph1 != iph1){
3257                                                   msg = next;
3258                                                   continue;
3259                                         }
3260 
3261                                         /* If the ph2handle is established, do not purge IPsec-SA */
3262                                         if (iph2->status == PHASE2ST_ESTABLISHED ||
3263                                                   iph2->status == PHASE2ST_EXPIRED) {
3264 
3265                                                   plog(LLV_INFO, LOCATION, NULL,
3266                                                              "keeping IPsec-SA spi=%u - found valid ISAKMP-SA spi=%s.\n",
3267                                                              ntohl(sa->sadb_sa_spi),
3268                                                              isakmp_pindex(&(new_iph1->index), new_iph1->msgid));
3269                                                   msg = next;
3270                                                   continue;
3271                                         }
3272                               }
3273                     }
3274 
3275 
3276                     pfkey_send_delete(lcconf->sock_pfkey,
3277                                           msg->sadb_msg_satype,
3278                                           IPSEC_MODE_ANY,
3279                                           src, dst, sa->sadb_sa_spi);
3280 
3281                     /* delete a relative phase 2 handle. */
3282                     if (iph2 != NULL) {
3283                               delete_spd(iph2, 0);
3284                               remph2(iph2);
3285                               delph2(iph2);
3286                     }
3287 
3288                     plog(LLV_INFO, LOCATION, NULL,
3289                                "purged IPsec-SA spi=%u.\n",
3290                                ntohl(sa->sadb_sa_spi));
3291 
3292                     msg = next;
3293           }
3294 
3295           if (buf)
3296                     vfree(buf);
3297 
3298           /* Mark the phase1 handler as EXPIRED */
3299           plog(LLV_INFO, LOCATION, NULL,
3300                      "purged ISAKMP-SA spi=%s.\n",
3301                      isakmp_pindex(&(iph1->index), iph1->msgid));
3302 
3303           isakmp_ph1delete(iph1);
3304 }
3305 
3306 void
delete_spd(struct ph2handle * iph2,u_int64_t created)3307 delete_spd(struct ph2handle *iph2, u_int64_t created)
3308 {
3309           struct policyindex spidx;
3310           struct sockaddr_storage addr;
3311           uint8_t pref;
3312           struct sockaddr *src;
3313           struct sockaddr *dst;
3314           int error;
3315           int idi2type = 0;/* switch whether copy IDs into id[src,dst]. */
3316 
3317           if (iph2 == NULL)
3318                     return;
3319 
3320           /* Delete the SPD entry if we generated it
3321            */
3322           if (! iph2->generated_spidx )
3323                     return;
3324 
3325           src = iph2->src;
3326           dst = iph2->dst;
3327 
3328           plog(LLV_INFO, LOCATION, NULL,
3329                      "deleting a generated policy.\n");
3330 
3331           memset(&spidx, 0, sizeof(spidx));
3332           iph2->spidx_gen = (caddr_t )&spidx;
3333 
3334           /* make inbound policy */
3335           iph2->src = dst;
3336           iph2->dst = src;
3337           spidx.dir = IPSEC_DIR_INBOUND;
3338           spidx.ul_proto = 0;
3339 
3340           /*
3341            * Note: code from get_proposal_r
3342            */
3343 
3344 #define _XIDT(d) ((struct ipsecdoi_id_b *)(d)->v)->type
3345 
3346           /*
3347            * make destination address in spidx from either ID payload
3348            * or phase 1 address into a address in spidx.
3349            */
3350           if (iph2->id != NULL
3351                     && (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
3352                               || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR
3353                               || _XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR_SUBNET
3354                               || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
3355                     /* get a destination address of a policy */
3356                     error = ipsecdoi_id2sockaddr(iph2->id,
3357                                                                                            (struct sockaddr *)&spidx.dst,
3358                                                                                            &spidx.prefd, &spidx.ul_proto);
3359                     if (error)
3360                               goto purge;
3361 
3362 #ifdef INET6
3363                     /*
3364                      * get scopeid from the SA address.
3365                      * note that the phase 1 source address is used as
3366                      * a destination address to search for a inbound
3367                      * policy entry because rcoon is responder.
3368                      */
3369                     if (_XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR) {
3370                               if ((error =
3371                                          setscopeid((struct sockaddr *)&spidx.dst,
3372                                                                       iph2->src)) != 0)
3373                                         goto purge;
3374                     }
3375 #endif
3376 
3377                     if (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
3378                               || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR)
3379                               idi2type = _XIDT(iph2->id);
3380 
3381           } else {
3382 
3383                     plog(LLV_DEBUG, LOCATION, NULL,
3384                                "get a destination address of SP index "
3385                                "from phase1 address "
3386                                "due to no ID payloads found "
3387                                "OR because ID type is not address.\n");
3388 
3389                     /*
3390                      * copy the SOURCE address of IKE into the
3391                      * DESTINATION address of the key to search the
3392                      * SPD because the direction of policy is inbound.
3393                      */
3394                     memcpy(&spidx.dst, iph2->src, sysdep_sa_len(iph2->src));
3395                     switch (spidx.dst.ss_family) {
3396                     case AF_INET:
3397                               spidx.prefd =
3398                                         sizeof(struct in_addr) << 3;
3399                               break;
3400 #ifdef INET6
3401                     case AF_INET6:
3402                               spidx.prefd =
3403                                         sizeof(struct in6_addr) << 3;
3404                               break;
3405 #endif
3406                     default:
3407                               spidx.prefd = 0;
3408                               break;
3409                     }
3410           }
3411 
3412                     /* make source address in spidx */
3413           if (iph2->id_p != NULL
3414                     && (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR
3415                               || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR
3416                               || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR_SUBNET
3417                               || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
3418                     /* get a source address of inbound SA */
3419                     error = ipsecdoi_id2sockaddr(iph2->id_p,
3420                                                        (struct sockaddr *)&spidx.src,
3421                                                        &spidx.prefs, &spidx.ul_proto);
3422                     if (error)
3423                               goto purge;
3424 
3425 #ifdef INET6
3426                     /*
3427                      * get scopeid from the SA address.
3428                      * for more detail, see above of this function.
3429                      */
3430                     if (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR) {
3431                               error =
3432                                         setscopeid((struct sockaddr *)&spidx.src,
3433                                                                iph2->dst);
3434                               if (error)
3435                                         goto purge;
3436                     }
3437 #endif
3438 
3439                     /* make sa_[src,dst] if both ID types are IP address and same */
3440                     if (_XIDT(iph2->id_p) == idi2type
3441                               && spidx.dst.ss_family == spidx.src.ss_family) {
3442                               iph2->sa_src =
3443                                         dupsaddr((struct sockaddr *)&spidx.dst);
3444                               if (iph2->sa_src == NULL) {
3445                                         plog(LLV_ERROR, LOCATION, NULL,
3446                                                    "allocation failed\n");
3447                                         goto purge;
3448                               }
3449                               iph2->sa_dst =
3450                                         dupsaddr((struct sockaddr *)&spidx.src);
3451                               if (iph2->sa_dst == NULL) {
3452                                         plog(LLV_ERROR, LOCATION, NULL,
3453                                                    "allocation failed\n");
3454                                         goto purge;
3455                               }
3456                     }
3457 
3458           } else {
3459                     plog(LLV_DEBUG, LOCATION, NULL,
3460                                "get a source address of SP index "
3461                                "from phase1 address "
3462                                "due to no ID payloads found "
3463                                "OR because ID type is not address.\n");
3464 
3465                     /* see above comment. */
3466                     memcpy(&spidx.src, iph2->dst, sysdep_sa_len(iph2->dst));
3467                     switch (spidx.src.ss_family) {
3468                     case AF_INET:
3469                               spidx.prefs =
3470                                         sizeof(struct in_addr) << 3;
3471                               break;
3472 #ifdef INET6
3473                     case AF_INET6:
3474                               spidx.prefs =
3475                                         sizeof(struct in6_addr) << 3;
3476                               break;
3477 #endif
3478                     default:
3479                               spidx.prefs = 0;
3480                               break;
3481                     }
3482           }
3483 
3484 #undef _XIDT
3485 
3486           plog(LLV_DEBUG, LOCATION, NULL,
3487                      "get a src address from ID payload "
3488                      "%s prefixlen=%u ul_proto=%u\n",
3489                      saddr2str((struct sockaddr *)&spidx.src),
3490                      spidx.prefs, spidx.ul_proto);
3491           plog(LLV_DEBUG, LOCATION, NULL,
3492                      "get dst address from ID payload "
3493                      "%s prefixlen=%u ul_proto=%u\n",
3494                      saddr2str((struct sockaddr *)&spidx.dst),
3495                      spidx.prefd, spidx.ul_proto);
3496 
3497           /*
3498            * convert the ul_proto if it is 0
3499            * because 0 in ID payload means a wild card.
3500            */
3501           if (spidx.ul_proto == 0)
3502                     spidx.ul_proto = IPSEC_ULPROTO_ANY;
3503 
3504 #undef _XIDT
3505 
3506           /* Check if the generated SPD has the same timestamp as the SA.
3507            * If timestamps are different, this means that the SPD entry has been
3508            * refreshed by another SA, and should NOT be deleted with the current SA.
3509            */
3510           if( created ){
3511                     struct secpolicy *p;
3512 
3513                     p = getsp(&spidx);
3514                     if(p != NULL){
3515                               /* just do no test if p is NULL, because this probably just means
3516                                * that the policy has already be deleted for some reason.
3517                                */
3518                               if(p->spidx.created != created)
3519                                         goto purge;
3520                     }
3521           }
3522 
3523           /* End of code from get_proposal_r
3524            */
3525 
3526           if (pk_sendspddelete(iph2) < 0) {
3527                     plog(LLV_ERROR, LOCATION, NULL,
3528                                "pfkey spddelete(inbound) failed.\n");
3529           }else{
3530                     plog(LLV_DEBUG, LOCATION, NULL,
3531                                "pfkey spddelete(inbound) sent.\n");
3532           }
3533 
3534 #ifdef HAVE_POLICY_FWD
3535           /* make forward policy if required */
3536           if (tunnel_mode_prop(iph2->approval)) {
3537                     spidx.dir = IPSEC_DIR_FWD;
3538                     if (pk_sendspddelete(iph2) < 0) {
3539                               plog(LLV_ERROR, LOCATION, NULL,
3540                                          "pfkey spddelete(forward) failed.\n");
3541                     }else{
3542                               plog(LLV_DEBUG, LOCATION, NULL,
3543                                          "pfkey spddelete(forward) sent.\n");
3544                     }
3545           }
3546 #endif
3547 
3548           /* make outbound policy */
3549           iph2->src = src;
3550           iph2->dst = dst;
3551           spidx.dir = IPSEC_DIR_OUTBOUND;
3552           addr = spidx.src;
3553           spidx.src = spidx.dst;
3554           spidx.dst = addr;
3555           pref = spidx.prefs;
3556           spidx.prefs = spidx.prefd;
3557           spidx.prefd = pref;
3558 
3559           if (pk_sendspddelete(iph2) < 0) {
3560                     plog(LLV_ERROR, LOCATION, NULL,
3561                                "pfkey spddelete(outbound) failed.\n");
3562           }else{
3563                     plog(LLV_DEBUG, LOCATION, NULL,
3564                                "pfkey spddelete(outbound) sent.\n");
3565           }
3566 purge:
3567           iph2->spidx_gen=NULL;
3568 }
3569 
3570 
3571 #ifdef INET6
3572 uint32_t
setscopeid(struct sockaddr * sp_addr0,struct sockaddr * sa_addr0)3573 setscopeid(struct sockaddr *sp_addr0, struct sockaddr *sa_addr0)
3574 {
3575           struct sockaddr_in6 *sp_addr, *sa_addr;
3576 
3577           sp_addr = (struct sockaddr_in6 *)sp_addr0;
3578           sa_addr = (struct sockaddr_in6 *)sa_addr0;
3579 
3580           if (!IN6_IS_ADDR_LINKLOCAL(&sp_addr->sin6_addr)
3581            && !IN6_IS_ADDR_SITELOCAL(&sp_addr->sin6_addr)
3582            && !IN6_IS_ADDR_MULTICAST(&sp_addr->sin6_addr))
3583                     return 0;
3584 
3585           /* this check should not be here ? */
3586           if (sa_addr->sin6_family != AF_INET6) {
3587                     plog(LLV_ERROR, LOCATION, NULL,
3588                               "can't get scope ID: family mismatch\n");
3589                     return (uint32_t)-1;
3590           }
3591 
3592           if (!IN6_IS_ADDR_LINKLOCAL(&sa_addr->sin6_addr)) {
3593                     plog(LLV_ERROR, LOCATION, NULL,
3594                               "scope ID is not supported except of lladdr.\n");
3595                     return (uint32_t)-1;
3596           }
3597 
3598           sp_addr->sin6_scope_id = sa_addr->sin6_scope_id;
3599 
3600           return 0;
3601 }
3602 #endif
3603