Example #1
0
            public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver)
            {
                string secretType = reader.GetAttribute(XD.SecurityJan2004Dictionary.TypeAttribute, null);
                string id         = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
                bool   isNonce    = false;

                if (secretType != null && secretType.Length > 0)
                {
                    if (secretType == _parent.SerializerDictionary.NonceBinarySecret.Value || secretType == _otherDictionary.NonceBinarySecret.Value)
                    {
                        isNonce = true;
                    }
                    else if (secretType != _parent.SerializerDictionary.SymmetricKeyBinarySecret.Value && secretType != _otherDictionary.SymmetricKeyBinarySecret.Value)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(string.Format(SRServiceModel.UnexpectedBinarySecretType, _parent.SerializerDictionary.SymmetricKeyBinarySecret.Value, secretType)));
                    }
                }

                byte[] secret = reader.ReadElementContentAsBase64();
                if (isNonce)
                {
                    return(new NonceToken(id, secret));
                }
                else
                {
                    return(new BinarySecretSecurityToken(id, secret));
                }
            }
Example #2
0
        /// <summary>
        /// Overloads  the base class method to load the custom policies from the config file
        /// </summary>
        /// <param name="nodelist">XmlNodeList containing the policy information read from the config file</param>
        public override void LoadCustomConfiguration(XmlNodeList nodelist)
        {
            Expression <Func <ClaimsPrincipal, bool> > policyExpression;

            foreach (XmlNode node in nodelist)
            {
                //
                // Initialize the policy cache
                //
                XmlDictionaryReader rdr = XmlDictionaryReader.CreateDictionaryReader(new XmlTextReader(new StringReader(node.OuterXml)));
                rdr.MoveToContent();

                string resource = rdr.GetAttribute("resource");
                string action   = rdr.GetAttribute("action");

                policyExpression = _policyReader.ReadPolicy(rdr);

                //
                // Compile the policy expression into a function
                //
                Func <ClaimsPrincipal, bool> policy = policyExpression.Compile();

                //
                // Insert the policy function into the policy cache
                //
                _policies[new ResourceAction(resource, action)] = policy;
            }
        }
        static OleTxTransactionHeader ReadFrom(XmlDictionaryReader reader)
        {
            WsatExtendedInformation info = null;

            if (reader.IsStartElement(XD.OleTxTransactionExternalDictionary.OleTxTransaction,
                                      XD.OleTxTransactionExternalDictionary.Namespace))
            {
                string identifier = reader.GetAttribute(XD.CoordinationExternalDictionary.Identifier, CoordinationNamespace);

                if (!string.IsNullOrEmpty(identifier))
                {
                    // Verify identifier is really a URI
                    Uri uri;
                    if (!Uri.TryCreate(identifier, UriKind.Absolute, out uri))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidWsatExtendedInfo)));
                    }
                }

                string attr = reader.GetAttribute(XD.CoordinationExternalDictionary.Expires, CoordinationNamespace);

                uint timeout = 0;
                if (!string.IsNullOrEmpty(attr))
                {
                    try
                    {
                        timeout = XmlConvert.ToUInt32(attr);
                    }
                    catch (FormatException e)
                    {
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidWsatExtendedInfo), e));
                    }
                    catch (OverflowException e)
                    {
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.InvalidWsatExtendedInfo), e));
                    }
                }

                if (!string.IsNullOrEmpty(identifier) || timeout != 0)
                {
                    info = new WsatExtendedInformation(identifier, timeout);
                }
            }

            reader.ReadFullStartElement(XD.OleTxTransactionExternalDictionary.OleTxTransaction,
                                        XD.OleTxTransactionExternalDictionary.Namespace);

            byte[] propagationToken = ReadPropagationTokenElement(reader);

            // Skip extensibility elements...
            while (reader.IsStartElement())
            {
                reader.Skip();
            }
            reader.ReadEndElement();

            return(new OleTxTransactionHeader(propagationToken, info));
        }
