示例#1
0
        /// <summary>
        /// Creates a new token handler.
        /// </summary>
        /// <param name="cfg">Configuration settings.</param>
        /// <param name="keyDeriver">Encryption key deriver.</param>
        public ActionTokenPairHandler(
            IOptions <ConfigurationAuthentication> cfg,
            IKeyDeriver keyDeriver)
        {
            this.Configuration = cfg.Value;

            var keyBase = AbstractionUtilities.UTF8.GetBytes(this.Configuration.TokenKey);

            if (keyBase.Length < 8)
            {
                throw new ArgumentException("Token key must be at least 8 bytes-long.", nameof(cfg));
            }

            var saltBytes = new byte[96];

            using (var rng = new SecureRandom())
                rng.GetBytes(saltBytes);

            var async = new AsyncExecutor();

            this.SigningKey = async.Execute(keyDeriver.DeriveKeyAsync(
                                                value: keyBase,
                                                salt: saltBytes,
                                                byteCount: 256 / 8));
        }
示例#2
0
 /// <summary>
 /// Instantiates the handler and configures the encryption key.
 /// </summary>
 /// <param name="cfg">Configuration for the handler.</param>
 public OAuthTokenHandler(
     IOptions <ConfigurationOAuth> cfg,
     IKeyDeriver keyDeriver)
 {
     this.KeyDeriver = keyDeriver;
     this.Key        = AbstractionUtilities.UTF8.GetBytes(cfg.Value.TokenKey);
 }
示例#3
0
        /// <summary>
        /// Creates a new handler.
        /// </summary>
        /// <param name="cfg">Configuration to use.</param>
        public JwtHandler(
            IOptions <ConfigurationAuthentication> cfg,
            IKeyDeriver keyDeriver)
        {
            this.Configuration = cfg.Value;

            var keyBase = AbstractionUtilities.UTF8.GetBytes(this.Configuration.TokenKey);

            if (keyBase.Length < 8)
            {
                throw new ArgumentException("Token key must be at least 8 bytes-long.", nameof(cfg));
            }

            var saltBase = MemoryMarshal.Read <long>(keyBase);

            saltBase *= 13;
            var saltBytes = MemoryMarshal.AsBytes(MemoryMarshal.CreateSpan(ref saltBase, 1));

            var async = new AsyncExecutor();

            this.Key = new SymmetricSecurityKey(
                async.Execute(
                    keyDeriver.DeriveKeyAsync(
                        value: keyBase,
                        salt: saltBytes.ToArray(),
                        byteCount: 512 / 8)));

            this.Credentials             = new SigningCredentials(this.Key, SecurityAlgorithms.HmacSha512);
            this.JwtValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = this.Configuration.TokenIssuer,
                ValidAudience    = this.Configuration.TokenIssuer,
                IssuerSigningKey = this.Key,
                ClockSkew        = TimeSpan.FromSeconds(1)
            };
        }
