Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if a class is referenced C#

I'm curious if it is possible to determine whether or not an Assembly has referenced a particular class or not. I'm currently using Reflection to load Assemblies and then I determine what Assemblies are being referenced from within the assembly I am loading:

foreach (var vReferencedAssembly in vSomeAssembly.GetReferencedAssemblies())

Now that I know what Assemblies are referenced, I want to dig into those vReferencedAssembly and determine if something like this occurs:

File.Create(vSomeFile);

In simple english, I don't want to load an Assembly from a list supplied to me that may contain what I consider a threat. So I may want to block things that may manipulate files and so forth.

like image 579
Tada Avatar asked Nov 04 '22 21:11

Tada


1 Answers

I believe what you're looking for is to load assemblies into the reflection only context. This allows you to load them into a safe area where no code will be executed until after you're inspected them.

See: http://msdn.microsoft.com/en-us/library/ms172331.aspx

Update: You may use reflection to look at things like, variables, properties, parameters, return types but that still won't help you detect malicious code that's completely contained inside a method. It is my understanding that distinguishing between safe and unsafe code is best left to the system administrator. These applications have an implicit trust relationship to a secured location(s) on the PC. IE: the global assembly cache, the current working directory or some fixed path determined by your application. The PC then only grants administrators the ability to manage the assemblies in this location.

Update 2: You may also consider running this potentially unsafe code in it's own application domain. Here you can set what is permitted and what isn't. See http://msdn.microsoft.com/en-us/library/bb763046.aspx.

Update 3: While I still maintain that loading untrusted code in it's own application domain with appropriate permissions is the cleanest approach, it is possible to determine what a method internally references at runtime as was asked by this question. The gist of it is to use reflection to obtain the raw IL bytes of the method (MethodBody.GetILAsByteArray) and analyse it with your choice of IL parser.

like image 104
Chris Kerekes Avatar answered Nov 09 '22 05:11

Chris Kerekes