Scripting

- Script Manager

- Script Category Tree

- Displays dynamic tree of categories

- Script Table

- Displays name, description, key binding

- Filter

- Matches filter to name or description
- Wildcard and case-insensitive

Scripting

- Run Script

- Click the RUN button
- Double-click on the row in the script table

Scripting

- Edit Script

- Click the Edit Script with basic editor button
- Make a change
- Click the SAVE or SAVE AS button

- Exercise

- Edit the HelloWorldScript.java to print "Hello Ghidra Student"
- Verify the output in the console

Scripting

- Assign Key Binding

- Allows scripts to run from anywhere in Ghidra

- Delete Script

- Deletes the selected script(s)
- System scripts cannot be deleted

- Rename script

Scripting

- Create New Script

- Click the NEW button
- In the New Script dialog

- Select a script type (if applicable)
- Select a directory (if applicable)
- Enter a script name
- Click OK button

Scripting

| Sample script template in Java Must fill in the TODO areas Create a description Fill in the run() method |

Scripting

- Refresh Script List

- Refreshes script manager
- Use it when change script category
- Needed when script development occurs outside Ghidra

- For example, using emacs for script development

Scripting

- Script Directories

- Allows management of script directories
- Default directories

- <HomeDirectory>/ghidra_scripts

- Useful for sharing scripts in multi-user

Scripting

- Help

- Opens javadoc for GhidraScript base class
- Provides access to javadoc for the entire Ghidra API

Scripting

- Exercise

1. Create a new Java script
MyClassScript.java
2. Set the description
3. Change the body of the run() method to
public void run() {
println("hello class");
}
4. Save it
5. Run it
6. Assign a keybinding of ctrl-5
7. Re-run the script using the key binding

Scripting

- Script Meta-data

- Special tags in header comment
- Describe the script
- All are optional
- Handle all the messy Java GUI stuff (buttons, menus, etc)
- Do not insert blank lines between meta-data

Scripting

- Script Meta-data

- @category

- The category path for the script
- Levels are separated by "."
- Example

- @category A.B.C

Scripting

- Script Meta-data

- @keybinding

- Default key binding for a script
- Format is [ctrl] [alt] [shift] [A-Z,0-9,F1-F12] and is case-sensitive
- Examples

- @keybinding L
- @keybinding ctrl alt shift F1
- @keybinding ctrl shift COMMA

Scripting

- Script Meta-data

- @menupath

- Top-level menu path for a script
- Use with caution!

- Overcrowded menu
- Collide with system action

- Example

- @menupath File.Run.My Script

Scripting

- Script Meta-data

- @toolbar

- Image for top-level toolbar button to launch this script
- Searches for image in script directories and then Ghidra installation directory
- Also use with caution! (same as @menupath)
- Example

- @toolbar myScriptImage.gif

Scripting

- Script Meta-data Exercise

- In MyClassScript.java

- Set category to Category A.Category B
- Set key binding to alt shift 6
- Set menu path to Script.My Class Script
- Set toolbar button to Info.png

Scripting

- Script Meta-data Exercise Solution

            //This is my class script.
         //It prints "hello class" to the console.
         //@category Category A.Category B
         //@keybinding alt shift 6
         //@menupath Script.My Class Script
         //@toolbar Info.png

         import ghidra.app.script.GhidraScript;

         public class MyClassScript extends GhidraScript {
             public void run() throws Exception {
                 println("hello class");
             }
         }

Scripting

- Console

- Provides a place to dump information
- Any text that represents a symbol or address can be navigated by double-clicking
- Example

- Run the PropagateExternalParameters.java script

Scripting

Ghidra Program API Object-oriented Very deep Can change from version to version | Program Listing Instruction Data Function Comments ... Memory Memory Blocks Bytes Symbol Table Symbol Reference Manager Reference

Scripting

- Script API

- Flat
- Provides access to most common features
- Is not complete
- Will not change on you

Scripting

