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

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