The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

UploadController.cs 23KB

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