protected override Stream OnAcceptUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity)
 {
     SslStream stream2 = new SslStream(stream, false, new RemoteCertificateValidationCallback(this.ValidateRemoteCertificate));
     try
     {
         stream2.AuthenticateAsServer(this.parent.ServerCertificate, this.parent.RequireClientCertificate, SslProtocols.Default, false);
     }
     catch (AuthenticationException exception)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception));
     }
     catch (IOException exception2)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NegotiationFailedIO", new object[] { exception2.Message }), exception2));
     }
     if (System.ServiceModel.Security.SecurityUtils.ShouldValidateSslCipherStrength())
     {
         System.ServiceModel.Security.SecurityUtils.ValidateSslCipherStrength(stream2.CipherStrength);
     }
     remoteSecurity = this.clientSecurity;
     if (this.IsChannelBindingSupportEnabled)
     {
         this.channelBindingToken = ChannelBindingUtility.GetToken(stream2);
     }
     return stream2;
 }
 protected virtual void OnVerifyIncomingMessageFailure(Message message, Exception exception)
 {
     SecurityTraceRecordHelper.TraceVerifyIncomingMessageFailure(this, message);
     if ((PerformanceCounters.PerformanceCountersEnabled && (null != this.factory.ListenUri)) && (((exception.GetType() == typeof(MessageSecurityException)) || exception.GetType().IsSubclassOf(typeof(MessageSecurityException))) || ((exception.GetType() == typeof(SecurityTokenException)) || exception.GetType().IsSubclassOf(typeof(SecurityTokenException)))))
     {
         PerformanceCounters.AuthenticationFailed(message, this.factory.ListenUri);
     }
     if (AuditLevel.Failure == (this.factory.MessageAuthenticationAuditLevel & AuditLevel.Failure))
     {
         try
         {
             string identityNamesFromContext;
             SecurityMessageProperty security = message.Properties.Security;
             if ((security != null) && (security.ServiceSecurityContext != null))
             {
                 identityNamesFromContext = System.ServiceModel.Security.SecurityUtils.GetIdentityNamesFromContext(security.ServiceSecurityContext.AuthorizationContext);
             }
             else
             {
                 identityNamesFromContext = System.ServiceModel.Security.SecurityUtils.AnonymousIdentity.Name;
             }
             SecurityAuditHelper.WriteMessageAuthenticationFailureEvent(this.factory.AuditLogLocation, this.factory.SuppressAuditFailure, message, message.Headers.To, message.Headers.Action, identityNamesFromContext, exception);
         }
         catch (Exception exception2)
         {
             if (Fx.IsFatal(exception2))
             {
                 throw;
             }
             DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Error);
         }
     }
 }
 protected void AddSupportingTokenSpecification(SecurityMessageProperty security, IList <SecurityToken> basicTokens, IList <SecurityToken> endorsingTokens, IList <SecurityToken> signedEndorsingTokens, IList <SecurityToken> signedTokens, IDictionary <SecurityToken, ReadOnlyCollection <IAuthorizationPolicy> > tokenPoliciesMapping)
 {
     AddSupportingTokenSpecification(security, basicTokens, SecurityTokenAttachmentMode.SignedEncrypted, tokenPoliciesMapping);
     AddSupportingTokenSpecification(security, endorsingTokens, SecurityTokenAttachmentMode.Endorsing, tokenPoliciesMapping);
     AddSupportingTokenSpecification(security, signedEndorsingTokens, SecurityTokenAttachmentMode.SignedEndorsing, tokenPoliciesMapping);
     AddSupportingTokenSpecification(security, signedTokens, SecurityTokenAttachmentMode.Signed, tokenPoliciesMapping);
 }
Beispiel #4
0
        internal bool CheckAccess(EndpointAddress reference, Message message)
        {
            if (reference == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reference");
            }
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }

            EndpointIdentity identity;

            if (!this.TryGetIdentity(reference, out identity))
            {
                return(false);
            }

            SecurityMessageProperty securityContextProperty = null;

            if (message.Properties != null)
            {
                securityContextProperty = message.Properties.Security;
            }

            if (securityContextProperty == null || securityContextProperty.ServiceSecurityContext == null)
            {
                return(false);
            }

            return(this.CheckAccess(identity, securityContextProperty.ServiceSecurityContext.AuthorizationContext));
        }
        public IMessageProperty CreateCopy()
        {
            ThrowIfDisposed();
            SecurityMessageProperty result = new SecurityMessageProperty();

            if (this.HasOutgoingSupportingTokens)
            {
                for (int i = 0; i < _outgoingSupportingTokens.Count; ++i)
                {
                    result.OutgoingSupportingTokens.Add(_outgoingSupportingTokens[i]);
                }
            }

            if (this.HasIncomingSupportingTokens)
            {
                for (int i = 0; i < _incomingSupportingTokens.Count; ++i)
                {
                    result.IncomingSupportingTokens.Add(_incomingSupportingTokens[i]);
                }
            }

            result._securityContext = _securityContext;
            result._externalAuthorizationPolicies = _externalAuthorizationPolicies;
            result._senderIdPrefix = _senderIdPrefix;

            result._protectionToken = _protectionToken;
            result._initiatorToken  = _initiatorToken;
            result._recipientToken  = _recipientToken;
            result._transportToken  = _transportToken;

            return(result);
        }
Beispiel #6
0
		public InitiatorSecureMessageDecryptor (
			Message source, SecurityMessageProperty secprop, InitiatorMessageSecurityBindingSupport security)
			: base (source, security)
		{
			this.security = security;
			request_security = secprop;
		}
 public IMessageProperty CreateCopy()
 {
     this.ThrowIfDisposed();
     SecurityMessageProperty property = new SecurityMessageProperty();
     if (this.HasOutgoingSupportingTokens)
     {
         for (int i = 0; i < this.outgoingSupportingTokens.Count; i++)
         {
             property.OutgoingSupportingTokens.Add(this.outgoingSupportingTokens[i]);
         }
     }
     if (this.HasIncomingSupportingTokens)
     {
         for (int j = 0; j < this.incomingSupportingTokens.Count; j++)
         {
             property.IncomingSupportingTokens.Add(this.incomingSupportingTokens[j]);
         }
     }
     property.securityContext = this.securityContext;
     property.externalAuthorizationPolicies = this.externalAuthorizationPolicies;
     property.senderIdPrefix = this.senderIdPrefix;
     property.protectionToken = this.protectionToken;
     property.initiatorToken = this.initiatorToken;
     property.recipientToken = this.recipientToken;
     property.transportToken = this.transportToken;
     return property;
 }
        public IMessageProperty CreateCopy()
        {
            this.ThrowIfDisposed();
            SecurityMessageProperty property = new SecurityMessageProperty();

            if (this.HasOutgoingSupportingTokens)
            {
                for (int i = 0; i < this.outgoingSupportingTokens.Count; i++)
                {
                    property.OutgoingSupportingTokens.Add(this.outgoingSupportingTokens[i]);
                }
            }
            if (this.HasIncomingSupportingTokens)
            {
                for (int j = 0; j < this.incomingSupportingTokens.Count; j++)
                {
                    property.IncomingSupportingTokens.Add(this.incomingSupportingTokens[j]);
                }
            }
            property.securityContext = this.securityContext;
            property.externalAuthorizationPolicies = this.externalAuthorizationPolicies;
            property.senderIdPrefix  = this.senderIdPrefix;
            property.protectionToken = this.protectionToken;
            property.initiatorToken  = this.initiatorToken;
            property.recipientToken  = this.recipientToken;
            property.transportToken  = this.transportToken;
            return(property);
        }
        protected void AttachRecipientSecurityProperty(Message message, IList <SecurityToken> basicTokens, IList <SecurityToken> endorsingTokens, IList <SecurityToken> signedEndorsingTokens, IList <SecurityToken> signedTokens, Dictionary <SecurityToken, ReadOnlyCollection <IAuthorizationPolicy> > tokenPoliciesMapping)
        {
            SecurityMessageProperty orCreate = SecurityMessageProperty.GetOrCreate(message);

            base.AddSupportingTokenSpecification(orCreate, basicTokens, endorsingTokens, signedEndorsingTokens, signedTokens, tokenPoliciesMapping);
            orCreate.ServiceSecurityContext = new ServiceSecurityContext(orCreate.GetInitiatorTokenAuthorizationPolicies());
        }
        protected override BodyWriter GetNextOutgoingMessageBody(Message incomingMessage, AcceleratedTokenProviderState negotiationState)
        {
            ThrowIfFault(incomingMessage, TargetAddress);
            if (incomingMessage.Headers.Action != RequestSecurityTokenResponseAction.Value)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.InvalidActionForNegotiationMessage, incomingMessage.Headers.Action)), incomingMessage);
            }
            // get the claims corresponding to the server
            SecurityMessageProperty serverContextProperty = incomingMessage.Properties.Security;
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            if (serverContextProperty != null && serverContextProperty.ServiceSecurityContext != null)
            {
                authorizationPolicies = serverContextProperty.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }
            RequestSecurityTokenResponse rstr       = null;
            XmlDictionaryReader          bodyReader = incomingMessage.GetReaderAtBodyContents();

            using (bodyReader)
            {
                if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    rstr = RequestSecurityTokenResponse.CreateFrom(StandardsManager, bodyReader);
                }
                else if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
                {
                    RequestSecurityTokenResponseCollection rstrc = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(bodyReader);

                    foreach (RequestSecurityTokenResponse rstrItem in rstrc.RstrCollection)
                    {
                        if (rstr != null)
                        {
                            // More than one RSTR is found. So throw an exception.
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MoreThanOneRSTRInRSTRC));
                        }
                        rstr = rstrItem;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }

                incomingMessage.ReadFromBodyContentsToEnd(bodyReader);
            }
            if (rstr.Context != negotiationState.Context)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.BadSecurityNegotiationContext), incomingMessage);
            }
            byte[] keyEntropy = negotiationState.GetRequestorEntropy();
            GenericXmlSecurityToken serviceToken = rstr.GetIssuedToken(null, null, _keyEntropyMode, keyEntropy, SecurityContextTokenUri, authorizationPolicies, SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false);

            negotiationState.SetServiceToken(serviceToken);
            return(null);
        }
