Mach Injection: System call open is not getting interposed when injecting in Excel - code-injection

I hooked system calls open, read, write, lstat etc. using osxinj project. Injected this into TextEdit application provided by apple and everything worked fine. When I opened new file using textedit, opencallback was called and messages were logged in system.log file.
typedef int (*open_type)(const char *, int, mode_t);
open_type open_func = 0;
int opencallback(const char* path, int oflag, mode_t mode)
{
syslog(LOG_ALERT, "In open...");
int returnVal = open_func(path, oflag, mode);
syslog(LOG_ALERT,"Open, ends\n");
return returnVal;
}
Injected into Excel and tried to override open system call using below code:
void* func_ptr = dlsym( RTLD_NEXT, "open");
if (func_ptr)
{
open_func = (open_type)func_ptr;
mach_error_t me = mach_override_ptr( func_ptr,
(void*)&opencallback,
(void**)&open_func);
}
opencallback is called when injecting to TextEdit but it is not getting called when injected in Microsoft Excel. But code written on same lines for other system calls read, write, lstat are getting interposed when injected in Excel.
Any thoughts on why open is not getting interposed when injected to Excel.

Finally, I got my code running. I am posting answer hoping it might help somebody.
I hooked __open which is an alias for open and it worked fine for i386 application like excel.

Related

Crash inside http_client constructor (Casablanca SDK)

I'm trying to use Casablanca to consume a REST api.
I've been following the microsoft tutorial, how ever i'm getting a crash and I cannot figure it out.
I'm using visual studio 2017 with C++11
I've codded a function GetRequest() that do work when used in a new empty project, but when I try to use it on my Project (Very big project with millions of code lines).
I'm crashing in the constructor of http_client, in the file xmemory0 line 118.
const uintptr_t _Ptr_container = _Ptr_user[-1];
This is a link to the callstack : https://i.imgur.com/lBm0Hv7.png
void RestManager::GetRequest()
{
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("XXX/XXX.svc/"));
// Build request URI and start the request.
uri_builder builder(U("/IsLive"));
builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::GET, builder.to_string());
})
// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
}
}
EDIT : I just want to add that the http_client constructor is the issue. It always crash inside it no matter what I send as parameter.
The wierd thing is that it's not crashing when i just make a main() that call this function.
I guess it must be due to some memory issues, however I have no idea how could I debug that.
Does anyone would have an idea about it?
Thanks and have a great day!
I've experienced a similar issue on ubuntu. It works in an empty project, but crashes randomly when put into an existing large project, complaining memory corruptions.
Turns out that the existing project loaded a proprietary library, which is using cpprestsdk (casablanca) internally. Even cpprestsdk is static linked, its symbols are still exported as Weak Symbols. So either my code crashes, or the proprietary library crashes.
Ideally, my project can be divided into several libraries, and load them with RTLD_LOCAL to avoid symbol clashes. But the proprietary library in my project only accept RTLD_GLOBAL, otherwise it crashes... So the import order and flags become important:
dlopen("my-lib-uses-cpprest", RTLD_LOCAL); //To avoid polluting the global
dlopen("proprietary-lib-with-built-in-cpprest", RTLD_GLOBAL); //In my case, this lib must be global
dlopen("another-lib-uses-cpprest", RTLD_DEEPBIND); //To avoid being affected by global
"it will probably never concern anyone."
I agree with that.
I guess this issues was very specific, and it will probably never concern anyone, but still I'm going to update on everything I found out about it.
On this project, we are using custom allocator, if i'm not wrong, it's not possible to give our custom allocator to this lib, which result to many random crash.
A good option to fix it would be to use the static version to this lib, however, since we are using a lot of dynamic lib, this option wasn't possible for us.
If you are on my case, I would advice to use the libcurl and rapidjson, it's a bit harder to use, but you can achieve the same goal.

Simple UDP socket in VC++ MFC

