Issues (18)

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/Updater.php (10 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
 * Humbug
4
 *
5
 * @category   Humbug
6
 * @package    Humbug
7
 * @copyright  Copyright (c) 2015 Pádraic Brady (http://blog.astrumfutura.com)
8
 * @license    https://github.com/padraic/phar-updater/blob/master/LICENSE New BSD License
9
 *
10
 * This class is partially patterned after Composer's self-update.
11
 */
12
13
namespace Humbug\SelfUpdate;
14
15
use Humbug\SelfUpdate\Exception\RuntimeException;
16
use Humbug\SelfUpdate\Exception\InvalidArgumentException;
17
use Humbug\SelfUpdate\Exception\FilesystemException;
18
use Humbug\SelfUpdate\Exception\HttpRequestException;
19
use Humbug\SelfUpdate\Exception\NoSignatureException;
20
use Humbug\SelfUpdate\Strategy\StrategyInterface;
21
use Humbug\SelfUpdate\Strategy\ShaStrategy;
22
use Humbug\SelfUpdate\Strategy\Sha256Strategy;
23
use Humbug\SelfUpdate\Strategy\GithubStrategy;
24
25
class Updater
26
{
27
    const STRATEGY_SHA1 = 'sha1';
28
29
    const STRATEGY_SHA256 = 'sha256';
30
31
    const STRATEGY_GITHUB = 'github';
32
33
    /**
34
     * @var StrategyInterface
35
     */
36
    protected $strategy;
37
38
    /**
39
     * @var string
40
     */
41
    protected $localPharFile;
42
43
    /**
44
     * @var string
45
     */
46
    protected $localPharFileBasename;
47
48
    /**
49
     * @var string
50
     */
51
    protected $localPubKeyFile;
52
53
    /**
54
     * @var bool
55
     */
56
    protected $hasPubKey;
57
58
    /**
59
     * @var string
60
     */
61
    protected $tempDirectory;
62
63
    /**
64
     * @var string
65
     */
66
    protected $newVersion;
67
68
    /**
69
     * @var string
70
     */
71
    protected $oldVersion;
72
73
    /**
74
     * @var string
75
     */
76
    protected $backupExtension = '-old.phar';
77
78
    /**
79
     * @var string
80
     */
81
    protected $backupPath;
82
83
    /**
84
     * @var string
85
     */
86
    protected $restorePath;
87
88
    /**
89
     * @var bool
90
     */
91
    protected $newVersionAvailable;
92
93
    /**
94
     * Constructor
95
     *
96
     * @param string $localPharFile
97
     * @param bool $hasPubKey
98
     * @param string $strategy
99
     */
100
    public function __construct($localPharFile = null, $hasPubKey = true, $strategy = self::STRATEGY_SHA1)
101
    {
102
        ini_set('phar.require_hash', 1);
103
        $this->setLocalPharFile($localPharFile);
104
        if (!is_bool($hasPubKey)) {
105
            throw new InvalidArgumentException(
106
                'Constructor parameter $hasPubKey must be boolean or null.'
107
            );
108
        } else {
109
            $this->hasPubKey = $hasPubKey;
110
        }
111
        if ($this->hasPubKey) {
112
            $this->setLocalPubKeyFile();
113
        }
114
        $this->setTempDirectory();
115
        $this->setStrategy($strategy);
116
    }
117
118
    /**
119
     * Check for update
120
     *
121
     * @return bool
122
     */
123
    public function hasUpdate()
124
    {
125
        $this->newVersionAvailable = $this->newVersionAvailable();
126
        return $this->newVersionAvailable;
127
    }
128
129
    /**
130
     * Perform an update
131
     *
132
     * @return bool
133
     */
134
    public function update()
135
    {
136
        if ($this->newVersionAvailable === false
137
        || (!is_bool($this->newVersionAvailable) && !$this->hasUpdate())) {
138
            return false;
139
        }
140
        $this->backupPhar();
141
        $this->downloadPhar();
142
        $this->replacePhar();
143
        return true;
144
    }
145
146
    /**
147
     * Perform an rollback to previous version
148
     *
149
     * @return bool
150
     */
151
    public function rollback()
152
    {
153
        if (!$this->restorePhar()) {
154
            return false;
155
        }
156
        return true;
157
    }
158
159
    /**
160
     * @param string $strategy
161
     */
162
    public function setStrategy($strategy)
163
    {
164
        switch ($strategy) {
165
            case self::STRATEGY_GITHUB:
166
                $this->strategy = new GithubStrategy;
167
                break;
168
169
            case self::STRATEGY_SHA256:
170
                $this->strategy = new Sha256Strategy;
171
                break;
172
173
            default:
174
                $this->strategy = new ShaStrategy;
0 ignored issues
show
Deprecated Code introduced by
The class Humbug\SelfUpdate\Strategy\ShaStrategy has been deprecated with message: 1.0.4 SHA-1 is increasingly susceptible to collision attacks; use SHA-256

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
175
                break;
176
        }
177
    }
178
179
    public function setStrategyObject(StrategyInterface $strategy)
180
    {
181
        $this->strategy = $strategy;
182
    }
183
184
    public function getStrategy()
185
    {
186
        return $this->strategy;
187
    }
188
189
    /**
190
     * Set backup extension for old phar versions
191
     *
192
     * @param string $extension
193
     */
194
    public function setBackupExtension($extension)
195
    {
196
        $this->backupExtension = $extension;
197
    }
198
199
    /**
200
     * Get backup extension for old phar versions
201
     *
202
     * @return string
203
     */
204
    public function getBackupExtension()
205
    {
206
        return $this->backupExtension;
207
    }
208
209
    public function getLocalPharFile()
210
    {
211
        return $this->localPharFile;
212
    }
213
214
    public function getLocalPharFileBasename()
215
    {
216
        return $this->localPharFileBasename;
217
    }
218
219
    public function getLocalPubKeyFile()
220
    {
221
        return $this->localPubKeyFile;
222
    }
223
224
    public function getTempDirectory()
225
    {
226
        return $this->tempDirectory;
227
    }
228
229
    public function getTempPharFile()
230
    {
231
        return $this->getTempDirectory()
232
            . '/'
233
            . sprintf('%s.phar.temp', $this->getLocalPharFileBasename());
234
    }
235
236
    public function getNewVersion()
237
    {
238
        return $this->newVersion;
239
    }
240
241
    public function getOldVersion()
242
    {
243
        return $this->oldVersion;
244
    }
245
246
    /**
247
     * Set backup path for old phar versions
248
     *
249
     * @param string $filePath
250
     */
251 View Code Duplication
    public function setBackupPath($filePath)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
252
    {
253
        $path = realpath(dirname($filePath));
254
        if (!is_dir($path)) {
255
            throw new FilesystemException(sprintf(
256
                'The backup directory does not exist: %s.', $path
257
            ));
258
        }
259
        if (!is_writable($path)) {
260
            throw new FilesystemException(sprintf(
261
                'The backup directory is not writeable: %s.', $path
262
            ));
263
        }
264
        $this->backupPath = $filePath;
265
    }
266
267
    /**
268
     * Get backup path for old phar versions
269
     *
270
     * @return string
271
     */
272
    public function getBackupPath()
273
    {
274
        return $this->backupPath;
275
    }
276
277
    /**
278
     * Set path for the backup phar to rollback/restore from
279
     *
280
     * @param string $filePath
281
     */
282 View Code Duplication
    public function setRestorePath($filePath)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
283
    {
284
        $path = realpath(dirname($filePath));
285
        if (!file_exists($path)) {
286
            throw new FilesystemException(sprintf(
287
                'The restore phar does not exist: %s.', $path
288
            ));
289
        }
290
        if (!is_readable($path)) {
291
            throw new FilesystemException(sprintf(
292
                'The restore file is not readable: %s.', $path
293
            ));
294
        }
295
        $this->restorePath = $filePath;
296
    }
297
298
    /**
299
     * Get path for the backup phar to rollback/restore from
300
     *
301
     * @return string
302
     */
303
    public function getRestorePath()
304
    {
305
        return $this->restorePath;
306
    }
307
308
    public function throwRuntimeException($errno, $errstr)
309
    {
310
        throw new RuntimeException($errstr);
311
    }
312
313
    public function throwHttpRequestException($errno, $errstr)
314
    {
315
        throw new HttpRequestException($errstr);
316
    }
317
318
    protected function hasPubKey()
319
    {
320
        return $this->hasPubKey;
321
    }
322
323
    protected function newVersionAvailable()
324
    {
325
        $this->newVersion = $this->strategy->getCurrentRemoteVersion($this);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->strategy->getCurrentRemoteVersion($this) can also be of type boolean. However, the property $newVersion is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
326
        $this->oldVersion = $this->strategy->getCurrentLocalVersion($this);
327
328
        if (!empty($this->newVersion) && ($this->newVersion !== $this->oldVersion)) {
329
            return true;
330
        }
331
        return false;
332
    }
333
334
    protected function backupPhar()
335
    {
336
        $result = copy($this->getLocalPharFile(), $this->getBackupPharFile());
337
        if ($result === false) {
338
            $this->cleanupAfterError();
339
            throw new FilesystemException(sprintf(
340
                'Unable to backup %s to %s.',
341
                $this->getLocalPharFile(),
342
                $this->getBackupPharFile()
343
            ));
344
        }
345
    }
346
347
    protected function downloadPhar()
348
    {
349
        $this->strategy->download($this);
350
351
        if (!file_exists($this->getTempPharFile())) {
352
            throw new FilesystemException(
353
                'Creation of download file failed.'
354
            );
355
        }
356
357
        if ($this->getStrategy() instanceof ShaStrategy
358
            || $this->getStrategy() instanceof Sha256Strategy
359
        ) {
360
            if ($this->getStrategy() instanceof ShaStrategy) {
361
                $tmpVersion = sha1_file($this->getTempPharFile());
362
                $algo = 'SHA-1';
363
            } else {
364
                $tmpVersion = hash_file('sha256', $this->getTempPharFile());
365
                $algo = 'SHA-256';
366
            }
367
            if ($tmpVersion !== $this->getNewVersion()) {
368
                $this->cleanupAfterError();
369
                throw new HttpRequestException(sprintf(
370
                    'Download file appears to be corrupted or outdated. The file '
371
                        . 'received does not have the expected %s hash: %s.',
372
                    $algo,
373
                    $this->getNewVersion()
374
                ));
375
            }
376
        }
377
378
        try {
379
            $this->validatePhar($this->getTempPharFile());
380
        } catch (\Exception $e) {
381
            restore_error_handler();
382
            $this->cleanupAfterError();
383
            throw $e;
384
        }
385
    }
386
387
    protected function replacePhar()
388
    {
389
        rename($this->getTempPharFile(), $this->getLocalPharFile());
390
    }
391
392
    protected function restorePhar()
393
    {
394
        $backup = $this->getRestorePharFile();
395
        if (!file_exists($backup)) {
396
            throw new RuntimeException(sprintf(
397
                'The backup file does not exist: %s.', $backup
398
            ));
399
        }
400
        $this->validatePhar($backup);
401
        return rename($backup, $this->getLocalPharFile());
402
    }
403
404 View Code Duplication
    protected function getBackupPharFile()
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
405
    {
406
        if (null !== $this->getBackupPath()) {
407
            return $this->getBackupPath();
408
        }
409
        return $this->getTempDirectory()
410
            . '/'
411
            . sprintf('%s%s', $this->getLocalPharFileBasename(), $this->getBackupExtension());
412
    }
413
414 View Code Duplication
    protected function getRestorePharFile()
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
415
    {
416
        if (null !== $this->getRestorePath()) {
417
            return $this->getRestorePath();
418
        }
419
        return $this->getTempDirectory()
420
            . '/'
421
            . sprintf('%s%s', $this->getLocalPharFileBasename(), $this->getBackupExtension()
422
        );
423
    }
424
425
    protected function getTempPubKeyFile()
426
    {
427
        return $this->getTempDirectory()
428
            . '/'
429
            . sprintf('%s.phar.temp.pubkey', $this->getLocalPharFileBasename());
430
    }
431
432
    protected function setLocalPharFile($localPharFile)
0 ignored issues
show
setLocalPharFile uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
433
    {
434
        if (!is_null($localPharFile)) {
435
            $localPharFile = realpath($localPharFile);
436
        } else {
437
            $localPharFile = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
438
        }
439
        if (!file_exists($localPharFile)) {
440
            throw new RuntimeException(sprintf(
441
                'The set phar file does not exist: %s.', $localPharFile
442
            ));
443
        }
444
        if (!is_writable($localPharFile)) {
445
            throw new FilesystemException(sprintf(
446
                'The current phar file is not writeable and cannot be replaced: %s.',
447
                $localPharFile
448
            ));
449
        }
450
        $this->localPharFile = $localPharFile;
451
        $this->localPharFileBasename = basename($localPharFile, '.phar');
452
    }
453
454
    protected function setLocalPubKeyFile()
455
    {
456
        $localPubKeyFile = $this->getLocalPharFile() . '.pubkey';
457
        if (!file_exists($localPubKeyFile)) {
458
            throw new RuntimeException(sprintf(
459
                'The phar pubkey file does not exist: %s.', $localPubKeyFile
460
            ));
461
        }
462
        $this->localPubKeyFile = $localPubKeyFile;
463
    }
464
465
    protected function setTempDirectory()
466
    {
467
        $tempDirectory = dirname($this->getLocalPharFile());
468
        if (!is_writable($tempDirectory)) {
469
            throw new FilesystemException(sprintf(
470
                'The directory is not writeable: %s.', $tempDirectory
471
            ));
472
        }
473
        $this->tempDirectory = $tempDirectory;
474
    }
475
476
    protected function validatePhar($phar)
477
    {
478
        $phar = realpath($phar);
479
        if ($this->hasPubKey()) {
480
            copy($this->getLocalPubKeyFile(), $phar . '.pubkey');
481
        }
482
        chmod($phar, fileperms($this->getLocalPharFile()));
483
        /** Switch invalid key errors to RuntimeExceptions */
484
        set_error_handler(array($this, 'throwRuntimeException'));
485
        $phar = new \Phar($phar);
486
        $signature = $phar->getSignature();
487
        if ($this->hasPubKey() && strtolower($signature['hash_type']) !== 'openssl') {
488
            throw new NoSignatureException(
489
                'The downloaded phar file has no OpenSSL signature.'
490
            );
491
        }
492
        restore_error_handler();
493
        if ($this->hasPubKey()) {
494
            @unlink($phar . '.pubkey');
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...
495
        }
496
        unset($phar);
497
    }
498
499
    protected function cleanupAfterError()
500
    {
501
        //@unlink($this->getBackupPharFile());
502
        @unlink($this->getTempPharFile());
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...
503
        @unlink($this->getTempPubKeyFile());
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...
504
    }
505
}
506