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