In website operation, the security of output content is crucial.Especially when displaying user-submitted data or information obtained from external sources, if not properly processed, websites are easily susceptible to cross-site scripting attacks (XSS) and other threats.AnQiCMS as a content management system that focuses on security provides a powerful escape mechanism in the template rendering layer, whereescape/eandescapejsThese filters are the key tools to ensure output safety.

The template engine of AnQiCMS has drawn inspiration from Django, which means it enables automatic escaping by default. When you output variables in the template, for example{{ user_name }}The system will automatically convert special characters in HTML (such as</>/&/"/') to the corresponding HTML entities (such as&lt;/&gt;/&amp;/&quot;/&#39;Thus, it effectively prevents malicious HTML or JavaScript code from being parsed and executed by the browser. This default automatic escaping mechanism is the first line of defense for website security.

HTML context safe escaping:escapeandeFilter

Even with default automatic escaping, in certain specific scenarios, we still need to use it explicitly.escapeoreFilter. These two filters are equivalent,eIsescapeis an abbreviation alias, their function is to force the escaping of HTML special characters in strings.

  • FeatureThey will convert the following five HTML special characters to their corresponding HTML entities:
    • <to&lt;
    • >to&gt;
    • &to&amp;
    • "to&quot;
    • 'to&#39;
  • Application scenario:
    1. Clear intention: When you want to explicitly express that the variable needs to be HTML-escaped, even if it has been escaped by default, using it explicitly can enhance the readability and maintainability of the code.
    2. Local escape auto-recovery after partial closureIn some special cases, you may need to use{% autoescape off %}Temporarily disable the automatic escaping feature of a template block (for example, output a known safe HTML structure). At this point, if some part of the block still needs to be escaped, it can be done manually using|escapeor|eThe filter ensures the safe output of this part of the content.
    3. Prevent secondary parsingIn some complex rich text processing workflows, if the data may be parsed multiple times,escapeEnsure that special characters are always output to HTML in entity form to avoid unexpected secondary parsing vulnerabilities.

For example, if you have a variableuser_comment, its value might be<script>alert('xss')</script>恶意评论in the HTML context{{ user_comment|escape }}The output will be&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;恶意评论, the browser will treat it as plain text instead of executing the script.

Safe escaping in JavaScript context:escapejsFilter

When we need to embed dynamic data from the AnQiCMS template into JavaScript code,escapejsThe filter is specifically designed for this security measure. Directly inserting unprocessed variables into JavaScript code can easily lead to JavaScript injection attacks, for example, by inserting malicious code through user input enclosed strings.

  • Feature:escapejsThe filter will convert special characters in JavaScript code (including carriage returns, line feeds, various quotes, and backslashes, etc.) to\uxxxxThe Unicode escape sequence, make sure these characters are safely interpreted in JavaScript strings or code blocks. It will escape characters that are not alphanumeric (a-zA-Z), spaces, and backslashes/Escape all characters outside of it.
  • Application scenario:
    1. Embed dynamic data in JavaScript strings.When you need to insert the value of a backend variable as part of a JavaScript string, for examplevar username = '{{ user_name|escapejs }}';.
    2. Insert dynamic data into HTML event attributesIn HTML tags,onclick/onmouseoverFor example, insert dynamic data in the event handling function<button onclick="doSomething('{{ item.id|escapejs }}')">点击</button>.
    3. Prevent JavaScript injection: By escaping all characters that may cause ambiguity into harmless forms\uxxxx,escapejsEnsured that even malicious code **in**, can only be part of a normal string and cannot be executed by the JavaScript engine.

For example, if a variableproduct_namehas a value of"手机",价格:100Directly inserting JavaScript may cause syntax errors or injection. Instead, use{{ product_name|escapejs }}after, the output may become手机\x22,\u4ef7\u683c:100This will be safely parsed as a string in JavaScript.

Disable escaping:safeFilter

The opposite of the above escaping filter issafeThe filter. When you confirm that the content of a variable is completely trusted and contains HTML or JavaScript code that you want the browser to parse and execute directly, you can use it.|safeDisable automatic escaping.

  • Feature:safeThe filter tells the template engine that the value it applies is considered 'safe' and does not require any escaping; it can be output in its original form directly.
  • Risk alert:Please use with cautionsafefilter.Only when you can fully control and trust the source of the variable's content can you use it. Once user input or data from an unreliable source is incorrectly marked assafeThis could lead to serious XSS vulnerabilities. For example,{{ trusted_html_content|safe }}.

Summary

Provided by AnQiCMSescape/eandescapejsThe filter is a powerful guarantee for building a secure website. Understanding and properly using these filters, combined with the default automatic escaping mechanism of AnQiCMS, can greatly reduce the risk of the website being attacked by XSS attacks.When processing any output that may contain user input or external data, always prioritize security: The AnQiCMS is used by default for automatic escaping, and explicit escaping is required in the HTML context.escapeoreIn the context of JavaScript, it usesescapejsFor cases where it is indeed necessary to output original HTML, consider it carefully.safefilter.


Frequently Asked Questions (FAQ)

Q1: The AnQiCMS template defaults to automatically escaping HTML, do I still need to use it?escapeorefilter?

A1: In most cases, if you are only outputting variables within HTML tags or text content, the default automatic escaping is already safe enough, and you do not need to use it additionallyescapeoreIf you use it in a template area{% autoescape off %}Explicitly disabling automatic escaping, while a variable indeed needs HTML escaping, in which case you need to use it manually|escapeor|eEnsure its security. Moreover, explicitly using these filters can sometimes improve the readability of the code, clearly expressing the developer's intention regarding the content security handling.

Q2: Do I use to directly output user input content in an HTML page?escapejsCan I?

A2: No.escapejsThe filter is specifically used in the JavaScript code context (such as<script>within a tag or HTML element'son*It escapes the content to be recognized by JavaScript in the event attribute. It will output the variable safely\uxxxxformat. If it is used in ordinary HTML text contentescapejs, the browser will display these directly\uxxxxEscape characters, rather than the original text you expect, and also cannot provide the correct HTML context escaping. In HTML content, the default automatic escaping of AnQiCMS is sufficient, or use it when automatic escaping is disabledescapeore.

Q3: UsesafeWhat are the risks of the filter? When should I use it?

A3:safeThe filter indicates that the AnQiCMS template engine should not escape the values applied, outputting them in their original form. The main risk is that if the value contains malicious HTML (such as<script>Tags) or JavaScript code, they will be executed directly by the browser, leading to cross-site scripting (XSS) attacks. You should only use them in the following casessafe: When youAbsolutely certainThe content source of this variable is completely trustworthy, and it indeed contains the legitimate HTML code that you want the browser to parse and render.For example, backend processed, administrator published rich text content, or HTML fragments generated and verified internally by the system.Do not directly use content from user input or any untrusted source|safeOutput.