Repository: advanced-threat-research/DotDumper
Branch: main
Commit: 82ab3750f81b
Files: 193
Total size: 4.6 MB
Directory structure:
gitextract_4_7p2e3s/
├── DotDumper/
│ ├── ArgumentHandler.cs
│ ├── Config.cs
│ ├── DotDumper.csproj
│ ├── Helpers/
│ │ ├── ArgumentHelper.cs
│ │ ├── AssemblyMapper.cs
│ │ ├── Hashes.cs
│ │ ├── LogEntryHelper.cs
│ │ ├── MissedAssemblyDumper.cs
│ │ ├── RaceConditionHandler.cs
│ │ ├── Serialise.cs
│ │ └── StagnationHandler.cs
│ ├── HookHandlers/
│ │ ├── Activator/
│ │ │ └── ActivatorHooks.cs
│ │ ├── Assembly/
│ │ │ └── AssemblyHooks.cs
│ │ ├── Console/
│ │ │ └── ConsoleHooks.cs
│ │ ├── Convert/
│ │ │ └── ConvertHooks.cs
│ │ ├── Directory/
│ │ │ └── DirectoryHooks.cs
│ │ ├── Environment/
│ │ │ └── EnvironmentHooks.cs
│ │ ├── File/
│ │ │ └── FileHooks.cs
│ │ ├── GenericHookHelper.cs
│ │ ├── MethodBase/
│ │ │ └── MethodBaseHooks.cs
│ │ ├── Path/
│ │ │ └── PathHooks.cs
│ │ ├── Process/
│ │ │ └── ProcessHooks.cs
│ │ ├── ResourceManager/
│ │ │ └── ResourceManagerHooks.cs
│ │ ├── Thread/
│ │ │ └── ThreadHooks.cs
│ │ └── Type/
│ │ ├── TypeHooks.cs
│ │ └── TypeHooksHelper.cs
│ ├── Hooks/
│ │ ├── Hook.cs
│ │ ├── HookManager.cs
│ │ ├── InteropFunctions.cs
│ │ ├── OriginalManagedFunctions.cs
│ │ └── OriginalUnmanagedFunctions.cs
│ ├── Logger.cs
│ ├── Models/
│ │ ├── Argument.cs
│ │ ├── AssemblyObject.cs
│ │ ├── Hash.cs
│ │ ├── LogEntry.cs
│ │ └── UnmanagedMethodInfo.cs
│ ├── Pipes/
│ │ └── PipeManager.cs
│ ├── Program.cs
│ ├── Properties/
│ │ └── AssemblyInfo.cs
│ ├── app.config
│ ├── bin/
│ │ └── Debug/
│ │ ├── DotDumper.exe.config
│ │ ├── DotDumper.pdb
│ │ ├── System.Buffers.xml
│ │ ├── System.Memory.xml
│ │ ├── System.Numerics.Vectors.xml
│ │ ├── System.Runtime.CompilerServices.Unsafe.xml
│ │ └── System.Security.Cryptography.Pkcs.xml
│ ├── obj/
│ │ ├── Debug/
│ │ │ ├── .NETFramework,Version=v4.7.2.AssemblyAttributes.cs
│ │ │ ├── .NETFramework,Version=v4.8.AssemblyAttributes.cs
│ │ │ ├── DesignTimeResolveAssemblyReferences.cache
│ │ │ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ │ │ ├── DotDumper.csproj.AssemblyReference.cache
│ │ │ ├── DotDumper.csproj.CopyComplete
│ │ │ ├── DotDumper.csproj.CoreCompileInputs.cache
│ │ │ ├── DotDumper.csproj.FileListAbsolute.txt
│ │ │ └── DotDumper.pdb
│ │ └── x64/
│ │ └── Debug/
│ │ ├── .NETFramework,Version=v4.7.2.AssemblyAttributes.cs
│ │ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ │ ├── DotDumper.csproj.AssemblyReference.cache
│ │ ├── DotDumper.csproj.CoreCompileInputs.cache
│ │ ├── DotDumper.csproj.FileListAbsolute.txt
│ │ └── DotDumper.pdb
│ └── packages.config
├── DotDumper.sln
├── LICENSE
├── README.md
└── packages/
├── PeNet.2.9.9/
│ ├── .signature.p7s
│ └── PeNet.2.9.9.nupkg
├── PeNet.Asn1.2.0.0/
│ ├── .signature.p7s
│ └── PeNet.Asn1.2.0.0.nupkg
├── System.Buffers.4.5.1/
│ ├── .signature.p7s
│ ├── LICENSE.TXT
│ ├── System.Buffers.4.5.1.nupkg
│ ├── THIRD-PARTY-NOTICES.TXT
│ ├── lib/
│ │ ├── net461/
│ │ │ └── System.Buffers.xml
│ │ ├── netcoreapp2.0/
│ │ │ └── _._
│ │ ├── netstandard1.1/
│ │ │ └── System.Buffers.xml
│ │ ├── netstandard2.0/
│ │ │ └── System.Buffers.xml
│ │ └── uap10.0.16299/
│ │ └── _._
│ ├── ref/
│ │ ├── net45/
│ │ │ └── System.Buffers.xml
│ │ ├── netcoreapp2.0/
│ │ │ └── _._
│ │ ├── netstandard1.1/
│ │ │ └── System.Buffers.xml
│ │ ├── netstandard2.0/
│ │ │ └── System.Buffers.xml
│ │ └── uap10.0.16299/
│ │ └── _._
│ ├── useSharedDesignerContext.txt
│ └── version.txt
├── System.Diagnostics.Process.4.3.0/
│ ├── .signature.p7s
│ ├── System.Diagnostics.Process.4.3.0.nupkg
│ ├── ThirdPartyNotices.txt
│ ├── dotnet_library_license.txt
│ ├── lib/
│ │ ├── MonoAndroid10/
│ │ │ └── _._
│ │ ├── MonoTouch10/
│ │ │ └── _._
│ │ ├── xamarinios10/
│ │ │ └── _._
│ │ ├── xamarinmac20/
│ │ │ └── _._
│ │ ├── xamarintvos10/
│ │ │ └── _._
│ │ └── xamarinwatchos10/
│ │ └── _._
│ ├── ref/
│ │ ├── MonoAndroid10/
│ │ │ └── _._
│ │ ├── MonoTouch10/
│ │ │ └── _._
│ │ ├── netstandard1.3/
│ │ │ ├── System.Diagnostics.Process.xml
│ │ │ ├── de/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── es/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── fr/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── it/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── ja/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── ko/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── ru/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── zh-hans/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ └── zh-hant/
│ │ │ └── System.Diagnostics.Process.xml
│ │ ├── netstandard1.4/
│ │ │ ├── System.Diagnostics.Process.xml
│ │ │ ├── de/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── es/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── fr/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── it/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── ja/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── ko/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── ru/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ ├── zh-hans/
│ │ │ │ └── System.Diagnostics.Process.xml
│ │ │ └── zh-hant/
│ │ │ └── System.Diagnostics.Process.xml
│ │ ├── xamarinios10/
│ │ │ └── _._
│ │ ├── xamarinmac20/
│ │ │ └── _._
│ │ ├── xamarintvos10/
│ │ │ └── _._
│ │ └── xamarinwatchos10/
│ │ └── _._
│ └── runtimes/
│ └── win7/
│ └── lib/
│ └── netcore50/
│ └── _._
├── System.Memory.4.5.5/
│ ├── .signature.p7s
│ ├── LICENSE.TXT
│ ├── System.Memory.4.5.5.nupkg
│ ├── THIRD-PARTY-NOTICES.TXT
│ ├── lib/
│ │ ├── net461/
│ │ │ └── System.Memory.xml
│ │ ├── netcoreapp2.1/
│ │ │ └── _._
│ │ ├── netstandard1.1/
│ │ │ └── System.Memory.xml
│ │ └── netstandard2.0/
│ │ └── System.Memory.xml
│ ├── ref/
│ │ └── netcoreapp2.1/
│ │ └── _._
│ ├── useSharedDesignerContext.txt
│ └── version.txt
├── System.Numerics.Vectors.4.5.0/
│ ├── .signature.p7s
│ ├── LICENSE.TXT
│ ├── System.Numerics.Vectors.4.5.0.nupkg
│ ├── THIRD-PARTY-NOTICES.TXT
│ ├── lib/
│ │ ├── MonoAndroid10/
│ │ │ └── _._
│ │ ├── MonoTouch10/
│ │ │ └── _._
│ │ ├── net46/
│ │ │ └── System.Numerics.Vectors.xml
│ │ ├── netcoreapp2.0/
│ │ │ └── _._
│ │ ├── netstandard1.0/
│ │ │ └── System.Numerics.Vectors.xml
│ │ ├── netstandard2.0/
│ │ │ └── System.Numerics.Vectors.xml
│ │ ├── portable-net45+win8+wp8+wpa81/
│ │ │ └── System.Numerics.Vectors.xml
│ │ ├── uap10.0.16299/
│ │ │ └── _._
│ │ ├── xamarinios10/
│ │ │ └── _._
│ │ ├── xamarinmac20/
│ │ │ └── _._
│ │ ├── xamarintvos10/
│ │ │ └── _._
│ │ └── xamarinwatchos10/
│ │ └── _._
│ ├── ref/
│ │ ├── MonoAndroid10/
│ │ │ └── _._
│ │ ├── MonoTouch10/
│ │ │ └── _._
│ │ ├── net45/
│ │ │ └── System.Numerics.Vectors.xml
│ │ ├── net46/
│ │ │ └── System.Numerics.Vectors.xml
│ │ ├── netcoreapp2.0/
│ │ │ └── _._
│ │ ├── netstandard1.0/
│ │ │ └── System.Numerics.Vectors.xml
│ │ ├── netstandard2.0/
│ │ │ └── System.Numerics.Vectors.xml
│ │ ├── uap10.0.16299/
│ │ │ └── _._
│ │ ├── xamarinios10/
│ │ │ └── _._
│ │ ├── xamarinmac20/
│ │ │ └── _._
│ │ ├── xamarintvos10/
│ │ │ └── _._
│ │ └── xamarinwatchos10/
│ │ └── _._
│ ├── useSharedDesignerContext.txt
│ └── version.txt
├── System.Runtime.CompilerServices.Unsafe.6.0.0/
│ ├── .signature.p7s
│ ├── LICENSE.TXT
│ ├── System.Runtime.CompilerServices.Unsafe.6.0.0.nupkg
│ ├── THIRD-PARTY-NOTICES.TXT
│ ├── buildTransitive/
│ │ ├── netcoreapp2.0/
│ │ │ └── System.Runtime.CompilerServices.Unsafe.targets
│ │ └── netcoreapp3.1/
│ │ └── _._
│ ├── lib/
│ │ ├── net461/
│ │ │ └── System.Runtime.CompilerServices.Unsafe.xml
│ │ ├── net6.0/
│ │ │ └── System.Runtime.CompilerServices.Unsafe.xml
│ │ ├── netcoreapp3.1/
│ │ │ └── System.Runtime.CompilerServices.Unsafe.xml
│ │ └── netstandard2.0/
│ │ └── System.Runtime.CompilerServices.Unsafe.xml
│ └── useSharedDesignerContext.txt
└── System.Security.Cryptography.Pkcs.6.0.1/
├── .signature.p7s
├── LICENSE.TXT
├── System.Security.Cryptography.Pkcs.6.0.1.nupkg
├── THIRD-PARTY-NOTICES.TXT
├── buildTransitive/
│ ├── netcoreapp2.0/
│ │ └── System.Security.Cryptography.Pkcs.targets
│ └── netcoreapp3.1/
│ └── _._
├── lib/
│ ├── net461/
│ │ └── System.Security.Cryptography.Pkcs.xml
│ ├── net6.0/
│ │ └── System.Security.Cryptography.Pkcs.xml
│ ├── netcoreapp3.1/
│ │ └── System.Security.Cryptography.Pkcs.xml
│ ├── netstandard2.0/
│ │ └── System.Security.Cryptography.Pkcs.xml
│ └── netstandard2.1/
│ └── System.Security.Cryptography.Pkcs.xml
├── runtimes/
│ └── win/
│ └── lib/
│ ├── net461/
│ │ └── System.Security.Cryptography.Pkcs.xml
│ ├── net6.0/
│ │ └── System.Security.Cryptography.Pkcs.xml
│ ├── netcoreapp3.1/
│ │ └── System.Security.Cryptography.Pkcs.xml
│ ├── netstandard2.0/
│ │ └── System.Security.Cryptography.Pkcs.xml
│ └── netstandard2.1/
│ └── System.Security.Cryptography.Pkcs.xml
└── useSharedDesignerContext.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: DotDumper/ArgumentHandler.cs
================================================
using System;
using System.IO;
using System.Reflection;
namespace DotDumper
{
///
/// This class handles user-provided arguments by parsing them, and updating the fields in the Config class when need be. At last, a check is performed to ensure that the required arguments are provided.
///
class ArgumentHandler
{
#region Argument markers and descriptions
///
/// The marker for the sample path (equals "-file")
///
public const string SamplePathMarker = "-file";
///
/// The description for the sample path
///
public const string SamplePathDescription = "The complete path to the file to launch. This is the only mandatory argument, if the provided file has\n\t\tan entry point. Note that providing only a single CLI argument with the file's location also works!";
///
/// The marker for the logging folder name (equals "-log")
///
public const string LoggingFolderNameMarker = "-log";
///
/// The description of the logging folder name
///
public const string LoggingFolderNameDescription = "The name of the folder to place artifacts in, which will be placed within the same folder as DotDumper.\n\t\tIf this argument is missing, the sample's file name will be used.";
///
/// The marker for the deprecated function inclusion/exclusion
///
public const string DeprecatedFunctionMarker = "-deprecated";
///
/// The description for the deprecated function inclusion/exclusion
///
public const string DeprecatedFunctionDescription = "Hook deprecated functions, needs to be true or false. The default value is true";
///
/// The marker for the argument which decides if the loaded hooks should be displayed
///
public const string LogHooksMarker = "-displayHooks";
///
/// The description for the logging of all loaded hooks
///
public const string LogHooksDescription = "Print all hooked functions upon startup, needs to be true or false. The default value is true";
///
/// The race condition marker, which indicates an overwrite of the delay on the race condition timer
///
public const string RaceConditionDueTimeMarker = "-raceTime";
///
/// The decription of the race condition delay argument
///
public const string RaceConditionDueTimeDescription = "The amount of milliseconds that are between the hook and re-hook of Invoke-related functions.\n\t\tThe default value is 20";
///
/// Decides if the entry point of the binary should be ignored
///
public const string OverrideEntryPointMarker = "-overrideEntry";
///
/// The description of the override functionality
///
public const string OverrideEntryPointDescription = "Defines if the default entry point should be overridden, needs to be true or false. The default value\n\t\tis false. The use of -fqcn and -functionName is mandatory with this argument, whereas -args and\n\t\t-argc are optional (though both -args and -argc need to be used together when they are used).";
///
/// The marker for the fully qualified class name (including the namespace)
///
public const string DllFullyQualifiedClassNameMarker = "-fqcn";
///
/// The description of the fully qualified class name (including the namespace)
///
public const string DllFullyQualifiedClassDescription = "The fully qualified class, including namespace, to find the function in. Only used when overriding\n\t\tthe entry point. Needs to be used together with -functionName.";
///
/// The marker for the function name
///
public const string DllFunctionNameMarker = "-functionName";
///
/// The description for the function name's description
///
public const string DllFunctionNameDescription = "The function name to call, excluding types and parameters, within the fully qualified class.\n\t\tOnly used when overriding the entry point. Needs to be used together with -fqcn.";
///
/// The marker for the arguments
///
public const string PayloadArgumentsMarker = "-args";
///
/// The description for the arguments
///
public const string PayloadArgumentsDescription = "The arguments for the function, providing the type and value at once, split by a pipe,\n\t\tsuch as int|7, double|3.14, or string|myValue\n\t\tThe following types are supported: bool, byte, sbyte, char, decimal, double, float, int, uint, long,\n\t\tulong, short, ushort, string, as well as arrays of each of those types. Arrays are indicated using \"[]\"\n\t\tdirectly after the type, such as \"string[]\". The values are to be split using commas.\n\t\tAn example: string[]|string1,string2,string3\n\t\tNull is also possible, but note that this value (or lack thereof) should not be capitalised.\n\t\tNeeds to be used together with -argc.";
///
/// The index of the first argument in the provided array of DotDumper arguments by the user
///
private static int PayloadArgumentsIndex = -1;
///
/// The marker for the argument count
///
public const string PayloadArgumentCountMarker = "-argc";
///
/// The description for the argument count
///
public const string PayloadArgumentCountDescription = "The number of arguments that are provided, as an integer. Needs to be used together with -args.";
///
/// The amount of arguments, as provided by the user
///
private static int PayloadArgumentCount = -1;
///
/// The marker to decide if sleep calls should be skipped
///
public const string SleepSkipMarker = "-sleepSkip";
///
/// The description for the sleep skip functionality
///
public const string SleepSkipDescription = "Defines if Thread.Sleep calls need to be skipped, needs to be true or false. The default value is true.";
///
/// The marker to decide if logs should be printed to the console
///
public const string ConsolePrintingMarker = "-console";
///
/// The description for the optional console logging functionality
///
public const string ConsolePrintingDescription = "Defines if the logging should be printed to the console window or not. The default value is true.";
///
/// The help marker
///
public const string HelpMarker = "-help";
///
/// The description of the help marker
///
public const string HelpDescription = "Prints the help menu. This cannot be used in combination with other options, as they will be ignored.";
#endregion
///
/// A helper function to combine a marker and a description, including the required newlines and tabs
///
/// The marker to combine with the description
/// The description to combine with the marker
/// The combined marker and description
private static string CombineMarkerAndDescription(string marker, string description)
{
return marker + "\n" +
"\t\t" + description + "\n";
}
///
/// A helper function to get the complete help message as a single string
///
/// The complete help message
private static string GetHelpMessage()
{
//Initialises the program's version, and a note that all arguments are case sensitive
string help = Program.VERSION + "\n" +
"Note that all arguments are cases sensitive!\n";
//Adds all the markers and their descriptions into the help message
help += CombineMarkerAndDescription(SamplePathMarker, SamplePathDescription);
help += CombineMarkerAndDescription(LoggingFolderNameMarker, LoggingFolderNameDescription);
help += CombineMarkerAndDescription(DeprecatedFunctionMarker, DeprecatedFunctionDescription);
help += CombineMarkerAndDescription(LogHooksMarker, LogHooksDescription);
help += CombineMarkerAndDescription(RaceConditionDueTimeMarker, RaceConditionDueTimeDescription);
help += CombineMarkerAndDescription(OverrideEntryPointMarker, OverrideEntryPointDescription);
help += CombineMarkerAndDescription(DllFullyQualifiedClassNameMarker, DllFullyQualifiedClassDescription);
help += CombineMarkerAndDescription(DllFunctionNameMarker, DllFunctionNameDescription);
help += CombineMarkerAndDescription(PayloadArgumentsMarker, PayloadArgumentsDescription);
help += CombineMarkerAndDescription(PayloadArgumentCountMarker, PayloadArgumentCountDescription);
help += CombineMarkerAndDescription(SleepSkipMarker, SleepSkipDescription);
help += CombineMarkerAndDescription(ConsolePrintingMarker, ConsolePrintingDescription);
help += CombineMarkerAndDescription(HelpMarker, HelpDescription);
//Adds the well known message to keep the console open, if it wasn't launched via a terminal
help += "\nPress any key to exit...";
//Return the complete message
return help;
}
///
/// Checks if the help marker is used as an argument at any point, or if the given array is null or empty. If any of the mentioned conditions is met, the help menu is printed, after which DotDumper will await for the user to press any key, leading to DotDumper's shutdown.
///
/// The args array to check for the help parameter
private static void CheckHelp(string[] args)
{
//Declare the variable which will incidate if the help marker has been found
bool help = false;
//If the provided argument is null or empty, the help menu must be shown, as one at least needs to provide a file to DotDumper
if (args == null || args.Length == 0)
{
help = true;
}
else
{
//If it is not null nor empty, iterate over all arguments
for (int i = 0; i < args.Length; i++)
{
//Check if the current argument equals the helpmarker
if (args[i].Equals(HelpMarker))
{
//Set the help variable to true
help = true;
//Break the loop, as the help marker has been found
break;
}
}
}
//If the help variable is true
if (help)
{
//Get and write the help message
Console.WriteLine(GetHelpMessage());
//Wait for any user input
Console.ReadKey();
//Exit
Environment.Exit(0);
}
//If the variable is false, nothing has to be done
}
///
/// Checks (in the listed order) if the given value is a file in the current directory, the directory of DotDumper, or if it is a full path.
///
/// The (partial) path and file name of the target file
private static void CheckFile(string value)
{
//Check if the sample is located in the current working directory
string filePath = Directory.GetCurrentDirectory() + @"\" + value;
if (File.Exists(filePath))
{
Config.SamplePath = filePath;
}
//Check if the sample is located in the same folder as DotDumper
filePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\" + value;
if (File.Exists(filePath))
{
Config.SamplePath = filePath;
}
//Check if a full path is given, but only after the two other defined directions have been checked, as the Assembly object can only be loaded with a full path, not a relative one
if (File.Exists(value))
{
Config.SamplePath = value;
}
//Only throw the exception if the sample path hasn't been set (meaning the sample hasn't been found)
if (Config.SamplePath == null)
{
//Throw an error if none of the above options results in a match with a file on the user's file system
throw new Exception("The provided sample path at \"" + value + "\" does not exist, and cannot be found in the current working directory nor in DotDumper's folder!");
}
}
///
/// Parses the arguments and sets the config fields that need to be updated based on the arguments. The checks afterwards ensure that only correct combinations of arguments are allowed, or an error is thrown.
///
///
public static void ParseArguments(string[] args)
{
//Check if the help marker is provided. If so, this function does not return
CheckHelp(args);
/*
* Ensure that a single argument leading to the path is possible, when the size of args equals 1,
* it is to be redefined as an array with the size of two, where the first argument is "-file"
*/
try
{
//Only attempt this if there is a single argument
if (args.Length == 1)
{
//Call the check file function, which throws an exception if it fails
CheckFile(args[0]);
/*
* If this code is reached, the function call above was successful, otherwise I'd throw an exception.
* Because of that, the normal CLI parsing can continue if the string array is set again, with the file
* path marker as the first argument, and its value as the second, as if it were done manually
*/
args = new string[] { SamplePathMarker, args[0] };
}
}
catch (Exception)
{
/*
* The sole argument was not equal to the file path marker. There is no need to handle this error, other than
* ignoring it.
*/
}
//Open the try block to handle wrong argument exceptions
try
{
//Declare i prior to the loop, as it is also used outside of the loop in some cases
int i;
for (i = 0; i < args.Length; i++)
{
//Get the current argument, in lower case
string arg = args[i];
//Check if the next index exists, as the marker is always accompanied by at least one argument
if (NextIndexExists(args, i))
{
//Get the value of the next index, which is known to exist at this point
string value = args[i + 1];
//Handle all marker options (aside from the help one, which was handled before the try block)
if (IsEqual(arg, SamplePathMarker))
{
CheckFile(value);
}
else if (IsEqual(arg, LoggingFolderNameMarker))
{
Config.LoggerFolder = value;
}
else if (IsEqual(arg, DeprecatedFunctionMarker))
{
try
{
Config.IncludeDeprecatedFunctions = Convert.ToBoolean(value);
}
catch (Exception)
{
throw new Exception("The boolean to determine if deprecated functions should also be hooked is not a valid boolean: \"" + value + "\"!");
}
}
else if (IsEqual(arg, LogHooksMarker))
{
try
{
Config.LogHooks = Convert.ToBoolean(value);
}
catch (Exception)
{
throw new Exception("The boolean to determine if the hooks should be logged is not a valid boolean: \"" + value + "\"!");
}
}
else if (IsEqual(arg, RaceConditionDueTimeMarker))
{
try
{
int raceConditionTime = Convert.ToInt32(value);
if (raceConditionTime <= 0)
{
throw new Exception();
}
Config.RaceConditionDueTime = raceConditionTime;
}
catch (Exception)
{
throw new Exception("The integer to determine the duration of the time the timer should wait before rehooking invoke related functions is not a valid integer with a size of more than zero: \"" + value + "\"!");
}
}
else if (IsEqual(arg, OverrideEntryPointMarker))
{
try
{
Config.OverrideEntryPoint = Convert.ToBoolean(value);
}
catch (Exception)
{
throw new Exception("The boolean to determine if a user-specified entry point should be used is not a valid boolean: \"" + value + "\"!");
}
}
else if (IsEqual(arg, DllFullyQualifiedClassNameMarker))
{
Config.DllFullyQualifiedClassName = value;
}
else if (IsEqual(arg, DllFunctionNameMarker))
{
Config.DllFunctionName = value;
}
else if (IsEqual(arg, PayloadArgumentsMarker))
{
PayloadArgumentsIndex = i + 1;
}
else if (IsEqual(arg, PayloadArgumentCountMarker))
{
try
{
int argCount = Convert.ToInt32(value);
if (argCount <= 0)
{
throw new Exception();
}
PayloadArgumentCount = argCount;
}
catch (Exception)
{
throw new Exception("The integer that indicates the amount of arguments the function requires is not a valid integer that is bigger than one: \"" + value + "\"!");
}
}
else if (IsEqual(arg, SleepSkipMarker))
{
try
{
Config.SleepSkip = Convert.ToBoolean(value);
}
catch (Exception)
{
throw new Exception("The boolean to determine if sleep calls need to be skipped is not a valid boolean: \"" + value + "\"!");
}
}
else if (IsEqual(arg, ConsolePrintingMarker))
{
try
{
Config.PrintLogsToConsole = Convert.ToBoolean(value);
}
catch (Exception)
{
throw new Exception("The boolean to determine if logs need to be printed to the console window is not a valid boolean: \"" + value + "\"!");
}
}
}
}
#region Mandatory value checks
//If no sample was provided, an error is thrown
if (Config.SamplePath == null)
{
throw new Exception("No file has been provided! Use \"" + SamplePathMarker + "\" to specify the file, or use \"" + HelpMarker + "\" to show the help menu!");
}
//If the name of the logger folder is not provided, the name of the given sample is used. The sample exists and is not null, as previous checks already ensured that
if (Config.LoggerFolder == null)
{
SetLoggerFolderName();
}
#endregion
#region Optional value checks
//If the entry point should be overridden
if (Config.OverrideEntryPoint == true)
{
//The fully qualified class name needs to be present
if (Config.DllFullyQualifiedClassName == null)
{
throw new Exception("The default entry point is to be overridden, but the fully qualified class name that is to be used, is null!");
}
//As well as the function name
if (Config.DllFunctionName == null)
{
throw new Exception("The default entry point is to be overridden, but the function name that is to be used, is null!");
}
//Arguments are optional, and can also be used for an entry point, which is why they are outside this if-block
}
//If the index and count are not equal to their initial value of -1, it means that they were both provided
if (PayloadArgumentsIndex > 0 && PayloadArgumentCount > 0)
{
//Given that they are both provided, they need to be handled
SetDllArguments(args, PayloadArgumentsIndex, PayloadArgumentCount);
}
else //In case one or both of these values is still equal to -1
{
//If the payload count is missing, an error is thrown
if (PayloadArgumentCount > 0)
{
throw new Exception("No argument count was found, even though arguments were specified!");
}
else if (PayloadArgumentsIndex > 0) //If the payload count is more than zero, it means that the index is missing, for which an error needs to be thrown
{
throw new Exception("No arguments were found, even though an argument count was specified!");
}
}
#endregion
}
catch (Exception ex) //Any thrown exception is caught, printed to the standard output, after which DotDumper waits for any key to exit
{
Console.WriteLine("[ERROR] " + ex.Message + "\n\nPress any key to exit...");
Console.ReadKey();
Environment.Exit(0);
}
}
///
/// Sets the logger folder name to the given file name, appending "_DotDumper" to it until the folder does not exist
///
private static void SetLoggerFolderName()
{
string loggerFolder = Path.GetFileNameWithoutExtension(Config.SamplePath);
while (true)
{
if (Directory.Exists(loggerFolder) == false && File.Exists(loggerFolder) == false)
{
break;
}
else
{
loggerFolder += "_DotDumper";
}
}
Config.LoggerFolder = loggerFolder;
}
///
/// Tries to fetch the next index from the array, based on the provided array and index
///
/// The array to use
/// The index to check if there is a next element
/// True if a next element exists, false if not
private static bool NextIndexExists(string[] args, int index)
{
try
{
string element = args[index + 1];
return true;
}
catch (Exception)
{
return false;
}
}
///
/// Sets the DllArguments field in the config, based on the provided parameters.
///
/// The complete set of parameters that DotDumper received
/// The index at which the first argument is found
/// The amount of arguments that are provided by the user
private static void SetDllArguments(string[] args, int payloadArgumentsIndex, int payloadArgumentCount)
{
//The object array that will contain all arguments
object[] dllArgs = new object[payloadArgumentCount];
//The string array that contains the split array for each of the provided types
string[] arrayValues;
//Iterate as many times as there are arguments
for (int i = 0; i < payloadArgumentCount; i++)
{
//Get the index to fetch data from the args array
int index = payloadArgumentsIndex + i;
//Get and split the data
string[] splitted = args[index].Split('|');
//If there are more or less than two fields, something is wrong, thus an error is thrown
if (splitted.Length != 2)
{
throw new Exception("The provided type-value combination is invalid: \"" + args[index] + "\"!");
}
//Get the type from the array, as a lowercase string (so a typo wont influence the outcome here)
string type = splitted[0].ToLowerInvariant();
//Get the value of the given argument
string value = splitted[1];
//Handle any type of supported variables
switch (type)
{
case "bool":
dllArgs[i] = Convert.ToBoolean(value);
break;
case "bool[]":
arrayValues = HandleArray(value);
bool[] bools = new bool[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
bools[count] = Convert.ToBoolean(arrayValues[count]);
}
dllArgs[i] = bools;
break;
case "byte":
dllArgs[i] = Convert.ToByte(value);
break;
case "byte[]":
arrayValues = HandleArray(value);
byte[] bytes = new byte[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
bytes[count] = Convert.ToByte(arrayValues[count]);
}
dllArgs[i] = bytes;
break;
case "sbyte":
dllArgs[i] = Convert.ToSByte(value);
break;
case "sbyte[]":
arrayValues = HandleArray(value);
sbyte[] sbytes = new sbyte[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
sbytes[count] = Convert.ToSByte(arrayValues[count]);
}
dllArgs[i] = sbytes;
break;
case "char":
dllArgs[i] = Convert.ToChar(value);
break;
case "char[]":
arrayValues = HandleArray(value);
char[] chars = new char[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
chars[count] = Convert.ToChar(arrayValues[count]);
}
dllArgs[i] = chars;
break;
case "decimal":
dllArgs[i] = Convert.ToDecimal(value);
break;
case "decimal[]":
arrayValues = HandleArray(value);
decimal[] decimals = new decimal[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
decimals[count] = Convert.ToDecimal(arrayValues[count]);
}
dllArgs[i] = decimals;
break;
case "double":
dllArgs[i] = Convert.ToDouble(value);
break;
case "double[]":
arrayValues = HandleArray(value);
double[] doubles = new double[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
doubles[count] = Convert.ToDouble(arrayValues[count]);
}
dllArgs[i] = doubles;
break;
case "float":
dllArgs[i] = Convert.ToSingle(value);
break;
case "float[]":
arrayValues = HandleArray(value);
float[] floats = new float[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
floats[count] = Convert.ToSingle(arrayValues[count]);
}
dllArgs[i] = floats;
break;
case "int":
dllArgs[i] = Convert.ToInt32(value);
break;
case "int[]":
arrayValues = HandleArray(value);
int[] integers = new int[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
integers[count] = Convert.ToInt32(arrayValues[count]);
}
dllArgs[i] = integers;
break;
case "uint":
dllArgs[i] = Convert.ToUInt32(value);
break;
case "uint[]":
arrayValues = HandleArray(value);
uint[] unsignedIntegers = new uint[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
unsignedIntegers[count] = Convert.ToUInt32(arrayValues[count]);
}
dllArgs[i] = unsignedIntegers;
break;
case "long":
dllArgs[i] = Convert.ToInt64(value);
break;
case "long[]":
arrayValues = HandleArray(value);
long[] longs = new long[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
longs[count] = Convert.ToInt64(arrayValues[count]);
}
dllArgs[i] = longs;
break;
case "ulong":
dllArgs[i] = Convert.ToUInt64(value);
break;
case "ulong[]":
arrayValues = HandleArray(value);
ulong[] unsignedLongs = new ulong[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
unsignedLongs[count] = Convert.ToUInt64(arrayValues[count]);
}
dllArgs[i] = unsignedLongs;
break;
case "short":
dllArgs[i] = Convert.ToInt16(value);
break;
case "short[]":
arrayValues = HandleArray(value);
short[] shorts = new short[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
shorts[count] = Convert.ToInt16(arrayValues[count]);
}
dllArgs[i] = shorts;
break;
case "ushort":
dllArgs[i] = Convert.ToUInt16(value);
break;
case "ushort[]":
arrayValues = HandleArray(value);
ushort[] unsignedShorts = new ushort[arrayValues.Length];
for (int count = 0; count < arrayValues.Length; count++)
{
unsignedShorts[count] = Convert.ToUInt16(arrayValues[count]);
}
dllArgs[i] = unsignedShorts;
break;
case "string":
dllArgs[i] = value;
break;
case "string[]":
dllArgs[i] = HandleArray(value);
break;
case "null":
dllArgs[i] = null;
break;
default:
throw new Exception("The given type is not supported: \"" + type + "\"");
}
}
//Once all arguments have been parsed without errors, the field in the Config class is set, and the function returns
Config.DllArguments = dllArgs;
}
///
/// A helper function to split an array. This function is created to be able to quickly replace the split value if need be
///
/// The value to split, using a comma as the splitter
/// The split string as a string array
private static string[] HandleArray(string value)
{
return value.Split(',');
}
///
/// A helper function to check if two given strings are equal, regardless of the used casing in either string
///
/// The first string to compare
/// The second string to compare
/// True if the strings are equal (regardless of the used casing), false if not
private static bool IsEqual(string string1, string string2)
{
if (string1.Equals(string2, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
return false;
}
}
}
================================================
FILE: DotDumper/Config.cs
================================================
namespace DotDumper
{
///
/// This class contains the default configuration values. Fields are overwritten with user-provided arguments if present.
///
class Config
{
///
/// The complete path to the sample that is to be executed. The default value is null.
///
public static string SamplePath = null;
///
/// The name of the folder that is to be used to place all artifacts in. This folder always resides within DotDumper.exe's folder. The default value is null.
///
public static string LoggerFolder = null;
///
/// True if deprecated functions should also be hooked (when a hook is present for such a function that is), false if not. The default value is true.
///
public static bool IncludeDeprecatedFunctions = true;
///
/// True if the hooks should be printed in string form during DotDumper's startup, false if not. The default value is true.
///
public static bool LogHooks = true;
///
/// The amount of milliseconds that the timer waits before calling the callback function for the rehook. The default value is 20.
///
public static int RaceConditionDueTime = 20;
///
/// Defines if the entry point (if present) should be overriden. A sample without an entrypoint should still be overridden! The default value is false.
///
public static bool OverrideEntryPoint = false;
///
/// The fully qualified class name, including the namespace(s). The default value is null.
///
public static string DllFullyQualifiedClassName = null;
///
/// The name of the public function in the given fully qualified class name. The default value is null.
///
public static string DllFunctionName = null;
///
/// The provided arguments for the given function (or the entry point). The default value is null.
///
public static object[] DllArguments = null;
///
/// True if calls to Thread.Sleep should be skipped, false if not. The default value is true.
///
public static bool SleepSkip = true;
///
/// True if the logs should be printed to the console, false if not. The default value is true.
///
public static bool PrintLogsToConsole = true;
}
}
================================================
FILE: DotDumper/DotDumper.csproj
================================================
Debug
AnyCPU
{97B3A6FF-A6EC-488A-8206-9820DC1F109B}
Exe
DotDumper
DotDumper
v4.8
512
true
true
AnyCPU
true
full
false
bin\Debug\
DEBUG;TRACE
prompt
4
true
AnyCPU
pdbonly
true
bin\Release\
TRACE
prompt
4
true
true
bin\x64\Debug\
DEBUG;TRACE
full
x64
prompt
MinimumRecommendedRules.ruleset
true
true
bin\x64\Release\
TRACE
true
pdbonly
x64
prompt
MinimumRecommendedRules.ruleset
true
true
DotDumper.ico
..\packages\PeNet.2.9.9\lib\net48\PeNet.dll
..\packages\PeNet.Asn1.2.0.0\lib\net48\PeNet.Asn1.dll
..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll
..\packages\System.Diagnostics.Process.4.3.0\lib\net461\System.Diagnostics.Process.dll
True
True
..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll
..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll
..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll
..\packages\System.Security.Cryptography.Pkcs.6.0.1\lib\net461\System.Security.Cryptography.Pkcs.dll
================================================
FILE: DotDumper/Helpers/ArgumentHelper.cs
================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using DotDumper.HookHandlers;
using DotDumper.Models;
namespace DotDumper.Helpers
{
///
/// This class is used to save and handle arguments from functions
///
class ArgumentHelper
{
///
/// Verifies if a given hash object occurs in the given list of hashes. Existance of the same hash is based on the included SHA-256 hash in the hash object, regardless of the casing. As such, two different objects based on the same file will be seen as duplicates in the same way as the same object will be seen as a duplicate when it is provided as an argument whilst also being in the list.
///
/// The list of hashes, which will be used to check if the given hash is present in this list
/// The hash to check if it is present in the given list
/// True if the list contains the hash, false if not
public static bool ContainsHash(List hashes, Hash hash)
{
//Iterate over all given hashes
foreach (Hash currentHash in hashes)
{
//If the currently iterated hash equals the given hash, regardless of the casing
if (currentHash.Sha256.Equals(hash.Sha256, StringComparison.InvariantCultureIgnoreCase))
{
//Return true
return true;
}
}
//If no matches were found while the iteration completed, return false
return false;
}
///
/// This function saves the value of the given object. The way it is saved depends on the type and the size of the given object. Anything larger than 100 bytes is written to disk. Values are represented in textual form when possible, but some types (i.e. an Assembly object) is always saved to disk, regardless of its size.
///
/// The object to save
/// A tuple with a string (the textual representation of the given input, which can be a reference to a file), and a list of hashes (which can be empty) for all files that were saved to the disk. This list can be empty, but will never be null
public static Tuple> SaveValue(object input)
{
List relatedFileHashes = new List();
string value = "";
if (input is bool
|| input is byte
|| input is sbyte
|| input is char
|| input is decimal
|| input is double
|| input is float
|| input is int
|| input is uint
|| input is long
|| input is ulong
|| input is short
|| input is ushort
|| input is string)
{
if (input.ToString().Length > 100)
{
//Save the file
Tuple result = GenericHookHelper.SaveFile(input.ToString());
if (ContainsHash(relatedFileHashes, result.Item2) == false)
{
relatedFileHashes.Add(result.Item2);
}
value += "";
}
else
{
value += input;
}
}
else if (input is Assembly)
{
Assembly assembly = (Assembly)input;
byte[] rawAssembly = GenericHookHelper.GetAsByteArray(assembly);
//Save the file, which returns the path to the file, where the file name is the SHA-256 hash of the given content
Tuple result = GenericHookHelper.SaveFile(rawAssembly);
if (ContainsHash(relatedFileHashes, result.Item2) == false)
{
relatedFileHashes.Add(result.Item2);
}
if (MissedAssemblyDumper.AssemblyHashes.Contains(result.Item2.Sha256) == false)
{
MissedAssemblyDumper.AssemblyHashes.Add(result.Item2.Sha256);
}
value = "";
}
else if (input is IList)
{
Tuple> result = HandleCollection(input);
value = result.Item1;
foreach (Hash hash in result.Item2)
{
if (ContainsHash(relatedFileHashes, hash) == false)
{
relatedFileHashes.Add(hash);
}
}
}
else if (input == null)
{
value = "null";
}
else
{
value = input.ToString();
}
return Tuple.Create(value, relatedFileHashes);
}
///
/// Creats an argument object, based on the given input and the name of the argument
///
/// The value of the argument, of which the type is derrived
/// The name of the argument
/// An argument object that corresponds with the given arguments
public static Argument Create(object input, string argumentName)
{
Tuple> result = SaveValue(input);
string argType = "null";
string argValue = "null";
if (input != null)
{
argType = input.GetType().FullName;
}
if (result.Item1 != null)
{
argValue = result.Item1;
}
return new Argument(argType, argumentName, argValue, result.Item2);
}
///
/// Creates a list of argument objects based on the given method, along with their values
///
/// The method to fetch the arguments from
/// The values of the parameters (in order of the method's parameters)
/// A list of argument objects based on the two given arguments
public static List Create(MethodBase method, object[] parameterValues)
{
List arguments = new List();
if (method != null && parameterValues != null)
{
ParameterInfo[] parameterInfos = method.GetParameters();
for (int i = 0; i < parameterInfos.Length; i++)
{
object parameter;
if (parameterValues.Length <= i)
{
parameter = null;
}
else
{
parameter = parameterValues[i];
}
string type = "null";
string name = "null";
if (parameterInfos[i] != null)
{
type = parameterInfos[i].ParameterType.FullName;
name = parameterInfos[i].Name;
}
Tuple> result = SaveValue(parameter);
string value = "null";
if (result.Item1 != null)
{
value = result.Item1;
}
Argument argument = new Argument(type, name, value, result.Item2);
arguments.Add(argument);
}
}
return arguments;
}
///
/// Handles a collection, either by converting it into a string, or by saving it to the disk and returning the location as if it were the value, together with a brief explanation).
///
/// The collection to handle
/// The handled collection in the form of a string (as Item1 in the tuple), as well as a list of file hashes of related files (if any, as Item2 in the tuple)
private static Tuple> HandleCollection(object collection)
{
//Initialise the list of related files
List files = new List();
//Initialise the data variable
string data = "";
//Any type of collection with a length of more than 100 indices is saved to disk, as converting and printing large arrays can consume a lot of time
if (((IList)collection).Count > 100)
{
//Save the file, which returns a tuple with the path to the file, and a hash object with the MD-5, SHA-1, and SHA-256 hash of the file, where the file name is the SHA-256 hash of the given content
Tuple result = GenericHookHelper.SaveFile((byte[])collection);
//Add it to the list of files
if (ContainsHash(files, result.Item2) == false)
{
files.Add(result.Item2);
}
//Inform the user that the data is stored in a file
data += "DotDumper::" + result.Item2.Sha256 + " "; //Note: the last two characters are removed once the function returns
}
else //Handle collections that are less than 100 indices in size
{
//If the type is an object collection, it needs to be handled in a specific way
if (collection is object[] || collection is IList)
{
if (collection is IList)
{
collection = ((IList)collection).ToArray();
}
if (((object[])collection).Length == 0)
{
data += "DotDumper::empty "; //Note: the last two characters are removed once the function returns
}
else
{
foreach (object subParameter in (object[])collection)
{
if (subParameter is object[] || subParameter is IList)
{
//Recursive call if the array contains an array
Tuple> result = HandleCollection(subParameter);
//Get the data from the tuple, and append it to this one
data += result.Item1;
//Add all file hashes to the current file list
foreach (Hash hash in result.Item2)
{
if (ContainsHash(files, hash) == false)
{
files.Add(hash);
}
}
}
else if (subParameter == null)
{
data += "null";
}
else
{
string subParameterType = subParameter.GetType().FullName;
data += subParameterType + " " + subParameter;
}
data += ", ";
}
}
}
else
{
foreach (var subParameter in (IList)collection)
{
if (subParameter == null)
{
data += "null";
}
else
{
data += subParameter;
}
data += ", ";
}
}
}
//Remove the last comma and space, after which a curly bracket is appended
data = data.Substring(0, data.Length - 2);
//Return the value as a tuple
return Tuple.Create(data, files);
}
}
}
================================================
FILE: DotDumper/Helpers/AssemblyMapper.cs
================================================
using System;
using System.Collections.Generic;
using System.Reflection;
using DotDumper.HookHandlers;
using DotDumper.Hooks;
using DotDumper.Models;
namespace DotDumper.Helpers
{
///
/// This class is used to map a (line of a) stack trace to an assembly object
///
class AssemblyMapper
{
///
/// Gets the function's signature as a string, formatted as "Full.Class.Path.With.Function(ArgumentType argumentName)". An example is "System.Reflection.Assembly.Load(Byte[] rawAssembly)".
///
/// The hook's full name as a string, i.e. "System.Reflection.Assembly.Load(Byte[] rawAssembly)"
private static string GetMethod(MethodInfo method)
{
string output = method.DeclaringType + "." + method.Name + "(";
foreach (ParameterInfo parameterInfo in method.GetParameters())
{
output += parameterInfo.ParameterType.Name + " " + parameterInfo.Name + ", ";
}
if (method.GetParameters().Length > 0)
{
output = output.Substring(0, output.Length - 2);
}
output += ")";
return output;
}
///
/// Creates the mapping as a dictionary where the keys equal a function signature as a string, and an assembly object as the value. Hooks are set prior to returning from this function!
///
/// The mapping to use when matching a (line of a) stack trace
public static Dictionary CreateMapping()
{
HookManager.UnHookAll();
Dictionary mapping = new Dictionary();
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
//Omit framework related objects, as well as DotDumper itself
if (assembly.GlobalAssemblyCache ||
assembly.GetName().FullName.ToLowerInvariant().Contains("dotdumper"))
{
continue;
}
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
//Gets all declared (omitting inherited functions to avoid duplicates) public, non-public, normal, and static functions
MethodInfo[] methodInfos = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
foreach (MethodInfo methodInfo in methodInfos)
{
if (methodInfo.DeclaringType.Assembly == assembly)
{
string functionSignature = GetMethod(methodInfo);
if (mapping.ContainsKey(functionSignature) == false)
{
mapping.Add(functionSignature, assembly);
}
}
}
}
}
HookManager.HookAll();
return mapping;
}
///
/// Get the assembly object where the referenced function of the stack trace line resides. If it is not found, null is returned!
///
/// The raw stack trace line to match
/// The assembly object if it can be found, null if it cannot be found
public static Assembly ProcessStackTraceLine(string stackTraceLine)
{
//Create the mapping, ensuring it is as up to date as possible
Dictionary mapping = CreateMapping();
//Remove leading and trailing whitespace
stackTraceLine = stackTraceLine.Trim();
//Skip "at " from the line in the beginning
stackTraceLine = stackTraceLine.Substring(3);
//Declare the corresponding Assembly object
Assembly assembly = null;
//Get the Assembly object from the mapping, which returns null if it is not present
mapping.TryGetValue(stackTraceLine, out assembly);
//Return the Assembly object (or null, if it couldn't be found)
return assembly;
}
///
/// Process a list of stack traces to get a list of assembly objects (concatenated as a string in their simple form) that are used, in the same order, excluding duplicates. A duplicate is when two stack trace lines originate from the same assembly object.
///
/// The stack trace lines to use
/// A string representation of the linked assembly objects, excluding duplicates, in the same order as the given list
public static string ProcessStackTraceOld(List stackTraceLines)
{
string output = "";
string lastItem = "";
foreach (string stackTraceLine in stackTraceLines)
{
Assembly assembly = ProcessStackTraceLine(stackTraceLine);
string currentItem;
if (assembly != null)
{
currentItem = assembly.FullName;
}
else
{
currentItem = "[DotDumper or DotNet Framework related assembly]";
}
if (currentItem.Equals(lastItem, StringComparison.InvariantCultureIgnoreCase) == false)
{
output += currentItem + "\n";
lastItem = currentItem;
}
}
return output;
}
///
/// Process a list of stack traces to get a list of assembly objects (concatenated as a string in their simple form) that are used, in the same order, excluding duplicates. A duplicate is when two stack trace lines originate from the same assembly object.
///
/// The stack trace lines to use
/// A string representation of the linked assembly objects, excluding duplicates, in the same order as the given list
public static Tuple> ProcessStackTrace(List stackTraceLines)
{
List assemblyObjects = new List();
Assembly originatingAssembly = null;
foreach (string stackTraceLine in stackTraceLines)
{
Assembly assembly = ProcessStackTraceLine(stackTraceLine);
//Default values, if the assembly is part of the GAC or if it refers to DotDumper
string name = "[DotDumper or DotNet Framework related assembly]";
string hash = "[none]";
//If the response from the function is not null, an object matches
if (assembly != null)
{
//Set the hash and the name for the given assembly object
hash = Hashes.Sha256(GenericHookHelper.GetAsByteArray(assembly));
name = assembly.GetName().Name;
//Set the originating assembly as the first non-GAC non-DotDumper assembly
if (originatingAssembly == null)
{
originatingAssembly = assembly;
}
}
//Check if this object is not the same as the last in the list
if (assemblyObjects.Count == 0)
{
AssemblyObject assemblyObject = new AssemblyObject(hash, name);
assemblyObjects.Add(assemblyObject);
}
else
{
if (assemblyObjects[assemblyObjects.Count - 1].Hash.Equals(hash, StringComparison.InvariantCultureIgnoreCase) == false)
{
AssemblyObject assemblyObject = new AssemblyObject(hash, name);
assemblyObjects.Add(assemblyObject);
}
}
}
return Tuple.Create(originatingAssembly, assemblyObjects);
}
///
/// Checks if a the most recent call of a given list of strack trace lines is coming from a stage of a sample, or from DotDumper, or a GAC module
///
/// The stack trace to use
/// True if the most recent call is coming from a sample stage, false if it is coming from DotDumper, or a GAC module
public static bool IsComingFromSample(List stackTraceLines)
{
/*
* Get the last call from the trace, as this is the origin of the hook location. Use the last call from the trace to check if it matches any key in the mapping
*/
Assembly assembly = ProcessStackTraceLine(stackTraceLines[0]);
if (assembly == null)
{
//Null means it didn't match a binary, since it is part of the framework's core, or DotDumper internally
return false;
}
{
//Not null means it matched with one of the binaries
return true;
}
}
}
}
================================================
FILE: DotDumper/Helpers/Hashes.cs
================================================
using System.Linq;
using System.Security.Cryptography;
using DotDumper.Hooks;
using PeNet;
namespace DotDumper.Helpers
{
///
/// This class contains functions to hash a byte array, after which the hash is returned as a string
///
class Hashes
{
///
/// Calculates the MD-5 hash of the given byte array
///
/// The data to hash
/// The MD-5 hash as a string
public static string Md5(byte[] data)
{
MD5 md5 = MD5.Create();
return CalculateHash(md5, data);
}
///
/// Calculates the SHA-1 hash of the given byte array
///
/// The data to hash
/// The SHA-1 hash as a string
public static string Sha1(byte[] data)
{
SHA1 sha1 = SHA1.Create();
return CalculateHash(sha1, data);
}
///
/// Calculates the SHA-256 hash of the given byte array
///
/// The data to hash
/// The SHA-256 hash as a string
public static string Sha256(byte[] data)
{
SHA256 sha256 = SHA256.Create();
return CalculateHash(sha256, data);
}
///
/// Calculates the SHA-384 hash of the given byte array
///
/// The data to hash
/// The SHA-384 hash as a string
public static string Sha384(byte[] data)
{
SHA384 sha384 = SHA384.Create();
return CalculateHash(sha384, data);
}
///
/// Calculates the SHA-512 hash of the given byte array
///
/// The data to hash
/// The SHA-512 hash as a string
public static string Sha512(byte[] data)
{
SHA512 sha512 = SHA512.Create();
return CalculateHash(sha512, data);
}
///
/// Calculates the TypeRef hash of the given byte array. Hooks are set prior to returning from this function!
///
/// The data to hash
/// The TypeRef hash as a string, or an empty string in case an error occurs (i.e. the input is not a valid PE file which targets the DotNet Framework)
public static string TypeRef(byte[] data)
{
HookManager.UnHookAll();
if (PeFile.TryParse(data, out PeFile peFile) == false)
{
return "";
}
if (peFile.IsDotNet == false)
{
return "";
}
string typeRefHash = peFile.TypeRefHash;
if (typeRefHash == null)
{
typeRefHash = "";
}
HookManager.HookAll();
return typeRefHash;
}
///
/// Calculates the import hash of the given byte array. Hooks are set prior to returning from this function!
///
/// The data to hash
/// The import hash as a string, or an empty string in case an error occurs (i.e. the input is not a valid PE file)
public static string ImportHash(byte[] data)
{
HookManager.UnHookAll();
if (PeFile.TryParse(data, out PeFile peFile) == false)
{
return "";
}
string importHash = peFile.ImpHash;
if (importHash == null)
{
importHash = "";
}
HookManager.HookAll();
return importHash;
}
///
/// Calculates the authenticode hash (SHA-256 based) of the given byte array. Hooks are set prior to returning from this function!
///
/// The data to hash
/// The authenticode hash (SHA-256 based) as a string, or an empty string in case an error occurs (i.e. the input is not a valid PE)
public static string AuthenticodeSha256(byte[] data)
{
return Authenticode(data, SHA256.Create());
}
///
/// Calculates the authenticode hash (based on the provided hash algorithm) of the given byte array. Hooks are set prior to returning from this function!
///
/// The data to hash
/// The hashing algorithm to use
/// The authenticode hash (based on the provided hash algorithm), or an empty string in case an error occurs (i.e. the input is not a valid PE file)
private static string Authenticode(byte[] data, HashAlgorithm hashAlgorithm)
{
HookManager.UnHookAll();
if (PeFile.TryParse(data, out PeFile peFile) == false)
{
return "";
}
string authenticode = peFile.Authenticode.ComputeAuthenticodeHashFromPeFile(hashAlgorithm).ToList().ToHexString();
if (authenticode == null || authenticode.Length < 2)
{
authenticode = authenticode.Substring(2);
}
else
{
authenticode = "";
}
HookManager.HookAll();
return authenticode;
}
///
/// This function calculates the hash of the given data, using the given hashing algorithm
///
/// The hashing algorithm to use
/// The data to hash
/// The hash of the data as a string, based on the given hash algorithm
private static string CalculateHash(HashAlgorithm hashAlgorithm, byte[] data)
{
string hash = "";
if (data == null || hashAlgorithm == null)
{
return hash;
}
byte[] rawHash = hashAlgorithm.ComputeHash(data);
for (int i = 0; i < rawHash.Length; i++)
{
hash += rawHash[i].ToString("x2");
}
return hash;
}
}
}
================================================
FILE: DotDumper/Helpers/LogEntryHelper.cs
================================================
using System;
using System.Collections.Generic;
using System.Reflection;
using DotDumper.HookHandlers;
using DotDumper.Hooks;
using DotDumper.Models;
namespace DotDumper.Helpers
{
///
/// This class is used to create DotDumper.Model.LogEntry objects based on as few parameters as possible
///
class LogEntryHelper
{
///
/// Creates a log entry object based on the given exception, with the given stack trace offset from the caller's position
///
/// The amount of layers away from the original call flow, based on the caller's position
/// The exception to base the log entry object on
/// A log entry based on the given values
public static LogEntry Create(int stackTraceOffset, Exception ex)
{
stackTraceOffset++;
LogEntry entry = Create(stackTraceOffset, ex.TargetSite, null, ex);
return entry;
}
///
/// Creates a log entry for an unmanaged function, along with its argument and return values
///
/// The unmanaged methodinfo object, corresponding to the original function that was hooked
/// An array of objects with the values of the function's arguments
/// The value of the function's return value
/// A log entry based on the given values
public static LogEntry Create(UnmanagedMethodInfo unmanagedMethodInfo, object[] parameterValues, object returnValue)
{
MethodInfo methodInfo = HookManager.GetMethodInfo(typeof(InteropFunctions), unmanagedMethodInfo.MethodName, unmanagedMethodInfo.ParameterTypes);
//A negative value for the stack trace, as the wrong value is obtained since this call is invoked based on async information that is shared via the unmanaged function hooks that share via a named pipe
return Create(-1, methodInfo, parameterValues, returnValue);
}
///
/// Creates a log entry based on the given stack trace offset (from the caller's position), method, the method values, and the return value of said method
///
/// The amount of layers away from the original call flow, based on the caller's position. A value less than 0 is used to indicate that the stack trace is to be ignored (done for unmanaged function hooks, as the function is obtained from a different location than the actual call comes from)
/// The method that is of importance to log
/// The values of said method's parameters
/// The return value of the function (use null if it's a void)
/// A log entry based on the given values
public static LogEntry Create(int stackTraceOffset, MethodBase method, object[] parameterValues, object returnValue)
{
//Gets a list of arguments based on the given function
List functionArguments = ArgumentHelper.Create(method, parameterValues);
//Initialises a list of related files
List relatedFileHashes = new List();
//Iterate over all extracted arguments
foreach (Argument argument in functionArguments)
{
//Iterate over all hashes
foreach (Hash hash in argument.RelatedFileHashes)
{
//If there is no such hash in the list, add it. Otherwise, ignore it
if (ArgumentHelper.ContainsHash(relatedFileHashes, hash) == false)
{
relatedFileHashes.Add(hash);
}
}
}
//Declare and initialise the stack trace variable
List stackTrace = new List();
/*
* If the value is negative, its a hook for an unmanaged function and the only obtainable stack trace is useless. If it is zero or higher, its a managed hook
*/
if (stackTraceOffset >= 0)
{
//Increment the stack trace offset, since this is another function deep into the trace
stackTraceOffset++;
//Get the stack trace
stackTrace = GenericHookHelper.GetStackTraceRaw(stackTraceOffset);
}
//Get the assembly and assembly object information based on the stack trace
Tuple> result = AssemblyMapper.ProcessStackTrace(stackTrace);
//Declare the originating assembly variable
Assembly originatingAssembly = null;
/*
* If the first tuple item (being the Assembly object) is null, the call is coming from either the DotNet Framework, or from DotDumper's code base.
* If the value is not-null, it is assigned.
*/
if (result.Item1 == null)
{
HookManager.UnHookAll();
originatingAssembly = Assembly.GetAssembly(typeof(Program));
HookManager.HookAll();
}
else
{
originatingAssembly = result.Item1;
}
//Get the name from the originating assembly
string originatingAssemblyName = originatingAssembly.GetName().Name;
//Get the raw assembly as an unboxed byte array
byte[] rawAssembly = GenericHookHelper.GetAsByteArray(originatingAssembly);
//Get the hashes based on the given raw assembly byte array
string md5 = Hashes.Md5(rawAssembly);
string sha1 = Hashes.Sha1(rawAssembly);
string sha256 = Hashes.Sha256(rawAssembly);
string sha384 = Hashes.Sha384(rawAssembly);
string sha512 = Hashes.Sha512(rawAssembly);
string typeRef = Hashes.TypeRef(rawAssembly);
string importHash = Hashes.ImportHash(rawAssembly);
string authenticodeSha256 = Hashes.AuthenticodeSha256(rawAssembly);
//Create a hash object to store the values in
Hash originatingAssemblyHash = new Hash(md5, sha1, sha256, sha384, sha512, typeRef, importHash, authenticodeSha256);
//Get the originating assembly version
string originatingAssemblyVersion = originatingAssembly.GetName().Version.ToString();
//Get the originating assembly resource names
List originatingAssemblyResourceNames = new List(originatingAssembly.GetManifestResourceNames());
//Get the call order, which is the second item from the tuple
List assemblyCallOrder = result.Item2;
//Declare and assign a value to the parent assembly hash string
string parentAssemblyHash = "[none]";
//Iterate over all assembly objects in the call order
foreach (AssemblyObject assemblyObject in assemblyCallOrder)
{
//If the hash is not equal to none nor to the current originating hash, it is set as the parent
if (assemblyObject.Hash.Equals("[none]", StringComparison.InvariantCultureIgnoreCase) == false
&& assemblyObject.Hash.Equals(originatingAssemblyHash.Sha256, StringComparison.InvariantCultureIgnoreCase) == false)
{
parentAssemblyHash = assemblyObject.Hash;
//There is no need to continue the iteration, since only the first parent is stored (and the rest is visible in the call order)
break;
}
}
//Get the function name
string functionName = Serialise.Method(method);
//The return value is stored in an argument object, with a hardcoded name
Argument returnValueArg = ArgumentHelper.Create(returnValue, "ReturnValue");
//The return value can also be related to a file
foreach (Hash hash in returnValueArg.RelatedFileHashes)
{
//Iterate over all the hashes, and add the ones that aren't in the list yet
if (ArgumentHelper.ContainsHash(relatedFileHashes, hash) == false)
{
relatedFileHashes.Add(hash);
}
}
//Return a new LogEntry object based on all the gathered information
return new LogEntry(originatingAssemblyName, originatingAssemblyHash, originatingAssemblyVersion, originatingAssemblyResourceNames, parentAssemblyHash, relatedFileHashes, functionName, functionArguments, returnValueArg, stackTrace, assemblyCallOrder);
}
}
}
================================================
FILE: DotDumper/Helpers/MissedAssemblyDumper.cs
================================================
using System;
using System.Collections.Generic;
using System.Reflection;
using DotDumper.HookHandlers;
using DotDumper.Hooks;
using DotDumper.Models;
namespace DotDumper.Helpers
{
///
/// This class is used to dump missed assembly objects from memory to the disk
///
class MissedAssemblyDumper
{
///
/// A list which contains the (partial) names of the assemblies to exclude during periodic dumping
///
public static List ExcludedAssemblies { get; set; }
///
/// SHA-256 hashes of raw Assembly objects (their byte[] representation) that have been written to the disk during the execution of this run of DotDumper
///
public static List AssemblyHashes { get; set; }
///
/// The static constructor of the class ensures the class scoped list is always initialised prior to its usage
///
static MissedAssemblyDumper()
{
//Initialise the lists
AssemblyHashes = new List();
ExcludedAssemblies = new List();
//Populate the list
ExcludedAssemblies.Add("dotdumper");
ExcludedAssemblies.Add("penet");
ExcludedAssemblies.Add("system.memory");
ExcludedAssemblies.Add("system.runtime.compilerservices.unsafe");
ExcludedAssemblies.Add("system.numerics.vectors");
ExcludedAssemblies.Add("microsoft.generatedcode");
}
///
/// Dumps all loaded assemblies that haven't been dumped before and are not part of the Global Assembly Cache (GAC). This function removes all hooks, dumps the missing data, after which all hooks are set again.
///
public static void Dump()
{
//Temporarily remove all hooks
HookManager.UnHookAll();
//If the original assembly is not null, it can be added to the list of hashes, this avoids the sample to show up as a "missed" assembly object
if (GenericHookHelper.OriginalAssembly != null)
{
//Get the raw bytes
byte[] sample = GenericHookHelper.GetAsByteArray(GenericHookHelper.OriginalAssembly);
//Unhook all hooks, as these are set after the previous call
HookManager.UnHookAll();
//Get the SHA-256 hash
string sampleSha256 = Hashes.Sha256(sample);
//Check if the list does not contain this item
if (AssemblyHashes.Contains(sampleSha256) == false)
{
//Add the hash to the list
AssemblyHashes.Add(sampleSha256);
}
}
//Declare and initialise the list for the saved assemblies
List savedAssemblies = new List();
//Get all the assemblies in the current domain
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
//Iterate over all assemblies within the current domain
foreach (Assembly assembly in assemblies)
{
//Omit DotDumper itself, as well as used (DotNet Framework related) libraries
if (ExcludeAssembly(assembly))
{
continue;
}
try
{
//Get the raw bytes of the assembly
byte[] rawAssembly = GenericHookHelper.GetAsByteArray(assembly);
//Unhook all hooks, as these are set via the previous call
HookManager.UnHookAll();
//Get the SHA-256 hash of the given assembly object's bytes
string sha256 = Hashes.Sha256(rawAssembly);
//Only save assemblies that haven't been saved before during this run
if (AssemblyHashes.Contains(sha256) == false)
{
//Save the file, and store the SHA-256 hash in the list of processed assembly objects, and store the Hash object in the saved assemblies list
Tuple result = GenericHookHelper.SaveFile(rawAssembly);
HookManager.UnHookAll();
savedAssemblies.Add(result.Item2);
AssemblyHashes.Add(result.Item2.Sha256);
}
}
catch (Exception)
{
//Ignore errors when trying to save an assembly object in its raw form. In some cases, DotNet Framework related assembly objects cause errors when attempting to save them, i.e. when they are dynamically generated
}
}
//If at least 1 assembly has been saved (and was thus missed), this should be logged
if (savedAssemblies.Count > 0)
{
//Create a nearly empty log entry object with the relevant information
LogEntry entry = new LogEntry(null, null, null, null, null, savedAssemblies, "periodic assembly dumping", null, null, null, null);
//Log the entry to all relevant logs
GenericHookHelper._Logger.Log(entry, false, false);
}
//Set all hooks prior to returning to the caller
HookManager.HookAll();
}
///
/// Checks if the given assembly is to be excluded or not. It will be if either of the following is true: the given assembly object is null, the given assembly is part of the global assembly cache, or if the fullname matches (in full or partially) the name of any of the names in the exclusion list.
///
/// The assembly to check for
/// True if the assembly is to be excluded, false if not
private static bool ExcludeAssembly(Assembly assembly)
{
//If the given assembly object is null, it is to be excluded
if (assembly == null)
{
return true;
}
//Excludes the assembly if it's part of the global assembly cache
if (assembly.GlobalAssemblyCache)
{
return true;
}
//Get the assembly name in lower case
string assemblyName = assembly.GetName().FullName.ToLowerInvariant();
//Iterate over all excluded assembly names
foreach (string excludedName in ExcludedAssemblies)
{
//If the current assembly name (in lower case) contains the excluded name (also in lower case), it is to be skipped
if (assemblyName.Contains(excludedName.ToLowerInvariant()))
{
return true;
}
}
//The assembly is not to be skipped if its not meeting any of the skip criteria
return false;
}
}
}
================================================
FILE: DotDumper/Helpers/RaceConditionHandler.cs
================================================
using System.Threading;
using DotDumper.Hooks;
using System;
using System.Collections.Generic;
namespace DotDumper.Helpers
{
///
/// This class handles the race condition that allows to rehook invoke related functions during their execution
///
class RaceConditionHandler
{
///
/// The dictionary that contains all timers (as multiple can be created via multiple threads), where a GUID is the key, and the timer object is the value
///
private static readonly Dictionary timers = new Dictionary();
///
/// This function unhooks the given hook based on its name, after which it waits 20 milliseconds. It then calls the timer callback function, which rehooks the given hook. The timer callback is only called once, after which the Timer object is destroyed.
///
/// The function to unhook and rehook
public static void StartTimer(string hookName)
{
//Create a string with the GUID and the hook name, split by a pipe
string data = hookName + "|" + Guid.NewGuid().ToString();
//Unhook the hook
HookManager.UnHookByHookName(hookName);
//Create a timer object which calls the callback function once, after a 20 ms delay, using the data string as an argument
Timer timer = new Timer(TimerCallback, data, Config.RaceConditionDueTime, Timeout.Infinite); //Timeout.Infinite (aka -1) means no repeated calls, see https://docs.microsoft.com/en-us/dotnet/api/system.threading.timeout.infinite
//Add the timer to the dictionary
timers.Add(data, timer);
}
///
/// The callback function for the timer that rehooks the unhooked function
///
/// The function argument has to be an argument, but it is actually a string array in this case. The format should be "my-guid|hookName"
private static void TimerCallback(object o)
{
//Split the string into the GUID and function name respectively
string[] array = ((string)o).Split('|');
//Set the hook again
HookManager.HookByHookName(array[0]);
//Get the GUID
string guid = array[1];
//Remove the GUID from the dictionary
timers.Remove(guid);
}
}
}
================================================
FILE: DotDumper/Helpers/Serialise.cs
================================================
using System.IO;
using System.Reflection;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using DotDumper.Hooks;
namespace DotDumper.Helpers
{
///
/// This class is used to convert a given object to JSON using the built-in JavaScriptSerializer object
///
class Serialise
{
///
/// Converts the given object into its JSON equivalent
///
/// The object to obtain the JSON equivalent from
/// The JSON equivalent of the given object
public static string ToJson(object input)
{
//If the input is null, return null in string format
if (input == null)
{
return "null";
}
//Remove all hooks
HookManager.UnHookAll();
//Initialise a serialiser object
JavaScriptSerializer serialiser = new JavaScriptSerializer();
//Serialise the input
string result = serialiser.Serialize(input);
//Restore all hooks
HookManager.HookAll();
//Return the result
return result;
}
///
/// Converts the given object into its XML equivalent
///
/// The object to obtain the XML equivalent from
/// The XML equivalent of the given object
public static string ToXml(object input)
{
//If the input is null, return null in string format
if (input == null)
{
return "null";
}
//Remove all hooks
HookManager.UnHookAll();
//Initialise the serialiser objects
StringWriter stringWriter = new StringWriter();
XmlSerializer serialiser = new XmlSerializer(input.GetType());
//Serialise the input
serialiser.Serialize(stringWriter, input);
string result = stringWriter.ToString();
//Restore all hooks
HookManager.HookAll();
//Return the result
return result;
}
///
/// Gets the given method as a string, formatted as "Full.ReturnType Full.Class.Path.With.Function(Complete.Argument.Type argumentName)". An example is "System.Reflection.Assembly System.Reflection.Assembly.Load(System.Byte[] rawAssembly)".
///
/// The method's full name as a string, i.e. "System.Reflection.Assembly System.Reflection.Assembly.Load(System.Byte[] rawAssembly)"
public static string Method(MethodBase method)
{
//Declare and initialise the output variable
string output = "";
//If the input is null, the output is set to null in string form, which is then returned
if (method == null)
{
return "null";
}
//If the method is a MethodInfo instance (rather than the MethodBase object that is expected in the function's argument), which is possible as the MethodInfo object inherits the MethodBase class, the return type is accessible, and is subsequently used in the output
if (method is MethodInfo)
{
output += ((MethodInfo)method).ReturnType.FullName + " ";
}
//Get the declaring type, the functino name, and open the arguments bracket
output += method.DeclaringType + "." + method.Name + "(";
//Iterate over all parameters
foreach (ParameterInfo parameterInfo in method.GetParameters())
{
//Get the parameter type and name, and include a comma for the potential following argument
output += parameterInfo.ParameterType + " " + parameterInfo.Name + ", ";
}
//If there is at least 1 argument, and all argumguments have been iterated over
if (method.GetParameters().Length > 0)
{
//The last two characters are to be removed, which equal the comma and a space, as there is no following argument
output = output.Substring(0, output.Length - 2);
}
//The closing bracket is then added
output += ")";
//And finally the output is returned
return output;
}
}
}
================================================
FILE: DotDumper/Helpers/StagnationHandler.cs
================================================
using System;
using DotDumper.HookHandlers;
using DotDumper.Hooks;
using DotDumper.Models;
namespace DotDumper.Helpers
{
///
/// A class which contains the stagnation timer's callback function. This function is called with an interval that is defined upon the timer's creation (see program.cs in the project's root).
/// If a third interval of the given time span passes without an increase logged messages, the callback function ensures that DotDumper is shut down. This is done to escape situations where
/// process injection took place (often with native functions) and DotDumper erroneously waits for the function to return (even though it wont until the malware stops its own execution).
/// When using a sandbox, this cuts down the runtime to the point where it only runs if DotDumper is actually active, thus saving time.
///
class StagnationHandler
{
///
/// The amount of logs that were logged by the logger
///
private static int _Count = 0;
///
/// The stage of the handler, where 0 is the start, and 2 is the moment to trigger the termination clause. The stage is increased with 1 every time the callback function is called and the amount of logs (as saved in count) is equal to the amount of logs the logger saved.
///
private static int _Stage = 0;
///
/// The stagnation handler timer's callback function, which is called at every interval of the timer
///
/// Optional parameters, as specified by the interface, but not used by this instance of the timer
public static void TimerCallback(object o)
{
//If the logging count and the current count are equal, raise the stage variable. The condition where the logging is empty is not a real case, as the reflective loading of the sample already creates a single log.
if (GenericHookHelper._Logger.Count == _Count)
{
_Stage++;
}
else //If the values are not equal, the local count variable is made equal to the amount of logs that were written, and the stage is set back to 0
{
_Count = GenericHookHelper._Logger.Count;
_Stage = 0;
}
//If the stage is equal to, or more than, two, it means that the timer has called this callback twice without the creation of a single log
if (_Stage >= 2)
{
//If the DEBUG variable set to false, it means it is running in a normal environment
if (Program.DEBUG == false)
{
//Remove all hooks
HookManager.UnHookAll();
//Create a new exception with a message
Exception ex = new Exception("DotDumper stagnated, and is shutting down!");
//Create a new log entry with the exception
LogEntry entry = LogEntryHelper.Create(0, ex);
//Log the entry
GenericHookHelper._Logger.Log(entry, true, true);
//Remove all hooks
HookManager.UnHookAll();
//Set the time a year ahead, forcing the sandbox to time out
SetTime();
//Exit normally, which is called directly as all hooks are removed
Environment.Exit(0);
}
}
}
///
/// Sets the system date and time to a year in the future, forcing the sandbox to time out of its runtime
///
public static void SetTime()
{
//Declares and initialises the SystemTime structure with a future time
InteropFunctions.SystemTime updatedTime = new InteropFunctions.SystemTime
{
Year = (ushort)(2200),
Month = (ushort)12,
Day = (ushort)30,
Hour = (ushort)12,
Minute = (ushort)00,
Second = (ushort)0
};
//Set the time to next year, forcing the sandbox to time out
InteropFunctions.SetSystemTime(ref updatedTime);
}
}
}
================================================
FILE: DotDumper/HookHandlers/Activator/ActivatorHooks.cs
================================================
using System;
using System.Configuration.Assemblies;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Remoting;
using System.Security.Policy;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class ActivatorHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateComInstanceFromHookStringStringByteArrayAssemblyHashAlgorithm(string assemblyName, string typeName, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateComInstanceFromHookStringStringByteArrayAssemblyHashAlgorithm");
//Call the original function
result = Activator.CreateComInstanceFrom(assemblyName, typeName, hashValue, hashAlgorithm);
HookManager.HookByHookName("CreateComInstanceFromHookStringStringByteArrayAssemblyHashAlgorithm");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateComInstanceFromStringStringByteArrayAssemblyHashAlgorithm(), new object[] { assemblyName, typeName, hashValue, hashAlgorithm }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateComInstanceFromHookStringString(string assemblyName, string typeName)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Within the DotNet framework, another CreateComInstance function is used, which is also hooked. To avoid duplicate entries in the logging, both are unhooked and rehooked
HookManager.UnHookByHookName("CreateComInstanceFromHookStringString");
HookManager.UnHookByHookName("CreateComInstanceFromHookStringStringByteArrayAssemblyHashAlgorithm");
//Call the original function
result = Activator.CreateComInstanceFrom(assemblyName, typeName);
HookManager.HookByHookName("CreateComInstanceFromHookStringString");
HookManager.HookByHookName("CreateComInstanceFromHookStringStringByteArrayAssemblyHashAlgorithm");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateComInstanceFromStringString(), new object[] { assemblyName, typeName }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static object CreateInstanceHookType(Type type)
{
//Declare the local variable to store the object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Double unhook due to DotNet internal wrappers, thereby avoiding double logging
HookManager.UnHookByHookName("CreateInstanceHookType");
HookManager.UnHookByHookName("CreateInstanceHookTypeBool");
//Call the original function
result = Activator.CreateInstance(type);
HookManager.HookByHookName("CreateInstanceHookType");
HookManager.HookByHookName("CreateInstanceHookTypeBool");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceTypeBool(), new object[] { type }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static object CreateInstanceHookTypeBool(Type type, bool nonPublic)
{
//Declare the local variable to store the object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookTypeBool");
//Call the original function
result = Activator.CreateInstance(type, nonPublic);
HookManager.HookByHookName("CreateInstanceHookTypeBool");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceTypeBool(), new object[] { type, nonPublic }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceHookActivationContext(ActivationContext activationContext)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookActivationContext");
//Call the original function
result = Activator.CreateInstance(activationContext);
HookManager.HookByHookName("CreateInstanceHookActivationContext");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceActivationContext(), new object[] { activationContext }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static object CreateInstanceHookTypeObjectArray(Type type, params object[] args)
{
//Declare the local variable to store the object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Double unhook due to internal calling of the function to an overload
HookManager.UnHookByHookName("CreateInstanceHookTypeObjectArray");
HookManager.UnHookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstance(type, args);
HookManager.HookByHookName("CreateInstanceHookTypeObjectArray");
HookManager.HookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceActivationContext(), new object[] { type, args }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static object CreateInstanceHookStringString(string assemblyName, string typeName)
{
//Declare the local variable to store the object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstance(assemblyName, typeName);
HookManager.HookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceStringString(), new object[] { assemblyName, typeName }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static object CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfo(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture)
{
//Declare the local variable to store the object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Double unhook due to an internal wrapper within the DotNet framework
HookManager.UnHookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfo");
HookManager.UnHookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstance(type, bindingAttr, binder, args, culture);
HookManager.HookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfo");
HookManager.HookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceActivationContext(), new object[] { type, bindingAttr, binder, args, culture }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static object CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
//Declare the local variable to store the object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes);
HookManager.HookByHookName("CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceActivationContext(), new object[] { type, bindingAttr, binder, args, culture, activationAttributes }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes);
HookManager.HookByHookName("CreateInstanceHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(), new object[] { assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceHookActivationContextStringArray(ActivationContext activationContext, string[] activationCustomData)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookActivationContextStringArray");
//Call the original function
result = Activator.CreateInstance(activationContext, activationCustomData);
HookManager.HookByHookName("CreateInstanceHookActivationContextStringArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceActivationContextStringArray(), new object[] { activationContext, activationCustomData }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceHookStringStringObjectArray(string assemblyName, string typeName, object[] activationAttributes)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookStringStringObjectArray");
//Call the original function
result = Activator.CreateInstance(assemblyName, typeName, activationAttributes);
HookManager.HookByHookName("CreateInstanceHookStringStringObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceStringStringObjectArray(), new object[] { assemblyName, typeName, activationAttributes }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceHookAppDomainStringString(AppDomain domain, string assemblyName, string typeName)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookAppDomainStringString");
//Call the original function
result = Activator.CreateInstance(domain, assemblyName, typeName);
HookManager.HookByHookName("CreateInstanceHookAppDomainStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceAppDomainStringString(), new object[] { domain, assemblyName, typeName }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityInfo)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence");
//Call the original function
result = Activator.CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityInfo);
HookManager.HookByHookName("CreateInstanceHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), new object[] { assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityInfo }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(AppDomain domain, string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstance(domain, assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes);
HookManager.HookByHookName("CreateInstanceHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(), new object[] { domain, assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(AppDomain domain, string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence");
//Call the original function
result = Activator.CreateInstance(domain, assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
HookManager.HookByHookName("CreateInstanceHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), new object[] { domain, assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceFromHookAppDomainStringString(AppDomain domain, string assemblyFile, string typeName)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceFromHookAppDomainStringString");
//Call the original function
result = Activator.CreateInstanceFrom(domain, assemblyFile, typeName);
HookManager.HookByHookName("CreateInstanceFromHookAppDomainStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceFromAppDomainStringString(), new object[] { domain, assemblyFile, typeName }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceFromHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityInfo)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceFromHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence");
//Call the original function
result = Activator.CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityInfo);
HookManager.HookByHookName("CreateInstanceFromHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceFromStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), new object[] { assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityInfo }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceFromHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(AppDomain domain, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceFromHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstanceFrom(domain, assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes);
HookManager.HookByHookName("CreateInstanceFromHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceFromAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(), new object[] { domain, assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceFromHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(AppDomain domain, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceFromHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence");
//Call the original function
result = Activator.CreateInstanceFrom(domain, assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
HookManager.HookByHookName("CreateInstanceFromHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceFromAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), new object[] { domain, assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceFromHookStringString(string assemblyFile, string typeName)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Multi unhooking due to DotNet wrapper calls
HookManager.UnHookByHookName("CreateInstanceFromHookStringString");
HookManager.UnHookByHookName("CreateInstanceFromHookStringStringObjectArray");
HookManager.UnHookByHookName("CreateInstanceFromHookStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstanceFrom(assemblyFile, typeName);
HookManager.HookByHookName("CreateInstanceFromHookStringString");
HookManager.HookByHookName("CreateInstanceFromHookStringStringObjectArray");
HookManager.HookByHookName("CreateInstanceFromHookStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceFromStringString(), new object[] { assemblyFile, typeName }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceFromHookStringStringObjectArray(string assemblyFile, string typeName, object[] activationAttributes)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookByHookName("CreateInstanceFromHookStringStringObjectArray");
HookManager.UnHookByHookName("CreateInstanceFromHookStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstanceFrom(assemblyFile, typeName, activationAttributes);
HookManager.HookByHookName("CreateInstanceFromHookStringStringObjectArray");
HookManager.HookByHookName("CreateInstanceFromHookStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceFromAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), new object[] { assemblyFile, typeName, activationAttributes }, result);
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static ObjectHandle CreateInstanceFromHookStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
{
//Declare the local variable to store the object in
ObjectHandle result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Multi unhook due to internal wrappers in the DotNet framework
HookManager.UnHookByHookName("CreateInstanceFromHookStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Call the original function
result = Activator.CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes);
HookManager.HookByHookName("CreateInstanceFromHookStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ActivatorCreateInstanceFromAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), new object[] { assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes }, result);
}
//Return the process object to the caller
return result;
}
}
}
================================================
FILE: DotDumper/HookHandlers/Assembly/AssemblyHooks.cs
================================================
using System.Configuration.Assemblies;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Policy;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class AssemblyHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly GetEntryAssemblyHook()
{
return GenericHookHelper.OriginalAssembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly GetExecutingAssemblyHook()
{
return GenericHookHelper.OriginalAssembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadHookByteArray(byte[] rawAssembly)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadHookByteArray");
//Call the original function
assembly = Assembly.Load(rawAssembly);
//Restore the hook
HookManager.HookByHookName("LoadHookByteArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadByteArray(), new object[] { rawAssembly }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadHookString(string assemblyString)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadHookString");
//Call the original function
assembly = Assembly.Load(assemblyString);
//Restore the hook
HookManager.HookByHookName("LoadHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadString(), new object[] { assemblyString }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadHookStringEvidence(string assemblyString, Evidence assemblySecurity)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadHookStringEvidence");
//Call the original function
assembly = Assembly.Load(assemblyString, assemblySecurity);
//Restore the hook
HookManager.HookByHookName("LoadHookStringEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadStringEvidence(), new object[] { assemblyString, assemblySecurity }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadHookByteArrayByteArrayEvidence(byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadHookByteArrayByteArrayEvidence");
//Call the original function
assembly = Assembly.Load(rawAssembly, rawSymbolStore, securityEvidence);
//Restore the hook
HookManager.HookByHookName("LoadHookByteArrayByteArrayEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadByteArrayByteArrayEvidence(), new object[] { rawAssembly, rawSymbolStore, securityEvidence }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadHookAssemblyName(AssemblyName assemblyRef)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadHookAssemblyName");
//Call the original function
assembly = Assembly.Load(assemblyRef);
//Restore the hook
HookManager.HookByHookName("LoadHookAssemblyName");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadAssemblyName(), new object[] { assemblyRef }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadHookAssemblyNameEvidence(AssemblyName assemblyRef, Evidence assemblySecurity)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadHookAssemblyNameEvidence");
//Call the original function
assembly = Assembly.Load(assemblyRef, assemblySecurity);
//Restore the hook
HookManager.HookByHookName("LoadHookAssemblyNameEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadAssemblyNameEvidence(), new object[] { assemblyRef, assemblySecurity }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadHookByteArrayByteArraySecurityContextSource(byte[] rawAssembly, byte[] rawSymbolStore, SecurityContextSource securityContextSource)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadHookByteArrayByteArraySecurityContextSource");
//Call the original function
assembly = Assembly.Load(rawAssembly, rawSymbolStore, securityContextSource);
//Restore the hook
HookManager.HookByHookName("LoadHookByteArrayByteArraySecurityContextSource");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadByteArrayByteArraySecurityContextSource(), new object[] { rawAssembly, rawSymbolStore, securityContextSource }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadHookByteArrayByteArray(byte[] rawAssembly, byte[] rawSymbolStore)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadHookByteArrayByteArray");
//Call the original function
assembly = Assembly.Load(rawAssembly, rawSymbolStore);
//Restore the hook
HookManager.HookByHookName("LoadHookByteArrayByteArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadByteArrayByteArray(), new object[] { rawAssembly, rawSymbolStore }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadFileHookString(string path)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadFileHookString");
//Call the original function
assembly = Assembly.LoadFile(path);
//Restore the hook
HookManager.HookByHookName("LoadFileHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadFileString(), new object[] { path }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadFileHookStringEvidence(string path, Evidence securityEvidence)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadFileHookStringEvidence");
//Call the original function
assembly = Assembly.LoadFile(path, securityEvidence);
//Restore the hook
HookManager.HookByHookName("LoadFileHookStringEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadFileStringEvidence(), new object[] { path, securityEvidence }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadFromHookString(string assemblyFile)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadFromHookString");
//Call the original function
assembly = Assembly.LoadFrom(assemblyFile);
//Restore the hook
HookManager.HookByHookName("LoadFromHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadFromString(), new object[] { assemblyFile }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadFromHookStringEvidence(string assemblyFile, Evidence securityEvidence)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadFromHookStringEvidence");
//Call the original function
assembly = Assembly.LoadFrom(assemblyFile, securityEvidence);
//Restore the hook
HookManager.HookByHookName("LoadFromHookStringEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadFromStringEvidence(), new object[] { assemblyFile, securityEvidence }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadFromHookStringEvidenceByteArrayAssemblyHashAlgorithm(string assemblyFile, Evidence securityEvidence, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadFromHookStringEvidenceByteArrayAssemblyHashAlgorithm");
//Call the original function
assembly = Assembly.LoadFrom(assemblyFile, securityEvidence, hashValue, hashAlgorithm);
//Restore the hook
HookManager.HookByHookName("LoadFromHookStringEvidenceByteArrayAssemblyHashAlgorithm");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadFromStringEvidenceByteArrayAssemblyHashAlgorithm(), new object[] { assemblyFile, securityEvidence, hashValue, hashAlgorithm }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadFromHookStringByteArrayAssemblyHashAlgorithm(string assemblyFile, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadFromHookStringByteArrayAssemblyHashAlgorithm");
//Call the original function
assembly = Assembly.LoadFrom(assemblyFile, hashValue, hashAlgorithm);
//Restore the hook
HookManager.HookByHookName("LoadFromHookStringByteArrayAssemblyHashAlgorithm");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadFromStringByteArrayAssemblyHashAlgorithm(), new object[] { assemblyFile, hashValue, hashAlgorithm }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadWithPartialNameHookStringEvidence(string partialName, Evidence securityEvidence)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadWithPartialNameHookStringEvidence");
//Call the original function
assembly = Assembly.LoadWithPartialName(partialName, securityEvidence);
//Restore the hook
HookManager.HookByHookName("LoadWithPartialNameHookStringEvidence");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadWithPartialNameStringEvidence(), new object[] { partialName, securityEvidence }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly LoadWithPartialNameHookString(string partialName)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("LoadWithPartialNameHookString");
//Call the original function
assembly = Assembly.LoadWithPartialName(partialName);
//Restore the hook
HookManager.HookByHookName("LoadWithPartialNameHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyLoadWithPartialNameString(), new object[] { partialName }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly ReflectionOnlyLoadHookString(string assemblyString)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReflectionOnlyLoadHookString");
//Call the original function
assembly = Assembly.ReflectionOnlyLoad(assemblyString);
//Restore the hook
HookManager.HookByHookName("ReflectionOnlyLoadHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyReflectionOnlyLoadString(), new object[] { assemblyString }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly ReflectionOnlyLoadHookByteArray(byte[] rawAssembly)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReflectionOnlyLoadHookByteArray");
//Call the original function
assembly = Assembly.ReflectionOnlyLoad(rawAssembly);
//Restore the hook
HookManager.HookByHookName("ReflectionOnlyLoadHookByteArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyReflectionOnlyLoadByteArray(), new object[] { rawAssembly }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly ReflectionOnlyLoadFromHookString(string assemblyFile)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReflectionOnlyLoadFromHookString");
//Call the original function
assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile);
//Restore the hook
HookManager.HookByHookName("ReflectionOnlyLoadFromHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyReflectionOnlyLoadFromString(), new object[] { assemblyFile }, assembly);
}
//Return the assembly to the caller
return assembly;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Assembly UnsafeLoadFromHookString(string assemblyFile)
{
//Declare the local variable to store the assembly in
Assembly assembly;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("UnsafeLoadFromHookString");
//Call the original function
assembly = Assembly.UnsafeLoadFrom(assemblyFile);
//Restore the hook
HookManager.HookByHookName("UnsafeLoadFromHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.AssemblyUnsafeLoadFromString(), new object[] { assemblyFile }, assembly);
}
//Return the assembly to the caller
return assembly;
}
}
}
================================================
FILE: DotDumper/HookHandlers/Console/ConsoleHooks.cs
================================================
using System;
using System.Runtime.CompilerServices;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class ConsoleHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookString(string value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteString(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookObject(object value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteObject(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookUlong(ulong value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteUlong(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookLong(long value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLong(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookInt(int value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteInt(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookUint(uint value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteUint(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookBool(bool value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteBool(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookChar(char value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteChar(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookDecimal(decimal value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteDecimal(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookFloat(float value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteFloat(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookDouble(double value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteDouble(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookStringObject(string format, object arg0)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteStringObject(), new object[] { format, arg0 }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookStringObjectObject(string format, object arg0, object arg1)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteStringObjectObject(), new object[] { format, arg0, arg1 }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookStringObjectObjectObject(string format, object arg0, object arg1, object arg2)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteStringObjectObjectObject(), new object[] { format, arg0, arg1, arg2 }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookStringObjectObjectObjectObject(string format, object arg0, object arg1, object arg2, object arg3)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteStringObjectObjectObjectObject(), new object[] { format, arg0, arg1, arg2, arg3 }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookStringObjectArray(string format, params object[] arg)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteStringObjectArray(), new object[] { format, arg }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookCharArray(char[] buffer)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteCharArray(), new object[] { buffer }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteHookCharArrayIntInt(char[] buffer, int index, int count)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteCharArrayIntInt(), new object[] { buffer, index, count }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookString(string value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteString(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookObject(object value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineObject(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookUlong(ulong value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineUlong(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookLong(long value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineLong(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookInt(int value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineInt(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookUint(uint value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineUint(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookBool(bool value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineBool(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookChar(char value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineChar(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookDecimal(decimal value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineDecimal(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookFloat(float value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineFloat(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookDouble(double value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineDouble(), new object[] { value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookStringObject(string format, object arg0)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineStringObject(), new object[] { format, arg0 }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookStringObjectObject(string format, object arg0, object arg1)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineStringObjectObject(), new object[] { format, arg0, arg1 }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookStringObjectObjectObject(string format, object arg0, object arg1, object arg2)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineStringObjectObjectObject(), new object[] { format, arg0, arg1, arg2 }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookStringObjectObjectObjectObject(string format, object arg0, object arg1, object arg2, object arg3)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineStringObjectObjectObjectObject(), new object[] { format, arg0, arg1, arg2, arg3 }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookStringObjectArray(string format, params object[] arg)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineStringObjectArray(), new object[] { format, arg }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookCharArray(char[] buffer)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineCharArray(), new object[] { buffer }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHookCharArrayIntInt(char[] buffer, int index, int count)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLineCharArrayIntInt(), new object[] { buffer, index, count }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteLineHook()
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
Console.WriteLine();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConsoleWriteLine(), new object[] { }, null);
}
}
}
}
================================================
FILE: DotDumper/HookHandlers/Convert/ConvertHooks.cs
================================================
using System;
using System.Runtime.CompilerServices;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class ConvertHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static byte[] FromBase64StringString(string s)
{
//Declare the local variable to store the object in
byte[] output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("FromBase64StringString");
//Call the original function
output = Convert.FromBase64String(s);
//Restore the hook
HookManager.HookByHookName("FromBase64StringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConvertFromBase64StringString(), new object[] { s }, output);
}
//Return the process object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static byte[] FromBase64CharArrayCharyArrayIntInt(char[] inArray, int offset, int length)
{
//Declare the local variable to store the object in
byte[] output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("FromBase64CharArrayCharyArrayIntInt");
//Call the original function
output = Convert.FromBase64CharArray(inArray, offset, length);
//Restore the hook
HookManager.HookByHookName("FromBase64CharArrayCharyArrayIntInt");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ConvertFromBase64CharArrayCharArrayIntInt(), new object[] { inArray, offset, length }, output);
}
//Return the process object to the caller
return output;
}
}
}
================================================
FILE: DotDumper/HookHandlers/Directory/DirectoryHooks.cs
================================================
namespace DotDumper.HookHandlers
{
class DirectoryHooks
{
}
}
================================================
FILE: DotDumper/HookHandlers/Environment/EnvironmentHooks.cs
================================================
using System;
using System.Runtime.CompilerServices;
using System.Collections;
using static System.Environment;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class EnvironmentHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ExitHookInt(int exitCode)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentExitInt(), new object[] { exitCode }, null);
//Disable the placed hook
HookManager.UnHookByHookName("ExitHookInt");
//Call the original function
Environment.Exit(exitCode);
//Restore the hook
HookManager.HookByHookName("ExitHookInt");
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string ExpandEnvironmentVariablesHookString(string name)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ExpandEnvironmentVariablesHookString");
//Call the original function
output = Environment.ExpandEnvironmentVariables(name);
//Restore the hook
HookManager.HookByHookName("ExpandEnvironmentVariablesHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentExpandEnvironmentVariablesString(), new object[] { name }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void FailFastHookStringException(string message, Exception exception)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentFailFastStringException(), new object[] { message, exception }, null);
//Disable the placed hook
HookManager.UnHookByHookName("FailFastHookStringException");
//Call the original function
Environment.FailFast(message, exception);
//Restore the hook
HookManager.HookByHookName("FailFastHookStringException");
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void FailFastHookString(string message)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentFailFastString(), new object[] { message }, null);
//Disable the placed hook
HookManager.UnHookByHookName("FailFastHookString");
//Call the original function
Environment.FailFast(message);
//Restore the hook
HookManager.HookByHookName("FailFastHookString");
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string[] GetCommandLineArgsHook()
{
//Declare the local variable to store the object in
string[] output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetCommandLineArgsHook");
//Call the original function
//TODO obtain provided CLI arguments, if any, otherwise return an empty array, as this would return the CLI arguments of DotDumper itself
//output = Environment.GetCommandLineArgs();
output = new string[0];
//Restore the hook
HookManager.HookByHookName("GetCommandLineArgsHook");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentGetCommandLineArgs(), new object[] { }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetEnvironmentVariableHookStringEnvironmentVariableTarget(string variable, EnvironmentVariableTarget target)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetEnvironmentVariableHookStringEnvironmentVariableTarget");
//Call the original function
output = Environment.GetEnvironmentVariable(variable, target);
//Restore the hook
HookManager.HookByHookName("GetEnvironmentVariableHookStringEnvironmentVariableTarget");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentGetEnvironmentVariableStringEnvironmentVariableTarget(), new object[] { variable, target }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetEnvironmentVariablesHookString(string variable)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetEnvironmentVariablesHookString");
//Call the original function
output = Environment.GetEnvironmentVariable(variable);
//Restore the hook
HookManager.HookByHookName("GetEnvironmentVariablesHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentGetEnvironmentVariableString(), new object[] { variable }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static IDictionary GetEnvironmentVariablesHookEnvironmentVariableTarget(EnvironmentVariableTarget target)
{
//Declare the local variable to store the object in
IDictionary output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetEnvironmentVariablesHookEnvironmentVariableTarget");
//Call the original function
output = Environment.GetEnvironmentVariables(target);
//Restore the hook
HookManager.HookByHookName("GetEnvironmentVariablesHookEnvironmentVariableTarget");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentGetEnvironmentVariablesEnvironmentVariableTarget(), new object[] { target }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static IDictionary GetEnvironmentVariablesHook()
{
//Declare the local variable to store the object in
IDictionary output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetEnvironmentVariablesHook");
//Call the original function
output = Environment.GetEnvironmentVariables();
//Restore the hook
HookManager.HookByHookName("GetEnvironmentVariablesHook");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentGetEnvironmentVariables(), new object[] { }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetFolderPathHookSpecialFolderSpecialFolderOption(SpecialFolder folder, SpecialFolderOption option)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetFolderPathHookSpecialFolderSpecialFolderOption");
//Call the original function
output = Environment.GetFolderPath(folder, option);
//Restore the hook
HookManager.HookByHookName("GetFolderPathHookSpecialFolderSpecialFolderOption");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentGetFolderPathSpecialFolderSpecialFolderOption(), new object[] { folder, option }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetFolderPathHookSpecialFolder(SpecialFolder folder)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetFolderPathHookSpecialFolder");
//Call the original function
output = Environment.GetFolderPath(folder);
//Restore the hook
HookManager.HookByHookName("GetFolderPathHookSpecialFolder");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentGetFolderPathSpecialFolder(), new object[] { folder }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string[] GetLogicalDrivesHook()
{
//Declare the local variable to store the object in
string[] output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetLogicalDrivesHook");
//Call the original function
output = Environment.GetLogicalDrives();
//Restore the hook
HookManager.HookByHookName("GetLogicalDrivesHook");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentGetLogicalDrives(), new object[] { }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SetEnvironmentVariableHookStringStringEnvironmentVariableTarget(string variable, string value, EnvironmentVariableTarget target)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("SetEnvironmentVariableHookStringStringEnvironmentVariableTarget");
//Call the original function
Environment.SetEnvironmentVariable(variable, value, target);
//Restore the hook
HookManager.HookByHookName("SetEnvironmentVariableHookStringStringEnvironmentVariableTarget");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentSetEnvironmentVariableStringStringEnvironmentVariableTarget(), new object[] { variable, value, target }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SetEnvironmentVariableHookStringString(string variable, string value)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("SetEnvironmentVariableHookStringStringEnvironmentVariableTarget");
//Call the original function
Environment.SetEnvironmentVariable(variable, value);
//Restore the hook
HookManager.HookByHookName("SetEnvironmentVariableHookStringStringEnvironmentVariableTarget");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.EnvironmentSetEnvironmentVariableStringString(), new object[] { variable, value }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetResourceFromDefaultHookString(string key)
{
object result = null;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookAll();
//Call the original function
result = OriginalManagedFunctions.EnvironmentGetResourceFromDefaultString().Invoke(null, new object[] { key });
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.EnvironmentGetResourceFromDefaultString(), new object[] { key }, result);
//Restore the hook
HookManager.HookAll();
}
return (string)result;
}
}
}
================================================
FILE: DotDumper/HookHandlers/File/FileHooks.cs
================================================
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security.AccessControl;
using System.Text;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class FileHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AppendAllLinesHookStringIenumerableString(string path, IEnumerable contents)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("FileAppendAllLinesHookStringIenumerableString");
//Call the original function
File.AppendAllLines(path, contents);
//Restore the hook
HookManager.HookByHookName("FileAppendAllLinesHookStringIenumerableString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileAppendAllLinesStringIenumerableString(), new object[] { path, contents }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AppendAllLinesHookStringIenumerableStringEncoding(string path, IEnumerable contents, Encoding encoding)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("FileAppendAllLinesHookStringIenumerableStringEncoding");
//Call the original function
File.AppendAllLines(path, contents, encoding);
//Restore the hook
HookManager.HookByHookName("FileAppendAllLinesHookStringIenumerableStringEncoding");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileAppendAllLinesStringIenumerableString(), new object[] { path, contents, encoding }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AppendAllTextHookStringStringEncoding(string path, string contents, Encoding encoding)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("FileAppendAllTextHookStringStringEncoding");
//Call the original function
File.AppendAllText(path, contents, encoding);
//Restore the hook
HookManager.HookByHookName("FileAppendAllTextHookStringStringEncoding");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileAppendAllTextStringStringEncoding(), new object[] { path, contents, encoding }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AppendAllTextHookStringString(string path, string contents)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("FileAppendAllTextHookStringString");
//Call the original function
File.AppendAllText(path, contents);
//Restore the hook
HookManager.HookByHookName("FileAppendAllTextHookStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileAppendAllTextStringString(), new object[] { path, contents }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static StreamWriter AppendTextHookString(string path)
{
//Declare the local variable to store the object in
StreamWriter stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("FileAppendTextHookString");
//Call the original function
stream = File.AppendText(path);
//Restore the hook
HookManager.HookByHookName("FileAppendTextHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileAppendTextString(), new object[] { path }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void CopyHookStringString(string sourceFileName, string destFileName)
{
//Declare the local variable to store the object in
//StreamWriter stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CopyHookStringString");
//Call the original function
File.Copy(sourceFileName, destFileName);
//Restore the hook
HookManager.HookByHookName("CopyHookStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileCopyStringString(), new object[] { sourceFileName, destFileName }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void CopyHookStringStringBoolean(string sourceFileName, string destFileName, bool overwrite)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CopyHookStringStringBoolean");
//Call the original function
File.Copy(sourceFileName, destFileName, overwrite);
//Restore the hook
HookManager.HookByHookName("CopyHookStringStringBoolean");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileCopyStringStringBoolean(), new object[] { sourceFileName, destFileName, overwrite }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static FileStream CreateHookString(string path)
{
//Declare the local variable to store the object in
FileStream stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CreateHookString");
//Call the original function
stream = File.Create(path);
//Restore the hook
HookManager.HookByHookName("CreateHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileCreateString(), new object[] { path }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static FileStream CreateHookStringInt(string path, int bufferSize)
{
//Declare the local variable to store the object in
FileStream stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CreateHookStringInt");
//Call the original function
stream = File.Create(path, bufferSize);
//Restore the hook
HookManager.HookByHookName("CreateHookStringInt");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileCreateStringInt(), new object[] { path, bufferSize }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static FileStream CreateHookStringIntFileOptions(string path, int bufferSize, FileOptions fileOptions)
{
//Declare the local variable to store the object in
FileStream stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CreateHookStringIntFileOptions");
//Call the original function
stream = File.Create(path, bufferSize, fileOptions);
//Restore the hook
HookManager.HookByHookName("CreateHookStringIntFileOptions");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileCreateStringIntFileOptions(), new object[] { path, bufferSize, fileOptions }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static FileStream CreateHookStringIntFileOptionsFileSecurity(string path, int bufferSize, FileOptions fileOptions, FileSecurity fileSecurity)
{
//Declare the local variable to store the object in
FileStream stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CreateHookStringIntFileOptionsFileSecurity");
//Call the original function
stream = File.Create(path, bufferSize, fileOptions, fileSecurity);
//Restore the hook
HookManager.HookByHookName("CreateHookStringIntFileOptionsFileSecurity");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileCreateStringIntFileOptionsFileSecurity(), new object[] { path, bufferSize, fileOptions, fileSecurity }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static StreamWriter CreateTextHookString(string path)
{
//Declare the local variable to store the object in
StreamWriter stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CreateTextHookString");
//Call the original function
stream = File.CreateText(path);
//Restore the hook
HookManager.HookByHookName("CreateTextHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileCreateTextString(), new object[] { path }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DecryptHookString(string path)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("DecryptHookString");
//Call the original function
File.Decrypt(path);
//Restore the hook
HookManager.HookByHookName("DecryptHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileDecryptString(), new object[] { path }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DeleteHookString(string path)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("DeleteHookString");
//Call the original function
File.Delete(path);
//Restore the hook
HookManager.HookByHookName("DeleteHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileDeleteString(), new object[] { path }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void EncryptHookString(string path)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("EncryptHookString");
//Call the original function
File.Encrypt(path);
//Restore the hook
HookManager.HookByHookName("EncryptHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileEncryptString(), new object[] { path }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool ExiststHookString(string path)
{
//Declare the local variable to store the object in
bool result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ExiststHookString");
//Call the original function
result = File.Exists(path);
//Restore the hook
HookManager.HookByHookName("ExiststHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.FileExiststString(), new object[] { path }, result);
}
//Return the result to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void MoveHookStringString(string sourceFileName, string destFileName)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("MoveHookStringString");
//Call the original function
File.Move(sourceFileName, destFileName);
//Restore the hook
HookManager.HookByHookName("MoveHookStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileMoveStringString(), new object[] { sourceFileName, destFileName }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static FileStream OpenHookStringFileModeFileAccessFileShare(string path, FileMode mode, FileAccess access, FileShare share)
{
//Declare the local variable to store the object in
FileStream stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("OpenHookStringFileModeFileAccessFileShare");
//Call the original function
stream = File.Open(path, mode, access, share);
//Restore the hook
HookManager.HookByHookName("OpenHookStringFileModeFileAccessFileShare");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileOpenStringFileModeFileAccessFileShare(), new object[] { path, mode, access, share }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static FileStream OpenHookStringFileModeFileAccess(string path, FileMode mode, FileAccess access)
{
//Declare the local variable to store the object in
FileStream stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("OpenHookStringFileModeFileAccess");
//Call the original function
stream = File.Open(path, mode, access);
//Restore the hook
HookManager.HookByHookName("OpenHookStringFileModeFileAccess");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileOpenStringFileModeFileAccess(), new object[] { path, mode, access }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static FileStream OpenHookStringFileMode(string path, FileMode mode)
{
//Declare the local variable to store the object in
FileStream stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("OpenHookStringFileMode");
//Call the original function
stream = File.Open(path, mode);
//Restore the hook
HookManager.HookByHookName("OpenHookStringFileMode");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileOpenStringFileMode(), new object[] { path, mode }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static StreamReader OpenTextHookString(string path)
{
//Declare the local variable to store the object in
StreamReader stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("OpenTextHookString");
//Call the original function
stream = File.OpenText(path);
//Restore the hook
HookManager.HookByHookName("OpenTextHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileOpenTextString(), new object[] { path }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static FileStream OpenWriteHookString(string path)
{
//Declare the local variable to store the object in
FileStream stream;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("OpenWriteHookString");
//Call the original function
stream = File.OpenWrite(path);
//Restore the hook
HookManager.HookByHookName("OpenWriteHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileOpenWriteString(), new object[] { path }, stream);
}
//Return the object to the caller
return stream;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string[] ReadAllLinesHookString(string path)
{
//Declare the local variable to store the object in
string[] lines;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReadAllLinesHookString");
//Call the original function
lines = File.ReadAllLines(path);
//Restore the hook
HookManager.HookByHookName("ReadAllLinesHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReadAllLinesString(), new object[] { path }, lines);
}
//Return the object to the caller
return lines;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string[] ReadAllLinesHookStringEncoding(string path, Encoding encoding)
{
//Declare the local variable to store the object in
string[] lines;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReadAllLinesHookStringEncoding");
//Call the original function
lines = File.ReadAllLines(path, encoding);
//Restore the hook
HookManager.HookByHookName("ReadAllLinesHookStringEncoding");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReadAllLinesStringEncoding(), new object[] { path, encoding }, lines);
}
//Return the object to the caller
return lines;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string ReadAllTextHookStringEncoding(string path, Encoding encoding)
{
//Declare the local variable to store the object in
string text;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReadAllTextHookStringEncoding");
//Call the original function
text = File.ReadAllText(path, encoding);
//Restore the hook
HookManager.HookByHookName("ReadAllTextHookStringEncoding");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReadAllTextStringEncoding(), new object[] { path, encoding }, text);
}
//Return the object to the caller
return text;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string ReadAllTextHookString(string path)
{
//Declare the local variable to store the object in
string text;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReadAllTextHookString");
//Call the original function
text = File.ReadAllText(path);
//Restore the hook
HookManager.HookByHookName("ReadAllTextHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReadAllTextString(), new object[] { path }, text);
}
//Return the object to the caller
return text;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static IEnumerable ReadLinesHookString(string path)
{
//Declare the local variable to store the object in
IEnumerable lines;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReadLinesHookString");
//Call the original function
lines = File.ReadLines(path);
//Restore the hook
HookManager.HookByHookName("ReadLinesHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReadLinesString(), new object[] { path }, lines);
}
//Return the object to the caller
return lines;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static IEnumerable ReadLinesHookStringEncoding(string path, Encoding encoding)
{
//Declare the local variable to store the object in
IEnumerable lines;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReadLinesHookStringEncoding");
//Call the original function
lines = File.ReadLines(path, encoding);
//Restore the hook
HookManager.HookByHookName("ReadLinesHookStringEncoding");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReadLinesStringEncoding(), new object[] { path, encoding }, lines);
}
//Return the object to the caller
return lines;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ReplaceHookStringStringString(string sourceFileName, string destinationFileName, string destinationBackupFileName)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReplaceHookStringStringString");
//Call the original function
File.Replace(sourceFileName, destinationFileName, destinationBackupFileName);
//Restore the hook
HookManager.HookByHookName("ReplaceHookStringStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReplaceStringStringString(), new object[] { sourceFileName, destinationFileName, destinationBackupFileName }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ReplaceHookStringStringStringBoolean(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReplaceHookStringStringStringBoolean");
//Call the original function
File.Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
//Restore the hook
HookManager.HookByHookName("ReplaceHookStringStringStringBoolean");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReplaceStringStringStringBoolean(), new object[] { sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SetAccessControlHookStringFileSecurity(string path, FileSecurity fileSecurity)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("SetAccessControlHookStringFileSecurity");
//Call the original function
File.SetAccessControl(path, fileSecurity);
//Restore the hook
HookManager.HookByHookName("SetAccessControlHookStringFileSecurity");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileSetAccessControlStringFileSecurity(), new object[] { path, fileSecurity }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SetAttributesHookStringFileAttributes(string path, FileAttributes fileAttributes)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("SetAttributesHookStringFileAttributes");
//Call the original function
File.SetAttributes(path, fileAttributes);
//Restore the hook
HookManager.HookByHookName("SetAttributesHookStringFileAttributes");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileSetAttributesStringFileAttributes(), new object[] { path, fileAttributes }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteAllBytesHookStringByteArray(string path, byte[] bytes)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("WriteAllBytesHookStringByteArray");
//Call the original function
File.WriteAllBytes(path, bytes);
//Restore the hook
HookManager.HookByHookName("WriteAllBytesHookStringByteArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileWriteAllBytesStringByteArray(), new object[] { path, bytes }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteAllLinesHookStringStringArray(string path, string[] lines)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("WriteAllLinesHookStringStringArray");
//Call the original function
File.WriteAllLines(path, lines);
//Restore the hook
HookManager.HookByHookName("WriteAllLinesHookStringStringArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileWriteAllLinesStringStringArray(), new object[] { path, lines }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteAllLinesHookStringStringArrayEncoding(string path, string[] lines, Encoding encoding)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("WriteAllLinesHookStringStringArrayEncoding");
//Call the original function
File.WriteAllLines(path, lines, encoding);
//Restore the hook
HookManager.HookByHookName("WriteAllLinesHookStringStringArrayEncoding");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileWriteAllLinesStringStringArrayEncoding(), new object[] { path, lines, encoding }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteAllLinesHookStringIenumerableString(string path, IEnumerable contents)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("WriteAllLinesHookStringIenumerableString");
//Call the original function
File.WriteAllLines(path, contents);
//Restore the hook
HookManager.HookByHookName("WriteAllLinesHookStringIenumerableString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileWriteAllLinesStringIenumerableString(), new object[] { path, contents }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteAllLinesHookStringIenumerableStringEncoding(string path, IEnumerable contents, Encoding encoding)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("WriteAllLinesHookStringIenumerableStringEncoding");
//Call the original function
File.WriteAllLines(path, contents, encoding);
//Restore the hook
HookManager.HookByHookName("WriteAllLinesHookStringIenumerableStringEncoding");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileWriteAllLinesStringIenumerableStringEncoding(), new object[] { path, contents, encoding }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteAllTextHookStringString(string path, string contents)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("WriteAllTextHookStringString");
//Call the original function
File.WriteAllText(path, contents);
//Restore the hook
HookManager.HookByHookName("WriteAllTextHookStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileWriteAllTextStringString(), new object[] { path, contents }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void WriteAllTextHookStringStringEncoding(string path, string contents, Encoding encoding)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("WriteAllTextHookStringStringEncoding");
//Call the original function
File.WriteAllText(path, contents, encoding);
//Restore the hook
HookManager.HookByHookName("WriteAllTextHookStringStringEncoding");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileWriteAllTextStringStringEncoding(), new object[] { path, contents, encoding }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static byte[] ReadAllBytesHookString(string path)
{
//Declare the local variable to store the object in
byte[] bytes;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ReadAllBytesHookString");
//Call the original function
bytes = File.ReadAllBytes(path);
//Restore the hook
HookManager.HookByHookName("ReadAllBytesHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.FileReadAllBytesString(), new object[] { path }, bytes);
}
//Return the object to the caller
return bytes;
}
}
}
================================================
FILE: DotDumper/HookHandlers/GenericHookHelper.cs
================================================
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.IO;
using DotDumper.Helpers;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
///
/// This class provides helper functions that are used by multiple hook classes, thereby avoiding duplicate code blocks.
///
class GenericHookHelper
{
///
/// The synchornisation object to ensure that multi-threaded malware does not cause two hooks to call the logger at the same time
///
public static readonly object SyncLock = new object();
///
/// The original sample that was loaded by DotDumper
///
public static Assembly OriginalAssembly;
///
/// The logger object to log data
///
public static Logger _Logger;
///
/// Gets the stack trace that leads to this function call, the amount of offset lines from the start. The removal is done to exclude hook related functions to end up in the trace, as that would clutter the overview.
///
/// The amount of lines to skip, equal to the amount of functions that are entered from the hook prior to this function (including the hook itself)
/// The stack trace to the call in the original code
public static string GetStackTraceAndAssemblyMapping(int offset)
{
//Increment the offset, as the trace is requested in this function, which is another line/layer deep
offset++;
//Initialise the variable where the result will be stored
string result = "---StackTrace information---\n";
//Get the trace, split by lines
List stackTraceLines = GetStackTraceRaw(offset);
//Add all lines from the given offset to the result variable, including a newline for each added line
for (int i = 0; i < stackTraceLines.Count; i++)
{
result += stackTraceLines[i] + "\n";
}
result += "----------------------------\n\n";
//Get the assembly call order from the mapper
result += "-----Assembly call order-----\n";
result += AssemblyMapper.ProcessStackTrace(stackTraceLines);
result += "-----------------------------\n\n";
//Return the result
return result;
}
///
/// Gets the stack trace, based on the given offset
///
/// the number of calls since the original function has been called
/// A list of strings that make up the stack trace. All hooks will be set prior to this function's return
public static List GetStackTraceRaw(int offset)
{
HookManager.UnHookAll();
List stackTraceLines = new List();
//Increment the offset, as the trace is requested in this function, which is another line/layer deep
offset++;
//Increment the offset by two as the stacktrace itself is two additional layers deep when requesting it
offset += 2;
//Initialise and simplify newlines in the stacktrace
string rawStackTrace = Environment.StackTrace.Replace("\r\n", "\n");
//Get the trace for each
string[] lines = rawStackTrace.Split(new char[] { '\n' });
//If the given offset is too big or less than zero, ignore the value and simply return the complete stacktrace
if (offset >= lines.Length || offset < 0)
{
offset = 0;
}
//Add all lines from the given offset to the result variable, including a newline for each added line
for (int i = offset; i < lines.Length; i++)
{
stackTraceLines.Add(lines[i]);
}
HookManager.HookAll();
//Return the result
return stackTraceLines;
}
///
/// Saves the given data in the logger folder as a file, with the given file name (not starting with a backslash). If such a file already exists, it is overwritten without warning! This function is only to be used after the hooks are set, as all hooks are set prior to returning.
///
/// The name of the file to save
/// The data to save
/// The complete path to the newly saved file
public static string SaveFile(string fileName, byte[] data)
{
//Call Directory.CreateDirectory by unhooking the hooks, and hooking them afterwards
DirectoryCreateDirectory(_Logger.Folder);
//Create the full path, using the logging folder as the base
string path = _Logger.Folder + @"\" + fileName;
//Write all bytes using File.WriteAllBytes to the given path
FileWriteAllBytes(path, data);
//Return the full path of the newly saved file
return path;
}
///
/// Saves the given data in the logger folder as a file, using the SHA-256 hash of the data as the file name (not starting with a backslash). If the file already exists, it is overwritten without warning! This function is only to be used after the hooks are set, as all hooks are set prior to returning.
///
/// The data to save
/// A tuple, with the complete path to the newly saved file, and a hash object with the MD-5, SHA-1, and SHA-256 hash of the newly saved file
public static Tuple SaveFile(byte[] data)
{
string md5 = Hashes.Md5(data);
string sha1 = Hashes.Sha1(data);
string sha256 = Hashes.Sha256(data);
string sha384 = Hashes.Sha384(data);
string sha512 = Hashes.Sha512(data);
string typeRef = Hashes.TypeRef(data);
string importHash = Hashes.ImportHash(data);
string authenticodeSha256 = Hashes.AuthenticodeSha256(data);
string path = SaveFile(sha256, data);
return Tuple.Create(path, new Models.Hash(md5, sha1, sha256, sha384, sha512, typeRef, importHash, authenticodeSha256));
}
///
/// Saves the given string in the logger folder as a file, using the SHA-256 hash of the data as the file name (not starting with a backslash). If the file already exists, it is overwritten without warning! This function is only to be used after the hooks are set, as all hooks are set prior to returning.
///
/// The data to save
/// The complete path to the newly saved file
public static Tuple SaveFile(string data)
{
byte[] rawData = Encoding.Default.GetBytes(data);
return SaveFile(rawData);
}
///
/// Removes all hooks, calls File.ReadAllBytes(string path) with the given path, and sets all hooks. The result of the function call is returned.
///
/// The path to read the data from
/// The data that has been read from the given path
public static byte[] FileReadAllBytes(string path)
{
HookManager.UnHookAll();
byte[] data = File.ReadAllBytes(path);
HookManager.HookAll();
return data;
}
///
/// Removes all hooks, calls File.AppendAllText(string path, string contents) with the given path and contents, and sets all hooks.
///
/// The path to append the contents to
/// The text to append
public static void FileAppendAllText(string path, string contents)
{
HookManager.UnHookAll();
File.AppendAllText(path, contents);
HookManager.HookAll();
}
///
/// Removes all hooks, calls File.WriteAllBytes(string path, byte[] bytes) with the given path and bytes, and sets all hooks.
///
/// The path to write all bytes to
/// The bytes to write
public static void FileWriteAllBytes(string path, byte[] bytes)
{
HookManager.UnHookAll();
File.WriteAllBytes(path, bytes);
HookManager.HookAll();
}
///
/// Removes all hooks, calls Path.GetFileName(string path) with the given path, sets all hooks, and returns the file name
///
/// The path to get the file name from
/// The file name of the file at the given path
public static string PathGetFileName(string path)
{
HookManager.UnHookAll();
string fileName = Path.GetFileName(path);
HookManager.HookAll();
return fileName;
}
///
/// Removes the hook named "SleepHookInt", calls Thread.Sleep(int milliseconds) with the given milliseconds, and sets the hook named "SleepHookInt".
///
/// The amount of milliseconds to sleep
public static void ThreadSleep(int milliseconds)
{
HookManager.UnHookByHookName("SleepHookInt");
Thread.Sleep(milliseconds);
HookManager.HookByHookName("SleepHookInt");
}
///
/// Removes all hooks, calls Directory.CreateDirectory(string folder) with the given folder, and sets all hooks.
///
/// The folder to create
/// The relevant DirectoryInfo object
public static DirectoryInfo DirectoryCreateDirectory(string folder)
{
HookManager.UnHookAll();
DirectoryInfo directoryInfo = Directory.CreateDirectory(folder);
HookManager.HookAll();
return directoryInfo;
}
///
/// Removes all hooks, calls Console.WriteLine(string value) with the given value, and sets all hooks
///
/// The value to write to the standard output
public static void ConsoleWriteLine(string value)
{
HookManager.UnHookAll();
Console.WriteLine(value);
HookManager.HookAll();
}
///
/// Gets the raw data of the given Assembly object. This function removes all hooks, after which the raw data is obtained reflectively. All hooks are then set.
///
/// The Assembly object to get the raw data from
/// The raw bytes of the given Assembly object
public static byte[] GetAsByteArray(Assembly assembly)
{
HookManager.UnHookAll();
//Taken from https://stackoverflow.com/a/46209735
Hash hash = new Hash(assembly);
byte[] rawAssembly = (byte[])hash.GetType().GetMethod("GetRawData", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(hash, new object[0]);
HookManager.HookAll();
return rawAssembly;
}
}
}
================================================
FILE: DotDumper/HookHandlers/MethodBase/MethodBaseHooks.cs
================================================
using System.Reflection;
using System.Runtime.CompilerServices;
using DotDumper.Helpers;
namespace DotDumper.HookHandlers
{
class MethodBaseHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static object InvokeHookObjectObjectArray(MethodBase methodBase, object obj, object[] parameters)
{
//Declare the local variable to store the assembly object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
int stackTraceOffset = 1;
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(stackTraceOffset, methodBase, parameters, null);
}
//Start the timer to induce the race condition
RaceConditionHandler.StartTimer("InvokeHookObjectObjectArray");
//Call the original function
result = methodBase.Invoke(obj, parameters);
//Return the process object to the caller
return result;
}
}
}
================================================
FILE: DotDumper/HookHandlers/Path/PathHooks.cs
================================================
using System.IO;
using System.Runtime.CompilerServices;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class PathHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static string ChangeExtensionHookStringString(string path, string extension)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("ChangeExtensionHookStringString");
//Call the original function
output = Path.ChangeExtension(path, extension);
//Restore the hook
HookManager.HookByHookName("ChangeExtensionHookStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathChangeExtensionStringString(), new object[] { path, extension }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string CombineHookStringString(string path1, string path2)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CombineHookStringString");
//Call the original function
output = Path.Combine(path1, path2);
//Restore the hook
HookManager.HookByHookName("CombineHookStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathCombineStringString(), new object[] { path1, path2 }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string CombineHookStringStringString(string path1, string path2, string path3)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CombineHookStringStringString");
//Call the original function
output = Path.Combine(path1, path2, path3);
//Restore the hook
HookManager.HookByHookName("CombineHookStringStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathCombineStringStringString(), new object[] { path1, path2, path3 }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string CombineHookStringStringStringString(string path1, string path2, string path3, string path4)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CombineHookStringStringStringString");
//Call the original function
output = Path.Combine(path1, path2, path3, path4);
//Restore the hook
HookManager.HookByHookName("CombineHookStringStringStringString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathCombineStringStringStringString(), new object[] { path1, path2, path3, path4 }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string CombineHookStringArray(string[] paths)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("CombineHookStringArray");
//Call the original function
output = Path.Combine(paths);
//Restore the hook
HookManager.HookByHookName("CombineHookStringArray");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathCombineStringArray(), new object[] { paths }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetDirectoryNameHookString(string path)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetDirectoryNameHookString");
//Call the original function
output = Path.GetDirectoryName(path);
//Restore the hook
HookManager.HookByHookName("GetDirectoryNameHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetDirectoryNameString(), new object[] { path }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetExtensionHookString(string path)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetExtensionHookString");
//Call the original function
output = Path.GetExtension(path);
//Restore the hook
HookManager.HookByHookName("GetExtensionHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetExtensionString(), new object[] { path }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetFileNameHookString(string path)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetFileNameHookString");
//Call the original function
output = Path.GetFileName(path);
//Restore the hook
HookManager.HookByHookName("GetFileNameHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetFileNameString(), new object[] { path }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetFileNameWithoutExtensionHookString(string path)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetFileNameWithoutExtensionHookString");
//Call the original function
output = Path.GetFileNameWithoutExtension(path);
//Restore the hook
HookManager.HookByHookName("GetFileNameWithoutExtensionHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetFileNameWithoutExtensionString(), new object[] { path }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetFullPathHookString(string path)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetFullPathHookString");
//Call the original function
output = Path.GetFullPath(path);
//Restore the hook
HookManager.HookByHookName("GetFullPathHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetFullPathString(), new object[] { path }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetPathRootHookString(string path)
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetPathRootHookString");
//Call the original function
output = Path.GetPathRoot(path);
//Restore the hook
HookManager.HookByHookName("GetPathRootHookString");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetPathRootString(), new object[] { path }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetRandomFileNameHook()
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetRandomFileNameHook");
//Call the original function
output = Path.GetRandomFileName();
//Restore the hook
HookManager.HookByHookName("GetRandomFileNameHook");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetRandomFileName(), new object[] { }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetTempFileNameHook()
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetTempFileNameHook");
//Call the original function
output = Path.GetTempFileName();
//Restore the hook
HookManager.HookByHookName("GetTempFileNameHook");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetTempFileName(), new object[] { }, output);
}
//Return the object to the caller
return output;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetTempPathHook()
{
//Declare the local variable to store the object in
string output;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hook
HookManager.UnHookByHookName("GetTempPathHook");
//Call the original function
output = Path.GetTempPath();
//Restore the hook
HookManager.HookByHookName("GetTempPathHook");
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.PathGetTempPath(), new object[] { }, output);
}
//Return the object to the caller
return output;
}
}
}
================================================
FILE: DotDumper/HookHandlers/Process/ProcessHooks.cs
================================================
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class ProcessHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process GetCurrentProcessHook()
{
//Declare the local variable to store the process object in
Process process;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
process = Process.GetCurrentProcess();
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessGetCurrentProcess(), new object[] { }, process);
}
//Return the process object to the caller
return process;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process GetProcessByIdHookIntString(int processId, string machineName)
{
//Declare the local variable to store the process object in
Process process;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
process = Process.GetProcessById(processId, machineName);
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessGetProcessByIdIntString(), new object[] { processId, machineName }, process);
}
//Return the process object to the caller
return process;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process GetProcessByIdHookInt(int processId)
{
//Declare the local variable to store the process object in
Process process;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
process = Process.GetProcessById(processId);
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessGetProcessByIdInt(), new object[] { processId }, process);
}
//Return the process object to the caller
return process;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process[] GetProcessesHook()
{
//Declare the local variable to store the process objects in
Process[] processes;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
processes = Process.GetProcesses();
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessGetProcesses(), new object[] { }, processes);
}
//Return the process object to the caller
return processes;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process[] GetProcessesHookString(string machineName)
{
//Declare the local variable to store the process objects in
Process[] processes;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
processes = Process.GetProcesses(machineName);
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessGetProcessesString(), new object[] { machineName }, processes);
}
//Return the process object to the caller
return processes;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process[] GetProcessesByNameHookString(string processName)
{
//Declare the local variable to store the process objects in
Process[] processes;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
processes = Process.GetProcessesByName(processName);
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessGetProcessesByNameString(), new object[] { processName }, processes);
}
//Return the process object to the caller
return processes;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process[] GetProcessesByNameHookStringString(string processName, string machineName)
{
//Declare the local variable to store the process objects in
Process[] processes;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
processes = Process.GetProcessesByName(processName, machineName);
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessGetProcessesByNameStringString(), new object[] { processName, machineName }, processes);
}
//Return the process object to the caller
return processes;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process ProcessStartHookStringString(string fileName, string arguments)
{
//Declare the local variable to store the process object in
Process process;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
process = Process.Start(fileName, arguments);
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessStartStringString(), new object[] { fileName, arguments }, process);
}
//Return the process object to the caller
return process;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process ProcessStartHookProcessStartInfo(ProcessStartInfo startInfo)
{
//Declare the local variable to store the process object in
Process process;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
process = Process.Start(startInfo);
//Restore the hooks
HookManager.HookAll();
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessStartProcessStartInfo(), new object[] { startInfo }, process);
}
//Return the process object to the caller
return process;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process ProcessStartHookString(string fileName)
{
//Declare the local variable to store the process object in
Process process;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
process = Process.Start(fileName);
//Restore the hooks
HookManager.HookAll();
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessStartString(), new object[] { fileName }, process);
}
//Return the process object to the caller
return process;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process ProcessStartHookStringStringStringSecureStringString(string fileName, string arguments, string userName, SecureString password, string domain)
{
//Declare the local variable to store the process object in
Process process;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
process = Process.Start(fileName, arguments, userName, password, domain);
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessStartStringStringStringSecureStringString(), new object[] { fileName, arguments, userName, password, domain }, process);
}
//Return the process object to the caller
return process;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Process ProcessStartHookStringStringSecureStringString(string fileName, string userName, SecureString password, string domain)
{
//Declare the local variable to store the process object in
Process process;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Disable the placed hooks
HookManager.UnHookAll();
//Call the original function
process = Process.Start(fileName, userName, password, domain);
//Restore the hooks
HookManager.HookAll();
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ProcessStartStringStringSecureStringString(), new object[] { fileName, userName, password, domain }, process);
}
//Return the process object to the caller
return process;
}
}
}
================================================
FILE: DotDumper/HookHandlers/ResourceManager/ResourceManagerHooks.cs
================================================
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class ResourceManagerHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static object GetObjectHookString(ResourceManager resourceManager, string name)
{
//Declare the local variable to store the result in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookAll();
result = null;
try
{
result = resourceManager.GetObject(name);
}
catch (Exception)
{
}
if (result == null)
{
result = BruteObjectGet(name);
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ResourceManagerGetObjectString(), new object[] { name }, result);
HookManager.HookAll();
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static object GetObjectHookStringCultureInfo(ResourceManager resourceManager, string name, CultureInfo cultureInfo)
{
//Declare the local variable to store the result in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookAll();
result = null;
try
{
result = resourceManager.GetObject(name, cultureInfo);
}
catch (Exception)
{
}
if (result == null)
{
result = BruteObjectGet(name);
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ResourceManagerGetObjectStringCultureInfo(), new object[] { name, cultureInfo }, result);
HookManager.HookAll();
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetStringHookString(ResourceManager resourceManager, string name)
{
//Declare the local variable to store the result in
string result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookAll();
result = null;
try
{
result = resourceManager.GetString(name);
}
catch (Exception)
{
}
if (result == null)
{
result = BruteStringGet(name);
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ResourceManagerGetStringString(), new object[] { name }, result);
HookManager.HookAll();
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetStringHookStringCultureInfo(ResourceManager resourceManager, string name, CultureInfo cultureInfo)
{
//Declare the local variable to store the result in
string result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookAll();
result = null;
try
{
result = resourceManager.GetString(name, cultureInfo);
}
catch (Exception)
{
}
if (result == null)
{
result = BruteStringGet(name);
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ResourceManagerGetStringStringCultureInfo(), new object[] { name, cultureInfo }, result);
HookManager.HookAll();
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static UnmanagedMemoryStream GetStreamHookString(ResourceManager resourceManager, string name)
{
//Declare the local variable to store the result in
UnmanagedMemoryStream result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookAll();
result = null;
try
{
result = resourceManager.GetStream(name);
}
catch (Exception)
{
}
if (result == null)
{
result = BruteStreamGet(name);
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ResourceManagerGetStreamString(), new object[] { name }, result);
HookManager.HookAll();
}
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static UnmanagedMemoryStream GetStreamHookStringCultureInfo(ResourceManager resourceManager, string name, CultureInfo cultureInfo)
{
//Declare the local variable to store the result in
UnmanagedMemoryStream result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
HookManager.UnHookAll();
result = null;
try
{
result = resourceManager.GetStream(name, cultureInfo);
}
catch (Exception)
{
}
if (result == null)
{
result = BruteStreamGet(name);
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.LogSampleCall(1, OriginalManagedFunctions.ResourceManagerGetStreamStringCultureInfo(), new object[] { name, cultureInfo }, result);
HookManager.HookAll();
}
//Return the process object to the caller
return result;
}
private static string BruteStringGet(string resourceName)
{
string result = null;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
string[] resourceNames = assembly.GetManifestResourceNames();
foreach (string resource in resourceNames)
{
try
{
ResourceManager resourceManager = new ResourceManager(resourceName, assembly);
result = resourceManager.GetString(resourceName);
if (result != null)
{
return result;
}
}
catch (Exception)
{
//Ignore exceptions, as this function returns null if the resource cannot be found
}
}
}
return result;
}
private static object BruteObjectGet(string resourceName)
{
object result = null;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
string[] resourceNames = assembly.GetManifestResourceNames();
foreach (string resource in resourceNames)
{
try
{
ResourceManager resourceManager = new ResourceManager(resourceName, assembly);
result = resourceManager.GetObject(resourceName);
if (result != null)
{
return result;
}
}
catch (Exception)
{
//Ignore exceptions, as this function returns null if the resource cannot be found
}
}
}
return result;
}
private static UnmanagedMemoryStream BruteStreamGet(string resourceName)
{
UnmanagedMemoryStream result = null;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
string[] resourceNames = assembly.GetManifestResourceNames();
foreach (string resource in resourceNames)
{
try
{
ResourceManager resourceManager = new ResourceManager(resourceName, assembly);
result = resourceManager.GetStream(resourceName, null);
if (result != null)
{
return result;
}
}
catch (Exception)
{
//Ignore exceptions, as this function returns null if the resource cannot be found
}
}
}
return result;
}
}
}
================================================
FILE: DotDumper/HookHandlers/Thread/ThreadHooks.cs
================================================
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using DotDumper.Hooks;
namespace DotDumper.HookHandlers
{
class ThreadHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SleepHookInt(int millisecondsTimeout)
{
//Avoids cluttering the log
if (millisecondsTimeout <= 1)
{
return;
}
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//If sleep is to be skipped, the function is never called
if (Config.SleepSkip == false)
{
//Disable the placed hook
HookManager.UnHookAll();
//Call the original function
Thread.Sleep(millisecondsTimeout);
//Restore the hook
HookManager.HookAll();
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ThreadSleepInt(), new object[] { millisecondsTimeout }, null);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void SleepHookTimeSpan(TimeSpan timeout)
{
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//If sleep is to be skipped, the function is never called
if (Config.SleepSkip == false)
{
//Disable the placed hook
HookManager.UnHookAll();
//Call the original function
Thread.Sleep(timeout);
//Restore the hook
HookManager.HookAll();
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(1, OriginalManagedFunctions.ThreadSleepTimeSpan(), new object[] { timeout }, null);
}
}
}
}
================================================
FILE: DotDumper/HookHandlers/Type/TypeHooks.cs
================================================
using System;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using DotDumper.Helpers;
namespace DotDumper.HookHandlers
{
class TypeHooks
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static object InvokeMemberHookStringBindingFlagsBinderObjectObjectArrayCultureInfo(Type type, string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture)
{
//Declare the local variable to store the object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Sets the title for the log
string functionName = "Type.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture)";
//Process the given data via the helper class
TypeHooksHelper.InvokeMemberHandler(functionName, type, name, invokeAttr, binder, target, args, culture);
}
//Start the timer to induce the race condition
RaceConditionHandler.StartTimer("InvokeMemberHookStringBindingFlagsBinderObjectObjectArrayCultureInfo");
//Call the original function
result = type.InvokeMember(name, invokeAttr, binder, target, args, culture);
//Return the process object to the caller
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static object InvokeMemberHookStringBindingFlagsBinderObjectObjectArray(Type type, string name, BindingFlags invokeAttr, Binder binder, object target, object[] args)
{
//Declare the local variable to store the object in
object result;
//Enable the thread safe lock, as a launched program can be multi-threaded
lock (GenericHookHelper.SyncLock)
{
//Sets the title for the log
string functionName = "Type.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args)";
//Process the given data via the helper class
TypeHooksHelper.InvokeMemberHandler(functionName, type, name, invokeAttr, binder, target, args, null);
}
//Start the timer to induce the race condition
RaceConditionHandler.StartTimer("InvokeMemberHookStringBindingFlagsBinderObjectObjectArray");
//Call the original function
result = type.InvokeMember(name, invokeAttr, binder, target, args);
//Return the process object to the caller
return result;
}
}
}
================================================
FILE: DotDumper/HookHandlers/Type/TypeHooksHelper.cs
================================================
using System;
using System.Globalization;
using System.Reflection;
using DotDumper.Helpers;
using DotDumper.Hooks;
using DotDumper.Models;
namespace DotDumper.HookHandlers
{
class TypeHooksHelper
{
public static void InvokeMemberHandler(string functionName, Type type, string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture)
{
MethodInfo methodInfo = GetMethodInfo(type, name, args);
LogEntry entry = null;
if (methodInfo == null)
{
string fullName = type.FullName + "." + name;
if (culture == null)
{
methodInfo = OriginalManagedFunctions.TypeInvokeMemberStringBindingFlagsBinderObjectObjectArray();
}
else
{
methodInfo = OriginalManagedFunctions.TypeInvokeMemberStringBindingFlagsBinderObjectObjectArrayCultureInfo();
}
}
else
{
entry = LogEntryHelper.Create(2, methodInfo, args, null);
}
//Write the aggregated data to the log and the console
GenericHookHelper._Logger.Log(entry, false, true);
}
private static MethodInfo GetMethodInfo(Type type, string name, object[] args)
{
MethodInfo method = null;
foreach (MethodInfo methodInfo in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
{
if (methodInfo.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
int argsLength = -1;
if (args == null)
{
argsLength = 0;
}
else
{
argsLength = args.Length;
}
if (parameterInfos.Length == argsLength)
{
bool match = true;
if (argsLength > 0)
{
for (int i = 0; i < args.Length; i++)
{
if (parameterInfos[i].ParameterType != args[i].GetType())
{
match = false;
}
}
}
if (match)
{
method = methodInfo;
return method;
}
}
}
}
return method;
}
}
}
================================================
FILE: DotDumper/Hooks/Hook.cs
================================================
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using DotDumper.Helpers;
using DotDumper.Models;
namespace DotDumper.Hooks
{
///
/// The original hook code has been taken from a forum post of the first of May 2017 by Michael 'donrevan' Pekar on UnknownCheats . The code is also available in this GitHub Gist. The code is licensed under the MIT license. Changes have been made by Max 'Libra' Kersten based on the original code in the linked posts.
///
class Hook
{
///
/// This summary is taken from MSDN . Changes the protection on a region of committed pages in the virtual address space of the calling process.
///
/// The address of the starting page of the region of pages whose access protection attributes are to be changed. All pages in the specified region must be within the same reserved region allocated when calling the VirtualAlloc or VirtualAllocEx function using MEM_RESERVE. The pages cannot span adjacent reserved regions that were allocated by separate calls to VirtualAlloc or VirtualAllocEx using MEM_RESERVE.
/// The size of the region whose access protection attributes are to be changed, in bytes. The region of affected pages includes all pages containing one or more bytes in the range from the lpAddress parameter to (lpAddress+dwSize). This means that a 2-byte range straddling a page boundary causes the protection attributes of both pages to be changed.
/// The memory protection option. This parameter can be one of the memory protection constants . For mapped views, this value must be compatible with the access protection specified when the view was mapped(see MapViewOfFile, MapViewOfFileEx, and MapViewOfFileExNuma).
/// A pointer to a variable that receives the previous access protection value of the first page in the specified region of pages. If this parameter is NULL or does not point to a valid variable, the function fails.
/// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool VirtualProtect(IntPtr address, uint size, uint newProtect, out uint oldProtect);
///
/// A constant to resemble the RWX memory protection constant
///
private const int PAGE_READ_WRITE_EXECUTE = 0x40;
///
/// The amount of bytes that the jump to the hook requires on the x86 architecture
///
private const uint HOOK_SIZE_X86 = 7;
///
/// The amount of bytes that the jump to the hook requires on the x86_64 architecture
///
private const uint HOOK_SIZE_X64 = 12;
///
/// The bytes of the original method that are overwritten with the hook jump
///
private byte[] originalBytes;
///
/// The original method that is hooked
///
public string OriginalMethod { get; private set; }
///
/// The method which is called instead of the original method
///
public string HookMethod { get; private set; }
///
/// The method which is called instead of the original MethodInfo's name
///
public string CompactHookMethod { get; private set; }
///
/// The pointer to the original method
///
private IntPtr OriginalMethodPointer { get; set; }
///
/// The pointer to the hook
///
private IntPtr HookMethodPointer { get; set; }
///
/// Creates a hook object, which requires two non-null MethodInfo objects. The hook is not set upon the creation of this object. To set and remove a hook, use the SetHook and UnHook methods in this class respectively.
///
/// The original method, which is to be replaced by the hookMethod
/// The hook to replace the originalMethod
public Hook(MethodInfo originalMethod, MethodInfo hookMethod)
{
//Checks if either of the arguments are null, throwing an error if one or more conditions are true
if (originalMethod == null || hookMethod == null)
{
throw new ArgumentException("Both the original and hook need to be valid methods");
}
//Sets the original bytes variable to null, meaning the original method is not hooked
originalBytes = null;
//Prepares the method for execution within a constrained execution region
RuntimeHelpers.PrepareMethod(originalMethod.MethodHandle);
RuntimeHelpers.PrepareMethod(hookMethod.MethodHandle);
//Sets the variables in the class for later use
OriginalMethod = Serialise.Method(originalMethod);
OriginalMethodPointer = originalMethod.MethodHandle.GetFunctionPointer();
HookMethod = Serialise.Method(hookMethod);
HookMethodPointer = hookMethod.MethodHandle.GetFunctionPointer();
CompactHookMethod = hookMethod.Name;
}
///
/// Creates a hook object, which requires two non-null UnmanagedMethodInfo objects. The hook is not set upon the creation of this object. To set and remove a hook, use the SetHook and UnHook methods in this class respectively.
///
/// The original method, which is to be replaced by the hookMethod
/// The hook to replace the originalMethod
public Hook(UnmanagedMethodInfo originalMethod, UnmanagedMethodInfo hookMethod)
{
//Checks if either of the arguments are null, throwing an error if one or more conditions are true
if (originalMethod == null || hookMethod == null)
{
throw new ArgumentException("Some provided hook arguments are invalid!");
}
//Sets the original bytes variable to null, meaning the original method is not hooked
originalBytes = null;
//Sets the variables in the class for later use
OriginalMethod = originalMethod.FullMethodName;
OriginalMethodPointer = originalMethod.Pointer;
HookMethod = hookMethod.FullMethodName;
HookMethodPointer = hookMethod.Pointer;
CompactHookMethod = hookMethod.MethodName;
}
///
/// Creates a hook object, which requires a non-null UnmanagedMethodInfo object and a non-null MethodInfo object. The hook is not set upon the creation of this object. To set and remove a hook, use the SetHook and UnHook methods in this class respectively.
///
/// The original method, which is to be replaced by the hookMethod
/// The hook to replace the originalMethod
public Hook(UnmanagedMethodInfo originalMethod, MethodInfo hookMethod)
{
//Checks if either of the arguments are null, throwing an error if one or more conditions are true
if (originalMethod == null || hookMethod == null)
{
throw new ArgumentException("Some provided hook arguments are invalid!");
}
//Sets the original bytes variable to null, meaning the original method is not hooked
originalBytes = null;
//Prepares the method for execution within a constrained execution region
RuntimeHelpers.PrepareMethod(hookMethod.MethodHandle);
//Sets the variables in the class for later use
OriginalMethod = originalMethod.FullMethodName;
OriginalMethodPointer = originalMethod.Pointer;
HookMethod = Serialise.Method(hookMethod);
HookMethodPointer = hookMethod.MethodHandle.GetFunctionPointer();
CompactHookMethod = hookMethod.Name;
}
///
/// Creates a hook object, which requires a non-null MethodInfo object and a non-null UnmanagedMethodInfo object. The hook is not set upon the creation of this object. To set and remove a hook, use the SetHook and UnHook methods in this class respectively.
///
/// The original method, which is to be replaced by the hookMethod
/// The hook to replace the originalMethod
public Hook(MethodInfo originalMethod, UnmanagedMethodInfo hookMethod)
{
//Checks if either of the arguments are null, throwing an error if one or more conditions are true
if (originalMethod == null || hookMethod == null)
{
throw new ArgumentException("Some provided hook arguments are invalid!");
}
//Sets the original bytes variable to null, meaning the original method is not hooked
originalBytes = null;
//Prepares the method for execution within a constrained execution region
RuntimeHelpers.PrepareMethod(originalMethod.MethodHandle);
//Sets the variables in the class for later use
OriginalMethod = Serialise.Method(originalMethod);
OriginalMethodPointer = originalMethod.MethodHandle.GetFunctionPointer();
HookMethod = hookMethod.FullMethodName;
HookMethodPointer = hookMethod.Pointer;
CompactHookMethod = hookMethod.MethodName;
}
///
/// Sets the detour for the original method, redirecting it to the previously provided hook. If the original method is not hooked, this method simply returns.
///
public void Enable()
{
/**
* The overwritten instructions of the original method are saved in a byte array, so they can be restored later on.
* Upon the creation of this object, and upon unhooking, this byte array is set to null. As such, any case where
* this byte array is not null, is a case where the hook is already in-place. To avoid overwriting the saved data
* with a hooked version, this method returns early.
*/
if (originalBytes != null)
{
return;
}
//Declare the variable that is used to store the previous memory protection value in, as returned by the Interop VirtualProtect call, as the memory segment needs to be writable to write the hook
uint oldProt;
//Declare the variable that is used to store the size of the hook in
uint hookSize;
//Depending on the architecture, the hook size differs
if (IntPtr.Size == 8)
{
hookSize = HOOK_SIZE_X64;
}
else
{
hookSize = HOOK_SIZE_X86;
}
//Initialise the byte array to store the original data in using the architeture specific size
originalBytes = new byte[hookSize];
/**
* Ensure that the hook can be writen to the start of the original function in memory, by making the area from the start of the original method
* plus the size of the hook executable, readable, and writable
*/
VirtualProtect(OriginalMethodPointer, hookSize, PAGE_READ_WRITE_EXECUTE, out oldProt);
//Starts the unsafe code block where the hook is set
unsafe
{
//Declares a byte pointer based on the original method
byte* ptr = (byte*)OriginalMethodPointer;
/**
* Copies the original bytes into the byte array in this class. The data in this array is used to restore
* the overwritten memory upon unhooking
*/
for (int i = 0; i < hookSize; ++i)
{
originalBytes[i] = ptr[i];
}
/**
* Depending on the architecture, the assembly instructions that need to be written to force the jump to the hook differ.
* The location of the hook is writting into the accumulating register (EAX on x86, RAX on x86_64), after which an
* unconditional jump to that location is taken. When the original function is called, the hook is called via the jump.
* The hook itself can perform the required and desired actions, after which it simply returns, which transfers the
* control back to the caller.
*/
if (IntPtr.Size == 8)
{
/**
* Writes the following x86_64 assembly instructions at the start of the original function:
* movabs rax, addr
* jmp rax
*/
*(ptr) = 0x48;
*(ptr + 1) = 0xb8;
*(IntPtr*)(ptr + 2) = HookMethodPointer;
*(ptr + 10) = 0xff;
*(ptr + 11) = 0xe0;
}
else
{
/**
* Writes the following x86 assembly instructions at the start of the original function:
* mov eax, addr
* jmp eax
*/
*(ptr) = 0xb8;
*(IntPtr*)(ptr + 1) = HookMethodPointer;
*(ptr + 5) = 0xff;
*(ptr + 6) = 0xe0;
}
}
//Restores the memory permissions for the memory segment to the original value
VirtualProtect(OriginalMethodPointer, hookSize, oldProt, out oldProt);
}
///
/// Unhooks the hook of the original method, allowing calls of the original method to work as usual. If the original method has not been hooked, this call simply returns.
///
public void Disable()
{
/**
* The overwritten instructions of the original method are saved in a byte array, so they can be restored later on.
* Upon the creation of this object, and upon unhooking, this byte array is set to null. As such, any case where
* this byte array is null, is a case where the hook is not in-place. If no hook is set, it cannot be removed either.
* Therefore, this method simply returns if it is called without having a hook in-place.
*/
if (originalBytes == null)
{
return;
}
//Declare the variable that is used to store the previous memory protection value in, as returned by the Interop VirtualProtect call, as the memory segment needs to be writable to write the hook
uint oldProt;
//The amount of the original bytes
uint codeSize = (uint)originalBytes.Length;
/**
* Ensure that the hook can be writen to the start of the original function in memory, by making the area from the start of the original method
* plus the size of the hook executable, readable, and writable
*/
VirtualProtect(OriginalMethodPointer, codeSize, PAGE_READ_WRITE_EXECUTE, out oldProt);
//Starts the unsafe code block where the hook is removed
unsafe
{
//Declares a byte pointer based on the original method
byte* ptr = (byte*)OriginalMethodPointer;
/**
* Copies the original bytes from the byte array to the original method, on their original place, thus removing the hook
*/
for (var i = 0; i < codeSize; ++i)
{
ptr[i] = originalBytes[i];
}
}
//Restores the memory permissions for the memory segment to the original value
VirtualProtect(OriginalMethodPointer, codeSize, oldProt, out oldProt);
//The function has been unhooked, meaning the original bytes need to be nulled again, to avoid a faulty (un)hook function to continue when called in the wrong order
originalBytes = null;
}
///
/// Compares the given method with this instance's hook, based on a string representation of the function's signature, ignoring casing
///
/// The method to compare the hook with
/// True if the two methods are equal in , false if not
public bool CompareHook(MethodInfo method)
{
return CompareHook(Serialise.Method(method));
}
///
/// Compares the given method with this instance's hook, based on a string representation of the function's signature, ignoring casing
///
/// The method to compare the hook with
/// True if the two methods are equal in , false if not
public bool CompareHook(string method)
{
return method.Equals(HookMethod, StringComparison.CurrentCultureIgnoreCase);
}
///
/// Compares the given method with this instance's original method, based on a string representation of the function's signature, ignoring casing
///
/// The method to compare the original method with
/// True if the two methods are equal, false if not
public bool CompareOriginal(MethodInfo method)
{
return CompareOriginal(Serialise.Method(method));
}
///
/// Compares the given method with this instance's original method, based on a string representation of the function's signature, ignoring casing
///
/// The method to compare the original method with
/// True if the two methods are equal, false if not
public bool CompareOriginal(string method)
{
return method.Equals(OriginalMethod, StringComparison.CurrentCultureIgnoreCase);
}
}
}
================================================
FILE: DotDumper/Hooks/HookManager.cs
================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using DotDumper.HookHandlers;
using DotDumper.Models;
namespace DotDumper.Hooks
{
///
/// The HookManager is used to create all hook objects, which are stored in a private static list. Additionally, this class contains methods to set and remove hooks for a given hook, or for all hooks
///
class HookManager
{
///
/// The list where all initialised hooks are stored. Hooks should be added via the AddHook function, rather than directly via the Add function of this list
///
private static List Hooks = new List();
///
/// Adds a hook to the list of hooks, unless the string representation (disregarding the casing) of the original method or the hook is already present in the list. If this is the case, a warning will be printed via the logger.
///
/// The method to hook
/// The hook to execute when the original method is called
private static void AddHook(MethodInfo original, MethodInfo hook)
{
AddHook(new Hook(original, hook));
}
private static void AddHook(UnmanagedMethodInfo original, UnmanagedMethodInfo hook)
{
AddHook(new Hook(original, hook));
}
private static void AddHook(UnmanagedMethodInfo original, MethodInfo hook)
{
AddHook(new Hook(original, hook));
}
private static void AddHook(MethodInfo original, UnmanagedMethodInfo hook)
{
AddHook(new Hook(original, hook));
}
private static void AddHook(Hook hook)
{
bool toAdd = true;
foreach (Hook currentHook in Hooks)
{
if (currentHook.CompareOriginal(hook.OriginalMethod))
{
string message = "A hook for \"" + currentHook.OriginalMethod + "\" is already present in the set hooks!\n" +
"\tThe hook that is already placed is named \"" + currentHook.HookMethod + "\"\n" +
"\tThe hook that was attempted to be added is named \"" + hook.HookMethod + "\"\n" +
"\n";
Console.WriteLine(message);
toAdd = false;
break;
}
if (currentHook.CompareHook(hook.HookMethod))
{
string message = "The hook function \"" + currentHook.HookMethod + "\" is already used in a different hook!\n" +
"\tThe original function that is hooked is named \"" + currentHook.OriginalMethod + "\"\n" +
"\tThe original function that was attempted to be added is named \"" + hook.OriginalMethod + "\"\n" +
"\n";
Console.WriteLine(message);
toAdd = false;
break;
}
}
if (toAdd)
{
Hooks.Add(hook);
}
}
///
/// Initialises all hook objects without setting the hooks. One can select the inclusion of deprecated functions with the first argument, whereas the second argument defines if the set hooks should be logged.
///
public static void Initialise()
{
if (Config.IncludeDeprecatedFunctions)
{
#region Deprecated Assembly hooks
//Deprecated!
AddHook(OriginalManagedFunctions.AssemblyLoadStringEvidence(), GetMethodInfo(typeof(AssemblyHooks), "LoadHookStringEvidence", null));
//Deprecated!
AddHook(OriginalManagedFunctions.AssemblyLoadAssemblyNameEvidence(), GetMethodInfo(typeof(AssemblyHooks), "LoadHookAssemblyNameEvidence", null));
//Deprecated!
AddHook(OriginalManagedFunctions.AssemblyLoadByteArrayByteArrayEvidence(), GetMethodInfo(typeof(AssemblyHooks), "LoadHookByteArrayByteArrayEvidence", null));
//Deprecated!
AddHook(OriginalManagedFunctions.AssemblyLoadFileStringEvidence(), GetMethodInfo(typeof(AssemblyHooks), "LoadFileHookStringEvidence", null));
//Deprecated!
AddHook(OriginalManagedFunctions.AssemblyLoadFromStringEvidence(), GetMethodInfo(typeof(AssemblyHooks), "LoadFromHookStringEvidence", null));
//Deprecated!
AddHook(OriginalManagedFunctions.AssemblyLoadFromStringEvidenceByteArrayAssemblyHashAlgorithm(), GetMethodInfo(typeof(AssemblyHooks), "LoadFromHookStringEvidenceByteArrayAssemblyHashAlgorithm", null));
//Deprecated!
AddHook(OriginalManagedFunctions.AssemblyLoadWithPartialNameString(), GetMethodInfo(typeof(AssemblyHooks), "LoadWithPartialNameHookString", null));
//Deprecated!
AddHook(OriginalManagedFunctions.AssemblyLoadWithPartialNameStringEvidence(), GetMethodInfo(typeof(AssemblyHooks), "LoadWithPartialNameHookStringEvidence", null));
#endregion
#region Deprecated Activator hooks
//Deprecated!
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence", null));
//Deprecated!
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence", null));
//Deprecated!
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceFromStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceFromHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence", null));
//Deprecated!
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceFromAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceFromHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArrayEvidence", null));
#endregion
}
#region Assembly hooks
AddHook(OriginalManagedFunctions.AssemblyGetEntryAssembly(), GetMethodInfo(typeof(AssemblyHooks), "GetEntryAssemblyHook", null));
AddHook(OriginalManagedFunctions.AssemblyGetExecutingAssembly(), GetMethodInfo(typeof(AssemblyHooks), "GetExecutingAssemblyHook", null));
AddHook(OriginalManagedFunctions.AssemblyLoadByteArray(), GetMethodInfo(typeof(AssemblyHooks), "LoadHookByteArray", null));
AddHook(OriginalManagedFunctions.AssemblyLoadAssemblyName(), GetMethodInfo(typeof(AssemblyHooks), "LoadHookAssemblyName", null));
AddHook(OriginalManagedFunctions.AssemblyLoadString(), GetMethodInfo(typeof(AssemblyHooks), "LoadHookString", null));
AddHook(OriginalManagedFunctions.AssemblyLoadByteArrayByteArraySecurityContextSource(), GetMethodInfo(typeof(AssemblyHooks), "LoadHookByteArrayByteArraySecurityContextSource", null));
AddHook(OriginalManagedFunctions.AssemblyLoadByteArrayByteArray(), GetMethodInfo(typeof(AssemblyHooks), "LoadHookByteArrayByteArray", null));
AddHook(OriginalManagedFunctions.AssemblyLoadFileString(), GetMethodInfo(typeof(AssemblyHooks), "LoadFileHookString", null));
AddHook(OriginalManagedFunctions.AssemblyLoadFromString(), GetMethodInfo(typeof(AssemblyHooks), "LoadFromHookString", null));
AddHook(OriginalManagedFunctions.AssemblyLoadFromStringByteArrayAssemblyHashAlgorithm(), GetMethodInfo(typeof(AssemblyHooks), "LoadFromHookStringByteArrayAssemblyHashAlgorithm", null));
AddHook(OriginalManagedFunctions.AssemblyReflectionOnlyLoadString(), GetMethodInfo(typeof(AssemblyHooks), "ReflectionOnlyLoadHookString", null));
AddHook(OriginalManagedFunctions.AssemblyReflectionOnlyLoadByteArray(), GetMethodInfo(typeof(AssemblyHooks), "ReflectionOnlyLoadHookByteArray", null));
AddHook(OriginalManagedFunctions.AssemblyReflectionOnlyLoadFromString(), GetMethodInfo(typeof(AssemblyHooks), "ReflectionOnlyLoadFromHookString", null));
AddHook(OriginalManagedFunctions.AssemblyUnsafeLoadFromString(), GetMethodInfo(typeof(AssemblyHooks), "UnsafeLoadFromHookString", null));
#endregion
#region Convert hooks
AddHook(OriginalManagedFunctions.ConvertFromBase64StringString(), GetMethodInfo(typeof(ConvertHooks), "FromBase64StringString", null));
AddHook(OriginalManagedFunctions.ConvertFromBase64CharArrayCharArrayIntInt(), GetMethodInfo(typeof(ConvertHooks), "FromBase64CharArrayCharyArrayIntInt", null));
#endregion
#region Process hooks
AddHook(OriginalManagedFunctions.ProcessGetCurrentProcess(), GetMethodInfo(typeof(ProcessHooks), "GetCurrentProcessHook", null));
AddHook(OriginalManagedFunctions.ProcessGetProcessByIdIntString(), GetMethodInfo(typeof(ProcessHooks), "GetProcessByIdHookIntString", null));
AddHook(OriginalManagedFunctions.ProcessGetProcessByIdInt(), GetMethodInfo(typeof(ProcessHooks), "GetProcessByIdHookInt", null));
AddHook(OriginalManagedFunctions.ProcessGetProcesses(), GetMethodInfo(typeof(ProcessHooks), "GetProcessesHook", null));
AddHook(OriginalManagedFunctions.ProcessGetProcessesString(), GetMethodInfo(typeof(ProcessHooks), "GetProcessesHookString", null));
AddHook(OriginalManagedFunctions.ProcessGetProcessesByNameString(), GetMethodInfo(typeof(ProcessHooks), "GetProcessesByNameHookString", null));
AddHook(OriginalManagedFunctions.ProcessGetProcessesByNameStringString(), GetMethodInfo(typeof(ProcessHooks), "GetProcessesByNameHookStringString", null));
AddHook(OriginalManagedFunctions.ProcessStartStringString(), GetMethodInfo(typeof(ProcessHooks), "ProcessStartHookStringString", null));
AddHook(OriginalManagedFunctions.ProcessStartProcessStartInfo(), GetMethodInfo(typeof(ProcessHooks), "ProcessStartHookProcessStartInfo", null));
AddHook(OriginalManagedFunctions.ProcessStartString(), GetMethodInfo(typeof(ProcessHooks), "ProcessStartHookString", null));
AddHook(OriginalManagedFunctions.ProcessStartStringStringStringSecureStringString(), GetMethodInfo(typeof(ProcessHooks), "ProcessStartHookStringStringStringSecureStringString", null));
AddHook(OriginalManagedFunctions.ProcessStartStringStringSecureStringString(), GetMethodInfo(typeof(ProcessHooks), "ProcessStartHookStringStringSecureStringString", null));
#endregion
#region File hooks
AddHook(OriginalManagedFunctions.FileAppendAllLinesStringIenumerableString(), GetMethodInfo(typeof(FileHooks), "AppendAllLinesHookStringIenumerableString", null));
AddHook(OriginalManagedFunctions.FileAppendAllLinesStringIenumerableStringEncoding(), GetMethodInfo(typeof(FileHooks), "AppendAllLinesHookStringIenumerableStringEncoding", null));
AddHook(OriginalManagedFunctions.FileAppendAllTextStringStringEncoding(), GetMethodInfo(typeof(FileHooks), "AppendAllTextHookStringStringEncoding", null));
AddHook(OriginalManagedFunctions.FileAppendAllTextStringString(), GetMethodInfo(typeof(FileHooks), "AppendAllTextHookStringString", null));
AddHook(OriginalManagedFunctions.FileAppendTextString(), GetMethodInfo(typeof(FileHooks), "AppendTextHookString", null));
AddHook(OriginalManagedFunctions.FileCopyStringString(), GetMethodInfo(typeof(FileHooks), "CopyHookStringString", null));
AddHook(OriginalManagedFunctions.FileCopyStringStringBoolean(), GetMethodInfo(typeof(FileHooks), "CopyHookStringStringBoolean", null));
AddHook(OriginalManagedFunctions.FileCreateString(), GetMethodInfo(typeof(FileHooks), "CreateHookString", null));
AddHook(OriginalManagedFunctions.FileCreateStringInt(), GetMethodInfo(typeof(FileHooks), "CreateHookStringInt", null));
AddHook(OriginalManagedFunctions.FileCreateStringIntFileOptions(), GetMethodInfo(typeof(FileHooks), "CreateHookStringIntFileOptions", null));
AddHook(OriginalManagedFunctions.FileCreateStringIntFileOptionsFileSecurity(), GetMethodInfo(typeof(FileHooks), "CreateHookStringIntFileOptionsFileSecurity", null));
AddHook(OriginalManagedFunctions.FileCreateTextString(), GetMethodInfo(typeof(FileHooks), "CreateTextHookString", null));
AddHook(OriginalManagedFunctions.FileDecryptString(), GetMethodInfo(typeof(FileHooks), "DecryptHookString", null));
AddHook(OriginalManagedFunctions.FileDeleteString(), GetMethodInfo(typeof(FileHooks), "DeleteHookString", null));
AddHook(OriginalManagedFunctions.FileEncryptString(), GetMethodInfo(typeof(FileHooks), "EncryptHookString", null));
AddHook(OriginalManagedFunctions.FileExiststString(), GetMethodInfo(typeof(FileHooks), "ExiststHookString", null));
AddHook(OriginalManagedFunctions.FileMoveStringString(), GetMethodInfo(typeof(FileHooks), "MoveHookStringString", null));
AddHook(OriginalManagedFunctions.FileOpenStringFileModeFileAccessFileShare(), GetMethodInfo(typeof(FileHooks), "OpenHookStringFileModeFileAccessFileShare", null));
AddHook(OriginalManagedFunctions.FileOpenStringFileModeFileAccess(), GetMethodInfo(typeof(FileHooks), "OpenHookStringFileModeFileAccess", null));
AddHook(OriginalManagedFunctions.FileOpenStringFileMode(), GetMethodInfo(typeof(FileHooks), "OpenHookStringFileMode", null));
AddHook(OriginalManagedFunctions.FileOpenTextString(), GetMethodInfo(typeof(FileHooks), "OpenTextHookString", null));
AddHook(OriginalManagedFunctions.FileOpenWriteString(), GetMethodInfo(typeof(FileHooks), "OpenWriteHookString", null));
AddHook(OriginalManagedFunctions.FileReadAllLinesString(), GetMethodInfo(typeof(FileHooks), "ReadAllLinesHookString", null));
AddHook(OriginalManagedFunctions.FileReadAllLinesStringEncoding(), GetMethodInfo(typeof(FileHooks), "ReadAllLinesHookStringEncoding", null));
AddHook(OriginalManagedFunctions.FileReadAllTextStringEncoding(), GetMethodInfo(typeof(FileHooks), "ReadAllTextHookStringEncoding", null));
AddHook(OriginalManagedFunctions.FileReadAllTextString(), GetMethodInfo(typeof(FileHooks), "ReadAllTextHookString", null));
AddHook(OriginalManagedFunctions.FileReadLinesString(), GetMethodInfo(typeof(FileHooks), "ReadLinesHookString", null));
AddHook(OriginalManagedFunctions.FileReadLinesStringEncoding(), GetMethodInfo(typeof(FileHooks), "ReadLinesHookStringEncoding", null));
AddHook(OriginalManagedFunctions.FileReplaceStringStringString(), GetMethodInfo(typeof(FileHooks), "ReplaceHookStringStringString", null));
AddHook(OriginalManagedFunctions.FileReplaceStringStringStringBoolean(), GetMethodInfo(typeof(FileHooks), "ReplaceHookStringStringStringBoolean", null));
AddHook(OriginalManagedFunctions.FileSetAccessControlStringFileSecurity(), GetMethodInfo(typeof(FileHooks), "SetAccessControlHookStringFileSecurity", null));
AddHook(OriginalManagedFunctions.FileSetAttributesStringFileAttributes(), GetMethodInfo(typeof(FileHooks), "SetAttributesHookStringFileAttributes", null));
AddHook(OriginalManagedFunctions.FileWriteAllBytesStringByteArray(), GetMethodInfo(typeof(FileHooks), "WriteAllBytesHookStringByteArray", null));
AddHook(OriginalManagedFunctions.FileWriteAllLinesStringStringArray(), GetMethodInfo(typeof(FileHooks), "WriteAllLinesHookStringStringArray", null));
AddHook(OriginalManagedFunctions.FileWriteAllLinesStringStringArrayEncoding(), GetMethodInfo(typeof(FileHooks), "WriteAllLinesHookStringStringArrayEncoding", null));
AddHook(OriginalManagedFunctions.FileWriteAllLinesStringIenumerableString(), GetMethodInfo(typeof(FileHooks), "WriteAllLinesHookStringIenumerableString", null));
AddHook(OriginalManagedFunctions.FileWriteAllLinesStringIenumerableStringEncoding(), GetMethodInfo(typeof(FileHooks), "WriteAllLinesHookStringIenumerableStringEncoding", null));
AddHook(OriginalManagedFunctions.FileWriteAllTextStringString(), GetMethodInfo(typeof(FileHooks), "WriteAllTextHookStringString", null));
AddHook(OriginalManagedFunctions.FileWriteAllTextStringStringEncoding(), GetMethodInfo(typeof(FileHooks), "WriteAllTextHookStringStringEncoding", null));
AddHook(OriginalManagedFunctions.FileReadAllBytesString(), GetMethodInfo(typeof(FileHooks), "ReadAllBytesHookString", null));
#endregion
#region Path hooks
AddHook(OriginalManagedFunctions.PathChangeExtensionStringString(), GetMethodInfo(typeof(PathHooks), "ChangeExtensionHookStringString", null));
AddHook(OriginalManagedFunctions.PathCombineStringString(), GetMethodInfo(typeof(PathHooks), "CombineHookStringString", null));
AddHook(OriginalManagedFunctions.PathCombineStringStringString(), GetMethodInfo(typeof(PathHooks), "CombineHookStringStringString", null));
AddHook(OriginalManagedFunctions.PathCombineStringStringStringString(), GetMethodInfo(typeof(PathHooks), "CombineHookStringStringStringString", null));
AddHook(OriginalManagedFunctions.PathCombineStringArray(), GetMethodInfo(typeof(PathHooks), "CombineHookStringArray", null));
AddHook(OriginalManagedFunctions.PathGetDirectoryNameString(), GetMethodInfo(typeof(PathHooks), "GetDirectoryNameHookString", null));
AddHook(OriginalManagedFunctions.PathGetExtensionString(), GetMethodInfo(typeof(PathHooks), "GetExtensionHookString", null));
AddHook(OriginalManagedFunctions.PathGetFileNameString(), GetMethodInfo(typeof(PathHooks), "GetFileNameHookString", null));
AddHook(OriginalManagedFunctions.PathGetFileNameWithoutExtensionString(), GetMethodInfo(typeof(PathHooks), "GetFileNameWithoutExtensionHookString", null));
AddHook(OriginalManagedFunctions.PathGetFullPathString(), GetMethodInfo(typeof(PathHooks), "GetFullPathHookString", null));
AddHook(OriginalManagedFunctions.PathGetPathRootString(), GetMethodInfo(typeof(PathHooks), "GetPathRootHookString", null));
AddHook(OriginalManagedFunctions.PathGetRandomFileName(), GetMethodInfo(typeof(PathHooks), "GetRandomFileNameHook", null));
AddHook(OriginalManagedFunctions.PathGetTempFileName(), GetMethodInfo(typeof(PathHooks), "GetTempFileNameHook", null));
AddHook(OriginalManagedFunctions.PathGetTempPath(), GetMethodInfo(typeof(PathHooks), "GetTempPathHook", null));
#endregion
#region Thread hooks
AddHook(OriginalManagedFunctions.ThreadSleepInt(), GetMethodInfo(typeof(ThreadHooks), "SleepHookInt", null));
AddHook(OriginalManagedFunctions.ThreadSleepTimeSpan(), GetMethodInfo(typeof(ThreadHooks), "SleepHookTimeSpan", null));
#endregion
#region Environment hooks
AddHook(OriginalManagedFunctions.EnvironmentExitInt(), GetMethodInfo(typeof(EnvironmentHooks), "ExitHookInt", null));
AddHook(OriginalManagedFunctions.EnvironmentExpandEnvironmentVariablesString(), GetMethodInfo(typeof(EnvironmentHooks), "ExpandEnvironmentVariablesHookString", null));
AddHook(OriginalManagedFunctions.EnvironmentFailFastStringException(), GetMethodInfo(typeof(EnvironmentHooks), "FailFastHookStringException", null));
AddHook(OriginalManagedFunctions.EnvironmentFailFastString(), GetMethodInfo(typeof(EnvironmentHooks), "FailFastHookString", null));
AddHook(OriginalManagedFunctions.EnvironmentGetCommandLineArgs(), GetMethodInfo(typeof(EnvironmentHooks), "GetCommandLineArgsHook", null));
AddHook(OriginalManagedFunctions.EnvironmentGetEnvironmentVariableStringEnvironmentVariableTarget(), GetMethodInfo(typeof(EnvironmentHooks), "GetEnvironmentVariableHookStringEnvironmentVariableTarget", null));
AddHook(OriginalManagedFunctions.EnvironmentGetEnvironmentVariableString(), GetMethodInfo(typeof(EnvironmentHooks), "GetEnvironmentVariablesHookString", null));
AddHook(OriginalManagedFunctions.EnvironmentGetEnvironmentVariablesEnvironmentVariableTarget(), GetMethodInfo(typeof(EnvironmentHooks), "GetEnvironmentVariablesHookEnvironmentVariableTarget", null));
AddHook(OriginalManagedFunctions.EnvironmentGetEnvironmentVariables(), GetMethodInfo(typeof(EnvironmentHooks), "GetEnvironmentVariablesHook", null));
AddHook(OriginalManagedFunctions.EnvironmentGetFolderPathSpecialFolderSpecialFolderOption(), GetMethodInfo(typeof(EnvironmentHooks), "GetFolderPathHookSpecialFolderSpecialFolderOption", null));
AddHook(OriginalManagedFunctions.EnvironmentGetFolderPathSpecialFolder(), GetMethodInfo(typeof(EnvironmentHooks), "GetFolderPathHookSpecialFolder", null));
AddHook(OriginalManagedFunctions.EnvironmentGetLogicalDrives(), GetMethodInfo(typeof(EnvironmentHooks), "GetLogicalDrivesHook", null));
AddHook(OriginalManagedFunctions.EnvironmentSetEnvironmentVariableStringStringEnvironmentVariableTarget(), GetMethodInfo(typeof(EnvironmentHooks), "SetEnvironmentVariableHookStringStringEnvironmentVariableTarget", null));
AddHook(OriginalManagedFunctions.EnvironmentSetEnvironmentVariableStringString(), GetMethodInfo(typeof(EnvironmentHooks), "SetEnvironmentVariableHookStringString", null));
AddHook(OriginalManagedFunctions.EnvironmentGetResourceFromDefaultString(), GetMethodInfo(typeof(EnvironmentHooks), "GetResourceFromDefaultHookString", null));
#endregion
#region ResourceManager hooks
AddHook(OriginalManagedFunctions.ResourceManagerGetObjectString(), GetMethodInfo(typeof(ResourceManagerHooks), "GetObjectHookString", null));
AddHook(OriginalManagedFunctions.ResourceManagerGetObjectStringCultureInfo(), GetMethodInfo(typeof(ResourceManagerHooks), "GetObjectHookStringCultureInfo", null));
AddHook(OriginalManagedFunctions.ResourceManagerGetStringString(), GetMethodInfo(typeof(ResourceManagerHooks), "GetStringHookString", null));
AddHook(OriginalManagedFunctions.ResourceManagerGetStringStringCultureInfo(), GetMethodInfo(typeof(ResourceManagerHooks), "GetStringHookStringCultureInfo", null));
AddHook(OriginalManagedFunctions.ResourceManagerGetStreamString(), GetMethodInfo(typeof(ResourceManagerHooks), "GetStreamHookString", null));
AddHook(OriginalManagedFunctions.ResourceManagerGetStreamStringCultureInfo(), GetMethodInfo(typeof(ResourceManagerHooks), "GetStreamHookStringCultureInfo", null));
#endregion
#region Console hooks
AddHook(OriginalManagedFunctions.ConsoleWriteString(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookString", null));
AddHook(OriginalManagedFunctions.ConsoleWriteObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteUlong(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookUlong", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLong(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookLong", null));
AddHook(OriginalManagedFunctions.ConsoleWriteStringObjectObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookStringObjectObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteInt(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookInt", null));
AddHook(OriginalManagedFunctions.ConsoleWriteStringObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookStringObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteUint(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookUint", null));
AddHook(OriginalManagedFunctions.ConsoleWriteStringObjectObjectObjectObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookStringObjectObjectObjectObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteStringObjectArray(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookStringObjectArray", null));
AddHook(OriginalManagedFunctions.ConsoleWriteBool(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookBool", null));
AddHook(OriginalManagedFunctions.ConsoleWriteChar(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookChar", null));
AddHook(OriginalManagedFunctions.ConsoleWriteCharArray(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookCharArray", null));
AddHook(OriginalManagedFunctions.ConsoleWriteCharArrayIntInt(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookCharArrayIntInt", null));
AddHook(OriginalManagedFunctions.ConsoleWriteStringObjectObjectObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookStringObjectObjectObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteDecimal(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookDecimal", null));
AddHook(OriginalManagedFunctions.ConsoleWriteFloat(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookFloat", null));
AddHook(OriginalManagedFunctions.ConsoleWriteDouble(), GetMethodInfo(typeof(ConsoleHooks), "WriteHookDouble", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineString(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookString", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineUlong(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookUlong", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineLong(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookLong", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineStringObjectObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookStringObjectObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineInt(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookInt", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineStringObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookStringObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineUint(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookUint", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineStringObjectObjectObjectObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookStringObjectObjectObjectObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineStringObjectArray(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookStringObjectArray", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineBool(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookBool", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineChar(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookChar", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineCharArray(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookCharArray", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineCharArrayIntInt(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookCharArrayIntInt", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineStringObjectObjectObject(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookStringObjectObjectObject", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineDecimal(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookDecimal", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineFloat(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookFloat", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLineDouble(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHookDouble", null));
AddHook(OriginalManagedFunctions.ConsoleWriteLine(), GetMethodInfo(typeof(ConsoleHooks), "WriteLineHook", null));
#endregion
#region MethodBase hooks
AddHook(OriginalManagedFunctions.MethodBaseInvokeObjectObjectArray(), GetMethodInfo(typeof(MethodBaseHooks), "InvokeHookObjectObjectArray", null));
//Cannot hook abstract method
//AddHook(OriginalFunctions.MethodBaseInvokeObjectBindingFlagsBinderObjectArrayCultureInfo(), GetMethodInfo(typeof(MethodBaseHooks), "InvokeHookObjectBindingFlagsBinderObjectArrayCultureInfo", null));
#endregion
#region Type hooks
AddHook(OriginalManagedFunctions.TypeInvokeMemberStringBindingFlagsBinderObjectObjectArray(), GetMethodInfo(typeof(TypeHooks), "InvokeMemberHookStringBindingFlagsBinderObjectObjectArray", null));
AddHook(OriginalManagedFunctions.TypeInvokeMemberStringBindingFlagsBinderObjectObjectArrayCultureInfo(), GetMethodInfo(typeof(TypeHooks), "InvokeMemberHookStringBindingFlagsBinderObjectObjectArrayCultureInfo", null));
#endregion
#region Activator hooks
AddHook(OriginalManagedFunctions.ActivatorCreateComInstanceFromStringStringByteArrayAssemblyHashAlgorithm(), GetMethodInfo(typeof(ActivatorHooks), "CreateComInstanceFromHookStringStringByteArrayAssemblyHashAlgorithm", null));
AddHook(OriginalManagedFunctions.ActivatorCreateComInstanceFromStringString(), GetMethodInfo(typeof(ActivatorHooks), "CreateComInstanceFromHookStringString", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceType(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookType", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceTypeBool(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookTypeBool", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceActivationContext(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookActivationContext", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceTypeObjectArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookTypeObjectArray", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceStringString(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookStringString", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceTypeBindingFlagsBinderObjectArrayCultureInfo(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfo", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookTypeBindingFlagsBinderObjectArrayCultureInfoObjectArray", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceActivationContextStringArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookActivationContextStringArray", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceStringStringObjectArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookStringStringObjectArray", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceAppDomainStringString(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookAppDomainStringString", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceFromAppDomainStringString(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceFromHookAppDomainStringString", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceFromAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceFromHookAppDomainStringStringBooleanBindingFlagsBinderObjectArrayCultureInfoObjectArray", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceFromStringString(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceFromHookStringString", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceFromStringStringObjectArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceFromHookStringStringObjectArray", null));
AddHook(OriginalManagedFunctions.ActivatorCreateInstanceFromStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray(), GetMethodInfo(typeof(ActivatorHooks), "CreateInstanceFromHookStringStringBoolBindingFlagsBinderObjectArrayCultureInfoObjectArray", null));
#endregion
#region kernel32.dll hooks
string hookPath = "DotDumperNative";
if (IntPtr.Size == 4)
{
hookPath += "_x86";
}
else if (IntPtr.Size == 8)
{
hookPath += "_x64";
}
hookPath += ".dll";
//Working hooks
AddHook(OriginalUnmanagedFunctions.Kernel32WriteProcessMemory(), new UnmanagedMethodInfo(hookPath, "WriteProcessMemoryHook", "WriteProcessMemoryHook", null));
AddHook(OriginalUnmanagedFunctions.Kernel32CreateProcessW(), new UnmanagedMethodInfo(hookPath, "CreateProcessWHook", "CreateProcessWHook", null));
AddHook(OriginalUnmanagedFunctions.Kernel32CreateProcessA(), new UnmanagedMethodInfo(hookPath, "CreateProcessAHook", "CreateProcessAHook", null));
AddHook(OriginalUnmanagedFunctions.User32MessageBoxW(), new UnmanagedMethodInfo(hookPath, "MessageBoxW", "MessageBoxWHook", null));
//Download related API calls
#endregion
if (Config.LogHooks)
{
LogHooks();
}
}
///
/// Gets the MethodInfo object from the given type, using the given name (disregarding the casing), and matching the given parameter types (disregarding the casing) and count. Note that only public methods from the given type are iterated!
///
/// The type to find the method in
/// The function name, case insensitive
/// The parameter type(s), insensitive
/// If a match is found, the corresponding MethodInfo object is returned. If no match is found, null is returned
public static MethodInfo GetMethodInfo(Type type, string name, List parameterTypes)
{
//Get all public methods from the given type
MethodInfo[] methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
//Iterate over all methods
foreach (MethodInfo methodInfo in methodInfos)
{
//If the name (disregarding casing) is the same, more checks follow, as the correct overloaded method needs to be selected (if present)
if (methodInfo.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
//If the given list is not null, include a check for the parameter types (and count)
if (parameterTypes != null)
{
//Get the information regarding the parameters of the method
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
//If the amount of parameters is the same, it is a potential match (though not a certain one, as overloads with different types can have the same amount of arguments)
if (parameterInfos.Length == parameterTypes.Count)
{
//A local variable that states if the two functions match
bool isMatching = true;
//Iterate over all the user-provided parameters
for (int i = 0; i < parameterTypes.Count; i++)
{
//Get the type from the parameter at the given index
string parameterInfoType = parameterInfos[i].ParameterType.Name;
//Compare the name (disregarding the casing) of the two parameters
if (parameterInfoType.Equals(parameterTypes[i], StringComparison.InvariantCultureIgnoreCase) == false)
{
//If the parameter types do not match at any point in time, the functions do not match
isMatching = false;
break;
}
}
//If all types matched, the boolean's value remains true
if (isMatching)
{
//Since everything matches, this function matches with the provided information
return methodInfo;
}
}
}
else //If no parameters are provided, the first hit is returned
{
return methodInfo;
}
}
}
//If no match is found, null is returned
return null;
}
///
/// Logs all loaded hooks via the logger object
///
private static void LogHooks()
{
string title = "---------------Logging all " + Hooks.Count + " loaded hooks---------------";
string message = title + "\n";
foreach (Hook hook in Hooks)
{
message += hook.OriginalMethod + "\n";
}
message += "\n";
//Create a nearly empty log entry object with the relevant information
//LogEntry entry = new LogEntry(null, null, null, null, null, null, message, null, null, null, null);
//The creation of a log entry sets all hooks as it obtains the current time, which needs to be un-set
//UnHookAll();
//Write the entry to the log
//GenericHookHelper._Logger.Log(entry, true, false);
Console.WriteLine(message);
}
///
/// Sets all hooks
///
public static void HookAll()
{
foreach (Hook hook in Hooks)
{
hook.Enable();
}
}
///
/// Removes all the hooks
///
public static void UnHookAll()
{
foreach (Hook hook in Hooks)
{
hook.Disable();
}
}
///
/// Sets the hook, based on the given hook name, ignoring the casing
///
/// The name of the hook function (ignoring the return type or parameters)
/// True if the hook is set, false if there is no hook with such a name
public static bool HookByHookName(string hookName)
{
foreach (Hook hook in Hooks)
{
if (hook.CompactHookMethod.Equals(hookName, StringComparison.InvariantCultureIgnoreCase))
{
hook.Enable();
return true;
}
}
return false;
}
///
/// Removes the hook for the given original method, based on the given hook name, ignoring the casing
///
/// The name of the hook function (ignoring the return type or parameters)
/// True if the hook is removed, false if there is no hook with such a name
public static bool UnHookByHookName(string hookName)
{
foreach (Hook hook in Hooks)
{
if (hook.CompactHookMethod.Equals(hookName, StringComparison.InvariantCultureIgnoreCase))
{
hook.Disable();
return true;
}
}
return false;
}
}
}
================================================
FILE: DotDumper/Hooks/InteropFunctions.cs
================================================
using System;
using System.Runtime.InteropServices;
namespace DotDumper.Hooks
{
class InteropFunctions
{
#region Structures
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PROCESS_INFORMATION
{
public IntPtr ProcessHandle;
public IntPtr ThreadHandle;
public uint ProcessId;
public uint ThreadId;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct STARTUP_INFORMATION
{
public uint Size;
public string Reserved1;
public string Desktop;
public string Title;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 36)]
public byte[] Misc;
public IntPtr Reserved2;
public IntPtr StdInput;
public IntPtr StdOutput;
public IntPtr StdError;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SECURITY_ATTRIBUTES
{
uint nLength;
IntPtr lpSecurityDescriptor;
bool bInheritHandle;
}
///
/// The struct definition for the SystemTime struct
///
public struct SystemTime
{
public ushort Year;
public ushort Month;
public ushort DayOfWeek;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Millisecond;
};
#endregion
#region kernel32.dll
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool WriteProcessMemory(IntPtr hProcess, int lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint GetProcessId(IntPtr handle);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr LoadLibrary(string libname);
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
public static extern int VirtualAllocEx(IntPtr handle, int address, int length, int type, int protect);
[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(IntPtr process, int baseAddress, ref int buffer, int bufferSize, ref int bytesRead);
[DllImport("kernel32.dll")]
public static extern bool Wow64SetThreadContext(IntPtr thread, int[] context);
[DllImport("kernel32.dll")]
public static extern bool SetThreadContext(IntPtr thread, int[] context);
[DllImport("kernel32.dll")]
public static extern bool Wow64GetThreadContext(IntPtr thread, int[] context);
[DllImport("kernel32.dll")]
public static extern bool GetThreadContext(IntPtr thread, int[] context);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
public static extern bool CreateProcessA(string applicationName, string commandLine, IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUP_INFORMATION startupInfo, ref PROCESS_INFORMATION processInformation);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern bool CreateProcessW(IntPtr applicationName, IntPtr commandLine, IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles, int creationFlags, IntPtr environment, IntPtr currentDirectory, ref IntPtr startupInfo, ref IntPtr processInformation);
[DllImport("kernel32.dll")]
public static extern int ResumeThread(IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool VirtualProtect(IntPtr address, uint size, uint newProtect, out uint oldProtect);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool VirtualProtectEx(IntPtr hProcess, int lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
///
/// The native import of the SetSystemTime function from kernel32.dll
///
/// A reference to an instance of the SystemTime struct
/// True if set correctly, false if not
[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
public extern static bool SetSystemTime(ref SystemTime sysTime);
#endregion
#region ntdll.dll
[DllImport("ntdll.dll")]
public static extern int NtUnmapViewOfSection(IntPtr process, int baseAddress);
#endregion
#region user32.dll
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBoxW(int hWnd, String text, String caption, uint type);
#endregion
}
}
================================================
FILE: DotDumper/Hooks/OriginalManagedFunctions.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Threading;
namespace DotDumper.Hooks
{
///
/// All methods within this class refer to managed functions. This class contains static functions which obtain the MethodInfo object. This object, for the corresponding function, is used in the hooks of DotDumper, and when logging certain calls.
///
class OriginalManagedFunctions
{
#region Original ResourceManager methods
///
/// Gets the MethodInfo object for ResourceManager.GetObject(string name)
///
///
public static MethodInfo ResourceManagerGetObjectString()
{
Type type = typeof(ResourceManager);
string name = "GetObject";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for ResourceManager.GetObject(string name, CultureInfo cultureInfo)
///
///
public static MethodInfo ResourceManagerGetObjectStringCultureInfo()
{
Type type = typeof(ResourceManager);
string name = "GetObject";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("cultureInfo");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for ResourceManager.GetString(string name)
///
///
public static MethodInfo ResourceManagerGetStringString()
{
Type type = typeof(ResourceManager);
string name = "GetString";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for ResourceManager.GetString(string name, CultureInfo cultureInfo)
///
///
public static MethodInfo ResourceManagerGetStringStringCultureInfo()
{
Type type = typeof(ResourceManager);
string name = "GetString";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("cultureInfo");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for ResourceManager.GetString(string name)
///
///
public static MethodInfo ResourceManagerGetStreamString()
{
Type type = typeof(ResourceManager);
string name = "GetStream";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for ResourceManager.GetString(string name, CultureInfo cultureInfo)
///
///
public static MethodInfo ResourceManagerGetStreamStringCultureInfo()
{
Type type = typeof(ResourceManager);
string name = "GetStream";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("cultureInfo");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
#endregion
#region Original Environment methods
///
/// Gets the MethodInfo object for Environment.Exit(int exitCode)
///
///
public static MethodInfo EnvironmentExitInt()
{
Type type = typeof(Environment);
string name = "Exit";
List parameterTypes = new List();
parameterTypes.Add("int32");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.ExpandEnvironmentVariables(string name)
///
///
public static MethodInfo EnvironmentExpandEnvironmentVariablesString()
{
Type type = typeof(Environment);
string name = "ExpandEnvironmentVariables";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.FailFast(string message, Exception exception)
///
///
public static MethodInfo EnvironmentFailFastStringException()
{
Type type = typeof(Environment);
string name = "FailFast";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("exception");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.FailFast(string message)
///
///
public static MethodInfo EnvironmentFailFastString()
{
Type type = typeof(Environment);
string name = "FailFast";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetCommandLineArgs()
///
///
public static MethodInfo EnvironmentGetCommandLineArgs()
{
Type type = typeof(Environment);
string name = "GetCommandLineArgs";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
///
///
public static MethodInfo EnvironmentGetEnvironmentVariableStringEnvironmentVariableTarget()
{
Type type = typeof(Environment);
string name = "GetEnvironmentVariable";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("EnvironmentVariableTarget");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetEnvironmentVariable(string variable)
///
///
public static MethodInfo EnvironmentGetEnvironmentVariableString()
{
Type type = typeof(Environment);
string name = "GetEnvironmentVariable";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetEnvironmentVariables(EnvironmentVariableTarget target)
///
///
public static MethodInfo EnvironmentGetEnvironmentVariablesEnvironmentVariableTarget()
{
Type type = typeof(Environment);
string name = "GetEnvironmentVariables";
List parameterTypes = new List();
parameterTypes.Add("EnvironmentVariableTarget");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetEnvironmentVariables()
///
///
public static MethodInfo EnvironmentGetEnvironmentVariables()
{
Type type = typeof(Environment);
string name = "GetEnvironmentVariables";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetFolderPath(SpecialFolder folder, SpecialFolderOption option)
///
///
public static MethodInfo EnvironmentGetFolderPathSpecialFolderSpecialFolderOption()
{
Type type = typeof(Environment);
string name = "GetFolderPath";
List parameterTypes = new List();
parameterTypes.Add("SpecialFolder");
parameterTypes.Add("SpecialFolderOption");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetFolderPath(SpecialFolder folder)
///
///
public static MethodInfo EnvironmentGetFolderPathSpecialFolder()
{
Type type = typeof(Environment);
string name = "GetFolderPath";
List parameterTypes = new List();
parameterTypes.Add("SpecialFolder");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetLogicalDrives()
///
///
public static MethodInfo EnvironmentGetLogicalDrives()
{
Type type = typeof(Environment);
string name = "GetLogicalDrives";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
///
///
public static MethodInfo EnvironmentSetEnvironmentVariableStringStringEnvironmentVariableTarget()
{
Type type = typeof(Environment);
string name = "SetEnvironmentVariable";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("EnvironmentVariableTarget");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.SetEnvironmentVariable(string variable, string value)
///
///
public static MethodInfo EnvironmentSetEnvironmentVariableStringString()
{
Type type = typeof(Environment);
string name = "SetEnvironmentVariable";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Environment.GetResourceFromDefault(string key)
///
///
public static MethodInfo EnvironmentGetResourceFromDefaultString()
{
Type type = typeof(Environment);
string name = "GetResourceFromDefault";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
#endregion
#region Original Thread methods
///
/// Gets the MethodInfo object for Thread.Sleep(int millisecondsTimeout)
///
///
public static MethodInfo ThreadSleepInt()
{
Type type = typeof(Thread);
string name = "Sleep";
List parameterTypes = new List();
parameterTypes.Add("int32");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Thread.Sleep(TimeSpan timeout)
///
///
public static MethodInfo ThreadSleepTimeSpan()
{
Type type = typeof(Thread);
string name = "Sleep";
List parameterTypes = new List();
parameterTypes.Add("timespan");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
#endregion
#region Original Path methods
///
/// Gets the MethodInfo object for Path.ChangeExtension(string path, string extension)
///
///
public static MethodInfo PathChangeExtensionStringString()
{
Type type = typeof(Path);
string name = "ChangeExtension";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.Combine(string path1, string path2)
///
///
public static MethodInfo PathCombineStringString()
{
Type type = typeof(Path);
string name = "Combine";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.Combine(string path1, string path2, string path3)
///
///
public static MethodInfo PathCombineStringStringString()
{
Type type = typeof(Path);
string name = "Combine";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.Combine(string path1, string path2, string path3, string path4)
///
///
public static MethodInfo PathCombineStringStringStringString()
{
Type type = typeof(Path);
string name = "Combine";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.Combine(params string[] paths)
///
///
public static MethodInfo PathCombineStringArray()
{
Type type = typeof(Path);
string name = "Combine";
List parameterTypes = new List();
parameterTypes.Add("string[]");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetDirectoryName(string path)
///
///
public static MethodInfo PathGetDirectoryNameString()
{
Type type = typeof(Path);
string name = "GetDirectoryName";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetExtension(string path)
///
///
public static MethodInfo PathGetExtensionString()
{
Type type = typeof(Path);
string name = "GetExtension";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetFileName(string path)
///
///
public static MethodInfo PathGetFileNameString()
{
Type type = typeof(Path);
string name = "GetFileName";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetFileNameWithoutExtension(string path)
///
///
public static MethodInfo PathGetFileNameWithoutExtensionString()
{
Type type = typeof(Path);
string name = "GetFileNameWithoutExtension";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetFullPath(string path)
///
///
public static MethodInfo PathGetFullPathString()
{
Type type = typeof(Path);
string name = "GetFullPath";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetPathRoot(string path)
///
///
public static MethodInfo PathGetPathRootString()
{
Type type = typeof(Path);
string name = "GetPathRoot";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetRandomFileName()
///
///
public static MethodInfo PathGetRandomFileName()
{
Type type = typeof(Path);
string name = "GetRandomFileName";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetTempFileName()
///
///
public static MethodInfo PathGetTempFileName()
{
Type type = typeof(Path);
string name = "GetTempFileName";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Path.GetTempPath()
///
///
public static MethodInfo PathGetTempPath()
{
Type type = typeof(Path);
string name = "GetTempPath";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
#endregion
#region Original File methods
///
/// Gets the MethodInfo object for File.AppendAllLines(string path, IEnumerable contents)
///
///
public static MethodInfo FileAppendAllLinesStringIenumerableString()
{
Type type = typeof(File);
string name = "AppendAllLines";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("IEnumerable`1");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.AppendAllLines(string path, IEnumerable contents, Encoding encoding)
///
///
public static MethodInfo FileAppendAllLinesStringIenumerableStringEncoding()
{
Type type = typeof(File);
string name = "AppendAllLines";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("IEnumerable`1");
parameterTypes.Add("encoding");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.AppendAllText(string path, string contents, Encoding encoding)
///
///
public static MethodInfo FileAppendAllTextStringStringEncoding()
{
Type type = typeof(File);
string name = "AppendAllText";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("encoding");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.AppendAllText(string path, string contents)
///
///
public static MethodInfo FileAppendAllTextStringString()
{
Type type = typeof(File);
string name = "AppendAllText";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.AppendText(string path)
///
///
public static MethodInfo FileAppendTextString()
{
Type type = typeof(File);
string name = "AppendText";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Copy(string sourceFileName, string destFileName)
///
///
public static MethodInfo FileCopyStringString()
{
Type type = typeof(File);
string name = "Copy";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Copy(string sourceFileName, string destFileName, bool overwrite)
///
///
public static MethodInfo FileCopyStringStringBoolean()
{
Type type = typeof(File);
string name = "Copy";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("boolean");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Create(string path)
///
///
public static MethodInfo FileCreateString()
{
Type type = typeof(File);
string name = "Create";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Create(string path, int bufferSize)
///
///
public static MethodInfo FileCreateStringInt()
{
Type type = typeof(File);
string name = "Create";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("int32");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Create(string path, int bufferSize, FileOptions options)
///
///
public static MethodInfo FileCreateStringIntFileOptions()
{
Type type = typeof(File);
string name = "Create";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("int32");
parameterTypes.Add("FileOptions");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity)
///
///
public static MethodInfo FileCreateStringIntFileOptionsFileSecurity()
{
Type type = typeof(File);
string name = "Create";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("int32");
parameterTypes.Add("FileOptions");
parameterTypes.Add("FileSecurity");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.CreateText(string path)
///
///
public static MethodInfo FileCreateTextString()
{
Type type = typeof(File);
string name = "CreateText";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Decrypt(string path)
///
///
public static MethodInfo FileDecryptString()
{
Type type = typeof(File);
string name = "Decrypt";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Delete(string path)
///
///
public static MethodInfo FileDeleteString()
{
Type type = typeof(File);
string name = "Delete";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Encrypt(string path)
///
///
public static MethodInfo FileEncryptString()
{
Type type = typeof(File);
string name = "Encrypt";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Exists(string path)
///
///
public static MethodInfo FileExiststString()
{
Type type = typeof(File);
string name = "Exists";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Move(string sourceFileName, string destFileName)
///
///
public static MethodInfo FileMoveStringString()
{
Type type = typeof(File);
string name = "Move";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Open(string path, FileMode mode, FileAccess access, FileShare share)
///
///
public static MethodInfo FileOpenStringFileModeFileAccessFileShare()
{
Type type = typeof(File);
string name = "Open";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("FileMode");
parameterTypes.Add("FileAccess");
parameterTypes.Add("FileShare");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Open(string path, FileMode mode)
///
///
public static MethodInfo FileOpenStringFileMode()
{
Type type = typeof(File);
string name = "Open";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("FileMode");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Open(string path, FileMode mode, FileAccess access)
///
///
public static MethodInfo FileOpenStringFileModeFileAccess()
{
Type type = typeof(File);
string name = "Open";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("FileMode");
parameterTypes.Add("FileAccess");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.OpenRead(string path)
///
///
public static MethodInfo FileOpenReadString()
{
Type type = typeof(File);
string name = "OpenRead";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.OpenText(string path)
///
///
public static MethodInfo FileOpenTextString()
{
Type type = typeof(File);
string name = "OpenText";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.OpenWrite(string path)
///
///
public static MethodInfo FileOpenWriteString()
{
Type type = typeof(File);
string name = "OpenWrite";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.ReadAllLines(string path, Encoding encoding)
///
///
public static MethodInfo FileReadAllLinesStringEncoding()
{
Type type = typeof(File);
string name = "ReadAllLines";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("encoding");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.ReadAllLines(string path)
///
///
public static MethodInfo FileReadAllLinesString()
{
Type type = typeof(File);
string name = "ReadAllLines";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.ReadAllText(string path)
///
///
public static MethodInfo FileReadAllTextString()
{
Type type = typeof(File);
string name = "ReadAllText";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.ReadAllText(string path, Encoding encoding)
///
///
public static MethodInfo FileReadAllTextStringEncoding()
{
Type type = typeof(File);
string name = "ReadAllText";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("encoding");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.ReadLines(string path, Encoding encoding)
///
///
public static MethodInfo FileReadLinesStringEncoding()
{
Type type = typeof(File);
string name = "ReadLines";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("encoding");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.ReadLines(string path)
///
///
public static MethodInfo FileReadLinesString()
{
Type type = typeof(File);
string name = "ReadLines";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName)
///
///
public static MethodInfo FileReplaceStringStringString()
{
Type type = typeof(File);
string name = "Replace";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors)
///
///
public static MethodInfo FileReplaceStringStringStringBoolean()
{
Type type = typeof(File);
string name = "Replace";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("boolean");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.SetAccessControl(string path, FileSecurity fileSecurity)
///
///
public static MethodInfo FileSetAccessControlStringFileSecurity()
{
Type type = typeof(File);
string name = "SetAccessControl";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("FileSecurity");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.SetAttributes(string path, FileAttributes fileAttributes)
///
///
public static MethodInfo FileSetAttributesStringFileAttributes()
{
Type type = typeof(File);
string name = "SetAttributes";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("FileAttributes");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.WriteAllBytes(string path, byte[] bytes)
///
///
public static MethodInfo FileWriteAllBytesStringByteArray()
{
Type type = typeof(File);
string name = "WriteAllBytes";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("byte[]");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.WriteAllLines(string path, string[] contents)
///
///
public static MethodInfo FileWriteAllLinesStringStringArray()
{
Type type = typeof(File);
string name = "WriteAllLines";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string[]");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.WriteAllLines(string path, string[] contents, Encoding encoding)
///
///
public static MethodInfo FileWriteAllLinesStringStringArrayEncoding()
{
Type type = typeof(File);
string name = "WriteAllLines";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string[]");
parameterTypes.Add("encoding");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.WriteAllLines(string path, IEnumerable contents)
///
///
public static MethodInfo FileWriteAllLinesStringIenumerableString()
{
Type type = typeof(File);
string name = "WriteAllLines";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("ienumerable`1");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.WriteAllLines(string path, IEnumerable contents, Encoding encoding)
///
///
public static MethodInfo FileWriteAllLinesStringIenumerableStringEncoding()
{
Type type = typeof(File);
string name = "WriteAllLines";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("ienumerable`1");
parameterTypes.Add("encoding");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.WriteAllText(string path, string contents)
///
///
public static MethodInfo FileWriteAllTextStringString()
{
Type type = typeof(File);
string name = "WriteAllText";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.WriteAllText(string path, string contents, Encoding encoding)
///
///
public static MethodInfo FileWriteAllTextStringStringEncoding()
{
Type type = typeof(File);
string name = "WriteAllText";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("encoding");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for File.ReadAllBytes(string path)
///
///
public static MethodInfo FileReadAllBytesString()
{
Type type = typeof(File);
string name = "ReadAllBytes";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
#endregion
#region Original Convert methods
///
/// Gets the MethodInfo object for Convert.FromBase64String(string s)
///
///
public static MethodInfo ConvertFromBase64StringString()
{
Type type = typeof(Convert);
string name = "FromBase64String";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Convert.FromBase64CharArray(char[] inArray, int offset, int length)
///
///
public static MethodInfo ConvertFromBase64CharArrayCharArrayIntInt()
{
Type type = typeof(Convert);
string name = "FromBase64CharArray";
List parameterTypes = new List();
parameterTypes.Add("char[]");
parameterTypes.Add("int32");
parameterTypes.Add("int32");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
#endregion
#region Original Process methods
///
/// Gets the MethodInfo object for Process.GetCurrentProcess()
///
///
public static MethodInfo ProcessGetCurrentProcess()
{
Type type = typeof(Process);
string name = "GetCurrentProcess";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.GetProcessById(int processId, string machineName)
///
///
public static MethodInfo ProcessGetProcessByIdIntString()
{
Type type = typeof(Process);
string name = "GetProcessById";
List parameterTypes = new List();
parameterTypes.Add("int32");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.GetProcessById(int processId)
///
///
public static MethodInfo ProcessGetProcessByIdInt()
{
Type type = typeof(Process);
string name = "GetProcessById";
List parameterTypes = new List();
parameterTypes.Add("int32");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.GetProcesses()
///
///
public static MethodInfo ProcessGetProcesses()
{
Type type = typeof(Process);
string name = "GetProcesses";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.GetProcesses(string machineName)
///
///
public static MethodInfo ProcessGetProcessesString()
{
Type type = typeof(Process);
string name = "GetProcesses";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.GetProcessesByName(string processName)
///
///
public static MethodInfo ProcessGetProcessesByNameString()
{
Type type = typeof(Process);
string name = "GetProcessesByName";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.GetProcessesByName(string processName, string machineName)
///
///
public static MethodInfo ProcessGetProcessesByNameStringString()
{
Type type = typeof(Process);
string name = "GetProcessesByName";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.Start(string fileName, string arguments)
///
///
public static MethodInfo ProcessStartStringString()
{
Type type = typeof(Process);
string name = "Start";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.Start(ProcessStartInfo startInfo)
///
///
public static MethodInfo ProcessStartProcessStartInfo()
{
Type type = typeof(Process);
string name = "Start";
List parameterTypes = new List();
parameterTypes.Add("ProcessStartInfo");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.Start(string fileName)
///
///
public static MethodInfo ProcessStartString()
{
Type type = typeof(Process);
string name = "Start";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.Start(string fileName, string arguments, string userName, SecureString password, string domain)
///
///
public static MethodInfo ProcessStartStringStringStringSecureStringString()
{
Type type = typeof(Process);
string name = "Start";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("securestring");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.Start(string fileName, string userName, SecureString password, string domain)
///
///
public static MethodInfo ProcessStartStringStringSecureStringString()
{
Type type = typeof(Process);
string name = "Start";
List parameterTypes = new List();
parameterTypes.Add("string");
parameterTypes.Add("string");
parameterTypes.Add("securestring");
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///
/// Gets the MethodInfo object for Process.Start()
///
///
public static MethodInfo ProcessStart()
{
Type type = typeof(Process);
string name = "Start";
List parameterTypes = new List();
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
#endregion
#region Original WebClient methods
///
/// Gets the MethodInfo object for new WebClient().DownloadData(string address)
///
///
public static MethodInfo WebClientDownloadDataString()
{
Type type = typeof(WebClient);
string name = "DownloadData";
List parameterTypes = new List();
parameterTypes.Add("string");
return HookManager.GetMethodInfo(type, name, parameterTypes);
}
///