Example #4
0
 public override bool CanReadClause(XmlDictionaryReader reader, string tokenType)
 {
     if (tokenType != null && tokenType != parent.SerializerDictionary.SecurityContextTokenType.Value)
     {
         return(false);
     }
     if (reader.IsStartElement(
             parent.SecurityTokenSerializer.DictionaryManager.SecurityJan2004Dictionary.Reference,
             parent.SecurityTokenSerializer.DictionaryManager.SecurityJan2004Dictionary.Namespace))
     {
         string valueType = reader.GetAttribute(parent.SecurityTokenSerializer.DictionaryManager.SecurityJan2004Dictionary.ValueType, null);
         if (valueType != null && valueType != parent.SerializerDictionary.SecurityContextTokenReferenceValueType.Value)
         {
             return(false);
         }
         string uri = reader.GetAttribute(parent.SecurityTokenSerializer.DictionaryManager.SecurityJan2004Dictionary.URI, null);
         if (uri != null)
         {
             if (uri.Length > 0 && uri[0] != '#')
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Example #5
0
 public void ReadFrom(XmlDictionaryReader reader, long maxBufferSize)
 {
     this.ValidateReadState();
     reader.MoveToStartElement(this.OpeningElementName, NamespaceUri);
     this.encoding = reader.GetAttribute(EncodingAttribute, null);
     this.id       = reader.GetAttribute(System.ServiceModel.XD.XmlEncryptionDictionary.Id, null) ?? System.ServiceModel.Security.SecurityUniqueId.Create().Value;
     this.wsuId    = reader.GetAttribute(System.ServiceModel.XD.XmlEncryptionDictionary.Id, System.ServiceModel.XD.UtilityDictionary.Namespace) ?? System.ServiceModel.Security.SecurityUniqueId.Create().Value;
     this.mimeType = reader.GetAttribute(MimeTypeAttribute, null);
     this.type     = reader.GetAttribute(TypeAttribute, null);
     this.ReadAdditionalAttributes(reader);
     reader.Read();
     if (reader.IsStartElement(EncryptionMethodElement.ElementName, NamespaceUri))
     {
         this.encryptionMethod.ReadFrom(reader);
     }
     if (this.tokenSerializer.CanReadKeyIdentifier(reader))
     {
         this.KeyIdentifier = this.tokenSerializer.ReadKeyIdentifier(reader);
     }
     reader.ReadStartElement(CipherDataElementName, NamespaceUri);
     reader.ReadStartElement(CipherValueElementName, NamespaceUri);
     if (maxBufferSize == 0L)
     {
         this.ReadCipherData(reader);
     }
     else
     {
         this.ReadCipherData(reader, maxBufferSize);
     }
     reader.ReadEndElement();
     reader.ReadEndElement();
     this.ReadAdditionalElements(reader);
     reader.ReadEndElement();
     this.State = EncryptionState.Read;
 }
Example #6
0
        static IIdentity DeserializePrimaryIdentity(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer)
        {
            IIdentity identity = null;

            if (reader.IsStartElement(dictionary.PrimaryIdentity, dictionary.EmptyString))
            {
                reader.ReadStartElement();
                if (reader.IsStartElement(dictionary.WindowsSidIdentity, dictionary.EmptyString))
                {
                    SecurityIdentifier sid = ReadSidAttribute(reader, dictionary);
                    string             authenticationType = reader.GetAttribute(dictionary.AuthenticationType, dictionary.EmptyString);
                    reader.ReadStartElement();
                    string name = reader.ReadContentAsString();
                    identity = new WindowsSidIdentity(sid, name, authenticationType ?? String.Empty);
                    reader.ReadEndElement();
                }
                else if (reader.IsStartElement(dictionary.GenericIdentity, dictionary.EmptyString))
                {
                    string authenticationType = reader.GetAttribute(dictionary.AuthenticationType, dictionary.EmptyString);
                    reader.ReadStartElement();
                    string name = reader.ReadContentAsString();
                    identity = SecurityUtils.CreateIdentity(name, authenticationType ?? String.Empty);
                    reader.ReadEndElement();
                }
                else
                {
                    identity = (IIdentity)serializer.ReadObject(reader);
                }
                reader.ReadEndElement();
            }
            return(identity);
        }
Example #7
0
 public void ReadFrom(XmlDictionaryReader reader, long maxBufferSize)
 {
     this.ValidateReadState();
     reader.MoveToStartElement(this.OpeningElementName, EncryptedType.NamespaceUri);
     this.encoding = reader.GetAttribute(EncryptedType.EncodingAttribute, (XmlDictionaryString)null);
     this.id       = reader.GetAttribute(System.IdentityModel.XD.XmlEncryptionDictionary.Id, (XmlDictionaryString)null) ?? SecurityUniqueId.Create().Value;
     this.wsuId    = reader.GetAttribute(System.IdentityModel.XD.XmlEncryptionDictionary.Id, System.IdentityModel.XD.UtilityDictionary.Namespace) ?? SecurityUniqueId.Create().Value;
     this.mimeType = reader.GetAttribute(EncryptedType.MimeTypeAttribute, (XmlDictionaryString)null);
     this.type     = reader.GetAttribute(EncryptedType.TypeAttribute, (XmlDictionaryString)null);
     this.ReadAdditionalAttributes(reader);
     reader.Read();
     if (reader.IsStartElement(EncryptedType.EncryptionMethodElement.ElementName, EncryptedType.NamespaceUri))
     {
         this.encryptionMethod.ReadFrom(reader);
     }
     if (this.tokenSerializer.CanReadKeyIdentifier((XmlReader)reader))
     {
         XmlElement          xmlElement = (XmlElement)null;
         XmlDictionaryReader dictionaryReader;
         if (this.ShouldReadXmlReferenceKeyInfoClause)
         {
             xmlElement       = new XmlDocument().ReadNode((XmlReader)reader) as XmlElement;
             dictionaryReader = XmlDictionaryReader.CreateDictionaryReader((XmlReader) new XmlNodeReader((XmlNode)xmlElement));
         }
         else
         {
             dictionaryReader = reader;
         }
         try
         {
             this.KeyIdentifier = this.tokenSerializer.ReadKeyIdentifier((XmlReader)dictionaryReader);
         }
         catch (Exception ex)
         {
             if (Fx.IsFatal(ex) || !this.ShouldReadXmlReferenceKeyInfoClause)
             {
                 throw;
             }
             else
             {
                 this.keyIdentifier = this.ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader.CreateDictionaryReader((XmlReader) new XmlNodeReader((XmlNode)xmlElement)), ex);
             }
         }
     }
     reader.ReadStartElement(EncryptedType.CipherDataElementName, EncryptedType.NamespaceUri);
     reader.ReadStartElement(EncryptedType.CipherValueElementName, EncryptedType.NamespaceUri);
     if (maxBufferSize == 0L)
     {
         this.ReadCipherData(reader);
     }
     else
     {
         this.ReadCipherData(reader, maxBufferSize);
     }
     reader.ReadEndElement();
     reader.ReadEndElement();
     this.ReadAdditionalElements(reader);
     reader.ReadEndElement();
     this.State = EncryptedType.EncryptionState.Read;
 }
Example #8
0
        public override void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
        {
            XmlDictionaryString localName = this.isCanonicalizationMethod ? dictionaryManager.XmlSignatureDictionary.CanonicalizationMethod : dictionaryManager.XmlSignatureDictionary.Transform;

            reader.MoveToStartElement(localName, dictionaryManager.XmlSignatureDictionary.Namespace);
            this.prefix = reader.Prefix;
            bool isEmptyElement = reader.IsEmptyElement;

            if (reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null) != this.Algorithm)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("AlgorithmMismatchForTransform")));
            }
            reader.Read();
            reader.MoveToContent();
            if (!isEmptyElement)
            {
                if (reader.IsStartElement(dictionaryManager.ExclusiveC14NDictionary.InclusiveNamespaces, dictionaryManager.ExclusiveC14NDictionary.Namespace))
                {
                    reader.MoveToStartElement(dictionaryManager.ExclusiveC14NDictionary.InclusiveNamespaces, dictionaryManager.ExclusiveC14NDictionary.Namespace);
                    this.inclusiveListElementPrefix = reader.Prefix;
                    bool flag2 = reader.IsEmptyElement;
                    this.InclusiveNamespacesPrefixList = reader.GetAttribute(dictionaryManager.ExclusiveC14NDictionary.PrefixList, null);
                    reader.Read();
                    if (!flag2)
                    {
                        reader.ReadEndElement();
                    }
                }
                reader.MoveToContent();
                reader.ReadEndElement();
            }
        }
