How to really obfuscate your pdf malware

Z
zynamics GmbHzynamics GmbH
How to really obfuscate
  your PDF malware


   Sebastian Porst - ReCon 2010
Email: sebastian.porst@zynamics.com
        Twitter: @LambdaCube
                                      1
Targeted Attacks 2008



                          Adobe Acrobat
  Microsoft Word;         Reader; 28.61%
      34.55%


                            Microsoft
                           PowerPoint;
       Microsoft Excel;      16.87%
           19.97%


     http://www.f-secure.com/weblog/archives/00001676.html 2
Targeted Attacks 2009



                    Adobe Acrobat
  Microsoft Word;
                    Reader; 48.87%
      39.22%




                           Microsoft
   Microsoft              PowerPoint;
  Excel; 7.39%              4.52%
                                        3
Exploited in the wild

CVE-            CVE-            CVE-            CVE-
2007-           2009-           2009-           2009-
5659            0658            1492            4324




        CVE-            CVE-            CVE-            CVE-
        2008-           2009-           2009-           2010-
        2992            0927            3459            0188
Four common exploit paths

Broken PDF Parser

Vulnerable JavaScript Engine

Vulnerable external libraries

/Launch
                                5
PDF Malware Obfuscation
 Different tricks for different purposes

Make manual analysis more difficult

Resist automated analysis

Avoid detection by virus scanners

                                           6
PDF Malware Obfuscation
         Conflicting goals


Avoid detection      Make analysis
   by being         difficult by being
  wellformed           malformed



                                         7
How to achieve these goals

  Being harmless         Being evil
• Avoid JavaScript       • Use heavy
• Do not use unusual       obfuscation
  encodings              • Try to break tools
• Do not try to break
  parser-based tools
• Ideally use an 0-day
                                                8
Let‘s be evil

                9
Breaking tools
Rule #1: Do the unexpected



                             11
This is what tools expect
• ASCII Strings
• Boring encodings like #41 instead of A
• Wellformed or only moderately malformed
  PDF file structure




                                            12
Malformed documents
• Adobe Reader tries to load malformed PDF
  files
• Very, very liberal interpretation of the PDF
  specification
• Parser-based analysis tools need to know
  about Adobe Reader file correction



                                                 13
Malformed PDF file – Example I
7 0 obj
  <<
   /Type /Action
   /S    /JavaScript
   /JS   (app.alert('whatever');)
  >>
endobj


                                    14
Malformed PDF file – Example II
5 0 obj
  << /Length 45 >>
  stream
    some data
  endstream
endobj




                                   15
Further reading




                  16
Obfuscating JavaScript code
Goal of JavaScript obfuscation




 Hide the shellcode

                                 18
JavaScript obfuscation in the wild
•   Screwed up formatting
•   Name obfuscation
•   Eval-chains
•   Splitting JavaScript code
•   Simple anti-emulation techniques
•   callee-trick
•   ...

                                         19
Screwed up formatting
• Basically just remove all newlines
• Completely useless: jsbeautifier.org




                                         20
Name obfuscation
• Variables or function names are renamed to
  hide their meaning
• Most JavaScript obfuscators screw this up




                                               21
Obfuscation example: Original code
function executePayload(payload, delay)
{
  if (delay > 1000)
  {
    // Whatever
  }
}

function heapSpray(code, repeat)
{
  for (i=0;i<repeat;i++)
  {
    code = code + code;
  }
}
                                          22
Obfuscation without considering scope
function executePayload(hkof3ewhoife, fhpfewhpofe)
{
  if (fhpfewhpofe > 1000)
  {
    // Whatever
  }
}

function heapSpray(hoprwehjoprew, hoifwep43)
{
  for (jnpfw93=0;jnpfw93<hoifwep43;jnpfw93++)
  {
    hoprwehjoprew = hoprwehjoprew + hoprwehjoprew;
  }
}
                                                     23
Obfuscation with considering scope
function executePayload(grtertttrr, hnpfefwefee)
{
  if (hnpfefwefee > 1000)
  {
    // Whatever
  }
}

