/**
  * The execution of this behavior comes rather late.
  * Anyone that inspects the service description in the meantime,
  * such as for metadata generation, won't see the protection level that we want to use.
  *
  * One way of doing it is at when create HostFactory
  *
  * ServiceEndpoint endpoint = host.Description.Endpoints.Find(typeof(IService));
  * OperationDescription operation = endpoint.Contract.Operations.Find("Action");
  * MessageDescription message = operation.Messages.Find("http://tempuri.org/IService/ActionResponse");
  * MessageHeaderDescription header = message.Headers[new XmlQualifiedName("aheader", "http://tempuri.org/")];
  * header.ProtectionLevel = ProtectionLevel.Sign;
  *
  * **/
 public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
 {
     ChannelProtectionRequirements requirements = bindingParameters.Find<ChannelProtectionRequirements>();
     XmlQualifiedName qName = new XmlQualifiedName(header, ns);
     MessagePartSpecification part = new MessagePartSpecification(qName);
     requirements.OutgoingSignatureParts.AddParts(part, action);
 }
        public void Union(MessagePartSpecification specification)
        {
            if (this.isReadOnly)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("ObjectIsReadOnly")));
            }
            if (specification == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("specification");
            }
            this.isBodyIncluded |= specification.IsBodyIncluded;
            List <XmlQualifiedName> headerTypes = specification.headerTypes;

            if ((headerTypes != null) && (headerTypes.Count > 0))
            {
                if (this.headerTypes == null)
                {
                    this.headerTypes = new List <XmlQualifiedName>(headerTypes.Count);
                }
                for (int i = 0; i < headerTypes.Count; i++)
                {
                    XmlQualifiedName item = headerTypes[i];
                    this.headerTypes.Add(item);
                }
            }
        }
Beispiel #3
0
 private static void AddFaultProtectionRequirements(FaultDescriptionCollection faults, ChannelProtectionRequirements requirements, ProtectionLevel defaultProtectionLevel, bool addToIncoming)
 {
     if (faults == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faults"));
     }
     if (requirements == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("requirements"));
     }
     foreach (FaultDescription description in faults)
     {
         MessagePartSpecification parts          = new MessagePartSpecification();
         MessagePartSpecification specification2 = new MessagePartSpecification();
         ProtectionLevel          level          = description.HasProtectionLevel ? description.ProtectionLevel : defaultProtectionLevel;
         if (level != ProtectionLevel.None)
         {
             parts.IsBodyIncluded = true;
             if (level == ProtectionLevel.EncryptAndSign)
             {
                 specification2.IsBodyIncluded = true;
             }
         }
         if (addToIncoming)
         {
             requirements.IncomingSignatureParts.AddParts(parts, description.Action);
             requirements.IncomingEncryptionParts.AddParts(specification2, description.Action);
         }
         else
         {
             requirements.OutgoingSignatureParts.AddParts(parts, description.Action);
             requirements.OutgoingEncryptionParts.AddParts(specification2, description.Action);
         }
     }
 }
Beispiel #4
0
        public void Union(MessagePartSpecification specification)
        {
            if (IsReadOnly)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly));
            }

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

            _isBodyIncluded |= specification.IsBodyIncluded;

            List <XmlQualifiedName> headerTypes = specification._headerTypes;

            if (headerTypes != null && headerTypes.Count > 0)
            {
                if (_headerTypes == null)
                {
                    _headerTypes = new List <XmlQualifiedName>(headerTypes.Count);
                }

                for (int i = 0; i < headerTypes.Count; i++)
                {
                    XmlQualifiedName qname = headerTypes[i];
                    _headerTypes.Add(qname);
                }
            }
        }
        protected override void StartPrimarySignatureCore(SecurityToken token, SecurityKeyIdentifier keyIdentifier, MessagePartSpecification signatureParts, bool generateTargettableSignature)
        {
            string str3;
            XmlDictionaryString    str4;
            SecurityAlgorithmSuite algorithmSuite   = base.AlgorithmSuite;
            string defaultCanonicalizationAlgorithm = algorithmSuite.DefaultCanonicalizationAlgorithm;
            XmlDictionaryString defaultCanonicalizationAlgorithmDictionaryString = algorithmSuite.DefaultCanonicalizationAlgorithmDictionaryString;

            if (defaultCanonicalizationAlgorithm != "http://www.w3.org/2001/10/xml-exc-c14n#")
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("UnsupportedCanonicalizationAlgorithm", new object[] { algorithmSuite.DefaultCanonicalizationAlgorithm })));
            }
            algorithmSuite.GetSignatureAlgorithmAndKey(token, out str3, out this.signatureKey, out str4);
            string defaultDigestAlgorithm = algorithmSuite.DefaultDigestAlgorithm;
            XmlDictionaryString defaultDigestAlgorithmDictionaryString = algorithmSuite.DefaultDigestAlgorithmDictionaryString;

            this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, defaultCanonicalizationAlgorithm, defaultCanonicalizationAlgorithmDictionaryString, defaultDigestAlgorithm, defaultDigestAlgorithmDictionaryString, str3, str4);
            this.signedXml  = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, base.StandardsManager.SecurityTokenSerializer);
            if (keyIdentifier != null)
            {
                this.signedXml.Signature.KeyIdentifier = keyIdentifier;
            }
            if (generateTargettableSignature)
            {
                this.signedXml.Id = base.GenerateId();
            }
            this.effectiveSignatureParts = signatureParts;
            this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(defaultDigestAlgorithm);
        }
        protected override void StartPrimarySignatureCore(SecurityToken token,
                                                          SecurityKeyIdentifier keyIdentifier,
                                                          MessagePartSpecification signatureParts,
                                                          bool generateTargettableSignature)
        {
            SecurityAlgorithmSuite suite     = this.AlgorithmSuite;
            string canonicalizationAlgorithm = suite.DefaultCanonicalizationAlgorithm;
            XmlDictionaryString canonicalizationAlgorithmDictionaryString = suite.DefaultCanonicalizationAlgorithmDictionaryString;

            if (canonicalizationAlgorithm != SecurityAlgorithms.ExclusiveC14n)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new MessageSecurityException(SR.GetString(SR.UnsupportedCanonicalizationAlgorithm, suite.DefaultCanonicalizationAlgorithm)));
            }
            string signatureAlgorithm;
            XmlDictionaryString signatureAlgorithmDictionaryString;

            suite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out this.signatureKey, out signatureAlgorithmDictionaryString);
            string digestAlgorithm = suite.DefaultDigestAlgorithm;
            XmlDictionaryString digestAlgorithmDictionaryString = suite.DefaultDigestAlgorithmDictionaryString;

            this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, canonicalizationAlgorithm, canonicalizationAlgorithmDictionaryString, digestAlgorithm, digestAlgorithmDictionaryString, signatureAlgorithm, signatureAlgorithmDictionaryString);
            this.signedXml  = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
            if (keyIdentifier != null)
            {
                this.signedXml.Signature.KeyIdentifier = keyIdentifier;
            }
            if (generateTargettableSignature)
            {
                this.signedXml.Id = GenerateId();
            }
            this.effectiveSignatureParts = signatureParts;
            this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(digestAlgorithm);
        }
        public bool TryGetParts(string action, bool excludeChannelScope, out MessagePartSpecification parts)
        {
            if (action == null)
            {
                action = MessageHeaders.WildcardAction;
            }
            parts = null;

            if (this.isReadOnly)
            {
                if (this.readOnlyNormalizedActionParts.ContainsKey(action))
                {
                    if (excludeChannelScope)
                    {
                        parts = this.actionParts[action];
                    }
                    else
                    {
                        parts = this.readOnlyNormalizedActionParts[action];
                    }
                }
            }
            else if (this.actionParts.ContainsKey(action))
            {
                MessagePartSpecification p = new MessagePartSpecification();
                p.Union(this.actionParts[action]);
                if (!excludeChannelScope)
                {
                    p.Union(this.channelParts);
                }
                parts = p;
            }

            return(parts != null);
        }
        public void AddParts(MessagePartSpecification parts,
                             string action)
        {
            if (parts == null)
            {
                throw new ArgumentNullException("parts");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }
            if (IsReadOnly)
            {
                throw new InvalidOperationException("This ScopedMessagePartSpecification is read-only.");
            }

            MessagePartSpecification existing;

            if (table.TryGetValue(action, out existing))
            {
                existing.Union(parts);
            }
            else
            {
                table.Add(action, parts);
            }
        }
