how to build an executable without import table in c/c++? - portable-executable

I found a tool to repair import table here, but how are PE executable without import table built in the first place in c/c++?

Just don't use CRT, and don't use any imported functions.
#pragma comment(linker, "/entry:start")
int start()
{
return 42;
}
To use WinAPI functions, find kernel32 base, parse it's export directory and find LoadLibrary() function (you should already have something like GetProcAddress() to find LoadLibrary())
This may looks like this:
// compile as console application, "release" configuration with /MT /GS-
#include <Windows.h>
#pragma comment(linker, "/entry:start")
void start()
{
HMODULE kernel32base = *(HMODULE*)(*(DWORD*)(*(DWORD*)(*(DWORD*)(*(DWORD*)(__readfsdword(0x30) + 0x0C) + 0x14))) + 0x10);
DWORD base = (DWORD)kernel32base;
IMAGE_NT_HEADERS* pe = PIMAGE_NT_HEADERS(base + PIMAGE_DOS_HEADER(base)->e_lfanew);
IMAGE_EXPORT_DIRECTORY* exportDir = PIMAGE_EXPORT_DIRECTORY(base + pe->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
DWORD* namePtr = (DWORD*)(base + exportDir->AddressOfNames);
WORD* ordPtr = (WORD*)(base + exportDir->AddressOfNameOrdinals);
for(; strcmp((const char*)(base + *namePtr), "GetProcAddress"); ++namePtr, ++ordPtr)
;
DWORD funcRVA = *(DWORD*)(base + exportDir->AddressOfFunctions + *ordPtr * 4);
typedef FARPROC (WINAPI *GetProcAddress_t)(HMODULE, const char*);
GetProcAddress_t GetProcAddress = (GetProcAddress_t)(base + funcRVA);
HANDLE (WINAPI *GetStdHandle)(DWORD);
*(FARPROC*)&GetStdHandle = GetProcAddress(kernel32base, "GetStdHandle");
HANDLE stdout = GetStdHandle(STD_OUTPUT_HANDLE);
BOOL (WINAPI *WriteFile)(HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED);
*(FARPROC*)&WriteFile = GetProcAddress(kernel32base, "WriteFile");
const char* greeting = "Hello world!\n";
DWORD written;
WriteFile(stdout, greeting, strlen(greeting), &written, NULL);
}

To strip imports from existing executable module, you should parse it's imports directory to get its imports, then generate and add a code to get those imports, then remove imports directory.

Related

Implementing stub function and linking it to a definition in a library during run time

When I was reading about using shared libraries, I learnt how the definitions of standard C functions, like printf, are resolved during run-time.
I want to implement functions in my project in the similar manner. I can have stub definition of functions for compiling and linking phase. And actual definition of the functions will be present in a library on the device where I'll run my executable.
Suppose I have a main function:
#include<stdio.h>
#include"sum.h"
int main()
{
int num = 10;
int result = 0;
result = sum(num);
printf("Sum = %d\n",result);
return 0;
}
And my sum.h looks like:
#ifndef SUM_H
#define SUM_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __EXPORT
#ifdef _USERDLL
#define __EXPORT __declspec(dllexport)
#else
#define __EXPORT __declspec(dllimport)
#endif // _USER_DLL
#endif // __EXPORT
__EXPORT int sum(int num);
}
#endif
#endif
And while builiding this executable, I'll use stub definition in sum_stub.c file:
// sum_stub.c
#include<stdio.h>
#include"sum.h"
int sum(int num) {
int res = 0;
printf("Inside stubbed function. Result=%d\n",res);
return res;
}
Let the executable that is build using above files is get_sum.exe
The actual function that will calculate sum is compiled as a shared library, say sum.dll.
// sum.c that will be compiled to sum.dll
#include<stdio.h>
#include"sum.h"
int sum(int num) {
int res = 0;
int i=0;
for (i=0; i<num; i++)
res = res + i;
return res;
}
Now as I run my executable, get_sum.exe, how can I link sum.dll at runtime so that correct function definition is used (inside sum.dll) instead of the stubbed one, that I used while compiling the executable?
I am looking for a way to implement it on windows target machine i.e. by using MSVC build tools and clang compiler.
What you are looking for is called "Delay-loaded DLL". Details on overriding default DLL loading code are provided in MSDN article on Linker support for delay-loaded DLLs.

