Inheritance: MonoBehaviour
Example #1
0
        public static void InjectDll()
        {
            Obfuscator obf = Obfuscator.Unknown;

            Console.WriteLine("Path: ");
            string      Path   = Console.ReadLine().Replace("\"", "");
            ModuleDefMD Module = ModuleDefMD.Load(Path);

            Console.Clear();
            Console.WriteLine("AutoDetect Obfuscator/VM (y/n): ");
            string choice = Console.ReadLine();

            Console.Clear();
            Injector inj = new Injector(Module, Path);
            bool     injected;

            if (choice.ToLower() == "y")
            {
                injected = inj.Inject(true);
            }
            else
            {
                injected = inj.Inject(false);
            }
            if (injected)
            {
                Console.WriteLine("Successfully Injected And Saved File!");
            }
            else
            {
                Console.WriteLine("Failed Injecting File.");
            }
            Console.ReadLine();
        }
Example #2
0
    //read messages from the server
    private void OnIncomingData(string data)
    {
        string[] aData = Obfuscator.DeObfuscate(data).Split('|');
        Debug.Log("Server Says: " + Obfuscator.DeObfuscate(data));
        switch (aData[0])
        {
        case "sWHO":
            for (int i = 1; i < aData.Length - 1; i++)
            {
                UserConnected(aData[i], false);
            }
            Send("cWHO|" + clientName + '|' + ((isHost)?1:0).ToString());
            break;

        case "sCNN":
            UserConnected(aData[1], false);
            break;

        case "sSEL":
            NumSelect.Instance.opponentNum = Int32.Parse(aData[1]);
            break;

        default:
            break;
        }
    }
Example #3
0
 public SleuthNode(string input, Obfuscator obfuscator)
     : this(input)
 {
     this.obfuscator   = obfuscator;
     this.output       = this.obfuscator.unobfuscate(this.input);
     this.currentState = this.output;
 }
Example #4
0
        public void Test()
        {
            void TestOK(string name, PropertyAttributes attributes)
            {
                PropertyDefinition definition = new PropertyDefinition(name, attributes, new TypeReference(string.Empty, string.Empty, null, null));

                string message = this.GetAssertMessage("TestProperty", "TestOK()", name, attributes.ToString(), true, false);

                Assert.True(Obfuscator.IsPropertyObfuscatable(definition), message);
            }

            void TestFAIL(string name, PropertyAttributes attributes)
            {
                PropertyDefinition definition = new PropertyDefinition(name, attributes, new TypeReference(string.Empty, string.Empty, null, null));

                string message = this.GetAssertMessage("TestProperty", "TestFAIL()", name, attributes.ToString(), false, true);

                Assert.False(Obfuscator.IsPropertyObfuscatable(definition), message);
            }

            TestFAIL("test", PropertyAttributes.SpecialName);
            TestFAIL("test", PropertyAttributes.RTSpecialName);

            TestOK("Test", PropertyAttributes.HasDefault);
            TestOK("Test", PropertyAttributes.None);
            TestOK("Test", PropertyAttributes.Unused);
        }
        public void CheckSkipAllEnums()
        {
            string xml = String.Format(
                @"<?xml version='1.0'?>" +
                @"<Obfuscator>" +
                @"<Var name='InPath' value='{0}' />" +
                @"<Var name='OutPath' value='{1}' />" +
                @"<Var name='KeepPublicApi' value='false' />" +
                @"<Var name='HidePrivateApi' value='true' />" +
                @"<Module file='$(InPath){2}AssemblyWithTypes.dll'>" +
                @"<SkipEnums value='true' />" +
                @"</Module>" +
                @"</Obfuscator>", TestHelper.InputPath, TestHelper.OutputPath, Path.DirectorySeparatorChar);

            Obfuscator obfuscator = TestHelper.BuildAndObfuscate("AssemblyWithTypes", string.Empty, xml);
            var        map        = obfuscator.Mapping;

            string assmName = "AssemblyWithTypes.dll";

            var inAssmDef = AssemblyDefinition.ReadAssembly(Path.Combine(TestHelper.InputPath, assmName));

            var enumType = inAssmDef.MainModule.GetType("TestClasses.TestEnum");
            var enum1    = map.GetClass(new TypeKey(enumType));

            Assert.True(enum1.Status == ObfuscationStatus.Skipped, "Internal enum is obfuscated");
        }
Example #6
0
        static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                ShowHelp();
                return(1);
            }

            int start = Environment.TickCount;

            try
            {
                Console.Write("Loading project...");
                Obfuscator obfuscator = new Obfuscator(args[0]);
                Console.WriteLine("Done.");

                obfuscator.RunRules();

                Console.WriteLine("Completed, {0:f2} secs.", (Environment.TickCount - start) / 1000.0);
            }
            catch (ApplicationException e)
            {
                Console.WriteLine();
                Console.Error.WriteLine("An error occurred during processing:");
                Console.Error.WriteLine(e.Message);
                if (e.InnerException != null)
                {
                    Console.Error.WriteLine(e.InnerException.Message);
                }
                return(1);
            }

            return(0);
        }
