public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
 {
     if (identity == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
     }
     if (authContext == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext");
     }
     for (int i = 0; i < authContext.ClaimSets.Count; i++)
     {
         ClaimSet claimSet = authContext.ClaimSets[i];
         if (claimSet.ContainsClaim(identity.IdentityClaim))
         {
             SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(identity, identity.IdentityClaim, base.GetType());
             return(true);
         }
         string expectedSpn = null;
         if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
         {
             expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", new object[] { (string)identity.IdentityClaim.Resource });
             Claim claim = this.CheckDnsEquivalence(claimSet, expectedSpn);
             if (claim != null)
             {
                 SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(identity, claim, base.GetType());
                 return(true);
             }
         }
         SecurityIdentifier identitySid = null;
         if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
         {
             identitySid = this.GetSecurityIdentifier(identity.IdentityClaim);
         }
         else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
         {
             identitySid = ((UpnEndpointIdentity)identity).GetUpnSid();
         }
         else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
         {
             identitySid = ((SpnEndpointIdentity)identity).GetSpnSid();
         }
         else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
         {
             identitySid = new SpnEndpointIdentity(expectedSpn).GetSpnSid();
         }
         if (identitySid != null)
         {
             Claim claim2 = this.CheckSidEquivalence(identitySid, claimSet);
             if (claim2 != null)
             {
                 SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(identity, claim2, base.GetType());
                 return(true);
             }
         }
     }
     SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, base.GetType());
     return(false);
 }
        private void EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, string errorString)
        {
            EndpointIdentity identity;

            if (authorizationContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
            }
            if (!this.TryGetIdentity(serviceReference, out identity))
            {
                SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authorizationContext, base.GetType());
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(System.ServiceModel.SR.GetString(errorString, new object[] { identity, serviceReference })));
            }
            if (!this.CheckAccess(identity, authorizationContext))
            {
                Exception exception = this.CreateIdentityCheckException(identity, authorizationContext, errorString, serviceReference);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(exception);
            }
        }
示例#3
0
        private void EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, String errorString)
        {
            if (authorizationContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
            }
            EndpointIdentity identity;

            if (!TryGetIdentity(serviceReference, out identity))
            {
                SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authorizationContext, this.GetType());
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(string.Format(errorString, identity, serviceReference)));
            }
            else
            {
                if (!CheckAccess(identity, authorizationContext))
                {
                    // CheckAccess performs a Trace on failure, no need to do it twice
                    Exception e = CreateIdentityCheckException(identity, authorizationContext, errorString, serviceReference);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(e);
                }
            }
        }
示例#4
0
            public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
            {
                //EventTraceActivity eventTraceActivity = null;

                if (identity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(identity));
                }

                if (authContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(authContext));
                }


                //if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
                //{
                //    eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
                //}

                for (int i = 0; i < authContext.ClaimSets.Count; ++i)
                {
                    ClaimSet claimSet = authContext.ClaimSets[i];
                    if (claimSet.ContainsClaim(identity.IdentityClaim))
                    {
                        //SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType());
                        return(true);
                    }

                    // try Claim equivalence
                    string expectedSpn = null;
                    if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    {
                        expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
                        Claim claim = CheckDnsEquivalence(claimSet, expectedSpn);
                        if (claim != null)
                        {
                            //SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                            return(true);
                        }
                    }
                    // Allow a Sid claim to support UPN, and SPN identities
                    SecurityIdentifier identitySid = null;
                    if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
                    {
                        identitySid = GetSecurityIdentifier(identity.IdentityClaim);
                    }
                    else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
                    {
                        identitySid = ((UpnEndpointIdentity)identity).GetUpnSid();
                    }
                    else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
                    {
                        identitySid = ((SpnEndpointIdentity)identity).GetSpnSid();
                    }
                    else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    {
                        identitySid = new SpnEndpointIdentity(expectedSpn).GetSpnSid();
                    }
                    if (identitySid != null)
                    {
                        Claim claim = CheckSidEquivalence(identitySid, claimSet);
                        if (claim != null)
                        {
                            //SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                            return(true);
                        }
                    }
                }
                SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, GetType());
                //if (TD.SecurityIdentityVerificationFailureIsEnabled())
                //{
                //    TD.SecurityIdentityVerificationFailure(eventTraceActivity);
                //}

                return(false);
            }
