Created: 29 Jun 2021, last update: 30 Jan 2022
Sitecore Forms virus upload validation
Since Sitecore 9.3 there is Out of the box a File upload Form element. Adding custom validations is possible. However, validating the upload files takes some effort as you have to make sure it is saved properly. See also my previous blog about Sitecore Forms machine learning upload validation.
How to scan the uploaded files for viruses and other malicious and unwanted programs? By doing it in a validation you have the possibility to directly tell the uploader you don’t accept the upload.
First, we need a virus scanner, many antivirus vendors have server-based tools which will allow you to programmatically submit a file to be scanned. Depending on what the upload is, you can, of course, ask yourself whether you entrust these files to an external vendor. I now use Cloudmersive but with some small changes, you can change it to the virus scanner of your choice. And if want running on your own infra.
Beside the paid plans, there is also a Free Tier currently 800 calls/Month Maximum File Size 3.5MB from a data center in North America. There is a also a nugget package to make it easy to use. However, there are Dependencies:
JsonSubTypes (>= 1.2.0)
NewtonSoft.Json (>= 10.0.3)
RestSharp (>= 106.6.10)
These should fit with Sitecore 9.3 and 10+ and if you don’t want to use the NuGet and do it yourself this is how the curl example look:
curl --location --request POST 'https://api.cloudmersive.com/virus/scan/file' --header 'Content-Type: multipart/form-data' --header 'Apikey: YOUR-API-KEY-HERE' --form 'inputFile=@"/path/to/file"'
Steps
- Read the upload from the http request
- Call the virus scanner
- If okay store the file in the Sitecore Forms by using the IFileStorageProvider Note: because the file is already read Sitecore Forms is not able to store it.
- On the save data step, fix the reference to the file so it pinned to the submit.
Code on Github (with reference to Sitecore 10.1 update-1)
https://github.com/jbluemink/Virus-Validation-Sitecore-Forms
To run put your Apikey in VirusValidation.config
Create Sitecore Item “Virus Validator” below /sitecore/system/Settings/Forms/Validations/ with template /sitecore/templates/System/Forms/Validation
Type VirusValidation.VirusValidation, VirusValidation
Message You cannot upload a file that contans a virus.
Goto /sitecore/system/Settings/Forms/Field Types/Basic/File Upload And add “Virus Validator” to Allowed Validations.
Also be aware of the limitations if you are using the free tier, (add also a file size limit validation)