← Documentation

Security Guide

This document provides a secure usage guide for the Zandy_Template template engine.

Table of Contents

Variable Access Security

Problem Description

⚠️ Important: By default, templates can access all global variables, including system variables and configuration information.

Security Risks

Solutions

Solution 1: Whitelist mode (recommended for production)

// Configure a whitelist so only the specified variables can be accessed by the template
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data', 'items'];

// Usage stays the same
$GLOBALS['user'] = $user;
$GLOBALS['data'] = $data;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

Advantages:

Solution 2: Explicit passing mode (most secure)

// Pass variables explicitly for full control over variable access
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
    'user' => $user,
    'data' => $data
]);

Advantages:

Security Recommendations

  1. Development environment: the fully open mode (default) may be used for convenient debugging
  2. Production environment: whitelist mode or explicit passing mode is recommended
  3. High security requirements: use explicit passing mode for full control over variable access
  4. Untrusted template sources: explicit passing mode must be used, and PHP code blocks must be disabled

Code Execution Security

Problem Description

⚠️ Important: the following syntax allows arbitrary PHP code to be executed, so make sure the template source is trusted:

Security Risks

Security Recommendations

  1. Trusted template source:

    • If the templates are written by developers, these features may be used
    • Make sure template file permissions are correct
  2. Untrusted template source:

    • PHP code blocks must be disabled (where possible)
    • Use a whitelist mechanism to restrict which files may be included
    • Strictly validate template paths
  3. Production environment:

    • If the template source is untrusted, these features should be disabled
    • Consider filtering this syntax during the template parsing stage

Sandbox Mode and Policy Object (v1.11.0)

Compile-time sandbox (tpl_sandbox): once enabled, the compile stage rejects php blocks, the include family of directives, and superglobal access:

$GLOBALS['siteConf']['tpl_sandbox'] = true;

Sandbox policy object (tpl_sandbox_policy): a fine-grained whitelist applied while the sandbox is on— Zandy_Template_SandboxPolicy provides four levels of control: functions/methods/properties/static calls, with string-aware call-surface extraction (string literal contents are not misread as calls):

$policy = new Zandy_Template_SandboxPolicy();
$policy->allowFunction('strtoupper')->allowFunction('date');
$policy->allowMethod('getName');        // object method whitelist
$policy->allowProperty('name');         // object property whitelist
$policy->allowStatic('MyClass::fmt');   // static call whitelist
$GLOBALS['siteConf']['tpl_sandbox'] = true;
$GLOBALS['siteConf']['tpl_sandbox_policy'] = $policy;

Call surfaces not on the whitelist are rejected at compile time (with a diagnostic carrying the template line number) and never make it into the artifact.

Sandbox and Plugin Boundary (v1.14.x)

The sandbox audits template source text only, never code generated by plugins. The compile-time sandbox (tpl_sandbox) and policy whitelist inspect expressions/call surfaces in the host template. Plugins (directive handlers, filters, validators, before/after hooks) emit PHP code directly during the compile pipeline; that generated code is not audited again by the sandbox. Therefore:

// Correct way to use an attribute value as an expression in a directive plugin
if (strpos($value, '$') !== false || preg_match('/[A-Za-z_]/', $value)) {
    Zandy_Template::checkExpressionAllowed($value, $line); // halts if sandbox/policy rejects
}

Tighter variable injection in the sandbox (V2-09): with tpl_sandbox enabled, extractTemplateVars() injects only the variables explicitly passed via $vars; it no longer injects siteConf or any global variables. Configuration needed by sandboxed templates (such as auto_escape) should be prepared by the caller and passed explicitly. Non-sandbox modes keep their historical semantics (open/whitelist/explicit unchanged).

eval Syntax Fallback Switch (v1.11.0)

Compiled artifacts are by default include-executed after validation via a temporary file + php -l; when the environment lacks both exec and opcache, the engine falls back to executing the compiled artifact through eval. eval will fully execute the artifact once (equivalent in side effects to include)—if a template contains side-effecting operations (such as a php block that writes to the database), take care in dual-execution environments. It can be explicitly disabled:

$GLOBALS['siteConf']['tpl_eval_fallback'] = false;
// Once disabled, a dual-lacking environment (no exec and no opcache) degrades to unvalidated + an error_log notice

Path Security

Protection Mechanism

The template engine automatically validates:

Path Validation Code

// Template path validation (validatePathInBase: boundary prefix comparison after realpath resolution)
$resolvedPath = realpath($path); // resolves ../, symbolic links and redundant separators
if ($resolvedPath === false) {
    self::halt('$tplDir is not a valid tpl path', true);
}
// Boundary check: the path equals the base directory (trailing separator stripped) or
// lives inside it ("base directory + directory separator" prefix). Never use a plain
// containment test such as stripos: the base string appearing mid-path can be
// constructed to bypass it, and trailing-separator differences would falsely reject
// "template directory == base directory".
$base = rtrim($tplBaseDir, '/\\');
if ($resolvedPath !== $base && 0 !== strpos($resolvedPath, $base . DIRECTORY_SEPARATOR)) {
    self::halt('$tplDir is not a valid tpl path', true);
}

// Cache path validation shares the same boundary semantics (realpath + prefix comparison);
// cache file writes additionally go through isCachePathSafe(): inside the cache
// directory (realpath boundary) and not a symbolic link.
// For targets that "do not exist yet but would exist after escaping", a lexical path
// check (resolving . and .. per segment, then prefix comparison) serves as the second boundary.

Security Recommendations

  1. Configure the correct paths:
    • Make sure tplBaseDir and tplCacheBaseDir are configured correctly
    • Use absolute paths to avoid relative path problems

Boundary contract differences between entry points (clarified in v1.15.0)