Beispiel #11
0
        private GenericXmlSecurityToken ExtractToken(Message response, object requestState)
        {
            // get the claims corresponding to the server
            SecurityMessageProperty serverContextProperty = response.Properties.Security;
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            if (serverContextProperty != null && serverContextProperty.ServiceSecurityContext != null)
            {
                authorizationPolicies = serverContextProperty.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }

            RequestSecurityTokenResponse rstr       = null;
            XmlDictionaryReader          bodyReader = response.GetReaderAtBodyContents();

            using (bodyReader)
            {
                if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    rstr = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponse(bodyReader);
                }
                else if (StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
                {
                    RequestSecurityTokenResponseCollection rstrc = StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(bodyReader);
                    foreach (RequestSecurityTokenResponse rstrItem in rstrc.RstrCollection)
                    {
                        if (rstr != null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.MoreThanOneRSTRInRSTRC));
                        }

                        rstr = rstrItem;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }

                response.ReadFromBodyContentsToEnd(bodyReader);
            }

            byte[] requestorEntropy;
            if (requestState != null)
            {
                requestorEntropy = (byte[])requestState;
            }
            else
            {
                requestorEntropy = null;
            }

            GenericXmlSecurityToken issuedToken = rstr.GetIssuedToken(null, null, KeyEntropyMode, requestorEntropy, _sctUri, authorizationPolicies, SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false);

            return(issuedToken);
        }
        // helper method for attaching the server claims in a symmetric security protocol
        protected void DoIdentityCheckAndAttachInitiatorSecurityProperty(Message message, SecurityToken protectionToken, ReadOnlyCollection <IAuthorizationPolicy> protectionTokenPolicies)
        {
            AuthorizationContext    protectionAuthContext = EnsureIncomingIdentity(message, protectionToken, protectionTokenPolicies);
            SecurityMessageProperty security = SecurityMessageProperty.GetOrCreate(message);

            security.ProtectionToken        = new SecurityTokenSpecification(protectionToken, protectionTokenPolicies);
            security.ServiceSecurityContext = new ServiceSecurityContext(protectionAuthContext, protectionTokenPolicies ?? EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance);
        }
 protected SingletonConnectionReader(IConnection connection, int offset, int size, SecurityMessageProperty security, IConnectionOrientedTransportFactorySettings transportSettings, Uri via)
 {
     this.connection = connection;
     this.offset = offset;
     this.size = size;
     this.security = security;
     this.transportSettings = transportSettings;
     this.via = via;
 }
        void DoIdentityCheckAndAttachInitiatorSecurityProperty(Message message, SecurityToken initiatorToken, SecurityToken recipientToken, ReadOnlyCollection <IAuthorizationPolicy> recipientTokenPolicies)
        {
            AuthorizationContext    recipientAuthorizationContext = base.EnsureIncomingIdentity(message, recipientToken, recipientTokenPolicies);
            SecurityMessageProperty security = SecurityMessageProperty.GetOrCreate(message);

            security.InitiatorToken         = (initiatorToken != null) ? new SecurityTokenSpecification(initiatorToken, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance) : null;
            security.RecipientToken         = new SecurityTokenSpecification(recipientToken, recipientTokenPolicies);
            security.ServiceSecurityContext = new ServiceSecurityContext(recipientAuthorizationContext, recipientTokenPolicies ?? EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance);
        }
        private static void SetSecurityHeaderId(SendSecurityHeader securityHeader, Message message)
        {
            SecurityMessageProperty messageProperty = message.Properties.Security;

            if (messageProperty != null)
            {
                securityHeader.IdPrefix = messageProperty.SenderIdPrefix;
            }
        }
        private void AttachRecipientSecurityProperty(Message message, SecurityToken initiatorToken, SecurityToken recipientToken, IList <SecurityToken> basicTokens, IList <SecurityToken> endorsingTokens, IList <SecurityToken> signedEndorsingTokens, IList <SecurityToken> signedTokens, Dictionary <SecurityToken, ReadOnlyCollection <IAuthorizationPolicy> > tokenPoliciesMapping)
        {
            SecurityMessageProperty orCreate = SecurityMessageProperty.GetOrCreate(message);

            orCreate.InitiatorToken = (initiatorToken != null) ? new SecurityTokenSpecification(initiatorToken, tokenPoliciesMapping[initiatorToken]) : null;
            orCreate.RecipientToken = (recipientToken != null) ? new SecurityTokenSpecification(recipientToken, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance) : null;
            base.AddSupportingTokenSpecification(orCreate, basicTokens, endorsingTokens, signedEndorsingTokens, signedTokens, tokenPoliciesMapping);
            orCreate.ServiceSecurityContext = new ServiceSecurityContext(orCreate.GetInitiatorTokenAuthorizationPolicies());
        }
Beispiel #17
0
        public SecurityTokenSpecificationEnumerable(SecurityMessageProperty securityMessageProperty)
        {
            if (securityMessageProperty == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityMessageProperty");
            }

            _securityMessageProperty = securityMessageProperty;
        }
Beispiel #18
0
        protected override BodyWriter GetNextOutgoingMessageBody(Message incomingMessage, AcceleratedTokenProviderState negotiationState)
        {
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            IssuanceTokenProviderBase <AcceleratedTokenProviderState> .ThrowIfFault(incomingMessage, base.TargetAddress);

            if (incomingMessage.Headers.Action != this.RequestSecurityTokenResponseAction.Value)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidActionForNegotiationMessage", new object[] { incomingMessage.Headers.Action })), incomingMessage);
            }
            SecurityMessageProperty security = incomingMessage.Properties.Security;

            if ((security != null) && (security.ServiceSecurityContext != null))
            {
                authorizationPolicies = security.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }
            RequestSecurityTokenResponse response             = null;
            XmlDictionaryReader          readerAtBodyContents = incomingMessage.GetReaderAtBodyContents();

            using (readerAtBodyContents)
            {
                if (base.StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    response = RequestSecurityTokenResponse.CreateFrom(base.StandardsManager, readerAtBodyContents);
                }
                else
                {
                    if (base.StandardsManager.MessageSecurityVersion.TrustVersion != TrustVersion.WSTrust13)
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                    }
                    foreach (RequestSecurityTokenResponse response2 in base.StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(readerAtBodyContents).RstrCollection)
                    {
                        if (response != null)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("MoreThanOneRSTRInRSTRC")));
                        }
                        response = response2;
                    }
                }
                incomingMessage.ReadFromBodyContentsToEnd(readerAtBodyContents);
            }
            if (response.Context != negotiationState.Context)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("BadSecurityNegotiationContext")), incomingMessage);
            }
            byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
            GenericXmlSecurityToken serviceToken = response.GetIssuedToken(null, null, this.keyEntropyMode, requestorEntropy, base.SecurityContextTokenUri, authorizationPolicies, base.SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false);

            negotiationState.SetServiceToken(serviceToken);
            return(null);
        }
 private void AddSupportingTokenSpecification(SecurityMessageProperty security, IList <SecurityToken> tokens, SecurityTokenAttachmentMode attachmentMode, IDictionary <SecurityToken, ReadOnlyCollection <IAuthorizationPolicy> > tokenPoliciesMapping)
 {
     if ((tokens != null) && (tokens.Count != 0))
     {
         for (int i = 0; i < tokens.Count; i++)
         {
             security.IncomingSupportingTokens.Add(new SupportingTokenSpecification(tokens[i], tokenPoliciesMapping[tokens[i]], attachmentMode));
         }
     }
 }
        public static SecurityMessageProperty GetOrCreate(Message message)
        {
            SecurityMessageProperty s = message.Properties.Security;

            if (s == null)
            {
                s = new SecurityMessageProperty();
                message.Properties.Security = s;
            }
            return(s);
        }
Beispiel #21
0
 void AddSupportingTokenSpecification(SecurityMessageProperty security, IList <SecurityToken> tokens, SecurityTokenAttachmentMode attachmentMode, IDictionary <SecurityToken, ReadOnlyCollection <IAuthorizationPolicy> > tokenPoliciesMapping)
 {
     if (tokens == null || tokens.Count == 0)
     {
         return;
     }
     for (int i = 0; i < tokens.Count; ++i)
     {
         security.IncomingSupportingTokens.Add(new SupportingTokenSpecification(tokens[i], tokenPoliciesMapping[tokens[i]], attachmentMode));
     }
 }
 public static void AddSupportingToken(Message message, RequestSecurityTokenResponse rstr)
 {
     GenericXmlSecurityToken token = rstr.GetIssuedToken(null, null, SecurityKeyEntropyMode.ServerEntropy, null, null, null);
     SecurityMessageProperty property = new SecurityMessageProperty();
     SupportingTokenSpecification item = new SupportingTokenSpecification(token, new List<IAuthorizationPolicy>().AsReadOnly(), SecurityTokenAttachmentMode.Endorsing, SecurityContextSecurityTokenParameters);
     property.OutgoingSupportingTokens.Add(item);
     message.Properties.Security = property;
     if (DebugTrace.Verbose)
     {
         DebugTrace.Trace(TraceLevel.Verbose, "Attached supporting token {0} to register message", rstr.Context);
     }
 }
        protected SingletonConnectionReader(IConnection connection, int offset, int size, SecurityMessageProperty security,
            IConnectionOrientedTransportFactorySettings transportSettings, Uri via)
        {
            Contract.Assert(connection != null);

            _connection = connection;
            _offset = offset;
            _size = size;
            _security = security;
            _transportSettings = transportSettings;
            _via = via;
        }
 protected SessionConnectionReader(IConnection connection, IConnection rawConnection,
     int offset, int size, SecurityMessageProperty security)
 {
     _offset = offset;
     _size = size;
     if (size > 0)
     {
         _buffer = connection.AsyncReadBuffer;
     }
     _connection = connection;
     _rawConnection = rawConnection;
     _security = security;
 }
 protected SessionConnectionReader(IConnection connection, IConnection rawConnection, int offset, int size, SecurityMessageProperty security)
 {
     this.offset = offset;
     this.size = size;
     if (size > 0)
     {
         this.buffer = connection.AsyncReadBuffer;
     }
     this.connection = connection;
     this.rawConnection = rawConnection;
     this.onAsyncReadComplete = new WaitCallback(this.OnAsyncReadComplete);
     this.security = security;
 }
