SlideShare una empresa de Scribd logo
1 de 23
Binary Patching for
  Fun and Profit
        with
     JRebel SDK
Binary Patching
Ninja.class             Ninja.class’
10101010101            10101010101
11000101010            11100001010
10101010001            10101010001
00010001110            00010001110
11011101011            11011101110




     a.k.a instrumentation
Binary Patching
                      ClassLoader
Application




              MyClass.class


               New code:
               1001010010010
                                        Transformer
               0101011001010




              MyObject
Why?
• Programming model (AOP, ORM)
• Tooling (profilers, coverage)
• Legacy integration


… or maybe you’re just bored? 
How?
• Add –javaagent to hook into class loading
  process
• Implement ClassFileTransformer
• Use bytecode manipulation libraries
  (Javassist, cglib, asm) to add any custom logic

            java.lang.instrument
java.lang.instrument
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;

public class Agent {
  public static void premain(String args, Instrumentation inst)
     throws Exception {
    inst.addTransformer(new ClassFileTransformer { … });
  }
}
java.lang.instrument
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;

public class Agent {
  public static void premain(String args, Instrumentation inst)
     throws Exception {
    inst.addTransformer(new ClassFileTransformer { … });
  }
}
java.lang.instrument
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
                                                  META-INF/MANIFEST.MF
public class Agent {                              Premain-Class: Agent
  public static void premain(String args, Instrumentation inst)
     throws Exception {
    inst.addTransformer(new ClassFileTransformer { … });
  }
}
                   java –javaagent:agent.jar …
j.l.instrument.ClassFileTransformer
new ClassFileTransformer() {
 public byte[] transform(ClassLoader loader, String className,
                        Class<?>classBeingRedefined,
                        ProtectionDomain protectionDomain,
                        byte[] classfileBuffer){


        ClassPool cp = ClassPool.getDefault();
        CtClass ct = cp.makeClass(new
                ByteArrayInputStream(classfileBuffer));
        transformClass(ct, cp);
        return ct.toBytecode();
    }
}
j.l.instrument.ClassFileTransformer
new ClassFileTransformer() {
 public byte[] transform(ClassLoader loader, String className,
                        Class<?>classBeingRedefined,
                        ProtectionDomain protectionDomain,
                        byte[] classfileBuffer){


        ClassPool cp = ClassPool.getDefault();
        CtClass ct = cp.makeClass(new
                ByteArrayInputStream(classfileBuffer));
        transformClass(ct, cp);
        return ct.toBytecode();
    }
}
j.l.instrument.ClassFileTransformer
new ClassFileTransformer() {
 public byte[] transform(ClassLoader loader, String className,
                        Class<?>classBeingRedefined,
                        ProtectionDomain protectionDomain,
                        byte[] classfileBuffer){


        ClassPool cp = ClassPool.getDefault();
        CtClass ct = cp.makeClass(new
                ByteArrayInputStream(classfileBuffer));
        transformClass(ct, cp);
        return ct.toBytecode();
    }
}
j.l.instrument.ClassFileTransformer
new ClassFileTransformer() {
 public byte[] transform(ClassLoader loader, String className,
                        Class<?>classBeingRedefined,
                        ProtectionDomain protectionDomain,
                        byte[] classfileBuffer){


        ClassPool cp = ClassPool.getDefault();
        CtClass ct = cp.makeClass(new
                ByteArrayInputStream(classfileBuffer));
        transformClass(ct, cp);
        return ct.toBytecode();
    }
}
Javassist
   1-2-3
Javassist
•   Bytecode manipulation made easy
•   Source-level and bytecode-level API
•   Uses the vocabulary of Java language
•   On-the-fly compilation of the injected code
•   http://www.jboss.org/javassist
Adding Interfaces
ClassPool cp = ClassPool.getDefault();

CtClass ct = cp.get("org.geecon.Alarm");

ct.addInterface(cp.get(Listener.class.getName()));

ct.addMethod(CtNewMethod.make("public void fire(){ alert(); }", ct));

public class Alarm {                 public interface Listener {

    void alert() {}                      void fire();

}                                    }
Adding Interfaces
ClassPool cp = ClassPool.getDefault();

CtClass ct = cp.get("org.geecon.Alarm");

ct.addInterface(cp.get(Listener.class.getName()));

ct.addMethod(CtNewMethod.make("public void fire(){ alert(); }", ct));

