OSDN Git Service

2013.10.24
[uclinux-h8/uClinux-dist.git] / freeswan / pluto / ipsec_doi.c
1 /* IPsec DOI and Oakley resolution routines
2  * Copyright (C) 1997 Angelos D. Keromytis.
3  * Copyright (C) 1998-2002  D. Hugh Redelmeier.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; either version 2 of the License, or (at your
8  * option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13  * for more details.
14  *
15  * RCSID $Id$
16  */
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <stddef.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <resolv.h>
27 #include <arpa/nameser.h>       /* missing from <resolv.h> on old systems */
28 #include <sys/time.h>           /* for gettimeofday */
29
30 #include <freeswan.h>
31
32 #include "constants.h"
33 #include "defs.h"
34 #include "state.h"
35 #include "x509.h"
36 #include "id.h"
37 #include "x509.h"
38 #include "connections.h"        /* needs id.h */
39 #include "preshared.h"
40 #include "packet.h"
41 #include "demux.h"      /* needs packet.h */
42 #include "adns.h"       /* needs <resolv.h> */
43 #include "dnskey.h"     /* needs preshared.h and adns.h */
44 #include "kernel.h"
45 #include "log.h"
46 #include "cookie.h"
47 #include "server.h"
48 #include "spdb.h"
49 #include "timer.h"
50 #include "rnd.h"
51 #include "ipsec_doi.h"  /* needs demux.h and state.h */
52 #include "whack.h"
53 #include "pkcs.h"
54
55 #include "sha1.h"
56 #include "md5.h"
57 #include "crypto.h" /* requires sha1.h and md5.h */
58 #include "ike_alg.h"
59 #include "kernel_alg.h"
60 #include "alg_info.h"
61
62 #include "vendor.h"
63
64 #ifdef NAT_TRAVERSAL
65 #include "nat_traversal.h"
66 #endif
67 #ifdef VIRTUAL_IP
68 #include "virtual.h"
69 #endif
70
71 static bool encrypt_message(pb_stream *pbs, struct state *st);  /* forward declaration */
72
73 typedef stf_status initiator_function(
74     int whack_sock,
75     struct connection *c,
76     struct state *predecessor,
77     lset_t policy,
78     unsigned long try);
79
80 /* MAGIC: perform f, a function that returns notification_t
81  * and return from the ENCLOSING stf_status returning function if it fails.
82  */
83 #define RETURN_STF_FAILURE(f) \
84     { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
85
86 static void dpd_init(struct state *st);
87
88 /* create output HDR as replica of input HDR */
89 void
90 echo_hdr(struct msg_digest *md, bool enc, u_int8_t np)
91 {
92     struct isakmp_hdr r_hdr = md->hdr;  /* mostly same as incoming header */
93
94     r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT;     /* we won't ever turn on this bit */
95     if (enc)
96         r_hdr.isa_flags |= ISAKMP_FLAG_ENCRYPTION;
97     /* some day, we may have to set r_hdr.isa_version */
98     r_hdr.isa_np = np;
99     if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
100         impossible();   /* surely must have room and be well-formed */
101 }
102
103 /* Compute DH shared secret from our local secret and the peer's public value.
104  * We make the leap that the length should be that of the group
105  * (see quoted passage at start of ACCEPT_KE).
106  */
107 static void
108 compute_dh_shared(struct state *st, const chunk_t g
109 , const struct oakley_group_desc *group)
110 {
111     MP_INT mp_g, mp_shared;
112     struct timeval tv0, tv1;
113     unsigned long tv_diff;
114
115     gettimeofday(&tv0, NULL);
116     passert(st->st_sec_in_use);
117     n_to_mpz(&mp_g, g.ptr, g.len);
118     mpz_init(&mp_shared);
119     mpz_powm(&mp_shared, &mp_g, &st->st_sec, group->modulus);
120     mpz_clear(&mp_g);
121     freeanychunk(st->st_shared);        /* happens in odd error cases */
122     st->st_shared = mpz_to_n(&mp_shared, group->bytes);
123     mpz_clear(&mp_shared);
124     gettimeofday(&tv1, NULL);
125     tv_diff=(tv1.tv_sec  - tv0.tv_sec) * 1000000 + (tv1.tv_usec - tv0.tv_usec);
126     DBG(DBG_CRYPT, 
127         DBG_log("%s(): time elapsed (%s): %ld usec"
128                 , __FUNCTION__
129                 , enum_show(&oakley_group_names, st->st_oakley.group->group)
130                 , tv_diff);
131        );
132
133 #if 0
134     /* if took more than 200 msec ... */
135     if (tv_diff > 200000) {
136         loglog(RC_LOG_SERIOUS, "WARNING: " __FUNCTION__ "(): for %s took "
137                         "%ld usec"
138                 , enum_show(&oakley_group_names, st->st_oakley.group->group)
139                 , tv_diff);
140     }
141 #endif
142
143 #ifdef DODGE_DH_MISSING_ZERO_BUG
144     if (st->st_shared.ptr[0] == 0)
145         loglog(RC_LOG_SERIOUS, "shared DH secret has leading zero -- triggers Pluto 1.0 bug");
146 #endif
147     DBG_cond_dump_chunk(DBG_CRYPT, "DH shared secret:\n", st->st_shared);
148 }
149
150 /* needed for PGPnet Vendor ID */
151 char pgp_vid[] = "OpenPGP10171";
152
153 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
154  * the corresponding public value (g).  This is emitted as a KE payload.
155  * KLUDGE: if DODGE_DH_MISSING_ZERO_BUG and we're the responder,
156  * this routine computes the shared secret to see if it would
157  * have a leading zero.  If so, we try again.
158  */
159 static bool
160 build_and_ship_KE(struct state *st, chunk_t *g
161 , const struct oakley_group_desc *group, pb_stream *outs, u_int8_t np)
162 {
163     if (!st->st_sec_in_use)
164     {
165         u_char tmp[LOCALSECRETSIZE];
166         MP_INT mp_g;
167
168         get_rnd_bytes(tmp, LOCALSECRETSIZE);
169         st->st_sec_in_use = TRUE;
170         n_to_mpz(&st->st_sec, tmp, LOCALSECRETSIZE);
171
172         mpz_init(&mp_g);
173         mpz_powm(&mp_g, &groupgenerator, &st->st_sec, group->modulus);
174         freeanychunk(*g);       /* happens in odd error cases */
175         *g = mpz_to_n(&mp_g, group->bytes);
176         mpz_clear(&mp_g);
177 #ifdef DODGE_DH_MISSING_ZERO_BUG
178         if (g->ptr[0] == 0)
179         {
180             /* generate a new secret to avoid this situation */
181             loglog(RC_LOG_SERIOUS, "regenerating DH private secret to avoid Pluto 1.0 bug"
182                 " handling public value with leading zero");
183             mpz_clear(&st->st_sec);
184             st->st_sec_in_use = FALSE;
185             return build_and_ship_KE(st, g, group, outs, np);
186         }
187         /* if we're the responder, we can compute the shared secret
188          * to see if it would turn out OK.
189          */
190         if (g == &st->st_gr)
191         {
192             int valid = FALSE;
193
194             compute_dh_shared(st, st->st_gi
195                 , IS_PHASE1(st->st_state)
196                     ? st->st_oakley.group : st->st_pfs_group);
197             {
198                     int i = 0;
199                     for (i = 0; i < st->st_shared.len; i++) {
200                         if (st->st_shared.ptr[i] != 0) {
201                                 valid = TRUE;
202                                 break;
203                         }
204                     }
205             }
206
207             if (!valid) {
208                 return 0;
209             } else if (st->st_shared.ptr[0] == 0) {
210                 /* generate a new secret to avoid this situation */
211                 loglog(RC_LOG_SERIOUS, "regenerating DH private secret to avoid Pluto 1.0 bug"
212                     " handling shared secret with leading zero");
213                 freeanychunk(st->st_shared);
214                 mpz_clear(&st->st_sec);
215                 st->st_sec_in_use = FALSE;
216                 return build_and_ship_KE(st, g, group, outs, np);
217             }
218         }
219 #endif
220
221         DBG(DBG_CRYPT,
222             DBG_dump("Local DH secret:\n", tmp, LOCALSECRETSIZE);
223             DBG_dump_chunk("Public DH value sent:\n", *g));
224     }
225     return out_generic_chunk(np, &isakmp_keyex_desc, outs, *g, "keyex value");
226 }
227
228 /* accept_ke
229  *
230  * Check and accept DH public value (Gi or Gr) from peer's message.
231  * According to RFC2409 "The Internet key exchange (IKE)" 5:
232  *  The Diffie-Hellman public value passed in a KE payload, in either
233  *  a phase 1 or phase 2 exchange, MUST be the length of the negotiated
234  *  Diffie-Hellman group enforced, if necessary, by pre-pending the
235  *  value with zeros.
236  * ??? For now, if DODGE_DH_MISSING_ZERO_BUG is defined, we accept shorter
237  *     values to interoperate with old Plutos.  This should change some day.
238  */
239 static notification_t
240 accept_KE(chunk_t *dest, const char *val_name
241 , const struct oakley_group_desc *gr
242 , pb_stream *pbs)
243 {
244     if (pbs_left(pbs) != gr->bytes)
245     {
246         loglog(RC_LOG_SERIOUS, "KE has %u byte DH public value; %u required"
247             , (unsigned) pbs_left(pbs), (unsigned) gr->bytes);
248 #ifdef DODGE_DH_MISSING_ZERO_BUG
249         if (pbs_left(pbs) > gr->bytes)
250 #endif
251             return INVALID_KEY_INFORMATION;
252     }
253     clonereplacechunk(*dest, pbs->cur, pbs_left(pbs), val_name);
254     DBG_cond_dump_chunk(DBG_CRYPT, "DH public value received:\n", *dest);
255     return NOTHING_WRONG;
256 }
257
258 /* accept_PFS_KE
259  *
260  * Check and accept optional Quick Mode KE payload for PFS.
261  * Extends ACCEPT_PFS to check whether KE is allowed or required.
262  */
263 static notification_t
264 accept_PFS_KE(struct msg_digest *md, chunk_t *dest
265 , const char *val_name, const char *msg_name)
266 {
267     struct state *st = md->st;
268     struct payload_digest *const ke_pd = md->chain[ISAKMP_NEXT_KE];
269
270     if (ke_pd == NULL)
271     {
272         if (st->st_pfs_group != NULL)
273         {
274             loglog(RC_LOG_SERIOUS, "missing KE payload in %s message", msg_name);
275             return INVALID_KEY_INFORMATION;
276         }
277     }
278     else
279     {
280         if (st->st_pfs_group == NULL)
281         {
282             loglog(RC_LOG_SERIOUS, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
283                 , msg_name);
284             return INVALID_KEY_INFORMATION;
285         }
286         if (ke_pd->next != NULL)
287         {
288             loglog(RC_LOG_SERIOUS, "%s message contains several KE payloads; we accept at most one", msg_name);
289             return INVALID_KEY_INFORMATION;     /* ??? */
290         }
291         return accept_KE(dest, val_name, st->st_pfs_group, &ke_pd->pbs);
292     }
293     return NOTHING_WRONG;
294 }
295
296 static bool
297 build_and_ship_nonce(chunk_t *n, pb_stream *outs, u_int8_t np
298 , const char *name)
299 {
300     setchunk(*n, alloc_bytes(DEFAULT_NONCE_SIZE, name), DEFAULT_NONCE_SIZE);
301     get_rnd_bytes(n->ptr, DEFAULT_NONCE_SIZE);
302     return out_generic_chunk(np, &isakmp_nonce_desc, outs, *n, name);
303 }
304
305 /*
306  * Send a notification to the peer. We could make a decision on
307  * whether to send the notification, based on the type and the
308  * destination, if we care to.
309  * It doesn't handle DELETE notifications (see send_ipsec_delete)
310  */
311 static void
312 send_notification(struct state *sndst, u_int16_t type, struct state *encst,
313     msgid_t msgid, u_char *icookie, u_char *rcookie,
314     u_char *spi, size_t spisize, u_char protoid)
315 {
316     u_char buffer[1024];
317     pb_stream pbs, r_hdr_pbs;
318     u_char *r_hashval, *r_hash_start;
319
320     passert((sndst) && (sndst->st_connection));
321
322     log("sending %snotification %s to %s:%u",
323         encst ? "encrypted " : "",
324         enum_name(&ipsec_notification_names, type),
325         ip_str(&sndst->st_connection->that.host_addr),
326         (unsigned)sndst->st_connection->that.host_port);
327         
328     memset(buffer, 0, sizeof(buffer));
329     init_pbs(&pbs, buffer, sizeof(buffer), "notification msg");
330
331     /* HDR* */
332     {
333         struct isakmp_hdr hdr;
334
335         hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
336         hdr.isa_np = encst ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_N;
337         hdr.isa_xchg = ISAKMP_XCHG_INFO;
338         hdr.isa_msgid = msgid;
339         hdr.isa_flags = encst ? ISAKMP_FLAG_ENCRYPTION : 0;
340         if (icookie)
341             memcpy(hdr.isa_icookie, icookie, COOKIE_SIZE);
342         if (rcookie)
343             memcpy(hdr.isa_rcookie, rcookie, COOKIE_SIZE);
344         if (!out_struct(&hdr, &isakmp_hdr_desc, &pbs, &r_hdr_pbs))
345             impossible();
346     }
347
348     /* HASH -- value to be filled later */
349     if (encst)
350     {
351         pb_stream hash_pbs;
352         if (!out_generic(ISAKMP_NEXT_N, &isakmp_hash_desc, &r_hdr_pbs,
353             &hash_pbs))
354             impossible();
355         r_hashval = hash_pbs.cur;  /* remember where to plant value */
356         if (!out_zero(
357 #ifdef _IKE_ALG_H
358             encst->st_oakley.hasher->hash_digest_size,
359 #else
360             encst->st_oakley.hasher->hash_digest_len,
361 #endif
362             &hash_pbs, "HASH(1)"))
363             impossible();
364         close_output_pbs(&hash_pbs);
365         r_hash_start = r_hdr_pbs.cur; /* hash from after HASH(1) */
366     }
367
368     /* Notification Payload */
369     {
370         pb_stream not_pbs;
371         struct isakmp_notification isan;
372
373         isan.isan_doi = ISAKMP_DOI_IPSEC;
374         isan.isan_np = ISAKMP_NEXT_NONE;
375         isan.isan_type = type;
376         isan.isan_spisize = spisize;
377         isan.isan_protoid = protoid;
378
379         if (!out_struct(&isan, &isakmp_notification_desc, &r_hdr_pbs, &not_pbs)
380             || !out_raw(spi, spisize, &not_pbs, "spi"))
381             impossible();
382         close_output_pbs(&not_pbs);
383     }
384
385     /* calculate hash value and patch into Hash Payload */
386     if (encst)
387     {
388         struct hmac_ctx ctx;
389         hmac_init_chunk(&ctx, encst->st_oakley.hasher, encst->st_skeyid_a);
390         hmac_update(&ctx, (u_char *) &msgid, sizeof(msgid_t));
391         hmac_update(&ctx, r_hash_start, r_hdr_pbs.cur-r_hash_start);
392         hmac_final(r_hashval, &ctx);
393
394 #ifdef _IKE_ALG_H
395         DBG(DBG_CRYPT,
396             DBG_log("HASH(1) computed:");
397             DBG_dump("", r_hashval, ctx.hmac_digest_size);
398         )
399     }
400 #else
401         DBG(DBG_CRYPT,
402             DBG_log("HASH(1) computed:");
403             DBG_dump("", r_hashval, ctx.hmac_digest_len);
404         )
405     }
406 #endif
407
408     /* Encrypt message (preserve st_iv) */
409     if (encst)
410     {
411         u_char old_iv[MAX_DIGEST_LEN];
412         if (encst->st_iv_len > MAX_DIGEST_LEN)
413             impossible();
414         memcpy(old_iv, encst->st_iv, encst->st_iv_len);
415         init_phase2_iv(encst, &msgid);
416         if (!encrypt_message(&r_hdr_pbs, encst))
417             impossible();
418         memcpy(encst->st_iv, old_iv, encst->st_iv_len);
419     }
420     else
421     {
422         close_output_pbs(&r_hdr_pbs);
423     }
424
425     /* Send packet (preserve st_tpacket) */
426     {
427         chunk_t saved_tpacket = sndst->st_tpacket;
428
429         setchunk(sndst->st_tpacket, pbs.start, pbs_offset(&pbs));
430         send_packet(sndst, "notification packet");
431         sndst->st_tpacket = saved_tpacket;
432     }
433 }
434
435 void
436 send_notification_from_state(struct state *st, enum state_kind state,
437     u_int16_t type)
438 {
439     struct state *p1st;
440
441     passert(st);
442
443     if (state == STATE_UNDEFINED)
444         state = st->st_state;
445
446     if (IS_QUICK(state)) {
447         p1st = find_phase1_state(st->st_connection, TRUE);
448         if ((p1st == NULL) || (!IS_ISAKMP_SA_ESTABLISHED(p1st->st_state))) {
449             loglog(RC_LOG_SERIOUS,
450                 "no Phase1 state for Quick mode notification");
451             return;
452         }
453         send_notification(st, type, p1st, generate_msgid(p1st),
454             st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
455     }
456     else if (IS_ISAKMP_SA_ESTABLISHED(state)) {
457         send_notification(st, type, st, generate_msgid(st),
458             st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
459     }
460     else {
461         /* no ISAKMP SA established - don't encrypt notification */
462         send_notification(st, type, NULL, 0,
463             st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
464     }
465 }
466
467 void
468 send_notification_from_md(struct msg_digest *md, u_int16_t type)
469 {
470     /**
471      * Create a dummy state to be able to use send_packet in
472      * send_notification
473      *
474      * we need to set:
475      *   st_connection->that.host_addr
476      *   st_connection->that.host_port
477      *   st_connection->interface
478      */
479     struct state st;
480     struct connection cnx;
481
482     passert(md);
483
484     memset(&st, 0, sizeof(st));
485     memset(&cnx, 0, sizeof(cnx));
486     st.st_connection = &cnx;
487     cnx.that.host_addr = md->sender;
488     cnx.that.host_port = md->sender_port;
489     cnx.interface = md->iface;
490
491     send_notification(&st, type, NULL, 0,
492         md->hdr.isa_icookie, md->hdr.isa_rcookie, NULL, 0, PROTO_ISAKMP);
493 }
494
495 /* Send a Delete Notification to announce deletion of inbound IPSEC/ISAKMP SAs.
496  * Ignores states that don't have any.
497  * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
498  */
499 void
500 send_delete(struct state *st)
501 {
502     pb_stream reply_pbs;
503     pb_stream r_hdr_pbs;
504     msgid_t     msgid;
505     u_char buffer[8192];
506     struct state *p1st;
507     ip_said said[EM_MAXRELSPIS];
508     ip_said *ns = said;
509     u_char
510         *r_hashval,     /* where in reply to jam hash value */
511         *r_hash_start;  /* start of what is to be hashed */
512     bool isakmp_sa = FALSE;
513
514     if (IS_IPSEC_SA_ESTABLISHED(st->st_state)) {
515         p1st = find_phase1_state(st->st_connection, TRUE);
516         if (p1st == NULL)
517         {
518             DBG(DBG_CONTROL, DBG_log("no Phase 1 state for Delete"));
519             return;
520         }
521
522         if (st->st_ah.present)
523         {
524             ns->spi = st->st_ah.our_spi;
525             ns->dst = st->st_connection->this.host_addr;
526             ns->proto = PROTO_IPSEC_AH;
527             ns++;
528         }
529         if (st->st_esp.present)
530         {
531             ns->spi = st->st_esp.our_spi;
532             ns->dst = st->st_connection->this.host_addr;
533             ns->proto = PROTO_IPSEC_ESP;
534             ns++;
535         }
536         
537         passert(ns != said);    /* there must be some SAs to delete */
538     }
539     else if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
540         p1st = st;
541         isakmp_sa = TRUE;
542     }
543     else {
544         return; /* nothing to do */
545     }
546
547     msgid = generate_msgid(p1st);
548
549     memset(buffer, '\0', sizeof(buffer));
550     init_pbs(&reply_pbs, buffer, sizeof(buffer), "delete msg");
551
552     /* HDR* */
553     {
554         struct isakmp_hdr hdr;
555
556         hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
557         hdr.isa_np = ISAKMP_NEXT_HASH;
558         hdr.isa_xchg = ISAKMP_XCHG_INFO;
559         hdr.isa_msgid = msgid;
560         hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
561         memcpy(hdr.isa_icookie, p1st->st_icookie, COOKIE_SIZE);
562         memcpy(hdr.isa_rcookie, p1st->st_rcookie, COOKIE_SIZE);
563         if (!out_struct(&hdr, &isakmp_hdr_desc, &reply_pbs, &r_hdr_pbs))
564             impossible();
565     }
566
567     /* HASH -- value to be filled later */
568     {
569         pb_stream hash_pbs;
570
571         if (!out_generic(ISAKMP_NEXT_D, &isakmp_hash_desc, &r_hdr_pbs, &hash_pbs))
572             impossible();
573         r_hashval = hash_pbs.cur;       /* remember where to plant value */
574         if (!out_zero(p1st->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH(1)"))
575             impossible();
576         close_output_pbs(&hash_pbs);
577         r_hash_start = r_hdr_pbs.cur;   /* hash from after HASH(1) */
578     }
579
580     /* Delete Payloads */
581     if (isakmp_sa) {
582         pb_stream del_pbs;
583         struct isakmp_delete isad;
584         u_char isakmp_spi[2*COOKIE_SIZE];
585
586         isad.isad_doi = ISAKMP_DOI_IPSEC;
587         isad.isad_np = ISAKMP_NEXT_NONE;
588         isad.isad_spisize = (2 * COOKIE_SIZE);
589         isad.isad_protoid = PROTO_ISAKMP;
590         isad.isad_nospi = 1;
591
592         memcpy(isakmp_spi, st->st_icookie, COOKIE_SIZE);
593         memcpy(isakmp_spi+COOKIE_SIZE, st->st_rcookie, COOKIE_SIZE);
594
595         if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
596         || !out_raw(&isakmp_spi, (2*COOKIE_SIZE), &del_pbs, "delete payload"))
597             impossible();
598         close_output_pbs(&del_pbs);
599     }
600     else while (ns != said) {
601         pb_stream del_pbs;
602         struct isakmp_delete isad;
603
604         ns--;
605         isad.isad_doi = ISAKMP_DOI_IPSEC;
606         isad.isad_np = ns == said? ISAKMP_NEXT_NONE : ISAKMP_NEXT_D;
607         isad.isad_spisize = sizeof(ipsec_spi_t);
608         isad.isad_protoid = ns->proto;
609         isad.isad_nospi = 1;
610
611         if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
612         || !out_raw(&ns->spi, sizeof(ipsec_spi_t), &del_pbs, "delete payload"))
613             impossible();
614         close_output_pbs(&del_pbs);
615     }
616
617     /* calculate hash value and patch into Hash Payload */
618     {
619         struct hmac_ctx ctx;
620         hmac_init_chunk(&ctx, p1st->st_oakley.hasher, p1st->st_skeyid_a);
621         hmac_update(&ctx, (u_char *) &msgid, sizeof(msgid_t));
622         hmac_update(&ctx, r_hash_start, r_hdr_pbs.cur-r_hash_start);
623         hmac_final(r_hashval, &ctx);
624
625         DBG(DBG_CRYPT,
626             DBG_log("HASH(1) computed:");
627             DBG_dump("", r_hashval, ctx.hmac_digest_size);
628         )
629     }
630
631     /* Do a dance to avoid needing a new state object.
632      * We use the Phase 1 State.  This is the one with right
633      * IV, for one thing.
634      * The tricky bits are:
635      * - we need to preserve (save/restore) st_iv (but not st_iv_new)
636      * - we need to preserve (save/restore) st_tpacket.
637      */
638     {
639         u_char old_iv[MAX_DIGEST_LEN];
640         chunk_t saved_tpacket = p1st->st_tpacket;
641
642         memcpy(old_iv, p1st->st_iv, p1st->st_iv_len);
643         init_phase2_iv(p1st, &msgid);
644
645         if(!encrypt_message(&r_hdr_pbs, p1st))
646             impossible();
647
648         setchunk(p1st->st_tpacket, reply_pbs.start, pbs_offset(&reply_pbs));
649         send_packet(p1st, "delete notify");
650         p1st->st_tpacket = saved_tpacket;
651
652         /* get back old IV for this state */
653         memcpy(p1st->st_iv, old_iv, p1st->st_iv_len);
654     }
655 }
656
657 void
658 accept_delete(struct state *st, struct msg_digest *md, struct payload_digest *p)
659 {
660     struct isakmp_delete *d = &(p->payload.delete);
661     size_t sizespi = 0;
662     u_char *spi;
663     struct state *dst = NULL;
664     int i;
665
666     if ((!st) && (!(md->hdr.isa_flags & ISAKMP_FLAG_ENCRYPTION))) {
667         loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: not encrypted");
668         return;
669     }
670
671     if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state)) {
672         /* can't happen (if msg is encrypt), but just to be sure */
673         loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
674         "ISAKMP SA not established");
675         return;
676     }
677
678     if (d->isad_nospi == 0) {
679         loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: no SPI");
680         return;
681     }
682
683     if (pbs_left(&p->pbs) != ((unsigned)d->isad_spisize * d->isad_nospi)) {
684         loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: invalid size");
685         return;
686     }
687
688     switch (d->isad_protoid) {
689         case PROTO_ISAKMP:
690             sizespi = (2*COOKIE_SIZE);
691             break;
692         case PROTO_IPSEC_AH:
693         case PROTO_IPSEC_ESP:
694             sizespi = sizeof(ipsec_spi_t);
695             break;
696         default:
697             loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
698                 "unknown Protocol ID (%s)",
699                 enum_show(&protocol_names, d->isad_protoid));
700             return;
701             break;
702     }
703
704     if (d->isad_spisize != sizespi) {
705         loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
706             "bad size (%d) for Protocol (%s)",
707             d->isad_spisize,
708             enum_show(&protocol_names, d->isad_protoid));
709         return;
710     }
711
712     for (i=0; i<d->isad_nospi; i++) {
713         spi = p->pbs.cur + (i * sizespi);
714         if (d->isad_protoid == PROTO_ISAKMP) {
715             /**
716              * ISAKMP
717              */
718             dst = find_phase1_state_to_delete(st, spi /*iCookie*/,
719                 spi+COOKIE_SIZE /*rCookie*/);
720             if (dst) {
721                 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
722                     "deleting ISAKMP State #%lu", dst->st_serialno);
723                 delete_state(dst);
724             }
725             else {
726                 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
727                     "ISAKMP SA not found (maybe expired)");
728             }
729         }
730         else {
731             /**
732              * IPSEC (ESP/AH)
733              */
734             bool bogus;
735             ipsec_spi_t ipsec_spi = *((ipsec_spi_t *)spi);
736
737             dst = find_phase2_state_to_delete(st, d->isad_protoid, ipsec_spi, &bogus);
738             if (dst) {
739                 struct connection *rc = dst->st_connection;
740                 if ((rc) && (rc->newest_ipsec_sa == dst->st_serialno) &&
741                     (rc->initiated)) {
742                     /*
743                      * Last IPSec SA for a permanent connection that we
744                      * have initiated. Replace it in a few seconds.
745                      *
746                      * Usefull if the other peer is rebooting
747                      */
748 #define DELETE_SA_DELAY  EVENT_RETRANSMIT_DELAY_0
749                     if ((dst->st_event) &&
750                         (dst->st_event->ev_type == EVENT_SA_REPLACE) &&
751                         (dst->st_event->ev_time <= DELETE_SA_DELAY + now())) {
752                         /*
753                          * Patch from Angus Lees to ignore retransmited Delete SA.
754                          */
755                         loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
756                             "already replacing IPSEC State #%lu in %d seconds",
757                             dst->st_serialno, (int)(dst->st_event->ev_time - now()));
758                     }
759                     else {
760                         loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
761                             "replace IPSEC State #%lu in %d seconds",
762                             dst->st_serialno, DELETE_SA_DELAY);
763                         dst->st_margin = DELETE_SA_DELAY;
764                         delete_event(dst);
765                         event_schedule(EVENT_SA_REPLACE, DELETE_SA_DELAY, dst);
766                     }
767                 }
768                 else {
769                     loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
770                         "deleting IPSEC State #%lu", dst->st_serialno);
771                     delete_state(dst);
772                 }
773             }
774             else {
775                 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
776                     "IPSEC SA not found (%s)",
777                     bogus ? "our spi - bogus implementation" : "maybe expired");
778             }
779         }
780     }
781 }
782
783 /* The whole message must be a multiple of 4 octets.
784  * I'm not sure where this is spelled out, but look at
785  * rfc2408 3.6 Transform Payload.
786  * Note: it talks about 4 BYTE boundaries!
787  */
788 static void
789 close_message(pb_stream *pbs)
790 {
791     size_t padding =  pad_up(pbs_offset(pbs), 4);
792
793     if (padding != 0)
794         (void) out_zero(padding, pbs, "message padding");
795     close_output_pbs(pbs);
796 }
797
798 /* Initiate an Oakley Main Mode exchange.
799  * --> HDR;SA
800  * Note: this is not called from demux.c
801  */
802 static stf_status
803 main_outI1(int whack_sock
804 , struct connection *c
805 , struct state *predecessor
806 , lset_t policy
807 , unsigned long try)
808 {
809     struct state *st = new_state();
810     pb_stream reply;    /* not actually a reply, but you know what I mean */
811     pb_stream rbody;
812
813     /* set up new state */
814     st->st_connection = c;
815     set_cur_state(st);  /* we must reset before exit */
816     st->st_policy = policy & ~POLICY_IPSEC_MASK;
817     st->st_whack_sock = whack_sock;
818     st->st_try = try;
819     st->st_state = STATE_MAIN_I1;
820
821     get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->that.host_addr);
822
823     if (c->dnshostname != NULL)
824     {
825         ip_address new_addr;
826
827         if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
828         && !sameaddr(&new_addr, &c->that.host_addr))
829         {
830             c->that.host_addr = new_addr;
831             state_rehash(c);
832             load_preshared_secrets();
833         }
834     }
835
836     insert_state(st);   /* needs cookies, connection, and msgid (0) */
837
838     if (HAS_IPSEC_POLICY(policy))
839         add_pending(dup_any(whack_sock), st, c, policy, 1
840             , predecessor == NULL? SOS_NOBODY : predecessor->st_serialno);
841
842     if (predecessor == NULL)
843         log("initiating Main Mode");
844     else
845         log("initiating Main Mode to replace #%lu", predecessor->st_serialno);
846
847     /* set up reply */
848     init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
849
850     /* HDR out */
851     {
852         struct isakmp_hdr hdr;
853         zero(&hdr);     /* default to 0 */
854         hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
855         hdr.isa_np = ISAKMP_NEXT_SA;
856         hdr.isa_xchg = ISAKMP_XCHG_IDPROT;
857         memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
858         /* R-cookie, flags and MessageID are left zero */
859
860         if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
861         {
862             reset_cur_state();
863             return STF_INTERNAL_ERROR;
864         }
865     }
866     DBG(DBG_CONTROL, DBG_log("main_outI1 - 4"));
867     /* SA out */
868     {
869         u_char *sa_start = rbody.cur;
870         lset_t auth_policy = policy & POLICY_ID_AUTH_MASK;
871
872         /* if we  use an ID_KEY_ID as own ID, we assume a
873          * PGPcert peer and have to send the Vendor ID
874          *  ++++ not sure, if this is an interop problem ++++++
875          */
876 #if 0    
877         int np = (c->this.id.kind == ID_KEY_ID)? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
878 #endif
879
880         int np = ISAKMP_NEXT_VID;
881
882         if (!out_sa(&rbody
883         , &oakley_sadb[auth_policy >> POLICY_ISAKMP_SHIFT]
884         , st, TRUE, np))
885         {
886             reset_cur_state();
887             return STF_INTERNAL_ERROR;
888         }
889         DBG(DBG_CONTROL, DBG_log("main_outI1 - 8"));
890         /* save initiator SA for later HASH */
891         passert(st->st_p1isa.ptr == NULL);      /* no leak!  (MUST be first time) */
892         clonetochunk(st->st_p1isa, sa_start, rbody.cur - sa_start
893             , "sa in main_outI1");
894     }
895
896     if (c->this.id.kind == ID_KEY_ID)
897     {
898             if (!out_generic_raw(ISAKMP_NEXT_VID, &isakmp_vendor_id_desc, &rbody
899             , pgp_vid, sizeof(pgp_vid)-1, "V_ID"))
900                  return STF_INTERNAL_ERROR;
901     }
902
903 #ifdef NAT_TRAVERSAL
904     if (nat_traversal_enabled) {
905         /* Add supported NAT-Traversal VID */
906         if (!nat_traversal_add_vid(ISAKMP_NEXT_VID, &rbody)) {
907             reset_cur_state();
908             return STF_INTERNAL_ERROR;
909         }
910     }
911 #endif
912
913     /* VID out */
914     if (!out_vendorid(ISAKMP_NEXT_NONE, &rbody, VID_MISC_DPD))
915         return STF_INTERNAL_ERROR;
916
917     close_message(&rbody);
918     close_output_pbs(&reply);
919
920     clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
921         , "reply packet for main_outI1");
922
923     /* Transmit */
924     DBG(DBG_CONTROL, DBG_log("main_outI1 - 9"));
925     send_packet(st, "main_outI1");
926
927     /* Set up a retransmission event, half a minute henceforth */
928     delete_event(st);
929     event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
930     DBG(DBG_CONTROL, DBG_log("main_outI1 - 10"));
931     if (predecessor != NULL)
932     {
933         update_pending(predecessor, st);
934         whack_log(RC_NEW_STATE + STATE_MAIN_I1
935             , "%s: initiate, replacing #%lu"
936             , enum_name(&state_names, st->st_state)
937             , predecessor->st_serialno);
938     }
939     else
940     {
941         DBG(DBG_CONTROL, DBG_log("main_outI1 - 11"));
942         whack_log(RC_NEW_STATE + STATE_MAIN_I1
943             , "%s: initiate", enum_name(&state_names, st->st_state));
944     }
945     reset_cur_state();
946     return STF_OK;
947 }
948
949
950 /* Initiate an Oakley Aggressive Mode exchange.
951  * --> HDR, SA, KE, Ni, IDii
952  */
953 static stf_status
954 aggr_outI1(
955         int whack_sock,
956         struct connection *c,
957         struct state *predecessor,
958         lset_t policy,
959         unsigned long try)
960 {
961     struct state *st = new_state();
962     pb_stream reply;    /* not actually a reply, but you know what I mean */
963     pb_stream rbody;
964
965     struct db_sa *sadb;
966
967     /* set up new state */
968     st->st_connection = c;
969     set_cur_state(st);  /* we must reset before exit */
970     st->st_policy = policy & ~POLICY_IPSEC_MASK;
971     st->st_whack_sock = whack_sock;
972     st->st_try = try;
973     st->st_state = STATE_AGGR_I1;
974
975     get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->that.host_addr);
976
977     if (c->dnshostname != NULL)
978     {
979         ip_address new_addr;
980
981         if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
982         && !sameaddr(&new_addr, &c->that.host_addr))
983         {
984             c->that.host_addr = new_addr;
985             state_rehash(c);
986             load_preshared_secrets();
987         }
988     }
989
990     insert_state(st);   /* needs cookies, connection, and msgid (0) */
991     
992     if (HAS_IPSEC_POLICY(policy))
993         add_pending(dup_any(whack_sock), st, c, policy, 1
994             , predecessor == NULL? SOS_NOBODY : predecessor->st_serialno);
995     if (predecessor == NULL)
996         log("initiating Aggressive Mode");
997     else
998         log("initiating Aggressive Mode to replace #%lu"
999         , predecessor->st_serialno);
1000
1001     /* set up reply */
1002     init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
1003
1004     /* HDR out */
1005     {
1006         struct isakmp_hdr hdr;
1007
1008         zero(&hdr);     /* default to 0 */
1009         hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
1010         hdr.isa_np = ISAKMP_NEXT_SA;
1011         hdr.isa_xchg = ISAKMP_XCHG_AGGR;
1012         memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
1013         /* R-cookie, flags and MessageID are left zero */
1014
1015         if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
1016         {
1017             reset_cur_state();
1018             return STF_INTERNAL_ERROR;
1019         }
1020     }
1021
1022     /* SA out */
1023     {
1024         u_char *sa_start = rbody.cur;
1025         lset_t auth_policy = policy & POLICY_ID_AUTH_MASK;
1026         /* if we  use an ID_KEY_ID as own ID, we assume a
1027          * PGPcert peer and have to send the Vendor ID
1028          *  ++++ not sure, if this is an interop problem ++++++
1029          */
1030
1031         int np = (c->this.id.kind == ID_KEY_ID)? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
1032
1033         init_st_oakley(st, auth_policy);
1034
1035         if (st->st_connection->algorithm_p1.dhg == OAKLEY_GROUP_MODP768) {
1036                 if (st->st_connection->algorithm_p1.hash == OAKLEY_SHA) 
1037                         if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC) 
1038                                 sadb = &otpsk768des3sha_sadb_am;
1039                         else
1040                                 sadb = &otpsk768dessha_sadb_am;
1041                 else 
1042                         if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC) 
1043                                 sadb = &otpsk768des3md5_sadb_am;
1044                         else
1045                                 sadb = &otpsk768desmd5_sadb_am;
1046         } else if (st->st_connection->algorithm_p1.dhg == OAKLEY_GROUP_MODP1024) {
1047                 if (st->st_connection->algorithm_p1.hash == OAKLEY_SHA) 
1048                         if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC)
1049                                 sadb = &otpsk1024des3sha_sadb_am;
1050                         else 
1051                                 sadb = &otpsk1024dessha_sadb_am;
1052                 else 
1053                         if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC)
1054                                 sadb = &otpsk1024des3md5_sadb_am;
1055                         else
1056                                 sadb = &otpsk1024desmd5_sadb_am;
1057
1058         } else {
1059                 if (st->st_connection->algorithm_p1.hash == OAKLEY_SHA) 
1060                         if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC) 
1061                                 sadb = &otpsk1536des3sha_sadb_am;
1062                         else
1063                                 sadb = &otpsk1536dessha_sadb_am;
1064                 else 
1065                         if (st->st_connection->algorithm_p1.cipher == OAKLEY_3DES_CBC) 
1066                                 sadb = &otpsk1536des3md5_sadb_am;
1067                         else
1068                                 sadb = &otpsk1536desmd5_sadb_am;
1069         }
1070
1071         if (!out_sa(&rbody, sadb, st, TRUE, ISAKMP_NEXT_VID))
1072         {
1073             reset_cur_state();
1074             return STF_INTERNAL_ERROR;
1075         }
1076
1077         /* save initiator SA for later HASH */
1078         passert(st->st_p1isa.ptr == NULL);      /* no leak!  (MUST be first time) */
1079         clonetochunk(st->st_p1isa, sa_start, rbody.cur - sa_start
1080             , "sa in aggr_outI1");
1081
1082     }
1083
1084 #ifdef NAT_TRAVERSAL
1085     if (nat_traversal_enabled) {
1086         /* Add supported NAT-Traversal VID */
1087         if (!nat_traversal_add_vid(ISAKMP_NEXT_VID, &rbody)) {
1088             reset_cur_state();
1089             return STF_INTERNAL_ERROR;
1090         }
1091     }
1092 #endif
1093
1094     /* VID out */
1095     if (!out_vendorid(ISAKMP_NEXT_KE, &rbody, VID_MISC_DPD))
1096         return STF_INTERNAL_ERROR;
1097
1098     /* KE out */
1099     if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group,
1100                            &rbody, ISAKMP_NEXT_NONCE))
1101         return STF_INTERNAL_ERROR;
1102
1103     /* Ni out */
1104     if (!build_and_ship_nonce(&st->st_ni, &rbody, ISAKMP_NEXT_ID, "Ni"))
1105         return STF_INTERNAL_ERROR;
1106
1107     /* IDii out */
1108     {
1109         struct isakmp_ipsec_id id_hd;
1110         chunk_t id_b;
1111         pb_stream id_pbs;
1112
1113         build_id_payload(&id_hd, &id_b, &st->st_connection->this);
1114         id_hd.isaiid_np = ISAKMP_NEXT_NONE;
1115         if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &rbody, &id_pbs)
1116         || !out_chunk(id_b, &id_pbs, "my identity"))
1117             return STF_INTERNAL_ERROR;
1118         close_output_pbs(&id_pbs);
1119     }
1120
1121     /* finish message */
1122
1123     close_message(&rbody);
1124     close_output_pbs(&reply);
1125
1126     clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply),
1127                  "reply packet from aggr_outI1");
1128
1129     /* Transmit */
1130
1131     DBG_cond_dump(DBG_RAW, "sending:\n",
1132                   st->st_tpacket.ptr, st->st_tpacket.len);
1133
1134     send_packet(st, "aggr_outI1");
1135
1136     /* Set up a retransmission event, half a minute henceforth */
1137     delete_event(st);
1138     event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
1139     
1140     if (predecessor != NULL)
1141     {
1142         update_pending(predecessor, st);
1143         whack_log(RC_NEW_STATE + STATE_AGGR_I1
1144             , "%s: initiate, replacing #%lu"
1145             , enum_name(&state_names, st->st_state)
1146             , predecessor->st_serialno);
1147     }
1148     else
1149     {
1150         whack_log(RC_NEW_STATE + STATE_AGGR_I1,
1151                   "%s: initiate", enum_name(&state_names, st->st_state));
1152     }
1153     reset_cur_state();
1154     return STF_OK;
1155 }
1156
1157
1158 void
1159 ipsecdoi_initiate(int whack_sock
1160 , struct connection *c
1161 , lset_t policy
1162 , unsigned long try
1163 , so_serial_t replacing)
1164 {
1165     /* If there's already an ISAKMP SA established, use that and
1166      * go directly to Quick Mode.
1167      * Note: there is no way to initiate with a Road Warrior.
1168      */
1169     struct state *st = find_phase1_state(c, FALSE);
1170
1171     DBG(DBG_CONTROL, DBG_log("ipsecdoi_initiate 1"));
1172     if (st == NULL)
1173     {
1174         initiator_function *initiator = (LALLIN(c->policy, POLICY_AGGRESSIVE)
1175                                          ? aggr_outI1 : main_outI1);
1176         DBG(DBG_CONTROL, DBG_log("ipsecdoi_initiate 2"));
1177         (void) initiator(whack_sock, c, NULL, policy, try);
1178     }
1179     else if (HAS_IPSEC_POLICY(policy))
1180     {
1181         DBG(DBG_CONTROL, DBG_log("ipsecdoi_initiate 3"));
1182         if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1183         {
1184             /* leave our Phase 2 negotiation pending */
1185             add_pending(whack_sock, st, c, policy, try, replacing);
1186         }
1187         else
1188         {
1189             DBG(DBG_CONTROL, DBG_log("ipsecdoi_initiate 4"));
1190             /* ??? we assume that peer_nexthop_sin isn't important:
1191              * we already have it from when we negotiated the ISAKMP SA!
1192              * It isn't clear what to do with the error return.
1193              */
1194             (void) quick_outI1(whack_sock, st, c, policy, try, replacing);
1195         }
1196     }
1197     else
1198     {
1199         close_any(whack_sock);
1200     }
1201 }
1202
1203 /* Replace SA with a fresh one that is similar
1204  *
1205  * Shares some logic with ipsecdoi_initiate, but not the same!
1206  * - we must not reuse the ISAKMP SA if we are trying to replace it!
1207  * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1208  *   ISAKMP SA if needed.
1209  * - duplicate whack fd, if live.
1210  * Does not delete the old state -- someone else will do that.
1211  */
1212 void
1213 ipsecdoi_replace(struct state *st, unsigned long try)
1214 {
1215     int whack_sock = dup_any(st->st_whack_sock);
1216     lset_t policy = st->st_policy;
1217     struct connection *c = st->st_connection;
1218
1219     if (IS_PHASE1(st->st_state))
1220     {
1221         initiator_function *initiator;
1222         passert(!HAS_IPSEC_POLICY(policy));
1223         initiator = (LALLIN(c->policy, POLICY_AGGRESSIVE)
1224                                          ? aggr_outI1 : main_outI1);
1225         (void) initiator(whack_sock, c, st, policy, try);
1226     }
1227     else
1228     {
1229         /* Add features of actual old state to policy.  This ensures
1230          * that rekeying doesn't downgrade security.  I admit that
1231          * this doesn't capture everything.
1232          */
1233         if (st->st_pfs_group != NULL)
1234             policy |= POLICY_PFS;
1235         if (st->st_ah.present)
1236         {
1237             policy |= POLICY_AUTHENTICATE;
1238             if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1239                 policy |= POLICY_TUNNEL;
1240         }
1241         if (st->st_esp.present && st->st_esp.attrs.transid != ESP_NULL)
1242         {
1243             policy |= POLICY_ENCRYPT;
1244             if (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1245                 policy |= POLICY_TUNNEL;
1246         }
1247         if (st->st_ipcomp.present)
1248         {
1249             policy |= POLICY_COMPRESS;
1250             if (st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1251                 policy |= POLICY_TUNNEL;
1252         }
1253         passert(HAS_IPSEC_POLICY(policy));
1254         ipsecdoi_initiate(whack_sock, st->st_connection, policy, try
1255             , st->st_serialno);
1256     }
1257 }
1258
1259 /* SKEYID for preshared keys.
1260  * See draft-ietf-ipsec-ike-01.txt 4.1
1261  */
1262 static bool
1263 skeyid_preshared(struct state *st)
1264 {
1265     const chunk_t *pss = get_preshared_secret(st->st_connection);
1266
1267     if (pss == NULL)
1268     {
1269         loglog(RC_LOG_SERIOUS, "preshared secret disappeared!");
1270         return FALSE;
1271     }
1272     else
1273     {
1274         struct hmac_ctx ctx;
1275
1276         hmac_init_chunk(&ctx, st->st_oakley.hasher, *pss);
1277         hmac_update_chunk(&ctx, st->st_ni);
1278         hmac_update_chunk(&ctx, st->st_nr);
1279         hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_preshared()", &ctx);
1280         return TRUE;
1281     }
1282 }
1283
1284 static bool
1285 skeyid_digisig(struct state *st)
1286 {
1287     struct hmac_ctx ctx;
1288     chunk_t nir;
1289
1290     /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1291      * so we have to build a temporary concatentation.
1292      */
1293     nir.len = st->st_ni.len + st->st_nr.len;
1294     nir.ptr = alloc_bytes(nir.len, "Ni + Nr in skeyid_digisig");
1295     memcpy(nir.ptr, st->st_ni.ptr, st->st_ni.len);
1296     memcpy(nir.ptr+st->st_ni.len, st->st_nr.ptr, st->st_nr.len);
1297     hmac_init_chunk(&ctx, st->st_oakley.hasher, nir);
1298     pfree(nir.ptr);
1299
1300     hmac_update_chunk(&ctx, st->st_shared);
1301     hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_digisig()", &ctx);
1302     return TRUE;
1303 }
1304
1305 /* Generate the SKEYID_* and new IV
1306  * See draft-ietf-ipsec-ike-01.txt 4.1
1307  */
1308 static bool
1309 generate_skeyids_iv(struct state *st)
1310 {
1311     /* Generate the SKEYID */
1312     switch (st->st_oakley.auth)
1313     {
1314         case OAKLEY_PRESHARED_KEY:
1315             if (!skeyid_preshared(st))
1316                 return FALSE;
1317             break;
1318
1319         case OAKLEY_RSA_SIG:
1320             if (!skeyid_digisig(st))
1321                 return FALSE;
1322             break;
1323
1324         case OAKLEY_DSS_SIG:
1325             /* XXX */
1326
1327         case OAKLEY_RSA_ENC:
1328         case OAKLEY_RSA_ENC_REV:
1329         case OAKLEY_ELGAMAL_ENC:
1330         case OAKLEY_ELGAMAL_ENC_REV:
1331             /* XXX */
1332
1333         default:
1334             exit_log("generate_skeyids_iv(): unsupported authentication method %s",
1335                 enum_show(&oakley_auth_names, st->st_oakley.auth));
1336     }
1337
1338     /* generate SKEYID_* from SKEYID */
1339     {
1340         struct hmac_ctx ctx;
1341
1342         hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1343
1344         /* SKEYID_D */
1345         hmac_update_chunk(&ctx, st->st_shared);
1346         hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1347         hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1348         hmac_update(&ctx, "\0", 1);
1349         hmac_final_chunk(st->st_skeyid_d, "st_skeyid_d in generate_skeyids_iv()", &ctx);
1350
1351         /* SKEYID_A */
1352         hmac_reinit(&ctx);
1353         hmac_update_chunk(&ctx, st->st_skeyid_d);
1354         hmac_update_chunk(&ctx, st->st_shared);
1355         hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1356         hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1357         hmac_update(&ctx, "\1", 1);
1358         hmac_final_chunk(st->st_skeyid_a, "st_skeyid_a in generate_skeyids_iv()", &ctx);
1359
1360         /* SKEYID_E */
1361         hmac_reinit(&ctx);
1362         hmac_update_chunk(&ctx, st->st_skeyid_a);
1363         hmac_update_chunk(&ctx, st->st_shared);
1364         hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1365         hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1366         hmac_update(&ctx, "\2", 1);
1367         hmac_final_chunk(st->st_skeyid_e, "st_skeyid_e in generate_skeyids_iv()", &ctx);
1368     }
1369
1370     /* generate IV */
1371     {
1372         union hash_ctx hash_ctx;
1373         const struct hash_desc *h = st->st_oakley.hasher;
1374
1375         st->st_new_iv_len = h->hash_digest_size;
1376         passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1377
1378         DBG(DBG_CRYPT,
1379             DBG_dump_chunk("DH_i:", st->st_gi);
1380             DBG_dump_chunk("DH_r:", st->st_gr);
1381         );
1382         h->hash_init(&hash_ctx);
1383         h->hash_update(&hash_ctx, st->st_gi.ptr, st->st_gi.len);
1384         h->hash_update(&hash_ctx, st->st_gr.ptr, st->st_gr.len);
1385         h->hash_final(st->st_new_iv, &hash_ctx);
1386     }
1387
1388     /* Oakley Keying Material
1389      * Derived from Skeyid_e: if it is not big enough, generate more
1390      * using the PRF.
1391      * See draft-ietf-ipsec-isakmp-oakley-07.txt Appendix B
1392      */
1393     {
1394         /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1395         const size_t keysize = st->st_oakley.enckeylen/BITS_PER_BYTE;
1396         u_char keytemp[MAX_OAKLEY_KEY_LEN + MAX_DIGEST_LEN];
1397         u_char *k = st->st_skeyid_e.ptr;
1398
1399         if (keysize > st->st_skeyid_e.len)
1400         {
1401             struct hmac_ctx ctx;
1402             size_t i = 0;
1403
1404             hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_e);
1405             hmac_update(&ctx, "\0", 1);
1406             for (;;)
1407             {
1408                 hmac_final(&keytemp[i], &ctx);
1409                 i += ctx.hmac_digest_size;
1410                 if (i >= keysize)
1411                     break;
1412                 hmac_reinit(&ctx);
1413                 hmac_update(&ctx, &keytemp[i - ctx.hmac_digest_size], ctx.hmac_digest_size);
1414             }
1415             k = keytemp;
1416         }
1417         clonereplacechunk(st->st_enc_key, k, keysize, "st_enc_key");
1418     }
1419
1420     DBG(DBG_CRYPT,
1421         DBG_dump_chunk("Skeyid:  ", st->st_skeyid);
1422         DBG_dump_chunk("Skeyid_d:", st->st_skeyid_d);
1423         DBG_dump_chunk("Skeyid_a:", st->st_skeyid_a);
1424         DBG_dump_chunk("Skeyid_e:", st->st_skeyid_e);
1425         DBG_dump_chunk("enc key:", st->st_enc_key);
1426         DBG_dump("IV:", st->st_new_iv, st->st_new_iv_len));
1427     return TRUE;
1428 }
1429
1430 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1431  * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1432  * New Group Mode, or ISAKMP Informational Exchanges).
1433  * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1434  * If hashus argument is TRUE, we're generating a hash for our end.
1435  * See RFC2409 IKE 5.
1436  *
1437  * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1438  * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1439  * The extensive common logic is embodied in main_mode_hash_body().
1440  * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1441  */
1442
1443 static void
1444 main_mode_hash_body(struct state *st
1445 , bool hashi    /* Initiator? */
1446 , const pb_stream *idpl /* ID payload, as PBS */
1447 , union hash_ctx *ctx
1448 , void (*hash_update)(union hash_ctx *, const u_char *input, unsigned int len))
1449 {
1450 #if 0   /* if desperate to debug hashing */
1451 #   define hash_update(ctx, input, len) { \
1452         DBG_cond_dump(DBG_CRYPT, "hash input", input, len); \
1453         (hash_update)(ctx, input, len); \
1454         }
1455 #endif
1456
1457 #   define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1458
1459     if (hashi)
1460     {
1461         hash_update_chunk(ctx, st->st_gi);
1462         hash_update_chunk(ctx, st->st_gr);
1463         hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1464         hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1465     }
1466     else
1467     {
1468         hash_update_chunk(ctx, st->st_gr);
1469         hash_update_chunk(ctx, st->st_gi);
1470         hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1471         hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1472     }
1473
1474     DBG(DBG_CRYPT, DBG_log("hashing %d bytes of SA"
1475         , st->st_p1isa.len - sizeof(struct isakmp_generic)));
1476
1477     /* SA_b */
1478     hash_update(ctx, st->st_p1isa.ptr + sizeof(struct isakmp_generic)
1479         , st->st_p1isa.len - sizeof(struct isakmp_generic));
1480
1481     /* Hash identification payload, without generic payload header.
1482      * We used to reconstruct ID Payload for this purpose, but now
1483      * we use the bytes as they appear on the wire to avoid
1484      * "spelling problems".
1485      */
1486     hash_update(ctx
1487         , idpl->start + sizeof(struct isakmp_generic)
1488         , pbs_offset(idpl) - sizeof(struct isakmp_generic));
1489
1490 #   undef hash_update_chunk
1491 #   undef hash_update
1492 }
1493
1494 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1495  * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1496  * New Group Mode, or ISAKMP Informational Exchanges).
1497  * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1498  * If hashus argument is TRUE, we're generating a hash for our end.
1499  * See RFC2409 IKE 5.
1500  *
1501  * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1502  * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1503  * The extensive common logic is embodied in main_mode_hash_body().
1504  * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1505  */
1506
1507 static void
1508 aggr_mode_hash_body(struct state *st, bool hashi, bool hashus
1509 , union hash_ctx *ctx
1510 , void (*hash_update)(union hash_ctx *, const u_char *input, unsigned int len))
1511 {
1512 #if 0   /* if desperate to debug hashing */
1513 #   define hash_update(ctx, input, len) { \
1514         DBG_cond_dump(DBG_CRYPT, "hash input", input, len); \
1515         (hash_update)(ctx, input, len); \
1516         }
1517 #endif
1518
1519 #   define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1520     if (hashi)
1521     {
1522         hash_update_chunk(ctx, st->st_gi);
1523         hash_update_chunk(ctx, st->st_gr);
1524         hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1525         hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1526     }
1527     else
1528     {
1529         hash_update_chunk(ctx, st->st_gr);
1530         hash_update_chunk(ctx, st->st_gi);
1531         hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1532         hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1533     }
1534
1535     DBG(DBG_CRYPT, DBG_log("hashing %d bytes of SA"
1536         , st->st_p1isa.len - sizeof(struct isakmp_generic)));
1537
1538     /* SA_b */
1539     hash_update(ctx, st->st_p1isa.ptr + sizeof(struct isakmp_generic)
1540         , st->st_p1isa.len - sizeof(struct isakmp_generic));
1541
1542     /* IDio_b (o stands for originator: i or r) */
1543     {
1544         /* Hash identification payload, without generic payload header.
1545          * Note: the part of header and body used must be in network order!
1546          */
1547         struct connection *c = st->st_connection;
1548         struct isakmp_ipsec_id id_hd;
1549         chunk_t id_b;
1550
1551         build_id_payload(&id_hd, &id_b, hashus? &c->this : &c->that);
1552         if (!hashus)
1553         {
1554             /* ugly feature *we* don't use */
1555             id_hd.isaiid_protoid = st->st_peeridentity_protocol;
1556             id_hd.isaiid_port = htons(st->st_peeridentity_port);
1557         }
1558         DBG(DBG_CRYPT,
1559             DBG_log("Hashing %s ID: Type %s, Protocol %d, Port %d"
1560                 , hashus? "my" : "his"
1561                 , enum_show(&ident_names, id_hd.isaiid_idtype)
1562                 , id_hd.isaiid_protoid, htons(id_hd.isaiid_port)));
1563         DBG(DBG_CRYPT,
1564             DBG_dump("ID to be hashed:"
1565                 , (u_char *)&id_hd + sizeof(struct isakmp_generic)
1566                 , sizeof(id_hd) - sizeof(struct isakmp_generic)));
1567         
1568         /* NOTE: hash does NOT include the generic payload part of
1569          * Identity Payload
1570          */
1571         hash_update(ctx
1572             , (u_char *)&id_hd + sizeof(struct isakmp_generic)
1573             , sizeof(id_hd) - sizeof(struct isakmp_generic));
1574
1575         DBG(DBG_CRYPT,
1576             DBG_dump_chunk("ID to be hashed:", id_b));
1577         
1578         hash_update_chunk(ctx, id_b);
1579     }
1580 #   undef hash_update_chunk
1581 #   undef hash_update
1582 }
1583
1584 static size_t   /* length of hash */
1585 main_mode_hash(struct state *st
1586 , u_char *hash_val      /* resulting bytes */
1587 , bool hashi    /* Initiator? */
1588 , const pb_stream *idpl)        /* ID payload, as PBS; cur must be at end */
1589 {
1590     struct hmac_ctx ctx;
1591
1592     hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1593     main_mode_hash_body(st, hashi, idpl, &ctx.hash_ctx, ctx.h->hash_update);
1594     hmac_final(hash_val, &ctx);
1595     return ctx.hmac_digest_size;
1596 }
1597
1598 static size_t
1599 aggr_mode_hash(struct state *st, u_char *hash_val
1600 , bool hashi, bool hashus)
1601 {
1602     struct hmac_ctx ctx;
1603
1604     hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1605     aggr_mode_hash_body(st, hashi, hashus, &ctx.hash_ctx, ctx.h->hash_update);
1606     hmac_final(hash_val, &ctx);
1607     return ctx.hmac_digest_size;
1608 }
1609
1610 #if 0   /* only needed for DSS */
1611 static void
1612 main_mode_sha1(struct state *st
1613 , u_char *hash_val      /* resulting bytes */
1614 , size_t *hash_len      /* length of hash */
1615 , bool hashi    /* Initiator? */
1616 , const pb_stream *idpl)        /* ID payload, as PBS */
1617 {
1618     union hash_ctx ctx;
1619
1620     SHA1Init(&ctx.ctx_sha1);
1621     SHA1Update(&ctx.ctx_sha1, st->st_skeyid.ptr, st->st_skeyid.len);
1622     *hash_len = SHA1_DIGEST_SIZE;
1623     main_mode_hash_body(st, hashi, idpl, &ctx
1624         , (void (*)(union hash_ctx *, const u_char *, unsigned int))&SHA1Update);
1625     SHA1Final(hash_val, &ctx.ctx_sha1);
1626 }
1627 #endif
1628
1629 /* Create an RSA signature of a hash.
1630  * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1631  * Use PKCS#1 version 1.5 encryption of hash (called
1632  * RSAES-PKCS1-V1_5) in PKCS#2.
1633  */
1634 static size_t
1635 RSA_sign_hash(struct connection *c
1636 , u_char sig_val[RSA_MAX_OCTETS]
1637 , const u_char *hash_val, size_t hash_len)
1638 {
1639     const struct RSA_private_key *k = get_RSA_private_key(c);
1640     size_t sz;
1641     u_char *p = sig_val;
1642     size_t padlen;
1643     mpz_t t1, t2;
1644     chunk_t ch;
1645
1646     if (k == NULL)
1647         return 0;       /* failure: no key to use */
1648     sz = k->pub.k;
1649     passert(RSA_MIN_OCTETS <= sz && 4 + hash_len < sz && sz <= RSA_MAX_OCTETS);
1650
1651     DBG(DBG_CONTROL | DBG_CRYPT
1652         , DBG_log("signing hash with RSA Key *%s", k->pub.keyid));
1653
1654     /* PKCS#1 v1.5 8.1 encryption-block formatting */
1655     *p++ = 0x00;
1656     *p++ = 0x01;        /* BT (block type) 01 */
1657     padlen = sz - 3 - hash_len;
1658     memset(p, 0xFF, padlen);
1659     p += padlen;
1660     *p++ = 0x00;
1661     memcpy(p, hash_val, hash_len);
1662     passert(p + hash_len - sig_val == (ptrdiff_t)sz);
1663
1664     /* PKCS#1 v1.5 8.2 octet-string-to-integer conversion */
1665     n_to_mpz(t1, sig_val, sz);  /* (could skip leading 0x00) */
1666
1667     /* PKCS#1 v1.5 8.3 RSA computation y = x^c mod n
1668      * Better described in PKCS#1 v2.0 5.1 RSADP.
1669      * There are two methods, depending on the form of the private key.
1670      * We use the one based on the Chinese Remainder Theorem.
1671      */
1672     mpz_init(t2);
1673
1674     mpz_powm(t2, t1, &k->dP, &k->p);    /* m1 = c^dP mod p */
1675
1676     mpz_powm(t1, t1, &k->dQ, &k->q);    /* m2 = c^dQ mod Q */
1677
1678     mpz_sub(t2, t2, t1);        /* h = qInv (m1 - m2) mod p */
1679     mpz_mod(t2, t2, &k->p);
1680     mpz_mul(t2, t2, &k->qInv);
1681     mpz_mod(t2, t2, &k->p);
1682
1683     mpz_mul(t2, t2, &k->q);     /* m = m2 + h q */
1684     mpz_add(t1, t1, t2);
1685
1686     /* PKCS#1 v1.5 8.4 integer-to-octet-string conversion */
1687     ch = mpz_to_n(t1, sz);
1688     memcpy(sig_val, ch.ptr, sz);
1689     pfree(ch.ptr);
1690
1691     mpz_clear(t1);
1692     mpz_clear(t2);
1693     return sz;
1694 }
1695
1696 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1697  *
1698  * As a side effect, on success, the public key is copied into the
1699  * state object to record the authenticator.
1700  *
1701  * Can fail because wrong public key is used or because hash disagrees.
1702  * We distinguish because diagnostics should also.
1703  *
1704  * The result is NULL if the Signature checked out.
1705  * Otherwise, the first character of the result indicates
1706  * how far along failure occurred.  A greater character signifies
1707  * greater progress.
1708  *
1709  * Classes:
1710  * 0    reserved for caller
1711  * 1    SIG length doesn't match key length -- wrong key
1712  * 2-8  malformed ECB after decryption -- probably wrong key
1713  * 9    decrypted hash != computed hash -- probably correct key
1714  *
1715  * Although the math should be the same for generating and checking signatures,
1716  * it is not: the knowledge of the private key allows more efficient (i.e.
1717  * different) computation for encryption.
1718  */
1719 static err_t
1720 try_RSA_signature(const u_char hash_val[MAX_DIGEST_LEN], size_t hash_len
1721 , const pb_stream *sig_pbs, const struct RSA_public_key *k
1722 , struct state *st)
1723 {
1724     const u_char *sig_val = sig_pbs->cur;
1725     size_t sig_len = pbs_left(sig_pbs);
1726     u_char s[RSA_MAX_OCTETS];   /* for decrypted sig_val */
1727     u_char *hash_in_s = &s[sig_len - hash_len];
1728
1729     /* decrypt the signature -- reversing RSA_sign_hash */
1730     if (sig_len != k->k)
1731     {
1732         /* XXX notification: INVALID_KEY_INFORMATION */
1733         return "1" "SIG length does not match public key length";
1734     }
1735
1736     /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1737     {
1738         chunk_t temp_s;
1739         mpz_t c;
1740
1741         n_to_mpz(c, sig_val, sig_len);
1742         mpz_powm(c, c, &k->e, &k->n);
1743
1744         temp_s = mpz_to_n(c, sig_len);  /* back to octets */
1745         memcpy(s, temp_s.ptr, sig_len);
1746         pfree(temp_s.ptr);
1747         mpz_clear(c);
1748     }
1749
1750     /* sanity check on signature: see if it matches
1751      * PKCS#1 v1.5 8.1 encryption-block formatting
1752      */
1753     {
1754         err_t ugh = NULL;
1755
1756         if (s[0] != 0x00)
1757             ugh = "2" "no leading 00";
1758         else if (hash_in_s[-1] != 0x00)
1759             ugh = "3" "00 separator not present";
1760         else if (s[1] == 0x01)
1761         {
1762             const u_char *p;
1763
1764             for (p = &s[2]; p != hash_in_s - 1; p++)
1765             {
1766                 if (*p != 0xFF)
1767                 {
1768                     ugh = "4" "invalid Padding String";
1769                     break;
1770                 }
1771             }
1772         }
1773         else if (s[1] == 0x02)
1774         {
1775             const u_char *p;
1776
1777             for (p = &s[2]; p != hash_in_s - 1; p++)
1778             {
1779                 if (*p == 0x00)
1780                 {
1781                     ugh = "5" "invalid Padding String";
1782                     break;
1783                 }
1784             }
1785         }
1786         else
1787             ugh = "6" "Block Type not 01 or 02";
1788
1789         if (ugh != NULL)
1790         {
1791             /* note: it might be a good idea to make sure that
1792              * an observer cannot tell what kind of failure happened.
1793              * I don't know what this means in practice.
1794              */
1795             /* We probably selected the wrong public key for peer:
1796              * SIG Payload decrypted into malformed ECB
1797              */
1798             /* XXX notification: INVALID_KEY_INFORMATION */
1799             return ugh;
1800         }
1801     }
1802
1803     /* We have the decoded hash: see if it matches. */
1804     if (memcmp(hash_val, hash_in_s, hash_len) != 0)
1805     {
1806         /* good: header, hash, signature, and other payloads well-formed
1807          * good: we could find an RSA Sig key for the peer.
1808          * bad: hash doesn't match
1809          * Guess: sides disagree about key to be used.
1810          */
1811         DBG_cond_dump(DBG_CRYPT, "decrypted SIG", s, sig_len);
1812         DBG_cond_dump(DBG_CRYPT, "computed HASH", hash_val, hash_len);
1813         /* XXX notification: INVALID_HASH_INFORMATION */
1814         return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1815     }
1816
1817     /* Success: copy successful key into state.
1818      * There might be an old one if we previously aborted this
1819      * state transition.
1820      */
1821     free_public_keys(&st->st_peer_pubkey);
1822     st->st_peer_pubkey = public_key_from_rsa(k);
1823
1824     return NULL;    /* happy happy */
1825 }
1826
1827 /* Check signature against all RSA public keys we can find.
1828  * If we need keys from DNS KEY records, and they haven't been fetched,
1829  * return STF_SUSPEND to ask for asynch DNS lookup.
1830  *
1831  * take_a_crack is a helper function.  Mostly forensic.
1832  * If only we had coroutines.
1833  */
1834 struct tac_state {
1835     /* RSA_check_signature's args that take_a_crack needs */
1836     struct state *st;
1837     const u_char *hash_val;
1838     size_t hash_len;
1839     const pb_stream *sig_pbs;
1840
1841     /* state carried between calls */
1842     err_t best_ugh;     /* most successful failure */
1843     int tried_cnt;      /* number of keys tried */
1844     char tried[50];     /* keyids of tried public keys */
1845     char *tn;   /* roof of tried[] */
1846 };
1847
1848 static bool
1849 take_a_crack(struct tac_state *s
1850 , const struct RSA_public_key *k
1851 , const char *story)
1852 {
1853     err_t ugh = try_RSA_signature(s->hash_val, s->hash_len, s->sig_pbs
1854         , k, s->st);
1855
1856     s->tried_cnt++;
1857     if (ugh == NULL)
1858     {
1859         DBG(DBG_CRYPT | DBG_CONTROL
1860             , DBG_log("an RSA Sig check passed with *%s [%s]"
1861                 , k->keyid, story));
1862         return TRUE;
1863     }
1864     else
1865     {
1866         DBG(DBG_CRYPT
1867             , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1868                 , ugh + 1, k->keyid, story));
1869         if (s->best_ugh == NULL || s->best_ugh[0] < ugh[0])
1870             s->best_ugh = ugh;
1871         if (ugh[0] > '0'
1872         && s->tn - s->tried + KEYID_BUF + 2 < (ptrdiff_t)sizeof(s->tried))
1873         {
1874             strcpy(s->tn, " *");
1875             strcpy(s->tn + 2, k->keyid);
1876             s->tn += strlen(s->tn);
1877         }
1878         return FALSE;
1879     }
1880 }
1881
1882 static stf_status
1883 RSA_check_signature(struct state *st
1884 , const u_char hash_val[MAX_DIGEST_LEN]
1885 , size_t hash_len
1886 , const pb_stream *sig_pbs)
1887 {
1888     const struct connection *c = st->st_connection;
1889     struct tac_state s;
1890     err_t dns_ugh = NULL;
1891
1892     s.st = st;
1893     s.hash_val = hash_val;
1894     s.hash_len = hash_len;
1895     s.sig_pbs = sig_pbs;
1896
1897     s.best_ugh = NULL;
1898     s.tried_cnt = 0;
1899     s.tn = s.tried;
1900
1901     /* try all gateway records hung off c */
1902     if ((c->policy & POLICY_OPPO))
1903     {
1904         struct gw_info *gw;
1905
1906         for (gw = c->gw_info; gw != NULL; gw = gw->next)
1907         {
1908             /* only consider entries that have a key and are for our peer */
1909             if (gw->gw_key_present
1910             && same_id(&gw->gw_id, &c->that.id)
1911             && take_a_crack(&s, &gw->gw_key, "key saved from DNS TXT"))
1912                 return STF_OK;
1913         }
1914     }
1915
1916     /* try all appropriate Public keys */
1917     {
1918         struct pubkeyrec *p, **pp;
1919
1920         pp = &pubkeys;
1921
1922         for (p = pubkeys; p != NULL; p = *pp)
1923         {
1924             if (p->alg == PUBKEY_ALG_RSA && same_id(&c->that.id, &p->id))
1925             {
1926                 time_t now;
1927
1928                 /* check if found public key has expired */
1929                 time(&now);
1930                 if (p->until != UNDEFINED_TIME && p->until < now)
1931                 {
1932                     loglog(RC_LOG_SERIOUS,
1933                         "cached RSA public key has expired and has been deleted");
1934                     *pp = free_public_key(p);
1935                     continue; /* continue with next public key */
1936                 }
1937
1938                 if (take_a_crack(&s, &p->u.rsa, "preloaded key"))
1939                 return STF_OK;
1940             }
1941             pp = &p->next;
1942         }
1943     }
1944
1945     /* if no key was found (evidenced by best_ugh == NULL)
1946      * and this connection is opportunistic,
1947      * then go search DNS for keys for peer.
1948      */
1949     if (s.best_ugh == NULL && (c->policy & POLICY_OPPO))
1950     {
1951         struct pubkeyrec *kr;
1952
1953         if (keys_from_dns == NULL)
1954             return STF_SUSPEND; /* ask for asynch DNS lookup */
1955
1956         for (kr = keys_from_dns; kr != NULL; kr = kr->next)
1957         {
1958             if (kr->alg == PUBKEY_ALG_RSA)
1959             {
1960                 if (take_a_crack(&s, &kr->u.rsa, "key from DNS KEY"))
1961                 {
1962                     free_public_keys(&keys_from_dns);
1963                     return STF_OK;
1964                 }
1965             }
1966         }
1967
1968         free_public_keys(&keys_from_dns);
1969     }
1970
1971     /* no acceptable key was found: diagnose */
1972     {
1973         char id_buf[IDTOA_BUF]; /* arbitrary limit on length of ID reported */
1974
1975         (void) idtoa(&st->st_connection->that.id, id_buf, sizeof(id_buf));
1976
1977         if (s.best_ugh == NULL)
1978         {
1979             if (dns_ugh == NULL)
1980                 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1981                     , id_buf);
1982             else
1983                 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1984                     "; DNS search for KEY failed (%s)"
1985                     , id_buf, dns_ugh);
1986
1987             /* ??? is this the best code there is? */
1988             return STF_FAIL + INVALID_KEY_INFORMATION;
1989         }
1990
1991         if (s.best_ugh[0] == '9')
1992         {
1993             loglog(RC_LOG_SERIOUS, "%s", s.best_ugh + 1);
1994             return STF_FAIL + INVALID_HASH_INFORMATION;
1995         }
1996         else
1997         {
1998             if (s.tried_cnt == 1)
1999             {
2000                 loglog(RC_LOG_SERIOUS
2001                     , "Signature check (on %s) failed (wrong key?); tried%s"
2002                     , id_buf, s.tried);
2003                 DBG(DBG_CONTROL,
2004                     DBG_log("public key for %s failed:"
2005                         " decrypted SIG payload into a malformed ECB (%s)"
2006                         , id_buf, s.best_ugh + 1));
2007             }
2008             else
2009             {
2010                 loglog(RC_LOG_SERIOUS
2011                     , "Signature check (on %s) failed:"
2012                       " tried%s keys but none worked."
2013                     , id_buf, s.tried);
2014                 DBG(DBG_CONTROL,
2015                     DBG_log("all %d public keys for %s failed:"
2016                         " best decrypted SIG payload into a malformed ECB (%s)"
2017                         , s.tried_cnt, id_buf, s.best_ugh + 1));
2018             }
2019             return STF_FAIL + INVALID_KEY_INFORMATION;
2020         }
2021     }
2022 }
2023
2024 /* CHECK_QUICK_HASH
2025  *
2026  * This macro is magic -- it cannot be expressed as a function.
2027  * - it causes the caller to return!
2028  * - it declares local variables and expects the "do_hash" argument
2029  *   expression to reference them (hash_val, hash_pbs)
2030  */
2031 #define CHECK_QUICK_HASH(md, do_hash, hash_name, msg_name) { \
2032         pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs; \
2033         u_char hash_val[MAX_DIGEST_LEN]; \
2034         size_t hash_len = do_hash; \
2035         if (pbs_left(hash_pbs) != hash_len \
2036         || memcmp(hash_pbs->cur, hash_val, hash_len) != 0) \
2037         { \
2038             DBG_cond_dump(DBG_CRYPT, "received " hash_name ":", hash_pbs->cur, pbs_left(hash_pbs)); \
2039             loglog(RC_LOG_SERIOUS, "received " hash_name " does not match computed value in " msg_name); \
2040             return STF_FAIL + INVALID_HASH_INFORMATION; \
2041         } \
2042     }
2043
2044 static notification_t
2045 accept_nonce(struct msg_digest *md, chunk_t *dest, const char *name)
2046 {
2047     pb_stream *nonce_pbs = &md->chain[ISAKMP_NEXT_NONCE]->pbs;
2048     size_t len = pbs_left(nonce_pbs);
2049
2050     if (len < MINIMUM_NONCE_SIZE || MAXIMUM_NONCE_SIZE < len)
2051     {
2052         loglog(RC_LOG_SERIOUS, "%s length not between %d and %d"
2053             , name , MINIMUM_NONCE_SIZE, MAXIMUM_NONCE_SIZE);
2054         return PAYLOAD_MALFORMED;       /* ??? */
2055     }
2056     clonereplacechunk(*dest, nonce_pbs->cur, len, "nonce");
2057     return NOTHING_WRONG;
2058 }
2059
2060 /* START_HASH_PAYLOAD
2061  *
2062  * Emit a to-be-filled-in hash payload, noting the field start (r_hashval)
2063  * and the start of the part of the message to be hashed (r_hash_start).
2064  * This macro is magic.
2065  * - it can cause the caller to return
2066  * - it references variables local to the caller (r_hashval, r_hash_start, st)
2067  */
2068 #define START_HASH_PAYLOAD(rbody, np) { \
2069     pb_stream hash_pbs; \
2070     if (!out_generic(np, &isakmp_hash_desc, &(rbody), &hash_pbs)) \
2071         return STF_INTERNAL_ERROR; \
2072     r_hashval = hash_pbs.cur;   /* remember where to plant value */ \
2073     if (!out_zero(st->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH")) \
2074         return STF_INTERNAL_ERROR; \
2075     close_output_pbs(&hash_pbs); \
2076     r_hash_start = (rbody).cur; /* hash from after HASH payload */ \
2077 }
2078
2079 /* encrypt message, sans fixed part of header
2080  * IV is fetched from st->st_new_iv and stored into st->st_iv.
2081  * The theory is that there will be no "backing out", so we commit to IV.
2082  * We also close the pbs.
2083  */
2084 static bool
2085 encrypt_message(pb_stream *pbs, struct state *st)
2086 {
2087     const struct encrypt_desc *e = st->st_oakley.encrypter;
2088     u_int8_t *enc_start = pbs->start + sizeof(struct isakmp_hdr);
2089     size_t enc_len = pbs_offset(pbs) - sizeof(struct isakmp_hdr);
2090
2091     DBG_cond_dump(DBG_CRYPT | DBG_RAW, "encrypting:\n", enc_start, enc_len);
2092
2093     /* Pad up to multiple of encryption blocksize.
2094      * See the description associated with the definition of
2095      * struct isakmp_hdr in packet.h.
2096      */
2097     {
2098         size_t padding = pad_up(enc_len, e->enc_blocksize);
2099
2100         if (padding != 0)
2101         {
2102             if (!out_zero(padding, pbs, "encryption padding"))
2103                 return FALSE;
2104             enc_len += padding;
2105         }
2106     }
2107
2108     DBG(DBG_CRYPT, DBG_log("encrypting using %s", enum_show(&oakley_enc_names, st->st_oakley.encrypt)));
2109     /* e->crypt(TRUE, enc_start, enc_len, st); */
2110     crypto_cbc_encrypt(e, TRUE, enc_start, enc_len, st);
2111
2112     update_iv(st);
2113     DBG_cond_dump(DBG_CRYPT, "next IV:", st->st_iv, st->st_iv_len);
2114     close_message(pbs);
2115     return TRUE;
2116 }
2117
2118 /* Compute HASH(1), HASH(2) of Quick Mode.
2119  * HASH(1) is part of Quick I1 message.
2120  * HASH(2) is part of Quick R1 message.
2121  * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
2122  * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
2123  */
2124 static size_t
2125 quick_mode_hash12(u_char *dest, const u_char *start, const u_char *roof
2126 , const struct state *st, const msgid_t *msgid, bool hash2)
2127 {
2128     struct hmac_ctx ctx;
2129
2130 #if 0   /* if desperate to debug hashing */
2131 #   define hmac_update(ctx, ptr, len) { \
2132         DBG_dump("hash input", (ptr), (len)); \
2133         (hmac_update)((ctx), (ptr), (len)); \
2134     }
2135     DBG_dump("hash key", st->st_skeyid_a.ptr, st->st_skeyid_a.len);
2136 #endif
2137     hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
2138     hmac_update(&ctx, (const void *) msgid, sizeof(msgid_t));
2139     if (hash2)
2140         hmac_update_chunk(&ctx, st->st_ni);     /* include Ni_b in the hash */
2141     hmac_update(&ctx, start, roof-start);
2142     hmac_final(dest, &ctx);
2143
2144     DBG(DBG_CRYPT,
2145         DBG_log("HASH(%d) computed:", hash2 + 1);
2146         DBG_dump("", dest, ctx.hmac_digest_size));
2147     return ctx.hmac_digest_size;
2148 #   undef hmac_update
2149 }
2150
2151 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
2152  * Used by: quick_inR1_outI2, quick_inI2
2153  * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
2154  * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
2155  * Message ID and Nonces.  This is a mistake.
2156  */
2157 static size_t
2158 quick_mode_hash3(u_char *dest, struct state *st)
2159 {
2160     struct hmac_ctx ctx;
2161
2162     hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
2163     hmac_update(&ctx, "\0", 1);
2164     hmac_update(&ctx, (u_char *) &st->st_msgid, sizeof(st->st_msgid));
2165     hmac_update_chunk(&ctx, st->st_ni);
2166     hmac_update_chunk(&ctx, st->st_nr);
2167     hmac_final(dest, &ctx);
2168     DBG_cond_dump(DBG_CRYPT, "HASH(3) computed:", dest, ctx.hmac_digest_size);
2169     return ctx.hmac_digest_size;
2170 }
2171
2172 /* Compute Phase 2 IV.
2173  * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
2174  */
2175 void
2176 init_phase2_iv(struct state *st, const msgid_t *msgid)
2177 {
2178     const struct hash_desc *h = st->st_oakley.hasher;
2179     union hash_ctx ctx;
2180
2181     DBG_cond_dump(DBG_CRYPT, "last Phase 1 IV:"
2182         , st->st_iv, st->st_iv_len);
2183
2184     st->st_new_iv_len = h->hash_digest_size;
2185     passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
2186
2187     h->hash_init(&ctx);
2188     h->hash_update(&ctx, st->st_iv, st->st_iv_len);
2189     passert(*msgid != 0);
2190     h->hash_update(&ctx, (const u_char *)msgid, sizeof(*msgid));
2191     h->hash_final(st->st_new_iv, &ctx);
2192
2193     DBG_cond_dump(DBG_CRYPT, "computed Phase 2 IV:"
2194         , st->st_new_iv, st->st_new_iv_len);
2195 }
2196
2197 /* Initiate quick mode.
2198  * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
2199  * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
2200  * Note: this is not called from demux.c
2201  */
2202
2203 static bool
2204 emit_subnet_id(ip_subnet *net
2205 , u_int8_t np, u_int8_t protoid, u_int16_t port, pb_stream *outs)
2206 {
2207     struct isakmp_ipsec_id id;
2208     pb_stream id_pbs;
2209     ip_address ta;
2210     const unsigned char *tbp;
2211     size_t tal;
2212
2213     id.isaiid_np = np;
2214     id.isaiid_idtype = aftoinfo(subnettypeof(net))->id_subnet;
2215     id.isaiid_protoid = protoid;
2216     id.isaiid_port = port;
2217
2218     if (!out_struct(&id, &isakmp_ipsec_identification_desc, outs, &id_pbs))
2219         return FALSE;
2220
2221     networkof(net, &ta);
2222     tal = addrbytesptr(&ta, &tbp);
2223     if (!out_raw(tbp, tal, &id_pbs, "client network"))
2224         return FALSE;
2225
2226     maskof(net, &ta);
2227     tal = addrbytesptr(&ta, &tbp);
2228     if (!out_raw(tbp, tal, &id_pbs, "client mask"))
2229         return FALSE;
2230
2231     close_output_pbs(&id_pbs);
2232     return TRUE;
2233 }
2234
2235 stf_status
2236 quick_outI1(int whack_sock
2237 , struct state *isakmp_sa
2238 , struct connection *c
2239 , lset_t policy
2240 , unsigned long try
2241 , so_serial_t replacing)
2242 {
2243     struct state *st = duplicate_state(isakmp_sa);
2244     pb_stream reply;    /* not really a reply */
2245     pb_stream rbody;
2246     u_char      /* set by START_HASH_PAYLOAD: */
2247         *r_hashval,     /* where in reply to jam hash value */
2248         *r_hash_start;  /* start of what is to be hashed */
2249     bool has_client = c->this.has_client ||  c->that.has_client;
2250
2251     st->st_whack_sock = whack_sock;
2252     st->st_connection = c;
2253     set_cur_state(st);  /* we must reset before exit */
2254     st->st_policy = policy;
2255     st->st_try = try;
2256
2257     st->st_myuserprotoid = st->st_peeruserprotoid = 0;
2258     st->st_myuserport = st->st_peeruserport = 0;
2259
2260     st->st_msgid = generate_msgid(isakmp_sa);
2261     st->st_state = STATE_QUICK_I1;
2262
2263     if (c->dnshostname != NULL)
2264     {
2265         ip_address new_addr;
2266
2267         if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
2268         && !sameaddr(&new_addr, &c->that.host_addr))
2269         {
2270             c->that.host_addr = new_addr;
2271             state_rehash(c);
2272             load_preshared_secrets();
2273         }
2274     }
2275
2276     insert_state(st);   /* needs cookies, connection, and msgid */
2277
2278     if (replacing == SOS_NOBODY)
2279         log("initiating Quick Mode %s"
2280             , bitnamesof(sa_policy_bit_names, policy));
2281     else
2282         log("initiating Quick Mode %s to replace #%lu"
2283             , bitnamesof(sa_policy_bit_names, policy), replacing);
2284
2285 #ifdef NAT_TRAVERSAL
2286     if (isakmp_sa->nat_traversal & NAT_T_DETECTED) {
2287         /* Duplicate nat_traversal status in new state */
2288         st->nat_traversal = isakmp_sa->nat_traversal;
2289         if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)) {
2290             has_client = TRUE;
2291         }
2292         nat_traversal_change_port_lookup(NULL, st);
2293     }
2294     else {
2295         st->nat_traversal = 0;
2296     }
2297 #endif
2298
2299     /* set up reply */
2300     init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
2301
2302     /* HDR* out */
2303     {
2304         struct isakmp_hdr hdr;
2305
2306         hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
2307         hdr.isa_np = ISAKMP_NEXT_HASH;
2308         hdr.isa_xchg = ISAKMP_XCHG_QUICK;
2309         hdr.isa_msgid = st->st_msgid;
2310         hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
2311         memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
2312         memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
2313         if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
2314         {
2315             reset_cur_state();
2316             return STF_INTERNAL_ERROR;
2317         }
2318     }
2319
2320     /* HASH(1) -- create and note space to be filled later */
2321     START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
2322
2323     /* SA out */
2324
2325     /* If PFS specified, use the same group as during Phase 1:
2326      * since no negotiation is possible, we pick one that is
2327      * very likely supported.
2328      */
2329     if (st->st_connection->alg_info_esp && st->st_connection->alg_info_esp->esp_pfsgroup)
2330             st->st_pfs_group = lookup_group(st->st_connection->alg_info_esp->esp_pfsgroup);
2331     if (!st->st_pfs_group)
2332             st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
2333
2334     /* Emit SA payload based on a subset of the policy bits.
2335      * POLICY_COMPRESS is considered iff we can do IPcomp.
2336      */
2337     {
2338         lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
2339
2340         if (can_do_IPcomp)
2341             pm |= POLICY_COMPRESS;
2342
2343         if (!out_sa(&rbody
2344         , &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT]
2345         , st, FALSE, ISAKMP_NEXT_NONCE))
2346         {
2347             reset_cur_state();
2348             return STF_INTERNAL_ERROR;
2349         }
2350     }
2351
2352     /* Ni out */
2353     if (!build_and_ship_nonce(&st->st_ni, &rbody
2354     , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : ISAKMP_NEXT_NONE
2355     , "Ni"))
2356     {
2357         reset_cur_state();
2358         return STF_INTERNAL_ERROR;
2359     }
2360
2361     /* [ KE ] out (for PFS) */
2362
2363     if (st->st_pfs_group != NULL)
2364     {
2365         if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2366         , &rbody, has_client? ISAKMP_NEXT_ID : ISAKMP_NEXT_NONE))
2367         {
2368             reset_cur_state();
2369             return STF_INTERNAL_ERROR;
2370         }
2371     }
2372
2373     /* [ IDci, IDcr ] out */
2374     if (has_client)
2375     {
2376         /* IDci (we are initiator), then IDcr (peer is responder) */
2377         if (!emit_subnet_id(&c->this.client
2378           , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2379         || !emit_subnet_id(&c->that.client
2380           , ISAKMP_NEXT_NONE, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2381         {
2382             reset_cur_state();
2383             return STF_INTERNAL_ERROR;
2384         }
2385     }
2386
2387 #ifdef NAT_TRAVERSAL
2388     if ((st->nat_traversal & NAT_T_WITH_NATOA) &&
2389         (!(st->st_policy & POLICY_TUNNEL)) &&
2390         (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))) {
2391         /** Send NAT-OA if our address is NATed */
2392         if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st)) {
2393         reset_cur_state();
2394             return STF_INTERNAL_ERROR;
2395         }
2396     }
2397 #endif
2398
2399     /* finish computing  HASH(1), inserting it in output */
2400     (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2401         , st, &st->st_msgid, FALSE);
2402
2403     /* encrypt message, except for fixed part of header */
2404
2405     init_phase2_iv(isakmp_sa, &st->st_msgid);
2406     st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2407     memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2408
2409     if (!encrypt_message(&rbody, st))
2410     {
2411         reset_cur_state();
2412         return STF_INTERNAL_ERROR;
2413     }
2414
2415     /* save packet, now that we know its size */
2416     clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
2417         , "reply packet from quick_outI1");
2418
2419     /* send the packet */
2420
2421     send_packet(st, "quick_outI1");
2422
2423     delete_event(st);
2424     event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2425
2426     if (replacing == SOS_NOBODY)
2427         whack_log(RC_NEW_STATE + STATE_QUICK_I1
2428             , "%s: initiate"
2429             , enum_name(&state_names, st->st_state));
2430     else
2431         whack_log(RC_NEW_STATE + STATE_QUICK_I1
2432             , "%s: initiate to replace #%lu"
2433             , enum_name(&state_names, st->st_state)
2434             , replacing);
2435     reset_cur_state();
2436     return STF_OK;
2437 }
2438
2439
2440 /*
2441  * Decode the CERT payload of Phase 1.
2442  */
2443 static void
2444 decode_cert(struct msg_digest *md)
2445 {
2446     struct payload_digest *p;
2447
2448     for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2449     {
2450         struct isakmp_cert *const cert = &p->payload.cert;
2451         chunk_t blob;
2452         blob.ptr = p->pbs.cur;
2453         blob.len = pbs_left(&p->pbs);
2454         if (cert->isacert_type == CERT_X509_SIGNATURE)
2455         {
2456             x509cert_t cert = empty_x509cert;
2457             if (parse_x509cert(blob, 0, &cert))
2458             {
2459                 if (verify_x509cert(&cert))
2460                 {
2461                     DBG(DBG_PARSING,
2462                         DBG_log("Public key validated")
2463                     )
2464                     add_x509_public_key(&cert, DAL_SIGNED);
2465                 }
2466                 else
2467                 {
2468                     log("X.509 certificate rejected");
2469                 }
2470                 free_generalNames(cert.subjectAltName);
2471                 free_generalNames(cert.crlDistributionPoints);
2472             }
2473             else
2474                 log("Error in X.509 certificate");
2475         }
2476         else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2477         {
2478             x509cert_t *cert = NULL;
2479
2480             if (parse_pkcs7_cert(blob, &cert))
2481                 store_x509certs(&cert);
2482             else
2483                 log("Error in PKCS#7 wrapped X.509 certificates");
2484         }
2485         else
2486         {
2487             loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2488                    enum_show(&cert_type_names, cert->isacert_type));
2489             DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2490         }
2491     }
2492 }
2493
2494
2495 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2496  * Note: we may change connections as a result.
2497  * We must be called before SIG or HASH are decoded since we
2498  * may change the peer's RSA key or ID.
2499  */
2500 static bool
2501 decode_peer_id(struct msg_digest *md, bool initiator, bool aggrmode)
2502 {
2503     struct state *const st = md->st;
2504     struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2505     pb_stream *const id_pbs = &id_pld->pbs;
2506     struct isakmp_id *const id = &id_pld->payload.id;
2507     struct id peer;
2508
2509     /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2510      * It talks about the protocol ID and Port fields of the ID
2511      * Payload, but they don't exist as such in Phase 1.
2512      * We use more appropriate names.
2513      * isaid_doi_specific_a is in place of Protocol ID.
2514      * isaid_doi_specific_b is in place of Port.
2515      * Besides, there is no good reason for allowing these to be
2516      * other than 0 in Phase 1.
2517      */
2518 #ifdef NAT_TRAVERSAL
2519     if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING) &&
2520         (id->isaid_doi_specific_a == IPPROTO_UDP) &&
2521         ((id->isaid_doi_specific_b == 0) || (id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))) {
2522             DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2523                 "accepted with port_floating NAT-T",
2524                 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2525     }
2526     else
2527 #endif
2528     if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2529     && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2530     {
2531         loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2532             " but are %d/%d"
2533             , IPPROTO_UDP, IKE_UDP_PORT
2534             , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2535         return FALSE;
2536     }
2537
2538     /* XXX Check for valid ID types? */
2539     peer.kind = id->isaid_idtype;
2540
2541     switch (peer.kind)
2542     {
2543     case ID_IPV4_ADDR:
2544     case ID_IPV6_ADDR:
2545         /* failure mode for initaddr is probably inappropriate address length */
2546         {
2547             err_t ugh = initaddr(id_pbs->cur, pbs_left(id_pbs)
2548                 , peer.kind == ID_IPV4_ADDR? AF_INET : AF_INET6
2549                 , &peer.ip_addr);
2550
2551             if (ugh != NULL)
2552             {
2553                 loglog(RC_LOG_SERIOUS, "improper %s identification payload: %s"
2554                     , enum_show(&ident_names, peer.kind), ugh);
2555                 return FALSE;
2556             }
2557         }
2558         break;
2559
2560     case ID_USER_FQDN:
2561 #ifndef INTEROP_CHECKPOINT_FW_4_1
2562         if (memchr(id_pbs->cur, '@', pbs_left(id_pbs)) == NULL)
2563         {
2564             loglog(RC_LOG_SERIOUS, "peer's ID_USER_FQDN contains no @");
2565             return FALSE;
2566         }
2567 #endif
2568         /* FALLTHROUGH */
2569     case ID_FQDN:
2570         if (memchr(id_pbs->cur, '\0', pbs_left(id_pbs)) != NULL)
2571         {
2572             loglog(RC_LOG_SERIOUS, "Phase 1 ID Payload of type %s contains a NUL"
2573                 , enum_show(&ident_names, peer.kind));
2574             return FALSE;
2575         }
2576
2577         /* ??? ought to do some more sanity check, but what? */
2578
2579         setchunk(peer.name, id_pbs->cur, pbs_left(id_pbs));
2580         break;
2581     
2582     case ID_KEY_ID:
2583         setchunk(peer.name, id_pbs->cur, pbs_left(id_pbs));
2584         DBG(DBG_PARSING,
2585             DBG_dump_chunk("KEY ID:", peer.name));
2586         break;  
2587
2588     case ID_DER_ASN1_DN:
2589         setchunk(peer.name, id_pbs->cur, pbs_left(id_pbs));
2590         DBG(DBG_PARSING,
2591             DBG_dump_chunk("DER ASN1 DN:", peer.name));
2592         break;  
2593                 
2594     default:
2595         loglog(RC_LOG_SERIOUS, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2596             " from %s"
2597             , enum_show(&ident_names, peer.kind)
2598             , inet_ntoa(md->sin.sin_addr));
2599         return FALSE;
2600     }
2601
2602     /* crazy stuff, must be kept for hash */
2603     st->st_peeridentity_protocol = id->isaid_doi_specific_a;
2604     st->st_peeridentity_port = id->isaid_doi_specific_b;
2605
2606     DBG(DBG_PARSING,
2607         {
2608             char buf[IDTOA_BUF];
2609
2610             idtoa(&peer, buf, sizeof(buf));
2611             DBG_log("%s Mode peer's ID is %s: '%s'",
2612                 aggrmode ? "Aggressive" : "Main",
2613                 enum_show(&ident_names, id->isaid_idtype),
2614                 buf);
2615             log("Peer ID is %s: '%s'",
2616             enum_show(&ident_names, id->isaid_idtype), buf);
2617         });
2618         
2619      /* check for certificates */       
2620      decode_cert(md);
2621
2622     /* Now that we've decoded the ID payload, let's see if we
2623      * need to switch connections.
2624      * We must not switch horses if we initiated:
2625      * - if the initiation was explicit, we'd be ignoring user's intent
2626      * - if opportunistic, we'll lose our HOLD info
2627      */
2628     if (initiator)
2629     {
2630         if (!same_id(&st->st_connection->that.id, &peer))
2631         {
2632             char expect[IDTOA_BUF]
2633                 , found[IDTOA_BUF];
2634
2635             idtoa(&st->st_connection->that.id, expect, sizeof(expect));
2636             idtoa(&peer, found, sizeof(found));
2637             loglog(RC_LOG_SERIOUS
2638                 , "we require peer to have ID '%s', but peer declares '%s'"
2639                 , expect, found);
2640             return FALSE;
2641         }
2642     }
2643     else
2644     {
2645         struct connection *c = st->st_connection;
2646         struct connection *r = refine_host_connection(st, &peer, initiator, aggrmode);
2647
2648         if (r == NULL)
2649         {
2650             char buf[IDTOA_BUF];
2651
2652             idtoa(&peer, buf, sizeof(buf));
2653             loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%s'", buf);
2654             return FALSE;
2655         }
2656         else if (r != c)
2657         {
2658             /* apparently, r is an improvement on c -- replace */
2659
2660             log("switched from \"%s\" to \"%s\"", c->name, r->name);
2661             if (r->kind == CK_TEMPLATE)
2662             {
2663                 /* instantiate it, filling in peer's ID */
2664                 r = rw_instantiate(r, &c->that.host_addr,
2665 #ifdef NAT_TRAVERSAL
2666                         c->that.host_port,
2667 #endif
2668 #ifdef VIRTUAL_IP
2669                         NULL,
2670 #endif
2671                         &peer);
2672             }
2673
2674             st->st_connection = r;      /* kill reference to c */
2675             set_cur_connection(r);
2676             connection_discard(c);
2677         }
2678     }
2679     return TRUE;
2680 }
2681
2682 /* Decode the variable part of an ID packet (during Quick Mode).
2683  * This is designed for packets that identify clients, not peers.
2684  * Rejects 0.0.0.0/32 or IPv6 equivalent because
2685  * (1) it is wrong and (2) we use this value for inband signalling.
2686  */
2687 static bool
2688 decode_net_id(struct isakmp_ipsec_id *id
2689 , pb_stream *id_pbs
2690 , ip_subnet *net
2691 , const char *which)
2692 {
2693     const struct af_info *afi = NULL;
2694
2695     /* Note: the following may be a pointer into static memory
2696      * that may be recycled, but only if the type is not known.
2697      * That case is disposed of very early -- in the first switch.
2698      */
2699     const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2700
2701     switch (id->isaiid_idtype)
2702     {
2703         case ID_FQDN:
2704         {
2705            /* 818043 NAT-T/L2TP/IPsec for Windows 2000 and XP
2706             * sends an ID_FQDN in the quick mode exchange (name
2707             * of host computer)
2708             *
2709             * This leaves net uninitialised and quick mode will
2710             * fail with "no connection is known"
2711             */
2712             memset(net, 0, sizeof(ip_subnet));
2713             break;
2714         }
2715         case ID_IPV4_ADDR:
2716         case ID_IPV4_ADDR_SUBNET:
2717         case ID_IPV4_ADDR_RANGE:
2718             afi = &af_inet4_info;
2719             break;
2720         case ID_IPV6_ADDR:
2721         case ID_IPV6_ADDR_SUBNET:
2722         case ID_IPV6_ADDR_RANGE:
2723             afi = &af_inet6_info;
2724             break;
2725
2726         default:
2727             /* XXX support more */
2728             loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2729                 , idtypename);
2730             return FALSE;
2731     }
2732
2733     switch (id->isaiid_idtype)
2734     {
2735         case ID_IPV4_ADDR:
2736         case ID_IPV6_ADDR:
2737         {
2738             ip_address temp_address;
2739             err_t ugh;
2740
2741             ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2742
2743             if (ugh != NULL)
2744             {
2745                 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2746                     , which, idtypename, ugh);
2747                 return FALSE;
2748             }
2749             happy(initsubnet(&temp_address, afi->mask_cnt, '0', net));
2750             DBG(DBG_PARSING | DBG_CONTROL,
2751                 {
2752                     char temp_buff[SUBNETTOT_BUF];
2753
2754                     subnettot(net, 0, temp_buff, sizeof(temp_buff));
2755                     DBG_log("%s is %s", which, temp_buff);
2756                 });
2757             break;
2758         }
2759
2760         case ID_IPV4_ADDR_SUBNET:
2761         case ID_IPV6_ADDR_SUBNET:
2762         {
2763             ip_address temp_address, temp_mask;
2764             err_t ugh;
2765
2766             if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2767             {
2768                 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2769                     , which, idtypename);
2770                 return FALSE;
2771             }
2772             ugh = initaddr(id_pbs->cur
2773                 , afi->ia_sz, afi->af, &temp_address);
2774             if (ugh == NULL)
2775                 ugh = initaddr(id_pbs->cur + afi->ia_sz
2776                     , afi->ia_sz, afi->af, &temp_mask);
2777             if (ugh == NULL)
2778                 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2779                     , '0', net);
2780             if (ugh != NULL)
2781             {
2782                 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2783                     , which, idtypename, ugh);
2784                 return FALSE;
2785             }
2786             DBG(DBG_PARSING | DBG_CONTROL,
2787                 {
2788                     char temp_buff[SUBNETTOT_BUF];
2789
2790                     subnettot(net, 0, temp_buff, sizeof(temp_buff));
2791                     DBG_log("%s is subnet %s", which, temp_buff);
2792                 });
2793             break;
2794         }
2795
2796         case ID_IPV4_ADDR_RANGE:
2797         case ID_IPV6_ADDR_RANGE:
2798         {
2799             ip_address temp_address_from, temp_address_to;
2800             err_t ugh;
2801
2802             if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2803             {
2804                 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2805                     , which, idtypename);
2806                 return FALSE;
2807             }
2808             ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2809             if (ugh == NULL)
2810                 ugh = initaddr(id_pbs->cur + afi->ia_sz
2811                     , afi->ia_sz, afi->af, &temp_address_to);
2812             if (ugh != NULL)
2813             {
2814                 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2815                     , which, idtypename, ugh);
2816                 return FALSE;
2817             }
2818
2819             ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2820             if (ugh != NULL)
2821             {
2822                 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2823
2824                 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2825                 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2826                 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2827                     " %s - %s unacceptable: %s"
2828                     , which, idtypename, temp_buff1, temp_buff2, ugh);
2829                 return FALSE;
2830             }
2831             DBG(DBG_PARSING | DBG_CONTROL,
2832                 {
2833                     char temp_buff[SUBNETTOT_BUF];
2834
2835                     subnettot(net, 0, temp_buff, sizeof(temp_buff));
2836                     DBG_log("%s is subnet %s (received as range)"
2837                         , which, temp_buff);
2838                 });
2839             break;
2840         }
2841     }
2842
2843     return TRUE;
2844 }
2845
2846 /* like decode, but checks that what is received matches what was sent */
2847 static bool
2848
2849 check_net_id(struct isakmp_ipsec_id *id
2850 , pb_stream *id_pbs
2851 , u_int8_t *protoid
2852 , u_int16_t *port
2853 , ip_subnet *net
2854 , const char *which)
2855 {
2856     ip_subnet net_temp;
2857
2858     if (!decode_net_id(id, id_pbs, &net_temp, which))
2859         return FALSE;
2860
2861     if (!samesubnet(net, &net_temp)
2862     || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2863     {
2864         loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2865         return FALSE;
2866     }
2867     return TRUE;
2868 }
2869
2870 /*
2871  * look for the existence of a non-expiring preloaded public key
2872  */
2873 static bool
2874 has_preloaded_public_key(struct state *st)
2875 {
2876     struct connection *c = st->st_connection;
2877
2878     /* do not consider rw connections since
2879      * the peer's identity must be known
2880      */
2881     if (c->kind == CK_PERMANENT)
2882     {
2883         struct pubkeyrec *p;
2884
2885         /* look for a matching RSA public key */
2886         for (p = pubkeys; p != NULL; p = p->next)
2887         {
2888             if (p->alg == PUBKEY_ALG_RSA &&
2889                 same_id(&c->that.id, &p->id) &&
2890                 p->until == UNDEFINED_TIME)
2891             {
2892                 /* found a preloaded public key */
2893                 return TRUE;
2894             }
2895         }
2896     }
2897     return FALSE;
2898 }
2899
2900 /*
2901  * Produce the new key material of Quick Mode.
2902  * draft-ietf-ipsec-isakmp-oakley-06.txt section 5.5
2903  * specifies how this is to be done.
2904  */
2905 static void
2906 compute_proto_keymat(struct state *st
2907 , u_int8_t protoid
2908 , struct ipsec_proto_info *pi)
2909 {
2910     size_t needed_len; /* bytes of keying material needed */
2911
2912     /* Add up the requirements for keying material
2913      * (It probably doesn't matter if we produce too much!)
2914      */
2915     switch (protoid)
2916     {
2917     case PROTO_IPSEC_ESP:
2918             switch (pi->attrs.transid)
2919             {
2920             case ESP_NULL:
2921                 needed_len = 0;
2922                 break;
2923             case ESP_DES:
2924                 needed_len = DES_CBC_BLOCK_SIZE;
2925                 break;
2926             case ESP_3DES:
2927                 needed_len = DES_CBC_BLOCK_SIZE * 3;
2928                 break;
2929             default:
2930 #ifndef NO_KERNEL_ALG
2931                 if((needed_len=kernel_alg_esp_enc_keylen(pi->attrs.transid))>0) {
2932                         /* XXX: check key_len "coupling with kernel.c's */
2933                         if (pi->attrs.key_len) {
2934                                 needed_len=pi->attrs.key_len/8;
2935                                 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2936                                                 "key_len=%d from peer",
2937                                                 needed_len));
2938                         }
2939                         break;
2940                 }
2941 #endif
2942                 exit_log("transform %s not implemented yet",
2943                     enum_show(&esp_transformid_names, pi->attrs.transid));
2944             }
2945 #ifndef NO_KERNEL_ALG
2946             DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2947                                     "needed_len (after ESP enc)=%d",
2948                                     needed_len));
2949             if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL)) {
2950                 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2951             } else
2952 #endif
2953             switch (pi->attrs.auth)
2954             {
2955             case AUTH_ALGORITHM_NONE:
2956                 break;
2957             case AUTH_ALGORITHM_HMAC_MD5:
2958                 needed_len += HMAC_MD5_KEY_LEN;
2959                 break;
2960             case AUTH_ALGORITHM_HMAC_SHA1:
2961                 needed_len += HMAC_SHA1_KEY_LEN;
2962                 break;
2963             case AUTH_ALGORITHM_DES_MAC:
2964             default:
2965                 exit_log("AUTH algorithm %s not implemented yet",
2966                     enum_show(&auth_alg_names, pi->attrs.auth));
2967             }
2968             DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2969                                     "needed_len (after ESP auth)=%d",
2970                                     needed_len));
2971             break;
2972
2973     case PROTO_IPSEC_AH:
2974             switch (pi->attrs.transid)
2975             {
2976             case AH_MD5:
2977                 needed_len = HMAC_MD5_KEY_LEN;
2978                 break;
2979             case AH_SHA:
2980                 needed_len = HMAC_SHA1_KEY_LEN;
2981                 break;
2982             default:
2983                 exit_log("transform %s not implemented yet",
2984                     enum_show(&ah_transformid_names, pi->attrs.transid));
2985             }
2986             break;
2987
2988     default:
2989         exit_log("protocol %s not implemented yet",
2990             enum_show(&protocol_names, protoid));
2991         break;
2992     }
2993
2994     pi->keymat_len = needed_len;
2995     /* Allocate space for the keying material.
2996      * Although only needed_len bytes are desired, we
2997      * must round up to a multiple of ctx.hmac_digest_size
2998      * so that our buffer isn't overrun.
2999      */
3000     {
3001         struct hmac_ctx ctx_me, ctx_peer;
3002         size_t needed_space;    /* space needed for keying material (rounded up) */
3003         size_t i;
3004
3005         hmac_init_chunk(&ctx_me, st->st_oakley.hasher, st->st_skeyid_d);
3006         ctx_peer = ctx_me;      /* duplicate initial conditions */
3007
3008         needed_space = needed_len + pad_up(needed_len, ctx_me.hmac_digest_size);
3009         replace(pi->our_keymat, alloc_bytes(needed_space, "keymat in compute_keymat()"));
3010         replace(pi->peer_keymat, alloc_bytes(needed_space, "peer_keymat in quick_inI1_outR1()"));
3011
3012         for (i = 0;; )
3013         {
3014             if (st->st_shared.ptr != NULL)
3015             {
3016                 /* PFS: include the g^xy */
3017                 hmac_update_chunk(&ctx_me, st->st_shared);
3018                 hmac_update_chunk(&ctx_peer, st->st_shared);
3019             }
3020             hmac_update(&ctx_me, &protoid, sizeof(protoid));
3021             hmac_update(&ctx_peer, &protoid, sizeof(protoid));
3022
3023             hmac_update(&ctx_me, (u_char *)&pi->our_spi, sizeof(pi->our_spi));
3024             hmac_update(&ctx_peer, (u_char *)&pi->attrs.spi, sizeof(pi->attrs.spi));
3025
3026             hmac_update_chunk(&ctx_me, st->st_ni);
3027             hmac_update_chunk(&ctx_peer, st->st_ni);
3028
3029             hmac_update_chunk(&ctx_me, st->st_nr);
3030             hmac_update_chunk(&ctx_peer, st->st_nr);
3031
3032             hmac_final(pi->our_keymat + i, &ctx_me);
3033             hmac_final(pi->peer_keymat + i, &ctx_peer);
3034
3035             i += ctx_me.hmac_digest_size;
3036             if (i >= needed_space)
3037                 break;
3038
3039             /* more keying material needed: prepare to go around again */
3040
3041             hmac_reinit(&ctx_me);
3042             hmac_reinit(&ctx_peer);
3043
3044             hmac_update(&ctx_me, pi->our_keymat + i - ctx_me.hmac_digest_size,
3045                 ctx_me.hmac_digest_size);
3046             hmac_update(&ctx_peer, pi->peer_keymat + i - ctx_peer.hmac_digest_size,
3047                 ctx_peer.hmac_digest_size);
3048         }
3049     }
3050
3051     DBG(DBG_CRYPT,
3052         DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
3053         DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
3054 }
3055
3056 static void
3057 compute_keymats(struct state *st)
3058 {
3059     if (st->st_ah.present)
3060         compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
3061     if (st->st_esp.present)
3062         compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
3063 }
3064
3065 /* State Transition Functions.
3066  *
3067  * The definition of state_microcode_table in demux.c is a good
3068  * overview of these routines.
3069  *
3070  * - Called from process_packet; result handled by complete_state_transition
3071  * - struct state_microcode member "processor" points to these
3072  * - these routine definitionss are in state order
3073  * - these routines must be restartable from any point of error return:
3074  *   beware of memory allocated before any error.
3075  * - output HDR is usually emitted by process_packet (if state_microcode
3076  *   member first_out_payload isn't ISAKMP_NEXT_NONE).
3077  *
3078  * The transition functions' functions include:
3079  * - process and judge payloads
3080  * - update st_iv (result of decryption is in st_new_iv)
3081  * - build reply packet
3082  */
3083
3084 /* Handle a Main Mode Oakley first packet (responder side).
3085  * HDR;SA --> HDR;SA
3086  */
3087 stf_status
3088 main_inI1_outR1(struct msg_digest *md)
3089 {
3090     struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
3091     struct state *st;
3092     struct connection *c = find_host_connection_mode(&md->iface->addr, pluto_port
3093         , &md->sender, md->sender_port, TRUE);
3094
3095     pb_stream r_sa_pbs;
3096
3097     DBG(DBG_CONTROL, DBG_log("main_inI1_outR1, destination: %s,"
3098         "portof(md->iface->addr): %d," "pluto_port: %d, "
3099                 "sender: %s," " md->sender_port: %d,", 
3100                 inet_ntoa(md->iface->addr.u.v4.sin_addr), ntohs(portof(&md->iface->addr)),
3101                 pluto_port, inet_ntoa(md->sender.u.v4.sin_addr), md->sender_port));
3102
3103     if (c == NULL)
3104     {
3105         /* see if a wildcarded connection can be found */
3106         c = find_host_connection_mode(&md->iface->addr, pluto_port
3107                 , (ip_address*)NULL, md->sender_port, TRUE);
3108
3109         if (c != NULL)
3110         {
3111             /* Create a temporary connection that is a copy of this one.
3112              * His ID isn't declared yet.
3113              */
3114             c = rw_instantiate(c, &md->sender,
3115 #ifdef NAT_TRAVERSAL
3116                         md->sender_port,
3117 #endif
3118 #ifdef VIRTUAL_IP
3119                         NULL,
3120 #endif
3121                         NULL);
3122         }
3123         else
3124         {
3125             loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3126                 " but no connection has been authorized"
3127                 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr)));
3128             /* XXX notification is in order! */
3129             return STF_IGNORE;
3130         }
3131     }
3132
3133     /* Set up state */
3134     md->st = st = new_state();
3135     st->st_connection = c;
3136     set_cur_state(st);  /* (caller will reset cur_state) */
3137     st->st_try = 0;     /* not our job to try again from start */
3138     st->st_policy = c->policy & ~POLICY_IPSEC_MASK;     /* only as accurate as connection */
3139
3140     memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
3141     get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
3142
3143     if (c->dnshostname != NULL)
3144     {
3145         ip_address new_addr;
3146
3147         if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
3148         && !sameaddr(&new_addr, &c->that.host_addr))
3149         {
3150             c->that.host_addr = new_addr;
3151             state_rehash(c);
3152             load_preshared_secrets();
3153         }
3154     }
3155
3156     insert_state(st);   /* needs cookies, connection, and msgid (0) */
3157
3158     st->st_doi = ISAKMP_DOI_IPSEC;
3159     st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
3160
3161     if ((c->kind == CK_INSTANCE) && (c->that.host_port != pluto_port))
3162     {
3163         log("responding to Main Mode from unknown peer %s:%u"
3164             , ip_str(&c->that.host_addr), c->that.host_port);
3165     }
3166     else if (c->kind == CK_INSTANCE)
3167     {
3168         log("responding to Main Mode from unknown peer %s"
3169             , ip_str(&c->that.host_addr));
3170     }
3171     else
3172     {
3173         log("responding to Main Mode");
3174     }
3175
3176     /* parse_isakmp_sa also spits out a winning SA into our reply,
3177      * so we have to build our md->reply and emit HDR before calling it.
3178      */
3179     
3180     /* HDR out.
3181      * We can't leave this to comm_handle() because we must
3182      * fill in the cookie.
3183      */
3184     {
3185         struct isakmp_hdr r_hdr = md->hdr;
3186
3187         r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3188         memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3189         r_hdr.isa_np = ISAKMP_NEXT_SA;
3190         if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3191             return STF_INTERNAL_ERROR;
3192     }
3193     DBG(DBG_CONTROL, DBG_log("main_inI1_outR1 -4"));
3194     /* start of SA out */
3195     {
3196         struct isakmp_sa r_sa = sa_pd->payload.sa;
3197
3198         /* if we  use an ID_KEY_ID as own ID, we assume a
3199          * PGPcert peer and have to send the Vendor ID
3200          *  ++++ not sure, if this is an interop problem ++++++
3201          */
3202 #if 0
3203         if (c->this.id.kind == ID_KEY_ID)
3204                 r_sa.isasa_np = ISAKMP_NEXT_VID;
3205         else
3206                 r_sa.isasa_np = ISAKMP_NEXT_NONE;
3207 #endif
3208
3209         r_sa.isasa_np = ISAKMP_NEXT_VID;
3210         if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3211             return STF_INTERNAL_ERROR;
3212     }
3213     /* SA body in and out */
3214     RETURN_STF_FAILURE(parse_isakmp_sa_body(&sa_pd->pbs, &sa_pd->payload.sa, &r_sa_pbs
3215             , FALSE, st));
3216
3217     if (c->this.id.kind == ID_KEY_ID)
3218     {
3219             if (!out_generic_raw(ISAKMP_NEXT_VID, &isakmp_vendor_id_desc, &md->rbody
3220             , pgp_vid, sizeof(pgp_vid)-1, "V_ID"))
3221                  return STF_INTERNAL_ERROR;
3222     }
3223
3224 #ifdef NAT_TRAVERSAL
3225     if (md->nat_traversal_vid && nat_traversal_enabled) {
3226         /* reply if NAT-Traversal draft is supported */
3227         st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3228         if ((st->nat_traversal) && (!out_vendorid(ISAKMP_NEXT_NONE,
3229             &md->rbody, md->nat_traversal_vid))) {
3230             return STF_INTERNAL_ERROR;
3231         }
3232     }
3233 #endif
3234
3235     /* VID out */
3236     if (!out_vendorid(ISAKMP_NEXT_NONE, &md->rbody, VID_MISC_DPD))
3237         return STF_INTERNAL_ERROR;
3238
3239     close_message(&md->rbody);
3240     
3241     /* save initiator SA for HASH */
3242     clonereplacechunk(st->st_p1isa, sa_pd->pbs.start, pbs_room(&sa_pd->pbs), "sa in main_inI1_outR1()");
3243
3244     return STF_OK;
3245 }
3246
3247 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3248  * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3249  *
3250  * The following are not yet implemented:
3251  * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3252  * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3253  *                <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3254  *
3255  * We must verify that the proposal received matches one we sent.
3256  */
3257 stf_status
3258 main_inR1_outI2(struct msg_digest *md)
3259 {
3260     struct state *const st = md->st;
3261
3262     /* verify echoed SA */
3263     {
3264         struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
3265         RETURN_STF_FAILURE(parse_isakmp_sa_body(&sapd->pbs
3266             , &sapd->payload.sa, NULL, TRUE, st));
3267     }
3268
3269 #ifdef NAT_TRAVERSAL
3270     if (nat_traversal_enabled && md->nat_traversal_vid) {
3271         st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3272     }
3273 #endif
3274
3275     /**************** build output packet HDR;KE;Ni ****************/
3276
3277     /* HDR out.
3278      * We can't leave this to comm_handle() because the isa_np
3279      * depends on the type of Auth (eventually).
3280      */
3281     echo_hdr(md, FALSE, ISAKMP_NEXT_KE);
3282
3283     /* KE out */
3284     if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group
3285     , &md->rbody, ISAKMP_NEXT_NONCE))
3286         return STF_INTERNAL_ERROR;
3287
3288 #ifdef IMPAIR_MTU_BUST_MI2      /* ship a really big VID payload in MI2 message */
3289     /* Ni out */
3290     if (!build_and_ship_nonce(&st->st_ni, &md->rbody, ISAKMP_NEXT_VID, "Ni"))
3291         return STF_INTERNAL_ERROR;
3292
3293     /* generate a pointless large VID payload to push message over MTU */
3294     {
3295         pb_stream vid_pbs;
3296
3297         if (!out_generic(ISAKMP_NEXT_NONE, &isakmp_vendor_id_desc, &md->rbody
3298             , &vid_pbs))
3299             return STF_INTERNAL_ERROR;
3300         if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3301             return STF_INTERNAL_ERROR;
3302         close_output_pbs(&vid_pbs);
3303     }
3304 #else
3305     /* Ni out */
3306     if (!build_and_ship_nonce(&st->st_ni, &md->rbody, ISAKMP_NEXT_NONE, "Ni"))
3307         return STF_INTERNAL_ERROR;
3308 #endif
3309
3310 #ifdef NAT_TRAVERSAL
3311     if (st->nat_traversal & NAT_T_WITH_NATD) {
3312         if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3313             return STF_INTERNAL_ERROR;
3314     }
3315 #endif
3316
3317     /* finish message */
3318     close_message(&md->rbody);
3319
3320     /* Reinsert the state, using the responder cookie we just received */
3321     unhash_state(st);
3322     memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
3323     insert_state(st);   /* needs cookies, connection, and msgid (0) */
3324
3325     return STF_OK;
3326 }
3327
3328 /* STATE_MAIN_R1:
3329  * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3330  *
3331  * The following are not yet implemented:
3332  * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3333  *          --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3334  * RPKE_AUTH:
3335  *          HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3336  *          --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3337  */
3338 stf_status
3339 main_inI2_outR2(struct msg_digest *md)
3340 {
3341     struct state *const st = md->st;
3342     pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3343  
3344     /* send CR if auth is RSA and no preloaded RSA public key exists*/
3345     bool send_cr = !no_cr_send && (st->st_oakley.auth == OAKLEY_RSA_SIG) &&
3346                    !has_preloaded_public_key(st);
3347
3348     /* KE in */
3349     RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
3350
3351     /* Ni in */
3352     RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
3353
3354 #ifdef NAT_TRAVERSAL
3355     if (st->nat_traversal & NAT_T_WITH_NATD) {
3356         nat_traversal_natd_lookup(md);
3357     }
3358     if (st->nat_traversal) {
3359         nat_traversal_show_result(st->nat_traversal, md->sender_port);
3360     }
3361     if (st->nat_traversal & NAT_T_WITH_KA) {
3362         nat_traversal_new_ka_event();
3363     }
3364 #endif
3365
3366     /**************** build output packet HDR;KE;Nr ****************/
3367
3368     /* HDR out done */
3369
3370     /* KE out */
3371     if (!build_and_ship_KE(st, &st->st_gr, st->st_oakley.group
3372     , &md->rbody, ISAKMP_NEXT_NONCE))
3373         return STF_INTERNAL_ERROR;
3374
3375 #ifdef IMPAIR_MTU_BUST_MR2      /* ship a really big VID payload in MR2 message */
3376     /* Nr out */
3377     if (!build_and_ship_nonce(&st->st_nr, &md->rbody, ISAKMP_NEXT_VID, "Nr"))
3378         return STF_INTERNAL_ERROR;
3379
3380     /* generate a pointless large VID payload to push message over MTU */
3381     {
3382         pb_stream vid_pbs;
3383
3384         if (!out_generic((send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_NONE,
3385             &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3386             return STF_INTERNAL_ERROR;
3387         if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3388             return STF_INTERNAL_ERROR;
3389         close_output_pbs(&vid_pbs);
3390     }
3391 #else
3392     /* Nr out */
3393     if (!build_and_ship_nonce(&st->st_nr, &md->rbody,
3394         (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_NONE, "Nr"))
3395         return STF_INTERNAL_ERROR;
3396 #endif
3397
3398     /* CR out */
3399     if (send_cr)
3400     {
3401         pb_stream cr_pbs;
3402
3403         struct isakmp_cr cr_hd;
3404         cr_hd.isacr_np = ISAKMP_NEXT_NONE;
3405         cr_hd.isacr_type = CERT_X509_SIGNATURE;
3406
3407         if (!out_struct(&cr_hd, &isakmp_ipsec_cert_req_desc, &md->rbody, &cr_pbs))
3408             return STF_INTERNAL_ERROR;
3409         close_output_pbs(&cr_pbs);
3410     }
3411
3412 #ifdef NAT_TRAVERSAL
3413     if (st->nat_traversal & NAT_T_WITH_NATD) {
3414         if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3415             return STF_INTERNAL_ERROR;
3416     }
3417 #endif
3418
3419     /* finish message */
3420     close_message(&md->rbody);
3421
3422     /* next message will be encrypted, but not this one.
3423      * We could defer this calculation.
3424      */
3425 #ifndef DODGE_DH_MISSING_ZERO_BUG
3426     compute_dh_shared(st, st->st_gi, st->st_oakley.group);
3427 #endif
3428     if (!generate_skeyids_iv(st))
3429         return STF_FAIL + AUTHENTICATION_FAILED;
3430     update_iv(st);
3431
3432     return STF_OK;
3433 }
3434
3435 /* STATE_MAIN_I2:
3436  * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3437  * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3438  *
3439  * The following are not yet implemented.
3440  * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3441  *          --> HDR*, HASH_I
3442  * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3443  *          --> HDR*, HASH_I
3444  */
3445 stf_status
3446 main_inR2_outI3(struct msg_digest *md)
3447 {
3448     struct state *const st = md->st;
3449     pb_stream *const keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3450     int auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
3451         ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
3452     pb_stream id_pbs;   /* ID Payload; also used for hash calculation */
3453     cert_t mycert;
3454
3455     /* send certificate if we have one and auth is RSA */
3456     bool send_cert = (st->st_oakley.auth == OAKLEY_RSA_SIG) &&
3457                      get_mycert(&mycert, st->st_connection->this.cert);
3458
3459     /* send certificate request, if we don't have a preloaded RSA public key */
3460     bool send_cr = !no_cr_send && send_cert && !has_preloaded_public_key(st);
3461
3462     /* KE in */
3463     RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
3464
3465     /* Nr in */
3466     RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
3467
3468     /* done parsing; initialize crypto  */
3469
3470     compute_dh_shared(st, st->st_gr, st->st_oakley.group);
3471 #ifdef DODGE_DH_MISSING_ZERO_BUG
3472     if (st->st_shared.ptr[0] == 0)
3473         return STF_REPLACE_DOOMED_EXCHANGE;
3474 #endif
3475     if (!generate_skeyids_iv(st))
3476         return STF_FAIL + AUTHENTICATION_FAILED;
3477
3478 #ifdef NAT_TRAVERSAL
3479     if (st->nat_traversal & NAT_T_WITH_NATD) {
3480         nat_traversal_natd_lookup(md);
3481     }
3482     if (st->nat_traversal) {
3483         nat_traversal_show_result(st->nat_traversal, md->sender_port);
3484     }
3485     if (st->nat_traversal & NAT_T_WITH_KA) {
3486         nat_traversal_new_ka_event();
3487     }
3488 #endif
3489
3490     /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3491     /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3492
3493     /* HDR* out done */
3494
3495     /* IDii out */
3496     {
3497         struct isakmp_ipsec_id id_hd;
3498         chunk_t id_b;
3499
3500         build_id_payload(&id_hd, &id_b, &st->st_connection->this);
3501         id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3502         if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &id_pbs)
3503         || !out_chunk(id_b, &id_pbs, "my identity"))
3504             return STF_INTERNAL_ERROR;
3505         close_output_pbs(&id_pbs);
3506     }
3507
3508     /* CERT out */
3509     if (send_cert)
3510     {
3511         pb_stream cert_pbs;
3512
3513         struct isakmp_cert cert_hd;
3514         cert_hd.isacert_np = (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_SIG;
3515         cert_hd.isacert_type = mycert.type;
3516
3517         if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3518             return STF_INTERNAL_ERROR;
3519         if (!out_chunk(mycert.cert, &cert_pbs, "CERT"))
3520             return STF_INTERNAL_ERROR;
3521         close_output_pbs(&cert_pbs);
3522     }
3523
3524     /* CR out */
3525     if (send_cr)
3526     {
3527         pb_stream cr_pbs;
3528
3529         struct isakmp_cr cr_hd;
3530         cr_hd.isacr_np = ISAKMP_NEXT_SIG;
3531         cr_hd.isacr_type = mycert.type;
3532
3533         if (!out_struct(&cr_hd, &isakmp_ipsec_cert_req_desc, &md->rbody, &cr_pbs))
3534             return STF_INTERNAL_ERROR;
3535         close_output_pbs(&cr_pbs);
3536     }
3537
3538     /* HASH_I or SIG_I out */
3539     {
3540         u_char hash_val[MAX_DIGEST_LEN];
3541         size_t hash_len = main_mode_hash(st, hash_val, TRUE, &id_pbs);
3542
3543         if (auth_payload == ISAKMP_NEXT_HASH)
3544         {
3545             /* HASH_I out */
3546             if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
3547             , hash_val, hash_len, "HASH_I"))
3548                 return STF_INTERNAL_ERROR;
3549         }
3550         else
3551         {
3552             /* SIG_I out */
3553             u_char sig_val[RSA_MAX_OCTETS];
3554             size_t sig_len = RSA_sign_hash(st->st_connection
3555                 , sig_val, hash_val, hash_len);
3556
3557             if (sig_len == 0)
3558             {
3559                 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
3560                 return STF_FAIL + AUTHENTICATION_FAILED;
3561             }
3562
3563             if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3564             , &md->rbody, sig_val, sig_len, "SIG_I"))
3565                 return STF_INTERNAL_ERROR;
3566         }
3567     }
3568
3569     /* encrypt message, except for fixed part of header */
3570
3571     /* st_new_iv was computed by generate_skeyids_iv */
3572     if (!encrypt_message(&md->rbody, st))
3573         return STF_INTERNAL_ERROR;      /* ??? we may be partly committed */
3574
3575     return STF_OK;
3576 }
3577
3578 /* Shared logic for asynchronous lookup of DNS KEY records.
3579  * Used for STATE_MAIN_R2 and STATE_MAIN_I3.
3580  */
3581
3582 struct key_continuation {
3583     struct adns_continuation ac;        /* common prefix */
3584     struct msg_digest *md;
3585 };
3586
3587 static void
3588 report_key_dns_failure(struct id *id, err_t ugh)
3589 {
3590     char id_buf[IDTOA_BUF];     /* arbitrary limit on length of ID reported */
3591
3592     (void) idtoa(id, id_buf, sizeof(id_buf));
3593     loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
3594         "; DNS search for KEY failed (%s)", id_buf, ugh);
3595 }
3596
3597 /* Processs the Main Mode ID Payload and the Authenticator
3598  * (Hash or Signature Payload).
3599  * If a KEY lookup is needed, it is initiated and STF_SUSPEND is returned.
3600  */
3601 static stf_status
3602 main_id_and_auth(struct msg_digest *md
3603 , bool initiator        /* are we the Initiator? */
3604 , bool aggrmode
3605 , cont_fn_t cont_fn)    /* continuation function */
3606 {
3607     struct state *st = md->st;
3608     u_char hash_val[MAX_DIGEST_LEN];
3609     size_t hash_len;
3610     stf_status r = STF_OK;
3611
3612     /* ID Payload in.
3613      * Note: this may switch the connection being used!
3614      */
3615     if (!aggrmode && !decode_peer_id(md, initiator, FALSE))
3616         return STF_FAIL + INVALID_ID_INFORMATION;
3617
3618     /* Hash the ID Payload.
3619      * main_mode_hash requires idpl->cur to be at end of payload
3620      * so we temporarily set if so.
3621      */
3622     if (aggrmode) 
3623            hash_len = aggr_mode_hash(st, hash_val, !initiator, FALSE); 
3624     else    
3625     {
3626         pb_stream *idpl = &md->chain[ISAKMP_NEXT_ID]->pbs;
3627         u_int8_t *old_cur = idpl->cur;
3628
3629         idpl->cur = idpl->roof;
3630         hash_len = main_mode_hash(st, hash_val, !initiator, idpl);
3631         idpl->cur = old_cur;
3632     }
3633
3634     switch (st->st_oakley.auth)
3635     {
3636     case OAKLEY_PRESHARED_KEY:
3637         {
3638             pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs;
3639
3640             if (pbs_left(hash_pbs) != hash_len
3641             || memcmp(hash_pbs->cur, hash_val, hash_len) != 0)
3642             {
3643                 DBG_cond_dump(DBG_CRYPT, "received HASH:"
3644                     , hash_pbs->cur, pbs_left(hash_pbs));
3645                 loglog(RC_LOG_SERIOUS, "received Hash Payload does not match computed value");
3646                 r = STF_FAIL + INVALID_HASH_INFORMATION;
3647             }
3648         }
3649         break;
3650
3651     case OAKLEY_RSA_SIG:
3652         r = RSA_check_signature(st, hash_val, hash_len
3653             , &md->chain[ISAKMP_NEXT_SIG]->pbs);
3654
3655         if (r == STF_SUSPEND)
3656         {
3657             /* initiate asynchronous DNS lookup for KEY record(s) */
3658             struct key_continuation *kc
3659                 = alloc_thing(struct key_continuation, "key continuation");
3660             err_t ugh;
3661
3662             /* Record that state is used by a suspended md */
3663             passert(st->st_suspended_md == NULL);
3664             kc->md = st->st_suspended_md = md;
3665
3666             ugh = start_adns_query(&st->st_connection->that.id
3667                 , NULL  /* no sgw for KEY */
3668                 , T_KEY
3669                 , cont_fn
3670                 , &kc->ac);
3671
3672             if (ugh != NULL)
3673             {
3674                 report_key_dns_failure(&st->st_connection->that.id, ugh);
3675                 st->st_suspended_md = NULL;
3676                 r = STF_FAIL + INVALID_KEY_INFORMATION;
3677             }
3678         }
3679         break;
3680
3681     default:
3682         impossible();
3683     }
3684     if (r == STF_OK) {
3685         DBG(DBG_CRYPT, DBG_log("authentication succeeded"));
3686     }
3687     return r;
3688 }
3689
3690 static void
3691 key_continue(struct adns_continuation *cr, err_t ugh
3692 , stf_status (*tail)(struct msg_digest *md))
3693 {
3694     stf_status r;
3695     struct key_continuation *kc = (void *)cr;
3696     struct state *st = kc->md->st;
3697
3698     passert(cur_state == NULL);
3699     /* if st == NULL, our state has been deleted -- just clean up */
3700     if (st != NULL)
3701     {
3702         passert(st->st_suspended_md == kc->md);
3703         st->st_suspended_md = NULL;     /* no longer connected or suspended */
3704         cur_state = kc->md->st;
3705         if (ugh != NULL)
3706         {
3707             report_key_dns_failure(&st->st_connection->that.id, ugh);
3708             r = STF_FAIL + INVALID_KEY_INFORMATION;
3709         }
3710         else
3711         {
3712             passert(keys_from_dns != NULL);
3713             r = (*tail)(kc->md);
3714             passert(keys_from_dns == NULL);
3715         }
3716         complete_state_transition(&kc->md, r);
3717     }
3718     release_md(kc->md);
3719     cur_state = NULL;
3720 }
3721
3722 /* STATE_MAIN_R2:
3723  * PSK_AUTH: HDR*, IDi1, HASH_I --> HDR*, IDr1, HASH_R
3724  * DS_AUTH: HDR*, IDi1, [ CERT, ] SIG_I --> HDR*, IDr1, [ CERT, ] SIG_R
3725  * PKE_AUTH, RPKE_AUTH: HDR*, HASH_I --> HDR*, HASH_R
3726  *
3727  * Broken into parts to allow asynchronous DNS for KEY records.
3728  *
3729  * - main_inI3_outR3 to start
3730  * - main_inI3_outR3_tail to finish or suspend for DNS lookup
3731  * - main_inI3_outR3_continue to start main_inI3_outR3_tail again
3732  */
3733 static stf_status main_inI3_outR3_tail(struct msg_digest *md);  /* forward */
3734
3735 stf_status
3736 main_inI3_outR3(struct msg_digest *md)
3737 {
3738     passert(keys_from_dns == NULL);
3739     return main_inI3_outR3_tail(md);
3740 }
3741
3742 static void
3743 main_inI3_outR3_continue(struct adns_continuation *cr, err_t ugh)
3744 {
3745     key_continue(cr, ugh, main_inI3_outR3_tail);
3746 }
3747
3748 static stf_status
3749 main_inI3_outR3_tail(struct msg_digest *md)
3750 {
3751     struct state *const st = md->st;
3752
3753     u_int8_t auth_payload;
3754     pb_stream r_id_pbs; /* ID Payload; also used for hash calculation */
3755     cert_t mycert;
3756     bool send_cert;
3757
3758     /* HASH_I or SIG_I in */
3759     {
3760         stf_status r = main_id_and_auth(md, FALSE, FALSE
3761             , main_inI3_outR3_continue);
3762
3763         if (r != STF_OK)
3764             return r;
3765     }
3766
3767     /* send certificate if we have one and auth is RSA */
3768     send_cert = (st->st_oakley.auth == OAKLEY_RSA_SIG) &&
3769                 get_mycert(&mycert, st->st_connection->this.cert);
3770
3771     /*************** build output packet HDR*;IDir;HASH/SIG_R ***************/
3772     /* proccess_packet() would automatically generate the HDR*
3773      * payload if smc->first_out_payload is not ISAKMP_NEXT_NONE.
3774      * We don't do this because we wish there to be no partially
3775      * built output packet if we need to suspend for asynch DNS.
3776      */
3777     /* ??? NOTE: this is almost the same as main_inR2_outI3's code */
3778
3779     /* HDR* out
3780      * If auth were PKE_AUTH or RPKE_AUTH, ISAKMP_NEXT_HASH would
3781      * be first payload.
3782      */
3783     echo_hdr(md, TRUE, ISAKMP_NEXT_ID);
3784
3785     auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
3786         ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
3787
3788     /* IDir out */
3789     {
3790         struct isakmp_ipsec_id id_hd;
3791         chunk_t id_b;
3792
3793         build_id_payload(&id_hd, &id_b, &st->st_connection->this);
3794         id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3795         if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &r_id_pbs)
3796         || !out_chunk(id_b, &r_id_pbs, "my identity"))
3797             return STF_INTERNAL_ERROR;
3798
3799         close_output_pbs(&r_id_pbs);
3800     }
3801
3802     /* CERT out, if we have one */
3803     if (send_cert)
3804     {
3805         pb_stream cert_pbs;
3806
3807         struct isakmp_cert cert_hd;
3808         cert_hd.isacert_np = ISAKMP_NEXT_SIG;
3809         cert_hd.isacert_type = mycert.type;
3810
3811         if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3812             return STF_INTERNAL_ERROR;
3813         if (!out_chunk(mycert.cert, &cert_pbs, "CERT"))
3814             return STF_INTERNAL_ERROR;
3815         close_output_pbs(&cert_pbs);
3816     }
3817
3818     /* HASH_R or SIG_R out */
3819     {
3820         u_char hash_val[MAX_DIGEST_LEN];
3821         size_t hash_len = main_mode_hash(st, hash_val, FALSE, &r_id_pbs);
3822
3823         if (auth_payload == ISAKMP_NEXT_HASH)
3824         {
3825             /* HASH_R out */
3826             if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
3827             , hash_val, hash_len, "HASH_R"))
3828                 return STF_INTERNAL_ERROR;
3829         }
3830         else
3831         {
3832             /* SIG_R out */
3833             u_char sig_val[RSA_MAX_OCTETS];
3834             size_t sig_len = RSA_sign_hash(st->st_connection
3835                 , sig_val, hash_val, hash_len);
3836
3837             if (sig_len == 0)
3838             {
3839                 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
3840                 return STF_FAIL + AUTHENTICATION_FAILED;
3841             }
3842
3843             if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3844             , &md->rbody, sig_val, sig_len, "SIG_R"))
3845                 return STF_INTERNAL_ERROR;
3846         }
3847     }
3848
3849     /* encrypt message, sans fixed part of header */
3850
3851     DBG(DBG_CONTROL, DBG_log(" main_inI3_outR3 -4"));
3852     if (!encrypt_message(&md->rbody, st))
3853         return STF_INTERNAL_ERROR;      /* ??? we may be partly committed */
3854
3855     /* Last block of Phase 1 (R3), kept for Phase 2 IV generation */
3856     DBG_cond_dump(DBG_CRYPT, "last encrypted block of Phase 1:"
3857         , st->st_new_iv, st->st_new_iv_len);
3858
3859     ISAKMP_SA_established(st->st_connection, st->st_serialno);
3860
3861     DBG(DBG_CONTROL, DBG_log(" main_inI3_outR3 -5"));
3862     /* ??? If st->st_connectionc->gw_info != NULL,
3863      * we should keep the public key -- it tested out.
3864      */
3865
3866     return STF_OK;
3867 }
3868
3869 /* STATE_MAIN_I3:
3870  * Handle HDR*;IDir;HASH/SIG_R from responder.
3871  *
3872  * Broken into parts to allow asynchronous DNS for KEY records.
3873  *
3874  * - main_inR3 to start
3875  * - main_inR3_tail to finish or suspend for DNS lookup
3876  * - main_inR3_continue to start main_inR3_tail again
3877  */
3878
3879 static stf_status main_inR3_tail(struct msg_digest *md);        /* forward */
3880
3881 stf_status
3882 main_inR3(struct msg_digest *md)
3883 {
3884     passert(keys_from_dns == NULL);
3885     return main_inR3_tail(md);
3886 }
3887
3888 static void
3889 main_inR3_continue(struct adns_continuation *cr, err_t ugh)
3890 {
3891     key_continue(cr, ugh, main_inR3_tail);
3892 }
3893
3894 static stf_status
3895 main_inR3_tail(struct msg_digest *md)
3896 {
3897     struct state *const st = md->st;
3898
3899     /* HASH_R or SIG_R in */
3900     {
3901         stf_status r = main_id_and_auth(md, TRUE, FALSE, main_inR3_continue);
3902
3903         if (r != STF_OK)
3904             return r;
3905     }
3906
3907     /**************** done input ****************/
3908
3909     ISAKMP_SA_established(st->st_connection, st->st_serialno);
3910
3911     /* ??? If c->gw_info != NULL,
3912      * we should keep the public key -- it tested out.
3913      */
3914
3915     update_iv(st);      /* finalize our Phase 1 IV */
3916
3917     return STF_OK;
3918 }
3919
3920 /* Handle first message of Phase 2 -- Quick Mode.
3921  * HDR*, HASH(1), SA, Ni [, KE ] [, IDci, IDcr ] -->
3922  * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ]
3923  * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
3924  * Installs inbound IPsec SAs.
3925  * Although this seems early, we know enough to do so, and
3926  * this way we know that it is soon enough to catch all
3927  * packets that other side could send using this IPsec SA.
3928  *
3929  * Broken into parts to allow asynchronous DNS for TXT records:
3930  *
3931  * - quick_inI1_outR1 starts the ball rolling.
3932  *   It checks and parses enough to learn the Phase 2 IDs
3933  *
3934  * - quick_inI1_outR1_tail does the rest of the job
3935  *   unless DNS must be consulted.  In that case,
3936  *   it starts a DNS query, salts away what is needed
3937  *   to continue, and suspends.
3938  *
3939  * - quick_inI1_outR1_continue will restart quick_inI1_outR1_tail
3940  *   when DNS comes back with an answer.
3941  *
3942  * A big chunk of quick_inI1_outR1_tail is executed twice.
3943  * This is necessary because the set of connections
3944  * might change while we are awaiting DNS.
3945  * When first called, gateways_from_dns == NULL.  If DNS is
3946  * consulted asynchronously, gateways_from_dns != NULL the second time.
3947  * Remember that our state object might disappear too!
3948  */
3949
3950 /* hold anything we can handle of a Phase 2 ID */
3951 struct p2id {
3952     ip_subnet net;
3953     u_int8_t proto;
3954     u_int16_t port;
3955 };
3956
3957 struct verify_continuation {
3958     struct adns_continuation ac;        /* common prefix */
3959     struct msg_digest *md;
3960     struct p2id my, his;
3961     unsigned int new_iv_len;    /* p1st's might change */
3962     u_char new_iv[MAX_DIGEST_LEN];
3963     /* int whackfd; */  /* not needed */
3964 };
3965
3966 static stf_status quick_inI1_outR1_tail(struct msg_digest *md
3967     , struct p2id *my, struct p2id *his
3968     , unsigned int new_iv_len
3969     , const u_char new_iv[MAX_DIGEST_LEN]);     /* forward */
3970
3971
3972 /* STATE_AGGR_R0: HDR, SA, KE, Ni, IDii 
3973  *           --> HDR, SA, KE, Nr, IDir, HASH_R/SIG_R
3974  */
3975 stf_status
3976 aggr_inI1_outR1(struct msg_digest *md)
3977 {
3978     /* With Aggressive Mode, we get an ID payload in this, the first
3979      * message, so we can use it to index the preshared-secrets
3980      * when the IP address would not be meaningful (i.e. Road
3981      * Warrior).  So our first task is to unravel the ID payload.
3982      */
3983
3984     struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
3985     struct state *st;
3986     pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3987     struct connection *c = find_host_connection_mode(&md->iface->addr, pluto_port
3988         , &md->sender, md->sender_port, FALSE);
3989     pb_stream r_sa_pbs;
3990     int auth_payload;
3991
3992     DBG(DBG_CONTROL, DBG_log("aggr_inI1_outR1,"
3993                 //"destination: %s," "portof(md->iface->addr): %d,"
3994                 "sender: %s," " md->sender_port: %d,", 
3995                 //inet_ntoa(md->iface->addr.u.v4.sin_addr), ntohs(portof(&md->iface->addr)),
3996                 inet_ntoa(md->sender.u.v4.sin_addr), md->sender_port));
3997         
3998     if (c == NULL)
3999     {
4000         /* see if a wildcarded connection can be found */
4001         c = find_host_connection_mode(&md->iface->addr, pluto_port
4002                 , (const ip_address *)NULL, md->sender_port, FALSE);
4003         if (c != NULL)
4004         {
4005             /* create a temporary connection that is a copy of this one */
4006             c = rw_instantiate(c, &md->sender,
4007 #ifdef NAT_TRAVERSAL
4008                         md->sender_port,
4009 #endif
4010 #ifdef VIRTUAL_IP
4011                         NULL,
4012 #endif
4013                         NULL);
4014         }
4015         else
4016         {
4017             loglog(RC_LOG_SERIOUS, "initial Aggressive Mode message from %s"
4018                 " but no (wildcard) connection has been configured"
4019                 , inet_ntoa(md->sender.u.v4.sin_addr));
4020             /* XXX notification is in order! */
4021             return STF_IGNORE;
4022         }
4023     }
4024
4025     /* Set up state */
4026     md->st = st = new_state();  
4027     st->st_connection = c;
4028     set_cur_state(st);  /* (caller will reset cur_state) */
4029     
4030     st->st_policy |= POLICY_AGGRESSIVE;
4031
4032     /* KLUDGE: st_oakley determined by SA parse which wants the pre-
4033        shared secret already determinable by decode_peer_id! */
4034     /* we really need to peek into the SA to see if it is RSASIG
4035        or something else. */
4036     st->st_oakley.auth = OAKLEY_PRESHARED_KEY;  /* FIXME! */
4037     
4038     if (!decode_peer_id(md, FALSE, TRUE))
4039     {
4040         char buf[200];
4041
4042         DBG(DBG_CONTROL, DBG_log("aggr_inI1_outR1 5, md->iface->addr.u.v4: %x,"
4043         " pluto_port: %x,"
4044         " md->sender: %x,"
4045         " md->sender_port: %x,", md->iface->addr.u.v4, pluto_port,
4046                                 md->sender.u.v4.sin_addr.s_addr, md->sender_port));
4047         (void) idtoa(&st->st_connection->that.id, buf, sizeof(buf));
4048         loglog(RC_LOG_SERIOUS,
4049              "initial Aggressive Mode packet claiming to be from %s"
4050              " on %s but no connection has been authorized",
4051             buf, inet_ntoa(md->sin.sin_addr));
4052         insert_state(st); /* schedule event to discard connection */
4053         /* XXX notification is in order! */
4054         return STF_FAIL + INVALID_ID_INFORMATION;
4055     }
4056
4057 #ifdef DEBUG
4058     extra_debugging(c);
4059 #endif
4060     st->st_try = 0;     /* Not our job to try again from start */
4061     st->st_policy = st->st_connection->policy & ~POLICY_IPSEC_MASK;  /* only as accurate as connection */
4062
4063 #if 0
4064     /* Copy identity from temporary state object */
4065     st->st_peeridentity = tempstate.st_peeridentity;
4066     st->st_peeridentity_type = tempstate.st_peeridentity_type;
4067     st->st_peeruserprotoid = tempstate.st_peeruserprotoid;
4068     st->st_peeruserport = tempstate.st_peeruserport;
4069 #endif
4070
4071     memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
4072     get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
4073
4074     if (c->dnshostname != NULL)
4075     {
4076         ip_address new_addr;
4077
4078         if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
4079         && !sameaddr(&new_addr, &c->that.host_addr))
4080         {
4081             c->that.host_addr = new_addr;
4082             state_rehash(c);
4083             load_preshared_secrets();
4084         }
4085     }
4086
4087     insert_state(st);   /* needs cookies, connection, and msgid (0) */
4088
4089     st->st_doi = ISAKMP_DOI_IPSEC;
4090     st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
4091     st->st_state = STATE_AGGR_R1;
4092
4093     log("responding to Aggressive Mode, state #%lu, connection \"%s\""
4094         " %s from %s"
4095         , st->st_serialno, st->st_connection->name
4096         , (st->st_connection->kind == CK_INSTANCE) ? "(Road Warrior)" : ""
4097         , inet_ntoa(st->st_connection->that.host_addr.u.v4.sin_addr));
4098     
4099     /* save initiator SA for HASH */
4100     clonereplacechunk(st->st_p1isa, sa_pd->pbs.start, pbs_room(&sa_pd->pbs),
4101                       "sa in aggr_inI1_outR1()");
4102
4103     /* parse_isakmp_sa also spits out a winning SA into our reply,
4104      * so we have to build our md->reply and emit HDR before calling it.
4105      */
4106
4107     /* HDR out */
4108     /* HDR out */
4109     {
4110         struct isakmp_hdr r_hdr = md->hdr;
4111
4112         memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
4113         r_hdr.isa_np = ISAKMP_NEXT_SA;
4114         if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
4115         impossible();   /* surely must have room and be well-formed */
4116     }
4117
4118     /* start of SA out */
4119     {
4120         struct isakmp_sa r_sa = sa_pd->payload.sa;
4121         notification_t r;
4122
4123         r_sa.isasa_np = ISAKMP_NEXT_VID;
4124         if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
4125             return STF_INTERNAL_ERROR;
4126             
4127         /* SA body in and out */
4128         r = parse_isakmp_sa_body(&sa_pd->pbs, &sa_pd->payload.sa,
4129                                  &r_sa_pbs, FALSE, st);
4130         if (r != NOTHING_WRONG)
4131             return STF_FAIL + r;
4132     }
4133
4134     /* don't know until after SA body has been parsed */
4135     auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
4136         ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
4137
4138
4139     /* KE in */
4140     RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
4141
4142     /* Ni in */
4143     RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
4144
4145
4146     /************** build rest of output: KE, Nr, IDir, HASH_R/SIG_R ********/
4147
4148 #ifdef NAT_TRAVERSAL
4149     if (md->nat_traversal_vid && nat_traversal_enabled) {
4150         /* reply if NAT-Traversal draft is supported */
4151         st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
4152         if ((st->nat_traversal) && (!out_vendorid(ISAKMP_NEXT_NONE,
4153             &md->rbody, md->nat_traversal_vid))) {
4154             return STF_INTERNAL_ERROR;
4155         }
4156     }
4157 #endif
4158
4159     /* VID out */
4160     if (!out_vendorid(ISAKMP_NEXT_KE, &md->rbody, VID_MISC_DPD))
4161         return STF_INTERNAL_ERROR;
4162
4163     /* KE */
4164     if (!build_and_ship_KE(st, &st->st_gr, st->st_oakley.group,
4165                            &md->rbody, ISAKMP_NEXT_NONCE))
4166         return STF_INTERNAL_ERROR;
4167
4168     /* Nr */
4169     if (!build_and_ship_nonce(&st->st_nr, &md->rbody, ISAKMP_NEXT_ID, "Nr"))
4170         return STF_INTERNAL_ERROR;
4171
4172     /* IDir out */
4173     {
4174         struct isakmp_ipsec_id id_hd;
4175         chunk_t id_b;
4176         pb_stream r_id_pbs;
4177
4178         build_id_payload(&id_hd, &id_b, &st->st_connection->this);
4179         id_hd.isaiid_np = auth_payload;
4180         if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &r_id_pbs)
4181         || !out_chunk(id_b, &r_id_pbs, "my identity"))
4182             return STF_INTERNAL_ERROR;
4183         close_output_pbs(&r_id_pbs);
4184     }
4185
4186
4187     compute_dh_shared(st, st->st_gi, st->st_oakley.group);
4188 #ifdef DODGE_DH_MISSING_ZERO_BUG
4189     if (st->st_shared.ptr[0] == 0)
4190         return STF_DROP_DOOMED_EXCHANGE;
4191 #endif
4192
4193     if (!generate_skeyids_iv(st))
4194         return STF_FAIL + AUTHENTICATION_FAILED;
4195     update_iv(st);
4196
4197     /* HASH_R or SIG_R out */
4198     {
4199         u_char hash_val[MAX_DIGEST_LEN];
4200         size_t hash_len = aggr_mode_hash(st, hash_val, FALSE, TRUE);
4201
4202         if (auth_payload == ISAKMP_NEXT_HASH)
4203         {
4204             /* HASH_R out */
4205             if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
4206             , hash_val, hash_len, "HASH_R"))
4207                 return STF_INTERNAL_ERROR;
4208         }
4209         else
4210         {
4211             /* SIG_R out */
4212             u_char sig_val[RSA_MAX_OCTETS];
4213             size_t sig_len = RSA_sign_hash(st->st_connection
4214                 , sig_val, hash_val, hash_len);
4215
4216             if (sig_len == 0)
4217             {
4218                 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
4219                 return STF_FAIL + AUTHENTICATION_FAILED;
4220             }
4221
4222             if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
4223             , &md->rbody, sig_val, sig_len, "SIG_R"))
4224                 return STF_INTERNAL_ERROR;
4225         }
4226     }
4227
4228 #ifdef NAT_TRAVERSAL
4229     if (st->nat_traversal & NAT_T_WITH_NATD) {
4230         if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
4231             return STF_INTERNAL_ERROR;
4232     }
4233 #endif
4234
4235     /* finish message */
4236     close_message(&md->rbody);
4237
4238     return STF_OK;
4239 }
4240
4241 /* STATE_AGGR_R2:
4242  * Broken into parts to allow asynchronous DNS for KEY records.
4243  *
4244  * - aggr_inI3_outR3 to start
4245  * - aggr_inI3_outR3_tail to finish or suspend for DNS lookup
4246  * - aggr_inI3_outR3_continue to start main_inI3_outR3_tail again
4247  */
4248 static stf_status aggr_inR1_outI2_tail(struct msg_digest *md);  /* forward */
4249
4250 stf_status
4251 aggr_inR1_outI2(struct msg_digest *md)
4252 {
4253     passert(keys_from_dns == NULL);
4254     return aggr_inR1_outI2_tail(md);
4255 }
4256
4257 static void
4258 aggr_inR1_outI2_continue(struct adns_continuation *cr, err_t ugh)
4259 {;
4260     key_continue(cr, ugh, aggr_inR1_outI2_tail);
4261 }
4262
4263 static stf_status
4264 aggr_inR1_outI2_tail(struct msg_digest *md)
4265 {
4266     /* With Aggressive Mode, we get an ID payload in this, the second
4267      * message, so we can use it to index the preshared-secrets
4268      * when the IP address would not be meaningful (i.e. Road
4269      * Warrior).  So our first task is to unravel the ID payload.
4270      */
4271     struct state *const st = md->st;
4272     pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
4273     struct connection *c = st->st_connection;
4274     u_int8_t auth_payload;
4275
4276     st->st_policy |= POLICY_AGGRESSIVE;
4277
4278 #ifdef NAT_TRAVERSAL
4279     if (md->nat_traversal_vid && nat_traversal_enabled) {
4280         st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
4281     }
4282 #endif
4283
4284     if (!decode_peer_id(md, FALSE, TRUE))
4285     {
4286         char buf[200];
4287
4288         (void) idtoa(&st->st_connection->that.id, buf, sizeof(buf));
4289         loglog(RC_LOG_SERIOUS,
4290              "Initial Aggressive Mode packet claiming to be from %s"
4291              " on %s but no connection has been authorized",
4292             buf, inet_ntoa(md->sender.u.v4.sin_addr));
4293         /* XXX notification is in order! */
4294         return STF_FAIL + INVALID_ID_INFORMATION;
4295     }
4296     auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
4297         ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
4298         
4299     /* verify echoed SA */
4300     {
4301         struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
4302         notification_t r = \
4303             parse_isakmp_sa_body(&sapd->pbs, &sapd->payload.sa,
4304                                  NULL, TRUE, st);
4305
4306         if (r != NOTHING_WRONG)
4307             return STF_FAIL + r;
4308     }
4309
4310     /* KE in */
4311     RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
4312
4313     /* Ni in */
4314     RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
4315
4316     /* moved the following up as we need Rcookie for hash, skeyids */
4317     /* Reinsert the state, using the responder cookie we just received */
4318     unhash_state(st);
4319     memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
4320     insert_state(st);   /* needs cookies, connection, and msgid (0) */
4321
4322     /* Generate SKEYID, SKEYID_A, SKEYID_D, SKEYID_E */
4323     compute_dh_shared(st, st->st_gr, st->st_oakley.group);
4324 #ifdef DODGE_DH_MISSING_ZERO_BUG
4325     if (st->st_shared.ptr[0] == 0)
4326         return STF_REPLACE_DOOMED_EXCHANGE;
4327 #endif
4328     if (!generate_skeyids_iv(st))
4329         return STF_FAIL + AUTHENTICATION_FAILED;
4330     update_iv(st);
4331
4332 #ifdef NAT_TRAVERSAL
4333     if (st->nat_traversal & NAT_T_WITH_NATD) {
4334         nat_traversal_natd_lookup(md);
4335     }
4336     if (st->nat_traversal) {
4337         nat_traversal_show_result(st->nat_traversal, md->sender_port);
4338     }
4339     if (st->nat_traversal & NAT_T_WITH_KA) {
4340         nat_traversal_new_ka_event();
4341     }
4342 #endif  
4343
4344     /* HASH_I or SIG_I in */
4345     {
4346         stf_status r = main_id_and_auth(md, TRUE, TRUE
4347             , aggr_inR1_outI2_continue);
4348
4349         if (r != STF_OK)
4350             return r;
4351     }
4352
4353     /*************** build output packet HDR*;IDir;HASH/SIG_R ***************/
4354     /* proccess_packet() would automatically generate the HDR*
4355      * payload if smc->first_out_payload is not ISAKMP_NEXT_NONE.
4356      * We don't do this because we wish there to be no partially
4357      * built output packet if we need to suspend for asynch DNS.
4358      */
4359     /* ??? NOTE: this is almost the same as main_inR2_outI3's code */
4360
4361     /* HDR* out
4362      * If auth were PKE_AUTH or RPKE_AUTH, ISAKMP_NEXT_HASH would
4363      * be first payload.
4364      */
4365     echo_hdr(md, TRUE, auth_payload);
4366
4367
4368     /* HASH_I or SIG_I out */
4369     {
4370         u_char hash_val[MAX_DIGEST_LEN];
4371         size_t hash_len = aggr_mode_hash(st, hash_val, TRUE, TRUE);
4372
4373         if (auth_payload == ISAKMP_NEXT_HASH)
4374         {
4375             /* HASH_I out */
4376             if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
4377             , hash_val, hash_len, "HASH_I"))
4378                 return STF_INTERNAL_ERROR;
4379         }
4380         else
4381         {
4382             /* SIG_I out */
4383             u_char sig_val[RSA_MAX_OCTETS];
4384             size_t sig_len = RSA_sign_hash(st->st_connection
4385                 , sig_val, hash_val, hash_len);
4386
4387             if (sig_len == 0)
4388             {
4389                 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
4390                 return STF_FAIL + AUTHENTICATION_FAILED;
4391             }
4392
4393             if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
4394             , &md->rbody, sig_val, sig_len, "SIG_I"))
4395                 return STF_INTERNAL_ERROR;
4396         }
4397     }
4398 #ifdef NAT_TRAVERSAL
4399     if (st->nat_traversal & NAT_T_WITH_NATD) {
4400         if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
4401             return STF_INTERNAL_ERROR;
4402     }
4403 #endif
4404
4405     /* encrypt message, sans fixed part of header */
4406
4407    /* st_new_iv was computed by generate_skeyids_iv */
4408     if (!encrypt_message(&md->rbody, st))
4409         return STF_INTERNAL_ERROR;      /* ??? we may be partly committed */
4410
4411     ISAKMP_SA_established(st->st_connection, st->st_serialno);
4412
4413     return STF_OK;
4414 }
4415
4416 /* STATE_AGGR_I2:
4417  * 
4418  * HDR*, HASH_I --> done
4419  *
4420  * Broken into parts to allow asynchronous DNS for KEY records.
4421  *
4422  * - aggr_inR3 to start
4423  * - aggr_inR3_tail to finish or suspend for DNS lookup
4424  * - aggr_inR3_continue to start aggr_inR3_tail again
4425  */
4426
4427 static stf_status aggr_inI2_tail(struct msg_digest *md);        /* forward */
4428
4429 stf_status
4430 aggr_inI2(struct msg_digest *md)
4431 {
4432     passert(keys_from_dns == NULL);
4433     return aggr_inI2_tail(md);
4434 }
4435
4436 static void
4437 aggr_inI2_continue(struct adns_continuation *cr, err_t ugh)
4438 {
4439     key_continue(cr, ugh, aggr_inI2_tail);
4440 }
4441
4442 static stf_status
4443 aggr_inI2_tail(struct msg_digest *md)
4444 {
4445     struct state *const st = md->st;
4446     struct connection *c = st->st_connection;
4447
4448 #ifdef NAT_TRAVERSAL
4449     if (st->nat_traversal & NAT_T_WITH_NATD) {
4450         nat_traversal_natd_lookup(md);
4451     }
4452     if (st->nat_traversal) {
4453         nat_traversal_show_result(st->nat_traversal, md->sender_port);
4454     }
4455     if (st->nat_traversal & NAT_T_WITH_KA) {
4456         nat_traversal_new_ka_event();
4457     }
4458 #endif  
4459
4460     /* HASH_R or SIG_R in */
4461     {
4462         stf_status r = main_id_and_auth(md, FALSE, TRUE, aggr_inI2_continue);
4463
4464         if (r != STF_OK)
4465             return r;
4466     }
4467     /**************** done input ****************/
4468
4469     ISAKMP_SA_established(st->st_connection, st->st_serialno);
4470
4471     /* ??? If c->gw_info != NULL,
4472      * we should keep the public key -- it tested out.
4473      */
4474     update_iv(st);      /* finalize our Phase 1 IV */
4475     return STF_OK;
4476 }
4477
4478 stf_status
4479 quick_inI1_outR1(struct msg_digest *md)
4480 {
4481     const struct state *const p1st = md->st;
4482     struct connection *c = p1st->st_connection;
4483     struct payload_digest *const id_pd = md->chain[ISAKMP_NEXT_ID];
4484     struct p2id my, his;
4485
4486     /* HASH(1) in */
4487     CHECK_QUICK_HASH(md
4488         , quick_mode_hash12(hash_val, hash_pbs->roof, md->message_pbs.roof
4489             , p1st, &md->hdr.isa_msgid, FALSE)
4490         , "HASH(1)", "Quick I1");
4491
4492     /* [ IDci, IDcr ] in
4493      * We do this now (probably out of physical order) because
4494      * we wish to select the correct connection before we consult
4495      * it for policy.
4496      */
4497
4498     if (id_pd != NULL)
4499     {
4500         /* ??? we are assuming IPSEC_DOI */
4501
4502         /* IDci (initiator is peer) */
4503
4504         if (!decode_net_id(&id_pd->payload.ipsec_id, &id_pd->pbs
4505         , &his.net, "peer client"))
4506             return STF_FAIL + INVALID_ID_INFORMATION;
4507
4508         his.proto = id_pd->payload.ipsec_id.isaiid_protoid;
4509         his.port = id_pd->payload.ipsec_id.isaiid_port;
4510
4511         /* IDcr (we are responder) */
4512
4513         if (!decode_net_id(&id_pd->next->payload.ipsec_id, &id_pd->next->pbs
4514         , &my.net, "our client"))
4515             return STF_FAIL + INVALID_ID_INFORMATION;
4516
4517         my.proto = id_pd->next->payload.ipsec_id.isaiid_protoid;
4518         my.port = id_pd->next->payload.ipsec_id.isaiid_port;
4519     }
4520     else
4521     {
4522         /* implicit IDci and IDcr: peer and self */
4523         if (!sameaddrtype(&c->this.host_addr, &c->that.host_addr))
4524             return STF_FAIL;
4525
4526         happy(addrtosubnet(&c->this.host_addr, &my.net));
4527         happy(addrtosubnet(&c->that.host_addr, &his.net));
4528         his.proto = my.proto = 0;
4529         his.port = my.port = 0;
4530     }
4531     passert(gateways_from_dns == NULL);
4532     return quick_inI1_outR1_tail(md, &my, &his
4533         , p1st->st_new_iv_len, p1st->st_new_iv);
4534 }
4535
4536 static void
4537 report_verify_failure(struct state *st, struct p2id *his, err_t ugh)
4538 {
4539     char fgwb[ADDRTOT_BUF]
4540         , cb[ADDRTOT_BUF];
4541     ip_address peer_client;
4542
4543     addrtot(&st->st_connection->that.host_addr, 0, fgwb, sizeof(fgwb));
4544     networkof(&his->net, &peer_client);
4545     addrtot(&peer_client, 0, cb, sizeof(cb));
4546     loglog(RC_OPPOFAILURE
4547         , "gateway %s claims client %s, but DNS for client fails to confirm: %s"
4548         , fgwb, cb, ugh);
4549 }
4550
4551 static void
4552 quick_inI1_outR1_continue(struct adns_continuation *cr, err_t ugh)
4553 {
4554     stf_status r;
4555     struct verify_continuation *vc = (void *)cr;
4556     struct state *st = vc->md->st;
4557
4558     passert(cur_state == NULL);
4559     /* if st == NULL, our state has been deleted -- just clean up */
4560     if (st != NULL)
4561     {
4562         passert(st->st_suspended_md == vc->md);
4563         st->st_suspended_md = NULL;     /* no longer connected or suspended */
4564         cur_state = vc->md->st;
4565         if (ugh != NULL)
4566         {
4567             report_verify_failure(st, &vc->his, ugh);
4568             r = STF_FAIL + INVALID_ID_INFORMATION;
4569         }
4570         else
4571         {
4572             passert(gateways_from_dns != NULL);
4573             r = quick_inI1_outR1_tail(vc->md, &vc->my, &vc->his
4574                 , vc->new_iv_len, vc->new_iv);
4575             passert(gateways_from_dns == NULL);
4576         }
4577         complete_state_transition(&vc->md, r);
4578     }
4579     release_md(vc->md);
4580     cur_state = NULL;
4581 }
4582
4583 static stf_status
4584 quick_inI1_outR1_tail(struct msg_digest *md
4585 , struct p2id *my, struct p2id *his
4586 , unsigned int new_iv_len
4587 , const u_char new_iv[MAX_DIGEST_LEN])
4588 {
4589     struct state *const p1st = md->st;
4590     struct connection *c = p1st->st_connection;
4591     struct payload_digest *const id_pd = md->chain[ISAKMP_NEXT_ID];
4592     ip_subnet *our_net = &my->net
4593         , *his_net = &his->net;
4594
4595     u_char      /* set by START_HASH_PAYLOAD: */
4596         *r_hashval,     /* where in reply to jam hash value */
4597         *r_hash_start;  /* from where to start hashing */
4598
4599     /* Now that we have identities of client subnets, we must look for
4600      * a suitable connection (our current one only matches for hosts).
4601      */
4602     {
4603         struct connection *p = find_client_connection(c
4604             , our_net, his_net, my->proto, my->port, his->proto, his->port);
4605
4606         if (p == NULL)
4607         {
4608             /* This message occurs in very puzzling circumstances
4609              * so we must add as much information and beauty as we can.
4610              */
4611             struct end
4612                 me = c->this,
4613                 he = c->that;
4614             char buf[2*SUBNETTOT_BUF + 2*ADDRTOT_BUF + 2*IDTOA_BUF + 2*ADDRTOT_BUF + 12]; /* + 12 for separating */
4615             size_t l;
4616
4617             me.client = *our_net;
4618             me.has_client = !subnetishost(our_net)
4619                 || !addrinsubnet(&me.host_addr, our_net);
4620             me.protocol = my->proto;
4621             me.port = my->port;
4622
4623             he.client = *his_net;
4624             he.has_client = !subnetishost(his_net)
4625                 || !addrinsubnet(&he.host_addr, his_net);
4626             he.protocol = his->proto;
4627             he.port = his->port;
4628
4629             l = format_end(buf, sizeof(buf), &me, NULL, TRUE);
4630             l += snprintf(buf + l, sizeof(buf) - l, "...");
4631             (void)format_end(buf + l, sizeof(buf) - l, &he, NULL, FALSE);
4632             log("cannot respond to IPsec SA request"
4633                 " because no connection is known for %s"
4634                 , buf);
4635             return STF_FAIL + INVALID_ID_INFORMATION;
4636         }
4637         else if (p != c)
4638         {
4639             /* We've got a better connection: it can support the
4640              * specified clients.  But it may need instantiation.
4641              */
4642             if (p->kind == CK_TEMPLATE)
4643             {
4644                 /* Yup, it needs instantiation.  How much?
4645                  * Is it a Road Warrior connection (simple)
4646                  * or is it an Opportunistic connection (needing gw validation)?
4647                  */
4648                 if (p->policy & POLICY_OPPO)
4649                 {
4650                     /* Opportunistic.
4651                      * We need to determine if this peer is authorized
4652                      * to negotiate for this client!  If the peer's
4653                      * client is the peer, we assume that it is authorized.
4654                      * Since p isn't yet instantiated, we need to look
4655                      * in c for description of peer.
4656                      */
4657                     ip_address our_client
4658                         , his_client;
4659
4660                     passert(subnetishost(our_net) && subnetishost(his_net));
4661
4662                     networkof(our_net, &our_client);
4663                     networkof(his_net, &his_client);
4664
4665                     /* refcounts for gateways_from_dns must balance,
4666                      * but NULL needs no count!
4667                      */
4668                     if (!sameaddr(&c->that.host_addr, &his_client))
4669                     {
4670                         if (gateways_from_dns == NULL)
4671                         {
4672                             /* initiate asynch DNS lookup and suspend */
4673                             struct verify_continuation *vc
4674                                 = alloc_thing(struct verify_continuation
4675                                   , "verify continuation");
4676                             struct id pc_id;
4677                             err_t ugh;
4678
4679                             /* Record that state is used by a suspended md */
4680                             passert(p1st->st_suspended_md == NULL);
4681                             vc->md = p1st->st_suspended_md = md;
4682
4683                             vc->my = *my;
4684                             vc->his = *his;
4685                             vc->new_iv_len = p1st->st_new_iv_len;
4686                             memcpy(vc->new_iv, p1st->st_new_iv, p1st->st_new_iv_len);
4687                             iptoid(&his_client, &pc_id);
4688                             ugh = start_adns_query(&pc_id
4689                                 , &c->that.id
4690                                 , T_TXT
4691                                 , quick_inI1_outR1_continue
4692                                 , &vc->ac);
4693                             if (ugh != NULL)
4694                             {
4695                                 report_verify_failure(p1st, his, ugh);
4696                                 p1st->st_suspended_md = NULL;
4697                                 return STF_FAIL + INVALID_ID_INFORMATION;
4698                             }
4699                             else
4700                             {
4701                                 return STF_SUSPEND;
4702                             }
4703                         }
4704                         else
4705                         {
4706                             /* use result of asynch DNS lookup */
4707                             struct gw_info *gwp;
4708
4709                             /* check that the public key that authenticated
4710                              * the ISAKMP SA (p1st) will do for this gateway.
4711                              */
4712                             for (gwp = gateways_from_dns; ; gwp = gwp->next)
4713                             {
4714                                 if (gwp == NULL)
4715                                 {
4716                                     /* out of luck */
4717                                     loglog(RC_OPPOFAILURE, "peer and client disagree about public key");
4718                                     gw_delref(&gateways_from_dns);
4719                                     return STF_FAIL + INVALID_ID_INFORMATION;
4720                                 }
4721                                 passert(same_id(&gwp->gw_id, &c->that.id));
4722                                 /* If there is a key from the TXT record,
4723                                  * we count it as a win if we match the key.
4724                                  * If there was no key, we claim a match since
4725                                  * it implies fetching a KEY from the same
4726                                  * place we must have gotten it.
4727                                  */
4728                                 if (!gwp->gw_key_present
4729                                 || same_RSA_public_key(&p1st->st_peer_pubkey->u.rsa
4730                                 , &gwp->gw_key))
4731                                     break;      /* good! */
4732                             }
4733                         }
4734                     }
4735
4736                     /* Instantiate inbound Opportunistic connection,
4737                      * carrying over authenticated peer ID
4738                      * and filling in a few more details.
4739                      */
4740                     p = oppo_instantiate(p, &c->that.host_addr, &c->that.id
4741                         , gateways_from_dns, &our_client, &his_client);
4742                     gw_delref(&gateways_from_dns);      /* gateways_from_dns is dead */
4743                 }
4744                 else
4745                 {
4746                     /* Plain Road Warrior:
4747                      * instantiate, carrying over authenticated peer ID
4748                      */
4749                     p = rw_instantiate(p, &c->that.host_addr,
4750 #ifdef NAT_TRAVERSAL
4751                                 md->sender_port,
4752 #endif
4753 #ifdef VIRTUAL_IP
4754                                 his_net,
4755 #endif
4756                                 &c->that.id);
4757                 }
4758             }
4759 #ifdef DEBUG
4760             /* temporarily bump up cur_debugging to get "using..." message
4761              * printed if we'd want it with new connection.
4762              */
4763             {
4764                 unsigned int old_cur_debugging = cur_debugging;
4765
4766                 cur_debugging |= p->extra_debugging;
4767                 DBG(DBG_CONTROL, DBG_log("using connection \"%s\"", p->name));
4768                 cur_debugging = old_cur_debugging;
4769             }
4770 #endif
4771             c = p;
4772         }
4773         /* fill in the client's true ip address/subnet */
4774         if (p->that.has_client_wildcard)
4775         {
4776             p->that.client = *his_net;
4777             p->that.has_client_wildcard = FALSE;
4778         }
4779 #ifdef VIRTUAL_IP
4780         else if (is_virtual_connection(c))
4781         {
4782             c->that.client = *his_net;
4783             c->that.virt = NULL;
4784             if (subnetishost(his_net) && addrinsubnet(&c->that.host_addr, his_net))
4785                 c->that.has_client = FALSE;
4786         }
4787 #endif
4788     }
4789
4790     /* now that we are sure of our connection, create our new state */
4791     {
4792         struct state *const st = duplicate_state(p1st);
4793
4794         /* first: fill in missing bits of our new state object
4795          * note: we don't copy over st_peer_pubkey, the public key
4796          * that authenticated the ISAKMP SA.  We only need it in this
4797          * routine, so we can "reach back" to p1st to get it.
4798          */
4799
4800         if (st->st_connection != c)
4801         {
4802             struct connection *t = st->st_connection;
4803
4804             st->st_connection = c;
4805             set_cur_connection(c);
4806             connection_discard(t);
4807         }
4808
4809         st->st_try = 0; /* not our job to try again from start */
4810
4811         st->st_msgid = md->hdr.isa_msgid;
4812
4813         st->st_new_iv_len = new_iv_len;
4814         memcpy(st->st_new_iv, new_iv, new_iv_len);
4815
4816         set_cur_state(st);      /* (caller will reset) */
4817         md->st = st;    /* feed back new state */
4818
4819         st->st_peeruserprotoid = his->proto;
4820         st->st_peeruserport = his->port;
4821         st->st_myuserprotoid = my->proto;
4822         st->st_myuserport = my->port;
4823
4824         if (c->dnshostname != NULL)
4825         {
4826             ip_address new_addr;
4827
4828             if (ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) == NULL
4829             && !sameaddr(&new_addr, &c->that.host_addr))
4830             {
4831                 c->that.host_addr = new_addr;
4832                 state_rehash(c);
4833                 load_preshared_secrets();
4834             }
4835         }
4836
4837         insert_state(st);       /* needs cookies, connection, and msgid */
4838
4839         /* copy the connection's
4840          * IPSEC policy into our state.  The ISAKMP policy is water under
4841          * the bridge, I think.  It will reflect the ISAKMP SA that we
4842          * are using.
4843          */
4844         st->st_policy = (p1st->st_policy & POLICY_ISAKMP_MASK)
4845             | (c->policy & ~POLICY_ISAKMP_MASK);
4846
4847 #ifdef NAT_TRAVERSAL
4848         if (p1st->nat_traversal & NAT_T_DETECTED) {
4849             st->nat_traversal = p1st->nat_traversal;
4850             nat_traversal_change_port_lookup(md, md->st);
4851         }
4852         else {
4853             st->nat_traversal = 0;
4854         }
4855         if ((st->nat_traversal & NAT_T_DETECTED) &&
4856             (st->nat_traversal & NAT_T_WITH_NATOA)) {
4857             nat_traversal_natoa_lookup(md);
4858         }
4859 #endif
4860
4861         /* Start the output packet.
4862          *
4863          * proccess_packet() would automatically generate the HDR*
4864          * payload if smc->first_out_payload is not ISAKMP_NEXT_NONE.
4865          * We don't do this because we wish there to be no partially
4866          * built output packet if we need to suspend for asynch DNS.
4867          *
4868          * We build the reply packet as we parse the message since
4869          * the parse_ipsec_sa_body emits the reply SA
4870          */
4871
4872         /* HDR* out */
4873         echo_hdr(md, TRUE, ISAKMP_NEXT_HASH);
4874
4875         /* HASH(2) out -- first pass */
4876         START_HASH_PAYLOAD(md->rbody, ISAKMP_NEXT_SA);
4877
4878         /* process SA (in and out) */
4879         {
4880             struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
4881             pb_stream r_sa_pbs;
4882             struct isakmp_sa sa = sapd->payload.sa;
4883
4884             /* sa header is unchanged -- except for np */
4885             sa.isasa_np = ISAKMP_NEXT_NONCE;
4886             if (!out_struct(&sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
4887                 return STF_INTERNAL_ERROR;
4888
4889             /* parse and accept body */
4890             st->st_pfs_group = &unset_group;
4891             RETURN_STF_FAILURE(parse_ipsec_sa_body(&sapd->pbs
4892                     , &sapd->payload.sa, &r_sa_pbs, FALSE, st));
4893         }
4894
4895         passert(st->st_pfs_group != &unset_group);
4896
4897         if ((st->st_policy & POLICY_PFS) && st->st_pfs_group == NULL)
4898         {
4899             loglog(RC_LOG_SERIOUS, "we require PFS but Quick I1 SA specifies no GROUP_DESCRIPTION");
4900             return STF_FAIL + NO_PROPOSAL_CHOSEN;       /* ??? */
4901         }
4902
4903         /* Ni in */
4904         RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
4905
4906         /* [ KE ] in (for PFS) */
4907         RETURN_STF_FAILURE(accept_PFS_KE(md, &st->st_gi, "Gi", "Quick Mode I1"));
4908
4909         log("responding to Quick Mode");
4910
4911         /**** finish reply packet: Nr [, KE ] [, IDci, IDcr ] ****/
4912
4913         /* Nr out */
4914         if (!build_and_ship_nonce(&st->st_nr, &md->rbody
4915         , st->st_pfs_group != NULL? ISAKMP_NEXT_KE : id_pd != NULL? ISAKMP_NEXT_ID : ISAKMP_NEXT_NONE
4916         , "Nr"))
4917             return STF_INTERNAL_ERROR;
4918
4919         /* [ KE ] out (for PFS) */
4920
4921         if (st->st_pfs_group != NULL)
4922         {
4923             if (!build_and_ship_KE(st, &st->st_gr, st->st_pfs_group
4924             , &md->rbody, id_pd != NULL? ISAKMP_NEXT_ID : ISAKMP_NEXT_NONE))
4925                     return STF_INTERNAL_ERROR;
4926
4927             /* MPZ-Operations might be done after sending the packet... */
4928
4929     #ifndef DODGE_DH_MISSING_ZERO_BUG
4930             compute_dh_shared(st, st->st_gi, st->st_pfs_group);
4931     #endif
4932         }
4933
4934         /* [ IDci, IDcr ] out */
4935         if  (id_pd != NULL)
4936         {
4937             struct isakmp_ipsec_id *p = (void *)md->rbody.cur;  /* UGH! */
4938
4939             if (!out_raw(id_pd->pbs.start, pbs_room(&id_pd->pbs), &md->rbody, "IDci"))
4940                 return STF_INTERNAL_ERROR;
4941             p->isaiid_np = ISAKMP_NEXT_ID;
4942
4943             p = (void *)md->rbody.cur;  /* UGH! */
4944
4945             if (!out_raw(id_pd->next->pbs.start, pbs_room(&id_pd->next->pbs), &md->rbody, "IDcr"))
4946                 return STF_INTERNAL_ERROR;
4947             p->isaiid_np = ISAKMP_NEXT_NONE;
4948         }
4949
4950 #ifdef NAT_TRAVERSAL
4951         if ((st->nat_traversal & NAT_T_WITH_NATOA) &&
4952             (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)) &&
4953             (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TRANSPORT)) {
4954             /** Send NAT-OA if our address is NATed and if we use Transport Mode */
4955             if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &md->rbody, md->st)) {
4956                 return STF_INTERNAL_ERROR;
4957             }
4958         }
4959         if ((st->nat_traversal & NAT_T_DETECTED) &&
4960             (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TRANSPORT) &&
4961             (c->that.has_client)) {
4962             /** Remove client **/
4963             addrtosubnet(&c->that.host_addr, &c->that.client);
4964             c->that.has_client = FALSE;
4965         }
4966 #endif
4967
4968         /* Compute reply HASH(2) and insert in output */
4969         (void)quick_mode_hash12(r_hashval, r_hash_start, md->rbody.cur
4970             , st, &st->st_msgid, TRUE);
4971
4972         /* Derive new keying material */
4973         compute_keymats(st);
4974
4975         /* Tell the kernel to establish the new inbound SA
4976          * (unless the commit bit is set -- which we don't support).
4977          * We do this before any state updating so that
4978          * failure won't look like success.
4979          */
4980         if (!install_inbound_ipsec_sa(st))
4981             return STF_INTERNAL_ERROR;  /* ??? we may be partly committed */
4982
4983         /* encrypt message, except for fixed part of header */
4984
4985         if (!encrypt_message(&md->rbody, st))
4986             return STF_INTERNAL_ERROR;  /* ??? we may be partly committed */
4987
4988         return STF_OK;
4989     }
4990 }
4991
4992 /* Handle (the single) message from Responder in Quick Mode.
4993  * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ] -->
4994  * HDR*, HASH(3)
4995  * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
4996  * Installs inbound and outbound IPsec SAs, routing, etc.
4997  */
4998 stf_status
4999 quick_inR1_outI2(struct msg_digest *md)
5000 {
5001     struct state *const st = md->st;
5002     const struct connection *c = st->st_connection;
5003
5004     /* HASH(2) in */
5005     CHECK_QUICK_HASH(md
5006         , quick_mode_hash12(hash_val, hash_pbs->roof, md->message_pbs.roof
5007             , st, &st->st_msgid, TRUE)
5008         , "HASH(2)", "Quick R1");
5009
5010     /* SA in */
5011     {
5012         struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
5013
5014         RETURN_STF_FAILURE(parse_ipsec_sa_body(&sa_pd->pbs
5015             , &sa_pd->payload.sa, NULL, TRUE, st));
5016     }
5017
5018     /* Nr in */
5019     RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
5020
5021     /* [ KE ] in (for PFS) */
5022     RETURN_STF_FAILURE(accept_PFS_KE(md, &st->st_gr, "Gr", "Quick Mode R1"));
5023
5024     if (st->st_pfs_group != NULL)
5025     {
5026         compute_dh_shared(st, st->st_gr, st->st_pfs_group);
5027 #ifdef DODGE_DH_MISSING_ZERO_BUG
5028         if (st->st_shared.ptr[0] == 0)
5029             return STF_REPLACE_DOOMED_EXCHANGE;
5030 #endif
5031     }
5032
5033     /* [ IDci, IDcr ] in; these must match what we sent */
5034
5035     {
5036         struct payload_digest *const id_pd = md->chain[ISAKMP_NEXT_ID];
5037
5038         if (id_pd != NULL)
5039         {
5040             /* ??? we are assuming IPSEC_DOI */
5041
5042             /* IDci (we are initiator) */
5043
5044             if (!check_net_id(&id_pd->payload.ipsec_id, &id_pd->pbs
5045             , &st->st_myuserprotoid, &st->st_myuserport
5046             , &st->st_connection->this.client
5047             , "our client"))
5048                 return STF_FAIL + INVALID_ID_INFORMATION;
5049
5050             /* IDcr (responder is peer) */
5051
5052             if (!check_net_id(&id_pd->next->payload.ipsec_id, &id_pd->next->pbs
5053             , &st->st_peeruserprotoid, &st->st_peeruserport
5054             , &st->st_connection->that.client
5055             , "peer client"))
5056                 return STF_FAIL + INVALID_ID_INFORMATION;
5057         }
5058         else
5059         {
5060             /* No IDci, IDcr: we must check that the defaults match our proposal.
5061              * Parallels a sequence of assignments in quick_outI1.
5062              */
5063             if (!subnetishost(&c->this.client) || !subnetishost(&c->that.client))
5064             {
5065                 loglog(RC_LOG_SERIOUS, "IDci, IDcr payloads missing in message"
5066                     " but default does not match proposal");
5067                 return STF_FAIL + INVALID_ID_INFORMATION;
5068             }
5069         }
5070     }
5071
5072 #ifdef NAT_TRAVERSAL
5073         if ((st->nat_traversal & NAT_T_DETECTED) &&
5074             (st->nat_traversal & NAT_T_WITH_NATOA)) {
5075             nat_traversal_natoa_lookup(md);
5076         }
5077 #endif
5078
5079     /* ??? We used to copy the accepted proposal into the state, but it was
5080      * never used.  From sa_pd->pbs.start, length pbs_room(&sa_pd->pbs).
5081      */
5082
5083     /**************** build reply packet HDR*, HASH(3) ****************/
5084
5085     /* HDR* out done */
5086
5087     /* HASH(3) out -- since this is the only content, no passes needed */
5088     {
5089         u_char  /* set by START_HASH_PAYLOAD: */
5090             *r_hashval, /* where in reply to jam hash value */
5091             *r_hash_start;      /* start of what is to be hashed */
5092
5093         START_HASH_PAYLOAD(md->rbody, ISAKMP_NEXT_NONE);
5094         (void)quick_mode_hash3(r_hashval, st);
5095     }
5096
5097     /* Derive new keying material */
5098     compute_keymats(st);
5099
5100     /* Tell the kernel to establish the inbound, outbound, and routing part
5101      * of the new SA (unless the commit bit is set -- which we don't support).
5102      * We do this before any state updating so that
5103      * failure won't look like success.
5104      */
5105     if (!install_ipsec_sa(st, TRUE))
5106         return STF_INTERNAL_ERROR;
5107
5108     /* encrypt message, except for fixed part of header */
5109
5110     if (!encrypt_message(&md->rbody, st))
5111         return STF_INTERNAL_ERROR;      /* ??? we may be partly committed */
5112
5113     st->st_connection->newest_ipsec_sa = st->st_serialno;
5114
5115     /* note (presumed) success */
5116     if (c->gw_info != NULL)
5117         c->gw_info->last_worked_time = now();
5118
5119     if (st->st_connection->kind == CK_PERMANENT && st->st_connection->dpd_delay)
5120         dpd_init(st);
5121
5122     return STF_OK;
5123 }
5124
5125 /* Handle last message of Quick Mode.
5126  * HDR*, HASH(3) -> done
5127  * (see draft-ietf-ipsec-isakmp-oakley-07.txt 5.5)
5128  * Installs outbound IPsec SAs, routing, etc.
5129  */
5130 stf_status
5131 quick_inI2(struct msg_digest *md)
5132 {
5133     struct state *const st = md->st;
5134
5135     /* HASH(3) in */
5136     CHECK_QUICK_HASH(md, quick_mode_hash3(hash_val, st)
5137         , "HASH(3)", "Quick I2");
5138
5139     /* Tell the kernel to establish the outbound and routing part of the new SA
5140      * (the previous state established inbound)
5141      * (unless the commit bit is set -- which we don't support).
5142      * We do this before any state updating so that
5143      * failure won't look like success.
5144      */
5145     if (!install_ipsec_sa(st, FALSE))
5146         return STF_INTERNAL_ERROR;
5147
5148     st->st_connection->newest_ipsec_sa = st->st_serialno;
5149
5150     update_iv(st);      /* not actually used, but tidy */
5151
5152     /* note (presumed) success */
5153     {
5154         struct gw_info *gw = st->st_connection->gw_info;
5155
5156         if (gw != NULL)
5157             gw->last_worked_time = now();
5158     }
5159
5160     if (st->st_connection->kind == CK_PERMANENT && st->st_connection->dpd_delay)
5161         dpd_init(st);
5162
5163     return STF_OK;
5164 }
5165
5166 static stf_status
5167 send_isakmp_notification(struct state *st,
5168         u_int16_t type, const void *data, size_t len)
5169 {
5170     msgid_t msgid;
5171     pb_stream reply;
5172     pb_stream rbody;
5173     u_char old_new_iv[MAX_DIGEST_LEN];
5174     u_char old_iv[MAX_DIGEST_LEN];
5175     u_char
5176         *r_hashval,     /* where in reply to jam hash value */
5177         *r_hash_start;  /* start of what is to be hashed */
5178
5179     msgid = generate_msgid(st);
5180
5181     init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "ISAKMP notify");
5182
5183     /* HDR* */
5184     {
5185         struct isakmp_hdr hdr;
5186
5187         hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
5188         hdr.isa_np = ISAKMP_NEXT_HASH;
5189         hdr.isa_xchg = ISAKMP_XCHG_INFO;
5190         hdr.isa_msgid = msgid;
5191         hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
5192         memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
5193         memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
5194         if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
5195             impossible();
5196     }
5197   
5198     /* HASH -- create and note space to be filled later */
5199     START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_N);
5200
5201     /* NOTIFY */
5202     {
5203         pb_stream notify_pbs;
5204         struct isakmp_notification isan;
5205
5206         isan.isan_np = ISAKMP_NEXT_NONE;
5207         isan.isan_doi = ISAKMP_DOI_IPSEC;
5208         isan.isan_protoid = PROTO_ISAKMP;
5209         isan.isan_spisize = COOKIE_SIZE * 2;
5210         isan.isan_type = type;
5211         if (!out_struct(&isan, &isakmp_notification_desc, &rbody, &notify_pbs))
5212             return STF_INTERNAL_ERROR;
5213         if (!out_raw(st->st_icookie, COOKIE_SIZE, &notify_pbs, "notify icookie"))
5214             return STF_INTERNAL_ERROR;
5215         if (!out_raw(st->st_rcookie, COOKIE_SIZE, &notify_pbs, "notify rcookie"))
5216             return STF_INTERNAL_ERROR;
5217         if (data != NULL && len > 0)
5218             if (!out_raw(data, len, &notify_pbs, "notify data"))
5219                 return STF_INTERNAL_ERROR;
5220         close_output_pbs(&notify_pbs);
5221     }
5222
5223     {
5224         /* finish computing HASH */
5225         struct hmac_ctx ctx;
5226
5227         hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
5228         hmac_update(&ctx, (const u_char *) &msgid, sizeof(msgid_t));
5229         hmac_update(&ctx, r_hash_start, rbody.cur-r_hash_start);
5230         hmac_final(r_hashval, &ctx);
5231
5232         DBG(DBG_CRYPT,
5233                 DBG_log("HASH computed:");
5234                 DBG_dump("", r_hashval, ctx.hmac_digest_size));
5235     }
5236
5237     /* save old IV (this prevents from copying a whole new state object 
5238      * for NOTIFICATION / DELETE messages we don't need to maintain a state
5239      * because there are no retransmissions...
5240      */
5241
5242     memcpy(old_new_iv, st->st_new_iv, st->st_new_iv_len);
5243     memcpy(old_iv, st->st_iv, st->st_iv_len);
5244     init_phase2_iv(st, &msgid);
5245
5246     if (!encrypt_message(&rbody, st))
5247         return STF_INTERNAL_ERROR;
5248
5249     {
5250         chunk_t saved_tpacket = st->st_tpacket;
5251
5252         setchunk(st->st_tpacket, reply.start, pbs_offset(&reply));
5253         send_packet(st, "ISAKMP notify");
5254         st->st_tpacket = saved_tpacket;
5255     }    
5256
5257     /* get back old IV for this state */
5258     memcpy(st->st_new_iv, old_new_iv, st->st_new_iv_len);
5259     memcpy(st->st_iv, old_iv, st->st_iv_len);
5260
5261     return STF_IGNORE;
5262 }
5263
5264 static void
5265 dpd_init(struct state *st)
5266 {
5267     struct state *p1st;
5268
5269     /* find the related Phase 1 state */
5270     p1st = find_state(st->st_icookie, st->st_rcookie,
5271             &st->st_connection->that.host_addr, 0);
5272     if (p1st == NULL)
5273         loglog(RC_LOG_SERIOUS, "could not find phase 1 state for DPD");
5274     else if (p1st->st_dpd)
5275         event_schedule(EVENT_DPD, st->st_connection->dpd_delay, st);
5276 }
5277
5278 void
5279 dpd_outI(struct state *p2st)
5280 {
5281     struct state *st;
5282     time_t tm;
5283     u_int32_t seqno;
5284     time_t delay = p2st->st_connection->dpd_delay;
5285     time_t timeout = p2st->st_connection->dpd_timeout;
5286
5287     /* find the related Phase 1 state */
5288     st = find_phase1_state(p2st->st_connection, FALSE);
5289     if (st == NULL)
5290     {
5291         loglog(RC_LOG_SERIOUS, "could not find newest phase 1 state for DPD");
5292         return;
5293     }
5294     if (!st->st_dpd)
5295         return;
5296
5297     /* If an R_U_THERE has been sent or received recently, then
5298      * base the resend time on that. */
5299     tm = now();
5300     if (tm < st->st_last_dpd + delay)
5301     {
5302         event_schedule(EVENT_DPD, st->st_last_dpd + delay - tm, p2st);
5303         /* If there is still a timeout for the last R_U_THERE sent,
5304          * and the timeout is greater than ours, then reduce it. */
5305         if (st->st_dpd_event != NULL
5306         && st->st_dpd_event->ev_time > st->st_last_dpd + timeout)
5307         {
5308             delete_dpd_event(st);
5309             event_schedule(EVENT_DPD_TIMEOUT, st->st_last_dpd + timeout - tm, st);
5310         }
5311         return;
5312     }
5313
5314     event_schedule(EVENT_DPD, delay, p2st);
5315
5316     if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
5317         return;
5318
5319     if (!st->st_dpd_seqno)
5320     {
5321         /* Get a non-zero random value that has room to grow */
5322         get_rnd_bytes((u_char *)&st->st_dpd_seqno, sizeof(st->st_dpd_seqno));
5323         st->st_dpd_seqno &= 0x7fff;
5324         st->st_dpd_seqno++;
5325     }
5326     seqno = htonl(st->st_dpd_seqno);
5327     if (send_isakmp_notification(st, R_U_THERE, &seqno, sizeof(seqno)) != STF_IGNORE)
5328     {
5329         loglog(RC_LOG_SERIOUS, "could not send R_U_THERE");
5330         return;
5331     }
5332
5333     st->st_dpd_expectseqno = st->st_dpd_seqno++;
5334     st->st_last_dpd = tm;
5335     /* Only schedule a new timeout if there isn't one currently,
5336      * or if it would be sooner than the current timeout. */
5337     if (st->st_dpd_event == NULL
5338     || st->st_dpd_event->ev_time > tm + timeout)
5339     {
5340         delete_dpd_event(st);
5341         event_schedule(EVENT_DPD_TIMEOUT, timeout, st);
5342     }
5343 }
5344
5345 stf_status
5346 dpd_inI_outR(struct state *st, struct isakmp_notification *const n, pb_stream *n_pbs)
5347 {
5348     time_t tm = now();
5349     u_int32_t seqno;
5350
5351     if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
5352     {
5353         loglog(RC_LOG_SERIOUS, "recevied R_U_THERE for unestablished ISKAMP SA");
5354         return;
5355     }
5356
5357     if (n->isan_spisize != COOKIE_SIZE * 2 || pbs_left(n_pbs) < COOKIE_SIZE * 2)
5358     {
5359         loglog(RC_LOG_SERIOUS, "R_U_THERE has invalid SPI length (%d)", n->isan_spisize);
5360         return;
5361     }
5362
5363     if (memcmp(n_pbs->cur, st->st_icookie, COOKIE_SIZE) != 0)
5364     {
5365         loglog(RC_LOG_SERIOUS, "R_U_THERE has invalid icookie");
5366         return;
5367     }
5368     n_pbs->cur += COOKIE_SIZE;
5369
5370     if (memcmp(n_pbs->cur, st->st_rcookie, COOKIE_SIZE) != 0)
5371     {
5372         loglog(RC_LOG_SERIOUS, "R_U_THERE has invalid rcookie");
5373         return;
5374     }
5375     n_pbs->cur += COOKIE_SIZE;
5376
5377     if (pbs_left(n_pbs) != sizeof(seqno))
5378     {
5379         loglog(RC_LOG_SERIOUS, "R_U_THERE has invalid data length (%d)", pbs_left(n_pbs));
5380         return;
5381     }
5382
5383     seqno = ntohl(*(u_int32_t *)n_pbs->cur);
5384     if (st->st_dpd_peerseqno && seqno <= st->st_dpd_peerseqno) {
5385         loglog(RC_LOG_SERIOUS, "received old or duplicate R_U_THERE");
5386         return;
5387     }
5388
5389     st->st_dpd_peerseqno = seqno;
5390     delete_dpd_event(st);
5391
5392     if (send_isakmp_notification(st, R_U_THERE_ACK, n_pbs->cur, pbs_left(n_pbs)) != STF_IGNORE)
5393     {
5394         loglog(RC_LOG_SERIOUS, "could not send R_U_THERE_ACK");
5395         return STF_IGNORE;
5396     }
5397
5398     st->st_last_dpd = tm;
5399     return STF_IGNORE;
5400 }
5401
5402 stf_status
5403 dpd_inR(struct state *st, struct isakmp_notification *const n, pb_stream *n_pbs)
5404 {
5405     u_int32_t seqno;
5406     u_int8_t tmp[COOKIE_SIZE];
5407     
5408     memset(tmp, 0, sizeof(tmp));
5409
5410     if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
5411     {
5412         loglog(RC_LOG_SERIOUS, "recevied R_U_THERE_ACK for unestablished ISKAMP SA");
5413         return;
5414     }
5415
5416     if (n->isan_spisize != COOKIE_SIZE * 2 || pbs_left(n_pbs) < COOKIE_SIZE * 2)
5417     {
5418         loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has invalid SPI length (%d)", n->isan_spisize);
5419         return;
5420     }
5421
5422     if (memcmp(n_pbs->cur, st->st_icookie, COOKIE_SIZE) != 0 && memcmp(n_pbs->cur, st->st_rcookie, COOKIE_SIZE) != 0)
5423     {
5424         loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has invalid icookie");
5425         return;
5426     }
5427     n_pbs->cur += COOKIE_SIZE;
5428     if (memcmp(n_pbs->cur, st->st_rcookie, COOKIE_SIZE) != 0 && memcmp(n_pbs->cur, &tmp, COOKIE_SIZE) != 0)
5429     {
5430         loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has invalid rcookie");
5431         return;
5432     }
5433     n_pbs->cur += COOKIE_SIZE;
5434
5435     if (pbs_left(n_pbs) != sizeof(seqno))
5436     {
5437         loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has invalid data length (%d)", pbs_left(n_pbs));
5438         return;
5439     }
5440
5441     seqno = ntohl(*(u_int32_t *)n_pbs->cur);
5442     if (!st->st_dpd_expectseqno && seqno != st->st_dpd_expectseqno) {
5443         loglog(RC_LOG_SERIOUS, "R_U_THERE_ACK has unexpected sequence number");
5444         return;
5445     }
5446
5447     st->st_dpd_expectseqno = 0;
5448     delete_dpd_event(st);
5449     return STF_IGNORE;
5450 }
5451
5452 void
5453 dpd_timeout(struct state *st)
5454 {
5455     struct connection *c = st->st_connection;
5456
5457     loglog(RC_LOG_SERIOUS, "timeout waiting for DPD ack, replacing SA");
5458     terminate_connections_by_peer(c);
5459     initiate_connections_by_peer(c);
5460 }