Reputation: 1243
Alright, so I would like to create a thumbnail storage with a couple of png image files in it.
I created a directory on the server side. Now in my controller I would like to process requests for images.
Currently the code of my controller looks like this:
public class ThumbnailController : ApiController
{
[Route("api/v1/thumbnail")]
[HttpGet]
public HttpResponseMessage GetThumbnail(string id)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
string filePath = $@"D:\server_data\Images\Thumbnails\{id}.png";
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid file");
var image = Image.FromFile(filePath);
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
}
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return result;
}
}
Now this one has a security issue: if I call something like http://my.address.com/api/v1/thumbnail?id=../securefile.png
I would essentially get the securefile.png
image file located in the parent directory. Similarly I could download any png image on the hard drive, which is obviously not desired.
For a reason the thumbnails directory must be detached from the server root, so I guess I can not use something like string filePath = HostingEnvironment.MapPath($"~/Images/{id}.png");
To avoid the problem I could trim starting dots or check the incoming id
for special characters, but it does not feel like the right way to fight it. I wonder if better practices exist.
Upvotes: 0
Views: 194
Reputation: 15570
Trimming starting dots is not enough, consider an input similar to foo/bar/../../../outside.png
.
You should validate the id
parameter to only contain say letters, or even better, only numbers. You can achieve complex validation through validation attributes or model validation, both are basically the same. The point is that a user should not be able to enter any special characters, which would effectively mitigate the path injection threat.
Upvotes: 1