Linux ptrace memory reading & process management - linux

I'm trying to read a processes memory on Linux (Xubuntu, to be precise). I'm pretty new to Linux, though I've done this same read using Win32API ReadProcessMemory() before in Windows. The general idea is that I'm trying to develop some software for a game which will get my stats and upload them to a server, which will track my progress and keep a log of it. The end goal is to make a bot which will automatically play and farm data about the game. In order to do this, I need to be able to access the processes memory. In Windows, that's dead easy. In Linux, it's proving a little more complex.
I've found a memory address which contains information I want to read. The information is an int32, and it is stored at 84a1bd8. I found it using GameConqueror 0.13. The address remains correct after restarting, so it appears there is no ASLR (as there was in Windows). I also know the ProcessID (I can find this using task manager for now, though if someone knows a simple way to get a PID by either ClassName, Exe name, or similar, that would be great too!) So, that looks like it should be all I really need to use PTRACE_PEEKDATA to read the memory, right? Well, that's the problem, it doesn't appear to be. My code looks like this:
#include <iostream>
#include <string>
#include <sys/ptrace.h>
#include <errno.h>
using namespace std;
int main()
{
pid_t pid = 4847;
int addr = 0x84a1bd8;
long ret = ptrace(PTRACE_TRACEME, pid, NULL, NULL);
cout << "ptrace Status: " << ret << endl;
cout << "Errno: " << errno << endl;
ret = ptrace(PTRACE_PEEKDATA, pid, (void*)addr, NULL);
cout << "ptrace Status: " << ret << endl;
cout << "Errno: " << errno << endl;
ret = ptrace(PTRACE_DETACH, pid, NULL, NULL);
cout << "ptrace Status: " << ret << endl;
cout << "Errno: " << errno << endl;
return 0;
}
The output looks like this:
ptrace Status: 0
Errno: 0
ptrace Status: -1
Errno: 3
ptrace Status: -1
Errno: 3
Being quite new to Linux, I don't know where I'm to find error codes and how I can work out what this error actually means, and nor do I know if I am even declaring the address correctly. Should I declare it as an int in it's decimal equivalent? Is there anything I'm missing?
Thanks for your time

Found the solution to be that when using ptrace() you must call in an order:
ptrace(PTRACE_ATTACH, pid, NULL, NULL)
ptrace(PTRACE_PEEKDATA, pid, addr, NULL)
ptrace(PTRACE_DETACH, pid, NULL, NULL)
So the simple answer: You need to attach and detach before and after reading the memory.
It may also be useful to know that between the attach and detach commands, the process will sleep, meaning this method isn't so good for my purpose, but may be useful to others :)
Thanks to #PeterL. for your help.

Related

Reading and writing different files in their own threads from my main loop in C++11

I am trying to understand, then, write some code that has to read from, and write to many different files and do so from the main loop of my application. I am hoping to use the C++11 model present in VS 2013.
I don't want to stall the main loop so I am investigating spinning off a thread each time a request to write or read a file is generated.
I've tried many things including using the async keyword which sounds promising. I boiled down some code to a simple example:
#include <future>
#include <iostream>
#include <string>
bool write_file(const std::string filename)
{
std::cout << "write_file: filename is " << filename << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
std::cout << "write_file: written" << std::endl;
return true;
}
int main(int argc, char* argv[])
{
const std::string filename = "foo.txt";
auto write = std::async(std::launch::async, write_file, filename);
while (true)
{
std::cout << "working..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "write result is " << write.get() << std::endl;
}
}
I'm struggling to understand the basics but my expectation would be that this code would constantly print "working..." and interspersed in the output would be the write_file start and end messages. Instead, I see that the write_file thread seems to block the main loop output until the timer expires.
I realize I need to also consider mutex/locking on the code to actually write the file but I would like to understand this bit first.
Thank you if you can point me in the right direction.
Molly.
write.get() will wait for the async task to finish. You want to use wait_for() instead:
do {
std::cout << "working...\n";
} while(write.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready);
std::cout << "write result is " << write.get() << "\n";

cross-platform self-modifying code (Intel/AMD only)

