SignedXml.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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.Net;
  16. using System.Text;
  17. using System.Xml;
  18. namespace System.Security.Cryptography.Xml {
  19. public class SignedXml {
  20. private Signature signature;
  21. private AsymmetricAlgorithm key;
  22. private string keyName;
  23. private XmlDocument envdoc;
  24. private IEnumerator pkEnumerator;
  25. private XmlElement signatureElement;
  26. public SignedXml ()
  27. {
  28. signature = new Signature ();
  29. signature.SignedInfo = new SignedInfo ();
  30. }
  31. public SignedXml (XmlDocument document)
  32. {
  33. signature = new Signature ();
  34. signature.SignedInfo = new SignedInfo ();
  35. envdoc = document;
  36. }
  37. public SignedXml (XmlElement elem) : this ()
  38. {
  39. if (elem == null)
  40. throw new ArgumentNullException ("elem");
  41. signature = new Signature ();
  42. signature.SignedInfo = new SignedInfo ();
  43. }
  44. public const string XmlDsigCanonicalizationUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
  45. public const string XmlDsigCanonicalizationWithCommentsUrl = XmlDsigCanonicalizationUrl + "#WithComments";
  46. public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#";
  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 XmlDsigRSASHA1Url = XmlDsigNamespaceUrl + "rsa-sha1";
  51. public const string XmlDsigSHA1Url = XmlDsigNamespaceUrl + "sha1";
  52. public KeyInfo KeyInfo {
  53. get { return signature.KeyInfo; }
  54. set { signature.KeyInfo = value; }
  55. }
  56. public Signature Signature {
  57. get { return signature; }
  58. }
  59. public string SignatureLength {
  60. get { return signature.SignedInfo.SignatureLength; }
  61. }
  62. public string SignatureMethod {
  63. get { return signature.SignedInfo.SignatureMethod; }
  64. }
  65. public byte[] SignatureValue {
  66. get { return signature.SignatureValue; }
  67. }
  68. public SignedInfo SignedInfo {
  69. get { return signature.SignedInfo; }
  70. }
  71. public AsymmetricAlgorithm SigningKey {
  72. get { return key; }
  73. set { key = value; }
  74. }
  75. public string SigningKeyName {
  76. get { return keyName; }
  77. set { keyName = value; }
  78. }
  79. public void AddObject (DataObject dataObject)
  80. {
  81. signature.AddObject (dataObject);
  82. }
  83. public void AddReference (Reference reference)
  84. {
  85. signature.SignedInfo.AddReference (reference);
  86. }
  87. private Stream ApplyTransform (Transform t, XmlDocument input)
  88. {
  89. XmlDocument doc = (XmlDocument) input.Clone ();
  90. t.LoadInput (doc);
  91. if (t is XmlDsigEnvelopedSignatureTransform) {
  92. object o = t.GetOutput ();
  93. MemoryStream ms = new MemoryStream ();
  94. XmlTextWriter xw = new XmlTextWriter (ms, Encoding.UTF8);
  95. XmlDocument d = o as XmlDocument;
  96. if (d != null)
  97. d.Save (xw);
  98. else {
  99. XmlNodeList nl = (XmlNodeList) o;
  100. foreach (XmlNode n in nl)
  101. n.WriteTo (xw);
  102. }
  103. // don't close xw (and thus ms).
  104. return ms;
  105. }
  106. object obj = t.GetOutput ();
  107. if (obj is Stream)
  108. return (Stream) obj;
  109. else {
  110. // e.g. XmlDsigXPathTransform returns XmlNodeList
  111. // TODO - fix
  112. return null;
  113. }
  114. }
  115. private Stream ApplyTransform (Transform t, Stream s)
  116. {
  117. try {
  118. t.LoadInput (s);
  119. s = (Stream) t.GetOutput ();
  120. }
  121. catch (Exception e) {
  122. string temp = e.ToString (); // stop debugger
  123. }
  124. return s;
  125. }
  126. [MonoTODO("incomplete")]
  127. private byte[] GetReferenceHash (Reference r)
  128. {
  129. Stream s = null;
  130. XmlDocument doc = null;
  131. if (r.Uri == String.Empty) {
  132. doc = envdoc;
  133. }
  134. else {
  135. doc = new XmlDocument ();
  136. doc.PreserveWhitespace = true;
  137. if (r.Uri [0] == '#') {
  138. foreach (DataObject obj in signature.ObjectList) {
  139. if ("#" + obj.Id == r.Uri) {
  140. doc.LoadXml (obj.GetXml ().OuterXml);
  141. break;
  142. }
  143. }
  144. }
  145. else {
  146. if (r.Uri.EndsWith (".xml"))
  147. doc.Load (r.Uri);
  148. else {
  149. WebRequest req = WebRequest.Create (r.Uri);
  150. s = req.GetResponse ().GetResponseStream ();
  151. }
  152. }
  153. }
  154. if (r.TransformChain.Count > 0) {
  155. foreach (Transform t in r.TransformChain) {
  156. if (s == null)
  157. s = ApplyTransform (t, doc);
  158. else
  159. s = ApplyTransform (t, s);
  160. }
  161. }
  162. else if (s == null) {
  163. // apply default C14N transformation
  164. s = ApplyTransform (new XmlDsigC14NTransform (), doc);
  165. }
  166. // TODO: We should reuse the same hash object (when possible)
  167. HashAlgorithm hash = (HashAlgorithm) CryptoConfig.CreateFromName (r.DigestMethod);
  168. if (hash == null)
  169. throw new CryptographicException ("Unknown digest algorithm {0}", r.DigestMethod);
  170. return hash.ComputeHash (s);
  171. }
  172. private void DigestReferences ()
  173. {
  174. // we must tell each reference which hash algorithm to use
  175. // before asking for the SignedInfo XML !
  176. foreach (Reference r in signature.SignedInfo.References) {
  177. // assume SHA-1 if nothing is specified
  178. if (r.DigestMethod == null)
  179. r.DigestMethod = XmlDsigSHA1Url;
  180. r.DigestValue = GetReferenceHash (r);
  181. }
  182. }
  183. private Stream SignedInfoTransformed ()
  184. {
  185. Transform t = (Transform) CryptoConfig.CreateFromName (signature.SignedInfo.CanonicalizationMethod);
  186. if (t == null)
  187. throw new CryptographicException ("Unknown Canonicalization Method {0}", signature.SignedInfo.CanonicalizationMethod);
  188. XmlDocument doc = new XmlDocument ();
  189. doc.PreserveWhitespace = true;
  190. doc.LoadXml (signature.SignedInfo.GetXml ().OuterXml);
  191. return ApplyTransform (t, doc);
  192. // to make unit tests happy - no signature will ever validate with this code (unless generated by the same parser before signing)
  193. /* if (signatureElement != null) {
  194. // TODO - check signature.SignedInfo.Id
  195. XmlNodeList xnl = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI);
  196. t.LoadInput (xnl);
  197. }
  198. // C14N and C14NWithComments always return a Stream in GetOutput
  199. return (Stream) t.GetOutput ();*/
  200. }
  201. private byte[] Hash (string hashAlgorithm)
  202. {
  203. HashAlgorithm hash = HashAlgorithm.Create (hashAlgorithm);
  204. // get the hash of the C14N SignedInfo element
  205. return hash.ComputeHash (SignedInfoTransformed ());
  206. }
  207. public bool CheckSignature ()
  208. {
  209. return (CheckSignatureInternal (null) != null);
  210. }
  211. private bool CheckReferenceIntegrity ()
  212. {
  213. pkEnumerator = null;
  214. // check digest (hash) for every reference
  215. foreach (Reference r in signature.SignedInfo.References) {
  216. // stop at first broken reference
  217. if (! Compare (r.DigestValue, GetReferenceHash (r)))
  218. return false;
  219. }
  220. return true;
  221. }
  222. public bool CheckSignature (AsymmetricAlgorithm key)
  223. {
  224. if (key == null)
  225. throw new ArgumentNullException ("key");
  226. return (CheckSignatureInternal (key) != null);
  227. }
  228. private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
  229. {
  230. // Part 1: Are all references digest valid ?
  231. if (!CheckReferenceIntegrity ())
  232. return null;
  233. if (key != null) {
  234. // check with supplied key
  235. if (CheckSignatureWithKey (key))
  236. return key;
  237. }
  238. else {
  239. // no supplied key, iterates all KeyInfo
  240. while ((key = GetPublicKey ()) != null) {
  241. if (CheckSignatureWithKey (key))
  242. return key;
  243. }
  244. }
  245. return null;
  246. }
  247. // Is the signature (over SignedInfo) valid ?
  248. private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
  249. {
  250. if (key == null)
  251. return false;
  252. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  253. if (sd == null)
  254. return false;
  255. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  256. if (verifier == null)
  257. return false;
  258. verifier.SetKey (key);
  259. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  260. byte[] hash = Hash (sd.DigestAlgorithm);
  261. return verifier.VerifySignature (hash, signature.SignatureValue);
  262. }
  263. private bool Compare (byte[] expected, byte[] actual)
  264. {
  265. bool result = ((expected != null) && (actual != null));
  266. if (result) {
  267. int l = expected.Length;
  268. result = (l == actual.Length);
  269. if (result) {
  270. for (int i=0; i < l; i++) {
  271. if (expected[i] != actual[i])
  272. return false;
  273. }
  274. }
  275. }
  276. return result;
  277. }
  278. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  279. {
  280. if (macAlg == null)
  281. throw new ArgumentNullException ("macAlg");
  282. // Part 1: Are all references digest valid ?
  283. bool result = CheckReferenceIntegrity ();
  284. if (result) {
  285. // Part 2: Is the signature (over SignedInfo) valid ?
  286. Stream s = SignedInfoTransformed ();
  287. if (s == null)
  288. return false;
  289. byte[] actual = macAlg.ComputeHash (s);
  290. int length = actual.Length;
  291. // HMAC signature may be partial
  292. if (signature.SignedInfo.SignatureLength != null) {
  293. try {
  294. // SignatureLength is in bits
  295. length = (Int32.Parse (signature.SignedInfo.SignatureLength) >> 3);
  296. }
  297. catch {
  298. }
  299. }
  300. if (length != actual.Length) {
  301. byte[] trunked = new byte [length];
  302. Buffer.BlockCopy (actual, 0, trunked, 0, length);
  303. actual = trunked;
  304. }
  305. result = Compare (signature.SignatureValue, actual);
  306. }
  307. return result;
  308. }
  309. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  310. {
  311. signingKey = CheckSignatureInternal (null);
  312. return (signingKey != null);
  313. }
  314. public void ComputeSignature ()
  315. {
  316. if (key != null) {
  317. // required before hashing
  318. signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  319. DigestReferences ();
  320. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  321. // the hard part - C14Ning the KeyInfo
  322. byte[] hash = Hash (sd.DigestAlgorithm);
  323. AsymmetricSignatureFormatter signer = null;
  324. // in need for a CryptoConfig factory
  325. if (key is DSA)
  326. signer = new DSASignatureFormatter (key);
  327. else if (key is RSA)
  328. signer = new RSAPKCS1SignatureFormatter (key);
  329. if (signer != null) {
  330. signer.SetHashAlgorithm ("SHA1");
  331. signature.SignatureValue = signer.CreateSignature (hash);
  332. }
  333. }
  334. }
  335. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  336. {
  337. if (macAlg == null)
  338. throw new ArgumentNullException ("macAlg");
  339. if (macAlg is HMACSHA1) {
  340. DigestReferences ();
  341. signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  342. signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  343. }
  344. else
  345. throw new CryptographicException ("unsupported algorithm");
  346. }
  347. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  348. {
  349. // this works only if there's a DTD or XSD available to define the ID
  350. XmlElement xel = document.GetElementById (idValue);
  351. if (xel == null) {
  352. // search an "undefined" ID
  353. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  354. }
  355. return xel;
  356. }
  357. // According to book ".NET Framework Security" this method
  358. // iterates all possible keys then return null
  359. protected virtual AsymmetricAlgorithm GetPublicKey ()
  360. {
  361. if (pkEnumerator == null) {
  362. pkEnumerator = signature.KeyInfo.GetEnumerator ();
  363. }
  364. if (pkEnumerator.MoveNext ()) {
  365. AsymmetricAlgorithm key = null;
  366. KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
  367. if (kic is DSAKeyValue)
  368. key = DSA.Create ();
  369. else if (kic is RSAKeyValue)
  370. key = RSA.Create ();
  371. if (key != null) {
  372. key.FromXmlString (kic.GetXml ().InnerXml);
  373. return key;
  374. }
  375. }
  376. return null;
  377. }
  378. public XmlElement GetXml ()
  379. {
  380. return signature.GetXml ();
  381. }
  382. public void LoadXml (XmlElement value)
  383. {
  384. if (value == null)
  385. throw new ArgumentNullException ("value");
  386. signatureElement = value;
  387. signature.LoadXml (value);
  388. }
  389. #if ! NET_1_0
  390. private XmlResolver xmlResolver;
  391. [MonoTODO("property not (yet) used in class")]
  392. [ComVisible(false)]
  393. public XmlResolver Resolver {
  394. set { xmlResolver = value; }
  395. }
  396. #endif
  397. }
  398. }