jinja2-autoescape

Try in Playground
python-securitySecurityCritical

0

No tags

CWE-94

By default, jinja2 is not autoescaping. This can lead to XSS attacks. The autoescape parameter should always be True.

Learn More

  • OWASP XSS
  • CWE-94 - Improper Control of Generation of Code

Ast Rule: function call


jinja2-autoescape

How to write a rule
function visit(node, filename, code) {
  
  if(!node.functionName || !node.context) {
    return;
  }
  
  if (node.functionName.value === "Environment") {
    
    const useJinja2Environment = node.context.imports.filter(i => i.elements && i.pkg).filter(i => i.elements.map(e => e.name.value).includes("Environment") && i.pkg.value === "jinja2").length > 0;
	
    if(useJinja2Environment) {
      if(!node.arguments || !node.arguments.values){
        return;
      }
      
      const hasAutoEscape = node.arguments.values.filter(a => a.name && a.name.value == "autoescape").length > 0;
			
      if(hasAutoEscape){
      	const arg = node.arguments.values.filter(a => a.name && a.name.value == "autoescape")[0];
        if(arg.value.value === "False"){
             const error = buildError(arg.start.line, arg.start.col, arg.end.line, arg.end.col, "autoescape=False leads to XSS issues", "CRITICAL", "SECURITY");

             const edit = buildEditUpdate(
               arg.value.start.line, arg.value.start.col,
               arg.value.end.line, arg.value.end.col, "True")
    				const fix = buildFix("use autoescape True", [edit]);
    				addError(error.addFix(fix));
        }
      }
    }
  }
  
}

autoescape-false.py

Expected test result: has error

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader("yourapp"),
    autoescape=False
)

autoescape-true.py

Expected test result: no error

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader("yourapp"),
    autoescape=select_autoescape()
)

autoescape-select.py

Expected test result: no error

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader("yourapp"),
    autoescape=select_autoescape()
)
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Explore
  • Cookbooks
  • Playground
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.