示例#4
0
        public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters)
        {
            this.context = context;
            random       = context.Registry.GetService <IRandomService>().GetRandomGenerator(parent.FullId);
            z            = random.NextUInt32();
            x            = random.NextUInt32();
            c            = random.NextUInt32();
            v            = random.NextUInt32();
            name1        = random.NextUInt32() & 0x7f7f7f7f;
            name2        = random.NextUInt32() & 0x7f7f7f7f;
            key          = random.NextUInt32();

            fieldLayout = new byte[6];
            for (int i = 0; i < 6; i++)
            {
                int index = random.NextInt32(0, 6);
                while (fieldLayout[index] != 0)
                {
                    index = random.NextInt32(0, 6);
                }
                fieldLayout[index] = (byte)i;
            }

            switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal))
            {
            case Mode.Normal:
                deriver = new NormalDeriver();
                break;

            case Mode.Dynamic:
                deriver = new DynamicDeriver();
                break;

            default:
                throw new UnreachableException();
            }
            deriver.Init(context, random);

            var     rt                   = context.Registry.GetService <IRuntimeService>();
            TypeDef initType             = rt.GetRuntimeType("Confuser.Runtime.AntiTamperJIT");
            IEnumerable <IDnlibDef> defs = InjectHelper.Inject(initType, context.CurrentModule.GlobalType, context.CurrentModule);

            initMethod = defs.OfType <MethodDef>().Single(method => method.Name == "Initialize");

            initMethod.Body.SimplifyMacros(initMethod.Parameters);
            List <Instruction> instrs = initMethod.Body.Instructions.ToList();

            for (int i = 0; i < instrs.Count; i++)
            {
                Instruction instr = instrs[i];
                if (instr.OpCode == OpCodes.Ldtoken)
                {
                    instr.Operand = context.CurrentModule.GlobalType;
                }
                else if (instr.OpCode == OpCodes.Call)
                {
                    var method = (IMethod)instr.Operand;
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt")
                    {
                        Instruction ldDst = instrs[i - 2];
                        Instruction ldSrc = instrs[i - 1];
                        Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, deriver.EmitDerivation(initMethod, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
                    }
                }
            }
            initMethod.Body.Instructions.Clear();
            foreach (Instruction instr in instrs)
            {
                initMethod.Body.Instructions.Add(instr);
            }

            MutationHelper.InjectKeys(initMethod,
                                      new[] { 0, 1, 2, 3, 4 },
                                      new[] { (int)(name1 * name2), (int)z, (int)x, (int)c, (int)v });

            var name   = context.Registry.GetService <INameService>();
            var marker = context.Registry.GetService <IMarkerService>();

            cctor = context.CurrentModule.GlobalType.FindStaticConstructor();

            cctorRepl          = new MethodDefUser(name.RandomName(), MethodSig.CreateStatic(context.CurrentModule.CorLibTypes.Void));
            cctorRepl.IsStatic = true;
            cctorRepl.Access   = MethodAttributes.CompilerControlled;
            cctorRepl.Body     = new CilBody();
            cctorRepl.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            context.CurrentModule.GlobalType.Methods.Add(cctorRepl);
            name.MarkHelper(cctorRepl, marker, parent);

            MutationHelper.InjectKeys(defs.OfType <MethodDef>().Single(method => method.Name == "HookHandler"),
                                      new[] { 0 }, new[] { (int)key });
            foreach (IDnlibDef def in defs)
            {
                if (def.Name == "MethodData")
                {
                    var        dataType = (TypeDef)def;
                    FieldDef[] fields   = dataType.Fields.ToArray();
                    var        layout   = fieldLayout.Clone() as byte[];
                    Array.Sort(layout, fields);
                    for (byte j = 0; j < 6; j++)
                    {
                        layout[j] = j;
                    }
                    Array.Sort(fieldLayout, layout);
                    fieldLayout = layout;
                    dataType.Fields.Clear();
                    foreach (FieldDef f in fields)
                    {
                        dataType.Fields.Add(f);
                    }
                }
                name.MarkHelper(def, marker, parent);
                if (def is MethodDef)
                {
                    parent.ExcludeMethod(context, (MethodDef)def);
                }
            }
            parent.ExcludeMethod(context, cctor);
        }
