This section describes how you can implement File Validation
Sometimes it might be necessary to validate the contents of a file before it gets saved to disk when uploading trough the backoffice.
To help with this, Umbraco supplies a FileStreamSecurityValidator that runs all registered IFileStreamSecurityAnalyzer implementations on the file streams it receives from it's different file upload endpoints. When any of the analyzers deem the file to be unsafe, the endpoint disregards the file and shows a relevant validation message where appropriate. This all happens in memory before the stream is written to a temporary file location.
Implementing a FileStreamSecurityValidator
The IFileStreamSecurityAnalyzer needs a single method to be implemented:
IsConsideredSafe: This method should return false if the analyzer finds a reason not to trust the file
Example FileStreamSecurityAnalyzer
The following class shows how one could potentially guard against Cross-site scripting(XSS) vulnerabilities in an svg file.
publicclassSvgXssSecurityAnalyzer:IFileStreamSecurityAnalyzer {publicboolShouldHandle(Stream fileStream) { // reduce memory footprint by partially reading the filevar startBuffer =newbyte[256];var endBuffer =newbyte[256];fileStream.Read(startBuffer);if (endBuffer.Length>fileStream.Length)fileStream.Seek(0,SeekOrigin.Begin);elsefileStream.Seek(fileStream.Length-endBuffer.Length,SeekOrigin.Begin);fileStream.Read(endBuffer);var startString =System.Text.Encoding.UTF8.GetString(startBuffer);var endString =System.Text.Encoding.UTF8.GetString(endBuffer);returnstartString.Contains("<svg")&&startString.Contains("xmlns=\"http://www.w3.org/2000/svg\"")&&endString.Contains("/svg>"); }publicboolIsConsideredSafe(Stream fileStream) {var streamReader =newStreamReader(fileStream); // do not use a using as this will dispose of the underlying streamvar fileContent =streamReader.ReadToEnd();return!(fileContent.Contains("<script") &&fileContent.Contains("/script>")); } }