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