Issues (10)

Security Analysis    not enabled

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/Http/Request.php (8 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 PHPFastCGI\FastCGIDaemon\Http;
6
7
use Nyholm\Psr7Server\ServerRequestCreatorInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Symfony\Component\HttpFoundation\Request as HttpFoundationRequest;
10
11
/**
12
 * The default implementation of the RequestInterface.
13
 */
14
final class Request implements RequestInterface
15
{
16
    /**
17
     * @var ServerRequestCreatorInterface|null
18
     */
19
    private static $serverRequestCreator = null;
20
21
    /**
22
     * @var int
23
     */
24
    private static $bufferSize = 10485760; // 10 MB
25
26
    /**
27
     * @var string
28
     */
29
    private static $uploadDir = null;
30
31
    /**
32
     * @var array
33
     */
34
    private $uploadedFiles = [];
35
36
    /**
37
     * @var array
38
     */
39
    private $params;
40
41
    /**
42
     * @var resource
43
     */
44
    private $stdin;
45
46
    /**
47
     * Constructor.
48
     *
49
     * @param array    $params The FastCGI server params as an associative array
50
     * @param resource $stdin  The FastCGI stdin data as a stream resource
51
     */
52
    public function __construct(array $params, $stdin)
53
    {
54
        $this->params = [];
55
56
        foreach ($params as $name => $value) {
57
            $this->params[strtoupper($name)] = $value;
58
        }
59
60
        $this->stdin  = $stdin;
61
62
        rewind($this->stdin);
63
    }
64
65
    public static function setServerRequestCreator(ServerRequestCreatorInterface $serverRequestCreator): void
66
    {
67
        self::$serverRequestCreator = $serverRequestCreator;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function getParams(): array
74
    {
75
        return $this->params;
76
    }
77
78
    /**
79
     * Remove all uploaded files
80
     */
81
    public function cleanUploadedFiles(): void
82
    {
83
        foreach ($this->uploadedFiles as $file) {
84
            @unlink($file['tmp_name']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
85
        }
86
    }
87
88
    /**
89
     * Set a buffer size to read uploaded files
90
     */
91
    public static function setBufferSize(int $size): void
92
    {
93
        static::$bufferSize = $size;
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
94
    }
95
96
    public static function getBufferSize(): int
97
    {
98
        return static::$bufferSize;
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
99
    }
100
101
    public static function setUploadDir(string $dir): void
102
    {
103
        static::$uploadDir = $dir;
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
104
    }
105
106
    public static function getUploadDir(): string
107
    {
108
        return static::$uploadDir ?: sys_get_temp_dir();
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public function getQuery(): array
115
    {
116
        $query = null;
117
118
        if (isset($this->params['QUERY_STRING'])) {
119
            parse_str($this->params['QUERY_STRING'], $query);
120
        }
121
122
        return $query ?: [];
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128
    public function getPost(): array
129
    {
130
        $post = null;
131
132
        if (isset($this->params['REQUEST_METHOD']) && isset($this->params['CONTENT_TYPE'])) {
133
            $requestMethod = $this->params['REQUEST_METHOD'];
134
            $contentType   = $this->params['CONTENT_TYPE'];
135
136
            if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'multipart/form-data') === 0) {
137
                if (preg_match('/boundary=(?P<quote>[\'"]?)(.*)(?P=quote)/', $contentType, $matches)) {
138
                    list($postData, $this->uploadedFiles) = $this->parseMultipartFormData($this->stdin, $matches[2]);
139
                    parse_str($postData, $post);
140
141
                    return $post;
142
                }
143
            }
144
145
            if (strcasecmp($requestMethod, 'POST') === 0 && stripos($contentType, 'application/x-www-form-urlencoded') === 0) {
146
                $postData = stream_get_contents($this->stdin);
147
                rewind($this->stdin);
148
149
                parse_str($postData, $post);
150
            }
151
        }
152
153
        return $post ?: [];
154
    }
155
156
    private function parseMultipartFormData($stream, string $boundary): array {
157
        $post = "";
158
        $files = [];
159
        $fieldType = $fieldName = $filename = $mimeType = null;
160
        $inHeader = $getContent = false;
0 ignored issues
show
$getContent is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
161
162
        while (!feof($stream)) {
163
            $getContent = $fieldName && !$inHeader;
0 ignored issues
show
Bug Best Practice introduced by
The expression $fieldName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
164
            $buffer = stream_get_line($stream, static::$bufferSize,  "\n" . ($getContent ? '--'.$boundary : ''));
0 ignored issues
show
Comprehensibility introduced by
Since PHPFastCGI\FastCGIDaemon\Http\Request is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
165
            $buffer = trim($buffer, "\r");
166
167
            // Find the empty line between headers and body
168
            if ($inHeader && strlen($buffer) == 0) {
169
                $inHeader = false;
170
171
                continue;
172
            }
173
174
            if ($getContent) {
175
                if ($fieldType === 'data') {
176
                    $post .= (isset($post[0]) ? '&' : '') . $fieldName . "=" . urlencode($buffer);
177
                } elseif ($fieldType === 'file' && $filename) {
178
                    $tmpPath = @tempnam($this->getUploadDir(), 'fastcgi_upload');
179
                    $err = file_put_contents($tmpPath, $buffer);
180
                    $this->addFile($files, $fieldName, $filename, $tmpPath, $mimeType, false === $err);
181
                    $filename = $mimeType = null;
182
                }
183
                $fieldName = $fieldType = null;
184
185
                continue;
186
            }
187
188
            // Assert: We may be in the header, lets try to find 'Content-Disposition' and 'Content-Type'.
189
            if (strpos($buffer, 'Content-Disposition') === 0) {
190
                $inHeader = true;
191
                if (preg_match('/name=\"([^\"]*)\"/', $buffer, $matches)) {
192
                    $fieldName = $matches[1];
193
                }
194
                if (preg_match('/filename=\"([^\"]*)\"/', $buffer, $matches)) {
195
                    $filename = $matches[1];
196
                    $fieldType = 'file';
197
                } else {
198
                    $fieldType = 'data';
199
                }
200
            } elseif (strpos($buffer, 'Content-Type') === 0) {
201
                $inHeader = true;
202
                if (preg_match('/Content-Type: (.*)?/', $buffer, $matches)) {
203
                    $mimeType = trim($matches[1]);
204
                }
205
            }
206
        }
207
208
        return [$post, $files];
209
    }
210
211
    /**
212
     * {@inheritdoc}
213
     */
214
    public function getCookies(): array
215
    {
216
        $cookies = [];
217
218
        if (isset($this->params['HTTP_COOKIE'])) {
219
            $cookiePairs = explode(';', $this->params['HTTP_COOKIE']);
220
221
            foreach ($cookiePairs as $cookiePair) {
222
                list($name, $value) = explode('=', trim($cookiePair));
223
                $cookies[$name] = $value;
224
            }
225
        }
226
227
        return $cookies;
228
    }
229
230
    /**
231
     * {@inheritdoc}
232
     */
233
    public function getStdin()
234
    {
235
        return $this->stdin;
236
    }
237
238
    /**
239
     * {@inheritdoc}
240
     */
241
    public function getServerRequest(): ServerRequestInterface
242
    {
243
        if (null === self::$serverRequestCreator) {
244
            throw new \RuntimeException('You need to add an object of \Nyholm\Psr7Server\ServerRequestCreatorInterface to \PHPFastCGI\FastCGIDaemon\Http\Request::setServerRequestCreator to use PSR-7 requests. Please install and read more at https://github.com/nyholm/psr7-server');
245
        }
246
247
        $server  = $this->params;
248
        $query   = $this->getQuery();
249
        $post    = $this->getPost();
250
        $cookies = $this->getCookies();
251
252
        return self::$serverRequestCreator->fromArrays(
253
            $server,
254
            self::$serverRequestCreator->getHeadersFromServer($server),
255
            $cookies,
256
            $query,
257
            $post,
258
            $this->uploadedFiles,
259
            $this->stdin
260
        );
261
262
263
    }
264
265
    /**
266
     * {@inheritdoc}
267
     */
268
    public function getHttpFoundationRequest(): HttpFoundationRequest
269
    {
270
        if (!class_exists(HttpFoundationRequest::class)) {
271
            throw new \RuntimeException('You need to install symfony/http-foundation:^4.0 to use HttpFoundation requests.');
272
        }
273
274
        $query   = $this->getQuery();
275
        $post    = $this->getPost();
276
        $cookies = $this->getCookies();
277
278
        return new HttpFoundationRequest($query, $post, [], $cookies, $this->uploadedFiles, $this->params, $this->stdin);
279
    }
280
281
    /**
282
     * Add a file to the $files array
283
     */
284
    private function addFile(array &$files, string $fieldName, string $filename, string $tmpPath, string $mimeType, bool $err): void
285
    {
286
        $data = [
287
            'type' => $mimeType ?: 'application/octet-stream',
288
            'name' => $filename,
289
            'tmp_name' => $tmpPath,
290
            'error' => $err ? UPLOAD_ERR_CANT_WRITE : UPLOAD_ERR_OK,
291
            'size' => filesize($tmpPath),
292
        ];
293
294
        $parts = preg_split('|(\[[^\]]*\])|', $fieldName, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
295
        $count = count($parts);
296
        if (1 === $count) {
297
            $files[$fieldName] = $data;
298
        } else {
299
            $current = &$files;
300
            foreach ($parts as $i => $part) {
301
                if ($part === '[]') {
302
                    $current[] = $data;
303
                    continue;
304
                }
305
306
                $trimmedMatch = trim($part, '[]');
307
                if ($i === $count -1) {
308
                    $current[$trimmedMatch] = $data;
309
                } else {
310
                    $current = &$current[$trimmedMatch];
311
                }
312
            }
313
        }
314
    }
315
}
316