Back to skill

Security audit

Csharp Dotnetcore Natasha

Security checks for vulnerabilities and agentic risk

Overview

This documentation skill is coherent for Natasha dynamic C# compilation, but it teaches high-impact runtime code execution and private-member bypass patterns without enough safety boundaries.

Install only if you are comfortable with guidance for runtime C# compilation. Treat any generated script, plugin, or private-member access example as trusted-code-only unless you add real isolation such as a separate least-privileged process or container, strict input control, reviewed package versions, and explicit filesystem/network limits.

Vulnerability Patterns
  • Insecure DependenciesIntroduces malicious components through unsafe dependency sources
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
Findings (2)

T09 · Insecure Skill Coding Practices

Error
Location
COMPILATION_ERROR_HANDLING.md:411
Finding
Untrusted C# Scripts Can Be Compiled and Executed with Host Process Privileges<![CDATA[ ## Vulnerability Details **File Location**: `COMPILATION_ERROR_HANDLING.md:411-430` **Vulnerability Type**: Arbitrary in-process code execution **Risk Level**: High ### Vulnerable Code ```csharp public class ScriptEngine { public object Execute(string script) { var builder = new AssemblyCSharpBuilder(); builder.UseRandomLoadContext().UseSmartMode(); NatashaCompilationLog? log = null; builder.CompileFailedEvent += (compilation, errors) => { log = compilation.GetNatashaLog(); }; try { builder.Add(script); var assembly = builder.GetAssembly(); var type = assembly.GetTypes().First(); var method = type.GetMethods().First(m => m.IsStatic && m.IsPublic); return method.Invoke(null, null); } ``` A second example demonstrates the same unsafe trust model for code loaded from files: **Additional Location**: `references/common-patterns.md:929-970` ```csharp public static List<T> ScanLogical<T>(string[] pluginFiles, string fatherClassName) where T : class { List<T> result = []; AssemblyCSharpBuilder assemblyCSharp = new(); assemblyCSharp .UseRandomLoadContext() .UseSmartMode() .WithDebugCompile(c => c.ForAssembly()); var fileIndexArray = new int[pluginFiles.Length]; Dictionary<int, string> typeNamesCache = []; for (int i = 0; i < pluginFiles.Length; i++) { var fileIndexString = Path.GetFileNameWithoutExtension(pluginFiles[i]); if (fileIndexString != null && Int32.TryParse(fileIndexString, out var fileIndex)) { var className = $"N{Guid.NewGuid():n}"; typeNamesCache.Add(fileIndex, className); var classMethodText = File.ReadAllText(pluginFiles[i]); var classScript = @$"public class {className} : {fatherClassName}{{ {classMethodText} ...[truncated 2990 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Explicitly document that these APIs must compile only trusted, administrator-controlled source code. 2. Do not expose raw C# source submission to unauthenticated or untrusted users. 3. If untrusted code execution is unavoidable, move compilation and execution into a separate, disposable process or container. 4. Run that worker under a dedicated least-privileged operating-system identity with: - No access to application secrets. - A read-only or isolated filesystem. - No outbound network access unless explicitly required. - No access to host sockets or privileged devices. - Strict CPU, memory, process, and execution-time limits. 5. Use a narrowly defined IPC contract and validate all inputs and outputs exchanged with the worker. 6. Authenticate and authorize script or plugin submission, retain audit logs, and require integrity verification or signed plugins where appropriate. 7. Treat syntax-tree allowlists only as defense in depth; they are not a replacement for operating-system isolation. 8. Avoid enabling private-member access, unsafe blocks, native interoperability, or broad metadata access for untrusted workloads. ]]>

T08 · Insecure Dependencies

Note
Location
SKILL.md:33
Finding
NuGet Installation Instructions Do Not Pin Reviewed Package Versions<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md:33-40` **Vulnerability Type**: Unpinned third-party dependencies **Risk Level**: Low ### Vulnerable Code ```bash # Core compiler package (基础编译单元) dotnet add package DotNetCore.Natasha.CSharp.Compiler # Domain implementation package (域实现包) dotnet add package DotNetCore.Natasha.CSharp.Compiler.Domain ``` ### Technical Analysis The installation commands omit explicit package versions. As a result, users following the instructions may receive whichever package version NuGet resolves at installation time rather than a release that was reviewed with this Skill. The package names and NuGet source shown in the project are not themselves identified as malicious. The issue is supply-chain reproducibility: future package updates can change runtime compilation behavior or introduce defects without a corresponding review of this documentation and its examples. ### Attack Path 1. A user follows the documented `dotnet add package` commands. 2. NuGet resolves the current package release instead of a fixed, reviewed version. 3. A future defective or compromised release is restored into the project. 4. Package code executes during build or application runtime with the permissions of the build agent or application process. 5. The unreviewed dependency may affect runtime compilation, assembly loading, or other application behavior. ### Impact Assessment The practical impact depends on the contents of the version resolved by NuGet. A compromised dependency could potentially: - Execute code in the build or application environment. - Access files, build credentials, or environment variables available to that process. - Alter dynamically compiled output or application behavior. - Make builds non-reproducible and complicate incident investigation. No evidence in the audited files establishes that the named packages are currently malicious; this finding concerns the absence of version pinning and dependency lock ...[truncated 8 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Pin each package to a specific reviewed version, for example: ```bash dotnet add package DotNetCore.Natasha.CSharp.Compiler --version <reviewed-version> dotnet add package DotNetCore.Natasha.CSharp.Compiler.Domain --version <reviewed-version> ``` 2. Use `packages.lock.json` and enable locked restore mode in CI to ensure reproducible dependency resolution. 3. Commit the lock file and require security review for dependency updates. 4. Configure trusted NuGet sources explicitly and use package source mapping where practical. 5. Add automated vulnerability and license scanning for direct and transitive dependencies. 6. Verify package ownership, signatures, and hashes where supported before approving upgrades. ]]>
Vulnerability Patterns
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
Findings (27)

