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