Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

detect possible sql injections #155

Merged
merged 37 commits into from
Oct 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
d005a0a
detect possible sql injections
staabm Oct 2, 2022
2e9b52b
Update expected.out
staabm Oct 2, 2022
396c40a
cs
staabm Oct 2, 2022
091e3a1
fix expectations
staabm Oct 2, 2022
92ddbf0
more tests
staabm Oct 2, 2022
385bf4e
whitelist some api calls which can be used in sql expressions but are…
staabm Oct 2, 2022
6451bee
tests and fixes
staabm Oct 2, 2022
3d95bb4
Update RexSqlInjectionRule.php
staabm Oct 2, 2022
d517f23
cover getArray(), getDbArray()
staabm Oct 2, 2022
d87a6e6
support indirect analysis via variable
staabm Oct 2, 2022
72419b7
support encapsed types
staabm Oct 2, 2022
d2eb801
added 'in' escaping method
staabm Oct 2, 2022
3cee00e
added another test
staabm Oct 3, 2022
cc4e6df
utilize `@psalm-taint-escape sql`
staabm Oct 3, 2022
a16ca3f
Revert "utilize `@psalm-taint-escape sql`"
staabm Oct 3, 2022
381fffa
fix
staabm Oct 3, 2022
8312e65
Update RexSqlInjectionRule.php
staabm Oct 4, 2022
33c09fa
better method name
staabm Oct 4, 2022
eb86eb6
added hint to the expression in question
staabm Oct 4, 2022
5f80a39
ignore queries from property-fetches
staabm Oct 4, 2022
6706ac9
more precise error in deep-concat cases
staabm Oct 4, 2022
d5e4e10
better tip
staabm Oct 4, 2022
7aa26a4
cs
staabm Oct 4, 2022
edd4805
Update expected.out
staabm Oct 4, 2022
fb905a6
cover more rex_sql apis
staabm Oct 4, 2022
09d6e94
Update RexSqlInjectionRule.php
staabm Oct 4, 2022
a02f231
more tests
staabm Oct 4, 2022
c17aff8
fix handling of encapsed values
staabm Oct 4, 2022
7f38abe
re-organize tests
staabm Oct 4, 2022
ec8f80d
support safe-implode() concat
staabm Oct 4, 2022
411d9b2
cs
staabm Oct 4, 2022
a35d609
`escapelikewildcards` requires an additional escape
staabm Oct 4, 2022
0694f86
better tip
staabm Oct 4, 2022
e5fb9ae
Update RexSqlInjectionRule.php
staabm Oct 4, 2022
a268fc4
fix
staabm Oct 5, 2022
abbc211
docs
staabm Oct 5, 2022
48ae696
Update RexSqlInjectionRule.php
staabm Oct 6, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions config/phpstan-dba.neon
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
services:
-
class: staabm\PHPStanDba\Ast\PreviousConnectingVisitor
tags:
- phpstan.parser.richParserNodeVisitor

# redaxos setQuery etc. APIs support both, prepared and unprepared statements..
# therefore we need to register them twice, to also cover cases which don't pass parameters.
-
Expand Down Expand Up @@ -54,6 +59,10 @@ services:
class: redaxo\phpstan\RexSqlGetValueRule
tags:
- phpstan.rules.rule
-
class: redaxo\phpstan\RexSqlInjectionRule
tags:
- phpstan.rules.rule

-
class: redaxo\phpstan\RexMediaGetValueDynamicReturnTypeExtension
Expand Down
2 changes: 1 addition & 1 deletion lib/rule/RexGetValueRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public function processNode(Node $methodCall, Scope $scope): array

return [
RuleErrorBuilder::message(
sprintf("Unknown name %s given to getValue().", $nameType->describe(VerbosityLevel::precise()))
sprintf('Unknown name %s given to getValue().', $nameType->describe(VerbosityLevel::precise()))
)->build(),
];
}
Expand Down
252 changes: 252 additions & 0 deletions lib/rule/RexSqlInjectionRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
<?php

declare(strict_types=1);

namespace redaxo\phpstan;

use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Concat;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Node\Printer\ExprPrinter;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\BooleanType;
use PHPStan\Type\FloatType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeWithClassName;
use rex;
use rex_i18n;
use rex_sql;
use staabm\PHPStanDba\Ast\ExpressionFinder;
use staabm\PHPStanDba\PhpDoc\PhpDocUtil;
use function array_key_exists;
use function count;
use function in_array;

/**
* @implements Rule<MethodCall>
*
* @see https://psalm.dev/docs/security_analysis/
*/
final class RexSqlInjectionRule implements Rule
{
/**
* @var ExprPrinter
*/
private $exprPrinter;

/**
* @var array<string, int>
*/
private $taintSinks = [
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

falls redaxo/redaxo#5353 gemergt wird, könnte man hier die liste um die methoden reduzieren die psalm-taint-sink markiert sind

'select' => 0,
'setrawvalue' => 1,
'setwhere' => 0,
'preparequery' => 0,
'setquery' => 0,
'getarray' => 0,
'setdbquery' => 0,
'getdbarray' => 0,
];

public function __construct(
ExprPrinter $exprPrinter
) {
$this->exprPrinter = $exprPrinter;
}

public function getNodeType(): string
{
return MethodCall::class;
}

public function processNode(Node $methodCall, Scope $scope): array
{
$args = $methodCall->getArgs();
if (count($args) < 1) {
return [];
}

if (!$methodCall->name instanceof Node\Identifier) {
return [];
}

if (!array_key_exists($methodCall->name->toLowerString(), $this->taintSinks)) {
return [];
}

$callerType = $scope->getType($methodCall->var);
if (!$callerType instanceof TypeWithClassName) {
return [];
}

if (rex_sql::class !== $callerType->getClassname()) {
return [];
}

$argNo = $this->taintSinks[$methodCall->name->toLowerString()];
$sqlExpression = $args[$argNo]->value;

// we can't infer query strings from properties
if ($sqlExpression instanceof Node\Expr\PropertyFetch) {
return [];
}

if ($sqlExpression instanceof Node\Expr\Variable) {
$finder = new ExpressionFinder();
$queryStringExpression = $finder->findQueryStringExpression($sqlExpression);
if (null !== $queryStringExpression) {
$sqlExpression = $queryStringExpression;
}
}

$rawValue = $this->findInsecureSqlExpr($sqlExpression, $scope);
if (null !== $rawValue) {
$description = $this->exprPrinter->printExpr($rawValue);

return [
RuleErrorBuilder::message(
'Possible SQL-injection in expression '. $description .'.')
->tip('Consider use of more SQL-safe types, prepared statements, rex_sql::escape*() or rex_sql::in().')
->build(),
];
}

return [];
}

private function findInsecureSqlExpr(Node\Expr $expr, Scope $scope, bool $resolveVariables = true): ?Node\Expr
{
if (true === $resolveVariables && $expr instanceof Node\Expr\Variable) {
$finder = new ExpressionFinder();
$assignExpr = $finder->findQueryStringExpression($expr);

if (null !== $assignExpr) {
return $this->findInsecureSqlExpr($assignExpr, $scope);
}

return $this->findInsecureSqlExpr($expr, $scope, false);
}

if ($expr instanceof Concat) {
$left = $expr->left;
$right = $expr->right;

$leftInsecure = $this->findInsecureSqlExpr($left, $scope);
if (null !== $leftInsecure) {
return $leftInsecure;
}

$rightInsecure = $this->findInsecureSqlExpr($right, $scope);
if (null !== $rightInsecure) {
return $rightInsecure;
}

return null;
}

if ($expr instanceof Node\Scalar\Encapsed) {
foreach ($expr->parts as $part) {
$insecurePart = $this->findInsecureSqlExpr($part, $scope);
if (null !== $insecurePart) {
return $insecurePart;
}
}
return null;
}

if ($expr instanceof Node\Scalar\EncapsedStringPart) {
return null;
}

$exprType = $scope->getType($expr);
$mixedType = new MixedType();
if ($exprType->isSuperTypeOf($mixedType)->yes()) {
return $expr;
}

if ($exprType->isString()->yes()) {
if ($expr instanceof Node\Expr\CallLike) {
if (PhpDocUtil::commentContains('@psalm-taint-escape sql', $expr, $scope)) {
return null;
}
}

if ($expr instanceof Node\Expr\MethodCall && $expr->name instanceof Node\Identifier) {
$callerType = $scope->getType($expr->var);

if ($callerType instanceof TypeWithClassName) {
// handle escaping methods
if (rex_sql::class === $callerType->getClassName() && in_array($expr->name->toLowerString(), ['escape', 'escapeidentifier', 'in'], true)) {
return null;
}
}
}

if ($expr instanceof Node\Expr\StaticCall && $expr->class instanceof Node\Name && $expr->name instanceof Node\Identifier) {
// lets assume rex::getTable() and rex::getTablePrefix() return untainted values.
// these methods are used in nearly every query and would otherwise create a lot of false positives.
if (rex::class === $expr->class->toString() && in_array($expr->name->toLowerString(), ['gettableprefix', 'gettable'], true)) {
return null;
}
// translations could still lead to syntax errors, but since the input is not end-user controlled, we ignore it.
if (rex_i18n::class === $expr->class->toString() && 'msg' === $expr->name->toLowerString()) {
return null;
}
}

if ($expr instanceof Node\Expr\FuncCall && $expr->name instanceof Node\Name) {
if (in_array($expr->name->toLowerString(), ['implode', 'join'], true)) {
$args = $expr->getArgs();

if (count($args) >= 2) {
$arrayValueType = $scope->getType($args[1]->value);

if ($arrayValueType->isArray()->yes() && $this->isSafeType($arrayValueType->getIterableValueType())) {
return null;
}
}
}
}

if ($this->isSafeType($exprType)) {
return null;
}

return $expr;
}

return null;
}

private function isSafeType(Type $type): bool
{
if ($type->isLiteralString()->yes()) {
return true;
}

if ($type->isNumericString()->yes()) {
return true;
}

$integer = new IntegerType();
if ($integer->isSuperTypeOf($type)->yes()) {
return true;
}

$bool = new BooleanType();
if ($bool->isSuperTypeOf($type)->yes()) {
return true;
}

$float = new FloatType();
if ($float->isSuperTypeOf($type)->yes()) {
return true;
}

return false;
}
}