Я использую функцию загрузки файлов на своем веб-сайте PHP / Javascript / jQuery и использую SwiftMailer для отправки файла в качестве вложения в электронное письмо.
Однако я уже давно пыталсячтобы файл прошел проверку API VirusTotal, прежде чем я смогу его отправить.
Вот страницы документации, которые я использовал: https://support.virustotal.com/hc/en-us/articles/115002146469-API-Scripts https://developers.virustotal.com/reference#getting-started https://github.com/IzzySoft/virustotal средимногие другие.Конечно, у меня уже есть ключ API для общедоступного API.
Я уже пытался отправить файл с помощью скриптов AdrianTNT и IzzyOnDroid, но независимо от того, что я пытаюсь, я всегда получаю один и тот же ответ от VirusTotal в verbose_msg :
Запрашиваемый ресурс не входит в число завершенных, поставленных в очередь или ожидающих сканирования
scan_id остается нулевым.
Самое смешное, что VirusTotal должен взять мой файл и поместить его в очередь на сканирование, поэтому в следующий раз, когда я попытаюсь загрузить тот же файл, API должен ответить «-2» (в очереди) или «1» (получил результаты).Но это просто не так, он продолжает отвечать 0 и сообщение выше ...
Вот мой текущий код с помощью скрипта IzzyOnDroid:
//Enclose attachment if it exists
if(isset($_FILES['enclosedFile'])) {
//Security control on file cleared
if(is_uploaded_file($_FILES['enclosedFile']['tmp_name']) &&
virusTotalApproval2($_FILES['enclosedFile']['tmp_name'])==1)
{
//Enclose attachment to prepared message
$message->attach(
Swift_Attachment::fromPath($_FILES['enclosedFile']['tmp_name'])->setFilename($_FILES['enclosedFile']['name'])
);
//Send message (along with attachment)
sendMessage($result,$mailer,$message);
}
//Security control on file failed
else{
echo 'security_issue';
}
}
else{
//Send message without attachment
sendMessage($result,$mailer,$message);
}
require_once("virustotal/virustotal.class.php");
function virusTotalApproval2($fileToScan) {
$apikey = "my_api_key";
$vt = new virustotal($apikey);
$hash = hash('sha256', file_get_contents($fileToScan));
$res = $vt->checkFile($fileToScan); // $hash is optional. Pass the $scan_id if you have it, or the file hash
switch($res) {
case -99: // API limit exceeded
// deal with it here – best by waiting a little before trying again :)
error_log('\nReturned -99');
return -99;
case -1: // an error occured
// deal with it here
error_log('\nReturned -1');
return -1;
case 0: // no results (yet) – but the file is already enqueued at VirusTotal
$scan_id = $vt->getScanId();
$json_response = $vt->getResponse();
error_log('\nReturned 0');
return 0;
case 1: // results are available
$json_response = $vt->getResponse();
error_log('\nReturned 1');
return 1;
default : // you should not reach this point if you've placed the break before :)
}
// deal with the JSON response here
}
В определенный момент я думал, что это былоиз-за файла tmp, поэтому я попытался предоставить файл, который я храню на сервере (хотя это не рекомендуется, поскольку я подозреваю, что файл заражен), используя move_uploaded_file вместо is_uploaded_file скаждый из двух сценариев:
//Initialize tmp dir and filepath
$tmpdir = 'C:/WAMP/www/server/files/';
$fileName = basename($_FILES['enclosedFile']['name']);
//Enclose attachment if it exists
if(isset($_FILES['enclosedFile'])) {
//Security control on file cleared
if(move_uploaded_file($_FILES['enclosedFile']['tmp_name'],$tmpdir.$fileName) && virusTotalApproval2($tmpdir.$fileName)==1)
{
//Enclose attachment to prepared message
$message->attach(
Swift_Attachment::fromPath($tmpdir.$fileName)->setFilename($_FILES['enclosedFile']['name'])
);
//Send message (along with attachment)
sendMessage($result,$mailer,$message);
}
//Security control on file failed
else{
echo 'security_issue';
}
}else{
//Send message without attachment
sendMessage($result,$mailer,$message);
}
Но результат остается прежним.С помощью скрипта AdrianTNT, вот мой код:
//Returns false if there is a problem with the file, or else true
function virusTotalApproval($fileToScan){
// edit the virustotal.com api key, get one from the site
$virustotal_api_key = "my_api_key";
// get the file size in mb, we will use it to know at what url to send for scanning (it's a different URL for over 30MB)
$file_size_mb = filesize($fileToScan)/1024/1024;
error_log('File size: '.$file_size_mb);
// calculate a hash of this file, we will use it as an unique ID when quering about this file
$file_hash = hash('sha256', file_get_contents($fileToScan));
// [PART 1] hecking if a report for this file already exists (check by providing the file hash (md5/sha1/sha256)
// or by providing a scan_id that you receive when posting a new file for scanning
// !!! NOTE that scan_id is the only one that indicates file is queued/pending, the others will only report once scan is completed !!!
$report_url = 'https://www.virustotal.com/vtapi/v2/file/report?apikey='.$virustotal_api_key."&resource=".$file_hash;
$api_reply = file_get_contents($report_url);
error_log('api reply: '.$api_reply);
// convert the json reply to an array of variables
$api_reply_array = json_decode($api_reply, true);
// your resource is queued for analysis
if($api_reply_array['response_code']==-2){
error_log('\nThe answer is -2, file queued.');
}
// reply is OK (it contains an antivirus report)
// use the variables from $api_reply_array to process the antivirus data
if($api_reply_array['response_code']==1){
error_log("\nThe answer is 1, file known. We got an antivirus report, there were ".$api_reply_array['positives']." positives found. Here is the full data: \n\n");
if($api_reply_array['positives']>0)
{
return false;
}else{
return true;
}
}
// [PART 2] a report for this file was not found, upload file for scanning
if($api_reply_array['response_code']=='0'){
error_log('The answer is 0, I don\'t know about that file, but I\'ll take it for scanning and keep you posted.');
// default url where to post files
$post_url = 'https://www.virustotal.com/vtapi/v2/file/scan';
// get a special URL for uploading files larger than 32MB (up to 200MB)
if($file_size_mb >= 32){
$api_reply = @file_get_contents('https://www.virustotal.com/vtapi/v2/file/scan/upload_url?apikey='.$virustotal_api_key);
$api_reply_array = json_decode($api_reply, true);
if(isset($api_reply_array['upload_url']) and $api_reply_array['upload_url']!=''){
$post_url = $api_reply_array['upload_url'];
}
}
// send a file for checking
// curl will accept an array here too:
$post['apikey'] = $virustotal_api_key;
$post['file'] = '@'.$fileToScan;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$post_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$api_reply = curl_exec ($ch);
curl_close ($ch);
$api_reply_array = json_decode($api_reply, true);
if($api_reply_array['response_code']==1){
error_log('Uuuh, it\'s 1 again now...');
error_log("\nfile queued OK, you can use this scan_id to check the scan progress:\n".$api_reply_array['scan_id']);
error_log("\nor just keep checking using the file hash, but it will only report once it is completed (no 'PENDING/QUEUED' reply will be given).");
}
else{
error_log('File hasnt been queued successfully, but verbose msg says: '.$api_reply_array['verbose_msg'].' and scan id says: '.$api_reply_array['scan_id']);
}
}
}
Независимо от того, какой из двух я выбрал для использования, результат остается неизменным.
Когда я обращаюсь к панели моего ключа API, я вижуколичество раз, которое я опрашивал API в «Все», и всегда 0 Не удалось, 0 Успешно ... это означает, что API получает мои файлы, но почему-то отказывается их обрабатывать, по причине, которая не объясняетдостаточно хорошо для меня ...
Я знаю, что мой код имеет много возможностей для оптимизации, и я еще не справился с ситуацией, когда файл заражен скриптом IzzyOnDroid, но я сделаю это позже.
Другие данные: - Я попытался отключить антивирус, следуя теме, которую видел в сети, ничего не изменилось.- Я попытался загрузить файл через веб-сайт, а затем API ответил 1 об этом файле, так как теперь он это знает, так что с этой частью все в порядке.- Файл, который я пытаюсь загрузить, неизвестен VirusTotal и не заражен.Это файл PDF.
Спасибо за помощь.