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 (6 issues)

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\Util\ConstantNodeChecker;
23
use function array_key_exists;
24
use function assert;
25
use function class_exists;
26
use function defined;
27
use function file_exists;
28
use function file_get_contents;
29
use function function_exists;
30
use function get_defined_constants;
31
use function get_included_files;
32
use function interface_exists;
33
use function is_string;
34
use function restore_error_handler;
35
use function set_error_handler;
36
use function stat;
37
use function stream_wrapper_register;
38
use function stream_wrapper_restore;
39
use function stream_wrapper_unregister;
40
use function trait_exists;
41
use const STREAM_URL_STAT_QUIET;
42
43
/**
44
 * Use PHP's built in autoloader to locate a class, without actually loading.
45
 *
46
 * There are some prerequisites...
47
 *   - we expect the autoloader to load classes from a file (i.e. using require/include)
48
 */
49
class AutoloadSourceLocator extends AbstractSourceLocator
50
{
51
    /** @var AstLocator */
52
    private $astLocator;
0 ignored issues
show
Comprehensibility introduced by Marco Pivetta
Consider using a different property name as you override a private property of the parent class.
Loading history...
53
54
    /** @var Parser */
55
    private $phpParser;
56
57
    /** @var NodeTraverser */
58
    private $nodeTraverser;
59
60
    /** @var NodeVisitorAbstract */
61
    private $constantVisitor;
62
63
    /**
64
     * Note: the constructor has been made a 0-argument constructor because `\stream_wrapper_register`
65
     *       is a piece of trash, and doesn't accept instances, just class names.
66
     */
67 18
    public function __construct(?AstLocator $astLocator = null, ?Parser $phpParser = null)
68
    {
69 18
        $betterReflection = new BetterReflection();
70
71 18
        $validLocator = $astLocator ?? self::$currentAstLocator ?? $betterReflection->astLocator();
72
73 18
        parent::__construct($validLocator);
74
75 18
        $this->astLocator      = $validLocator;
76 18
        $this->phpParser       = $phpParser ?? $betterReflection->phpParser();
77 18
        $this->constantVisitor = $this->createConstantVisitor();
78
79 18
        $this->nodeTraverser = new NodeTraverser();
80 18
        $this->nodeTraverser->addVisitor(new NameResolver());
81 18
        $this->nodeTraverser->addVisitor($this->constantVisitor);
82 18
    }
83
84
    /**
85
     * Primarily used by the non-loading-autoloader magic trickery to determine
86
     * the filename used during autoloading.
87
     *
88
     * @var string|null
89
     */
90
    private static $autoloadLocatedFile;
91
92
    /** @var AstLocator */
93
    private static $currentAstLocator;
94
95
    /**
96
     * {@inheritDoc}
97
     *
98
     * @throws InvalidArgumentException
99
     * @throws InvalidFileLocation
100
     */
101 18
    protected function createLocatedSource(Identifier $identifier) : ?LocatedSource
102
    {
103 18
        $potentiallyLocatedFile = $this->attemptAutoloadForIdentifier($identifier);
104
105 18
        if (! ($potentiallyLocatedFile && file_exists($potentiallyLocatedFile))) {
106 7
            return null;
107
        }
108
109 11
        return new LocatedSource(
110 11
            file_get_contents($potentiallyLocatedFile),
111
            $potentiallyLocatedFile
112
        );
113
    }
114
115
    /**
116
     * Attempts to locate the specified identifier.
117
     *
118
     * @throws ReflectionException
119
     */
120 18
    private function attemptAutoloadForIdentifier(Identifier $identifier) : ?string
121
    {
122 18
        if ($identifier->isClass()) {
123 9
            return $this->locateClassByName($identifier->getName());
124
        }
125
126 9
        if ($identifier->isFunction()) {
127 3
            return $this->locateFunctionByName($identifier->getName());
128
        }
129
130 6
        if ($identifier->isConstant()) {
131 5
            return $this->locateConstantByName($identifier->getName());
132
        }
133
134 1
        return null;
135
    }
136
137
    /**
138
     * Attempt to locate a class by name.
139
     *
140
     * If class already exists, simply use internal reflection API to get the
141
     * filename and store it.
142
     *
143
     * If class does not exist, we make an assumption that whatever autoloaders
144
     * that are registered will be loading a file. We then override the file://
145
     * protocol stream wrapper to "capture" the filename we expect the class to
146
     * be in, and then restore it. Note that class_exists will cause an error
147
     * that it cannot find the file, so we squelch the errors by overriding the
148
     * error handler temporarily.
149
     *
150
     * @throws ReflectionException
151
     */
152 9
    private function locateClassByName(string $className) : ?string
153
    {
154 9
        if (class_exists($className, false) || interface_exists($className, false) || trait_exists($className, false)) {
155 4
            $filename = (new ReflectionClass($className))->getFileName();
156
157 4
            if (! is_string($filename)) {
158
                return null;
159
            }
160
161 4
            return $filename;
162
        }
163
164 5
        self::$autoloadLocatedFile = null;
165 5
        self::$currentAstLocator   = $this->astLocator; // passing the locator on to the implicitly instantiated `self`
166
        $previousErrorHandler      = set_error_handler(static function (int $errno, string $errstr) : bool {
0 ignored issues
show
The parameter $errno is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $errstr is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
167 4
            return true;
168 5
        });
169 5
        stream_wrapper_unregister('file');
170 5
        stream_wrapper_register('file', self::class);
171 5
        class_exists($className);
172 5
        stream_wrapper_restore('file');
173 5
        set_error_handler($previousErrorHandler);
174
175 5
        return self::$autoloadLocatedFile;
176
    }
177
178
    /**
179
     * We can only load functions if they already exist, because PHP does not
180
     * have function autoloading. Therefore if it exists, we simply use the
181
     * internal reflection API to find the filename. If it doesn't we can do
182
     * nothing so throw an exception.
183
     *
184
     * @throws ReflectionException
185
     */
186 3
    private function locateFunctionByName(string $functionName) : ?string
187
    {
188 3
        if (! function_exists($functionName)) {
189 1
            return null;
190
        }
191
192 2
        $reflection         = new ReflectionFunction($functionName);
193 2
        $reflectionFileName = $reflection->getFileName();
194
195 2
        if (! is_string($reflectionFileName)) {
196 1
            return null;
197
        }
198
199 1
        return $reflectionFileName;
200
    }
201
202
    /**
203
     * We can only load constants if they already exist, because PHP does not
204
     * have constant autoloading. Therefore if it exists, we simply use brute force
205
     * to search throught all included files to find the right filename.
206
     */
207 5
    private function locateConstantByName(string $constantName) : ?string
208
    {
209 5
        if (! defined($constantName)) {
210 1
            return null;
211
        }
212
213 4
        /** @psalm-var array<string, array<string,int|string|float|bool|null|array|resource>> $constants */
214 1
        $constants = get_defined_constants(true);
215
216
        if (! array_key_exists($constantName, $constants['user'])) {
217
            return null;
218 3
        }
219
220 3
        /** @psalm-suppress UndefinedMethod */
221
        $this->constantVisitor->setConstantName($constantName);
222 3
223 3
        $constantFileName = null;
224
225 3
        foreach (get_included_files() as $includedFileName) {
226
            $ast = $this->phpParser->parse(file_get_contents($includedFileName));
227
228 3
            $this->nodeTraverser->traverse($ast);
229 3
230 3
            /** @psalm-suppress UndefinedMethod */
231
            if ($this->constantVisitor->getNode() !== null) {
232
                $constantFileName = $includedFileName;
233
                break;
234 3
            }
235
        }
236
237
        return $constantFileName;
238
    }
239
240
    /**
241
     * Our wrapper simply records which file we tried to load and returns
242
     * boolean false indicating failure.
243
     *
244
     * @see https://php.net/manual/en/class.streamwrapper.php
245
     * @see https://php.net/manual/en/streamwrapper.stream-open.php
246
     *
247
     * @param string $path
248
     * @param string $mode
249
     * @param int    $options
250
     * @param string $opened_path
251 4
     *
252
     * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
253 4
     */
254
    public function stream_open($path, $mode, $options, &$opened_path) : bool
0 ignored issues
show
The parameter $mode is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $opened_path is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
255 4
    {
256
        self::$autoloadLocatedFile = $path;
257
258
        return false;
259
    }
260
261
    /**
262
     * url_stat is triggered by calls like "file_exists". The call to "file_exists" must not be overloaded.
263
     * This function restores the original "file" stream, issues a call to "stat" to get the real results,
264
     * and then re-registers the AutoloadSourceLocator stream wrapper.
265
     *
266
     * @see https://php.net/manual/en/class.streamwrapper.php
267
     * @see https://php.net/manual/en/streamwrapper.url-stat.php
268
     *
269
     * @param string $path
270
     * @param int    $flags
271
     *
272
     * @return mixed[]|bool
273 4
     *
274
     * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
275 4
     */
276
    public function url_stat($path, $flags)
277 4
    {
278
        stream_wrapper_restore('file');
279
280 1
        if ($flags & STREAM_URL_STAT_QUIET) {
281 4
            set_error_handler(static function () {
282 4
                // Use native error handler
283 4
                return false;
284
            });
285
            $result = @stat($path);
286
            restore_error_handler();
287
        } else {
288 4
            $result = stat($path);
289 4
        }
290
291 4
        stream_wrapper_unregister('file');
292
        stream_wrapper_register('file', self::class);
293
294
        return $result;
295
    }
296
297
    private function createConstantVisitor() : NodeVisitorAbstract
298
    {
299
        return new class() extends NodeVisitorAbstract
300
        {
301
            /** @var string|null */
302
            private $constantName;
303
304 3
            /** @var Node\Stmt\Const_|Node\Expr\FuncCall|null */
305
            private $node;
306 3
307 3
            public function enterNode(Node $node) : ?int
308
            {
309 3
                if ($node instanceof Node\Stmt\Const_) {
310 1
                    foreach ($node->consts as $constNode) {
311
                        /** @psalm-suppress UndefinedPropertyFetch */
312 1
                        if ($constNode->namespacedName->toString() === $this->constantName) {
313
                            $this->node = $node;
314
315
                            return NodeTraverser::STOP_TRAVERSAL;
316 3
                        }
317
                    }
318
319 3
                    return NodeTraverser::DONT_TRAVERSE_CHILDREN;
320
                }
321 3
322 3
                if ($node instanceof Node\Expr\FuncCall) {
323 3
                    try {
324
                        ConstantNodeChecker::assertValidDefineFunctionCall($node);
325
                    } catch (InvalidConstantNode $e) {
326 3
                        return null;
327 3
                    }
328
329 3
                    $nameNode = $node->args[0]->value;
330 2
                    assert($nameNode instanceof Node\Scalar\String_);
331
332 2
                    if ($nameNode->value === $this->constantName) {
333
                        $this->node = $node;
334
335
                        return NodeTraverser::STOP_TRAVERSAL;
336 3
                    }
337 3
                }
338
339
                if ($node instanceof Node\Stmt\Class_) {
340 3
                    return NodeTraverser::DONT_TRAVERSE_CHILDREN;
341
                }
342
343 3
                return null;
344
            }
345 3
346 3
            public function setConstantName(string $constantName) : void
347
            {
348
                $this->constantName = $constantName;
349
            }
350
351 3
            /**
352
             * @return Node\Stmt\Const_|Node\Expr\FuncCall|null
353 3
             */
354
            public function getNode() : ?Node
355
            {
356
                return $this->node;
357
            }
358
        };
359
    }
360
}
361