public async void GetReportForRecentFile()
        {
            //We ignore these fields due to unknown file
            IgnoreMissingJson(" / MD5", " / Permalink", " / Positives", " / scan_date", " / Scans", " / SHA1", " / SHA256", " / Total");

            ScanResult result = await VirusTotal.ScanFileAsync(TestData.GetRandomFile(128, 1).First(), TestData.TestFileName);

            FileReport fileReport = await VirusTotal.GetFileReportAsync(result.ScanId);

            Assert.Equal(FileReportResponseCode.Queued, fileReport.ResponseCode);
        }
Esempio n. 2
0
    private static async Task Main(string[] args)
    {
        VirusTotal virusTotal = new VirusTotal("YOUR API KEY HERE");

        //Use HTTPS instead of HTTP
        virusTotal.UseTLS = true;

        //Create the EICAR test virus. See http://www.eicar.org/86-0-Intended-use.html
        byte[] eicar = Encoding.ASCII.GetBytes(@"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*");

        //Check if the file has been scanned before.
        FileReport fileReport = await virusTotal.GetFileReportAsync(eicar);

        bool hasFileBeenScannedBefore = fileReport.ResponseCode == FileReportResponseCode.Present;

        Console.WriteLine("File has been scanned before: " + (hasFileBeenScannedBefore ? "Yes" : "No"));

        //If the file has been scanned before, the results are embedded inside the report.
        if (hasFileBeenScannedBefore)
        {
            PrintScan(fileReport);
        }
        else
        {
            ScanResult fileResult = await virusTotal.ScanFileAsync(eicar, "EICAR.txt");

            PrintScan(fileResult);
        }

        Console.WriteLine();

        string scanUrl = "http://www.google.com/";

        UrlReport urlReport = await virusTotal.GetUrlReportAsync(scanUrl);

        bool hasUrlBeenScannedBefore = urlReport.ResponseCode == UrlReportResponseCode.Present;

        Console.WriteLine("URL has been scanned before: " + (hasUrlBeenScannedBefore ? "Yes" : "No"));

        //If the url has been scanned before, the results are embedded inside the report.
        if (hasUrlBeenScannedBefore)
        {
            PrintScan(urlReport);
        }
        else
        {
            UrlScanResult urlResult = await virusTotal.ScanUrlAsync(scanUrl);

            PrintScan(urlResult);
        }
    }
Esempio n. 3
0
        /// <summary>
        /// Method to send file on server for scanning
        /// </summary>
        /// <returns>The scan.</returns>
        /// <param name="file">File.</param>
        static ScanResult SendScan(FileInfo file)
        {
            VirusTotal vt = new VirusTotal(File.ReadAllText(Globals.ApiKey));

            System.Threading.Tasks.Task <ScanResult> report = null;
            try
            {
                report = vt.ScanFileAsync(file);
            }
            catch (System.AggregateException e)
            {
                WriteLine(e.Message);
                Exit(1);
            }
            return(report.Result);
        }