I have searched considerably for an answer to this without success.
In a debugger, one may write instructions and then execute them.
This requires special permissions in the executable image.
I seek to perform this function without the debugger.
Please show me an ASM "hello world" program that has self-modifying code
(perhaps replacing a series of 090H with code to uppercase the 'h' in hello)
and the commands necessary to enable its execution.
The next 2 lines are the before and after machine code for the h->H replacement.
90 90 90 90 90 90 90 90 90 90 90 ; 11 NOPs
8a 26 50 00 80 e4 df 88 26 50 00 ; MOV AH,[BX]; AND AH,0DFH; MOV [BX],AH;
I have complete competence and confidence constructing iAPX86 machine code.
My problem is convincing linux, darwin/yosemite, and windows to allow execution.
In the end, I want to be able to construct and modify an executable
on-the-fly for a new language I am writing.
The architecture of the new language has no parallels in modern practice.
I expect much criticism for flying in the face of convention,
but I will proceed with my plans notwithstanding.
Thank you all for taking my question seriously.
This code works! It turned out to be far simpler than I thought;
without special compiler flags, or ELF or MACHO specialization.
In iAPX86 machine code, C3 is near RET without a return value.
I have a few improvements to make, listed after the code,
but this question, as asked, is completely answered to my satisfaction.
working code
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
typedef void (*fptr)();
int main(int argc, char **argv) {
try {
fptr p = (fptr)"\xc3";
p();
cout << "Hello world" << endl;
}
catch (const int e) { cout << "int exception: " << e << endl; }
catch (const char e) { cout << "char exception: " << e << endl; }
catch (const string &e) { cout << "string exception: " << e << endl; }
catch (...) { cout << "default exception" << endl; }
exit(0);
}
TODO
bracket opcode strings with safety code.
prevent certain opcodes from appearing in strings.
catch signals as well as exceptions.

Error on the first code I wrote on C++. Don't know what's happening

I wrote this code for my class and when i debug it runs but shuts down within seconds i dont know what i'm doing wrong here. I am really new to C++ so.
here is the code:
#include "stdafx.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
double gallons;
double startmile;
double endmile;
double totalmilestravelled;
cout << "This Program Calculates your vehicle's gas mileage on this trip\n" << endl;
cout << "What is the number of gallons consumed on the trip: ";
cin >> gallons;
cout << "\nWhat was your ending mile?";
cin >> endmile;
cout << "\nWhat was your starting mile?";
cin >> startmile;
totalmilestravelled = endmile-startmile;
double mpg = totalmilestravelled/gallons;
cout << "your gas mileage is: " << mpg << endl;
return 0;
}
and this is the error:
The program '[9848] gasmileage.exe: Native' has exited with code 0 (0x0).
That's not an error. The program exited normally. When you run a program, it executes and exits with an exit code specified by the program. In this case you return 0, so the program exits with code 0. If you want the program to "pause" to allow you to see the result of the program before it closes, add this just before the return statement:
cin.ignore(128, '\n');
cin.get();
The first line discards newlines that were left over in the standard input. Don't worry about this too much until you learn more about the input stream, but you need to do this if you are attempting to read a string after reading numeric input from the user. The second line will prompt the user for some input (push return). You don't care what the input is, and you aren't going to do anything with the input. You just want to force the program to wait for user input so that you can see what's going on before continuing with the program (which in this case the program immediately exit).
Think about programs that say "Press any key." It's the same thing we're doing here. Giving the user a moment to view the output.

C++ Delete Error -- _unlock_fhandle throwing exception?

I have a straightforward problem but I don't understand why I have it.
I would greatly appreciate any insight.
I wrote this code to test that I was correctly creating and using DLLs in Visual Studio 2010 under Win 7 64bit that could execute on Windows XP. The code executes correctly, and because it is a small test program freeing the allocated memory is not critical, but certainly will be in the future.
I am implicitly calling the DLL, as I say, it appears to work just fine. When I add the line "delete dllMsg;" to toyUseDLL.cpp it crashes, and the debugger shows _unlock_fhandle in osfinfo.c.
If it's relevant I am compiling the program with /MT to embed the runtime library (for a small handful of not important reasons).
It seems pretty obvious that I'm deallocating something not allocated, but the program output is correct since the pointers are passing the referenced memory locations. The only thing I can think of is that my pointer isn't valid, and it's only working by pure chance that the memory wasn't overwritten.
Thanks for any help, I'm pretty new to C++ and have already found a lot of great help on this site, so thanks for everyone who has posted in the past!! :-)
msgDLL.h
#include <string>
using namespace std;
namespace toyMsgs {
class myToyMsgs {
public:
static __declspec(dllexport) string* helloMsg(void);
static __declspec(dllexport) string* goodbyeMsg(void);
};
}
msgDLL.cpp
#include <iostream>
#include <string>
#include "msgDLL.h"
using namespace std;
namespace toyMsgs {
string* myToyMsgs::helloMsg(void) {
string *dllMsg = new string;
dllMsg->assign("Hello from the DLL");
cout << "Here in helloMsg, dllMsg is: \"" << *(dllMsg) << "\"" << endl;
return (dllMsg);
}
string* myToyMsgs::goodbyeMsg(void) {
string *dllMsg = new string;
dllMsg->assign("Good bye from the DLL");
cout << "Here in goodbyeMsg, dllMsg is: \"" << *(dllMsg) << "\"" << endl;
return (dllMsg);
}
}
toyUseDLL.cpp
#include <iostream>
#include <string>
#include "stdafx.h"
#include "msgDLL.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
string myMsg;
string *dllMsg;
myMsg.assign ("This is a hello from the toy program");
cout << myMsg << endl;
dllMsg = toyMsgs::myToyMsgs::helloMsg();
cout << "Saying Hello? " << *(dllMsg) << endl;
delete dllMsg;
myMsg.assign ("This is the middle of the toy program");
cout << myMsg << endl;
dllMsg = toyMsgs::myToyMsgs::goodbyeMsg();
cout << "Saying goodbye? " << *(dllMsg) << endl;
myMsg.assign ("This is a goodbye from the toy program");
cout << myMsg << endl;
return 0;
}
Program Output:
This is a hello from the toy program
Here in helloMsg, dllMsg is: "Hello from the DLL"
Saying Hello? Hello from the DLL
This is the middle of the toy program
Here in goodbyeMsg, dllMsg is: "Good bye from the DLL"
Saying goodbye? Good bye from the DLL
This is a goodbye from the toy program
The problem is that you are using /MT to compile your EXE and DLL. When you use /MT, each executable gets its own copy of the C runtime library, which is a separate and independent context. CRT and Standard C++ Library types can't safely be passed across the DLL boundary when both DLLs are compiled /MT. In your case the string is allocated by one CRT (on its private OS Heap), and freed by the EXE (which has a different heap) causing the crash in question.
To make the program work, simply compile /MD.
General advice: /MT is almost never the right thing to do (for a large handful of relatively important reasons including memory cost, performance, servicing, security and others).
Martyn
There is some good analysis here Why does this program crash: passing of std::string between DLLs

