SignedXml.cs 17 KB

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