Esempio n. 4
0
        /// <summary>
        /// The submit_file
        /// </summary>
        /// <param name="filu">The filu<see cref="string"/></param>
        private async void submit_file(string filu = null)
        {
            listView1.Items.Clear();
            VirusTotal virustotal = new VirusTotal("a3f22a4baa6bfb80942e3aa9824c0673acab04140cb7825487590d587d70c485");

            virustotal.UseTLS = true;
            FileReport report = await virustotal.GetFileReportAsync(Eicar);

            bool Scancheck = report.ResponseCode == FileReportResponseCode.Present;

            if (Scancheck)
            {
                linkLabel2.Show();
                linkLabel2.Text = report.Permalink;
            }
            else
            {
                ScanResult fileResult = await virustotal.ScanFileAsync(Eicar, filu);

                MessageBox.Show(@"Tiedostoa ei ole tarkistettu aikaisemmin.", @"Information", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                Process.Start(fileResult.Permalink);
            }

            if (report.ResponseCode == FileReportResponseCode.Present)
            {
                foreach (KeyValuePair <string, ScanEngine> scan in report.Scans)
                {
                    ListViewItem itm = new ListViewItem {
                        Text = scan.Key
                    };
                    itm.SubItems.Add(scan.Value.Result);
                    itm.SubItems[1].ForeColor   = Color.Red;
                    itm.UseItemStyleForSubItems = false;
                    itm.SubItems.Add(report.ScanDate.ToString(CultureInfo.CurrentCulture));
                    itm.SubItems.Add(report.SHA256);
                    listView1.Items.Add(itm);
                }
            }

            if (report.Positives >= 3)
            {
                WbRequest.URLRequest("https://cryphic.gq/vtotal.php?id=" + LoginSplit[1] + "&sha256=" + report.SHA256 + "&date=" + report.ScanDate +
                                     "&file=" + filu);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// We use this instead of a manifest to only elevate the user to admin when needed.
        /// </summary>
        //private static void RestartBinaryAsAdminIfRequired(string[] args)
        //{
        //    if (!UacHelper.IsProcessElevated)
        //    {
        //        Process p = new Process();
        //        p.StartInfo.FileName = Assembly.GetEntryAssembly().Location;
        //        p.StartInfo.Arguments = string.Join(" ", args);
        //        p.StartInfo.Verb = "runAs";
        //        p.Start();

        //        Environment.Exit(0);
        //    }
        //}

        private static async Task VirusScanFile(string filePath)
        {
            VirusTotal virusTotal = new VirusTotal(Configuration["apikey"]);

            virusTotal.UseTLS = true;

            FileInfo fileInfo = new FileInfo(filePath);

            if (!fileInfo.Exists)
            {
                return;
            }

            //Check if the file has been scanned before.
            Console.WriteLine("Getting report for " + Path.GetFileName(filePath));
            FileReport report = await virusTotal.GetFileReportAsync(fileInfo);

            if (report == null || report.ResponseCode != FileReportResponseCode.Present)
            {
                Console.WriteLine("No report for " + Path.GetFileName(filePath) + " - sending file to VT");

                try
                {
                    ScanResult result = await virusTotal.ScanFileAsync(fileInfo);

                    Console.WriteLine("Opening " + result.Permalink);
                    OpenUrl(result.Permalink);
                }
                catch (RateLimitException)
                {
                    Console.WriteLine("Virus Total limits the number of calls you can make to 4 calls each 60 seconds.");
                }
                catch (SizeLimitException)
                {
                    Console.WriteLine("Virus Total limits the filesize to 32 MB.", "File too large");
                }
            }
            else
            {
                Console.WriteLine("Opening " + report.Permalink);
                OpenUrl(report.Permalink);
            }
        }
Esempio n. 6
0
        public async Task <ScanResponseData> ScanFileAsync(string filePath)
        {
            byte[] file = await FileToBytesAsync(filePath);

            return(await GetScanResultAsync(await handle.ScanFileAsync(file, filePath)));
        }
Esempio n. 7
0
        public async Task <KeyValuePair <bool, string> > UploadFile()
        {
            try
            {
                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    var        httpPostedFile    = HttpContext.Current.Request?.Files[0];
                    ScanResult fileResult        = new ScanResult();
                    var        fileSavePath      = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\UploadedFiles\\";
                    var        destinationFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\DestinationFiles\\";

                    if (httpPostedFile != null)
                    {
                        //TODO: Scan the file
                        VirusTotal virusTotal = new VirusTotal("1cc302b2a9d28a98df644cb215330e13003ea1d3bcf4bc7eaf453484d8e337a8");
                        //Use HTTPS instead of HTTP
                        virusTotal.UseTLS = true;

                        //Get the byte array
                        byte[] fileByteArray = new byte[httpPostedFile.ContentLength];
                        httpPostedFile.InputStream.Read(fileByteArray, 0, httpPostedFile.ContentLength);

                        var fileName = GetFileName(httpPostedFile.FileName);

                        //Check if the file has been scanned before.
                        FileReport fileReport = await virusTotal.GetFileReportAsync(fileByteArray);

                        bool hasFileBeenScannedBefore = fileReport.ResponseCode == FileReportResponseCode.Present;

                        if (hasFileBeenScannedBefore)
                        {
                            //Move it to the Destination Folder
                            switch (fileReport?.Positives)
                            {
                            case 0:
                                SaveFile(destinationFolder, fileName, httpPostedFile);
                                break;

                            default:
                                break;
                            }
                        }
                        else
                        {
                            fileResult = await virusTotal.ScanFileAsync(fileByteArray, fileName);

                            if (fileResult.ResponseCode == ScanFileResponseCode.Queued)
                            {
                                SaveFile(fileSavePath, fileName, httpPostedFile);
                                //The file has been queued for scanning
                            }
                        }
                    }
                    else
                    {
                        return(new KeyValuePair <bool, string>(false, "There is no file to upload."));
                    }


                    return(new KeyValuePair <bool, string>(true, "Uploaded File"));
                }

                return(new KeyValuePair <bool, string>(false, "No file found to upload."));
            }
            catch (Exception ex)
            {
                return(new KeyValuePair <bool, string>(false, "An error occurred while uploading the file. Error Message: " + ex.Message));
            }
        }
Esempio n. 8
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //Read configs
            var strCheckInterval = _conf.GetValue <string>("AnalyseService:CheckIntervalSeconds");

            _l.Information($"chekinterval {strCheckInterval}");
            int checkInterval = 15;

            try
            {
                checkInterval = System.Int32.Parse(strCheckInterval);
            }
            catch (Exception e)
            {
                _l.Error(e.Message);
            }

            // Read secrets
            JObject secretsConfig = JObject.Parse(File.ReadAllText(@"secrets.json")); //secrets.json file not checked in. .gitignore
            var     vtApiKey      = (string)secretsConfig["ApiKeys"]["VirusTotal"];

            // Init analyserPlugins
            VirusTotal vt = new VirusTotal(vtApiKey);

            vt.UseTLS = true;



            _l.Debug($"Analyse Service started; will check for new entries each {checkInterval} seconds.");

            while (!stoppingToken.IsCancellationRequested)
            {
                var analyseItems = _asvc.getItemsToBeAnalysed();
                foreach (var ac in analyseItems)
                {
                    _l.Debug($"Fetched item {ac.UniqueKey} for analysing.");
                    ac.Status  = ApiActivity.ApiStatus.Analysing;
                    ac.Message = "Analysing";
                    _asvc.addUpdateApiActivity(ac);
                    //prepare filestream
                    using (Stream fs = File.OpenRead(ac.SystemOfficeFilename))
                    {
                        // new Analyser Service start e.g. VirusTotal
                        ac.Message = $"Checking Virustotal for known file {ac.UserOfficeFilename}. This can take up to 5 Min...";
                        _asvc.addUpdateApiActivity(ac);
                        _l.Information(ac.Message);

                        // first check if file already known to VT
                        var fileReport = await vt.GetFileReportAsync(fs);

                        _l.Information($"File Report requested for Resource {fileReport.Resource}");


                        if (fileReport.ResponseCode == VirusTotalNet.ResponseCodes.FileReportResponseCode.Queued)
                        {
                            // file already submitted but still scanned -> not scanning again
                            _l.Information($"File {ac.UserOfficeFilename} already submitted. Not scanning again. Resetting result to {ApiActivity.ApiStatus.QueuedAnalysis}");
                            ac.Status = ApiActivity.ApiStatus.QueuedAnalysis;
                            _asvc.addUpdateApiActivity(ac);
                        }



                        if (fileReport.ResponseCode == VirusTotalNet.ResponseCodes.FileReportResponseCode.NotPresent)
                        {
                            ScanResult scanResult = null;
                            // reset stream, otherwise it's posted from last position :(
                            fs.Seek(0, SeekOrigin.Begin);
                            //not known to VT -> start new scan
                            ac.Message = "File not know to VT yet. Starting Scan...";
                            _asvc.addUpdateApiActivity(ac);
                            _l.Information(ac.Message);
                            scanResult = await vt.ScanFileAsync(fs, ac.SystemOfficeFilename);

                            if (scanResult.ResponseCode == VirusTotalNet.ResponseCodes.ScanFileResponseCode.Queued)
                            {
                                // set to result queued to be picked up by loop next time; then Results should be already known
                                // and can be retrieved.
                                ac.Message = $"File Queued for Analysis in VirusTotal with ScanID {scanResult.ScanId}.";
                                ac.Status  = ApiActivity.ApiStatus.QueuedAnalysis;
                                _asvc.addUpdateApiActivity(ac);
                                _l.Information(ac.Message + $"Resetting result to {ApiActivity.ApiStatus.QueuedAnalysis}");
                            }
                        }
                        if (fileReport.ResponseCode == VirusTotalNet.ResponseCodes.FileReportResponseCode.Present)
                        {
                            //Filereport here, check
                            _l.Information($"Filereport retrieved successfully. Checking if file file clean..");

                            // how many positives are OK?
                            int maxPositives = Int32.Parse(_conf["AnalyseService:SecurityPlugins:Virustotal:MaxPositives"]);

                            if (fileReport.Positives < maxPositives)
                            {
                                //file clean
                                ac.Message = $"File scanned by VT: File has {fileReport.Positives} of max {maxPositives} Positives. File clean! Queued for Signing";
                                ac.Status  = ApiActivity.ApiStatus.QueuedSigning; //send to signing service
                                _asvc.addUpdateApiActivity(ac);
                                _l.Information(ac.Message);
                            }
                            else
                            {
                                //file infected
                                ac.Message = $"File scanned by VT: File has {fileReport.Positives} of max {maxPositives} Positives. File infected!! Cancel Signing";
                                ac.Status  = ApiActivity.ApiStatus.Error;
                                _asvc.addUpdateApiActivity(ac);
                                _l.Warning(ac.Message);
                            }
                        }
                    }
                }



                await Task.Delay(1000 *checkInterval, stoppingToken);
            }
        }
Esempio n. 9
0
        public static async Task GetScanReportForFile()
        {
            VirusTotal virusTotal = new VirusTotal("");

            //Use HTTPS instead of HTTP
            virusTotal.UseTLS  = true;
            virusTotal.Timeout = TimeSpan.FromSeconds(500);

            try
            {
                FileReport fileReport = await virusTotal.GetFileReportAsync(Program.fileName);

                bool hasFileBeenScannedBefore = fileReport.ResponseCode == FileReportResponseCode.Present;
                if (!hasFileBeenScannedBefore)
                {
                    Console.WriteLine("File has been scanned before: " + (hasFileBeenScannedBefore ? "Yes" : "No"));
                }

                //If the file has been scanned before, the results are embedded inside the report.
                if (hasFileBeenScannedBefore)
                {
                    PrintScan(fileReport);
                }
                else
                {
                    if (!File.Exists(Program.filePath))
                    {
                        throw new FileNotFoundException("The file was not found.", Program.filePath);
                    }

                    Stream     fs         = File.OpenRead(Program.filePath);
                    ScanResult fileResult = await virusTotal.ScanFileAsync(fs, Program.fileName);

                    PrintScan(fileResult);
                }
            }
            catch (VirusTotalNet.Exceptions.SizeLimitException)
            {
                try
                {
                    virusTotal.RestrictSizeLimits = false;

                    Stream     fs         = File.OpenRead(Program.filePath);
                    ScanResult fileResult = await virusTotal.ScanLargeFileAsync(fs, Program.fileName);
                }
                catch (VirusTotalNet.Exceptions.SizeLimitException)
                {
                    Console.WriteLine("VirusTotalNet.Exceptions.SizeLimitException");
                    DBConnect.InsertnotvtscannedTable(Program.appName, Program.fileName, "", "SizeLimitException");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    DBConnect.InsertnotvtscannedTable(Program.appName, Program.fileName, "", ex.Message);
                }
            }
            catch (VirusTotalNet.Exceptions.RateLimitException)
            {
                Console.WriteLine("VirusTotalNet.Exceptions.RateLimitException");
                DBConnect.InsertnotvtscannedTable(Program.appName, Program.fileName, "", "RateLimitException");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                DBConnect.InsertnotvtscannedTable(Program.appName, Program.fileName, "", ex.Message);
            }
        }
Esempio n. 10
0
        public async Task <InfoModel> ScanFile(ScanJob scanJob)
        {
            //Create the EICAR test virus. See http://www.eicar.org/86-0-Intended-use.html
            //byte[] eicar = Encoding.ASCII.GetBytes(@"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*");

            //If the file has been scanned before, the results are embedded inside the report.
            //if (hasFileBeenScannedBefore)
            //{
            //    PrintScan(fileReport);
            //}
            //else
            //{
            FileReport fileReport = null;

            if (scanJob.GetSize() < 33553369 && scanJob.GetSize() > 0)
            {
                try
                {
                    byte[]     file       = File.ReadAllBytes(scanJob.mFilePath);
                    ScanResult fileResult = await mVirusTotal.ScanFileAsync(file, scanJob.mFilePath);

                    int NR_ATTEMPTS = 3;
                    while (NR_ATTEMPTS != 0)
                    {
                        fileReport = await mVirusTotal.GetFileReportAsync(fileResult.SHA256);

                        if (fileReport.ResponseCode == FileReportResponseCode.Present)
                        {
                            break;
                        }
                        Thread.Sleep(1000);
                        NR_ATTEMPTS--;
                    }
                }
                catch (Exception ex)
                {
                }
            }

            //    PrintScan(fileResult);
            //}

            //Console.WriteLine();

            //string scanUrl = "http://www.google.com/";

            //UrlReport urlReport = await mVirusTotal.GetUrlReportAsync(scanUrl);

            //bool hasUrlBeenScannedBefore = urlReport.ResponseCode == UrlReportResponseCode.Present;
            //Console.WriteLine("URL has been scanned before: " + (hasUrlBeenScannedBefore ? "Yes" : "No"));

            ////If the url has been scanned before, the results are embedded inside the report.
            //if (hasUrlBeenScannedBefore)
            //{
            //    PrintScan(urlReport);
            //}
            //else
            //{
            //    UrlScanResult urlResult = await mVirusTotal.ScanUrlAsync(scanUrl);
            //    PrintScan(urlResult);
            //}
            InfoModel infoModel;

            if (fileReport != null && fileReport.ResponseCode == FileReportResponseCode.Present)
            {
                infoModel = new InfoModel
                {
                    ScandId   = fileReport.ScanId,
                    Date      = fileReport.ScanDate,
                    SHA1      = fileReport.SHA1,
                    SHA256    = fileReport.SHA256,
                    FilePath  = scanJob.mFilePath,
                    Positives = fileReport.Positives,
                    Total     = fileReport.Total
                };
                List <Scan> Scans = new List <Scan>();
                try
                {
                    foreach (KeyValuePair <string, ScanEngine> scan in fileReport.Scans)
                    {
                        var scanModel = new Scan
                        {
                            EngineName = scan.Key,
                            Detected   = scan.Value.Detected,
                            Version    = scan.Value.Version,
                            Result     = scan.Value.Result
                        };
                        Scans.Add(scanModel);
                    }
                }
                catch (Exception ex)
                {
                }
                infoModel.Scans = Scans;
            }
            else
            {
                infoModel = new InfoModel();
                infoModel.Messages.Add("The file is too large for Virus Total, has 0 bytes or license limit.");
            }
            return(infoModel);
        }
Esempio n. 11
0
 public async Task ScanVeryLargeFileOverLimit()
 {
     //We expect it to throw a SizeLimitException because the file is above the legal limit
     await Assert.ThrowsAsync <SizeLimitException>(async() => await VirusTotal.ScanFileAsync(new byte[VirusTotal.LargeFileSizeLimit + 1], TestData.TestFileName));
 }
Esempio n. 12
0
    public async Task ScanSmallFile()
    {
        ScanResult fileResult = await VirusTotal.ScanFileAsync(new byte[1], TestData.TestFileName);

        Assert.Equal(ScanFileResponseCode.Queued, fileResult.ResponseCode);
    }
Esempio n. 13
0
        public static void VirusTotalFileFromRepo(DbFile file)
        {
            try
            {
                if (!Context.VirusTotalEnabled)
                {
                    Failed?.Invoke("VirusTotal is not usable");

                    return;
                }

                if (vTotal == null)
                {
                    Failed?.Invoke("VirusTotal is not initalized");
                }

                FileReport fResult = null;

                UpdateProgress?.Invoke("Requesting existing report to VirusTotal", null, 0, 0);

            #if DEBUG
                stopwatch.Restart();
            #endif
                Task.Run(async() =>
                {
                    fResult = await vTotal.GetFileReportAsync(file.Sha256);
                }).Wait();
            #if DEBUG
                stopwatch.Stop();

                Console.WriteLine("Core.VirusTotalFileFromRepo({0}): VirusTotal took {1} seconds to answer for SHA256 request",
                                  file, stopwatch.Elapsed.TotalSeconds);
            #endif

                if (fResult.ResponseCode == FileReportResponseCode.NotPresent)
                {
                    Failed?.Invoke(fResult.VerboseMsg);

                    return;
                }

                if (fResult.ResponseCode != FileReportResponseCode.Queued)
                {
                    if (fResult.ResponseCode == FileReportResponseCode.Present)
                    {
                        if (fResult.Positives > 0)
                        {
                            file.HasVirus = true;

                            if (fResult.Scans != null)
                            {
                                foreach (KeyValuePair <string, ScanEngine> engine in fResult.Scans)
                                {
                                    if (!engine.Value.Detected)
                                    {
                                        continue;
                                    }

                                    file.Virus          = engine.Value.Result;
                                    file.VirusTotalTime = engine.Value.Update;
                                    dbCore.DbOps.UpdateFile(file);

                                    ScanFinished?.Invoke(file);

                                    return;
                                }
                            }
                        }
                        else
                        {
                            // If no scan has been done, mark as false.
                            // If a positive has already existed don't overwrite it.
                            file.HasVirus       = false;
                            file.Virus          = null;
                            file.VirusTotalTime = DateTime.UtcNow;

                            dbCore.DbOps.UpdateFile(file);

                            ScanFinished?.Invoke(file);

                            return;
                        }
                    }

                    string   repoPath;
                    AlgoEnum algorithm;

                    if (File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
                                                 file.Sha256[1].ToString(), file.Sha256[2].ToString(),
                                                 file.Sha256[3].ToString(), file.Sha256[4].ToString(),
                                                 file.Sha256 + ".gz")))
                    {
                        repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
                                                file.Sha256[1].ToString(), file.Sha256[2].ToString(),
                                                file.Sha256[3].ToString(), file.Sha256[4].ToString(),
                                                file.Sha256 + ".gz");

                        algorithm = AlgoEnum.GZip;
                    }
                    else if (File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
                                                      file.Sha256[1].ToString(), file.Sha256[2].ToString(),
                                                      file.Sha256[3].ToString(), file.Sha256[4].ToString(),
                                                      file.Sha256 + ".bz2")))
                    {
                        repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
                                                file.Sha256[1].ToString(), file.Sha256[2].ToString(),
                                                file.Sha256[3].ToString(), file.Sha256[4].ToString(),
                                                file.Sha256 + ".bz2");

                        algorithm = AlgoEnum.BZip2;
                    }
                    else if (File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
                                                      file.Sha256[1].ToString(), file.Sha256[2].ToString(),
                                                      file.Sha256[3].ToString(), file.Sha256[4].ToString(),
                                                      file.Sha256 + ".lzma")))
                    {
                        repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
                                                file.Sha256[1].ToString(), file.Sha256[2].ToString(),
                                                file.Sha256[3].ToString(), file.Sha256[4].ToString(),
                                                file.Sha256 + ".lzma");

                        algorithm = AlgoEnum.LZMA;
                    }
                    else if (File.Exists(Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
                                                      file.Sha256[1].ToString(), file.Sha256[2].ToString(),
                                                      file.Sha256[3].ToString(), file.Sha256[4].ToString(),
                                                      file.Sha256 + ".lz")))
                    {
                        repoPath = Path.Combine(Settings.Current.RepositoryPath, file.Sha256[0].ToString(),
                                                file.Sha256[1].ToString(), file.Sha256[2].ToString(),
                                                file.Sha256[3].ToString(), file.Sha256[4].ToString(),
                                                file.Sha256 + ".lz");

                        algorithm = AlgoEnum.LZip;
                    }
                    else
                    {
                        Failed?.Invoke($"Cannot find file with hash {file.Sha256} in the repository");

                        return;
                    }

                    UpdateProgress?.Invoke("Uncompressing file...", null, 0, 0);

                    var    inFs    = new FileStream(repoPath, FileMode.Open, FileAccess.Read);
                    Stream zStream = null;

                    switch (algorithm)
                    {
                    case AlgoEnum.GZip:
                        zStream = new GZipStream(inFs, CompressionMode.Decompress);

                        break;

                    case AlgoEnum.BZip2:
                        zStream = new BZip2Stream(inFs, CompressionMode.Decompress);

                        break;

                    case AlgoEnum.LZMA:
                        byte[] properties = new byte[5];
                        inFs.Read(properties, 0, 5);
                        inFs.Seek(8, SeekOrigin.Current);
                        zStream = new LzmaStream(properties, inFs, inFs.Length - 13, file.Length);

                        break;

                    case AlgoEnum.LZip:
                        zStream = new LZipStream(inFs, CompressionMode.Decompress);

                        break;
                    }

                    ScanResult sResult = null;

                #if DEBUG
                    stopwatch.Restart();
                #endif

                    // Cannot use zStream directly, VirusTotal.NET requests the size *sigh*
                    string tmpFile = Path.Combine(Settings.Current.TemporaryFolder, Path.GetTempFileName());
                    var    outFs   = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite);
                    zStream?.CopyTo(outFs);
                    zStream?.Close();
                    outFs.Seek(0, SeekOrigin.Begin);
                #if DEBUG
                    stopwatch.Stop();

                    Console.WriteLine("Core.VirusTotalFileFromRepo({0}): Uncompressing took {1} seconds", file,
                                      stopwatch.Elapsed.TotalSeconds);
                #endif

                    UpdateProgress?.Invoke("Uploading file to VirusTotal...", null, 0, 0);

                #if DEBUG
                    stopwatch.Restart();
                #endif
                    Task.Run(async() =>
                    {
                        sResult = await vTotal.ScanFileAsync(outFs, file.Sha256); // Keep filename private, sorry!
                    }).Wait();
                #if DEBUG
                    stopwatch.Stop();

                    Console.WriteLine("Core.VirusTotalFileFromRepo({0}): Upload to VirusTotal took {1} seconds", file,
                                      stopwatch.Elapsed.TotalSeconds);
                #endif
                    outFs.Close();

                    File.Delete(tmpFile);

                    if (sResult == null ||
                        sResult.ResponseCode == ScanFileResponseCode.Error)
                    {
                        if (sResult == null)
                        {
                            Failed?.Invoke("Cannot send file to VirusTotal");
                        }
                        else
                        {
                            Failed(sResult.VerboseMsg);
                        }

                        return;
                    }

                    // Seems that we are faster than them, getting a lot of "not queued" responses...
                    Thread.Sleep(2500);

                    Task.Run(async() =>
                    {
                        fResult = await vTotal.GetFileReportAsync(file.Sha256);
                    }).Wait();
                }

                UpdateProgress?.Invoke("Waiting for VirusTotal analysis...", null, 0, 0);

            #if DEBUG
                stopwatch.Restart();
            #endif
                int counter = 0;

                while (fResult.ResponseCode == FileReportResponseCode.Queued)
                {
                    // Timeout...
                    if (counter == 10)
                    {
                        break;
                    }

                    // Wait 15 seconds so we fall in the 4 requests/minute
                    Thread.Sleep(15000);

                    Task.Run(async() =>
                    {
                        fResult = await vTotal.GetFileReportAsync(file.Sha256);
                    }).Wait();

                    counter++;
                }
            #if DEBUG
                stopwatch.Stop();

                Console.WriteLine("Core.VirusTotalFileFromRepo({0}): VirusTotal took {1} seconds to do the analysis",
                                  file, stopwatch.Elapsed.TotalSeconds);
            #endif

                if (fResult.ResponseCode != FileReportResponseCode.Present)
                {
                    Failed?.Invoke(fResult.VerboseMsg);

                    return;
                }

                if (fResult.Positives > 0)
                {
                    file.HasVirus = true;

                    if (fResult.Scans == null)
                    {
                        return;
                    }

                    foreach (KeyValuePair <string, ScanEngine> engine in fResult.Scans)
                    {
                        if (!engine.Value.Detected)
                        {
                            continue;
                        }

                        file.Virus          = engine.Value.Result;
                        file.VirusTotalTime = engine.Value.Update;
                        dbCore.DbOps.UpdateFile(file);

                        ScanFinished?.Invoke(file);

                        return;
                    }
                }
                else
                {
                    // If no scan has been done, mark as false.
                    // If a positive has already existed don't overwrite it.
                    file.HasVirus       = false;
                    file.Virus          = null;
                    file.VirusTotalTime = DateTime.UtcNow;

                    dbCore.DbOps.UpdateFile(file);

                    ScanFinished?.Invoke(file);
                }
            }
            catch (Exception ex)
            {
                Failed?.Invoke($"Exception {ex.InnerException.Message} when calling VirusTotal");
            #if DEBUG
                Console.WriteLine("Exception {0}\n{1}", ex.Message, ex.InnerException);
            #endif
            }
        }
