3 Easy steps to scanning files for viruses in MVC (and for free)

By | September 2

Well it’s been a while since I wrote something here, but now I came across something useful and worth sharing. In a few projects I work on, users upload content to share online. Now while we have virus scanners running, they only scan files saved on disk. I needed to figure out a better way of keeping my system virus free, and not write dangerous files to disk, to check if its dangerous!

After a scan on Google, I really struggled to find a good (complete) example for my needs. So I thought I’d share how I got a solution set up which may be helpful for a few others who are trying to do the same thing.(And also help remind me how I did it in a few months’ time.)

Step 1 Install ClamAv



Firstly, you need to download and install clamAv. You can get a copy from here and follow the step by step instructions below:

  1. Extract or install ClamAV, I have put mine in d:\clamAV
  2. Create a directory “db” for the virus definitions etc.
  3. Start command prompt as administrator and run freshclam, this will start the ClamAV update process
  4. Run clamd –install to set up clamAV as a service.
  5. Start this ClamAV service (called ClamWin Free Antivirus Scanner Service) and also set it up to automatically start when your system starts up

 Step 2 – Create your test cases and classes

I find it a lot easier to start by creating some basic unit tests, and then work on integrating the bits I need to later on. I have included some snippets from my github project here, just to give an overview of the main areas. In our test cases, we will use a VirusScannerFactory to give us an implementation of IScanViruses. I think the most useful objects to scan are memory streams, byte arrays and files. I have created the interface for this below.

  1. /// Interface for us to implement for each Virus scanner
  2. public interface IScanViruses {
  3.  
  4.     /// Scans a file for a virus
  5.     ScanResult ScanFile(string fullPath);
  6.  
  7.     /// Scans some bytes for a virus
  8.     ScanResult ScanBytes(byte[] bytes);
  9.  
  10.     /// Scans a stream for a virus
  11.     ScanResult ScanStream(Stream stream);
  12. }

In MVC the HttpPostedFileBase is used to represent the uploaded file. We will pass the HttpPostedFileBase.InputStream to our IScanViruses.ScanStream Method to make sure the stream is virus free. So in the example test cases, we will pass a clean string and read this into a memory stream. This can then be scanned for viruses. We also use the EICAR test string to make sure our virus scanner implementation works correctly too!

  1. /// Test scanning a memory stream, typically what we get from a MVC http file base
  2. [TestCase("Here is another nice clean string to scan for viruses", true)]
  3. [TestCase(@"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*", false)]
  4. public void Can_scan_memory_stream_for_virus(string stringData, bool expectedToBeVirusFree) {
  5.     var stream = new MemoryStream(Encoding.ASCII.GetBytes(stringData));
  6.     var scanner = VirusScannerFactory.GetVirusScanner();
  7.     var result = scanner.ScanStream(stream);
  8.     Assert.That(result.IsVirusFree, Is.EqualTo(expectedToBeVirusFree), result.Message);
  9. }

We now need to implement the IScanViruses using ClamAV. For this we will use nClam. You can install it from nuget. This little library gives us access to ClamClient which wraps ClamAv functionality in a neat little API. Our ClamAvScanner class can then be used to scan for viruses.

  1. /// Implmemntation of Clam AV to scan viruses
  2. public class ClamAvScanner : IScanViruses {
  3.  
  4.     /// Scans a file for viruses
  5.     public ScanResult ScanFile(string pathToFile) {
  6.         var clam = new ClamClient("localhost", 3310);
  7.         return MapScanResult(clam.ScanFileOnServer(pathToFile));
  8.     }
  9.  
  10.     /// Scans some bytes for virus
  11.     public ScanResult ScanBytes(byte[] data) {
  12.         var clam = new ClamClient("localhost", 3310);
  13.         return MapScanResult(clam.SendAndScanFile(data));
  14.     }
  15.  
  16.     /// Scans your data stream for virus
  17.     public ScanResult ScanStream(Stream stream) {
  18.         var clam = new ClamClient("localhost", 3310);
  19.         return MapScanResult(clam.SendAndScanFile(stream));
  20.     }
  21.  
  22.     /// helper method to map scan result
  23.     private ScanResult MapScanResult(ClamScanResult scanResult) {
  24.         var result = new ScanResult();
  25.         switch (scanResult.Result) {
  26.             case ClamScanResults.Unknown:
  27.                 result.Message = "Could not scan file";
  28.                 result.IsVirusFree = false;
  29.                 break;
  30.            case ClamScanResults.Clean:
  31.                 result.Message = "No Virus found";
  32.                 result.IsVirusFree = true;
  33.                 break;
  34.            case ClamScanResults.VirusDetected:
  35.                 result.Message = "Virus found: " + scanResult.InfectedFiles.First().VirusName;
  36.                 result.IsVirusFree = false;
  37.                 break;
  38.            case ClamScanResults.Error:
  39.                 result.Message = string.Format("VIRUS SCAN ERROR! {0}", scanResult.RawResult);
  40.                 result.IsVirusFree = false;
  41.                 break;
  42.           }
  43.        return result;
  44.     }
  45. }

Step 3 – Integrating it with MVC

Now that we have got some test cases passing, we can look at how we hook this up into our MVC Application. In this example, we have a simple page that allows users to upload a file. In the [HttpPost] Index method, we expect a HttpPostedFileBase parameter which we will pass directly to our Virus scanner. The result of the scan is then stored in temp data, so the user knows if it is virus free.

  1. /// Main controller
  2. public class HomeController : Controller {
  3.  
  4.     /// Get the upload view
  5.     [HttpGet]
  6.     public ActionResult Index() {
  7.         return View();
  8.     }
  9.  
  10.     /// Handle the file upload
  11.     [HttpPost]
  12.     public ActionResult Index(UploadViewModel model, HttpPostedFileBase file) {
  13.         var scanner = VirusScannerFactory.GetVirusScanner();
  14.         var result = scanner.ScanStream(file.InputStream);
  15.         ViewBag.Message = result.Message;
  16.         return View(model);
  17.     }
  18. }

It’s quite tricky to test this on a real virus. I have used the test EICAR virus file, which is probably a safe way to test it out. A more robust solution may be to try it out some real viruses. This is another post on its own!
Here are some tips for a solution like this:

  1. Make sure that you have a scheduled task to keep ClamAV up to date
  2. Just in case, have a second virus scanner, that scans your uploads directory for viruses every now and then
  3.  more tips to come…

A full copy of this project can be found on Github.

A special thanks to:
Ryan Hoffman, with some of this code influenced by his examples
The guys at ClamAV for their great work and keeping the software up to date