public class Alarm {                 public interface Listener {

    void alert() {}                      void fire();

}                                    }
Adding Interfaces
ClassPool cp = ClassPool.getDefault();

CtClass ct = cp.get("org.geecon.Alarm");

ct.addInterface(cp.get(Listener.class.getName()));

ct.addMethod(CtNewMethod.make("public void fire(){ alert(); }", ct));

public class Alarm {                 public interface Listener {

    void alert() {}                      void fire();

}                                    }
Adding Interfaces
ClassPool cp = ClassPool.getDefault();

CtClass ct = cp.get("org.geecon.Alarm");

ct.addInterface(cp.get(Listener.class.getName()));

ct.addMethod(CtNewMethod.make("public void fire(){ alert(); }", ct));

public class Alarm {                 public interface Listener {

    void alert() {}                      void fire();

}                                    }
Simple AOP
ProxyFactory pf = new ProxyFactory();

pf.setSuperclass(Notifier.class);

pf.setFilter(new MethodFilter() { … });
Notifier notifier = (Notifier) pf.createClass().newInstance();

((ProxyObject) notifier).setHandler(new MethodHandler() { … });

System.out.println("calling on()");
notifier.on();                                           public class Notifier {

System.out.println("calling off()");                         public void on(){ }
notifier.off();
                                                             @Pointcut
                                                             public void off(){}
                                                         }
Intercept Statements
ClassPool pool = ClassPool.getDefault();

CtClass ct = pool.get("org.geecon.PaymentMachine");

ct.getDeclaredMethod("process")
  .instrument(new ExprEditor() {
     public void edit(NewExpr e)
        throws CannotCompileException {
        e.replace("$_ = $proceed($$);");
     }
});
JRebel SDK
   Ö_õ
IDEs               Containers      Frameworks




   Build Tools




More at http://www.jrebel.com/features
Binary patching for fun and profit @ JUG.ru, 25.02.2012

Más contenido relacionado

La actualidad más candente

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
elliando dias
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
Mario Fusco
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
Kiyotaka Oku
 
NetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportNetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience Report
Anton Arhipov
 

La actualidad más candente (20)

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingJEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Java programs
Java programsJava programs
Java programs
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
EMFPath
EMFPathEMFPath
EMFPath
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?
 
The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184
 
The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
 
NetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportNetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience Report
 

Similar a Binary patching for fun and profit @ JUG.ru, 25.02.2012

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 

Similar a Binary patching for fun and profit @ JUG.ru, 25.02.2012 (20)

Taming Java Agents
Taming Java AgentsTaming Java Agents
Taming Java Agents
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
Java agents are watching your ByteCode
Java agents are watching your ByteCodeJava agents are watching your ByteCode
Java agents are watching your ByteCode
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Java Generics
Java GenericsJava Generics
Java Generics
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)
 
srgoc
srgocsrgoc
srgoc
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
DevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The CoversDevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The Covers
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камни
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 

Más de Anton Arhipov

JavaZone 2022 - Building Kotlin DSL.pdf
JavaZone 2022 - Building Kotlin DSL.pdfJavaZone 2022 - Building Kotlin DSL.pdf
JavaZone 2022 - Building Kotlin DSL.pdf
Anton Arhipov
 
Devclub 01/2017 - (Не)адекватное Java-интервью
Devclub 01/2017 - (Не)адекватное Java-интервьюDevclub 01/2017 - (Не)адекватное Java-интервью
Devclub 01/2017 - (Не)адекватное Java-интервью
Anton Arhipov
 

Más de Anton Arhipov (20)

JavaZone 2022 - Building Kotlin DSL.pdf
JavaZone 2022 - Building Kotlin DSL.pdfJavaZone 2022 - Building Kotlin DSL.pdf
JavaZone 2022 - Building Kotlin DSL.pdf
 
Idiomatic kotlin
Idiomatic kotlinIdiomatic kotlin
Idiomatic kotlin
 
TechTrain 2019 - (Не)адекватное техническое интервью
TechTrain 2019 - (Не)адекватное техническое интервьюTechTrain 2019 - (Не)адекватное техническое интервью
TechTrain 2019 - (Не)адекватное техническое интервью
 
Build pipelines with TeamCity
Build pipelines with TeamCityBuild pipelines with TeamCity
Build pipelines with TeamCity
 
