Skip to content Skip to sidebar Skip to footer

.net Core Cli to Scan Uploaded Files

This article volition demonstrate virtually the what is the easiest mode to protect our files/documents from viruses before they got uploaded to a storage location. Usually, without performing anti-virus scanning or other content checking against the uploaded file, there might exist a chance that attackers could target other users of the application by uploading malware to the server.

In today's article, we will perform filtering and content checking on whatsoever files which are uploaded to the server. Files should be thoroughly scanned and validated confronting an anti-virus scanner with upwards-to-date virus signatures before existence made available to other users. Any files flagged as malicious should be discarded or deleted immediately.

Prerequisites

I've been using the .Cyberspace 5.0 template to perform this operation and hither I'chiliad sharing the link to install the SDK,

Create a Web API projection with a .Net 5.0 Template.

Step 2

Install the Parcel which will be used for the virus when uploading whatsoever document to the API endpoint.

Scan File(s) For The Virus Before Uploading To Server Using .NET 5.0

For more than details almost nclam & Clam Av, yous can cheque here.

Step iii

There are two possible ways in which we can use this Clam AV Server in our projection,

  1. Running the Clam Av Server under the Docker image
  2. Using their own Clam Av Ip accost to browse our files (If clam server is already installed in our machine)

Running the Mollusk Av Server under the Docker image

Setup the Mollusk server - in local using Docker

  1. Click here to install the docker.
  2. Use the below commands in command prompt to setup the clam Av server locally
    • docker run -d -p 3310:3310 mkodockx/docker-clamav:alpine
    • docker run -d -p 3310:3310 mk0x/docker-clamav
    • docker ps

Scan File(s) For The Virus Before Uploading To Server Using .NET 5.0

Once this setup is washed, let'south create an endpoint and the necessary configuration to scan our files under that mollusk Av server by docker epitome. Add the Mollusk Av port configuration in the appsettings.json file.

appsettings.json

  1. {
  2. "Logging" : {
  3. "LogLevel" : {
  4. "Default" : "Information" ,
  5. "Microsoft" : "Warning" ,
  6. "Microsoft.Hosting.Lifetime" : "Information"
  7.     }
  8.   },
  9. "AllowedHosts" : "*" ,
  10. "ClamAVServer" : {
  11. "URL" : "localhost" ,
  12. "Port" : "3310"
  13.   }
  14. }

Create an endpoint and read the file from the file upload endpoint and convert the file to a byte array. ClamClient scan result returns with ClamScanResult enum values which tells you that your browse was make clean or a virus was detected.

Here is some sample lawmaking,

FileController.cs

  1. using  Microsoft.AspNetCore.Http;
  2. using  Microsoft.AspNetCore.Mvc;
  3. using  Microsoft.Extensions.Configuration;
  4. using  Microsoft.Extensions.Logging;
  5. using  nClam;
  6. using  Organization;
  7. using  Organisation.Collections.Generic;
  8. using  Organization.IO;
  9. using  Organization.Linq;
  10. using  System.Net;
  11. using  Organisation.Threading.Tasks;
  12. namespace  ScanFiles_AntiVirus.Controllers
  13. {
  14.     [Route("api/[controller]" )]
  15.     [ApiController]
  16. public grade  FileUploadController : ControllerBase
  17.     {
  18. private  readonly IConfiguration _configuration;
  19. public  FileUploadController(
  20.             IConfiguration configuration)
  21.         {
  22.             _configuration = configuration;
  23.         }
  24.         [HttpPost]
  25. public  async Task<IActionResult> UploadFile(IFormFile file)
  26.         {
  27. if  (file == nix || file.Length == 0)
  28. return  Content( "file not selected" );
  29.             var ms =new  MemoryStream();
  30.             file.OpenReadStream().CopyTo(ms);
  31.             byte[] fileBytes = ms.ToArray();
  32.             string Result = cord.Empty;
  33. attempt
  34.             {
  35.                 var mollusk =new  ClamClient( this ._configuration[ "ClamAVServer:URL" ],
  36.                 Catechumen.ToInt32(this ._configuration[ "ClamAVServer:Port" ]));
  37.                 var scanResult = await clam.SendAndScanFileAsync(fileBytes);
  38.                 Result =  scanResult.Resultswitch
  39.                 {
  40.                     ClamScanResults.Clean =>"Clean" ,
  41.                     ClamScanResults.VirusDetected =>"Virus Detected" ,
  42.                     ClamScanResults.Mistake =>"Error in File" ,
  43.                     ClamScanResults.Unknown =>"Unknown File" ,
  44.                           _ =>"No instance available"
  45.                 };
  46.             }
  47. catch  (Exception ex)
  48.             {
  49. throw  ex;
  50.             }
  51. render  Ok(Result);
  52.         }
  53.     }
  54. }

