public HttpTransportSecurity()
 {
     this.clientCredentialType = DefaultClientCredentialType;
     this.proxyCredentialType = DefaultProxyCredentialType;
     this.realm = DefaultRealm;
     this.extendedProtectionPolicy = ChannelBindingUtility.DefaultPolicy;
 }
 internal SecurityProtocolFactory(SecurityProtocolFactory factory) : this()
 {
     if (factory == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("factory");
     }
     this.actAsInitiator         = factory.actAsInitiator;
     this.addTimestamp           = factory.addTimestamp;
     this.detectReplays          = factory.detectReplays;
     this.incomingAlgorithmSuite = factory.incomingAlgorithmSuite;
     this.maxCachedNonces        = factory.maxCachedNonces;
     this.maxClockSkew           = factory.maxClockSkew;
     this.outgoingAlgorithmSuite = factory.outgoingAlgorithmSuite;
     this.replayWindow           = factory.replayWindow;
     this.channelSupportingTokenAuthenticatorSpecification = new Collection <SupportingTokenAuthenticatorSpecification>(new List <SupportingTokenAuthenticatorSpecification>(factory.channelSupportingTokenAuthenticatorSpecification));
     this.scopedSupportingTokenAuthenticatorSpecification  = new Dictionary <string, ICollection <SupportingTokenAuthenticatorSpecification> >(factory.scopedSupportingTokenAuthenticatorSpecification);
     this.standardsManager                = factory.standardsManager;
     this.timestampValidityDuration       = factory.timestampValidityDuration;
     this.auditLogLocation                = factory.auditLogLocation;
     this.suppressAuditFailure            = factory.suppressAuditFailure;
     this.serviceAuthorizationAuditLevel  = factory.serviceAuthorizationAuditLevel;
     this.messageAuthenticationAuditLevel = factory.messageAuthenticationAuditLevel;
     if (factory.securityBindingElement != null)
     {
         this.securityBindingElement = (System.ServiceModel.Channels.SecurityBindingElement)factory.securityBindingElement.Clone();
     }
     this.securityTokenManager     = factory.securityTokenManager;
     this.privacyNoticeUri         = factory.privacyNoticeUri;
     this.privacyNoticeVersion     = factory.privacyNoticeVersion;
     this.endpointFilterTable      = factory.endpointFilterTable;
     this.extendedProtectionPolicy = factory.extendedProtectionPolicy;
 }
 protected HttpTransportBindingElement(HttpTransportBindingElement elementToBeCloned) : base(elementToBeCloned)
 {
     this.allowCookies               = elementToBeCloned.allowCookies;
     this.authenticationScheme       = elementToBeCloned.authenticationScheme;
     this.bypassProxyOnLocal         = elementToBeCloned.bypassProxyOnLocal;
     this.decompressionEnabled       = elementToBeCloned.decompressionEnabled;
     this.hostNameComparisonMode     = elementToBeCloned.hostNameComparisonMode;
     this.inheritBaseAddressSettings = elementToBeCloned.InheritBaseAddressSettings;
     this.keepAliveEnabled           = elementToBeCloned.keepAliveEnabled;
     this.maxBufferSize              = elementToBeCloned.maxBufferSize;
     this.maxBufferSizeInitialized   = elementToBeCloned.maxBufferSizeInitialized;
     this.method       = elementToBeCloned.method;
     this.proxyAddress = elementToBeCloned.proxyAddress;
     this.proxyAuthenticationScheme = elementToBeCloned.proxyAuthenticationScheme;
     this.realm        = elementToBeCloned.realm;
     this.transferMode = elementToBeCloned.transferMode;
     this.unsafeConnectionNtlmAuthentication = elementToBeCloned.unsafeConnectionNtlmAuthentication;
     this.useDefaultWebProxy       = elementToBeCloned.useDefaultWebProxy;
     this.webProxy                 = elementToBeCloned.webProxy;
     this.extendedProtectionPolicy = elementToBeCloned.ExtendedProtectionPolicy;
     if (elementToBeCloned.anonymousUriPrefixMatcher != null)
     {
         this.anonymousUriPrefixMatcher = new HttpAnonymousUriPrefixMatcher(elementToBeCloned.anonymousUriPrefixMatcher);
     }
 }
        internal void ValidateCreateContext(
            string package,
            NetworkCredential credential,
            string servicePrincipalName,
            ExtendedProtectionPolicy policy,
            ProtectionLevel protectionLevel,
            TokenImpersonationLevel impersonationLevel)
        {
            if (policy != null)
            {
                // One of these must be set if EP is turned on
                if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null)
                {
                    throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, nameof(policy));
                }

                _extendedProtectionPolicy = policy;
            }
            else
            {
                _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
            }

            ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel);
        }
 public TcpTransportSecurity()
 {
     this.clientCredentialType = DefaultClientCredentialType;
     this.protectionLevel = DefaultProtectionLevel;
     this.extendedProtectionPolicy = ChannelBindingUtility.DefaultPolicy;
     this.sslProtocols = TransportDefaults.SslProtocols;
 }
        public void HttpTransportSecurity_DisableTransportAuthentication()
        {
            ExtendedProtectionPolicy policy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
            HttpTransportSecurity security = new HttpTransportSecurity()
            {
                ClientCredentialType = HttpClientCredentialType.Basic,
                ProxyCredentialType = HttpProxyCredentialType.Basic,
                Realm = "MyRealm",
                ExtendedProtectionPolicy = policy
            };
            HttpTransportBindingElement binding = new HttpTransportBindingElement();

            // first configure it
            security.ConfigureTransportAuthentication(binding);

            Assert.AreEqual(AuthenticationSchemes.Basic, binding.AuthenticationScheme, "AuthenticationScheme failed to init");
            Assert.AreEqual(AuthenticationSchemes.Basic, binding.ProxyAuthenticationScheme, "ProxyAuthenticationScheme failed to init");
            Assert.AreEqual("MyRealm", binding.Realm, "Realm failed to init");
            Assert.AreEqual(policy, binding.ExtendedProtectionPolicy, "ExtendedProtectionPolicy failed to init");

            // then disable it
            security.DisableTransportAuthentication(binding);

            Assert.AreEqual(AuthenticationSchemes.Anonymous, binding.AuthenticationScheme, "AuthenticationScheme failed to init");
            Assert.AreEqual(AuthenticationSchemes.Anonymous, binding.ProxyAuthenticationScheme, "ProxyAuthenticationScheme failed to init");
            Assert.AreEqual(string.Empty, binding.Realm, "Realm failed to init");
            Assert.AreEqual(policy, binding.ExtendedProtectionPolicy, "ExtendedProtectionPolicy failed to init");
        }
