Giter Site home page Giter Site logo

marcocesarato / php-antimalware-scanner Goto Github PK

View Code? Open in Web Editor NEW
565.0 29.0 98.0 6.71 MB

AMWScan (PHP Antimalware Scanner) is a free tool to scan php files and analyze your project to find any malicious code inside it.

Home Page: https://marcocesarato.github.io/PHP-Antimalware-Scanner/

License: GNU General Public License v3.0

PHP 98.81% Shell 0.32% Dockerfile 0.06% HTML 0.82%
scan wordpress antivirus antimalware cleaner scanner amwscan php malware exploit

php-antimalware-scanner's Introduction

Hi there ๐Ÿ‘‹

I'm Marco Cesarato, a Italian Fullstack Software Engineer.

I'm a weird guy ๐Ÿ‘ฝ who likes making weird things with the technology.

I like to resolve problems, create smart user interfaces and imagine useful interaction, developing rich web experiences & good web and mobile applications. I care about creating high-quality, in terms of UI/UX ๐Ÿ”ญ and performance ๐Ÿš€, applications.

I know likely all the most popular programming languages ๐Ÿ˜†, but I'm ready to pick up new one ๐ŸŒฑ.

  • ๐Ÿ‘ถ Programming since: 2012
  • ๐Ÿ“š Interests: I'm always interested in learning
  • ๐Ÿ˜ Favorite Programming Language: probably are TypeScript and Python, because they can be well structured and is dynamic at the same time, don't need too much external libaries and its learning cost is very low, saving more valuable time
  • ๐ŸŽฎ Hobbies: I like to play to League of Legends and I think to be a decent player, peak elo Master ๐Ÿ˜ƒ

php-antimalware-scanner's People

Contributors

aronnovak avatar dependabot[bot] avatar esurov avatar imgbotapp avatar marcocesarato avatar milosdjakonovic avatar renovate[bot] avatar sommomicc avatar stephanniewerth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-antimalware-scanner's Issues

Lack of unit tests

It would be great to add unit tests to the code to make it more reliable and tested.

FTP Scan :)

I have a suggestion, is it possible to make it possible to scan via FTP?

Feature Requests - Option to e-mail summary report after scan and config option to scan different folders

It would be nice to have a built in option to automatically e-mail scan results after a scan...

Or, better... have a text/config file with paths, command line options, and the e-mail to send the report to.. An example:

/home/website1;auto-skip,only-exploits;[email protected]
/home/website2;scan-all;[email protected]

The e-mail option and the ability to scan different paths with different options would make this solution a lot more effective in battling malware and issues plaguing sites...

Documentation issue and Infinite loop instantiating in non CLI mode

First, documentation.

The README.md file contains a section about instantiating and using this programmatically:

use AMWScan\Scanner;

$app = new Scanner();
$report = $app->setPathScan("my/path/to/scan")
              ->enableBackups()
              ->setPathBackups("/my/path/backups")
              ->enableLiteMode()
              ->setAutoClean()
              ->run();

However this example is invalid due to the fact that the majority of those class methods are actually static.

It has to be said that the documented approach would definitely be preferable as it is a more common object oriented approach.

All or most of those method calls above actually instantiate the object again from scratch because they tend to end with:

return new self();

I guess the documentation needs to be something like this but you'd be instantiating the class at least 6 times:

use AMWScan\Scanner;

Scanner::setPathScan("my/path/to/scan");
Scanner::enableBackups();
Scanner::setPathBackups("/my/path/backups");
Scanner::enableLiteMode();
Scanner::setAutoClean();

$app = new Scanner();

However, the bigger problem with this approach is the __construct method if you're not running via the CLI:

if (!self::isCli()) {
    self::setSilentMode();
}

In case the issue isn't obvious, the setSilentMode method ends in:

return new self();

So you have a code path in the __construct method which results in calling the __construct method therefore there is an infinite loop.

My gut feeling is that the best approach would be to move away from these static methods entirely and make them public class methods and use class properties:

    public function setPathScan($pathScan)
    {
        $this->pathScan = Path::get($pathScan);

        return $this;
    }

This would result in the documented example actually working - assuming similar changes are applied to all of the methods, though there is at least 52 methods that would need to be changed and I suspect there would be many more changes to accommodate that.

$scanner = new Scanner();
$scanner->setPathScan("path")
    ->enableBackups()
    ->setAutoClean();

The simplest solution may be to update the documentation and also change these methods to no longer return themselves. I don't tend to see a lot of that with static method calls so it strikes me as strange but I'm saying that with the ignorance of only having seen a little bit of the Scanner class and not fully understanding the full library.

Any thoughts?

dist version has been detected as malware

The downloadable version in the dist folder has been detected by clamav as malware.

If you look into the file, there are nearly 300 lines of code in the beginning that look suspicious.
It might only download patterns and other necessary stuff with this section - it did not reverse engineered it...

I was only informed by our ISP about this finding - it did not scan myself and thus cannot provide the details at this time.

Is this a known issue?

thanks

Undefined index when running programmatically

In Scanner::arguments a new Argv object is instantiated and later Argv::parse is called.

if (empty($args)) {
	$args = array_slice($_SERVER['argv'], 1); // First argument removed (php [index.php.php] [<path>] [<functions>])
}

Accessing $_SERVER['argv'] when not running via the CLI will cause an undefined index error.

--exploits flag not working ?

Hi, thanks for this amazing tool !
When I try to run a scan with the --exploits flags, it seems it is not working as intended :

This is the command I enter :

php scanner web/app/ --exploits="double_var2"

I get :

Exploit to search: double_var2 Start scanning...

And then :

Evil code found: [!] Function (create_function) [line 61] - Potentially dangerous function 'create_function'

Shouldn't I get only double_var exploits detection ?
Am I missing something ?

Run without CLI?

I'd like to run this script without CLI. I have tried requiring the library I see:

$isCLI = (php_sapi_name() === 'cli');
if (!$isCLI) {
    die('This file must run from a console session.');
}

Is there a way I can run this script without being in CLI? The reason being that many webhosts don't allow CLI.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php >=5.5
  • brainmaestro/composer-git-hooks ^2.8
  • friendsofphp/php-cs-fixer ^3.0
  • marcocesarato/php-conventional-changelog ^1.10
dockerfile
Dockerfile
  • php 8-alpine
github-actions
.github/workflows/php.yml
  • actions/checkout v3
  • actions/cache v3
  • davidlienhard/php-simple-lint 1
  • symfonycorp/security-checker-action v5
html
src/Templates/Report.html
  • jquery 3.6.4
  • twitter-bootstrap 5.2.3
  • popper.js 2.11.6
  • twitter-bootstrap 5.2.3
  • mdbootstrap 4.20.0
  • mdbootstrap 4.20.0
npm
docs/package.json
  • @docusaurus/core 2.3.1
  • @docusaurus/preset-classic 2.3.1
  • @easyops-cn/docusaurus-search-local ^0.34.0
  • @mdx-js/react ^2.0.0
  • @svgr/webpack ^6.0.0
  • clsx ^1.1.1
  • file-loader ^6.2.0
  • react ^18.0.0
  • react-dom ^18.0.0
  • url-loader ^4.1.1

  • Check this box to trigger a request for Renovate to run again on this repository

The "files finding" gives inconsistent result across platforms based on same set of files.

Description
When launch awscan to scan a folder, i.e. awscan wordpress, it sometimes check files and sometimes not, I tried same set of files in different hosting and local, gives inconsistent result.

Problem Reproduction Step
Local environment: MacOS 10.14.x terminal
PHP 7.4.22
awscan.phar
1 Create a dummy folder eg. wordpress
2 cd wordpress
3 wp core download # download a new set of WordPress
4 awscan wordpress OR awscan ./ # depends the PWD
It shows:
[===============================] 100% 1061/1061 [1 sec/0 sec]
Found 0 files to check

Then I test in hosting A ssh with same steps
Fedora release 31 (Thirty One)
PHP 7.4.29
awscan.phar
It shows:
[=============================> ] 100% 1060/1061 [3 min/0 sec] # The number seems wrong, should be 1061/1061

                                SUMMARY                                     

Files scanned: 1061
Files edited: 0
Files quarantined: 0
Files whitelisted: 0
Files ignored: 18

And I test in hosting B ssh with same steps
CentOS Linux release 7.9.2009 (Core)
PHP 7.4.29
awscan.phar
It shows the same result as in local.

So I am not sure what makes the difference. While they all detect there are 1061 files,
sometimes it scan and sometimes it does not.

false positive on doubleval

[!] Signature (11413268) [line 180]
    - Malware Signature (hash: 11413268)
      => eval($_REQUEST
180 | $val = doubleval($_REQUEST...

Please declare exact PHP extension requirements

it happened that was testing this tool on empty system, with only php php-cli installed. Each run resulted in no any kind of output and 255 exit status code.

I have blindly installed php-xml php-zip php-mbstring php-json php-common php-curl php-gd packages - after that it worked. No idea which of them was required though.

Open with VIM open at line

When user choses open with vim it would be great to open at line where the problem is.
Vim allows to open the file at certain line of code, e.g. vim +546 functions.php

Should identify compose packages and validate their checksums

Hi,

while scanning encountered really annoying issue, when scanned laravel project or projects with phpunit, there is constant detection of evil functions. Wouldn't it be better to skip these packages, by detected whether composer.json, composer.lock or vendor/autoload.php exists and just scan vendor dir for package files and validate their checksums, instead of file by file scan.

Best regards :-)

Chosen Dot-Files on font loading in console mode prevents scanning

Problem:

In console mode, an iterator randomly selects fonts. DirectoryIterator also includes dot files (.|..). If it selects one of these as a font, no scans are made.

Possible fonts for the DirectoryIterator:

stop.flf
colossal.flf
basic.flf
smkeyboard.flf
rozzo.flf
ansishadow.flf
..
.

Selected font: /XYZ/vendor/marcocesarato/amwscan/src/Console/Fonts/..

Console Output:

Warning: file(/XYZ/vendor/marcocesarato/amwscan/src/Console/Fonts//XYZ/vendor/marcocesarato/amwscan/src/Console/Fonts/..): failed to open stream: No such file or directory

# Output report:
1^ {#250
  +"scanned": 0
  +"detected": 0
  +"removed": []
  +"ignored": []
  +"edited": []
  +"quarantine": []
  +"whitelist": []
  +"infectedFound": []
}

So nothing was done. You have to check for the scanned key in the report for a plausibility check and have to rerun it until no dot files are selected.

Possible fix:

Use FilesystemIterator with SKIP_DOTS flag.

Build fails

gene@Genes-MacBook-Air PHP-Antimalware-Scanner % composer build

php bin/build
PHP Fatal error: Uncaught UnexpectedValueException: creating archive "/Users/gene/Work/WordPress Antivirus Project/PHP-Antimalware-Scanner/dist/scanner.phar" disabled by the php.ini setting phar.readonly in /Users/gene/Work/WordPress Antivirus Project/PHP-Antimalware-Scanner/bin/build:31
Stack trace:
#0 /Users/gene/Work/WordPress Antivirus Project/PHP-Antimalware-Scanner/bin/build(31): Phar->__construct('/Users/gene/Wor...')
#1 {main}
thrown in /Users/gene/Work/WordPress Antivirus Project/PHP-Antimalware-Scanner/bin/build on line 31
Script php bin/build handling the build event returned with error code 255

Scanner stops at 96%

Hi there,

I ran multiple scans with

php scanner ./website -l --only-signatures

but the scanner stops at 96% and user@ssh:/var/www/user/html is displayed next to the estimated time.

Is there anything i do wrong or could this be a bug?

Thanks in advance

Signatures for the Symfony Process component

The Antimalware Scanner would detect the existence of the Symfony Process component as it makes extensive use of the exec proc_* and posix functions but one thing the scanner doesn't account for is if the environment - by design - already includes that component but the code we're scanning may be attempting to use it which may have undesirable effects.

"Don't have the Symfony Process component in your environment" seems like a sensible solution but one that doesn't work for us unfortunately.

For example, this code would be blocked by the scanner:

exec("rm -rf /path/to/delete");

But this code wouldn't be:

$process = new Process("rm -rf /path/to/delete");

Yet the effect is the same.

Is it worth adjusting the scanner to detect potential usages of this component? There may be others out there, of course, but Symfony Process is the only one that affects us at this time.

There is a small desired option --report

With option -r Currently it only stores the path file to scanner_infected.log, without saving the malware content.

You can update additional malware content to the file scanner_infected.log.

In files : https://github.com/marcocesarato/PHP-Antimalware-Scanner/blob/master/dist/scanner

Line 1044: self::$summary_ignored[] = $_FILE_PATH
=> self::$summary_ignored[] = $_FILE_PATH . "\n" . implode("\n", array_keys($pattern_found));

I think so, because I cannot edit your file.
Thank you so much!

Run silently?

Is there a way to run this command silently? E.g. without any output being returned?

scanner_whitelist.csv ignored?

hi,
running the latest version on a ubuntu 18.04 host,
created scanner_whitelist.csv after the first run correctly,
but in the second run it shows me the same files as in the first run even though they are in the csv file mentioned.
even the file row number is the same.

am I missing something?

Commit fails

Trying to commit php code to the repo fails with a PHP Deprecated

gene@Genes-MacBook-Air PHP-Antimalware-Scanner % git commit -m bin/build
Checking PHP Lint...
[Done] Operation completed!
PHP Deprecated:  Return type of Symfony\Component\Console\Helper\HelperSet::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in phar:///Users/gene/Work/WordPress Antivirus Project/PHP-Antimalware-Scanner/bin/composer/vendor/symfony/console/Helper/HelperSet.php on line 112

too many false positives.

It is impossible to use this scanner.
Is any word with 'eval' or 'lave' a malware?
and like this many more, I have wasted half an hour scanning and reviewing and they are all false positives.

Path error can not write file scanner_infected.log

I stood at folder: /var/www/
Run: php scanner code/ -r

Result:
Files infected: 'phar:///var/www/scanner/scanner_infected.log'

If that is: Files infected: 'phar:///var/www/scanner_infected.log' ( not folder scanner )

Disable check checksums

Hello ,

Can I know how to disable checksums plugins check? I have hundreds wordpress wait to scan.

Thanks.

PHP scanner crashes

Hi
Currently trying to run it locally and on docker it starts scanning then crashes

Unwanted functionality or bug: .php files shall not be scanned if MIME type not satisfied

to demonstrate this issue, download zip of https://github.com/x-o-r-r-o/PHP-Webshells-Collection, unzip files,

run scan

see that a small number of files was undetected (G-Security-Webshell.php, b374v2.8-b374k.php, bayz21-priv-shell-v1.php ...).

I was dazzled why I cannot detect these files no matter what regex I place in the signatures.

I found that this files was application/octet-stream and still valid php.

PR is on the way.

O yeah, with this change, PHP Antimalware Scanner detects this files easily.

[Feature request] Make it possible to use wildcards for path(s)

I'd like to (only) scan all public and web folder in a given folder tree, like this:

php scanner /var/www/*/web

It should scan all folders called "web" in any folder below /var/www/, but it only scans the first folder it encounters. Am I doing something wrong, or is this not possible?

Could not open input file: scanner

Hi,

I'm getting the following error when I executed this command:

php -d disable_functions='' scanner -a
Could not open input file: scanner

It would be great if you could help me to fix the issue and run the scanner smoothly.

Thanks in advance.

Scanning wordpress site

Hi!
This is my frst qiestion on GItHub(sorry if something wrong)
I have report which say that:
Exploit nano Line: 2627 "Dangerous"
screenshot

Its basic wordpress file, At all other wordpress scanning programs and plugins its not an issue, Can You explain what im not understand and maybe need to report wordpress developers also?
Thanks a lot,
Serfer

Could not open input file: awscan

when running the commands

 amwscan 

&&

php amwscan ./mywebsite/http/ -l -s --only-exploits

I'm getting errors:

 Could not open input file: awscan

&&&

php awscan --all

Could not open input file: awscan

would I have to restart or implement something to make it work as described?

A question about malware signatures contribution

Hi.
Do you accept malware signatures contribution?
If yes, how is that done: are the src/Signatures.php Signatures::$raw and Signatures::$regex what we could update?

Do you enforce limits regarding regex / raw rule length or complexity?

Last but not least, how do I as a contributor prove that the code is malware? Example, a few lines of readable and nicely formatted code (no eval|gunzip|base64_decode crap):

# pseudo - code
if [...] $_GET['username'] === md5([...]) 
move_uploaded_file($_FILES['file']['tmp_name'], $_GET['filename'])

most certainly this does not have to be malware per se, but if I add info that this file suddenly occurred as dodgy WP plugin ("WP plugin"), than it's a different call.

It doesn't seem possible to disable the HTML report

Given the following code:

$scanner = new \AMWScan\Scanner();
$report = $scanner->setPathScan("/path/to/scan")
	->enableLiteMode()
	->disableReport()
	->disableReportMode()
	->run();

Executing this will still generate the HTML report. I tried various combinations as I wasn't totally clear of the difference between disableReport and disableReportMode.

disableReportMode seems to cancel out disableReport because setReportMode seems to always call enableReport:

/**
 * @return self
 */
public static function setReportMode($mode = true)
{
    self::$settings['report-mode'] = $mode;
    self::enableReport();

    return new self();
}

My understanding is that all reporting should be disabled anyway if not using the CLI:

if (!self::isCli()) {
    self::$settings['silent'] = true;
    self::$settings['report'] = false;
    self::$settings['report-mode'] = false;
    self::$prompt = 'skip';
}

But I believe the Scanner::arguments method may be overriding this:

// Report mode
self::setReportMode((isset(self::$argv['report']) && self::$argv['report']) || !self::isCli());

As I noted above, regardless of what is passed into setReportMode the enableReport method is called.

Also you seem to be enabling report mode when NOT running in CLI which is the opposite of what happens in the constructor.

This all being said, I think I actually quite like the HTML generated report and I may well end up using it in my project so if fixed, I'm hoping it will still be possible to generate the HTML report even if not using the CLI.

Skipping repetitive functions.

Hi,
I have a question if it can be added that the report will list all dangerous functions, because so far it is only one (first) suspicious function and it omits the rest with the same name. Thanks.

Attempt to remove exploits without any confirmation

Is it possible to run the scanner and let it try to fix any exploits, without running through a confirmation prompt? E.g. I am running this script outside of CLI and I need to run a command that will scan and attempt to fix the exploits in one-go, without any user confirmation.

--path-report does not seem to work as documented

I'm sorry if I have missed something big but this option --path-report='' does not seem to work like declared:

--path-report <path>                           - Set report log file
                                                 [default: ./scanner-report.html]

If I run my scan like in example:

/usr/bin/php7.2 /opt/awscan.phar '/path/to/site' --report --path-report='/tmp/something' --report-format='txt' --disable-checksum --silent

I get:

  • /tmp/something isn't generated
  • /tmp/something.log is generated and is ok - has all the info needed

This two are not the same thing and may be confusing for user - for example, I don't know if it is a bug or poorly worded feature.

Suggestion: if this isn't a bug, improve wording: "Set report log file path and name. Note that name will be appended with .log extension.".

Changing scanner ERROR Uncaught PharException:

Hi,

I have edited the /scanner file to send report via POST json method and it throws following error, even after removing empty lines it throws the same error. Can you help with the reason?

php scanner /home/ --auto-skip
PHP Fatal error: Uncaught PharException: phar "/scanner" does not have a signature in /scanner:8
Stack trace:
#0 /scanner(8): Phar::webPhar()
#1 {main}
thrown in /scanner on line 8

Regards

Add ignored paths

As I am currently writing an app that is supposed to run scans on a webserver in a WEB GUI, and not through the CLI, it would be helpful if this command could be run in batches (e.g. batch 1, batch 2, batch 3).

I have coded some logic that does exactly this, but I need some kind of --ignore="" flag so I can set a base path to scan, but tell it to ignore lots of folders.

This way I can run scan multiple times, and each time ignore a different set of folders. E.g.

 scan --ignore="/some/path/, /some/other/path/, /some/third/path/"

Allow user level scans

At present, when PHP Antimalware Scanner comes to unreadable directory unrecoverable error happens and all subsequent actions are gone. It's enough that there's a single unreadable dir (probably the same is true for file) and the whole scan is error-terminated.

In my opinion this isn't the best design; also, a non-root scans are frequently affected by this.

Solution: allow scanner to skip unreadable directories (PR is on the way).

Anyone help me ,I am noob

Bro ,i need Tutorial ,how To install and Use That Tools bro ,because after the update, a little confusing
i am using Termux in android
Screenshot_2020-07-10-00-40-43-26

Binary output of a file breaks OPTIONS prompt

When scanning all files (--all option), PAS tries to output binary file which may lead to OPTIONS prompt being broken - whatever you type, opt 1 - 8 or - leads to warning (Option not found! Retry...). IMO, somehow, there are characters in your prompt before you enter your option of choice.

To reproduce:
take some .zip file, for example wordpress-seo-16.7.zip and scan it in empty dir.

Proposition:
Disable OPTIONS prompt when file extension doesn't belong to default extension set...

Scanner crash when encountering certain kind of malware

Hi there,

I use your scanner on multiple websites, but some times, it crashes prematurely (like described in issue #46 for example).

So I tried to run the scanner on sub directory until I find THE one which makes the scanner crashed.

I found a malware (attached), I move it to quarantine, then ran the scanner again : it didn't crash !

What's really weird is that if I run the scanner on the quarantine, it doesn't crash ...

(the file was a dot php file of course, renamed it to txt to upload it)

2308ba68.txt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.