How to prevent access to local file system - c#

I have a situation in which my (C#) application can load external DLLs (not written by me) and execute code from those libraries. The libraries can be C# or CPP.
I need to make sure this external code won't access any files in my local file system (read and write) except from a specific folder.
How can i do that?

I've seen third-party code that does this; for example, Jint lets you write JavaScript scripts that manipulate CLR objects, but it prevents any JavaScript-originated code paths from accessing the filesystem, Reflection, etc. by using permissions.
You can read Jint's documentation and poke through their source code for more details, but the essence of it seems to be this:
PermissionSet myPermissionSet = new PermissionSet(PermissionState.None);
// or some other permission set, depending on your requirements
try {
myPermissionSet.PermitOnly();
// run untrusted code
} finally {
CodeAccessSecurity.RevertPermitOnly();
}
A lot of things I've read say you need to create a sandboxed Appdomain (something I've never had much success with), but Jint's approach seems to work pretty well. You might have to watch out for the third-party code hooking static events that would fire later, though -- then they could escape the PermitOnly scope.

Run the application as a restricted user account and only grant the user access to that specific folder.

Secure the files through the OS facilities (filesystem privs), create an account that can access only those files and use this account to run the application

It depends on your framework, but you can use Caspol (Code Access Security Policy) up to .Net 3.5 (and I think C++ DLLs also) to specify security privileges including IO access.
Hope that helps :)

Take a look at Molebox, maybe it will fit your needs. Molebox lets you wrap modules to sandbox them.

Related

Roslyn c# scripting sandbox

Is there a way to sandbox execution of a script such that it a) Can't do anything "dangerous" and b) it can access any files it wants to so long as the file is within the same directory as the script file itself. Kind-of as-if it were to treat all file-paths as relative.
I guess I'm asking about Roslyn's scripting security measures and their level of customization.
This is possible, but as SLaks says, it is a hard problem. You should probably read In .NET 4.0, how do I 'sandbox' an in-memory assembly and execute a method?. You would need the following steps
Use a CSharpCodeProvider or VBCodeProvider to compile the source to an assembly on the harddrive.
Create a new AppDomain granting it only those permissions you would like it to have.
Use MarshalByRefObject's to communicate back and forth between your original AppDomain and the child AppDomain you've just created. See this and this.

How do I open OLEDB Prompt for 32-bit from x64

Good day everyone,
I am writing a C# application that will allow users to dynamically set the database they want to connect to (I'll work a bit with the database data and such, but that's not important). The important part is that I'm allowing my users to connect to data-stores from OLEDB using the code below.
ADODB.Connection connection;
MSDASC.DataLinks instance = new MSDASC.DataLinksClass();
if( (connection = instance.PromptNew() as ADODB.Connection) == null ) return;
This will open the very same Dialog that windows opens for *.udl files, and that's exactly what I want.
However, I hit a interesting problem to which your brightness could come in handy: some customer WILL have to browse for x86 drivers, and the vast majority will certainly use x64.
I know you can open x86 UDL files with the following command-line:
"C:\Windows\syswow64\rundll32.exe" "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile "C:\myConnectionFile.udl"
When the default (64 bit) command is:
"C:\Program Files\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile "C:\myConnectionFile.udl"
In other words: windows' allowing users to create entries in both fashion. I would like to do the same in my app, using the API.
I have considered the option of creating a temp UDL file and opening from the command-line above, which made my conversation with my technical lead rather unpleasant, so that's not an option.
All suggestions are welcome. I will not dismiss unsafe coding nor the thought of building wrapper in C++ if we get to that (although my C++ is inconveniently rusty nowadays).
Thank you all in advance and happy coding...
Good day fellow developers,
After a tedious and lengthy research process I have around the answer I was looking for.
In order to use OLEDB providers for both 32 and 64 bit platform from one single C# 64bit app I'll need to create an Out-of-Process Wrapper to the 32bit call, and make the call over IPC (Internal Process Calls). Because the amount of functionalities I'm exposing is moderate, the hindrance was just re-creating some method calls on the wrapper.
This blog helped me put the parts together, and now I'm able to determine what type of OLEDB connection I'll allow my user create, and I'm also able to perform all operations I need regardless of the Provider Architecture.
I hope this will benefit other people who might be having the issue.
If time (and NDA) allows, I'll get the code here for people to copy and try it later.
These links were also very useful on my research
http://blog.mattmags.com/2007/06/30/accessing-32-bit-dlls-from-64-bit-code/
Registering the DLL Server for Surrogate Activation
https: // msdn.microsoft.com/en-us/library/windows/desktop/ms686606(v=vs.85).aspx)
Writing Serviced Component
https: // msdn.microsoft.com/en-us/library/3x7357ez(VS.80).aspx)
How to: Create Serviced Component
https: // msdn.microsoft.com/en-us/library/ty17dz7h(VS.80).aspx)
Create Out-Of-Process COM in C#/.Net?http: // stackoverflow.com/questions/446417/create-out-of-process-com-in-c-net
Thanks everyone
D

