SignedXml.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. private Signature signature;
  22. private AsymmetricAlgorithm key;
  23. private string keyName;
  24. private XmlDocument envdoc;
  25. private IEnumerator pkEnumerator;
  26. private XmlElement signatureElement;
  27. private Hashtable hashes;
  28. #if NET_1_0
  29. private XmlResolver xmlResolver = new XmlUrlResolver ();
  30. #else
  31. // FIXME: later
  32. private XmlResolver xmlResolver = new XmlUrlResolver ();
  33. // private XmlResolver xmlResolver = new XmlSecureResolver (new XmlUrlResolver (), new Evidence ());
  34. #endif
  35. private ArrayList manifests;
  36. public SignedXml ()
  37. {
  38. signature = new Signature ();
  39. 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 signature.KeyInfo; }
  65. set { signature.KeyInfo = value; }
  66. }
  67. public Signature Signature {
  68. get { return signature; }
  69. }
  70. public string SignatureLength {
  71. get { return signature.SignedInfo.SignatureLength; }
  72. }
  73. public string SignatureMethod {
  74. get { return signature.SignedInfo.SignatureMethod; }
  75. }
  76. public byte[] SignatureValue {
  77. get { return signature.SignatureValue; }
  78. }
  79. public SignedInfo SignedInfo {
  80. get { return 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 keyName; }
  89. set { keyName = value; }
  90. }
  91. public void AddObject (DataObject dataObject)
  92. {
  93. signature.AddObject (dataObject);
  94. }
  95. public void AddReference (Reference reference)
  96. {
  97. 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 ("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("incomplete")]
  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. if (r.Uri [0] == '#') {
  187. foreach (DataObject obj in signature.ObjectList) {
  188. if ("#" + obj.Id == r.Uri) {
  189. XmlElement xel = obj.GetXml ();
  190. doc.LoadXml (xel.OuterXml);
  191. /*
  192. foreach (XmlAttribute attr in xel.SelectNodes ("namespace::*")) {
  193. if (attr.LocalName == "xml")
  194. continue;
  195. if (attr.OwnerElement == xel)
  196. continue;
  197. doc.DocumentElement.SetAttributeNode (doc.ImportNode (attr, true) as XmlAttribute);
  198. }
  199. */
  200. FixupNamespaceNodes (xel, doc.DocumentElement);
  201. break;
  202. }
  203. }
  204. }
  205. else if (xmlResolver != null) {
  206. // TODO: test but doc says that Resolver = null -> no access
  207. try {
  208. // no way to know if valid without throwing an exception
  209. Uri uri = new Uri (r.Uri);
  210. s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
  211. }
  212. catch {
  213. // may still be a local file (and maybe not xml)
  214. s = File.OpenRead (r.Uri);
  215. }
  216. }
  217. }
  218. if (r.TransformChain.Count > 0) {
  219. foreach (Transform t in r.TransformChain) {
  220. if (s == null) {
  221. s = ApplyTransform (t, doc);
  222. }
  223. else {
  224. t.LoadInput (s);
  225. object o = t.GetOutput ();
  226. if (o is Stream)
  227. s = (Stream) o;
  228. else
  229. s = CanonicalizeOutput (o);
  230. }
  231. }
  232. }
  233. else if (s == null) {
  234. // we must not C14N references from outside the document
  235. // e.g. non-xml documents
  236. if (r.Uri [0] != '#') {
  237. s = new MemoryStream ();
  238. doc.Save (s);
  239. }
  240. else {
  241. // apply default C14N transformation
  242. s = ApplyTransform (new XmlDsigC14NTransform (), doc);
  243. }
  244. }
  245. HashAlgorithm digest = GetHash (r.DigestMethod);
  246. return digest.ComputeHash (s);
  247. }
  248. private void DigestReferences ()
  249. {
  250. // we must tell each reference which hash algorithm to use
  251. // before asking for the SignedInfo XML !
  252. foreach (Reference r in signature.SignedInfo.References) {
  253. // assume SHA-1 if nothing is specified
  254. if (r.DigestMethod == null)
  255. r.DigestMethod = XmlDsigSHA1Url;
  256. r.DigestValue = GetReferenceHash (r);
  257. }
  258. }
  259. private Transform GetC14NMethod ()
  260. {
  261. Transform t = (Transform) CryptoConfig.CreateFromName (signature.SignedInfo.CanonicalizationMethod);
  262. if (t == null)
  263. throw new CryptographicException ("Unknown Canonicalization Method {0}", signature.SignedInfo.CanonicalizationMethod);
  264. return t;
  265. }
  266. private Stream SignedInfoTransformed ()
  267. {
  268. Transform t = GetC14NMethod ();
  269. if (signatureElement == null) {
  270. // when creating signatures
  271. XmlDocument doc = new XmlDocument ();
  272. doc.PreserveWhitespace = true;
  273. doc.LoadXml (signature.SignedInfo.GetXml ().OuterXml);
  274. t.LoadInput (doc);
  275. }
  276. else {
  277. // when verifying signatures
  278. // TODO - check signature.SignedInfo.Id
  279. XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
  280. StringWriter sw = new StringWriter ();
  281. XmlTextWriter xtw = new XmlTextWriter (sw);
  282. xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI);
  283. // context namespace nodes (except for "xmlns:xml")
  284. XmlNodeList nl = el.SelectNodes ("namespace::*");
  285. foreach (XmlAttribute attr in nl) {
  286. if (attr.ParentNode == el)
  287. continue;
  288. if (attr.LocalName == "xml")
  289. continue;
  290. attr.WriteTo (xtw);
  291. }
  292. foreach (XmlNode attr in el.Attributes)
  293. attr.WriteTo (xtw);
  294. foreach (XmlNode n in el.ChildNodes)
  295. n.WriteTo (xtw);
  296. xtw.WriteEndElement ();
  297. byte [] si = Encoding.UTF8.GetBytes (sw.ToString ());
  298. MemoryStream ms = new MemoryStream ();
  299. ms.Write (si, 0, si.Length);
  300. ms.Position = 0;
  301. t.LoadInput (ms);
  302. }
  303. // C14N and C14NWithComments always return a Stream in GetOutput
  304. return (Stream) t.GetOutput ();
  305. }
  306. // reuse hash - most document will always use the same hash
  307. private HashAlgorithm GetHash (string algorithm)
  308. {
  309. HashAlgorithm hash = (HashAlgorithm) hashes [algorithm];
  310. if (hash == null) {
  311. hash = HashAlgorithm.Create (algorithm);
  312. if (hash == null)
  313. throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm);
  314. hashes.Add (algorithm, hash);
  315. // now ready to be used
  316. }
  317. else {
  318. // important before reusing an hash object
  319. hash.Initialize ();
  320. }
  321. return hash;
  322. }
  323. public bool CheckSignature ()
  324. {
  325. return (CheckSignatureInternal (null) != null);
  326. }
  327. private bool CheckReferenceIntegrity (ArrayList referenceList)
  328. {
  329. if (referenceList == null)
  330. return false;
  331. // check digest (hash) for every reference
  332. foreach (Reference r in referenceList) {
  333. // stop at first broken reference
  334. byte[] hash = GetReferenceHash (r);
  335. if (! Compare (r.DigestValue, hash))
  336. return false;
  337. }
  338. return true;
  339. }
  340. public bool CheckSignature (AsymmetricAlgorithm key)
  341. {
  342. if (key == null)
  343. throw new ArgumentNullException ("key");
  344. return (CheckSignatureInternal (key) != null);
  345. }
  346. private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
  347. {
  348. pkEnumerator = null;
  349. if (key != null) {
  350. // check with supplied key
  351. if (!CheckSignatureWithKey (key))
  352. return null;
  353. }
  354. else {
  355. if (Signature.KeyInfo == null)
  356. throw new CryptographicException ("At least one KeyInfo is required.");
  357. // no supplied key, iterates all KeyInfo
  358. while ((key = GetPublicKey ()) != null) {
  359. if (CheckSignatureWithKey (key)) {
  360. break;
  361. }
  362. }
  363. pkEnumerator = null;
  364. if (key == null)
  365. return null;
  366. }
  367. // some parts may need to be downloaded
  368. // so where doing it last
  369. if (! CheckReferenceIntegrity (signature.SignedInfo.References))
  370. return null;
  371. if (manifests != null) {
  372. // do not use foreach as a manifest could contain manifests...
  373. for (int i=0; i < manifests.Count; i++) {
  374. Manifest manifest = new Manifest ((manifests [i] as XmlDocument).DocumentElement);
  375. if (! CheckReferenceIntegrity (manifest.References))
  376. return null;
  377. }
  378. }
  379. return key;
  380. }
  381. // Is the signature (over SignedInfo) valid ?
  382. private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
  383. {
  384. if (key == null)
  385. return false;
  386. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  387. if (sd == null)
  388. return false;
  389. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  390. if (verifier == null)
  391. return false;
  392. try {
  393. verifier.SetKey (key);
  394. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  395. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  396. // get the hash of the C14N SignedInfo element
  397. MemoryStream ms = (MemoryStream) SignedInfoTransformed ();
  398. byte[] debug = ms.ToArray ();
  399. byte[] digest = hash.ComputeHash (ms);
  400. return verifier.VerifySignature (digest, signature.SignatureValue);
  401. }
  402. catch {
  403. // e.g. SignatureMethod != AsymmetricAlgorithm type
  404. return false;
  405. }
  406. }
  407. private bool Compare (byte[] expected, byte[] actual)
  408. {
  409. bool result = ((expected != null) && (actual != null));
  410. if (result) {
  411. int l = expected.Length;
  412. result = (l == actual.Length);
  413. if (result) {
  414. for (int i=0; i < l; i++) {
  415. if (expected[i] != actual[i])
  416. return false;
  417. }
  418. }
  419. }
  420. return result;
  421. }
  422. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  423. {
  424. if (macAlg == null)
  425. throw new ArgumentNullException ("macAlg");
  426. pkEnumerator = null;
  427. // Is the signature (over SignedInfo) valid ?
  428. Stream s = SignedInfoTransformed ();
  429. if (s == null)
  430. return false;
  431. byte[] actual = macAlg.ComputeHash (s);
  432. // HMAC signature may be partial
  433. if (signature.SignedInfo.SignatureLength != null) {
  434. int length = actual.Length;
  435. try {
  436. // SignatureLength is in bits
  437. length = (Int32.Parse (signature.SignedInfo.SignatureLength) >> 3);
  438. }
  439. catch {
  440. }
  441. if (length != actual.Length) {
  442. byte[] trunked = new byte [length];
  443. Buffer.BlockCopy (actual, 0, trunked, 0, length);
  444. actual = trunked;
  445. }
  446. }
  447. if (Compare (signature.SignatureValue, actual)) {
  448. // some parts may need to be downloaded
  449. // so where doing it last
  450. return CheckReferenceIntegrity (signature.SignedInfo.References);
  451. }
  452. return false;
  453. }
  454. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  455. {
  456. signingKey = CheckSignatureInternal (null);
  457. return (signingKey != null);
  458. }
  459. public void ComputeSignature ()
  460. {
  461. if (key != null) {
  462. // required before hashing
  463. signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  464. DigestReferences ();
  465. AsymmetricSignatureFormatter signer = null;
  466. // in need for a CryptoConfig factory
  467. if (key is DSA)
  468. signer = new DSASignatureFormatter (key);
  469. else if (key is RSA)
  470. signer = new RSAPKCS1SignatureFormatter (key);
  471. if (signer != null) {
  472. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  473. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  474. // get the hash of the C14N SignedInfo element
  475. byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
  476. signer.SetHashAlgorithm ("SHA1");
  477. signature.SignatureValue = signer.CreateSignature (digest);
  478. }
  479. }
  480. }
  481. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  482. {
  483. if (macAlg == null)
  484. throw new ArgumentNullException ("macAlg");
  485. if (macAlg is HMACSHA1) {
  486. DigestReferences ();
  487. signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  488. signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  489. }
  490. else
  491. throw new CryptographicException ("unsupported algorithm");
  492. }
  493. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  494. {
  495. // this works only if there's a DTD or XSD available to define the ID
  496. XmlElement xel = document.GetElementById (idValue);
  497. if (xel == null) {
  498. // search an "undefined" ID
  499. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  500. }
  501. return xel;
  502. }
  503. // According to book ".NET Framework Security" this method
  504. // iterates all possible keys then return null
  505. protected virtual AsymmetricAlgorithm GetPublicKey ()
  506. {
  507. if (signature.KeyInfo == null)
  508. return null;
  509. if (pkEnumerator == null) {
  510. pkEnumerator = signature.KeyInfo.GetEnumerator ();
  511. }
  512. if (pkEnumerator.MoveNext ()) {
  513. AsymmetricAlgorithm key = null;
  514. KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
  515. if (kic is DSAKeyValue)
  516. key = DSA.Create ();
  517. else if (kic is RSAKeyValue)
  518. key = RSA.Create ();
  519. if (key != null) {
  520. key.FromXmlString (kic.GetXml ().InnerXml);
  521. return key;
  522. }
  523. }
  524. return null;
  525. }
  526. public XmlElement GetXml ()
  527. {
  528. return signature.GetXml ();
  529. }
  530. public void LoadXml (XmlElement value)
  531. {
  532. if (value == null)
  533. throw new ArgumentNullException ("value");
  534. signatureElement = value;
  535. signature.LoadXml (value);
  536. }
  537. #if ! NET_1_0
  538. [MonoTODO("property not (yet) used in class")]
  539. [ComVisible(false)]
  540. public XmlResolver Resolver {
  541. set { xmlResolver = value; }
  542. }
  543. #endif
  544. }
  545. }