I have been trying to write a working program that takes in data from a UDP socket and displays it in an edit control box as you receive the data (My exposure to c++ is also only about a week :P have only done embedded C code before). I have a working program that can send and output data on a button click but I want something that can do it in real time. The aim is scale this up into a larger GUI program that can send control data to hardware and get responses from them.
I have run into various problems including:
The program just not executing my OnReceivefunction (derived from
CAsyncSocket)
Getting the OnReceive function to run on a separate thread so that it can still run after a button has been clicked sending a control packet to the client then waiting for a response in a while loop
Not being able to output the data in the edit box (tried using both CEdit and CString)
ReplaceSel error saying that the type char is incompatible with LPCTSTR
My code is based on this codeproject.com tutorial, being almost exactly what I want but I get the error in 4.
EDIT: the error in 4. disappears when I change it to a TCHAR but then it outputs random chinese characters. The codeproject.com tutorial outputs the correct characters regardless of char or TCHAR declaration. When debugged my code has type wchar_t instead type char like the other code.
Chinese output
In the working program echoBuffer[0] the character sent and displayed was a 1
UINT ReceiveData(LPVOID pParam)
{
CTesterDlg *dlg = (CTesterDlg*)pParam;
AfxSocketInit(NULL);
CSocket echoServer;
// Create socket for sending/receiving datagrams
if (echoServer.Create(12345, SOCK_DGRAM, NULL) == 0)
{
AfxMessageBox(_T("Create() failed"));
}
for (;;)
{ // Run forever
// Client address
SOCKADDR_IN echoClntAddr;
// Set the size of the in-out parameter
int clntAddrLen = sizeof(echoClntAddr);
// Buffer for echo string
char echoBuffer[ECHOMAX];
// Block until receive message from a client
int recvMsgSize = echoServer.ReceiveFrom(echoBuffer, ECHOMAX, (SOCKADDR*)&echoClntAddr, &clntAddrLen, 0);
if (recvMsgSize < 0)
{
AfxMessageBox(_T("RecvFrom() failed"));
}
echoBuffer[recvMsgSize] = '\0';
dlg->m_edit.ReplaceSel(echoBuffer);
dlg->m_edit.ReplaceSel(_T("\r\n"));
}
}
After reading the link that #IInspectable provided about working with strings and checking the settings differences between the two programs it became clear that the issue lay with an incorrect conversion to UNICODE. My program does not require it so I disabled it.
This has cleared up the issue in 4. and provided solutions for 2 and 3.
I also think I know why another instance of my program would not run OnReceivein 1. because that file was not being defined by one that was already being run by the program, but that is now irrelevant.

System call implementation in Pintos

I want to implement the already defined system calls in PintOS ( halt(), create()...etc defined in pintos/src/lib/user/syscall.c ). The current system call handler in pintos/src/userprog/syscall.c does not do anything. How do I make a process that makes system calls. Further I need to myself add a few system calls. How do I proceed in that too. But first I need to implement the existing system calls.
The default implementation in pintos terminates the calling process.
goto this link.There is explanation on where to modify the code to implement the system calls.
The "src/examples" directory contains a few sample user programs.
The "Makefile" in this directory compiles the provided examples, and you can edit it compile your own programs as well.
This program/process when run will inturn make a system call.
Use gdb to follow the execution of one such program a simple printf statement will eventually call write system call to STDOUT file.
The link given also has pointers on how to run pintos on gdb, my guess is you are using either bochs or qemu.In any case just run the gdb once with a simple hello world program running on pintos.
This will give u an idea of how the system call is made.
static void
syscall_handler (struct intr_frame *f)// UNUSED)
{
int *p=f->esp;
switch(*p)
case *p=SYS_CREATE // NUMBER # DEFINED
const char *name=*(p+1); //extract the filename
if(name==NULL||*name==NULL)
exit(-1);
off_t size=(int32_t)*(p+2);//extract file size
f->eax=filesys_create(name,size,_FILE); //call filesys_create
//eax will have the return value
}
This is pseudo code for sys_create .. all file system related system call are very trivial,
Filesys realted system calls like open read write close needs you to translate file to their corresponding fd (file descriptor). You need to add a file table for each process to keep track this, this can either be preprocess data or a global data.(UR choice),
case (*p==SYS_WRITE)
{
// printf("wite syscall\n");
char *buffer=*(p+2);
unsigned size=*(p+3);
int fd=*(p+1);
// getiing the fd of specified file
struct file *fil= thread_current()->fdtable[fd];/ my per thread fdtable
if(fd==1) goto here;
if(is_directory(fil->inode)){
exit(-1);
goto done;
}
here:
if(buffer>=PHYS_BASE)exit(-1);
if(fd<0||fd>=128){exit(-1);}
if(fd==0){exit(-1);} // writing to STDIN
if(fd==1) //writing to STDOUT
{
int a=(int)size;
while(a>=100)
{
putbuf(buffer,100);
buffer=buffer+100;
a-=100;
}
putbuf(buffer,a);
f->eax=(int)size;
}
else
if(thread_current()->fdtable[fd]==NULL)
{f->eax=-1;}
else
{
f->eax=file_write(thread_current()->fdtable[fd],buffer,(off_t)size);
}
done: ;
}//printf("write");} /* Write to a file. */
Open - adds anew entry to fdtable and return the fd number u give to the file,
close - remove that entry from fd table
read - similar to write.
The process_create ,wait are not simple to implement...
Cheers :)