Example #9
0
        public virtual void ReadXml(XmlDictionaryReader reader,
                                    SamlSerializer samlSerializer,
                                    SecurityTokenSerializer keyInfoTokenSerializer,
                                    SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (samlSerializer == null)
            {
                throw new ArgumentNullException("samlSerializer");
            }

            reader.ReadStartElement("Subject", SamlConstants.Namespace);
            NameFormat    = reader.GetAttribute("Format");
            NameQualifier = reader.GetAttribute("NameQualifier");
            Name          = reader.ReadElementContentAsString("NameIdentifier", SamlConstants.Namespace);
            reader.ReadEndElement();

            if (Name == null || Name.Length == 0)
            {
                throw new SecurityTokenException("non-zero length string must be exist for Name.");
            }
        }
        /// <summary>
        /// Loads the policies from config file
        /// </summary>
        static void LoadPolicies(XmlNodeList nodes)
        {
            Expression <Func <IClaimsPrincipal, bool> > policyExpression;

            foreach (XmlNode node in nodes)
            {
                //
                // Initialize the policy cache
                //
                XmlDictionaryReader rdr = XmlDictionaryReader.CreateDictionaryReader(new XmlTextReader(new StringReader(node.OuterXml)));
                rdr.MoveToContent();

                string resource = rdr.GetAttribute("resource");
                string action   = rdr.GetAttribute("action");

                Console.WriteLine("Loading policy for Resource:{0}, Action:{1}", resource, action);

                policyExpression = _policyReader.ReadPolicy(rdr);

                //
                // Compile the policy expression into a function
                //
                Func <IClaimsPrincipal, bool> policy = policyExpression.Compile();

                //
                // Insert the policy function into the policy cache
                //
                _policies[new ResourceAction(resource, action)] = policy;
            }
        }