Beispiel #26
0
        private GenericXmlSecurityToken ExtractToken(Message response, object requestState)
        {
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;

            byte[] buffer;
            SecurityMessageProperty security = response.Properties.Security;

            if ((security != null) && (security.ServiceSecurityContext != null))
            {
                authorizationPolicies = security.ServiceSecurityContext.AuthorizationPolicies;
            }
            else
            {
                authorizationPolicies = System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }
            RequestSecurityTokenResponse response2            = null;
            XmlDictionaryReader          readerAtBodyContents = response.GetReaderAtBodyContents();

            using (readerAtBodyContents)
            {
                if (this.StandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrustFeb2005)
                {
                    response2 = this.StandardsManager.TrustDriver.CreateRequestSecurityTokenResponse(readerAtBodyContents);
                }
                else
                {
                    if (this.StandardsManager.MessageSecurityVersion.TrustVersion != TrustVersion.WSTrust13)
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                    }
                    foreach (RequestSecurityTokenResponse response3 in this.StandardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(readerAtBodyContents).RstrCollection)
                    {
                        if (response2 != null)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("MoreThanOneRSTRInRSTRC")));
                        }
                        response2 = response3;
                    }
                }
                response.ReadFromBodyContentsToEnd(readerAtBodyContents);
            }
            if (requestState != null)
            {
                buffer = (byte[])requestState;
            }
            else
            {
                buffer = null;
            }
            return(response2.GetIssuedToken(null, null, this.KeyEntropyMode, buffer, this.sctUri, authorizationPolicies, this.SecurityAlgorithmSuite.DefaultSymmetricKeyLength, false));
        }
 private void CompleteAuthenticateAsClient(IAsyncResult result)
 {
     try
     {
         this.upgradedStream = this.OnCompleteAuthenticateAsClient(result);
     }
     catch (AuthenticationException exception)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception));
     }
     catch (IOException exception2)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NegotiationFailedIO", new object[] { exception2.Message }), exception2));
     }
     this.remoteSecurity = this.ValidateCreateSecurity();
 }
        protected virtual Message CreateRenewRequest(EndpointAddress target, SecurityToken currentSessionToken, out object requestState)
        {
            this.CommunicationObject.ThrowIfClosedOrNotOpen();
            RequestSecurityToken rst = CreateRst(target, out requestState);

            rst.RequestType = this.StandardsManager.TrustDriver.RequestTypeRenew;
            rst.RenewTarget = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(currentSessionToken, SecurityTokenReferenceStyle.External);
            rst.MakeReadOnly();
            Message result = Message.CreateMessage(this.MessageVersion, ActionHeader.Create(this.RenewAction, this.MessageVersion.Addressing), rst);
            SecurityMessageProperty supportingTokenProperty = new SecurityMessageProperty();

            supportingTokenProperty.OutgoingSupportingTokens.Add(new SupportingTokenSpecification(currentSessionToken, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, this.IssuedSecurityTokenParameters));
            result.Properties.Security = supportingTokenProperty;
            PrepareRequest(result);
            return(result);
        }
 public override SecurityMessageProperty GetRemoteSecurity()
 {
     if (this.clientSecurity.TransportToken != null)
     {
         return this.clientSecurity;
     }
     if (this.clientCertificate != null)
     {
         SecurityToken token = new X509SecurityToken(this.clientCertificate);
         ReadOnlyCollection<IAuthorizationPolicy> tokenPolicies = System.ServiceModel.Security.SecurityUtils.NonValidatingX509Authenticator.ValidateToken(token);
         this.clientSecurity = new SecurityMessageProperty();
         this.clientSecurity.TransportToken = new SecurityTokenSpecification(token, tokenPolicies);
         this.clientSecurity.ServiceSecurityContext = new ServiceSecurityContext(tokenPolicies);
         return this.clientSecurity;
     }
     return base.GetRemoteSecurity();
 }
Beispiel #30
0
        protected virtual Message CreateRenewRequest(EndpointAddress target, SecurityToken currentSessionToken, out object requestState)
        {
            base.CommunicationObject.ThrowIfClosedOrNotOpen();
            RequestSecurityToken body = this.CreateRst(target, out requestState);

            body.RequestType = this.StandardsManager.TrustDriver.RequestTypeRenew;
            body.RenewTarget = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(currentSessionToken, SecurityTokenReferenceStyle.External);
            body.MakeReadOnly();
            Message message = Message.CreateMessage(this.MessageVersion, ActionHeader.Create(this.RenewAction, this.MessageVersion.Addressing), body);
            SecurityMessageProperty property = new SecurityMessageProperty {
                OutgoingSupportingTokens = { new SupportingTokenSpecification(currentSessionToken, System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, this.IssuedSecurityTokenParameters) }
            };

            message.Properties.Security = property;
            this.PrepareRequest(message);
            return(message);
        }
        protected void AttachRecipientSecurityProperty(Message message, SecurityToken protectionToken, bool isWrappedToken, IList <SecurityToken> basicTokens, IList <SecurityToken> endorsingTokens, IList <SecurityToken> signedEndorsingTokens, IList <SecurityToken> signedTokens, Dictionary <SecurityToken, ReadOnlyCollection <IAuthorizationPolicy> > tokenPoliciesMapping)
        {
            ReadOnlyCollection <IAuthorizationPolicy> instance;

            if (isWrappedToken)
            {
                instance = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
            }
            else
            {
                instance = tokenPoliciesMapping[protectionToken];
            }
            SecurityMessageProperty orCreate = SecurityMessageProperty.GetOrCreate(message);

            orCreate.ProtectionToken = new SecurityTokenSpecification(protectionToken, instance);
            base.AddSupportingTokenSpecification(orCreate, basicTokens, endorsingTokens, signedEndorsingTokens, signedTokens, tokenPoliciesMapping);
            orCreate.ServiceSecurityContext = new ServiceSecurityContext(orCreate.GetInitiatorTokenAuthorizationPolicies());
        }
        internal IConnection SendPreamble(IConnection connection, ref TimeoutHelper timeoutHelper,
            ClientFramingDecoder decoder, out SecurityMessageProperty remoteSecurity)
        {
            connection.Write(Preamble, 0, Preamble.Length, true, timeoutHelper.RemainingTime());

            if (_upgrade != null)
            {
                IStreamUpgradeChannelBindingProvider channelBindingProvider = _upgrade.GetProperty<IStreamUpgradeChannelBindingProvider>();

                StreamUpgradeInitiator upgradeInitiator = _upgrade.CreateUpgradeInitiator(this.RemoteAddress, this.Via);

                if (!ConnectionUpgradeHelper.InitiateUpgrade(upgradeInitiator, ref connection, decoder,
                    this, ref timeoutHelper))
                {
                    ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, Via, _messageEncoder.ContentType, ref timeoutHelper);
                }

#if FEATURE_CORECLR // ExtendedProtection
                if (channelBindingProvider != null && channelBindingProvider.IsChannelBindingSupportEnabled)
                {
                    _channelBindingToken = channelBindingProvider.GetChannelBinding(upgradeInitiator, ChannelBindingKind.Endpoint);
                }
#endif // FEATURE_CORECLR // ExtendedProtection

                remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(upgradeInitiator);

                connection.Write(ClientSingletonEncoder.PreambleEndBytes, 0,
                    ClientSingletonEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
            }
            else
            {
                remoteSecurity = null;
            }

            // read ACK
            byte[] ackBuffer = new byte[1];
            int ackBytesRead = connection.Read(ackBuffer, 0, ackBuffer.Length, timeoutHelper.RemainingTime());
            if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, decoder, this.Via))
            {
                ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, Via, _messageEncoder.ContentType, ref timeoutHelper);
            }

            return connection;
        }
        public static SecurityMessageProperty GetOrCreate(Message message)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            SecurityMessageProperty security = null;

            if (message.Properties != null)
            {
                security = message.Properties.Security;
            }
            if (security == null)
            {
                security = new SecurityMessageProperty();
                message.Properties.Security = security;
            }
            return(security);
        }
        void CompleteAuthenticateAsServer(IAsyncResult result)
        {
            try
            {
                this.upgradedStream = this.OnCompleteAuthenticateAsServer(result);
            }
            catch (AuthenticationException exception)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message,
                    exception));
            }
            catch (IOException ioException)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(
                    SR.GetString(SR.NegotiationFailedIO, ioException.Message), ioException));
            }

            this.remoteSecurity = this.ValidateCreateSecurity();
        }
