refactoring of Mode Config functionality allows transport and handling of any attribute
[strongswan.git] / src / pluto / ipsec_doi.c
1 /* IPsec DOI and Oakley resolution routines
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
4 * Copyright (C) 2009 Andreas Steffen - Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 */
16
17 #include <stdio.h>
18 #include <string.h>
19 #include <stddef.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
25 #include <resolv.h>
26 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
27 #include <sys/queue.h>
28
29 #include <freeswan.h>
30
31 #include <library.h>
32 #include <asn1/asn1.h>
33 #include <crypto/hashers/hasher.h>
34 #include <crypto/prfs/prf.h>
35 #include <crypto/rngs/rng.h>
36 #include <credentials/keys/private_key.h>
37 #include <credentials/keys/public_key.h>
38 #include <utils/identification.h>
39
40 #include "constants.h"
41 #include "defs.h"
42 #include "myid.h"
43 #include "state.h"
44 #include "x509.h"
45 #include "ac.h"
46 #include "crl.h"
47 #include "ca.h"
48 #include "certs.h"
49 #include "smartcard.h"
50 #include "connections.h"
51 #include "keys.h"
52 #include "packet.h"
53 #include "demux.h" /* needs packet.h */
54 #include "adns.h" /* needs <resolv.h> */
55 #include "dnskey.h" /* needs keys.h and adns.h */
56 #include "kernel.h"
57 #include "log.h"
58 #include "cookie.h"
59 #include "server.h"
60 #include "spdb.h"
61 #include "timer.h"
62 #include "ipsec_doi.h" /* needs demux.h and state.h */
63 #include "whack.h"
64 #include "fetch.h"
65 #include "pkcs7.h"
66 #include "crypto.h"
67 #include "vendor.h"
68 #include "alg_info.h"
69 #include "ike_alg.h"
70 #include "kernel_alg.h"
71 #include "nat_traversal.h"
72 #include "virtual.h"
73
74 /*
75 * are we sending Pluto's Vendor ID?
76 */
77 #ifdef VENDORID
78 #define SEND_PLUTO_VID 1
79 #else /* !VENDORID */
80 #define SEND_PLUTO_VID 0
81 #endif /* !VENDORID */
82
83 /*
84 * are we sending an XAUTH VID?
85 */
86 #ifdef XAUTH_VID
87 #define SEND_XAUTH_VID 1
88 #else /* !XAUTH_VID */
89 #define SEND_XAUTH_VID 0
90 #endif /* !XAUTH_VID */
91
92 /*
93 * are we sending a Cisco Unity VID?
94 */
95 #ifdef CISCO_QUIRKS
96 #define SEND_CISCO_UNITY_VID 1
97 #else /* !CISCO_QUIRKS */
98 #define SEND_CISCO_UNITY_VID 0
99 #endif /* !CISCO_QUIRKS */
100
101 /* MAGIC: perform f, a function that returns notification_t
102 * and return from the ENCLOSING stf_status returning function if it fails.
103 */
104 #define RETURN_STF_FAILURE(f) \
105 { int r = (f); if (r != ISAKMP_NOTHING_WRONG) return STF_FAIL + r; }
106
107 /* create output HDR as replica of input HDR */
108 void echo_hdr(struct msg_digest *md, bool enc, u_int8_t np)
109 {
110 struct isakmp_hdr r_hdr = md->hdr; /* mostly same as incoming header */
111
112 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
113 if (enc)
114 {
115 r_hdr.isa_flags |= ISAKMP_FLAG_ENCRYPTION;
116 }
117 /* some day, we may have to set r_hdr.isa_version */
118 r_hdr.isa_np = np;
119 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
120 {
121 impossible(); /* surely must have room and be well-formed */
122 }
123 }
124
125 /* Compute DH shared secret from our local secret and the peer's public value.
126 * We make the leap that the length should be that of the group
127 * (see quoted passage at start of ACCEPT_KE).
128 */
129 static void compute_dh_shared(struct state *st, const chunk_t g)
130 {
131 passert(st->st_dh);
132 st->st_dh->set_other_public_value(st->st_dh, g);
133 st->st_dh->get_shared_secret(st->st_dh, &st->st_shared);
134 DBG_cond_dump_chunk(DBG_CRYPT, "DH shared secret:\n", st->st_shared);
135 }
136
137 /* if we haven't already done so, compute a local DH secret (st->st_sec) and
138 * the corresponding public value (g). This is emitted as a KE payload.
139 */
140 static bool build_and_ship_KE(struct state *st, chunk_t *g,
141 const struct dh_desc *group,
142 pb_stream *outs, u_int8_t np)
143 {
144 if (st->st_dh == NULL)
145 {
146 st->st_dh = lib->crypto->create_dh(lib->crypto, group->algo_id);
147 if (st->st_dh == NULL)
148 {
149 plog("Diffie Hellman group %N is not available",
150 diffie_hellman_group_names, group->algo_id);
151 return FALSE;
152 }
153 }
154 st->st_dh->get_my_public_value(st->st_dh, g);
155 DBG(DBG_CRYPT,
156 DBG_dump_chunk("Public DH value sent:\n", *g)
157 )
158 return out_generic_chunk(np, &isakmp_keyex_desc, outs, *g, "keyex value");
159 }
160
161 /* accept_ke
162 *
163 * Check and accept DH public value (Gi or Gr) from peer's message.
164 * According to RFC2409 "The Internet key exchange (IKE)" 5:
165 * The Diffie-Hellman public value passed in a KE payload, in either
166 * a phase 1 or phase 2 exchange, MUST be the length of the negotiated
167 * Diffie-Hellman group enforced, if necessary, by pre-pending the
168 * value with zeros.
169 */
170 static notification_t accept_KE(chunk_t *dest, const char *val_name,
171 const struct dh_desc *gr,
172 pb_stream *pbs)
173 {
174 if (pbs_left(pbs) != gr->ke_size)
175 {
176 loglog(RC_LOG_SERIOUS, "KE has %u byte DH public value; %u required"
177 , (unsigned) pbs_left(pbs), gr->ke_size);
178 /* XXX Could send notification back */
179 return ISAKMP_INVALID_KEY_INFORMATION;
180 }
181 free(dest->ptr);
182 *dest = chunk_create(pbs->cur, pbs_left(pbs));
183 *dest = chunk_clone(*dest);
184 DBG_cond_dump_chunk(DBG_CRYPT, "DH public value received:\n", *dest);
185 return ISAKMP_NOTHING_WRONG;
186 }
187
188 /* accept_PFS_KE
189 *
190 * Check and accept optional Quick Mode KE payload for PFS.
191 * Extends ACCEPT_PFS to check whether KE is allowed or required.
192 */
193 static notification_t accept_PFS_KE(struct msg_digest *md, chunk_t *dest,
194 const char *val_name, const char *msg_name)
195 {
196 struct state *st = md->st;
197 struct payload_digest *const ke_pd = md->chain[ISAKMP_NEXT_KE];
198
199 if (ke_pd == NULL)
200 {
201 if (st->st_pfs_group != NULL)
202 {
203 loglog(RC_LOG_SERIOUS, "missing KE payload in %s message", msg_name);
204 return ISAKMP_INVALID_KEY_INFORMATION;
205 }
206 }
207 else
208 {
209 if (st->st_pfs_group == NULL)
210 {
211 loglog(RC_LOG_SERIOUS, "%s message KE payload requires a GROUP_DESCRIPTION attribute in SA"
212 , msg_name);
213 return ISAKMP_INVALID_KEY_INFORMATION;
214 }
215 if (ke_pd->next != NULL)
216 {
217 loglog(RC_LOG_SERIOUS, "%s message contains several KE payloads; we accept at most one", msg_name);
218 return ISAKMP_INVALID_KEY_INFORMATION; /* ??? */
219 }
220 return accept_KE(dest, val_name, st->st_pfs_group, &ke_pd->pbs);
221 }
222 return ISAKMP_NOTHING_WRONG;
223 }
224
225 static bool build_and_ship_nonce(chunk_t *n, pb_stream *outs, u_int8_t np,
226 const char *name)
227 {
228 rng_t *rng;
229
230 free(n->ptr);
231 *n = chunk_create(malloc(DEFAULT_NONCE_SIZE), DEFAULT_NONCE_SIZE);
232 rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
233 rng->get_bytes(rng, DEFAULT_NONCE_SIZE, n->ptr);
234 rng->destroy(rng);
235 return out_generic_chunk(np, &isakmp_nonce_desc, outs, *n, name);
236 }
237
238 static linked_list_t* collect_rw_ca_candidates(struct msg_digest *md)
239 {
240 linked_list_t *list = linked_list_create();
241 connection_t *d;
242
243 d = find_host_connection(&md->iface->addr, pluto_port, (ip_address*)NULL,
244 md->sender_port, LEMPTY);
245
246 for (; d != NULL; d = d->hp_next)
247 {
248 /* must be a road warrior connection */
249 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO) &&
250 d->spd.that.ca)
251 {
252 enumerator_t *enumerator;
253 identification_t *ca;
254 bool new_entry = TRUE;
255
256 enumerator = list->create_enumerator(list);
257 while (enumerator->enumerate(enumerator, &ca))
258 {
259 if (ca->equals(ca, d->spd.that.ca))
260 {
261 new_entry = FALSE;
262 break;
263 }
264 }
265 enumerator->destroy(enumerator);
266
267 if (new_entry)
268 {
269 list->insert_last(list, d->spd.that.ca->clone(d->spd.that.ca));
270 }
271 }
272 }
273 return list;
274 }
275
276 static bool build_and_ship_CR(u_int8_t type, chunk_t ca, pb_stream *outs,
277 u_int8_t np)
278 {
279 pb_stream cr_pbs;
280 struct isakmp_cr cr_hd;
281 cr_hd.isacr_np = np;
282 cr_hd.isacr_type = type;
283
284 /* build CR header */
285 if (!out_struct(&cr_hd, &isakmp_ipsec_cert_req_desc, outs, &cr_pbs))
286 {
287 return FALSE;
288 }
289 if (ca.ptr != NULL)
290 {
291 /* build CR body containing the distinguished name of the CA */
292 if (!out_chunk(ca, &cr_pbs, "CA"))
293 return FALSE;
294 }
295 close_output_pbs(&cr_pbs);
296 return TRUE;
297 }
298
299 /* Send a notification to the peer. We could decide
300 * whether to send the notification, based on the type and the
301 * destination, if we care to.
302 */
303 static void send_notification(struct state *sndst, u_int16_t type,
304 struct state *encst, msgid_t msgid,
305 u_char *icookie, u_char *rcookie,
306 u_char *spi, size_t spisize, u_char protoid)
307 {
308 u_char buffer[1024];
309 pb_stream pbs, r_hdr_pbs;
310 u_char *r_hashval = NULL; /* where in reply to jam hash value */
311 u_char *r_hash_start = NULL; /* start of what is to be hashed */
312
313 passert((sndst) && (sndst->st_connection));
314
315 plog("sending %snotification %s to %s:%u"
316 , encst ? "encrypted " : ""
317 , enum_name(&notification_names, type)
318 , ip_str(&sndst->st_connection->spd.that.host_addr)
319 , (unsigned)sndst->st_connection->spd.that.host_port);
320
321 memset(buffer, 0, sizeof(buffer));
322 init_pbs(&pbs, buffer, sizeof(buffer), "ISAKMP notify");
323
324 /* HDR* */
325 {
326 struct isakmp_hdr hdr;
327
328 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
329 hdr.isa_np = encst ? ISAKMP_NEXT_HASH : ISAKMP_NEXT_N;
330 hdr.isa_xchg = ISAKMP_XCHG_INFO;
331 hdr.isa_msgid = msgid;
332 hdr.isa_flags = encst ? ISAKMP_FLAG_ENCRYPTION : 0;
333 if (icookie)
334 {
335 memcpy(hdr.isa_icookie, icookie, COOKIE_SIZE);
336 }
337 if (rcookie)
338 {
339 memcpy(hdr.isa_rcookie, rcookie, COOKIE_SIZE);
340 }
341 if (!out_struct(&hdr, &isakmp_hdr_desc, &pbs, &r_hdr_pbs))
342 {
343 impossible();
344 }
345 }
346
347 /* HASH -- value to be filled later */
348 if (encst)
349 {
350 pb_stream hash_pbs;
351 if (!out_generic(ISAKMP_NEXT_N, &isakmp_hash_desc, &r_hdr_pbs, &hash_pbs))
352 {
353 impossible();
354 }
355 r_hashval = hash_pbs.cur; /* remember where to plant value */
356 if (!out_zero(
357 encst->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH"))
358 {
359 impossible();
360 }
361 close_output_pbs(&hash_pbs);
362 r_hash_start = r_hdr_pbs.cur; /* hash from after HASH */
363 }
364
365 /* Notification Payload */
366 {
367 pb_stream not_pbs;
368 struct isakmp_notification isan;
369
370 isan.isan_doi = ISAKMP_DOI_IPSEC;
371 isan.isan_np = ISAKMP_NEXT_NONE;
372 isan.isan_type = type;
373 isan.isan_spisize = spisize;
374 isan.isan_protoid = protoid;
375
376 if (!out_struct(&isan, &isakmp_notification_desc, &r_hdr_pbs, &not_pbs)
377 || !out_raw(spi, spisize, &not_pbs, "spi"))
378 {
379 impossible();
380 }
381 close_output_pbs(&not_pbs);
382 }
383
384 /* calculate hash value and patch into Hash Payload */
385 if (encst)
386 {
387 chunk_t msgid_chunk = chunk_from_thing(msgid);
388 chunk_t msg_chunk = { r_hash_start, r_hdr_pbs.cur-r_hash_start };
389 pseudo_random_function_t prf_alg;
390 prf_t *prf;
391
392 prf_alg = oakley_to_prf(encst->st_oakley.hash);
393 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
394 prf->set_key(prf, encst->st_skeyid_a);
395 prf->get_bytes(prf, msgid_chunk, NULL);
396 prf->get_bytes(prf, msg_chunk, r_hashval);
397
398 DBG(DBG_CRYPT,
399 DBG_log("HASH computed:");
400 DBG_dump("", r_hashval, prf->get_block_size(prf));
401 )
402 prf->destroy(prf);
403 }
404
405 /* Encrypt message (preserve st_iv and st_new_iv) */
406 if (encst)
407 {
408 u_char old_iv[MAX_DIGEST_LEN];
409 u_char new_iv[MAX_DIGEST_LEN];
410
411 u_int old_iv_len = encst->st_iv_len;
412 u_int new_iv_len = encst->st_new_iv_len;
413
414 if (old_iv_len > MAX_DIGEST_LEN || new_iv_len > MAX_DIGEST_LEN)
415 {
416 impossible();
417 }
418 memcpy(old_iv, encst->st_iv, old_iv_len);
419 memcpy(new_iv, encst->st_new_iv, new_iv_len);
420
421 if (!IS_ISAKMP_SA_ESTABLISHED(encst->st_state))
422 {
423 memcpy(encst->st_ph1_iv, encst->st_new_iv, encst->st_new_iv_len);
424 encst->st_ph1_iv_len = encst->st_new_iv_len;
425 }
426 init_phase2_iv(encst, &msgid);
427 if (!encrypt_message(&r_hdr_pbs, encst))
428 {
429 impossible();
430 }
431
432 /* restore preserved st_iv and st_new_iv */
433 memcpy(encst->st_iv, old_iv, old_iv_len);
434 memcpy(encst->st_new_iv, new_iv, new_iv_len);
435 encst->st_iv_len = old_iv_len;
436 encst->st_new_iv_len = new_iv_len;
437 }
438 else
439 {
440 close_output_pbs(&r_hdr_pbs);
441 }
442
443 /* Send packet (preserve st_tpacket) */
444 {
445 chunk_t saved_tpacket = sndst->st_tpacket;
446
447 sndst->st_tpacket = chunk_create(pbs.start, pbs_offset(&pbs));
448 send_packet(sndst, "ISAKMP notify");
449 sndst->st_tpacket = saved_tpacket;
450 }
451 }
452
453 void send_notification_from_state(struct state *st, enum state_kind state,
454 u_int16_t type)
455 {
456 struct state *p1st;
457
458 passert(st);
459
460 if (state == STATE_UNDEFINED)
461 state = st->st_state;
462
463 if (IS_QUICK(state))
464 {
465 p1st = find_phase1_state(st->st_connection, ISAKMP_SA_ESTABLISHED_STATES);
466 if ((p1st == NULL) || (!IS_ISAKMP_SA_ESTABLISHED(p1st->st_state)))
467 {
468 loglog(RC_LOG_SERIOUS,
469 "no Phase1 state for Quick mode notification");
470 return;
471 }
472 send_notification(st, type, p1st, generate_msgid(p1st),
473 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
474 }
475 else if (IS_ISAKMP_ENCRYPTED(state) && st->st_enc_key.ptr != NULL)
476 {
477 send_notification(st, type, st, generate_msgid(st),
478 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
479 }
480 else
481 {
482 /* no ISAKMP SA established - don't encrypt notification */
483 send_notification(st, type, NULL, 0,
484 st->st_icookie, st->st_rcookie, NULL, 0, PROTO_ISAKMP);
485 }
486 }
487
488 void send_notification_from_md(struct msg_digest *md, u_int16_t type)
489 {
490 /**
491 * Create a dummy state to be able to use send_packet in
492 * send_notification
493 *
494 * we need to set:
495 * st_connection->that.host_addr
496 * st_connection->that.host_port
497 * st_connection->interface
498 */
499 struct state st;
500 connection_t cnx;
501
502 passert(md);
503
504 memset(&st, 0, sizeof(st));
505 memset(&cnx, 0, sizeof(cnx));
506 st.st_connection = &cnx;
507 cnx.spd.that.host_addr = md->sender;
508 cnx.spd.that.host_port = md->sender_port;
509 cnx.interface = md->iface;
510
511 send_notification(&st, type, NULL, 0,
512 md->hdr.isa_icookie, md->hdr.isa_rcookie, NULL, 0, PROTO_ISAKMP);
513 }
514
515 /* Send a Delete Notification to announce deletion of ISAKMP SA or
516 * inbound IPSEC SAs. Does nothing if no such SAs are being deleted.
517 * Delete Notifications cannot announce deletion of outbound IPSEC/ISAKMP SAs.
518 */
519 void send_delete(struct state *st)
520 {
521 pb_stream reply_pbs;
522 pb_stream r_hdr_pbs;
523 msgid_t msgid;
524 u_char buffer[8192];
525 struct state *p1st;
526 ip_said said[EM_MAXRELSPIS];
527 ip_said *ns = said;
528 u_char
529 *r_hashval, /* where in reply to jam hash value */
530 *r_hash_start; /* start of what is to be hashed */
531 bool isakmp_sa = FALSE;
532
533 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
534 {
535 p1st = find_phase1_state(st->st_connection, ISAKMP_SA_ESTABLISHED_STATES);
536 if (p1st == NULL)
537 {
538 DBG(DBG_CONTROL, DBG_log("no Phase 1 state for Delete"));
539 return;
540 }
541
542 if (st->st_ah.present)
543 {
544 ns->spi = st->st_ah.our_spi;
545 ns->dst = st->st_connection->spd.this.host_addr;
546 ns->proto = PROTO_IPSEC_AH;
547 ns++;
548 }
549 if (st->st_esp.present)
550 {
551 ns->spi = st->st_esp.our_spi;
552 ns->dst = st->st_connection->spd.this.host_addr;
553 ns->proto = PROTO_IPSEC_ESP;
554 ns++;
555 }
556
557 passert(ns != said); /* there must be some SAs to delete */
558 }
559 else if (IS_ISAKMP_SA_ESTABLISHED(st->st_state))
560 {
561 p1st = st;
562 isakmp_sa = TRUE;
563 }
564 else
565 {
566 return; /* nothing to do */
567 }
568
569 msgid = generate_msgid(p1st);
570
571 zero(buffer);
572 init_pbs(&reply_pbs, buffer, sizeof(buffer), "delete msg");
573
574 /* HDR* */
575 {
576 struct isakmp_hdr hdr;
577
578 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
579 hdr.isa_np = ISAKMP_NEXT_HASH;
580 hdr.isa_xchg = ISAKMP_XCHG_INFO;
581 hdr.isa_msgid = msgid;
582 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
583 memcpy(hdr.isa_icookie, p1st->st_icookie, COOKIE_SIZE);
584 memcpy(hdr.isa_rcookie, p1st->st_rcookie, COOKIE_SIZE);
585 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply_pbs, &r_hdr_pbs))
586 impossible();
587 }
588
589 /* HASH -- value to be filled later */
590 {
591 pb_stream hash_pbs;
592
593 if (!out_generic(ISAKMP_NEXT_D, &isakmp_hash_desc, &r_hdr_pbs, &hash_pbs))
594 {
595 impossible();
596 }
597 r_hashval = hash_pbs.cur; /* remember where to plant value */
598 if (!out_zero(p1st->st_oakley.hasher->hash_digest_size, &hash_pbs, "HASH(1)"))
599 {
600 impossible();
601 }
602 close_output_pbs(&hash_pbs);
603 r_hash_start = r_hdr_pbs.cur; /* hash from after HASH(1) */
604 }
605
606 /* Delete Payloads */
607 if (isakmp_sa)
608 {
609 pb_stream del_pbs;
610 struct isakmp_delete isad;
611 u_char isakmp_spi[2*COOKIE_SIZE];
612
613 isad.isad_doi = ISAKMP_DOI_IPSEC;
614 isad.isad_np = ISAKMP_NEXT_NONE;
615 isad.isad_spisize = (2 * COOKIE_SIZE);
616 isad.isad_protoid = PROTO_ISAKMP;
617 isad.isad_nospi = 1;
618
619 memcpy(isakmp_spi, st->st_icookie, COOKIE_SIZE);
620 memcpy(isakmp_spi+COOKIE_SIZE, st->st_rcookie, COOKIE_SIZE);
621
622 if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
623 || !out_raw(&isakmp_spi, (2*COOKIE_SIZE), &del_pbs, "delete payload"))
624 {
625 impossible();
626 }
627 close_output_pbs(&del_pbs);
628 }
629 else
630 {
631 while (ns != said)
632 {
633
634 pb_stream del_pbs;
635 struct isakmp_delete isad;
636
637 ns--;
638 isad.isad_doi = ISAKMP_DOI_IPSEC;
639 isad.isad_np = ns == said? ISAKMP_NEXT_NONE : ISAKMP_NEXT_D;
640 isad.isad_spisize = sizeof(ipsec_spi_t);
641 isad.isad_protoid = ns->proto;
642
643 isad.isad_nospi = 1;
644 if (!out_struct(&isad, &isakmp_delete_desc, &r_hdr_pbs, &del_pbs)
645 || !out_raw(&ns->spi, sizeof(ipsec_spi_t), &del_pbs, "delete payload"))
646 {
647 impossible();
648 }
649 close_output_pbs(&del_pbs);
650 }
651 }
652
653 /* calculate hash value and patch into Hash Payload */
654 {
655 chunk_t msgid_chunk = chunk_from_thing(msgid);
656 chunk_t msg_chunk = { r_hash_start, r_hdr_pbs.cur-r_hash_start };
657 pseudo_random_function_t prf_alg;
658 prf_t *prf;
659
660 prf_alg = oakley_to_prf(p1st->st_oakley.hash);
661 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
662 prf->set_key(prf, p1st->st_skeyid_a);
663 prf->get_bytes(prf, msgid_chunk, NULL);
664 prf->get_bytes(prf, msg_chunk, r_hashval);
665
666 DBG(DBG_CRYPT,
667 DBG_log("HASH(1) computed:");
668 DBG_dump("", r_hashval, prf->get_block_size(prf));
669 )
670
671 prf->destroy(prf);
672 }
673
674 /* Do a dance to avoid needing a new state object.
675 * We use the Phase 1 State. This is the one with right
676 * IV, for one thing.
677 * The tricky bits are:
678 * - we need to preserve (save/restore) st_iv (but not st_iv_new)
679 * - we need to preserve (save/restore) st_tpacket.
680 */
681 {
682 u_char old_iv[MAX_DIGEST_LEN];
683 chunk_t saved_tpacket = p1st->st_tpacket;
684
685 memcpy(old_iv, p1st->st_iv, p1st->st_iv_len);
686 init_phase2_iv(p1st, &msgid);
687
688 if (!encrypt_message(&r_hdr_pbs, p1st))
689 {
690 impossible();
691 }
692 p1st->st_tpacket = chunk_create(reply_pbs.start, pbs_offset(&reply_pbs));
693 send_packet(p1st, "delete notify");
694 p1st->st_tpacket = saved_tpacket;
695
696 /* get back old IV for this state */
697 memcpy(p1st->st_iv, old_iv, p1st->st_iv_len);
698 }
699 }
700
701 void accept_delete(struct state *st, struct msg_digest *md,
702 struct payload_digest *p)
703 {
704 struct isakmp_delete *d = &(p->payload.delete);
705 identification_t *this_id = NULL, *that_id = NULL;
706 ip_address peer_addr;
707 size_t sizespi;
708 int i;
709
710 if (!md->encrypted)
711 {
712 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: not encrypted");
713 return;
714 }
715
716 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
717 {
718 /* can't happen (if msg is encrypt), but just to be sure */
719 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
720 "ISAKMP SA not established");
721 return;
722 }
723
724 if (d->isad_nospi == 0)
725 {
726 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: no SPI");
727 return;
728 }
729
730 switch (d->isad_protoid)
731 {
732 case PROTO_ISAKMP:
733 sizespi = 2 * COOKIE_SIZE;
734 break;
735 case PROTO_IPSEC_AH:
736 case PROTO_IPSEC_ESP:
737 sizespi = sizeof(ipsec_spi_t);
738 break;
739 case PROTO_IPCOMP:
740 /* nothing interesting to delete */
741 return;
742 default:
743 loglog(RC_LOG_SERIOUS
744 , "ignoring Delete SA payload: unknown Protocol ID (%s)"
745 , enum_show(&protocol_names, d->isad_protoid));
746 return;
747 }
748
749 if (d->isad_spisize != sizespi)
750 {
751 loglog(RC_LOG_SERIOUS
752 , "ignoring Delete SA payload: bad SPI size (%d) for %s"
753 , d->isad_spisize, enum_show(&protocol_names, d->isad_protoid));
754 return;
755 }
756
757 if (pbs_left(&p->pbs) != d->isad_nospi * sizespi)
758 {
759 loglog(RC_LOG_SERIOUS
760 , "ignoring Delete SA payload: invalid payload size");
761 return;
762 }
763
764 if (d->isad_protoid == PROTO_ISAKMP)
765 {
766 struct end *this = &st->st_connection->spd.this;
767 struct end *that = &st->st_connection->spd.that;
768 this_id = this->id->clone(this->id);
769 that_id = that->id->clone(that->id);
770 peer_addr = st->st_connection->spd.that.host_addr;
771 }
772
773 for (i = 0; i < d->isad_nospi; i++)
774 {
775 u_char *spi = p->pbs.cur + (i * sizespi);
776
777 if (d->isad_protoid == PROTO_ISAKMP)
778 {
779 /**
780 * ISAKMP
781 */
782 struct state *dst = find_state(spi /*iCookie*/
783 , spi+COOKIE_SIZE /*rCookie*/
784 , &peer_addr
785 , MAINMODE_MSGID);
786
787 if (dst == NULL)
788 {
789 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
790 "ISAKMP SA not found (maybe expired)");
791 }
792 else if (! this_id->equals(this_id, dst->st_connection->spd.this.id) ||
793 ! that_id->equals(that_id, dst->st_connection->spd.that.id))
794 {
795 /* we've not authenticated the relevant identities */
796 loglog(RC_LOG_SERIOUS, "ignoring Delete SA payload: "
797 "ISAKMP SA used to convey Delete has different IDs from ISAKMP SA it deletes");
798 }
799 else
800 {
801 connection_t *oldc;
802
803 oldc = cur_connection;
804 set_cur_connection(dst->st_connection);
805
806 if (nat_traversal_enabled)
807 {
808 nat_traversal_change_port_lookup(md, dst);
809 }
810 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
811 "deleting ISAKMP State #%lu", dst->st_serialno);
812 delete_state(dst);
813 set_cur_connection(oldc);
814 }
815 }
816 else
817 {
818 /**
819 * IPSEC (ESP/AH)
820 */
821 bool bogus;
822 struct state *dst = find_phase2_state_to_delete(st
823 , d->isad_protoid
824 , *(ipsec_spi_t *)spi /* network order */
825 , &bogus);
826
827 if (dst == NULL)
828 {
829 loglog(RC_LOG_SERIOUS
830 , "ignoring Delete SA payload: %s SA(0x%08lx) not found (%s)"
831 , enum_show(&protocol_names, d->isad_protoid)
832 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t *)spi)
833 , bogus ? "our SPI - bogus implementation" : "maybe expired");
834 }
835 else
836 {
837 connection_t *rc = dst->st_connection;
838 connection_t *oldc;
839
840 oldc = cur_connection;
841 set_cur_connection(rc);
842
843 if (nat_traversal_enabled)
844 {
845 nat_traversal_change_port_lookup(md, dst);
846 }
847 if (rc->newest_ipsec_sa == dst->st_serialno
848 && (rc->policy & POLICY_UP))
849 {
850 /* Last IPSec SA for a permanent connection that we
851 * have initiated. Replace it in a few seconds.
852 *
853 * Useful if the other peer is rebooting.
854 */
855 #define DELETE_SA_DELAY EVENT_RETRANSMIT_DELAY_0
856 if (dst->st_event != NULL
857 && dst->st_event->ev_type == EVENT_SA_REPLACE
858 && dst->st_event->ev_time <= DELETE_SA_DELAY + now())
859 {
860 /* Patch from Angus Lees to ignore retransmited
861 * Delete SA.
862 */
863 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
864 "already replacing IPSEC State #%lu in %d seconds"
865 , dst->st_serialno, (int)(dst->st_event->ev_time - now()));
866 }
867 else
868 {
869 loglog(RC_LOG_SERIOUS, "received Delete SA payload: "
870 "replace IPSEC State #%lu in %d seconds"
871 , dst->st_serialno, DELETE_SA_DELAY);
872 dst->st_margin = DELETE_SA_DELAY;
873 delete_event(dst);
874 event_schedule(EVENT_SA_REPLACE, DELETE_SA_DELAY, dst);
875 }
876 }
877 else
878 {
879 loglog(RC_LOG_SERIOUS, "received Delete SA(0x%08lx) payload: "
880 "deleting IPSEC State #%lu"
881 , (unsigned long)ntohl((unsigned long)*(ipsec_spi_t *)spi)
882 , dst->st_serialno);
883 delete_state(dst);
884 }
885
886 /* reset connection */
887 set_cur_connection(oldc);
888 }
889 }
890 }
891
892 if (d->isad_protoid == PROTO_ISAKMP)
893 {
894 this_id->destroy(this_id);
895 that_id->destroy(that_id);
896 }
897 }
898
899 /* The whole message must be a multiple of 4 octets.
900 * I'm not sure where this is spelled out, but look at
901 * rfc2408 3.6 Transform Payload.
902 * Note: it talks about 4 BYTE boundaries!
903 */
904 void close_message(pb_stream *pbs)
905 {
906 size_t padding = pad_up(pbs_offset(pbs), 4);
907
908 if (padding != 0)
909 {
910 (void) out_zero(padding, pbs, "message padding");
911 }
912 close_output_pbs(pbs);
913 }
914
915 /* Initiate an Oakley Main Mode exchange.
916 * --> HDR;SA
917 * Note: this is not called from demux.c
918 */
919 static stf_status
920 main_outI1(int whack_sock, connection_t *c, struct state *predecessor
921 , lset_t policy, unsigned long try)
922 {
923 struct state *st = new_state();
924 pb_stream reply; /* not actually a reply, but you know what I mean */
925 pb_stream rbody;
926 int vids_to_send = 0;
927
928 /* set up new state */
929 st->st_connection = c;
930 set_cur_state(st); /* we must reset before exit */
931 st->st_policy = policy & ~POLICY_IPSEC_MASK;
932 st->st_whack_sock = whack_sock;
933 st->st_try = try;
934 st->st_state = STATE_MAIN_I1;
935
936 /* determine how many Vendor ID payloads we will be sending */
937 if (SEND_PLUTO_VID)
938 {
939 vids_to_send++;
940 }
941 if (SEND_CISCO_UNITY_VID)
942 {
943 vids_to_send++;
944 }
945 if (c->spd.this.cert &&
946 c->spd.this.cert->cert->get_type(c->spd.this.cert->cert) == CERT_GPG)
947 {
948 vids_to_send++;
949 }
950 if (SEND_XAUTH_VID)
951 {
952 vids_to_send++;
953 }
954
955 /* always send DPD Vendor ID */
956 vids_to_send++;
957
958 if (nat_traversal_enabled)
959 {
960 vids_to_send++;
961 }
962
963 get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->spd.that.host_addr);
964
965 insert_state(st); /* needs cookies, connection, and msgid (0) */
966
967 if (HAS_IPSEC_POLICY(policy))
968 {
969 add_pending(dup_any(whack_sock), st, c, policy, 1
970 , predecessor == NULL? SOS_NOBODY : predecessor->st_serialno);
971 }
972 if (predecessor == NULL)
973 {
974 plog("initiating Main Mode");
975 }
976 else
977 {
978 plog("initiating Main Mode to replace #%lu", predecessor->st_serialno);
979 }
980
981 /* set up reply */
982 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
983
984 /* HDR out */
985 {
986 struct isakmp_hdr hdr;
987
988 zero(&hdr); /* default to 0 */
989 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
990 hdr.isa_np = ISAKMP_NEXT_SA;
991 hdr.isa_xchg = ISAKMP_XCHG_IDPROT;
992 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
993 /* R-cookie, flags and MessageID are left zero */
994
995 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
996 {
997 reset_cur_state();
998 return STF_INTERNAL_ERROR;
999 }
1000 }
1001
1002 /* SA out */
1003 {
1004 u_char *sa_start = rbody.cur;
1005
1006 if (!out_sa(&rbody, &oakley_sadb, st, TRUE
1007 , vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE))
1008 {
1009 reset_cur_state();
1010 return STF_INTERNAL_ERROR;
1011 }
1012
1013 /* save initiator SA for later HASH */
1014 passert(st->st_p1isa.ptr == NULL); /* no leak! (MUST be first time) */
1015 st->st_p1isa = chunk_create(sa_start, rbody.cur - sa_start);
1016 st->st_p1isa = chunk_clone(st->st_p1isa);
1017 }
1018
1019 /* if enabled send Pluto Vendor ID */
1020 if (SEND_PLUTO_VID)
1021 {
1022 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1023 , &rbody, VID_STRONGSWAN))
1024 {
1025 reset_cur_state();
1026 return STF_INTERNAL_ERROR;
1027 }
1028 }
1029
1030 /* if enabled send Cisco Unity Vendor ID */
1031 if (SEND_CISCO_UNITY_VID)
1032 {
1033 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1034 , &rbody, VID_CISCO_UNITY))
1035 {
1036 reset_cur_state();
1037 return STF_INTERNAL_ERROR;
1038 }
1039 }
1040 /* if we have an OpenPGP certificate we assume an
1041 * OpenPGP peer and have to send the Vendor ID
1042 */
1043 if (c->spd.this.cert &&
1044 c->spd.this.cert->cert->get_type(c->spd.this.cert->cert) == CERT_GPG)
1045 {
1046 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1047 , &rbody, VID_OPENPGP))
1048 {
1049 reset_cur_state();
1050 return STF_INTERNAL_ERROR;
1051 }
1052 }
1053
1054 /* Announce our ability to do eXtended AUTHentication to the peer */
1055 if (SEND_XAUTH_VID)
1056 {
1057 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1058 , &rbody, VID_MISC_XAUTH))
1059 {
1060 reset_cur_state();
1061 return STF_INTERNAL_ERROR;
1062 }
1063 }
1064
1065 /* Announce our ability to do Dead Peer Detection to the peer */
1066 {
1067 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1068 , &rbody, VID_MISC_DPD))
1069 {
1070 reset_cur_state();
1071 return STF_INTERNAL_ERROR;
1072 }
1073 }
1074
1075 if (nat_traversal_enabled)
1076 {
1077 /* Add supported NAT-Traversal VID */
1078 if (!nat_traversal_add_vid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
1079 , &rbody))
1080 {
1081 reset_cur_state();
1082 return STF_INTERNAL_ERROR;
1083 }
1084 }
1085
1086 close_message(&rbody);
1087 close_output_pbs(&reply);
1088 st->st_tpacket = chunk_create(reply.start, pbs_offset(&reply));
1089 st->st_tpacket = chunk_clone(st->st_tpacket);
1090
1091 /* Transmit */
1092
1093 send_packet(st, "main_outI1");
1094
1095 /* Set up a retransmission event, half a minute henceforth */
1096 delete_event(st);
1097 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
1098
1099 if (predecessor != NULL)
1100 {
1101 update_pending(predecessor, st);
1102 whack_log(RC_NEW_STATE + STATE_MAIN_I1
1103 , "%s: initiate, replacing #%lu"
1104 , enum_name(&state_names, st->st_state)
1105 , predecessor->st_serialno);
1106 }
1107 else
1108 {
1109 whack_log(RC_NEW_STATE + STATE_MAIN_I1
1110 , "%s: initiate", enum_name(&state_names, st->st_state));
1111 }
1112 reset_cur_state();
1113 return STF_OK;
1114 }
1115
1116 void ipsecdoi_initiate(int whack_sock, connection_t *c, lset_t policy,
1117 unsigned long try, so_serial_t replacing)
1118 {
1119 /* If there's already an ISAKMP SA established, use that and
1120 * go directly to Quick Mode. We are even willing to use one
1121 * that is still being negotiated, but only if we are the Initiator
1122 * (thus we can be sure that the IDs are not going to change;
1123 * other issues around intent might matter).
1124 * Note: there is no way to initiate with a Road Warrior.
1125 */
1126 struct state *st = find_phase1_state(c
1127 , ISAKMP_SA_ESTABLISHED_STATES | PHASE1_INITIATOR_STATES);
1128
1129 if (st == NULL)
1130 {
1131 (void) main_outI1(whack_sock, c, NULL, policy, try);
1132 }
1133 else if (HAS_IPSEC_POLICY(policy))
1134 {
1135 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1136 {
1137 /* leave our Phase 2 negotiation pending */
1138 add_pending(whack_sock, st, c, policy, try, replacing);
1139 }
1140 else
1141 {
1142 /* ??? we assume that peer_nexthop_sin isn't important:
1143 * we already have it from when we negotiated the ISAKMP SA!
1144 * It isn't clear what to do with the error return.
1145 */
1146 (void) quick_outI1(whack_sock, st, c, policy, try, replacing);
1147 }
1148 }
1149 else
1150 {
1151 close_any(whack_sock);
1152 }
1153 }
1154
1155 /* Replace SA with a fresh one that is similar
1156 *
1157 * Shares some logic with ipsecdoi_initiate, but not the same!
1158 * - we must not reuse the ISAKMP SA if we are trying to replace it!
1159 * - if trying to replace IPSEC SA, use ipsecdoi_initiate to build
1160 * ISAKMP SA if needed.
1161 * - duplicate whack fd, if live.
1162 * Does not delete the old state -- someone else will do that.
1163 */
1164 void ipsecdoi_replace(struct state *st, unsigned long try)
1165 {
1166 int whack_sock = dup_any(st->st_whack_sock);
1167 lset_t policy = st->st_policy;
1168
1169 if (IS_PHASE1(st->st_state))
1170 {
1171 passert(!HAS_IPSEC_POLICY(policy));
1172 (void) main_outI1(whack_sock, st->st_connection, st, policy, try);
1173 }
1174 else
1175 {
1176 /* Add features of actual old state to policy. This ensures
1177 * that rekeying doesn't downgrade security. I admit that
1178 * this doesn't capture everything.
1179 */
1180 if (st->st_pfs_group != NULL)
1181 policy |= POLICY_PFS;
1182 if (st->st_ah.present)
1183 {
1184 policy |= POLICY_AUTHENTICATE;
1185 if (st->st_ah.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1186 policy |= POLICY_TUNNEL;
1187 }
1188 if (st->st_esp.present && st->st_esp.attrs.transid != ESP_NULL)
1189 {
1190 policy |= POLICY_ENCRYPT;
1191 if (st->st_esp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1192 policy |= POLICY_TUNNEL;
1193 }
1194 if (st->st_ipcomp.present)
1195 {
1196 policy |= POLICY_COMPRESS;
1197 if (st->st_ipcomp.attrs.encapsulation == ENCAPSULATION_MODE_TUNNEL)
1198 policy |= POLICY_TUNNEL;
1199 }
1200 passert(HAS_IPSEC_POLICY(policy));
1201 ipsecdoi_initiate(whack_sock, st->st_connection, policy, try
1202 , st->st_serialno);
1203 }
1204 }
1205
1206 /* SKEYID for preshared keys.
1207 * See draft-ietf-ipsec-ike-01.txt 4.1
1208 */
1209 static bool skeyid_preshared(struct state *st)
1210 {
1211 const chunk_t *pss = get_preshared_secret(st->st_connection);
1212
1213 if (pss == NULL)
1214 {
1215 loglog(RC_LOG_SERIOUS, "preshared secret disappeared!");
1216 return FALSE;
1217 }
1218 else
1219 {
1220 pseudo_random_function_t prf_alg;
1221 prf_t *prf;
1222
1223 prf_alg = oakley_to_prf(st->st_oakley.hash);
1224 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1225 if (prf == NULL)
1226 {
1227 loglog(RC_LOG_SERIOUS, "%N not available to compute skeyid",
1228 pseudo_random_function_names, prf_alg);
1229 return FALSE;
1230 }
1231 free(st->st_skeyid.ptr);
1232 prf->set_key(prf, *pss);
1233 prf->allocate_bytes(prf, st->st_ni, NULL);
1234 prf->allocate_bytes(prf, st->st_nr, &st->st_skeyid);
1235 prf->destroy(prf);
1236 return TRUE;
1237 }
1238 }
1239
1240 static bool skeyid_digisig(struct state *st)
1241 {
1242 chunk_t nir;
1243 pseudo_random_function_t prf_alg;
1244 prf_t *prf;
1245
1246 prf_alg = oakley_to_prf(st->st_oakley.hash);
1247 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1248 if (prf == NULL)
1249 {
1250 loglog(RC_LOG_SERIOUS, "%N not available to compute skeyid",
1251 pseudo_random_function_names, prf_alg);
1252 return FALSE;
1253 }
1254 free(st->st_skeyid.ptr);
1255 nir = chunk_cat("cc", st->st_ni, st->st_nr);
1256 prf->set_key(prf, nir);
1257 prf->allocate_bytes(prf, st->st_shared, &st->st_skeyid);
1258 prf->destroy(prf);
1259 free(nir.ptr);
1260 return TRUE;
1261 }
1262
1263 /* Generate the SKEYID_* and new IV
1264 * See draft-ietf-ipsec-ike-01.txt 4.1
1265 */
1266 static bool generate_skeyids_iv(struct state *st)
1267 {
1268 /* Generate the SKEYID */
1269 switch (st->st_oakley.auth)
1270 {
1271 case OAKLEY_PRESHARED_KEY:
1272 case XAUTHInitPreShared:
1273 case XAUTHRespPreShared:
1274 if (!skeyid_preshared(st))
1275 {
1276 return FALSE;
1277 }
1278 break;
1279
1280 case OAKLEY_RSA_SIG:
1281 case OAKLEY_ECDSA_256:
1282 case OAKLEY_ECDSA_384:
1283 case OAKLEY_ECDSA_521:
1284 case XAUTHInitRSA:
1285 case XAUTHRespRSA:
1286 if (!skeyid_digisig(st))
1287 {
1288 return FALSE;
1289 }
1290 break;
1291
1292 case OAKLEY_DSS_SIG:
1293 /* XXX */
1294
1295 case OAKLEY_RSA_ENC:
1296 case OAKLEY_RSA_ENC_REV:
1297 case OAKLEY_ELGAMAL_ENC:
1298 case OAKLEY_ELGAMAL_ENC_REV:
1299 /* XXX */
1300
1301 default:
1302 bad_case(st->st_oakley.auth);
1303 }
1304
1305 /* generate SKEYID_* from SKEYID */
1306 {
1307 chunk_t seed_skeyid_d = chunk_from_chars(0x00);
1308 chunk_t seed_skeyid_a = chunk_from_chars(0x01);
1309 chunk_t seed_skeyid_e = chunk_from_chars(0x02);
1310 chunk_t icookie = { st->st_icookie, COOKIE_SIZE };
1311 chunk_t rcookie = { st->st_rcookie, COOKIE_SIZE };
1312 pseudo_random_function_t prf_alg;
1313 prf_t *prf;
1314
1315 prf_alg = oakley_to_prf(st->st_oakley.hash);
1316 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1317 prf->set_key(prf, st->st_skeyid);
1318
1319 /* SKEYID_D */
1320 free(st->st_skeyid_d.ptr);
1321 prf->allocate_bytes(prf, st->st_shared, NULL);
1322 prf->allocate_bytes(prf, icookie, NULL);
1323 prf->allocate_bytes(prf, rcookie, NULL);
1324 prf->allocate_bytes(prf, seed_skeyid_d, &st->st_skeyid_d);
1325
1326 /* SKEYID_A */
1327 free(st->st_skeyid_a.ptr);
1328 prf->allocate_bytes(prf, st->st_skeyid_d, NULL);
1329 prf->allocate_bytes(prf, st->st_shared, NULL);
1330 prf->allocate_bytes(prf, icookie, NULL);
1331 prf->allocate_bytes(prf, rcookie, NULL);
1332 prf->allocate_bytes(prf, seed_skeyid_a, &st->st_skeyid_a);
1333
1334 /* SKEYID_E */
1335 free(st->st_skeyid_e.ptr);
1336 prf->allocate_bytes(prf, st->st_skeyid_a, NULL);
1337 prf->allocate_bytes(prf, st->st_shared, NULL);
1338 prf->allocate_bytes(prf, icookie, NULL);
1339 prf->allocate_bytes(prf, rcookie, NULL);
1340 prf->allocate_bytes(prf, seed_skeyid_e, &st->st_skeyid_e);
1341
1342 prf->destroy(prf);
1343 }
1344
1345 /* generate IV */
1346 {
1347 hash_algorithm_t hash_alg;
1348 hasher_t *hasher;
1349
1350 hash_alg = oakley_to_hash_algorithm(st->st_oakley.hash);
1351 hasher = lib->crypto->create_hasher(lib->crypto, hash_alg);
1352 st->st_new_iv_len = hasher->get_hash_size(hasher);
1353 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1354
1355 DBG(DBG_CRYPT,
1356 DBG_dump_chunk("DH_i:", st->st_gi);
1357 DBG_dump_chunk("DH_r:", st->st_gr);
1358 );
1359
1360 hasher->get_hash(hasher, st->st_gi, NULL);
1361 hasher->get_hash(hasher, st->st_gr, st->st_new_iv);
1362 hasher->destroy(hasher);
1363 }
1364
1365 /* Oakley Keying Material
1366 * Derived from Skeyid_e: if it is not big enough, generate more
1367 * using the PRF.
1368 * See RFC 2409 "IKE" Appendix B
1369 */
1370 {
1371 size_t keysize = st->st_oakley.enckeylen/BITS_PER_BYTE;
1372
1373 /* free any existing key */
1374 free(st->st_enc_key.ptr);
1375
1376 if (keysize > st->st_skeyid_e.len)
1377 {
1378 u_char keytemp[MAX_OAKLEY_KEY_LEN + MAX_DIGEST_LEN];
1379 chunk_t seed = chunk_from_chars(0x00);
1380 size_t prf_block_size, i;
1381 pseudo_random_function_t prf_alg;
1382 prf_t *prf;
1383
1384 prf_alg = oakley_to_prf(st->st_oakley.hash);
1385 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1386 prf->set_key(prf, st->st_skeyid_e);
1387 prf_block_size = prf->get_block_size(prf);
1388
1389 for (i = 0;;)
1390 {
1391 prf->get_bytes(prf, seed, &keytemp[i]);
1392 i += prf_block_size;
1393 if (i >= keysize)
1394 {
1395 break;
1396 }
1397 seed = chunk_create(&keytemp[i-prf_block_size], prf_block_size);
1398 }
1399 prf->destroy(prf);
1400 st->st_enc_key = chunk_create(keytemp, keysize);
1401 }
1402 else
1403 {
1404 st->st_enc_key = chunk_create(st->st_skeyid_e.ptr, keysize);
1405 }
1406 st->st_enc_key = chunk_clone(st->st_enc_key);
1407 }
1408
1409 DBG(DBG_CRYPT,
1410 DBG_dump_chunk("Skeyid: ", st->st_skeyid);
1411 DBG_dump_chunk("Skeyid_d:", st->st_skeyid_d);
1412 DBG_dump_chunk("Skeyid_a:", st->st_skeyid_a);
1413 DBG_dump_chunk("Skeyid_e:", st->st_skeyid_e);
1414 DBG_dump_chunk("enc key:", st->st_enc_key);
1415 DBG_dump("IV:", st->st_new_iv, st->st_new_iv_len));
1416 return TRUE;
1417 }
1418
1419 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1420 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1421 * New Group Mode, or ISAKMP Informational Exchanges).
1422 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1423 * If hashus argument is TRUE, we're generating a hash for our end.
1424 * See RFC2409 IKE 5.
1425 */
1426 static void main_mode_hash(struct state *st, chunk_t *hash, bool hashi,
1427 const pb_stream *idpl)
1428 {
1429 chunk_t icookie = { st->st_icookie, COOKIE_SIZE };
1430 chunk_t rcookie = { st->st_rcookie, COOKIE_SIZE };
1431 chunk_t sa_body = { st->st_p1isa.ptr + sizeof(struct isakmp_generic),
1432 st->st_p1isa.len - sizeof(struct isakmp_generic) };
1433 chunk_t id_body = { idpl->start + sizeof(struct isakmp_generic),
1434 pbs_offset(idpl) - sizeof(struct isakmp_generic) };
1435 pseudo_random_function_t prf_alg;
1436 prf_t *prf;
1437
1438 switch (st->st_oakley.auth)
1439 {
1440 case OAKLEY_ECDSA_256:
1441 prf_alg = PRF_HMAC_SHA2_256;
1442 break;
1443 case OAKLEY_ECDSA_384:
1444 prf_alg = PRF_HMAC_SHA2_384;
1445 break;
1446 case OAKLEY_ECDSA_521:
1447 prf_alg = PRF_HMAC_SHA2_512;
1448 break;
1449 default:
1450 prf_alg = oakley_to_prf(st->st_oakley.hash);
1451 }
1452 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1453 prf->set_key(prf, st->st_skeyid);
1454
1455 if (hashi)
1456 {
1457 prf->get_bytes(prf, st->st_gi, NULL);
1458 prf->get_bytes(prf, st->st_gr, NULL);
1459 prf->get_bytes(prf, icookie, NULL);
1460 prf->get_bytes(prf, rcookie, NULL);
1461 }
1462 else
1463 {
1464 prf->get_bytes(prf, st->st_gr, NULL);
1465 prf->get_bytes(prf, st->st_gi, NULL);
1466 prf->get_bytes(prf, rcookie, NULL);
1467 prf->get_bytes(prf, icookie, NULL);
1468 }
1469
1470 DBG(DBG_CRYPT,
1471 DBG_log("hashing %u bytes of SA", sa_body.len)
1472 )
1473 prf->get_bytes(prf, sa_body, NULL);
1474
1475 /* Hash identification payload, without generic payload header.
1476 * We used to reconstruct ID Payload for this purpose, but now
1477 * we use the bytes as they appear on the wire to avoid
1478 * "spelling problems".
1479 */
1480 prf->get_bytes(prf, id_body, hash->ptr);
1481 hash->len = prf->get_block_size(prf);
1482 prf->destroy(prf);
1483 }
1484
1485 /* Create a public key signature of a hash.
1486 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1487 * Use PKCS#1 version 1.5 encryption of hash (called
1488 * RSAES-PKCS1-V1_5) in PKCS#2.
1489 */
1490 static size_t sign_hash(signature_scheme_t scheme, connection_t *c,
1491 u_char sig_val[RSA_MAX_OCTETS], chunk_t hash)
1492 {
1493 size_t sz = 0;
1494 smartcard_t *sc = c->spd.this.sc;
1495
1496 if (sc == NULL) /* no smartcard */
1497 {
1498 chunk_t sig;
1499 private_key_t *private = get_private_key(c);
1500
1501 if (private == NULL)
1502 {
1503 return 0; /* failure: no key to use */
1504 }
1505 if (!private->sign(private, scheme, hash, &sig))
1506 {
1507 return 0;
1508 }
1509 memcpy(sig_val, sig.ptr, sig.len);
1510 sz = sig.len;
1511 free(sig.ptr);
1512 }
1513 else if (sc->valid) /* if valid pin then sign hash on the smartcard */
1514 {
1515 lock_certs_and_keys("sign_hash");
1516 if (!scx_establish_context(sc) || !scx_login(sc))
1517 {
1518 scx_release_context(sc);
1519 unlock_certs_and_keys("sign_hash");
1520 return 0;
1521 }
1522
1523 sz = scx_get_keylength(sc);
1524 if (sz == 0)
1525 {
1526 plog("failed to get keylength from smartcard");
1527 scx_release_context(sc);
1528 unlock_certs_and_keys("sign_hash");
1529 return 0;
1530 }
1531
1532 DBG(DBG_CONTROL | DBG_CRYPT,
1533 DBG_log("signing hash with private key from smartcard (slot: %d, id: %s)"
1534 , (int)sc->slot, sc->id)
1535 )
1536 sz = scx_sign_hash(sc, hash.ptr, hash.len, sig_val, sz) ? sz : 0;
1537 if (!pkcs11_keep_state)
1538 {
1539 scx_release_context(sc);
1540 }
1541 unlock_certs_and_keys("sign_hash");
1542 }
1543 return sz;
1544 }
1545
1546 /* Check signature against all public keys we can find.
1547 * If we need keys from DNS KEY records, and they haven't been fetched,
1548 * return STF_SUSPEND to ask for asynch DNS lookup.
1549 *
1550 * Note: parameter keys_from_dns contains results of DNS lookup for key
1551 * or is NULL indicating lookup not yet tried.
1552 *
1553 * take_a_crack is a helper function. Mostly forensic.
1554 * If only we had coroutines.
1555 */
1556 struct tac_state {
1557 struct state *st;
1558 chunk_t hash;
1559 chunk_t sig;
1560 int tried_cnt; /* number of keys tried */
1561 };
1562
1563 static bool take_a_crack(struct tac_state *s, pubkey_t *kr)
1564 {
1565 public_key_t *pub_key = kr->public_key;
1566 chunk_t keyid = chunk_empty;
1567 signature_scheme_t scheme;
1568
1569 s->tried_cnt++;
1570 scheme = oakley_to_signature_scheme(s->st->st_oakley.auth);
1571 pub_key->get_fingerprint(pub_key, 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 c->spd.this.host_srcip->is_anyaddr(c->spd.this.host_srcip))
1953 {
1954 connection_t *ph1_c = isakmp_sa->st_connection;
1955 host_t * ph1_srcip = ph1_c->spd.this.host_srcip;
1956
1957 if (ph1_c->spd.this.modecfg && !ph1_srcip->is_anyaddr(ph1_srcip))
1958 {
1959 c->spd.this.host_srcip->destroy(c->spd.this.host_srcip);
1960 c->spd.this.host_srcip = ph1_srcip->clone(ph1_srcip);
1961 c->spd.this.client = ph1_c->spd.this.client;
1962 c->spd.this.has_client = TRUE;
1963 plog("inheriting virtual IP source address %H from ModeCfg", ph1_srcip);
1964 }
1965 }
1966
1967 st->st_whack_sock = whack_sock;
1968 st->st_connection = c;
1969 set_cur_state(st); /* we must reset before exit */
1970 st->st_policy = policy;
1971 st->st_try = try;
1972
1973 st->st_myuserprotoid = c->spd.this.protocol;
1974 st->st_peeruserprotoid = c->spd.that.protocol;
1975 st->st_myuserport = c->spd.this.port;
1976 st->st_peeruserport = c->spd.that.port;
1977
1978 st->st_msgid = generate_msgid(isakmp_sa);
1979 st->st_state = STATE_QUICK_I1;
1980
1981 insert_state(st); /* needs cookies, connection, and msgid */
1982
1983 if (replacing == SOS_NOBODY)
1984 {
1985 plog("initiating Quick Mode %s {using isakmp#%lu}",
1986 prettypolicy(policy), isakmp_sa->st_serialno);
1987 }
1988 else
1989 {
1990 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}",
1991 prettypolicy(policy), replacing, isakmp_sa->st_serialno);
1992 }
1993 if (isakmp_sa->nat_traversal & NAT_T_DETECTED)
1994 {
1995 /* Duplicate nat_traversal status in new state */
1996 st->nat_traversal = isakmp_sa->nat_traversal;
1997
1998 if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))
1999 {
2000 has_client = TRUE;
2001 }
2002 nat_traversal_change_port_lookup(NULL, st);
2003 }
2004 else
2005 {
2006 st->nat_traversal = 0;
2007 }
2008
2009 /* are we going to send a NAT-OA payload? */
2010 if ((st->nat_traversal & NAT_T_WITH_NATOA)
2011 && !(st->st_policy & POLICY_TUNNEL)
2012 && (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)))
2013 {
2014 send_natoa = TRUE;
2015 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
2016 ISAKMP_NEXT_NATOA_RFC : ISAKMP_NEXT_NATOA_DRAFTS;
2017 }
2018
2019 /* set up reply */
2020 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
2021
2022 /* HDR* out */
2023 {
2024 struct isakmp_hdr hdr;
2025
2026 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
2027 hdr.isa_np = ISAKMP_NEXT_HASH;
2028 hdr.isa_xchg = ISAKMP_XCHG_QUICK;
2029 hdr.isa_msgid = st->st_msgid;
2030 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
2031 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
2032 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
2033 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
2034 {
2035 reset_cur_state();
2036 return STF_INTERNAL_ERROR;
2037 }
2038 }
2039
2040 /* HASH(1) -- create and note space to be filled later */
2041 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
2042
2043 /* SA out */
2044
2045 /*
2046 * See if pfs_group has been specified for this conn,
2047 * if not, fallback to old use-same-as-P1 behaviour
2048 */
2049 #ifndef NO_IKE_ALG
2050 if (st->st_connection)
2051 {
2052 st->st_pfs_group = ike_alg_pfsgroup(st->st_connection, policy);
2053 }
2054 if (!st->st_pfs_group)
2055 #endif
2056 /* If PFS specified, use the same group as during Phase 1:
2057 * since no negotiation is possible, we pick one that is
2058 * very likely supported.
2059 */
2060 st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
2061
2062 /* Emit SA payload based on a subset of the policy bits.
2063 * POLICY_COMPRESS is considered iff we can do IPcomp.
2064 */
2065 {
2066 lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
2067
2068 if (can_do_IPcomp)
2069 {
2070 pm |= POLICY_COMPRESS;
2071 }
2072 if (!out_sa(&rbody,
2073 &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT],
2074 st, FALSE, ISAKMP_NEXT_NONCE))
2075 {
2076 reset_cur_state();
2077 return STF_INTERNAL_ERROR;
2078 }
2079 }
2080
2081 /* Ni out */
2082 if (!build_and_ship_nonce(&st->st_ni, &rbody
2083 , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : np
2084 , "Ni"))
2085 {
2086 reset_cur_state();
2087 return STF_INTERNAL_ERROR;
2088 }
2089
2090 /* [ KE ] out (for PFS) */
2091
2092 if (st->st_pfs_group != NULL)
2093 {
2094 if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2095 , &rbody, has_client? ISAKMP_NEXT_ID : np))
2096 {
2097 reset_cur_state();
2098 return STF_INTERNAL_ERROR;
2099 }
2100 }
2101
2102 /* [ IDci, IDcr ] out */
2103 if (has_client)
2104 {
2105 /* IDci (we are initiator), then IDcr (peer is responder) */
2106 if (!emit_subnet_id(&c->spd.this.client
2107 , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2108 || !emit_subnet_id(&c->spd.that.client
2109 , np, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2110 {
2111 reset_cur_state();
2112 return STF_INTERNAL_ERROR;
2113 }
2114 }
2115
2116 /* Send NAT-OA if our address is NATed */
2117 if (send_natoa)
2118 {
2119 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st))
2120 {
2121 reset_cur_state();
2122 return STF_INTERNAL_ERROR;
2123 }
2124 }
2125
2126 /* finish computing HASH(1), inserting it in output */
2127 (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2128 , st, &st->st_msgid, FALSE);
2129
2130 /* encrypt message, except for fixed part of header */
2131
2132 init_phase2_iv(isakmp_sa, &st->st_msgid);
2133 st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2134 memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2135
2136 if (!encrypt_message(&rbody, st))
2137 {
2138 reset_cur_state();
2139 return STF_INTERNAL_ERROR;
2140 }
2141
2142 /* save packet, now that we know its size */
2143 st->st_tpacket = chunk_create(reply.start, pbs_offset(&reply));
2144 st->st_tpacket = chunk_clone(st->st_tpacket);
2145
2146 /* send the packet */
2147
2148 send_packet(st, "quick_outI1");
2149
2150 delete_event(st);
2151 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2152
2153 if (replacing == SOS_NOBODY)
2154 {
2155 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2156 , "%s: initiate"
2157 , enum_name(&state_names, st->st_state));
2158 }
2159 else
2160 {
2161 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2162 , "%s: initiate to replace #%lu"
2163 , enum_name(&state_names, st->st_state)
2164 , replacing);
2165 }
2166 reset_cur_state();
2167 return STF_OK;
2168 }
2169
2170
2171 /*
2172 * Decode the CERT payload of Phase 1.
2173 */
2174 static void decode_cert(struct msg_digest *md)
2175 {
2176 struct payload_digest *p;
2177
2178 for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2179 {
2180 struct isakmp_cert *const cert = &p->payload.cert;
2181 chunk_t blob;
2182 time_t valid_until;
2183 blob.ptr = p->pbs.cur;
2184 blob.len = pbs_left(&p->pbs);
2185 if (cert->isacert_type == CERT_X509_SIGNATURE)
2186 {
2187 cert_t x509cert = cert_empty;
2188
2189 x509cert.cert = lib->creds->create(lib->creds,
2190 CRED_CERTIFICATE, CERT_X509,
2191 BUILD_BLOB_ASN1_DER, blob,
2192 BUILD_END);
2193 if (x509cert.cert)
2194 {
2195 if (verify_x509cert(&x509cert, strict_crl_policy, &valid_until))
2196 {
2197 DBG(DBG_PARSING,
2198 DBG_log("Public key validated")
2199 )
2200 add_public_key_from_cert(&x509cert, valid_until, DAL_SIGNED);
2201 }
2202 else
2203 {
2204 plog("X.509 certificate rejected");
2205 }
2206 x509cert.cert->destroy(x509cert.cert);
2207 }
2208 else
2209 {
2210 plog("Syntax error in X.509 certificate");
2211 }
2212 }
2213 else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2214 {
2215 linked_list_t *certs = linked_list_create();
2216
2217 if (pkcs7_parse_signedData(blob, NULL, certs, NULL, NULL))
2218 {
2219 store_x509certs(certs, strict_crl_policy);
2220 }
2221 else
2222 {
2223 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2224 }
2225 certs->destroy_offset(certs, offsetof(certificate_t, destroy));
2226 }
2227 else
2228 {
2229 loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2230 enum_show(&cert_type_names, cert->isacert_type));
2231 DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2232 }
2233 }
2234 }
2235
2236 /*
2237 * Decode the CR payload of Phase 1.
2238 */
2239 static void decode_cr(struct msg_digest *md, connection_t *c)
2240 {
2241 struct payload_digest *p;
2242
2243 for (p = md->chain[ISAKMP_NEXT_CR]; p != NULL; p = p->next)
2244 {
2245 struct isakmp_cr *const cr = &p->payload.cr;
2246 chunk_t ca_name;
2247
2248 ca_name.len = pbs_left(&p->pbs);
2249 ca_name.ptr = (ca_name.len > 0)? p->pbs.cur : NULL;
2250
2251 DBG_cond_dump_chunk(DBG_PARSING, "CR", ca_name);
2252
2253 if (cr->isacr_type == CERT_X509_SIGNATURE)
2254 {
2255 if (ca_name.len > 0)
2256 {
2257 identification_t *ca;
2258
2259 if (!is_asn1(ca_name))
2260 {
2261 continue;
2262 }
2263 if (c->requested_ca == NULL)
2264 {
2265 c->requested_ca = linked_list_create();
2266 }
2267 ca = identification_create_from_encoding(ID_DER_ASN1_DN, ca_name);
2268 c->requested_ca->insert_last(c->requested_ca, ca);
2269 DBG(DBG_PARSING | DBG_CONTROL,
2270 DBG_log("requested CA: \"%Y\"", ca)
2271 )
2272 }
2273 else
2274 {
2275 DBG(DBG_PARSING | DBG_CONTROL,
2276 DBG_log("requested CA: %%any")
2277 )
2278 }
2279 c->got_certrequest = TRUE;
2280 }
2281 else
2282 {
2283 loglog(RC_LOG_SERIOUS, "ignoring %s certificate request payload",
2284 enum_show(&cert_type_names, cr->isacr_type));
2285 }
2286 }
2287 }
2288
2289 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2290 * Note: we may change connections as a result.
2291 * We must be called before SIG or HASH are decoded since we
2292 * may change the peer's public key or ID.
2293 */
2294 static bool decode_peer_id(struct msg_digest *md, identification_t **peer)
2295 {
2296 struct state *const st = md->st;
2297 struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2298 const pb_stream *const id_pbs = &id_pld->pbs;
2299 struct isakmp_id *const id = &id_pld->payload.id;
2300 chunk_t id_payload;
2301
2302 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2303 * It talks about the protocol ID and Port fields of the ID
2304 * Payload, but they don't exist as such in Phase 1.
2305 * We use more appropriate names.
2306 * isaid_doi_specific_a is in place of Protocol ID.
2307 * isaid_doi_specific_b is in place of Port.
2308 * Besides, there is no good reason for allowing these to be
2309 * other than 0 in Phase 1.
2310 */
2311 if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING)
2312 && id->isaid_doi_specific_a == IPPROTO_UDP
2313 && (id->isaid_doi_specific_b == 0 || id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))
2314 {
2315 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2316 "accepted with port_floating NAT-T",
2317 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2318 }
2319 else if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2320 && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2321 {
2322 loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2323 " but are %d/%d"
2324 , IPPROTO_UDP, IKE_UDP_PORT
2325 , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2326 return FALSE;
2327 }
2328
2329 id_payload = chunk_create(id_pbs->cur, pbs_left(id_pbs));
2330
2331 switch (id->isaid_idtype)
2332 {
2333 case ID_IPV4_ADDR:
2334 if (id_payload.len != 4)
2335 {
2336 loglog(RC_LOG_SERIOUS, "improper %s Phase 1 ID payload",
2337 enum_show(&ident_names, id->isaid_idtype));
2338 return FALSE;
2339 }
2340 break;
2341 case ID_IPV6_ADDR:
2342 if (id_payload.len != 16)
2343 {
2344 loglog(RC_LOG_SERIOUS, "improper %s Phase 1 ID payload",
2345 enum_show(&ident_names, id->isaid_idtype));
2346 return FALSE;
2347 }
2348 break;
2349 case ID_USER_FQDN:
2350 case ID_FQDN:
2351 if (memchr(id_payload.ptr, '\0', id_payload.len) != NULL)
2352 {
2353 loglog(RC_LOG_SERIOUS, "%s Phase 1 ID payload contains "
2354 "a NUL character",
2355 enum_show(&ident_names, id->isaid_idtype));
2356 return FALSE;
2357 }
2358 break;
2359 case ID_KEY_ID:
2360 case ID_DER_ASN1_DN:
2361 break;
2362 default:
2363 /* XXX Could send notification back */
2364 loglog(RC_LOG_SERIOUS, "unacceptable identity type (%s) "
2365 "in Phase 1 ID payload",
2366 enum_show(&ident_names, id->isaid_idtype));
2367 return FALSE;
2368 }
2369 *peer = identification_create_from_encoding(id->isaid_idtype, id_payload);
2370
2371 plog("Peer ID is %s: '%Y'", enum_show(&ident_names, id->isaid_idtype),
2372 *peer);
2373
2374 /* check for certificates */
2375 decode_cert(md);
2376 return TRUE;
2377 }
2378
2379 /* Now that we've decoded the ID payload, let's see if we
2380 * need to switch connections.
2381 * We must not switch horses if we initiated:
2382 * - if the initiation was explicit, we'd be ignoring user's intent
2383 * - if opportunistic, we'll lose our HOLD info
2384 */
2385 static bool switch_connection(struct msg_digest *md, identification_t *peer,
2386 bool initiator)
2387 {
2388 struct state *const st = md->st;
2389 connection_t *c = st->st_connection;
2390 identification_t *peer_ca;
2391
2392 peer_ca = st->st_peer_pubkey ? st->st_peer_pubkey->issuer : NULL;
2393 if (peer_ca)
2394 {
2395 DBG(DBG_CONTROL,
2396 DBG_log("peer CA: \"%Y\"", peer_ca)
2397 )
2398 }
2399 else
2400 {
2401 DBG(DBG_CONTROL,
2402 DBG_log("peer CA: %%none")
2403 )
2404 }
2405
2406 if (initiator)
2407 {
2408 int pathlen;
2409
2410 if (!peer->equals(peer, c->spd.that.id))
2411 {
2412 loglog(RC_LOG_SERIOUS,
2413 "we require peer to have ID '%Y', but peer declares '%Y'",
2414 c->spd.that.id, peer);
2415 return FALSE;
2416 }
2417
2418 if (c->spd.that.ca)
2419 {
2420 DBG(DBG_CONTROL,
2421 DBG_log("required CA: \"%s\"", c->spd.that.ca);
2422 )
2423 }
2424 else
2425 {
2426 DBG(DBG_CONTROL,
2427 DBG_log("required CA: %%none");
2428 )
2429 }
2430
2431 if (!trusted_ca(peer_ca, c->spd.that.ca, &pathlen))
2432 {
2433 loglog(RC_LOG_SERIOUS
2434 , "we don't accept the peer's CA");
2435 return FALSE;
2436 }
2437 }
2438 else
2439 {
2440 connection_t *r;
2441
2442 /* check for certificate requests */
2443 decode_cr(md, c);
2444
2445 r = refine_host_connection(st, peer, peer_ca);
2446
2447 /* delete the collected certificate requests */
2448 if (c->requested_ca)
2449 {
2450 c->requested_ca->destroy_offset(c->requested_ca,
2451 offsetof(identification_t, destroy));
2452 c->requested_ca = NULL;
2453 }
2454
2455 if (r == NULL)
2456 {
2457 loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%Y'", peer);
2458 return FALSE;
2459 }
2460
2461 if (r->spd.this.ca)
2462 {
2463 DBG(DBG_CONTROL,
2464 DBG_log("offered CA: \"%Y\"", r->spd.this.ca)
2465 )
2466 }
2467 else
2468 {
2469 DBG(DBG_CONTROL,
2470 DBG_log("offered CA: %%none")
2471 )
2472 }
2473
2474 if (r != c)
2475 {
2476 /* apparently, r is an improvement on c -- replace */
2477
2478 DBG(DBG_CONTROL
2479 , DBG_log("switched from \"%s\" to \"%s\"", c->name, r->name));
2480 if (r->kind == CK_TEMPLATE)
2481 {
2482 /* instantiate it, filling in peer's ID */
2483 r = rw_instantiate(r, &c->spd.that.host_addr
2484 , c->spd.that.host_port, NULL, peer);
2485 }
2486
2487 /* copy certificate request info */
2488 r->got_certrequest = c->got_certrequest;
2489
2490 st->st_connection = r; /* kill reference to c */
2491 set_cur_connection(r);
2492 connection_discard(c);
2493 }
2494 else if (c->spd.that.has_id_wildcards)
2495 {
2496 c->spd.that.id->destroy(c->spd.that.id);
2497 c->spd.that.id = peer->clone(peer);
2498 c->spd.that.has_id_wildcards = FALSE;
2499 }
2500 }
2501 return TRUE;
2502 }
2503
2504 /* Decode the variable part of an ID packet (during Quick Mode).
2505 * This is designed for packets that identify clients, not peers.
2506 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2507 * (1) it is wrong and (2) we use this value for inband signalling.
2508 */
2509 static bool decode_net_id(struct isakmp_ipsec_id *id, pb_stream *id_pbs,
2510 ip_subnet *net, const char *which)
2511 {
2512 const struct af_info *afi = NULL;
2513
2514 /* Note: the following may be a pointer into static memory
2515 * that may be recycled, but only if the type is not known.
2516 * That case is disposed of very early -- in the first switch.
2517 */
2518 const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2519
2520 switch (id->isaiid_idtype)
2521 {
2522 case ID_IPV4_ADDR:
2523 case ID_IPV4_ADDR_SUBNET:
2524 case ID_IPV4_ADDR_RANGE:
2525 afi = &af_inet4_info;
2526 break;
2527 case ID_IPV6_ADDR:
2528 case ID_IPV6_ADDR_SUBNET:
2529 case ID_IPV6_ADDR_RANGE:
2530 afi = &af_inet6_info;
2531 break;
2532 case ID_FQDN:
2533 return TRUE;
2534 default:
2535 /* XXX support more */
2536 loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2537 , idtypename);
2538 /* XXX Could send notification back */
2539 return FALSE;
2540 }
2541
2542 switch (id->isaiid_idtype)
2543 {
2544 case ID_IPV4_ADDR:
2545 case ID_IPV6_ADDR:
2546 {
2547 ip_address temp_address;
2548 err_t ugh;
2549
2550 ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2551
2552 if (ugh != NULL)
2553 {
2554 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2555 , which, idtypename, ugh);
2556 /* XXX Could send notification back */
2557 return FALSE;
2558 }
2559 if (isanyaddr(&temp_address))
2560 {
2561 loglog(RC_LOG_SERIOUS, "%s ID payload %s is invalid (%s) in Quick I1"
2562 , which, idtypename, ip_str(&temp_address));
2563 /* XXX Could send notification back */
2564 return FALSE;
2565 }
2566 happy(addrtosubnet(&temp_address, net));
2567 DBG(DBG_PARSING | DBG_CONTROL
2568 , DBG_log("%s is %s", which, ip_str(&temp_address)));
2569 break;
2570 }
2571
2572 case ID_IPV4_ADDR_SUBNET:
2573 case ID_IPV6_ADDR_SUBNET:
2574 {
2575 ip_address temp_address, temp_mask;
2576 err_t ugh;
2577
2578 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2579 {
2580 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2581 , which, idtypename);
2582 /* XXX Could send notification back */
2583 return FALSE;
2584 }
2585 ugh = initaddr(id_pbs->cur
2586 , afi->ia_sz, afi->af, &temp_address);
2587 if (ugh == NULL)
2588 {
2589 ugh = initaddr(id_pbs->cur + afi->ia_sz
2590 , afi->ia_sz, afi->af, &temp_mask);
2591 }
2592 if (ugh == NULL)
2593 {
2594 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2595 , '0', net);
2596 }
2597 if (ugh == NULL && subnetisnone(net))
2598 {
2599 ugh = "contains only anyaddr";
2600 }
2601 if (ugh != NULL)
2602 {
2603 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2604 , which, idtypename, ugh);
2605 /* XXX Could send notification back */
2606 return FALSE;
2607 }
2608 DBG(DBG_PARSING | DBG_CONTROL,
2609 {
2610 char temp_buff[SUBNETTOT_BUF];
2611
2612 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2613 DBG_log("%s is subnet %s", which, temp_buff);
2614 });
2615 break;
2616 }
2617
2618 case ID_IPV4_ADDR_RANGE:
2619 case ID_IPV6_ADDR_RANGE:
2620 {
2621 ip_address temp_address_from, temp_address_to;
2622 err_t ugh;
2623
2624 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2625 {
2626 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2627 , which, idtypename);
2628 /* XXX Could send notification back */
2629 return FALSE;
2630 }
2631 ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2632 if (ugh == NULL)
2633 {
2634 ugh = initaddr(id_pbs->cur + afi->ia_sz
2635 , afi->ia_sz, afi->af, &temp_address_to);
2636 }
2637 if (ugh != NULL)
2638 {
2639 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2640 , which, idtypename, ugh);
2641 /* XXX Could send notification back */
2642 return FALSE;
2643 }
2644
2645 ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2646 if (ugh == NULL && subnetisnone(net))
2647 {
2648 ugh = "contains only anyaddr";
2649 }
2650 if (ugh != NULL)
2651 {
2652 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2653
2654 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2655 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2656 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2657 " %s - %s unacceptable: %s"
2658 , which, idtypename, temp_buff1, temp_buff2, ugh);
2659 return FALSE;
2660 }
2661 DBG(DBG_PARSING | DBG_CONTROL,
2662 {
2663 char temp_buff[SUBNETTOT_BUF];
2664
2665 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2666 DBG_log("%s is subnet %s (received as range)"
2667 , which, temp_buff);
2668 });
2669 break;
2670 }
2671 }
2672
2673 /* set the port selector */
2674 setportof(htons(id->isaiid_port), &net->addr);
2675
2676 DBG(DBG_PARSING | DBG_CONTROL,
2677 DBG_log("%s protocol/port is %d/%d", which, id->isaiid_protoid, id->isaiid_port)
2678 )
2679
2680 return TRUE;
2681 }
2682
2683 /* like decode, but checks that what is received matches what was sent */
2684 static bool check_net_id(struct isakmp_ipsec_id *id, pb_stream *id_pbs,
2685 u_int8_t *protoid, u_int16_t *port, ip_subnet *net,
2686 const char *which)
2687 {
2688 ip_subnet net_temp;
2689
2690 if (!decode_net_id(id, id_pbs, &net_temp, which))
2691 {
2692 return FALSE;
2693 }
2694 if (!samesubnet(net, &net_temp)
2695 || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2696 {
2697 loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2698 return FALSE;
2699 }
2700 return TRUE;
2701 }
2702
2703 /*
2704 * look for the existence of a non-expiring preloaded public key
2705 */
2706 static bool has_preloaded_public_key(struct state *st)
2707 {
2708 connection_t *c = st->st_connection;
2709
2710 /* do not consider rw connections since
2711 * the peer's identity must be known
2712 */
2713 if (c->kind == CK_PERMANENT)
2714 {
2715 pubkey_list_t *p;
2716
2717 /* look for a matching RSA public key */
2718 for (p = pubkeys; p != NULL; p = p->next)
2719 {
2720 pubkey_t *key = p->key;
2721 key_type_t type = key->public_key->get_type(key->public_key);
2722
2723 if (type == KEY_RSA &&
2724 c->spd.that.id->equals(c->spd.that.id, key->id) &&
2725 key->until_time == UNDEFINED_TIME)
2726 {
2727 /* found a preloaded public key */
2728 return TRUE;
2729 }
2730 }
2731 }
2732 return FALSE;
2733 }
2734
2735 /*
2736 * Produce the new key material of Quick Mode.
2737 * RFC 2409 "IKE" section 5.5
2738 * specifies how this is to be done.
2739 */
2740 static void compute_proto_keymat(struct state *st, u_int8_t protoid,
2741 struct ipsec_proto_info *pi)
2742 {
2743 size_t needed_len = 0; /* bytes of keying material needed */
2744
2745 /* Add up the requirements for keying material
2746 * (It probably doesn't matter if we produce too much!)
2747 */
2748 switch (protoid)
2749 {
2750 case PROTO_IPSEC_ESP:
2751 {
2752 needed_len = kernel_alg_esp_enc_keylen(pi->attrs.transid);
2753
2754 if (needed_len && pi->attrs.key_len)
2755 {
2756 needed_len = pi->attrs.key_len / BITS_PER_BYTE;
2757 }
2758
2759 switch (pi->attrs.transid)
2760 {
2761 case ESP_NULL:
2762 needed_len = 0;
2763 break;
2764 case ESP_AES_CCM_8:
2765 case ESP_AES_CCM_12:
2766 case ESP_AES_CCM_16:
2767 needed_len += 3;
2768 break;
2769 case ESP_AES_GCM_8:
2770 case ESP_AES_GCM_12:
2771 case ESP_AES_GCM_16:
2772 case ESP_AES_CTR:
2773 case ESP_AES_GMAC:
2774 needed_len += 4;
2775 break;
2776 default:
2777 if (needed_len == 0)
2778 {
2779 bad_case(pi->attrs.transid);
2780 }
2781 }
2782
2783 if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL))
2784 {
2785 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2786 }
2787 else
2788 {
2789 switch (pi->attrs.auth)
2790 {
2791 case AUTH_ALGORITHM_NONE:
2792 break;
2793 case AUTH_ALGORITHM_HMAC_MD5:
2794 needed_len += HMAC_MD5_KEY_LEN;
2795 break;
2796 case AUTH_ALGORITHM_HMAC_SHA1:
2797 needed_len += HMAC_SHA1_KEY_LEN;
2798 break;
2799 case AUTH_ALGORITHM_DES_MAC:
2800 default:
2801 bad_case(pi->attrs.auth);
2802 }
2803 }
2804 break;
2805 }
2806 case PROTO_IPSEC_AH:
2807 {
2808 switch (pi->attrs.transid)
2809 {
2810 case AH_MD5:
2811 needed_len = HMAC_MD5_KEY_LEN;
2812 break;
2813 case AH_SHA:
2814 needed_len = HMAC_SHA1_KEY_LEN;
2815 break;
2816 default:
2817 bad_case(pi->attrs.transid);
2818 }
2819 break;
2820 }
2821 default:
2822 bad_case(protoid);
2823 }
2824
2825 pi->keymat_len = needed_len;
2826
2827 /* Allocate space for the keying material. Although only needed_len bytes
2828 * are desired, we must round up to a multiple of hash_size
2829 * so that our buffer isn't overrun.
2830 */
2831 {
2832 size_t needed_space; /* space needed for keying material (rounded up) */
2833 size_t i, prf_block_size;
2834 chunk_t protoid_chunk = chunk_from_thing(protoid);
2835 chunk_t spi_our = chunk_from_thing(pi->our_spi);
2836 chunk_t spi_peer = chunk_from_thing(pi->attrs.spi);
2837 pseudo_random_function_t prf_alg;
2838 prf_t *prf_our, *prf_peer;
2839
2840 prf_alg = oakley_to_prf(st->st_oakley.hash);
2841 prf_our = lib->crypto->create_prf(lib->crypto, prf_alg);
2842 prf_peer = lib->crypto->create_prf(lib->crypto, prf_alg);
2843 prf_our->set_key(prf_our, st->st_skeyid_d);
2844 prf_peer->set_key(prf_peer, st->st_skeyid_d);
2845 prf_block_size = prf_our->get_block_size(prf_our);
2846
2847 needed_space = needed_len + pad_up(needed_len, prf_block_size);
2848 replace(pi->our_keymat, malloc(needed_space));
2849 replace(pi->peer_keymat, malloc(needed_space));
2850
2851 for (i = 0;; )
2852 {
2853 char *keymat_i_our = pi->our_keymat + i;
2854 char *keymat_i_peer = pi->peer_keymat + i;
2855 chunk_t keymat_our = { keymat_i_our, prf_block_size };
2856 chunk_t keymat_peer = { keymat_i_peer, prf_block_size };
2857
2858 if (st->st_shared.ptr != NULL)
2859 {
2860 /* PFS: include the g^xy */
2861 prf_our->get_bytes(prf_our, st->st_shared, NULL);
2862 prf_peer->get_bytes(prf_peer, st->st_shared, NULL);
2863 }
2864 prf_our->get_bytes(prf_our, protoid_chunk, NULL);
2865 prf_peer->get_bytes(prf_peer, protoid_chunk, NULL);
2866
2867 prf_our->get_bytes(prf_our, spi_our, NULL);
2868 prf_peer->get_bytes(prf_peer, spi_peer, NULL);
2869
2870 prf_our->get_bytes(prf_our, st->st_ni, NULL);
2871 prf_peer->get_bytes(prf_peer, st->st_ni, NULL);
2872
2873 prf_our->get_bytes(prf_our, st->st_nr, keymat_i_our);
2874 prf_peer->get_bytes(prf_peer, st->st_nr, keymat_i_peer);
2875
2876 i += prf_block_size;
2877 if (i >= needed_space)
2878 {
2879 break;
2880 }
2881
2882 /* more keying material needed: prepare to go around again */
2883 prf_our->get_bytes(prf_our, keymat_our, NULL);
2884 prf_peer->get_bytes(prf_peer, keymat_peer, NULL);
2885 }
2886 prf_our->destroy(prf_our);
2887 prf_peer->destroy(prf_peer);
2888 }
2889 DBG(DBG_CRYPT,
2890 DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
2891 DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
2892 }
2893
2894 static void compute_keymats(struct state *st)
2895 {
2896 if (st->st_ah.present)
2897 {
2898 compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
2899 }
2900 if (st->st_esp.present)
2901 {
2902 compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
2903 }
2904 }
2905
2906 static bool uses_pubkey_auth(int auth)
2907 {
2908 switch (auth)
2909 {
2910 case OAKLEY_RSA_SIG:
2911 case OAKLEY_ECDSA_SIG:
2912 case OAKLEY_ECDSA_256:
2913 case OAKLEY_ECDSA_384:
2914 case OAKLEY_ECDSA_521:
2915 case XAUTHInitRSA:
2916 case XAUTHRespRSA:
2917 return TRUE;
2918 default:
2919 return FALSE;
2920 }
2921 }
2922
2923 /* build an ID payload
2924 * Note: no memory is allocated for the body of the payload (tl->ptr).
2925 * We assume it will end up being a pointer into a sufficiently
2926 * stable datastructure. It only needs to last a short time.
2927 */
2928 static void build_id_payload(struct isakmp_ipsec_id *hd, chunk_t *tl, struct end *end)
2929 {
2930 identification_t *id = resolve_myid(end->id);
2931
2932 zero(hd);
2933 hd->isaiid_idtype = id->get_type(id);
2934
2935 switch (id->get_type(id))
2936 {
2937 case ID_ANY:
2938 hd->isaiid_idtype = aftoinfo(addrtypeof(&end->host_addr))->id_addr;
2939 tl->len = addrbytesptr(&end->host_addr,
2940 (const unsigned char **)&tl->ptr); /* sets tl->ptr too */
2941 break;
2942 case ID_IPV4_ADDR:
2943 case ID_IPV6_ADDR:
2944 case ID_FQDN:
2945 case ID_USER_FQDN:
2946 case ID_DER_ASN1_DN:
2947 case ID_KEY_ID:
2948 *tl = id->get_encoding(id);
2949 break;
2950 default:
2951 bad_case(id->get_type(id));
2952 }
2953 }
2954
2955 /* State Transition Functions.
2956 *
2957 * The definition of state_microcode_table in demux.c is a good
2958 * overview of these routines.
2959 *
2960 * - Called from process_packet; result handled by complete_state_transition
2961 * - struct state_microcode member "processor" points to these
2962 * - these routine definitionss are in state order
2963 * - these routines must be restartable from any point of error return:
2964 * beware of memory allocated before any error.
2965 * - output HDR is usually emitted by process_packet (if state_microcode
2966 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2967 *
2968 * The transition functions' functions include:
2969 * - process and judge payloads
2970 * - update st_iv (result of decryption is in st_new_iv)
2971 * - build reply packet
2972 */
2973
2974 /* Handle a Main Mode Oakley first packet (responder side).
2975 * HDR;SA --> HDR;SA
2976 */
2977 stf_status main_inI1_outR1(struct msg_digest *md)
2978 {
2979 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
2980 struct state *st;
2981 connection_t *c;
2982 struct isakmp_proposal proposal;
2983 pb_stream proposal_pbs;
2984 pb_stream r_sa_pbs;
2985 u_int32_t ipsecdoisit;
2986 lset_t policy = LEMPTY;
2987 int vids_to_send = 0;
2988
2989 /* We preparse the peer's proposal in order to determine
2990 * the requested authentication policy (RSA or PSK)
2991 */
2992 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd->payload.sa
2993 , &sa_pd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
2994
2995 backup_pbs(&proposal_pbs);
2996 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2997 , proposal.isap_notrans, &policy));
2998 restore_pbs(&proposal_pbs);
2999
3000 /* We are only considering candidate connections that match
3001 * the requested authentication policy (RSA or PSK)
3002 */
3003 c = find_host_connection(&md->iface->addr, pluto_port
3004 , &md->sender, md->sender_port, policy);
3005
3006 if (c == NULL && md->iface->ike_float)
3007 {
3008 c = find_host_connection(&md->iface->addr, NAT_T_IKE_FLOAT_PORT
3009 , &md->sender, md->sender_port, policy);
3010 }
3011
3012 if (c == NULL)
3013 {
3014 /* See if a wildcarded connection can be found.
3015 * We cannot pick the right connection, so we're making a guess.
3016 * All Road Warrior connections are fair game:
3017 * we pick the first we come across (if any).
3018 * If we don't find any, we pick the first opportunistic
3019 * with the smallest subnet that includes the peer.
3020 * There is, of course, no necessary relationship between
3021 * an Initiator's address and that of its client,
3022 * but Food Groups kind of assumes one.
3023 */
3024 {
3025 connection_t *d;
3026
3027 d = find_host_connection(&md->iface->addr
3028 , pluto_port, (ip_address*)NULL, md->sender_port, policy);
3029
3030 for (; d != NULL; d = d->hp_next)
3031 {
3032 if (d->kind == CK_GROUP)
3033 {
3034 /* ignore */
3035 }
3036 else
3037 {
3038 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO))
3039 {
3040 /* must be Road Warrior: we have a winner */
3041 c = d;
3042 break;
3043 }
3044
3045 /* Opportunistic or Shunt: pick tightest match */
3046 if (addrinsubnet(&md->sender, &d->spd.that.client)
3047 && (c == NULL || !subnetinsubnet(&c->spd.that.client, &d->spd.that.client)))
3048 c = d;
3049 }
3050 }
3051 }
3052
3053 if (c == NULL)
3054 {
3055 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3056 " but no connection has been authorized%s%s"
3057 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr))
3058 , (policy != LEMPTY) ? " with policy=" : ""
3059 , (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : "");
3060 /* XXX notification is in order! */
3061 return STF_IGNORE;
3062 }
3063 else if (c->kind != CK_TEMPLATE)
3064 {
3065 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
3066 " but \"%s\" forbids connection"
3067 , ip_str(&md->iface->addr), pluto_port, c->name);
3068 /* XXX notification is in order! */
3069 return STF_IGNORE;
3070 }
3071 else
3072 {
3073 /* Create a temporary connection that is a copy of this one.
3074 * His ID isn't declared yet.
3075 */
3076 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, NULL);
3077 }
3078 }
3079 else if (c->kind == CK_TEMPLATE)
3080 {
3081 /* Create an instance
3082 * This is a rare case: wildcard peer ID but static peer IP address
3083 */
3084 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, c->spd.that.id);
3085 }
3086
3087 /* Set up state */
3088 md->st = st = new_state();
3089 st->st_connection = c;
3090 set_cur_state(st); /* (caller will reset cur_state) */
3091 st->st_try = 0; /* not our job to try again from start */
3092 st->st_policy = c->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
3093
3094 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
3095 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
3096
3097 insert_state(st); /* needs cookies, connection, and msgid (0) */
3098
3099 st->st_doi = ISAKMP_DOI_IPSEC;
3100 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
3101
3102 if ((c->kind == CK_INSTANCE) && (c->spd.that.host_port != pluto_port))
3103 {
3104 plog("responding to Main Mode from unknown peer %s:%u"
3105 , ip_str(&c->spd.that.host_addr), c->spd.that.host_port);
3106 }
3107 else if (c->kind == CK_INSTANCE)
3108 {
3109 plog("responding to Main Mode from unknown peer %s"
3110 , ip_str(&c->spd.that.host_addr));
3111 }
3112 else
3113 {
3114 plog("responding to Main Mode");
3115 }
3116
3117 /* parse_isakmp_sa also spits out a winning SA into our reply,
3118 * so we have to build our md->reply and emit HDR before calling it.
3119 */
3120
3121 /* determine how many Vendor ID payloads we will be sending */
3122 if (SEND_PLUTO_VID)
3123 {
3124 vids_to_send++;
3125 }
3126 if (SEND_CISCO_UNITY_VID)
3127 {
3128 vids_to_send++;
3129 }
3130 if (md->openpgp)
3131 {
3132 vids_to_send++;
3133 }
3134 if (SEND_XAUTH_VID)
3135 {
3136 vids_to_send++;
3137 }
3138 /* always send DPD Vendor ID */
3139 vids_to_send++;
3140 if (md->nat_traversal_vid && nat_traversal_enabled)
3141 {
3142 vids_to_send++;
3143 }
3144
3145 /* HDR out.
3146 * We can't leave this to comm_handle() because we must
3147 * fill in the cookie.
3148 */
3149 {
3150 struct isakmp_hdr r_hdr = md->hdr;
3151
3152 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3153 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3154 r_hdr.isa_np = ISAKMP_NEXT_SA;
3155 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3156 return STF_INTERNAL_ERROR;
3157 }
3158
3159 /* start of SA out */
3160 {
3161 struct isakmp_sa r_sa = sa_pd->payload.sa;
3162
3163 r_sa.isasa_np = vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
3164
3165 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3166 return STF_INTERNAL_ERROR;
3167 }
3168
3169 /* SA body in and out */
3170 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit, &proposal_pbs
3171 ,&proposal, &r_sa_pbs, st, FALSE));
3172
3173 /* if enabled send Pluto Vendor ID */
3174 if (SEND_PLUTO_VID)
3175 {
3176 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3177 , &md->rbody, VID_STRONGSWAN))
3178 {
3179 return STF_INTERNAL_ERROR;
3180 }
3181 }
3182
3183 /* if enabled send Cisco Unity Vendor ID */
3184 if (SEND_CISCO_UNITY_VID)
3185 {
3186 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3187 , &md->rbody, VID_CISCO_UNITY))
3188 {
3189 return STF_INTERNAL_ERROR;
3190 }
3191 }
3192
3193 /*
3194 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3195 */