Esempio n. 7
0
        //does not validate the ExtendedProtectionPolicy.CustomServiceNames collections on the policies
        public static bool AreEqual(ExtendedProtectionPolicy policy1, ExtendedProtectionPolicy policy2)
        {
            Fx.Assert(policy1 != null, "policy1 param cannot be null");
            Fx.Assert(policy2 != null, "policy2 param cannot be null");

            if (policy1.PolicyEnforcement == PolicyEnforcement.Never && policy2.PolicyEnforcement == PolicyEnforcement.Never)
            {
                return true;
            }

            if (policy1.PolicyEnforcement != policy2.PolicyEnforcement)
            {
                return false;
            }

            if (policy1.ProtectionScenario != policy2.ProtectionScenario)
            {
                return false;
            }

            if (policy1.CustomChannelBinding != policy2.CustomChannelBinding)
            {
                return false;
            }

            return true;
        }
 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
 {
     if (destinationType == typeof(InstanceDescriptor))
     {
         ExtendedProtectionPolicy policy = value as ExtendedProtectionPolicy;
         if (policy != null)
         {
             Type[]   typeArray;
             object[] objArray;
             if (policy.PolicyEnforcement == PolicyEnforcement.Never)
             {
                 typeArray = new Type[] { typeof(PolicyEnforcement) };
                 objArray  = new object[] { PolicyEnforcement.Never };
             }
             else
             {
                 typeArray = new Type[] { typeof(PolicyEnforcement), typeof(ProtectionScenario), typeof(ICollection) };
                 object[] array = null;
                 if ((policy.CustomServiceNames != null) && (policy.CustomServiceNames.Count > 0))
                 {
                     array = new object[policy.CustomServiceNames.Count];
                     ((ICollection)policy.CustomServiceNames).CopyTo(array, 0);
                 }
                 objArray = new object[] { policy.PolicyEnforcement, policy.ProtectionScenario, array };
             }
             return(new InstanceDescriptor(typeof(ExtendedProtectionPolicy).GetConstructor(typeArray), objArray));
         }
     }
     return(base.ConvertTo(context, culture, value, destinationType));
 }
Esempio n. 9
0
 protected TcpTransportBindingElement(TcpTransportBindingElement elementToBeCloned) : base(elementToBeCloned)
 {
     this.listenBacklog            = elementToBeCloned.listenBacklog;
     this.portSharingEnabled       = elementToBeCloned.portSharingEnabled;
     this.teredoEnabled            = elementToBeCloned.teredoEnabled;
     this.connectionPoolSettings   = elementToBeCloned.connectionPoolSettings.Clone();
     this.extendedProtectionPolicy = elementToBeCloned.ExtendedProtectionPolicy;
 }
Esempio n. 10
0
 public TcpTransportBindingElement()
 {
     this.listenBacklog            = 10;
     this.portSharingEnabled       = false;
     this.teredoEnabled            = false;
     this.connectionPoolSettings   = new TcpConnectionPoolSettings();
     this.extendedProtectionPolicy = ChannelBindingUtility.DefaultPolicy;
 }
 internal HttpListenerContext(HttpListener httpListener, RequestContextBase memoryBlob)
 {
     if (Logging.On) Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "httpListener#" + ValidationHelper.HashString(httpListener) + " requestBlob=" + ValidationHelper.HashString((IntPtr) memoryBlob.RequestBlob));
     m_Listener = httpListener;
     m_Request = new HttpListenerRequest(this, memoryBlob);
     m_AuthenticationSchemes = httpListener.AuthenticationSchemes;
     m_ExtendedProtectionPolicy = httpListener.ExtendedProtectionPolicy;
     GlobalLog.Print("HttpListenerContext#" + ValidationHelper.HashString(this) + "::.ctor() HttpListener#" + ValidationHelper.HashString(m_Listener) + " HttpListenerRequest#" + ValidationHelper.HashString(m_Request));
 }