- Script API

           public abstract class GhidraScript {
             ask...()
             create...()
             find...()
             get...()
             remove...()
             runScript()
             set...()
             to...()
         }

Scripting

- Script State

- currentProgram

- The current active open program

- currentAddress

- The current address of the location of the cursor

- currentLocation

- The program location of the cursor

Scripting

- Script State (continued)

- currentSelection

- The current selection or null if no selection exists

- currentHighlight

- The current highlight or null if no highlight exists

- state

- Encapsulates script state
- Allows script state to be passed to other called scripts
- Provides place to store environment variables

Scripting

- Script State (continued)

- monitor

- Allows script writer to inform user

- messages and progress

- Allows user to cancel script
- Always use inside loops

    while (!monitor.isCancelled()) {
      ...
    }
      for (int i = 0; i < max(); ++i) {
        if (monitor.isCancelled()) {
          break;
        }
      }
        inside loop:

        monitor.checkCancelled();

Scripting

- Eclipse

- Integrated Development Environment (IDE) for Java, Python, C/C++, etc.
- Highly recommended for Ghidra script development

- Officially supported by Ghidra
- Makes development significantly faster and easier

Scripting

- GhidraDev Eclipse plugin

- Provides an interface between Eclipse and Ghidra
- Quickly create and manage Ghidra script and module projects
- Can be installed into Eclipse manually or automatically by Ghidra
- Plugin and documentation found at <GhidraInstall>/Extensions/
  Eclipse/GhidraDev/

Scripting

- Edit Script with Eclipse

- Click the Edit Script with Eclipse button
- Click Yes to point Ghidra at Eclipse
- Enter path to pre-installed Eclipse Installation Directory
- Remaining options can use default values
- Click OK to save changes and launch Eclipse
- Choose Eclipse workspace (default recommended)
- GhidraDev plugin automatically starts during Eclipse initialization (more on next slide)

Scripting

- GhidraDev New Script Project Wizard

- Automatically started if a Ghidra Script Project does not exist
- Allows customization of Ghidra script project
- Click Finish to use default wizard settings (recommended)
OR
- Click Next to see advanced project customization options

Scripting

Editing in Eclipse Package Explorer Projects Source Folders Packages Libraries Non-source folders Resources |

Scripting

Editing in Eclipse Outline Methods Public, Protected, Private, Default Fields Instance, Static Import Statements |

Scripting

Editing in Eclipse Hierarchy Super-class Entire sub-class hierarchy |

Scripting

- Editing in Eclipse

- Java Editor

Scripting

- Eclipse Java Editor Tips and Tricks

- Open Type (Control-Shift-T)

- Allows you to find a class without knowing package

- Organize Imports (Control-Shift-O)

- Automatically fixes import statements

- Navigation (F3)

- Navigate to the class or method at the current cursor location

- Object Hierarchy (F4)

- Show the object inheritance hierarchy of current object

Scripting

- Eclipse Java Editor Tips and Tricks (continued)

- Find References (Control-Shift-G)

- Finds all the places that reference the object at the current cursor location

- Toggle Comments (Control-/)

- Convert selection to comments, or uncomment the selection

- Outline View (Control-O)

- Lists methods of the class

- Code Completion (Control-SPACE)

- Displays a list of matches to completion current expression

Scripting

- Eclipse Java Editor Tips and Tricks (continued)

- Quick Fix (Control-1)

- Eclipse editor can offer corrections to certain problems underline with a highlight line

Scripting

- Running Scripts

- Scripts are always run from the Ghidra Script Manager, even if they are created/edited in Eclipse
- Any open Ghidra will be able to find and run your script
  - No need to launch a new instance of Ghidra
  - The Script Manager may need to be refreshed in order to discover new scripts that were created outside of the Script Manager

Scripting

- Debugging in Eclipse

- Launch Ghidra project in debug mode (bug icon)

- Note: Any open instances of Ghidra must be closed before launching a new instance of Ghidra from Eclipse