Missing User Warnings

High
Confidence
95% confidence
Finding
The plugin-system example explicitly registers and executes user-provided code at runtime without any warning, validation, isolation, or trust-boundary discussion. In the context of a runtime C# compiler, this is effectively arbitrary code execution and can lead to full process compromise, data theft, or destructive system actions if consumers copy the pattern for untrusted plugins.

Missing User Warnings

High
Confidence
97% confidence
Finding
The hot-loading example reads logic from external files, wraps it, compiles it, and executes it without any security warning about file-origin trust. This creates a dangerous path from filesystem content to code execution, enabling attackers who can modify those files or their source path to achieve arbitrary code execution within the host process.

Natural-Language Policy Violations

Medium
Confidence
92% confidence
Finding
The title and introductory description are entirely in Chinese, and the document does not indicate that language selection is optional or that the Chinese-only presentation is required for a region-specific purpose. This can violate language/locale policy when a skill or its documentation implicitly mandates a specific language without user opt-in.

Natural-Language Policy Violations

Medium
Confidence
93% confidence
Finding
The title and introductory instruction are entirely in Chinese and present the learning requirements as the expected interaction mode, with no indication that another language is supported. This creates a language/locale policy issue because the skill content effectively mandates a specific language without user opt-in or a stated regional justification.

Missing User Warnings

Medium
Confidence
94% confidence
Finding
This documentation explicitly instructs users to disable C# accessibility checks via `IgnoreAccessibility`, include all metadata, and generate code that can access private/internal members. While framed as a feature guide, it enables encapsulation bypass and can expose secrets, tamper with internal state, or circumvent library/framework security assumptions when used in production or against untrusted targets.

Natural-Language Policy Violations

Medium
Confidence
87% confidence
Finding
The README content is written entirely in Chinese, including usage instructions and examples, without indicating that users may choose another language or that the skill is intended only for a Chinese-speaking audience. The policy explicitly flags language or locale constraints when they are imposed without opt-in or documented justification.

Missing User Warnings

Medium
Confidence
92% confidence
Finding
The examples implement a script engine and batch compiler that accept arbitrary C# source strings, compile them at runtime, and invoke methods via reflection, but the document does not prominently warn that untrusted input here is equivalent to arbitrary code execution in the host process. In the context of a skill specifically about Natasha-based dynamic compilation, this is especially dangerous because readers are likely to copy these patterns into real services, turning user-controlled script input into direct remote code execution.

Missing User Warnings

Medium
Confidence
97% confidence
Finding
The skill explicitly teaches how to access private fields and enable private-compilation features, but it does so without any warning about violating encapsulation, breaking security boundaries, or exposing secrets from in-memory objects. In a runtime-compilation skill, this is especially risky because users can generate code that bypasses intended access controls and extract sensitive state from trusted application types.

Missing User Warnings

Medium
Confidence
94% confidence
Finding
This example documents bypassing access controls to private members using IgnoreAccessibility and private-access helpers, but provides no warning about violating encapsulation and exposing sensitive internal state. In practice, such patterns can be abused to read secrets, tamper with invariants, or reach unsafe internals that developers assumed were protected.

Context-Inappropriate Capability

Medium
Confidence
91% confidence
Finding
The manifest describes a skill for dynamic C# generation/compilation, private-member access, and metadata strategies. This example explicitly demonstrates writing to the filesystem via `File.WriteAllText`, which is not justified by that stated purpose and expands the apparent capability of the skill beyond dynamic compilation itself.

Context-Inappropriate Capability

Medium
Confidence
95% confidence
Finding
The surrounding section is about adaptive compilation behavior, but the concrete demo configures `System.IO.File` and executes `File.WriteAllText` in dynamically compiled code. File creation is not a necessary or obvious requirement of a skill whose manifest is limited to runtime C# generation, dynamic methods, private access, and compilation metadata management.

Natural-Language Policy Violations

Medium
Confidence
97% confidence
Finding
The heading and the rest of the file are written in Chinese, which imposes a specific language on users without any opt-in or explanation that the skill is region- or locale-specific. Under the policy, forced language choice in natural-language content is a reportable violation unless the file offers alternatives or documents a justified locale constraint.

