This repository was archived by the owner on Apr 16, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathVersionScan.php
More file actions
588 lines (484 loc) · 19.2 KB
/
VersionScan.php
File metadata and controls
588 lines (484 loc) · 19.2 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
<?php
declare(strict_types=1);
namespace App;
use App\Webapps\Releases\Releases;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class VersionScan
{
protected $website;
protected $delay;
protected $userAgent;
protected $callbackUrls = [];
protected $candidates = [];
protected $client;
protected $result = [
"CMS" => null,
"Versions" => []
];
/**
* VersionScan constructor.
*
* @param string $website
* @param int $delay delay in ms
* @param array $callbackUrls
* @param bool $userAgent
*/
public function __construct(string $website, int $delay = 0, array $callbackUrls = [], $userAgent = false)
{
// Make IDN conversion
$website = $this->punycodeUrl($website);
// Save website with trailing slash
$this->website = rtrim($website, '/') . '/';
$this->delay = $delay;
$this->callbackUrls = $callbackUrls;
$this->userAgent = $userAgent;
$this->client = new Client([
'headers' => [
'User-Agent' => $userAgent,
],
'verify' => false
]);
}
/**
* Execute the job.
*
* @return array
*/
public function scan(): array
{
try {
$fileExists = Storage::disk('signatures')->exists('candidates.json');
// Check if candidates file exists
if (!$fileExists) {
throw new \RuntimeException('Could not find candidates.json in storage folder');
}
// Read candidates file
$this->candidates = json_decode(Storage::disk('signatures')->get('candidates.json'), true);
if (!is_array($this->candidates) || !count($this->candidates)) {
throw new \RuntimeException('Invalid candidates file');
}
Log::info('=== Starting Scan Job for : ' . $this->website . ' ===');
// Detect used CMS
$this->testBaseUrl();
$this->detectCms();
$this->detectVersion();
$this->isSupported();
// Make callbacks
if (count($this->callbackUrls)) {
$this->notifyCallbacks();
}
Log::info('=== Finishing Scan Job for : ' . $this->website . ' ===');
return $this->result;
} catch (\Exception $e) {
if (!count($this->callbackUrls)) {
throw $e;
}
Log::info('=== Caught Scan Job Exception for : ' . $this->website . ' ===');
$report = [
'name' => 'VERSION',
'version' => file_get_contents(base_path('VERSION')),
'hasError' => true,
'errorMessage' => [
'translationStringId' => 'INTERNAL_ERROR_OCCURED',
'placeholders' => [
'EXCEPTION_MESSAGE' => $e->getMessage()
]
],
'score' => 0,
'tests' => [
[
"name" => "CMSVERSION",
"errorMessage" => [
'translationStringId' => 'INTERNAL_ERROR_OCCURED',
'placeholders' => [
'EXCEPTION_MESSAGE' => $e->getMessage()
]
],
"hasError" => true,
"score" => 0,
"scoreType" => 'info',
"testDetails" => []
]
]
];
foreach ($this->callbackUrls as $url) {
try {
$this->client->post($url, [
'http_errors' => false,
'timeout' => 60,
'json' => $report,
]);
} catch (\Exception $e) {
Log::warning('Could not send the error report to the following callback url: ' . $url);
}
}
return [];
}
}
/**
* Test if baseurl can be reached in general, if not escape early
*
* @return void
*/
protected function testBaseUrl(): void
{
try {
$this->client->get($this->website, [
'timeout' => 5
]);
} catch (ClientException | ConnectException | RequestException $e) {
throw new \RuntimeException('Could not connect to site');
}
}
/**
* Detect the CMS used
*
* @return void
*/
protected function detectCms(): void
{
$matchCount = [];
foreach ($this->candidates as $cms => $cmsData) {
// Get the first 10 files per CMS
$bestCandidates = array_splice($cmsData["identifier"], 0, 10);
Log::info('=== Scanning for CMS: ' . $cms . ' ===');
foreach ($bestCandidates as $filename => $hashInfo) {
// Remove lead slashes
$filename = ltrim($filename, '/');
// Sleep to not overwhelm the server
usleep($this->delay * 1000);
try {
$this->client->get($this->website . $filename, [
'timeout' => 5
]);
Log::debug('=== File found: ' . $this->website . $filename . ' ===');
if (!isset($matchCount[$cms])) {
$matchCount[$cms] = 0;
}
$matchCount[$cms]++;
} catch (ClientException | ConnectException | RequestException $e) {
Log::info('=== File not found: ' . $this->website . $filename . ' ===');
continue;
}
}
}
if (!count($matchCount)) {
return;
}
// Check for an edge case: if multiple CMS have the full match count, it's most likely because
// the server returns 200 status code for 404 pages
if (count(array_filter($matchCount, function ($count) {
return ($count === 10);
})) > 1) {
Log::info('Returning no CMS because server is misconfigured');
return;
}
// Sort matches array
arsort($matchCount);
reset($matchCount);
$matches = $matchCount[key($matchCount)];
// If we have less than 4 matches, it's very likely that this is not one of our CMS
if ($matches < 4) {
Log::info('Returning no CMS because less than 3 matches');
return;
}
Log::info('Returning ' . key($matchCount) . ' as CMS with ' . $matches . ' matches');
$this->result["CMS"] = key($matchCount);
}
/**
* Detect the used version
*
* @return void
*/
public function detectVersion(): void
{
Log::info('=== Detecting used Version ===');
// We can only detect a version if we know the CMS
if ($this->result["CMS"] === null) {
return;
}
$possibleVersions = [];
// Entry point of this scan. Iterates over the main candidates.
foreach ($this->candidates[$this->result["CMS"]]['identifier'] as $filename => $hashInfo) {
$sourceHashes = $hashInfo['data'];
$filename = ltrim($filename, '/');
Log::debug('Fetching ' . $filename);
// Sleep to not overwhelm the server
usleep($this->delay * 1000);
try {
$response = $this->client->get($this->website . $filename, [
'timeout' => 5
]);
$body = (string) $response->getBody();
// Hash generation of the requested file from the website.
$targetHash = md5($body);
Log::debug('File ' . $this->website . $filename . ' with hash ' . $targetHash . ' found');
} catch (ClientException | ConnectException | RequestException $e) {
Log::debug('File ' . $this->website . $filename . ' not found, next file...');
continue;
}
// First look up, if the candidates hash list contains the generated hash from the website.
if (!isset($sourceHashes[$targetHash])) {
Log::debug('Unknown hash of ' . $this->website . $filename . ', next file...');
continue;
}
// Count how many versions are related to this hash.
$amountOfVersions = count($sourceHashes[$targetHash]);
// If there is only one version, no further searching required
if ($amountOfVersions === 1) {
$this->result["Versions"] = [$sourceHashes[$targetHash][0]];
return;
}
/**
* Continuing here means that there are more versions related to this hash and -
* it is impossible to tell which version the CMS has.
*/
if (!count($possibleVersions)) {
// Store those versions and compare them later
$possibleVersions = $sourceHashes[$targetHash];
continue;
}
// Get the intersection of the current hash tree and the one before
$possibleVersions = array_intersect($possibleVersions, $sourceHashes[$targetHash]);
Log::debug('Remaining versions after this file: ' . count($possibleVersions));
// Check again, if the intersection resulted in one entry. No further searching required then.
if (count($possibleVersions) === 1) {
$this->result["Versions"] = [reset($possibleVersions)];
return;
}
}
// THE single possible has not be found yet. Starting a more detailed and specific scan with -
// the last few versions left to check on.
foreach ($this->candidates[$this->result["CMS"]]['versionproof'] as $versionNumber => $fileInfo) {
if (in_array($versionNumber, $possibleVersions, true)) {
// This may results into a boolean => false; which means that this version cannot be identified.
if (!is_array($fileInfo)) {
continue;
}
foreach ($fileInfo as $filename => $hash) {
$filename = ltrim($filename, '/');
// Sleep to not overwhelm the server
usleep($this->delay * 1000);
try {
$response = $this->client->get($this->website . $filename, [
'timeout' => 5
]);
$body = (string) $response->getBody();
$websiteFileHash = md5($body);
// We have an exact match, it's the version we are looking for
if ($websiteFileHash === $hash) {
$this->result["Versions"] = [$versionNumber];
return;
}
} catch (ClientException | ConnectException | RequestException $e) {
continue;
}
}
}
}
$this->result["Versions"] = $possibleVersions;
}
/**
* Check if the detected version is supported
*
* @return void
*/
protected function isSupported(): void
{
// We can only detect a version if we know the CMS
if ($this->result["CMS"] === null || $this->result["Versions"] === null) {
return;
}
$detailedVersions = [];
// Try to find the right branch
foreach ($this->result["Versions"] as $version) {
$matchedBranch = $this->getBranchForVersion($version);
Log::info("Found a matching branch " . $matchedBranch["branch"] . " for version " . $version);
// Compare if we are using a supported version
$detailedVersions[$version] = [];
$detailedVersions[$version]["Supported"] = $matchedBranch["supported"];
$detailedVersions[$version]["IsLatest"] = version_compare($version, $matchedBranch["version"], '>=');
$detailedVersions[$version]["Latest"] = $matchedBranch["version"];
}
$this->result["Versions"] = $detailedVersions;
}
/**
* @param string $version
* @return array
*/
protected function getBranchForVersion(string $version): array
{
// Get latest versions for CMS
$releaseClassName = 'App\\Webapps\\Releases\\' . $this->result["CMS"];
/** @var Releases $releaseClass */
$releaseClass = new $releaseClassName;
$branches = $releaseClass->getLatest();
foreach ($branches as $branch) {
if (stripos($version, (string) $branch["branch"]) === 0) {
return $branch;
}
}
throw new \RuntimeException("Could not find branch for CMS version " . $version);
}
/**
* Send callbacks with SIWECOS report format
*/
protected function notifyCallbacks(): void
{
$score = 100;
$scoreType = 'success';
$testDetails = null;
// Case 1: CMS and only 1 Version detected, up to date and supported
if (
count($this->result["Versions"]) === 1
&& $this->result["CMS"] !== null
&& $this->result["Versions"][key($this->result["Versions"])]["Supported"]
&& $this->result["Versions"][key($this->result["Versions"])]["IsLatest"]
) {
$testDetails = [
[
"translationStringId" => "CMS_UPTODATE",
"placeholders" => [
"cms" => $this->result["CMS"],
"version" => key($this->result["Versions"])
]
]
];
}
$outdated = 0;
$upToDate = 0;
$unsupported = 0;
foreach ($this->result["Versions"] as $version => $details) {
if ($this->result["CMS"] !== null && $details["Supported"] && !$details["IsLatest"]) {
$outdated++;
}
if ($this->result["CMS"] !== null && $details["Supported"] && $details["IsLatest"]) {
$upToDate++;
}
if ($this->result["CMS"] !== null && !$details["Supported"]) {
$unsupported++;
}
}
// Case 2: CMS and Version detected but outdated
if ($this->result["CMS"] !== null && $upToDate === 0 && $outdated > 0) {
$testDetails = [
[
"translationStringId" => "CMS_OUTDATED",
"placeholders" => [
"cms" => $this->result["CMS"],
"version" => implode(', ', array_keys($this->result["Versions"])),
"latest" => $this->result["Versions"][key($this->result["Versions"])]['Latest']
]
]
];
$score = 0;
$scoreType = 'warning';
}
// Case 3: CMS and Version detected but out of support
if ($this->result["CMS"] !== null && $upToDate === 0 && $unsupported > 0) {
$testDetails = [
[
"translationStringId" => "CMS_OUT_OF_SUPPORT",
"placeholders" => [
"cms" => $this->result["CMS"],
"version" => implode(', ', array_keys($this->result["Versions"]))
]
]
];
$score = 0;
$scoreType = 'critical';
}
// Case 4: One version up-to-date; others outdated
if ($this->result["CMS"] !== null && $upToDate === 1 && $outdated > 0) {
$testDetails = [
[
"translationStringId" => "CMS_MIGHT_UPTODATE",
"placeholders" => [
"cms" => $this->result["CMS"],
"version" => implode(', ', array_keys($this->result["Versions"]))
]
]
];
$score = 90;
$scoreType = 'warning';
}
// Case 5: CMS found but can't detect version
if ($this->result["CMS"] !== null && count($this->result["Versions"]) === 0) {
$testDetails = [
[
"translationStringId" => "CMS_CANT_DETECT_VERSION",
"placeholders" => [
"cms" => $this->result["CMS"]
]
]
];
$scoreType = 'info';
}
// Case 6: Can't detect CMS
if ($this->result["CMS"] === null) {
$testDetails = [
[
"translationStringId" => "CMS_CANT_DETECT_CMS"
]
];
$scoreType = 'info';
}
$report = [
'name' => 'VERSION',
'version' => file_get_contents(base_path('VERSION')),
'hasError' => false,
'errorMessage' => null,
'score' => $score,
'tests' => [
[
"name" => "CMSVERSION",
"errorMessage" => null,
"hasError" => false,
"score" => $score,
"scoreType" => $scoreType,
"testDetails" => $testDetails
]
],
];
foreach ($this->callbackUrls as $url) {
Log::info('Making callback for ' . $this->website . ' to '
. $url . ' with content ' . json_encode($report));
try {
$this->client->post($url, [
'http_errors' => false,
'timeout' => 60,
'json' => $report,
]);
} catch (\Exception $e) {
Log::warning('Could not send the report to the following callback url: ' . $url);
}
Log::info('Finished callback for ' . $this->website);
}
}
/**
* Returns the Punycode encoded URL for a given URL.
*
* @param string $url URL to encode
*
* @return string Punycode-Encoded URL.
*/
public function punycodeUrl($url)
{
$parsed_url = parse_url($url);
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ?
idn_to_ascii($parsed_url['host'], IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46) : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "$pass@" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
return "$scheme$user$pass$host$port$path$query";
}
}