SignedXml.cs 24 KB

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