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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. // Are they downloading it by range?
  165. bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]); // We do not support ranges
  166. bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]); // Check to see if they have a cache
  167. if (isCached)
  168. {
  169. // The file is cached, let's just 304 this
  170. Response.StatusCode = 304;
  171. Response.StatusDescription = "Not Modified";
  172. Response.AddHeader("Content-Length", "0");
  173. return Content(string.Empty);
  174. }
  175. else
  176. {
  177. string subDir = fileName[0].ToString();
  178. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, fileName);
  179. long startByte = 0;
  180. long endByte = contentLength - 1;
  181. long length = contentLength;
  182. if (System.IO.File.Exists(filePath))
  183. {
  184. #region Range Calculation
  185. // check to see if we need to pass a specified range
  186. if (byRange)
  187. {
  188. long anotherStart = startByte;
  189. long anotherEnd = endByte;
  190. string[] arr_split = Request.ServerVariables["HTTP_RANGE"].Split(new char[] { '=' });
  191. string range = arr_split[1];
  192. // Make sure the client hasn't sent us a multibyte range
  193. if (range.IndexOf(",") > -1)
  194. {
  195. // (?) Shoud this be issued here, or should the first
  196. // range be used? Or should the header be ignored and
  197. // we output the whole content?
  198. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  199. throw new HttpException(416, "Requested Range Not Satisfiable");
  200. }
  201. // If the range starts with an '-' we start from the beginning
  202. // If not, we forward the file pointer
  203. // And make sure to get the end byte if spesified
  204. if (range.StartsWith("-"))
  205. {
  206. // The n-number of the last bytes is requested
  207. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  208. }
  209. else
  210. {
  211. arr_split = range.Split(new char[] { '-' });
  212. anotherStart = Convert.ToInt64(arr_split[0]);
  213. long temp = 0;
  214. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
  215. }
  216. /* Check the range and make sure it's treated according to the specs.
  217. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  218. */
  219. // End bytes can not be larger than $end.
  220. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  221. // Validate the requested range and return an error if it's not correct.
  222. if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
  223. {
  224. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  225. throw new HttpException(416, "Requested Range Not Satisfiable");
  226. }
  227. startByte = anotherStart;
  228. endByte = anotherEnd;
  229. length = endByte - startByte + 1; // Calculate new content length
  230. // Ranges are response of 206
  231. Response.StatusCode = 206;
  232. }
  233. #endregion
  234. // Add cache parameters
  235. Response.Cache.SetCacheability(HttpCacheability.Public);
  236. Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
  237. Response.Cache.SetLastModified(dateUploaded);
  238. // We accept ranges
  239. Response.AddHeader("Accept-Ranges", "0-" + contentLength);
  240. // Notify the client the byte range we'll be outputting
  241. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  242. // Notify the client the content length we'll be outputting
  243. Response.AddHeader("Content-Length", length.ToString());
  244. // Create content disposition
  245. var cd = new System.Net.Mime.ContentDisposition
  246. {
  247. FileName = url,
  248. Inline = true
  249. };
  250. Response.AddHeader("Content-Disposition", cd.ToString());
  251. // Apply content security policy for downloads
  252. Response.AddHeader("Content-Security-Policy", "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self'; media-src 'self'; child-src 'self'; form-action 'none';");
  253. // Read in the file
  254. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  255. // Reset file stream to starting position (or start of range)
  256. fs.Seek(startByte, SeekOrigin.Begin);
  257. try
  258. {
  259. // If the IV is set, and Key is set, then decrypt it while sending
  260. if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  261. {
  262. byte[] keyBytes = Encoding.UTF8.GetBytes(key);
  263. byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
  264. return new FileGenerateResult(url,
  265. contentType,
  266. (response) => ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)length, Config.UploadConfig.ChunkSize),
  267. false);
  268. }
  269. else // Otherwise just send it
  270. {
  271. // Send the file
  272. return new FileGenerateResult(url,
  273. contentType,
  274. (response) => ResponseHelper.StreamToOutput(response, true, fs, (int)length, Config.UploadConfig.ChunkSize),
  275. false);
  276. }
  277. }
  278. catch (Exception ex)
  279. {
  280. Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Download", ex);
  281. }
  282. }
  283. }
  284. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  285. }
  286. }
  287. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  288. }
  289. [HttpPost]
  290. [AllowAnonymous]
  291. public FileResult DownloadData(string file)
  292. {
  293. if (Config.UploadConfig.DownloadEnabled)
  294. {
  295. using (TeknikEntities db = new TeknikEntities())
  296. {
  297. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  298. if (upload != null)
  299. {
  300. string subDir = upload.FileName[0].ToString();
  301. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  302. if (System.IO.File.Exists(filePath))
  303. {
  304. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  305. return File(fileStream, System.Net.Mime.MediaTypeNames.Application.Octet, file);
  306. }
  307. }
  308. Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  309. return null;
  310. }
  311. }
  312. Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  313. return null;
  314. }
  315. [HttpGet]
  316. [AllowAnonymous]
  317. public ActionResult Delete(string file, string key)
  318. {
  319. using (TeknikEntities db = new TeknikEntities())
  320. {
  321. ViewBag.Title = "File Delete - " + file + " - " + Config.Title;
  322. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  323. if (upload != null)
  324. {
  325. DeleteViewModel model = new DeleteViewModel();
  326. model.File = file;
  327. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  328. {
  329. string filePath = upload.FileName;
  330. // Delete from the DB
  331. db.Uploads.Remove(upload);
  332. db.SaveChanges();
  333. // Delete the File
  334. if (System.IO.File.Exists(filePath))
  335. {
  336. System.IO.File.Delete(filePath);
  337. }
  338. model.Deleted = true;
  339. }
  340. else
  341. {
  342. model.Deleted = false;
  343. }
  344. return View(model);
  345. }
  346. return RedirectToRoute("Error.Http404");
  347. }
  348. }
  349. [HttpPost]
  350. public ActionResult GenerateDeleteKey(string file)
  351. {
  352. using (TeknikEntities db = new TeknikEntities())
  353. {
  354. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  355. if (upload != null)
  356. {
  357. if (upload.User.Username == User.Identity.Name)
  358. {
  359. string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength);
  360. upload.DeleteKey = delKey;
  361. db.Entry(upload).State = EntityState.Modified;
  362. db.SaveChanges();
  363. return Json(new { result = new { url = Url.SubRouteUrl("u", "Upload.Delete", new { file = file, key = delKey }) } });
  364. }
  365. return Json(new { error = new { message = "You do not own this upload" } });
  366. }
  367. return Json(new { error = new { message = "Invalid URL" } });
  368. }
  369. }
  370. }
  371. }