When building a website, ensuring the security of the content, especially the prevention of cross-site scripting (XSS) attacks, is a crucial factor.AnQiCMS (AnQiCMS) provides powerful tools at the template level to manage the escaping of HTML content, thereby effectively protecting the website and its users.Understanding how to safely handle HTML code in templates is essential knowledge for every Anqi CMS user when conducting content operations and template development.

The default security mechanism of the Anqi CMS template

The Anqi CMS template engine adopts a design philosophy similar to Django, which means it defaults to enabling automatic escaping (Auto-escaping) functionality.This is a very important security feature. When we use double curly braces directly in the template{{ 变量名 }}When outputting content, the template engine will automatically convert HTML special characters (such as<,>,&,",') to their corresponding HTML entities.

For example, if a variableuser_inputContains malicious HTML code, such as<script>alert('XSS攻击');</script>When you output it like this in the template:

<p>用户评论:{{ user_input }}</p>

Anqi CMS will escape this code into:

<p>用户评论:&lt;script&gt;alert(&#39;XSS攻击&#39;);&lt;/script&gt;</p>

This will display the browser as plain text, not executing JavaScript code, thereby effectively preventing XSS attacks.This default mechanism is the first line of defense that Anqicms provides for website security, greatly reducing the risk of security vulnerabilities caused by negligence.

When do you need to force non-escaping of HTML content?

Although automatic escaping ensures security, in certain specific scenarios, we may need to display content that has been confirmed safe and contains HTML tags.For example, website administrators write article details, product descriptions, or some strictly reviewed custom HTML fragments through the rich text editor in the background.If this content is also escaped, the original formatting and style will be lost, resulting in poor display.

In this case, we can use|safea filter to explicitly inform the template engine that this content is 'safe' and does not require HTML escaping.

<div>文章内容:{{ archiveContent|safe }}</div>

HerearchiveContentVariables usually come from the background rich text editor. By adding|safe,archiveContentof<p>,<strong>,<a>HTML tags are parsed and rendered correctly by the browser, rather than displayed as plain text.

Important reminder: |safeThe filter must be used carefully. Once you have used|safe, you have entrusted the responsibility of content security to yourself. Please make sure to use|safeThe content source is absolutely可信, and it has been thoroughly disinfected and verified before entering the database storage to prevent any potential malicious code injection.

When do you need to manually escape HTML content or control the escaping area?

In most cases, due to the default automatic escaping behavior of AnQi CMS, we rarely need to use it manually|escapeThe filter is used to enforce escaping. In fact, if you use it in the default auto-escaping environment|escapeit may result in double escaping of the content, producing unnecessary HTML entities.

|escapeThe filter is mainly used when you explicitly turn off automatic escaping (such as by{% autoescape off %}After labeling, you also want to escape a specific variable. Or, it can also be used to demonstrate the effect of HTML escaping.

AnQi CMS also provides{% autoescape %}The tag controls the automatic escaping behavior of an area in the template.

{# 默认行为下,以下内容会被自动转义 #}
{{ user_comment_safe }}

{% autoescape off %}
    {# 在这个区块内,所有变量输出都将不再自动转义 #}
    <p>管理员输入的HTML:{{ admin_html_content }}</p>
    {# 如果这里admin_html_content是用户输入,则需手动转义 #}
    <p>强制转义的用户输入:{{ user_input_again|escape }}</p>
{% endautoescape %}

{% autoescape on %}
    {# 在这个区块内,即使之前关闭了,现在又会重新开启自动转义 #}
    <p>重新开启自动转义:{{ another_user_input }}</p>
{% endautoescape %}

In cases where variables need to be inserted into JavaScript code blocks, it is especially important to be aware of XSS risks. Anqi CMS provides|escapejsFilter. It escapes special characters in strings to make them safe for JavaScript formatting, such as escaping single quotes to\'and newline characters to\nTo avoid breaking JavaScript syntax or injecting malicious code.

<script>
    var data = '{{ some_variable|escapejs }}';
    alert(data);
</script>

Handle rich text content and Markdown rendering

The AnQi CMS backend content management supports Markdown editor.When the content of the article we publish is written in Markdown format, the template engine needs to convert it to HTML when displaying it.The document mentions,archiveDetailTags will automatically convert Markdown to HTML after the Markdown editor is turned on. If you want to manually control the conversion, you can userenderParameter.

For example, if you have a variablemarkdown_textContains Markdown formatted content, do you want to render it as HTML and display it?

<div>
    {{ markdown_text|render|safe }}
</div>

here,|renderThe filter is responsible for parsing Markdown text and converting it to HTML format.Note:The HTML content converted still needs to be marked as safe|safebecause it is already in HTML format, if missing|safeThese HTML tags will be processed again by the default automatic escaping mechanism, causing the HTML to be displayed as plain text.

**Practical and Security Suggestions

  1. Trust the default escaping:Trust the default automatic escaping mechanism of Anqi CMS. It can effectively prevent XSS attacks in most cases.
  2. Use with caution.|safe:Only when you are absolutely sure of the safety of the content source, and it has been verified and purified by the server, should you use|safethe filter. This is usually applicable to rich text content published by backend administrators.
  3. Server-side validation and filtering:Regardless of any content submitted by the user, strict input validation, filtering, and sterilization should be performed on the server side before the data is saved to the database.This includes limiting HTML tags, attributes, and even using a whitelist mechanism to ensure only safe HTML elements are allowed.
  4. |escapejsApplied to the JavaScript context:When you need to<script>Be sure to use inside the tag when inserting any dynamic data:|escapejsuse a filter to prevent JavaScript injection.
  5. Understanding|renderwith|safethe combination of:For Markdown or other content that needs to be converted to HTML, remember to use|renderthe conversion first, then|safeto allow the rendering of HTML content.

By mastering the strategy of escaping and unescaping HTML content in the Anqi CMS template, you will be able to better balance the richness and security of website content, providing users with a stable and protected browsing environment.


Frequently Asked Questions (FAQ)

Q1: I edited an article using a rich text editor in the background, which contained images and paragraphs, but when displayed on the front end, I saw that<p>/<img>These tags instead of the rendered effect, what's the matter?A1: This situation usually occurs because you did not use|safeFilter. The AnQi CMS defaults to all.{{ 变量 }}The content output is HTML escaped to prevent XSS attacks.The content generated by the rich text editor already contains HTML tags, and you need to explicitly inform the system in the template that these contents are safe and do not need to be escaped.Try to modify your output code content to{{ archiveContent|safe }}(SupposearchiveContentIt is the variable for the article content.

Q2: Can the default automatic escaping mechanism of Anqi CMS completely prevent XSS attacks? Do I still need to filter the content submitted by users on the server side?A2: The default automatic escaping mechanism of Anqi CMS can effectively prevent most common reflected and stored XSS attacks because it prevents the direct execution of malicious scripts.However, it is strongly recommended to validate and filter all user submitted content on the server side in order to build a more robust system.Template escaping is a protection at the output stage, while server-side filtering is a protection at the input stage. Using both together can provide a more comprehensive level of security, such as restricting allowed HTML tags, cleaning up unsafe attributes, and so on.

Q3: If I obtain a segment of HTML code from an external source, how can I display it in an Anqi CMS template while ensuring its safety?A3: If the source of the external HTML code is very trustworthy and you have confirmed that it does not contain malicious content, you can use it directly|safeFilter. But a safer approach is to first strictly sanitize this external HTML on the server side before saving it to the database or rendering it to the page (for example, using special