Issues (45)

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/Wrapped/Parser.php (9 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
 * Copyright (c) 2014 Robin Appelman <[email protected]>
4
 * This file is licensed under the Licensed under the MIT license:
5
 * http://opensource.org/licenses/MIT
6
 */
7
8
namespace Icewind\SMB\Wrapped;
9
10
use Icewind\SMB\ACL;
11
use Icewind\SMB\Exception\AccessDeniedException;
12
use Icewind\SMB\Exception\AlreadyExistsException;
13
use Icewind\SMB\Exception\AuthenticationException;
14
use Icewind\SMB\Exception\Exception;
15
use Icewind\SMB\Exception\FileInUseException;
16
use Icewind\SMB\Exception\InvalidHostException;
17
use Icewind\SMB\Exception\InvalidParameterException;
18
use Icewind\SMB\Exception\InvalidResourceException;
19
use Icewind\SMB\Exception\InvalidTypeException;
20
use Icewind\SMB\Exception\NoLoginServerException;
21
use Icewind\SMB\Exception\NotEmptyException;
22
use Icewind\SMB\Exception\NotFoundException;
23
24
class Parser {
25
	const MSG_NOT_FOUND = 'Error opening local file ';
26
27
	/**
28
	 * @var string
29
	 */
30
	protected $timeZone;
31
32
	// see error.h
33
	const EXCEPTION_MAP = [
34
		ErrorCodes::LogonFailure      => AuthenticationException::class,
35
		ErrorCodes::PathNotFound      => NotFoundException::class,
36
		ErrorCodes::ObjectNotFound    => NotFoundException::class,
37
		ErrorCodes::NoSuchFile        => NotFoundException::class,
38
		ErrorCodes::NameCollision     => AlreadyExistsException::class,
39
		ErrorCodes::AccessDenied      => AccessDeniedException::class,
40
		ErrorCodes::DirectoryNotEmpty => NotEmptyException::class,
41
		ErrorCodes::FileIsADirectory  => InvalidTypeException::class,
42
		ErrorCodes::NotADirectory     => InvalidTypeException::class,
43
		ErrorCodes::SharingViolation  => FileInUseException::class,
44
		ErrorCodes::InvalidParameter  => InvalidParameterException::class
45
	];
46
47
	const MODE_STRINGS = [
48
		'R' => FileInfo::MODE_READONLY,
49
		'H' => FileInfo::MODE_HIDDEN,
50
		'S' => FileInfo::MODE_SYSTEM,
51
		'D' => FileInfo::MODE_DIRECTORY,
52
		'A' => FileInfo::MODE_ARCHIVE,
53
		'N' => FileInfo::MODE_NORMAL
54
	];
55
56
	/**
57
	 * @param string $timeZone
58
	 */
59
	public function __construct(string $timeZone) {
60
		$this->timeZone = $timeZone;
61
	}
62
63 542
	private function getErrorCode(string $line): ?string {
64 542
		$parts = explode(' ', $line);
65 542
		foreach ($parts as $part) {
66
			if (substr($part, 0, 9) === 'NT_STATUS') {
67 38
				return $part;
68 38
			}
69 38
		}
70 38
		return null;
71 38
	}
72
73
	/**
74 2
	 * @param string[] $output
75
	 * @param string $path
76
	 * @return no-return
0 ignored issues
show
The doc-type no-return could not be parsed: Unknown type name "no-return" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
77 38
	 * @throws Exception
78 38
	 * @throws InvalidResourceException
79
	 * @throws NotFoundException
80
	 */
81 38
	public function checkForError(array $output, string $path): void {
82
		if (strpos($output[0], 'does not exist')) {
83 38
			throw new NotFoundException($path);
84 2
		}
85 2
		$error = $this->getErrorCode($output[0]);
86
87
		if (substr($output[0], 0, strlen(self::MSG_NOT_FOUND)) === self::MSG_NOT_FOUND) {
88 38
			$localPath = substr($output[0], strlen(self::MSG_NOT_FOUND));
89
			throw new InvalidResourceException('Failed opening local file "' . $localPath . '" for writing');
90
		}
91
92
		throw Exception::fromMap(self::EXCEPTION_MAP, $error, $path);
93
	}
94
95
	/**
96
	 * check if the first line holds a connection failure
97
	 *
98
	 * @param string $line
99
	 * @throws AuthenticationException
100 494
	 * @throws InvalidHostException
101 494
	 * @throws NoLoginServerException
102 494
	 * @throws AccessDeniedException
103 2
	 */
104
	public function checkConnectionError(string $line): void {
105 492
		$line = rtrim($line, ')');
106
		if (substr($line, -23) === ErrorCodes::LogonFailure) {
107
			throw new AuthenticationException('Invalid login');
108 492
		}
109 6
		if (substr($line, -26) === ErrorCodes::BadHostName) {
110
			throw new InvalidHostException('Invalid hostname');
111 488
		}
112
		if (substr($line, -22) === ErrorCodes::Unsuccessful) {
113
			throw new InvalidHostException('Connection unsuccessful');
114 488
		}
115
		if (substr($line, -28) === ErrorCodes::ConnectionRefused) {
116
			throw new InvalidHostException('Connection refused');
117 488
		}
118
		if (substr($line, -26) === ErrorCodes::NoLogonServers) {
119
			throw new NoLoginServerException('No login server');
120 488
		}
121
		if (substr($line, -23) === ErrorCodes::AccessDenied) {
122 230
			throw new AccessDeniedException('Access denied');
123 230
		}
124 230
	}
125 230
126 230
	public function parseMode(string $mode): int {
127
		$result = 0;
128
		foreach (self::MODE_STRINGS as $char => $val) {
129 230
			if (strpos($mode, $char) !== false) {
130
				$result |= $val;
131
			}
132 14
		}
133 14
		return $result;
134 14
	}
135
136
	/**
137 14
	 * @param string[] $output
138 14
	 * @return array{"mtime": int, "mode": int, "size": int}
0 ignored issues
show
The doc-type array{"mtime": could not be parsed: Unknown type name "array{"mtime":" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
139 14
	 * @throws Exception
140 14
	 */
141
	public function parseStat(array $output): array {
142 14
		$data = [];
143 14
		foreach ($output as $line) {
144
			// A line = explode statement may not fill all array elements
145
			// properly. May happen when accessing non Windows Fileservers
146
			$words = explode(':', $line, 2);
147 14
			$name = isset($words[0]) ? $words[0] : '';
148 14
			$value = isset($words[1]) ? $words[1] : '';
149 14
			$value = trim($value);
150
151
			if (!isset($data[$name])) {
152
				$data[$name] = $value;
153 488
			}
154
		}
155 488
		$attributeStart = strpos($data['attributes'], '(');
156 488
		if ($attributeStart === false) {
157
			throw new Exception("Malformed state response from server");
158 488
		}
159 488
		return [
160 488
			'mtime' => strtotime($data['write_time']),
161 488
			'mode'  => hexdec(substr($data['attributes'], $attributeStart + 1, -1)),
162 488
			'size'  => isset($data['stream']) ? (int)(explode(' ', $data['stream'])[1]) : 0
163 198
		];
164 198
	}
165 198
166 198
	/**
167
	 * @param string[] $output
168 198
	 * @param string $basePath
169
	 * @param callable(string):ACL[] $aclCallback
0 ignored issues
show
The doc-type callable(string):ACL[] could not be parsed: Expected "|" or "end of type", but got "(" at position 8. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
170
	 * @return FileInfo[]
171
	 */
172 488
	public function parseDir(array $output, string $basePath, callable $aclCallback): array {
173
		//last line is used space
174
		array_pop($output);
175 4
		$regex = '/^\s*(.*?)\s\s\s\s+(?:([NDHARS]*)\s+)?([0-9]+)\s+(.*)$/';
176 4
		//2 spaces, filename, optional type, size, date
177 4
		$content = [];
178 4
		foreach ($output as $line) {
179
			if (preg_match($regex, $line, $matches)) {
180
				list(, $name, $mode, $size, $time) = $matches;
181
				if ($name !== '.' and $name !== '..') {
182
					$mode = $this->parseMode($mode);
183 4
					$time = strtotime($time . ' ' . $this->timeZone);
184
					$path = $basePath . '/' . $name;
185 4
					$content[] = new FileInfo($path, $name, (int)$size, $time, $mode, function () use ($aclCallback, $path): array {
186 4
						return $aclCallback($path);
187
					});
188
				}
189 4
			}
190
		}
191
		return $content;
192
	}
193
194
	/**
195
	 * @param string[] $output
196
	 * @return array<string, string>
0 ignored issues
show
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
197
	 */
198
	public function parseListShares(array $output): array {
199
		$shareNames = [];
200
		foreach ($output as $line) {
201
			if (strpos($line, '|')) {
202
				list($type, $name, $description) = explode('|', $line);
203
				if (strtolower($type) === 'disk') {
204
					$shareNames[$name] = $description;
205
				}
206
			} elseif (strpos($line, 'Disk')) {
207
				// new output format
208
				list($name, $description) = explode('Disk', $line);
209
				$shareNames[trim($name)] = trim($description);
210
			}
211
		}
212
		return $shareNames;
213
	}
214
215
	/**
216
	 * @param string[] $rawAcls
217
	 * @return ACL[]
218
	 */
219
	public function parseACLs(array $rawAcls): array {
220
		$acls = [];
221
		foreach ($rawAcls as $acl) {
222
			if (strpos($acl, ':') === false) {
223
				continue;
224
			}
225
			[$type, $acl] = explode(':', $acl, 2);
0 ignored issues
show
The variable $type does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
226
			if ($type !== 'ACL') {
227
				continue;
228
			}
229
			[$user, $permissions] = explode(':', $acl, 2);
0 ignored issues
show
The variable $permissions does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
The variable $user does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
230
			[$type, $flags, $mask] = explode('/', $permissions);
0 ignored issues
show
The variable $flags does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
The variable $mask does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
231
232
			$type = $type === 'ALLOWED' ? ACL::TYPE_ALLOW : ACL::TYPE_DENY;
233
234
			$flagsInt = 0;
235
			foreach (explode('|', $flags) as $flagString) {
236
				if ($flagString === 'OI') {
237
					$flagsInt += ACL::FLAG_OBJECT_INHERIT;
238
				} elseif ($flagString === 'CI') {
239
					$flagsInt += ACL::FLAG_CONTAINER_INHERIT;
240
				}
241
			}
242
243
			if (substr($mask, 0, 2) === '0x') {
244
				$maskInt = hexdec($mask);
245
			} else {
246
				$maskInt = 0;
247
				foreach (explode('|', $mask) as $maskString) {
248
					if ($maskString === 'R') {
249
						$maskInt += ACL::MASK_READ;
250
					} elseif ($maskString === 'W') {
251
						$maskInt += ACL::MASK_WRITE;
252
					} elseif ($maskString === 'X') {
253
						$maskInt += ACL::MASK_EXECUTE;
254
					} elseif ($maskString === 'D') {
255
						$maskInt += ACL::MASK_DELETE;
256
					} elseif ($maskString === 'READ') {
257
						$maskInt += ACL::MASK_READ + ACL::MASK_EXECUTE;
258
					} elseif ($maskString === 'CHANGE') {
259
						$maskInt += ACL::MASK_READ + ACL::MASK_EXECUTE + ACL::MASK_WRITE + ACL::MASK_DELETE;
260
					} elseif ($maskString === 'FULL') {
261
						$maskInt += ACL::MASK_READ + ACL::MASK_EXECUTE + ACL::MASK_WRITE + ACL::MASK_DELETE;
262
					}
263
				}
264
			}
265
266
			if (isset($acls[$user])) {
267
				$existing = $acls[$user];
268
				$maskInt += $existing->getMask();
269
			}
270
			$acls[$user] = new ACL($type, $flagsInt, $maskInt);
271
		}
272
273
		ksort($acls);
274
275
		return $acls;
276
	}
277
}
278