Beispiel #35
0
        protected virtual void OnVerifyIncomingMessageFailure(Message message, Exception exception)
        {
            SecurityTraceRecordHelper.TraceVerifyIncomingMessageFailure(this, message);
            if (PerformanceCounters.PerformanceCountersEnabled && null != this.factory.ListenUri) //service side
            {
                if ((exception.GetType() == typeof(MessageSecurityException) || exception.GetType().IsSubclassOf(typeof(MessageSecurityException))) ||
                    (exception.GetType() == typeof(SecurityTokenException) || exception.GetType().IsSubclassOf(typeof(SecurityTokenException))))
                {
                    PerformanceCounters.AuthenticationFailed(message, this.factory.ListenUri);
                }
            }

            if (AuditLevel.Failure == (this.factory.MessageAuthenticationAuditLevel & AuditLevel.Failure))
            {
                try
                {
                    SecurityMessageProperty security = message.Properties.Security;
                    string primaryIdentity;
                    if (security != null && security.ServiceSecurityContext != null)
                    {
                        primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(security.ServiceSecurityContext.AuthorizationContext);
                    }
                    else
                    {
                        primaryIdentity = SecurityUtils.AnonymousIdentity.Name;
                    }

                    SecurityAuditHelper.WriteMessageAuthenticationFailureEvent(this.factory.AuditLogLocation,
                                                                               this.factory.SuppressAuditFailure, message, message.Headers.To, message.Headers.Action, primaryIdentity, exception);
                }
#pragma warning suppress 56500
                catch (Exception auditException)
                {
                    if (Fx.IsFatal(auditException))
                    {
                        throw;
                    }

                    DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error);
                }
            }
        }
        internal void AddMessageSupportingTokens(Message message, ref IList <SupportingTokenSpecification> supportingTokens)
        {
            SecurityMessageProperty security = message.Properties.Security;

            if ((security != null) && security.HasOutgoingSupportingTokens)
            {
                if (supportingTokens == null)
                {
                    supportingTokens = new Collection <SupportingTokenSpecification>();
                }
                for (int i = 0; i < security.OutgoingSupportingTokens.Count; i++)
                {
                    SupportingTokenSpecification item = security.OutgoingSupportingTokens[i];
                    if (item.SecurityTokenParameters == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("SenderSideSupportingTokensMustSpecifySecurityTokenParameters")));
                    }
                    supportingTokens.Add(item);
                }
            }
        }
Beispiel #37
0
        internal void AddMessageSupportingTokens(Message message, ref IList <SupportingTokenSpecification> supportingTokens)
        {
            SecurityMessageProperty supportingTokensProperty = message.Properties.Security;

            if (supportingTokensProperty != null && supportingTokensProperty.HasOutgoingSupportingTokens)
            {
                if (supportingTokens == null)
                {
                    supportingTokens = new Collection <SupportingTokenSpecification>();
                }
                for (int i = 0; i < supportingTokensProperty.OutgoingSupportingTokens.Count; ++i)
                {
                    SupportingTokenSpecification spec = supportingTokensProperty.OutgoingSupportingTokens[i];
                    if (spec.SecurityTokenParameters == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SenderSideSupportingTokensMustSpecifySecurityTokenParameters)));
                    }
                    supportingTokens.Add(spec);
                }
            }
        }
Beispiel #38
0
        public static SecurityMessageProperty GetOrCreate(Message message)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(message));
            }

            SecurityMessageProperty result = null;

            if (message.Properties != null)
            {
                result = message.Properties.Security;
            }

            if (result == null)
            {
                result = new SecurityMessageProperty();
                message.Properties.Security = result;
            }

            return(result);
        }
		public Message SecureMessage ()
		{
			secprop = Message.Properties.Security ?? new SecurityMessageProperty ();

			SecurityToken encToken =
				secprop.InitiatorToken != null ? secprop.InitiatorToken.SecurityToken : security.EncryptionToken;
			// FIXME: it might be still incorrect.
			SecurityToken signToken =
				Parameters == CounterParameters ? null :
				security.SigningToken;
			MessageProtectionOrder protectionOrder =
				security.MessageProtectionOrder;
			SecurityTokenSerializer serializer =
				security.TokenSerializer;
			SecurityBindingElement element =
				security.Element;
			SecurityAlgorithmSuite suite = element.DefaultAlgorithmSuite;

// FIXME: remove this hack
if (!ShouldOutputEncryptedKey)
	encToken = new BinarySecretSecurityToken (secprop.EncryptionKey);

			string messageId = "uuid-" + Guid.NewGuid ();
			int identForMessageId = 1;
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;

			UniqueId relatesTo = RelatesTo;
			if (relatesTo != null)
				msg.Headers.RelatesTo = relatesTo;
			else // FIXME: probably it is always added when it is stateful ?
				msg.Headers.MessageId = new UniqueId ("urn:" + messageId);

			// FIXME: get correct ReplyTo value
			if (Direction == MessageDirection.Input)
				msg.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);

			if (MessageTo != null)
				msg.Headers.To = MessageTo.Uri;

			// wss:Security
			WSSecurityMessageHeader header =
				new WSSecurityMessageHeader (serializer);
			msg.Headers.Add (header);
			// 1. [Timestamp]
			if (element.IncludeTimestamp) {
				WsuTimestamp timestamp = new WsuTimestamp ();
				timestamp.Id = messageId + "-" + identForMessageId++;
				timestamp.Created = DateTime.Now;
				// FIXME: on service side, use element.LocalServiceSettings.TimestampValidityDuration
				timestamp.Expires = timestamp.Created.Add (element.LocalClientSettings.TimestampValidityDuration);
				header.AddContent (timestamp);
			}

			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", msg.Version.Envelope.Namespace);
			nsmgr.AddNamespace ("o", Constants.WssNamespace);
			nsmgr.AddNamespace ("u", Constants.WsuNamespace);
			nsmgr.AddNamespace ("o11", Constants.Wss11Namespace);

			/*WrappedKey*/SecurityToken primaryToken = null;
			DerivedKeySecurityToken dkeyToken = null;
			SecurityToken actualToken = null;
			SecurityKeyIdentifierClause actualClause = null;
			Signature sig = null;

			List<DerivedKeySecurityToken> derivedKeys =
				new List<DerivedKeySecurityToken> ();

			SymmetricAlgorithm masterKey = new RijndaelManaged ();
			masterKey.KeySize = suite.DefaultSymmetricKeyLength;
			masterKey.Mode = CipherMode.CBC;
			masterKey.Padding = PaddingMode.ISO10126;
			SymmetricAlgorithm actualKey = masterKey;

			// 2. [Encryption Token]

			// SecurityTokenInclusionMode
			// - Initiator or Recipient
			// - done or notyet. FIXME: not implemented yet
			// It also affects on key reference output

			bool includeEncToken = // /* FIXME: remove this hack */Parameters is SslSecurityTokenParameters ? false :
						ShouldIncludeToken (
				Security.RecipientParameters.InclusionMode, false);
			bool includeSigToken = // /* FIXME: remove this hack */ Parameters is SslSecurityTokenParameters ? false :
						ShouldIncludeToken (
				Security.InitiatorParameters.InclusionMode, false);

			SecurityKeyIdentifierClause encClause = ShouldOutputEncryptedKey ?
				CounterParameters.CallCreateKeyIdentifierClause (encToken, !ShouldOutputEncryptedKey ? SecurityTokenReferenceStyle.Internal : includeEncToken ? Parameters.ReferenceStyle : SecurityTokenReferenceStyle.External) : null;

			MessagePartSpecification sigSpec = SignaturePart;
			MessagePartSpecification encSpec = EncryptionPart;

			// encryption key (possibly also used for signing)
			// FIXME: get correct SymmetricAlgorithm according to the algorithm suite
			if (secprop.EncryptionKey != null)
				actualKey.Key = secprop.EncryptionKey;

// FIXME: remove thid hack
if (!ShouldOutputEncryptedKey)
primaryToken = RequestContext.RequestMessage.Properties.Security.ProtectionToken.SecurityToken as WrappedKeySecurityToken;
else
			primaryToken =
				// FIXME: remove this hack?
				encToken is SecurityContextSecurityToken ? encToken :
				new WrappedKeySecurityToken (messageId + "-" + identForMessageId++,
				actualKey.Key,
				// security.DefaultKeyWrapAlgorithm,
				Parameters.InternalHasAsymmetricKey ?
					suite.DefaultAsymmetricKeyWrapAlgorithm :
					suite.DefaultSymmetricKeyWrapAlgorithm,
				encToken,
				encClause != null ? new SecurityKeyIdentifier (encClause) : null);

			// If it reuses request's encryption key, do not output.
			if (ShouldOutputEncryptedKey)
				header.AddContent (primaryToken);

			actualToken = primaryToken;

			// FIXME: I doubt it is correct...
			WrappedKeySecurityToken requestEncKey = ShouldOutputEncryptedKey ? null : primaryToken as WrappedKeySecurityToken;
			actualClause = requestEncKey == null ? (SecurityKeyIdentifierClause)
				new LocalIdKeyIdentifierClause (actualToken.Id, typeof (WrappedKeySecurityToken)) :
				new InternalEncryptedKeyIdentifierClause (SHA1.Create ().ComputeHash (requestEncKey.GetWrappedKey ()));

			// generate derived key if needed
			if (CounterParameters.RequireDerivedKeys) {
				RijndaelManaged deriv = new RijndaelManaged ();
				deriv.KeySize = suite.DefaultEncryptionKeyDerivationLength;
				deriv.Mode = CipherMode.CBC;
				deriv.Padding = PaddingMode.ISO10126;
				deriv.GenerateKey ();
				dkeyToken = new DerivedKeySecurityToken (
					GenerateId (doc),
					null, // algorithm
					actualClause,
					new InMemorySymmetricSecurityKey (actualKey.Key),
					null, // name
					null, // generation
					null, // offset
					deriv.Key.Length,
					null, // label
					deriv.Key);
				derivedKeys.Add (dkeyToken);
				actualToken = dkeyToken;
				actualKey.Key = ((SymmetricSecurityKey) dkeyToken.SecurityKeys [0]).GetSymmetricKey ();
				actualClause = new LocalIdKeyIdentifierClause (dkeyToken.Id);
				header.AddContent (dkeyToken);
			}

			ReferenceList refList = new ReferenceList ();
			// When encrypted with DerivedKeyToken, put references
			// immediately after the derived token (not inside the
			// primary token).
			// Similarly, when we do not output EncryptedKey,
			// output ReferenceList in the same way.
			if (CounterParameters.RequireDerivedKeys ||
			    !ShouldOutputEncryptedKey)
				header.AddContent (refList);
			else
				((WrappedKeySecurityToken) primaryToken).ReferenceList = refList;

			// [Signature Confirmation]
			if (security.RequireSignatureConfirmation && secprop.ConfirmedSignatures.Count > 0)
				foreach (string value in secprop.ConfirmedSignatures)
					header.AddContent (new Wss11SignatureConfirmation (GenerateId (doc), value));

			SupportingTokenInfoCollection tokenInfos =
				Direction == MessageDirection.Input ?
				security.CollectSupportingTokens (GetAction ()) :
				new SupportingTokenInfoCollection (); // empty

			foreach (SupportingTokenInfo tinfo in tokenInfos)
				header.AddContent (tinfo.Token);

			// populate DOM to sign.
			XPathNavigator nav = doc.CreateNavigator ();
			using (XmlWriter w = nav.AppendChild ()) {
				msg.WriteMessage (w);
			}

			XmlElement body = doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement;
			string bodyId = null;
			XmlElement secElem = null;
			Collection<WSSignedXml> endorsedSignatures =
				new Collection<WSSignedXml> ();
			bool signatureProtection = (protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature);

			// Below are o:Security contents that are not signed...
			if (includeSigToken && signToken != null)
				header.AddContent (signToken);

			switch (protectionOrder) {
			case MessageProtectionOrder.EncryptBeforeSign:
				// FIXME: implement
				throw new NotImplementedException ();
			case MessageProtectionOrder.SignBeforeEncrypt:
			case MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature:

				// sign
				// see clause 8 of WS-SecurityPolicy C.2.2
				WSSignedXml sxml = new WSSignedXml (doc);
				SecurityTokenReferenceKeyInfo sigKeyInfo;

				sig = sxml.Signature;
				sig.SignedInfo.CanonicalizationMethod =
					suite.DefaultCanonicalizationAlgorithm;
				foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/u:Timestamp", nsmgr))
					CreateReference (sig, elem, elem.GetAttribute ("Id", Constants.WsuNamespace));
				foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr))
					CreateReference (sig, elem, elem.GetAttribute ("Id", Constants.WsuNamespace));
				foreach (SupportingTokenInfo tinfo in tokenInfos)
					if (tinfo.Mode != SecurityTokenAttachmentMode.Endorsing) {
						XmlElement el = sxml.GetIdElement (doc, tinfo.Token.Id);
						CreateReference (sig, el, el.GetAttribute ("Id", Constants.WsuNamespace));
					}
				XmlNodeList nodes = doc.SelectNodes ("/s:Envelope/s:Header/*", nsmgr);
				for (int i = 0; i < msg.Headers.Count; i++) {
					MessageHeaderInfo h = msg.Headers [i];
					if (h.Name == "Security" && h.Namespace == Constants.WssNamespace)
						secElem = nodes [i] as XmlElement;
					else if (sigSpec.HeaderTypes.Count == 0 ||
					    sigSpec.HeaderTypes.Contains (new XmlQualifiedName (h.Name, h.Namespace))) {
						string id = GenerateId (doc);
						h.Id = id;
						CreateReference (sig, nodes [i] as XmlElement, id);
					}
				}
				if (sigSpec.IsBodyIncluded) {
					bodyId = GenerateId (doc);
					CreateReference (sig, body.ParentNode as XmlElement, bodyId);
				}

				if (security.DefaultSignatureAlgorithm == SignedXml.XmlDsigHMACSHA1Url) {
					// FIXME: use appropriate hash algorithm
					sxml.ComputeSignature (new HMACSHA1 (actualKey.Key));
					sigKeyInfo = new SecurityTokenReferenceKeyInfo (actualClause, serializer, doc);
				}
				else {
					SecurityKeyIdentifierClause signClause =
						CounterParameters.CallCreateKeyIdentifierClause (signToken, includeSigToken ? CounterParameters.ReferenceStyle : SecurityTokenReferenceStyle.External);
					AsymmetricSecurityKey signKey = (AsymmetricSecurityKey) signToken.ResolveKeyIdentifierClause (signClause);
					sxml.SigningKey = signKey.GetAsymmetricAlgorithm (security.DefaultSignatureAlgorithm, true);
					sxml.ComputeSignature ();
					sigKeyInfo = new SecurityTokenReferenceKeyInfo (signClause, serializer, doc);
				}

				sxml.KeyInfo = new KeyInfo ();
				sxml.KeyInfo.AddClause (sigKeyInfo);

				if (!signatureProtection)
					header.AddContent (sig);

				// endorse the signature with (signed)endorsing
				// supporting tokens.

				foreach (SupportingTokenInfo tinfo in tokenInfos) {
					switch (tinfo.Mode) {
					case SecurityTokenAttachmentMode.Endorsing:
					case SecurityTokenAttachmentMode.SignedEndorsing:
						if (sxml.Signature.Id == null) {
							sig.Id = GenerateId (doc);
							secElem.AppendChild (sxml.GetXml ());
						}
						WSSignedXml ssxml = new WSSignedXml (doc);
						ssxml.Signature.SignedInfo.CanonicalizationMethod = suite.DefaultCanonicalizationAlgorithm;
						CreateReference (ssxml.Signature, doc, sig.Id);
						SecurityToken sst = tinfo.Token;
						SecurityKey ssk = sst.SecurityKeys [0]; // FIXME: could be different?
						SecurityKeyIdentifierClause tclause = new LocalIdKeyIdentifierClause (sst.Id); // FIXME: could be different?
						if (ssk is SymmetricSecurityKey) {
							SymmetricSecurityKey signKey = (SymmetricSecurityKey) ssk;
							ssxml.ComputeSignature (signKey.GetKeyedHashAlgorithm (suite.DefaultSymmetricSignatureAlgorithm));
						} else {
							AsymmetricSecurityKey signKey = (AsymmetricSecurityKey) ssk;
							ssxml.SigningKey = signKey.GetAsymmetricAlgorithm (suite.DefaultAsymmetricSignatureAlgorithm, true);
							ssxml.ComputeSignature ();
						}
						ssxml.KeyInfo.AddClause (new SecurityTokenReferenceKeyInfo (tclause, serializer, doc));
						if (!signatureProtection)
							header.AddContent (ssxml.Signature);
						endorsedSignatures.Add (ssxml);

						break;
					}
				}

				// encrypt

				WSEncryptedXml exml = new WSEncryptedXml (doc);

				EncryptedData edata = Encrypt (body, actualKey, actualToken.Id, refList, actualClause, exml, doc);
				EncryptedXml.ReplaceElement (body, edata, false);

				// encrypt signature
				if (signatureProtection) {
					XmlElement sigxml = sig.GetXml ();
					edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc);
					header.AddContent (edata);

					foreach (WSSignedXml ssxml in endorsedSignatures) {
						sigxml = ssxml.GetXml ();
						edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc);
						header.AddContent (edata);
					}

					if (security.RequireSignatureConfirmation) {
						Collection<Wss11SignatureConfirmation> confs = header.FindAll<Wss11SignatureConfirmation> ();
						int count = 0;
						foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr)) {
							edata = Encrypt (elem, actualKey, confs [count].Id, refList, actualClause, exml, doc);
							EncryptedXml.ReplaceElement (elem, edata, false);
							header.Contents.Insert (header.Contents.IndexOf (confs [count]), edata);
							header.Contents.Remove (confs [count++]);
						}
					}
				}

				// encrypt Encrypted supporting tokens
				foreach (SupportingTokenInfo tinfo in tokenInfos) {
					if (tinfo.Mode == SecurityTokenAttachmentMode.SignedEncrypted) {
						XmlElement el = exml.GetIdElement (doc, tinfo.Token.Id);
						tinfo.Encrypted = Encrypt (el, actualKey, actualToken.Id, refList, actualClause, exml, doc);
						EncryptedXml.ReplaceElement (el, tinfo.Encrypted, false);
						header.Contents.Insert (header.Contents.IndexOf (tinfo.Token), tinfo.Encrypted);
						header.Contents.Remove (tinfo.Token);
					}
				}
				break;
			}

			Message ret = new WSSecurityMessage (Message.CreateMessage (msg.Version, msg.Headers.Action, new XmlNodeReader (doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement)), bodyId);
			ret.Properties.Security = (SecurityMessageProperty) secprop.CreateCopy ();
			ret.Properties.Security.EncryptionKey = masterKey.Key;

			// FIXME: can we support TransportToken here?
			if (element is AsymmetricSecurityBindingElement) {
				ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (encToken, null); // FIXME: second argument
				ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (signToken, null); // FIXME: second argument
			}
			else
				ret.Properties.Security.ProtectionToken = new SecurityTokenSpecification (primaryToken, null);

			ret.Headers.Clear ();
			ret.Headers.CopyHeadersFrom (msg);

			// Header contents are:
			//	- Timestamp
			//	- SignatureConfirmation if required
			//	- EncryptionToken if included
			//	- derived key token for EncryptionToken
			//	- ReferenceList for encrypted items
			//	- signed supporting tokens
			//	- signed endorsing supporting tokens
			//	(i.e. Signed/SignedEncrypted/SignedEndorsing)
			//	- Signature Token if different from enc token.
			//	- derived key token for sig token if different
			//	- Signature for:
			//		- Timestamp
			//		- supporting tokens (regardless of
			//		  its inclusion)
			//		- message parts in SignedParts
			//		- SignatureToken if TokenProtection
			//		  (regardless of its inclusion)
			//	- Signatures for the main signature (above),
			//	  for every endorsing token and signed
			//	  endorsing token.
			//	

//MessageBuffer zzz = ret.CreateBufferedCopy (100000);
//ret = zzz.CreateMessage ();
//Console.WriteLine (zzz.CreateMessage ());
			return ret;
		}
 public static Stream End(IAsyncResult result, out SecurityMessageProperty remoteSecurity)
 {
     StreamSecurityUpgradeAcceptorAsyncResult thisPtr = AsyncResult.End<StreamSecurityUpgradeAcceptorAsyncResult>(result);
     remoteSecurity = thisPtr.remoteSecurity;
     return thisPtr.upgradedStream;
 }
Beispiel #41
0
		protected override IAsyncResult OnBeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
		{
			// FIXME: make it really async
			Message secure = SecureMessage (message);
			secprop = secure.Properties.Security;
			return base.BeginRequest (secure, timeout, callback, state);
		}
 public static Stream End(IAsyncResult result, out SecurityMessageProperty remoteSecurity, out ChannelBinding channelBinding)
 {
     Stream stream = StreamSecurityUpgradeInitiatorAsyncResult.End(result, out remoteSecurity);
     channelBinding = ((SslStreamSecurityUpgradeInitiator.InitiateUpgradeAsyncResult) result).channelBindingToken;
     return stream;
 }
 private IConnection SendPreamble(IConnection connection, ref TimeoutHelper timeoutHelper, ClientFramingDecoder decoder, out SecurityMessageProperty remoteSecurity)
 {
     connection.Write(this.Preamble, 0, this.Preamble.Length, true, timeoutHelper.RemainingTime());
     if (this.upgrade != null)
     {
         IStreamUpgradeChannelBindingProvider property = this.upgrade.GetProperty<IStreamUpgradeChannelBindingProvider>();
         StreamUpgradeInitiator upgradeInitiator = this.upgrade.CreateUpgradeInitiator(base.RemoteAddress, base.Via);
         if (!ConnectionUpgradeHelper.InitiateUpgrade(upgradeInitiator, ref connection, decoder, this, ref timeoutHelper))
         {
             ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, base.Via, this.messageEncoder.ContentType, ref timeoutHelper);
         }
         if ((property != null) && property.IsChannelBindingSupportEnabled)
         {
             this.channelBindingToken = property.GetChannelBinding(upgradeInitiator, ChannelBindingKind.Endpoint);
         }
         remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(upgradeInitiator);
         connection.Write(ClientSingletonEncoder.PreambleEndBytes, 0, ClientSingletonEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
     }
     else
     {
         remoteSecurity = null;
     }
     byte[] buffer = new byte[1];
     int count = connection.Read(buffer, 0, buffer.Length, timeoutHelper.RemainingTime());
     if (!ConnectionUpgradeHelper.ValidatePreambleResponse(buffer, count, decoder, base.Via))
     {
         ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, base.Via, this.messageEncoder.ContentType, ref timeoutHelper);
     }
     return connection;
 }
Beispiel #44
0
        /// <summary>
        /// Converts a given set of WCF IAuthorizationPolicy to WIF ClaimIdentities.
        /// </summary>
        /// <param name="authorizationPolicies">Set of AuthorizationPolicies to convert to IDFx.</param>
        /// <param name="securityTokenHandlerCollection">The SecurityTokenHandlerCollection to use.</param>
        /// <returns>ClaimsIdentityCollection</returns>
        static ReadOnlyCollection <ClaimsIdentity> ConvertToIDFxIdentities(IList <IAuthorizationPolicy> authorizationPolicies,
                                                                           SecurityTokenHandlerCollection securityTokenHandlerCollection)
        {
            if (authorizationPolicies == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
            }

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

            List <ClaimsIdentity> identities = new List <ClaimsIdentity>();

            SecurityTokenSpecification kerberosTokenSpecification = null;
            SysAuthorizationContext    kerberosAuthContext        = null;

            if ((OperationContext.Current != null) &&
                (OperationContext.Current.IncomingMessageProperties != null) &&
                (OperationContext.Current.IncomingMessageProperties.Security != null))
            {
                SecurityMessageProperty securityMessageProperty = OperationContext.Current.IncomingMessageProperties.Security;
                foreach (SecurityTokenSpecification tokenSpecification in new SecurityTokenSpecificationEnumerable(securityMessageProperty))
                {
                    if (tokenSpecification.SecurityToken is KerberosReceiverSecurityToken)
                    {
                        kerberosTokenSpecification = tokenSpecification;
                        kerberosAuthContext        = SysAuthorizationContext.CreateDefaultAuthorizationContext(kerberosTokenSpecification.SecurityTokenPolicies);
                        break;
                    }
                }
            }

            bool hasKerberosTokenPolicyMatched = false;

            foreach (IAuthorizationPolicy policy in authorizationPolicies)
            {
                bool authPolicyHandled = false;

                if ((kerberosTokenSpecification != null) && !hasKerberosTokenPolicyMatched)
                {
                    if (kerberosTokenSpecification.SecurityTokenPolicies.Contains(policy))
                    {
                        hasKerberosTokenPolicyMatched = true;
                    }
                    else
                    {
                        SysAuthorizationContext authContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(new List <IAuthorizationPolicy>()
                        {
                            policy
                        });
                        // Kerberos creates only one ClaimSet. So any more ClaimSet would mean that this is not a Policy created from Kerberos.
                        if (authContext.ClaimSets.Count == 1)
                        {
                            bool allClaimsMatched = true;
                            foreach (System.IdentityModel.Claims.Claim c in authContext.ClaimSets[0])
                            {
                                if (!kerberosAuthContext.ClaimSets[0].ContainsClaim(c))
                                {
                                    allClaimsMatched = false;
                                    break;
                                }
                            }
                            hasKerberosTokenPolicyMatched = allClaimsMatched;
                        }
                    }

                    if (hasKerberosTokenPolicyMatched)
                    {
                        SecurityTokenHandler tokenHandler = securityTokenHandlerCollection[kerberosTokenSpecification.SecurityToken];
                        if ((tokenHandler != null) && tokenHandler.CanValidateToken)
                        {
                            identities.AddRange(tokenHandler.ValidateToken(kerberosTokenSpecification.SecurityToken));
                            authPolicyHandled = true;
                        }
                    }
                }

                if (!authPolicyHandled)
                {
                    SysAuthorizationContext defaultAuthContext = SysAuthorizationContext.CreateDefaultAuthorizationContext(new List <IAuthorizationPolicy>()
                    {
                        policy
                    });
                    //
                    // Merge all ClaimSets to IClaimsIdentity.
                    //

                    identities.Add(ConvertToIDFxIdentity(defaultAuthContext.ClaimSets, securityTokenHandlerCollection.Configuration));
                }
            }

            return(identities.AsReadOnly());
        }
 protected abstract Stream OnAcceptUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity);
 protected abstract Stream OnEndAcceptUpgrade(IAsyncResult result,
     out SecurityMessageProperty remoteSecurity);
Beispiel #47
0
		public RecipientMessageSecurityGenerator (
			Message msg,
			SecurityMessageProperty requestSecProp,
			RecipientMessageSecurityBindingSupport security)
			: base (msg, security)
		{
			this.security = security;
			SecurityMessageProperty secprop =
				(SecurityMessageProperty) requestSecProp.CreateCopy ();
			msg.Properties.Security = secprop;
		}
