Our application parses and compiles user input as C# code and this has introduced some security issues. Usually, a user will create expressions using basic arithmetic operators and functions from the math library. However, it is also possible to write an expression that executes arbitrary code as long as it returns the expected type.
ex. new System.Threading.Thread(<malicious code>).ManagedThreadId
We are using the CSharpCompilation
class together with the static methods from SyntaxFactory
to compile the expressions.
Basically what I need is some way to restrict what types or methods that can be used in the expressions. My first thought was to use a blacklist/whitelist approach, but I am not familiar with the CodeAnalysis namespace and was hoping someone could point me in the right direction.
It would also be great if someone could explain to me how the above example compiles successfully when no reference to System.Threading
has been added to the CSharpCompilation
instance?