Feedback

ark-pentest-issue-resolver

@mckinsey Claim

Basic information

Repository
mckinsey
Skill
ark-pentest-issue-resolver

About ark-pentest-issue-resolver

Resolve common penetration testing issues in Ark. Use when fixing security vulnerabilities from pentest reports, security audits, or OWASP Top 10 issues.

ark-pentest-issue-resolver is an agent skill listed in the AddMCP.net directory, published by mckinsey. Runtime: TypeScript. License: Apache-2.0. The repository has 433 GitHub stars. Source code is hosted on github.com. Related topics: agentic-ai, ai, cloud, devops, kubernetes.

Overview

What is ark-pentest-issue-resolver?


name: ark-pentest-issue-resolver description: Resolve common penetration testing issues in Ark. Use when fixing security vulnerabilities from pentest reports, security audits, or OWASP Top 10 issues.


Ark Penetration Test Issue Resolver

Provides detection patterns, mitigation strategies, and fixes for common penetration testing issues found in the Ark platform.

When to use this skill

Use this skill when:

  • User reports a penetration testing finding without a specific CVE
  • Security audit reveals OWASP Top 10 vulnerabilities
  • User mentions issues like "XSS", "SQL injection", "CSRF", etc.
  • Need to identify and fix common security misconfigurations

Note: This skill is used by the ark-security-patcher agent when no specific CVE is mentioned. It helps identify and resolve standard penetration testing findings.

Common Penetration Test Issues

