Back to skill

Security audit

dapr-dotnet

Security checks for vulnerabilities and agentic risk

Overview

This skill is a coherent .NET/Dapr backend template, but it includes production-style code patterns with unsafe CORS and error-handling defaults that users should review before using.

Review and harden the generated backend code before using it in any real service. In particular, require an explicit trusted CORS origin allowlist, avoid credentialed wildcard-style CORS behavior, return sanitized error messages, and validate or replace string-based SQL/order parameters with allowlisted or strongly typed alternatives.

Vulnerability Patterns
  • 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
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
Findings (3)

T09 · Insecure Skill Coding Practices

Error
Location
SKILL.md:311
Finding
Credentialed CORS Requests Allowed from Arbitrary Origins<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md:311-323` **Vulnerability Type**: Insecure CORS configuration **Risk Level**: High ### Vulnerable Code ```csharp builder.Services.AddCors(options => { options.AddPolicy("CorsPolicy", policy => { var withOrigins = builder.Configuration["WithOrigins"]; if (!string.IsNullOrWhiteSpace(withOrigins) && withOrigins.Split(';').Length > 0) policy.WithOrigins(withOrigins.Split(';')); else policy.SetIsOriginAllowed((host) => true); policy.AllowAnyMethod(); policy.AllowAnyHeader(); policy.AllowCredentials(); }); }); ``` ### Technical Analysis The policy falls back to trusting every requesting origin when `WithOrigins` is absent or empty. It simultaneously enables credentials, arbitrary HTTP methods, and arbitrary request headers. This configuration permits an attacker-controlled website to make cross-origin requests through a victim's browser and read the responses when the browser attaches credentials accepted by the generated service. The effective exploitability depends on the application's authentication mechanism and cookie attributes, but this configuration removes the browser's normal origin-based response isolation. The fallback also fails open: an omitted or misspelled production setting silently produces the least restrictive policy. ### Attack Path 1. The service is deployed without a valid `WithOrigins` value. 2. A victim authenticates to the service using browser-managed credentials that can be attached to cross-origin requests. 3. The victim visits an attacker-controlled website. 4. Malicious JavaScript sends a credentialed request to the service. 5. `SetIsOriginAllowed((host) => true)` approves the attacker's origin. 6. `AllowCredentials()`, `AllowAnyMethod()`, and `AllowAnyHeader()` permit the credentialed operation. 7. The attacker reads sensitive responses or performs authenticated state-changing acti ...[truncated 357 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Fail closed when `WithOrigins` is absent, malformed, or empty; do not start the application with an unrestricted fallback. - Require an explicit allowlist of trusted HTTPS origins for every deployed environment. - Remove `AllowCredentials()` unless browser-managed cross-origin credentials are a documented requirement. - Restrict allowed methods and headers to those required by the API. - Validate and normalize configured origins during startup. - Add automated tests that reject unknown origins and verify that missing configuration causes startup failure. A safer pattern is: ```csharp var configuredOrigins = builder.Configuration .GetSection("Cors:AllowedOrigins") .Get<string[]>(); if (configuredOrigins is null || configuredOrigins.Length == 0) { throw new InvalidOperationException( "At least one trusted CORS origin must be configured."); } builder.Services.AddCors(options => { options.AddPolicy("CorsPolicy", policy => { policy.WithOrigins(configuredOrigins) .WithMethods("GET", "POST", "PUT", "DELETE") .WithHeaders("Authorization", "Content-Type"); // Add AllowCredentials() only if it is explicitly required. }); }); ``` ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
SKILL.md:663
Finding
Internal Exception Details Returned to API Clients<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md:663-667` **Vulnerability Type**: Sensitive information exposure through error messages **Risk Level**: Medium ### Vulnerable Code ```csharp public void Failed(Exception ex) { base.Failed(); _Message = ex.Message.ToString(); } ``` ### Technical Analysis The error-handling method copies the raw exception message into the API response. Exception messages can disclose database object names, SQL fragments, filesystem paths, internal hostnames, dependency behavior, validation rules, and other implementation details. Although this does not directly grant additional privileges, it gives unauthenticated or low-privileged clients information that can be used to refine subsequent attacks. The exposure is especially significant when exceptions originate from database, filesystem, or network operations. ### Attack Path 1. An attacker submits malformed, oversized, or boundary-case input to an API endpoint. 2. The request triggers an exception in the application, ORM, database provider, or another dependency. 3. The endpoint passes the exception to `Failed(Exception ex)`. 4. The method assigns the raw exception message to `_Message`. 5. The serialized API response reveals the internal error details to the attacker. 6. The attacker uses the disclosed schema, query, path, or infrastructure information to improve further injection, enumeration, or targeted exploitation attempts. ### Impact Assessment The direct impact is information disclosure rather than immediate code execution or privilege escalation. Information is exposed with the privileges of the failing server operation and may reveal internal database or infrastructure details. Repeated probing can provide attackers with a useful map of the application's implementation and deployment environment. ]]>
Remediation
<![CDATA[ ## Remediation Suggestions - Never return raw exception messages to untrusted clients. - Return a stable, generic message and a server-generated correlation identifier. - Log the complete exception only through a protected server-side logging system. - Apply centralized exception-handling middleware so all endpoints follow the same disclosure policy. - Ensure production logs are access-controlled and do not unnecessarily record secrets or personal data. - Map expected business exceptions to explicit, sanitized client responses. For example: ```csharp public void Failed(Exception ex) { base.Failed(); var correlationId = Activity.Current?.Id ?? Guid.NewGuid().ToString("N"); _Message = $"An internal error occurred. Reference: {correlationId}"; // Log the complete exception and correlation ID on the server. } ``` ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
SKILL.md:2629
Finding
Unvalidated String-Based Database Ordering Expression<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md:2629-2637` **Vulnerability Type**: Potential SQL manipulation through dynamic ordering **Risk Level**: Medium ### Vulnerable Code ```csharp public async Task<List<T>> QueryAsync( Expression<Func<T, bool>> func, string orderByFields, int APageIndex, int APageSize, RefAsync<int> ATotal) { return await base.Context.Queryable<T>() .Where(func) .OrderBy(orderByFields) .ToPageListAsync(APageIndex, APageSize, ATotal); } ``` ### Technical Analysis The repository accepts an unrestricted string and passes it to the ORM's string-based `OrderBy` API. Unlike the adjacent strongly typed expression overload, this method does not constrain the input to known model properties or valid ordering directions. If a controller or service forwards a user-controlled sort parameter into `orderByFields`, the attacker reaches a query-construction boundary. Depending on the SqlSugar version, database provider, and parser behavior, crafted ordering syntax could modify generated SQL, cause query errors that disclose details, or enable SQL injection. Even where the ORM blocks full injection, unrestricted expressions can still permit unintended columns, expensive expressions, or denial-of-service-oriented query plans. ### Attack Path 1. An endpoint accepts a client-provided sort field or ordering expression. 2. The controller or service forwards that value to this repository method without an allowlist. 3. The repository passes the value directly to `OrderBy(orderByFields)`. 4. The ORM interprets the attacker-controlled string as part of query construction. 5. The attacker submits crafted SQL-like syntax, unauthorized column names, or computationally expensive ordering expressions. 6. If accepted by the ORM/provider, the generated query is altered; otherwise, resulting database errors may still disclose useful implementation information. ### Impact Assessment The maximum im ...[truncated 380 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Replace string-based ordering with strongly typed expression trees wherever possible. - Translate external sort keys through a fixed allowlist rather than passing client input to the ORM. - Represent sort direction with an enum and reject all unrecognized values. - Do not allow clients to supply SQL fragments, function calls, multiple columns, comments, or punctuation. - Apply maximum page-size limits to reduce query-abuse and denial-of-service risks. - Add tests using malicious and malformed sort values to confirm rejection before query construction. - Run the application under a least-privileged database account. For example: ```csharp public Task<List<T>> QueryAsync<TKey>( Expression<Func<T, bool>> filter, Expression<Func<T, TKey>> orderBy, OrderByType direction, int pageIndex, int pageSize, RefAsync<int> total) { return base.Context.Queryable<T>() .Where(filter) .OrderBy(orderBy, direction) .ToPageListAsync(pageIndex, pageSize, total); } ``` At the API boundary, map fixed client-facing values such as `name`, `createdAt`, and `id` to predefined expressions. Reject any value not present in that mapping. ]]>
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 (1)

Natural-Language Policy Violations

Medium
Confidence
96% confidence
Finding
The natural-language description and role definition are written as unconditional first-person instructions in Chinese, presenting the skill as operating in that language by default with no opt-in or alternative language choice. This can violate language/locale policy requirements when users have not explicitly chosen Chinese.

Static analysis

No suspicious patterns detected.