Unable to set WSPStartup as a dll export - c++

I am trying to write a LSP for winsock and as per MSDN documentation the dll is supposed to export a single function viz. WSPStartup() as defined in Ws2spi.h
While compiling I get an error:
error C2375: 'WSPStartup' : redefinition; different linkage
If I append the
__declspec(dllexport)
directive to it. On the other hand, if I use the
__control_entrypoint(DllExport)
it compiles fine, but the function is not actually exported. I checked using dependency viewer. To make sure that other LSP implementations export the functions or not, I used dependency viewer on VMWares vsocklib.dll and mswsock.dll, both dlls export the said function.
My sample implementation is as follows :-
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include <Ws2spi.h>
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
__declspec(dllexport)
__checkReturn
int
WSPAPI
WSPStartup(
__in WORD wVersionRequested,
__in LPWSPDATA lpWSPData,
__in LPWSAPROTOCOL_INFOW lpProtocolInfo,
__in WSPUPCALLTABLE UpcallTable,
__out LPWSPPROC_TABLE lpProcTable
)
{
return 0;
}
So what am I doing wrong here? How do I make a DLL which exports the WSPStartup() function ??

Since the function prototype is given in the Ws2spi.h file, adding any kind of additional specifiers to the function in the definition will cause the compiler to give the
'redefinition' error.
Also it is not possible to have it exported directly via declspec(dllexport) which will create a decorated name since WSPAPI specifier declares the function as a stdcall.
To mitigate all these problems I exported the method by a DEF file as shown in this article - Exporting from a DLL Using DEF Files
I believe that is the only proper method to get an undecorated WSPStartup() function export in your dll.

Related

Custom Windows Authentication Package not loaded

