MDL-72029 lib: Prevent path traversal for clean_param with PARAM_SAFEPATH

This commit is contained in:
Huong Nguyen
2022-07-06 05:24:15 +02:00
committed by Jenkins
parent 8af0c977d0
commit edc7eb06b7
2 changed files with 46 additions and 2 deletions
+12 -2
View File
@@ -983,8 +983,18 @@ function clean_param($param, $type) {
return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
case PARAM_SAFEPATH:
// Remove everything not a-zA-Z0-9/_- .
return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
// Replace MS \ separators.
$param = str_replace('\\', '/', $param);
// Remove any number of ../ to prevent path traversal.
$param = preg_replace('/\.\.+\//', '', $param);
// Remove everything not a-zA-Z0-9/:_- .
$param = preg_replace('/[^a-zA-Z0-9\/:_-]/i', '', $param);
// Remove leading slash.
$param = ltrim($param, '/');
if ($param === '.') {
$param = '';
}
return $param;
case PARAM_FILE:
// Strip all suspicious characters from filename.
+34
View File
@@ -837,6 +837,40 @@ class core_moodlelib_testcase extends advanced_testcase {
}
}
/**
* Provide some tested base url and expected results.
*
* @return array Array of tested base url and expected results.
*/
public function clean_param_safepath_provider(): array {
return [
// MS separator test.
['c:\temp', 'c:/temp'],
// Leading slash test.
['/tmp/', 'tmp/'],
// Path traversal test.
['../../../../../etc/', 'etc/'],
['../', ''],
['.../...//', ''],
['.', '']
];
}
/**
* Test clean_param() method with PARAM_SAFEPATH type.
*
* @dataProvider clean_param_safepath_provider
* @covers ::clean_param
* @param string $path
* @param string $expected
*/
public function test_clean_param_safepath(string $path, string $expected) {
$result = clean_param($path, PARAM_SAFEPATH);
$this->assertSame($expected, $result);
}
public function test_validate_param() {
try {
$param = validate_param('11a', PARAM_INT);