Created
July 21, 2009 04:26
-
-
Save dap/151109 to your computer and use it in GitHub Desktop.
Detect PHP in non-php files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl | |
| # php_watch.pl - Monitor directory for PHP code in non-.php files | |
| # Darian Anthony Patrick <[email protected]> | |
| # | |
| # Uses inotify to monitor a directory for the | |
| # existence of files containing PHP code which | |
| # are not named with a .php file extension | |
| use perl5i; | |
| use threads; | |
| use Thread::Queue; | |
| use Proc::Daemon; | |
| use Sys::Syslog qw(:standard :macros); | |
| use Linux::Inotify2; | |
| use IO::All; | |
| use Net::SMTP::OneLiner; | |
| sub inspect_file { | |
| my $file_path = shift; | |
| # Skip PHP files | |
| return | |
| if $file_path =~ m/\.php$/; | |
| syslog(LOG_INFO, "Inspecting $file_path..."); | |
| my $file = io($file_path); | |
| for (@$file) { | |
| if ( m/<\?php|<\?=|\[%/ ) { | |
| my $message = "$file_path appears to contain PHP!"; | |
| syslog(LOG_ALERT, $message); | |
| send_mail( | |
| '[email protected]', | |
| '[email protected]', | |
| "php_watch alert: $file_path", | |
| "$file_path appears to contain PHP!" | |
| ); | |
| return; | |
| } | |
| } | |
| syslog(LOG_INFO, "$file_path OK"); | |
| } | |
| sub main { | |
| # Check that a directory was supplied | |
| unless ( defined $ARGV[0] && -d $ARGV[0] ) { | |
| say STDERR 'Error: Please supply a directory to watch.'; | |
| exit 1; | |
| } | |
| # Open syslog | |
| openlog('php_watch', '', LOG_USER); | |
| # Daemonize process | |
| Proc::Daemon::Init(); | |
| syslog(LOG_INFO, "Daemon started; watching $ARGV[0]"); | |
| # Create queue for processing new files | |
| my $file_queue = Thread::Queue->new(); | |
| # Create thread handling file inspection | |
| my $inspect_thread | |
| = threads->create(sub { | |
| while ( my $file_path = $file_queue->dequeue() ) { | |
| inspect_file($file_path); | |
| } | |
| })->detach(); | |
| my $inotify = Linux::Inotify2->new() | |
| or die "Could not create new inotify object: $!"; | |
| # Define filesystem events which require inspection | |
| $inotify->watch( $ARGV[0], IN_CREATE | IN_MODIFY | IN_MOVED_TO, sub { | |
| my $e = shift; | |
| $file_queue->enqueue($e->fullname); | |
| }); | |
| # Start manual event loop, waiting for events in supplied directory | |
| 1 while $inotify->poll; | |
| } | |
| main() if $0 eq __FILE__; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment