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

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