Send data from Visual C++ via socket on the same machine

I am currently in a project involving data visualization of a signal captured from a device which has a Visual C++ API. I currently can log each datasample to file, but I'd like to do some sort of plot to screen.
I have had a previous successful experience with a similar job using socket between C++ and Python, but the code was lost. I have the Python socket "receiver" to reuse, but don't have the Visual C++ "sender" to reverse engineer or otherwise copy/paste.
My current Python code, which was working very fine, is:
import SocketServer
class SocketHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
## do something with 'data' here!
server = SocketServer.UDPServer(("192.168.1.23", 8888), SocketHandler)
server.serve_forever()
And the part of the Visual C++ that currently logs to file and I want to send to the socket is:
#include <fstream>
//(...lots of code...)
short int * dataBuff;
unsigned int dataNum;
int isAcqRunning;
int startFromTrg, stopFromTrg;
unsigned int firstSample, lastSample;
int errcode;
int i;
std::ofstream out("./out.txt");
// device->transferData is called inside a loop
// to get data from aquisition hardware's buffer
errcode = device->transferData(&dataBuff, &dataNum, &isAcqRunning,
&startFromTrg, &stopFromTrg,
&firstSample, &lastSample);
if(errcode == 0)
{
printf("\n Acquired samples: %d", dataNum);
for (i=firstSample; i<lastSample; i++)
out<<dataBuff[i]<<'\n'; /////// I'd like to send dataBuff[i] via socket!!
}
//(...lots of more code...)
Possibly useful additional information:
I'm using VisualStudio 2010 in Windows7;
This is the first time I touch C++ code in my life, I use Python almost exclusively;
I haven't have success trying to follow C++ examples from books and sites because, as it appears, C++ and VISUAL C++ are NOT the same thing and can behave very differently :o(
I thank very much for any help, and for reading this.
(EDIT: if there is a better way to do that without any additional complexity overhead for a noob, I would be glad to try. I like the socket stuff because it is language-transparent and solved a previous problem with very good speed)

winsock socket as file handle

i have been scratching my head and been searching for an answer for this for hours now. Basically what I do is open a socket to some other machine and reading the data from it. This socket is than "converted" to a file handle via an fdopen call passing in the int that represent the socket. The resulting file handle is then passed to a bison parser which directly parsed the data received over the socket. All of this works fine on linux. Now I have tried to port this code to windows and I dismally fail. The code looks something like this:
FILE* fileHandle;
#if defined WINCE || defined WIN32
int fd = _open_osfhandle(socket, _O_RDONLY);
if (fileHandle = fdopen(fd, "r")) {
#else
if (fileHandle = fdopen(socket, "r")) {
#endif
... // code to call my parser with fileHandle as argument
The bison/flex parser fails in the windows version since the filehandle seems to point to an empty stream/file. Can anybody point to a comprehensive resource that explains this stuff or hint at an alternative solution?
Thanks and best Regards,
André
In Windows, a socket handle is not a file handle, and you cannot treat it as such in the C API. In Linux, you can. However, in Windows, a socket handle can be passed to the ReadFile/Ex() and WriteFile/Ex() functions, which support numerous handle types, not just files, despite their names.
You need to fake a little bit, but this one works for me - nSocketFd a file descriptor return by socket()
FILE* fpSocket = NULL;
#ifdef WIN32
fpSocket = new FILE;
fpSocket->_file = nSocketFd;
fpSocket->_cnt = 0;
fpSocket->_ptr = NULL;
fpSocket->_base = NULL;
fpSocket->_flag = 0;
#else
// build the file pointer from the file descriptor
fpSocket = fdopen (nSocketFd, "rb+");
#endif