public X509Certificate2ImplMono(byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { switch (X509Certificate2.GetCertContentType(rawData)) { case X509ContentType.Pkcs12: _cert = ImportPkcs12(rawData, password); break; case X509ContentType.Cert: case X509ContentType.Pkcs7: _cert = new MX.X509Certificate(rawData); break; #if !MONOTOUCH_WATCH case X509ContentType.Authenticode: AuthenticodeDeformatter ad = new AuthenticodeDeformatter(rawData); _cert = ad.SigningCertificate; if (_cert == null) { goto default; } break; #endif default: string msg = Locale.GetText("Unable to decode certificate."); throw new CryptographicException(msg); } }
public static X509Certificate CreateFromSignedFile(string filename) { try { AuthenticodeDeformatter a = new AuthenticodeDeformatter(filename); if (a.SigningCertificate != null) { #if !NET_2_0 // before 2.0 the signing certificate is returned only if the signature is valid if (a.Reason != 0) { string msg = String.Format(Locale.GetText( "Invalid digital signature on {0}, reason #{1}."), filename, a.Reason); throw new COMException(msg); } #endif return(new X509Certificate(a.SigningCertificate.RawData)); } } catch (SecurityException) { // don't wrap SecurityException into a COMException throw; } catch (Exception e) { string msg = Locale.GetText("Couldn't extract digital signature from {0}.", filename); throw new COMException(msg, e); } #if NET_2_0 throw new CryptographicException(Locale.GetText("{0} isn't signed.", filename)); #else // if no signature is present return an empty certificate byte[] cert = null; // must not confuse compiler about null ;) return(new X509Certificate(cert)); #endif }
void ImportAuthenticode(byte[] data) { if (data != null) { AuthenticodeDeformatter ad = new AuthenticodeDeformatter(data); Import(ad.SigningCertificate.RawData); } }
public X509ContentType GetCertContentType(byte[] rawData) { if ((rawData == null) || (rawData.Length == 0)) { throw new ArgumentException("rawData"); } if (rawData[0] == 0x30) { // ASN.1 SEQUENCE try { ASN1 data = new ASN1(rawData); // SEQUENCE / SEQUENCE / BITSTRING if (data.Count == 3 && data[0].Tag == 0x30 && data[1].Tag == 0x30 && data[2].Tag == 0x03) { return(X509ContentType.Cert); } // INTEGER / SEQUENCE / SEQUENCE if (data.Count == 3 && data[0].Tag == 0x02 && data[1].Tag == 0x30 && data[2].Tag == 0x30) { return(X509ContentType.Pkcs12); // note: Pfx == Pkcs12 } // check for PKCS#7 (count unknown but greater than 0) // SEQUENCE / OID (signedData) if (data.Count > 0 && data[0].Tag == 0x06 && data[0].CompareValue(signedData)) { return(X509ContentType.Pkcs7); } return(X509ContentType.Unknown); } catch (Exception) { return(X509ContentType.Unknown); } } else { string pem = Encoding.ASCII.GetString(rawData); int start = pem.IndexOf("-----BEGIN CERTIFICATE-----"); if (start >= 0) { return(X509ContentType.Cert); } } #if MONOTOUCH_WATCH return(X509ContentType.Unknown); #else try { AuthenticodeDeformatter ad = new AuthenticodeDeformatter(rawData); return(X509ContentType.Authenticode); } catch { return(X509ContentType.Unknown); } #endif }
/// <summary> /// Checks if the <paramref name="assemblyName"/> has the same publisher public key as <see cref="publisherPublicKey"/>. /// </summary> /// <param name="assemblyName"> /// The assembly name where to compare it's publisher against <see cref="publisherPublicKey"/>. /// </param> /// <returns> /// <c>True</c> if the <paramref name="assemblyName"/>'s publisher public key equals to the <see cref="publisherPublicKey"/>. /// </returns> private bool HasSamePublisher(AssemblyName assemblyName) { var path = new Uri(assemblyName.CodeBase).LocalPath; var authenticodeDeformatter = new AuthenticodeDeformatter(path); if (authenticodeDeformatter.SigningCertificate == null) { return(false); } var assemblyPublisherPublicKey = authenticodeDeformatter.SigningCertificate.PublicKey; return(assemblyPublisherPublicKey.SequenceEqual(this.publisherPublicKey)); }
public static bool IsTrusted(string filePath) { try { // AuthenticodeTools.IsTrusted(filePath) AuthenticodeDeformatter a = new AuthenticodeDeformatter(filePath); var isTrusted = a.IsTrusted(); return(isTrusted); } catch (Exception) { throw; } }
public static X509Certificate CreateFromSignedFile(string filename) { try { AuthenticodeDeformatter a = new AuthenticodeDeformatter(filename); if (a.SigningCertificate != null) { return(new X509Certificate(a.SigningCertificate.RawData)); } } catch (SecurityException) { // don't wrap SecurityException into a COMException throw; } catch (Exception e) { string msg = Locale.GetText("Couldn't extract digital signature from {0}.", filename); throw new COMException(msg, e); } throw new CryptographicException(Locale.GetText("{0} isn't signed.", filename)); }
// static methods static public int Check(string fileName, bool quiet, bool verbose) { AuthenticodeDeformatter a = new AuthenticodeDeformatter(fileName); // debug /* FileStream fs = File.Open (fileName + ".sig", FileMode.Create, FileAccess.Write); * fs.Write (a.Signature, 0, a.Signature.Length); * fs.Close ();*/ // get something shorter to display fileName = Path.GetFileName(fileName); if (verbose) { Console.WriteLine("Verifying file {0} for Authenticode(tm) signatures...{1}", fileName, Environment.NewLine); } if (a.Timestamp == DateTime.MinValue) { // signature only valid if the certificate is valid Console.WriteLine("WARNING! {0} is not timestamped!", fileName); } else if (verbose) { Console.WriteLine("INFO! {0} was timestamped on {1}", fileName, a.Timestamp); } if (a.Reason > 0) { string msg = null; // FAILURES switch (a.Reason) { case 1: msg = "doesn't contain a digital signature"; break; case 2: msg = "digital signature is invalid"; break; case 3: msg = "countersignature (timestamp) is invalid"; break; case 4: msg = "timestamp is outside certificate validity"; break; case 5: msg = "use an unsupported hash algorithm. Verification is impossible"; break; case 6: msg = "signature can't be traced back to a trusted root"; break; case 7: msg = "couldn't find the certificate that signed the file"; break; case 8: msg = "certificate is expired and no timestamp is present"; break; default: msg = "unknown error"; break; } Console.WriteLine("ERROR! {0} {1}!{2}", fileName, msg, Environment.NewLine); return(1); } Console.WriteLine("SUCCESS: {0} signature is valid{1}and can be traced back to a trusted root!{2}", fileName, Environment.NewLine, Environment.NewLine); return(0); }
static internal Evidence GetDefaultHostEvidence(Assembly a) { Evidence e = new Evidence(); string aname = a.EscapedCodeBase; // by default all assembly have the Zone, Url and Hash evidences e.AddHost(Zone.CreateFromUrl(aname)); e.AddHost(new Url(aname)); e.AddHost(new Hash(a)); // non local files (e.g. http://) also get a Site evidence if (String.Compare("FILE://", 0, aname, 0, 7, true, CultureInfo.InvariantCulture) != 0) { e.AddHost(Site.CreateFromUrl(aname)); } // strongnamed assemblies gets a StrongName evidence AssemblyName an = a.GetName(); byte[] pk = an.GetPublicKey(); if ((pk != null) && (pk.Length > 0)) { StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(pk); e.AddHost(new StrongName(blob, an.Name, an.Version)); } // Authenticode(r) signed assemblies get a Publisher evidence if (IsAuthenticodePresent(a)) { // Note: The certificate is part of the evidences even if it is not trusted! // so we can't call X509Certificate.CreateFromSignedFile AuthenticodeDeformatter ad = new AuthenticodeDeformatter(a.Location); if (ad.SigningCertificate != null) { X509Certificate x509 = new X509Certificate(ad.SigningCertificate.RawData); if (x509.GetHashCode() != 0) { e.AddHost(new Publisher(x509)); } } } // assemblies loaded from the GAC also get a Gac evidence (new in Fx 2.0) if (a.GlobalAssemblyCache) { e.AddHost(new GacInstalled()); } // the current HostSecurityManager may add/remove some evidence AppDomainManager dommgr = AppDomain.CurrentDomain.DomainManager; if (dommgr != null) { if ((dommgr.HostSecurityManager.Flags & HostSecurityManagerOptions.HostAssemblyEvidence) == HostSecurityManagerOptions.HostAssemblyEvidence) { e = dommgr.HostSecurityManager.ProvideAssemblyEvidence(a, e); } } return(e); }
public bool AuthenticodeVerifier(string dll, string authenticode, string sign, string outputPath) { try { AuthenticodeDeformatter a; a = new AuthenticodeDeformatter(dll); if (dll.ToUpperInvariant().Contains("LIB\\NETSTANDARD1.4") || dll.ToUpperInvariant().Contains("LIB\\NETSTANDARD2.0")) { AssemblyName assemblyName = Assembly.LoadFrom(dll).GetName(); byte[] key = assemblyName.GetPublicKey(); if (key.Length > 0) { InstallChecker.report.AppendLine(Environment.NewLine + "Signed : True"); Console.WriteLine("Signed : True"); File.AppendAllText(outputPath, Environment.NewLine + dll + Environment.NewLine + "Signed : True"); } } if (dll.ToUpperInvariant().Contains("LICENSING") && (dll.ToUpperInvariant().Contains("NETSTANDARD1.2") || dll.ToUpperInvariant().Contains("NETSTANDARD1.4") || dll.ToUpperInvariant().Contains("NETSTANDARD2.0"))) { sign = "False"; authenticode = "False"; } if (sign.ToLower() == "true") { if (Path.GetExtension(dll).ToLower() == ".dll") { AssemblyName assemblyName = Assembly.LoadFrom(dll).GetName(); byte[] key = assemblyName.GetPublicKey(); if (key.Length > 0) { InstallChecker.report.AppendLine(Environment.NewLine + "Signed : True"); Console.WriteLine("Signed : True"); } else { InstallChecker.report.AppendLine(Environment.NewLine + "Signed : False"); Console.WriteLine("Signed : False"); File.AppendAllText(outputPath, Environment.NewLine + dll + Environment.NewLine + "Signed : False"); } } else if (Path.GetExtension(dll).ToLower() == ".nupkg") { Process verify = new Process(); verify.StartInfo.FileName = Program.nugetExePath; verify.StartInfo.WorkingDirectory = Path.GetDirectoryName(Program.nugetExePath); verify.StartInfo.Arguments = "verify -signature \"" + dll + "\""; verify.StartInfo.RedirectStandardInput = true; verify.StartInfo.CreateNoWindow = true; verify.StartInfo.UseShellExecute = false; verify.StartInfo.RedirectStandardOutput = true; verify.Start(); verify.WaitForExit(); if (!verify.ExitCode.Equals(0)) { InstallChecker.report.AppendLine(Environment.NewLine + "Signed : False"); Console.WriteLine("Signed : False"); File.AppendAllText(outputPath, Environment.NewLine + dll + Environment.NewLine + "Signed : False"); } } } if (authenticode.ToLower() == "true") { if (a.SigningCertificate != null) { if (a.SigningCertificate.IsCurrent) { InstallChecker.report.AppendLine(Environment.NewLine + "Authenticode : True"); Console.WriteLine("Authenticode : True"); } else { InstallChecker.report.AppendLine(Environment.NewLine + "Authenticode certificate was expired."); Console.WriteLine("Authenticode certificate was expired."); } } else { InstallChecker.report.AppendLine(Environment.NewLine + "Authenticode : False"); Console.WriteLine("Authenticode : False"); } } return(true); } catch (Exception ex) { InstallChecker.report.AppendLine(Environment.NewLine + ex.Message); Console.WriteLine(ex.Message); File.AppendAllText(outputPath, Environment.NewLine + dll + Environment.NewLine + ex.Message); return(false); } }