/// <summary> /// Loads file with specific path and name (file) and saves it in UploadedModel class. /// </summary> /// /// <param name="file">Name of the file to be loaded into instance of UploadedModel class.</param> private void LoadFile(string file) { // Declare the hashtable reference. Hashtable addresses = null; // Open the file containing the data that you want to deserialize. FileStream fs = new FileStream(file, FileMode.Open); try { BinaryFormatter formatter = new BinaryFormatter(); // Deserialize the hashtable from the file and // assign the reference to the local variable. addresses = (Hashtable)formatter.Deserialize(fs); } catch (SerializationException e) { string m = "Failed to deserialize. Reason: " + e.Message; CustomDialogBox dialog = new CustomDialogBox("Failed", m, global::antico.Properties.Resources.error, MessageBoxButtons.OK); dialog.ShowDialog(); throw new Exception("[LoadFile] Failed to deserialize. Reason: " + e.Message); } finally { fs.Close(); } // New uploaded model. this.detection = new UploadedModel(); // Load values from file into UploadedModel class. foreach (DictionaryEntry de in addresses) { this.detection.LoadBasic(de.Key.ToString(), de.Value); } }
/// <summary> /// Forward user to form where he can check if his file is malicious. /// </summary> /// /// <param name="sender"></param> /// <param name="e"></param> private void IsThisMaliciousSign_MouseClick(object sender, MouseEventArgs e) { // TODO: only for clamp database. // Get path to \Downloads folder. string downloadsPath = KnownFolders.Downloads.Path; DialogResult result = this.chooseFileToDetermineIfMaliciousDialog.ShowDialog(); // Show the dialog. if (result == DialogResult.OK) // Test result. { string file = this.chooseFileToDetermineIfMaliciousDialog.FileName; string script = "../../../../[PYTHON]/extractFeatures.py"; #region handle non-english charachters in path // Move script to \Downloads. File.Copy(Path.GetFullPath(script).Replace("/", @"\\"), downloadsPath + @"\\" + Path.GetFileName(script), true); // Move file to \Downloads. File.Copy(file, downloadsPath + @"\\" + Path.GetFileName(file), true); var targetDirPath = new DirectoryInfo(downloadsPath + @"\\Python"); var sourceDirPath = new DirectoryInfo(Path.GetFullPath("../../../../[PYTHON]/Python/")); CopyAll(targetDirPath, sourceDirPath); script = downloadsPath + @"\\" + Path.GetFileName(script); string outputFile = (downloadsPath + @"\" + Path.GetFileName(file) + rand.Next(10000).ToString() + "_clamp_features.csv").ToString(); #endregion #region extract features with python script try { // Create process info. var psi = new ProcessStartInfo(); // Location to python. psi.FileName = Path.GetFullPath(@"../../../../[PYTHON]/Python/python.exe").ToString(); // Provide script and arguments. psi.Arguments = string.Format("{0} {1} {2}", script, downloadsPath + @"\\" + Path.GetFileName(file), outputFile); // Process configuration. psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; // Execute process and get output. var errors = ""; var results = ""; // Execute script. using (var process = Process.Start(psi)) { errors = process.StandardError.ReadToEnd(); results = process.StandardOutput.ReadToEnd(); } if (errors != "") { throw new Exception("[IsThisMaliciousSign_MouseClick]\r\n" + errors); } } catch (IOException) { throw new Exception("[UploadSign_MouseClick] Coudn't process the file."); } #endregion int packed = 0; string packer = "NoPacker"; #region find out packer and packer type using YaraSharp // All API calls happens here. YSInstance instance = new YSInstance(); // Declare external variables (could be null). Dictionary <string, object> externals = new Dictionary <string, object>() { { "filename", string.Empty }, { "filepath", string.Empty }, { "extension", string.Empty } }; // Get list of YARA rules. List <string> rulesFile = new List <string>(); // Download rules (peid.yara) to users computer since YaraSharp can't read non-english charachters in file path. WebClient Client = new WebClient(); Client.DownloadFile(new Uri("https://raw.githubusercontent.com/urwithajit9/ClaMP/master/scripts/peid.yara"), downloadsPath + @"\peid.yara"); rulesFile.Add(Path.GetFullPath(downloadsPath + @"\peid.yara").ToString()); // Context is where yara is initialized. // From yr_initialize() to yr_finalize(). using (YSContext context = new YSContext()) { // Compiling rules. using (YSCompiler compiler = instance.CompileFromFiles(rulesFile, externals)) { // Get compiled rules. YSRules rules = compiler.GetRules(); // Get errors. YSReport errors = compiler.GetErrors(); // Get warnings. YSReport warnings = compiler.GetWarnings(); // Some file to test yara rules. string Filename = file; // Get matches. List <YSMatches> Matches = instance.ScanFile(Filename, rules, new Dictionary <string, object>() { { "filename", Path.GetFileName(Filename) }, { "filepath", Path.GetFullPath(Filename) }, { "extension", Path.GetExtension(Filename) } }, 0); // Get packer name if packed. if (Matches.Count > 0) { packed = 1; packer = Matches[0].Rule.Identifier; } } } #endregion #region determine if file is malicious using best model so far DataTable fileFeatures = new DataTable(); #region csv to datatable using (StreamReader sr = new StreamReader(outputFile)) { string[] headers = sr.ReadLine().Split(','); foreach (string header in headers) { fileFeatures.Columns.Add(header); } while (!sr.EndOfStream) { string[] rows = sr.ReadLine().Split(','); if (rows[0] == "") { continue; } DataRow dr = fileFeatures.NewRow(); for (int i = 0; i < headers.Length; i++) { if (headers[i] == "packer") { dr[i] = packed; continue; } if (headers[i] == "packer_type") { dr[i] = packer; continue; } dr[i] = rows[i]; } fileFeatures.Rows.Add(dr); } } #endregion double evaluation = this.detection.model.symbolicTree.Evaluate(fileFeatures.Rows[0]); if (evaluation >= 0) { string mnok = "Your file is malicious!"; CustomDialogBox dialog = new CustomDialogBox("Malicious", mnok, global::antico.Properties.Resources.nok_shield, MessageBoxButtons.OK); dialog.ShowDialog(); } else { string mok = "Your file is benign!"; CustomDialogBox dialog = new CustomDialogBox("Benign", mok, global::antico.Properties.Resources.ok_shield, MessageBoxButtons.OK); dialog.ShowDialog(); } #endregion #region handle non-english charachters in path // Delete and move files at the end. if (File.Exists(downloadsPath + @"\\" + Path.GetFileName(script))) { // Delete script from \Downloads directory. File.Delete(downloadsPath + @"\\" + Path.GetFileName(script)); } if (File.Exists(outputFile)) { // Move file to its true destination. File.Move(outputFile, @"..\\..\\..\\..\\[PYTHON]\\ExtractedFeatures\\" + Path.GetFileName(outputFile)); } if (File.Exists(downloadsPath + @"\\" + Path.GetFileName(file))) { File.Delete(downloadsPath + @"\\" + Path.GetFileName(file)); } if (Directory.Exists(downloadsPath + @"\\Python")) { Directory.Delete(downloadsPath + @"\\Python", true); } #endregion // Delete downloaded peid.yara file. if (File.Exists(downloadsPath + @"\peid.yara")) { File.Delete(downloadsPath + @"\peid.yara"); } } }