static void Main(string[] args)
            {
                bool            is_verbose     = false;
                bool            show_help      = false;
                CLRPH_DEMANGLER demangler_name = CLRPH_DEMANGLER.Default;

                OptionSet opts = new OptionSet()
                {
                    { "v|verbose", "redirect debug traces to console", v => is_verbose = v != null },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                    { "d=|demangler=", "Choose demangler name", v => demangler_name = ParseDemanglerName(v) },
                };

                List <string> eps = opts.Parse(args);

                if (show_help)
                {
                    ShowHelp(opts);
                    return;
                }

                if (is_verbose)
                {
                    // Redirect debug log to the console
                    Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
                    Debug.AutoFlush = true;
                }

                // always the first call to make
                Phlib.InitializePhLib();
                Demangler demangler;

                switch (args.Length)
                {
                case 0:
                    demangler = new Demangler(CLRPH_DEMANGLER.Microsoft);
                    TestKnownInputs(demangler);
                    break;

                default:
                case 1:
                    demangler = new Demangler(demangler_name);
                    string Filepath = args[1];

                    if (NativeFile.Exists(Filepath))
                    {
                        TestFilepath(Filepath, demangler);
                    }
                    else
                    {
                        string undecoratedName = demangler.UndecorateName(args[1]).Item2;
                        Console.WriteLine(undecoratedName);
                    }

                    break;
                }

                // Force flushing out buffer
                Console.Out.Flush();
            }
        public void InitializeView()
        {
            if (!NativeFile.Exists(this.Filename))
            {
                MessageBox.Show(
                    String.Format("{0:s} is not present on the disk", this.Filename),
                    "Invalid PE",
                    MessageBoxButton.OK
                    );

                return;
            }

            this.Pe = (Application.Current as App).LoadBinary(this.Filename);
            if (this.Pe == null || !this.Pe.LoadSuccessful)
            {
                MessageBox.Show(
                    String.Format("{0:s} is not a valid PE-COFF file", this.Filename),
                    "Invalid PE",
                    MessageBoxButton.OK
                    );

                return;
            }

            this.SymPrv                = new PhSymbolProvider();
            this.RootFolder            = Path.GetDirectoryName(this.Filename);
            this.SxsEntriesCache       = SxsManifest.GetSxsEntries(this.Pe);
            this.ProcessedModulesCache = new ModulesCache();
            this.ApiSetmapCache        = Phlib.GetApiSetSchema();
            this._SelectedModule       = null;
            this._DisplayWarning       = false;

            // TODO : Find a way to properly bind commands instead of using this hack
            this.ModulesList.Items.Clear();
            this.ModulesList.DoFindModuleInTreeCommand   = DoFindModuleInTree;
            this.ModulesList.ConfigureSearchOrderCommand = ConfigureSearchOrderCommand;

            var RootFilename = Path.GetFileName(this.Filename);
            var RootModule   = new DisplayModuleInfo(RootFilename, this.Pe, ModuleSearchStrategy.ROOT);

            this.ProcessedModulesCache.Add(new ModuleCacheKey(RootFilename, this.Filename), RootModule);

            ModuleTreeViewItem    treeNode             = new ModuleTreeViewItem();
            DependencyNodeContext childTreeInfoContext = new DependencyNodeContext()
            {
                ModuleInfo = new WeakReference(RootModule),
                IsDummy    = false
            };

            treeNode.DataContext = childTreeInfoContext;
            treeNode.Header      = treeNode.GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath);
            treeNode.IsExpanded  = true;

            this.DllTreeView.Items.Clear();
            this.DllTreeView.Items.Add(treeNode);

            // Recursively construct tree of dll imports
            ConstructDependencyTree(treeNode, this.Pe);
        }
Exemple #3
0
        void App_Startup(object sender, StartupEventArgs e)
        {
            Phlib.InitializePhLib();

            BinaryCache.Instance.Load();

            MainWindow mainWindow = new MainWindow();

            mainWindow.IsMaster = true;

            switch (Phlib.GetClrPhArch())
            {
            case CLRPH_ARCH.x86:
                mainWindow.Title = "Dependencies (x86)";
                break;

            case CLRPH_ARCH.x64:
                mainWindow.Title = "Dependencies (x64)";
                break;

            case CLRPH_ARCH.WOW64:
                mainWindow.Title = "Dependencies (WoW64)";
                break;
            }

            mainWindow.Show();


            // Process command line args
            if (e.Args.Length > 0)
            {
                mainWindow.OpenNewDependencyWindow(e.Args[0]);
            }
        }
 public NativeDepend()
 {
     if (!_PhInited)
     {
         Phlib.InitializePhLib();
         _PhInited = true;
     }
 }
 /// <summary>
 /// Initial from a PE File
 /// </summary>
 /// <param name="file">The file name</param>
 public NativeDepend(string file)
 {
     filename = file;
     if (!_PhInited)
     {
         Phlib.InitializePhLib();
         _PhInited = true;
     }
 }
 /// <summary>
 /// Initialize the class from a PE file
 /// </summary>
 /// <param name="file"></param>
 public void Init(string file)
 {
     if (!File.Exists(file))
     {
         throw new FileNotFoundException();
     }
     filename        = file;
     localPE         = new PE(file);
     SxsEntriesCache = SxsManifest.GetSxsEntries(localPE);
     ApiSetmapCache  = Phlib.GetApiSetSchema();
 }
Exemple #7
0
        void App_Startup(object sender, StartupEventArgs e)
        {
            (Application.Current as App).PropertyChanged += App_PropertyChanged;

            Phlib.InitializePhLib();

            // Load singleton for binary caching
            if (Dependencies.BinaryCacheOption.GetGlobalBehaviour() == Dependencies.BinaryCacheOption.BinaryCacheOptionValue.Yes)
            {
                string ApplicationLocalAppDataPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    "Dependencies"
                    );
                BinaryCache.Instance = new BinaryCacheImpl(ApplicationLocalAppDataPath, 200);
            }
            else
            {
                BinaryCache.Instance = new BinaryNoCacheImpl();
            }

            BinaryCache.Instance.Load();


            // https://www.red-gate.com/simple-talk/blogs/wpf-menu-displays-to-the-left-of-the-window/
            SetDropDownMenuToBeRightAligned();

            mainWindow          = new MainWindow();
            mainWindow.IsMaster = true;

            switch (Phlib.GetClrPhArch())
            {
            case CLRPH_ARCH.x86:
                mainWindow.Title = "Dependencies (x86)";
                break;

            case CLRPH_ARCH.x64:
                mainWindow.Title = "Dependencies (x64)";
                break;

            case CLRPH_ARCH.WOW64:
                mainWindow.Title = "Dependencies (WoW64)";
                break;
            }

            mainWindow.Show();



            // Process command line args
            if (e.Args.Length > 0)
            {
                mainWindow.OpenNewDependencyWindow(e.Args[0]);
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            // always the first call to make
            Phlib.InitializePhLib();

            int         recursion_depth = 0;
            bool        early_exit      = false;
            bool        show_help       = false;
            bool        export_as_json  = false;
            DumpCommand command         = null;

            OptionSet opts = new OptionSet()
            {
                { "h|help", "show this message and exit", v => show_help = v != null },
                { "json", "Export results in json format", v => export_as_json = v != null },
                { "d|depth=", "limit recursion depth when analyisng loaded modules or dependency chain. Default value is infinite", (int v) => recursion_depth = v },
                { "knowndll", "List all known dlls", v => { DumpKnownDlls(GetObjectPrinter(export_as_json));  early_exit = true; } },
                { "apisets", "List apisets redirections", v => { DumpApiSets(GetObjectPrinter(export_as_json));  early_exit = true; } },
                { "apisetsdll", "List apisets redirections from apisetschema.dll", v => command = DumpApiSets },
                { "manifest", "show manifest information embedded in PE file", v => command = DumpManifest },
                { "sxsentries", "dump all of FILE's sxs dependencies", v => command = DumpSxsEntries },
                { "imports", "dump FILE imports", v => command = DumpImports },
                { "exports", "dump  FILE exports", v => command = DumpExports },
                { "chain", "dump FILE whole dependency chain", v => command = DumpDependencyChain },
                { "modules", "dump FILE resolved modules", v => command = DumpModules },
            };

            List <string> eps = opts.Parse(args);

            if (early_exit)
            {
                return;
            }

            if ((show_help) || (args.Length == 0) || (command == null))
            {
                DumpUsage();
                return;
            }

            String FileName = eps[0];
            //Console.WriteLine("[-] Loading file {0:s} ", FileName);
            PE Pe = new PE(FileName);

            if (!Pe.Load())
            {
                Console.Error.WriteLine("[x] Could not load file {0:s} as a PE", FileName);
                return;
            }

            command(Pe, GetObjectPrinter(export_as_json), recursion_depth);
        }