Example #11
0
        public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            string str2;
            string str3;

            if (reader == null)
            {
                throw System.IdentityModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }
            if (samlSerializer == null)
            {
                throw System.IdentityModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }
            SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
            string         attribute      = reader.GetAttribute(samlDictionary.AuthorityKind, null);

            if (string.IsNullOrEmpty(attribute))
            {
                throw System.IdentityModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorityBindingMissingAuthorityKindOnRead")));
            }
            string[] strArray = attribute.Split(new char[] { ':' });
            if (strArray.Length > 2)
            {
                throw System.IdentityModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorityBindingInvalidAuthorityKind")));
            }
            if (strArray.Length == 2)
            {
                str3 = strArray[0];
                str2 = strArray[1];
            }
            else
            {
                str3 = string.Empty;
                str2 = strArray[0];
            }
            string ns = reader.LookupNamespace(str3);

            this.authorityKind = new XmlQualifiedName(str2, ns);
            this.binding       = reader.GetAttribute(samlDictionary.Binding, null);
            if (string.IsNullOrEmpty(this.binding))
            {
                throw System.IdentityModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorityBindingMissingBindingOnRead")));
            }
            this.location = reader.GetAttribute(samlDictionary.Location, null);
            if (string.IsNullOrEmpty(this.location))
            {
                throw System.IdentityModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorityBindingMissingLocationOnRead")));
            }
            if (reader.IsEmptyElement)
            {
                reader.MoveToContent();
                reader.Read();
            }
            else
            {
                reader.MoveToContent();
                reader.Read();
                reader.ReadEndElement();
            }
        }
Example #12
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);
            }
        }
Example #13
0
        /// <summary>
        /// Read the claim node
        /// </summary>
        /// <param name="rdr">XmlDictionaryReader of the policy Xml</param>
        /// <returns>A LINQ expression created from the claim node</returns>
        private Expression <Func <ClaimsPrincipal, bool> > ReadClaim(XmlDictionaryReader rdr)
        {
            string claimType  = rdr.GetAttribute("claimType");
            string claimValue = rdr.GetAttribute("claimValue");
            Expression <Func <ClaimsPrincipal, bool> > hasClaim = (icp) => HasClaim(icp, claimType, claimValue);

            rdr.Read();
            return(hasClaim);
        }
Example #14
0
        public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));

            if (samlSerializer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));

            #pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            string authKind = reader.GetAttribute(dictionary.AuthorityKind, null);
            if (string.IsNullOrEmpty(authKind))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorityBindingMissingAuthorityKindOnRead)));

            string[] authKindParts = authKind.Split(':');
            if (authKindParts.Length > 2)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorityBindingInvalidAuthorityKind)));

            string localName;
            string prefix;
            string nameSpace;
            if (authKindParts.Length == 2)
            {
                prefix = authKindParts[0];
                localName = authKindParts[1];
            }
            else
            {
                prefix = String.Empty;
                localName = authKindParts[0];
            }

            nameSpace = reader.LookupNamespace(prefix);

            this.authorityKind = new XmlQualifiedName(localName, nameSpace);

            this.binding = reader.GetAttribute(dictionary.Binding, null);
            if (string.IsNullOrEmpty(this.binding))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorityBindingMissingBindingOnRead)));

            this.location = reader.GetAttribute(dictionary.Location, null);
            if (string.IsNullOrEmpty(this.location))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorityBindingMissingLocationOnRead)));

            if (reader.IsEmptyElement)
            {
                reader.MoveToContent();
                reader.Read();
            }
            else
            {
                reader.MoveToContent();
                reader.Read();
                reader.ReadEndElement();
            }
        }
