In order to obtain what we want, i.e. fine grained resource control for our "snippets", we can act at two levels:

  • compilation time
  • execution time

Furthermore, we can control execution in three ways:

  1. AppDomain sandboxing: "classical" way, tested, good for security
  2. Hosting the CLR: greater control on resource allocation
  3. Execute in a debugger: even greater control on the executed program. Can be slower, can be complex

Let's examine all the alternatives.

Control at compilation time

Here, as I mentioned, the perfect choice would be to use the new (and open-source) C# compiler.

It divides well compilation phases, has a nice API, and can be used to recognize "unsafe" or undesired code, like unsafe blocks, pointers, creation of unwanted classes or call to undesired methods.

Basically, the idea is to parse the program text into a SyntaxTree, extract the node matching some criteria (e.g. DeclarationModifiers.Unsafe, calls to File.Read, ...), and raise an error. Also, it a possibility is to write a CSharpSyntaxRewriter that encapsulates (for diagnostic) or completely replace some classes or methods.

Unfortunately, Roslyn is not an option: StackOverflow requirements prevents the usage of this new compiler. Why? Well, users may want to show a bug, or ask for a particular behaviour they are seeing in version 1 of C# (no generics), or version 2 (No extension methods, no anonymous delegates, etc.). So, for the sake of fidelity, it is required that the snippet can be compiled with an older version of the compiler (and no, the /langversion switch is not really the same thing).

An alternative is to act at a lower level: IL bytecode. 
It is possible to compile the program, and then inspect the bytecode and even modify it. You can detect all the kind of unsafe code you do not want to execute (unsafe, pointers, ...), detect the usage of Types you do not want to load (e.g. through a whitelist), insert "probes" into the code to help you catch runaway code.

I'm definitely NOT thinking about "solving" the halting problem with some fancy new static analysis technique... :) Don't worry!

I'm talking about intercepting calls to "problematic" methods and wrap them. So for example:

static void ThreadMethod() {
   while (1) {
      new Thread(ThreadMethod).Start();
   }
}
This is a sort of fork bomb

(funny aside: I really coded a fork bomb once, 15 years ago. It was on an old Digital Alpha machine running Digital UNIX we had at the university. The problem was that the machine was used as a terminal server powering all the dumb terminals in the class, so bringing it down meant the whole class halted... whoops!)

After passing it through the IL analyser/transpiler, the method is rewritted (compiled) to:


static void ThreadMethod() {
   while (1) {
      new Wrapped_Thread(ThreadMethod).Start();
   }
}

And in Wrapped_Thread.Start() you can add "probes", perform every check you need, and allow or disallow certain behaviours or patterns. For example, something like: 

if (Monitor[currentSnippet].ThreadCount > MAX_THREADS)
  throw new TooManyThreadException();

if (OtherConditionThatWeWantToEnforce)
  ...

innerThread.Start();


You intercept all the code that deals with threads and wrap it: thread creation, synchronization object creation (and wait), setting thread priority ... and replace them with wrappers that do checks before actually calling the original code.

You can even insert "probes" at predefined points: inside loops (when you parse a while, or a for, or (at IL level), before you jump), before functions calls (to have the ability to check execution status before recursion). These "probes" may be used to perform checks, to yield the thread quantum more often (Thread.Sleep(0)), and/or to check execution time, so you are sure snippets will not take the CPU all by themselves. 

An initial version of Pumpkin used this very approach. I used the great Cecil project from Mono/Xamarin. IL rewriting is not trivial, but at least Cecil makes it less cumbersome. This sub-project is also on GitHub as ManagedPumpkin.

And obviously, whatever solution we may chose, we do not let the user change thread priorities: we may even run all the snippets in a thread with *lower* priority, so the "snippet" manager/supervisor classes are always guaranteed to run.

Control at execution time

Let's start with the basics: AppDomain sandboxing is the bare minimum. We want to run the snippets in a separate AppDomain, with a custom PermissionSet. Possibly starting with an almost empty one. 

Why? Because AppDomains are a unit of isolation in the .NET CLI used to control the scope of execution and resource ownership. It is already there, with the explicit mission of isolating "questionable" assemblies into "partially trusted" AppDomains. You can select from a set of well-known permissions or customize them as appropriate. Sometimes you will hear this approach referred to as sandboxing.

There are plenty of examples on how to do that, it should be simple to implement (for example, the PTRunner project).

AppDomain sandboxing helps with the security aspect, but can do little about resource control. For that, we should look into some form of CLR hosting.

Hosting the CLR

"Hosting" the CLR means running it inside an executable, which is notified of several events and acts as a proxy between the managed code and the unmanaged runtime for some aspects of the execution. It can actually be done in two ways:

1. "Proper" hosting of the CLR, like ASP.NET and SQL Server do

Looking a what you can control through the hosting interface  you see that, for example, you can control and replace all the native implementations of "task-related" (thread) functions.
It MAY seem overkill. But it gives you complete control. For example, there was a time (a beta of CLR v2 IIRC) in which it was possible to run the CLR on fibers, instead of threads. This was dropped, but gives you an idea of the level of control that can be obtained.

2. Hosting through the CLR Profiling API (link1, link2)

You can monitor (and DO!) a lot of things with it: I used it in the past to do on-the-fly IL rewriting (you are notified when a method is JIT-ed and you can modify the IL stream before JIT) (my past project used it for a similar thing, monitor thread synchronization... I should have talked about it on this blog years ago!)

In particular, you can intercept all kind of events relative to memory usage, CPU usage, thread creation, assembly loading, ... (it is a profiler, after all!).
An hypothetical snippet manager running alongside the profiler (which you control, as it is part of your own executable) can then use a set of policies to say "enough!" and terminate the offending snippet's threads.

Debugging

Another project I did in the past involved using the managed debugging API to run code step-by-step.

