Module: PWN::FFI::Keystone

Extended by:
Library
Defined in:
lib/pwn/ffi/keystone.rb

Overview

Thin libkeystone assembler.

Constant Summary collapse

KS_ARCH_ARM =
1
KS_ARCH_ARM64 =
2
KS_ARCH_X86 =
4
KS_MODE_LITTLE_ENDIAN =
0
KS_MODE_32 =
4
KS_MODE_64 =
8

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.load_errorObject (readonly)

Returns the value of attribute load_error.



28
29
30
# File 'lib/pwn/ffi/keystone.rb', line 28

def load_error
  @load_error
end

Class Method Details

.assemble(opts = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/pwn/ffi/keystone.rb', line 43

public_class_method def self.assemble(opts = {})
  raise 'ERROR: libkeystone not available' unless available?(mod: self)

  asm = opts[:asm].to_s
  raise 'ERROR: asm is required' if asm.empty?

  arch, mode = arch_mode(arch: opts[:arch], endian: opts[:endian])
  ks_ptr = PubFFI::MemoryPointer.new(:pointer)
  raise 'ERROR: ks_open failed' unless ks_open(arch, mode, ks_ptr).zero?

  ks = ks_ptr.read_pointer
  enc = PubFFI::MemoryPointer.new(:pointer)
  size = PubFFI::MemoryPointer.new(:ulong)
  count = PubFFI::MemoryPointer.new(:ulong)
  rc = ks_asm(ks, asm, (opts[:address] || 0).to_i, enc, size, count)
  raise 'ERROR: ks_asm failed' unless rc.zero?

  n = size.read_ulong
  bytes = enc.read_pointer.read_string(n)
  ks_free(enc.read_pointer)
  ks_close(ks)
  { engine: 'keystone', bytes: bytes, hex: bytes.unpack1('H*'), count: count.read_ulong }
end

.authorsObject



81
82
83
# File 'lib/pwn/ffi/keystone.rb', line 81

public_class_method def self.authors
  "AUTHOR(S):\n  0day Inc. <[email protected]>\n"
end

.available?(opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
# File 'lib/pwn/ffi/keystone.rb', line 38

public_class_method def self.available?(opts = {})
  opts[:mod]
  load_error.nil?
end

.helpObject



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/pwn/ffi/keystone.rb', line 85

public_class_method def self.help
  puts "USAGE:
    # True when libkeystone is loadable.
    #{self}.available?(
      mod: 'optional - ignored; present so (opts = {}) reads opts['
    )

    # Assemble instructions with Keystone.
    #{self}.assemble(
      asm: 'required - assembly source (one instruction per line)',
      arch: 'optional - x86_64|x86|arm|aarch64',
      endian: 'optional - :little or :big byte order',
      address: 'optional - start address'
    )

    # Print the AUTHOR(S) string for this module.
    #{self}.authors
  "
  constants.sort
end