fixed bug in ifdef CISCO_QUIRKS
[strongswan.git] / src / 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: ipsec_doi.c,v 1.39 2006/04/22 21:59:20 as Exp $
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/queue.h>
29 #include <sys/time.h> /* for gettimeofday */
30
31 #include <freeswan.h>
32 #include <ipsec_policy.h>
33
34 #include "constants.h"
35 #include "defs.h"
36 #include "mp_defs.h"
37 #include "state.h"
38 #include "id.h"
39 #include "x509.h"
40 #include "crl.h"
41 #include "ca.h"
42 #include "certs.h"
43 #include "smartcard.h"
44 #include "connections.h"
45 #include "keys.h"
46 #include "packet.h"
47 #include "demux.h" /* needs packet.h */
48 #include "adns.h" /* needs <resolv.h> */
49 #include "dnskey.h" /* needs keys.h and adns.h */
50 #include "kernel.h"
51 #include "log.h"
52 #include "cookie.h"
53 #include "server.h"
54 #include "spdb.h"
55 #include "timer.h"
56 #include "rnd.h"
57 #include "ipsec_doi.h" /* needs demux.h and state.h */
58 #include "whack.h"
59 #include "fetch.h"
60 #include "pkcs7.h"
61 #include "asn1.h"
62
63 #include "sha1.h"
64 #include "md5.h"
65 #include "crypto.h" /* requires sha1.h and md5.h */
66 #include "vendor.h"
67 #include "alg_info.h"
68 #include "ike_alg.h"
69 #include "kernel_alg.h"
70 #include "nat_traversal.h"
71 #include "virtual.h"
72
73 /*
74 * are we sending Pluto's Vendor ID?
75 */
76 #ifdef VENDORID
77 #define SEND_PLUTO_VID 1
78 #else /* !VENDORID */
79 #define SEND_PLUTO_VID 0
80 #endif /* !VENDORID */
81
82 /*
83 * are we sending an XAUTH VID (Cisco Mode Config Interoperability)?
84 */
85 #ifdef XAUTH_VID
86 #define SEND_XAUTH_VID 1
87 #else /* !XAUTH_VID */
88 #define SEND_XAUTH_VID 0
89 #endif /* !XAUTH_VID */
90
91 /*
92 * are we sending a Cisco Unity VID?
93 */
94 #ifdef CISCO_QUIRKS
95 #define SEND_CISCO_UNITY_VID 1
96 #else /* !CISCO_QUIRKS */
97 #define SEND_CISCO_UNITY_VID 0
98 #endif /* !CISCO_QUIRKS */
99
100 /* MAGIC: perform f, a function that returns notification_t
101 * and return from the ENCLOSING stf_status returning function if it fails.
102 */
103 #define RETURN_STF_FAILURE(f) \
104 { int r = (f); if (r != NOTHING_WRONG) return STF_FAIL + r; }
105
106 /* create output HDR as replica of input HDR */
107 void
108 echo_hdr(struct msg_digest *md, bool enc, u_int8_t np)
109 {
110 struct isakmp_hdr r_hdr = md->hdr; /* mostly same as incoming header */
111
112 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
113 if (enc)
114 r_hdr.isa_flags |= ISAKMP_FLAG_ENCRYPTION;
115 /* some day, we may have to set r_hdr.isa_version */
116 r_hdr.isa_np = np;
117 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
118 impossible(); /* surely must have room and be well-formed */
119 }
120
121 /* Compute DH shared secret from our local secret and the peer's public value.
122 * We make the leap that the length should be that of the group
123 * (see quoted passage at start of ACCEPT_KE).
124 */
125 static void
126 compute_dh_shared(struct state *st, const chunk_t g
127 , const struct oakley_group_desc *group)
128 {
129 MP_INT mp_g, mp_shared;
130 struct timeval tv0, tv1;
131 unsigned long tv_diff;
132
133 gettimeofday(&tv0, NULL);
134 passert(st->st_sec_in_use);
135 n_to_mpz(&mp_g, g.ptr, g.len);
136 mpz_init(&mp_shared);
137 mpz_powm(&mp_shared, &mp_g, &st->st_sec, group->modulus);
138 mpz_clear(&mp_g);
139 freeanychunk(st->st_shared); /* happens in odd error cases */
140 st->st_shared = mpz_to_n(&mp_shared, group->bytes);
141 mpz_clear(&mp_shared);
142 gettimeofday(&tv1, NULL);
143 tv_diff=(tv1.tv_sec - tv0.tv_sec) * 1000000 + (tv1.tv_usec - tv0.tv_usec);
144 DBG(DBG_CRYPT,
145 DBG_log("compute_dh_shared(): time elapsed (%s): %ld usec"
146 , enum_show(&oakley_group_names, st->st_oakley.group->group)
147 , tv_diff);
148 );
149 /* if took more than 200 msec ... */
150 if (tv_diff > 200000) {
151 loglog(RC_LOG_SERIOUS, "WARNING: compute_dh_shared(): for %s took "
152 "%ld usec"
153 , enum_show(&oakley_group_names, st->st_oakley.group->group)
154 , tv_diff);
155 }
156
157 DBG_cond_dump_chunk(DBG_CRYPT, "DH shared secret:\n", st->st_shared);
158 }
159
160 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
161 * the corresponding public value (g). This is emitted as a KE payload.
162 */
163 static bool
164 build_and_ship_KE(struct state *st, chunk_t *g
165 , const struct oakley_group_desc *group, pb_stream *outs, u_int8_t np)
166 {
167 if (!st->st_sec_in_use)
168 {
169 u_char tmp[LOCALSECRETSIZE];
170 MP_INT mp_g;
171
172 get_rnd_bytes(tmp, LOCALSECRETSIZE);
173 st->st_sec_in_use = TRUE;
174 n_to_mpz(&st->st_sec, tmp, LOCALSECRETSIZE);
175
176 mpz_init(&mp_g);
177 mpz_powm(&mp_g, &groupgenerator, &st->st_sec, group->modulus);
178 freeanychunk(*g); /* happens in odd error cases */
179 *g = mpz_to_n(&mp_g, group->bytes);
180 mpz_clear(&mp_g);
181 DBG(DBG_CRYPT,
182 DBG_dump("Local DH secret:\n", tmp, LOCALSECRETSIZE);
183 DBG_dump_chunk("Public DH value sent:\n", *g));
184 }
185 return out_generic_chunk(np, &isakmp_keyex_desc, outs, *g, "keyex value");
186 }
187
188 /* accept_ke
189 *
190 * Check and accept DH public value (Gi or Gr) from peer's message.
191 * According to RFC2409 "The Internet key exchange (IKE)" 5:
192 * The Diffie-Hellman public value passed in a KE payload, in either
193 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
194 * Diffie-Hellman group enforced, if necessary, by pre-pending the
195 * value with zeros.
196 */
197 static notification_t
198 accept_KE(chunk_t *dest, const char *val_name
199 , const struct oakley_group_desc *gr
200 , pb_stream *pbs)
201 {
202 if (pbs_left(pbs) != gr->bytes)
203 {
204 loglog(RC_LOG_SERIOUS, "KE has %u byte DH public value; %u required"
205 , (unsigned) pbs_left(pbs), (unsigned) gr->bytes);
206 /* XXX Could send notification back */
207 return INVALID_KEY_INFORMATION;
208 }
209 clonereplacechunk(*dest, pbs->cur, pbs_left(pbs), val_name);
210 DBG_cond_dump_chunk(DBG_CRYPT, "DH public value received:\n", *dest);
211 return NOTHING_WRONG;
212 }
213
214 /* accept_PFS_KE
215 *
216 * Check and accept optional Quick Mode KE payload for PFS.
217 * Extends ACCEPT_PFS to check whether KE is allowed or required.
218 */
219 static notification_t
220 accept_PFS_KE(struct msg_digest *md, chunk_t *dest
221 , const char *val_name, const char *msg_name)
222 {
223 struct state *st = md->st;
224 struct payload_digest *const ke_pd = md->chain[ISAKMP_NEXT_KE];
225
226 if (ke_pd == NULL)
227 {
228 if (st->st_pfs_group != NULL)
229 {
230 loglog(RC_LOG_SERIOUS, "missing KE payload in %s message", msg_name);
231 return INVALID_KEY_INFORMATION;
232 }
233 }
234 else
235 {
236 if (st->st_pfs_group == NULL)
237 {
238 loglog(RC_LOG_SERIOUS, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
239 , msg_name);
240 return INVALID_KEY_INFORMATION;
241 }
242 if (ke_pd->next != NULL)
243 {
244 loglog(RC_LOG_SERIOUS, "%s message contains several KE payloads; we accept at most one", msg_name);
245 return INVALID_KEY_INFORMATION; /* ??? */
246 }
247 return accept_KE(dest, val_name, st->st_pfs_group, &ke_pd->pbs);
248 }
249 return NOTHING_WRONG;
250 }
251
252 static bool
253 build_and_ship_nonce(chunk_t *n, pb_stream *outs, u_int8_t np
254 , const char *name)
255 {
256 freeanychunk(*n);
257 setchunk(*n, alloc_bytes(DEFAULT_NONCE_SIZE, name), DEFAULT_NONCE_SIZE);
258 get_rnd_bytes(n->ptr, DEFAULT_NONCE_SIZE);
259 return out_generic_chunk(np, &isakmp_nonce_desc, outs, *n, name);
260 }
261
262 static bool
263 collect_rw_ca_candidates(struct msg_digest *md, generalName_t **top)
264 {
265 struct connection *d = find_host_connection(&md->iface->addr
266 , pluto_port, (ip_address*)NULL, md->sender_port, LEMPTY);
267
268 for (; d != NULL; d = d->hp_next)
269 {
270 /* must be a road warrior connection */
271 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)
272 && d->spd.that.ca.ptr != NULL)
273 {
274 generalName_t *gn;
275 bool new_entry = TRUE;
276
277 for (gn = *top; gn != NULL; gn = gn->next)
278 {
279 if (same_dn(gn->name, d->spd.that.ca))
280 {
281 new_entry = FALSE;
282 break;
283 }
284 }
285 if (new_entry)
286 {
287 gn = alloc_thing(generalName_t, "generalName");
288 gn->kind = GN_DIRECTORY_NAME;
289 gn->name = d->spd.that.ca;
290 gn->next = *top;
291 *top = gn;
292 }
293 }
294 }
295 return *top != NULL;
296 }
297
298 static bool
299 build_and_ship_CR(u_int8_t type, chunk_t ca, pb_stream *outs, u_int8_t np)
300 {
301 pb_stream cr_pbs;
302 struct isakmp_cr cr_hd;
303 cr_hd.isacr_np = np;
304 cr_hd.isacr_type = type;
305
306 /* build CR header */
307 if (!out_struct(&cr_hd, &isakmp_ipsec_cert_req_desc, outs, &cr_pbs))
308 return FALSE;
309
310 if (ca.ptr != NULL)
311 {
312 /* build CR body containing the distinguished name of the CA */
313 if (!out_chunk(ca, &cr_pbs, "CA"))
314 return FALSE;
315 }
316 close_output_pbs(&cr_pbs);
317 return TRUE;
318 }
319
320 /* Send a notification to the peer. We could decide
321 * whether to send the notification, based on the type and the
322 * destination, if we care to.
323 */
324 static void
325 send_notification(struct state *sndst, u_int16_t type, struct state *encst,
326 msgid_t msgid, u_char *icookie, u_char *rcookie,
327 u_char *spi, size_t spisize, u_char protoid)
328 {
329 u_char buffer[1024];
330 pb_stream pbs, r_hdr_pbs;
331 u_char *r_hashval = NULL; /* where in reply to jam hash value */
332 u_char *r_hash_start = NULL; /* start of what is to be hashed */
333
334 passert((sndst) && (sndst->st_connection));
335
336 plog("sending %snotification %s to %s:%u"
337 , encst ? "encrypted " : ""
338 , enum_name(&notification_names, type)
339 , ip_str(&sndst->st_connection->spd.that.host_addr)
340 , (unsigned)sndst->st_connection->spd.that.host_port);
341
342 memset(buffer, 0, sizeof(buffer));
343 init_pbs(&pbs, buffer, sizeof(buffer), "ISAKMP notify");
344
345 /* HDR* */
346 {
347 struct isakmp_hdr hdr;
348
349 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
350 hdr.isa_np = encst ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_N;
351 hdr.isa_xchg = ISAKMP_XCHG_INFO;
352 hdr.isa_msgid = msgid;
353 hdr.isa_flags = encst ? ISAKMP_FLAG_ENCRYPTION : 0;
354 if (icookie)
355 memcpy(hdr.isa_icookie, icookie, COOKIE_SIZE);
356 if (rcookie)
357 memcpy(hdr.isa_rcookie, rcookie, COOKIE_SIZE);
358 if (!out_struct(&hdr, &isakmp_hdr_desc, &pbs, &r_hdr_pbs))
359 impossible();
360 }
361
362 /* HASH -- value to be filled later */
363 if (encst)
364 {
365 pb_stream hash_pbs;
366 if (!out_generic(ISAKMP_NEXT_N, &isakmp_hash_desc, &r_hdr_pbs,
367 &hash_pbs))
368 impossible();
369 r_hashval = hash_pbs.cur; /* remember where to plant value */
370 if (!out_zero(
371 encst->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH"))
372 impossible();
373 close_output_pbs(&hash_pbs);
374 r_hash_start = r_hdr_pbs.cur; /* hash from after HASH */
375 }
376
377 /* Notification Payload */
378 {
379 pb_stream not_pbs;
380 struct isakmp_notification isan;
381
382 isan.isan_doi = ISAKMP_DOI_IPSEC;
383 isan.isan_np = ISAKMP_NEXT_NONE;
384 isan.isan_type = type;
385 isan.isan_spisize = spisize;
386 isan.isan_protoid = protoid;
387
388 if (!out_struct(&isan, &isakmp_notification_desc, &r_hdr_pbs, &not_pbs)
389 || !out_raw(spi, spisize, &not_pbs, "spi"))
390 impossible();
391 close_output_pbs(&not_pbs);
392 }
393
394 /* calculate hash value and patch into Hash Payload */
395 if (encst)
396 {
397 struct hmac_ctx ctx;
398 hmac_init_chunk(&ctx, encst->st_oakley.hasher, encst->st_skeyid_a);
399 hmac_update(&ctx, (u_char *) &msgid, sizeof(msgid_t));
400 hmac_update(&ctx, r_hash_start, r_hdr_pbs.cur-r_hash_start);
401 hmac_final(r_hashval, &ctx);
402
403 DBG(DBG_CRYPT,
404 DBG_log("HASH computed:");
405 DBG_dump("", r_hashval, ctx.hmac_digest_size);
406 )
407 }
408
409 /* Encrypt message (preserve st_iv and st_new_iv) */
410 if (encst)
411 {
412 u_char old_iv[MAX_DIGEST_LEN];
413 u_char new_iv[MAX_DIGEST_LEN];
414
415 u_int old_iv_len = encst->st_iv_len;
416 u_int new_iv_len = encst->st_new_iv_len;
417
418 if (old_iv_len > MAX_DIGEST_LEN || new_iv_len > MAX_DIGEST_LEN)
419 impossible();
420
421 memcpy(old_iv, encst->st_iv, old_iv_len);
422 memcpy(new_iv, encst->st_new_iv, new_iv_len);
423
424 if (!IS_ISAKMP_SA_ESTABLISHED(encst->st_state))
425 {
426 memcpy(encst->st_ph1_iv, encst->st_new_iv, encst->st_new_iv_len);
427 encst->st_ph1_iv_len = encst->st_new_iv_len;
428 }
429 init_phase2_iv(encst, &msgid);
430 if (!encrypt_message(&r_hdr_pbs, encst))
431 impossible();
432
433 /* restore preserved st_iv and st_new_iv */
434 memcpy(encst->st_iv, old_iv, old_iv_len);
435 memcpy(encst->st_new_iv, new_iv, new_iv_len);
436 encst->st_iv_len = old_iv_len;
437 encst->st_new_iv_len = new_iv_len;
438 }
439 else
440 {
441 close_output_pbs(&r_hdr_pbs);
442 }
443
444 /* Send packet (preserve st_tpacket) */
445 {
446 chunk_t saved_tpacket = sndst->st_tpacket;
447
448 setchunk(sndst->st_tpacket, pbs.start, pbs_offset(&pbs));
449 send_packet(sndst, "ISAKMP notify");
450 sndst->st_tpacket = saved_tpacket;
451 }
452 }
453
454 void
455 send_notification_from_state(struct state *st, enum state_kind state,
456 u_int16_t type)
457 {
458 struct state *p1st;
459
460 passert(st);
461
462 if (state == STATE_UNDEFINED)
463 state = st->st_state;
464
465 if (IS_QUICK(state)) {
466 p1st = find_phase1_state(st->st_connection, ISAKMP_SA_ESTABLISHED_STATES);
467 if ((p1st == NULL) || (!IS_ISAKMP_SA_ESTABLISHED(p1st->st_state))) {
468 loglog(RC_LOG_SERIOUS,
469 "no Phase1 state for Quick mode notification");
470 return;
471 }
472 send_notification(st, type, p1st, generate_msgid(p1st),
473 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
474 }
475 else if (IS_ISAKMP_ENCRYPTED(state)) {
476 send_notification(st, type, st, generate_msgid(st),
477 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
478 }
479 else {
480 /* no ISAKMP SA established - don't encrypt notification */
481 send_notification(st, type, NULL, 0,
482 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
483 }
484 }
485
486 void
487 send_notification_from_md(struct msg_digest *md, u_int16_t type)
488 {
489 /**
490 * Create a dummy state to be able to use send_packet in
491 * send_notification
492 *
493 * we need to set:
494 * st_connection->that.host_addr
495 * st_connection->that.host_port
496 * st_connection->interface
497 */
498 struct state st;
499 struct connection cnx;
500
501 passert(md);
502
503 memset(&st, 0, sizeof(st));
504 memset(&cnx, 0, sizeof(cnx));
505 st.st_connection = &cnx;
506 cnx.spd.that.host_addr = md->sender;
507 cnx.spd.that.host_port = md->sender_port;
508 cnx.interface = md->iface;
509
510 send_notification(&st, type, NULL, 0,
511 md->hdr.isa_icookie, md->hdr.isa_rcookie, NULL, 0, PROTO_ISAKMP);
512 }
513
514 /* Send a Delete Notification to announce deletion of ISAKMP SA or
515 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
516 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
517 */
518 void
519 send_delete(struct state *st)
520 {
521 pb_stream reply_pbs;
522 pb_stream r_hdr_pbs;
523 msgid_t msgid;
524 u_char buffer[8192];
525 struct state *p1st;
526 ip_said said[EM_MAXRELSPIS];
527 ip_said *ns = said;
528 u_char
529 *r_hashval, /* where in reply to jam hash value */
530 *r_hash_start; /* start of what is to be hashed */
531 bool isakmp_sa = FALSE;
532
533 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
534 {
535 p1st = find_phase1_state(st->st_connection, ISAKMP_SA_ESTABLISHED_STATES);
536 if (p1st == NULL)
537 {
538 DBG(DBG_CONTROL, DBG_log("no Phase 1 state for Delete"));
539 return;
540 }
541
542 if (st->st_ah.present)
543 {
544 ns->spi = st->st_ah.our_spi;
545 ns->dst = st->st_connection->spd.this.host_addr;
546 ns->proto = PROTO_IPSEC_AH;
547 ns++;
548 }
549 if (st->st_esp.present)
550 {
551 ns->spi = st->st_esp.our_spi;
552 ns->dst = st->st_connection->spd.this.host_addr;
553 ns->proto = PROTO_IPSEC_ESP;
554 ns++;
555 }
556
557 passert(ns != said); /* there must be some SAs to delete */
558 }
559 else if (IS_ISAKMP_SA_ESTABLISHED(st->st_state))
560 {
561 p1st = st;
562 isakmp_sa = TRUE;
563 }
564 else
565 {
566 return; /* nothing to do */
567 }
568
569 msgid = generate_msgid(p1st);
570
571 zero(buffer);
572 init_pbs(&reply_pbs, buffer, sizeof(buffer), "delete msg");
573
574 /* HDR* */
575 {
576 struct isakmp_hdr hdr;
577
578 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
579 hdr.isa_np = ISAKMP_NEXT_HASH;
580 hdr.isa_xchg = ISAKMP_XCHG_INFO;
581 hdr.isa_msgid = msgid;
582 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
583 memcpy(hdr.isa_icookie, p1st->st_icookie, COOKIE_SIZE);
584 memcpy(hdr.isa_rcookie, p1st->st_rcookie, COOKIE_SIZE);
585 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply_pbs, &r_hdr_pbs))
586 impossible();
587 }
588
589 /* HASH -- value to be filled later */
590 {
591 pb_stream hash_pbs;
592
593 if (!out_generic(ISAKMP_NEXT_D, &isakmp_hash_desc, &r_hdr_pbs, &hash_pbs))
594 impossible();
595 r_hashval = hash_pbs.cur; /* remember where to plant value */
596 if (!out_zero(p1st->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH(1)"))
597 impossible();
598 close_output_pbs(&hash_pbs);
599 r_hash_start = r_hdr_pbs.cur; /* hash from after HASH(1) */
600 }
601
602 /* Delete Payloads */
603 if (isakmp_sa)
604 {
605 pb_stream del_pbs;
606 struct isakmp_delete isad;
607 u_char isakmp_spi[2*COOKIE_SIZE];
608
609 isad.isad_doi = ISAKMP_DOI_IPSEC;
610 isad.isad_np = ISAKMP_NEXT_NONE;
611 isad.isad_spisize = (2 * COOKIE_SIZE);
612 isad.isad_protoid = PROTO_ISAKMP;
613 isad.isad_nospi = 1;
614
615 memcpy(isakmp_spi, st->st_icookie, COOKIE_SIZE);
616 memcpy(isakmp_spi+COOKIE_SIZE, st->st_rcookie, COOKIE_SIZE);
617
618 if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
619 || !out_raw(&isakmp_spi, (2*COOKIE_SIZE), &del_pbs, "delete payload"))
620 impossible();
621 close_output_pbs(&del_pbs);
622 }
623 else
624 {
625 while (ns != said)
626 {
627
628 pb_stream del_pbs;
629 struct isakmp_delete isad;
630
631 ns--;
632 isad.isad_doi = ISAKMP_DOI_IPSEC;
633 isad.isad_np = ns == said? ISAKMP_NEXT_NONE : ISAKMP_NEXT_D;
634 isad.isad_spisize = sizeof(ipsec_spi_t);
635 isad.isad_protoid = ns->proto;
636
637 isad.isad_nospi = 1;
638 if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
639 || !out_raw(&ns->spi, sizeof(ipsec_spi_t), &del_pbs, "delete payload"))
640 impossible();
641 close_output_pbs(&del_pbs);
642 }
643 }
644
645 /* calculate hash value and patch into Hash Payload */
646 {
647 struct hmac_ctx ctx;
648 hmac_init_chunk(&ctx, p1st->st_oakley.hasher, p1st->st_skeyid_a);
649 hmac_update(&ctx, (u_char *) &msgid, sizeof(msgid_t));
650 hmac_update(&ctx, r_hash_start, r_hdr_pbs.cur-r_hash_start);
651 hmac_final(r_hashval, &ctx);
652
653 DBG(DBG_CRYPT,
654 DBG_log("HASH(1) computed:");
655 DBG_dump("", r_hashval, ctx.hmac_digest_size);
656 )
657 }
658
659 /* Do a dance to avoid needing a new state object.
660 * We use the Phase 1 State. This is the one with right
661 * IV, for one thing.
662 * The tricky bits are:
663 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
664 * - we need to preserve (save/restore) st_tpacket.
665 */
666 {
667 u_char old_iv[MAX_DIGEST_LEN];
668 chunk_t saved_tpacket = p1st->st_tpacket;
669
670 memcpy(old_iv, p1st->st_iv, p1st->st_iv_len);
671 init_phase2_iv(p1st, &msgid);
672
673 if (!encrypt_message(&r_hdr_pbs, p1st))
674 impossible();
675
676 setchunk(p1st->st_tpacket, reply_pbs.start, pbs_offset(&reply_pbs));
677 send_packet(p1st, "delete notify");
678 p1st->st_tpacket = saved_tpacket;
679
680 /* get back old IV for this state */
681 memcpy(p1st->st_iv, old_iv, p1st->st_iv_len);
682 }
683 }
684
685 void
686 accept_delete(struct state *st, struct msg_digest *md, struct payload_digest *p)
687 {
688 struct isakmp_delete *d = &(p->payload.delete);
689 size_t sizespi;
690 int i;
691
692 if (!md->encrypted)
693 {
694 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: not encrypted");
695 return;
696 }
697
698 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
699 {
700 /* can't happen (if msg is encrypt), but just to be sure */
701 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
702 "ISAKMP SA not established");
703 return;
704 }
705
706 if (d->isad_nospi == 0)
707 {
708 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: no SPI");
709 return;
710 }
711
712 switch (d->isad_protoid)
713 {
714 case PROTO_ISAKMP:
715 sizespi = 2 * COOKIE_SIZE;
716 break;
717 case PROTO_IPSEC_AH:
718 case PROTO_IPSEC_ESP:
719 sizespi = sizeof(ipsec_spi_t);
720 break;
721 case PROTO_IPCOMP:
722 /* nothing interesting to delete */
723 return;
724 default:
725 loglog(RC_LOG_SERIOUS
726 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
727 , enum_show(&protocol_names, d->isad_protoid));
728 return;
729 }
730
731 if (d->isad_spisize != sizespi)
732 {
733 loglog(RC_LOG_SERIOUS
734 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
735 , d->isad_spisize, enum_show(&protocol_names, d->isad_protoid));
736 return;
737 }
738
739 if (pbs_left(&p->pbs) != d->isad_nospi * sizespi)
740 {
741 loglog(RC_LOG_SERIOUS
742 , "ignoring Delete SA payload: invalid payload size");
743 return;
744 }
745
746 for (i = 0; i < d->isad_nospi; i++)
747 {
748 u_char *spi = p->pbs.cur + (i * sizespi);
749
750 if (d->isad_protoid == PROTO_ISAKMP)
751 {
752 /**
753 * ISAKMP
754 */
755 struct state *dst = find_state(spi /*iCookie*/
756 , spi+COOKIE_SIZE /*rCookie*/
757 , &st->st_connection->spd.that.host_addr
758 , MAINMODE_MSGID);
759
760 if (dst == NULL)
761 {
762 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
763 "ISAKMP SA not found (maybe expired)");
764 }
765 else if (!same_peer_ids(st->st_connection, dst->st_connection, NULL))
766 {
767 /* we've not authenticated the relevant identities */
768 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
769 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
770 }
771 else
772 {
773 struct connection *oldc;
774
775 oldc = cur_connection;
776 set_cur_connection(dst->st_connection);
777
778 if (nat_traversal_enabled)
779 nat_traversal_change_port_lookup(md, dst);
780
781 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
782 "deleting ISAKMP State #%lu", dst->st_serialno);
783 delete_state(dst);
784 set_cur_connection(oldc);
785 }
786 }
787 else
788 {
789 /**
790 * IPSEC (ESP/AH)
791 */
792 bool bogus;
793 struct state *dst = find_phase2_state_to_delete(st
794 , d->isad_protoid
795 , *(ipsec_spi_t *)spi /* network order */
796 , &bogus);
797
798 if (dst == NULL)
799 {
800 loglog(RC_LOG_SERIOUS
801 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
802 , enum_show(&protocol_names, d->isad_protoid)
803 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t *)spi)
804 , bogus ? "our SPI - bogus implementation" : "maybe expired");
805 }
806 else
807 {
808 struct connection *rc = dst->st_connection;
809 struct connection *oldc;
810
811 oldc = cur_connection;
812 set_cur_connection(rc);
813
814 if (nat_traversal_enabled)
815 nat_traversal_change_port_lookup(md, dst);
816
817 if (rc->newest_ipsec_sa == dst->st_serialno
818 && (rc->policy & POLICY_UP))
819 {
820 /* Last IPSec SA for a permanent connection that we
821 * have initiated. Replace it in a few seconds.
822 *
823 * Useful if the other peer is rebooting.
824 */
825 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
826 if (dst->st_event != NULL
827 && dst->st_event->ev_type == EVENT_SA_REPLACE
828 && dst->st_event->ev_time <= DELETE_SA_DELAY + now())
829 {
830 /* Patch from Angus Lees to ignore retransmited
831 * Delete SA.
832 */
833 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
834 "already replacing IPSEC State #%lu in %d seconds"
835 , dst->st_serialno, (int)(dst->st_event->ev_time - now()));
836 }
837 else
838 {
839 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
840 "replace IPSEC State #%lu in %d seconds"
841 , dst->st_serialno, DELETE_SA_DELAY);
842 dst->st_margin = DELETE_SA_DELAY;
843 delete_event(dst);
844 event_schedule(EVENT_SA_REPLACE, DELETE_SA_DELAY, dst);
845 }
846 }
847 else
848 {
849 loglog(RC_LOG_SERIOUS, "received Delete SA(0x%08lx) payload: "
850 "deleting IPSEC State #%lu"
851 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t *)spi)
852 , dst->st_serialno);
853 delete_state(dst);
854 }
855
856 /* reset connection */
857 set_cur_connection(oldc);
858 }
859 }
860 }
861 }
862
863 /* The whole message must be a multiple of 4 octets.
864 * I'm not sure where this is spelled out, but look at
865 * rfc2408 3.6 Transform Payload.
866 * Note: it talks about 4 BYTE boundaries!
867 */
868 void
869 close_message(pb_stream *pbs)
870 {
871 size_t padding = pad_up(pbs_offset(pbs), 4);
872
873 if (padding != 0)
874 (void) out_zero(padding, pbs, "message padding");
875 close_output_pbs(pbs);
876 }
877
878 /* Initiate an Oakley Main Mode exchange.
879 * --> HDR;SA
880 * Note: this is not called from demux.c
881 */
882 static stf_status
883 main_outI1(int whack_sock, struct connection *c, struct state *predecessor
884 , lset_t policy, unsigned long try)
885 {
886 struct state *st = new_state();
887 pb_stream reply; /* not actually a reply, but you know what I mean */
888 pb_stream rbody;
889
890 int vids_to_send = 0;
891
892 /* set up new state */
893 st->st_connection = c;
894 set_cur_state(st); /* we must reset before exit */
895 st->st_policy = policy & ~POLICY_IPSEC_MASK;
896 st->st_whack_sock = whack_sock;
897 st->st_try = try;
898 st->st_state = STATE_MAIN_I1;
899
900 /* determine how many Vendor ID payloads we will be sending */
901 if (SEND_PLUTO_VID)
902 vids_to_send++;
903 if (SEND_XAUTH_VID)
904 vids_to_send++;
905 if (SEND_CISCO_UNITY_VID)
906 vids_to_send++;
907 if (c->spd.this.cert.type == CERT_PGP)
908 vids_to_send++;
909 /* always send DPD Vendor ID */
910 vids_to_send++;
911 if (nat_traversal_enabled)
912 vids_to_send++;
913
914 get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->spd.that.host_addr);
915
916 insert_state(st); /* needs cookies, connection, and msgid (0) */
917
918 if (HAS_IPSEC_POLICY(policy))
919 add_pending(dup_any(whack_sock), st, c, policy, 1
920 , predecessor == NULL? SOS_NOBODY : predecessor->st_serialno);
921
922 if (predecessor == NULL)
923 plog("initiating Main Mode");
924 else
925 plog("initiating Main Mode to replace #%lu", predecessor->st_serialno);
926
927 /* set up reply */
928 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
929
930 /* HDR out */
931 {
932 struct isakmp_hdr hdr;
933
934 zero(&hdr); /* default to 0 */
935 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
936 hdr.isa_np = ISAKMP_NEXT_SA;
937 hdr.isa_xchg = ISAKMP_XCHG_IDPROT;
938 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
939 /* R-cookie, flags and MessageID are left zero */
940
941 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
942 {
943 reset_cur_state();
944 return STF_INTERNAL_ERROR;
945 }
946 }
947
948 /* SA out */
949 {
950 u_char *sa_start = rbody.cur;
951 lset_t auth_policy = policy & POLICY_ID_AUTH_MASK;
952
953 if (!out_sa(&rbody, &oakley_sadb[auth_policy >> POLICY_ISAKMP_SHIFT]
954 , st, TRUE, vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE))
955 {
956 reset_cur_state();
957 return STF_INTERNAL_ERROR;
958 }
959
960 /* save initiator SA for later HASH */
961 passert(st->st_p1isa.ptr == NULL); /* no leak! (MUST be first time) */
962 clonetochunk(st->st_p1isa, sa_start, rbody.cur - sa_start
963 , "sa in main_outI1");
964 }
965
966 /* if enabled send Pluto Vendor ID */
967 if (SEND_PLUTO_VID)
968 {
969 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
970 , &rbody, VID_STRONGSWAN))
971 {
972 reset_cur_state();
973 return STF_INTERNAL_ERROR;
974 }
975 }
976
977 /* if enabled send XAUTH Vendor ID */
978 if (SEND_XAUTH_VID)
979 {
980 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
981 , &rbody, VID_MISC_XAUTH))
982 {
983 reset_cur_state();
984 return STF_INTERNAL_ERROR;
985 }
986 }
987
988 /* if enabled send Cisco Unity Vendor ID */
989 if (SEND_CISCO_UNITY_VID)
990 {
991 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
992 , &rbody, VID_CISCO_UNITY))
993 {
994 reset_cur_state();
995 return STF_INTERNAL_ERROR;
996 }
997 }
998 /* if we have an OpenPGP certificate we assume an
999 * OpenPGP peer and have to send the Vendor ID
1000 */
1001 if (c->spd.this.cert.type == CERT_PGP)
1002 {
1003 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1004 , &rbody, VID_OPENPGP))
1005 {
1006 reset_cur_state();
1007 return STF_INTERNAL_ERROR;
1008 }
1009 }
1010
1011 /* Announce our ability to do Dead Peer Detection to the peer */
1012 {
1013 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1014 , &rbody, VID_MISC_DPD))
1015 {
1016 reset_cur_state();
1017 return STF_INTERNAL_ERROR;
1018 }
1019 }
1020
1021 if (nat_traversal_enabled)
1022 {
1023 /* Add supported NAT-Traversal VID */
1024 if (!nat_traversal_add_vid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1025 , &rbody))
1026 {
1027 reset_cur_state();
1028 return STF_INTERNAL_ERROR;
1029 }
1030 }
1031
1032 close_message(&rbody);
1033 close_output_pbs(&reply);
1034
1035 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
1036 , "reply packet for main_outI1");
1037
1038 /* Transmit */
1039
1040 send_packet(st, "main_outI1");
1041
1042 /* Set up a retransmission event, half a minute henceforth */
1043 delete_event(st);
1044 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
1045
1046 if (predecessor != NULL)
1047 {
1048 update_pending(predecessor, st);
1049 whack_log(RC_NEW_STATE + STATE_MAIN_I1
1050 , "%s: initiate, replacing #%lu"
1051 , enum_name(&state_names, st->st_state)
1052 , predecessor->st_serialno);
1053 }
1054 else
1055 {
1056 whack_log(RC_NEW_STATE + STATE_MAIN_I1
1057 , "%s: initiate", enum_name(&state_names, st->st_state));
1058 }
1059 reset_cur_state();
1060 return STF_OK;
1061 }
1062
1063 void
1064 ipsecdoi_initiate(int whack_sock
1065 , struct connection *c
1066 , lset_t policy
1067 , unsigned long try
1068 , so_serial_t replacing)
1069 {
1070 /* If there's already an ISAKMP SA established, use that and
1071 * go directly to Quick Mode. We are even willing to use one
1072 * that is still being negotiated, but only if we are the Initiator
1073 * (thus we can be sure that the IDs are not going to change;
1074 * other issues around intent might matter).
1075 * Note: there is no way to initiate with a Road Warrior.
1076 */
1077 struct state *st = find_phase1_state(c
1078 , ISAKMP_SA_ESTABLISHED_STATES | PHASE1_INITIATOR_STATES);
1079
1080 if (st == NULL)
1081 {
1082 (void) main_outI1(whack_sock, c, NULL, policy, try);
1083 }
1084 else if (HAS_IPSEC_POLICY(policy))
1085 {
1086 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1087 {
1088 /* leave our Phase 2 negotiation pending */
1089 add_pending(whack_sock, st, c, policy, try, replacing);
1090 }
1091 else
1092 {
1093 /* ??? we assume that peer_nexthop_sin isn't important:
1094 * we already have it from when we negotiated the ISAKMP SA!
1095 * It isn't clear what to do with the error return.
1096 */
1097 (void) quick_outI1(whack_sock, st, c, policy, try, replacing);
1098 }
1099 }
1100 else
1101 {
1102 close_any(whack_sock);
1103 }
1104 }
1105
1106 /* Replace SA with a fresh one that is similar
1107 *
1108 * Shares some logic with ipsecdoi_initiate, but not the same!
1109 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1110 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1111 * ISAKMP SA if needed.
1112 * - duplicate whack fd, if live.
1113 * Does not delete the old state -- someone else will do that.
1114 */
1115 void
1116 ipsecdoi_replace(struct state *st, unsigned long try)
1117 {
1118 int whack_sock = dup_any(st->st_whack_sock);
1119 lset_t policy = st->st_policy;
1120
1121 if (IS_PHASE1(st->st_state))
1122 {
1123 passert(!HAS_IPSEC_POLICY(policy));
1124 (void) main_outI1(whack_sock, st->st_connection, st, policy, try);
1125 }
1126 else
1127 {
1128 /* Add features of actual old state to policy. This ensures
1129 * that rekeying doesn't downgrade security. I admit that
1130 * this doesn't capture everything.
1131 */
1132 if (st->st_pfs_group != NULL)
1133 policy |= POLICY_PFS;
1134 if (st->st_ah.present)
1135 {
1136 policy |= POLICY_AUTHENTICATE;
1137 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1138 policy |= POLICY_TUNNEL;
1139 }
1140 if (st->st_esp.present && st->st_esp.attrs.transid != ESP_NULL)
1141 {
1142 policy |= POLICY_ENCRYPT;
1143 if (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1144 policy |= POLICY_TUNNEL;
1145 }
1146 if (st->st_ipcomp.present)
1147 {
1148 policy |= POLICY_COMPRESS;
1149 if (st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1150 policy |= POLICY_TUNNEL;
1151 }
1152 passert(HAS_IPSEC_POLICY(policy));
1153 ipsecdoi_initiate(whack_sock, st->st_connection, policy, try
1154 , st->st_serialno);
1155 }
1156 }
1157
1158 /* SKEYID for preshared keys.
1159 * See draft-ietf-ipsec-ike-01.txt 4.1
1160 */
1161 static bool
1162 skeyid_preshared(struct state *st)
1163 {
1164 const chunk_t *pss = get_preshared_secret(st->st_connection);
1165
1166 if (pss == NULL)
1167 {
1168 loglog(RC_LOG_SERIOUS, "preshared secret disappeared!");
1169 return FALSE;
1170 }
1171 else
1172 {
1173 struct hmac_ctx ctx;
1174
1175 hmac_init_chunk(&ctx, st->st_oakley.hasher, *pss);
1176 hmac_update_chunk(&ctx, st->st_ni);
1177 hmac_update_chunk(&ctx, st->st_nr);
1178 hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_preshared()", &ctx);
1179 return TRUE;
1180 }
1181 }
1182
1183 static bool
1184 skeyid_digisig(struct state *st)
1185 {
1186 struct hmac_ctx ctx;
1187 chunk_t nir;
1188
1189 /* We need to hmac_init with the concatenation of Ni_b and Nr_b,
1190 * so we have to build a temporary concatentation.
1191 */
1192 nir.len = st->st_ni.len + st->st_nr.len;
1193 nir.ptr = alloc_bytes(nir.len, "Ni + Nr in skeyid_digisig");
1194 memcpy(nir.ptr, st->st_ni.ptr, st->st_ni.len);
1195 memcpy(nir.ptr+st->st_ni.len, st->st_nr.ptr, st->st_nr.len);
1196 hmac_init_chunk(&ctx, st->st_oakley.hasher, nir);
1197 pfree(nir.ptr);
1198
1199 hmac_update_chunk(&ctx, st->st_shared);
1200 hmac_final_chunk(st->st_skeyid, "st_skeyid in skeyid_digisig()", &ctx);
1201 return TRUE;
1202 }
1203
1204 /* Generate the SKEYID_* and new IV
1205 * See draft-ietf-ipsec-ike-01.txt 4.1
1206 */
1207 static bool
1208 generate_skeyids_iv(struct state *st)
1209 {
1210 /* Generate the SKEYID */
1211 switch (st->st_oakley.auth)
1212 {
1213 case OAKLEY_PRESHARED_KEY:
1214 if (!skeyid_preshared(st))
1215 return FALSE;
1216 break;
1217
1218 case OAKLEY_RSA_SIG:
1219 if (!skeyid_digisig(st))
1220 return FALSE;
1221 break;
1222
1223 case OAKLEY_DSS_SIG:
1224 /* XXX */
1225
1226 case OAKLEY_RSA_ENC:
1227 case OAKLEY_RSA_ENC_REV:
1228 case OAKLEY_ELGAMAL_ENC:
1229 case OAKLEY_ELGAMAL_ENC_REV:
1230 /* XXX */
1231
1232 default:
1233 bad_case(st->st_oakley.auth);
1234 }
1235
1236 /* generate SKEYID_* from SKEYID */
1237 {
1238 struct hmac_ctx ctx;
1239
1240 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1241
1242 /* SKEYID_D */
1243 hmac_update_chunk(&ctx, st->st_shared);
1244 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1245 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1246 hmac_update(&ctx, "\0", 1);
1247 hmac_final_chunk(st->st_skeyid_d, "st_skeyid_d in generate_skeyids_iv()", &ctx);
1248
1249 /* SKEYID_A */
1250 hmac_reinit(&ctx);
1251 hmac_update_chunk(&ctx, st->st_skeyid_d);
1252 hmac_update_chunk(&ctx, st->st_shared);
1253 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1254 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1255 hmac_update(&ctx, "\1", 1);
1256 hmac_final_chunk(st->st_skeyid_a, "st_skeyid_a in generate_skeyids_iv()", &ctx);
1257
1258 /* SKEYID_E */
1259 hmac_reinit(&ctx);
1260 hmac_update_chunk(&ctx, st->st_skeyid_a);
1261 hmac_update_chunk(&ctx, st->st_shared);
1262 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1263 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1264 hmac_update(&ctx, "\2", 1);
1265 hmac_final_chunk(st->st_skeyid_e, "st_skeyid_e in generate_skeyids_iv()", &ctx);
1266 }
1267
1268 /* generate IV */
1269 {
1270 union hash_ctx hash_ctx;
1271 const struct hash_desc *h = st->st_oakley.hasher;
1272
1273 st->st_new_iv_len = h->hash_digest_size;
1274 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1275
1276 DBG(DBG_CRYPT,
1277 DBG_dump_chunk("DH_i:", st->st_gi);
1278 DBG_dump_chunk("DH_r:", st->st_gr);
1279 );
1280 h->hash_init(&hash_ctx);
1281 h->hash_update(&hash_ctx, st->st_gi.ptr, st->st_gi.len);
1282 h->hash_update(&hash_ctx, st->st_gr.ptr, st->st_gr.len);
1283 h->hash_final(st->st_new_iv, &hash_ctx);
1284 }
1285
1286 /* Oakley Keying Material
1287 * Derived from Skeyid_e: if it is not big enough, generate more
1288 * using the PRF.
1289 * See RFC 2409 "IKE" Appendix B
1290 */
1291 {
1292 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1293 const size_t keysize = st->st_oakley.enckeylen/BITS_PER_BYTE;
1294 u_char keytemp[MAX_OAKLEY_KEY_LEN + MAX_DIGEST_LEN];
1295 u_char *k = st->st_skeyid_e.ptr;
1296
1297 if (keysize > st->st_skeyid_e.len)
1298 {
1299 struct hmac_ctx ctx;
1300 size_t i = 0;
1301
1302 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_e);
1303 hmac_update(&ctx, "\0", 1);
1304 for (;;)
1305 {
1306 hmac_final(&keytemp[i], &ctx);
1307 i += ctx.hmac_digest_size;
1308 if (i >= keysize)
1309 break;
1310 hmac_reinit(&ctx);
1311 hmac_update(&ctx, &keytemp[i - ctx.hmac_digest_size], ctx.hmac_digest_size);
1312 }
1313 k = keytemp;
1314 }
1315 clonereplacechunk(st->st_enc_key, k, keysize, "st_enc_key");
1316 }
1317
1318 DBG(DBG_CRYPT,
1319 DBG_dump_chunk("Skeyid: ", st->st_skeyid);
1320 DBG_dump_chunk("Skeyid_d:", st->st_skeyid_d);
1321 DBG_dump_chunk("Skeyid_a:", st->st_skeyid_a);
1322 DBG_dump_chunk("Skeyid_e:", st->st_skeyid_e);
1323 DBG_dump_chunk("enc key:", st->st_enc_key);
1324 DBG_dump("IV:", st->st_new_iv, st->st_new_iv_len));
1325 return TRUE;
1326 }
1327
1328 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1329 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1330 * New Group Mode, or ISAKMP Informational Exchanges).
1331 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1332 * If hashus argument is TRUE, we're generating a hash for our end.
1333 * See RFC2409 IKE 5.
1334 *
1335 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1336 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1337 * The extensive common logic is embodied in main_mode_hash_body().
1338 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1339 */
1340
1341 typedef void (*hash_update_t)(union hash_ctx *, const u_char *, size_t) ;
1342 static void
1343 main_mode_hash_body(struct state *st
1344 , bool hashi /* Initiator? */
1345 , const pb_stream *idpl /* ID payload, as PBS */
1346 , union hash_ctx *ctx
1347 , void (*hash_update_void)(void *, const u_char *input, size_t))
1348 {
1349 #define HASH_UPDATE_T (union hash_ctx *, const u_char *input, unsigned int len)
1350 hash_update_t hash_update=(hash_update_t) hash_update_void;
1351 #if 0 /* if desperate to debug hashing */
1352 # define hash_update(ctx, input, len) { \
1353 DBG_dump("hash input", input, len); \
1354 (hash_update)(ctx, input, len); \
1355 }
1356 #endif
1357
1358 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1359
1360 if (hashi)
1361 {
1362 hash_update_chunk(ctx, st->st_gi);
1363 hash_update_chunk(ctx, st->st_gr);
1364 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1365 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1366 }
1367 else
1368 {
1369 hash_update_chunk(ctx, st->st_gr);
1370 hash_update_chunk(ctx, st->st_gi);
1371 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1372 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1373 }
1374
1375 DBG(DBG_CRYPT, DBG_log("hashing %lu bytes of SA"
1376 , (unsigned long) (st->st_p1isa.len - sizeof(struct isakmp_generic))));
1377
1378 /* SA_b */
1379 hash_update(ctx, st->st_p1isa.ptr + sizeof(struct isakmp_generic)
1380 , st->st_p1isa.len - sizeof(struct isakmp_generic));
1381
1382 /* Hash identification payload, without generic payload header.
1383 * We used to reconstruct ID Payload for this purpose, but now
1384 * we use the bytes as they appear on the wire to avoid
1385 * "spelling problems".
1386 */
1387 hash_update(ctx
1388 , idpl->start + sizeof(struct isakmp_generic)
1389 , pbs_offset(idpl) - sizeof(struct isakmp_generic));
1390
1391 # undef hash_update_chunk
1392 # undef hash_update
1393 }
1394
1395 static size_t /* length of hash */
1396 main_mode_hash(struct state *st
1397 , u_char *hash_val /* resulting bytes */
1398 , bool hashi /* Initiator? */
1399 , const pb_stream *idpl) /* ID payload, as PBS; cur must be at end */
1400 {
1401 struct hmac_ctx ctx;
1402
1403 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1404 main_mode_hash_body(st, hashi, idpl, &ctx.hash_ctx, ctx.h->hash_update);
1405 hmac_final(hash_val, &ctx);
1406 return ctx.hmac_digest_size;
1407 }
1408
1409 #if 0 /* only needed for DSS */
1410 static void
1411 main_mode_sha1(struct state *st
1412 , u_char *hash_val /* resulting bytes */
1413 , size_t *hash_len /* length of hash */
1414 , bool hashi /* Initiator? */
1415 , const pb_stream *idpl) /* ID payload, as PBS */
1416 {
1417 union hash_ctx ctx;
1418
1419 SHA1Init(&ctx.ctx_sha1);
1420 SHA1Update(&ctx.ctx_sha1, st->st_skeyid.ptr, st->st_skeyid.len);
1421 *hash_len = SHA1_DIGEST_SIZE;
1422 main_mode_hash_body(st, hashi, idpl, &ctx
1423 , (void (*)(union hash_ctx *, const u_char *, unsigned int))&SHA1Update);
1424 SHA1Final(hash_val, &ctx.ctx_sha1);
1425 }
1426 #endif
1427
1428 /* Create an RSA signature of a hash.
1429 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1430 * Use PKCS#1 version 1.5 encryption of hash (called
1431 * RSAES-PKCS1-V1_5) in PKCS#2.
1432 */
1433 static size_t
1434 RSA_sign_hash(struct connection *c
1435 , u_char sig_val[RSA_MAX_OCTETS]
1436 , const u_char *hash_val, size_t hash_len)
1437 {
1438 size_t sz = 0;
1439 smartcard_t *sc = c->spd.this.sc;
1440
1441 if (sc == NULL) /* no smartcard */
1442 {
1443 const struct RSA_private_key *k = get_RSA_private_key(c);
1444
1445 if (k == NULL)
1446 return 0; /* failure: no key to use */
1447
1448 sz = k->pub.k;
1449 passert(RSA_MIN_OCTETS <= sz && 4 + hash_len < sz && sz <= RSA_MAX_OCTETS);
1450 sign_hash(k, hash_val, hash_len, sig_val, sz);
1451 }
1452 else if (sc->valid) /* if valid pin then sign hash on the smartcard */
1453 {
1454 lock_certs_and_keys("RSA_sign_hash");
1455 if (!scx_establish_context(sc) || !scx_login(sc))
1456 {
1457 scx_release_context(sc);
1458 unlock_certs_and_keys("RSA_sign_hash");
1459 return 0;
1460 }
1461
1462 sz = scx_get_keylength(sc);
1463 if (sz == 0)
1464 {
1465 plog("failed to get keylength from smartcard");
1466 scx_release_context(sc);
1467 unlock_certs_and_keys("RSA_sign_hash");
1468 return 0;
1469 }
1470
1471 DBG(DBG_CONTROL | DBG_CRYPT,
1472 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1473 , (int)sc->slot, sc->id)
1474 )
1475 sz = scx_sign_hash(sc, hash_val, hash_len, sig_val, sz) ? sz : 0;
1476 if (!pkcs11_keep_state)
1477 scx_release_context(sc);
1478 unlock_certs_and_keys("RSA_sign_hash");
1479 }
1480 return sz;
1481 }
1482
1483 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1484 *
1485 * As a side effect, on success, the public key is copied into the
1486 * state object to record the authenticator.
1487 *
1488 * Can fail because wrong public key is used or because hash disagrees.
1489 * We distinguish because diagnostics should also.
1490 *
1491 * The result is NULL if the Signature checked out.
1492 * Otherwise, the first character of the result indicates
1493 * how far along failure occurred. A greater character signifies
1494 * greater progress.
1495 *
1496 * Classes:
1497 * 0 reserved for caller
1498 * 1 SIG length doesn't match key length -- wrong key
1499 * 2-8 malformed ECB after decryption -- probably wrong key
1500 * 9 decrypted hash != computed hash -- probably correct key
1501 *
1502 * Although the math should be the same for generating and checking signatures,
1503 * it is not: the knowledge of the private key allows more efficient (i.e.
1504 * different) computation for encryption.
1505 */
1506 static err_t
1507 try_RSA_signature(const u_char hash_val[MAX_DIGEST_LEN], size_t hash_len
1508 , const pb_stream *sig_pbs, pubkey_t *kr
1509 , struct state *st)
1510 {
1511 const u_char *sig_val = sig_pbs->cur;
1512 size_t sig_len = pbs_left(sig_pbs);
1513 u_char s[RSA_MAX_OCTETS]; /* for decrypted sig_val */
1514 u_char *hash_in_s = &s[sig_len - hash_len];
1515 const struct RSA_public_key *k = &kr->u.rsa;
1516
1517 /* decrypt the signature -- reversing RSA_sign_hash */
1518 if (sig_len != k->k)
1519 {
1520 /* XXX notification: INVALID_KEY_INFORMATION */
1521 return "1" "SIG length does not match public key length";
1522 }
1523
1524 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1525 {
1526 chunk_t temp_s;
1527 mpz_t c;
1528
1529 n_to_mpz(c, sig_val, sig_len);
1530 mpz_powm(c, c, &k->e, &k->n);
1531
1532 temp_s = mpz_to_n(c, sig_len); /* back to octets */
1533 memcpy(s, temp_s.ptr, sig_len);
1534 pfree(temp_s.ptr);
1535 mpz_clear(c);
1536 }
1537
1538 /* sanity check on signature: see if it matches
1539 * PKCS#1 v1.5 8.1 encryption-block formatting
1540 */
1541 {
1542 err_t ugh = NULL;
1543
1544 if (s[0] != 0x00)
1545 ugh = "2" "no leading 00";
1546 else if (hash_in_s[-1] != 0x00)
1547 ugh = "3" "00 separator not present";
1548 else if (s[1] == 0x01)
1549 {
1550 const u_char *p;
1551
1552 for (p = &s[2]; p != hash_in_s - 1; p++)
1553 {
1554 if (*p != 0xFF)
1555 {
1556 ugh = "4" "invalid Padding String";
1557 break;
1558 }
1559 }
1560 }
1561 else if (s[1] == 0x02)
1562 {
1563 const u_char *p;
1564
1565 for (p = &s[2]; p != hash_in_s - 1; p++)
1566 {
1567 if (*p == 0x00)
1568 {
1569 ugh = "5" "invalid Padding String";
1570 break;
1571 }
1572 }
1573 }
1574 else
1575 ugh = "6" "Block Type not 01 or 02";
1576
1577 if (ugh != NULL)
1578 {
1579 /* note: it might be a good idea to make sure that
1580 * an observer cannot tell what kind of failure happened.
1581 * I don't know what this means in practice.
1582 */
1583 /* We probably selected the wrong public key for peer:
1584 * SIG Payload decrypted into malformed ECB
1585 */
1586 /* XXX notification: INVALID_KEY_INFORMATION */
1587 return ugh;
1588 }
1589 }
1590
1591 /* We have the decoded hash: see if it matches. */
1592 if (memcmp(hash_val, hash_in_s, hash_len) != 0)
1593 {
1594 /* good: header, hash, signature, and other payloads well-formed
1595 * good: we could find an RSA Sig key for the peer.
1596 * bad: hash doesn't match
1597 * Guess: sides disagree about key to be used.
1598 */
1599 DBG_cond_dump(DBG_CRYPT, "decrypted SIG", s, sig_len);
1600 DBG_cond_dump(DBG_CRYPT, "computed HASH", hash_val, hash_len);
1601 /* XXX notification: INVALID_HASH_INFORMATION */
1602 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1603 }
1604
1605 /* Success: copy successful key into state.
1606 * There might be an old one if we previously aborted this
1607 * state transition.
1608 */
1609 unreference_key(&st->st_peer_pubkey);
1610 st->st_peer_pubkey = reference_key(kr);
1611
1612 return NULL; /* happy happy */
1613 }
1614
1615 /* Check signature against all RSA public keys we can find.
1616 * If we need keys from DNS KEY records, and they haven't been fetched,
1617 * return STF_SUSPEND to ask for asynch DNS lookup.
1618 *
1619 * Note: parameter keys_from_dns contains results of DNS lookup for key
1620 * or is NULL indicating lookup not yet tried.
1621 *
1622 * take_a_crack is a helper function. Mostly forensic.
1623 * If only we had coroutines.
1624 */
1625 struct tac_state {
1626 /* RSA_check_signature's args that take_a_crack needs */
1627 struct state *st;
1628 const u_char *hash_val;
1629 size_t hash_len;
1630 const pb_stream *sig_pbs;
1631
1632 /* state carried between calls */
1633 err_t best_ugh; /* most successful failure */
1634 int tried_cnt; /* number of keys tried */
1635 char tried[50]; /* keyids of tried public keys */
1636 char *tn; /* roof of tried[] */
1637 };
1638
1639 static bool
1640 take_a_crack(struct tac_state *s
1641 , pubkey_t *kr
1642 , const char *story USED_BY_DEBUG)
1643 {
1644 err_t ugh = try_RSA_signature(s->hash_val, s->hash_len, s->sig_pbs
1645 , kr, s->st);
1646 const struct RSA_public_key *k = &kr->u.rsa;
1647
1648 s->tried_cnt++;
1649 if (ugh == NULL)
1650 {
1651 DBG(DBG_CRYPT | DBG_CONTROL
1652 , DBG_log("an RSA Sig check passed with *%s [%s]"
1653 , k->keyid, story));
1654 return TRUE;
1655 }
1656 else
1657 {
1658 DBG(DBG_CRYPT
1659 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1660 , ugh + 1, k->keyid, story));
1661 if (s->best_ugh == NULL || s->best_ugh[0] < ugh[0])
1662 s->best_ugh = ugh;
1663 if (ugh[0] > '0'
1664 && s->tn - s->tried + KEYID_BUF + 2 < (ptrdiff_t)sizeof(s->tried))
1665 {
1666 strcpy(s->tn, " *");
1667 strcpy(s->tn + 2, k->keyid);
1668 s->tn += strlen(s->tn);
1669 }
1670 return FALSE;
1671 }
1672 }
1673
1674 static stf_status
1675 RSA_check_signature(const struct id* peer
1676 , struct state *st
1677 , const u_char hash_val[MAX_DIGEST_LEN]
1678 , size_t hash_len
1679 , const pb_stream *sig_pbs
1680 #ifdef USE_KEYRR
1681 , const pubkey_list_t *keys_from_dns
1682 #endif /* USE_KEYRR */
1683 , const struct gw_info *gateways_from_dns
1684 )
1685 {
1686 const struct connection *c = st->st_connection;
1687 struct tac_state s;
1688 err_t dns_ugh = NULL;
1689
1690 s.st = st;
1691 s.hash_val = hash_val;
1692 s.hash_len = hash_len;
1693 s.sig_pbs = sig_pbs;
1694
1695 s.best_ugh = NULL;
1696 s.tried_cnt = 0;
1697 s.tn = s.tried;
1698
1699 /* try all gateway records hung off c */
1700 if (c->policy & POLICY_OPPO)
1701 {
1702 struct gw_info *gw;
1703
1704 for (gw = c->gw_info; gw != NULL; gw = gw->next)
1705 {
1706 /* only consider entries that have a key and are for our peer */
1707 if (gw->gw_key_present
1708 && same_id(&gw->gw_id, &c->spd.that.id)
1709 && take_a_crack(&s, gw->key, "key saved from DNS TXT"))
1710 return STF_OK;
1711 }
1712 }
1713
1714 /* try all appropriate Public keys */
1715 {
1716 pubkey_list_t *p, **pp;
1717
1718 pp = &pubkeys;
1719
1720 for (p = pubkeys; p != NULL; p = *pp)
1721 {
1722 pubkey_t *key = p->key;
1723
1724 if (key->alg == PUBKEY_ALG_RSA && same_id(peer, &key->id))
1725 {
1726 time_t now = time(NULL);
1727
1728 /* check if found public key has expired */
1729 if (key->until_time != UNDEFINED_TIME && key->until_time < now)
1730 {
1731 loglog(RC_LOG_SERIOUS,
1732 "cached RSA public key has expired and has been deleted");
1733 *pp = free_public_keyentry(p);
1734 continue; /* continue with next public key */
1735 }
1736
1737 if (take_a_crack(&s, key, "preloaded key"))
1738 return STF_OK;
1739 }
1740 pp = &p->next;
1741 }
1742 }
1743
1744 /* if no key was found (evidenced by best_ugh == NULL)
1745 * and that side of connection is key_from_DNS_on_demand
1746 * then go search DNS for keys for peer.
1747 */
1748 if (s.best_ugh == NULL && c->spd.that.key_from_DNS_on_demand)
1749 {
1750 if (gateways_from_dns != NULL)
1751 {
1752 /* TXT keys */
1753 const struct gw_info *gwp;
1754
1755 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1756 if (gwp->gw_key_present
1757 && take_a_crack(&s, gwp->key, "key from DNS TXT"))
1758 return STF_OK;
1759 }
1760 #ifdef USE_KEYRR
1761 else if (keys_from_dns != NULL)
1762 {
1763 /* KEY keys */
1764 const pubkey_list_t *kr;
1765
1766 for (kr = keys_from_dns; kr != NULL; kr = kr->next)
1767 if (kr->key->alg == PUBKEY_ALG_RSA
1768 && take_a_crack(&s, kr->key, "key from DNS KEY"))
1769 return STF_OK;
1770 }
1771 #endif /* USE_KEYRR */
1772 else
1773 {
1774 /* nothing yet: ask for asynch DNS lookup */
1775 return STF_SUSPEND;
1776 }
1777 }
1778
1779 /* no acceptable key was found: diagnose */
1780 {
1781 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
1782
1783 (void) idtoa(&st->st_connection->spd.that.id, id_buf, sizeof(id_buf));
1784
1785 if (s.best_ugh == NULL)
1786 {
1787 if (dns_ugh == NULL)
1788 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1789 , id_buf);
1790 else
1791 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1792 "; DNS search for KEY failed (%s)"
1793 , id_buf, dns_ugh);
1794
1795 /* ??? is this the best code there is? */
1796 return STF_FAIL + INVALID_KEY_INFORMATION;
1797 }
1798
1799 if (s.best_ugh[0] == '9')
1800 {
1801 loglog(RC_LOG_SERIOUS, "%s", s.best_ugh + 1);
1802 /* XXX Could send notification back */
1803 return STF_FAIL + INVALID_HASH_INFORMATION;
1804 }
1805 else
1806 {
1807 if (s.tried_cnt == 1)
1808 {
1809 loglog(RC_LOG_SERIOUS
1810 , "Signature check (on %s) failed (wrong key?); tried%s"
1811 , id_buf, s.tried);
1812 DBG(DBG_CONTROL,
1813 DBG_log("public key for %s failed:"
1814 " decrypted SIG payload into a malformed ECB (%s)"
1815 , id_buf, s.best_ugh + 1));
1816 }
1817 else
1818 {
1819 loglog(RC_LOG_SERIOUS
1820 , "Signature check (on %s) failed:"
1821 " tried%s keys but none worked."
1822 , id_buf, s.tried);
1823 DBG(DBG_CONTROL,
1824 DBG_log("all %d public keys for %s failed:"
1825 " best decrypted SIG payload into a malformed ECB (%s)"
1826 , s.tried_cnt, id_buf, s.best_ugh + 1));
1827 }
1828 return STF_FAIL + INVALID_KEY_INFORMATION;
1829 }
1830 }
1831 }
1832
1833 static notification_t
1834 accept_nonce(struct msg_digest *md, chunk_t *dest, const char *name)
1835 {
1836 pb_stream *nonce_pbs = &md->chain[ISAKMP_NEXT_NONCE]->pbs;
1837 size_t len = pbs_left(nonce_pbs);
1838
1839 if (len < MINIMUM_NONCE_SIZE || MAXIMUM_NONCE_SIZE < len)
1840 {
1841 loglog(RC_LOG_SERIOUS, "%s length not between %d and %d"
1842 , name , MINIMUM_NONCE_SIZE, MAXIMUM_NONCE_SIZE);
1843 return PAYLOAD_MALFORMED; /* ??? */
1844 }
1845 clonereplacechunk(*dest, nonce_pbs->cur, len, "nonce");
1846 return NOTHING_WRONG;
1847 }
1848
1849 /* encrypt message, sans fixed part of header
1850 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1851 * The theory is that there will be no "backing out", so we commit to IV.
1852 * We also close the pbs.
1853 */
1854 bool
1855 encrypt_message(pb_stream *pbs, struct state *st)
1856 {
1857 const struct encrypt_desc *e = st->st_oakley.encrypter;
1858 u_int8_t *enc_start = pbs->start + sizeof(struct isakmp_hdr);
1859 size_t enc_len = pbs_offset(pbs) - sizeof(struct isakmp_hdr);
1860
1861 DBG_cond_dump(DBG_CRYPT | DBG_RAW, "encrypting:\n", enc_start, enc_len);
1862
1863 /* Pad up to multiple of encryption blocksize.
1864 * See the description associated with the definition of
1865 * struct isakmp_hdr in packet.h.
1866 */
1867 {
1868 size_t padding = pad_up(enc_len, e->enc_blocksize);
1869
1870 if (padding != 0)
1871 {
1872 if (!out_zero(padding, pbs, "encryption padding"))
1873 return FALSE;
1874 enc_len += padding;
1875 }
1876 }
1877
1878 DBG(DBG_CRYPT, DBG_log("encrypting using %s", enum_show(&oakley_enc_names, st->st_oakley.encrypt)));
1879
1880 /* e->crypt(TRUE, enc_start, enc_len, st); */
1881 crypto_cbc_encrypt(e, TRUE, enc_start, enc_len, st);
1882
1883 update_iv(st);
1884 DBG_cond_dump(DBG_CRYPT, "next IV:", st->st_iv, st->st_iv_len);
1885 close_message(pbs);
1886 return TRUE;
1887 }
1888
1889 /* Compute HASH(1), HASH(2) of Quick Mode.
1890 * HASH(1) is part of Quick I1 message.
1891 * HASH(2) is part of Quick R1 message.
1892 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1893 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1894 */
1895 static size_t
1896 quick_mode_hash12(u_char *dest, const u_char *start, const u_char *roof
1897 , const struct state *st, const msgid_t *msgid, bool hash2)
1898 {
1899 struct hmac_ctx ctx;
1900
1901 #if 0 /* if desperate to debug hashing */
1902 # define hmac_update(ctx, ptr, len) { \
1903 DBG_dump("hash input", (ptr), (len)); \
1904 (hmac_update)((ctx), (ptr), (len)); \
1905 }
1906 DBG_dump("hash key", st->st_skeyid_a.ptr, st->st_skeyid_a.len);
1907 #endif
1908 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
1909 hmac_update(&ctx, (const void *) msgid, sizeof(msgid_t));
1910 if (hash2)
1911 hmac_update_chunk(&ctx, st->st_ni); /* include Ni_b in the hash */
1912 hmac_update(&ctx, start, roof-start);
1913 hmac_final(dest, &ctx);
1914
1915 DBG(DBG_CRYPT,
1916 DBG_log("HASH(%d) computed:", hash2 + 1);
1917 DBG_dump("", dest, ctx.hmac_digest_size));
1918 return ctx.hmac_digest_size;
1919 # undef hmac_update
1920 }
1921
1922 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1923 * Used by: quick_inR1_outI2, quick_inI2
1924 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1925 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1926 * Message ID and Nonces. This is a mistake.
1927 */
1928 static size_t
1929 quick_mode_hash3(u_char *dest, struct state *st)
1930 {
1931 struct hmac_ctx ctx;
1932
1933 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
1934 hmac_update(&ctx, "\0", 1);
1935 hmac_update(&ctx, (u_char *) &st->st_msgid, sizeof(st->st_msgid));
1936 hmac_update_chunk(&ctx, st->st_ni);
1937 hmac_update_chunk(&ctx, st->st_nr);
1938 hmac_final(dest, &ctx);
1939 DBG_cond_dump(DBG_CRYPT, "HASH(3) computed:", dest, ctx.hmac_digest_size);
1940 return ctx.hmac_digest_size;
1941 }
1942
1943 /* Compute Phase 2 IV.
1944 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1945 */
1946 void
1947 init_phase2_iv(struct state *st, const msgid_t *msgid)
1948 {
1949 const struct hash_desc *h = st->st_oakley.hasher;
1950 union hash_ctx ctx;
1951
1952 DBG_cond_dump(DBG_CRYPT, "last Phase 1 IV:"
1953 , st->st_ph1_iv, st->st_ph1_iv_len);
1954
1955 st->st_new_iv_len = h->hash_digest_size;
1956 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1957
1958 h->hash_init(&ctx);
1959 h->hash_update(&ctx, st->st_ph1_iv, st->st_ph1_iv_len);
1960 passert(*msgid != 0);
1961 h->hash_update(&ctx, (const u_char *)msgid, sizeof(*msgid));
1962 h->hash_final(st->st_new_iv, &ctx);
1963
1964 DBG_cond_dump(DBG_CRYPT, "computed Phase 2 IV:"
1965 , st->st_new_iv, st->st_new_iv_len);
1966 }
1967
1968 /* Initiate quick mode.
1969 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1970 * (see RFC 2409 "IKE" 5.5)
1971 * Note: this is not called from demux.c
1972 */
1973
1974 static bool
1975 emit_subnet_id(ip_subnet *net
1976 , u_int8_t np, u_int8_t protoid, u_int16_t port, pb_stream *outs)
1977 {
1978 struct isakmp_ipsec_id id;
1979 pb_stream id_pbs;
1980 ip_address ta;
1981 const unsigned char *tbp;
1982 size_t tal;
1983
1984 id.isaiid_np = np;
1985 id.isaiid_idtype = subnetishost(net)
1986 ? aftoinfo(subnettypeof(net))->id_addr
1987 : aftoinfo(subnettypeof(net))->id_subnet;
1988 id.isaiid_protoid = protoid;
1989 id.isaiid_port = port;
1990
1991 if (!out_struct(&id, &isakmp_ipsec_identification_desc, outs, &id_pbs))
1992 return FALSE;
1993
1994 networkof(net, &ta);
1995 tal = addrbytesptr(&ta, &tbp);
1996 if (!out_raw(tbp, tal, &id_pbs, "client network"))
1997 return FALSE;
1998
1999 if (!subnetishost(net))
2000 {
2001 maskof(net, &ta);
2002 tal = addrbytesptr(&ta, &tbp);
2003 if (!out_raw(tbp, tal, &id_pbs, "client mask"))
2004 return FALSE;
2005 }
2006
2007 close_output_pbs(&id_pbs);
2008 return TRUE;
2009 }
2010
2011 stf_status
2012 quick_outI1(int whack_sock
2013 , struct state *isakmp_sa
2014 , struct connection *c
2015 , lset_t policy
2016 , unsigned long try
2017 , so_serial_t replacing)
2018 {
2019 struct state *st = duplicate_state(isakmp_sa);
2020 pb_stream reply; /* not really a reply */
2021 pb_stream rbody;
2022 u_char /* set by START_HASH_PAYLOAD: */
2023 *r_hashval, /* where in reply to jam hash value */
2024 *r_hash_start; /* start of what is to be hashed */
2025 bool has_client = c->spd.this.has_client || c->spd.that.has_client ||
2026 c->spd.this.protocol || c->spd.that.protocol ||
2027 c->spd.this.port || c->spd.that.port;
2028
2029 bool send_natoa = FALSE;
2030 u_int8_t np = ISAKMP_NEXT_NONE;
2031
2032 st->st_whack_sock = whack_sock;
2033 st->st_connection = c;
2034 set_cur_state(st); /* we must reset before exit */
2035 st->st_policy = policy;
2036 st->st_try = try;
2037
2038 st->st_myuserprotoid = c->spd.this.protocol;
2039 st->st_peeruserprotoid = c->spd.that.protocol;
2040 st->st_myuserport = c->spd.this.port;
2041 st->st_peeruserport = c->spd.that.port;
2042
2043 st->st_msgid = generate_msgid(isakmp_sa);
2044 st->st_state = STATE_QUICK_I1;
2045
2046 insert_state(st); /* needs cookies, connection, and msgid */
2047
2048 if (replacing == SOS_NOBODY)
2049 plog("initiating Quick Mode %s {using isakmp#%lu}"
2050 , prettypolicy(policy)
2051 , isakmp_sa->st_serialno);
2052 else
2053 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
2054 , prettypolicy(policy)
2055 , replacing
2056 , isakmp_sa->st_serialno);
2057
2058 if (isakmp_sa->nat_traversal & NAT_T_DETECTED)
2059 {
2060 /* Duplicate nat_traversal status in new state */
2061 st->nat_traversal = isakmp_sa->nat_traversal;
2062
2063 if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))
2064 has_client = TRUE;
2065
2066 nat_traversal_change_port_lookup(NULL, st);
2067 }
2068 else
2069 st->nat_traversal = 0;
2070
2071 /* are we going to send a NAT-OA payload? */
2072 if ((st->nat_traversal & NAT_T_WITH_NATOA)
2073 && !(st->st_policy & POLICY_TUNNEL)
2074 && (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)))
2075 {
2076 send_natoa = TRUE;
2077 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
2078 ISAKMP_NEXT_NATOA_RFC : ISAKMP_NEXT_NATOA_DRAFTS;
2079 }
2080
2081 /* set up reply */
2082 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
2083
2084 /* HDR* out */
2085 {
2086 struct isakmp_hdr hdr;
2087
2088 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
2089 hdr.isa_np = ISAKMP_NEXT_HASH;
2090 hdr.isa_xchg = ISAKMP_XCHG_QUICK;
2091 hdr.isa_msgid = st->st_msgid;
2092 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
2093 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
2094 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
2095 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
2096 {
2097 reset_cur_state();
2098 return STF_INTERNAL_ERROR;
2099 }
2100 }
2101
2102 /* HASH(1) -- create and note space to be filled later */
2103 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
2104
2105 /* SA out */
2106
2107 /*
2108 * See if pfs_group has been specified for this conn,
2109 * if not, fallback to old use-same-as-P1 behaviour
2110 */
2111 #ifndef NO_IKE_ALG
2112 if (st->st_connection)
2113 st->st_pfs_group = ike_alg_pfsgroup(st->st_connection, policy);
2114 if (!st->st_pfs_group)
2115 #endif
2116 /* If PFS specified, use the same group as during Phase 1:
2117 * since no negotiation is possible, we pick one that is
2118 * very likely supported.
2119 */
2120 st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
2121
2122 /* Emit SA payload based on a subset of the policy bits.
2123 * POLICY_COMPRESS is considered iff we can do IPcomp.
2124 */
2125 {
2126 lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
2127
2128 if (can_do_IPcomp)
2129 pm |= POLICY_COMPRESS;
2130
2131 if (!out_sa(&rbody
2132 , &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT]
2133 , st, FALSE, ISAKMP_NEXT_NONCE))
2134 {
2135 reset_cur_state();
2136 return STF_INTERNAL_ERROR;
2137 }
2138 }
2139
2140 /* Ni out */
2141 if (!build_and_ship_nonce(&st->st_ni, &rbody
2142 , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : np
2143 , "Ni"))
2144 {
2145 reset_cur_state();
2146 return STF_INTERNAL_ERROR;
2147 }
2148
2149 /* [ KE ] out (for PFS) */
2150
2151 if (st->st_pfs_group != NULL)
2152 {
2153 if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2154 , &rbody, has_client? ISAKMP_NEXT_ID : np))
2155 {
2156 reset_cur_state();
2157 return STF_INTERNAL_ERROR;
2158 }
2159 }
2160
2161 /* [ IDci, IDcr ] out */
2162 if (has_client)
2163 {
2164 /* IDci (we are initiator), then IDcr (peer is responder) */
2165 if (!emit_subnet_id(&c->spd.this.client
2166 , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2167 || !emit_subnet_id(&c->spd.that.client
2168 , np, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2169 {
2170 reset_cur_state();
2171 return STF_INTERNAL_ERROR;
2172 }
2173 }
2174
2175 /* Send NAT-OA if our address is NATed */
2176 if (send_natoa)
2177 {
2178 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st))
2179 {
2180 reset_cur_state();
2181 return STF_INTERNAL_ERROR;
2182 }
2183 }
2184
2185 /* finish computing HASH(1), inserting it in output */
2186 (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2187 , st, &st->st_msgid, FALSE);
2188
2189 /* encrypt message, except for fixed part of header */
2190
2191 init_phase2_iv(isakmp_sa, &st->st_msgid);
2192 st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2193 memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2194
2195 if (!encrypt_message(&rbody, st))
2196 {
2197 reset_cur_state();
2198 return STF_INTERNAL_ERROR;
2199 }
2200
2201 /* save packet, now that we know its size */
2202 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
2203 , "reply packet from quick_outI1");
2204
2205 /* send the packet */
2206
2207 send_packet(st, "quick_outI1");
2208
2209 delete_event(st);
2210 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2211
2212 if (replacing == SOS_NOBODY)
2213 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2214 , "%s: initiate"
2215 , enum_name(&state_names, st->st_state));
2216 else
2217 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2218 , "%s: initiate to replace #%lu"
2219 , enum_name(&state_names, st->st_state)
2220 , replacing);
2221 reset_cur_state();
2222 return STF_OK;
2223 }
2224
2225
2226 /*
2227 * Decode the CERT payload of Phase 1.
2228 */
2229 static void
2230 decode_cert(struct msg_digest *md)
2231 {
2232 struct payload_digest *p;
2233
2234 for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2235 {
2236 struct isakmp_cert *const cert = &p->payload.cert;
2237 chunk_t blob;
2238 time_t valid_until;
2239 blob.ptr = p->pbs.cur;
2240 blob.len = pbs_left(&p->pbs);
2241 if (cert->isacert_type == CERT_X509_SIGNATURE)
2242 {
2243 x509cert_t cert = empty_x509cert;
2244 if (parse_x509cert(blob, 0, &cert))
2245 {
2246 if (verify_x509cert(&cert, strict_crl_policy, &valid_until))
2247 {
2248 DBG(DBG_PARSING,
2249 DBG_log("Public key validated")
2250 )
2251 add_x509_public_key(&cert, valid_until, DAL_SIGNED);
2252 }
2253 else
2254 {
2255 plog("X.509 certificate rejected");
2256 }
2257 free_generalNames(cert.subjectAltName, FALSE);
2258 free_generalNames(cert.crlDistributionPoints, FALSE);
2259 }
2260 else
2261 plog("Syntax error in X.509 certificate");
2262 }
2263 else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2264 {
2265 x509cert_t *cert = NULL;
2266
2267 if (pkcs7_parse_signedData(blob, NULL, &cert, NULL, NULL))
2268 store_x509certs(&cert, strict_crl_policy);
2269 else
2270 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2271 }
2272 else
2273 {
2274 loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2275 enum_show(&cert_type_names, cert->isacert_type));
2276 DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2277 }
2278 }
2279 }
2280
2281 /*
2282 * Decode the CR payload of Phase 1.
2283 */
2284 static void
2285 decode_cr(struct msg_digest *md, struct connection *c)
2286 {
2287 struct payload_digest *p;
2288
2289 for (p = md->chain[ISAKMP_NEXT_CR]; p != NULL; p = p->next)
2290 {
2291 struct isakmp_cr *const cr = &p->payload.cr;
2292 chunk_t ca_name;
2293
2294 ca_name.len = pbs_left(&p->pbs);
2295 ca_name.ptr = (ca_name.len > 0)? p->pbs.cur : NULL;
2296
2297 DBG_cond_dump_chunk(DBG_PARSING, "CR", ca_name);
2298
2299 if (cr->isacr_type == CERT_X509_SIGNATURE)
2300 {
2301 char buf[BUF_LEN];
2302
2303 if (ca_name.len > 0)
2304 {
2305 generalName_t *gn;
2306
2307 if (!is_asn1(ca_name))
2308 continue;
2309
2310 gn = alloc_thing(generalName_t, "generalName");
2311 clonetochunk(ca_name, ca_name.ptr,ca_name.len, "ca name");
2312 gn->kind = GN_DIRECTORY_NAME;
2313 gn->name = ca_name;
2314 gn->next = c->requested_ca;
2315 c->requested_ca = gn;
2316 }
2317 c->got_certrequest = TRUE;
2318
2319 DBG(DBG_PARSING | DBG_CONTROL,
2320 dntoa_or_null(buf, BUF_LEN, ca_name, "%any");
2321 DBG_log("requested CA: '%s'", buf);
2322 )
2323 }
2324 else
2325 loglog(RC_LOG_SERIOUS, "ignoring %s certificate request payload",
2326 enum_show(&cert_type_names, cr->isacr_type));
2327 }
2328 }
2329
2330 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2331 * Note: we may change connections as a result.
2332 * We must be called before SIG or HASH are decoded since we
2333 * may change the peer's RSA key or ID.
2334 */
2335 static bool
2336 decode_peer_id(struct msg_digest *md, struct id *peer)
2337 {
2338 struct state *const st = md->st;
2339 struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2340 const pb_stream *const id_pbs = &id_pld->pbs;
2341 struct isakmp_id *const id = &id_pld->payload.id;
2342
2343 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2344 * It talks about the protocol ID and Port fields of the ID
2345 * Payload, but they don't exist as such in Phase 1.
2346 * We use more appropriate names.
2347 * isaid_doi_specific_a is in place of Protocol ID.
2348 * isaid_doi_specific_b is in place of Port.
2349 * Besides, there is no good reason for allowing these to be
2350 * other than 0 in Phase 1.
2351 */
2352 if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING)
2353 && id->isaid_doi_specific_a == IPPROTO_UDP
2354 && (id->isaid_doi_specific_b == 0 || id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))
2355 {
2356 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2357 "accepted with port_floating NAT-T",
2358 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2359 }
2360 else if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2361 && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2362 {
2363 loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2364 " but are %d/%d"
2365 , IPPROTO_UDP, IKE_UDP_PORT
2366 , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2367 return FALSE;
2368 }
2369
2370 peer->kind = id->isaid_idtype;
2371
2372 switch (peer->kind)
2373 {
2374 case ID_IPV4_ADDR:
2375 case ID_IPV6_ADDR:
2376 /* failure mode for initaddr is probably inappropriate address length */
2377 {
2378 err_t ugh = initaddr(id_pbs->cur, pbs_left(id_pbs)
2379 , peer->kind == ID_IPV4_ADDR? AF_INET : AF_INET6
2380 , &peer->ip_addr);
2381
2382 if (ugh != NULL)
2383 {
2384 loglog(RC_LOG_SERIOUS, "improper %s identification payload: %s"
2385 , enum_show(&ident_names, peer->kind), ugh);
2386 /* XXX Could send notification back */
2387 return FALSE;
2388 }
2389 }
2390 break;
2391
2392 case ID_USER_FQDN:
2393 if (memchr(id_pbs->cur, '@', pbs_left(id_pbs)) == NULL)
2394 {
2395 loglog(RC_LOG_SERIOUS, "peer's ID_USER_FQDN contains no @");
2396 return FALSE;
2397 }
2398 /* FALLTHROUGH */
2399 case ID_FQDN:
2400 if (memchr(id_pbs->cur, '\0', pbs_left(id_pbs)) != NULL)
2401 {
2402 loglog(RC_LOG_SERIOUS, "Phase 1 ID Payload of type %s contains a NUL"
2403 , enum_show(&ident_names, peer->kind));
2404 return FALSE;
2405 }
2406
2407 /* ??? ought to do some more sanity check, but what? */
2408
2409 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2410 break;
2411
2412 case ID_KEY_ID:
2413 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2414 DBG(DBG_PARSING,
2415 DBG_dump_chunk("KEY ID:", peer->name));
2416 break;
2417
2418 case ID_DER_ASN1_DN:
2419 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2420 DBG(DBG_PARSING,
2421 DBG_dump_chunk("DER ASN1 DN:", peer->name));
2422 break;
2423
2424 default:
2425 /* XXX Could send notification back */
2426 loglog(RC_LOG_SERIOUS, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2427 , enum_show(&ident_names, peer->kind));
2428 return FALSE;
2429 }
2430
2431 {
2432 char buf[BUF_LEN];
2433
2434 idtoa(peer, buf, sizeof(buf));
2435 plog("Peer ID is %s: '%s'",
2436 enum_show(&ident_names, id->isaid_idtype), buf);
2437 }
2438
2439 /* check for certificates */
2440 decode_cert(md);
2441 return TRUE;
2442 }
2443
2444 /* Now that we've decoded the ID payload, let's see if we
2445 * need to switch connections.
2446 * We must not switch horses if we initiated:
2447 * - if the initiation was explicit, we'd be ignoring user's intent
2448 * - if opportunistic, we'll lose our HOLD info
2449 */
2450 static bool
2451 switch_connection(struct msg_digest *md, struct id *peer, bool initiator)
2452 {
2453 struct state *const st = md->st;
2454 struct connection *c = st->st_connection;
2455
2456 chunk_t peer_ca = (st->st_peer_pubkey != NULL)
2457 ? st->st_peer_pubkey->issuer : empty_chunk;
2458
2459 DBG(DBG_CONTROL,
2460 char buf[BUF_LEN];
2461
2462 dntoa_or_null(buf, BUF_LEN, peer_ca, "%none");
2463 DBG_log("peer CA: '%s'", buf);
2464 )
2465
2466 if (initiator)
2467 {
2468 int pathlen;
2469
2470 if (!same_id(&c->spd.that.id, peer))
2471 {
2472 char expect[BUF_LEN]
2473 , found[BUF_LEN];
2474
2475 idtoa(&c->spd.that.id, expect, sizeof(expect));
2476 idtoa(peer, found, sizeof(found));
2477 loglog(RC_LOG_SERIOUS
2478 , "we require peer to have ID '%s', but peer declares '%s'"
2479 , expect, found);
2480 return FALSE;
2481 }
2482
2483 DBG(DBG_CONTROL,
2484 char buf[BUF_LEN];
2485
2486 dntoa_or_null(buf, BUF_LEN, c->spd.this.ca, "%none");
2487 DBG_log("required CA: '%s'", buf);
2488 )
2489
2490 if (!trusted_ca(peer_ca, c->spd.that.ca, &pathlen))
2491 {
2492 loglog(RC_LOG_SERIOUS
2493 , "we don't accept the peer's CA");
2494 return FALSE;
2495 }
2496 }
2497 else
2498 {
2499 struct connection *r;
2500
2501 /* check for certificate requests */
2502 decode_cr(md, c);
2503
2504 r = refine_host_connection(st, peer, peer_ca);
2505
2506 /* delete the collected certificate requests */
2507 free_generalNames(c->requested_ca, TRUE);
2508 c->requested_ca = NULL;
2509
2510 if (r == NULL)
2511 {
2512 char buf[BUF_LEN];
2513
2514 idtoa(peer, buf, sizeof(buf));
2515 loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%s'", buf);
2516 return FALSE;
2517 }
2518
2519 DBG(DBG_CONTROL,
2520 char buf[BUF_LEN];
2521
2522 dntoa_or_null(buf, BUF_LEN, r->spd.this.ca, "%none");
2523 DBG_log("offered CA: '%s'", buf);
2524 )
2525
2526 if (r != c)
2527 {
2528 /* apparently, r is an improvement on c -- replace */
2529
2530 DBG(DBG_CONTROL
2531 , DBG_log("switched from \"%s\" to \"%s\"", c->name, r->name));
2532 if (r->kind == CK_TEMPLATE)
2533 {
2534 /* instantiate it, filling in peer's ID */
2535 r = rw_instantiate(r, &c->spd.that.host_addr
2536 , c->spd.that.host_port, NULL, peer);
2537 }
2538
2539 /* copy certificate request info */
2540 r->got_certrequest = c->got_certrequest;
2541
2542 st->st_connection = r; /* kill reference to c */
2543 set_cur_connection(r);
2544 connection_discard(c);
2545 }
2546 else if (c->spd.that.has_id_wildcards)
2547 {
2548 free_id_content(&c->spd.that.id);
2549 c->spd.that.id = *peer;
2550 c->spd.that.has_id_wildcards = FALSE;
2551 unshare_id_content(&c->spd.that.id);
2552 }
2553 }
2554 return TRUE;
2555 }
2556
2557 /* Decode the variable part of an ID packet (during Quick Mode).
2558 * This is designed for packets that identify clients, not peers.
2559 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2560 * (1) it is wrong and (2) we use this value for inband signalling.
2561 */
2562 static bool
2563 decode_net_id(struct isakmp_ipsec_id *id
2564 , pb_stream *id_pbs
2565 , ip_subnet *net
2566 , const char *which)
2567 {
2568 const struct af_info *afi = NULL;
2569
2570 /* Note: the following may be a pointer into static memory
2571 * that may be recycled, but only if the type is not known.
2572 * That case is disposed of very early -- in the first switch.
2573 */
2574 const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2575
2576 switch (id->isaiid_idtype)
2577 {
2578 case ID_IPV4_ADDR:
2579 case ID_IPV4_ADDR_SUBNET:
2580 case ID_IPV4_ADDR_RANGE:
2581 afi = &af_inet4_info;
2582 break;
2583 case ID_IPV6_ADDR:
2584 case ID_IPV6_ADDR_SUBNET:
2585 case ID_IPV6_ADDR_RANGE:
2586 afi = &af_inet6_info;
2587 break;
2588 case ID_FQDN:
2589 return TRUE;
2590 default:
2591 /* XXX support more */
2592 loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2593 , idtypename);
2594 /* XXX Could send notification back */
2595 return FALSE;
2596 }
2597
2598 switch (id->isaiid_idtype)
2599 {
2600 case ID_IPV4_ADDR:
2601 case ID_IPV6_ADDR:
2602 {
2603 ip_address temp_address;
2604 err_t ugh;
2605
2606 ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2607
2608 if (ugh != NULL)
2609 {
2610 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2611 , which, idtypename, ugh);
2612 /* XXX Could send notification back */
2613 return FALSE;
2614 }
2615 if (isanyaddr(&temp_address))
2616 {
2617 loglog(RC_LOG_SERIOUS, "%s ID payload %s is invalid (%s) in Quick I1"
2618 , which, idtypename, ip_str(&temp_address));
2619 /* XXX Could send notification back */
2620 return FALSE;
2621 }
2622 happy(addrtosubnet(&temp_address, net));
2623 DBG(DBG_PARSING | DBG_CONTROL
2624 , DBG_log("%s is %s", which, ip_str(&temp_address)));
2625 break;
2626 }
2627
2628 case ID_IPV4_ADDR_SUBNET:
2629 case ID_IPV6_ADDR_SUBNET:
2630 {
2631 ip_address temp_address, temp_mask;
2632 err_t ugh;
2633
2634 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2635 {
2636 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2637 , which, idtypename);
2638 /* XXX Could send notification back */
2639 return FALSE;
2640 }
2641 ugh = initaddr(id_pbs->cur
2642 , afi->ia_sz, afi->af, &temp_address);
2643 if (ugh == NULL)
2644 ugh = initaddr(id_pbs->cur + afi->ia_sz
2645 , afi->ia_sz, afi->af, &temp_mask);
2646 if (ugh == NULL)
2647 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2648 , '0', net);
2649 if (ugh == NULL && subnetisnone(net))
2650 ugh = "contains only anyaddr";
2651 if (ugh != NULL)
2652 {
2653 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2654 , which, idtypename, ugh);
2655 /* XXX Could send notification back */
2656 return FALSE;
2657 }
2658 DBG(DBG_PARSING | DBG_CONTROL,
2659 {
2660 char temp_buff[SUBNETTOT_BUF];
2661
2662 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2663 DBG_log("%s is subnet %s", which, temp_buff);
2664 });
2665 break;
2666 }
2667
2668 case ID_IPV4_ADDR_RANGE:
2669 case ID_IPV6_ADDR_RANGE:
2670 {
2671 ip_address temp_address_from, temp_address_to;
2672 err_t ugh;
2673
2674 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2675 {
2676 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2677 , which, idtypename);
2678 /* XXX Could send notification back */
2679 return FALSE;
2680 }
2681 ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2682 if (ugh == NULL)
2683 ugh = initaddr(id_pbs->cur + afi->ia_sz
2684 , afi->ia_sz, afi->af, &temp_address_to);
2685 if (ugh != NULL)
2686 {
2687 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2688 , which, idtypename, ugh);
2689 /* XXX Could send notification back */
2690 return FALSE;
2691 }
2692
2693 ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2694 if (ugh == NULL && subnetisnone(net))
2695 ugh = "contains only anyaddr";
2696 if (ugh != NULL)
2697 {
2698 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2699
2700 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2701 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2702 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2703 " %s - %s unacceptable: %s"
2704 , which, idtypename, temp_buff1, temp_buff2, ugh);
2705 return FALSE;
2706 }
2707 DBG(DBG_PARSING | DBG_CONTROL,
2708 {
2709 char temp_buff[SUBNETTOT_BUF];
2710
2711 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2712 DBG_log("%s is subnet %s (received as range)"
2713 , which, temp_buff);
2714 });
2715 break;
2716 }
2717 }
2718
2719 /* set the port selector */
2720 setportof(htons(id->isaiid_port), &net->addr);
2721
2722 DBG(DBG_PARSING | DBG_CONTROL,
2723 DBG_log("%s protocol/port is %d/%d", which, id->isaiid_protoid, id->isaiid_port)
2724 )
2725
2726 return TRUE;
2727 }
2728
2729 /* like decode, but checks that what is received matches what was sent */
2730 static bool
2731
2732 check_net_id(struct isakmp_ipsec_id *id
2733 , pb_stream *id_pbs
2734 , u_int8_t *protoid
2735 , u_int16_t *port
2736 , ip_subnet *net
2737 , const char *which)
2738 {
2739 ip_subnet net_temp;
2740
2741 if (!decode_net_id(id, id_pbs, &net_temp, which))
2742 return FALSE;
2743
2744 if (!samesubnet(net, &net_temp)
2745 || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2746 {
2747 loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2748 return FALSE;
2749 }
2750 return TRUE;
2751 }
2752
2753 /*
2754 * look for the existence of a non-expiring preloaded public key
2755 */
2756 static bool
2757 has_preloaded_public_key(struct state *st)
2758 {
2759 struct connection *c = st->st_connection;
2760
2761 /* do not consider rw connections since
2762 * the peer's identity must be known
2763 */
2764 if (c->kind == CK_PERMANENT)
2765 {
2766 pubkey_list_t *p;
2767
2768 /* look for a matching RSA public key */
2769 for (p = pubkeys; p != NULL; p = p->next)
2770 {
2771 pubkey_t *key = p->key;
2772
2773 if (key->alg == PUBKEY_ALG_RSA &&
2774 same_id(&c->spd.that.id, &key->id) &&
2775 key->until_time == UNDEFINED_TIME)
2776 {
2777 /* found a preloaded public key */
2778 return TRUE;
2779 }
2780 }
2781 }
2782 return FALSE;
2783 }
2784
2785 /*
2786 * Produce the new key material of Quick Mode.
2787 * RFC 2409 "IKE" section 5.5
2788 * specifies how this is to be done.
2789 */
2790 static void
2791 compute_proto_keymat(struct state *st
2792 , u_int8_t protoid
2793 , struct ipsec_proto_info *pi)
2794 {
2795 size_t needed_len; /* bytes of keying material needed */
2796
2797 /* Add up the requirements for keying material
2798 * (It probably doesn't matter if we produce too much!)
2799 */
2800 switch (protoid)
2801 {
2802 case PROTO_IPSEC_ESP:
2803 switch (pi->attrs.transid)
2804 {
2805 case ESP_NULL:
2806 needed_len = 0;
2807 break;
2808 case ESP_DES:
2809 needed_len = DES_CBC_BLOCK_SIZE;
2810 break;
2811 case ESP_3DES:
2812 needed_len = DES_CBC_BLOCK_SIZE * 3;
2813 break;
2814 default:
2815 #ifndef NO_KERNEL_ALG
2816 if((needed_len=kernel_alg_esp_enc_keylen(pi->attrs.transid))>0) {
2817 /* XXX: check key_len "coupling with kernel.c's */
2818 if (pi->attrs.key_len) {
2819 needed_len=pi->attrs.key_len/8;
2820 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2821 "key_len=%d from peer",
2822 (int)needed_len));
2823 }
2824 break;
2825 }
2826 #endif
2827 bad_case(pi->attrs.transid);
2828 }
2829
2830 #ifndef NO_KERNEL_ALG
2831 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2832 "needed_len (after ESP enc)=%d",
2833 (int)needed_len));
2834 if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL)) {
2835 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2836 } else
2837 #endif
2838 switch (pi->attrs.auth)
2839 {
2840 case AUTH_ALGORITHM_NONE:
2841 break;
2842 case AUTH_ALGORITHM_HMAC_MD5:
2843 needed_len += HMAC_MD5_KEY_LEN;
2844 break;
2845 case AUTH_ALGORITHM_HMAC_SHA1:
2846 needed_len += HMAC_SHA1_KEY_LEN;
2847 break;
2848 case AUTH_ALGORITHM_DES_MAC:
2849 default:
2850 bad_case(pi->attrs.auth);
2851 }
2852 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2853 "needed_len (after ESP auth)=%d",
2854 (int)needed_len));
2855 break;
2856
2857 case PROTO_IPSEC_AH:
2858 switch (pi->attrs.transid)
2859 {
2860 case AH_MD5:
2861 needed_len = HMAC_MD5_KEY_LEN;
2862 break;
2863 case AH_SHA:
2864 needed_len = HMAC_SHA1_KEY_LEN;
2865 break;
2866 default:
2867 bad_case(pi->attrs.transid);
2868 }
2869 break;
2870
2871 default:
2872 bad_case(protoid);
2873 }
2874
2875 pi->keymat_len = needed_len;
2876
2877 /* Allocate space for the keying material.
2878 * Although only needed_len bytes are desired, we
2879 * must round up to a multiple of ctx.hmac_digest_size
2880 * so that our buffer isn't overrun.
2881 */
2882 {
2883 struct hmac_ctx ctx_me, ctx_peer;
2884 size_t needed_space; /* space needed for keying material (rounded up) */
2885 size_t i;
2886
2887 hmac_init_chunk(&ctx_me, st->st_oakley.hasher, st->st_skeyid_d);
2888 ctx_peer = ctx_me; /* duplicate initial conditions */
2889
2890 needed_space = needed_len + pad_up(needed_len, ctx_me.hmac_digest_size);
2891 replace(pi->our_keymat, alloc_bytes(needed_space, "keymat in compute_keymat()"));
2892 replace(pi->peer_keymat, alloc_bytes(needed_space, "peer_keymat in quick_inI1_outR1()"));
2893
2894 for (i = 0;; )
2895 {
2896 if (st->st_shared.ptr != NULL)
2897 {
2898 /* PFS: include the g^xy */
2899 hmac_update_chunk(&ctx_me, st->st_shared);
2900 hmac_update_chunk(&ctx_peer, st->st_shared);
2901 }
2902 hmac_update(&ctx_me, &protoid, sizeof(protoid));
2903 hmac_update(&ctx_peer, &protoid, sizeof(protoid));
2904
2905 hmac_update(&ctx_me, (u_char *)&pi->our_spi, sizeof(pi->our_spi));
2906 hmac_update(&ctx_peer, (u_char *)&pi->attrs.spi, sizeof(pi->attrs.spi));
2907
2908 hmac_update_chunk(&ctx_me, st->st_ni);
2909 hmac_update_chunk(&ctx_peer, st->st_ni);
2910
2911 hmac_update_chunk(&ctx_me, st->st_nr);
2912 hmac_update_chunk(&ctx_peer, st->st_nr);
2913
2914 hmac_final(pi->our_keymat + i, &ctx_me);
2915 hmac_final(pi->peer_keymat + i, &ctx_peer);
2916
2917 i += ctx_me.hmac_digest_size;
2918 if (i >= needed_space)
2919 break;
2920
2921 /* more keying material needed: prepare to go around again */
2922
2923 hmac_reinit(&ctx_me);
2924 hmac_reinit(&ctx_peer);
2925
2926 hmac_update(&ctx_me, pi->our_keymat + i - ctx_me.hmac_digest_size
2927 , ctx_me.hmac_digest_size);
2928 hmac_update(&ctx_peer, pi->peer_keymat + i - ctx_peer.hmac_digest_size
2929 , ctx_peer.hmac_digest_size);
2930 }
2931 }
2932
2933 DBG(DBG_CRYPT,
2934 DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
2935 DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
2936 }
2937
2938 static void
2939 compute_keymats(struct state *st)
2940 {
2941 if (st->st_ah.present)
2942 compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
2943 if (st->st_esp.present)
2944 compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
2945 }
2946
2947 /* State Transition Functions.
2948 *
2949 * The definition of state_microcode_table in demux.c is a good
2950 * overview of these routines.
2951 *
2952 * - Called from process_packet; result handled by complete_state_transition
2953 * - struct state_microcode member "processor" points to these
2954 * - these routine definitionss are in state order
2955 * - these routines must be restartable from any point of error return:
2956 * beware of memory allocated before any error.
2957 * - output HDR is usually emitted by process_packet (if state_microcode
2958 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2959 *
2960 * The transition functions' functions include:
2961 * - process and judge payloads
2962 * - update st_iv (result of decryption is in st_new_iv)
2963 * - build reply packet
2964 */
2965
2966 /* Handle a Main Mode Oakley first packet (responder side).
2967 * HDR;SA --> HDR;SA
2968 */
2969 stf_status
2970 main_inI1_outR1(struct msg_digest *md)
2971 {
2972 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
2973 struct state *st;
2974 struct connection *c;
2975 struct isakmp_proposal proposal;
2976 pb_stream proposal_pbs;
2977 pb_stream r_sa_pbs;
2978 u_int32_t ipsecdoisit;
2979 lset_t policy = LEMPTY;
2980 int vids_to_send = 0;
2981
2982 /* We preparse the peer's proposal in order to determine
2983 * the requested authentication policy (RSA or PSK)
2984 */
2985 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd->payload.sa
2986 , &sa_pd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
2987
2988 backup_pbs(&proposal_pbs);
2989 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2990 , proposal.isap_notrans, &policy));
2991 restore_pbs(&proposal_pbs);
2992
2993 /* We are only considering candidate connections that match
2994 * the requested authentication policy (RSA or PSK)
2995 */
2996 c = find_host_connection(&md->iface->addr, pluto_port
2997 , &md->sender, md->sender_port, policy);
2998
2999 if (c == NULL && md->iface->ike_float)
3000 {
3001 c = find_host_connection(&md->iface->addr, NAT_T_IKE_FLOAT_PORT
3002 , &md->sender, md->sender_port, policy);
3003 }
3004
3005 if (c == NULL)
3006 {
3007 /* See if a wildcarded connection can be found.
3008 * We cannot pick the right connection, so we're making a guess.
3009 * All Road Warrior connections are fair game:
3010 * we pick the first we come across (if any).
3011 * If we don't find any, we pick the first opportunistic
3012 * with the smallest subnet that includes the peer.
3013 * There is, of course, no necessary relationship between
3014 * an Initiator's address and that of its client,
3015 * but Food Groups kind of assumes one.
3016 */
3017 {
3018 struct connection *d;
3019
3020 d = find_host_connection(&md->iface->addr
3021 , pluto_port, (ip_address*)NULL, md->sender_port, policy);
3022
3023 for (; d != NULL; d = d->hp_next)
3024 {
3025 if (d->kind == CK_GROUP)
3026 {
3027 /* ignore */
3028 }
3029 else
3030 {
3031 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO))
3032 {
3033 /* must be Road Warrior: we have a winner */
3034 c = d;
3035 break;
3036 }
3037
3038 /* Opportunistic or Shunt: pick tightest match */
3039 if (addrinsubnet(&md->sender, &d->spd.that.client)
3040 && (c == NULL || !subnetinsubnet(&c->spd.that.client, &d->spd.that.client)))
3041 c = d;
3042 }
3043 }
3044 }
3045
3046 if (c == NULL)
3047 {
3048 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3049 " but no connection has been authorized%s%s"
3050 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr))
3051 , (policy != LEMPTY) ? " with policy=" : ""
3052 , (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : "");
3053 /* XXX notification is in order! */
3054 return STF_IGNORE;
3055 }
3056 else if (c->kind != CK_TEMPLATE)
3057 {
3058 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3059 " but \"%s\" forbids connection"
3060 , ip_str(&md->iface->addr), pluto_port, c->name);
3061 /* XXX notification is in order! */
3062 return STF_IGNORE;
3063 }
3064 else
3065 {
3066 /* Create a temporary connection that is a copy of this one.
3067 * His ID isn't declared yet.
3068 */
3069 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, NULL);
3070 }
3071 }
3072 else if (c->kind == CK_TEMPLATE)
3073 {
3074 /* Create an instance
3075 * This is a rare case: wildcard peer ID but static peer IP address
3076 */
3077 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, &c->spd.that.id);
3078 }
3079
3080 /* Set up state */
3081 md->st = st = new_state();
3082 st->st_connection = c;
3083 set_cur_state(st); /* (caller will reset cur_state) */
3084 st->st_try = 0; /* not our job to try again from start */
3085 st->st_policy = c->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
3086
3087 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
3088 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
3089
3090 insert_state(st); /* needs cookies, connection, and msgid (0) */
3091
3092 st->st_doi = ISAKMP_DOI_IPSEC;
3093 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
3094
3095 if ((c->kind == CK_INSTANCE) && (c->spd.that.host_port != pluto_port))
3096 {
3097 plog("responding to Main Mode from unknown peer %s:%u"
3098 , ip_str(&c->spd.that.host_addr), c->spd.that.host_port);
3099 }
3100 else if (c->kind == CK_INSTANCE)
3101 {
3102 plog("responding to Main Mode from unknown peer %s"
3103 , ip_str(&c->spd.that.host_addr));
3104 }
3105 else
3106 {
3107 plog("responding to Main Mode");
3108 }
3109
3110 /* parse_isakmp_sa also spits out a winning SA into our reply,
3111 * so we have to build our md->reply and emit HDR before calling it.
3112 */
3113
3114 /* determine how many Vendor ID payloads we will be sending */
3115 if (SEND_PLUTO_VID)
3116 vids_to_send++;
3117 if (SEND_XAUTH_VID)
3118 vids_to_send++;
3119 if (SEND_CISCO_UNITY_VID)
3120 vids_to_send++;
3121 if (md->openpgp)
3122 vids_to_send++;
3123 /* always send DPD Vendor ID */
3124 vids_to_send++;
3125 if (md->nat_traversal_vid && nat_traversal_enabled)
3126 vids_to_send++;
3127
3128 /* HDR out.
3129 * We can't leave this to comm_handle() because we must
3130 * fill in the cookie.
3131 */
3132 {
3133 struct isakmp_hdr r_hdr = md->hdr;
3134
3135 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3136 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3137 r_hdr.isa_np = ISAKMP_NEXT_SA;
3138 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3139 return STF_INTERNAL_ERROR;
3140 }
3141
3142 /* start of SA out */
3143 {
3144 struct isakmp_sa r_sa = sa_pd->payload.sa;
3145
3146 r_sa.isasa_np = vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
3147
3148 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3149 return STF_INTERNAL_ERROR;
3150 }
3151
3152 /* SA body in and out */
3153 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit, &proposal_pbs
3154 ,&proposal, &r_sa_pbs, st));
3155
3156 /* if enabled send Pluto Vendor ID */
3157 if (SEND_PLUTO_VID)
3158 {
3159 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3160 , &md->rbody, VID_STRONGSWAN))
3161 {
3162 return STF_INTERNAL_ERROR;
3163 }
3164 }
3165
3166 /* if enabled send XAUTH Vendor ID */
3167 if (SEND_XAUTH_VID)
3168 {
3169 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3170 , &md->rbody, VID_MISC_XAUTH))
3171 {
3172 return STF_INTERNAL_ERROR;
3173 }
3174 }
3175
3176 /* if enabled send Cisco Unity Vendor ID */
3177 if (SEND_CISCO_UNITY_VID)
3178 {
3179 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3180 , &md->rbody, VID_CISCO_UNITY))
3181 {
3182 return STF_INTERNAL_ERROR;
3183 }
3184 }
3185
3186 /*
3187 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3188 */
3189 if (md->openpgp)
3190 {
3191 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3192 , &md->rbody, VID_OPENPGP))
3193 {
3194 return STF_INTERNAL_ERROR;
3195 }
3196 }
3197
3198 /* Announce our ability to do Dead Peer Detection to the peer */
3199 {
3200 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3201 , &md->rbody, VID_MISC_DPD))
3202 {
3203 return STF_INTERNAL_ERROR;
3204 }
3205 }
3206
3207 if (md->nat_traversal_vid && nat_traversal_enabled)
3208 {
3209 /* reply if NAT-Traversal draft is supported */
3210 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3211
3212 if (st->nat_traversal
3213 && !out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3214 , &md->rbody, md->nat_traversal_vid))
3215 {
3216 return STF_INTERNAL_ERROR;
3217 }
3218 }
3219
3220 close_message(&md->rbody);
3221
3222 /* save initiator SA for HASH */
3223 clonereplacechunk(st->st_p1isa, sa_pd->pbs.start, pbs_room(&sa_pd->pbs), "sa in main_inI1_outR1()");
3224
3225 return STF_OK;
3226 }
3227
3228 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3229 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3230 *
3231 * The following are not yet implemented:
3232 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3233 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3234 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3235 *
3236 * We must verify that the proposal received matches one we sent.
3237 */
3238 stf_status
3239 main_inR1_outI2(struct msg_digest *md)
3240 {
3241 struct state *const st = md->st;
3242
3243 u_int8_t np = ISAKMP_NEXT_NONE;
3244
3245 /* verify echoed SA */
3246 {
3247 u_int32_t ipsecdoisit;
3248 pb_stream proposal_pbs;
3249 struct isakmp_proposal proposal;
3250 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
3251
3252 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd->payload.sa
3253 ,&sapd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
3254 if (proposal.isap_notrans != 1)
3255 {
3256 loglog(RC_LOG_SERIOUS, "a single Transform is required in a selecting Oakley Proposal; found %u"
3257 , (unsigned)proposal.isap_notrans);
3258 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX);
3259 }
3260 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3261 , &proposal_pbs, &proposal, NULL, st));
3262 }
3263
3264 if (nat_traversal_enabled && md->nat_traversal_vid)
3265 {
3266 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3267 plog("enabling possible NAT-traversal with method %s"
3268 , bitnamesof(natt_type_bitnames, st->nat_traversal));
3269 }
3270 if (st->nat_traversal & NAT_T_WITH_NATD)
3271 {
3272 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3273 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3274 }
3275
3276 /**************** build output packet HDR;KE;Ni ****************/
3277
3278 /* HDR out.
3279 * We can't leave this to comm_handle() because the isa_np
3280 * depends on the type of Auth (eventually).
3281 */
3282 echo_hdr(md, FALSE, ISAKMP_NEXT_KE);
3283
3284 /* KE out */
3285 if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group
3286 , &md->rbody, ISAKMP_NEXT_NONCE))
3287 return STF_INTERNAL_ERROR;
3288
3289 #ifdef DEBUG
3290 /* Ni out */
3291 if (!build_and_ship_nonce(&st->st_ni, &md->rbody
3292 , (cur_debugging & IMPAIR_BUST_MI2)? ISAKMP_NEXT_VID : np, "Ni"))
3293 return STF_INTERNAL_ERROR;
3294
3295 if (cur_debugging & IMPAIR_BUST_MI2)
3296 {
3297 /* generate a pointless large VID payload to push message over MTU */
3298 pb_stream vid_pbs;
3299
3300 if (!out_generic(np, &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3301 return STF_INTERNAL_ERROR;
3302 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3303 return STF_INTERNAL_ERROR;
3304 close_output_pbs(&vid_pbs);
3305 }
3306 #else
3307 /* Ni out */
3308 if (!build_and_ship_nonce(&st->st_ni, &md->rbody, np, "Ni"))
3309 return STF_INTERNAL_ERROR;
3310 #endif
3311
3312 if (st->nat_traversal & NAT_T_WITH_NATD)
3313 {
3314 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3315 return STF_INTERNAL_ERROR;
3316 }
3317
3318 /* finish message */
3319 close_message(&md->rbody);
3320
3321 /* Reinsert the state, using the responder cookie we just received */
3322 unhash_state(st);
3323 memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
3324 insert_state(st); /* needs cookies, connection, and msgid (0) */
3325
3326 return STF_OK;
3327 }
3328
3329 /* STATE_MAIN_R1:
3330 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3331 *
3332 * The following are not yet implemented:
3333 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3334 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3335 * RPKE_AUTH:
3336 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3337 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3338 */
3339 stf_status
3340 main_inI2_outR2(struct msg_digest *md)
3341 {
3342 struct state *const st = md->st;
3343 pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3344
3345 /* send CR if auth is RSA and no preloaded RSA public key exists*/
3346 bool send_cr = !no_cr_send && (st->st_oakley.auth == OAKLEY_RSA_SIG) &&
3347 !has_preloaded_public_key(st);
3348
3349 u_int8_t np = ISAKMP_NEXT_NONE;
3350
3351 /* KE in */
3352 RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
3353
3354 /* Ni in */
3355 RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
3356
3357 if (st->nat_traversal & NAT_T_WITH_NATD)
3358 {
3359 nat_traversal_natd_lookup(md);
3360
3361 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3362 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3363 }
3364 if (st->nat_traversal)
3365 {
3366 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3367 }
3368 if (st->nat_traversal & NAT_T_WITH_KA)
3369 {
3370 nat_traversal_new_ka_event();
3371 }
3372
3373 /* decode certificate requests */
3374 st->st_connection->got_certrequest = FALSE;
3375 decode_cr(md, st->st_connection);
3376
3377 /**************** build output packet HDR;KE;Nr ****************/
3378
3379 /* HDR out done */
3380
3381 /* KE out */
3382 if (!build_and_ship_KE(st, &st->st_gr, st->st_oakley.group
3383 , &md->rbody, ISAKMP_NEXT_NONCE))
3384 return STF_INTERNAL_ERROR;
3385
3386 #ifdef DEBUG
3387 /* Nr out */
3388 if (!build_and_ship_nonce(&st->st_nr, &md->rbody
3389 , (cur_debugging & IMPAIR_BUST_MR2)? ISAKMP_NEXT_VID
3390 : (send_cr? ISAKMP_NEXT_CR : np), "Nr"))
3391 return STF_INTERNAL_ERROR;
3392
3393 if (cur_debugging & IMPAIR_BUST_MR2)
3394 {
3395 /* generate a pointless large VID payload to push message over MTU */
3396 pb_stream vid_pbs;
3397
3398 if (!out_generic((send_cr)? ISAKMP_NEXT_CR : np,
3399 &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3400 return STF_INTERNAL_ERROR;
3401 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3402 return STF_INTERNAL_ERROR;
3403 close_output_pbs(&vid_pbs);
3404 }
3405 #else
3406 /* Nr out */
3407 if (!build_and_ship_nonce(&st->st_nr, &md->rbody,
3408 (send_cr)? ISAKMP_NEXT_CR : np, "Nr"))
3409 return STF_INTERNAL_ERROR;
3410 #endif
3411
3412 /* CR out */
3413 if (send_cr)
3414 {
3415 if (st->st_connection->kind == CK_PERMANENT)
3416 {
3417 if (!build_and_ship_CR(CERT_X509_SIGNATURE
3418 , st->st_connection->spd.that.ca
3419 , &md->rbody, np))
3420 return STF_INTERNAL_ERROR;
3421 }
3422 else
3423 {
3424 generalName_t *ca = NULL;
3425
3426 if (collect_rw_ca_candidates(md, &ca))
3427 {
3428 generalName_t *gn;
3429
3430 for (gn = ca; gn != NULL; gn = gn->next)
3431 {
3432 if (!build_and_ship_CR(CERT_X509_SIGNATURE, gn->name
3433 , &md->rbody
3434 , gn->next == NULL ? np : ISAKMP_NEXT_CR))
3435 return STF_INTERNAL_ERROR;
3436 }
3437 free_generalNames(ca, FALSE);
3438 }
3439 else
3440 {
3441 if (!build_and_ship_CR(CERT_X509_SIGNATURE, empty_chunk
3442 , &md->rbody, np))
3443 return STF_INTERNAL_ERROR;
3444 }
3445 }
3446 }
3447
3448 if (st->nat_traversal & NAT_T_WITH_NATD)
3449 {
3450 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3451 return STF_INTERNAL_ERROR;
3452 }
3453
3454 /* finish message */
3455 close_message(&md->rbody);
3456
3457 /* next message will be encrypted, but not this one.
3458 * We could defer this calculation.
3459 */
3460 compute_dh_shared(st, st->st_gi, st->st_oakley.group);
3461 if (!generate_skeyids_iv(st))
3462 return STF_FAIL + AUTHENTICATION_FAILED;
3463 update_iv(st);
3464
3465 return STF_OK;
3466 }
3467
3468 /* STATE_MAIN_I2:
3469 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3470 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3471 *
3472 * The following are not yet implemented.
3473 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3474 * --> HDR*, HASH_I
3475 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3476 * --> HDR*, HASH_I
3477 */
3478 stf_status
3479 main_inR2_outI3(struct msg_digest *md)
3480 {
3481 struct state *const st = md->st;
3482 pb_stream *const keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3483 int auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
3484 ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
3485 pb_stream id_pbs; /* ID Payload; also used for hash calculation */
3486
3487 certpolicy_t cert_policy = st->st_connection->spd.this.sendcert;
3488 cert_t mycert = st->st_connection->spd.this.cert;
3489 bool requested, send_cert, send_cr;
3490
3491 /* KE in */
3492 RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
3493
3494 /* Nr in */
3495 RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
3496
3497 /* decode certificate requests */
3498 st->st_connection->got_certrequest = FALSE;
3499 decode_cr(md, st->st_connection);
3500
3501 /* free collected certificate requests since as initiator
3502 * we don't heed them anyway
3503 */
3504 free_generalNames(st->st_connection->requested_ca, TRUE);
3505 st->st_connection->requested_ca = NULL;
3506
3507 /* send certificate if auth is RSA, we have one and we want
3508 * or are requested to send it
3509 */
3510 requested = cert_policy == CERT_SEND_IF_ASKED
3511 && st->st_connection->got_certrequest;
3512 send_cert = st->st_oakley.auth == OAKLEY_RSA_SIG
3513 && mycert.type != CERT_NONE
3514 && (cert_policy == CERT_ALWAYS_SEND || requested);
3515
3516 /* send certificate request if we don't have a preloaded RSA public key */
3517 send_cr = !no_cr_send && send_cert && !has_preloaded_public_key(st);
3518
3519 /* done parsing; initialize crypto */
3520
3521 compute_dh_shared(st, st->st_gr, st->st_oakley.group);
3522 if (!generate_skeyids_iv(st))
3523 return STF_FAIL + AUTHENTICATION_FAILED;
3524
3525 if (st->nat_traversal & NAT_T_WITH_NATD)
3526 {
3527 nat_traversal_natd_lookup(md);
3528 }
3529 if (st->nat_traversal)
3530 {
3531 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3532 }
3533 if (st->nat_traversal & NAT_T_WITH_KA)
3534 {
3535 nat_traversal_new_ka_event();
3536 }
3537
3538 /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3539 /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3540
3541 /* HDR* out done */
3542
3543 /* IDii out */
3544 {
3545 struct isakmp_ipsec_id id_hd;
3546 chunk_t id_b;
3547
3548 build_id_payload(&id_hd, &id_b, &st->st_connection->spd.this);
3549 id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3550 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &id_pbs)
3551 || !out_chunk(id_b, &id_pbs, "my identity"))
3552 return STF_INTERNAL_ERROR;
3553 close_output_pbs(&id_pbs);
3554 }
3555
3556 /* CERT out */
3557 if ( st->st_oakley.auth == OAKLEY_RSA_SIG)
3558 {
3559 DBG(DBG_CONTROL,
3560 DBG_log("our certificate policy is %s"
3561 , enum_name(&cert_policy_names, cert_policy))
3562 )
3563 if (mycert.type != CERT_NONE)
3564 {
3565 const char *request_text = "";
3566
3567 if (cert_policy == CERT_SEND_IF_ASKED)
3568 request_text = (send_cert)? "upon request":"without request";
3569 plog("we have a cert %s sending it %s"
3570 , send_cert? "and are":"but are not", request_text);
3571 }
3572 else
3573 {
3574 plog("we don't have a cert");
3575 }
3576 }
3577 if (send_cert)
3578 {
3579 pb_stream cert_pbs;
3580
3581 struct isakmp_cert cert_hd;
3582 cert_hd.isacert_np = (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_SIG;
3583 cert_hd.isacert_type = mycert.type;
3584
3585 if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3586 return STF_INTERNAL_ERROR;
3587 if (!out_chunk(get_mycert(mycert), &cert_pbs, "CERT"))
3588 return STF_INTERNAL_ERROR;
3589 close_output_pbs(&cert_pbs);
3590 }
3591
3592 /* CR out */
3593 if (send_cr)
3594 {
3595 if (!build_and_ship_CR(mycert.type, st->st_connection->spd.that.ca
3596 , &md->rbody, ISAKMP_NEXT_SIG))
3597 return STF_INTERNAL_ERROR;
3598 }
3599
3600 /* HASH_I or SIG_I out */
3601 {
3602 u_char hash_val[MAX_DIGEST_LEN];
3603 size_t hash_len = main_mode_hash(st, hash_val, TRUE, &id_pbs);
3604
3605 if (auth_payload == ISAKMP_NEXT_HASH)
3606 {
3607 /* HASH_I out */
3608 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
3609 , hash_val, hash_len, "HASH_I"))
3610 return STF_INTERNAL_ERROR;
3611 }
3612 else
3613 {
3614 /* SIG_I out */
3615 u_char sig_val[RSA_MAX_OCTETS];
3616 size_t sig_len = RSA_sign_hash(st->st_connection
3617 , sig_val, hash_val, hash_len);
3618
3619 if (sig_len == 0)
3620 {
3621 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
3622 return STF_FAIL + AUTHENTICATION_FAILED;
3623 }
3624
3625 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3626 , &md->rbody, sig_val, sig_len, "SIG_I"))
3627 return STF_INTERNAL_ERROR;
3628 }
3629 }
3630
3631 /* encrypt message, except for fixed part of header */
3632
3633 /* st_new_iv was computed by generate_skeyids_iv */
3634 if (!encrypt_message(&md->rbody, st))
3635 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
3636
3637 return STF_OK;
3638 }
3639
3640 /* Shared logic for asynchronous lookup of DNS KEY records.
3641 * Used for STATE_MAIN_R2 and STATE_MAIN_I3.
3642 */
3643
3644 enum key_oppo_step {
3645 kos_null,
3646 kos_his_txt
3647 #ifdef USE_KEYRR
3648 , kos_his_key
3649 #endif
3650 };
3651
3652 struct key_continuation {
3653 struct adns_continuation ac; /* common prefix */
3654 struct msg_digest *md;
3655 enum key_oppo_step step;
3656 bool failure_ok;
3657 err_t last_ugh;
3658 };
3659
3660 typedef stf_status (key_tail_fn)(struct msg_digest *md
3661 , struct key_continuation *kc);
3662 static void
3663 report_key_dns_failure(struct id *id, err_t ugh)
3664 {
3665 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
3666
3667 (void) idtoa(id, id_buf, sizeof(id_buf));
3668 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
3669 "; DNS search for KEY failed (%s)", id_buf, ugh);
3670 }
3671
3672
3673 /* Processs the Main Mode ID Payload and the Authenticator
3674 * (Hash or Signature Payload).
3675 * If a DNS query is still needed to get the other host's public key,
3676 * the query is initiated and STF_SUSPEND is returned.
3677 * Note: parameter kc is a continuation containing the results from
3678 * the previous DNS query, or NULL indicating no query has been issued.
3679 */
3680 static stf_status
3681 main_id_and_auth(struct msg_digest *md
3682 , bool initiator /* are we the Initiator? */
3683 , cont_fn_t cont_fn /* continuation function */
3684 , const struct key_continuation *kc /* current state, can be NULL */
3685 )
3686 {
3687 struct state *st = md->st;
3688 u_char hash_val[MAX_DIGEST_LEN];
3689 size_t hash_len;
3690 struct id peer;
3691 stf_status r = STF_OK;
3692
3693 /* ID Payload in */
3694 if (!decode_peer_id(md, &peer))
3695 return STF_FAIL + INVALID_ID_INFORMATION;
3696
3697 /* Hash the ID Payload.
3698 * main_mode_hash requires idpl->cur to be at end of payload
3699 * so we temporarily set if so.
3700 */
3701 {
3702 pb_stream *idpl = &md->chain[ISAKMP_NEXT_ID]->pbs;
3703 u_int8_t *old_cur = idpl->cur;
3704
3705 idpl->cur = idpl->roof;
3706 hash_len = main_mode_hash(st, hash_val, !initiator, idpl);
3707 idpl->cur = old_cur;
3708 }
3709
3710 switch (st->st_oakley.auth)
3711 {
3712 case OAKLEY_PRESHARED_KEY:
3713 {
3714 pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs;
3715
3716 if (pbs_left(hash_pbs) != hash_len
3717 || memcmp(hash_pbs->cur, hash_val, hash_len) != 0)
3718 {
3719 DBG_cond_dump(DBG_CRYPT, "received HASH:"
3720 , hash_pbs->cur, pbs_left(hash_pbs));
3721 loglog(RC_LOG_SERIOUS, "received Hash Payload does not match computed value");
3722 /* XXX Could send notification back */
3723 r = STF_FAIL + INVALID_HASH_INFORMATION;
3724 }
3725 }
3726 break;
3727
3728 case OAKLEY_RSA_SIG:
3729 r = RSA_check_signature(&peer, st, hash_val, hash_len
3730 , &md->chain[ISAKMP_NEXT_SIG]->pbs
3731 #ifdef USE_KEYRR
3732 , kc == NULL? NULL : kc->ac.keys_from_dns
3733 #endif /* USE_KEYRR */
3734 , kc == NULL? NULL : kc->ac.gateways_from_dns
3735 );
3736
3737 if (r == STF_SUSPEND)
3738 {
3739 /* initiate/resume asynchronous DNS lookup for key */
3740 struct key_continuation *nkc
3741 = alloc_thing(struct key_continuation, "key continuation");
3742 enum key_oppo_step step_done = kc == NULL? kos_null : kc->step;
3743 err_t ugh;
3744
3745 /* Record that state is used by a suspended md */
3746 passert(st->st_suspended_md == NULL);
3747 st->st_suspended_md = md;
3748
3749 nkc->failure_ok = FALSE;
3750 nkc->md = md;
3751
3752 switch (step_done)
3753 {
3754 case kos_null:
3755 /* first try: look for the TXT records */
3756 nkc->step = kos_his_txt;
3757 #ifdef USE_KEYRR
3758 nkc->failure_ok = TRUE;
3759 #endif
3760 ugh = start_adns_query(&peer
3761 , &peer /* SG itself */
3762 , T_TXT
3763 , cont_fn
3764 , &nkc->ac);
3765 break;
3766
3767 #ifdef USE_KEYRR
3768 case kos_his_txt:
3769 /* second try: look for the KEY records */
3770 nkc->step = kos_his_key;
3771 ugh = start_adns_query(&peer
3772 , NULL /* no sgw for KEY */
3773 , T_KEY
3774 , cont_fn
3775 , &nkc->ac);
3776 break;
3777 #endif /* USE_KEYRR */
3778
3779 default:
3780 bad_case(step_done);
3781 }
3782
3783 if (ugh != NULL)
3784 {
3785 report_key_dns_failure(&peer, ugh);
3786 st->st_suspended_md = NULL;
3787 r = STF_FAIL + INVALID_KEY_INFORMATION;
3788 }
3789 }
3790 break;
3791
3792 default:
3793 bad_case(st->st_oakley.auth);
3794 }
3795 if (r != STF_OK)