mssqlpot 2.0.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. core/__init__.py +0 -0
  2. core/config.py +50 -0
  3. core/logfile.py +74 -0
  4. core/output.py +39 -0
  5. core/paths.py +53 -0
  6. core/protocol.py +143 -0
  7. core/tools.py +157 -0
  8. mssqlpot/__init__.py +25 -0
  9. mssqlpot/cli.py +511 -0
  10. mssqlpot/data/Dockerfile +56 -0
  11. mssqlpot/data/docs/INSTALL.md +399 -0
  12. mssqlpot/data/docs/INSTALLWIN.md +410 -0
  13. mssqlpot/data/docs/PLUGINS.md +21 -0
  14. mssqlpot/data/docs/TODO.md +8 -0
  15. mssqlpot/data/docs/datadog/README.md +32 -0
  16. mssqlpot/data/docs/discord/README.md +49 -0
  17. mssqlpot/data/docs/geoipupdtask.ps1 +270 -0
  18. mssqlpot/data/docs/mysql/README.md +176 -0
  19. mssqlpot/data/docs/mysql/READMEWIN.md +157 -0
  20. mssqlpot/data/docs/mysql/mysql.sql +62 -0
  21. mssqlpot/data/docs/postgres/README.md +184 -0
  22. mssqlpot/data/docs/postgres/READMEWIN.md +196 -0
  23. mssqlpot/data/docs/postgres/postgres.sql +56 -0
  24. mssqlpot/data/docs/slack/README.md +68 -0
  25. mssqlpot/data/docs/sqlite3/README.md +131 -0
  26. mssqlpot/data/docs/sqlite3/READMEWIN.md +123 -0
  27. mssqlpot/data/docs/sqlite3/sqlite3.sql +52 -0
  28. mssqlpot/data/docs/telegram/README.md +103 -0
  29. mssqlpot/data/etc/honeypot.cfg +427 -0
  30. mssqlpot/data/etc/honeypot.cfg.base +417 -0
  31. mssqlpot/data/test/.gitignore +3 -0
  32. mssqlpot/data/test/test.py +59 -0
  33. mssqlpot/honeypot.py +118 -0
  34. mssqlpot-2.0.0.dist-info/METADATA +151 -0
  35. mssqlpot-2.0.0.dist-info/RECORD +61 -0
  36. mssqlpot-2.0.0.dist-info/WHEEL +6 -0
  37. mssqlpot-2.0.0.dist-info/entry_points.txt +2 -0
  38. mssqlpot-2.0.0.dist-info/licenses/LICENSE +674 -0
  39. mssqlpot-2.0.0.dist-info/top_level.txt +3 -0
  40. output_plugins/__init__.py +0 -0
  41. output_plugins/couch.py +68 -0
  42. output_plugins/datadog.py +74 -0
  43. output_plugins/discord.py +125 -0
  44. output_plugins/elastic.py +137 -0
  45. output_plugins/hpfeed.py +43 -0
  46. output_plugins/influx2.py +62 -0
  47. output_plugins/jsonlog.py +36 -0
  48. output_plugins/kafka.py +57 -0
  49. output_plugins/localsyslog.py +66 -0
  50. output_plugins/mongodb.py +83 -0
  51. output_plugins/mysql.py +201 -0
  52. output_plugins/nlcvapi.py +119 -0
  53. output_plugins/postgres.py +142 -0
  54. output_plugins/redisdb.py +47 -0
  55. output_plugins/rethinkdblog.py +46 -0
  56. output_plugins/slack.py +85 -0
  57. output_plugins/socketlog.py +40 -0
  58. output_plugins/sqlite.py +132 -0
  59. output_plugins/telegram.py +130 -0
  60. output_plugins/textlog.py +37 -0
  61. output_plugins/xmpp.py +181 -0
