CVE-2021-4041 (published 2022-08-24T16:15Z)

A flaw was found in ansible-runner. An improper escaping of the shell command, while calling the ansible_runner.interface.run_command, can lead to parameters getting executed as host's shell command. A developer could unintentionally write code that gets executed in the host rather than the virtual environment.

CVSS v3 base score: 7.8, HIGH (CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-116
cwe_name: Improper Encoding or Escaping of Output
description: The product prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.
extended_description: 
            Improper encoding or escaping can allow attackers to change the commands that are sent to another component, inserting malicious commands instead.
            Most products follow a certain protocol that uses structured messages for communication between components, such as queries or commands. These structured messages can contain raw data interspersed with metadata or control information. For example, "GET /index.html HTTP/1.1" is a structured message containing a command ("GET") with a single argument ("/index.html") and metadata about which protocol version is being used ("HTTP/1.1").
            If an application uses attacker-supplied inputs to construct a structured message without properly encoding or escaping, then the attacker could insert special characters that will cause the data to be interpreted as control information or metadata. Consequently, the component that receives the output will perform the wrong operations, or otherwise interpret the data incorrectly.
         
         

Fix information:
repo_url: https://github.com/ansible/ansible-runner
commit_details: repo_url: https://github.com/ansible/ansible-runner
author: David Shrewsbury
author_date: 2021-10-15 11:22:12-04:00
msg: Remove shell use in subprocess

Co-authored-by: Sam Doran <sdoran@redhat.com>
repository: repo_url: https://github.com/ansible/ansible-runner
repo_name: ansible/ansible-runner
description: A tool and python library that helps when interfacing with Ansible directly or as part of another system whether that be through a container image interface, as a standalone tool, or as a Python module that can be imported. The goal is to provide a stable and consistent interface abstraction to Ansible.
repo_language: Python
owner: ansible
file_changes: filename: doc.py
change_type: ModificationType.MODIFY
diff: @@ -87,7 +87,7 @@ class DocConfig(BaseConfig):
         if module_path:
             self.cmdline_args.extend(['-M', module_path])
 
-        self.cmdline_args.append(" ".join(plugin_names))
+        self.cmdline_args.extend(plugin_names)
 
         self.command = [self._ansible_doc_exec_path] + self.cmdline_args
         self._handle_command_wrap(self.execution_mode, self.cmdline_args)

programming_language: Python
filename: runner.py
change_type: ModificationType.MODIFY
diff: @@ -204,8 +204,12 @@ class Runner(object):
             user = getpass.getuser()
             group = grp.getgrgid(os.getgid()).gr_name
 
-            cmd = 'cgcreate -a {user}:{group} -t {user}:{group} -g cpuacct,memory,pids:{}'.format(cgroup_path, user=user, group=group)
-            proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
+            cmd = ['cgcreate',
+                   '-a', f'{user}:{group}',
+                   '-t', f'{user}:{group}',
+                   '-g', f'cpuacct,memory,pids:{cgroup_path}',
+                   ]
+            proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
             _, stderr = proc.communicate()
             if proc.returncode:
                 # Unable to create cgroup
@@ -249,12 +253,11 @@ class Runner(object):
                     'stderr': error_fd,
                     'check': True,
                     'universal_newlines': True,
-                    'shell': True
                 }
                 if subprocess_timeout is not None:
                     kwargs.update({'timeout': subprocess_timeout})
 
-                proc_out = run_subprocess(" ".join(command), **kwargs)
+                proc_out = run_subprocess(command, **kwargs)
 
                 stdout_response = proc_out.stdout
                 stderr_response = proc_out.stderr
@@ -391,8 +394,8 @@ class Runner(object):
                 return True
             _delete()
         if self.resource_profiling:
-            cmd = 'cgdelete -g cpuacct,memory,pids:{}'.format(cgroup_path)
-            proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
+            cmd = ['cgdelete', '-g', f'cpuacct,memory,pids:{cgroup_path}']
+            proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
             _, stderr = proc.communicate()
             if proc.returncode:
                 logger.error('Failed to delete cgroup: {}'.format(stderr))
@@ -532,8 +535,8 @@ class Runner(object):
         container_name = self.config.container_name
         if container_name:
             container_cli = self.config.process_isolation_executable
-            cmd = '{} kill {}'.format(container_cli, container_name)
-            proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
+            cmd = [container_cli, 'kill', container_name]
+            proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
             _, stderr = proc.communicate()
             if proc.returncode:
                 logger.info('Error from {} kill {} command:\n{}'.format(container_cli, container_name, stderr))

programming_language: Python
filename: test_interface.py
change_type: ModificationType.MODIFY
diff: @@ -152,6 +152,30 @@ def test_run_command(project_fixtures):
     assert err == ''
 
 
+def test_run_command_injection_error():
+    out, err, rc = run_command(
+        executable_cmd='whoami',
+        cmdline_args=[';hostname'],
+        runner_mode='subprocess',
+    )
+    assert rc == 1
+    assert "usage: whoami" in err or "whoami: extra operand ‘;hostname’" in err
+
+
+@pytest.mark.test_all_runtimes
+def test_run_command_injection_error_within_container(runtime):
+    out, err, rc = run_command(
+        executable_cmd='whoami',
+        cmdline_args=[';hostname'],
+        runner_mode='subprocess',
+        process_isolation_executable=runtime,
+        process_isolation=True,
+        container_image=defaults.default_container_image,
+    )
+    assert rc == 1
+    assert "whoami: extra operand ';hostname'" in err
+
+
 @pytest.mark.test_all_runtimes
 def test_run_ansible_command_within_container(project_fixtures, runtime):
     private_data_dir = project_fixtures / 'debug'

programming_language: Python
filename: test_doc.py
change_type: ModificationType.MODIFY
diff: @@ -52,7 +52,7 @@ def test_prepare_plugin_docs_command():
     plugin_names = ['copy', 'file']
     plugin_type = 'module'
     rc.prepare_plugin_docs_command(plugin_names, plugin_type=plugin_type, snippet=True, playbook_dir='/tmp/test')
-    expected_command = [get_executable_path('ansible-doc'), '-s', '-t', 'module', '--playbook-dir', '/tmp/test', 'copy file']
+    expected_command = [get_executable_path('ansible-doc'), '-s', '-t', 'module', '--playbook-dir', '/tmp/test', 'copy', 'file']
     assert rc.command == expected_command
     assert rc.runner_mode == 'subprocess'
     assert rc.execution_mode == BaseExecutionMode.ANSIBLE_COMMANDS
@@ -113,7 +113,7 @@ def test_prepare_plugin_docs_command_with_containerization(tmp_path, runtime, mo
         '-s',
         '-t', 'module',
         '--playbook-dir', '/tmp/test',
-        'copy '
+        'copy',
         'file',
     ])
 

programming_language: Python