The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UploadController.cs 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. using nClam;
  2. using Piwik.Tracker;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data.Entity;
  6. using System.Drawing;
  7. using System.Drawing.Imaging;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Web;
  11. using System.Web.Mvc;
  12. using Teknik.Areas.Error.ViewModels;
  13. using Teknik.Areas.Upload.Models;
  14. using Teknik.Areas.Upload.ViewModels;
  15. using Teknik.Controllers;
  16. using Teknik.Filters;
  17. using Teknik.Helpers;
  18. using Teknik.Models;
  19. namespace Teknik.Areas.Upload.Controllers
  20. {
  21. public class UploadController : DefaultController
  22. {
  23. private TeknikEntities db = new TeknikEntities();
  24. // GET: Upload/Upload
  25. [HttpGet]
  26. [TrackPageView]
  27. [AllowAnonymous]
  28. public ActionResult Index()
  29. {
  30. ViewBag.Title = "Teknik Upload - End to End Encryption";
  31. UploadViewModel model = new UploadViewModel();
  32. model.CurrentSub = Subdomain;
  33. Users.Models.User user = db.Users.Where(u => u.Username == User.Identity.Name).FirstOrDefault();
  34. if (user != null)
  35. {
  36. model.SaveKey = user.UploadSettings.SaveKey;
  37. model.ServerSideEncrypt = user.UploadSettings.ServerSideEncrypt;
  38. }
  39. else
  40. {
  41. model.SaveKey = true;
  42. model.ServerSideEncrypt = true;
  43. }
  44. return View(model);
  45. }
  46. [HttpPost]
  47. [AllowAnonymous]
  48. public ActionResult Upload(string fileType, string fileExt, string iv, int keySize, int blockSize, bool encrypt, bool saveKey, HttpPostedFileWrapper data, string key = null)
  49. {
  50. try
  51. {
  52. if (Config.UploadConfig.UploadEnabled)
  53. {
  54. if (data.ContentLength <= Config.UploadConfig.MaxUploadSize)
  55. {
  56. // convert file to bytes
  57. byte[] fileData = null;
  58. int contentLength = data.ContentLength;
  59. using (var binaryReader = new BinaryReader(data.InputStream))
  60. {
  61. fileData = binaryReader.ReadBytes(data.ContentLength);
  62. }
  63. // Scan the file to detect a virus
  64. if (Config.UploadConfig.VirusScanEnable)
  65. {
  66. byte[] scanData = fileData;
  67. // If it was encrypted client side, decrypt it
  68. if (!encrypt && key != null)
  69. {
  70. // If the IV is set, and Key is set, then decrypt it
  71. if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  72. {
  73. // Decrypt the data
  74. scanData = AES.Decrypt(scanData, key, iv);
  75. }
  76. }
  77. ClamClient clam = new ClamClient(Config.UploadConfig.ClamServer, Config.UploadConfig.ClamPort);
  78. clam.MaxStreamSize = Config.UploadConfig.MaxUploadSize;
  79. ClamScanResult scanResult = clam.SendAndScanFile(scanData);
  80. switch (scanResult.Result)
  81. {
  82. case ClamScanResults.Clean:
  83. break;
  84. case ClamScanResults.VirusDetected:
  85. return Json(new { error = new { message = string.Format("Virus Detected: {0}. As per our <a href=\"{1}\">Terms of Service</a>, Viruses are not permited.", scanResult.InfectedFiles.First().VirusName, Url.SubRouteUrl("tos", "TOS.Index")) } });
  86. case ClamScanResults.Error:
  87. return Json(new { error = new { message = string.Format("Error scanning the file upload for viruses. {0}", scanResult.RawResult) } });
  88. case ClamScanResults.Unknown:
  89. return Json(new { error = new { message = string.Format("Unknown result while scanning the file upload for viruses. {0}", scanResult.RawResult) } });
  90. }
  91. }
  92. // if they want us to encrypt it, we do so here
  93. if (encrypt)
  94. {
  95. // Generate key and iv if empty
  96. if (string.IsNullOrEmpty(key))
  97. {
  98. key = Utility.RandomString(keySize / 8);
  99. }
  100. fileData = AES.Encrypt(fileData, key, iv);
  101. if (fileData == null || fileData.Length <= 0)
  102. {
  103. return Json(new { error = new { message = "Unable to encrypt file" } });
  104. }
  105. }
  106. Models.Upload upload = Uploader.SaveFile(db, Config, fileData, fileType, contentLength, fileExt, iv, (saveKey) ? key : null, keySize, blockSize);
  107. if (upload != null)
  108. {
  109. if (User.Identity.IsAuthenticated)
  110. {
  111. Users.Models.User user = db.Users.Where(u => u.Username == User.Identity.Name).FirstOrDefault();
  112. if (user != null)
  113. {
  114. upload.UserId = user.UserId;
  115. db.Entry(upload).State = EntityState.Modified;
  116. db.SaveChanges();
  117. }
  118. }
  119. return Json(new { result = new { name = upload.Url, url = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url }), key = key } }, "text/plain");
  120. }
  121. return Json(new { error = new { message = "Unable to upload file" } });
  122. }
  123. else
  124. {
  125. return Json(new { error = new { message = "File Too Large" } });
  126. }
  127. }
  128. return Json(new { error = new { message = "Uploads are disabled" } });
  129. }
  130. catch (Exception ex)
  131. {
  132. return Json(new { error = new { message = "Exception while uploading file: " + ex.GetFullMessage(true) } });
  133. }
  134. }
  135. // User did not supply key
  136. [HttpGet]
  137. [AllowAnonymous]
  138. public ActionResult Download(string file)
  139. {
  140. if (Config.UploadConfig.DownloadEnabled)
  141. {
  142. ViewBag.Title = "Teknik Download - " + file;
  143. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  144. if (upload != null)
  145. {
  146. upload.Downloads += 1;
  147. db.Entry(upload).State = EntityState.Modified;
  148. db.SaveChanges();
  149. // We don't have the key, so we need to decrypt it client side
  150. if (string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  151. {
  152. DownloadViewModel model = new DownloadViewModel();
  153. model.FileName = file;
  154. model.ContentType = upload.ContentType;
  155. model.ContentLength = upload.ContentLength;
  156. model.IV = upload.IV;
  157. return View(model);
  158. }
  159. else // We have the key, so that means server side decryption
  160. {
  161. // Are they downloading it by range?
  162. bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]);
  163. // Check to see if they have a cache
  164. bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]);
  165. if (isCached && !byRange)
  166. {
  167. // The file is cached, let's just 304 this
  168. Response.StatusCode = 304;
  169. Response.StatusDescription = "Not Modified";
  170. Response.AddHeader("Content-Length", "0");
  171. return Content(string.Empty);
  172. }
  173. else
  174. {
  175. string subDir = upload.FileName[0].ToString();
  176. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  177. long startByte = 0;
  178. long endByte = upload.ContentLength - 1;
  179. long length = upload.ContentLength;
  180. if (System.IO.File.Exists(filePath))
  181. {
  182. // Read in the file
  183. byte[] data = System.IO.File.ReadAllBytes(filePath);
  184. // If the IV is set, and Key is set, then decrypt it
  185. if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  186. {
  187. // Decrypt the data
  188. data = AES.Decrypt(data, upload.Key, upload.IV);
  189. }
  190. // We accept ranges
  191. Response.AddHeader("Accept-Ranges", "0-" + upload.ContentLength);
  192. // check to see if we need to pass a specified range
  193. if (byRange)
  194. {
  195. long anotherStart = startByte;
  196. long anotherEnd = endByte;
  197. string[] arr_split = Request.ServerVariables["HTTP_RANGE"].Split(new char[] { '=' });
  198. string range = arr_split[1];
  199. // Make sure the client hasn't sent us a multibyte range
  200. if (range.IndexOf(",") > -1)
  201. {
  202. // (?) Shoud this be issued here, or should the first
  203. // range be used? Or should the header be ignored and
  204. // we output the whole content?
  205. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  206. throw new HttpException(416, "Requested Range Not Satisfiable");
  207. }
  208. // If the range starts with an '-' we start from the beginning
  209. // If not, we forward the file pointer
  210. // And make sure to get the end byte if spesified
  211. if (range.StartsWith("-"))
  212. {
  213. // The n-number of the last bytes is requested
  214. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  215. }
  216. else
  217. {
  218. arr_split = range.Split(new char[] { '-' });
  219. anotherStart = Convert.ToInt64(arr_split[0]);
  220. long temp = 0;
  221. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : upload.ContentLength;
  222. }
  223. /* Check the range and make sure it's treated according to the specs.
  224. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  225. */
  226. // End bytes can not be larger than $end.
  227. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  228. // Validate the requested range and return an error if it's not correct.
  229. if (anotherStart > anotherEnd || anotherStart > upload.ContentLength - 1 || anotherEnd >= upload.ContentLength)
  230. {
  231. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  232. throw new HttpException(416, "Requested Range Not Satisfiable");
  233. }
  234. startByte = anotherStart;
  235. endByte = anotherEnd;
  236. length = endByte - startByte + 1; // Calculate new content length
  237. // grab the portion of the data we want
  238. byte[] dataRange = new byte[length];
  239. Array.Copy(data, startByte, dataRange, 0, length);
  240. data = dataRange;
  241. // Ranges are response of 206
  242. Response.StatusCode = 206;
  243. }
  244. // Add cache parameters
  245. Response.Cache.SetCacheability(HttpCacheability.Public);
  246. Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
  247. Response.Cache.SetLastModified(upload.DateUploaded);
  248. // Notify the client the byte range we'll be outputting
  249. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  250. Response.AddHeader("Content-Length", length.ToString());
  251. // Create content disposition
  252. var cd = new System.Net.Mime.ContentDisposition
  253. {
  254. FileName = upload.Url,
  255. Inline = true
  256. };
  257. Response.AppendHeader("Content-Disposition", cd.ToString());
  258. return File(data, upload.ContentType);
  259. }
  260. }
  261. }
  262. }
  263. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  264. }
  265. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  266. }
  267. [HttpPost]
  268. [AllowAnonymous]
  269. public FileResult DownloadData(string file)
  270. {
  271. if (Config.UploadConfig.DownloadEnabled)
  272. {
  273. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  274. if (upload != null)
  275. {
  276. string subDir = upload.FileName[0].ToString();
  277. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  278. if (System.IO.File.Exists(filePath))
  279. {
  280. byte[] buffer;
  281. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  282. try
  283. {
  284. int length = (int)fileStream.Length; // get file length
  285. buffer = new byte[length]; // create buffer
  286. int count; // actual number of bytes read
  287. int sum = 0; // total number of bytes read
  288. // read until Read method returns 0 (end of the stream has been reached)
  289. while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
  290. sum += count; // sum is a buffer offset for next reading
  291. }
  292. finally
  293. {
  294. fileStream.Close();
  295. }
  296. return File(buffer, System.Net.Mime.MediaTypeNames.Application.Octet, file);
  297. }
  298. }
  299. Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  300. return null;
  301. }
  302. Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  303. return null;
  304. }
  305. [HttpGet]
  306. [AllowAnonymous]
  307. public ActionResult Delete(string file, string key)
  308. {
  309. ViewBag.Title = "File Delete - " + file + " - " + Config.Title;
  310. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  311. if (upload != null)
  312. {
  313. DeleteViewModel model = new DeleteViewModel();
  314. model.File = file;
  315. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  316. {
  317. string filePath = upload.FileName;
  318. // Delete from the DB
  319. db.Uploads.Remove(upload);
  320. db.SaveChanges();
  321. // Delete the File
  322. if (System.IO.File.Exists(filePath))
  323. {
  324. System.IO.File.Delete(filePath);
  325. }
  326. model.Deleted = true;
  327. }
  328. else
  329. {
  330. model.Deleted = false;
  331. }
  332. return View(model);
  333. }
  334. return RedirectToRoute("Error.Http404");
  335. }
  336. [HttpPost]
  337. [AllowAnonymous]
  338. public ActionResult GenerateDeleteKey(string file)
  339. {
  340. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  341. if (upload != null)
  342. {
  343. string delKey = Utility.RandomString(Config.UploadConfig.DeleteKeyLength);
  344. upload.DeleteKey = delKey;
  345. db.Entry(upload).State = EntityState.Modified;
  346. db.SaveChanges();
  347. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Delete", new { file = file, key = delKey }) });
  348. }
  349. return Json(new { error = "Invalid URL" });
  350. }
  351. [HttpPost]
  352. [AllowAnonymous]
  353. public ActionResult SaveFileKey(string file, string key)
  354. {
  355. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  356. if (upload != null)
  357. {
  358. upload.Key = key;
  359. db.Entry(upload).State = EntityState.Modified;
  360. db.SaveChanges();
  361. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Download", new { file = file }) });
  362. }
  363. return Json(new { error = "Invalid URL" });
  364. }
  365. [HttpPost]
  366. [AllowAnonymous]
  367. public ActionResult RemoveFileKey(string file, string key)
  368. {
  369. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  370. if (upload != null)
  371. {
  372. if (upload.Key == key)
  373. {
  374. upload.Key = null;
  375. db.Entry(upload).State = EntityState.Modified;
  376. db.SaveChanges();
  377. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Download", new { file = file }) });
  378. }
  379. return Json(new { error = "Non-Matching Key" });
  380. }
  381. return Json(new { error = "Invalid URL" });
  382. }
  383. }
  384. }