Ejemplo n.º 1
0
 public AssemblyRef FindAssemblyRef(TypeRef nonNestedTypeRef)
 {
     return(assemblyDef.ToAssemblyRef());
 }
        public override bool Execute()
        {
            if (string.IsNullOrWhiteSpace(DestinationDirectory))
            {
                Log.LogMessageFromText(nameof(DestinationDirectory) + " is an empty string", MessageImportance.High);
                return(false);
            }

            using (var assemblyFactory = new AssemblyFactory(ReferencePath.Select(a => a.ItemSpec))) {
                AssemblyRef netstandardAsmRef = null;
                AssemblyDef netstandardAsm    = null;
                var         typeComparer      = new TypeEqualityComparer(SigComparerOptions.DontCompareTypeScope);
                var         netstandardTypes  = new HashSet <IType>(typeComparer);
                OutputReferencePath = new ITaskItem[ReferencePath.Length];
                for (int i = 0; i < ReferencePath.Length; i++)
                {
                    var file = ReferencePath[i];
                    OutputReferencePath[i] = file;
                    var filename      = file.ItemSpec;
                    var fileExt       = Path.GetExtension(filename);
                    var asmSimpleName = Path.GetFileNameWithoutExtension(filename);
                    if (!ShouldPatchAssembly(asmSimpleName))
                    {
                        continue;
                    }
                    if (!File.Exists(filename))
                    {
                        Log.LogMessageFromText($"File does not exist: {filename}", MessageImportance.High);
                        return(false);
                    }

                    var patchDir = DestinationDirectory;
                    Directory.CreateDirectory(patchDir);

                    var  fileInfo  = new FileInfo(filename);
                    long filesize  = fileInfo.Length;
                    long writeTime = fileInfo.LastWriteTimeUtc.ToBinary();

                    var extraInfo       = $"_{VERSION} {filesize} {writeTime}_";
                    var patchedFilename = Path.Combine(patchDir, asmSimpleName + extraInfo + fileExt);
                    if (StringComparer.OrdinalIgnoreCase.Equals(patchedFilename, filename))
                    {
                        continue;
                    }

                    if (!File.Exists(patchedFilename))
                    {
                        var asm = assemblyFactory.Resolve(asmSimpleName);
                        if (asm == null)
                        {
                            throw new Exception($"Couldn't resolve assembly {filename}");
                        }
                        var mod = (ModuleDefMD)asm.ManifestModule;
                        if (!ShouldPatchAssembly(mod))
                        {
                            continue;
                        }

                        if (netstandardAsm == null)
                        {
                            netstandardAsm = assemblyFactory.Resolve("netstandard");
                            if (netstandardAsm == null)
                            {
                                throw new Exception("Couldn't find a netstandard file");
                            }
                            netstandardAsmRef = netstandardAsm.ToAssemblyRef();
                            foreach (var type in netstandardAsm.ManifestModule.GetTypes())
                            {
                                if (type.IsGlobalModuleType)
                                {
                                    continue;
                                }
                                if (IsPublic(type))
                                {
                                    netstandardTypes.Add(type);
                                }
                            }
                            foreach (var type in netstandardAsm.ManifestModule.ExportedTypes)
                            {
                                netstandardTypes.Add(type);
                            }
                        }

                        for (uint rid = 1; ; rid++)
                        {
                            var tr = mod.ResolveTypeRef(rid);
                            if (tr == null)
                            {
                                break;
                            }
                            if (!netstandardTypes.Contains(tr))
                            {
                                continue;
                            }
                            if (tr.ResolutionScope is AssemblyRef asmRef && CanReplaceAssemblyRef(asmRef))
                            {
                                tr.ResolutionScope = netstandardAsmRef;
                            }
                        }

                        var options = new ModuleWriterOptions(mod);
                        mod.Write(patchedFilename, options);

                        var xmlDocFile = Path.ChangeExtension(filename, "xml");
                        if (File.Exists(xmlDocFile))
                        {
                            var newXmlDocFile = Path.ChangeExtension(patchedFilename, "xml");
                            if (File.Exists(newXmlDocFile))
                            {
                                File.Delete(newXmlDocFile);
                            }
                            File.Copy(xmlDocFile, newXmlDocFile);
                        }
                    }

                    OutputReferencePath[i] = new TaskItem(patchedFilename);
                }

                return(true);
            }
        }
Ejemplo n.º 3
0
        public void OldEncryptSFX(string fileName, string message, string key)
        {
            var cube = new NBytzCube.NBCube();                         //Dummy to import assembly

            AssemblyDef cubeDll   = AssemblyDef.Load("NBytzCube.dll"); //Load powercrypt
            ModuleDef   nbCubeMod = cubeDll.Modules[0];

            nbCubeMod.Kind = ModuleKind.Console;             //convert to EXE
            //AssemblyDef dnlibDll = AssemblyDef.Load("dnlib.dll");
            //ModuleDef dnlibModule = dnlibDll.Modules[0];
            Importer importer = new Importer(nbCubeMod);


            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser(namespaceName, "Startup", nbCubeMod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            nbCubeMod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Int32, new SZArraySig(nbCubeMod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            nbCubeMod.EntryPoint = entryPoint;

            #region TypeRefs
            // Create a TypeRef to System.Console
            TypeRef consoleRef = new TypeRefUser(nbCubeMod, "System", "Console", nbCubeMod.CorLibTypes.AssemblyRef);
            // Create a method ref to 'System.Void System.Console::WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(nbCubeMod, "WriteLine",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String),
                                                        consoleRef);

            MemberRef consoleReadLine1 = new MemberRefUser(nbCubeMod, "ReadLine",
                                                           MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String),
                                                           consoleRef);

            AssemblyRef powerAESLibRef = cubeDll.ToAssemblyRef();

            TypeRef powerAESRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4", "PowerAES",
                                                  powerAESLibRef);

            ITypeDefOrRef byteArrayRef = importer.Import(typeof(System.Byte[]));

            MemberRef decryptRef = new MemberRefUser(nbCubeMod, "Decrypt",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String)
                                                     , powerAESRef);

            TypeRef byteConverterRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4.Utilities", "ByteConverter",
                                                       powerAESLibRef);

            MemberRef getBytesRef = new MemberRefUser(nbCubeMod, "GetBytes",
                                                      MethodSig.CreateStatic(byteArrayRef.ToTypeSig(), nbCubeMod.CorLibTypes.String)
                                                      , byteConverterRef);

            TypeRef nbCubeRef = new TypeRefUser(nbCubeMod, "NBytzCube", "NBCube",
                                                powerAESLibRef);

            MemberRef launchAsmRef = new MemberRefUser(nbCubeMod, "LaunchAssembly",
                                                       MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, byteArrayRef.ToTypeSig())
                                                       , nbCubeRef);

            TypeRef fileRef = new TypeRefUser(nbCubeMod, "System.IO", "File",
                                              nbCubeMod.CorLibTypes.AssemblyRef);

            MemberRef writeBytesRef = new MemberRefUser(nbCubeMod, "WriteAllBytes",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String, byteArrayRef.ToTypeSig()),
                                                        fileRef);
            #endregion

            // Add a CIL method body to the entry point method
            CilBody epBody = new CilBody();
            entryPoint.Body = epBody;
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("NetBytz Encrypted SFX - (c) 2016 0xFireball\nEnter key: "));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(PowerAES.Encrypt(message, key))); //push encrypted text
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleReadLine1));                //push key from user
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(decryptRef));                      //decrypt
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(getBytesRef));                     //getbytes
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(launchAsmRef));                    //Launch assembly from bytes (managed code)
            epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());                            //push 0
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());                                 //Return/End
            // Save the assembly to a file on disk
            nbCubeMod.Write(fileName);
        }
