2023-03-07 17:16:47 +01:00

77 lines
2.2 KiB
Plaintext

== How to fix it in .NET
=== Code examples
The following code is vulnerable to arbitrary code execution because it compiles
and runs HTTP data.
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
using System.CodeDom.Compiler;
public class ExampleController : Controller
{
public void Run(string message)
{
const string code = @"
using System;
public class MyClass
{
public void MyMethod()
{
Console.WriteLine(""" + message + @""");
}
}
";
var provider = CodeDomProvider.CreateProvider("CSharp");
var compilerParameters = new CompilerParameters { ReferencedAssemblies = { "System.dll", "System.Runtime.dll" } };
var compilerResults = provider.CompileAssemblyFromSource(compilerParameters, code);
object myInstance = compilerResults.CompiledAssembly.CreateInstance("MyClass");
myInstance.GetType().GetMethod("MyMethod").Invoke(myInstance, new object[0]);
}
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
using System.CodeDom.Compiler;
public class ExampleController : Controller
{
public void Run(string message)
{
const string code = @"
using System;
public class MyClass
{
public void MyMethod(string input)
{
Console.WriteLine(input);
}
}
";
var provider = CodeDomProvider.CreateProvider("CSharp");
var compilerParameters = new CompilerParameters { ReferencedAssemblies = { "System.dll", "System.Runtime.dll" } };
var compilerResults = provider.CompileAssemblyFromSource(compilerParameters, code);
object myInstance = compilerResults.CompiledAssembly.CreateInstance("MyClass");
myInstance.GetType().GetMethod("MyMethod").Invoke(myInstance, new object[]{ message }); // Pass message to dynamic method
}
}
----
=== How does this work?
include::../../common/fix/introduction.adoc[]
include::../../common/fix/parameters.adoc[]
The compliant code example uses such an approach.
include::../../common/fix/allowlist.adoc[]