Jump to content

Recommended Posts

Posted

The Tutorial

Here's how it's going to go down. I'm going to run through the theory on its own first, then I'll start writing it out in code and explain each step as it appears.

 

What is LoadLibrary Injection?

This is the very first thing you need to know; What are we attempting to do?

Well, for starters, LoadLibrary (as you may or may not know) is a function in the kernel32.dll. Here's its actual method signature according to MSDN:

HMODULE WINAPI LoadLibrary(__in  LPCTSTR lpFileName );

 

Despite the C++, that's not that scary right? It's just a function that takes a single string argument which then tells LoadLibrary where to load the file from. It then loads that library into the process and -in the case of dlls- calls the DllMain function. Simple enough to grasp I hope (you don't have to know how LoadLibrary works, just understand what it does)

 

Why is this useful to us?

Well, I'll tell you. kernel32.dll is loaded into almost, if not all (there, protected against your nitpicking [MENTION=609301]freedompeace[/MENTION]) windows processes. This means that all it's functions are ALSO loaded into the process, in particular, LoadLibrary. Due to some trickery, we can call LoadLibrary in an external process and tell it to load our designated dll. More on that to come.

 

Okay, so we have to somehow call LoadLibrary in the external process...how the?

Okay, first things first, you need to open a handle to your process so we can access it. Next you'll need to write the dll location to that processes memory (in bytes, of course). We need to do this because when calling the LoadLibrary function, we'll need to pass the parameter as an address for it to find the dll location. After we've called the LoadLibrary function, and everything has worked successfully, we just do some cleaning up, close all the handles and shit.

 

That's it! Simple eh? Now we just need to translate that simple process into code.

 

First, we'll need some API declarations so we can do what we need. Here they are.

 

    Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Integer, ByVal bInheritHandle As Integer, ByVal dwProcessId As Integer) As Integer
    Private Declare Function VirtualAllocEx Lib "kernel32" (ByVal hProcess As Integer, ByVal lpAddress As Integer, ByVal dwSize As Integer, ByVal flAllocationType As Integer, ByVal flProtect As Integer) As Integer
    Private Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As Integer, ByVal lpBaseAddress As Integer, ByVal lpBuffer() As Byte, ByVal nSize As Integer, ByVal lpNumberOfBytesWritten As UInteger) As Boolean
    Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Integer, ByVal lpProcName As String) As Integer
    Private Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As Integer
    Private Declare Function CreateRemoteThread Lib "kernel32" (ByVal hProcess As Integer, ByVal lpThreadAttributes As Integer, ByVal dwStackSize As Integer, ByVal lpStartAddress As Integer, ByVal lpParameter As Integer, ByVal dwCreationFlags As Integer, ByVal lpThreadId As Integer) As Integer
    Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Integer, ByVal dwMilliseconds As Integer) As Integer
    Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Integer) As Integer

 

And here's what we'll use them for:

OpenProcess This function returns the handle to the process specified by the dwProcessId parameter, we need this when accessing the process externally.

 

VirtualAllocEx Allows us to allocate memory in an external process specified by the hProcess handle. This is needed to allocate the memory to write our dll location to.

 

WriteProcessMemory Write memory to an external process specified by the hProcess handle. We'll use this simple function to write our dll location to the memory allocated by VirtualAllocEx

 

GetModuleHandle Gets the handle to a specified module within our program (THIS IS NOT EXTERNAL), we'll use this to get the handle to the kernel32.dll module.

 

GetProcAddress Find the address of a function within a module, given the module handle. We'll find the address of the LoadLibrary function within kernel32 with this.

 

CreateRemoteThread Creates a thread in the remote process. We'll use this as the final step: Calling the LoadLibrary function and giving the dll its own thread so it doesn't conflict with the process's main thread.

 

WaitForSingleObject Waits for an object to return. In particular we'll wait for the LoadLibrary function to finish its work, then close the handle to it.

 

CloseHandle Very simple function. Closes an open handle.

 

That's it for APIs. All we need

 

First up, I just wanna code a tiny little cleanup routine for when we get further into the function and want to abort. Basically just cleans up input handles and returns false. You'll see it in action later.

Private Function Die(Optional ByVal hProc As Integer = Nothing, Optional ByVal libThread As Integer = Nothing) As Boolean
    If Not hProc = Nothing Then CloseHandle(hProc)
    If Not libThread = Nothing Then CloseHandle(libThread)
    Return False
End Function

 

Now that moment is finally here, coding our function.to inject a process. First comes the method signature.

Private Function InjectDll(ByVal processID As Integer, ByVal dllLocation As String) As Boolean

 

Simple method singature, we'll take in a process id and a dll location and do our injection. If everything goes okay, we'll return true, otherwise false.

 

Now we're going to start with some simple error checking so that our function doesn't assrape itself.

If Not IO.File.Exists(dllLocation) Then Return False 'if the dll doesn't exist, no point in continuing. So we return false.
If IntPtr.Size = 8 Then Return False 'If the size of an IntPtr is 8, then is program was compiled as x64. x64 processes can't access x86 processes properly, so we just return false. You need to compile this program as x86.

 

Time to open up that process!

Dim hProcess As Integer = OpenProcess(&H1F0FFF, 1, processID) 'We'll open the process specified by the input process ID. With PROCESS_ALL_ACCESS access, seeing as we only need to write.
If hProcess = 0 Then Return Die() 'If we didn't get the handle, we exit and return false. No cleanup so no params for die()

 

Next we've gotta allocate some memory for the dll location, and then write it.

Dim dllBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(dllLocation) 'As I mentioned earlier, we have to write the dll location as bytes to the process memory, so we take the bytes of the string using the standard encoding.
Dim pathLocation As Integer = VirtualAllocEx(hProcess, 0, dllBytes.Length, &H1000, &H4) 'Allocate memory the size of the string we need to write to memory. pathLocation now holds the address of where the memory was allocated.
If pathLocation = Nothing Then Return Die(hProcess) 'VirtualAllocEx returns Nothing when it fails, so we check for that and return false if we find it. We've opened a process handle so we have to pass that to Die to clean it up.

 

So hopefully you could see in that step that we just converted the dll location to bytes, and then allocated some memory (the size of the dll location bytes) in the target process. Now we need to write to it.

 

Dim wpm As Integer = WriteProcessMemory(hProcess, pathLocation, dllBytes, dllBytes.Length, 0) 'write the contents of dllBytes to the memory allocated at pathLocation.
If wpm = 0 Then Return Die(hProcess) ' WriteProcessMemory returns 0 if it fails.

 

Alright we're getting there, so far we have written the location of our dll to the other processes memory, and we have the address where we wrote that. That's part one complete, the next part is actually finding and calling LoadLibrary

 

in that process and passing in the variable we wrote to memory. We'll get the address of LoadLibrary first.

 

Here's how:

Dim kernelMod As Integer = GetModuleHandle("kernel32.dll") 'Remember what I was saying about kernel32 being loaded into the same address space for every normal process? This means we don't have to do any fancy crap to find its location in our target process, we can get the location in our own process and safely assume it will be the same for all process. This means we can use GetModuleHandle, which only works internally.
Dim loadLibAddr As Integer = GetProcAddress(kernelMod, "LoadLibraryA") ' GetProcAddress gives us the address of the specified function within the module.
If loadLibAddr = 0 Then Return Die(hProcess) 'If GetProcAddress failed it'll return 0.

 

Yay, we finally have the address of the LoadLibrary function. NOW WE CAN CALL IT AND LOAD THIS FUCKER.

Dim procThread As Integer = CreateRemoteThread(hProcess, 0, 0, loadLibAddr, pathLocation, 0, 0) 'Okay, this is the thread creation. We pass our process handle to tell what process to create the thread on. the third param is the handle of the function to call. In this case we choose the LoadLibrary function. The next param is the arguments to pass to the function (omg remember we wrote that to memory? NOW WE PASS THE ADDRESS BACK!)
If procThread = 0 Then Return Die(hProcess) 'unable to create the thread. Return false
Dim waitVal As Integer = WaitForSingleObject(procThread, 5000) 'allow the LoadLibrary function 5 seconds to process.
If Not waitVal = &H0UI Then Return Die(hProcess, procThread) 'Function didn't signal completion. Fuck that shit abort ABORT
CloseHandle(procThread) 'close the handle to the LoadLibrary function
CloseHandle(hProcess) 'close the handle to the process
Return True 'made it, yay.

 

And that's it, you have successfully located the LoadLibrary function and called it, passing our dll location as the param. The dll should now load successfully.

 

