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