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

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