Exemple #9
0
        public static void DumpApiSets()
        {
            VerboseWriteLine("[-] Api Sets Map : ");

            foreach (var ApiSetEntry in Phlib.GetApiSetSchema())
            {
                ApiSetTarget ApiSetImpl    = ApiSetEntry.Value;
                string       ApiSetName    = ApiSetEntry.Key;
                string       ApiSetImplStr = (ApiSetImpl.Count > 0) ? String.Join(",", ApiSetImpl.ToArray()) : "";

                Console.WriteLine("{0:s} -> [ {1:s} ]", ApiSetName, ApiSetImplStr);
            }

            VerboseWriteLine("");
        }
Exemple #10
0
        public MainWindow()
        {
            Phlib.InitializePhLib();

            InitializeComponent();

            PopulateRecentFilesMenuItems(true);

            this.AboutPage    = new About();
            this.UserSettings = new UserSettings();

            // TODO : understand how to reliably bind in xaml
            this.TabControl.InterTabController.InterTabClient = DoNothingInterTabClient;

            this._Master = false;
        }
Exemple #11
0
        public DependencyWindow(String FileName)
        {
            InitializeComponent();

            this.Filename = FileName;
            this.Pe       = new PE(FileName);

            if (!this.Pe.LoadSuccessful)
            {
                MessageBox.Show(
                    String.Format("{0:s} is not a valid PE-COFF file", this.Filename),
                    "Invalid PE",
                    MessageBoxButton.OK
                    );
                return;
            }

            this.SymPrv                = new PhSymbolProvider();
            this.RootFolder            = Path.GetDirectoryName(FileName);
            this.SxsEntriesCache       = SxsManifest.GetSxsEntries(this.Pe);
            this.ProcessedModulesCache = new ModulesCache();
            this.ApiSetmapCache        = Phlib.GetApiSetSchema();

            // TODO : Find a way to properly bind commands instead of using this hack
            this.ModulesList.DoFindModuleInTreeCommand = DoFindModuleInTree;

            var RootFilename = Path.GetFileName(FileName);
            var RootModule   = new DisplayModuleInfo(RootFilename, this.Pe);

            this.ProcessedModulesCache.Add(new ModuleCacheKey(RootFilename, FileName), RootModule);

            ModuleTreeViewItem    treeNode             = new ModuleTreeViewItem();
            DependencyNodeContext childTreeInfoContext = new DependencyNodeContext()
            {
                ModuleInfo = new WeakReference(RootModule),
                IsDummy    = false
            };

            treeNode.DataContext = childTreeInfoContext;
            treeNode.Header      = treeNode.GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath);
            treeNode.IsExpanded  = true;

            this.DllTreeView.Items.Add(treeNode);

            // Recursively construct tree of dll imports
            ConstructDependencyTree(treeNode, this.Pe);
        }
