-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathssh_honeypot.py
251 lines (205 loc) · 9.14 KB
/
ssh_honeypot.py
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/env python
import argparse
import threading
import socket
import sys
import os
import traceback
import re
import logging
import paramiko
import redis
from datetime import datetime
from binascii import hexlify
from paramiko.py3compat import b, u, decodebytes
REDIS_HOST=os.environ.get("REDIS_HOST")
REDIS_PORT=os.environ.get("REDIS_PORT")
REDIS_PASSWORD=os.environ.get("REDIS_PASSWORD")
r = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD, decode_responses=True)
HOST_KEY = paramiko.RSAKey(filename='server.key')
SSH_BANNER = "SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.1"
UP_KEY = '\x1b[A'.encode()
DOWN_KEY = '\x1b[B'.encode()
RIGHT_KEY = '\x1b[C'.encode()
LEFT_KEY = '\x1b[D'.encode()
BACK_KEY = '\x7f'.encode()
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO,
filename='ssh_honeypot.log')
def detect_url(command, client_ip):
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
result = re.findall(regex, command)
if result:
for ar in result:
for url in ar:
if url != '':
logging.info('New URL detected ({}): {}'.format(client_ip, url))
r.lpush("download_queue", url)
ip_regex = r"([0-9]+(?:\.[0-9]+){3}\/\S*)"
ip_result = re.findall(ip_regex, command)
if ip_result:
for ip_url in ip_result:
if ip_url != '':
logging.info('New IP-based URL detected ({}): {}'.format(client_ip, ip_url))
r.lpush("download_queue", ip_url)
def handle_cmd(cmd, chan, ip):
detect_url(cmd, ip)
response = ""
if cmd.startswith("ls"):
response = "users.txt"
elif cmd.startswith("pwd"):
response = "/home/root"
elif cmd.startswith("cat /proc/cpuinfo | grep name | wc -l"):
response = "2"
elif cmd.startswith("uname -a"):
response = "Linux server 4.15.0-147-generic #151-Ubuntu SMP Fri Jun 18 19:21:19 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux"
elif cmd.startswith("cat /proc/cpuinfo | grep name | head -n 1 | awk '{print $4,$5,$6,$7,$8,$9;}'"):
response = "Intel(R) Xeon(R) CPU E5-2680 v3 @"
elif cmd.startswith("free -m | grep Mem | awk '{print $2 ,$3, $4, $5, $6, $7}'"):
response = "7976 5167 199 1 2609 2519"
elif cmd.startswith("ls -lh $(which ls)"):
response = "-rwxr-xr-x 1 root root 131K Jan 18 2018 /bin/ls"
elif cmd.startswith("crontab -l "):
response = "no crontab for root"
if response != '':
logging.info('Response from honeypot ({}): '.format(ip, response))
response = response + "\r\n"
chan.send(response)
class BasicSshHoneypot(paramiko.ServerInterface):
client_ip = None
def __init__(self, client_ip):
self.client_ip = client_ip
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
logging.info('client called check_channel_request ({}): {}'.format(
self.client_ip, kind))
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
def get_allowed_auths(self, username):
logging.info('client called get_allowed_auths ({}) with username {}'.format(
self.client_ip, username))
return "publickey,password"
def check_auth_publickey(self, username, key):
fingerprint = u(hexlify(key.get_fingerprint()))
logging.info('client public key ({}): username: {}, key name: {}, md5 fingerprint: {}, base64: {}, bits: {}'.format(
self.client_ip, username, key.get_name(), fingerprint, key.get_base64(), key.get_bits()))
return paramiko.AUTH_PARTIALLY_SUCCESSFUL
def check_auth_password(self, username, password):
# Accept all passwords as valid by default
logging.info('new client credentials ({}): username: {}, password: {}'.format(
self.client_ip, username, password))
return paramiko.AUTH_SUCCESSFUL
def check_channel_shell_request(self, channel):
self.event.set()
return True
def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes):
return True
def check_channel_exec_request(self, channel, command):
command_text = str(command.decode("utf-8"))
handle_cmd(command_text, channel, self.client_ip)
logging.info('client sent command via check_channel_exec_request ({}): {}'.format(
self.client_ip, command))
return True
def handle_connection(client, addr):
client_ip = addr[0]
logging.info('New connection from: {}'.format(client_ip))
print('New connection from: {}'.format(client_ip))
try:
transport = paramiko.Transport(client)
transport.add_server_key(HOST_KEY)
transport.local_version = SSH_BANNER # Change banner to appear more convincing
server = BasicSshHoneypot(client_ip)
try:
transport.start_server(server=server)
except paramiko.SSHException:
print('*** SSH negotiation failed.')
raise Exception("SSH negotiation failed")
# wait for auth
chan = transport.accept(10)
if chan is None:
print('*** No channel (from '+client_ip+').')
raise Exception("No channel")
chan.settimeout(10)
if transport.remote_mac != '':
logging.info('Client mac ({}): {}'.format(client_ip, transport.remote_mac))
if transport.remote_compression != '':
logging.info('Client compression ({}): {}'.format(client_ip, transport.remote_compression))
if transport.remote_version != '':
logging.info('Client SSH version ({}): {}'.format(client_ip, transport.remote_version))
if transport.remote_cipher != '':
logging.info('Client SSH cipher ({}): {}'.format(client_ip, transport.remote_cipher))
server.event.wait(10)
if not server.event.is_set():
logging.info('** Client ({}): never asked for a shell'.format(client_ip))
raise Exception("No shell request")
try:
chan.send("Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-128-generic x86_64)\r\n\r\n")
run = True
while run:
chan.send("$ ")
command = ""
while not command.endswith("\r"):
transport = chan.recv(1024)
print(client_ip+"- received:",transport)
# Echo input to psuedo-simulate a basic terminal
if(
transport != UP_KEY
and transport != DOWN_KEY
and transport != LEFT_KEY
and transport != RIGHT_KEY
and transport != BACK_KEY
):
chan.send(transport)
command += transport.decode("utf-8")
chan.send("\r\n")
command = command.rstrip()
logging.info('Command received ({}): {}'.format(client_ip, command))
if command == "exit":
logging.info('Connection closed (via exit command): {}'.format(client_ip))
run = False
else:
handle_cmd(command, chan, client_ip)
except Exception as err:
print('!!! Exception: {}: {}'.format(err.__class__, err))
try:
transport.close()
except Exception:
pass
chan.close()
except Exception as err:
print('!!! Exception: {}: {}'.format(err.__class__, err))
try:
transport.close()
except Exception:
pass
def start_server(port, bind):
"""Init and run the ssh server"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((bind, port))
except Exception as err:
print('*** Bind failed: {}'.format(err))
traceback.print_exc()
sys.exit(1)
threads = []
while True:
try:
sock.listen(100)
print('Listening for connection on port {} ...'.format(port))
client, addr = sock.accept()
except Exception as err:
print('*** Listen/accept failed: {}'.format(err))
traceback.print_exc()
new_thread = threading.Thread(target=handle_connection, args=(client, addr))
new_thread.start()
threads.append(new_thread)
for thread in threads:
thread.join()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Run an SSH honeypot server')
parser.add_argument("--port", "-p", help="The port to bind the ssh server to (default 22)", default=2222, type=int, action="store")
parser.add_argument("--bind", "-b", help="The address to bind the ssh server to", default="", type=str, action="store")
args = parser.parse_args()
start_server(args.port, args.bind)