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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. string subDir = upload.FileName[0].ToString();
  197. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  198. // Delete from the DB
  199. _dbContext.Uploads.Remove(upload);
  200. _dbContext.SaveChanges();
  201. // Delete the File
  202. if (System.IO.File.Exists(filePath))
  203. {
  204. System.IO.File.Delete(filePath);
  205. }
  206. return new StatusCodeResult(StatusCodes.Status404NotFound);
  207. }
  208. upload.Downloads += 1;
  209. _dbContext.Entry(upload).State = EntityState.Modified;
  210. _dbContext.SaveChanges();
  211. fileName = upload.FileName;
  212. url = upload.Url;
  213. key = upload.Key;
  214. iv = upload.IV;
  215. contentType = upload.ContentType;
  216. contentLength = upload.ContentLength;
  217. dateUploaded = upload.DateUploaded;
  218. if (User.Identity.IsAuthenticated)
  219. {
  220. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  221. premiumAccount = userInfo.AccountType == AccountType.Premium;
  222. }
  223. if (!premiumAccount && upload.User != null)
  224. {
  225. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, upload.User.Username);
  226. premiumAccount = userInfo.AccountType == AccountType.Premium;
  227. }
  228. }
  229. else
  230. {
  231. return new StatusCodeResult(StatusCodes.Status404NotFound);
  232. }
  233. // We don't have the key, so we need to decrypt it client side
  234. if (string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  235. {
  236. DownloadViewModel model = new DownloadViewModel();
  237. model.CurrentSub = Subdomain;
  238. model.FileName = file;
  239. model.ContentType = contentType;
  240. model.ContentLength = contentLength;
  241. model.IV = iv;
  242. model.Decrypt = true;
  243. return View(model);
  244. }
  245. else if (!premiumAccount && _config.UploadConfig.MaxDownloadSize < contentLength)
  246. {
  247. // We want to force them to the dl page due to them being over the max download size for embedded content
  248. DownloadViewModel model = new DownloadViewModel();
  249. model.CurrentSub = Subdomain;
  250. model.FileName = file;
  251. model.ContentType = contentType;
  252. model.ContentLength = contentLength;
  253. model.Decrypt = false;
  254. return View(model);
  255. }
  256. else // We have the key, so that means server side decryption
  257. {
  258. // Check for the cache
  259. bool isCached = false;
  260. string modifiedSince = Request.Headers["If-Modified-Since"];
  261. if (!string.IsNullOrEmpty(modifiedSince))
  262. {
  263. DateTime modTime = new DateTime();
  264. bool parsed = DateTime.TryParse(modifiedSince, out modTime);
  265. if (parsed)
  266. {
  267. if ((modTime - dateUploaded).TotalSeconds <= 1)
  268. {
  269. isCached = true;
  270. }
  271. }
  272. }
  273. if (isCached)
  274. {
  275. return new StatusCodeResult(StatusCodes.Status304NotModified);
  276. }
  277. else
  278. {
  279. string subDir = fileName[0].ToString();
  280. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, fileName);
  281. long startByte = 0;
  282. long endByte = contentLength - 1;
  283. long length = contentLength;
  284. if (System.IO.File.Exists(filePath))
  285. {
  286. #region Range Calculation
  287. // Are they downloading it by range?
  288. bool byRange = !string.IsNullOrEmpty(Request.Headers["Range"]); // We do not support ranges
  289. // check to see if we need to pass a specified range
  290. if (byRange)
  291. {
  292. long anotherStart = startByte;
  293. long anotherEnd = endByte;
  294. string[] arr_split = Request.Headers["Range"].ToString().Split(new char[] { '=' });
  295. string range = arr_split[1];
  296. // Make sure the client hasn't sent us a multibyte range
  297. if (range.IndexOf(",") > -1)
  298. {
  299. // (?) Shoud this be issued here, or should the first
  300. // range be used? Or should the header be ignored and
  301. // we output the whole content?
  302. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  303. return new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable);
  304. }
  305. // If the range starts with an '-' we start from the beginning
  306. // If not, we forward the file pointer
  307. // And make sure to get the end byte if spesified
  308. if (range.StartsWith("-"))
  309. {
  310. // The n-number of the last bytes is requested
  311. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  312. }
  313. else
  314. {
  315. arr_split = range.Split(new char[] { '-' });
  316. anotherStart = Convert.ToInt64(arr_split[0]);
  317. long temp = 0;
  318. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
  319. }
  320. /* Check the range and make sure it's treated according to the specs.
  321. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  322. */
  323. // End bytes can not be larger than $end.
  324. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  325. // Validate the requested range and return an error if it's not correct.
  326. if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
  327. {
  328. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  329. return new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable);
  330. }
  331. startByte = anotherStart;
  332. endByte = anotherEnd;
  333. length = endByte - startByte + 1; // Calculate new content length
  334. // Ranges are response of 206
  335. Response.StatusCode = 206;
  336. }
  337. #endregion
  338. // Set Last Modified
  339. Response.GetTypedHeaders().LastModified = dateUploaded;
  340. // We accept ranges
  341. Response.Headers.Add("Accept-Ranges", "0-" + contentLength);
  342. // Notify the client the byte range we'll be outputting
  343. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  344. // Notify the client the content length we'll be outputting
  345. Response.Headers.Add("Content-Length", length.ToString());
  346. // Set the content type of this response
  347. Response.Headers.Add("Content-Type", contentType);
  348. // Create content disposition
  349. var cd = new System.Net.Mime.ContentDisposition
  350. {
  351. FileName = url,
  352. Inline = true
  353. };
  354. Response.Headers.Add("Content-Disposition", cd.ToString());
  355. // Read in the file
  356. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  357. // Reset file stream to starting position (or start of range)
  358. fs.Seek(startByte, SeekOrigin.Begin);
  359. try
  360. {
  361. // If the IV is set, and Key is set, then decrypt it while sending
  362. if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  363. {
  364. byte[] keyBytes = Encoding.UTF8.GetBytes(key);
  365. byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
  366. return new BufferedFileStreamResult(contentType, async (response) => await ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)length, _config.UploadConfig.ChunkSize), false);
  367. }
  368. else // Otherwise just send it
  369. {
  370. // Send the file
  371. return new BufferedFileStreamResult(contentType, async (response) => await ResponseHelper.StreamToOutput(response, true, fs, (int)length, _config.UploadConfig.ChunkSize), false);
  372. }
  373. }
  374. catch (Exception ex)
  375. {
  376. _logger.LogWarning(ex, "Error in Download: {url}", new { url });
  377. }
  378. }
  379. }
  380. return new StatusCodeResult(StatusCodes.Status404NotFound);
  381. }
  382. }
  383. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  384. }
  385. [HttpPost]
  386. [AllowAnonymous]
  387. public IActionResult DownloadData(string file, bool decrypt)
  388. {
  389. if (_config.UploadConfig.DownloadEnabled)
  390. {
  391. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  392. if (upload != null)
  393. {
  394. // Check Expiration
  395. if (UploadHelper.CheckExpiration(upload))
  396. {
  397. string delDir = upload.FileName[0].ToString();
  398. string delPath = Path.Combine(_config.UploadConfig.UploadDirectory, delDir, upload.FileName);
  399. // Delete from the DB
  400. _dbContext.Uploads.Remove(upload);
  401. _dbContext.SaveChanges();
  402. // Delete the File
  403. if (System.IO.File.Exists(delPath))
  404. {
  405. System.IO.File.Delete(delPath);
  406. }
  407. return Json(new { error = new { message = "File Does Not Exist" } });
  408. }
  409. string subDir = upload.FileName[0].ToString();
  410. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  411. if (System.IO.File.Exists(filePath))
  412. {
  413. // Notify the client the content length we'll be outputting
  414. Response.Headers.Add("Content-Length", upload.ContentLength.ToString());
  415. // Create content disposition
  416. var cd = new System.Net.Mime.ContentDisposition
  417. {
  418. FileName = upload.Url,
  419. Inline = true
  420. };
  421. // Set the content type of this response
  422. Response.Headers.Add("Content-Type", upload.ContentType);
  423. Response.Headers.Add("Content-Disposition", cd.ToString());
  424. // Read in the file
  425. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  426. // If the IV is set, and Key is set, then decrypt it while sending
  427. if (decrypt && !string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  428. {
  429. byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
  430. byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
  431. return new BufferedFileStreamResult(upload.ContentType, (response) => ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)upload.ContentLength, _config.UploadConfig.ChunkSize), false);
  432. }
  433. else // Otherwise just send it
  434. {
  435. // Send the file
  436. return new BufferedFileStreamResult(upload.ContentType, (response) => ResponseHelper.StreamToOutput(response, true, fs, (int)upload.ContentLength, _config.UploadConfig.ChunkSize), false);
  437. }
  438. }
  439. }
  440. return Json(new { error = new { message = "File Does Not Exist" } });
  441. }
  442. return Json(new { error = new { message = "Downloads are disabled" } });
  443. }
  444. [HttpGet]
  445. [AllowAnonymous]
  446. public IActionResult DeleteByKey(string file, string key)
  447. {
  448. ViewBag.Title = "File Delete | " + file ;
  449. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  450. if (upload != null)
  451. {
  452. DeleteViewModel model = new DeleteViewModel();
  453. model.File = file;
  454. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  455. {
  456. string subDir = upload.FileName[0].ToString();
  457. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  458. // Delete from the DB
  459. _dbContext.Uploads.Remove(upload);
  460. _dbContext.SaveChanges();
  461. // Delete the File
  462. if (System.IO.File.Exists(filePath))
  463. {
  464. System.IO.File.Delete(filePath);
  465. }
  466. model.Deleted = true;
  467. }
  468. else
  469. {
  470. model.Deleted = false;
  471. }
  472. return View(model);
  473. }
  474. return new StatusCodeResult(StatusCodes.Status404NotFound);
  475. }
  476. [HttpPost]
  477. public IActionResult GenerateDeleteKey(string file)
  478. {
  479. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  480. if (upload != null)
  481. {
  482. if (upload.User.Username == User.Identity.Name)
  483. {
  484. string delKey = StringHelper.RandomString(_config.UploadConfig.DeleteKeyLength);
  485. upload.DeleteKey = delKey;
  486. _dbContext.Entry(upload).State = EntityState.Modified;
  487. _dbContext.SaveChanges();
  488. return Json(new { result = new { url = Url.SubRouteUrl("u", "Upload.DeleteByKey", new { file = file, key = delKey }) } });
  489. }
  490. return Json(new { error = new { message = "You do not own this upload" } });
  491. }
  492. return Json(new { error = new { message = "Invalid URL" } });
  493. }
  494. [HttpPost]
  495. [HttpOptions]
  496. public IActionResult Delete(string id)
  497. {
  498. Models.Upload foundUpload = _dbContext.Uploads.Where(u => u.Url == id).FirstOrDefault();
  499. if (foundUpload != null)
  500. {
  501. if (foundUpload.User.Username == User.Identity.Name)
  502. {
  503. string subDir = foundUpload.FileName[0].ToString();
  504. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, foundUpload.FileName);
  505. // Delete from the DB
  506. _dbContext.Uploads.Remove(foundUpload);
  507. _dbContext.SaveChanges();
  508. // Delete the File
  509. if (System.IO.File.Exists(filePath))
  510. {
  511. System.IO.File.Delete(filePath);
  512. }
  513. return Json(new { result = true });
  514. }
  515. return Json(new { error = new { message = "You do not have permission to edit this Paste" } });
  516. }
  517. return Json(new { error = new { message = "This Paste does not exist" } });
  518. }
  519. }
  520. }