Monitor GMAIL Account Activity Using Perl

As recently noted over at my favorite website lifehacker.com…Google has recently added a nice feature to GMAIL that allows you to see your account activity.
If you scroll to the bottom of you Inbox, you will see something that looks like this.
This really got me thinking. This is a great feature, however its lacking in a few areas.

1) I’d like to know when suspicious activity is occuring. Although the likelyhood is low (that someone is trying to hack in…at least I  think), I’d still like to have alerts that tell me there is an issue.

2)  I’d also like tracking details in case there is an issue, I can try to figure out who it is,and where they are coming from.  Actually, when I first looked at this, I noticed someone or somethign was hitting me from 67.228.182.163. Using my technical efficentcies…I was able to track it back to Xoopit. Another service I found over at lifehacker.com.

The process was basically taking the IP in the activity window and doing a whois lookup. The problem is that the whois, generally returns the ISP. However, luckily there was an RWHOIS available. That pointed me to Xoopit!
Well, from here I decided to write a script that will run every 30 mins, Alert me if something looks suspicious.

It does the following.
1) Logs into Gmail.
2) Pulls up Account Activity Page
3) Parses Page.
4) If IP is not in the whitelist…
a. does a Whois Loopup on the IP
b. generates

5) If the count of suspicious IP’s is > 0. Sends and email using Gmail as SMTP server to whomever cares to know.
HERE IS THE CODE:
Use it as you wish. If you have issues or like it, please leave comments.
#!c:\\perl\\bin
#use strict;
use WWW::Mechanize;
use HTTP::Cookies;
use HTML::TableExtract;
use Net::Whois::IP qw(whoisip_query);
use chilkat;
our $count = 0;
my %Whitelist = 
		( 	
			'67.228.182.163' => 'Xoopit',			
			'ip.ip.ip.ip' => 'Work'			
		);
 
my $capture = GetGoogleActivity();	
my $HTML = ParseActivity($capture);
 
print "Count = $count\n";
if ($count > 0) {
	DoEmail("GMAIL: Possible Suspicious Activity", $HTML);
}
 
 
 
sub GetGoogleActivity {
###go to login page and login.
	my $url = "https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=1k96igf4806cy&ltmpl=default&ltmplcache=2&hl=en";
	my $username = "someone@gmail.com";
	my $password = "password";
	my $mech = WWW::Mechanize->new();
	$mech->cookie_jar(HTTP::Cookies->new());
	$mech->get($url);
	$mech->form_number(1);
	$mech->field(Email => $username);
	$mech->field(Passwd => $password);
	$mech->click();
	#Go to the next link, now that we are logged in.
	$url = 'https://mail.google.com/mail/?ui=2&ik=46e3aa5be5&view=ac';
	$mech->get($url);
	my $output_page = $mech->content();
	return $output_page;
}
 
sub ParseActivity {
my ($capture) = @_;
 
$te = HTML::TableExtract->new( depth => 3, count => 1);
$te->parse($capture);
$table = $te->first_table_found;
foreach $ts ($te->tables) {
     foreach $row ($ts->rows) {
		#for my $r (@$row) {
			$type = @$row->[0];
			$ip = @$row->[1];
			$when = @$row->[2];
			$type = RemoveWhiteSpace($type);
			chop($ip);
			$ip = RemoveWhiteSpace($ip);
 
			$when = RemoveWhiteSpace($when);	
			print "Whitelisted IP [$ip] = $Whitelist{$ip}\n";
			if ($ip !=~ "?") { 
					if (! $Whitelist{$ip}) {
						#if (($ip !=~ "?") && (! $Whitelist{$ip})) {
						$HTML = $HTML . "<table broder=\"1\">\n<th colspan=\"3\" align=\"left\">Connection From $ip</th>\n<tr>\n<td>$type</td><td>$when</td><td>$ip</td>\n</tr>\n";
						#print "$type\t$when\t$ip\n\n";
						$HTML = Whois($ip,$HTML);
						$HTML = $HTML . "</table>\n";
					}
			}		
				#}
 
 
			#$html = "$html" . "$town \t $d<br>\n";
			#$count++;
		}
	}
	return $HTML;	
}
 
sub Whois {
	$count++;
	my ($IP,$html) = @_;	
	print "Looking up $IP\n";
	my $response = whoisip_query($IP); 
	foreach (sort keys(%{$response}) ) { 
		$html = $html . "<tr><td colspan=\"2\">$_</td><td>$response->{$_}</td></tr>\n";		 
	}
	return $html;
}
 
sub RemoveWhiteSpace {
	my ($val) = @_;
	for ($val) {
		s/\*//; #Also removes *
		s/^\s+//;
		s/\s+$//;		
	}
return $val;
}
 
sub DoEmail {
my ($title,$description) = @_;
# file: GMail.pl
print "$title\n $description\n";
# Perl script to send email using GMail as the SMTP server.	
 
 
$mailman = new chilkat::CkMailMan();
$mailman->UnlockComponent('anything for 30-day trial');
 
# Set your SMTP server's hostname
$mailman->put_SmtpHost('smtp.gmail.com');
 
# GMail requires a login/password to send mail.
# Strings containing a '@' should always be in single quotes.
$mailman->put_SmtpUsername('someone@gmail.com');
$mailman->put_SmtpPassword("password");
 
# The default SMTP port is 25.  When using it, GMail requires STARTTLS.
$mailman->put_StartTLS(true);
 
# Alternatively, you may comment-out the STARTTLS line and instead use SSL
# on port 465 by commenting-in these 2 lines:
# $mailman->put_SmtpPort(465);
# $mailman->put_SmtpSsl(true);
 
# If you are connected to a network that blocks outbound port 25 connections,
# use GMail's alternative port 587.  You'll need STARTTLS, so uncomment the 
# STARTTLS line and make sure the two lines for SMTP SSL are commented out.
$mailman->put_SmtpPort(587);
 
$mht = new chilkat::CkMht();
$mht->UnlockComponent('anything for 30-day trial');
 
open(INFO, ">GmailActivity.html");
$body = "<html>
<head>
<html>$description
</html>";
print INFO "$body";
close INFO;
 
# Instantiate a new email object.
$email = new chilkat::CkEmail();
$email = $mht->GetEmail('GmailActivity.html');
$email->put_Subject($title);
#$email->put_Body($body);
$email->put_From('Greg The Great! <someone@gmail.com>');
 
# Add some recipients
$email->AddTo('Email','someone@gmail.com');
 
 
 
$success = $mailman->SendEmail($email);
if (! $success)
    {
	$mailman->SaveLastError('lastError.txt');	
    }
else 
{
	# The log will contain information allowing you to verify
	# what actually happened.
	# If you see an error "Error authenticating server credentials!" this is 
	# normal and OK.
	$mailman->SaveLastError('lastInfo.txt');	
}
 
}

About the Author

Greg

Leave a Reply

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>


Warning: stristr() [function.stristr]: Empty delimiter in /home/thegard5/public_html/gregjessup/wp-content/plugins/wassup/wassup.php on line 2093