Example #15
0
        /// <summary>
        /// Reads the X.509 Security token referenced by the XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader pointing to a X.509 Security token.</param>
        /// <returns>An instance of <see cref="X509SecurityToken"/>.</returns>
        /// <exception cref="ArgumentNullException">The parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">XmlReader is not pointing to an valid X509SecurityToken as
        /// defined in WS-Security X.509 Token Profile. Or the encodingType specified is other than Base64
        /// or HexBinary.</exception>
        public override SecurityToken ReadToken(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            XmlDictionaryReader dicReader = XmlDictionaryReader.CreateDictionaryReader(reader);

            if (!dicReader.IsStartElement(WSSecurity10Constants.Elements.BinarySecurityToken, WSSecurity10Constants.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new XmlException(
                              SR.GetString(
                                  SR.ID4065,
                                  WSSecurity10Constants.Elements.BinarySecurityToken,
                                  WSSecurity10Constants.Namespace,
                                  dicReader.LocalName,
                                  dicReader.NamespaceURI)));
            }

            string valueTypeUri = dicReader.GetAttribute(WSSecurity10Constants.Attributes.ValueType, null);

            if (!StringComparer.Ordinal.Equals(valueTypeUri, WSSecurity10Constants.X509TokenType))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new XmlException(
                              SR.GetString(
                                  SR.ID4066,
                                  WSSecurity10Constants.Elements.BinarySecurityToken,
                                  WSSecurity10Constants.Namespace,
                                  WSSecurity10Constants.Attributes.ValueType,
                                  WSSecurity10Constants.X509TokenType,
                                  valueTypeUri)));
            }

            string wsuId    = dicReader.GetAttribute(WSSecurityUtilityConstants.Attributes.Id, WSSecurityUtilityConstants.Namespace);
            string encoding = dicReader.GetAttribute(WSSecurity10Constants.Attributes.EncodingType, null);

            byte[] binaryData;
            if (encoding == null || StringComparer.Ordinal.Equals(encoding, WSSecurity10Constants.Base64EncodingType))
            {
                binaryData = dicReader.ReadElementContentAsBase64();
            }
            else if (StringComparer.Ordinal.Equals(encoding, WSSecurity10Constants.HexBinaryEncodingType))
            {
                binaryData = SoapHexBinary.Parse(dicReader.ReadElementContentAsString()).Value;
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4068)));
            }

            return(String.IsNullOrEmpty(wsuId) ?
                   new X509SecurityToken(new X509Certificate2(binaryData)) :
                   new X509SecurityToken(new X509Certificate2(binaryData), wsuId));
        }
        public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }

            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            string time = reader.GetAttribute(dictionary.NotBefore, null);
            if (!string.IsNullOrEmpty(time))
            {
                this.notBefore = DateTime.ParseExact(
                    time, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }

            time = reader.GetAttribute(dictionary.NotOnOrAfter, null);
            if (!string.IsNullOrEmpty(time))
            {
                this.notOnOrAfter = DateTime.ParseExact(
                    time, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }

            // Saml Conditions element is an optional element and all its child element
            // are optional as well. So we can have a empty <saml:Conditions /> element
            // in a valid Saml token.
            if (reader.IsEmptyElement)
            {
                // Just issue a read to read the Empty element.
                reader.MoveToContent();
                reader.Read();
                return;
            }

            reader.MoveToContent();
            reader.Read();
            while (reader.IsStartElement())
            {
                SamlCondition condition = samlSerializer.LoadCondition(reader, keyInfoSerializer, outOfBandTokenResolver);
                if (condition == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadCondtion)));
                }
                this.conditions.Add(condition);
            }
            reader.MoveToContent();
            reader.ReadEndElement();
        }
        public override void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager, bool preserveComments)
        {
            XmlDictionaryString elementName = this.isCanonicalizationMethod ?
                                              dictionaryManager.XmlSignatureDictionary.CanonicalizationMethod : dictionaryManager.XmlSignatureDictionary.Transform;

            reader.MoveToStartElement(elementName, dictionaryManager.XmlSignatureDictionary.Namespace);
            this.prefix = reader.Prefix;
            bool isEmptyElement = reader.IsEmptyElement;

            algorithm = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null);
            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.ID0001, dictionaryManager.XmlSignatureDictionary.Algorithm, reader.LocalName)));
            }

            if (algorithm == dictionaryManager.SecurityAlgorithmDictionary.ExclusiveC14nWithComments.Value)
            {
                // to include comments in canonicalization, two conditions need to be met
                // 1. the Reference must be an xpointer.
                // 2. the transform must be #withComments
                includeComments = preserveComments && true;
            }
            else if (algorithm == dictionaryManager.SecurityAlgorithmDictionary.ExclusiveC14n.Value)
            {
                includeComments = false;
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.ID6005, algorithm)));
            }

            reader.Read();
            reader.MoveToContent();

            if (!isEmptyElement)
            {
                if (reader.IsStartElement(dictionaryManager.ExclusiveC14NDictionary.InclusiveNamespaces, dictionaryManager.ExclusiveC14NDictionary.Namespace))
                {
                    reader.MoveToStartElement(dictionaryManager.ExclusiveC14NDictionary.InclusiveNamespaces, dictionaryManager.ExclusiveC14NDictionary.Namespace);
                    this.inclusiveListElementPrefix = reader.Prefix;
                    bool emptyElement = reader.IsEmptyElement;
                    // We treat PrefixList as optional Attribute.
                    this.InclusiveNamespacesPrefixList = reader.GetAttribute(dictionaryManager.ExclusiveC14NDictionary.PrefixList, null);
                    reader.Read();
                    if (!emptyElement)
                    {
                        reader.ReadEndElement();
                    }
                }
                reader.MoveToContent();
                reader.ReadEndElement(); // Transform
            }
        }
        public static void Deserialize(XmlDictionaryReader reader, out IList <DirectoryControl> controls, bool mustBePresent, bool fullChecks)
        {
            string str  = null;
            string str1 = null;
            bool   flag;

            byte[] numArray = null;
            controls = new List <DirectoryControl>();
            if (mustBePresent || reader.IsStartElement("controls", "http://schemas.microsoft.com/2008/1/ActiveDirectory"))
            {
                reader.ReadFullStartElement("controls", "http://schemas.microsoft.com/2008/1/ActiveDirectory");
                while (reader.IsStartElement("control", "http://schemas.microsoft.com/2008/1/ActiveDirectory"))
                {
                    string attribute  = reader.GetAttribute("type");
                    string attribute1 = reader.GetAttribute("criticality");
                    reader.Read();
                    if (!reader.IsStartElement("controlValue", "http://schemas.microsoft.com/2008/1/ActiveDirectory"))
                    {
                        numArray = null;
                    }
                    else
                    {
                        string attribute2 = reader.GetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance");
                        if (attribute2 != null)
                        {
                            XmlUtility.SplitPrefix(attribute2, out str, out str1);
                            numArray = reader.ReadElementContentAsBase64();
                        }
                        else
                        {
                            throw new ArgumentException();
                        }
                    }
                    if (!string.Equals("true", attribute1))
                    {
                        flag = false;
                    }
                    else
                    {
                        flag = true;
                    }
                    DirectoryControl directoryControl = new DirectoryControl(attribute, numArray, flag, true);
                    controls.Add(directoryControl);
                    reader.Read();
                }
                return;
            }
            else
            {
                return;
            }
        }
        public override void LoadCustomConfiguration(System.Xml.XmlNodeList nodelist)
        {
            foreach (XmlNode node in nodelist)
            {
                XmlDictionaryReader rdr = XmlDictionaryReader.CreateDictionaryReader(new XmlTextReader(new StringReader(node.OuterXml)));
                rdr.MoveToContent();

                string symmetricKey = rdr.GetAttribute("symmetricKey");
                string audience     = rdr.GetAttribute("audience");

                this.AddAudienceKeyPair(audience, symmetricKey);
            }
        }
Example #20
0
            public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlDictionaryReader reader)
            {
                byte[] nonce  = null;
                int    length = 0;

                if (reader.IsStartElement(XD.SecurityJan2004Dictionary.SecurityTokenReference, NamespaceUri))
                {
                    string nonceString = reader.GetAttribute(XD.SecureConversationFeb2005Dictionary.Nonce, XD.SecureConversationFeb2005Dictionary.Namespace);
                    if (nonceString != null)
                    {
                        nonce = Convert.FromBase64String(nonceString);
                    }

                    string lengthString = reader.GetAttribute(XD.SecureConversationFeb2005Dictionary.Length, XD.SecureConversationFeb2005Dictionary.Namespace);
                    if (lengthString != null)
                    {
                        length = Convert.ToInt32(lengthString, CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        length = DefaultDerivedKeyLength;
                    }
                }
                string tokenType = ReadTokenType(reader);
                string strId     = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);

                reader.ReadStartElement(XD.SecurityJan2004Dictionary.SecurityTokenReference, NamespaceUri);
                SecurityKeyIdentifierClause clause = null;

                for (int i = 0; i < this.strEntries.Count; ++i)
                {
                    if (this.strEntries[i].CanReadClause(reader, tokenType))
                    {
                        clause = this.strEntries[i].ReadClause(reader, nonce, length, tokenType);
                        break;
                    }
                }

                if (clause == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.CannotReadKeyIdentifierClause, reader.LocalName, reader.NamespaceURI)));
                }

                if (!string.IsNullOrEmpty(strId))
                {
                    clause.Id = strId;
                }

                reader.ReadEndElement();
                return(clause);
            }
        /// <summary>
        /// Reads an "EncryptedType" xmlfragment
        /// </summary>
        /// <remarks>Assumes that the reader is positioned on an "EncryptedData" or "EncryptedKey" element.
        /// Both of these elements extend EncryptedType</remarks>
        public virtual void ReadXml(XmlDictionaryReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            reader.MoveToContent();

            _id       = reader.GetAttribute(XmlEncryptionConstants.Attributes.Id, null);
            _type     = reader.GetAttribute(XmlEncryptionConstants.Attributes.Type, null);
            _mimeType = reader.GetAttribute(XmlEncryptionConstants.Attributes.MimeType, null);
            _encoding = reader.GetAttribute(XmlEncryptionConstants.Attributes.Encoding, null);

            reader.ReadStartElement();
            reader.MoveToContent();

            // <EncryptedMethod>? 0 - 1
            if (reader.IsStartElement(XmlEncryptionConstants.Elements.EncryptionMethod, XmlEncryptionConstants.Namespace))
            {
                _encryptionMethod.ReadXml(reader);
            }

            // <KeyInfo>? 0 - 1
            reader.MoveToContent();
            if (reader.IsStartElement(XD.XmlSignatureDictionary.KeyInfo.Value, XD.XmlSignatureDictionary.Namespace.Value))
            {
                _keyInfo = new KeyInfo(_keyInfoSerializer);

                // if there is a keyInfo, we need to reset the default which is
                // contains a single EmptyKeyInfoClause
                if (_keyInfoSerializer.CanReadKeyIdentifier(reader))
                {
                    _keyInfo.KeyIdentifier = _keyInfoSerializer.ReadKeyIdentifier(reader);
                }
                else
                {
                    _keyInfo.ReadXml(reader);
                }
            }

            // <CipherData> 1
            reader.MoveToContent();
            _cipherData.ReadXml(reader);

            ReadExtensions(reader);

            // should be on EndElement for the extended type.
            reader.MoveToContent();
            reader.ReadEndElement();
        }
