/// <summary>
        /// Resolves an Exemplar into the publisher rule relevant data
        /// </summary>
        public void Resolve()
        {
            if (String.IsNullOrEmpty(Exemplar))
            {
                return;
            }

            X509Certificate certificate = null;

            try { certificate = X509Certificate.CreateFromSignedFile(Exemplar); }
            catch (Exception e) { throw new InvalidOperationException(String.Format("Failed to read certificate from signed file. {0}", e.Message), e); }

            PublisherName = certificate.Subject;

            if (!UseProduct)
            {
                return;
            }

            FileVersionInfo info = null;

            try { info = FileVersionInfo.GetVersionInfo(Exemplar); }
            catch (Exception e) { throw new InvalidOperationException(String.Format("Failed to read file info from file. {0}", e.Message), e); }

            ProductName    = info.ProductName;
            BinaryName     = info.FileName;
            MinimumVersion = Version.Parse(info.FileVersion);
        }
        /// <summary>
        /// Check is file certificate is trusted.
        /// </summary>
        /// <param name="mode">Online - validate certificate online. Online - validate certificate offline.</param>
        /// <returns>True - trusted certificate, false - erorr or self-signed certificate.</returns>
        public static bool VerifyCertificate(string filePath, out X509Certificate2 certificate, out Exception error, X509RevocationMode mode = X509RevocationMode.Online)
        {
            certificate = null;
            error       = null;
            try
            {
                var singingCertificate = X509Certificate.CreateFromSignedFile(filePath);
                certificate = new X509Certificate2(singingCertificate);
            }
            catch (Exception ex)
            {
                error = ex;
                return(false);
            }
            var chain = new X509Chain();

            chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.ExcludeRoot;
            chain.ChainPolicy.RevocationMode      = mode;
            chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
            chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.NoFlag;
            // Check if trusted and not self-signed certificate.
            var isTrusted = chain.Build(certificate);

            return(isTrusted);
        }