How to dump/list all kernel symbols with addresses from Linux kernel module?

In a kernel module, how to list all the kernel symbols with their addresses?
The kernel should not be re-compiled.
I know "cat /proc/kallsyms" in an interface, but how to get them directly from kernel data structures, using functions like kallsyms_lookup_name.
Example
Working module code:
#include <linux/module.h>
#include <linux/kallsyms.h>
static int prsyms_print_symbol(void *data, const char *namebuf,
struct module *module, unsigned long address)
{
pr_info("### %lx\t%s\n", address, namebuf);
return 0;
}
static int __init prsyms_init(void)
{
kallsyms_on_each_symbol(prsyms_print_symbol, NULL);
return 0;
}
static void __exit prsyms_exit(void)
{
}
module_init(prsyms_init);
module_exit(prsyms_exit);
MODULE_AUTHOR("Sam Protsenko");
MODULE_DESCRIPTION("Module for printing all kernel symbols");
MODULE_LICENSE("GPL");
Explanation
kernel/kallsyms.c implements /proc/kallsyms. Some of its functions are available for external usage. They are exported via EXPORT_SYMBOL_GPL() macro. Yes, your module should have GPL license to use it. Those functions are:
kallsyms_lookup_name()
kallsyms_on_each_symbol()
sprint_symbol()
sprint_symbol_no_offset()
To use those functions, include <linux/kallsyms.h> in your module. It should be mentioned that CONFIG_KALLSYMS must be enabled (=y) in your kernel configuration.
To print all the symbols you obviously have to use kallsyms_on_each_symbol() function. The documentation says next about it:
/* Call a function on each kallsyms symbol in the core kernel */
int kallsyms_on_each_symbol(int (*fn)(void *, const char *, struct module *,
unsigned long), void *data);
where fn is your callback function that should be called for each symbol found, and data is a pointer to some private data of yours (will be passed as first parameter to your callback function).
Callback function must have next signature:
int fn(void *data, const char *namebuf, struct module *module,
unsigned long address);
This function will be called for each kernel symbol with next parameters:
data: will contain pointer to your private data you passed as last argument to kallsyms_on_each_symbol()
namebuf: will contain name of current kernel symbol
module: will always be NULL, just ignore that
address: will contain address of current kernel symbol
Return value should always be 0 (on non-zero return value the iteration through symbols will be interrupted).
Supplemental
Answering the questions in your comment.
Also, is there a way to output the size of each function?
Yes, you can use sprint_symbol() function I mentioned above to do that. It will print symbol information in next format:
symbol_name+offset/size [module_name]
Example:
psmouse_poll+0x0/0x30 [psmouse]
Module name part can be omitted if symbol is built-in.
I tried the module and see the result with "dmesg". But a lot of symbols are missing such as "futex_requeue". The output symbol number is about 10K, while it is 100K when I use "nm vmlinux".
This is most likely because your printk buffer size is insufficient to store all the output of module above.
Let's improve above module a bit, so it provides symbols information via miscdevice. Also let's add function size to the output, as requested. The code as follows:
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/kallsyms.h>
#include <linux/module.h>
#include <linux/miscdevice.h>
#include <linux/sizes.h>
#include <linux/uaccess.h>
#include <linux/vmalloc.h>
#define DEVICE_NAME "prsyms2"
/* 16 MiB is sufficient to store information about approx. 200K symbols */
#define SYMBOLS_BUF_SIZE SZ_16M
struct symbols {
char *buf;
size_t pos;
};
static struct symbols symbols;
/* ---- misc char device definitions ---- */
static ssize_t prsyms2_read(struct file *file, char __user *buf, size_t count,
loff_t *pos)
{
return simple_read_from_buffer(buf, count, pos, symbols.buf,
symbols.pos);
}
static const struct file_operations prsyms2_fops = {
.owner = THIS_MODULE,
.read = prsyms2_read,
};
static struct miscdevice prsyms2_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEVICE_NAME,
.fops = &prsyms2_fops,
};
/* ---- module init/exit definitions ---- */
static int prsyms2_store_symbol(void *data, const char *namebuf,
struct module *module, unsigned long address)
{
struct symbols *s = data;
int count;
/* Append address of current symbol */
count = sprintf(s->buf + s->pos, "%lx\t", address);
s->pos += count;
/* Append name, offset, size and module name of current symbol */
count = sprint_symbol(s->buf + s->pos, address);
s->pos += count;
s->buf[s->pos++] = '\n';
if (s->pos >= SYMBOLS_BUF_SIZE)
return -ENOMEM;
return 0;
}
static int __init prsyms2_init(void)
{
int ret;
ret = misc_register(&prsyms2_misc);
if (ret)
return ret;
symbols.pos = 0;
symbols.buf = vmalloc(SYMBOLS_BUF_SIZE);
if (symbols.buf == NULL) {
ret = -ENOMEM;
goto err1;
}
dev_info(prsyms2_misc.this_device, "Populating symbols buffer...\n");
ret = kallsyms_on_each_symbol(prsyms2_store_symbol, &symbols);
if (ret != 0) {
ret = -EINVAL;
goto err2;
}
symbols.buf[symbols.pos] = '\0';
dev_info(prsyms2_misc.this_device, "Symbols buffer is ready!\n");
return 0;
err2:
vfree(symbols.buf);
err1:
misc_deregister(&prsyms2_misc);
return ret;
}
static void __exit prsyms2_exit(void)
{
vfree(symbols.buf);
misc_deregister(&prsyms2_misc);
}
module_init(prsyms2_init);
module_exit(prsyms2_exit);
MODULE_AUTHOR("Sam Protsenko");
MODULE_DESCRIPTION("Module for printing all kernel symbols");
MODULE_LICENSE("GPL");
And here is how to use it:
$ sudo insmod prsyms2.ko
$ sudo cat /dev/prsyms2 >symbols.txt
$ wc -l symbols.txt
$ sudo rmmod prsyms2
File symbols.txt will contain all kernel symbols (both built-in and from loaded modules) in next format:
ffffffffc01dc0d0 psmouse_poll+0x0/0x30 [psmouse]
It seems that I can use kallsyms_lookup_name() to find the address of the function, can then use a function pointer to call the function?
Yes, you can. If I recall correctly, it's called reflection. Below is an example how to do so:
typedef int (*custom_print)(const char *fmt, ...);
custom_print my_print;
my_print = (custom_print)kallsyms_lookup_name("printk");
if (my_print == 0) {
pr_err("Unable to find printk\n");
return -EINVAL;
}
my_print(KERN_INFO "### printk found!\n");

