diff --git a/changelogs/fragments/fix_unsafe_newline.yml b/changelogs/fragments/fix_unsafe_newline.yml new file mode 100644 index 00000000000000..44180c6237fccc --- /dev/null +++ b/changelogs/fragments/fix_unsafe_newline.yml @@ -0,0 +1,2 @@ +security_fixes: + - templating engine fix for not preserving usnafe status when trying to preserve newlines. CVE-2021-3583 diff --git a/lib/ansible/template/__init__.py b/lib/ansible/template/__init__.py index 58da28df9b1b95..d2e39cb2f62fc4 100644 --- a/lib/ansible/template/__init__.py +++ b/lib/ansible/template/__init__.py @@ -1114,7 +1114,8 @@ def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes= res = ansible_native_concat(rf) else: res = j2_concat(rf) - if getattr(new_context, 'unsafe', False): + unsafe = getattr(new_context, 'unsafe', False) + if unsafe: res = wrap_var(res) except TypeError as te: if 'AnsibleUndefined' in to_native(te): @@ -1144,6 +1145,8 @@ def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes= res_newlines = _count_newlines_from_end(res) if data_newlines > res_newlines: res += self.environment.newline_sequence * (data_newlines - res_newlines) + if unsafe: + res = wrap_var(res) return res except (UndefinedError, AnsibleUndefinedVariable) as e: if fail_on_undefined: diff --git a/test/integration/targets/template/runme.sh b/test/integration/targets/template/runme.sh index cb00df754d71f7..1b4e980e5bb539 100755 --- a/test/integration/targets/template/runme.sh +++ b/test/integration/targets/template/runme.sh @@ -34,3 +34,7 @@ ansible-playbook 6653.yml -v "$@" # https://github.com/ansible/ansible/issues/72262 ansible-playbook 72262.yml -v "$@" + +# ensure unsafe is preserved, even with extra newlines +ansible-playbook unsafe.yml -v "$@" + diff --git a/test/integration/targets/template/unsafe.yml b/test/integration/targets/template/unsafe.yml new file mode 100644 index 00000000000000..6746e1ea0ca223 --- /dev/null +++ b/test/integration/targets/template/unsafe.yml @@ -0,0 +1,19 @@ +- hosts: localhost + gather_facts: false + vars: + nottemplated: this should not be seen + imunsafe: !unsafe '{{ nottemplated }}' + tasks: + + - set_fact: + this_was_unsafe: > + {{ imunsafe }} + + - set_fact: + this_always_safe: '{{ imunsafe }}' + + - name: ensure nothing was templated + assert: + that: + - this_always_safe == imunsafe + - imunsafe == this_was_unsafe.strip()