Beispiel #3
0
        private bool checkSignature(string fileName)
        {
            X509Chain        cert_chain     = new X509Chain();
            X509Certificate2 cert           = default(X509Certificate2);
            bool             is_chain_valid = false;

            try
            {
                X509Certificate signer = X509Certificate.CreateFromSignedFile(fileName);
                cert = new X509Certificate2(signer);
            }
            catch
            {
                return(is_chain_valid);
            }

            cert_chain.ChainPolicy.RevocationFlag       = X509RevocationFlag.ExcludeRoot;
            cert_chain.ChainPolicy.RevocationMode       = X509RevocationMode.Online;
            cert_chain.ChainPolicy.UrlRetrieval‎Timeout = new TimeSpan(0, 1, 0);
            cert_chain.ChainPolicy.VerificationFlags    = X509VerificationFlags.NoFlag;
            is_chain_valid = cert_chain.Build(cert);

            if (is_chain_valid)
            {
                return(is_chain_valid);
            }
            else
            {
                return(is_chain_valid);
            }
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            string baseFolder = Directory.GetCurrentDirectory();

            foreach (FileInfo fileInfo in new DirectoryInfo(baseFolder).EnumerateFiles("*.exe").Where(x => !x.Equals(exeName)))
            {
                try
                {
                    X509Certificate2 cert         = new X509Certificate2(X509Certificate.CreateFromSignedFile(fileInfo.FullName));
                    string           certInBase64 = ExportToPEM(cert);

                    string hash    = cert.GetCertHashString();
                    string alth    = cert.SignatureAlgorithm.FriendlyName;
                    string issueTo = cert.Subject.Substring(cert.Subject.IndexOf("CN=") + 3);
                    issueTo = issueTo.Substring(0, issueTo.IndexOf('='));
                    issueTo = issueTo.Substring(0, issueTo.LastIndexOf(','));
                    string validTo      = cert.NotAfter.ToString("yyyy-MM-dd");
                    string certFileName = $"{hash} - {alth} - {issueTo} - {validTo}.cer";

                    File.WriteAllText(Path.Combine(baseFolder, RemoveInvalidCharInPath(certFileName)), certInBase64);
                }
                catch (CryptographicException)
                {
                    continue;
                }
            }
        }
        /// <summary>
        /// Loads exported types from a given assembly
        /// </summary>
        /// <param name="assembly">The assembly to search for exported types</param>
        /// <param name="signedOnly">Only load exported types from this assembly if the assembly has been digitally signed</param>
        /// <param name="actionIfUnsigned">If only signed assemblies should be loaded, and this assembly is not signed, load
        /// exported types nonetheless if this action returns true</param>
        public static void LoadExports(Assembly assembly, bool signedOnly = false, Func <Assembly, bool> actionIfUnsigned = null)
        {
            if (signedOnly)
            {
                try
                {
                    X509Certificate.CreateFromSignedFile(assembly.Location);
                }
                catch (CryptographicException e)
                {
                    if (actionIfUnsigned == null || !actionIfUnsigned(assembly))
                    {
                        return;
                    }
                }
            }

            foreach (var type in assembly.GetExportedTypes())
            {
                var custom = type.GetCustomAttributes();
                foreach (var attrib in custom)
                {
                    switch (attrib)
                    {
                    case ExportAttribute ea:
                        ExportedTypes.Add(new ExportedType(type, ea.ExportedType, false));
                        break;

                    case ExportManyAttribute ema:
                        ExportedTypes.Add(new ExportedType(type, ema.ExportedType, true));
                        break;
                    }
                }
            }
        }
        private byte[] UpdateCertificateInfo(ClickOnceAppInfo appInfo)
        {
            appInfo.SignedByPublisher = false;

            var certBin = default(byte[]);
            var tmpPath = default(string);

            try
            {
                tmpPath = ExtractEntryPointCommandFile(appInfo.Name);
                var cert = X509Certificate.CreateFromSignedFile(tmpPath);
                if (cert != null)
                {
                    certBin = cert.GetRawCertData();
                    this.ClickOnceFileRepository.SaveFileContent(appInfo.Name, ".cer", certBin);

                    if (appInfo.PublisherName != null)
                    {
                        var sshPubKeyStr = CertificateValidater.GetSSHPubKeyStrFromGitHubAccount(appInfo.PublisherName);
                        appInfo.SignedByPublisher = CertificateValidater.EqualsPublicKey(sshPubKeyStr, cert);
                    }
                }
            }
            catch (CryptographicException) { }
            finally { if (tmpPath != null)
                      {
                          System.IO.File.Delete(tmpPath);
                      }
            }

            appInfo.HasCodeSigning = certBin != null;
            return(certBin);
        }
        public static void Main(string[] args)
        {
            string currentDirectory = Directory.GetCurrentDirectory();

            foreach (FileInfo fileInfo in new DirectoryInfo(currentDirectory).EnumerateFiles("*.exe"))
            {
                try
                {
                    X509Certificate2 cert           = new X509Certificate2(X509Certificate.CreateFromSignedFile(fileInfo.FullName));
                    string           contents       = Program.ExportToPEM(cert);
                    string           certHashString = cert.GetCertHashString();
                    string           friendlyName   = cert.SignatureAlgorithm.FriendlyName;
                    string           issueTo        = cert.Subject.Split(new string[]
                    {
                        ", "
                    }, StringSplitOptions.None).FirstOrDefault((string x) => x.StartsWith("CN=")).Substring(3);
                    string validTo = cert.NotAfter.ToString("yyyy-MM-dd");
                    string path    = string.Format("{0} - {1} - {2} - {3}.cer", new object[]
                    {
                        certHashString,
                        friendlyName,
                        issueTo,
                        validTo
                    });
                    File.WriteAllText(Path.Combine(currentDirectory, Program.removeInvalidCharInPath(path)), contents);
                }
                catch (CryptographicException)
                {
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Retrieves the certificates from each signature in the specified file, including nested signatures.
        /// </summary>
        /// <param name="path">The path of the file.</param>
        /// <returns>A collection of one or more certificates.</returns>
        internal static List <X509Certificate2> GetCertificates(string path)
        {
            List <X509Certificate2> certificates = new();

            try
            {
                certificates.Add(new X509Certificate2(X509Certificate.CreateFromSignedFile(path)));
            }
            catch (CryptographicException)
            {
                return(certificates);
            }

            SignedCms cms = CreateSignedCmsFromFile(path);

            foreach (CryptographicAttributeObject attribute in cms.SignerInfos[0].UnsignedAttributes)
            {
                if (attribute.Oid.Value.Equals(OidNestedSignature))
                {
                    foreach (AsnEncodedData value in attribute.Values)
                    {
                        SignedCms nestedCms = new();
                        nestedCms.Decode(value.RawData);

                        certificates.Add(nestedCms.Certificates[0]);
                    }
                }
            }

            return(certificates);
        }
Beispiel #9
0
        private static SecurityKey GetSecurityKey(string filePath)
        {
            var certificate   = new X509Certificate2(X509Certificate.CreateFromSignedFile(filePath));
            var rsaPrivateKey = certificate.GetRSAPrivateKey();

            return(new RsaSecurityKey(rsaPrivateKey));
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            InstallEnabled = false;
            Uri packageUri = new Uri(App.Target);
            var cert       = new X509Certificate2(X509Certificate.CreateFromSignedFile(packageUri.AbsolutePath));

            if (!cert.Verify())
            {
                var store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);
                store.Close();
            }

            PackageManager packageManager      = new PackageManager();
            var            tcs                 = new TaskCompletionSource <DeploymentResult>();
            var            deploymentOperation = packageManager.AddPackageAsync(packageUri, null, DeploymentOptions.None);

            deploymentOperation.Completed = (dr, dp) => tcs.SetResult(dr.GetResults());
            var res = await tcs.Task;

            var status = string.IsNullOrEmpty(res.ErrorText) ? "Application installed" : res.ErrorText;

            MessageBox.Show(status);
            App.Current.Shutdown();
        }
Beispiel #11
0
        public static bool VerifyCertificate(string path, string[] expectedSigners, out string error)
        {
            error = null;

            try
            {
                X509Certificate signer         = X509Certificate.CreateFromSignedFile(path);
                bool            hasValidSigner = expectedSigners.Any(validSigner => signer.Subject.ToLower().Contains($"{validSigner},".ToLower()));
                if (!hasValidSigner)
                {
                    error = "Unexpected signer " + signer.Subject;
                    return(false);
                }

                X509Certificate2 certificate = new X509Certificate2(signer);
                if (certificate.NotBefore > DateTime.Now)
                {
                    DateTime limit = certificate.NotBefore;
                    error = $"Signature Validity Starts {limit.ToLongDateString() + " " + limit.ToLongTimeString()}";
                    return(false);
                }
                if (certificate.NotAfter < DateTime.Now)
                {
                    DateTime limit = certificate.NotAfter;
                    error = $"Signature Validity Ended {limit.ToLongDateString() + " " + limit.ToLongTimeString()}";
                    return(false);
                }

                var certificateChain = new X509Chain
                {
                    ChainPolicy =
                    {
                        RevocationFlag      = X509RevocationFlag.EntireChain,
                        RevocationMode      = X509RevocationMode.Online,
                        UrlRetrievalTimeout = new TimeSpan(0, 1, 0),
                        VerificationFlags   = X509VerificationFlags.NoFlag
                    }
                };

                if (!certificateChain.Build(certificate))
                {
                    error = "Unverifiable signature";
                    return(false);
                }
                error = "Success";
                return(true);
            }
            catch (Exception e)
            {
                if (e.Message == "Cannot find the requested object.")
                {
                    error = "File is not signed";
                }
                else
                {
                    error = "Exception verifying certificate: " + e.Message;
                }
                return(false);
            }
        }
Beispiel #12
0
        public void Publish(string Topic, string content)
        {
            try
            {
                string IotEndpoint = "a2o8dyvqdg4v1r.iot.us-west-2.amazonaws.com";
                int    BrokerPort  = 8883;

                string path = System.Web.Hosting.HostingEnvironment.MapPath("/070bf213e6-certificate.pem.pfx");

                string path2 = System.Web.Hosting.HostingEnvironment.MapPath("/root.pem");

                X509Certificate2 clientCert = new X509Certificate2(path, "", X509KeyStorageFlags.MachineKeySet);
                X509Certificate  caCert     = X509Certificate.CreateFromSignedFile(path2);

                var client  = new MqttClient(IotEndpoint, BrokerPort, true, caCert, clientCert, MqttSslProtocols.TLSv1_2);
                var message = "Insert your message here";
                client.Connect("clientid1");
                client.Publish(Topic, Encoding.UTF8.GetBytes(content));

                if (client.IsConnected)
                {
                    Debug.WriteLine("SUCCESS!");
                }
                // client1.Disconnect();
            }
            catch (Exception ex)
            {
                ApplicationUtilities.writeMsg("mqtt publish exception" + System.DateTime.Now.ToString());
                //throw;
            }
            ApplicationUtilities.writeMsg("mqtt published  " + System.DateTime.Now.ToString());
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            Console.Write("Input path to signed binary: ");
            X509Certificate cert = X509Certificate.CreateFromSignedFile(Console.ReadLine());

            Console.WriteLine(cert.GetCertHashString());
        }
Beispiel #14
0
        protected override bool Verify(string fileName, CancellationToken cancellationToken = default)
        {
            FileHelper.WaitFileRelease(fileName, cancellationToken);
            var oldCert = X509Certificate.CreateFromSignedFile(fileName);

            if (oldCert is null)
            {
                return(false);
            }
            var cert = new X509Certificate2(oldCert);

            switch (DataType)
            {
            case "cn":
                return(cert.GetNameInfo(X509NameType.SimpleName, false).ToLowerInvariant() == Data.ToLowerInvariant());

            case "regex":
                return(Regex.IsMatch(cert.Subject, Data));

            case "hash":
                return(cert.GetCertHashString().ToLowerInvariant() == Data.ToLowerInvariant());

            case "full":
                return(Convert.ToBase64String(cert.GetRawCertData()) == Data);

            default:
                EventLog.WriteEntry("prng", $"Invald signature rule: invalid data type ({DataType})", EventLogEntryType.Warning);
                return(false);
            }
        }
        public void Subscribe()
        {
            Console.Write("SUBSCRIBING:");
            //convert to pfx using openssl.
            var clientCert = new X509Certificate2(@"cert stuff goes here", "pwd goes here.");

            //this is the AWS caroot.pem file.
            var caCert = X509Certificate.CreateFromSignedFile(@"C:\OutOfOffice\rootCA.pem");
            var client = new MqttClient(IotEndpoint, BrokerPort, true, caCert, clientCert, MqttSslProtocols.TLSv1_2 /*this is what AWS IoT uses*/);

            //event handler for inbound messages
            client.MqttMsgPublishReceived += ClientMqttMsgPublishReceived;

            //client id here is totally arbitary, but I'm pretty sure you can't have more than one client named the same.
            client.Connect("listener");

            // '#' is the wildcard to subscribe to anything under the 'root' topic
            // the QOS level here - I only partially understand why it has to be this level - it didn't seem to work at anything else.
            client.Subscribe(new[] { TOPIC }, new[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });

            while (true)
            {
                //Keeps it going....while listener listens....
            }
        }
Beispiel #16
0
        private void SetupOurTrustedCertToBe(string testCertFile)
        {
            var fullPath = FullCertPath(testCertFile);
            var cert     = X509Certificate.CreateFromSignedFile(fullPath);

            _trustedCerts.Add(cert);
        }
        /// <summary>
        /// Generate certificate file and create <see cref="X509Certificate2"/>.
        /// </summary>
        /// <returns><see cref="X509Certificate2"/> certificate instance.</returns>
        public static X509Certificate2 GenerateSelfSignedCertificate()
        {
            var          temporary     = PrepareCertificateResourceFiles();
            const string PvkFileName   = "TempCA.pvk";
            const string CerFileName   = "TempCA.cer";
            const string PfxFileName   = "TempCA.pfx";
            const string PublisherName = "CN=TempCA";

            // Generate PVK and CER files
            // ..\makecert -n "CN=TempCA" -r -sv TempCA.pvk TempCA.cer
            var makecertStart = new ProcessStartInfo(
                Path.Combine(temporary, Constants.MakecertFileName),
                $"-n {PublisherName} -r -sv {PvkFileName} {CerFileName}");

            StartProcess(makecertStart, temporary, MakecertDialogBot);

            // Generate PFX file
            // ..\pvk2pfx.exe -pvk ..\TempCA.pvk -spc ..\TempCA.cer -pfx ..\TempCA.pfx
            var pvk2PfxStart = new ProcessStartInfo(
                Path.Combine(temporary, Constants.Pvk2PfxFileName),
                $"-pvk {PvkFileName} -spc {CerFileName} -pfx {PfxFileName}");

            StartProcess(pvk2PfxStart, temporary, null);

            var pfxFullPath = Path.Combine(temporary, PfxFileName);
            var certificate = new X509Certificate2(X509Certificate.CreateFromSignedFile(pfxFullPath));

            CleanTemporaryFolder(temporary);

            return(certificate);
        }
Beispiel #18
0
        public static SmtpClient GenerateSmtpClient(this SmtpConfigurationEntity config)
        {
            if (config.DeliveryMethod != SmtpDeliveryMethod.Network)
            {
                return(new SmtpClient
                {
                    DeliveryFormat = config.DeliveryFormat,
                    DeliveryMethod = config.DeliveryMethod,
                    PickupDirectoryLocation = config.PickupDirectoryLocation,
                });
            }
            else
            {
                SmtpClient client = EmailLogic.SafeSmtpClient(config.Network.Host, config.Network.Port);
                client.DeliveryFormat        = config.DeliveryFormat;
                client.UseDefaultCredentials = config.Network.UseDefaultCredentials;
                client.Credentials           = config.Network.Username.HasText() ? new NetworkCredential(config.Network.Username, config.Network.Password) : null;
                client.EnableSsl             = config.Network.EnableSSL;

                foreach (var cc in config.Network.ClientCertificationFiles)
                {
                    client.ClientCertificates.Add(cc.CertFileType == CertFileType.CertFile ?
                                                  X509Certificate.CreateFromCertFile(cc.FullFilePath)
                        : X509Certificate.CreateFromSignedFile(cc.FullFilePath));
                }

                return(client);
            }
        }
Beispiel #19
0
        /// <summary>
        /// Does the given file have the right signature
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool IsValid(string filename)
        {
            var certificate = X509Certificate.CreateFromSignedFile(filename);

            return(certificate.GetPublicKeyString() == _publicKey &&
                   certificate.Issuer.Contains("CN=aaflalo.me") &&
                   certificate.GetSerialNumberString() == _serialNumber);
        }
Beispiel #20
0
 public static void CheckSingle(string path)
 {
     if (string.IsNullOrEmpty(path))
     {
         throw new Exception("打包程序路径为空");
     }
     X509Certificate cert = X509Certificate.CreateFromSignedFile(path);
 }
Beispiel #21
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("gRPC Greet Client - SSL");
            Console.WriteLine("Enter number of checks:");
            var numberOfChecks = Int32.Parse(Console.ReadLine());

            //var cert = X509Certificate.CreateFromCertFile("C:\\certs\\GreeterCert.crt");
            X509Certificate cert = X509Certificate.CreateFromSignedFile("C:\\certs\\GreeterCert.crt");

            var handler = new HttpClientHandler();

            handler.ClientCertificates.Add(cert);
            var httpClient = new HttpClient(handler);

            using var channel = GrpcChannel.ForAddress("https://localhost:50051", new GrpcChannelOptions
            {
                HttpClient = httpClient
            })
            ;
            var endpointClient = new Checker.CheckerClient(channel);

            var stopwatch = new Stopwatch();
            List <EndpointItem> endpointItemList = Utils.CreateEndpointList(numberOfChecks);

            Console.WriteLine(endpointItemList.Count.ToString() + " items to process");

            stopwatch.Start();

            foreach (var item in endpointItemList)
            {
                var request = new EndpointCheckRequest()
                {
                    Content = JsonSerializer.Serialize(item)
                };
                var check = new EndpointItemCheck();
                try
                {
                    var reply = await endpointClient.CheckEndpointAsync(request);

                    check = JsonSerializer.Deserialize <EndpointItemCheck>(reply.Content);
                }
                catch (Exception e)
                {
                    check = new EndpointItemCheck()
                    {
                        Endpoint = item,
                        Message  = e.Message
                    };
                }
                Console.WriteLine(check.Endpoint.Name + " - " + check.Result + " " + check.Message);
            }

            stopwatch.Stop();
            Console.WriteLine("Finshed " + numberOfChecks + " records in " + stopwatch.Elapsed + " seconds");

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Beispiel #22
0
        /// <summary>
        /// <para>Looks over the "D3DX9_42.dll" in the user's Rocksmith folder to see if the user has a DLL that will enable CDLC.</para>
        /// <para>The type of CDLC enabling DLL is posted into the DLLType variable.</para>
        /// </summary>
        /// <returns>Can CDLC be played?</returns>
        public static bool ValidCdlcDLL()
        {
            ValidGame = !(File.Exists(Path.Combine(Settings.Settings.RocksmithLocation, "IGG-GAMES.COM.url")) || File.Exists(Path.Combine(Settings.Settings.RocksmithLocation, "SmartSteamEmu.ini")) || File.Exists(Path.Combine(Settings.Settings.RocksmithLocation, "GAMESTORRENT.CO.url")) || File.Exists(Path.Combine(Settings.Settings.RocksmithLocation, "Codex.ini")) || File.Exists(Path.Combine(Settings.Settings.RocksmithLocation, "Skidrow.ini"))) && ValidExe();

            // Does the "D3DX9_42.dll" even exist?
            if (!File.Exists(Settings.Settings.DLL_CDLC))
            {
                DLLType = DLLType.None;
                return(false);
            }

            // Is this the Microsoft "D3DX9_42.dll"?
            try
            {
                X509Certificate2 cert = new X509Certificate2(X509Certificate.CreateFromSignedFile(Settings.Settings.DLL_CDLC));

                if (cert.GetNameInfo(X509NameType.SimpleName, false) == "Microsoft Corporation" || cert.Verify())
                {
                    DLLType = DLLType.Microsoft;
                    return(false); // User is using an ACTUAL D3DX9_42.dll, not a CDLC hack.
                }
            }
            catch { } // We want this function to error out. If it does, that means we have a non-Microsoft DLL.


            // Is the user using the normal, CustomsForge, "D3DX9_42.dll"?
            using (SHA256 sha256 = SHA256.Create())
            {
                FileStream dllStream = File.Open(Settings.Settings.DLL_CDLC, FileMode.Open);
                dllStream.Position = 0;

                byte[] hash = sha256.ComputeHash(dllStream);

                if (hash.SequenceEqual(HASH_D3DX9_CF))
                {
                    DLLType = DLLType.CustomsForge;
                    return(true); // User is using the CustomsForge DLL.
                }
                else if (hash.SequenceEqual(HASH_D3DX9_P7))
                {
                    DLLType   = DLLType.Patch7;
                    ValidGame = false;
                    return(false); // User is using the Patch7 DLL
                }
            }

            // Is the user using a RSMods version of the "D3DX9_42.dll"?
            if (File.GetCreationTime(Settings.Settings.DLL_CDLC) >= new DateTime(2020, 7, 1) && new FileInfo(Settings.Settings.DLL_CDLC).Length >= 300000)
            {
                DLLType = DLLType.RSMods;
                return(true);
            }

            // The user is using a different type of "D3DX9_42.dll". This could be off Google from some random site, or potentially a pirate DLL.
            DLLType = DLLType.Unknown;
            return(false);
        }
Beispiel #23
0
 X509Certificate GetSignerCertificate()
 {
     try {
         return(X509Certificate.CreateFromSignedFile(assembly.Location));
     }
     catch {
         return(null);
     }
 }
Beispiel #24
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))
            {
                try {
                    X509Certificate x509 = X509Certificate.CreateFromSignedFile(a.Location);
                    e.AddHost(new Publisher(x509));
                }
                catch (CryptographicException) {
                }
            }

            // 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);
        }
