New upstream version 0.3.7
[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 methods 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-2014 Markus Grüneis, 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  *  In addition, as a special exception, the copyright holders give
33  *  permission to link the code of portions of this program with the
34  *  OpenSSL library under certain conditions as described in each
35  *  individual source file, and distribute linked combinations
36  *  including the two.
37  *  You must obey the GNU General Public License in all respects
38  *  for all of the code used other than OpenSSL.  If you modify
39  *  file(s) with this exception, you may extend this exception to your
40  *  version of the file(s), but you are not obligated to do so.  If you
41  *  do not wish to do so, delete this exception statement from your
42  *  version.  If you delete this exception statement from all source
43  *  files in the program, then also delete it here.
44  */
45
46
47 #include "log.h"
48 #include "anytunError.h"
49 #include "keyDerivation.h"
50 #include "threadUtils.hpp"
51 #include "datatypes.h"
52 #include "endian.h"
53
54 #include <stdexcept>
55 #include <iostream>
56 #include <sstream>
57 #include <string>
58 #include <cstring>
59
60 #ifndef NO_CRYPT
61 #ifndef NO_PASSPHRASE
62
63 #if defined(USE_SSL_CRYPTO)
64 #include <openssl/crypto.h>
65 #include <openssl/sha.h>
66 #include <openssl/modes.h>
67 #elif defined(USE_NETTLE)
68 #include <nettle/sha1.h>
69 #include <nettle/sha2.h>
70 #include <nettle/ctr.h>
71 #endif
72
73 #endif
74 #endif
75
76 void KeyDerivation::setRole(const role_t role)
77 {
78   WritersLock lock(mutex_);
79   role_ = role;
80   cLog.msg(Log::PRIO_NOTICE) << "KeyDerivation: using role " << role_;
81 }
82
83 #ifndef NO_CRYPT
84 #ifndef NO_PASSPHRASE
85 void KeyDerivation::calcMasterKey(std::string passphrase, uint16_t length)
86 {
87   cLog.msg(Log::PRIO_NOTICE) << "KeyDerivation: calculating master key from passphrase";
88   if(!length) {
89     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation: bad master key length";
90     return;
91   }
92
93 #if defined(USE_SSL_CRYPTO)
94   if(length > SHA256_DIGEST_LENGTH) {
95 #elif defined(USE_NETTLE)
96   if(length > SHA256_DIGEST_SIZE) {
97 #else  // USE_GCRYPT is the default
98   if(length > gcry_md_get_algo_dlen(GCRY_MD_SHA256)) {
99 #endif
100     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation: master key too long for passphrase algorithm";
101     return;
102   }
103
104 #if defined(USE_SSL_CRYPTO)
105   Buffer digest(uint32_t(SHA256_DIGEST_LENGTH));
106   SHA256(reinterpret_cast<const unsigned char*>(passphrase.c_str()), passphrase.length(), digest.getBuf());
107 #elif defined(USE_NETTLE)
108   Buffer digest(uint32_t(SHA256_DIGEST_SIZE));
109   struct sha256_ctx ctx;
110   sha256_init(&ctx);
111   sha256_update(&ctx, passphrase.length(), reinterpret_cast<const unsigned char*>(passphrase.c_str()));
112   sha256_digest(&ctx, digest.getLength(), digest.getBuf());
113 #else  // USE_GCRYPT is the default
114   Buffer digest(static_cast<uint32_t>(gcry_md_get_algo_dlen(GCRY_MD_SHA256)));
115   gcry_md_hash_buffer(GCRY_MD_SHA256, digest.getBuf(), passphrase.c_str(), passphrase.length());
116 #endif
117   master_key_.setLength(length);
118
119   std::memcpy(master_key_.getBuf(), &digest.getBuf()[digest.getLength() - master_key_.getLength()], master_key_.getLength());
120 }
121
122 void KeyDerivation::calcMasterSalt(std::string passphrase, uint16_t length)
123 {
124   cLog.msg(Log::PRIO_NOTICE) << "KeyDerivation: calculating master salt from passphrase";
125   if(!length) {
126     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation: bad master salt length";
127     return;
128   }
129
130 #if defined(USE_SSL_CRYPTO)
131   if(length > SHA_DIGEST_LENGTH) {
132 #elif defined(USE_NETTLE)
133   if(length > SHA1_DIGEST_SIZE) {
134 #else  // USE_GCRYPT is the default
135   if(length > gcry_md_get_algo_dlen(GCRY_MD_SHA1)) {
136 #endif
137     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation: master key too long for passphrase algorithm";
138     return;
139   }
140
141 #if defined(USE_SSL_CRYPTO)
142   Buffer digest(uint32_t(SHA_DIGEST_LENGTH));
143   SHA1(reinterpret_cast<const unsigned char*>(passphrase.c_str()), passphrase.length(), digest.getBuf());
144 #elif defined(USE_NETTLE)
145   Buffer digest(uint32_t(SHA1_DIGEST_SIZE));
146   struct sha1_ctx ctx;
147   sha1_init(&ctx);
148   sha1_update(&ctx, passphrase.length(), reinterpret_cast<const unsigned char*>(passphrase.c_str()));
149   sha1_digest(&ctx, digest.getLength(), digest.getBuf());
150 #else  // USE_GCRYPT is the default
151   Buffer digest(static_cast<uint32_t>(gcry_md_get_algo_dlen(GCRY_MD_SHA1)));
152   gcry_md_hash_buffer(GCRY_MD_SHA1, digest.getBuf(), passphrase.c_str(), passphrase.length());
153 #endif
154   master_salt_.setLength(length);
155
156   std::memcpy(master_salt_.getBuf(), &digest.getBuf()[digest.getLength() - master_salt_.getLength()], master_salt_.getLength());
157 }
158 #endif
159 #endif
160
161 satp_prf_label_t KeyDerivation::convertLabel(kd_dir_t dir, satp_prf_label_t label)
162 {
163   switch(label) {
164   case LABEL_ENC: {
165     if(dir == KD_OUTBOUND) {
166       if(role_ == ROLE_LEFT) { return LABEL_LEFT_ENC; }
167       if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_ENC; }
168     } else {
169       if(role_ == ROLE_LEFT) { return LABEL_RIGHT_ENC; }
170       if(role_ == ROLE_RIGHT) { return LABEL_LEFT_ENC; }
171     }
172     break;
173   }
174   case LABEL_SALT: {
175     if(dir == KD_OUTBOUND) {
176       if(role_ == ROLE_LEFT) { return LABEL_LEFT_SALT; }
177       if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_SALT; }
178     } else {
179       if(role_ == ROLE_LEFT) { return LABEL_RIGHT_SALT; }
180       if(role_ == ROLE_RIGHT) { return LABEL_LEFT_SALT; }
181     }
182     break;
183   }
184   case LABEL_AUTH: {
185     if(dir == KD_OUTBOUND) {
186       if(role_ == ROLE_LEFT) { return LABEL_LEFT_AUTH; }
187       if(role_ == ROLE_RIGHT) { return LABEL_RIGHT_AUTH; }
188     } else {
189       if(role_ == ROLE_LEFT) { return LABEL_RIGHT_AUTH; }
190       if(role_ == ROLE_RIGHT) { return LABEL_LEFT_AUTH; }
191     }
192     break;
193   }
194   }
195
196   return label;
197 }
198
199 //****** NullKeyDerivation ******
200
201 bool NullKeyDerivation::generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key)
202 {
203   std::memset(key.getBuf(), 0, key.getLength());
204   return true;
205 }
206
207 #ifndef NO_CRYPT
208 //****** AesIcmKeyDerivation ******
209
210 AesIcmKeyDerivation::AesIcmKeyDerivation() : KeyDerivation(DEFAULT_KEY_LENGTH)
211 {
212 #if defined(USE_GCRYPT)
213   for(int i=0; i<2; i++) {
214     handle_[i] = NULL;
215   }
216 #endif
217 }
218
219 AesIcmKeyDerivation::AesIcmKeyDerivation(uint16_t key_length) : KeyDerivation(key_length)
220 {
221 #if defined(USE_GCRYPT)
222   for(int i=0; i<2; i++) {
223     handle_[i] = NULL;
224   }
225 #endif
226 }
227
228 AesIcmKeyDerivation::~AesIcmKeyDerivation()
229 {
230   WritersLock lock(mutex_);
231 #if defined(USE_GCRYPT)
232   for(int i=0; i<2; i++)
233     if(handle_[i]) {
234       gcry_cipher_close(handle_[i]);
235     }
236 #endif
237 }
238
239 void AesIcmKeyDerivation::init(Buffer key, Buffer salt, std::string passphrase)
240 {
241   WritersLock lock(mutex_);
242
243   is_initialized_ = false;
244 #ifndef NO_PASSPHRASE
245   if(passphrase != "" && !key.getLength()) {
246     calcMasterKey(passphrase, key_length_/8);
247   } else {
248     master_key_ = SyncBuffer(key);
249   }
250
251   if(passphrase != "" && !salt.getLength()) {
252     calcMasterSalt(passphrase, SALT_LENGTH);
253   } else {
254     master_salt_ = SyncBuffer(salt);
255   }
256 #else
257   master_key_ = SyncBuffer(key);
258   master_salt_ = SyncBuffer(salt);
259 #endif
260
261   updateMasterKey();
262 }
263
264 void AesIcmKeyDerivation::updateMasterKey()
265 {
266   if(master_key_.getLength()*8 != key_length_) {
267     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: key lengths don't match";
268     return;
269   }
270
271   if(master_salt_.getLength() != SALT_LENGTH) {
272     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: salt lengths don't match";
273     return;
274   }
275
276 #if defined(USE_SSL_CRYPTO)
277   for(int i=0; i<2; i++) {
278     int ret = AES_set_encrypt_key(master_key_.getBuf(), master_key_.getLength()*8, &aes_key_[i]);
279     if(ret) {
280       cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: Failed to set ssl key (code: " << ret << ")";
281       return;
282     }
283   }
284 #elif defined(USE_NETTLE)
285   for(int i=0; i<2; i++) {
286     aes_set_encrypt_key(&(ctx_[i]), master_key_.getLength(), master_key_.getBuf());
287   }
288 #else  // USE_GCRYPT is the default
289   int algo;
290   switch(key_length_) {
291   case 128:
292     algo = GCRY_CIPHER_AES128;
293     break;
294   case 192:
295     algo = GCRY_CIPHER_AES192;
296     break;
297   case 256:
298     algo = GCRY_CIPHER_AES256;
299     break;
300   default: {
301     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: cipher key length of " << key_length_ << " Bits is not supported";
302     return;
303   }
304   }
305
306   for(int i=0; i<2; i++) {
307     if(handle_[i]) {
308       gcry_cipher_close(handle_[i]);
309     }
310
311     gcry_error_t err = gcry_cipher_open(&handle_[i], algo, GCRY_CIPHER_MODE_CTR, 0);
312     if(err) {
313       cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: Failed to open cipher: " << AnytunGpgError(err);
314       return;
315     }
316
317     err = gcry_cipher_setkey(handle_[i], master_key_.getBuf(), master_key_.getLength());
318     if(err) {
319       cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::updateMasterKey: Failed to set cipher key: " << AnytunGpgError(err);
320       return;
321     }
322   }
323 #endif
324   is_initialized_ = true;
325 }
326
327 std::string AesIcmKeyDerivation::printType()
328 {
329   ReadersLock lock(mutex_);
330
331   std::stringstream sstr;
332   sstr << "AesIcm" << key_length_ << "KeyDerivation";
333   return sstr.str();
334 }
335
336 bool AesIcmKeyDerivation::calcCtr(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr)
337 {
338   if(master_salt_.getLength() != SALT_LENGTH) {
339     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::calcCtr: salt lengths don't match";
340     return false;
341   }
342   std::memcpy(ctr_[dir].salt_.buf_, master_salt_.getBuf(), SALT_LENGTH);
343   ctr_[dir].salt_.zero_ = 0;
344   ctr_[dir].params_.label_ ^= SATP_PRF_LABEL_T_HTON(convertLabel(dir, label));
345   ctr_[dir].params_.seq_ ^= SEQ_NR_T_HTON(seq_nr);
346
347   return true;
348 }
349
350 bool AesIcmKeyDerivation::generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key)
351 {
352   ReadersLock lock(mutex_);
353
354   if(!is_initialized_) {
355     return false;
356   }
357
358   if(!calcCtr(dir, label, seq_nr)) {
359     return false;
360   }
361
362 #if defined(USE_SSL_CRYPTO)
363   if(CTR_LENGTH != AES_BLOCK_SIZE) {
364     cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to set cipher CTR: size doesn't fit";
365     return false;
366   }
367   unsigned int num = 0;
368   std::memset(key.getBuf(), 0, key.getLength());
369   std::memset(ecount_buf_[dir], 0, AES_BLOCK_SIZE);
370   CRYPTO_ctr128_encrypt(key.getBuf(), key.getBuf(), key.getLength(), &aes_key_[dir], ctr_[dir].buf_, ecount_buf_[dir], &num, (block128_f)AES_encrypt);
371 #elif defined(USE_NETTLE)
372   if(CTR_LENGTH != AES_BLOCK_SIZE) {
373     cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to set cipher CTR: size doesn't fit";
374     return false;
375   }
376   std::memset(key.getBuf(), 0, key.getLength());
377   ctr_crypt(&(ctx_[dir]), (nettle_crypt_func *)(aes_encrypt), AES_BLOCK_SIZE, ctr_[dir].buf_, key.getLength(), key.getBuf(), key.getBuf());
378 #else  // USE_GCRYPT is the default
379   gcry_error_t err = gcry_cipher_reset(handle_[dir]);
380   if(err) {
381     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::generate: Failed to reset cipher: " << AnytunGpgError(err);
382   }
383
384   err = gcry_cipher_setctr(handle_[dir], ctr_[dir].buf_, CTR_LENGTH);
385   if(err) {
386     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::generate: Failed to set CTR: " << AnytunGpgError(err);
387     return false;
388   }
389
390   std::memset(key.getBuf(), 0, key.getLength());
391   err = gcry_cipher_encrypt(handle_[dir], key, key.getLength(), NULL, 0);
392   if(err) {
393     cLog.msg(Log::PRIO_ERROR) << "KeyDerivation::generate: Failed to generate cipher bitstream: " << AnytunGpgError(err);
394   }
395 #endif
396
397   return true;
398 }
399 #endif
400