Issues (135)

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 (5 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;
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
        if (! array_key_exists($constantName, get_defined_constants(true)['user'])) {
214 1
            return null;
215
        }
216
217
        /** @psalm-suppress UndefinedMethod */
218 3
        $this->constantVisitor->setConstantName($constantName);
219
220 3
        $constantFileName = null;
221
222 3
        foreach (get_included_files() as $includedFileName) {
223 3
            $ast = $this->phpParser->parse(file_get_contents($includedFileName));
224
225 3
            $this->nodeTraverser->traverse($ast);
226
227
            /** @psalm-suppress UndefinedMethod */
228 3
            if ($this->constantVisitor->getNode() !== null) {
229 3
                $constantFileName = $includedFileName;
230 3
                break;
231
            }
232
        }
233
234 3
        return $constantFileName;
235
    }
236
237
    /**
238
     * Our wrapper simply records which file we tried to load and returns
239
     * boolean false indicating failure.
240
     *
241
     * @see https://php.net/manual/en/class.streamwrapper.php
242
     * @see https://php.net/manual/en/streamwrapper.stream-open.php
243
     *
244
     * @param string $path
245
     * @param string $mode
246
     * @param int    $options
247
     * @param string $opened_path
248
     *
249
     * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
250
     */
251 4
    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...
252
    {
253 4
        self::$autoloadLocatedFile = $path;
254
255 4
        return false;
256
    }
257
258
    /**
259
     * url_stat is triggered by calls like "file_exists". The call to "file_exists" must not be overloaded.
260
     * This function restores the original "file" stream, issues a call to "stat" to get the real results,
261
     * and then re-registers the AutoloadSourceLocator stream wrapper.
262
     *
263
     * @see https://php.net/manual/en/class.streamwrapper.php
264
     * @see https://php.net/manual/en/streamwrapper.url-stat.php
265
     *
266
     * @param string $path
267
     * @param int    $flags
268
     *
269
     * @return mixed[]|bool
270
     *
271
     * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
272
     */
273 4
    public function url_stat($path, $flags)
274
    {
275 4
        stream_wrapper_restore('file');
276
277 4
        if ($flags & STREAM_URL_STAT_QUIET) {
278
            set_error_handler(static function () {
279
                // Use native error handler
280 1
                return false;
281 4
            });
282 4
            $result = @stat($path);
283 4
            restore_error_handler();
284
        } else {
285
            $result = stat($path);
286
        }
287
288 4
        stream_wrapper_unregister('file');
289 4
        stream_wrapper_register('file', self::class);
290
291 4
        return $result;
292
    }
293
294
    private function createConstantVisitor() : NodeVisitorAbstract
295
    {
296
        return new class() extends NodeVisitorAbstract
297
        {
298
            /** @var string|null */
299
            private $constantName;
300
301
            /** @var Node\Stmt\Const_|Node\Expr\FuncCall|null */
302
            private $node;
303
304 3
            public function enterNode(Node $node) : ?int
305
            {
306 3
                if ($node instanceof Node\Stmt\Const_) {
307 3
                    foreach ($node->consts as $constNode) {
308
                        /** @psalm-suppress UndefinedPropertyFetch */
309 3
                        if ($constNode->namespacedName->toString() === $this->constantName) {
310 1
                            $this->node = $node;
311
312 1
                            return NodeTraverser::STOP_TRAVERSAL;
313
                        }
314
                    }
315
316 3
                    return NodeTraverser::DONT_TRAVERSE_CHILDREN;
317
                }
318
319 3
                if ($node instanceof Node\Expr\FuncCall) {
320
                    try {
321 3
                        ConstantNodeChecker::assertValidDefineFunctionCall($node);
322 3
                    } catch (InvalidConstantNode $e) {
323 3
                        return null;
324
                    }
325
326 3
                    $nameNode = $node->args[0]->value;
327 3
                    assert($nameNode instanceof Node\Scalar\String_);
328
329 3
                    if ($nameNode->value === $this->constantName) {
330 2
                        $this->node = $node;
331
332 2
                        return NodeTraverser::STOP_TRAVERSAL;
333
                    }
334
                }
335
336 3
                if ($node instanceof Node\Stmt\Class_) {
337 3
                    return NodeTraverser::DONT_TRAVERSE_CHILDREN;
338
                }
339
340 3
                return null;
341
            }
342
343 3
            public function setConstantName(string $constantName) : void
344
            {
345 3
                $this->constantName = $constantName;
346 3
            }
347
348
            /**
349
             * @return Node\Stmt\Const_|Node\Expr\FuncCall|null
350
             */
351 3
            public function getNode() : ?Node
352
            {
353 3
                return $this->node;
354
            }
355
        };
356
    }
357
}
358