SignedXml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
  192. StringWriter sw = new StringWriter ();
  193. XmlTextWriter xtw = new XmlTextWriter (sw);
  194. xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI);
  195. // context namespace nodes (except for "xmlns:xml")
  196. XmlNodeList nl = el.SelectNodes ("namespace::*");
  197. foreach (XmlAttribute attr in nl) {
  198. if (attr.ParentNode == el)
  199. continue;
  200. if (attr.LocalName == "xml")
  201. continue;
  202. attr.WriteTo (xtw);
  203. }
  204. foreach (XmlNode attr in el.Attributes)
  205. attr.WriteTo (xtw);
  206. foreach (XmlNode n in el.ChildNodes)
  207. n.WriteTo (xtw);
  208. xtw.WriteEndElement ();
  209. byte [] si = Encoding.UTF8.GetBytes (sw.ToString ());
  210. MemoryStream ms = new MemoryStream ();
  211. ms.Write (si, 0, si.Length);
  212. ms.Position = 0;
  213. t.LoadInput (ms);
  214. }
  215. // C14N and C14NWithComments always return a Stream in GetOutput
  216. return (Stream) t.GetOutput ();
  217. }
  218. /*
  219. private void CollectDescendants (XmlNode n, ArrayList al)
  220. {
  221. switch (n.NodeType) {
  222. case XmlNodeType.EntityReference:
  223. break;
  224. default:
  225. al.Add (n);
  226. break;
  227. }
  228. if (n.Attributes != null)
  229. foreach (XmlAttribute a in n.Attributes)
  230. al.Add (a);
  231. foreach (XmlNode c in n.ChildNodes)
  232. CollectDescendants (c, al);
  233. }
  234. */
  235. // reuse hash - most document will always use the same hash
  236. private HashAlgorithm GetHash (string algorithm)
  237. {
  238. HashAlgorithm hash = (HashAlgorithm) hashes [algorithm];
  239. if (hash == null) {
  240. hash = HashAlgorithm.Create (algorithm);
  241. if (hash == null)
  242. throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm);
  243. hashes.Add (algorithm, hash);
  244. // now ready to be used
  245. }
  246. else {
  247. // important before reusing an hash object
  248. hash.Initialize ();
  249. }
  250. return hash;
  251. }
  252. public bool CheckSignature ()
  253. {
  254. return (CheckSignatureInternal (null) != null);
  255. }
  256. private bool CheckReferenceIntegrity ()
  257. {
  258. // check digest (hash) for every reference
  259. foreach (Reference r in signature.SignedInfo.References) {
  260. // stop at first broken reference
  261. if (! Compare (r.DigestValue, GetReferenceHash (r)))
  262. return false;
  263. }
  264. return true;
  265. }
  266. public bool CheckSignature (AsymmetricAlgorithm key)
  267. {
  268. if (key == null)
  269. throw new ArgumentNullException ("key");
  270. return (CheckSignatureInternal (key) != null);
  271. }
  272. private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
  273. {
  274. pkEnumerator = null;
  275. if (key != null) {
  276. // check with supplied key
  277. if (!CheckSignatureWithKey (key))
  278. return null;
  279. }
  280. else {
  281. // no supplied key, iterates all KeyInfo
  282. while ((key = GetPublicKey ()) != null) {
  283. if (CheckSignatureWithKey (key)) {
  284. break;
  285. }
  286. }
  287. if (key == null)
  288. throw new CryptographicException ("No public key found to verify the signature.");
  289. }
  290. // some parts may need to be downloaded
  291. // so where doing it last
  292. return (CheckReferenceIntegrity () ? key : null);
  293. }
  294. // Is the signature (over SignedInfo) valid ?
  295. private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
  296. {
  297. if (key == null)
  298. return false;
  299. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  300. if (sd == null)
  301. return false;
  302. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  303. if (verifier == null)
  304. return false;
  305. verifier.SetKey (key);
  306. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  307. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  308. // get the hash of the C14N SignedInfo element
  309. byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
  310. return verifier.VerifySignature (digest, signature.SignatureValue);
  311. }
  312. private bool Compare (byte[] expected, byte[] actual)
  313. {
  314. bool result = ((expected != null) && (actual != null));
  315. if (result) {
  316. int l = expected.Length;
  317. result = (l == actual.Length);
  318. if (result) {
  319. for (int i=0; i < l; i++) {
  320. if (expected[i] != actual[i])
  321. return false;
  322. }
  323. }
  324. }
  325. return result;
  326. }
  327. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  328. {
  329. if (macAlg == null)
  330. throw new ArgumentNullException ("macAlg");
  331. pkEnumerator = null;
  332. // Is the signature (over SignedInfo) valid ?
  333. Stream s = SignedInfoTransformed ();
  334. if (s == null)
  335. return false;
  336. byte[] actual = macAlg.ComputeHash (s);
  337. // HMAC signature may be partial
  338. if (signature.SignedInfo.SignatureLength != null) {
  339. int length = actual.Length;
  340. try {
  341. // SignatureLength is in bits
  342. length = (Int32.Parse (signature.SignedInfo.SignatureLength) >> 3);
  343. }
  344. catch {
  345. }
  346. if (length != actual.Length) {
  347. byte[] trunked = new byte [length];
  348. Buffer.BlockCopy (actual, 0, trunked, 0, length);
  349. actual = trunked;
  350. }
  351. }
  352. if (Compare (signature.SignatureValue, actual)) {
  353. // some parts may need to be downloaded
  354. // so where doing it last
  355. return CheckReferenceIntegrity ();
  356. }
  357. return false;
  358. }
  359. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  360. {
  361. signingKey = CheckSignatureInternal (null);
  362. return (signingKey != null);
  363. }
  364. public void ComputeSignature ()
  365. {
  366. if (key != null) {
  367. // required before hashing
  368. signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  369. DigestReferences ();
  370. AsymmetricSignatureFormatter signer = null;
  371. // in need for a CryptoConfig factory
  372. if (key is DSA)
  373. signer = new DSASignatureFormatter (key);
  374. else if (key is RSA)
  375. signer = new RSAPKCS1SignatureFormatter (key);
  376. if (signer != null) {
  377. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  378. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  379. // get the hash of the C14N SignedInfo element
  380. byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
  381. signer.SetHashAlgorithm ("SHA1");
  382. signature.SignatureValue = signer.CreateSignature (digest);
  383. }
  384. }
  385. }
  386. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  387. {
  388. if (macAlg == null)
  389. throw new ArgumentNullException ("macAlg");
  390. if (macAlg is HMACSHA1) {
  391. DigestReferences ();
  392. signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  393. signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  394. }
  395. else
  396. throw new CryptographicException ("unsupported algorithm");
  397. }
  398. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  399. {
  400. // this works only if there's a DTD or XSD available to define the ID
  401. XmlElement xel = document.GetElementById (idValue);
  402. if (xel == null) {
  403. // search an "undefined" ID
  404. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  405. }
  406. return xel;
  407. }
  408. // According to book ".NET Framework Security" this method
  409. // iterates all possible keys then return null
  410. protected virtual AsymmetricAlgorithm GetPublicKey ()
  411. {
  412. if (signature.KeyInfo == null)
  413. return null;
  414. if (pkEnumerator == null) {
  415. pkEnumerator = signature.KeyInfo.GetEnumerator ();
  416. }
  417. if (pkEnumerator.MoveNext ()) {
  418. AsymmetricAlgorithm key = null;
  419. KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
  420. if (kic is DSAKeyValue)
  421. key = DSA.Create ();
  422. else if (kic is RSAKeyValue)
  423. key = RSA.Create ();
  424. if (key != null) {
  425. key.FromXmlString (kic.GetXml ().InnerXml);
  426. return key;
  427. }
  428. }
  429. return null;
  430. }
  431. public XmlElement GetXml ()
  432. {
  433. return signature.GetXml ();
  434. }
  435. public void LoadXml (XmlElement value)
  436. {
  437. if (value == null)
  438. throw new ArgumentNullException ("value");
  439. signatureElement = value;
  440. signature.LoadXml (value);
  441. }
  442. #if ! NET_1_0
  443. private XmlResolver xmlResolver;
  444. [MonoTODO("property not (yet) used in class")]
  445. [ComVisible(false)]
  446. public XmlResolver Resolver {
  447. set { xmlResolver = value; }
  448. }
  449. #endif
  450. }
  451. }