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