Skip to content

Commit

Permalink
added reference proxy protection
Browse files Browse the repository at this point in the history
  • Loading branch information
yck1509 committed Mar 9, 2014
1 parent 65d1aff commit a10c2c8
Show file tree
Hide file tree
Showing 44 changed files with 1,454 additions and 67 deletions.
6 changes: 4 additions & 2 deletions Confuser.CLI/Confuser.CLI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>..\Debug\bin\Confuser.CLI.XML</DocumentationFile>
<DocumentationFile>
</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
Expand All @@ -34,7 +35,8 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>..\Release\bin\Confuser.CLI.XML</DocumentationFile>
<DocumentationFile>
</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
Expand Down
2 changes: 1 addition & 1 deletion Confuser.CLI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public void Finish(bool successful)
{
DateTime now = DateTime.Now;
string timeString = string.Format(
"at {0}, {1}:{2} elapsed.",
"at {0}, {1}:{2:d2} elapsed.",
now.ToShortTimeString(),
(int)now.Subtract(begin).TotalMinutes,
now.Subtract(begin).Seconds);
Expand Down
1 change: 1 addition & 0 deletions Confuser.Core/Confuser.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
<Compile Include="ConfuserComponent.cs" />
<Compile Include="DnlibUtils.cs" />
<Compile Include="Helpers\InjectHelper.cs" />
<Compile Include="Helpers\MutationHelper.cs" />
<Compile Include="ILogger.cs" />
<Compile Include="Marker.cs" />
<Compile Include="MarkerResult.cs" />
Expand Down
21 changes: 21 additions & 0 deletions Confuser.Core/DnlibUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,27 @@ public static bool IsDelegate(this TypeDef type)
return fullName == "System.Delegate" || fullName == "System.MulticastDelegate";
}

/// <summary>
/// Determines whether the specified type is inherited from a base type in corlib.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="baseType">The full name of base type.</param>
/// <returns><c>true</c> if the specified type is inherited from a base type; otherwise, <c>false</c>.</returns>
public static bool InheritsFromCorlib(this TypeDef type, string baseType)
{
if (type.BaseType == null)
return false;

TypeDef bas = type;
do
{
bas = bas.BaseType.ResolveTypeDefThrow();
if (bas.ReflectionFullName == baseType)
return true;
} while (bas.BaseType != null && bas.BaseType.DefinitionAssembly.IsCorLib());
return false;
}

/// <summary>
/// Determines whether the specified type implements the specified interface.
/// </summary>
Expand Down
16 changes: 15 additions & 1 deletion Confuser.Core/Helpers/InjectHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public InjectContext(ModuleDef module, ModuleDef target)
{
OriginModule = module;
TargetModule = target;
importer = new Importer(target);
importer = new Importer(target, ImporterOptions.TryToUseTypeDefs);
importer.Resolver = this;
}

Expand Down Expand Up @@ -282,6 +282,20 @@ public static TypeDef Inject(TypeDef typeDef, ModuleDef target)
return (TypeDef)ctx.Map[typeDef];
}

/// <summary>
/// Injects the specified MethodDef to another module.
/// </summary>
/// <param name="methodDef">The source MethodDef.</param>
/// <param name="target">The target module.</param>
/// <returns>The injected MethodDef.</returns>
public static MethodDef Inject(MethodDef methodDef, ModuleDef target)
{
InjectContext ctx = new InjectContext(methodDef.Module, target);
ctx.Map[methodDef] = Clone(methodDef);
CopyMethodDef(methodDef, ctx);
return (MethodDef)ctx.Map[methodDef];
}

/// <summary>
/// Injects the members of specified TypeDef to another module.
/// </summary>
Expand Down
123 changes: 123 additions & 0 deletions Confuser.Core/Helpers/MutationHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using Confuser.Core.Services;

