Issues (138)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/SourceLocator/Type/AutoloadSourceLocator.php (3 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Roave\BetterReflection\SourceLocator\Type;
6
7
use InvalidArgumentException;
8
use PhpParser\Node;
9
use PhpParser\NodeTraverser;
10
use PhpParser\NodeVisitor\NameResolver;
11
use PhpParser\NodeVisitorAbstract;
12
use PhpParser\Parser;
13
use ReflectionClass;
14
use ReflectionException;
15
use ReflectionFunction;
16
use Roave\BetterReflection\BetterReflection;
17
use Roave\BetterReflection\Identifier\Identifier;
18
use Roave\BetterReflection\Reflection\Exception\InvalidConstantNode;
19
use Roave\BetterReflection\SourceLocator\Ast\Locator as AstLocator;
20
use Roave\BetterReflection\SourceLocator\Exception\InvalidFileLocation;
21
use Roave\BetterReflection\SourceLocator\Located\LocatedSource;
22
use Roave\BetterReflection\SourceLocator\Type\AutoloadSourceLocator\FileReadTrapStreamWrapper;
23
use Roave\BetterReflection\Util\ConstantNodeChecker;
24
use function array_key_exists;
25
use function array_reverse;
26
use function assert;
27
use function class_exists;
28
use function defined;
29
use function file_exists;
30
use function file_get_contents;
31
use function function_exists;
32
use function get_defined_constants;
33
use function get_included_files;
34
use function interface_exists;
35
use function is_string;
36
use function restore_error_handler;
37
use function set_error_handler;
38
use function spl_autoload_functions;
39
use function trait_exists;
40
41
/**
42
 * Use PHP's built in autoloader to locate a class, without actually loading.
43
 *
44
 * There are some prerequisites...
45
 *   - we expect the autoloader to load classes from a file (i.e. using require/include)
46
 *   - your autoloader of choice does not replace stream wrappers
47
 */
48
class AutoloadSourceLocator extends AbstractSourceLocator
49
{
50
    /** @var Parser */
51
    private $phpParser;
52
53
    /** @var NodeTraverser */
54
    private $nodeTraverser;
55
56
    /** @var NodeVisitorAbstract */
57
    private $constantVisitor;
58
59
    public function __construct(?AstLocator $astLocator = null, ?Parser $phpParser = null)
60
    {
61
        $betterReflection = new BetterReflection();
62
63
        parent::__construct($astLocator ?? $betterReflection->astLocator());
64
65
        $this->phpParser       = $phpParser ?? $betterReflection->phpParser();
66
        $this->constantVisitor = $this->createConstantVisitor();
67 18
68
        $this->nodeTraverser = new NodeTraverser();
69 18
        $this->nodeTraverser->addVisitor(new NameResolver());
70
        $this->nodeTraverser->addVisitor($this->constantVisitor);
71 18
    }
72
73 18
    /**
74
     * {@inheritDoc}
75 18
     *
76 18
     * @throws InvalidArgumentException
77 18
     * @throws InvalidFileLocation
78
     */
79 18
    protected function createLocatedSource(Identifier $identifier) : ?LocatedSource
80 18
    {
81 18
        $potentiallyLocatedFile = $this->attemptAutoloadForIdentifier($identifier);
82 18
83
        if (! ($potentiallyLocatedFile && file_exists($potentiallyLocatedFile))) {
84
            return null;
85
        }
86
87
        return new LocatedSource(
88
            file_get_contents($potentiallyLocatedFile),
89
            $potentiallyLocatedFile
90
        );
91
    }
92
93
    /**
94
     * Attempts to locate the specified identifier.
95
     *
96
     * @throws ReflectionException
97
     */
98
    private function attemptAutoloadForIdentifier(Identifier $identifier) : ?string
99
    {
100
        if ($identifier->isClass()) {
101 18
            return $this->locateClassByName($identifier->getName());
102
        }
103 18
104
        if ($identifier->isFunction()) {
105 18
            return $this->locateFunctionByName($identifier->getName());
106 7
        }
107
108
        if ($identifier->isConstant()) {
109 11
            return $this->locateConstantByName($identifier->getName());
110 11
        }
111
112
        return null;
113
    }
114
115
    /**
116
     * Attempt to locate a class by name.
117
     *
118
     * If class already exists, simply use internal reflection API to get the
119
     * filename and store it.
120 18
     *
121
     * If class does not exist, we make an assumption that whatever autoloaders
122 18
     * that are registered will be loading a file. We then override the file://
123 9
     * protocol stream wrapper to "capture" the filename we expect the class to
124
     * be in, and then restore it. Note that class_exists will cause an error
125
     * that it cannot find the file, so we squelch the errors by overriding the
126 9
     * error handler temporarily.
127 3
     *
128
     * Note: the following code is designed so that the first hit on an actual
129
     *       **file** leads to a path being resolved. No actual autoloading nor
130 6
     *       file reading should happen, and most certainly no other classes
131 5
     *       should exist after execution. The only filesystem access is to
132
     *       check whether the file exists.
133
     *
134 1
     * @throws ReflectionException
135
     */
136
    private function locateClassByName(string $className) : ?string
137
    {
138
        if (class_exists($className, false) || interface_exists($className, false) || trait_exists($className, false)) {
139
            $filename = (new ReflectionClass($className))->getFileName();
140
141
            if (! is_string($filename)) {
142
                return null;
143
            }
144
145
            return $filename;
146
        }
147
148
        $this->silenceErrors();
149
150
        try {
151
            return FileReadTrapStreamWrapper::withStreamWrapperOverride(
152 9
                static function () use ($className) : ?string {
153
                    foreach (spl_autoload_functions() as $preExistingAutoloader) {
154 9
                        $preExistingAutoloader($className);
155 4
156
                        /**
157 4
                         * This static variable is populated by the side-effect of the stream wrapper
158
                         * trying to read the file path when `include()` is used by an autoloader.
159
                         *
160
                         * This will not be `null` when the autoloader tried to read a file.
161 4
                         */
162
                        if (FileReadTrapStreamWrapper::$autoloadLocatedFile !== null) {
163
                            return FileReadTrapStreamWrapper::$autoloadLocatedFile;
164 5
                        }
165 5
                    }
166
167 4
                    return null;
168 5
                }
169 5
            );
170 5
        } finally {
171 5
            restore_error_handler();
172 5
        }
173 5
    }
174
175 5
    private function silenceErrors() : void
176
    {
177
        set_error_handler(static function () : bool {
178
            return true;
179
        });
180
    }
181
182
    /**
183
     * We can only load functions if they already exist, because PHP does not
184
     * have function autoloading. Therefore if it exists, we simply use the
185
     * internal reflection API to find the filename. If it doesn't we can do
186 3
     * nothing so throw an exception.
187
     *
188 3
     * @throws ReflectionException
189 1
     */
190
    private function locateFunctionByName(string $functionName) : ?string
191
    {
192 2
        if (! function_exists($functionName)) {
193 2
            return null;
194
        }
195 2
196 1
        $reflectionFileName = (new ReflectionFunction($functionName))->getFileName();
197
198
        if (! is_string($reflectionFileName)) {
199 1
            return null;
200
        }
201
202
        return $reflectionFileName;
203
    }
204
205
    /**
206
     * We can only load constants if they already exist, because PHP does not
207 5
     * have constant autoloading. Therefore if it exists, we simply use brute force
208
     * to search throught all included files to find the right filename.
209 5
     */
210 1
    private function locateConstantByName(string $constantName) : ?string
211
    {
212
        if (! defined($constantName)) {
213
            return null;
214 4
        }
215
216 4
        /** @psalm-var array<string, array<string, int|string|float|bool|array|resource|null>> $constants */
217 1
        $constants = get_defined_constants(true);
218
219
        if (! array_key_exists($constantName, $constants['user'])) {
220
            return null;
221 3
        }
222
223 3
        /** @psalm-suppress UndefinedMethod */
224
        $this->constantVisitor->setConstantName($constantName);
0 ignored issues
show
It seems like you code against a specific sub-type and not the parent class PhpParser\NodeVisitorAbstract as the method setConstantName() does only exist in the following sub-classes of PhpParser\NodeVisitorAbstract: Roave\BetterReflection\S...loadSourceLocator.php$0. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
225 3
226 3
        $constantFileName = null;
227
228 3
        // Note: looking at files in reverse order, since newer files are more likely to have
229
        //       defined a constant that is being looked up. Earlier files are possibly related
230
        //       to libraries/frameworks that we rely upon.
231 3
        foreach (array_reverse(get_included_files()) as $includedFileName) {
232 3
            $ast = $this->phpParser->parse(file_get_contents($includedFileName));
233 3
234
            $this->nodeTraverser->traverse($ast);
0 ignored issues
show
It seems like $ast defined by $this->phpParser->parse(...nts($includedFileName)) on line 232 can also be of type null; however, PhpParser\NodeTraverser::traverse() does only seem to accept array<integer,object<PhpParser\Node>>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
235
236
            /** @psalm-suppress UndefinedMethod */
237 3
            if ($this->constantVisitor->getNode() !== null) {
0 ignored issues
show
It seems like you code against a specific sub-type and not the parent class PhpParser\NodeVisitorAbstract as the method getNode() does only exist in the following sub-classes of PhpParser\NodeVisitorAbstract: Psalm\Internal\PhpVisitor\TraitFinder, Roave\BetterReflection\S...loadSourceLocator.php$0. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
238
                $constantFileName = $includedFileName;
239
                break;
240
            }
241
        }
242
243
        return $constantFileName;
244
    }
245
246
    private function createConstantVisitor() : NodeVisitorAbstract
247
    {
248
        return new class() extends NodeVisitorAbstract
249
        {
250
            /** @var string|null */
251
            private $constantName;
252
253
            /** @var Node\Stmt\Const_|Node\Expr\FuncCall|null */
254 4
            private $node;
255
256 4
            public function enterNode(Node $node) : ?int
257
            {
258 4
                if ($node instanceof Node\Stmt\Const_) {
259
                    foreach ($node->consts as $constNode) {
260
                        if ($constNode->namespacedName->toString() === $this->constantName) {
261
                            $this->node = $node;
262
263
                            return NodeTraverser::STOP_TRAVERSAL;
264
                        }
265
                    }
266
267
                    return NodeTraverser::DONT_TRAVERSE_CHILDREN;
268
                }
269
270
                if ($node instanceof Node\Expr\FuncCall) {
271
                    try {
272
                        ConstantNodeChecker::assertValidDefineFunctionCall($node);
273
                    } catch (InvalidConstantNode $e) {
274
                        return null;
275
                    }
276 4
277
                    $nameNode = $node->args[0]->value;
278 4
                    assert($nameNode instanceof Node\Scalar\String_);
279
280 4
                    if ($nameNode->value === $this->constantName) {
281
                        $this->node = $node;
282
283 1
                        return NodeTraverser::STOP_TRAVERSAL;
284 4
                    }
285 4
                }
286 4
287
                if ($node instanceof Node\Stmt\Class_) {
288
                    return NodeTraverser::DONT_TRAVERSE_CHILDREN;
289
                }
290
291 4
                return null;
292 4
            }
293
294 4
            public function setConstantName(string $constantName) : void
295
            {
296
                $this->constantName = $constantName;
297
            }
298
299
            /**
300
             * @return Node\Stmt\Const_|Node\Expr\FuncCall|null
301
             */
302
            public function getNode() : ?Node
303
            {
304
                return $this->node;
305
            }
306
        };
307 3
    }
308
}
309