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