Example #7
0
        private void Obfuscate(Error error)
        {
            error.User = string.Empty;
            if (error.Form != null)
            {
                error.Form.Clear();
            }

            //ServerVariables overrides requiring context from the http request should be handled in NuGetGallery.QuietLog
            var elmahException = error.Exception as ElmahException;

            if (elmahException != null)
            {
                var piiServerVaribles = elmahException.ServerVariables;
                foreach (var key in piiServerVaribles.Keys)
                {
                    error.ServerVariables[key] = piiServerVaribles[key];
                }
            }

            error.ServerVariables["AUTH_USER"]   = string.Empty;
            error.ServerVariables["LOGON_USER"]  = string.Empty;
            error.ServerVariables["REMOTE_USER"] = string.Empty;

            error.ServerVariables["REMOTE_ADDR"] = Obfuscator.ObfuscateIp(error.ServerVariables["REMOTE_ADDR"]);
            error.ServerVariables["REMOTE_HOST"] = Obfuscator.ObfuscateIp(error.ServerVariables["REMOTE_HOST"]);
            error.ServerVariables["LOCAL_ADDR"]  = Obfuscator.ObfuscateIp(error.ServerVariables["LOCAL_ADDR"]);
        }
Example #8
0
        internal static void ReadIncludeTag(XmlReader parentReader, Project project, Action <XmlReader, Project> readAction)
        {
            if (parentReader == null)
            {
                throw new ArgumentNullException("parentReader");
            }

            if (readAction == null)
            {
                throw new ArgumentNullException("readAction");
            }

            string            path = Environment.ExpandEnvironmentVariables(project.vars.Replace(Helper.GetAttribute(parentReader, "path")));
            XmlReaderSettings includeReaderSettings = Obfuscator.GetReaderSettings();

            using (XmlReader includeReader = XmlReader.Create(File.OpenRead(path), includeReaderSettings))
            {
                // Start reading
                includeReader.Read();

                // Skip declaration, if present
                if (includeReader.NodeType == XmlNodeType.XmlDeclaration)
                {
                    includeReader.Read();
                }

                Debug.Assert(includeReader.NodeType == XmlNodeType.Element && includeReader.Name == "Include");

                readAction(includeReader, project);
            }
        }
        public void HappyPath()
        {
            FileIdentifier identifier = FileIdentifier.Decloak(Obfuscator.Cloak("myPath::myHash"));

            Assert.Equal("myPath", identifier.Path);
            Assert.Equal("myHash", identifier.Hash);
        }
Example #10
0
        public void Test()
        {
            void TestOK(string name, FieldAttributes attributes)
            {
                FieldDefinition definition = new FieldDefinition(name, attributes, new TypeReference(string.Empty, string.Empty, null, null));

                string message = this.GetAssertMessage("TestField", "TestOK()", name, attributes.ToString(), true, false);

                Assert.True(Obfuscator.IsFieldObfuscatable(definition), message);
            }

            void TestFAIL(string name, FieldAttributes attributes)
            {
                FieldDefinition definition = new FieldDefinition(name, attributes, new TypeReference(string.Empty, string.Empty, null, null));

                string message = this.GetAssertMessage("TestField", "TestFAIL()", name, attributes.ToString(), false, true);

                Assert.False(Obfuscator.IsFieldObfuscatable(definition), message);
            }

            TestFAIL("<Test>", FieldAttributes.Public);
            TestFAIL("<Test>", FieldAttributes.SpecialName);
            TestFAIL("Test", FieldAttributes.SpecialName);
            TestFAIL("Test", FieldAttributes.RTSpecialName);

            TestOK("Test", FieldAttributes.Public);
        }