Beispiel #9
0
        static MessagePartSpecification ExtractMessageParts(string action,
                                                            ScopedMessagePartSpecification scopedParts, bool isForSignature)
        {
            MessagePartSpecification parts = null;

            if (scopedParts.TryGetParts(action, out parts))
            {
                return(parts);
            }
            else if (scopedParts.TryGetParts(MessageHeaders.WildcardAction, out parts))
            {
                return(parts);
            }

            // send back a fault indication that the action is unknown
            SecurityVersion wss        = MessageSecurityVersion.Default.SecurityVersion;
            FaultCode       subCode    = new FaultCode(wss.InvalidSecurityFaultCode.Value, wss.HeaderNamespace.Value);
            FaultCode       senderCode = FaultCode.CreateSenderFaultCode(subCode);
            FaultReason     reason     = new FaultReason(SR.GetString(SR.InvalidOrUnrecognizedAction, action), System.Globalization.CultureInfo.CurrentCulture);
            MessageFault    fault      = MessageFault.CreateFault(senderCode, reason);

            if (isForSignature)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoSignaturePartsSpecified, action), null, fault));
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoEncryptionPartsSpecified, action), null, fault));
            }
        }
Beispiel #10
0
        void VerifySoapAttributeMatchForHeader(MessageHeaderInfo info, MessagePartSpecification signatureParts, XmlDictionaryReader reader)
        {
            if (!signatureParts.IsHeaderIncluded(info.Name, info.Namespace))
            {
                return;
            }

            EnvelopeVersion currentVersion = this.Version.Envelope;
            EnvelopeVersion otherVersion   = currentVersion == EnvelopeVersion.Soap11 ? EnvelopeVersion.Soap12 : EnvelopeVersion.Soap11;

            bool presentInCurrentVersion;
            bool presentInOtherVersion;

            presentInCurrentVersion = null != reader.GetAttribute(XD.MessageDictionary.MustUnderstand, currentVersion.DictionaryNamespace);
            presentInOtherVersion   = null != reader.GetAttribute(XD.MessageDictionary.MustUnderstand, otherVersion.DictionaryNamespace);
            if (presentInOtherVersion && !presentInCurrentVersion)
            {
                throw TraceUtility.ThrowHelperError(
                          new MessageSecurityException(SR.GetString(
                                                           SR.InvalidAttributeInSignedHeader, info.Name, info.Namespace,
                                                           XD.MessageDictionary.MustUnderstand, otherVersion.DictionaryNamespace,
                                                           XD.MessageDictionary.MustUnderstand, currentVersion.DictionaryNamespace)), this.SecurityVerifiedMessage);
            }

            presentInCurrentVersion = null != reader.GetAttribute(currentVersion.DictionaryActor, currentVersion.DictionaryNamespace);
            presentInOtherVersion   = null != reader.GetAttribute(otherVersion.DictionaryActor, otherVersion.DictionaryNamespace);
            if (presentInOtherVersion && !presentInCurrentVersion)
            {
                throw TraceUtility.ThrowHelperError(
                          new MessageSecurityException(SR.GetString(
                                                           SR.InvalidAttributeInSignedHeader, info.Name, info.Namespace,
                                                           otherVersion.DictionaryActor, otherVersion.DictionaryNamespace,
                                                           currentVersion.DictionaryActor, currentVersion.DictionaryNamespace)), this.SecurityVerifiedMessage);
            }
        }
 private void AddParts(ref MessagePartSpecification parts1, MessagePartSpecification parts2)
 {
     if (parts1 == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts1"));
     }
     if (parts2 == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts2"));
     }
     if (!parts2.IsEmpty())
     {
         if (parts1.IsReadOnly)
         {
             MessagePartSpecification specification = new MessagePartSpecification();
             specification.Union(parts1);
             specification.Union(parts2);
             parts1 = specification;
         }
         else
         {
             parts1.Union(parts2);
         }
     }
 }
		public void AddParts (MessagePartSpecification parts)
		{
			if (parts == null)
				throw new ArgumentNullException ("parts");
			if (IsReadOnly)
				throw new InvalidOperationException ("This ScopedMessagePartSpecification is read-only.");
			ChannelParts.Union (parts);
		}
		public void UnionReadOnlyPart ()
		{
			MessagePartSpecification s =
				new MessagePartSpecification ();
			s.MakeReadOnly ();
			Assert.AreEqual (true, s.IsReadOnly, "#1");
			s.Union (new MessagePartSpecification ());
		}
 internal void AddParts(MessagePartSpecification parts, XmlDictionaryString action)
 {
     if (action == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
     }
     this.AddParts(parts, action.Value);
 }
