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

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