Ejemplo n.º 4
0
        public static MemoryStream CreateSFXModuleEx(Dictionary <ModuleDefMD, string> inputModules, string mainExecutableModuleFN = null)
        {
            var         cube    = new NBytzCube.NBCube();            //Dummy to import assembl
            AssemblyDef cubeDll = AssemblyDef.Load("NBytzCube.dll"); //Load NBCube

            cubeDll.Name = "NBytzHypercube";
            ModuleDef nbCubeMod = cubeDll.Modules[0];

            nbCubeMod.Name = "NBytzProtector.Core";
            nbCubeMod.Kind = ModuleKind.Console; //convert to EXE
            Importer    importer = new Importer(nbCubeMod);
            string      mainExe;
            ModuleDefMD mainModule;

            if (mainExecutableModuleFN == null)
            {
                IEnumerable <ModuleDefMD> __mainModule = inputModules.Keys.Where(mod => mod.Kind == ModuleKind.Console || mod.Kind == ModuleKind.Windows);
                if (__mainModule.Count() != 1)
                {
                    throw new InvalidAssemblySetException("Invalid number of executable modules! Specify a main module if there are multiple executables.");
                }
                mainModule = __mainModule.ElementAt(0);
                mainExe    = inputModules[mainModule];
            }
            else
            {
                mainModule = ModuleDefMD.Load(mainExecutableModuleFN);
                mainExe    = mainExecutableModuleFN;
            }
            nbCubeMod.Kind = mainModule.Kind;
            string moduleContents = "";

            moduleContents += SquashFile(mainExe); //add exe module first
            inputModules.Remove(mainModule);
            foreach (string fileName in inputModules.Values)
            {
                moduleContents += "_" + SquashFile(fileName); //add module to mess
            }
            moduleContents = CompressString(moduleContents);  //compress
            GC.Collect();
            GC.WaitForPendingFinalizers();                    //Clean up the massive memory usage

            #region Create EntryPoint
            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser(namespaceName, "Startup", nbCubeMod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            nbCubeMod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Int32, new SZArraySig(nbCubeMod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            nbCubeMod.EntryPoint = entryPoint;
            #endregion

            #region TypeRefs
            // Create a TypeRef to System.Console
            TypeRef consoleRef = new TypeRefUser(nbCubeMod, "System", "Console", nbCubeMod.CorLibTypes.AssemblyRef);
            // Create a method ref to 'System.Void System.Console::WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(nbCubeMod, "WriteLine",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String),
                                                        consoleRef);

            MemberRef consoleReadLine1 = new MemberRefUser(nbCubeMod, "ReadLine",
                                                           MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String),
                                                           consoleRef);

            AssemblyRef powerAESLibRef = cubeDll.ToAssemblyRef();

            TypeRef powerAESRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4", "PowerAES",
                                                  powerAESLibRef);

            ITypeDefOrRef byteArrayRef = importer.Import(typeof(System.Byte[]));

            MemberRef decryptRef = new MemberRefUser(nbCubeMod, "Decrypt",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String)
                                                     , powerAESRef);

            TypeRef byteConverterRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4.Utilities", "ByteConverter",
                                                       powerAESLibRef);

            MemberRef getBytesRef = new MemberRefUser(nbCubeMod, "GetBytes",
                                                      MethodSig.CreateStatic(byteArrayRef.ToTypeSig(), nbCubeMod.CorLibTypes.String)
                                                      , byteConverterRef);

            TypeRef nbCubeRef = new TypeRefUser(nbCubeMod, "NBytzCube", "NBCube",
                                                powerAESLibRef);

            MemberRef extractAndLaunchAsmRef = new MemberRefUser(nbCubeMod, "ExtractUnpackAndLaunchAssembly",
                                                                 MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String)
                                                                 , nbCubeRef);

            TypeRef fileRef = new TypeRefUser(nbCubeMod, "System.IO", "File",
                                              nbCubeMod.CorLibTypes.AssemblyRef);

            MemberRef writeBytesRef = new MemberRefUser(nbCubeMod, "WriteAllBytes",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String, byteArrayRef.ToTypeSig()),
                                                        fileRef);
            #endregion

            // Add a CIL method body to the entry point method
            CilBody epBody = new CilBody();
            entryPoint.Body = epBody;
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("NetBytz Encrypted SFX - (c) 2016 0xFireball"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(moduleContents));        //push encrypted text
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(extractAndLaunchAsmRef)); //Helper Method Launch assembly
            epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());                   //push 0
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());                        //Return/End
                                                                                         //write to stream
            var ms = new MemoryStream();
            nbCubeMod.Write(ms);
            return(ms);
        }
Ejemplo n.º 5
0
 public AssemblyRef FindAssemblyRef(TypeRef nonNestedTypeRef) => assemblyDef.ToAssemblyRef();