<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: implementing-template-variables
description: >-
  Implement Nuclei template variables, helper functions, and dynamic payloads.
  Covers built-in variables, custom variables, DSL expressions, payload
  generators, environment variables, and inter-template data sharing.
domain: cybersecurity
subdomain: nuclei-templating
tags:
  - nuclei
  - variables
  - dsl
  - helpers
  - dynamic-payloads
  - expressions
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: []
---

# Implementing Template Variables

## Overview

Template variables enable dynamic payload generation, inter-request data
sharing, and environment-aware scanning. Mastering variables transforms
static templates into adaptive detection tools that adjust to each target.

Mode: `[MODE: BLUE]` — Dynamic template engineering.

## Prerequisites

| Requirement | Details |
|---|---|
| Nuclei v3+ for full DSL and variable support | Required |
| Understanding of template execution flow | Required |

## Key Concepts

### Built-In Variables

```yaml
id: target-info-extraction

info:
  name: Target Information Extraction
  author: nerf
  severity: info
  tags: recon,info,variables
  metadata:
    max-request: 1

http:
  - method: GET
    path:
      - "{{BaseURL}}/"
    extractors:
      - type: dsl
        dsl:
          - '"Scheme: " + Scheme'
          - '"Host: " + Host'
          - '"Hostname: " + Hostname'
          - '"Port: " + Port'
          - '"Path: " + Path'
          - '"BaseURL: " + BaseURL'
          - '"RootURL: " + RootURL'
```

### Custom Variables

```yaml
id: custom-var-scanning

info:
  name: Custom Variable Scanning
  author: nerf
  severity: info
  tags: variables,custom

variables:
  api_version: "v2"
  content_type: "application/json"
  canary: '{{md5("nuclei-scan-{{rand_int(1000,9999)}}") }}'

http:
  - method: GET
    path:
      - "{{BaseURL}}/api/{{api_version}}/status"
    headers:
      Content-Type: "{{content_type}}"
      X-Request-ID: "{{canary}}"
    matchers:
      - type: status
        status:
          - 200
```

### Helper Functions

```yaml
id: helper-function-demo

info:
  name: Template Helper Functions
  author: nerf
  severity: info
  tags: variables,helpers

http:
  - method: POST
    path:
      - "{{BaseURL}}/api/test"
    headers:
      Content-Type: application/json
    body: |
      {
        "random_id": "{{rand_int(100000, 999999)}}",
        "random_string": "{{rand_text_alpha(16)}}",
        "timestamp": "{{unix_time()}}",
        "encoded_payload": "{{base64('<script>alert(1)</script>')}}",
        "url_encoded": "{{url_encode('param=value&key=<test>')}}",
        "hash_check": "{{md5('verification-string')}}",
        "sha_check": "{{sha256('integrity-value')}}"
      }
    matchers:
      - type: status
        status:
          - 200
```

### Environment Variable Access

```yaml
id: authenticated-scan-env

info:
  name: Authenticated Scan via Environment
  author: nerf
  severity: info
  tags: auth,environment,variables
  metadata:
    max-request: 1

http:
  - method: GET
    path:
      - "{{BaseURL}}/api/me"
    headers:
      Authorization: "Bearer {{env_var('API_TOKEN')}}"
    matchers-condition: and
    matchers:
      - type: word
        part: body
        words:
          - '"email"'
          - '"username"'
        condition: or
      - type: status
        status:
          - 200
```

### Dynamic Extractor Variables

```yaml
id: version-conditional-check

info:
  name: Version-Conditional Vulnerability Check
  author: nerf
  severity: high
  tags: version,conditional,variables
  metadata:
    max-request: 2

http:
  - raw:
      - |
        GET {{BaseURL}}/version HTTP/1.1
        Host: {{Hostname}}
      - |
        GET {{BaseURL}}/admin HTTP/1.1
        Host: {{Hostname}}
        X-Version: {{app_version}}
    cookie-reuse: true
    extractors:
      - type: regex
        name: app_version
        part: body_1
        group: 1
        regex:
          - '"version":\s*"([0-9.]+)"'
        internal: true
    matchers-condition: and
    matchers:
      - type: dsl
        dsl:
          - 'compare_versions(app_version, "< 2.0.0")'
      - type: word
        part: body_2
        words:
          - "admin"
```

### DSL Expression Variables

```yaml
id: response-analysis-dsl

info:
  name: Response Analysis via DSL
  author: nerf
  severity: info
  tags: dsl,analysis,variables

http:
  - method: GET
    path:
      - "{{BaseURL}}/"
    matchers:
      - type: dsl
        dsl:
          - 'status_code == 200'
          - 'len(body) > 0'
          - 'contains(to_lower(all_headers), "x-powered-by")'
          - '!contains(body, "error")'
        condition: and
    extractors:
      - type: dsl
        dsl:
          - '"Content-Length: " + to_string(content_length)'
          - '"Response Time: " + to_string(duration) + "s"'
          - '"Header Count: " + to_string(len(split(all_headers, "\n")))'
```

## Workflow

### Step 1: Test Variable Resolution

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

### Step 2: Scan with Custom Variables

```bash
node scripts/agent.js --action scan --target https://staging.example.com \
  --template template.yaml --vars "api_version=v3,token=abc123" \
  --output /tmp/var-scan.json
```

## Verification

- [ ] Built-in variables resolve correctly for target URL format
- [ ] Custom variables defined in `variables:` block at template root
- [ ] Internal extractors use `internal: true` for inter-request sharing
- [ ] Helper functions produce expected output format
- [ ] Environment variables have fallback handling
- [ ] DSL expressions tested with edge case values
- [ ] Variable names follow lowercase underscore convention

## References

- [Nuclei Variables](https://docs.projectdiscovery.io/templates/reference/variables)
- [Nuclei Helper Functions](https://docs.projectdiscovery.io/templates/reference/helper-functions)
- [Nuclei DSL Reference](https://docs.projectdiscovery.io/templates/reference/helper-functions)
