c++ Injected DLL vars getting corrupted - c++

I'm currently trying to add some functionality to a basic server application by injecting a DLL and detouring several functions and I'm having a problem with a stored IP address getting corrupted in-between 2 calls.
First I detour 'accept' and parse some values then enter them into a connection class and add it to a list.
Accept detour function:
std::list<Connection*> ConnectionsList;
SOCKET WINAPI MyAccept(SOCKET s, sockaddr *addr, int *addrlen)
{
...
ConnectionsList.push_back(new Connection(ClientSocket, ipstr));
...
}
connection class:
SOCKET s;
char * ipAddress;
char * playerName;
Connection::Connection(SOCKET sock, char * address)
{
s = sock;
ipAddress = address;
}
I've also detoured 'closesocket' at which point I'd like to remove the socket from the list of connections. If I breakpoint on this function the IP address appears to be corrupted.
Does anyone know why this is happening?

ipAddress = address; will just copy the pointer. If something else changes what it points to, you will be in trouble.
Since this is C++ it might be safest to use a std::string.
std::string ipAdreess;
...
ipAddress = address;
Otherwise, stdcpy into a buffer big enough.
BTW, what deletes all the Connection* from the list?

try to protect your ConnectionList etc static/global variable with a lock.

Related

Convert IPv6 to IPv4 format in c++?

I am maintaining an old system which runs fine on IPv4 format and i found out that the listener did not trigger when the requestor is coming from IPv6. I have the following line of code
SOCKADDR_IN SocketAddr;
INT nBufferSize=sizeof(SocketAddr);
hConnectSocket=WSAAccept(m_hListenSocket,(SOCKADDR *)&SocketAddr,&nBufferSize,NULL,NULL);
if (hConnectSocket==INVALID_SOCKET) return false;
I also googled and i know i should be using SOCKADDR_IN6 for IPv6. Is it possible to convert SOCKADDR_IN6 to SOCKADDR_IN format so that the rest of the application will work?
Thanks.
You can't convert all IPv6 addresses to IPv4 - there are more IPv6 addresses than IPv4 addresses. The best way to tackle this issue is to update/upgrade your application so it understand and store IPv6 addresses. This thread might be useful.
I implemented some time ago a solution that can work with IPV4 and IPV6 addresses. I did even encapsulate that property from the outside world.
The rest of the program should only know about sockets. And if your code accepts an address in the IPV6 or IPV4 format does not really matter /after accepting).
The important point is that you need to specify the ai_family with AF_UNSPEC. Then it will handle both address families. And for the accept function, you can handover a parameter big enough to hold both address types.
I am not sure, but maybe that could help you.
Please see the following code snippet that I developed some years ago in C++98.
// The following structures are used in order to be independent from the internet address families
// e.g. IPV4 or IPV6. The basic original functions have been designed for IPV4 only.
// But now we are in the age of IPV6. And we need to have means to deal with both address types
// So we have one Data type, that can hold both IPV4 and IPV6 (because it has the length of the
// larger IPV6 address). The pointer of this structure can be casted to the original data type
// that the functions always expected.
// The first field in the structures denotes the IP Address Family
// This is the big storage that can hold either a IPV4 or a IPV6 address
typedef struct sockaddr_storage SocketAddressStorage;
// This Type can hold the length of the IP Address container
typedef socklen_t SocketAddressStorageLength;
// This type is the Socket Address that OS function expect. We will cast the pointer of the big
// data type to this one
typedef struct sockaddr SocketAddress;
// The next 2 are specific address containers for either IPV4 or IPV6.
// One of them will be a part of the big "struct sockaddr_storage"
typedef struct sockaddr_in SocketAddressInternetIPV4;
typedef struct sockaddr_in6 SocketAddressInternetIPV6;
// We use the big structure that can hold an IPV4 and IPV6 address
// because we do not know, who is contacting this node
SocketAddressStorage addressOfCommunicationPartner;
// Get the length of the above define data structure
SocketAddressStorageLength socketAddressStorageLength = sizeof(addressOfCommunicationPartner);
// Accept the connection request from a client
// handle is the filedescriptor bound to this node and listening for connection requests
// The function will return a new file descriptor for the connected socket. This is a specific socket
// for the just established connection. The handle will continue to listen for more connection requests
// So this is a factory. We are listening for connection requests and if we get one, we create a new
// file descriptor for the specific communication purposes
// The information of the foreign node will be put in the "addressOfCommunicationPartner"
// Accept the connection request from a client
//lint -e{740,929,1924}
const Handle connectionHandle = accept(handle, reinterpret_cast<SocketAddress *>(&addressOfCommunicationPartner), &socketAddressStorageLength);
// Check, if connection could be established and we have a valid file descriptor
if (connectionHandle > null<Handle>())
{
// Now we want to get the IP address of the partner. Can be IPv4 or IPv6
// The following old style C String can hold both IPv4 and IPv6 address strings
mchar ipAddressCString[INET6_ADDRSTRLEN+1];
// This is a pointer into the address structure of the communication partner
// It points either to sin_addr for IPv4 or sin6_addr for IPv6
const void *ipAddressPEitherV4orV6;
// This will contain the IP Version as a string
std::string ipVersion;
// Now check, what family, what type of IP adress we have
//lint -e{911,1960}
if (AF_INET == addressOfCommunicationPartner.ss_family)
{
// So, it is IPv4. Remember that
ipVersion = "IPv4";
// Get a pointer to the appropriate element of the struct, which contains IP address info. And this depending on the IP Family/Type
//lint --e{740,925,929} Yes indeed, an unusual pointer cast
ipAddressPEitherV4orV6 = static_cast<const void *>( &((reinterpret_cast<const SocketAddressInternetIPV4 *const>(&addressOfCommunicationPartner))->sin_addr) );
}
else
{
// It is IPv6. Remember that
ipVersion = "IPv6";
// Get a pointer to the appropriate element of the struct, which contains IP address info. And this depending on the IP Family/Type
//lint --e{740,925,929} Yes indeed, an unusual pointer cast
ipAddressPEitherV4orV6 = static_cast<const void *>( &((reinterpret_cast<const SocketAddressInternetIPV6 *const>(&addressOfCommunicationPartner))->sin6_addr) );
}
// Convert native IP address format to readable C-String
//lint -e{917,1960}
if (null<mchar *>() == inet_ntop(addressOfCommunicationPartner.ss_family, ipAddressPEitherV4orV6, ipAddressCString, sizeof(ipAddressCString)))
{
// If this did not work then we will not show any IP Address. We can live with that
ipAddressCString[0] = '\x0';
}
// Debug Output
{
static long i=1;
ui << "Connection accepted " << i << " " << ipVersion << " " << ipAddressCString << " " << machineNetworkAddressInfo.portNumberString << std::endl;
i++;
}
// So. The connection request was established. We gathered all information
// Create a new TCP connection
TcpConnectionBase *tcpConnectionBase =tcpConnectionFactory->createInstance(machineNetworkAddressInfo.portNumberString, connectionHandle);
// And put a pointer to it in our internal list of Tcp Connection
tcpConnection.push_back(tcpConnectionBase);
You may find the rest here

How to get client IP Address with C++ in thrift

I am implementing a thrift-based (0.4.0) service in C++ at the moment and encountered a question:
Is there a way to get the client's IP address from inside a service method implementation? I am using a TNonblockingServer.
Thanks in advance!
In TNonblockingServer, When TProcessor::process() is called the TProtocol.transport is a TMemoryBuffer, so aquiring client ip address is impossible.
But We can extend class TServerEventHandler, method TServerEventHandler::processContext() is called when a client is about to call the processor.
static boost::thread_specific_ptr<std::string> thrift_client_ip; // thread specific
class MyServerEventHandler : public TServerEventHandler
{
virtual void processContext(void* serverContext, boost::shared_ptr<TTransport> transport)
{
TSocket *sock = static_cast<TSocket *>(transport.get());
if (sock)
{
//thrift_client_ip.reset(new string(sock->getPeerAddress())); // 0.9.2, reused TNonblockingServer::TConnection return dirty address, see https://issues.apache.org/jira/browse/THRIFT-3270
sock->getCachedAddress(); // use this api instead
}
}
};
// create nonblocking server
TNonblockingServer server(processor, protocolFactory, port, threadManager);
boost::shared_ptr<MyServerEventHandler> eventHandler(new MyServerEventHandler());
server.setServerEventHandler(eventHandler);
Ticket THRIFT-1053 describes a similar request for Java. The solution is basically to allow access to the inner (endpoint) transport and retrieve the data from it. Without having it really tested, building a similar solution for C++ should be easy. Since you are operating on Thrift 0.4.0, I'd strongly recommend to look at current trunk (0.9.3) first. The TBufferedTransport, TFramedTransport and TShortReadTransport already implement
boost::shared_ptr<TTransport> getUnderlyingTransport();
so the patch mentioned above may not be necessary at all.
Your TProcessor-derived class gets a hold of both transports when process() gets called. If you overwrite that method you should be able to manage access to the data you are interested in:
/**
* A processor is a generic object that acts upon two streams of data, one
* an input and the other an output. The definition of this object is loose,
* though the typical case is for some sort of server that either generates
* responses to an input stream or forwards data from one pipe onto another.
*
*/
class TProcessor {
public:
// more code
virtual bool process(boost::shared_ptr<protocol::TProtocol> in,
boost::shared_ptr<protocol::TProtocol> out,
void* connectionContext) = 0;
// more code
#ifndef NONBLOCK_SERVER_EVENT_HANDLER_H
#define NONBLOCK_SERVER_EVENT_HANDLER_H
#include <thrift/transport/TSocket.h>
#include <thrift/server/TServer.h>
namespace apache{
namespace thrift{
namespace server{
class ServerEventHandler:public TServerEventHandler{
void* createContext(boost::shared_ptr<TProtocol> input, boost::shared_ptr<TProtocol> output){
(void)input;
(void)output;
return (void*)(new char[32]);//TODO
}
virtual void deleteContext(void* serverContext,
boost::shared_ptr<TProtocol>input,
boost::shared_ptr<TProtocol>output) {
delete [](char*)serverContext;
}
virtual void processContext(void *serverContext, boost::shared_ptr<TTransport> transport){
TSocket *tsocket = static_cast<TSocket*>(transport.get());
if(socket){
struct sockaddr* addrPtr;
socklen_t addrLen;
addrPtr = tsocket->getCachedAddress(&addrLen);
if (addrPtr){
getnameinfo((sockaddr*)addrPtr,addrLen,(char*)serverContext,32,NULL,0,0) ;
}
}
}
};
}
}
}
#endif
boost::shared_ptr<ServerEventHandler> serverEventHandler(new ServerEventHandler()
server.setServerEventHandler(serverEventHandler);

Accessing the member of a class that is part of a WiFi listener callback member function

I have a WiFi Listener registered as a callback (pointer function) with a fixed 3rd party interface. I used a static member of my function to register the callback function and then that static function calls a nonstatic member through a static cast. The main problem is that I cannot touch the resulting char * buff with any members of my class nor can I even change an int flag that is also a member of my class. All result in runtime access violations. What can I do? Please see some of my code below. Other problems are described after the code.
void *pt2Object;
TextWiFiCommunication::TextWiFiCommunication()
{
networkDeviceListen.rawCallback = ReceiveMessage_thunkB;
/* some other initializing */
}
int TextWiFiCommunication::ReceiveMessage_thunkB(int eventType, NETWORK_DEVICE *networkDevice)
{
if (eventType == TCP_CLIENT_DATA_READY)
static_cast<TextWiFiCommunication *>(pt2Object)->ReceiveMessageB(eventType,networkDevice);
return 1;
}
int TextWiFiCommunication::ReceiveMessageB(int eventType, NETWORK_DEVICE *networkDevice)
{
unsigned char outputBuffer[8];
// function from an API that reads the WiFi socket for incoming data
TCP_readData(networkDevice, (char *)outputBuffer, 0, 8);
std::string tempString((char *)outputBuffer);
tempString.erase(tempString.size()-8,8); //funny thing happens the outputBuffer is double in size and have no idea why
if (tempString.compare("facereco") == 0)
cmdflag = 1;
return 1;
}
So I can't change the variable cmdflag without an access violation during runtime. I can't declare outputBuffer as a class member because nothing gets written to it so I have to do it within the function. I can't copy the outputBuffer to a string type member of my class. The debugger shows me strlen.asm code. No idea why. How can I get around this? I seem to be imprisoned in this function ReceiveMessageB.
Thanks in advance!
Some other bizzare issues include: Even though I call a buffer size of 8. When I take outputBuffer and initialize a string with it, the string has a size of 16.
You are likely getting an access violation because p2tObject does not point to a valid object but to garbage. When is p2tObject initialized? To what does it point?
For this to work, your code should look something like this:
...
TextWifiCommunication twc;
p2tObject = reinterpret_cast<void*>(&twc);
...
Regarding the string error, TCP_readData is not likely to null-terminate the character array you give it. A C-string ends at the first '\0' (null) character. When you convert the C-string to a std::string, the std::string copies bytes from the C-string pointer until it finds the null terminator. In your case, it happens to find it after 16 characters.
To read up to 8 character from a TCP byte stream, the buffer should be 9 characters long and all the bytes of the buffer should be initialized to '\0':
...
unsigned char outputBuffer[9] = { 0 };
// function from an API that reads the WiFi socket for incoming data
TCP_readData(networkDevice, (char *)outputBuffer, 0, 8);
std::string tempString((char *)outputBuffer);
...

Lua RPC and userdata

I'm currently using luarpc in my program to make interprocess communication. The problem now is that due to my tolua++ binding which stores class instances as userdata im unable to use any of those functions cause luarpc cant handle userdata. My question now is if would be possible (and how) to transmit userdata if you know that its always only a pointer (4 Bytes) and has a metatable attached for call and indexing operations.
You can't.
It doesn't matter if the userdata is a pointer or an object. The reason you can't arbitrarily RPC through them is because the data is not stored in Lua. And therefore LuaRPC cannot transmit it properly.
A pointer into your address space is absolutely worthless for some other process; even moreso if it's running on another machine. You have to actually transmit the data itself to make the RPC work. LuaRPC can do this transmission, but only for data that it can understand. And the only data it understands is data stored in Lua.
Ok i got it working now. What i did is for userdata args/returns i send the actual ptr + metatable name(typename) to the client. the client then attaches a metatable with an __index method that creates a new helper with the typename and appends a helper with the field you want to access. when you then call or read a field from that userdata the client sends the data for calling a field of the typetable and the userdata to the server.
ReadVariable:
lua_pushlightuserdata(L,msg.read<void*>());
#ifndef RPC_SERVER
luaL_getmetatable(L,"rpc.userdata");
int len = msg.read<int>();
char* s = new char[len];
msg.read((uint8*)s,len);
s[len] = '\0';
lua_pushlstring(L,s,len);
lua_setfield(L,-2,"__name");
lua_pushlightuserdata(L,TlsGetValue(transporttls));
lua_setfield(L,-2,"__transport");
lua_setmetatable(L,-2);
#endif
Write Variable:
else
{
msg.append<RPCType>(RPC_USERDATA);
msg.append<void*>(lua_touserdata(L,idx));
#ifdef RPC_SERVER
lua_getmetatable(L,idx);
lua_rawget(L,LUA_REGISTRYINDEX);
const char* s = lua_tostring(L,-1);
int len = lua_strlen(L,-1);
msg.append<int>(len);
msg.append(s,len);
#endif
lua_settop(L,stack_at_start);
}
userdata indexing:
checkNumArgs(L,2);
ASSERT(lua_isuserdata(L,1) && isMetatableType(L,1,"rpc.userdata"));
if(lua_type(L,2) != LUA_TSTRING)
return luaL_error( L, "can't index a handle with a non-string" );
const char* s = lua_tostring(L,2);
if(strlen(s) > MAX_PATH - 1)
return luaL_error(L,"string to long");
int stack = lua_gettop(L);
lua_getmetatable(L,1);
lua_getfield(L,-1,"__name");
const char* name = lua_tostring(L,-1);
if(strlen(name) > MAX_PATH - 1)
return luaL_error(L,"string to long");
lua_pop(L,1); // remove name
lua_getfield(L,-1,"__transport");
Transport* t = reinterpret_cast<Transport*>(lua_touserdata(L,-1));
lua_pop(L,1);
Helper* h = Helper::create(L,t,name);
Helper::append(L,h,s);
return 1;
well i more or less rewrote the complete rpc library to work with named pipes and windows but i think the code should give anyone enough information to implement it.
this allows code like:
local remote = rpc.remoteobj:getinstance()
remote:dosmthn()
on the clientside. it currently doesnt allow to add new fields but well this is all i need for now :D

Winsock2 recv() hook into a remote process

I was trying to hook a custom recv() winsock2.0 method to a remote process, so that my function executes instead of the one in the process, i have been googling this and i found some really good example, but they lack description
typedef (WINAPI * WSAREC)( SOCKET s, char *buf, int len, int flags ) = recv;
Now my question is, what does this mean, or does, is this some sort of a pointer to the real recv() function?
And then the other piece of code for the custom function
int WINAPI Cus_Recv( SOCKET s, char *buf, int len, int flags )
{
printf("Intercepted a packet");
return WSAREC( s, buf, len, flags ); // <- What is this?
}
Sorry if these questions sound really basic, i only started learning 2 or 3 weeks ago.
Thanks.
where did you find such an example ?
the first line tries to define a new type WSAREC, which is a pointer to a function having the same signature as recv(). unfortunately, it is also trying to declare a variable of this type to store the address of the recv() function. the typedef is wrong since the function is lacking a return type. so it does not compile under Visual Studio 2003.
you may have more luck using:
int (WINAPI * WSAREC)( SOCKET s, char *buf, int len, int flags ) = &recv;
which declares only a variable of type "pointer to function", which stores the address of the recv().
now the second snippet is a function which has the same signature as the recv()function, which prints a message, then calls the original recv() through the function pointer declared above.
the code here only shows how to call a function through a pointer: it does not replace anything in the current process.
also, i am not sure you can interfere with another process and replace one function at your will. it would be a great threat to the security of the system. but why would you do that in the first place ??