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
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
[StructLayout(LayoutKind.Sequential)]
struct SystemTime
{
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
public SystemTime(DateTime date)
{
wYear = (short)date.Year;
wMonth = (short)date.Month;
wDayOfWeek = (short)date.DayOfWeek;
wDay = (short)date.Day;
wHour = (short)date.Hour;
wMinute = (short)date.Minute;
wSecond = (short)date.Second;
wMilliseconds = (short)date.Millisecond;
}
}
[SuppressUnmanagedCodeSecurity]
class CertificateHandle : SafeHandle
{
#region PInvoke declarations
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall)]
[ResourceExposure(ResourceScope.None)]
extern static bool CertFreeCertificateContext(IntPtr pCertContext);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
extern static bool CertDeleteCertificateFromStore(IntPtr pCertContext);
#endregion
protected bool delete = false;
protected CertificateHandle()
: base(IntPtr.Zero, true)
{
return;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
if (delete)
return CertDeleteCertificateFromStore(handle);
else
return CertFreeCertificateContext(handle);
}
}
[SuppressUnmanagedCodeSecurity]
sealed class StoreCertificateHandle : CertificateHandle
{
StoreCertificateHandle() : base() { base.delete = true; }
}
[SuppressUnmanagedCodeSecurity]
sealed class CertificateStoreHandle : SafeHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall)]
[ResourceExposure(ResourceScope.None)]
static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags);
CertificateStoreHandle()
: base(IntPtr.Zero, true)
{
return;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
return CertCloseStore(handle, 0);
}
}
[SuppressUnmanagedCodeSecurity]
sealed class KeyContainerHandle : SafeHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall)]
[ResourceExposure(ResourceScope.None)]
static extern bool CryptReleaseContext(IntPtr hProv, int dwFlags);
KeyContainerHandle()
: base(IntPtr.Zero, true)
{
return;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
return CryptReleaseContext(handle, 0);
}
}
sealed class KeyHandle : SafeHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall)]
[ResourceExposure(ResourceScope.None)]
static extern bool CryptDestroyKey(IntPtr hKey);
KeyHandle()
: base(IntPtr.Zero, true)
{
return;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
return CryptDestroyKey(handle);
}
}
sealed class CryptoApiBlob : IDisposable
{
int cbData;
CriticalAllocHandle data;
public CryptoApiBlob()
{
}
public CryptoApiBlob(byte[] bytes)
{
Fx.Assert(bytes != null, "Cannot set null data");
AllocateBlob(bytes.Length);
Marshal.Copy(bytes, 0, (IntPtr)data, bytes.Length);
cbData = bytes.Length;
return;
}
public int DataSize
{
get
{
Fx.Assert(cbData >= 0, "Size must be greater than or equal to zero");
return cbData;
}
}
public void AllocateBlob(int size)
{
data = CriticalAllocHandle.FromSize(size);
cbData = size;
}
[StructLayout(LayoutKind.Sequential)]
public class InteropHelper
{
public int size;
public IntPtr data;
public InteropHelper(int size, IntPtr data)
{
this.size = size;
this.data = data;
}
}
public InteropHelper GetMemoryForPinning()
{
return new InteropHelper(cbData, (IntPtr)data);
}
public byte[] GetBytes()
{
if (cbData == 0)
return null;
byte[] bytes = DiagnosticUtility.Utility.AllocateByteArray(cbData);
Marshal.Copy((IntPtr)data, bytes, 0, cbData);
return bytes;
}
void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
}
}
public void Dispose()
{
Dispose(true);
return;
}
}
sealed class CertificateName
{
#region PInvoke Declarations
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
extern static bool CertStrToName(CertEncodingType dwCertEncodingType,
[MarshalAs(UnmanagedType.LPTStr)]string pszX500,
StringType dwStrType,
IntPtr pvReserved,
[In, Out]byte[] pbEncoded,
[In, Out]ref int pcbEncoded,
[MarshalAs(UnmanagedType.LPTStr)]ref StringBuilder ppszError);
[Flags]
enum CertEncodingType : int
{
X509AsnEncoding = 0x00000001,
PKCS7AsnEncoding = 0x00010000
}
[Flags]
enum StringType : int
{
SimpleNameString = 1,
OIDNameString = 2,
X500NameString = 3,
CommaFlag = 0x04000000,
SemicolonFlag = 0x40000000,
CRLFFlag = 0x08000000,
NoPlusFlag = 0x20000000,
NoQuotingFlag = 0x10000000,
ReverseFlag = 0x02000000,
DisableIE4UTF8Flag = 0x00010000,
EnableT61UnicodeFlag = 0x00020000,
EnableUTF8UnicodeFlag = 0x00040000
}
#endregion
string dn;
public CertificateName(string dn)
{
Fx.Assert(!String.IsNullOrEmpty(dn), "Empty subject name for certificate!");
this.dn = dn;
}
public string DistinguishedName
{
get { return dn; }
}
public CryptoApiBlob GetCryptoApiBlob()
{
byte[] encodedName = GetEncodedName();
return new CryptoApiBlob(encodedName);
}
byte[] GetEncodedName()
{
int encodingSize = 0;
StringBuilder errorString = null;
CertStrToName(CertEncodingType.X509AsnEncoding | CertEncodingType.PKCS7AsnEncoding,
DistinguishedName,
StringType.OIDNameString | StringType.ReverseFlag,
IntPtr.Zero,
null,
ref encodingSize,
ref errorString);
byte[] encodedBytes = new byte[encodingSize];
bool ok = CertStrToName(CertEncodingType.X509AsnEncoding | CertEncodingType.PKCS7AsnEncoding,
DistinguishedName,
StringType.OIDNameString | StringType.ReverseFlag,
IntPtr.Zero,
encodedBytes,
ref encodingSize,
ref errorString);
if (!ok)
{
PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
}
return encodedBytes;
}
}
sealed partial class SelfSignedCertificate : IDisposable
{
#region PInvoke declarations
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
extern static CertificateHandle CertCreateSelfSignCertificate(
KeyContainerHandle hProv,
CryptoApiBlob.InteropHelper pSubjectIssuerBlob,
SelfSignFlags dwFlags,
IntPtr pKeyProvInfo,
IntPtr pSignatureAlgorithm,
[In] ref SystemTime pStartTime,
[In] ref SystemTime pEndTime,
IntPtr pExtensions);
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
extern static CertificateStoreHandle CertOpenStore(
IntPtr lpszStoreProvider,
int dwMsgAndCertEncodingType,
IntPtr hCryptProv,
int dwFlags,
IntPtr pvPara);
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
extern static bool CertAddCertificateContextToStore(
CertificateStoreHandle hCertStore,
CertificateHandle pCertContext,
AddDisposition dwAddDisposition,
[Out]out StoreCertificateHandle ppStoreContext);
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
extern static bool CryptAcquireContext(
[Out]out KeyContainerHandle phProv,
string pszContainer,
string pszProvider,
ProviderType dwProvType,
ContextFlags dwFlags);
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
extern static bool CryptGenKey(
KeyContainerHandle hProv,
AlgorithmType algId,
KeyFlags dwFlags,
[Out]out KeyHandle phKey);
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
extern static bool PFXExportCertStoreEx(
CertificateStoreHandle hStore,
IntPtr pPFX,
//IntPtr szPassword,
string password,
IntPtr pvReserved,
PfxExportFlags dwFlags);
[DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
extern static bool CertSetCertificateContextProperty(
CertificateHandle context,
int propId,
int flags,
KeyHandle pv);
[Flags]
enum SelfSignFlags : int
{
None = 0,
NoSign = 1,
NoKeyInfo = 2,
}
enum AddDisposition : int
{
New = 1,
UseExisting = 2,
ReplaceExisting = 3,
Always = 4,
ReplaceExistingInheritProperties = 5
}
[Flags]
enum PfxExportFlags : int
{
ReportNoPrivateKey = 0x00000001,
ReportNotAbleToExportPrivateKey = 0x00000002,
ExportPrivateKeys = 0x00000004
}
enum ProviderType : int
{
RsaFull = 1,
RsaSignature = 2,
Dss = 3,
Fortezza = 4,
MsExchange = 5,
Ssl = 6,
RsaSecureChannel = 12,
DssDiffieHellman = 13,
EcDsaSignature = 14,
EcNraSignature = 15,
EcDsaFull = 16,
EcNraFull = 17,
DiffieHellmanSecureChannel = 18,
SpyrusLynks = 20,
RandomNumberGenerator = 21,
IntelSec = 22,
ReplaceOwf = 23,
RsaAes = 24
}
[Flags]
enum ContextFlags : uint
{
VerifyContext = 0xF0000000,
NewKeySet = 0x00000008,
DeleteKeySet = 0x00000010,
MachineKeySet = 0x00000020,
Silent = 0x00000040
}
enum AlgorithmType : int
{
KeyExchange = 1,
Signature = 2
}
enum KeyFlags : int
{
Exportable = 0x00000001,
UserProtected = 0x00000002,
CreateSalt = 0x00000004,
UpdateKey = 0x00000008,
NoSalt = 0x00000010,
PreGenerate = 0x00000040,
Online = 0x00000080,
Sf = 0x00000100,
CreateIv = 0x00000200,
KeyExchangeKey = 0x00000400,
DataKey = 0x00000800,
Volatile = 0x00001000,
SgcKey = 0x00002000,
Archivable = 0x00004000,
Exportable2k = 0x08000001,
}
const int CERT_KEY_SPEC_PROP_ID = 1;
const int CERT_KEY_PROV_INFO_PROP_ID = 2;
#endregion
[Serializable]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class CRYPT_KEY_PROV_INFO
{
public string container;
public string provName;
public int providerType;
public int flags;
public int paramsCount;
public IntPtr param;
public int keySpec;
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_OBJID_BLOB
{
public int count;
public IntPtr parameters;
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public class CRYPT_ALGORITHM_IDENTIFIER
{
public CRYPT_ALGORITHM_IDENTIFIER(string id)
{
this.pszObjId = id;
}
public string pszObjId;
public CRYPT_OBJID_BLOB Parameters;
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public class Sha1AlgorithmId : CRYPT_ALGORITHM_IDENTIFIER
{
const string AlgId = "1.2.840.113549.1.1.5";
public Sha1AlgorithmId() : base(AlgId) { }
}
CriticalAllocHandle GetProviderInfo()
{
CRYPT_KEY_PROV_INFO provInfo = new CRYPT_KEY_PROV_INFO();
provInfo.container = this.keyContainerName;
provInfo.providerType = (int)ProviderType.RsaSecureChannel;
provInfo.paramsCount = 0;
provInfo.keySpec = (int)AlgorithmType.KeyExchange;
return CriticalAllocHandleBlob.FromBlob<CRYPT_KEY_PROV_INFO>(provInfo);
}
static CriticalAllocHandle GetSha1AlgorithmId()
{
Sha1AlgorithmId sha1Id = new Sha1AlgorithmId();
return CriticalAllocHandleBlob.FromBlob<CRYPT_ALGORITHM_IDENTIFIER>(sha1Id);
}
}
}
|