-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt_cng.c
1434 lines (1313 loc) · 41.7 KB
/
encrypt_cng.c
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
/*
* UFTP - UDP based FTP with multicast
*
* Copyright (C) 2001-2015 Dennis A. Bush, Jr. [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the copyright holder
* grants you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
//#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Use this #define to pull in necessary declarations from uftp_common.h
// in encryption.h instead. We don't include uftp_common.h because it contains
// an include for winsock2.h which is needed pretty much everyplace else.
// Including winsock2.h prevents BCryptEncrypt and BCryptDecrypt from working
// with GCM and CCM mode ciphers.
#define NO_UFTP_COMMON_H
#include "uftp.h"
#include "encryption.h"
#define MAXLIST 100
#define BLOBLEN 1000
static struct providers_t {
LPCWSTR alg;
LPCWSTR mode;
int hmac;
BCRYPT_ALG_HANDLE handle;
} providers[MAXLIST];
static int provlen;
static const struct keyinfo_t {
int keytype;
int keysize;
int blocksize;
} keyinfo[] = {
{ KEY_DES, 8, 8 },
{ KEY_DES_EDE3, 24, 8 },
{ KEY_AES128_CBC, 16, 16 },
{ KEY_AES128_GCM, 16, 12 },
{ KEY_AES128_CCM, 16, 12 },
{ KEY_AES256_CBC, 32, 16 },
{ KEY_AES256_GCM, 32, 12 },
{ KEY_AES256_CCM, 32, 12 }
};
static int machine_keyset = 0;
static int init_done = 0;
/**
* Prints Microsoft specific error messages to log
*/
static void mserror(const char *str, int err)
{
char errbuf[300];
HMODULE Hand = LoadLibrary("NTDLL.DLL");
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_IGNORE_INSERTS, Hand, err,
0, errbuf, sizeof(errbuf), NULL);
clog0(0, 0, 0, "%s: (0x%08X) %s", str, err, errbuf);
FreeLibrary(Hand);
}
/**
* Performs all necessary steps to initialize the crypto library
*/
void crypto_init(int set_sys_key)
{
provlen = 0;
if (set_sys_key) {
machine_keyset = NCRYPT_MACHINE_KEY_FLAG;
} else {
machine_keyset = 0;
}
init_done = 1;
}
/**
* Performs all necessary steps to clean up the crypto library
*/
void crypto_cleanup(void)
{
NTSTATUS status;
int i;
if (!init_done) {
return;
}
for (i = 0; i < provlen; i++) {
status = BCryptCloseAlgorithmProvider(providers[i].handle, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptCloseAlgorithmProvider failed", status);
}
}
}
/**
* Returns the next key for the current user
*/
const char *get_next_container(void)
{
static NCRYPT_PROV_HANDLE prov = 0;
static NCryptKeyName *keyitem = NULL;
static void *ptr = NULL;
static char name[256];
SECURITY_STATUS sstatus;
if (!prov) {
sstatus = NCryptOpenStorageProvider(&prov, NULL, 0);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptOpenStorageProvider failed", sstatus);
return NULL;
}
}
if (keyitem) {
NCryptFreeBuffer(keyitem);
}
sstatus = NCryptEnumKeys(prov, NULL, &keyitem, &ptr,
NCRYPT_SILENT_FLAG | machine_keyset);
if (sstatus == ERROR_SUCCESS) {
wcstombs(name, keyitem->pszName, sizeof(name));
return name;
} else {
if (sstatus != NTE_NO_MORE_ITEMS) {
mserror("NCryptEnumKeys failed", sstatus);
}
NCryptFreeBuffer(keyitem);
keyitem = NULL;
NCryptFreeBuffer(ptr);
ptr = NULL;
NCryptFreeObject(prov);
prov = 0;
return NULL;
}
}
/**
* Deletes the key container with the given name
*/
void delete_container(const char *container)
{
NCRYPT_PROV_HANDLE prov;
NCRYPT_KEY_HANDLE key;
SECURITY_STATUS sstatus;
wchar_t wcontainer[256];
if (!BCRYPT_SUCCESS(sstatus = NCryptOpenStorageProvider(&prov, NULL, 0))) {
mserror("NCryptOpenStorageProvider failed", sstatus);
}
memset(wcontainer, 0, sizeof(wcontainer));
mbstowcs(wcontainer, container, strlen(container));
sstatus = NCryptOpenKey(prov, &key, wcontainer, 0,
NCRYPT_SILENT_FLAG | machine_keyset);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptOpenKey failed", sstatus);
NCryptFreeObject(prov);
}
if (!BCRYPT_SUCCESS(sstatus = NCryptDeleteKey(key, NCRYPT_SILENT_FLAG))) {
NCryptFreeObject(prov);
mserror("NCryptDeleteKey failed", sstatus);
}
NCryptFreeObject(prov);
}
/**
* Gets an algorithm provider handle for the given hash or cipher.
* Check the provider list to see if it exists. If so, return it,
* otherwise get a new one and put it in the list.
*/
static BCRYPT_ALG_HANDLE get_alg_handle(LPCWSTR alg, LPCWSTR mode, int hmac)
{
BCRYPT_ALG_HANDLE handle;
NTSTATUS status;
int i;
for (i=0; i<provlen; i++) {
if ((providers[i].alg == alg) && (providers[i].mode == mode) &&
(providers[i].hmac == hmac)) {
return providers[i].handle;
}
}
status = BCryptOpenAlgorithmProvider(&handle, alg, NULL,
hmac ? BCRYPT_ALG_HANDLE_HMAC_FLAG : 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptOpenAlgorithmProvider failed", status);
return NULL;
}
providers[provlen].alg = alg;
providers[provlen].mode = mode;
providers[provlen].hmac = hmac;
providers[provlen].handle = handle;
provlen++;
return handle;
}
/**
* Returns the cipher name associated with the given keytype
*/
static LPCWSTR get_cipher(int keytype)
{
switch (keytype) {
case KEY_DES:
return BCRYPT_DES_ALGORITHM;
case KEY_DES_EDE3:
return BCRYPT_3DES_ALGORITHM;
case KEY_AES128_CBC:
case KEY_AES256_CBC:
case KEY_AES128_GCM:
case KEY_AES256_GCM:
case KEY_AES128_CCM:
case KEY_AES256_CCM:
return BCRYPT_AES_ALGORITHM;
default:
log0(0, 0, 0, "Unknown keytype: %d", keytype);
return NULL;
}
}
/**
* Returns the cipher mode associated with the given keytype
*/
static LPCWSTR get_cipher_mode(int keytype)
{
switch (keytype) {
case KEY_DES:
case KEY_DES_EDE3:
case KEY_AES128_CBC:
case KEY_AES256_CBC:
return BCRYPT_CHAIN_MODE_CBC;
case KEY_AES128_GCM:
case KEY_AES256_GCM:
return BCRYPT_CHAIN_MODE_GCM;
case KEY_AES128_CCM:
case KEY_AES256_CCM:
return BCRYPT_CHAIN_MODE_CCM;
default:
return NULL;
}
}
/**
* Returns the hash name associated with a given hashtype
*/
static LPCWSTR get_hash(int hashtype)
{
switch (hashtype) {
case HASH_SHA512:
return BCRYPT_SHA512_ALGORITHM;
case HASH_SHA384:
return BCRYPT_SHA384_ALGORITHM;
case HASH_SHA256:
return BCRYPT_SHA256_ALGORITHM;
case HASH_SHA1:
return BCRYPT_SHA1_ALGORITHM;
case HASH_MD5:
return BCRYPT_MD5_ALGORITHM;
default:
log0(0, 0, 0, "Unknown hashtype: %d", hashtype);
return NULL;
}
}
static LPCWSTR get_curve_alg(int curve, int isdh)
{
if (isdh) {
switch (curve) {
case CURVE_prime256v1:
return BCRYPT_ECDH_P256_ALGORITHM;
case CURVE_secp384r1:
return BCRYPT_ECDH_P384_ALGORITHM;
case CURVE_secp521r1:
return BCRYPT_ECDH_P521_ALGORITHM;
default:
return NULL;
}
} else {
switch (curve) {
case CURVE_prime256v1:
return BCRYPT_ECDSA_P256_ALGORITHM;
case CURVE_secp384r1:
return BCRYPT_ECDSA_P384_ALGORITHM;
case CURVE_secp521r1:
return BCRYPT_ECDSA_P521_ALGORITHM;
default:
return NULL;
}
}
}
static ULONG get_curve_magic(int curve, int isdh)
{
if (isdh) {
switch (curve) {
case CURVE_prime256v1:
return BCRYPT_ECDH_PUBLIC_P256_MAGIC;
case CURVE_secp384r1:
return BCRYPT_ECDH_PUBLIC_P384_MAGIC;
case CURVE_secp521r1:
return BCRYPT_ECDH_PUBLIC_P521_MAGIC;
default:
return 0;
}
} else {
switch (curve) {
case CURVE_prime256v1:
return BCRYPT_ECDSA_PUBLIC_P256_MAGIC;
case CURVE_secp384r1:
return BCRYPT_ECDSA_PUBLIC_P384_MAGIC;
case CURVE_secp521r1:
return BCRYPT_ECDSA_PUBLIC_P521_MAGIC;
default:
return 0;
}
}
}
/**
* Returns whether a particular algorithm of a given type is available
*/
static int alg_found(LPCWSTR alg, int type)
{
NTSTATUS status;
BCRYPT_ALGORITHM_IDENTIFIER *balglist;
int count, found, i;
status = BCryptEnumAlgorithms(type, &count, &balglist, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptEnumAlgorithms failed", status);
return 0;
}
for (found = 0, i = 0; i < count; i++) {
if (!wcscmp(alg, balglist[i].pszName)) {
found = 1;
break;
}
}
BCryptFreeBuffer(balglist);
return found;
}
/**
* Returns whether a particular cipher is supported
*/
int cipher_supported(int keytype)
{
LPCWSTR alg;
if ((alg = get_cipher(keytype)) == NULL) {
return 0;
}
return alg_found(alg, BCRYPT_CIPHER_OPERATION);
}
/**
* Returns whether a particular hash is supported
*/
int hash_supported(int hashtype)
{
LPCWSTR alg;
if ((alg = get_hash(hashtype)) == NULL) {
return 0;
}
return alg_found(alg, BCRYPT_HASH_OPERATION);
}
/**
* Gets the key length and IV/block length of a given key
*/
void get_key_info(int keytype, int *keylen, int *ivlen)
{
int numkeys, i;
numkeys = sizeof(keyinfo) / sizeof(struct keyinfo_t);
for (i = 0; i < numkeys; i++) {
if (keytype == keyinfo[i].keytype) {
*keylen = keyinfo[i].keysize;
*ivlen = keyinfo[i].blocksize;
return;
}
}
*keylen = 0;
*ivlen = 0;
}
/**
* Gets the length of the given hash
*/
int get_hash_len(int hashtype)
{
BCRYPT_ALG_HANDLE alg;
NTSTATUS status;
DWORD hashlen, len;
alg = get_alg_handle(get_hash(hashtype), NULL, 0);
if (!alg) {
return 0;
}
status = BCryptGetProperty(alg, BCRYPT_HASH_LENGTH, (PUCHAR)&hashlen,
sizeof(DWORD), &len, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptGetProperty failed", status);
return 0;
}
return hashlen;
}
/**
* Gets num cryptographically random bytes
*/
int get_random_bytes(unsigned char *buf, int num)
{
BCRYPT_ALG_HANDLE alg;
NTSTATUS status;
alg = get_alg_handle(BCRYPT_RNG_ALGORITHM, NULL, 0);
if (!alg) {
return 0;
}
status = BCryptGenRandom(alg, buf, num, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptGenRandom failed", status);
return 0;
}
return 1;
}
/**
* Takes a block of data and encrypts it with a symmetric cypher.
* For authenticated cipher modes, also takes additional authentication data.
* The output buffer must be at least the size of source data + block size.
*/
int encrypt_block(int keytype, const unsigned char *IV,
const unsigned char *key,
const unsigned char *aad, unsigned int aadlen,
const unsigned char *src, unsigned int srclen,
unsigned char *dest, unsigned int *destlen)
{
BCRYPT_ALG_HANDLE alghandle = NULL;
BCRYPT_KEY_HANDLE keyhandle = NULL;
LPCWSTR alg, mode;
NTSTATUS status;
BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authinfo, *pauthinfo;
unsigned char *l_IV, *p_IV;
int keylen, ivlen, taglen, flags, l_ivlen;
alg = get_cipher(keytype);
get_key_info(keytype, &keylen, &ivlen);
mode = get_cipher_mode(keytype);
if ((alghandle = get_alg_handle(alg, mode, 0)) == NULL) {
log0(0, 0, 0, "get_alg_handle failed\n");
return 0;
}
status = BCryptSetProperty(alghandle, BCRYPT_CHAINING_MODE, (PUCHAR)mode,
sizeof(mode), 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptSetProperty failed", status);
return 0;
}
status = BCryptGenerateSymmetricKey(alghandle, &keyhandle, NULL, 0,
(PUCHAR)key, keylen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptGenerateSymmetricKey failed", status);
return 0;
}
l_IV = safe_calloc(ivlen, 1);
memcpy(l_IV, IV, ivlen);
taglen = is_gcm_mode(keytype) ? GCM_TAG_LEN :
is_ccm_mode(keytype) ? CCM_TAG_LEN : 0;
if (is_auth_enc(keytype)) {
BCRYPT_INIT_AUTH_MODE_INFO(authinfo);
authinfo.pbNonce = l_IV;
authinfo.cbNonce = ivlen;
authinfo.pbAuthData = (unsigned char *)aad;
authinfo.cbAuthData = aadlen;
authinfo.pbTag = dest + srclen;
authinfo.cbTag = taglen;
authinfo.pbMacContext = NULL;
authinfo.cbMacContext = 0;
authinfo.cbAAD = 0;
authinfo.cbData = 0;
authinfo.dwFlags = 0;
pauthinfo = &authinfo;
flags = 0;
p_IV = NULL;
l_ivlen = 0;
} else {
pauthinfo = NULL;
flags = BCRYPT_BLOCK_PADDING;
p_IV = l_IV;
l_ivlen = ivlen;
}
status = BCryptEncrypt(keyhandle, (PUCHAR)src, srclen, pauthinfo,
p_IV, l_ivlen, dest, srclen + GCM_TAG_LEN, destlen, flags);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptEncrypt failed", status);
free(l_IV);
return 0;
}
free(l_IV);
*destlen += taglen;
if (!BCRYPT_SUCCESS(status = BCryptDestroyKey(keyhandle))) {
mserror("BCryptDestroyKey failed", status);
}
return 1;
}
/**
* Takes a block of data encrypted with a symmetric cypher and decrypts it.
* For authenticated cipher modes, also takes additional authentication data.
* The output buffer must be at least the size of source data.
*/
int decrypt_block(int keytype, const unsigned char *IV,
const unsigned char *key,
const unsigned char *aad, unsigned int aadlen,
unsigned char *src, unsigned int srclen,
unsigned char *dest, unsigned int *destlen)
{
BCRYPT_ALG_HANDLE alghandle = NULL;
BCRYPT_KEY_HANDLE keyhandle = NULL;
LPCWSTR alg, mode;
NTSTATUS status;
BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authinfo, *pauthinfo;
unsigned char *l_IV, *p_IV;
int keylen, ivlen, taglen, flags, l_ivlen;
alg = get_cipher(keytype);
get_key_info(keytype, &keylen, &ivlen);
mode = get_cipher_mode(keytype);
if ((alghandle = get_alg_handle(alg, mode, 0)) == NULL) {
log0(0, 0, 0, "get_alg_handle failed\n");
return 0;
}
status = BCryptSetProperty(alghandle, BCRYPT_CHAINING_MODE, (PUCHAR)mode,
sizeof(mode), 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptSetProperty failed", status);
return 0;
}
status = BCryptGenerateSymmetricKey(alghandle, &keyhandle, NULL, 0,
(PUCHAR)key, keylen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptGenerateSymmetricKey failed", status);
return 0;
}
l_IV = safe_calloc(ivlen, 1);
memcpy(l_IV, IV, ivlen);
taglen = is_gcm_mode(keytype) ? GCM_TAG_LEN :
is_ccm_mode(keytype) ? CCM_TAG_LEN : 0;
if (is_auth_enc(keytype)) {
BCRYPT_INIT_AUTH_MODE_INFO(authinfo);
authinfo.pbNonce = l_IV;
authinfo.cbNonce = ivlen;
authinfo.pbAuthData = (unsigned char *)aad;
authinfo.cbAuthData = aadlen;
authinfo.pbTag = (unsigned char *)src + srclen - taglen;
authinfo.cbTag = taglen;
authinfo.pbMacContext = NULL;
authinfo.cbMacContext = 0;
authinfo.cbAAD = 0;
authinfo.cbData = 0;
authinfo.dwFlags = 0;
pauthinfo = &authinfo;
flags = 0;
p_IV = NULL;
l_ivlen = 0;
} else {
pauthinfo = NULL;
flags = BCRYPT_BLOCK_PADDING;
p_IV = l_IV;
l_ivlen = ivlen;
}
status = BCryptDecrypt(keyhandle, (PUCHAR)src, srclen - taglen, pauthinfo,
p_IV, l_ivlen, dest, srclen + GCM_TAG_LEN, destlen, flags);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptDecrypt failed", status);
free(l_IV);
return 0;
}
free(l_IV);
if (!BCRYPT_SUCCESS(status = BCryptDestroyKey(keyhandle))) {
mserror("BCryptDestroyKey failed", status);
}
return 1;
}
/**
* Calculates the HMAC of the given message, hashtype, and hashkey.
* dest must be at least the hash length.
*/
int create_hmac(int hashtype, const unsigned char *key, unsigned int keylen,
const unsigned char *src, unsigned int srclen,
unsigned char *dest, unsigned int *destlen)
{
BCRYPT_ALG_HANDLE alghandle = NULL;
BCRYPT_HASH_HANDLE hashhandle = NULL;
LPCWSTR alg;
NTSTATUS status;
DWORD _destlen, rlen;
alg = get_hash(hashtype);
if ((alghandle = get_alg_handle(alg, NULL, 1)) == NULL) {
log0(0, 0, 0, "get_alg_handle failed\n");
return 0;
}
status = BCryptGetProperty(alghandle, BCRYPT_HASH_LENGTH,
(char *)&_destlen, sizeof(destlen), &rlen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptGetProperty failed", status);
return 0;
}
status = BCryptCreateHash(alghandle, &hashhandle, NULL, 0,
(char *)key, keylen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptCreateHash failed", status);
return 0;
}
status = BCryptHashData(hashhandle, (PUCHAR)src, srclen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptHashData failed", status);
return 0;
}
status = BCryptFinishHash(hashhandle, dest, _destlen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptFinishHash failed", status);
return 0;
}
*destlen = _destlen;
if (!BCRYPT_SUCCESS(status = BCryptDestroyHash(hashhandle))) {
mserror("BCryptDestroyHash failed", status);
}
return 1;
}
/**
* Calculates the hash of the given message and hashtype
*/
int hash(int hashtype, const unsigned char *src, unsigned int srclen,
unsigned char *dest, unsigned int *destlen)
{
BCRYPT_ALG_HANDLE alghandle = NULL;
BCRYPT_HASH_HANDLE hashhandle = NULL;
LPCWSTR alg;
NTSTATUS status;
DWORD _destlen, rlen;
alg = get_hash(hashtype);
if ((alghandle = get_alg_handle(alg, NULL, 0)) == NULL) {
log0(0, 0, 0, "get_alg_handle failed\n");
return 0;
}
status = BCryptGetProperty(alghandle, BCRYPT_HASH_LENGTH,
(char *)&_destlen, sizeof(destlen), &rlen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptGetProperty failed", status);
return 0;
}
status = BCryptCreateHash(alghandle, &hashhandle, NULL, 0, NULL, 0, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptCreateHash failed", status);
return 0;
}
status = BCryptHashData(hashhandle, (PUCHAR)src, srclen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptHashData failed", status);
return 0;
}
status = BCryptFinishHash(hashhandle, dest, _destlen, 0);
if (!BCRYPT_SUCCESS(status)) {
mserror("BCryptFinishHash failed", status);
return 0;
}
*destlen = _destlen;
if (!BCRYPT_SUCCESS(status = BCryptDestroyHash(hashhandle))) {
mserror("BCryptDestroyHash failed", status);
}
return 1;
}
/**
* Returns the length in bytes of the modulus for the given RSA key
*/
int RSA_keylen(const RSA_key_t rsa)
{
int bits, len;
SECURITY_STATUS sstatus;
sstatus = NCryptGetProperty(rsa, NCRYPT_LENGTH_PROPERTY, (PBYTE)&bits,
sizeof(bits), &len, NCRYPT_SILENT_FLAG);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptGetProperty failed", sstatus);
return 0;
}
return bits / 8;
}
/**
* Returns the length of an exported EC public key
* An exported key is built as follows:
* uint8_t xpoint[ceil(curve_bitlen/8)]
* uint8_t ypoint[ceil(curve_bitlen/8)]
* uint8_t padding[]
*/
int EC_keylen(const EC_key_t ec)
{
SECURITY_STATUS sstatus;
int len, padding;
sstatus = NCryptExportKey(ec, (NCRYPT_KEY_HANDLE)NULL,
BCRYPT_ECCPUBLIC_BLOB, NULL, NULL, 0, &len, NCRYPT_SILENT_FLAG);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptExportKey failed", sstatus);
return 0;
}
len -= sizeof(BCRYPT_ECCKEY_BLOB);
if ((len % 4) == 0) {
padding = 0;
} else {
padding = 4 - (len % 4);
}
return len + padding;
}
/**
* Returns the length in bytes of a signature created by the given ECDSA key
* ECDSA signatures consist of:
* uint16_t rlen
* uint16_t slen
* uint8_t rsig[ceil(curve_bitlen/8)]
* uint8_t ssig[ceil(curve_bitlen/8)]
* uint8_t padding[]
*/
int ECDSA_siglen(const EC_key_t ec)
{
return sizeof(uint16_t) + sizeof(uint16_t) + EC_keylen(ec);
}
/**
* Encrypts a small block of data with an RSA public key.
* Output buffer must be at least the key size.
*/
int RSA_encrypt(RSA_key_t rsa, const unsigned char *from, unsigned int fromlen,
unsigned char *to, unsigned int *tolen)
{
SECURITY_STATUS sstatus;
BCRYPT_OAEP_PADDING_INFO pad, *ppad;
int keylen, _tolen, flags;
keylen = RSA_keylen(rsa);
if (keylen * 8 < 768) {
flags = NCRYPT_PAD_PKCS1_FLAG;
ppad = NULL;
} else {
flags = NCRYPT_PAD_OAEP_FLAG;
ppad = &pad;
pad.pszAlgId = BCRYPT_SHA1_ALGORITHM;
pad.pbLabel = NULL;
pad.cbLabel = 0;
}
_tolen = keylen * ((fromlen / keylen) + 1);
sstatus = NCryptEncrypt(rsa, (PUCHAR)from, fromlen, ppad, to, _tolen,
&_tolen, flags);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptEncrypt failed", sstatus);
return 0;
}
*tolen = _tolen;
return 1;
}
/**
* Decrypts a small block of data with an RSA private key.
*/
int RSA_decrypt(RSA_key_t rsa, const unsigned char *from, unsigned int fromlen,
unsigned char *to, unsigned int *tolen)
{
SECURITY_STATUS sstatus;
BCRYPT_OAEP_PADDING_INFO pad, *ppad;
int _tolen, flags;
if (RSA_keylen(rsa) * 8 < 768) {
flags = NCRYPT_PAD_PKCS1_FLAG;
ppad = NULL;
} else {
flags = NCRYPT_PAD_OAEP_FLAG;
ppad = &pad;
pad.pszAlgId = BCRYPT_SHA1_ALGORITHM;
pad.pbLabel = NULL;
pad.cbLabel = 0;
}
_tolen = fromlen;
sstatus = NCryptDecrypt(rsa, (PUCHAR)from, fromlen, ppad, to, _tolen,
&_tolen, flags);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptDecrypt failed", sstatus);
return 0;
}
*tolen = _tolen;
return 1;
}
/**
* Hashes a block of data and signs it with an RSA private key.
* Output buffer must be at least the key size.
*/
int create_RSA_sig(RSA_key_t rsa, int hashtype,
const unsigned char *mes, unsigned int meslen,
unsigned char *sig, unsigned int *siglen)
{
SECURITY_STATUS sstatus;
unsigned char meshash[HMAC_LEN];
unsigned int meshashlen, _siglen;
BCRYPT_PKCS1_PADDING_INFO padding;
if (!hash(hashtype, mes, meslen, meshash, &meshashlen)) {
return 0;
}
padding.pszAlgId = get_hash(hashtype);
_siglen = RSA_keylen(rsa);
sstatus = NCryptSignHash(rsa, &padding, meshash, meshashlen, sig, _siglen,
&_siglen, BCRYPT_PAD_PKCS1);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptSignHash failed", sstatus);
return 0;
}
*siglen = _siglen;
return 1;
}
/**
* Hashes a block of data and verifies it against an RSA signature.
*/
int verify_RSA_sig(RSA_key_t rsa, int hashtype,
const unsigned char *mes, unsigned int meslen,
unsigned char *sig, unsigned int siglen)
{
SECURITY_STATUS sstatus;
unsigned char meshash[HMAC_LEN];
unsigned int meshashlen;
BCRYPT_PKCS1_PADDING_INFO padding;
if (!hash(hashtype, mes, meslen, meshash, &meshashlen)) {
return 0;
}
padding.pszAlgId = get_hash(hashtype);
sstatus = NCryptVerifySignature(rsa, &padding, meshash, meshashlen, sig,
siglen, BCRYPT_PAD_PKCS1);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptVerifySignature failed", sstatus);
return 0;
}
return 1;
}
/**
* Hashes a block of data and signs it with an ECDSA private key.
* Output buffer must be at least ECDSA_siglen bytes.
*/
int create_ECDSA_sig(EC_key_t ec, int hashtype,
const unsigned char *mes, unsigned int meslen,
unsigned char *sig, unsigned int *siglen)
{
SECURITY_STATUS sstatus;
unsigned char meshash[HMAC_LEN], *buf;
unsigned int meshashlen, _siglen;
uint16_t *rlen, *slen;
unsigned char *rsval;
if (!hash(hashtype, mes, meslen, meshash, &meshashlen)) {
return 0;
}
sstatus = NCryptSignHash(ec, NULL, meshash, meshashlen, NULL, 0,
&_siglen, 0);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptSignHash failed", sstatus);
return 0;
}
buf = safe_malloc(_siglen);
sstatus = NCryptSignHash(ec, NULL, meshash, meshashlen, buf, _siglen,
&_siglen, 0);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptSignHash failed", sstatus);
free(buf);
return 0;
}
rlen = (uint16_t *)sig;
slen = (uint16_t *)(sig + sizeof(uint16_t));
rsval = (unsigned char *)slen + sizeof(uint16_t);
*siglen = ECDSA_siglen(ec);
memset(sig, 0, *siglen);
*rlen = htons((uint16_t)_siglen / 2);
*slen = htons((uint16_t)_siglen / 2);
memcpy(rsval, buf, _siglen);
free(buf);
return 1;
}
/**
* Hashes a block of data and verifies it against an ECDSA signature.
*/
int verify_ECDSA_sig(EC_key_t ec, int hashtype,
const unsigned char *mes, unsigned int meslen,
const unsigned char *sig, unsigned int siglen)
{
SECURITY_STATUS sstatus;
unsigned char meshash[HMAC_LEN];
unsigned int meshashlen;
uint16_t *rlen, *slen;
unsigned char *rsval;
if (!hash(hashtype, mes, meslen, meshash, &meshashlen)) {
return 0;
}
rlen = (uint16_t *)sig;
slen = (uint16_t *)(sig + sizeof(uint16_t));
rsval = (unsigned char *)slen + sizeof(uint16_t);
if ((unsigned int)ntohs(*rlen) + ntohs(*slen) > siglen) {
log0(0, 0, 0, "Invalid signature length");
return 0;
}
sstatus = NCryptVerifySignature(ec, NULL, meshash, meshashlen, rsval,
ntohs(*rlen) + ntohs(*slen), 0);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptVerifySignature failed", sstatus);
return 0;
}
return 1;
}
/**
* Creates an ECDH key based on two EC keys, one public and one private
*/
int get_ECDH_key(EC_key_t pubkey, EC_key_t privkey, unsigned char *key,
unsigned int *keylen)
{
SECURITY_STATUS sstatus;
NCRYPT_SECRET_HANDLE secret;
int _len;
sstatus = NCryptSecretAgreement(privkey, pubkey, &secret, 0);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptSecretAgreement failed", sstatus);
return 0;
}
sstatus = NCryptDeriveKey(secret, BCRYPT_KDF_HASH, NULL, NULL, 0, &_len, 0);
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptDeriveKey failed", sstatus);
return 0;
}
sstatus = NCryptDeriveKey(secret, BCRYPT_KDF_HASH, NULL, key, _len,
keylen, 0 );
if (!BCRYPT_SUCCESS(sstatus)) {
mserror("NCryptDeriveKey failed", sstatus);
return 0;
}
return 1;
}