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