Exemplo n.º 1
0
        public static Models.Upload SaveFile(TeknikEntities db, Config config, byte[] file, string contentType, int contentLength, string defaultExtension, string iv, string key, int keySize, int blockSize)
        {
            if (!Directory.Exists(config.UploadConfig.UploadDirectory))
            {
                Directory.CreateDirectory(config.UploadConfig.UploadDirectory);
            }

            // Generate a unique file name that does not currently exist
            string filePath = Utility.GenerateUniqueFileName(config.UploadConfig.UploadDirectory, config.UploadConfig.FileExtension, 10);
            string fileName = Path.GetFileName(filePath);

            // once we have the filename, lets save the file
            File.WriteAllBytes(filePath, file);

            // Generate a unique url
            string extension = (config.UploadConfig.IncludeExtension) ? Utility.GetDefaultExtension(contentType, defaultExtension) : string.Empty;
            string url = Utility.RandomString(config.UploadConfig.UrlLength) + extension;
            while (db.Uploads.Where(u => u.Url == url).FirstOrDefault() != null)
            {
                url = Utility.RandomString(config.UploadConfig.UrlLength) + extension;
            }

            // Now we need to update the database with the new upload information
            Models.Upload upload = db.Uploads.Create();
            upload.DateUploaded = DateTime.Now;
            upload.Url = url;
            upload.FileName = fileName;
            upload.ContentType = (!string.IsNullOrEmpty(contentType)) ? contentType : "application/octet-stream";
            upload.ContentLength = contentLength;
            upload.Key = key;
            upload.IV = iv;
            upload.KeySize = keySize;
            upload.BlockSize = blockSize;

            db.Uploads.Add(upload);
            db.SaveChanges();

            return upload;
        }
Exemplo n.º 2
0
        public static void CleanGit(Config config, TeknikEntities db)
        {
            Output(string.Format("[{0}] Started Cleaning of Orphaned Git Accounts.", DateTime.Now));
            List<string> gitAccounts = GetOrphanedGit(config, db);
            foreach (string account in gitAccounts)
            {
                // User doesn't exist, and it isn't reserved.  Let's nuke it.
                UserHelper.DeleteUserGit(config, account);
            }

            if (gitAccounts.Count > 0)
            {
                // Add to transparency report if any users were removed
                Takedown report = db.Takedowns.Create();
                report.Requester = TAKEDOWN_REPORTER;
                report.RequesterContact = config.SupportEmail;
                report.DateRequested = DateTime.Now;
                report.Reason = "Orphaned Git Account";
                report.ActionTaken = string.Format("{0} Accounts Removed", gitAccounts.Count);
                report.DateActionTaken = DateTime.Now;
                db.Takedowns.Add(report);
                db.SaveChanges();
            }

            Output(string.Format("[{0}] Finished Cleaning of Orphaned Git Accounts.  {1} Accounts Removed.", DateTime.Now, gitAccounts.Count));
        }
Exemplo n.º 3
0
        public static void CleanAccounts(Config config, TeknikEntities db, int maxDays)
        {
            Output(string.Format("[{0}] Started Cleaning of Inactive/Invalid Users.", DateTime.Now));
            List<string> invalidAccounts = GetInvalidAccounts(config, db);
            List<string> inactiveAccounts = GetInactiveAccounts(config, db, maxDays);

            // Delete invalid accounts
            foreach (string account in invalidAccounts)
            {
                UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account));
            }

            if (invalidAccounts.Count > 0)
            {
                // Add to transparency report if any users were removed
                Takedown report = db.Takedowns.Create();
                report.Requester = TAKEDOWN_REPORTER;
                report.RequesterContact = config.SupportEmail;
                report.DateRequested = DateTime.Now;
                report.Reason = "Username Invalid";
                report.ActionTaken = string.Format("{0} Accounts Removed", invalidAccounts.Count);
                report.DateActionTaken = DateTime.Now;
                db.Takedowns.Add(report);
                db.SaveChanges();
            }

            // Delete inactive accounts
            foreach (string account in inactiveAccounts)
            {
                UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account));
            }

            if (invalidAccounts.Count > 0)
            {
                // Add to transparency report if any users were removed
                Takedown report = db.Takedowns.Create();
                report.Requester = TAKEDOWN_REPORTER;
                report.RequesterContact = config.SupportEmail;
                report.DateRequested = DateTime.Now;
                report.Reason = "Account Inactive";
                report.ActionTaken = string.Format("{0} Accounts Removed", inactiveAccounts.Count);
                report.DateActionTaken = DateTime.Now;
                db.Takedowns.Add(report);
                db.SaveChanges();
            }

            Output(string.Format("[{0}] Finished Cleaning of Inactive/Invalid Users.  {1} Accounts Removed.", DateTime.Now, invalidAccounts.Count + inactiveAccounts.Count));
        }