Esempio n. 12
0
 internal void ValidateCreateContext(string package,
                                     NetworkCredential credential,
                                     string servicePrincipalName,
                                     ExtendedProtectionPolicy policy,
                                     ProtectionLevel protectionLevel,
                                     TokenImpersonationLevel impersonationLevel)
 {
     throw new PlatformNotSupportedException();
 }
 public ExtendedProtectionPolicyHelper(System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding, ExtendedProtectionPolicy extendedProtectionPolicy)
 {
     this._channelBinding = channelBinding;
     this._serviceNameCollection = null;
     this._checkServiceBinding = true;
     if (extendedProtectionPolicy != null)
     {
         this._policyEnforcement = extendedProtectionPolicy.PolicyEnforcement;
         this._protectionScenario = extendedProtectionPolicy.ProtectionScenario;
         this._serviceNameCollection = extendedProtectionPolicy.CustomServiceNames;
     }
     if (this._policyEnforcement == System.Security.Authentication.ExtendedProtection.PolicyEnforcement.Never)
     {
         this._checkServiceBinding = false;
     }
 }
 public static bool AreEqual(ExtendedProtectionPolicy policy1, ExtendedProtectionPolicy policy2)
 {
     if ((policy1.PolicyEnforcement != PolicyEnforcement.Never) || (policy2.PolicyEnforcement != PolicyEnforcement.Never))
     {
         if (policy1.PolicyEnforcement != policy2.PolicyEnforcement)
         {
             return false;
         }
         if (policy1.ProtectionScenario != policy2.ProtectionScenario)
         {
             return false;
         }
         if (policy1.CustomChannelBinding != policy2.CustomChannelBinding)
         {
             return false;
         }
     }
     return true;
 }
 public HttpTransportBindingElement()
 {
     this.allowCookies           = false;
     this.authenticationScheme   = AuthenticationSchemes.Anonymous;
     this.bypassProxyOnLocal     = false;
     this.decompressionEnabled   = true;
     this.hostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
     this.keepAliveEnabled       = true;
     this.maxBufferSize          = 0x10000;
     this.method = string.Empty;
     this.proxyAuthenticationScheme = AuthenticationSchemes.Anonymous;
     this.proxyAddress = null;
     this.realm        = "";
     this.transferMode = System.ServiceModel.TransferMode.Buffered;
     this.unsafeConnectionNtlmAuthentication = false;
     this.useDefaultWebProxy       = true;
     this.webProxy                 = null;
     this.extendedProtectionPolicy = ChannelBindingUtility.DefaultPolicy;
 }
        public static void InitializeFrom(ExtendedProtectionPolicy source, ExtendedProtectionPolicyElement destination)
        {
            if (!IsDefaultPolicy(source))
            {
                destination.PolicyEnforcement = source.PolicyEnforcement;
                destination.ProtectionScenario = source.ProtectionScenario;
                destination.CustomServiceNames.Clear();

                if (source.CustomServiceNames != null)
                {
                    foreach (string name in source.CustomServiceNames)
                    {
                        ServiceNameElement entry = new ServiceNameElement();
                        entry.Name = name;
                        destination.CustomServiceNames.Add(entry);
                    }
                }
            }
        }
 public HttpChannelListener(HttpTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory(), bindingElement.HostNameComparisonMode)
 {
     if (bindingElement.TransferMode == System.ServiceModel.TransferMode.Buffered)
     {
         if (bindingElement.MaxReceivedMessageSize > 0x7fffffffL)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize", System.ServiceModel.SR.GetString("MaxReceivedMessageSizeMustBeInIntegerRange")));
         }
         if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", System.ServiceModel.SR.GetString("MaxBufferSizeMustMatchMaxReceivedMessageSize"));
         }
     }
     else if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", System.ServiceModel.SR.GetString("MaxBufferSizeMustNotExceedMaxReceivedMessageSize"));
     }
     if ((bindingElement.AuthenticationScheme == AuthenticationSchemes.Basic) && (bindingElement.ExtendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Always))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.ServiceModel.SR.GetString("ExtendedProtectionPolicyBasicAuthNotSupported")));
     }
     this.authenticationScheme       = bindingElement.AuthenticationScheme;
     this.keepAliveEnabled           = bindingElement.KeepAliveEnabled;
     base.InheritBaseAddressSettings = bindingElement.InheritBaseAddressSettings;
     this.maxBufferSize = bindingElement.MaxBufferSize;
     this.method        = bindingElement.Method;
     this.realm         = bindingElement.Realm;
     this.transferMode  = bindingElement.TransferMode;
     this.unsafeConnectionNtlmAuthentication = bindingElement.UnsafeConnectionNtlmAuthentication;
     this.credentialProvider       = context.BindingParameters.Find <SecurityCredentialsManager>();
     this.acceptor                 = new TransportReplyChannelAcceptor(this);
     this.securityCapabilities     = bindingElement.GetProperty <ISecurityCapabilities>(context);
     this.extendedProtectionPolicy = GetPolicyWithDefaultSpnCollection(bindingElement.ExtendedProtectionPolicy, this.authenticationScheme, base.HostNameComparisonModeInternal, base.Uri, out this.usingDefaultSpnList);
     if (bindingElement.AnonymousUriPrefixMatcher != null)
     {
         this.anonymousUriPrefixMatcher = new HttpAnonymousUriPrefixMatcher(bindingElement.AnonymousUriPrefixMatcher);
     }
 }
 public HttpListener()
 {
     if (Logging.On)
     {
         Logging.Enter(Logging.HttpListener, this, "HttpListener", "");
     }
     if (!UnsafeNclNativeMethods.HttpApi.Supported)
     {
         throw new PlatformNotSupportedException();
     }
     this.m_State = 0;
     this.m_InternalLock = new object();
     this.m_DefaultServiceNames = new ServiceNameStore();
     if (Version == UnsafeNclNativeMethods.HttpApi.HTTP_API_VERSION.Version20)
     {
         this.m_TimeoutManager = new HttpListenerTimeoutManager(this);
     }
     this.m_ExtendedProtectionPolicy = new System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy(PolicyEnforcement.Never);
     if (Logging.On)
     {
         Logging.Exit(Logging.HttpListener, this, "HttpListener", "");
     }
 }
Esempio n. 19
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
            {
                ExtendedProtectionPolicy policy = value as ExtendedProtectionPolicy;

                if (policy != null)
                {
                    Type[]   parameterTypes;
                    object[] parameterValues;

                    if (policy.PolicyEnforcement == PolicyEnforcement.Never)
                    {
                        parameterTypes  = new Type[] { typeof(PolicyEnforcement) };
                        parameterValues = new object[] { PolicyEnforcement.Never };
                    }
                    else
                    {
                        parameterTypes = new Type[] { typeof(PolicyEnforcement), typeof(ProtectionScenario), typeof(ICollection) };

                        object[] customServiceNames = null;
                        if (policy.CustomServiceNames?.Count > 0)
                        {
                            customServiceNames = new object[policy.CustomServiceNames.Count];
                            ((ICollection)policy.CustomServiceNames).CopyTo(customServiceNames, 0);
                        }

                        parameterValues = new object[] { policy.PolicyEnforcement, policy.ProtectionScenario, customServiceNames };
                    }

                    ConstructorInfo constructor = typeof(ExtendedProtectionPolicy).GetConstructor(parameterTypes);
                    return(new InstanceDescriptor(constructor, parameterValues));
                }
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
 private static void FillExtendedProtectionPolicy(IWmiInstance instance, ExtendedProtectionPolicy policy)
 {
     IWmiInstance instance2 = instance.NewInstance("ExtendedProtectionPolicy");
     instance2.SetProperty("PolicyEnforcement", policy.PolicyEnforcement.ToString());
     instance2.SetProperty("ProtectionScenario", policy.ProtectionScenario.ToString());
     if (policy.CustomServiceNames != null)
     {
         List<string> list = new List<string>(policy.CustomServiceNames.Count);
         foreach (string str in policy.CustomServiceNames)
         {
             list.Add(str);
         }
         instance2.SetProperty("CustomServiceNames", list.ToArray());
     }
     if (policy.CustomChannelBinding != null)
     {
         instance2.SetProperty("CustomChannelBinding", policy.CustomChannelBinding.GetType().ToString());
     }
     instance.SetProperty("ExtendedProtectionPolicy", instance2);
 }
        public byte[] GetOutgoingBlob(byte[] incomingBlob, ChannelBinding channelbinding, ExtendedProtectionPolicy protectionPolicy)
        {
            ThrowIfDisposed();
            int statusCode = 0;

            // use the confidentiality option to ensure we can encrypt messages
            SspiContextFlags requestedFlags = SspiContextFlags.Confidentiality
                                            | SspiContextFlags.ReplayDetect
                                            | SspiContextFlags.SequenceDetect;

            if (this.doMutualAuth)
            {
                requestedFlags |= SspiContextFlags.MutualAuth;
            }

            if (this.impersonationLevel == TokenImpersonationLevel.Delegation)
            {
                requestedFlags |= SspiContextFlags.Delegate;
            }
            else if (this.isServer == false && this.impersonationLevel == TokenImpersonationLevel.Identification)
            {
                requestedFlags |= SspiContextFlags.InitIdentify;
            }
            else if (this.isServer == false && this.impersonationLevel == TokenImpersonationLevel.Anonymous)
            {
                requestedFlags |= SspiContextFlags.InitAnonymous;
            }

            ExtendedProtectionPolicyHelper policyHelper = new ExtendedProtectionPolicyHelper(channelbinding, protectionPolicy);

            if (isServer)
            {
                if (policyHelper.PolicyEnforcement == PolicyEnforcement.Always && policyHelper.ChannelBinding == null && policyHelper.ProtectionScenario != ProtectionScenario.TrustedProxy)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SecurityChannelBindingMissing)));
                }

                if (policyHelper.PolicyEnforcement == PolicyEnforcement.WhenSupported)
                {
                    requestedFlags |= SspiContextFlags.ChannelBindingAllowMissingBindings;
                }

                if (policyHelper.ProtectionScenario == ProtectionScenario.TrustedProxy)
                {
                    requestedFlags |= SspiContextFlags.ChannelBindingProxyBindings;
                }
            }

            List<SecurityBuffer> list = new List<SecurityBuffer>(2);

            if (incomingBlob != null)
            {
                list.Add(new SecurityBuffer(incomingBlob, BufferType.Token));
            }

            // when deciding if the channel binding should be added to the security buffer
            // it is necessary to differentiate between  client and server.
            // Server rules were added to policyHelper as they are shared with Kerb and I want them consistent
            // Client adds if not null.
            if (this.isServer)
            {
                if (policyHelper.ShouldAddChannelBindingToASC())
                {
                    list.Add(new SecurityBuffer(policyHelper.ChannelBinding));
                }
            }
            else
            {
                if (policyHelper.ChannelBinding != null)
                {
                    list.Add(new SecurityBuffer(policyHelper.ChannelBinding));
                }
            }

            SecurityBuffer[] inSecurityBuffer = null;
            if (list.Count > 0)
            {
                inSecurityBuffer = list.ToArray();
            }

            SecurityBuffer outSecurityBuffer = new SecurityBuffer(this.tokenSize, BufferType.Token);

            if (!this.isServer)
            {
                //client session
                statusCode = SspiWrapper.InitializeSecurityContext(this.credentialsHandle,
                                                                    ref this.securityContext,
                                                                    this.servicePrincipalName,
                                                                    requestedFlags,
                                                                    Endianness.Network,
                                                                    inSecurityBuffer,
                                                                    outSecurityBuffer,
                                                                    ref this.contextFlags);
            }
            else
            {
                // server session
                //This check is to save an unnecessary ASC call.
                bool isServerSecurityContextNull = this.securityContext == null;
                SspiContextFlags serverContextFlags = this.contextFlags;

                statusCode = SspiWrapper.AcceptSecurityContext(this.credentialsHandle,
                                                                ref this.securityContext,
                                                                requestedFlags,
                                                                Endianness.Network,
                                                                inSecurityBuffer,
                                                                outSecurityBuffer,
                                                                ref this.contextFlags);

                if (statusCode == (int)SecurityStatus.InvalidToken && !isServerSecurityContextNull)
                {
                    // Call again into ASC after deleting the Securitycontext. If this securitycontext is not deleted 
                    // then when the client sends NTLM blob the service will treat it as Nego2blob and will fail to authenticate the client.
                    this.contextFlags = serverContextFlags;
                    CloseContext();
                    statusCode = SspiWrapper.AcceptSecurityContext(this.credentialsHandle,
                                                                    ref this.securityContext,
                                                                    requestedFlags,
                                                                    Endianness.Network,
                                                                    inSecurityBuffer,
                                                                    outSecurityBuffer,
                                                                    ref this.contextFlags);
                }
            }

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                IMD.SecurityTraceRecordHelper.TraceChannelBindingInformation(policyHelper, this.isServer, channelbinding);
            }

            if ((statusCode & unchecked((int)0x80000000)) != 0)
            {
                if (!this.isServer
                    && this.interactiveNegoLogonEnabled
                    && SecurityUtils.IsOSGreaterThanOrEqualToWin7()
                    && SspiWrapper.IsSspiPromptingNeeded((uint)statusCode)
                    && SspiWrapper.IsNegotiateExPackagePresent())
                {
                    // If we have prompted enough number of times (DefaultMaxPromptAttempts) with wrong credentials, then we do not prompt again and throw. 
                    if (MaxPromptAttempts >= DefaultMaxPromptAttempts)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode, SR.GetString(SR.InvalidClientCredentials)));
                    }

                    IntPtr ppAuthIdentity = IntPtr.Zero;
                    uint errorCode = SspiWrapper.SspiPromptForCredential(this.servicePrincipalName, this.clientPackageName, out ppAuthIdentity, ref this.saveClientCredentialsOnSspiUi);
                    if (errorCode == (uint)CredentialStatus.Success)
                    {
                        IntPtr ppNewAuthIdentity = IntPtr.Zero;

                        if (!this.allowNtlm)
                        {
                            // When Ntlm is  explicitly disabled we don't want the collected 
                            //creds from the Kerb/NTLM tile to be used for NTLM auth.

                            uint status = UnsafeNativeMethods.SspiExcludePackage(ppAuthIdentity, "NTLM", out ppNewAuthIdentity);
                        }
                        else
                        {
                            ppNewAuthIdentity = ppAuthIdentity;
                        }

                        this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle(this.clientPackageName, CredentialUse.Outbound, ref ppNewAuthIdentity);

                        if (IntPtr.Zero != ppNewAuthIdentity)
                        {
                            UnsafeNativeMethods.SspiFreeAuthIdentity(ppNewAuthIdentity);
                        }

                        CloseContext();

                        MaxPromptAttempts++;
                        return this.GetOutgoingBlob(null, channelbinding, protectionPolicy);
                    }
                    else
                    {
                        // Call into SspiPromptForCredential had an error. Time to throw.
                        if (IntPtr.Zero != ppAuthIdentity)
                        {
                            UnsafeNativeMethods.SspiFreeAuthIdentity(ppAuthIdentity);
                        }

                        CloseContext();
                        this.isCompleted = true;
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception((int)errorCode, SR.GetString(SR.SspiErrorOrInvalidClientCredentials)));
                    }
                }

                CloseContext();
                this.isCompleted = true;
                if (!this.isServer && (statusCode == (int)SecurityStatus.TargetUnknown
                    || statusCode == (int)SecurityStatus.WrongPrincipal))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode, SR.GetString(SR.IncorrectSpnOrUpnSpecified, this.servicePrincipalName)));
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode, SR.GetString(SR.InvalidSspiNegotiation)));
                }
            }

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                if (this.isServer)
                {
                    SecurityTraceRecordHelper.TraceServiceOutgoingSpnego(this);
                }
                else
                {
                    SecurityTraceRecordHelper.TraceClientOutgoingSpnego(this);
                }
            }

            if (statusCode == (int)SecurityStatus.OK)
            {
                // we're done
                this.isCompleted = true;

                // These must all be true to check service binding
                // 1. we are the service (listener)
                // 2. caller is not anonymous
                // 3. protocol is not Kerberos
                // 4. policy is set to check service binding
                // 
                if (isServer && ((this.contextFlags & SspiContextFlags.AcceptAnonymous) == 0) && (string.Compare(this.ProtocolName, NegotiationInfoClass.Kerberos, StringComparison.OrdinalIgnoreCase) != 0) && policyHelper.ShouldCheckServiceBinding)
                {
                    // in the server case the servicePrincipalName is the defaultServiceBinding
                   
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        string serviceBindingNameSentByClient;
                        SspiWrapper.QuerySpecifiedTarget(securityContext, out serviceBindingNameSentByClient);
                        IMD.SecurityTraceRecordHelper.TraceServiceNameBindingOnServer( serviceBindingNameSentByClient, this.servicePrincipalName, policyHelper.ServiceNameCollection);
                    }
                    
                    policyHelper.CheckServiceBinding(this.securityContext, this.servicePrincipalName);
                }
            }
            else
            {
                // we need to continue
            }

            return outSecurityBuffer.token;
        }