Step from CertEnumSystemStoreLocation() to CertEnumSystemStore()

My question is about cryptoAPI interface.
Look, CertEnumSystemStoreLocation() is a function to enumerate all certificate store locations available in system. It returns (using callback) enumerated location as wide string (LPCWSTR).
CertEnumSystemStore() enumerates stores by the given location. It takes integer constant for location (DWORD) as argument.
I tried to enumerate locations and the result was a list of strings, that semantically is equal to the list of DWORD location constants from CryptoAPI import module.
And my question is: what should i do to translate wide string representation of store location to DWORD constant? Is there a cryptoAPI function (or, at least, commonly used method) for it?
It looks like the dwFlags passed to your CertEnumSystemStoreLocationCallback callback function actually gives you the store location constant, although this is incredibly badly documented.
The example shown here for Listing System and Physical Stores handles the dwFlags value in its callback like this:
dwFlags &= CERT_SYSTEM_STORE_MASK;
dwFlags |= pEnumArg->dwFlags & ~CERT_SYSTEM_STORE_LOCATION_MASK;
CertEnumSystemStore(dwFlags, ...);
So I think if you do that masking you'll be left with the location constant in dwFlags equivalent to the string passed in the pvszStoreLocation parameter.
The dwFlags argument passed to the CertEnumSystemStoreLocationCallback callback function contains the store location encoded in the bits CERT_SYSTEM_STORE_LOCATION_MASK. Shifting those to the right by CERT_SYSTEM_STORE_LOCATION_SHIFT turns it into the numeric store ID.
The following code retrieves the list of store locations alongside the numeric store IDs:
Structure for communication:
#include <SDKDDKVer.h>
#include <windows.h>
#include <wincrypt.h>
#pragma comment(lib, "Crypt32.lib")
#include <vector>
#include <string>
#include <iostream>
struct Location {
DWORD StoreId;
std::wstring Name;
};
typedef std::vector<Location> StoreLocationsContainer;
Callback:
BOOL WINAPI CertEnumSystemStoreLocationCallback( LPCWSTR pvszStoreLocations,
DWORD dwFlags,
void* pvReserved,
void* pvArg
) {
StoreLocationsContainer& locations = *reinterpret_cast<StoreLocationsContainer*>( pvArg );
DWORD StoreId = ( dwFlags & CERT_SYSTEM_STORE_LOCATION_MASK )
>> CERT_SYSTEM_STORE_LOCATION_SHIFT;
Location location = { StoreId, std::wstring( pvszStoreLocations ) };
locations.push_back( location );
return TRUE;
}
Implementation:
StoreLocationsContainer GetStoreLocations() {
StoreLocationsContainer locations;
if ( !::CertEnumSystemStoreLocation( 0x0,
&locations,
CertEnumSystemStoreLocationCallback ) ) {
throw std::runtime_error( "CertEnumSystemStoreLocation" );
}
return locations;
}
For completeness, here is the remaining code to dump all stores across all locations:
BOOL WINAPI CertEnumSystemStoreCallback( const void* pvSystemStore,
DWORD dwFlags,
PCERT_SYSTEM_STORE_INFO pStoreInfo,
void* pvReserved,
void* pvArg ) {
std::wcout << L" " << static_cast<const wchar_t*>( pvSystemStore ) << std::endl;
return TRUE;
}
void PrintStores( const StoreLocationsContainer& locations ) {
for ( const Location& loc : locations ) {
std::wcout << loc.Name << std::endl;
DWORD dwFlags = ( loc.StoreId << CERT_SYSTEM_STORE_LOCATION_SHIFT )
& CERT_SYSTEM_STORE_LOCATION_MASK;
::CertEnumSystemStore( dwFlags, nullptr, nullptr, CertEnumSystemStoreCallback );
}
}
int main() {
StoreLocationsContainer locations = GetStoreLocations();
PrintStores( locations );
return 0;
}

