Example #1
0
		static Statement ReplaceVar(Statement st, Variable buff) {
			if (st is AssignmentStatement) {
				((AssignmentStatement)st).Value = ReplaceVar(((AssignmentStatement)st).Value, buff);
				((AssignmentStatement)st).Target = ReplaceVar(((AssignmentStatement)st).Target, buff);
			}
			return st;
		}
Example #2
0
		public CipherGenContext(RandomGenerator random, int dataVarCount) {
			this.random = random;
			Block = new StatementBlock(); // new LoopStatement() { Begin = 0, Limit = 4 };
			dataVars = new Variable[dataVarCount];
			for (int i = 0; i < dataVarCount; i++)
				dataVars[i] = new Variable("v" + i) { Tag = i };
		}
Example #3
0
			protected override Local Var(Variable var) {
				if (var.Name == "{BUFFER}")
					return block;
				if (var.Name == "{KEY}")
					return key;
				return base.Var(var);
			}
			protected override void LoadVar(Variable var) {
				if (var.Name == "{RESULT}") {
					foreach (Instruction instr in arg)
						Emit(instr);
				}
				else
					base.LoadVar(var);
			}
Example #5
0
		protected virtual Local Var(Variable var) {
			Local ret;
			if (!localMap.TryGetValue(var.Name, out ret)) {
				ret = new Local(Method.Module.CorLibTypes.UInt32);
				ret.Name = var.Name;
				localMap[var.Name] = ret;
			}
			return ret;
		}
Example #6
0
		public IDisposable AcquireTempVar(out VariableExpression exp) {
			Variable var;
			if (tempVars.Count == 0)
				var = new Variable("t" + tempVarCounter++);
			else {
				var = tempVars[random.NextInt32(tempVars.Count)];
				tempVars.Remove(var);
			}
			exp = new VariableExpression { Variable = var };
			return new TempVarHolder(this, var);
		}
		void Compile(RPContext ctx, CilBody body, out Func<int, int> expCompiled, out Expression inverse) {
			var var = new Variable("{VAR}");
			var result = new Variable("{RESULT}");

			Expression expression;
			ctx.DynCipher.GenerateExpressionPair(
				ctx.Random,
				new VariableExpression { Variable = var }, new VariableExpression { Variable = result },
				ctx.Depth, out expression, out inverse);

			expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
				.GenerateCIL(expression)
				.Compile<Func<int, int>>();
		}
		void Compile(CilBody body) {
			var var = new Variable("{VAR}");
			var result = new Variable("{RESULT}");

			ctx.DynCipher.GenerateExpressionPair(
				ctx.Random,
				new VariableExpression { Variable = var }, new VariableExpression { Variable = result },
				ctx.Depth, out expression, out inverse);

			expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
				.GenerateCIL(expression)
				.Compile<Func<int, int>>();

			invCompiled = new List<Instruction>();
			new CodeGen(stateVar, ctx, invCompiled).GenerateCIL(inverse);
			body.MaxStack += (ushort)ctx.Depth;
		}
Example #9
0
		static Expression ReplaceVar(Expression exp, Variable buff) {
			if (exp is VariableExpression) {
				if (((VariableExpression)exp).Variable.Name[0] != 'v') return exp;
				return new ArrayIndexExpression {
					Array = new VariableExpression { Variable = buff },
					Index = (int)(exp as VariableExpression).Variable.Tag
				};
			}
			if (exp is ArrayIndexExpression) {
				((ArrayIndexExpression)exp).Array = ReplaceVar(((ArrayIndexExpression)exp).Array, buff);
			}
			else if (exp is BinOpExpression) {
				((BinOpExpression)exp).Left = ReplaceVar(((BinOpExpression)exp).Left, buff);
				((BinOpExpression)exp).Right = ReplaceVar(((BinOpExpression)exp).Right, buff);
			}
			else if (exp is UnaryOpExpression) {
				((UnaryOpExpression)exp).Value = ReplaceVar(((UnaryOpExpression)exp).Value, buff);
			}
			return exp;
		}
Example #10
0
        private void Compile(RPContext ctx, out Func<int, int> expCompiled, out MethodDef native)
        {
            var var = new Variable("{VAR}");
            var result = new Variable("{RESULT}");

            CorLibTypeSig int32 = ctx.Module.CorLibTypes.Int32;
            native = new MethodDefUser(ctx.Context.Registry.GetService<INameService>().RandomName(), MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static);
            native.ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
            ctx.Module.GlobalType.Methods.Add(native);

            ctx.Context.Registry.GetService<IMarkerService>().Mark(native);
            ctx.Context.Registry.GetService<INameService>().SetCanRename(native, false);

            x86Register? reg;
            var codeGen = new x86CodeGen();
            Expression expression, inverse;
            do {
                ctx.DynCipher.GenerateExpressionPair(
                    ctx.Random,
                    new VariableExpression { Variable = var }, new VariableExpression { Variable = result },
                    ctx.Depth, out expression, out inverse);

                reg = codeGen.GenerateX86(inverse, (v, r) => { return new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }; });
            } while (reg == null);

            byte[] code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

            expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                .GenerateCIL(expression)
                .Compile<Func<int, int>>();

            nativeCodes.Add(Tuple.Create(native, code, (MethodBody)null));
            if (!addedHandler) {
                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
                addedHandler = true;
            }
        }
