When using AnQiCMS to build a website, we often need to fill dynamic content into the page template, which may include text input from users.However, if not handled properly, the content entered by these users may be exploited by malicious attackers, to plant malicious scripts, thereby triggering cross-site scripting (XSS) attacks.XSS attacks can steal user data, tamper with page content, and even hijack user sessions, posing serious threats to websites and users.
AnQiCMS as a content management system that emphasizes security, provides us with powerful protection mechanisms at the template engine level, helping us effectively avoid such risks.Understanding and correctly applying these mechanisms is a crucial step in ensuring website security.
AnQiCMS Template Engine's default security mechanism
AnQiCMS uses a template engine syntax similar to Django, one of its core advantages being the defaultAutomatic escapingFunction.This means that when we output the variable to the HTML page, the template engine will automatically recognize and convert special characters in the content.</>/&/"/'Characters such as these, when output, are automatically converted to HTML entities, such as</>/&/"/'.
This default automatic escaping behavior is the first and most important line of defense against XSS attacks. It ensures that any content submitted by the user, even if it contains malicious<script>Tags or HTML structures are also treated as plain text and are not parsed as executable code by the browser. For example, if a malicious user enters<script>alert('XSS');</script>In the case of automatic escaping, what is displayed on the page will be<script>alert('XSS');</script>The browser will treat it as a plain string only, thereby effectively preventing the execution of the script.
When do you need to manually intervene in escaping (and how to do it safely)?
Although automatic escaping provides basic protection, in some specific scenarios, we may need to manually adjust the escaping behavior.This usually occurs when we need to insert legitimate,可信 HTML or JavaScript code into the page.AnQiCMS Template Engine provides specific filters and tags for this.
1. When the content is known to be safe HTML:safeFilter
Imagine if your website allowed administrators to post articles with content generated by a rich text editor, which already includes valid HTML tags such as paragraphs, images, links, etc.In this case, if automatic escaping is still performed, these valid HTML tags will also be converted to entities, causing the page to display incorrectly.
At this point, you can usesafeThe filter tells the template engine that the content of this variable is 'safe' and does not need to be escaped, and can be output directly as HTML code.
Example Usage:If you havearchiveDetailLabel the article content and output it to the page:
{# 默认会自动转义,导致HTML标签无法正常渲染 #}
<div>{{ article.Content }}</div>
{# 使用 |safe 过滤器告知模板引擎此内容是安全的HTML,无需转义 #}
<div>{{ article.Content|safe }}</div>
Or, intag-/anqiapi-archive/142.htmlAn example of document content in Chinese:
<div>文档内容:{% archiveDetail archiveContent with name="Content" %}{{archiveContent|safe}}</div>
Important reminder: safeA filter is a double-edged sword. Only when youFully trustedContent source, and it can be used only when it is confirmed that it does not contain any malicious scripts. Misuse will open the door to XSS attacks. Please be sure to evaluate the use with caution.safeThe scenario of the filter. Any data from untrusted users or uncontrollable external sources should be avoidedsafe.
2. Handling data in JavaScript:escapejsFilter
When embedding server-side data into client-side JavaScript code, it is necessary to be particularly careful.The HTML escaping is not sufficient to prevent JavaScript injection completely.For example, directly inserting user input enclosed in quotes into a JavaScript string may cause the string to close prematurely, thereby executing malicious code.
escapejsThe filter is specifically used to escape strings so that they can be safely embedded in JavaScript strings, data attributes, or event handlers. It converts special characters in JavaScript (such as quotes, slashes, newline characters, etc.) to\uXXXXThe Unicode escape sequences, ensuring they are parsed as part of the string rather than code logic.
Example Usage:Suppose you want to use a username variableuser.NamePass to JavaScript script:
<script>
var userName = "{{ user.Name|escapejs }}"; // 使用 escapejs 进行转义
alert('欢迎回来,' + userName + '!');
</script>
In this example, evenuser.NameContaining such as'; alert('恶意脚本') //Such malicious strings,escapejsIt will also be escaped as\u0027\u003B\u0020alert(\u0027\u6076\u610F\u811A\u672C\u0027)\u0020//,ensureuserNameThe value of the variable is still a string, it will not damagealert()the structure of the function.
3. Explicit control of automatic escaping:autoescapetags
In addition to filters, AnQiCMS also providesautoescape标签来控制模板代码块的自动转义行为。您可以选择开启 (English)on) 或关闭 (English)off) 某个区域的自动转义。
Example Usage:
{# 默认情况下所有内容都会被自动转义 #}
{{ "<script>alert('Hello');</script>" }}
{% autoescape off %}
{# 在这个代码块内,自动转义被关闭,HTML内容会按原样输出 #}
{{ "<p>这是一个未转义的段落。</p>" }}
{% endautoescape %}
{% autoescape on %}
{# 在这个代码块内,自动转义被强制开启 #}
{{ "<p>这个段落会再次被转义。</p>" }}
{% endautoescape %}
autoescape off标签的使用与safeFilter similar, be highly vigilant. It is usually used to import known safe, precompiled HTML fragments.
Summary**Practice
- Trust default escaping:Unless there is a clear reason and convincing evidence, always let the AnQiCMS template engine execute its default automatic escaping.This is the simplest and most effective way to defend against XSS.
- Use with caution
safe:Only use when you are sure that the output content is strictly validated and safe HTML|safeFilter. For example, content entered by backend administrators through a rich text editor is usually considered trustworthy. - Data processing in the JavaScript environment:Any dynamic data that needs to be embedded into JavaScript must be used.
|escapejsEscape with filters to prevent JavaScript injection. - Minimize.
autoescape offRange:If you indeed need to disable auto-escaping, please use{% autoescape off %}tags to limit the scope of action to the smallest possible code block. - Backend validation and filtering:Although the escaping in the template layer is crucial, the strict validation and filtering of all user input by the backend is still an indispensable security measure.This is a necessary component of multi-level security protection.
By following these principles, you can fully utilize the security features provided by the AnQiCMS template engine, effectively prevent XSS attacks, and provide your website and users with a safer browsing experience.
Common Questions (FAQ)
Q1: Why does the HTML tag (such as ) in my article content not display normally, but is output as text instead?<p>/<img>)没有正常显示,而是原样作为文本输出了?
A1: This is very likely because the automatic escaping mechanism of the template engine is in effect.For security reasons, all variable content output to the page is automatically escaped, converting HTML special characters to entities.|safeFilter, for example{{ article.Content|safe }}Please ensure the content source is reliable to avoid introducing XSS risks.
Q2: I used in JavaScript code{{ user.input }}Display the user-submitted text, is it safe?
A2: Use directly{{ user.input }}In JavaScript isUnsafeEnglish.Although the default HTML auto-escape can prevent the execution of scripts in the HTML structure, it cannot prevent the construction of malicious code in JavaScript strings.user.inputhas a value of'; alert('XSS'); var x='This will break your JavaScript syntax and execute malicious scripts. In this case, you should use|escapejsFilter, such asvar myVar = "{{ user.input|escapejs }}";This will escape special characters in JavaScript, ensuring that the data is safely treated as a string.
Q3:|safefilters and|escapeWhat's the difference between filters? Which one should I use?
A3:|safeFilters are used toDisabledAutomatically escaped, it tells the template engine that this content is safe HTML that can be output directly without converting special characters.|escapeFilters areExplicitly executedEscape operation, converts HTML special characters to entities. Since AnQiCMS template engine is set to auto-escape by default, you usually don't need to use it extra.|escapeFilter, because variables are automatically escaped when output. Only use unescaped HTML (and content is trusted) when you are sure|safe; Otherwise, relying on the default automatic escaping is sufficient.