Author Topic: [C#] VirusTotal Scanner 0.1  (Read 3428 times)

0 Members and 1 Guest are viewing this topic.

Offline Doddy

  • Serf
  • *
  • Posts: 30
  • Cookies: 20
    • View Profile
[C#] VirusTotal Scanner 0.1
« on: June 27, 2014, 03:53:16 pm »
My first program in C# , A simple virustotal scanner.

Sources :

Form1.cs

Code: [Select]
// VirusTotal Scanner 0.1
// (C) Doddy Hackman 2014

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace virustotalscanner
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            if (File.Exists(openFileDialog1.FileName))
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            DH_Tools tools = new DH_Tools();

            if (File.Exists(textBox1.Text))
            {

                string md5 = tools.md5file(textBox1.Text);

                listView1.Items.Clear();
                richTextBox1.Clear();

                string apikey = "07d6f7d301eb1ca58931a396643b91e4c98f830dcaf52aa646f034c876689064"; // API Key
                toolStripStatusLabel1.Text = "[+] Scanning ...";
                this.Refresh();
               
                string code = tools.tomar("http://www.virustotal.com/vtapi/v2/file/report", "resource=" + md5 + "&apikey=" + apikey);
                code = code.Replace("{\"scans\":", "");

                string anti = "";
                string reanti = "";

                Match regex = Regex.Match(code, "\"(.*?)\": {\"detected\": (.*?), \"version\": (.*?), \"result\": (.*?), \"update\": (.*?)}", RegexOptions.IgnoreCase);

                while (regex.Success)
                {
                    anti = regex.Groups[1].Value;
                    reanti = regex.Groups[4].Value;
                    reanti = reanti.Replace("\"", "");

                    ListViewItem item = new ListViewItem();
                    if (reanti == "null")
                    {
                        item.ForeColor = Color.Cyan;
                        reanti = "Clean";
                    }
                    else
                    {
                        item.ForeColor = Color.Red;
                    }

                    item.Text = anti;
                    item.SubItems.Add(reanti);

                    listView1.Items.Add(item);

                    regex = regex.NextMatch();
                }

                regex = Regex.Match(code, "\"scan_id\": \"(.*?)\"", RegexOptions.IgnoreCase);
                if (regex.Success)
                {
                    richTextBox1.AppendText("[+] Scan_ID : " + regex.Groups[1].Value + Environment.NewLine);
                }
                else
                {
                    MessageBox.Show("Not Found");
                }

                regex = Regex.Match(code, "\"scan_date\": \"(.*?)\"", RegexOptions.IgnoreCase);
                if (regex.Success)
                {
                    richTextBox1.AppendText("[+] Scan_Date : " + regex.Groups[1].Value + Environment.NewLine);
                }

                regex = Regex.Match(code, "\"permalink\": \"(.*?)\"", RegexOptions.IgnoreCase);
                if (regex.Success)
                {
                    richTextBox1.AppendText("[+] PermaLink : " + regex.Groups[1].Value + Environment.NewLine);
                }

                regex = Regex.Match(code, "\"verbose_msg\": \"(.*?)\", \"total\": (.*?), \"positives\": (.*?),", RegexOptions.IgnoreCase);
                if (regex.Success)
                {
                    richTextBox1.AppendText("[+] Founds : " + regex.Groups[3].Value + "/" + regex.Groups[2].Value + Environment.NewLine);
                }

                toolStripStatusLabel1.Text = "[+] Finished";
                this.Refresh();


            }
            else
            {
                MessageBox.Show("File not found");
            }
           

        }
    }
}

// The End ?

DH_Tools.cs