Esempio n. 22
0
 public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
 {
     throw new PlatformNotSupportedException();
 }
Esempio n. 23
0
 public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy policy)
 {
     throw new PlatformNotSupportedException();
 }
 private static System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy GetPolicyWithDefaultSpnCollection(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy policy, AuthenticationSchemes authenticationScheme, System.ServiceModel.HostNameComparisonMode hostNameComparisonMode, Uri listenUri, out bool usingDefaultSpnList)
 {
     if ((((policy.PolicyEnforcement != PolicyEnforcement.Never) && (policy.CustomServiceNames == null)) && ((policy.CustomChannelBinding == null) && (authenticationScheme != AuthenticationSchemes.Anonymous))) && string.Equals(listenUri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
     {
         usingDefaultSpnList = true;
         return(new System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy(policy.PolicyEnforcement, policy.ProtectionScenario, GetDefaultSpnList(hostNameComparisonMode, listenUri)));
     }
     usingDefaultSpnList = false;
     return(policy);
 }
Esempio n. 25
0
        private IAsyncResult BeginAuthenticateAsServer(
            NetworkCredential credential,
            ExtendedProtectionPolicy policy,
            ProtectionLevel requiredProtectionLevel,
            TokenImpersonationLevel requiredImpersonationLevel,
            AsyncCallback asyncCallback,
            object asyncState)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
            {
#endif
                _negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);

                LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback);
                _negoState.ProcessAuthentication(result);

                return result;
#if DEBUG
            }
#endif
        }
Esempio n. 26
0
        private ArrayList BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId,
            out NTAuthentication newContext, ExtendedProtectionPolicy policy, bool isSecureConnection)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, "AuthenticationScheme:" + authenticationScheme.ToString());
            ArrayList challenges = null;
            newContext = null;

            if ((authenticationScheme & AuthenticationSchemes.Negotiate) != 0)
            {
                AddChallenge(ref challenges, AuthConstants.Negotiate);
            }

            if ((authenticationScheme & AuthenticationSchemes.Ntlm) != 0)
            {
                AddChallenge(ref challenges, AuthConstants.NTLM);
            }

            if ((authenticationScheme & AuthenticationSchemes.Digest) != 0)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, "WDigest");
                throw new NotImplementedException();
            }

            if ((authenticationScheme & AuthenticationSchemes.Basic) != 0)
            {
                AddChallenge(ref challenges, "Basic realm =\"" + Realm + "\"");
            }

            return challenges;
        }