Exemple #12
0
        void App_Startup(object sender, StartupEventArgs e)
        {
            Phlib.InitializePhLib();

            BinaryCache.Instance.Load();

            MainWindow mainWindow = new MainWindow();

            mainWindow.IsMaster = true;
            mainWindow.Show();

            // Process command line args
            if (e.Args.Length > 0)
            {
                mainWindow.OpenNewDependencyWindow(e.Args[0]);
            }
        }
Exemple #13
0
            static void Main(string[] args)
            {
                bool is_verbose = false;
                bool show_help  = false;

                OptionSet opts = new OptionSet()
                {
                    { "v|verbose", "redirect debug traces to console", v => is_verbose = v != null },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                };

                List <string> eps = opts.Parse(args);

                if (show_help)
                {
                    ShowHelp(opts);
                    return;
                }

                if (is_verbose)
                {
                    // Redirect debug log to the console
                    Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
                    Debug.AutoFlush = true;
                }

                // always the first call to make
                Phlib.InitializePhLib();

                BinaryCache.Instance.Load();

                foreach (var peFilePath in eps)
                {
                    PE Pe = BinaryCache.LoadPe(peFilePath);
                    Console.WriteLine("Loaded PE file : {0:s}", Pe.Filepath);
                }


                BinaryCache.Instance.Unload();
            }
Exemple #14
0
        public void Load()
        {
            // "warm up" the cache
            foreach (var CachedBinary in Directory.EnumerateFiles(BinaryCacheFolderPath))
            {
                GetBinary(CachedBinary);
            }

            string System32Folder = Environment.GetFolderPath(Environment.SpecialFolder.System);
            string SysWow64Folder = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86);

            // preload all well konwn dlls
            foreach (String KnownDll in Phlib.GetKnownDlls(false))
            {
                GetBinary(Path.Combine(System32Folder, KnownDll));
            }

            foreach (String KnownDll in Phlib.GetKnownDlls(true))
            {
                GetBinary(Path.Combine(SysWow64Folder, KnownDll));
            }
        }
Exemple #15
0
            static void Main(string[] args)
            {
                // always the first call to make
                Phlib.InitializePhLib();

                Demangler demangler;

                switch (args.Length)
                {
                case 0:
                    demangler = new Demangler("Microsoft");
                    TestKnownInputs(demangler);
                    break;

                case 1:
                    demangler = new Demangler();
                    TestFilepath(args[0], demangler);

                    break;

                default:
                case 2:
                    string demanglerName = args[0].TrimStart(new char[] { '-' });
                    string Filepath      = args[1];

                    demangler = new Demangler(demanglerName);
                    if (NativeFile.Exists(Filepath))
                    {
                        TestFilepath(Filepath, demangler);
                    }
                    else
                    {
                        Console.WriteLine(demangler.UndecorateName(args[1]));
                    }

                    break;
                }
            }
Exemple #16
0
        public static void DumpKnownDlls()
        {
            VerboseWriteLine("[-] 64-bit KnownDlls : ");

            foreach (String KnownDll in Phlib.GetKnownDlls(false))
            {
                string System32Folder = Environment.GetFolderPath(Environment.SpecialFolder.System);
                Console.WriteLine("  {0:s}\\{1:s}", System32Folder, KnownDll);
            }

            VerboseWriteLine("");

            VerboseWriteLine("[-] 32-bit KnownDlls : ");

            foreach (String KnownDll in Phlib.GetKnownDlls(true))
            {
                string SysWow64Folder = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86);
                Console.WriteLine("  {0:s}\\{1:s}", SysWow64Folder, KnownDll);
            }


            VerboseWriteLine("");
        }