Code: [Select]
// Class Name : DH Tools
// Version : Beta
// Author : Doddy Hackman
// (C) Doddy Hackman 2014
//
// Functions :
//
// [+] HTTP Methods GET & POST
// [+] Get HTTP Status code number
// [+] HTTP FingerPrinting
// [+] Read File
// [+] Write File
// [+] GET OS
// [+] Remove duplicates from a List
// [+] Cut urls from a List
// [+] Download
// [+] Upload
// [+] Get Basename from a path
// [+] Execute commands
// [+] URI Split
// [+] MD5 Hash Generator
// [+] Get MD5 of file
// [+] Get IP address from host name
//
// Credits :
//
// Method POST -> https://technet.rapaport.com/Info/Prices/SampleCode/Full_Example.aspx
// Method GET -> http://stackoverflow.com/questions/4510212/how-i-can-get-web-pages-content-and-save-it-into-the-string-variable
// HTTP Headers -> http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers%28v=vs.110%29.aspx
// List Cleaner -> http://forums.asp.net/t/1318899.aspx?Remove+duplicate+items+from+List+String+
// Execute command -> http://www.codeproject.com/Articles/25983/How-to-Execute-a-Command-in-C
// MD5 Hash Generator -> http://www.java2s.com/Code/CSharp/Security/GetandverifyMD5Hash.htm
// Get MD5 of file -> http://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file
//
// Thanks to : $DoC and atheros14 (Forum indetectables)
//

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace virustotalscanner
{
    class DH_Tools
    {
        public string toma(string url)
        {
            string code = "";

            try
            {
                WebClient nave = new WebClient();
                nave.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0";
                code = nave.DownloadString(url);
            }
            catch
            {
                //
            }
            return code;
        }

        public string tomar(string url, string par)
        {

            string code = "";

            try
            {

                HttpWebRequest nave = (HttpWebRequest)
                WebRequest.Create(url);

                nave.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0";
                nave.Method = "POST";
                nave.ContentType = "application/x-www-form-urlencoded";

                Stream anteantecode = nave.GetRequestStream();

                anteantecode.Write(Encoding.ASCII.GetBytes(par), 0, Encoding.ASCII.GetBytes(par).Length);
                anteantecode.Close();

                StreamReader antecode = new StreamReader(nave.GetResponse().GetResponseStream());
                code = antecode.ReadToEnd();

            }
            catch
            {
                //
            }

            return code;

        }

        public string respondecode(string url)
        {
            String code = "";
            try
            {
                HttpWebRequest nave = (HttpWebRequest)WebRequest.Create(url);
                nave.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0";
                HttpWebResponse num = (HttpWebResponse)nave.GetResponse();

                int number = (int)num.StatusCode;
                code = Convert.ToString(number);

            }
            catch
            {

                code = "404";

            }
            return code;
        }

        public string httpfinger(string url)
        {

            String code = "";

            try
            {

                HttpWebRequest nave1 = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse nave2 = (HttpWebResponse)nave1.GetResponse();

                for (int num = 0; num < nave2.Headers.Count; ++num)
                {
                    code = code + "[+] " + nave2.Headers.Keys[num] + ":" + nave2.Headers[num] + Environment.NewLine;
                }

                nave2.Close();
            }
            catch
            {
                //
            }

            return code;

        }

        public string openword(string file)
        {
            String code = "";
            try
            {
                code = System.IO.File.ReadAllText(file);
            }
            catch
            {
                //
            }
            return code;
        }

        public void savefile(string file, string texto)
        {

            try
            {
                System.IO.StreamWriter save = new System.IO.StreamWriter(file, true);
                save.Write(texto);
                save.Close();
            }
            catch
            {
                //
            }
        }

        public string getos()
        {
            string code = "";

            try
            {
                System.OperatingSystem os = System.Environment.OSVersion;
                code = Convert.ToString(os);
            }
            catch
            {
                code = "?";
            }

            return code;
        }

        public List<string> repes(List<string> array)
        {
            List<string> repe = new List<string>();
            foreach (string lin in array)
            {
                if (!repe.Contains(lin))
                {
                    repe.Add(lin);
                }
            }

            return repe;

        }

        public List<string> cortar(List<string> otroarray)
        {
            List<string> cort = new List<string>();

            foreach (string row in otroarray)
            {

                String lineafinal = "";

                Match regex = Regex.Match(row, @"(.*)\?(.*)=(.*)", RegexOptions.IgnoreCase);
                if (regex.Success)
                {
                    lineafinal = regex.Groups[1].Value + "?" + regex.Groups[2].Value + "=";
                    cort.Add(lineafinal);
                }

            }

            return cort;
        }

        public string download(string url, string savename)
        {

            String code = "";

            WebClient nave = new WebClient();
            nave.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0";

            try
            {
                nave.DownloadFile(url, savename);
                code = "OK";
            }
            catch
            {
                code = "Error";
            }

            return code;
        }

        public string upload(string link, string archivo)
        {

            String code = "";

            try
            {

                WebClient nave = new WebClient();
                nave.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0";
                byte[] codedos = nave.UploadFile(link, "POST", archivo);
                code = System.Text.Encoding.UTF8.GetString(codedos, 0, codedos.Length);

            }

            catch
            {
                code = "Error";
            }

            return code;

        }

        public string basename(string file)
        {
            String nombre = "";

            FileInfo basename = new FileInfo(file);
            nombre = basename.Name;

            return nombre;

        }

        public string console(string cmd)
        {

            string code = "";

            try
            {

                System.Diagnostics.ProcessStartInfo loadnow = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd);
                loadnow.RedirectStandardOutput = true;
                loadnow.UseShellExecute = false;
                loadnow.CreateNoWindow = true;
                System.Diagnostics.Process loadnownow = new System.Diagnostics.Process();
                loadnownow.StartInfo = loadnow;
                loadnownow.Start();
                code = loadnownow.StandardOutput.ReadToEnd();

            }

            catch
            {
                code = "Error";
            }

            return code;

        }

        public string urisplit(string url, string opcion)
        {

            string code = "";

            Uri dividir = new Uri(url);

            if (opcion == "host")
            {
                code = dividir.Host;
            }

            if (opcion == "port")
            {
                code = Convert.ToString(dividir.Port);
            }

            if (opcion == "path")
            {
                code = dividir.LocalPath;
            }

            if (opcion == "file")
            {
                code = dividir.AbsolutePath;
                FileInfo basename = new FileInfo(code);
                code = basename.Name;
            }

            if (opcion == "query")
            {
                code = dividir.Query;
            }

            if (opcion == "")
            {
                code = "Error";
            }

            return code;
        }

        public string convertir_md5(string text)
        {
            MD5 convertirmd5 = MD5.Create();
            byte[] infovalor = convertirmd5.ComputeHash(Encoding.Default.GetBytes(text));
            StringBuilder guardar = new StringBuilder();
            for (int numnow = 0; numnow < infovalor.Length; numnow++)
            {
                guardar.Append(infovalor[numnow].ToString("x2"));
            }
            return guardar.ToString();
        }

        public string md5file(string file)
        {

            string code = "";

            try
            {
                var gen = MD5.Create();
                var ar = File.OpenRead(file);
                code = BitConverter.ToString(gen.ComputeHash(ar)).Replace("-", "").ToLower();

            }
            catch
            {
                code = "Error";
            }

            return code;
        }

        public string getip(string host)
        {
            string code = "";
            try
            {
                IPAddress[] find = Dns.GetHostAddresses(host);
                code = find[0].ToString();
            }
            catch
            {
                code = "Error";
            }
            return code;
        }

    }
}