Context-Inappropriate Capability

Medium
Confidence
96% confidence
Finding
The guide explicitly recommends configuring the compiler with accessibility-bypass behavior (`IgnoreAccessibility`) and building code that reads a private field. In a skill centered on runtime C# compilation, this materially expands capability from dynamic code generation into encapsulation bypass, enabling generated code to access internal secrets or sensitive state that normal code paths should not read.

Missing User Warnings

Medium
Confidence
93% confidence
Finding
The documentation demonstrates bypassing private-member protections without any warning about security, trust boundaries, or misuse risks. Because the skill is specifically for generating and compiling code at runtime, examples tend to be copied directly into production, so omission of guardrails increases the chance that developers normalize unsafe reflective/compiled access patterns.

Natural-Language Policy Violations

Medium
Confidence
92% confidence
Finding
This markdown file contains user-facing natural-language instructions exclusively in Chinese, and there is no indication that users may choose another language or that the skill is intentionally limited to a Chinese-speaking audience. Under the policy rule for language/locale constraints, forcing a specific language without user opt-in is a natural-language policy violation.

Natural-Language Policy Violations

Low
Confidence
94% confidence
Finding
This markdown file contains user-facing natural language exclusively in Chinese, and there is no indication that the skill or document supports user language preference or is intentionally limited to a Chinese-speaking audience. Under the language/locale policy, forcing a specific language without opt-in can be a policy violation.

Unpinned Dependencies

Low
Category
Supply Chain
Content
```csharp
AssemblyCSharpBuilder builder = new();
builder
    .UseRandomLoadContext()
    .UseSmartMode();
Confidence
60% confidence
Finding
Dependencies lack version pinning, allowing potential malicious package updates. Consider pinning versions.

Unpinned Dependencies

Low
Category
Supply Chain
Content
```csharp
AssemblyCSharpBuilder builder = new();
builder
    .UseRandomLoadContext()
    .UseSmartMode();
Confidence
60% confidence
Finding
Dependencies lack version pinning, allowing potential malicious package updates. Consider pinning versions.

Unpinned Dependencies

Low
Category
Supply Chain
Content
```csharp
AssemblyCSharpBuilder builder = new();
builder
    .UseRandomLoadContext()
    .UseSmartMode();
Confidence
60% confidence
Finding
Dependencies lack version pinning, allowing potential malicious package updates. Consider pinning versions.

Unpinned Dependencies

Low
Category
Supply Chain
Content
```csharp
AssemblyCSharpBuilder builder = new();
builder
    .UseRandomLoadContext()
    .UseSmartMode();
Confidence
60% confidence
Finding
Dependencies lack version pinning, allowing potential malicious package updates. Consider pinning versions.

Unpinned Dependencies

Low
Category
Supply Chain
Content
```csharp
AssemblyCSharpBuilder builder = new();
builder
    .UseRandomLoadContext()
    .UseSmartMode();
Confidence
60% confidence
Finding
Dependencies lack version pinning, allowing potential malicious package updates. Consider pinning versions.

Unpinned Dependencies

Low
Category
Supply Chain
Content
```csharp
AssemblyCSharpBuilder builder = new();
builder
    .UseRandomLoadContext()
    .UseSmartMode();
Confidence
60% confidence
Finding
Dependencies lack version pinning, allowing potential malicious package updates. Consider pinning versions.

Missing User Warnings

Low
Confidence
82% confidence
Finding
The documentation describes `WithForceCleanFile()` overwriting an existing DLL and contrasts it with generating a new filename, but it does not foreground the risk of destructive file replacement. In a dynamic compilation skill, normalizing overwrite behavior without warning can lead users to clobber application binaries or other important assemblies if names or paths become attacker-influenced or operationally misconfigured.

Missing User Warnings

Low
Confidence
88% confidence
Finding
The skill documents writing a cache file to disk and later discusses forced deletion/cleanup behavior, but it does not clearly warn users about filesystem side effects, path control, or operational risks. While not inherently malicious, silent disk writes and file replacement behaviors can surprise operators, damage local artifacts, or create abuse opportunities if paths or working directories are attacker-influenced.

Excessive Permissions

Low
Category
Privilege Escalation
Content
```csharp
builder.ConfigCompilerOption(opt => opt
    .AppendCompilerFlag(CompilerBinderFlags.IgnoreAccessibility)   // Bypass access checks
    .WithAllMetadata()                                              // Access all metadata levels
    .AppendNullableFlag(NullableContextOptions.Enable)             // Enable nullable annotations
);
Confidence
96% confidence
Finding
The documented use of CompilerBinderFlags.IgnoreAccessibility instructs users to bypass language/runtime accessibility checks. In the context of dynamic compilation, this grants powerful capabilities to inspect or invoke non-public members, which can undermine application trust assumptions, expose secrets, and weaken isolation if used with untrusted or semi-trusted code.

Static analysis

No suspicious patterns detected.