improved DPD error message
[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 OAKLEY_ECDSA_256:
1212 case OAKLEY_ECDSA_384:
1213 case OAKLEY_ECDSA_521:
1214 case XAUTHInitRSA:
1215 case XAUTHRespRSA:
1216 if (!skeyid_digisig(st))
1217 {
1218 return FALSE;
1219 }
1220 break;
1221
1222 case OAKLEY_DSS_SIG:
1223 /* XXX */
1224
1225 case OAKLEY_RSA_ENC:
1226 case OAKLEY_RSA_ENC_REV:
1227 case OAKLEY_ELGAMAL_ENC:
1228 case OAKLEY_ELGAMAL_ENC_REV:
1229 /* XXX */
1230
1231 default:
1232 bad_case(st->st_oakley.auth);
1233 }
1234
1235 /* generate SKEYID_* from SKEYID */
1236 {
1237 char buf_skeyid_d[] = { 0x00 };
1238 char buf_skeyid_a[] = { 0x01 };
1239 char buf_skeyid_e[] = { 0x02 };
1240 chunk_t seed_skeyid_d = chunk_from_buf(buf_skeyid_d);
1241 chunk_t seed_skeyid_a = chunk_from_buf(buf_skeyid_a);
1242 chunk_t seed_skeyid_e = chunk_from_buf(buf_skeyid_e);
1243 chunk_t icookie = { st->st_icookie, COOKIE_SIZE };
1244 chunk_t rcookie = { st->st_rcookie, COOKIE_SIZE };
1245 pseudo_random_function_t prf_alg;
1246 prf_t *prf;
1247
1248 prf_alg = oakley_to_prf(st->st_oakley.hash);
1249 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1250 prf->set_key(prf, st->st_skeyid);
1251
1252 /* SKEYID_D */
1253 free(st->st_skeyid_d.ptr);
1254 prf->allocate_bytes(prf, st->st_shared, NULL);
1255 prf->allocate_bytes(prf, icookie, NULL);
1256 prf->allocate_bytes(prf, rcookie, NULL);
1257 prf->allocate_bytes(prf, seed_skeyid_d, &st->st_skeyid_d);
1258
1259 /* SKEYID_A */
1260 free(st->st_skeyid_a.ptr);
1261 prf->allocate_bytes(prf, st->st_skeyid_d, NULL);
1262 prf->allocate_bytes(prf, st->st_shared, NULL);
1263 prf->allocate_bytes(prf, icookie, NULL);
1264 prf->allocate_bytes(prf, rcookie, NULL);
1265 prf->allocate_bytes(prf, seed_skeyid_a, &st->st_skeyid_a);
1266
1267 /* SKEYID_E */
1268 free(st->st_skeyid_e.ptr);
1269 prf->allocate_bytes(prf, st->st_skeyid_a, NULL);
1270 prf->allocate_bytes(prf, st->st_shared, NULL);
1271 prf->allocate_bytes(prf, icookie, NULL);
1272 prf->allocate_bytes(prf, rcookie, NULL);
1273 prf->allocate_bytes(prf, seed_skeyid_e, &st->st_skeyid_e);
1274
1275 prf->destroy(prf);
1276 }
1277
1278 /* generate IV */
1279 {
1280 hash_algorithm_t hash_alg;
1281 hasher_t *hasher;
1282
1283 hash_alg = oakley_to_hash_algorithm(st->st_oakley.hash);
1284 hasher = lib->crypto->create_hasher(lib->crypto, hash_alg);
1285 st->st_new_iv_len = hasher->get_hash_size(hasher);
1286 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1287
1288 DBG(DBG_CRYPT,
1289 DBG_dump_chunk("DH_i:", st->st_gi);
1290 DBG_dump_chunk("DH_r:", st->st_gr);
1291 );
1292
1293 hasher->get_hash(hasher, st->st_gi, NULL);
1294 hasher->get_hash(hasher, st->st_gr, st->st_new_iv);
1295 hasher->destroy(hasher);
1296 }
1297
1298 /* Oakley Keying Material
1299 * Derived from Skeyid_e: if it is not big enough, generate more
1300 * using the PRF.
1301 * See RFC 2409 "IKE" Appendix B
1302 */
1303 {
1304 size_t keysize = st->st_oakley.enckeylen/BITS_PER_BYTE;
1305
1306 /* free any existing key */
1307 free(st->st_enc_key.ptr);
1308
1309 if (keysize > st->st_skeyid_e.len)
1310 {
1311 u_char keytemp[MAX_OAKLEY_KEY_LEN + MAX_DIGEST_LEN];
1312 char seed_buf[] = { 0x00 };
1313 chunk_t seed = chunk_from_buf(seed_buf);
1314 size_t prf_block_size, i;
1315 pseudo_random_function_t prf_alg;
1316 prf_t *prf;
1317
1318 prf_alg = oakley_to_prf(st->st_oakley.hash);
1319 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1320 prf->set_key(prf, st->st_skeyid_e);
1321 prf_block_size = prf->get_block_size(prf);
1322
1323 for (i = 0;;)
1324 {
1325 prf->get_bytes(prf, seed, &keytemp[i]);
1326 i += prf_block_size;
1327 if (i >= keysize)
1328 {
1329 break;
1330 }
1331 seed = chunk_create(&keytemp[i-prf_block_size], prf_block_size);
1332 }
1333 prf->destroy(prf);
1334 st->st_enc_key = chunk_create(keytemp, keysize);
1335 }
1336 else
1337 {
1338 st->st_enc_key = chunk_create(st->st_skeyid_e.ptr, keysize);
1339 }
1340 st->st_enc_key = chunk_clone(st->st_enc_key);
1341 }
1342
1343 DBG(DBG_CRYPT,
1344 DBG_dump_chunk("Skeyid: ", st->st_skeyid);
1345 DBG_dump_chunk("Skeyid_d:", st->st_skeyid_d);
1346 DBG_dump_chunk("Skeyid_a:", st->st_skeyid_a);
1347 DBG_dump_chunk("Skeyid_e:", st->st_skeyid_e);
1348 DBG_dump_chunk("enc key:", st->st_enc_key);
1349 DBG_dump("IV:", st->st_new_iv, st->st_new_iv_len));
1350 return TRUE;
1351 }
1352
1353 /* Generate HASH_I or HASH_R for ISAKMP Phase I.
1354 * This will *not* generate other hash payloads (eg. Phase II or Quick Mode,
1355 * New Group Mode, or ISAKMP Informational Exchanges).
1356 * If the hashi argument is TRUE, generate HASH_I; if FALSE generate HASH_R.
1357 * If hashus argument is TRUE, we're generating a hash for our end.
1358 * See RFC2409 IKE 5.
1359 */
1360 static void main_mode_hash(struct state *st, chunk_t *hash, bool hashi,
1361 const pb_stream *idpl)
1362 {
1363 chunk_t icookie = { st->st_icookie, COOKIE_SIZE };
1364 chunk_t rcookie = { st->st_rcookie, COOKIE_SIZE };
1365 chunk_t sa_body = { st->st_p1isa.ptr + sizeof(struct isakmp_generic),
1366 st->st_p1isa.len - sizeof(struct isakmp_generic) };
1367 chunk_t id_body = { idpl->start + sizeof(struct isakmp_generic),
1368 pbs_offset(idpl) - sizeof(struct isakmp_generic) };
1369 pseudo_random_function_t prf_alg;
1370 prf_t *prf;
1371
1372 switch (st->st_oakley.auth)
1373 {
1374 case OAKLEY_ECDSA_256:
1375 prf_alg = PRF_HMAC_SHA2_256;
1376 break;
1377 case OAKLEY_ECDSA_384:
1378 prf_alg = PRF_HMAC_SHA2_384;
1379 break;
1380 case OAKLEY_ECDSA_521:
1381 prf_alg = PRF_HMAC_SHA2_512;
1382 break;
1383 default:
1384 prf_alg = oakley_to_prf(st->st_oakley.hash);
1385 }
1386 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1387 prf->set_key(prf, st->st_skeyid);
1388
1389 if (hashi)
1390 {
1391 prf->get_bytes(prf, st->st_gi, NULL);
1392 prf->get_bytes(prf, st->st_gr, NULL);
1393 prf->get_bytes(prf, icookie, NULL);
1394 prf->get_bytes(prf, rcookie, NULL);
1395 }
1396 else
1397 {
1398 prf->get_bytes(prf, st->st_gr, NULL);
1399 prf->get_bytes(prf, st->st_gi, NULL);
1400 prf->get_bytes(prf, rcookie, NULL);
1401 prf->get_bytes(prf, icookie, NULL);
1402 }
1403
1404 DBG(DBG_CRYPT,
1405 DBG_log("hashing %u bytes of SA", sa_body.len)
1406 )
1407 prf->get_bytes(prf, sa_body, NULL);
1408
1409 /* Hash identification payload, without generic payload header.
1410 * We used to reconstruct ID Payload for this purpose, but now
1411 * we use the bytes as they appear on the wire to avoid
1412 * "spelling problems".
1413 */
1414 prf->get_bytes(prf, id_body, hash->ptr);
1415 hash->len = prf->get_block_size(prf);
1416 prf->destroy(prf);
1417 }
1418
1419 /* Create a public key signature of a hash.
1420 * Poorly specified in draft-ietf-ipsec-ike-01.txt 6.1.1.2.
1421 * Use PKCS#1 version 1.5 encryption of hash (called
1422 * RSAES-PKCS1-V1_5) in PKCS#2.
1423 */
1424 static size_t sign_hash(signature_scheme_t scheme, struct connection *c,
1425 u_char sig_val[RSA_MAX_OCTETS], chunk_t hash)
1426 {
1427 size_t sz = 0;
1428 smartcard_t *sc = c->spd.this.sc;
1429
1430 if (sc == NULL) /* no smartcard */
1431 {
1432 chunk_t sig;
1433 private_key_t *private = get_private_key(c);
1434
1435 if (private == NULL)
1436 {
1437 return 0; /* failure: no key to use */
1438 }
1439 if (!private->sign(private, scheme, hash, &sig))
1440 {
1441 return 0;
1442 }
1443 memcpy(sig_val, sig.ptr, sig.len);
1444 sz = sig.len;
1445 free(sig.ptr);
1446 }
1447 else if (sc->valid) /* if valid pin then sign hash on the smartcard */
1448 {
1449 lock_certs_and_keys("sign_hash");
1450 if (!scx_establish_context(sc) || !scx_login(sc))
1451 {
1452 scx_release_context(sc);
1453 unlock_certs_and_keys("sign_hash");
1454 return 0;
1455 }
1456
1457 sz = scx_get_keylength(sc);
1458 if (sz == 0)
1459 {
1460 plog("failed to get keylength from smartcard");
1461 scx_release_context(sc);
1462 unlock_certs_and_keys("sign_hash");
1463 return 0;
1464 }
1465
1466 DBG(DBG_CONTROL | DBG_CRYPT,
1467 DBG_log("signing hash with private key from smartcard (slot: %d, id: %s)"
1468 , (int)sc->slot, sc->id)
1469 )
1470 sz = scx_sign_hash(sc, hash.ptr, hash.len, sig_val, sz) ? sz : 0;
1471 if (!pkcs11_keep_state)
1472 scx_release_context(sc);
1473 unlock_certs_and_keys("sign_hash");
1474 }
1475 return sz;
1476 }
1477
1478 /* Check signature against all public keys we can find.
1479 * If we need keys from DNS KEY records, and they haven't been fetched,
1480 * return STF_SUSPEND to ask for asynch DNS lookup.
1481 *
1482 * Note: parameter keys_from_dns contains results of DNS lookup for key
1483 * or is NULL indicating lookup not yet tried.
1484 *
1485 * take_a_crack is a helper function. Mostly forensic.
1486 * If only we had coroutines.
1487 */
1488 struct tac_state {
1489 struct state *st;
1490 chunk_t hash;
1491 chunk_t sig;
1492 int tried_cnt; /* number of keys tried */
1493 };
1494
1495 static bool take_a_crack(struct tac_state *s, pubkey_t *kr)
1496 {
1497 public_key_t *pub_key = kr->public_key;
1498 identification_t *keyid = pub_key->get_id(pub_key, ID_PUBKEY_INFO_SHA1);
1499 signature_scheme_t scheme;
1500
1501 s->tried_cnt++;
1502 scheme = oakley_to_signature_scheme(s->st->st_oakley.auth);
1503
1504 if (pub_key->verify(pub_key, scheme, s->hash, s->sig))
1505 {
1506 DBG(DBG_CRYPT | DBG_CONTROL,
1507 DBG_log("%s check passed with keyid %Y",
1508 enum_show(&oakley_auth_names, s->st->st_oakley.auth), keyid)
1509 )
1510 unreference_key(&s->st->st_peer_pubkey);
1511 s->st->st_peer_pubkey = reference_key(kr);
1512 return TRUE;
1513 }
1514 else
1515 {
1516 DBG(DBG_CRYPT,
1517 DBG_log("%s check failed with keyid %Y",
1518 enum_show(&oakley_auth_names, s->st->st_oakley.auth), keyid)
1519 )
1520 return FALSE;
1521 }
1522 }
1523
1524 static stf_status check_signature(key_type_t key_type, const struct id* peer,
1525 struct state *st, chunk_t hash,
1526 const pb_stream *sig_pbs,
1527 #ifdef USE_KEYRR
1528 const pubkey_list_t *keys_from_dns,
1529 #endif /* USE_KEYRR */
1530 const struct gw_info *gateways_from_dns)
1531 {
1532 const struct connection *c = st->st_connection;
1533 struct tac_state s;
1534
1535 s.st = st;
1536 s.hash = hash;
1537 s.sig = chunk_create(sig_pbs->cur, pbs_left(sig_pbs));
1538 s.tried_cnt = 0;
1539
1540 /* try all gateway records hung off c */
1541 if (c->policy & POLICY_OPPO)
1542 {
1543 struct gw_info *gw;
1544
1545 for (gw = c->gw_info; gw != NULL; gw = gw->next)
1546 {
1547 /* only consider entries that have a key and are for our peer */
1548 if (gw->gw_key_present && same_id(&gw->gw_id, &c->spd.that.id)&&
1549 take_a_crack(&s, gw->key))
1550 {
1551 return STF_OK;
1552 }
1553 }
1554 }
1555
1556 /* try all appropriate Public keys */
1557 {
1558 pubkey_list_t *p, **pp;
1559
1560 pp = &pubkeys;
1561
1562 for (p = pubkeys; p != NULL; p = *pp)
1563 {
1564 pubkey_t *key = p->key;
1565 key_type_t type = key->public_key->get_type(key->public_key);
1566
1567 if (type == key_type && same_id(peer, &key->id))
1568 {
1569 time_t now = time(NULL);
1570
1571 /* check if found public key has expired */
1572 if (key->until_time != UNDEFINED_TIME && key->until_time < now)
1573 {
1574 loglog(RC_LOG_SERIOUS,
1575 "cached public key has expired and has been deleted");
1576 *pp = free_public_keyentry(p);
1577 continue; /* continue with next public key */
1578 }
1579
1580 if (take_a_crack(&s, key))
1581 {
1582 return STF_OK;
1583 }
1584 }
1585 pp = &p->next;
1586 }
1587 }
1588
1589 /* if no key was found and that side of connection is
1590 * key_from_DNS_on_demand then go search DNS for keys for peer.
1591 */
1592 if (s.tried_cnt == 0 && c->spd.that.key_from_DNS_on_demand)
1593 {
1594 if (gateways_from_dns != NULL)
1595 {
1596 /* TXT keys */
1597 const struct gw_info *gwp;
1598
1599 for (gwp = gateways_from_dns; gwp != NULL; gwp = gwp->next)
1600 {
1601 if (gwp->gw_key_present && take_a_crack(&s, gwp->key))
1602 {
1603 return STF_OK;
1604 }
1605 }
1606 }
1607 #ifdef USE_KEYRR
1608 else if (keys_from_dns != NULL)
1609 {
1610 /* KEY keys */
1611 const pubkey_list_t *kr;
1612
1613 for (kr = keys_from_dns; kr != NULL; kr = kr->next)
1614 {
1615 if (kr->key->alg == PUBKEY_ALG_RSA && take_a_crack(&s, kr->key))
1616 {
1617 return STF_OK;
1618 }
1619 }
1620 }
1621 #endif /* USE_KEYRR */
1622 else
1623 {
1624 /* nothing yet: ask for asynch DNS lookup */
1625 return STF_SUSPEND;
1626 }
1627 }
1628
1629 /* no acceptable key was found: diagnose */
1630 {
1631 char id_buf[BUF_LEN]; /* arbitrary limit on length of ID reported */
1632
1633 idtoa(peer, id_buf, sizeof(id_buf));
1634
1635 if (s.tried_cnt == 0)
1636 {
1637 loglog(RC_LOG_SERIOUS, "no public key known for '%s'", id_buf);
1638 }
1639 else if (s.tried_cnt == 1)
1640 {
1641 loglog(RC_LOG_SERIOUS, "signature check for '%s' failed: "
1642 " wrong key?; tried %d", id_buf, s.tried_cnt);
1643 DBG(DBG_CONTROL,
1644 DBG_log("public key for '%s' failed: "
1645 "decrypted SIG payload into a malformed ECB", id_buf)
1646 )
1647 }
1648 else
1649 {
1650 loglog(RC_LOG_SERIOUS, "signature check for '%s' failed: "
1651 "tried %d keys but none worked.", id_buf, s.tried_cnt);
1652 DBG(DBG_CONTROL,
1653 DBG_log("all %d public keys for '%s' failed: "
1654 "best decrypted SIG payload into a malformed ECB",
1655 s.tried_cnt, id_buf)
1656 )
1657 }
1658 return STF_FAIL + INVALID_KEY_INFORMATION;
1659 }
1660 }
1661
1662 static notification_t accept_nonce(struct msg_digest *md, chunk_t *dest,
1663 const char *name)
1664 {
1665 pb_stream *nonce_pbs = &md->chain[ISAKMP_NEXT_NONCE]->pbs;
1666 size_t len = pbs_left(nonce_pbs);
1667
1668 if (len < MINIMUM_NONCE_SIZE || MAXIMUM_NONCE_SIZE < len)
1669 {
1670 loglog(RC_LOG_SERIOUS, "%s length not between %d and %d"
1671 , name , MINIMUM_NONCE_SIZE, MAXIMUM_NONCE_SIZE);
1672 return PAYLOAD_MALFORMED; /* ??? */
1673 }
1674 free(dest->ptr);
1675 *dest = chunk_create(nonce_pbs->cur, len);
1676 *dest = chunk_clone(*dest);
1677 return NOTHING_WRONG;
1678 }
1679
1680 /* encrypt message, sans fixed part of header
1681 * IV is fetched from st->st_new_iv and stored into st->st_iv.
1682 * The theory is that there will be no "backing out", so we commit to IV.
1683 * We also close the pbs.
1684 */
1685 bool
1686 encrypt_message(pb_stream *pbs, struct state *st)
1687 {
1688 u_int8_t *enc_start = pbs->start + sizeof(struct isakmp_hdr);
1689 size_t enc_len = pbs_offset(pbs) - sizeof(struct isakmp_hdr);
1690 chunk_t data, iv;
1691 char *new_iv;
1692 size_t crypter_block_size;
1693 encryption_algorithm_t enc_alg;
1694 crypter_t *crypter;
1695
1696 DBG_cond_dump(DBG_CRYPT | DBG_RAW, "encrypting:\n", enc_start, enc_len);
1697 enc_alg = oakley_to_encryption_algorithm(st->st_oakley.encrypt);
1698 crypter = lib->crypto->create_crypter(lib->crypto, enc_alg, st->st_enc_key.len);
1699 crypter_block_size = crypter->get_block_size(crypter);
1700
1701 /* Pad up to multiple of encryption blocksize.
1702 * See the description associated with the definition of
1703 * struct isakmp_hdr in packet.h.
1704 */
1705 {
1706 size_t padding = pad_up(enc_len, crypter_block_size);
1707
1708 if (padding != 0)
1709 {
1710 if (!out_zero(padding, pbs, "encryption padding"))
1711 return FALSE;
1712 enc_len += padding;
1713 }
1714 }
1715
1716 DBG(DBG_CRYPT, DBG_log("encrypting using %s", enum_show(&oakley_enc_names, st->st_oakley.encrypt)));
1717 data = chunk_create(enc_start, enc_len);
1718
1719 /* form iv by truncation */
1720 st->st_new_iv_len = crypter_block_size;
1721 iv = chunk_create(st->st_new_iv, st->st_new_iv_len);
1722
1723 crypter->set_key(crypter, st->st_enc_key);
1724 crypter->encrypt(crypter, data, iv, NULL);
1725 crypter->destroy(crypter);
1726
1727 new_iv = data.ptr + data.len - crypter_block_size;
1728 memcpy(st->st_new_iv, new_iv, crypter_block_size);
1729 update_iv(st);
1730 DBG_cond_dump(DBG_CRYPT, "next IV:", st->st_iv, st->st_iv_len);
1731 close_message(pbs);
1732 return TRUE;
1733 }
1734
1735 /* Compute HASH(1), HASH(2) of Quick Mode.
1736 * HASH(1) is part of Quick I1 message.
1737 * HASH(2) is part of Quick R1 message.
1738 * Used by: quick_outI1, quick_inI1_outR1 (twice), quick_inR1_outI2
1739 * (see RFC 2409 "IKE" 5.5, pg. 18 or draft-ietf-ipsec-ike-01.txt 6.2 pg 25)
1740 */
1741 static size_t quick_mode_hash12(u_char *dest, u_char *start, u_char *roof,
1742 const struct state *st, const msgid_t *msgid,
1743 bool hash2)
1744 {
1745 chunk_t msgid_chunk = chunk_from_thing(*msgid);
1746 chunk_t msg_chunk = { start, roof - start };
1747 pseudo_random_function_t prf_alg;
1748 prf_t *prf;
1749 size_t prf_block_size;
1750
1751 prf_alg = oakley_to_prf(st->st_oakley.hash);
1752 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1753 prf->set_key(prf, st->st_skeyid_a);
1754 prf->get_bytes(prf, msgid_chunk, NULL);
1755 if (hash2)
1756 {
1757 prf->get_bytes(prf, st->st_ni, NULL); /* include Ni_b in the hash */
1758 }
1759 prf->get_bytes(prf, msg_chunk, dest);
1760 prf_block_size = prf->get_block_size(prf);
1761 prf->destroy(prf);
1762
1763 DBG(DBG_CRYPT,
1764 DBG_log("HASH(%d) computed:", hash2 + 1);
1765 DBG_dump("", dest, prf_block_size)
1766 )
1767 return prf_block_size;
1768 }
1769
1770 /* Compute HASH(3) in Quick Mode (part of Quick I2 message).
1771 * Used by: quick_inR1_outI2, quick_inI2
1772 * See RFC2409 "The Internet Key Exchange (IKE)" 5.5.
1773 * NOTE: this hash (unlike HASH(1) and HASH(2)) ONLY covers the
1774 * Message ID and Nonces. This is a mistake.
1775 */
1776 static size_t quick_mode_hash3(u_char *dest, struct state *st)
1777 {
1778 char seed_buf[] = { 0x00 };
1779 chunk_t seed_chunk = chunk_from_buf(seed_buf);
1780 chunk_t msgid_chunk = chunk_from_thing(st->st_msgid);
1781 pseudo_random_function_t prf_alg;
1782 prf_t *prf;
1783 size_t prf_block_size;
1784
1785 prf_alg = oakley_to_prf(st->st_oakley.hash);
1786 prf = lib->crypto->create_prf(lib->crypto, prf_alg);
1787 prf->set_key(prf, st->st_skeyid_a);
1788 prf->get_bytes(prf, seed_chunk, NULL );
1789 prf->get_bytes(prf, msgid_chunk, NULL);
1790 prf->get_bytes(prf, st->st_ni, NULL);
1791 prf->get_bytes(prf, st->st_nr, dest);
1792 prf_block_size = prf->get_block_size(prf);
1793 prf->destroy(prf);
1794
1795 DBG_cond_dump(DBG_CRYPT, "HASH(3) computed:", dest, prf_block_size);
1796 return prf_block_size;
1797 }
1798
1799 /* Compute Phase 2 IV.
1800 * Uses Phase 1 IV from st_iv; puts result in st_new_iv.
1801 */
1802 void init_phase2_iv(struct state *st, const msgid_t *msgid)
1803 {
1804 chunk_t iv_chunk = { st->st_ph1_iv, st->st_ph1_iv_len };
1805 chunk_t msgid_chunk = chunk_from_thing(*msgid);
1806 hash_algorithm_t hash_alg;
1807 hasher_t *hasher;
1808
1809 hash_alg = oakley_to_hash_algorithm(st->st_oakley.hash);
1810 hasher = lib->crypto->create_hasher(lib->crypto, hash_alg);
1811
1812 DBG_cond_dump(DBG_CRYPT, "last Phase 1 IV:",
1813 st->st_ph1_iv, st->st_ph1_iv_len);
1814
1815 st->st_new_iv_len = hasher->get_hash_size(hasher);
1816 passert(st->st_new_iv_len <= sizeof(st->st_new_iv));
1817
1818 hasher->get_hash(hasher, iv_chunk, NULL);
1819 hasher->get_hash(hasher, msgid_chunk, st->st_new_iv);
1820 hasher->destroy(hasher);
1821
1822 DBG_cond_dump(DBG_CRYPT, "computed Phase 2 IV:",
1823 st->st_new_iv, st->st_new_iv_len);
1824 }
1825
1826 /* Initiate quick mode.
1827 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
1828 * (see RFC 2409 "IKE" 5.5)
1829 * Note: this is not called from demux.c
1830 */
1831
1832 static bool emit_subnet_id(ip_subnet *net, u_int8_t np, u_int8_t protoid,
1833 u_int16_t port, pb_stream *outs)
1834 {
1835 struct isakmp_ipsec_id id;
1836 pb_stream id_pbs;
1837 ip_address ta;
1838 const unsigned char *tbp;
1839 size_t tal;
1840
1841 id.isaiid_np = np;
1842 id.isaiid_idtype = subnetishost(net)
1843 ? aftoinfo(subnettypeof(net))->id_addr
1844 : aftoinfo(subnettypeof(net))->id_subnet;
1845 id.isaiid_protoid = protoid;
1846 id.isaiid_port = port;
1847
1848 if (!out_struct(&id, &isakmp_ipsec_identification_desc, outs, &id_pbs))
1849 return FALSE;
1850
1851 networkof(net, &ta);
1852 tal = addrbytesptr(&ta, &tbp);
1853 if (!out_raw(tbp, tal, &id_pbs, "client network"))
1854 return FALSE;
1855
1856 if (!subnetishost(net))
1857 {
1858 maskof(net, &ta);
1859 tal = addrbytesptr(&ta, &tbp);
1860 if (!out_raw(tbp, tal, &id_pbs, "client mask"))
1861 return FALSE;
1862 }
1863
1864 close_output_pbs(&id_pbs);
1865 return TRUE;
1866 }
1867
1868 stf_status quick_outI1(int whack_sock, struct state *isakmp_sa,
1869 struct connection *c, lset_t policy, unsigned long try,
1870 so_serial_t replacing)
1871 {
1872 struct state *st = duplicate_state(isakmp_sa);
1873 pb_stream reply; /* not really a reply */
1874 pb_stream rbody;
1875 u_char /* set by START_HASH_PAYLOAD: */
1876 *r_hashval, /* where in reply to jam hash value */
1877 *r_hash_start; /* start of what is to be hashed */
1878 bool has_client = c->spd.this.has_client || c->spd.that.has_client ||
1879 c->spd.this.protocol || c->spd.that.protocol ||
1880 c->spd.this.port || c->spd.that.port;
1881
1882 bool send_natoa = FALSE;
1883 u_int8_t np = ISAKMP_NEXT_NONE;
1884
1885 st->st_whack_sock = whack_sock;
1886 st->st_connection = c;
1887 set_cur_state(st); /* we must reset before exit */
1888 st->st_policy = policy;
1889 st->st_try = try;
1890
1891 st->st_myuserprotoid = c->spd.this.protocol;
1892 st->st_peeruserprotoid = c->spd.that.protocol;
1893 st->st_myuserport = c->spd.this.port;
1894 st->st_peeruserport = c->spd.that.port;
1895
1896 st->st_msgid = generate_msgid(isakmp_sa);
1897 st->st_state = STATE_QUICK_I1;
1898
1899 insert_state(st); /* needs cookies, connection, and msgid */
1900
1901 if (replacing == SOS_NOBODY)
1902 plog("initiating Quick Mode %s {using isakmp#%lu}"
1903 , prettypolicy(policy)
1904 , isakmp_sa->st_serialno);
1905 else
1906 plog("initiating Quick Mode %s to replace #%lu {using isakmp#%lu}"
1907 , prettypolicy(policy)
1908 , replacing
1909 , isakmp_sa->st_serialno);
1910
1911 if (isakmp_sa->nat_traversal & NAT_T_DETECTED)
1912 {
1913 /* Duplicate nat_traversal status in new state */
1914 st->nat_traversal = isakmp_sa->nat_traversal;
1915
1916 if (isakmp_sa->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME))
1917 has_client = TRUE;
1918
1919 nat_traversal_change_port_lookup(NULL, st);
1920 }
1921 else
1922 st->nat_traversal = 0;
1923
1924 /* are we going to send a NAT-OA payload? */
1925 if ((st->nat_traversal & NAT_T_WITH_NATOA)
1926 && !(st->st_policy & POLICY_TUNNEL)
1927 && (st->nat_traversal & LELEM(NAT_TRAVERSAL_NAT_BHND_ME)))
1928 {
1929 send_natoa = TRUE;
1930 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
1931 ISAKMP_NEXT_NATOA_RFC : ISAKMP_NEXT_NATOA_DRAFTS;
1932 }
1933
1934 /* set up reply */
1935 init_pbs(&reply, reply_buffer, sizeof(reply_buffer), "reply packet");
1936
1937 /* HDR* out */
1938 {
1939 struct isakmp_hdr hdr;
1940
1941 hdr.isa_version = ISAKMP_MAJOR_VERSION << ISA_MAJ_SHIFT | ISAKMP_MINOR_VERSION;
1942 hdr.isa_np = ISAKMP_NEXT_HASH;
1943 hdr.isa_xchg = ISAKMP_XCHG_QUICK;
1944 hdr.isa_msgid = st->st_msgid;
1945 hdr.isa_flags = ISAKMP_FLAG_ENCRYPTION;
1946 memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE);
1947 memcpy(hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
1948 if (!out_struct(&hdr, &isakmp_hdr_desc, &reply, &rbody))
1949 {
1950 reset_cur_state();
1951 return STF_INTERNAL_ERROR;
1952 }
1953 }
1954
1955 /* HASH(1) -- create and note space to be filled later */
1956 START_HASH_PAYLOAD(rbody, ISAKMP_NEXT_SA);
1957
1958 /* SA out */
1959
1960 /*
1961 * See if pfs_group has been specified for this conn,
1962 * if not, fallback to old use-same-as-P1 behaviour
1963 */
1964 #ifndef NO_IKE_ALG
1965 if (st->st_connection)
1966 st->st_pfs_group = ike_alg_pfsgroup(st->st_connection, policy);
1967 if (!st->st_pfs_group)
1968 #endif
1969 /* If PFS specified, use the same group as during Phase 1:
1970 * since no negotiation is possible, we pick one that is
1971 * very likely supported.
1972 */
1973 st->st_pfs_group = policy & POLICY_PFS? isakmp_sa->st_oakley.group : NULL;
1974
1975 /* Emit SA payload based on a subset of the policy bits.
1976 * POLICY_COMPRESS is considered iff we can do IPcomp.
1977 */
1978 {
1979 lset_t pm = POLICY_ENCRYPT | POLICY_AUTHENTICATE;
1980
1981 if (can_do_IPcomp)
1982 pm |= POLICY_COMPRESS;
1983
1984 if (!out_sa(&rbody
1985 , &ipsec_sadb[(st->st_policy & pm) >> POLICY_IPSEC_SHIFT]
1986 , st, FALSE, ISAKMP_NEXT_NONCE))
1987 {
1988 reset_cur_state();
1989 return STF_INTERNAL_ERROR;
1990 }
1991 }
1992
1993 /* Ni out */
1994 if (!build_and_ship_nonce(&st->st_ni, &rbody
1995 , policy & POLICY_PFS? ISAKMP_NEXT_KE : has_client? ISAKMP_NEXT_ID : np
1996 , "Ni"))
1997 {
1998 reset_cur_state();
1999 return STF_INTERNAL_ERROR;
2000 }
2001
2002 /* [ KE ] out (for PFS) */
2003
2004 if (st->st_pfs_group != NULL)
2005 {
2006 if (!build_and_ship_KE(st, &st->st_gi, st->st_pfs_group
2007 , &rbody, has_client? ISAKMP_NEXT_ID : np))
2008 {
2009 reset_cur_state();
2010 return STF_INTERNAL_ERROR;
2011 }
2012 }
2013
2014 /* [ IDci, IDcr ] out */
2015 if (has_client)
2016 {
2017 /* IDci (we are initiator), then IDcr (peer is responder) */
2018 if (!emit_subnet_id(&c->spd.this.client
2019 , ISAKMP_NEXT_ID, st->st_myuserprotoid, st->st_myuserport, &rbody)
2020 || !emit_subnet_id(&c->spd.that.client
2021 , np, st->st_peeruserprotoid, st->st_peeruserport, &rbody))
2022 {
2023 reset_cur_state();
2024 return STF_INTERNAL_ERROR;
2025 }
2026 }
2027
2028 /* Send NAT-OA if our address is NATed */
2029 if (send_natoa)
2030 {
2031 if (!nat_traversal_add_natoa(ISAKMP_NEXT_NONE, &rbody, st))
2032 {
2033 reset_cur_state();
2034 return STF_INTERNAL_ERROR;
2035 }
2036 }
2037
2038 /* finish computing HASH(1), inserting it in output */
2039 (void) quick_mode_hash12(r_hashval, r_hash_start, rbody.cur
2040 , st, &st->st_msgid, FALSE);
2041
2042 /* encrypt message, except for fixed part of header */
2043
2044 init_phase2_iv(isakmp_sa, &st->st_msgid);
2045 st->st_new_iv_len = isakmp_sa->st_new_iv_len;
2046 memcpy(st->st_new_iv, isakmp_sa->st_new_iv, st->st_new_iv_len);
2047
2048 if (!encrypt_message(&rbody, st))
2049 {
2050 reset_cur_state();
2051 return STF_INTERNAL_ERROR;
2052 }
2053
2054 /* save packet, now that we know its size */
2055 st->st_tpacket = chunk_create(reply.start, pbs_offset(&reply));
2056 st->st_tpacket = chunk_clone(st->st_tpacket);
2057
2058 /* send the packet */
2059
2060 send_packet(st, "quick_outI1");
2061
2062 delete_event(st);
2063 event_schedule(EVENT_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st);
2064
2065 if (replacing == SOS_NOBODY)
2066 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2067 , "%s: initiate"
2068 , enum_name(&state_names, st->st_state));
2069 else
2070 whack_log(RC_NEW_STATE + STATE_QUICK_I1
2071 , "%s: initiate to replace #%lu"
2072 , enum_name(&state_names, st->st_state)
2073 , replacing);
2074 reset_cur_state();
2075 return STF_OK;
2076 }
2077
2078
2079 /*
2080 * Decode the CERT payload of Phase 1.
2081 */
2082 static void decode_cert(struct msg_digest *md)
2083 {
2084 struct payload_digest *p;
2085
2086 for (p = md->chain[ISAKMP_NEXT_CERT]; p != NULL; p = p->next)
2087 {
2088 struct isakmp_cert *const cert = &p->payload.cert;
2089 chunk_t blob;
2090 time_t valid_until;
2091 blob.ptr = p->pbs.cur;
2092 blob.len = pbs_left(&p->pbs);
2093 if (cert->isacert_type == CERT_X509_SIGNATURE)
2094 {
2095 x509cert_t cert = empty_x509cert;
2096 if (parse_x509cert(blob, 0, &cert))
2097 {
2098 if (verify_x509cert(&cert, strict_crl_policy, &valid_until))
2099 {
2100 DBG(DBG_PARSING,
2101 DBG_log("Public key validated")
2102 )
2103 add_x509_public_key(&cert, valid_until, DAL_SIGNED);
2104 }
2105 else
2106 {
2107 plog("X.509 certificate rejected");
2108 }
2109 DESTROY_IF(cert.public_key);
2110 free_generalNames(cert.subjectAltName, FALSE);
2111 free_generalNames(cert.crlDistributionPoints, FALSE);
2112 }
2113 else
2114 plog("Syntax error in X.509 certificate");
2115 }
2116 else if (cert->isacert_type == CERT_PKCS7_WRAPPED_X509)
2117 {
2118 x509cert_t *cert = NULL;
2119
2120 if (pkcs7_parse_signedData(blob, NULL, &cert, NULL, NULL))
2121 store_x509certs(&cert, strict_crl_policy);
2122 else
2123 plog("Syntax error in PKCS#7 wrapped X.509 certificates");
2124 }
2125 else
2126 {
2127 loglog(RC_LOG_SERIOUS, "ignoring %s certificate payload",
2128 enum_show(&cert_type_names, cert->isacert_type));
2129 DBG_cond_dump_chunk(DBG_PARSING, "CERT:\n", blob);
2130 }
2131 }
2132 }
2133
2134 /*
2135 * Decode the CR payload of Phase 1.
2136 */
2137 static void decode_cr(struct msg_digest *md, struct connection *c)
2138 {
2139 struct payload_digest *p;
2140
2141 for (p = md->chain[ISAKMP_NEXT_CR]; p != NULL; p = p->next)
2142 {
2143 struct isakmp_cr *const cr = &p->payload.cr;
2144 chunk_t ca_name;
2145
2146 ca_name.len = pbs_left(&p->pbs);
2147 ca_name.ptr = (ca_name.len > 0)? p->pbs.cur : NULL;
2148
2149 DBG_cond_dump_chunk(DBG_PARSING, "CR", ca_name);
2150
2151 if (cr->isacr_type == CERT_X509_SIGNATURE)
2152 {
2153 char buf[BUF_LEN];
2154
2155 if (ca_name.len > 0)
2156 {
2157 generalName_t *gn;
2158
2159 if (!is_asn1(ca_name))
2160 continue;
2161
2162 gn = malloc_thing(generalName_t);
2163 ca_name = chunk_clone(ca_name);
2164 gn->kind = GN_DIRECTORY_NAME;
2165 gn->name = ca_name;
2166 gn->next = c->requested_ca;
2167 c->requested_ca = gn;
2168 }
2169 c->got_certrequest = TRUE;
2170
2171 DBG(DBG_PARSING | DBG_CONTROL,
2172 dntoa_or_null(buf, BUF_LEN, ca_name, "%any");
2173 DBG_log("requested CA: '%s'", buf);
2174 )
2175 }
2176 else
2177 loglog(RC_LOG_SERIOUS, "ignoring %s certificate request payload",
2178 enum_show(&cert_type_names, cr->isacr_type));
2179 }
2180 }
2181
2182 /* Decode the ID payload of Phase 1 (main_inI3_outR3 and main_inR3)
2183 * Note: we may change connections as a result.
2184 * We must be called before SIG or HASH are decoded since we
2185 * may change the peer's public key or ID.
2186 */
2187 static bool decode_peer_id(struct msg_digest *md, struct id *peer)
2188 {
2189 struct state *const st = md->st;
2190 struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
2191 const pb_stream *const id_pbs = &id_pld->pbs;
2192 struct isakmp_id *const id = &id_pld->payload.id;
2193
2194 /* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
2195 * It talks about the protocol ID and Port fields of the ID
2196 * Payload, but they don't exist as such in Phase 1.
2197 * We use more appropriate names.
2198 * isaid_doi_specific_a is in place of Protocol ID.
2199 * isaid_doi_specific_b is in place of Port.
2200 * Besides, there is no good reason for allowing these to be
2201 * other than 0 in Phase 1.
2202 */
2203 if ((st->nat_traversal & NAT_T_WITH_PORT_FLOATING)
2204 && id->isaid_doi_specific_a == IPPROTO_UDP
2205 && (id->isaid_doi_specific_b == 0 || id->isaid_doi_specific_b == NAT_T_IKE_FLOAT_PORT))
2206 {
2207 DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
2208 "accepted with port_floating NAT-T",
2209 id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2210 }
2211 else if (!(id->isaid_doi_specific_a == 0 && id->isaid_doi_specific_b == 0)
2212 && !(id->isaid_doi_specific_a == IPPROTO_UDP && id->isaid_doi_specific_b == IKE_UDP_PORT))
2213 {
2214 loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload must be 0/0 or %d/%d"
2215 " but are %d/%d"
2216 , IPPROTO_UDP, IKE_UDP_PORT
2217 , id->isaid_doi_specific_a, id->isaid_doi_specific_b);
2218 return FALSE;
2219 }
2220
2221 peer->kind = id->isaid_idtype;
2222
2223 switch (peer->kind)
2224 {
2225 case ID_IPV4_ADDR:
2226 case ID_IPV6_ADDR:
2227 /* failure mode for initaddr is probably inappropriate address length */
2228 {
2229 err_t ugh = initaddr(id_pbs->cur, pbs_left(id_pbs)
2230 , peer->kind == ID_IPV4_ADDR? AF_INET : AF_INET6
2231 , &peer->ip_addr);
2232
2233 if (ugh != NULL)
2234 {
2235 loglog(RC_LOG_SERIOUS, "improper %s identification payload: %s"
2236 , enum_show(&ident_names, peer->kind), ugh);
2237 /* XXX Could send notification back */
2238 return FALSE;
2239 }
2240 }
2241 break;
2242
2243 case ID_USER_FQDN:
2244 if (memchr(id_pbs->cur, '@', pbs_left(id_pbs)) == NULL)
2245 {
2246 loglog(RC_LOG_SERIOUS, "peer's ID_USER_FQDN contains no @");
2247 return FALSE;
2248 }
2249 /* FALLTHROUGH */
2250 case ID_FQDN:
2251 if (memchr(id_pbs->cur, '\0', pbs_left(id_pbs)) != NULL)
2252 {
2253 loglog(RC_LOG_SERIOUS, "Phase 1 ID Payload of type %s contains a NUL"
2254 , enum_show(&ident_names, peer->kind));
2255 return FALSE;
2256 }
2257
2258 /* ??? ought to do some more sanity check, but what? */
2259
2260 peer->name = chunk_create(id_pbs->cur, pbs_left(id_pbs));
2261 break;
2262
2263 case ID_KEY_ID:
2264 peer->name = chunk_create(id_pbs->cur, pbs_left(id_pbs));
2265 DBG(DBG_PARSING,
2266 DBG_dump_chunk("KEY ID:", peer->name));
2267 break;
2268
2269 case ID_DER_ASN1_DN:
2270 peer->name = chunk_create(id_pbs->cur, pbs_left(id_pbs));
2271 DBG(DBG_PARSING,
2272 DBG_dump_chunk("DER ASN1 DN:", peer->name));
2273 break;
2274
2275 default:
2276 /* XXX Could send notification back */
2277 loglog(RC_LOG_SERIOUS, "Unacceptable identity type (%s) in Phase 1 ID Payload"
2278 , enum_show(&ident_names, peer->kind));
2279 return FALSE;
2280 }
2281
2282 {
2283 char buf[BUF_LEN];
2284
2285 idtoa(peer, buf, sizeof(buf));
2286 plog("Peer ID is %s: '%s'",
2287 enum_show(&ident_names, id->isaid_idtype), buf);
2288 }
2289
2290 /* check for certificates */
2291 decode_cert(md);
2292 return TRUE;
2293 }
2294
2295 /* Now that we've decoded the ID payload, let's see if we
2296 * need to switch connections.
2297 * We must not switch horses if we initiated:
2298 * - if the initiation was explicit, we'd be ignoring user's intent
2299 * - if opportunistic, we'll lose our HOLD info
2300 */
2301 static bool switch_connection(struct msg_digest *md, struct id *peer,
2302 bool initiator)
2303 {
2304 struct state *const st = md->st;
2305 struct connection *c = st->st_connection;
2306
2307 chunk_t peer_ca = (st->st_peer_pubkey != NULL)
2308 ? st->st_peer_pubkey->issuer : chunk_empty;
2309
2310 DBG(DBG_CONTROL,
2311 char buf[BUF_LEN];
2312
2313 dntoa_or_null(buf, BUF_LEN, peer_ca, "%none");
2314 DBG_log("peer CA: '%s'", buf);
2315 )
2316
2317 if (initiator)
2318 {
2319 int pathlen;
2320
2321 if (!same_id(&c->spd.that.id, peer))
2322 {
2323 char expect[BUF_LEN]
2324 , found[BUF_LEN];
2325
2326 idtoa(&c->spd.that.id, expect, sizeof(expect));
2327 idtoa(peer, found, sizeof(found));
2328 loglog(RC_LOG_SERIOUS
2329 , "we require peer to have ID '%s', but peer declares '%s'"
2330 , expect, found);
2331 return FALSE;
2332 }
2333
2334 DBG(DBG_CONTROL,
2335 char buf[BUF_LEN];
2336
2337 dntoa_or_null(buf, BUF_LEN, c->spd.that.ca, "%none");
2338 DBG_log("required CA: '%s'", buf);
2339 )
2340
2341 if (!trusted_ca(peer_ca, c->spd.that.ca, &pathlen))
2342 {
2343 loglog(RC_LOG_SERIOUS
2344 , "we don't accept the peer's CA");
2345 return FALSE;
2346 }
2347 }
2348 else
2349 {
2350 struct connection *r;
2351
2352 /* check for certificate requests */
2353 decode_cr(md, c);
2354
2355 r = refine_host_connection(st, peer, peer_ca);
2356
2357 /* delete the collected certificate requests */
2358 free_generalNames(c->requested_ca, TRUE);
2359 c->requested_ca = NULL;
2360
2361 if (r == NULL)
2362 {
2363 char buf[BUF_LEN];
2364
2365 idtoa(peer, buf, sizeof(buf));
2366 loglog(RC_LOG_SERIOUS, "no suitable connection for peer '%s'", buf);
2367 return FALSE;
2368 }
2369
2370 DBG(DBG_CONTROL,
2371 char buf[BUF_LEN];
2372
2373 dntoa_or_null(buf, BUF_LEN, r->spd.this.ca, "%none");
2374 DBG_log("offered CA: '%s'", buf);
2375 )
2376
2377 if (r != c)
2378 {
2379 /* apparently, r is an improvement on c -- replace */
2380
2381 DBG(DBG_CONTROL
2382 , DBG_log("switched from \"%s\" to \"%s\"", c->name, r->name));
2383 if (r->kind == CK_TEMPLATE)
2384 {
2385 /* instantiate it, filling in peer's ID */
2386 r = rw_instantiate(r, &c->spd.that.host_addr
2387 , c->spd.that.host_port, NULL, peer);
2388 }
2389
2390 /* copy certificate request info */
2391 r->got_certrequest = c->got_certrequest;
2392
2393 st->st_connection = r; /* kill reference to c */
2394 set_cur_connection(r);
2395 connection_discard(c);
2396 }
2397 else if (c->spd.that.has_id_wildcards)
2398 {
2399 free_id_content(&c->spd.that.id);
2400 c->spd.that.id = *peer;
2401 c->spd.that.has_id_wildcards = FALSE;
2402 unshare_id_content(&c->spd.that.id);
2403 }
2404 }
2405 return TRUE;
2406 }
2407
2408 /* Decode the variable part of an ID packet (during Quick Mode).
2409 * This is designed for packets that identify clients, not peers.
2410 * Rejects 0.0.0.0/32 or IPv6 equivalent because
2411 * (1) it is wrong and (2) we use this value for inband signalling.
2412 */
2413 static bool decode_net_id(struct isakmp_ipsec_id *id, pb_stream *id_pbs,
2414 ip_subnet *net, const char *which)
2415 {
2416 const struct af_info *afi = NULL;
2417
2418 /* Note: the following may be a pointer into static memory
2419 * that may be recycled, but only if the type is not known.
2420 * That case is disposed of very early -- in the first switch.
2421 */
2422 const char *idtypename = enum_show(&ident_names, id->isaiid_idtype);
2423
2424 switch (id->isaiid_idtype)
2425 {
2426 case ID_IPV4_ADDR:
2427 case ID_IPV4_ADDR_SUBNET:
2428 case ID_IPV4_ADDR_RANGE:
2429 afi = &af_inet4_info;
2430 break;
2431 case ID_IPV6_ADDR:
2432 case ID_IPV6_ADDR_SUBNET:
2433 case ID_IPV6_ADDR_RANGE:
2434 afi = &af_inet6_info;
2435 break;
2436 case ID_FQDN:
2437 return TRUE;
2438 default:
2439 /* XXX support more */
2440 loglog(RC_LOG_SERIOUS, "unsupported ID type %s"
2441 , idtypename);
2442 /* XXX Could send notification back */
2443 return FALSE;
2444 }
2445
2446 switch (id->isaiid_idtype)
2447 {
2448 case ID_IPV4_ADDR:
2449 case ID_IPV6_ADDR:
2450 {
2451 ip_address temp_address;
2452 err_t ugh;
2453
2454 ugh = initaddr(id_pbs->cur, pbs_left(id_pbs), afi->af, &temp_address);
2455
2456 if (ugh != NULL)
2457 {
2458 loglog(RC_LOG_SERIOUS, "%s ID payload %s has wrong length in Quick I1 (%s)"
2459 , which, idtypename, ugh);
2460 /* XXX Could send notification back */
2461 return FALSE;
2462 }
2463 if (isanyaddr(&temp_address))
2464 {
2465 loglog(RC_LOG_SERIOUS, "%s ID payload %s is invalid (%s) in Quick I1"
2466 , which, idtypename, ip_str(&temp_address));
2467 /* XXX Could send notification back */
2468 return FALSE;
2469 }
2470 happy(addrtosubnet(&temp_address, net));
2471 DBG(DBG_PARSING | DBG_CONTROL
2472 , DBG_log("%s is %s", which, ip_str(&temp_address)));
2473 break;
2474 }
2475
2476 case ID_IPV4_ADDR_SUBNET:
2477 case ID_IPV6_ADDR_SUBNET:
2478 {
2479 ip_address temp_address, temp_mask;
2480 err_t ugh;
2481
2482 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2483 {
2484 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2485 , which, idtypename);
2486 /* XXX Could send notification back */
2487 return FALSE;
2488 }
2489 ugh = initaddr(id_pbs->cur
2490 , afi->ia_sz, afi->af, &temp_address);
2491 if (ugh == NULL)
2492 ugh = initaddr(id_pbs->cur + afi->ia_sz
2493 , afi->ia_sz, afi->af, &temp_mask);
2494 if (ugh == NULL)
2495 ugh = initsubnet(&temp_address, masktocount(&temp_mask)
2496 , '0', net);
2497 if (ugh == NULL && subnetisnone(net))
2498 ugh = "contains only anyaddr";
2499 if (ugh != NULL)
2500 {
2501 loglog(RC_LOG_SERIOUS, "%s ID payload %s bad subnet in Quick I1 (%s)"
2502 , which, idtypename, ugh);
2503 /* XXX Could send notification back */
2504 return FALSE;
2505 }
2506 DBG(DBG_PARSING | DBG_CONTROL,
2507 {
2508 char temp_buff[SUBNETTOT_BUF];
2509
2510 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2511 DBG_log("%s is subnet %s", which, temp_buff);
2512 });
2513 break;
2514 }
2515
2516 case ID_IPV4_ADDR_RANGE:
2517 case ID_IPV6_ADDR_RANGE:
2518 {
2519 ip_address temp_address_from, temp_address_to;
2520 err_t ugh;
2521
2522 if (pbs_left(id_pbs) != 2 * afi->ia_sz)
2523 {
2524 loglog(RC_LOG_SERIOUS, "%s ID payload %s wrong length in Quick I1"
2525 , which, idtypename);
2526 /* XXX Could send notification back */
2527 return FALSE;
2528 }
2529 ugh = initaddr(id_pbs->cur, afi->ia_sz, afi->af, &temp_address_from);
2530 if (ugh == NULL)
2531 ugh = initaddr(id_pbs->cur + afi->ia_sz
2532 , afi->ia_sz, afi->af, &temp_address_to);
2533 if (ugh != NULL)
2534 {
2535 loglog(RC_LOG_SERIOUS, "%s ID payload %s malformed (%s) in Quick I1"
2536 , which, idtypename, ugh);
2537 /* XXX Could send notification back */
2538 return FALSE;
2539 }
2540
2541 ugh = rangetosubnet(&temp_address_from, &temp_address_to, net);
2542 if (ugh == NULL && subnetisnone(net))
2543 ugh = "contains only anyaddr";
2544 if (ugh != NULL)
2545 {
2546 char temp_buff1[ADDRTOT_BUF], temp_buff2[ADDRTOT_BUF];
2547
2548 addrtot(&temp_address_from, 0, temp_buff1, sizeof(temp_buff1));
2549 addrtot(&temp_address_to, 0, temp_buff2, sizeof(temp_buff2));
2550 loglog(RC_LOG_SERIOUS, "%s ID payload in Quick I1, %s"
2551 " %s - %s unacceptable: %s"
2552 , which, idtypename, temp_buff1, temp_buff2, ugh);
2553 return FALSE;
2554 }
2555 DBG(DBG_PARSING | DBG_CONTROL,
2556 {
2557 char temp_buff[SUBNETTOT_BUF];
2558
2559 subnettot(net, 0, temp_buff, sizeof(temp_buff));
2560 DBG_log("%s is subnet %s (received as range)"
2561 , which, temp_buff);
2562 });
2563 break;
2564 }
2565 }
2566
2567 /* set the port selector */
2568 setportof(htons(id->isaiid_port), &net->addr);
2569
2570 DBG(DBG_PARSING | DBG_CONTROL,
2571 DBG_log("%s protocol/port is %d/%d", which, id->isaiid_protoid, id->isaiid_port)
2572 )
2573
2574 return TRUE;
2575 }
2576
2577 /* like decode, but checks that what is received matches what was sent */
2578 static bool check_net_id(struct isakmp_ipsec_id *id, pb_stream *id_pbs,
2579 u_int8_t *protoid, u_int16_t *port, ip_subnet *net,
2580 const char *which)
2581 {
2582 ip_subnet net_temp;
2583
2584 if (!decode_net_id(id, id_pbs, &net_temp, which))
2585 return FALSE;
2586
2587 if (!samesubnet(net, &net_temp)
2588 || *protoid != id->isaiid_protoid || *port != id->isaiid_port)
2589 {
2590 loglog(RC_LOG_SERIOUS, "%s ID returned doesn't match my proposal", which);
2591 return FALSE;
2592 }
2593 return TRUE;
2594 }
2595
2596 /*
2597 * look for the existence of a non-expiring preloaded public key
2598 */
2599 static bool has_preloaded_public_key(struct state *st)
2600 {
2601 struct connection *c = st->st_connection;
2602
2603 /* do not consider rw connections since
2604 * the peer's identity must be known
2605 */
2606 if (c->kind == CK_PERMANENT)
2607 {
2608 pubkey_list_t *p;
2609
2610 /* look for a matching RSA public key */
2611 for (p = pubkeys; p != NULL; p = p->next)
2612 {
2613 pubkey_t *key = p->key;
2614 key_type_t type = key->public_key->get_type(key->public_key);
2615
2616 if (type == KEY_RSA && same_id(&c->spd.that.id, &key->id) &&
2617 key->until_time == UNDEFINED_TIME)
2618 {
2619 /* found a preloaded public key */
2620 return TRUE;
2621 }
2622 }
2623 }
2624 return FALSE;
2625 }
2626
2627 /*
2628 * Produce the new key material of Quick Mode.
2629 * RFC 2409 "IKE" section 5.5
2630 * specifies how this is to be done.
2631 */
2632 static void compute_proto_keymat(struct state *st, u_int8_t protoid,
2633 struct ipsec_proto_info *pi)
2634 {
2635 size_t needed_len = 0; /* bytes of keying material needed */
2636
2637 /* Add up the requirements for keying material
2638 * (It probably doesn't matter if we produce too much!)
2639 */
2640 switch (protoid)
2641 {
2642 case PROTO_IPSEC_ESP:
2643 {
2644 needed_len = kernel_alg_esp_enc_keylen(pi->attrs.transid);
2645
2646 if (needed_len && pi->attrs.key_len)
2647 {
2648 needed_len = pi->attrs.key_len / BITS_PER_BYTE;
2649 }
2650
2651 switch (pi->attrs.transid)
2652 {
2653 case ESP_NULL:
2654 needed_len = 0;
2655 break;
2656 case ESP_AES_CCM_8:
2657 case ESP_AES_CCM_12:
2658 case ESP_AES_CCM_16:
2659 needed_len += 3;
2660 break;
2661 case ESP_AES_GCM_8:
2662 case ESP_AES_GCM_12:
2663 case ESP_AES_GCM_16:
2664 case ESP_AES_CTR:
2665 needed_len += 4;
2666 break;
2667 default:
2668 if (needed_len == 0)
2669 {
2670 bad_case(pi->attrs.transid);
2671 }
2672 }
2673
2674 if (kernel_alg_esp_auth_ok(pi->attrs.auth, NULL))
2675 {
2676 needed_len += kernel_alg_esp_auth_keylen(pi->attrs.auth);
2677 }
2678 else
2679 {
2680 switch (pi->attrs.auth)
2681 {
2682 case AUTH_ALGORITHM_NONE:
2683 break;
2684 case AUTH_ALGORITHM_HMAC_MD5:
2685 needed_len += HMAC_MD5_KEY_LEN;
2686 break;
2687 case AUTH_ALGORITHM_HMAC_SHA1:
2688 needed_len += HMAC_SHA1_KEY_LEN;
2689 break;
2690 case AUTH_ALGORITHM_DES_MAC:
2691 default:
2692 bad_case(pi->attrs.auth);
2693 }
2694 }
2695 break;
2696 }
2697 case PROTO_IPSEC_AH:
2698 {
2699 switch (pi->attrs.transid)
2700 {
2701 case AH_MD5:
2702 needed_len = HMAC_MD5_KEY_LEN;
2703 break;
2704 case AH_SHA:
2705 needed_len = HMAC_SHA1_KEY_LEN;
2706 break;
2707 default:
2708 bad_case(pi->attrs.transid);
2709 }
2710 break;
2711 }
2712 default:
2713 bad_case(protoid);
2714 }
2715
2716 pi->keymat_len = needed_len;
2717
2718 /* Allocate space for the keying material. Although only needed_len bytes
2719 * are desired, we must round up to a multiple of hash_size
2720 * so that our buffer isn't overrun.
2721 */
2722 {
2723 size_t needed_space; /* space needed for keying material (rounded up) */
2724 size_t i, prf_block_size;
2725 chunk_t protoid_chunk = chunk_from_thing(protoid);
2726 chunk_t spi_our = chunk_from_thing(pi->our_spi);
2727 chunk_t spi_peer = chunk_from_thing(pi->attrs.spi);
2728 pseudo_random_function_t prf_alg;
2729 prf_t *prf_our, *prf_peer;
2730
2731 prf_alg = oakley_to_prf(st->st_oakley.hash);
2732 prf_our = lib->crypto->create_prf(lib->crypto, prf_alg);
2733 prf_peer = lib->crypto->create_prf(lib->crypto, prf_alg);
2734 prf_our->set_key(prf_our, st->st_skeyid_d);
2735 prf_peer->set_key(prf_peer, st->st_skeyid_d);
2736 prf_block_size = prf_our->get_block_size(prf_our);
2737
2738 needed_space = needed_len + pad_up(needed_len, prf_block_size);
2739 replace(pi->our_keymat, malloc(needed_space));
2740 replace(pi->peer_keymat, malloc(needed_space));
2741
2742 for (i = 0;; )
2743 {
2744 char *keymat_i_our = pi->our_keymat + i;
2745 char *keymat_i_peer = pi->peer_keymat + i;
2746 chunk_t keymat_our = { keymat_i_our, prf_block_size };
2747 chunk_t keymat_peer = { keymat_i_peer, prf_block_size };
2748
2749 if (st->st_shared.ptr != NULL)
2750 {
2751 /* PFS: include the g^xy */
2752 prf_our->get_bytes(prf_our, st->st_shared, NULL);
2753 prf_peer->get_bytes(prf_peer, st->st_shared, NULL);
2754 }
2755 prf_our->get_bytes(prf_our, protoid_chunk, NULL);
2756 prf_peer->get_bytes(prf_peer, protoid_chunk, NULL);
2757
2758 prf_our->get_bytes(prf_our, spi_our, NULL);
2759 prf_peer->get_bytes(prf_peer, spi_peer, NULL);
2760
2761 prf_our->get_bytes(prf_our, st->st_ni, NULL);
2762 prf_peer->get_bytes(prf_peer, st->st_ni, NULL);
2763
2764 prf_our->get_bytes(prf_our, st->st_nr, keymat_i_our);
2765 prf_peer->get_bytes(prf_peer, st->st_nr, keymat_i_peer);
2766
2767 i += prf_block_size;
2768 if (i >= needed_space)
2769 {
2770 break;
2771 }
2772
2773 /* more keying material needed: prepare to go around again */
2774 prf_our->get_bytes(prf_our, keymat_our, NULL);
2775 prf_peer->get_bytes(prf_peer, keymat_peer, NULL);
2776 }
2777 prf_our->destroy(prf_our);
2778 prf_peer->destroy(prf_peer);
2779 }
2780 DBG(DBG_CRYPT,
2781 DBG_dump("KEYMAT computed:\n", pi->our_keymat, pi->keymat_len);
2782 DBG_dump("Peer KEYMAT computed:\n", pi->peer_keymat, pi->keymat_len));
2783 }
2784
2785 static void compute_keymats(struct state *st)
2786 {
2787 if (st->st_ah.present)
2788 compute_proto_keymat(st, PROTO_IPSEC_AH, &st->st_ah);
2789 if (st->st_esp.present)
2790 compute_proto_keymat(st, PROTO_IPSEC_ESP, &st->st_esp);
2791 }
2792
2793 static bool uses_pubkey_auth(int auth)
2794 {
2795 switch (auth)
2796 {
2797 case OAKLEY_RSA_SIG:
2798 case OAKLEY_ECDSA_SIG:
2799 case OAKLEY_ECDSA_256:
2800 case OAKLEY_ECDSA_384:
2801 case OAKLEY_ECDSA_521:
2802 case XAUTHInitRSA:
2803 case XAUTHRespRSA:
2804 return TRUE;
2805 default:
2806 return FALSE;
2807 }
2808 }
2809
2810 /* State Transition Functions.
2811 *
2812 * The definition of state_microcode_table in demux.c is a good
2813 * overview of these routines.
2814 *
2815 * - Called from process_packet; result handled by complete_state_transition
2816 * - struct state_microcode member "processor" points to these
2817 * - these routine definitionss are in state order
2818 * - these routines must be restartable from any point of error return:
2819 * beware of memory allocated before any error.
2820 * - output HDR is usually emitted by process_packet (if state_microcode
2821 * member first_out_payload isn't ISAKMP_NEXT_NONE).
2822 *
2823 * The transition functions' functions include:
2824 * - process and judge payloads
2825 * - update st_iv (result of decryption is in st_new_iv)
2826 * - build reply packet
2827 */
2828
2829 /* Handle a Main Mode Oakley first packet (responder side).
2830 * HDR;SA --> HDR;SA
2831 */
2832 stf_status main_inI1_outR1(struct msg_digest *md)
2833 {
2834 struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_SA];
2835 struct state *st;
2836 struct connection *c;
2837 struct isakmp_proposal proposal;
2838 pb_stream proposal_pbs;
2839 pb_stream r_sa_pbs;
2840 u_int32_t ipsecdoisit;
2841 lset_t policy = LEMPTY;
2842 int vids_to_send = 0;
2843
2844 /* We preparse the peer's proposal in order to determine
2845 * the requested authentication policy (RSA or PSK)
2846 */
2847 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sa_pd->payload.sa
2848 , &sa_pd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
2849
2850 backup_pbs(&proposal_pbs);
2851 RETURN_STF_FAILURE(parse_isakmp_policy(&proposal_pbs
2852 , proposal.isap_notrans, &policy));
2853 restore_pbs(&proposal_pbs);
2854
2855 /* We are only considering candidate connections that match
2856 * the requested authentication policy (RSA or PSK)
2857 */
2858 c = find_host_connection(&md->iface->addr, pluto_port
2859 , &md->sender, md->sender_port, policy);
2860
2861 if (c == NULL && md->iface->ike_float)
2862 {
2863 c = find_host_connection(&md->iface->addr, NAT_T_IKE_FLOAT_PORT
2864 , &md->sender, md->sender_port, policy);
2865 }
2866
2867 if (c == NULL)
2868 {
2869 /* See if a wildcarded connection can be found.
2870 * We cannot pick the right connection, so we're making a guess.
2871 * All Road Warrior connections are fair game:
2872 * we pick the first we come across (if any).
2873 * If we don't find any, we pick the first opportunistic
2874 * with the smallest subnet that includes the peer.
2875 * There is, of course, no necessary relationship between
2876 * an Initiator's address and that of its client,
2877 * but Food Groups kind of assumes one.
2878 */
2879 {
2880 struct connection *d;
2881
2882 d = find_host_connection(&md->iface->addr
2883 , pluto_port, (ip_address*)NULL, md->sender_port, policy);
2884
2885 for (; d != NULL; d = d->hp_next)
2886 {
2887 if (d->kind == CK_GROUP)
2888 {
2889 /* ignore */
2890 }
2891 else
2892 {
2893 if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO))
2894 {
2895 /* must be Road Warrior: we have a winner */
2896 c = d;
2897 break;
2898 }
2899
2900 /* Opportunistic or Shunt: pick tightest match */
2901 if (addrinsubnet(&md->sender, &d->spd.that.client)
2902 && (c == NULL || !subnetinsubnet(&c->spd.that.client, &d->spd.that.client)))
2903 c = d;
2904 }
2905 }
2906 }
2907
2908 if (c == NULL)
2909 {
2910 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
2911 " but no connection has been authorized%s%s"
2912 , ip_str(&md->iface->addr), ntohs(portof(&md->iface->addr))
2913 , (policy != LEMPTY) ? " with policy=" : ""
2914 , (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : "");
2915 /* XXX notification is in order! */
2916 return STF_IGNORE;
2917 }
2918 else if (c->kind != CK_TEMPLATE)
2919 {
2920 loglog(RC_LOG_SERIOUS, "initial Main Mode message received on %s:%u"
2921 " but \"%s\" forbids connection"
2922 , ip_str(&md->iface->addr), pluto_port, c->name);
2923 /* XXX notification is in order! */
2924 return STF_IGNORE;
2925 }
2926 else
2927 {
2928 /* Create a temporary connection that is a copy of this one.
2929 * His ID isn't declared yet.
2930 */
2931 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, NULL);
2932 }
2933 }
2934 else if (c->kind == CK_TEMPLATE)
2935 {
2936 /* Create an instance
2937 * This is a rare case: wildcard peer ID but static peer IP address
2938 */
2939 c = rw_instantiate(c, &md->sender, md->sender_port, NULL, &c->spd.that.id);
2940 }
2941
2942 /* Set up state */
2943 md->st = st = new_state();
2944 st->st_connection = c;
2945 set_cur_state(st); /* (caller will reset cur_state) */
2946 st->st_try = 0; /* not our job to try again from start */
2947 st->st_policy = c->policy & ~POLICY_IPSEC_MASK; /* only as accurate as connection */
2948
2949 memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE);
2950 get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender);
2951
2952 insert_state(st); /* needs cookies, connection, and msgid (0) */
2953
2954 st->st_doi = ISAKMP_DOI_IPSEC;
2955 st->st_situation = SIT_IDENTITY_ONLY; /* We only support this */
2956
2957 if ((c->kind == CK_INSTANCE) && (c->spd.that.host_port != pluto_port))
2958 {
2959 plog("responding to Main Mode from unknown peer %s:%u"
2960 , ip_str(&c->spd.that.host_addr), c->spd.that.host_port);
2961 }
2962 else if (c->kind == CK_INSTANCE)
2963 {
2964 plog("responding to Main Mode from unknown peer %s"
2965 , ip_str(&c->spd.that.host_addr));
2966 }
2967 else
2968 {
2969 plog("responding to Main Mode");
2970 }
2971
2972 /* parse_isakmp_sa also spits out a winning SA into our reply,
2973 * so we have to build our md->reply and emit HDR before calling it.
2974 */
2975
2976 /* determine how many Vendor ID payloads we will be sending */
2977 if (SEND_PLUTO_VID)
2978 {
2979 vids_to_send++;
2980 }
2981 if (SEND_CISCO_UNITY_VID)
2982 {
2983 vids_to_send++;
2984 }
2985 if (md->openpgp)
2986 {
2987 vids_to_send++;
2988 }
2989 if (SEND_XAUTH_VID)
2990 {
2991 vids_to_send++;
2992 }
2993 /* always send DPD Vendor ID */
2994 vids_to_send++;
2995 if (md->nat_traversal_vid && nat_traversal_enabled)
2996 {
2997 vids_to_send++;
2998 }
2999
3000 /* HDR out.
3001 * We can't leave this to comm_handle() because we must
3002 * fill in the cookie.
3003 */
3004 {
3005 struct isakmp_hdr r_hdr = md->hdr;
3006
3007 r_hdr.isa_flags &= ~ISAKMP_FLAG_COMMIT; /* we won't ever turn on this bit */
3008 memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE);
3009 r_hdr.isa_np = ISAKMP_NEXT_SA;
3010 if (!out_struct(&r_hdr, &isakmp_hdr_desc, &md->reply, &md->rbody))
3011 return STF_INTERNAL_ERROR;
3012 }
3013
3014 /* start of SA out */
3015 {
3016 struct isakmp_sa r_sa = sa_pd->payload.sa;
3017
3018 r_sa.isasa_np = vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE;
3019
3020 if (!out_struct(&r_sa, &isakmp_sa_desc, &md->rbody, &r_sa_pbs))
3021 return STF_INTERNAL_ERROR;
3022 }
3023
3024 /* SA body in and out */
3025 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit, &proposal_pbs
3026 ,&proposal, &r_sa_pbs, st, FALSE));
3027
3028 /* if enabled send Pluto Vendor ID */
3029 if (SEND_PLUTO_VID)
3030 {
3031 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3032 , &md->rbody, VID_STRONGSWAN))
3033 {
3034 return STF_INTERNAL_ERROR;
3035 }
3036 }
3037
3038 /* if enabled send Cisco Unity Vendor ID */
3039 if (SEND_CISCO_UNITY_VID)
3040 {
3041 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3042 , &md->rbody, VID_CISCO_UNITY))
3043 {
3044 return STF_INTERNAL_ERROR;
3045 }
3046 }
3047
3048 /*
3049 * if the peer sent an OpenPGP Vendor ID we offer the same capability
3050 */
3051 if (md->openpgp)
3052 {
3053 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3054 , &md->rbody, VID_OPENPGP))
3055 {
3056 return STF_INTERNAL_ERROR;
3057 }
3058 }
3059
3060 /* Announce our ability to do eXtended AUTHentication to the peer */
3061 if (SEND_XAUTH_VID)
3062 {
3063 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3064 , &md->rbody, VID_MISC_XAUTH))
3065 {
3066 return STF_INTERNAL_ERROR;
3067 }
3068 }
3069
3070 /* Announce our ability to do Dead Peer Detection to the peer */
3071 if (!out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3072 , &md->rbody, VID_MISC_DPD))
3073 {
3074 return STF_INTERNAL_ERROR;
3075 }
3076
3077 if (md->nat_traversal_vid && nat_traversal_enabled)
3078 {
3079 /* reply if NAT-Traversal draft is supported */
3080 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3081
3082 if (st->nat_traversal
3083 && !out_vendorid(vids_to_send-- ? ISAKMP_NEXT_VID : ISAKMP_NEXT_NONE
3084 , &md->rbody, md->nat_traversal_vid))
3085 {
3086 return STF_INTERNAL_ERROR;
3087 }
3088 }
3089
3090 close_message(&md->rbody);
3091
3092 /* save initiator SA for HASH */
3093 free(st->st_p1isa.ptr);
3094 st->st_p1isa = chunk_create(sa_pd->pbs.start, pbs_room(&sa_pd->pbs));
3095 st->st_p1isa = chunk_clone(st->st_p1isa);
3096
3097 return STF_OK;
3098 }
3099
3100 /* STATE_MAIN_I1: HDR, SA --> auth dependent
3101 * PSK_AUTH, DS_AUTH: --> HDR, KE, Ni
3102 *
3103 * The following are not yet implemented:
3104 * PKE_AUTH: --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
3105 * RPKE_AUTH: --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i,
3106 * <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
3107 *
3108 * We must verify that the proposal received matches one we sent.
3109 */
3110 stf_status main_inR1_outI2(struct msg_digest *md)
3111 {
3112 struct state *const st = md->st;
3113
3114 u_int8_t np = ISAKMP_NEXT_NONE;
3115
3116 /* verify echoed SA */
3117 {
3118 u_int32_t ipsecdoisit;
3119 pb_stream proposal_pbs;
3120 struct isakmp_proposal proposal;
3121 struct payload_digest *const sapd = md->chain[ISAKMP_NEXT_SA];
3122
3123 RETURN_STF_FAILURE(preparse_isakmp_sa_body(&sapd->payload.sa
3124 ,&sapd->pbs, &ipsecdoisit, &proposal_pbs, &proposal));
3125 if (proposal.isap_notrans != 1)
3126 {
3127 loglog(RC_LOG_SERIOUS, "a single Transform is required in a selecting Oakley Proposal; found %u"
3128 , (unsigned)proposal.isap_notrans);
3129 RETURN_STF_FAILURE(BAD_PROPOSAL_SYNTAX);
3130 }
3131 RETURN_STF_FAILURE(parse_isakmp_sa_body(ipsecdoisit
3132 , &proposal_pbs, &proposal, NULL, st, TRUE));
3133 }
3134
3135 if (nat_traversal_enabled && md->nat_traversal_vid)
3136 {
3137 st->nat_traversal = nat_traversal_vid_to_method(md->nat_traversal_vid);
3138 plog("enabling possible NAT-traversal with method %s"
3139 , bitnamesof(natt_type_bitnames, st->nat_traversal));
3140 }
3141 if (st->nat_traversal & NAT_T_WITH_NATD)
3142 {
3143 np = (st->nat_traversal & NAT_T_WITH_RFC_VALUES) ?
3144 ISAKMP_NEXT_NATD_RFC : ISAKMP_NEXT_NATD_DRAFTS;
3145 }
3146
3147 /**************** build output packet HDR;KE;Ni ****************/
3148
3149 /* HDR out.
3150 * We can't leave this to comm_handle() because the isa_np
3151 * depends on the type of Auth (eventually).
3152 */
3153 echo_hdr(md, FALSE, ISAKMP_NEXT_KE);
3154
3155 /* KE out */
3156 if (!build_and_ship_KE(st, &st->st_gi, st->st_oakley.group
3157 , &md->rbody, ISAKMP_NEXT_NONCE))
3158 return STF_INTERNAL_ERROR;
3159
3160 #ifdef DEBUG
3161 /* Ni out */
3162 if (!build_and_ship_nonce(&st->st_ni, &md->rbody
3163 , (cur_debugging & IMPAIR_BUST_MI2)? ISAKMP_NEXT_VID : np, "Ni"))
3164 return STF_INTERNAL_ERROR;
3165
3166 if (cur_debugging & IMPAIR_BUST_MI2)
3167 {
3168 /* generate a pointless large VID payload to push message over MTU */
3169 pb_stream vid_pbs;
3170
3171 if (!out_generic(np, &isakmp_vendor_id_desc, &md->rbody, &vid_pbs))
3172 return STF_INTERNAL_ERROR;
3173 if (!out_zero(1500 /*MTU?*/, &vid_pbs, "Filler VID"))
3174 return STF_INTERNAL_ERROR;
3175 close_output_pbs(&vid_pbs);
3176 }
3177 #else
3178 /* Ni out */
3179 if (!build_and_ship_nonce(&st->st_ni, &md->rbody, np, "Ni"))
3180 return STF_INTERNAL_ERROR;
3181 #endif
3182
3183 if (st->nat_traversal & NAT_T_WITH_NATD)
3184 {
3185 if (!nat_traversal_add_natd(ISAKMP_NEXT_NONE, &md->rbody, md))
3186 return STF_INTERNAL_ERROR;
3187 }
3188
3189 /* finish message */
3190 close_message(&md->rbody);