Skip to content

Commit

Permalink
Use yaml.safe_load() instead of yaml.load()
Browse files Browse the repository at this point in the history
* Use yaml.safe_load() instead of yaml.load() as recommended by pyyaml documentation in order to avoid the execution of untrusted code.

* Add tests for load_config() function from watchmedo module.
  • Loading branch information
julianolf authored and BoboTiG committed Jan 8, 2019
1 parent 2cea5e8 commit 48701f3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/watchdog/watchmedo.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def load_config(tricks_file_pathname):
f = open(tricks_file_pathname, 'rb')
content = f.read()
f.close()
config = yaml.load(content)
config = yaml.safe_load(content)
return config


Expand Down
42 changes: 42 additions & 0 deletions tests/test_watchmedo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from watchdog import watchmedo
import pytest
import yaml
import os


def test_load_config_valid(tmpdir):
"""Verifies the load of a valid yaml file"""

yaml_file = os.path.join(tmpdir, 'config_file.yaml')
with open(yaml_file, 'w') as f:
f.write('one: value\ntwo:\n- value1\n- value2\n')

config = watchmedo.load_config(yaml_file)
assert isinstance(config, dict)
assert 'one' in config
assert 'two' in config
assert isinstance(config['two'], list)
assert config['one'] == 'value'
assert config['two'] == ['value1', 'value2']


def test_load_config_invalid(tmpdir):
"""Verifies if safe load avoid the execution
of untrusted code inside yaml files"""

critical_dir = os.path.join(tmpdir, 'critical')
yaml_file = os.path.join(tmpdir, 'tricks_file.yaml')
with open(yaml_file, 'w') as f:
content = (
'one: value\n'
'run: !!python/object/apply:os.system ["mkdir {}"]\n'
).format(critical_dir)
f.write(content)

with pytest.raises(yaml.constructor.ConstructorError):
watchmedo.load_config(yaml_file)

assert not os.path.exists(critical_dir)

0 comments on commit 48701f3

Please sign in to comment.