Beispiel #15
0
        public bool TryGetParts(string action, out MessagePartSpecification parts)
        {
            Contract.Ensures(Contract.Result <bool>() == (Contract.ValueAtReturn(out parts) != null));

            parts = default(MessagePartSpecification);

            return(default(bool));
        }
 internal void AddParts(MessagePartSpecification parts, XmlDictionaryString action)
 {
     if (action == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
     }
     AddParts(parts, action.Value);
 }
    public bool TryGetParts(string action, out MessagePartSpecification parts)
    {
      Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn(out parts) != null));

      parts = default(MessagePartSpecification);

      return default(bool);
    }
		public ScopedMessagePartSpecification (
			ScopedMessagePartSpecification other)
		{
			XmlQualifiedName [] array = new XmlQualifiedName [other.parts.HeaderTypes.Count];
			other.parts.HeaderTypes.CopyTo (array, 0);
			parts = new MessagePartSpecification (
				other.parts.IsBodyIncluded, array);
			table = new Dictionary<string,MessagePartSpecification> (other.table);
		}
 public ScopedMessagePartSpecification(
     ScopedMessagePartSpecification other)
 {
     XmlQualifiedName [] array = new XmlQualifiedName [other.parts.HeaderTypes.Count];
     other.parts.HeaderTypes.CopyTo(array, 0);
     parts = new MessagePartSpecification(
         other.parts.IsBodyIncluded, array);
     table = new Dictionary <string, MessagePartSpecification> (other.table);
 }
        public void AddParts(MessagePartSpecification parts)
        {
            if (parts == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts"));

            ThrowIfReadOnly();

            _channelParts.Union(parts);
        }
Beispiel #21
0
 public void AddParts(MessagePartSpecification parts)
 {
     if (parts == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts"));
     }
     this.ThrowIfReadOnly();
     this.channelParts.Union(parts);
 }
        protected override ISignatureValueSecurityElement CompletePrimarySignatureCore(SendSecurityHeaderElement[] signatureConfirmations, SecurityToken[] signedEndorsingTokens, SecurityToken[] signedTokens, SendSecurityHeaderElement[] basicTokens)
        {
            ISignatureValueSecurityElement signedXml;

            if (this.signedXml == null)
            {
                return(null);
            }
            SecurityTimestamp timestamp = base.Timestamp;

            if (timestamp != null)
            {
                if (timestamp.Id == null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("TimestampToSignHasNoId")));
                }
                HashStream stream = this.TakeHashStream();
                base.StandardsManager.WSUtilitySpecificationVersion.WriteTimestampCanonicalForm(stream, timestamp, this.signedInfo.ResourcePool.TakeEncodingBuffer());
                this.signedInfo.AddReference(timestamp.Id, stream.FlushHashAndGetValue());
            }
            if ((base.ShouldSignToHeader && (this.signatureKey is AsymmetricSecurityKey)) && (base.Version.Addressing != AddressingVersion.None))
            {
                if (this.toHeaderHash == null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("TransportSecurityRequireToHeader")));
                }
                this.signedInfo.AddReference(this.toHeaderId, this.toHeaderHash);
            }
            this.AddSignatureReference(signatureConfirmations);
            if (base.RequireMessageProtection)
            {
                this.AddSignatureReference(signedEndorsingTokens);
                this.AddSignatureReference(signedTokens);
                this.AddSignatureReference(basicTokens);
            }
            if (this.signedInfo.ReferenceCount == 0)
            {
                throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("NoPartsOfMessageMatchedPartsToSign")), base.Message);
            }
            try
            {
                this.signedXml.ComputeSignature(this.signatureKey);
                signedXml = this.signedXml;
            }
            finally
            {
                this.hashStream              = null;
                this.signedInfo              = null;
                this.signedXml               = null;
                this.signatureKey            = null;
                this.effectiveSignatureParts = null;
            }
            return(signedXml);
        }
		public void DefaultValues ()
		{
			MessagePartSpecification s =
				new MessagePartSpecification ();
			Assert.IsFalse (s.IsBodyIncluded, "#1");
			Assert.AreEqual (0, s.HeaderTypes.Count, "#2");

			s = new MessagePartSpecification (new XmlQualifiedName [] {new XmlQualifiedName ("foo", "urn:foo")});
			Assert.IsFalse (s.IsBodyIncluded, "#3");
			Assert.AreEqual (1, s.HeaderTypes.Count, "#4");
		}
 public void AddParts(MessagePartSpecification parts)
 {
     if (parts == null)
     {
         throw new ArgumentNullException("parts");
     }
     if (IsReadOnly)
     {
         throw new InvalidOperationException("This ScopedMessagePartSpecification is read-only.");
     }
     ChannelParts.Union(parts);
 }
        public void AddParts(MessagePartSpecification parts, string action)
        {
            if (action == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
            if (parts == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts"));

            ThrowIfReadOnly();

            if (!_actionParts.ContainsKey(action))
                _actionParts[action] = new MessagePartSpecification();
            _actionParts[action].Union(parts);
        }
        internal IChannelListener <TChannel> BuildNegotiationChannelListener <TChannel>(BindingContext context)
            where TChannel : class, IChannel
        {
            SecurityCredentialsManager securityCredentials = this.IssuerBindingContext.BindingParameters.Find <SecurityCredentialsManager>();

            if (securityCredentials == null)
            {
                securityCredentials = ServiceCredentials.CreateDefaultCredentials();
            }

            this.bootstrapSecurityBindingElement.ReaderQuotas = context.GetInnerProperty <XmlDictionaryReaderQuotas>();
            if (this.bootstrapSecurityBindingElement.ReaderQuotas == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.EncodingBindingElementDoesNotHandleReaderQuotas)));
            }

            TransportBindingElement transportBindingElement = context.RemainingBindingElements.Find <TransportBindingElement>();

            if (transportBindingElement != null)
            {
                this.bootstrapSecurityBindingElement.MaxReceivedMessageSize = transportBindingElement.MaxReceivedMessageSize;
            }

            SecurityProtocolFactory        securityProtocolFactory = this.bootstrapSecurityBindingElement.CreateSecurityProtocolFactory <TChannel>(this.IssuerBindingContext.Clone(), securityCredentials, true, this.IssuerBindingContext.Clone());
            MessageSecurityProtocolFactory soapBindingFactory      = securityProtocolFactory as MessageSecurityProtocolFactory;

            if (soapBindingFactory != null)
            {
                soapBindingFactory.ApplyConfidentiality             = soapBindingFactory.ApplyIntegrity
                                                                    = soapBindingFactory.RequireConfidentiality = soapBindingFactory.RequireIntegrity = true;
                MessagePartSpecification bodyPart = new MessagePartSpecification(true);
                soapBindingFactory.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, RequestSecurityTokenResponseAction);
                soapBindingFactory.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, RequestSecurityTokenResponseAction);
                soapBindingFactory.ProtectionRequirements.IncomingSignatureParts.AddParts(bodyPart, RequestSecurityTokenAction);
                soapBindingFactory.ProtectionRequirements.IncomingEncryptionParts.AddParts(bodyPart, RequestSecurityTokenAction);
            }

            SecurityChannelListener <TChannel> securityChannelListener =
                new SecurityChannelListener <TChannel>(this.bootstrapSecurityBindingElement, context);

            securityChannelListener.SecurityProtocolFactory = securityProtocolFactory;
            // do not send back unsecured faults over composite duplex
            securityChannelListener.SendUnsecuredFaults = !SecurityUtils.IsCompositeDuplexBinding(context);

            ChannelBuilder channelBuilder = new ChannelBuilder(context, true);

            securityChannelListener.InitializeListener(channelBuilder);
            this.shouldMatchRstWithEndpointFilter = SecurityUtils.ShouldMatchRstWithEndpointFilter(this.bootstrapSecurityBindingElement);
            return(securityChannelListener);
        }
        private static void AddHeaderProtectionRequirements(MessageHeaderDescription header, MessagePartSpecification signedParts,
                                                            MessagePartSpecification encryptedParts, ProtectionLevel defaultProtectionLevel)
        {
            ProtectionLevel p = header.HasProtectionLevel ? header.ProtectionLevel : defaultProtectionLevel;

            if (p != ProtectionLevel.None)
            {
                XmlQualifiedName headerName = new XmlQualifiedName(header.Name, header.Namespace);
                signedParts.HeaderTypes.Add(headerName);
                if (p == ProtectionLevel.EncryptAndSign)
                {
                    encryptedParts.HeaderTypes.Add(headerName);
                }
            }
        }
        protected override void StartPrimarySignatureCore(SecurityToken token,
                                                          SecurityKeyIdentifier keyIdentifier,
                                                          MessagePartSpecification signatureParts,
                                                          bool generateTargettableSignature)
        {
            SecurityAlgorithmSuite suite     = AlgorithmSuite;
            string canonicalizationAlgorithm = suite.DefaultCanonicalizationAlgorithm;

            if (canonicalizationAlgorithm != SecurityAlgorithms.ExclusiveC14n)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new MessageSecurityException(SR.Format(SR.UnsupportedCanonicalizationAlgorithm, suite.DefaultCanonicalizationAlgorithm)));
            }
            string signatureAlgorithm;
            XmlDictionaryString signatureAlgorithmDictionaryString;
            SecurityKey         signatureKey;

            suite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out signatureKey, out signatureAlgorithmDictionaryString);
            AsymmetricAlgorithm asymmetricAlgorithm = null;

            GetSigningAlgorithm(signatureKey, signatureAlgorithm, out _signingKey, out asymmetricAlgorithm);

            _signedXml = new SignedXml();
            _signedXml.SignedInfo.CanonicalizationMethod = canonicalizationAlgorithm;
            _signedXml.SignedInfo.SignatureMethod        = signatureAlgorithm;
            _signedXml.SigningKey = asymmetricAlgorithm;
            if (keyIdentifier != null)
            {
                var stream = new MemoryStream();
                using (var xmlWriter = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false))
                {
                    StandardsManager.SecurityTokenSerializer.WriteKeyIdentifier(xmlWriter, keyIdentifier);
                }

                stream.Position = 0;
                XmlDocument doc = new XmlDocument();
                doc.Load(stream);
                var keyInfo = new KeyInfo();
                keyInfo.LoadXml(doc.DocumentElement);
                _signedXml.KeyInfo = keyInfo;
            }

            if (generateTargettableSignature)
            {
                _signedXml.Signature.Id = GenerateId();
            }
            _effectiveSignatureParts = signatureParts;
        }
 public void MakeReadOnly()
 {
     if (!this.isReadOnly)
     {
         this.readOnlyNormalizedActionParts = new Dictionary <string, MessagePartSpecification>();
         foreach (string action in this.actionParts.Keys)
         {
             MessagePartSpecification p = new MessagePartSpecification();
             p.Union(this.actionParts[action]);
             p.Union(this.channelParts);
             p.MakeReadOnly();
             this.readOnlyNormalizedActionParts[action] = p;
         }
         this.isReadOnly = true;
     }
 }
 public void MakeReadOnly()
 {
     if (!IsReadOnly)
     {
         _readOnlyNormalizedActionParts = new Dictionary <string, MessagePartSpecification>();
         foreach (string action in _actionParts.Keys)
         {
             MessagePartSpecification p = new MessagePartSpecification();
             p.Union(_actionParts[action]);
             p.Union(ChannelParts);
             p.MakeReadOnly();
             _readOnlyNormalizedActionParts[action] = p;
         }
         IsReadOnly = true;
     }
 }
		public void AddParts (MessagePartSpecification parts,
			string action)
		{
			if (parts == null)
				throw new ArgumentNullException ("parts");
			if (action == null)
				throw new ArgumentNullException ("action");
			if (IsReadOnly)
				throw new InvalidOperationException ("This ScopedMessagePartSpecification is read-only.");

			MessagePartSpecification existing;
			if (table.TryGetValue (action, out existing))
				existing.Union (parts);
			else
				table.Add (action, parts);
		}
