Limiting Functionality of Dynamic Invocation in C# - c#

I have created some utility code that allows me to take text entered into our content management system and dynamically compile and invoke it with a method similar to this.
But this raises a security risk--since a content author could mistakenly (or worse--maliciously) enter code that would do things outside of what I am looking for. Any recommendations for keeping this functionality open, but be able to prevent certain types of code from being written? For example, there are obvious things to limit like writing to the file system.
My initial thought is excluding certain assemblies, but I am curious if anyone has any clever ideas on this.

Don't do this. There are endless possibilities for what a user could write and you won't be able to prevent them all. In security you should always specify what a user can do instead of what he can't do (whitelist instead of blacklist) because you will miss something if you do it otherwise.
In this specific case, allowing a user to write arbitrary code never seems like a good idea. Instead, you should choose specific operations that a user can perform and add a button/control for each one.

If you REALLY need such functionality consider creating very limited functionality. Don't allow users to enter text; give them "blocks".
Start with very basic, limited set of instructions and add new ones only when asked to.

Related

Isn't accessing private fields and properties due to reflection a security issue?

I just recently found out here that it is possible (at least in c#) to look up private fields and properties due to reflection.
I was surprised, although I knew that somehow constructs like the DataContractSerializer class need the possibility to access them.
The question now is, if anyone can access every field in my classes, this is kind of insecure, isn't it? I mean what if someone has a private bool _isLicensed field. It could be changed easily!
Later I found out here that the field accessors are not meant as a security mechanism.
So how do I make my Application safe, meaning how do I prevent anyone other than me from changing essential status values inside my classes?
The question now is, if anyone can access every field in my classes, this is kind of insecure, isn't it?
Not everyone can. Only code with sufficient permissions - trusted code. Untrusted code is restricted quite a bit. On the other hand, if the person who wants to use reflection has your assembly, they can run trusted code on their own machine. That's not a new attack vector though, as if they've got your code they could also modify it to make the field public in the first place.
Basically, if code is running on their machine, you should expect them to be able to do pretty much anything with it. Don't rely on access modifiers to keep anything secret.
So how do I make my Application safe, meaning how do I prevent anyone other than me from changing essential status values inside my classes?
If the hostile user is running your code themselves, you pretty much can't. You can make it harder for them, but that's an arms race which is no fun.
So one option in some cases is not to let anyone else run your code - host it on the web in an environment you've locked down. That's not appropriate in all cases, of course.
If you have to let users run the code themselves, you need to weigh up the downsides of them tampering with the costs of making that tampering difficult. We can't really help you with that balancing act - we don't have any idea what your application is, or what the costs involved are (reputational, financial etc).
private public and so on are a part of http://en.wikipedia.org/wiki/Encapsulation. the use is to make your API clear and to avoid mistakes.
there is no solid way to avoid people messing with your program.
you may have noticed that all programs are cracked in a few days usually.
in .net it is VERY easy because of IL code been very readable http://ilspy.net/ and such allow you to take any DLL and just read it like C# code.
you can make it more annoying to read your code using obfuscator
http://en.wikipedia.org/wiki/List_of_obfuscators_for_.NET
but applications like http://de4dot.com/
break this VERY easily.
SecureString is a nice trick: https://msdn.microsoft.com/en-us/library/system.security.securestring%28v=vs.110%29.aspx
writing your code in low level language like c++ might make cracking your code really annoying. but soon a skilled hacker will do whatever he wants with your program.
the only option that might be safe is providing your application as a cloud service where the user only sees the screen output and sends keyboard/mouse input.
This was meant to be a comment for John Skeets answer but ran out of room..
Great answer by the way, but I also must add that code is not meant to be secure its meant to clearly defined.
Most developers know how to change classes and inject into classes. There are many utilities to not only decompile your code but to also allow injection into it.
I wouldn't spend to much effort trying to your make code more secure, I would try and expect the code to be changed. Many programming languages do not have such modifiers as private, public, internal, protected etc. They rely on the developers to understand the consequences of using this code on their own. These programming languages have been quite successful as the developers understand that modifying, calling or injecting into code the API does not specify has results that the developing company cant and will not support.
Therefore, expect your code to be modified and ensure your applications responds to invalid changes appropriately.
Sorry if this seems like a comment...
To add to all the other answers, a simple way of looking at it is this: If the user really wants to break your code, let them. You don't have to support that usage.
Just don't use access modifiers for security. Everything else is user experience.

Implementing a refactoring system for my autogenerated code

I have a little visual system for generation FSM's where the user can draw a graph using boxes (states) and link them with lines (transitions). This, in the end, generates c# code when user presses the "Generate code" button that defines the FSM in runtime.
I want my users to be able to change things like graph name, transitions names, states names, delete nodes, delete transitions and a bit more after the first save, so, I need a way to handle refactoring.
I'm struggling trying to find a non intrusive way to accomplish this. Have tried to apply a modification of a do/redo algorithm I made some time ago but couldn't be able to get something nice.
Could anyone explain how to create such a system, making it as less intrussive with existent code as possible?
Cheers.
I would suggest keeping the state in your graph datastructure, and generating the C# code anew on changes to the FSM, this is a simple solution that will allow arbitrary modification of the FSM-datastructure without having to worry about applying said modifications to the generated code.
For implementing 'refactorings' of the base FSM-data structure, you could use something like a Command Pattern to encapsulate the refactorings and undo/redo operations.

Writing and changing code at runtime

I have a situation where I'd like to build MVC style views at runtime using their EditorFor/DisplayFor templates (or something similar).
Ideally our application would let the user choose which fields they want in their UI (so they can add /remove any as they see fit), to this end I thinking it'd be handy to be create viewmodel classess at runtime and add the various dataannotation attributes to them according to what user selects (ie. stringlength, required etc).
One thing I need to be able to support is changing of the generated classes at runtime without affecting other users or having to do a full iisreset.
To go about this I've been doing a bit of research and it seems like there might be 3 different approaches, CodeDom, RunSharp / Relfection.Emit,Roslyn.
From what I can tell reflection.Emit/Runsharp would allow me to create the classes and add attibutes and properties to them at runtime and probably also modify them when I need to without adverse effects.
I'm not sure if Roslyn would allow this, I haven't been able to track down any simple examples of creating a class with properties or attributes in it, and I've seen a few mentions that Roslyn's output is immutable so I'm not sure how that goes for allowing me to modify it at a later date without adverse effects.
In general from what I've seen most people don't recommend CodeDom so I'm not entirely sure if I should bother going down that route.
Can anyone give me an idea of which of these directions might be viable for me?
So, none of these solutions are going to work, and honestly, generating type at runtime really isn't what you want here.
When it comes to the CLR, once you have a type with fields and methods, you can't really add new members or change members at runtime. The closest we come to doing that is the edit-and-continue features in Visual Studio, we're highly restricted to what changes we can make. We often 'cheat' by not adding methods or attributes where you think they added, but we hide them somewhere else and emit IL that references this secret location when you make an edit. Crazy things like removing members is entirely unsupported. Even if it was supported, lots of code likes to presume that doing someObject.GetType().GetMembers() returns the same thing over and over again.
As far as Roslyn is concerned, when we say the results are "immutable" we don't mean that puts any requirement on any IL that you might generate with it. Rather, when you ask Roslyn to parse something or analyze source code, the objects (syntax trees, type information, etc) is immutable. Still, it doesn't matter since you can't modify types in the CLR once they exist.
I'm with svick in his comment -- this isn't what you want to do. Use some appropriate data structures to represent your information at runtime, rather than trying to think of this as a concrete class that can be mutated somehow.

ASP.NET MVC 3 Razor View Restrictions

I apologize in advance for the generic nature of my question, but I was unable to find any helpful advice from people trying to do the same thing as me on the web. Let me describe my scenario:
I am providing end users/designers of a website the ability to customize their views by storing the views (using Razor) in the database. I have all of this working, but my question is the following; From a security standpoint, how can I ensure and enforce that unwanted code doesn't get executed in the user-defined view? There are two basic approaches that I think will work conceptually, but am not sure which one is more possible or feasible.
Option 1: Create a validation method in the administration tool that allows the user to input the view code. This would need to either take a whitelist or blacklist approach to what is allowable or not.
Option 2: Prevent unwanted code from being able to execute when rendering of the view occurs.
As a quick example of something that would need to be blocked, we wouldn't want to allow access to read or write files, access any data access functions, or even access configuration settings, etc. in the web.config. There will likely be a decently-sized list of things that probably shouldn't be allowable, but I'll need to sit down and try to think of as many security-related concerns as possible.
My question then is, which method would be the best bet? Also, can any direction be provided on how to go about either? I thought I might be able to make trust-level based change which would be Option 2, but couldn't find any way to make that work in a per-view based manor (the administration code is allowed to execute whatever it wants). I'm thinking Option 1 will end up being the best bet and I'll have to check for the input of certain framework functions that shouldn't be allowed. Does anyone have any experience doing anything like what I'm trying to do? ANY feedback is much appreciated!
This would be extremely difficult.
You could run the the template through the Razor preprocessor, then use Roslyn (still in early beta) to parse the generated file and look through all method calls (or constructors) and return an error if it calls something you don't like.
I strongly recommend that you use a whitelist for that, since the .Net framework is big enough that you are bound to overlook something in a blacklist.
However, I would instead recommend that you not use Razor at all and instead use a templating engine that does not allow real C# code.

Ideas needed for manual obfuscation

I want to avoid my program being simple to have the license-verifier part removed from.
I don't want to use a commercial obfuscator because:
Of the cost. And though they can do a better job than I – they
too don't make it impossible to crack, just harder.
It seems that sometimes obfuscators cause bugs in the generated
code.
Obviously, I will be keeping an un-obfuscated copy for maintenance.
I once had to hide a license verifier in code that the customer could modify. Conceivably, they could have removed it if they knew where to look. Here are some tricks that I used at the time.
Give your verifier classes, assembly names, and variable names that look like they actually do something else.
Call the verifier from multiple parts of the code.
Add a randomizer to the call for verification so that sometimes it runs, and sometimes it doesn't. This will make it harder to know where the verification code is actually coming from.
I should add that all of this is defeatable and could cause serious maintenance headaches, but in my particular scenario it worked.
If your intent is to make it harder, but not impossible, one way is to have multiple code points that check your licence file is valid.
Lets say you have a licence file with some key like so
abc-def-fhi-asdf
So, four parts to the key. We would then create four different methods that check for the various parts of the key.
By doing this, and varying the methods used through the code (ideally, randomly choosing the verification method at runtime), you make it significantly more difficult to remove the validation.
on top of this, one method would be to have a publish process that inlined your verification method, subtly changing it each time it is called.
for example something like this:
*user clicks a common function
// [VALIDATION STUB]
*perform user action
The new publish process runs through the code, pulling out // [VALIDATION STUB] and replacing it with your validation code (before the code is compiled), which as I say should vary as much as possible each time.
The main thing to pull from my answer really is that obfuscation is hard, but not impossible. Especially if you resign yourself to the reality that the malevolent user will always break it eventually
I have some suggestions that you may find usefull.
First of course you can use free obfuscators like the one that comes with VisualStudio. It's better than nothing.
Second you can write your license verification code and once it's working fine, refactor it as much as you can, change class names, member variables, local variables and methods to something like c1, v1, l1, m1 and so on. That's basically what obfuscators do.
Third, do all of the above.
Fourth, write your licence verification in unmanaged code (C++, Delphi) and make it a DLL named something important like core.dll, net.dll etc. You can also put some decoy methods in there that would do nothing important. Make many calls to that DLL from multiple places of your code and pretend that you do something with the results of those calls.

Categories