private void CreateCertContext(string name, DateTime start, DateTime expire) { CriticalAllocHandle providerInfo = this.GetProviderInfo(); CriticalAllocHandle handle2 = GetSha1AlgorithmId(); SystemTime pStartTime = new SystemTime(start); SystemTime pEndTime = new SystemTime(expire); CertificateName name2 = new CertificateName(name); using (CryptoApiBlob blob = name2.GetCryptoApiBlob()) { using (providerInfo) { using (handle2) { this.cert = CertCreateSelfSignCertificate(this.keyContainer, blob.GetMemoryForPinning(), SelfSignFlags.None, (IntPtr)providerInfo, (IntPtr)handle2, ref pStartTime, ref pEndTime, IntPtr.Zero); if (this.cert.IsInvalid) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } if (!CertSetCertificateContextProperty(this.cert, 1, 0, this.key)) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } } } } }
public bool Authenticate(ServiceSecurityContext context, byte[] message) { Claim claim = null; if (context == null) { return(authenticationMode == PeerAuthenticationMode.None); } if (authenticationMode == PeerAuthenticationMode.Password) { if (!(context != null)) { throw Fx.AssertAndThrow("No SecurityContext attached in security mode!"); } claim = FindClaim(context); return(PeerSecurityHelpers.Authenticate(claim, this.credManager.Password, message)); } else { if (message != null) { PeerExceptionHelper.ThrowInvalidOperation_UnexpectedSecurityTokensDuringHandshake(); } return(true); } }
public SecurityProtocolFactory GetProtocolFactory <TChannel>() { if (securityProtocolFactory == null) { CreateSecurityProtocolFactory(); } if (typeof(TChannel) == typeof(IOutputChannel)) { if (enableSigning && securityProtocolFactory.ForwardProtocolFactory is PeerDoNothingSecurityProtocolFactory) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication); } return(securityProtocolFactory.ForwardProtocolFactory); } else if (typeof(TChannel) == typeof(IInputChannel)) { if (enableSigning && securityProtocolFactory.ReverseProtocolFactory is PeerDoNothingSecurityProtocolFactory) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication); } return(securityProtocolFactory.ReverseProtocolFactory); } else { if (enableSigning && ((securityProtocolFactory.ReverseProtocolFactory is PeerDoNothingSecurityProtocolFactory) || (securityProtocolFactory.ForwardProtocolFactory is PeerDoNothingSecurityProtocolFactory))) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication); } return(securityProtocolFactory); } }
public void CheckIfCompatibleNodeSettings(object other) { string mismatch = null; PeerSecurityManager that = other as PeerSecurityManager; if (that == null) { mismatch = PeerBindingPropertyNames.Security; } else if (this.authenticationMode != that.authenticationMode) { mismatch = PeerBindingPropertyNames.SecurityDotMode; } else if (this.authenticationMode == PeerAuthenticationMode.None) { return; } else if (!this.tokenManager.Equals(that.tokenManager)) { if (this.credManager != null) { this.credManager.CheckIfCompatible(that.credManager); } else { Fx.Assert(typeof(PeerSecurityCredentialsManager.PeerClientSecurityTokenManager).IsAssignableFrom(tokenManager.GetType()), ""); mismatch = PeerBindingPropertyNames.Credentials; } } if (mismatch != null) { PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(mismatch); } }
public override PeerResolver CreatePeerResolver() { if (resolver == null) { if (address == null || ((binding == null) && (String.IsNullOrEmpty(this.bindingSection) || String.IsNullOrEmpty(this.bindingConfiguration)))) { PeerExceptionHelper.ThrowArgument_InsufficientResolverSettings(); } if (binding == null) { this.binding = ConfigLoader.LookupBinding(this.bindingSection, this.bindingConfiguration); if (binding == null) { PeerExceptionHelper.ThrowArgument_InsufficientResolverSettings(); } } resolver = new PeerDefaultCustomResolverClient(); } if (resolver != null) { resolver.Initialize(address, binding, credentials, this.referralPolicy); if (resolver is PeerDefaultCustomResolverClient) { (resolver as PeerDefaultCustomResolverClient).BindingName = this.bindingSection; (resolver as PeerDefaultCustomResolverClient).BindingConfigurationName = this.bindingConfiguration; } } return(resolver); }
static PeerSecurityCredentialsManager GetCredentialsManager(PeerAuthenticationMode mode, bool signing, BindingContext context) { if (mode == PeerAuthenticationMode.None && !signing) { return(null); } ClientCredentials clientCredentials = context.BindingParameters.Find <ClientCredentials>(); if (clientCredentials != null) { return(new PeerSecurityCredentialsManager(clientCredentials.Peer, mode, signing)); } ServiceCredentials serviceCredentials = context.BindingParameters.Find <ServiceCredentials>(); if (serviceCredentials != null) { return(new PeerSecurityCredentialsManager(serviceCredentials.Peer, mode, signing)); } SecurityCredentialsManager credman = context.BindingParameters.Find <SecurityCredentialsManager>(); if (credman == null) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Credentials); } return(new PeerSecurityCredentialsManager(credman.CreateSecurityTokenManager(), mode, signing)); }
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); }
void GenerateKeys() { // generate the key container to put the key in if (!CryptAcquireContext(out keyContainer, keyContainerName, null, ProviderType.RsaSecureChannel, ContextFlags.NewKeySet | ContextFlags.Silent)) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(keyContainer); keyContainer = null; PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(new Win32Exception(error)); } // generate the key if (!CryptGenKey(keyContainer, AlgorithmType.KeyExchange, KeyFlags.Exportable2k, out key)) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(key); key = null; PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(new Win32Exception(error)); } }
private static void ValidateCredentialSettings(PeerAuthenticationMode authenticationMode, bool signMessages, PeerCredential credential) { if ((authenticationMode != PeerAuthenticationMode.None) || signMessages) { X509CertificateValidator validator; switch (authenticationMode) { case PeerAuthenticationMode.Password: if (string.IsNullOrEmpty(credential.MeshPassword)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Password); } break; case PeerAuthenticationMode.MutualCertificate: if (credential.Certificate == null) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Certificate); } if (!credential.PeerAuthentication.TryGetCertificateValidator(out validator)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.PeerAuthentication); } break; } if (signMessages && !credential.MessageSenderAuthentication.TryGetCertificateValidator(out validator)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication); } } }
private byte[] GetEncodedName() { int pcbEncoded = 0; StringBuilder ppszError = null; CertStrToName(CertEncodingType.PKCS7AsnEncoding | CertEncodingType.X509AsnEncoding, this.DistinguishedName, StringType.ReverseFlag | StringType.OIDNameString, IntPtr.Zero, null, ref pcbEncoded, ref ppszError); byte[] pbEncoded = new byte[pcbEncoded]; if (!CertStrToName(CertEncodingType.PKCS7AsnEncoding | CertEncodingType.X509AsnEncoding, this.DistinguishedName, StringType.ReverseFlag | StringType.OIDNameString, IntPtr.Zero, pbEncoded, ref pcbEncoded, ref ppszError)) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } return(pbEncoded); }
void CreateCertContext(string name, DateTime start, DateTime expire) { CriticalAllocHandle provInfo; CriticalAllocHandle algorithmId; provInfo = GetProviderInfo(); algorithmId = GetSha1AlgorithmId(); // convert the times to SystemTime structures SystemTime beginTime = new SystemTime(start); SystemTime expireTime = new SystemTime(expire); // convert the name into a X500 name CertificateName certName = new CertificateName(name); using (CryptoApiBlob nameBlob = certName.GetCryptoApiBlob()) { using (provInfo) { using (algorithmId) { cert = CertCreateSelfSignCertificate(keyContainer, nameBlob.GetMemoryForPinning(), SelfSignFlags.None, provInfo, algorithmId, ref beginTime, ref expireTime, IntPtr.Zero); if (cert.IsInvalid) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } // if (!CertSetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, 0, provInfo)) // PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); if (!CertSetCertificateContextProperty(cert, CERT_KEY_SPEC_PROP_ID, 0, key)) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } } } } }
public void CheckIfCompatible(PeerSecurityCredentialsManager that) { if (that == null) { PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(PeerBindingPropertyNames.Credentials); } if (this.mode != PeerAuthenticationMode.None) { if ((this.mode == PeerAuthenticationMode.Password) && (this.Password != that.Password)) { PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(PeerBindingPropertyNames.Password); } if (!this.Certificate.Equals((X509Certificate)that.Certificate)) { PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(PeerBindingPropertyNames.Certificate); } } }
private void Export() { using (CertificateStoreHandle handle = CertOpenStore(new IntPtr(2), 0, IntPtr.Zero, 0, IntPtr.Zero)) { StoreCertificateHandle handle2; if (!CertAddCertificateContextToStore(handle, this.cert, AddDisposition.ReplaceExisting, out handle2)) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(handle2); PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(new Win32Exception(error)); } using (handle2) { CryptoApiBlob blob = new CryptoApiBlob(); CryptoApiBlob.InteropHelper memoryForPinning = blob.GetMemoryForPinning(); GCHandle handle3 = GCHandle.Alloc(memoryForPinning, GCHandleType.Pinned); try { if (!PFXExportCertStoreEx(handle, handle3.AddrOfPinnedObject(), this.password, IntPtr.Zero, PfxExportFlags.ExportPrivateKeys | PfxExportFlags.ReportNotAbleToExportPrivateKey | PfxExportFlags.ReportNoPrivateKey)) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } int size = memoryForPinning.size; handle3.Free(); blob.AllocateBlob(size); handle3 = GCHandle.Alloc(blob.GetMemoryForPinning(), GCHandleType.Pinned); if (!PFXExportCertStoreEx(handle, handle3.AddrOfPinnedObject(), this.password, IntPtr.Zero, PfxExportFlags.ExportPrivateKeys | PfxExportFlags.ReportNotAbleToExportPrivateKey | PfxExportFlags.ReportNoPrivateKey)) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } this.exportedBytes = blob.GetBytes(); } finally { handle3.Free(); if (blob != null) { blob.Dispose(); } } } } }
static public PeerSecurityManager Create(PeerAuthenticationMode authenticationMode, bool signMessages, BindingContext context, XmlDictionaryReaderQuotas readerQuotas) { if (authenticationMode == PeerAuthenticationMode.None && !signMessages) { return(CreateDummy()); } // test FIPS mode if (authenticationMode == PeerAuthenticationMode.Password) { try { using (HMACSHA256 algo = new HMACSHA256()) { using (SHA256Managed sha = new SHA256Managed()) { } } } catch (InvalidOperationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); PeerExceptionHelper.ThrowInvalidOperation_InsufficientCryptoSupport(e); } } ChannelProtectionRequirements reqs = context.BindingParameters.Find <ChannelProtectionRequirements>(); PeerSecurityCredentialsManager credman = GetCredentialsManager(authenticationMode, signMessages, context); if (credman.Credential != null) { //for compatibility with existing code: ValidateCredentialSettings(authenticationMode, signMessages, credman.Credential); } PeerSecurityManager manager = Create(authenticationMode, signMessages, credman, reqs, readerQuotas); credman.Parent = manager; manager.ApplyAuditBehaviorSettings(context); return(manager); }
public void CheckIfCompatibleNodeSettings(object other) { string propertyName = null; PeerSecurityManager manager = other as PeerSecurityManager; if (manager == null) { propertyName = PeerBindingPropertyNames.Security; } else if (this.authenticationMode != manager.authenticationMode) { propertyName = PeerBindingPropertyNames.SecurityDotMode; } else { if (this.authenticationMode == PeerAuthenticationMode.None) { return; } if (!this.tokenManager.Equals(manager.tokenManager)) { if (this.credManager != null) { this.credManager.CheckIfCompatible(manager.credManager); } else { propertyName = PeerBindingPropertyNames.Credentials; } } } if (propertyName != null) { PeerExceptionHelper.ThrowInvalidOperation_PeerConflictingPeerNodeSettings(propertyName); } }
static public PeerSecurityManager Create(PeerAuthenticationMode authenticationMode, bool messageAuthentication, PeerSecurityCredentialsManager credman, ChannelProtectionRequirements reqs, XmlDictionaryReaderQuotas readerQuotas) { PeerSecurityManager manager = null; X509CertificateValidator connectionValidator = null; X509CertificateValidator messageValidator = null; PeerCredential credential = credman.Credential; if (null == credential && credman == null) { if (authenticationMode != PeerAuthenticationMode.None || messageAuthentication) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Credentials); } //create one that doesnt have any credentials in it. return(CreateDummy()); } manager = new PeerSecurityManager(authenticationMode, messageAuthentication); manager.credManager = credman; manager.password = credman.Password; manager.readerQuotas = readerQuotas; if (reqs != null) { manager.protection = new ChannelProtectionRequirements(reqs); } manager.tokenManager = credman.CreateSecurityTokenManager(); if (credential == null) { return(manager); } switch (authenticationMode) { case PeerAuthenticationMode.None: break; case PeerAuthenticationMode.Password: { manager.password = credential.MeshPassword; if (String.IsNullOrEmpty(manager.credManager.Password)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Password); } connectionValidator = X509CertificateValidator.None; } break; case PeerAuthenticationMode.MutualCertificate: { if (manager.credManager.Certificate == null) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Certificate); } if (!credential.PeerAuthentication.TryGetCertificateValidator(out connectionValidator)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.PeerAuthentication); } } break; } if (messageAuthentication) { if (credential.MessageSenderAuthentication != null) { if (!credential.MessageSenderAuthentication.TryGetCertificateValidator(out messageValidator)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication); } } else { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication); } } return(manager); }
void Export() { Fx.Assert(this.exportedBytes == null, "calling Export twice!!"); // create a temporary store to export using (CertificateStoreHandle store = CertOpenStore(new IntPtr(CERT_STORE_PROV_MEMORY), 0, IntPtr.Zero, 0, IntPtr.Zero)) { // add the certificate to the store StoreCertificateHandle addedCert; if (!CertAddCertificateContextToStore(store, cert, AddDisposition.ReplaceExisting, out addedCert)) { int error = Marshal.GetLastWin32Error(); Utility.CloseInvalidOutSafeHandle(addedCert); PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(new Win32Exception(error)); } using (addedCert) { // Translate to a PFX CryptoApiBlob pfxBlob = new CryptoApiBlob(); CryptoApiBlob.InteropHelper blob = pfxBlob.GetMemoryForPinning(); GCHandle pfxHandle = GCHandle.Alloc(blob, GCHandleType.Pinned); try { // first figure out the storage space necessary bool result = PFXExportCertStoreEx(store, pfxHandle.AddrOfPinnedObject(), password, IntPtr.Zero, PfxExportFlags.ExportPrivateKeys | PfxExportFlags.ReportNoPrivateKey | PfxExportFlags.ReportNotAbleToExportPrivateKey); if (!result) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } int storageSize = blob.size; pfxHandle.Free(); pfxBlob.AllocateBlob(storageSize); blob = pfxBlob.GetMemoryForPinning(); pfxHandle = GCHandle.Alloc(blob, GCHandleType.Pinned); // now do the translation if (!PFXExportCertStoreEx(store, pfxHandle.AddrOfPinnedObject(), password, IntPtr.Zero, PfxExportFlags.ExportPrivateKeys | PfxExportFlags.ReportNoPrivateKey | PfxExportFlags.ReportNotAbleToExportPrivateKey)) { PeerExceptionHelper.ThrowInvalidOperation_PeerCertGenFailure(PeerExceptionHelper.GetLastException()); } exportedBytes = pfxBlob.GetBytes(); } finally { if (pfxHandle != null) { pfxHandle.Free(); } if (pfxBlob != null) { pfxBlob.Dispose(); } } } } }
public static PeerSecurityManager Create(PeerAuthenticationMode authenticationMode, bool messageAuthentication, PeerSecurityCredentialsManager credman, ChannelProtectionRequirements reqs, XmlDictionaryReaderQuotas readerQuotas) { PeerSecurityManager manager = null; X509CertificateValidator none = null; X509CertificateValidator validator2 = null; PeerCredential credential = credman.Credential; if ((credential == null) && (credman == null)) { if ((authenticationMode != PeerAuthenticationMode.None) || messageAuthentication) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Credentials); } return(CreateDummy()); } manager = new PeerSecurityManager(authenticationMode, messageAuthentication) { credManager = credman, password = credman.Password, readerQuotas = readerQuotas }; if (reqs != null) { manager.protection = new ChannelProtectionRequirements(reqs); } manager.tokenManager = credman.CreateSecurityTokenManager(); if (credential != null) { switch (authenticationMode) { case PeerAuthenticationMode.Password: manager.password = credential.MeshPassword; if (string.IsNullOrEmpty(manager.credManager.Password)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Password); } none = X509CertificateValidator.None; break; case PeerAuthenticationMode.MutualCertificate: if (manager.credManager.Certificate == null) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Certificate); } if (!credential.PeerAuthentication.TryGetCertificateValidator(out none)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.PeerAuthentication); } break; } if (messageAuthentication) { if (credential.MessageSenderAuthentication != null) { if (!credential.MessageSenderAuthentication.TryGetCertificateValidator(out validator2)) { PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication); } return(manager); } PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.MessageSenderAuthentication); } } return(manager); }