forked from dotnet/corefx
-
Notifications
You must be signed in to change notification settings - Fork 7
/
PkcsPalWindows.cs
362 lines (309 loc) · 14.7 KB
/
PkcsPalWindows.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal.Windows
{
internal sealed partial class PkcsPalWindows : PkcsPal
{
internal PkcsPalWindows()
{
}
public sealed override DecryptorPal Decode(byte[] encodedMessage, out int version, out ContentInfo contentInfo, out AlgorithmIdentifier contentEncryptionAlgorithm, out X509Certificate2Collection originatorCerts, out CryptographicAttributeObjectCollection unprotectedAttributes)
{
return DecryptorPalWindows.Decode(encodedMessage, out version, out contentInfo, out contentEncryptionAlgorithm, out originatorCerts, out unprotectedAttributes);
}
public sealed override byte[] EncodeOctetString(byte[] octets)
{
unsafe
{
fixed (byte* pOctets = octets)
{
DATA_BLOB blob = new DATA_BLOB((IntPtr)pOctets, (uint)(octets.Length));
return Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob);
}
}
}
public sealed override byte[] DecodeOctetString(byte[] encodedOctets)
{
using (SafeHandle sh = Interop.Crypt32.CryptDecodeObjectToMemory(CryptDecodeObjectStructType.X509_OCTET_STRING, encodedOctets))
{
unsafe
{
DATA_BLOB blob = *(DATA_BLOB*)(sh.DangerousGetHandle());
return blob.ToByteArray();
}
}
}
public sealed override byte[] EncodeUtcTime(DateTime utcTime)
{
long ft;
try
{
ft = utcTime.ToFileTimeUtc();
}
catch (ArgumentException ex)
{
throw new CryptographicException(ex.Message, ex);
}
unsafe
{
return Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.PKCS_UTC_TIME, &ft);
}
}
public sealed override DateTime DecodeUtcTime(byte[] encodedUtcTime)
{
long signingTime = 0;
unsafe
{
fixed (byte* pEncodedUtcTime = encodedUtcTime)
{
int cbSize = sizeof(long);
if (!Interop.Crypt32.CryptDecodeObject(CryptDecodeObjectStructType.PKCS_UTC_TIME, (IntPtr)pEncodedUtcTime, encodedUtcTime.Length, &signingTime, ref cbSize))
throw Interop.CPError.GetLastWin32Error().ToCryptographicException();
}
}
return DateTime.FromFileTimeUtc(signingTime);
}
public sealed override string DecodeOid(byte[] encodedOid)
{
using (SafeHandle sh = Interop.Crypt32.CryptDecodeObjectToMemory(CryptDecodeObjectStructType.X509_OBJECT_IDENTIFIER, encodedOid))
{
unsafe
{
IntPtr pOidValue = *(IntPtr*)(sh.DangerousGetHandle());
string contentType = pOidValue.ToStringAnsi();
return contentType;
}
}
}
public sealed override Oid GetEncodedMessageType(byte[] encodedMessage)
{
using (SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToDecode(MsgEncodingType.All, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero))
{
if (hCryptMsg == null || hCryptMsg.IsInvalid)
throw Interop.CPError.GetLastWin32Error().ToCryptographicException();
if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedMessage, encodedMessage.Length, fFinal: true))
throw Interop.CPError.GetLastWin32Error().ToCryptographicException();
int msgTypeAsInt;
int cbSize = sizeof(int);
if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_TYPE_PARAM, 0, out msgTypeAsInt, ref cbSize))
throw Interop.CPError.GetLastWin32Error().ToCryptographicException();
CryptMsgType msgType = (CryptMsgType)msgTypeAsInt;
switch (msgType)
{
case CryptMsgType.CMSG_DATA:
return Oid.FromOidValue(Oids.Pkcs7Data, OidGroup.ExtensionOrAttribute);
case CryptMsgType.CMSG_SIGNED:
return Oid.FromOidValue(Oids.Pkcs7Signed, OidGroup.ExtensionOrAttribute);
case CryptMsgType.CMSG_ENVELOPED:
return Oid.FromOidValue(Oids.Pkcs7Enveloped, OidGroup.ExtensionOrAttribute);
case CryptMsgType.CMSG_SIGNED_AND_ENVELOPED:
return Oid.FromOidValue(Oids.Pkcs7SignedEnveloped, OidGroup.ExtensionOrAttribute);
case CryptMsgType.CMSG_HASHED:
return Oid.FromOidValue(Oids.Pkcs7Hashed, OidGroup.ExtensionOrAttribute);
case CryptMsgType.CMSG_ENCRYPTED:
return Oid.FromOidValue(Oids.Pkcs7Encrypted, OidGroup.ExtensionOrAttribute);
default:
throw ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException();
}
}
}
public sealed override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs)
{
certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: true));
certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: true));
}
public sealed override Exception CreateRecipientsNotFoundException()
{
return ErrorCode.CRYPT_E_RECIPIENT_NOT_FOUND.ToCryptographicException();
}
public sealed override Exception CreateRecipientInfosAfterEncryptException()
{
return ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException();
}
public sealed override Exception CreateDecryptAfterEncryptException()
{
return ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException();
}
public sealed override Exception CreateDecryptTwiceException()
{
return ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException();
}
public sealed override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate)
{
using (SafeCertContextHandle hCertContext = certificate.CreateCertContextHandle())
{
byte[] ski = hCertContext.GetSubjectKeyIdentifer();
return ski;
}
}
public override T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent)
{
return GetPrivateKey<T>(certificate, silent, preferNCrypt: true);
}
public override T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent)
{
return GetPrivateKey<T>(certificate, silent, preferNCrypt: false);
}
private T GetPrivateKey<T>(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm
{
if (!certificate.HasPrivateKey)
{
return null;
}
SafeProvOrNCryptKeyHandle handle = GetCertificatePrivateKey(
certificate,
silent,
preferNCrypt,
out CryptKeySpec keySpec,
out Exception exception);
using (handle)
{
if (handle == null || handle.IsInvalid)
{
if (exception != null)
{
throw exception;
}
return null;
}
if (keySpec == CryptKeySpec.CERT_NCRYPT_KEY_SPEC)
{
using (SafeNCryptKeyHandle keyHandle = new SafeNCryptKeyHandle(handle.DangerousGetHandle(), handle))
{
CngKeyHandleOpenOptions options = CngKeyHandleOpenOptions.None;
byte clrIsEphemeral = 0;
Interop.NCrypt.ErrorCode errorCode = Interop.NCrypt.NCryptGetByteProperty(keyHandle, "CLR IsEphemeral", ref clrIsEphemeral, CngPropertyOptions.CustomProperty);
if (errorCode == Interop.NCrypt.ErrorCode.ERROR_SUCCESS && clrIsEphemeral == 1)
{
options |= CngKeyHandleOpenOptions.EphemeralKey;
}
using (CngKey cngKey = CngKey.Open(keyHandle, options))
{
if (typeof(T) == typeof(RSA))
return (T)(object)new RSACng(cngKey);
if (typeof(T) == typeof(ECDsa))
return (T)(object)new ECDsaCng(cngKey);
if (typeof(T) == typeof(DSA))
return (T)(object)new DSACng(cngKey);
Debug.Fail($"Unknown CNG key type request: {typeof(T).FullName}");
return null;
}
}
}
// The key handle is for CAPI.
// Our CAPI types don't allow usage from a handle, so we have a few choices:
// 1) Extract the information we need to re-open the key handle.
// 2) Re-implement {R|D}SACryptoServiceProvider
// 3) PNSE.
// 4) Defer to cert.Get{R|D}SAPrivateKey if not silent, throw otherwise.
CspParameters cspParams = handle.GetProvParameters();
Debug.Assert((cspParams.Flags & CspProviderFlags.UseExistingKey) != 0);
cspParams.KeyNumber = (int)keySpec;
if (silent)
{
cspParams.Flags |= CspProviderFlags.NoPrompt;
}
if (typeof(T) == typeof(RSA))
return (T)(object)new RSACryptoServiceProvider(cspParams);
if (typeof(T) == typeof(DSA))
return (T)(object)new DSACryptoServiceProvider(cspParams);
//begin: gost
if (typeof(T) == typeof(Gost3410))
return (T)(object)new Gost3410CryptoServiceProvider(cspParams);
if (typeof(T) == typeof(Gost3410_2012_256))
return (T)(object)new Gost3410_2012_256CryptoServiceProvider(cspParams);
if (typeof(T) == typeof(Gost3410_2012_512))
return (T)(object)new Gost3410_2012_512CryptoServiceProvider(cspParams);
//end: gost
Debug.Fail($"Unknown CAPI key type request: {typeof(T).FullName}");
return null;
}
}
internal static SafeProvOrNCryptKeyHandle GetCertificatePrivateKey(
X509Certificate2 cert,
bool silent,
bool preferNCrypt,
out CryptKeySpec keySpec,
out Exception exception)
{
CryptAcquireCertificatePrivateKeyFlags flags =
CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG
| CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_COMPARE_KEY_FLAG;
if (preferNCrypt)
{
flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
}
else
{
flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG;
}
if (silent)
{
flags |= CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_SILENT_FLAG;
}
bool isNCrypt;
bool mustFree;
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
IntPtr hKey;
int cbSize = IntPtr.Size;
if (Interop.Crypt32.CertGetCertificateContextProperty(
hCertContext,
CertContextPropId.CERT_NCRYPT_KEY_HANDLE_PROP_ID,
out hKey,
ref cbSize))
{
exception = null;
keySpec = CryptKeySpec.CERT_NCRYPT_KEY_SPEC;
return new SafeProvOrNCryptKeyHandleUwp(hKey, hCertContext);
}
if (!Interop.Crypt32.CryptAcquireCertificatePrivateKey(
hCertContext,
flags,
IntPtr.Zero,
out hKey,
out keySpec,
out mustFree))
{
exception = Interop.CPError.GetHRForLastWin32Error().ToCryptographicException();
return null;
}
// We need to know whether we got back a CRYPTPROV or NCrypt handle.
// Unfortunately, NCryptIsKeyHandle() is a prohibited api on UWP.
// Fortunately, CryptAcquireCertificatePrivateKey() is documented to tell us which
// one we got through the keySpec value.
switch (keySpec)
{
case CryptKeySpec.AT_KEYEXCHANGE:
case CryptKeySpec.AT_SIGNATURE:
isNCrypt = false;
break;
case CryptKeySpec.CERT_NCRYPT_KEY_SPEC:
isNCrypt = true;
break;
default:
// As of this writing, we've exhausted all the known values of keySpec.
// We have no idea what kind of key handle we got so play it safe and fail fast.
throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_UnknownKeySpec, keySpec));
}
SafeProvOrNCryptKeyHandleUwp hProvOrNCryptKey = new SafeProvOrNCryptKeyHandleUwp(
hKey,
ownsHandle: mustFree,
isNcrypt: isNCrypt);
exception = null;
return hProvOrNCryptKey;
}
}
}
}