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