コード例 #1
0
        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));
        }
コード例 #2
0
        public IActionResult Paste(PasteAPIv1Model model)
        {
            try
            {
                if (model != null && model.code != null)
                {
                    Paste.Models.Paste paste = PasteHelper.CreatePaste(_config, _dbContext, model.code, model.title, model.syntax, model.expireUnit, model.expireLength, model.password);

                    // Associate this with the user if they are logged in
                    if (User.Identity.IsAuthenticated)
                    {
                        User foundUser = UserHelper.GetUser(_dbContext, User.Identity.Name);
                        if (foundUser != null)
                        {
                            paste.UserId = foundUser.UserId;
                        }
                    }

                    _dbContext.Pastes.Add(paste);
                    _dbContext.SaveChanges();

                    return(Json(new
                    {
                        result = new
                        {
                            id = paste.Url,
                            url = Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url, password = model.password }),
                            title = paste.Title,
                            syntax = paste.Syntax,
                            expiration = paste.ExpireDate,
                            password = model.password
                        }
                    }));
                }
                return(Json(new { error = new { message = "Invalid Paste Request" } }));
            }
            catch (Exception ex)
            {
                return(Json(new { error = new { message = "Exception: " + ex.Message } }));
            }
        }
コード例 #3
0
ファイル: TeknikMigration.cs プロジェクト: detmach/Teknik
        public static void MigratePastes(TeknikEntities db, Config config)
        {
            if (!Directory.Exists(config.PasteConfig.PasteDirectory))
            {
                Directory.CreateDirectory(config.PasteConfig.PasteDirectory);
            }

            var pastes = db.Pastes.Select(p => p.PasteId).ToList();

            foreach (var pasteId in pastes)
            {
                var paste = db.Pastes.Where(p => p.PasteId == pasteId).FirstOrDefault();
                if (!string.IsNullOrEmpty(paste.Content) && string.IsNullOrEmpty(paste.FileName) && string.IsNullOrEmpty(paste.HashedPassword))
                {
                    // Generate a unique file name that does not currently exist
                    string filePath = FileHelper.GenerateRandomFileName(config.PasteConfig.PasteDirectory, config.PasteConfig.FileExtension, 10);
                    string fileName = Path.GetFileName(filePath);

                    string key = PasteHelper.GenerateKey(config.PasteConfig.KeySize);
                    string iv  = PasteHelper.GenerateIV(config.PasteConfig.BlockSize);

                    // Encrypt the contents to the file
                    PasteHelper.EncryptContents(paste.Content, filePath, null, key, iv, config.PasteConfig.KeySize, config.PasteConfig.ChunkSize);

                    // Generate a deletion key
                    paste.DeleteKey = StringHelper.RandomString(config.PasteConfig.DeleteKeyLength);

                    paste.Key       = key;
                    paste.KeySize   = config.PasteConfig.KeySize;
                    paste.IV        = iv;
                    paste.BlockSize = config.PasteConfig.BlockSize;

                    paste.FileName = fileName;
                    paste.Content  = string.Empty;

                    db.Entry(paste).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
        }
コード例 #4
0
        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))
                {
                    DeleteFile(paste);
                    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));
        }
コード例 #5
0
        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));
                            }
                        }

                        // get the old file
                        string subDir  = paste.FileName[0].ToString();
                        string oldFile = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.FileName);

                        // 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();

                        // Delete the old file
                        if (System.IO.File.Exists(oldFile))
                        {
                            System.IO.File.Delete(oldFile);
                        }

                        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));
        }
コード例 #6
0
        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))
                {
                    DeleteFile(paste);
                    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));
        }
コード例 #7
0
ファイル: VaultController.cs プロジェクト: detmach/Teknik
        public async Task <IActionResult> ViewVault(string id)
        {
            Models.Vault foundVault = _dbContext.Vaults.Where(v => v.Url == id).FirstOrDefault();
            if (foundVault != null)
            {
                // Update view count
                foundVault.Views += 1;
                _dbContext.Entry(foundVault).State = EntityState.Modified;
                _dbContext.SaveChanges();

                ViewBag.Title = foundVault.Title + " | Vault";

                VaultViewModel model = new VaultViewModel();
                model.CurrentSub = Subdomain;

                model.Url         = foundVault.Url;
                model.UserId      = foundVault.UserId;
                model.User        = foundVault.User;
                model.Title       = foundVault.Title;
                model.Description = foundVault.Description;
                model.DateCreated = foundVault.DateCreated;
                model.DateEdited  = foundVault.DateEdited;

                if (foundVault.VaultItems.Any())
                {
                    foreach (VaultItem item in foundVault.VaultItems.OrderBy(v => v.Index))
                    {
                        if (item.GetType().BaseType == typeof(UploadVaultItem))
                        {
                            UploadVaultItem upload = (UploadVaultItem)item;
                            // Increment Views
                            upload.Upload.Downloads += 1;
                            _dbContext.Entry(upload.Upload).State = EntityState.Modified;
                            _dbContext.SaveChanges();

                            UploadItemViewModel uploadModel = new UploadItemViewModel();
                            uploadModel.VaultItemId = item.VaultItemId;
                            uploadModel.Title       = item.Title;
                            uploadModel.Description = item.Description;
                            uploadModel.DateAdded   = item.DateAdded;
                            uploadModel.Upload      = upload.Upload;
                            model.Items.Add(uploadModel);
                        }
                        else if (item.GetType().BaseType == typeof(PasteVaultItem))
                        {
                            PasteVaultItem paste = (PasteVaultItem)item;
                            // Increment Views
                            paste.Paste.Views += 1;
                            _dbContext.Entry(paste.Paste).State = EntityState.Modified;
                            _dbContext.SaveChanges();

                            // Check Expiration
                            if (PasteHelper.CheckExpiration(paste.Paste))
                            {
                                _dbContext.Pastes.Remove(paste.Paste);
                                _dbContext.SaveChanges();
                                break;
                            }

                            PasteItemViewModel pasteModel = new PasteItemViewModel();
                            pasteModel.VaultItemId = item.VaultItemId;
                            pasteModel.Title       = item.Title;
                            pasteModel.Description = item.Description;
                            pasteModel.DateAdded   = item.DateAdded;

                            pasteModel.PasteId     = paste.Paste.PasteId;
                            pasteModel.Url         = paste.Paste.Url;
                            pasteModel.DatePosted  = paste.Paste.DatePosted;
                            pasteModel.Syntax      = paste.Paste.Syntax;
                            pasteModel.HasPassword = !string.IsNullOrEmpty(paste.Paste.HashedPassword);

                            if (!pasteModel.HasPassword)
                            {
                                // Read in the file
                                string subDir   = paste.Paste.FileName[0].ToString();
                                string filePath = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.Paste.FileName);
                                if (!System.IO.File.Exists(filePath))
                                {
                                    continue;
                                }

                                byte[] ivBytes  = Encoding.Unicode.GetBytes(paste.Paste.IV);
                                byte[] keyBytes = AesCounterManaged.CreateKey(paste.Paste.Key, ivBytes, paste.Paste.KeySize);
                                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))
                                        {
                                            pasteModel.Content = await sr.ReadToEndAsync();
                                        }
                            }

                            model.Items.Add(pasteModel);
                        }
                    }
                }

                return(View(model));
            }
            return(new StatusCodeResult(StatusCodes.Status404NotFound));
        }