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

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