Just want an executable to enumarate processes and enumarate loaded .dlls

I want to make like a function with an argument stdvector::<std::string> of process names and std::vector<std::string> of .dll's to find in them and feed it into a function and get like PROCESSENTRY32 info std::vector<PROCESSENTRY32> returned of anything that matches the names.
You can google but won't find much as I have thanks for helping new to winapi but not to figuring things out
There is a perfect example to do exactly what you want on MSDN here. The relevant code is copied below. As the introduction to the sample says
To determine which processes have loaded a particular DLL, you must enumerate the modules for each process. The following sample code uses the EnumProcessModules function to enumerate the modules of current processes in the system.
Now the sample code
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h>
// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1
int PrintModules( DWORD processID )
{
HMODULE hMods[1024];
HANDLE hProcess;
DWORD cbNeeded;
unsigned int i;
// Print the process identifier.
printf( "\nProcess ID: %u\n", processID );
// Get a handle to the process.
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE, processID );
if (NULL == hProcess)
return 1;
// Get a list of all the modules in this process.
if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ )
{
TCHAR szModName[MAX_PATH];
// Get the full path to the module's file.
if ( GetModuleFileNameEx( hProcess, hMods[i], szModName,
sizeof(szModName) / sizeof(TCHAR)))
{
// Print the module name and handle value.
_tprintf( TEXT("\t%s (0x%08X)\n"), szModName, hMods[i] );
}
}
}
// Release the handle to the process.
CloseHandle( hProcess );
return 0;
}
int main( void )
{
DWORD aProcesses[1024];
DWORD cbNeeded;
DWORD cProcesses;
unsigned int i;
// Get the list of process identifiers.
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return 1;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the names of the modules for each process.
for ( i = 0; i < cProcesses; i++ )
{
PrintModules( aProcesses[i] );
}
return 0;
}
The only change you will need to make is to push-back the module names of interest to your std::vector<std::string> beforehand and then search that vector with the enumerated module names instead of printing them.

