fixed table deserialization from XML
[public/netxms.git] / src / libnetxms / crypto.cpp
CommitLineData
5039dede
AK
1/*
2** NetXMS - Network Management System
3** NetXMS Foundation Library
e5390fb5 4** Copyright (C) 2003-2015 Victor Kirhenshtein
5039dede
AK
5**
6** This program is free software; you can redistribute it and/or modify
68f384ea
VK
7** it under the terms of the GNU Lesser General Public License as published
8** by the Free Software Foundation; either version 3 of the License, or
5039dede
AK
9** (at your option) any later version.
10**
11** This program is distributed in the hope that it will be useful,
12** but WITHOUT ANY WARRANTY; without even the implied warranty of
13** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14** GNU General Public License for more details.
15**
68f384ea 16** You should have received a copy of the GNU Lesser General Public License
5039dede
AK
17** along with this program; if not, write to the Free Software
18** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19**
20** File: crypto.cpp
21**
22**/
23
24#include "libnetxms.h"
4e2debcc 25#include "ice.h"
5039dede 26
b1e9b6b3
VK
27/**
28 * Constants
29 */
5039dede
AK
30#define KEY_BUFFER_SIZE 4096
31
b1e9b6b3
VK
32/**
33 * Supported ciphers. By default, we support all ciphers compiled
34 * into OpenSSL library.
35 */
e5390fb5 36static UINT32 s_supportedCiphers =
5039dede
AK
37#ifdef _WITH_ENCRYPTION
38#ifndef OPENSSL_NO_AES
43a6f3ca
VK
39 NXCP_SUPPORT_AES_256 |
40 NXCP_SUPPORT_AES_128 |
5039dede
AK
41#endif
42#ifndef OPENSSL_NO_BF
43a6f3ca
VK
43 NXCP_SUPPORT_BLOWFISH_256 |
44 NXCP_SUPPORT_BLOWFISH_128 |
5039dede
AK
45#endif
46#ifndef OPENSSL_NO_IDEA
43a6f3ca 47 NXCP_SUPPORT_IDEA |
5039dede
AK
48#endif
49#ifndef OPENSSL_NO_DES
43a6f3ca 50 NXCP_SUPPORT_3DES |
5039dede
AK
51#endif
52#endif /* _WITH_ENCRYPTION */
53 0;
54
b1e9b6b3
VK
55/**
56 * Static data
57 */
e4e091f0 58static void (*s_debugCallback)(int, const TCHAR *, va_list args) = NULL;
c1099678 59static WORD s_noEncryptionFlag = 0;
e4e091f0 60
5039dede
AK
61#ifdef _WITH_ENCRYPTION
62
bb586165 63extern "C" typedef OPENSSL_CONST EVP_CIPHER * (*CIPHER_FUNC)();
6468147c 64static CIPHER_FUNC s_ciphers[NETXMS_MAX_CIPHERS] =
5039dede
AK
65{
66#ifndef OPENSSL_NO_AES
67 EVP_aes_256_cbc,
68#else
69 NULL,
70#endif
71#ifndef OPENSSL_NO_BF
72 EVP_bf_cbc,
73#else
74 NULL,
75#endif
76#ifndef OPENSSL_NO_IDEA
77 EVP_idea_cbc,
78#else
79 NULL,
80#endif
81#ifndef OPENSSL_NO_DES
9e9d631e
VK
82 EVP_des_ede3_cbc,
83#else
84 NULL,
85#endif
86#ifndef OPENSSL_NO_AES
d772d0dd
VK
87 EVP_aes_128_cbc,
88#else
89 NULL,
90#endif
91#ifndef OPENSSL_NO_BF
92 EVP_bf_cbc
5039dede
AK
93#else
94 NULL
95#endif
96};
6468147c 97static const TCHAR *s_cipherNames[NETXMS_MAX_CIPHERS] = { _T("AES-256"), _T("Blowfish-256"), _T("IDEA"), _T("3DES"), _T("AES-128"), _T("Blowfish-128") };
6468147c 98static MUTEX *s_cryptoMutexList = NULL;
5039dede 99
b1e9b6b3
VK
100/**
101 * Locking callback for CRYPTO library
102 */
bb586165
VK
103#if defined(__SUNPRO_CC)
104extern "C"
105#endif
5039dede
AK
106static void CryptoLockingCallback(int nMode, int nLock, const char *pszFile, int nLine)
107{
108 if (nMode & CRYPTO_LOCK)
6468147c 109 MutexLock(s_cryptoMutexList[nLock]);
5039dede 110 else
6468147c 111 MutexUnlock(s_cryptoMutexList[nLock]);
5039dede
AK
112}
113
b1e9b6b3
VK
114/**
115 * ID callback for CRYPTO library
116 */
5039dede
AK
117#ifndef _WIN32
118
bb586165
VK
119#if defined(__SUNPRO_CC)
120extern "C"
121#endif
9e9d631e 122static unsigned long CryptoIdCallback()
5039dede
AK
123{
124 return (unsigned long)GetCurrentThreadId();
125}
126
127#endif
128
129#endif /* _WITH_ENCRYPTION */
130
b1e9b6b3 131/**
6468147c
VK
132 * Debug output
133 */
134static void CryptoDbgPrintf(int level, const TCHAR *format, ...)
135{
136 if (s_debugCallback == NULL)
137 return;
138
139 va_list args;
140 va_start(args, format);
141 s_debugCallback(level, format, args);
142 va_end(args);
143}
144
145/**
b1e9b6b3
VK
146 * Initialize OpenSSL library
147 */
bf6fb6c3 148bool LIBNETXMS_EXPORTABLE InitCryptoLib(UINT32 dwEnabledCiphers, void (*debugCallback)(int, const TCHAR *, va_list args))
5039dede 149{
6468147c 150 s_debugCallback = debugCallback;
c1099678 151 s_noEncryptionFlag = htons(MF_DONT_ENCRYPT);
6468147c 152
5039dede
AK
153#ifdef _WITH_ENCRYPTION
154 BYTE random[8192];
155 int i;
156
157 CRYPTO_malloc_init();
158 ERR_load_CRYPTO_strings();
159 OpenSSL_add_all_algorithms();
160 RAND_seed(random, 8192);
6468147c 161 s_cryptoMutexList = (MUTEX *)malloc(sizeof(MUTEX) * CRYPTO_num_locks());
5039dede 162 for(i = 0; i < CRYPTO_num_locks(); i++)
6468147c 163 s_cryptoMutexList[i] = MutexCreate();
5039dede
AK
164 CRYPTO_set_locking_callback(CryptoLockingCallback);
165#ifndef _WIN32
166 CRYPTO_set_id_callback(CryptoIdCallback);
167#endif /* _WIN32 */
6468147c
VK
168
169 // validate supported ciphers
ae8e3292 170 CryptoDbgPrintf(1, _T("Validating ciphers"));
e5390fb5 171 s_supportedCiphers &= dwEnabledCiphers;
6468147c
VK
172 UINT32 cipherBit = 1;
173 for(i = 0; i < NETXMS_MAX_CIPHERS; i++, cipherBit = cipherBit << 1)
174 {
e5390fb5 175 if ((s_supportedCiphers & cipherBit) == 0)
ae8e3292
VK
176 {
177 CryptoDbgPrintf(1, _T(" %s disabled (config)"), s_cipherNames[i]);
6468147c 178 continue;
ae8e3292 179 }
6468147c
VK
180 NXCPEncryptionContext *ctx = NXCPEncryptionContext::create(cipherBit);
181 if (ctx != NULL)
182 {
183 delete ctx;
ae8e3292 184 CryptoDbgPrintf(1, _T(" %s enabled"), s_cipherNames[i]);
6468147c
VK
185 }
186 else
187 {
e5390fb5 188 s_supportedCiphers &= ~cipherBit;
ae8e3292 189 CryptoDbgPrintf(1, _T(" %s disabled (validation failed)"), s_cipherNames[i]);
6468147c
VK
190 }
191 }
192
193 CryptoDbgPrintf(1, _T("Crypto library initialized"));
194
195#else
196 CryptoDbgPrintf(1, _T("Crypto library will not be initialized because libnetxms was built without encryption support"));
5039dede 197#endif /* _WITH_ENCRYPTION */
bf6fb6c3 198 return true;
5039dede
AK
199}
200
b1e9b6b3
VK
201/**
202 * Get supported ciphers
203 */
e5390fb5 204UINT32 LIBNETXMS_EXPORTABLE NXCPGetSupportedCiphers()
5039dede 205{
e5390fb5
VK
206 return s_supportedCiphers;
207}
208
209/**
210 * Get supported ciphers as text
211 */
212String LIBNETXMS_EXPORTABLE NXCPGetSupportedCiphersAsText()
213{
214 String s;
215 UINT32 cipherBit = 1;
216 for(int i = 0; i < NETXMS_MAX_CIPHERS; i++, cipherBit = cipherBit << 1)
217 {
218 if ((s_supportedCiphers & cipherBit) == 0)
219 {
220 continue;
221 }
222 NXCPEncryptionContext *ctx = NXCPEncryptionContext::create(cipherBit);
223 if (ctx != NULL)
224 {
225 delete ctx;
226 if (s.length() > 0)
227 s.append(_T(", "));
228 s.append(s_cipherNames[i]);
229 }
230 }
231 return s;
5039dede
AK
232}
233
b1e9b6b3
VK
234/**
235 * Encrypt message
236 */
b368969c 237NXCP_ENCRYPTED_MESSAGE LIBNETXMS_EXPORTABLE *NXCPEncryptMessage(NXCPEncryptionContext *pCtx, NXCP_MESSAGE *msg)
5039dede 238{
b368969c 239 return (pCtx != NULL) ? pCtx->encryptMessage(msg) : NULL;
5039dede
AK
240}
241
7aad6641
VK
242/**
243 * Decrypt message
244 */
bf6fb6c3 245bool LIBNETXMS_EXPORTABLE NXCPDecryptMessage(NXCPEncryptionContext *pCtx, NXCP_ENCRYPTED_MESSAGE *msg, BYTE *pDecryptionBuffer)
5039dede 246{
bf6fb6c3 247 return (pCtx != NULL) ? pCtx->decryptMessage(msg, pDecryptionBuffer) : false;
5039dede
AK
248}
249
b1e9b6b3
VK
250/**
251 * Setup encryption context
252 * Function will determine is it called on initiator or responder side
253 * by message code. Initiator should provide it's private key,
254 * and responder should provide pointer to response message.
255 */
b368969c 256UINT32 LIBNETXMS_EXPORTABLE SetupEncryptionContext(NXCPMessage *msg,
98abc9f1 257 NXCPEncryptionContext **ppCtx,
b368969c 258 NXCPMessage **ppResponse,
5039dede
AK
259 RSA *pPrivateKey, int nNXCPVersion)
260{
967893bb 261 UINT32 dwResult = RCC_NOT_IMPLEMENTED;
5039dede 262
98abc9f1 263 *ppCtx = NULL;
5039dede 264#ifdef _WITH_ENCRYPTION
b368969c 265 if (msg->getCode() == CMD_REQUEST_SESSION_KEY)
5039dede 266 {
967893bb 267 UINT32 dwCiphers;
5039dede 268
b368969c
VK
269 *ppResponse = new NXCPMessage(nNXCPVersion);
270 (*ppResponse)->setCode(CMD_SESSION_KEY);
271 (*ppResponse)->setId(msg->getId());
4af351c7 272 (*ppResponse)->disableEncryption();
5039dede 273
e5390fb5 274 dwCiphers = msg->getFieldAsUInt32(VID_SUPPORTED_ENCRYPTION) & s_supportedCiphers;
5039dede
AK
275 if (dwCiphers == 0)
276 {
b368969c 277 (*ppResponse)->setField(VID_RCC, RCC_NO_CIPHERS);
5039dede
AK
278 dwResult = RCC_NO_CIPHERS;
279 }
280 else
281 {
98abc9f1
VK
282 BYTE *pBufPos, ucKeyBuffer[KEY_BUFFER_SIZE];
283 RSA *pServerKey;
5039dede 284
98abc9f1 285 *ppCtx = NXCPEncryptionContext::create(dwCiphers);
5039dede
AK
286
287 // Encrypt key
b368969c 288 int size = msg->getFieldAsBinary(VID_PUBLIC_KEY, ucKeyBuffer, KEY_BUFFER_SIZE);
5039dede 289 pBufPos = ucKeyBuffer;
eae8c74c 290 pServerKey = d2i_RSAPublicKey(NULL, (OPENSSL_CONST BYTE **)&pBufPos, size);
5039dede
AK
291 if (pServerKey != NULL)
292 {
b368969c 293 (*ppResponse)->setField(VID_RCC, RCC_SUCCESS);
eae8c74c
VK
294
295 size = RSA_public_encrypt((*ppCtx)->getKeyLength(), (*ppCtx)->getSessionKey(), ucKeyBuffer, pServerKey, RSA_PKCS1_OAEP_PADDING);
b368969c
VK
296 (*ppResponse)->setField(VID_SESSION_KEY, ucKeyBuffer, (UINT32)size);
297 (*ppResponse)->setField(VID_KEY_LENGTH, (WORD)(*ppCtx)->getKeyLength());
eae8c74c 298
6468147c 299 int ivLength = EVP_CIPHER_iv_length(s_ciphers[(*ppCtx)->getCipher()]());
eae8c74c
VK
300 if ((ivLength <= 0) || (ivLength > EVP_MAX_IV_LENGTH))
301 ivLength = EVP_MAX_IV_LENGTH;
302 size = RSA_public_encrypt(ivLength, (*ppCtx)->getIV(), ucKeyBuffer, pServerKey, RSA_PKCS1_OAEP_PADDING);
b368969c
VK
303 (*ppResponse)->setField(VID_SESSION_IV, ucKeyBuffer, (UINT32)size);
304 (*ppResponse)->setField(VID_IV_LENGTH, (WORD)ivLength);
eae8c74c 305
b368969c 306 (*ppResponse)->setField(VID_CIPHER, (WORD)(*ppCtx)->getCipher());
5039dede
AK
307 RSA_free(pServerKey);
308 dwResult = RCC_SUCCESS;
309 }
310 else
311 {
b368969c 312 (*ppResponse)->setField(VID_RCC, RCC_INVALID_PUBLIC_KEY);
5039dede
AK
313 dwResult = RCC_INVALID_PUBLIC_KEY;
314 }
315 }
316 }
b368969c 317 else if (msg->getCode() == CMD_SESSION_KEY)
5039dede 318 {
b368969c 319 dwResult = msg->getFieldAsUInt32(VID_RCC);
5039dede
AK
320 if (dwResult == RCC_SUCCESS)
321 {
b368969c 322 *ppCtx = NXCPEncryptionContext::create(msg, pPrivateKey);
98abc9f1
VK
323 if (*ppCtx == NULL)
324 {
325 dwResult = RCC_INVALID_SESSION_KEY;
326 }
5039dede
AK
327 }
328 }
329
330 if ((dwResult != RCC_SUCCESS) && (*ppCtx != NULL))
331 {
98abc9f1 332 delete *ppCtx;
5039dede
AK
333 *ppCtx = NULL;
334 }
335#else
b368969c 336 if (msg->getCode() == CMD_REQUEST_SESSION_KEY)
5039dede 337 {
b368969c 338 *ppResponse = new NXCPMessage(nNXCPVersion);
5039dede 339 (*ppResponse)->SetCode(CMD_SESSION_KEY);
b368969c 340 (*ppResponse)->SetId(msg->getId());
26de9040 341 (*ppResponse)->disableEncryption();
b368969c 342 (*ppResponse)->setField(VID_RCC, dwResult);
5039dede
AK
343 }
344#endif
345
346 return dwResult;
347}
348
b1e9b6b3
VK
349/**
350 * Prepare session key request message
351 */
b368969c 352void LIBNETXMS_EXPORTABLE PrepareKeyRequestMsg(NXCPMessage *msg, RSA *pServerKey, bool useX509Format)
5039dede
AK
353{
354#ifdef _WITH_ENCRYPTION
355 int iLen;
356 BYTE *pKeyBuffer, *pBufPos;
357
b368969c 358 msg->setCode(CMD_REQUEST_SESSION_KEY);
e5390fb5 359 msg->setField(VID_SUPPORTED_ENCRYPTION, s_supportedCiphers);
5039dede 360
9e9d631e
VK
361 if (useX509Format)
362 {
363 iLen = i2d_RSA_PUBKEY(pServerKey, NULL);
364 pKeyBuffer = (BYTE *)malloc(iLen);
365 pBufPos = pKeyBuffer;
366 i2d_RSA_PUBKEY(pServerKey, &pBufPos);
367 }
368 else
369 {
370 iLen = i2d_RSAPublicKey(pServerKey, NULL);
371 pKeyBuffer = (BYTE *)malloc(iLen);
372 pBufPos = pKeyBuffer;
373 i2d_RSAPublicKey(pServerKey, &pBufPos);
374 }
b368969c 375 msg->setField(VID_PUBLIC_KEY, pKeyBuffer, iLen);
5039dede
AK
376 free(pKeyBuffer);
377#endif
378}
379
7aad6641
VK
380/**
381 * Load RSA key(s) from file
382 */
5039dede
AK
383RSA LIBNETXMS_EXPORTABLE *LoadRSAKeys(const TCHAR *pszKeyFile)
384{
385#ifdef _WITH_ENCRYPTION
386 FILE *fp;
387 BYTE *pKeyBuffer, *pBufPos, hash[SHA1_DIGEST_SIZE];
967893bb 388 UINT32 dwLen;
5039dede
AK
389 RSA *pKey = NULL;
390
391 fp = _tfopen(pszKeyFile, _T("rb"));
392 if (fp != NULL)
393 {
967893bb 394 if (fread(&dwLen, 1, sizeof(UINT32), fp) == sizeof(UINT32) && dwLen < 10 * 1024)
5039dede
AK
395 {
396 pKeyBuffer = (BYTE *)malloc(dwLen);
397 pBufPos = pKeyBuffer;
398 if (fread(pKeyBuffer, 1, dwLen, fp) == dwLen)
399 {
400 BYTE hash2[SHA1_DIGEST_SIZE];
401
7aad6641 402 if (fread(hash, 1, SHA1_DIGEST_SIZE, fp) == SHA1_DIGEST_SIZE)
5039dede 403 {
7aad6641
VK
404 CalculateSHA1Hash(pKeyBuffer, dwLen, hash2);
405 if (!memcmp(hash, hash2, SHA1_DIGEST_SIZE))
5039dede 406 {
7aad6641
VK
407 pKey = d2i_RSAPublicKey(NULL, (OPENSSL_CONST BYTE **)&pBufPos, dwLen);
408 if (pKey != NULL)
5039dede 409 {
7aad6641 410 if (d2i_RSAPrivateKey(&pKey, (OPENSSL_CONST BYTE **)&pBufPos,
967893bb 411 dwLen - CAST_FROM_POINTER((pBufPos - pKeyBuffer), UINT32)) == NULL)
7aad6641
VK
412 {
413 RSA_free(pKey);
414 pKey = NULL;
415 }
5039dede
AK
416 }
417 }
418 }
419 }
420 free(pKeyBuffer);
421 }
422 fclose(fp);
423 }
424
425 return pKey;
426#else
427 return NULL;
428#endif
429}
430
7aad6641
VK
431/**
432 * Create signature for message using certificate (MS CAPI version)
433 * Paraeters:
b368969c 434 * msg and dwMsgLen - message to sign and it's length
7aad6641
VK
435 * pCert - certificate
436 * pBuffer - output buffer
437 * dwBufSize - buffer size
438 * pdwSigLen - actual signature size
439 */
5039dede
AK
440#ifdef _WIN32
441
b368969c 442BOOL LIBNETXMS_EXPORTABLE SignMessageWithCAPI(BYTE *msg, UINT32 dwMsgLen, const CERT_CONTEXT *pCert,
967893bb 443 BYTE *pBuffer, UINT32 dwBufSize, UINT32 *pdwSigLen)
5039dede
AK
444{
445 BOOL bFreeProv, bRet = FALSE;
446 DWORD i, j, dwLen, dwKeySpec;
447 HCRYPTPROV hProv;
448 HCRYPTHASH hHash;
449 BYTE *pTemp;
450
6468147c 451 if (CryptAcquireCertificatePrivateKey(pCert, CRYPT_ACQUIRE_COMPARE_KEY_FLAG, NULL, &hProv, &dwKeySpec, &bFreeProv))
5039dede
AK
452 {
453 if (CryptCreateHash(hProv, CALG_SHA1, NULL, 0, &hHash))
454 {
b368969c 455 if (CryptHashData(hHash, msg, dwMsgLen, 0))
5039dede
AK
456 {
457 dwLen = dwBufSize;
458 pTemp = (BYTE *)malloc(dwBufSize);;
459 bRet = CryptSignHash(hHash, dwKeySpec, NULL, 0, pTemp, &dwLen);
460 *pdwSigLen = dwLen;
461 // we have to reverse the byte-order in the result from CryptSignHash()
462 for(i = 0, j = dwLen - 1; i < dwLen; i++, j--)
463 pBuffer[i] = pTemp[j];
464 }
465 CryptDestroyHash(hHash);
466 }
467
468 if (bFreeProv)
469 CryptReleaseContext(hProv, 0);
470 }
471 return bRet;
472}
473
474#endif
4e2debcc 475
7aad6641
VK
476/**
477 * Encrypt data block with ICE
478 */
4e2debcc
VK
479void LIBNETXMS_EXPORTABLE ICEEncryptData(const BYTE *in, int inLen, BYTE *out, const BYTE *key)
480{
481 ICE_KEY *ice = ice_key_create(1);
482 ice_key_set(ice, key);
483
484 int stopPos = inLen - (inLen % 8);
4e2debcc
VK
485 for(int pos = 0; pos < stopPos; pos += 8)
486 ice_key_encrypt(ice, &in[pos], &out[pos]);
487
488 if (stopPos < inLen)
489 {
490 BYTE plainText[8], encrypted[8];
491
492 memcpy(plainText, &in[stopPos], inLen - stopPos);
493 ice_key_encrypt(ice, plainText, encrypted);
494 memcpy(&out[stopPos], encrypted, inLen - stopPos);
495 }
496
497 ice_key_destroy(ice);
498}
499
7aad6641
VK
500/**
501 * Decrypt data block with ICE
502 */
4e2debcc
VK
503void LIBNETXMS_EXPORTABLE ICEDecryptData(const BYTE *in, int inLen, BYTE *out, const BYTE *key)
504{
505 ICE_KEY *ice = ice_key_create(1);
506 ice_key_set(ice, key);
507
508 int stopPos = inLen - (inLen % 8);
4e2debcc
VK
509 for(int pos = 0; pos < stopPos; pos += 8)
510 ice_key_decrypt(ice, &in[pos], &out[pos]);
511
512 if (stopPos < inLen)
513 {
514 BYTE plainText[8], encrypted[8];
515
516 memcpy(encrypted, &in[stopPos], inLen - stopPos);
517 ice_key_decrypt(ice, encrypted, plainText);
518 memcpy(&out[stopPos], plainText, inLen - stopPos);
519 }
520
521 ice_key_destroy(ice);
522}
98abc9f1 523
7aad6641
VK
524/**
525 * Encryption context constructor
526 */
98abc9f1
VK
527NXCPEncryptionContext::NXCPEncryptionContext()
528{
e4e091f0
VK
529 m_sessionKey = NULL;
530#ifdef _WITH_ENCRYPTION
e6336a90
VK
531 EVP_CIPHER_CTX_init(&m_encryptor);
532 EVP_CIPHER_CTX_init(&m_decryptor);
db05c2af 533 m_encryptorLock = MutexCreate();
e4e091f0 534#endif
98abc9f1
VK
535}
536
7aad6641
VK
537/**
538 * Encryption context destructor
539 */
98abc9f1
VK
540NXCPEncryptionContext::~NXCPEncryptionContext()
541{
e4e091f0
VK
542 safe_free(m_sessionKey);
543#ifdef _WITH_ENCRYPTION
e6336a90
VK
544 EVP_CIPHER_CTX_cleanup(&m_encryptor);
545 EVP_CIPHER_CTX_cleanup(&m_decryptor);
db05c2af 546 MutexDestroy(m_encryptorLock);
e4e091f0 547#endif
98abc9f1
VK
548}
549
7aad6641
VK
550/**
551 * Create encryption context from CMD_SESSION_KEY NXCP message
552 */
b368969c 553NXCPEncryptionContext *NXCPEncryptionContext::create(NXCPMessage *msg, RSA *privateKey)
98abc9f1 554{
e4cba530 555#ifdef _WITH_ENCRYPTION
98abc9f1 556 BYTE ucKeyBuffer[KEY_BUFFER_SIZE], ucSessionKey[KEY_BUFFER_SIZE];
967893bb 557 UINT32 dwKeySize;
98abc9f1
VK
558 int nSize, nIVLen;
559 NXCPEncryptionContext *ctx = new NXCPEncryptionContext;
560
b368969c 561 int cipher = (int)msg->getFieldAsUInt16(VID_CIPHER);
e6336a90 562 if (ctx->initCipher(cipher))
98abc9f1 563 {
b368969c 564 if (ctx->m_keyLength == (int)msg->getFieldAsUInt16(VID_KEY_LENGTH))
98abc9f1 565 {
e6336a90
VK
566 ctx->m_sessionKey = (BYTE *)malloc(ctx->m_keyLength);
567
568 // Decrypt session key
b368969c 569 dwKeySize = msg->getFieldAsBinary(VID_SESSION_KEY, ucKeyBuffer, KEY_BUFFER_SIZE);
e6336a90
VK
570 nSize = RSA_private_decrypt(dwKeySize, ucKeyBuffer, ucSessionKey, privateKey, RSA_PKCS1_OAEP_PADDING);
571 if (nSize == ctx->m_keyLength)
572 {
573 memcpy(ctx->m_sessionKey, ucSessionKey, nSize);
574
575 // Decrypt session IV
b368969c 576 nIVLen = msg->getFieldAsUInt16(VID_IV_LENGTH);
e6336a90
VK
577 if (nIVLen == 0) // Versions prior to 0.2.13 don't send IV length, assume 16
578 nIVLen = 16;
b368969c 579 dwKeySize = msg->getFieldAsBinary(VID_SESSION_IV, ucKeyBuffer, KEY_BUFFER_SIZE);
e6336a90
VK
580 nSize = RSA_private_decrypt(dwKeySize, ucKeyBuffer, ucSessionKey, privateKey, RSA_PKCS1_OAEP_PADDING);
581 if ((nSize == nIVLen) &&
6468147c 582 (nIVLen <= EVP_CIPHER_iv_length(s_ciphers[ctx->m_cipher]())))
e6336a90
VK
583 {
584 memcpy(ctx->m_iv, ucSessionKey, min(EVP_MAX_IV_LENGTH, nIVLen));
585 }
586 else
587 {
6468147c 588 CryptoDbgPrintf(6, _T("NXCPEncryptionContext::create: IV decryption failed"));
e6336a90
VK
589 delete_and_null(ctx);
590 }
591 }
592 else
593 {
6468147c 594 CryptoDbgPrintf(6, _T("NXCPEncryptionContext::create: session key decryption failed"));
e6336a90
VK
595 delete_and_null(ctx);
596 }
98abc9f1
VK
597 }
598 else
599 {
b368969c 600 CryptoDbgPrintf(6, _T("NXCPEncryptionContext::create: key length mismatch (remote: %d local: %d)"), (int)msg->getFieldAsUInt16(VID_KEY_LENGTH), ctx->m_keyLength);
98abc9f1
VK
601 delete_and_null(ctx);
602 }
603 }
604 else
605 {
6468147c 606 CryptoDbgPrintf(6, _T("NXCPEncryptionContext::create: initCipher(%d) call failed"), cipher);
98abc9f1
VK
607 delete_and_null(ctx);
608 }
609 return ctx;
e4cba530
VK
610#else
611 return new NXCPEncryptionContext;
612#endif
98abc9f1
VK
613}
614
7aad6641 615/**
e6336a90
VK
616 * Initialize cipher
617 */
618bool NXCPEncryptionContext::initCipher(int cipher)
619{
620#ifdef _WITH_ENCRYPTION
6468147c 621 if (s_ciphers[cipher] == NULL)
e6336a90
VK
622 return false; // Unsupported cipher
623
6468147c 624 if (!EVP_EncryptInit_ex(&m_encryptor, s_ciphers[cipher](), NULL, NULL, NULL))
e6336a90 625 return false;
6468147c 626 if (!EVP_DecryptInit_ex(&m_decryptor, s_ciphers[cipher](), NULL, NULL, NULL))
e6336a90
VK
627 return false;
628
629 switch(cipher)
630 {
43a6f3ca 631 case NXCP_CIPHER_AES_256:
e6336a90
VK
632 m_keyLength = 32;
633 break;
43a6f3ca 634 case NXCP_CIPHER_AES_128:
e6336a90
VK
635 m_keyLength = 16;
636 break;
43a6f3ca 637 case NXCP_CIPHER_BLOWFISH_256:
e6336a90
VK
638 m_keyLength = 32;
639 break;
43a6f3ca 640 case NXCP_CIPHER_BLOWFISH_128:
e6336a90
VK
641 m_keyLength = 16;
642 break;
43a6f3ca 643 case NXCP_CIPHER_IDEA:
e6336a90
VK
644 m_keyLength = 16;
645 break;
43a6f3ca 646 case NXCP_CIPHER_3DES:
e6336a90
VK
647 m_keyLength = 24;
648 break;
649 default:
650 return false;
651 }
652
653 if (!EVP_CIPHER_CTX_set_key_length(&m_encryptor, m_keyLength) || !EVP_CIPHER_CTX_set_key_length(&m_decryptor, m_keyLength))
654 return false;
655
6468147c
VK
656 // This check is needed because at least some OpenSSL versions return no error
657 // from EVP_CIPHER_CTX_set_key_length but still not change key length
658 if ((EVP_CIPHER_CTX_key_length(&m_encryptor) != m_keyLength) || (EVP_CIPHER_CTX_key_length(&m_decryptor) != m_keyLength))
659 return false;
660
e6336a90
VK
661 m_cipher = cipher;
662 return true;
663#else
664 return false;
665#endif
666}
667
668/**
7aad6641
VK
669 * Create encryption context from CMD_REQUEST_SESSION_KEY NXCP message
670 */
967893bb 671NXCPEncryptionContext *NXCPEncryptionContext::create(UINT32 ciphers)
98abc9f1
VK
672{
673 NXCPEncryptionContext *ctx = new NXCPEncryptionContext;
674
e4cba530 675#ifdef _WITH_ENCRYPTION
98abc9f1 676 // Select cipher
e6336a90
VK
677 bool selected = false;
678
43a6f3ca 679 if (ciphers & NXCP_SUPPORT_AES_256)
98abc9f1 680 {
43a6f3ca 681 selected = ctx->initCipher(NXCP_CIPHER_AES_256);
98abc9f1 682 }
e6336a90 683
43a6f3ca 684 if (!selected && (ciphers & NXCP_SUPPORT_BLOWFISH_256))
98abc9f1 685 {
43a6f3ca 686 selected = ctx->initCipher(NXCP_CIPHER_BLOWFISH_256);
98abc9f1 687 }
e6336a90 688
43a6f3ca 689 if (!selected && (ciphers & NXCP_SUPPORT_AES_128))
9e9d631e 690 {
43a6f3ca 691 selected = ctx->initCipher(NXCP_CIPHER_AES_128);
9e9d631e 692 }
e6336a90 693
43a6f3ca 694 if (!selected && (ciphers & NXCP_SUPPORT_BLOWFISH_128))
d772d0dd 695 {
43a6f3ca 696 selected = ctx->initCipher(NXCP_CIPHER_BLOWFISH_128);
d772d0dd 697 }
e6336a90 698
43a6f3ca 699 if (!selected && (ciphers & NXCP_SUPPORT_IDEA))
98abc9f1 700 {
43a6f3ca 701 selected = ctx->initCipher(NXCP_CIPHER_IDEA);
98abc9f1 702 }
e6336a90 703
43a6f3ca 704 if (!selected && (ciphers & NXCP_SUPPORT_3DES))
98abc9f1 705 {
43a6f3ca 706 selected = ctx->initCipher(NXCP_CIPHER_3DES);
e6336a90
VK
707 }
708
709 if (!selected)
710 {
711 delete ctx;
712 return NULL;
98abc9f1
VK
713 }
714
715 // Generate key
716 ctx->m_sessionKey = (BYTE *)malloc(ctx->m_keyLength);
717 RAND_bytes(ctx->m_sessionKey, ctx->m_keyLength);
718 RAND_bytes(ctx->m_iv, EVP_MAX_IV_LENGTH);
e4cba530 719#endif
98abc9f1
VK
720
721 return ctx;
722}
e6336a90
VK
723
724/**
725 * Encrypt message
726 */
b368969c 727NXCP_ENCRYPTED_MESSAGE *NXCPEncryptionContext::encryptMessage(NXCP_MESSAGE *msg)
e6336a90 728{
b368969c
VK
729 if (msg->flags & s_noEncryptionFlag)
730 return (NXCP_ENCRYPTED_MESSAGE *)nx_memdup(msg, ntohl(msg->size));
e6336a90
VK
731
732#ifdef _WITH_ENCRYPTION
db05c2af
VK
733 MutexLock(m_encryptorLock);
734
e6336a90 735 if (!EVP_EncryptInit_ex(&m_encryptor, NULL, NULL, m_sessionKey, m_iv))
db05c2af
VK
736 {
737 MutexUnlock(m_encryptorLock);
e6336a90 738 return NULL;
db05c2af 739 }
e6336a90 740
b368969c 741 UINT32 msgSize = ntohl(msg->size);
6be0a20b
VK
742 NXCP_ENCRYPTED_MESSAGE *emsg =
743 (NXCP_ENCRYPTED_MESSAGE *)malloc(msgSize + NXCP_ENCRYPTION_HEADER_SIZE + EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(&m_encryptor)) + 8);
b368969c
VK
744 emsg->code = htons(CMD_ENCRYPTED_MESSAGE);
745 emsg->reserved = 0;
e6336a90 746
6be0a20b 747 NXCP_ENCRYPTED_PAYLOAD_HEADER header;
e6336a90
VK
748 header.dwChecksum = htonl(CalculateCRC32((BYTE *)msg, msgSize, 0));
749 header.dwReserved = 0;
750
751 int dataSize;
6be0a20b 752 EVP_EncryptUpdate(&m_encryptor, emsg->data, &dataSize, (BYTE *)&header, NXCP_EH_ENCRYPTED_BYTES);
e6336a90 753 msgSize = dataSize;
b368969c 754 EVP_EncryptUpdate(&m_encryptor, emsg->data + msgSize, &dataSize, (BYTE *)msg, ntohl(msg->size));
e6336a90
VK
755 msgSize += dataSize;
756 EVP_EncryptFinal_ex(&m_encryptor, emsg->data + msgSize, &dataSize);
6be0a20b 757 msgSize += dataSize + NXCP_EH_UNENCRYPTED_BYTES;
e6336a90 758
db05c2af
VK
759 MutexUnlock(m_encryptorLock);
760
e6336a90
VK
761 if (msgSize % 8 != 0)
762 {
b368969c
VK
763 emsg->padding = (BYTE)(8 - (msgSize % 8));
764 msgSize += emsg->padding;
e6336a90
VK
765 }
766 else
767 {
b368969c 768 emsg->padding = 0;
e6336a90 769 }
b368969c 770 emsg->size = htonl(msgSize);
e6336a90
VK
771
772 return emsg;
773#else /* _WITH_ENCRYPTION */
774 return NULL;
775#endif
776}
777
778/**
779 * Decrypt message
780 */
6be0a20b 781bool NXCPEncryptionContext::decryptMessage(NXCP_ENCRYPTED_MESSAGE *msg, BYTE *decryptionBuffer)
e6336a90
VK
782{
783#ifdef _WITH_ENCRYPTION
784 if (!EVP_DecryptInit_ex(&m_decryptor, NULL, NULL, m_sessionKey, m_iv))
785 return false;
786
b368969c 787 msg->size = ntohl(msg->size);
e6336a90
VK
788 int dataSize;
789 EVP_DecryptUpdate(&m_decryptor, decryptionBuffer, &dataSize, msg->data,
b368969c 790 msg->size - NXCP_EH_UNENCRYPTED_BYTES - msg->padding);
e6336a90
VK
791 EVP_DecryptFinal(&m_decryptor, decryptionBuffer + dataSize, &dataSize);
792
b368969c
VK
793 NXCP_MESSAGE *clearMsg = (NXCP_MESSAGE *)(decryptionBuffer + NXCP_EH_ENCRYPTED_BYTES);
794 UINT32 msgSize = ntohl(clearMsg->size);
795 if (msgSize > msg->size)
e6336a90
VK
796 return false; // Message decrypted incorrectly, because it can't be larger than encrypted
797 UINT32 crc32 = CalculateCRC32((BYTE *)clearMsg, msgSize, 0);
6be0a20b 798 if (crc32 != ntohl(((NXCP_ENCRYPTED_PAYLOAD_HEADER *)decryptionBuffer)->dwChecksum))
e6336a90
VK
799 return false; // Bad checksum
800
801 memcpy(msg, clearMsg, msgSize);
802 return true;
803#else /* _WITH_ENCRYPTION */
804 return false;
805#endif
806}
981d246a
VK
807
808/**
809 * Generate random bytes
810 */
811void LIBNETXMS_EXPORTABLE GenerateRandomBytes(BYTE *buffer, size_t size)
812{
813#ifdef _WITH_ENCRYPTION
814 RAND_bytes(buffer, (int)size);
815#else
816 srand((unsigned int)time(NULL));
817 for(size_t i = 0; i < size; i++)
818 buffer[i] = (BYTE)(rand() % 256);
819#endif
820}