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 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. using nClam;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data.Entity;
  5. using System.Drawing;
  6. using System.Drawing.Imaging;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Web;
  10. using System.Web.Mvc;
  11. using Teknik.Areas.Error.ViewModels;
  12. using Teknik.Areas.Upload.Models;
  13. using Teknik.Areas.Upload.ViewModels;
  14. using Teknik.Areas.Users.Utility;
  15. using Teknik.Controllers;
  16. using Teknik.Filters;
  17. using Teknik.Utilities;
  18. using Teknik.Models;
  19. using Teknik.Attributes;
  20. using System.Text;
  21. using Teknik.Utilities.Cryptography;
  22. using System.Web.SessionState;
  23. namespace Teknik.Areas.Upload.Controllers
  24. {
  25. [TeknikAuthorize]
  26. [SessionState(SessionStateBehavior.ReadOnly)]
  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. // Check content type restrictions (Only for encrypting server side
  84. if (encrypt)
  85. {
  86. if (Config.UploadConfig.RestrictedContentTypes.Contains(fileType))
  87. {
  88. return Json(new { error = new { message = "File Type Not Allowed" } });
  89. }
  90. }
  91. using (TeknikEntities db = new TeknikEntities())
  92. {
  93. Models.Upload upload = Uploader.SaveFile(db, Config, data.InputStream, fileType, contentLength, encrypt, fileExt, iv, null, keySize, blockSize);
  94. if (upload != null)
  95. {
  96. if (User.Identity.IsAuthenticated)
  97. {
  98. Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
  99. if (user != null)
  100. {
  101. upload.UserId = user.UserId;
  102. db.Entry(upload).State = EntityState.Modified;
  103. db.SaveChanges();
  104. }
  105. }
  106. 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");
  107. }
  108. return Json(new { error = new { message = "Unable to upload file" } });
  109. }
  110. }
  111. else
  112. {
  113. return Json(new { error = new { message = "File Too Large" } });
  114. }
  115. }
  116. return Json(new { error = new { message = "Uploads are disabled" } });
  117. }
  118. catch (Exception ex)
  119. {
  120. return Json(new { error = new { message = "Exception while uploading file: " + ex.GetFullMessage(true) } });
  121. }
  122. }
  123. // User did not supply key
  124. [HttpGet]
  125. [TrackDownload]
  126. [AllowAnonymous]
  127. public ActionResult Download(string file)
  128. {
  129. if (Config.UploadConfig.DownloadEnabled)
  130. {
  131. ViewBag.Title = "Teknik Download - " + file;
  132. string fileName = string.Empty;
  133. string url = string.Empty;
  134. string key = string.Empty;
  135. string iv = string.Empty;
  136. string contentType = string.Empty;
  137. long contentLength = 0;
  138. bool userUploaded = false;
  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. userUploaded = uploads.User != null;
  156. }
  157. else
  158. {
  159. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  160. }
  161. }
  162. // We don't have the key, so we need to decrypt it client side
  163. if (string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  164. {
  165. DownloadViewModel model = new DownloadViewModel();
  166. model.CurrentSub = Subdomain;
  167. model.FileName = file;
  168. model.ContentType = contentType;
  169. model.ContentLength = contentLength;
  170. model.IV = iv;
  171. model.Decrypt = true;
  172. return View(model);
  173. }
  174. else if (!userUploaded && Config.UploadConfig.MaxDownloadSize < contentLength)
  175. {
  176. // We want to force them to the dl page due to them being over the max download size for embedded content
  177. DownloadViewModel model = new DownloadViewModel();
  178. model.CurrentSub = Subdomain;
  179. model.FileName = file;
  180. model.ContentType = contentType;
  181. model.ContentLength = contentLength;
  182. model.Decrypt = false;
  183. return View(model);
  184. }
  185. else // We have the key, so that means server side decryption
  186. {
  187. // Check for the cache
  188. bool isCached = false;
  189. string modifiedSince = Request.Headers["If-Modified-Since"];
  190. if (!string.IsNullOrEmpty(modifiedSince))
  191. {
  192. DateTime modTime = new DateTime();
  193. bool parsed = DateTime.TryParse(modifiedSince, out modTime);
  194. if (parsed)
  195. {
  196. if ((modTime - dateUploaded).TotalSeconds <= 1)
  197. {
  198. isCached = true;
  199. }
  200. }
  201. }
  202. if (isCached)
  203. {
  204. // The file is cached, let's just 304 this
  205. Response.StatusCode = 304;
  206. Response.StatusDescription = "Not Modified";
  207. return new EmptyResult();
  208. }
  209. else
  210. {
  211. string subDir = fileName[0].ToString();
  212. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, fileName);
  213. long startByte = 0;
  214. long endByte = contentLength - 1;
  215. long length = contentLength;
  216. if (System.IO.File.Exists(filePath))
  217. {
  218. #region Range Calculation
  219. // Are they downloading it by range?
  220. bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]); // We do not support ranges
  221. // check to see if we need to pass a specified range
  222. if (byRange)
  223. {
  224. long anotherStart = startByte;
  225. long anotherEnd = endByte;
  226. string[] arr_split = Request.ServerVariables["HTTP_RANGE"].Split(new char[] { '=' });
  227. string range = arr_split[1];
  228. // Make sure the client hasn't sent us a multibyte range
  229. if (range.IndexOf(",") > -1)
  230. {
  231. // (?) Shoud this be issued here, or should the first
  232. // range be used? Or should the header be ignored and
  233. // we output the whole content?
  234. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  235. throw new HttpException(416, "Requested Range Not Satisfiable");
  236. }
  237. // If the range starts with an '-' we start from the beginning
  238. // If not, we forward the file pointer
  239. // And make sure to get the end byte if spesified
  240. if (range.StartsWith("-"))
  241. {
  242. // The n-number of the last bytes is requested
  243. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  244. }
  245. else
  246. {
  247. arr_split = range.Split(new char[] { '-' });
  248. anotherStart = Convert.ToInt64(arr_split[0]);
  249. long temp = 0;
  250. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
  251. }
  252. /* Check the range and make sure it's treated according to the specs.
  253. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  254. */
  255. // End bytes can not be larger than $end.
  256. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  257. // Validate the requested range and return an error if it's not correct.
  258. if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
  259. {
  260. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  261. throw new HttpException(416, "Requested Range Not Satisfiable");
  262. }
  263. startByte = anotherStart;
  264. endByte = anotherEnd;
  265. length = endByte - startByte + 1; // Calculate new content length
  266. // Ranges are response of 206
  267. Response.StatusCode = 206;
  268. }
  269. #endregion
  270. // Add cache parameters
  271. Response.Cache.SetCacheability(HttpCacheability.Public);
  272. Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
  273. Response.Cache.SetLastModified(dateUploaded);
  274. // We accept ranges
  275. Response.AddHeader("Accept-Ranges", "0-" + contentLength);
  276. // Notify the client the byte range we'll be outputting
  277. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  278. // Notify the client the content length we'll be outputting
  279. Response.AddHeader("Content-Length", length.ToString());
  280. // Create content disposition
  281. var cd = new System.Net.Mime.ContentDisposition
  282. {
  283. FileName = url,
  284. Inline = true
  285. };
  286. Response.AddHeader("Content-Disposition", cd.ToString());
  287. // Read in the file
  288. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  289. // Reset file stream to starting position (or start of range)
  290. fs.Seek(startByte, SeekOrigin.Begin);
  291. try
  292. {
  293. // If the IV is set, and Key is set, then decrypt it while sending
  294. if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  295. {
  296. byte[] keyBytes = Encoding.UTF8.GetBytes(key);
  297. byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
  298. return new FileGenerateResult(url,
  299. contentType,
  300. (response) => ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)length, Config.UploadConfig.ChunkSize),
  301. false);
  302. }
  303. else // Otherwise just send it
  304. {
  305. // Send the file
  306. return new FileGenerateResult(url,
  307. contentType,
  308. (response) => ResponseHelper.StreamToOutput(response, true, fs, (int)length, Config.UploadConfig.ChunkSize),
  309. false);
  310. }
  311. }
  312. catch (Exception ex)
  313. {
  314. Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Download", ex);
  315. }
  316. }
  317. }
  318. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  319. }
  320. }
  321. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  322. }
  323. [HttpPost]
  324. [AllowAnonymous]
  325. public ActionResult DownloadData(string file, bool decrypt)
  326. {
  327. if (Config.UploadConfig.DownloadEnabled)
  328. {
  329. using (TeknikEntities db = new TeknikEntities())
  330. {
  331. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  332. if (upload != null)
  333. {
  334. string subDir = upload.FileName[0].ToString();
  335. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  336. if (System.IO.File.Exists(filePath))
  337. {
  338. // Notify the client the content length we'll be outputting
  339. Response.AddHeader("Content-Length", upload.ContentLength.ToString());
  340. // Create content disposition
  341. var cd = new System.Net.Mime.ContentDisposition
  342. {
  343. FileName = upload.Url,
  344. Inline = true
  345. };
  346. Response.AddHeader("Content-Disposition", cd.ToString());
  347. // Read in the file
  348. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  349. // If the IV is set, and Key is set, then decrypt it while sending
  350. if (decrypt && !string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  351. {
  352. byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
  353. byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
  354. return new FileGenerateResult(upload.Url,
  355. upload.ContentType,
  356. (response) => ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)upload.ContentLength, Config.UploadConfig.ChunkSize),
  357. false);
  358. }
  359. else // Otherwise just send it
  360. {
  361. // Send the file
  362. return new FileGenerateResult(upload.Url,
  363. upload.ContentType,
  364. (response) => ResponseHelper.StreamToOutput(response, true, fs, (int)upload.ContentLength, Config.UploadConfig.ChunkSize),
  365. false);
  366. }
  367. }
  368. }
  369. return Json(new { error = new { message = "File Does Not Exist" } });
  370. }
  371. }
  372. return Json(new { error = new { message = "Downloads are disabled" } });
  373. }
  374. [HttpGet]
  375. [AllowAnonymous]
  376. public ActionResult Delete(string file, string key)
  377. {
  378. using (TeknikEntities db = new TeknikEntities())
  379. {
  380. ViewBag.Title = "File Delete - " + file + " - " + Config.Title;
  381. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  382. if (upload != null)
  383. {
  384. DeleteViewModel model = new DeleteViewModel();
  385. model.File = file;
  386. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  387. {
  388. string filePath = upload.FileName;
  389. // Delete from the DB
  390. db.Uploads.Remove(upload);
  391. db.SaveChanges();
  392. // Delete the File
  393. if (System.IO.File.Exists(filePath))
  394. {
  395. System.IO.File.Delete(filePath);
  396. }
  397. model.Deleted = true;
  398. }
  399. else
  400. {
  401. model.Deleted = false;
  402. }
  403. return View(model);
  404. }
  405. return RedirectToRoute("Error.Http404");
  406. }
  407. }
  408. [HttpPost]
  409. public ActionResult GenerateDeleteKey(string file)
  410. {
  411. using (TeknikEntities db = new TeknikEntities())
  412. {
  413. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  414. if (upload != null)
  415. {
  416. if (upload.User.Username == User.Identity.Name)
  417. {
  418. string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength);
  419. upload.DeleteKey = delKey;
  420. db.Entry(upload).State = EntityState.Modified;
  421. db.SaveChanges();
  422. return Json(new { result = new { url = Url.SubRouteUrl("u", "Upload.Delete", new { file = file, key = delKey }) } });
  423. }
  424. return Json(new { error = new { message = "You do not own this upload" } });
  425. }
  426. return Json(new { error = new { message = "Invalid URL" } });
  427. }
  428. }
  429. }
  430. }