Exemple #17
0
        public void Load()
        {
            // "warm up" the cache
            foreach (var CachedBinary in Directory.EnumerateFiles(BinaryCacheFolderPath))
            {
                GetBinaryAsync(CachedBinary);
            }

            string System32Folder = Environment.GetFolderPath(Environment.SpecialFolder.System);
            string SysWow64Folder = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86);

            // wow64.dll, wow64cpu.dll and wow64win.dll are listed as wow64 known dlls,
            // but they are actually x64 binaries.
            List <String> Wow64Dlls = new List <string>(new string[] {
                "wow64.dll",
                "wow64cpu.dll",
                "wow64win.dll"
            });

            // preload all well konwn dlls
            foreach (String KnownDll in Phlib.GetKnownDlls(false))
            {
                GetBinaryAsync(Path.Combine(System32Folder, KnownDll));
            }

            foreach (String KnownDll in Phlib.GetKnownDlls(true))
            {
                if (Wow64Dlls.Contains(KnownDll))
                {
                    GetBinaryAsync(Path.Combine(System32Folder, KnownDll));
                }
                else
                {
                    GetBinaryAsync(Path.Combine(SysWow64Folder, KnownDll));
                }
            }
        }
Exemple #18
0
 public NtKnownDlls()
 {
     x64 = Phlib.GetKnownDlls(false);
     x86 = Phlib.GetKnownDlls(true);
 }
Exemple #19
0
        // default search order :
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx
        //
        // if (SafeDllSearchMode) {
        //      -1. Sxs manifests
        //      0. KnownDlls list
        //      1. Loaded PE folder
        //      2. C:\Windows\(System32 | SysWow64 )
        //      3. 16-bit system directory   <-- ignored
        //      4. C:\Windows
        //      5. %pwd%
        //      6. AppDatas
        //      }
        public static Tuple <ModuleSearchStrategy, string> FindPeFromDefault(PE RootPe, string ModuleName, SxsEntries SxsCache)
        {
            bool   Wow64Dll     = RootPe.IsWow64Dll();
            string RootPeFolder = Path.GetDirectoryName(RootPe.Filepath);
            string FoundPePath  = null;

            Environment.SpecialFolder WindowsSystemFolder = (Wow64Dll) ?
                                                            Environment.SpecialFolder.SystemX86 :
                                                            Environment.SpecialFolder.System;
            String WindowsSystemFolderPath = Environment.GetFolderPath(WindowsSystemFolder);


            // -1. Look in Sxs manifest (copious reversing needed)
            // TODO : find dll search order
            if (SxsCache.Count != 0)
            {
                SxsEntry Entry = SxsCache.Find(SxsItem =>
                                               string.Equals(SxsItem.Name, ModuleName, StringComparison.OrdinalIgnoreCase)
                                               );

                if (Entry != null)
                {
                    return(new Tuple <ModuleSearchStrategy, string>(ModuleSearchStrategy.SxS, Entry.Path));
                }
            }


            // 0. Look in well-known dlls list
            // HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\KnownDLLs
            // https://blogs.msdn.microsoft.com/larryosterman/2004/07/19/what-are-known-dlls-anyway/
            String KnownDll = Phlib.GetKnownDlls(Wow64Dll).Find(x => string.Equals(x, ModuleName, StringComparison.OrdinalIgnoreCase));

            if (KnownDll != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.WellKnownDlls,
                           Path.Combine(WindowsSystemFolderPath, KnownDll)
                           ));
            }


            // 1. Look in application folder
            FoundPePath = FindPeFromPath(ModuleName, new List <string>(new string[] { RootPeFolder }), Wow64Dll);
            if (FoundPePath != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.ApplicationDirectory,
                           FoundPePath
                           ));
            }

            // {2-3-4}. Look in system folders
            List <String> SystemFolders = new List <string>(new string[] {
                WindowsSystemFolderPath,
                Environment.GetFolderPath(Environment.SpecialFolder.Windows)
            }
                                                            );

            FoundPePath = FindPeFromPath(ModuleName, SystemFolders, Wow64Dll);
            if (FoundPePath != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.WindowsFolder,
                           FoundPePath
                           ));
            }

            // 5. Look in current directory
            // Ignored for the time being since we can't know from
            // where the exe is run
            // TODO : Add a user supplied path emulating %cwd%


            // 6. Look in local app data (check for python for exemple)



            // 7. Find in PATH
            string        PATH        = Environment.GetEnvironmentVariable("PATH");
            List <String> PATHFolders = new List <string>(PATH.Split(';'));

            FoundPePath = FindPeFromPath(ModuleName, PATHFolders, Wow64Dll);
            if (FoundPePath != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.Environment,
                           FoundPePath
                           ));
            }


            return(new Tuple <ModuleSearchStrategy, string>(
                       ModuleSearchStrategy.NOT_FOUND,
                       null
                       ));
        }
Exemple #20
0
        static void Main(string[] args)
        {
            String FileName    = null;
            var    ProgramArgs = ParseArgs(args);
            Action <IPrettyPrintable> ObjectPrinter = PrettyPrinter;

            // always the first call to make
            Phlib.InitializePhLib();

            if (ProgramArgs.ContainsKey("file"))
            {
                FileName = ProgramArgs["file"];
            }

            if (ProgramArgs.ContainsKey("-json"))
            {
                ObjectPrinter = JsonPrinter;
            }


            // no need to load PE for those commands
            if ((args.Length == 0) || ProgramArgs.ContainsKey("-h") || ProgramArgs.ContainsKey("-help"))
            {
                DumpUsage();
                return;
            }

            if (ProgramArgs.ContainsKey("-knowndll"))
            {
                DumpKnownDlls(ObjectPrinter);
                return;
            }

            if (ProgramArgs.ContainsKey("-apisets"))
            {
                DumpApiSets(ObjectPrinter);
                return;
            }

            //Console.WriteLine("[-] Loading file {0:s} ", FileName);
            PE Pe = new PE(FileName);

            if (!Pe.Load())
            {
                Console.Error.WriteLine("[x] Could not load file {0:s} as a PE", FileName);
                return;
            }


            if (ProgramArgs.ContainsKey("-manifest"))
            {
                DumpManifest(Pe, ObjectPrinter);
            }
            else if (ProgramArgs.ContainsKey("-sxsentries"))
            {
                DumpSxsEntries(Pe, ObjectPrinter);
            }
            else if (ProgramArgs.ContainsKey("-imports"))
            {
                DumpImports(Pe, ObjectPrinter);
            }
            else if (ProgramArgs.ContainsKey("-exports"))
            {
                DumpExports(Pe, ObjectPrinter);
            }
            else if (ProgramArgs.ContainsKey("-chain"))
            {
                DumpDependencyChain(Pe, ObjectPrinter);
            }
            else if (ProgramArgs.ContainsKey("-modules"))
            {
                DumpModules(Pe, ObjectPrinter);
            }
        }
Exemple #21
0
        static void Main(string[] args)
        {
            Phlib.InitializePhLib();
            var ProgramArgs = ParseArgs(args);

            String FileName = null;

            if (ProgramArgs.ContainsKey("file"))
            {
                FileName = ProgramArgs["file"];
            }

            if (ProgramArgs.ContainsKey("-verbose"))
            {
                VerboseOutput = true;
            }

            // no need to load PE for those commands
            if ((args.Length == 0) || ProgramArgs.ContainsKey("-h") || ProgramArgs.ContainsKey("-help"))
            {
                DumpUsage();
                return;
            }

            if (ProgramArgs.ContainsKey("-knowndll"))
            {
                DumpKnownDlls();
                return;
            }

            if (ProgramArgs.ContainsKey("-apisets"))
            {
                DumpApiSets();
                return;
            }

            VerboseWriteLine("[-] Loading file {0:s} ", FileName);
            PE Pe = new PE(FileName);

            if (!Pe.LoadSuccessful)
            {
                Console.Error.WriteLine("[x] Could not load file {0:s} as a PE", FileName);
                return;
            }


            if (ProgramArgs.ContainsKey("-manifest"))
            {
                DumpManifest(Pe);
            }
            if (ProgramArgs.ContainsKey("-sxsentries"))
            {
                DumpSxsEntries(Pe);
            }
            if (ProgramArgs.ContainsKey("-imports"))
            {
                DumpImports(Pe);
            }
            if (ProgramArgs.ContainsKey("-exports"))
            {
                DumpExports(Pe);
            }
        }