core/__init__.py ADDED
File without changes
core/config.py ADDED
@@ -0,0 +1,50 @@
1
+
2
+ from configparser import ConfigParser, ExtendedInterpolation
3
+
4
+ from os import environ
5
+
6
+
7
+ def to_environ_key(key):
8
+ return key.upper()
9
+
10
+
11
+ class EnvironmentConfigParser(ConfigParser):
12
+
13
+ def has_option(self, section, option):
14
+ if to_environ_key('_'.join((section, option))) in environ:
15
+ return True
16
+ return super(EnvironmentConfigParser, self).has_option(section, option)
17
+
18
+ def get(self, section, option, **kwargs):
19
+ key = to_environ_key('_'.join((section, option)))
20
+ if key in environ:
21
+ return environ[key]
22
+ return super(EnvironmentConfigParser, self).get(section, option, **kwargs)
23
+
24
+
25
+ def readConfigFile(cfgfile):
26
+ """
27
+ Read config files and return ConfigParser object
28
+
29
+ @param cfgfile: filename or array of filenames
30
+ @return: ConfigParser object
31
+ """
32
+ parser = EnvironmentConfigParser(
33
+ interpolation=ExtendedInterpolation(),
34
+ converters={'list': lambda x: [i.strip() for i in x.split(',')]}
35
+ )
36
+ parser.read(cfgfile)
37
+ return parser
38
+
39
+
40
+ def _config_files():
41
+ # Import here (not at module top) to avoid any circular-import risk.
42
+ from core.paths import workdir_path, bundled
43
+ return [
44
+ bundled('etc', 'honeypot.cfg.base'), # bundled read-only defaults
45
+ workdir_path('etc', 'honeypot.cfg'), # site-local overrides
46
+ workdir_path('honeypot.cfg'), # convenience root-level override
47
+ ]
48
+
49
+
50
+ CONFIG = readConfigFile(_config_files())
core/logfile.py ADDED
@@ -0,0 +1,74 @@
1
+
2
+ from sys import stdout
3
+ from datetime import datetime
4
+
5
+ from pytz import timezone
6
+
7
+ from twisted.python import log, util
8
+ from twisted.python.logfile import DailyLogFile
9
+
10
+
11
+ class HoneypotDailyLogFile(DailyLogFile):
12
+ """
13
+ Overload original Twisted with improved date formatting
14
+ """
15
+
16
+ def suffix(self, tupledate):
17
+ """
18
+ Return the suffix given a (year, month, day) tuple or unixtime
19
+ """
20
+ try:
21
+ return "{:02d}-{:02d}-{:02d}".format(tupledate[0], tupledate[1], tupledate[2])
22
+ except Exception:
23
+ # try taking a float unixtime
24
+ return '_'.join(map(str, self.toDate(tupledate)))
25
+
26
+
27
+ def myFLOemit(self, eventDict):
28
+ """
29
+ Format the given log event as text and write it to the output file.
30
+
31
+ @param eventDict: a log event
32
+ @type eventDict: L{dict} mapping L{str} (native string) to L{object}
33
+ """
34
+
35
+ # Custom emit for FileLogObserver
36
+ text = log.textFromEventDict(eventDict)
37
+ if text is None:
38
+ return
39
+ timeStr = self.formatTime(eventDict['time'])
40
+ fmtDict = {
41
+ 'text': text.replace('\n', '\n\t')
42
+ }
43
+ msgStr = log._safeFormat('%(text)s\n', fmtDict)
44
+ util.untilConcludes(self.write, timeStr + ' ' + msgStr)
45
+ util.untilConcludes(self.flush)
46
+
47
+
48
+ def myFLOformatTime(self, when):
49
+ """
50
+ Log time in UTC
51
+
52
+ By default it's formatted as an ISO8601-like string (ISO8601 date and
53
+ ISO8601 time separated by a space). It can be customized using the
54
+ C{timeFormat} attribute, which will be used as input for the underlying
55
+ L{datetime.datetime.strftime} call.
56
+
57
+ @type when: C{int}
58
+ @param when: POSIX (ie, UTC) timestamp.
59
+
60
+ @rtype: C{str}
61
+ """
62
+ timeFormatString = self.timeFormat
63
+ if timeFormatString is None:
64
+ timeFormatString = '[%Y-%m-%d %H:%M:%S.%fZ]'
65
+ return datetime.fromtimestamp(when, tz=timezone('UTC')).strftime(timeFormatString)
66
+
67
+
68
+ def set_logger(cfg_options):
69
+ log.FileLogObserver.emit = myFLOemit
70
+ log.FileLogObserver.formatTime = myFLOformatTime
71
+ if cfg_options['logfile'] is None:
72
+ log.startLogging(stdout)
73
+ else:
74
+ log.startLogging(HoneypotDailyLogFile.fromFullPath(cfg_options['logfile']), setStdout=False)
core/output.py ADDED
@@ -0,0 +1,39 @@
1
+
2
+ from socket import gethostname
3
+
4
+ from core.config import CONFIG
5
+
6
+
7
+ class Output(object):
8
+ """
9
+ Abstract base class intended to be inherited by output plugins.
10
+ """
11
+
12
+ def __init__(self, general_options):
13
+
14
+ self.cfg = general_options
15
+
16
+ if 'sensor' in self.cfg:
17
+ self.sensor = self.cfg['sensor']
18
+ else:
19
+ self.sensor = CONFIG.get('honeypot', 'sensor_name', fallback=gethostname())
20
+
21
+ self.start()
22
+
23
+ def start(self):
24
+ """
25
+ Abstract method to initialize output plugin
26
+ """
27
+ pass
28
+
29
+ def stop(self):
30
+ """
31
+ Abstract method to shut down output plugin
32
+ """
33
+ pass
34
+
35
+ def write(self, event):
36
+ """
37
+ Handle a general event within the output plugin
38
+ """
39
+ pass
core/paths.py ADDED
@@ -0,0 +1,53 @@
1
+ """
2
+ paths.py - Single source of truth for runtime path resolution.
3
+
4
+ The honeypot needs a "working directory" containing:
5
+ data/ geolocation databases, SQLite db, etc.
6
+ etc/ config file (honeypot.cfg.base)
7
+ log/ rotating log files (created on demand)
8
+
9
+ Priority for locating the working directory:
10
+ 1. MSSQLPOT_WORKDIR environment variable
11
+ 2. Current working directory
12
+
13
+ The bundled read-only defaults (etc/*.cfg.base, responses/*.json)
14
+ are installed inside the `mssqlpot` package and located via the package's
15
+ own __file__ attribute, which works on all Python versions without
16
+ requiring pkg_resources or importlib.resources.
17
+ """
18
+
19
+ from __future__ import absolute_import
20
+
21
+
22
+ from os import getcwd, environ
23
+ from os.path import abspath, dirname, join
24
+
25
+
26
+ def get_workdir():
27
+ """Return the absolute path to the runtime working directory."""
28
+ env = environ.get('MSSQLPOT_WORKDIR', '').strip()
29
+ if env:
30
+ return abspath(env)
31
+ return getcwd()
32
+
33
+
34
+ def workdir_path(*parts):
35
+ """Return an absolute path rooted at the working directory."""
36
+ return join(get_workdir(), *parts)
37
+
38
+
39
+ def bundled(*parts):
40
+ """
41
+ Return the filesystem path to a file bundled inside the installed package.
42
+ Arguments are path components relative to the mssqlpot/data/ directory,
43
+ passed as separate strings (like os.path.join) to avoid hardcoded separators.
44
+
45
+ Uses the package's own __file__ to locate the data directory, which works
46
+ on all Python versions (2.7+) without requiring pkg_resources or
47
+ importlib.resources.
48
+ """
49
+ # mssqlpot/data/ lives alongside this module's package (core/ is a sibling
50
+ # of mssqlpot/), so we go up one level from core/ to find mssqlpot/data/.
51
+ here = dirname(abspath(__file__))
52
+ package_dir = join(dirname(here), 'mssqlpot')
53
+ return join(package_dir, 'data', *parts)
core/protocol.py ADDED
@@ -0,0 +1,143 @@
1
+
2
+ from __future__ import absolute_import
3
+
4
+ from binascii import hexlify, unhexlify
5
+ from ipaddress import ip_address, ip_network
6
+ from struct import pack, unpack
7
+ from sys import version_info
8
+ from time import time
9
+ from uuid import uuid4
10
+
11
+ from core.tools import (
12
+ decode,
13
+ get_local_ip,
14
+ get_utc_time,
15
+ write_event
16
+ )
17
+
18
+ from twisted.internet.protocol import Factory, Protocol
19
+ from twisted.python.log import msg
20
+
21
+
22
+ if version_info[0] >= 3:
23
+ def unicode(x):
24
+ return x
25
+ def ord(x):
26
+ return x
27
+
28
+
29
+ class PacketType:
30
+ login = 0x10
31
+ pre_login = 0x12
32
+
33
+
34
+ class MSSQLServer(Protocol):
35
+ def __init__(self, options):
36
+ self.cfg = options
37
+ self.state = None
38
+
39
+ def dataReceived(self, data):
40
+ if self.state == 1:
41
+ version = '11000000'
42
+ packet_type = ord(data[0])
43
+ if packet_type == PacketType.pre_login:
44
+ self.transport.write(
45
+ unhexlify(
46
+ '0401002500000100000015000601001b000102'
47
+ '001c000103001d0000ff' + version + '00000200'
48
+ )
49
+ )
50
+ elif packet_type == PacketType.login:
51
+ self.handle_login(data)
52
+ else:
53
+ self.transport.loseConnection()
54
+
55
+ def connectionMade(self):
56
+ self.state = 1
57
+ self.session = uuid4().hex[:12]
58
+ peer = self.transport.getPeer()
59
+ self.report_event(self.session, 'connect', peer.host, peer.port)
60
+
61
+ def connectionLost(self, reason):
62
+ peer = self.transport.getPeer()
63
+ self.report_event(self.session, 'disconnect', peer.host, peer.port, reason.value)
64
+ self.state = None
65
+ self.session = None
66
+
67
+ def handle_login(self, data):
68
+ value_start, value_length = unpack('=HH', data[48:52])
69
+ username = decode(data[8 + value_start : 8 + value_start + (value_length * 2)].replace(b'\x00', b''))
70
+ value_start, value_length = unpack('=HH', data[52:56])
71
+ password = data[8 + value_start : 8 + value_start + (value_length * 2)]
72
+ password = password.replace(b'\x00', b'').replace(b'\xa5', b'')
73
+ password_decrypted = ''
74
+ for x in password:
75
+ password_decrypted += chr(((ord(x) ^ 0xA5) & 0x0F) << 4 | ((ord(x) ^ 0xA5) & 0xF0) >> 4)
76
+ peer = self.transport.getPeer()
77
+ self.report_event(self.session, 'login', peer.host, peer.port, username, password_decrypted)
78
+ payload = self.create_payload(server_name=self.cfg['server_name'], token_error_msg='Login Failed', error_code=18456)
79
+ self.transport.write(payload)
80
+
81
+ def create_payload(self, server_name='', token_error_msg='', error_code=2):
82
+ if token_error_msg == '':
83
+ token_error_msg = 'An error has occurred while establishing a connection to the server.'
84
+ server_name_hex_len = hexlify(pack('b', len(server_name)))
85
+ token_error_msg_hex_len = hexlify(pack('<H', len(token_error_msg)))
86
+ error_code_hex = hexlify(pack('<I', error_code))
87
+ token_error_hex = (
88
+ error_code_hex
89
+ + b'010e'
90
+ + token_error_msg_hex_len
91
+ + hexlify(token_error_msg.encode('utf-16-le'))
92
+ + server_name_hex_len
93
+ + hexlify(server_name.encode('utf-16-le'))
94
+ + b'0001000000'
95
+ )
96
+ token_done_hex = b'fd020000000000000000000000'
97
+ token_error_len = hexlify(pack('<H', len(unhexlify(token_error_hex))))
98
+ data_stream = (
99
+ b'0401007600350100aa'
100
+ + token_error_len
101
+ + token_error_hex
102
+ + token_done_hex
103
+ )
104
+ data_len = hexlify(pack('>H', len(unhexlify(data_stream))))
105
+ return unhexlify(data_stream[0:4] + data_len + data_stream[8:])
106
+
107
+ def report_event(self, session, operation, ip, port, username=None, password=None):
108
+ for network in self.cfg['blacklist']:
109
+ if ip_address(unicode(ip)) in ip_network(unicode(network)):
110
+ return
111
+ event = {}
112
+ event['session'] = session
113
+ unix_time = time()
114
+ operation = operation.lower()
115
+ if operation == 'login':
116
+ event['username'] = username
117
+ event['password'] = password
118
+ message = 'Login with username: "{}", password: "{}" from {}:{}.'.format(username, password, ip, port)
119
+ elif operation == 'connect':
120
+ message = 'Connection made from {}:{}.'.format(ip, port)
121
+ elif operation == 'disconnect':
122
+ message = '{}:{} disconnected. Reason: {}'.format(ip, port, username)
123
+ else:
124
+ message = 'Error: Unknown operation "{}".'.format(operation)
125
+ event['eventid'] = 'mssqlpot.' + operation
126
+ event['operation'] = operation
127
+ event['timestamp'] = get_utc_time(unix_time)
128
+ event['unixtime'] = unix_time
129
+ event['src_ip'] = ip
130
+ event['src_port'] = port
131
+ event['dst_port'] = self.cfg['port']
132
+ event['sensor'] = self.cfg['sensor']
133
+ event['dst_ip'] = self.cfg['public_ip'] if self.cfg['report_public_ip'] else get_local_ip()
134
+ msg(message)
135
+ write_event(event, self.cfg)
136
+
137
+
138
+ class MSSQLFactory(Factory):
139
+ def __init__(self, options):
140
+ self.cfg = options
141
+
142
+ def buildProtocol(self, addr):
143
+ return MSSQLServer(self.cfg)
core/tools.py ADDED
@@ -0,0 +1,157 @@
1
+
2
+ from datetime import datetime
3
+ from ipaddress import ip_address, ip_network
4
+ from os import makedirs, path
5
+ from socket import socket, AF_INET, SOCK_DGRAM
6
+ from sys import version_info
7
+
8
+ from core.config import CONFIG
9
+
10
+ from pytz import timezone
11
+
12
+ from twisted.python.log import msg
13
+
14
+ try:
15
+ from urllib.request import urlopen
16
+ except ImportError:
17
+ from urllib import urlopen
18
+
19
+
20
+ if version_info[0] >= 3:
21
+ def decode(x):
22
+ return x.decode('utf-8', errors='ignore')
23
+ def encode(x):
24
+ return x.encode()
25
+ def ord(x):
26
+ return x
27
+ def to_bytes(x):
28
+ return bytes(x, 'ascii')
29
+ def unicode(x):
30
+ return x
31
+ else:
32
+ def decode(x):
33
+ return x
34
+ def encode(x):
35
+ return x
36
+ def to_bytes(x):
37
+ return bytes(x)
38
+
39
+
40
+ def mkdir(dir_path):
41
+ if not dir_path:
42
+ return
43
+ if path.exists(dir_path) and path.isdir(dir_path):
44
+ return
45
+ makedirs(dir_path)
46
+
47
+
48
+ def import_plugins(cfg):
49
+ # Load output modules (inspired by the Cowrie honeypot)
50
+ msg('Loading the plugins...')
51
+ output_plugins = []
52
+ general_options = cfg
53
+ for x in CONFIG.sections():
54
+ if not x.startswith('output_'):
55
+ continue
56
+ if CONFIG.getboolean(x, 'enabled') is False:
57
+ continue
58
+ engine = x.split('_')[1]
59
+ try:
60
+ output = __import__('output_plugins.{}'.format(engine),
61
+ globals(), locals(), ['output'], 0).Output(general_options)
62
+ output_plugins.append(output)
63
+ msg('Loaded output engine: {}'.format(engine))
64
+ except ImportError as e:
65
+ msg('Failed to load output engine: {} due to ImportError: {}'.format(engine, e))
66
+ except Exception as e:
67
+ msg('Failed to load output engine: {} {}'.format(engine, e))
68
+ return output_plugins
69
+
70
+
71
+ def stop_plugins(cfg):
72
+ msg('Stoping the plugins...')
73
+ for plugin in cfg['output_plugins']:
74
+ try:
75
+ plugin.stop()
76
+ except Exception as e:
77
+ msg(e)
78
+ continue
79
+
80
+
81
+ def get_public_ip(ip_reporter):
82
+ try:
83
+ if version_info[0] < 3:
84
+ return urlopen(ip_reporter).read().decode('latin1', errors='replace').encode('utf-8')
85
+ else:
86
+ return decode(urlopen(ip_reporter).read())
87
+ except:
88
+ return None
89
+
90
+
91
+ def get_local_ip():
92
+ s = socket(AF_INET, SOCK_DGRAM)
93
+ try:
94
+ s.connect(('10.255.255.255', 1))
95
+ ip = s.getsockname()[0]
96
+ except:
97
+ ip = '127.0.0.1'
98
+ finally:
99
+ s.close()
100
+ return ip
101
+
102
+
103
+ def get_utc_time(unix_time):
104
+ return datetime.fromtimestamp(unix_time, tz=timezone('UTC')).isoformat() + 'Z'
105
+
106
+
107
+ def write_event(event, cfg):
108
+ ip = event['src_ip']
109
+ for network in cfg['blacklist']:
110
+ if ip_address(unicode(ip)) in ip_network(unicode(network)):
111
+ return
112
+ output_plugins = cfg['output_plugins']
113
+ for plugin in output_plugins:
114
+ try:
115
+ plugin.write(event)
116
+ except Exception as e:
117
+ msg(e)
118
+ continue
119
+
120
+
121
+ def geolocate(remote_ip, reader_city, reader_asn):
122
+ try:
123
+ response_city = reader_city.city(remote_ip)
124
+ city = response_city.city.name
125
+ if city is None:
126
+ city = ''
127
+ else:
128
+ city = decode(city.encode('utf-8'))
129
+ country = response_city.country.name
130
+ if country is None:
131
+ country = ''
132
+ country_code = ''
133
+ else:
134
+ country = decode(country.encode('utf-8'))
135
+ country_code = decode(response_city.country.iso_code.encode('utf-8'))
136
+ except Exception as e:
137
+ msg(e)
138
+ city = ''
139
+ country = ''
140
+ country_code = ''
141
+
142
+ try:
143
+ response_asn = reader_asn.asn(remote_ip)
144
+ if response_asn.autonomous_system_organization is None:
145
+ org = ''
146
+ else:
147
+ org = decode(response_asn.autonomous_system_organization.encode('utf-8'))
148
+
149
+ if response_asn.autonomous_system_number is not None:
150
+ asn_num = response_asn.autonomous_system_number
151
+ else:
152
+ asn_num = 0
153
+ except Exception as e:
154
+ msg(e)
155
+ org = ''
156
+ asn_num = 0
157
+ return country, country_code, city, org, asn_num
mssqlpot/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ # mssqlpot: the installable Python package for the mssqlpot honeypot.
2
+ #
3
+ # After `pip install mssqlpot`, use the `mssqlpot` command:
4
+ #
5
+ # mssqlpot init -- scaffold a working directory
6
+ # mssqlpot run -- start the honeypot in the foreground
7
+ # mssqlpot start -- start the honeypot in the background
8
+ # mssqlpot stop -- stop the background honeypot
9
+ # mssqlpot restart -- restart the honeypot (stop and start the honeypot in
10
+ # the background)
11
+ # mssqlpot status -- show running status
12
+ #
13
+ # NOTE: mssqlpot/honeypot.py is generated at build time by the build_py
14
+ # hook in setup.py - it is a copy of the top-level honeypot.py bundled so
15
+ # that the `mssqlpot run/start` entry point can locate and run it.
16
+ # It is listed in .gitignore and should not be committed.
17
+ #
18
+ # Contents:
19
+ # cli.py the `mssqlpot` console entry point (init/run/start/stop/status)
20
+ # honeypot.py the main honeypot script (copied from repo root at build time)
21
+ # data/ bundled read-only assets copied to the working directory
22
+ # by `mssqlpot init`:
23
+ # docs/ documentation and SQL schema files
24
+ # etc/ default configuration templates
25
+ # test/ test.py for verifying a running honeypot