Example #11
0
        private static int Main(string[] args)
        {
            if (args.Length < 1) {
                ShowHelp ();
                return 1;
            }

            int start = Environment.TickCount;

            try {
                Console.Write ("Loading project...");
                Obfuscator obfuscator = new Obfuscator (args [0]);
                Console.WriteLine ("Done.");

                obfuscator.RunRules ();

                Console.WriteLine ("Completed, {0:f2} secs.", (Environment.TickCount - start) / 1000.0);
            } catch (ApplicationException e) {
                Console.WriteLine ();
                Console.Error.WriteLine ("An error occurred during processing:");
                Console.Error.WriteLine (e.Message);
                if (e.InnerException != null)
                    Console.Error.WriteLine (e.InnerException.Message);
                return 1;
            }

            return 0;
        }
        public static Action <T, TMember> CreateSetter <T, TMember>(this Expression <Func <T, TMember> > expression)
        {
            Debug.Assert(expression.Body is MemberExpression, "Expression is not property or field selector");
            Debug.Assert(((MemberExpression)expression.Body).Member is PropertyInfo || ((MemberExpression)expression.Body).Member is FieldInfo, "Expression is not property or field selector");
            Debug.Assert(Obfuscator.CheckAttribute(((MemberExpression)expression.Body).Member), "Missing obfuscation attribute: [Obfuscation(Feature = Obfuscator.NoRename, Exclude = true)]");

            var member = (MemberExpression)expression.Body;

            if (member.Member is PropertyInfo)
            {
                ParameterExpression paramExpression          = Expression.Parameter(typeof(T));
                ParameterExpression paramExpression2         = Expression.Parameter(typeof(TMember));
                MemberExpression    propertyGetterExpression = Expression.Property(paramExpression, (PropertyInfo)member.Member);
                return(Expression.Lambda <Action <T, TMember> >(Expression.Assign(propertyGetterExpression, paramExpression2), paramExpression, paramExpression2).Compile());
            }
            else
            {
                var info = (FieldInfo)member.Member;
                ParameterExpression objParm    = Expression.Parameter(info.DeclaringType, "obj");
                ParameterExpression valueParm  = Expression.Parameter(info.FieldType, "value");
                MemberExpression    memberExpr = Expression.Field(objParm, info.Name);
                Expression          assignExpr = Expression.Assign(memberExpr, valueParm);
                return(Expression.Lambda <Action <T, TMember> >(assignExpr, objParm, valueParm).Compile());
            }
        }
Example #13
0
    //read from server
    private void OnIncomingData(ServerClient c, string data)
    {
        string[] aData = Obfuscator.DeObfuscate(data).Split('|');
        Debug.Log(c.clientName + " Says: " + Obfuscator.DeObfuscate(data));
        switch (aData[0])
        {
        case "cWHO":
            c.clientName = (aData[1] == "")? aData[1]:"client";
            c.isHost     = (aData[2] == "0")? false:true;
            if (c.isHost)
            {
                c.clientName = "host";
            }
            Broadcast("sCNN|" + c.clientName, clients);
            break;

        case "cSEL":
            Broadcast("sSEL|" + aData[1], clients[(c.isHost)?1:0]);
            break;

        case "cGAME":

            break;

        default:
            break;
        }
    }
Example #14
0
        public void Test()
        {
            void TestOK(string name, MethodAttributes attributes)
            {
                MethodDefinition definition = new MethodDefinition(name, attributes, new TypeReference(string.Empty, string.Empty, null, null));

                string message = this.GetAssertMessage("TestMethod", "TestOK()", name, attributes.ToString(), true, false);

                Assert.True(Obfuscator.IsMethodObfuscatable(definition), message);
            }

            void TestFAIL(string name, MethodAttributes attributes)
            {
                MethodDefinition definition = new MethodDefinition(name, attributes, new TypeReference(string.Empty, string.Empty, null, null));

                string message = this.GetAssertMessage("TestMethod", "TestFAIL()", name, attributes.ToString(), false, true);

                Assert.False(Obfuscator.IsMethodObfuscatable(definition), message);
            }

            TestFAIL("", MethodAttributes.Public);
            TestFAIL("Main", MethodAttributes.Public);
            TestFAIL("Main", MethodAttributes.SpecialName);
            TestFAIL("Main", MethodAttributes.RTSpecialName);
            TestFAIL("<Test>", MethodAttributes.Public);
            TestFAIL("<Test>", MethodAttributes.Abstract);
            TestFAIL("Test", MethodAttributes.Abstract);
            TestFAIL("Test", MethodAttributes.Virtual);

            TestOK("Test", MethodAttributes.Private);
            TestOK("Test", MethodAttributes.Static);
            TestOK("Test", MethodAttributes.Public);
        }
Example #15
0
        public void CheckInterfaces()
        {
            Obfuscator     item = BuildAndObfuscateAssemblies("AssemblyWithInterfaces");
            ObfuscationMap map  = item.Mapping;

            string assmName = "AssemblyWithInterfaces.dll";

            AssemblyDefinition inAssmDef = AssemblyDefinition.ReadAssembly(
                Path.Combine(TestHelper.InputPath, assmName));

            AssemblyDefinition outAssmDef = AssemblyDefinition.ReadAssembly(
                Path.Combine(item.Project.Settings.OutPath, assmName));
            {
                TypeDefinition     classCType = inAssmDef.MainModule.GetType("TestClasses.C");
                MethodDefinition   method     = FindMethodByName(classCType, "Method");
                PropertyDefinition property   = FindPropertyByName(classCType, "Property");

                ObfuscatedThing methodEntry   = map.GetMethod(new MethodKey(method));
                ObfuscatedThing propertyEntry = map.GetProperty(new PropertyKey(new TypeKey(classCType), property));

                Assert.True(methodEntry.Status == ObfuscationStatus.Skipped, "public interface method should not be obfuscated.");

                Assert.True(propertyEntry.Status == ObfuscationStatus.Skipped, "public interface property should not be obfuscated.");
            }
        }
Example #16
0
		private static int Main (string[] args)
		{
			Console.WriteLine ("Obfuscar is available at http://obfuscar.codeplex.com.");
			Console.WriteLine ("(C) 2007-2014, Ryan Williams and other contributors.");
			Console.WriteLine ();

			if (args.Length != 1) {
				ShowHelp ();
				return 1;
			}

			int start = Environment.TickCount;

			try {
				Console.Write ("Loading project...");
				Obfuscator obfuscator = new Obfuscator (args [0]);
				Console.WriteLine ("Done.");

				obfuscator.RunRules ();
				
				Console.WriteLine ("Completed, {0:f2} secs.", (Environment.TickCount - start) / 1000.0);
			} catch (ObfuscarException e) {
				Console.WriteLine ();
				Console.Error.WriteLine ("An error occurred during processing:");
				Console.Error.WriteLine (e.Message);
				if (e.InnerException != null)
					Console.Error.WriteLine (e.InnerException.Message);
				return 1;
			}

			return 0;
		}
Example #17
0
        private static int Main(string[] args)
        {
            Console.WriteLine("Obfuscar is available at http://obfuscar.codeplex.com.");
            Console.WriteLine("(C) 2007-2014, Ryan Williams and other contributors.");
            Console.WriteLine();

            if (args.Length != 1)
            {
                ShowHelp();
                return(1);
            }

            int start = Environment.TickCount;

            try {
                Console.Write("Loading project...");
                Obfuscator obfuscator = new Obfuscator(args [0]);
                Console.WriteLine("Done.");

                obfuscator.RunRules();

                Console.WriteLine("Completed, {0:f2} secs.", (Environment.TickCount - start) / 1000.0);
            } catch (ObfuscarException e) {
                Console.WriteLine();
                Console.Error.WriteLine("An error occurred during processing:");
                Console.Error.WriteLine(e.Message);
                if (e.InnerException != null)
                {
                    Console.Error.WriteLine(e.InnerException.Message);
                }
                return(1);
            }

            return(0);
        }
Example #18
0
        public void Test()
        {
            void TestOK(string @namespace, string name, TypeAttributes attributes)
            {
                TypeDefinition definition = new TypeDefinition(@namespace, name, attributes, new TypeReference(string.Empty, string.Empty, null, null));

                string message = this.GetAssertMessage("TestType", "TestOK()", name, attributes.ToString(), true, false);

                Assert.True(Obfuscator.IsTypeObfuscatable(definition), message);
            }

            void TestFAIL(string @namespace, string name, TypeAttributes attributes)
            {
                TypeDefinition definition = new TypeDefinition(@namespace, name, attributes, new TypeReference(string.Empty, string.Empty, null, null));

                string message = this.GetAssertMessage("TestType", "TestFAIL()", name, attributes.ToString(), false, true);

                Assert.False(Obfuscator.IsTypeObfuscatable(definition), message);
            }

            TestFAIL("x", "<Module>", TypeAttributes.Public);
            TestFAIL("x", "Resources", TypeAttributes.Public);
            TestFAIL("x", "", TypeAttributes.Public);
            TestFAIL("x", "___TEST__", TypeAttributes.Public);
            TestFAIL("x", "<Test>", TypeAttributes.Public);
            TestFAIL("x", "Test", TypeAttributes.SpecialName);
            TestFAIL("x", "Test", TypeAttributes.RTSpecialName);

            TestOK("x", "Test", TypeAttributes.Public);
            TestOK("x", "_Test_", TypeAttributes.Public);
        }
        public void CheckGenericMethodRenaming()
        {
            string xml = String.Format(
                @"<?xml version='1.0'?>" +
                @"<Obfuscator>" +
                @"<Var name='InPath' value='{0}' />" +
                @"<Var name='OutPath' value='{1}' />" +
                @"<Var name='KeepPublicApi' value='false' />" +
                @"<Var name='HidePrivateApi' value='true' />" +
                @"<Module file='$(InPath){2}AssemblyWithGenericOverrides.dll' />" +
                @"<Module file='$(InPath){2}AssemblyWithGenericOverrides2.dll'>" +
                @"<SkipNamespace name='*' />" +
                @"</Module>" +
                @"</Obfuscator>", TestHelper.InputPath, TestHelper.OutputPath, Path.DirectorySeparatorChar);

            Obfuscator obfuscator = TestHelper.BuildAndObfuscate(new[] { "AssemblyWithGenericOverrides", "AssemblyWithGenericOverrides2" }, xml);

            var assembly2Path = Path.Combine(Directory.GetCurrentDirectory(), TestHelper.OutputPath, "AssemblyWithGenericOverrides2.dll");
            var assembly2     = Assembly.LoadFile(assembly2Path);
            var type          = assembly2.GetType("TestClasses.Test");
            var ctor          = type.GetConstructor(new Type[0]);
            var instance      = ctor.Invoke(new object[0]);

            try {
                AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
                Assert.True(instance.ToString() == "Empty<string, string>=A<B<String, String>>",
                            "Generic override should have been updated");
            }
            finally {
                AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolve;
            }
        }
