Added a keymat_t version to cast it safely
[strongswan.git] / src / libcharon / sa / ikev1 / keymat_v1.c
1 /*
2 * Copyright (C) 2011 Tobias Brunner
3 * Hochschule fuer Technik Rapperswil
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 "keymat_v1.h"
17
18 #include <daemon.h>
19 #include <encoding/generator.h>
20 #include <encoding/payloads/nonce_payload.h>
21 #include <utils/linked_list.h>
22
23 typedef struct private_keymat_v1_t private_keymat_v1_t;
24
25 /**
26 * Max. number of IVs to track.
27 */
28 #define MAX_IV 3
29
30 /**
31 * Max. number of Quick Modes to track.
32 */
33 #define MAX_QM 2
34
35 /**
36 * Data stored for IVs
37 */
38 typedef struct {
39 /** message ID */
40 u_int32_t mid;
41 /** current IV */
42 chunk_t iv;
43 /** last block of encrypted message */
44 chunk_t last_block;
45 } iv_data_t;
46
47 /**
48 * Private data of an keymat_t object.
49 */
50 struct private_keymat_v1_t {
51
52 /**
53 * Public keymat_v1_t interface.
54 */
55 keymat_v1_t public;
56
57 /**
58 * IKE_SA Role, initiator or responder
59 */
60 bool initiator;
61
62 /**
63 * General purpose PRF
64 */
65 prf_t *prf;
66
67 /**
68 * Negotiated PRF algorithm
69 */
70 pseudo_random_function_t prf_alg;
71
72 /**
73 * Crypter wrapped in an aead_t interface
74 */
75 aead_t *aead;
76
77 /**
78 * Hasher used for IV generation (and other things like e.g. NAT-T)
79 */
80 hasher_t *hasher;
81
82 /**
83 * Key used for authentication during main mode
84 */
85 chunk_t skeyid;
86
87 /**
88 * Key to derive key material from for non-ISAKMP SAs, rekeying
89 */
90 chunk_t skeyid_d;
91
92 /**
93 * Key used for authentication after main mode
94 */
95 chunk_t skeyid_a;
96
97 /**
98 * Phase 1 IV
99 */
100 iv_data_t phase1_iv;
101
102 /**
103 * Keep track of IVs for exchanges after phase 1. We store only a limited
104 * number of IVs in an MRU sort of way. Stores iv_data_t objects.
105 */
106 linked_list_t *ivs;
107
108 /**
109 * Keep track of Nonces during Quick Mode exchanges. Only a limited number
110 * of QMs are tracked at the same time. Stores qm_data_t objects.
111 */
112 linked_list_t *qms;
113 };
114
115
116 /**
117 * Destroy an iv_data_t object.
118 */
119 static void iv_data_destroy(iv_data_t *this)
120 {
121 chunk_free(&this->last_block);
122 chunk_free(&this->iv);
123 free(this);
124 }
125
126 /**
127 * Data stored for Quick Mode exchanges
128 */
129 typedef struct {
130 /** message ID */
131 u_int32_t mid;
132 /** Ni_b (Nonce from first message) */
133 chunk_t n_i;
134 /** Nr_b (Nonce from second message) */
135 chunk_t n_r;
136 } qm_data_t;
137
138 /**
139 * Destroy a qm_data_t object.
140 */
141 static void qm_data_destroy(qm_data_t *this)
142 {
143 chunk_free(&this->n_i);
144 chunk_free(&this->n_r);
145 free(this);
146 }
147
148 /**
149 * Constants used in key derivation.
150 */
151 static const chunk_t octet_0 = chunk_from_chars(0x00);
152 static const chunk_t octet_1 = chunk_from_chars(0x01);
153 static const chunk_t octet_2 = chunk_from_chars(0x02);
154
155 /**
156 * Simple aead_t implementation without support for authentication.
157 */
158 typedef struct {
159 /** implements aead_t interface */
160 aead_t aead;
161 /** crypter to be used */
162 crypter_t *crypter;
163 } private_aead_t;
164
165
166 METHOD(aead_t, encrypt, void,
167 private_aead_t *this, chunk_t plain, chunk_t assoc, chunk_t iv,
168 chunk_t *encrypted)
169 {
170 this->crypter->encrypt(this->crypter, plain, iv, encrypted);
171 }
172
173 METHOD(aead_t, decrypt, bool,
174 private_aead_t *this, chunk_t encrypted, chunk_t assoc, chunk_t iv,
175 chunk_t *plain)
176 {
177 this->crypter->decrypt(this->crypter, encrypted, iv, plain);
178 return TRUE;
179 }
180
181 METHOD(aead_t, get_block_size, size_t,
182 private_aead_t *this)
183 {
184 return this->crypter->get_block_size(this->crypter);
185 }
186
187 METHOD(aead_t, get_icv_size, size_t,
188 private_aead_t *this)
189 {
190 return 0;
191 }
192
193 METHOD(aead_t, get_iv_size, size_t,
194 private_aead_t *this)
195 {
196 /* in order to create the messages properly we return 0 here */
197 return 0;
198 }
199
200 METHOD(aead_t, get_key_size, size_t,
201 private_aead_t *this)
202 {
203 return this->crypter->get_key_size(this->crypter);
204 }
205
206 METHOD(aead_t, set_key, void,
207 private_aead_t *this, chunk_t key)
208 {
209 this->crypter->set_key(this->crypter, key);
210 }
211
212 METHOD(aead_t, aead_destroy, void,
213 private_aead_t *this)
214 {
215 this->crypter->destroy(this->crypter);
216 free(this);
217 }
218
219 /**
220 * Expand SKEYID_e according to Appendix B in RFC 2409.
221 * TODO-IKEv1: verify keys (e.g. for weak keys, see Appendix B)
222 */
223 static chunk_t expand_skeyid_e(chunk_t skeyid_e, size_t key_size, prf_t *prf)
224 {
225 size_t block_size;
226 chunk_t seed, ka;
227 int i;
228
229 if (skeyid_e.len >= key_size)
230 { /* no expansion required, reduce to key_size */
231 skeyid_e.len = key_size;
232 return skeyid_e;
233 }
234 block_size = prf->get_block_size(prf);
235 ka = chunk_alloc((key_size / block_size + 1) * block_size);
236 ka.len = key_size;
237
238 /* Ka = K1 | K2 | ..., K1 = prf(SKEYID_e, 0), K2 = prf(SKEYID_e, K1) ... */
239 prf->set_key(prf, skeyid_e);
240 seed = octet_0;
241 for (i = 0; i < key_size; i += block_size)
242 {
243 prf->get_bytes(prf, seed, ka.ptr + i);
244 seed = chunk_create(ka.ptr + i, block_size);
245 }
246 chunk_clear(&skeyid_e);
247 return ka;
248 }
249
250 /**
251 * Create a simple implementation of the aead_t interface which only encrypts
252 * or decrypts data.
253 */
254 static aead_t *create_aead(proposal_t *proposal, prf_t *prf, chunk_t skeyid_e)
255 {
256 private_aead_t *this;
257 u_int16_t alg, key_size;
258 crypter_t *crypter;
259 chunk_t ka;
260
261 if (!proposal->get_algorithm(proposal, ENCRYPTION_ALGORITHM, &alg,
262 &key_size))
263 {
264 DBG1(DBG_IKE, "no %N selected",
265 transform_type_names, ENCRYPTION_ALGORITHM);
266 return NULL;
267 }
268 crypter = lib->crypto->create_crypter(lib->crypto, alg, key_size / 8);
269 if (!crypter)
270 {
271 DBG1(DBG_IKE, "%N %N (key size %d) not supported!",
272 transform_type_names, ENCRYPTION_ALGORITHM,
273 encryption_algorithm_names, alg, key_size);
274 return NULL;
275 }
276 key_size = crypter->get_key_size(crypter);
277 ka = expand_skeyid_e(skeyid_e, crypter->get_key_size(crypter), prf);
278 DBG4(DBG_IKE, "encryption key Ka %B", &ka);
279 crypter->set_key(crypter, ka);
280 chunk_clear(&ka);
281
282 INIT(this,
283 .aead = {
284 .encrypt = _encrypt,
285 .decrypt = _decrypt,
286 .get_block_size = _get_block_size,
287 .get_icv_size = _get_icv_size,
288 .get_iv_size = _get_iv_size,
289 .get_key_size = _get_key_size,
290 .set_key = _set_key,
291 .destroy = _aead_destroy,
292 },
293 .crypter = crypter,
294 );
295 return &this->aead;
296 }
297
298 /**
299 * Converts integrity algorithm to PRF algorithm
300 */
301 static u_int16_t auth_to_prf(u_int16_t alg)
302 {
303 switch (alg)
304 {
305 case AUTH_HMAC_SHA1_96:
306 return PRF_HMAC_SHA1;
307 case AUTH_HMAC_SHA2_256_128:
308 return PRF_HMAC_SHA2_256;
309 case AUTH_HMAC_SHA2_384_192:
310 return PRF_HMAC_SHA2_384;
311 case AUTH_HMAC_SHA2_512_256:
312 return PRF_HMAC_SHA2_512;
313 case AUTH_HMAC_MD5_96:
314 return PRF_HMAC_MD5;
315 case AUTH_AES_XCBC_96:
316 return PRF_AES128_XCBC;
317 default:
318 return PRF_UNDEFINED;
319 }
320 }
321
322 /**
323 * Converts integrity algorithm to hash algorithm
324 */
325 static u_int16_t auth_to_hash(u_int16_t alg)
326 {
327 switch (alg)
328 {
329 case AUTH_HMAC_SHA1_96:
330 return HASH_SHA1;
331 case AUTH_HMAC_SHA2_256_128:
332 return HASH_SHA256;
333 case AUTH_HMAC_SHA2_384_192:
334 return HASH_SHA384;
335 case AUTH_HMAC_SHA2_512_256:
336 return HASH_SHA512;
337 case AUTH_HMAC_MD5_96:
338 return HASH_MD5;
339 default:
340 return HASH_UNKNOWN;
341 }
342 }
343
344 /**
345 * Adjust the key length for PRF algorithms that expect a fixed key length.
346 */
347 static void adjust_keylen(u_int16_t alg, chunk_t *key)
348 {
349 switch (alg)
350 {
351 case PRF_AES128_XCBC:
352 /* while rfc4434 defines variable keys for AES-XCBC, rfc3664 does
353 * not and therefore fixed key semantics apply to XCBC for key
354 * derivation. */
355 key->len = min(key->len, 16);
356 break;
357 default:
358 /* all other algorithms use variable key length */
359 break;
360 }
361 }
362
363 METHOD(keymat_v1_t, derive_ike_keys, bool,
364 private_keymat_v1_t *this, proposal_t *proposal, diffie_hellman_t *dh,
365 chunk_t dh_other, chunk_t nonce_i, chunk_t nonce_r, ike_sa_id_t *id,
366 auth_method_t auth, shared_key_t *shared_key)
367 {
368 chunk_t g_xy, g_xi, g_xr, dh_me, spi_i, spi_r, nonces, data, skeyid_e;
369 u_int16_t alg;
370
371 spi_i = chunk_alloca(sizeof(u_int64_t));
372 spi_r = chunk_alloca(sizeof(u_int64_t));
373
374 if (!proposal->get_algorithm(proposal, PSEUDO_RANDOM_FUNCTION, &alg, NULL))
375 { /* no PRF negotiated, use HMAC version of integrity algorithm instead */
376 if (!proposal->get_algorithm(proposal, INTEGRITY_ALGORITHM, &alg, NULL)
377 || (alg = auth_to_prf(alg)) == PRF_UNDEFINED)
378 {
379 DBG1(DBG_IKE, "no %N selected",
380 transform_type_names, PSEUDO_RANDOM_FUNCTION);
381 return FALSE;
382 }
383 }
384 this->prf_alg = alg;
385 this->prf = lib->crypto->create_prf(lib->crypto, alg);
386 if (!this->prf)
387 {
388 DBG1(DBG_IKE, "%N %N not supported!",
389 transform_type_names, PSEUDO_RANDOM_FUNCTION,
390 pseudo_random_function_names, alg);
391 return FALSE;
392 }
393 if (this->prf->get_block_size(this->prf) <
394 this->prf->get_key_size(this->prf))
395 { /* TODO-IKEv1: support PRF output expansion (RFC 2409, Appendix B) */
396 DBG1(DBG_IKE, "expansion of %N %N output not supported!",
397 transform_type_names, PSEUDO_RANDOM_FUNCTION,
398 pseudo_random_function_names, alg);
399 return FALSE;
400 }
401
402 if (dh->get_shared_secret(dh, &g_xy) != SUCCESS)
403 {
404 return FALSE;
405 }
406 DBG4(DBG_IKE, "shared Diffie Hellman secret %B", &g_xy);
407
408 *((u_int64_t*)spi_i.ptr) = id->get_initiator_spi(id);
409 *((u_int64_t*)spi_r.ptr) = id->get_responder_spi(id);
410 nonces = chunk_cata("cc", nonce_i, nonce_r);
411
412 switch (auth)
413 {
414 case AUTH_PSK:
415 case AUTH_XAUTH_INIT_PSK:
416 { /* SKEYID = prf(pre-shared-key, Ni_b | Nr_b) */
417 chunk_t psk;
418 if (!shared_key)
419 {
420 chunk_clear(&g_xy);
421 return FALSE;
422 }
423 psk = shared_key->get_key(shared_key);
424 adjust_keylen(alg, &psk);
425 this->prf->set_key(this->prf, psk);
426 this->prf->allocate_bytes(this->prf, nonces, &this->skeyid);
427 break;
428 }
429 case AUTH_RSA:
430 case AUTH_XAUTH_INIT_RSA:
431 case AUTH_XAUTH_RESP_RSA:
432 case AUTH_HYBRID_INIT_RSA:
433 case AUTH_HYBRID_RESP_RSA:
434 {
435 this->prf->set_key(this->prf, nonces);
436 this->prf->allocate_bytes(this->prf, g_xy, &this->skeyid);
437 break;
438 }
439 default:
440 /* TODO-IKEv1: implement key derivation for other schemes */
441 /* authentication class not supported */
442 chunk_clear(&g_xy);
443 return FALSE;
444 }
445 adjust_keylen(alg, &this->skeyid);
446 DBG4(DBG_IKE, "SKEYID %B", &this->skeyid);
447
448 /* SKEYID_d = prf(SKEYID, g^xy | CKY-I | CKY-R | 0) */
449 data = chunk_cat("cccc", g_xy, spi_i, spi_r, octet_0);
450 this->prf->set_key(this->prf, this->skeyid);
451 this->prf->allocate_bytes(this->prf, data, &this->skeyid_d);
452 chunk_clear(&data);
453 DBG4(DBG_IKE, "SKEYID_d %B", &this->skeyid_d);
454
455 /* SKEYID_a = prf(SKEYID, SKEYID_d | g^xy | CKY-I | CKY-R | 1) */
456 data = chunk_cat("ccccc", this->skeyid_d, g_xy, spi_i, spi_r, octet_1);
457 this->prf->set_key(this->prf, this->skeyid);
458 this->prf->allocate_bytes(this->prf, data, &this->skeyid_a);
459 chunk_clear(&data);
460 DBG4(DBG_IKE, "SKEYID_a %B", &this->skeyid_a);
461
462 /* SKEYID_e = prf(SKEYID, SKEYID_a | g^xy | CKY-I | CKY-R | 2) */
463 data = chunk_cat("ccccc", this->skeyid_a, g_xy, spi_i, spi_r, octet_2);
464 this->prf->set_key(this->prf, this->skeyid);
465 this->prf->allocate_bytes(this->prf, data, &skeyid_e);
466 chunk_clear(&data);
467 DBG4(DBG_IKE, "SKEYID_e %B", &skeyid_e);
468
469 chunk_clear(&g_xy);
470
471 this->aead = create_aead(proposal, this->prf, skeyid_e);
472 if (!this->aead)
473 {
474 return FALSE;
475 }
476 if (!this->hasher && !this->public.create_hasher(&this->public, proposal))
477 {
478 return FALSE;
479 }
480
481 dh->get_my_public_value(dh, &dh_me);
482 g_xi = this->initiator ? dh_me : dh_other;
483 g_xr = this->initiator ? dh_other : dh_me;
484
485 /* initial IV = hash(g^xi | g^xr) */
486 data = chunk_cata("cc", g_xi, g_xr);
487 this->hasher->allocate_hash(this->hasher, data, &this->phase1_iv.iv);
488 if (this->phase1_iv.iv.len > this->aead->get_block_size(this->aead))
489 {
490 this->phase1_iv.iv.len = this->aead->get_block_size(this->aead);
491 }
492 chunk_free(&dh_me);
493 DBG4(DBG_IKE, "initial IV %B", &this->phase1_iv.iv);
494
495 return TRUE;
496 }
497
498 METHOD(keymat_v1_t, derive_child_keys, bool,
499 private_keymat_v1_t *this, proposal_t *proposal, diffie_hellman_t *dh,
500 u_int32_t spi_i, u_int32_t spi_r, chunk_t nonce_i, chunk_t nonce_r,
501 chunk_t *encr_i, chunk_t *integ_i, chunk_t *encr_r, chunk_t *integ_r)
502 {
503 u_int16_t enc_alg, int_alg, enc_size = 0, int_size = 0;
504 u_int8_t protocol;
505 prf_plus_t *prf_plus;
506 chunk_t seed, secret = chunk_empty;
507
508 if (proposal->get_algorithm(proposal, ENCRYPTION_ALGORITHM,
509 &enc_alg, &enc_size))
510 {
511 DBG2(DBG_CHD, " using %N for encryption",
512 encryption_algorithm_names, enc_alg);
513
514 if (!enc_size)
515 {
516 enc_size = keymat_get_keylen_encr(enc_alg);
517 }
518 if (enc_alg != ENCR_NULL && !enc_size)
519 {
520 DBG1(DBG_CHD, "no keylength defined for %N",
521 encryption_algorithm_names, enc_alg);
522 return FALSE;
523 }
524 /* to bytes */
525 enc_size /= 8;
526
527 /* CCM/GCM/CTR/GMAC needs additional bytes */
528 switch (enc_alg)
529 {
530 case ENCR_AES_CCM_ICV8:
531 case ENCR_AES_CCM_ICV12:
532 case ENCR_AES_CCM_ICV16:
533 case ENCR_CAMELLIA_CCM_ICV8:
534 case ENCR_CAMELLIA_CCM_ICV12:
535 case ENCR_CAMELLIA_CCM_ICV16:
536 enc_size += 3;
537 break;
538 case ENCR_AES_GCM_ICV8:
539 case ENCR_AES_GCM_ICV12:
540 case ENCR_AES_GCM_ICV16:
541 case ENCR_AES_CTR:
542 case ENCR_NULL_AUTH_AES_GMAC:
543 enc_size += 4;
544 break;
545 default:
546 break;
547 }
548 }
549
550 if (proposal->get_algorithm(proposal, INTEGRITY_ALGORITHM,
551 &int_alg, &int_size))
552 {
553 DBG2(DBG_CHD, " using %N for integrity",
554 integrity_algorithm_names, int_alg);
555
556 if (!int_size)
557 {
558 int_size = keymat_get_keylen_integ(int_alg);
559 }
560 if (!int_size)
561 {
562 DBG1(DBG_CHD, "no keylength defined for %N",
563 integrity_algorithm_names, int_alg);
564 return FALSE;
565 }
566 /* to bytes */
567 int_size /= 8;
568 }
569
570 /* KEYMAT = prf+(SKEYID_d, [ g(qm)^xy | ] protocol | SPI | Ni_b | Nr_b) */
571 this->prf->set_key(this->prf, this->skeyid_d);
572 protocol = proposal->get_protocol(proposal);
573 if (dh)
574 {
575 if (dh->get_shared_secret(dh, &secret) != SUCCESS)
576 {
577 return FALSE;
578 }
579 DBG4(DBG_CHD, "DH secret %B", &secret);
580 }
581
582 seed = chunk_cata("ccccc", secret, chunk_from_thing(protocol),
583 chunk_from_thing(spi_r), nonce_i, nonce_r);
584 DBG4(DBG_CHD, "initiator SA seed %B", &seed);
585
586 prf_plus = prf_plus_create(this->prf, FALSE, seed);
587 prf_plus->allocate_bytes(prf_plus, enc_size, encr_i);
588 prf_plus->allocate_bytes(prf_plus, int_size, integ_i);
589 prf_plus->destroy(prf_plus);
590
591 seed = chunk_cata("ccccc", secret, chunk_from_thing(protocol),
592 chunk_from_thing(spi_i), nonce_i, nonce_r);
593 DBG4(DBG_CHD, "responder SA seed %B", &seed);
594 prf_plus = prf_plus_create(this->prf, FALSE, seed);
595 prf_plus->allocate_bytes(prf_plus, enc_size, encr_r);
596 prf_plus->allocate_bytes(prf_plus, int_size, integ_r);
597 prf_plus->destroy(prf_plus);
598
599 chunk_clear(&secret);
600
601 if (enc_size)
602 {
603 DBG4(DBG_CHD, "encryption initiator key %B", encr_i);
604 DBG4(DBG_CHD, "encryption responder key %B", encr_r);
605 }
606 if (int_size)
607 {
608 DBG4(DBG_CHD, "integrity initiator key %B", integ_i);
609 DBG4(DBG_CHD, "integrity responder key %B", integ_r);
610 }
611 return TRUE;
612 }
613
614 METHOD(keymat_v1_t, create_hasher, bool,
615 private_keymat_v1_t *this, proposal_t *proposal)
616 {
617 u_int16_t alg;
618 if (!proposal->get_algorithm(proposal, INTEGRITY_ALGORITHM, &alg, NULL) ||
619 (alg = auth_to_hash(alg)) == HASH_UNKNOWN)
620 {
621 DBG1(DBG_IKE, "no %N selected", transform_type_names, HASH_ALGORITHM);
622 return FALSE;
623 }
624 this->hasher = lib->crypto->create_hasher(lib->crypto, alg);
625 if (!this->hasher)
626 {
627 DBG1(DBG_IKE, "%N %N not supported!",
628 transform_type_names, HASH_ALGORITHM,
629 hash_algorithm_names, alg);
630 return FALSE;
631 }
632 return TRUE;
633 }
634
635 METHOD(keymat_v1_t, get_hasher, hasher_t*,
636 private_keymat_v1_t *this)
637 {
638 return this->hasher;
639 }
640
641 METHOD(keymat_v1_t, get_hash, chunk_t,
642 private_keymat_v1_t *this, bool initiator, chunk_t dh, chunk_t dh_other,
643 ike_sa_id_t *ike_sa_id, chunk_t sa_i, chunk_t id)
644 {
645 chunk_t hash, data;
646 u_int64_t spi, spi_other;
647
648 /* HASH_I = prf(SKEYID, g^xi | g^xr | CKY-I | CKY-R | SAi_b | IDii_b )
649 * HASH_R = prf(SKEYID, g^xr | g^xi | CKY-R | CKY-I | SAi_b | IDir_b )
650 */
651 if (initiator)
652 {
653 spi = ike_sa_id->get_initiator_spi(ike_sa_id);
654 spi_other = ike_sa_id->get_responder_spi(ike_sa_id);
655 }
656 else
657 {
658 spi_other = ike_sa_id->get_initiator_spi(ike_sa_id);
659 spi = ike_sa_id->get_responder_spi(ike_sa_id);
660 }
661 data = chunk_cat("cccccc", dh, dh_other,
662 chunk_from_thing(spi), chunk_from_thing(spi_other),
663 sa_i, id);
664
665 DBG3(DBG_IKE, "HASH_%c data %B", initiator ? 'I' : 'R', &data);
666
667 this->prf->set_key(this->prf, this->skeyid);
668 this->prf->allocate_bytes(this->prf, data, &hash);
669
670 DBG3(DBG_IKE, "HASH_%c %B", initiator ? 'I' : 'R', &hash);
671
672 free(data.ptr);
673 return hash;
674 }
675
676 /**
677 * Get the nonce value found in the given message.
678 * Returns FALSE if none is found.
679 */
680 static bool get_nonce(message_t *message, chunk_t *n)
681 {
682 nonce_payload_t *nonce;
683 nonce = (nonce_payload_t*)message->get_payload(message, NONCE_V1);
684 if (nonce)
685 {
686 *n = nonce->get_nonce(nonce);
687 return TRUE;
688 }
689 return FALSE;
690 }
691
692 /**
693 * Generate the message data in order to generate the hashes.
694 */
695 static chunk_t get_message_data(message_t *message, generator_t *generator)
696 {
697 payload_t *payload, *next;
698 enumerator_t *enumerator;
699 u_int32_t *lenpos;
700
701 if (message->is_encoded(message))
702 { /* inbound, although the message is generated, we cannot access the
703 * cleartext message data, so generate it anyway */
704 enumerator = message->create_payload_enumerator(message);
705 while (enumerator->enumerate(enumerator, &payload))
706 {
707 if (payload->get_type(payload) == HASH_V1)
708 {
709 continue;
710 }
711 generator->generate_payload(generator, payload);
712 }
713 enumerator->destroy(enumerator);
714 }
715 else
716 {
717 /* outbound, generate the payloads (there is no HASH payload yet) */
718 enumerator = message->create_payload_enumerator(message);
719 if (enumerator->enumerate(enumerator, &payload))
720 {
721 while (enumerator->enumerate(enumerator, &next))
722 {
723 payload->set_next_type(payload, next->get_type(next));
724 generator->generate_payload(generator, payload);
725 payload = next;
726 }
727 payload->set_next_type(payload, NO_PAYLOAD);
728 generator->generate_payload(generator, payload);
729 }
730 enumerator->destroy(enumerator);
731 }
732 return generator->get_chunk(generator, &lenpos);
733 }
734
735 /**
736 * Try to find data about a Quick Mode with the given message ID,
737 * if none is found, state is generated.
738 */
739 static qm_data_t *lookup_quick_mode(private_keymat_v1_t *this, u_int32_t mid)
740 {
741 enumerator_t *enumerator;
742 qm_data_t *qm, *found = NULL;
743
744 enumerator = this->qms->create_enumerator(this->qms);
745 while (enumerator->enumerate(enumerator, &qm))
746 {
747 if (qm->mid == mid)
748 { /* state gets moved to the front of the list */
749 this->qms->remove_at(this->qms, enumerator);
750 found = qm;
751 break;
752 }
753 }
754 enumerator->destroy(enumerator);
755 if (!found)
756 {
757 INIT(found,
758 .mid = mid,
759 );
760 }
761 this->qms->insert_first(this->qms, found);
762 /* remove least recently used state if maximum reached */
763 if (this->qms->get_count(this->qms) > MAX_QM &&
764 this->qms->remove_last(this->qms, (void**)&qm) == SUCCESS)
765 {
766 qm_data_destroy(qm);
767 }
768 return found;
769 }
770
771 METHOD(keymat_v1_t, get_hash_phase2, chunk_t,
772 private_keymat_v1_t *this, message_t *message)
773 {
774 u_int32_t mid = message->get_message_id(message), mid_n = htonl(mid);
775 chunk_t data = chunk_empty, hash = chunk_empty;
776 bool add_message = TRUE;
777 char *name = "Hash";
778
779 if (!this->prf)
780 { /* no keys derived yet */
781 return hash;
782 }
783
784 /* Hashes are simple for most exchanges in Phase 2:
785 * Hash = prf(SKEYID_a, M-ID | Complete message after HASH payload)
786 * For Quick Mode there are three hashes:
787 * Hash(1) = same as above
788 * Hash(2) = prf(SKEYID_a, M-ID | Ni_b | Message after HASH payload)
789 * Hash(3) = prf(SKEYID_a, 0 | M-ID | Ni_b | Nr_b)
790 * So, for Quick Mode we keep track of the nonce values.
791 */
792 switch (message->get_exchange_type(message))
793 {
794 case QUICK_MODE:
795 {
796 qm_data_t *qm = lookup_quick_mode(this, mid);
797 if (!qm->n_i.ptr)
798 { /* Hash(1) = prf(SKEYID_a, M-ID | Message after HASH payload) */
799 name = "Hash(1)";
800 if (!get_nonce(message, &qm->n_i))
801 {
802 return hash;
803 }
804 data = chunk_from_thing(mid_n);
805 }
806 else if (!qm->n_r.ptr)
807 { /* Hash(2) = prf(SKEYID_a, M-ID | Ni_b | Message after HASH) */
808 name = "Hash(2)";
809 if (!get_nonce(message, &qm->n_r))
810 {
811 return hash;
812 }
813 data = chunk_cata("cc", chunk_from_thing(mid_n), qm->n_i);
814 }
815 else
816 { /* Hash(3) = prf(SKEYID_a, 0 | M-ID | Ni_b | Nr_b) */
817 name = "Hash(3)";
818 data = chunk_cata("cccc", octet_0, chunk_from_thing(mid_n),
819 qm->n_i, qm->n_r);
820 add_message = FALSE;
821 /* we don't need the state anymore */
822 this->qms->remove(this->qms, qm, NULL);
823 qm_data_destroy(qm);
824 }
825 break;
826 }
827 case TRANSACTION:
828 case INFORMATIONAL_V1:
829 /* Hash = prf(SKEYID_a, M-ID | Message after HASH payload) */
830 data = chunk_from_thing(mid_n);
831 break;
832 default:
833 break;
834 }
835 if (data.ptr)
836 {
837 this->prf->set_key(this->prf, this->skeyid_a);
838 if (add_message)
839 {
840 generator_t *generator = generator_create_no_dbg();
841 chunk_t msg = get_message_data(message, generator);
842 this->prf->allocate_bytes(this->prf, data, NULL);
843 this->prf->allocate_bytes(this->prf, msg, &hash);
844 generator->destroy(generator);
845 }
846 else
847 {
848 this->prf->allocate_bytes(this->prf, data, &hash);
849 }
850 DBG3(DBG_IKE, "%s %B", name, &hash);
851 }
852 return hash;
853 }
854
855 /**
856 * Generate an IV
857 */
858 static void generate_iv(private_keymat_v1_t *this, iv_data_t *iv)
859 {
860 if (iv->mid == 0 || iv->iv.ptr)
861 { /* use last block of previous encrypted message */
862 chunk_free(&iv->iv);
863 iv->iv = iv->last_block;
864 iv->last_block = chunk_empty;
865 }
866 else
867 {
868 /* initial phase 2 IV = hash(last_phase1_block | mid) */
869 u_int32_t net = htonl(iv->mid);
870 chunk_t data = chunk_cata("cc", this->phase1_iv.iv,
871 chunk_from_thing(net));
872 this->hasher->allocate_hash(this->hasher, data, &iv->iv);
873 if (iv->iv.len > this->aead->get_block_size(this->aead))
874 {
875 iv->iv.len = this->aead->get_block_size(this->aead);
876 }
877 }
878 DBG4(DBG_IKE, "next IV for MID %u %B", iv->mid, &iv->iv);
879 }
880
881 /**
882 * Try to find an IV for the given message ID, if not found, generate it.
883 */
884 static iv_data_t *lookup_iv(private_keymat_v1_t *this, u_int32_t mid)
885 {
886 enumerator_t *enumerator;
887 iv_data_t *iv, *found = NULL;
888
889 if (mid == 0)
890 {
891 return &this->phase1_iv;
892 }
893
894 enumerator = this->ivs->create_enumerator(this->ivs);
895 while (enumerator->enumerate(enumerator, &iv))
896 {
897 if (iv->mid == mid)
898 { /* IV gets moved to the front of the list */
899 this->ivs->remove_at(this->ivs, enumerator);
900 found = iv;
901 break;
902 }
903 }
904 enumerator->destroy(enumerator);
905 if (!found)
906 {
907 INIT(found,
908 .mid = mid,
909 );
910 generate_iv(this, found);
911 }
912 this->ivs->insert_first(this->ivs, found);
913 /* remove least recently used IV if maximum reached */
914 if (this->ivs->get_count(this->ivs) > MAX_IV &&
915 this->ivs->remove_last(this->ivs, (void**)&iv) == SUCCESS)
916 {
917 iv_data_destroy(iv);
918 }
919 return found;
920 }
921
922 METHOD(keymat_v1_t, get_iv, chunk_t,
923 private_keymat_v1_t *this, u_int32_t mid)
924 {
925 return chunk_clone(lookup_iv(this, mid)->iv);
926 }
927
928 METHOD(keymat_v1_t, update_iv, void,
929 private_keymat_v1_t *this, u_int32_t mid, chunk_t last_block)
930 {
931 iv_data_t *iv = lookup_iv(this, mid);
932 if (iv)
933 { /* update last block */
934 chunk_free(&iv->last_block);
935 iv->last_block = chunk_clone(last_block);
936 }
937 }
938
939 METHOD(keymat_v1_t, confirm_iv, void,
940 private_keymat_v1_t *this, u_int32_t mid)
941 {
942 iv_data_t *iv = lookup_iv(this, mid);
943 if (iv)
944 {
945 generate_iv(this, iv);
946 }
947 }
948
949 METHOD(keymat_t, get_version, ike_version_t,
950 private_keymat_v1_t *this)
951 {
952 return IKEV1;
953 }
954
955 METHOD(keymat_t, create_dh, diffie_hellman_t*,
956 private_keymat_v1_t *this, diffie_hellman_group_t group)
957 {
958 return lib->crypto->create_dh(lib->crypto, group);
959 }
960
961 METHOD(keymat_t, get_aead, aead_t*,
962 private_keymat_v1_t *this, bool in)
963 {
964 return this->aead;
965 }
966
967 METHOD(keymat_t, destroy, void,
968 private_keymat_v1_t *this)
969 {
970 DESTROY_IF(this->prf);
971 DESTROY_IF(this->aead);
972 DESTROY_IF(this->hasher);
973 chunk_clear(&this->skeyid);
974 chunk_clear(&this->skeyid_d);
975 chunk_clear(&this->skeyid_a);
976 chunk_free(&this->phase1_iv.iv);
977 chunk_free(&this->phase1_iv.last_block);
978 this->ivs->destroy_function(this->ivs, (void*)iv_data_destroy);
979 this->qms->destroy_function(this->qms, (void*)qm_data_destroy);
980 free(this);
981 }
982
983 /**
984 * See header
985 */
986 keymat_v1_t *keymat_v1_create(bool initiator)
987 {
988 private_keymat_v1_t *this;
989
990 INIT(this,
991 .public = {
992 .keymat = {
993 .get_version = _get_version,
994 .create_dh = _create_dh,
995 .get_aead = _get_aead,
996 .destroy = _destroy,
997 },
998 .derive_ike_keys = _derive_ike_keys,
999 .derive_child_keys = _derive_child_keys,
1000 .create_hasher = _create_hasher,
1001 .get_hasher = _get_hasher,
1002 .get_hash = _get_hash,
1003 .get_hash_phase2 = _get_hash_phase2,
1004 .get_iv = _get_iv,
1005 .update_iv = _update_iv,
1006 .confirm_iv = _confirm_iv,
1007 },
1008 .ivs = linked_list_create(),
1009 .qms = linked_list_create(),
1010 .initiator = initiator,
1011 .prf_alg = PRF_UNDEFINED,
1012 );
1013
1014 return &this->public;
1015 }