Linux – Monitoring sendmail function (php) usage

Often we can encounter server that started to send spam (infected page, virus inside php file, bad plugin).

If its our own server we can very easily monitor usage of sendmail which is commonly used in php to send mails, and we will do it with usage of simply ‘wrapper’ .

 

1. Create /usr/local/bin/phpsendmail:

vi /usr/local/bin/phpsendmail
### content ###
#!/usr/bin/php
<?php

/**
  This script is a sendmail wrapper for php to log calls of the php mail() function.
  Author: Till Brehm, www.ispconfig.org
  (Hopefully) secured by David Goodwin <david @ _palepurple_.co.uk>
*/

$sendmail_bin = '/usr/sbin/sendmail';
$logfile = '/tmp/mail_php.log';

//* Get the email content
$logline = '';
$pointer = fopen('php://stdin', 'r');

while ($line = fgets($pointer)) {
        if(preg_match('/^to:/i', $line) || preg_match('/^from:/i', $line)) {
                $logline .= trim($line).' ';
        }
        $mail .= $line;
}

//* compose the sendmail command
$command = 'echo ' . escapeshellarg($mail) . ' | '.$sendmail_bin.' -t -i';
for ($i = 1; $i < $_SERVER['argc']; $i++) {
        $command .= escapeshellarg($_SERVER['argv'][$i]).' ';
}

//* Write the log
file_put_contents($logfile, date('Y-m-d H:i:s') . ' ' . $_ENV['PWD'] . ' ' . $logline, FILE_APPEND);
//* Execute the command
return shell_exec($command);
?>
### end of content ###

Lets check where is sendmail:

which sendmail

If its not in this localization /usr/sbin/sendmail then we will need to edit above script

Setup right permissions for file:

chmod +x /usr/local/bin/phpsendmail
#make log file
touch /var/log/mail.form
chmod 777 /var/log/mail.form

2.  Next we need edit php.ini file

vi /etc/php5/apache2/php.ini
#change this code:
[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
## to this:
[mail function]
; For Win32 only.
;SMTP = localhost
;smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = /usr/local/bin/phpsendmail

If we use PHP as CGI or suPHP, you need edit also /etc/php5/cgi/php.ini

Restart service:

service apache2 restart

3. Lets test our wrapper

Create mailtest.php in www directory ex. /var/www/example.com/public_html

<?php
mail('yourname@yourdomain.com','This is a test message subject','This is a test message body');
echo 'Mail sent.'; 
?>

Open file in browser

Check if you have something in log file:

cat /var/log/mail.form

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*