Beispiel #48
0
		public Message SecureMessage ()
		{
			secprop = Message.Properties.Security ?? new SecurityMessageProperty ();

			SecurityToken encToken =
				secprop.InitiatorToken != null ? secprop.InitiatorToken.SecurityToken : security.EncryptionToken;
			// FIXME: it might be still incorrect.
			SecurityToken signToken =
				Parameters == CounterParameters ? null :
				security.SigningToken;
			MessageProtectionOrder protectionOrder =
				security.MessageProtectionOrder;
			SecurityBindingElement element =
				security.Element;
			SecurityAlgorithmSuite suite = element.DefaultAlgorithmSuite;

			string messageId = "uuid-" + Guid.NewGuid ();
			int identForMessageId = 1;
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
            var action = msg.Headers.Action;

			if (msg.Version.Addressing != AddressingVersion.None) {
                AddAddressingToHeader (msg.Headers);
			}
				
			// wss:Security
			WSSecurityMessageHeader header =
                new WSSecurityMessageHeader (security.TokenSerializer);
			msg.Headers.Add (header);
			// 1. [Timestamp]
			if (element.IncludeTimestamp) {
                AddTimestampToHeader (header, messageId + "-" + identForMessageId++);
			}

			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", msg.Version.Envelope.Namespace);
			nsmgr.AddNamespace ("o", Constants.WssNamespace);
			nsmgr.AddNamespace ("u", Constants.WsuNamespace);
			nsmgr.AddNamespace ("o11", Constants.Wss11Namespace);

			/*WrappedKey*/SecurityToken primaryToken = null;
			SecurityToken actualToken = null;
			SecurityKeyIdentifierClause actualClause = null;

			

			SymmetricAlgorithm masterKey = new RijndaelManaged ();
			masterKey.KeySize = suite.DefaultSymmetricKeyLength;
			masterKey.Mode = CipherMode.CBC;
			masterKey.Padding = PaddingMode.ISO10126;
			SymmetricAlgorithm actualKey = masterKey;

			// 2. [Encryption Token]

			// SecurityTokenInclusionMode
			// - Initiator or Recipient
			// - done or notyet. FIXME: not implemented yet
			// It also affects on key reference output

			bool includeEncToken = // /* FIXME: remove this hack */Parameters is SslSecurityTokenParameters ? false :
						ShouldIncludeToken (
				Security.RecipientParameters.InclusionMode, false);
			bool includeSigToken = // /* FIXME: remove this hack */ Parameters is SslSecurityTokenParameters ? false :
						ShouldIncludeToken (
				Security.InitiatorParameters.InclusionMode, false);

			SecurityKeyIdentifierClause encClause = ShouldOutputEncryptedKey ?
				CounterParameters.CallCreateKeyIdentifierClause (encToken, !ShouldOutputEncryptedKey ? SecurityTokenReferenceStyle.Internal : includeEncToken ? Parameters.ReferenceStyle : SecurityTokenReferenceStyle.External) : null;

			MessagePartSpecification encSpec = EncryptionPart;

			// encryption key (possibly also used for signing)
			// FIXME: get correct SymmetricAlgorithm according to the algorithm suite
			if (secprop.EncryptionKey != null)
				actualKey.Key = secprop.EncryptionKey;

// FIXME: remove thid hack
if (!ShouldOutputEncryptedKey)
primaryToken = secprop.ProtectionToken.SecurityToken as WrappedKeySecurityToken;
else
			primaryToken =
				// FIXME: remove this hack?
				encToken is SecurityContextSecurityToken ? encToken :
				new WrappedKeySecurityToken (messageId + "-" + identForMessageId++,
				actualKey.Key,
				// security.DefaultKeyWrapAlgorithm,
				Parameters.InternalHasAsymmetricKey ?
					suite.DefaultAsymmetricKeyWrapAlgorithm :
					suite.DefaultSymmetricKeyWrapAlgorithm,
				encToken,
				encClause != null ? new SecurityKeyIdentifier (encClause) : null);

			// If it reuses request's encryption key, do not output.
			if (ShouldOutputEncryptedKey)
				header.AddContent (primaryToken);

			actualToken = primaryToken;

			// FIXME: I doubt it is correct...
			WrappedKeySecurityToken requestEncKey = ShouldOutputEncryptedKey ? null : primaryToken as WrappedKeySecurityToken;
			actualClause = requestEncKey == null ? (SecurityKeyIdentifierClause)
				new LocalIdKeyIdentifierClause (actualToken.Id, typeof (WrappedKeySecurityToken)) :
				new InternalEncryptedKeyIdentifierClause (SHA1.Create ().ComputeHash (requestEncKey.GetWrappedKey ()));

			// generate derived key if needed
			if (CounterParameters.RequireDerivedKeys) {
                var dkeyToken = CreateDerivedKey (GenerateId (doc), actualClause, actualKey);
                actualToken = dkeyToken;
                actualKey.Key = ((SymmetricSecurityKey)dkeyToken.SecurityKeys [0]).GetSymmetricKey ();
                actualClause = new LocalIdKeyIdentifierClause (dkeyToken.Id);
                header.AddContent (dkeyToken);
			}

			ReferenceList refList = new ReferenceList ();
			// When encrypted with DerivedKeyToken, put references
			// immediately after the derived token (not inside the
			// primary token).
			// Similarly, when we do not output EncryptedKey,
			// output ReferenceList in the same way.
			if (CounterParameters.RequireDerivedKeys ||
			    !ShouldOutputEncryptedKey)
				header.AddContent (refList);
			else
				((WrappedKeySecurityToken) primaryToken).ReferenceList = refList;

			// [Signature Confirmation]
			if (security.RequireSignatureConfirmation && secprop.ConfirmedSignatures.Count > 0)
				foreach (string value in secprop.ConfirmedSignatures)
					header.AddContent (new Wss11SignatureConfirmation (GenerateId (doc), value));

			SupportingTokenInfoCollection tokenInfos =
				Direction == MessageDirection.Input ?
				security.CollectSupportingTokens (GetAction ()) :
				new SupportingTokenInfoCollection (); // empty

			foreach (SupportingTokenInfo tinfo in tokenInfos)
				header.AddContent (tinfo.Token);

			// populate DOM to sign.
			XPathNavigator nav = doc.CreateNavigator ();
			using (XmlWriter w = nav.AppendChild ()) {
				msg.WriteMessage (w);
			}

			XmlElement body = doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement;
			string bodyId = null;
			Collection<WSSignedXml> endorsedSignatures =
				new Collection<WSSignedXml> ();
			bool signatureProtection = (protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature);

			// Below are o:Security contents that are not signed...
			if (includeSigToken && signToken != null)
				header.AddContent (signToken);

			switch (protectionOrder) {
			case MessageProtectionOrder.EncryptBeforeSign:
				// FIXME: implement
				throw new NotImplementedException ();
			case MessageProtectionOrder.SignBeforeEncrypt:
			case MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature:

               
                var sig = CreateSignature (doc, body, nsmgr, tokenInfos, 
                    actualClause, actualKey, signToken, includeSigToken, 
                    signatureProtection, header, endorsedSignatures, 
                    ref bodyId);

				
				// encrypt

				WSEncryptedXml exml = new WSEncryptedXml (doc);

				EncryptedData edata = Encrypt (body, actualKey, actualToken.Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementContentUrl);
				EncryptedXml.ReplaceElement (body, edata, false);

				// encrypt signature
				if (signatureProtection) {
					XmlElement sigxml = sig.GetXml ();
					edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementUrl);
					header.AddContent (edata);

					foreach (WSSignedXml ssxml in endorsedSignatures) {
						sigxml = ssxml.GetXml ();
						edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementUrl);
						header.AddContent (edata);
					}

					if (security.RequireSignatureConfirmation) {
						Collection<Wss11SignatureConfirmation> confs = header.FindAll<Wss11SignatureConfirmation> ();
						int count = 0;
						foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr)) {
							edata = Encrypt (elem, actualKey, confs [count].Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementUrl);
							EncryptedXml.ReplaceElement (elem, edata, false);
							header.Contents.Insert (header.Contents.IndexOf (confs [count]), edata);
							header.Contents.Remove (confs [count++]);
						}
					}
				}


				// encrypt Encrypted supporting tokens
				foreach (SupportingTokenInfo tinfo in tokenInfos) {
					if (tinfo.Mode == SecurityTokenAttachmentMode.SignedEncrypted) {
						XmlElement el = exml.GetIdElement (doc, tinfo.Token.Id);
						tinfo.Encrypted = Encrypt (el, actualKey, actualToken.Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementUrl);
						EncryptedXml.ReplaceElement (el, tinfo.Encrypted, false);
						header.Contents.Insert (header.Contents.IndexOf (tinfo.Token), tinfo.Encrypted);
						header.Contents.Remove (tinfo.Token);
					}
				}
				break;
			}


            

			Message ret = new WSSecurityMessage (Message.CreateMessage (msg.Version, action, new XmlNodeReader (doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement)), bodyId);
			ret.Properties.Security = (SecurityMessageProperty) secprop.CreateCopy ();
			ret.Properties.Security.EncryptionKey = masterKey.Key;

			// FIXME: can we support TransportToken here?
			if (element is AsymmetricSecurityBindingElement) {
				ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (encToken, null); // FIXME: second argument
				ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (signToken, null); // FIXME: second argument
			}
			else
				ret.Properties.Security.ProtectionToken = new SecurityTokenSpecification (primaryToken, null);

			ret.Headers.Clear ();
			ret.Headers.CopyHeadersFrom (msg);
            
			// Header contents are:
			//	- Timestamp
			//	- SignatureConfirmation if required
			//	- EncryptionToken if included
			//	- derived key token for EncryptionToken
			//	- ReferenceList for encrypted items
			//	- signed supporting tokens
			//	- signed endorsing supporting tokens
			//	(i.e. Signed/SignedEncrypted/SignedEndorsing)
			//	- Signature Token if different from enc token.
			//	- derived key token for sig token if different
			//	- Signature for:
			//		- Timestamp
			//		- supporting tokens (regardless of
			//		  its inclusion)
			//		- message parts in SignedParts
			//		- SignatureToken if TokenProtection
			//		  (regardless of its inclusion)
			//	- Signatures for the main signature (above),
			//	  for every endorsing token and signed
			//	  endorsing token.
			//	