.NET Windows API Check if folder accessed

I am searching for a function that allows me to put a dialog-window(w/ a password query) before the folder is accessed. Is there such a function? Also, this would be great if this protection is there before any program, even Windows Explorer/cmd.exe are allowed to access those files. Is that possible to make?
I'm not using something like IOContainer, passwd. protected ZIPs or any other things that are too slow, because I guess 20GB in one file are a bit overkill and it would take ages to decrypt that file. Is there maybe a VFS solution for C# which supports password protection and can be used as a normal filesystem or folder on the disk?
Thanks!
There exist two options. The simpler one is to have a virtual file system mapped from the file. Our product, SolFS (OS edition), does exactly what you are asking in the second part of your question - it provides a container with optional encryption, which is exposed as a virtual drive so that access to the contents is transparent. Decryption in such systems is done in pages, so 20GB-large file won't be decrypted in whole as you worry.
Another option is to employ a filesystem filter driver, which will intercept requests for directory opening, and will ask the user for a password. This approach is possible (we even have a product for this, called CallbackFilter), but there are two drawbacks in it: first, it's not impossible to remove the driver, leaving the data unprotected. And the second problem is that if you ask the user for a password in a callback, while the OS is waiting for access to the directory, you can end up in a deadlock or a timeout while the user is thinking.
With these two limitations in mind something like SolFS is the preferred and recommended approach.
PS: and we have free non-commercial licenses as well.

C# DLL from VBScript, no regasm

Is it possible to access a C# DLL's method from VBScript without registering it with regasm? I will be creating the DLL so pretty much any exotic requirement to make it visible to VBScript, I can do...
I have read here that it might be possible to use GetObject from VBScript to achieve this, but I have tried that with no success... Is there anything else I need to do aside from making the DLL "COM visible" to make this work?
The reason why I need to avoid regasm is that it requires admin rights, and I need to deploy this DLL "silently" to many clients that may or may not have admin rights.
No, registration is required, the only way that the script interpreter can find the DLL that contains the ProgId that you use in the script's CreateObject() call. Isolated COM with a manifest doesn't work, you can't modify the manifest for the script interpreter.
There is a technical solution, you can write registry keys in the HKCU registry hive without acquiring UAC elevation. The Regasm.exe tool always writes them in the HKLM hive. That registers the assembly as well, but only for the user that runs Regasm.exe. It is however pretty painful and easy to get wrong, you have to write your own registration method and apply the [ComRegisterFunction] attribute. It is now your job to use the RegistryKey class to set the keys. Same for the [ComUnregisterFunction], it should delete the keys again. There are a lot of bad examples out on the interwebs, best way to get this right is to use SysInternals' ProcMon to observe the registry keys that get written when you use Regasm.exe normally, then reproduce that in your own code, using HKCU instead.
Do note the other side of that medal, you are in fact making configuration changes to the machine that allows arbitrary code to run. Trying to hide that doesn't do the user any favors and should never be considered if you honor the user's desire to keep the machine safe and predictable. UAC is not there to stop you from making changes, it is only there to inform the user about it.
The accepted answer is incorrect that registration is required to use a DLL. You can use the GetObject() method instead of the CreateObject() method as shown in my answer to this question.
Using DLLs in VBScript

