dynamically running a DLL at a remote Windows box? - windows

Is there a way of dynamically running a DLL at a remote Windows box?
Say a user wants to send a his own DLL file to a remote server and run a function in that DLL at the remote site. The user may be able to provide function entry points as well as required parameters, but no more. (e.g. no header file)
I am thinking of setting up an agent executable at the remote site that can (1) dynamically load and bind a unknown DLL and (2) run a function with parameters. Is this a good a approach, or is such an executable possible?

You can use a technique of Dynamically loading your DLL's.
Normally you use a DLL by statically linking a .LIB into your project and compiling it. To load a DLL dynamically at runtime you use the following WIN32 API functions and a few other tricks.
LoadLibaray();
LoadLibarayEx();
GetProcAddress();
FreeLibrary();
There are some other tricks involved
You need to declare the dll functions as export'ed.
In c++ you need to use extern "C" to prevent name mangling of your functions.
FARPROC ... with GetProcAddress
It is all explained in the following wiki article - http://en.wikipedia.org/wiki/Dynamic-link_library
Your idea of installing an executable on the remote machine is a good one. So long as you agree on the function names and parameters with the user. If the dll complies with this then the dll can be changed at any time without requiring you EXE to be changed. Once set up and working it is simple to add extra functions.

Yes you could write small program that runs the DLL function using this information and call it remotely using the something like PSEXEC from sysinternals.
PsExec is a light-weight
telnet-replacement that lets you
execute processes on other systems,
complete with full interactivity for
console applications, without having
to manually install client softwareto manually install client software

Andrew Cash's reply is sound for unmanaged code. The technique he describes around GetProcAddress is essentially what RunDll32.exe does. RunDll32.exe is part of Windows and specializes at loading arbitrary DLLs and executing their code. You can run it like this:
RUNDLL32.EXE [dllfile],[entrypoint] [optional arguments]
When you do this, RunDll32 will call LoadLibrary on the DLL and then GetProcAddress on the entrypoint name you give it. If all that goes well then it calls the entry point function.
For this to actually work the entrypoint function needs to be exported. It must also be declared like this:
void CALLBACK MyEntryPoint(
HWND hwnd,
HINSTANCE hinst,
LPSTR lpszCmdLine,
int nCmdShow);

Related

Can you make a Windows desktop app in Rust and winapi?

I've got a Windows application with a GUI written in Rust and winapi. Despite its GUI, it behaves like a console application. When the exe file is started, a Command Prompt window pops up, and the application is run from it. This is not what I want; a main window should open instead, as in all real desktop apps. How can I achieve this goal in Rust with winapi?
I've investigated some options. You can develop Windows desktop applications using Tauri or gtk-rs, but both of these techniques have drawbacks when used for Windows apps. More options may be found here. I've also tried the windows-rs samples available on the internet, but they're all console apps with a graphical user interface, which isn't what I'm looking for.
I also note that C++ desktop applications use the function int APIENTRY wWinMain(...) as the entry point while console applications use int main(...), and wWinMain doesn't seem available in rust winapi.
Whether the system allocates a console for a newly created process is controlled by the Subsystem field in the Windows-specific optional PE header. The field is populated through the linker's /SUBSYSTEM command line option. The only relevant arguments for desktop applications are CONSOLE and WINDOWS. The former instructs the system to allocate a console on launch, whereas the latter won't.
You can instruct the linker to target the WINDOWS subsystem from Rust code by placing the per-module
#![windows_subsystem = "windows"]
attribute (see windows-subsystem) inside the main module of your application.
You'll find an example of this in the core_app sample of the windows crate.
This is the most convenient way to target the WINDOWS subsystem. You can also explicitly pass the linker flag along, e.g. by placing the following override into .cargo/config.toml:
[build]
rustflags = [
"-C", "link-arg=/SUBSYSTEM:WINDOWS",
]
This may or may not work, depending on the linker you happen to be using. Since the linker isn't part of the Rust toolchain, making sure that this works and has the intended effect is on you.
A note on the entry point's function name: It is irrelevant as far as the OS loader is concerned. It never even makes it into the final executable image anyway. The PE image only stores the (image-base-relative) AddressOfEntryPoint, and that symbol could have been named anything.
The concrete name is only relevant to the build tools involved in generating the respective linker input.
More info here: WinMain is just the conventional name for the Win32 process entry point. The underlying principles apply to Rust just the same, particularly the aspect that the user-defined entry point (fn main()) isn't actually the executable's entry point.

WinMain entry point - VS Linker vs Windows API

I had been setting my application (MASM assembly language program) entry point via Visual Studio configurations, in the Project properties as:
Linker\System\SubSystem: Windows (/SUBSYSTEM:WINDOWS)
Linker\Advanced\Entry Point: WinMain
Any my main proc called WinMain (matching the above setting). It is a basic application that makes simple Windows API calls, e.g. MessageBoxA... and it works.
Now I'm building a Window application (in assembly), I read somewhere that I need to call the WinMain Windows API for an entry point.
I'm now confused! Which technique do I use to set the entry point to my application (exe)? The Windows API call 'WinMain' or the Visual Studio Linker entry point settings? And is the difference, i.e. C++ runtime vs OS?
If you are using the C runtime library (which is usually the case when programming in C) then you must not specify the linker entry point yourself. If you do, the runtime library will not be properly initialized, and any runtime library calls (including those inserted by the compiler) may fail.
Instead, your main function should correspond to the relevant standard: WinMain() for a GUI application, or main() for a console application.
In an assembly language program that is not linked to the C runtime library, you should specify an entry point of your choosing.
The signature of the native entry point is
DWORD CALLBACK RawEntryPoint(void);
Important:
Returning from the raw entry point implicitly calls ExitThread (see this answer) which is not usually the right thing to do, because if the Windows API has created any threads that you don't know about, the process won't exit until they do. Note that the Windows API documentation does not always indicate when a particular API function may cause a thread to be created.
Instead, you should explicitly call ExitProcess. This is what the C runtime library does when you return from WinMain() or main().

