11.07.2015 Views

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

206 Part III: Building Secure <strong>Web</strong> <strong>Application</strong>sConfiguring your application for Medium trust is one way to constrain file I/O,although this also constrains your application’s ability to access other resource types.There are two other ways you can restrict your code’s file I/O capabilities:● Using PermitOnly to restrict File I/O● Configuring code access security policy to restrict File I/OUsing PermitOnly to Restrict File I/OYou can use declarative attributes together with <strong>Security</strong>Action.PermitOnly asshown in the following example to constrain file I/O.// Allow the code only to read files from c:\YourAppDir[FileIOPermission(<strong>Security</strong>Action.PermitOnly, Read=@"c:\YourAppDir\")][FileIOPermission(<strong>Security</strong>Action.PermitOnly, PathDiscovery=@"c:\YourAppDir\")]public static string ReadFile(string filename){// Use Path.GetFilePath() to canonicalize the file name// Use FileStream.OpenRead to open the file// Use FileStream.Read to access <strong>and</strong> return the data}Note The second attribute that specifies PathDicovery access is required by the Path.GetFilePathfunction that is used to canonicalize the input file name.To avoid hard coding your application’s directory hierarchy, you can use imperativesecurity syntax, <strong>and</strong> use the HttpContext.Current.Request.MapPath(".") to retrieveyour <strong>Web</strong> application’s directory at runtime. You must reference the System.<strong>Web</strong>assembly <strong>and</strong> add the corresponding using statement as shown in the followingexample.using System.<strong>Web</strong>;public static string ReadFile(string filename){string appDir = HttpContext.Current.Request.MapPath(".");FileIOPermission f = new FileIOPermission(PermissionState.None);f.SetPathList(FileIOPermissionAccess.Read, appDir);f.SetPathList(FileIOPermissionAccess.PathDiscovery, appDir);f.PermitOnly();}// Use Path.GetFilePath() to canonicalize the file name// Use FileStream.OpenRead to open the file// Use FileStream.Read to access <strong>and</strong> return the dataNote For a Windows application you can replace the call to MapPath with a call toDirectory.GetCurrentDirectory to obtain the application’s current directory.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!