Esempio n. 27
0
        internal HttpListenerContext HandleAuthentication(RequestContextBase memoryBlob, out bool stoleBlob)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, "HandleAuthentication() memoryBlob:0x" + ((IntPtr)memoryBlob.RequestBlob).ToString("x"));

            string challenge = null;
            stoleBlob = false;

            // Some things we need right away.  Lift them out now while it's convenient.
            string verb = Interop.HttpApi.GetVerb(memoryBlob.RequestBlob);
            string authorizationHeader = Interop.HttpApi.GetKnownHeader(memoryBlob.RequestBlob, (int)HttpRequestHeader.Authorization);
            ulong connectionId = memoryBlob.RequestBlob->ConnectionId;
            ulong requestId = memoryBlob.RequestBlob->RequestId;
            bool isSecureConnection = memoryBlob.RequestBlob->pSslInfo != null;

            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"HandleAuthentication() authorizationHeader: ({authorizationHeader})");

            // if the app has turned on AuthPersistence, an anonymous request might
            // be authenticated by virtue of it coming on a connection that was
            // previously authenticated.
            // assurance that we do this only for NTLM/Negotiate is not here, but in the
            // code that caches WindowsIdentity instances in the Dictionary.
            DisconnectAsyncResult disconnectResult;
            DisconnectResults.TryGetValue(connectionId, out disconnectResult);
            if (UnsafeConnectionNtlmAuthentication)
            {
                if (authorizationHeader == null)
                {
                    WindowsPrincipal principal = disconnectResult?.AuthenticatedConnection;
                    if (principal != null)
                    {
                        if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Principal: {principal} principal.Identity.Name: {principal.Identity.Name} creating request");
                        stoleBlob = true;
                        HttpListenerContext ntlmContext = new HttpListenerContext(this, memoryBlob);
                        ntlmContext.SetIdentity(principal, null);
                        ntlmContext.Request.ReleasePins();
                        return ntlmContext;
                    }
                }
                else
                {
                    // They sent an authorization - destroy their previous credentials.
                    if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Clearing principal cache");
                    if (disconnectResult != null)
                    {
                        disconnectResult.AuthenticatedConnection = null;
                    }
                }
            }

            // Figure out what schemes we're allowing, what context we have.
            stoleBlob = true;
            HttpListenerContext httpContext = null;
            NTAuthentication oldContext = null;
            NTAuthentication newContext = null;
            NTAuthentication context = null;
            AuthenticationSchemes headerScheme = AuthenticationSchemes.None;
            AuthenticationSchemes authenticationScheme = AuthenticationSchemes;
            ExtendedProtectionPolicy extendedProtectionPolicy = _extendedProtectionPolicy;
            try
            {
                // Take over handling disconnects for now.
                if (disconnectResult != null && !disconnectResult.StartOwningDisconnectHandling())
                {
                    // Just disconnected just then.  Pretend we didn't see the disconnectResult.
                    disconnectResult = null;
                }

                // Pick out the old context now.  By default, it'll be removed in the finally, unless context is set somewhere. 
                if (disconnectResult != null)
                {
                    oldContext = disconnectResult.Session;
                }

                httpContext = new HttpListenerContext(this, memoryBlob);

                AuthenticationSchemeSelector authenticationSelector = _authenticationDelegate;
                if (authenticationSelector != null)
                {
                    try
                    {
                        httpContext.Request.ReleasePins();
                        authenticationScheme = authenticationSelector(httpContext.Request);
                        // Cache the results of authenticationSelector (if any)
                        httpContext.AuthenticationSchemes = authenticationScheme;
                        if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"AuthenticationScheme: {authenticationScheme}");
                    }
                    catch (Exception exception) when (!ExceptionCheck.IsFatal(exception))
                    {
                        if (NetEventSource.IsEnabled)
                        {
                            NetEventSource.Error(this, SR.Format(SR.net_log_listener_delegate_exception, exception));
                            NetEventSource.Info(this, $"authenticationScheme: {authenticationScheme}");
                        }
                        SendError(requestId, HttpStatusCode.InternalServerError, null);
                        httpContext.Close();
                        return null;
                    }
                }
                else
                {
                    // We didn't give the request to the user yet, so we haven't lost control of the unmanaged blob and can
                    // continue to reuse the buffer.
                    stoleBlob = false;
                }

                ExtendedProtectionSelector extendedProtectionSelector = _extendedProtectionSelectorDelegate;
                if (extendedProtectionSelector != null)
                {
                    extendedProtectionPolicy = extendedProtectionSelector(httpContext.Request);

                    if (extendedProtectionPolicy == null)
                    {
                        extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
                    }
                    // Cache the results of extendedProtectionSelector (if any)
                    httpContext.ExtendedProtectionPolicy = extendedProtectionPolicy;
                }

                // Then figure out what scheme they're trying (if any are allowed)
                int index = -1;
                if (authorizationHeader != null && (authenticationScheme & ~AuthenticationSchemes.Anonymous) != AuthenticationSchemes.None)
                {
                    // Find the end of the scheme name.  Trust that HTTP.SYS parsed out just our header ok.
                    for (index = 0; index < authorizationHeader.Length; index++)
                    {
                        if (authorizationHeader[index] == ' ' || authorizationHeader[index] == '\t' ||
                            authorizationHeader[index] == '\r' || authorizationHeader[index] == '\n')
                        {
                            break;
                        }
                    }

                    // Currently only allow one Authorization scheme/header per request.
                    if (index < authorizationHeader.Length)
                    {
                        if ((authenticationScheme & AuthenticationSchemes.Negotiate) != AuthenticationSchemes.None &&
                            string.Compare(authorizationHeader, 0, AuthConstants.Negotiate, 0, index, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            headerScheme = AuthenticationSchemes.Negotiate;
                        }
                        else if ((authenticationScheme & AuthenticationSchemes.Ntlm) != AuthenticationSchemes.None &&
                            string.Compare(authorizationHeader, 0, AuthConstants.NTLM, 0, index, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            headerScheme = AuthenticationSchemes.Ntlm;
                        }
                        else if ((authenticationScheme & AuthenticationSchemes.Digest) != AuthenticationSchemes.None &&
                            string.Compare(authorizationHeader, 0, AuthConstants.Digest, 0, index, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            headerScheme = AuthenticationSchemes.Digest;
                        }
                        else if ((authenticationScheme & AuthenticationSchemes.Basic) != AuthenticationSchemes.None &&
                            string.Compare(authorizationHeader, 0, AuthConstants.Basic, 0, index, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            headerScheme = AuthenticationSchemes.Basic;
                        }
                        else
                        {
                            if (NetEventSource.IsEnabled) NetEventSource.Error(this, SR.Format(SR.net_log_listener_unsupported_authentication_scheme, authorizationHeader, authenticationScheme));
                        }
                    }
                }

                // httpError holds the error we will return if an Authorization header is present but can't be authenticated
                HttpStatusCode httpError = HttpStatusCode.InternalServerError;

                // See if we found an acceptable auth header
                if (headerScheme == AuthenticationSchemes.None)
                {
                    if (NetEventSource.IsEnabled) NetEventSource.Error(this, SR.Format(SR.net_log_listener_unmatched_authentication_scheme, authenticationScheme.ToString(), (authorizationHeader == null ? "<null>" : authorizationHeader)));

                    // If anonymous is allowed, just return the context.  Otherwise go for the 401.
                    if ((authenticationScheme & AuthenticationSchemes.Anonymous) != AuthenticationSchemes.None)
                    {
                        if (!stoleBlob)
                        {
                            stoleBlob = true;
                            httpContext.Request.ReleasePins();
                        }
                        return httpContext;
                    }

                    httpError = HttpStatusCode.Unauthorized;
                    httpContext.Request.DetachBlob(memoryBlob);
                    httpContext.Close();
                    httpContext = null;
                }
                else
                {
                    throw new NotImplementedException();
                }

                // if we're not giving a request to the application, we need to send an error
                ArrayList challenges = null;
                if (httpContext == null)
                {
                    // If we already have a challenge, just use it.  Otherwise put a challenge for each acceptable scheme.
                    if (challenge != null)
                    {
                        AddChallenge(ref challenges, challenge);
                    }
                    else
                    {
                        // We're starting over.  Any context SSPI might have wanted us to keep is useless.
                        if (newContext != null)
                        {
                            if (newContext == context)
                            {
                                context = null;
                            }

                            if (newContext != oldContext)
                            {
                                NTAuthentication toClose = newContext;
                                newContext = null;
                                toClose.CloseContext();
                            }
                            else
                            {
                                newContext = null;
                            }
                        }

                        // If we're sending something besides 401, do it here.
                        if (httpError != HttpStatusCode.Unauthorized)
                        {
                            if (NetEventSource.IsEnabled) NetEventSource.Info(this, "ConnectionId:" + connectionId + " because of error:" + httpError.ToString());
                            SendError(requestId, httpError, null);
                            return null;
                        }

                        challenges = BuildChallenge(authenticationScheme, connectionId, out newContext,
                            extendedProtectionPolicy, isSecureConnection);
                    }
                }

                // Check if we need to call WaitForDisconnect, because if we do and it fails, we want to send a 500 instead.
                if (disconnectResult == null && newContext != null)
                {
                    RegisterForDisconnectNotification(connectionId, ref disconnectResult);

                    // Failed - send 500.
                    if (disconnectResult == null)
                    {
                        if (newContext != null)
                        {
                            if (newContext == context)
                            {
                                context = null;
                            }

                            if (newContext != oldContext)
                            {
                                NTAuthentication toClose = newContext;
                                newContext = null;
                                toClose.CloseContext();
                            }
                            else
                            {
                                newContext = null;
                            }
                        }

                        if (NetEventSource.IsEnabled) NetEventSource.Info(this, "connectionId:" + connectionId + " because of failed HttpWaitForDisconnect");
                        SendError(requestId, HttpStatusCode.InternalServerError, null);
                        httpContext.Request.DetachBlob(memoryBlob);
                        httpContext.Close();
                        return null;
                    }
                }

                // Update Session if necessary.
                if (oldContext != newContext)
                {
                    if (oldContext == context)
                    {
                        // Prevent the finally from closing this twice.
                        context = null;
                    }

                    NTAuthentication toClose = oldContext;
                    oldContext = newContext;
                    disconnectResult.Session = newContext;

                    if (toClose != null)
                    {
                        // Save digest context in digest cache, we may need it later because of
                        // subsequest responses to the same req on the same/diff connection
                        if ((authenticationScheme & AuthenticationSchemes.Digest) != 0)
                        {
                            SaveDigestContext(toClose);
                        }
                        else
                        {
                            toClose.CloseContext();
                        }
                    }
                }

                // Send the 401 here.
                if (httpContext == null)
                {
                    SendError(requestId, challenges != null && challenges.Count > 0 ? HttpStatusCode.Unauthorized : HttpStatusCode.Forbidden, challenges);
                    if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Scheme:" + authenticationScheme);
                    return null;
                }

                if (!stoleBlob)
                {
                    stoleBlob = true;
                    httpContext.Request.ReleasePins();
                }
                return httpContext;
            }
            catch
            {
                if (httpContext != null)
                {
                    httpContext.Request.DetachBlob(memoryBlob);
                    httpContext.Close();
                }
                if (newContext != null)
                {
                    if (newContext == context)
                    {
                        // Prevent the finally from closing this twice.
                        context = null;
                    }

                    if (newContext != oldContext)
                    {
                        NTAuthentication toClose = newContext;
                        newContext = null;
                        toClose.CloseContext();
                    }
                    else
                    {
                        newContext = null;
                    }
                }
                throw;
            }
            finally
            {
                try
                {
                    // Clean up the previous context if necessary.
                    if (oldContext != null && oldContext != newContext)
                    {
                        // Clear out Session if it wasn't already.
                        if (newContext == null && disconnectResult != null)
                        {
                            disconnectResult.Session = null;
                        }

                        // Save digest context in digest cache, we may need it later because of
                        // subsequest responses to the same req on the same/diff connection

                        if ((authenticationScheme & AuthenticationSchemes.Digest) != 0)
                        {
                            SaveDigestContext(oldContext);
                        }
                        else
                        {
                            oldContext.CloseContext();
                        }
                    }

                    // Delete any context created but not stored.
                    if (context != null && oldContext != context && newContext != context)
                    {
                        context.CloseContext();
                    }
                }
                finally
                {
                    // Check if the connection got deleted while in this method, and clear out the hashtables if it did.
                    // In a nested finally because if this doesn't happen, we leak.
                    if (disconnectResult != null)
                    {
                        disconnectResult.FinishOwningDisconnectHandling();
                    }
                }
            }
        }
 public static bool IsDefaultPolicy(ExtendedProtectionPolicy policy)
 {
     return Object.ReferenceEquals(policy, defaultPolicy);
 }
Esempio n. 29
0
 public virtual Task AuthenticateAsServerAsync(
     NetworkCredential credential, ExtendedProtectionPolicy policy,
     ProtectionLevel requiredProtectionLevel,
     TokenImpersonationLevel requiredImpersonationLevel)
 {
     return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(credential, policy, requiredProtectionLevel, requiredImpersonationLevel, callback, state), EndAuthenticateAsClient, null);
 }
            internal override void WriteTo(XmlWriter xml)
            {
                if (xml == null)
                    return;
                if (this.policyHelper != null)
                {
                    xml.WriteElementString("PolicyEnforcement", this.policyHelper.PolicyEnforcement.ToString());
                    xml.WriteElementString("ProtectionScenario", this.policyHelper.ProtectionScenario.ToString());

                    xml.WriteStartElement("ServiceNameCollection");

                    if (this.policyHelper.ServiceNameCollection != null && this.policyHelper.ServiceNameCollection.Count > 0)
                    {
                        foreach (string serviceName in this.policyHelper.ServiceNameCollection)
                        {
                            xml.WriteElementString("ServiceName", serviceName);
                        }
                    }

                    xml.WriteFullEndElement();

                    if (this.isServer)
                    {
                        this.channelBindingUsed = this.policyHelper.ShouldAddChannelBindingToASC();
                    }
                    else
                    {
                        this.channelBindingUsed = this.policyHelper.ChannelBinding != null;
                    }

                    xml.WriteElementString("ChannelBindingUsed", this.channelBindingUsed.ToString());

                    if (this.channelBinding != null && this.policyHelper.PolicyEnforcement != PolicyEnforcement.Never && this.channelBindingUsed == true)
                    {
                        ExtendedProtectionPolicy extendedProtection = new ExtendedProtectionPolicy(policyHelper.PolicyEnforcement, channelBinding);
                        xml.WriteElementString("ChannelBindingData", GetBase64EncodedChannelBindingData(extendedProtection));
                    }
                }
                else
                {
                    // This is the case for KerberosRequestorSecurityToken where policyHelper is null.
                    if (this.channelBinding != null)
                    {
                        xml.WriteElementString("ChannelBindingUsed", "true");

                        // We do not know the PolicyEnforcement value here on the client side and we can not pass Never 
                        //as ExtendedProtectionPolicy constructor would throw on PolicyEnforcement.Never
                        ExtendedProtectionPolicy extendedProtection = new ExtendedProtectionPolicy(PolicyEnforcement.WhenSupported, channelBinding);
                        xml.WriteElementString("ChannelBindingData", GetBase64EncodedChannelBindingData(extendedProtection));
                    }
                    else
                    {
                        xml.WriteElementString("ChannelBindingUsed", "false");
                        xml.WriteElementString("ChannelBindingData", null);
                    }
                }

            }
Esempio n. 31
0
        public HttpListener()
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this);

            _state = State.Stopped;
            _internalLock = new object();
            _defaultServiceNames = new ServiceNameStore();

            _timeoutManager = new HttpListenerTimeoutManager(this);

            // default: no CBT checks on any platform (appcompat reasons); applies also to PolicyEnforcement 
            // config element
            _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }
 internal string GetBase64EncodedChannelBindingData(ExtendedProtectionPolicy extendedProtectionPolicy)
 {
     MemoryStream ms = new MemoryStream();
     BinaryFormatter formatter = new BinaryFormatter();
     formatter.Serialize(ms, extendedProtectionPolicy);
     byte[] channelBindingData = ms.GetBuffer();
     return Convert.ToBase64String(channelBindingData, Base64FormattingOptions.None);
 }
 public virtual void ValidateHttpSettings(string virtualPath, bool isMetadataListener, bool usingDefaultSpnList, ref AuthenticationSchemes supportedSchemes, ref ExtendedProtectionPolicy extendedProtectionPolicy, ref string realm)
 {
 }