function heapSpray(grtertttrr, hnpfefwefee)
{
  for (hjnprew=0;hjnprew<hnpfefwefee;hjnprew++)
  {
    grtertttrr = grtertttrr + grtertttrr;
  }
}
                                                   24
Obfuscation: Going the whole way
function ____(____, _____)
{
  if (_____ > 1000)
  {
    // Whatever
  }
}

function _____(____, _____)
{
  for (______=0; ______<_____; ______++)
  {
    ____ = ____ + ____;
  }
}
                                           25
Name obfuscation: Lessons learned
• Consider name scope
  – Deobfuscator needs to know scoping rules too
• Use underscores
  – Drives human analysts crazy
• Also cute: Use meaningful names that have
  nothing to do with the variable
  – Maybe shuffle real variable names


                                                   26
Eval chains
• JavaScript code can execute JavaScript code in
  strings through eval
• Often used to hide later code stages which are
  decrypted on the fly
• Common way to extract argument: replace
  eval with a printing function



                                               27
Eval chains: Doing it better
• Make sure your later stages reference
  variables or functions from earlier stages
• Re-use individual eval statements multiple
  times to make sure eval calls can not just be
  replaced




                                                  28
JavaScript splitting
• JavaScript can be split over several PDF
  objects
• These scripts can be executed consecutively
• Context is preserved between scripts
• In the wild I‘ve seen splitting across 2-4
  objects



                                                29
JavaScript splitting: Doing it better
• One line of JavaScript per object
• Randomize the order of JavaScript objects
• Admittedly it takes only one script to sort and
  extract the scripts from the objects




                                                    30
Anti-emulation code
• Simple checks for Adobe Reader extensions
• Multistaged JavaScript code




                                              31
Current malware loads code from

Pages

Annotations

Info Dictionary
                                  32
Example: Loading code from
            annotations
y = app.doc;

y.syncAnnotScan();

var p = y["getAnnots"]({nPage: 0});

var s = p[0].subject;

eval(s);
                                  33
Problems with current approaches



    Code is         Easy to
   in the file      extract


                               34
Anti-emulation code: Improved
 Key ideas behind anti-emulation code

Find idiosyncrasies in the
Adobe JavaScript engine

Find extensions that are
difficult to emulate
                                        35
Exhibit A: Idiosyncrasy
cypher = [7, 17, 28, 93, 4, 10, 4, 30, 7, 77, 83, 72];
cypherLength = cypher.length;

hidden = "ThisIsNotTheKeyYouAreLookingFor";
hiddenLength = hidden.toString().length;

for(i=0,j=0;i<cypherLength;i++,j++)
{
  cypherChar = cypher[i];
  keyChar = hidden.toString().charCodeAt(j);
  cypher[i] = String.fromCharCode(cypherChar ^ keyChar);

    if (j == hiddenLength - 1)
      j = -1;
}

eval(cypher.join(""));
                                                           36
Exhibit A: Explained

  JavaScript Standard         Adobe Reader JavaScript

  hidden = false;              hidden = false;
  hidden = "Key";              hidden = "Key";




hidden has the value „Key“   hidden has the value „true“
                                                     37
Exhibit A: Explained
The Adobe Reader JavaScript engine
defines global variables that do not
change their type on assignment.


(I suspect this happens because they are backed by C++ code)




                                                               38
Exhibit B: Difficult to emulate
• Goal: Find Adobe JavaScript API functions
  which are nearly impossible to emulate
• Then use effects of these functions in sneaky
  ways to change malware behavior
• The Adobe Reader JavaScript documentation
  is your friend



                                                  39
Exhibit B: Difficult to emulate
       Functions to look for

Rendering engine

Forms extensions

Multimedia extensions
                                   40
Exhibit B: Difficult to emulate
crypt = "T^_]^[T IEYYD__ FuRRKBD ";
plain = Array();
key = getPageNthWordQuads(0, 0).toString().split(",")[1];

