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