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

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