SignedXml.cs 13 KB

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