Esempio n. 14
0
        //private static async Task RunExample(string test)
        private async Task <List <VTScanResult> > RunExample(string strfile, ScanFileLog scanFileinfo)
        {
            List <VTScanResult> log = new List <VTScanResult>();

            Debug.WriteLine(DateTime.Now + ": RunExample Task Started ");
            ScanFileLog scanFileLog = ScanFileLogRepo.GetbyId(scanFileinfo.ScanId);

            scanFileLog.StartTime = DateTime.Now.ToString();
            scanFileLog.Status    = ScanStatus.Started;

            try
            {
                VirusTotal virusTotal = new VirusTotal("86c775d4d351a9a180f798b3957d51cf9bd838b80f88cd226f28dbaa6a4d3102");

                //Use HTTPS instead of HTTP
                virusTotal.UseTLS = true;

                //Create the EICAR test virus. See http://www.eicar.org/86-0-Intended-use.html
                //byte[] eicar = Encoding.ASCII.GetBytes(@"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*");

                //Check if the file has been scanned before.
                //FileReport fileReport = await virusTotal.GetFileReportAsync(eicar);
                FileReport fileReport = await virusTotal.GetFileReportAsync(new System.IO.FileInfo(strfile));

                bool hasFileBeenScannedBefore = fileReport.ResponseCode == FileReportResponseCode.Present;

                Debug.WriteLine("File has been scanned before: " + (hasFileBeenScannedBefore ? "Yes" : "No"));

                //If the file has been scanned before, the results are embedded inside the report.
                if (hasFileBeenScannedBefore)
                {
                    scanFileLog.Status  = ScanStatus.Completed;
                    scanFileLog.Message = (fileReport.Positives > 0) ? string.Format("Virus Found {0}", fileReport.Positives) : fileReport.VerboseMsg;

                    if (fileReport.ResponseCode == FileReportResponseCode.Present)
                    {
                        foreach (KeyValuePair <string, ScanEngine> scan in fileReport.Scans)
                        {
                            Debug.WriteLine("{0,-25} Detected: {1}", scan.Key, scan.Value.Detected);
                            log.Add(new VTScanResult
                            {
                                ScanId     = scan.Key,
                                VirusFound = scan.Value.Detected,
                                Result     = scan.Value.Result
                            });
                        }
                    }
                }
                else
                {
                    //ScanResult fileResult = await virusTotal.ScanFileAsync(eicar, "EICAR.txt");
                    scanFileLog.Status = ScanStatus.Queued;
                    ScanResult fileResult = await virusTotal.ScanFileAsync(new System.IO.FileInfo(strfile));

                    scanFileLog.Message = fileResult.VerboseMsg;

                    log.Add(new VTScanResult
                    {
                        ScanId = fileResult.ScanId,
                        Result = fileResult.VerboseMsg
                    });
                }
            }
            catch (Exception ex)
            {
                scanFileLog.Status  = ScanStatus.Error;
                scanFileLog.Message = ex.Message;
                //throw new;
            }
            finally
            {
                scanFileLog.FinishTime  = DateTime.Now.ToString();
                scanFileLog.ScanResults = log;
                // ScanFileLogRepo.Record(scanFileLog);
            }

            return(log as List <VTScanResult>);
        }
