Back to skill

Security audit

Teamgram RPC Development

Security checks for vulnerabilities and agentic risk

Overview

This is a documentation-only RPC development skill, but its examples include unsafe payment, authorization, secret-handling, and logging patterns that could be copied into production.

Review this skill before installing or using it as a coding reference. It is not an active malware-like package, but developers should not copy the premium payment, authorization, logging, Vault, or secret-loading examples without adding authenticated identity checks, verified payment callbacks, transaction/idempotency handling, redaction, endpoint validation, and path traversal protections.

Vulnerability Patterns
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • 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 (6)

T05 · Unauthorized Access and Privilege Escalation

Error
Location
SKILL.md:340
Finding
Client-Controlled User Identity Permits Unauthorized Premium Operations<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md`, lines 340–355 **Vulnerability Type**: Broken object-level authorization **Risk Level**: High ### Vulnerable Code ```go func (s *Server) PremiumGetStatus(ctx context.Context, req *mtproto.TLPremiumGetStatus) (*mtproto.PremiumStatus, error) { status, err := s.premiumCore.GetPremiumStatus(ctx, req.UserId) if err != nil { return nil, err } return &mtproto.TLPremiumStatus{ UserId: status.UserID, Status: status.Status, ExpiresAt: status.ExpiresAt, }, nil } func (s *Server) PremiumPurchase(ctx context.Context, req *mtproto.TLPremiumPurchase) (*mtproto.Bool, error) { err := s.premiumCore.PurchasePremium(ctx, req.UserId, int(req.PlanId), req.PaymentMethod) if err != nil { return mtproto.BoolFalse, err } return mtproto.BoolTrue, nil } ``` ### Technical Analysis The RPC handlers use `req.UserId` directly as the identity on which the operation is performed. The examples do not derive the acting user from authenticated context or verify that the caller is authorized to operate on the supplied user ID. Input validation that only checks whether a user ID is syntactically valid would not prevent this vulnerability. The target resource must be bound to the authenticated principal, or access must be authorized through a separate privileged role. ### Attack Path 1. An attacker authenticates as user A. 2. The attacker obtains or guesses the identifier of user B. 3. The attacker sends `PremiumGetStatus` with user B's identifier. 4. The server queries and returns user B's premium information without an ownership check. 5. Alternatively, the attacker calls `PremiumPurchase` with user B's identifier. 6. The server initiates premium processing for user B because the request body is treated as authoritative identity information. ### Impact Assessment An authenticated user may be able to read another user's premium status or initia ...[truncated 249 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Derive the acting user ID from authenticated server-side context rather than the request body. - If the method only operates on the caller, remove `user_id` from the public request entirely. - If acting on another user is a legitimate administrative feature, require an explicit role and resource-level authorization check. - Reject requests where the supplied user ID differs from the authenticated identity unless delegated access is verified. - Add negative authorization tests showing that user A cannot query or modify user B. - Record authorization failures without logging sensitive request contents. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
SKILL.md:283
Finding
Premium Entitlement Is Granted Without Verified Payment<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md`, lines 283–303 **Vulnerability Type**: Payment workflow integrity failure **Risk Level**: Critical ### Vulnerable Code ```go // 3. 调用支付网关(异步处理) go c.processPayment(txnID, userID, plan) return nil } // processPayment 处理支付(异步) func (c *PremiumCore) processPayment(txnID int64, userID int64, plan *Plan) { ctx := context.Background() // 调用支付接口... // 成功后在回调中: // 1. 更新交易状态 _ = c.dao.UpdateTransactionStatus(ctx, txnID, 1) // success // 2. 更新用户会员状态 expiresAt := time.Now().AddDate(0, plan.DurationMonths, 0).Unix() _ = c.dao.CreateOrUpdatePremium(ctx, userID, 1, plan.ID, expiresAt) // 3. 发送通知 c.svcCtx.PushClient.SendToUser(ctx, userID, "Premium activated!") } ``` ### Technical Analysis The asynchronous function does not call or verify a payment gateway. It unconditionally changes the transaction status to successful and grants the premium entitlement. The comments imply that these updates should occur following a successful callback, but the actual example contains no callback authentication, payment status verification, amount comparison, currency validation, transaction binding, or replay protection. Errors from both state-changing database operations are discarded. The transaction status and premium entitlement are also changed as separate operations without an atomic database transaction. Consequently, a partial failure can create inconsistent financial and entitlement state. ### Attack Path 1. An attacker calls `PremiumPurchase` with any valid plan ID. 2. The application creates a pending transaction. 3. The application starts `processPayment` asynchronously. 4. `processPayment` marks the transaction successful without evidence that funds were captured. 5. It grants premium status to the selected user. 6. The attacker receives premium access without completing payment. ### Impact Assessment An attacker able to invoke the purchase endpoint can obtain ...[truncated 381 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Never grant an entitlement based only on initiating a purchase. - Update payment state only after receiving a cryptographically authenticated callback from the payment provider or after server-to-server verification. - Verify the provider transaction ID, merchant account, amount, currency, plan, user binding, and final captured status. - Use an idempotency key and enforce a unique provider transaction identifier to prevent replay. - Place transaction-state and entitlement updates in one atomic database transaction. - Check and propagate every database error instead of assigning it to `_`. - Use a durable job queue rather than an unmanaged goroutine for financial processing. - Model allowed state transitions, such as `pending -> paid -> fulfilled`, and reject invalid or repeated transitions. - Add tests for failed payment, altered amount, replayed callback, duplicate callback, timeout, and partial database failure. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
references/v1.3.0-security.md:304
Finding
Vault Token Can Be Transmitted to a Caller-Controlled or Plaintext Endpoint<![CDATA[ ## Vulnerability Details **File Location**: `references/v1.3.0-security.md`, lines 304–320 **Vulnerability Type**: Insufficient validation of a secret-management endpoint **Risk Level**: High ### Vulnerable Code ```go func NewVaultManager(addr, token string) (*VaultManager, error) { config := &api.Config{ Address: addr, } client, err := api.NewClient(config) if err != nil { return nil, err } client.SetToken(token) return &VaultManager{client: client}, nil } func (v *VaultManager) GetSecret(path string) (map[string]interface{}, error) { secret, err := v.client.Logical().Read(path) ``` ### Technical Analysis The Vault address is accepted as an unrestricted string. The example does not require HTTPS, constrain the hostname to an approved Vault service, or demonstrate trusted CA configuration. The Vault token is then attached to the client and used by subsequent secret requests. If an attacker can influence configuration or if an operator supplies an untrusted HTTP endpoint, authenticated Vault requests may disclose the token to that endpoint. The issue exceeds least privilege because a credential capable of retrieving secrets can be sent to an arbitrary destination. This finding depends on the deployment allowing an attacker or untrusted configuration source to control `addr`; no hard-coded malicious destination was found in the project. ### Attack Path 1. An attacker gains influence over the Vault address through configuration, environment management, or a deployment pipeline. 2. The attacker sets the address to an HTTP service or an HTTPS service under attacker control. 3. The application creates the client and assigns its Vault token. 4. The application invokes `GetSecret`. 5. The client sends an authenticated request to the configured endpoint. 6. The attacker captures the Vault token and attempts to use its assigned permissions against the legitimate Vault service. ### Impact Assessment Th ...[truncated 361 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Require an `https` URL and reject plaintext HTTP outside a tightly controlled local test environment. - Keep the Vault endpoint in trusted administrator-controlled configuration; do not accept it from request data. - Allowlist the exact Vault hostname and port. - Configure and verify the expected private CA or certificate chain. - Disable unsafe redirects or verify that redirects remain on an approved origin. - Use short-lived, renewable, minimally scoped Vault tokens. - Prefer workload identity or Vault Agent authentication where available instead of distributing static tokens. - Avoid including tokens or secret response data in logs and error messages. - Add startup validation that fails closed when the endpoint or TLS configuration is invalid. ]]>

T05 · Unauthorized Access and Privilege Escalation

Error
Location
references/v1.3.0-security.md:333
Finding
Secret Name Is Used in a Filesystem Path Without Traversal Protection<![CDATA[ ## Vulnerability Details **File Location**: `references/v1.3.0-security.md`, lines 333–349 **Vulnerability Type**: Path traversal and arbitrary local file read **Risk Level**: High ### Vulnerable Code ```go func LoadSecret(keyName string) string { // 1. 尝试从环境变量读取 if val := os.Getenv(keyName); val != "" { return val } // 2. 尝试从文件读取(Docker Secrets等) if data, err := os.ReadFile("/run/secrets/" + keyName); err == nil { return string(data) } // 3. 开发环境使用默认值(生产环境不允许) if os.Getenv("ENV") == "development" { return getDevSecret(keyName) } log.Fatal("Secret not found: ", keyName) return "" } ``` ### Technical Analysis The function concatenates `keyName` directly onto `/run/secrets/`. It does not reject path separators, `..` components, absolute paths, or symbolic-link escapes. If `keyName` can be influenced by an attacker, a value such as `../../etc/passwd` creates `/run/secrets/../../etc/passwd`, which resolves outside the intended directory. The process can therefore read any file permitted by its operating-system account. The same value is also used as an environment-variable name and included in a fatal log message, although the principal security issue is the unconstrained filesystem path. ### Attack Path 1. An attacker identifies a request, configuration field, or indirect input that controls `keyName`. 2. The attacker supplies a traversal value such as `../../etc/passwd`. 3. The environment-variable lookup does not return a value. 4. `os.ReadFile` resolves the constructed path outside `/run/secrets`. 5. The function returns the contents of the targeted file to its caller. 6. If the caller exposes or uses that value observably, the attacker obtains the file contents or leverages them in a subsequent attack. ### Impact Assessment The accessible scope consists of files readable by the service account. Depending on runtime permissions, this may include mounted credentials, applic ...[truncated 180 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Accept only secret identifiers from a fixed allowlist. - Reject empty names, path separators, absolute paths, null bytes, and `.` or `..` path components. - Use `filepath.Join`, resolve the path, and verify with `filepath.Rel` that it remains below the canonical `/run/secrets` directory. - Consider rejecting symbolic links or securely opening files relative to a trusted directory descriptor. - Do not allow request data to select arbitrary secret names. - Run the service as a dedicated unprivileged account with access only to required secret files. - Return an error rather than calling `log.Fatal`, allowing the caller to fail safely without terminating the entire process. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
references/v1.1.0-error-handling.md:145
Finding
Logging Examples Expose Complete Requests and Private Message Content<![CDATA[ ## Vulnerability Details **File Location**: `references/v1.1.0-error-handling.md`, lines 145–150 and 313–318 **Vulnerability Type**: Sensitive information exposure through logs **Risk Level**: Medium ### Vulnerable Code ```go log.Debug(). Str("service", "biz"). Str("method", "sendMessage"). Int64("user_id", userID). Str("request", req.String()). Msg("processing request") ``` The same guide also recommends logging message content: ```go logger.Debug(). Int64("to_user", req.Peer.UserID). Str("message_preview", preview(req.Message)). Msg("sending message") ``` ### Technical Analysis Serializing an entire request into logs creates an uncontrolled data sink. Depending on request types, `req.String()` may contain authentication tokens, phone numbers, payment data, message text, identifiers, or other personal information. A message preview intentionally records private communication content. Although the examples use debug-level logging, the logger configuration enables debug logging in every environment whose value is not exactly `production`. Staging, testing, and incorrectly labeled production deployments may consequently retain these fields. Log data is commonly copied to centralized collectors, backups, monitoring services, and incident-response systems, increasing the number of identities and systems that can access it. ### Attack Path 1. A user submits a request containing a credential, personal information, or confidential message content. 2. Request processing invokes the illustrated debug logging. 3. The complete serialized request or message preview is written to the application log. 4. The log is forwarded to a centralized logging pipeline or retained on disk. 5. An operator, compromised logging account, or attacker with read access obtains the sensitive content. ### Impact Assessment The issue can expose user communications, identifiers, authentication material, and transaction-related information to an ...[truncated 290 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Never log complete serialized requests by default. - Define an explicit allowlist of non-sensitive metadata fields for each request type. - Redact authorization headers, tokens, cookies, phone numbers, payment fields, and secret values. - Do not log message bodies or previews; log a message identifier, size, and processing result instead. - Enforce safe production log levels through validated configuration that fails closed. - Apply encryption in transit and at rest to centralized logs. - Restrict log access using least-privilege roles and maintain access auditing. - Establish short, documented retention periods for personal data. - Add automated tests that verify known secret and personal-data fields are redacted. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
references/v1.3.0-security.md:180
Finding
CSRF Referer Validation Can Be Bypassed With a Prefix-Matching Domain<![CDATA[ ## Vulnerability Details **File Location**: `references/v1.3.0-security.md`, lines 180–185 **Vulnerability Type**: Improper origin validation **Risk Level**: Medium ### Vulnerable Code ```go // 验证Referer referer := r.Header.Get("Referer") if referer != "" && !strings.HasPrefix(referer, allowedDomain) { http.Error(w, "Invalid referer", http.StatusForbidden) return } ``` ### Technical Analysis A raw string-prefix comparison does not validate URL origin boundaries. For example, if `allowedDomain` is `https://trusted.example`, then a Referer beginning with `https://trusted.example.attacker.test/` satisfies the prefix condition despite belonging to an attacker-controlled hostname. The check also permits an empty Referer. The middleware separately calls `validateCSRFToken`, so exploitation of this Referer defect alone depends on the token check being absent, weak, bypassable, or not correctly bound to the authenticated session. Nevertheless, this code should not be presented as a valid domain-security check. ### Attack Path 1. An attacker registers or controls a hostname whose URL begins with the trusted-domain string, such as `trusted.example.attacker.test`. 2. The attacker hosts a page that submits a state-changing request to the application. 3. The victim visits the attacker's page while authenticated to the target application. 4. The browser sends a Referer containing the attacker-controlled prefix-matching hostname. 5. `strings.HasPrefix` accepts the Referer. 6. If the CSRF token control is missing or independently bypassed, the state-changing request executes under the victim's session. ### Impact Assessment The flawed check weakens defense in depth for all cookie-authenticated state-changing endpoints using this middleware. Actual impact depends on the strength of `validateCSRFToken`. If that control fails, an attacker may perform operations available to the victim, potentially including account changes or destructive actions. ]]>
Remediation
<![CDATA[ ## Remediation Suggestions - Parse the Referer using `net/url`. - Compare the normalized scheme, hostname, and effective port against an exact allowlist. - Do not use string prefixes or suffixes for origin authorization. - Validate the `Origin` header with the same exact-origin rules. - Keep a cryptographically random, session-bound CSRF token as the primary control. - Use `SameSite=Lax` or `SameSite=Strict` cookies where application compatibility permits. - Reject requests with malformed origin information. - Define an explicit policy for missing Origin and Referer headers instead of silently accepting them. - Add tests for lookalike hosts, subdomain confusion, altered ports, user-info syntax, mixed case, and malformed URLs. ]]>
Vulnerability Patterns
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
Findings (17)

Natural-Language Policy Violations

Medium
Confidence
94% confidence
Finding
The markdown mixes English headings with substantial instructional content presented only in Chinese, including the highlighted version note and navigation items. This imposes a language choice on users without offering an alternative or opt-in, which matches the language/locale policy violation criteria.

Intent-Code Divergence

Medium
Confidence
96% confidence
Finding
This is a true issue: the guide’s primary implementation demonstrates unsafe patterns that it later explicitly labels as 'Wrong', including ignored errors (`_ = ...`), fire-and-forget async payment processing, and lack of context propagation/cancellation handling. Because this is a development skill intended to be copied by engineers, these contradictions can directly propagate reliability and security flaws into production payment and entitlement code.

Intent-Code Divergence

Medium
Confidence
93% confidence
Finding
This is a real vulnerability pattern: the purchase flow records a transaction and later activates premium status without a transaction boundary or compensating mechanism, despite the guide later recommending atomic operations. In payment/entitlement logic, partial failure can leave inconsistent state, such as successful activation without confirmed payment or stuck pending transactions, enabling fraud, support burden, and accounting errors.

Missing User Warnings

Medium
Confidence
88% confidence
Finding
The examples normalize logging user IDs, request data, and related sensitive fields without warning about privacy implications or safe-handling requirements. In a developer guidance skill, omission of those warnings is risky because readers are likely to treat the examples as approved patterns and replicate privacy-invasive logging broadly.

Context-Inappropriate Capability

Medium
Confidence
87% confidence
Finding
The logging guidance includes recording full request data via `req.String()`, which can easily capture message bodies, identifiers, tokens, or other sensitive fields. In an error-handling/logging best-practices document, demonstrating broad request logging normalizes over-collection and can lead downstream developers to persist sensitive data into logs, increasing privacy and incident-response risk.

Context-Inappropriate Capability

Medium
Confidence
91% confidence
Finding
The business-operation example logs `message_preview`, which directly encourages logging user-generated content. Even partial message content may contain secrets, personal information, or regulated data, so this example can cause widespread sensitive-data leakage if copied into production services.

Natural-Language Policy Violations

Medium
Confidence
88% confidence
Finding
This markdown file presents its title and surrounding instructional content in Chinese only, and there is no visible opt-in, alternative language, or justification that the skill is region-specific. That can violate a language/locale policy requiring user choice rather than forcing a specific language by default.

Natural-Language Policy Violations

Medium
Confidence
92% confidence
Finding
The file title and all instructional content are presented in Chinese, with no indication that other languages are supported or that the locale is intentionally region-specific. Under the policy, forcing a specific language without user opt-in is a natural-language locale violation.

Natural-Language Policy Violations

Medium
Confidence
95% confidence
Finding
This markdown file contains user-facing instructional content in Chinese, including headings and code-context descriptions, but does not indicate that the skill is region- or language-specific or offer an opt-in language choice. Under the policy rule, forcing a specific language without user choice is a natural-language policy violation.

Natural-Language Policy Violations

Medium
Confidence
94% confidence
Finding
The document title, headings, comments, and examples are all presented in Chinese, and there is no indication that users can opt into another language or that the file is intentionally region-specific. Under the stated policy, forcing a specific language without user opt-in is a natural-language policy violation.

Intent-Code Divergence

Medium
Confidence
96% confidence
Finding
The example claims to enforce tenant isolation automatically, but it does so by blindly appending `WHERE tenant_id = ?` to any query string. This can produce invalid SQL when the original query already contains `WHERE`, `ORDER BY`, `LIMIT`, joins, or subqueries, and it can also give developers a false sense that tenant isolation is reliably enforced when it is not. In a multi-tenant RPC development guide, misleading isolation examples are security-relevant because they may be copied into production code and lead to cross-tenant data exposure or broken access controls.

Natural-Language Policy Violations

Low
Confidence
95% confidence
Finding
The file's natural-language instructions and headings are entirely in Chinese, which effectively forces a specific language for readers without any opt-in or explanation. Under the stated policy, language constraints should either offer a choice or be clearly justified as region-specific.

Context-Inappropriate Capability

Low
Confidence
80% confidence
Finding
The tracing example logs client IP addresses even though IPs are not necessary to illustrate trace propagation. IP addresses are personal data in many environments, and adding them to standard request logs increases privacy exposure and data-retention obligations without a clear operational need in this documentation context.

Natural-Language Policy Violations

Low
Confidence
95% confidence
Finding
This markdown file presents its instructions and examples entirely in Chinese, beginning with the title and section headings, with no indication that the user can choose another language. Under the policy rule for natural-language violations, forcing a specific language without user opt-in is a reportable issue.

Natural-Language Policy Violations

Low
Confidence
95% confidence
Finding
The file title and all instructional content are presented in Chinese, which imposes a specific language choice in natural-language content. The file does not indicate that language selection is optional or that the skill is intentionally region-specific.

Natural-Language Policy Violations

Low
Confidence
84% confidence
Finding
The heading is entirely in Chinese ("数据库优化"), which indicates a language-specific presentation without any visible user choice or justification in the file. The policy explicitly flags language or locale constraints when they are imposed without opt-in.

Natural-Language Policy Violations

Low
Confidence
93% confidence
Finding
This markdown file uses Chinese headings and labels throughout, such as the title and section names, but does not indicate that the skill is region-specific or provide any user language choice. Under the policy rule for natural-language violations, forcing a specific language without opt-in is a reportable issue.

Static analysis

No suspicious patterns detected.