namespace Confuser.Core.Helpers
{
/// <summary>
/// Provides methods to mutated injected methods.
/// </summary>
public static class MutationHelper
{
const string mutationType = "Mutation";
static Dictionary<string, int> field2index = new Dictionary<string, int>()
{
{ "KeyI0", 0 },
{ "KeyI1", 1 },
{ "KeyI2", 2 },
{ "KeyI3", 3 },
{ "KeyI4", 4 },
{ "KeyI5", 5 },
{ "KeyI6", 6 },
{ "KeyI7", 7 },
{ "KeyI8", 8 },
{ "KeyI9", 9 },
{ "KeyI10", 10 },
{ "KeyI11", 11 },
{ "KeyI12", 12 },
{ "KeyI13", 13 },
{ "KeyI14", 14 },
{ "KeyI15", 15 }
};

/// <summary>
/// Replaces the mutation key placeholder in method with actual key.
/// </summary>
/// <param name="method">The method to process.</param>
/// <param name="keyId">The mutation key ID.</param>
/// <param name="key">The actual key.</param>
public static void InjectKey(MethodDef method, int keyId, int key)
{
foreach (var instr in method.Body.Instructions)
{
if (instr.OpCode == OpCodes.Ldsfld)
{
IField field = (IField)instr.Operand;
int _keyId;
if (field.DeclaringType.FullName == mutationType &&
field2index.TryGetValue(field.Name, out _keyId) &&
_keyId == keyId)
{
instr.OpCode = OpCodes.Ldc_I4;
instr.Operand = key;
}
}
}

}

/// <summary>
/// Replaces the mutation key placeholders in method with actual keys.
/// </summary>
/// <param name="method">The method to process.</param>
/// <param name="keyId">The mutation key IDs.</param>
/// <param name="key">The actual keys.</param>
public static void InjectKeys(MethodDef method, int[] keyIds, int[] keys)
{
foreach (var instr in method.Body.Instructions)
{
if (instr.OpCode == OpCodes.Ldsfld)
{
IField field = (IField)instr.Operand;
int _keyIndex;
if (field.DeclaringType.FullName == mutationType &&
field2index.TryGetValue(field.Name, out _keyIndex) &&
(_keyIndex = Array.IndexOf(keyIds, _keyIndex)) != -1)
{
instr.OpCode = OpCodes.Ldc_I4;
instr.Operand = keys[_keyIndex];
}
}
}
}

/// <summary>
/// Replaces the placeholder call in method with actual instruction sequence.
/// </summary>
/// <param name="method">The methodto process.</param>
/// <param name="repl">The function replacing the argument of placeholder call with actual instruction sequence.</param>
public static void ReplacePlaceholder(MethodDef method, Func<Instruction[], Instruction[]> repl)
{
MethodTrace trace = new MethodTrace(method).Trace();
for (int i = 0; i < method.Body.Instructions.Count; i++)
{
var instr = method.Body.Instructions[i];
if (instr.OpCode == OpCodes.Call)
{
IMethod operand = (IMethod)instr.Operand;
if (operand.DeclaringType.FullName == mutationType &&
operand.Name == "Placeholder")
{
var argIndexes = trace.TraceArguments(instr);
if (argIndexes == null)
throw new ArgumentException("Failed to trace placeholder argument.");

var argIndex = argIndexes[0];
Instruction[] arg = method.Body.Instructions.Skip(argIndex).Take(i - argIndex).ToArray();
for (int j = 0; j < arg.Length; j++)
method.Body.Instructions.RemoveAt(argIndex);
method.Body.Instructions.RemoveAt(argIndex);
arg = repl(arg);
for (int j = arg.Length - 1; j >= 0; j--)
method.Body.Instructions.Insert(argIndex, arg[j]);
return;
}
}
}
}
}
}
1 change: 0 additions & 1 deletion Confuser.Core/Marker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,6 @@ protected internal virtual MarkerResult MarkProject(ConfuserProject proj, Confus
{
context.Logger.InfoFormat("Loading '{0}'...", module.Path);
ModuleDefMD modDef = module.Resolve(proj.BaseDirectory, context.Resolver.DefaultModuleContext);
modDef.EnableTypeDefFindCache = true;
var rules = ParseRules(proj, module, context);

context.Annotations.Set(modDef, SNKey, LoadSNKey(context, module.SNKeyPath, module.SNKeyPassword));
Expand Down
15 changes: 15 additions & 0 deletions Confuser.Core/Services/RandomService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,19 @@ public void NextBytes(byte[] buffer, int offset, int length)
}
}

/// <summary>
/// Returns a random byte.
/// </summary>
/// <returns>Requested random byte.</returns>
public byte NextByte()
{
byte ret = state[32 - stateFilled];
stateFilled--;
if (stateFilled == 0)
NextState();
return ret;
}

/// <summary>
/// Gets a buffer of random bytes with the specified length.
/// </summary>
Expand All @@ -126,6 +139,7 @@ public int NextInt32()
{
return BitConverter.ToInt32(NextBytes(4), 0);
}

/// <summary>
/// Returns a nonnegative random integer that is less than the specified maximum.
/// </summary>
Expand All @@ -135,6 +149,7 @@ public int NextInt32(int max)
{
return (int)(NextUInt32() % max);
}

/// <summary>
/// Returns a random integer that is within a specified range.
/// </summary>
Expand Down
28 changes: 14 additions & 14 deletions Confuser.Core/Services/TraceService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public MethodTrace Trace(MethodDef method)
{
if (method == null)
throw new ArgumentNullException("method");
return cache.GetValueOrDefaultLazy(method, m => cache[m] = new MethodTrace(this, m)).Trace();
return cache.GetValueOrDefaultLazy(method, m => cache[m] = new MethodTrace(m)).Trace();
}
}