Stop looking for the entry point at runtime in a DLL

I have an application which runs on windows 2003, window 2008 and windows small business server.
There is a windows call that I make to reboot the system.All the calls mentioned below come from advapi32.dll
InitiateSystemshutdown - This is fine in windows 2003 and windows 2008 but for some reason not working in Windows aurora
InitiateShutdown - since the above call is not working in windows aurora we used this call and minimum supported OS for this call is windows 2008
Now my application fails to run in windows 2003 since the InitiateShutDown is not present in the advapi32.dll on Windows 2003
I get a failed to find procedure entry point for Initiateshutdown in advapi32.dll
I have already put a condition also so that the proper function calls are called with respect to the windows version.
Is there way to stop looking for the entry point in the dll when the application launches.The condition will make sure that the proper function call are called?
OR
I should be asking Microsoft why the old call InitiateSystemshutdown is not working properly ?
You have to use GetProcAddress and set your preprocessor variables for the earlier version of Windows. See http://msdn.microsoft.com/en-us/library/aa383745(VS.85).aspx#setting_winver_or__win32_winnt
Basically, you should:
Set WINVER to the earliest version of Windows you must support so you don't accidentally use something newer.
Some API calls and definitions won't work anymore (like InitiateShutdown in your case) in your code, because they aren't included by header files. For these, you must use them dynamically. Typically you use the GetProcAddress API and use a "typedef" to define the function's signature (since it isn't in the header files you're including anymore). An example is here: http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx. In your case you would use the InitiateShutdown API instead of the given GetNativeSystemInfo. If the call to GetProcAddress fails then you can assume that the API is not supported on that version of Windows.
Rather that explicitly calling that function in your code (such that your app will fail to load if the function can't be loaded from the expected DLL), call it implicitly via LoadLibrary and GetProcAddress.
Do a "LoadLibrary" on advapi32.dll. And then call GetProcAddress for "InitiateShutdown". Fail gracefully if the function doesn't exist, otherwise cast it to an appropriate function pointer and
invoke it.
typedef DWORD (WINAPI *InitiateSystemShutdownTypeA) (char*, char*, DWORD, DWORD, DWORD);
typedef DWORD (WINAPI *InitiateSystemShutdownTypeW) (wchar_t*, wchar_t*, DWORD, DWORD, DWORD);
InitiateShutdownTypeA func = NULL;
HMODULE hMod = LoadLibrary("advapi32.dll");
if (hMod)
func = (InitiateShutdownTypeA)GetProcAddress("InitiateShutdownW");
if (func)
func(pwszMachineName, pwszMessage, dwGracePeriod, dwFlags, dwReason);

SetErrorMode has no effect?

I call
"SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);"
before loading a DLL. Nevertheless a windows message pops up
"This application has failed to start
because blabla.dll was not found...".
Why does that happen? I thought that was what SetErrorMode was supposed to prevent?
Thanks!
The call to SetErrorMode is probably never executed - if you statically link to the DLL, it will be loaded along with the executable. The message you see is popped by the operating system, and not by your code. If you want control over the load of the DLL, you should load it using LoadLibrary - but then using exported functions is a bit harder.
You can create your own loader (a different executable), which will make sure all DLLs are available, and then run the main executable. But that might be an overkill...

System calls on Windows

I just want to ask, I know that standart system calls in Linux are done by int instruction pointing into Interrupt Vector Table. I assume this is similiar on Windows. But, how do you call some higher-level specific system routines? Such as how do you tell Windows to create a window? I know this is handled by the code in the dll, but what actually happend at assembler-instruction level? Does the routine in dll calls software interrupt by int instruction, or is there any different approach to handle this? Thanks.
Making a Win32 call to create a window is not really related to an interrupt. The client application is already linked with the .dll that provides the call which exposes the address for the linker to use. Since you are asking about the difference in calling mechanism, I'm limiting the discussion here to those Win32 calls that are available to any application as opposed to kernel-level calls or device drivers. At an assembly language level, it would be the same as any other function call since most Win32 calls are user-level calls which internally make the needed kernel calls. The linker provides the address of the Win32 function as the target for some sort of branching instruction, the specifics would depend on the compiler.
[Edit]
It looks like you are right about the interrupts and the int. vector table. CodeGuru has a good article with the OS details on how NT kernel calls work. Link:
http://www.codeguru.com/cpp/w-p/system/devicedriverdevelopment/article.php/c8035
Windows doesn't let you call system calls directly because system call numbers can change between builds, if a new system call gets added the others can shift forward or if a system call gets removed others can shift backwards. So to maintain backwards compatability you call the win32 or native functions in DLLs.
Now there are 2 groups of system calls, those serviced by the kernel (ntoskrnl) and by the win32 kernel layer (win32k).
Kernel system call stubs are easily accessible from ntdll.dll, while win32k ones are not exported, they're private within user32.dll. Those stubs contain the system call number and the actual system call instruction which does the job.
So if you wanted to create a window, you'd call CreateWindow in user32.dll, then the extended version CreateWindowEx gets called for backwards compatability, that calls the private system call stub NtUserCreateWindowEx, which invokes code within the win32k window manager.

Resources