Created
July 25, 2016 07:07
-
-
Save NaxAlpha/639c17079d38361599547828adf304fd to your computer and use it in GitHub Desktop.
Managed Dll Injection with C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
using System.Windows.Forms; | |
namespace Loader { | |
public static class Library | |
{ | |
[DllExport] | |
static void ShowMessage() { | |
using(var p = Process.GetCurrentProcess()) { | |
// Add System.Windows.Forms reference | |
MessageBox.Show("Hello From " + p.ProcessName); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Runtime.InteropServices; | |
class Program { | |
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] | |
static extern IntPtr GetProcAddress(IntPtr hModule, string procName); | |
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)] | |
static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName); | |
static void Main(string[] args) { | |
// Get our process | |
using (var p = Process.GetProcessesByName("notepad++")[0]) { | |
// Must give full path of library | |
// Or relative to target process | |
var path = @"c:\fakepath\Loader.dll"; | |
var ptr = p.LoadLibrary(path); | |
// In order to get function address | |
// we must load library in our process | |
var lib = LoadLibrary(path); | |
var addr = GetProcAddress(lib, "ShowMessage"); | |
// Lets call target function | |
p.Call(addr, IntPtr.Zero); | |
} | |
} | |
} |
Works with 64-bit processes.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think this only works for 32-bit processes.