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

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