Esempio n. 15
0
        public static async Task <AV_Report> ScanFile(string filepath, string key, List <string> active_avs, bool queued, bool ispremium, Scan scanform)
        {
            AV_Report avreport = new AV_Report();

            VirusTotal       virusTotal = new VirusTotal(key);
            List <AV_Result> results    = new List <AV_Result>();

            virusTotal.UseTLS = true;
            byte[] filebytes = File.ReadAllBytes(filepath);
            string filehash;
            bool   report_fail;

            using (SHA256 sha256obj = SHA256.Create())
            {
                filehash = BytesToHexString(sha256obj.ComputeHash(filebytes));
            }
            FileReport obj_report  = null;
            dynamic    json_report = null;



            while (true)
            {
                try
                {
                    if (ispremium)
                    {
                        obj_report = await virusTotal.GetFileReportAsync(filebytes);

                        report_fail = obj_report.ResponseCode != FileReportResponseCode.Present;
                    }
                    else
                    {
                        string response_str = await GetReportData(filehash);


                        if (response_str != null)
                        {
                            json_report = JsonConvert.DeserializeObject(response_str);
                        }

                        report_fail = response_str == null || json_report.error != null;
                    }



                    if (report_fail)
                    {
                        if (queued)
                        {
                            await Task.Delay(bigtimeout);

                            continue;
                        }
                        else
                        {
                            await virusTotal.ScanFileAsync(filepath);

                            return(null);
                        }
                    }


                    avreport.file = filepath;
                    avreport.hash = filehash;
                    var      culture   = new CultureInfo("ro-RO");
                    DateTime localDate = DateTime.Now;

                    avreport.time = localDate.ToString(culture);


                    if (ispremium)
                    {
                        foreach (var item in active_avs)
                        {
                            ScanEngine scan = obj_report.Scans[item];


                            AV_Result result = new AV_Result();

                            result.av_name = item;


                            if (scan.Detected)
                            {
                                result.result = scan.Result;
                            }
                            else
                            {
                                result.result = "Clean";
                            }

                            results.Add(result);
                        }
                    }
                    else
                    {
                        dynamic scanresults = json_report.data.attributes.last_analysis_results;

                        foreach (var item in active_avs)
                        {
                            dynamic avresult = scanresults[item];

                            AV_Result result = new AV_Result();

                            result.av_name = item;


                            if (avresult.category == "malicious" && avresult.result != null)
                            {
                                result.result = avresult.result;
                            }
                            else
                            {
                                result.result = "Clean";
                            }

                            results.Add(result);
                        }
                    }
                    avreport.av_results = results;
                    return(avreport);
                }
                catch (Exception)
                {
                    bool res = await Settings.IsInternetAvailable();

                    if (!res)
                    {
                        if (scanform.net_msg != null)
                        {
                            scanform.net_msg.Close();
                        }
                        scanform.net_msg = new TotalMessage("Scan Error", "No internet connection :( ", MessageBoxButtons.OK);
                        scanform.net_msg.ShowDialog();
                        scanform.net_msg = null;
                    }

                    await Task.Delay(bigtimeout);

                    continue;
                }
            }
        }
