Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
475 lines (415 sloc) 22 KB
#!/usr/bin/env python
__description__ = 'TCP honeypot'
__author__ = 'Didier Stevens'
__version__ = '0.0.4'
__date__ = '2019/03/12'
Source code put in public domain by Didier Stevens, no Copyright
Use at your own risk
2018/03/08: start
2018/03/09: continue
2018/03/17: continue, added ssl
2018/03/22: 0.0.2 added ssh
2018/08/26: 0.0.3 added randomness when selecting a matching regular expression
2018/09/09: added support for listeners via arguments
2018/12/23: 0.0.4 added THP_SPLIT
2019/03/12: added error handling
THP_REFERENCE = 'reference'
THP_SSL = 'ssl'
THP_CERTFILE = 'certfile'
THP_KEYFILE = 'keyfile'
THP_SSLCONTEXT = 'sslcontext'
THP_SSH = 'ssh'
THP_BANNER = 'banner'
THP_REPLY = 'reply'
THP_MATCH = 'match'
THP_LOOP = 'loop'
THP_REGEX = 'regex'
THP_ACTION = 'action'
THP_DISCONNECT = 'disconnect'
THP_SPLIT = 'split'
#Terminate With CR LF
def TW_CRLF(data):
if isinstance(data, str):
data = [data]
return '\r\n'.join(data + [''])
dListeners = {
22: {THP_BANNER: TW_CRLF('SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2')},
2222: {THP_REFERENCE: 22},
2200: {THP_SSH: {THP_KEYFILE: 'test_rsa.key', THP_BANNER: 'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2'},
THP_BANNER: TW_CRLF('Last login: Thu Mar 22 18:10:31 2018 from') + 'root@vps:~# ',
THP_REPLY: '\r\nroot@vps:~# ',
443: {THP_SSL: {THP_CERTFILE: 'cert-20180317-161753.crt', THP_KEYFILE: 'key-20180317-161753.pem'},
THP_REPLY: TW_CRLF(['HTTP/1.1 200 OK', 'Date: %TIME_GMT_RFC2822%', 'Server: Apache', 'Last-Modified: Wed, 06 Jul 2016 17:51:03 GMT', 'ETag: "59652-cfd-edc33a50bfec6"', 'Accept-Ranges: bytes', 'Content-Length: 285', 'Connection: close', 'Content-Type: text/html; charset=UTF-8', '', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">', '<link rel="icon" type="image/png" href="favicon.png"/>', '<html>', ' <head>', ' <title>Home</title>', ' <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">', ' </head>', ' <body>Welcome home!</body>', '</html>'])
8443: {THP_REFERENCE: 443},
80: {THP_REPLY: TW_CRLF(['HTTP/1.1 200 OK', 'Date: %TIME_GMT_RFC2822%', 'Server: Apache', 'Last-Modified: Wed, 06 Jul 2016 17:51:03 GMT', 'ETag: "59652-cfd-edc33a50bfec6"', 'Accept-Ranges: bytes', 'Content-Length: 285', 'Connection: close', 'Content-Type: text/html; charset=UTF-8', '', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">', '<link rel="icon" type="image/png" href="favicon.png"/>', '<html>', ' <head>', ' <title>Home</title>', ' <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">', ' </head>', ' <body>Welcome home!</body>', '</html>'])},
591: {THP_REFERENCE: 80},
8008: {THP_REFERENCE: 80},
8080: {THP_REFERENCE: 80},
25: {THP_LOOP: 10,
THP_BANNER: TW_CRLF('220 Microsoft ESMTP MAIL Service ready at %TIME_GMT_RFC2822%'),
'EHLO': {THP_REGEX: '^[Ee][Hh][Ll][Oo]', THP_REPLY: TW_CRLF(['', '250-PIPELINING', '250-SIZE 20971520', '250-ETRN', '250-ENHANCEDSTATUSCODES', '250 8BITMIME'])},
'default': {THP_REGEX: '^.', THP_REPLY: TW_CRLF('500 5.5.2 Error: bad syntax')},
11211: {THP_LOOP: 10,
'stats': {THP_REGEX: '^stats', THP_REPLY: TW_CRLF(['STAT pid 14868', 'STAT uptime 175931', 'STAT time %TIME_GMT_EPOCH%', 'STAT version 1.5.4', 'STAT id C3B806AA71F0887773210E75DD12BDAD', 'STAT pointer_size 32', 'STAT rusage_user 620.299700', 'STAT rusage_system 1545.703017', 'STAT curr_items 228', 'STAT total_items 779', 'STAT bytes 15525', 'STAT curr_connections 92', 'STAT total_connections 1740', 'STAT connection_structures 165', 'STAT cmd_get 7411', 'STAT cmd_set 28445156', 'STAT get_hits 5183', 'STAT get_misses 2228', 'STAT evictions 0', 'STAT bytes_read 2112768087', 'STAT bytes_written 1000038245', 'STAT limit_maxbytes 52428800', 'STAT threads 1', 'END'])},
'version': {THP_REGEX: '^version', THP_REPLY: TW_CRLF('VERSION 1.5.4')},
'get': {THP_REGEX: '^get ', THP_REPLY: TW_CRLF(['VALUE a 0 2', 'AA', 'END'])},
'set': {THP_REGEX: '^set ', THP_REPLY: TW_CRLF('STORED')},
21: {THP_LOOP: 10,
THP_BANNER: TW_CRLF('220 FTP server ready. All transfers are logged. (FTP) [no EPSV]'),
'user': {THP_REGEX: '^USER ', THP_REPLY: TW_CRLF('331 Please specify the password.')},
'pass': {THP_REGEX: '^PASS ', THP_REPLY: TW_CRLF('230 Login successful.')},
'typea': {THP_REGEX: '^TYPE A', THP_REPLY: TW_CRLF('200 Switching to ASCII mode.')},
'auth': {THP_REGEX: '^AUTH', THP_REPLY: TW_CRLF('530 Please login with USER and PASS.')},
'pasv': {THP_REGEX: '^PASV', THP_REPLY: TW_CRLF('227 Entering Passive Mode (121)')},
'help': {THP_REGEX: '^HELP', THP_REPLY: TW_CRLF(['220 FTP server ready. All transfers are logged. (FTP) [no EPSV]', '530 Please login with USER and PASS.'])},
121: {},
import optparse
import socket
import select
import threading
import time
import re
import ssl
import textwrap
import sys
import random
import traceback
import binascii
import paramiko
def PrintManual():
manual = r'''
TCP listeners are configured with Python dictionary dListeners. The key is the port number (integer) and the value is another dictionary (listener dictionary).
When this listener dictionary is empty, the honeypot will accept TCP connections on the configured port, perform a single read and then close the connection.
The listener can be configured to perform more than one read: add key THP_LOOP to the dictionary with an integer as value. The integer specifies the maximum number of reads.
A banner can be transmitted before the first read, this is done by adding key THP_BANNER to the dictionary with a string as the value (the banner).
The listener can be configured to send a reply after each read, this is done by adding key THP_REPLY to the dictionary with a string as the value (the reply).
To increase the interactivity of the honeypot, keywords can be defined with replies. This is done by adding a new dictionary to the dictionary with key THP_MATCH.
Entries in this match dictionary are regular expressions (THP_REGEX): when a regular expression matches read data, the corresponding reply is send or action performed (e.g. disconnect).
If more than one regular expression matches, then the longest matching is selected. If there is more than one longest match (e.g. equal length), then one is selected at random.
A listener can be configured to accept SSL/TLS connections by adding key THP_SSL to the listener dictionary with a dictionary as value specifying the certificate (THP_CERTFILE) and key (THP_KEYFILE) to use. If an SSL context can not be created (for example because of missing certificate file), the listener will fallback to TCP.
A listener can be configured to accept SSH connections by adding key THP_SSH to the listener dictionary with a dictionary as value specifying the key (THP_KEYFILE) to use. This requires Python module paramiko, the listener will fallback to TCP if this module is missing.
When several ports need to behave the same, the dictionary can just contain a reference (THP_REFERENCE) to the port which contains the detailed description.
Helper function TW_CRLF (Terminate With CR/LF) can be used to format replies and banners.
Replies and banners can contain aliases: %TIME_GMT_RFC2822% and %TIME_GMT_EPOCH%, they will be instantiated when a reply is transmitted.
Output is written to stdout and a log file.
This tool has several command-line options, and can take listeners as arguments. These arguments are filenames of Python programs that define listeners.
It is written for Python 2.7 and was tested on Windows 10, Ubuntu 16 and CentOS 6.
for line in manual.split('\n'):
print(textwrap.fill(line, 79))
#Convert 2 Bytes If Python 3
def C2BIP3(string):
if sys.version_info[0] > 2:
return bytes([ord(x) for x in string])
return string
#Convert 2 Integer If Python 2
def C2IIP2(data):
if sys.version_info[0] > 2:
return data
return ord(data)
# CIC: Call If Callable
def CIC(expression):
if callable(expression):
return expression()
return expression
# IFF: IF Function
def IFF(expression, valueTrue, valueFalse):
if expression:
return CIC(valueTrue)
return CIC(valueFalse)
def FormatTime(epoch=None):
if epoch == None:
epoch = time.time()
return '%04d%02d%02d-%02d%02d%02d' % time.localtime(epoch)[0:6]
class cOutput():
def __init__(self, filename=None, bothoutputs=False):
self.filename = filename
self.bothoutputs = bothoutputs
if self.filename and self.filename != '':
self.f = open(self.filename, 'w')
self.f = None
def Line(self, line):
if not self.f or self.bothoutputs:
if self.f:
self.f.write(line + '\n')
def LineTimestamped(self, line):
self.Line('%s: %s' % (FormatTime(), line))
def Exception(self):
self.LineTimestamped('Exception occured:')
if not self.f or self.bothoutputs:
if self.f:
def Close(self):
if self.f:
self.f = None
def ReplaceAliases(data):
data = data.replace('%TIME_GMT_RFC2822%', time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))
data = data.replace('%TIME_GMT_EPOCH%', str(int(time.time())))
return data
def ParseNumber(number):
if number.startswith('0x'):
return int(number[2:], 16)
return int(number)
def MyRange(begin, end):
if begin < end:
return range(begin, end + 1)
elif begin == end:
return [begin]
return range(begin, end - 1, -1)
def ParsePorts(expression):
ports = []
for portrange in expression.split(','):
result = portrange.split('-')
if len(result) == 1:
ports.extend(MyRange(ParseNumber(result[0]), ParseNumber(result[1])))
return ports
def ModuleLoaded(name):
return name in sys.modules
if ModuleLoaded('paramiko'):
class cSSHServer(paramiko.ServerInterface):
def __init__(self, oOutput, connectionID):
self.oEvent = threading.Event()
self.oOutput = oOutput
self.connectionID = connectionID
def check_channel_request(self, kind, chanid):
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
def check_auth_password(self, username, password):
self.oOutput.LineTimestamped('%s SSH username: %s' % (self.connectionID, username))
self.oOutput.LineTimestamped('%s SSH password: %s' % (self.connectionID, password))
return paramiko.AUTH_SUCCESSFUL
def get_allowed_auths(self, username):
return 'password'
def check_channel_shell_request(self, channel):
return True
def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes):
return True
def SplitIfRequested(dListener, data):
if THP_SPLIT in dListener:
return [part for part in data.split(dListener[THP_SPLIT]) if part != '']
return [data]
class ConnectionThread(threading.Thread):
global dListeners
def __init__(self, oSocket, oOutput, options):
self.oSocket = oSocket
self.oOutput = oOutput
self.options = options
def run(self):
oSocketConnection, address = self.oSocket.accept()
connectionID = '%s:%d-%s:%d' % (self.oSocket.getsockname() + address)
self.oOutput.LineTimestamped('%s connection' % connectionID)
dListener = dListeners[self.oSocket.getsockname()[1]]
if THP_REFERENCE in dListener:
dListener = dListeners[dListener[THP_REFERENCE]]
oSSLConnection = None
oSSLContext = dListener.get(THP_SSLCONTEXT, None)
oSSHConnection = None
oSSHFile = None
if oSSLContext != None:
oSSLConnection = oSSLContext.wrap_socket(oSocketConnection, server_side=True)
connection = oSSLConnection
elif dListener.get(THP_SSH, None) != None:
if ModuleLoaded('paramiko'):
if THP_KEYFILE in dListener[THP_SSH]:
oRSAKey = paramiko.RSAKey(filename=dListener[THP_SSH][THP_KEYFILE])
oRSAKey = paramiko.RSAKey.generate(1024)
self.oOutput.LineTimestamped('%s SSH generated RSA key' % connectionID)
oTransport = paramiko.Transport(oSocketConnection)
if THP_BANNER in dListener[THP_SSH]:
oTransport.local_version = dListener[THP_SSH][THP_BANNER]
oSSHServer = cSSHServer(self.oOutput, connectionID)
except paramiko.SSHException:
self.oOutput.LineTimestamped('%s SSH negotiation failed' % connectionID)
self.oOutput.LineTimestamped('%s SSH banner %s' % (connectionID, oTransport.remote_version))
oSSHConnection = oTransport.accept(20)
if oSSHConnection is None:
self.oOutput.LineTimestamped('%s SSH no channel' % connectionID)
self.oOutput.LineTimestamped('%s SSH authenticated' % connectionID)
if not oSSHServer.oEvent.is_set():
self.oOutput.LineTimestamped('%s SSH no shell' % connectionID)
connection = oSSHConnection
oSSHFile = oSSHConnection.makefile('rU')
self.oOutput.LineTimestamped('%s can not create SSH server, Python module paramiko missing' % connectionID)
connection = oSocketConnection
connection = oSocketConnection
if THP_BANNER in dListener:
self.oOutput.LineTimestamped('%s send banner' % connectionID)
for i in range(0, dListener.get(THP_LOOP, 1)):
if oSSHFile == None:
data = connection.recv(self.options.readbuffer)
data = oSSHFile.readline()
self.oOutput.LineTimestamped('%s data %s' % (connectionID, repr(data)))
for splitdata in SplitIfRequested(dListener, data):
if splitdata != data:
self.oOutput.LineTimestamped('%s splitdata %s' % (connectionID, repr(splitdata)))
if THP_REPLY in dListener:
self.oOutput.LineTimestamped('%s send reply' % connectionID)
if THP_MATCH in dListener:
matches = []
for matchname, dMatch in dListener[THP_MATCH].items():
oMatch =[THP_REGEX], splitdata)
if oMatch != None:
matches.append([len(, dMatch, matchname])
if matches != []:
matches = sorted(matches, reverse=True)
longestmatches = [match for match in matches if match[0] == matches[0][0]]
longestmatch = random.choice(longestmatches)
dMatchLongest = longestmatch[1]
if THP_REPLY in dMatchLongest:
self.oOutput.LineTimestamped('%s send %s reply' % (connectionID, longestmatch[2]))
if dMatchLongest.get(THP_ACTION, '') == THP_DISCONNECT:
self.oOutput.LineTimestamped('%s disconnecting' % connectionID)
#a# is it necessary to close both oSSLConnection and oSocketConnection?
if oSSLConnection != None:
self.oOutput.LineTimestamped('%s closed' % connectionID)
except socket.timeout:
self.oOutput.LineTimestamped('%s timeout' % connectionID)
except Exception as e:
self.oOutput.LineTimestamped('%s %s' % (connectionID, str(e)))
def TCPHoneypot(filenames, options):
global dListeners
for filename in filenames:
execfile(filename, globals())
oOutput = cOutput('tcp-honeypot-%s.log' % FormatTime(), True)
if ModuleLoaded('paramiko'):
paramiko.util.log_to_file('tcp-honeypot-ssh-%s.log' % FormatTime())
if options.ports != '':
oOutput.LineTimestamped('Ports specified via command-line option: %s' % options.ports)
dListeners = {}
for port in ParsePorts(options.ports):
dListeners[port] = {}
if options.extraports != '':
oOutput.LineTimestamped('Extra ports: %s' % options.extraports)
for port in ParsePorts(options.extraports):
dListeners[port] = {}
sockets = []
for port in dListeners.keys():
if THP_SSL in dListeners[port]:
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile=dListeners[port][THP_SSL][THP_CERTFILE], keyfile=dListeners[port][THP_SSL][THP_KEYFILE])
dListeners[port][THP_SSLCONTEXT] = context
oOutput.LineTimestamped('Created SSL context for %d' % port)
except IOError as e:
if '[Errno 2]' in str(e):
oOutput.LineTimestamped('Error reading certificate and/or key file: %s %s' % (dListeners[port][THP_SSL][THP_CERTFILE], dListeners[port][THP_SSL][THP_KEYFILE]))
oOutput.LineTimestamped('Error creating SSL context: %s' % e)
oOutput.LineTimestamped('SSL not enabled for %d' % port)
oSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
oSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
oSocket.bind((options.address, port))
except socket.error as e:
if '[Errno 98] Address already in use' in str(e):
oOutput.LineTimestamped('Port %d can not be used, it is already open' % port)
elif '[Errno 99] Cannot assign requested address' in str(e) or '[Errno 10049] The requested address is not valid in its context' in str(e):
oOutput.LineTimestamped('Address %s can not be used (port %d)' % (options.address, port))
elif '[Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions' in str(e):
oOutput.LineTimestamped('Port %d can not be used, access is forbidden' % port)
raise e
oOutput.LineTimestamped('Listening on %s %d' % oSocket.getsockname())
if sockets == []:
while True:
readables, writables, exceptionals =, [], [])
for oSocket in readables:
ConnectionThread(oSocket, oOutput, options).start()
def Main():
moredesc = '''
Source code put in the public domain by Didier Stevens, no Copyright
Use at your own risk'''
oParser = optparse.OptionParser(usage='usage: %prog [options]\n' + __description__ + moredesc, version='%prog ' + __version__)
oParser.add_option('-m', '--man', action='store_true', default=False, help='Print manual')
oParser.add_option('-t', '--timeout', type=int, default=10, help='Timeout value for sockets in seconds (default 10s)')
oParser.add_option('-r', '--readbuffer', type=int, default=10240, help='Size read buffer in bytes (default 10240)')
oParser.add_option('-a', '--address', default='', help='Address to listen on (default')
oParser.add_option('-P', '--ports', default='', help='Ports to listen on (overrides ports configured in the program)')
oParser.add_option('-p', '--extraports', default='', help='Extra ports to listen on (default none)')
(options, args) = oParser.parse_args()
TCPHoneypot(args, options)
if __name__ == '__main__':
You can’t perform that action at this time.