示例#5
0
        public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters)
        {
            random = context.Registry.GetService <IRandomService>().GetRandomGenerator(parent.FullId);
            z      = random.NextUInt32();
            x      = random.NextUInt32();
            c      = random.NextUInt32();
            v      = random.NextUInt32();
            name1  = random.NextUInt32() & 0x7f7f7f7f;
            name2  = random.NextUInt32() & 0x7f7f7f7f;

            switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal))
            {
            case Mode.Normal:
                deriver = new NormalDeriver();
                break;

            case Mode.Dynamic:
                deriver = new DynamicDeriver();
                break;

            default:
                throw new UnreachableException();
            }
            deriver.Init(context, random);

            var     rt       = context.Registry.GetService <IRuntimeService>();
            TypeDef initType = rt.GetRuntimeType("Confuser.Runtime.AntiTamperAnti");
            IEnumerable <IDnlibDef> members = InjectHelper.Inject(initType, context.CurrentModule.GlobalType, context.CurrentModule);
            var initMethod = (MethodDef)members.Single(m => m.Name == "Initialize");

            initMethod.Body.SimplifyMacros(initMethod.Parameters);
            List <Instruction> instrs = initMethod.Body.Instructions.ToList();

            for (int i = 0; i < instrs.Count; i++)
            {
                Instruction instr = instrs[i];
                if (instr.OpCode == OpCodes.Ldtoken)
                {
                    instr.Operand = context.CurrentModule.GlobalType;
                }
                else if (instr.OpCode == OpCodes.Call)
                {
                    var method = (IMethod)instr.Operand;
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt")
                    {
                        Instruction ldDst = instrs[i - 2];
                        Instruction ldSrc = instrs[i - 1];
                        Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, deriver.EmitDerivation(initMethod, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
                    }
                }
            }
            initMethod.Body.Instructions.Clear();
            foreach (Instruction instr in instrs)
            {
                initMethod.Body.Instructions.Add(instr);
            }

            MutationHelper.InjectKeys(initMethod,
                                      new[] { 0, 1, 2, 3, 4 },
                                      new[] { (int)(name1 * name2), (int)z, (int)x, (int)c, (int)v });

            var name   = context.Registry.GetService <INameService>();
            var marker = context.Registry.GetService <IMarkerService>();

            foreach (IDnlibDef def in members)
            {
                name.MarkHelper(def, marker, parent);
                if (def is MethodDef)
                {
                    parent.ExcludeMethod(context, (MethodDef)def);
                }
            }

            MethodDef cctor = context.CurrentModule.GlobalType.FindStaticConstructor();

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, initMethod));

            parent.ExcludeMethod(context, cctor);
        }
示例#6
0
		public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters) {
			random = context.Registry.GetService<IRandomService>().GetRandomGenerator(parent.FullId);
			z = random.NextUInt32();
			x = random.NextUInt32();
			c = random.NextUInt32();
			v = random.NextUInt32();
			name1 = random.NextUInt32() & 0x7f7f7f7f;
			name2 = random.NextUInt32() & 0x7f7f7f7f;

			switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal)) {
				case Mode.Normal:
					deriver = new NormalDeriver();
					break;
				case Mode.Dynamic:
					deriver = new DynamicDeriver();
					break;
				default:
					throw new UnreachableException();
			}
			deriver.Init(context, random);

			var rt = context.Registry.GetService<IRuntimeService>();
			TypeDef initType = rt.GetRuntimeType("Confuser.Runtime.AntiTamperNormal");
			IEnumerable<IDnlibDef> members = InjectHelper.Inject(initType, context.CurrentModule.GlobalType, context.CurrentModule);
			var initMethod = (MethodDef)members.Single(m => m.Name == "Initialize");

			initMethod.Body.SimplifyMacros(initMethod.Parameters);
			List<Instruction> instrs = initMethod.Body.Instructions.ToList();
			for (int i = 0; i < instrs.Count; i++) {
				Instruction instr = instrs[i];
				if (instr.OpCode == OpCodes.Ldtoken) {
					instr.Operand = context.CurrentModule.GlobalType;
				}
				else if (instr.OpCode == OpCodes.Call) {
					var method = (IMethod)instr.Operand;
					if (method.DeclaringType.Name == "Mutation" &&
					    method.Name == "Crypt") {
						Instruction ldDst = instrs[i - 2];
						Instruction ldSrc = instrs[i - 1];
						Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
						instrs.RemoveAt(i);
						instrs.RemoveAt(i - 1);
						instrs.RemoveAt(i - 2);
						instrs.InsertRange(i - 2, deriver.EmitDerivation(initMethod, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
					}
				}
			}
			initMethod.Body.Instructions.Clear();
			foreach (Instruction instr in instrs)
				initMethod.Body.Instructions.Add(instr);

			MutationHelper.InjectKeys(initMethod,
			                          new[] { 0, 1, 2, 3, 4 },
			                          new[] { (int)(name1 * name2), (int)z, (int)x, (int)c, (int)v });

			var name = context.Registry.GetService<INameService>();
			var marker = context.Registry.GetService<IMarkerService>();
			foreach (IDnlibDef def in members) {
				name.MarkHelper(def, marker, parent);
				if (def is MethodDef)
					parent.ExcludeMethod(context, (MethodDef)def);
			}

			MethodDef cctor = context.CurrentModule.GlobalType.FindStaticConstructor();
			cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, initMethod));

			parent.ExcludeMethod(context, cctor);
		}