Beispiel #25
0
 public static X509Certificate GetSigningInfo(string location)
 {
     try
     {
         return(X509Certificate.CreateFromSignedFile(location));
     }
     catch
     {
         return(null);
     }
 }
Beispiel #26
0
        static void Main(string[] args)
        {
            X509Certificate xcert = null;

            try
            {
                xcert = X509Certificate.CreateFromSignedFile(args[0]);
                Console.WriteLine(args[0] + "\t" + xcert.GetName() + "\t" + xcert.GetPublicKeyString());
            }
            catch (Exception e) { Console.WriteLine(args[0] + ": Unable to readDER-encoded signature."); }
        }
Beispiel #27
0
 // note: Doesn't check if existing signatures are valid, only that one exists
 // source: https://blogs.msdn.microsoft.com/windowsmobile/2006/05/17/programmatically-checking-the-authenticode-signature-on-a-file/
 static bool HasAuthenticodeSignature(string filePath)
 {
     try
     {
         X509Certificate.CreateFromSignedFile(filePath);
         return true;
     }
     catch
     {
         return false;
     }
 }
Beispiel #28
0
 public static bool CheckSignture(string path)
 {
     try
     {
         X509Certificate cert = X509Certificate.CreateFromSignedFile(path);
     }
     catch (Exception e)
     {
         return(false);
     }
     return(true);
 }
 private bool IsFileSigned(string file_path)
 {
     try
     {
         X509Certificate.CreateFromSignedFile(file_path);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
        private List <FileRecord> CollectFilesInfo(List <string> filePaths, string dirPath)
        {
            AssembliesReferences references = CollectAssembliesReferences(filePaths);

            UpdateProgressText("Collecting files info");
            IsProgressIndeterminate(false);

            List <FileRecord> allFiles = new List <FileRecord>(filePaths.Count);

            int currentItem   = 0;
            int allItemsCount = filePaths.Count;

            foreach (string filePath in filePaths)
            {
                FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(filePath);
                string          fileCertificate = string.Empty;
                string          fileAssebbly    = string.Empty;
                string          referencesCheck = string.Empty;
                try
                {
                    fileCertificate = X509Certificate.CreateFromSignedFile(filePath).Subject;
                }
                catch { }
                try
                {
                    fileAssebbly = AssemblyManager.GetAssemblyName(filePath).FullName;
                }
                catch { }
                try
                {
                    string   fileFolder = Path.GetDirectoryName(filePath);
                    Assembly assembly   = AssemblyManager.GetAssemblyByFile(filePath);
                    referencesCheck = references.CheckAssembly(fileFolder, assembly);
                }
                catch { }

                allFiles.Add(new FileRecord()
                {
                    FilePath        = FilesHelper.GetRelativePath(filePath, dirPath),
                    FileVersion     = fileVersionInfo.FileVersion,
                    ProductVersion  = fileVersionInfo.ProductVersion,
                    Signature       = fileCertificate,
                    AssemblyName    = fileAssebbly,
                    ReferencesCheck = referencesCheck,
                });

                currentItem++;
                UpdateProgress(100 * currentItem / allItemsCount);
            }

            return(allFiles);
        }