I hope someone actually reads the tutorial, it's pretty lengthy for such a short function but there's a lot of shit going on if you're new to it.

 

EDIT: Oh yeah, if you're having trouble finding how to compile to x86. Check out this MSDN article.

Compile options VS Express Editions - SocialMSDN

 

 

Credits,

Chooka/Jason

 

 

  • 4 weeks later...
Posted

This is a way to hack your own pc.. rofl usefull xD

 

You can also use it to inject dll's into games like aimbots, and generally cheating dll's ;).

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Posts

    • --- Interlude Faction/GvE PvP grand opening 2025-11-15 19:00 GMT+2 ---   Gameplay: Chronicle: Interlude Type: Faction/GvE (Angels vs Nature vs Demons) GM Shop: B-S grade Buff slots: 20+4 Starting level: 74 + rebirth system   New Features: Client: Modern interface based on Essence Balance: New class skills for better balance Achievement Rewards: Daily, Weekly, One-time TOP rankings: PvP, Event PvP, Map PvP, Clan PvP, Event MvP, Map MvP Zones: 70 different PvP zones,  18 different events (8 map events | 10 main events) 12 Grand/raid bosses. Castle siege Olympiad Clan Hall challenge Custom Enchant System: Dynamic success chance (greater enchant level or item grade less enchanting success chance) Enchant rate: Blessed scrolls dynamic from 100% to 25%. Crystal Scrolls: 100%; Max enchant weapon +12 Max enchant armor +8 Safe point enchant system Extra Features: PvP items with level upgrade Weapon/Armor upgrade (from B grade to S) system Attributes system   Website: https://l2cygnus.com Community: Discord Facebook: https://www.facebook.com/l2cygnus Youtube:   
    • More fluid combat, not 100% yet, but I think it's acceptable. I put the following logic in movetopawn, moveto, maybemovetopawn, validatelocation, movetolocation: If Config.GeoData is active, it applies the coordinates using geodata; if disabled, use setdistanceplansq to measure the distance of things! Fix for reflected damage (if the attacker is null, it will not be calculated). Minor improvements to the Day/Night item generation manager. Fix to not punish players who destroy items with a count = 0... Fix for when a player tried to use a resurrection scroll while seated, it disappeared without effect. Fix for when it was possible to equip armor while paralyzed. Cleanup of System message. Rework of PathNodes. Fixed the ia for mobs attack range when chasing the player (test) Fixed Pathnodes loading Added # ------------------------ #Show Red Name for Aggressive Mobs # ------------------------ ShowRedName = True Which was missing in the configs
    • ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⚔️ L2JOmen High Five - SERVIDOR 100% RETAIL ⚔️ 📢 SOLICITAMOS APOYO PARA TESTING 📢 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ¡Saludos, comunidad de Lineage II! Estamos desarrollando un proyecto ambicioso y de calidad: L2JOmen High Five, un servidor  100% RETAIL que busca ofrecer la experiencia más auténtica de High Five.  Nos encontramos en la fase de desarrollo y testing, y necesitamos tu ayuda para hacerlo  grande. Si eres un amante del retail, disfrutas probar nuevas funciones y quieres formar  parte de un proyecto serio desde sus inicios, ¡tu apoyo es invaluable! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🎮 CARACTERÍSTICAS PRINCIPALES 🎮 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ✅ SERVIDOR 100% RETAIL    • Experiencia auténtica de High Five    • Geodata PTS Official    • Plataforma Premium 2025 ✅ SISTEMA DE RATES DINÁMICO (Progresión Retail x1 con ayuda x5 -> x1)    • XP: 1-20 (5.0x) | 21-40 (3.0x) | 41-60 (2.0x) | 61-75 (1.5x) | 76-85 (1.0x)    • SP: 1-20 (5.0x) | 21-40 (3.0x) | 41-60 (2.0x) | 61-75 (1.5x) | 76-85 (1.0x)    • Adena: x2.0 (Retail con pequeño ajuste)    • Drop y Spoil: x1.0 (Mobs, Raids y Epics) ✅ SISTEMA DE ENCANTAMIENTO PROFESIONAL    • Enchant Safe: +6 (100% seguro hasta +6)    • Enchant Máximo: +30    • Tasas de encantamiento balanceadas:      * 0-3: 100% | 4: 80% | 5: 75% | 6: 70% | 7: 65% | 8: 60%      * 9: 55% | 10: 50% | 11: 45% | 12: 40%      * 13: 10% | 14-25: 5-9% | 26-30: 1-4%    • Sistema Blessed Enchant habilitado ✅ INICIO DE PERSONAJE    • Dynasty Masterwork Set completo +12    • 1 Ticket para Weapon S +12    • Duración: 7 días ✅ CONFIGURACIÓN RETAIL    • Element Limit: Nivel 4    • Buffs: Duración de 1 hora    • Nobless: Obtenible mediante quest    • Subclass Máxima: 10 (Certificación para cada Subclass) ✅ SISTEMA DE FARM Y ECONOMÍA    • Múltiples monedas de farm (Adena, Ancient Adena, Coin of Luck, PC Bang Points, Farm Coins)    • Varias zonas de farm disponibles    • Zona de Party Farm (se habilita cada 3 horas por 1 hora)    • 4 Raids diarias programadas ✅ SISTEMA PC BANG POINTS    • Aproximadamente 10,000 puntos por 24 horas conectado    • Entrega cada 10 minutos    • Jugadores Normales: 60-72 puntos/intervalo    • Jugadores Premium: 96-116 puntos/intervalo    • 5% probabilidad de doble puntos ✅ SHOPS COMPLETOS    • Shop Normal (Adena y Farm Coins)    • Shop Donate (con opciones premium)    • Armaduras y Armas hasta Grado Dynasty, Moirai, S84    • Joyas completas, no incluye Epics    • Scrolls (Normales, Blessed, Divine, Ancient)    • Elementos hasta nivel 4-7    • Accesorios y consumibles ✅ SISTEMA VIP    • 5 niveles de VIP disponibles    • Bonificaciones progresivas de XP/SP/Drop    • Recompensas diarias exclusivas ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🤝 ¿QUÉ NECESITAMOS DE TI? 🤝 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🔍 TESTERS ACTIVOS    • Jugadores que prueben todas las funciones del servidor    • Feedback constructivo sobre bugs, balance y mejoras    • Reporte de problemas encontrados 🎮 JUGADORES DEDICADOS    • Amantes del retail que valoren la experiencia auténtica    • Personas dispuestas a ayudar a mejorar el proyecto    • Comunidad comprometida con el crecimiento del servidor 📊 REPORTES DETALLADOS    • Bugs y errores encontrados    • Sugerencias de balance    • Opiniones sobre el gameplay    • Feedback sobre sistemas implementados ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 💎 ¿POR QUÉ UNIRTE A L2JOmen? 💎 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🌟 PROYECTO SERIO Y COMPROMETIDO    • Desarrollo constante y mejoras continuas    • Atención a la comunidad activa    • Transparencia en todas las decisiones 🎯 EXPERIENCIA 100% RETAIL    • Sin modificaciones que rompan el juego original    • Balance auténtico de High Five    • Gameplay puro y tradicional ⚡ TECNOLOGÍA DE VANGUARDIA    • Servidor optimizado y estable    • Geodata oficial de PTS    • Sistema robusto y sin lag    • Sistema Anticheat Premium 🎁 RECOMPENSAS PARA TESTERS    • Participación activa en el desarrollo    • Reconocimiento especial en el lanzamiento    • Beneficios exclusivos para early testers ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📞 CONTACTO E INFORMACIÓN 📞 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Si estás interesado en formar parte de este proyecto y ayudarnos a crear el mejor  servidor retail de High Five, contáctanos. Tu apoyo es fundamental para hacer realidad  este grandioso proyecto. 💬 Únete a nuestro grupo de testing 🌐 WhatsApp: https://chat.whatsapp.com/Km6uRtFsoUq2tNZZalo5HB?mode=wwt ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 🏆 ¡Juntos construimos el mejor servidor retail! 🏆 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  
    • any server used these files? if yes let me know in pm.
    • L2Net is an in-game (IG) bot. I already have Adrenaline for that. I'm looking for an out-of-game (OOG) bot - one that doesn’t require the Lineage 2 client to run.
  • Topics

×
×
  • Create New...

AdBlock Extension Detected!

Our website is made possible by displaying online advertisements to our members.

Please disable AdBlock browser extension first, to be able to use our community.

I've Disabled AdBlock