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

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