Exemplo n.º 4
0
        public static void ScanUploads(Config config, TeknikEntities db)
        {
            Output(string.Format("[{0}] Started Virus Scan.", DateTime.Now));
            List<Upload> uploads = db.Uploads.ToList();

            // Initialize ClamAV
            ClamClient clam = new ClamClient(config.UploadConfig.ClamServer, config.UploadConfig.ClamPort);
            clam.MaxStreamSize = config.UploadConfig.MaxUploadSize;

            int totalCount = uploads.Count();
            int totalScans = 0;
            int totalClean = 0;
            int totalViruses = 0;
            foreach (Upload upload in uploads)
            {
                totalScans++;
                string subDir = upload.FileName[0].ToString();
                string filePath = Path.Combine(config.UploadConfig.UploadDirectory, subDir, upload.FileName);
                if (File.Exists(filePath))
                {
                    // Read in the file
                    byte[] data = File.ReadAllBytes(filePath);
                    // If the IV is set, and Key is set, then decrypt it
                    if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
                    {
                        // Decrypt the data
                        data = AES.Decrypt(data, upload.Key, upload.IV);
                    }

                    // We have the data, let's scan it
                    ClamScanResult scanResult = clam.SendAndScanFile(data);

                    switch (scanResult.Result)
                    {
                        case ClamScanResults.Clean:
                            totalClean++;
                            string cleanMsg = string.Format("[{0}] Clean Scan: {1}/{2} Scanned | {3} - {4}", DateTime.Now, totalScans, totalCount, upload.Url, upload.FileName);
                            Output(cleanMsg);
                            break;
                        case ClamScanResults.VirusDetected:
                            totalViruses++;
                            string msg = string.Format("[{0}] Virus Detected: {1} - {2} - {3}", DateTime.Now, upload.Url, upload.FileName, scanResult.InfectedFiles.First().VirusName);
                            File.AppendAllLines(virusFile, new List<string> { msg });
                            Output(msg);
                            // Delete from the DB
                            db.Uploads.Remove(upload);
                            db.SaveChanges();

                            // Delete the File
                            if (File.Exists(filePath))
                            {
                                File.Delete(filePath);
                            }
                            break;
                        case ClamScanResults.Error:
                            string errorMsg = string.Format("[{0}] Scan Error: {1}", DateTime.Now, scanResult.RawResult);
                            File.AppendAllLines(errorFile, new List<string> { errorMsg });
                            Output(errorMsg);
                            break;
                        case ClamScanResults.Unknown:
                            string unkMsg = string.Format("[{0}] Unknown Scan Result: {1}", DateTime.Now, scanResult.RawResult);
                            File.AppendAllLines(errorFile, new List<string> { unkMsg });
                            Output(unkMsg);
                            break;
                    }
                }
            }

            if (totalViruses > 0)
            {
                // Add to transparency report if any were found
                Takedown report = db.Takedowns.Create();
                report.Requester = TAKEDOWN_REPORTER;
                report.RequesterContact = config.SupportEmail;
                report.DateRequested = DateTime.Now;
                report.Reason = "Malware Found";
                report.ActionTaken = string.Format("{0} Uploads removed", totalViruses);
                report.DateActionTaken = DateTime.Now;
                db.Takedowns.Add(report);
                db.SaveChanges();
            }

            Output(string.Format("Scanning Complete.  {0} Scanned | {1} Viruses Found | {2} Total Files", totalScans, totalViruses, totalCount));
        }
Exemplo n.º 5
0
        public static bool VerifyResetPassword(TeknikEntities db, Config config, string username, string code)
        {
            User user = GetUser(db, username);
            ResetPasswordVerification verCode = db.ResetPasswordVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
            if (verCode != null)
            {
                // We have a match, so clear out the verifications for that user
                List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == username).ToList();
                if (verCodes != null && verCodes.Any())
                {
                    foreach (ResetPasswordVerification ver in verCodes)
                    {
                        db.ResetPasswordVerifications.Remove(ver);
                    }
                }
                db.SaveChanges();

                return true;
            }
            return false;
        }
Exemplo n.º 6
0
        public static string CreateResetPasswordVerification(TeknikEntities db, Config config, User user)
        {
            // Check to see if there already is a verification code for the user
            List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
            if (verCodes != null && verCodes.Any())
            {
                foreach (ResetPasswordVerification verCode in verCodes)
                {
                    db.ResetPasswordVerifications.Remove(verCode);
                }
            }

            // Create a new verification code and add it
            string verifyCode = Helpers.Utility.RandomString(24);
            ResetPasswordVerification ver = new ResetPasswordVerification();
            ver.UserId = user.UserId;
            ver.Code = verifyCode;
            ver.DateCreated = DateTime.Now;
            db.ResetPasswordVerifications.Add(ver);
            db.SaveChanges();

            return verifyCode;
        }
