Created
April 2, 2014 10:30
-
-
Save feanz/5553274bd6be081d73e1 to your computer and use it in GitHub Desktop.
MVC Action Filter Allow upload of safe files attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.linq; | |
using System.collections.generic; | |
using System.IO; | |
using System.web.mvc; | |
namespace Securitymodule | |
{ | |
[Attributeusage (Attributetargets.method, Allowmultiple = false )] | |
public sealed class Allowuploadsafefilesattribute: Actionfilterattribute | |
{ | |
static readonly IList < string > Exttofilter = new List < string > { | |
". Aspx" , ". Asax" , ". asp" , ". Ashx" , ". aspx," , ". Axd" , ". master" , ". svc" , ". php" , | |
". Php3" , ". php4" , ". Ph3" , ". Ph4" , ". php4" , ". Ph5" , ". Sphp" , ". cfm" , ". ps" , ". Stm" , | |
". Htaccess" , ". Htpasswd" , ". php5" , ". Phtml" , ". cgi" , ". pl" , ". Plx" , ". py" , ". rb" , ". sh" , ". jsp" , | |
". Cshtml" , ". Vbhtml" , ". swf" , ". Xap" , ". Asptxt" | |
}; | |
static readonly IList < string > Nametofilter = new List < string > { | |
"Web.config" , "htaccess" , "Htpasswd" , "web ~ 1.con" | |
}; | |
static bool Canupload ( string fileName) | |
{ | |
if ( string . Isnullorwhitespace (fileName)) | |
return false ; | |
fileName = fileName.ToLowerInvariant (); | |
var name = Path.GetFileName (fileName); | |
var ext = Path.GetExtension (fileName); | |
if ( string . Isnullorwhitespace (name)) | |
throw new InvalidOperationException ( "Uploaded file should have a name." ); | |
return ! Exttofilter.contains (ext) && | |
! NameToFilter.Contains (name) && | |
! NameToFilter.Contains (ext) && | |
/ / For "file.asp;. Jpg" files | |
ExtToFilter.All (item =>! Name.Contains (item)); | |
} | |
public override void Onactionexecuting (Actionexecutingcontext Filtercontext) | |
{ | |
var files = filterContext.HttpContext.Request.Files; | |
foreach ( string file in files) | |
{ | |
var postedFile = files [file]; | |
if (Postedfile == null | | Postedfile.contentlength == 0) continue ; | |
if (! Canupload (Postedfile.filename)) | |
throw new InvalidOperationException ( string . Format ( "You are not allowed to upload file {0}." , Path.getfilename (Postedfile.filename))); | |
} | |
base . Onactionexecuting (Filtercontext); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment