Verifies that a C# code uses only permitted types and assemblies
- Specify allowed types as type name strings
- Specify allowed type names as regex pattern
- Specify referenced assemblies via file paths
- Install the ScriptVerifier NuGet package (
Install-Package ScriptVerifier) - Configure a the ICompilerSetup.
- Verify C# code with "Verifier.Verify()"
usingSystem;namespaceScriptVerifier.Sample{publicclassProgram{publicstaticvoidMain(){TestMaliciousScript();TestScriptWithPermittedTypes();}privatestaticvoidTestMaliciousScript(){varscript=@"using System;var i = 42;i = 42 + 42;var fileType = Type.GetType(""System.IO.File, System.IO.FileSystem""); // use reflection to execute malicious codevar deleteMethod = fileType!.GetMethod(""Delete"");deleteMethod!.Invoke(null, new object[] {@""d:\passwd.txt""});";RunVerification(script,newDefaultCompilerSetup());// Not allowed type 'System.Type' used at location ': (6,0)-(6,67)''}privatestaticvoidTestScriptWithPermittedTypes(){varscript=@"using System;var i = 42;i = 42 + 42;Console.WriteLine(""Result was: "" + i);";varcompilerSetup=newDefaultCompilerSetup();compilerSetup.AddAllowedType(typeof(Console));RunVerification(script,compilerSetup);// OK}privatestaticvoidRunVerification(stringscript,ICompilerSetupcompilerSetup){try{varverifier=newVerifier(compilerSetup);varresult=verifier.Verify(script);Console.WriteLine("Script verification successful, only allowed types were used!");}catch(ScriptVerificationExceptionex){Console.WriteLine("Script verification got the following error:");Console.WriteLine(ex.Message);}}}}