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