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

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