When building a website with AnQiCMS, we often need to fill dynamic content into the page template, which includes text that may come from user input.However, if not handled properly, the user input content may be exploited by malicious attackers, planted with malicious scripts, thereby triggering cross-site scripting (XSS) attacks.XSS attacks can steal user data, alter page content, even hijack user sessions, and cause serious harm to websites and users.
AnQiCMS is a content management system that pays attention to security, and it provides us with strong protection mechanisms at the template engine level, helping us effectively avoid such risks.Understanding and correctly applying these mechanisms is a key step in ensuring website security.
The default security mechanism of AnQiCMS template engine
AnQiCMS uses a template engine syntax similar to Django, one of its core advantages is the defaultAutomatic escapingFunction. This means that when we output the variable to an HTML page, the template engine will automatically recognize and convert special characters in the content.For example, commonly used HTML tags</>/&/"/'& characters, in the output they will be 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 displayed as plain text and are not parsed by the browser as executable code. For example, if a malicious user enters comments.<script>alert('XSS');</script>In automatic escaping, what is displayed on the page will be<script>alert('XSS');</script>The browser will treat it as a plain string, thus effectively preventing the execution of the script.
When is manual escaping required (and how to do it safely?)
Although automatic escaping provides basic protection, but in certain specific scenarios, we may need to manually adjust the escaping behavior.This usually happens when we need to insert legitimate, trusted HTML or JavaScript code into a page.The 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 allows administrators to publish articles with content generated by a rich text editor, which already includes valid HTML tags such as paragraphs, images, links, and so on.In this case, if automatic escaping is still performed, then these valid HTML tags will also be converted to entities, causing the page to display confusion.
At this point, you can usesafeThe filter tells the template engine that the content of the variable is 'safe', and it does not need to be escaped. It can be output directly as HTML code.
Usage example:If you are inarchiveDetailRetrieve the content of the article from the tag and output it to the page:
{# 默认会自动转义,导致HTML标签无法正常渲染 #}
<div>{{ article.Content }}</div>
{# 使用 |safe 过滤器告知模板引擎此内容是安全的HTML,无需转义 #}
<div>{{ article.Content|safe }}</div>
ortag-/anqiapi-archive/142.htmlExample of the content of the Chinese document:
<div>文档内容:{% archiveDetail archiveContent with name="Content" %}{{archiveContent|safe}}</div>
Important reminder: safeThe filter is a double-edged sword. Only when youCompletely trustThe content source must be confirmed as free of malicious scripts before it can be used. Misuse will open the door to XSS attacks. Please be sure to carefully evaluate its use.safeThe scenario of the filter. Any data coming from untrusted users or external uncontrollable sources should be avoidedsafe.
2. Handling data in JavaScript:escapejsFilter
Be especially careful when embedding server-side data into client-side JavaScript code.The HTML escaping is not enough to completely prevent JavaScript injection.For example, directly inserting user input that contains quotes into a JavaScript string can cause the string to close prematurely, thereby executing malicious code.
escapejsA filter is specifically used to escape strings, making them safe to embed in JavaScript strings, data attributes, or event handlers. It converts special characters in JavaScript (such as quotes, slashes, newline characters, etc.) to\uXXXXFormatted Unicode escape sequences, ensure they are parsed as part of the string, not code logic.
Usage example:Suppose you want to use a username variableuser.NamePass to the JavaScript script:
<script>
var userName = "{{ user.Name|escapejs }}"; // 使用 escapejs 进行转义
alert('欢迎回来,' + userName + '!');
</script>
In this example, evenuser.NameContaining such as'; alert('恶意脚本') //malicious strings,escapejsIt will also escape them as\u0027\u003B\u0020alert(\u0027\u6076\u610F\u811A\u672C\u0027)\u0020//EnsureuserNameThe value of the variable remains a string, it will not be broken.alert()The structure of the function.
3. Explicit control of automatic escaping:autoescapeTag
In addition to the filter, AnQiCMS also providesautoescapeTags to control the automatic escaping behavior of template code blocks. You can choose to enable (on) or disable (off) the automatic escaping of a certain area.
Usage example:
{# 默认情况下所有内容都会被自动转义 #}
{{ "<script>alert('Hello');</script>" }}
{% autoescape off %}
{# 在这个代码块内,自动转义被关闭,HTML内容会按原样输出 #}
{{ "<p>这是一个未转义的段落。</p>" }}
{% endautoescape %}
{% autoescape on %}
{# 在这个代码块内,自动转义被强制开启 #}
{{ "<p>这个段落会再次被转义。</p>" }}
{% endautoescape %}
autoescape offthe use of the tag withsafeFilter similar, be highly vigilant. It is usually used to import known safe, precompiled HTML fragments.
Summarize **practice
- Trust default escaping:Unless there is a clear reason and conclusive 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 the output when you are sure that the 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 in JavaScript must be
|escapejsescaped using a filter to prevent JavaScript injection. - Minimize
autoescape offScope:If indeed it is necessary to disable automatic escaping, please use{% autoescape off %}tags to limit the scope of action to the smallest code block possible. - Backend validation and filtering:Although escaping at the template layer is crucial, strict validation and filtering of all user input by the backend is still an indispensable safety 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 a safer browsing experience for your website and users.
Frequently Asked Questions (FAQ)
Q1: Why do the HTML tags (such as<p>/<img>) in my article content not display normally, but are output as plain text instead?
A1: This is very likely because the template engine's automatic escaping mechanism is in effect.For safety reasons, all variables output to the page are automatically escaped, converting HTML special characters to entities.If your article content is edited through a rich text editor, and you trust the safety of the output HTML structure, you need to use|safeFilter, for example{{ article.Content|safe }}Make sure the content source is reliable to avoid introducing XSS risks.
Q2: I used in JavaScript code:{{ user.input }}Is it safe to display the user submitted text?
A2: Use directly{{ user.input }}In JavaScript it isUnsafeAlthough the default HTML automatic escaping can prevent the execution of scripts in the HTML structure, it cannot prevent the construction of malicious code in JavaScript strings.For example, ifuser.inputThe value is'; alert('XSS'); var x='This will break your JavaScript syntax and execute malicious scripts. In this case, you should use|escapejsa filter 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 is the difference between filters? Which one should I use?
A3:|safeFilters are used todisableIt escapes, telling the template engine that this content is safe HTML, which can be output directly without converting special characters. And|escapeThe filter isExplicitly executedEscape operation, converts HTML special characters to entities. Since the AnQiCMS template engine is automatically escaped by default, you usually do not need to use it extra.|escapeThe filter, because the variable output is automatically escaped. Only use unescaped HTML (and content is trusted) when you are sure.|safe; Otherwise, relying on the default automatic escaping is sufficient.