Segmentation fault when changing default gateway

I wrote a simple application on Qt4 that modifier network adapter parameters, for that I have a slot called setInterfaceParams, implemented as so:
DWORD WinNetInterface::setInterfaceParams(QString index, QString ip, QString netmask, QString gateway)
{
DWORD res = NULL;
HINSTANCE lib = (HINSTANCE) LoadLibrary((WCHAR *)"iphlpapi.dll");
_SetAdapterIpAddress SetAdapterIpAddress = (_SetAdapterIpAddress) GetProcAddress(lib, "SetAdapterIpAddress");
PWSTR pszGUID = NULL;
//char *szGUID = (char *)index.toStdString().c_str();
QByteArray a = index.toLocal8Bit();
char *szGUID = a.data();
WideCharToMultiByte(CP_ACP, 0, pszGUID, -1, szGUID, sizeof(szGUID), NULL, NULL);
// Method 01
res = SetAdapterIpAddress(szGUID,
0,
inet_addr(ip.toStdString().c_str()),
inet_addr(netmask.toStdString().c_str()),
inet_addr(gateway.toStdString().c_str()));
// End of method 01
// Method 02
/*res = SetAdapterIpAddress("{422C5689-A17B-402D-A6A2-22CE13E857B5}",
0,
inet_addr("192.168.1.10"),
inet_addr("255.255.255.0"),
inet_addr("192.168.1.1"));*/
// End of method 02
return res;
}
When I click on button that connected to slot setInterfaceParams, I get segmentation fault. If I comment method01, nothing happen, the some thing happen when I use method02.
I tried this function on a simple c++ application and it is work fine, test on Windows XP SP3.
#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <iostream>
typedef DWORD (WINAPI *_SetAdapterIpAddress )(char *szAdapterGUID,
DWORD dwDHCP,
DWORD dwIP,
DWORD dwMask,
DWORD dwGateway);
int main()
{
HINSTANCE lib = (HINSTANCE) LoadLibrary("iphlpapi.dll");
_SetAdapterIpAddress SetAdapterIpAddress = (_SetAdapterIpAddress) GetProcAddress(lib, "SetAdapterIpAddress");
PWSTR pszGUID = NULL;
char szGUID[] = "{422C5689-A17B-402D-A6A2-22CE13E857B5}";
DWORD dwSize = 0;
WideCharToMultiByte(CP_ACP, 0, pszGUID, -1, szGUID, sizeof(szGUID), NULL, NULL);
DWORD res = SetAdapterIpAddress(szGUID,
0,
inet_addr("192.168.1.10"),
inet_addr("255.255.255.0"),
inet_addr("192.168.1.1"));
std::cout << res;
return 0;
}
LoadLibrary((WCHAR *)"iphlpapi.dll");
That can't work, the literal string is in 8-bits, casting it without real conversion doesn't make it wide, so the dll loading probably failed.
You should use the TEXT or _T macro around most of the literal strings passed to WinAPI functions to make them regular or wide depending on the compilation options:
LoadLibrary(_T("iphlpapi.dll"));
which will translate to either LoadLibrary("iphlpapi.dll"); or LoadLibrary(L"iphlpapi.dll");.
Also you should always check the value returned by the LoadLibrary and GetProcAddress functions, which return NULL if the call is unsuccessful.

Resources