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

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