Skip to content

Commit

Permalink
fix unsafe preservation across newlines (#74960)
Browse files Browse the repository at this point in the history
* fix unsafe preservation across newlines

  CVE-2021-3583
  ensure we always have unsafe

Co-authored-by: Rick Elrod <rick@elrod.me>
  • Loading branch information
bcoca and relrod committed Jun 11, 2021
1 parent 473df5c commit 4c8c40f
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
2 changes: 2 additions & 0 deletions 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
5 changes: 4 additions & 1 deletion lib/ansible/template/__init__.py
Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 4 additions & 0 deletions test/integration/targets/template/runme.sh
Expand Up @@ -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 "$@"

19 changes: 19 additions & 0 deletions 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()

0 comments on commit 4c8c40f

Please sign in to comment.