Example #11
0
			public void Compile(CFContext ctx) {
				var var = new Variable("{VAR}");
				var result = new Variable("{RESULT}");

				CorLibTypeSig int32 = ctx.Method.Module.CorLibTypes.Int32;
				native = new MethodDefUser(ctx.Context.Registry.GetService<INameService>().RandomName(), MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static);
				native.ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
				// Attempt to improve performance --- failed with StackOverflowException... :/
				//var suppressAttr = ctx.Method.Module.CorLibTypes.GetTypeRef("System.Security", "SuppressUnmanagedCodeSecurityAttribute").ResolveThrow();
				//native.CustomAttributes.Add(new CustomAttribute((MemberRef)ctx.Method.Module.Import(suppressAttr.FindDefaultConstructor())));
				//native.HasSecurity = true;
				ctx.Method.Module.GlobalType.Methods.Add(native);

				ctx.Context.Registry.GetService<IMarkerService>().Mark(native, ctx.Protection);
				ctx.Context.Registry.GetService<INameService>().SetCanRename(native, false);

				x86Register? reg;
				var codeGen = new x86CodeGen();
				do {
					ctx.DynCipher.GenerateExpressionPair(
						ctx.Random,
						new VariableExpression { Variable = var }, new VariableExpression { Variable = result },
						ctx.Depth, out expression, out inverse);

					reg = codeGen.GenerateX86(inverse, (v, r) => { return new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }; });
				} while (reg == null);

				code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

				expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
					.GenerateCIL(expression)
					.Compile<Func<int, int>>();


				ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
			}
			protected override Local Var(Variable var) {
				if (var.Name == "{RESULT}")
					return state;
				return base.Var(var);
			}
Example #13
0
		protected virtual void StoreVar(Variable var) {
			Emit(Instruction.Create(OpCodes.Stloc, Var(var)));
		}
Example #14
0
		protected virtual void LoadVar(Variable var) {
			Emit(Instruction.Create(OpCodes.Ldloc, Var(var)));
		}
Example #15
0
 public static void Run(StatementBlock block)
 {
     var mainBuff = new Variable("{BUFFER}");
     for (int i = 0; i < block.Statements.Count; i++)
         block.Statements[i] = ReplaceVar(block.Statements[i], mainBuff);
 }
Example #16
0
 public TempVarHolder(CipherGenContext p, Variable v)
 {
     parent = p;
     tempVar = v;
 }
Example #17
0
        private TypeDef GetKeyAttr(RPContext ctx)
        {
            if (keyAttrs == null)
                keyAttrs = new Tuple<TypeDef, Func<int, int>>[0x10];

            int index = ctx.Random.NextInt32(keyAttrs.Length);
            if (keyAttrs[index] == null) {
                TypeDef rtType = ctx.Context.Registry.GetService<IRuntimeService>().GetRuntimeType("Confuser.Runtime.RefProxyKey");
                TypeDef injectedAttr = InjectHelper.Inject(rtType, ctx.Module);
                injectedAttr.Name = ctx.Name.RandomName();
                injectedAttr.Namespace = string.Empty;

                Expression expression, inverse;
                var var = new Variable("{VAR}");
                var result = new Variable("{RESULT}");

                ctx.DynCipher.GenerateExpressionPair(
                    ctx.Random,
                    new VariableExpression { Variable = var }, new VariableExpression { Variable = result },
                    ctx.Depth, out expression, out inverse);

                var expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                    .GenerateCIL(expression)
                    .Compile<Func<int, int>>();

                MethodDef ctor = injectedAttr.FindMethod(".ctor");
                MutationHelper.ReplacePlaceholder(ctor, arg => {
                    var invCompiled = new List<Instruction>();
                    new CodeGen(arg, ctor, invCompiled).GenerateCIL(inverse);
                    return invCompiled.ToArray();
                });
                keyAttrs[index] = Tuple.Create(injectedAttr, expCompiled);

                ctx.Module.AddAsNonNestedType(injectedAttr);

                foreach (IDnlibDef def in injectedAttr.FindDefinitions()) {
                    if (def.Name == "GetHashCode") {
                        ctx.Name.MarkHelper(def, ctx.Marker);
                        ((MethodDef)def).Access = MethodAttributes.Public;
                    }
                    else
                        ctx.Name.MarkHelper(def, ctx.Marker);
                }
            }
            return keyAttrs[index].Item1;
        }