Gallaxhar
Gallaxhar

Reputation: 1036

Is it possible to inject a dll with c# code and override a return value?

Lets say there is a simple c# application that is running which returns the answer for 1+1 in the form of a int with a value of 2, and I have the sourcecode for it but for curiosity's sake I want to change what it does without modifying the dll before runtime.

Is it possible to inject the running application with your own .dll and change the answer it returns in the same class & method to a value of something besides 2?

I already know I can go into the memory while the program is running and theoretically change the answer of "2" to something else, I'm curious if I can change the programs logic as it does it.

I also already know it's possible to "extend" running applications by injecting another .dll and "adding" additional functionality to an application, I'm interested in the theoretical possibility to change the code that is already running in the original .dll.

Upvotes: 2

Views: 3662

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127593

It is not easy to "change" the code inside a external DLL, however if you want to modify a argument going in or a result coming back that is not hard to do. The process of intercepting the call to either modify the input or output is called "Hooking".

In C# there is a easy to use library that does most of the work for you called EasyHook, this will allow you to intercept calls and replace the return values with your own results.

static IntPtr CreateFile_Hooked(
    String InFileName, 
    UInt32 InDesiredAccess, 
    UInt32 InShareMode, 
    IntPtr InSecurityAttributes,
    UInt32 InCreationDisposition, 
    UInt32 InFlagsAndAttributes, 
    IntPtr InTemplateFile)
{
    try
    {
        Main This = (Main)HookRuntimeInfo.Callback;

        lock (This.Queue)
        {
        if (This.Queue.Count < 1000)
                This.Queue.Push(InFileName);
        }
    }
    catch
    {
    }

    // call original API...
    return CreateFile(
        InFileName, 
        InDesiredAccess, 
        InShareMode, 
        InSecurityAttributes, 
        InCreationDisposition,
        InFlagsAndAttributes, 
        InTemplateFile);
}

In the above code it takes the argument passed in to InFileName and records it for later use inside your external mointoring program. You could easily just capture the result returned from CreateFile (or whatever real dll function you are calling) modify it to be whatever you want, then return the modified value.

To the caller of the original function they would have no idea that the value they got back from the DLL call was modified before they received it.

Upvotes: 6

Related Questions