/// <inheritdoc /> public Object GetConfigEntry(String entryName, String node = null) { if (entryName == null) { throw new ArgumentNullException(nameof(entryName)); } if (String.Empty.Equals(entryName)) { throw new ArgumentException("'entryName' parameter cannot be empty string."); } ICertAdmin2 certAdmin = new CCertAdminClass(); try { return(useActive ? certAdmin.GetConfigEntry($"{ComputerName}\\{ActiveConfig}", node ?? String.Empty, entryName) : certAdmin.GetConfigEntry(ComputerName, String.Empty, entryName)); } catch (Exception ex) { if (ex is FileNotFoundException) { return(null); } throw; } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public void SetCertificateExtension(Int32 requestID, X509Extension extension) { if (extension == null) { throw new ArgumentNullException(nameof(extension)); } var certAdmin = new CCertAdminClass(); // BSTR is length-prefixed type, so allocate extra 4 bytes to store BSTR length IntPtr pbBstr = Marshal.AllocHGlobal(extension.RawData.Length + 4); // write length in front of actual BSTR value Marshal.WriteInt32(pbBstr, 0, extension.RawData.Length); // copy raw bytes right after length prefix Marshal.Copy(extension.RawData, 0, pbBstr + 4, extension.RawData.Length); // create an instance of VARIANT and configure it var variant = new OleAut.VARIANT { vt = OleAut.VT_BSTR, // the pointer to BSTR doesn't include prefix length, so skip 4 bytes pvRecord = pbBstr + 4 }; Int32 flags = extension.Critical ? 1 : 0; IntPtr pvarValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(OleAut.VARIANT))); Marshal.StructureToPtr(variant, pvarValue, false); try { certAdmin.SetCertificateExtension(_configString, requestID, extension.Oid.Value, CertAdmConstants.ProptypeBinary, flags, pvarValue); } finally { Marshal.FreeHGlobal(pbBstr); Marshal.FreeHGlobal(pvarValue); CryptographyUtils.ReleaseCom(certAdmin); } }
/// <summary> /// Retrieves the most recent 'CA Exchange' certificate. If the certificate does not exist, the method /// will instruct CA server to generate or enroll a new one. /// </summary> /// <exception cref="UninitializedObjectException">The object is not properly initialized.</exception> /// <exception cref="ServerUnavailableException">CA server is not accessible via RPC/DCOM.</exception> /// <exception cref="UnauthorizedAccessException">The caller do not have at least <strong>Read</strong> permissions.</exception> /// <exception cref="PlatformNotSupportedException">Current CA is not <strong>Enterprise CA</strong>. Only Enterprise CAs supports this feature.</exception> /// <returns>CA Exchange certificate.</returns> public X509Certificate2 GetCAExchangeCertificate() { if (String.IsNullOrEmpty(Name)) { throw new UninitializedObjectException(); } if (!IsEnterprise) { throw new PlatformNotSupportedException(Error.E_NONENTERPRISE); } if (!Ping()) { ServerUnavailableException e = new ServerUnavailableException(DisplayName); e.Data.Add(nameof(e.Source), OfflineSource.DCOM); throw e; } var CertAdmin = new CCertAdmin(); try { Int32 index = (Int32)CertAdmin.GetCAProperty(ConfigString, CertAdmConstants.CrPropCaxchgcertcount, 0, 1, 0) - 1; if (index >= 0) { String Base64 = (String)CertAdmin.GetCAProperty(ConfigString, CertAdmConstants.CrPropCaxchgcert, index, 3, 1); return(new X509Certificate2(Convert.FromBase64String(Base64))); } throw new Exception(String.Format(Error.E_XCHGUNAVAILABLE, DisplayName)); } catch (Exception e) { throw Error.ComExceptionHandler(e); } finally { CryptographyUtils.ReleaseCom(CertAdmin); } }
/// <summary> /// This method publishes certificate revocation lists (CRLs) for a certification authority (CA). /// <para> /// The PublishCRL method publishes a CRL based on the CA's current certificate, as well as CRLs /// based on any CA certificates that have been renewed and are not yet expired. /// </para> /// </summary> /// <param name="deltaOnly"> /// A delta CRL is published, or the most recent delta CRL is republished if <strong>updateFilesOnly</strong> /// parameter is set. Note that if the CA has not enabled delta CRL publishing, use of this flag will result /// in an error.</param> /// <param name="updateFilesOnly"> /// The most recent base or delta CRL, is republished. The CA will not republish a CRL to a CRL distribution point /// if the CRL at the distribution point is already the most recent CRL. /// </param> /// <exception cref="UninitializedObjectException">The object is not properly initialized.</exception> /// <exception cref="ServerUnavailableException">CA server is not accessible via RPC/DCOM.</exception> public void PublishCRL(Boolean deltaOnly = false, Boolean updateFilesOnly = false) { if (String.IsNullOrEmpty(Name)) { throw new UninitializedObjectException(); } if (!Ping()) { ServerUnavailableException e = new ServerUnavailableException(DisplayName); e.Data.Add(nameof(e.Source), OfflineSource.DCOM); throw e; } var CertAdmin = new CCertAdmin(); try { if (deltaOnly) { CertAdmin.PublishCRLs(ConfigString, new DateTime(0), 0x2); } else if (updateFilesOnly) { CertAdmin.PublishCRLs(ConfigString, new DateTime(0), 0x11); } else { CertAdmin.PublishCRLs(ConfigString, new DateTime(0), 0x1); } } catch (Exception e) { throw Error.ComExceptionHandler(e); } finally { CryptographyUtils.ReleaseCom(CertAdmin); } }
/// <summary> /// Unregisters (deletes) certificate enrollment policy server endpoint from registry. /// </summary> /// <exception cref="InvalidOperationException"> /// The current CEP object is not registered. /// </exception> /// <exception cref="UninitializedObjectException"> /// The current object is not properly initialized through any of public constructor. /// </exception> public void Unregister() { if (URL == null) { throw new UninitializedObjectException(); } if (!registered) { throw new InvalidOperationException("The current CEP object is not registered."); } CX509PolicyServerUrl urlClass = new CX509PolicyServerUrl(); urlClass.Initialize(UserContext ? X509CertificateEnrollmentContext.ContextUser : X509CertificateEnrollmentContext.ContextMachine); try { urlClass.AuthFlags = (X509EnrollmentAuthFlags)(Int32)Authentication; urlClass.Cost = (UInt32)Priority; urlClass.Flags = (PolicyServerUrlFlags)Flags; urlClass.Url = URL.AbsoluteUri; if (!String.IsNullOrEmpty(Name)) { urlClass.SetStringProperty(PolicyServerUrlPropertyID.PsFriendlyName, Name); } urlClass.SetStringProperty(PolicyServerUrlPropertyID.PsPolicyID, PolicyId); urlClass.RemoveFromRegistry(UserContext ? X509CertificateEnrollmentContext.ContextUser : X509CertificateEnrollmentContext.ContextMachine); } catch (Exception e) { throw Error.ComExceptionHandler(e); } finally { CryptographyUtils.ReleaseCom(urlClass); } }
/// <summary> /// Gets locally registered enrollment policy server endpoints. /// </summary> /// <param name="userContext">Specifies whether to retrieve enrollment policy server endpoints for user or machine context.</param> /// <exception cref="NotSupportedException">The operating system do not support certificate enrollment policy servers.</exception> /// <returns>An array of registered enrollment policy server endpoints.</returns> public static PolicyServerClient[] GetPolicyServers(Boolean userContext) { if (!CryptographyUtils.TestCepCompat()) { throw new NotSupportedException(); } List <PolicyServerClient> policies = new List <PolicyServerClient>(); X509CertificateEnrollmentContext context = userContext ? X509CertificateEnrollmentContext.ContextUser : X509CertificateEnrollmentContext.ContextMachine; foreach (PolicyServerUrlFlags flag in new [] { PolicyServerUrlFlags.PsfLocationGroupPolicy, PolicyServerUrlFlags.PsfLocationRegistry }) { CX509PolicyServerListManager serverManager = new CX509PolicyServerListManager(); try { serverManager.Initialize(context, flag); IEnumerator enumerator = serverManager.GetEnumerator(); do { if (enumerator.Current != null) { policies.Add(new PolicyServerClient((IX509PolicyServerUrl)enumerator.Current, userContext)); } } while (enumerator.MoveNext()); } finally { CryptographyUtils.ReleaseCom(serverManager); } } return(policies.ToArray()); }
void releaseUnmanagedResources() { if (dbRow != null) { CryptographyUtils.ReleaseCom(dbRow); } CryptographyUtils.ReleaseCom(_caView); }
/// <summary> /// Registers or updates a current object in local registry. /// </summary> /// <exception cref="UninitializedObjectException"> /// The current object is not properly initialized through any of public constructor. /// </exception> /// <exception cref="NotSupportedException"> /// <strong>Authentication</strong> property is set to <strong>None</strong>. /// </exception> public void Register() { if (URL == null) { throw new UninitializedObjectException(); } CX509EnrollmentHelper urlClass = new CX509EnrollmentHelper(); urlClass.Initialize(UserContext ? X509CertificateEnrollmentContext.ContextUser : X509CertificateEnrollmentContext.ContextMachine); try { switch (Authentication) { case PolicyAuthenticationEnum.Anonymous: case PolicyAuthenticationEnum.Kerberos: urlClass.AddPolicyServer( URL.AbsoluteUri, PolicyId, 0, (X509EnrollmentAuthFlags)(Int32)Authentication, null, null ); break; case PolicyAuthenticationEnum.UserNameAndPassword: urlClass.AddPolicyServer( URL.AbsoluteUri, PolicyId, 0, (X509EnrollmentAuthFlags)(Int32)Authentication, uName, Marshal.PtrToStringAuto(Marshal.SecureStringToBSTR(uPassword)) ); break; case PolicyAuthenticationEnum.ClientCertificate: urlClass.AddPolicyServer( URL.AbsoluteUri, PolicyId, 0, (X509EnrollmentAuthFlags)(Int32)Authentication, uName, null ); break; default: throw new NotSupportedException(); } registered = true; } catch (Exception e) { throw Error.ComExceptionHandler(e); } finally { CryptographyUtils.ReleaseCom(urlClass); } }
void publishCRL(AdcsCrlPublishType crlFlags, DateTime?nexUpdate = null) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { certAdmin.PublishCRLs(_configString, nexUpdate ?? DateTime.UtcNow, (Int32)crlFlags); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public Int32 DeleteExpiredCRLs(DateTime notAfter) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { return(certAdmin.DeleteRow(_configString, (Int32)BulkRowRemovalOption.Expired, notAfter, (Int32)AdcsDbCRTable.CRL, 0)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public Int32 DeleteDatabaseRow(Int32 requestID, AdcsDbCRTable table = AdcsDbCRTable.Request) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { return(certAdmin.DeleteRow(_configString, 0, new DateTime(), (Int32)table, requestID)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public void RevokeRequest(String serialNumber, DateTime?revocationDate = null, AdcsCrlReason reason = AdcsCrlReason.Unspecified) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { certAdmin.RevokeCertificate(_configString, serialNumber, (Int32)reason, revocationDate ?? DateTime.UtcNow); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public void DenyRequest(Int32 requestID) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { certAdmin.DenyRequest(_configString, requestID); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public AdcsPropCertState ApproveRequest(Int32 requestID) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { return((AdcsPropCertState)certAdmin.ResubmitRequest(_configString, requestID)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public Int32 DeleteLastUpdatedRequests(DateTime notAfter) { ICertAdmin2 certAdmin = new CCertAdminClass(); try { return(certAdmin.DeleteRow(_configString, (Int32)BulkRowRemovalOption.LastChanged, notAfter, (Int32)AdcsDbCRTable.Request, 0)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
void set_property(String propName, Object propValue) { if (FromPolicy) { return; } if (propValue == null) { return; } CX509PolicyServerListManager serverManager = new CX509PolicyServerListManager(); X509CertificateEnrollmentContext context = UserContext ? X509CertificateEnrollmentContext.ContextUser : X509CertificateEnrollmentContext.ContextMachine; try { serverManager.Initialize(context, PolicyServerUrlFlags.PsfLocationRegistry); IEnumerator enumerator = serverManager.GetEnumerator(); do { if (enumerator.Current != null) { if (((IX509PolicyServerUrl)enumerator.Current).GetStringProperty(PolicyServerUrlPropertyID.PsPolicyID) == PolicyId) { switch (propName) { case "Name": ((IX509PolicyServerUrl)enumerator.Current).SetStringProperty(PolicyServerUrlPropertyID.PsFriendlyName, (String)propValue); break; case "Priority": ((IX509PolicyServerUrl)enumerator.Current).Cost = (UInt32)propValue; break; case "Authentication": ((IX509PolicyServerUrl)enumerator.Current).AuthFlags = (X509EnrollmentAuthFlags)propValue; break; case "Flags": ((IX509PolicyServerUrl)enumerator.Current).Flags = (PolicyServerUrlFlags)propValue; break; } ((IX509PolicyServerUrl)enumerator.Current).UpdateRegistry(context); CryptographyUtils.ReleaseCom(serverManager); return; } } } while (enumerator.MoveNext()); } finally { CryptographyUtils.ReleaseCom(serverManager); } }
/// <summary> /// Releases unmanaged resources held by the object. /// </summary> public void Dispose() { Name = null; configString = null; CACertificate = null; SigningCertificate = null; if (OcspConfig != null) { CryptographyUtils.ReleaseCom(OcspConfig); OcspConfig = null; IsDisposed = true; } }
internal CspProviderAlgorithmInfo(ICspAlgorithm alg) { Name = alg.Name; LongName = alg.LongName; AlgorithmType = (AlgorithmTypeEnum)alg.Type; AlgorithmOperations = (AlgorithmOperationsEnum)alg.Operations; DefaultLength = alg.DefaultLength; MinLength = alg.MinLength; MaxLength = alg.MaxLength; IncrementLength = alg.IncrementLength; IsValid = alg.Valid; CryptographyUtils.ReleaseCom(alg); }
internal OcspResponderRevocationConfiguration(String computerName, IOCSPCAConfiguration config) { ComputerName = computerName; Name = config.Identifier; CACertificate = new X509Certificate2((Byte[])config.CACertificate); try { String clsid = config.ProviderCLSID; } catch { config.ProviderCLSID = "{4956d17f-88fd-4198-b287-1e6e65883b19}"; } try { ConfigString = config.CAConfig; } catch { } try { CryptoProviderName = config.CSPName; } catch { } readProperties(config); CryptographyUtils.ReleaseCom(config); }
String readActiveConfig() { ICertAdmin2 certAdmin = new CCertAdminClass(); try { String active = (String)certAdmin.GetConfigEntry(ComputerName, String.Empty, "Active"); IsAccessible = true; return(active); } catch { IsAccessible = false; } finally { CryptographyUtils.ReleaseCom(certAdmin); } return(null); }
public static CspProviderInfoCollection GetProviderInfo() { if (!CryptographyUtils.TestCNGCompat()) { throw new PlatformNotSupportedException(); } var csps = new CCspInformations(); csps.AddAvailableCsps(); var retValue = new CspProviderInfoCollection(); retValue.AddRange((from ICspInformation csp in csps select new CspProviderInfo(csp)).ToArray()); CryptographyUtils.ReleaseCom(csps); return(retValue); }
public static CspProviderInfoCollection GetProviderInfo(String name) { if (!CryptographyUtils.TestCNGCompat()) { throw new PlatformNotSupportedException(); } var csps = new CCspInformations(); csps.AddAvailableCsps(); var retValue = new CspProviderInfoCollection { new CspProviderInfo(csps.ItemByName[name]) }; CryptographyUtils.ReleaseCom(csps); return(retValue); }
internal CspProviderInfo(ICspInformation csp) { Name = csp.Name; Type = (CspProviderType)csp.Type; IsHardware = csp.IsHardwareDevice; IsSoftware = csp.IsSoftwareDevice; IsRemovable = csp.IsRemovable; IsSmartCard = csp.IsSmartCard; IsLegacy = csp.LegacyCsp; HardwareRNG = csp.HasHardwareRandomNumberGenerator; KeyContainerLength = csp.MaxKeyContainerNameLength; KeySpec = (X509KeySpecFlags)csp.KeySpec; Version = csp.Version; IsValid = csp.Valid; _algorithms.AddRange(from ICspAlgorithm alg in csp.CspAlgorithms select new CspProviderAlgorithmInfo(alg)); CryptographyUtils.ReleaseCom(csp); }
/// <summary> /// Writes this object to a securable object's Access Control List. /// </summary> /// <exception cref="ServerUnavailableException"> /// The target Online Responder server could not be contacted via remote registry and RPC protocol. /// </exception> public void SetObjectSecurity() { var ocspAdmin = new OCSPAdminClass(); try { ocspAdmin.SetSecurity(ComputerName, GetSecurityDescriptorSddlForm(AccessControlSections.All)); } catch (COMException cex) { if (cex.ErrorCode == Error.RpcUnavailableException) { var e = new ServerUnavailableException(ComputerName); e.Data.Add(nameof(e.Source), OfflineSource.DCOM); throw e; } } finally { CryptographyUtils.ReleaseCom(ocspAdmin); } }
/// <summary> /// Releases unmanaged resources held by the object. /// </summary> public void Dispose() { ComputerName = null; ServiceStatus = ServiceControllerStatus.Stopped; //ProvConfig = null; ActiveConfigurations = null; ArrayController = null; ArrayMembers = null; maxNumOfCacheEntries = numOfThreads = 0; AuditFilter = 0; if (OcspAdmin != null) { CryptographyUtils.ReleaseCom(OcspAdmin); OcspAdmin = null; IsDisposed = true; } }
/// <summary> /// Updates KRA configuration by writing KRA certificates to Certification Authority. The method writes all certificates contained in /// <see cref="Certificate"/> property. /// </summary> /// <param name="restart"> /// Indiciates whether to restart certificate services to immediately apply changes. Updated settings has no effect until /// CA service is restarted. /// </param> /// <exception cref="UnauthorizedAccessException"> /// The caller do not have sufficient permissions to make changes in the CA configuration. /// </exception> /// <exception cref="ServerUnavailableException"> /// The target CA server could not be contacted via RPC/DCOM transport. /// </exception> /// <remarks> /// <para>This method do not check whether the certificates in <see cref="Certificate"/> property are valid. /// The caller is responsible to check if the certificates are time-valid, trusted and not revoked.</para> /// </remarks> /// <returns> /// <strong>True</strong> if configuration was changed. If an object was not modified since it was instantiated, configuration is not updated /// and the method returns <strong>False</strong>. /// </returns> /// <remarks>The caller must have <strong>Administrator</strong> permissions on the target CA server.</remarks> public Boolean SetInfo(Boolean restart) { if (IsModified) { if (!CertificateAuthority.Ping(ComputerName)) { ServerUnavailableException e = new ServerUnavailableException(DisplayName); e.Data.Add(nameof(e.Source), OfflineSource.DCOM); throw e; } CCertAdmin CertAdmin = new CCertAdmin(); try { if (_certs.Count > 0) { Int32 kracount = (Int32)CertAdmin.GetCAProperty(ConfigString, CertAdmConst.CrPropKracertcount, 0, CertAdmConst.ProptypeLong, 0); if (kracount > 0) { CertAdmin.SetCAProperty(ConfigString, CertAdmConst.CrPropKracertcount, 0, CertAdmConst.ProptypeLong, 0); } for (Int32 index = 0; index < _certs.Count; index++) { String der = CryptographyUtils.EncodeDerString(_certs[index].RawData); CertAdmin.SetCAProperty(ConfigString, CertAdmConst.CrPropKracert, index, CertAdmConst.ProptypeBinary, der); } CertAdmin.SetCAProperty(ConfigString, CertAdmConst.CrPropKracertusedcount, 0, CertAdmConst.ProptypeLong, _certs.Count); } else { CertAdmin.SetCAProperty(ConfigString, CertAdmConst.CrPropKracertcount, 0, CertAdmConst.ProptypeLong, 0); CertAdmin.SetCAProperty(ConfigString, CertAdmConst.CrPropKracertusedcount, 0, CertAdmConst.ProptypeLong, 0); } } catch (Exception e) { throw Error.ComExceptionHandler(e); } finally { CryptographyUtils.ReleaseCom(CertAdmin); } IsModified = false; if (restart) { CertificateAuthority.Restart(ComputerName); } return(true); } return(false); }
/// <inheritdoc /> public Int32 ImportCertificate(X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } ICertAdmin2 certAdmin = new CCertAdminClass(); try { return(certAdmin.ImportCertificate( _configString, CryptographyUtils.EncodeDerString(certificate.RawData), (Int32)ImportForeignOption.AllowForeign)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <inheritdoc /> public AdcsPropCertState GetCertificateStatus(String serialNumber) { if (serialNumber == null) { throw new ArgumentNullException(nameof(serialNumber)); } if (String.IsNullOrWhiteSpace(serialNumber)) { throw new ArgumentException("'serialNumber' parameter cannot be empty string"); } ICertAdmin2 certAdmin = new CCertAdminClass(); try { return((AdcsPropCertState)certAdmin.IsValidCertificate(_configString, serialNumber)); } finally { CryptographyUtils.ReleaseCom(certAdmin); } }
/// <summary> /// Enumerates registered Enterprise Certification Authorities from the current Active Directory forest. /// </summary> /// <param name="findType">Specifies CA object search type. The search type can be either: <strong>Name</strong> /// or <strong>Server</strong>.</param> /// <param name="findValue">Specifies search pattern for a type specifed in <strong>findType</strong> argument. /// Wildcard characters: * and ? are accepted.</param> /// <returns>Enterprise Certification Authority collection.</returns> public static CertificateAuthority[] EnumEnterpriseCAs(String findType, String findValue) { if (!DsUtils.Ping()) { throw new Exception("Non-domain environments are not supported."); } List <CertificateAuthority> CAs = new List <CertificateAuthority>(); CCertConfig certConfig = new CCertConfig(); while (certConfig.Next() >= 0) { Int32 flags = Convert.ToInt32(certConfig.GetField("Flags")); if ((flags & 1) == 0) { continue; } Wildcard wildcard = new Wildcard(findValue, RegexOptions.IgnoreCase); switch (findType.ToLower()) { case "name": if (!wildcard.IsMatch(certConfig.GetField("CommonName"))) { continue; } break; case "server": if (!wildcard.IsMatch(certConfig.GetField("Server"))) { continue; } break; default: throw new ArgumentException("The value for 'findType' must be either 'Name' or 'Server'."); } CAs.Add(new CertificateAuthority(certConfig.GetField("Server"), certConfig.GetField("SanitizedName"))); } CryptographyUtils.ReleaseCom(certConfig); return(CAs.ToArray()); }
/// <summary> /// Attempts to check Online Responder's management interfaces availability. /// </summary> /// <param name="computerName"></param> /// <returns> /// <strong>True</strong> if management interfaces are available and accessible, otherwise <strong>False</strong>. /// </returns> /// <exception cref="ArgumentNullException"><strong>computerName</strong> parameter is null or empty string.</exception> public static Boolean Ping(String computerName) { if (String.IsNullOrEmpty(computerName)) { throw new ArgumentNullException(nameof(computerName)); } OCSPAdmin ocspAdmin = null; try { ocspAdmin = new OCSPAdmin(); ocspAdmin.Ping(computerName); return(true); } catch { return(false); } finally { if (ocspAdmin != null) { CryptographyUtils.ReleaseCom(ocspAdmin); } } }