### 1. SQL Injection **Description**: Attacker can inject malicious SQL queries through user input. **Detection Patterns**: ```python # VULNERABLE: Direct string concatenation query = f"SELECT * FROM users WHERE username = '{username}'" # VULNERABLE: String formatting query = "SELECT * FROM users WHERE id = %s" % user_id ``` **Mitigation**: ```python # SECURE: Use parameterized queries cursor.execute("SELECT * FROM users WHERE username = ?", (username,)) # SECURE: Use ORM with parameter binding User.objects.filter(username=username) # SECURE: Use sqlalchemy with bound parameters session.query(User).filter(User.username == username) ``` **Ark Context**: - Check Python services: `services/ark-api/`, executor services - Search for: `cursor.execute`, `db.query`, SQL string concatenation - Verify all database queries use parameterized statements --- ### 2. Cross-Site Scripting (XSS) **Description**: Attacker can inject malicious JavaScript into web pages viewed by other users. **Types**: - **Reflected XSS**: Malicious script in URL/request is reflected in response - **Stored XSS**: Malicious script stored in database and displayed to users - **DOM-based XSS**: Vulnerability exists in client-side JavaScript **Detection Patterns**: ```javascript // VULNERABLE: Direct innerHTML manipulation element.innerHTML = userInput; // VULNERABLE: Unescaped template rendering return `
${userInput}
`; // VULNERABLE: dangerouslySetInnerHTML in React
``` **Mitigation**: ```javascript // SECURE: Use textContent element.textContent = userInput; // SECURE: Use React/Vue built-in escaping return
{userInput}
// SECURE: Sanitize HTML if HTML input is required import DOMPurify from 'dompurify'; const clean = DOMPurify.sanitize(userInput); // SECURE: Set Content-Security-Policy header Content-Security-Policy: default-src 'self'; script-src 'self' ``` **Ark Context**: - Check: `ark-dashboard/`, `docs/` (Next.js applications) - Search for: `dangerouslySetInnerHTML`, `innerHTML`, unescaped templates - Ensure proper Content-Security-Policy headers in Next.js config - Verify all user input is escaped in React components --- ### 3. Cross-Site Request Forgery (CSRF) **Description**: Attacker tricks user into executing unwanted actions on authenticated application. **Detection Patterns**: ```go // VULNERABLE: No CSRF token validation http.HandleFunc("/api/delete", func(w http.ResponseWriter, r *http.Request) { // Directly processes DELETE without token deleteUser(r.FormValue("id")) }) ``` **Mitigation**: ```go // SECURE: Use CSRF middleware import "github.com/gorilla/csrf" csrfMiddleware := csrf.Protect( []byte("32-byte-long-auth-key"), csrf.Secure(true), ) http.ListenAndServe(":8000", csrfMiddleware(router)) // SECURE: Verify CSRF token token := r.Header.Get("X-CSRF-Token") if !csrf.Validate(token, session) { http.Error(w, "Invalid CSRF token", http.StatusForbidden) return } // SECURE: Use SameSite cookie attribute http.SetCookie(w, &http.Cookie{ Name: "session", Value: sessionID, SameSite: http.SameSiteStrictMode, Secure: true, HttpOnly: true, }) ``` **Ark Context**: - Check: Go operator API endpoints, Python API services - Search for: State-changing endpoints (POST, PUT, DELETE) without CSRF protection - Verify cookies use `SameSite=Strict` or `SameSite=Lax` - Add CSRF middleware to API routes that modify state --- ### 4. Insecure Direct Object References (IDOR) **Description**: Application exposes internal implementation objects (IDs) without proper authorization checks. **Detection Patterns**: ```python # VULNERABLE: No authorization check @app.route('/api/user/') def get_user(user_id): return User.query.get(user_id) # Any authenticated user can access any user # VULNERABLE: Predictable IDs @app.route('/api/document/') def get_document(doc_id): return Document.query.get(doc_id) # Sequential IDs are guessable ``` **Mitigation**: ```python # SECURE: Check authorization @app.route('/api/user/') def get_user(user_id): user = User.query.get(user_id) if user.id != current_user.id and not current_user.is_admin: abort(403, "Unauthorized") return user # SECURE: Use UUIDs instead of sequential IDs import uuid user_id = uuid.uuid4() # SECURE: Implement resource ownership check def check_ownership(resource_id, user_id): resource = Resource.query.get(resource_id) if resource.owner_id != user_id: raise PermissionDenied() ``` **Ark Context**: - Check: All REST API endpoints in Python services, Go operator - Search for: Direct ID references in URL paths, missing authorization checks - Verify: Every resource access checks user permissions - Consider: Using UUIDs for resource identifiers --- ### 5. Security Misconfiguration **Description**: Insecure default configurations, incomplete setups, open cloud storage, misconfigured HTTP headers. **Common Issues**: #### Missing Security Headers **Detection**: ```bash curl -I https://ark-dashboard.example.com | grep -E "X-Frame-Options|X-Content-Type-Options|Strict-Transport-Security" ``` **Mitigation**: ```go // Add security headers middleware func securityHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-XSS-Protection", "1; mode=block") w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") w.Header().Set("Content-Security-Policy", "default-src 'self'") w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") next.ServeHTTP(w, r) }) } ``` ```javascript // Next.js configuration (next.config.js) module.exports = { async headers() { return [ { source: '/:path*', headers: [ { key: 'X-Frame-Options', value: 'DENY' }, { key: 'X-Content-Type-Options', value: 'nosniff' }, { key: 'X-XSS-Protection', value: '1; mode=block' }, { key: 'Strict-Transport-Security', value: 'max-age=31536000; includeSubDomains' }, { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, ], }, ] }, } ``` #### Debug Mode Enabled in Production **Detection**: ```bash grep -r "DEBUG.*=.*true" . grep -r "NODE_ENV.*development" . ``` **Mitigation**: - Set `DEBUG=false` in production - Set `NODE_ENV=production` - Remove stack traces from error responses - Disable verbose logging in production --- ### 6. Sensitive Data Exposure **Description**: Application exposes sensitive data through logs, error messages, or insecure transmission. **Detection Patterns**: ```python # VULNERABLE: Logging sensitive data logger.info(f"User {username} logged in with password {password}") # VULNERABLE: Exposing secrets in error messages raise Exception(f"Database connection failed: {db_password}") # VULNERABLE: Sensitive data in URLs redirect(f"/reset-password?token={reset_token}") ``` **Mitigation**: ```python # SECURE: Never log sensitive data logger.info(f"User {username} logged in successfully") # SECURE: Generic error messages raise Exception("Database connection failed") logger.error("DB error", exc_info=True) # Full details only in logs # SECURE: Use POST for sensitive data # POST /reset-password with token in body # SECURE: Mask sensitive data def mask_credit_card(card_number): return f"****-****-****-{card_number[-4:]}" ``` **Environment Variables**: ```bash # VULNERABLE: Hardcoded secrets API_KEY = "sk_live_abc123xyz" # SECURE: Use environment variables API_KEY = os.getenv("API_KEY") # SECURE: Use Kubernetes secrets apiVersion: v1 kind: Secret metadata: name: ark-secrets type: Opaque data: api-key: ``` **Ark Context**: - Check: All logging statements, error handlers - Search for: Hardcoded secrets, API keys, passwords - Verify: TLS/HTTPS for all communications - Use: Kubernetes Secrets for sensitive configuration --- ### 7. Broken Authentication **Description**: Weak authentication mechanisms allowing credential stuffing, brute force, or session hijacking. **Common Issues**: #### Weak Password Requirements **Mitigation**: ```python import re def validate_password(password): """Enforce strong password policy""" if len(password)

