SignedXml.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. //
  2. // SignedXml.cs - SignedXml implementation for XML Signature
  3. //
  4. // Author:
  5. // Sebastien Pouliot <[email protected]>
  6. // Atsushi Enomoto <[email protected]>
  7. //
  8. // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
  9. // (C) 2004 Novell (http://www.novell.com)
  10. //
  11. using System.Collections;
  12. using System.IO;
  13. using System.Runtime.InteropServices;
  14. using System.Security.Cryptography;
  15. using System.Security.Policy;
  16. using System.Net;
  17. using System.Text;
  18. using System.Xml;
  19. namespace System.Security.Cryptography.Xml {
  20. public class SignedXml {
  21. protected Signature m_signature;
  22. private AsymmetricAlgorithm key;
  23. protected string m_strSigningKeyName;
  24. private XmlDocument envdoc;
  25. private IEnumerator pkEnumerator;
  26. private XmlElement signatureElement;
  27. private Hashtable hashes;
  28. // FIXME: enable it after CAS implementation
  29. #if false //NET_1_1
  30. private XmlResolver xmlResolver = new XmlSecureResolver (new XmlUrlResolver (), new Evidence ());
  31. #else
  32. private XmlResolver xmlResolver = new XmlUrlResolver ();
  33. #endif
  34. private ArrayList manifests;
  35. private static readonly char [] whitespaceChars = new char [] {' ', '\r', '\n', '\t'};
  36. public SignedXml ()
  37. {
  38. m_signature = new Signature ();
  39. m_signature.SignedInfo = new SignedInfo ();
  40. hashes = new Hashtable (2); // 98% SHA1 for now
  41. }
  42. public SignedXml (XmlDocument document) : this ()
  43. {
  44. if (document == null)
  45. throw new ArgumentNullException ("document");
  46. envdoc = document;
  47. }
  48. public SignedXml (XmlElement elem) : this ()
  49. {
  50. if (elem == null)
  51. throw new ArgumentNullException ("elem");
  52. envdoc = new XmlDocument ();
  53. envdoc.LoadXml (elem.OuterXml);
  54. }
  55. public const string XmlDsigCanonicalizationUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
  56. public const string XmlDsigCanonicalizationWithCommentsUrl = XmlDsigCanonicalizationUrl + "#WithComments";
  57. public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#";
  58. public const string XmlDsigDSAUrl = XmlDsigNamespaceUrl + "dsa-sha1";
  59. public const string XmlDsigHMACSHA1Url = XmlDsigNamespaceUrl + "hmac-sha1";
  60. public const string XmlDsigMinimalCanonicalizationUrl = XmlDsigNamespaceUrl + "minimal";
  61. public const string XmlDsigRSASHA1Url = XmlDsigNamespaceUrl + "rsa-sha1";
  62. public const string XmlDsigSHA1Url = XmlDsigNamespaceUrl + "sha1";
  63. public KeyInfo KeyInfo {
  64. get { return m_signature.KeyInfo; }
  65. set { m_signature.KeyInfo = value; }
  66. }
  67. public Signature Signature {
  68. get { return m_signature; }
  69. }
  70. public string SignatureLength {
  71. get { return m_signature.SignedInfo.SignatureLength; }
  72. }
  73. public string SignatureMethod {
  74. get { return m_signature.SignedInfo.SignatureMethod; }
  75. }
  76. public byte[] SignatureValue {
  77. get { return m_signature.SignatureValue; }
  78. }
  79. public SignedInfo SignedInfo {
  80. get { return m_signature.SignedInfo; }
  81. }
  82. public AsymmetricAlgorithm SigningKey {
  83. get { return key; }
  84. set { key = value; }
  85. }
  86. // NOTE: CryptoAPI related ? documented as fx internal
  87. public string SigningKeyName {
  88. get { return m_strSigningKeyName; }
  89. set { m_strSigningKeyName = value; }
  90. }
  91. public void AddObject (DataObject dataObject)
  92. {
  93. m_signature.AddObject (dataObject);
  94. }
  95. public void AddReference (Reference reference)
  96. {
  97. m_signature.SignedInfo.AddReference (reference);
  98. }
  99. private Stream ApplyTransform (Transform t, XmlDocument input)
  100. {
  101. // These transformer modify input document, which should
  102. // not affect to the input itself.
  103. if (t is XmlDsigXPathTransform ||
  104. t is XmlDsigEnvelopedSignatureTransform)
  105. input = (XmlDocument) input.Clone ();
  106. t.LoadInput (input);
  107. if (t is XmlDsigEnvelopedSignatureTransform)
  108. // It returns XmlDocument for XmlDocument input.
  109. return CanonicalizeOutput (t.GetOutput ());
  110. object obj = t.GetOutput ();
  111. if (obj is Stream)
  112. return (Stream) obj;
  113. else if (obj is XmlDocument) {
  114. MemoryStream ms = new MemoryStream ();
  115. XmlTextWriter xtw = new XmlTextWriter (ms, Encoding.UTF8);
  116. ((XmlDocument) obj).WriteTo (xtw);
  117. return ms;
  118. }
  119. else if (obj == null) {
  120. throw new NotImplementedException ("This should not occur. Transform is " + t + ".");
  121. }
  122. else {
  123. // e.g. XmlDsigXPathTransform returns XmlNodeList
  124. return CanonicalizeOutput (obj);
  125. }
  126. }
  127. private Stream CanonicalizeOutput (object obj)
  128. {
  129. Transform c14n = GetC14NMethod ();
  130. c14n.LoadInput (obj);
  131. return (Stream) c14n.GetOutput ();
  132. }
  133. private XmlDocument GetManifest (Reference r)
  134. {
  135. XmlDocument doc = new XmlDocument ();
  136. doc.PreserveWhitespace = true;
  137. if (r.Uri [0] == '#') {
  138. // local manifest
  139. if (signatureElement != null) {
  140. XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1));
  141. if (xel == null)
  142. throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1));
  143. doc.LoadXml (xel.OuterXml);
  144. FixupNamespaceNodes (xel, doc.DocumentElement);
  145. }
  146. }
  147. else if (xmlResolver != null) {
  148. // TODO: need testing
  149. Stream s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
  150. doc.Load (s);
  151. }
  152. if (doc.FirstChild != null) {
  153. // keep a copy of the manifests to check their references later
  154. if (manifests == null)
  155. manifests = new ArrayList ();
  156. manifests.Add (doc);
  157. return doc;
  158. }
  159. return null;
  160. }
  161. private void FixupNamespaceNodes (XmlElement src, XmlElement dst)
  162. {
  163. // add namespace nodes
  164. foreach (XmlAttribute attr in src.SelectNodes ("namespace::*")) {
  165. if (attr.LocalName == "xml")
  166. continue;
  167. if (attr.OwnerElement == src)
  168. continue;
  169. dst.SetAttributeNode (dst.OwnerDocument.ImportNode (attr, true) as XmlAttribute);
  170. }
  171. }
  172. [MonoTODO ("Need testing")]
  173. private byte[] GetReferenceHash (Reference r)
  174. {
  175. Stream s = null;
  176. XmlDocument doc = null;
  177. if (r.Uri == String.Empty) {
  178. doc = envdoc;
  179. }
  180. else if (r.Type == XmlSignature.Uri.Manifest) {
  181. doc = GetManifest (r);
  182. }
  183. else {
  184. doc = new XmlDocument ();
  185. doc.PreserveWhitespace = true;
  186. string objectName = null;
  187. if (r.Uri.StartsWith ("#xpointer")) {
  188. string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars));
  189. if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
  190. // FIXME: how to handle invalid xpointer?
  191. uri = String.Empty;
  192. else
  193. uri = uri.Substring (1, uri.Length - 2);
  194. if (uri == "/")
  195. doc = envdoc;
  196. else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')')
  197. // id('foo'), id("foo")
  198. objectName = uri.Substring (4, uri.Length - 6);
  199. }
  200. else if (r.Uri [0] == '#') {
  201. objectName = r.Uri.Substring (1);
  202. }
  203. else if (xmlResolver != null) {
  204. // TODO: test but doc says that Resolver = null -> no access
  205. try {
  206. // no way to know if valid without throwing an exception
  207. Uri uri = new Uri (r.Uri);
  208. s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
  209. }
  210. catch {
  211. // may still be a local file (and maybe not xml)
  212. s = File.OpenRead (r.Uri);
  213. }
  214. }
  215. if (objectName != null) {
  216. foreach (DataObject obj in m_signature.ObjectList) {
  217. if (obj.Id == objectName) {
  218. XmlElement xel = obj.GetXml ();
  219. doc.LoadXml (xel.OuterXml);
  220. FixupNamespaceNodes (xel, doc.DocumentElement);
  221. break;
  222. }
  223. }
  224. }
  225. }
  226. if (r.TransformChain.Count > 0) {
  227. foreach (Transform t in r.TransformChain) {
  228. if (s == null) {
  229. s = ApplyTransform (t, doc);
  230. }
  231. else {
  232. t.LoadInput (s);
  233. object o = t.GetOutput ();
  234. if (o is Stream)
  235. s = (Stream) o;
  236. else
  237. s = CanonicalizeOutput (o);
  238. }
  239. }
  240. }
  241. else if (s == null) {
  242. // we must not C14N references from outside the document
  243. // e.g. non-xml documents
  244. if (r.Uri [0] != '#') {
  245. s = new MemoryStream ();
  246. doc.Save (s);
  247. }
  248. else {
  249. // apply default C14N transformation
  250. s = ApplyTransform (new XmlDsigC14NTransform (), doc);
  251. }
  252. }
  253. HashAlgorithm digest = GetHash (r.DigestMethod);
  254. return digest.ComputeHash (s);
  255. }
  256. private void DigestReferences ()
  257. {
  258. // we must tell each reference which hash algorithm to use
  259. // before asking for the SignedInfo XML !
  260. foreach (Reference r in m_signature.SignedInfo.References) {
  261. // assume SHA-1 if nothing is specified
  262. if (r.DigestMethod == null)
  263. r.DigestMethod = XmlDsigSHA1Url;
  264. r.DigestValue = GetReferenceHash (r);
  265. }
  266. }
  267. private Transform GetC14NMethod ()
  268. {
  269. Transform t = (Transform) CryptoConfig.CreateFromName (m_signature.SignedInfo.CanonicalizationMethod);
  270. if (t == null)
  271. throw new CryptographicException ("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod);
  272. return t;
  273. }
  274. private Stream SignedInfoTransformed ()
  275. {
  276. Transform t = GetC14NMethod ();
  277. if (signatureElement == null) {
  278. // when creating signatures
  279. XmlDocument doc = new XmlDocument ();
  280. doc.PreserveWhitespace = true;
  281. doc.LoadXml (m_signature.SignedInfo.GetXml ().OuterXml);
  282. if (envdoc != null)
  283. foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes ("namespace::*")) {
  284. if (attr.LocalName == "xml")
  285. continue;
  286. if (attr.Prefix == doc.DocumentElement.Prefix)
  287. continue;
  288. doc.DocumentElement.SetAttributeNode (doc.ImportNode (attr, true) as XmlAttribute);
  289. }
  290. t.LoadInput (doc);
  291. }
  292. else {
  293. // when verifying signatures
  294. // TODO - check m_signature.SignedInfo.Id
  295. XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
  296. StringWriter sw = new StringWriter ();
  297. XmlTextWriter xtw = new XmlTextWriter (sw);
  298. xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI);
  299. // context namespace nodes (except for "xmlns:xml")
  300. XmlNodeList nl = el.SelectNodes ("namespace::*");
  301. foreach (XmlAttribute attr in nl) {
  302. if (attr.ParentNode == el)
  303. continue;
  304. if (attr.LocalName == "xml")
  305. continue;
  306. if (attr.Prefix == el.Prefix)
  307. continue;
  308. attr.WriteTo (xtw);
  309. }
  310. foreach (XmlNode attr in el.Attributes)
  311. attr.WriteTo (xtw);
  312. foreach (XmlNode n in el.ChildNodes)
  313. n.WriteTo (xtw);
  314. xtw.WriteEndElement ();
  315. byte [] si = Encoding.UTF8.GetBytes (sw.ToString ());
  316. MemoryStream ms = new MemoryStream ();
  317. ms.Write (si, 0, si.Length);
  318. ms.Position = 0;
  319. t.LoadInput (ms);
  320. }
  321. // C14N and C14NWithComments always return a Stream in GetOutput
  322. return (Stream) t.GetOutput ();
  323. }
  324. // reuse hash - most document will always use the same hash
  325. private HashAlgorithm GetHash (string algorithm)
  326. {
  327. HashAlgorithm hash = (HashAlgorithm) hashes [algorithm];
  328. if (hash == null) {
  329. hash = HashAlgorithm.Create (algorithm);
  330. if (hash == null)
  331. throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm);
  332. hashes.Add (algorithm, hash);
  333. // now ready to be used
  334. }
  335. else {
  336. // important before reusing an hash object
  337. hash.Initialize ();
  338. }
  339. return hash;
  340. }
  341. public bool CheckSignature ()
  342. {
  343. return (CheckSignatureInternal (null) != null);
  344. }
  345. private bool CheckReferenceIntegrity (ArrayList referenceList)
  346. {
  347. if (referenceList == null)
  348. return false;
  349. // check digest (hash) for every reference
  350. foreach (Reference r in referenceList) {
  351. // stop at first broken reference
  352. byte[] hash = GetReferenceHash (r);
  353. if (! Compare (r.DigestValue, hash))
  354. return false;
  355. }
  356. return true;
  357. }
  358. public bool CheckSignature (AsymmetricAlgorithm key)
  359. {
  360. if (key == null)
  361. throw new ArgumentNullException ("key");
  362. return (CheckSignatureInternal (key) != null);
  363. }
  364. private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
  365. {
  366. pkEnumerator = null;
  367. if (key != null) {
  368. // check with supplied key
  369. if (!CheckSignatureWithKey (key))
  370. return null;
  371. }
  372. else {
  373. if (Signature.KeyInfo == null)
  374. throw new CryptographicException ("At least one KeyInfo is required.");
  375. // no supplied key, iterates all KeyInfo
  376. while ((key = GetPublicKey ()) != null) {
  377. if (CheckSignatureWithKey (key)) {
  378. break;
  379. }
  380. }
  381. pkEnumerator = null;
  382. if (key == null)
  383. return null;
  384. }
  385. // some parts may need to be downloaded
  386. // so where doing it last
  387. if (!CheckReferenceIntegrity (m_signature.SignedInfo.References))
  388. return null;
  389. if (manifests != null) {
  390. // do not use foreach as a manifest could contain manifests...
  391. for (int i=0; i < manifests.Count; i++) {
  392. Manifest manifest = new Manifest ((manifests [i] as XmlDocument).DocumentElement);
  393. if (! CheckReferenceIntegrity (manifest.References))
  394. return null;
  395. }
  396. }
  397. return key;
  398. }
  399. // Is the signature (over SignedInfo) valid ?
  400. private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
  401. {
  402. if (key == null)
  403. return false;
  404. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
  405. if (sd == null)
  406. return false;
  407. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  408. if (verifier == null)
  409. return false;
  410. try {
  411. verifier.SetKey (key);
  412. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  413. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  414. // get the hash of the C14N SignedInfo element
  415. MemoryStream ms = (MemoryStream) SignedInfoTransformed ();
  416. byte[] digest = hash.ComputeHash (ms);
  417. return verifier.VerifySignature (digest, m_signature.SignatureValue);
  418. }
  419. catch {
  420. // e.g. SignatureMethod != AsymmetricAlgorithm type
  421. return false;
  422. }
  423. }
  424. private bool Compare (byte[] expected, byte[] actual)
  425. {
  426. bool result = ((expected != null) && (actual != null));
  427. if (result) {
  428. int l = expected.Length;
  429. result = (l == actual.Length);
  430. if (result) {
  431. for (int i=0; i < l; i++) {
  432. if (expected[i] != actual[i])
  433. return false;
  434. }
  435. }
  436. }
  437. return result;
  438. }
  439. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  440. {
  441. if (macAlg == null)
  442. throw new ArgumentNullException ("macAlg");
  443. pkEnumerator = null;
  444. // Is the signature (over SignedInfo) valid ?
  445. Stream s = SignedInfoTransformed ();
  446. if (s == null)
  447. return false;
  448. byte[] actual = macAlg.ComputeHash (s);
  449. // HMAC signature may be partial
  450. if (m_signature.SignedInfo.SignatureLength != null) {
  451. int length = actual.Length;
  452. try {
  453. // SignatureLength is in bits
  454. length = (Int32.Parse (m_signature.SignedInfo.SignatureLength) >> 3);
  455. }
  456. catch {
  457. }
  458. if (length != actual.Length) {
  459. byte[] trunked = new byte [length];
  460. Buffer.BlockCopy (actual, 0, trunked, 0, length);
  461. actual = trunked;
  462. }
  463. }
  464. if (Compare (m_signature.SignatureValue, actual)) {
  465. // some parts may need to be downloaded
  466. // so where doing it last
  467. return CheckReferenceIntegrity (m_signature.SignedInfo.References);
  468. }
  469. return false;
  470. }
  471. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  472. {
  473. signingKey = CheckSignatureInternal (null);
  474. return (signingKey != null);
  475. }
  476. public void ComputeSignature ()
  477. {
  478. if (key != null) {
  479. // required before hashing
  480. m_signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  481. DigestReferences ();
  482. AsymmetricSignatureFormatter signer = null;
  483. // in need for a CryptoConfig factory
  484. if (key is DSA)
  485. signer = new DSASignatureFormatter (key);
  486. else if (key is RSA)
  487. signer = new RSAPKCS1SignatureFormatter (key);
  488. if (signer != null) {
  489. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
  490. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  491. // get the hash of the C14N SignedInfo element
  492. byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
  493. signer.SetHashAlgorithm ("SHA1");
  494. m_signature.SignatureValue = signer.CreateSignature (digest);
  495. }
  496. }
  497. }
  498. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  499. {
  500. if (macAlg == null)
  501. throw new ArgumentNullException ("macAlg");
  502. if (macAlg is HMACSHA1) {
  503. DigestReferences ();
  504. m_signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  505. m_signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  506. }
  507. else
  508. throw new CryptographicException ("unsupported algorithm");
  509. }
  510. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  511. {
  512. // this works only if there's a DTD or XSD available to define the ID
  513. XmlElement xel = document.GetElementById (idValue);
  514. if (xel == null) {
  515. // search an "undefined" ID
  516. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  517. }
  518. return xel;
  519. }
  520. // According to book ".NET Framework Security" this method
  521. // iterates all possible keys then return null
  522. protected virtual AsymmetricAlgorithm GetPublicKey ()
  523. {
  524. if (m_signature.KeyInfo == null)
  525. return null;
  526. if (pkEnumerator == null) {
  527. pkEnumerator = m_signature.KeyInfo.GetEnumerator ();
  528. }
  529. if (pkEnumerator.MoveNext ()) {
  530. AsymmetricAlgorithm key = null;
  531. KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
  532. if (kic is DSAKeyValue)
  533. key = DSA.Create ();
  534. else if (kic is RSAKeyValue)
  535. key = RSA.Create ();
  536. if (key != null) {
  537. key.FromXmlString (kic.GetXml ().InnerXml);
  538. return key;
  539. }
  540. }
  541. return null;
  542. }
  543. public XmlElement GetXml ()
  544. {
  545. return m_signature.GetXml ();
  546. }
  547. public void LoadXml (XmlElement value)
  548. {
  549. if (value == null)
  550. throw new ArgumentNullException ("value");
  551. signatureElement = value;
  552. m_signature.LoadXml (value);
  553. }
  554. #if NET_1_1
  555. [ComVisible (false)]
  556. public XmlResolver Resolver {
  557. set { xmlResolver = value; }
  558. }
  559. #endif
  560. }
  561. }