Build pipelines with TeamCity
Build pipelines with TeamCityBuild pipelines with TeamCity
Build pipelines with TeamCity
 
Devoxx Ukraine 2018 - Kotlin DSL in under an hour
Devoxx Ukraine 2018 - Kotlin DSL in under an hourDevoxx Ukraine 2018 - Kotlin DSL in under an hour
Devoxx Ukraine 2018 - Kotlin DSL in under an hour
 
GeeCON Prague 2018 - Kotlin DSL in under an hour
GeeCON Prague 2018 - Kotlin DSL in under an hourGeeCON Prague 2018 - Kotlin DSL in under an hour
GeeCON Prague 2018 - Kotlin DSL in under an hour
 
Build pipelines with TeamCity and Kotlin DSL
Build pipelines with TeamCity and Kotlin DSLBuild pipelines with TeamCity and Kotlin DSL
Build pipelines with TeamCity and Kotlin DSL
 
Build pipelines with TeamCity
Build pipelines with TeamCityBuild pipelines with TeamCity
Build pipelines with TeamCity
 
JavaDay Kiev 2017 - Integration testing with TestContainers
JavaDay Kiev 2017 - Integration testing with TestContainersJavaDay Kiev 2017 - Integration testing with TestContainers
JavaDay Kiev 2017 - Integration testing with TestContainers
 
GeeCON Prague 2017 - TestContainers
GeeCON Prague 2017 - TestContainersGeeCON Prague 2017 - TestContainers
GeeCON Prague 2017 - TestContainers
 
JavaOne 2017 - The hitchhiker’s guide to Java class reloading
JavaOne 2017 - The hitchhiker’s guide to Java class reloadingJavaOne 2017 - The hitchhiker’s guide to Java class reloading
JavaOne 2017 - The hitchhiker’s guide to Java class reloading
 
JavaOne 2017 - TestContainers: integration testing without the hassle
JavaOne 2017 - TestContainers: integration testing without the hassleJavaOne 2017 - TestContainers: integration testing without the hassle
JavaOne 2017 - TestContainers: integration testing without the hassle
 
JavaOne 2017 - The hitchhiker’s guide to Java class reloading
JavaOne 2017 - The hitchhiker’s guide to Java class reloadingJavaOne 2017 - The hitchhiker’s guide to Java class reloading
JavaOne 2017 - The hitchhiker’s guide to Java class reloading
 
JavaZone 2017 - The Hitchhiker’s guide to Java class reloading
JavaZone 2017 - The Hitchhiker’s guide to Java class reloadingJavaZone 2017 - The Hitchhiker’s guide to Java class reloading
JavaZone 2017 - The Hitchhiker’s guide to Java class reloading
 
JUG.ua 20170225 - Java bytecode instrumentation
JUG.ua 20170225 - Java bytecode instrumentationJUG.ua 20170225 - Java bytecode instrumentation
JUG.ua 20170225 - Java bytecode instrumentation
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
Devclub 01/2017 - (Не)адекватное Java-интервью
Devclub 01/2017 - (Не)адекватное Java-интервьюDevclub 01/2017 - (Не)адекватное Java-интервью
Devclub 01/2017 - (Не)адекватное Java-интервью
 
Joker 2016 - Bytecode 101
Joker 2016 - Bytecode 101Joker 2016 - Bytecode 101
Joker 2016 - Bytecode 101
 