Workflow: Resolving Pentest Issues

Step 1: Identify the Issue Category

Map the reported issue to one of the categories above:

  • SQL Injection → Database queries
  • XSS → User input rendering
  • CSRF → State-changing API endpoints
  • IDOR → Resource access without authorization
  • Security Misconfiguration → Headers, debug mode, defaults
  • Sensitive Data Exposure → Logging, error messages, transmission
  • Broken Authentication → Password policy, session management
  • Broken Access Control → Permission checks, RBAC
  • Insufficient Logging → Security event logging
  • SSRF → External URL fetching
  • XXE → XML parsing
  • Insecure Deserialization → Pickle, YAML loading
  • Path Traversal → File system access
  • Command Injection → System command execution
  • Missing Rate Limiting → API protection

Step 2: Search for Vulnerable Patterns

Use grep/ripgrep to find vulnerable code patterns:

# SQL Injection
grep -r "cursor.execute.*%" .
grep -r "query.*format" .

# XSS
grep -r "innerHTML" .
grep -r "dangerouslySetInnerHTML" .

# Command Injection
grep -r "os.system" .
grep -r "shell=True" .

# Path Traversal
grep -r "open.*request" .

# Insecure Deserialization
grep -r "pickle.loads" .
grep -r "yaml.load" .

Step 3: Analyze Impact on Ark

Consider which Ark components are affected:

  • Go Operator: ark/ - Controllers, webhooks, API server
  • Python Services: services/ - Executor services, API endpoints
  • Node.js Applications: ark-dashboard/, docs/, ark-cli/
  • Kubernetes Resources: Deployment configs, RBAC, Network Policies

Step 4: Present Mitigation Options

Present the user with:

  1. Vulnerable code patterns found
  2. Recommended fixes for each pattern
  3. Testing strategy
  4. Potential breaking changes

Wait for user approval before implementing.

Step 5: Implement Fixes

Apply the appropriate mitigation from the categories above:

  • Update vulnerable code patterns
  • Add security middleware/validators
  • Configure security headers
  • Update dependencies if needed

Step 6: Test the Fixes

# Run existing tests
make test

# Security-specific tests
# - Test with malicious input
# - Verify security headers
# - Check authorization enforcement
# - Validate input sanitization

Step 7: Create PR with Security Context

Document:

  • What vulnerability was found
  • Where it was found (files, line numbers)
  • What was changed to fix it
  • How to verify the fix
  • Any breaking changes

Ark-Specific Security Considerations

Kubernetes Operator Security

CRD Validation:

// Add validation to CRD specs
// +kubebuilder:validation:Pattern=^[a-zA-Z0-9-]+$
// +kubebuilder:validation:MinLength=1
// +kubebuilder:validation:MaxLength=253
Name string `json:"name"`

RBAC Principle of Least Privilege:

# Only grant necessary permissions
rules:
- apiGroups: ["ark.example.com"]
  resources: ["models"]
  verbs: ["get", "list"]  # Not "delete" or "*"

Python Service Security

Input Validation:

from pydantic import BaseModel, validator

class PromptRequest(BaseModel):
    prompt: str
    max_tokens: int

    @validator('prompt')
    def validate_prompt(cls, v):
        if len(v) > 10000:
            raise ValueError('Prompt too long')
        return v

    @validator('max_tokens')
    def validate_max_tokens(cls, v):
        if v < 1 or v > 4096:
            raise ValueError('Invalid max_tokens')
        return v

Node.js / Next.js Security

Environment Variables:

// Only expose NEXT_PUBLIC_ vars to client
// next.config.js
module.exports = {
  env: {
    // Server-side only
    DATABASE_URL: process.env.DATABASE_URL,
  },
  publicRuntimeConfig: {
    // Client-side accessible
    API_URL: process.env.NEXT_PUBLIC_API_URL,
  },
}

Docker Security

Non-root User:

# Run as non-root user
RUN addgroup -g 1001 -S appuser && \
    adduser -u 1001 -S appuser -G appuser
USER appuser

Minimal Base Images:

# Use distroless or alpine
FROM gcr.io/distroless/python3
# OR
FROM python:3.11-alpine

Testing Security Fixes

Manual Testing Checklist

  • [ ] Test with malicious input (SQL injection payloads)
  • [ ] Test with XSS payloads (<script>alert('XSS')</script>)
  • [ ] Test with path traversal (../../../../etc/passwd)
  • [ ] Test authorization bypasses (user A accessing user B's data)
  • [ ] Test rate limiting (excessive requests)
  • [ ] Verify security headers present
  • [ ] Check error messages don't expose sensitive data
  • [ ] Verify HTTPS/TLS is enforced

Automated Security Testing

# Static analysis
bandit -r services/  # Python
gosec ./...          # Go
npm audit            # Node.js

# Dependency scanning
safety check         # Python
go list -json -m all | nancy sleuth  # Go
npm audit fix        # Node.js

# Container scanning
trivy image ark-operator:latest

Common Penetration Test Report Keywords

When you see these terms in a pentest report, map them to the appropriate category:

  • "Insufficient input validation" → SQL Injection, XSS, Command Injection, Path Traversal
  • "Missing security headers" → Security Misconfiguration (#5)
  • "Sensitive information disclosure" → Sensitive Data Exposure (#6)
  • "Missing CSRF protection" → CSRF (#3)
  • "Broken access control" → IDOR (#4) or Broken Access Control (#8)
  • "Weak authentication" → Broken Authentication (#7)
  • "Insecure session management" → Broken Authentication (#7)
  • "Server-side request forgery" → SSRF (#10)
  • "XML external entity injection" → XXE (#11)
  • "Insecure deserialization" → Insecure Deserialization (#12)
  • "Directory traversal" → Path Traversal (#13)
  • "OS command injection" → Command Injection (#14)
  • "No rate limiting" → Missing Rate Limiting (#15)
  • "Information leakage" → Sensitive Data Exposure (#6)
  • "Insufficient logging" → Insufficient Logging & Monitoring (#9)

Important Notes

  • Always get user approval before implementing security fixes
  • Test thoroughly - security fixes can break functionality
  • Document the vulnerability clearly in commit messages and PRs
  • Consider backward compatibility when changing APIs or behaviors
  • Prioritize by severity: Critical > High > Medium > Low
  • Defense in depth: Apply multiple layers of security controls
  • Principle of least privilege: Grant minimum necessary permissions

Comments

No comments yet

Be the first to share feedback about this listing. Sign in to leave a comment.

Sign In

Feedback 💬