├── plugins └── tableau_hll │ ├── .gitignore │ ├── test.py │ └── __init__.py ├── requirements.txt ├── setup.sh ├── test_plugin.py ├── config.yml ├── .gitignore ├── connection.py ├── README.md ├── interceptors.py ├── config_schema.py ├── proxy.py └── LICENSE /plugins/tableau_hll/.gitignore: -------------------------------------------------------------------------------- 1 | config.yml 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | psycopg2-binary==2.9.3 2 | PyYAML==6.0 3 | -------------------------------------------------------------------------------- /setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ ! -d "./.venv" ]; then 4 | echo "Creating virtual environment.." 5 | python3 -m venv .venv 6 | fi 7 | 8 | source .venv/bin/activate 9 | 10 | echo "Installing requirements.." 11 | python3 -m pip install -r requirements.txt 12 | -------------------------------------------------------------------------------- /test_plugin.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import sys 3 | 4 | """ Rudimentary test runner for plugins 5 | Pass in the plugin name as an argument, and make sure that there is a test.py file with a run() function in the plugin 6 | directory. 7 | """ 8 | 9 | plugin = sys.argv[1] 10 | test = importlib.import_module('plugins.' + plugin + '.test') 11 | 12 | test.run() 13 | -------------------------------------------------------------------------------- /config.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | - tableau_hll 3 | 4 | settings: 5 | log-level: debug 6 | intercept-log: logs/intercept.log 7 | general-log: logs/general.log 8 | 9 | instances: 10 | - listen: 11 | name: proxy 12 | host: 127.0.0.1 13 | port: 5111 14 | redirect: 15 | name: postgresql 16 | host: 127.0.0.1 17 | port: 5432 18 | intercept: 19 | commands: 20 | queries: 21 | - plugin: tableau_hll 22 | function: rewrite_query 23 | connects: 24 | responses: 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # visual studio code settings 107 | .vscode 108 | 109 | # Intellij 110 | .idea 111 | -------------------------------------------------------------------------------- /plugins/tableau_hll/test.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import os 3 | import plugins.tableau_hll as hll 4 | import yaml 5 | 6 | def test_context(): 7 | with open(os.path.dirname(__file__) + '/config.yml', 'r') as fp: 8 | config = yaml.load(fp) 9 | InstanceConfig = collections.namedtuple('InstanceConfig', 'redirect') 10 | Redirect = collections.namedtuple('Redirect', 'name host port') 11 | return { 12 | 'instance_config': InstanceConfig(redirect=Redirect(**config['redirect'])), 13 | 'connect_params': config['connect_params'] 14 | } 15 | 16 | 17 | def run(): 18 | queries = [ 19 | ( 20 | 'SELECT COUNT(DISTINCT "crm_data_source"."Set of Customers") AS "ctd:Set of Customers:ok"\nFROM "crm_dim"."crm_data_source" "crm_data_source"\nHAVING (COUNT(1) > 0);', 21 | 'SELECT hll_cardinality(hll_union_agg("crm_data_source"."Set of Customers")) :: BIGINT AS "ctd:Set of Customers:ok"\nFROM "crm_dim"."crm_data_source" "crm_data_source"\nHAVING (COUNT(1) > 0);' 22 | ), 23 | ( 24 | 'BEGIN;declare "SQL_CUR0x7fb46c01e3b0" cursor with hold for SELECT CAST("crm_data_source"."Campaign Name" AS TEXT) AS "Campaign Name",\n COUNT(DISTINCT "crm_data_source"."Set of Unique Clicks") AS "usr:# Unique Customers (copy):ok"\nFROM "crm_dim"."crm_data_source" "crm_data_source"\nGROUP BY 1;fetch 2048 in "SQL_CUR0x7fb46c01e3b0"', 25 | 'BEGIN;declare "SQL_CUR0x7fb46c01e3b0" cursor with hold for SELECT CAST("crm_data_source"."Campaign Name" AS TEXT) AS "Campaign Name",\n hll_cardinality(hll_union_agg("crm_data_source"."Set of Unique Clicks")) :: BIGINT AS "usr:# Unique Customers (copy):ok"\nFROM "crm_dim"."crm_data_source" "crm_data_source"\nGROUP BY 1;fetch 2048 in "SQL_CUR0x7fb46c01e3b0"' 26 | ) 27 | ] 28 | context = test_context() 29 | for src, dst in queries: 30 | res = hll.rewrite_query(src, context) 31 | try: 32 | assert res == dst 33 | except AssertionError: 34 | print(f"Rewriting query:\n\n{src}\n\nExpecting:\n\n{dst}\n\nGot:\n\n{res}") 35 | -------------------------------------------------------------------------------- /connection.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | class Connection: 4 | def __init__(self, sock, address, name, events, context): 5 | self.sock = sock 6 | self.address = address 7 | self.name = name 8 | self.events = events 9 | self.context = context 10 | self.interceptor = None 11 | self.redirect_conn = None 12 | self.out_bytes = b'' 13 | self.in_bytes = b'' 14 | 15 | def parse_length(self, length_bytes): 16 | return int.from_bytes(length_bytes, 'big') 17 | 18 | def encode_length(self, length): 19 | return length.to_bytes(4, byteorder='big') 20 | 21 | def received(self, in_bytes): 22 | self.in_bytes += in_bytes 23 | # Read packet from byte array while there are enough bytes to make up a packet. 24 | # Otherwise wait for more bytes to be received (break and exit) 25 | while True: 26 | ptype = self.in_bytes[0:1] 27 | if ptype == b'\x00': 28 | if len(self.in_bytes) < 4: 29 | break 30 | header_length = 4 31 | body_length = self.parse_length(self.in_bytes[0:4]) - 4 32 | elif ptype == b'N': 33 | header_length = 1 34 | body_length = 0 35 | else: 36 | if len(self.in_bytes) < 5: 37 | break 38 | header_length = 5 39 | body_length = self.parse_length(self.in_bytes[1:5]) - 4 40 | 41 | length = header_length + body_length 42 | if len(self.in_bytes) < length: 43 | break 44 | header = self.in_bytes[0:header_length] 45 | body = self.in_bytes[header_length:length] 46 | self.process_inbound_packet(header, body) 47 | self.in_bytes = self.in_bytes[length:] 48 | 49 | def process_inbound_packet(self, header, body): 50 | if header != b'N': 51 | packet_type = header[0:-4] 52 | logging.info("intercepting packet of type '%s' from %s", packet_type, self.name) 53 | body = self.interceptor.intercept(packet_type, body) 54 | header = packet_type + self.encode_length(len(body) + 4) 55 | message = header + body 56 | logging.debug("Received message. Relaying. Speaker: %s, message:\n%s", self.name, message) 57 | self.redirect_conn.out_bytes += message 58 | 59 | def sent(self, num_bytes): 60 | self.out_bytes = self.out_bytes[num_bytes:] 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Postgresql Proxy 2 | 3 | Serves as a proper server that Postgresql clients can connect to. Can modify packets that pass through. 4 | 5 | Currently used for rewriting queries to force proper use of postgres-hll module by external proprietary software that doesn't know about that functionality 6 | 7 | ## Installing 8 | ### Linux 9 | 1. Make sure you have [python3 and pip3 installed on your system](https://stackoverflow.com/questions/6587507/how-to-install-pip-with-python-3#6587528). It has been tested with Python3.6 but should also run on Python3.5. 10 | 2. Clone it locally and cd to that directory 11 | ``` 12 | git clone git@github.com:kfzteile24/postgresql-proxy.git 13 | cd postgresql-proxy 14 | ``` 15 | 3. Run [setup.sh](setup.sh) 16 | ``` 17 | source setup.sh 18 | ``` 19 | 20 | ## Configuring 21 | In the `config.yml` file you can define the following things 22 | ### Plugins 23 | A list of dynamically loaded modules that reside in the [plugins](plugins) directory. These plugins can be used in later configuration, to intercept queries, commands, or responses. View plugin documentation for example plugins for more details on how to do that. 24 | ### Settings 25 | General application settings. Currently the following settings are used 26 | * `log-level` - the log level for the general log. See [python logging](https://docs.python.org/3.6/library/logging.html) for more details about the logging functionality 27 | * `general-log` - the location for the general log. All general messages go in there. 28 | * `intercept-log` - the location for the intercept log. Intercepted messages and return values from various enabled plugins will be written there. This log can be quite verbose as it contains the full binary messages being circulated. 29 | 30 | Make sure to manage the logs yourself, as they accumulate and take up disk space. 31 | 32 | ### Instances 33 | `instances` is a list of instance definitions. Each instance has a listening port and redirects to a different postgresql instance. They have individual configurations for which message interceptors to use. It **requires**, for every instance, a `listen` directive and `redirect` directive. 34 | * `listen` directive, that must contain a `name` (for logging purposes), `host` and `port` for the listening socket. This is the host and port that external tools will connect to, as if it were the actual PostgreSql server. 35 | * `redirect` directive, that must contain the same components as `listen`, is the address of the actual PostgreSql server that this instance redirects to. 36 | * `intercept` - defines message interceptors 37 | * `commands` - interceptors for commands (messages from the client) 38 | * `queries` - interceptors for queries. 39 | * `connects` - interceptors for connection requests. *Not implemented yet* 40 | * `responses` - interceptors for responses (messages from PostgreSql server). *Not implemented yet* 41 | 42 | Each interceptor definition must have a `plugin`, which should also be present in the [plugins](#Plugins) configuration, and a `function`, that is found directly in that module, that will be called each time with the intercepted message as a byte string, and a context variable that is an instance of the `Proxy` class, that contains connection information and other useful stuff. 43 | 44 | ## Running in testing mode 45 | If you want to test it, do this. Otherwise scroll down for instructions on how to install it as a service 46 | ### Linux 47 | 1. Activate the virtual environment 48 | ``` 49 | source .venv/bin/activate 50 | ``` 51 | 2. Run it 52 | ``` 53 | python proxy.py 54 | ``` 55 | -------------------------------------------------------------------------------- /interceptors.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | class Interceptor: 4 | def __init__(self, interceptor_config, plugins, context): 5 | self.interceptor_config = interceptor_config 6 | self.plugins = plugins 7 | self.context = context 8 | 9 | def intercept(self, packet_type, data): 10 | return data 11 | 12 | def get_codec(self): 13 | if self.context is not None and 'connect_params' in self.context: 14 | if self.context['connect_params'] is not None and 'client_encoding' in self.context['connect_params']: 15 | return self.context['connect_params']['client_encoding'] 16 | return 'utf-8' 17 | 18 | 19 | class CommandInterceptor(Interceptor): 20 | def intercept(self, packet_type, data): 21 | if self.interceptor_config.queries is not None: 22 | ic_queries = self.interceptor_config.queries 23 | if packet_type == b'Q': 24 | # Query, ends with b'\x00' 25 | data = self.__intercept_query(data, ic_queries) 26 | elif packet_type == b'P': 27 | # Statement that needs parsing. 28 | # First byte of the body is some Statement flag. Ignore, don't lose 29 | # Next is the query, same as above, ends with an b'\x00' 30 | # Last 2 bytes are the number of parameters. Ignore, don't lose 31 | statement = data[0:1] 32 | query = self.__intercept_query(data[1:-2], ic_queries) 33 | params = data[-2:] 34 | data = statement + query + params 35 | elif packet_type == b'': 36 | self.__intercept_context_data(data) 37 | return data 38 | 39 | 40 | def __intercept_context_data(self, data): 41 | # first 4 bytes and last zero byte are not interesting 42 | relevant_data = data[4:-1] 43 | # Each entry is terminated by b'\x00' 44 | entries = relevant_data.split(b'\x00')[:-1] 45 | entries = dict(zip(entries[0::2], entries[1::2])) 46 | self.context['connect_params'] = {} 47 | # Try to set codec, then transcode the dict 48 | if b'client_encoding' in entries: 49 | self.context['connect_params']['client_encoding'] = entries[b'client_encoding'].decode('ascii') 50 | codec = self.get_codec() 51 | for k, v in entries.items(): 52 | self.context['connect_params'][k.decode(codec)] = v.decode(codec) 53 | 54 | 55 | def __intercept_query(self, query, interceptors): 56 | logging.getLogger('intercept').debug("intercepting query\n%s", query) 57 | # Remove zero byte at the end 58 | query = query[:-1].decode('utf-8') 59 | for interceptor in interceptors: 60 | if interceptor.plugin in self.plugins: 61 | plugin = self.plugins[interceptor.plugin] 62 | if hasattr(plugin, interceptor.function): 63 | func = getattr(plugin, interceptor.function) 64 | query = func(query, self.context) 65 | logging.getLogger('intercept').debug( 66 | "modifying query using interceptor %s.%s\n%s", 67 | interceptor.plugin, 68 | interceptor.function, 69 | query) 70 | else: 71 | raise Exception("Can't find function {} in plugin {}".format( 72 | interceptor.function, 73 | interceptor.plugin 74 | )) 75 | else: 76 | raise Exception("Plugin {} not loaded".format(interceptor.plugin)) 77 | # Append the zero byte at the end 78 | return query.encode('utf-8') + b'\x00' 79 | 80 | 81 | class ResponseInterceptor(Interceptor): 82 | pass 83 | -------------------------------------------------------------------------------- /plugins/tableau_hll/__init__.py: -------------------------------------------------------------------------------- 1 | import psycopg2 2 | import re 3 | 4 | # The field to replace 5 | field_pattern = re.compile('(?<=[^\w])count\(distinct (?:cast\()?("[^"]+")\.("[^"]+")(?: as text\))?\)', re.IGNORECASE) 6 | # Table name 7 | table_pattern = re.compile('from ([^\(\)]+?)\s*\)? (?:AS )?("[^"]+")', re.IGNORECASE | re.DOTALL) 8 | 9 | def rewrite_query(query, context): 10 | original_table = '' 11 | table_alias = '' 12 | 13 | # cache only works on current query. Mainly because there's no way to tell if the table has been modified between 14 | # 2 different requests. 15 | column_cache = {} 16 | 17 | # Replaces 18 | # COUNT(DISTINCT CAST("Some Table Alias"."Some Field" AS TEXT)) 19 | # With 20 | # hll_cardinality(hll_union_agg("Some Table Alias"."Some Field") :: BIGINT 21 | # Only for "Some Table Alias"."Some Field" that are hll 22 | def replace(match): 23 | field_table_alias = match.group(1) 24 | if field_table_alias.strip('" ') == table_alias.strip('" '): 25 | hll_table = original_table 26 | hll_column_candidate = match.group(2).strip() 27 | 28 | # need to know which columns are hll 29 | if not hll_table.lower() in column_cache: 30 | db_conn_info = context['instance_config'].redirect 31 | conn = None 32 | try: 33 | conn = psycopg2.connect( 34 | "host='{}' port={} dbname='{}' user='{}'".format( 35 | # Get host info from proxy config 36 | db_conn_info.host, 37 | db_conn_info.port, 38 | # Get auth information from the proxied request 39 | context['connect_params']['database'], 40 | context['connect_params']['user'] 41 | ) 42 | ) 43 | 44 | hll_type_code = None 45 | cur = conn.cursor() 46 | try: 47 | cur.execute("SELECT oid FROM pg_type WHERE typname='hll';") 48 | hll_type_code, = cur.fetchone() 49 | except: 50 | pass 51 | finally: 52 | cur.close() 53 | 54 | # If there's no hll in the database, no need to replace anything 55 | if hll_type_code is None: 56 | return match.group(0) 57 | 58 | # Create a set of all hll columns, and cache it for any other replacement for the same query 59 | cur = conn.cursor() 60 | try: 61 | cur.execute("SELECT * FROM {} LIMIT 0".format(hll_table)) 62 | hll_columns = set() 63 | for desc in cur.description: 64 | if desc.type_code == hll_type_code: 65 | hll_columns.add(desc.name.lower()) 66 | 67 | column_cache[hll_table.lower()] = hll_columns 68 | except: 69 | pass 70 | finally: 71 | cur.close() 72 | except: 73 | raise 74 | finally: 75 | if conn is not None: 76 | conn.close() 77 | 78 | # Replace 79 | if hll_column_candidate.strip('"').lower() in column_cache[hll_table.lower()]: 80 | return ' hll_cardinality(hll_union_agg({}.{})) :: BIGINT '.format(match.group(1), match.group(2)) 81 | 82 | # Don't replace 83 | return match.group(0) 84 | 85 | 86 | # Matches this string. The 2 groups are `schema.table` and `"alias"` 87 | # FROM schema.table) "alias" 88 | table_result = table_pattern.search(query) 89 | if table_result is not None: 90 | original_table = table_result.group(1).strip() 91 | table_alias = table_result.group(2).strip() 92 | 93 | # Replaces count(distinct ...) with hll_cardinality(hll_union_agg(...)) :: BIGINT 94 | # where and how it is appropriate 95 | # the inner function `replace` uses the variables `original_table` and `table_alias` from this scope (smelly code) 96 | return field_pattern.sub(replace, query) 97 | -------------------------------------------------------------------------------- /config_schema.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | ''' This class is used to validate the config 4 | ''' 5 | class Schema: 6 | def __init__(self): 7 | pass 8 | 9 | def _validate(self): 10 | pass 11 | 12 | def __hyphen_to_underscore(self, k): 13 | return k.replace('-', '_') 14 | 15 | def _populate(self, data, definition): 16 | try: 17 | for (k, v) in data.items(): 18 | k = self.__hyphen_to_underscore(k) 19 | if k in definition: 20 | vtype = definition[k] 21 | if isinstance(vtype, list): 22 | assert isinstance(v, list), "{} should be a list".format(k) 23 | newlist = [] 24 | for item in v: 25 | newlist.append(vtype[0](item)) 26 | setattr(self, k, newlist) 27 | else: 28 | setattr(self, k, vtype(v)) 29 | self._validate() 30 | except AssertionError as err: 31 | logging.error("Invalid config: %s", str(err)) 32 | raise Exception("Invalid config") 33 | 34 | def _assert_non_empty(self, *attrs): 35 | for attr in attrs: 36 | assert len(getattr(self, attr)) > 0, "{}.{} must not be empty".format(type(self).__name__, attr) 37 | 38 | def _assert_non_null(self, *attrs): 39 | for attr in attrs: 40 | assert getattr(self, attr) is not None, "{}.{} must not be None".format(type(self).__name__, attr) 41 | 42 | 43 | class InterceptQuerySettings(Schema): 44 | def __init__(self, data): 45 | self.plugin = None 46 | self.function = None 47 | 48 | self._populate(data, { 49 | 'plugin': str, 50 | 'function': str 51 | }) 52 | 53 | def _validate(self): 54 | self._assert_non_null('plugin', 'function') 55 | self._assert_non_empty('plugin', 'function') 56 | 57 | 58 | class InterceptCommandSettings(Schema): 59 | def __init__(self, data): 60 | self.queries = [] 61 | self.connects = None 62 | 63 | self._populate(data, { 64 | 'queries': [InterceptQuerySettings], 65 | 'connects': str 66 | }) 67 | 68 | 69 | class InterceptSettings(Schema): 70 | def __init__(self, data): 71 | self.commands = None 72 | self.responses = None 73 | 74 | self._populate(data, { 75 | 'commands': InterceptCommandSettings, 76 | 'responses': str 77 | }) 78 | 79 | 80 | class Connection(Schema): 81 | def __init__(self, data): 82 | self.name = None 83 | self.host = None 84 | self.port = None 85 | 86 | self._populate(data, { 87 | 'name': str, 88 | 'host': str, 89 | 'port': int 90 | }) 91 | 92 | def _validate(self): 93 | self._assert_non_null('name', 'host', 'port') 94 | self._assert_non_empty('name') 95 | 96 | 97 | class InstanceSettings(Schema): 98 | def __init__(self, data): 99 | self.listen = None 100 | self.redirect = None 101 | self.intercept = None 102 | 103 | self._populate(data, { 104 | 'listen': Connection, 105 | 'redirect': Connection, 106 | 'intercept': InterceptSettings 107 | }) 108 | 109 | 110 | def _validate(self): 111 | self._assert_non_null('listen', 'redirect') 112 | 113 | 114 | class Settings(Schema): 115 | def __init__(self, data): 116 | self.log_level = None 117 | self.intercept_log = None 118 | self.general_log = None 119 | 120 | self._populate(data, { 121 | 'log_level': str, 122 | 'intercept_log': str, 123 | 'general_log': str 124 | }) 125 | 126 | def _validate(self): 127 | self._assert_non_null('log_level', 'intercept_log', 'general_log') 128 | self._assert_non_empty('log_level', 'intercept_log', 'general_log') 129 | 130 | 131 | class Config(Schema): 132 | def __init__(self, data): 133 | self.plugins = [] 134 | self.settings = None 135 | self.instances = [] 136 | 137 | self._populate(data, { 138 | 'plugins' : [str], 139 | 'settings' : Settings, 140 | 'instances' : [InstanceSettings] 141 | }) 142 | 143 | def _validate(self): 144 | self._assert_non_empty('instances') 145 | -------------------------------------------------------------------------------- /proxy.py: -------------------------------------------------------------------------------- 1 | '''For every configured instance, a Proxy object is created, that starts a listener. 2 | On connect, it initiates a parallel connection to postgresql and pairs them together. 3 | Using selectors, packets are received, intercepted and relayed to the other party. 4 | 5 | Protocol: 6 | The challenge is in identifying 3 types of packets: 7 | 1. With type and data. 8 | ex. 1 byte for type identifier, 4 bytes header for header and body length, body. Usually the body is ended with 9 | 0x00 byte as well, that is part of the length. 10 | The queries are part of this type of packets. A query is b'Q####SELECT whatever\\x00' 11 | 2. Without type. They contain just a 4 byte header with packet length. It just so happens that the first byte is 0x00 12 | just because nothing is that long. These contain information about connection. 13 | Usually it's the client sending connection information. Ex. 14 | b'x00x00x00O' - length 15 | b'x00x03x00x00' - unexplained 16 | then, separated by x00 is a list of key, value: user, database, application_name, client_encoding, etc 17 | then, ended by b'x00' 18 | 3. Without data. Just the type. Since it's b'N', it might be "null"? The whole packet is this single byte. 19 | Signals "ok" according to wireshark 20 | 21 | Handling: 22 | proxy.py - connections and sockets things 23 | connection.py - parsing and composing packets, launching interceptors 24 | interceptors.py - intercepting for modification 25 | ''' 26 | 27 | import config_schema as cfg 28 | import connection 29 | import logging 30 | import selectors 31 | import socket 32 | import types 33 | from interceptors import ResponseInterceptor, CommandInterceptor 34 | 35 | class Proxy: 36 | def __init__(self, instance_config, plugins): 37 | self.plugins = plugins 38 | self.num_clients = 0 39 | self.instance_config = instance_config 40 | self.connections = [] 41 | self.selector = selectors.DefaultSelector() 42 | 43 | 44 | def __create_pg_connection(self, address, context): 45 | redirect_config = self.instance_config.redirect 46 | 47 | pg_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 48 | pg_sock.connect((redirect_config.host, redirect_config.port)) 49 | pg_sock.setblocking(False) 50 | 51 | events = selectors.EVENT_READ | selectors.EVENT_WRITE 52 | 53 | pg_conn = connection.Connection(pg_sock, 54 | name = redirect_config.name + '_' + str(self.num_clients), 55 | address = address, 56 | events = events, 57 | context = context) 58 | 59 | logging.info("initiated client connection to %s:%s called %s", 60 | redirect_config.host, redirect_config.port, redirect_config.name) 61 | return pg_conn 62 | 63 | 64 | def __register_conn(self, conn): 65 | self.selector.register(conn.sock, conn.events, data=conn) 66 | 67 | 68 | def __unregister_conn(self, conn): 69 | self.selector.unregister(conn.sock) 70 | 71 | 72 | def accept_wrapper(self, sock): 73 | clientsocket, address = sock.accept() # Should be ready to 74 | clientsocket.setblocking(False) 75 | self.num_clients+=1 76 | sock_name = '{}_{}'.format(self.instance_config.listen.name, self.num_clients) 77 | logging.info("connection from %s, connection initiated %s", address, sock_name) 78 | 79 | events = selectors.EVENT_READ | selectors.EVENT_WRITE 80 | 81 | # Context dictionary, for sharing state data, connection details, which might be useful for interceptors 82 | context = { 83 | 'instance_config': self.instance_config 84 | } 85 | 86 | conn = connection.Connection(clientsocket, 87 | name = sock_name, 88 | address = address, 89 | events = events, 90 | context = context) 91 | 92 | pg_conn = self.__create_pg_connection(address, context) 93 | 94 | if self.instance_config.intercept is not None and self.instance_config.intercept.responses is not None: 95 | pg_conn.interceptor = ResponseInterceptor(self.instance_config.intercept.responses, self.plugins, context) 96 | pg_conn.redirect_conn = conn 97 | 98 | if self.instance_config.intercept is not None and self.instance_config.intercept.commands is not None: 99 | conn.interceptor = CommandInterceptor(self.instance_config.intercept.commands, self.plugins, context) 100 | conn.redirect_conn = pg_conn 101 | 102 | self.__register_conn(conn) 103 | self.__register_conn(pg_conn) 104 | 105 | 106 | def service_connection(self, key, mask): 107 | sock = key.fileobj 108 | conn = key.data 109 | if mask & selectors.EVENT_READ: 110 | logging.debug('%s can receive', conn.name) 111 | recv_data = sock.recv(4096) # Should be ready to read 112 | if recv_data: 113 | logging.debug('%s received data:\n%s', conn.name, recv_data) 114 | conn.received(recv_data) 115 | else: 116 | logging.info('%s connection closing %s', conn.name, conn.address) 117 | sock.close() 118 | self.__unregister_conn(conn) 119 | if mask & selectors.EVENT_WRITE: 120 | if conn.out_bytes: 121 | logging.debug('sending to %s:\n%s', conn.name, conn.out_bytes) 122 | sent = sock.send(conn.out_bytes) # Should be ready to write 123 | conn.sent(sent) 124 | 125 | 126 | 127 | def listen(self, max_connections = 8): 128 | '''Listen server socket. On connect launch a new thread with the client connection as an argument 129 | ''' 130 | lconf = self.instance_config.listen 131 | ip, port = (lconf.host, lconf.port) 132 | try: 133 | logging.info("listening to %s:%s", ip, port) 134 | self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 135 | self.sock.bind((ip, port)) 136 | self.sock.listen(max_connections) 137 | self.sock.setblocking(False) 138 | self.selector.register(self.sock, selectors.EVENT_READ, data=None) 139 | while True: 140 | events = self.selector.select(timeout=None) 141 | hit = False 142 | for key, mask in events: 143 | hit = True 144 | if key.data is None: 145 | self.accept_wrapper(key.fileobj) 146 | else: 147 | self.service_connection(key, mask) 148 | except OSError as ex: 149 | logging.critical("Can't establish listener", exc_info=ex) 150 | finally: 151 | self.sock.close() 152 | self.sock = None 153 | logging.info("closed socket") 154 | 155 | 156 | if(__name__=='__main__'): 157 | import importlib 158 | import os 159 | from yaml import load, Loader 160 | 161 | path = os.path.dirname(os.path.realpath(__file__)) 162 | config = None 163 | try: 164 | with open(path + '/' + 'config.yml', 'r') as fp: 165 | config = cfg.Config(load(stream=fp, Loader=Loader)) 166 | except Exception: 167 | logging.critical("Could not read config. Aborting.") 168 | exit(1) 169 | 170 | logging.basicConfig( 171 | filename=config.settings.general_log, 172 | level=getattr(logging, config.settings.log_level.upper()), 173 | format='%(asctime)s : %(levelname)s : %(message)s' 174 | ) 175 | 176 | qlog = logging.getLogger('intercept') 177 | qformat = logging.Formatter('%(asctime)s : %(message)s') 178 | qhandler = logging.FileHandler(config.settings.intercept_log, mode = 'w') 179 | qhandler.setFormatter(qformat) 180 | qlog.addHandler(qhandler) 181 | qlog.setLevel(logging.DEBUG) 182 | 183 | print('general log, level {}: {}'.format(config.settings.log_level, config.settings.general_log)) 184 | print('intercept log: {}'.format(config.settings.intercept_log)) 185 | print('further messages directed to log') 186 | 187 | plugins = {} 188 | for plugin in config.plugins: 189 | logging.info("Loading module %s", plugin) 190 | module = importlib.import_module('plugins.' + plugin) 191 | plugins[plugin] = module 192 | 193 | for instance in config.instances: 194 | logging.info("Starting proxy instance") 195 | proxy = Proxy(instance, plugins) 196 | proxy.listen() 197 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------