// The End ?

Available for download here
« Last Edit: June 27, 2014, 07:00:14 pm by Doddy »

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: [C#] VirusTotal Scanner 0.1
« Reply #1 on: June 27, 2014, 05:36:30 pm »
You really need to loose the shitty interface design bro, it makes your otherwise good tools look like complete shit.

Offline Doddy

  • Serf
  • *
  • Posts: 30
  • Cookies: 20
    • View Profile
Re: [C#] VirusTotal Scanner 0.1
« Reply #2 on: June 27, 2014, 05:44:25 pm »
ajajaa, I have a strange taste in colors, but like equal.

Offline Fur

  • Knight
  • **
  • Posts: 216
  • Cookies: 34
    • View Profile
Re: [C#] VirusTotal Scanner 0.1
« Reply #3 on: June 27, 2014, 06:32:05 pm »
Okay, let's start off with the UI. First of all, it looks really skiddish and ugly. Personally I'd just use a CLI or maybe a very basic form.

Now that we have that out of the way, let's look at the code.
First of all, your variable names are terrible. Form1? richTextBox1? Come on, give them descriptive names.

Second, separate your core actions from your UI. Instead of having the button2_Click method, have something like VirusTotalScanner.ScanFile(string filepath) which returns a dictionary containing the scanner name and whether it detected the file, then you could just iterate over the results and add them to the listview.

Third, there must be a better way to parse the API result than a regex. I'm sure they use a standard format, so use a parser for it.


I can't even be bothered to review DH_Tools because it looks like just a bunch of barely related functions c/p'd into one big class. I'd instead use a namespace like DH.Tools and group related functions into classes, like reading and writing files into IO. Still, I'd completely scrap the original code because the names make no sense and the actual code is awful. Oh, and your practice of returning "Error" if something fucks up instead of exceptions is generally a bad idea (go Google "why use exceptions" or something).

Get away from malware programming for a bit and go read some books like Clean Code. I think you seriously need to read about the single responsibility principle.
« Last Edit: June 27, 2014, 06:32:46 pm by Fur »

Offline Doddy

  • Serf
  • *
  • Posts: 30
  • Cookies: 20
    • View Profile
Re: [C#] VirusTotal Scanner 0.1
« Reply #4 on: June 27, 2014, 06:59:31 pm »
great, thanks for the suggestions fur.

Offline ansh17

  • NULL
  • Posts: 1
  • Cookies: -3
    • View Profile
Re: [C#] VirusTotal Scanner 0.1
« Reply #5 on: July 03, 2014, 07:14:54 pm »
Sir can you please provide source code for re-scan a file.

The code you provided gets the last scan report only. :(

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: [C#] VirusTotal Scanner 0.1
« Reply #6 on: July 04, 2014, 08:30:58 am »
Sir can you please provide source code for re-scan a file.

The code you provided gets the last scan report only. :(

https://github.com/Genbox/VirusTotal.NET