2 // AuthenticodeDeformatter.cs: Authenticode signature validator
5 // Sebastien Pouliot <sebastien@ximian.com>
7 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Runtime.InteropServices;
33 using System.Security.Cryptography;
36 using Mono.Security.X509;
38 namespace Mono.Security.Authenticode {
41 // a. http://www.cs.auckland.ac.nz/~pgut001/pubs/authenticode.txt
48 class AuthenticodeDeformatter : AuthenticodeBase {
50 private string filename;
52 private X509CertificateCollection coll;
53 private ASN1 signedHash;
54 private DateTime timestamp;
55 private X509Certificate signingCertificate;
57 private bool trustedRoot;
58 private bool trustedTimestampRoot;
61 private X509Chain signerChain;
62 private X509Chain timestampChain;
64 public AuthenticodeDeformatter () : base ()
67 signerChain = new X509Chain ();
68 timestampChain = new X509Chain ();
71 public AuthenticodeDeformatter (string fileName) : this ()
76 public string FileName {
77 get { return filename; }
81 CheckSignature (value);
91 if (signedHash == null)
93 return (byte[]) signedHash.Value.Clone ();
105 public bool IsTrusted ()
112 if (signingCertificate == null) {
117 if ((signerChain.Root == null) || !trustedRoot) {
122 if (timestamp != DateTime.MinValue) {
123 if ((timestampChain.Root == null) || !trustedTimestampRoot) {
128 // check that file was timestamped when certificates were valid
129 if (!signingCertificate.WasCurrent (Timestamp)) {
134 else if (!signingCertificate.IsCurrent) {
135 // signature only valid if the certificate is valid
144 public byte[] Signature {
148 return (byte[]) entry.Clone ();
152 public DateTime Timestamp {
153 get { return timestamp; }
156 public X509CertificateCollection Certificates {
160 public X509Certificate SigningCertificate {
161 get { return signingCertificate; }
164 private bool CheckSignature (string fileName)
167 base.Open (filename);
168 entry = base.GetSecurityEntry ();
170 // no signature is present
176 PKCS7.ContentInfo ci = new PKCS7.ContentInfo (entry);
177 if (ci.ContentType != PKCS7.Oid.signedData) {
182 PKCS7.SignedData sd = new PKCS7.SignedData (ci.Content);
183 if (sd.ContentInfo.ContentType != spcIndirectDataContext) {
188 coll = sd.Certificates;
190 ASN1 spc = sd.ContentInfo.Content;
191 signedHash = spc [0][1][1];
193 HashAlgorithm ha = null;
194 switch (signedHash.Length) {
196 ha = HashAlgorithm.Create ("MD5");
200 ha = HashAlgorithm.Create ("SHA1");
210 if (!signedHash.CompareValue (hash))
213 // messageDigest is a hash of spcIndirectDataContext (which includes the file hash)
214 byte[] spcIDC = spc [0].Value;
215 ha.Initialize (); // re-using hash instance
216 byte[] messageDigest = ha.ComputeHash (spcIDC);
218 return VerifySignature (sd, messageDigest, ha);
221 private bool CompareIssuerSerial (string issuer, byte[] serial, X509Certificate x509)
223 if (issuer != x509.IssuerName)
225 if (serial.Length != x509.SerialNumber.Length)
227 // MS shows the serial number inversed (so is Mono.Security.X509.X509Certificate)
228 int n = serial.Length;
229 for (int i=0; i < serial.Length; i++) {
230 if (serial [i] != x509.SerialNumber [--n])
237 //private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName)
238 private bool VerifySignature (PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha)
240 string contentType = null;
241 ASN1 messageDigest = null;
242 string spcStatementType = null;
243 string spcSpOpusInfo = null;
245 for (int i=0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++) {
246 ASN1 attr = (ASN1) sd.SignerInfo.AuthenticatedAttributes [i];
247 string oid = ASN1Convert.ToOid (attr[0]);
249 case "1.2.840.113549.1.9.3":
251 contentType = ASN1Convert.ToOid (attr[1][0]);
253 case "1.2.840.113549.1.9.4":
255 messageDigest = attr[1][0];
257 case "1.3.6.1.4.1.311.2.1.11":
258 // spcStatementType (Microsoft code signing)
260 // - individualCodeSigning (1 3 6 1 4 1 311 2 1 21)
261 // - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22)
262 spcStatementType = ASN1Convert.ToOid (attr[1][0][0]);
264 case "1.3.6.1.4.1.311.2.1.12":
265 // spcSpOpusInfo (Microsoft code signing)
267 spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value);
269 catch (NullReferenceException) {
270 spcSpOpusInfo = null;
277 if (contentType != spcIndirectDataContext)
280 // verify message digest
281 if (messageDigest == null)
283 if (!messageDigest.CompareValue (calculatedMessageDigest))
287 string hashOID = CryptoConfig.MapNameToOID (ha.ToString ());
289 // change to SET OF (not [0]) as per PKCS #7 1.5
290 ASN1 aa = new ASN1 (0x31);
291 foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes)
294 byte[] p7hash = ha.ComputeHash (aa.GetBytes ());
296 byte[] signature = sd.SignerInfo.Signature;
297 // we need to find the specified certificate
298 string issuer = sd.SignerInfo.IssuerName;
299 byte[] serial = sd.SignerInfo.SerialNumber;
300 foreach (X509Certificate x509 in coll) {
301 if (CompareIssuerSerial (issuer, serial, x509)) {
302 // don't verify is key size don't match
303 if (x509.PublicKey.Length > (signature.Length >> 3)) {
304 RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
305 if (rsa.VerifyHash (p7hash, hashOID, signature)) {
306 signerChain.LoadCertificates (coll);
307 trustedRoot = signerChain.Build (x509);
308 signingCertificate = x509;
315 for (int i=0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++) {
316 ASN1 attr = (ASN1) sd.SignerInfo.UnauthenticatedAttributes [i];
317 string oid = ASN1Convert.ToOid (attr [0]);
319 case PKCS7.Oid.countersignature:
322 // countersignature (1 2 840 113549 1 9 6)
324 PKCS7.SignerInfo cs = new PKCS7.SignerInfo (attr [1]);
325 trustedTimestampRoot = VerifyCounterSignature (cs, signature);
328 // we don't support other unauthenticated attributes
333 return (trustedRoot && trustedTimestampRoot);
336 private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature)
345 string contentType = null;
346 ASN1 messageDigest = null;
347 for (int i=0; i < cs.AuthenticatedAttributes.Count; i++) {
350 ASN1 attr = (ASN1) cs.AuthenticatedAttributes [i];
351 string oid = ASN1Convert.ToOid (attr[0]);
353 case "1.2.840.113549.1.9.3":
355 contentType = ASN1Convert.ToOid (attr[1][0]);
357 case "1.2.840.113549.1.9.4":
359 messageDigest = attr[1][0];
361 case "1.2.840.113549.1.9.5":
364 // signingTime (1 2 840 113549 1 9 5)
366 // UTCTime '030124013651Z'
369 timestamp = ASN1Convert.ToDateTime (attr[1][0]);
376 if (contentType != PKCS7.Oid.data)
379 // verify message digest
380 if (messageDigest == null)
382 // TODO: must be read from the ASN.1 structure
383 string hashName = null;
384 switch (messageDigest.Length) {
392 HashAlgorithm ha = HashAlgorithm.Create (hashName);
393 if (!messageDigest.CompareValue (ha.ComputeHash (signature)))
397 byte[] counterSignature = cs.Signature;
398 string hashOID = CryptoConfig.MapNameToOID (hashName);
400 // change to SET OF (not [0]) as per PKCS #7 1.5
401 ASN1 aa = new ASN1 (0x31);
402 foreach (ASN1 a in cs.AuthenticatedAttributes)
404 byte[] p7hash = ha.ComputeHash (aa.GetBytes ());
406 // we need to try all certificates
407 string issuer = cs.IssuerName;
408 byte[] serial = cs.SerialNumber;
409 foreach (X509Certificate x509 in coll) {
410 if (CompareIssuerSerial (issuer, serial, x509)) {
411 // don't verify if key size don't match
412 if (x509.PublicKey.Length > (counterSignature.Length >> 3)) {
413 RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
414 if (rsa.VerifyHash (p7hash, hashOID, counterSignature)) {
415 timestampChain.LoadCertificates (coll);
416 return (timestampChain.Build (x509));
421 // no certificate can verify this signature!
425 private void Reset ()
431 signingCertificate = null;
434 trustedTimestampRoot = false;
435 signerChain.Reset ();
436 timestampChain.Reset ();
437 timestamp = DateTime.MinValue;