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

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