Added a function to keymat_v1 to create the hasher earlier than during key derivation.
[strongswan.git] / src / libcharon / sa / 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 {
432 /* signatures : SKEYID = prf(Ni_b | Nr_b, g^xy)
433 * pubkey encr: SKEYID = prf(hash(Ni_b | Nr_b), CKY-I | CKY-R) */
434 /* TODO-IKEv1: implement key derivation for other schemes,
435 * fall for now */
436 }
437 default:
438 /* authentication class not supported */
439 chunk_clear(&g_xy);
440 return FALSE;
441 }
442 adjust_keylen(alg, &this->skeyid);
443 DBG4(DBG_IKE, "SKEYID %B", &this->skeyid);
444
445 /* SKEYID_d = prf(SKEYID, g^xy | CKY-I | CKY-R | 0) */
446 data = chunk_cat("cccc", g_xy, spi_i, spi_r, octet_0);
447 this->prf->set_key(this->prf, this->skeyid);
448 this->prf->allocate_bytes(this->prf, data, &this->skeyid_d);
449 chunk_clear(&data);
450 DBG4(DBG_IKE, "SKEYID_d %B", &this->skeyid_d);
451
452 /* SKEYID_a = prf(SKEYID, SKEYID_d | g^xy | CKY-I | CKY-R | 1) */
453 data = chunk_cat("ccccc", this->skeyid_d, g_xy, spi_i, spi_r, octet_1);
454 this->prf->set_key(this->prf, this->skeyid);
455 this->prf->allocate_bytes(this->prf, data, &this->skeyid_a);
456 chunk_clear(&data);
457 DBG4(DBG_IKE, "SKEYID_a %B", &this->skeyid_a);
458
459 /* SKEYID_e = prf(SKEYID, SKEYID_a | g^xy | CKY-I | CKY-R | 2) */
460 data = chunk_cat("ccccc", this->skeyid_a, g_xy, spi_i, spi_r, octet_2);
461 this->prf->set_key(this->prf, this->skeyid);
462 this->prf->allocate_bytes(this->prf, data, &skeyid_e);
463 chunk_clear(&data);
464 DBG4(DBG_IKE, "SKEYID_e %B", &skeyid_e);
465
466 chunk_clear(&g_xy);
467
468 this->aead = create_aead(proposal, this->prf, skeyid_e);
469 if (!this->aead)
470 {
471 return FALSE;
472 }
473 if (!this->hasher && !this->public.create_hasher(&this->public, proposal))
474 {
475 return FALSE;
476 }
477
478 dh->get_my_public_value(dh, &dh_me);
479 g_xi = this->initiator ? dh_me : dh_other;
480 g_xr = this->initiator ? dh_other : dh_me;
481
482 /* initial IV = hash(g^xi | g^xr) */
483 data = chunk_cata("cc", g_xi, g_xr);
484 this->hasher->allocate_hash(this->hasher, data, &this->phase1_iv.iv);
485 if (this->phase1_iv.iv.len > this->aead->get_block_size(this->aead))
486 {
487 this->phase1_iv.iv.len = this->aead->get_block_size(this->aead);
488 }
489 chunk_free(&dh_me);
490 DBG4(DBG_IKE, "initial IV %B", &this->phase1_iv.iv);
491
492 return TRUE;
493 }
494
495 METHOD(keymat_v1_t, derive_child_keys, bool,
496 private_keymat_v1_t *this, proposal_t *proposal, diffie_hellman_t *dh,
497 u_int32_t spi_i, u_int32_t spi_r, chunk_t nonce_i, chunk_t nonce_r,
498 chunk_t *encr_i, chunk_t *integ_i, chunk_t *encr_r, chunk_t *integ_r)
499 {
500 u_int16_t enc_alg, int_alg, enc_size = 0, int_size = 0;
501 u_int8_t protocol;
502 prf_plus_t *prf_plus;
503 chunk_t seed, secret = chunk_empty;
504
505 if (proposal->get_algorithm(proposal, ENCRYPTION_ALGORITHM,
506 &enc_alg, &enc_size))
507 {
508 DBG2(DBG_CHD, " using %N for encryption",
509 encryption_algorithm_names, enc_alg);
510
511 if (!enc_size)
512 {
513 enc_size = keymat_get_keylen_encr(enc_alg);
514 }
515 if (enc_alg != ENCR_NULL && !enc_size)
516 {
517 DBG1(DBG_CHD, "no keylength defined for %N",
518 encryption_algorithm_names, enc_alg);
519 return FALSE;
520 }
521 /* to bytes */
522 enc_size /= 8;
523
524 /* CCM/GCM/CTR/GMAC needs additional bytes */
525 switch (enc_alg)
526 {
527 case ENCR_AES_CCM_ICV8:
528 case ENCR_AES_CCM_ICV12:
529 case ENCR_AES_CCM_ICV16:
530 case ENCR_CAMELLIA_CCM_ICV8:
531 case ENCR_CAMELLIA_CCM_ICV12:
532 case ENCR_CAMELLIA_CCM_ICV16:
533 enc_size += 3;
534 break;
535 case ENCR_AES_GCM_ICV8:
536 case ENCR_AES_GCM_ICV12:
537 case ENCR_AES_GCM_ICV16:
538 case ENCR_AES_CTR:
539 case ENCR_NULL_AUTH_AES_GMAC:
540 enc_size += 4;
541 break;
542 default:
543 break;
544 }
545 }
546
547 if (proposal->get_algorithm(proposal, INTEGRITY_ALGORITHM,
548 &int_alg, &int_size))
549 {
550 DBG2(DBG_CHD, " using %N for integrity",
551 integrity_algorithm_names, int_alg);
552
553 if (!int_size)
554 {
555 int_size = keymat_get_keylen_integ(int_alg);
556 }
557 if (!int_size)
558 {
559 DBG1(DBG_CHD, "no keylength defined for %N",
560 integrity_algorithm_names, int_alg);
561 return FALSE;
562 }
563 /* to bytes */
564 int_size /= 8;
565 }
566
567 /* KEYMAT = prf+(SKEYID_d, [ g(qm)^xy | ] protocol | SPI | Ni_b | Nr_b) */
568 this->prf->set_key(this->prf, this->skeyid_d);
569 protocol = proposal->get_protocol(proposal);
570 if (dh)
571 {
572 if (dh->get_shared_secret(dh, &secret) != SUCCESS)
573 {
574 return FALSE;
575 }
576 DBG4(DBG_CHD, "DH secret %B", &secret);
577 }
578
579 seed = chunk_cata("ccccc", secret, chunk_from_thing(protocol),
580 chunk_from_thing(spi_r), nonce_i, nonce_r);
581 DBG4(DBG_CHD, "initiator SA seed %B", &seed);
582
583 prf_plus = prf_plus_create(this->prf, FALSE, seed);
584 prf_plus->allocate_bytes(prf_plus, enc_size, encr_i);
585 prf_plus->allocate_bytes(prf_plus, int_size, integ_i);
586 prf_plus->destroy(prf_plus);
587
588 seed = chunk_cata("ccccc", secret, chunk_from_thing(protocol),
589 chunk_from_thing(spi_i), nonce_i, nonce_r);
590 DBG4(DBG_CHD, "responder SA seed %B", &seed);
591 prf_plus = prf_plus_create(this->prf, FALSE, seed);
592 prf_plus->allocate_bytes(prf_plus, enc_size, encr_r);
593 prf_plus->allocate_bytes(prf_plus, int_size, integ_r);
594 prf_plus->destroy(prf_plus);
595
596 chunk_clear(&secret);
597
598 if (enc_size)
599 {
600 DBG4(DBG_CHD, "encryption initiator key %B", encr_i);
601 DBG4(DBG_CHD, "encryption responder key %B", encr_r);
602 }
603 if (int_size)
604 {
605 DBG4(DBG_CHD, "integrity initiator key %B", integ_i);
606 DBG4(DBG_CHD, "integrity responder key %B", integ_r);
607 }
608 return TRUE;
609 }
610
611 METHOD(keymat_v1_t, create_hasher, bool,
612 private_keymat_v1_t *this, proposal_t *proposal)
613 {
614 u_int16_t alg;
615 if (!proposal->get_algorithm(proposal, INTEGRITY_ALGORITHM, &alg, NULL) ||
616 (alg = auth_to_hash(alg)) == HASH_UNKNOWN)
617 {
618 DBG1(DBG_IKE, "no %N selected", transform_type_names, HASH_ALGORITHM);
619 return FALSE;
620 }
621 this->hasher = lib->crypto->create_hasher(lib->crypto, alg);
622 if (!this->hasher)
623 {
624 DBG1(DBG_IKE, "%N %N not supported!",
625 transform_type_names, HASH_ALGORITHM,
626 hash_algorithm_names, alg);
627 return FALSE;
628 }
629 return TRUE;
630 }
631
632 METHOD(keymat_v1_t, get_hasher, hasher_t*,
633 private_keymat_v1_t *this)
634 {
635 return this->hasher;
636 }
637
638 METHOD(keymat_v1_t, get_hash, chunk_t,
639 private_keymat_v1_t *this, bool initiator, chunk_t dh, chunk_t dh_other,
640 ike_sa_id_t *ike_sa_id, chunk_t sa_i, identification_t *id)
641 {
642 chunk_t hash, data;
643 u_int64_t spi, spi_other;
644 /* TODO-IKEv1: get real bytes from ID header? */
645 u_int8_t id_header[4] = { id->get_type(id), 0, 0, 0 };
646
647 /* HASH_I = prf(SKEYID, g^xi | g^xr | CKY-I | CKY-R | SAi_b | IDii_b )
648 * HASH_R = prf(SKEYID, g^xr | g^xi | CKY-R | CKY-I | SAi_b | IDir_b )
649 */
650 if (initiator)
651 {
652 spi = ike_sa_id->get_initiator_spi(ike_sa_id);
653 spi_other = ike_sa_id->get_responder_spi(ike_sa_id);
654 }
655 else
656 {
657 spi_other = ike_sa_id->get_initiator_spi(ike_sa_id);
658 spi = ike_sa_id->get_responder_spi(ike_sa_id);
659 }
660 data = chunk_cat("ccccccc", dh, dh_other,
661 chunk_from_thing(spi), chunk_from_thing(spi_other),
662 sa_i, chunk_from_thing(id_header), id->get_encoding(id));
663
664 DBG3(DBG_IKE, "HASH_%c data %B", initiator ? 'I' : 'R', &data);
665
666 this->prf->set_key(this->prf, this->skeyid);
667 this->prf->allocate_bytes(this->prf, data, &hash);
668
669 DBG3(DBG_IKE, "HASH_%c %B", initiator ? 'I' : 'R', &hash);
670
671 free(data.ptr);
672 return hash;
673 }
674
675 /**
676 * Get the nonce value found in the given message.
677 * Returns FALSE if none is found.
678 */
679 static bool get_nonce(message_t *message, chunk_t *n)
680 {
681 nonce_payload_t *nonce;
682 nonce = (nonce_payload_t*)message->get_payload(message, NONCE_V1);
683 if (nonce)
684 {
685 *n = nonce->get_nonce(nonce);
686 return TRUE;
687 }
688 return FALSE;
689 }
690
691 /**
692 * Generate the message data in order to generate the hashes.
693 */
694 static chunk_t get_message_data(message_t *message, generator_t *generator)
695 {
696 payload_t *payload, *next;
697 enumerator_t *enumerator;
698 u_int32_t *lenpos;
699
700 if (message->is_encoded(message))
701 { /* inbound, although the message is generated, we cannot access the
702 * cleartext message data, so generate it anyway */
703 enumerator = message->create_payload_enumerator(message);
704 while (enumerator->enumerate(enumerator, &payload))
705 {
706 if (payload->get_type(payload) == HASH_V1)
707 {
708 continue;
709 }
710 generator->generate_payload(generator, payload);
711 }
712 enumerator->destroy(enumerator);
713 }
714 else
715 {
716 /* outbound, generate the payloads (there is no HASH payload yet) */
717 enumerator = message->create_payload_enumerator(message);
718 if (enumerator->enumerate(enumerator, &payload))
719 {
720 while (enumerator->enumerate(enumerator, &next))
721 {
722 payload->set_next_type(payload, next->get_type(next));
723 generator->generate_payload(generator, payload);
724 payload = next;
725 }
726 payload->set_next_type(payload, NO_PAYLOAD);
727 generator->generate_payload(generator, payload);
728 }
729 enumerator->destroy(enumerator);
730 }
731 return generator->get_chunk(generator, &lenpos);
732 }
733
734 /**
735 * Try to find data about a Quick Mode with the given message ID,
736 * if none is found, state is generated.
737 */
738 static qm_data_t *lookup_quick_mode(private_keymat_v1_t *this, u_int32_t mid)
739 {
740 enumerator_t *enumerator;
741 qm_data_t *qm, *found = NULL;
742
743 enumerator = this->qms->create_enumerator(this->qms);
744 while (enumerator->enumerate(enumerator, &qm))
745 {
746 if (qm->mid == mid)
747 { /* state gets moved to the front of the list */
748 this->qms->remove_at(this->qms, enumerator);
749 found = qm;
750 break;
751 }
752 }
753 enumerator->destroy(enumerator);
754 if (!found)
755 {
756 INIT(found,
757 .mid = mid,
758 );
759 }
760 this->qms->insert_first(this->qms, found);
761 /* remove least recently used state if maximum reached */
762 if (this->qms->get_count(this->qms) > MAX_QM &&
763 this->qms->remove_last(this->qms, (void**)&qm) == SUCCESS)
764 {
765 qm_data_destroy(qm);
766 }
767 return found;
768 }
769
770 METHOD(keymat_v1_t, get_hash_phase2, chunk_t,
771 private_keymat_v1_t *this, message_t *message)
772 {
773 u_int32_t mid = message->get_message_id(message), mid_n = htonl(mid);
774 chunk_t data = chunk_empty, hash = chunk_empty;
775 bool add_message = TRUE;
776 char *name = "Hash";
777
778 if (!this->prf)
779 { /* no keys derived yet */
780 return hash;
781 }
782
783 /* Hashes are simple for most exchanges in Phase 2:
784 * Hash = prf(SKEYID_a, M-ID | Complete message after HASH payload)
785 * For Quick Mode there are three hashes:
786 * Hash(1) = same as above
787 * Hash(2) = prf(SKEYID_a, M-ID | Ni_b | Message after HASH payload)
788 * Hash(3) = prf(SKEYID_a, 0 | M-ID | Ni_b | Nr_b)
789 * So, for Quick Mode we keep track of the nonce values.
790 */
791 switch (message->get_exchange_type(message))
792 {
793 case QUICK_MODE:
794 {
795 qm_data_t *qm = lookup_quick_mode(this, mid);
796 if (!qm->n_i.ptr)
797 { /* Hash(1) = prf(SKEYID_a, M-ID | Message after HASH payload) */
798 name = "Hash(1)";
799 if (!get_nonce(message, &qm->n_i))
800 {
801 return hash;
802 }
803 data = chunk_from_thing(mid_n);
804 }
805 else if (!qm->n_r.ptr)
806 { /* Hash(2) = prf(SKEYID_a, M-ID | Ni_b | Message after HASH) */
807 name = "Hash(2)";
808 if (!get_nonce(message, &qm->n_r))
809 {
810 return hash;
811 }
812 data = chunk_cata("cc", chunk_from_thing(mid_n), qm->n_i);
813 }
814 else
815 { /* Hash(3) = prf(SKEYID_a, 0 | M-ID | Ni_b | Nr_b) */
816 name = "Hash(3)";
817 data = chunk_cata("cccc", octet_0, chunk_from_thing(mid_n),
818 qm->n_i, qm->n_r);
819 add_message = FALSE;
820 /* we don't need the state anymore */
821 this->qms->remove(this->qms, qm, NULL);
822 qm_data_destroy(qm);
823 }
824 break;
825 }
826 case TRANSACTION:
827 case INFORMATIONAL_V1:
828 /* Hash = prf(SKEYID_a, M-ID | Message after HASH payload) */
829 data = chunk_from_thing(mid_n);
830 break;
831 default:
832 break;
833 }
834 if (data.ptr)
835 {
836 this->prf->set_key(this->prf, this->skeyid_a);
837 if (add_message)
838 {
839 generator_t *generator = generator_create_no_dbg();
840 chunk_t msg = get_message_data(message, generator);
841 this->prf->allocate_bytes(this->prf, data, NULL);
842 this->prf->allocate_bytes(this->prf, msg, &hash);
843 generator->destroy(generator);
844 }
845 else
846 {
847 this->prf->allocate_bytes(this->prf, data, &hash);
848 }
849 DBG3(DBG_IKE, "%s %B", name, &hash);
850 }
851 return hash;
852 }
853
854 /**
855 * Generate an IV
856 */
857 static void generate_iv(private_keymat_v1_t *this, iv_data_t *iv)
858 {
859 if (iv->mid == 0 || iv->iv.ptr)
860 { /* use last block of previous encrypted message */
861 chunk_free(&iv->iv);
862 iv->iv = iv->last_block;
863 iv->last_block = chunk_empty;
864 }
865 else
866 {
867 /* initial phase 2 IV = hash(last_phase1_block | mid) */
868 u_int32_t net = htonl(iv->mid);
869 chunk_t data = chunk_cata("cc", this->phase1_iv.iv,
870 chunk_from_thing(net));
871 this->hasher->allocate_hash(this->hasher, data, &iv->iv);
872 if (iv->iv.len > this->aead->get_block_size(this->aead))
873 {
874 iv->iv.len = this->aead->get_block_size(this->aead);
875 }
876 }
877 DBG4(DBG_IKE, "next IV for MID %u %B", iv->mid, &iv->iv);
878 }
879
880 /**
881 * Try to find an IV for the given message ID, if not found, generate it.
882 */
883 static iv_data_t *lookup_iv(private_keymat_v1_t *this, u_int32_t mid)
884 {
885 enumerator_t *enumerator;
886 iv_data_t *iv, *found = NULL;
887
888 if (mid == 0)
889 {
890 return &this->phase1_iv;
891 }
892
893 enumerator = this->ivs->create_enumerator(this->ivs);
894 while (enumerator->enumerate(enumerator, &iv))
895 {
896 if (iv->mid == mid)
897 { /* IV gets moved to the front of the list */
898 this->ivs->remove_at(this->ivs, enumerator);
899 found = iv;
900 break;
901 }
902 }
903 enumerator->destroy(enumerator);
904 if (!found)
905 {
906 INIT(found,
907 .mid = mid,
908 );
909 generate_iv(this, found);
910 }
911 this->ivs->insert_first(this->ivs, found);
912 /* remove least recently used IV if maximum reached */
913 if (this->ivs->get_count(this->ivs) > MAX_IV &&
914 this->ivs->remove_last(this->ivs, (void**)&iv) == SUCCESS)
915 {
916 iv_data_destroy(iv);
917 }
918 return found;
919 }
920
921 METHOD(keymat_v1_t, get_iv, chunk_t,
922 private_keymat_v1_t *this, u_int32_t mid)
923 {
924 return chunk_clone(lookup_iv(this, mid)->iv);
925 }
926
927 METHOD(keymat_v1_t, update_iv, void,
928 private_keymat_v1_t *this, u_int32_t mid, chunk_t last_block)
929 {
930 iv_data_t *iv = lookup_iv(this, mid);
931 if (iv)
932 { /* update last block */
933 chunk_free(&iv->last_block);
934 iv->last_block = chunk_clone(last_block);
935 }
936 }
937
938 METHOD(keymat_v1_t, confirm_iv, void,
939 private_keymat_v1_t *this, u_int32_t mid)
940 {
941 iv_data_t *iv = lookup_iv(this, mid);
942 if (iv)
943 {
944 generate_iv(this, iv);
945 }
946 }
947
948 METHOD(keymat_t, create_dh, diffie_hellman_t*,
949 private_keymat_v1_t *this, diffie_hellman_group_t group)
950 {
951 return lib->crypto->create_dh(lib->crypto, group);
952 }
953
954 METHOD(keymat_t, get_aead, aead_t*,
955 private_keymat_v1_t *this, bool in)
956 {
957 return this->aead;
958 }
959
960 METHOD(keymat_t, destroy, void,
961 private_keymat_v1_t *this)
962 {
963 DESTROY_IF(this->prf);
964 DESTROY_IF(this->aead);
965 DESTROY_IF(this->hasher);
966 chunk_clear(&this->skeyid);
967 chunk_clear(&this->skeyid_d);
968 chunk_clear(&this->skeyid_a);
969 chunk_free(&this->phase1_iv.iv);
970 chunk_free(&this->phase1_iv.last_block);
971 this->ivs->destroy_function(this->ivs, (void*)iv_data_destroy);
972 this->qms->destroy_function(this->qms, (void*)qm_data_destroy);
973 free(this);
974 }
975
976 /**
977 * See header
978 */
979 keymat_v1_t *keymat_v1_create(bool initiator)
980 {
981 private_keymat_v1_t *this;
982
983 INIT(this,
984 .public = {
985 .keymat = {
986 .create_dh = _create_dh,
987 .get_aead = _get_aead,
988 .destroy = _destroy,
989 },
990 .derive_ike_keys = _derive_ike_keys,
991 .derive_child_keys = _derive_child_keys,
992 .create_hasher = _create_hasher,
993 .get_hasher = _get_hasher,
994 .get_hash = _get_hash,
995 .get_hash_phase2 = _get_hash_phase2,
996 .get_iv = _get_iv,
997 .update_iv = _update_iv,
998 .confirm_iv = _confirm_iv,
999 },
1000 .ivs = linked_list_create(),
1001 .qms = linked_list_create(),
1002 .initiator = initiator,
1003 .prf_alg = PRF_UNDEFINED,
1004 );
1005
1006 return &this->public;
1007 }