Run and Test with Valid File,

Scan File(s) For The Virus Before Uploading To Server Using .NET 5.0

Test with Anti-malware File

As a POC, the EICAR file was uploaded. This is a sample file used to test the response of anti-virus software. You can download a sample file from this Site. You may demand to pause your antivirus protection on your device to perform this activity.

Scan File(s) For The Virus Before Uploading To Server Using .NET 5.0

Using their ain Clam Av Ip address to scan our files

To browse the documents without docker image and if the clam av server is already installed in our machine we need to change a bit of code in the API level instead of going with docker port.

Hither is the following lawmaking,

FileController.cs

  1. using  Microsoft.AspNetCore.Http;
  2. using  Microsoft.AspNetCore.Mvc;
  3. using  Microsoft.Extensions.Configuration;
  4. using  Microsoft.Extensions.Logging;
  5. using  nClam;
  6. using  Organisation;
  7. using  Arrangement.Collections.Generic;
  8. using  Arrangement.IO;
  9. using  System.Linq;
  10. using  System.Net;
  11. using  System.Threading.Tasks;
  12. namespace  ScanFiles_AntiVirus.Controllers
  13. {
  14.     [Route("api/[controller]" )]
  15.     [ApiController]
  16. public class  FileUploadController : ControllerBase
  17.     {
  18. private  readonly IConfiguration _configuration;
  19. public  FileUploadController(
  20.             IConfiguration configuration)
  21.         {
  22.             _configuration = configuration;
  23.         }
  24.         [HttpPost]
  25. public  async Job<IActionResult> UploadFile(IFormFile file)
  26.         {
  27. if  (file == null || file.Length == 0)
  28. return  Content( "file non selected" );
  29.             var ms =new  MemoryStream();
  30.             file.OpenReadStream().CopyTo(ms);
  31.             byte[] fileBytes = ms.ToArray();
  32.             string Effect = string.Empty;
  33. effort
  34.             {
  35. var clam = new  ClamClient(IPAddress.Parse( "127.0.0.ane" ), 3310);
  36.                 var scanResult = await mollusk.SendAndScanFileAsync(fileBytes);
  37.                 Result =  scanResult.Resultswitch
  38.                 {
  39.                     ClamScanResults.Clean =>"Make clean" ,
  40.                     ClamScanResults.VirusDetected =>"Virus Detected" ,
  41.                     ClamScanResults.Error =>"Error in File" ,
  42.                     ClamScanResults.Unknown =>"Unknown File" ,
  43.                           _ =>"No case bachelor"
  44.                 };
  45.             }
  46. take hold of  (Exception ex)
  47.             {
  48. throw  ex;
  49.             }
  50. render  Ok(Result);
  51.         }
  52.     }
  53. }

Conclusion

Thank you for reading, delight let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.

keep learning....!

reyesmamrainy1941.blogspot.com

Source: https://www.c-sharpcorner.com/article/antivirus-protection-scan-on-document-upload-in-net/

Post a Comment for ".net Core Cli to Scan Uploaded Files"