Beispiel #32
0
 public void AddParts(MessagePartSpecification parts, string action)
 {
     if (action == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
     }
     if (parts == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts"));
     }
     this.ThrowIfReadOnly();
     if (!this.actionParts.ContainsKey(action))
     {
         this.actionParts[action] = new MessagePartSpecification();
     }
     this.actionParts[action].Union(parts);
 }
 public ScopedMessagePartSpecification(ScopedMessagePartSpecification other) : this()
 {
     if (other == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("other"));
     }
     this.channelParts.Union(other.channelParts);
     if (other.actionParts != null)
     {
         foreach (string str in other.actionParts.Keys)
         {
             MessagePartSpecification specification = new MessagePartSpecification();
             specification.Union(other.actionParts[str]);
             this.actionParts[str] = specification;
         }
     }
 }
        public ScopedMessagePartSpecification(ScopedMessagePartSpecification other)
            : this()
        {
            if (other == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("other"));

            _channelParts.Union(other._channelParts);
            if (other._actionParts != null)
            {
                foreach (string action in other._actionParts.Keys)
                {
                    MessagePartSpecification p = new MessagePartSpecification();
                    p.Union(other._actionParts[action]);
                    _actionParts[action] = p;
                }
            }
        }
Beispiel #35
0
 public ScopedMessagePartSpecification(ScopedMessagePartSpecification other) : this()
 {
     if (other == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("other"));
     }
     this.channelParts.Union(other.channelParts);
     if (other.actionParts != null)
     {
         foreach (string str in other.actionParts.Keys)
         {
             MessagePartSpecification specification = new MessagePartSpecification();
             specification.Union(other.actionParts[str]);
             this.actionParts[str] = specification;
         }
     }
 }
		public void Union ()
		{
			XmlQualifiedName q1, q2, q3;
			q1 = new XmlQualifiedName ("foo");
			q2 = new XmlQualifiedName ("bar");
			q3 = new XmlQualifiedName ("baz");
			MessagePartSpecification p1 =
				new MessagePartSpecification (false, new XmlQualifiedName [] {q1, q2});
			MessagePartSpecification p2 =
				new MessagePartSpecification (true, new XmlQualifiedName [] {q3, q2});
			p1.Union (p2);
			Assert.IsTrue (p1.IsBodyIncluded, "#1");
			// Sigh. It does not exclude duplicates.
			Assert.AreEqual (4, p1.HeaderTypes.Count, "#1-2");
			Assert.IsTrue (p1.HeaderTypes.Contains (q1), "#2");
			Assert.IsTrue (p1.HeaderTypes.Contains (q2), "#3");
			Assert.IsTrue (p1.HeaderTypes.Contains (q3), "#4");
		}
Beispiel #37
0
 protected void EnsureEndpointAddressDoesNotRequireEncryption(EndpointAddress target)
 {
     if ((this.ApplicationProtectionRequirements != null) && (this.ApplicationProtectionRequirements.OutgoingEncryptionParts != null))
     {
         MessagePartSpecification channelParts = this.ApplicationProtectionRequirements.OutgoingEncryptionParts.ChannelParts;
         if (channelParts != null)
         {
             for (int i = 0; i < this.targetAddress.Headers.Count; i++)
             {
                 AddressHeader header = target.Headers[i];
                 if (channelParts.IsHeaderIncluded(header.Name, header.Namespace))
                 {
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("SecurityNegotiationCannotProtectConfidentialEndpointHeader", new object[] { target, header.Name, header.Namespace })));
                 }
             }
         }
     }
 }
 private void VerifySoapAttributeMatchForHeader(MessageHeaderInfo info, MessagePartSpecification signatureParts, XmlDictionaryReader reader)
 {
     if (signatureParts.IsHeaderIncluded(info.Name, info.Namespace))
     {
         EnvelopeVersion envelope = base.Version.Envelope;
         EnvelopeVersion version2 = (envelope == EnvelopeVersion.Soap11) ? EnvelopeVersion.Soap12 : EnvelopeVersion.Soap11;
         bool            flag     = null != reader.GetAttribute(System.ServiceModel.XD.MessageDictionary.MustUnderstand, envelope.DictionaryNamespace);
         if ((null != reader.GetAttribute(System.ServiceModel.XD.MessageDictionary.MustUnderstand, version2.DictionaryNamespace)) && !flag)
         {
             throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("InvalidAttributeInSignedHeader", new object[] { info.Name, info.Namespace, System.ServiceModel.XD.MessageDictionary.MustUnderstand, version2.DictionaryNamespace, System.ServiceModel.XD.MessageDictionary.MustUnderstand, envelope.DictionaryNamespace })), base.SecurityVerifiedMessage);
         }
         flag = null != reader.GetAttribute(envelope.DictionaryActor, envelope.DictionaryNamespace);
         if ((null != reader.GetAttribute(version2.DictionaryActor, version2.DictionaryNamespace)) && !flag)
         {
             throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("InvalidAttributeInSignedHeader", new object[] { info.Name, info.Namespace, version2.DictionaryActor, version2.DictionaryNamespace, envelope.DictionaryActor, envelope.DictionaryNamespace })), base.SecurityVerifiedMessage);
         }
     }
 }
 public void Union(MessagePartSpecification other)
 {
     if (other == null)
     {
         throw new ArgumentNullException("other");
     }
     if (header_types.IsReadOnly)
     {
         throw new InvalidOperationException("This MessagePartSpecification is read-only.");
     }
     body |= other.body;
     foreach (XmlQualifiedName q in other.header_types)
     {
         // Sigh. It could be much better here.
         //if (!header_types.Contains (q))
         header_types.Add(q);
     }
 }
 private AddressingVersion(string ns, XmlDictionaryString dictionaryNs, string toStringFormat, MessagePartSpecification signedMessageParts, string anonymous, XmlDictionaryString dictionaryAnonymous, string none, string faultAction, string defaultFaultAction)
 {
     this.ns = ns;
     this.dictionaryNs = dictionaryNs;
     this.toStringFormat = toStringFormat;
     this.signedMessageParts = signedMessageParts;
     this.anonymous = anonymous;
     this.dictionaryAnonymous = dictionaryAnonymous;
     if (anonymous != null)
     {
         this.anonymousUri = new Uri(anonymous);
     }
     if (none != null)
     {
         this.noneUri = new Uri(none);
     }
     this.faultAction = faultAction;
     this.defaultFaultAction = defaultFaultAction;
 }
        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {

            var proReq =
                bindingParameters.Remove<ChannelProtectionRequirements>();

            proReq = new ChannelProtectionRequirements();

            MessagePartSpecification unProtectedSpec = new MessagePartSpecification();
            MessagePartSpecification protectedSpec = new MessagePartSpecification(true);

            // I'm setting same protection level for all the actions.
            // You could specify different protection level per action, if required. 
            // Also note, I haven't implemented any support for custom SOAP headers.
            // However that can easily be added using the same mechansim.
            switch (level)
            {
                case ProtectionLevel.None:
                    proReq.OutgoingSignatureParts.AddParts(unProtectedSpec, "*");
                    proReq.IncomingSignatureParts.AddParts(unProtectedSpec, "*");

                    proReq.OutgoingEncryptionParts.AddParts(unProtectedSpec, "*");
                    proReq.IncomingEncryptionParts.AddParts(unProtectedSpec, "*");
                    break;
                case ProtectionLevel.Sign:
                    proReq.OutgoingSignatureParts.AddParts(protectedSpec, "*");
                    proReq.IncomingSignatureParts.AddParts(protectedSpec, "*");

                    proReq.OutgoingEncryptionParts.AddParts(unProtectedSpec, "*");
                    proReq.IncomingEncryptionParts.AddParts(unProtectedSpec, "*");
                    break;
                case ProtectionLevel.EncryptAndSign:
                    proReq.OutgoingSignatureParts.AddParts(protectedSpec, "*");
                    proReq.IncomingSignatureParts.AddParts(protectedSpec, "*");

                    proReq.OutgoingEncryptionParts.AddParts(protectedSpec, "*");
                    proReq.IncomingEncryptionParts.AddParts(protectedSpec, "*");
                    break;
            }
            // Add our protection requirement for this endpoint into the binding params.

            bindingParameters.Add(proReq);
        }
        public ScopedMessagePartSpecification(ScopedMessagePartSpecification other)
            : this()
        {
            if (other == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(other)));
            }

            ChannelParts.Union(other.ChannelParts);
            if (other._actionParts != null)
            {
                foreach (string action in other._actionParts.Keys)
                {
                    MessagePartSpecification p = new MessagePartSpecification();
                    p.Union(other._actionParts[action]);
                    _actionParts[action] = p;
                }
            }
        }
