#!/usr/bin/perl

#
# $Id: securemail.pl 21 2010-11-18 09:37:16Z deploy $
#
# This will tell you who is emailing from your server and where from. Good for diagnosing which person has an insecure website and is sending spam via a PHP application. Possible to use for other services also.
#
# Put this into where ever you want the mail logged from. edit where $mailprog is for this particular server (if you use postfix or qmail etc then find the path and put that instead
#
# Edit php.ini and adjust the sendmail_path to be this script
# If you want to do it domain by domain you can add the following line into your virtualhost
#	php_admin_value sendmail_path "/usr/local/securemail.pl "
#
# Now for the finale, chmod +x /usr/local/securemail.pl (or where ever you put the script)
# touch /var/log/formmail.log ; chown www-data.www-data /var/log/formmail.log
# Basicly create and make sure apache user owns/can write to the log.
#
# The alternative is to rename your mta (mv sendmail sendmail.real) and ln -s /usr/local/securemail.pl /usr/sbin/sendmail then use /usr/sbin/sendmail.real as $mailprog which will log mail sent from any application
#
# The layout of the formmail.log is  date - pwd - user information 
# ie Mon Sep  1 21:12:04 UTC 2008 - /var/www/html - apache x 48 48   Apache /var/www /sbin/nologin
#
#
#use strict;
use Env;
my $date = `date`;
chomp $date;
open (INFO, ">>/var/log/formmail.log") || die "Failed to open file ::$!";
my $uid = $>;
my @info = getpwuid($uid);
if($REMOTE_ADDR) {
print INFO "$date - $REMOTE_ADDR ran $SCRIPT_NAME at $SERVER_NAME \n";
}
else {

print INFO "$date - $PWD - @info\n";

}
#my $mailprog = '/usr/sbin/exim -t ';
my $mailprog = '/usr/sbin/sendmail.postfix -t -i ';
foreach (@ARGV) {
$arg="$arg" . " $_";
}

open (MAIL,"|$mailprog $arg") || die "cannot open $mailprog: $!\n";
while (<STDIN> ) {
print MAIL;
}
close (INFO);
close (MAIL);
