added XAUTH server and client support
[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, st, TRUE
954 , 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 case XAUTHInitPreShared:
1215 case XAUTHRespPreShared:
1216 if (!skeyid_preshared(st))
1217 return FALSE;
1218 break;
1219
1220 case OAKLEY_RSA_SIG:
1221 case XAUTHInitRSA:
1222 case XAUTHRespRSA:
1223 if (!skeyid_digisig(st))
1224 return FALSE;
1225 break;
1226
1227 case OAKLEY_DSS_SIG:
1228 /* XXX */
1229
1230 case OAKLEY_RSA_ENC:
1231 case OAKLEY_RSA_ENC_REV:
1232 case OAKLEY_ELGAMAL_ENC:
1233 case OAKLEY_ELGAMAL_ENC_REV:
1234 /* XXX */
1235
1236 default:
1237 bad_case(st->st_oakley.auth);
1238 }
1239
1240 /* generate SKEYID_* from SKEYID */
1241 {
1242 struct hmac_ctx ctx;
1243
1244 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1245
1246 /* SKEYID_D */
1247 hmac_update_chunk(&ctx, st->st_shared);
1248 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1249 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1250 hmac_update(&ctx, "\0", 1);
1251 hmac_final_chunk(st->st_skeyid_d, "st_skeyid_d in generate_skeyids_iv()", &ctx);
1252
1253 /* SKEYID_A */
1254 hmac_reinit(&ctx);
1255 hmac_update_chunk(&ctx, st->st_skeyid_d);
1256 hmac_update_chunk(&ctx, st->st_shared);
1257 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1258 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1259 hmac_update(&ctx, "\1", 1);
1260 hmac_final_chunk(st->st_skeyid_a, "st_skeyid_a in generate_skeyids_iv()", &ctx);
1261
1262 /* SKEYID_E */
1263 hmac_reinit(&ctx);
1264 hmac_update_chunk(&ctx, st->st_skeyid_a);
1265 hmac_update_chunk(&ctx, st->st_shared);
1266 hmac_update(&ctx, st->st_icookie, COOKIE_SIZE);
1267 hmac_update(&ctx, st->st_rcookie, COOKIE_SIZE);
1268 hmac_update(&ctx, "\2", 1);
1269 hmac_final_chunk(st->st_skeyid_e, "st_skeyid_e in generate_skeyids_iv()", &ctx);
1270 }
1271
1272 /* generate IV */
1273 {
1274 union hash_ctx hash_ctx;
1275 const struct hash_desc *h = st->st_oakley.hasher;
1276
1277 st->st_new_iv_len = h->hash_digest_size;
1278 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1279
1280 DBG(DBG_CRYPT,
1281 DBG_dump_chunk("DH_i:", st->st_gi);
1282 DBG_dump_chunk("DH_r:", st->st_gr);
1283 );
1284 h->hash_init(&hash_ctx);
1285 h->hash_update(&hash_ctx, st->st_gi.ptr, st->st_gi.len);
1286 h->hash_update(&hash_ctx, st->st_gr.ptr, st->st_gr.len);
1287 h->hash_final(st->st_new_iv, &hash_ctx);
1288 }
1289
1290 /* Oakley Keying Material
1291 * Derived from Skeyid_e: if it is not big enough, generate more
1292 * using the PRF.
1293 * See RFC 2409 "IKE" Appendix B
1294 */
1295 {
1296 /* const size_t keysize = st->st_oakley.encrypter->keydeflen/BITS_PER_BYTE; */
1297 const size_t keysize = st->st_oakley.enckeylen/BITS_PER_BYTE;
1298 u_char keytemp[MAX_OAKLEY_KEY_LEN + MAX_DIGEST_LEN];
1299 u_char *k = st->st_skeyid_e.ptr;
1300
1301 if (keysize > st->st_skeyid_e.len)
1302 {
1303 struct hmac_ctx ctx;
1304 size_t i = 0;
1305
1306 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_e);
1307 hmac_update(&ctx, "\0", 1);
1308 for (;;)
1309 {
1310 hmac_final(&keytemp[i], &ctx);
1311 i += ctx.hmac_digest_size;
1312 if (i >= keysize)
1313 break;
1314 hmac_reinit(&ctx);
1315 hmac_update(&ctx, &keytemp[i - ctx.hmac_digest_size], ctx.hmac_digest_size);
1316 }
1317 k = keytemp;
1318 }
1319 clonereplacechunk(st->st_enc_key, k, keysize, "st_enc_key");
1320 }
1321
1322 DBG(DBG_CRYPT,
1323 DBG_dump_chunk("Skeyid: ", st->st_skeyid);
1324 DBG_dump_chunk("Skeyid_d:", st->st_skeyid_d);
1325 DBG_dump_chunk("Skeyid_a:", st->st_skeyid_a);
1326 DBG_dump_chunk("Skeyid_e:", st->st_skeyid_e);
1327 DBG_dump_chunk("enc key:", st->st_enc_key);
1328 DBG_dump("IV:", st->st_new_iv, st->st_new_iv_len));
1329 return TRUE;
1330 }
1331
1332 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1333 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1334 * New Group Mode, or ISAKMP Informational Exchanges).
1335 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1336 * If hashus argument is TRUE, we're generating a hash for our end.
1337 * See RFC2409 IKE 5.
1338 *
1339 * Generating the SIG_I and SIG_R for DSS is an odd perversion of this:
1340 * Most of the logic is the same, but SHA-1 is used in place of HMAC-whatever.
1341 * The extensive common logic is embodied in main_mode_hash_body().
1342 * See draft-ietf-ipsec-ike-01.txt 4.1 and 6.1.1.2
1343 */
1344
1345 typedef void (*hash_update_t)(union hash_ctx *, const u_char *, size_t) ;
1346 static void
1347 main_mode_hash_body(struct state *st
1348 , bool hashi /* Initiator? */
1349 , const pb_stream *idpl /* ID payload, as PBS */
1350 , union hash_ctx *ctx
1351 , void (*hash_update_void)(void *, const u_char *input, size_t))
1352 {
1353 #define HASH_UPDATE_T (union hash_ctx *, const u_char *input, unsigned int len)
1354 hash_update_t hash_update=(hash_update_t) hash_update_void;
1355 #if 0 /* if desperate to debug hashing */
1356 # define hash_update(ctx, input, len) { \
1357 DBG_dump("hash input", input, len); \
1358 (hash_update)(ctx, input, len); \
1359 }
1360 #endif
1361
1362 # define hash_update_chunk(ctx, ch) hash_update((ctx), (ch).ptr, (ch).len)
1363
1364 if (hashi)
1365 {
1366 hash_update_chunk(ctx, st->st_gi);
1367 hash_update_chunk(ctx, st->st_gr);
1368 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1369 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1370 }
1371 else
1372 {
1373 hash_update_chunk(ctx, st->st_gr);
1374 hash_update_chunk(ctx, st->st_gi);
1375 hash_update(ctx, st->st_rcookie, COOKIE_SIZE);
1376 hash_update(ctx, st->st_icookie, COOKIE_SIZE);
1377 }
1378
1379 DBG(DBG_CRYPT, DBG_log("hashing %lu bytes of SA"
1380 , (unsigned long) (st->st_p1isa.len - sizeof(struct isakmp_generic))));
1381
1382 /* SA_b */
1383 hash_update(ctx, st->st_p1isa.ptr + sizeof(struct isakmp_generic)
1384 , st->st_p1isa.len - sizeof(struct isakmp_generic));
1385
1386 /* Hash identification payload, without generic payload header.
1387 * We used to reconstruct ID Payload for this purpose, but now
1388 * we use the bytes as they appear on the wire to avoid
1389 * "spelling problems".
1390 */
1391 hash_update(ctx
1392 , idpl->start + sizeof(struct isakmp_generic)
1393 , pbs_offset(idpl) - sizeof(struct isakmp_generic));
1394
1395 # undef hash_update_chunk
1396 # undef hash_update
1397 }
1398
1399 static size_t /* length of hash */
1400 main_mode_hash(struct state *st
1401 , u_char *hash_val /* resulting bytes */
1402 , bool hashi /* Initiator? */
1403 , const pb_stream *idpl) /* ID payload, as PBS; cur must be at end */
1404 {
1405 struct hmac_ctx ctx;
1406
1407 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid);
1408 main_mode_hash_body(st, hashi, idpl, &ctx.hash_ctx, ctx.h->hash_update);
1409 hmac_final(hash_val, &ctx);
1410 return ctx.hmac_digest_size;
1411 }
1412
1413 #if 0 /* only needed for DSS */
1414 static void
1415 main_mode_sha1(struct state *st
1416 , u_char *hash_val /* resulting bytes */
1417 , size_t *hash_len /* length of hash */
1418 , bool hashi /* Initiator? */
1419 , const pb_stream *idpl) /* ID payload, as PBS */
1420 {
1421 union hash_ctx ctx;
1422
1423 SHA1Init(&ctx.ctx_sha1);
1424 SHA1Update(&ctx.ctx_sha1, st->st_skeyid.ptr, st->st_skeyid.len);
1425 *hash_len = SHA1_DIGEST_SIZE;
1426 main_mode_hash_body(st, hashi, idpl, &ctx
1427 , (void (*)(union hash_ctx *, const u_char *, unsigned int))&SHA1Update);
1428 SHA1Final(hash_val, &ctx.ctx_sha1);
1429 }
1430 #endif
1431
1432 /* Create an RSA signature of a hash.
1433 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1434 * Use PKCS#1 version 1.5 encryption of hash (called
1435 * RSAES-PKCS1-V1_5) in PKCS#2.
1436 */
1437 static size_t
1438 RSA_sign_hash(struct connection *c
1439 , u_char sig_val[RSA_MAX_OCTETS]
1440 , const u_char *hash_val, size_t hash_len)
1441 {
1442 size_t sz = 0;
1443 smartcard_t *sc = c->spd.this.sc;
1444
1445 if (sc == NULL) /* no smartcard */
1446 {
1447 const struct RSA_private_key *k = get_RSA_private_key(c);
1448
1449 if (k == NULL)
1450 return 0; /* failure: no key to use */
1451
1452 sz = k->pub.k;
1453 passert(RSA_MIN_OCTETS <= sz && 4 + hash_len < sz && sz <= RSA_MAX_OCTETS);
1454 sign_hash(k, hash_val, hash_len, sig_val, sz);
1455 }
1456 else if (sc->valid) /* if valid pin then sign hash on the smartcard */
1457 {
1458 lock_certs_and_keys("RSA_sign_hash");
1459 if (!scx_establish_context(sc) || !scx_login(sc))
1460 {
1461 scx_release_context(sc);
1462 unlock_certs_and_keys("RSA_sign_hash");
1463 return 0;
1464 }
1465
1466 sz = scx_get_keylength(sc);
1467 if (sz == 0)
1468 {
1469 plog("failed to get keylength from smartcard");
1470 scx_release_context(sc);
1471 unlock_certs_and_keys("RSA_sign_hash");
1472 return 0;
1473 }
1474
1475 DBG(DBG_CONTROL | DBG_CRYPT,
1476 DBG_log("signing hash with RSA key from smartcard (slot: %d, id: %s)"
1477 , (int)sc->slot, sc->id)
1478 )
1479 sz = scx_sign_hash(sc, hash_val, hash_len, sig_val, sz) ? sz : 0;
1480 if (!pkcs11_keep_state)
1481 scx_release_context(sc);
1482 unlock_certs_and_keys("RSA_sign_hash");
1483 }
1484 return sz;
1485 }
1486
1487 /* Check a Main Mode RSA Signature against computed hash using RSA public key k.
1488 *
1489 * As a side effect, on success, the public key is copied into the
1490 * state object to record the authenticator.
1491 *
1492 * Can fail because wrong public key is used or because hash disagrees.
1493 * We distinguish because diagnostics should also.
1494 *
1495 * The result is NULL if the Signature checked out.
1496 * Otherwise, the first character of the result indicates
1497 * how far along failure occurred. A greater character signifies
1498 * greater progress.
1499 *
1500 * Classes:
1501 * 0 reserved for caller
1502 * 1 SIG length doesn't match key length -- wrong key
1503 * 2-8 malformed ECB after decryption -- probably wrong key
1504 * 9 decrypted hash != computed hash -- probably correct key
1505 *
1506 * Although the math should be the same for generating and checking signatures,
1507 * it is not: the knowledge of the private key allows more efficient (i.e.
1508 * different) computation for encryption.
1509 */
1510 static err_t
1511 try_RSA_signature(const u_char hash_val[MAX_DIGEST_LEN], size_t hash_len
1512 , const pb_stream *sig_pbs, pubkey_t *kr
1513 , struct state *st)
1514 {
1515 const u_char *sig_val = sig_pbs->cur;
1516 size_t sig_len = pbs_left(sig_pbs);
1517 u_char s[RSA_MAX_OCTETS]; /* for decrypted sig_val */
1518 u_char *hash_in_s = &s[sig_len - hash_len];
1519 const struct RSA_public_key *k = &kr->u.rsa;
1520
1521 /* decrypt the signature -- reversing RSA_sign_hash */
1522 if (sig_len != k->k)
1523 {
1524 /* XXX notification: INVALID_KEY_INFORMATION */
1525 return "1" "SIG length does not match public key length";
1526 }
1527
1528 /* actual exponentiation; see PKCS#1 v2.0 5.1 */
1529 {
1530 chunk_t temp_s;
1531 mpz_t c;
1532
1533 n_to_mpz(c, sig_val, sig_len);
1534 mpz_powm(c, c, &k->e, &k->n);
1535
1536 temp_s = mpz_to_n(c, sig_len); /* back to octets */
1537 memcpy(s, temp_s.ptr, sig_len);
1538 pfree(temp_s.ptr);
1539 mpz_clear(c);
1540 }
1541
1542 /* sanity check on signature: see if it matches
1543 * PKCS#1 v1.5 8.1 encryption-block formatting
1544 */
1545 {
1546 err_t ugh = NULL;
1547
1548 if (s[0] != 0x00)
1549 ugh = "2" "no leading 00";
1550 else if (hash_in_s[-1] != 0x00)
1551 ugh = "3" "00 separator not present";
1552 else if (s[1] == 0x01)
1553 {
1554 const u_char *p;
1555
1556 for (p = &s[2]; p != hash_in_s - 1; p++)
1557 {
1558 if (*p != 0xFF)
1559 {
1560 ugh = "4" "invalid Padding String";
1561 break;
1562 }
1563 }
1564 }
1565 else if (s[1] == 0x02)
1566 {
1567 const u_char *p;
1568
1569 for (p = &s[2]; p != hash_in_s - 1; p++)
1570 {
1571 if (*p == 0x00)
1572 {
1573 ugh = "5" "invalid Padding String";
1574 break;
1575 }
1576 }
1577 }
1578 else
1579 ugh = "6" "Block Type not 01 or 02";
1580
1581 if (ugh != NULL)
1582 {
1583 /* note: it might be a good idea to make sure that
1584 * an observer cannot tell what kind of failure happened.
1585 * I don't know what this means in practice.
1586 */
1587 /* We probably selected the wrong public key for peer:
1588 * SIG Payload decrypted into malformed ECB
1589 */
1590 /* XXX notification: INVALID_KEY_INFORMATION */
1591 return ugh;
1592 }
1593 }
1594
1595 /* We have the decoded hash: see if it matches. */
1596 if (memcmp(hash_val, hash_in_s, hash_len) != 0)
1597 {
1598 /* good: header, hash, signature, and other payloads well-formed
1599 * good: we could find an RSA Sig key for the peer.
1600 * bad: hash doesn't match
1601 * Guess: sides disagree about key to be used.
1602 */
1603 DBG_cond_dump(DBG_CRYPT, "decrypted SIG", s, sig_len);
1604 DBG_cond_dump(DBG_CRYPT, "computed HASH", hash_val, hash_len);
1605 /* XXX notification: INVALID_HASH_INFORMATION */
1606 return "9" "authentication failure: received SIG does not match computed HASH, but message is well-formed";
1607 }
1608
1609 /* Success: copy successful key into state.
1610 * There might be an old one if we previously aborted this
1611 * state transition.
1612 */
1613 unreference_key(&st->st_peer_pubkey);
1614 st->st_peer_pubkey = reference_key(kr);
1615
1616 return NULL; /* happy happy */
1617 }
1618
1619 /* Check signature against all RSA public keys we can find.
1620 * If we need keys from DNS KEY records, and they haven't been fetched,
1621 * return STF_SUSPEND to ask for asynch DNS lookup.
1622 *
1623 * Note: parameter keys_from_dns contains results of DNS lookup for key
1624 * or is NULL indicating lookup not yet tried.
1625 *
1626 * take_a_crack is a helper function. Mostly forensic.
1627 * If only we had coroutines.
1628 */
1629 struct tac_state {
1630 /* RSA_check_signature's args that take_a_crack needs */
1631 struct state *st;
1632 const u_char *hash_val;
1633 size_t hash_len;
1634 const pb_stream *sig_pbs;
1635
1636 /* state carried between calls */
1637 err_t best_ugh; /* most successful failure */
1638 int tried_cnt; /* number of keys tried */
1639 char tried[50]; /* keyids of tried public keys */
1640 char *tn; /* roof of tried[] */
1641 };
1642
1643 static bool
1644 take_a_crack(struct tac_state *s
1645 , pubkey_t *kr
1646 , const char *story USED_BY_DEBUG)
1647 {
1648 err_t ugh = try_RSA_signature(s->hash_val, s->hash_len, s->sig_pbs
1649 , kr, s->st);
1650 const struct RSA_public_key *k = &kr->u.rsa;
1651
1652 s->tried_cnt++;
1653 if (ugh == NULL)
1654 {
1655 DBG(DBG_CRYPT | DBG_CONTROL
1656 , DBG_log("an RSA Sig check passed with *%s [%s]"
1657 , k->keyid, story));
1658 return TRUE;
1659 }
1660 else
1661 {
1662 DBG(DBG_CRYPT
1663 , DBG_log("an RSA Sig check failure %s with *%s [%s]"
1664 , ugh + 1, k->keyid, story));
1665 if (s->best_ugh == NULL || s->best_ugh[0] < ugh[0])
1666 s->best_ugh = ugh;
1667 if (ugh[0] > '0'
1668 && s->tn - s->tried + KEYID_BUF + 2 < (ptrdiff_t)sizeof(s->tried))
1669 {
1670 strcpy(s->tn, " *");
1671 strcpy(s->tn + 2, k->keyid);
1672 s->tn += strlen(s->tn);
1673 }
1674 return FALSE;
1675 }
1676 }
1677
1678 static stf_status
1679 RSA_check_signature(const struct id* peer
1680 , struct state *st
1681 , const u_char hash_val[MAX_DIGEST_LEN]
1682 , size_t hash_len
1683 , const pb_stream *sig_pbs
1684 #ifdef USE_KEYRR
1685 , const pubkey_list_t *keys_from_dns
1686 #endif /* USE_KEYRR */
1687 , const struct gw_info *gateways_from_dns
1688 )
1689 {
1690 const struct connection *c = st->st_connection;
1691 struct tac_state s;
1692 err_t dns_ugh = NULL;
1693
1694 s.st = st;
1695 s.hash_val = hash_val;
1696 s.hash_len = hash_len;
1697 s.sig_pbs = sig_pbs;
1698
1699 s.best_ugh = NULL;
1700 s.tried_cnt = 0;
1701 s.tn = s.tried;
1702
1703 /* try all gateway records hung off c */
1704 if (c->policy & POLICY_OPPO)
1705 {
1706 struct gw_info *gw;
1707
1708 for (gw = c->gw_info; gw != NULL; gw = gw->next)
1709 {
1710 /* only consider entries that have a key and are for our peer */
1711 if (gw->gw_key_present
1712 && same_id(&gw->gw_id, &c->spd.that.id)
1713 && take_a_crack(&s, gw->key, "key saved from DNS TXT"))
1714 return STF_OK;
1715 }
1716 }
1717
1718 /* try all appropriate Public keys */
1719 {
1720 pubkey_list_t *p, **pp;
1721
1722 pp = &pubkeys;
1723
1724 for (p = pubkeys; p != NULL; p = *pp)
1725 {
1726 pubkey_t *key = p->key;
1727
1728 if (key->alg == PUBKEY_ALG_RSA && same_id(peer, &key->id))
1729 {
1730 time_t now = time(NULL);
1731
1732 /* check if found public key has expired */
1733 if (key->until_time != UNDEFINED_TIME && key->until_time < now)
1734 {
1735 loglog(RC_LOG_SERIOUS,
1736 "cached RSA public key has expired and has been deleted");
1737 *pp = free_public_keyentry(p);
1738 continue; /* continue with next public key */
1739 }
1740
1741 if (take_a_crack(&s, key, "preloaded key"))
1742 return STF_OK;
1743 }
1744 pp = &p->next;
1745 }
1746 }
1747
1748 /* if no key was found (evidenced by best_ugh == NULL)
1749 * and that side of connection is key_from_DNS_on_demand
1750 * then go search DNS for keys for peer.
1751 */
1752 if (s.best_ugh == NULL && c->spd.that.key_from_DNS_on_demand)
1753 {
1754 if (gateways_from_dns != NULL)
1755 {
1756 /* TXT keys */
1757 const struct gw_info *gwp;
1758
1759 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1760 if (gwp->gw_key_present
1761 && take_a_crack(&s, gwp->key, "key from DNS TXT"))
1762 return STF_OK;
1763 }
1764 #ifdef USE_KEYRR
1765 else if (keys_from_dns != NULL)
1766 {
1767 /* KEY keys */
1768 const pubkey_list_t *kr;
1769
1770 for (kr = keys_from_dns; kr != NULL; kr = kr->next)
1771 if (kr->key->alg == PUBKEY_ALG_RSA
1772 && take_a_crack(&s, kr->key, "key from DNS KEY"))
1773 return STF_OK;
1774 }
1775 #endif /* USE_KEYRR */
1776 else
1777 {
1778 /* nothing yet: ask for asynch DNS lookup */
1779 return STF_SUSPEND;
1780 }
1781 }
1782
1783 /* no acceptable key was found: diagnose */
1784 {
1785 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
1786
1787 (void) idtoa(&st->st_connection->spd.that.id, id_buf, sizeof(id_buf));
1788
1789 if (s.best_ugh == NULL)
1790 {
1791 if (dns_ugh == NULL)
1792 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1793 , id_buf);
1794 else
1795 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
1796 "; DNS search for KEY failed (%s)"
1797 , id_buf, dns_ugh);
1798
1799 /* ??? is this the best code there is? */
1800 return STF_FAIL + INVALID_KEY_INFORMATION;
1801 }
1802
1803 if (s.best_ugh[0] == '9')
1804 {
1805 loglog(RC_LOG_SERIOUS, "%s", s.best_ugh + 1);
1806 /* XXX Could send notification back */
1807 return STF_FAIL + INVALID_HASH_INFORMATION;
1808 }
1809 else
1810 {
1811 if (s.tried_cnt == 1)
1812 {
1813 loglog(RC_LOG_SERIOUS
1814 , "Signature check (on %s) failed (wrong key?); tried%s"
1815 , id_buf, s.tried);
1816 DBG(DBG_CONTROL,
1817 DBG_log("public key for %s failed:"
1818 " decrypted SIG payload into a malformed ECB (%s)"
1819 , id_buf, s.best_ugh + 1));
1820 }
1821 else
1822 {
1823 loglog(RC_LOG_SERIOUS
1824 , "Signature check (on %s) failed:"
1825 " tried%s keys but none worked."
1826 , id_buf, s.tried);
1827 DBG(DBG_CONTROL,
1828 DBG_log("all %d public keys for %s failed:"
1829 " best decrypted SIG payload into a malformed ECB (%s)"
1830 , s.tried_cnt, id_buf, s.best_ugh + 1));
1831 }
1832 return STF_FAIL + INVALID_KEY_INFORMATION;
1833 }
1834 }
1835 }
1836
1837 static notification_t
1838 accept_nonce(struct msg_digest *md, chunk_t *dest, const char *name)
1839 {
1840 pb_stream *nonce_pbs = &md->chain[ISAKMP_NEXT_NONCE]->pbs;
1841 size_t len = pbs_left(nonce_pbs);
1842
1843 if (len < MINIMUM_NONCE_SIZE || MAXIMUM_NONCE_SIZE < len)
1844 {
1845 loglog(RC_LOG_SERIOUS, "%s length not between %d and %d"
1846 , name , MINIMUM_NONCE_SIZE, MAXIMUM_NONCE_SIZE);
1847 return PAYLOAD_MALFORMED; /* ??? */
1848 }
1849 clonereplacechunk(*dest, nonce_pbs->cur, len, "nonce");
1850 return NOTHING_WRONG;
1851 }
1852
1853 /* encrypt message, sans fixed part of header
1854 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1855 * The theory is that there will be no "backing out", so we commit to IV.
1856 * We also close the pbs.
1857 */
1858 bool
1859 encrypt_message(pb_stream *pbs, struct state *st)
1860 {
1861 const struct encrypt_desc *e = st->st_oakley.encrypter;
1862 u_int8_t *enc_start = pbs->start + sizeof(struct isakmp_hdr);
1863 size_t enc_len = pbs_offset(pbs) - sizeof(struct isakmp_hdr);
1864
1865 DBG_cond_dump(DBG_CRYPT | DBG_RAW, "encrypting:\n", enc_start, enc_len);
1866
1867 /* Pad up to multiple of encryption blocksize.
1868 * See the description associated with the definition of
1869 * struct isakmp_hdr in packet.h.
1870 */
1871 {
1872 size_t padding = pad_up(enc_len, e->enc_blocksize);
1873
1874 if (padding != 0)
1875 {
1876 if (!out_zero(padding, pbs, "encryption padding"))
1877 return FALSE;
1878 enc_len += padding;
1879 }
1880 }
1881
1882 DBG(DBG_CRYPT, DBG_log("encrypting using %s", enum_show(&oakley_enc_names, st->st_oakley.encrypt)));
1883
1884 /* e->crypt(TRUE, enc_start, enc_len, st); */
1885 crypto_cbc_encrypt(e, TRUE, enc_start, enc_len, st);
1886
1887 update_iv(st);
1888 DBG_cond_dump(DBG_CRYPT, "next IV:", st->st_iv, st->st_iv_len);
1889 close_message(pbs);
1890 return TRUE;
1891 }
1892
1893 /* Compute HASH(1), HASH(2) of Quick Mode.
1894 * HASH(1) is part of Quick I1 message.
1895 * HASH(2) is part of Quick R1 message.
1896 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1897 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1898 */
1899 static size_t
1900 quick_mode_hash12(u_char *dest, const u_char *start, const u_char *roof
1901 , const struct state *st, const msgid_t *msgid, bool hash2)
1902 {
1903 struct hmac_ctx ctx;
1904
1905 #if 0 /* if desperate to debug hashing */
1906 # define hmac_update(ctx, ptr, len) { \
1907 DBG_dump("hash input", (ptr), (len)); \
1908 (hmac_update)((ctx), (ptr), (len)); \
1909 }
1910 DBG_dump("hash key", st->st_skeyid_a.ptr, st->st_skeyid_a.len);
1911 #endif
1912 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
1913 hmac_update(&ctx, (const void *) msgid, sizeof(msgid_t));
1914 if (hash2)
1915 hmac_update_chunk(&ctx, st->st_ni); /* include Ni_b in the hash */
1916 hmac_update(&ctx, start, roof-start);
1917 hmac_final(dest, &ctx);
1918
1919 DBG(DBG_CRYPT,
1920 DBG_log("HASH(%d) computed:", hash2 + 1);
1921 DBG_dump("", dest, ctx.hmac_digest_size));
1922 return ctx.hmac_digest_size;
1923 # undef hmac_update
1924 }
1925
1926 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1927 * Used by: quick_inR1_outI2, quick_inI2
1928 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1929 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1930 * Message ID and Nonces. This is a mistake.
1931 */
1932 static size_t
1933 quick_mode_hash3(u_char *dest, struct state *st)
1934 {
1935 struct hmac_ctx ctx;
1936
1937 hmac_init_chunk(&ctx, st->st_oakley.hasher, st->st_skeyid_a);
1938 hmac_update(&ctx, "\0", 1);
1939 hmac_update(&ctx, (u_char *) &st->st_msgid, sizeof(st->st_msgid));
1940 hmac_update_chunk(&ctx, st->st_ni);
1941 hmac_update_chunk(&ctx, st->st_nr);
1942 hmac_final(dest, &ctx);
1943 DBG_cond_dump(DBG_CRYPT, "HASH(3) computed:", dest, ctx.hmac_digest_size);
1944 return ctx.hmac_digest_size;
1945 }
1946
1947 /* Compute Phase 2 IV.
1948 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1949 */
1950 void
1951 init_phase2_iv(struct state *st, const msgid_t *msgid)
1952 {
1953 const struct hash_desc *h = st->st_oakley.hasher;
1954 union hash_ctx ctx;
1955
1956 DBG_cond_dump(DBG_CRYPT, "last Phase 1 IV:"
1957 , st->st_ph1_iv, st->st_ph1_iv_len);
1958
1959 st->st_new_iv_len = h->hash_digest_size;
1960 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1961
1962 h->hash_init(&ctx);
1963 h->hash_update(&ctx, st->st_ph1_iv, st->st_ph1_iv_len);
1964 passert(*msgid != 0);
1965 h->hash_update(&ctx, (const u_char *)msgid, sizeof(*msgid));
1966 h->hash_final(st->st_new_iv, &ctx);
1967
1968 DBG_cond_dump(DBG_CRYPT, "computed Phase 2 IV:"
1969 , st->st_new_iv, st->st_new_iv_len);
1970 }
1971
1972 /* Initiate quick mode.
1973 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1974 * (see RFC 2409 "IKE" 5.5)
1975 * Note: this is not called from demux.c
1976 */
1977
1978 static bool
1979 emit_subnet_id(ip_subnet *net
1980 , u_int8_t np, u_int8_t protoid, u_int16_t port, pb_stream *outs)
1981 {
1982 struct isakmp_ipsec_id id;
1983 pb_stream id_pbs;
1984 ip_address ta;
1985 const unsigned char *tbp;
1986 size_t tal;
1987
1988 id.isaiid_np = np;
1989 id.isaiid_idtype = subnetishost(net)
1990 ? aftoinfo(subnettypeof(net))->id_addr
1991 : aftoinfo(subnettypeof(net))->id_subnet;
1992 id.isaiid_protoid = protoid;
1993 id.isaiid_port = port;
1994
1995 if (!out_struct(&id, &isakmp_ipsec_identification_desc, outs, &id_pbs))
1996 return FALSE;
1997
1998 networkof(net, &ta);
1999 tal = addrbytesptr(&ta, &tbp);
2000 if (!out_raw(tbp, tal, &id_pbs, "client network"))
2001 return FALSE;
2002
2003 if (!subnetishost(net))
2004 {
2005 maskof(net, &ta);
2006 tal = addrbytesptr(&ta, &tbp);
2007 if (!out_raw(tbp, tal, &id_pbs, "client mask"))
2008 return FALSE;
2009 }
2010
2011 close_output_pbs(&id_pbs);
2012 return TRUE;
2013 }
2014
2015 stf_status
2016 quick_outI1(int whack_sock
2017 , struct state *isakmp_sa
2018 , struct connection *c
2019 , lset_t policy
2020 , unsigned long try
2021 , so_serial_t replacing)
2022 {
2023 struct state *st = duplicate_state(isakmp_sa);
2024 pb_stream reply; /* not really a reply */
2025 pb_stream rbody;
2026 u_char /* set by START_HASH_PAYLOAD: */
2027 *r_hashval, /* where in reply to jam hash value */
2028 *r_hash_start; /* start of what is to be hashed */
2029 bool has_client = c->spd.this.has_client || c->spd.that.has_client ||
2030 c->spd.this.protocol || c->spd.that.protocol ||
2031 c->spd.this.port || c->spd.that.port;
2032
2033 bool send_natoa = FALSE;
2034 u_int8_t np = ISAKMP_NEXT_NONE;
2035
2036 st->st_whack_sock = whack_sock;
2037 st->st_connection = c;
2038 set_cur_state(st); /* we must reset before exit */
2039 st->st_policy = policy;
2040 st->st_try = try;
2041
2042 st->st_myuserprotoid = c->spd.this.protocol;
2043 st->st_peeruserprotoid = c->spd.that.protocol;
2044 st->st_myuserport = c->spd.this.port;
2045 st->st_peeruserport = c->spd.that.port;
2046
2047 st->st_msgid = generate_msgid(isakmp_sa);
2048 st->st_state = STATE_QUICK_I1;
2049
2050 insert_state(st); /* needs cookies, connection, and msgid */
2051
2052 if (replacing == SOS_NOBODY)
2053 plog("initiating Quick Mode %s {using isakmp#%lu}"
2054 , prettypolicy(policy)
2055 , isakmp_sa->st_serialno);
2056 else
2057 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
2058 , prettypolicy(policy)
2059 , replacing
2060 , isakmp_sa->st_serialno);
2061
2062 if (isakmp_sa->nat_traversal & NAT_T_DETECTED)
2063 {
2064 /* Duplicate nat_traversal status in new state */
2065 st->nat_traversal = isakmp_sa->nat_traversal;
2066
2067 if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))
2068 has_client = TRUE;
2069
2070 nat_traversal_change_port_lookup(NULL, st);
2071 }
2072 else
2073 st->nat_traversal = 0;
2074
2075 /* are we going to send a NAT-OA payload? */
2076 if ((st->nat_traversal & NAT_T_WITH_NATOA)
2077 && !(st->st_policy & POLICY_TUNNEL)
2078 && (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)))
2079 {
2080 send_natoa = TRUE;
2081 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
2082 ISAKMP_NEXT_NATOA_RFC : ISAKMP_NEXT_NATOA_DRAFTS;
2083 }
2084
2085 /* set up reply */
2086 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
2087
2088 /* HDR* out */
2089 {
2090 struct isakmp_hdr hdr;
2091
2092 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
2093 hdr.isa_np = ISAKMP_NEXT_HASH;
2094 hdr.isa_xchg = ISAKMP_XCHG_QUICK;
2095 hdr.isa_msgid = st->st_msgid;
2096 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
2097 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
2098 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
2099 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
2100 {
2101 reset_cur_state();
2102 return STF_INTERNAL_ERROR;
2103 }
2104 }
2105
2106 /* HASH(1) -- create and note space to be filled later */
2107 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
2108
2109 /* SA out */
2110
2111 /*
2112 * See if pfs_group has been specified for this conn,
2113 * if not, fallback to old use-same-as-P1 behaviour
2114 */
2115 #ifndef NO_IKE_ALG
2116 if (st->st_connection)
2117 st->st_pfs_group = ike_alg_pfsgroup(st->st_connection, policy);
2118 if (!st->st_pfs_group)
2119 #endif
2120 /* If PFS specified, use the same group as during Phase 1:
2121 * since no negotiation is possible, we pick one that is
2122 * very likely supported.
2123 */
2124 st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
2125
2126 /* Emit SA payload based on a subset of the policy bits.
2127 * POLICY_COMPRESS is considered iff we can do IPcomp.
2128 */
2129 {
2130 lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
2131
2132 if (can_do_IPcomp)
2133 pm |= POLICY_COMPRESS;
2134
2135 if (!out_sa(&rbody
2136 , &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT]
2137 , st, FALSE, ISAKMP_NEXT_NONCE))
2138 {
2139 reset_cur_state();
2140 return STF_INTERNAL_ERROR;
2141 }
2142 }
2143
2144 /* Ni out */
2145 if (!build_and_ship_nonce(&st->st_ni, &rbody
2146 , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : np
2147 , "Ni"))
2148 {
2149 reset_cur_state();
2150 return STF_INTERNAL_ERROR;
2151 }
2152
2153 /* [ KE ] out (for PFS) */
2154
2155 if (st->st_pfs_group != NULL)
2156 {
2157 if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2158 , &rbody, has_client? ISAKMP_NEXT_ID : np))
2159 {
2160 reset_cur_state();
2161 return STF_INTERNAL_ERROR;
2162 }
2163 }
2164
2165 /* [ IDci, IDcr ] out */
2166 if (has_client)
2167 {
2168 /* IDci (we are initiator), then IDcr (peer is responder) */
2169 if (!emit_subnet_id(&c->spd.this.client
2170 , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2171 || !emit_subnet_id(&c->spd.that.client
2172 , np, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2173 {
2174 reset_cur_state();
2175 return STF_INTERNAL_ERROR;
2176 }
2177 }
2178
2179 /* Send NAT-OA if our address is NATed */
2180 if (send_natoa)
2181 {
2182 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st))
2183 {
2184 reset_cur_state();
2185 return STF_INTERNAL_ERROR;
2186 }
2187 }
2188
2189 /* finish computing HASH(1), inserting it in output */
2190 (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2191 , st, &st->st_msgid, FALSE);
2192
2193 /* encrypt message, except for fixed part of header */
2194
2195 init_phase2_iv(isakmp_sa, &st->st_msgid);
2196 st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2197 memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2198
2199 if (!encrypt_message(&rbody, st))
2200 {
2201 reset_cur_state();
2202 return STF_INTERNAL_ERROR;
2203 }
2204
2205 /* save packet, now that we know its size */
2206 clonetochunk(st->st_tpacket, reply.start, pbs_offset(&reply)
2207 , "reply packet from quick_outI1");
2208
2209 /* send the packet */
2210
2211 send_packet(st, "quick_outI1");
2212
2213 delete_event(st);
2214 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2215
2216 if (replacing == SOS_NOBODY)
2217 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2218 , "%s: initiate"
2219 , enum_name(&state_names, st->st_state));
2220 else
2221 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2222 , "%s: initiate to replace #%lu"
2223 , enum_name(&state_names, st->st_state)
2224 , replacing);
2225 reset_cur_state();
2226 return STF_OK;
2227 }
2228
2229
2230 /*
2231 * Decode the CERT payload of Phase 1.
2232 */
2233 static void
2234 decode_cert(struct msg_digest *md)
2235 {
2236 struct payload_digest *p;
2237
2238 for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2239 {
2240 struct isakmp_cert *const cert = &p->payload.cert;
2241 chunk_t blob;
2242 time_t valid_until;
2243 blob.ptr = p->pbs.cur;
2244 blob.len = pbs_left(&p->pbs);
2245 if (cert->isacert_type == CERT_X509_SIGNATURE)
2246 {
2247 x509cert_t cert = empty_x509cert;
2248 if (parse_x509cert(blob, 0, &cert))
2249 {
2250 if (verify_x509cert(&cert, strict_crl_policy, &valid_until))
2251 {
2252 DBG(DBG_PARSING,
2253 DBG_log("Public key validated")
2254 )
2255 add_x509_public_key(&cert, valid_until, DAL_SIGNED);
2256 }
2257 else
2258 {
2259 plog("X.509 certificate rejected");
2260 }
2261 free_generalNames(cert.subjectAltName, FALSE);
2262 free_generalNames(cert.crlDistributionPoints, FALSE);
2263 }
2264 else
2265 plog("Syntax error in X.509 certificate");
2266 }
2267 else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2268 {
2269 x509cert_t *cert = NULL;
2270
2271 if (pkcs7_parse_signedData(blob, NULL, &cert, NULL, NULL))
2272 store_x509certs(&cert, strict_crl_policy);
2273 else
2274 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2275 }
2276 else
2277 {
2278 loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2279 enum_show(&cert_type_names, cert->isacert_type));
2280 DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2281 }
2282 }
2283 }
2284
2285 /*
2286 * Decode the CR payload of Phase 1.
2287 */
2288 static void
2289 decode_cr(struct msg_digest *md, struct connection *c)
2290 {
2291 struct payload_digest *p;
2292
2293 for (p = md->chain[ISAKMP_NEXT_CR]; p != NULL; p = p->next)
2294 {
2295 struct isakmp_cr *const cr = &p->payload.cr;
2296 chunk_t ca_name;
2297
2298 ca_name.len = pbs_left(&p->pbs);
2299 ca_name.ptr = (ca_name.len > 0)? p->pbs.cur : NULL;
2300
2301 DBG_cond_dump_chunk(DBG_PARSING, "CR", ca_name);
2302
2303 if (cr->isacr_type == CERT_X509_SIGNATURE)
2304 {
2305 char buf[BUF_LEN];
2306
2307 if (ca_name.len > 0)
2308 {
2309 generalName_t *gn;
2310
2311 if (!is_asn1(ca_name))
2312 continue;
2313
2314 gn = alloc_thing(generalName_t, "generalName");
2315 clonetochunk(ca_name, ca_name.ptr,ca_name.len, "ca name");
2316 gn->kind = GN_DIRECTORY_NAME;
2317 gn->name = ca_name;
2318 gn->next = c->requested_ca;
2319 c->requested_ca = gn;
2320 }
2321 c->got_certrequest = TRUE;
2322
2323 DBG(DBG_PARSING | DBG_CONTROL,
2324 dntoa_or_null(buf, BUF_LEN, ca_name, "%any");
2325 DBG_log("requested CA: '%s'", buf);
2326 )
2327 }
2328 else
2329 loglog(RC_LOG_SERIOUS, "ignoring %s certificate request payload",
2330 enum_show(&cert_type_names, cr->isacr_type));
2331 }
2332 }
2333
2334 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2335 * Note: we may change connections as a result.
2336 * We must be called before SIG or HASH are decoded since we
2337 * may change the peer's RSA key or ID.
2338 */
2339 static bool
2340 decode_peer_id(struct msg_digest *md, struct id *peer)
2341 {
2342 struct state *const st = md->st;
2343 struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2344 const pb_stream *const id_pbs = &id_pld->pbs;
2345 struct isakmp_id *const id = &id_pld->payload.id;
2346
2347 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2348 * It talks about the protocol ID and Port fields of the ID
2349 * Payload, but they don't exist as such in Phase 1.
2350 * We use more appropriate names.
2351 * isaid_doi_specific_a is in place of Protocol ID.
2352 * isaid_doi_specific_b is in place of Port.
2353 * Besides, there is no good reason for allowing these to be
2354 * other than 0 in Phase 1.
2355 */
2356 if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING)
2357 && id->isaid_doi_specific_a == IPPROTO_UDP
2358 && (id->isaid_doi_specific_b == 0 || id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))
2359 {
2360 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2361 "accepted with port_floating NAT-T",
2362 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2363 }
2364 else if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2365 && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2366 {
2367 loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2368 " but are %d/%d"
2369 , IPPROTO_UDP, IKE_UDP_PORT
2370 , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2371 return FALSE;
2372 }
2373
2374 peer->kind = id->isaid_idtype;
2375
2376 switch (peer->kind)
2377 {
2378 case ID_IPV4_ADDR:
2379 case ID_IPV6_ADDR:
2380 /* failure mode for initaddr is probably inappropriate address length */
2381 {
2382 err_t ugh = initaddr(id_pbs->cur, pbs_left(id_pbs)
2383 , peer->kind == ID_IPV4_ADDR? AF_INET : AF_INET6
2384 , &peer->ip_addr);
2385
2386 if (ugh != NULL)
2387 {
2388 loglog(RC_LOG_SERIOUS, "improper %s identification payload: %s"
2389 , enum_show(&ident_names, peer->kind), ugh);
2390 /* XXX Could send notification back */
2391 return FALSE;
2392 }
2393 }
2394 break;
2395
2396 case ID_USER_FQDN:
2397 if (memchr(id_pbs->cur, '@', pbs_left(id_pbs)) == NULL)
2398 {
2399 loglog(RC_LOG_SERIOUS, "peer's ID_USER_FQDN contains no @");
2400 return FALSE;
2401 }
2402 /* FALLTHROUGH */
2403 case ID_FQDN:
2404 if (memchr(id_pbs->cur, '\0', pbs_left(id_pbs)) != NULL)
2405 {
2406 loglog(RC_LOG_SERIOUS, "Phase 1 ID Payload of type %s contains a NUL"
2407 , enum_show(&ident_names, peer->kind));
2408 return FALSE;
2409 }
2410
2411 /* ??? ought to do some more sanity check, but what? */
2412
2413 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2414 break;
2415
2416 case ID_KEY_ID:
2417 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2418 DBG(DBG_PARSING,
2419 DBG_dump_chunk("KEY ID:", peer->name));
2420 break;
2421
2422 case ID_DER_ASN1_DN:
2423 setchunk(peer->name, id_pbs->cur, pbs_left(id_pbs));
2424 DBG(DBG_PARSING,
2425 DBG_dump_chunk("DER ASN1 DN:", peer->name));
2426 break;
2427
2428 default:
2429 /* XXX Could send notification back */
2430 loglog(RC_LOG_SERIOUS, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2431 , enum_show(&ident_names, peer->kind));
2432 return FALSE;
2433 }
2434
2435 {
2436 char buf[BUF_LEN];
2437
2438 idtoa(peer, buf, sizeof(buf));
2439 plog("Peer ID is %s: '%s'",
2440 enum_show(&ident_names, id->isaid_idtype), buf);
2441 }
2442
2443 /* check for certificates */
2444 decode_cert(md);
2445 return TRUE;
2446 }
2447
2448 /* Now that we've decoded the ID payload, let's see if we
2449 * need to switch connections.
2450 * We must not switch horses if we initiated:
2451 * - if the initiation was explicit, we'd be ignoring user's intent
2452 * - if opportunistic, we'll lose our HOLD info
2453 */
2454 static bool
2455 switch_connection(struct msg_digest *md, struct id *peer, bool initiator)
2456 {
2457 struct state *const st = md->st;
2458 struct connection *c = st->st_connection;
2459
2460 chunk_t peer_ca = (st->st_peer_pubkey != NULL)
2461 ? st->st_peer_pubkey->issuer : empty_chunk;
2462
2463 DBG(DBG_CONTROL,
2464 char buf[BUF_LEN];
2465
2466 dntoa_or_null(buf, BUF_LEN, peer_ca, "%none");
2467 DBG_log("peer CA: '%s'", buf);
2468 )
2469
2470 if (initiator)
2471 {
2472 int pathlen;
2473
2474 if (!same_id(&c->spd.that.id, peer))
2475 {
2476 char expect[BUF_LEN]
2477 , found[BUF_LEN];
2478
2479 idtoa(&c->spd.that.id, expect, sizeof(expect));
2480 idtoa(peer, found, sizeof(found));
2481 loglog(RC_LOG_SERIOUS
2482 , "we require peer to have ID '%s', but peer declares '%s'"
2483 , expect, found);
2484 return FALSE;
2485 }
2486
2487 DBG(DBG_CONTROL,
2488 char buf[BUF_LEN];
2489
2490 dntoa_or_null(buf, BUF_LEN, c->spd.this.ca, "%none");
2491 DBG_log("required CA: '%s'", buf);
2492 )
2493
2494 if (!trusted_ca(peer_ca, c->spd.that.ca, &pathlen))
2495 {
2496 loglog(RC_LOG_SERIOUS
2497 , "we don't accept the peer's CA");
2498 return FALSE;
2499 }
2500 }
2501 else
2502 {
2503 struct connection *r;
2504
2505 /* check for certificate requests */
2506 decode_cr(md, c);
2507
2508 r = refine_host_connection(st, peer, peer_ca);
2509
2510 /* delete the collected certificate requests */
2511 free_generalNames(c->requested_ca, TRUE);
2512 c->requested_ca = NULL;
2513
2514 if (r == NULL)
2515 {
2516 char buf[BUF_LEN];
2517
2518 idtoa(peer, buf, sizeof(buf));
2519 loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%s'", buf);
2520 return FALSE;
2521 }
2522
2523 DBG(DBG_CONTROL,
2524 char buf[BUF_LEN];
2525
2526 dntoa_or_null(buf, BUF_LEN, r->spd.this.ca, "%none");
2527 DBG_log("offered CA: '%s'", buf);
2528 )
2529
2530 if (r != c)
2531 {
2532 /* apparently, r is an improvement on c -- replace */
2533
2534 DBG(DBG_CONTROL
2535 , DBG_log("switched from \"%s\" to \"%s\"", c->name, r->name));
2536 if (r->kind == CK_TEMPLATE)
2537 {
2538 /* instantiate it, filling in peer's ID */
2539 r = rw_instantiate(r, &c->spd.that.host_addr
2540 , c->spd.that.host_port, NULL, peer);
2541 }
2542
2543 /* copy certificate request info */
2544 r->got_certrequest = c->got_certrequest;
2545
2546 st->st_connection = r; /* kill reference to c */
2547 set_cur_connection(r);
2548 connection_discard(c);
2549 }
2550 else if (c->spd.that.has_id_wildcards)
2551 {
2552 free_id_content(&c->spd.that.id);
2553 c->spd.that.id = *peer;
2554 c->spd.that.has_id_wildcards = FALSE;
2555 unshare_id_content(&c->spd.that.id);
2556 }
2557 }
2558 return TRUE;
2559 }
2560
2561 /* Decode the variable part of an ID packet (during Quick Mode).
2562 * This is designed for packets that identify clients, not peers.
2563 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2564 * (1) it is wrong and (2) we use this value for inband signalling.
2565 */
2566 static bool
2567 decode_net_id(struct isakmp_ipsec_id *id
2568 , pb_stream *id_pbs
2569 , ip_subnet *net
2570 , const char *which)
2571 {
2572 const struct af_info *afi = NULL;
2573
2574 /* Note: the following may be a pointer into static memory
2575 * that may be recycled, but only if the type is not known.
2576 * That case is disposed of very early -- in the first switch.
2577 */
2578 const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2579
2580 switch (id->isaiid_idtype)
2581 {
2582 case ID_IPV4_ADDR:
2583 case ID_IPV4_ADDR_SUBNET:
2584 case ID_IPV4_ADDR_RANGE:
2585 afi = &af_inet4_info;
2586 break;
2587 case ID_IPV6_ADDR:
2588 case ID_IPV6_ADDR_SUBNET:
2589 case ID_IPV6_ADDR_RANGE:
2590 afi = &af_inet6_info;
2591 break;
2592 case ID_FQDN:
2593 return TRUE;
2594 default:
2595 /* XXX support more */
2596 loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2597 , idtypename);
2598 /* XXX Could send notification back */
2599 return FALSE;
2600 }
2601
2602 switch (id->isaiid_idtype)
2603 {
2604 case ID_IPV4_ADDR:
2605 case ID_IPV6_ADDR:
2606 {
2607 ip_address temp_address;
2608 err_t ugh;
2609
2610 ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2611
2612 if (ugh != NULL)
2613 {
2614 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2615 , which, idtypename, ugh);
2616 /* XXX Could send notification back */
2617 return FALSE;
2618 }
2619 if (isanyaddr(&temp_address))
2620 {
2621 loglog(RC_LOG_SERIOUS, "%s ID payload %s is invalid (%s) in Quick I1"
2622 , which, idtypename, ip_str(&temp_address));
2623 /* XXX Could send notification back */
2624 return FALSE;
2625 }
2626 happy(addrtosubnet(&temp_address, net));
2627 DBG(DBG_PARSING | DBG_CONTROL
2628 , DBG_log("%s is %s", which, ip_str(&temp_address)));
2629 break;
2630 }
2631
2632 case ID_IPV4_ADDR_SUBNET:
2633 case ID_IPV6_ADDR_SUBNET:
2634 {
2635 ip_address temp_address, temp_mask;
2636 err_t ugh;
2637
2638 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2639 {
2640 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2641 , which, idtypename);
2642 /* XXX Could send notification back */
2643 return FALSE;
2644 }
2645 ugh = initaddr(id_pbs->cur
2646 , afi->ia_sz, afi->af, &temp_address);
2647 if (ugh == NULL)
2648 ugh = initaddr(id_pbs->cur + afi->ia_sz
2649 , afi->ia_sz, afi->af, &temp_mask);
2650 if (ugh == NULL)
2651 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2652 , '0', net);
2653 if (ugh == NULL && subnetisnone(net))
2654 ugh = "contains only anyaddr";
2655 if (ugh != NULL)
2656 {
2657 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2658 , which, idtypename, ugh);
2659 /* XXX Could send notification back */
2660 return FALSE;
2661 }
2662 DBG(DBG_PARSING | DBG_CONTROL,
2663 {
2664 char temp_buff[SUBNETTOT_BUF];
2665
2666 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2667 DBG_log("%s is subnet %s", which, temp_buff);
2668 });
2669 break;
2670 }
2671
2672 case ID_IPV4_ADDR_RANGE:
2673 case ID_IPV6_ADDR_RANGE:
2674 {
2675 ip_address temp_address_from, temp_address_to;
2676 err_t ugh;
2677
2678 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2679 {
2680 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2681 , which, idtypename);
2682 /* XXX Could send notification back */
2683 return FALSE;
2684 }
2685 ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2686 if (ugh == NULL)
2687 ugh = initaddr(id_pbs->cur + afi->ia_sz
2688 , afi->ia_sz, afi->af, &temp_address_to);
2689 if (ugh != NULL)
2690 {
2691 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2692 , which, idtypename, ugh);
2693 /* XXX Could send notification back */
2694 return FALSE;
2695 }
2696
2697 ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2698 if (ugh == NULL && subnetisnone(net))
2699 ugh = "contains only anyaddr";
2700 if (ugh != NULL)
2701 {
2702 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2703
2704 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2705 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2706 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2707 " %s - %s unacceptable: %s"
2708 , which, idtypename, temp_buff1, temp_buff2, ugh);
2709 return FALSE;
2710 }
2711 DBG(DBG_PARSING | DBG_CONTROL,
2712 {
2713 char temp_buff[SUBNETTOT_BUF];
2714
2715 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2716 DBG_log("%s is subnet %s (received as range)"
2717 , which, temp_buff);
2718 });
2719 break;
2720 }
2721 }
2722
2723 /* set the port selector */
2724 setportof(htons(id->isaiid_port), &net->addr);
2725
2726 DBG(DBG_PARSING | DBG_CONTROL,
2727 DBG_log("%s protocol/port is %d/%d", which, id->isaiid_protoid, id->isaiid_port)
2728 )
2729
2730 return TRUE;
2731 }
2732
2733 /* like decode, but checks that what is received matches what was sent */
2734 static bool
2735
2736 check_net_id(struct isakmp_ipsec_id *id
2737 , pb_stream *id_pbs
2738 , u_int8_t *protoid
2739 , u_int16_t *port
2740 , ip_subnet *net
2741 , const char *which)
2742 {
2743 ip_subnet net_temp;
2744
2745 if (!decode_net_id(id, id_pbs, &net_temp, which))
2746 return FALSE;
2747
2748 if (!samesubnet(net, &net_temp)
2749 || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2750 {
2751 loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2752 return FALSE;
2753 }
2754 return TRUE;
2755 }
2756
2757 /*
2758 * look for the existence of a non-expiring preloaded public key
2759 */
2760 static bool
2761 has_preloaded_public_key(struct state *st)
2762 {
2763 struct connection *c = st->st_connection;
2764
2765 /* do not consider rw connections since
2766 * the peer's identity must be known
2767 */
2768 if (c->kind == CK_PERMANENT)
2769 {
2770 pubkey_list_t *p;
2771
2772 /* look for a matching RSA public key */
2773 for (p = pubkeys; p != NULL; p = p->next)
2774 {
2775 pubkey_t *key = p->key;
2776
2777 if (key->alg == PUBKEY_ALG_RSA &&
2778 same_id(&c->spd.that.id, &key->id) &&
2779 key->until_time == UNDEFINED_TIME)
2780 {
2781 /* found a preloaded public key */
2782 return TRUE;
2783 }
2784 }
2785 }
2786 return FALSE;
2787 }
2788
2789 /*
2790 * Produce the new key material of Quick Mode.
2791 * RFC 2409 "IKE" section 5.5
2792 * specifies how this is to be done.
2793 */
2794 static void
2795 compute_proto_keymat(struct state *st
2796 , u_int8_t protoid
2797 , struct ipsec_proto_info *pi)
2798 {
2799 size_t needed_len; /* bytes of keying material needed */
2800
2801 /* Add up the requirements for keying material
2802 * (It probably doesn't matter if we produce too much!)
2803 */
2804 switch (protoid)
2805 {
2806 case PROTO_IPSEC_ESP:
2807 switch (pi->attrs.transid)
2808 {
2809 case ESP_NULL:
2810 needed_len = 0;
2811 break;
2812 case ESP_DES:
2813 needed_len = DES_CBC_BLOCK_SIZE;
2814 break;
2815 case ESP_3DES:
2816 needed_len = DES_CBC_BLOCK_SIZE * 3;
2817 break;
2818 default:
2819 #ifndef NO_KERNEL_ALG
2820 if((needed_len=kernel_alg_esp_enc_keylen(pi->attrs.transid))>0) {
2821 /* XXX: check key_len "coupling with kernel.c's */
2822 if (pi->attrs.key_len) {
2823 needed_len=pi->attrs.key_len/8;
2824 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2825 "key_len=%d from peer",
2826 (int)needed_len));
2827 }
2828 break;
2829 }
2830 #endif
2831 bad_case(pi->attrs.transid);
2832 }
2833
2834 #ifndef NO_KERNEL_ALG
2835 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2836 "needed_len (after ESP enc)=%d",
2837 (int)needed_len));
2838 if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL)) {
2839 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2840 } else
2841 #endif
2842 switch (pi->attrs.auth)
2843 {
2844 case AUTH_ALGORITHM_NONE:
2845 break;
2846 case AUTH_ALGORITHM_HMAC_MD5:
2847 needed_len += HMAC_MD5_KEY_LEN;
2848 break;
2849 case AUTH_ALGORITHM_HMAC_SHA1:
2850 needed_len += HMAC_SHA1_KEY_LEN;
2851 break;
2852 case AUTH_ALGORITHM_DES_MAC:
2853 default:
2854 bad_case(pi->attrs.auth);
2855 }
2856 DBG(DBG_PARSING, DBG_log("compute_proto_keymat:"
2857 "needed_len (after ESP auth)=%d",
2858 (int)needed_len));
2859 break;
2860
2861 case PROTO_IPSEC_AH:
2862 switch (pi->attrs.transid)
2863 {
2864 case AH_MD5:
2865 needed_len = HMAC_MD5_KEY_LEN;
2866 break;
2867 case AH_SHA:
2868 needed_len = HMAC_SHA1_KEY_LEN;
2869 break;
2870 default:
2871 bad_case(pi->attrs.transid);
2872 }
2873 break;
2874
2875 default:
2876 bad_case(protoid);
2877 }
2878
2879 pi->keymat_len = needed_len;
2880
2881 /* Allocate space for the keying material.
2882 * Although only needed_len bytes are desired, we
2883 * must round up to a multiple of ctx.hmac_digest_size
2884 * so that our buffer isn't overrun.
2885 */
2886 {
2887 struct hmac_ctx ctx_me, ctx_peer;
2888 size_t needed_space; /* space needed for keying material (rounded up) */
2889 size_t i;
2890
2891 hmac_init_chunk(&ctx_me, st->st_oakley.hasher, st->st_skeyid_d);
2892 ctx_peer = ctx_me; /* duplicate initial conditions */
2893
2894 needed_space = needed_len + pad_up(needed_len, ctx_me.hmac_digest_size);
2895 replace(pi->our_keymat, alloc_bytes(needed_space, "keymat in compute_keymat()"));
2896 replace(pi->peer_keymat, alloc_bytes(needed_space, "peer_keymat in quick_inI1_outR1()"));
2897
2898 for (i = 0;; )
2899 {
2900 if (st->st_shared.ptr != NULL)
2901 {
2902 /* PFS: include the g^xy */
2903 hmac_update_chunk(&ctx_me, st->st_shared);
2904 hmac_update_chunk(&ctx_peer, st->st_shared);
2905 }
2906 hmac_update(&ctx_me, &protoid, sizeof(protoid));
2907 hmac_update(&ctx_peer, &protoid, sizeof(protoid));
2908
2909 hmac_update(&ctx_me, (u_char *)&pi->our_spi, sizeof(pi->our_spi));
2910 hmac_update(&ctx_peer, (u_char *)&pi->attrs.spi, sizeof(pi->attrs.spi));
2911
2912 hmac_update_chunk(&ctx_me, st->st_ni);
2913 hmac_update_chunk(&ctx_peer, st->st_ni);
2914
2915 hmac_update_chunk(&ctx_me, st->st_nr);
2916 hmac_update_chunk(&ctx_peer, st->st_nr);
2917
2918 hmac_final(pi->our_keymat + i, &ctx_me);
2919 hmac_final(pi->peer_keymat + i, &ctx_peer);
2920
2921 i += ctx_me.hmac_digest_size;
2922 if (i >= needed_space)
2923 break;
2924
2925 /* more keying material needed: prepare to go around again */
2926
2927 hmac_reinit(&ctx_me);
2928 hmac_reinit(&ctx_peer);
2929
2930 hmac_update(&ctx_me, pi->our_keymat + i - ctx_me.hmac_digest_size
2931 , ctx_me.hmac_digest_size);
2932 hmac_update(&ctx_peer, pi->peer_keymat + i - ctx_peer.hmac_digest_size
2933 , ctx_peer.hmac_digest_size);
2934 }
2935 }
2936
2937 DBG(DBG_CRYPT,
2938 DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
2939 DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
2940 }
2941
2942 static void
2943 compute_keymats(struct state *st)
2944 {
2945 if (st->st_ah.present)
2946 compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
2947 if (st->st_esp.present)
2948 compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
2949 }
2950
2951 /* State Transition Functions.
2952 *
2953 * The definition of state_microcode_table in demux.c is a good
2954 * overview of these routines.
2955 *
2956 * - Called from process_packet; result handled by complete_state_transition
2957 * - struct state_microcode member "processor" points to these
2958 * - these routine definitionss are in state order
2959 * - these routines must be restartable from any point of error return:
2960 * beware of memory allocated before any error.
2961 * - output HDR is usually emitted by process_packet (if state_microcode
2962 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2963 *
2964 * The transition functions' functions include:
2965 * - process and judge payloads
2966 * - update st_iv (result of decryption is in st_new_iv)
2967 * - build reply packet
2968 */
2969
2970 /* Handle a Main Mode Oakley first packet (responder side).
2971 * HDR;SA --> HDR;SA
2972 */
2973 stf_status
2974 main_inI1_outR1(struct msg_digest *md)
2975 {
2976 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
2977 struct state *st;
2978 struct connection *c;
2979 struct isakmp_proposal proposal;
2980 pb_stream proposal_pbs;
2981 pb_stream r_sa_pbs;
2982 u_int32_t ipsecdoisit;
2983 lset_t policy = LEMPTY;
2984 int vids_to_send = 0;
2985
2986 /* We preparse the peer's proposal in order to determine
2987 * the requested authentication policy (RSA or PSK)
2988 */
2989 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd->payload.sa
2990 , &sa_pd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
2991
2992 backup_pbs(&proposal_pbs);
2993 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2994 , proposal.isap_notrans, &policy));
2995 restore_pbs(&proposal_pbs);
2996
2997 /* We are only considering candidate connections that match
2998 * the requested authentication policy (RSA or PSK)
2999 */
3000 c = find_host_connection(&md->iface->addr, pluto_port
3001 , &md->sender, md->sender_port, policy);
3002
3003 if (c == NULL && md->iface->ike_float)
3004 {
3005 c = find_host_connection(&md->iface->addr, NAT_T_IKE_FLOAT_PORT
3006 , &md->sender, md->sender_port, policy);
3007 }
3008
3009 if (c == NULL)
3010 {
3011 /* See if a wildcarded connection can be found.
3012 * We cannot pick the right connection, so we're making a guess.
3013 * All Road Warrior connections are fair game:
3014 * we pick the first we come across (if any).
3015 * If we don't find any, we pick the first opportunistic
3016 * with the smallest subnet that includes the peer.
3017 * There is, of course, no necessary relationship between
3018 * an Initiator's address and that of its client,
3019 * but Food Groups kind of assumes one.
3020 */
3021 {
3022 struct connection *d;
3023
3024 d = find_host_connection(&md->iface->addr
3025 , pluto_port, (ip_address*)NULL, md->sender_port, policy);
3026
3027 for (; d != NULL; d = d->hp_next)
3028 {
3029 if (d->kind == CK_GROUP)
3030 {
3031 /* ignore */
3032 }
3033 else
3034 {
3035 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO))
3036 {
3037 /* must be Road Warrior: we have a winner */
3038 c = d;
3039 break;
3040 }
3041
3042 /* Opportunistic or Shunt: pick tightest match */
3043 if (addrinsubnet(&md->sender, &d->spd.that.client)
3044 && (c == NULL || !subnetinsubnet(&c->spd.that.client, &d->spd.that.client)))
3045 c = d;
3046 }
3047 }
3048 }
3049
3050 if (c == NULL)
3051 {
3052 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3053 " but no connection has been authorized%s%s"
3054 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr))
3055 , (policy != LEMPTY) ? " with policy=" : ""
3056 , (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : "");
3057 /* XXX notification is in order! */
3058 return STF_IGNORE;
3059 }
3060 else if (c->kind != CK_TEMPLATE)
3061 {
3062 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3063 " but \"%s\" forbids connection"
3064 , ip_str(&md->iface->addr), pluto_port, c->name);
3065 /* XXX notification is in order! */
3066 return STF_IGNORE;
3067 }
3068 else
3069 {
3070 /* Create a temporary connection that is a copy of this one.
3071 * His ID isn't declared yet.
3072 */
3073 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, NULL);
3074 }
3075 }
3076 else if (c->kind == CK_TEMPLATE)
3077 {
3078 /* Create an instance
3079 * This is a rare case: wildcard peer ID but static peer IP address
3080 */
3081 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, &c->spd.that.id);
3082 }
3083
3084 /* Set up state */
3085 md->st = st = new_state();
3086 st->st_connection = c;
3087 set_cur_state(st); /* (caller will reset cur_state) */
3088 st->st_try = 0; /* not our job to try again from start */
3089 st->st_policy = c->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
3090
3091 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
3092 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
3093
3094 insert_state(st); /* needs cookies, connection, and msgid (0) */
3095
3096 st->st_doi = ISAKMP_DOI_IPSEC;
3097 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
3098
3099 if ((c->kind == CK_INSTANCE) && (c->spd.that.host_port != pluto_port))
3100 {
3101 plog("responding to Main Mode from unknown peer %s:%u"
3102 , ip_str(&c->spd.that.host_addr), c->spd.that.host_port);
3103 }
3104 else if (c->kind == CK_INSTANCE)
3105 {
3106 plog("responding to Main Mode from unknown peer %s"
3107 , ip_str(&c->spd.that.host_addr));
3108 }
3109 else
3110 {
3111 plog("responding to Main Mode");
3112 }
3113
3114 /* parse_isakmp_sa also spits out a winning SA into our reply,
3115 * so we have to build our md->reply and emit HDR before calling it.
3116 */
3117
3118 /* determine how many Vendor ID payloads we will be sending */
3119 if (SEND_PLUTO_VID)
3120 vids_to_send++;
3121 if (SEND_XAUTH_VID)
3122 vids_to_send++;
3123 if (SEND_CISCO_UNITY_VID)
3124 vids_to_send++;
3125 if (md->openpgp)
3126 vids_to_send++;
3127 /* always send DPD Vendor ID */
3128 vids_to_send++;
3129 if (md->nat_traversal_vid && nat_traversal_enabled)
3130 vids_to_send++;
3131
3132 /* HDR out.
3133 * We can't leave this to comm_handle() because we must
3134 * fill in the cookie.
3135 */
3136 {
3137 struct isakmp_hdr r_hdr = md->hdr;
3138
3139 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3140 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3141 r_hdr.isa_np = ISAKMP_NEXT_SA;
3142 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3143 return STF_INTERNAL_ERROR;
3144 }
3145
3146 /* start of SA out */
3147 {
3148 struct isakmp_sa r_sa = sa_pd->payload.sa;
3149
3150 r_sa.isasa_np = vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
3151
3152 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3153 return STF_INTERNAL_ERROR;
3154 }
3155
3156 /* SA body in and out */
3157 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit, &proposal_pbs
3158 ,&proposal, &r_sa_pbs, st, FALSE));
3159
3160 /* if enabled send Pluto Vendor ID */
3161 if (SEND_PLUTO_VID)
3162 {
3163 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3164 , &md->rbody, VID_STRONGSWAN))
3165 {
3166 return STF_INTERNAL_ERROR;
3167 }
3168 }
3169
3170 /* if enabled send XAUTH Vendor ID */
3171 if (SEND_XAUTH_VID)
3172 {
3173 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3174 , &md->rbody, VID_MISC_XAUTH))
3175 {
3176 return STF_INTERNAL_ERROR;
3177 }
3178 }
3179
3180 /* if enabled send Cisco Unity Vendor ID */
3181 if (SEND_CISCO_UNITY_VID)
3182 {
3183 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3184 , &md->rbody, VID_CISCO_UNITY))
3185 {
3186 return STF_INTERNAL_ERROR;
3187 }
3188 }
3189
3190 /*
3191 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3192 */
3193 if (md->openpgp)
3194 {
3195 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3196 , &md->rbody, VID_OPENPGP))
3197 {
3198 return STF_INTERNAL_ERROR;
3199 }
3200 }
3201
3202 /* Announce our ability to do Dead Peer Detection to the peer */
3203 {
3204 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3205 , &md->rbody, VID_MISC_DPD))
3206 {
3207 return STF_INTERNAL_ERROR;
3208 }
3209 }
3210
3211 if (md->nat_traversal_vid && nat_traversal_enabled)
3212 {
3213 /* reply if NAT-Traversal draft is supported */
3214 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3215
3216 if (st->nat_traversal
3217 && !out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3218 , &md->rbody, md->nat_traversal_vid))
3219 {
3220 return STF_INTERNAL_ERROR;
3221 }
3222 }
3223
3224 close_message(&md->rbody);
3225
3226 /* save initiator SA for HASH */
3227 clonereplacechunk(st->st_p1isa, sa_pd->pbs.start, pbs_room(&sa_pd->pbs), "sa in main_inI1_outR1()");
3228
3229 return STF_OK;
3230 }
3231
3232 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3233 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3234 *
3235 * The following are not yet implemented:
3236 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3237 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3238 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3239 *
3240 * We must verify that the proposal received matches one we sent.
3241 */
3242 stf_status
3243 main_inR1_outI2(struct msg_digest *md)
3244 {
3245 struct state *const st = md->st;
3246
3247 u_int8_t np = ISAKMP_NEXT_NONE;
3248
3249 /* verify echoed SA */
3250 {
3251 u_int32_t ipsecdoisit;
3252 pb_stream proposal_pbs;
3253 struct isakmp_proposal proposal;
3254 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
3255
3256 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd->payload.sa
3257 ,&sapd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
3258 if (proposal.isap_notrans != 1)
3259 {
3260 loglog(RC_LOG_SERIOUS, "a single Transform is required in a selecting Oakley Proposal; found %u"
3261 , (unsigned)proposal.isap_notrans);
3262 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX);
3263 }
3264 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3265 , &proposal_pbs, &proposal, NULL, st, TRUE));
3266 }
3267
3268 if (nat_traversal_enabled && md->nat_traversal_vid)
3269 {
3270 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3271 plog("enabling possible NAT-traversal with method %s"
3272 , bitnamesof(natt_type_bitnames, st->nat_traversal));
3273 }
3274 if (st->nat_traversal & NAT_T_WITH_NATD)
3275 {
3276 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3277 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3278 }
3279
3280 /**************** build output packet HDR;KE;Ni ****************/
3281
3282 /* HDR out.
3283 * We can't leave this to comm_handle() because the isa_np
3284 * depends on the type of Auth (eventually).
3285 */
3286 echo_hdr(md, FALSE, ISAKMP_NEXT_KE);
3287
3288 /* KE out */
3289 if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group
3290 , &md->rbody, ISAKMP_NEXT_NONCE))
3291 return STF_INTERNAL_ERROR;
3292
3293 #ifdef DEBUG
3294 /* Ni out */
3295 if (!build_and_ship_nonce(&st->st_ni, &md->rbody
3296 , (cur_debugging & IMPAIR_BUST_MI2)? ISAKMP_NEXT_VID : np, "Ni"))
3297 return STF_INTERNAL_ERROR;
3298
3299 if (cur_debugging & IMPAIR_BUST_MI2)
3300 {
3301 /* generate a pointless large VID payload to push message over MTU */
3302 pb_stream vid_pbs;
3303
3304 if (!out_generic(np, &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3305 return STF_INTERNAL_ERROR;
3306 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3307 return STF_INTERNAL_ERROR;
3308 close_output_pbs(&vid_pbs);
3309 }
3310 #else
3311 /* Ni out */
3312 if (!build_and_ship_nonce(&st->st_ni, &md->rbody, np, "Ni"))
3313 return STF_INTERNAL_ERROR;
3314 #endif
3315
3316 if (st->nat_traversal & NAT_T_WITH_NATD)
3317 {
3318 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3319 return STF_INTERNAL_ERROR;
3320 }
3321
3322 /* finish message */
3323 close_message(&md->rbody);
3324
3325 /* Reinsert the state, using the responder cookie we just received */
3326 unhash_state(st);
3327 memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
3328 insert_state(st); /* needs cookies, connection, and msgid (0) */
3329
3330 return STF_OK;
3331 }
3332
3333 /* STATE_MAIN_R1:
3334 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3335 *
3336 * The following are not yet implemented:
3337 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3338 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3339 * RPKE_AUTH:
3340 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3341 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3342 */
3343 stf_status
3344 main_inI2_outR2(struct msg_digest *md)
3345 {
3346 struct state *const st = md->st;
3347 pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3348
3349 /* send CR if auth is RSA and no preloaded RSA public key exists*/
3350 bool RSA_auth = st->st_oakley.auth == OAKLEY_RSA_SIG
3351 || st->st_oakley.auth == XAUTHInitRSA
3352 || st->st_oakley.auth == XAUTHRespRSA;
3353 bool send_cr = !no_cr_send && RSA_auth && !has_preloaded_public_key(st);
3354
3355 u_int8_t np = ISAKMP_NEXT_NONE;
3356
3357 /* KE in */
3358 RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
3359
3360 /* Ni in */
3361 RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
3362
3363 if (st->nat_traversal & NAT_T_WITH_NATD)
3364 {
3365 nat_traversal_natd_lookup(md);
3366
3367 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3368 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3369 }
3370 if (st->nat_traversal)
3371 {
3372 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3373 }
3374 if (st->nat_traversal & NAT_T_WITH_KA)
3375 {
3376 nat_traversal_new_ka_event();
3377 }
3378
3379 /* decode certificate requests */
3380 st->st_connection->got_certrequest = FALSE;
3381 decode_cr(md, st->st_connection);
3382
3383 /**************** build output packet HDR;KE;Nr ****************/
3384
3385 /* HDR out done */
3386
3387 /* KE out */
3388 if (!build_and_ship_KE(st, &st->st_gr, st->st_oakley.group
3389 , &md->rbody, ISAKMP_NEXT_NONCE))
3390 return STF_INTERNAL_ERROR;
3391
3392 #ifdef DEBUG
3393 /* Nr out */
3394 if (!build_and_ship_nonce(&st->st_nr, &md->rbody
3395 , (cur_debugging & IMPAIR_BUST_MR2)? ISAKMP_NEXT_VID
3396 : (send_cr? ISAKMP_NEXT_CR : np), "Nr"))
3397 return STF_INTERNAL_ERROR;
3398
3399 if (cur_debugging & IMPAIR_BUST_MR2)
3400 {
3401 /* generate a pointless large VID payload to push message over MTU */
3402 pb_stream vid_pbs;
3403
3404 if (!out_generic((send_cr)? ISAKMP_NEXT_CR : np,
3405 &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3406 return STF_INTERNAL_ERROR;
3407 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3408 return STF_INTERNAL_ERROR;
3409 close_output_pbs(&vid_pbs);
3410 }
3411 #else
3412 /* Nr out */
3413 if (!build_and_ship_nonce(&st->st_nr, &md->rbody,
3414 (send_cr)? ISAKMP_NEXT_CR : np, "Nr"))
3415 return STF_INTERNAL_ERROR;
3416 #endif
3417
3418 /* CR out */
3419 if (send_cr)
3420 {
3421 if (st->st_connection->kind == CK_PERMANENT)
3422 {
3423 if (!build_and_ship_CR(CERT_X509_SIGNATURE
3424 , st->st_connection->spd.that.ca
3425 , &md->rbody, np))
3426 return STF_INTERNAL_ERROR;
3427 }
3428 else
3429 {
3430 generalName_t *ca = NULL;
3431
3432 if (collect_rw_ca_candidates(md, &ca))
3433 {
3434 generalName_t *gn;
3435
3436 for (gn = ca; gn != NULL; gn = gn->next)
3437 {
3438 if (!build_and_ship_CR(CERT_X509_SIGNATURE, gn->name
3439 , &md->rbody
3440 , gn->next == NULL ? np : ISAKMP_NEXT_CR))
3441 return STF_INTERNAL_ERROR;
3442 }
3443 free_generalNames(ca, FALSE);
3444 }
3445 else
3446 {
3447 if (!build_and_ship_CR(CERT_X509_SIGNATURE, empty_chunk
3448 , &md->rbody, np))
3449 return STF_INTERNAL_ERROR;
3450 }
3451 }
3452 }
3453
3454 if (st->nat_traversal & NAT_T_WITH_NATD)
3455 {
3456 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3457 return STF_INTERNAL_ERROR;
3458 }
3459
3460 /* finish message */
3461 close_message(&md->rbody);
3462
3463 /* next message will be encrypted, but not this one.
3464 * We could defer this calculation.
3465 */
3466 compute_dh_shared(st, st->st_gi, st->st_oakley.group);
3467 if (!generate_skeyids_iv(st))
3468 return STF_FAIL + AUTHENTICATION_FAILED;
3469 update_iv(st);
3470
3471 return STF_OK;
3472 }
3473
3474 /* STATE_MAIN_I2:
3475 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3476 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3477 *
3478 * The following are not yet implemented.
3479 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3480 * --> HDR*, HASH_I
3481 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3482 * --> HDR*, HASH_I
3483 */
3484 stf_status
3485 main_inR2_outI3(struct msg_digest *md)
3486 {
3487 struct state *const st = md->st;
3488 pb_stream *const keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3489 int auth_payload = st->st_oakley.auth == OAKLEY_PRESHARED_KEY
3490 ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_SIG;
3491 pb_stream id_pbs; /* ID Payload; also used for hash calculation */
3492
3493 certpolicy_t cert_policy = st->st_connection->spd.this.sendcert;
3494 cert_t mycert = st->st_connection->spd.this.cert;
3495 bool requested, send_cert, send_cr;
3496
3497 bool RSA_auth = st->st_oakley.auth == OAKLEY_RSA_SIG
3498 || st->st_oakley.auth == XAUTHInitRSA
3499 || st->st_oakley.auth == XAUTHRespRSA;
3500
3501 /* KE in */
3502 RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
3503
3504 /* Nr in */
3505 RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
3506
3507 /* decode certificate requests */
3508 st->st_connection->got_certrequest = FALSE;
3509 decode_cr(md, st->st_connection);
3510
3511 /* free collected certificate requests since as initiator
3512 * we don't heed them anyway
3513 */
3514 free_generalNames(st->st_connection->requested_ca, TRUE);
3515 st->st_connection->requested_ca = NULL;
3516
3517 /* send certificate if auth is RSA, we have one and we want
3518 * or are requested to send it
3519 */
3520 requested = cert_policy == CERT_SEND_IF_ASKED
3521 && st->st_connection->got_certrequest;
3522 send_cert = RSA_auth && mycert.type != CERT_NONE
3523 && (cert_policy == CERT_ALWAYS_SEND || requested);
3524
3525 /* send certificate request if we don't have a preloaded RSA public key */
3526 send_cr = !no_cr_send && send_cert && !has_preloaded_public_key(st);
3527
3528 /* done parsing; initialize crypto */
3529
3530 compute_dh_shared(st, st->st_gr, st->st_oakley.group);
3531 if (!generate_skeyids_iv(st))
3532 return STF_FAIL + AUTHENTICATION_FAILED;
3533
3534 if (st->nat_traversal & NAT_T_WITH_NATD)
3535 {
3536 nat_traversal_natd_lookup(md);
3537 }
3538 if (st->nat_traversal)
3539 {
3540 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3541 }
3542 if (st->nat_traversal & NAT_T_WITH_KA)
3543 {
3544 nat_traversal_new_ka_event();
3545 }
3546
3547 /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3548 /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3549
3550 /* HDR* out done */
3551
3552 /* IDii out */
3553 {
3554 struct isakmp_ipsec_id id_hd;
3555 chunk_t id_b;
3556
3557 build_id_payload(&id_hd, &id_b, &st->st_connection->spd.this);
3558 id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3559 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &id_pbs)
3560 || !out_chunk(id_b, &id_pbs, "my identity"))
3561 return STF_INTERNAL_ERROR;
3562 close_output_pbs(&id_pbs);
3563 }
3564
3565 /* CERT out */
3566 if (RSA_auth)
3567 {
3568 DBG(DBG_CONTROL,
3569 DBG_log("our certificate policy is %s"
3570 , enum_name(&cert_policy_names, cert_policy))
3571 )
3572 if (mycert.type != CERT_NONE)
3573 {
3574 const char *request_text = "";
3575
3576 if (cert_policy == CERT_SEND_IF_ASKED)
3577 request_text = (send_cert)? "upon request":"without request";
3578 plog("we have a cert %s sending it %s"
3579 , send_cert? "and are":"but are not", request_text);
3580 }
3581 else
3582 {
3583 plog("we don't have a cert");
3584 }
3585 }
3586 if (send_cert)
3587 {
3588 pb_stream cert_pbs;
3589
3590 struct isakmp_cert cert_hd;
3591 cert_hd.isacert_np = (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_SIG;
3592 cert_hd.isacert_type = mycert.type;
3593
3594 if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3595 return STF_INTERNAL_ERROR;
3596 if (!out_chunk(get_mycert(mycert), &cert_pbs, "CERT"))
3597 return STF_INTERNAL_ERROR;
3598 close_output_pbs(&cert_pbs);
3599 }
3600
3601 /* CR out */
3602 if (send_cr)
3603 {
3604 if (!build_and_ship_CR(mycert.type, st->st_connection->spd.that.ca
3605 , &md->rbody, ISAKMP_NEXT_SIG))
3606 return STF_INTERNAL_ERROR;
3607 }
3608
3609 /* HASH_I or SIG_I out */
3610 {
3611 u_char hash_val[MAX_DIGEST_LEN];
3612 size_t hash_len = main_mode_hash(st, hash_val, TRUE, &id_pbs);
3613
3614 if (auth_payload == ISAKMP_NEXT_HASH)
3615 {
3616 /* HASH_I out */
3617 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody
3618 , hash_val, hash_len, "HASH_I"))
3619 return STF_INTERNAL_ERROR;
3620 }
3621 else
3622 {
3623 /* SIG_I out */
3624 u_char sig_val[RSA_MAX_OCTETS];
3625 size_t sig_len = RSA_sign_hash(st->st_connection
3626 , sig_val, hash_val, hash_len);
3627
3628 if (sig_len == 0)
3629 {
3630 loglog(RC_LOG_SERIOUS, "unable to locate my private key for RSA Signature");
3631 return STF_FAIL + AUTHENTICATION_FAILED;
3632 }
3633
3634 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3635 , &md->rbody, sig_val, sig_len, "SIG_I"))
3636 return STF_INTERNAL_ERROR;
3637 }
3638 }
3639
3640 /* encrypt message, except for fixed part of header */
3641
3642 /* st_new_iv was computed by generate_skeyids_iv */
3643 if (!encrypt_message(&md->rbody, st))
3644 return STF_INTERNAL_ERROR; /* ??? we may be partly committed */
3645
3646 return STF_OK;
3647 }
3648
3649 /* Shared logic for asynchronous lookup of DNS KEY records.
3650 * Used for STATE_MAIN_R2 and STATE_MAIN_I3.
3651 */
3652
3653 enum key_oppo_step {
3654 kos_null,
3655 kos_his_txt
3656 #ifdef USE_KEYRR
3657 , kos_his_key
3658 #endif
3659 };
3660
3661 struct key_continuation {
3662 struct adns_continuation ac; /* common prefix */
3663 struct msg_digest *md;
3664 enum key_oppo_step step;
3665 bool failure_ok;
3666 err_t last_ugh;
3667 };
3668
3669 typedef stf_status (key_tail_fn)(struct msg_digest *md
3670 , struct key_continuation *kc);
3671 static void
3672 report_key_dns_failure(struct id *id, err_t ugh)
3673 {
3674 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
3675
3676 (void) idtoa(id, id_buf, sizeof(id_buf));
3677 loglog(RC_LOG_SERIOUS, "no RSA public key known for '%s'"
3678 "; DNS search for KEY failed (%s)", id_buf, ugh);
3679 }
3680
3681
3682 /* Processs the Main Mode ID Payload and the Authenticator
3683 * (Hash or Signature Payload).
3684 * If a DNS query is still needed to get the other host's public key,
3685 * the query is initiated and STF_SUSPEND is returned.
3686 * Note: parameter kc is a continuation containing the results from
3687 * the previous DNS query, or NULL indicating no query has been issued.
3688 */
3689 static stf_status
3690 main_id_and_auth(struct msg_digest *md
3691 , bool initiator /* are we the Initiator? */
3692 , cont_fn_t cont_fn /* continuation function */
3693 , const struct key_continuation *kc /* current state, can be NULL */
3694 )
3695 {
3696 struct state *st = md->st;
3697 u_char hash_val[MAX_DIGEST_LEN];
3698 size_t hash_len;
3699 struct id peer;
3700 stf_status r = STF_OK;
3701
3702 /* ID Payload in */
3703 if (!decode_peer_id(md, &peer))
3704 return STF_FAIL + INVALID_ID_INFORMATION;
3705
3706 /* Hash the ID Payload.
3707 * main_mode_hash requires idpl->cur to be at end of payload
3708 * so we temporarily set if so.
3709 */
3710 {
3711 pb_stream *idpl = &md->chain[ISAKMP_NEXT_ID]->pbs;
3712 u_int8_t *old_cur = idpl->cur;
3713
3714 idpl->cur = idpl->roof;
3715 hash_len = main_mode_hash(st, hash_val, !initiator, idpl);
3716 idpl->cur = old_cur;
3717 }
3718
3719 switch (st->st_oakley.auth)
3720 {
3721 case OAKLEY_PRESHARED_KEY:
3722 case XAUTHInitPreShared:
3723 case XAUTHRespPreShared:
3724 {
3725 pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs;
3726
3727 if (pbs_left(hash_pbs) != hash_len
3728 || memcmp(hash_pbs->cur, hash_val, hash_len) != 0)
3729 {
3730 DBG_cond_dump(DBG_CRYPT, "received HASH:"
3731 , hash_pbs->cur, pbs_left(hash_pbs));
3732 loglog(RC_LOG_SERIOUS, "received Hash Payload does not match computed value");
3733 /* XXX Could send notification back */
3734 r = STF_FAIL + INVALID_HASH_INFORMATION;
3735 }
3736 }
3737 break;
3738
3739 case OAKLEY_RSA_SIG:
3740 case XAUTHInitRSA:
3741 case XAUTHRespRSA:
3742 r = RSA_check_signature(&peer, st, hash_val, hash_len
3743 , &md->chain[ISAKMP_NEXT_SIG]->pbs
3744 #ifdef USE_KEYRR
3745 , kc == NULL? NULL : kc->ac.keys_from_dns
3746 #endif /* USE_KEYRR */
3747 , kc == NULL? NULL : kc->ac.gateways_from_dns
3748 );
3749
3750 if (r == STF_SUSPEND)
3751 {
3752 /* initiate/resume asynchronous DNS lookup for key */
3753 struct key_continuation *nkc
3754 = alloc_thing(struct key_continuation, "key continuation");
3755 enum key_oppo_step step_done = kc == NULL? kos_null : kc->step;
3756 err_t ugh;
3757
3758 /* Record that state is used by a suspended md */
3759 passert(st->st_suspended_md == NULL);
3760 st->st_suspended_md = md;
3761
3762 nkc->failure_ok = FALSE;
3763 nkc->md = md;
3764
3765 switch (step_done)
3766 {
3767 case kos_null:
3768 /* first try: look for the TXT records */
3769 nkc->step = kos_his_txt;
3770 #ifdef USE_KEYRR
3771 nkc->failure_ok = TRUE;
3772 #endif
3773 ugh = start_adns_query(&peer
3774 , &peer /* SG itself */
3775 , T_TXT
3776 , cont_fn
3777 , &nkc->ac);
3778 break;
3779
3780 #ifdef USE_KEYRR
3781 case kos_his_txt:
3782 /* second try: look for the KEY records */
3783 nkc->step = kos_his_key;
3784 ugh = start_adns_query(&peer
3785 , NULL /* no sgw for KEY */
3786 , T_KEY
3787 , cont_fn
3788 , &nkc->ac);
3789 break;
3790 #endif /* USE_KEYRR */
3791
3792 default:
3793 bad_case(step_done);
3794 }