SignedXml.cs 14 KB

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