Beispiel #43
0
        protected override IChannelFactory <IRequestChannel> GetNegotiationChannelFactory(IChannelFactory <IRequestChannel> transportChannelFactory, ChannelBuilder channelBuilder)
        {
            ISecurityCapabilities      securityCapabilities = this.bootstrapSecurityBindingElement.GetProperty <ISecurityCapabilities>(this.IssuerBindingContext);
            SecurityCredentialsManager securityCredentials  = this.IssuerBindingContext.BindingParameters.Find <SecurityCredentialsManager>();

            if (securityCredentials == null)
            {
                securityCredentials = ClientCredentials.CreateDefaultCredentials();
            }

            this.bootstrapSecurityBindingElement.ReaderQuotas = this.IssuerBindingContext.GetInnerProperty <XmlDictionaryReaderQuotas>();
            if (this.bootstrapSecurityBindingElement.ReaderQuotas == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.EncodingBindingElementDoesNotHandleReaderQuotas)));
            }

            TransportBindingElement transportBindingElement = this.IssuerBindingContext.RemainingBindingElements.Find <TransportBindingElement>();

            if (transportBindingElement != null)
            {
                this.bootstrapSecurityBindingElement.MaxReceivedMessageSize = transportBindingElement.MaxReceivedMessageSize;
            }

            SecurityProtocolFactory        securityProtocolFactory = this.bootstrapSecurityBindingElement.CreateSecurityProtocolFactory <IRequestChannel>(this.IssuerBindingContext.Clone(), securityCredentials, false, this.IssuerBindingContext.Clone());
            MessageSecurityProtocolFactory soapBindingFactory      = (securityProtocolFactory as MessageSecurityProtocolFactory);

            if (soapBindingFactory != null)
            {
                soapBindingFactory.ApplyConfidentiality             = soapBindingFactory.ApplyIntegrity
                                                                    = soapBindingFactory.RequireConfidentiality = soapBindingFactory.RequireIntegrity = true;

                MessagePartSpecification bodyPart = new MessagePartSpecification(true);
                soapBindingFactory.ProtectionRequirements.IncomingSignatureParts.AddParts(bodyPart, RequestSecurityTokenAction);
                soapBindingFactory.ProtectionRequirements.IncomingEncryptionParts.AddParts(bodyPart, RequestSecurityTokenAction);
                soapBindingFactory.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, RequestSecurityTokenResponseAction);
                soapBindingFactory.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, RequestSecurityTokenResponseAction);
            }
            securityProtocolFactory.PrivacyNoticeUri     = this.PrivacyNoticeUri;
            securityProtocolFactory.PrivacyNoticeVersion = this.PrivacyNoticeVersion;
            return(new SecurityChannelFactory <IRequestChannel>(
                       securityCapabilities, this.IssuerBindingContext, channelBuilder, securityProtocolFactory, transportChannelFactory));
        }
        internal IChannelListener <TChannel> BuildNegotiationChannelListener <TChannel>(BindingContext context) where TChannel : class, IChannel
        {
            SecurityCredentialsManager credentialsManager = base.IssuerBindingContext.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }
            this.bootstrapSecurityBindingElement.ReaderQuotas = context.GetInnerProperty <XmlDictionaryReaderQuotas>();
            if (this.bootstrapSecurityBindingElement.ReaderQuotas == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("EncodingBindingElementDoesNotHandleReaderQuotas")));
            }
            TransportBindingElement element = context.RemainingBindingElements.Find <TransportBindingElement>();

            if (element != null)
            {
                this.bootstrapSecurityBindingElement.MaxReceivedMessageSize = element.MaxReceivedMessageSize;
            }
            SecurityProtocolFactory        factory  = this.bootstrapSecurityBindingElement.CreateSecurityProtocolFactory <TChannel>(base.IssuerBindingContext.Clone(), credentialsManager, true, base.IssuerBindingContext.Clone());
            MessageSecurityProtocolFactory factory2 = factory as MessageSecurityProtocolFactory;

            if (factory2 != null)
            {
                factory2.ApplyConfidentiality = factory2.ApplyIntegrity = factory2.RequireConfidentiality = factory2.RequireIntegrity = true;
                MessagePartSpecification parts = new MessagePartSpecification(true);
                factory2.ProtectionRequirements.OutgoingSignatureParts.AddParts(parts, this.RequestSecurityTokenResponseAction);
                factory2.ProtectionRequirements.OutgoingEncryptionParts.AddParts(parts, this.RequestSecurityTokenResponseAction);
                factory2.ProtectionRequirements.IncomingSignatureParts.AddParts(parts, this.RequestSecurityTokenAction);
                factory2.ProtectionRequirements.IncomingEncryptionParts.AddParts(parts, this.RequestSecurityTokenAction);
            }
            SecurityChannelListener <TChannel> listener = new SecurityChannelListener <TChannel>(this.bootstrapSecurityBindingElement, context)
            {
                SecurityProtocolFactory = factory,
                SendUnsecuredFaults     = !System.ServiceModel.Security.SecurityUtils.IsCompositeDuplexBinding(context)
            };
            ChannelBuilder channelBuilder = new ChannelBuilder(context, true);

            listener.InitializeListener(channelBuilder);
            this.shouldMatchRstWithEndpointFilter = System.ServiceModel.Security.SecurityUtils.ShouldMatchRstWithEndpointFilter(this.bootstrapSecurityBindingElement);
            return(listener);
        }
        internal static ChannelProtectionRequirements GetChannelProtectionRequirements(ProtectionLevel protectionLevel)
        {
            ChannelProtectionRequirements result;

            if (protectionLevel == ProtectionLevel.EncryptAndSign)
            {
                if (encryptAndSignChannelProtectionRequirements == null)
                {
                    MessagePartSpecification header = new MessagePartSpecification();
                    header.HeaderTypes.Add(new XmlQualifiedName(CallbackContextHeaderName, CallbackContextHeaderNamespace));
                    ChannelProtectionRequirements requirements = new ChannelProtectionRequirements();
                    requirements.IncomingSignatureParts.AddParts(header);
                    requirements.IncomingEncryptionParts.AddParts(header);
                    requirements.OutgoingSignatureParts.AddParts(header);
                    requirements.OutgoingEncryptionParts.AddParts(header);
                    requirements.MakeReadOnly();
                    encryptAndSignChannelProtectionRequirements = requirements;
                }
                result = encryptAndSignChannelProtectionRequirements;
            }
            else if (protectionLevel == ProtectionLevel.Sign)
            {
                if (signChannelProtectionRequirements == null)
                {
                    MessagePartSpecification header = new MessagePartSpecification();
                    header.HeaderTypes.Add(new XmlQualifiedName(CallbackContextHeaderName, CallbackContextHeaderNamespace));
                    ChannelProtectionRequirements requirements = new ChannelProtectionRequirements();
                    requirements.IncomingSignatureParts.AddParts(header);
                    requirements.OutgoingSignatureParts.AddParts(header);
                    requirements.MakeReadOnly();
                    signChannelProtectionRequirements = requirements;
                }
                result = signChannelProtectionRequirements;
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("protectionLevel"));
            }

            return result;
        }
        // helper methods
        protected void EnsureEndpointAddressDoesNotRequireEncryption(EndpointAddress target)
        {
            if (ApplicationProtectionRequirements == null ||
                ApplicationProtectionRequirements.OutgoingEncryptionParts == null)
            {
                return;
            }
            MessagePartSpecification channelEncryptionParts = ApplicationProtectionRequirements.OutgoingEncryptionParts.ChannelParts;

            if (channelEncryptionParts == null)
            {
                return;
            }
            for (int i = 0; i < _targetAddress.Headers.Count; ++i)
            {
                AddressHeader header = target.Headers[i];
                if (channelEncryptionParts.IsHeaderIncluded(header.Name, header.Namespace))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.SecurityNegotiationCannotProtectConfidentialEndpointHeader, target, header.Name, header.Namespace)));
                }
            }
        }
        private static MessagePartSpecification ExtractMessageParts(string action, ScopedMessagePartSpecification scopedParts, bool isForSignature)
        {
            MessagePartSpecification parts = (MessagePartSpecification)null;

            if (scopedParts.TryGetParts(action, out parts) || scopedParts.TryGetParts("*", out parts))
            {
                return(parts);
            }
            SecurityVersion securityVersion = MessageSecurityVersion.Default.SecurityVersion;
            MessageFault    fault           = MessageFault.CreateFault(FaultCode.CreateSenderFaultCode(new FaultCode(securityVersion.InvalidSecurityFaultCode.Value, securityVersion.HeaderNamespace.Value)), new FaultReason(SR.GetString("InvalidOrUnrecognizedAction", new object[1] {
                (object)action
            }), CultureInfo.CurrentCulture));

            if (isForSignature)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError((Exception) new MessageSecurityException(SR.GetString("NoSignaturePartsSpecified", new object[1] {
                    (object)action
                }), (Exception)null, fault));
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError((Exception) new MessageSecurityException(SR.GetString("NoEncryptionPartsSpecified", new object[1] {
                (object)action
            }), (Exception)null, fault));
        }
 internal static ChannelProtectionRequirements GetChannelProtectionRequirements(ProtectionLevel protectionLevel)
 {
     if (protectionLevel == ProtectionLevel.EncryptAndSign)
     {
         if (encryptAndSignChannelProtectionRequirements == null)
         {
             MessagePartSpecification parts = new MessagePartSpecification {
                 HeaderTypes = { new XmlQualifiedName("CallbackContext", "http://schemas.microsoft.com/ws/2008/02/context") }
             };
             ChannelProtectionRequirements requirements2 = new ChannelProtectionRequirements();
             requirements2.IncomingSignatureParts.AddParts(parts);
             requirements2.IncomingEncryptionParts.AddParts(parts);
             requirements2.OutgoingSignatureParts.AddParts(parts);
             requirements2.OutgoingEncryptionParts.AddParts(parts);
             requirements2.MakeReadOnly();
             encryptAndSignChannelProtectionRequirements = requirements2;
         }
         return encryptAndSignChannelProtectionRequirements;
     }
     if (protectionLevel != ProtectionLevel.Sign)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("protectionLevel"));
     }
     if (signChannelProtectionRequirements == null)
     {
         MessagePartSpecification specification2 = new MessagePartSpecification {
             HeaderTypes = { new XmlQualifiedName("CallbackContext", "http://schemas.microsoft.com/ws/2008/02/context") }
         };
         ChannelProtectionRequirements requirements3 = new ChannelProtectionRequirements();
         requirements3.IncomingSignatureParts.AddParts(specification2);
         requirements3.OutgoingSignatureParts.AddParts(specification2);
         requirements3.MakeReadOnly();
         signChannelProtectionRequirements = requirements3;
     }
     return signChannelProtectionRequirements;
 }
        void ImportProtectionAssertions(ICollection<XmlElement> assertions, out MessagePartSpecification signedParts, out MessagePartSpecification encryptedParts)
        {
            XmlElement assertion;

            signedParts = null;
            encryptedParts = null;

            WSSecurityPolicy securityPolicy;
            if (WSSecurityPolicy.TryGetSecurityPolicyDriver(assertions, out securityPolicy))
            {
                if (!securityPolicy.TryImportWsspEncryptedPartsAssertion(assertions, out encryptedParts, out assertion)
                    && assertion != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnsupportedSecurityPolicyAssertion, assertion.OuterXml)));
                }

                if (!securityPolicy.TryImportWsspSignedPartsAssertion(assertions, out signedParts, out assertion)
                    && assertion != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnsupportedSecurityPolicyAssertion, assertion.OuterXml)));
                }
            }

            if (encryptedParts == null)
            {
                encryptedParts = MessagePartSpecification.NoParts;
            }
            if (signedParts == null)
            {
                signedParts = MessagePartSpecification.NoParts;
            }
        }
 protected override void StartPrimarySignatureCore(SecurityToken token,
     SecurityKeyIdentifier keyIdentifier,
     MessagePartSpecification signatureParts,
     bool generateTargettableSignature)
 {
     SecurityAlgorithmSuite suite = this.AlgorithmSuite;
     string canonicalizationAlgorithm = suite.DefaultCanonicalizationAlgorithm;
     XmlDictionaryString canonicalizationAlgorithmDictionaryString = suite.DefaultCanonicalizationAlgorithmDictionaryString;
     if (canonicalizationAlgorithm != SecurityAlgorithms.ExclusiveC14n)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
             new MessageSecurityException(SR.GetString(SR.UnsupportedCanonicalizationAlgorithm, suite.DefaultCanonicalizationAlgorithm)));
     }
     string signatureAlgorithm;
     XmlDictionaryString signatureAlgorithmDictionaryString;
     suite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out this.signatureKey, out signatureAlgorithmDictionaryString);
     string digestAlgorithm = suite.DefaultDigestAlgorithm;
     XmlDictionaryString digestAlgorithmDictionaryString = suite.DefaultDigestAlgorithmDictionaryString;
     this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, canonicalizationAlgorithm, canonicalizationAlgorithmDictionaryString, digestAlgorithm, digestAlgorithmDictionaryString, signatureAlgorithm, signatureAlgorithmDictionaryString);
     this.signedXml = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
     if (keyIdentifier != null)
     {
         this.signedXml.Signature.KeyIdentifier = keyIdentifier;
     }
     if (generateTargettableSignature)
     {
         this.signedXml.Id = GenerateId();
     }
     this.effectiveSignatureParts = signatureParts;
     this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(digestAlgorithm);
 }
        protected override ISignatureValueSecurityElement CompletePrimarySignatureCore(
            SendSecurityHeaderElement[] signatureConfirmations,
            SecurityToken[] signedEndorsingTokens,
            SecurityToken[] signedTokens,
            SendSecurityHeaderElement[] basicTokens, bool isPrimarySignature)
        {
            if (this.signedXml == null)
            {
                return null;
            }

            SecurityTimestamp timestamp = this.Timestamp;
            if (timestamp != null)
            {
                if (timestamp.Id == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TimestampToSignHasNoId)));
                }
                HashStream hashStream = TakeHashStream();
                this.StandardsManager.WSUtilitySpecificationVersion.WriteTimestampCanonicalForm(
                    hashStream, timestamp, this.signedInfo.ResourcePool.TakeEncodingBuffer());
                signedInfo.AddReference(timestamp.Id, hashStream.FlushHashAndGetValue());
            }

            if ((this.ShouldSignToHeader) && (this.signatureKey is AsymmetricSecurityKey) && (this.Version.Addressing != AddressingVersion.None))
            {
                if (this.toHeaderHash != null)
                    signedInfo.AddReference(this.toHeaderId, this.toHeaderHash);
                else
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TransportSecurityRequireToHeader)));
            }

            AddSignatureReference(signatureConfirmations);
            if (isPrimarySignature && this.ShouldProtectTokens)
            {
                AddPrimaryTokenSignatureReference(this.ElementContainer.SourceSigningToken, this.SigningTokenParameters);
            }

            if (this.RequireMessageProtection)
            {
                AddSignatureReference(signedEndorsingTokens, SecurityTokenAttachmentMode.SignedEndorsing);
                AddSignatureReference(signedTokens, SecurityTokenAttachmentMode.Signed);
                AddSignatureReference(basicTokens);
            }

            if (this.signedInfo.ReferenceCount == 0)
            {
                throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoPartsOfMessageMatchedPartsToSign)), this.Message);
            }
            try
            {
                this.signedXml.ComputeSignature(this.signatureKey);
                return this.signedXml;
            }
            finally
            {
                this.hashStream = null;
                this.signedInfo = null;
                this.signedXml = null;
                this.signatureKey = null;
                this.effectiveSignatureParts = null;
            }
        }
        private static void AddFaultProtectionRequirements(FaultDescriptionCollection faults, ChannelProtectionRequirements requirements, ProtectionLevel defaultProtectionLevel, bool addToIncoming)
        {
            if (faults == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faults"));
            if (requirements == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("requirements"));

            foreach (FaultDescription fault in faults)
            {
                MessagePartSpecification signedParts = new MessagePartSpecification();
                MessagePartSpecification encryptedParts = new MessagePartSpecification();
                ProtectionLevel p = fault.HasProtectionLevel ? fault.ProtectionLevel : defaultProtectionLevel;
                if (p != ProtectionLevel.None)
                {
                    signedParts.IsBodyIncluded = true;
                    if (p == ProtectionLevel.EncryptAndSign)
                    {
                        encryptedParts.IsBodyIncluded = true;
                    }
                }
                if (addToIncoming)
                {
                    requirements.IncomingSignatureParts.AddParts(signedParts, fault.Action);
                    requirements.IncomingEncryptionParts.AddParts(encryptedParts, fault.Action);
                }
                else
                {
                    requirements.OutgoingSignatureParts.AddParts(signedParts, fault.Action);
                    requirements.OutgoingEncryptionParts.AddParts(encryptedParts, fault.Action);
                }
            }
        }
 private static void AddHeaderProtectionRequirements(MessageHeaderDescription header, MessagePartSpecification signedParts,
     MessagePartSpecification encryptedParts, ProtectionLevel defaultProtectionLevel)
 {
     ProtectionLevel p = header.HasProtectionLevel ? header.ProtectionLevel : defaultProtectionLevel;
     if (p != ProtectionLevel.None)
     {
         XmlQualifiedName headerName = new XmlQualifiedName(header.Name, header.Namespace);
         signedParts.HeaderTypes.Add(headerName);
         if (p == ProtectionLevel.EncryptAndSign)
             encryptedParts.HeaderTypes.Add(headerName);
     }
 }
        public virtual MessagePartSpecification TryGetProtectedParts(XmlElement assertion)
        {
            MessagePartSpecification parts = new MessagePartSpecification();

            foreach (XmlNode node in assertion.ChildNodes)
            {
                if (node.NodeType == XmlNodeType.Whitespace || node.NodeType == XmlNodeType.Comment)
                {
                    continue;
                }
                else if (node is XmlElement)
                {
                    XmlElement element = (XmlElement)node;
                    if (IsWsspAssertion(element, BodyName))
                    {
                        parts.IsBodyIncluded = true;
                    }
                    else if (IsWsspAssertion(element, HeaderName))
                    {
                        string name = element.GetAttribute(NameName);
                        string ns = element.GetAttribute(NamespaceName);

                        if (ns == null)
                        {
                            parts = null;
                            break;
                        }

                        parts.HeaderTypes.Add(new XmlQualifiedName(name, ns));
                    }
                    else
                    {
                        parts = null;
                        break;
                    }
                }
                else
                {
                    parts = null;
                    break;
                }
            }

            return parts;
        }
        public virtual XmlElement CreateWsspBootstrapPolicyAssertion(MetadataExporter exporter, SecurityBindingElement bootstrapSecurity)
        {
            if (bootstrapSecurity == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bootstrapBinding");

            WSSecurityPolicy sp = WSSecurityPolicy.GetSecurityPolicyDriver(bootstrapSecurity.MessageSecurityVersion);

            // create complete bootstrap binding

            CustomBinding bootstrapBinding = new CustomBinding(bootstrapSecurity);
            if (exporter.State.ContainsKey(SecurityPolicyStrings.SecureConversationBootstrapBindingElementsBelowSecurityKey))
            {
                BindingElementCollection bindingElementsBelowSecurity = exporter.State[SecurityPolicyStrings.SecureConversationBootstrapBindingElementsBelowSecurityKey] as BindingElementCollection;
                if (bindingElementsBelowSecurity != null)
                {
                    foreach (BindingElement be in bindingElementsBelowSecurity)
                    {
                        bootstrapBinding.Elements.Add(be);
                    }
                }
            }

            // generate policy for the "how" of security 

            ServiceEndpoint bootstrapEndpoint = new ServiceEndpoint(NullContract);
            bootstrapEndpoint.Binding = bootstrapBinding;
            PolicyConversionContext policyContext = exporter.ExportPolicy(bootstrapEndpoint);

            // generate policy for the "what" of security (protection assertions)

            // hard-coded requirements in V1: sign and encrypt RST and RSTR body
            ChannelProtectionRequirements bootstrapProtection = new ChannelProtectionRequirements();
            bootstrapProtection.IncomingEncryptionParts.AddParts(new MessagePartSpecification(true));
            bootstrapProtection.OutgoingEncryptionParts.AddParts(new MessagePartSpecification(true));
            bootstrapProtection.IncomingSignatureParts.AddParts(new MessagePartSpecification(true));
            bootstrapProtection.OutgoingSignatureParts.AddParts(new MessagePartSpecification(true));

            // add boostrap binding protection requirements (e.g. addressing headers)
            ChannelProtectionRequirements cpr = bootstrapBinding.GetProperty<ChannelProtectionRequirements>(new BindingParameterCollection());
            if (cpr != null)
            {
                bootstrapProtection.Add(cpr);
            }

            // extract channel-scope protection requirements and union them across request and response
            MessagePartSpecification encryption = new MessagePartSpecification();
            encryption.Union(bootstrapProtection.IncomingEncryptionParts.ChannelParts);
            encryption.Union(bootstrapProtection.OutgoingEncryptionParts.ChannelParts);
            encryption.MakeReadOnly();
            MessagePartSpecification signature = new MessagePartSpecification();
            signature.Union(bootstrapProtection.IncomingSignatureParts.ChannelParts);
            signature.Union(bootstrapProtection.OutgoingSignatureParts.ChannelParts);
            signature.MakeReadOnly();

            // create final boostrap policy assertion

            XmlElement nestedPolicy = CreateWspPolicyWrapper(
                    exporter,
                    sp.CreateWsspSignedPartsAssertion(signature),
                    sp.CreateWsspEncryptedPartsAssertion(encryption));
            foreach (XmlElement e in sp.FilterWsspPolicyAssertions(policyContext.GetBindingAssertions()))
            {
                nestedPolicy.AppendChild(e);
            }
            XmlElement result = CreateWsspAssertion(BootstrapPolicyName);
            result.AppendChild(nestedPolicy);

            return result;
        }
 protected override void StartPrimarySignatureCore(SecurityToken token, SecurityKeyIdentifier keyIdentifier, MessagePartSpecification signatureParts, bool generateTargettableSignature)
 {
     string str3;
     XmlDictionaryString str4;
     SecurityAlgorithmSuite algorithmSuite = base.AlgorithmSuite;
     string defaultCanonicalizationAlgorithm = algorithmSuite.DefaultCanonicalizationAlgorithm;
     XmlDictionaryString defaultCanonicalizationAlgorithmDictionaryString = algorithmSuite.DefaultCanonicalizationAlgorithmDictionaryString;
     if (defaultCanonicalizationAlgorithm != "http://www.w3.org/2001/10/xml-exc-c14n#")
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("UnsupportedCanonicalizationAlgorithm", new object[] { algorithmSuite.DefaultCanonicalizationAlgorithm })));
     }
     algorithmSuite.GetSignatureAlgorithmAndKey(token, out str3, out this.signatureKey, out str4);
     string defaultDigestAlgorithm = algorithmSuite.DefaultDigestAlgorithm;
     XmlDictionaryString defaultDigestAlgorithmDictionaryString = algorithmSuite.DefaultDigestAlgorithmDictionaryString;
     this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, defaultCanonicalizationAlgorithm, defaultCanonicalizationAlgorithmDictionaryString, defaultDigestAlgorithm, defaultDigestAlgorithmDictionaryString, str3, str4);
     this.signedXml = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, base.StandardsManager.SecurityTokenSerializer);
     if (keyIdentifier != null)
     {
         this.signedXml.Signature.KeyIdentifier = keyIdentifier;
     }
     if (generateTargettableSignature)
     {
         this.signedXml.Id = base.GenerateId();
     }
     this.effectiveSignatureParts = signatureParts;
     this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(defaultDigestAlgorithm);
 }
        public virtual XmlElement CreateWsspEncryptedPartsAssertion(MessagePartSpecification parts)
        {
            if (parts == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parts");
            }

            XmlElement result;

            if (parts.IsEmpty())
            {
                result = null;
            }
            else
            {
                result = CreateWsspAssertion(EncryptedPartsName);
                if (parts.IsBodyIncluded)
                {
                    result.AppendChild(CreateWsspAssertion(BodyName));
                }
                foreach (XmlQualifiedName header in parts.HeaderTypes)
                {
                    result.AppendChild(CreateWsspHeaderAssertion(header));
                }
            }
            return result;
        }
 private static MessagePartSpecification UnionMessagePartSpecifications(ScopedMessagePartSpecification actionParts)
 {
     MessagePartSpecification result = new MessagePartSpecification(false);
     foreach (string action in actionParts.Actions)
     {
         MessagePartSpecification parts;
         if (actionParts.TryGetParts(action, out parts))
         {
             if (parts.IsBodyIncluded)
             {
                 result.IsBodyIncluded = true;
             }
             foreach (XmlQualifiedName headerType in parts.HeaderTypes)
             {
                 if (!result.IsHeaderIncluded(headerType.Name, headerType.Namespace))
                 {
                     result.HeaderTypes.Add(headerType);
                 }
             }
         }
     }
     return result;
 }
        public virtual bool TryImportWsspSignedPartsAssertion(ICollection<XmlElement> assertions, out MessagePartSpecification parts, out XmlElement assertion)
        {
            if (TryImportWsspAssertion(assertions, SignedPartsName, out assertion))
            {
                parts = TryGetProtectedParts(assertion);
            }
            else
            {
                parts = null;
            }

            return parts != null;
        }
        internal static ChannelProtectionRequirements CreateFromContract(ContractDescription contract, ProtectionLevel defaultRequestProtectionLevel, ProtectionLevel defaultResponseProtectionLevel, bool isForClient)
        {
            if (contract == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contract"));

            ChannelProtectionRequirements requirements = new ChannelProtectionRequirements();

            ProtectionLevel contractScopeDefaultRequestProtectionLevel;
            ProtectionLevel contractScopeDefaultResponseProtectionLevel;
            if (contract.HasProtectionLevel)
            {
                contractScopeDefaultRequestProtectionLevel = contract.ProtectionLevel;
                contractScopeDefaultResponseProtectionLevel = contract.ProtectionLevel;
            }
            else
            {
                contractScopeDefaultRequestProtectionLevel = defaultRequestProtectionLevel;
                contractScopeDefaultResponseProtectionLevel = defaultResponseProtectionLevel;
            }

            foreach (OperationDescription operation in contract.Operations)
            {
                ProtectionLevel operationScopeDefaultRequestProtectionLevel;
                ProtectionLevel operationScopeDefaultResponseProtectionLevel;

                operationScopeDefaultRequestProtectionLevel = contractScopeDefaultRequestProtectionLevel;
                operationScopeDefaultResponseProtectionLevel = contractScopeDefaultResponseProtectionLevel;

                foreach (MessageDescription message in operation.Messages)
                {
                    ProtectionLevel messageScopeDefaultProtectionLevel;
                    if (message.HasProtectionLevel)
                    {
                        messageScopeDefaultProtectionLevel = message.ProtectionLevel;
                    }
                    else if (message.Direction == MessageDirection.Input)
                    {
                        messageScopeDefaultProtectionLevel = operationScopeDefaultRequestProtectionLevel;
                    }
                    else
                    {
                        messageScopeDefaultProtectionLevel = operationScopeDefaultResponseProtectionLevel;
                    }

                    MessagePartSpecification signedParts = new MessagePartSpecification();
                    MessagePartSpecification encryptedParts = new MessagePartSpecification();

                    // determine header protection requirements for message
                    foreach (MessageHeaderDescription header in message.Headers)
                    {
                        AddHeaderProtectionRequirements(header, signedParts, encryptedParts, messageScopeDefaultProtectionLevel);
                    }

                    // determine body protection requirements for message
                    ProtectionLevel bodyProtectionLevel;
                    if (message.Body.Parts.Count > 0)
                    {
                        // initialize the body protection level to none. all the body parts will be
                        // unioned to get the effective body protection level
                        bodyProtectionLevel = ProtectionLevel.None;
                    }
                    else if (message.Body.ReturnValue != null)
                    {
                        if (!(message.Body.ReturnValue.GetType().Equals(typeof(MessagePartDescription))))
                        {
                            Fx.Assert("Only body return values are supported currently");
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.OnlyBodyReturnValuesSupported));
                        }
                        MessagePartDescription desc = message.Body.ReturnValue;
                        bodyProtectionLevel = desc.HasProtectionLevel ? desc.ProtectionLevel : messageScopeDefaultProtectionLevel;
                    }
                    else
                    {
                        bodyProtectionLevel = messageScopeDefaultProtectionLevel;
                    }

                    // determine body protection requirements for message
                    if (message.Body.Parts.Count > 0)
                    {
                        foreach (MessagePartDescription body in message.Body.Parts)
                        {
                            ProtectionLevel partProtectionLevel = body.HasProtectionLevel ? body.ProtectionLevel : messageScopeDefaultProtectionLevel;
                            bodyProtectionLevel = ProtectionLevelHelper.Max(bodyProtectionLevel, partProtectionLevel);
                            if (bodyProtectionLevel == ProtectionLevel.EncryptAndSign)
                                break;
                        }
                    }
                    if (bodyProtectionLevel != ProtectionLevel.None)
                    {
                        signedParts.IsBodyIncluded = true;
                        if (bodyProtectionLevel == ProtectionLevel.EncryptAndSign)
                            encryptedParts.IsBodyIncluded = true;
                    }

                    // add requirements for message 
                    if (message.Direction == MessageDirection.Input)
                    {
                        requirements.IncomingSignatureParts.AddParts(signedParts, message.Action);
                        requirements.IncomingEncryptionParts.AddParts(encryptedParts, message.Action);
                    }
                    else
                    {
                        requirements.OutgoingSignatureParts.AddParts(signedParts, message.Action);
                        requirements.OutgoingEncryptionParts.AddParts(encryptedParts, message.Action);
                    }
                }
                if (operation.Faults != null)
                {
                    if (operation.IsServerInitiated())
                    {
                        AddFaultProtectionRequirements(operation.Faults, requirements, operationScopeDefaultRequestProtectionLevel, true);
                    }
                    else
                    {
                        AddFaultProtectionRequirements(operation.Faults, requirements, operationScopeDefaultResponseProtectionLevel, false);
                    }
                }
            }

            return requirements;
        }