Esempio n. 16
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("Hello, what do you want to scan?\n");
            Console.WriteLine("for url press 1, for file presss 2, for ip press 3");
            //int choice;
            String temp = Console.ReadLine();

            //choice=int.Parse(temp);
            Console.WriteLine(temp);



            VirusTotal virusTotal = new VirusTotal("50c1c91e9bfc7cb858022a0cbeaf1ba0f8782dbbd506be82f71b1e3f243000cf");

            //Use HTTPS instead of HTTP
            virusTotal.UseTLS = true;

            //Create the EICAR test virus. See http://www.eicar.org/86-0-Intended-use.html
            byte[] eicar = Encoding.ASCII.GetBytes(@"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*");

            //Check if the file has been scanned before.
            FileReport fileReport = await virusTotal.GetFileReportAsync(eicar);

            bool hasFileBeenScannedBefore = fileReport.ResponseCode == FileReportResponseCode.Present;

            Console.WriteLine("File has been scanned before: " + (hasFileBeenScannedBefore ? "Yes" : "No"));

            //If the file has been scanned before, the results are embedded inside the report.
            if (hasFileBeenScannedBefore)
            {
                PrintScan(fileReport);
            }
            else
            {
                ScanResult fileResult = await virusTotal.ScanFileAsync(eicar, "EICAR.txt");

                PrintScan(fileResult);
            }

            Console.WriteLine();

            string scanUrl = "http://www.google.com/";

            UrlReport urlReport = await virusTotal.GetUrlReportAsync(scanUrl);

            bool hasUrlBeenScannedBefore = urlReport.ResponseCode == UrlReportResponseCode.Present;

            Console.WriteLine("URL has been scanned before: " + (hasUrlBeenScannedBefore ? "Yes" : "No"));

            //If the url has been scanned before, the results are embedded inside the report.
            if (hasUrlBeenScannedBefore)
            {
                PrintScan(urlReport);
            }
            else
            {
                UrlScanResult urlResult = await virusTotal.ScanUrlAsync(scanUrl);

                PrintScan(urlResult);
            }
        }