34c42e294998f68649439600f67db6e647cc23a3
[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, *that_id;
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, KEY_ID_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
1948 bool send_natoa = FALSE;
1949 u_int8_t np = ISAKMP_NEXT_NONE;
1950
1951 if (c->spd.this.modecfg && !c->spd.this.has_client &&
1952 isanyaddr(&c->spd.this.host_srcip))
1953 {
1954 connection_t *ph1_c = isakmp_sa->st_connection;
1955
1956 if (ph1_c->spd.this.modecfg && !isanyaddr(&ph1_c->spd.this.host_srcip))
1957 {
1958 char srcip[ADDRTOT_BUF];
1959
1960 c->spd.this.host_srcip = ph1_c->spd.this.host_srcip;
1961 c->spd.this.client = ph1_c->spd.this.client;
1962 c->spd.this.has_client = TRUE;
1963 addrtot(&c->spd.this.host_srcip, 0, srcip, sizeof(srcip));
1964 plog("inheriting virtual IP source address %s from ModeCfg", srcip);
1965 }
1966 }
1967
1968 st->st_whack_sock = whack_sock;
1969 st->st_connection = c;
1970 set_cur_state(st); /* we must reset before exit */
1971 st->st_policy = policy;
1972 st->st_try = try;
1973
1974 st->st_myuserprotoid = c->spd.this.protocol;
1975 st->st_peeruserprotoid = c->spd.that.protocol;
1976 st->st_myuserport = c->spd.this.port;
1977 st->st_peeruserport = c->spd.that.port;
1978
1979 st->st_msgid = generate_msgid(isakmp_sa);
1980 st->st_state = STATE_QUICK_I1;
1981
1982 insert_state(st); /* needs cookies, connection, and msgid */
1983
1984 if (replacing == SOS_NOBODY)
1985 {
1986 plog("initiating Quick Mode %s {using isakmp#%lu}",
1987 prettypolicy(policy), isakmp_sa->st_serialno);
1988 }
1989 else
1990 {
1991 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}",
1992 prettypolicy(policy), replacing, isakmp_sa->st_serialno);
1993 }
1994 if (isakmp_sa->nat_traversal & NAT_T_DETECTED)
1995 {
1996 /* Duplicate nat_traversal status in new state */
1997 st->nat_traversal = isakmp_sa->nat_traversal;
1998
1999 if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))
2000 {
2001 has_client = TRUE;
2002 }
2003 nat_traversal_change_port_lookup(NULL, st);
2004 }
2005 else
2006 {
2007 st->nat_traversal = 0;
2008 }
2009
2010 /* are we going to send a NAT-OA payload? */
2011 if ((st->nat_traversal & NAT_T_WITH_NATOA)
2012 && !(st->st_policy & POLICY_TUNNEL)
2013 && (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)))
2014 {
2015 send_natoa = TRUE;
2016 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
2017 ISAKMP_NEXT_NATOA_RFC : ISAKMP_NEXT_NATOA_DRAFTS;
2018 }
2019
2020 /* set up reply */
2021 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
2022
2023 /* HDR* out */
2024 {
2025 struct isakmp_hdr hdr;
2026
2027 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
2028 hdr.isa_np = ISAKMP_NEXT_HASH;
2029 hdr.isa_xchg = ISAKMP_XCHG_QUICK;
2030 hdr.isa_msgid = st->st_msgid;
2031 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
2032 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
2033 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
2034 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
2035 {
2036 reset_cur_state();
2037 return STF_INTERNAL_ERROR;
2038 }
2039 }
2040
2041 /* HASH(1) -- create and note space to be filled later */
2042 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
2043
2044 /* SA out */
2045
2046 /*
2047 * See if pfs_group has been specified for this conn,
2048 * if not, fallback to old use-same-as-P1 behaviour
2049 */
2050 #ifndef NO_IKE_ALG
2051 if (st->st_connection)
2052 {
2053 st->st_pfs_group = ike_alg_pfsgroup(st->st_connection, policy);
2054 }
2055 if (!st->st_pfs_group)
2056 #endif
2057 /* If PFS specified, use the same group as during Phase 1:
2058 * since no negotiation is possible, we pick one that is
2059 * very likely supported.
2060 */
2061 st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
2062
2063 /* Emit SA payload based on a subset of the policy bits.
2064 * POLICY_COMPRESS is considered iff we can do IPcomp.
2065 */
2066 {
2067 lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
2068
2069 if (can_do_IPcomp)
2070 {
2071 pm |= POLICY_COMPRESS;
2072 }
2073 if (!out_sa(&rbody,
2074 &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT],
2075 st, FALSE, ISAKMP_NEXT_NONCE))
2076 {
2077 reset_cur_state();
2078 return STF_INTERNAL_ERROR;
2079 }
2080 }
2081
2082 /* Ni out */
2083 if (!build_and_ship_nonce(&st->st_ni, &rbody
2084 , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : np
2085 , "Ni"))
2086 {
2087 reset_cur_state();
2088 return STF_INTERNAL_ERROR;
2089 }
2090
2091 /* [ KE ] out (for PFS) */
2092
2093 if (st->st_pfs_group != NULL)
2094 {
2095 if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2096 , &rbody, has_client? ISAKMP_NEXT_ID : np))
2097 {
2098 reset_cur_state();
2099 return STF_INTERNAL_ERROR;
2100 }
2101 }
2102
2103 /* [ IDci, IDcr ] out */
2104 if (has_client)
2105 {
2106 /* IDci (we are initiator), then IDcr (peer is responder) */
2107 if (!emit_subnet_id(&c->spd.this.client
2108 , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2109 || !emit_subnet_id(&c->spd.that.client
2110 , np, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2111 {
2112 reset_cur_state();
2113 return STF_INTERNAL_ERROR;
2114 }
2115 }
2116
2117 /* Send NAT-OA if our address is NATed */
2118 if (send_natoa)
2119 {
2120 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st))
2121 {
2122 reset_cur_state();
2123 return STF_INTERNAL_ERROR;
2124 }
2125 }
2126
2127 /* finish computing HASH(1), inserting it in output */
2128 (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2129 , st, &st->st_msgid, FALSE);
2130
2131 /* encrypt message, except for fixed part of header */
2132
2133 init_phase2_iv(isakmp_sa, &st->st_msgid);
2134 st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2135 memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2136
2137 if (!encrypt_message(&rbody, st))
2138 {
2139 reset_cur_state();
2140 return STF_INTERNAL_ERROR;
2141 }
2142
2143 /* save packet, now that we know its size */
2144 st->st_tpacket = chunk_create(reply.start, pbs_offset(&reply));
2145 st->st_tpacket = chunk_clone(st->st_tpacket);
2146
2147 /* send the packet */
2148
2149 send_packet(st, "quick_outI1");
2150
2151 delete_event(st);
2152 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2153
2154 if (replacing == SOS_NOBODY)
2155 {
2156 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2157 , "%s: initiate"
2158 , enum_name(&state_names, st->st_state));
2159 }
2160 else
2161 {
2162 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2163 , "%s: initiate to replace #%lu"
2164 , enum_name(&state_names, st->st_state)
2165 , replacing);
2166 }
2167 reset_cur_state();
2168 return STF_OK;
2169 }
2170
2171
2172 /*
2173 * Decode the CERT payload of Phase 1.
2174 */
2175 static void decode_cert(struct msg_digest *md)
2176 {
2177 struct payload_digest *p;
2178
2179 for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2180 {
2181 struct isakmp_cert *const cert = &p->payload.cert;
2182 chunk_t blob;
2183 time_t valid_until;
2184 blob.ptr = p->pbs.cur;
2185 blob.len = pbs_left(&p->pbs);
2186 if (cert->isacert_type == CERT_X509_SIGNATURE)
2187 {
2188 cert_t x509cert = cert_empty;
2189
2190 x509cert.cert = lib->creds->create(lib->creds,
2191 CRED_CERTIFICATE, CERT_X509,
2192 BUILD_BLOB_ASN1_DER, blob,
2193 BUILD_END);
2194 if (x509cert.cert)
2195 {
2196 if (verify_x509cert(&x509cert, strict_crl_policy, &valid_until))
2197 {
2198 DBG(DBG_PARSING,
2199 DBG_log("Public key validated")
2200 )
2201 add_public_key_from_cert(&x509cert, valid_until, DAL_SIGNED);
2202 }
2203 else
2204 {
2205 plog("X.509 certificate rejected");
2206 }
2207 x509cert.cert->destroy(x509cert.cert);
2208 }
2209 else
2210 {
2211 plog("Syntax error in X.509 certificate");
2212 }
2213 }
2214 else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2215 {
2216 linked_list_t *certs = linked_list_create();
2217
2218 if (pkcs7_parse_signedData(blob, NULL, certs, NULL, NULL))
2219 {
2220 store_x509certs(certs, strict_crl_policy);
2221 }
2222 else
2223 {
2224 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2225 }
2226 certs->destroy_offset(certs, offsetof(certificate_t, destroy));
2227 }
2228 else
2229 {
2230 loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2231 enum_show(&cert_type_names, cert->isacert_type));
2232 DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2233 }
2234 }
2235 }
2236
2237 /*
2238 * Decode the CR payload of Phase 1.
2239 */
2240 static void decode_cr(struct msg_digest *md, connection_t *c)
2241 {
2242 struct payload_digest *p;
2243
2244 for (p = md->chain[ISAKMP_NEXT_CR]; p != NULL; p = p->next)
2245 {
2246 struct isakmp_cr *const cr = &p->payload.cr;
2247 chunk_t ca_name;
2248
2249 ca_name.len = pbs_left(&p->pbs);
2250 ca_name.ptr = (ca_name.len > 0)? p->pbs.cur : NULL;
2251
2252 DBG_cond_dump_chunk(DBG_PARSING, "CR", ca_name);
2253
2254 if (cr->isacr_type == CERT_X509_SIGNATURE)
2255 {
2256 if (ca_name.len > 0)
2257 {
2258 identification_t *ca;
2259
2260 if (!is_asn1(ca_name))
2261 {
2262 continue;
2263 }
2264 if (c->requested_ca == NULL)
2265 {
2266 c->requested_ca = linked_list_create();
2267 }
2268 ca = identification_create_from_encoding(ID_DER_ASN1_DN, ca_name);
2269 c->requested_ca->insert_last(c->requested_ca, ca);
2270 DBG(DBG_PARSING | DBG_CONTROL,
2271 DBG_log("requested CA: \"%Y\"", ca)
2272 )
2273 }
2274 else
2275 {
2276 DBG(DBG_PARSING | DBG_CONTROL,
2277 DBG_log("requested CA: %%any")
2278 )
2279 }
2280 c->got_certrequest = TRUE;
2281 }
2282 else
2283 {
2284 loglog(RC_LOG_SERIOUS, "ignoring %s certificate request payload",
2285 enum_show(&cert_type_names, cr->isacr_type));
2286 }
2287 }
2288 }
2289
2290 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2291 * Note: we may change connections as a result.
2292 * We must be called before SIG or HASH are decoded since we
2293 * may change the peer's public key or ID.
2294 */
2295 static bool decode_peer_id(struct msg_digest *md, identification_t **peer)
2296 {
2297 struct state *const st = md->st;
2298 struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2299 const pb_stream *const id_pbs = &id_pld->pbs;
2300 struct isakmp_id *const id = &id_pld->payload.id;
2301 chunk_t id_payload;
2302
2303 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2304 * It talks about the protocol ID and Port fields of the ID
2305 * Payload, but they don't exist as such in Phase 1.
2306 * We use more appropriate names.
2307 * isaid_doi_specific_a is in place of Protocol ID.
2308 * isaid_doi_specific_b is in place of Port.
2309 * Besides, there is no good reason for allowing these to be
2310 * other than 0 in Phase 1.
2311 */
2312 if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING)
2313 && id->isaid_doi_specific_a == IPPROTO_UDP
2314 && (id->isaid_doi_specific_b == 0 || id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))
2315 {
2316 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2317 "accepted with port_floating NAT-T",
2318 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2319 }
2320 else if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2321 && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2322 {
2323 loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2324 " but are %d/%d"
2325 , IPPROTO_UDP, IKE_UDP_PORT
2326 , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2327 return FALSE;
2328 }
2329
2330 id_payload = chunk_create(id_pbs->cur, pbs_left(id_pbs));
2331
2332 switch (id->isaid_idtype)
2333 {
2334 case ID_IPV4_ADDR:
2335 if (id_payload.len != 4)
2336 {
2337 loglog(RC_LOG_SERIOUS, "improper %s Phase 1 ID payload",
2338 enum_show(&ident_names, id->isaid_idtype));
2339 return FALSE;
2340 }
2341 break;
2342 case ID_IPV6_ADDR:
2343 if (id_payload.len != 16)
2344 {
2345 loglog(RC_LOG_SERIOUS, "improper %s Phase 1 ID payload",
2346 enum_show(&ident_names, id->isaid_idtype));
2347 return FALSE;
2348 }
2349 break;
2350 case ID_USER_FQDN:
2351 case ID_FQDN:
2352 if (memchr(id_payload.ptr, '\0', id_payload.len) != NULL)
2353 {
2354 loglog(RC_LOG_SERIOUS, "%s Phase 1 ID payload contains "
2355 "a NUL character",
2356 enum_show(&ident_names, id->isaid_idtype));
2357 return FALSE;
2358 }
2359 break;
2360 case ID_KEY_ID:
2361 case ID_DER_ASN1_DN:
2362 break;
2363 default:
2364 /* XXX Could send notification back */
2365 loglog(RC_LOG_SERIOUS, "unacceptable identity type (%s) "
2366 "in Phase 1 ID payload",
2367 enum_show(&ident_names, id->isaid_idtype));
2368 return FALSE;
2369 }
2370 *peer = identification_create_from_encoding(id->isaid_idtype, id_payload);
2371
2372 plog("Peer ID is %s: '%Y'", enum_show(&ident_names, id->isaid_idtype),
2373 *peer);
2374
2375 /* check for certificates */
2376 decode_cert(md);
2377 return TRUE;
2378 }
2379
2380 /* Now that we've decoded the ID payload, let's see if we
2381 * need to switch connections.
2382 * We must not switch horses if we initiated:
2383 * - if the initiation was explicit, we'd be ignoring user's intent
2384 * - if opportunistic, we'll lose our HOLD info
2385 */
2386 static bool switch_connection(struct msg_digest *md, identification_t *peer,
2387 bool initiator)
2388 {
2389 struct state *const st = md->st;
2390 connection_t *c = st->st_connection;
2391 identification_t *peer_ca;
2392
2393 peer_ca = st->st_peer_pubkey ? st->st_peer_pubkey->issuer : NULL;
2394 if (peer_ca)
2395 {
2396 DBG(DBG_CONTROL,
2397 DBG_log("peer CA: \"%Y\"", peer_ca)
2398 )
2399 }
2400 else
2401 {
2402 DBG(DBG_CONTROL,
2403 DBG_log("peer CA: %%none")
2404 )
2405 }
2406
2407 if (initiator)
2408 {
2409 int pathlen;
2410
2411 if (!peer->equals(peer, c->spd.that.id))
2412 {
2413 loglog(RC_LOG_SERIOUS,
2414 "we require peer to have ID '%Y', but peer declares '%Y'",
2415 c->spd.that.id, peer);
2416 return FALSE;
2417 }
2418
2419 if (c->spd.that.ca)
2420 {
2421 DBG(DBG_CONTROL,
2422 DBG_log("required CA: \"%s\"", c->spd.that.ca);
2423 )
2424 }
2425 else
2426 {
2427 DBG(DBG_CONTROL,
2428 DBG_log("required CA: %%none");
2429 )
2430 }
2431
2432 if (!trusted_ca(peer_ca, c->spd.that.ca, &pathlen))
2433 {
2434 loglog(RC_LOG_SERIOUS
2435 , "we don't accept the peer's CA");
2436 return FALSE;
2437 }
2438 }
2439 else
2440 {
2441 connection_t *r;
2442
2443 /* check for certificate requests */
2444 decode_cr(md, c);
2445
2446 r = refine_host_connection(st, peer, peer_ca);
2447
2448 /* delete the collected certificate requests */
2449 if (c->requested_ca)
2450 {
2451 c->requested_ca->destroy_offset(c->requested_ca,
2452 offsetof(identification_t, destroy));
2453 c->requested_ca = NULL;
2454 }
2455
2456 if (r == NULL)
2457 {
2458 loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%Y'", peer);
2459 return FALSE;
2460 }
2461
2462 if (r->spd.this.ca)
2463 {
2464 DBG(DBG_CONTROL,
2465 DBG_log("offered CA: \"%Y\"", r->spd.this.ca)
2466 )
2467 }
2468 else
2469 {
2470 DBG(DBG_CONTROL,
2471 DBG_log("offered CA: %%none")
2472 )
2473 }
2474
2475 if (r != c)
2476 {
2477 /* apparently, r is an improvement on c -- replace */
2478
2479 DBG(DBG_CONTROL
2480 , DBG_log("switched from \"%s\" to \"%s\"", c->name, r->name));
2481 if (r->kind == CK_TEMPLATE)
2482 {
2483 /* instantiate it, filling in peer's ID */
2484 r = rw_instantiate(r, &c->spd.that.host_addr
2485 , c->spd.that.host_port, NULL, peer);
2486 }
2487
2488 /* copy certificate request info */
2489 r->got_certrequest = c->got_certrequest;
2490
2491 st->st_connection = r; /* kill reference to c */
2492 set_cur_connection(r);
2493 connection_discard(c);
2494 }
2495 else if (c->spd.that.has_id_wildcards)
2496 {
2497 c->spd.that.id->destroy(c->spd.that.id);
2498 c->spd.that.id = peer->clone(peer);
2499 c->spd.that.has_id_wildcards = FALSE;
2500 }
2501 }
2502 return TRUE;
2503 }
2504
2505 /* Decode the variable part of an ID packet (during Quick Mode).
2506 * This is designed for packets that identify clients, not peers.
2507 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2508 * (1) it is wrong and (2) we use this value for inband signalling.
2509 */
2510 static bool decode_net_id(struct isakmp_ipsec_id *id, pb_stream *id_pbs,
2511 ip_subnet *net, const char *which)
2512 {
2513 const struct af_info *afi = NULL;
2514
2515 /* Note: the following may be a pointer into static memory
2516 * that may be recycled, but only if the type is not known.
2517 * That case is disposed of very early -- in the first switch.
2518 */
2519 const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2520
2521 switch (id->isaiid_idtype)
2522 {
2523 case ID_IPV4_ADDR:
2524 case ID_IPV4_ADDR_SUBNET:
2525 case ID_IPV4_ADDR_RANGE:
2526 afi = &af_inet4_info;
2527 break;
2528 case ID_IPV6_ADDR:
2529 case ID_IPV6_ADDR_SUBNET:
2530 case ID_IPV6_ADDR_RANGE:
2531 afi = &af_inet6_info;
2532 break;
2533 case ID_FQDN:
2534 return TRUE;
2535 default:
2536 /* XXX support more */
2537 loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2538 , idtypename);
2539 /* XXX Could send notification back */
2540 return FALSE;
2541 }
2542
2543 switch (id->isaiid_idtype)
2544 {
2545 case ID_IPV4_ADDR:
2546 case ID_IPV6_ADDR:
2547 {
2548 ip_address temp_address;
2549 err_t ugh;
2550
2551 ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2552
2553 if (ugh != NULL)
2554 {
2555 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2556 , which, idtypename, ugh);
2557 /* XXX Could send notification back */
2558 return FALSE;
2559 }
2560 if (isanyaddr(&temp_address))
2561 {
2562 loglog(RC_LOG_SERIOUS, "%s ID payload %s is invalid (%s) in Quick I1"
2563 , which, idtypename, ip_str(&temp_address));
2564 /* XXX Could send notification back */
2565 return FALSE;
2566 }
2567 happy(addrtosubnet(&temp_address, net));
2568 DBG(DBG_PARSING | DBG_CONTROL
2569 , DBG_log("%s is %s", which, ip_str(&temp_address)));
2570 break;
2571 }
2572
2573 case ID_IPV4_ADDR_SUBNET:
2574 case ID_IPV6_ADDR_SUBNET:
2575 {
2576 ip_address temp_address, temp_mask;
2577 err_t ugh;
2578
2579 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2580 {
2581 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2582 , which, idtypename);
2583 /* XXX Could send notification back */
2584 return FALSE;
2585 }
2586 ugh = initaddr(id_pbs->cur
2587 , afi->ia_sz, afi->af, &temp_address);
2588 if (ugh == NULL)
2589 {
2590 ugh = initaddr(id_pbs->cur + afi->ia_sz
2591 , afi->ia_sz, afi->af, &temp_mask);
2592 }
2593 if (ugh == NULL)
2594 {
2595 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2596 , '0', net);
2597 }
2598 if (ugh == NULL && subnetisnone(net))
2599 {
2600 ugh = "contains only anyaddr";
2601 }
2602 if (ugh != NULL)
2603 {
2604 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2605 , which, idtypename, ugh);
2606 /* XXX Could send notification back */
2607 return FALSE;
2608 }
2609 DBG(DBG_PARSING | DBG_CONTROL,
2610 {
2611 char temp_buff[SUBNETTOT_BUF];
2612
2613 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2614 DBG_log("%s is subnet %s", which, temp_buff);
2615 });
2616 break;
2617 }
2618
2619 case ID_IPV4_ADDR_RANGE:
2620 case ID_IPV6_ADDR_RANGE:
2621 {
2622 ip_address temp_address_from, temp_address_to;
2623 err_t ugh;
2624
2625 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2626 {
2627 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2628 , which, idtypename);
2629 /* XXX Could send notification back */
2630 return FALSE;
2631 }
2632 ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2633 if (ugh == NULL)
2634 {
2635 ugh = initaddr(id_pbs->cur + afi->ia_sz
2636 , afi->ia_sz, afi->af, &temp_address_to);
2637 }
2638 if (ugh != NULL)
2639 {
2640 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2641 , which, idtypename, ugh);
2642 /* XXX Could send notification back */
2643 return FALSE;
2644 }
2645
2646 ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2647 if (ugh == NULL && subnetisnone(net))
2648 {
2649 ugh = "contains only anyaddr";
2650 }
2651 if (ugh != NULL)
2652 {
2653 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2654
2655 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2656 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2657 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2658 " %s - %s unacceptable: %s"
2659 , which, idtypename, temp_buff1, temp_buff2, ugh);
2660 return FALSE;
2661 }
2662 DBG(DBG_PARSING | DBG_CONTROL,
2663 {
2664 char temp_buff[SUBNETTOT_BUF];
2665
2666 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2667 DBG_log("%s is subnet %s (received as range)"
2668 , which, temp_buff);
2669 });
2670 break;
2671 }
2672 }
2673
2674 /* set the port selector */
2675 setportof(htons(id->isaiid_port), &net->addr);
2676
2677 DBG(DBG_PARSING | DBG_CONTROL,
2678 DBG_log("%s protocol/port is %d/%d", which, id->isaiid_protoid, id->isaiid_port)
2679 )
2680
2681 return TRUE;
2682 }
2683
2684 /* like decode, but checks that what is received matches what was sent */
2685 static bool check_net_id(struct isakmp_ipsec_id *id, pb_stream *id_pbs,
2686 u_int8_t *protoid, u_int16_t *port, ip_subnet *net,
2687 const char *which)
2688 {
2689 ip_subnet net_temp;
2690
2691 if (!decode_net_id(id, id_pbs, &net_temp, which))
2692 {
2693 return FALSE;
2694 }
2695 if (!samesubnet(net, &net_temp)
2696 || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2697 {
2698 loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2699 return FALSE;
2700 }
2701 return TRUE;
2702 }
2703
2704 /*
2705 * look for the existence of a non-expiring preloaded public key
2706 */
2707 static bool has_preloaded_public_key(struct state *st)
2708 {
2709 connection_t *c = st->st_connection;
2710
2711 /* do not consider rw connections since
2712 * the peer's identity must be known
2713 */
2714 if (c->kind == CK_PERMANENT)
2715 {
2716 pubkey_list_t *p;
2717
2718 /* look for a matching RSA public key */
2719 for (p = pubkeys; p != NULL; p = p->next)
2720 {
2721 pubkey_t *key = p->key;
2722 key_type_t type = key->public_key->get_type(key->public_key);
2723
2724 if (type == KEY_RSA &&
2725 c->spd.that.id->equals(c->spd.that.id, key->id) &&
2726 key->until_time == UNDEFINED_TIME)
2727 {
2728 /* found a preloaded public key */
2729 return TRUE;
2730 }
2731 }
2732 }
2733 return FALSE;
2734 }
2735
2736 /*
2737 * Produce the new key material of Quick Mode.
2738 * RFC 2409 "IKE" section 5.5
2739 * specifies how this is to be done.
2740 */
2741 static void compute_proto_keymat(struct state *st, u_int8_t protoid,
2742 struct ipsec_proto_info *pi)
2743 {
2744 size_t needed_len = 0; /* bytes of keying material needed */
2745
2746 /* Add up the requirements for keying material
2747 * (It probably doesn't matter if we produce too much!)
2748 */
2749 switch (protoid)
2750 {
2751 case PROTO_IPSEC_ESP:
2752 {
2753 needed_len = kernel_alg_esp_enc_keylen(pi->attrs.transid);
2754
2755 if (needed_len && pi->attrs.key_len)
2756 {
2757 needed_len = pi->attrs.key_len / BITS_PER_BYTE;
2758 }
2759
2760 switch (pi->attrs.transid)
2761 {
2762 case ESP_NULL:
2763 needed_len = 0;
2764 break;
2765 case ESP_AES_CCM_8:
2766 case ESP_AES_CCM_12:
2767 case ESP_AES_CCM_16:
2768 needed_len += 3;
2769 break;
2770 case ESP_AES_GCM_8:
2771 case ESP_AES_GCM_12:
2772 case ESP_AES_GCM_16:
2773 case ESP_AES_CTR:
2774 case ESP_AES_GMAC:
2775 needed_len += 4;
2776 break;
2777 default:
2778 if (needed_len == 0)
2779 {
2780 bad_case(pi->attrs.transid);
2781 }
2782 }
2783
2784 if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL))
2785 {
2786 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2787 }
2788 else
2789 {
2790 switch (pi->attrs.auth)
2791 {
2792 case AUTH_ALGORITHM_NONE:
2793 break;
2794 case AUTH_ALGORITHM_HMAC_MD5:
2795 needed_len += HMAC_MD5_KEY_LEN;
2796 break;
2797 case AUTH_ALGORITHM_HMAC_SHA1:
2798 needed_len += HMAC_SHA1_KEY_LEN;
2799 break;
2800 case AUTH_ALGORITHM_DES_MAC:
2801 default:
2802 bad_case(pi->attrs.auth);
2803 }
2804 }
2805 break;
2806 }
2807 case PROTO_IPSEC_AH:
2808 {
2809 switch (pi->attrs.transid)
2810 {
2811 case AH_MD5:
2812 needed_len = HMAC_MD5_KEY_LEN;
2813 break;
2814 case AH_SHA:
2815 needed_len = HMAC_SHA1_KEY_LEN;
2816 break;
2817 default:
2818 bad_case(pi->attrs.transid);
2819 }
2820 break;
2821 }
2822 default:
2823 bad_case(protoid);
2824 }
2825
2826 pi->keymat_len = needed_len;
2827
2828 /* Allocate space for the keying material. Although only needed_len bytes
2829 * are desired, we must round up to a multiple of hash_size
2830 * so that our buffer isn't overrun.
2831 */
2832 {
2833 size_t needed_space; /* space needed for keying material (rounded up) */
2834 size_t i, prf_block_size;
2835 chunk_t protoid_chunk = chunk_from_thing(protoid);
2836 chunk_t spi_our = chunk_from_thing(pi->our_spi);
2837 chunk_t spi_peer = chunk_from_thing(pi->attrs.spi);
2838 pseudo_random_function_t prf_alg;
2839 prf_t *prf_our, *prf_peer;
2840
2841 prf_alg = oakley_to_prf(st->st_oakley.hash);
2842 prf_our = lib->crypto->create_prf(lib->crypto, prf_alg);
2843 prf_peer = lib->crypto->create_prf(lib->crypto, prf_alg);
2844 prf_our->set_key(prf_our, st->st_skeyid_d);
2845 prf_peer->set_key(prf_peer, st->st_skeyid_d);
2846 prf_block_size = prf_our->get_block_size(prf_our);
2847
2848 needed_space = needed_len + pad_up(needed_len, prf_block_size);
2849 replace(pi->our_keymat, malloc(needed_space));
2850 replace(pi->peer_keymat, malloc(needed_space));
2851
2852 for (i = 0;; )
2853 {
2854 char *keymat_i_our = pi->our_keymat + i;
2855 char *keymat_i_peer = pi->peer_keymat + i;
2856 chunk_t keymat_our = { keymat_i_our, prf_block_size };
2857 chunk_t keymat_peer = { keymat_i_peer, prf_block_size };
2858
2859 if (st->st_shared.ptr != NULL)
2860 {
2861 /* PFS: include the g^xy */
2862 prf_our->get_bytes(prf_our, st->st_shared, NULL);
2863 prf_peer->get_bytes(prf_peer, st->st_shared, NULL);
2864 }
2865 prf_our->get_bytes(prf_our, protoid_chunk, NULL);
2866 prf_peer->get_bytes(prf_peer, protoid_chunk, NULL);
2867
2868 prf_our->get_bytes(prf_our, spi_our, NULL);
2869 prf_peer->get_bytes(prf_peer, spi_peer, NULL);
2870
2871 prf_our->get_bytes(prf_our, st->st_ni, NULL);
2872 prf_peer->get_bytes(prf_peer, st->st_ni, NULL);
2873
2874 prf_our->get_bytes(prf_our, st->st_nr, keymat_i_our);
2875 prf_peer->get_bytes(prf_peer, st->st_nr, keymat_i_peer);
2876
2877 i += prf_block_size;
2878 if (i >= needed_space)
2879 {
2880 break;
2881 }
2882
2883 /* more keying material needed: prepare to go around again */
2884 prf_our->get_bytes(prf_our, keymat_our, NULL);
2885 prf_peer->get_bytes(prf_peer, keymat_peer, NULL);
2886 }
2887 prf_our->destroy(prf_our);
2888 prf_peer->destroy(prf_peer);
2889 }
2890 DBG(DBG_CRYPT,
2891 DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
2892 DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
2893 }
2894
2895 static void compute_keymats(struct state *st)
2896 {
2897 if (st->st_ah.present)
2898 {
2899 compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
2900 }
2901 if (st->st_esp.present)
2902 {
2903 compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
2904 }
2905 }
2906
2907 static bool uses_pubkey_auth(int auth)
2908 {
2909 switch (auth)
2910 {
2911 case OAKLEY_RSA_SIG:
2912 case OAKLEY_ECDSA_SIG:
2913 case OAKLEY_ECDSA_256:
2914 case OAKLEY_ECDSA_384:
2915 case OAKLEY_ECDSA_521:
2916 case XAUTHInitRSA:
2917 case XAUTHRespRSA:
2918 return TRUE;
2919 default:
2920 return FALSE;
2921 }
2922 }
2923
2924 /* build an ID payload
2925 * Note: no memory is allocated for the body of the payload (tl->ptr).
2926 * We assume it will end up being a pointer into a sufficiently
2927 * stable datastructure. It only needs to last a short time.
2928 */
2929 static void build_id_payload(struct isakmp_ipsec_id *hd, chunk_t *tl, struct end *end)
2930 {
2931 identification_t *id = resolve_myid(end->id);
2932
2933 zero(hd);
2934 hd->isaiid_idtype = id->get_type(id);
2935
2936 switch (id->get_type(id))
2937 {
2938 case ID_ANY:
2939 hd->isaiid_idtype = aftoinfo(addrtypeof(&end->host_addr))->id_addr;
2940 tl->len = addrbytesptr(&end->host_addr,
2941 (const unsigned char **)&tl->ptr); /* sets tl->ptr too */
2942 break;
2943 case ID_IPV4_ADDR:
2944 case ID_IPV6_ADDR:
2945 case ID_FQDN:
2946 case ID_USER_FQDN:
2947 case ID_DER_ASN1_DN:
2948 case ID_KEY_ID:
2949 *tl = id->get_encoding(id);
2950 break;
2951 default:
2952 bad_case(id->get_type(id));
2953 }
2954 }
2955
2956 /* State Transition Functions.
2957 *
2958 * The definition of state_microcode_table in demux.c is a good
2959 * overview of these routines.
2960 *
2961 * - Called from process_packet; result handled by complete_state_transition
2962 * - struct state_microcode member "processor" points to these
2963 * - these routine definitionss are in state order
2964 * - these routines must be restartable from any point of error return:
2965 * beware of memory allocated before any error.
2966 * - output HDR is usually emitted by process_packet (if state_microcode
2967 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2968 *
2969 * The transition functions' functions include:
2970 * - process and judge payloads
2971 * - update st_iv (result of decryption is in st_new_iv)
2972 * - build reply packet
2973 */
2974
2975 /* Handle a Main Mode Oakley first packet (responder side).
2976 * HDR;SA --> HDR;SA
2977 */
2978 stf_status main_inI1_outR1(struct msg_digest *md)
2979 {
2980 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
2981 struct state *st;
2982 connection_t *c;
2983 struct isakmp_proposal proposal;
2984 pb_stream proposal_pbs;
2985 pb_stream r_sa_pbs;
2986 u_int32_t ipsecdoisit;
2987 lset_t policy = LEMPTY;
2988 int vids_to_send = 0;
2989
2990 /* We preparse the peer's proposal in order to determine
2991 * the requested authentication policy (RSA or PSK)
2992 */
2993 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd->payload.sa
2994 , &sa_pd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
2995
2996 backup_pbs(&proposal_pbs);
2997 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2998 , proposal.isap_notrans, &policy));
2999 restore_pbs(&proposal_pbs);
3000
3001 /* We are only considering candidate connections that match
3002 * the requested authentication policy (RSA or PSK)
3003 */
3004 c = find_host_connection(&md->iface->addr, pluto_port
3005 , &md->sender, md->sender_port, policy);
3006
3007 if (c == NULL && md->iface->ike_float)
3008 {
3009 c = find_host_connection(&md->iface->addr, NAT_T_IKE_FLOAT_PORT
3010 , &md->sender, md->sender_port, policy);
3011 }
3012
3013 if (c == NULL)
3014 {
3015 /* See if a wildcarded connection can be found.
3016 * We cannot pick the right connection, so we're making a guess.
3017 * All Road Warrior connections are fair game:
3018 * we pick the first we come across (if any).
3019 * If we don't find any, we pick the first opportunistic
3020 * with the smallest subnet that includes the peer.
3021 * There is, of course, no necessary relationship between
3022 * an Initiator's address and that of its client,
3023 * but Food Groups kind of assumes one.
3024 */
3025 {
3026 connection_t *d;
3027
3028 d = find_host_connection(&md->iface->addr
3029 , pluto_port, (ip_address*)NULL, md->sender_port, policy);
3030
3031 for (; d != NULL; d = d->hp_next)
3032 {
3033 if (d->kind == CK_GROUP)
3034 {
3035 /* ignore */
3036 }
3037 else
3038 {
3039 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO))
3040 {
3041 /* must be Road Warrior: we have a winner */
3042 c = d;
3043 break;
3044 }
3045
3046 /* Opportunistic or Shunt: pick tightest match */
3047 if (addrinsubnet(&md->sender, &d->spd.that.client)
3048 && (c == NULL || !subnetinsubnet(&c->spd.that.client, &d->spd.that.client)))
3049 c = d;
3050 }
3051 }
3052 }
3053
3054 if (c == NULL)
3055 {
3056 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3057 " but no connection has been authorized%s%s"
3058 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr))
3059 , (policy != LEMPTY) ? " with policy=" : ""
3060 , (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : "");
3061 /* XXX notification is in order! */
3062 return STF_IGNORE;
3063 }
3064 else if (c->kind != CK_TEMPLATE)
3065 {
3066 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3067 " but \"%s\" forbids connection"
3068 , ip_str(&md->iface->addr), pluto_port, c->name);
3069 /* XXX notification is in order! */
3070 return STF_IGNORE;
3071 }
3072 else
3073 {
3074 /* Create a temporary connection that is a copy of this one.
3075 * His ID isn't declared yet.
3076 */
3077 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, NULL);
3078 }
3079 }
3080 else if (c->kind == CK_TEMPLATE)
3081 {
3082 /* Create an instance
3083 * This is a rare case: wildcard peer ID but static peer IP address
3084 */
3085 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, c->spd.that.id);
3086 }
3087
3088 /* Set up state */
3089 md->st = st = new_state();
3090 st->st_connection = c;
3091 set_cur_state(st); /* (caller will reset cur_state) */
3092 st->st_try = 0; /* not our job to try again from start */
3093 st->st_policy = c->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
3094
3095 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
3096 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
3097
3098 insert_state(st); /* needs cookies, connection, and msgid (0) */
3099
3100 st->st_doi = ISAKMP_DOI_IPSEC;
3101 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
3102
3103 if ((c->kind == CK_INSTANCE) && (c->spd.that.host_port != pluto_port))
3104 {
3105 plog("responding to Main Mode from unknown peer %s:%u"
3106 , ip_str(&c->spd.that.host_addr), c->spd.that.host_port);
3107 }
3108 else if (c->kind == CK_INSTANCE)
3109 {
3110 plog("responding to Main Mode from unknown peer %s"
3111 , ip_str(&c->spd.that.host_addr));
3112 }
3113 else
3114 {
3115 plog("responding to Main Mode");
3116 }
3117
3118 /* parse_isakmp_sa also spits out a winning SA into our reply,
3119 * so we have to build our md->reply and emit HDR before calling it.
3120 */
3121
3122 /* determine how many Vendor ID payloads we will be sending */
3123 if (SEND_PLUTO_VID)
3124 {
3125 vids_to_send++;
3126 }
3127 if (SEND_CISCO_UNITY_VID)
3128 {
3129 vids_to_send++;
3130 }
3131 if (md->openpgp)
3132 {
3133 vids_to_send++;
3134 }
3135 if (SEND_XAUTH_VID)
3136 {
3137 vids_to_send++;
3138 }
3139 /* always send DPD Vendor ID */
3140 vids_to_send++;
3141 if (md->nat_traversal_vid && nat_traversal_enabled)
3142 {
3143 vids_to_send++;
3144 }
3145
3146 /* HDR out.
3147 * We can't leave this to comm_handle() because we must
3148 * fill in the cookie.
3149 */
3150 {
3151 struct isakmp_hdr r_hdr = md->hdr;
3152
3153 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3154 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3155 r_hdr.isa_np = ISAKMP_NEXT_SA;
3156 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3157 return STF_INTERNAL_ERROR;
3158 }
3159
3160 /* start of SA out */
3161 {
3162 struct isakmp_sa r_sa = sa_pd->payload.sa;
3163
3164 r_sa.isasa_np = vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
3165
3166 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3167 return STF_INTERNAL_ERROR;
3168 }
3169
3170 /* SA body in and out */
3171 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit, &proposal_pbs
3172 ,&proposal, &r_sa_pbs, st, FALSE));
3173
3174 /* if enabled send Pluto Vendor ID */
3175 if (SEND_PLUTO_VID)
3176 {
3177 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3178 , &md->rbody, VID_STRONGSWAN))
3179 {
3180 return STF_INTERNAL_ERROR;
3181 }
3182 }
3183
3184 /* if enabled send Cisco Unity Vendor ID */
3185 if (SEND_CISCO_UNITY_VID)
3186 {
3187 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3188 , &md->rbody, VID_CISCO_UNITY))
3189 {
3190 return STF_INTERNAL_ERROR;
3191 }
3192 }
3193
3194 /*
3195 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3196 */
3197 if (md->openpgp)
3198 {
3199 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3200 , &md->rbody, VID_OPENPGP))
3201 {
3202 return STF_INTERNAL_ERROR;
3203 }
3204 }
3205
3206 /* Announce our ability to do eXtended AUTHentication to the peer */
3207 if (SEND_XAUTH_VID)
3208 {
3209 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3210 , &md->rbody, VID_MISC_XAUTH))
3211 {
3212 return STF_INTERNAL_ERROR;
3213 }
3214 }
3215
3216 /* Announce our ability to do Dead Peer Detection to the peer */
3217 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3218 , &md->rbody, VID_MISC_DPD))
3219 {
3220 return STF_INTERNAL_ERROR;
3221 }
3222
3223 if (md->nat_traversal_vid && nat_traversal_enabled)
3224 {
3225 /* reply if NAT-Traversal draft is supported */
3226 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3227
3228 if (st->nat_traversal
3229 && !out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3230 , &md->rbody, md->nat_traversal_vid))
3231 {
3232 return STF_INTERNAL_ERROR;
3233 }
3234 }
3235
3236 close_message(&md->rbody);
3237
3238 /* save initiator SA for HASH */
3239 free(st->st_p1isa.ptr);
3240 st->st_p1isa = chunk_create(sa_pd->pbs.start, pbs_room(&sa_pd->pbs));
3241 st->st_p1isa = chunk_clone(st->st_p1isa);
3242
3243 return STF_OK;
3244 }
3245
3246 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3247 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3248 *
3249 * The following are not yet implemented:
3250 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3251 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3252 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3253 *
3254 * We must verify that the proposal received matches one we sent.
3255 */
3256 stf_status main_inR1_outI2(struct msg_digest *md)
3257 {
3258 struct state *const st = md->st;
3259
3260 u_int8_t np = ISAKMP_NEXT_NONE;
3261
3262 /* verify echoed SA */
3263 {
3264 u_int32_t ipsecdoisit;
3265 pb_stream proposal_pbs;
3266 struct isakmp_proposal proposal;
3267 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
3268
3269 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd->payload.sa
3270 ,&sapd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
3271 if (proposal.isap_notrans != 1)
3272 {
3273 loglog(RC_LOG_SERIOUS, "a single Transform is required in a selecting Oakley Proposal; found %u"
3274 , (unsigned)proposal.isap_notrans);
3275 RETURN_STF_FAILURE(ISAKMP_BAD_PROPOSAL_SYNTAX);
3276 }
3277 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3278 , &proposal_pbs, &proposal, NULL, st, TRUE));
3279 }
3280
3281 if (nat_traversal_enabled && md->nat_traversal_vid)
3282 {
3283 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3284 plog("enabling possible NAT-traversal with method %s"
3285 , bitnamesof(natt_type_bitnames, st->nat_traversal));
3286 }
3287 if (st->nat_traversal & NAT_T_WITH_NATD)
3288 {
3289 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3290 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3291 }
3292
3293 /**************** build output packet HDR;KE;Ni ****************/
3294
3295 /* HDR out.
3296 * We can't leave this to comm_handle() because the isa_np
3297 * depends on the type of Auth (eventually).
3298 */
3299 echo_hdr(md, FALSE, ISAKMP_NEXT_KE);
3300
3301 /* KE out */
3302 if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group
3303 , &md->rbody, ISAKMP_NEXT_NONCE))
3304 {
3305 return STF_INTERNAL_ERROR;
3306 }
3307
3308 #ifdef DEBUG
3309 /* Ni out */
3310 if (!build_and_ship_nonce(&st->st_ni, &md->rbody
3311 , (cur_debugging & IMPAIR_BUST_MI2)? ISAKMP_NEXT_VID : np, "Ni"))
3312 {
3313 return STF_INTERNAL_ERROR;
3314 }
3315 if (cur_debugging & IMPAIR_BUST_MI2)
3316 {
3317 /* generate a pointless large VID payload to push message over MTU */
3318 pb_stream vid_pbs;
3319
3320 if (!out_generic(np, &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3321 {
3322 return STF_INTERNAL_ERROR;
3323 }
3324 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3325 {
3326 return STF_INTERNAL_ERROR;
3327 }
3328 close_output_pbs(&vid_pbs);
3329 }
3330 #else
3331 /* Ni out */
3332 if (!build_and_ship_nonce(&st->st_ni, &md->rbody, np, "Ni"))
3333 {
3334 return STF_INTERNAL_ERROR;
3335 }
3336 #endif
3337
3338 if (st->nat_traversal & NAT_T_WITH_NATD)
3339 {
3340 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3341 {
3342 return STF_INTERNAL_ERROR;
3343 }
3344 }
3345
3346 /* finish message */
3347 close_message(&md->rbody);
3348
3349 /* Reinsert the state, using the responder cookie we just received */
3350 unhash_state(st);
3351 memcpy(st->st_rcookie, md->hdr.isa_rcookie, COOKIE_SIZE);
3352 insert_state(st); /* needs cookies, connection, and msgid (0) */
3353
3354 return STF_OK;
3355 }
3356
3357 /* STATE_MAIN_R1:
3358 * PSK_AUTH, DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
3359 *
3360 * The following are not yet implemented:
3361 * PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3362 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3363 * RPKE_AUTH:
3364 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3365 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3366 */
3367 stf_status main_inI2_outR2(struct msg_digest *md)
3368 {
3369 struct state *const st = md->st;
3370 pb_stream *keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3371
3372 /* send CR if auth is RSA or ECDSA and no preloaded public key exists*/
3373 bool pubkey_auth = uses_pubkey_auth(st->st_oakley.auth);
3374 bool send_cr = !no_cr_send && pubkey_auth && !has_preloaded_public_key(st);
3375
3376 u_int8_t np = ISAKMP_NEXT_NONE;
3377
3378 /* KE in */
3379 RETURN_STF_FAILURE(accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs));
3380
3381 /* Ni in */
3382 RETURN_STF_FAILURE(accept_nonce(md, &st->st_ni, "Ni"));
3383
3384 if (st->nat_traversal & NAT_T_WITH_NATD)
3385 {
3386 nat_traversal_natd_lookup(md);
3387
3388 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3389 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3390 }
3391 if (st->nat_traversal)
3392 {
3393 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3394 }
3395 if (st->nat_traversal & NAT_T_WITH_KA)
3396 {
3397 nat_traversal_new_ka_event();
3398 }
3399
3400 /* decode certificate requests */
3401 st->st_connection->got_certrequest = FALSE;
3402 decode_cr(md, st->st_connection);
3403
3404 /**************** build output packet HDR;KE;Nr ****************/
3405
3406 /* HDR out done */
3407
3408 /* KE out */
3409 if (!build_and_ship_KE(st, &st->st_gr, st->st_oakley.group
3410 , &md->rbody, ISAKMP_NEXT_NONCE))
3411 {
3412 return STF_INTERNAL_ERROR;
3413 }
3414
3415 #ifdef DEBUG
3416 /* Nr out */
3417 if (!build_and_ship_nonce(&st->st_nr, &md->rbody,
3418 (cur_debugging & IMPAIR_BUST_MR2)? ISAKMP_NEXT_VID
3419 : (send_cr? ISAKMP_NEXT_CR : np), "Nr"))
3420 {
3421 return STF_INTERNAL_ERROR;
3422 }
3423 if (cur_debugging & IMPAIR_BUST_MR2)
3424 {
3425 /* generate a pointless large VID payload to push message over MTU */
3426 pb_stream vid_pbs;
3427
3428 if (!out_generic((send_cr)? ISAKMP_NEXT_CR : np,
3429 &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3430 {
3431 return STF_INTERNAL_ERROR;
3432 }
3433 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3434 {
3435 return STF_INTERNAL_ERROR;
3436 }
3437 close_output_pbs(&vid_pbs);
3438 }
3439 #else
3440 /* Nr out */
3441 if (!build_and_ship_nonce(&st->st_nr, &md->rbody,
3442 (send_cr)? ISAKMP_NEXT_CR : np, "Nr"))
3443 return STF_INTERNAL_ERROR;
3444 #endif
3445
3446 /* CR out */
3447 if (send_cr)
3448 {
3449 if (st->st_connection->kind == CK_PERMANENT)
3450 {
3451 identification_t *ca = st->st_connection->spd.that.ca;
3452 chunk_t cr = (ca) ? ca->get_encoding(ca) : chunk_empty;
3453
3454 if (!build_and_ship_CR(CERT_X509_SIGNATURE, cr, &md->rbody, np))
3455 {
3456 return STF_INTERNAL_ERROR;
3457 }
3458 }
3459 else
3460 {
3461 linked_list_t *list = collect_rw_ca_candidates(md);
3462 int count = list->get_count(list);
3463 bool error = FALSE;
3464
3465 if (count)
3466 {
3467 enumerator_t *enumerator;
3468 identification_t *ca;
3469
3470 enumerator = list->create_enumerator(list);
3471 while (enumerator->enumerate(enumerator, &ca))
3472 {
3473 if (!build_and_ship_CR(CERT_X509_SIGNATURE,
3474 ca->get_encoding(ca), &md->rbody,
3475 --count ? ISAKMP_NEXT_CR : np))
3476 {
3477 error = TRUE;
3478 break;
3479 }
3480 }
3481 enumerator->destroy(enumerator);
3482 }
3483 else
3484 {
3485 if (!build_and_ship_CR(CERT_X509_SIGNATURE, chunk_empty,
3486 &md->rbody, np))
3487 {
3488 error = TRUE;
3489 }
3490 }
3491 list->destroy_offset(list, offsetof(identification_t, destroy));
3492 if (error)
3493 {
3494 return STF_INTERNAL_ERROR;
3495 }
3496 }
3497 }
3498
3499 if (st->nat_traversal & NAT_T_WITH_NATD)
3500 {
3501 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3502 {
3503 return STF_INTERNAL_ERROR;
3504 }
3505 }
3506
3507 /* finish message */
3508 close_message(&md->rbody);
3509
3510 /* next message will be encrypted, but not this one.
3511 * We could defer this calculation.
3512 */
3513 compute_dh_shared(st, st->st_gi);
3514 if (!generate_skeyids_iv(st))
3515 {
3516 return STF_FAIL + ISAKMP_AUTHENTICATION_FAILED;
3517 }
3518 update_iv(st);
3519
3520 return STF_OK;
3521 }
3522
3523 /* STATE_MAIN_I2:
3524 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
3525 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
3526 *
3527 * The following are not yet implemented.
3528 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
3529 * --> HDR*, HASH_I
3530 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
3531 * --> HDR*, HASH_I
3532 */
3533 stf_status main_inR2_outI3(struct msg_digest *md)
3534 {
3535 struct state *const st = md->st;
3536 pb_stream *const keyex_pbs = &md->chain[ISAKMP_NEXT_KE]->pbs;
3537 pb_stream id_pbs; /* ID Payload; also used for hash calculation */
3538
3539 connection_t *c = st->st_connection;
3540 certpolicy_t cert_policy = c->spd.this.sendcert;
3541 cert_t *mycert = c->spd.this.cert;
3542 bool requested, send_cert, send_cr;
3543 bool pubkey_auth = uses_pubkey_auth(st->st_oakley.auth);
3544
3545 int auth_payload = pubkey_auth ? ISAKMP_NEXT_SIG : ISAKMP_NEXT_HASH;
3546
3547 /* KE in */
3548 RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs));
3549
3550 /* Nr in */
3551 RETURN_STF_FAILURE(accept_nonce(md, &st->st_nr, "Nr"));
3552
3553 /* decode certificate requests */
3554 c->got_certrequest = FALSE;
3555 decode_cr(md, c);
3556
3557 /* free collected certificate requests since as initiator
3558 * we don't heed them anyway
3559 */
3560 if (c->requested_ca)
3561 {
3562 c->requested_ca->destroy_offset(c->requested_ca,
3563 offsetof(identification_t, destroy));
3564 c->requested_ca = NULL;
3565 }
3566
3567 /* send certificate if auth is RSA, we have one and we want
3568 * or are requested to send it
3569 */
3570 requested = cert_policy == CERT_SEND_IF_ASKED && c->got_certrequest;
3571 send_cert = pubkey_auth && mycert &&
3572 mycert->cert->get_type(mycert->cert) == CERT_X509 &&
3573 (cert_policy == CERT_ALWAYS_SEND || requested);
3574
3575 /* send certificate request if we don't have a preloaded RSA public key */
3576 send_cr = !no_cr_send && send_cert && !has_preloaded_public_key(st);
3577
3578 /* done parsing; initialize crypto */
3579 compute_dh_shared(st, st->st_gr);
3580 if (!generate_skeyids_iv(st))
3581 {
3582 return STF_FAIL + ISAKMP_AUTHENTICATION_FAILED;
3583 }
3584 if (st->nat_traversal & NAT_T_WITH_NATD)
3585 {
3586 nat_traversal_natd_lookup(md);
3587 }
3588 if (st->nat_traversal)
3589 {
3590 nat_traversal_show_result(st->nat_traversal, md->sender_port);
3591 }
3592 if (st->nat_traversal & NAT_T_WITH_KA)
3593 {
3594 nat_traversal_new_ka_event();
3595 }
3596
3597 /*************** build output packet HDR*;IDii;HASH/SIG_I ***************/
3598 /* ??? NOTE: this is almost the same as main_inI3_outR3's code */
3599
3600 /* HDR* out done */
3601
3602 /* IDii out */
3603 {
3604 struct isakmp_ipsec_id id_hd;
3605 chunk_t id_b;
3606
3607 build_id_payload(&id_hd, &id_b, &c->spd.this);
3608 id_hd.isaiid_np = (send_cert)? ISAKMP_NEXT_CERT : auth_payload;
3609 if (!out_struct(&id_hd, &isakmp_ipsec_identification_desc, &md->rbody, &id_pbs)
3610 || !out_chunk(id_b, &id_pbs, "my identity"))
3611 {
3612 return STF_INTERNAL_ERROR;
3613 }
3614 close_output_pbs(&id_pbs);
3615 }
3616
3617 /* CERT out */
3618 if (pubkey_auth)
3619 {
3620 DBG(DBG_CONTROL,
3621 DBG_log("our certificate policy is %N", cert_policy_names, cert_policy)
3622 )
3623 if (mycert && mycert->cert->get_type(mycert->cert) == CERT_X509)
3624 {
3625 const char *request_text = "";
3626
3627 if (cert_policy == CERT_SEND_IF_ASKED)
3628 {
3629 request_text = (send_cert)? "upon request":"without request";
3630 }
3631 plog("we have a cert %s sending it %s"
3632 , send_cert? "and are":"but are not", request_text);
3633 }
3634 else
3635 {
3636 plog("we don't have a cert");
3637 }
3638 }
3639 if (send_cert)
3640 {
3641 bool success;
3642 chunk_t cert_encoding;
3643 pb_stream cert_pbs;
3644
3645 struct isakmp_cert cert_hd;
3646 cert_hd.isacert_np = (send_cr)? ISAKMP_NEXT_CR : ISAKMP_NEXT_SIG;
3647 cert_hd.isacert_type = CERT_X509_SIGNATURE;
3648
3649 if (!out_struct(&cert_hd, &isakmp_ipsec_certificate_desc, &md->rbody, &cert_pbs))
3650 {
3651 return STF_INTERNAL_ERROR;
3652 }
3653 cert_encoding = mycert->cert->get_encoding(mycert->cert);
3654 success = out_chunk(cert_encoding, &cert_pbs, "CERT");
3655 free(cert_encoding.ptr);
3656 if (!success)
3657 {
3658 return STF_INTERNAL_ERROR;
3659 }
3660 close_output_pbs(&cert_pbs);
3661 }
3662
3663 /* CR out */
3664 if (send_cr)
3665 {
3666 identification_t *ca = st->st_connection->spd.that.ca;
3667 chunk_t cr = (ca) ? ca->get_encoding(ca) : chunk_empty;
3668
3669 if (!build_and_ship_CR(CERT_X509_SIGNATURE, cr, &md->rbody, ISAKMP_NEXT_SIG))
3670 {
3671 return STF_INTERNAL_ERROR;
3672 }
3673 }
3674
3675 /* HASH_I or SIG_I out */
3676 {
3677 chunk_t hash = chunk_alloca(MAX_DIGEST_LEN);
3678
3679 main_mode_hash(st, &hash, TRUE, &id_pbs);
3680
3681 if (auth_payload == ISAKMP_NEXT_HASH)
3682 {
3683 /* HASH_I out */
3684 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_hash_desc, &md->rbody,
3685 hash.ptr, hash.len, "HASH_I"))
3686 {
3687 return STF_INTERNAL_ERROR;
3688 }
3689 }
3690 else
3691 {
3692 /* SIG_I out */
3693 u_char sig_val[RSA_MAX_OCTETS];
3694 signature_scheme_t scheme;
3695 size_t sig_len;
3696
3697 scheme = oakley_to_signature_scheme(st->st_oakley.auth);
3698
3699 sig_len = sign_hash(scheme, c, sig_val, hash);
3700 if (sig_len == 0)
3701 {
3702 loglog(RC_LOG_SERIOUS, "unable to locate my private key for signature");
3703 return STF_FAIL + ISAKMP_AUTHENTICATION_FAILED;
3704 }
3705
3706 if (!out_generic_raw(ISAKMP_NEXT_NONE, &isakmp_signature_desc
3707 , &md->rbody, sig_val, sig_len, "SIG_I"))
3708 {
3709 return STF_INTERNAL_ERROR;
3710 }
3711 }
3712 }
3713
3714 /* encrypt message, except for fixed part of header */