Security Guide
This document provides a secure usage guide for the Zandy_Template template engine.
Table of Contents
- Variable Access Security
- Code Execution Security
- Path Security
- HTML Escaping and XSS Protection
- Best Practices
Variable Access Security
Problem Description
⚠️ Important: By default, templates can access all global variables, including system variables and configuration information.
Security Risks
- Variable leakage: templates can access all global variables
- Sensitive information leakage: database connection details, API keys and the like may be exposed
- Variable overriding: variables may be overridden, affecting program logic
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:
- Balances security and ease of use
- Only the specified variables can be accessed by the template
- Recommended for production
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:
- Most secure, with full control over variable access
- Does not rely on global variables
- Suited to scenarios with high security requirements
Security Recommendations
- Development environment: the fully open mode (default) may be used for convenient debugging
- Production environment: whitelist mode or explicit passing mode is recommended
- High security requirements: use explicit passing mode for full control over variable access
- 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:
<!--{php}-->...<!--{/php}-->- executes arbitrary PHP code<!--{set ...}-->- sets variables, and can execute code<!--{include ...}-->- includes PHP files
Security Risks
- Arbitrary code execution: templates can execute arbitrary PHP code
- System access: can access the file system, the database and more
- Data leakage: sensitive files can be read
Security Recommendations
Trusted template source:
- If the templates are written by developers, these features may be used
- Make sure template file permissions are correct
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
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:
- Enabling a plugin means trusting its code: only load plugins from trusted sources; never load plugin files uploaded by users or writable by low-privilege roles.
- Plugins must not splice template arguments into PHP expressions raw: when a filter
or directive handler treats an attribute value/argument as an expression, it must call
Zandy_Template::checkExpressionAllowed($expr, $line)first to reuse the core superglobal / dangerous-construct / policy checks, then splice. - Dynamic file paths produced by plugins need the same boundary checks
(
isTemplatePathInTplDir()/isCachePathSafe()); do not assume the sandbox covers them.
// 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 noticePath Security
Protection Mechanism
The template engine automatically validates:
- ✅ The template directory must be inside
tplBaseDir - ✅ The cache directory must be inside
tplCacheBaseDir - ✅ Path traversal attacks are prevented (checked with
realpath())
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
- Configure the correct paths:
- Make sure
tplBaseDirandtplCacheBaseDirare configured correctly - Use absolute paths to avoid relative path problems
- Make sure
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.
File permissions:
- Template files: read-only permission
- Cache directory: writable permission, but restrict access
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:
- Default behavior: no escaping (keeps backward compatibility)
- Escaping method: add the
|escapemodifier manually when escaping is needed - Syntax:
- Escaped:
{$var|escape}→htmlspecialchars($var, ENT_QUOTES, 'UTF-8') - Not escaped:
{$var}→$var
- Escaped:
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:
- User input may contain malicious scripts (such as
<script>alert('XSS')</script>) - Without escaping this leads to XSS attacks
- After escaping:
<script>alert('XSS')</script>(safe)
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:
- The content is generated by the system and does not come from user input
- The content has already been validated and sanitized
- The content source is fully trusted
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:
- If the HTML comes from user input, it must be escaped (shown as plain text)
- If the HTML is system generated and needs to be rendered, it may be left unescaped (but the content must be safe)
- If users are allowed to submit HTML, process it with an HTML sanitizing library (such as HTMLPurifier) before output
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
User input must be escaped:
<!-- ✅ Correct: escape user input --> {$userInput|escape} <!-- ❌ Wrong: do not leave user input unescaped --> {$userInput}System content may be left unescaped:
<!-- ✅ Acceptable: system-generated content --> {$systemTitle} {$systemDescription}Handle HTML content with care:
<!-- ✅ Recommended: escape user HTML into plain text --> {$userHtml|escape} <!-- ⚠️ Careful: system HTML left unescaped (must be safe) --> {$systemHtml}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 <) will be displayed, affecting the visual result.
✅ Correct example 2: leaving system content unescaped
<!-- Correct: system content left unescaped -->
Title: {$systemTitle}Security Checklist
- Is all user input escaped with
|escape? - Is all data submitted through forms escaped?
- Are URL parameters and cookie data escaped?
- Is user data stored in the database escaped when output?
- Is HTML content handled according to its source (user input escaped, system generated may be left unescaped)?
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:
Use explicit passing mode:
$html = Zandy_Template::outString('template.htm', $tplDir, $cacheDir, false, [ 'user' => $user ]);Disable PHP code blocks (where possible):
- Filter the
<!--{php}-->syntax during template parsing - Or use the template validation mechanism
- Filter the
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
- Does production use whitelist mode or explicit passing mode?
- Are template file permissions correct (read-only)?
- Are cache directory permissions correct (writable but access restricted)?
- Is the template path configuration correct?
- Are PHP code blocks disabled if the template source is untrusted?
- Are
includeTemplate()orgetTemplateVars()used instead of a directextract($GLOBALS)?
Output Escaping and Static Text
What auto_escape Covers
When $GLOBALS['siteConf']['auto_escape'] = true:
- Automatically escaped: variable output syntax such as
{$var}and{$var|upper}(only braces starting with{$) - Not escaped:
{echo ...},{LANG key},{CONSTANT},<!--{php}-->blocks, and sub-template output from include (theautoescapecontext block is the exception:{LANG}andtransoutput inside it are context-escaped, and an explicit|escapeis not escaped a second time) - Unaffected: ordinary curly braces in CSS/JS (
.a{color:red},{a:1})—auto_escape only recognizes the{$prefix
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
- Template names undergo traversal validation (components such as
../are rejected), but a whitelist routing map is still recommended rather than concatenating request parameters directly into the template file name - Before any filesystem call, template names reject NUL bytes and names longer than 4096 bytes (PHP 8 throws
ValueErrorfor paths containing NUL); directory/cache paths are subject to the same limits - HTTP_HOST is sanitized against a whitelist before being joined into the compiled cache subdirectory; in production it is recommended to also
pin the Host at the web server layer (such as an Nginx
server_namecheck) or define aPROJECT_NAMEconstant - A
$cacheDirpassed explicitly must be inside thetplCacheBaseDirconfiguration directory (the boundary check is enforced) - Engine-created cache directories are 0755 and cache files 0644 (earlier versions used 0777); temporary files use
tempnam()random names inside the target directory and are re-checked to not be symlinks before writing
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 constantMore Information
- Usage Guide - Detailed usage instructions
- API Reference - Complete API documentation
- Syntax Reference - Complete template syntax
- Performance Optimization Guide - Performance optimization tips and best practices