for (i=0,j=0;i<crypt.length;i++,j++)
{
   plain = plain + String.fromCharCode((crypt.charCodeAt(i) ^
key.charCodeAt(j)));

    if (j >= key.length)
        j = 0;
}

app.alert(plain);
)


                                                            41
Exhibit B: Difficult to emulate
       Functions to avoid


Anything with
security restrictions

                                   42
Exhibit C: Multi-threaded JavaScript
• Multi-threaded applications are difficult to
  reverse engineer
• Problem: There are no threads in JavaScript
• Solution: setTimeOut
• Example: Cooperative multi-threading with
  message-passing between objects



                                                 43
Basic idea
• Multiple server objects
• String messages are passed between servers
• Messages contain new timeout value and
  code to evaluate




                                               44
function Server(name)
{
  ...
}

s1 = new Server("S1");
s2 = new Server("S2");

s1.receive(ENCODED_MESSAGE);




                               45
function Server(name)
{
  this.name = name;

  this.receive = function(message)
  {
    recipient = parse_recipient(message)
    delayTime = parse_delay(message)
    eval_string = parse_eval_string(message)
    msg_string = parse_message_string(message)

     eval(eval_string);
     command = "recipient.receive('" + msg_string + "')";
     this.x = app.setTimeOut(command, delayTime);
}
};




                                                            46
How to improve this
• Use a global string object as the message
  queue and manipulate the object on the fly
• Usage of non-commutative operations so that
  execution order really matters
• Message broadcasting
• Add anti-emulation code to eval-ed code



                                            47
callee-trick
• Not specific to Adobe Reader
• Frequently used by JavaScript code in other
  contexts
• Function accesses its own source and uses it
  as a key to decrypt code or data
• Add a single whitespace and decryption fails



                                                 48
callee-trick Example
function decrypt(cypher)
{
  var key = arguments.callee.toString();

    for (var i = 0; i < cypher.length; i++)
    {
      plain = key.charCodeAt(i) ^ cypher.charCodeAt(i);
    }

    ...
}




                                                          49
More ideas for the future
• Combine anti-debugging, callee-trick, and
  message passing
• Find more JavaScript engine idiosyncracies:
  Sputnik JavaScript test suite




                                                50
Thanks
•   Didier Stevens
•   Julia Wolf
•   Peter Silberman
•   Bruce Dang




                               51
52
1 of 52

Recommended

Introduction to mobile reversing by
Introduction to mobile reversingIntroduction to mobile reversing
Introduction to mobile reversingjduart
10.7K views32 slides
ShaREing Is Caring by
ShaREing Is CaringShaREing Is Caring
ShaREing Is Caringsporst
1.3K views52 slides
Packer Genetics: The selfish code by
Packer Genetics: The selfish codePacker Genetics: The selfish code
Packer Genetics: The selfish codejduart
4.3K views35 slides
Bootstrapping iPhone Development by
Bootstrapping iPhone DevelopmentBootstrapping iPhone Development
Bootstrapping iPhone DevelopmentThoughtWorks
832 views23 slides
Learn To Test Like A Grumpy Programmer - 3 hour workshop by
Learn To Test Like A Grumpy Programmer - 3 hour workshopLearn To Test Like A Grumpy Programmer - 3 hour workshop
Learn To Test Like A Grumpy Programmer - 3 hour workshopchartjes
746 views42 slides
Assignment1 B 0 by
Assignment1 B 0Assignment1 B 0
Assignment1 B 0Mahmoud
319 views6 slides

More Related Content

What's hot

Php extensions by
Php extensionsPhp extensions
Php extensionsElizabeth Smith
736 views82 slides
Handout 00 0 by
Handout 00 0Handout 00 0
Handout 00 0Mahmoud
338 views5 slides
Wahckon[2] - iOS Runtime Hacking Crash Course by
Wahckon[2] - iOS Runtime Hacking Crash CourseWahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash Courseeightbit
274 views45 slides
Ch01 basic-java-programs by
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programsJames Brotsos
2.4K views52 slides
Pigaios: A Tool for Diffing Source Codes against Binaries (Hacktivity 2018) by
Pigaios: A Tool for Diffing Source Codes against Binaries (Hacktivity 2018)Pigaios: A Tool for Diffing Source Codes against Binaries (Hacktivity 2018)
Pigaios: A Tool for Diffing Source Codes against Binaries (Hacktivity 2018)Joxean Koret
363 views49 slides
Half-automatic Compilable Source Code Recovery by
Half-automatic Compilable Source Code RecoveryHalf-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code RecoveryJoxean Koret
541 views37 slides

What's hot(20)

Handout 00 0 by Mahmoud
Handout 00 0Handout 00 0
Handout 00 0
Mahmoud 338 views
Wahckon[2] - iOS Runtime Hacking Crash Course by eightbit
Wahckon[2] - iOS Runtime Hacking Crash CourseWahckon[2] - iOS Runtime Hacking Crash Course
Wahckon[2] - iOS Runtime Hacking Crash Course
eightbit274 views
Ch01 basic-java-programs by James Brotsos
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programs
James Brotsos2.4K views
Pigaios: A Tool for Diffing Source Codes against Binaries (Hacktivity 2018) by Joxean Koret
Pigaios: A Tool for Diffing Source Codes against Binaries (Hacktivity 2018)Pigaios: A Tool for Diffing Source Codes against Binaries (Hacktivity 2018)
Pigaios: A Tool for Diffing Source Codes against Binaries (Hacktivity 2018)
Joxean Koret363 views
Half-automatic Compilable Source Code Recovery by Joxean Koret
Half-automatic Compilable Source Code RecoveryHalf-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code Recovery
Joxean Koret541 views
C++ to java by Ajmal Ak
C++ to javaC++ to java
C++ to java
Ajmal Ak2.4K views
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version) by Alex Balhatchet
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Alex Balhatchet1.2K views
Net serialization by Greg Sohl
Net serializationNet serialization
Net serialization
Greg Sohl407 views
Object Oriented Apologetics by Vance Lucas
Object Oriented ApologeticsObject Oriented Apologetics
Object Oriented Apologetics
Vance Lucas1.3K views
Metaprogramming JavaScript by danwrong
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
danwrong43.6K views
Clean Code summary by Jan de Vries
Clean Code summaryClean Code summary
Clean Code summary
Jan de Vries19.3K views
Basic buffer overflow part1 by Payampardaz
Basic buffer overflow part1Basic buffer overflow part1
Basic buffer overflow part1
Payampardaz278 views
Call Graph Agnostic Malware Indexing (EuskalHack 2017) by Joxean Koret
Call Graph Agnostic Malware Indexing (EuskalHack 2017)Call Graph Agnostic Malware Indexing (EuskalHack 2017)
Call Graph Agnostic Malware Indexing (EuskalHack 2017)
Joxean Koret2.3K views
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips by Felipe Prado
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tipsDEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
Felipe Prado98 views

Viewers also liked

0-knowledge fuzzing white paper by
0-knowledge fuzzing white paper0-knowledge fuzzing white paper
0-knowledge fuzzing white paperVincenzo Iozzo
1.6K views12 slides
ShaREing is Caring by
ShaREing is CaringShaREing is Caring
ShaREing is Caringzynamics GmbH
2.6K views52 slides
0-knowledge fuzzing by
0-knowledge fuzzing0-knowledge fuzzing
0-knowledge fuzzingVincenzo Iozzo
1.6K views71 slides
Uni mannheim debuggers by
Uni mannheim debuggersUni mannheim debuggers
Uni mannheim debuggerszynamics GmbH
1.7K views53 slides
Formale Methoden im Reverse Engineering by
Formale Methoden im Reverse EngineeringFormale Methoden im Reverse Engineering
Formale Methoden im Reverse Engineeringzynamics GmbH
1.2K views66 slides
Architectural Diversity (German) by
Architectural Diversity (German)Architectural Diversity (German)
Architectural Diversity (German)zynamics GmbH
2.1K views40 slides