Does Creating a New Thread Duplicate File Descriptors and Socket Descriptors in Linux?

Everyone knows the classic model of a process listening for connections on a socket and forking a new process to handle each new connection. Normal practice is for the parent process to immediately call close on the newly created socket, decrementing the handle count so that only the child has a handle to the new socket.
I've read that the only difference between a process and a thread in Linux is that threads share the same memory. In this case I'm assuming spawning a new thread to handle a new connection also duplicates file descriptors and would also require the 'parent' thread to close it's copy of the socket?
No. Threads share the same memory, so they share the same variables. If you close socket in parent thread, it will be also closed in child thread.
EDIT:
man fork: The child inherits copies of the parent’s set of open file descriptors.
man pthreads: threads share a range of other attributes (i.e., these attributes are process-wide rather than per-thread): [...] open file descriptors
And some code:
#include <cstring>
#include <iostream>
using namespace std;
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
// global variable
int fd = -1;
void * threadProc(void * param) {
cout << "thread: begin" << endl;
sleep(2);
int rc = close(fd);
if (rc == -1) {
int errsv = errno;
cout << "thread: close() failed: " << strerror(errsv) << endl;
}
else {
cout << "thread: file is closed" << endl;
}
cout << "thread: end" << endl;
}
int main() {
int rc = open("/etc/passwd", O_RDONLY);
fd = rc;
pthread_t threadId;
rc = pthread_create(&threadId, NULL, &threadProc, NULL);
sleep(1);
rc = close(fd);
if (rc == -1) {
int errsv = errno;
cout << "main: close() failed: " << strerror(errsv) << endl;
return 0;
}
else {
cout << "main: file is closed" << endl;
}
sleep(2);
}
Output is:
thread: begin
main: file is closed
thread: close() failed: Bad file descriptor
thread: end
In principle, Linux clone() can implement not only a new process (like fork()), or a new thread (like pthread_create perhaps), but also anything in between.
In practice, it is only ever used for one or the other. Threads created with pthread_create share the file descriptors with all other threads in the process (not just the parent). This is non-negotiable.
Sharing a file descriptor and having a copy is different. If you have a copy (like fork()) then all copies must be closed before the file handle goes away. If you share the FD in a thread, once one closes it, it's gone.
On Linux threads are implemented via the clone syscall using the CLONE_FILES flag:
If CLONE_FILES is set, the calling
process and the child processes share
the same file descriptor table. Any
file descriptor created by the calling
process or by the child process is
also valid in the other process.
Similarly, if one of the processes
closes a file descriptor, or changes
its associated flags (using the
fcntl(2) F_SETFD operation), the other
process is also affected.
Also have a look at the glibc source code for the details of how it is used in createthread.c:
int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGNAL
| CLONE_SETTLS | CLONE_PARENT_SETTID
| CLONE_CHILD_CLEARTID | CLONE_SYSVSEM
#if __ASSUME_NO_CLONE_DETACHED == 0
| CLONE_DETACHED
#endif
| 0);

Resources