Example #22
0
        public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }

            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            this.name = reader.GetAttribute(dictionary.AttributeName, null);
            if (string.IsNullOrEmpty(this.name))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeMissingNameAttributeOnRead)));
            }

            this.nameSpace = reader.GetAttribute(dictionary.AttributeNamespace, null);
            if (string.IsNullOrEmpty(this.nameSpace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeMissingNamespaceAttributeOnRead)));
            }

            this.claimType = string.IsNullOrEmpty(this.nameSpace) ? this.name : this.nameSpace + "/" + this.name;

            reader.MoveToContent();
            reader.Read();
            while (reader.IsStartElement(dictionary.AttributeValue, dictionary.Namespace))
            {
                // We will load all Attributes as a string value by default.
                string attrValue = reader.ReadString();
                this.attributeValues.Add(attrValue);

                reader.MoveToContent();
                reader.ReadEndElement();
            }

            if (this.attributeValues.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeShouldHaveOneValue)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();
        }
Example #23
0
        /// <summary>
        /// Reads a serialized token and converts it into a <see cref="SecurityToken"/>.
        /// </summary>
        /// <param name="reader">An XML reader positioned at the token's start element.</param>
        /// <returns>The parsed form of the token.</returns>
        public override SecurityToken ReadToken(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);

            byte[] binaryData;
            string encoding = dictionaryReader.GetAttribute(EncodingType);

            if (encoding == null || encoding == Base64EncodingType)
            {
                dictionaryReader.Read();
                binaryData = dictionaryReader.ReadContentAsBase64();
            }
            else
            {
                throw new SecurityTokenException(
                          "Cannot read SecurityToken as its encoding is" + encoding + ". Expected a BinarySecurityToken with base64 encoding.");
            }

            string serializedToken = Encoding.UTF8.GetString(binaryData);

            return(ReadSecurityTokenFromString(serializedToken));
        }
Example #24
0
 void AssertNode(int depth, string localName, XmlNodeType nodeType, string value, string type, XmlDictionaryReader reader, string label)
 {
     Assert.AreEqual(localName, reader.LocalName, label + ".LocalName");
     Assert.AreEqual(nodeType, reader.NodeType, label + ".NodeType");
     Assert.AreEqual(value, reader.Value, label + ".Value");
     Assert.AreEqual(type, reader.GetAttribute("type"), label + ".GetAttribute('type')");
 }
Example #25
0
        static FaultReason ReadFaultReason12(XmlDictionaryReader r, string ns)
        {
            List <FaultReasonText> l = new List <FaultReasonText> ();

            if (r.IsEmptyElement)
            {
                throw new ArgumentException("One or more Text element is mandatory in SOAP fault reason text.");
            }

            r.ReadStartElement("Reason", ns);
            for (r.MoveToContent();
                 r.NodeType != XmlNodeType.EndElement;
                 r.MoveToContent())
            {
                string lang = r.GetAttribute("lang", "http://www.w3.org/XML/1998/namespace");
                if (lang == null)
                {
                    throw new XmlException("xml:lang is mandatory on fault reason Text");
                }
                l.Add(new FaultReasonText(r.ReadElementContentAsString("Text", ns), lang));
            }
            r.ReadEndElement();

            return(new FaultReason(l));
        }
