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