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.

PasteController.cs 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Teknik.Areas.Paste.ViewModels;
  6. using Teknik.Areas.Users.Utility;
  7. using Teknik.Controllers;
  8. using Teknik.Filters;
  9. using Teknik.Utilities;
  10. using Teknik.Models;
  11. using Teknik.Attributes;
  12. using Teknik.Utilities.Cryptography;
  13. using Microsoft.Extensions.Logging;
  14. using Teknik.Configuration;
  15. using Teknik.Data;
  16. using Microsoft.AspNetCore.Authorization;
  17. using Microsoft.AspNetCore.Mvc;
  18. using Microsoft.EntityFrameworkCore;
  19. using Microsoft.AspNetCore.Http;
  20. using Teknik.Logging;
  21. using System.IO;
  22. using System.Threading.Tasks;
  23. using Microsoft.AspNetCore.Diagnostics;
  24. namespace Teknik.Areas.Paste.Controllers
  25. {
  26. [Authorize]
  27. [Area("Paste")]
  28. public class PasteController : DefaultController
  29. {
  30. public PasteController(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
  31. [AllowAnonymous]
  32. [TrackPageView]
  33. public IActionResult Index()
  34. {
  35. ViewBag.Title = "Pastebin";
  36. ViewBag.Description = "Paste your code or text easily and securely. Set an expiration, set a password, or leave it open for the world to see.";
  37. PasteCreateViewModel model = new PasteCreateViewModel();
  38. return View(model);
  39. }
  40. [AllowAnonymous]
  41. [TrackPageView]
  42. public async Task<IActionResult> ViewPaste(string type, string url, string password)
  43. {
  44. Models.Paste paste = _dbContext.Pastes.Where(p => p.Url == url).FirstOrDefault();
  45. if (paste != null)
  46. {
  47. ViewBag.Title = (string.IsNullOrEmpty(paste.Title)) ? "Untitled Paste" : paste.Title + " | Pastebin";
  48. ViewBag.Description = "Paste your code or text easily and securely. Set an expiration, set a password, or leave it open for the world to see.";
  49. // Increment Views
  50. paste.Views += 1;
  51. _dbContext.Entry(paste).State = EntityState.Modified;
  52. _dbContext.SaveChanges();
  53. // Check Expiration
  54. if (PasteHelper.CheckExpiration(paste))
  55. {
  56. if (!string.IsNullOrEmpty(paste.FileName))
  57. {
  58. string delSub = paste.FileName[0].ToString();
  59. string delPath = Path.Combine(_config.PasteConfig.PasteDirectory, delSub, paste.FileName);
  60. // Delete the File
  61. if (System.IO.File.Exists(delPath))
  62. {
  63. System.IO.File.Delete(delPath);
  64. }
  65. }
  66. _dbContext.Pastes.Remove(paste);
  67. _dbContext.SaveChanges();
  68. return new StatusCodeResult(StatusCodes.Status404NotFound);
  69. }
  70. PasteViewModel model = new PasteViewModel();
  71. model.Url = url;
  72. model.Title = paste.Title;
  73. model.Syntax = paste.Syntax;
  74. model.DatePosted = paste.DatePosted;
  75. model.Username = paste.User?.Username;
  76. if (User.Identity.IsAuthenticated && type.ToLower() == "full")
  77. {
  78. Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  79. if (user != null)
  80. {
  81. model.Vaults = user.Vaults.ToList();
  82. }
  83. }
  84. byte[] ivBytes = (string.IsNullOrEmpty(paste.IV)) ? new byte[paste.BlockSize] : Encoding.Unicode.GetBytes(paste.IV);
  85. byte[] keyBytes = (string.IsNullOrEmpty(paste.Key)) ? new byte[paste.KeySize] : AesCounterManaged.CreateKey(paste.Key, ivBytes, paste.KeySize);
  86. // The paste has a password set
  87. if (!string.IsNullOrEmpty(paste.HashedPassword))
  88. {
  89. if (string.IsNullOrEmpty(password))
  90. {
  91. // Try to get the password from the session
  92. password = GetCachedPassword(url);
  93. }
  94. string hash = string.Empty;
  95. if (!string.IsNullOrEmpty(password))
  96. {
  97. hash = PasteHelper.HashPassword(paste.Key, password);
  98. keyBytes = AesCounterManaged.CreateKey(password, ivBytes, paste.KeySize);
  99. }
  100. if (string.IsNullOrEmpty(password) || hash != paste.HashedPassword)
  101. {
  102. PasswordViewModel passModel = new PasswordViewModel();
  103. passModel.ActionUrl = Url.SubRouteUrl("p", "Paste.View");
  104. passModel.Url = url;
  105. passModel.Type = type;
  106. if (!string.IsNullOrEmpty(password) && hash != paste.HashedPassword)
  107. {
  108. passModel.Error = true;
  109. passModel.ErrorMessage = "Invalid Password";
  110. }
  111. // Redirect them to the password request page
  112. return View("~/Areas/Paste/Views/Paste/PasswordNeeded.cshtml", passModel);
  113. }
  114. }
  115. // Save the password to the cache
  116. CachePassword(url, password);
  117. // Read in the file
  118. if (string.IsNullOrEmpty(paste.FileName))
  119. return new StatusCodeResult(StatusCodes.Status404NotFound);
  120. string subDir = paste.FileName[0].ToString();
  121. string filePath = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.FileName);
  122. if (!System.IO.File.Exists(filePath))
  123. {
  124. return new StatusCodeResult(StatusCodes.Status404NotFound);
  125. }
  126. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
  127. using (AesCounterStream cs = new AesCounterStream(fs, false, keyBytes, ivBytes))
  128. using (StreamReader sr = new StreamReader(cs, Encoding.Unicode))
  129. {
  130. model.Content = await sr.ReadToEndAsync();
  131. }
  132. switch (type.ToLower())
  133. {
  134. case "full":
  135. return View("~/Areas/Paste/Views/Paste/Full.cshtml", model);
  136. case "simple":
  137. return View("~/Areas/Paste/Views/Paste/Simple.cshtml", model);
  138. case "raw":
  139. return Content(model.Content, "text/plain");
  140. case "download":
  141. //Create File
  142. var cd = new System.Net.Mime.ContentDisposition
  143. {
  144. FileName = url + ".txt",
  145. Inline = true
  146. };
  147. Response.Headers.Add("Content-Disposition", cd.ToString());
  148. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  149. return new BufferedFileStreamResult("application/octet-stream", async (response) => await ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)fs.Length, _config.PasteConfig.ChunkSize), false);
  150. default:
  151. return View("~/Areas/Paste/Views/Paste/Full.cshtml", model);
  152. }
  153. }
  154. return new StatusCodeResult(StatusCodes.Status404NotFound);
  155. }
  156. [HttpPost]
  157. [AllowAnonymous]
  158. [DisableRequestSizeLimit]
  159. public IActionResult Paste([Bind("Content, Title, Syntax, ExpireLength, ExpireUnit, Password")]PasteCreateViewModel model)
  160. {
  161. if (ModelState.IsValid)
  162. {
  163. if (_config.PasteConfig.Enabled)
  164. {
  165. try
  166. {
  167. Models.Paste paste = PasteHelper.CreatePaste(_config, _dbContext, model.Content, model.Title, model.Syntax, model.ExpireUnit, model.ExpireLength ?? 1, model.Password);
  168. if (model.ExpireUnit == ExpirationUnit.Views)
  169. {
  170. paste.Views = -1;
  171. }
  172. if (User.Identity.IsAuthenticated)
  173. {
  174. Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  175. if (user != null)
  176. {
  177. paste.UserId = user.UserId;
  178. }
  179. }
  180. _dbContext.Pastes.Add(paste);
  181. _dbContext.SaveChanges();
  182. // Cache the password
  183. CachePassword(paste.Url, model.Password);
  184. return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
  185. }
  186. catch (Exception ex)
  187. {
  188. return Redirect(Url.SubRouteUrl("error", "Error.500", new { exception = ex }));
  189. }
  190. }
  191. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  192. }
  193. return View("~/Areas/Paste/Views/Paste/Index.cshtml", model);
  194. }
  195. [TrackPageView]
  196. public async Task<IActionResult> Edit(string url, string password)
  197. {
  198. Models.Paste paste = _dbContext.Pastes.Where(p => p.Url == url).FirstOrDefault();
  199. if (paste != null)
  200. {
  201. if (paste.User?.Username != User.Identity.Name)
  202. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  203. ViewBag.Title = "Edit Paste";
  204. ViewBag.Description = "Edit your paste's content.";
  205. // Check Expiration
  206. if (PasteHelper.CheckExpiration(paste))
  207. {
  208. if (!string.IsNullOrEmpty(paste.FileName))
  209. {
  210. string delSub = paste.FileName[0].ToString();
  211. string delPath = Path.Combine(_config.PasteConfig.PasteDirectory, delSub, paste.FileName);
  212. // Delete the File
  213. if (System.IO.File.Exists(delPath))
  214. {
  215. System.IO.File.Delete(delPath);
  216. }
  217. }
  218. // Delete from the DB
  219. _dbContext.Pastes.Remove(paste);
  220. _dbContext.SaveChanges();
  221. return new StatusCodeResult(StatusCodes.Status404NotFound);
  222. }
  223. PasteViewModel model = new PasteViewModel();
  224. model.Url = url;
  225. model.Title = paste.Title;
  226. model.Syntax = paste.Syntax;
  227. model.DatePosted = paste.DatePosted;
  228. model.Username = paste.User?.Username;
  229. byte[] ivBytes = (string.IsNullOrEmpty(paste.IV)) ? new byte[paste.BlockSize] : Encoding.Unicode.GetBytes(paste.IV);
  230. byte[] keyBytes = (string.IsNullOrEmpty(paste.Key)) ? new byte[paste.KeySize] : AesCounterManaged.CreateKey(paste.Key, ivBytes, paste.KeySize);
  231. // The paste has a password set
  232. if (!string.IsNullOrEmpty(paste.HashedPassword))
  233. {
  234. if (string.IsNullOrEmpty(password))
  235. {
  236. // Try to get the password from the session
  237. password = GetCachedPassword(url);
  238. }
  239. string hash = string.Empty;
  240. if (!string.IsNullOrEmpty(password))
  241. {
  242. hash = PasteHelper.HashPassword(paste.Key, password);
  243. keyBytes = AesCounterManaged.CreateKey(password, ivBytes, paste.KeySize);
  244. }
  245. if (string.IsNullOrEmpty(password) || hash != paste.HashedPassword)
  246. {
  247. PasswordViewModel passModel = new PasswordViewModel();
  248. passModel.ActionUrl = Url.SubRouteUrl("p", "Paste.Edit");
  249. passModel.Url = url;
  250. if (!string.IsNullOrEmpty(password) && hash != paste.HashedPassword)
  251. {
  252. passModel.Error = true;
  253. passModel.ErrorMessage = "Invalid Password";
  254. }
  255. // Redirect them to the password request page
  256. return View("~/Areas/Paste/Views/Paste/PasswordNeeded.cshtml", passModel);
  257. }
  258. }
  259. // Cache the password
  260. CachePassword(url, password);
  261. // Read in the file
  262. if (string.IsNullOrEmpty(paste.FileName))
  263. return new StatusCodeResult(StatusCodes.Status404NotFound);
  264. string subDir = paste.FileName[0].ToString();
  265. string filePath = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.FileName);
  266. if (!System.IO.File.Exists(filePath))
  267. {
  268. return new StatusCodeResult(StatusCodes.Status404NotFound);
  269. }
  270. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
  271. using (AesCounterStream cs = new AesCounterStream(fs, false, keyBytes, ivBytes))
  272. using (StreamReader sr = new StreamReader(cs, Encoding.Unicode))
  273. {
  274. model.Content = await sr.ReadToEndAsync();
  275. }
  276. return View("~/Areas/Paste/Views/Paste/Edit.cshtml", model);
  277. }
  278. return new StatusCodeResult(StatusCodes.Status404NotFound);
  279. }
  280. [HttpPost]
  281. [DisableRequestSizeLimit]
  282. public IActionResult EditSubmit([Bind("Content, Title, Syntax, Url")]PasteEditViewModel model)
  283. {
  284. if (_config.PasteConfig.Enabled)
  285. {
  286. try
  287. {
  288. Models.Paste paste = _dbContext.Pastes.Where(p => p.Url == model.Url).FirstOrDefault();
  289. if (paste != null)
  290. {
  291. if (paste.User?.Username != User.Identity.Name)
  292. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  293. string password = null;
  294. // The paste has a password set
  295. if (!string.IsNullOrEmpty(paste.HashedPassword))
  296. {
  297. // Try to get the password from the session
  298. password = GetCachedPassword(model.Url);
  299. string hash = string.Empty;
  300. if (!string.IsNullOrEmpty(password))
  301. {
  302. hash = PasteHelper.HashPassword(paste.Key, password);
  303. }
  304. if (string.IsNullOrEmpty(password) || hash != paste.HashedPassword)
  305. {
  306. PasswordViewModel passModel = new PasswordViewModel();
  307. passModel.ActionUrl = Url.SubRouteUrl("p", "Paste.Edit");
  308. passModel.Url = model.Url;
  309. if (!string.IsNullOrEmpty(password) && hash != paste.HashedPassword)
  310. {
  311. passModel.Error = true;
  312. passModel.ErrorMessage = "Invalid Password";
  313. }
  314. // Redirect them to the password request page
  315. return View("~/Areas/Paste/Views/Paste/PasswordNeeded.cshtml", passModel);
  316. }
  317. }
  318. // get the old file
  319. string subDir = paste.FileName[0].ToString();
  320. string oldFile = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.FileName);
  321. // Generate a unique file name that does not currently exist
  322. string newFilePath = FileHelper.GenerateRandomFileName(_config.PasteConfig.PasteDirectory, _config.PasteConfig.FileExtension, 10);
  323. string fileName = Path.GetFileName(newFilePath);
  324. string key = PasteHelper.GenerateKey(_config.PasteConfig.KeySize);
  325. string iv = PasteHelper.GenerateIV(_config.PasteConfig.BlockSize);
  326. PasteHelper.EncryptContents(model.Content, newFilePath, password, key, iv, _config.PasteConfig.KeySize, _config.PasteConfig.ChunkSize);
  327. paste.Key = key;
  328. paste.KeySize = _config.PasteConfig.KeySize;
  329. paste.IV = iv;
  330. paste.BlockSize = _config.PasteConfig.BlockSize;
  331. if (!string.IsNullOrEmpty(password))
  332. paste.HashedPassword = PasteHelper.HashPassword(paste.Key, password);
  333. paste.FileName = fileName;
  334. paste.Title = model.Title;
  335. paste.Syntax = model.Syntax;
  336. paste.DateEdited = DateTime.Now;
  337. _dbContext.Entry(paste).State = EntityState.Modified;
  338. _dbContext.SaveChanges();
  339. // Delete the old file
  340. if (System.IO.File.Exists(oldFile))
  341. System.IO.File.Delete(oldFile);
  342. return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
  343. }
  344. }
  345. catch (Exception ex)
  346. {
  347. return Redirect(Url.SubRouteUrl("error", "Error.500", new { exception = ex }));
  348. }
  349. }
  350. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  351. }
  352. [HttpPost]
  353. [HttpOptions]
  354. public IActionResult Delete(string id)
  355. {
  356. Models.Paste foundPaste = _dbContext.Pastes.Where(p => p.Url == id).FirstOrDefault();
  357. if (foundPaste != null)
  358. {
  359. if (foundPaste.User.Username == User.Identity.Name)
  360. {
  361. string subDir = foundPaste.FileName[0].ToString();
  362. string filePath = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, foundPaste.FileName);
  363. // Delete from the DB
  364. _dbContext.Pastes.Remove(foundPaste);
  365. _dbContext.SaveChanges();
  366. // Delete the File
  367. if (System.IO.File.Exists(filePath))
  368. {
  369. System.IO.File.Delete(filePath);
  370. }
  371. return Json(new { result = true, redirect = Url.SubRouteUrl("p", "Paste.Index") });
  372. }
  373. return Json(new { error = new { message = "You do not have permission to edit this Paste" } });
  374. }
  375. return Json(new { error = new { message = "This Paste does not exist" } });
  376. }
  377. private void CachePassword(string url, string password)
  378. {
  379. if (HttpContext != null && HttpContext.Session != null)
  380. {
  381. HttpContext.Session?.Set("PastePassword_" + url, password);
  382. }
  383. }
  384. private string GetCachedPassword(string url)
  385. {
  386. if (HttpContext != null && HttpContext.Session != null)
  387. {
  388. return HttpContext.Session.Get<string>("PastePassword_" + url);
  389. }
  390. return null;
  391. }
  392. private void ClearCachedPassword(string url)
  393. {
  394. if (HttpContext != null)
  395. {
  396. HttpContext.Session.Remove("PastePassword_" + url);
  397. }
  398. }
  399. }
  400. }