-
Notifications
You must be signed in to change notification settings - Fork 82
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sanitize the string to avoid a connection string injection (#532)
We should avoid possible connection injection. To do so, we have to sanitize and validate inputs for the database
- Loading branch information
Showing
8 changed files
with
120 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,59 @@ | ||
import os | ||
import re | ||
|
||
_SANITIZE_WORD_REGEX = r"[^\w]" # A-Za-z0-9_ | ||
_SANITIZE_HOST_REGEX = r"[^\w.-]" | ||
_SANITIZE_PWD_REGEX = r"[\"\s%+~`#$&*()|\[\]{}:;<>?!'/]+" | ||
_AURORA_HOST_SUFFIX = "rds.amazonaws.com" | ||
_POSTGRES_MAX_LEN = 63 | ||
_MAX_HOST_LENGTH = 253 | ||
|
||
_envname = os.getenv('envname', 'local') | ||
|
||
|
||
class DbConfig: | ||
def __init__(self, **kwargs): | ||
self.params = kwargs | ||
self.url = f"postgresql+pygresql://{self.params['user']}:{self.params['pwd']}@{self.params['host']}/{self.params['db']}" | ||
def __init__(self, user: str, pwd: str, host: str, db: str, schema: str): | ||
for param in (user, db, schema): | ||
if len(param) > _POSTGRES_MAX_LEN: | ||
raise ValueError( | ||
f"PostgreSQL doesn't allow values more than 63 characters" | ||
f" parameters {user}, {db}, {schema}" | ||
) | ||
|
||
if len(host) > _MAX_HOST_LENGTH: | ||
raise ValueError(f"Hostname is too long: {host}") | ||
|
||
if _envname not in ['local', 'pytest', 'dkrcompose'] and not host.lower().endswith(_AURORA_HOST_SUFFIX): | ||
raise ValueError(f"Unknown host {host} for the rds") | ||
|
||
self.user = self._sanitize_and_compare(_SANITIZE_WORD_REGEX, user, "username") | ||
self.host = self._sanitize_and_compare(_SANITIZE_HOST_REGEX, host, "host") | ||
self.db = self._sanitize_and_compare(_SANITIZE_WORD_REGEX, db, "database name") | ||
self.schema = self._sanitize_and_compare(_SANITIZE_WORD_REGEX, schema, "schema") | ||
pwd = self._sanitize_and_compare(_SANITIZE_PWD_REGEX, pwd, "password") | ||
self.url = f"postgresql+pygresql://{self.user}:{pwd}@{self.host}/{self.db}" | ||
|
||
def __str__(self): | ||
lines = [] | ||
lines.append(' DbConfig >') | ||
lines = [' DbConfig >'] | ||
hr = ' '.join(['+', ''.ljust(10, '-'), '+', ''.ljust(65, '-'), '+']) | ||
lines.append(hr) | ||
header = ' '.join(['+', 'Db Param'.ljust(10), ' ', 'Value'.ljust(65), '+']) | ||
lines.append(header) | ||
hr = ' '.join(['+', ''.ljust(10, '-'), '+', ''.ljust(65, '-'), '+']) | ||
lines.append(hr) | ||
for k in self.params: | ||
v = self.params[k] | ||
if k == 'pwd': | ||
v = '*' * len(self.params[k]) | ||
lines.append(' '.join(['|', k.ljust(10), '|', v.ljust(65), '|'])) | ||
lines.append(' '.join(['|', "host".ljust(10), '|', self.host.ljust(65), '|'])) | ||
lines.append(' '.join(['|', "db".ljust(10), '|', self.db.ljust(65), '|'])) | ||
lines.append(' '.join(['|', "user".ljust(10), '|', self.user.ljust(65), '|'])) | ||
lines.append(' '.join(['|', "pwd".ljust(10), '|', "*****".ljust(65), '|'])) | ||
|
||
hr = ' '.join(['+', ''.ljust(10, '-'), '+', ''.ljust(65, '-'), '+']) | ||
lines.append(hr) | ||
return '\n'.join(lines) | ||
|
||
@staticmethod | ||
def _sanitize_and_compare(regex, string: str, param_name) -> str: | ||
sanitized = re.sub(regex, "", string) | ||
if sanitized != string: | ||
raise ValueError(f"Can't create a database connection. The {param_name} parameter has invalid symbols." | ||
f" The sanitized string length: {len(sanitized)} < original : {len(string)}") | ||
return sanitized |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import pytest | ||
|
||
from dataall.db import DbConfig | ||
|
||
|
||
def test_incorrect_database(): | ||
with pytest.raises(ValueError): | ||
DbConfig( | ||
user='dataall', | ||
pwd='123456789', | ||
host="dataall.eu-west-1.rds.amazonaws.com", | ||
db='dataall\'; DROP TABLE users;', | ||
schema='dev' | ||
) | ||
|
||
|
||
def test_incorrect_user(): | ||
with pytest.raises(ValueError): | ||
DbConfig( | ||
user='dataall2;^&*end', | ||
pwd='qwsufn3i20d-_s3qaSW3d2', | ||
host="dataall.eu-west-1.rds.amazonaws.com", | ||
db='dataall', | ||
schema='dev' | ||
) | ||
|
||
|
||
def test_incorrect_pwd(): | ||
with pytest.raises(ValueError): | ||
DbConfig( | ||
user='dataall', | ||
pwd='qazxsVFRTGBdfrew-332_c2@dataall.eu-west-1.rds.amazonaws.com/dataall\'; drop table dataset; # ', | ||
host="dataall.eu-west-1.rds.amazonaws.com", | ||
db='dataall', | ||
schema='dev' | ||
) | ||
|
||
|
||
def test_incorrect_host(): | ||
with pytest.raises(ValueError): | ||
DbConfig( | ||
user='dataall', | ||
pwd='q68rjdmwiosoxahGDYJWIdi-9eu93_9dJJ_', | ||
host="dataall.eu-west-1$%#&@*#)$#.rds.amazonaws.com", | ||
db='dataall', | ||
schema='dev' | ||
) | ||
|
||
|
||
def test_correct_config(): | ||
# no exception is raised | ||
DbConfig( | ||
user='dataall', | ||
pwd='q68rjdm_aX', | ||
host="dataall.eu-west-1.rds.amazonaws.com", | ||
db='dataall', | ||
schema='dev' | ||
) |