Dynamic Code Security Model
Relevant source files
The following files were used as context for generating this wiki page:- Packages/src/Editor/Security/SecurityValidator.cs
- Packages/src/Editor/Security/DangerousApiDetector.cs
- Packages/src/Editor/Security/SecuritySettings.cs
- Packages/src/Editor/Security/SecuritySyntaxWalker.cs
- Packages/src/Editor/Compilation/RoslynCompiler.cs
- Packages/src/Editor/UI/UIToolkit/Components/SecuritySettingsSection.cs
- README.md
- Assets/Tests/Editor/DynamicCodeToolTests/RestrictedModeUserClassTests.cs
- ARCHITECTURE.md
The Dynamic Code Security Model is a core feature of uLoopMCP, providing a robust framework for safely executing C# code snippets generated by AI agents within the Unity Editor. It is primarily associated with the execute-dynamic-code tool. The model is built around a tiered security system that allows users to control the level of access dynamic code has to system and Unity APIs, preventing potentially harmful operations while enabling powerful editor automation.
This system leverages the Roslyn compiler API to perform static analysis on code before execution. By parsing the code into a syntax tree and analyzing it semantically, it can detect and block calls to dangerous APIs, ensuring that AI-generated code operates within a safe, defined boundary. The security level is configurable through the uLoopMCP editor window, providing flexibility for different trust levels and use cases.
Sources: README.md, ARCHITECTURE.md, Packages/src/Editor/Compilation/RoslynCompiler.cs
Architecture and Core Components
The security model is composed of several key components that work together to compile, analyze, and validate dynamic code. The process is initiated by the RoslynCompiler and involves a series of validation steps, especially when operating in Restricted mode.
This diagram shows the relationship between the main classes of the security model.
Key Components
| Component | Description | File Path |
|---|---|---|
RoslynCompiler | Orchestrates the entire process. It receives code, wraps it, compiles it, and, if the security level is Restricted, invokes the SecurityValidator. | Packages/src/Editor/Compilation/RoslynCompiler.cs |
SecurityValidator | The entry point for security analysis. It checks the current security level and, if Restricted, uses a SecuritySyntaxWalker to inspect the compiled code's syntax tree. | Packages/src/Editor/Security/SecurityValidator.cs |
SecuritySyntaxWalker | Traverses the C# abstract syntax tree (AST) of the code. It overrides Visit methods for different syntax nodes (e.g., method calls, object creation) to check for security violations. | Packages/src/Editor/Security/SecuritySyntaxWalker.cs |
DangerousApiDetector | Contains predefined lists of dangerous API calls, types, and namespaces. The SecuritySyntaxWalker consults this class to determine if a given API is blacklisted. | Packages/src/Editor/Security/DangerousApiDetector.cs |
SecuritySettingsSection | The UI component within the McpEditorWindow that allows users to configure the DynamicCodeSecurityLevel and other security-related toggles. | Packages/src/Editor/UI/UIToolkit/Components/SecuritySettingsSection.cs |
Security Levels
The system implements a 3-tier security model to control the capabilities of the execute-dynamic-code tool. The level can be selected from the "Dynamic Code Security Level" dropdown in the uLoopMCP window's Security Settings.
| Level | Name | Description | Recommended Use |
|---|---|---|---|
| 0 | Disabled | Completely disables compilation and execution of dynamic code. The execute-dynamic-code tool will fail with an error. | Safest setting; when dynamic code execution is not needed. |
| 1 | Restricted | (Recommended) Allows access to most Unity and .NET APIs but blocks specific, potentially dangerous operations like file deletion, network access, and process execution. | Default for most AI-driven development and automation tasks. |
| 2 | FullAccess | No restrictions. All APIs are accessible. This poses a security risk and should only be used with fully trusted code. | For trusted, complex scripts that require access to otherwise restricted APIs. |
Sources: README.md, Packages/src/Editor/UI/UIToolkit/Components/SecuritySettingsSection.cs:122-128, Packages/src/Editor/Compilation/RoslynCompiler.cs:288-307
Validation Process Flow
When code is submitted for execution via the execute-dynamic-code tool, it undergoes a validation process, particularly in Restricted mode.
This flowchart illustrates the validation steps for a dynamic code execution request.
- The
RoslynCompilerfirst checks the currentDynamicCodeSecurityLevel. - If the level is
Disabled, execution is immediately halted. - If
FullAccess, the code is compiled and executed without security checks. - If
Restricted, theRoslynCompilerproceeds with compilation. - If compilation fails, the errors are returned.
- If compilation succeeds, the
SecurityValidatoris invoked. - The validator creates a
SecuritySyntaxWalkerto traverse the code's syntax tree. - The walker inspects nodes such as method calls (
VisitInvocationExpression), object creation (VisitObjectCreationExpression), and property access (VisitMemberAccessExpression). - For each relevant node, it consults the
DangerousApiDetectorto check if the API is on the blocklist. - If any violations are found, the execution is blocked, and the violations are reported.
- If no violations are found, the code is executed.
Sources: Packages/src/Editor/Security/SecuritySyntaxWalker.cs, Packages/src/Editor/Security/SecurityValidator.cs
Dangerous API Detection
In Restricted mode, the security model relies on static analysis to identify and block a predefined set of dangerous APIs.
Blocked Operations
The DangerousApiDetector class maintains a HashSet of strings representing forbidden API calls. These are categorized as follows:
- File System (Write/Delete):
File.Delete,Directory.Delete,File.WriteAllText,FileUtil.DeleteFileOrDirectory. - Network Communication:
HttpClient,WebClient,WebRequest,Socket,TcpClient,UnityWebRequest. - Process Execution:
Process.Start,Process.Kill. - Dynamic Code Execution/Reflection:
Assembly.Load*,Type.InvokeMember,Activator.CreateComInstanceFrom. - Thread Manipulation: Direct use of
ThreadandTaskclasses,Thread.Abort. - Registry Operations: The entire
Microsoft.Win32namespace. - Environment Control:
Environment.Exit.
Safe operations like file reading (File.ReadAllText) and path manipulation (Path.*) are permitted.
Sources: README.md, Assets/Tests/Editor/DynamicCodeToolTests/RestrictedModeUserClassTests.cs:30-74, Packages/src/Editor/Security/DangerousApiDetector.cs
Detection Mechanism
The SecuritySyntaxWalker is the component that performs the actual detection by traversing the code's syntax tree. It uses the SemanticModel provided by the Roslyn compiler to get detailed type and symbol information for every part of the code.
For example, when the walker visits a method call:
- It gets the
IMethodSymbolfor the called method. - It constructs the fully qualified name (e.g.,
System.IO.File.Delete). - It passes this name to
DangerousApiDetector.IsDangerousApi(). - If it returns
true, aSecurityViolationis created and added to a list.
This process is repeated for object creation, property access, inheritance, and direct type references.
// Example from SecuritySyntaxWalker.cs
public override void VisitInvocationExpression(InvocationExpressionSyntax node)
{
IMethodSymbol methodSymbol = semanticModel.GetSymbolInfo(node).Symbol as IMethodSymbol;
if (methodSymbol != null)
{
string fullName = GetFullMethodName(methodSymbol);
if (apiDetector.IsDangerousApi(fullName))
{
violations.Add(new SecurityViolation
{
Type = SecurityViolationType.DangerousApiCall,
Description = $"Dangerous method call detected: {fullName}",
// ...
});
}
}
base.VisitInvocationExpression(node);
}
Sources: Packages/src/Editor/Security/SecuritySyntaxWalker.cs:221-242
Configuration in Unity Editor
Users can configure the dynamic code security level through the uLoopMCP editor window, accessible via Window > uLoopMCP.
The "Security Settings" section contains the controls for the security model:
- Dynamic Code Security Level: An
EnumFielddropdown to select one of the three security levels (Disabled,Restricted,FullAccess). - Allow Tests Execution: A toggle for the
run-teststool. - Allow Menu Item Execution: A toggle for the
execute-menu-itemtool. - Allow Third Party Tools: A toggle to enable custom, user-developed tools.
Changes to these settings are saved via McpEditorSettings and take effect immediately without requiring a server restart. When changing the security level from Disabled to an enabled state, the system checks if the required Microsoft.CodeAnalysis.CSharp package is installed.
Sources: Packages/src/Editor/UI/UIToolkit/Components/SecuritySettingsSection.cs, README.md