Viewers also liked(6)

0-knowledge fuzzing white paper by Vincenzo Iozzo
0-knowledge fuzzing white paper0-knowledge fuzzing white paper
0-knowledge fuzzing white paper
Vincenzo Iozzo1.6K views
Uni mannheim debuggers by zynamics GmbH
Uni mannheim debuggersUni mannheim debuggers
Uni mannheim debuggers
zynamics GmbH1.7K views
Formale Methoden im Reverse Engineering by zynamics GmbH
Formale Methoden im Reverse EngineeringFormale Methoden im Reverse Engineering
Formale Methoden im Reverse Engineering
zynamics GmbH1.2K views
Architectural Diversity (German) by zynamics GmbH
Architectural Diversity (German)Architectural Diversity (German)
Architectural Diversity (German)
zynamics GmbH2.1K views

Similar to How to really obfuscate your pdf malware

Polyglot and Poly-paradigm Programming for Better Agility by
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
2.2K views90 slides
Fundamentals of java --- version 2 by
Fundamentals of java --- version 2Fundamentals of java --- version 2
Fundamentals of java --- version 2Uday Sharma
2.9K views19 slides
Anti patterns part 2 by
Anti patterns part 2Anti patterns part 2
Anti patterns part 2Return on Intelligence
4.4K views46 slides
The operation principles of PVS-Studio static code analyzer by
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerAndrey Karpov
624 views33 slides
How to write good quality code by
How to write good quality codeHow to write good quality code
How to write good quality codeHayden Bleasel
882 views50 slides
Anti patterns part 2 by
Anti patterns part 2Anti patterns part 2
Anti patterns part 2Return on Intelligence
710 views46 slides

Similar to How to really obfuscate your pdf malware(20)

Polyglot and Poly-paradigm Programming for Better Agility by elliando dias
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
elliando dias2.2K views
Fundamentals of java --- version 2 by Uday Sharma
Fundamentals of java --- version 2Fundamentals of java --- version 2
Fundamentals of java --- version 2
Uday Sharma2.9K views
The operation principles of PVS-Studio static code analyzer by Andrey Karpov
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
Andrey Karpov624 views
How to write good quality code by Hayden Bleasel
How to write good quality codeHow to write good quality code
How to write good quality code
Hayden Bleasel882 views
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194... by Nilesh Panchal
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Nilesh Panchal5K views
Search for Vulnerabilities Using Static Code Analysis by Andrey Karpov
Search for Vulnerabilities Using Static Code AnalysisSearch for Vulnerabilities Using Static Code Analysis
Search for Vulnerabilities Using Static Code Analysis
Andrey Karpov364 views
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0 by Marcel Bruch
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0
JUG Münster 2014 - Code Recommenders & Codetrails - Wissenstransfer 2.0
Marcel Bruch824 views
Groovy In the Cloud by Jim Driscoll
Groovy In the CloudGroovy In the Cloud
Groovy In the Cloud
Jim Driscoll1.9K views
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017 by Andrey Karpov
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
Andrey Karpov3.8K views
Exciting JavaScript - Part II by Eugene Lazutkin
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part II
Eugene Lazutkin1.7K views
Documenting Bugs in Doxygen by PVS-Studio
Documenting Bugs in DoxygenDocumenting Bugs in Doxygen
Documenting Bugs in Doxygen
PVS-Studio165 views

More from zynamics GmbH

