Imported Upstream version 0.3.4
[anytun.git] / src / keyDerivation.cpp
1 /*
2  *  anytun
3  *
4  *  The secure anycast tunneling protocol (satp) defines a protocol used
5  *  for communication between any combination of unicast and anycast
6  *  tunnel endpoints.  It has less protocol overhead than IPSec in Tunnel
7  *  mode and allows tunneling of every ETHER TYPE protocol (e.g.
8  *  ethernet, ip, arp ...). satp directly includes cryptography and
9  *  message authentication based on the methodes used by SRTP.  It is
10  *  intended to deliver a generic, scaleable and secure solution for
11  *  tunneling and relaying of packets of any protocol.
12  *
13  *
14  *  Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl,
15  *                          Christian Pointner <satp@wirdorange.org>
16  *
17  *  This file is part of Anytun.
18  *
19  *  Anytun is free software: you can redistribute it and/or modify
20  *  it under the terms of the GNU General Public License as published by
21  *  the Free Software Foundation, either version 3 of the License, or
22  *  any later version.
23  *
24  *  Anytun is distributed in the hope that it will be useful,
25  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
26  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  *  GNU General Public License for more details.
28  *
29  *  You should have received a copy of the GNU General Public License
30  *  along with anytun.  If not, see <http://www.gnu.org/licenses/>.
31  */
32
33
34 #include "log.h"
35 #include "anytunError.h"
36 #include "keyDerivation.h"
37 #include "threadUtils.hpp"
38 #include "datatypes.h"
39 #include "endian.h"
40
41 #include <stdexcept>
42 #include <iostream>
43 #include <sstream>
44 #include <string>
45 #include <cstring>
46
47 #ifndef NO_CRYPT
48 #ifndef NO_PASSPHRASE
49 #ifdef USE_SSL_CRYPTO
50 #include <openssl/sha.h>
51 #endif
52 #endif
53 #endif
54
55 void KeyDerivation::setRole(const role_t role)
56 {
57   WritersLock lock(mutex_);
58   role_ = role;
59   cLog.msg(Log::PRIO_NOTICE) << "KeyDerivation: using role " << role_;
60 }
61
62 #ifndef NO_CRYPT
63 #ifndef NO_PASSPHRASE
64 void KeyDerivation::calcMasterKey(std::string passphrase, uint16_t length)
65 {
66   cLog.msg(Log::PRIO_NOTICE) << "KeyDerivation: calculating master key from passphrase";
67   if(!length) {
68     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation: bad master key length";
69     return;
70   }
71
72 #ifndef USE_SSL_CRYPTO
73   if(length > gcry_md_get_algo_dlen(GCRY_MD_SHA256)) {
74 #else
75   if(length > SHA256_DIGEST_LENGTH) {
76 #endif
77     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation: master key too long for passphrase algorithm";
78     return;
79   }
80
81 #ifndef USE_SSL_CRYPTO
82   Buffer digest(static_cast<uint32_t>(gcry_md_get_algo_dlen(GCRY_MD_SHA256)));
83   gcry_md_hash_buffer(GCRY_MD_SHA256, digest.getBuf(), passphrase.c_str(), passphrase.length());
84 #else
85   Buffer digest(uint32_t(SHA256_DIGEST_LENGTH));
86   SHA256(reinterpret_cast<const unsigned char*>(passphrase.c_str()), passphrase.length(), digest.getBuf());
87 #endif
88   master_key_.setLength(length);
89
90   std::memcpy(master_key_.getBuf(), &digest.getBuf()[digest.getLength() - master_key_.getLength()], master_key_.getLength());
91 }
92
93 void KeyDerivation::calcMasterSalt(std::string passphrase, uint16_t length)
94 {
95   cLog.msg(Log::PRIO_NOTICE) << "KeyDerivation: calculating master salt from passphrase";
96   if(!length) {
97     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation: bad master salt length";
98     return;
99   }
100
101 #ifndef USE_SSL_CRYPTO
102   if(length > gcry_md_get_algo_dlen(GCRY_MD_SHA1)) {
103 #else
104   if(length > SHA_DIGEST_LENGTH) {
105 #endif
106     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation: master key too long for passphrase algorithm";
107     return;
108   }
109
110 #ifndef USE_SSL_CRYPTO
111   Buffer digest(static_cast<uint32_t>(gcry_md_get_algo_dlen(GCRY_MD_SHA1)));
112   gcry_md_hash_buffer(GCRY_MD_SHA1, digest.getBuf(), passphrase.c_str(), passphrase.length());
113 #else
114   Buffer digest(uint32_t(SHA_DIGEST_LENGTH));
115   SHA1(reinterpret_cast<const unsigned char*>(passphrase.c_str()), passphrase.length(), digest.getBuf());
116 #endif
117   master_salt_.setLength(length);
118
119   std::memcpy(master_salt_.getBuf(), &digest.getBuf()[digest.getLength() - master_salt_.getLength()], master_salt_.getLength());
120 }
121 #endif
122 #endif
123
124 satp_prf_label_t KeyDerivation::convertLabel(kd_dir_t dir, satp_prf_label_t label)
125 {
126   switch(label) {
127   case LABEL_ENC: {
128     if(dir == KD_OUTBOUND) {
129       if(role_ == ROLE_LEFT) { return LABEL_LEFT_ENC; }
130       if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_ENC; }
131     } else {
132       if(role_ == ROLE_LEFT) { return LABEL_RIGHT_ENC; }
133       if(role_ == ROLE_RIGHT) { return LABEL_LEFT_ENC; }
134     }
135     break;
136   }
137   case LABEL_SALT: {
138     if(dir == KD_OUTBOUND) {
139       if(role_ == ROLE_LEFT) { return LABEL_LEFT_SALT; }
140       if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_SALT; }
141     } else {
142       if(role_ == ROLE_LEFT) { return LABEL_RIGHT_SALT; }
143       if(role_ == ROLE_RIGHT) { return LABEL_LEFT_SALT; }
144     }
145     break;
146   }
147   case LABEL_AUTH: {
148     if(dir == KD_OUTBOUND) {
149       if(role_ == ROLE_LEFT) { return LABEL_LEFT_AUTH; }
150       if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_AUTH; }
151     } else {
152       if(role_ == ROLE_LEFT) { return LABEL_RIGHT_AUTH; }
153       if(role_ == ROLE_RIGHT) { return LABEL_LEFT_AUTH; }
154     }
155     break;
156   }
157   }
158
159   return label;
160 }
161
162 //****** NullKeyDerivation ******
163
164 bool NullKeyDerivation::generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key)
165 {
166   std::memset(key.getBuf(), 0, key.getLength());
167   return true;
168 }
169
170 #ifndef NO_CRYPT
171 //****** AesIcmKeyDerivation ******
172
173 AesIcmKeyDerivation::AesIcmKeyDerivation() : KeyDerivation(DEFAULT_KEY_LENGTH)
174 {
175 #ifndef USE_SSL_CRYPTO
176   for(int i=0; i<2; i++) {
177     handle_[i] = NULL;
178   }
179 #endif
180 }
181
182 AesIcmKeyDerivation::AesIcmKeyDerivation(uint16_t key_length) : KeyDerivation(key_length)
183 {
184 #ifndef USE_SSL_CRYPTO
185   for(int i=0; i<2; i++) {
186     handle_[i] = NULL;
187   }
188 #endif
189 }
190
191 AesIcmKeyDerivation::~AesIcmKeyDerivation()
192 {
193   WritersLock lock(mutex_);
194 #ifndef USE_SSL_CRYPTO
195   for(int i=0; i<2; i++)
196     if(handle_[i]) {
197       gcry_cipher_close(handle_[i]);
198     }
199 #endif
200 }
201
202 void AesIcmKeyDerivation::init(Buffer key, Buffer salt, std::string passphrase)
203 {
204   WritersLock lock(mutex_);
205
206   is_initialized_ = false;
207 #ifndef NO_PASSPHRASE
208   if(passphrase != "" && !key.getLength()) {
209     calcMasterKey(passphrase, key_length_/8);
210   } else {
211     master_key_ = SyncBuffer(key);
212   }
213
214   if(passphrase != "" && !salt.getLength()) {
215     calcMasterSalt(passphrase, SALT_LENGTH);
216   } else {
217     master_salt_ = SyncBuffer(salt);
218   }
219 #else
220   master_key_ = SyncBuffer(key);
221   master_salt_ = SyncBuffer(salt);
222 #endif
223
224   updateMasterKey();
225 }
226
227 void AesIcmKeyDerivation::updateMasterKey()
228 {
229   if(master_key_.getLength()*8 != key_length_) {
230     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: key lengths don't match";
231     return;
232   }
233
234   if(master_salt_.getLength() != SALT_LENGTH) {
235     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: salt lengths don't match";
236     return;
237   }
238
239 #ifndef USE_SSL_CRYPTO
240   int algo;
241   switch(key_length_) {
242   case 128:
243     algo = GCRY_CIPHER_AES128;
244     break;
245   case 192:
246     algo = GCRY_CIPHER_AES192;
247     break;
248   case 256:
249     algo = GCRY_CIPHER_AES256;
250     break;
251   default: {
252     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: cipher key length of " << key_length_ << " Bits is not supported";
253     return;
254   }
255   }
256
257   for(int i=0; i<2; i++) {
258     if(handle_[i]) {
259       gcry_cipher_close(handle_[i]);
260     }
261
262     gcry_error_t err = gcry_cipher_open(&handle_[i], algo, GCRY_CIPHER_MODE_CTR, 0);
263     if(err) {
264       cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: Failed to open cipher: " << AnytunGpgError(err);
265       return;
266     }
267
268     err = gcry_cipher_setkey(handle_[i], master_key_.getBuf(), master_key_.getLength());
269     if(err) {
270       cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: Failed to set cipher key: " << AnytunGpgError(err);
271       return;
272     }
273   }
274 #else
275   for(int i=0; i<2; i++) {
276     int ret = AES_set_encrypt_key(master_key_.getBuf(), master_key_.getLength()*8, &aes_key_[i]);
277     if(ret) {
278       cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: Failed to set ssl key (code: " << ret << ")";
279       return;
280     }
281   }
282 #endif
283   is_initialized_ = true;
284 }
285
286 std::string AesIcmKeyDerivation::printType()
287 {
288   ReadersLock lock(mutex_);
289
290   std::stringstream sstr;
291   sstr << "AesIcm" << key_length_ << "KeyDerivation";
292   return sstr.str();
293 }
294
295 bool AesIcmKeyDerivation::calcCtr(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr)
296 {
297   if(master_salt_.getLength() != SALT_LENGTH) {
298     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::calcCtr: salt lengths don't match";
299     return false;
300   }
301   std::memcpy(ctr_[dir].salt_.buf_, master_salt_.getBuf(), SALT_LENGTH);
302   ctr_[dir].salt_.zero_ = 0;
303   ctr_[dir].params_.label_ ^= SATP_PRF_LABEL_T_HTON(convertLabel(dir, label));
304   ctr_[dir].params_.seq_ ^= SEQ_NR_T_HTON(seq_nr);
305
306   return true;
307 }
308
309 bool AesIcmKeyDerivation::generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key)
310 {
311   ReadersLock lock(mutex_);
312
313   if(!is_initialized_) {
314     return false;
315   }
316
317   if(!calcCtr(dir, label, seq_nr)) {
318     return false;
319   }
320
321 #ifndef USE_SSL_CRYPTO
322   gcry_error_t err = gcry_cipher_reset(handle_[dir]);
323   if(err) {
324     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::generate: Failed to reset cipher: " << AnytunGpgError(err);
325   }
326
327   err = gcry_cipher_setctr(handle_[dir], ctr_[dir].buf_, CTR_LENGTH);
328   if(err) {
329     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::generate: Failed to set CTR: " << AnytunGpgError(err);
330     return false;
331   }
332
333   std::memset(key.getBuf(), 0, key.getLength());
334   err = gcry_cipher_encrypt(handle_[dir], key, key.getLength(), NULL, 0);
335   if(err) {
336     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::generate: Failed to generate cipher bitstream: " << AnytunGpgError(err);
337   }
338 #else
339   if(CTR_LENGTH != AES_BLOCK_SIZE) {
340     cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to set cipher CTR: size don't fits";
341     return false;
342   }
343   unsigned int num = 0;
344   std::memset(ecount_buf_[dir], 0, AES_BLOCK_SIZE);
345   std::memset(key.getBuf(), 0, key.getLength());
346   AES_ctr128_encrypt(key.getBuf(), key.getBuf(), key.getLength(), &aes_key_[dir], ctr_[dir].buf_, ecount_buf_[dir], &num);
347 #endif
348
349   return true;
350 }
351 #endif
352