How to execute an executable embedded as resource - c#

Is it possible to execute an exe file that is included in the project as a resource? Can I fetch the file as a byte array and execute it in memory?
I don't want to write the file to a temporary location and execute it there. I'm searching for a solution where I can execute it in memory. (It's not a .NET assembly.)

It's quite possible - I've done it myself - but it's fiddly and more so from managed code. There's no .NET API for it, nor is there a native API for it which you can PInvoke. So you'll have to fenagle the load by hand, which will require some knowledge of the PE (Portable Executable) file format used for modules such as DLLs and EXEs - http://msdn.microsoft.com/en-us/magazine/cc301805.aspx. There'll be a lot of pointer manipulation (mandating use of unsafe {} blocks) and PInvoke.
First load the PE file into memory (or use MapViewOfFile). A PE file is internally made up of different sections containing code, data or resources. The offsets of each section in the file don't always match intended in-memory offsets, so some minor adjustments are required.
Every PE file assumes it'll be loaded at a certain base address in virtual memory. Unless you can ensure this you'll need to walk the PE file's relocation table to adjust pointers accordingly.
Each PE file also has an import table listing which other DLLs' functions it wants to call. You'll need to walk this table and call LoadLibrary() / GetProcAddress() to fill in each import.
Next, memory protection needs to be set correctly for each section. Each section's header notes the protection it wants, so it's just a matter of calling VirtualProtect() for each section with the correct flags. At a minimum you'll need to VirtualProtect the loaded module with PAGE_EXECUTE_READWRITE or you're unlikely to be able to execute any code.
Lastly for a DLL you need to call its entry point, whose address can be found in the PE header; you can then freely call exported functions.
Since you want to run an EXE, you've got some additional headaches. You can just spin up a new thread and call the EXE's entry point from it, but many EXE's may get upset since the process is set up for you, not the EXE. It also may well kill your process when it tries to exit. You might want to spawn a new process therefore - perhaps another copy of your main EXE with special arguments to tell it it's going to run some different code - in which case you'd have to fenagle the EXE into its memory space. You'd probably want to do most of the above work in the new process, not the old. You could either create a named pipe and send the data across from one EXE to the other, or allocate a named shared memory area with MapViewOfFile. Of course the EXE may still get upset since the process its running in still isn't its own.
All in all its far easier just to write to a temporary file and then use Process.Start().
If you still want to do it the hard way, take a look at this example in unmanaged code: http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/. This doesn't cover executables, just DLLs, but if the code therein doesn't scare you you'd be fine extending the process to cover executables.

A much better way is to create a temporary DLL file with FILE_FLAG_DELETE_ON_CLOSE attribute. This way the file will be deleted automatically when it is no longer used.
I don't think there is a way to load DLL from a memory (rather than a file).

Its not very easy to create a new process from a memory image, all of the kernel functions are geared towards loading an image from disk. See the process section of the Windows NT/2000 native API reference for more information - page 161 has an example of manually forking a process.
If it is ok to run the code from within your own process then you can create a small DLL that will take a pointer to executable data and run it.

Related

How to detect when a file is checked for in a directory?

I want to be able to programmatically (C#) detect when a program attempts to load (or otherwise access) a non-existent DLL from a directory that I control/own on Windows.
I can manually accomplish this using Sysinternals Process Monitor (ProcMon). For example, using the filters shown below, I am able to detect an attempt by the ClientPrj.exe program, to load a dll (GetEvenOdd.dll) from a directory I control (C:\MyDirectory);
How do I accomplish something similar programmatically?
My attempts thus far have involved manually enabling Windows Auditing on the folder, running the program, and then checking the Windows Event log for any Audit entries, but no new entries appear in the event log related to this folder.
Note, I am not looking to exactly replicate procmon, I simply want to detect when a file (in this case a DLL) is attempted to be loaded from the directory I control.
Side note; It's unclear to me why ProcMon lists the attempt to load the DLL as a "CreateFile" operation, because the "ClientPrj.exe" program is simply trying to Load the DLL (in C++ the "ClientPrj.exe" program is using the the LoadLibrary method to load the DLL).
I thinks is pretty safe to answer this question,
I want to be able to programmatically (C#) detect when a program
attempts to load (or otherwise access) a non-existent DLL from a
directory that I control/own on Windows.
There is really only one reliable way to achieve this, and its really not for the faint-or-heart.
I can manually accomplish this using Sysinternals Process Monitor
(ProcMon).
ProcMon is a very complex application and makes use of all sorts of black magic in Kernel Mode to achieve what it does
DLL injection
In computer programming, DLL injection is a technique used for running
code within the address space of another process by forcing it to load
a dynamic-link library.1 DLL injection is often used by external
programs to influence the behavior of another program in a way its
authors did not anticipate or intend.1[2][3] For example, the
injected code could hook system function calls,[4][5] or read the
contents of password textboxes, which cannot be done the usual way.[6]
A program used to inject arbitrary code into arbitrary processes is
called a DLL injector.
The premise is exceedingly simple, and its a well used technique to do various things.
Basically, you need to inject a DLL into the program address space. The best known and most often used method is "Import Table Patching". Each win32 module (application/DLL) has a so-called "import table", which is basically a list of all APIs, which this module calls. Patching this import table is a quite easy job and works very nicely.
Another more robust method is, you can also directly manipulate the API's binary code in memory. The most often used method is to overwrite the first 5 bytes of the API code with a JMP instruction, which then jumps to your callback function.
In your case you want to Find LoadLibrary in your target application, JMP to a proxy where you can monitor the libraries loaded and also the results of the call, then pass back the results to the original caller.
This is pretty intense stuff, however it is more common that what you think. There are libraries written that Use Drivers that work in Kernel Mode Which work for 64bit and 32Bit applications that take care off all the hard work, you basically just give it a scope a dll and a signature of the apis you want to hook and write a proxy. and it will take care of the rest. At that point you can IPC the results anywhere you like.
Your first problem is setting a hook before it loads your target lib. However once again this has all be done for you. take a look at http://help.madshi.net/madCodeHook.htm
The onyl down side here, is it has to be done with a traditional DLL and not in .net
Anyway good luck
I can only assume that you have not even tried. I just did
private FileSystemWatcher fsWatcher;
public void SetupWatcher()
{
fsWatcher = new FileSystemWatcher();
fsWatcher.Path = #"C:\SomePath\SomeSubFolder\";
fsWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
fsWatcher.Filter = "*.*";
fsWatcher.Changed += FsWatcher_Changed;
fsWatcher.EnableRaisingEvents = true;
System.IO.File.WriteAllText(fsWatcher.Path + "MyFile.txt", "testing" );
}
private void FsWatcher_Changed(object sender, FileSystemEventArgs e)
{
var msg = "Action " + e.ChangeType + "\r\n"
+ "FullPath " + e.FullPath + "\r\n"
+ "Just File Name " + e.Name;
MessageBox.Show(msg);
}
So, even though my "MyFile.txt" does not exist in the folder, as soon as I try to write to it, create, etc, the FsWatcher_Changed event handler is called. I can then check the change type, path of the file, just file name, etc. From that you can detect and confirm if the file name is what you expect (or not) and act on it as needed.
Feedback from comment...
As per from another program... If I am running my program with the above sample SystemFileWatcher and am listening to the entire folder in question.. Then I go to another applications (even ex: Word, Excel, whatever) and try to create a file in this folder, it will still get caught.
If another program is trying to open a file that does not exist, that program would fail out anyhow. Why would you necessarily care if another program fails validating a file to open that does not exist. That is a problem of the other program?

extracting a file without letting the user access it

I was always pretty impressed by those programs that you could install by executing one installer file, which would then extract all the other required files to run the actual program.
And even now im still wondering how you would code a program that extracts files that are literally still inside the program ( so not in some kind of zip) , i've seen tons of installers for games who have this. I need this cause I want to extract a file on the right moment without giving the person who uses the program the ability to delete the file before its extracted, this may seem vague, but I hope i've informed you enough.
I'm just going to say that building an installer is difficult.
I'd recommend using NSIS: http://nsis.sourceforge.net/Main_Page
As for creating a file the user can't access, create a temp file with the correct read/write permissions, extract the data to the temp file, then copy the file where it needs to go.
Extract happens without the user interfering, and copy protection is handled by the OS.
What about changing the build action for the file you want to hide to Embedded Resource, or something like that that compiles the file inside the dll/exe?
Executable program is just file, So you can append any data at you executables. (works for my c++ compiled program)
$ cat executables some_blob_data > new_executables
Since argv[0] of main() is name of your file, you can use this to acess data in this file itself (works for c or c++ and likley for other languages to)
A really simple way to do this is to use your archive tool or one of the dozens of already made installers. WinRar, WinZip and most others allow the creation of self extracting exe files. I know you've said that is not what you want but if you make sure to make it auto exec your installer app and remove all of the temporary files when you're done it really can be very fool proof and professional looking. Obviously, the various installer applications are able to do what you're wanting.
If you really want to do this yourself the easy solution is going to most likely be dependant on your IDE software and language. The generic answer is that you'll need a compression library which can accept a stream as input. Then you'll want to make your actual files into resources inside your installer app. At that point it's just a matter of telling the compression library to read from a stream which is pointed at the resource. How that is done varies greatly from language to language.

process.start() embedded exe without extracting to file first c#

I have an executable embedded into my app resources. ATM I use assembly reflection to extract the executable to its own file and then start the executive using process,START(). Is it possible to run the embedded executable straight from a stream instead of writing it to file first? Could someone please show me the most efficient way to do this please.
Here's what I gather from your question, and your comments:
You want to know if it is possible to execute an executable embedded into your program, without extracting it to disk first
Your program is a .NET program
The executable you want to execute is not a .NET program
The answer to that is: yes
However, the answer to that is also it is very, very, hard
What you have to do is, and note that I do not know all the details about this since I don't do this, but anyway:
Load the executable code into memory
Remap all addresses in the binary image so that they're correct in relation to the base address you loaded the executable at
Possibly load external references, ie. other DLL's that executable need
Remap the addresses of those references
Possibly load references needed by the just loaded referenced DLL's
Remape those dll's
Repeat 3 through 6 until done
Call the code
I'm assuming your question is "can I do 1 and 8", and the answer to that is no.
if it's a .net executable, you should be able to load it into an appdomain and start it that way:
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.load.aspx
Very simple actually:
byte[] bytes = File.ReadAllBytes(path);
a = Assembly.Load(bytes);
Now instead of reading the bytes from a file, read it from the resource and you're done. Actually there is a very good article on that: Dynamically Loading Embedded Resource Assemblies
If you don't want it on a hard drive, you could possible look at saving it to a ram-drive and then run it from there.
It can be done without your native EXE having to touch the disk.
See here....it shows an example of a "process" image being embedded as a Resource. It's read into memory, and then CreateProcess and a number of other things are done to build a valid running "process".
http://www.rohitab.com/discuss/topic/31681-c-run-program-from-memory-and-not-file/

Embedded a *.exe into a dll

does somebody know how can I embedd an exe file into a dll ?
I have a tool which is an exe file that I call from c# code.
The thing is that I want to have 1 dll containing this tool (exe file) and the dll containg my c# code.
Is it possible to embedd this exe file within the resources?
Thx in advance
Sure it is. You can add any file as RC_DATA in application as resource. But I believe you will need to extract it to disk first before calling it!
Which IDE/Language you are using?
[EDIT]
Sorry! you did mention that you are using C#.
Add a resource file to you application (right click application in IDE and select "Add new item".
Use the toolbar in resource editor to add an existing file.
Then extract the exe whenever required by calling code something like:
System.IO.File.WriteAllBytes (#"C:\MyEXE\", Resource1.MyEXE);
It's worth baring in mind that your uses may not be too happy about you doing this. Embedding an executable that they've got no control over into a DLL that you'll extract and run will probably make people worry about the running a Trojan on their machine.
It's better to leave the .EXE in the filesystem and be transparent about what your application is doing.
You can load an Assembly from a byte[]. This can be obtained via the ManifestResourceStream of an embedded resource.
An alternative may be to not embed the .exe itself, but rather include its functionality in the dll, and use rundll32[1] to execute it.
On a side note, remember that when you pull a file from your resources to disk and then execute code on it, you may trigger Windows Data Execution Prevention - basically, Windows tries to automatically detect if something is supposed to be code or data, and if it looks like data (which a resource would), then it will prevent that data from being executed as code.
This becomes a particularly sticky issue if your .NET assembly is going to be used over a network instead of from a local drive - there are all sorts of .NET security configurations that might prevent this from working correctly.
Another option, and not knowing the details of your project, take this with a grain of salt: add a .exe.readme file to your install that describes to any curious users or IT people why there is an executable they weren't expecting in the installation directory :)

Checking if a file is a .NET assembly

I've seen some methods of checking if a PEFile is a .NET assembly by examining the binary structure.
Is that the fastest method to test multiple files? I assume that trying to load each file (e.g. via Assembly.ReflectionOnlyLoad) file might be pretty slow since it'll be loading file type information.
Note: I'm looking for a way to check files programmatically.
I guess Stormenet's answer isn't technically programmatic, so I'll seperate my response into an answer.
For best performance, nothing is going to beat opening the file(s) with a StreamReader, reading the first (n) bytes and checking for the .NET file signature data structures in the byte stream.
Pretty much the same way you'd verify something is a DOS executable:
http://en.wikipedia.org/wiki/DOS_executable
Look for the "MZ" header bytes, which also happen to be the initials of Mark Zbikowski, one of the developers of MS-DOS..
Maybe this helps
from https://web.archive.org/web/20110930194955/http://www.grimes.demon.co.uk/dotnet/vistaAndDotnet.htm
Next, I check to see if it is a .NET assembly. To do this I check to see if the file contains the CLR header. This header contains important information about the location of the .NET code in the file and the version of the framework that was used to write that code. The location of this header is given in the file's Data Directory table. If the data directory item has zero values then the file is unmanaged, if it has non-zero values then the file is a .NET assembly.
You can test this yourself using the dumpbin utility with the /headers switch. This utility will print the various headers in a file on the command line. At the end of the Optional Header Values you'll see a list of the Data Directories (there will always be 16 of them) and if the COM Descriptor Directory has a non-zero location it indicates that the file is a .NET assembly. The contents of the CLR header can also be listed using the /clrheader switch (if the file is unmanaged this will show no values). XP tests for the CLR header when it executes a file and if the CLR header is present it will initialize the runtime and pass the entry point of the assembly to the runtime, so that the file runs totally within the runtime.
In the past I've used AssemblyName.GetAssemblyName(), which throws an exception if it's not a managed assembly. However, I've never performance tested it, so I can't say how fast it is.
Official Documentation
The first link there is going to be the fastest and simplest method of checking (the PE file header one). You're correct in assuming that calling Assembly.ReflectionOnlyLoad is going to be pretty slow.

Categories

Resources