Inheritance: Mono.Cecil.Resource
Ejemplo n.º 1
0
 public bool canDecryptResource(EmbeddedResource resource)
 {
     var info = getEmbeddedAssemblyInfo(resource);
     if (info == null || !info.isCompressed)
         return true;
     return resourceDecrypter.CanDecrypt;
 }
Ejemplo n.º 2
0
        protected override bool checkHandlerMethod(MethodDefinition method)
        {
            if (!method.IsStatic || !method.HasBody)
                return false;

            EmbeddedResource resource = null;
            var instructions = method.Body.Instructions;
            for (int i = 0; i < instructions.Count; i++) {
                var instrs = DotNetUtils.getInstructions(instructions, i, OpCodes.Ldstr, OpCodes.Call);
                if (instrs == null)
                    continue;

                var s = instrs[0].Operand as string;
                var calledMethod = instrs[1].Operand as MethodReference;
                if (s == null || calledMethod == null)
                    continue;

                resource = DotNetUtils.getResource(module, SA_Utils.getAssemblySimpleName(s)) as EmbeddedResource;
                if (resource != null)
                    break;
            }
            if (resource == null)
                return false;

            embeddedAssembliesResource = resource;
            Log.v("Found embedded assemblies resource {0}", Utils.toCsharpString(embeddedAssembliesResource.Name));
            return true;
        }
Ejemplo n.º 3
0
 public byte[] decrypt(EmbeddedResource resource)
 {
     if (!CanDecrypt)
         throw new ApplicationException("Can't decrypt resources");
     var encryptedData = resource.GetResourceData();
     return decrypt(encryptedData);
 }
        public void Process(EmbeddedResource embeddedResource, ResourceWriter resourceWriter)
        {
            if (_bamlStreams.Count == 0)
                return;

            WriteCollectedBamlStreams(resourceWriter);
            PatchGenericThemesBaml(resourceWriter);
        }
Ejemplo n.º 5
0
 void Embedd(string fullPath)
 {
     logger.LogMessage(string.Format("\tEmbedding '{0}'", fullPath));
     var fileStream = File.OpenRead(fullPath);
     streams.Add(fileStream);
     var resource = new EmbeddedResource("costura." + Path.GetFileName(fullPath).ToLowerInvariant(), ManifestResourceAttributes.Private, fileStream);
     moduleReader.Module.Resources.Add(resource);
 }
        /// <summary>
        /// Adds infromation about embedded resource file in Mono.Cecil format into list.
        /// </summary>
        /// <param name="item">Embedded resouce file information in Mono.Cecil format.</param>
        /// <param name="count">Number of recource items in this resouce file.</param>
        public void AddResourceFile(
            EmbeddedResource item,
            UInt32 count)
        {
            var correctFileName = Path.ChangeExtension(item.Name, ".tinyresources");
            var nameStringId = _context.StringTable.GetOrCreateStringId(correctFileName);

            _resouces.Add(new Tuple<UInt16, UInt32>(nameStringId, count));
        }
        public override void VisitEmbeddedResource(EmbeddedResource res)
        {
            // TODO: Description?
            IResourceWriter resourceWriter = module.Builder.DefineResource(res.Name, "",
                (System.Reflection.ResourceAttributes)res.Flags);

            resourceWriter.AddResource(res.Name, res.Data);
            resourceWriter.Generate();
        }
Ejemplo n.º 8
0
 public Csvm(IDeobfuscatorContext deobfuscatorContext, ModuleDefinition module, Csvm oldOne)
 {
     this.deobfuscatorContext = deobfuscatorContext;
     this.module = module;
     if (oldOne.resource != null)
         this.resource = (EmbeddedResource)module.Resources[oldOne.module.Resources.IndexOf(oldOne.resource)];
     if (oldOne.vmAssemblyReference != null)
         this.vmAssemblyReference = module.AssemblyReferences[oldOne.module.AssemblyReferences.IndexOf(oldOne.vmAssemblyReference)];
 }
Ejemplo n.º 9
0
    private string Embed(string prefix, string fullPath, bool compress)
    {
        var resourceName = String.Format("{0}{1}", prefix, Path.GetFileName(fullPath).ToLowerInvariant());
        if (ModuleDefinition.Resources.Any(x => x.Name == resourceName))
        {
            LogInfo(string.Format("\tSkipping '{0}' because it is already embedded", fullPath));
            return resourceName;
        }

        if (compress)
        {
            resourceName = String.Format("{0}{1}.zip", prefix, Path.GetFileName(fullPath).ToLowerInvariant());
        }

        LogInfo(string.Format("\tEmbedding '{0}'", fullPath));

        var checksum = CalculateChecksum(fullPath);
        var cacheFile = Path.Combine(cachePath, String.Format("{0}.{1}", checksum, resourceName));
        var memoryStream = new MemoryStream();

        if (File.Exists(cacheFile))
        {
            using (var fileStream = File.Open(cacheFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                fileStream.CopyTo(memoryStream);
            }
        }
        else
        {
            using (var cacheFileStream = File.Open(cacheFile, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
            {
                using (var fileStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    if (compress)
                    {
                        using (var compressedStream = new DeflateStream(memoryStream, CompressionMode.Compress, true))
                        {
                            fileStream.CopyTo(compressedStream);
                        }
                    }
                    else
                    {
                        fileStream.CopyTo(memoryStream);
                    }
                }
                memoryStream.Position = 0;
                memoryStream.CopyTo(cacheFileStream);
            }
        }
        memoryStream.Position = 0;
        streams.Add(memoryStream);
        var resource = new EmbeddedResource(resourceName, ManifestResourceAttributes.Private, memoryStream);
        ModuleDefinition.Resources.Add(resource);

        return resourceName;
    }
Ejemplo n.º 10
0
 public void RelativeBasedOnNamespace()
 {
     var expected = new EmbeddedResource("AssemblyName.Namespace1.ResourceName", ManifestResourceAttributes.Public, (Stream) null);
     var definition = ModuleDefinition.CreateModule("AssemblyName", ModuleKind.Dll);
     definition.Resources.Add(expected);
     var moduleWeaver = new ModuleWeaver
                        {
                            ModuleDefinition = definition
                        };
     var actual = moduleWeaver.FindResource("ResourceName", "AssemblyName.Namespace1", null, null);
     Assert.AreEqual(expected, actual);
 }
Ejemplo n.º 11
0
 public void RelativeBasedOnDirUpTwoLevelsMultipleNamespaces()
 {
     var expected = new EmbeddedResource("AssemblyName.ResourceName", ManifestResourceAttributes.Public, (Stream) null);
     var definition = ModuleDefinition.CreateModule("AssemblyName", ModuleKind.Dll);
     definition.Resources.Add(expected);
     var moduleWeaver = new ModuleWeaver
                        {
                            ModuleDefinition = definition
                        };
     var actual = moduleWeaver.FindResource(@"..\..\ResourceName", "BadPrefix", @"Namespace1\Namespace2", null);
     Assert.AreEqual(expected, actual);
 }
        static void Main(string[] args)
        {
            // TODO: Smarter handling of command line parameters if there ever are additional ones
            if (args.Length < 4 || args.Length == 5 || args.Length > 6)
            {
                Console.Error.WriteLine("Expected arguments: <Assembly-Path> <New-Assembly-Path> <Resource-Name> <Resource-Path> [-snk <Strong-Name-Key-Path>]");
                Environment.Exit(1);
            }
            else if (args.Length == 6 && args[4] != "-snk")
            {
                Console.Error.WriteLine("Available options are:");
                Console.Error.WriteLine("\t-snk: Path to strong name key file (.snk).");
                Environment.Exit(1);
            }

            var assemblyPath    = args[0];
            var newAssemblyPath = args[1];
            var resourceName    = args[2];
            var resourcePath    = args[3];
            var snkPath         = args.Length == 6 ? args[5] : null;

            var assemblyDef = AssemblyDefinition.ReadAssembly(assemblyPath);

            Console.WriteLine("Loaded assembly " + assemblyDef);

            // TODO: Support other modules than MainModule

            var resources = assemblyDef.MainModule.Resources;

            var selectedResource = resources.FirstOrDefault(x => x.Name == resourceName);

            if (selectedResource != null)
            {
                var newResource = new EmbeddedResource(resourceName, selectedResource.Attributes, File.ReadAllBytes(resourcePath));
                resources.Remove(selectedResource);
                resources.Add(newResource);
                if (snkPath == null)
                    assemblyDef.Write(newAssemblyPath);
                else
                {
                    Console.WriteLine("Using strong name key file " + snkPath);
                    assemblyDef.Write(newAssemblyPath, new WriterParameters() { StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(snkPath)) });
                }

                Console.WriteLine("Replaced embedded resource " + resourceName + " successfully!");
            }
            else
            {
                Console.Error.WriteLine("Could not find a resource with name " + resourceName);
                Console.Error.WriteLine("Available resources: " + String.Join(", ", resources.Select(x => x.Name).DefaultIfEmpty("<none>")));
            }
        }
Ejemplo n.º 13
0
        public byte[] removeDecryptedResource(EmbeddedResource resource)
        {
            if (resource == null)
                return null;

            var info = getEmbeddedAssemblyInfo(resource);
            if (info == null)
                return null;

            var data = decryptResource(info);
            if (!assemblyResolverInfo.EmbeddedAssemblyInfos.Remove(info))
                throw new ApplicationException(string.Format("Could not remove resource {0}", Utils.toCsharpString(info.resourceName)));
            return data;
        }
Ejemplo n.º 14
0
        public void initialize()
        {
            if (resolveHandler == null)
                return;

            if (isV3) {
                simpleDeobfuscator.deobfuscate(resolveHandler);
                simpleDeobfuscator.decryptStrings(resolveHandler, deob);
                resource = DeobUtils.getEmbeddedResourceFromCodeStrings(module, resolveHandler);
                if (resource == null) {
                    Log.w("Could not find resource of encrypted resources");
                    return;
                }
            }
        }
Ejemplo n.º 15
0
 byte[] decryptResource(EmbeddedResource resource)
 {
     using (var rsrcStream = resource.GetResourceStream()) {
         using (var reader = new BinaryReader(rsrcStream)) {
             var key = reader.ReadString();
             var data = reader.ReadBytes((int)(rsrcStream.Length - rsrcStream.Position));
             var cryptoTransform = new DESCryptoServiceProvider {
                 Key = Encoding.ASCII.GetBytes(key),
                 IV = Encoding.ASCII.GetBytes(key),
             }.CreateDecryptor();
             var memStream = new MemoryStream(data);
             using (var reader2 = new BinaryReader(new CryptoStream(memStream, cryptoTransform, CryptoStreamMode.Read))) {
                 return reader2.ReadBytes((int)memStream.Length);
             }
         }
     }
 }
        void Commit()
        {
            var n = _form.TreeViewHandler.SelectedNode;
            var r = (Resource)n.Tag;
            if (r is EmbeddedResource)
            {
                var er = (EmbeddedResource)r;
                var detailType = (SimpleAssemblyExplorer.ClassEditResourceHandler.DetailTypes)_form.DetailsTabPage.Tag;
                var data = Encoding.Unicode.GetBytes(_textbox.Text);

                if (detailType == ClassEditResourceHandler.DetailTypes.TextResource)
                {
                    var newEr = new EmbeddedResource(er.Name, er.Attributes, data);
                    var ad = _form.TreeViewHandler.GetCurrentAssembly();
                    ad.MainModule.Resources.Remove(er);
                    ad.MainModule.Resources.Add(newEr);
                    n.Tag = newEr;
                }
                else if (detailType == ClassEditResourceHandler.DetailTypes.ResourcesRowAsText)
                {
                    var row = _form.ResourceDataGrid.CurrentRow;
                    string key = _form.ResourceHandler.GetNameCellValue(row);
                    var newEr = _form.ResourceHandler.ReplaceResource(er, key, data);

                    var ad = _form.TreeViewHandler.GetCurrentAssembly();
                    ad.MainModule.Resources.Remove(er);
                    ad.MainModule.Resources.Add(newEr);
                    n.Tag = newEr;

                    var rowIndex = row.Index;
                    _form.ResourceHandler.InitResource(newEr);

                    row = _form.ResourceDataGrid.Rows[rowIndex];
                    _form.ResourceDataGrid.CurrentCell = row.Cells[0];
                    row.Selected = true;
                    _form.ResourceDataGrid.FirstDisplayedScrollingRowIndex = rowIndex > 10 ? rowIndex - 10 : 0;

                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            _form.SetStatusText("Changes committed.");
        }
Ejemplo n.º 17
0
        static int Main(string[] args)
        {
            string inputFile = null, outputFile = null;
            var opts = new OptionSet()
                           {
                               {"i|input=", "Input file",
                                   i => inputFile = i},
                               {"o|output=", "Output file",
                                   o => outputFile = o}
                           };
            var files = opts.Parse(args);
            if (string.IsNullOrWhiteSpace(inputFile))
            {
                Console.WriteLine("No assembly specified as embedding target.  Please use the -i option.");
                return -1;
            }
            if (outputFile == null)
            {
                Console.WriteLine("Overwriting target assembly {0}", inputFile);
                outputFile = inputFile;
            }
            if (files.Count <= 0)
            {
                Console.WriteLine("No input files specified");
                return -1;
            }

            Console.WriteLine("Reading {0}", inputFile);
            var module = ModuleDefinition.ReadModule(inputFile);
            foreach (var file in files)
            {
                Console.WriteLine("Embedding {0}", file);
                var bytes = File.ReadAllBytes(file);
                var resname = file.Replace("/", ".");
                var resource = new EmbeddedResource(resname, ManifestResourceAttributes.Public, bytes);
                module.Resources.Add(resource);
            }
            Console.WriteLine("Writing {0}", outputFile);
            module.Write(outputFile);
            return 0;
        }
Ejemplo n.º 18
0
		public ResourcesFileTreeNode(EmbeddedResource er)
			: base(er)
		{
			this.LazyLoading = true;
		}
        void CleanUp()
        {
            if (hexBox.ByteProvider != null)
            {
                IDisposable byteProvider = hexBox.ByteProvider as IDisposable;
                if (byteProvider != null)
                    byteProvider.Dispose();
                hexBox.ByteProvider = null;
            }

            _resource = null;
        }
        /// <summary>
        /// Bind a ressource.
        /// </summary>
        /// <param name="resource">resource to bind</param>
        public void Bind(EmbeddedResource resource)
        {
            CleanUp();
            
            if (resource != null)
            {
                IByteProvider provider = new DynamicByteProvider(resource.Data);
                provider.Changed += new EventHandler(byteProvider_Changed);
                provider.LengthChanged += new EventHandler(byteProvider_LengthChanged);

                hexBox.ByteProvider = provider;
                _resource = resource;
                hexBox.ReadOnly = false;
            } else
            {
                hexBox.ReadOnly = true;
            }

            UpdateSizeStatus();
            ManageAbility();
        }
Ejemplo n.º 21
0
        private void AddResource (EmbeddedResource resource)
        {
            if (embedded_resource_parser == null) {
                return;
            }

            if (Path.GetExtension (resource.Name) == ".resources") {
                using (var reader = new ResourceReader (resource.GetResourceStream ())) {
                    foreach (DictionaryEntry re in reader) {
                        if (embedded_resource_parser.SupportedFileExtensions.Contains (Path.GetExtension (re.Key as string))) {
                            embedded_resource_parser.Add (re.Value as Stream, re.Key as string);
                        }
                    }        
                }
            } else if (embedded_resource_parser.SupportedFileExtensions.Contains (Path.GetExtension(resource.Name))) {			
                embedded_resource_parser.Add (resource.GetResourceStream (), resource.Name);
            }
        }
Ejemplo n.º 22
0
		public override void VisitEmbeddedResource (EmbeddedResource res)
		{
			AddManifestResource (
				m_mdWriter.AddResource (res.Data),
				res.Name, res.Flags,
				new MetadataToken (TokenType.ManifestResource, 0));
		}
 public virtual void VisitEmbeddedResource(EmbeddedResource res)
 {
 }
Ejemplo n.º 24
0
        protected virtual void ExtractLocale(EmbeddedResource res, string outputPath, bool nodebug, StringBuilder bufferjs, StringBuilder bufferjsmin)
        {
            var fileName = res.Name.Substring(Translator.LocalesPrefix.Length);
            if (!string.IsNullOrWhiteSpace(this.AssemblyInfo.LocalesOutput))
            {
                outputPath = Path.Combine(outputPath, this.AssemblyInfo.LocalesOutput);
            }

            var file = CreateFileDirectory(outputPath, fileName);

            string resourcesStr = null;
            string resourcesStrMin = null;
            using (var resourcesStream = ((EmbeddedResource)res).GetResourceStream())
            {
                using (StreamReader reader = new StreamReader(resourcesStream))
                {
                    resourcesStr = reader.ReadToEnd();
                }
            }

            if (this.AssemblyInfo.OutputFormatting != JavaScriptOutputType.Formatted && !nodebug)
            {
                var minifier = new Minifier();
                resourcesStrMin = minifier.MinifyJavaScript(resourcesStr, new CodeSettings {TermSemicolons = true});
            }

            if (this.AssemblyInfo.CombineLocales)
            {
                if (this.AssemblyInfo.CombineScripts)
                {
                    if (this.AssemblyInfo.OutputFormatting != JavaScriptOutputType.Minified)
                    {
                        this.SaveToFile(file.FullName, resourcesStr);
                    }
                    if (resourcesStrMin != null)
                    {
                        this.SaveToFile(file.FullName.ReplaceLastInstanceOf(".js", ".min.js"), resourcesStrMin);
                    }
                }
                else
                {
                    if (this.AssemblyInfo.OutputFormatting != JavaScriptOutputType.Minified)
                    {
                        NewLine(bufferjs, resourcesStr);
                    }
                    if (resourcesStrMin != null)
                    {
                        bufferjsmin.Append(resourcesStrMin);
                    }
                }
            }
            else
            {
                if (this.AssemblyInfo.OutputFormatting != JavaScriptOutputType.Minified)
                {
                    File.WriteAllText(file.FullName, resourcesStr, OutputEncoding);
                }
                if (resourcesStrMin != null)
                {
                    File.WriteAllText(file.FullName.ReplaceLastInstanceOf(".js", ".min.js"), resourcesStrMin, OutputEncoding);
                }
            }
        }
Ejemplo n.º 25
0
        public void find()
        {
            var requiredTypes = new string[] {
                "System.Reflection.Assembly",
                "System.Object",
                "System.Int32",
                "System.String[]",
            };
            foreach (var type in module.Types) {
                if (type.HasEvents)
                    continue;
                if (!new FieldTypes(type).exactly(requiredTypes))
                    continue;

                MethodDefinition regMethod, handler;
                if (!BabelUtils.findRegisterMethod(type, out regMethod, out handler))
                    continue;

                var resource = BabelUtils.findEmbeddedResource(module, type);
                if (resource == null)
                    continue;

                resolverType = type;
                registerMethod = regMethod;
                encryptedResource = resource;
                return;
            }
        }
Ejemplo n.º 26
0
 public EmbeddedResource mergeResources()
 {
     if (encryptedResource == null)
         return null;
     DeobUtils.decryptAndAddResources(module, encryptedResource.Name, () => decryptResourceAssembly());
     var result = encryptedResource;
     encryptedResource = null;
     return result;
 }
Ejemplo n.º 27
0
        public bool init(IDeobfuscator deob, ISimpleDeobfuscator simpleDeobfuscator)
        {
            var cctor = DotNetUtils.getMethod(stringsEncodingClass, ".cctor");
            if (cctor == null)
                throw new ApplicationException("Could not find .cctor");
            simpleDeobfuscator.deobfuscate(cctor);

            stringsResource = findStringResource(cctor);
            if (stringsResource == null) {
                simpleDeobfuscator.decryptStrings(cctor, deob);
                stringsResource = findStringResource(cctor);
                if (stringsResource == null)
                    return false;
            }

            var offsetVal = findOffsetValue(cctor);
            if (offsetVal == null)
                throw new ApplicationException("Could not find string offset");
            stringOffset = offsetVal.Value;

            if (!findDecrypterMethod())
                throw new ApplicationException("Could not find string decrypter method");

            simpleZipType = findSimpleZipType(cctor);
            if (simpleZipType != null)
                resourceDecrypter = new ResourceDecrypter(new ResourceDecrypterInfo(module, simpleZipType, simpleDeobfuscator));

            return true;
        }
Ejemplo n.º 28
0
 void dumpEmbeddedFile(EmbeddedResource resource, string assemblyName, string extension, string reason)
 {
     DeobfuscatedFile.createAssemblyFile(resourceDecrypter.decrypt(resource.GetResourceStream()), Utils.getAssemblySimpleName(assemblyName), extension);
     addResourceToBeRemoved(resource, reason);
 }
Ejemplo n.º 29
0
        protected virtual void InjectResources(Dictionary<string, string> files)
        {
            if (files == null || files.Count == 0)
            {
                return;
            }

            var assemblyDef = this.AssemblyDefinition;
            var resources = assemblyDef.MainModule.Resources;
            var resourcesList = new List<string>();

            foreach (var file in files)
            {
                var name = file.Key;
                name = this.NormalizePath(name);
                var newResource = new EmbeddedResource(name, ManifestResourceAttributes.Public, File.ReadAllBytes(file.Value));
                resources.Add(newResource);
                resourcesList.Add(file.Key + ":" + name);
            }

            StringBuilder sb = new StringBuilder();
            foreach (var res in resourcesList)
            {
                sb.Append(res).Append("+");
            }
            sb.Remove(sb.Length - 1, 1);

            var listResources = new EmbeddedResource(Translator.BridgeResourcesList, ManifestResourceAttributes.Public, OutputEncoding.GetBytes(sb.ToString()));
            resources.Add(listResources);

            assemblyDef.Write(this.AssemblyLocation);
        }
Ejemplo n.º 30
0
 public AssemblyInfo(string assemblyName, EmbeddedResource resource, EmbeddedResource symbolsResource)
 {
     this.assemblyName = assemblyName;
     this.resource = resource;
     this.symbolsResource = symbolsResource;
 }
Ejemplo n.º 31
0
        private static void EmbedInAssembly(string dllName)
        {
            var readerParameters = new ReaderParameters { ReadSymbols = true };
            var assemblyDefinition = AssemblyDefinition.ReadAssembly(dllName, readerParameters);
            var newFilename = Path.ChangeExtension(dllName, "cdfy");
            var resourceName = Path.GetFileName(newFilename);
            var filestream = new FileStream(newFilename, FileMode.Open);

            var existingResource = assemblyDefinition.MainModule.Resources.Where(res => res.Name == resourceName).FirstOrDefault();
            if (existingResource != null)
                assemblyDefinition.MainModule.Resources.Remove(existingResource);

            EmbeddedResource erTemp = new EmbeddedResource(resourceName, ManifestResourceAttributes.Public, filestream);
            assemblyDefinition.MainModule.Resources.Add(erTemp);
            WriterParameters wp = new WriterParameters()
            {
                WriteSymbols = true
            };
            assemblyDefinition.Write(dllName, wp);
        }