public void WriteBodyToSignThenEncryptWithFragments(Stream stream, bool includeComments, string[] inclusivePrefixes, EncryptedData encryptedData, SymmetricAlgorithm algorithm, XmlDictionaryWriter writer) { int num; IFragmentCapableXmlDictionaryWriter writer2 = (IFragmentCapableXmlDictionaryWriter)writer; this.SetBodyId(); encryptedData.Id = this.securityHeader.GenerateId(); this.startBodyFragment = new MemoryStream(); BufferedOutputStream stream2 = new BufferManagerOutputStream("XmlBufferQuotaExceeded", 0x400, 0x7fffffff, BufferManager.CreateBufferManager(0L, 0x7fffffff)); this.endBodyFragment = new MemoryStream(); writer.StartCanonicalization(stream, includeComments, inclusivePrefixes); writer2.StartFragment(this.startBodyFragment, false); this.WriteStartInnerMessageWithId(writer); writer2.EndFragment(); writer2.StartFragment(stream2, true); base.InnerMessage.WriteBodyContents(writer); writer2.EndFragment(); writer2.StartFragment(this.endBodyFragment, false); writer.WriteEndElement(); writer2.EndFragment(); writer.EndCanonicalization(); byte[] array = stream2.ToArray(out num); encryptedData.SetUpEncryption(algorithm, new ArraySegment <byte>(array, 0, num)); this.encryptedBodyContent = encryptedData; this.state = BodyState.SignedThenEncrypted; }
public byte[] CanonicalizeUsingDictionaryWriter(XmlReader reader) { _canonicalWriterStream.Seek(0, SeekOrigin.Begin); _canonicalWriterStream.SetLength(0); MemoryStream writerStream = new MemoryStream(); XmlDictionaryWriter dicWriter = XmlDictionaryWriter.CreateTextWriter(writerStream); dicWriter.WriteStartElement("Foo"); if (_tokenizedInclusivePrefixes != null) { // Populate the Canonicalizer with prefix that are already read in // by the reader. foreach (string inclusivePrefix in _tokenizedInclusivePrefixes) { string ns = reader.LookupNamespace(inclusivePrefix); if (ns != null) { dicWriter.WriteXmlnsAttribute(inclusivePrefix, ns); } } } dicWriter.StartCanonicalization(_canonicalWriterStream, _includeComments, _tokenizedInclusivePrefixes); reader.MoveToContent(); dicWriter.WriteNode(reader, false); dicWriter.EndCanonicalization(); dicWriter.WriteEndElement(); return(_canonicalWriterStream.ToArray()); }
public void WriteBodyToEncryptThenSign(Stream canonicalStream, EncryptedData encryptedData, SymmetricAlgorithm algorithm) { encryptedData.Id = this.securityHeader.GenerateId(); this.SetBodyId(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null); writer.WriteStartElement("a"); MemoryStream stream = new MemoryStream(); ((IFragmentCapableXmlDictionaryWriter)writer).StartFragment(stream, true); base.InnerMessage.WriteBodyContents(writer); ((IFragmentCapableXmlDictionaryWriter)writer).EndFragment(); writer.WriteEndElement(); stream.Flush(); encryptedData.SetUpEncryption(algorithm, new ArraySegment <byte>(stream.GetBuffer(), 0, (int)stream.Length)); this.fullBodyBuffer = new XmlBuffer(0x7fffffff); XmlDictionaryWriter writer2 = this.fullBodyBuffer.OpenSection(XmlDictionaryReaderQuotas.Max); writer2.StartCanonicalization(canonicalStream, false, null); this.WriteStartInnerMessageWithId(writer2); encryptedData.WriteTo(writer2, ServiceModelDictionaryManager.Instance); writer2.WriteEndElement(); writer2.EndCanonicalization(); writer2.Flush(); this.fullBodyBuffer.CloseSection(); this.fullBodyBuffer.Close(); this.state = BodyState.EncryptedThenSigned; }
// Given a token and useStarTransform value this method adds apporopriate reference accordingly. // 1. If strTransform is disabled, it adds a reference to the token's id. // 2. Else if strtransform is enabled it adds a reference the security token's keyIdentifier's id. void AddTokenSignatureReference(SecurityToken token, SecurityKeyIdentifierClause keyIdentifierClause, bool strTransformEnabled) { if (!strTransformEnabled && token.Id == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.ElementToSignMustHaveId)), this.Message); } HashStream hashStream = TakeHashStream(); XmlDictionaryWriter utf8Writer = TakeUtf8Writer(); utf8Writer.StartCanonicalization(hashStream, false, null); this.StandardsManager.SecurityTokenSerializer.WriteToken(utf8Writer, token); utf8Writer.EndCanonicalization(); if (strTransformEnabled) { if (keyIdentifierClause != null) { if (String.IsNullOrEmpty(keyIdentifierClause.Id)) { keyIdentifierClause.Id = SecurityUniqueId.Create().Value; } this.ElementContainer.MapSecurityTokenToStrClause(token, keyIdentifierClause); this.signedInfo.AddReference(keyIdentifierClause.Id, hashStream.FlushHashAndGetValue(), true); } else { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCannotCreateTokenReference)), this.Message); } } else { this.signedInfo.AddReference(token.Id, hashStream.FlushHashAndGetValue()); } }
public void WriteTo(Stream canonicalStream) { if (this.reader != null) { XmlDictionaryReader dicReader = this.reader as XmlDictionaryReader; if ((dicReader != null) && (dicReader.CanCanonicalize)) { dicReader.MoveToContent(); dicReader.StartCanonicalization(canonicalStream, this.includeComments, this.inclusivePrefixes); dicReader.Skip(); dicReader.EndCanonicalization(); } else { XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null); if (this.inclusivePrefixes != null) { // Add a dummy element at the top and populate the namespace // declaration of all the inclusive prefixes. writer.WriteStartElement("a", reader.LookupNamespace(String.Empty)); for (int i = 0; i < this.inclusivePrefixes.Length; ++i) { string ns = reader.LookupNamespace(this.inclusivePrefixes[i]); if (ns != null) { writer.WriteXmlnsAttribute(this.inclusivePrefixes[i], ns); } } } writer.StartCanonicalization(canonicalStream, this.includeComments, this.inclusivePrefixes); if (reader is WrappedReader) { ((WrappedReader)reader).XmlTokens.GetWriter().WriteTo(writer, new DictionaryManager()); } else { writer.WriteNode(reader, false); } writer.Flush(); writer.EndCanonicalization(); if (this.inclusivePrefixes != null) { writer.WriteEndElement(); } writer.Close(); } if (this.closeReadersAfterProcessing) { this.reader.Close(); } this.reader = null; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoInputIsSetForCanonicalization))); } }
public static void C14NWriterNegativeTests() { const string TestTypeNullStream = "Null Stream"; const string TestTypeNullElementInIncludePrefixes = "Null element in IncludePrefixes"; TestCase tc = TestConfigHelper.GetTest("C14NWriterNegativeTests"); foreach (var input in tc.Inputs) { string testType = input.Arguments[0].Value; if (testType == TestTypeNullStream) { try { //creating XmlC14NWriter with a null stream; XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null); writer.StartCanonicalization(null, true, new string[] { "p1", "p2" }); Assert.False(true, "Error, creating XmlC14NWriter with a null stream should have thrown!"); } catch (Exception ex) { //System.ArgumentNullException: {{ResLookup:;Value cannot be null.;ManagedString;mscorlib.dll;mscorlib;ArgumentNull_Generic}} Assert.Equal(input.Arguments[1].Value, ex.GetType().FullName); } } else if (testType == TestTypeNullElementInIncludePrefixes) { MemoryStream ms1 = new MemoryStream(); MemoryStream ms2 = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms1); try { //Creating the C14N writer with null elements in the IncludePrefixes array; writer.WriteStartElement("p2", "Root", "http://namespace"); //Starting the canonicalization; writer.StartCanonicalization(ms2, true, new string[] { "p1", null, "p2" }); //Writing the first element in the C14N writer; writer.WriteStartElement("Wee"); //Writing some content to finish the start element. Last chance for it to throw writer.WriteQualifiedName("foo", "http://namespace"); writer.WriteEndElement(); writer.EndCanonicalization(); writer.WriteEndElement(); Assert.False(true, "Error, creating XmlC14NWriter with null elements in include prefixes should have thrown!"); } catch (Exception ex) { //System.ArgumentException: {{ResLookup:;The inclusive namespace prefix collection cannot contain null as one of the items.;ManagedString;System.Runtime.Serialization.dll;System.Runtime.Serialization;InvalidInclusivePrefixListCollection}} Assert.Equal(input.Arguments[1].Value, ex.GetType().FullName); } } else { throw new ArgumentException("Don't know how to run test " + testType); } } }
void AddSignatureReference(SendSecurityHeaderElement[] elements) { if (elements != null) { for (int i = 0; i < elements.Length; ++i) { SecurityKeyIdentifierClause keyIdentifierClause = null; TokenElement signedEncryptedTokenElement = elements[i].Item as TokenElement; // signedEncryptedTokenElement can either be a TokenElement ( in SignThenEncrypt case) or EncryptedData ( in !SignThenEncryptCase) // STR-Transform does not make sense in !SignThenEncrypt case . // note: signedEncryptedTokenElement can also be SignatureConfirmation but we do not care about it here. bool useStrTransform = signedEncryptedTokenElement != null && SignThenEncrypt && this.ShouldUseStrTransformForToken(signedEncryptedTokenElement.Token, i, SecurityTokenAttachmentMode.SignedEncrypted, out keyIdentifierClause); if (!useStrTransform && elements[i].Id == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.ElementToSignMustHaveId)), this.Message); } HashStream hashStream = TakeHashStream(); XmlDictionaryWriter utf8Writer = TakeUtf8Writer(); utf8Writer.StartCanonicalization(hashStream, false, null); elements[i].Item.WriteTo(utf8Writer, ServiceModelDictionaryManager.Instance); utf8Writer.EndCanonicalization(); if (useStrTransform) { if (keyIdentifierClause != null) { if (String.IsNullOrEmpty(keyIdentifierClause.Id)) { keyIdentifierClause.Id = SecurityUniqueId.Create().Value; } this.ElementContainer.MapSecurityTokenToStrClause(signedEncryptedTokenElement.Token, keyIdentifierClause); this.signedInfo.AddReference(keyIdentifierClause.Id, hashStream.FlushHashAndGetValue(), true); } else { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCannotCreateTokenReference)), this.Message); } } else { this.signedInfo.AddReference(elements[i].Id, hashStream.FlushHashAndGetValue()); } } } }
private void AddSignatureReference(SecurityToken token) { if (token.Id == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("ElementToSignMustHaveId")), base.Message); } HashStream stream = this.TakeHashStream(); XmlDictionaryWriter writer = this.TakeUtf8Writer(); writer.StartCanonicalization(stream, false, null); base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, token); writer.EndCanonicalization(); this.signedInfo.AddReference(token.Id, stream.FlushHashAndGetValue()); }
public void WriteBodyToSign(Stream canonicalStream) { this.SetBodyId(); this.fullBodyBuffer = new XmlBuffer(0x7fffffff); XmlDictionaryWriter writer = this.fullBodyBuffer.OpenSection(XmlDictionaryReaderQuotas.Max); writer.StartCanonicalization(canonicalStream, false, null); this.WriteInnerMessageWithId(writer); writer.EndCanonicalization(); writer.Flush(); this.fullBodyBuffer.CloseSection(); this.fullBodyBuffer.Close(); this.state = BodyState.Signed; }
public void AddReference(string headerId, XmlDictionaryReader reader, XmlDictionaryWriter writer) { HashStream hashStream = this.TakeHashStream(); writer.StartCanonicalization(hashStream, false, this.InclusivePrefixes); // The reader must be positioned on the start element of the header / body we want to canonicalize writer.WriteNode(reader, false); writer.EndCanonicalization(); writer.Flush(); // Add a reference for this block this.AddReference(headerId, hashStream.FlushHashAndGetValue()); }
public void WriteBodyToSign(Stream canonicalStream) { SetBodyId(); _fullBodyBuffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter canonicalWriter = _fullBodyBuffer.OpenSection(XmlDictionaryReaderQuotas.Max); canonicalWriter.StartCanonicalization(canonicalStream, false, null); WriteInnerMessageWithId(canonicalWriter); canonicalWriter.EndCanonicalization(); canonicalWriter.Flush(); _fullBodyBuffer.CloseSection(); _fullBodyBuffer.Close(); _state = BodyState.Signed; }
public void WriteBodyToSignWithFragments(Stream stream, bool includeComments, string[] inclusivePrefixes, XmlDictionaryWriter writer) { IFragmentCapableXmlDictionaryWriter writer2 = (IFragmentCapableXmlDictionaryWriter)writer; this.SetBodyId(); BufferedOutputStream stream2 = new BufferManagerOutputStream("XmlBufferQuotaExceeded", 0x400, 0x7fffffff, BufferManager.CreateBufferManager(0L, 0x7fffffff)); writer.StartCanonicalization(stream, includeComments, inclusivePrefixes); writer2.StartFragment(stream2, false); this.WriteStartInnerMessageWithId(writer); base.InnerMessage.WriteBodyContents(writer); writer.WriteEndElement(); writer2.EndFragment(); writer.EndCanonicalization(); this.fullBodyFragment = stream2.ToArray(out this.fullBodyFragmentLength); this.state = BodyState.Signed; }
public void WriteTo(Stream canonicalStream) { if (this.reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.IdentityModel.SR.GetString("NoInputIsSetForCanonicalization"))); } XmlDictionaryReader reader = this.reader as XmlDictionaryReader; if ((reader != null) && reader.CanCanonicalize) { reader.MoveToContent(); reader.StartCanonicalization(canonicalStream, this.includeComments, this.inclusivePrefixes); reader.Skip(); reader.EndCanonicalization(); } else { XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null); if (this.inclusivePrefixes != null) { writer.WriteStartElement("a", this.reader.LookupNamespace(string.Empty)); for (int i = 0; i < this.inclusivePrefixes.Length; i++) { string namespaceUri = this.reader.LookupNamespace(this.inclusivePrefixes[i]); if (namespaceUri != null) { writer.WriteXmlnsAttribute(this.inclusivePrefixes[i], namespaceUri); } } } writer.StartCanonicalization(canonicalStream, this.includeComments, this.inclusivePrefixes); writer.WriteNode(this.reader, false); writer.Flush(); writer.EndCanonicalization(); if (this.inclusivePrefixes != null) { writer.WriteEndElement(); } writer.Close(); } if (this.closeReadersAfterProcessing) { this.reader.Close(); } this.reader = null; }
protected override ISignatureValueSecurityElement CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier, ISecurityElement elementToSign) { string signatureAlgorithm; XmlDictionaryString signatureAlgorithmDictionaryString; SecurityKey signatureKey; AlgorithmSuite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out signatureKey, out signatureAlgorithmDictionaryString); SignedXml signedXml = new SignedXml(); SignedInfo signedInfo = signedXml.SignedInfo; signedInfo.CanonicalizationMethod = AlgorithmSuite.DefaultCanonicalizationAlgorithm; signedInfo.SignatureMethod = signatureAlgorithm; if (elementToSign.Id == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ElementToSignMustHaveId)); } MemoryStream stream = new MemoryStream(); XmlDictionaryWriter utf8Writer = TakeUtf8Writer(); utf8Writer.StartCanonicalization(stream, false, null); elementToSign.WriteTo(utf8Writer, ServiceModelDictionaryManager.Instance); utf8Writer.EndCanonicalization(); stream.Position = 0; AddReference("#" + elementToSign.Id, stream); AsymmetricAlgorithm asymmetricAlgorithm = null; KeyedHashAlgorithm keyedHashAlgorithm = null; GetSigningAlgorithm(signatureKey, signatureAlgorithm, out keyedHashAlgorithm, out asymmetricAlgorithm); if (keyedHashAlgorithm != null) { signedXml.ComputeSignature(keyedHashAlgorithm); } else { signedXml.SigningKey = asymmetricAlgorithm; signedXml.ComputeSignature(); } SetKeyInfo(signedXml, identifier); return(new SignatureValue(signedXml.Signature)); }
public void WriteBodyToSignWithFragments(Stream stream, bool includeComments, string[] inclusivePrefixes, XmlDictionaryWriter writer) { IFragmentCapableXmlDictionaryWriter fragmentingWriter = (IFragmentCapableXmlDictionaryWriter)writer; SetBodyId(); BufferedOutputStream fullBodyFragment = new BufferManagerOutputStream(SR.XmlBufferQuotaExceeded, 1024, int.MaxValue, this.securityHeader.StreamBufferManager); writer.StartCanonicalization(stream, includeComments, inclusivePrefixes); fragmentingWriter.StartFragment(fullBodyFragment, false); WriteStartInnerMessageWithId(writer); this.InnerMessage.WriteBodyContents(writer); writer.WriteEndElement(); fragmentingWriter.EndFragment(); writer.EndCanonicalization(); this.fullBodyFragment = fullBodyFragment.ToArray(out this.fullBodyFragmentLength); this.state = BodyState.Signed; }
private void AddSignatureReference(SendSecurityHeaderElement[] elements) { if (elements != null) { for (int i = 0; i < elements.Length; i++) { if (elements[i].Id == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("ElementToSignMustHaveId")), base.Message); } HashStream stream = this.TakeHashStream(); XmlDictionaryWriter writer = this.TakeUtf8Writer(); writer.StartCanonicalization(stream, false, null); elements[i].Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); writer.EndCanonicalization(); this.signedInfo.AddReference(elements[i].Id, stream.FlushHashAndGetValue()); } } }
byte[] BufferBodyAndGetInclusivePrefixes() { // Look at the body for inclusive prefixes and buffer it at the same time. using (MemoryStream bufferStream = new MemoryStream()) { using (MemoryStream canonicalStream = new MemoryStream()) { using (XmlDictionaryWriter helperWriter = Utility.CreateWriter(bufferStream)) { helperWriter.StartCanonicalization(canonicalStream, false, null); this.WriteInnerMessageWithId(helperWriter); helperWriter.EndCanonicalization(); // canonicalStream contains the canonicalized body without inclusive prefixes this.inclusivePrefixes = this.GetInclusivePrefixesList(canonicalStream); return(bufferStream.ToArray()); } } } }
private void AddSignatureReference(SendSecurityHeaderElement[] elements) { if (elements != null) { for (int i = 0; i < elements.Length; ++i) { SecurityKeyIdentifierClause keyIdentifierClause = null; TokenElement signedEncryptedTokenElement = elements[i].Item as TokenElement; // signedEncryptedTokenElement can either be a TokenElement ( in SignThenEncrypt case) or EncryptedData ( in !SignThenEncryptCase) // STR-Transform does not make sense in !SignThenEncrypt case . // note: signedEncryptedTokenElement can also be SignatureConfirmation but we do not care about it here. bool useStrTransform = signedEncryptedTokenElement != null && SignThenEncrypt && ShouldUseStrTransformForToken(signedEncryptedTokenElement.Token, i, SecurityTokenAttachmentMode.SignedEncrypted, out keyIdentifierClause); if (!useStrTransform && elements[i].Id == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.ElementToSignMustHaveId), Message); } MemoryStream stream = new MemoryStream(); XmlDictionaryWriter utf8Writer = TakeUtf8Writer(); utf8Writer.StartCanonicalization(stream, false, null); elements[i].Item.WriteTo(utf8Writer, ServiceModelDictionaryManager.Instance); utf8Writer.EndCanonicalization(); stream.Position = 0; if (useStrTransform) { throw new PlatformNotSupportedException("StrTransform not supported yet"); } else { AddReference("#" + elements[i].Id, stream); } } } }
void WriteCanonicalizedBody(Stream canonicalStream) { byte[] buffer = null; if (this.discoveryInfo.SupportsInclusivePrefixes) { buffer = this.BufferBodyAndGetInclusivePrefixes(); } using (MemoryStream bodyBufferStream = new MemoryStream()) { using (XmlDictionaryWriter writer = Utility.CreateWriter(bodyBufferStream)) { writer.StartCanonicalization(canonicalStream, false, this.inclusivePrefixes); this.WriteBufferOrMessageBody(writer, buffer); writer.EndCanonicalization(); writer.Flush(); this.fullBodyBuffer = bodyBufferStream.ToArray(); } } }
public override object Process(object input, SignatureResourcePool resourcePool, DictionaryManager dictionaryManager) { if (input is XmlReader) { CanonicalizationDriver configuredDriver = this.GetConfiguredDriver(resourcePool); configuredDriver.SetInput(input as XmlReader); return(configuredDriver.GetMemoryStream()); } if (!(input is ISecurityElement)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("UnsupportedInputTypeForTransform", new object[] { input.GetType() }))); } MemoryStream stream = new MemoryStream(); XmlDictionaryWriter writer = resourcePool.TakeUtf8Writer(); writer.StartCanonicalization(stream, false, null); (input as ISecurityElement).WriteTo(writer, dictionaryManager); writer.EndCanonicalization(); stream.Seek(0L, SeekOrigin.Begin); return(stream); }
public void WriteBodyToSignThenEncryptWithFragments( Stream stream, bool includeComments, string[] inclusivePrefixes, EncryptedData encryptedData, SymmetricAlgorithm algorithm, XmlDictionaryWriter writer) { IFragmentCapableXmlDictionaryWriter fragmentingWriter = (IFragmentCapableXmlDictionaryWriter)writer; SetBodyId(); encryptedData.Id = this.securityHeader.GenerateId(); this.startBodyFragment = new MemoryStream(); BufferedOutputStream bodyContentFragment = new BufferManagerOutputStream(SR.XmlBufferQuotaExceeded, 1024, int.MaxValue, this.securityHeader.StreamBufferManager); this.endBodyFragment = new MemoryStream(); writer.StartCanonicalization(stream, includeComments, inclusivePrefixes); fragmentingWriter.StartFragment(this.startBodyFragment, false); WriteStartInnerMessageWithId(writer); fragmentingWriter.EndFragment(); fragmentingWriter.StartFragment(bodyContentFragment, true); this.InnerMessage.WriteBodyContents(writer); fragmentingWriter.EndFragment(); fragmentingWriter.StartFragment(this.endBodyFragment, false); writer.WriteEndElement(); fragmentingWriter.EndFragment(); writer.EndCanonicalization(); int bodyLength; byte[] bodyBuffer = bodyContentFragment.ToArray(out bodyLength); encryptedData.SetUpEncryption(algorithm, new ArraySegment <byte>(bodyBuffer, 0, bodyLength)); this.encryptedBodyContent = encryptedData; this.state = BodyState.SignedThenEncrypted; }
public void ProcessAndDigest(object input, SignatureResourcePool resourcePool, HashAlgorithm hash, DictionaryManager dictionaryManger) { HashStream hashStream = resourcePool.TakeHashStream(hash); XmlReader reader = input as XmlReader; if (reader != null) { this.ProcessReaderInput(reader, resourcePool, hashStream); } else { if (!(input is ISecurityElement)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.IdentityModel.SR.GetString("UnsupportedInputTypeForTransform", new object[] { input.GetType() }))); } XmlDictionaryWriter writer = resourcePool.TakeUtf8Writer(); writer.StartCanonicalization(hashStream, this.IncludeComments, this.GetInclusivePrefixes()); (input as ISecurityElement).WriteTo(writer, dictionaryManger); writer.EndCanonicalization(); } hashStream.FlushHash(); }
void WriteCanonicalizedBodyWithFragments(Stream canonicalStream, XmlDictionaryWriter writer) { byte[] buffer = null; if (this.discoveryInfo.SupportsInclusivePrefixes) { buffer = this.BufferBodyAndGetInclusivePrefixes(); } using (MemoryStream bodyBufferStream = new MemoryStream()) { writer.StartCanonicalization(canonicalStream, false, this.inclusivePrefixes); IFragmentCapableXmlDictionaryWriter fragmentingWriter = (IFragmentCapableXmlDictionaryWriter)writer; fragmentingWriter.StartFragment(bodyBufferStream, false); this.WriteBufferOrMessageBody(writer, buffer); fragmentingWriter.EndFragment(); writer.EndCanonicalization(); writer.Flush(); this.fullBodyFragmentLength = (int)bodyBufferStream.Length; this.fullBodyFragment = bodyBufferStream.ToArray(); } }
// multi-transform case, inefficient path public override object Process(object input, SignatureResourcePool resourcePool, DictionaryManager dictionaryManager) { if (input is XmlReader) { CanonicalizationDriver driver = GetConfiguredDriver(resourcePool); driver.SetInput(input as XmlReader); return(driver.GetMemoryStream()); } else if (input is ISecurityElement) { MemoryStream stream = new MemoryStream(); XmlDictionaryWriter utf8Writer = resourcePool.TakeUtf8Writer(); utf8Writer.StartCanonicalization(stream, false, null); (input as ISecurityElement).WriteTo(utf8Writer, dictionaryManager); utf8Writer.EndCanonicalization(); stream.Seek(0, SeekOrigin.Begin); return(stream); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedInputTypeForTransform, input.GetType()))); } }
public void WriteBodyToEncryptThenSign(Stream canonicalStream, EncryptedData encryptedData, SymmetricAlgorithm algorithm) { encryptedData.Id = this.securityHeader.GenerateId(); SetBodyId(); XmlDictionaryWriter encryptingWriter = XmlDictionaryWriter.CreateTextWriter(Stream.Null); // The XmlSerializer body formatter would add a // document declaration to the body fragment when a fresh writer // is provided. Hence, insert a dummy element here and capture // the body contents as a fragment. encryptingWriter.WriteStartElement("a"); MemoryStream ms = new MemoryStream(); ((IFragmentCapableXmlDictionaryWriter)encryptingWriter).StartFragment(ms, true); this.InnerMessage.WriteBodyContents(encryptingWriter); ((IFragmentCapableXmlDictionaryWriter)encryptingWriter).EndFragment(); encryptingWriter.WriteEndElement(); ms.Flush(); encryptedData.SetUpEncryption(algorithm, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length)); this.fullBodyBuffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter canonicalWriter = this.fullBodyBuffer.OpenSection(XmlDictionaryReaderQuotas.Max); canonicalWriter.StartCanonicalization(canonicalStream, false, null); WriteStartInnerMessageWithId(canonicalWriter); encryptedData.WriteTo(canonicalWriter, ServiceModelDictionaryManager.Instance); canonicalWriter.WriteEndElement(); canonicalWriter.EndCanonicalization(); canonicalWriter.Flush(); this.fullBodyBuffer.CloseSection(); this.fullBodyBuffer.Close(); this.state = BodyState.EncryptedThenSigned; }
public void AddReference( MessageHeaders headers, int i, XmlDictionaryWriter writer, string headerId, bool idInserted) { HashStream hashStream = this.TakeHashStream(); writer.StartCanonicalization(hashStream, false, this.InclusivePrefixes); headers.WriteStartHeader(i, writer); if (idInserted) { writer.WriteAttributeString(this.discoveryInfo.DiscoveryPrefix, ProtocolStrings.IdAttributeName, this.discoveryInfo.DiscoveryNamespace, headerId); } headers.WriteHeaderContents(i, writer); writer.WriteEndElement(); writer.EndCanonicalization(); writer.Flush(); // Add a pre-digested reference for this header this.AddReference(headerId, hashStream.FlushHashAndGetValue()); }
/// <summary> /// Indicates the start of Canonicalization. Any write operatation following this will canonicalize the data /// and will wirte it to the given stream. /// </summary> /// <param name="stream">Stream to which the canonical stream should be written.</param> /// <param name="includeComments">The value indicates if comments written should be canonicalized as well.</param> /// <param name="inclusivePrefixes">Set of prefixes that needs to be included into the canonical stream. The prefixes are defined at /// the first element that is written to the canonical stream.</param> public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) { _innerWriter.StartCanonicalization(stream, includeComments, inclusivePrefixes); }
protected virtual void ComputeHash(HashStream hashStream) { if (this.sendSide) { XmlDictionaryWriter writer = this.ResourcePool.TakeUtf8Writer(); writer.StartCanonicalization(hashStream, false, null); this.WriteTo(writer, this.dictionaryManager); writer.EndCanonicalization(); } else if (this.canonicalStream != null) { this.canonicalStream.WriteTo(hashStream); } else { if (this.readerProvider == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("InclusiveNamespacePrefixRequiresSignatureReader"))); } XmlDictionaryReader reader = this.readerProvider.GetReader(this.signatureReaderProviderCallbackContext); if (!reader.CanCanonicalize) { MemoryStream stream = new MemoryStream(); XmlDictionaryWriter writer2 = XmlDictionaryWriter.CreateBinaryWriter(stream, this.DictionaryManager.ParentDictionary); string[] inclusivePrefixes = this.GetInclusivePrefixes(); if (inclusivePrefixes != null) { writer2.WriteStartElement("a"); for (int i = 0; i < inclusivePrefixes.Length; i++) { string namespaceForInclusivePrefix = this.GetNamespaceForInclusivePrefix(inclusivePrefixes[i]); if (namespaceForInclusivePrefix != null) { writer2.WriteXmlnsAttribute(inclusivePrefixes[i], namespaceForInclusivePrefix); } } } reader.MoveToContent(); writer2.WriteNode(reader, false); if (inclusivePrefixes != null) { writer2.WriteEndElement(); } writer2.Flush(); byte[] buffer = stream.ToArray(); int length = (int)stream.Length; writer2.Close(); reader.Close(); reader = XmlDictionaryReader.CreateBinaryReader(buffer, 0, length, this.DictionaryManager.ParentDictionary, XmlDictionaryReaderQuotas.Max); if (inclusivePrefixes != null) { reader.ReadStartElement("a"); } } reader.ReadStartElement(this.dictionaryManager.XmlSignatureDictionary.Signature, this.dictionaryManager.XmlSignatureDictionary.Namespace); reader.MoveToStartElement(this.dictionaryManager.XmlSignatureDictionary.SignedInfo, this.dictionaryManager.XmlSignatureDictionary.Namespace); reader.StartCanonicalization(hashStream, false, this.GetInclusivePrefixes()); reader.Skip(); reader.EndCanonicalization(); reader.Close(); } }
public static void ReaderWriter_C14N_DifferentReadersWriters() { int count = 0; var params1 = TestConfigHelper.GetTest("ReaderWriter_C14N_DifferentReadersWriters_ParamGroup1"); var params2 = TestConfigHelper.GetTest("ReaderWriter_C14N_DifferentReadersWriters_ParamGroup2"); var params3 = TestConfigHelper.GetTest("ReaderWriter_C14N_DifferentReadersWriters_ParamGroup3"); var params4 = TestConfigHelper.GetTest("ReaderWriter_C14N_DifferentReadersWriters_ParamGroup4"); Transform transform; MemoryStream canonicalStream; MemoryStream ms; Stream transformedOutput; byte[] outputFromSecurity; byte[] outputFromIndigo; //TestC14NInMultipleWriters foreach (var input in params1.Inputs) { foreach (var input2 in params2.Inputs) { foreach (var input3 in params3.Inputs) { count++; string rwTypeStr = input.Arguments[0].Value; ReaderWriterFactory.ReaderWriterType rwType = (ReaderWriterFactory.ReaderWriterType)Enum.Parse(typeof(ReaderWriterFactory.ReaderWriterType), rwTypeStr, true); Encoding encoding = Encoding.GetEncoding((string)input.Arguments[1].Value); string sampleXmlFileName = input2.Arguments[0].Value; bool mustSupportV14N = input.Arguments[2].Value == "true"; string baselineFileName = input2.Arguments[1].Value; bool testWithComments = input3.Arguments[0].Value == "true"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; if (testWithComments) { transform = new XmlDsigExcC14NWithCommentsTransform(); } else { transform = new XmlDsigExcC14NTransform(); } xmlDoc.Load(baselineFileName); transform.LoadInput(xmlDoc); transformedOutput = transform.GetOutput(typeof(Stream)) as Stream; outputFromSecurity = StreamToByteArray(transformedOutput); byte[] sampleXmlFileBytes = File.ReadAllBytes(sampleXmlFileName); ms = new MemoryStream(); XmlWriter w = ReaderWriterFactory.CreateXmlWriter(rwType, ms, encoding); canonicalStream = new MemoryStream(); XmlDictionaryWriter dicWriter = w as XmlDictionaryWriter; if (dicWriter == null) { dicWriter = XmlDictionaryWriter.CreateDictionaryWriter(w); } if (!dicWriter.CanCanonicalize) { Assert.False(mustSupportV14N, "Error, writer should support C14N, but it doesn't!"); continue; } dicWriter.WriteStartElement("MyRoot"); dicWriter.StartCanonicalization(canonicalStream, testWithComments, null); FileStream fs = File.OpenRead(sampleXmlFileName); XmlReader webdataReader = XmlReader.Create(fs); CopyXmlToWriter(webdataReader, dicWriter); dicWriter.EndCanonicalization(); dicWriter.WriteEndElement(); dicWriter.Flush(); webdataReader.Close(); fs.Close(); outputFromIndigo = canonicalStream.ToArray(); Helper.DumpToFile(outputFromSecurity); Helper.DumpToFile(outputFromIndigo); Assert.True(Enumerable.SequenceEqual(outputFromSecurity, outputFromIndigo), $"ReaderWriter_C14N_DifferentReadersWriters test variation #{count} failed"); } } } //TestC14NInReader foreach (var input in params4.Inputs) { count++; string sampleXmlFileName = input.Arguments[3].Value; string rwTypeStr = input.Arguments[0].Value; ReaderWriterFactory.ReaderWriterType rwType = (ReaderWriterFactory.ReaderWriterType)Enum.Parse(typeof(ReaderWriterFactory.ReaderWriterType), rwTypeStr, true); Encoding encoding = Encoding.GetEncoding((string)input.Arguments[1].Value); bool mustSupportV14N = input.Arguments[2].Value == "true"; string baselineFileName = "ReaderWriter_C14N_BaselineXML_OnlyLF.xml"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; transform = new XmlDsigExcC14NTransform(); xmlDoc.Load(baselineFileName); transform.LoadInput(xmlDoc); transformedOutput = transform.GetOutput(typeof(Stream)) as Stream; outputFromSecurity = StreamToByteArray(transformedOutput); byte[] sampleXmlFileBytes = File.ReadAllBytes(sampleXmlFileName); XmlReader r = ReaderWriterFactory.CreateXmlReader(rwType, sampleXmlFileBytes, encoding); XmlDictionaryReader dicReader = r as XmlDictionaryReader; if (dicReader == null) { dicReader = XmlDictionaryReader.CreateDictionaryReader(r); } canonicalStream = new MemoryStream(); if (!dicReader.CanCanonicalize) { Assert.False(mustSupportV14N, "Error, reader should support C14N, but it doesn't!"); continue; } dicReader.StartCanonicalization(canonicalStream, false, null); canonicalStream.Position = 0; string str = new StreamReader(canonicalStream).ReadToEnd(); canonicalStream.Position = 0; while (dicReader.Read()) { ; // simply read it all into the C14N writer } dicReader.EndCanonicalization(); dicReader.Close(); outputFromIndigo = canonicalStream.ToArray(); Helper.DumpToFile(outputFromSecurity); Helper.DumpToFile(outputFromIndigo); Assert.True(Enumerable.SequenceEqual(outputFromSecurity, outputFromIndigo), $"ReaderWriter_C14N_DifferentReadersWriters test variation #{count} failed"); } //TestC14NWriterWithManyAttributes int numberOfAttributes = 1000; int seed = (int)DateTime.Now.Ticks; Random rndGen = new Random(seed); StringBuilder sb = new StringBuilder(); sb.Append("<Root><Element"); int prefixIndex = 0; for (int i = 0; i < numberOfAttributes; i++) { string namespaceUri = null; string prefix = null; if ((rndGen.Next() % 5) == 0) { prefix = "p" + (prefixIndex++); namespaceUri = "http://namespace_" + i; } string localName = "attr" + i; string value = "attrValue" + i; if (prefix == null) { sb.Append($" {localName}=\"{value}\""); } else { sb.Append($" {prefix}:{localName}=\"{2}\" xmlns:{value}=\"{namespaceUri}\""); } } sb.Append(">Hello world</Element></Root>"); string xmlString = sb.ToString(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlString); ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms); canonicalStream = new MemoryStream(); writer.StartCanonicalization(canonicalStream, false, null); doc.WriteTo(writer); writer.Flush(); writer.EndCanonicalization(); outputFromIndigo = canonicalStream.ToArray(); byte[] nonCanonicalOutput = ms.ToArray(); XmlDsigExcC14NTransform transform2 = new XmlDsigExcC14NTransform(); transform2.LoadInput(doc); transformedOutput = transform2.GetOutput(typeof(Stream)) as Stream; outputFromSecurity = StreamToByteArray(transformedOutput); Helper.DumpToFile(outputFromSecurity); Helper.DumpToFile(outputFromIndigo); Helper.DumpToFile(nonCanonicalOutput); Assert.True(Enumerable.SequenceEqual(outputFromSecurity, outputFromIndigo), $"ReaderWriter_C14N_DifferentReadersWriters test variation #{count} failed"); count++; Assert.Equal(params1.Inputs.Count * params2.Inputs.Count * params3.Inputs.Count + params4.Inputs.Count + 1, count); }
public static void TestC14NInclusivePrefixes() { TestCase tc = TestConfigHelper.GetTest("TestC14NInclusivePrefixes"); int count = 0; foreach (var input in tc.Inputs) { count++; string rwTypeStr = input.Arguments[0].Value; ReaderWriterFactory.ReaderWriterType rwType = (ReaderWriterFactory.ReaderWriterType)Enum.Parse(typeof(ReaderWriterFactory.ReaderWriterType), rwTypeStr, true); Encoding encoding = Encoding.GetEncoding(input.Arguments[1].Value); bool mustSupportV14N = input.Arguments[2].Value.ToLower() == "true"; MemoryStream ms = new MemoryStream(); XmlWriter w = ReaderWriterFactory.CreateXmlWriter(rwType, ms, encoding); XmlDictionaryWriter writer = w as XmlDictionaryWriter; if (writer == null) { writer = XmlDictionaryWriter.CreateDictionaryWriter(w); } if (!writer.CanCanonicalize) { Assert.False(mustSupportV14N, string.Format("Error, writer {0},{1} should support C14N, but it doesn't!", rwTypeStr, encoding.ToString())); continue; } string myDefaultNamespace = "http://mynamespace"; string myNamespace1 = "http://mynamespace1"; string myNamespace2 = "http://mynamespace2"; string myNamespace3 = "http://mynamespace3"; string myNamespace4 = "http://mynamespace4"; writer.WriteStartElement("Root"); writer.WriteXmlnsAttribute("p1", myNamespace1); writer.WriteAttributeString("p1", "a", null, "b"); writer.WriteStartElement("", "Element1", myDefaultNamespace); writer.WriteAttributeString("p3", "c", myNamespace3, "d"); writer.WriteStartElement("Element2"); MemoryStream canonicalStream = new MemoryStream(); writer.StartCanonicalization(canonicalStream, false, new string[] { "p3", "p2", "p1", "" }); writer.WriteStartElement("pre", "Element3", myNamespace2); writer.WriteAttributeString("pre2", "attrName", myNamespace4, "attrValue"); writer.WriteStartElement("Element4", ""); writer.WriteStartAttribute("attr1"); writer.WriteQualifiedName("foo", myNamespace1); writer.WriteEndAttribute(); writer.WriteStartAttribute("attr2"); writer.WriteQualifiedName("bar", myNamespace3); writer.WriteEndAttribute(); writer.WriteString("Hello world"); writer.WriteEndElement(); // Element4 writer.WriteEndElement(); // pre:Element3 writer.EndCanonicalization(); writer.WriteEndElement(); // Element2 writer.WriteEndElement(); // Element1 writer.WriteEndElement(); // Root writer.Flush(); byte[] canonicalDoc = canonicalStream.ToArray(); byte[] fullDoc = ms.ToArray(); writer.Close(); // Finished creating the document XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform(); transform.InclusiveNamespacesPrefixList = "p3 p2 p1 #default"; transform.LoadInput(new MemoryStream(canonicalDoc)); Stream transformedOutput = transform.GetOutput(typeof(Stream)) as Stream; byte[] outputFromSecurity = StreamToByteArray(transformedOutput); //Finished creating the doc from the security class Helper.DumpToFile(fullDoc); Helper.DumpToFile(canonicalDoc); Helper.DumpToFile(outputFromSecurity); Assert.True(Enumerable.SequenceEqual(outputFromSecurity, canonicalDoc), $"TestC14NInclusivePrefixes test variation #{count} failed"); } }