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

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