-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.php
More file actions
331 lines (278 loc) · 10.6 KB
/
command.php
File metadata and controls
331 lines (278 loc) · 10.6 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
<?php
declare(strict_types=1);
/**
* Checks active plugins against Wordfence Intelligence V3 vulnerability feed.
*/
final class Plugin_Vuln_Command
{
public const WORDFENCE_V3_ENDPOINT =
'https://www.wordfence.com/api/intelligence/v3/vulnerabilities/production';
private const CACHE_SUBDIR = 'wordfence';
private const CACHE_FILE = 'v3-vulnerabilities-production.json';
private const CACHE_TTL = 7200;
/**
* Check active plugins for known vulnerabilities.
*
* ## OPTIONS
*
* [--format=<format>]
* : Output format: table|json
* ---
* default: table
* options:
* - table
* - json
* ---
*
* ## EXAMPLES
*
* wp plugin vuln
* wp plugin vuln --format=table
*
* @when after_wp_load
*/
public function __invoke(array $args, array $assocArgs): void
{
try {
if (!function_exists('get_plugins')) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$apiKey = getenv('WORDFENCE_API_KEY') ?: '';
if ($apiKey === '') {
throw new RuntimeException('Missing WORDFENCE_API_KEY environment variable.');
}
$format = $assocArgs['format'] ?? 'table';
if (!in_array($format, ['table', 'json'], true)) {
throw new InvalidArgumentException('Invalid --format. Allowed: table, json');
}
$feed = $this->fetchFeed(self::WORDFENCE_V3_ENDPOINT, $apiKey);
$index = $this->buildPluginPatchedVersionIndex($feed);
$results = $this->scanActivePlugins($index);
if ($format === 'json') {
WP_CLI::line((string) wp_json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
return;
}
if ($results === []) {
WP_CLI::success('No vulnerable active plugins found (based on feed + version comparison).');
return;
}
WP_CLI\Utils\format_items(
'table',
$results,
['slug', 'installed_version', 'patched_version', 'update_command']
);
} catch (Throwable $e) {
WP_CLI::error($e->getMessage());
}
}
/**
* Fetches and decodes the Wordfence feed with local cache.
*
* @return array<mixed>
*/
private function fetchFeed(string $endpoint, string $apiKey): array
{
$cacheFile = $this->getCacheFilePath();
$this->ensureCacheDirectory(dirname($cacheFile));
if (is_file($cacheFile)) {
$mtime = filemtime($cacheFile);
if ($mtime !== false && (time() - $mtime) < self::CACHE_TTL) {
$cachedBody = file_get_contents($cacheFile);
if ($cachedBody !== false && $cachedBody !== '') {
$cachedData = json_decode($cachedBody, true);
if (is_array($cachedData)) {
return $cachedData;
}
}
}
}
$response = wp_remote_get(
$endpoint,
[
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . $apiKey,
'Accept' => 'application/json',
],
]
);
if (is_wp_error($response)) {
throw new RuntimeException('API request failed: ' . $response->get_error_message());
}
$status = (int) wp_remote_retrieve_response_code($response);
$body = (string) wp_remote_retrieve_body($response);
if ($status === 429) {
// If we have any cache at all (even stale), use it as a fallback.
if (is_file($cacheFile)) {
$cachedBody = file_get_contents($cacheFile);
if ($cachedBody !== false && $cachedBody !== '') {
$cachedData = json_decode($cachedBody, true);
if (is_array($cachedData)) {
return $cachedData;
}
}
}
throw new RuntimeException(
'Wordfence API rate limit reached (HTTP 429). Try again in about 30 minutes.'
);
}
if ($status < 200 || $status >= 300) {
throw new RuntimeException(sprintf('API request failed with HTTP %d', $status));
}
$data = json_decode($body, true);
if (!is_array($data)) {
throw new RuntimeException('Invalid JSON received from Wordfence API.');
}
if (file_put_contents($cacheFile, $body, LOCK_EX) === false) {
throw new RuntimeException(sprintf('Failed to write cache file: %s', $cacheFile));
}
return $data;
}
/**
* Returns the absolute cache file path inside the WP-CLI cache directory.
*/
private function getCacheFilePath(): string
{
$baseCacheDir = \WP_CLI\Utils\get_cache_dir();
if (!is_string($baseCacheDir) || $baseCacheDir === '') {
throw new RuntimeException('Unable to resolve WP-CLI cache directory.');
}
return rtrim($baseCacheDir, '/\\')
. DIRECTORY_SEPARATOR
. self::CACHE_SUBDIR
. DIRECTORY_SEPARATOR
. self::CACHE_FILE;
}
/**
* Ensures the cache directory exists and is writable.
*/
private function ensureCacheDirectory(string $directory): void
{
if (is_dir($directory)) {
if (!is_writable($directory)) {
throw new RuntimeException(sprintf('Cache directory is not writable: %s', $directory));
}
return;
}
if (!wp_mkdir_p($directory)) {
throw new RuntimeException(sprintf('Failed to create cache directory: %s', $directory));
}
if (!is_writable($directory)) {
throw new RuntimeException(sprintf('Cache directory is not writable: %s', $directory));
}
}
/**
* Builds an index: plugin slug => max patched version found in feed.
*
* This intentionally uses a generic recursive walk because feed schemas can evolve.
*
* @param array<mixed> $feed
* @return array<string, string>
*/
private function buildPluginPatchedVersionIndex(array $feed): array
{
$records = [];
$stack = [$feed];
while ($stack !== []) {
$node = array_pop($stack);
if (!is_array($node)) {
throw new UnexpectedValueException('Feed contains a non-array node where array traversal was expected.');
}
if (
($node['type'] ?? null) === 'plugin'
&& array_key_exists('slug', $node)
&& array_key_exists('patched_versions', $node)
) {
if (!is_string($node['slug']) || $node['slug'] === '') {
throw new UnexpectedValueException('Feed plugin record has invalid slug.');
}
if (!is_array($node['patched_versions'])) {
throw new UnexpectedValueException(
sprintf('Feed plugin record "%s" has invalid patched_versions.', $node['slug'])
);
}
$slug = $node['slug'];
foreach ($node['patched_versions'] as $patchedVersion) {
if (!is_string($patchedVersion) || $patchedVersion === '') {
throw new UnexpectedValueException(
sprintf('Feed plugin record "%s" contains invalid patched version.', $slug)
);
}
if (
!isset($records[$slug])
|| version_compare($patchedVersion, $records[$slug], '>')
) {
$records[$slug] = $patchedVersion;
}
}
}
foreach ($node as $child) {
if (is_array($child)) {
$stack[] = $child;
}
}
}
return $records;
}
/**
* Scans active plugins and returns vulnerable ones.
*
* Assumes WordPress returns a valid active_plugins option shape.
*
* @param array<string, string> $patchedVersionIndex
* @return array<int, array<string, string>>
*/
private function scanActivePlugins(array $patchedVersionIndex): array
{
$plugins = get_plugins();
$activePluginFiles = (array) get_option('active_plugins', []);
$results = [];
foreach ($activePluginFiles as $pluginFile) {
if (!isset($plugins[$pluginFile])) {
throw new RuntimeException(sprintf('Active plugin "%s" not found in get_plugins() list.', $pluginFile));
}
$pluginData = $plugins[$pluginFile];
$installedVersion = $pluginData['Version'] ?? null;
if (!is_string($installedVersion) || $installedVersion === '') {
throw new RuntimeException(
sprintf('Plugin "%s" has missing or invalid Version field.', $pluginFile)
);
}
$slug = $this->pluginFileToSlug($pluginFile);
if (!isset($patchedVersionIndex[$slug])) {
continue;
}
$patchedVersion = $patchedVersionIndex[$slug];
if (!is_string($patchedVersion) || $patchedVersion === '') {
throw new UnexpectedValueException(
sprintf('Patched version index contains invalid version for slug "%s".', $slug)
);
}
if (version_compare($installedVersion, $patchedVersion, '<')) {
$results[] = [
'slug' => $slug,
'installed_version' => $installedVersion,
'patched_version' => $patchedVersion,
'update_command' => 'wp plugin update ' . $slug,
];
}
}
return $results;
}
/**
* Converts plugin file path to a WP.org-style slug heuristic.
*/
private function pluginFileToSlug(string $pluginFile): string
{
$dir = dirname($pluginFile);
if ($dir !== '.' && $dir !== '') {
return $dir;
}
$slug = basename($pluginFile, '.php');
if ($slug === '') {
throw new RuntimeException(sprintf('Cannot derive slug from plugin file "%s".', $pluginFile));
}
return $slug;
}
}
WP_CLI::add_command('plugin vuln', Plugin_Vuln_Command::class);