default services conflit ?

This commit is contained in:
armansansd
2022-04-27 11:30:43 +02:00
parent 28190a5749
commit 8bb1064a3b
8132 changed files with 900138 additions and 426 deletions

View File

@@ -0,0 +1,60 @@
# Release Notes
## [Unreleased](https://github.com/enlightn/security-checker/compare/v1.9.0...master)
## [v1.9.0 (2021-05-06)](https://github.com/enlightn/security-checker/compare/v1.8.0...v1.9.0)
### Added
- Add allow list option to exclude vulnerabilities by CVE or title ([#21](https://github.com/enlightn/security-checker/pull/21))
## [v1.8.0 (2021-04-19)](https://github.com/enlightn/security-checker/compare/v1.7.0...v1.8.0)
### Changed
- Drop ext-zip requirement via unzip command ([#19](https://github.com/enlightn/security-checker/pull/19))
## [v1.7.0 (2021-03-03)](https://github.com/enlightn/security-checker/compare/v1.6.1...v1.7.0)
### Added
- Add option to specify a custom temp directory for caching the advisories database ([#18](https://github.com/enlightn/security-checker/pull/18))
## [v1.6.1 (2021-02-24)](https://github.com/enlightn/security-checker/compare/v1.6.0...v1.6.1)
### Fixed
- Fix --no-dev input option ([#16](https://github.com/enlightn/security-checker/pull/16))
## [v1.6.0 (2021-02-24)](https://github.com/enlightn/security-checker/compare/v1.5.1...v1.6.0)
### Added
- Add option to exclude dev dependencies from scanning ([#14](https://github.com/enlightn/security-checker/pull/14))
## [v1.5.1 (2021-02-17)](https://github.com/enlightn/security-checker/compare/v1.5.0...v1.5.1)
### Fixed
- Fix advisory analyzer for dev package dependencies ([#12](https://github.com/enlightn/security-checker/pull/12))
## [v1.5.0 (2021-02-09)](https://github.com/enlightn/security-checker/compare/v1.4...v1.5.0)
### Added
- Improve installation instructions with Composer links ([#9](https://github.com/enlightn/security-checker/pull/9))
- Support multiple formats: ANSI and JSON ([#8](https://github.com/enlightn/security-checker/pull/8))
## [v1.4 (2021-02-01)](https://github.com/enlightn/security-checker/compare/v1.3...v1.4)
### Added
- Support PHP 5.6 ([#6](https://github.com/enlightn/security-checker/pull/6))
## [v1.3 (2021-01-28)](https://github.com/enlightn/security-checker/compare/v1.2...v1.3)
### Added
- Add simplified API ([#4](https://github.com/enlightn/security-checker/pull/4))
## [v1.2 (2021-01-27)](https://github.com/enlightn/security-checker/compare/v1.1...v1.2)
### Changed
- Improve JSON output ([#3](https://github.com/enlightn/security-checker/pull/3))
- Fix requirements to allow supported versions of symfony and guzzle ([#2](https://github.com/enlightn/security-checker/pull/2))
## [v1.1 (2021-01-19)](https://github.com/enlightn/security-checker/compare/v1.0...v1.1)
### Changed
- Make json format of analyzer consistent ([d4487a7](https://github.com/enlightn/security-checker/commit/d4487a7881ce2a438c3199e7f158dd10bdb66ede))

View File

@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at paras@laravel-enlightn.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@@ -0,0 +1,25 @@
The MIT License (MIT)
=====================
Copyright © Enlightn Software
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,111 @@
# Enlightn Security Checker
![tests](https://github.com/enlightn/security-checker/workflows/tests/badge.svg?branch=main)
[![MIT Licensed](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
[![Latest Stable Version](https://poser.pugx.org/enlightn/security-checker/v/stable?format=flat-square)](https://packagist.org/packages/enlightn/security-checker)
[![Total Downloads](https://img.shields.io/packagist/dt/enlightn/security-checker.svg?style=flat-square)](https://packagist.org/packages/enlightn/security-checker)
The Enlightn Security Checker is a command line tool that checks if your
application uses dependencies with known security vulnerabilities. It uses the [Security Advisories Database](https://github.com/FriendsOfPHP/security-advisories).
## Installation Options
1. You may install the Enlightn Security Checker with Composer globally, for use with multiple projects:
```bash
composer global require enlightn/security-checker
```
2. You may also install the Enlightn Security Checker in your project as a dev dependency using Composer:
```bash
composer require --dev enlightn/security-checker
```
3. Instead of installing via Composer, you may also download the [security-checker.phar](https://www.laravel-enlightn.com/security-checker.phar) file. Then, in the commands below you can replace `security-checker` with `security-checker.phar`.
## Usage
To check for security vulnerabilities in your dependencies, you may run the `security:check` command:
```bash
php security-checker security:check /path/to/composer.lock
```
This command will return a success status code of `0` if there are no vulnerabilities and `1` if there is at least one vulnerability.
**Note**: You would need to provide the full path of the security-checker executable if the directory is not in your path. For instance:
```bash
php vendor/bin/security-checker security:check /path/to/composer.lock
```
## Options
### Format
By default, this command displays the result in ANSI. You may use the `--format` option to display the result in JSON instead:
```bash
php security-checker security:check /path/to/composer.lock --format=json
```
### Exclude Dev Dependencies
If you would like to exclude dev dependencies from the vulnerabilities scanning, you may use the `--no-dev` option (defaults to false):
```bash
php security-checker security:check /path/to/composer.lock --no-dev
```
### Allow vulnerabilities
If you would like to exclude some vulnerabilities, you may use the `--allow-list` option by passing the CVE identifier, or the CVE title. You can pass multiple values as well:
```bash
php security-checker security:check /path/to/composer.lock --allow-list CVE-2018-15133 --allow-list "untrusted X-XSRF-TOKEN value"
```
Do not forget to wrap the title with quotes
### Custom Directory for Caching Advisories Database
By default, the `SecurityChecker` API and the `security:check` command use the directory returned by the `sys_get_temp_dir` PHP function for storing the cached advisories database. If you wish to modify the directory, you may use the `--temp-dir` option:
```bash
php security-checker security:check /path/to/composer.lock --temp-dir=/tmp
```
## API
You may also use the API directly in your own code like so:
```php
use Enlightn\SecurityChecker\SecurityChecker;
$result = (new SecurityChecker)->check('/path/to/composer.lock');
```
The result above is an associative array. The key is the package name and the value is an array of vulnerabilities based on your package version. An example of the JSON encoded version is as below:
```json
{
"laravel/framework": {
"version": "8.22.0",
"time": "2021-01-13T13:37:56+00:00",
"advisories": [{
"title": "Unexpected bindings in QueryBuilder",
"link": "https://blog.laravel.com/security-laravel-62011-7302-8221-released",
"cve": null
}]
}
}
```
## Contribution Guide
Thank you for considering contributing to the Enlightn security-checker project! The contribution guide can be found [here](https://www.laravel-enlightn.com/docs/getting-started/contribution-guide.html).
## License
The Enlightn security checkers licensed under the [MIT license](LICENSE.md).

View File

@@ -0,0 +1,7 @@
# Security Policy
**PLEASE DON'T DISCLOSE SECURITY-RELATED ISSUES PUBLICLY, [SEE BELOW](#reporting-a-vulnerability).**
## Reporting a Vulnerability
If you discover a security vulnerability within the Enlightn security-checker project, please send an email to Paras Malhotra at paras@laravel-enlightn.com. All security vulnerabilities will be promptly addressed.

View File

@@ -0,0 +1,23 @@
{
"output": "security-checker.phar",
"chmod": "0755",
"compactors": [
"KevinGH\\Box\\Compactor\\Php"
],
"main": "security-checker",
"files": [
"LICENSE.md"
],
"finder": [
{
"name": "*.*",
"exclude": ["Tests"],
"in": "vendor"
},
{
"name": ["*.*"],
"in": "src"
}
],
"stub": true
}

View File

@@ -0,0 +1,61 @@
{
"name": "enlightn/security-checker",
"description": "A PHP dependency vulnerabilities scanner based on the Security Advisories Database.",
"type": "library",
"keywords": [
"php",
"package",
"security",
"scanner",
"vulnerability scanner",
"security advisories"
],
"license": "MIT",
"authors": [
{
"name": "Paras Malhotra",
"email": "paras@laravel-enlightn.com"
},
{
"name": "Miguel Piedrafita",
"email": "soy@miguelpiedrafita.com"
}
],
"support": {
"issues": "https://github.com/enlightn/security-checker/issues"
},
"require": {
"php": ">=5.6",
"ext-json": "*",
"symfony/console": "^3.4|^4|^5|^6",
"symfony/finder": "^3|^4|^5|^6",
"symfony/process": "^3.4|^4|^5|^6",
"symfony/yaml": "^3.4|^4|^5|^6",
"guzzlehttp/guzzle": "^6.3|^7.0"
},
"require-dev": {
"ext-zip" : "*",
"friendsofphp/php-cs-fixer": "^2.18|^3.0",
"phpunit/phpunit": "^5.5|^6|^7|^8|^9"
},
"bin": ["security-checker"],
"autoload": {
"psr-4": {
"Enlightn\\SecurityChecker\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Enlightn\\SecurityChecker\\Tests\\": "tests"
}
},
"scripts": {
"test": "vendor/bin/phpunit --colors=always",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage"
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
}

View File

@@ -0,0 +1,22 @@
#!/usr/bin/env php
<?php
function includeIfExists($file)
{
if (file_exists($file)) {
return include $file;
}
}
if ((!$loader = includeIfExists(__DIR__.'/vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../autoload.php'))) {
die('You must have Composer installed and must run the composer install CLI command.'.PHP_EOL.
'Download Composer from the website: https://getcomposer.org/download/'.PHP_EOL.
'Then, run the "composer install" command.'.PHP_EOL);
}
use Enlightn\SecurityChecker\SecurityCheckerCommand;
use Symfony\Component\Console\Application;
$console = new Application('Enlightn Security Checker');
$console->add(new SecurityCheckerCommand);
$console->run();

View File

@@ -0,0 +1,111 @@
<?php
namespace Enlightn\SecurityChecker;
class AdvisoryAnalyzer
{
/**
* @var array
*/
private $advisories;
public function __construct($advisories)
{
$this->advisories = $advisories;
}
/**
* Returns an array of vulnerabilities for the given package and version.
*
* @param string $package
* @param string $version
* @param string|null|int $time
* @return array
*/
public function analyzeDependency($package, $version, $time = null)
{
if (! isset($this->advisories[$package])) {
return [];
}
$vulnerabilities = [];
if (is_string($time)) {
$time = strtotime($time) ?: null;
}
foreach ($this->advisories[$package] as $advisory) {
$packageBranchName = $this->normalizeVersion($version);
foreach ($advisory['branches'] as $branch => $versionInfo) {
if ($this->isDevPackage($version)) {
$branchName = preg_replace('/.x$/', '', $branch);
if ($branchName !== $packageBranchName) {
continue;
}
if (is_null($time) || is_null($versionInfo['time']) || $time > $versionInfo['time']) {
continue;
}
} else {
$passed = false;
foreach ($versionInfo['versions'] as $versionConstraint) {
$constrainedVersion = str_replace(['>', '<', '='], '', $versionConstraint);
$operator = str_replace($constrainedVersion, '', $versionConstraint) ?: '=';
if (version_compare($version, $constrainedVersion, $operator)) {
continue;
} else {
$passed = true;
break;
}
}
if ($passed) {
continue;
}
}
$vulnerabilities[] = [
'title' => isset($advisory['title']) ? $advisory['title'] : null,
'link' => isset($advisory['link']) ? $advisory['link'] : null,
'cve' => isset($advisory['cve']) ? $advisory['cve'] : null,
];
}
}
return $vulnerabilities;
}
public function analyzeDependencies($dependencies)
{
$vulnerabilities = [];
foreach ($dependencies as $package => $versionInfo) {
$advisories = $this->analyzeDependency($package, $versionInfo['version'], $versionInfo['time']);
if (! empty($advisories)) {
$vulnerabilities[$package] = [
'version' => $versionInfo['version'],
'time' => $versionInfo['time'],
'advisories' => $advisories,
];
}
}
return $vulnerabilities;
}
protected function normalizeVersion($version)
{
return preg_replace(['/-dev$/', '/^dev-/'], '', $version);
}
protected function isDevPackage($version)
{
return ! is_null(preg_filter(['/-dev$/', '/^dev-/'], '', $version));
}
}

View File

@@ -0,0 +1,137 @@
<?php
namespace Enlightn\SecurityChecker;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
class AdvisoryFetcher
{
/**
* @var \GuzzleHttp\Client
*/
private $client;
/**
* @var string
*/
private $tempDir;
const ADVISORIES_URL = 'https://codeload.github.com/FriendsOfPHP/security-advisories/zip/master';
const CACHE_FILE_NAME = 'php_security_advisories.json';
const ARCHIVE_FILE_NAME = 'php_security_advisories.zip';
const EXTRACT_PATH = 'php_security_advisories';
public function __construct($tempDir = null)
{
$this->client = new Client();
$this->tempDir = is_null($tempDir) ? sys_get_temp_dir() : $tempDir;
}
/**
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function fetchAdvisories()
{
$archivePath = $this->fetchAdvisoriesArchive();
(new Filesystem)->deleteDirectory($extractPath = $this->getExtractDirectoryPath());
$zip = new ZipExtractor;
$zip->extract($archivePath, $extractPath);
return $extractPath;
}
/**
* @return string
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function fetchAdvisoriesArchive()
{
$headers = [];
$cacheResult = [];
if (! empty($cache = $this->getCacheFile())) {
$cacheResult = json_decode($cache, true);
if (is_file($cacheResult['ArchivePath'])) {
// Set cache headers only if both the cache file and archive file exist.
$headers = [
'If-None-Match' => $cacheResult['Key'],
'If-Modified-Since' => $cacheResult['Date'],
];
}
}
$response = $this->client->get(self::ADVISORIES_URL, [
'headers' => $headers,
]);
if ($response->getStatusCode() !== 304) {
$this->writeCacheFile($response);
$this->storeAdvisoriesArchive((string) $response->getBody());
return $this->getArchiveFilePath();
}
// If a 304 Not Modified header is found, simply rely on the cached archive file.
return $cacheResult['ArchivePath'];
}
/**
* @param string $content
* @return false|int
*/
public function storeAdvisoriesArchive($content)
{
return file_put_contents($this->getArchiveFilePath(), $content);
}
/**
* @return false|string|null
*/
public function getCacheFile()
{
if (! is_file($path = $this->getCacheFilePath())) {
return null;
}
return file_get_contents($path);
}
public function getCacheFilePath()
{
return $this->tempDir.DIRECTORY_SEPARATOR.self::CACHE_FILE_NAME;
}
public function getArchiveFilePath()
{
return $this->tempDir.DIRECTORY_SEPARATOR.self::ARCHIVE_FILE_NAME;
}
public function getExtractDirectoryPath()
{
return $this->tempDir.DIRECTORY_SEPARATOR.self::EXTRACT_PATH;
}
public function setClient(Client $client)
{
$this->client = $client;
}
protected function writeCacheFile(ResponseInterface $response)
{
$cache = [
'Key' => $response->getHeader('Etag')[0],
'Date' => $response->getHeader('Date')[0],
'ArchivePath' => $this->getArchiveFilePath(),
];
file_put_contents($this->getCacheFilePath(), json_encode($cache), LOCK_EX);
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Enlightn\SecurityChecker;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Yaml\Yaml;
class AdvisoryParser
{
/**
* @var string
*/
private $advisoriesDirectory;
private $advisories = [];
public function __construct($advisoriesDirectory)
{
$this->advisoriesDirectory = $advisoriesDirectory;
}
public function getAdvisories(array $allowList = [])
{
$files = (new Finder)->in($this->advisoriesDirectory)->files()->name('*.yaml');
foreach ($files as $fileInfo) {
$contents = Yaml::parseFile($fileInfo->getRealPath());
if (isset($contents['cve']) && in_array($contents['cve'], $allowList, true)) {
continue;
}
if (isset($contents['title']) && in_array($contents['title'], $allowList, true)) {
continue;
}
$package = str_replace('composer://', '', $contents['reference']);
unset($contents['reference']);
$this->advisories[$package][] = $contents;
}
return $this->advisories;
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Enlightn\SecurityChecker;
use Exception;
use Symfony\Component\Console\Output\OutputInterface;
class AnsiFormatter implements FormatterInterface
{
/**
* Display the result.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param array $result
* @return void
*/
public function displayResult(OutputInterface $output, array $result)
{
if ($count = count($result)) {
$status = 'CRITICAL';
$style = 'error';
} else {
$status = 'OK';
$style = 'info';
}
$output->writeln(sprintf(
'<%s>[%s] %d %s known vulnerabilities</>',
$style,
$status,
$count,
1 === $count ? 'package has' : 'packages have'
));
if (0 !== $count) {
$output->write("\n");
foreach ($result as $dependency => $issues) {
$dependencyFullName = $dependency.' ('.$issues['version'].')';
$output->writeln('<info>'.$dependencyFullName."\n".str_repeat(
'-',
strlen($dependencyFullName)
)."</>\n");
foreach ($issues['advisories'] as $issue => $details) {
$output->write(' * ');
if (! empty($details['cve'])) {
$output->write('<comment>'.$details['cve'].': </comment>');
}
$output->writeln($details['title']);
if (! empty($details['link'])) {
$output->writeln(' '.$details['link']);
}
$output->writeln('');
}
}
}
}
/**
* Display the error.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Exception $exception
* @return void
*/
public function displayError(OutputInterface $output, Exception $exception)
{
$output->writeln(sprintf(
'<error>[ERROR] Vulnerabilities scan failed with exception: %s</error>',
$exception->getMessage()
));
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Enlightn\SecurityChecker;
use RuntimeException;
class Composer
{
/**
* @param string $composerLockPath
* @param false $excludeDev
* @return array
*/
public function getDependencies($composerLockPath, $excludeDev = false)
{
if (! is_file($composerLockPath)) {
throw new RuntimeException("File not found at [$composerLockPath]");
}
if (! ($lockFileContent = file_get_contents($composerLockPath))) {
throw new RuntimeException("Unable to read file");
}
$json = json_decode($lockFileContent, true);
if (is_null($json) || ! isset($json['packages'])) {
throw new RuntimeException("Invalid composer file format");
}
if ($excludeDev) {
$packages = $json['packages'];
} else {
$packages = array_merge($json['packages'], isset($json['packages-dev']) ? $json['packages-dev'] : []);
}
if (empty($packages)) {
return [];
}
return array_merge(...array_map(function ($package) {
return [$package['name'] => [
'version' => ltrim($package['version'], 'v'),
'time' => isset($package['time']) ? $package['time'] : null,
]];
}, $packages));
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Enlightn\SecurityChecker;
use ErrorException;
use FilesystemIterator;
class Filesystem
{
/**
* Recursively delete a directory.
*
* The directory itself may be optionally preserved.
*
* @param string $directory
* @param bool $preserve
* @return bool
*/
public function deleteDirectory($directory, $preserve = false)
{
if (! is_dir($directory)) {
return false;
}
$items = new FilesystemIterator($directory);
foreach ($items as $item) {
// If the item is a directory, we can just recurse into the function and
// delete that sub-directory otherwise we'll just delete the file and
// keep iterating through each file until the directory is cleaned.
if ($item->isDir() && ! $item->isLink()) {
$this->deleteDirectory($item->getPathname());
}
// If the item is just a file, we can go ahead and delete it since we're
// just looping through and waxing all of the files in this directory
// and calling directories recursively, so we delete the real path.
else {
$this->delete($item->getPathname());
}
}
if (! $preserve) {
@rmdir($directory);
}
return true;
}
/**
* Delete the file at a given path.
*
* @param string|array $paths
* @return bool
*/
public function delete($paths)
{
$paths = is_array($paths) ? $paths : func_get_args();
$success = true;
foreach ($paths as $path) {
try {
if (! @unlink($path)) {
$success = false;
}
} catch (ErrorException $e) {
$success = false;
}
}
return $success;
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Enlightn\SecurityChecker;
use Exception;
use Symfony\Component\Console\Output\OutputInterface;
interface FormatterInterface
{
/**
* Display the result.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param array $result
* @return void
*/
public function displayResult(OutputInterface $output, array $result);
/**
* Display the error.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Exception $exception
* @return void
*/
public function displayError(OutputInterface $output, Exception $exception);
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Enlightn\SecurityChecker;
use Exception;
use Symfony\Component\Console\Output\OutputInterface;
class JsonFormatter implements FormatterInterface
{
/**
* Display the result.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param array $result
* @return void
*/
public function displayResult(OutputInterface $output, array $result)
{
$output->writeln(json_encode($result, JSON_PRETTY_PRINT));
}
/**
* Display the error.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Exception $exception
* @return void
*/
public function displayError(OutputInterface $output, Exception $exception)
{
$output->writeln(json_encode([
'error' => $exception->getMessage(),
], JSON_PRETTY_PRINT));
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Enlightn\SecurityChecker;
class SecurityChecker
{
/**
* @var string
*/
private $tempDir;
public function __construct($tempDir = null)
{
$this->tempDir = $tempDir;
}
/**
* @param string $composerLockPath
* @param false $excludeDev
* @param array $allowList
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function check($composerLockPath, $excludeDev = false, $allowList = [])
{
$parser = new AdvisoryParser((new AdvisoryFetcher($this->tempDir))->fetchAdvisories());
$dependencies = (new Composer)->getDependencies($composerLockPath, $excludeDev);
return (new AdvisoryAnalyzer($parser->getAdvisories($allowList)))->analyzeDependencies($dependencies);
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Enlightn\SecurityChecker;
use Exception;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class SecurityCheckerCommand extends Command
{
protected static $defaultName = 'security:check';
/**
* @see Command
*/
protected function configure()
{
$this
->setName('security:check')
->setDefinition([
new InputArgument('lockfile', InputArgument::OPTIONAL, 'The path to the composer.lock file', 'composer.lock'),
new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Whether to exclude dev packages from scanning'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'ansi'),
new InputOption('temp-dir', null, InputOption::VALUE_REQUIRED, 'The temp directory to use for caching', null),
new InputOption('allow-list', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'List of vulnerabilities to allow', []),
])
->setDescription('Checks for vulnerabilities in your project dependencies')
->setHelp(
<<<EOF
The <info>%command.name%</info> command looks for security vulnerabilities in the
project dependencies:
<info>php %command.full_name%</info>
You can also pass the path to a <info>composer.lock</info> file as an argument:
<info>php %command.full_name% /path/to/composer.lock</info>
By default, the command displays the result in ansi, but you can also
configure it to output JSON instead by using the <info>--format</info> option:
<info>php %command.full_name% /path/to/composer.lock --format=json</info>
You can specify a list of vulnerabilities to allow by using the CVE identifier or the vulnerability title:
<info>php %command.full_name% /path/to/composer.lock --allow-list CVE-2018-15133 --allow-list "untrusted X-XSRF-TOKEN value"</info>
EOF
);
}
/**
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return int
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$formatter = $input->getOption('format') == 'ansi' ? new AnsiFormatter : new JsonFormatter;
$excludeDev = $input->getOption('no-dev');
$tempDir = $input->getOption('temp-dir');
$allowList = $input->getOption('allow-list');
try {
$result = (new SecurityChecker($tempDir))->check(
$input->getArgument('lockfile'),
$excludeDev,
$allowList
);
$formatter->displayResult($output, $result);
} catch (Exception $throwable) {
$formatter->displayError($output, $throwable);
return 1;
}
if (count($result) > 0) {
return 1;
}
return 0;
}
}

View File

@@ -0,0 +1,109 @@
<?php
namespace Enlightn\SecurityChecker;
use RuntimeException;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
use UnexpectedValueException;
use ZipArchive;
class ZipExtractor
{
/**
* @param string $archivePath
* @param string $extractPath
*/
public function extract($archivePath, $extractPath)
{
if ($this->unzipCommandExists()) {
$this->extractWithSystemUnzip($archivePath, $extractPath);
return;
}
if (class_exists('ZipArchive')) {
$this->extractWithZipArchive($archivePath, $extractPath);
return;
}
throw new RuntimeException('The unzip command and zip php extension are both missing.');
}
/**
* @return bool
*/
public function unzipCommandExists()
{
$finder = new ExecutableFinder;
return (bool) $finder->find('unzip');
}
/**
* @param string $archivePath
* @param string $extractPath
*/
public function extractWithSystemUnzip($archivePath, $extractPath)
{
$process = new Process(['unzip', '-qq', '-o', $archivePath, '-d', $extractPath]);
$process->mustRun();
}
/**
* @param string $archivePath
* @param string $extractPath
*/
public function extractWithZipArchive($archivePath, $extractPath)
{
$zip = new ZipArchive;
$openResult = $zip->open($archivePath);
if (true === $openResult) {
$extractResult = $zip->extractTo($extractPath);
if (true === $extractResult) {
$zip->close();
} else {
throw new RuntimeException('There was an error in extracting the ZIP file. It is either corrupted or using an invalid format.');
}
} else {
throw new UnexpectedValueException($this->getErrorMessage($openResult, $archivePath));
}
}
/**
* Give a meaningful error message to the user.
*
* @param int $retval
* @param string $file
* @return string
*/
protected function getErrorMessage($retval, $file)
{
switch ($retval) {
case ZipArchive::ER_EXISTS:
return sprintf("File '%s' already exists.", $file);
case ZipArchive::ER_INCONS:
return sprintf("Zip archive '%s' is inconsistent.", $file);
case ZipArchive::ER_INVAL:
return sprintf("Invalid argument (%s)", $file);
case ZipArchive::ER_MEMORY:
return sprintf("Malloc failure (%s)", $file);
case ZipArchive::ER_NOENT:
return sprintf("No such zip file: '%s'", $file);
case ZipArchive::ER_NOZIP:
return sprintf("'%s' is not a zip archive.", $file);
case ZipArchive::ER_OPEN:
return sprintf("Can't open zip file: %s", $file);
case ZipArchive::ER_READ:
return sprintf("Zip read error (%s)", $file);
case ZipArchive::ER_SEEK:
return sprintf("Zip seek error (%s)", $file);
default:
return sprintf("'%s' is not a valid zip archive, got error code: %s", $file, $retval);
}
}
}