JPoint 2016 - Etudes of DIY Java profiler
JPoint 2016 - Etudes of DIY Java profilerJPoint 2016 - Etudes of DIY Java profiler
JPoint 2016 - Etudes of DIY Java profiler
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Binary patching for fun and profit @ JUG.ru, 25.02.2012

  • 1. Binary Patching for Fun and Profit with JRebel SDK
  • 2. Binary Patching Ninja.class Ninja.class’ 10101010101 10101010101 11000101010 11100001010 10101010001 10101010001 00010001110 00010001110 11011101011 11011101110 a.k.a instrumentation
  • 3. Binary Patching ClassLoader Application MyClass.class New code: 1001010010010 Transformer 0101011001010 MyObject
  • 4. Why? • Programming model (AOP, ORM) • Tooling (profilers, coverage) • Legacy integration … or maybe you’re just bored? 
  • 5. How? • Add –javaagent to hook into class loading process • Implement ClassFileTransformer • Use bytecode manipulation libraries (Javassist, cglib, asm) to add any custom logic java.lang.instrument
  • 6. java.lang.instrument import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; public class Agent { public static void premain(String args, Instrumentation inst) throws Exception { inst.addTransformer(new ClassFileTransformer { … }); } }
  • 7. java.lang.instrument import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; public class Agent { public static void premain(String args, Instrumentation inst) throws Exception { inst.addTransformer(new ClassFileTransformer { … }); } }
  • 8. java.lang.instrument import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; META-INF/MANIFEST.MF public class Agent { Premain-Class: Agent public static void premain(String args, Instrumentation inst) throws Exception { inst.addTransformer(new ClassFileTransformer { … }); } } java –javaagent:agent.jar …
  • 9. j.l.instrument.ClassFileTransformer new ClassFileTransformer() { public byte[] transform(ClassLoader loader, String className, Class<?>classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer){ ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.makeClass(new ByteArrayInputStream(classfileBuffer)); transformClass(ct, cp); return ct.toBytecode(); } }
  • 10. j.l.instrument.ClassFileTransformer new ClassFileTransformer() { public byte[] transform(ClassLoader loader, String className, Class<?>classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer){ ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.makeClass(new ByteArrayInputStream(classfileBuffer)); transformClass(ct, cp); return ct.toBytecode(); } }
  • 11. j.l.instrument.ClassFileTransformer new ClassFileTransformer() { public byte[] transform(ClassLoader loader, String className, Class<?>classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer){ ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.makeClass(new ByteArrayInputStream(classfileBuffer)); transformClass(ct, cp); return ct.toBytecode(); } }
  • 12. j.l.instrument.ClassFileTransformer new ClassFileTransformer() { public byte[] transform(ClassLoader loader, String className, Class<?>classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer){ ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.makeClass(new ByteArrayInputStream(classfileBuffer)); transformClass(ct, cp); return ct.toBytecode(); } }
  • 13. Javassist 1-2-3
  • 14. Javassist • Bytecode manipulation made easy • Source-level and bytecode-level API • Uses the vocabulary of Java language • On-the-fly compilation of the injected code • http://www.jboss.org/javassist
  • 15. Adding Interfaces ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.get("org.geecon.Alarm"); ct.addInterface(cp.get(Listener.class.getName())); ct.addMethod(CtNewMethod.make("public void fire(){ alert(); }", ct)); public class Alarm { public interface Listener { void alert() {} void fire(); } }
  • 16. Adding Interfaces ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.get("org.geecon.Alarm"); ct.addInterface(cp.get(Listener.class.getName())); ct.addMethod(CtNewMethod.make("public void fire(){ alert(); }", ct)); public class Alarm { public interface Listener { void alert() {} void fire(); } }
  • 17. Adding Interfaces ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.get("org.geecon.Alarm"); ct.addInterface(cp.get(Listener.class.getName())); ct.addMethod(CtNewMethod.make("public void fire(){ alert(); }", ct)); public class Alarm { public interface Listener { void alert() {} void fire(); } }
  • 18. Adding Interfaces ClassPool cp = ClassPool.getDefault(); CtClass ct = cp.get("org.geecon.Alarm"); ct.addInterface(cp.get(Listener.class.getName())); ct.addMethod(CtNewMethod.make("public void fire(){ alert(); }", ct)); public class Alarm { public interface Listener { void alert() {} void fire(); } }
  • 19. Simple AOP ProxyFactory pf = new ProxyFactory(); pf.setSuperclass(Notifier.class); pf.setFilter(new MethodFilter() { … }); Notifier notifier = (Notifier) pf.createClass().newInstance(); ((ProxyObject) notifier).setHandler(new MethodHandler() { … }); System.out.println("calling on()"); notifier.on(); public class Notifier { System.out.println("calling off()"); public void on(){ } notifier.off(); @Pointcut public void off(){} }
  • 20. Intercept Statements ClassPool pool = ClassPool.getDefault(); CtClass ct = pool.get("org.geecon.PaymentMachine"); ct.getDeclaredMethod("process") .instrument(new ExprEditor() { public void edit(NewExpr e) throws CannotCompileException { e.replace("$_ = $proceed($$);"); } });
  • 21. JRebel SDK Ö_õ
  • 22. IDEs Containers Frameworks Build Tools More at http://www.jrebel.com/features