Skip to content

Commit

Permalink
Merge pull request #7 from luyadev/csv-sanitizer
Browse files Browse the repository at this point in the history
Csv sanitizer
  • Loading branch information
nadar committed Apr 21, 2022
2 parents f481844 + 63874c7 commit 9956ed6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).

## 1.2.1 (21. April 2022)

+ [#7](https://github.com/luyadev/yii-helpers/pull/7) Fixed security issue with csv injection for formulas and functions.

## 1.2.0 (15. June 2021)

+ [#4](https://github.com/luyadev/yii-helpers/pull/4) Added option to define the delimiter in `StringHelper::template` function.
Expand Down
30 changes: 25 additions & 5 deletions src/helpers/ExportHelper.php
Expand Up @@ -179,13 +179,33 @@ protected static function generateRow(array $row, $delimiter, $enclose)
} elseif (!is_scalar($item)) {
$item = "[array]";
}
$item = $enclose.str_replace([
'"',
], [
'""',
], $item).$enclose;
$item = $enclose.self::sanitizeValue($item).$enclose;
});

return implode($delimiter, $row) . PHP_EOL;
}

/**
* Sanitize Certain Values to increase security from user generated output.
*
* @param string $value
* @return string
* @see https://owasp.org/www-community/attacks/CSV_Injection
* @since 1.2.1
*/
public static function sanitizeValue($value)
{
$value = str_replace([
'"',
], [
'""',
], trim($value));

$firstChar = substr($value, 0, 1);
if (in_array($firstChar, ['=', '+', '-', '@', PHP_EOL, "\t", "\n"])) {
$value = StringHelper::replaceFirst($firstChar, "'$firstChar", $value);
}

return $value;
}
}
3 changes: 2 additions & 1 deletion tests/helpers/ExportHelperTest.php
Expand Up @@ -137,8 +137,9 @@ public function testSpecialCharsEncoding()
{
$content = ExportHelper::csv([
['&', "'", 'a"b"c'],
['nix', 'nix', '=1+2";=1+2']
], [], false);

$this->assertSameTrimmed('"&","\'","a""b""c"', $content);
$this->assertSameTrimmed('"&","\'","a""b""c" "nix","nix","\'=1+2"";=1+2"', $content);
}
}

0 comments on commit 9956ed6

Please sign in to comment.