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