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

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