SignedXml.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. //
  2. // SignedXml.cs - SignedXml implementation for XML Signature
  3. //
  4. // Author:
  5. // Sebastien Pouliot <[email protected]>
  6. // Atsushi Enomoto <[email protected]>
  7. // Tim Coleman <[email protected]>
  8. //
  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)
  12. //
  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:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  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.
  31. //
  32. using System.Collections;
  33. using System.IO;
  34. using System.Runtime.InteropServices;
  35. using System.Security.Cryptography;
  36. using System.Security.Policy;
  37. using System.Net;
  38. using System.Text;
  39. using System.Xml;
  40. using System.Security.Cryptography.X509Certificates;
  41. namespace System.Security.Cryptography.Xml {
  42. public class SignedXml {
  43. public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#";
  44. public const string XmlDsigMinimalCanonicalizationUrl = "http://www.w3.org/2000/09/xmldsig#minimal";
  45. public const string XmlDsigCanonicalizationUrl = XmlDsigC14NTransformUrl;
  46. public const string XmlDsigCanonicalizationWithCommentsUrl = XmlDsigC14NWithCommentsTransformUrl;
  47. public const string XmlDsigSHA1Url = "http://www.w3.org/2000/09/xmldsig#sha1";
  48. public const string XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
  49. public const string XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
  50. public const string XmlDsigHMACSHA1Url = "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
  51. public const string XmlDsigSHA256Url = "http://www.w3.org/2001/04/xmlenc#sha256";
  52. public const string XmlDsigRSASHA256Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
  53. // Yes, SHA384 is in the xmldsig-more namespace even though all the other SHA variants are in xmlenc. That's the standard.
  54. public const string XmlDsigSHA384Url = "http://www.w3.org/2001/04/xmldsig-more#sha384";
  55. public const string XmlDsigRSASHA384Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384";
  56. public const string XmlDsigSHA512Url = "http://www.w3.org/2001/04/xmlenc#sha512";
  57. public const string XmlDsigRSASHA512Url = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
  58. public const string XmlDsigC14NTransformUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
  59. public const string XmlDsigC14NWithCommentsTransformUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
  60. public const string XmlDsigExcC14NTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#";
  61. public const string XmlDsigExcC14NWithCommentsTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
  62. public const string XmlDsigBase64TransformUrl = "http://www.w3.org/2000/09/xmldsig#base64";
  63. public const string XmlDsigXPathTransformUrl = "http://www.w3.org/TR/1999/REC-xpath-19991116";
  64. public const string XmlDsigXsltTransformUrl = "http://www.w3.org/TR/1999/REC-xslt-19991116";
  65. public const string XmlDsigEnvelopedSignatureTransformUrl = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
  66. public const string XmlDecryptionTransformUrl = "http://www.w3.org/2002/07/decrypt#XML";
  67. public const string XmlLicenseTransformUrl = "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform";
  68. private EncryptedXml encryptedXml;
  69. protected Signature m_signature;
  70. private AsymmetricAlgorithm key;
  71. protected string m_strSigningKeyName;
  72. private XmlDocument envdoc;
  73. private IEnumerator pkEnumerator;
  74. private XmlElement signatureElement;
  75. private Hashtable hashes;
  76. // FIXME: enable it after CAS implementation
  77. internal XmlResolver _xmlResolver = new XmlUrlResolver ();
  78. private bool _bResolverSet = true;
  79. internal XmlElement _context;
  80. private ArrayList manifests;
  81. private IEnumerator _x509Enumerator;
  82. private static readonly char [] whitespaceChars = new char [] {' ', '\r', '\n', '\t'};
  83. public SignedXml ()
  84. {
  85. m_signature = new Signature ();
  86. m_signature.SignedInfo = new SignedInfo ();
  87. hashes = new Hashtable (2); // 98% SHA1 for now
  88. _context = null;
  89. }
  90. public SignedXml (XmlDocument document) : this ()
  91. {
  92. if (document == null)
  93. throw new ArgumentNullException ("document");
  94. envdoc = document;
  95. _context = document.DocumentElement;
  96. }
  97. public SignedXml (XmlElement elem) : this ()
  98. {
  99. if (elem == null)
  100. throw new ArgumentNullException ("elem");
  101. envdoc = new XmlDocument ();
  102. _context = elem;
  103. envdoc.LoadXml (elem.OuterXml);
  104. }
  105. [ComVisible (false)]
  106. public EncryptedXml EncryptedXml {
  107. get { return encryptedXml; }
  108. set { encryptedXml = value; }
  109. }
  110. public KeyInfo KeyInfo {
  111. get {
  112. if (m_signature.KeyInfo == null)
  113. m_signature.KeyInfo = new KeyInfo ();
  114. return m_signature.KeyInfo;
  115. }
  116. set { m_signature.KeyInfo = value; }
  117. }
  118. public Signature Signature {
  119. get { return m_signature; }
  120. }
  121. public string SignatureLength {
  122. get { return m_signature.SignedInfo.SignatureLength; }
  123. }
  124. public string SignatureMethod {
  125. get { return m_signature.SignedInfo.SignatureMethod; }
  126. }
  127. public byte[] SignatureValue {
  128. get { return m_signature.SignatureValue; }
  129. }
  130. public SignedInfo SignedInfo {
  131. get { return m_signature.SignedInfo; }
  132. }
  133. public AsymmetricAlgorithm SigningKey {
  134. get { return key; }
  135. set { key = value; }
  136. }
  137. // NOTE: CryptoAPI related ? documented as fx internal
  138. public string SigningKeyName {
  139. get { return m_strSigningKeyName; }
  140. set { m_strSigningKeyName = value; }
  141. }
  142. public XmlResolver Resolver
  143. {
  144. // This property only has a setter. The rationale for this is that we don't have a good value
  145. // to return when it has not been explicitely set, as we are using XmlSecureResolver by default
  146. set
  147. {
  148. _xmlResolver = value;
  149. _bResolverSet = true;
  150. }
  151. }
  152. internal bool ResolverSet
  153. {
  154. get { return _bResolverSet; }
  155. }
  156. public void AddObject (DataObject dataObject)
  157. {
  158. m_signature.AddObject (dataObject);
  159. }
  160. public void AddReference (Reference reference)
  161. {
  162. if (reference == null)
  163. throw new ArgumentNullException ("reference");
  164. m_signature.SignedInfo.AddReference (reference);
  165. }
  166. private Stream ApplyTransform (Transform t, XmlDocument input)
  167. {
  168. // These transformer modify input document, which should
  169. // not affect to the input itself.
  170. if (t is XmlDsigXPathTransform
  171. || t is XmlDsigEnvelopedSignatureTransform
  172. || t is XmlDecryptionTransform
  173. )
  174. input = (XmlDocument) input.Clone ();
  175. t.LoadInput (input);
  176. if (t is XmlDsigEnvelopedSignatureTransform)
  177. // It returns XmlDocument for XmlDocument input.
  178. return CanonicalizeOutput (t.GetOutput ());
  179. object obj = t.GetOutput ();
  180. if (obj is Stream)
  181. return (Stream) obj;
  182. else if (obj is XmlDocument) {
  183. MemoryStream ms = new MemoryStream ();
  184. XmlTextWriter xtw = new XmlTextWriter (ms, Encoding.UTF8);
  185. ((XmlDocument) obj).WriteTo (xtw);
  186. xtw.Flush ();
  187. // Rewind to the start of the stream
  188. ms.Position = 0;
  189. return ms;
  190. }
  191. else if (obj == null) {
  192. throw new NotImplementedException ("This should not occur. Transform is " + t + ".");
  193. }
  194. else {
  195. // e.g. XmlDsigXPathTransform returns XmlNodeList
  196. return CanonicalizeOutput (obj);
  197. }
  198. }
  199. private Stream CanonicalizeOutput (object obj)
  200. {
  201. Transform c14n = GetC14NMethod ();
  202. c14n.LoadInput (obj);
  203. return (Stream) c14n.GetOutput ();
  204. }
  205. private XmlDocument GetManifest (Reference r)
  206. {
  207. XmlDocument doc = new XmlDocument ();
  208. doc.PreserveWhitespace = true;
  209. if (r.Uri [0] == '#') {
  210. // local manifest
  211. if (signatureElement != null) {
  212. XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1));
  213. if (xel == null)
  214. throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1));
  215. doc.AppendChild (doc.ImportNode (xel, true));
  216. FixupNamespaceNodes (xel, doc.DocumentElement, false);
  217. }
  218. }
  219. else if (_xmlResolver != null) {
  220. // TODO: need testing
  221. Stream s = (Stream) _xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
  222. doc.Load (s);
  223. }
  224. if (doc.FirstChild != null) {
  225. // keep a copy of the manifests to check their references later
  226. if (manifests == null)
  227. manifests = new ArrayList ();
  228. manifests.Add (doc);
  229. return doc;
  230. }
  231. return null;
  232. }
  233. private void FixupNamespaceNodes (XmlElement src, XmlElement dst, bool ignoreDefault)
  234. {
  235. // add namespace nodes
  236. foreach (XmlAttribute attr in src.SelectNodes ("namespace::*")) {
  237. if (attr.LocalName == "xml")
  238. continue;
  239. if (ignoreDefault && attr.LocalName == "xmlns")
  240. continue;
  241. dst.SetAttributeNode (dst.OwnerDocument.ImportNode (attr, true) as XmlAttribute);
  242. }
  243. }
  244. private byte[] GetReferenceHash (Reference r, bool check_hmac)
  245. {
  246. Stream s = null;
  247. XmlDocument doc = null;
  248. if (r.Uri == String.Empty) {
  249. doc = envdoc;
  250. }
  251. else if (r.Type == XmlSignature.Uri.Manifest) {
  252. doc = GetManifest (r);
  253. }
  254. else {
  255. doc = new XmlDocument ();
  256. doc.PreserveWhitespace = true;
  257. string objectName = null;
  258. if (r.Uri.StartsWith ("#xpointer")) {
  259. string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars));
  260. if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
  261. // FIXME: how to handle invalid xpointer?
  262. uri = String.Empty;
  263. else
  264. uri = uri.Substring (1, uri.Length - 2);
  265. if (uri == "/")
  266. doc = envdoc;
  267. else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')')
  268. // id('foo'), id("foo")
  269. objectName = uri.Substring (4, uri.Length - 6);
  270. }
  271. else if (r.Uri [0] == '#') {
  272. objectName = r.Uri.Substring (1);
  273. }
  274. else if (_xmlResolver != null) {
  275. // TODO: test but doc says that Resolver = null -> no access
  276. try {
  277. // no way to know if valid without throwing an exception
  278. Uri uri = new Uri (r.Uri);
  279. s = (Stream) _xmlResolver.GetEntity (uri, null, typeof (Stream));
  280. }
  281. catch {
  282. // may still be a local file (and maybe not xml)
  283. s = File.OpenRead (r.Uri);
  284. }
  285. }
  286. if (objectName != null) {
  287. XmlElement found = null;
  288. foreach (DataObject obj in m_signature.ObjectList) {
  289. if (obj.Id == objectName) {
  290. found = obj.GetXml ();
  291. found.SetAttribute ("xmlns", SignedXml.XmlDsigNamespaceUrl);
  292. doc.AppendChild (doc.ImportNode (found, true));
  293. // FIXME: there should be theoretical justification of copying namespace declaration nodes this way.
  294. foreach (XmlNode n in found.ChildNodes)
  295. // Do not copy default namespace as it must be xmldsig namespace for "Object" element.
  296. if (n.NodeType == XmlNodeType.Element)
  297. FixupNamespaceNodes (n as XmlElement, doc.DocumentElement, true);
  298. break;
  299. }
  300. }
  301. if (found == null && envdoc != null) {
  302. found = GetIdElement (envdoc, objectName);
  303. if (found != null) {
  304. doc.AppendChild (doc.ImportNode (found, true));
  305. FixupNamespaceNodes (found, doc.DocumentElement, false);
  306. }
  307. }
  308. if (found == null)
  309. throw new CryptographicException (String.Format ("Malformed reference object: {0}", objectName));
  310. }
  311. }
  312. if (r.TransformChain.Count > 0) {
  313. foreach (Transform t in r.TransformChain) {
  314. if (s == null) {
  315. s = ApplyTransform (t, doc);
  316. }
  317. else {
  318. t.LoadInput (s);
  319. object o = t.GetOutput ();
  320. if (o is Stream)
  321. s = (Stream) o;
  322. else
  323. s = CanonicalizeOutput (o);
  324. }
  325. }
  326. }
  327. else if (s == null) {
  328. // we must not C14N references from outside the document
  329. // e.g. non-xml documents
  330. if (r.Uri [0] != '#') {
  331. s = new MemoryStream ();
  332. doc.Save (s);
  333. }
  334. else {
  335. // apply default C14N transformation
  336. s = ApplyTransform (new XmlDsigC14NTransform (), doc);
  337. }
  338. }
  339. HashAlgorithm digest = GetHash (r.DigestMethod, check_hmac);
  340. return (digest == null) ? null : digest.ComputeHash (s);
  341. }
  342. private void DigestReferences ()
  343. {
  344. // we must tell each reference which hash algorithm to use
  345. // before asking for the SignedInfo XML !
  346. foreach (Reference r in m_signature.SignedInfo.References) {
  347. // assume SHA-1 if nothing is specified
  348. if (r.DigestMethod == null)
  349. r.DigestMethod = XmlDsigSHA1Url;
  350. r.DigestValue = GetReferenceHash (r, false);
  351. }
  352. }
  353. private Transform GetC14NMethod ()
  354. {
  355. Transform t = (Transform) CryptoConfig.CreateFromName (m_signature.SignedInfo.CanonicalizationMethod);
  356. if (t == null)
  357. throw new CryptographicException ("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod);
  358. return t;
  359. }
  360. private Stream SignedInfoTransformed ()
  361. {
  362. Transform t = GetC14NMethod ();
  363. if (signatureElement == null) {
  364. // when creating signatures
  365. XmlDocument doc = new XmlDocument ();
  366. doc.PreserveWhitespace = true;
  367. doc.LoadXml (m_signature.SignedInfo.GetXml ().OuterXml);
  368. if (envdoc != null)
  369. foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes ("namespace::*")) {
  370. if (attr.LocalName == "xml")
  371. continue;
  372. if (attr.Prefix == doc.DocumentElement.Prefix)
  373. continue;
  374. doc.DocumentElement.SetAttributeNode (doc.ImportNode (attr, true) as XmlAttribute);
  375. }
  376. t.LoadInput (doc);
  377. }
  378. else {
  379. // when verifying signatures
  380. // TODO - check m_signature.SignedInfo.Id
  381. XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
  382. StringWriter sw = new StringWriter ();
  383. XmlTextWriter xtw = new XmlTextWriter (sw);
  384. xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI);
  385. // context namespace nodes (except for "xmlns:xml")
  386. XmlNodeList nl = el.SelectNodes ("namespace::*");
  387. foreach (XmlAttribute attr in nl) {
  388. if (attr.ParentNode == el)
  389. continue;
  390. if (attr.LocalName == "xml")
  391. continue;
  392. if (attr.Prefix == el.Prefix)
  393. continue;
  394. attr.WriteTo (xtw);
  395. }
  396. foreach (XmlNode attr in el.Attributes)
  397. attr.WriteTo (xtw);
  398. foreach (XmlNode n in el.ChildNodes)
  399. n.WriteTo (xtw);
  400. xtw.WriteEndElement ();
  401. byte [] si = Encoding.UTF8.GetBytes (sw.ToString ());
  402. MemoryStream ms = new MemoryStream ();
  403. ms.Write (si, 0, si.Length);
  404. ms.Position = 0;
  405. t.LoadInput (ms);
  406. }
  407. // C14N and C14NWithComments always return a Stream in GetOutput
  408. return (Stream) t.GetOutput ();
  409. }
  410. // reuse hash - most document will always use the same hash
  411. private HashAlgorithm GetHash (string algorithm, bool check_hmac)
  412. {
  413. HashAlgorithm hash = (HashAlgorithm) hashes [algorithm];
  414. if (hash == null) {
  415. hash = HashAlgorithm.Create (algorithm);
  416. if (hash == null)
  417. throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm);
  418. hashes.Add (algorithm, hash);
  419. // now ready to be used
  420. }
  421. else {
  422. // important before reusing an hash object
  423. hash.Initialize ();
  424. }
  425. // we can sign using any hash algorith, including HMAC, but we can only verify hash (MS compatibility)
  426. if (check_hmac && (hash is KeyedHashAlgorithm))
  427. return null;
  428. return hash;
  429. }
  430. public bool CheckSignature ()
  431. {
  432. return (CheckSignatureInternal (null) != null);
  433. }
  434. private bool CheckReferenceIntegrity (ArrayList referenceList)
  435. {
  436. if (referenceList == null)
  437. return false;
  438. // check digest (hash) for every reference
  439. foreach (Reference r in referenceList) {
  440. // stop at first broken reference
  441. byte[] hash = GetReferenceHash (r, true);
  442. if (! Compare (r.DigestValue, hash))
  443. return false;
  444. }
  445. return true;
  446. }
  447. public bool CheckSignature (AsymmetricAlgorithm key)
  448. {
  449. if (key == null)
  450. throw new ArgumentNullException ("key");
  451. return (CheckSignatureInternal (key) != null);
  452. }
  453. private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
  454. {
  455. pkEnumerator = null;
  456. if (key != null) {
  457. // check with supplied key
  458. if (!CheckSignatureWithKey (key))
  459. return null;
  460. } else {
  461. if (Signature.KeyInfo == null)
  462. return null;
  463. // no supplied key, iterates all KeyInfo
  464. while ((key = GetPublicKey ()) != null) {
  465. if (CheckSignatureWithKey (key)) {
  466. break;
  467. }
  468. }
  469. pkEnumerator = null;
  470. if (key == null)
  471. return null;
  472. }
  473. // some parts may need to be downloaded
  474. // so where doing it last
  475. if (!CheckReferenceIntegrity (m_signature.SignedInfo.References))
  476. return null;
  477. if (manifests != null) {
  478. // do not use foreach as a manifest could contain manifests...
  479. for (int i=0; i < manifests.Count; i++) {
  480. Manifest manifest = new Manifest ((manifests [i] as XmlDocument).DocumentElement);
  481. if (! CheckReferenceIntegrity (manifest.References))
  482. return null;
  483. }
  484. }
  485. return key;
  486. }
  487. // Is the signature (over SignedInfo) valid ?
  488. private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
  489. {
  490. if (key == null)
  491. return false;
  492. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
  493. if (sd == null)
  494. return false;
  495. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  496. if (verifier == null)
  497. return false;
  498. try {
  499. verifier.SetKey (key);
  500. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  501. HashAlgorithm hash = GetHash (sd.DigestAlgorithm, true);
  502. // get the hash of the C14N SignedInfo element
  503. MemoryStream ms = (MemoryStream) SignedInfoTransformed ();
  504. byte[] digest = hash.ComputeHash (ms);
  505. return verifier.VerifySignature (digest, m_signature.SignatureValue);
  506. }
  507. catch {
  508. // e.g. SignatureMethod != AsymmetricAlgorithm type
  509. return false;
  510. }
  511. }
  512. private bool Compare (byte[] expected, byte[] actual)
  513. {
  514. bool result = ((expected != null) && (actual != null));
  515. if (result) {
  516. int l = expected.Length;
  517. result = (l == actual.Length);
  518. if (result) {
  519. for (int i=0; i < l; i++) {
  520. if (expected[i] != actual[i])
  521. return false;
  522. }
  523. }
  524. }
  525. return result;
  526. }
  527. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  528. {
  529. if (macAlg == null)
  530. throw new ArgumentNullException ("macAlg");
  531. pkEnumerator = null;
  532. // Is the signature (over SignedInfo) valid ?
  533. Stream s = SignedInfoTransformed ();
  534. if (s == null)
  535. return false;
  536. byte[] actual = macAlg.ComputeHash (s);
  537. // HMAC signature may be partial and specified by <HMACOutputLength>
  538. if (m_signature.SignedInfo.SignatureLength != null) {
  539. int length = Int32.Parse (m_signature.SignedInfo.SignatureLength);
  540. // we only support signatures with a multiple of 8 bits
  541. // and the value must match the signature length
  542. if ((length & 7) != 0)
  543. throw new CryptographicException ("Signature length must be a multiple of 8 bits.");
  544. // SignatureLength is in bits (and we works on bytes, only in multiple of 8 bits)
  545. // and both values must match for a signature to be valid
  546. length >>= 3;
  547. if (length != m_signature.SignatureValue.Length)
  548. throw new CryptographicException ("Invalid signature length.");
  549. // is the length "big" enough to make the signature meaningful ?
  550. // we use a minimum of 80 bits (10 bytes) or half the HMAC normal output length
  551. // e.g. HMACMD5 output 128 bits but our minimum is 80 bits (not 64 bits)
  552. int minimum = Math.Max (10, actual.Length / 2);
  553. if (length < minimum)
  554. throw new CryptographicException ("HMAC signature is too small");
  555. if (length < actual.Length) {
  556. byte[] trunked = new byte [length];
  557. Buffer.BlockCopy (actual, 0, trunked, 0, length);
  558. actual = trunked;
  559. }
  560. }
  561. if (Compare (m_signature.SignatureValue, actual)) {
  562. // some parts may need to be downloaded
  563. // so where doing it last
  564. return CheckReferenceIntegrity (m_signature.SignedInfo.References);
  565. }
  566. return false;
  567. }
  568. [MonoTODO]
  569. [ComVisible (false)]
  570. public bool CheckSignature (X509Certificate2 certificate, bool verifySignatureOnly)
  571. {
  572. throw new NotImplementedException ();
  573. }
  574. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  575. {
  576. signingKey = CheckSignatureInternal (null);
  577. return (signingKey != null);
  578. }
  579. public void ComputeSignature ()
  580. {
  581. DigestReferences ();
  582. if (key == null)
  583. throw new CryptographicException (SR.Cryptography_Xml_LoadKeyFailed);
  584. // Check the signature algorithm associated with the key so that we can accordingly set the signature method
  585. if (SignedInfo.SignatureMethod == null) {
  586. if (key is DSA) {
  587. SignedInfo.SignatureMethod = XmlDsigDSAUrl;
  588. } else if (key is RSA) {
  589. // Default to RSA-SHA1
  590. SignedInfo.SignatureMethod = XmlDsigRSASHA1Url;
  591. } else {
  592. throw new CryptographicException (SR.Cryptography_Xml_CreatedKeyFailed);
  593. }
  594. }
  595. // See if there is a signature description class defined in the Config file
  596. SignatureDescription signatureDescription = CryptoConfig.CreateFromName (SignedInfo.SignatureMethod) as SignatureDescription;
  597. if (signatureDescription == null)
  598. throw new CryptographicException (SR.Cryptography_Xml_SignatureDescriptionNotCreated);
  599. HashAlgorithm hashAlg = signatureDescription.CreateDigest ();
  600. if (hashAlg == null)
  601. throw new CryptographicException (SR.Cryptography_Xml_CreateHashAlgorithmFailed);
  602. byte[] hashvalue = hashAlg.ComputeHash (SignedInfoTransformed ());
  603. AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter (key);
  604. m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature (hashAlg);
  605. }
  606. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  607. {
  608. if (macAlg == null)
  609. throw new ArgumentNullException ("macAlg");
  610. string method = null;
  611. if (macAlg is HMACSHA1) {
  612. method = XmlDsigHMACSHA1Url;
  613. } else if (macAlg is HMACSHA256) {
  614. method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
  615. } else if (macAlg is HMACSHA384) {
  616. method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
  617. } else if (macAlg is HMACSHA512) {
  618. method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
  619. } else if (macAlg is HMACRIPEMD160) {
  620. method = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160";
  621. }
  622. if (method == null)
  623. throw new CryptographicException ("unsupported algorithm");
  624. DigestReferences ();
  625. m_signature.SignedInfo.SignatureMethod = method;
  626. m_signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  627. }
  628. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  629. {
  630. if ((document == null) || (idValue == null))
  631. return null;
  632. // this works only if there's a DTD or XSD available to define the ID
  633. XmlElement xel = document.GetElementById (idValue);
  634. if (xel == null) {
  635. // search an "undefined" ID
  636. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  637. if (xel == null) {
  638. xel = (XmlElement) document.SelectSingleNode ("//*[@ID='" + idValue + "']");
  639. if (xel == null) {
  640. xel = (XmlElement) document.SelectSingleNode ("//*[@id='" + idValue + "']");
  641. }
  642. }
  643. }
  644. return xel;
  645. }
  646. // According to book ".NET Framework Security" this method
  647. // iterates all possible keys then return null
  648. protected virtual AsymmetricAlgorithm GetPublicKey ()
  649. {
  650. if (m_signature.KeyInfo == null)
  651. return null;
  652. if (pkEnumerator == null) {
  653. pkEnumerator = m_signature.KeyInfo.GetEnumerator ();
  654. }
  655. #if SECURITY_DEP
  656. if (_x509Enumerator != null) {
  657. if (_x509Enumerator.MoveNext ()) {
  658. X509Certificate cert = (X509Certificate) _x509Enumerator.Current;
  659. return new X509Certificate2 (cert.GetRawCertData ()).PublicKey.Key;
  660. } else {
  661. _x509Enumerator = null;
  662. }
  663. }
  664. #endif
  665. while (pkEnumerator.MoveNext ()) {
  666. AsymmetricAlgorithm key = null;
  667. KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
  668. if (kic is DSAKeyValue)
  669. key = DSA.Create ();
  670. else if (kic is RSAKeyValue)
  671. key = RSA.Create ();
  672. if (key != null) {
  673. key.FromXmlString (kic.GetXml ().InnerXml);
  674. return key;
  675. }
  676. #if SECURITY_DEP
  677. if (kic is KeyInfoX509Data) {
  678. _x509Enumerator = ((KeyInfoX509Data) kic).Certificates.GetEnumerator ();
  679. if (_x509Enumerator.MoveNext ()) {
  680. X509Certificate cert = (X509Certificate) _x509Enumerator.Current;
  681. return new X509Certificate2 (cert.GetRawCertData ()).PublicKey.Key;
  682. }
  683. }
  684. #endif
  685. }
  686. return null;
  687. }
  688. public XmlElement GetXml ()
  689. {
  690. return m_signature.GetXml (envdoc);
  691. }
  692. public void LoadXml (XmlElement value)
  693. {
  694. if (value == null)
  695. throw new ArgumentNullException ("value");
  696. signatureElement = value;
  697. m_signature.LoadXml (value);
  698. if (_context == null) {
  699. _context = value;
  700. }
  701. // Need to give the EncryptedXml object to the
  702. // XmlDecryptionTransform to give it a fighting
  703. // chance at decrypting the document.
  704. foreach (Reference r in m_signature.SignedInfo.References) {
  705. foreach (Transform t in r.TransformChain) {
  706. if (t is XmlDecryptionTransform)
  707. ((XmlDecryptionTransform) t).EncryptedXml = EncryptedXml;
  708. }
  709. }
  710. }
  711. }
  712. }