Esempio n. 34
0
 private IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState)
 {
     return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState);
 }
Esempio n. 35
0
        public override void ValidateHttpSettings(string virtualPath, bool isMetadataListener, bool usingDefaultSpnList, ref AuthenticationSchemes bindingElementAuthenticationSchemes, ref ExtendedProtectionPolicy extendedProtectionPolicy, ref string realm)
        {
            // Verify the authentication settings
            AuthenticationSchemes hostSupportedSchemes = HostedTransportConfigurationManager.MetabaseSettings.GetAuthenticationSchemes(virtualPath);

            if ((bindingElementAuthenticationSchemes & hostSupportedSchemes) == 0)
            {
                if (bindingElementAuthenticationSchemes == AuthenticationSchemes.Negotiate ||
                    bindingElementAuthenticationSchemes == AuthenticationSchemes.Ntlm ||
                    bindingElementAuthenticationSchemes == AuthenticationSchemes.IntegratedWindowsAuthentication)
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_AuthSchemesRequireWindowsAuth));
                }
                else
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_AuthSchemesRequireOtherAuth(bindingElementAuthenticationSchemes.ToString())));
                }
            }

            //only use AuthenticationSchemes, which are supported both in IIS and the WCF binding
            bindingElementAuthenticationSchemes &= hostSupportedSchemes;

            if (bindingElementAuthenticationSchemes != AuthenticationSchemes.Anonymous)
            {
                //Compare the ExtendedProtectionPolicy setttings to IIS
                ExtendedProtectionPolicy iisPolicy = HostedTransportConfigurationManager.MetabaseSettings.GetExtendedProtectionPolicy(virtualPath);

                if (iisPolicy == null) //OS doesn't support CBT
                {
                    if (extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Always)
                    {
                        throw FxTrace.Exception.AsError(new NotSupportedException(SR.ExtendedProtectionNotSupported));
                    }
                }
                else
                {
                    if (isMetadataListener && ChannelBindingUtility.IsDefaultPolicy(extendedProtectionPolicy))
                    {
                        //push the IIS policy onto the metadataListener if and only if the default policy is 
                        //in force. policy for non metadata listeners will still have to match IIS policy.
                        extendedProtectionPolicy = iisPolicy;
                    }
                    else
                    {
                        if (!ChannelBindingUtility.AreEqual(iisPolicy, extendedProtectionPolicy))
                        {
                            string mismatchErrorMessage;
                            if (iisPolicy.PolicyEnforcement != extendedProtectionPolicy.PolicyEnforcement)
                            {
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyEnforcementMismatch(iisPolicy.PolicyEnforcement, extendedProtectionPolicy.PolicyEnforcement);
                            }
                            else if (iisPolicy.ProtectionScenario != extendedProtectionPolicy.ProtectionScenario)
                            {
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyScenarioMismatch(iisPolicy.ProtectionScenario, extendedProtectionPolicy.ProtectionScenario);
                            }
                            else 
                            {
                                Fx.Assert(iisPolicy.CustomChannelBinding != extendedProtectionPolicy.CustomChannelBinding, "new case in ChannelBindingUtility.AreEqual to account for");
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyCustomChannelBindingMismatch;
                            }

                            if (mismatchErrorMessage != null)
                            {
                                throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_ExtendedProtectionPoliciesMustMatch(mismatchErrorMessage)));
                            }
                        }

                        //when using the default SPN list we auto generate, we should make sure that the IIS policy is also the default...
                        ServiceNameCollection listenerSpnList = usingDefaultSpnList ? null : extendedProtectionPolicy.CustomServiceNames;
                        if (!ChannelBindingUtility.IsSubset(iisPolicy.CustomServiceNames, listenerSpnList))
                        {
                            throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_ExtendedProtectionPoliciesMustMatch(SR.Hosting_ExtendedProtectionSPNListNotSubset)));
                        }
                    }
                }
            }

            

            // Do not set realm for Cassini.
            if (!ServiceHostingEnvironment.IsSimpleApplicationHost)
            {
                // Set the realm
                realm = HostedTransportConfigurationManager.MetabaseSettings.GetRealm(virtualPath);
            }
        }