Entry point When tplBaseDir is not configured When configured
outCache / instance API Required (missing → explicit error and halt) Path boundary validation active
outHTML / outEval Historical pass-through (fail-open) + one-time error_log notice (since v1.15.0) Path boundary validation active

Without tplBaseDir, outHTML/outEval have no boundary baseline (validation is skipped and the template directory may point anywhere). Since v1.15.0 this state emits a one-time error_log notice; once deployment is ready, set $GLOBALS['siteConf']['tplRequireBaseDir'] = true to enforce it (missing → refuse to render, fully aligning with the outCache contract). Configure tplBaseDir in all production environments and enable tplRequireBaseDir after upgrade verification.

  1. File permissions:

    • Template files: read-only permission
    • Cache directory: writable permission, but restrict access
  2. Path validation:

    • The engine already validates paths automatically, so no extra handling is needed
    • Just make sure the configured paths are correct

HTML Escaping and XSS Protection

Escaping Strategy

Zandy_Template adopts a manual escaping strategy:

Usage Scenarios

Scenario 1: User input (must be escaped)

<!-- User input must be escaped to prevent XSS attacks -->
Username: {$username|escape}
Comment: {$comment|escape}
Search keyword: {$keyword|escape}

Why escaping is required:

Scenario 2: Trusted content (may be left unescaped)

<!-- Content generated by the system from a trusted source may be left unescaped -->
Title: {$title}
Description: {$description}

When it is safe to skip escaping:

Scenario 3: HTML content (needs special handling)

<!-- If the variable contains HTML content, handle it according to the situation -->
<!-- Case 1: the HTML comes from user input, so it must be escaped -->
HTML submitted by the user: {$userHtml|escape}

<!-- Case 2: the HTML is system generated and needs to be rendered -->
System-generated HTML: {$systemHtml}
<!-- Note: make sure the content of $systemHtml is safe -->

Best practices:

Escaping Implementation

The escaping feature is provided by the filters plugin:

// Load the filters plugin
require_once 'plugins/filters.php';

// Or load it through the builtin plugin
require_once 'plugins/builtin.php';

How escaping is implemented:

// Internal implementation
htmlspecialchars($var, ENT_QUOTES, 'UTF-8')

Security Recommendations

  1. User input must be escaped:

    <!-- ✅ Correct: escape user input -->
    {$userInput|escape}
    
    <!-- ❌ Wrong: do not leave user input unescaped -->
    {$userInput}
  2. System content may be left unescaped:

    <!-- ✅ Acceptable: system-generated content -->
    {$systemTitle}
    {$systemDescription}
  3. Handle HTML content with care:

    <!-- ✅ Recommended: escape user HTML into plain text -->
    {$userHtml|escape}
    
    <!-- ⚠️ Careful: system HTML left unescaped (must be safe) -->
    {$systemHtml}
  4. Use filter chains:

    <!-- Multiple filters can be combined -->
    {$username|upper|escape}  <!-- uppercase first, then escape -->
    {$description|truncate:50|escape}  <!-- truncate first, then escape -->

Common Mistakes

❌ Wrong example 1: forgetting to escape user input

<!-- Dangerous: user input left unescaped -->
Username: {$username}
Comment: {$comment}

Risk: if a user enters <script>alert('XSS')</script>, this leads to an XSS attack.

✅ Correct example 1: escaping user input

<!-- Safe: user input escaped -->
Username: {$username|escape}
Comment: {$comment|escape}

❌ Wrong example 2: over-escaping system content

<!-- Unnecessary: system content does not need escaping -->
Title: {$systemTitle|escape}

Explanation: although it causes no security problem, HTML entities (such as &lt;) will be displayed, affecting the visual result.

✅ Correct example 2: leaving system content unescaped

<!-- Correct: system content left unescaped -->
Title: {$systemTitle}

Security Checklist

Best Practices

Development Environment

// The fully open mode (default) may be used for convenient debugging
$GLOBALS['user'] = $user;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

Production Environment

// Recommended: whitelist mode
$GLOBALS['siteConf']['template_vars_mode'] = 'whitelist';
$GLOBALS['siteConf']['template_vars_whitelist'] = ['user', 'data', 'items'];
$GLOBALS['user'] = $user;
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir);

High Security Requirements

// Recommended: explicit passing mode
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
    'user' => $user,
    'data' => $data
]);

Untrusted Template Source

If the template source is untrusted, you must:

  1. Use explicit passing mode:

    $html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [
        'user' => $user
    ]);
  2. Disable PHP code blocks (where possible):

    • Filter the <!--{php}--> syntax during template parsing
    • Or use the template validation mechanism
  3. Strictly validate template paths:

    • Make sure template files are inside the allowed directories
    • Use a whitelist mechanism to restrict which files may be included

Security Checklist

Output Escaping and Static Text

What auto_escape Covers

When $GLOBALS['siteConf']['auto_escape'] = true:

Static Text Preserved Verbatim

Static text in a template is output literally: $total, \n, \t, ${user} and the like are not subject to PHP interpolation or escaping (historical versions handed such text to heredoc interpolation, silently corrupting the content).

Note the exception: the {$var} form is the template variable output syntax (it is interpolated); if you need to output the literal {$ characters in text, use the {echo '{'} combination or reword the copy.

Template Path and Cache Path

Error Pages (V2-10)

With tpl_debug off (production default), fatal error pages for missing templates / syntax errors show only the template name and a generic notice — no deployment absolute paths or compiled-artifact line contents. Full diagnostics go to error_log for operators. For development, enable:

$GLOBALS['siteConf']['tpl_debug'] = true; // error pages keep paths/artifact lines/details
// or define the TPL_DEBUG constant

More Information