I'm writing a custom windows authentication package, but the LSA does not load my Dll.
I have the following methods exported via the .def file
EXTERN_C __declspec(dllexport) NTSTATUS NTAPI SpLsaModeInitialize(
ULONG LsaVersion,
PULONG PackageVersion,
PSECPKG_FUNCTION_TABLE * ppTables,
PULONG pcTables
) {
__LOG_TRACE_FUNC_BEGIN(); // Write a log entry to C:\temp\log.txt
*PackageVersion = SECPKG_INTERFACE_VERSION;
*ppTables = sp_lsa_function_table;
*pcTables = 1;
__LOG_TRACE_FUNC_END(); // Write a log entry to C:\temp\log.txt
return 0;
}
I also have the DllMain and DllInit functions.
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
__LOG_TRACE_FUNC_BEGIN(); // Write a log entry to C:\temp\log.txt
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
__LOG_TRACE_FUNC_END(); // Write a log entry to C:\temp\log.txt
return TRUE;
}
BOOLEAN DllInit(IN PVOID DllHandle, IN ULONG Reason, IN PCONTEXT Context OPTIONAL)
{
__LOG_TRACE_FUNC_BEGIN(); // Write a log entry to C:\temp\log.txt
switch (Reason)
{
case DLL_PROCESS_ATTACH:
#if defined (DEBUG)
DebugBreak();
#endif
InitializeCriticalSection(&DllCritSect);
break;
case DLL_PROCESS_DETACH:
EnterCriticalSection(&DllCritSect);
LeaveCriticalSection(&DllCritSect);
DeleteCriticalSection(&DllCritSect);
break;
}
__LOG_TRACE_FUNC_END(); // Write a log entry to C:\temp\log.txt
return TRUE;
UNREFERENCED_PARAMETER(Context);
UNREFERENCED_PARAMETER(DllHandle);
}
I have the export definition in dap.def as below,
EXPORTS
DllMain
DllInit
SpLsaModeInitialize
I also have the dap.dll.manifest file (even though I'm not sure if it is required. The manifest file was required for another part of the project, a credential provider)
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity
type='win32'
name='Microsoft.VC80.DebugCRT'
version='8.0.50608.0'
processorArchitecture='x64'
publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
My Dll is compiled for Release/x64.
I'm signing my Dll (dap.dll) as below (not sure if this step is mandatory)
makecert.exe -sv dap.pvk -n "CN=Dallas" dap.cer -r
pvk2pfx.exe -pvk dap.pvk -spc dap.cer -pfx dap.pfx -po 123
signtool.exe sign /f "dap.pfx" /p 123 "dap.dll"
Then I move my file, dap.dll, into Windows\System32 in the target Windows 10 VM and add the following registry entry.
I've also tried adding the same into the Security Packages.
Then I restart the VM.
But none of these attempts worked, and my Dll never gets called (I don't see any log entries created.).
Here is my OS info,
My questions are,
Am I doing everything right? or am I missing any step?
Does the signing step mandatory, and Am I doing it right?
When the Local Security Authority process ignores my DLL, does it create any event entries? I tried enabling %SystemRoot%\System32\Winevt\Logs\Microsoft-Windows-LSA%4Operational.evtx events, but nothing useful came up. Is there any other place?
Are there any other way to troubleshoot this?
Cheers,

How to register a COM (Component Object Model) in Windows? (for Icon Overlay Handler)

I am quite inexperienced with COM objects, following is what I did:
In C++, I created a class which extend IUnknow and implements QueryInterface, AddRef and Release.
Extend IShellIconOverlayIdentifier and implements the 3 methods inside.
Export the class with __declspec(dllexport)
The DLL is compiled with MSVC2015 64 bits. (working on a windows7 64bits).
Now comes the difficult part:
How to make windows to link/use the DLL:
https://msdn.microsoft.com/en-us/library/windows/desktop/hh127455(v=vs.85).aspx Explain how to register the Overlay handler, but not how to register the COM object. I made a few tries, but after windows restart, nothing happens.
How to register and how to check if registered a COM dll?
Is there compilation restrictions like compiler/architecture?
EDITED Simplified:
It seem that I had a very incomplete vision of COM implementation, and in order to register the COM object, 2 directions are possible:
Register manually the object in the register, which is a nightmare.
Implement DllRegisterServer and DllUnregisterServer: which is a nightmare also.
To simplify the problem, I removed everything else up to having only those 2 functions:
STDAPI DllRegisterServer(void)
{
return NOERROR;
}
STDAPI DllUnregisterServer(void)
{
return NOERROR;
}
Unfortunately, this is not exported to the DLL, (as no __declspec(dllexport) is specified). As soon as I try to add this declaration, the compiler complain and no DLL is generated.
SOLUTION STEP 1:
Olectl.h is very very bad and avoid DllRegisterServer to be exported.
In order to create a COM object manually (without wizard), following steps are required:
Implement DllGetClassObject & DllCanUnloadNow
Implement Factory extending IClassFactory
Implement the Target class, extending IUknown
Register the COM in the registry
[optional] implement DllRegisterServer & DllUnregisterServer to make registry easier.
Implements DllGetClassObject & DllCanUnloadNow
Those are the only exported to the DLL functions:
STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID * ppObject)
STDAPI DllCanUnloadNow(void)
DllGetClassObject, if the provided rclsid is the TargetClassCLSID and riid is the `FactoryCLSID, it creates and return a Factory object.
DllCanUnloadNow return if the DLL is in use (S_OK) or not, in which case the user/client may unload the DLL (S_FALSE).
The problem is, the definition do not allows to add __declspec(dllexport) due probably to some Microsoft monopol directive to make VS "mandatory".
To export them, just add before
#pragma comment( linker, "/export:DllGetClassObject,PRIVATE" )
#pragma comment( linker, "/export:DllCanUnloadNow,PRIVATE" )
//TODO: make this cross-compiler compatible?
Implementing the Factory
Implements AddRef and Release: they maintain how many client/users are currently using this Factory object. AddRef increment it by 1, Release decrements it by 1. As soon as the number is 0, Releasemay auto delete itself.
Implements QueryInterface which return if riidis the FactoryCLSID.
Implements CreateInstance, which return an instance of the TargetObject if riid match TargetClassCLSID
Implementing the Target Class
Again, we have to implements AddRef, Release and QueryInterface, but for the final class this time.
In my case, this Target class extends IShellIconOverlayIdentifier.
Register the COM object into the OS registry
After generating the dll, several registry need to be set. Some of them are linked together, so adding one may automatically add another.
HKEY_CLASS_ROOT::CLSID::<Add Here>
HKEY_CLASS_ROOT::Wow6432Node::CLSID::<Add Here>
HKEY_LOCAL_MACHINE::SOFTWARE::Classes::CLSID::<Add Here>
HKEY_LOCAL_MACHINE::SOFTWARE::Classes::Wow6432Node::CLSID::<Add Here>
HKEY_LOCAL_MACHINE::SOFTWARE::Wow6432Node::Classes::CLSID::<Add Here>
Content to add is:
Create a key: name={TargetClassCLSID}, value=<Any app name>
Create a sub-key: name=InProcServer32, value=<link to your dll>
Create a sub-string of InProcServer32: name=ThreadingModel, value=Apartment
//TODO: probably there are other alternatives, to better understand what that mean.
In my case, I had to register some more registers for the IconHandler:
HKEY_LOCAL_MACHINE::SOFTWARE::Microsoft::Windows::CurrentVersion::Explorer::ShellIconOverlayIdentifier::<Overlay here>
HKEY_LOCAL_MACHINE::SOFTWARE::Microsoft::Windows::CurrentVersion::ShellExtensions::Aproved::<new entry here>
Where the overlay entry is a key: name=<Any app name>, value=<TargetClassCLSID>
The new entry is a string value which name=<TargetClassCLSID>and value=Any app name
Those values need also to be in:
HKEY_LOCAL_MACHINE::SOFTWARE::Wow6432Node::Microsoft::Windows....

MFC app and shared libs

I have a application which seems has written in MFC (process hacker and DependencyWalker show link to MFC90).
Also, There is a library(FTD2XX) in the installation path. But the DependencyWalker won't show the MFC90 link for the lib and show:
SetupAPI.dll
KERNEL32.dll
USER32.dll
ADVAPI32.dll
In what framework the lib is built?
I don't have experience in MFC. I don't have information in its compiler and if VC++ libs can be used to link with MFC apps.
If you want to log calls going to a dll, the best way is to write a proxy dll (a dll redirection). But for that you must know the signature (syntax) of the function which you are going to override, i.e. exact number of parameters, their types and return type etc. If I can assume that you somehow can find out signature of all the functions in ftd2xx.dll, then it is merely simple to get it done.
Get dll functions and Ordinal numbers:
For this just use dumpbin.exe comes with Visual Studio (use it by running Visual Studio command prompt)
dumpbin.exe /exports {yourpath}\ftd2xx.dll > ftd2xx.txt
Now your ftd2xx.txt has all the function names and ordinal numbers of the ftd2xx.dll. You can even use your dependency walker to export and get this list.
Create you own dll named ftd2xx.dll:
Open Visual Studio, choose VC++ >> Win32 >> Win32 Project >> Dll (with Export symbols option) and finally use #pragma directive to declare all your exported original dll functions within your dll code like below,
//#pragma comment (linker, "/export:<function>=<origdll_name>.<function>,#<ordinal_number>")
#pragma comment (linker, "/export:FT_Open=ftd2xx_.FT_Open,#1")
#pragma comment (linker, "/export:FT_Close=ftd2xx_.FT_Close,#2")
// :
// :
// :
// delcare all your exported functions here with ordinal number
// :
// :
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
}
Now, you need to write your own function which can pretend as an original function of ftd2xx.dll which will get called when the application calls a original function of ftd2xx.dll. The below code is just to explain how it works. As I said earlier you need to know the exact signature of the dll functions which you want to override (redirect). And also keep in mind that you need to call the original function after whatever you wanted to do, otherwise you may endup having unexpected behaviour with your application.
Assuming FT_Close() function takes no parameter and returns void, I am putting this just for example in which I override FT_Close() function of ftd2xx.dll with a proxy NewFT_Close() function. Note that, if you override a function, then remove it from #pragma directive and add it in a .def file (add a new ftd2xx.def file to your project and declare your new functions like below).
DEF file example
LIBRARY ftd2xx.dll
EXPORTS
FT_Close = NewFT_Close #2
Dll code example
HINSTANCE hInstance = NULL; // handle to ftd2xx.dll
FARPROC fpFTClose = {NULL}; // function pointer to hold original function address
extern "C" void __stdcall NewFT_Close()
{
// This is our proxy function for FT_Close()
// Do whatever you want to do here and the
// finally call the original FT_Close() using
// the function pointer we got from GetProcAddress()
typedef void (__stdcall *PFTCLOSE)();
PFTCLOSE pFc = (PFTCLOSE)fpFTClose;
if(pFc) pFc();
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
// Load the original dll in to the memory and get the handle
hInstance = LoadLibraryA("ftd2xx_.dll");
if(!hInstance) return FALSE;
// Get the address of the function to be overriden
fpFTClose = GetProcAddress(hInstance,"FT_Close");
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
// Our dll is getting unloaded from the application, unload original as well
FreeLibrary(hInstance);
break;
}
return TRUE;
}
Note that the original dll is referred as ftd2xx_.dll in LoadLibraryA() call. So, rename the original dll to ftd2xx_.dll or name it whatever you want. Build your proxy dll code and take your proxy dll (ftd2xx.dll) to the path where the original ftd2xx.dll present. Now, your application will call ftd2xx.dll (proxy) as usual, but ftd2xx.dll will call the original dll ftd2xx_.dll internally.
Update #1:
I kept mentioning that you need to know the signature of the functions your are trying to override, and by luck I just found the ftd2xx.h file in the linux version of the driver.
Linux version of ftd2xx
Download the libftd2xx-i386-1.3.6.tgz file from above link and extract it to a folder (I used 7zip), further extract the .tar file to get the release folder and you'll find ftd2xx.h file within the "release" folder. There you go, now you got complete function signatures of the dll and you know how to write a proxy dll. Good Luck.

creating a dll file in code::blocks and using it in powerpoint 2007

I have tired to create a dll file in code blocks and then use it in my powerpoint presentation. In the dll file as I have mentioned below the argument of the function contains (LPCSTR)
void DLL_EXPORT SomeFunction(const LPCSTR sometext)
{
MessageBoxA(0, sometext, " DLL Message ", MB_OK | MB_ICONINFORMATION);
}
In my powerpoint file I have
Declare Function DLL_EXPORT _
Lib "myfile.dll" _
Alias "SomeFunction" (???)
and when I run the file I get
Because I do not know how to define the argument of my function in the powerpoint. I mean this part of the code:
Alias "SomeFunction" (???)
Your C++ code uses the wrong calling convention. It should be:
__declspec(dllexport) void __stdcall SomeFunction(const char* sometext)
You can use macros like DLL_EXPORT, APIENTRY, LPCSTR etc. if you wish. However, at least until you know what the macros all mean, it is probably easier to be explicit, as I show above.
The correct VBA declaration for your function is:
Declare Sub SomeFunction Lib "myfile.dll" (ByVal sometext As String)
However, this alone is not enough because your function will be subject to name decoration and mangling. You can use dumpbin or Dependency Walker to view the actual name by which your function is exported. Then your VBA declaration would need to be modified like so:
Declare Sub SomeFunction Lib "myfile.dll" Alias "<DecoratedNameHere>" (ByVal sometext As String)

Hooking LoadLibrary API call

I want to load a different version of a DLL than is present in the working directory of the application. For this I need to hook the LoadLibrary call so that when the application makes a call to load the DLL I can substitute it with the newer version of that DLL transparently. I tried using NCodeHook and have the following code in my DLL which I inject into the application using NInjectLib but it crashes while loading kernel32.dll. Can anybody please tell me if this is the correct way of injecting the call or are there any other alternatives.
// CodeHook.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include <NCodeHookInstantiation.h>
#include "CodeHook.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
typedef HMODULE (WINAPI *LoadLibraryFPtr)(LPCTSTR dllName);
#pragma data_seg("SHARED")
LoadLibraryFPtr origFunc = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:SHARED,RWS")
HMODULE WINAPI LoadLibraryHook(LPCTSTR dllName)
{
if (origFunc != NULL)
{
return origFunc(dllName);
}
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
CODEHOOK_API void Initialize (void)
{
NCodeHookIA32 nch;
origFunc = nch.createHookByName("kernel32.dll", "LoadLibrary", LoadLibraryHook);
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
I don't know the NCodeHook library, but one important thing to know is that there are actually 2 versions of the LoadLibrary function: LoadLibraryA(LPCSTR) and LoadLibraryW(LPCWSTR). Make sure you hook the correct one and use the appropriate function definition. You may also need to hook LoadLibraryExA/LoadLibraryExW
Detours is a more widely known library for API hooking. Also see this article for more hooking techniques.
I had similar problems of crashes in kernel32.dll when using a hand-written hooking/detours library. I found a good explanation of the problem in the discussion pages of the MinHook library:
As far I understand it, your detour library does not account for the possibility that a function it tries to hook is implemented using a short jump opcode (apparently the LoadLibrary(Ex)W is implemented this way). This will lead to different bytes which need to be replaced during hooking.
Using MinHook for my hooking of LoadLibrary and friends works for me:
HMODULE WINAPI LoadLibraryA_replacement(_In_ LPCTSTR lpFileName)
{
// do your stuff
return loadLibraryA_original(lpFileName);
}
bool installLoadLibraryHook()
{
// Initialize MinHook.
if (MH_Initialize() != MH_OK)
return false;
if (MH_CreateHook(&LoadLibraryA, &LoadLibraryA_replacement,
reinterpret_cast<LPVOID*>(&loadLibraryA_original)) != MH_OK)
return false;
if (MH_EnableHook(&LoadLibraryA) != MH_OK)
return false;
// same for LoadLibraryW, LoadLibraryExW, LoadLibraryExA
return true;
}
There are lots of pitfalls associated with API hooking. I don't know specifics about the NCodeHook implementation, but there is potential for trouble if the API hooking code doesn't properly deal with non-writable pages. One would assume that the library would call VirtualProtect and that the OS would properly handle copy-on-write, but it's hard to say.
I agree with the comment that this might not be the best solution to your problem. API hooking relies on the application binary interface, which is quasi-documented at best. I would not recommend it for a commercial app that is intended for production use.
Side-by-side assemblies would definitely be useful, as the strong name removes any ambiguities about which DLL needs to be loaded. Alternatively, consider using LoadLibraryEx with an absolute path to the DLL and the LOAD_WITH_ALTERED_SEARCH_PATH flag.