<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: writing-code-protocol-templates
description: >-
  Write Nuclei code protocol templates that execute custom scripts for
  vulnerability detection. Covers Go, Python, and JavaScript code execution,
  external tool integration, custom protocol handlers, and safe sandbox
  patterns for complex detection logic.
domain: cybersecurity
subdomain: nuclei-templating
tags:
  - nuclei
  - code-protocol
  - scripting
  - custom-checks
  - go
  - python
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1190"]
---

# Writing Code Protocol Templates

## Overview

Code protocol templates execute custom scripts when detection logic exceeds
what matchers and DSL can express. They support Go, Python, and JavaScript,
enabling integration with external tools, complex parsing, and custom protocol
implementations that are impossible with declarative templates alone.

Mode: `[MODE: RED]` — Custom code-based vulnerability detection.

## Prerequisites

| Requirement | Details |
|---|---|
| Nuclei v3+ with `-code` flag enabled | Required |
| Go, Python 3, or Node.js installed on scanning host | Required |
| Templates require explicit `-code` opt-in for security | Required |

## Key Concepts

### Basic Python Code Template

```yaml
id: custom-jwt-weakness

info:
  name: JWT Algorithm Confusion Detection
  author: nerf
  severity: high
  description: |
    Detects JWT implementations vulnerable to algorithm confusion
    by testing if the server accepts tokens signed with 'none' algorithm.
  classification:
    cwe-id: CWE-327
  tags: jwt,auth,code-protocol,crypto
  metadata:
    max-request: 1

code:
  - engine:
      - py
      - python3
    source: |
      import jwt
      import json
      import sys

      target = "{{BaseURL}}"
      # Create token with 'none' algorithm
      payload = {"sub": "admin", "role": "admin"}
      try:
          token = jwt.encode(payload, key="", algorithm="none")
          print(json.dumps({
              "vulnerable": True,
              "token": token,
              "target": target
          }))
      except Exception as e:
          print(json.dumps({
              "vulnerable": False,
              "error": str(e)
          }))

    matchers:
      - type: word
        words:
          - '"vulnerable": true'
```

### Go Code Template

```yaml
id: custom-dns-rebinding-check

info:
  name: DNS Rebinding Vulnerability Check
  author: nerf
  severity: high
  classification:
    cwe-id: CWE-350
  tags: dns,rebinding,code-protocol
  metadata:
    max-request: 0

code:
  - engine:
      - go
    source: |
      package main

      import (
        "fmt"
        "net"
        "time"
      )

      func main() {
        host := "{{Hostname}}"
        results := make(map[string]bool)

        for i := 0; i < 5; i++ {
          ips, err := net.LookupHost(host)
          if err == nil {
            for _, ip := range ips {
              results[ip] = true
            }
          }
          time.Sleep(500 * time.Millisecond)
        }

        if len(results) > 1 {
          fmt.Printf("VULNERABLE: DNS rebinding detected — %d unique IPs\n", len(results))
          for ip := range results {
            fmt.Printf("  IP: %s\n", ip)
          }
        } else {
          fmt.Println("SAFE: consistent DNS resolution")
        }
      }

    matchers:
      - type: word
        words:
          - "VULNERABLE: DNS rebinding"
```

### External Tool Integration

```yaml
id: custom-ssl-audit

info:
  name: Custom SSL Configuration Audit
  author: nerf
  severity: medium
  tags: ssl,tls,audit,code-protocol
  metadata:
    max-request: 0

code:
  - engine:
      - py
      - python3
    source: |
      import ssl
      import socket
      import json

      host = "{{Hostname}}"
      port = 443
      findings = []

      ctx = ssl.create_default_context()
      try:
          with ctx.wrap_socket(socket.socket(), server_hostname=host) as s:
              s.settimeout(10)
              s.connect((host, port))
              cert = s.getpeercert()
              cipher = s.cipher()

              if cipher[1] == "TLSv1" or cipher[1] == "TLSv1.1":
                  findings.append(f"Weak TLS version: {cipher[1]}")
              if "RC4" in cipher[0] or "DES" in cipher[0]:
                  findings.append(f"Weak cipher: {cipher[0]}")

              print(json.dumps({
                  "host": host,
                  "protocol": cipher[1],
                  "cipher": cipher[0],
                  "findings": findings,
                  "vulnerable": len(findings) > 0
              }))
      except Exception as e:
          print(json.dumps({"error": str(e), "vulnerable": False}))

    matchers:
      - type: word
        words:
          - '"vulnerable": true'
```

### JavaScript Code Template

```yaml
id: custom-cors-check

info:
  name: CORS Misconfiguration Deep Check
  author: nerf
  severity: medium
  classification:
    cwe-id: CWE-942
  tags: cors,misconfig,code-protocol
  metadata:
    max-request: 0

code:
  - engine:
      - js
      - node
    source: |
      const https = require('https');
      const url = require('url');

      const target = '{{BaseURL}}';
      const origins = ['https://evil.com', 'null', '{{BaseURL}}.evil.com'];
      const results = [];

      let completed = 0;
      origins.forEach(origin => {
        const parsed = url.parse(target);
        const options = {
          hostname: parsed.hostname,
          port: parsed.port || 443,
          path: parsed.path || '/',
          method: 'GET',
          headers: { 'Origin': origin },
          rejectUnauthorized: false
        };

        const req = https.request(options, res => {
          const acao = res.headers['access-control-allow-origin'];
          if (acao && (acao === origin || acao === '*')) {
            results.push({ origin, reflected: acao, vulnerable: true });
          }
          completed++;
          if (completed === origins.length) {
            console.log(JSON.stringify({ results, vulnerable: results.length > 0 }));
          }
        });
        req.on('error', () => { completed++; });
        req.end();
      });

    matchers:
      - type: word
        words:
          - '"vulnerable": true'
```

## Workflow

### Step 1: Run Code Template

```bash
node scripts/agent.js --action scan --target https://staging.example.com \
  --template code-template.yaml --output /tmp/code-scan.json
```

### Step 2: Validate Template

```bash
node scripts/agent.js --action validate --template code-template.yaml
```

## Verification

- [ ] Template uses correct engine specification (py/go/js)
- [ ] Code handles errors gracefully with try/except
- [ ] Output is JSON for structured matcher evaluation
- [ ] No destructive operations in code blocks
- [ ] `-code` flag documented in usage instructions
- [ ] External dependencies noted in template description
- [ ] Template variables (`{{BaseURL}}`, `{{Hostname}}`) used correctly

## References

- [Nuclei Code Protocol](https://docs.projectdiscovery.io/templates/protocols/code/basic-code)
- [Nuclei Template Variables](https://docs.projectdiscovery.io/templates/reference/variables)
