|
| 1 | +use crate::checkers::ast::Checker; |
| 2 | +use ruff_diagnostics::{Diagnostic, Violation}; |
| 3 | +use ruff_macros::{derive_message_formats, violation}; |
| 4 | +use ruff_python_ast::{self as ast}; |
| 5 | +use ruff_text_size::Ranged; |
| 6 | + |
| 7 | +/// ## What it does |
| 8 | +/// Checks for uses of the `mako` templates. |
| 9 | +/// |
| 10 | +/// ## Why is this bad? |
| 11 | +/// Mako templates allow HTML and JavaScript rendering by default, and are |
| 12 | +/// inherently open to XSS attacks. Ensure variables in all templates are |
| 13 | +/// properly sanitized via the `n`, `h` or `x` flags (depending on context). |
| 14 | +/// For example, to HTML escape the variable `data`, use `${ data |h }`. |
| 15 | +/// |
| 16 | +/// ## Example |
| 17 | +/// ```python |
| 18 | +/// from mako.template import Template |
| 19 | +/// |
| 20 | +/// Template("hello") |
| 21 | +/// ``` |
| 22 | +/// |
| 23 | +/// Use instead: |
| 24 | +/// ```python |
| 25 | +/// from mako.template import Template |
| 26 | +/// |
| 27 | +/// Template("hello |h") |
| 28 | +/// ``` |
| 29 | +/// |
| 30 | +/// ## References |
| 31 | +/// - [Mako documentation](https://www.makotemplates.org/) |
| 32 | +/// - [OpenStack security: Cross site scripting XSS](https://security.openstack.org/guidelines/dg_cross-site-scripting-xss.html) |
| 33 | +/// - [Common Weakness Enumeration: CWE-80](https://cwe.mitre.org/data/definitions/80.html) |
| 34 | +#[violation] |
| 35 | +pub struct MakoTemplates; |
| 36 | + |
| 37 | +impl Violation for MakoTemplates { |
| 38 | + #[derive_message_formats] |
| 39 | + fn message(&self) -> String { |
| 40 | + format!( |
| 41 | + "Mako templates allow HTML and JavaScript rendering by default and are inherently open to XSS attacks" |
| 42 | + ) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/// S702 |
| 47 | +pub(crate) fn mako_templates(checker: &mut Checker, call: &ast::ExprCall) { |
| 48 | + if checker |
| 49 | + .semantic() |
| 50 | + .resolve_call_path(&call.func) |
| 51 | + .is_some_and(|call_path| matches!(call_path.as_slice(), ["mako", "template", "Template"])) |
| 52 | + { |
| 53 | + checker |
| 54 | + .diagnostics |
| 55 | + .push(Diagnostic::new(MakoTemplates, call.func.range())); |
| 56 | + } |
| 57 | +} |
0 commit comments