Example #20
0
        private static void ObfuscateWhileLocked()
        {
            if (_options == null)
            {
                _options = OptionsManager.LoadOptions();
            }
            Obfuscator.FixHexBug(_options);

            if (ShouldObfuscate() == false)
            {
                return;
            }

            AssemblySelector selector = new AssemblySelector(_options);

            ICollection <string> compiledDlls = selector.GetCompiledAssemblyPaths();

            BackupDlls(compiledDlls);
            ICollection <string> dlls = selector.GetAssemblyPaths();

            if (dlls.Count == 0 && compiledDlls.Count == 0)
            {
                _noCSharpScripts = true;
            }
            else
            {
                HashSet <string> extraAssemblyReferenceDirectories = new HashSet <string>(_options.extraAssemblyDirectories);

#if UNITY_2017_3_OR_NEWER
                extraAssemblyReferenceDirectories.UnionWith(AssemblyReferenceLocator.GetAssemblyReferenceDirectories());
#endif

                Obfuscator.SetExtraAssemblyDirectories(extraAssemblyReferenceDirectories.ToArray());

#if UNITY_2018_2_OR_NEWER
                if (_options.obfuscateMonoBehaviourClassNames)
                {
                    Debug.LogError(
                        "The mechanism to obfuscate MonoBehaviour class names no longer works since Unity " +
                        "2018.2. You must either roll back to 2018.1, or disable this option.\n" +
                        "\nThis build will be obfuscated as instructed, but you are likely to see " +
                        "NullReferenceException runtime errors.\n");
                }
#endif

                Obfuscator.Obfuscate(dlls, compiledDlls, _options, EditorUserBuildSettings.activeBuildTarget);

                if (_options.obfuscateMonoBehaviourClassNames)
                {
                    /*
                     * RestoreAssets must be called via the update delegate because [PostProcessBuild] is not guaranteed to be called
                     */
                    EditorApplication.update         += RestoreAssets;
                    _monoBehaviourAssetsNeedReverting = true;
                }

                _obfuscatedAfterScene = true;
            }
        }
Example #21
0
 public static byte[] Data()
 {
     if (IsPopulated == false)
     {
         return(null);
     }
     return(Obfuscator.DeObfuscate(data, order, key));
 }
Example #22
0
        public static void Obfuscate()
        {
            if (!EditorApplication.isPlayingOrWillChangePlaymode && !obfuscatedAfterScene)
            {
                try
                {
                    EditorApplication.LockReloadAssemblies();

                    HashSet <string> dlls = new HashSet <string>();

                    foreach (string assemblyName in Config.permanentDLLs)
                    {
                        dlls.Add(FindDllLocation(assemblyName));
                    }
                    backupDlls(dlls);

                    foreach (string assemblyName in Config.temporaryDLLs)
                    {
                        dlls.Add(FindDllLocation(assemblyName));
                    }

                    if (dlls.Count == 0)
                    {
                        noCSharpScripts = true;
                    }
                    else
                    {
                        if (options == null)
                        {
                            options = OptionsManager.LoadOptions();
                        }

                        Obfuscator.FixHexBug(options);

                        if (options.enabled)
                        {
                            Obfuscator.SetExtraAssemblyDirectories(Config.extraAssemblyDirectories);
                            Obfuscator.Obfuscate(dlls, options, EditorUserBuildSettings.activeBuildTarget);

                            if (options.obfuscateMonoBehaviourClassNames)
                            {
                                /*
                                 * RestoreAssets must be called via the update delegate because [PostProcessBuild] is not guaranteed to be called
                                 */
                                EditorApplication.update        += RestoreAssets;
                                monoBehaviourAssetsNeedReverting = true;
                            }
                        }
                        obfuscatedAfterScene = true;
                    }
                }
                finally
                {
                    EditorApplication.UnlockReloadAssemblies();
                }
            }
        }
Example #23
0
        public void SanitizeLogLine(ref string line)
        {
            var    lineSegments = ExtensionsUtils.GetSegmentsFromCSV(line, _headerMetadata.Delimiter);
            string clientIp     = lineSegments[_headerValueIndex];

            lineSegments[_headerValueIndex] = Obfuscator.ObfuscateIp(clientIp);

            line = string.Join(new string(_headerMetadata.Delimiter, 1), lineSegments);
        }
Example #24
0
 //send messages to the server
 public void Send(string data)
 {
     if (!socketReady)
     {
         return;
     }
     writer.WriteLine(Obfuscator.Obfuscate(data));
     writer.Flush();
 }
Example #25
0
        private static void Clear()
        {
            obfuscatedAfterScene = false;
            noCSharpScripts      = false;

            if (options != null && options.obfuscateMonoBehaviourClassNames == false)
            {
                Obfuscator.Clear();
            }
        }
