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