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