Example #26
0
        public void CheckGenericMethodRenaming()
        {
            string outputPath = TestHelper.OutputPath;
            string xml        = string.Format(
                @"<?xml version='1.0'?>" +
                @"<Obfuscator>" +
                @"<Var name='InPath' value='{0}' />" +
                @"<Var name='OutPath' value='{1}' />" +
                @"<Var name='KeepPublicApi' value='false' />" +
                @"<Var name='HidePrivateApi' value='true' />" +
                @"<Module file='$(InPath){2}AssemblyWithGenericOverrides.dll' />" +
                @"<Module file='$(InPath){2}AssemblyWithGenericOverrides2.dll'>" +
                @"<SkipNamespace name='*' />" +
                @"</Module>" +
                @"</Obfuscator>", TestHelper.InputPath, outputPath, Path.DirectorySeparatorChar);

            var        assmName   = "AssemblyWithGenericOverrides";
            Obfuscator obfuscator =
                TestHelper.BuildAndObfuscate(new[] { assmName, "AssemblyWithGenericOverrides2" },
                                             xml);
            var map = obfuscator.Mapping;

            AssemblyDefinition inAssmDef = AssemblyDefinition.ReadAssembly(
                Path.Combine(TestHelper.InputPath, $"{assmName}.dll"));
            TypeDefinition classAType    = inAssmDef.MainModule.GetType("TestClasses.Alpha`1");
            TypeDefinition classBType    = inAssmDef.MainModule.GetType("TestClasses.IBeta`2");
            var            classARenamed = map.GetClass(new TypeKey(classAType));
            var            classBRenamed = map.GetClass(new TypeKey(classBType));
            var            end           = assmName.Length + 2;

            Assert.True(classARenamed.Status == ObfuscationStatus.Renamed, "Type must be obfuscated");
            Assert.True(classBRenamed.Status == ObfuscationStatus.Renamed, "Interface must be obfuscated");
            var newNameA        = classARenamed.StatusText.Substring(end);
            var newNameB        = classBRenamed.StatusText.Substring(end);
            var formattedString = $"Empty<string, string>={newNameA}[{newNameB}[System.String,System.String]]";

            var assembly2Path = Path.Combine(Directory.GetCurrentDirectory(), outputPath,
                                             "AssemblyWithGenericOverrides2.dll");
            var assembly2 = Assembly.LoadFile(assembly2Path);
            var type      = assembly2.GetType("TestClasses.Test");
            var ctor      = type.GetConstructor(new Type[0]);
            var instance  = ctor.Invoke(new object[0]);

            try
            {
                output = outputPath;
                AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
                Assert.True(instance.ToString() == formattedString,
                            "Generic override should have been updated");
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolve;
            }
        }
Example #27
0
        public void CheckBadInPath()
        {
            string xml = String.Format(
                @"<?xml version='1.0'?>" +
                @"<Obfuscator>" +
                @"<Var name='InPath' value='{0}' />" +
                @"</Obfuscator>", BadPath);
            var exception = Assert.Throws <ObfuscarException>(() => { Obfuscator.CreateFromXml(xml); });

            Assert.AreEqual("Path specified by InPath variable must exist:Q:\\Does\\Not\\Exist", exception.Message);
        }
Example #28
0
        public void ObfuscateInteger_UnobfuscateGuid(int expected)
        {
            // Arrange
            Guid guid = Obfuscator.IntegerToGuid(expected);

            // Act
            int actual = Obfuscator.GuidToInteger(guid);

            // Assert
            Assert.Equal(expected, actual);
        }
Example #29
0
        public void CheckGoodDependency()
        {
            string xml = String.Format(
                @"<?xml version='1.0'?>" +
                @"<Obfuscator>" +
                @"<Var name='InPath' value='{0}' />" +
                @"<Module file='$(InPath){1}AssemblyB.dll' />" +
                @"</Obfuscator>", TestHelper.InputPath, Path.DirectorySeparatorChar);

            Obfuscator obfuscator = Obfuscator.CreateFromXml(xml);
        }
Example #30
0
        public void CheckBadModuleFile()
        {
            string xml = String.Format(
                @"<?xml version='1.0'?>" +
                @"<Obfuscator>" +
                @"<Module file='{0}\ObfuscarTests.dll' />" +
                @"</Obfuscator>", BadPath);
            var exception = Assert.Throws <ObfuscarException>(() => { Obfuscator.CreateFromXml(xml); });

            Assert.Equal("Unable to find assembly:  Q:\\Does\\Not\\Exist\\ObfuscarTests.dll", exception.Message);
        }
Example #31
0
 private byte[] GetDecryptedBytes()
 {
     if (settings.encryptionType == ES2Settings.EncryptionType.AES128)        // AES 128-bit encryption
     {
         AESEncryptor aesEncryptor = new AESEncryptor(settings.encryptionPassword, MoodkieSecurity.AESBits.BITS128);
         return(aesEncryptor.Decrypt(reader.ReadBytes(reader.ReadInt32())));
     }
     else         // XOR Obfuscation
     {
         return(Obfuscator.Obfuscate(reader.ReadBytes(reader.ReadInt32()), settings.encryptionPassword));
     }
 }