- When debugging, scripts are still launched from the Ghidra Script Manager
- Not only can Ghidra scripts be debugged, but so can all of Ghidra!

- To see this, simply "Step Into" any call you make to the Ghidra API.

Scripting

Eclipse Debug window allows you to control the process and threads Execution Control Commands Resume Suspend Terminate Step Into Step Over Step Return |

Scripting

- Eclipse Breakpoints window display all existing breakpoints

- Remove and modify breakpoints
- All breakpoints global

- Across projects and processes

Scripting

- Breakpoints are created by right-clicking on the left margin of the Eclipse editor and selecting Toggle Breakpoint
- Ctrl-Shift-B

Scripting

- Eclipse Variables window displays variables within scope of the selected thread

- Variables can be inspected and modified from within this window

Scripting

- Script API Example

- Create new script that will ask for an integer and print the current program’s name that many times to the console.

Scripting

- Script API Example Solution

            public class PrintProgramScript extends GhidraScript {
           public void run() {
             int n = askInt( "How many times?" ,  "N" );
             for ( int i = 0 ; i < n ; ++i ) {
               if ( monitor.isCancelled() ) {
                 break;
               }
               println( i + ")" + currentProgram.getName() );
               Thread.sleep( 1000 );
             }
           }
         }

Scripting

- Eclipse Exercise

- Debug PrintProgramScript

- Use breakpoints
- Inspect and modify variables
- Use execution control commands

Scripting

- Python support in Ghidra

- Based on Jython, a Java-based Python implementation

- Jython 2.7.1
- Full generic Java API access from Python
- Full access to Ghidra's Java API

- Eclipse support with GhidraDev + PyDev plugins

- PyDev must be independently acquired and installed. See GhidraDev_README.html for more info.

- Ghidra Python Interpreter plugin

- Click Window -> Python

Scripting

- Python Interpreter plugin

- Tightly tied to tool's currently open program
- Issue commands one at a time
- Excellent way to experiment with scripting API
- Ghidra scripting API automatically imported

- Must manually import other Ghidra classes not contained in scripting API

- Type help(item_name) to see API help for a particular script class or method
- Press TAB for code completion on partially typed variable/function
- Hit F1 in interpreter window for more tips and help

Scripting

- Python Interpreter Example

- Print memory block information

      Python Interpreter for Ghidra
      Based on Jython version 2.7.1 (default:0df7adb1b397, Jun 30 2017, 19:02:43)
      [Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)]
      Press 'F1' for usage instructions
      >>>
      >>> mem = currentProgram.getMemory()
      >>> for block in mem.getBlocks():
      ...   print block.getName() + ", " + hex(block.getSize())
      ...
      Headers, 0x400L
      .textbss, 0x10000L
      .text, 0x4b57L
      .rdata, 0x1ed6L
      .data, 0x200L
      .data, 0x384L
      .idata, 0x8b7L
      .rsrc, 0x1b4L
      .reloc, 0x48fL

Scripting

- Python Interpreter Exercise

1. Make a selection in your program with your mouse
2. Ask the user for an address using the GhidraScript API
3. Determine if the current selection contains the address entered by the user

- Hints:
  - Use TAB-completion to figure out how to ask the user for an address
  - Use the help() command on currentSelection to find and use a function that checks if a program selection contains an address

Scripting

- Python Interpreter Exercise Solution

        Python Interpreter for Ghidra
        Based on Jython version 2.7.1 (default:0df7adb1b397, Jun 30 2017, 19:02:43)
        [Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)]
        Press 'F1' for usage instructions
        >>>
        >>> currentSelection
        ProgramSelection: [[01022362, 01022379] ]
        >>> addr = askAddress("Address", "Enter an address")
        >>> addr
        0102236b
        >>> currentSelection.contains(addr)
        True
        >>> addr = askAddress("Address", "Enter an address")
        >>> addr
        00000000
        >>> currentSelection.contains(addr)
        False