示例#7
0
		public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters) {
			this.context = context;
			random = context.Registry.GetService<IRandomService>().GetRandomGenerator(parent.FullId);
			z = random.NextUInt32();
			x = random.NextUInt32();
			c = random.NextUInt32();
			v = random.NextUInt32();
			name1 = random.NextUInt32() & 0x7f7f7f7f;
			name2 = random.NextUInt32() & 0x7f7f7f7f;
			key = random.NextUInt32();

			fieldLayout = new byte[6];
			for (int i = 0; i < 6; i++) {
				int index = random.NextInt32(0, 6);
				while (fieldLayout[index] != 0)
					index = random.NextInt32(0, 6);
				fieldLayout[index] = (byte)i;
			}

			switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal)) {
				case Mode.Normal:
					deriver = new NormalDeriver();
					break;
				case Mode.Dynamic:
					deriver = new DynamicDeriver();
					break;
				default:
					throw new UnreachableException();
			}
			deriver.Init(context, random);

			var rt = context.Registry.GetService<IRuntimeService>();
			TypeDef initType = rt.GetRuntimeType("Confuser.Runtime.AntiTamperJIT");
			IEnumerable<IDnlibDef> defs = InjectHelper.Inject(initType, context.CurrentModule.GlobalType, context.CurrentModule);
			initMethod = defs.OfType<MethodDef>().Single(method => method.Name == "Initialize");

			initMethod.Body.SimplifyMacros(initMethod.Parameters);
			List<Instruction> instrs = initMethod.Body.Instructions.ToList();
			for (int i = 0; i < instrs.Count; i++) {
				Instruction instr = instrs[i];
				if (instr.OpCode == OpCodes.Ldtoken) {
					instr.Operand = context.CurrentModule.GlobalType;
				}
				else if (instr.OpCode == OpCodes.Call) {
					var method = (IMethod)instr.Operand;
					if (method.DeclaringType.Name == "Mutation" &&
					    method.Name == "Crypt") {
						Instruction ldDst = instrs[i - 2];
						Instruction ldSrc = instrs[i - 1];
						Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
						instrs.RemoveAt(i);
						instrs.RemoveAt(i - 1);
						instrs.RemoveAt(i - 2);
						instrs.InsertRange(i - 2, deriver.EmitDerivation(initMethod, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
					}
				}
			}
			initMethod.Body.Instructions.Clear();
			foreach (Instruction instr in instrs)
				initMethod.Body.Instructions.Add(instr);

			MutationHelper.InjectKeys(initMethod,
			                          new[] { 0, 1, 2, 3, 4 },
			                          new[] { (int)(name1 * name2), (int)z, (int)x, (int)c, (int)v });

			var name = context.Registry.GetService<INameService>();
			var marker = context.Registry.GetService<IMarkerService>();

			cctor = context.CurrentModule.GlobalType.FindStaticConstructor();

			cctorRepl = new MethodDefUser(name.RandomName(), MethodSig.CreateStatic(context.CurrentModule.CorLibTypes.Void));
			cctorRepl.IsStatic = true;
			cctorRepl.Access = MethodAttributes.CompilerControlled;
			cctorRepl.Body = new CilBody();
			cctorRepl.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
			context.CurrentModule.GlobalType.Methods.Add(cctorRepl);
			name.MarkHelper(cctorRepl, marker, parent);

			MutationHelper.InjectKeys(defs.OfType<MethodDef>().Single(method => method.Name == "HookHandler"),
			                          new[] { 0 }, new[] { (int)key });
			foreach (IDnlibDef def in defs) {
				if (def.Name == "MethodData") {
					var dataType = (TypeDef)def;
					FieldDef[] fields = dataType.Fields.ToArray();
					var layout = fieldLayout.Clone() as byte[];
					Array.Sort(layout, fields);
					for (byte j = 0; j < 6; j++)
						layout[j] = j;
					Array.Sort(fieldLayout, layout);
					fieldLayout = layout;
					dataType.Fields.Clear();
					foreach (FieldDef f in fields)
						dataType.Fields.Add(f);
				}
				name.MarkHelper(def, marker, parent);
				if (def is MethodDef)
					parent.ExcludeMethod(context, (MethodDef)def);
			}
			parent.ExcludeMethod(context, cctor);
		}