Skip to content

Commit ae39067

Browse files
committed
Sanitizing path input in api requests
1 parent a4e5c3d commit ae39067

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

BlogEngine/BlogEngine.Core/Data/FileManagerRepository.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ public IEnumerable<FileInstance> Find(int take = 10, int skip = 0, string path =
1818
var rwr = Utils.RelativeWebRoot;
1919
var responsePath = "root";
2020

21+
path = path.SanitizePath();
22+
2123
if(string.IsNullOrEmpty(path))
2224
path = Blog.CurrentInstance.StorageLocation + Utils.FilesFolder;
2325

BlogEngine/BlogEngine.Core/Extensions.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,5 +92,27 @@ public static bool TryParse<T>(this string theString, out T output)
9292

9393
return success;
9494
}
95+
96+
/// <summary>
97+
/// Sanitize path by removing invalid characters. Valid path should look similar to "path/to/sub/folder"
98+
/// </summary>
99+
/// <param name="str">String to sanitize</param>
100+
/// <param name="root">Optionally validate datastore root</param>
101+
/// <returns>String out</returns>
102+
public static string SanitizePath(this string str, string root = "")
103+
{
104+
if (str.Contains(".."))
105+
return "";
106+
107+
if (str.StartsWith("~/") && !string.IsNullOrEmpty(root) && !str.StartsWith(root))
108+
return "";
109+
110+
str = str.Replace(".", "").Replace("\\", "").Replace("%2F", "");
111+
112+
if (str.Contains("//"))
113+
return "";
114+
115+
return str;
116+
}
95117
}
96118
}

BlogEngine/BlogEngine.NET/AppCode/Api/UploadController.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ public HttpResponseMessage Post(string action, string dirPath = "")
2929
fileName = fileName.Replace("image.jpg", DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg");
3030
fileName = fileName.Replace("image.png", DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png");
3131

32+
var root = Blog.CurrentInstance.StorageLocation + Utils.FilesFolder;
33+
34+
dirPath = dirPath.SanitizePath(root);
35+
3236
if (!string.IsNullOrEmpty(dirPath))
3337
dirName = dirPath;
3438

0 commit comments

Comments
 (0)