Csharp

Dynamic API Calls in .NET

2 minute read Published:

Using Reflection to call APIs dinamically

Today I’m going to share a way to call APIs without DLLImport. I’ve first saw this years ago at OpenSC.ws as far as I remember and got into the idea. The code was lost since then but I found a copy.

Program.cs

using System;
using System.Reflection;

namespace APICaller
{
class Program
{

```
	public static void Main(string[] args)
	{
		Console.Title = "Dynamic API Caller";
		Console.WriteLine("Press any key to call your API!");
		Console.ReadKey(true);
		
		string className = MethodBase.GetCurrentMethod().DeclaringType.Name; //getting our current class name
		string asmName = Assembly.GetExecutingAssembly().FullName; //getting our current assembly name
		string methodName = MethodBase.GetCurrentMethod().Name; //getting our current method name
		
		//Sample with a simple MessageBox. You can adapt this call to whatever you need
		//(note that you should also adapt the class if needed)
		DynamicAPIs CreateDynamicAPI = new DynamicAPIs("user32.dll",
		                                               "MessageBoxA",
		                                               asmName,
		                                               methodName,
		                                               className,
		                                               typeof(int),
		                                               new object[] {
		                                               	IntPtr.Zero,
		                                               	"Test Message",
		                                               	"Test Title",
		                                               	0
		                                               });			
		
		Console.Write("Press any key to exit . . . ");
		Console.ReadKey(true);
	}
}

```

}

And our mighty class.

MBR Dump With .NET - Part 1

2 minute read Published:

Dumping MBR with .NET

Greetings. Years ago I was messing around with Windows MBR (VXHeaven thread) and got stuck while trying to write a modified copy back to the disk. I’m calling this “Part 1” because I’m still stuck at this and plan to get back on my research.

Anyways, it will be a short post, just to share where I was at that time.

using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.IO;

namespace MBR
{
	class MainClass
	{

		[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
		static extern uint SetFilePointer(
			[In] SafeFileHandle hFile,
			[In] int lDistanceToMove,
			[Out] out int lpDistanceToMoveHigh,
			[In] EMoveMethod dwMoveMethod);

		[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
		static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
			uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
			uint dwFlagsAndAttributes, IntPtr hTemplateFile);

		[DllImport("kernel32", SetLastError = true)]
		internal extern static int ReadFile(SafeFileHandle handle, byte[] bytes,
			int numBytesToRead, out int numBytesRead, IntPtr overlapped_MustBeZero);


		public enum EMoveMethod : uint
		{
			Begin = 0,
			Current = 1,
			End = 2
		}

		public static void Main (string[] args)
		{
			Console.Title = "MBR Dumper";
			Console.WriteLine ("Dump MBR to raw.bin? (Y or N)");
			string ans = Console.ReadLine ();

			if (ans == "Y" || ans == "y") { 
				Console.WriteLine("\nDumping...");
				Dump ();
				Console.WriteLine("Done!");
				Console.ReadKey (true);
			} else {
				Environment.Exit (0);
			}

		}

		public static void Dump() {
			uint GENERIC_READ = 0x80000000;
			uint OPEN_EXISTING = 3;

			SafeFileHandle handleValue = CreateFile (@"\\.\PHYSICALDRIVE0", GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
			if (handleValue.IsInvalid) {
				Marshal.ThrowExceptionForHR (Marshal.GetHRForLastWin32Error ());
			}
			int offset = int.Parse ("0", System.Globalization.NumberStyles.HexNumber);
			int size = int.Parse ("200", System.Globalization.NumberStyles.HexNumber);
			byte[] buf = new byte[size];
			int read = 0;
			int moveToHigh;
			SetFilePointer (handleValue, offset, out moveToHigh, EMoveMethod.Begin);
			ReadFile (handleValue, buf, size, out read, IntPtr.Zero);
			FileStream myStream = File.OpenWrite ("raw.bin");
			myStream.Write (buf, 0, size);
			myStream.Flush ();
			myStream.Close ();
			handleValue.Close ();

		}
	}
}

That’s it, MBR will be dumped to “raw.bin” in your current application directory. You can open it with a text editor or even better, a hex editor and modify as you wish. I will keep my work on this and if I ever find a way to write it back to the disk (tried several things already, no luck), I will post a Part 2.

A Steganographic .NET Executable

3 minute read Published:

A simple introduction to steganography with .NET

A while ago, alcopaul suggested a .NET executable that could store a secret message inside. While I did not followed his strict theory, I did wrote a working proof of concept, very basic and dirty but, well, it’s only a POC. Here we go (dirty code, do not judge me):

Our includes for this application.

using System;
using System.Reflection;
using System.IO;
using System.Windows.Forms;
using System.Security.Cryptography;

I’ll now show you the methods I’m using here.

private static byte[] JoinTwoByteArrays(byte[] arrayA, byte[] arrayB)
		{
			byte[] outputBytes = new byte[arrayA.Length + arrayB.Length];
			Buffer.BlockCopy(arrayA, 0, outputBytes, 0, arrayA.Length);
			Buffer.BlockCopy(arrayB, 0, outputBytes, arrayA.Length, arrayB.Length);
			return outputBytes;
		}
private static byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)
{
	AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();
	dataencrypt.BlockSize = 128;
	dataencrypt.KeySize = 128;
	dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
	dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
	dataencrypt.Padding = PaddingMode.PKCS7;
	dataencrypt.Mode = CipherMode.CBC;
	ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);
	byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);
	crypto1.Dispose();
	return encrypteddata;
	}
private static byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)
	{
	AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();
	keydecrypt.BlockSize = 128;
	keydecrypt.KeySize = 128;
	keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
	keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
	keydecrypt.Padding = PaddingMode.PKCS7;
	keydecrypt.Mode = CipherMode.CBC;
	ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);
	byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);
	crypto1.Dispose();
	return returnbytearray;
	}

A basic method for joining two byte[] arrays and, of course, a standard AES encrypt/decrypt routine I’ve found somewhere. I could write my own but I was kind of in a hurry so I got this, credits to the creator, whoever you are. You can use your own, code your own, use other cypher, it does not matter, the concept should still work.

.NET Injection Cecil

3 minute read Published:

Getting into .NET injection with Mono

This may not be news for everyone but I find it interesting. Mono.Cecil is a impressive work and can provide a lot of cool features such as runtime .NET assembly manipulation. We can inject opcodes (IL instructions) into a target assembly, transforming it as we wish. Here’s the test scenario:

A dummy C# application like the one below, compile it to get it’s executable file, that’s what we need (https://github.com/guitmz/msil-cecil-injection).

using System;

namespace Dummy
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("DUMMY APP HERE YO!");
			Console.ReadLine();
		}
	}
}

We also have this other application which will be our injector. You’ll need to download the Mono.Cecil DLL file and add it as reference in the injector project.