Example #32
0
 public byte[] GetEncryptedBytes(string password)
 {
     if (settings.encryptionType == ES2Settings.EncryptionType.AES128)        // AES 128-bit encryption
     {
         AESEncryptor aesEncryptor = new AESEncryptor(password, MoodkieSecurity.AESBits.BITS128);
         return(aesEncryptor.Encrypt((writer.BaseStream as MemoryStream).ToArray()));
     }
     else         // XOR Obfuscation
     {
         return(Obfuscator.Obfuscate((writer.BaseStream as MemoryStream).ToArray(), password));
     }
 }
Example #33
0
        static void Main(string[] args)
        {
            //<script>alert(String.fromCharCode('A'.charCodeAt(0) + 'B'.charCodeAt(0) - 'A'.charCodeAt(0)));</script>
            if (true)
            {
                string text = args.Length > 0 ? args[0] : "test";
                Obfuscator o = new Obfuscator();
                string res = o.Obfuscate(text, "7fkc83Rhjas61dfBc0xZgfspPs1nNf2EeЁйжпyyКйзЗХяЯбИпРдээвУЖ");
                Console.WriteLine(res);
            }
            string s = "" + (char)((((33 | 68) + (('W') - 0x59)) < (0x47 + ((0x49 + ((0x66 + (((char)0x5E) - 0x47)) - (35 | 35))) - 0x53)) ? ((32 | 66) + (('_') - 0x4D)) : (0x50 + (((44 | 44) + ((109 + (((char)0x4D) - 0x50)) - 83)) - 0x5C)))) + (char)(((0x59 + (93 + (('S') - 0x45))) < ((0x4D + (((49 | 50) + ((0x45 + ((84 + ((0x63 + ((92 + (('S') - 0x4B)) - 80)) - 0x49)) - (36 | 37))) - 0x59)) - 0x4C)) - 0x5A) ? (0x4A + ((95 + (('T') - 73)) - 84)) : (0x69 + (((char)78) - (27 | 55))))) + (char)((((0x74 + (((char)0x5B) - 72)) - 0x47) > (0x60 + ((0x63 + ((0x51 + (((33 | 66) + (((char)0x4C) - (26 | 52))) - (22 | 46))) - (28 | 58))) - 0x4F)) ? ((111 + ((107 + (('C') - 74)) - (26 | 53))) - (46 | 46)) : (0x5D + ((72 + ((91 + ((83 + ((68 + ((0x57 + ((0x61 + (((char)(25 | 50)) - (34 | 34))) - 0x5C)) - 0x46)) - 0x4D)) - 0x4B)) - (30 | 61))) - 0x4E)))) + (char)((((char)0x5B) < (98 + ((char)0x4D)) ? ((36 | 74) + (((char)0x5F) - 0x59)) : ((char)70)));

            //BinHelper bin = new BinHelper();
            //Console.WriteLine( BinHelper.int2bin(1027));
            //List<int> pos = BinHelper.findPos(3, 1027);
            //string a = BinHelper.MakeXfromY(22, 709);

            Console.ReadLine();
        }
Example #34
0
 private void button1_Click(object sender, EventArgs e)
 {
     Obfuscator o = new Obfuscator();
     textBox2.Text = o.Obfuscate(textBox1.Text, textBox3.Text);
 }
