In the template development of AnQi CMS, we often encounter situations where we need to handle special characters or HTML content.The system provides various filters to help us control the display of content more flexibly.addslashesfilters and|safeThe filters are all related to character processing, but their mechanisms and application scenarios are quite different.Understanding their specific functions and performance when used simultaneously is crucial for ensuring the security and correct rendering of website content.

Understand the default security mechanism of the Anqi CMS template

Firstly, we need to know that Anqi CMS is developed based on Go language, and its template engine has taken full consideration of security from the design.This means that when you output a variable that may contain HTML tags or JavaScript code directly to the template, the system will automatically escape these special characters by default.<script>The string of tags, as output without processing, will be displayed in the browser at the end&lt;script&gt;This automatic escaping mechanism is the first line of defense against security vulnerabilities such as cross-site scripting (XSS).

addslashesFilter: Add 'umbrella' to special characters

addslashesThe filter, as the name implies, mainly serves the purpose of adding predefined characters (single quotes) to strings', double quotes)"backslash\as well as NULL character) add a backslash before it.This is usually done to ensure that special characters are correctly identified as literals rather than code structures when strings are output as part of JavaScript variables or regular expressions in certain specific scenarios.

Imagine we have a string我喜欢'AnQiCMS'。If we pass it throughaddslashesAfter filtering, the output will be:

{{ "我喜欢'AnQiCMS'"|addslashes }}

At this point, the output content will become我喜欢\'AnQiCMS'However, since the default HTML escaping mechanism of the template is still active, the final effect seen by the browser is我喜欢&#39;AnQiCMS&#39;because the newly added backslash has also been escaped&#92;Here,addslashesJust modified the string at the logical level, but the security protection at the HTML level still exists.

|safeFilter: Breaking the 'seal' of HTML escaping.

Withaddslashesdifferent,|safeThe function of the filter is to explicitly tell the security CMS template engine: 'This content is safe, please do not perform HTML escaping and output it directly as raw content.'This filter is typically used to output content that you are sure has been processed, or is itself HTML code and needs to be parsed correctly by the browser, such as content retrieved from a rich text editor.

If you have a variable containing HTML tagsunsafe_htmlwith the value<script>alert('xss')</script>and you want it to be rendered as actual HTML:

{{ unsafe_html|safe }}

Now, the browser will directly parse and try to execute this JavaScript code. Because of|safeThe filter has the powerful ability to remove default HTML encoding, so we must be extremely careful in its use to ensure that the content being processed is indeed trustworthy and harmless to avoid introducing security risks.

addslashesWith|safeWhat is the order of use and how effective is it?

Whenaddslashesfilters and|safeThe filters are applied to the same variable in the order from left to right. This is an ordered operation, not a priority competition.

In particular, the process is as follows:

  1. addslashesFirst execute:The original string content of the variable will first pass throughaddslashesFilter processing, where predefined special characters (such as single quotes, double quotes, backslashes) are escaped with a backslash.
  2. |safeExecuted later:Next,|safeThe filter will act onAlready beenaddslashesProcessed string. Due to|safeThe function of this is to disable subsequent HTML escaping, so the string containing the new backslash will be output directly to the HTML without any HTML escaping.

Let us understand intuitively through an example:

Suppose we have a string variable.my_string = "这是一个'测试'字符串,包含\\反斜杠和\"双引号\"".

  1. Only useaddslashes:

    {{ my_string|addslashes }}
    

    Output effect (actually displayed in the browser):这是一个&#39;测试&#39;字符串,包含&#92;反斜杠和&#92;&quot;双引号&#92;&quot;Explanation:addslashesAdded a backslash, and then the default template mechanism escapes all HTML special characters (including the backslash itself).

  2. Only use|safe:

    {{ my_string|safe }}
    

    Output effect (actually displayed in the browser):这是一个'测试'字符串,包含\反斜杠和"双引号"Explanation:|safeDisabled HTML escaping, the original string content is output directly.

  3. Used simultaneouslyaddslashesand|safe:

    {{ my_string|addslashes|safe }}
    

    Output effect (actually displayed in the browser):这是一个\'测试\'字符串,包含\\反斜杠和\"双引号\"Explanation:addslashesConvert the string to这是一个\'测试\'字符串,包含\\反斜杠和\"双引号\". Then,|safeAffects this processed string, indicating that the template engine should output directly without performing HTML escaping. Therefore, we see the literal backslashes in the string.

Conclusion:addslashesThe filter is responsible for modifying the content of strings, while|safeThe filter controls whether the template engine performs HTML escaping.They have no priority conflict, but are executed in the order of the pipe (pipe), with the output of the previous filter as the input of the next filter.The final effect depends on the superposition of these two operations.

choices in practical applications

In most cases, you are unlikely to need to use both these filters to handle regular text content.

  • If you needoutput some HTML content generated by a rich text editor, and make sure that its HTML tags can be parsed by the browser, then just use|safeBut please make sure that these HTML contents are trusted.
  • If you need toembed dynamically generated strings in JavaScript codeAnd make sure that the quotes, backslashes, and other special characters in the string do not break the JS syntax, then you may needaddslashesto preprocess the string, then consider whether you need|safeThis depends on how you ultimately embed JS code into HTML (for example, if the JS code itself is part of thescripttag)|safeIt is required; if the JS code is loaded from an external file, then HTML escaping is usually no longer an issue).

Remember, security is always the first priority.|safeis a powerful tool, but it also comes with corresponding risks. Be sure to thoroughly verify and clean the content source before using it.


Common Questions (FAQ)

  1. What is the default HTML escaping mechanism of the Anqi CMS template? Why is there such a mechanism?The template engine of AnQi CMS defaults to escaping all output variable content. This means that, like</>/&/'/"Such special characters will be converted to their corresponding HTML entities (for example,)<Changes to&lt;)。The main purpose of this mechanism is to prevent cross-site scripting attacks (XSS), ensuring that malicious HTML or JavaScript code contained in user or external data will not be executed by the browser on your website, thereby enhancing the security of the website.

  2. When should I use|safeFilter, what are the risks?You usually use in two cases|safeFilter: First, when you know for sure that the output string contains the HTML content you want the browser to parse (for example, content from a rich text editor on an article detail page); second, when you have already strictly sanitized the string to ensure it does not contain any malicious code.|safeThe risk of it is that it completely disables the HTML escaping protection of the template. If it is|safeThe content processed comes from an untrusted source and contains malicious scripts, which will execute in the user's browser, leading to XSS attacks and severely affecting the security of the website and users.

  3. addslashesFilter can effectively prevent XSS attacks?Cannot.addslashesThe main function of the filter is to add a backslash before specific characters (such as single quotes, double quotes, backslashes, etc.), which is more for maintaining the literal meaning of characters in other programming language environments (such as JavaScript strings) rather than for HTML safe encoding.It does not convert HTML tags to entities, so it cannot prevent XSS attacks directly.To prevent XSS, you should rely on the default HTML escaping mechanism of the template engine, or perform strict validation and sanitization of the content.