PeerUnsafeNativeCryptMethods.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System;
  7. using System.Runtime;
  8. using System.Runtime.ConstrainedExecution;
  9. using System.Runtime.InteropServices;
  10. using System.Runtime.Versioning;
  11. using System.Security;
  12. using System.Text;
  13. [StructLayout(LayoutKind.Sequential)]
  14. struct SystemTime
  15. {
  16. public short wYear;
  17. public short wMonth;
  18. public short wDayOfWeek;
  19. public short wDay;
  20. public short wHour;
  21. public short wMinute;
  22. public short wSecond;
  23. public short wMilliseconds;
  24. public SystemTime(DateTime date)
  25. {
  26. wYear = (short)date.Year;
  27. wMonth = (short)date.Month;
  28. wDayOfWeek = (short)date.DayOfWeek;
  29. wDay = (short)date.Day;
  30. wHour = (short)date.Hour;
  31. wMinute = (short)date.Minute;
  32. wSecond = (short)date.Second;
  33. wMilliseconds = (short)date.Millisecond;
  34. }
  35. }
  36. [SuppressUnmanagedCodeSecurity]
  37. class CertificateHandle : SafeHandle
  38. {
  39. #region PInvoke declarations
  40. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  41. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall)]
  42. [ResourceExposure(ResourceScope.None)]
  43. extern static bool CertFreeCertificateContext(IntPtr pCertContext);
  44. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  45. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  46. [ResourceExposure(ResourceScope.None)]
  47. extern static bool CertDeleteCertificateFromStore(IntPtr pCertContext);
  48. #endregion
  49. protected bool delete = false;
  50. protected CertificateHandle()
  51. : base(IntPtr.Zero, true)
  52. {
  53. return;
  54. }
  55. public override bool IsInvalid
  56. {
  57. get { return handle == IntPtr.Zero; }
  58. }
  59. protected override bool ReleaseHandle()
  60. {
  61. if (delete)
  62. return CertDeleteCertificateFromStore(handle);
  63. else
  64. return CertFreeCertificateContext(handle);
  65. }
  66. }
  67. [SuppressUnmanagedCodeSecurity]
  68. sealed class StoreCertificateHandle : CertificateHandle
  69. {
  70. StoreCertificateHandle() : base() { base.delete = true; }
  71. }
  72. [SuppressUnmanagedCodeSecurity]
  73. sealed class CertificateStoreHandle : SafeHandle
  74. {
  75. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  76. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall)]
  77. [ResourceExposure(ResourceScope.None)]
  78. static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags);
  79. CertificateStoreHandle()
  80. : base(IntPtr.Zero, true)
  81. {
  82. return;
  83. }
  84. public override bool IsInvalid
  85. {
  86. get { return handle == IntPtr.Zero; }
  87. }
  88. protected override bool ReleaseHandle()
  89. {
  90. return CertCloseStore(handle, 0);
  91. }
  92. }
  93. [SuppressUnmanagedCodeSecurity]
  94. sealed class KeyContainerHandle : SafeHandle
  95. {
  96. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  97. [DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall)]
  98. [ResourceExposure(ResourceScope.None)]
  99. static extern bool CryptReleaseContext(IntPtr hProv, int dwFlags);
  100. KeyContainerHandle()
  101. : base(IntPtr.Zero, true)
  102. {
  103. return;
  104. }
  105. public override bool IsInvalid
  106. {
  107. get { return handle == IntPtr.Zero; }
  108. }
  109. protected override bool ReleaseHandle()
  110. {
  111. return CryptReleaseContext(handle, 0);
  112. }
  113. }
  114. sealed class KeyHandle : SafeHandle
  115. {
  116. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  117. [DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall)]
  118. [ResourceExposure(ResourceScope.None)]
  119. static extern bool CryptDestroyKey(IntPtr hKey);
  120. KeyHandle()
  121. : base(IntPtr.Zero, true)
  122. {
  123. return;
  124. }
  125. public override bool IsInvalid
  126. {
  127. get { return handle == IntPtr.Zero; }
  128. }
  129. protected override bool ReleaseHandle()
  130. {
  131. return CryptDestroyKey(handle);
  132. }
  133. }
  134. sealed class CryptoApiBlob : IDisposable
  135. {
  136. int cbData;
  137. CriticalAllocHandle data;
  138. public CryptoApiBlob()
  139. {
  140. }
  141. public CryptoApiBlob(byte[] bytes)
  142. {
  143. Fx.Assert(bytes != null, "Cannot set null data");
  144. AllocateBlob(bytes.Length);
  145. Marshal.Copy(bytes, 0, (IntPtr)data, bytes.Length);
  146. cbData = bytes.Length;
  147. return;
  148. }
  149. public int DataSize
  150. {
  151. get
  152. {
  153. Fx.Assert(cbData >= 0, "Size must be greater than or equal to zero");
  154. return cbData;
  155. }
  156. }
  157. public void AllocateBlob(int size)
  158. {
  159. data = CriticalAllocHandle.FromSize(size);
  160. cbData = size;
  161. }
  162. [StructLayout(LayoutKind.Sequential)]
  163. public class InteropHelper
  164. {
  165. public int size;
  166. public IntPtr data;
  167. public InteropHelper(int size, IntPtr data)
  168. {
  169. this.size = size;
  170. this.data = data;
  171. }
  172. }
  173. public InteropHelper GetMemoryForPinning()
  174. {
  175. return new InteropHelper(cbData, (IntPtr)data);
  176. }
  177. public byte[] GetBytes()
  178. {
  179. if (cbData == 0)
  180. return null;
  181. byte[] bytes = DiagnosticUtility.Utility.AllocateByteArray(cbData);
  182. Marshal.Copy((IntPtr)data, bytes, 0, cbData);
  183. return bytes;
  184. }
  185. void Dispose(bool disposing)
  186. {
  187. if (disposing)
  188. {
  189. GC.SuppressFinalize(this);
  190. }
  191. }
  192. public void Dispose()
  193. {
  194. Dispose(true);
  195. return;
  196. }
  197. }
  198. sealed class CertificateName
  199. {
  200. #region PInvoke Declarations
  201. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
  202. [ResourceExposure(ResourceScope.None)]
  203. extern static bool CertStrToName(CertEncodingType dwCertEncodingType,
  204. [MarshalAs(UnmanagedType.LPTStr)]string pszX500,
  205. StringType dwStrType,
  206. IntPtr pvReserved,
  207. [In, Out]byte[] pbEncoded,
  208. [In, Out]ref int pcbEncoded,
  209. [MarshalAs(UnmanagedType.LPTStr)]ref StringBuilder ppszError);
  210. [Flags]
  211. enum CertEncodingType : int
  212. {
  213. X509AsnEncoding = 0x00000001,
  214. PKCS7AsnEncoding = 0x00010000
  215. }
  216. [Flags]
  217. enum StringType : int
  218. {
  219. SimpleNameString = 1,
  220. OIDNameString = 2,
  221. X500NameString = 3,
  222. CommaFlag = 0x04000000,
  223. SemicolonFlag = 0x40000000,
  224. CRLFFlag = 0x08000000,
  225. NoPlusFlag = 0x20000000,
  226. NoQuotingFlag = 0x10000000,
  227. ReverseFlag = 0x02000000,
  228. DisableIE4UTF8Flag = 0x00010000,
  229. EnableT61UnicodeFlag = 0x00020000,
  230. EnableUTF8UnicodeFlag = 0x00040000
  231. }
  232. #endregion
  233. string dn;
  234. public CertificateName(string dn)
  235. {
  236. Fx.Assert(!String.IsNullOrEmpty(dn), "Empty subject name for certificate!");
  237. this.dn = dn;
  238. }
  239. public string DistinguishedName
  240. {
  241. get { return dn; }
  242. }
  243. public CryptoApiBlob GetCryptoApiBlob()
  244. {
  245. byte[] encodedName = GetEncodedName();
  246. return new CryptoApiBlob(encodedName);
  247. }
  248. byte[] GetEncodedName()
  249. {
  250. int encodingSize = 0;
  251. StringBuilder errorString = null;
  252. CertStrToName(CertEncodingType.X509AsnEncoding | CertEncodingType.PKCS7AsnEncoding,
  253. DistinguishedName,
  254. StringType.OIDNameString | StringType.ReverseFlag,
  255. IntPtr.Zero,
  256. null,
  257. ref encodingSize,
  258. ref errorString);
  259. byte[] encodedBytes = new byte[encodingSize];
  260. bool ok = CertStrToName(CertEncodingType.X509AsnEncoding | CertEncodingType.PKCS7AsnEncoding,
  261. DistinguishedName,
  262. StringType.OIDNameString | StringType.ReverseFlag,
  263. IntPtr.Zero,
  264. encodedBytes,
  265. ref encodingSize,
  266. ref errorString);
  267. if (!ok)
  268. {
  269. PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException());
  270. }
  271. return encodedBytes;
  272. }
  273. }
  274. sealed partial class SelfSignedCertificate : IDisposable
  275. {
  276. #region PInvoke declarations
  277. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  278. [ResourceExposure(ResourceScope.None)]
  279. extern static CertificateHandle CertCreateSelfSignCertificate(
  280. KeyContainerHandle hProv,
  281. CryptoApiBlob.InteropHelper pSubjectIssuerBlob,
  282. SelfSignFlags dwFlags,
  283. IntPtr pKeyProvInfo,
  284. IntPtr pSignatureAlgorithm,
  285. [In] ref SystemTime pStartTime,
  286. [In] ref SystemTime pEndTime,
  287. IntPtr pExtensions);
  288. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  289. [ResourceExposure(ResourceScope.None)]
  290. extern static CertificateStoreHandle CertOpenStore(
  291. IntPtr lpszStoreProvider,
  292. int dwMsgAndCertEncodingType,
  293. IntPtr hCryptProv,
  294. int dwFlags,
  295. IntPtr pvPara);
  296. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  297. [ResourceExposure(ResourceScope.None)]
  298. extern static bool CertAddCertificateContextToStore(
  299. CertificateStoreHandle hCertStore,
  300. CertificateHandle pCertContext,
  301. AddDisposition dwAddDisposition,
  302. [Out]out StoreCertificateHandle ppStoreContext);
  303. [DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  304. [ResourceExposure(ResourceScope.None)]
  305. extern static bool CryptAcquireContext(
  306. [Out]out KeyContainerHandle phProv,
  307. string pszContainer,
  308. string pszProvider,
  309. ProviderType dwProvType,
  310. ContextFlags dwFlags);
  311. [DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  312. [ResourceExposure(ResourceScope.None)]
  313. extern static bool CryptGenKey(
  314. KeyContainerHandle hProv,
  315. AlgorithmType algId,
  316. KeyFlags dwFlags,
  317. [Out]out KeyHandle phKey);
  318. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, CharSet = CharSet.Unicode)]
  319. [ResourceExposure(ResourceScope.None)]
  320. extern static bool PFXExportCertStoreEx(
  321. CertificateStoreHandle hStore,
  322. IntPtr pPFX,
  323. //IntPtr szPassword,
  324. string password,
  325. IntPtr pvReserved,
  326. PfxExportFlags dwFlags);
  327. [DllImport("Crypt32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  328. [ResourceExposure(ResourceScope.None)]
  329. extern static bool CertSetCertificateContextProperty(
  330. CertificateHandle context,
  331. int propId,
  332. int flags,
  333. KeyHandle pv);
  334. [Flags]
  335. enum SelfSignFlags : int
  336. {
  337. None = 0,
  338. NoSign = 1,
  339. NoKeyInfo = 2,
  340. }
  341. enum AddDisposition : int
  342. {
  343. New = 1,
  344. UseExisting = 2,
  345. ReplaceExisting = 3,
  346. Always = 4,
  347. ReplaceExistingInheritProperties = 5
  348. }
  349. [Flags]
  350. enum PfxExportFlags : int
  351. {
  352. ReportNoPrivateKey = 0x00000001,
  353. ReportNotAbleToExportPrivateKey = 0x00000002,
  354. ExportPrivateKeys = 0x00000004
  355. }
  356. enum ProviderType : int
  357. {
  358. RsaFull = 1,
  359. RsaSignature = 2,
  360. Dss = 3,
  361. Fortezza = 4,
  362. MsExchange = 5,
  363. Ssl = 6,
  364. RsaSecureChannel = 12,
  365. DssDiffieHellman = 13,
  366. EcDsaSignature = 14,
  367. EcNraSignature = 15,
  368. EcDsaFull = 16,
  369. EcNraFull = 17,
  370. DiffieHellmanSecureChannel = 18,
  371. SpyrusLynks = 20,
  372. RandomNumberGenerator = 21,
  373. IntelSec = 22,
  374. ReplaceOwf = 23,
  375. RsaAes = 24
  376. }
  377. [Flags]
  378. enum ContextFlags : uint
  379. {
  380. VerifyContext = 0xF0000000,
  381. NewKeySet = 0x00000008,
  382. DeleteKeySet = 0x00000010,
  383. MachineKeySet = 0x00000020,
  384. Silent = 0x00000040
  385. }
  386. enum AlgorithmType : int
  387. {
  388. KeyExchange = 1,
  389. Signature = 2
  390. }
  391. enum KeyFlags : int
  392. {
  393. Exportable = 0x00000001,
  394. UserProtected = 0x00000002,
  395. CreateSalt = 0x00000004,
  396. UpdateKey = 0x00000008,
  397. NoSalt = 0x00000010,
  398. PreGenerate = 0x00000040,
  399. Online = 0x00000080,
  400. Sf = 0x00000100,
  401. CreateIv = 0x00000200,
  402. KeyExchangeKey = 0x00000400,
  403. DataKey = 0x00000800,
  404. Volatile = 0x00001000,
  405. SgcKey = 0x00002000,
  406. Archivable = 0x00004000,
  407. Exportable2k = 0x08000001,
  408. }
  409. const int CERT_KEY_SPEC_PROP_ID = 1;
  410. const int CERT_KEY_PROV_INFO_PROP_ID = 2;
  411. #endregion
  412. [Serializable]
  413. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  414. public class CRYPT_KEY_PROV_INFO
  415. {
  416. public string container;
  417. public string provName;
  418. public int providerType;
  419. public int flags;
  420. public int paramsCount;
  421. public IntPtr param;
  422. public int keySpec;
  423. }
  424. [Serializable]
  425. [StructLayout(LayoutKind.Sequential)]
  426. public struct CRYPT_OBJID_BLOB
  427. {
  428. public int count;
  429. public IntPtr parameters;
  430. }
  431. [Serializable]
  432. [StructLayout(LayoutKind.Sequential)]
  433. public class CRYPT_ALGORITHM_IDENTIFIER
  434. {
  435. public CRYPT_ALGORITHM_IDENTIFIER(string id)
  436. {
  437. this.pszObjId = id;
  438. }
  439. public string pszObjId;
  440. public CRYPT_OBJID_BLOB Parameters;
  441. }
  442. [Serializable]
  443. [StructLayout(LayoutKind.Sequential)]
  444. public class Sha1AlgorithmId : CRYPT_ALGORITHM_IDENTIFIER
  445. {
  446. const string AlgId = "1.2.840.113549.1.1.5";
  447. public Sha1AlgorithmId() : base(AlgId) { }
  448. }
  449. CriticalAllocHandle GetProviderInfo()
  450. {
  451. CRYPT_KEY_PROV_INFO provInfo = new CRYPT_KEY_PROV_INFO();
  452. provInfo.container = this.keyContainerName;
  453. provInfo.providerType = (int)ProviderType.RsaSecureChannel;
  454. provInfo.paramsCount = 0;
  455. provInfo.keySpec = (int)AlgorithmType.KeyExchange;
  456. return CriticalAllocHandleBlob.FromBlob<CRYPT_KEY_PROV_INFO>(provInfo);
  457. }
  458. static CriticalAllocHandle GetSha1AlgorithmId()
  459. {
  460. Sha1AlgorithmId sha1Id = new Sha1AlgorithmId();
  461. return CriticalAllocHandleBlob.FromBlob<CRYPT_ALGORITHM_IDENTIFIER>(sha1Id);
  462. }
  463. }
  464. }