Run a program from an array of bytes without creating a temporary file . c#

后端 未结 3 1804
眼角桃花
眼角桃花 2021-01-25 04:47

I have many .exe files stored on IIS server (MSSQL) that contain reports and access to the file(s) on the servers . (These files will be change on Sundays .)

After conne

相关标签:
3条回答
  • 2021-01-25 05:02

    There are two different concerns for security here:

    1. That someone can see the file that you've downloaded from the database.
    2. That executing the file might be a security threat.

    For the first concern: Create a directory on the server and restrict access to that directory so that no one but the user account that runs your server program can see/use it. Save the byte array into a temporary file in that directory, execute it, and once the process has completed, delete the temporary file.

    For the second concern: You'll need to run that executable in a sandboxed environment. In .NET you can run code in a sandboxed environment by loading the code into a separate AppDomain that you've setup to only have partial trust. How to do that deserves another question on SO though.

    0 讨论(0)
  • 2021-01-25 05:16

    Doesn't sound safe either way, why are you storing exécutables in a db to begin with? Who uploads them? Wether they're on the filesystem or not they're just as dangerous if malicious.

    Are those .net exes? If so you could load the assembly into a child appdomain with security restrictions and i'm pretty sure you can do that without copying to disk.

    For regular native exe i don't think it's possible to just launch an exe without a physical file backing it (even in the task manager you can see the path from which a program was launched)

    0 讨论(0)
  • 2021-01-25 05:18

    Be warned that your belief of any extra security is illusory. If the user has access to the machine to read files, they will also be able to read the memory of your process.

    However, to answer your question, what you are asking to do is simple enough and described here: Load an EXE File and Run It from Memory.

    In essence you do the following:

    1. Pass your byte array to Assembly.Load to create a new Assembly.
    2. Read the entry point of that assembly using the EntryPoint property.
    3. Create an instance using Assembly.CreateInstance, and invoke the method on that instance.

    The code looks like this:

    Assembly a = Assembly.Load(bytes);
    MethodInfo method = a.EntryPoint;
    if (method != null)
        method.Invoke(a.CreateInstance(method.Name), null);
    
    0 讨论(0)
提交回复
热议问题