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.

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