Expand All @@ -51,17 +51,14 @@ public interface ITraceService
/// </summary>
public class MethodTrace
{
TraceService service;
MethodDef method;

/// <summary>
/// Initializes a new instance of the <see cref="MethodTrace"/> class.
/// </summary>
/// <param name="service">The trace service.</param>
/// <param name="method">The method to trace.</param>
internal MethodTrace(TraceService service, MethodDef method)
internal MethodTrace(MethodDef method)
{
this.service = service;
this.method = method;
}

Expand Down Expand Up @@ -222,7 +219,7 @@ internal MethodTrace Trace()
/// <exception cref="InvalidMethodException">The method body is invalid.</exception>
public int[] TraceArguments(Instruction instr)
{
if (instr.OpCode.Code != Code.Call && instr.OpCode.Code != Code.Callvirt)
if (instr.OpCode.Code != Code.Call && instr.OpCode.Code != Code.Callvirt && instr.OpCode.Code != Code.Newobj)
throw new ArgumentException("Invalid call instruction.", "instr");

int push, pop;
Expand Down Expand Up @@ -259,12 +256,12 @@ public int[] TraceArguments(Instruction instr)
index--;
}
if (index < 0)
throw new InvalidMethodException("Empty evaluation stack.");
return null;

if (beginInstrIndex == -1)
beginInstrIndex = index;
else if (beginInstrIndex != index)
throw new InvalidMethodException("Stack depth not matched.");
return null;
}

// Trace the index of arguments
Expand All @@ -279,9 +276,9 @@ public int[] TraceArguments(Instruction instr)
int index = tuple.Item1;
Stack<int> evalStack = tuple.Item2;

while (index != instrIndex)
while (index != instrIndex && index < method.Body.Instructions.Count)
{
Instruction currentInstr = method.Body.Instructions[index];
Instruction currentInstr = Instructions[index];
currentInstr.CalculateStackUsage(out push, out pop);
int stackUsage = pop - push;
if (stackUsage < 0)
Expand All @@ -291,6 +288,9 @@ public int[] TraceArguments(Instruction instr)
}
else
{
if (evalStack.Count < stackUsage)
return null;

for (int i = 0; i < stackUsage; i++)
evalStack.Pop();
}
Expand Down Expand Up @@ -319,17 +319,17 @@ public int[] TraceArguments(Instruction instr)
}

if (evalStack.Count != argCount)
throw new InvalidMethodException("Cannot find argument index.");
return null;
else if (ret != null && !evalStack.SequenceEqual(ret))
throw new InvalidMethodException("Stack depths mismatched.");
return null;
else
ret = evalStack.ToArray();
}

Array.Reverse(ret);
if (ret == null)
throw new InvalidMethodException("Cannot find argument index.");
return ret;

Array.Reverse(ret);
return ret;
}
}
Expand Down
2 changes: 1 addition & 1 deletion Confuser.DynCipher/Elements/NumOp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public override void Initialize(RandomGenerator random)
break;
case CryptoNumOps.Mul:
Key = random.NextUInt32() | 1;
InverseKey = Utils.modInv(Key);
InverseKey = MathsUtils.modInv(Key);
break;
case CryptoNumOps.Xnor:
Key = random.NextUInt32();
Expand Down
4 changes: 2 additions & 2 deletions Confuser.DynCipher/Elements/Swap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ void EmitCore(CipherGenContext context)
Target = a
}).Emit(new AssignmentStatement()
{
Value = tmp * (LiteralExpression)Utils.modInv(Key),
Value = tmp * (LiteralExpression)MathsUtils.modInv(Key),
Target = b
});
}
Expand All @@ -76,7 +76,7 @@ void EmitCore(CipherGenContext context)
Target = a
}).Emit(new AssignmentStatement()
{
Value = (b & notMask) | (tmp * (LiteralExpression)Utils.modInv(Key)),
Value = (b & notMask) | (tmp * (LiteralExpression)MathsUtils.modInv(Key)),
Target = b
});
}
Expand Down
2 changes: 1 addition & 1 deletion Confuser.DynCipher/Generation/ExpressionGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ static Expression GenerateInverse(Expression exp, Expression var, Dictionary<Exp
{
Debug.Assert(constExp is LiteralExpression);
uint val = ((LiteralExpression)constExp).Value;
val = Utils.modInv(val);
val = MathsUtils.modInv(val);
result = new BinOpExpression()
{
Operation = BinOps.Mul,
Expand Down
Loading

0 comments on commit a10c2c8

Please sign in to comment.