Exemple #22
0
 public NtApiSet()
 {
     Schema = Phlib.GetApiSetSchema();
 }
Exemple #23
0
        // default search order :
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx
        //
        // if (SafeDllSearchMode) {
        //      -1. Sxs manifests
        //      0. KnownDlls list
        //      1. Loaded PE folder
        //      2. C:\Windows\(System32 | SysWow64 )
        //      3. 16-bit system directory   <-- ignored
        //      4. C:\Windows
        //      5. %pwd%
        //      6. AppDatas
        //      }
        public static Tuple <ModuleSearchStrategy, string> FindPeFromDefault(PE RootPe, string ModuleName, SxsEntries SxsCache, List <string> CustomSearchFolders, string WorkingDirectory)
        {
            bool   Wow64Dll     = RootPe.IsWow64Dll();
            string RootPeFolder = Path.GetDirectoryName(RootPe.Filepath);
            string FoundPePath  = null;

            Environment.SpecialFolder WindowsSystemFolder = (Wow64Dll) ?
                                                            Environment.SpecialFolder.SystemX86 :
                                                            Environment.SpecialFolder.System;
            String WindowsSystemFolderPath = Environment.GetFolderPath(WindowsSystemFolder);


            // -1. Look in Sxs manifest (copious reversing needed)
            // TODO : find dll search order
            if (SxsCache.Count != 0)
            {
                SxsEntry Entry = SxsCache.Find(SxsItem =>
                                               string.Equals(SxsItem.Name, ModuleName, StringComparison.OrdinalIgnoreCase)
                                               );

                if (Entry != null)
                {
                    return(new Tuple <ModuleSearchStrategy, string>(ModuleSearchStrategy.SxS, Entry.Path));
                }
            }


            // 0. Look in well-known dlls list
            // HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\KnownDLLs
            // https://blogs.msdn.microsoft.com/larryosterman/2004/07/19/what-are-known-dlls-anyway/
            String KnownDll = Phlib.GetKnownDlls(Wow64Dll).Find(x => string.Equals(x, ModuleName, StringComparison.OrdinalIgnoreCase));

            if (KnownDll != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.WellKnownDlls,
                           Path.Combine(WindowsSystemFolderPath, KnownDll)
                           ));
            }


            // 1. Look in application folder
            FoundPePath = FindPeFromPath(ModuleName, new List <string>(new string[] { RootPeFolder }), Wow64Dll);
            if (FoundPePath != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.ApplicationDirectory,
                           FoundPePath
                           ));
            }

            // {2-3-4}. Look in system folders
            List <String> SystemFolders = new List <string>(new string[] {
                WindowsSystemFolderPath,
                Environment.GetFolderPath(Environment.SpecialFolder.Windows)
            }
                                                            );

            FoundPePath = FindPeFromPath(ModuleName, SystemFolders, Wow64Dll);
            if (FoundPePath != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.WindowsFolder,
                           FoundPePath
                           ));
            }

            // 5. Look in current directory
            // Ignored for the time being since we can't know from
            // where the exe is run
            // TODO : Add a user supplied path emulating %cwd%
            FoundPePath = FindPeFromPath(ModuleName, new List <string>(new string[] { WorkingDirectory }), Wow64Dll);
            if (FoundPePath != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.WorkingDirectory,
                           FoundPePath
                           ));
            }

            // 6. Look in local app data (check for python for exemple)



            // 7. Find in PATH
            string        PATH        = Environment.GetEnvironmentVariable("PATH");
            List <String> PATHFolders = new List <string>(PATH.Split(';'));

            // Filter out empty paths, since it resolve to the current working directory
            // fix https://github.com/lucasg/Dependencies/issues/51
            PATHFolders = PATHFolders.Where(path => path.Length != 0).ToList();


            FoundPePath = FindPeFromPath(ModuleName, PATHFolders, Wow64Dll);
            if (FoundPePath != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.Environment,
                           FoundPePath
                           ));
            }


            // 8. Check if it's an absolute import
            if ((Path.GetFullPath(ModuleName) == ModuleName) && File.Exists(ModuleName))
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.Fullpath,
                           ModuleName
                           ));
            }


            // 0xff. Allow the user to supply custom search folders, to take into account
            // specific cases.
            FoundPePath = FindPeFromPath(ModuleName, CustomSearchFolders, Wow64Dll);
            if (FoundPePath != null)
            {
                return(new Tuple <ModuleSearchStrategy, string>(
                           ModuleSearchStrategy.UserDefined,
                           FoundPePath
                           ));
            }

            return(new Tuple <ModuleSearchStrategy, string>(
                       ModuleSearchStrategy.NOT_FOUND,
                       null
                       ));
        }
