public void GetAll_RequestSignatures_OkResult() { var controller = new SignatureController(_logger, _signatureService); var data = controller.GetAllSignatures(); Assert.IsType <OkObjectResult>(data); }
private void importToolStripMenuItem_Click(object sender, EventArgs e) { // create a new open file dialog using (OpenFileDialog ofd = new OpenFileDialog()) { // set filter for the open file dialog ofd.Filter = "(*.sdb)|*.sdb";; // Check if a file is selected if (ofd.ShowDialog() == DialogResult.OK) { // intialize the sig controller on the file selected Signatures = new SignatureController(ofd.FileName); // try to load the file if (Signatures.LoadDatabase()) { // clean up currently loaded db if any CleanUp(); // load new db into view loadIntoView(); } else { // alert user the file could not be loaded... MessageBox.Show("Unable to load signature database, a new database will be created if you save."); } } } }
public void GetById_NoExistingId_NotFoundResult() { var controller = new SignatureController(_logger, _signatureService); var signatureId = new Guid("A9253E48-A1AB-4F83-A1A7-0E14D0F12345"); var data = controller.GetSignatureById(signatureId); Assert.IsType <NotFoundResult>(data); }
public void GetById_ExistingId_OkResult() { var controller = new SignatureController(_logger, _signatureService); var signatureId = new Guid("EED7F976-58B7-4C05-E3E4-08D6F9F0FC2C"); var data = controller.GetSignatureById(signatureId); Assert.IsType <OkObjectResult>(data); }
public void Delete_NonExistingSignature_NotFoundResult() { var controller = new SignatureController(_logger, _signatureService); var signatureId = new Guid("1c575a69-27f3-4379-b7be-5798a0001449"); var data = controller.DeleteSignature(signatureId); Assert.IsType <NotFoundResult>(data); }
public MainPage() { this.InitializeComponent(); this.setNavbarColor(); this.signatureController = new SignatureController(); this.authorController = new AuthorController(signatureController); this.goToDefaultPage(this, null); this.showTitleBar(true); }
protected override void OnNavigatedTo(NavigationEventArgs e) { //base.OnNavigatedTo(e); this.authorController = (AuthorController)e.Parameter; this.signatureController = authorController.signatureController; //Zaktualizowanie listy autorów this.updateAuthorCombobox(); }
public void GetAll_RequestSignatures_MatchResult() { var controller = new SignatureController(_logger, _signatureService); var data = controller.GetAllSignatures(); Assert.IsType <OkObjectResult>(data); var signatures = data as OkObjectResult; var signatureList = signatures.Value as IList <Entities.Models.Signature>; Assert.Equal("eed7f976-58b7-4c05-e3e4-08d6f9f0fc2c", signatureList[0].Id.ToString()); Assert.Equal("Signature 1", signatureList[0].Name); }
public SignaturePage() { //Start the clock! timer = new Stopwatch(); timer.Start(); signatureController = new SignatureController(); this.InitializeComponent(); this.initializePenHandlers(); //inicjalizacja wielkości pola do rysowania this.initRealSizeInkCanvas(110, 40); }
public void run(SignatureController patterns) { t = new Thread(() => { Result = PatternAnalyzer.AnalyzeByteArray(this.Buffer, patterns); this.Buffer = null; Complete = true; }); t.IsBackground = true; t.SetApartmentState(ApartmentState.MTA); t.Start(); }
public void Create_SignatureWithValidData_OkResult() { var controller = new SignatureController(_logger, _signatureService); var signature = new Entities.Models.Signature { Id = new Guid("e47c0cb5-05b6-437d-b40f-f2c5b5a08385"), Name = "Signature 6", Description = "Signature 6 description" }; var data = controller.CreateSignature(signature); Assert.IsType <CreatedAtRouteResult>(data as CreatedAtRouteResult); }
public static Signature ScanProcess(System.Diagnostics.Process process, ref SignatureController Signatures) { try { if (process.ProcessName == "runnable") { //System.IO.File.WriteAllBytes("dump.txt", buffer); Console.Write(""); } // Get the start address of the main module int regionStart = process.MainModule.EntryPointAddress.ToInt32(); int regionEnd = 0; // Could add multiple module support here ... // for now just get end address regionEnd = process.MainModule.ModuleMemorySize; // Create variables to read the block byte[] buffer = new byte[regionEnd]; IntPtr zero = IntPtr.Zero; // Try to read the section ReadProcessMemory(process.Handle, (IntPtr)regionStart, buffer, (UInt32)buffer.Length, out zero); //if (zero != IntPtr.Zero) { // Run a scan pass of the buffer var result = PatternAnalyzer.AnalyzeByteArray(buffer, Signatures); // Check for results if (result != null) { return(result); } } // nothing found return(null); } catch (Exception ex) { return(null); } //throw new NotImplementedException(); }
public void Update_SignatureWithValidData_OkResult() { var controller = new SignatureController(_logger, _signatureService); var signatureId = new Guid("EED7F976-58B7-4C05-E3E4-08D6F9F0FC2C"); var existingSignature = controller.GetSignatureById(signatureId); Assert.IsType <OkObjectResult>(existingSignature); var signature = (existingSignature as ObjectResult).Value as Entities.Models.Signature; signature.Name = "Signature Modified"; var updatedData = controller.UpdateSignature(signatureId, signature); Assert.IsType <NoContentResult>(updatedData); }
public void Delete_ExistingSignature_OkResult() { var controller = new SignatureController(_logger, _signatureService); var signature = new Entities.Models.Signature { Id = new Guid("f7afefa9-2cc6-4ea9-901d-d99e227a12de"), Name = "Signature", Description = "" }; var data = controller.CreateSignature(signature); Assert.IsType <CreatedAtRouteResult>(data as CreatedAtRouteResult); var deleteResult = controller.DeleteSignature(signature.Id); Assert.IsType <NoContentResult>(deleteResult); }
private void testToolStripMenuItem_Click(object sender, EventArgs e) { Signatures = new SignatureController("test.sdb"); Signatures.SetDbVersion(3.3); using (OpenFileDialog ofd = new OpenFileDialog()) { if (ofd.ShowDialog() != DialogResult.OK) { return; } using (System.IO.StreamReader sr = new System.IO.StreamReader(ofd.FileName)) { while (sr.Peek() > 0) { string line = sr.ReadLine(); string[] data = line.Split('='); this.lstSignatures.Items.Add(new ListViewItem(new string[] { (lstSignatures.Items.Count + 1).ToString(), data[0], format(data[1].ToUpper()), "TEST", DateTime.Now.ToShortDateString() })); var sig = new Signature() { Id = Signatures.NextId(), DateFound = DateTime.Now.ToShortDateString(), Definition = data[0], Description = "Imported" }; sig.SetPatternBytes(format(data[1].ToUpper())); Signatures.AddOne(sig); } } } }
private void newToolStripMenuItem_Click(object sender, EventArgs e) { // create a new save file dialog to save the new sig db to using (SaveFileDialog sfd = new SaveFileDialog()) { // set the filter sfd.Filter = "(*.sdb)|*.sdb"; // If a file location was selected if (sfd.ShowDialog() == DialogResult.OK) { // create new signatures db Signatures = new SignatureController(sfd.FileName); // set default db version Signatures.SetDbVersion(0.1); // clean up currently loaded db if any CleanUp(); } } }
static void Main(string[] args) { // Output some information about the program running Console.Title = "Berzerk Malware Scanner 2 - Test Client - http://JordanHook.com"; // Output version of tester Console.WriteLine("Berzerk Malware Scanner Test Client 2.0"); // Scan a folder based on the args if (args.Length == 0) { Console.WriteLine("No scan directory specified..."); return; } // Declare some variables for the scan string ScanDirectory = args[0]; // Our controllers... SignatureController Signatures = new SignatureController("sigs.sdb"); // Load the library setting defaults (we will add a settings controller later...) BerzerkAPI.Settings.Defaults(); //Set max file size to 5mb to testing purposes.. BerzerkAPI.Settings.MaxFileSize = (1024 * 1024) * 5; // Try to load the signatures if (Signatures.LoadDatabase()) { Console.WriteLine("Signature database was loaded with {0} entries", Signatures.Signatures.Count); } else { // If the signatures can't be loaded... we can't scan for anything Console.WriteLine("Unable to load signature database..."); return; } // Output current task Console.WriteLine("\nGathering files to scan..."); // Now that our controllers have been loaded... we can attempt to start scanning files Queue <string> ScanList = BerzerkAPI.IO.File.CreateFileQueue(ScanDirectory, true); Threats = new List <ThreatDetectedArgs>(); // Store total files to scan... TotalFiles = ScanList.Count; // Output current task Console.WriteLine("\nScanning {0} files...", ScanList.Count); // Create an instance of the scan controller to work with ScanController scanner = new ScanController(ScanList, Signatures); // Setup events scanner.ThreatDetected += Scanner_ThreatDetected; scanner.ThreatScanComplete += Scanner_ThreatScanComplete; // setup watch watch = new Stopwatch(); // Background reporting.. new Thread(() => { Thread.Sleep(1000); // Output some information about the current scan... while (scanner.Scanning) { Console.WriteLine("{0}/{1} Files scanned\t{2:0.00} MB Processed\t{3}", TotalFiles - scanner.TargetFiles.Count, TotalFiles, scanner.ScannedData, watch.Elapsed.ToString()); Console.WriteLine("{0} Threads Active", scanner.RunningThreads); Thread.Sleep(1000); } }).Start(); // start the watch watch.Start(); // Start the scan scanner.Run(); // Keep the program open System.Diagnostics.Process.GetCurrentProcess().WaitForExit(); }
public TestSignatureController() { _signatureController = new SignatureController(_entityFactory); }
/// <summary> /// Non referenced file scan /// </summary> /// <param name="filePath">File to scan.</param> /// <param name="Signatures">Signatures to scan with</param> /// <returns>Null or signature matching or found in file. </returns> //public static ScanResultArgs ScanFile(string filePath, SignatureController Signatures) //{ // return ScanFile(filePath, ref Signatures); //} /// <summary> /// Performs a scan on the provided file /// </summary> /// <param name="filePath">The file to scan.</param> /// <param name="Signatures">The signature controller</param> /// <param name="cached">The cache controller</param> /// <returns>Null or a signature</returns> public static ScanResultArgs ScanFile(string filePath, SignatureController Signatures) { //return ScanFileV2(filePath, Signatures); try { // Final args to return var args = new ScanResultArgs(); // *** NEW *** // Create a new filestream to read the file with FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // Before performing any kind of scan, we need to make sure it's a executable file if (!isScannable(filePath)) { // If it's not, return null and theres no point of scanning it //return null; return(new ScanResultArgs() { Detection = null, Size = fs.Length }); } // Determine if the file is too large to scan based on settings if (fs.Length > Settings.MaxFileSize) { // If so, just return null... return(new ScanResultArgs() { Detection = null, Size = fs.Length }); } // *********** // Some local variables to store scan information in //byte[] hash = MD5.quickMD5(filePath); // If a cache database is supplied with the scan request //if (cached != null) //{ // // Try to obtain a md5 hash from the file (see exception below for possible issues) // //hash = MD5.FromFile(ref fs); // hash = MD5.quickMD5(filePath); // // Check the file cache to see if the file has already been scanned // var found = cached.GetById(hash); // // If a cached item was found in the db // if(found != null) // { // // Return the matching signature if any... // //return Signatures.GetById(found.SignatureId); // return new ScanResultArgs() { Detection = Signatures.GetById(found.SignatureId), Size = fs.Length, Cached = found }; // } //} // Either the file cache database is not being used or no entry was found // So we must perform a new scan on the file byte[] buffer = new byte[1024 * Settings.BufferSize]; // Scan in 32kb increments int read = -1; // count how many bytes have been read on each read here // Make sure our buffer isn't bigger than the file if (buffer.Length > fs.Length) { // If it is, resize the buffer accordinly buffer = new byte[fs.Length]; } // While there is data to read in the file stream while (read != 0) { // Attempt to read the buffered amount.. read = fs.Read(buffer, 0, buffer.Length); // If the buffered amount if greater than the amount read... // Lets shrink buffer to speed up the pattern search if (read < buffer.Length) { Array.Resize(ref buffer, read); } // Analyze the buffer with the pattern analyzer var result = PatternAnalyzer.AnalyzeByteArray(buffer, Signatures); // try version 2.... //var result = PatternAnalyzer.AnyalyzeByteArrayv2(buffer, Signatures); // If the result is not null... a detection was found if (result != null) { // Create args before closing args = new ScanResultArgs() { Detection = result, Size = fs.Length, }; // Detected upx packing... if (args.Detection.Definition == "PACKED") { // UPX ISNT WORKING YET //return new ScanResultArgs() { Detection = null, Size = 0 }; // unpack the file and store the unpacked path... string unpacked = API.UPXHelper.UnpackFile(filePath); // Perform another scan args = ScanFile(unpacked, Signatures); // this was an unpacked program... //if(args.Detection != null) //{ // //args.Detection.Definition = args.Detection.Definition + "/UPX"; //} // delete the unpacked file File.DeleteFile(unpacked); // Remove the unpacked file from white lsit Settings.WhiteList.Remove(unpacked); } // We already detected the threat so we do not need to read any more.. fs.Dispose(); // return the threat return(args); } } // We finished reading the file and no threat was detected // Time to clean and and may be log to cache // Create clean args args = new ScanResultArgs() { Detection = null, Size = fs.Length, }; // Close up the file stream fs.Close(); fs.Dispose(); // clear buffer buffer = null; // Return a clean scan return(args); } catch (Exception ex) // for debugging purposes { #if DEBUG Console.WriteLine(ex.Message); #endif // Throw an exception with info about what may have caused the error. throw new Exception(String.Format("[2] Unable to scan file at location {0}. File may be use or additional rights may be required.", filePath)); //return new ScanResultArgs() { Detection = null, Size = 0 }; } }
public static ScanResultArgs ScanFileV2(string filePath, SignatureController signatures) { try { // Create a new scan result to return with var args = new ScanResultArgs(); // open new file stream FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // set file size args.Size = fs.Length; // Check if scannable file type if (!isScannable(filePath)) { return(new ScanResultArgs() { Detection = null }); } // any other additional checks to perform here // Create variables to load file buffers into //byte[] buffer = new byte[1024 * Settings.BufferSize]; int read = 1; // check if buffer is bigger than file //if(buffer.Length > fs.Length) //{ // fix buffer //buffer = new byte[fs.Length]; //} // Create list of tasks to perform scan on List <ThreadedAnalysis> scans = new List <ThreadedAnalysis>(); int max = Environment.ProcessorCount;; if (Settings.ReducePriority) { max = Environment.ProcessorCount / 2; } // Loop to read file while possible while (read > 0 && args.Detection == null) { // read the file chunk //read = fs.Read(buffer, 0, buffer.Length); // create new threaded scan of the buffer read ThreadedAnalysis t = new ThreadedAnalysis(); read = fs.Read(t.Buffer, 0, t.Buffer.Length); scans.Add(t); t.run(signatures); // we now have to do a check if (scans.Count > max) { // if we have max number of scans running we need to clear up some space for (int i = 0; i < scans.Count; i++) { // check if a scan is done... if (scans[i].Complete) { // if it is, check it's result if (scans[i].Result != null) { // copy detection over args.Detection = scans[i].Result; // Detected upx packing... if (args.Detection.Definition == "PACKED") { // unpack the file and store the unpacked path... string unpacked = API.UPXHelper.UnpackFile(filePath); // Perform another scan args = ScanFileV2(unpacked, signatures); // delete the unpacked file File.DeleteFile(unpacked); // Remove the unpacked file from white lsit Settings.WhiteList.Remove(unpacked); } return(args); } else { // no detection so clear up the scan list scans.Remove(scans[i]); } } } } } while (scans.Count > 0) { // if we have max number of scans running we need to clear up some space for (int i = 0; i < scans.Count; i++) { // check if a scan is done... if (scans[i].Complete) { // if it is, check it's result if (scans[i].Result != null) { // copy detection over args.Detection = scans[i].Result; // Detected upx packing... if (args.Detection.Definition == "PACKED") { // unpack the file and store the unpacked path... string unpacked = API.UPXHelper.UnpackFile(filePath); // Perform another scan args = ScanFileV2(unpacked, signatures); // delete the unpacked file File.DeleteFile(unpacked); // Remove the unpacked file from white lsit Settings.WhiteList.Remove(unpacked); } return(args); } else { // no detection so clear up the scan list scans.Remove(scans[i]); } } else { scans[i].waiting(); } } } fs.Dispose(); //buffer = null; // return scan results return(args); } catch (Exception ex) { #if DEBUG Console.WriteLine(ex.Message); #endif throw new Exception("Unable to scan file at location: " + filePath); } }
static void Main(string[] args) { // Output some information about the program running Console.Title = "Berzerk Malware Scanner - Test Client - http://JordanHook.com"; // Output version of tester Console.WriteLine("Berzerk Malware Scanner Test Client 1.0"); // Scan a folder based on the args if (args.Length == 0) { Console.WriteLine("No scan directory specified..."); return; } // Declare some variables for the scan string ScanDirectory = args[0]; // Our controllers... SignatureController Signatures = new SignatureController("sigs.sdb"); // Load the library setting defaults (we will add a settings controller later...) BerzerkAPI.Settings.Defaults(); //Set max file size to 5mb to testing purposes.. BerzerkAPI.Settings.MaxFileSize = (1024 * 1024) * 5; // Try to load the signatures if (Signatures.LoadDatabase()) { Console.WriteLine("Signature database was loaded with {0} entries", Signatures.Signatures.Count); } else { // If the signatures can't be loaded... we can't scan for anything Console.WriteLine("Unable to load signature database..."); return; } // Output current task Console.WriteLine("\nGathering files to scan..."); // Now that our controllers have been loaded... we can attempt to start scanning files Queue <string> ScanList = BerzerkAPI.IO.File.CreateFileQueue(ScanDirectory, true); // Output current task Console.WriteLine("\nScanning {0} files...", ScanList.Count); // Loop through each file in the list //foreach (string file in ScanList) //{ // try // { // // Run a scan on the file // Signature scan = BerzerkAPI.IO.File.ScanFile(file, Signatures, Cached); // // Check if there is a threat detected // if (scan != null) // { // // Output the detection type and file location // Console.WriteLine("\nDETECTED {0}:\n{1}", scan.Definition, file); // } // } // catch (Exception) // { // // We were unable to access the current file due to permission issues or it being in use... // } //} // Multi threaded scan List <Thread> ScanThreads = new List <Thread>(); int totalFiles = ScanList.Count(); // Run an extra thread to display some information about the scan... new Thread(() => { // While the scan is still running while (ScanList.Count > 0) { Thread.Sleep(5000); Console.WriteLine("{0} Files left to scan...", ScanList.Count); Console.WriteLine("{0} Scanning threads running...", ScanThreads.Count()); Console.WriteLine("{0} Files have been scanned...", totalFiles - ScanList.Count()); // Garbage collect call since our scans use a lot of resources GC.Collect(); } }).Start(); // While there are files left to scan... while (true) { // If there are no scans running and no files left to scan // Exit the infinite loop if (ScanThreads.Count() == 0 && ScanList.Count == 0) { break; } // Find a dead thread... var dead = ScanThreads.FirstOrDefault(th => th.ThreadState == ThreadState.Stopped); // While there are more dead threads while (dead != null) { // Remove them ScanThreads.Remove(dead); // Find more? dead = ScanThreads.FirstOrDefault(th => th.ThreadState == ThreadState.Stopped); } // Ensure 1 thread per processor core while (ScanThreads.Count() < Environment.ProcessorCount) { // Don't start a new thread if the scan list is empty.. we just need to wait for the rest of the scans to finish... if (ScanList.Count == 0) { break; } // Create a new thead Thread t = new Thread(() => { try { // Get the next file string current = ScanList.Dequeue(); // Scan the current file //Signature scan = BerzerkAPI.IO.File.ScanFile(current, ref Signatures, ref Cached); ScanResultArgs result = BerzerkAPI.IO.File.ScanFile(current, Signatures); // Check the results if (result.Detection != null) { Console.WriteLine("\nDETECTED {0}:\n{1}", result.Detection.Definition, current); } } catch (Exception) { // We were unable to access the current file due to permission issues or it being in use... } }); // Add the scan thread to the list ScanThreads.Add(t); // Run the thread t.IsBackground = true; t.Start(); } // Pause while we wait for a scan to finish... Thread.Sleep(10); } // All scans completed, give a delay before outputting finished results incase a detection is still being outputted.. Thread.Sleep(1500); // EOP... Console.WriteLine("\n\n\nScan complete, press any key to exit..."); Console.ReadKey(); }
protected override void OnNavigatedTo(NavigationEventArgs e) { //base.OnNavigatedTo(e); this.authorController = (AuthorController)e.Parameter; this.signatureController = authorController.signatureController; }
public void GetById_NullId_BadRequestResult() { var controller = new SignatureController(_logger, _signatureService); Guid signatureId = Guid.Empty; var data = controller.GetSignatureById(signatureId); }
// public static AhoCorasick.Trie<byte, Signature> matcher; /// <summary> /// Searches a byte array for matching patterns /// </summary> /// <param name="data">The byte array to search</param> /// <param name="patterns">The list of patterns to search for</param> /// <returns>A matching malware signature or null if nothing is found</returns> public static Signature AnalyzeByteArray(byte[] data, SignatureController patterns) { var found = patterns.Analyzer.SearchFirst(data); if (found.Index == -1) { return(null); } else { return(found.Match); } //var found = matcher.Find(data); //if (found.Count() > 0) //{ // return found.ElementAt(0); //} ////////if (matcher.Find(data).Any()) ////////{ //////// return new Signature() { Definition = "TEST" }; ////////} //return null; //var result = matcher.Find(data); //if (result.Count() == 0) // return null; //else // return result.ElementAt(0); // Get all signatures that are a valid length to search for // Signatures must be less than or equal to the length of data //var validSignatures = patterns.Signatures.Where(s => s.Pattern.Length < data.Length); //// Now loop through all the valid signatures and compare them agaisnt the data looking for a match foreach (Signature s in patterns.Signatures) { // Based on the size of the pattern, run an appropriate algorithm if (s.Pattern.Length <= 8) { // Shorter algorithms will run linear searches if (LinearSearch(ref data, s.Pattern) != -1) { return(s); } //if (find(data, data.Length, s.Pattern, s.Pattern.Length) != -1) // return s; } // Longer patterns will perform a BoyerMooreSearch else if (SimpleBoyerMooreSearch(data, s.Pattern) != -1) { return(s); } //else if (KnuthMorrisPrat(data, s.Pattern) != -1) //{ // return s; //} //else if (boyerMoore(data, data.Length, s.Pattern, s.Pattern.Length) != -1) // return s; } //foreach(Signature s in patterns.Signatures) //{ // if(data.Length <= 32768) // { // if (LinearSearch(ref data, s.Pattern) != -1) // return s; // } // else // { // if (SimpleBoyerMooreSearch(data, s.Pattern) != -1) // return s; // } //} // If no matches were found, return null return(null); }