Example #26
0
        private SecurityKeyIdentifier ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader localReader, Exception previousException)
        {
            if (!localReader.IsStartElement(System.IdentityModel.XD.XmlSignatureDictionary.KeyInfo, System.IdentityModel.XD.XmlSignatureDictionary.Namespace))
            {
                return((SecurityKeyIdentifier)null);
            }
            localReader.ReadStartElement(System.IdentityModel.XD.XmlSignatureDictionary.KeyInfo, System.IdentityModel.XD.XmlSignatureDictionary.Namespace);
            SecurityKeyIdentifier securityKeyIdentifier = new SecurityKeyIdentifier();

            if (localReader.IsStartElement())
            {
#if FEATURE_CORECLR
                throw new NotImplementedException("GenericXmlSecurityKeyIdentifierClause not supported");
#else
                string attribute = localReader.GetAttribute(System.IdentityModel.XD.UtilityDictionary.IdAttribute, System.IdentityModel.XD.UtilityDictionary.Namespace);
                SecurityKeyIdentifierClause clause = (SecurityKeyIdentifierClause) new GenericXmlSecurityKeyIdentifierClause(new XmlDocument().ReadNode((XmlReader)localReader) as XmlElement);
                if (!string.IsNullOrEmpty(attribute))
                {
                    clause.Id = attribute;
                }
                securityKeyIdentifier.Add(clause);
#endif
            }
            if (securityKeyIdentifier.Count == 0)
            {
                throw previousException;
            }
            localReader.ReadEndElement();
            return(securityKeyIdentifier);
        }
Example #27
0
        void CacheAllHeaderIds()
        {
            int crtHeaderPosition      = 0;
            XmlDictionaryReader reader = this.Message.Headers.GetReaderAtHeader(0);

            while (crtHeaderPosition < this.Message.Headers.Count)
            {
                if (reader.NodeType != XmlNodeType.Element)
                {
                    reader.MoveToContent();
                }

                reader.MoveToStartElement();

                if (crtHeaderPosition != this.headerIndex)
                {
                    // Look if the header has an d:Id attribute.
                    // The headers's children are not of interest, because
                    // only top-level SOAP header blocks (/s:Envelope/s:Header/*) can be referenced.
                    string idValue = reader.GetAttribute(ProtocolStrings.IdAttributeName, this.DiscoveryInfo.DiscoveryNamespace);
                    if (!String.IsNullOrEmpty(idValue))
                    {
                        this.blockIds.AddHeader(idValue, crtHeaderPosition);
                    }
                }

                reader.Skip();
                crtHeaderPosition++;
            }

            reader.Close();
        }
Example #28
0
        private SecurityKeyIdentifier ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader localReader, Exception previousException)
        {
            if (!localReader.IsStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace))
            {
                return(null);
            }

            localReader.ReadStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace);
            SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier();

            if (localReader.IsStartElement())
            {
                SecurityKeyIdentifierClause clause = null;
                string      strId = localReader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
                XmlDocument doc   = new XmlDocument();
                XmlElement  keyIdentifierReferenceXml = (doc.ReadNode(localReader) as XmlElement);
                clause = new GenericXmlSecurityKeyIdentifierClause(keyIdentifierReferenceXml);
                if (!string.IsNullOrEmpty(strId))
                {
                    clause.Id = strId;
                }
                keyIdentifier.Add(clause);
            }

            if (keyIdentifier.Count == 0)
            {
                throw previousException;
            }

            localReader.ReadEndElement();
            return(keyIdentifier);
        }
Example #29
0
            public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType)
            {
                string encodingType = reader.GetAttribute(XD.SecurityJan2004Dictionary.EncodingType, null);

                if (encodingType == null)
                {
                    encodingType = DefaultEncodingType;
                }

                reader.ReadStartElement();

                byte[] bytes;
                if (encodingType == EncodingTypeValueBase64Binary)
                {
                    bytes = reader.ReadContentAsBase64();
                }
                else if (encodingType == EncodingTypeValueHexBinary)
                {
                    bytes = HexBinary.Parse(reader.ReadContentAsString()).Value;
                }
                else if (encodingType == EncodingTypeValueText)
                {
                    bytes = new UTF8Encoding().GetBytes(reader.ReadContentAsString());
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityMessageSerializationException(SR.GetString(SR.UnknownEncodingInKeyIdentifier)));
                }

                reader.ReadEndElement();

                return(CreateClause(bytes, derivationNonce, derivationLength));
            }
Example #30
0
            public override string ExtractId(XmlDictionaryReader reader)
            {
                if (reader == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
                }

                if (reader.IsStartElement(ElementName, XD.XmlEncryptionDictionary.Namespace))
                {
                    return(reader.GetAttribute(XD.XmlEncryptionDictionary.Id, null));
                }
                else
                {
                    return(reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace));
                }
            }