Friday, May 11, 2012

Using the VirusTotal API v2.0


VirusTotal is a very useful Website for getting the opinions of >40 anti-virus products as to whether or not a file is infected with malware.  What is particularly interesting is that in addition to their Web interface, they offer an API for their service (https://www.virustotal.com/documentation/public-api/).  While their documentation for their API is good, all of the code examples are in Python.  The code snippets below illustrate how to interact with the VirusTotal API using Perl.  The first LWP request of the application demonstrates the submission of a file to VirusTotal.  The JSON response is then processed to obtain the SHA256 hash of the submitted file, which in turn is used as part of a second request to VirusTotal to retrieve the scan results.  The response from the second request will indicate how many AV products flagged the file as containing a virus. 

In terms of testing the API, it may be helpful to consider using EICAR test strings (http://www.eicar.org/86-0-Intended-use.html) as they provide a safe way to trigger the majority of AV scanners.  The Test.txt file used to test the code provided here contained an EICAR test string.  

 #!usr/bin/perl

# Copyright 2012- Christopher M. Frenz
# This script is free software - it may be used, copied, redistributed, and/or modified
# under the terms laid forth in the Perl Artistic License

use LWP::UserAgent;
use JSON;
use strict;

#Code to submit a file to Virus Total
my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 1 });
my $url='https://www.virustotal.com/vtapi/v2/file/scan';

my $key='YourKeyHere';

my $response = $ua->post( $url,
    Content_Type => 'multipart/form-data',
    Content => ['apikey' => $key,
    'file' => ['Test.txt']]
  );
die "$url error: ", $response->status_line
   unless $response->is_success;
my $results=$response->content;

#pulls the sha256 value out of the JSON response
#Note: there are many other values that could also be pulled out
my $json = JSON->new->allow_nonref;   
my $decjson = $json->decode( $results);
my $sha=$decjson->{"sha256"};
print $sha ."\n\n";

#Code to retrieve the results that pertain to a submitted file by hash value
$url='https://www.virustotal.com/vtapi/v2/file/report';

$response = $ua->post( $url,
    ['apikey' => $key,
    'resource' => $sha]
  );
die "$url error: ", $response->status_line
   unless $response->is_success;
$results=$response->content;

#processes the JSON to see how many AV products consider the file a virus
$json = JSON->new->allow_nonref;   
$decjson = $json->decode( $results);
print $decjson->{"positives"};

112 comments: