/
Auditor.php
247 lines (225 loc) · 8.12 KB
/
Auditor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
<?php
namespace Composer\Util;
use Composer\IO\ConsoleIO;
use Composer\IO\IOInterface;
use Composer\Package\PackageInterface;
use Composer\Semver\Semver;
use InvalidArgumentException;
/**
* @internal
*/
class Auditor
{
private const API_URL = 'https://packagist.org/api/security-advisories/';
public const FORMAT_TABLE = 'table';
public const FORMAT_PLAIN = 'plain';
public const FORMAT_SUMMARY = 'summary';
public const FORMATS = [
self::FORMAT_TABLE,
self::FORMAT_PLAIN,
self::FORMAT_SUMMARY,
];
/** @var HttpDownloader */
private $httpDownloader;
/**
* @param HttpDownloader $httpDownloader
*/
public function __construct(HttpDownloader $httpDownloader)
{
$this->httpDownloader = $httpDownloader;
}
/**
* @param IOInterface $io
* @param PackageInterface[] $packages
* @param self::FORMAT_* $format The format that will be used to output audit results.
* @param bool $warningOnly If true, outputs a warning. If false, outputs an error.
* @return int
* @throws InvalidArgumentException If no packages are passed in
*/
public function audit(IOInterface $io, array $packages, string $format, bool $warningOnly = true): int
{
$advisories = $this->getAdvisories($packages);
$errorOrWarn = $warningOnly ? 'warning' : 'error';
if (count($advisories) > 0) {
$numAdvisories = $this->countAdvisories($advisories);
$plurality = $numAdvisories === 1 ? 'y' : 'ies';
$punctuation = $format === 'summary' ? '.' : ':';
$io->writeError("<$errorOrWarn>Found $numAdvisories security vulnerability advisor{$plurality}{$punctuation}</$errorOrWarn>");
$this->outputAdvisories($io, $advisories, $format);
return 1;
}
$io->writeError('<info>No security vulnerability advisories found</info>');
return 0;
}
/**
* Get advisories from packagist.org
*
* @param PackageInterface[] $packages
* @param ?int $updatedSince Timestamp
* @param bool $filterByVersion Filter by the package versions if true
* @return string[][][]
* @throws InvalidArgumentException If no packages and no updatedSince timestamp are passed in
*/
public function getAdvisories(array $packages = [], int $updatedSince = null, bool $filterByVersion = true): array
{
if (count($packages) === 0 && $updatedSince === null) {
throw new InvalidArgumentException(
'At least one package or an $updatedSince timestamp must be passed in.'
);
}
if (count($packages) === 0 && $filterByVersion) {
return [];
}
// Add updatedSince query to URL if passed in
$url = self::API_URL;
if ($updatedSince !== null) {
$url .= "?updatedSince=$updatedSince";
}
// Get advisories from API
$response = $this->httpDownloader->get($url, $this->createPostOptions($packages));
$advisories = $response->decodeJson()['advisories'];
if (count($advisories) > 0 && $filterByVersion) {
return $this->filterAdvisories($advisories, $packages);
}
return $advisories;
}
/**
* @param PackageInterface[] $packages
* @return string[]
* @phpstan-return array<string, array<string, array<int, string>|int|string>>
*/
private function createPostOptions(array $packages): array
{
$options = [
'http' => [
'method' => 'POST',
'header' => ['Content-type: application/x-www-form-urlencoded'],
'timeout' => 10,
],
];
if (count($packages) > 0) {
$content = ['packages' => []];
foreach ($packages as $package) {
$content['packages'][] = $package->getName();
}
$options['http']['content'] = http_build_query($content);
}
return $options;
}
/**
* @param string[][][] $advisories
* @param PackageInterface[] $packages
* @return string[][][]
*/
private function filterAdvisories(array $advisories, array $packages): array
{
$filteredAdvisories = [];
foreach ($packages as $package) {
if (array_key_exists($package->getName(), $advisories)) {
foreach ($advisories[$package->getName()] as $advisory) {
if (Semver::satisfies($package->getVersion(), $advisory['affectedVersions'])) {
$filteredAdvisories[$package->getName()][] = $advisory;
}
}
}
}
return $filteredAdvisories;
}
/**
* @param string[][][] $advisories
* @return integer
*/
private function countAdvisories(array $advisories): int
{
$count = 0;
foreach ($advisories as $packageAdvisories) {
$count += count($packageAdvisories);
}
return $count;
}
/**
* @param IOInterface $io
* @param string[][][] $advisories
* @param self::FORMAT_* $format The format that will be used to output audit results.
* @return void
*/
private function outputAdvisories(IOInterface $io, array $advisories, string $format): void
{
switch ($format) {
case self::FORMAT_TABLE:
if (!($io instanceof ConsoleIO)) {
throw new InvalidArgumentException('Cannot use table format with ' . get_class($io));
}
$this->outputAvisoriesTable($io, $advisories);
return;
case self::FORMAT_PLAIN:
$this->outputAdvisoriesPlain($io, $advisories);
return;
case self::FORMAT_SUMMARY:
// We've already output the number of advisories in audit()
$io->writeError('Run composer audit for a full list of advisories.');
return;
default:
throw new InvalidArgumentException('Invalid format "'.$format.'".');
}
}
/**
* @param ConsoleIO $io
* @param string[][][] $advisories
* @return void
*/
private function outputAvisoriesTable(ConsoleIO $io, array $advisories): void
{
foreach ($advisories as $package => $packageAdvisories) {
foreach ($packageAdvisories as $advisory) {
$io->getTable()
->setHorizontal()
->setHeaders([
'Package',
'CVE',
'Title',
'URL',
'Affected versions',
'Reported at',
])
->addRow([
$package,
$advisory['cve'] ?? 'NO CVE',
$advisory['title'],
$advisory['link'],
$advisory['affectedVersions'],
$advisory['reportedAt'],
])
->setColumnWidth(1, 80)
->setColumnMaxWidth(1, 80)
->render();
}
}
}
/**
* @param IOInterface $io
* @param string[][][] $advisories
* @return void
*/
private function outputAdvisoriesPlain(IOInterface $io, array $advisories): void
{
$error = [];
$firstAdvisory = true;
foreach ($advisories as $package => $packageAdvisories) {
foreach ($packageAdvisories as $advisory) {
if (!$firstAdvisory) {
$error[] = '--------';
}
$cve = $advisory['cve'] ?? 'NO CVE';
$error[] = "Package: $package";
$error[] = "CVE: $cve";
$error[] = "Title: {$advisory['title']}";
$error[] = "URL: {$advisory['link']}";
$error[] = "Affected versions: {$advisory['affectedVersions']}";
$error[] = "Reported at: {$advisory['reportedAt']}";
$firstAdvisory = false;
}
}
$io->writeError($error);
}
}