//MessageBuffer zzz = ret.CreateBufferedCopy (100000);
//ret = zzz.CreateMessage ();
//Console.WriteLine (zzz.CreateMessage ());
			return ret;
		}
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                if (requestSecurityToken.RequestType != null && requestSecurityToken.RequestType != this.StandardsManager.TrustDriver.RequestTypeIssue)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.InvalidRstRequestType, requestSecurityToken.RequestType)), request);
                }
                if (requestSecurityToken.TokenType != null && requestSecurityToken.TokenType != this.SecurityContextTokenUri)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.CannotIssueRstTokenType, requestSecurityToken.TokenType)), request);
                }

                EndpointAddress        appliesTo;
                DataContractSerializer appliesToSerializer;
                string appliesToName;
                string appliesToNamespace;
                requestSecurityToken.GetAppliesToQName(out appliesToName, out appliesToNamespace);
                if (appliesToName == AddressingStrings.EndpointReference && appliesToNamespace == request.Version.Addressing.Namespace)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddress10>(appliesToSerializer).ToEndpointAddress();
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(appliesToSerializer).ToEndpointAddress();
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                else
                {
                    appliesTo           = null;
                    appliesToSerializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    SecurityUtils.MatchRstWithEndpointFilter(request, this.EndpointFilterTable, this.ListenUri);
                }
                int           issuedKeySize;
                byte[]        issuerEntropy;
                byte[]        proofKey;
                SecurityToken proofToken;
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, this.SecurityAlgorithmSuite,
                                                     out issuedKeySize, out issuerEntropy, out proofKey, out proofToken);
                UniqueId contextId      = SecurityUtils.GenerateUniqueId();
                string   id             = SecurityUtils.GenerateId();
                DateTime effectiveTime  = DateTime.UtcNow;
                DateTime expirationTime = TimeoutHelper.Add(effectiveTime, this.ServiceTokenLifetime);
                // ensure that a SecurityContext is present in the message
                SecurityMessageProperty securityProperty = request.Properties.Security;
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;
                if (securityProperty != null)
                {
                    authorizationPolicies = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(securityProperty, expirationTime);
                }
                else
                {
                    authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken serviceToken = this.IssueSecurityContextToken(contextId, id, proofKey, effectiveTime, expirationTime, authorizationPolicies,
                                                                                           this.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    serviceToken.BootstrapMessageProperty = (securityProperty == null) ? null : (SecurityMessageProperty)securityProperty.CreateCopy();
                    SecurityUtils.ErasePasswordInUsernameTokenIfPresent(serviceToken.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(this.StandardsManager);
                rstr.Context = requestSecurityToken.Context;
                rstr.KeySize = issuedKeySize;
                rstr.RequestedUnattachedReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                rstr.RequestedAttachedReference   = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);
                rstr.TokenType = this.SecurityContextTokenUri;
                rstr.RequestedSecurityToken = serviceToken;
                if (issuerEntropy != null)
                {
                    rstr.SetIssuerEntropy(issuerEntropy);
                    rstr.ComputeKey = true;
                }
                if (proofToken != null)
                {
                    rstr.RequestedProofToken = proofToken;
                }
                if (appliesTo != null)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                rstr.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(serviceToken);

                if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(rstr);
                }
                else if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversation13)
                {
                    List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(1);
                    rstrList.Add(rstr);
                    RequestSecurityTokenResponseCollection rstrCollection = new RequestSecurityTokenResponseCollection(rstrList, this.StandardsManager);
                    return(rstrCollection);
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
        }
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            BodyWriter writer;

            if (request == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                EndpointAddress        address;
                DataContractSerializer serializer;
                string        str;
                string        str2;
                int           num;
                byte[]        buffer;
                byte[]        buffer2;
                SecurityToken token;
                ReadOnlyCollection <IAuthorizationPolicy> instance;
                if ((requestSecurityToken.RequestType != null) && (requestSecurityToken.RequestType != base.StandardsManager.TrustDriver.RequestTypeIssue))
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidRstRequestType", new object[] { requestSecurityToken.RequestType })), request);
                }
                if ((requestSecurityToken.TokenType != null) && (requestSecurityToken.TokenType != base.SecurityContextTokenUri))
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("CannotIssueRstTokenType", new object[] { requestSecurityToken.TokenType })), request);
                }
                requestSecurityToken.GetAppliesToQName(out str, out str2);
                if ((str == "EndpointReference") && (str2 == request.Version.Addressing.Namespace))
                {
                    if (request.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (request.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { request.Version.Addressing })));
                        }
                        serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), 0x10000);
                        address    = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(serializer).ToEndpointAddress();
                    }
                    else
                    {
                        serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), 0x10000);
                        address    = requestSecurityToken.GetAppliesTo <EndpointAddress10>(serializer).ToEndpointAddress();
                    }
                }
                else
                {
                    address    = null;
                    serializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    System.ServiceModel.Security.SecurityUtils.MatchRstWithEndpointFilter(request, base.EndpointFilterTable, base.ListenUri);
                }
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, base.SecurityAlgorithmSuite, out num, out buffer, out buffer2, out token);
                UniqueId contextId               = System.ServiceModel.Security.SecurityUtils.GenerateUniqueId();
                string   id                      = System.ServiceModel.Security.SecurityUtils.GenerateId();
                DateTime utcNow                  = DateTime.UtcNow;
                DateTime expirationTime          = TimeoutHelper.Add(utcNow, base.ServiceTokenLifetime);
                SecurityMessageProperty security = request.Properties.Security;
                if (security != null)
                {
                    instance = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(security, expirationTime);
                }
                else
                {
                    instance = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken token2 = base.IssueSecurityContextToken(contextId, id, buffer2, utcNow, expirationTime, instance, base.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    token2.BootstrapMessageProperty = (security == null) ? null : ((SecurityMessageProperty)security.CreateCopy());
                    System.ServiceModel.Security.SecurityUtils.ErasePasswordInUsernameTokenIfPresent(token2.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse response = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    Context = requestSecurityToken.Context,
                    KeySize = num,
                    RequestedUnattachedReference = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token2, SecurityTokenReferenceStyle.External),
                    RequestedAttachedReference   = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token2, SecurityTokenReferenceStyle.Internal),
                    TokenType = base.SecurityContextTokenUri,
                    RequestedSecurityToken = token2
                };
                if (buffer != null)
                {
                    response.SetIssuerEntropy(buffer);
                    response.ComputeKey = true;
                }
                if (token != null)
                {
                    response.RequestedProofToken = token;
                }
                if (address != null)
                {
                    if (request.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (request.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { request.Version.Addressing })));
                        }
                        response.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(address), serializer);
                    }
                    else
                    {
                        response.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(address), serializer);
                    }
                }
                response.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(token2);
                if (base.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(response);
                }
                if (base.StandardsManager.MessageSecurityVersion.SecureConversationVersion != SecureConversationVersion.WSSecureConversation13)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
                RequestSecurityTokenResponseCollection responses = new RequestSecurityTokenResponseCollection(new List <RequestSecurityTokenResponse>(1)
                {
                    response
                }, base.StandardsManager);
                writer = responses;
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
            return(writer);
        }
 public static IConnection End(IAsyncResult result, out SecurityMessageProperty remoteSecurity)
 {
     SendPreambleAsyncResult thisPtr = AsyncResult.End<SendPreambleAsyncResult>(result);
     remoteSecurity = thisPtr.remoteSecurity;
     return thisPtr.connection;
 }
 public static IConnection End(IAsyncResult result, out SecurityMessageProperty remoteSecurity)
 {
     StreamedFramingRequestChannel.StreamedConnectionPoolHelper.SendPreambleAsyncResult result2 = AsyncResult.End<StreamedFramingRequestChannel.StreamedConnectionPoolHelper.SendPreambleAsyncResult>(result);
     remoteSecurity = result2.remoteSecurity;
     return result2.connection;
 }
 protected override Stream OnEndInitiateUpgrade(IAsyncResult result, out SecurityMessageProperty remoteSecurity)
 {
     return InitiateUpgradeAsyncResult.End(result, out remoteSecurity, out this.channelBindingToken);
 }
 private bool HandleUpgrade(IAsyncResult result)
 {
     this.connection = ConnectionUpgradeHelper.EndInitiateUpgrade(result);
     if ((this.channelBindingProvider != null) && this.channelBindingProvider.IsChannelBindingSupportEnabled)
     {
         this.channel.channelBindingToken = this.channelBindingProvider.GetChannelBinding(this.upgradeInitiator, ChannelBindingKind.Endpoint);
     }
     this.remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(this.upgradeInitiator);
     this.upgradeInitiator = null;
     if (onWritePreambleEnd == null)
     {
         onWritePreambleEnd = Fx.ThunkCallback(new AsyncCallback(StreamedFramingRequestChannel.StreamedConnectionPoolHelper.SendPreambleAsyncResult.OnWritePreambleEnd));
     }
     IAsyncResult result2 = this.connection.BeginWrite(ClientSingletonEncoder.PreambleEndBytes, 0, ClientSingletonEncoder.PreambleEndBytes.Length, true, this.timeoutHelper.RemainingTime(), onWritePreambleEnd, this);
     if (!result2.CompletedSynchronously)
     {
         return false;
     }
     this.connection.EndWrite(result2);
     return this.ReadPreambleAck();
 }
 protected override Stream OnInitiateUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity)
 {
     X509CertificateCollection clientCertificates = null;
     LocalCertificateSelectionCallback userCertificateSelectionCallback = null;
     if (this.clientToken != null)
     {
         clientCertificates = new X509CertificateCollection();
         clientCertificates.Add(this.clientToken.Certificate);
         userCertificateSelectionCallback = ClientCertificateSelectionCallback;
     }
     SslStream stream2 = new SslStream(stream, false, new RemoteCertificateValidationCallback(this.ValidateRemoteCertificate), userCertificateSelectionCallback);
     try
     {
         stream2.AuthenticateAsClient(string.Empty, clientCertificates, SslProtocols.Default, false);
     }
     catch (SecurityTokenValidationException exception)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception));
     }
     catch (AuthenticationException exception2)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception2.Message, exception2));
     }
     catch (IOException exception3)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NegotiationFailedIO", new object[] { exception3.Message }), exception3));
     }
     if (System.ServiceModel.Security.SecurityUtils.ShouldValidateSslCipherStrength())
     {
         System.ServiceModel.Security.SecurityUtils.ValidateSslCipherStrength(stream2.CipherStrength);
     }
     remoteSecurity = this.serverSecurity;
     if (this.IsChannelBindingSupportEnabled)
     {
         this.channelBindingToken = ChannelBindingUtility.GetToken(stream2);
     }
     return stream2;
 }
 public static SecurityMessageProperty GetOrCreate(Message message)
 {
     if (message == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
     }
     SecurityMessageProperty security = null;
     if (message.Properties != null)
     {
         security = message.Properties.Security;
     }
     if (security == null)
     {
         security = new SecurityMessageProperty();
         message.Properties.Security = security;
     }
     return security;
 }
 private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
 {
     X509Certificate2 certificate2 = new X509Certificate2(certificate);
     SecurityToken token = new X509SecurityToken(certificate2, false);
     ReadOnlyCollection<IAuthorizationPolicy> tokenPolicies = this.serverCertificateAuthenticator.ValidateToken(token);
     this.serverSecurity = new SecurityMessageProperty();
     this.serverSecurity.TransportToken = new SecurityTokenSpecification(token, tokenPolicies);
     this.serverSecurity.ServiceSecurityContext = new ServiceSecurityContext(tokenPolicies);
     AuthorizationContext authorizationContext = this.serverSecurity.ServiceSecurityContext.AuthorizationContext;
     this.parent.IdentityVerifier.EnsureOutgoingIdentity(base.RemoteAddress, base.Via, authorizationContext);
     return true;
 }
                bool HandleUpgrade(IAsyncResult result)
                {
                    connection = ConnectionUpgradeHelper.EndInitiateUpgrade(result);

                    if (this.channelBindingProvider != null && this.channelBindingProvider.IsChannelBindingSupportEnabled)
                    {
                        this.channel.channelBindingToken = this.channelBindingProvider.GetChannelBinding(this.upgradeInitiator, ChannelBindingKind.Endpoint);
                    }

                    this.remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(this.upgradeInitiator);
                    this.upgradeInitiator = null; // we're done with the initiator
                    if (onWritePreambleEnd == null)
                    {
                        onWritePreambleEnd = Fx.ThunkCallback(new WaitCallback(OnWritePreambleEnd));
                    }

                    AsyncCompletionResult writePreambleResult = connection.BeginWrite(
                        ClientSingletonEncoder.PreambleEndBytes, 0, ClientSingletonEncoder.PreambleEndBytes.Length, true,
                        timeoutHelper.RemainingTime(), onWritePreambleEnd, this);

                    if (writePreambleResult == AsyncCompletionResult.Queued)
                    {
                        return false;
                    }

                    connection.EndWrite();
                    return ReadPreambleAck();
                }
Beispiel #59
0
		Message ProcessReply (Message message, SecurityMessageProperty secprop)
		{
			// FIXME: provide correct parameters
			return message.IsFault ? message : new InitiatorSecureMessageDecryptor (message, secprop, security).DecryptMessage ();
		}