Example #35
0
	public static bool Obfuscate(string inPath, string resultPath, bool webPlayer=false) {
		var assemblies = new List<string>();

		var files = Directory.GetFiles(inPath, "*.dll", SearchOption.TopDirectoryOnly);

		foreach (var filePath in files) {
			foreach (var match in assemblyMatches) {
				var regex = new Regex(match, RegexOptions.IgnoreCase);

				if (regex.IsMatch(Path.GetFileName(filePath))) {
					assemblies.Add(filePath);
				}
			}
		}

		string outPath = FileUtil.GetUniqueTempPathInProject();
		Directory.CreateDirectory(outPath);

		// load xml rules
		var templatePath = Path.GetFullPath(Path.GetDirectoryName(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(ScriptableObject.CreateInstance<Obfuscarator>()))));
		templatePath = Path.Combine(templatePath, RULES_TEMPLATE);

		var xmlDoc = new XmlDocument();
		xmlDoc.Load(templatePath);

		var nodes = xmlDoc.GetElementsByTagName("Var");

		foreach (XmlNode node in nodes) {
			switch (node.Attributes["name"].Value) {
			case "InPath":
				node.Attributes["value"].Value = inPath;
				break;
			case "OutPath":
				node.Attributes["value"].Value = outPath;
				break;
			case "HideStrings":
				if (webPlayer) {
					// Hiding strings doesn't work with web player builds.
					node.Attributes["value"].Value = "false";
				}
				break;
			}
		}

		nodes = xmlDoc.GetElementsByTagName("Module");

		if (nodes.Count == 0) {
			Debug.LogError("no Module node");
		}

		XmlNode module = nodes[0];

		var root = nodes[0].ParentNode;
		root.RemoveChild(nodes[0]);

		foreach (var file in assemblies) {
			var newModule = module.Clone();
			newModule.Attributes["file"].Value = file;

			root.AppendChild(newModule);
		}

		var rulesPath = Path.Combine(outPath, "rules.xml");
		xmlDoc.Save(rulesPath);

		try {
			var obfuscator = new Obfuscator(rulesPath);
			obfuscator.Log += Debug.Log;
			obfuscator.RunRules();
		}
		catch (System.ApplicationException e) {
			Debug.LogError(e.Message);
			return false;
		}

		// copy obfuscated assemblies over originals.
		foreach (var file in assemblies) {
			var obfuscatedPath = Path.Combine(outPath, Path.GetFileName(file));

			File.Copy(obfuscatedPath, file, true);
		}

		File.Copy(Path.Combine(outPath, "Mapping.txt"), Path.Combine(resultPath, "Mapping.txt"), true);

		// cleanup
		DeleteTempFolder(outPath);
		return true;
	}
Example #36
0
        public static int Main( string[] args )
        {
            if ( args.Length < 1 )
            {
                ShowHelp( );
                return 1;
            }

            int start = Environment.TickCount;

            try
            {
                Console.Write( "Loading project (calling as EXE)..." );
                Obfuscator obfuscator = new Obfuscator( args[0] );
                Console.WriteLine( "Done." );

                Console.Write( "Renaming:  fields..." );
                obfuscator.RenameFields( );

                Console.Write( "parameters..." );
                obfuscator.RenameParams( );

                Console.Write( "properties..." );
                obfuscator.RenameProperties( );

                Console.Write( "events..." );
                obfuscator.RenameEvents( );

                Console.Write( "methods..." );
                obfuscator.RenameMethods( );

                Console.Write( "types..." );
                obfuscator.RenameTypes( );

                if (obfuscator.Project.Settings.HideStrings)
                {
                    Console.WriteLine("hiding strings...");
                    obfuscator.HideStrings();
                }

                Console.WriteLine( "Done." );

                Console.Write( "Saving assemblies..." );
                obfuscator.SaveAssemblies( );
                Console.WriteLine( "Done." );

                Console.Write( "Writing log file..." );
                obfuscator.SaveMapping( );
                Console.WriteLine( "Done." );

                Console.WriteLine( "Completed, {0:f2} secs.", ( Environment.TickCount - start ) / 1000.0 );
            }
            catch ( ApplicationException e )
            {
                Console.WriteLine( );
                Console.WriteLine( "An error occurred during processing:" );
                Console.WriteLine( e.Message );
                return 1;
            }
            catch(Exception e) {
                Console.WriteLine ();
                Console.WriteLine ("A fatal error occurred during processing:");
                Console.WriteLine (e.ToString ());
                return 1;
            }

            return 0;
        }
Example #37
0
		static int Main(string[] args)
		{
			if (args.Length < 1)
			{
				ShowHelp();
				return 1;
			}

			int start = Environment.TickCount;

			try
			{
				Console.Write("Loading project...");
				Obfuscator obfuscator = new Obfuscator(args[0]);
				Console.WriteLine("Done.");

				// The SemanticAttributes of MethodDefinitions have to be loaded before any fields,properties or events are removed
				obfuscator.LoadMethodSemantics();

				Console.Write("Renaming:  fields...");
				obfuscator.RenameFields();

				Console.Write("parameters...");
				obfuscator.RenameParams();

				Console.Write("properties...");
				obfuscator.RenameProperties();

				Console.Write("events...");
				obfuscator.RenameEvents();

				Console.Write("methods...");
				obfuscator.RenameMethods();

				Console.Write("types...");
				obfuscator.RenameTypes();

				if (obfuscator.Project.Settings.HideStrings)
				{
					Console.WriteLine("hiding strings...");
					obfuscator.HideStrings();
				}

				Console.WriteLine("Done.");

				Console.Write("Saving assemblies...");
				obfuscator.SaveAssemblies();
				Console.WriteLine("Done.");

				Console.Write("Writing log file...");
				obfuscator.SaveMapping();
				Console.WriteLine("Done.");

				Console.WriteLine("Completed, {0:f2} secs.", (Environment.TickCount - start) / 1000.0);
			}
			catch (ApplicationException e)
			{
				Console.WriteLine();
				Console.Error.WriteLine("An error occurred during processing:");
				Console.Error.WriteLine(e.Message);
				if (e.InnerException != null)
					Console.Error.WriteLine(e.InnerException.Message);
				return 1;
			}

			return 0;
		}