示例#5
0
            public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
            {
                EventTraceActivity eventTraceActivity = null;

                if (identity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
                }

                if (authContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext");
                }


                if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
                {
                    eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
                }

                for (int i = 0; i < authContext.ClaimSets.Count; ++i)
                {
                    ClaimSet claimSet = authContext.ClaimSets[i];
                    if (claimSet.ContainsClaim(identity.IdentityClaim))
                    {
                        SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType());
                        return(true);
                    }

                    // try Claim equivalence
                    string expectedSpn = null;
                    if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    {
                        expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
                        Claim claim = CheckDnsEquivalence(claimSet, expectedSpn);
                        if (claim != null)
                        {
                            SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                            return(true);
                        }
                    }

                    // Allow a Sid claim to support UPN, and SPN identities

                    // SID claims not available yet
                    //SecurityIdentifier identitySid = null;
                    //if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Sid");
                    //}
                    //else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Upn");
                    //}
                    //else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Spn");
                    //}
                    //else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
                    //{
                    //    throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Dns");
                    //}
                    //if (identitySid != null)
                    //{
                    //    Claim claim = CheckSidEquivalence(identitySid, claimSet);
                    //    if (claim != null)
                    //    {
                    //        SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
                    //        return true;
                    //    }
                    //}
                }
                SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, this.GetType());
                if (WcfEventSource.Instance.SecurityIdentityVerificationFailureIsEnabled())
                {
                    WcfEventSource.Instance.SecurityIdentityVerificationFailure(eventTraceActivity);
                }

                return(false);
            }
        protected override async Task <Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper <SecurityMessageProperty> remoteSecurityWrapper)
        {
            if (WcfEventSource.Instance.SslOnInitiateUpgradeIsEnabled())
            {
                WcfEventSource.Instance.SslOnInitiateUpgrade();
            }

            // There is currently no way to convert a .Net X509Certificate2 to a UWP Certificate. The client certificate
            // needs to be provided by looking it up in the certificate store. E.g.
            //
            //     factory.Credentials.ClientCertificate.SetCertificate(
            //         StoreLocation.CurrentUser,
            //         StoreName.My,
            //         X509FindType.FindByThumbprint,
            //         clientCertThumb);
            //
            // The certificate is retrieved using .Net api's and UWP api's. An artifical X509Extension is used to attach the
            // UWP certificate to the .Net X509Certificate2. This is then retrieved at the point of usage to use with UWP
            // networking api's.

            Certificate clientCertificate = null;

            if (_clientToken != null)
            {
                foreach (var extension in _clientToken.Certificate.Extensions)
                {
                    var attachmentExtension =
                        extension as X509CertificateInitiatorClientCredential.X509UwpCertificateAttachmentExtension;
                    if (attachmentExtension != null && attachmentExtension.AttachedCertificate != null)
                    {
                        clientCertificate = attachmentExtension.AttachedCertificate;
                        break;
                    }
                }

                Contract.Assert(clientCertificate != null, "Missing UWP Certificate as an attachment to X509Certificate2");
            }

            try
            {
                // Fetch the underlying raw transport object. For UWP, this will be a StreamSocket
                var connectionStream = stream as ConnectionStream;
                Contract.Assert(connectionStream != null, "stream is either null or not a ConnectionStream");
                var rtStreamSocket = connectionStream.Connection.GetCoreTransport() as StreamSocket;
                Contract.Assert(rtStreamSocket != null, "Core transport is either null or not a StreamSocket");
                rtStreamSocket.Control.ClientCertificate = clientCertificate;

                // On CoreClr, we use SslStream which calls a callback with any problems with the server certificate, which
                // returns whether to accept the certificate or not. With SocketStream in UWP, any custom validation needs to
                // happen after the connection has successfully negotiated. Some certificate errors need to be set to be ignored
                // to allow the connection to be established so we can retrieve the server certificate and choose whether to
                // accept the server certificate or not.
                rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
                rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
                rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain);
                rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(
                    ChainValidationResult.RevocationInformationMissing);
                rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationFailure);

                // SocketStream doesn't take a bitwise field of accepted protocols, but instead accepts a value specifying the highest
                // protocol that can be negotiated. A check is made for each of the protocols in order to see if they've been requested
                // by the binding and set the protection level to the UWP equivalent. This will have the effect of protectionLevel being
                // set to the most secure protocol that was specified by client code. After the connection is established, if a protocol
                // was negotiated which the binding didn't request, the connection needs to be aborted. This could happen for example if
                // the requested SslProtocols was SslProtocols.Tls11 | SslProtocols.Tls12 and the server only supported SSL3 | Tls10. In
                // this case, SocketProtectionLevel would be set to SocketProtectionLevel.Tls12, which would mean Tls10, Tls11 and Tls12
                // are all acceptable protocols to negotiate. As the server is offering SSL3 | Tls10, the connection would be successfully
                // negotiated using Tls10 which isn't allowed according to the binding configuration.
                SocketProtectionLevel protectionLevel = SocketProtectionLevel.PlainSocket;
                if ((_parent.SslProtocols & SslProtocols.Tls) != SslProtocols.None)
                {
                    protectionLevel = SocketProtectionLevel.Tls10;
                }
                if ((_parent.SslProtocols & SslProtocols.Tls11) != SslProtocols.None)
                {
                    protectionLevel = SocketProtectionLevel.Tls11;
                }
                if ((_parent.SslProtocols & SslProtocols.Tls12) != SslProtocols.None)
                {
                    protectionLevel = SocketProtectionLevel.Tls12;
                }

                // With SslStream, the hostname provided in the server certificate is provided to the client and verified in the callback.
                // With UWP StreamSocket, the hostname needs to be provided to the call to UpgradeToSslAsync. The code to fetch the identity
                // lives in the callback for CoreClr but needs to be pulled into this method for UWP.
                EndpointAddress remoteAddress = RemoteAddress;
                if (remoteAddress.Identity == null && remoteAddress.Uri != Via)
                {
                    remoteAddress = new EndpointAddress(Via);
                }
                EndpointIdentity identity;
                if (!_parent.IdentityVerifier.TryGetIdentity(remoteAddress, out identity))
                {
                    SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity: identity, authContext: null, identityVerifier: GetType());
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(
                              new MessageSecurityException(SR.Format(SR.IdentityCheckFailedForOutgoingMessage, identity,
                                                                     remoteAddress)));
                }
                Contract.Assert(identity.IdentityClaim.ClaimType == ClaimTypes.Dns);
                string dnsHostName = identity.IdentityClaim.Resource as string;

                // This is the actual call to negotiate an SSL connection
                await rtStreamSocket.UpgradeToSslAsync(protectionLevel, new HostName(dnsHostName)).AsTask();

                // Verify that we didn't negotiate a protocol lower than the binding configuration specified. No need to check Tls12
                // as it will only be negotiated if Tls12 was actually specified.
                var negotiatedProtectionLevel = rtStreamSocket.Information.ProtectionLevel;
                if ((negotiatedProtectionLevel == SocketProtectionLevel.Tls11 && (_parent.SslProtocols & SslProtocols.Tls11) == SslProtocols.None) ||
                    (negotiatedProtectionLevel == SocketProtectionLevel.Tls10 && (_parent.SslProtocols & SslProtocols.Tls) == SslProtocols.None))
                {
                    // Need to dispose StreamSocket as normally SslStream wouldn't end up in a usable state in this situation. As
                    // post-upgrade validation is required in UWP, the connection needs to be Dispose'd to ensure it isn't used.
                    rtStreamSocket.Dispose();
                    throw new SecurityNegotiationException(SR.Format(SR.SSLProtocolNegotiationFailed, _parent.SslProtocols, negotiatedProtectionLevel));
                }

                X509Certificate2   serverCertificate = null;
                X509Certificate2[] chainCertificates = null;
                X509Chain          chain             = null;
                try
                {
                    // Convert the UWP Certificate object to a .Net X509Certificate2.
                    byte[] serverCertificateBlob =
                        rtStreamSocket.Information.ServerCertificate.GetCertificateBlob().ToArray();
                    serverCertificate = new X509Certificate2(serverCertificateBlob);

                    // The chain building and validation logic is done by SslStream in CoreClr. This section of code is based
                    // on the SslStream implementation to try to maintain behavior parity.
                    chain = new X509Chain();
                    chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                    chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;

                    var serverIntermediateCertificates = rtStreamSocket.Information.ServerIntermediateCertificates;
                    chainCertificates = new X509Certificate2[serverIntermediateCertificates.Count];
                    for (int i = 0; i < chainCertificates.Length; i++)
                    {
                        chainCertificates[i] =
                            new X509Certificate2(serverIntermediateCertificates[i].GetCertificateBlob().ToArray());
                    }
                    chain.ChainPolicy.ExtraStore.AddRange(chainCertificates);

                    chain.Build(serverCertificate);
                    SslPolicyErrors policyErrors = SslPolicyErrors.None;
                    foreach (var serverCertificateError in rtStreamSocket.Information.ServerCertificateErrors)
                    {
                        if (serverCertificateError == ChainValidationResult.InvalidName)
                        {
                            policyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
                            continue;
                        }
                        if (serverCertificateError == ChainValidationResult.IncompleteChain)
                        {
                            policyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
                        }
                    }

                    X509ChainStatus[] chainStatusArray = chain.ChainStatus;
                    if (chainStatusArray != null && chainStatusArray.Length != 0)
                    {
                        policyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
                    }

                    if (!ValidateRemoteCertificate(this, serverCertificate, chain, policyErrors))
                    {
                        // Need to dispose StreamSocket as normally SslStream wouldn't end up in a usable state in this situation. As
                        // post-upgrade validation is required in UWP, the connection needs to be Dispose'd to ensure it isn't used.
                        rtStreamSocket.Dispose();
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new SecurityNegotiationException(SR.ssl_io_cert_validation));
                    }
                }
                finally
                {
                    serverCertificate?.Dispose();
                    chain?.Dispose();
                    if (chainCertificates != null)
                    {
                        foreach (var chainCert in chainCertificates)
                        {
                            chainCert?.Dispose();
                        }
                    }
                }
            }
            catch (SecurityTokenValidationException tokenValidationException)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new SecurityNegotiationException(tokenValidationException.Message,
                                                           tokenValidationException));
            }
            catch (IOException ioException)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(
                                                                              SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException));
            }
            catch (Exception exception)
            {
                // In NET Native the WinRT API's can throw the base Exception
                // class with an HRESULT indicating the issue.  However, custom
                // validation code can also throw Exception, and to be compatible
                // with the CoreCLR version, we must allow those exceptions to
                // propagate without wrapping them.  We use the simple heuristic
                // that if an HRESULT has been set to other than the default,
                // the exception should be wrapped in SecurityNegotiationException.
                if (exception.HResult == __HResults.COR_E_EXCEPTION)
                {
                    throw;
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(
                                                                              exception.Message, exception));
            }

            remoteSecurityWrapper.Value = _serverSecurity;

            return(stream);
        }