Exemple #24
0
        static void Main(string[] args)
        {
            // always the first call to make
            Phlib.InitializePhLib();

            int         recursion_depth = 0;
            bool        early_exit      = false;
            bool        show_help       = false;
            bool        export_as_json  = false;
            bool        use_bin_cache   = false;
            DumpCommand command         = null;

            OptionSet opts = new OptionSet()
            {
                { "h|help", "show this message and exit", v => show_help = v != null },
                { "json", "Export results in json format", v => export_as_json = v != null },
                { "cache", "load and use binary cache to prevent dll file locking", v => use_bin_cache = v != null },
                { "d|depth=", "limit recursion depth when analysing loaded modules or dependency chain. Default value is infinite", (int v) => recursion_depth = v },
                { "knowndll", "List all known dlls", v => { DumpKnownDlls(GetObjectPrinter(export_as_json));  early_exit = true; } },
                { "apisets", "List apisets redirections", v => { DumpApiSets(GetObjectPrinter(export_as_json));  early_exit = true; } },
                { "apisetsdll", "List apisets redirections from apisetschema <FILE>", v => command = DumpApiSets },
                { "manifest", "show manifest information embedded in <FILE>", v => command = DumpManifest },
                { "sxsentries", "dump all of <FILE>'s sxs dependencies", v => command = DumpSxsEntries },
                { "imports", "dump <FILE> imports", v => command = DumpImports },
                { "exports", "dump <FILE> exports", v => command = DumpExports },
                { "assemblyrefs", "dump <FILE> assemblyrefs", v => command = DumpAssemblyReferences },
                { "modulerefs", "dump <FILE> modulerefs", v => command = DumpModuleReferences },
                { "chain", "dump <FILE> whole dependency chain", v => command = DumpDependencyChain },
                { "modules", "dump <FILE> resolved modules", v => command = DumpModules },
            };

            List <string> eps = opts.Parse(args);

            if (early_exit)
            {
                return;
            }

            if ((show_help) || (args.Length == 0) || (command == null))
            {
                DumpUsage();
                return;
            }

            BinaryCache.InitializeBinaryCache(use_bin_cache);

            if (eps.Count == 0)
            {
                Console.Error.WriteLine("[x] Command {0:s} needs to have a PE <FILE> argument", command.Method.Name);
                Console.Error.WriteLine("");

                DumpUsage();
                return;
            }

            String FileName = eps[0];

            if (!NativeFile.Exists(FileName))
            {
                Console.Error.WriteLine("[x] Could not find file {0:s} on disk", FileName);
                return;
            }

            Debug.WriteLine("[-] Loading file {0:s} ", FileName);
            PE Pe = new PE(FileName);

            if (!Pe.Load())
            {
                Console.Error.WriteLine("[x] Could not load file {0:s} as a PE", FileName);
                return;
            }

            command(Pe, GetObjectPrinter(export_as_json), recursion_depth);
        }