7

Short version:

I'm trying to open a process handle with debug privileges and define a pointer which points to an object in the memory of the debuggee.

Long version

I'm a computer science university student in my final year of graduation and got tasked to build an application which should be used for educational purposes for the next generation of students.

Why am I here asking for help, you might ask? Well, the target platform is Windows and I have unfortunately no knowledge of the WinAPI whatsoever...

Okay, here is the basic requirement:

  • Programming language: C++
  • Platform: Windows (7 Professional)
  • Used IDE: Visual Studio 2012
  • No additional libraries if they aren't essential to ease the development

What will the application be used for?

Using this application the students shall learn to handle addresses, in this case static ones: the debuggee process will have some static pointers, which lead to other pointers themself to form a multi-dimensional pointer. The students have to find these base addresses using some debugging techniques (which is not part of my work!) and try to find the values at the end of these pointers.

My application will be used by the tutors to randomly change the values and/or structures in the debuggee process.

Some search did yield the first answer: using ReadProcessMemory and WriteProcessMemory one can easily change values in the memory of another process without any need to get debug privileges.

What my tutors want, however, is to have the ability to define pointers (let's say unsigned int) which should point into the memory space of the debuggee process, effectively holding the base addresses I wrote about earlier. They really want this and I couldn't even talk this out of them so I'm stuck to do this at the end...

And what exactly should work?

Well, I'd have accomplished my task if the following (pseudo) code works:

grantThisProcessDebugPrivileges();
openAnotherProcessWhileItsRunning("targetProcess.exe");

unsigned int * targetValue = (unsigned int*) 0xDE123F00;
// or even
myCustomClass * targetClass = (myCustomClass*) 0xDE123F00;

where the address 0xDE123F00 lies in the memory space of targetProcess.exe.

I know this is possible, else there wouldn't be debuggers which could show this information.

What I did so far (or tried...)

Okay, the thing is: I'm really confused whether I have to activate debug privileges for my application prior opening the target process, doing it after opening or rather giving the target process these privileges.

So I found an example in MSDN and tried to implement it:

    BOOL SetPrivilege(
    HANDLE hToken,          // token handle
    LPCTSTR Privilege,      // Privilege to enable/disable
    BOOL bEnablePrivilege   // TRUE to enable.  FALSE to disable
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;
    TOKEN_PRIVILEGES tpPrevious;
    DWORD cbPrevious=sizeof(TOKEN_PRIVILEGES);

    if(!LookupPrivilegeValue( NULL, Privilege, &luid )) return FALSE;

    // 
    // first pass.  get current privilege setting
    // 
    tp.PrivilegeCount           = 1;
    tp.Privileges[0].Luid       = luid;
    tp.Privileges[0].Attributes = 0;

    AdjustTokenPrivileges(
            hToken,
            FALSE,
            &tp,
            sizeof(TOKEN_PRIVILEGES),
            &tpPrevious,
            &cbPrevious
            );

    if (GetLastError() != ERROR_SUCCESS) return FALSE;

    // 
    // second pass.  set privilege based on previous setting
    // 
    tpPrevious.PrivilegeCount       = 1;
    tpPrevious.Privileges[0].Luid   = luid;

    if(bEnablePrivilege) {
        tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);
    }
    else {
        tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED &
            tpPrevious.Privileges[0].Attributes);
    }

    AdjustTokenPrivileges(
            hToken,
            FALSE,
            &tpPrevious,
            cbPrevious,
            NULL,
            NULL
            );

    if (GetLastError() != ERROR_SUCCESS) return FALSE;

    return TRUE;
};

And in my main:

HANDLE mainToken;

// I really don't know what this block of code does :<
if(!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &mainToken))
{
    if (GetLastError() == ERROR_NO_TOKEN)
    {
        if (!ImpersonateSelf(SecurityImpersonation))
        return 1;

        if(!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &mainToken)){
            cout << GetLastError();
        return 1;
        }
     }
    else
        return 1;
}

if (!SetPrivilege(mainToken, SE_DEBUG_NAME, true))
{
    CloseHandle(mainToken);
    cout << "Couldn't set DEBUG MODE: " << GetLastError() << endl;
    return 1;
};

unsigned int processID = getPID("targetProcess.exe");
HANDLE hproc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);

if (hproc == NULL)
{
    cout << "Couldn't open the process" << endl;
    return 1;
};

    unsigned int * theValue = (unsigned int*) 0xDE123F;

Okay, this code runs without any errors, SetPrivilege returns TRUE so I guess it really did set SE_DEBUG_NAME, which I think is the flag I need to set.

