2 // SignedXml.cs - SignedXml implementation for XML Signature
5 // Sebastien Pouliot <sebastien@ximian.com>
6 // Atsushi Enomoto <atsushi@ximian.com>
7 // Tim Coleman <tim@timcoleman.com>
9 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
10 // Copyright (C) Tim Coleman, 2004
11 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
35 using System.Runtime.InteropServices;
36 using System.Security.Cryptography;
37 using System.Security.Policy;
43 using System.Security.Cryptography.X509Certificates;
46 namespace System.Security.Cryptography.Xml {
48 public class SignedXml {
50 public const string XmlDsigCanonicalizationUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
51 public const string XmlDsigCanonicalizationWithCommentsUrl = XmlDsigCanonicalizationUrl + "#WithComments";
52 public const string XmlDsigDSAUrl = XmlDsigNamespaceUrl + "dsa-sha1";
53 public const string XmlDsigHMACSHA1Url = XmlDsigNamespaceUrl + "hmac-sha1";
54 public const string XmlDsigMinimalCanonicalizationUrl = XmlDsigNamespaceUrl + "minimal";
55 public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#";
56 public const string XmlDsigRSASHA1Url = XmlDsigNamespaceUrl + "rsa-sha1";
57 public const string XmlDsigSHA1Url = XmlDsigNamespaceUrl + "sha1";
60 public const string XmlDecryptionTransformUrl = "http://www.w3.org/2002/07/decrypt#XML";
61 public const string XmlDsigBase64TransformUrl = XmlDsigNamespaceUrl + "base64";
62 public const string XmlDsigC14NTransformUrl = XmlDsigCanonicalizationUrl;
63 public const string XmlDsigC14NWithCommentsTransformUrl = XmlDsigCanonicalizationWithCommentsUrl;
64 public const string XmlDsigEnvelopedSignatureTransformUrl = XmlDsigNamespaceUrl + "enveloped-signature";
65 public const string XmlDsigExcC14NTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#";
66 public const string XmlDsigExcC14NWithCommentsTransformUrl = XmlDsigExcC14NTransformUrl + "WithComments";
67 public const string XmlDsigXPathTransformUrl = "http://www.w3.org/TR/1999/REC-xpath-19991116";
68 public const string XmlDsigXsltTransformUrl = "http://www.w3.org/TR/1999/REC-xslt-19991116";
69 public const string XmlLicenseTransformUrl = "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform";
71 private EncryptedXml encryptedXml;
74 protected Signature m_signature;
75 private AsymmetricAlgorithm key;
76 protected string m_strSigningKeyName;
77 private XmlDocument envdoc;
78 private IEnumerator pkEnumerator;
79 private XmlElement signatureElement;
80 private Hashtable hashes;
81 // FIXME: enable it after CAS implementation
83 private XmlResolver xmlResolver = new XmlSecureResolver (new XmlUrlResolver (), new Evidence ());
85 private XmlResolver xmlResolver = new XmlUrlResolver ();
87 private ArrayList manifests;
89 private IEnumerator _x509Enumerator;
92 private static readonly char [] whitespaceChars = new char [] {' ', '\r', '\n', '\t'};
96 m_signature = new Signature ();
97 m_signature.SignedInfo = new SignedInfo ();
98 hashes = new Hashtable (2); // 98% SHA1 for now
101 public SignedXml (XmlDocument document) : this ()
103 if (document == null)
104 throw new ArgumentNullException ("document");
108 public SignedXml (XmlElement elem) : this ()
111 throw new ArgumentNullException ("elem");
112 envdoc = new XmlDocument ();
113 envdoc.LoadXml (elem.OuterXml);
118 public EncryptedXml EncryptedXml {
119 get { return encryptedXml; }
120 set { encryptedXml = value; }
124 public KeyInfo KeyInfo {
127 if (m_signature.KeyInfo == null)
128 m_signature.KeyInfo = new KeyInfo ();
130 return m_signature.KeyInfo;
132 set { m_signature.KeyInfo = value; }
135 public Signature Signature {
136 get { return m_signature; }
139 public string SignatureLength {
140 get { return m_signature.SignedInfo.SignatureLength; }
143 public string SignatureMethod {
144 get { return m_signature.SignedInfo.SignatureMethod; }
147 public byte[] SignatureValue {
148 get { return m_signature.SignatureValue; }
151 public SignedInfo SignedInfo {
152 get { return m_signature.SignedInfo; }
155 public AsymmetricAlgorithm SigningKey {
160 // NOTE: CryptoAPI related ? documented as fx internal
161 public string SigningKeyName {
162 get { return m_strSigningKeyName; }
163 set { m_strSigningKeyName = value; }
166 public void AddObject (DataObject dataObject)
168 m_signature.AddObject (dataObject);
171 public void AddReference (Reference reference)
174 if (reference == null)
175 throw new ArgumentNullException ("reference");
177 m_signature.SignedInfo.AddReference (reference);
180 private Stream ApplyTransform (Transform t, XmlDocument input)
182 // These transformer modify input document, which should
183 // not affect to the input itself.
184 if (t is XmlDsigXPathTransform
185 || t is XmlDsigEnvelopedSignatureTransform
187 || t is XmlDecryptionTransform
190 input = (XmlDocument) input.Clone ();
194 if (t is XmlDsigEnvelopedSignatureTransform)
195 // It returns XmlDocument for XmlDocument input.
196 return CanonicalizeOutput (t.GetOutput ());
198 object obj = t.GetOutput ();
201 else if (obj is XmlDocument) {
202 MemoryStream ms = new MemoryStream ();
203 XmlTextWriter xtw = new XmlTextWriter (ms, Encoding.UTF8);
204 ((XmlDocument) obj).WriteTo (xtw);
208 // Rewind to the start of the stream
212 else if (obj == null) {
213 throw new NotImplementedException ("This should not occur. Transform is " + t + ".");
216 // e.g. XmlDsigXPathTransform returns XmlNodeList
217 return CanonicalizeOutput (obj);
221 private Stream CanonicalizeOutput (object obj)
223 Transform c14n = GetC14NMethod ();
224 c14n.LoadInput (obj);
225 return (Stream) c14n.GetOutput ();
228 private XmlDocument GetManifest (Reference r)
230 XmlDocument doc = new XmlDocument ();
231 doc.PreserveWhitespace = true;
233 if (r.Uri [0] == '#') {
235 if (signatureElement != null) {
236 XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1));
238 throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1));
239 doc.LoadXml (xel.OuterXml);
240 FixupNamespaceNodes (xel, doc.DocumentElement);
243 else if (xmlResolver != null) {
244 // TODO: need testing
245 Stream s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
249 if (doc.FirstChild != null) {
250 // keep a copy of the manifests to check their references later
251 if (manifests == null)
252 manifests = new ArrayList ();
260 private void FixupNamespaceNodes (XmlElement src, XmlElement dst)
262 // add namespace nodes
263 foreach (XmlAttribute attr in src.SelectNodes ("namespace::*")) {
264 if (attr.LocalName == "xml")
266 if (attr.OwnerElement == src)
268 dst.SetAttributeNode (dst.OwnerDocument.ImportNode (attr, true) as XmlAttribute);
272 [MonoTODO ("Need testing")]
273 private byte[] GetReferenceHash (Reference r)
276 XmlDocument doc = null;
277 if (r.Uri == String.Empty) {
280 else if (r.Type == XmlSignature.Uri.Manifest) {
281 doc = GetManifest (r);
284 doc = new XmlDocument ();
285 doc.PreserveWhitespace = true;
286 string objectName = null;
288 if (r.Uri.StartsWith ("#xpointer")) {
289 string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars));
290 if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
291 // FIXME: how to handle invalid xpointer?
294 uri = uri.Substring (1, uri.Length - 2);
297 else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')')
298 // id('foo'), id("foo")
299 objectName = uri.Substring (4, uri.Length - 6);
301 else if (r.Uri [0] == '#') {
302 objectName = r.Uri.Substring (1);
304 else if (xmlResolver != null) {
305 // TODO: test but doc says that Resolver = null -> no access
307 // no way to know if valid without throwing an exception
308 Uri uri = new Uri (r.Uri);
309 s = (Stream) xmlResolver.GetEntity (uri, null, typeof (Stream));
312 // may still be a local file (and maybe not xml)
313 s = File.OpenRead (r.Uri);
316 if (objectName != null) {
317 foreach (DataObject obj in m_signature.ObjectList) {
318 if (obj.Id == objectName) {
319 XmlElement xel = obj.GetXml ();
320 doc.LoadXml (xel.OuterXml);
321 FixupNamespaceNodes (xel, doc.DocumentElement);
328 if (r.TransformChain.Count > 0) {
329 foreach (Transform t in r.TransformChain) {
331 s = ApplyTransform (t, doc);
335 object o = t.GetOutput ();
339 s = CanonicalizeOutput (o);
343 else if (s == null) {
344 // we must not C14N references from outside the document
345 // e.g. non-xml documents
346 if (r.Uri [0] != '#') {
347 s = new MemoryStream ();
351 // apply default C14N transformation
352 s = ApplyTransform (new XmlDsigC14NTransform (), doc);
355 HashAlgorithm digest = GetHash (r.DigestMethod);
356 return digest.ComputeHash (s);
359 private void DigestReferences ()
361 // we must tell each reference which hash algorithm to use
362 // before asking for the SignedInfo XML !
363 foreach (Reference r in m_signature.SignedInfo.References) {
364 // assume SHA-1 if nothing is specified
365 if (r.DigestMethod == null)
366 r.DigestMethod = XmlDsigSHA1Url;
367 r.DigestValue = GetReferenceHash (r);
371 private Transform GetC14NMethod ()
373 Transform t = (Transform) CryptoConfig.CreateFromName (m_signature.SignedInfo.CanonicalizationMethod);
375 throw new CryptographicException ("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod);
379 private Stream SignedInfoTransformed ()
381 Transform t = GetC14NMethod ();
383 if (signatureElement == null) {
384 // when creating signatures
385 XmlDocument doc = new XmlDocument ();
386 doc.PreserveWhitespace = true;
387 doc.LoadXml (m_signature.SignedInfo.GetXml ().OuterXml);
389 foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes ("namespace::*")) {
390 if (attr.LocalName == "xml")
392 if (attr.Prefix == doc.DocumentElement.Prefix)
394 doc.DocumentElement.SetAttributeNode (doc.ImportNode (attr, true) as XmlAttribute);
399 // when verifying signatures
400 // TODO - check m_signature.SignedInfo.Id
401 XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
402 StringWriter sw = new StringWriter ();
403 XmlTextWriter xtw = new XmlTextWriter (sw);
404 xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI);
406 // context namespace nodes (except for "xmlns:xml")
407 XmlNodeList nl = el.SelectNodes ("namespace::*");
408 foreach (XmlAttribute attr in nl) {
409 if (attr.ParentNode == el)
411 if (attr.LocalName == "xml")
413 if (attr.Prefix == el.Prefix)
417 foreach (XmlNode attr in el.Attributes)
419 foreach (XmlNode n in el.ChildNodes)
422 xtw.WriteEndElement ();
423 byte [] si = Encoding.UTF8.GetBytes (sw.ToString ());
425 MemoryStream ms = new MemoryStream ();
426 ms.Write (si, 0, si.Length);
431 // C14N and C14NWithComments always return a Stream in GetOutput
432 return (Stream) t.GetOutput ();
435 // reuse hash - most document will always use the same hash
436 private HashAlgorithm GetHash (string algorithm)
438 HashAlgorithm hash = (HashAlgorithm) hashes [algorithm];
440 hash = HashAlgorithm.Create (algorithm);
442 throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm);
443 hashes.Add (algorithm, hash);
444 // now ready to be used
447 // important before reusing an hash object
453 public bool CheckSignature ()
455 return (CheckSignatureInternal (null) != null);
458 private bool CheckReferenceIntegrity (ArrayList referenceList)
460 if (referenceList == null)
463 // check digest (hash) for every reference
464 foreach (Reference r in referenceList) {
465 // stop at first broken reference
466 byte[] hash = GetReferenceHash (r);
467 if (! Compare (r.DigestValue, hash))
473 public bool CheckSignature (AsymmetricAlgorithm key)
476 throw new ArgumentNullException ("key");
477 return (CheckSignatureInternal (key) != null);
480 private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
485 // check with supplied key
486 if (!CheckSignatureWithKey (key))
490 if (Signature.KeyInfo == null)
493 if (Signature.KeyInfo == null)
494 throw new CryptographicException ("At least one KeyInfo is required.");
496 // no supplied key, iterates all KeyInfo
497 while ((key = GetPublicKey ()) != null) {
498 if (CheckSignatureWithKey (key)) {
507 // some parts may need to be downloaded
508 // so where doing it last
509 if (!CheckReferenceIntegrity (m_signature.SignedInfo.References))
512 if (manifests != null) {
513 // do not use foreach as a manifest could contain manifests...
514 for (int i=0; i < manifests.Count; i++) {
515 Manifest manifest = new Manifest ((manifests [i] as XmlDocument).DocumentElement);
516 if (! CheckReferenceIntegrity (manifest.References))
523 // Is the signature (over SignedInfo) valid ?
524 private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
529 SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
533 AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
534 if (verifier == null)
538 verifier.SetKey (key);
539 verifier.SetHashAlgorithm (sd.DigestAlgorithm);
541 HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
542 // get the hash of the C14N SignedInfo element
543 MemoryStream ms = (MemoryStream) SignedInfoTransformed ();
545 byte[] digest = hash.ComputeHash (ms);
546 return verifier.VerifySignature (digest, m_signature.SignatureValue);
549 // e.g. SignatureMethod != AsymmetricAlgorithm type
554 private bool Compare (byte[] expected, byte[] actual)
556 bool result = ((expected != null) && (actual != null));
558 int l = expected.Length;
559 result = (l == actual.Length);
561 for (int i=0; i < l; i++) {
562 if (expected[i] != actual[i])
570 public bool CheckSignature (KeyedHashAlgorithm macAlg)
573 throw new ArgumentNullException ("macAlg");
577 // Is the signature (over SignedInfo) valid ?
578 Stream s = SignedInfoTransformed ();
582 byte[] actual = macAlg.ComputeHash (s);
583 // HMAC signature may be partial
584 if (m_signature.SignedInfo.SignatureLength != null) {
585 int length = actual.Length;
587 // SignatureLength is in bits
588 length = (Int32.Parse (m_signature.SignedInfo.SignatureLength) >> 3);
593 if (length != actual.Length) {
594 byte[] trunked = new byte [length];
595 Buffer.BlockCopy (actual, 0, trunked, 0, length);
600 if (Compare (m_signature.SignatureValue, actual)) {
601 // some parts may need to be downloaded
602 // so where doing it last
603 return CheckReferenceIntegrity (m_signature.SignedInfo.References);
611 public bool CheckSignature (X509Certificate2 certificate, bool verifySignatureOnly)
613 throw new NotImplementedException ();
617 public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
619 signingKey = CheckSignatureInternal (null);
620 return (signingKey != null);
623 public void ComputeSignature ()
626 // required before hashing
627 m_signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
630 AsymmetricSignatureFormatter signer = null;
631 // in need for a CryptoConfig factory
633 signer = new DSASignatureFormatter (key);
635 signer = new RSAPKCS1SignatureFormatter (key);
637 if (signer != null) {
638 SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
640 HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
641 // get the hash of the C14N SignedInfo element
642 byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
644 signer.SetHashAlgorithm ("SHA1");
645 m_signature.SignatureValue = signer.CreateSignature (digest);
650 public void ComputeSignature (KeyedHashAlgorithm macAlg)
653 throw new ArgumentNullException ("macAlg");
655 if (macAlg is HMACSHA1) {
658 m_signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
659 m_signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
662 throw new CryptographicException ("unsupported algorithm");
665 public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
667 // this works only if there's a DTD or XSD available to define the ID
668 XmlElement xel = document.GetElementById (idValue);
670 // search an "undefined" ID
671 xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
676 // According to book ".NET Framework Security" this method
677 // iterates all possible keys then return null
678 protected virtual AsymmetricAlgorithm GetPublicKey ()
680 if (m_signature.KeyInfo == null)
683 if (pkEnumerator == null) {
684 pkEnumerator = m_signature.KeyInfo.GetEnumerator ();
688 if (_x509Enumerator != null) {
689 if (_x509Enumerator.MoveNext ()) {
690 X509Certificate cert = (X509Certificate) _x509Enumerator.Current;
691 return new X509Certificate2 (cert.GetRawCertData ()).PublicKey.Key;
693 _x509Enumerator = null;
697 while (pkEnumerator.MoveNext ()) {
698 AsymmetricAlgorithm key = null;
699 KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
701 if (kic is DSAKeyValue)
703 else if (kic is RSAKeyValue)
707 key.FromXmlString (kic.GetXml ().InnerXml);
712 if (kic is KeyInfoX509Data) {
713 _x509Enumerator = ((KeyInfoX509Data) kic).Certificates.GetEnumerator ();
714 if (_x509Enumerator.MoveNext ()) {
715 X509Certificate cert = (X509Certificate) _x509Enumerator.Current;
716 return new X509Certificate2 (cert.GetRawCertData ()).PublicKey.Key;
724 public XmlElement GetXml ()
726 return m_signature.GetXml (envdoc);
729 public void LoadXml (XmlElement value)
732 throw new ArgumentNullException ("value");
734 signatureElement = value;
735 m_signature.LoadXml (value);
737 // Need to give the EncryptedXml object to the
738 // XmlDecryptionTransform to give it a fighting
739 // chance at decrypting the document.
740 foreach (Reference r in m_signature.SignedInfo.References) {
741 foreach (Transform t in r.TransformChain) {
742 if (t is XmlDecryptionTransform)
743 ((XmlDecryptionTransform) t).EncryptedXml = EncryptedXml;
751 public XmlResolver Resolver {
752 set { xmlResolver = value; }