Coder Social home page Coder Social logo

bootleg / ret-sync Goto Github PK

View Code? Open in Web Editor NEW
1.9K 50.0 255.0 2.73 MB

ret-sync is a set of plugins that helps to synchronize a debugging session (WinDbg/GDB/LLDB/OllyDbg2/x64dbg) with IDA/Ghidra/Binary Ninja disassemblers.

License: GNU General Public License v3.0

Python 19.73% C++ 14.28% C 57.16% CSS 0.34% HTML 0.11% Java 8.37%
reverse-engineering debugger disassembler software-analysis ida-pro ghidra ida-plugin binaryninja

ret-sync's Introduction

ret-sync

ret-sync stands for Reverse-Engineering Tools SYNChronization. It is a set of plugins that help to synchronize a debugging session (WinDbg/GDB/LLDB/OllyDbg/OllyDbg2/x64dbg) with a disassembler (IDA/Ghidra/Binary Ninja). The underlying idea is simple: take the best from both worlds (static and dynamic analysis).

Debuggers and dynamic analysis provide us with:

  • local view, with live dynamic context (registers, memory, etc.)
  • built-in specialized features/API (ex: WinDbg's !peb, !drvobj, !address, etc.)

Disassemblers and static analysis provide us with:

  • macro view over modules
  • code analysis, signatures, types, etc.
  • fancy graph view
  • decompilation
  • persistent storage of knowledge within IDBs/GPRs

Key features:

  • synchronize graph and decompilation views with debugger's state
  • no need to deal with ASLR, addresses are rebased on-the-fly
  • pass data (comment, command output) from debugger to disassembler
  • multiple IDBs/GPRs can be synced at the same time allowing to easily trace through multiple modules
  • disassembler and debugger can be on different hosts / VMs

ret-sync is a fork of qb-sync that I developed and maintained during my stay at Quarkslab.


Table of contents


Repository content

The debugger plugins:

  • ext_windbg/sync: WinDbg extension source files, once built: sync.dll
  • ext_gdb/sync.py: GDB plugin
  • ext_lldb/sync.py: LLDB plugin
  • ext_olly1: OllyDbg 1.10 plugin
  • ext_olly2: OllyDbg v2 plugin
  • ext_x64dbg: x64dbg plugin

The disassembler plugins:

  • ext_ida/SyncPlugin.py
  • ext_ghidra/dist/ghidra_*_retsync.zip: Ghidra plugin
  • ext_bn/retsync: Binary Ninja plugin

And the library plugin:

  • ext_lib/sync.py: standalone Python library

General prerequisites

IDA and GDB plugins require a valid Python setup. Python 2 (>=2.7) and Python 3 are supported.

Binary release

Pre-built binaries for WinDbg/OllyDbg/OllyDbg2/x64dbg debuggers are proposed through an Azure DevOps pipeline: Build Status

Select the last build and check the artifacts under the Related section: 6 published.

A pre-built plugin archive of the Ghidra plugin is provided in ext_ghidra/dist.

ret-sync configuration

ret-sync should work out of the box for most users with a typical setup: debugger and disassembler(s) on the same host, module names matching.

Still, in some scenarios a specific configuration may be used. For that, extensions and plugins check for an optional global configuration file named .sync in the user's home directory. It must be a valid .INI file.

Additionally, the IDA and Ghidra plugins also look for the configuration file in the IDB or project directory (<project>.rep) first to allow local, per-IDB/project, settings. If a local configuration file is present, the global configuration file is ignored.

Values declared in these configuration files override default values. Please note, that no .sync file is created by default.

Below we detail, three common scenarios where a configuration file is useful/needed:

  • Remote debugging
  • Modules names mismatch
  • Missing PID

Remote debugging: debugger and disassembler are on different hosts

The [INTERFACE] section is used to customize network related settings. Let's suppose one wants to synchronize IDA with a debugger running inside a virtual machine (or simply another host), common remote kernel debugging scenario.

Simply create two .sync file:

  • one on the machine where IDA is installed, in the IDB directory:
  • For Ghidra, place at home directory, ex. "/home/user" or "C:\Users\user".
[INTERFACE]
host=192.168.128.1
port=9234

It tells ret-sync IDA plugin to listen on the interface 192.168.128.1 with port 9234. It goes without saying that this interface must be reachable from the remote host or virtual machine.

  • one on the machine where the debugger is executed, in the user's home directory:
[INTERFACE]
host=192.168.128.1
port=9234

It tells ret-sync debugger plugin to connect to the ret-sync IDA plugin configured previously to listen in this interface.

NOTE: You must specify a real IP here, and not use 0.0.0.0. This is because the variable is used by multiple sources both for binding and connecting, so using 0.0.0.0 will result in weird errors.

IDB and debugger modules names are different

[ALIASES]
ntoskrnl_vuln.exe=ntkrnlmp.exe

The [ALIASES] section is used to customize the name which is used by a disassembler (IDA/Ghidra) to register a module to its dispatcher/program manager.

By default, disassembler plugins use the name of the input file. However one may have renamed the file beforehand and it doesn't match anymore the name of the actual process or loaded module as seen by the debugger.

Here we simply tell to the dispatcher to match the name ntkrnlmp.exe (real name) instead of ntoskrnl_vuln.exe (IDB name).

gdb with Qt Creator debugging frontend

The Qt Creator debugging frontend changes the way gdb command output is logged. Since this would interfere with the synchronization an option exists to use the raw gdb output for synchronization instead of a temporary file. In the .sync configuration file use

[GENERAL]
use_tmp_logging_file=false

if you wish to use the Qt debugging frontend for the target.

Embedded devices and missing /proc/<pid>/maps

In some scenarios, such as debugging embedded devices over serial or raw firmware in QEMU, gdb is not aware of the PID and cannot access /proc/<pid>/maps.

In these cases, The [INIT] section is used to pass a custom context to the plugin. It allows overriding some fields such as the PID and memory mappings.

.sync content extract:

[INIT]
context = {
      "pid": 200,
      "mappings": [ [0x400000, 0x7A81158, 0x7681158, "asav941-200.qcow2|lina"] ]
  }

Each entry in the mappings is: mem_base, mem_end, mem_size, mem_name.

Bypassing automatic address rebasing

In some scenarios, such as debugging embedded devices or connecting to minimalist debug interfaces, it may be more convenient to bypass the automatic address rebasing feature implemented in the disassembler plugins.

The use_raw_addr option is currently supported only for Ghidra. In the .sync configuration file use:

[GENERAL]
use_raw_addr=true

Installation

IDA extension

IDA prerequisites

IDA 7.x branch is required. For older versions (6.9x) please see archived release ida6.9x.

Install the IDA extension

For IDA installation, copy Syncplugin.py and retsync folder from ext_ida to IDA plugins directory, for example:

  • C:\Program Files\IDA Pro 7.4\plugins
  • %APPDATA%\Hex-Rays\IDA Pro\plugins
  • ~/.idapro/plugins

Run the IDA extension

  1. Open IDB
  2. Run the plugin in IDA (Alt-Shift-S) or Edit -> Plugins -> ret-sync
[sync] default idb name: ld.exe
[sync] sync enabled
[sync] cmdline: "C:\Program Files\Python38\python.exe" -u "C:\Users\user\AppData\Roaming\Hex-Rays\IDA Pro\plugins\retsync\broker.py" --idb "target.exe"
[sync] module base 0x100400000
[sync] hexrays #7.3.0.190614 found
[sync] broker started
[sync] plugin loaded
[sync] << broker << dispatcher not found, trying to run it
[sync] << broker << dispatcher now runs with pid: 6544
[sync] << broker << connected to dispatcher
[sync] << broker << listening on port 63107

IDA plugin troubleshooting

To troubleshoot issues with the IDA extension two options are available in the file retsync/rsconfig.py:

LOG_LEVEL = logging.INFO
LOG_TO_FILE_ENABLE = False

Setting LOG_LEVEL value to logging.DEBUG makes the plugin more verbose.

Setting LOG_TO_FILE_ENABLE value to True triggers the logging of exception information from broker.py and dispatcher.py into dedicated files. Log file are generated in the %TMP% folder with a name pattern retsync.%s.err .

Ghidra extension

Build the Ghidra extension

Either use the pre-built version from the ext_ghidra/dist folder or follow the instruction to build it. Each extension build only supports the version of Ghidra specified in the plugin's file name. E.g. ghidra_9.1_PUBLIC_20191104_retsync.zip is for Ghidra 9.1 Public.

  1. Install Ghidra
  2. Install gradle
apt install gradle
  1. Build extension for your Ghidra installation (replace $GHIDRA_DIR with your installation directory)
cd ext_ghidra
gradle -PGHIDRA_INSTALL_DIR=$GHIDRA_DIR

Install the Ghidra extension

  1. From Ghidra projects manager: File -> Install Extensions..., click on the + sign and select the ext_ghidra/dist/ghidra_*_retsync.zip and click OK. This will effectively extract the retsync folder from the zip into $GHIDRA_DIR/Extensions/Ghidra/
  2. Restart Ghidra as requested
  3. After reloading Ghidra, open a module in CodeBrowser. It should tell you a new extension plugin has been detected. Select "yes" to configure it. Then tick "RetSyncPlugin" and click OK. The console should show something like:
[*] retsync init
[>] programOpened: tm.sys
    imageBase: 0x1c0000000
  1. From Ghidra CodeBrowser tool: use toolbar icons or shortcuts to enable (Alt+s)/disable (Alt+Shift+s)/restart (Alt+r) synchronization.

A status window is also available from Windows -> RetSyncPlugin. You generally want to drop it on the side to integrate it with the Ghidra environment windows.

Binary Ninja extension

Binary Ninja support is experimental, make sure to backup your analysis databases.

Binary Ninja prerequisites

ret-sync requires Binary Ninja version 2.2 at minimum as well as Python 3 (Python 2 is not supported).

Install the Binary Ninja extension

ret-sync is not yet distributed through the Binary Ninja's Plugin Manager; a manual installation is required. Simply copy that content of the ext_bn folder into Binary Ninja's plugins folder, for example:

%APPDATA%\Binary Ninja\plugins

After restarting Binary Ninja, the following output should be present in the console window:

[sync] commands added
Loaded python3 plugin 'retsync'

WinDbg extension

Build the WinDbg extension

Either use pre-built binaries or use the Visual Studio 2017 solution provided in ext_windbg, (see https://docs.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes if needed).

This will build the x64\release\sync.dll file.

Install the WinDbg extension

You will need to copy the resulting sync.dll file into the appropriate Windbg extension path.

  • WinDbg Classic:

For earlier versions of Windbg this is is something like this (be careful of x86/x64 flavours), for example

C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\winext\sync.dll

  • Windbg Preview

The folder for storing extension seems to be based on the PATH, so you need to put it one of the queried locations.

One example is to put it here:

C:\Users\user\AppData\Local\Microsoft\WindowsApps\sync.dll

Run the WinDbg extension

  1. Launch WinDbg on target
  2. Load extension (.load command)
    0:000> .load sync
    [sync.dll] DebugExtensionInitialize, ExtensionApis loaded
  1. Sync WinDbg
      0:000> !sync
      [sync] No argument found, using default host (127.0.0.1:9100)
      [sync] sync success, sock 0x5a8
      [sync] probing sync
      [sync] sync is now enabled with host 127.0.0.1

E.g. in IDA's Output window

      [*] << broker << dispatcher msg: add new client (listening on port 63898), nb client(s): 1
      [*] << broker << dispatcher msg: new debugger client: dbg connect - HostMachine\HostUser
      [sync] set debugger dialect to windbg, enabling hotkeys

If Windbg's current module matches IDA file name

      [sync] idb is enabled with the idb client matching the module name.

WinDbg installation troubleshooting

Note: If you get the following error, it is because you haven't copied the file to the right folder in the above steps.

0: kd> .load sync
The call to LoadLibrary(sync) failed, Win32 error 0n2
    "The system cannot find the file specified."
Please check your debugger configuration and/or network access.

The error below usually means that Windbg tried to load the incorrect flavour of the extension, ex: x64 in place of the x86 sync.dll.

0:000> .load sync
The call to LoadLibrary(sync) failed, Win32 error 0n193
    "%1 is not a valid Win32 application."
Please check your debugger configuration and/or network access.

As WinDbg Preview loads both plugins (x86 and x64) from the same directory, one can rename the x86 file sync32.dll.

0:000> .load sync32

GNU gdb (GDB) installation

  1. Copy the ext_gdb/sync.py to the directory of your choice
  2. Load the extension (see auto-load-scripts)
    gdb> source sync.py
    [sync] configuration file loaded 192.168.52.1:9100
    [sync] commands added

LLDB installation

LLDB support is experimental, however:

  1. Load extension (can also be added in ~/.lldbinit)
    lldb> command script import sync

OllyDbg 1.10 installation

OllyDbg 1.10 support is experimental, however:

  1. Build the plugin using the VS solution (optional, see pre-built binaries)
  2. Copy the dll within OllyDbg's plugin directory

OllyDbg2 installation

OllyDbg2 support is experimental, however:

  1. Build the plugin using the VS solution (optional, see pre-built binaries)
  2. Copy the dll within OllyDbg2's plugin directory

x64dbg installation

Based on testplugin, https://github.com/x64dbg/testplugin. x64dbg support is experimental, however:

  1. Build the plugin using the VS solution (optional, see pre-built binaries). May you need a different version of the plugin sdk, a copy can be found in each release of x64dbg. Paste the "pluginsdk" directory into "ext_x64dbg\x64dbg_sync"
  2. Copy the dll (extension is .d32 or .dp64) within x64dbg's plugin directory.

Usage

ret-sync debugger commands

For command-line oriented debuggers (mainly Windbg and GDB) a set of commands is exposed by ret-sync to assist in the reverse-engineering task.

The commands below are generic (Windbg and GDB), please note that a ! prefix is needed on WinDbg (e.g.: sync in GDB, !sync in Windbg).

Debugger command Description
synchelp Display the list of available commands with short explanation
sync Start synchronization
syncoff Stop synchronization
cmt [-a address] <string> Add a comment at current ip in disassembler
rcmt [-a address] Reset comment at current ip in disassembler
fcmt [-a address] <string> Add a function comment for function in which current ip is located
raddr <expression> Add a comment with rebased address evaluated from expression
rln <expression> Get symbol from the disassembler for the given address
lbl [-a address] <string> Add a label name at current ip in disassembler
cmd <string> Execute a command in debugger and add its output as comment at current ip in disassembler
bc <||on|off|set 0xBBGGRR> Enable/disable path coloring in disassembler
idblist Get list of all IDB clients connected to the dispatcher
syncmodauto <on|off> Enable/disable disassembler auto switch based on module name
idbn <n> Set active IDB to the nth client
jmpto <expression>
jmpraw <expression> If an IDB is enabled then disassembler's view is synced with the resulting address.
translate <base> <addr> <mod> rebase an address with respect to its module's name and offset

WinDbg specific commands:

Debugger command Description
curmod Display module infomation for current instruction offset (for troubleshooting)
modlist Debugger Markup Language (DML) enhanced module list meant for smoother active idb switching
idb <module name> Set given module as the active idb (see modlist enhanced version of lm)
modmap <base> <size> <name> A synthetic ("faked") module (defined using its base address and size) is added to the debugger internal list
modunmap <base> Remove a previously mapped synthetic module at base address
modcheck <||md5> Use to check if current module really matches IDB's file (ex: module has been updated)
bpcmds <||save|load|> bpcmds wrapper, save and reload .bpcmds (breakpoints commands list) output to current IDB
ks Debugger Markup Language (DML) enhanced output of kv command

GDB specific commands:

Debugger command Description
bbt Beautiful backtrace. Similar to bt in GDB but requests symbols from disassembler
patch Patch bytes in disassembler based on live context
bx Similar to GDB x but using a symbol. The symbol will be resolved by disassembler
cc Continue to cursor in disassembler

IDA usage

IDA plugin's GUI

The Overwrite idb name input field is meant to change the default IDB name. It is the name that is used by the plugin to register with the dispatcher. IDB automatic switch is based on module name matching. In case of conflicting names (like a foo.exe and foo.dll), this can be used to ease matching. Please note, if you modify the input field while the sync is active, you have to re-register with the dispatcher; this can be done simply by using the "Restart" button.

As a reminder it is possible to alias by default using the .sync configuration file.

IDA global shortcuts

ret-sync defines these global shortcuts in IDA:

  • Alt-Shift-S - Run ret-sync plugin
  • Ctrl-Shift-S - Toggle global syncing
  • Ctrl-H - Toggle Hex-Rays syncing

Two buttons are also available in the Debug toolbar to toggle global and Hex-Rays syncing.

IDA bindings over debugger commands

Syncplugin.py also registers debugger command wrapper hotkeys.

  • F2 - Set breakpoint at cursor address
  • F3 - Set one-shot breakpoint at cursor address
  • Ctrl-F2 - Set hardware breakpoint at cursor address
  • Ctrl-F3 - Set one-shot hardware breakpoint at cursor address
  • Alt-F2 - Translate (rebase in debugger) current cursor address
  • Alt-F5 - Go
  • Ctrl-Alt-F5 - Run (GDB only)
  • F10 - Single step
  • F11 - Single trace

These commands are only available when the current IDB is active. When possible they have also been implemented for others debuggers.

Ghidra usage

Ghidra plugin's GUI

Once the RetSyncPlugin opened, you can add it to the CodeBrowser window by simple drag'n'drop:

If you want to view several modules, files need to be open in the same CodeBrowser viewer, simply drag'n'drop the additional ones in the CodeBrowser window to obtain the result as above.

Ghidra global shortcuts

ret-sync defines these global shortcuts in Ghidra:

  • Alt-S - Enable syncing
  • Alt-Shift-S - Disable syncing
  • Alt-R - Restart syncing
  • Alt-Shift-R - Reload configuration

Ghidra bindings over debugger commands

Bindings over debugger commands are also implemented. They are similar to the ones from IDA's extension (except the "Go" command).

  • F2 - Set breakpoint at cursor address
  • Ctrl-F2 - Set hardware breakpoint at cursor address
  • Alt-F3 - Set one-shot breakpoint at cursor address
  • Ctrl-F3 - Set one-shot hardware breakpoint at cursor address
  • Alt-F2 - Translate (rebase in debugger) current cursor address
  • F5 - Go
  • Alt-F5 - Run (GDB only)
  • F10 - Single step
  • F11 - Single trace

Binary Ninja usage

Binary Ninja global shortcuts

ret-sync defines these global shortcuts in Binary Ninja:

  • Alt-S - Enable syncing
  • Alt-Shift-S - Disable syncing

Binary Ninja shortcuts

Bindings over debugger commands are also implemented. They are similar to the ones from IDA's extension.

  • F2 - Set breakpoint at cursor address
  • Ctrl-F2 - Set hardware breakpoint at cursor address
  • Alt-F3 - Set one-shot breakpoint at cursor address
  • Ctrl-F3 - Set one-shot hardware breakpoint at cursor address
  • Alt-F2 - Translate (rebase in debugger) current cursor address
  • Alt-F5 - Go
  • F10 - Single step
  • F11 - Single trace

WinDbg usage

WinDbg plugin commands

  • !sync: Start synchronization
  • !syncoff: Stop synchronization
  • !synchelp: Display the list of available commands with short explanation.
  • !cmt [-a address] : Add comment at current ip in IDA
    [WinDbg]
    0:000:x86> pr
    eax=00000032 ebx=00000032 ecx=00000032 edx=0028eebc esi=00000032 edi=00000064
    eip=00430db1 esp=0028ed94 ebp=00000000 iopl=0         nv up ei pl nz na po nc
    cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
    image00000000_00400000+0x30db1:
    00430db1 57    push    edi

    0:000:x86> dd esp 8
    0028ed94  00000000 00433845 0028eebc 00000032
    0028eda4  0028f88c 00000064 002b049e 00000110

    0:000:x86> !cmt 0028ed94  00000000 00433845 0028eebc 00000032
    [sync.dll]  !cmt called

    [IDA]
    .text:00430DB1    push    edi             ; 0028ed94  00000000 00433845 0028eebc 00000032
  • !rcmt [-a address]: Reset comment at current ip in IDA
    [WinDbg]
    0:000:x86> !rcmt
    [sync] !rcmt called

    [IDA]
    .text:00430DB1    push    edi
  • !fcmt [-a address] : Add a function comment for function in which current ip is located
    [WinDbg]
    0:000:x86> !fcmt decodes buffer with key
    [sync] !fcmt called

    [IDA]
    .text:004012E0 ; decodes buffer with key
    .text:004012E0                 public decrypt_func
    .text:004012E0 decrypt_func    proc near
    .text:004012E0                 push    ebp

Note: calling this command without argument reset the function's comment.

  • !raddr : Add a comment with rebased address evaluated from expression
  • !rln : Get symbol from the disassembler for the given address
  • !lbl [-a address] : Add a label name at current ip in disassembler
    [WinDbg]
    0:000:x86> !lbl meaningful_label
    [sync] !lbl called

    [IDA]
    .text:000000000040271E meaningful_label:
    .text:000000000040271E    mov     rdx, rsp
  • !cmd : Execute a command in WinDbg and add its output as comment at current ip in disassembler
    [WinDbg]
    0:000:x86> pr
    eax=00000032 ebx=00000032 ecx=00000032 edx=0028eebc esi=00000032 edi=00000064
    eip=00430db1 esp=0028ed94 ebp=00000000 iopl=0         nv up ei pl nz na po nc
    cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
    image00000000_00400000+0x30db1:
    00430db1 57     push    edi
    [sync.dll]  !cmd r edi

    [IDA]
    .text:00430DB1    push    edi             ; edi=00000064
  • !bc <||on|off|set 0xBBGGRR> : Enable/disable path coloring in disassembler. This is NOT a code tracing tool, there are efficient tools for that. Each manually stepped instruction is colored in the graph. Color a single instruction at current ip if called without argument. "set" argument is used to set path color with a new hex rgb code (reset color if called with a value > 0xFFFFFF).
  • !idblist: Get list of all IDB clients connected to the dispatcher:
    [WinDbg]
    0:000> !idblist
    > currently connected idb(s):
        [0] target.exe
  • !syncmodauto <on|off>: Enable/disable disassembler auto switch based on module name:
    [WinDbg]
    0:000> !syncmodauto off

    [IDA]
    [*] << broker << dispatcher msg: sync mode auto set to off
  • !idbn : Set active IDB to the nth client. n should be a valid decimal value. This is a semi-automatic mode (personal tribute to the tremendous jj)
    [WinDbg]
    0:000:> !idbn 0
    > current idb set to 0

In this example, current active IDB client would have been set to:

	[0] target.exe.
  • !jmpto : Expression given as argument is evaluated in the context of the current debugger's status. disassembler's view is then synced with the resulting address if a matching module is registered. Can be seen as a manual syncing, relocation is automatically performed, on the fly. Especially useful for randomly relocated binary.
  • !jmpraw : Expression given as argument is evaluated in the context of the current debugger's status. If an IDB is enabled then disassembler's view is synced with the resulting address. Address is not rebased and there is no IDB switching. Especially useful for dynamically allocated/generated code.
  • !modmap : A synthetic ("faked") module (defined using its base address and size) is added to the debugger internal list. From msdn: "If all the modules are reloaded - for example, by calling Reload with the Module parameter set to an empty string - all synthetic modules will be discarded." It can be used to more easily debug dynamically allocated/generated code.
  • !modunmap : Remove a previously mapped synthetic module at base address.
  • !modcheck <||md5>: Use to check if current module really matches IDB's file (ex: module has been updated) When called without an argument, pdb's GUID from Debug Directory is used. It can alternatively use md5, but only with a local debuggee (not in remote kernel debugging).
  • !bpcmds <||save|load|>: bpcmds wrapper, save and reload .bpcmds (breakpoints commands list) output to current IDB. Display (but not execute) saved data if called with no argument. Persistent storage is achieved using IDA's netnode feature.
  • !ks: Debugger Markup Language (DML) enhanced output of kv command. Code Addresses are clickable (!jmpto) as well as data addresses (dc).
  • !translate : Meant to be used from IDA (Alt-F2 shortcut), rebase an address with respect to its module's name and offset.

Address optional argument

!cmt, !rcmt and !fcmt commands support an optional address option: -a or --address. Address should be passed as an hexadecimal value. Command parsing is based on python's argparse module. To stop line parsing use --.

    [WinDbg]
    0:000:x86> !cmt -a 0x430DB2 comment

The address has to be a valid instruction's address.

GNU gdb (GDB) usage

Sync with host:

    gdb> sync
    [sync] sync is now enabled with host 192.168.52.1
    <not running>

    gdb> r
    Starting program: /bin/ls
    [Thread debugging using libthread_db enabled]
    Using host libthread_db library "/lib/libthread_db.so.1".

GDB plugin commands

Use commands, without "!" prefix

    (gdb) cmd x/i $pc
    [sync] command output: => 0x8049ca3:    push   edi

    (gdb) synchelp
    [sync] extension commands help:
     > sync <host>
     > syncoff
     > cmt [-a address] <string>
     > rcmt [-a address] <string>
     > fcmt [-a address] <string>
     > cmd <string>
     > bc <on|off|>
     > rln <address>
     > bbt <symbol>
     > patch <addr> <count> <size>
     > bx /i <symbol>
     > cc
     > translate <base> <addr> <mod>
  • rln: Get symbol from the IDB for the given address
  • bbt: Beautiful backtrace. Similar to bt but requests symbols from disassembler
    (gdb) bt
    #0  0x0000000000a91a73 in ?? ()
    #1  0x0000000000a6d994 in ?? ()
    #2  0x0000000000a89125 in ?? ()
    #3  0x0000000000a8a574 in ?? ()
    #4  0x000000000044f83b in ?? ()
    #5  0x0000000000000000 in ?? ()
    (gdb) bbt
    #0 0x0000000000a91a73 in IKE_GetAssembledPkt ()
    #1 0x0000000000a6d994 in catcher ()
    #2 0x0000000000a89125 in IKEProcessMsg ()
    #3 0x0000000000a8a574 in IkeDaemon ()
    #4 0x000000000044f83b in sub_44F7D0 ()
    #5 0x0000000000000000 in  ()
  • patch: Patch bytes in disassembler based on live context
  • bx: Beautiful display. Similar to x but using a symbol. The symbol will be resolved by disassembler.
  • cc: Continue to cursor in disassembler. This is an alternative to using F3 to set a one-shot breakpoint and F5 to continue. This is useful if you prefer to do it from gdb.
    (gdb) b* 0xA91A73
    Breakpoint 1 at 0xa91a73
    (gdb) c
    Continuing.

    Breakpoint 1, 0x0000000000a91a73 in ?? ()
    (gdb) cc
    [sync] current cursor: 0xa91a7f
    [sync] reached successfully
    (gdb)

LLDB usage

  1. Sync with host
    lldb> process launch -s
    lldb> sync
    [sync] connecting to localhost
    [sync] sync is now enabled with host localhost
    [sync] event handler started
  1. Use commands
    lldb> synchelp
    [sync] extension commands help:
     > sync <host>                   = synchronize with <host> or the default value
     > syncoff                       = stop synchronization
     > cmt <string>                  = add comment at current eip in IDA
     > rcmt <string>                 = reset comments at current eip in IDA
     > fcmt <string>                 = add a function comment for 'f = get_func(eip)' in IDA
     > cmd <string>                  = execute command <string> and add its output as comment at current eip in IDA
     > bc <on|off|>                  = enable/disable path coloring in IDA
                                       color a single instruction at current eip if called without argument
    lldb> cmt mooo

OllyDbg 1.10 usage

  1. Use Plugins menu or shortcuts to enable (Alt+s)/disable (Alt+u) synchronization.

OllyDbg2 usage

  1. Use Plugins menu or shortcuts to enable (Ctrl+s)/disable (Ctrl+u) synchronization.

Due to the beta status of OllyDbg2 API, only the following features have been implemented:

  • Graph sync [use F7; F8 for stepping]
  • Comment [use CTRL+;]
  • Label [use CTRL+:]

x64dbg usage

  1. Use Plugins menu or commands enable ("!sync") or disable ("!syncoff") synchronization.

  2. Use commands

[sync] synchelp command!
[sync] extension commands help:
 > !sync                          = synchronize with <host from conf> or the default value
 > !syncoff                       = stop synchronization
 > !syncmodauto <on | off>        = enable / disable idb auto switch based on module name
 > !synchelp                      = display this help
 > !cmt <string>                  = add comment at current eip in IDA
 > !rcmt <string>                 = reset comments at current eip in IDA
 > !idblist                       = display list of all IDB clients connected to the dispatcher
 > !idb <module name>             = set given module as the active idb (see !idblist)
 > !idbn <n>                      = set active idb to the n_th client. n should be a valid decimal value
 > !translate <base> <addr> <mod> = rebase an address with respect to local module's base

Note: using the !translate command from a disassembler (IDA/Ghidra, Alt-F2 shortcut), will make the disassembler window to "jump" to the specific address (equivalent of running disasm in x64dbg command line).

Python library usage

One may want to use ret-sync core features (position syncing with a disassembler, symbol resolution) even though a full debugging environment is not available or with a custom tool. To that end, a minimalist Python library has been extracted.

The example below illustrates the usage of the Python library with a script that walks through the output of an event based logging/tracing tool.

from sync import *

HOST = '127.0.0.1'

MAPPINGS = [
    [0x555555400000, 0x555555402000,  0x2000, " /bin/tempfile"],
    [0x7ffff7dd3000, 0x7ffff7dfc000, 0x29000, " /lib/x86_64-linux-gnu/ld-2.27.so"],
    [0x7ffff7ff7000, 0x7ffff7ffb000,  0x4000, " [vvar]"],
    [0x7ffff7ffb000, 0x7ffff7ffc000,  0x1000, " [vdso]"],
    [0x7ffffffde000, 0x7ffffffff000, 0x21000, " [stack]"],
]

EVENTS = [
    [0x0000555555400e74, "malloc"],
    [0x0000555555400eb3, "open"],
    [0x0000555555400ee8, "exit"]
]

synctool = Sync(HOST, MAPPINGS)

for e in EVENTS:
    offset, name = e
    synctool.invoke(offset)
    print("    0x%08x - %s" % (offset, name))
    print("[>] press enter for next event")
    input()

Extend

While initially focused on dynamic analysis (debuggers), it is of-course possible to extend the plugins set and integrate with other tools.

Other resource(s):

TODO

  • Sure.

Known Bugs/Limitations

  • Tested with Python 2.7/3.7, IDA 7.7 (Windows, Linux and Mac OS X), Ghidra 10.1.1, Binary Ninja 3.0.3225-dev, GNU gdb (GDB) 8.1.0 (Debian), lldb 310.2.37.
  • THERE IS NO AUTHENTICATION/ENCRYPTION whatsoever between the parties; you're on your own.
  • Self modifying code is out of scope.

With GDB:

  • it seems that stop event is not called when using 'return' command.
  • multi-threading debugging have issues with signals.

With WinDbg:

  • IDA's client plugin gets notified even though encountered breakpoint uses a command string that makes it continue ('g'). This can cause major slow-down if there are too much of these events. A limited fix has been implemented, the best solution is still to sync off temporarily.
  • Possible race condition

With Ghidra:

  • Shortcuts are not working as expected in decompiler widget.

With IDA:

  • Graph window redrawing is quite slow for big graphs.
  • ret-sync shortcuts conflicts in Linux environments.

Conflict(s):

  • Logitech Updater software is known to use the same default port (9100). A solution is to use a global .sync configuration file to define a different port.
[INTERFACE]
host=127.0.0.1
port=9234

License

ret-sync is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

The Binary Ninja plugin is released under the MIT licence.

Greetz

Hail to Bruce Dang, StalkR, @Ivanlef0u, Damien Aumaître, Sébastien Renaud and Kévin Szkudlapski, @m00dy, @saidelike, Xavier Mehrenberger, ben64, Raphaël Rigo, Jiss for their kindness, help, feedbacks and thoughts. Ilfak Guilfanov, Igor Skochinsky and Arnaud Diederen for their help with IDA's internals and outstanding support. Thank you to Jordan Wiens and Vector 35. Finally, thank you also to all the contributors and everyone who reported issues/bugs.

ret-sync's People

Contributors

aguinetqb avatar badsugar avatar bootleg avatar citronneur avatar deividalfa avatar dk1978 avatar elbiazo avatar gbps avatar kyle-kyle avatar lxp avatar mikeryan avatar p4nd4sec avatar rourke101 avatar saidelike avatar terrynini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ret-sync's Issues

Any luck on MacOs?

Hi, thanks a lot for your work on ret-sync.
I've been trying to get a decent reverse engineering setup running on mac but so far with no luck.
I've tried using ret-sync on ghidra with gdb and lldb, with the former seemingly connecting and syncing up but hanging if you set a breakpoint using F2 (and anyway always showing "Client program: none") while the latter not being recognized and ignoring bps and all (dialect: unknown client debugger: unknown).
Is anyone using ret-sync on macos successfully?

Simple question

I've been looking around but still haven't found how to connect ret-sync with windbg + ghidra.

After pressing 'start listening' it shows N/A on the debugger option and on the last one.
Will you please help me on setting it up?

olly1 support

do you have plans for olly1 support?

can we implement our own exported versions of exported functions instead of using the .lib?

IDA Pro 7.5 and Ghida

Today I decided to use the Python debug to find out what was going on with this fantastic software.
There is an error when is loading the API (idaapi), IDA has changed the name of dll and how it is making the connection with function, Do you pretend to rewrite the program?

Ghidra 9.2 compatibility

Is there an ETA for Ghidra 9.2 compatibility now that it is released to the public?
You can update the properties file to be seen as valid, but the configuration phase crashes.
Thanks

Support For Binary Ninja

I've found myself using Binary Ninja more and more recently, and really like the way that ret-sync makes x64dbg work with Ghidra. It'd be really useful if the same thing could be done in Binary Ninja. BN supports pure-python plugins, and I am primarily a Python developer so I'm happy to do the dev work. I have no concept of where to start though.

Is there any way you could point me in the correct direction?

Also, thank you for making this to begin with. It's fricken' awesome.

Getting lldb - ghidra setup working: Program unavailable

Hi, thanks for this great plugin!

I am trying to get lldb setup with either ghidra or IDA Pro (don't assume you want to make a Hopper plugin, do you? :))

I setup lldb to load the extension and can start the sync which then gives me a debug message:

[*] retsync init
[>] server started
[x] fail to parse json request: org.json.JSONException: JSONObject["dialect"] not found.
<< {"msg": "dbg connect - Darwin Kernel Version 19.4.0: Wed Mar  4 22:28:40 PST 2020; root:xnu-6153.101.6~15/RELEASE_X86_64", "type": "new_dbg"}
[x] program unavailable: <myprogram>

I tried this with a IDA Pro installation and it's working really well, just with ghidra it can't manage to find the program for some reason. Same setup as in IDA

The binary I am trying to load is a loader program for a library that I want to debug. I double-checked that process name is identical

Tried both, self-built and the extension from the dist/ that was already there but same behaviour

Add option to disable breakpoints

Currently, the plugin can create windbg breakpoints directly from IDA (using F2), but there is not way to disable them via IDA.

Also, the created BP does not show up in the IDA GUI, making it difficult to keep track.

How do i sync between ida and x32dbg?

I installed the plugin for this two programs, and x32dbg says "sync is now enabled with host 127.0.0.1"
and IDA Says: "[sync] << broker << connected to dispatcher
[sync] << broker << listening on port 57776"

now how do i connected between them?

Exceptions

There are exceptions when I trying to attach the windbg debugger to ida 7.4:

Traceback (most recent call last):
  File "C:/Program Files/IDA Pro 7.4/plugins/SyncPlugin.py", line 805, in cb_broker_on_out
    self.worker.parse_exec(req.strip())
  File "C:/Program Files/IDA Pro 7.4/plugins/SyncPlugin.py", line 596, in parse_exec
    req_handler(hash)
  File "C:/Program Files/IDA Pro 7.4/plugins/SyncPlugin.py", line 508, in req_set_dbg_dialect
    SyncForm.init_hotkeys()
  File "C:/Program Files/IDA Pro 7.4/plugins/SyncPlugin.py", line 1009, in init_hotkeys
    ('F2', self.broker.worker.bp_notice, 'BreakpointToggle'),
AttributeError: 'SyncForm_t' object has no attribute 'broker'```

and one more exception is thrown for some reason while debugging:
```Traceback (most recent call last):
  File "C:/Program Files/IDA Pro 7.4/plugins/SyncPlugin.py", line 805, in cb_broker_on_out
    self.worker.parse_exec(req.strip())
  File "C:/Program Files/IDA Pro 7.4/plugins/SyncPlugin.py", line 599, in parse_exec
    req_handler(hash)
  File "C:/Program Files/IDA Pro 7.4/plugins/SyncPlugin.py", line 217, in req_loc
    self.hexsync.cb_loc(ea)
  File "C:/Program Files/IDA Pro 7.4/plugins\retsync\syncrays.py", line 99, in cb_loc
    func_ea = idaapi.get_func(ea).start_ea
AttributeError: 'NoneType' object has no attribute 'start_ea'```

configParser error

When I 've configured gdb to use ret-sync i've this error:

(gdb) source /home/solace/Téléchargements/ret-sync/ext_gdb/sync.py
/........../sync.py:1031: DeprecationWarning: The SafeConfigParser class has been renamed to ConfigParser in Python 3.2. This alias will be removed in future versions. Use ConfigParser directly instead.
config = configparser.SafeConfigParser({'host': HOST, 'port': PORT, 'context': '', 'use_tmp_logging_file': USE_TMP_LOGGING_FILE})
[sync] configuration file loaded from: /root/.sync
interface: x.x.x.x:zzzz
[sync] init
[sync] 18 commands added
(gdb) quit

So i've just correct it by change SafeConfigParser to ConfigParser.
Is it possible to commit the correction ?

best regards

Can't sync IDA & WinDbg Preview

Hi,

I followed the following instructions :

  • Installed the IDA plugin (IDA 7.2) and launched it, I have the following output in the console
[sync] default idb name: win32kfull.sys
[sync] sync enabled
[sync] cmdline: "C:\Python27\python.exe" -u "C:\Program Files\IDA 7.2\plugins\retsync\broker.py" --idb "win32kfull.sys"
[sync] module base 0x1c0000000
[sync] hexrays #7.2.0.181105 found
[sync] broker started
[sync] plugin loaded
[sync] << broker << connected to dispatcher
[sync] << broker << listening on port 55368
  • Compiled WinDbg extension and placed in "C:\Users\user\AppData\Local\Microsoft\WindowsApps" (using WinDbg Preview)
  • .load sync
    [sync] DebugExtensionInitialize, ExtensionApis loaded
  • !sync
[sync] No argument found, using default host (127.0.0.1:9100)
[sync] sync success, sock 0x348
[sync] probing sync
[sync] sync is now enabled with host 127.0.0.1
[sync] recv: connection closed
[sync] sync is off

But there is no more output in the IDA console. How can I troubleshoot this issue please ?

"rrln" command fails on IDA 7.0

Traceback (most recent call last):
  File "/Applications/IDA Pro 7.0/ida64.app/Contents/MacOS/plugins/SyncPlugin.py", line 824, in cb_broker_on_out
    self.worker.parse_exec(req.strip())
  File "/Applications/IDA Pro 7.0/ida64.app/Contents/MacOS/plugins/SyncPlugin.py", line 614, in parse_exec
    req_handler(hash)
  File "/Applications/IDA Pro 7.0/ida64.app/Contents/MacOS/plugins/SyncPlugin.py", line 386, in req_rrln
    addr = idc.get_name_ea_simple(sym)
  File "/Applications/IDA Pro 7.0/ida64.app/Contents/MacOS/python/idc.py", line 1888, in get_name_ea_simple
    return ida_name.get_name_ea(BADADDR, name)
  File "/Applications/IDA Pro 7.0/ida64.app/Contents/MacOS/python/ida_name.py", line 258, in get_name_ea
    return _ida_name.get_name_ea(*args)
TypeError: in method 'get_name_ea', argument 2 of type 'char const *'

This is because the IDAPython 2.7 api can't convert type unicode to str implicitly from the api level.

This can be resolved at SyncPlugin.py:385

 addr = idc.get_name_ea_simple(sym)

to

 addr = idc.get_name_ea_simple(str(sym))

Thanks!

Highlight current EIP in HexRays Pseudocode window too

Atm ret-sync supports highlighting the current EIP pointer in the IDA View window (assembly). It would be nice to have it highlight the current line in the Pseudocode window (output of HexRays decompiler) when HexRays is available.

Indeed IDA already knows how to link the assembly with a line in the decompiled code as when we hit F5 the cursor is on the right line corresponding to the assembly.

However I am not sure changing the colour of one line in the Pseudocode is something provided by IDA Pro yet though so may need to ask them first to add support for that before we can implement this feature in ret-sync.

dispatcher failed

dispatcher failed
-> AttributeError("'NoneType' object has no attribute 'enabled'",)

Labeling and comments x64dbg/Ghidra

I have installed everything and got sync'ed. I can step over and both programs are coordinated.

However I am wondering how I can populate labels/comments/var names from Ghidra to x64dbg and viceversa:
1- I opened a file with some changes made from Ghidra but these are not populated into x64dbg.
2- After synchronizing, by setting the comment manually in either program (e.g. by using ";") does not do any synchronization and the comment remains local to the program.
3- If I try to manually execute "cmt Test", "cmt -a 401039 Test", "cmt "Test"", etc from x64dbg I get an error saying "Not enough arguments! At least 2 arguments must be specified"

1 is the most convenient, as I might have a disassembled file with some renaming already and it would be great to have this populated into the debugger.

2 is also nice, as I can make changes as they are both opened, by using the usual options from Ghidra or x64dbg, and get it populated to the other.

3 is not ideal, since I need to use specific commands (instead of e.g. pressing ";" for comment) and it seems to work only while they both are open.

Annoying updating ida view while debugging

Description

I use ret-sync with gdb. And my gdb and ida are on ther same Destop. So, when I just send ni in gdb, the ida window jump out !!! Then I have to switch back to gdb. What a annoyance !!!

My Solution

First, I just comment the idaapi.jumpto(ea) in SyncPlugin.py, and the annoyance gone.
But there's still sometimes I need to check ida. So I and some code.
SyncPlugin.py

''' this code is in class RequestHandler '''
    def req_loc2(self, hash):
        offset, base = hash['offset'], hash.get('base')
        ea = self.rebase(base, offset)
        if not ea:
            return
        idaapi.jumpto(ea)
''' here I register my function '''
    self.req_handlers = {
            'broker': self.req_broker,
            'loc': self.req_loc,
            'loc2': self.req_loc2,
            'cmd': self.req_cmd,
            'cmt': self.req_cmt,
            'rcmt': self.req_rcmt,
            'fcmt': self.req_fcmt,
            'raddr': self.req_raddr,
            'cursor': self.req_cursor,
            'patch': self.req_patch,
            'rln': self.req_rln,
            'rrln': self.req_rrln,
            'lbl': self.req_lbl,
            'bc': self.req_bc,
            'bps_get': self.req_bps_get,
            'bps_set': self.req_bps_set,
            'modcheck': self.req_modcheck,
            'dialect': self.req_set_dbg_dialect
        }

sync.py

class Loc(gdb.Command):

    def __init__(self, sync):
        gdb.Command.__init__(self, "loc", gdb.COMMAND_OBSCURE, gdb.COMPLETE_NONE)
        self.sync = sync

    def invoke(self, arg, from_tty):
        offset = get_pc()
        if not offset:
            print("<not running>")
            return
        if not self.sync.base:
            print("[sync] process not synced, command is dropped")
            return
        if not self.sync.pid:
            self.sync.pid = get_pid(ctx=self.sync.ctx)
            if self.sync.pid is None:
                print("[sync] failed to get pid")
                return
            else:
                print("[sync] pid: %s" % self.sync.pid)

        self.sync.offset = offset
        mod = self.sync.mod_info(self.sync.offset)
        if mod:
            if VERBOSE >= 2:
                print("[sync] mod found")
                print(mod)

            base, sym = mod

            if self.sync.base != base:
                self.sync.tunnel.send("[notice]{\"type\":\"module\",\"path\":\"%s\"}\n" % sym)
                self.sync.base = base

            self.sync.tunnel.send("[sync]{\"type\":\"loc2\",\"base\":%d,\"offset\":%d}\n" % (self.sync.base, self.sync.offset))
        else:
            print("[sync] unknown module at current PC: 0x%x" % self.offset)
            print("[sync] NOTE: will resume sync when at a known module address")
            self.base = None
            self.offset = None
''' also need to be registered '''
    Loc(sync)

Insert these code properly, and just type loc in gdb, ida cursor will be updated, instead of updating everytime.

Suggestion

Forget about my ugly code. Hope my problem will be solved in future edition.

jmp in memory allocation : "Could not get module base"

I debug a program (with x64dbg) that create a new memory allocation (VirtualAlloc) en drop executable code inside and then jmp to this memory.
Before jump I dump this allocation to file and I load it as new segment in IDA Pro, I set the same address as in x64dbg.
However, ret-sync won't jump inside because it isn't in the module :

[sync] UpdateState(00540585): could not get module base...

(00540585 exist in IDA after creating manually seg/loading bin)

So, before reading all plugin Python code, is any solution to follow code in allocation ?

Can this directly set breakpoints in lldb/gdb?

I wasn't completely sure because all the breakpoint commands mention over windebug which doesn't exist on mac.

From my short test with IDA, setting breakpoints in IDA doesn't reflect inside lldb so I'm guessing no, but might also just be my setup that's the problem.

GDB plugin is Python 3 only

Just tried to use ret-sync on a GDB installation that only had Python 2.7 support. Bombed with complaints about line 524:

super().__init(sync, True)
TypeError: super() takes at least 1 argument (0 given)

I have extremely minimal Python fu, but some Googling suggests that the syntax being used there is Python 3-specific. Using the copy of sync.py from this commit (which is the commit before the one that introduced that new syntax) loads fine (I'm yet to use it in anger).

I'm not asking for Python 2.7 support to necessarily be retained -- it is well past its use-by date. It's just that the README still says that Python 2 is supported, and if the intention is that that is no longer the case, it'd be good to get the docs up-to-date.

!bpcmds Fails

In some cases, the !bpcmds save commands fails. When it does, I get the following output in IDA, and Windbg hangs.

[-] Sync failed to parse json
 {"type":"bps_set","msg":"censored-base64-sensitive-data"
------------------------------------
\[<] bad hdr '}'
[-] Request dropped due to bad header

Since this only happens once every few attempts, it is a bit tricky to reproduce (failed to do that on purpose so far) and therefore tricky to debug.

IDA symbols sync with gdb

If ret-sync support symbols sync , it will be really great for debugging.
Symbols include function names and some variable names(or static) are important.
https://github.com/ALSchwalm/dwarfexport this project use ida to export dwarf for gdb.
https://github.com/danigargu/syms2elf this project export elf for gdb.
I think there is a better way to use ret-sync to do this job.
Also, pwndbg has a ida_script.py, which has a similar function to this project. But that script can resolve the symbols in IDA.
Don't know if I can do anything to help.

No communication between Ghidra and gdb

ret-sync never seems to sync with gdb. Screenshot is attached showing ret-sync loaded in both gdb and Ghidra and Ghidra listening on port 9100 but no connection made. I can confirm the java process listed in lsof is Ghidra.

image

"rrln" command ignores remote base when returning addresses from symbols

def req_rrln(self, hash):

    # return address for a given idb's symbol
    def req_rrln(self, hash):
        sym, rbase, offset, base = hash['sym'], hash['rbase'], hash['offset'], hash['base']

        rs_log("%s -  0x%x - 0x%x - 0x%x" % (sym, rbase, offset, base))

        addr = idc.get_name_ea_simple(str(sym))
        if addr:
            self.notice_broker("cmd", "\"cmd\":\"%s\"" % addr)
            rs_log("resolved address: %s" % addr)
        else:
            rs_log("could not resolve address for symbol %s" % sym)

This function ignores the base argument from hash['base'] and does not calculate an address based off of the ida base and remote base.

I believe this should change so that the ida base is remove from the address and the remote base is added before returning. This should result in an address that is relative to the remote module.

    # return address for a given idb's symbol
    def req_rrln(self, hash):
        sym, rbase, offset, base = hash['sym'], hash['rbase'], hash['offset'], hash['base']

        rs_log("%s -  0x%x - 0x%x - 0x%x" % (sym, rbase, offset, base))

        addr = idc.get_name_ea_simple(str(sym))
        if addr:
            # rebase the address to remote base
            addr = addr - self.base + hash['base']
            self.notice_broker("cmd", "\"cmd\":\"%s\"" % addr)
            rs_log("resolved address: %s" % addr)
        else:
            rs_log("could not resolve address for symbol %s" % sym)

Ghidra - program unavailable

I used ret-sync to sync ghidra with gdb.
Everything goes right until I try running the program in gdb, then it runs correctly on gdb but ghidra doesn't show anything.
The console says:
[*] retsync init
[>] ret-sync enable
[>] server listening
[>] server started
[<] new_dbg: dbg connect - Linux #1 SMP Debian 5.7.6-1kali2 (2020-07-01) x86_64
dialect: gdb
[x] program unavailable: program_name

Is there a way to fix this?

Is there minimum version of gdb?

I just cloned and got ret-sync added to Ghidra OK.

I am also running gdb 7.9.1 and when I type in source sync.py, I get:

sync.py:1: Error in sourced command file:

(I am on Windows 10, with python 2.7.6.) Is there min. GDB version I should be running? Or is the script only good on UNIX boxes?

Syncing Ghidra with Gdb over QEMU

I am currently emulating an ISA in QEMU, while a custom gdb port (written for said ISA) is connected via localhost:1234. When I issue the sync command I receive the following error:

[sync] pid: 42000
Python Exception <class 'gdb.error'> Not supported on this target.:

The Readme indicated an issue with /proc/mappings, but I have not been able to resolve this issue. I am using Ghidra by the way

Can't determine the current process's PID

I have add a .sync file in my .idb directoty. When i start retsync plugin ,it also find this .sync file.But when i enter cmd 'sync' in gdb,it prints "Python Exception <class 'gdb.error'> Can't determine the current process's PID: you must name one.: ".

gdb
image

ida pro output window
image

.sync file
image

Dispatcher path is not properly set

[sync] default idb name: ex1 - Copy.exe
[sync] sync enabled
[sync] cmdline: "C:\msys64\usr\bin\python.exe" -u "C:\Program Files\IDA Pro 7.5\plugins\retsync\broker.py" --idb "ex1 - Copy.exe"
[sync] module base 0x400000
[sync] hexrays #7.5.0.201028 found
[sync] broker started
[sync] plugin loaded
[sync] [<] bad hdr '[-] dispatcher path is not properly set, current value: </c/Users/XXXX/Documents/ex/dispatcher.py>'
[sync] [-] Request dropped due to bad header
[sync] broker finished
[sync] idb is disabled

the script seems to search dispatcher.py in my idb folder, whereas dispatcher.py is in plugins folder.

IDA7.5,ERROR:[sync] idb is disabled

Ret-sync is a very useful tool, and I've used it before.But when I used it again recently, it didn't work.Please give me a hand
IDA7.5 cannot be used,Did I make a configuration mistake?
Output infomations:
[sync] default idb name: PEhash.exe
[sync] sync enabled
[sync] cmdline: "C:\python39-x64\python.exe" -u "D:\01_Tools\06_IDA7.5\IDA_7.5\plugins\retsync\broker.py" --idb "PEhash.exe"
[sync] module base 0x400000
[sync] hexrays #7.5.0.201028 found
[sync] broker started
[sync] plugin loaded
[sync] << broker << connected to dispatcher
[sync] << broker << beacon not received (possible dispatcher error)
[sync] << broker << received kill notice
[sync] broker finished
[sync] idb is disabled

Color Configuration

At the moment, it is unclear how one should customize colors.

Having a separate configuration file for colors (and other configuration?) will be much appreciated.

idb isn't enabled, can't go

Hello, I recently noticed your excellent work, but when I try to use ida to connect to gdb on a LAN server, I cannot run the program with alt+F5 in ida, and the output window will display "idb" isn't enabled, can't go". When I ran this program in gdb, ida did not respond, as if I was not connected. But "set debugger dialect to gdb, enabling hotkeys" is indeed displayed in the output window. I want to ask what is wrong here?

IDA output window:

[sync] sync enabled
[sync] cmdline: "C:\ProgramData\Miniconda3\python.exe" -u "C:\Program Files\IDA 7.5\plugins\retsync\broker.py" --idb "shellcode_x64"
[sync] module base 0x400000
[sync] hexrays #7.5.0.201028 found
[sync] broker started
[sync] << broker << dispatcher not found, trying to run it
[sync] << broker << dispatcher now runs with pid: 8680
[sync] << broker << connected to dispatcher
[sync] << broker << dispatcher msg: add new client (listening on port 54837), nb client(s): 1
[sync] << broker << dispatcher msg: new debugger client: dbg connect - Linux #67~18.04.1-Ubuntu SMP Tue Jan 5 22:01:05 UTC 2021 x86_64
[sync] set debugger dialect to gdb, enabling hotkeys
[sync] idb isn't enabled, can't go
[sync] << broker << dispatcher msg: dispatcher stopped
[sync] << broker << server.loop
[sync] broker finished
[sync] idb is disabled
Flushing buffers, please wait...ok
Unloading IDP module C:\Program Files\IDA 7.5\procs\pc64.dll...

  bytes   pages size description
--------- ----- ---- --------------------------------------------
   524288    64 8192 allocating memory for b-tree...
    65536     8 8192 allocating memory for virtual array...
   262144    32 8192 allocating memory for name pointers...
-----------------------------------------------------------------
   851968            total memory allocated

Loading processor module C:\Program Files\IDA 7.5\procs\pc64.dll for metapc...Initializing processor module metapc...OK
Loading type libraries...
Autoanalysis subsystem has been initialized.
Database for file 'shellcode_x64' has been loaded.
Hex-Rays Decompiler plugin has been loaded (v7.5.0.201028)
  License: 55-2FD4-F731-D2 P.Y.G Team, Personal license (1 user)
  The hotkeys are F5: decompile, Ctrl-F5: decompile all.
  Please check the Edit/Plugins menu for more informaton.
IDAPython Hex-Rays bindings initialized.
[sync] default idb name: shellcode_x64
[sync] found config file: user_conf(host='10.168.1.29', port=9234, alias=None, path='C:\\Users\\hp\\Desktop\\tfctmp\\ctfzone_pwn\\.sync')
[sync] sync enabled
[sync] cmdline: "C:\ProgramData\Miniconda3\python.exe" -u "C:\Program Files\IDA 7.5\plugins\retsync\broker.py" --idb "shellcode_x64"
[sync] module base 0x400000
[sync] hexrays #7.5.0.201028 found
[sync] broker started
[sync] plugin loaded
[sync] << broker << dispatcher not found, trying to run it
[sync] << broker << dispatcher now runs with pid: 15292
[sync] << broker << connected to dispatcher
[sync] << broker << dispatcher msg: add new client (listening on port 55085), nb client(s): 1
[sync] << broker << dispatcher msg: new debugger client: dbg connect - Linux #67~18.04.1-Ubuntu SMP Tue Jan 5 22:01:05 UTC 2021 x86_64
[sync] set debugger dialect to gdb, enabling hotkeys
[sync] idb isn't enabled, can't go

GDB:

(pwn) root@sc-ThinkPad-T14-Gen-1:~/pwn$ gdb findshellcode -qReading symbols from findshellcode...(no debugging symbols found)...done.
[sync] configuration file loaded from: /home/qsp/.sync
       interface: 10.168.1.29:9234
[sync] init
[sync] 18 commands added
gdb-peda$ sync
[sync] initializing tunnel to IDA using 10.168.1.29:9234...
[sync] sync is now enabled with host 10.168.1.29

为何总是出现这个?哪里的问题?

0: kd> !sync
[sync] No argument found, using default host (127.0.0.1:9100)
[sync] connect failed (check if broker is running)
[sync] probing sync
[sync] TunnelSend: tunnel is unavailable
[sync] sync aborted

windbg kernel failed.

hi, i'm debugging the windows kernel. but it can't be synchronized. so i create the custom file, .sync.

[ALIASES]
nt=ntoskrnl.exe

, but once i opend ida and load the plugin, it failed. i dont' know where i made fault.Can you give me some help, thanks.
image

Detect Mismatching Binaries

This could be done in several ways. The issue that made me request this is accidentally loading a 64bit dll in IDA while debugging a 32bit application in windbg. If the plugin could verify that some basic info is matching (CPU, for instance) it could safe time on such issues.

Rebase exception sync IDA/WinDBG

Hi!

I just tested your amazing plugin and I get this exception after setting a breakpoint in IDA.

It seems like self.base_remote is None.

Exception in ida_kernwin.UI_Hooks dispatcher function: SWIG director method error. Error detected when calling 'UI_Hooks.preprocess_action'
Traceback (most recent call last):
  File "C:/Users/user/AppData/Roaming/Hex-Rays/IDA Pro/plugins/SyncPlugin.py", line 922, in preprocess_action
    self.hooked[action_name]()
  File "C:/Users/user/AppData/Roaming/Hex-Rays/IDA Pro/plugins/SyncPlugin.py", line 629, in bp_notice
    offset = self.rebase_remote(ea)
  File "C:/Users/user/AppData/Roaming/Hex-Rays/IDA Pro/plugins/SyncPlugin.py", line 174, in rebase_remote
    offset = (offset - self.base) + self.base_remote
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

WinDBG Log:

0: kd> .load sync
[sync] DebugExtensionInitialize, ExtensionApis loaded
0: kd> !sync
[sync] No argument found, using default host (127.0.0.1:9100)
[sync] sync success, sock 0x258
[sync] probing sync
[sync] sync is now enabled with host 127.0.0.1
0: kd> !idblist
> currently connected idb(s):
    [0] XXXX.sys
0: kd> !idbn 0
> current idb set to 0

When I try to configure a manual bp (in WinDBG) on the module and then run !sync, I get the following error:

0: kd> !sync
[sync] sync update
[sync] failed to GetModuleByOffset for offset: 0xfffff8022bf31538

Now I have mapped the module manually and now it seems to sync fine.

1: kd> !modmap 0xfffff8022bf30000 0x8000 XXXX.sys
*** WARNING: Unable to verify timestamp for XXXX.sys

Would it be possible to fix it?

EDIT: After several attemps, multiple debug restarts, etc, the plugin constantly fails, sometimes preventing setting breakpoints (exception above), and at other times memory addresses do not match IDA / Windbg (maybe wrong rebase). Now, even modmap doesn't work (AddSyntheticModule failed).

Thanks!

Can I use this with a custom gdb stub?

Most emulators like RPCS3 and pcsx2 feature gdb stubs (example) that allow a gdb client like gdb's or IDA's to debug the emulated guest.

I would like to have an emulator as the "debugger" & sync that with Ghidra.

Can it work with arbitrary gdb stubs this way? Or are the existing GDB tools only for using it with a program that's run/managed by GDB?

If not, I suppose I'd need to write and extension myself, like the one for x64dbg etc. (but presumably in the emulator's own codebase). Any docs/pointers on that or should I just study the existing one's code to figure it out?

Thank you, great plugins!

ida 7.3 not found ret-sync plugin

Place the downloaded ida plugin in the plugin directory according to the document method. The plugin cannot be seen in ida, and the version is ida 7.3

Gdb bbt command: Ghidra tries to resolve wrong address

When gdb runs the bbt command, it sends a [sync] rln command to the Ghidra module which calls rebase(rbase, raddr) to get the final address to resolve the symbol. rebase then calls imageBaseLocal.addNoWrap(raddr - rbase), but because gdb sets rbase always to 0, raddr - rbase is the final address already, so adding the base causes the wrong address to be returned by rebase.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.