How to really obfuscate your pdf malware by
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malwarezynamics GmbH
1.6K views52 slides
Architectural Diversity (German) by
Architectural Diversity (German)Architectural Diversity (German)
Architectural Diversity (German)zynamics GmbH
556 views40 slides
Introduction to mobile reversing by
Introduction to mobile reversingIntroduction to mobile reversing
Introduction to mobile reversingzynamics GmbH
963 views32 slides
0-knowledge fuzzing white paper by
0-knowledge fuzzing white paper0-knowledge fuzzing white paper
0-knowledge fuzzing white paperzynamics GmbH
488 views12 slides
Inbot10 vxclass by
Inbot10 vxclassInbot10 vxclass
Inbot10 vxclasszynamics GmbH
664 views26 slides
0-knowledge fuzzing by
0-knowledge fuzzing0-knowledge fuzzing
0-knowledge fuzzingzynamics GmbH
390 views71 slides

More from zynamics GmbH(6)

How to really obfuscate your pdf malware by zynamics GmbH
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malware
zynamics GmbH1.6K views
Architectural Diversity (German) by zynamics GmbH
Architectural Diversity (German)Architectural Diversity (German)
Architectural Diversity (German)
zynamics GmbH556 views
Introduction to mobile reversing by zynamics GmbH
Introduction to mobile reversingIntroduction to mobile reversing
Introduction to mobile reversing
zynamics GmbH963 views
0-knowledge fuzzing white paper by zynamics GmbH
0-knowledge fuzzing white paper0-knowledge fuzzing white paper
0-knowledge fuzzing white paper
zynamics GmbH488 views

Recently uploaded

Democratising digital commerce in India-Report by
Democratising digital commerce in India-ReportDemocratising digital commerce in India-Report
Democratising digital commerce in India-ReportKapil Khandelwal (KK)
18 views161 slides
Five Things You SHOULD Know About Postman by
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About PostmanPostman
36 views43 slides
Future of Indian ConsumerTech by
Future of Indian ConsumerTechFuture of Indian ConsumerTech
Future of Indian ConsumerTechKapil Khandelwal (KK)
22 views68 slides
MVP and prioritization.pdf by
MVP and prioritization.pdfMVP and prioritization.pdf
MVP and prioritization.pdfrahuldharwal141
31 views8 slides
Voice Logger - Telephony Integration Solution at Aegis by
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at AegisNirmal Sharma
39 views1 slide
Case Study Copenhagen Energy and Business Central.pdf by
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdfAitana
16 views3 slides

Recently uploaded(20)

Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman36 views
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma39 views
Case Study Copenhagen Energy and Business Central.pdf by Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 views
Powerful Google developer tools for immediate impact! (2023-24) by wesley chun
Powerful Google developer tools for immediate impact! (2023-24)Powerful Google developer tools for immediate impact! (2023-24)
Powerful Google developer tools for immediate impact! (2023-24)
wesley chun10 views
Future of AR - Facebook Presentation by ssuserb54b561
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
ssuserb54b56115 views
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2218 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive

How to really obfuscate your pdf malware

  • 1. How to really obfuscate your PDF malware Sebastian Porst - ReCon 2010 Email: sebastian.porst@zynamics.com Twitter: @LambdaCube 1
  • 2. Targeted Attacks 2008 Adobe Acrobat Microsoft Word; Reader; 28.61% 34.55% Microsoft PowerPoint; Microsoft Excel; 16.87% 19.97% http://www.f-secure.com/weblog/archives/00001676.html 2
  • 3. Targeted Attacks 2009 Adobe Acrobat Microsoft Word; Reader; 48.87% 39.22% Microsoft Microsoft PowerPoint; Excel; 7.39% 4.52% 3
  • 4. Exploited in the wild CVE- CVE- CVE- CVE- 2007- 2009- 2009- 2009- 5659 0658 1492 4324 CVE- CVE- CVE- CVE- 2008- 2009- 2009- 2010- 2992 0927 3459 0188
  • 5. Four common exploit paths Broken PDF Parser Vulnerable JavaScript Engine Vulnerable external libraries /Launch 5
  • 6. PDF Malware Obfuscation Different tricks for different purposes Make manual analysis more difficult Resist automated analysis Avoid detection by virus scanners 6
  • 7. PDF Malware Obfuscation Conflicting goals Avoid detection Make analysis by being difficult by being wellformed malformed 7
  • 8. How to achieve these goals Being harmless Being evil • Avoid JavaScript • Use heavy • Do not use unusual obfuscation encodings • Try to break tools • Do not try to break parser-based tools • Ideally use an 0-day 8
  • 11. Rule #1: Do the unexpected 11
  • 12. This is what tools expect • ASCII Strings • Boring encodings like #41 instead of A • Wellformed or only moderately malformed PDF file structure 12
  • 13. Malformed documents • Adobe Reader tries to load malformed PDF files • Very, very liberal interpretation of the PDF specification • Parser-based analysis tools need to know about Adobe Reader file correction 13
  • 14. Malformed PDF file – Example I 7 0 obj << /Type /Action /S /JavaScript /JS (app.alert('whatever');) >> endobj 14
  • 15. Malformed PDF file – Example II 5 0 obj << /Length 45 >> stream some data endstream endobj 15
  • 18. Goal of JavaScript obfuscation Hide the shellcode 18
  • 19. JavaScript obfuscation in the wild • Screwed up formatting • Name obfuscation • Eval-chains • Splitting JavaScript code • Simple anti-emulation techniques • callee-trick • ... 19
  • 20. Screwed up formatting • Basically just remove all newlines • Completely useless: jsbeautifier.org 20
  • 21. Name obfuscation • Variables or function names are renamed to hide their meaning • Most JavaScript obfuscators screw this up 21
  • 22. Obfuscation example: Original code function executePayload(payload, delay) { if (delay > 1000) { // Whatever } } function heapSpray(code, repeat) { for (i=0;i<repeat;i++) { code = code + code; } } 22
  • 23. Obfuscation without considering scope function executePayload(hkof3ewhoife, fhpfewhpofe) { if (fhpfewhpofe > 1000) { // Whatever } } function heapSpray(hoprwehjoprew, hoifwep43) { for (jnpfw93=0;jnpfw93<hoifwep43;jnpfw93++) { hoprwehjoprew = hoprwehjoprew + hoprwehjoprew; } } 23
  • 24. Obfuscation with considering scope function executePayload(grtertttrr, hnpfefwefee) { if (hnpfefwefee > 1000) { // Whatever } } function heapSpray(grtertttrr, hnpfefwefee) { for (hjnprew=0;hjnprew<hnpfefwefee;hjnprew++) { grtertttrr = grtertttrr + grtertttrr; } } 24
  • 25. Obfuscation: Going the whole way function ____(____, _____) { if (_____ > 1000) { // Whatever } } function _____(____, _____) { for (______=0; ______<_____; ______++) { ____ = ____ + ____; } } 25
  • 26. Name obfuscation: Lessons learned • Consider name scope – Deobfuscator needs to know scoping rules too • Use underscores – Drives human analysts crazy • Also cute: Use meaningful names that have nothing to do with the variable – Maybe shuffle real variable names 26
  • 27. Eval chains • JavaScript code can execute JavaScript code in strings through eval • Often used to hide later code stages which are decrypted on the fly • Common way to extract argument: replace eval with a printing function 27
  • 28. Eval chains: Doing it better • Make sure your later stages reference variables or functions from earlier stages • Re-use individual eval statements multiple times to make sure eval calls can not just be replaced 28
  • 29. JavaScript splitting • JavaScript can be split over several PDF objects • These scripts can be executed consecutively • Context is preserved between scripts • In the wild I‘ve seen splitting across 2-4 objects 29
  • 30. JavaScript splitting: Doing it better • One line of JavaScript per object • Randomize the order of JavaScript objects • Admittedly it takes only one script to sort and extract the scripts from the objects 30
  • 31. Anti-emulation code • Simple checks for Adobe Reader extensions • Multistaged JavaScript code 31
  • 32. Current malware loads code from Pages Annotations Info Dictionary 32
  • 33. Example: Loading code from annotations y = app.doc; y.syncAnnotScan(); var p = y["getAnnots"]({nPage: 0}); var s = p[0].subject; eval(s); 33
  • 34. Problems with current approaches Code is Easy to in the file extract 34
  • 35. Anti-emulation code: Improved Key ideas behind anti-emulation code Find idiosyncrasies in the Adobe JavaScript engine Find extensions that are difficult to emulate 35
  • 36. Exhibit A: Idiosyncrasy cypher = [7, 17, 28, 93, 4, 10, 4, 30, 7, 77, 83, 72]; cypherLength = cypher.length; hidden = "ThisIsNotTheKeyYouAreLookingFor"; hiddenLength = hidden.toString().length; for(i=0,j=0;i<cypherLength;i++,j++) { cypherChar = cypher[i]; keyChar = hidden.toString().charCodeAt(j); cypher[i] = String.fromCharCode(cypherChar ^ keyChar); if (j == hiddenLength - 1) j = -1; } eval(cypher.join("")); 36
  • 37. Exhibit A: Explained JavaScript Standard Adobe Reader JavaScript hidden = false; hidden = false; hidden = "Key"; hidden = "Key"; hidden has the value „Key“ hidden has the value „true“ 37
  • 38. Exhibit A: Explained The Adobe Reader JavaScript engine defines global variables that do not change their type on assignment. (I suspect this happens because they are backed by C++ code) 38
  • 39. Exhibit B: Difficult to emulate • Goal: Find Adobe JavaScript API functions which are nearly impossible to emulate • Then use effects of these functions in sneaky ways to change malware behavior • The Adobe Reader JavaScript documentation is your friend 39
  • 40. Exhibit B: Difficult to emulate Functions to look for Rendering engine Forms extensions Multimedia extensions 40
  • 41. Exhibit B: Difficult to emulate crypt = "T^_]^[T IEYYD__ FuRRKBD "; plain = Array(); key = getPageNthWordQuads(0, 0).toString().split(",")[1]; for (i=0,j=0;i<crypt.length;i++,j++) { plain = plain + String.fromCharCode((crypt.charCodeAt(i) ^ key.charCodeAt(j))); if (j >= key.length) j = 0; } app.alert(plain); ) 41
  • 42. Exhibit B: Difficult to emulate Functions to avoid Anything with security restrictions 42
  • 43. Exhibit C: Multi-threaded JavaScript • Multi-threaded applications are difficult to reverse engineer • Problem: There are no threads in JavaScript • Solution: setTimeOut • Example: Cooperative multi-threading with message-passing between objects 43
  • 44. Basic idea • Multiple server objects • String messages are passed between servers • Messages contain new timeout value and code to evaluate 44
  • 45. function Server(name) { ... } s1 = new Server("S1"); s2 = new Server("S2"); s1.receive(ENCODED_MESSAGE); 45
  • 46. function Server(name) { this.name = name; this.receive = function(message) { recipient = parse_recipient(message) delayTime = parse_delay(message) eval_string = parse_eval_string(message) msg_string = parse_message_string(message) eval(eval_string); command = "recipient.receive('" + msg_string + "')"; this.x = app.setTimeOut(command, delayTime); } }; 46
  • 47. How to improve this • Use a global string object as the message queue and manipulate the object on the fly • Usage of non-commutative operations so that execution order really matters • Message broadcasting • Add anti-emulation code to eval-ed code 47
  • 48. callee-trick • Not specific to Adobe Reader • Frequently used by JavaScript code in other contexts • Function accesses its own source and uses it as a key to decrypt code or data • Add a single whitespace and decryption fails 48
  • 49. callee-trick Example function decrypt(cypher) { var key = arguments.callee.toString(); for (var i = 0; i < cypher.length; i++) { plain = key.charCodeAt(i) ^ cypher.charCodeAt(i); } ... } 49
  • 50. More ideas for the future • Combine anti-debugging, callee-trick, and message passing • Find more JavaScript engine idiosyncracies: Sputnik JavaScript test suite 50
  • 51. Thanks • Didier Stevens • Julia Wolf • Peter Silberman • Bruce Dang 51
  • 52. 52