How to test whether a given functional code unit (C#) does NOT create/write any files to disk?

Imagine there's a mission-critical process that'll be used in a business which handles sensitive information (think of Credit Card, social security, patient records...etc). I would think this unit ideally should do whatever it has to do on-the-fly, meaning it won't intentionally write files to disk containing sensitive information. The idea here is that if the computer that runs this process is compromised, no sensitive information can be leaked, at least not by means of files.
What approaches could be taken to, say, come up with a unit test that will fail if the unit under test tries to write any file to disk?
There is the FileSystemWatcher (http://www.c-sharpcorner.com/uploadfile/puranindia/filesystemwatcher-in-C-Sharp/) however this requires you to know a specific directory. In your case this probably isn't very helpful since the program could write anything to disk any where. This introduces a unique problem. However, I have also found something called Detours from Microsoft. This appears to intercept all native win32 api calls. http://research.microsoft.com/en-us/projects/detours/ The issue with this is that its kind of hard to test, and integrating it into unit testing will be a challenge.
When you have to treat your software as "untrusted" in the sense that you need to prove it doesn't do something, testing becomes a complex task that requires you to run them on very controlled environments. When hooking in to the Win32 API, you will be deluged with API calls that need to be processed quickly. This can result in unintentional side effects because the application is not running in a truly native environment.
My suggestion to you (having worked several years doing software testing for Pharma automation to the exacting standards of the FDA) is to create a controlled environment, eg a virtual machine, that has a known starting state. This can be accomplished by never actually saving vmdk changes to disk. You have to take a snapshot of the file system. You can do this by writing a C# app to enumerate all files on the virtual drive, getting their size, some timestamps and maybe even a hash of the file. This can be time consuming so you may want (or be able) to skip the hashing. Create some sort of report, easiest would be by dropping them in a CSV or XML export. You then run your software under normal circumstances for a set period of time. Once this is complete, you run a file system analysis again and compare the results. There are some good apps out there for comparing file contents (like WinMerge). When taking these snap shots, the best way to do it would be to mount the vmdk as a drive in the host OS. This will bypass any file locks the guest OS might have.
This method is time intensive but quite thorough. If you don't need something of this depth, you can use something like Process Monitor and write the output to a file and run a report against that. However in my work I would have to prove that Process Monitor shows all IO before I could use it which can be just as hard as the method I spoke of above.
Just my 2 cents.
UPDATE:
I've been thinking about it, and you might be able to achieve fairly reliable results if you remove all references to System.IO from your code. Write a library to wrap around System.IO that either does not implement a write method, or only implements one that also writes to a log file. In this case, you simply have to validate that every time a write occurs using your library, it gets logged. Then validate using reflection that you don't reference System.IO outside of this new wrapper library. Your tests can then simply look at this log file to make sure only approved writes are occurring. You could make use of a SQL Database instead of a flat log file to help avoid cases of tampering or contaminated results. This should be much easier to validate than trying to script a virtual machine setup like I described above. This, of course, all requires you to access to the source code of the "untrusted" application, although since you are unit testing it, I assume you do.
1st option:
Maybe you could use Code Access Security, but the "Deny" is obsolete in .NET 4 (but should works in previous version):
[FileIOPermission(SecurityAction.Deny)]
public class MyClass
{
...
}
You may reactivate this behavior in .NET 4 using NetFx40_LegacySecurityPolicy
2nd option:
reducing the level of privilege may also works, as I know that downloaded app can't write on the disk and must use a special storage area.
3rd option:
Remove any reference to System.IO and replace by an interface that your code must use to write data to disk.
Then write an implementation that use System.IO (in a separate project)
In the nunit test, mock this interface and throw an exception when a method id called.
Problem is to ensure any developers will not call System.IO anymore. You can try to do this by enforcing coding rules using FxCop (or other similar tools)

Categories