But after - for example - outputting the dereferenced value of theValue, the application crashes with an access violation message, which shows that my approach didn't work. I did especially pay attention to start the VisualStudio Debugger with admin rights (SetPrivilege failed otherwise).

I am really clueless here, the fact that I don't know whether setting SE_DEBUG_NAME is the right approach adds to my overall confusion.

I hope you can help me out :) My hands are tied concerning the specific requests of the application , if you have ideas to achieve my goal using an entire dfferent approach, you're free to enlight me, but I won't be able to present it to my superiors so it will only add to my knowledge :D

5
  • 1
    You only need to enable the debug privilege if you want to debug system level processes (i.e. services). If you are debugging non-system level processes enabling this flag gains you nothing. Jun 21, 2013 at 22:09
  • Well, this explains why nothing happens :D But there has to be some flag I can set, isn't there? I read something about CreateProcess and that one can set a DEBUG flag, I rather don't want to create the process but if this is the only way...
    – Ahnihmuhs
    Jun 21, 2013 at 22:25
  • Have you tried using DebugActiveProcess? Jun 21, 2013 at 22:32
  • Well I didn't, but after this I just tried it out and - OMG! - it worked, for the first time! Can't believe this, but well, it just worked ONCE, I could output the value of theValue and could confirm the correctness. But every other time I tried it now it won't work, there are no errors returned either, just the same old access violation message :( Why did it work once and not anymore?
    – Ahnihmuhs
    Jun 21, 2013 at 23:07
  • @Ahnihmuhs You wrote in the answer that was deleted, There is some other way to access "foreign" pointers depicted by Mark Tempel through writing kernel space code. I don't believe that is true. Jun 22, 2013 at 13:32

4 Answers 4

2

From you description, it appears that you have gotten to the point where you can open the process with SE_DEBUG. At this point you now have a handle to the target process.

What your code appears to be missing is the use of ReadProcessMemory.

First we need to look at the definition of ReadProcessMemory:

BOOL WINAPI ReadProcessMemory(
          _In_   HANDLE hProcess,
          _In_   LPCVOID lpBaseAddress,
          _Out_  LPVOID lpBuffer,
          _In_   SIZE_T nSize,
          _Out_  SIZE_T *lpNumberOfBytesRead);

This function essentially gives you the ability to copy a block of memory from one process space into your process space. So you need to use this method to read a block of memory the size of the data structure you wish to read into your process space, then you can reinterpret the memory block as that data type.

So semi pseudocode for reading an unsigned int from your target process looks like this:

unsigned int ReadUInt(HANDLE process, const void * address)
{
    // Add parameter validation

    unsigned char buffer[sizeof(unsigned int)] = {};
    size_t bytesRead = 0;

    BOOL res = ::ReadProcessMemory(process,  // The handle you opened with SE_DEBUG privs
                                   address,  // The location in the other process
                                   buffer,   // Where to transfer the memory to
                                   sizeof(unsigned int), // The number of bytes to read
                                   &bytesRead); // The number of bytes actually read

    if (!res)
    {
        // Deal with the error
    }

    if (bytesRead != sizeof(unsigned int))
    {
        // Deal with error where we didn't get enough memory
    }

   return *reinterpret_cast<unsigned int *>(buffer);
}

Instead of using this line:

unsigned int * theValue = (unsigned int*) 0xDE123F00;

You would do this:

unsigned int theValue = ReadUInt(hproc, 0xDE123F00);

Keep in mind that this requires that you know the size and memory layout of the types you are trying to read. Simple types that are contained in contiguous memory can be retrieved in a single ReadProcessMemory call. Types that contain pointers as well as values will require you to make extra calls to ReadProcessMemory to find the values referenced by the pointers.

7
  • As I read the Q, asker knows all about ReadProcessMemory, has succeeded in using it, but is being told not to use it, and instead access the other process memory using plain pointer de-referencing. Obviously that's nonsense. Jun 21, 2013 at 22:52
  • Well, this is the read part. The write part is done by using WriteProcessMemory. The allocating new memory part, if it is necessary is done using VirtualAlloc. What he is being asked to do is totally doable, after all, the debugger lets me read and modify data in a separate process. The real sticking point is how to find that base address in the other process. One way is to have the target process export a symbol in its export table pointing to the fixed address space. Jun 21, 2013 at 22:55
  • Yes, but the asker already knows all of that and has been told to do it a different way. Which happens to be impossible. That's my point. Jun 21, 2013 at 22:58
  • Perhaps it was the manner I read the question. I didn't get the impression that the asker had connected the dots here. If the request is to be able to dereference a pointer in a different process virtual memory context, the only way I know how to do that is in kernel space. If they just want a program that lets them manipulate data in another process, this is how to do it. Jun 21, 2013 at 23:04
  • I think it is the superior tutors that cannot connect the dots. The asker seems to be many steps ahead of them!! Jun 21, 2013 at 23:06
