-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaesecure_quickscan.php
4549 lines (3782 loc) · 195 KB
/
aesecure_quickscan.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
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Name : aeSecure QuickScan - Free scanner
* Description : Scan your website for possible hacks, viruses, malwares, SEO black hat and exploits
* Version : 2.0.3
* Date : November 2018
* Last update : September 2023
* Author : AVONTURE Christophe ([email protected])
* Author website: https://www.avonture.be.
*
* --------------------------------------------------------------------------------------------------------
* aeSecure QuickScan - Malware Scan.
*
* This script will make a quick and *superficial*, not deeply, scan and will detect the presence of
* a few patterns in files present on your website. If such files are found, they will be reported.
*
* This script is a quick scan tool: only a very few patterns will be scanned and if you find
* viruses with it, consider making a full and deeply scan to search for other malware scripts.
*
* If no files are reported by the script, here too, it's possible that other type of virus are
* present.
*
* If you wish a full scan, contact me by surfing on https://www.avonture.be and take a look on my
* services.
*
* Changelog:
*
* version 2.0.3
* + Prevent empty files to be scanned
* + Immediately show the listing of files having detected as being a virus (blacklist) or
* containing a virus (edited file having a virus load)
*
* version 2.0.2
* + Revert to PHP 8.0 compatibility
*
* version 2.0.1
* + Add the "_COOKIE" pattern in aesecure_quickscan_pattern.json
*
* version 2.0
* + PHP 8.2 compatibility
* + look for hashes in hashes directory
*
* version 1.2
* + Rewrite for downloading all settings and signatures files from GitHub
* + Add a lot more signatures in these lists: blacklist, whitelist, other and edited json
* + Ad more patterns for viruses detection
* + Reformat the code of the scanner
*
* version 1.1.12
* + Add support for Grr, mediawiki, piwik and pmb
* + Solve an issue with session_start() for some hosts
*
* version 1.1.11
* + Add support for Grav
*
* version 1.1.10
* + Add support for phpMyAdmin
*
* version 1.1.9
* + Solve an error with session_start (on some hoster, the creation of the session gives a fatal error due to incorrect path)
*
* version 1.1.8
* + Solve an error with the link to the FAQ
* + Better handling of languages files
*
* version 1.1.7
* + Add localizations (class aeSecureLanguage)
*
* version 1.1.6
* + Improve the detection of the list of files by immediatly skipping whitelisted files. On a site of 4.900 files, the scanner will be able to detect that
* only 11 files should be scanned if 4.889 are already white listed. This way, the scanner will be really fast.
*
* version 1.1.5
* + Small change to correctly handle Joomla 3.5.0 with a newer way to determine the version number (no more dollar sign before variables name)
*
* version 1.1.4
* + Add aesecure_quickscan.whitelist.json as a file to download from avonture.be to speed up the processing and reduce the number of false positive
* + Add a lot of new signatures in the blacklist
*
* version 1.1.3
* + Add a timeout for the CURL request
*
* version 1.1.2
* + Support of concrete5, contao (aka previously called Typolight), dolibarr, eFront, EspoCRM, formaLMS, phpBB, phpList,
* SilverStripe and x3cms
*
* version 1.1.1
* + Monitored folders for Joomla: files present in a native Joomla's folder (part of the CMS) will
* be analysed
* - If not part of the distribution (intrusion)
* - If part of the distribution but with an another hash (hacked file or, at least, altered one)
*
* version 1.1.0
* + Support CakePHP, Drupal, Magento, PrestaShop (on top of Joomla and WordPress)
* + Improved security by no more loading core Joomla files
* + Advanced menu (left side)
* + Allow to activate debug and expert mode (without any changes in the code)
* + Allow to specify how many files to process by cycle (without any changes in the code)
* + Allow to specify with type of files to ignore (archives, images, medias, ...)
*
* Avoid __DIR__.
*
* __DIR__ is the folder where the running script is started so, perhaps, things like
* c:/sites/hacked/. In most of case, it's correct because the script file has been
* saved there... but not always: think to symbolic links.
* The file can be saved f.i. in c:/repository/aesecure_quickscan/aesecure_quickscan.php
* and a symlink has been made in c:/sites/hacked/. We want that __DIR__ points to the
* hacked site but won't be the case with symlink. __DIR__ is where the file IS REALLY.
*
* So, don't use __DIR__ but c:/sites/hacked/
*/
define('REPO', 'https://github.com/cavo789/aesecure_quickscan');
define('DIR', str_replace('/', DIRECTORY_SEPARATOR, dirname((string) $_SERVER['SCRIPT_FILENAME'])));
define('FILE', str_replace('/', DIRECTORY_SEPARATOR, basename((string) $_SERVER['SCRIPT_FILENAME'])));
// Don't allow to kill this script when demo mode is enabled
// Don't show the "Enable expert mode" checkbox in Demo mode
define('DEMO', false);
define('DEBUG', false); // Enable debugging (Note: there is no progress bar in debug mode)
define('FULLDEBUG', false); // Output a lot of information
define('VERSION', '2.0.3'); // Version number of this script
define('EXPERT', false); // Display Kill file button and allow to specify a folder
define('MAX_SIZE', 1 * 1024 * 1024); // One megabyte: skip files when filesize is greater than this max size.
define('MAXFILESBYCYCLE', 500); // Number of files to process by cycle, reduce this figure if you receive HTTP error 504 - Gateway timeout
define('CONTEXT_NBRCHARS', 100); // When a suspicious pattern is found, the portion of code where this pattern is found will be displayed. The portion is xxx characters before the pattern; the pattern and the same number of characters after it.
define('SHOWMD5', false); // Allow to generate a hash file
define('PROGRESSBARFREQUENCY', 3); // Frequency of updates for the progress bar. In seconds.
define('MEMORY_LIMIT', '256M'); // DEBUG MODE ONLY - Maximum memory limit that will be used
define('CURL_TIMEOUT', 2); // Max number of seconds before the timeout when requesting a JSON file from avonture.be
// Download URL for the file with CMS hashes
define('DOWNLOAD_URL', 'https://raw.githubusercontent.com/cavo789/aesecure_quickscan/master/');
define('MD5', '');
define('DIRNOTFOUND', 'Directory not found');
// List of extensions, by "category". Add an extension if you want to skip that files when
// skipping the category
define('ExtArchives', '7z, bak, gz, gzip, jpa, tar, zip');
define('ExtDocuments', 'doc, docx, pdf, ppt, pptx, xls, xlsx');
define('ExtFonts', 'eot, otf, ttf, ttf2, woff, woff2');
define('ExtImages', 'bmp, eps, gif, ico, icon, jpeg, jpg, png, psd, svg, tiff, webp');
define('ExtMedia', 'css, js, less');
define('ExtSoundMovies', 'aiff, asf, avi, fla, flv, f4v, m4v, mkv, mov, mp3, mp4, mpeg, mpg, ogg, ogv, swf, wav, webm, wma');
define('ExtText', 'ini, json, log, md, mo, po, sql, text, txt, xml, xsl');
define('CRLF', "\r\n");
define('DS', DIRECTORY_SEPARATOR);
// Register error handling functions
set_error_handler(function ($code, $string, $file, $line): never {
throw new ErrorException($string, 0, $code, $file, $line);
});
register_shutdown_function(function () {
$memory = 'ini_get memory_limit=' . ini_get('memory_limit') . ' | ' .
'memory used=' . aeSecureFct::getMemoryUsed();
$error = error_get_last();
});
class aeSecureDebug
{
/**
* Debugging mode state (On / Off).
*
*
* @access private
*/
private static bool $debugMode = false;
/**
* Instantiate the class.
*
* @param bool $debugMode False will hide errors in the browser
* True will activate a verbose mode
*
* @return void
*/
public function __construct($debugMode = false)
{
// Informs PHP where to store errors
ini_set('error_log', DIR . 'aesecure_quickscan_error_log');
// Initialize the debug mode
self::setDebugMode($debugMode);
}
/**
* Set the debugging mode.
*
* @param bool $onOff
*
* @return void
*/
public static function setDebugMode($onOff = false)
{
static::$debugMode = $onOff;
// When debug mode is on, we want to see every messages; even notice.
if (true === static::$debugMode) {
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
ini_set('html_errors', '1');
ini_set('docref_root', 'http://www.php.net/');
ini_set(
'error_prepend_string',
"<div style='color:red; font-family:verdana;" .
"border:1px solid red; padding:5px;'>"
);
ini_set('error_append_string', '</div>');
error_reporting(E_ALL);
} else {
error_reporting(E_ALL & ~E_NOTICE);
}
}
}
class Download
{
// Timeout delay in seconds
public const CURL_TIMEOUT = 2;
public const ERROR_CURL = 1001;
private static $sAppName = '';
private static string $sFileName = '';
private static string $sSourceURL = '';
private static bool $bDebug = false;
private static string $sDebugFileName = '';
public function __construct($ApplicationName)
{
static::$bDebug = false;
static::$sAppName = $ApplicationName;
}
/**
* Enable the debug mode for this class.
*
* @param mixed $bOnOff
*/
public function debugMode($bOnOff)
{
static::$bDebug = $bOnOff;
if ($bOnOff) {
// A debug.log file will be created in
// the folder of the calling script
static::$sDebugFileName = DIR . 'debug.log';
}
}
// URL where the script will find a file to download
public function setURL($sURL)
{
static::$sSourceURL = trim((string) $sURL);
}
/**
* Once download, a file will be created on the disk.
* Use this property to specify the name of that file.
*
* @param mixed $sName
*/
public function setFileName($sName)
{
static::$sFileName = trim((string) $sName);
}
/**
* Download the application package ZIP file.
*
* @param type $url
* @param type $file
*
* @return string
*/
public function download()
{
$wError = 0;
// Try to use CURL, if installed
if (self::iscURLEnabled()) {
// $sFileName is the fullname of the file to create f.i.
// /home/www/username/rootweb/downloaded-file.zip
$fp = @fopen(static::$sFileName, 'w');
if (!$fp) {
throw new Exception(static::$sAppName . ' - Could not open the file!');
}
if (!file_exists(static::$sFileName)) {
$wError = self::ERROR_CURL;
} else {
@fclose($fp);
@chmod(static::$sFileName, 0644);
}
if (0 === $wError) {
// Ok, try to download the file
$ch = curl_init(static::$sSourceURL);
if ($ch) {
// Start the download process
@set_time_limit(0);
$fp = @fopen(static::$sFileName, 'w');
if (!curl_setopt($ch, CURLOPT_URL, static::$sSourceURL)) {
fclose($fp);
curl_close($ch);
$wError = self::ERROR_CURL;
} else {
// Download
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' .
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 ' .
'Safari/537.36 FirePHP/4Chrome');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CURL_TIMEOUT);
// Output curl debugging messages into a text file
if (static::$bDebug) {
// output debugging info in a txt file
curl_setopt($ch, CURLOPT_VERBOSE, true);
$fdebug = fopen(static::$sDebugFileName, 'w');
curl_setopt($ch, CURLOPT_STDERR, $fdebug);
}
// Add CURLOPT_SSL if the protocol is https
if ('https' == substr((string) static::$sSourceURL, 0, 5)) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
}
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
$rc = curl_exec($ch);
curl_close($ch);
fclose($fp);
if (!$rc) {
$wError = self::ERROR_CURL;
}
@chmod(static::$sFileName, 0644);
}
}
}
}
self::removeIfNull();
if (!file_exists(static::$sFileName)) {
// Unsuccessful, try with fopen()
// Use a context to be able to define a timeout
$context = stream_context_create(
['http' => ['timeout' => self::CURL_TIMEOUT]]
);
// Get the content if fopen() is enabled
$content = @fopen(static::$sSourceURL, 'r', false, $context);
if ('' !== $content) {
@file_put_contents(static::$sFileName, $content);
}
self::removeIfNull();
if (file_exists(static::$sFileName)) {
$wError = 0;
}
}
return $wError;
}
/**
* Return a text for the encountered error.
*
* @param mixed $code
*/
public function getErrorMessage($code)
{
$sReturn =
'<p>Your system configuration doesn\'t allow to download the file.</p>' .
'<p>Please click ' .
'<a href="' . static::$sSourceURL . '">here</a> to ' .
'manually download the file, then open your ' .
'FTP client and send the downloaded file to your ' .
'website folder.</p>' .
'<p>Once this is done, just refresh this page.</p>' .
'<p><em>Note: the filename should be ' . static::$sFileName . '</em></p>';
return $sReturn;
}
/**
* Detect if the CURL library is loaded.
*/
private function iscURLEnabled()
{
return (!function_exists('curl_init') && !function_exists('curl_setopt') &&
!function_exists('curl_exec') && !function_exists('curl_close')) ? false : true;
}
/**
* If the file is there and has a size of 0 byte,
* it's a failure, the file wasn't downloaded.
*/
private function removeIfNull()
{
if (file_exists(static::$sFileName)) {
if (filesize(static::$sFileName) < 1000) {
unlink(static::$sFileName);
}
}
}
}
class aeSecureDownload
{
/**
* Download a file from GitHub like "aesecure_quickscan_pattern.json", ...
* See the DOWNLOAD_URL constant for the URL.
*
* @param [type] $file
* @param mixed $uri
*
* @return void
*/
public static function get($file, $uri)
{
try {
// Try to download
$aeDownload = new Download('Quickscan');
$aeDownload->debugMode(DEBUG);
// Be sure to have only one "/" and not two
if (trim('' !== $uri)) {
$uri = ltrim(rtrim((string) $uri, '/'), '/') . '/';
}
$url = rtrim(DOWNLOAD_URL, '/') . '/' . $uri . basename((string) $file);
$aeDownload->setURL($url);
$aeDownload->setFileName($file);
$wReturn = $aeDownload->download();
if (0 !== $wReturn) {
$sErrorMsg = $aeDownload->getErrorMessage($wReturn);
}
} catch (Exception $e) {
$wReturn = 1001;
$sErrorMsg = $e->getMessage();
}
unset($aeDownload);
}
}
/**
* Add localization; read an external json file with translations.
*/
class aeSecureLanguage
{
public const DEFAULT_LANGUAGE = 'en-GB';
// Filename pattern for languages files
public const LANG_FILE = 'aesecure_quickscan_lang_%s.json';
// Hard-coded list of supported languages
// @See https://github.com/cavo789/aesecure_quickscan for xxx_lang_xxxx.json files
public const SUPPORTED_LANGUAGES = 'en;en-GB;fr;fr-FR;nl;nl-BE';
private string $_filename = '';
private $_lang = null;
private $_arrLanguage = null;
private bool $_bLoaded = false;
private $supportedLanguages = null;
private $browserLanguages = null;
protected static $instance = null;
public function __construct($lang = null)
{
$aeSession = aeSecureSession::getInstance();
if (null == $lang) {
$lang = str_replace('_', '-', (string) aeSecureFct::getParam('lang', 'string', '', 5));
}
// Initialize the list of supported languages
$this->supportedLanguages = explode(';', self::SUPPORTED_LANGUAGES);
// Get the list of languages supported by the Browser and by aeSecure
// (presence of the language's file)
self::getBrowserLanguage();
if (in_array($lang, $this->supportedLanguages)) {
// Perfect match
// The language (f.i. nl-BE) is supported; we've a nl-BE.json file; use it
$result = $lang;
} elseif (in_array(substr((string) $lang, 0, 2), $this->supportedLanguages)) {
// If the user ask for f.i. en-US and we've a file for "en", use that file.
// For instance en-GB
$result = substr((string) $lang, 0, 2);
} else {
// No, not found. Use the languages supported by the browser and check if aeSecure
// support that language
$result = '';
// Search for a perfect match so if the language is en_US, try to find en_US.json
// and not en_GB.json
foreach ($this->browserLanguages as $lang => $value) {
if (in_array($lang, $this->supportedLanguages)) {
$result = $lang;
break;
}
}
// If $result is still empty, no perfect match so search on the language and not
// language and country. So, if the language is en-US and if a file en-GB is found, get it.
if ('' == $result) {
$result = 'en-GB';
foreach ($this->browserLanguages as $lang => $value) {
// Check if there is a language file (f.i. if $lang is "fr"
// (and not "fr_FR"), the glob function will return
// the list of files like fr*.json
if (in_array(substr((string) $lang, 0, 2), $this->supportedLanguages)) {
$result = substr((string) $lang, 0, 2);
break;
}
}
}
// Still not? Use en-GB by default
if ('' == $result) {
$result = self::DEFAULT_LANGUAGE;
}
}
$aeSession->set('Lang', $lang);
// Max 5 characters
$lang = substr((string) $lang, 0, 5);
// Just be sure to have en-GB and not f.i. EN-GB or en_gb
$lang = strtolower(substr($lang, 0, 2)) . '-' . strtoupper(substr($lang, -2));
if ('en-US' == $lang) {
$lang = 'en-GB';
}
$this->_lang = $lang;
$this->_filename = DIR . DS . sprintf(self::LANG_FILE, $this->_lang);
$this->_bLoaded = false;
if (!file_exists($this->_filename)) {
// Try to download if not present
aeSecureDownload::get($this->_filename, 'settings/');
}
if (file_exists($this->_filename)) {
$string = file_get_contents($this->_filename);
$string = str_replace('\\u', '\u', $string);
if (null === json_decode($string, true, 512, JSON_THROW_ON_ERROR)) {
die('There is a problem in ' . $this->_filename .
'. Probably an invalid json file <pre>' .
html_entity_decode($string) . '</pre>');
}
$this->_arrLanguage = json_decode($string, true, 512, JSON_THROW_ON_ERROR);
$this->_bLoaded = true;
}
// If the parametrized file isn't found (f.i. the user set fr-FR has
// preferred language and the file is not
// present), then use by default en-GB
if (!$this->_bLoaded) {
// Try to download if not present
$this->_filename = DIR . DS . sprintf(self::LANG_FILE, self::DEFAULT_LANGUAGE);
if (!file_exists($this->_filename)) {
aeSecureDownload::get($this->_filename, 'settings/');
}
if (file_exists($this->_filename)) {
$string = file_get_contents($this->_filename);
$string = str_replace('\\u', '\u', $string);
if (null === json_decode($string, true, 512, JSON_THROW_ON_ERROR)) {
die('There is a problem in ' . $this->_filename . '. ' .
'Probably an invalid json file <pre>' .
html_entity_decode($string) . '</pre>');
}
$this->_arrLanguage = json_decode($string, true, 512, JSON_THROW_ON_ERROR);
$this->_bLoaded = true;
}
}
// Still not? Use the first language file that is present
if ((!$this->_bLoaded) && (count($this->supportedLanguages) > 0)) {
foreach ($this->supportedLanguages as $key => $value) {
$this->_filename = DIR . DS . sprintf(self::LANG_FILE, $value);
if (file_exists($this->_filename)) {
$string = file_get_contents($this->_filename);
$string = str_replace('\\u', '\u', $string);
if (null === json_decode($string, true, 512, JSON_THROW_ON_ERROR)) {
die('There is a problem in ' . $this->_filename .
'. Probably an invalid json file <pre>' .
html_entity_decode($string) . '</pre>');
}
$this->_arrLanguage = json_decode($string, true, 512, JSON_THROW_ON_ERROR);
$this->_bLoaded = true;
$this->_lang = $value;
break;
}
}
}
return true;
}
public function ready(): bool
{
return $this->_bLoaded;
}
/**
* Translation functionality, search the CODE in the json file and returns its
* value (the translated text).
*/
public function get(string $code): string
{
$sText = '';
if (isset($this->_arrLanguage[$code])) {
$sText = $this->_arrLanguage[$code];
}
return $sText;
}
public function getlang(): string
{
return $this->_lang;
}
/**
* $language can be initialized or not. If not, the script will detect supported
* languages as defined in the user's browser. If initialized, should be something
* like 'en-GB', 'fr-FR', ...
*/
public static function getInstance(?string $lang = null): self
{
if (null === self::$instance) {
self::$instance = new aeSecureLanguage($lang);
}
return self::$instance;
}
/**
* Read the HTTP_ACCEPT_LANGUAGE browser info to determine the best language
* to use for aeSecure based on the browser's preferences.
*
* @return string Returns f.i. en-GB, fr-FR, nl-NL, ...
*/
private function getBrowserLanguage(): string
{
$default = null;
$httplanguages = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if (empty($httplanguages)) {
return $default;
}
$this->browserLanguages = [];
$result = '';
// $this->browserLanguages is an array, sorted by priority order, of the
// supported languages; for instance:
// array
// 'fr' => float 1
// 'en_US' => float 0.8
// 'en' => float 0.6
foreach (preg_split('/,\s*/', (string) $httplanguages) as $accept) {
$result = preg_match('/^([a-z]{1,8}(?:[-_][a-z]{1,8})*)(?:;\s*' .
'q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', (string) $accept, $match);
if (!$result) {
continue;
}
$quality = (isset($match[2]) ? (float)$match[2] : 1.0);
$countries = explode('-', $match[1]);
$region = array_shift($countries);
$country_sub = explode('_', $region);
$region = array_shift($country_sub);
foreach ($countries as $country) {
$this->browserLanguages[$region . '-' . strtoupper($country)] = $quality;
}
foreach ($country_sub as $country) {
$this->browserLanguages[$region . '-' . strtoupper($country)] = $quality;
}
$this->browserLanguages[$region] = $quality;
}
return true;
}
}
/**
* A few helping functions.
*/
class aeSecureFct
{
/**
* Remove special characters, f.i clean('a|"bc!@£de^&$f g') will return 'abcdef-g'.
*/
public static function sanitize(string $string): string
{
// Replaces all spaces with hyphens.
$string = str_replace(' ', '-', $string);
// Removes special chars.
return (string) preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
/**
* Generic function for adding a js in the HTML response.
*
* @param type $localfile
* @param type $weblocation
* @param mixed $defer
*
* @return string
*/
public static function addJavascript($localfile, $weblocation = '', $defer = false)
{
$return = '';
// Perhaps the script (aesecure_quickscan.php) is a symbolic link so __DIR__
// is the folder where the real file can be found and SCRIPT_FILENAME his link,
// the line below should therefore not be used anymore
if (is_file(str_replace('/', DS, dirname((string) $_SERVER['SCRIPT_FILENAME'])) . DS . $localfile)) {
$return = '<script ' . (true == $defer ? 'defer="defer" ' : '') .
'type="text/javascript" src="../' . $localfile . '"></script>';
} else {
if ('' != $weblocation) {
$return = '<script ' . (true == $defer ? 'defer="defer" ' : '') .
'type="text/javascript" src="' . $weblocation . '"></script>';
}
}
return $return;
}
/**
* Generic function for adding a css in the HTML response.
*
* @param type $localfile
* @param type $weblocation
*
* @return string
*/
public static function addStylesheet($localfile, $weblocation = '')
{
$return = '';
// Perhaps the script (aesecure_quickscan.php) is a symbolic link so __DIR__ is the
// folder where the real file can be found and SCRIPT_FILENAME his link, the line
// below should therefore not be used anymore
if (is_file(str_replace('/', DS, dirname((string) $_SERVER['SCRIPT_FILENAME'])) . DS . $localfile)) {
$return = '<link href="../' . $localfile . '" rel="stylesheet" />';
} else {
if ('' != $weblocation) {
$return = '<link href="' . $weblocation . '" rel="stylesheet" />';
}
}
return $return;
}
public static function human_filesize($bytes, $decimals = 2)
{
$sz = 'BKMGTP';
$factor = intval(floor((strlen((string) $bytes) - 1) / 3));
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
/**
* Return a string like '1 an 10 mois 6 jours 3 heures'... ie the age of f.i. a file.
*
* echo aeSecureFct::time_elapsed_string(filemtime($filename))
*/
public static function time_elapsed_string(int $ptime): string
{
$diff = time() - $ptime;
$calc_times = [];
$timeleft = [];
// Prepare array, depending on the output we want to get.
$calc_times[] = ['an', 'ans', 31557600];
$calc_times[] = ['mois', 'mois', 2592000];
$calc_times[] = ['jour', 'jour', 86400];
$calc_times[] = ['heure', 'heures', 3600];
$calc_times[] = ['minute', 'minutes', 60];
$calc_times[] = ['seconde', 'secondes', 1];
foreach ($calc_times as $timedata) {
[$time_sing, $time_plur, $offset] = $timedata;
if ($diff >= $offset) {
$left = floor($diff / $offset);
$diff -= ($left * $offset);
$timeleft[] = "{$left} " . (1 == $left ? $time_sing : $time_plur);
}
}
return $timeleft ? (time() > $ptime ? null : '-') . implode(' ', $timeleft) : 0;
}
/**
* Return true when the call to the php script has been done through an ajax request.
*/
public static function isAjaxRequest(): bool
{
$bAjax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
('XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']));
return $bAjax;
}
/**
* Return the memory usage when this function is called. By calling this function
* at different place in the code, it's then possible to determine which part is
* eating a lot of memory.
*
* @return type
*/
public static function getMemoryUsed()
{
$mem_usage = memory_get_peak_usage(true);
return ($mem_usage < 1048576)
? round($mem_usage / 1024, 2) . ' kb'
: round($mem_usage / 1048576, 2) . ' mb';
}
/**
* Safely read values from posted forms ($_POST).
*
* @param mixed $type
*/
public static function getParam(string $name, $type = 'string', mixed $default = '', int $maxlen = 0): mixed
{
$tmp = '';
$return = $default;
if (isset($_POST[$name])) {
if (in_array($type, ['int', 'integer'])) {
$return = htmlspecialchars((string) $_POST[$name], ENT_QUOTES); // filter_input(INPUT_POST, $name, FILTER_SANITIZE_NUMBER_INT);
} elseif ('boolean' == $type) {
// false = 5 characters
$tmp = substr(htmlspecialchars((string) $_POST[$name], ENT_QUOTES), 0, 5); // substr(filter_input(INPUT_POST, $name, FILTER_SANITIZE_STRING), 0, 5);
$return = (in_array(strtolower($tmp), ['on', 'true'])) ? true : false;
} elseif ('string' == $type) {
$return = htmlspecialchars((string) $_POST[$name], ENT_QUOTES); //filter_input(INPUT_POST, $name, FILTER_SANITIZE_STRING);
if ($maxlen > 0) {
$return = substr($return, 0, $maxlen);
}
} elseif ('unsafe' == $type) {
$return = $_POST[$name];
}
} else {
$aeSession = aeSecureSession::getInstance();
// Get from the $_GET only in debug mode or for very few parameters like "lang" (to allow to switch between
// languages) and "aes" (boolean set to 1 when QuickScan is started from within the aeSecure Firewall interface)
if ((true === $aeSession->get('Debug', DEBUG)) || in_array($name, ['aes', 'lang'])) {
if (isset($_GET[$name])) {
if (in_array($type, ['int', 'integer'])) {
$return = htmlspecialchars((string) $_GET[$name], ENT_QUOTES); //filter_input(INPUT_GET, $name, FILTER_SANITIZE_NUMBER_INT);
} elseif ('boolean' == $type) {
// false = 5 characters
$tmp = substr(htmlspecialchars((string) $_GET[$name], ENT_QUOTES), 0, 5);
$return = (in_array(strtolower($tmp), ['1', 'on', 'true'])) ? true : false;
} elseif ('string' == $type) {
$return = htmlspecialchars((string) $_GET[$name], ENT_QUOTES);
} elseif ('unsafe' == $type) {
$return = $_GET[$name];
}
}
}
}
if ('boolean' == $type) {
$return = (in_array($return, ['on', '1']) ? true : false);
}
return $return;
}
}
/**
* Logging functionality.
*/
class aeSecureLog
{
private $_sLogFile = null;
protected static $instance = null;
public function __construct($sLogFile, $killFile = true)
{
$this->_sLogFile = $sLogFile;
if ((true == $killFile) && (file_exists($this->_sLogFile)) && (is_writable($this->_sLogFile))) {
unlink($this->_sLogFile);
}
return true;
}
public function kill()
{
if ((file_exists($this->_sLogFile)) && (is_writable($this->_sLogFile))) {
unlink($this->_sLogFile);
}
}
public function filename()
{
return $this->_sLogFile;
}
/**
* Add a line in the $sLogFile log file.
*
* @param type $sLine
*
* @return type
*/
public function addLog($sLine)
{
if (!is_writable(dirname((string) $this->_sLogFile))) {
return;
}
if ('' != $this->_sLogFile) {
if ($handle = fopen($this->_sLogFile, 'a')) {
fwrite($handle, (string) ($sLine . "\n"));
fclose($handle);
}
}
}
/**
* @param type $sLogFile Name of the logfile that will be used
* @param type $killFile Default True : kill the logfile if present when starting the run
*
* @return type
*/
public static function getInstance($sLogFile = null, $killFile = false)
{
if (null != $sLogFile) {
if (null === self::$instance) {
self::$instance = new aeSecureLog($sLogFile, $killFile);
}
}
return self::$instance;
}
}
/**
* Working with files and folders.
*/
class aeSecureFiles
{