Exemplo n.º 7
0
        public static bool VerifyRecoveryEmail(TeknikEntities db, Config config, string username, string code)
        {
            User user = GetUser(db, username);
            RecoveryEmailVerification verCode = db.RecoveryEmailVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
            if (verCode != null)
            {
                // We have a match, so clear out the verifications for that user
                List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == username).ToList();
                if (verCodes != null && verCodes.Any())
                {
                    foreach (RecoveryEmailVerification ver in verCodes)
                    {
                        db.RecoveryEmailVerifications.Remove(ver);
                    }
                }
                // Update the user
                user.SecuritySettings.RecoveryVerified = true;
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();

                return true;
            }
            return false;
        }
Exemplo n.º 8
0
        public static void DeleteUser(TeknikEntities db, Config config, User user)
        {
            try
            {
                // Update uploads
                List<Upload.Models.Upload> uploads = db.Uploads.Where(u => u.User.Username == user.Username).ToList();
                if (uploads != null)
                {
                    foreach (Upload.Models.Upload upload in uploads)
                    {
                        upload.UserId = null;
                        db.Entry(upload).State = EntityState.Modified;
                    }
                    db.SaveChanges();
                }

                // Update pastes
                List<Paste.Models.Paste> pastes = db.Pastes.Where(u => u.User.Username == user.Username).ToList();
                if (pastes != null)
                {
                    foreach (Paste.Models.Paste paste in pastes)
                    {
                        paste.UserId = null;
                        db.Entry(paste).State = EntityState.Modified;
                    }
                    db.SaveChanges();
                }

                // Update shortened urls
                List<ShortenedUrl> shortUrls = db.ShortenedUrls.Where(u => u.User.Username == user.Username).ToList();
                if (shortUrls != null)
                {
                    foreach (ShortenedUrl shortUrl in shortUrls)
                    {
                        shortUrl.UserId = null;
                        db.Entry(shortUrl).State = EntityState.Modified;
                    }
                    db.SaveChanges();
                }

                // Delete Blogs
                Blog.Models.Blog blog = db.Blogs.Where(u => u.User.Username == user.Username).FirstOrDefault();
                if (blog != null)
                {
                    db.Blogs.Remove(blog);
                    db.SaveChanges();
                }

                // Delete post comments
                List<BlogPostComment> postComments = db.BlogComments.Where(u => u.User.Username == user.Username).ToList();
                if (postComments != null)
                {
                    foreach (BlogPostComment postComment in postComments)
                    {
                        db.BlogComments.Remove(postComment);
                    }
                    db.SaveChanges();
                }

                // Delete podcast comments
                List<Podcast.Models.PodcastComment> podComments = db.PodcastComments.Where(u => u.User.Username == user.Username).ToList();
                if (podComments != null)
                {
                    foreach (Podcast.Models.PodcastComment podComment in podComments)
                    {
                        db.PodcastComments.Remove(podComment);
                    }
                    db.SaveChanges();
                }

                // Delete Recovery Email Verifications
                List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
                if (verCodes != null)
                {
                    foreach (RecoveryEmailVerification verCode in verCodes)
                    {
                        db.RecoveryEmailVerifications.Remove(verCode);
                    }
                    db.SaveChanges();
                }

                // Delete Password Reset Verifications 
                List<ResetPasswordVerification> verPass = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
                if (verPass != null)
                {
                    foreach (ResetPasswordVerification ver in verPass)
                    {
                        db.ResetPasswordVerifications.Remove(ver);
                    }
                    db.SaveChanges();
                }

                // Delete User
                db.Users.Remove(user);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Unable to delete user {0}.", user.Username), ex);
            }
        }
Exemplo n.º 9
0
 public static void EditUser(TeknikEntities db, Config config, User user, bool changePass, string password)
 {
     try
     {
         // Changing Password?
         if (changePass)
         {
             // Update User password
             user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
         }
         db.Entry(user).State = EntityState.Modified;
         db.SaveChanges();
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format("Unable to edit user {0}.", user.Username), ex);
     }
 }
Exemplo n.º 10
0
        public static void AddUser(TeknikEntities db, Config config, User user, string password)
        {
            try
            {
                // Add User
                user.HashedPassword = GeneratePassword(config, user, password);
                db.Users.Add(user);
                db.SaveChanges();

                // Generate blog for the user
                var newBlog = db.Blogs.Create();
                newBlog.UserId = user.UserId;
                db.Blogs.Add(newBlog);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to create user.", ex);
            }
        }
Exemplo n.º 11
0
 public static void TransferUser(TeknikEntities db, Config config, User user, string password)
 {
     try
     {
         List<TransferType> transfers = user.Transfers.ToList();
         for (int i = 0; i < transfers.Count; i++)
         {
             TransferType transfer = transfers[i];
             switch (transfer.Type)
             {
                 case TransferTypes.Sha256Password:
                 case TransferTypes.CaseSensitivePassword:
                 case TransferTypes.ASCIIPassword:
                     user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
                     break;
                 default:
                     break;
             }
             user.Transfers.Remove(transfer);
         }
         db.Entry(user).State = EntityState.Modified;
         db.SaveChanges();
     }
     catch (Exception ex)
     {
         throw new Exception("Unable to transfer user info.", ex);
     }
 }