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

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