-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathsecurity.cpp
2768 lines (2389 loc) · 89.3 KB
/
security.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 (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
//=--------------------------------------------------------------------------=
// security.cpp by Stanley Man-Kit Ho
//=--------------------------------------------------------------------------=
//
#include <jni.h>
#include "jni_util.h"
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <BaseTsd.h>
#include <wincrypt.h>
#include <stdio.h>
#include <memory>
#include "sun_security_mscapi_CKey.h"
#include "sun_security_mscapi_CKeyStore.h"
#include "sun_security_mscapi_PRNG.h"
#include "sun_security_mscapi_CRSACipher.h"
#include "sun_security_mscapi_CKeyPairGenerator_RSA.h"
#include "sun_security_mscapi_CPublicKey.h"
#include "sun_security_mscapi_CPublicKey_CRSAPublicKey.h"
#include "sun_security_mscapi_CSignature.h"
#include "sun_security_mscapi_CSignature_RSA.h"
#define OID_EKU_ANY "2.5.29.37.0"
#define CERTIFICATE_PARSING_EXCEPTION \
"java/security/cert/CertificateParsingException"
#define INVALID_KEY_EXCEPTION \
"java/security/InvalidKeyException"
#define KEY_EXCEPTION "java/security/KeyException"
#define KEYSTORE_EXCEPTION "java/security/KeyStoreException"
#define PROVIDER_EXCEPTION "java/security/ProviderException"
#define SIGNATURE_EXCEPTION "java/security/SignatureException"
#define OUT_OF_MEMORY_ERROR "java/lang/OutOfMemoryError"
#define KEYSTORE_LOCATION_CURRENTUSER 0
#define KEYSTORE_LOCATION_LOCALMACHINE 1
#define SS_CHECK(Status) \
if (Status != ERROR_SUCCESS) { \
ThrowException(env, SIGNATURE_EXCEPTION, Status); \
__leave; \
}
#define PP(fmt, ...) \
if (trace) { \
fprintf(stdout, "MSCAPI (%ld): ", __LINE__); \
fprintf(stdout, fmt, ##__VA_ARGS__); \
fprintf(stdout, "\n"); \
fflush(stdout); \
}
extern "C" {
char* trace = getenv("CAPI_TRACE");
/*
* Declare library specific JNI_Onload entry if static build
*/
DEF_STATIC_JNI_OnLoad
void showProperty(NCRYPT_HANDLE hKey);
void dump(LPCSTR title, PBYTE data, DWORD len)
{
if (trace) {
printf("==== %s ====\n", title);
for (DWORD i = 0; i < len; i+=16) {
printf("%04x: ", i);
for (int j = 0; j < 16; j++) {
if (j == 8) {
printf(" ");
}
if (i + j < len) {
printf("%02X ", *(data + i + j) & 0xff);
} else {
printf(" ");
}
}
for (int j = 0; j < 16; j++) {
if (i + j < len) {
int k = *(data + i + j) & 0xff;
if (k < 32 || k > 127) printf(".");
else printf("%c", (char)k);
}
}
printf("\n");
}
fflush(stdout);
}
}
/*
* Throws an arbitrary Java exception with the given message.
*/
void ThrowExceptionWithMessage(JNIEnv *env, const char *exceptionName,
const char *szMessage)
{
jclass exceptionClazz = env->FindClass(exceptionName);
if (exceptionClazz != NULL) {
env->ThrowNew(exceptionClazz, szMessage);
}
}
void ThrowExceptionWithMessageAndErrcode(JNIEnv *env, const char *exceptionName,
const char *msg, DWORD dwError) {
char szMessage[500];
szMessage[0] = '\0';
char szMessage2[1024];
szMessage2[0] = '\0';
DWORD res = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,
NULL, szMessage, sizeof(szMessage), NULL);
if (res == 0) {
strcpy(szMessage, "Unknown error");
}
snprintf(szMessage2, sizeof(szMessage2), "%s: error %lu, %s", msg, dwError, szMessage);
ThrowExceptionWithMessage(env, exceptionName, szMessage2);
}
/*
* Throws an arbitrary Java exception.
* The exception message is a Windows system error message.
*/
void ThrowException(JNIEnv *env, const char *exceptionName, DWORD dwError)
{
char szMessage[500];
szMessage[0] = '\0';
char szMessage2[1024];
szMessage2[0] = '\0';
DWORD res = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,
NULL, szMessage, sizeof(szMessage), NULL);
if (res == 0) {
strcpy(szMessage, "Unknown error");
}
snprintf(szMessage2, sizeof(szMessage2), "error %lu, %s", dwError, szMessage);
ThrowExceptionWithMessage(env, exceptionName, szMessage2);
}
/*
* Overloaded 'operator new[]' variant, which will raise Java's
* OutOfMemoryError in the case of a failure.
*/
void* operator new[](std::size_t size, JNIEnv *env)
{
void* buf = ::operator new[](size, std::nothrow);
if (buf == NULL) {
ThrowExceptionWithMessage(env, OUT_OF_MEMORY_ERROR,
"Native memory allocation failed");
}
return buf;
}
/*
* Maps the name of a hash algorithm to an algorithm identifier.
*/
ALG_ID MapHashAlgorithm(JNIEnv *env, jstring jHashAlgorithm) {
const char* pszHashAlgorithm = NULL;
ALG_ID algId = 0;
if ((pszHashAlgorithm = env->GetStringUTFChars(jHashAlgorithm, NULL))
== NULL) {
return algId;
}
if ((strcmp("SHA", pszHashAlgorithm) == 0) ||
(strcmp("SHA1", pszHashAlgorithm) == 0) ||
(strcmp("SHA-1", pszHashAlgorithm) == 0)) {
algId = CALG_SHA1;
} else if (strcmp("SHA1+MD5", pszHashAlgorithm) == 0) {
algId = CALG_SSL3_SHAMD5; // a 36-byte concatenation of SHA-1 and MD5
} else if (strcmp("SHA-256", pszHashAlgorithm) == 0) {
algId = CALG_SHA_256;
} else if (strcmp("SHA-384", pszHashAlgorithm) == 0) {
algId = CALG_SHA_384;
} else if (strcmp("SHA-512", pszHashAlgorithm) == 0) {
algId = CALG_SHA_512;
} else if (strcmp("MD5", pszHashAlgorithm) == 0) {
algId = CALG_MD5;
} else if (strcmp("MD2", pszHashAlgorithm) == 0) {
algId = CALG_MD2;
}
if (pszHashAlgorithm)
env->ReleaseStringUTFChars(jHashAlgorithm, pszHashAlgorithm);
return algId;
}
/*
* Maps the name of a hash algorithm to a CNG Algorithm Identifier.
*/
LPCWSTR MapHashIdentifier(JNIEnv *env, jstring jHashAlgorithm) {
const char* pszHashAlgorithm = NULL;
LPCWSTR id = NULL;
if ((pszHashAlgorithm = env->GetStringUTFChars(jHashAlgorithm, NULL))
== NULL) {
return id;
}
if ((strcmp("SHA", pszHashAlgorithm) == 0) ||
(strcmp("SHA1", pszHashAlgorithm) == 0) ||
(strcmp("SHA-1", pszHashAlgorithm) == 0)) {
id = BCRYPT_SHA1_ALGORITHM;
} else if (strcmp("SHA-256", pszHashAlgorithm) == 0) {
id = BCRYPT_SHA256_ALGORITHM;
} else if (strcmp("SHA-384", pszHashAlgorithm) == 0) {
id = BCRYPT_SHA384_ALGORITHM;
} else if (strcmp("SHA-512", pszHashAlgorithm) == 0) {
id = BCRYPT_SHA512_ALGORITHM;
}
if (pszHashAlgorithm)
env->ReleaseStringUTFChars(jHashAlgorithm, pszHashAlgorithm);
return id;
}
/*
* Returns a certificate chain context given a certificate context and key
* usage identifier.
*/
bool GetCertificateChain(LPSTR lpszKeyUsageIdentifier, PCCERT_CONTEXT pCertContext, PCCERT_CHAIN_CONTEXT* ppChainContext)
{
CERT_ENHKEY_USAGE EnhkeyUsage;
CERT_USAGE_MATCH CertUsage;
CERT_CHAIN_PARA ChainPara;
DWORD dwFlags = 0;
LPSTR szUsageIdentifierArray[1];
szUsageIdentifierArray[0] = lpszKeyUsageIdentifier;
EnhkeyUsage.cUsageIdentifier = 1;
EnhkeyUsage.rgpszUsageIdentifier = szUsageIdentifierArray;
CertUsage.dwType = USAGE_MATCH_TYPE_AND;
CertUsage.Usage = EnhkeyUsage;
ChainPara.cbSize = sizeof(CERT_CHAIN_PARA);
ChainPara.RequestedUsage=CertUsage;
// Build a chain using CertGetCertificateChain
// and the certificate retrieved.
return (::CertGetCertificateChain(NULL, // use the default chain engine
pCertContext, // pointer to the end certificate
NULL, // use the default time
NULL, // search no additional stores
&ChainPara, // use AND logic and enhanced key usage
// as indicated in the ChainPara
// data structure
dwFlags,
NULL, // currently reserved
ppChainContext) == TRUE); // return a pointer to the chain created
}
/////////////////////////////////////////////////////////////////////////////
//
/*
* Class: sun_security_mscapi_PRNG
* Method: getContext
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_sun_security_mscapi_PRNG_getContext
(JNIEnv *env, jclass clazz) {
HCRYPTPROV hCryptProv = NULL;
if(::CryptAcquireContext( //deprecated
&hCryptProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT) == FALSE)
{
ThrowException(env, PROVIDER_EXCEPTION, GetLastError());
}
return hCryptProv;
}
/*
* Class: sun_security_mscapi_PRNG
* Method: releaseContext
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_sun_security_mscapi_PRNG_releaseContext
(JNIEnv *env, jclass clazz, jlong ctxt) {
if (ctxt) {
::CryptReleaseContext((HCRYPTPROV)ctxt, 0); //deprecated
}
}
/*
* Class: sun_security_mscapi_PRNG
* Method: generateSeed
* Signature: (JI[B)[B
*/
JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_PRNG_generateSeed
(JNIEnv *env, jclass clazz, jlong ctxt, jint length, jbyteArray seed)
{
HCRYPTPROV hCryptProv = (HCRYPTPROV)ctxt;
jbyte* reseedBytes = NULL;
jbyte* seedBytes = NULL;
jbyteArray result = NULL;
__try
{
/*
* If length is negative then use the supplied seed to re-seed the
* generator and return null.
* If length is non-zero then generate a new seed according to the
* requested length and return the new seed.
* If length is zero then overwrite the supplied seed with a new
* seed of the same length and return the seed.
*/
if (length < 0) {
length = env->GetArrayLength(seed);
if ((reseedBytes = env->GetByteArrayElements(seed, 0)) == NULL) {
__leave;
}
if (::CryptGenRandom( //deprecated
hCryptProv,
length,
(BYTE *) reseedBytes) == FALSE) {
ThrowException(env, PROVIDER_EXCEPTION, GetLastError());
__leave;
}
result = NULL;
} else {
if (length > 0) {
seed = env->NewByteArray(length);
if (seed == NULL) {
__leave;
}
} else {
length = env->GetArrayLength(seed);
}
if ((seedBytes = env->GetByteArrayElements(seed, 0)) == NULL) {
__leave;
}
if (::CryptGenRandom( //deprecated
hCryptProv,
length,
(BYTE *) seedBytes) == FALSE) {
ThrowException(env, PROVIDER_EXCEPTION, GetLastError());
__leave;
}
result = seed; // seed will be updated when seedBytes gets released
}
}
__finally
{
//--------------------------------------------------------------------
// Clean up.
if (reseedBytes)
env->ReleaseByteArrayElements(seed, reseedBytes, JNI_ABORT);
if (seedBytes)
env->ReleaseByteArrayElements(seed, seedBytes, 0); // update orig
}
return result;
}
/*
* Class: sun_security_mscapi_CKeyStore
* Method: loadKeysOrCertificateChains
* Signature: (Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_sun_security_mscapi_CKeyStore_loadKeysOrCertificateChains
(JNIEnv *env, jobject obj, jstring jCertStoreName, jint jCertStoreLocation)
{
/**
* Certificate in cert store has enhanced key usage extension
* property (or EKU property) that is not part of the certificate itself. To determine
* if the certificate should be returned, both the enhanced key usage in certificate
* extension block and the extension property stored along with the certificate in
* certificate store should be examined. Otherwise, we won't be able to determine
* the proper key usage from the Java side because the information is not stored as
* part of the encoded certificate.
*/
const char* pszCertStoreName = NULL;
HCERTSTORE hCertStore = NULL;
PCCERT_CONTEXT pCertContext = NULL;
wchar_t* pszNameString = NULL; // certificate's friendly name
DWORD cchNameString = 0;
__try
{
// Open a system certificate store.
if ((pszCertStoreName = env->GetStringUTFChars(jCertStoreName, NULL))
== NULL) {
__leave;
}
if (jCertStoreLocation == KEYSTORE_LOCATION_CURRENTUSER) {
hCertStore = ::CertOpenSystemStore(NULL, pszCertStoreName);
}
else if (jCertStoreLocation == KEYSTORE_LOCATION_LOCALMACHINE) {
hCertStore = ::CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, NULL,
CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_MAXIMUM_ALLOWED_FLAG, pszCertStoreName);
}
else {
PP("jCertStoreLocation is not a valid value");
__leave;
}
if (hCertStore == NULL) {
ThrowException(env, KEYSTORE_EXCEPTION, GetLastError());
__leave;
}
// Determine clazz and method ID to generate certificate
jclass clazzArrayList = env->FindClass("java/util/ArrayList");
if (clazzArrayList == NULL) {
__leave;
}
jmethodID mNewArrayList = env->GetMethodID(clazzArrayList, "<init>", "()V");
if (mNewArrayList == NULL) {
__leave;
}
jclass clazzOfThis = env->GetObjectClass(obj);
if (clazzOfThis == NULL) {
__leave;
}
jmethodID mGenCert = env->GetMethodID(clazzOfThis,
"generateCertificate",
"([BLjava/util/Collection;)V");
if (mGenCert == NULL) {
__leave;
}
// Determine method ID to generate certificate chain
jmethodID mGenCertChain = env->GetMethodID(clazzOfThis,
"generateCertificateChain",
"(Ljava/lang/String;Ljava/util/Collection;)V");
if (mGenCertChain == NULL) {
__leave;
}
// Determine method ID to generate RSA certificate chain
jmethodID mGenKeyAndCertChain = env->GetMethodID(clazzOfThis,
"generateKeyAndCertificateChain",
"(ZLjava/lang/String;JJILjava/util/Collection;)V");
if (mGenKeyAndCertChain == NULL) {
__leave;
}
// Use CertEnumCertificatesInStore to get the certificates
// from the open store. pCertContext must be reset to
// NULL to retrieve the first certificate in the store.
while (pCertContext = ::CertEnumCertificatesInStore(hCertStore, pCertContext))
{
PP("--------------------------");
// Check if private key available - client authentication certificate
// must have private key available.
HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv = NULL;
DWORD dwKeySpec = 0;
HCRYPTKEY hUserKey = NULL;
BOOL bCallerFreeProv = FALSE;
BOOL bHasNoPrivateKey = FALSE;
DWORD dwPublicKeyLength = 0;
// First, probe it silently
if (::CryptAcquireCertificatePrivateKey(pCertContext,
CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG | CRYPT_ACQUIRE_SILENT_FLAG, NULL,
&hCryptProv, &dwKeySpec, &bCallerFreeProv) == FALSE
&& GetLastError() != NTE_SILENT_CONTEXT)
{
PP("bHasNoPrivateKey = TRUE!");
bHasNoPrivateKey = TRUE;
}
else
{
if (bCallerFreeProv == TRUE) {
if ((dwKeySpec & CERT_NCRYPT_KEY_SPEC) == CERT_NCRYPT_KEY_SPEC) {
NCryptFreeObject(hCryptProv);
} else {
::CryptReleaseContext(hCryptProv, NULL); // deprecated
}
bCallerFreeProv = FALSE;
}
// Second, acquire the key normally (not silently)
if (::CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG, NULL,
&hCryptProv, &dwKeySpec, &bCallerFreeProv) == FALSE)
{
PP("bHasNoPrivateKey = TRUE!!");
bHasNoPrivateKey = TRUE;
}
else
{
if ((dwKeySpec & CERT_NCRYPT_KEY_SPEC) == CERT_NCRYPT_KEY_SPEC) {
PP("CNG %I64d", (__int64)hCryptProv);
} else {
// Private key is available
BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey); //deprecated
// Skip certificate if cannot find private key
if (bGetUserKey == FALSE) {
if (bCallerFreeProv)
::CryptReleaseContext(hCryptProv, NULL); // deprecated
continue;
}
// Set cipher mode to ECB
DWORD dwCipherMode = CRYPT_MODE_ECB;
::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL); //deprecated
PP("CAPI %I64d %I64d", (__int64)hCryptProv, (__int64)hUserKey);
}
// If the private key is present in smart card, we may not be able to
// determine the key length by using the private key handle. However,
// since public/private key pairs must have the same length, we could
// determine the key length of the private key by using the public key
// in the certificate.
dwPublicKeyLength = ::CertGetPublicKeyLength(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
&(pCertContext->pCertInfo->SubjectPublicKeyInfo));
}
}
PCCERT_CHAIN_CONTEXT pCertChainContext = NULL;
// Build certificate chain by using system certificate store.
// Add cert chain into collection for any key usage.
//
if (GetCertificateChain((LPSTR)OID_EKU_ANY, pCertContext, &pCertChainContext))
{
for (DWORD i = 0; i < pCertChainContext->cChain; i++)
{
// Found cert chain
PCERT_SIMPLE_CHAIN rgpChain =
pCertChainContext->rgpChain[i];
// Create ArrayList to store certs in each chain
jobject jArrayList =
env->NewObject(clazzArrayList, mNewArrayList);
if (jArrayList == NULL) {
__leave;
}
// Cleanup the previous allocated name
if (pszNameString) {
delete [] pszNameString;
pszNameString = NULL;
}
for (unsigned int j=0; j < rgpChain->cElement; j++)
{
PCERT_CHAIN_ELEMENT rgpElement =
rgpChain->rgpElement[j];
PCCERT_CONTEXT pc = rgpElement->pCertContext;
// Retrieve the friendly name of the first certificate
// in the chain
if (j == 0) {
// If the cert's name cannot be retrieved then
// pszNameString remains set to NULL.
// (An alias name will be generated automatically
// when storing this cert in the keystore.)
// Get length of friendly name
if ((cchNameString = CertGetNameStringW(pc,
CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL,
NULL, 0)) > 1) {
// Found friendly name
pszNameString = new (env) wchar_t[cchNameString];
if (pszNameString == NULL) {
__leave;
}
CertGetNameStringW(pc,
CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, NULL,
pszNameString, cchNameString);
}
}
BYTE* pbCertEncoded = pc->pbCertEncoded;
DWORD cbCertEncoded = pc->cbCertEncoded;
// Allocate and populate byte array
jbyteArray byteArray = env->NewByteArray(cbCertEncoded);
if (byteArray == NULL) {
__leave;
}
env->SetByteArrayRegion(byteArray, 0, cbCertEncoded,
(jbyte*) pbCertEncoded);
// Generate certificate from byte array and store into
// cert collection
env->CallVoidMethod(obj, mGenCert, byteArray, jArrayList);
JNU_CHECK_EXCEPTION(env);
}
// Usually pszNameString should be non-NULL. It's either
// the friendly name or an element from the subject name
// or SAN.
if (pszNameString)
{
PP("%S: %s", pszNameString, pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
jsize nameLen = (jsize)wcslen(pszNameString);
if (bHasNoPrivateKey)
{
// Generate certificate chain and store into cert chain
// collection
jstring name = env->NewString(pszNameString, nameLen);
if (name == NULL) {
__leave;
}
env->CallVoidMethod(obj, mGenCertChain,
name,
jArrayList);
JNU_CHECK_EXCEPTION(env);
}
else
{
if (hUserKey) {
// Only accept RSA for CAPI
DWORD dwData = CALG_RSA_KEYX;
DWORD dwSize = sizeof(DWORD);
::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData, //deprecated
&dwSize, NULL);
if ((dwData & ALG_TYPE_RSA) == ALG_TYPE_RSA)
{
// Generate RSA certificate chain and store into cert
// chain collection
jstring name = env->NewString(pszNameString, nameLen);
if (name == NULL) {
__leave;
}
env->CallVoidMethod(obj, mGenKeyAndCertChain,
1,
name,
(jlong) hCryptProv, (jlong) hUserKey,
dwPublicKeyLength, jArrayList);
JNU_CHECK_EXCEPTION(env);
}
} else {
// Only accept EC for CNG
BYTE buffer[32];
DWORD len = 0;
if (::NCryptGetProperty(
hCryptProv, NCRYPT_ALGORITHM_PROPERTY,
(PBYTE)buffer, 32, &len, NCRYPT_SILENT_FLAG) == ERROR_SUCCESS) {
jstring name = env->NewString(pszNameString, nameLen);
if (name == NULL) {
__leave;
}
if (buffer[0] == 'E' && buffer[2] == 'C'
&& (dwPublicKeyLength == 256
|| dwPublicKeyLength == 384
|| dwPublicKeyLength == 521)) {
env->CallVoidMethod(obj, mGenKeyAndCertChain,
0,
name,
(jlong) hCryptProv, (jlong) 0,
dwPublicKeyLength, jArrayList);
JNU_CHECK_EXCEPTION(env);
} else if (buffer[0] == 'R' && buffer[2] == 'S'
&& buffer[4] == 'A') {
env->CallVoidMethod(obj, mGenKeyAndCertChain,
1,
name,
(jlong) hCryptProv, (jlong) 0,
dwPublicKeyLength, jArrayList);
JNU_CHECK_EXCEPTION(env);
} else {
dump("Unknown NCRYPT_ALGORITHM_PROPERTY", buffer, len);
}
}
}
}
}
}
// Free cert chain
if (pCertChainContext)
::CertFreeCertificateChain(pCertChainContext);
} else {
PP("GetCertificateChain failed %d", GetLastError());
}
}
}
__finally
{
if (hCertStore)
::CertCloseStore(hCertStore, 0);
if (pszCertStoreName)
env->ReleaseStringUTFChars(jCertStoreName, pszCertStoreName);
if (pszNameString)
delete [] pszNameString;
}
}
/*
* Class: sun_security_mscapi_CKey
* Method: cleanUp
* Signature: (JJ)V
*/
JNIEXPORT void JNICALL Java_sun_security_mscapi_CKey_cleanUp
(JNIEnv *env, jclass clazz, jlong hCryptProv, jlong hCryptKey)
{
if (hCryptKey == NULL && hCryptProv != NULL) {
NCryptFreeObject((NCRYPT_HANDLE)hCryptProv);
} else {
if (hCryptKey != NULL)
::CryptDestroyKey((HCRYPTKEY) hCryptKey); // deprecated
if (hCryptProv != NULL)
::CryptReleaseContext((HCRYPTPROV) hCryptProv, NULL); // deprecated
}
}
/*
* Class: sun_security_mscapi_CSignature
* Method: signHash
* Signature: (Z[BILjava/lang/String;JJ)[B
*/
JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signHash
(JNIEnv *env, jclass clazz, jboolean noHashOID, jbyteArray jHash,
jint jHashSize, jstring jHashAlgorithm, jlong hCryptProv,
jlong hCryptKey)
{
HCRYPTHASH hHash = NULL;
jbyte* pHashBuffer = NULL;
jbyte* pSignedHashBuffer = NULL;
jbyteArray jSignedHash = NULL;
HCRYPTPROV hCryptProvAlt = NULL;
__try
{
// Map hash algorithm
ALG_ID algId = MapHashAlgorithm(env, jHashAlgorithm);
// Acquire a hash object handle.
if (::CryptCreateHash(HCRYPTPROV(hCryptProv), algId, 0, 0, &hHash) == FALSE) //deprecated
{
// Failover to using the PROV_RSA_AES CSP
DWORD cbData = 256;
BYTE pbData[256];
pbData[0] = '\0';
// Get name of the key container
::CryptGetProvParam((HCRYPTPROV)hCryptProv, PP_CONTAINER, //deprecated
(BYTE *)pbData, &cbData, 0);
DWORD keysetType = 0;
DWORD keysetTypeLen = sizeof(keysetType);
::CryptGetProvParam((HCRYPTPROV)hCryptProv, PP_KEYSET_TYPE, //deprecated
(BYTE*)&keysetType, &keysetTypeLen, 0);
// Acquire an alternative CSP handle
if (::CryptAcquireContext(&hCryptProvAlt, LPCSTR(pbData), NULL, //deprecated
PROV_RSA_AES, 0 | keysetType) == FALSE)
{
ThrowException(env, SIGNATURE_EXCEPTION, GetLastError());
__leave;
}
// Acquire a hash object handle.
if (::CryptCreateHash(HCRYPTPROV(hCryptProvAlt), algId, 0, 0, //deprecated
&hHash) == FALSE)
{
ThrowException(env, SIGNATURE_EXCEPTION, GetLastError());
__leave;
}
}
// Copy hash from Java to native buffer
pHashBuffer = new (env) jbyte[jHashSize];
if (pHashBuffer == NULL) {
__leave;
}
env->GetByteArrayRegion(jHash, 0, jHashSize, pHashBuffer);
// Set hash value in the hash object
if (::CryptSetHashParam(hHash, HP_HASHVAL, (BYTE*)pHashBuffer, NULL) == FALSE) //deprecated
{
ThrowException(env, SIGNATURE_EXCEPTION, GetLastError());
__leave;
}
// Determine key spec.
DWORD dwKeySpec = AT_SIGNATURE;
ALG_ID dwAlgId;
DWORD dwAlgIdLen = sizeof(ALG_ID);
if (! ::CryptGetKeyParam((HCRYPTKEY) hCryptKey, KP_ALGID, (BYTE*)&dwAlgId, &dwAlgIdLen, 0)) { //deprecated
ThrowException(env, SIGNATURE_EXCEPTION, GetLastError());
__leave;
}
if (CALG_RSA_KEYX == dwAlgId) {
dwKeySpec = AT_KEYEXCHANGE;
}
// Determine size of buffer
DWORD dwBufLen = 0;
DWORD dwFlags = 0;
if (noHashOID == JNI_TRUE) {
dwFlags = CRYPT_NOHASHOID; // omit hash OID in NONEwithRSA signature
}
if (::CryptSignHash(hHash, dwKeySpec, NULL, dwFlags, NULL, &dwBufLen) == FALSE) //deprecated
{
ThrowException(env, SIGNATURE_EXCEPTION, GetLastError());
__leave;
}
pSignedHashBuffer = new (env) jbyte[dwBufLen];
if (pSignedHashBuffer == NULL) {
__leave;
}
if (::CryptSignHash(hHash, dwKeySpec, NULL, dwFlags, (BYTE*)pSignedHashBuffer, &dwBufLen) == FALSE) //deprecated
{
ThrowException(env, SIGNATURE_EXCEPTION, GetLastError());
__leave;
}
// Create new byte array
jbyteArray temp = env->NewByteArray(dwBufLen);
if (temp == NULL) {
__leave;
}
// Copy data from native buffer
env->SetByteArrayRegion(temp, 0, dwBufLen, pSignedHashBuffer);
jSignedHash = temp;
}
__finally
{
if (pSignedHashBuffer)
delete [] pSignedHashBuffer;
if (pHashBuffer)
delete [] pHashBuffer;
if (hHash)
::CryptDestroyHash(hHash); //deprecated
if (hCryptProvAlt)
::CryptReleaseContext(hCryptProvAlt, 0); // deprecated
}
return jSignedHash;
}
/*
* Class: sun_security_mscapi_CSignature
* Method: signCngHash
* Signature: (I[BIILjava/lang/String;JJ)[B
*/
JNIEXPORT jbyteArray JNICALL Java_sun_security_mscapi_CSignature_signCngHash
(JNIEnv *env, jclass clazz, jint type, jbyteArray jHash,
jint jHashSize, jint saltLen, jstring jHashAlgorithm, jlong hCryptProv,
jlong hCryptKey)
{
jbyteArray jSignedHash = NULL;
jbyte* pHashBuffer = NULL;
jbyte* pSignedHashBuffer = NULL;
NCRYPT_KEY_HANDLE hk = NULL;
__try
{
if (hCryptKey == 0) {
hk = (NCRYPT_KEY_HANDLE)hCryptProv;
} else {
SS_CHECK(::NCryptTranslateHandle(
NULL,
&hk,
(HCRYPTPROV)hCryptProv,
(HCRYPTKEY)hCryptKey,
NULL,
0));
}
// Copy hash from Java to native buffer
pHashBuffer = new (env) jbyte[jHashSize];
if (pHashBuffer == NULL) {
__leave;
}
env->GetByteArrayRegion(jHash, 0, jHashSize, pHashBuffer);
BCRYPT_PKCS1_PADDING_INFO pkcs1Info;
BCRYPT_PSS_PADDING_INFO pssInfo;
VOID* param;
DWORD dwFlags;
switch (type) {
case 0:
param = NULL;
dwFlags = 0;
break;
case 1:
if (jHashAlgorithm) {
pkcs1Info.pszAlgId = MapHashIdentifier(env, jHashAlgorithm);
if (pkcs1Info.pszAlgId == NULL) {
ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION,
"Unrecognised hash algorithm");
__leave;
}
} else {
pkcs1Info.pszAlgId = NULL;
}
param = &pkcs1Info;
dwFlags = BCRYPT_PAD_PKCS1;
break;
case 2:
pssInfo.pszAlgId = MapHashIdentifier(env, jHashAlgorithm);
pssInfo.cbSalt = saltLen;
if (pssInfo.pszAlgId == NULL) {
ThrowExceptionWithMessage(env, SIGNATURE_EXCEPTION,
"Unrecognised hash algorithm");
__leave;
}
param = &pssInfo;
dwFlags = BCRYPT_PAD_PSS;
break;
}
DWORD jSignedHashSize = 0;
SS_CHECK(::NCryptSignHash(
hk,
param,
(BYTE*)pHashBuffer, jHashSize,
NULL, 0, &jSignedHashSize,
dwFlags
));
pSignedHashBuffer = new (env) jbyte[jSignedHashSize];
if (pSignedHashBuffer == NULL) {
__leave;
}
SS_CHECK(::NCryptSignHash(
hk,
param,
(BYTE*)pHashBuffer, jHashSize,
(BYTE*)pSignedHashBuffer, jSignedHashSize, &jSignedHashSize,
dwFlags
));
// Create new byte array