public void ExtractStrings() { try { using (var file = new ElfFile(StreamLoader.FromFile(ElfFilePath))) { if (file.Header.IsValid) { var strings = new List <string>(); foreach (var strSec in file.GetStringSections()) { foreach (var str in strSec) { if (str != null) { var n = str.Name; var idx = str.Index; var e = $"STRING ENTRY: {idx} :: {n}"; strings.Add(e); } } } File.WriteAllLines(@"strings.log", strings); } } } catch (Exception ex) { UiMessages.Error(ex.ToString()); } }
static void ReadAxml(String filePath) { using (AxmlFile axml = new AxmlFile(StreamLoader.FromFile(filePath))) { if (!axml.Header.IsValid) { throw new ArgumentException("Invalid header"); } Utils.ConsoleWriteMembers(axml.Header); Console.WriteLine(axml.RootNode.ConvertToString()); } }
public PEResources(string FiletoScan, ref XMLParser raport) { //var peHeader = new PeNet.PeFile(FiletoScan); using (PEFile info = new PEFile(StreamLoader.FromFile(FiletoScan))) { if (!info.Resource.IsEmpty) { Int32 directoriesCount = 0; foreach (var dir in info.Resource) { directoriesCount++; foreach (var dir1 in dir) { foreach (var dir2 in dir1) { if (dir2.DirectoryEntry.IsDataEntry) { ListResourcesbyLanguage(dir2.Name); ListResourcesbyType(dir.Name); Byte[] bytesM = dir2.GetData(); using (SHA256 SHA256 = SHA256.Create()) { if (Convert.ToInt32(dir2.Name) > 0) { CultureInfo LCID = new CultureInfo(Convert.ToInt32(dir2.Name), false); raport.AddPEResources(dir.Name, LCID.Name, BitConverter.ToString(SHA256.ComputeHash(bytesM)).Replace("-", string.Empty)); } else { raport.AddPEResources(dir.Name, "Neutral", BitConverter.ToString(SHA256.ComputeHash(bytesM)).Replace("-", string.Empty)); } } } } } } } } var items = from pair in ResourcesbyType orderby pair.Value descending select pair; raport.AddPEResourcesbyType(items); var items2 = from pair in ResourcesbyLanguage orderby pair.Value descending select pair; raport.AddPEResourcesbyLanguage(items2); }
static void ReadApkManifest(String manifestPath, String resourcesPath) { AxmlFile axml = new AxmlFile(StreamLoader.FromFile(manifestPath)); ArscFile resources = new ArscFile(File.ReadAllBytes(resourcesPath)); if (!axml.Header.IsValid || !resources.Header.IsValid) { throw new InvalidOperationException(); } AndroidManifest apk = AndroidManifest.Load(axml, resources); Console.WriteLine("Label: " + apk.Application.Label); Console.WriteLine("Package: " + apk.Package); Console.WriteLine("Icon: " + apk.Application.Icon); Console.WriteLine("Permissions: " + String.Join(", ", apk.UsesPermission.Select(p => p.Name))); Console.WriteLine("Services: " + String.Join(", ", apk.Application.Service)); Console.WriteLine("Activities: " + String.Join(", ", apk.Application.Activity)); Console.WriteLine("Reciever: " + String.Join(", ", apk.Application.Reciever)); Console.WriteLine("Features: " + String.Join(", ", apk.UsesFeature)); Console.WriteLine("Uses Libraries: " + String.Join(", ", apk.Application.UsesLibrary.Select(p => p.Name))); }
internal static async Task InjectDLL(Process Process, string DLLName, bool x86proc) { IntPtr hProcess = Process.Handle; // Length of string containing the DLL file name +1 byte padding IntPtr LenWrite = new IntPtr(DLLName.Length + 1); // Allocate memory within the virtual address space of the target process IntPtr AllocMem = VirtualAllocEx(hProcess, (IntPtr)null, LenWrite, AllocationType.Commit, MemoryProtection.ExecuteReadWrite); //allocation pour WriteProcessMemory // Write DLL file name to allocated memory in target process WriteProcessMemory(hProcess, AllocMem, Encoding.Default.GetBytes(DLLName), LenWrite, out uint bytesout); // Function pointer "Injector" IntPtr Injector; if (Environment.Is64BitProcess && x86proc)//WOW64 case { MODULEENTRY32 k32mod = GetModules((uint)Process.Id).SingleOrDefault(x => x.szModule.Equals("kernel32.dll", StringComparison.InvariantCultureIgnoreCase)); using (PEFile pe = new PEFile(StreamLoader.FromFile(k32mod.szExePath)))//alternatively ReadProcessMemory... but source name? { Version winver = Environment.OSVersion.Version; string LoadLibraryVariant = winver.Major <= 6 && winver.Minor <= 1 ? "LoadLibraryA" : "LoadLibraryExA"; Injector = IntPtr.Add(k32mod.hModule, (int)pe.Export.GetExportFunctions().SingleOrDefault(x => x.Name.Equals(LoadLibraryVariant)).Address); } } else { Injector = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); } if (Injector == null) { LogHost.Default.Error("Injector Error!"); // return failed return; } // Create thread in target process, and store handle in hThread IntPtr hThread = CreateRemoteThread(hProcess, (IntPtr)null, IntPtr.Zero, Injector, AllocMem, 0, out bytesout); // Make sure thread handle is valid if (hThread == null) { //incorrect thread handle ... return failed LogHost.Default.Error("hThread [ 1 ] Error!"); return; } // Time-out is 10 seconds... uint Result = WaitForSingleObject(hThread, 10 * 1000); // Check whether thread timed out... if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFFF) { /* Thread timed out... */ LogHost.Default.Error("hThread [ 2 ] Error!"); // Make sure thread handle is valid before closing... prevents crashes. if (hThread != null) { //Close thread in target process CloseHandle(hThread); } return; } // Sleep for 1 second await Task.Delay(1000);//Thread.Sleep(1000); //for (int w = 0; !PersistentNamedPipeServer.Instance.IsConnected && w < 1000; w += 10) //{ // await Task.Delay(10); //} // Clear up allocated space ( Allocmem ) VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000); // Make sure thread handle is valid before closing... prevents crashes. if (hThread != null) { //Close thread in target process CloseHandle(hThread); } // return succeeded return; }
static void Main(string[] args) { Console.WriteLine("Skater.net Deobfuscator \n \n"); int nombreDeStringEncodée = 0; ModuleDefMD module = ModuleDefMD.Load(args[0]); //Type which contains String Initialization TypeDef InitialType = null; //We grab native method to count all of them List <MethodDef> ListOfNativeMeths = new List <MethodDef>(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); foreach (TypeDef t in module.GetTypes()) { foreach (MethodDef m in t.Methods) { if (m.Name.Contains("OOOOlx")) { ListOfNativeMeths.Add(m); } } } nombreDeStringEncodée = ListOfNativeMeths.Count(); //We grab the type to find cctor afterwards InitialType = ListOfNativeMeths.First().DeclaringType; string DLLName = ListOfNativeMeths.First().ImplMap.Module.Name; Console.WriteLine("Native DLL Name : " + DLLName); //We stock strings in a list List <string> deHexedstring = new List <string>(); //Reading PE using (PEFile file = new PEFile(StreamLoader.FromFile(Path.GetDirectoryName(args[0]) + @"\" + DLLName))) { var section = file.Header.Sections; foreach (var item in section) { var realName = new string(item.Name); //Strings are stored in .data section if (realName.Contains(".data")) { //offset of the beginning of the section var start = item.PointerToRawData; //calculation of section's size var length = item.PointerToRawData + item.SizeOfRawData; //We copy all bytes into a list List <byte> b = new List <byte>(); using (FileStream fsSourceDDS = new FileStream(Path.GetDirectoryName(args[0]) + @"\" + DLLName, FileMode.Open, FileAccess.Read)) using (BinaryReader binaryReader = new BinaryReader(fsSourceDDS)) { fsSourceDDS.Seek(start, SeekOrigin.Begin); while (start < length) { byte y = binaryReader.ReadByte(); b.Add(y); start++; } } dataSectionContent = b.ToArray(); string input = ByteArrayToString(dataSectionContent); //we split the whole strings string[] datacontent = input.Split(new string[] { "00" }, StringSplitOptions.None); //We remove empty results datacontent = datacontent.Where(x => !string.IsNullOrEmpty(x)).ToArray(); //We only need values associated to strings string[] encodedstring = datacontent.Take(nombreDeStringEncodée).Select(i => i.ToString()).ToArray(); foreach (var hexedstring in encodedstring) { deHexedstring.Add(Encoding.UTF8.GetString(StringToByteArray(hexedstring))); } } } } //That's why we needed to find the type MethodDef cctor = InitialType.FindStaticConstructor(); if (cctor == null) { Console.WriteLine("Impossible to find Method which initialize strings"); return; } //We make a dictionnary to replace values of field Dictionary <FieldDef, string> FieldValue = new Dictionary <FieldDef, string>(); for (int i = 0; i < cctor.Body.Instructions.Count - 1; i++) { if (cctor.Body.Instructions[i].OpCode == OpCodes.Ldsfld && cctor.Body.Instructions[i + 1].OpCode == OpCodes.Call && cctor.Body.Instructions[i + 2].OpCode == OpCodes.Stsfld) { cctor.Body.Instructions[i].OpCode = OpCodes.Nop; cctor.Body.Instructions[i + 1].OpCode = OpCodes.Ldstr; string decrypted = smethod_0(deHexedstring[0]); cctor.Body.Instructions[i + 1].Operand = decrypted; FieldValue.Add((FieldDef)cctor.Body.Instructions[i + 2].Operand, decrypted); deHexedstring.RemoveAt(0); } } int DecryptedStrings = 0; //Replacing field values foreach (TypeDef type in module.Types) { foreach (MethodDef method in type.Methods) { if (method.HasBody && method.Body.HasInstructions) { Cleaner(method); for (int i = 0; i < method.Body.Instructions.Count - 1; i++) { try { if (method.Body.Instructions[i].OpCode == OpCodes.Ldsfld) { FieldDef fld = (FieldDef)method.Body.Instructions[i].Operand; if (FieldValue.Keys.Contains(fld)) { method.Body.Instructions[i].OpCode = OpCodes.Ldstr; method.Body.Instructions[i].Operand = FieldValue[fld]; DecryptedStrings++; } } } catch { } } } } } stopWatch.Stop(); Console.WriteLine("Done ! Elapsed time : " + stopWatch.Elapsed.TotalSeconds); //Saving ASM string SavingPath = module.Kind == ModuleKind.Dll ? args[0].Replace(".dll", "-Deobfuscated.dll") : args[0].Replace(".exe", "-Deobfuscated.exe"); var opts = new ModuleWriterOptions(module); opts.MetaDataOptions.Flags = MetaDataFlags.PreserveAll; opts.Logger = DummyLogger.NoThrowInstance; module.Write(SavingPath, opts); Console.WriteLine("Sucessfully decrypted {0} strings", DecryptedStrings); Console.WriteLine("Control Flow removed", DecryptedStrings); Console.ReadLine(); }
static void ReadSo(String binFile) { using (ElfFile file = new ElfFile(StreamLoader.FromFile(binFile))) { Utils.ConsoleWriteMembers(file.Header.Identification); if (file.Header.IsValid) { DebugStringSection debugSection = file.GetDebugStringSection(); if (debugSection != null) { foreach (var symbolSec in debugSection) { Utils.ConsoleWriteMembers(symbolSec); } } foreach (var noteSec in file.GetNotesSections()) { foreach (var note in noteSec) { Utils.ConsoleWriteMembers(note); } } Utils.ConsoleWriteMembers(file.Header.Header); foreach (var strSec in file.GetStringSections()) { foreach (var str in strSec) { Utils.ConsoleWriteMembers(str); } } foreach (var symbolSec in file.GetSymbolSections()) { foreach (var symbol in symbolSec) { Utils.ConsoleWriteMembers(symbol); } } foreach (var relSec in file.GetRelocationSections()) { foreach (var rel in relSec) { Utils.ConsoleWriteMembers(rel); } } foreach (var relaSec in file.GetRelocationASections()) { foreach (var rela in relaSec) //TODO: Check it { Utils.ConsoleWriteMembers(rela); } } SymbolSection symbols = file.GetSymbolSections().FirstOrDefault(); if (symbols != null) { foreach (var item in symbols) { if (String.IsNullOrEmpty(item.Name)) { Console.WriteLine("EMPTY REF"); } } /*StringSection strings = file.GetStringSections().FirstOrDefault(p => p.Section.Name == ".dynstr"); * foreach(var item in symbols) * { * String str = strings[item.st_name]; * Console.WriteLine(str); * if(String.IsNullOrEmpty(str)) * Console.WriteLine("EMPTY REF"); * if(item.st_shndx != 0) * { * Section someSec = file.Sections.First(p => p.Index == item.st_shndx); * Utils.ConsoleWriteMembers(someSec); * } * }*/ } String[] secTypes = file.Sections.Select(p => p.sh_type.ToString()).Distinct().ToArray(); } } }
/// <summary>Create instance of test loader</summary> /// <param name="filePath"></param> public LookupLoader(String filePath) { this._baseLoader = StreamLoader.FromFile(filePath); this._map = new Byte[new FileInfo(filePath).Length]; }
static void ReadDex(String filePath) { using (DexFile info = new DexFile(StreamLoader.FromFile(filePath))) { var items = info.STRING_ID_ITEM; foreach (string_data_row row in info.STRING_DATA_ITEM) { Utils.ConsoleWriteMembers(row); } Utils.ConsoleWriteMembers(info.header); foreach (DexApi.map_item mapItem in info.map_list) { Utils.ConsoleWriteMembers(mapItem); } foreach (annotation_set_row row in info.ANNOTATION_SET_ITEM) { Utils.ConsoleWriteMembers(row); } foreach (annotation_set_ref_row row in info.ANNOTATION_SET_REF_LIST) { Utils.ConsoleWriteMembers(row); } foreach (annotation_directory_row row in info.ANNOTATIONS_DIRECTORY_ITEM) { Utils.ConsoleWriteMembers(row); } foreach (field_annotation_row row in info.field_annotation) { Utils.ConsoleWriteMembers(row); } foreach (parameter_annotation_row row in info.parameter_annotation) { Utils.ConsoleWriteMembers(row); } foreach (method_annotation_row row in info.method_annotation) { Utils.ConsoleWriteMembers(row); } foreach (class_data_row row in info.CLASS_DATA_ITEM) { Utils.ConsoleWriteMembers(row); } foreach (encoded_field_row row in info.encoded_field) { Utils.ConsoleWriteMembers(row); } foreach (encoded_method_row row in info.encoded_method) { Utils.ConsoleWriteMembers(row); } foreach (code_row row in info.CODE_ITEM) { Utils.ConsoleWriteMembers(row); } foreach (try_item_row row in info.try_item) { Utils.ConsoleWriteMembers(row); } foreach (encoded_catch_handler_row row in info.encoded_catch_handler_list) { Utils.ConsoleWriteMembers(row); } foreach (encoded_type_addr_pair_row row in info.encoded_type_addr_pair) { Utils.ConsoleWriteMembers(row); } foreach (type_list_row row in info.TYPE_LIST) { Utils.ConsoleWriteMembers(row); } foreach (type_id_row row in info.TYPE_ID_ITEM) { Utils.ConsoleWriteMembers(row); } foreach (proto_id_row row in info.PROTO_ID_ITEM) { Utils.ConsoleWriteMembers(row); } foreach (field_id_row row in info.FIELD_ID_ITEM) { Utils.ConsoleWriteMembers(row); } foreach (method_id_row row in info.METHOD_ID_ITEM) { Utils.ConsoleWriteMembers(row); } foreach (class_def_row row in info.CLASS_DEF_ITEM) { Utils.ConsoleWriteMembers(row); } } }
static void ReadManifest(String filePath) { AxmlFile manifest = new AxmlFile(StreamLoader.FromFile(filePath)); Console.Write(manifest.RootNode.ConvertToString()); }