Jump to content

[Guide][VB]An Injection


FighterBoss

Recommended Posts

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

 

 

Link to comment
Share on other sites

  • 4 weeks later...

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 ;).

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Posts

    • make an item that expires either a week or a day when u press the accept , if u try to redo it and u have the item it wont let you, can be in quest items and not destroyable... 
    • If you are this new to java, I would strongly recommend using IntelliJ Community Edition (free) instead of Eclipse since it indexes your entire source and makes it extremely easy to navigate forward and backward dependencies and method calls. Now, on the topic. Unless your Mobius sources are ancient, they should already have native support. It is called `DailyTaskManager`. It would be impossible to give you a mould without such a DailyTaskManager. I would suggest you parse/adapt it from a newer source version if you don't have it. The logic is rather simple once you get to understand it. 1. You need a handler to count the mobs and give rewards, etc. 2. You need to keep mission status for each individual player in the database. 3. You need to INSERT the data when a player takes the mission, UPDATE it whenever you like, be it on every single mob or not (I would only update the DB on player disconnect/log out, or on mission completion), and SELECT/extract it when the player logs in (EnterWorld.java). 4. You need a way to get the Mission Reset Type (Daily/Weekly), and you should call a reset method similar to the one at the bottom of my post from within the DailyTaskManager every day at 9am or whenever you like. Keep in mind that the above is not an exhaustive list, but some generalised approach aimed at helping you see the bigger picture.   public synchronized void reset() { DailyMissionResetType reset = _holder.getResetType(); switch (reset) { case NEVER -> { return; } case MONTHLY -> { if (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) != 1) { return; } } case WEEKLY -> { if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { return; } } case WEEKEND -> { if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) { return; } } case DAILY -> { } default -> { LOGGER.warning("Unhandled daily mission reset type: " + reset); return; } } try ( Connection con = DatabaseFactory.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM character_daily_rewards WHERE missionId = ? AND status = ?")) { ps.setInt(1, _holder.getId()); ps.setInt(2, DailyMissionStatus.COMPLETED.getClientId()); ps.execute(); } catch (SQLException e) { LOGGER.log(Level.WARNING, "Error while clearing data for: " + getClass().getSimpleName(), e); } finally { _entries.clear(); // resets the entries in the Manager. DailyMissionsManager.getInstance().clearEntries(); } } *Disclaimer: The provided code snippet is just an adaptation of Mobius' implementation on newer chronicles.  
    • Please post ebooks and magazines here.
    • https://l2balerion.com   GENERAL RATES Exp: 5000x Sp: 5000x Adena: 100x Drop: 50x     ENCHANT RATES Safe Enchant: +6 Maximum Enchant Weapon: +20 Maximum Enchant Armor/Jewel: +20 Normal Scrolls Rate: 55% Blessed Scrolls Rate Until +16: 100% Crystal Scrolls Rate From +16 to +20: 100%     AUGMENT RATES & SKILL ENCHANT Mid Life Stone Rate: 5% High Life Stone Rate: 20% Top Life Stone Rate: 30% Max Skill Enchant: +14     COMMANDS .menu .info .repair     EVENTS EVERY HOUR DeathMatch Team vs Team Domination Double Domination Lucky Chests Simon Says Capture the Flag Mutant Korean TvT   NPC Global GK GM Shop Donation Shop Buffer Server Rankings Special Shop Augmenter Skill Enchanter Raid Info Castle Manager Dynamic Zone Engine Password Changer Skin Manager   EXTRA Olympiad Max Enchant +6 ( Your Items must be at least +6) Flame of Splendor Barakiel, drops Noblesse Item ( Last Blow cannot be Noblesse ). Tournaments are at 00.00 ( GMT+3 )
    • Hellllllo everyone ! Good news for some, bad news for others : aCis was, once again, leaked.   It wouldn't be that problematic if it was old content, or even last revision 408 ; but this time, the whole content of under development/master branches was leaked out. One pack project is actually reselling NEXT revision content - before even being announced on aCis forums.   The mole/leaker is still part of customers, and is still capable to leak data, at the date I speak about.   Since I'm on a joyful mood, following events will occur :   PIRATE PLANK MINIGAME   Since we got restricted amount of donators (we're actually 13 on sources counting developers, over all), it's not extremely hard to actually delete the mole ; few ppl are actually matching the description, and a list can be easily generated based on time leak, potential country, contributions,...   Which basically end with that representation :     How will it work ? Everytime a new leak will occur, the following donator on the board will jump out of ship (and Talking Island waters are kinda cold). Since I'm not a monster and got principles, I will send back spent money for the non-granted months to the kicked dude. You won't be added back to the sources, anytime. The game ends when the mole is dropped out, or when I'm alone with my most loyal peeps around.   CONTRIBUTION   Leftover donators will have to contribute to the pack, being reports or code edits. Silent people won't be renewed anymore solely based on money.   In the same order of idea, I will now request a minimum of 100 cookies contribution before accepting any new ppl on the gitlab - which anyway won't be hard to do if you're a minimum invested into the pack.   If you understood the concept, free ppl can access gitlab sharing for 200 cookies contribution (100+100), and donators can access with 100 cookies + 200€. Regarding monthly contribution, there are no special numbers to achieve, stay active and you will stay.   PUBLIC REVISION WILL STEP UP   Next rev 409 will be exceptionally released as public revision. This revision got unique reworks, notably AI (L2OFF GF 1:1) and pathfind systems (up to 100 times faster, see #for-your-eyes-only over aCis discord for screens proofs).   This revision got a lot of new content, and is far ahead of any other L2J pack in terms of AI fidelity with L2OFF - even the costier.   ENDING WORD   Thanks to all loyal people who have, will or currently support this pack - one of the very few to offer unique reworks.   L2J community, as a whole, unfortunately never stepped up or shined by its cleverness or integrity - and is more preocuppied to add poorly written customs over quality leaked sources.   The olympic medal goes to the poop-eater project owner applying straight leak, not even knowing what exactly is the changeset content (because yes, he doesn't know)... It's actually sad real people follow and pay for your work, but well, good job surfing on my own merits, I guess. Maybe one day you will go out of my shadows, and make your own path. That's the best I can wish you.   So, my thanks to the few beacons of light in this mere pool of shadows. That's essentially for you (and for my own pleasure, ofc) I continue to work on this hobbyist project - started almost 14 years ago.   -----------------------------------------------------   Changeset 409 (3301)   SCH, Castles, IU, Npc movement, Drop rate rework, Bugfixes, Organization   SCH - Ty Bandnentans for the good work All SCHs are normally fixed and working. CH decorations are reworked (they got their own XML, related Configs are dropped). Aden CHs got the Wyvern option, as stated in Patch Notes. Ty Denzel for report. CH features levels are corrected. Ty Denzel for report. Fix NPC clan crest issue. Castles Keep Castle next tax percent instead of resetting it to 0. Implementation of missing variables over Castle vault management. Ty KejbL for report. Remove doublons over Residence npcIds. Add npcId 35552 HTMs. Ty //Dev for report. Fix the tax income calculation. IU Add PAPERDOLL as potential location for IU (fix gm enchant, arrows consumption). Ty Roko91 for report. Fix weight calculation over login. Ty KejbL for report. Fix inventory update upon teleport (BSOE consumption). Ty //Dev for report, La Roja for fix. Fix inventory weight upon NPC buy. Npc movement MOVE_TO desire is cleansed over onEvtBlocked, avoiding to build infinite desire. Don't add MOVE_TO desire if given Location isn't reachable. FLEE doesn't call event upon onEvtBlocked (that event means something wrong happened, it's then impossible to trigger "regular" FLEE checks). Use Location#equals in few scripts. NpcAI#thinkFollow cleanup (-8 arrays, -24 List#get, -8 distance2D). Drop rate rework Main idea is to iterate each category X times, as if X monsters were killed. No % re-calculation or whatever, it's plain and simple. x50 means you got the calculated drops of 50 monsters. Avoid to generate IntIntHolder, manage the drop/spoil using a Map<Integer, Integer> instead, which also allow to merge similar itemIds. Categories % are tested no matter if drop or spoil, which allow levelMultiplier to be properly applied. Monster#dropItem is moved to Npc#dropItem, which allow any Npc to drop an item and avoid cast. "killer" is now part of all Npc#dropItem, meaning the item is properly item protected. Bugfixes Fix a ClassCastException over Quest#onClanAttacked. Fix a NegativeSizeArrayException upon client logging. Drop few logging errors related to invalid client attempts. Fix NPE over Q635. Fix PDAM calculation prior to rev 399 physical attack/skill split. Ty Yoska for report. Fix TradeList automatic title cleanup. Ty Denzel for report/fix. Add back missing Config.PARTY_XP_CUTOFF_METHOD "none" option. Ty CUCU23 for report/fix. Fix "upper roof" NPCs. Ty Bandnentans for fix. Fix Seven Signs individual stone contribution method. Ty //Dev for report. Fix Q372 reward table and drop rate. Ty //Dev for report. Q348 now distributes drops as party-random, despite the client info. Ty Denzel for report. Fix Benom teleports out. Hardcode other in/out Locations. Ty //Dev for report. Don't show Crystallize icon on inventory for Bounty Hunters (was an addition of CT1 GP1). Ty Bandnentans for report. Replace "weightPenalty" for "weightLimit" over skills XMLs. Ty //Dev for report/fix. When Heroes participate in a raid against Antharas, Valakas, and Baium, the boss monster has a chance to shout out the Hero characters’ names. Ty deekay for fix. Fix isRaidBoss implementation (a raidboss minion without master was considered raidboss). Fix Nurse Ants not healing the Queen Ant larva. Fix a SQLException over Olympiad server startup. Fix a SQLException over Clan member removal (since clan privs rework). Fix default 30169 npcId HTM. Ty Bandnentans for report. Fix Festival Guide missing rift option. Ty Denzel for report/semi-fix. Few dwarven/general manufacture fixes Add the missing max recipe integrity check. Upon shop fail, call back the manage window. Upon shop fail, don't cleanup the manufacture list. Upon shop success, cleanup the reverse manufacture list (successful general shop resets dwarven, successful dwarven shop resets general). Organization Rework HtmCache and CrestCache to use NIO. Move CrestType to enums. Implementation of WorldObject#forEachKnownType / WorldRegion#forEachType & forEachRegion - Avoid List overhead in numerous popular locations (notably broadcastPacket or region checks - which are done on every knownlist check). Rework SkillList packet, it is now handled as other packets. Delete Player#sendSkillList method. Delete DeadlockDetector class and related configs. Add GameServer#isServerCrash, based on LaRoja implementation - without uses, for now. Move IPv4Filter class to commons.network, delete net.sf.l2j.util package. Add DefaultSeeRange config, use the retail value 450 instead of 400. Add more records, ty LaRoja for the merge request. Delete unused dimensionalRift.xml. Few ItemContainer optimizations. Rename all ocurrences of adenas to Adena. SonarLint / UCDetector fixes : Drop MathUtil#limit, use Math#clamp instead (introduced in JDK21). Drop following unused Configs : FS_TIME_ENTRY, FS_TIME_END, RAID_MINION_RESPAWN_TIMER. Few public / protected / private edits. A lot more to come. switch cases are merged (introduced in JDK12). Boolean object is compared to Boolean.FALSE/TRUE, not directly tested as a boolean. String#replaceAll is replaced with String#replace when a regex pattern isn't involved. Generate few records : Sequence, TutorialEvent. Few class-based variables are now local. Use HashMap.newHashMap instead of new HashMap when the capacity is known (static final maps). HashMap.newHashMap avoids to set 0.75 capacity when it's not needed. LogRecord record is renamed LogRecord logRecord, due to record being now a keyword. Use proper Singleton pattern for instance type (notably listeners). Generate private constructors calling IllegalStateException for utility classes.
  • Topics

×
×
  • Create New...