2

Each process has its own virtual address space. An address in one process only has meaning in that process. De-referencing a pointer in C++ code will access the virtual address space of the executing process.

When you de-referenced the pointer in your code you were actually attempting to access memory in your process. No amount of wishful thinking on the part of your tutors can make pointer de-reference access memory in another process.

If you wish to read and write memory from other processes then you must use ReadProcessMemory and WriteProcessMemory.

I don't think you really need to go to all those lengths with tokens and privileges. If I recall correctly you add the debug privilege, call OpenProcess and go straight to it. And I think you can typically skip adding the privilege.

Some search did yield the first answer: using ReadProcessMemory and WriteProcessMemory one can easily change values in the memory of another process without any need to get debug privileges. What my tutors want, however, is to have the ability to define pointers (let's say unsigned int) which should point into the memory space of the debuggee process, effectively holding the base addresses I wrote about earlier. They really want this and I couldn't even talk this out of them so I'm stuck to do this at the end...

What they want is impossible. I suggest you tell them to get a better understanding of virtual memory before making impossible requirements!


@Cody Gray helpfully mentions memory mapped files. If debuggee and debugger co-operate then they can use memory mapped files to share a common region of memory. In that situation then both process can map the memory into their virtual address space and access it in the normal manner.

I rather assumed that your debuggee was an unwilling victim, but if it is prepared to co-operate then sharing memory could be an option.

Even then you'd need to be careful with any pointers in that shared memory because the memory would, in general, be mapped onto different virtual addresses in each process.

7
  • This is the correct answer. The only exception to this is shared memory regions. If two processes share a particular region of memory and both have the necessary privileges, then one process can directly modify the memory "seen" by the other process. It's not clear to me if that's what the asker is hoping to achieve, though. This is another one of those weird questions like "I want to do x. I found that you do it via y. But I don't want to use y. How do I do x?" Jun 21, 2013 at 22:52
  • @Cody I had not thought of memory mapping. Of course it requires both processes to cooperate. And it does not sounde like that is the scenario here. Jun 21, 2013 at 22:55
  • Well, I should have mentioned that I have enough knowledge in how the MMU works and that it's normally impossible to access addresses not within your own context. I also know about shared memory and using it frequently in my other projects. But thats still very confusing because some say it IS possible, and others refute. How does the debugger access the memory of the debuggee then? I can't bring myself to believe that the debugger is using ReadMemory/WriteMemory to show the values :S
    – Ahnihmuhs
    Jun 21, 2013 at 23:13
  • It's clear that you understand virtual memory, but then there is that attempt in the Q to read from the other process using pointer de-ref. Debuggers use ReadProcessMemory and WriteProcessMemory. Jun 21, 2013 at 23:18
  • Oh, okay, then I have to tell my superiors that the way they wanted to have it implemented isn't possible, well, no surprise for me, I knew something like this would happen from the very start :D
    – Ahnihmuhs
    Jun 21, 2013 at 23:23
1

I think you are trying to access kernel land memory range and hence the exception.

The user land range is from 0x00000000 - 7FFFFFFF, so try accessing in this range, as anything above is kernel space.

I am assuming you are on a 32-bit machine.

Check User Space and System Space (Microsoft Docs).

7
  • Ah sry, I gave a rather bad example there, the address has to be 0x00DE123F, thus being in user space.
    – Ahnihmuhs
    Jun 21, 2013 at 22:21
  • 1
    0x00DE123F should work , are you sure you have admin privs.Also 0x80000000 to 0xFFFFFFFF is kernel space. 0xDE123F00 is kernel space. Jun 21, 2013 at 22:24
  • on a 32 bit machine that is! Jun 21, 2013 at 22:27
  • 1
    you can create a user land process with debug privilages CreateProcess using the dwCreationFlags parameter , setting it to DEBUG_PROCESS. see - msdn.microsoft.com/en-us/library/windows/desktop/… Jun 21, 2013 at 22:40
  • 1
    @user You are missing the point. The asker is hoping to read and write in the other process using *theValue. Jun 21, 2013 at 22:49
0

You can create a type that behaves like a pointer by implementing the appropriate operators, just like shared_ptr does:

foreign_ptr<int> ptr{0xDE123F00};


int a = *ptr;
*ptr = 1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.