Skip to content

Instantly share code, notes, and snippets.

@carcigenicate
Created January 31, 2021 01:50
Show Gist options
  • Select an option

  • Save carcigenicate/28975aad8e4c5c81d85f535e8779bfc1 to your computer and use it in GitHub Desktop.

Select an option

Save carcigenicate/28975aad8e4c5c81d85f535e8779bfc1 to your computer and use it in GitHub Desktop.
A small script that emits NASM code that pushes a string to the stack and prints it via a system call.
def little_encode(text: bytes, word_size: int) -> list[int]:
return [int.from_bytes(text[i:i+word_size], "little")
for i in range(0, len(text), word_size)]
def emit_pushes(text: bytes, word_size: int, pushed_register: str) -> str:
chunks = little_encode(text, word_size)
return "\n".join(f"mov {pushed_register}, {chunk:#{word_size}x}\npush {pushed_register}"
for chunk in reversed(chunks))
def emit_write(text: bytes, word_size: int) -> str:
pointer_register = "rsi"
instucts = ["mov rax, 1\nmov rdi, 1",
emit_pushes(text, word_size, pointer_register),
f"mov {pointer_register}, rsp\nmov rdx, {len(text)}\nsyscall"]
return "\n".join(instucts)
# s = "This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources."
# print(emit_write(s.encode("utf-8"), 8))
#
# mov rax, 1
# mov rdi, 1
# mov rsi, 0x2e736563
# push rsi
# mov rsi, 0x72756f7320726568
# push rsi
# mov rsi, 0x746f20676e6f6d61
# push rsi
# mov rsi, 0x202c736e6f697463
# push rsi
# mov rsi, 0x656e6e6f63206b72
# push rsi
# mov rsi, 0x6f7774656e206d6f
# push rsi
# mov rsi, 0x726620726f207365
# push rsi
# mov rsi, 0x6c6966206e692064
# push rsi
# mov rsi, 0x65726f7473206174
# push rsi
# mov rsi, 0x6164207972616e69
# push rsi
# mov rsi, 0x6220676e696c646e
# push rsi
# mov rsi, 0x6168206e69206465
# push rsi
# mov rsi, 0x7375206562206e61
# push rsi
# mov rsi, 0x632073696854202e
# push rsi
# mov rsi, 0x737463656a626f20
# push rsi
# mov rsi, 0x7365747962206e6f
# push rsi
# mov rsi, 0x6874795020736120
# push rsi
# mov rsi, 0x6465746e65736572
# push rsi
# mov rsi, 0x7065722073746375
# push rsi
# mov rsi, 0x727473204320646e
# push rsi
# mov rsi, 0x61207365756c6176
# push rsi
# mov rsi, 0x206e6f6874795020
# push rsi
# mov rsi, 0x6e65657774656220
# push rsi
# mov rsi, 0x736e6f6973726576
# push rsi
# mov rsi, 0x6e6f6320736d726f
# push rsi
# mov rsi, 0x6672657020656c75
# push rsi
# mov rsi, 0x646f6d2073696854
# push rsi
# mov rsi, rsp
# mov rdx, 212
# syscall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment