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