DEV Community

Cover image for Introducing SecureCSharpEval: Revolutionize Your Dynamic C# Code Execution
Duc Nguyen Thanh
Duc Nguyen Thanh

Posted on

Introducing SecureCSharpEval: Revolutionize Your Dynamic C# Code Execution

Are you looking for a robust and secure way to execute dynamic C# code without compromising your system? Meet SecureCSharpEval—a cutting-edge library that offers safe, controlled, and efficient code evaluation for your .NET projects.


SecureCSharpEval

What is SecureCSharpEval?

SecureCSharpEval is an innovative library designed to dynamically execute C# code in a secure environment. Built with modern development needs in mind, it safeguards your applications by sandboxing code execution to prevent unauthorized file access, process spawning, and system manipulation. Whether you’re developing a plugin system, a dynamic evaluator, or simply need to execute user-provided scripts, SecureCSharpEval has got you covered.

Why Choose SecureCSharpEval?

Bulletproof Security

  • Sandboxed Execution: Prevents risky operations by isolating executed code from sensitive system resources.
  • Shell Execution Control: Although shell execution is supported, it’s disabled by default to ensure maximum security.
  • Input Validation: Encourages rigorous input validation, ensuring that only trusted scripts run.

Developer-Friendly Features

  • Timeout & Memory Limits: Easily configure execution timeouts and memory usage to keep your application running smoothly even under heavy loads.
  • Seamless .NET Compatibility: Works flawlessly with .NET 6, 7, 8, and 9, making it a versatile choice for modern applications.
  • Simple Installation: Integrate the library quickly via NuGet with just one command.

Quick Start: Installation and Example

Getting started with SecureCSharpEval is a breeze. Simply install the package from NuGet:

Install-Package SecureCSharpEval

Enter fullscreen mode Exit fullscreen mode

Once installed, you can start evaluating C# scripts securely. Here’s a fun example to determine if a number is prime:

class Program
{
    private static string checkPrime = @"
    static bool IsPrime(int n)
    {
        if (n < 2) return false;
        for (int i = 2; i * i <= n; i++)
        {
            if (n % i == 0) return false;
        }
        return true;
    };
    return IsPrime(number);
    ";

    static async Task Main(string[] args)
    {
        var n = 4;
        var evaluator = new ScriptEvaluator();

        Console.WriteLine("Before: {0}", n);

        var parameters = new Dictionary<string, object>
        {
            { "number", n },
        };

        var result = await evaluator.EvaluateAsync(checkPrime, parameters);

        if (result.HasError)
        {
            Console.WriteLine($"Error: {result.ErrorMessage}");
        }
        else
        {
            Console.WriteLine($"Is Prime: {result.Result}");
            Console.WriteLine($"Execution Time: {result.ExecutionTimeMs}ms");
        }

        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

Configuring Security Options

ScriptEvaluator(new SecurityConfiguration()
{
    TimeoutMs = 3000,  // Increase timeout to 3 seconds
    BlockedKeywords  = new HashSet<string>{},
    BlockedNamespaces =  new HashSet<string>{};
}
Enter fullscreen mode Exit fullscreen mode

Security Configuration Default

AllowedNamespaces: [
    System,
    System.Collections.Generic,
    System.Linq,
    System.Text,
    System.Threading.Tasks
]
BlockedNamespaces: [
    System.IO,
    System.Net,
    System.Reflection,
    System.Diagnostics,
    System.Runtime,
    Microsoft.Win32
]
BlockedKeywords: [
    unsafe,
    fixed,
    stackalloc,
    Process,
    File,
    Directory,
    Registry,
    Socket,
    WebClient,
    HttpClient
]
TimeoutMs: 5000ms (5 seconds)
Enter fullscreen mode Exit fullscreen mode

Security Features

  • The execution time limit feature is automatically enabled

Execution time retrict

  • Feature to limit malicious behavior (access to Files or Folders)

malicious behavior

  • Feature to limit malicious behavior (remote command execution)

remote command execution

  • Prevent execution of commands related to directories or files

directories or files retrict


This sample highlights how easily you can incorporate dynamic code evaluation into your project while maintaining full control over execution parameters.


Final Thoughts

SecureCSharpEval is more than just a code execution tool—it’s your gateway to dynamic, secure, and efficient C# scripting. Its blend of security features, developer-friendly API, and seamless integration with modern .NET environments makes it an essential addition to any developer’s toolkit.

Ready to revolutionize your approach to dynamic code execution? Give SecureCSharpEval a try and elevate your development process today!

Top comments (3)

Collapse
 
angelobelchior profile image
Angelo Belchior • Edited

Great Post! Congratz :)

Use
Image description
to colorize de code :)

Collapse
 
ngtduc693 profile image
Duc Nguyen Thanh

thanks, I will update

Collapse
 
ngtduc693 profile image
Duc Nguyen Thanh

Let's me know if you have any dout