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

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