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