Esempio n. 36
0
 public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy policy)
 {
     return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, policy, null);
 }
Esempio n. 37
0
 public virtual void AuthenticateAsServer(ExtendedProtectionPolicy policy)
 {
     AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification);
 }
        public byte[] GetOutgoingBlob(byte[] incomingBlob, ChannelBinding channelbinding, ExtendedProtectionPolicy protectionPolicy)
        {
            ThrowIfDisposed();
            SecurityBuffer incomingSecurity = null;
            if (incomingBlob != null)
            {
                incomingSecurity = new SecurityBuffer(incomingBlob, BufferType.Token);
            }

            SecurityBuffer outgoingSecurity = new SecurityBuffer(null, BufferType.Token);
            this.remoteCertificate = null;
            int statusCode = 0;
            if (this.isServer == true)
            {
                statusCode = SspiWrapper.AcceptSecurityContext(
                    this.credentialsHandle,
                    ref this.securityContext,
                    ServerStandardFlags | (this.clientCertRequired ? SspiContextFlags.MutualAuth : SspiContextFlags.Zero),
                    Endianness.Native,
                    incomingSecurity,
                    outgoingSecurity,
                    ref this.attributes
                    );

            }
            else
            {
                statusCode = SspiWrapper.InitializeSecurityContext(
                    this.credentialsHandle,
                    ref this.securityContext,
                    this.destination,
                    ClientStandardFlags,
                    Endianness.Native,
                    incomingSecurity,
                    outgoingSecurity,
                    ref this.attributes
                    );
            }

            if ((statusCode & unchecked((int)0x80000000)) != 0)
            {
                this.Dispose();
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode));
            }

            if (statusCode == (int)SecurityStatus.OK)
            {
                // we're done
                // ensure that the key negotiated is strong enough
                if (SecurityUtils.ShouldValidateSslCipherStrength())
                {
                    SslConnectionInfo connectionInfo = (SslConnectionInfo)SspiWrapper.QueryContextAttributes(this.securityContext, ContextAttribute.ConnectionInfo);
                    if (connectionInfo == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.CannotObtainSslConnectionInfo)));
                    }
                    SecurityUtils.ValidateSslCipherStrength(connectionInfo.DataKeySize);
                }
                this.isCompleted = true;
            }
            else if (statusCode == (int)SecurityStatus.CredentialsNeeded)
            {
                // the server requires the client to supply creds
                // Currently we dont attempt to find the client cert to choose at runtime
                // so just re-call the function
                AcquireClientCredentials();
                if (this.ClientCertificate != null)
                {
                    this.wasClientCertificateSent = true;
                }
                return this.GetOutgoingBlob(incomingBlob, channelbinding, protectionPolicy);
            }
            else if (statusCode != (int)SecurityStatus.ContinueNeeded)
            {
                this.Dispose();
                if (statusCode == (int)SecurityStatus.InternalError)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode, SR.GetString(SR.LsaAuthorityNotContacted)));
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode));
                }
            }
            return outgoingSecurity.token;
        }
Esempio n. 39
0
        public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
            {
#endif
                _negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
                _negoState.ProcessAuthentication(null);
#if DEBUG
            }
#endif
        }