SignedXml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. public bool CheckSignature ()
  219. {
  220. return (CheckSignatureInternal (null) != null);
  221. }
  222. private bool CheckReferenceIntegrity ()
  223. {
  224. // check digest (hash) for every reference
  225. foreach (Reference r in signature.SignedInfo.References) {
  226. // stop at first broken reference
  227. if (! Compare (r.DigestValue, GetReferenceHash (r)))
  228. return false;
  229. }
  230. return true;
  231. }
  232. public bool CheckSignature (AsymmetricAlgorithm key)
  233. {
  234. if (key == null)
  235. throw new ArgumentNullException ("key");
  236. return (CheckSignatureInternal (key) != null);
  237. }
  238. private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
  239. {
  240. pkEnumerator = null;
  241. if (key != null) {
  242. // check with supplied key
  243. if (!CheckSignatureWithKey (key))
  244. return null;
  245. }
  246. else {
  247. // no supplied key, iterates all KeyInfo
  248. while ((key = GetPublicKey ()) != null) {
  249. if (CheckSignatureWithKey (key)) {
  250. break;
  251. }
  252. }
  253. if (key == null)
  254. throw new CryptographicException ("No public key found to verify the signature.");
  255. }
  256. // some parts may need to be downloaded
  257. // so where doing it last
  258. return (CheckReferenceIntegrity () ? key : null);
  259. }
  260. // Is the signature (over SignedInfo) valid ?
  261. private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
  262. {
  263. if (key == null)
  264. return false;
  265. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  266. if (sd == null)
  267. return false;
  268. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  269. if (verifier == null)
  270. return false;
  271. verifier.SetKey (key);
  272. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  273. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  274. // get the hash of the C14N SignedInfo element
  275. byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
  276. return verifier.VerifySignature (digest, signature.SignatureValue);
  277. }
  278. private bool Compare (byte[] expected, byte[] actual)
  279. {
  280. bool result = ((expected != null) && (actual != null));
  281. if (result) {
  282. int l = expected.Length;
  283. result = (l == actual.Length);
  284. if (result) {
  285. for (int i=0; i < l; i++) {
  286. if (expected[i] != actual[i])
  287. return false;
  288. }
  289. }
  290. }
  291. return result;
  292. }
  293. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  294. {
  295. if (macAlg == null)
  296. throw new ArgumentNullException ("macAlg");
  297. pkEnumerator = null;
  298. // Is the signature (over SignedInfo) valid ?
  299. Stream s = SignedInfoTransformed ();
  300. if (s == null)
  301. return false;
  302. byte[] actual = macAlg.ComputeHash (s);
  303. // HMAC signature may be partial
  304. if (signature.SignedInfo.SignatureLength != null) {
  305. int length = actual.Length;
  306. try {
  307. // SignatureLength is in bits
  308. length = (Int32.Parse (signature.SignedInfo.SignatureLength) >> 3);
  309. }
  310. catch {
  311. }
  312. if (length != actual.Length) {
  313. byte[] trunked = new byte [length];
  314. Buffer.BlockCopy (actual, 0, trunked, 0, length);
  315. actual = trunked;
  316. }
  317. }
  318. if (Compare (signature.SignatureValue, actual)) {
  319. // some parts may need to be downloaded
  320. // so where doing it last
  321. return CheckReferenceIntegrity ();
  322. }
  323. return false;
  324. }
  325. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  326. {
  327. signingKey = CheckSignatureInternal (null);
  328. return (signingKey != null);
  329. }
  330. public void ComputeSignature ()
  331. {
  332. if (key != null) {
  333. // required before hashing
  334. signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  335. DigestReferences ();
  336. AsymmetricSignatureFormatter signer = null;
  337. // in need for a CryptoConfig factory
  338. if (key is DSA)
  339. signer = new DSASignatureFormatter (key);
  340. else if (key is RSA)
  341. signer = new RSAPKCS1SignatureFormatter (key);
  342. if (signer != null) {
  343. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  344. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  345. // get the hash of the C14N SignedInfo element
  346. byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
  347. signer.SetHashAlgorithm ("SHA1");
  348. signature.SignatureValue = signer.CreateSignature (digest);
  349. }
  350. }
  351. }
  352. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  353. {
  354. if (macAlg == null)
  355. throw new ArgumentNullException ("macAlg");
  356. if (macAlg is HMACSHA1) {
  357. DigestReferences ();
  358. signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  359. signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  360. }
  361. else
  362. throw new CryptographicException ("unsupported algorithm");
  363. }
  364. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  365. {
  366. // this works only if there's a DTD or XSD available to define the ID
  367. XmlElement xel = document.GetElementById (idValue);
  368. if (xel == null) {
  369. // search an "undefined" ID
  370. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  371. }
  372. return xel;
  373. }
  374. // According to book ".NET Framework Security" this method
  375. // iterates all possible keys then return null
  376. protected virtual AsymmetricAlgorithm GetPublicKey ()
  377. {
  378. if (signature.KeyInfo == null)
  379. return null;
  380. if (pkEnumerator == null) {
  381. pkEnumerator = signature.KeyInfo.GetEnumerator ();
  382. }
  383. if (pkEnumerator.MoveNext ()) {
  384. AsymmetricAlgorithm key = null;
  385. KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
  386. if (kic is DSAKeyValue)
  387. key = DSA.Create ();
  388. else if (kic is RSAKeyValue)
  389. key = RSA.Create ();
  390. if (key != null) {
  391. key.FromXmlString (kic.GetXml ().InnerXml);
  392. return key;
  393. }
  394. }
  395. return null;
  396. }
  397. public XmlElement GetXml ()
  398. {
  399. return signature.GetXml ();
  400. }
  401. public void LoadXml (XmlElement value)
  402. {
  403. if (value == null)
  404. throw new ArgumentNullException ("value");
  405. signatureElement = value;
  406. signature.LoadXml (value);
  407. }
  408. #if ! NET_1_0
  409. private XmlResolver xmlResolver;
  410. [MonoTODO("property not (yet) used in class")]
  411. [ComVisible(false)]
  412. public XmlResolver Resolver {
  413. set { xmlResolver = value; }
  414. }
  415. #endif
  416. }
  417. }