123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Teknik.Areas.Paste.ViewModels;
- using Teknik.Areas.Users.Utility;
- using Teknik.Controllers;
- using Teknik.Filters;
- using Teknik.Utilities;
- using Teknik.Models;
- using Teknik.Attributes;
- using Teknik.Utilities.Cryptography;
- using Microsoft.Extensions.Logging;
- using Teknik.Configuration;
- using Teknik.Data;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.AspNetCore.Http;
- using Teknik.Logging;
- using System.IO;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Diagnostics;
-
- namespace Teknik.Areas.Paste.Controllers
- {
- [Authorize]
- [Area("Paste")]
- public class PasteController : DefaultController
- {
- public PasteController(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
-
- [AllowAnonymous]
- [TrackPageView]
- public IActionResult Index()
- {
- ViewBag.Title = "Pastebin";
- 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.";
- PasteCreateViewModel model = new PasteCreateViewModel();
- return View(model);
- }
-
- [AllowAnonymous]
- [TrackPageView]
- public async Task<IActionResult> ViewPaste(string type, string url, string password)
- {
- Models.Paste paste = _dbContext.Pastes.Where(p => p.Url == url).FirstOrDefault();
- if (paste != null)
- {
- ViewBag.Title = (string.IsNullOrEmpty(paste.Title)) ? "Untitled Paste" : paste.Title + " | Pastebin";
- 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.";
- // Increment Views
- paste.Views += 1;
- _dbContext.Entry(paste).State = EntityState.Modified;
- _dbContext.SaveChanges();
-
- // Check Expiration
- if (PasteHelper.CheckExpiration(paste))
- {
- _dbContext.Pastes.Remove(paste);
- _dbContext.SaveChanges();
- return new StatusCodeResult(StatusCodes.Status404NotFound);
- }
-
- PasteViewModel model = new PasteViewModel();
- model.Url = url;
- model.Title = paste.Title;
- model.Syntax = paste.Syntax;
- model.DatePosted = paste.DatePosted;
- model.Username = paste.User?.Username;
-
- if (User.Identity.IsAuthenticated && type.ToLower() == "full")
- {
- Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
- if (user != null)
- {
- model.Vaults = user.Vaults.ToList();
- }
- }
-
- byte[] ivBytes = (string.IsNullOrEmpty(paste.IV)) ? new byte[paste.BlockSize] : Encoding.Unicode.GetBytes(paste.IV);
- byte[] keyBytes = (string.IsNullOrEmpty(paste.Key)) ? new byte[paste.KeySize] : AesCounterManaged.CreateKey(paste.Key, ivBytes, paste.KeySize);
-
- // The paste has a password set
- if (!string.IsNullOrEmpty(paste.HashedPassword))
- {
- if (string.IsNullOrEmpty(password))
- {
- // Try to get the password from the session
- password = GetCachedPassword(url);
- }
- string hash = string.Empty;
- if (!string.IsNullOrEmpty(password))
- {
- hash = PasteHelper.HashPassword(paste.Key, password);
- keyBytes = AesCounterManaged.CreateKey(password, ivBytes, paste.KeySize);
- }
- if (string.IsNullOrEmpty(password) || hash != paste.HashedPassword)
- {
- PasswordViewModel passModel = new PasswordViewModel();
- passModel.ActionUrl = Url.SubRouteUrl("p", "Paste.View");
- passModel.Url = url;
- passModel.Type = type;
-
- if (!string.IsNullOrEmpty(password) && hash != paste.HashedPassword)
- {
- passModel.Error = true;
- passModel.ErrorMessage = "Invalid Password";
- }
-
- // Redirect them to the password request page
- return View("~/Areas/Paste/Views/Paste/PasswordNeeded.cshtml", passModel);
- }
- }
-
- // Save the password to the cache
- CachePassword(url, password);
-
- // Read in the file
- if (string.IsNullOrEmpty(paste.FileName))
- return new StatusCodeResult(StatusCodes.Status404NotFound);
- string subDir = paste.FileName[0].ToString();
- string filePath = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.FileName);
- if (!System.IO.File.Exists(filePath))
- {
- return new StatusCodeResult(StatusCodes.Status404NotFound);
- }
-
- using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
- using (AesCounterStream cs = new AesCounterStream(fs, false, keyBytes, ivBytes))
- using (StreamReader sr = new StreamReader(cs, Encoding.Unicode))
- {
- model.Content = await sr.ReadToEndAsync();
- }
-
- switch (type.ToLower())
- {
- case "full":
- return View("~/Areas/Paste/Views/Paste/Full.cshtml", model);
- case "simple":
- return View("~/Areas/Paste/Views/Paste/Simple.cshtml", model);
- case "raw":
- return Content(model.Content, "text/plain");
- case "download":
- //Create File
- var cd = new System.Net.Mime.ContentDisposition
- {
- FileName = url + ".txt",
- Inline = true
- };
-
- Response.Headers.Add("Content-Disposition", cd.ToString());
-
- FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
- 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);
- default:
- return View("~/Areas/Paste/Views/Paste/Full.cshtml", model);
- }
- }
- return new StatusCodeResult(StatusCodes.Status404NotFound);
- }
-
- [HttpPost]
- [AllowAnonymous]
- [DisableRequestSizeLimit]
- public IActionResult Paste([Bind("Content, Title, Syntax, ExpireLength, ExpireUnit, Password")]PasteCreateViewModel model)
- {
- if (ModelState.IsValid)
- {
- if (_config.PasteConfig.Enabled)
- {
- try
- {
- Models.Paste paste = PasteHelper.CreatePaste(_config, _dbContext, model.Content, model.Title, model.Syntax, model.ExpireUnit, model.ExpireLength ?? 1, model.Password);
-
- if (model.ExpireUnit == ExpirationUnit.Views)
- {
- paste.Views = -1;
- }
-
- if (User.Identity.IsAuthenticated)
- {
- Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
- if (user != null)
- {
- paste.UserId = user.UserId;
- }
- }
-
- _dbContext.Pastes.Add(paste);
- _dbContext.SaveChanges();
-
- // Cache the password
- CachePassword(paste.Url, model.Password);
-
- return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
- }
- catch (Exception ex)
- {
- return Redirect(Url.SubRouteUrl("error", "Error.500", new { exception = ex }));
- }
- }
- return new StatusCodeResult(StatusCodes.Status403Forbidden);
- }
- return View("~/Areas/Paste/Views/Paste/Index.cshtml", model);
- }
-
- [TrackPageView]
- public async Task<IActionResult> Edit(string url, string password)
- {
- Models.Paste paste = _dbContext.Pastes.Where(p => p.Url == url).FirstOrDefault();
- if (paste != null)
- {
- if (paste.User?.Username != User.Identity.Name)
- return new StatusCodeResult(StatusCodes.Status403Forbidden);
-
- ViewBag.Title = "Edit Paste";
- ViewBag.Description = "Edit your paste's content.";
-
- // Check Expiration
- if (PasteHelper.CheckExpiration(paste))
- {
- _dbContext.Pastes.Remove(paste);
- _dbContext.SaveChanges();
- return new StatusCodeResult(StatusCodes.Status404NotFound);
- }
-
- PasteViewModel model = new PasteViewModel();
- model.Url = url;
- model.Title = paste.Title;
- model.Syntax = paste.Syntax;
- model.DatePosted = paste.DatePosted;
- model.Username = paste.User?.Username;
-
- byte[] ivBytes = (string.IsNullOrEmpty(paste.IV)) ? new byte[paste.BlockSize] : Encoding.Unicode.GetBytes(paste.IV);
- byte[] keyBytes = (string.IsNullOrEmpty(paste.Key)) ? new byte[paste.KeySize] : AesCounterManaged.CreateKey(paste.Key, ivBytes, paste.KeySize);
-
- // The paste has a password set
- if (!string.IsNullOrEmpty(paste.HashedPassword))
- {
- if (string.IsNullOrEmpty(password))
- {
- // Try to get the password from the session
- password = GetCachedPassword(url);
- }
- string hash = string.Empty;
- if (!string.IsNullOrEmpty(password))
- {
- hash = PasteHelper.HashPassword(paste.Key, password);
- keyBytes = AesCounterManaged.CreateKey(password, ivBytes, paste.KeySize);
- }
- if (string.IsNullOrEmpty(password) || hash != paste.HashedPassword)
- {
- PasswordViewModel passModel = new PasswordViewModel();
- passModel.ActionUrl = Url.SubRouteUrl("p", "Paste.Edit");
- passModel.Url = url;
-
- if (!string.IsNullOrEmpty(password) && hash != paste.HashedPassword)
- {
- passModel.Error = true;
- passModel.ErrorMessage = "Invalid Password";
- }
-
- // Redirect them to the password request page
- return View("~/Areas/Paste/Views/Paste/PasswordNeeded.cshtml", passModel);
- }
- }
-
- // Cache the password
- CachePassword(url, password);
-
- // Read in the file
- if (string.IsNullOrEmpty(paste.FileName))
- return new StatusCodeResult(StatusCodes.Status404NotFound);
- string subDir = paste.FileName[0].ToString();
- string filePath = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.FileName);
- if (!System.IO.File.Exists(filePath))
- {
- return new StatusCodeResult(StatusCodes.Status404NotFound);
- }
-
- using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
- using (AesCounterStream cs = new AesCounterStream(fs, false, keyBytes, ivBytes))
- using (StreamReader sr = new StreamReader(cs, Encoding.Unicode))
- {
- model.Content = await sr.ReadToEndAsync();
- }
-
- return View("~/Areas/Paste/Views/Paste/Edit.cshtml", model);
- }
- return new StatusCodeResult(StatusCodes.Status404NotFound);
- }
-
- [HttpPost]
- [DisableRequestSizeLimit]
- public IActionResult EditSubmit([Bind("Content, Title, Syntax, Url")]PasteEditViewModel model)
- {
- if (_config.PasteConfig.Enabled)
- {
- try
- {
- Models.Paste paste = _dbContext.Pastes.Where(p => p.Url == model.Url).FirstOrDefault();
- if (paste != null)
- {
- if (paste.User?.Username != User.Identity.Name)
- return new StatusCodeResult(StatusCodes.Status403Forbidden);
-
- string password = null;
- // The paste has a password set
- if (!string.IsNullOrEmpty(paste.HashedPassword))
- {
- // Try to get the password from the session
- password = GetCachedPassword(model.Url);
- string hash = string.Empty;
- if (!string.IsNullOrEmpty(password))
- {
- hash = PasteHelper.HashPassword(paste.Key, password);
- }
- if (string.IsNullOrEmpty(password) || hash != paste.HashedPassword)
- {
- PasswordViewModel passModel = new PasswordViewModel();
- passModel.ActionUrl = Url.SubRouteUrl("p", "Paste.Edit");
- passModel.Url = model.Url;
-
- if (!string.IsNullOrEmpty(password) && hash != paste.HashedPassword)
- {
- passModel.Error = true;
- passModel.ErrorMessage = "Invalid Password";
- }
-
- // Redirect them to the password request page
- return View("~/Areas/Paste/Views/Paste/PasswordNeeded.cshtml", passModel);
- }
- }
-
- // Delete the old file
- string subDir = paste.FileName[0].ToString();
- string filePath = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.FileName);
- if (System.IO.File.Exists(filePath))
- System.IO.File.Delete(filePath);
-
- // Generate a unique file name that does not currently exist
- string newFilePath = FileHelper.GenerateRandomFileName(_config.PasteConfig.PasteDirectory, _config.PasteConfig.FileExtension, 10);
- string fileName = Path.GetFileName(newFilePath);
-
- string key = PasteHelper.GenerateKey(_config.PasteConfig.KeySize);
- string iv = PasteHelper.GenerateIV(_config.PasteConfig.BlockSize);
-
- PasteHelper.EncryptContents(model.Content, newFilePath, password, key, iv, _config.PasteConfig.KeySize, _config.PasteConfig.ChunkSize);
-
- paste.Key = key;
- paste.KeySize = _config.PasteConfig.KeySize;
- paste.IV = iv;
- paste.BlockSize = _config.PasteConfig.BlockSize;
-
- if (!string.IsNullOrEmpty(password))
- paste.HashedPassword = PasteHelper.HashPassword(paste.Key, password);
- paste.FileName = fileName;
- paste.Title = model.Title;
- paste.Syntax = model.Syntax;
- paste.DateEdited = DateTime.Now;
-
- _dbContext.Entry(paste).State = EntityState.Modified;
- _dbContext.SaveChanges();
-
- return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
- }
- }
- catch (Exception ex)
- {
- return Redirect(Url.SubRouteUrl("error", "Error.500", new { exception = ex }));
- }
- }
- return new StatusCodeResult(StatusCodes.Status403Forbidden);
- }
-
- [HttpPost]
- public IActionResult Delete(string id)
- {
- Models.Paste foundPaste = _dbContext.Pastes.Where(p => p.Url == id).FirstOrDefault();
- if (foundPaste != null)
- {
- if (foundPaste.User.Username == User.Identity.Name)
- {
- string filePath = foundPaste.FileName;
- // Delete from the DB
- _dbContext.Pastes.Remove(foundPaste);
- _dbContext.SaveChanges();
-
- // Delete the File
- if (System.IO.File.Exists(filePath))
- {
- System.IO.File.Delete(filePath);
- }
-
- return Json(new { result = true, redirect = Url.SubRouteUrl("p", "Paste.Index") });
- }
- return Json(new { error = new { message = "You do not have permission to edit this Paste" } });
- }
- return Json(new { error = new { message = "This Paste does not exist" } });
- }
-
- private void CachePassword(string url, string password)
- {
- if (HttpContext != null && HttpContext.Session != null)
- {
- HttpContext.Session?.Set("PastePassword_" + url, password);
- }
- }
-
- private string GetCachedPassword(string url)
- {
- if (HttpContext != null && HttpContext.Session != null)
- {
- return HttpContext.Session.Get<string>("PastePassword_" + url);
- }
- return null;
- }
-
- private void ClearCachedPassword(string url)
- {
- if (HttpContext != null)
- {
- HttpContext.Session.Remove("PastePassword_" + url);
- }
- }
- }
- }
|