-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
CryptoImpl.cpp
1427 lines (1205 loc) · 55.9 KB
/
CryptoImpl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/utils/crypto/bcrypt/CryptoImpl.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/utils/memory/AWSMemory.h>
#include <aws/core/utils/Outcome.h>
#include <aws/core/utils/crypto/Hash.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/utils/StringUtils.h>
#include <atomic>
#include <bcrypt.h>
#include <winternl.h>
#include <winerror.h>
#ifndef NT_SUCCESS
#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
#endif // NT_SUCCESS
using namespace Aws::Utils;
using namespace Aws::Utils::Crypto;
namespace Aws
{
namespace Utils
{
namespace Crypto
{
SecureRandomBytes_BCrypt::SecureRandomBytes_BCrypt()
{
NTSTATUS status = BCryptOpenAlgorithmProvider(&m_algHandle, BCRYPT_RNG_ALGORITHM, nullptr, 0);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_FATAL(SecureRandom_BCrypt_Tag, "Failed to initialize decryptor chaining mode with status code " << status);
}
}
SecureRandomBytes_BCrypt::~SecureRandomBytes_BCrypt()
{
if (m_algHandle)
{
BCryptCloseAlgorithmProvider(m_algHandle, 0);
}
}
void SecureRandomBytes_BCrypt::GetBytes(unsigned char* buffer, size_t bufferSize)
{
if (!m_algHandle)
{
AWS_LOGSTREAM_FATAL(SecureRandom_BCrypt_Tag, "Secure Random Bytes generator can't generate bytes with empty algorithm handle.");
m_failure = true;
assert(m_algHandle);
return;
}
if (!bufferSize)
{
return;
}
if (!buffer)
{
AWS_LOGSTREAM_FATAL(SecureRandom_BCrypt_Tag, "Secure Random Bytes generator can't generate: " << bufferSize << " bytes with nullptr buffer.");
assert(buffer);
return;
}
NTSTATUS status = BCryptGenRandom(m_algHandle, buffer, static_cast<ULONG>(bufferSize), 0);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_FATAL(SecureRandom_BCrypt_Tag, "Failed to generate random number with status " << status);
}
}
static const char* logTag = "CryptoHash";
// RAII class for one-use-per-hash-call data used in Windows cryptographic hash implementations
// Useful so we don't have to call a Cleanup function for every failure point
class BCryptHashContext
{
public:
BCryptHashContext(void* algorithmHandle, PBYTE hashObject, DWORD hashObjectLength) :
m_hashHandle(nullptr),
m_isValid(false)
{
NTSTATUS status = BCryptCreateHash(algorithmHandle, &m_hashHandle, hashObject, hashObjectLength, nullptr, 0, 0);
m_isValid = NT_SUCCESS(status);
}
BCryptHashContext(void* algorithmHandle, PBYTE hashObject, DWORD hashObjectLength, const ByteBuffer& secret) :
m_hashHandle(nullptr),
m_isValid(false)
{
NTSTATUS status = BCryptCreateHash(algorithmHandle, &m_hashHandle, hashObject, hashObjectLength, secret.GetUnderlyingData(), (ULONG)secret.GetLength(), 0);
m_isValid = NT_SUCCESS(status);
}
~BCryptHashContext()
{
if (m_hashHandle)
{
BCryptDestroyHash(m_hashHandle);
}
}
bool IsValid() const { return m_isValid; }
BCRYPT_HASH_HANDLE m_hashHandle;
bool m_isValid;
};
BCryptHashImpl::BCryptHashImpl(LPCWSTR algorithmName, bool isHMAC) :
m_algorithmHandle(nullptr),
m_hashHandle(nullptr),
m_hashBufferLength(0),
m_hashBuffer(nullptr),
m_hashObjectLength(0),
m_hashObject(nullptr),
m_algorithmMutex()
{
NTSTATUS status = BCryptOpenAlgorithmProvider(&m_algorithmHandle, algorithmName, MS_PRIMITIVE_PROVIDER, isHMAC ? BCRYPT_ALG_HANDLE_HMAC_FLAG : 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(logTag, "Failed initializing BCryptOpenAlgorithmProvider for " << Aws::Utils::StringUtils::FromWString(algorithmName));
return;
}
DWORD resultLength = 0;
status = BCryptGetProperty(m_algorithmHandle, BCRYPT_HASH_LENGTH, (PBYTE)&m_hashBufferLength, sizeof(m_hashBufferLength), &resultLength, 0);
if (!NT_SUCCESS(status) || m_hashBufferLength <= 0)
{
AWS_LOGSTREAM_ERROR(logTag, "Error computing hash buffer length.");
return;
}
m_hashBuffer = Aws::NewArray<BYTE>(m_hashBufferLength, logTag);
if (!m_hashBuffer)
{
AWS_LOGSTREAM_ERROR(logTag, "Error allocating hash buffer.");
return;
}
resultLength = 0;
status = BCryptGetProperty(m_algorithmHandle, BCRYPT_OBJECT_LENGTH, (PBYTE)&m_hashObjectLength, sizeof(m_hashObjectLength), &resultLength, 0);
if (!NT_SUCCESS(status) || m_hashObjectLength <= 0)
{
AWS_LOGSTREAM_ERROR(logTag, "Error computing hash object length.");
return;
}
m_hashObject = Aws::NewArray<BYTE>(m_hashObjectLength, logTag);
if (!m_hashObject)
{
AWS_LOGSTREAM_ERROR(logTag, "Error allocating hash object.");
return;
}
status = BCryptCreateHash(m_algorithmHandle, &m_hashHandle, m_hashObject, m_hashObjectLength, nullptr, 0, 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(logTag, "Error creating hash handle.");
if (m_hashHandle)
{
BCryptDestroyHash(m_hashHandle);
m_hashHandle = nullptr;
}
return;
}
}
BCryptHashImpl::~BCryptHashImpl()
{
Aws::DeleteArray(m_hashObject);
Aws::DeleteArray(m_hashBuffer);
if (m_algorithmHandle)
{
BCryptCloseAlgorithmProvider(m_algorithmHandle, 0);
}
}
HashResult BCryptHashImpl::HashData(const BCryptHashContext& context, PBYTE data, ULONG dataLength)
{
NTSTATUS status = BCryptHashData(context.m_hashHandle, data, dataLength, 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(logTag, "Error computing hash.");
return HashResult();
}
status = BCryptFinishHash(context.m_hashHandle, m_hashBuffer, m_hashBufferLength, 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(logTag, "Error obtaining computed hash");
return HashResult();
}
return HashResult(ByteBuffer(m_hashBuffer, m_hashBufferLength));
}
HashResult BCryptHashImpl::Calculate(const Aws::String& str)
{
if (!IsValid())
{
return HashResult();
}
std::lock_guard<std::mutex> locker(m_algorithmMutex);
BCryptHashContext context(m_algorithmHandle, m_hashObject, m_hashObjectLength);
if (!context.IsValid())
{
AWS_LOGSTREAM_ERROR(logTag, "Error creating hash handle.");
return HashResult();
}
return HashData(context, (PBYTE)str.c_str(), static_cast<ULONG>(str.length()));
}
HashResult BCryptHashImpl::Calculate(const ByteBuffer& toHash, const ByteBuffer& secret)
{
if (!IsValid())
{
return HashResult();
}
std::lock_guard<std::mutex> locker(m_algorithmMutex);
BCryptHashContext context(m_algorithmHandle, m_hashObject, m_hashObjectLength, secret);
if (!context.IsValid())
{
AWS_LOGSTREAM_ERROR(logTag, "Error creating hash handle.");
return HashResult();
}
return HashData(context, static_cast<PBYTE>(toHash.GetUnderlyingData()), static_cast<ULONG>(toHash.GetLength()));
}
void BCryptHashImpl::Update(unsigned char* buffer, size_t bufferSize)
{
if (!IsValid())
{
return;
}
std::lock_guard<std::mutex> locker(m_algorithmMutex);
NTSTATUS status = 0;
status = BCryptHashData(m_hashHandle, (PBYTE)buffer, (ULONG)bufferSize, 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(logTag, "Error computing hash:" << static_cast<int>(status));
if (m_hashHandle)
{
BCryptDestroyHash(m_hashHandle);
m_hashHandle = nullptr;
}
return;
}
}
HashResult BCryptHashImpl::GetHash()
{
if (!IsValid())
{
return HashResult();
}
std::lock_guard<std::mutex> locker(m_algorithmMutex);
NTSTATUS status = BCryptFinishHash(m_hashHandle, m_hashBuffer, m_hashBufferLength, 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(logTag, "Error obtaining computed hash");
if (m_hashHandle)
{
BCryptDestroyHash(m_hashHandle);
m_hashHandle = nullptr;
}
return HashResult();
}
return HashResult(ByteBuffer(m_hashBuffer, m_hashBufferLength));
}
bool BCryptHashImpl::IsValid() const
{
return m_hashBuffer != nullptr && m_hashBufferLength > 0 && m_hashObject != nullptr && m_hashObjectLength > 0 && m_hashHandle != nullptr;
}
bool BCryptHashImpl::HashStream(Aws::IStream& stream)
{
BCryptHashContext context(m_algorithmHandle, m_hashObject, m_hashObjectLength);
if (!context.IsValid())
{
AWS_LOGSTREAM_ERROR(logTag, "Error creating hash handle.");
return false;
}
char streamBuffer[Aws::Utils::Crypto::Hash::INTERNAL_HASH_STREAM_BUFFER_SIZE];
NTSTATUS status = 0;
stream.seekg(0, stream.beg);
while (stream.good())
{
stream.read(streamBuffer, Aws::Utils::Crypto::Hash::INTERNAL_HASH_STREAM_BUFFER_SIZE);
std::streamsize bytesRead = stream.gcount();
if (bytesRead > 0)
{
status = BCryptHashData(context.m_hashHandle, (PBYTE)streamBuffer, (ULONG)bytesRead, 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(logTag, "Error computing hash.");
return false;
}
}
}
if (!stream.eof())
{
return false;
}
status = BCryptFinishHash(context.m_hashHandle, m_hashBuffer, m_hashBufferLength, 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(logTag, "Error obtaining computed hash");
return false;
}
return true;
}
HashResult BCryptHashImpl::Calculate(Aws::IStream& stream)
{
if (!IsValid())
{
return HashResult();
}
std::lock_guard<std::mutex> locker(m_algorithmMutex);
auto startingPos = stream.tellg();
bool success = HashStream(stream);
if (success)
{
stream.clear();
}
stream.seekg(startingPos, stream.beg);
if (!success)
{
return HashResult();
}
return HashResult(ByteBuffer(m_hashBuffer, m_hashBufferLength));
}
MD5BcryptImpl::MD5BcryptImpl() :
m_impl(BCRYPT_MD5_ALGORITHM, false)
{
}
HashResult MD5BcryptImpl::Calculate(const Aws::String& str)
{
return m_impl.Calculate(str);
}
HashResult MD5BcryptImpl::Calculate(Aws::IStream& stream)
{
return m_impl.Calculate(stream);
}
void MD5BcryptImpl::Update(unsigned char* buffer, size_t bufferSize)
{
m_impl.Update(buffer, bufferSize);
}
HashResult MD5BcryptImpl::GetHash()
{
return m_impl.GetHash();
}
Sha1BcryptImpl::Sha1BcryptImpl() :
m_impl(BCRYPT_SHA1_ALGORITHM, false)
{
}
HashResult Sha1BcryptImpl::Calculate(const Aws::String& str)
{
return m_impl.Calculate(str);
}
HashResult Sha1BcryptImpl::Calculate(Aws::IStream& stream)
{
return m_impl.Calculate(stream);
}
void Sha1BcryptImpl::Update(unsigned char* buffer, size_t bufferSize)
{
m_impl.Update(buffer, bufferSize);
}
HashResult Sha1BcryptImpl::GetHash()
{
return m_impl.GetHash();
}
Sha256BcryptImpl::Sha256BcryptImpl() :
m_impl(BCRYPT_SHA256_ALGORITHM, false)
{
}
HashResult Sha256BcryptImpl::Calculate(const Aws::String& str)
{
return m_impl.Calculate(str);
}
HashResult Sha256BcryptImpl::Calculate(Aws::IStream& stream)
{
return m_impl.Calculate(stream);
}
void Sha256BcryptImpl::Update(unsigned char* buffer, size_t bufferSize)
{
m_impl.Update(buffer, bufferSize);
}
HashResult Sha256BcryptImpl::GetHash()
{
return m_impl.GetHash();
}
Sha256HMACBcryptImpl::Sha256HMACBcryptImpl() :
m_impl(BCRYPT_SHA256_ALGORITHM, true)
{
}
HashResult Sha256HMACBcryptImpl::Calculate(const ByteBuffer& toSign, const ByteBuffer& secret)
{
return m_impl.Calculate(toSign, secret);
}
static const char* SYM_CIPHER_TAG = "BCryptSymmetricCipherImpl";
BCryptSymmetricCipher::BCryptSymmetricCipher(const CryptoBuffer& key, size_t ivSizeBytes, bool ctrMode) :
SymmetricCipher(key, ivSizeBytes, ctrMode),
m_algHandle(nullptr), m_keyHandle(nullptr), m_authInfoPtr(nullptr)
{
Init();
}
BCryptSymmetricCipher::BCryptSymmetricCipher(BCryptSymmetricCipher&& toMove) : SymmetricCipher(std::move(toMove)),
m_authInfoPtr(nullptr)
{
m_algHandle = toMove.m_algHandle;
m_keyHandle = toMove.m_keyHandle;
toMove.m_algHandle = nullptr;
toMove.m_keyHandle = nullptr;
}
BCryptSymmetricCipher::BCryptSymmetricCipher(CryptoBuffer&& key, CryptoBuffer&& initializationVector, CryptoBuffer&& tag) :
SymmetricCipher(std::move(key), std::move(initializationVector), std::move(tag)),
m_algHandle(nullptr), m_keyHandle(nullptr), m_authInfoPtr(nullptr)
{
Init();
}
BCryptSymmetricCipher::BCryptSymmetricCipher(const CryptoBuffer& key, const CryptoBuffer& initializationVector,
const CryptoBuffer& tag) :
SymmetricCipher(key, initializationVector, tag),
m_algHandle(nullptr), m_keyHandle(nullptr), m_authInfoPtr(nullptr)
{
Init();
}
BCryptSymmetricCipher::~BCryptSymmetricCipher()
{
Cleanup();
}
void BCryptSymmetricCipher::Init()
{
m_workingIv = m_initializationVector;
m_encryptDecryptCalled = false;
}
BCRYPT_KEY_HANDLE BCryptSymmetricCipher::ImportKeyBlob(BCRYPT_ALG_HANDLE algHandle, CryptoBuffer& key)
{
NTSTATUS status = 0;
BCRYPT_KEY_DATA_BLOB_HEADER keyData;
keyData.dwMagic = BCRYPT_KEY_DATA_BLOB_MAGIC;
keyData.dwVersion = BCRYPT_KEY_DATA_BLOB_VERSION1;
keyData.cbKeyData = static_cast<ULONG>(key.GetLength());
CryptoBuffer pbInputBuffer(sizeof(keyData) + key.GetLength());
memcpy(pbInputBuffer.GetUnderlyingData(), &keyData, sizeof(keyData));
memcpy(pbInputBuffer.GetUnderlyingData() + sizeof(keyData), key.GetUnderlyingData(), key.GetLength());
BCRYPT_KEY_HANDLE keyHandle;
status = BCryptImportKey(algHandle, nullptr, BCRYPT_KEY_DATA_BLOB, &keyHandle, nullptr, 0, pbInputBuffer.GetUnderlyingData(), static_cast<ULONG>(pbInputBuffer.GetLength()), 0);
if (!NT_SUCCESS(status))
{
AWS_LOGSTREAM_ERROR(SYM_CIPHER_TAG, "Failed to set symmetric key with status code " << status);
return nullptr;
}
return keyHandle;
}
void BCryptSymmetricCipher::InitKey()
{
if (m_failure || !m_algHandle)
{
return;
}
m_keyHandle = ImportKeyBlob(m_algHandle, m_key);
if (!m_keyHandle)
{
m_failure = true;
return;
}
if(!m_authInfoPtr && m_initializationVector.GetLength() > 0)
{
NTSTATUS status = BCryptSetProperty(m_keyHandle, BCRYPT_INITIALIZATION_VECTOR, m_initializationVector.GetUnderlyingData(), static_cast<ULONG>(m_initializationVector.GetLength()), 0);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(SYM_CIPHER_TAG, "Failed to set symmetric key initialization vector with status code " << status);
return;
}
}
}
CryptoBuffer BCryptSymmetricCipher::EncryptBuffer(const CryptoBuffer& unEncryptedData)
{
if (m_failure)
{
AWS_LOGSTREAM_FATAL(SYM_CIPHER_TAG, "Cipher not properly initialized for encryption. Aborting");
return CryptoBuffer();
}
if (unEncryptedData.GetLength() == 0 && m_encryptDecryptCalled)
{
return CryptoBuffer();
}
size_t predictedWriteLengths = m_flags & BCRYPT_BLOCK_PADDING ? unEncryptedData.GetLength() + (GetBlockSizeBytes() - unEncryptedData.GetLength() % GetBlockSizeBytes())
: unEncryptedData.GetLength();
ULONG lengthWritten = static_cast<ULONG>(predictedWriteLengths);
CryptoBuffer encryptedText(static_cast<size_t>(predictedWriteLengths));
PUCHAR iv = nullptr;
ULONG ivSize = 0;
if (m_authInfoPtr)
{
iv = m_workingIv.GetUnderlyingData();
ivSize = static_cast<ULONG>(m_workingIv.GetLength());
}
//iv was set on the key itself, so we don't need to pass it here.
NTSTATUS status = BCryptEncrypt(m_keyHandle, unEncryptedData.GetUnderlyingData(), (ULONG)unEncryptedData.GetLength(),
m_authInfoPtr, iv, ivSize, encryptedText.GetUnderlyingData(), (ULONG)encryptedText.GetLength(), &lengthWritten, m_flags);
m_encryptDecryptCalled = true;
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(SYM_CIPHER_TAG, "Failed to compute encrypted output with error code " << status);
return CryptoBuffer();
}
if (static_cast<size_t>(lengthWritten) < encryptedText.GetLength())
{
return CryptoBuffer(encryptedText.GetUnderlyingData(), static_cast<size_t>(lengthWritten));
}
return encryptedText;
}
CryptoBuffer BCryptSymmetricCipher::FinalizeEncryption()
{
return CryptoBuffer();
}
CryptoBuffer BCryptSymmetricCipher::DecryptBuffer(const CryptoBuffer& encryptedData)
{
if (m_failure)
{
AWS_LOGSTREAM_FATAL(SYM_CIPHER_TAG, "Cipher not properly initialized for decryption. Aborting");
return CryptoBuffer();
}
if (encryptedData.GetLength() == 0 && m_encryptDecryptCalled)
{
return CryptoBuffer();
}
PUCHAR iv = nullptr;
ULONG ivSize = 0;
if (m_authInfoPtr)
{
iv = m_workingIv.GetUnderlyingData();
ivSize = static_cast<ULONG>(m_workingIv.GetLength());
}
size_t predictedWriteLengths = encryptedData.GetLength();
ULONG lengthWritten = static_cast<ULONG>(predictedWriteLengths);
CryptoBuffer decryptedText(static_cast<size_t>(predictedWriteLengths));
//iv was set on the key itself, so we don't need to pass it here.
NTSTATUS status = BCryptDecrypt(m_keyHandle, encryptedData.GetUnderlyingData(), (ULONG)encryptedData.GetLength(),
m_authInfoPtr, iv, ivSize, decryptedText.GetUnderlyingData(), (ULONG)decryptedText.GetLength(), &lengthWritten, m_flags);
m_encryptDecryptCalled = true;
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(SYM_CIPHER_TAG, "Failed to compute encrypted output with error code " << status);
return CryptoBuffer();
}
if (static_cast<size_t>(lengthWritten) < decryptedText.GetLength())
{
return CryptoBuffer(decryptedText.GetUnderlyingData(), static_cast<size_t>(lengthWritten));
}
return decryptedText;
}
CryptoBuffer BCryptSymmetricCipher::FinalizeDecryption()
{
return CryptoBuffer();
}
void BCryptSymmetricCipher::Reset()
{
Cleanup();
Init();
}
void BCryptSymmetricCipher::Cleanup()
{
if (m_keyHandle)
{
BCryptDestroyKey(m_keyHandle);
m_keyHandle = nullptr;
}
if (m_algHandle)
{
BCryptCloseAlgorithmProvider(m_algHandle, 0);
m_algHandle = nullptr;
}
m_flags = 0;
m_authInfoPtr = nullptr;
m_failure = false;
}
bool BCryptSymmetricCipher::CheckKeyAndIVLength(size_t expectedKeyLength, size_t expectedIVLength)
{
if (!m_failure && ((m_key.GetLength() != expectedKeyLength) || m_initializationVector.GetLength() != expectedIVLength))
{
AWS_LOGSTREAM_ERROR(SYM_CIPHER_TAG, "Expected Key size is: " << expectedKeyLength << " and expected IV size is: " << expectedIVLength);
m_failure = true;
}
return !m_failure;
}
size_t AES_CBC_Cipher_BCrypt::BlockSizeBytes = 16;
size_t AES_CBC_Cipher_BCrypt::KeyLengthBits = 256;
AES_CBC_Cipher_BCrypt::AES_CBC_Cipher_BCrypt(const CryptoBuffer& key) : BCryptSymmetricCipher(key, BlockSizeBytes)
{
InitCipher();
InitKey();
}
AES_CBC_Cipher_BCrypt::AES_CBC_Cipher_BCrypt(CryptoBuffer&& key, CryptoBuffer&& initializationVector) : BCryptSymmetricCipher(key, initializationVector)
{
InitCipher();
InitKey();
}
AES_CBC_Cipher_BCrypt::AES_CBC_Cipher_BCrypt(const CryptoBuffer& key, const CryptoBuffer& initializationVector) : BCryptSymmetricCipher(key, initializationVector)
{
InitCipher();
InitKey();
}
static const char* CBC_LOG_TAG = "BCrypt_AES_CBC_Cipher";
void AES_CBC_Cipher_BCrypt::InitCipher()
{
if (m_failure || !CheckKeyAndIVLength(KeyLengthBits/8, BlockSizeBytes))
{
return;
}
//due to odd BCrypt api behavior, we have to manually handle the padding, however we are producing padded output.
m_flags = 0;
NTSTATUS status = BCryptOpenAlgorithmProvider(&m_algHandle, BCRYPT_AES_ALGORITHM, nullptr, 0);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(CBC_LOG_TAG, "Failed to initialize encryptor/decryptor with status code " << status);
return;
}
status = BCryptSetProperty(m_algHandle, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_CBC, static_cast<ULONG>(wcslen(BCRYPT_CHAIN_MODE_CBC) + 1), 0);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(CBC_LOG_TAG, "Failed to initialize encryptor/decryptor chaining mode with status code " << status);
}
}
/**
* This is needlessly complicated due to the way BCrypt handles CBC mode. It assumes that you will only make one call to BCryptEncrypt and as a result
* appends the padding to the output of every call. The simplest way around this is to have an extra 32 byte block sitting around. During EncryptBuffer calls
* we don't use padding at all, we enforce that we only pass multiples of 32 bytes to BCryptEncrypt. Anything extra goes into either the next EncryptBuffer call
* or is handled in the Finalize call. On the very last call, we add the padding back. This is what the other Crypto APIs such as OpenSSL and CommonCrypto do under the hood anyways.
*/
CryptoBuffer AES_CBC_Cipher_BCrypt::FillInOverflow(const CryptoBuffer& buffer)
{
if (m_failure)
{
return CryptoBuffer();
}
static const size_t RESERVE_SIZE = BlockSizeBytes * 2;
m_flags = 0;
CryptoBuffer finalBuffer;
if (m_blockOverflow.GetLength() > 0)
{
finalBuffer = CryptoBuffer({ (ByteBuffer*)&m_blockOverflow, (ByteBuffer*)&buffer });
m_blockOverflow = CryptoBuffer();
}
else
{
finalBuffer = buffer;
}
auto overflow = finalBuffer.GetLength() % RESERVE_SIZE;
if (finalBuffer.GetLength() > RESERVE_SIZE)
{
auto offset = overflow == 0 ? RESERVE_SIZE : overflow;
m_blockOverflow = CryptoBuffer(finalBuffer.GetUnderlyingData() + finalBuffer.GetLength() - offset, offset);
finalBuffer = CryptoBuffer(finalBuffer.GetUnderlyingData(), finalBuffer.GetLength() - offset);
return finalBuffer;
}
else
{
m_blockOverflow = finalBuffer;
return CryptoBuffer();
}
}
CryptoBuffer AES_CBC_Cipher_BCrypt::EncryptBuffer(const CryptoBuffer& unEncryptedData)
{
return BCryptSymmetricCipher::EncryptBuffer(FillInOverflow(unEncryptedData));
}
/**
* If we had actual data that overflowed a block left over from the packing, then let BCrypt handle the padding.
* Otherwise, we have to manally encrypt the padding indicating that a full block is in the previous block.
*/
CryptoBuffer AES_CBC_Cipher_BCrypt::FinalizeEncryption()
{
if (!m_failure && m_blockOverflow.GetLength() > 0)
{
m_flags = BCRYPT_BLOCK_PADDING;
return BCryptSymmetricCipher::EncryptBuffer(m_blockOverflow);
}
return CryptoBuffer();
}
CryptoBuffer AES_CBC_Cipher_BCrypt::DecryptBuffer(const CryptoBuffer& encryptedData)
{
return BCryptSymmetricCipher::DecryptBuffer(FillInOverflow(encryptedData));
}
CryptoBuffer AES_CBC_Cipher_BCrypt::FinalizeDecryption()
{
if (!m_failure && m_blockOverflow.GetLength() > 0)
{
m_flags = BCRYPT_BLOCK_PADDING;
return BCryptSymmetricCipher::DecryptBuffer(m_blockOverflow);
}
return CryptoBuffer();
}
void AES_CBC_Cipher_BCrypt::Reset()
{
BCryptSymmetricCipher::Reset();
m_blockOverflow = CryptoBuffer();
InitCipher();
InitKey();
}
size_t AES_CBC_Cipher_BCrypt::GetBlockSizeBytes() const
{
return BlockSizeBytes;
}
size_t AES_CBC_Cipher_BCrypt::GetKeyLengthBits() const
{
return KeyLengthBits;
}
static const char* CTR_LOG_TAG = "BCrypt_AES_CTR_Cipher";
size_t AES_CTR_Cipher_BCrypt::BlockSizeBytes = 16;
size_t AES_CTR_Cipher_BCrypt::KeyLengthBits = 256;
AES_CTR_Cipher_BCrypt::AES_CTR_Cipher_BCrypt(const CryptoBuffer& key) : BCryptSymmetricCipher(key, BlockSizeBytes, true)
{
InitCipher();
InitKey();
}
AES_CTR_Cipher_BCrypt::AES_CTR_Cipher_BCrypt(CryptoBuffer&& key, CryptoBuffer&& initializationVector) : BCryptSymmetricCipher(key, initializationVector)
{
InitCipher();
InitKey();
}
AES_CTR_Cipher_BCrypt::AES_CTR_Cipher_BCrypt(const CryptoBuffer& key, const CryptoBuffer& initializationVector) : BCryptSymmetricCipher(key, initializationVector)
{
InitCipher();
InitKey();
}
CryptoBuffer AES_CTR_Cipher_BCrypt::EncryptBuffer(const CryptoBuffer& unEncryptedData)
{
if (m_failure)
{
AWS_LOGSTREAM_FATAL(CTR_LOG_TAG, "Cipher not properly initialized for encryption. Aborting");
return CryptoBuffer();
}
return EncryptWithCtr(unEncryptedData);
}
/**
* In case we didn't have an even 16 byte multiple for the message, send the last
* remaining data.
*/
CryptoBuffer AES_CTR_Cipher_BCrypt::FinalizeEncryption()
{
if (!m_failure && m_blockOverflow.GetLength())
{
CryptoBuffer const& returnBuffer = EncryptBuffer(m_blockOverflow);
m_blockOverflow = CryptoBuffer();
return returnBuffer;
}
return CryptoBuffer();
}
CryptoBuffer AES_CTR_Cipher_BCrypt::DecryptBuffer(const CryptoBuffer& encryptedData)
{
if (m_failure)
{
AWS_LOGSTREAM_FATAL(CTR_LOG_TAG, "Cipher not properly initialized for encryption. Aborting");
return CryptoBuffer();
}
//Encryption and decryption are identical in CTR mode.
return EncryptWithCtr(encryptedData);
}
/**
* In case we didn't have an even 16 byte multiple for the message, send the last
* remaining data.
*/
CryptoBuffer AES_CTR_Cipher_BCrypt::FinalizeDecryption()
{
if (!m_failure && m_blockOverflow.GetLength())
{
CryptoBuffer const& returnBuffer = DecryptBuffer(m_blockOverflow);
m_blockOverflow = CryptoBuffer();
return returnBuffer;
}
return CryptoBuffer();
}
void AES_CTR_Cipher_BCrypt::InitCipher()
{
if (m_failure || !CheckKeyAndIVLength(KeyLengthBits/8, BlockSizeBytes))
{
return;
}
m_flags = 0;
NTSTATUS status = BCryptOpenAlgorithmProvider(&m_algHandle, BCRYPT_AES_ALGORITHM, nullptr, 0);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(CTR_LOG_TAG, "Failed to initialize encryptor/decryptor with status code " << status);
}
status = BCryptSetProperty(m_algHandle, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_ECB, static_cast<ULONG>(wcslen(BCRYPT_CHAIN_MODE_ECB) + 1), 0);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(CTR_LOG_TAG, "Failed to initialize encryptor/decryptor chaining mode with status code " << status);
}
}
/**
* Windows doesn't expose CTR mode. We can however, build it manually from ECB. Here, split each
* buffer into 16 byte chunks, for each complete buffer encrypt the counter and xor it against the unencrypted
* text. Save anything left over for the next run.
*/
CryptoBuffer AES_CTR_Cipher_BCrypt::EncryptWithCtr(const CryptoBuffer& buffer)
{
if (m_failure)
{
return CryptoBuffer();
}
size_t bytesWritten = 0;
Aws::Vector<ByteBuffer*> finalBufferSet(0);
CryptoBuffer bufferToEncrypt;
if (m_blockOverflow.GetLength() > 0 && &m_blockOverflow != &buffer)
{
bufferToEncrypt = CryptoBuffer({ (ByteBuffer*)&m_blockOverflow, (ByteBuffer*)&buffer });
m_blockOverflow = CryptoBuffer();
}
else
{
bufferToEncrypt = buffer;
}
Aws::Utils::Array<CryptoBuffer> slicedBuffers;
if (bufferToEncrypt.GetLength() > BlockSizeBytes)
{
slicedBuffers = bufferToEncrypt.Slice(BlockSizeBytes);
}
else
{
slicedBuffers = Aws::Utils::Array<CryptoBuffer>(1u);
slicedBuffers[0] = bufferToEncrypt;
}
finalBufferSet = Aws::Vector<ByteBuffer*>(slicedBuffers.GetLength());
InitBuffersToNull(finalBufferSet);
for (size_t i = 0; i < slicedBuffers.GetLength(); ++i)
{
if (slicedBuffers[i].GetLength() == BlockSizeBytes || (m_blockOverflow.GetLength() > 0 && slicedBuffers.GetLength() == 1))
{
ULONG lengthWritten = static_cast<ULONG>(BlockSizeBytes);
CryptoBuffer encryptedText(BlockSizeBytes);
NTSTATUS status = BCryptEncrypt(m_keyHandle, m_workingIv.GetUnderlyingData(), (ULONG)m_workingIv.GetLength(),
nullptr, nullptr, 0, encryptedText.GetUnderlyingData(), (ULONG)encryptedText.GetLength(), &lengthWritten, m_flags);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(CTR_LOG_TAG, "Failed to compute encrypted output with error code " << status);
CleanupBuffers(finalBufferSet);
return CryptoBuffer();
}
CryptoBuffer* newBuffer = Aws::New<CryptoBuffer>(CTR_LOG_TAG, BlockSizeBytes);
*newBuffer = slicedBuffers[i] ^ encryptedText;
finalBufferSet[i] = newBuffer;
m_workingIv = IncrementCTRCounter(m_workingIv, 1);
bytesWritten += static_cast<size_t>(lengthWritten);
}
else
{
m_blockOverflow = slicedBuffers[i];
CryptoBuffer* newBuffer = Aws::New<CryptoBuffer>(CTR_LOG_TAG, 0);
finalBufferSet[i] = newBuffer;
}
}
CryptoBuffer returnBuffer(std::move(finalBufferSet));
CleanupBuffers(finalBufferSet);
return returnBuffer;