This gives you plenty of control, even if you do not do step-by-step execution: you can make the debugger code "break into" the debugger at thread creation, exit, ... And you can issue a "break" any time, effectively gaining complete control on the debugged process (after all, you are a debugger: it is your raison d'etre to inspect running code). It can be done at regular intervals, preventing resource depletion by the snippet.


Choices, choices, choices...

How would you design and write a system that takes some C# code and runs it "in the browser"?

In general, my answer would be: Roslyn. Roslyn was already quite hot and mature at the end of 2014; having something like scriptcs would give you complete control on each line of code you are going to execute.

But this particular project, being something that must work for StackOverflow, had several constraints, most of which were in stern contrast one with the other:
  • High fidelity: if I am asking a question about a peculiar problem I am having with C# 1 on .NET 1.1, I want my "snippet" to behave as if it is compiled with C# 1 and run on .NET CLR 1.1
  • Safe: can you just compile and execute your snippet inside your IIS? Mmmm.. not a great idea...
  • High performance: can you spin up a VM (or a container), wait for it to be ready, "deploy" the snippet, execute it, get it back? That would be very safe, but a bit slow.

Safety/security is particularly important. For example: you do not want users to use WMI to shutdown the machine, or open a random port, install a torrent server, read configuration files from your machine, erase files...
For safety, we want to be able to handle dependencies in a sensible way. Also, some assemblies/classes/methods just do no make any sense in this scenario: Windows Forms? Workflow Foundations? Sql?
For safety and performace, we want to monitor and cap resource usage (no snippet that does not terminate).

Going a deep further, I stared to dash out some constraints. It turns out that we need to disallow something, even if this means going againt the goal of "high-fidelity":
  • no "unsafe", no pointers
  • no p/invoke or unmanaged code
  • nothing from the server that runs the snippet is accessible: no file read, no access to local registry (read OR write!)
  • no arbitrary external dependency (assemblies): whitelist assemblies

Also, we need control over some "resources". We cannot allow snippets to get a unlimited or uncontrolled amount of them.
  1. limit execution time
    • per process/per thread?
    • running time/execution time
  2. limit kernel objects
    • thread creation (avoid "fork-bombs")
    • limit other too? Events, mutexes, semaphores...
    • deny (or handle in a sensible way) access to named kernel objects (e.g. named semaphores.. you do not want some casual interaction with them!)
  3. limit process creation (zero?)
  4. limit memory usage
  5. limit file usage (no files)
  6. limit network usage (no network)
    • in the future: virtual network, virtual files?
  7. limit output (Console.WriteLine, Debug.out...)
    • and of course redirect it
Does it sounds familiar? For me, it was when I learned about something called cgroups. Too bad we don't have it in windows! Yes, there are Job Objects, but they do not cover every aspect.

Could we have cgroups-like control for .NET applications?


Pumpink: a .NET "container"

More or less 20 months ago (gosh, time flies!) I started a side-project for a very famous company (StackExchange).
StackExchange had just launched, a few months before, a new feature on the main site of their network (StackOverflow).
This feature is called "Code Snippets", and it allows you to embed some sample HTML + JS code in a Question, or an Answer, and let the visitors of the page run it.
Of course, being JS it would run inside the browser, and with few focused precautions it can be made safe for both servers and clients (you do not want to leave an attack vector open on your servers, but you also don't want your visitors to be attacked/exploited as well!)

More details on how they implemented and safeguarded it can be found on their meta.stackoverflow.com site.

The feature got a lot of attention, and of course there where requests to extend it to other languages.
I was one of those that wanted more languages added, but I understood that JS was a very particular case.
Snippets in any other language would have meant an entirely different approach and an entirely different scale of complexity.

In October 2014 I visited NYC; before my visit I got in touch with David Fullerton, the "big boss" of SO development team. We were in touch since my previous "adventure", a few years before, when I interviewed for a position on their Q&A team. We discussed briefly about my past interview, and then he asked me a very interesting question: what would I add to StackOverflow? C# snippets immediately come to my mind.

We discussed briefly about it, drafted up some ideas, added requirements in the process (discarding most of the ideas) and finally David asked if I would like to try it out, as an Open Source experiment sponsored buy StackExchange.

... well, of course! Fun and challenging software, exchanging ideas with some of the most brilliant devs in the .NET ecosystem, and I get paid too! :)

So "Pumpink" was born. If you are curious, you can find it on my GitHub. It already contains a rather in-depth analysis about the structure of the project, and how it works.

Or, if you want to know "why?" instead of simply "how?", you can wait for the upcoming blog posts, in which I will detail some of the choices, problems, headaches that shaped the problem.


Recently, I was fighting with a Primefaces component: calendar. I was using it with my keyboard, and I immediately noticed that the ajax update that keeps the control synchronized with the bean was not working. Selecting a date with the mouse was fine, editing and pressing "Enter" was OK, but changing it and tabbing or clicking away was not.

Curious, I dug in and found that primefaces uses the standart jQuery UI datepicker, and wires itself to its standard onSelect event. But this event is fired only when you explicitly select a date, not when a date changes (through the keyboard, or code).

So, I decided to write a quick js to call onSelect when a date is updated. Here it is: I also keep track of the previous date, to avoid double notifications. And it works very well for us!

Strangest bug of the day

System.TypeLoadException:
Could not load type 'System.Diagnostic.Debug'
from assembly 'MyAssembly'

Uhm... Hello?
Why are you looking for 'System.Diagnostic.Debug' inside my assembly? Go look inside System!

To be fair, I was fiddling with the CLR Hosting APIs, in particular IHostAssemblyStore.
Using this interface, you can override the CLR assemby probing logic, and load you own assemblies from wherever you want.
This is particularly helpful if you are using your own AppDomainManager, and you want to load it inside your sandboxed domain, which you carefully configured to disallow loading of any external assembly.
If you try to do that, binding fails, obviously. And since the AppDomainManager is created and loaded by the unmanaged portion of the CLR, you don't get a chance to use AssemblyResolve (tried, didn't work).

But that does not really justify this behavior: the Fusion log viewer was reporting no errors, and the exception was wrong (or, at least, not one of the usual exceptions you should look for when debugging binging failures).

There is a tiny parameter, called pAssemblyId. The docs are quite clear: it is used internally to see if that assembly was already loaded.
If it is, do not try to load it again. Sounds like a good optimization BUT:

The docs don't say it, but if you pass back "0", something very peculiar happens.
In my case, I had the Jitter looking for types inside my assembly. Others had different issues.

That was definitely the strangest bug of the day :)


Copyright 2020 - Lorenzo Dematte