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